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 "MCTargetDesc/PPCPredicates.h"
00016 #include "PPCMachineFunctionInfo.h"
00017 #include "PPCPerfectShuffle.h"
00018 #include "PPCTargetMachine.h"
00019 #include "PPCTargetObjectFile.h"
00020 #include "llvm/ADT/STLExtras.h"
00021 #include "llvm/ADT/StringSwitch.h"
00022 #include "llvm/ADT/Triple.h"
00023 #include "llvm/CodeGen/CallingConvLower.h"
00024 #include "llvm/CodeGen/MachineFrameInfo.h"
00025 #include "llvm/CodeGen/MachineFunction.h"
00026 #include "llvm/CodeGen/MachineInstrBuilder.h"
00027 #include "llvm/CodeGen/MachineRegisterInfo.h"
00028 #include "llvm/CodeGen/SelectionDAG.h"
00029 #include "llvm/CodeGen/TargetLoweringObjectFileImpl.h"
00030 #include "llvm/IR/CallingConv.h"
00031 #include "llvm/IR/Constants.h"
00032 #include "llvm/IR/DerivedTypes.h"
00033 #include "llvm/IR/Function.h"
00034 #include "llvm/IR/Intrinsics.h"
00035 #include "llvm/Support/CommandLine.h"
00036 #include "llvm/Support/ErrorHandling.h"
00037 #include "llvm/Support/MathExtras.h"
00038 #include "llvm/Support/raw_ostream.h"
00039 #include "llvm/Target/TargetOptions.h"
00040 using namespace llvm;
00041 
00042 static cl::opt<bool> DisablePPCPreinc("disable-ppc-preinc",
00043 cl::desc("disable preincrement load/store generation on PPC"), cl::Hidden);
00044 
00045 static cl::opt<bool> DisableILPPref("disable-ppc-ilp-pref",
00046 cl::desc("disable setting the node scheduling preference to ILP on PPC"), cl::Hidden);
00047 
00048 static cl::opt<bool> DisablePPCUnaligned("disable-ppc-unaligned",
00049 cl::desc("disable unaligned load/store generation on PPC"), cl::Hidden);
00050 
00051 // FIXME: Remove this once the bug has been fixed!
00052 extern cl::opt<bool> ANDIGlueBug;
00053 
00054 static TargetLoweringObjectFile *createTLOF(const Triple &TT) {
00055   // If it isn't a Mach-O file then it's going to be a linux ELF
00056   // object file.
00057   if (TT.isOSDarwin())
00058     return new TargetLoweringObjectFileMachO();
00059 
00060   return new PPC64LinuxTargetObjectFile();
00061 }
00062 
00063 PPCTargetLowering::PPCTargetLowering(PPCTargetMachine &TM)
00064     : TargetLowering(TM, createTLOF(Triple(TM.getTargetTriple()))),
00065       Subtarget(*TM.getSubtargetImpl()) {
00066   setPow2DivIsCheap();
00067 
00068   // Use _setjmp/_longjmp instead of setjmp/longjmp.
00069   setUseUnderscoreSetJmp(true);
00070   setUseUnderscoreLongJmp(true);
00071 
00072   // On PPC32/64, arguments smaller than 4/8 bytes are extended, so all
00073   // arguments are at least 4/8 bytes aligned.
00074   bool isPPC64 = Subtarget.isPPC64();
00075   setMinStackArgumentAlignment(isPPC64 ? 8:4);
00076 
00077   // Set up the register classes.
00078   addRegisterClass(MVT::i32, &PPC::GPRCRegClass);
00079   addRegisterClass(MVT::f32, &PPC::F4RCRegClass);
00080   addRegisterClass(MVT::f64, &PPC::F8RCRegClass);
00081 
00082   // PowerPC has an i16 but no i8 (or i1) SEXTLOAD
00083   setLoadExtAction(ISD::SEXTLOAD, MVT::i1, Promote);
00084   setLoadExtAction(ISD::SEXTLOAD, MVT::i8, Expand);
00085 
00086   setTruncStoreAction(MVT::f64, MVT::f32, Expand);
00087 
00088   // PowerPC has pre-inc load and store's.
00089   setIndexedLoadAction(ISD::PRE_INC, MVT::i1, Legal);
00090   setIndexedLoadAction(ISD::PRE_INC, MVT::i8, Legal);
00091   setIndexedLoadAction(ISD::PRE_INC, MVT::i16, Legal);
00092   setIndexedLoadAction(ISD::PRE_INC, MVT::i32, Legal);
00093   setIndexedLoadAction(ISD::PRE_INC, MVT::i64, Legal);
00094   setIndexedStoreAction(ISD::PRE_INC, MVT::i1, Legal);
00095   setIndexedStoreAction(ISD::PRE_INC, MVT::i8, Legal);
00096   setIndexedStoreAction(ISD::PRE_INC, MVT::i16, Legal);
00097   setIndexedStoreAction(ISD::PRE_INC, MVT::i32, Legal);
00098   setIndexedStoreAction(ISD::PRE_INC, MVT::i64, Legal);
00099 
00100   if (Subtarget.useCRBits()) {
00101     setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1, Expand);
00102 
00103     if (isPPC64 || Subtarget.hasFPCVT()) {
00104       setOperationAction(ISD::SINT_TO_FP, MVT::i1, Promote);
00105       AddPromotedToType (ISD::SINT_TO_FP, MVT::i1,
00106                          isPPC64 ? MVT::i64 : MVT::i32);
00107       setOperationAction(ISD::UINT_TO_FP, MVT::i1, Promote);
00108       AddPromotedToType (ISD::UINT_TO_FP, MVT::i1, 
00109                          isPPC64 ? MVT::i64 : MVT::i32);
00110     } else {
00111       setOperationAction(ISD::SINT_TO_FP, MVT::i1, Custom);
00112       setOperationAction(ISD::UINT_TO_FP, MVT::i1, Custom);
00113     }
00114 
00115     // PowerPC does not support direct load / store of condition registers
00116     setOperationAction(ISD::LOAD, MVT::i1, Custom);
00117     setOperationAction(ISD::STORE, MVT::i1, Custom);
00118 
00119     // FIXME: Remove this once the ANDI glue bug is fixed:
00120     if (ANDIGlueBug)
00121       setOperationAction(ISD::TRUNCATE, MVT::i1, Custom);
00122 
00123     setLoadExtAction(ISD::SEXTLOAD, MVT::i1, Promote);
00124     setLoadExtAction(ISD::ZEXTLOAD, MVT::i1, Promote);
00125     setTruncStoreAction(MVT::i64, MVT::i1, Expand);
00126     setTruncStoreAction(MVT::i32, MVT::i1, Expand);
00127     setTruncStoreAction(MVT::i16, MVT::i1, Expand);
00128     setTruncStoreAction(MVT::i8, MVT::i1, Expand);
00129 
00130     addRegisterClass(MVT::i1, &PPC::CRBITRCRegClass);
00131   }
00132 
00133   // This is used in the ppcf128->int sequence.  Note it has different semantics
00134   // from FP_ROUND:  that rounds to nearest, this rounds to zero.
00135   setOperationAction(ISD::FP_ROUND_INREG, MVT::ppcf128, Custom);
00136 
00137   // We do not currently implement these libm ops for PowerPC.
00138   setOperationAction(ISD::FFLOOR, MVT::ppcf128, Expand);
00139   setOperationAction(ISD::FCEIL,  MVT::ppcf128, Expand);
00140   setOperationAction(ISD::FTRUNC, MVT::ppcf128, Expand);
00141   setOperationAction(ISD::FRINT,  MVT::ppcf128, Expand);
00142   setOperationAction(ISD::FNEARBYINT, MVT::ppcf128, Expand);
00143   setOperationAction(ISD::FREM, MVT::ppcf128, Expand);
00144 
00145   // PowerPC has no SREM/UREM instructions
00146   setOperationAction(ISD::SREM, MVT::i32, Expand);
00147   setOperationAction(ISD::UREM, MVT::i32, Expand);
00148   setOperationAction(ISD::SREM, MVT::i64, Expand);
00149   setOperationAction(ISD::UREM, MVT::i64, Expand);
00150 
00151   // Don't use SMUL_LOHI/UMUL_LOHI or SDIVREM/UDIVREM to lower SREM/UREM.
00152   setOperationAction(ISD::UMUL_LOHI, MVT::i32, Expand);
00153   setOperationAction(ISD::SMUL_LOHI, MVT::i32, Expand);
00154   setOperationAction(ISD::UMUL_LOHI, MVT::i64, Expand);
00155   setOperationAction(ISD::SMUL_LOHI, MVT::i64, Expand);
00156   setOperationAction(ISD::UDIVREM, MVT::i32, Expand);
00157   setOperationAction(ISD::SDIVREM, MVT::i32, Expand);
00158   setOperationAction(ISD::UDIVREM, MVT::i64, Expand);
00159   setOperationAction(ISD::SDIVREM, MVT::i64, Expand);
00160 
00161   // We don't support sin/cos/sqrt/fmod/pow
00162   setOperationAction(ISD::FSIN , MVT::f64, Expand);
00163   setOperationAction(ISD::FCOS , MVT::f64, Expand);
00164   setOperationAction(ISD::FSINCOS, MVT::f64, Expand);
00165   setOperationAction(ISD::FREM , MVT::f64, Expand);
00166   setOperationAction(ISD::FPOW , MVT::f64, Expand);
00167   setOperationAction(ISD::FMA  , MVT::f64, Legal);
00168   setOperationAction(ISD::FSIN , MVT::f32, Expand);
00169   setOperationAction(ISD::FCOS , MVT::f32, Expand);
00170   setOperationAction(ISD::FSINCOS, MVT::f32, Expand);
00171   setOperationAction(ISD::FREM , MVT::f32, Expand);
00172   setOperationAction(ISD::FPOW , MVT::f32, Expand);
00173   setOperationAction(ISD::FMA  , MVT::f32, Legal);
00174 
00175   setOperationAction(ISD::FLT_ROUNDS_, MVT::i32, Custom);
00176 
00177   // If we're enabling GP optimizations, use hardware square root
00178   if (!Subtarget.hasFSQRT() &&
00179       !(TM.Options.UnsafeFPMath &&
00180         Subtarget.hasFRSQRTE() && Subtarget.hasFRE()))
00181     setOperationAction(ISD::FSQRT, MVT::f64, Expand);
00182 
00183   if (!Subtarget.hasFSQRT() &&
00184       !(TM.Options.UnsafeFPMath &&
00185         Subtarget.hasFRSQRTES() && Subtarget.hasFRES()))
00186     setOperationAction(ISD::FSQRT, MVT::f32, Expand);
00187 
00188   if (Subtarget.hasFCPSGN()) {
00189     setOperationAction(ISD::FCOPYSIGN, MVT::f64, Legal);
00190     setOperationAction(ISD::FCOPYSIGN, MVT::f32, Legal);
00191   } else {
00192     setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
00193     setOperationAction(ISD::FCOPYSIGN, MVT::f32, Expand);
00194   }
00195 
00196   if (Subtarget.hasFPRND()) {
00197     setOperationAction(ISD::FFLOOR, MVT::f64, Legal);
00198     setOperationAction(ISD::FCEIL,  MVT::f64, Legal);
00199     setOperationAction(ISD::FTRUNC, MVT::f64, Legal);
00200     setOperationAction(ISD::FROUND, MVT::f64, Legal);
00201 
00202     setOperationAction(ISD::FFLOOR, MVT::f32, Legal);
00203     setOperationAction(ISD::FCEIL,  MVT::f32, Legal);
00204     setOperationAction(ISD::FTRUNC, MVT::f32, Legal);
00205     setOperationAction(ISD::FROUND, MVT::f32, Legal);
00206   }
00207 
00208   // PowerPC does not have BSWAP, CTPOP or CTTZ
00209   setOperationAction(ISD::BSWAP, MVT::i32  , Expand);
00210   setOperationAction(ISD::CTTZ , MVT::i32  , Expand);
00211   setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i32, Expand);
00212   setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i32, Expand);
00213   setOperationAction(ISD::BSWAP, MVT::i64  , Expand);
00214   setOperationAction(ISD::CTTZ , MVT::i64  , Expand);
00215   setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i64, Expand);
00216   setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i64, Expand);
00217 
00218   if (Subtarget.hasPOPCNTD()) {
00219     setOperationAction(ISD::CTPOP, MVT::i32  , Legal);
00220     setOperationAction(ISD::CTPOP, MVT::i64  , Legal);
00221   } else {
00222     setOperationAction(ISD::CTPOP, MVT::i32  , Expand);
00223     setOperationAction(ISD::CTPOP, MVT::i64  , Expand);
00224   }
00225 
00226   // PowerPC does not have ROTR
00227   setOperationAction(ISD::ROTR, MVT::i32   , Expand);
00228   setOperationAction(ISD::ROTR, MVT::i64   , Expand);
00229 
00230   if (!Subtarget.useCRBits()) {
00231     // PowerPC does not have Select
00232     setOperationAction(ISD::SELECT, MVT::i32, Expand);
00233     setOperationAction(ISD::SELECT, MVT::i64, Expand);
00234     setOperationAction(ISD::SELECT, MVT::f32, Expand);
00235     setOperationAction(ISD::SELECT, MVT::f64, Expand);
00236   }
00237 
00238   // PowerPC wants to turn select_cc of FP into fsel when possible.
00239   setOperationAction(ISD::SELECT_CC, MVT::f32, Custom);
00240   setOperationAction(ISD::SELECT_CC, MVT::f64, Custom);
00241 
00242   // PowerPC wants to optimize integer setcc a bit
00243   if (!Subtarget.useCRBits())
00244     setOperationAction(ISD::SETCC, MVT::i32, Custom);
00245 
00246   // PowerPC does not have BRCOND which requires SetCC
00247   if (!Subtarget.useCRBits())
00248     setOperationAction(ISD::BRCOND, MVT::Other, Expand);
00249 
00250   setOperationAction(ISD::BR_JT,  MVT::Other, Expand);
00251 
00252   // PowerPC turns FP_TO_SINT into FCTIWZ and some load/stores.
00253   setOperationAction(ISD::FP_TO_SINT, MVT::i32, Custom);
00254 
00255   // PowerPC does not have [U|S]INT_TO_FP
00256   setOperationAction(ISD::SINT_TO_FP, MVT::i32, Expand);
00257   setOperationAction(ISD::UINT_TO_FP, MVT::i32, Expand);
00258 
00259   setOperationAction(ISD::BITCAST, MVT::f32, Expand);
00260   setOperationAction(ISD::BITCAST, MVT::i32, Expand);
00261   setOperationAction(ISD::BITCAST, MVT::i64, Expand);
00262   setOperationAction(ISD::BITCAST, MVT::f64, Expand);
00263 
00264   // We cannot sextinreg(i1).  Expand to shifts.
00265   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1, Expand);
00266 
00267   // NOTE: EH_SJLJ_SETJMP/_LONGJMP supported here is NOT intended to support
00268   // SjLj exception handling but a light-weight setjmp/longjmp replacement to
00269   // support continuation, user-level threading, and etc.. As a result, no
00270   // other SjLj exception interfaces are implemented and please don't build
00271   // your own exception handling based on them.
00272   // LLVM/Clang supports zero-cost DWARF exception handling.
00273   setOperationAction(ISD::EH_SJLJ_SETJMP, MVT::i32, Custom);
00274   setOperationAction(ISD::EH_SJLJ_LONGJMP, MVT::Other, Custom);
00275 
00276   // We want to legalize GlobalAddress and ConstantPool nodes into the
00277   // appropriate instructions to materialize the address.
00278   setOperationAction(ISD::GlobalAddress, MVT::i32, Custom);
00279   setOperationAction(ISD::GlobalTLSAddress, MVT::i32, Custom);
00280   setOperationAction(ISD::BlockAddress,  MVT::i32, Custom);
00281   setOperationAction(ISD::ConstantPool,  MVT::i32, Custom);
00282   setOperationAction(ISD::JumpTable,     MVT::i32, Custom);
00283   setOperationAction(ISD::GlobalAddress, MVT::i64, Custom);
00284   setOperationAction(ISD::GlobalTLSAddress, MVT::i64, Custom);
00285   setOperationAction(ISD::BlockAddress,  MVT::i64, Custom);
00286   setOperationAction(ISD::ConstantPool,  MVT::i64, Custom);
00287   setOperationAction(ISD::JumpTable,     MVT::i64, Custom);
00288 
00289   // TRAP is legal.
00290   setOperationAction(ISD::TRAP, MVT::Other, Legal);
00291 
00292   // TRAMPOLINE is custom lowered.
00293   setOperationAction(ISD::INIT_TRAMPOLINE, MVT::Other, Custom);
00294   setOperationAction(ISD::ADJUST_TRAMPOLINE, MVT::Other, Custom);
00295 
00296   // VASTART needs to be custom lowered to use the VarArgsFrameIndex
00297   setOperationAction(ISD::VASTART           , MVT::Other, Custom);
00298 
00299   if (Subtarget.isSVR4ABI()) {
00300     if (isPPC64) {
00301       // VAARG always uses double-word chunks, so promote anything smaller.
00302       setOperationAction(ISD::VAARG, MVT::i1, Promote);
00303       AddPromotedToType (ISD::VAARG, MVT::i1, MVT::i64);
00304       setOperationAction(ISD::VAARG, MVT::i8, Promote);
00305       AddPromotedToType (ISD::VAARG, MVT::i8, MVT::i64);
00306       setOperationAction(ISD::VAARG, MVT::i16, Promote);
00307       AddPromotedToType (ISD::VAARG, MVT::i16, MVT::i64);
00308       setOperationAction(ISD::VAARG, MVT::i32, Promote);
00309       AddPromotedToType (ISD::VAARG, MVT::i32, MVT::i64);
00310       setOperationAction(ISD::VAARG, MVT::Other, Expand);
00311     } else {
00312       // VAARG is custom lowered with the 32-bit SVR4 ABI.
00313       setOperationAction(ISD::VAARG, MVT::Other, Custom);
00314       setOperationAction(ISD::VAARG, MVT::i64, Custom);
00315     }
00316   } else
00317     setOperationAction(ISD::VAARG, MVT::Other, Expand);
00318 
00319   if (Subtarget.isSVR4ABI() && !isPPC64)
00320     // VACOPY is custom lowered with the 32-bit SVR4 ABI.
00321     setOperationAction(ISD::VACOPY            , MVT::Other, Custom);
00322   else
00323     setOperationAction(ISD::VACOPY            , MVT::Other, Expand);
00324 
00325   // Use the default implementation.
00326   setOperationAction(ISD::VAEND             , MVT::Other, Expand);
00327   setOperationAction(ISD::STACKSAVE         , MVT::Other, Expand);
00328   setOperationAction(ISD::STACKRESTORE      , MVT::Other, Custom);
00329   setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i32  , Custom);
00330   setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i64  , Custom);
00331 
00332   // We want to custom lower some of our intrinsics.
00333   setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
00334 
00335   // To handle counter-based loop conditions.
00336   setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::i1, Custom);
00337 
00338   // Comparisons that require checking two conditions.
00339   setCondCodeAction(ISD::SETULT, MVT::f32, Expand);
00340   setCondCodeAction(ISD::SETULT, MVT::f64, Expand);
00341   setCondCodeAction(ISD::SETUGT, MVT::f32, Expand);
00342   setCondCodeAction(ISD::SETUGT, MVT::f64, Expand);
00343   setCondCodeAction(ISD::SETUEQ, MVT::f32, Expand);
00344   setCondCodeAction(ISD::SETUEQ, MVT::f64, Expand);
00345   setCondCodeAction(ISD::SETOGE, MVT::f32, Expand);
00346   setCondCodeAction(ISD::SETOGE, MVT::f64, Expand);
00347   setCondCodeAction(ISD::SETOLE, MVT::f32, Expand);
00348   setCondCodeAction(ISD::SETOLE, MVT::f64, Expand);
00349   setCondCodeAction(ISD::SETONE, MVT::f32, Expand);
00350   setCondCodeAction(ISD::SETONE, MVT::f64, Expand);
00351 
00352   if (Subtarget.has64BitSupport()) {
00353     // They also have instructions for converting between i64 and fp.
00354     setOperationAction(ISD::FP_TO_SINT, MVT::i64, Custom);
00355     setOperationAction(ISD::FP_TO_UINT, MVT::i64, Expand);
00356     setOperationAction(ISD::SINT_TO_FP, MVT::i64, Custom);
00357     setOperationAction(ISD::UINT_TO_FP, MVT::i64, Expand);
00358     // This is just the low 32 bits of a (signed) fp->i64 conversion.
00359     // We cannot do this with Promote because i64 is not a legal type.
00360     setOperationAction(ISD::FP_TO_UINT, MVT::i32, Custom);
00361 
00362     if (Subtarget.hasLFIWAX() || Subtarget.isPPC64())
00363       setOperationAction(ISD::SINT_TO_FP, MVT::i32, Custom);
00364   } else {
00365     // PowerPC does not have FP_TO_UINT on 32-bit implementations.
00366     setOperationAction(ISD::FP_TO_UINT, MVT::i32, Expand);
00367   }
00368 
00369   // With the instructions enabled under FPCVT, we can do everything.
00370   if (Subtarget.hasFPCVT()) {
00371     if (Subtarget.has64BitSupport()) {
00372       setOperationAction(ISD::FP_TO_SINT, MVT::i64, Custom);
00373       setOperationAction(ISD::FP_TO_UINT, MVT::i64, Custom);
00374       setOperationAction(ISD::SINT_TO_FP, MVT::i64, Custom);
00375       setOperationAction(ISD::UINT_TO_FP, MVT::i64, Custom);
00376     }
00377 
00378     setOperationAction(ISD::FP_TO_SINT, MVT::i32, Custom);
00379     setOperationAction(ISD::FP_TO_UINT, MVT::i32, Custom);
00380     setOperationAction(ISD::SINT_TO_FP, MVT::i32, Custom);
00381     setOperationAction(ISD::UINT_TO_FP, MVT::i32, Custom);
00382   }
00383 
00384   if (Subtarget.use64BitRegs()) {
00385     // 64-bit PowerPC implementations can support i64 types directly
00386     addRegisterClass(MVT::i64, &PPC::G8RCRegClass);
00387     // BUILD_PAIR can't be handled natively, and should be expanded to shl/or
00388     setOperationAction(ISD::BUILD_PAIR, MVT::i64, Expand);
00389     // 64-bit PowerPC wants to expand i128 shifts itself.
00390     setOperationAction(ISD::SHL_PARTS, MVT::i64, Custom);
00391     setOperationAction(ISD::SRA_PARTS, MVT::i64, Custom);
00392     setOperationAction(ISD::SRL_PARTS, MVT::i64, Custom);
00393   } else {
00394     // 32-bit PowerPC wants to expand i64 shifts itself.
00395     setOperationAction(ISD::SHL_PARTS, MVT::i32, Custom);
00396     setOperationAction(ISD::SRA_PARTS, MVT::i32, Custom);
00397     setOperationAction(ISD::SRL_PARTS, MVT::i32, Custom);
00398   }
00399 
00400   if (Subtarget.hasAltivec()) {
00401     // First set operation action for all vector types to expand. Then we
00402     // will selectively turn on ones that can be effectively codegen'd.
00403     for (unsigned i = (unsigned)MVT::FIRST_VECTOR_VALUETYPE;
00404          i <= (unsigned)MVT::LAST_VECTOR_VALUETYPE; ++i) {
00405       MVT::SimpleValueType VT = (MVT::SimpleValueType)i;
00406 
00407       // add/sub are legal for all supported vector VT's.
00408       setOperationAction(ISD::ADD , VT, Legal);
00409       setOperationAction(ISD::SUB , VT, Legal);
00410 
00411       // We promote all shuffles to v16i8.
00412       setOperationAction(ISD::VECTOR_SHUFFLE, VT, Promote);
00413       AddPromotedToType (ISD::VECTOR_SHUFFLE, VT, MVT::v16i8);
00414 
00415       // We promote all non-typed operations to v4i32.
00416       setOperationAction(ISD::AND   , VT, Promote);
00417       AddPromotedToType (ISD::AND   , VT, MVT::v4i32);
00418       setOperationAction(ISD::OR    , VT, Promote);
00419       AddPromotedToType (ISD::OR    , VT, MVT::v4i32);
00420       setOperationAction(ISD::XOR   , VT, Promote);
00421       AddPromotedToType (ISD::XOR   , VT, MVT::v4i32);
00422       setOperationAction(ISD::LOAD  , VT, Promote);
00423       AddPromotedToType (ISD::LOAD  , VT, MVT::v4i32);
00424       setOperationAction(ISD::SELECT, VT, Promote);
00425       AddPromotedToType (ISD::SELECT, VT, MVT::v4i32);
00426       setOperationAction(ISD::STORE, VT, Promote);
00427       AddPromotedToType (ISD::STORE, VT, MVT::v4i32);
00428 
00429       // No other operations are legal.
00430       setOperationAction(ISD::MUL , VT, Expand);
00431       setOperationAction(ISD::SDIV, VT, Expand);
00432       setOperationAction(ISD::SREM, VT, Expand);
00433       setOperationAction(ISD::UDIV, VT, Expand);
00434       setOperationAction(ISD::UREM, VT, Expand);
00435       setOperationAction(ISD::FDIV, VT, Expand);
00436       setOperationAction(ISD::FREM, VT, Expand);
00437       setOperationAction(ISD::FNEG, VT, Expand);
00438       setOperationAction(ISD::FSQRT, VT, Expand);
00439       setOperationAction(ISD::FLOG, VT, Expand);
00440       setOperationAction(ISD::FLOG10, VT, Expand);
00441       setOperationAction(ISD::FLOG2, VT, Expand);
00442       setOperationAction(ISD::FEXP, VT, Expand);
00443       setOperationAction(ISD::FEXP2, VT, Expand);
00444       setOperationAction(ISD::FSIN, VT, Expand);
00445       setOperationAction(ISD::FCOS, VT, Expand);
00446       setOperationAction(ISD::FABS, VT, Expand);
00447       setOperationAction(ISD::FPOWI, VT, Expand);
00448       setOperationAction(ISD::FFLOOR, VT, Expand);
00449       setOperationAction(ISD::FCEIL,  VT, Expand);
00450       setOperationAction(ISD::FTRUNC, VT, Expand);
00451       setOperationAction(ISD::FRINT,  VT, Expand);
00452       setOperationAction(ISD::FNEARBYINT, VT, Expand);
00453       setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Expand);
00454       setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Expand);
00455       setOperationAction(ISD::BUILD_VECTOR, VT, Expand);
00456       setOperationAction(ISD::UMUL_LOHI, VT, Expand);
00457       setOperationAction(ISD::SMUL_LOHI, VT, Expand);
00458       setOperationAction(ISD::UDIVREM, VT, Expand);
00459       setOperationAction(ISD::SDIVREM, VT, Expand);
00460       setOperationAction(ISD::SCALAR_TO_VECTOR, VT, Expand);
00461       setOperationAction(ISD::FPOW, VT, Expand);
00462       setOperationAction(ISD::BSWAP, VT, Expand);
00463       setOperationAction(ISD::CTPOP, VT, Expand);
00464       setOperationAction(ISD::CTLZ, VT, Expand);
00465       setOperationAction(ISD::CTLZ_ZERO_UNDEF, VT, Expand);
00466       setOperationAction(ISD::CTTZ, VT, Expand);
00467       setOperationAction(ISD::CTTZ_ZERO_UNDEF, VT, Expand);
00468       setOperationAction(ISD::VSELECT, VT, Expand);
00469       setOperationAction(ISD::SIGN_EXTEND_INREG, VT, Expand);
00470 
00471       for (unsigned j = (unsigned)MVT::FIRST_VECTOR_VALUETYPE;
00472            j <= (unsigned)MVT::LAST_VECTOR_VALUETYPE; ++j) {
00473         MVT::SimpleValueType InnerVT = (MVT::SimpleValueType)j;
00474         setTruncStoreAction(VT, InnerVT, Expand);
00475       }
00476       setLoadExtAction(ISD::SEXTLOAD, VT, Expand);
00477       setLoadExtAction(ISD::ZEXTLOAD, VT, Expand);
00478       setLoadExtAction(ISD::EXTLOAD, VT, Expand);
00479     }
00480 
00481     // We can custom expand all VECTOR_SHUFFLEs to VPERM, others we can handle
00482     // with merges, splats, etc.
00483     setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v16i8, Custom);
00484 
00485     setOperationAction(ISD::AND   , MVT::v4i32, Legal);
00486     setOperationAction(ISD::OR    , MVT::v4i32, Legal);
00487     setOperationAction(ISD::XOR   , MVT::v4i32, Legal);
00488     setOperationAction(ISD::LOAD  , MVT::v4i32, Legal);
00489     setOperationAction(ISD::SELECT, MVT::v4i32,
00490                        Subtarget.useCRBits() ? Legal : Expand);
00491     setOperationAction(ISD::STORE , MVT::v4i32, Legal);
00492     setOperationAction(ISD::FP_TO_SINT, MVT::v4i32, Legal);
00493     setOperationAction(ISD::FP_TO_UINT, MVT::v4i32, Legal);
00494     setOperationAction(ISD::SINT_TO_FP, MVT::v4i32, Legal);
00495     setOperationAction(ISD::UINT_TO_FP, MVT::v4i32, Legal);
00496     setOperationAction(ISD::FFLOOR, MVT::v4f32, Legal);
00497     setOperationAction(ISD::FCEIL, MVT::v4f32, Legal);
00498     setOperationAction(ISD::FTRUNC, MVT::v4f32, Legal);
00499     setOperationAction(ISD::FNEARBYINT, MVT::v4f32, Legal);
00500 
00501     addRegisterClass(MVT::v4f32, &PPC::VRRCRegClass);
00502     addRegisterClass(MVT::v4i32, &PPC::VRRCRegClass);
00503     addRegisterClass(MVT::v8i16, &PPC::VRRCRegClass);
00504     addRegisterClass(MVT::v16i8, &PPC::VRRCRegClass);
00505 
00506     setOperationAction(ISD::MUL, MVT::v4f32, Legal);
00507     setOperationAction(ISD::FMA, MVT::v4f32, Legal);
00508 
00509     if (TM.Options.UnsafeFPMath || Subtarget.hasVSX()) {
00510       setOperationAction(ISD::FDIV, MVT::v4f32, Legal);
00511       setOperationAction(ISD::FSQRT, MVT::v4f32, Legal);
00512     }
00513 
00514     setOperationAction(ISD::MUL, MVT::v4i32, Custom);
00515     setOperationAction(ISD::MUL, MVT::v8i16, Custom);
00516     setOperationAction(ISD::MUL, MVT::v16i8, Custom);
00517 
00518     setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4f32, Custom);
00519     setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4i32, Custom);
00520 
00521     setOperationAction(ISD::BUILD_VECTOR, MVT::v16i8, Custom);
00522     setOperationAction(ISD::BUILD_VECTOR, MVT::v8i16, Custom);
00523     setOperationAction(ISD::BUILD_VECTOR, MVT::v4i32, Custom);
00524     setOperationAction(ISD::BUILD_VECTOR, MVT::v4f32, Custom);
00525 
00526     // Altivec does not contain unordered floating-point compare instructions
00527     setCondCodeAction(ISD::SETUO, MVT::v4f32, Expand);
00528     setCondCodeAction(ISD::SETUEQ, MVT::v4f32, Expand);
00529     setCondCodeAction(ISD::SETUGT, MVT::v4f32, Expand);
00530     setCondCodeAction(ISD::SETUGE, MVT::v4f32, Expand);
00531     setCondCodeAction(ISD::SETULT, MVT::v4f32, Expand);
00532     setCondCodeAction(ISD::SETULE, MVT::v4f32, Expand);
00533 
00534     setCondCodeAction(ISD::SETO,   MVT::v4f32, Expand);
00535     setCondCodeAction(ISD::SETONE, MVT::v4f32, Expand);
00536 
00537     if (Subtarget.hasVSX()) {
00538       setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v2f64, Legal);
00539       setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2f64, Legal);
00540 
00541       setOperationAction(ISD::FFLOOR, MVT::v2f64, Legal);
00542       setOperationAction(ISD::FCEIL, MVT::v2f64, Legal);
00543       setOperationAction(ISD::FTRUNC, MVT::v2f64, Legal);
00544       setOperationAction(ISD::FNEARBYINT, MVT::v2f64, Legal);
00545       setOperationAction(ISD::FROUND, MVT::v2f64, Legal);
00546 
00547       setOperationAction(ISD::FROUND, MVT::v4f32, Legal);
00548 
00549       setOperationAction(ISD::MUL, MVT::v2f64, Legal);
00550       setOperationAction(ISD::FMA, MVT::v2f64, Legal);
00551 
00552       setOperationAction(ISD::FDIV, MVT::v2f64, Legal);
00553       setOperationAction(ISD::FSQRT, MVT::v2f64, Legal);
00554 
00555       setOperationAction(ISD::VSELECT, MVT::v16i8, Legal);
00556       setOperationAction(ISD::VSELECT, MVT::v8i16, Legal);
00557       setOperationAction(ISD::VSELECT, MVT::v4i32, Legal);
00558       setOperationAction(ISD::VSELECT, MVT::v4f32, Legal);
00559       setOperationAction(ISD::VSELECT, MVT::v2f64, Legal);
00560 
00561       // Share the Altivec comparison restrictions.
00562       setCondCodeAction(ISD::SETUO, MVT::v2f64, Expand);
00563       setCondCodeAction(ISD::SETUEQ, MVT::v2f64, Expand);
00564       setCondCodeAction(ISD::SETUGT, MVT::v2f64, Expand);
00565       setCondCodeAction(ISD::SETUGE, MVT::v2f64, Expand);
00566       setCondCodeAction(ISD::SETULT, MVT::v2f64, Expand);
00567       setCondCodeAction(ISD::SETULE, MVT::v2f64, Expand);
00568 
00569       setCondCodeAction(ISD::SETO,   MVT::v2f64, Expand);
00570       setCondCodeAction(ISD::SETONE, MVT::v2f64, Expand);
00571 
00572       setOperationAction(ISD::LOAD, MVT::v2f64, Legal);
00573       setOperationAction(ISD::STORE, MVT::v2f64, Legal);
00574 
00575       setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v2f64, Legal);
00576 
00577       addRegisterClass(MVT::f64, &PPC::VSFRCRegClass);
00578 
00579       addRegisterClass(MVT::v4f32, &PPC::VSRCRegClass);
00580       addRegisterClass(MVT::v2f64, &PPC::VSRCRegClass);
00581 
00582       // VSX v2i64 only supports non-arithmetic operations.
00583       setOperationAction(ISD::ADD, MVT::v2i64, Expand);
00584       setOperationAction(ISD::SUB, MVT::v2i64, Expand);
00585 
00586       setOperationAction(ISD::SHL, MVT::v2i64, Expand);
00587       setOperationAction(ISD::SRA, MVT::v2i64, Expand);
00588       setOperationAction(ISD::SRL, MVT::v2i64, Expand);
00589 
00590       setOperationAction(ISD::SETCC, MVT::v2i64, Custom);
00591 
00592       setOperationAction(ISD::LOAD, MVT::v2i64, Promote);
00593       AddPromotedToType (ISD::LOAD, MVT::v2i64, MVT::v2f64);
00594       setOperationAction(ISD::STORE, MVT::v2i64, Promote);
00595       AddPromotedToType (ISD::STORE, MVT::v2i64, MVT::v2f64);
00596 
00597       setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v2i64, Legal);
00598 
00599       setOperationAction(ISD::SINT_TO_FP, MVT::v2i64, Legal);
00600       setOperationAction(ISD::UINT_TO_FP, MVT::v2i64, Legal);
00601       setOperationAction(ISD::FP_TO_SINT, MVT::v2i64, Legal);
00602       setOperationAction(ISD::FP_TO_UINT, MVT::v2i64, Legal);
00603 
00604       // Vector operation legalization checks the result type of
00605       // SIGN_EXTEND_INREG, overall legalization checks the inner type.
00606       setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i64, Legal);
00607       setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i32, Legal);
00608       setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i16, Custom);
00609       setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i8, Custom);
00610 
00611       addRegisterClass(MVT::v2i64, &PPC::VSRCRegClass);
00612     }
00613   }
00614 
00615   if (Subtarget.has64BitSupport()) {
00616     setOperationAction(ISD::PREFETCH, MVT::Other, Legal);
00617     setOperationAction(ISD::READCYCLECOUNTER, MVT::i64, Legal);
00618   }
00619 
00620   setOperationAction(ISD::ATOMIC_LOAD,  MVT::i32, Expand);
00621   setOperationAction(ISD::ATOMIC_STORE, MVT::i32, Expand);
00622   setOperationAction(ISD::ATOMIC_LOAD,  MVT::i64, Expand);
00623   setOperationAction(ISD::ATOMIC_STORE, MVT::i64, Expand);
00624 
00625   setBooleanContents(ZeroOrOneBooleanContent);
00626   // Altivec instructions set fields to all zeros or all ones.
00627   setBooleanVectorContents(ZeroOrNegativeOneBooleanContent);
00628 
00629   if (isPPC64) {
00630     setStackPointerRegisterToSaveRestore(PPC::X1);
00631     setExceptionPointerRegister(PPC::X3);
00632     setExceptionSelectorRegister(PPC::X4);
00633   } else {
00634     setStackPointerRegisterToSaveRestore(PPC::R1);
00635     setExceptionPointerRegister(PPC::R3);
00636     setExceptionSelectorRegister(PPC::R4);
00637   }
00638 
00639   // We have target-specific dag combine patterns for the following nodes:
00640   setTargetDAGCombine(ISD::SINT_TO_FP);
00641   setTargetDAGCombine(ISD::LOAD);
00642   setTargetDAGCombine(ISD::STORE);
00643   setTargetDAGCombine(ISD::BR_CC);
00644   if (Subtarget.useCRBits())
00645     setTargetDAGCombine(ISD::BRCOND);
00646   setTargetDAGCombine(ISD::BSWAP);
00647   setTargetDAGCombine(ISD::INTRINSIC_WO_CHAIN);
00648 
00649   setTargetDAGCombine(ISD::SIGN_EXTEND);
00650   setTargetDAGCombine(ISD::ZERO_EXTEND);
00651   setTargetDAGCombine(ISD::ANY_EXTEND);
00652 
00653   if (Subtarget.useCRBits()) {
00654     setTargetDAGCombine(ISD::TRUNCATE);
00655     setTargetDAGCombine(ISD::SETCC);
00656     setTargetDAGCombine(ISD::SELECT_CC);
00657   }
00658 
00659   // Use reciprocal estimates.
00660   if (TM.Options.UnsafeFPMath) {
00661     setTargetDAGCombine(ISD::FDIV);
00662     setTargetDAGCombine(ISD::FSQRT);
00663   }
00664 
00665   // Darwin long double math library functions have $LDBL128 appended.
00666   if (Subtarget.isDarwin()) {
00667     setLibcallName(RTLIB::COS_PPCF128, "cosl$LDBL128");
00668     setLibcallName(RTLIB::POW_PPCF128, "powl$LDBL128");
00669     setLibcallName(RTLIB::REM_PPCF128, "fmodl$LDBL128");
00670     setLibcallName(RTLIB::SIN_PPCF128, "sinl$LDBL128");
00671     setLibcallName(RTLIB::SQRT_PPCF128, "sqrtl$LDBL128");
00672     setLibcallName(RTLIB::LOG_PPCF128, "logl$LDBL128");
00673     setLibcallName(RTLIB::LOG2_PPCF128, "log2l$LDBL128");
00674     setLibcallName(RTLIB::LOG10_PPCF128, "log10l$LDBL128");
00675     setLibcallName(RTLIB::EXP_PPCF128, "expl$LDBL128");
00676     setLibcallName(RTLIB::EXP2_PPCF128, "exp2l$LDBL128");
00677   }
00678 
00679   // With 32 condition bits, we don't need to sink (and duplicate) compares
00680   // aggressively in CodeGenPrep.
00681   if (Subtarget.useCRBits())
00682     setHasMultipleConditionRegisters();
00683 
00684   setMinFunctionAlignment(2);
00685   if (Subtarget.isDarwin())
00686     setPrefFunctionAlignment(4);
00687 
00688   if (isPPC64 && Subtarget.isJITCodeModel())
00689     // Temporary workaround for the inability of PPC64 JIT to handle jump
00690     // tables.
00691     setSupportJumpTables(false);
00692 
00693   setInsertFencesForAtomic(true);
00694 
00695   if (Subtarget.enableMachineScheduler())
00696     setSchedulingPreference(Sched::Source);
00697   else
00698     setSchedulingPreference(Sched::Hybrid);
00699 
00700   computeRegisterProperties();
00701 
00702   // The Freescale cores does better with aggressive inlining of memcpy and
00703   // friends. Gcc uses same threshold of 128 bytes (= 32 word stores).
00704   if (Subtarget.getDarwinDirective() == PPC::DIR_E500mc ||
00705       Subtarget.getDarwinDirective() == PPC::DIR_E5500) {
00706     MaxStoresPerMemset = 32;
00707     MaxStoresPerMemsetOptSize = 16;
00708     MaxStoresPerMemcpy = 32;
00709     MaxStoresPerMemcpyOptSize = 8;
00710     MaxStoresPerMemmove = 32;
00711     MaxStoresPerMemmoveOptSize = 8;
00712 
00713     setPrefFunctionAlignment(4);
00714   }
00715 }
00716 
00717 /// getMaxByValAlign - Helper for getByValTypeAlignment to determine
00718 /// the desired ByVal argument alignment.
00719 static void getMaxByValAlign(Type *Ty, unsigned &MaxAlign,
00720                              unsigned MaxMaxAlign) {
00721   if (MaxAlign == MaxMaxAlign)
00722     return;
00723   if (VectorType *VTy = dyn_cast<VectorType>(Ty)) {
00724     if (MaxMaxAlign >= 32 && VTy->getBitWidth() >= 256)
00725       MaxAlign = 32;
00726     else if (VTy->getBitWidth() >= 128 && MaxAlign < 16)
00727       MaxAlign = 16;
00728   } else if (ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
00729     unsigned EltAlign = 0;
00730     getMaxByValAlign(ATy->getElementType(), EltAlign, MaxMaxAlign);
00731     if (EltAlign > MaxAlign)
00732       MaxAlign = EltAlign;
00733   } else if (StructType *STy = dyn_cast<StructType>(Ty)) {
00734     for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
00735       unsigned EltAlign = 0;
00736       getMaxByValAlign(STy->getElementType(i), EltAlign, MaxMaxAlign);
00737       if (EltAlign > MaxAlign)
00738         MaxAlign = EltAlign;
00739       if (MaxAlign == MaxMaxAlign)
00740         break;
00741     }
00742   }
00743 }
00744 
00745 /// getByValTypeAlignment - Return the desired alignment for ByVal aggregate
00746 /// function arguments in the caller parameter area.
00747 unsigned PPCTargetLowering::getByValTypeAlignment(Type *Ty) const {
00748   // Darwin passes everything on 4 byte boundary.
00749   if (Subtarget.isDarwin())
00750     return 4;
00751 
00752   // 16byte and wider vectors are passed on 16byte boundary.
00753   // The rest is 8 on PPC64 and 4 on PPC32 boundary.
00754   unsigned Align = Subtarget.isPPC64() ? 8 : 4;
00755   if (Subtarget.hasAltivec() || Subtarget.hasQPX())
00756     getMaxByValAlign(Ty, Align, Subtarget.hasQPX() ? 32 : 16);
00757   return Align;
00758 }
00759 
00760 const char *PPCTargetLowering::getTargetNodeName(unsigned Opcode) const {
00761   switch (Opcode) {
00762   default: return nullptr;
00763   case PPCISD::FSEL:            return "PPCISD::FSEL";
00764   case PPCISD::FCFID:           return "PPCISD::FCFID";
00765   case PPCISD::FCTIDZ:          return "PPCISD::FCTIDZ";
00766   case PPCISD::FCTIWZ:          return "PPCISD::FCTIWZ";
00767   case PPCISD::FRE:             return "PPCISD::FRE";
00768   case PPCISD::FRSQRTE:         return "PPCISD::FRSQRTE";
00769   case PPCISD::STFIWX:          return "PPCISD::STFIWX";
00770   case PPCISD::VMADDFP:         return "PPCISD::VMADDFP";
00771   case PPCISD::VNMSUBFP:        return "PPCISD::VNMSUBFP";
00772   case PPCISD::VPERM:           return "PPCISD::VPERM";
00773   case PPCISD::Hi:              return "PPCISD::Hi";
00774   case PPCISD::Lo:              return "PPCISD::Lo";
00775   case PPCISD::TOC_ENTRY:       return "PPCISD::TOC_ENTRY";
00776   case PPCISD::LOAD:            return "PPCISD::LOAD";
00777   case PPCISD::LOAD_TOC:        return "PPCISD::LOAD_TOC";
00778   case PPCISD::DYNALLOC:        return "PPCISD::DYNALLOC";
00779   case PPCISD::GlobalBaseReg:   return "PPCISD::GlobalBaseReg";
00780   case PPCISD::SRL:             return "PPCISD::SRL";
00781   case PPCISD::SRA:             return "PPCISD::SRA";
00782   case PPCISD::SHL:             return "PPCISD::SHL";
00783   case PPCISD::CALL:            return "PPCISD::CALL";
00784   case PPCISD::CALL_NOP:        return "PPCISD::CALL_NOP";
00785   case PPCISD::MTCTR:           return "PPCISD::MTCTR";
00786   case PPCISD::BCTRL:           return "PPCISD::BCTRL";
00787   case PPCISD::RET_FLAG:        return "PPCISD::RET_FLAG";
00788   case PPCISD::EH_SJLJ_SETJMP:  return "PPCISD::EH_SJLJ_SETJMP";
00789   case PPCISD::EH_SJLJ_LONGJMP: return "PPCISD::EH_SJLJ_LONGJMP";
00790   case PPCISD::MFOCRF:          return "PPCISD::MFOCRF";
00791   case PPCISD::VCMP:            return "PPCISD::VCMP";
00792   case PPCISD::VCMPo:           return "PPCISD::VCMPo";
00793   case PPCISD::LBRX:            return "PPCISD::LBRX";
00794   case PPCISD::STBRX:           return "PPCISD::STBRX";
00795   case PPCISD::LARX:            return "PPCISD::LARX";
00796   case PPCISD::STCX:            return "PPCISD::STCX";
00797   case PPCISD::COND_BRANCH:     return "PPCISD::COND_BRANCH";
00798   case PPCISD::BDNZ:            return "PPCISD::BDNZ";
00799   case PPCISD::BDZ:             return "PPCISD::BDZ";
00800   case PPCISD::MFFS:            return "PPCISD::MFFS";
00801   case PPCISD::FADDRTZ:         return "PPCISD::FADDRTZ";
00802   case PPCISD::TC_RETURN:       return "PPCISD::TC_RETURN";
00803   case PPCISD::CR6SET:          return "PPCISD::CR6SET";
00804   case PPCISD::CR6UNSET:        return "PPCISD::CR6UNSET";
00805   case PPCISD::ADDIS_TOC_HA:    return "PPCISD::ADDIS_TOC_HA";
00806   case PPCISD::LD_TOC_L:        return "PPCISD::LD_TOC_L";
00807   case PPCISD::ADDI_TOC_L:      return "PPCISD::ADDI_TOC_L";
00808   case PPCISD::PPC32_GOT:       return "PPCISD::PPC32_GOT";
00809   case PPCISD::ADDIS_GOT_TPREL_HA: return "PPCISD::ADDIS_GOT_TPREL_HA";
00810   case PPCISD::LD_GOT_TPREL_L:  return "PPCISD::LD_GOT_TPREL_L";
00811   case PPCISD::ADD_TLS:         return "PPCISD::ADD_TLS";
00812   case PPCISD::ADDIS_TLSGD_HA:  return "PPCISD::ADDIS_TLSGD_HA";
00813   case PPCISD::ADDI_TLSGD_L:    return "PPCISD::ADDI_TLSGD_L";
00814   case PPCISD::GET_TLS_ADDR:    return "PPCISD::GET_TLS_ADDR";
00815   case PPCISD::ADDIS_TLSLD_HA:  return "PPCISD::ADDIS_TLSLD_HA";
00816   case PPCISD::ADDI_TLSLD_L:    return "PPCISD::ADDI_TLSLD_L";
00817   case PPCISD::GET_TLSLD_ADDR:  return "PPCISD::GET_TLSLD_ADDR";
00818   case PPCISD::ADDIS_DTPREL_HA: return "PPCISD::ADDIS_DTPREL_HA";
00819   case PPCISD::ADDI_DTPREL_L:   return "PPCISD::ADDI_DTPREL_L";
00820   case PPCISD::VADD_SPLAT:      return "PPCISD::VADD_SPLAT";
00821   case PPCISD::SC:              return "PPCISD::SC";
00822   }
00823 }
00824 
00825 EVT PPCTargetLowering::getSetCCResultType(LLVMContext &, EVT VT) const {
00826   if (!VT.isVector())
00827     return Subtarget.useCRBits() ? MVT::i1 : MVT::i32;
00828   return VT.changeVectorElementTypeToInteger();
00829 }
00830 
00831 //===----------------------------------------------------------------------===//
00832 // Node matching predicates, for use by the tblgen matching code.
00833 //===----------------------------------------------------------------------===//
00834 
00835 /// isFloatingPointZero - Return true if this is 0.0 or -0.0.
00836 static bool isFloatingPointZero(SDValue Op) {
00837   if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Op))
00838     return CFP->getValueAPF().isZero();
00839   else if (ISD::isEXTLoad(Op.getNode()) || ISD::isNON_EXTLoad(Op.getNode())) {
00840     // Maybe this has already been legalized into the constant pool?
00841     if (ConstantPoolSDNode *CP = dyn_cast<ConstantPoolSDNode>(Op.getOperand(1)))
00842       if (const ConstantFP *CFP = dyn_cast<ConstantFP>(CP->getConstVal()))
00843         return CFP->getValueAPF().isZero();
00844   }
00845   return false;
00846 }
00847 
00848 /// isConstantOrUndef - Op is either an undef node or a ConstantSDNode.  Return
00849 /// true if Op is undef or if it matches the specified value.
00850 static bool isConstantOrUndef(int Op, int Val) {
00851   return Op < 0 || Op == Val;
00852 }
00853 
00854 /// isVPKUHUMShuffleMask - Return true if this is the shuffle mask for a
00855 /// VPKUHUM instruction.
00856 bool PPC::isVPKUHUMShuffleMask(ShuffleVectorSDNode *N, bool isUnary,
00857                                SelectionDAG &DAG) {
00858   unsigned j = DAG.getTarget().getDataLayout()->isLittleEndian() ? 0 : 1;
00859   if (!isUnary) {
00860     for (unsigned i = 0; i != 16; ++i)
00861       if (!isConstantOrUndef(N->getMaskElt(i),  i*2+j))
00862         return false;
00863   } else {
00864     for (unsigned i = 0; i != 8; ++i)
00865       if (!isConstantOrUndef(N->getMaskElt(i),    i*2+j) ||
00866           !isConstantOrUndef(N->getMaskElt(i+8),  i*2+j))
00867         return false;
00868   }
00869   return true;
00870 }
00871 
00872 /// isVPKUWUMShuffleMask - Return true if this is the shuffle mask for a
00873 /// VPKUWUM instruction.
00874 bool PPC::isVPKUWUMShuffleMask(ShuffleVectorSDNode *N, bool isUnary,
00875                                SelectionDAG &DAG) {
00876   unsigned j, k;
00877   if (DAG.getTarget().getDataLayout()->isLittleEndian()) {
00878     j = 0;
00879     k = 1;
00880   } else {
00881     j = 2;
00882     k = 3;
00883   }
00884   if (!isUnary) {
00885     for (unsigned i = 0; i != 16; i += 2)
00886       if (!isConstantOrUndef(N->getMaskElt(i  ),  i*2+j) ||
00887           !isConstantOrUndef(N->getMaskElt(i+1),  i*2+k))
00888         return false;
00889   } else {
00890     for (unsigned i = 0; i != 8; i += 2)
00891       if (!isConstantOrUndef(N->getMaskElt(i  ),  i*2+j) ||
00892           !isConstantOrUndef(N->getMaskElt(i+1),  i*2+k) ||
00893           !isConstantOrUndef(N->getMaskElt(i+8),  i*2+j) ||
00894           !isConstantOrUndef(N->getMaskElt(i+9),  i*2+k))
00895         return false;
00896   }
00897   return true;
00898 }
00899 
00900 /// isVMerge - Common function, used to match vmrg* shuffles.
00901 ///
00902 static bool isVMerge(ShuffleVectorSDNode *N, unsigned UnitSize,
00903                      unsigned LHSStart, unsigned RHSStart) {
00904   if (N->getValueType(0) != MVT::v16i8)
00905     return false;
00906   assert((UnitSize == 1 || UnitSize == 2 || UnitSize == 4) &&
00907          "Unsupported merge size!");
00908 
00909   for (unsigned i = 0; i != 8/UnitSize; ++i)     // Step over units
00910     for (unsigned j = 0; j != UnitSize; ++j) {   // Step over bytes within unit
00911       if (!isConstantOrUndef(N->getMaskElt(i*UnitSize*2+j),
00912                              LHSStart+j+i*UnitSize) ||
00913           !isConstantOrUndef(N->getMaskElt(i*UnitSize*2+UnitSize+j),
00914                              RHSStart+j+i*UnitSize))
00915         return false;
00916     }
00917   return true;
00918 }
00919 
00920 /// isVMRGLShuffleMask - Return true if this is a shuffle mask suitable for
00921 /// a VMRGL* instruction with the specified unit size (1,2 or 4 bytes).
00922 bool PPC::isVMRGLShuffleMask(ShuffleVectorSDNode *N, unsigned UnitSize,
00923                              bool isUnary, SelectionDAG &DAG) {
00924   if (DAG.getTarget().getDataLayout()->isLittleEndian()) {
00925     if (!isUnary)
00926       return isVMerge(N, UnitSize, 0, 16);
00927     return isVMerge(N, UnitSize, 0, 0);
00928   } else {
00929     if (!isUnary)
00930       return isVMerge(N, UnitSize, 8, 24);
00931     return isVMerge(N, UnitSize, 8, 8);
00932   }
00933 }
00934 
00935 /// isVMRGHShuffleMask - Return true if this is a shuffle mask suitable for
00936 /// a VMRGH* instruction with the specified unit size (1,2 or 4 bytes).
00937 bool PPC::isVMRGHShuffleMask(ShuffleVectorSDNode *N, unsigned UnitSize,
00938                              bool isUnary, SelectionDAG &DAG) {
00939   if (DAG.getTarget().getDataLayout()->isLittleEndian()) {
00940     if (!isUnary)
00941       return isVMerge(N, UnitSize, 8, 24);
00942     return isVMerge(N, UnitSize, 8, 8);
00943   } else {
00944     if (!isUnary)
00945       return isVMerge(N, UnitSize, 0, 16);
00946     return isVMerge(N, UnitSize, 0, 0);
00947   }
00948 }
00949 
00950 
00951 /// isVSLDOIShuffleMask - If this is a vsldoi shuffle mask, return the shift
00952 /// amount, otherwise return -1.
00953 int PPC::isVSLDOIShuffleMask(SDNode *N, bool isUnary, SelectionDAG &DAG) {
00954   if (N->getValueType(0) != MVT::v16i8)
00955     return -1;
00956 
00957   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
00958 
00959   // Find the first non-undef value in the shuffle mask.
00960   unsigned i;
00961   for (i = 0; i != 16 && SVOp->getMaskElt(i) < 0; ++i)
00962     /*search*/;
00963 
00964   if (i == 16) return -1;  // all undef.
00965 
00966   // Otherwise, check to see if the rest of the elements are consecutively
00967   // numbered from this value.
00968   unsigned ShiftAmt = SVOp->getMaskElt(i);
00969   if (ShiftAmt < i) return -1;
00970 
00971   if (DAG.getTarget().getDataLayout()->isLittleEndian()) {
00972 
00973     ShiftAmt += i;
00974 
00975     if (!isUnary) {
00976       // Check the rest of the elements to see if they are consecutive.
00977       for (++i; i != 16; ++i)
00978         if (!isConstantOrUndef(SVOp->getMaskElt(i), ShiftAmt - i))
00979           return -1;
00980     } else {
00981       // Check the rest of the elements to see if they are consecutive.
00982       for (++i; i != 16; ++i)
00983         if (!isConstantOrUndef(SVOp->getMaskElt(i), (ShiftAmt - i) & 15))
00984           return -1;
00985     }
00986 
00987   } else {  // Big Endian
00988 
00989     ShiftAmt -= i;
00990 
00991     if (!isUnary) {
00992       // Check the rest of the elements to see if they are consecutive.
00993       for (++i; i != 16; ++i)
00994         if (!isConstantOrUndef(SVOp->getMaskElt(i), ShiftAmt+i))
00995           return -1;
00996     } else {
00997       // Check the rest of the elements to see if they are consecutive.
00998       for (++i; i != 16; ++i)
00999         if (!isConstantOrUndef(SVOp->getMaskElt(i), (ShiftAmt+i) & 15))
01000           return -1;
01001     }
01002   }
01003   return ShiftAmt;
01004 }
01005 
01006 /// isSplatShuffleMask - Return true if the specified VECTOR_SHUFFLE operand
01007 /// specifies a splat of a single element that is suitable for input to
01008 /// VSPLTB/VSPLTH/VSPLTW.
01009 bool PPC::isSplatShuffleMask(ShuffleVectorSDNode *N, unsigned EltSize) {
01010   assert(N->getValueType(0) == MVT::v16i8 &&
01011          (EltSize == 1 || EltSize == 2 || EltSize == 4));
01012 
01013   // This is a splat operation if each element of the permute is the same, and
01014   // if the value doesn't reference the second vector.
01015   unsigned ElementBase = N->getMaskElt(0);
01016 
01017   // FIXME: Handle UNDEF elements too!
01018   if (ElementBase >= 16)
01019     return false;
01020 
01021   // Check that the indices are consecutive, in the case of a multi-byte element
01022   // splatted with a v16i8 mask.
01023   for (unsigned i = 1; i != EltSize; ++i)
01024     if (N->getMaskElt(i) < 0 || N->getMaskElt(i) != (int)(i+ElementBase))
01025       return false;
01026 
01027   for (unsigned i = EltSize, e = 16; i != e; i += EltSize) {
01028     if (N->getMaskElt(i) < 0) continue;
01029     for (unsigned j = 0; j != EltSize; ++j)
01030       if (N->getMaskElt(i+j) != N->getMaskElt(j))
01031         return false;
01032   }
01033   return true;
01034 }
01035 
01036 /// isAllNegativeZeroVector - Returns true if all elements of build_vector
01037 /// are -0.0.
01038 bool PPC::isAllNegativeZeroVector(SDNode *N) {
01039   BuildVectorSDNode *BV = cast<BuildVectorSDNode>(N);
01040 
01041   APInt APVal, APUndef;
01042   unsigned BitSize;
01043   bool HasAnyUndefs;
01044 
01045   if (BV->isConstantSplat(APVal, APUndef, BitSize, HasAnyUndefs, 32, true))
01046     if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
01047       return CFP->getValueAPF().isNegZero();
01048 
01049   return false;
01050 }
01051 
01052 /// getVSPLTImmediate - Return the appropriate VSPLT* immediate to splat the
01053 /// specified isSplatShuffleMask VECTOR_SHUFFLE mask.
01054 unsigned PPC::getVSPLTImmediate(SDNode *N, unsigned EltSize,
01055                                 SelectionDAG &DAG) {
01056   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
01057   assert(isSplatShuffleMask(SVOp, EltSize));
01058   if (DAG.getTarget().getDataLayout()->isLittleEndian())
01059     return (16 / EltSize) - 1 - (SVOp->getMaskElt(0) / EltSize);
01060   else
01061     return SVOp->getMaskElt(0) / EltSize;
01062 }
01063 
01064 /// get_VSPLTI_elt - If this is a build_vector of constants which can be formed
01065 /// by using a vspltis[bhw] instruction of the specified element size, return
01066 /// the constant being splatted.  The ByteSize field indicates the number of
01067 /// bytes of each element [124] -> [bhw].
01068 SDValue PPC::get_VSPLTI_elt(SDNode *N, unsigned ByteSize, SelectionDAG &DAG) {
01069   SDValue OpVal(nullptr, 0);
01070 
01071   // If ByteSize of the splat is bigger than the element size of the
01072   // build_vector, then we have a case where we are checking for a splat where
01073   // multiple elements of the buildvector are folded together into a single
01074   // logical element of the splat (e.g. "vsplish 1" to splat {0,1}*8).
01075   unsigned EltSize = 16/N->getNumOperands();
01076   if (EltSize < ByteSize) {
01077     unsigned Multiple = ByteSize/EltSize;   // Number of BV entries per spltval.
01078     SDValue UniquedVals[4];
01079     assert(Multiple > 1 && Multiple <= 4 && "How can this happen?");
01080 
01081     // See if all of the elements in the buildvector agree across.
01082     for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
01083       if (N->getOperand(i).getOpcode() == ISD::UNDEF) continue;
01084       // If the element isn't a constant, bail fully out.
01085       if (!isa<ConstantSDNode>(N->getOperand(i))) return SDValue();
01086 
01087 
01088       if (!UniquedVals[i&(Multiple-1)].getNode())
01089         UniquedVals[i&(Multiple-1)] = N->getOperand(i);
01090       else if (UniquedVals[i&(Multiple-1)] != N->getOperand(i))
01091         return SDValue();  // no match.
01092     }
01093 
01094     // Okay, if we reached this point, UniquedVals[0..Multiple-1] contains
01095     // either constant or undef values that are identical for each chunk.  See
01096     // if these chunks can form into a larger vspltis*.
01097 
01098     // Check to see if all of the leading entries are either 0 or -1.  If
01099     // neither, then this won't fit into the immediate field.
01100     bool LeadingZero = true;
01101     bool LeadingOnes = true;
01102     for (unsigned i = 0; i != Multiple-1; ++i) {
01103       if (!UniquedVals[i].getNode()) continue;  // Must have been undefs.
01104 
01105       LeadingZero &= cast<ConstantSDNode>(UniquedVals[i])->isNullValue();
01106       LeadingOnes &= cast<ConstantSDNode>(UniquedVals[i])->isAllOnesValue();
01107     }
01108     // Finally, check the least significant entry.
01109     if (LeadingZero) {
01110       if (!UniquedVals[Multiple-1].getNode())
01111         return DAG.getTargetConstant(0, MVT::i32);  // 0,0,0,undef
01112       int Val = cast<ConstantSDNode>(UniquedVals[Multiple-1])->getZExtValue();
01113       if (Val < 16)
01114         return DAG.getTargetConstant(Val, MVT::i32);  // 0,0,0,4 -> vspltisw(4)
01115     }
01116     if (LeadingOnes) {
01117       if (!UniquedVals[Multiple-1].getNode())
01118         return DAG.getTargetConstant(~0U, MVT::i32);  // -1,-1,-1,undef
01119       int Val =cast<ConstantSDNode>(UniquedVals[Multiple-1])->getSExtValue();
01120       if (Val >= -16)                            // -1,-1,-1,-2 -> vspltisw(-2)
01121         return DAG.getTargetConstant(Val, MVT::i32);
01122     }
01123 
01124     return SDValue();
01125   }
01126 
01127   // Check to see if this buildvec has a single non-undef value in its elements.
01128   for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
01129     if (N->getOperand(i).getOpcode() == ISD::UNDEF) continue;
01130     if (!OpVal.getNode())
01131       OpVal = N->getOperand(i);
01132     else if (OpVal != N->getOperand(i))
01133       return SDValue();
01134   }
01135 
01136   if (!OpVal.getNode()) return SDValue();  // All UNDEF: use implicit def.
01137 
01138   unsigned ValSizeInBytes = EltSize;
01139   uint64_t Value = 0;
01140   if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(OpVal)) {
01141     Value = CN->getZExtValue();
01142   } else if (ConstantFPSDNode *CN = dyn_cast<ConstantFPSDNode>(OpVal)) {
01143     assert(CN->getValueType(0) == MVT::f32 && "Only one legal FP vector type!");
01144     Value = FloatToBits(CN->getValueAPF().convertToFloat());
01145   }
01146 
01147   // If the splat value is larger than the element value, then we can never do
01148   // this splat.  The only case that we could fit the replicated bits into our
01149   // immediate field for would be zero, and we prefer to use vxor for it.
01150   if (ValSizeInBytes < ByteSize) return SDValue();
01151 
01152   // If the element value is larger than the splat value, cut it in half and
01153   // check to see if the two halves are equal.  Continue doing this until we
01154   // get to ByteSize.  This allows us to handle 0x01010101 as 0x01.
01155   while (ValSizeInBytes > ByteSize) {
01156     ValSizeInBytes >>= 1;
01157 
01158     // If the top half equals the bottom half, we're still ok.
01159     if (((Value >> (ValSizeInBytes*8)) & ((1 << (8*ValSizeInBytes))-1)) !=
01160          (Value                        & ((1 << (8*ValSizeInBytes))-1)))
01161       return SDValue();
01162   }
01163 
01164   // Properly sign extend the value.
01165   int MaskVal = SignExtend32(Value, ByteSize * 8);
01166 
01167   // If this is zero, don't match, zero matches ISD::isBuildVectorAllZeros.
01168   if (MaskVal == 0) return SDValue();
01169 
01170   // Finally, if this value fits in a 5 bit sext field, return it
01171   if (SignExtend32<5>(MaskVal) == MaskVal)
01172     return DAG.getTargetConstant(MaskVal, MVT::i32);
01173   return SDValue();
01174 }
01175 
01176 //===----------------------------------------------------------------------===//
01177 //  Addressing Mode Selection
01178 //===----------------------------------------------------------------------===//
01179 
01180 /// isIntS16Immediate - This method tests to see if the node is either a 32-bit
01181 /// or 64-bit immediate, and if the value can be accurately represented as a
01182 /// sign extension from a 16-bit value.  If so, this returns true and the
01183 /// immediate.
01184 static bool isIntS16Immediate(SDNode *N, short &Imm) {
01185   if (!isa<ConstantSDNode>(N))
01186     return false;
01187 
01188   Imm = (short)cast<ConstantSDNode>(N)->getZExtValue();
01189   if (N->getValueType(0) == MVT::i32)
01190     return Imm == (int32_t)cast<ConstantSDNode>(N)->getZExtValue();
01191   else
01192     return Imm == (int64_t)cast<ConstantSDNode>(N)->getZExtValue();
01193 }
01194 static bool isIntS16Immediate(SDValue Op, short &Imm) {
01195   return isIntS16Immediate(Op.getNode(), Imm);
01196 }
01197 
01198 
01199 /// SelectAddressRegReg - Given the specified addressed, check to see if it
01200 /// can be represented as an indexed [r+r] operation.  Returns false if it
01201 /// can be more efficiently represented with [r+imm].
01202 bool PPCTargetLowering::SelectAddressRegReg(SDValue N, SDValue &Base,
01203                                             SDValue &Index,
01204                                             SelectionDAG &DAG) const {
01205   short imm = 0;
01206   if (N.getOpcode() == ISD::ADD) {
01207     if (isIntS16Immediate(N.getOperand(1), imm))
01208       return false;    // r+i
01209     if (N.getOperand(1).getOpcode() == PPCISD::Lo)
01210       return false;    // r+i
01211 
01212     Base = N.getOperand(0);
01213     Index = N.getOperand(1);
01214     return true;
01215   } else if (N.getOpcode() == ISD::OR) {
01216     if (isIntS16Immediate(N.getOperand(1), imm))
01217       return false;    // r+i can fold it if we can.
01218 
01219     // If this is an or of disjoint bitfields, we can codegen this as an add
01220     // (for better address arithmetic) if the LHS and RHS of the OR are provably
01221     // disjoint.
01222     APInt LHSKnownZero, LHSKnownOne;
01223     APInt RHSKnownZero, RHSKnownOne;
01224     DAG.computeKnownBits(N.getOperand(0),
01225                          LHSKnownZero, LHSKnownOne);
01226 
01227     if (LHSKnownZero.getBoolValue()) {
01228       DAG.computeKnownBits(N.getOperand(1),
01229                            RHSKnownZero, RHSKnownOne);
01230       // If all of the bits are known zero on the LHS or RHS, the add won't
01231       // carry.
01232       if (~(LHSKnownZero | RHSKnownZero) == 0) {
01233         Base = N.getOperand(0);
01234         Index = N.getOperand(1);
01235         return true;
01236       }
01237     }
01238   }
01239 
01240   return false;
01241 }
01242 
01243 // If we happen to be doing an i64 load or store into a stack slot that has
01244 // less than a 4-byte alignment, then the frame-index elimination may need to
01245 // use an indexed load or store instruction (because the offset may not be a
01246 // multiple of 4). The extra register needed to hold the offset comes from the
01247 // register scavenger, and it is possible that the scavenger will need to use
01248 // an emergency spill slot. As a result, we need to make sure that a spill slot
01249 // is allocated when doing an i64 load/store into a less-than-4-byte-aligned
01250 // stack slot.
01251 static void fixupFuncForFI(SelectionDAG &DAG, int FrameIdx, EVT VT) {
01252   // FIXME: This does not handle the LWA case.
01253   if (VT != MVT::i64)
01254     return;
01255 
01256   // NOTE: We'll exclude negative FIs here, which come from argument
01257   // lowering, because there are no known test cases triggering this problem
01258   // using packed structures (or similar). We can remove this exclusion if
01259   // we find such a test case. The reason why this is so test-case driven is
01260   // because this entire 'fixup' is only to prevent crashes (from the
01261   // register scavenger) on not-really-valid inputs. For example, if we have:
01262   //   %a = alloca i1
01263   //   %b = bitcast i1* %a to i64*
01264   //   store i64* a, i64 b
01265   // then the store should really be marked as 'align 1', but is not. If it
01266   // were marked as 'align 1' then the indexed form would have been
01267   // instruction-selected initially, and the problem this 'fixup' is preventing
01268   // won't happen regardless.
01269   if (FrameIdx < 0)
01270     return;
01271 
01272   MachineFunction &MF = DAG.getMachineFunction();
01273   MachineFrameInfo *MFI = MF.getFrameInfo();
01274 
01275   unsigned Align = MFI->getObjectAlignment(FrameIdx);
01276   if (Align >= 4)
01277     return;
01278 
01279   PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
01280   FuncInfo->setHasNonRISpills();
01281 }
01282 
01283 /// Returns true if the address N can be represented by a base register plus
01284 /// a signed 16-bit displacement [r+imm], and if it is not better
01285 /// represented as reg+reg.  If Aligned is true, only accept displacements
01286 /// suitable for STD and friends, i.e. multiples of 4.
01287 bool PPCTargetLowering::SelectAddressRegImm(SDValue N, SDValue &Disp,
01288                                             SDValue &Base,
01289                                             SelectionDAG &DAG,
01290                                             bool Aligned) const {
01291   // FIXME dl should come from parent load or store, not from address
01292   SDLoc dl(N);
01293   // If this can be more profitably realized as r+r, fail.
01294   if (SelectAddressRegReg(N, Disp, Base, DAG))
01295     return false;
01296 
01297   if (N.getOpcode() == ISD::ADD) {
01298     short imm = 0;
01299     if (isIntS16Immediate(N.getOperand(1), imm) &&
01300         (!Aligned || (imm & 3) == 0)) {
01301       Disp = DAG.getTargetConstant(imm, N.getValueType());
01302       if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(N.getOperand(0))) {
01303         Base = DAG.getTargetFrameIndex(FI->getIndex(), N.getValueType());
01304         fixupFuncForFI(DAG, FI->getIndex(), N.getValueType());
01305       } else {
01306         Base = N.getOperand(0);
01307       }
01308       return true; // [r+i]
01309     } else if (N.getOperand(1).getOpcode() == PPCISD::Lo) {
01310       // Match LOAD (ADD (X, Lo(G))).
01311       assert(!cast<ConstantSDNode>(N.getOperand(1).getOperand(1))->getZExtValue()
01312              && "Cannot handle constant offsets yet!");
01313       Disp = N.getOperand(1).getOperand(0);  // The global address.
01314       assert(Disp.getOpcode() == ISD::TargetGlobalAddress ||
01315              Disp.getOpcode() == ISD::TargetGlobalTLSAddress ||
01316              Disp.getOpcode() == ISD::TargetConstantPool ||
01317              Disp.getOpcode() == ISD::TargetJumpTable);
01318       Base = N.getOperand(0);
01319       return true;  // [&g+r]
01320     }
01321   } else if (N.getOpcode() == ISD::OR) {
01322     short imm = 0;
01323     if (isIntS16Immediate(N.getOperand(1), imm) &&
01324         (!Aligned || (imm & 3) == 0)) {
01325       // If this is an or of disjoint bitfields, we can codegen this as an add
01326       // (for better address arithmetic) if the LHS and RHS of the OR are
01327       // provably disjoint.
01328       APInt LHSKnownZero, LHSKnownOne;
01329       DAG.computeKnownBits(N.getOperand(0), LHSKnownZero, LHSKnownOne);
01330 
01331       if ((LHSKnownZero.getZExtValue()|~(uint64_t)imm) == ~0ULL) {
01332         // If all of the bits are known zero on the LHS or RHS, the add won't
01333         // carry.
01334         if (FrameIndexSDNode *FI =
01335               dyn_cast<FrameIndexSDNode>(N.getOperand(0))) {
01336           Base = DAG.getTargetFrameIndex(FI->getIndex(), N.getValueType());
01337           fixupFuncForFI(DAG, FI->getIndex(), N.getValueType());
01338         } else {
01339           Base = N.getOperand(0);
01340         }
01341         Disp = DAG.getTargetConstant(imm, N.getValueType());
01342         return true;
01343       }
01344     }
01345   } else if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(N)) {
01346     // Loading from a constant address.
01347 
01348     // If this address fits entirely in a 16-bit sext immediate field, codegen
01349     // this as "d, 0"
01350     short Imm;
01351     if (isIntS16Immediate(CN, Imm) && (!Aligned || (Imm & 3) == 0)) {
01352       Disp = DAG.getTargetConstant(Imm, CN->getValueType(0));
01353       Base = DAG.getRegister(Subtarget.isPPC64() ? PPC::ZERO8 : PPC::ZERO,
01354                              CN->getValueType(0));
01355       return true;
01356     }
01357 
01358     // Handle 32-bit sext immediates with LIS + addr mode.
01359     if ((CN->getValueType(0) == MVT::i32 ||
01360          (int64_t)CN->getZExtValue() == (int)CN->getZExtValue()) &&
01361         (!Aligned || (CN->getZExtValue() & 3) == 0)) {
01362       int Addr = (int)CN->getZExtValue();
01363 
01364       // Otherwise, break this down into an LIS + disp.
01365       Disp = DAG.getTargetConstant((short)Addr, MVT::i32);
01366 
01367       Base = DAG.getTargetConstant((Addr - (signed short)Addr) >> 16, MVT::i32);
01368       unsigned Opc = CN->getValueType(0) == MVT::i32 ? PPC::LIS : PPC::LIS8;
01369       Base = SDValue(DAG.getMachineNode(Opc, dl, CN->getValueType(0), Base), 0);
01370       return true;
01371     }
01372   }
01373 
01374   Disp = DAG.getTargetConstant(0, getPointerTy());
01375   if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(N)) {
01376     Base = DAG.getTargetFrameIndex(FI->getIndex(), N.getValueType());
01377     fixupFuncForFI(DAG, FI->getIndex(), N.getValueType());
01378   } else
01379     Base = N;
01380   return true;      // [r+0]
01381 }
01382 
01383 /// SelectAddressRegRegOnly - Given the specified addressed, force it to be
01384 /// represented as an indexed [r+r] operation.
01385 bool PPCTargetLowering::SelectAddressRegRegOnly(SDValue N, SDValue &Base,
01386                                                 SDValue &Index,
01387                                                 SelectionDAG &DAG) const {
01388   // Check to see if we can easily represent this as an [r+r] address.  This
01389   // will fail if it thinks that the address is more profitably represented as
01390   // reg+imm, e.g. where imm = 0.
01391   if (SelectAddressRegReg(N, Base, Index, DAG))
01392     return true;
01393 
01394   // If the operand is an addition, always emit this as [r+r], since this is
01395   // better (for code size, and execution, as the memop does the add for free)
01396   // than emitting an explicit add.
01397   if (N.getOpcode() == ISD::ADD) {
01398     Base = N.getOperand(0);
01399     Index = N.getOperand(1);
01400     return true;
01401   }
01402 
01403   // Otherwise, do it the hard way, using R0 as the base register.
01404   Base = DAG.getRegister(Subtarget.isPPC64() ? PPC::ZERO8 : PPC::ZERO,
01405                          N.getValueType());
01406   Index = N;
01407   return true;
01408 }
01409 
01410 /// getPreIndexedAddressParts - returns true by value, base pointer and
01411 /// offset pointer and addressing mode by reference if the node's address
01412 /// can be legally represented as pre-indexed load / store address.
01413 bool PPCTargetLowering::getPreIndexedAddressParts(SDNode *N, SDValue &Base,
01414                                                   SDValue &Offset,
01415                                                   ISD::MemIndexedMode &AM,
01416                                                   SelectionDAG &DAG) const {
01417   if (DisablePPCPreinc) return false;
01418 
01419   bool isLoad = true;
01420   SDValue Ptr;
01421   EVT VT;
01422   unsigned Alignment;
01423   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
01424     Ptr = LD->getBasePtr();
01425     VT = LD->getMemoryVT();
01426     Alignment = LD->getAlignment();
01427   } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
01428     Ptr = ST->getBasePtr();
01429     VT  = ST->getMemoryVT();
01430     Alignment = ST->getAlignment();
01431     isLoad = false;
01432   } else
01433     return false;
01434 
01435   // PowerPC doesn't have preinc load/store instructions for vectors.
01436   if (VT.isVector())
01437     return false;
01438 
01439   if (SelectAddressRegReg(Ptr, Base, Offset, DAG)) {
01440 
01441     // Common code will reject creating a pre-inc form if the base pointer
01442     // is a frame index, or if N is a store and the base pointer is either
01443     // the same as or a predecessor of the value being stored.  Check for
01444     // those situations here, and try with swapped Base/Offset instead.
01445     bool Swap = false;
01446 
01447     if (isa<FrameIndexSDNode>(Base) || isa<RegisterSDNode>(Base))
01448       Swap = true;
01449     else if (!isLoad) {
01450       SDValue Val = cast<StoreSDNode>(N)->getValue();
01451       if (Val == Base || Base.getNode()->isPredecessorOf(Val.getNode()))
01452         Swap = true;
01453     }
01454 
01455     if (Swap)
01456       std::swap(Base, Offset);
01457 
01458     AM = ISD::PRE_INC;
01459     return true;
01460   }
01461 
01462   // LDU/STU can only handle immediates that are a multiple of 4.
01463   if (VT != MVT::i64) {
01464     if (!SelectAddressRegImm(Ptr, Offset, Base, DAG, false))
01465       return false;
01466   } else {
01467     // LDU/STU need an address with at least 4-byte alignment.
01468     if (Alignment < 4)
01469       return false;
01470 
01471     if (!SelectAddressRegImm(Ptr, Offset, Base, DAG, true))
01472       return false;
01473   }
01474 
01475   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
01476     // PPC64 doesn't have lwau, but it does have lwaux.  Reject preinc load of
01477     // sext i32 to i64 when addr mode is r+i.
01478     if (LD->getValueType(0) == MVT::i64 && LD->getMemoryVT() == MVT::i32 &&
01479         LD->getExtensionType() == ISD::SEXTLOAD &&
01480         isa<ConstantSDNode>(Offset))
01481       return false;
01482   }
01483 
01484   AM = ISD::PRE_INC;
01485   return true;
01486 }
01487 
01488 //===----------------------------------------------------------------------===//
01489 //  LowerOperation implementation
01490 //===----------------------------------------------------------------------===//
01491 
01492 /// GetLabelAccessInfo - Return true if we should reference labels using a
01493 /// PICBase, set the HiOpFlags and LoOpFlags to the target MO flags.
01494 static bool GetLabelAccessInfo(const TargetMachine &TM, unsigned &HiOpFlags,
01495                                unsigned &LoOpFlags,
01496                                const GlobalValue *GV = nullptr) {
01497   HiOpFlags = PPCII::MO_HA;
01498   LoOpFlags = PPCII::MO_LO;
01499 
01500   // Don't use the pic base if not in PIC relocation model.
01501   bool isPIC = TM.getRelocationModel() == Reloc::PIC_;
01502 
01503   if (isPIC) {
01504     HiOpFlags |= PPCII::MO_PIC_FLAG;
01505     LoOpFlags |= PPCII::MO_PIC_FLAG;
01506   }
01507 
01508   // If this is a reference to a global value that requires a non-lazy-ptr, make
01509   // sure that instruction lowering adds it.
01510   if (GV && TM.getSubtarget<PPCSubtarget>().hasLazyResolverStub(GV, TM)) {
01511     HiOpFlags |= PPCII::MO_NLP_FLAG;
01512     LoOpFlags |= PPCII::MO_NLP_FLAG;
01513 
01514     if (GV->hasHiddenVisibility()) {
01515       HiOpFlags |= PPCII::MO_NLP_HIDDEN_FLAG;
01516       LoOpFlags |= PPCII::MO_NLP_HIDDEN_FLAG;
01517     }
01518   }
01519 
01520   return isPIC;
01521 }
01522 
01523 static SDValue LowerLabelRef(SDValue HiPart, SDValue LoPart, bool isPIC,
01524                              SelectionDAG &DAG) {
01525   EVT PtrVT = HiPart.getValueType();
01526   SDValue Zero = DAG.getConstant(0, PtrVT);
01527   SDLoc DL(HiPart);
01528 
01529   SDValue Hi = DAG.getNode(PPCISD::Hi, DL, PtrVT, HiPart, Zero);
01530   SDValue Lo = DAG.getNode(PPCISD::Lo, DL, PtrVT, LoPart, Zero);
01531 
01532   // With PIC, the first instruction is actually "GR+hi(&G)".
01533   if (isPIC)
01534     Hi = DAG.getNode(ISD::ADD, DL, PtrVT,
01535                      DAG.getNode(PPCISD::GlobalBaseReg, DL, PtrVT), Hi);
01536 
01537   // Generate non-pic code that has direct accesses to the constant pool.
01538   // The address of the global is just (hi(&g)+lo(&g)).
01539   return DAG.getNode(ISD::ADD, DL, PtrVT, Hi, Lo);
01540 }
01541 
01542 SDValue PPCTargetLowering::LowerConstantPool(SDValue Op,
01543                                              SelectionDAG &DAG) const {
01544   EVT PtrVT = Op.getValueType();
01545   ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
01546   const Constant *C = CP->getConstVal();
01547 
01548   // 64-bit SVR4 ABI code is always position-independent.
01549   // The actual address of the GlobalValue is stored in the TOC.
01550   if (Subtarget.isSVR4ABI() && Subtarget.isPPC64()) {
01551     SDValue GA = DAG.getTargetConstantPool(C, PtrVT, CP->getAlignment(), 0);
01552     return DAG.getNode(PPCISD::TOC_ENTRY, SDLoc(CP), MVT::i64, GA,
01553                        DAG.getRegister(PPC::X2, MVT::i64));
01554   }
01555 
01556   unsigned MOHiFlag, MOLoFlag;
01557   bool isPIC = GetLabelAccessInfo(DAG.getTarget(), MOHiFlag, MOLoFlag);
01558 
01559   if (isPIC && Subtarget.isSVR4ABI()) {
01560     SDValue GA = DAG.getTargetConstantPool(C, PtrVT, CP->getAlignment(),
01561                                            PPCII::MO_PIC_FLAG);
01562     SDLoc DL(CP);
01563     return DAG.getNode(PPCISD::TOC_ENTRY, DL, MVT::i32, GA,
01564                        DAG.getNode(PPCISD::GlobalBaseReg, DL, PtrVT));
01565   }
01566 
01567   SDValue CPIHi =
01568     DAG.getTargetConstantPool(C, PtrVT, CP->getAlignment(), 0, MOHiFlag);
01569   SDValue CPILo =
01570     DAG.getTargetConstantPool(C, PtrVT, CP->getAlignment(), 0, MOLoFlag);
01571   return LowerLabelRef(CPIHi, CPILo, isPIC, DAG);
01572 }
01573 
01574 SDValue PPCTargetLowering::LowerJumpTable(SDValue Op, SelectionDAG &DAG) const {
01575   EVT PtrVT = Op.getValueType();
01576   JumpTableSDNode *JT = cast<JumpTableSDNode>(Op);
01577 
01578   // 64-bit SVR4 ABI code is always position-independent.
01579   // The actual address of the GlobalValue is stored in the TOC.
01580   if (Subtarget.isSVR4ABI() && Subtarget.isPPC64()) {
01581     SDValue GA = DAG.getTargetJumpTable(JT->getIndex(), PtrVT);
01582     return DAG.getNode(PPCISD::TOC_ENTRY, SDLoc(JT), MVT::i64, GA,
01583                        DAG.getRegister(PPC::X2, MVT::i64));
01584   }
01585 
01586   unsigned MOHiFlag, MOLoFlag;
01587   bool isPIC = GetLabelAccessInfo(DAG.getTarget(), MOHiFlag, MOLoFlag);
01588 
01589   if (isPIC && Subtarget.isSVR4ABI()) {
01590     SDValue GA = DAG.getTargetJumpTable(JT->getIndex(), PtrVT,
01591                                         PPCII::MO_PIC_FLAG);
01592     SDLoc DL(GA);
01593     return DAG.getNode(PPCISD::TOC_ENTRY, SDLoc(JT), PtrVT, GA,
01594                        DAG.getNode(PPCISD::GlobalBaseReg, DL, PtrVT));
01595   }
01596 
01597   SDValue JTIHi = DAG.getTargetJumpTable(JT->getIndex(), PtrVT, MOHiFlag);
01598   SDValue JTILo = DAG.getTargetJumpTable(JT->getIndex(), PtrVT, MOLoFlag);
01599   return LowerLabelRef(JTIHi, JTILo, isPIC, DAG);
01600 }
01601 
01602 SDValue PPCTargetLowering::LowerBlockAddress(SDValue Op,
01603                                              SelectionDAG &DAG) const {
01604   EVT PtrVT = Op.getValueType();
01605 
01606   const BlockAddress *BA = cast<BlockAddressSDNode>(Op)->getBlockAddress();
01607 
01608   unsigned MOHiFlag, MOLoFlag;
01609   bool isPIC = GetLabelAccessInfo(DAG.getTarget(), MOHiFlag, MOLoFlag);
01610   SDValue TgtBAHi = DAG.getTargetBlockAddress(BA, PtrVT, 0, MOHiFlag);
01611   SDValue TgtBALo = DAG.getTargetBlockAddress(BA, PtrVT, 0, MOLoFlag);
01612   return LowerLabelRef(TgtBAHi, TgtBALo, isPIC, DAG);
01613 }
01614 
01615 SDValue PPCTargetLowering::LowerGlobalTLSAddress(SDValue Op,
01616                                               SelectionDAG &DAG) const {
01617 
01618   // FIXME: TLS addresses currently use medium model code sequences,
01619   // which is the most useful form.  Eventually support for small and
01620   // large models could be added if users need it, at the cost of
01621   // additional complexity.
01622   GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
01623   SDLoc dl(GA);
01624   const GlobalValue *GV = GA->getGlobal();
01625   EVT PtrVT = getPointerTy();
01626   bool is64bit = Subtarget.isPPC64();
01627 
01628   TLSModel::Model Model = getTargetMachine().getTLSModel(GV);
01629 
01630   if (Model == TLSModel::LocalExec) {
01631     SDValue TGAHi = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0,
01632                                                PPCII::MO_TPREL_HA);
01633     SDValue TGALo = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0,
01634                                                PPCII::MO_TPREL_LO);
01635     SDValue TLSReg = DAG.getRegister(is64bit ? PPC::X13 : PPC::R2,
01636                                      is64bit ? MVT::i64 : MVT::i32);
01637     SDValue Hi = DAG.getNode(PPCISD::Hi, dl, PtrVT, TGAHi, TLSReg);
01638     return DAG.getNode(PPCISD::Lo, dl, PtrVT, TGALo, Hi);
01639   }
01640 
01641   if (Model == TLSModel::InitialExec) {
01642     SDValue TGA = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, 0);
01643     SDValue TGATLS = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0,
01644                                                 PPCII::MO_TLS);
01645     SDValue GOTPtr;
01646     if (is64bit) {
01647       SDValue GOTReg = DAG.getRegister(PPC::X2, MVT::i64);
01648       GOTPtr = DAG.getNode(PPCISD::ADDIS_GOT_TPREL_HA, dl,
01649                            PtrVT, GOTReg, TGA);
01650     } else
01651       GOTPtr = DAG.getNode(PPCISD::PPC32_GOT, dl, PtrVT);
01652     SDValue TPOffset = DAG.getNode(PPCISD::LD_GOT_TPREL_L, dl,
01653                                    PtrVT, TGA, GOTPtr);
01654     return DAG.getNode(PPCISD::ADD_TLS, dl, PtrVT, TPOffset, TGATLS);
01655   }
01656 
01657   if (Model == TLSModel::GeneralDynamic) {
01658     SDValue TGA = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, 0);
01659     SDValue GOTReg = DAG.getRegister(PPC::X2, MVT::i64);
01660     SDValue GOTEntryHi = DAG.getNode(PPCISD::ADDIS_TLSGD_HA, dl, PtrVT,
01661                                      GOTReg, TGA);
01662     SDValue GOTEntry = DAG.getNode(PPCISD::ADDI_TLSGD_L, dl, PtrVT,
01663                                    GOTEntryHi, TGA);
01664 
01665     // We need a chain node, and don't have one handy.  The underlying
01666     // call has no side effects, so using the function entry node
01667     // suffices.
01668     SDValue Chain = DAG.getEntryNode();
01669     Chain = DAG.getCopyToReg(Chain, dl, PPC::X3, GOTEntry);
01670     SDValue ParmReg = DAG.getRegister(PPC::X3, MVT::i64);
01671     SDValue TLSAddr = DAG.getNode(PPCISD::GET_TLS_ADDR, dl,
01672                                   PtrVT, ParmReg, TGA);
01673     // The return value from GET_TLS_ADDR really is in X3 already, but
01674     // some hacks are needed here to tie everything together.  The extra
01675     // copies dissolve during subsequent transforms.
01676     Chain = DAG.getCopyToReg(Chain, dl, PPC::X3, TLSAddr);
01677     return DAG.getCopyFromReg(Chain, dl, PPC::X3, PtrVT);
01678   }
01679 
01680   if (Model == TLSModel::LocalDynamic) {
01681     SDValue TGA = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, 0);
01682     SDValue GOTReg = DAG.getRegister(PPC::X2, MVT::i64);
01683     SDValue GOTEntryHi = DAG.getNode(PPCISD::ADDIS_TLSLD_HA, dl, PtrVT,
01684                                      GOTReg, TGA);
01685     SDValue GOTEntry = DAG.getNode(PPCISD::ADDI_TLSLD_L, dl, PtrVT,
01686                                    GOTEntryHi, TGA);
01687 
01688     // We need a chain node, and don't have one handy.  The underlying
01689     // call has no side effects, so using the function entry node
01690     // suffices.
01691     SDValue Chain = DAG.getEntryNode();
01692     Chain = DAG.getCopyToReg(Chain, dl, PPC::X3, GOTEntry);
01693     SDValue ParmReg = DAG.getRegister(PPC::X3, MVT::i64);
01694     SDValue TLSAddr = DAG.getNode(PPCISD::GET_TLSLD_ADDR, dl,
01695                                   PtrVT, ParmReg, TGA);
01696     // The return value from GET_TLSLD_ADDR really is in X3 already, but
01697     // some hacks are needed here to tie everything together.  The extra
01698     // copies dissolve during subsequent transforms.
01699     Chain = DAG.getCopyToReg(Chain, dl, PPC::X3, TLSAddr);
01700     SDValue DtvOffsetHi = DAG.getNode(PPCISD::ADDIS_DTPREL_HA, dl, PtrVT,
01701                                       Chain, ParmReg, TGA);
01702     return DAG.getNode(PPCISD::ADDI_DTPREL_L, dl, PtrVT, DtvOffsetHi, TGA);
01703   }
01704 
01705   llvm_unreachable("Unknown TLS model!");
01706 }
01707 
01708 SDValue PPCTargetLowering::LowerGlobalAddress(SDValue Op,
01709                                               SelectionDAG &DAG) const {
01710   EVT PtrVT = Op.getValueType();
01711   GlobalAddressSDNode *GSDN = cast<GlobalAddressSDNode>(Op);
01712   SDLoc DL(GSDN);
01713   const GlobalValue *GV = GSDN->getGlobal();
01714 
01715   // 64-bit SVR4 ABI code is always position-independent.
01716   // The actual address of the GlobalValue is stored in the TOC.
01717   if (Subtarget.isSVR4ABI() && Subtarget.isPPC64()) {
01718     SDValue GA = DAG.getTargetGlobalAddress(GV, DL, PtrVT, GSDN->getOffset());
01719     return DAG.getNode(PPCISD::TOC_ENTRY, DL, MVT::i64, GA,
01720                        DAG.getRegister(PPC::X2, MVT::i64));
01721   }
01722 
01723   unsigned MOHiFlag, MOLoFlag;
01724   bool isPIC = GetLabelAccessInfo(DAG.getTarget(), MOHiFlag, MOLoFlag, GV);
01725 
01726   if (isPIC && Subtarget.isSVR4ABI()) {
01727     SDValue GA = DAG.getTargetGlobalAddress(GV, DL, PtrVT,
01728                                             GSDN->getOffset(),
01729                                             PPCII::MO_PIC_FLAG);
01730     return DAG.getNode(PPCISD::TOC_ENTRY, DL, MVT::i32, GA,
01731                        DAG.getNode(PPCISD::GlobalBaseReg, DL, MVT::i32));
01732   }
01733 
01734   SDValue GAHi =
01735     DAG.getTargetGlobalAddress(GV, DL, PtrVT, GSDN->getOffset(), MOHiFlag);
01736   SDValue GALo =
01737     DAG.getTargetGlobalAddress(GV, DL, PtrVT, GSDN->getOffset(), MOLoFlag);
01738 
01739   SDValue Ptr = LowerLabelRef(GAHi, GALo, isPIC, DAG);
01740 
01741   // If the global reference is actually to a non-lazy-pointer, we have to do an
01742   // extra load to get the address of the global.
01743   if (MOHiFlag & PPCII::MO_NLP_FLAG)
01744     Ptr = DAG.getLoad(PtrVT, DL, DAG.getEntryNode(), Ptr, MachinePointerInfo(),
01745                       false, false, false, 0);
01746   return Ptr;
01747 }
01748 
01749 SDValue PPCTargetLowering::LowerSETCC(SDValue Op, SelectionDAG &DAG) const {
01750   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
01751   SDLoc dl(Op);
01752 
01753   if (Op.getValueType() == MVT::v2i64) {
01754     // When the operands themselves are v2i64 values, we need to do something
01755     // special because VSX has no underlying comparison operations for these.
01756     if (Op.getOperand(0).getValueType() == MVT::v2i64) {
01757       // Equality can be handled by casting to the legal type for Altivec
01758       // comparisons, everything else needs to be expanded.
01759       if (CC == ISD::SETEQ || CC == ISD::SETNE) {
01760         return DAG.getNode(ISD::BITCAST, dl, MVT::v2i64,
01761                  DAG.getSetCC(dl, MVT::v4i32,
01762                    DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op.getOperand(0)),
01763                    DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op.getOperand(1)),
01764                    CC));
01765       }
01766 
01767       return SDValue();
01768     }
01769 
01770     // We handle most of these in the usual way.
01771     return Op;
01772   }
01773 
01774   // If we're comparing for equality to zero, expose the fact that this is
01775   // implented as a ctlz/srl pair on ppc, so that the dag combiner can
01776   // fold the new nodes.
01777   if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
01778     if (C->isNullValue() && CC == ISD::SETEQ) {
01779       EVT VT = Op.getOperand(0).getValueType();
01780       SDValue Zext = Op.getOperand(0);
01781       if (VT.bitsLT(MVT::i32)) {
01782         VT = MVT::i32;
01783         Zext = DAG.getNode(ISD::ZERO_EXTEND, dl, VT, Op.getOperand(0));
01784       }
01785       unsigned Log2b = Log2_32(VT.getSizeInBits());
01786       SDValue Clz = DAG.getNode(ISD::CTLZ, dl, VT, Zext);
01787       SDValue Scc = DAG.getNode(ISD::SRL, dl, VT, Clz,
01788                                 DAG.getConstant(Log2b, MVT::i32));
01789       return DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, Scc);
01790     }
01791     // Leave comparisons against 0 and -1 alone for now, since they're usually
01792     // optimized.  FIXME: revisit this when we can custom lower all setcc
01793     // optimizations.
01794     if (C->isAllOnesValue() || C->isNullValue())
01795       return SDValue();
01796   }
01797 
01798   // If we have an integer seteq/setne, turn it into a compare against zero
01799   // by xor'ing the rhs with the lhs, which is faster than setting a
01800   // condition register, reading it back out, and masking the correct bit.  The
01801   // normal approach here uses sub to do this instead of xor.  Using xor exposes
01802   // the result to other bit-twiddling opportunities.
01803   EVT LHSVT = Op.getOperand(0).getValueType();
01804   if (LHSVT.isInteger() && (CC == ISD::SETEQ || CC == ISD::SETNE)) {
01805     EVT VT = Op.getValueType();
01806     SDValue Sub = DAG.getNode(ISD::XOR, dl, LHSVT, Op.getOperand(0),
01807                                 Op.getOperand(1));
01808     return DAG.getSetCC(dl, VT, Sub, DAG.getConstant(0, LHSVT), CC);
01809   }
01810   return SDValue();
01811 }
01812 
01813 SDValue PPCTargetLowering::LowerVAARG(SDValue Op, SelectionDAG &DAG,
01814                                       const PPCSubtarget &Subtarget) const {
01815   SDNode *Node = Op.getNode();
01816   EVT VT = Node->getValueType(0);
01817   EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
01818   SDValue InChain = Node->getOperand(0);
01819   SDValue VAListPtr = Node->getOperand(1);
01820   const Value *SV = cast<SrcValueSDNode>(Node->getOperand(2))->getValue();
01821   SDLoc dl(Node);
01822 
01823   assert(!Subtarget.isPPC64() && "LowerVAARG is PPC32 only");
01824 
01825   // gpr_index
01826   SDValue GprIndex = DAG.getExtLoad(ISD::ZEXTLOAD, dl, MVT::i32, InChain,
01827                                     VAListPtr, MachinePointerInfo(SV), MVT::i8,
01828                                     false, false, 0);
01829   InChain = GprIndex.getValue(1);
01830 
01831   if (VT == MVT::i64) {
01832     // Check if GprIndex is even
01833     SDValue GprAnd = DAG.getNode(ISD::AND, dl, MVT::i32, GprIndex,
01834                                  DAG.getConstant(1, MVT::i32));
01835     SDValue CC64 = DAG.getSetCC(dl, MVT::i32, GprAnd,
01836                                 DAG.getConstant(0, MVT::i32), ISD::SETNE);
01837     SDValue GprIndexPlusOne = DAG.getNode(ISD::ADD, dl, MVT::i32, GprIndex,
01838                                           DAG.getConstant(1, MVT::i32));
01839     // Align GprIndex to be even if it isn't
01840     GprIndex = DAG.getNode(ISD::SELECT, dl, MVT::i32, CC64, GprIndexPlusOne,
01841                            GprIndex);
01842   }
01843 
01844   // fpr index is 1 byte after gpr
01845   SDValue FprPtr = DAG.getNode(ISD::ADD, dl, PtrVT, VAListPtr,
01846                                DAG.getConstant(1, MVT::i32));
01847 
01848   // fpr
01849   SDValue FprIndex = DAG.getExtLoad(ISD::ZEXTLOAD, dl, MVT::i32, InChain,
01850                                     FprPtr, MachinePointerInfo(SV), MVT::i8,
01851                                     false, false, 0);
01852   InChain = FprIndex.getValue(1);
01853 
01854   SDValue RegSaveAreaPtr = DAG.getNode(ISD::ADD, dl, PtrVT, VAListPtr,
01855                                        DAG.getConstant(8, MVT::i32));
01856 
01857   SDValue OverflowAreaPtr = DAG.getNode(ISD::ADD, dl, PtrVT, VAListPtr,
01858                                         DAG.getConstant(4, MVT::i32));
01859 
01860   // areas
01861   SDValue OverflowArea = DAG.getLoad(MVT::i32, dl, InChain, OverflowAreaPtr,
01862                                      MachinePointerInfo(), false, false,
01863                                      false, 0);
01864   InChain = OverflowArea.getValue(1);
01865 
01866   SDValue RegSaveArea = DAG.getLoad(MVT::i32, dl, InChain, RegSaveAreaPtr,
01867                                     MachinePointerInfo(), false, false,
01868                                     false, 0);
01869   InChain = RegSaveArea.getValue(1);
01870 
01871   // select overflow_area if index > 8
01872   SDValue CC = DAG.getSetCC(dl, MVT::i32, VT.isInteger() ? GprIndex : FprIndex,
01873                             DAG.getConstant(8, MVT::i32), ISD::SETLT);
01874 
01875   // adjustment constant gpr_index * 4/8
01876   SDValue RegConstant = DAG.getNode(ISD::MUL, dl, MVT::i32,
01877                                     VT.isInteger() ? GprIndex : FprIndex,
01878                                     DAG.getConstant(VT.isInteger() ? 4 : 8,
01879                                                     MVT::i32));
01880 
01881   // OurReg = RegSaveArea + RegConstant
01882   SDValue OurReg = DAG.getNode(ISD::ADD, dl, PtrVT, RegSaveArea,
01883                                RegConstant);
01884 
01885   // Floating types are 32 bytes into RegSaveArea
01886   if (VT.isFloatingPoint())
01887     OurReg = DAG.getNode(ISD::ADD, dl, PtrVT, OurReg,
01888                          DAG.getConstant(32, MVT::i32));
01889 
01890   // increase {f,g}pr_index by 1 (or 2 if VT is i64)
01891   SDValue IndexPlus1 = DAG.getNode(ISD::ADD, dl, MVT::i32,
01892                                    VT.isInteger() ? GprIndex : FprIndex,
01893                                    DAG.getConstant(VT == MVT::i64 ? 2 : 1,
01894                                                    MVT::i32));
01895 
01896   InChain = DAG.getTruncStore(InChain, dl, IndexPlus1,
01897                               VT.isInteger() ? VAListPtr : FprPtr,
01898                               MachinePointerInfo(SV),
01899                               MVT::i8, false, false, 0);
01900 
01901   // determine if we should load from reg_save_area or overflow_area
01902   SDValue Result = DAG.getNode(ISD::SELECT, dl, PtrVT, CC, OurReg, OverflowArea);
01903 
01904   // increase overflow_area by 4/8 if gpr/fpr > 8
01905   SDValue OverflowAreaPlusN = DAG.getNode(ISD::ADD, dl, PtrVT, OverflowArea,
01906                                           DAG.getConstant(VT.isInteger() ? 4 : 8,
01907                                           MVT::i32));
01908 
01909   OverflowArea = DAG.getNode(ISD::SELECT, dl, MVT::i32, CC, OverflowArea,
01910                              OverflowAreaPlusN);
01911 
01912   InChain = DAG.getTruncStore(InChain, dl, OverflowArea,
01913                               OverflowAreaPtr,
01914                               MachinePointerInfo(),
01915                               MVT::i32, false, false, 0);
01916 
01917   return DAG.getLoad(VT, dl, InChain, Result, MachinePointerInfo(),
01918                      false, false, false, 0);
01919 }
01920 
01921 SDValue PPCTargetLowering::LowerVACOPY(SDValue Op, SelectionDAG &DAG,
01922                                        const PPCSubtarget &Subtarget) const {
01923   assert(!Subtarget.isPPC64() && "LowerVACOPY is PPC32 only");
01924 
01925   // We have to copy the entire va_list struct:
01926   // 2*sizeof(char) + 2 Byte alignment + 2*sizeof(char*) = 12 Byte
01927   return DAG.getMemcpy(Op.getOperand(0), Op,
01928                        Op.getOperand(1), Op.getOperand(2),
01929                        DAG.getConstant(12, MVT::i32), 8, false, true,
01930                        MachinePointerInfo(), MachinePointerInfo());
01931 }
01932 
01933 SDValue PPCTargetLowering::LowerADJUST_TRAMPOLINE(SDValue Op,
01934                                                   SelectionDAG &DAG) const {
01935   return Op.getOperand(0);
01936 }
01937 
01938 SDValue PPCTargetLowering::LowerINIT_TRAMPOLINE(SDValue Op,
01939                                                 SelectionDAG &DAG) const {
01940   SDValue Chain = Op.getOperand(0);
01941   SDValue Trmp = Op.getOperand(1); // trampoline
01942   SDValue FPtr = Op.getOperand(2); // nested function
01943   SDValue Nest = Op.getOperand(3); // 'nest' parameter value
01944   SDLoc dl(Op);
01945 
01946   EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
01947   bool isPPC64 = (PtrVT == MVT::i64);
01948   Type *IntPtrTy =
01949     DAG.getTargetLoweringInfo().getDataLayout()->getIntPtrType(
01950                                                              *DAG.getContext());
01951 
01952   TargetLowering::ArgListTy Args;
01953   TargetLowering::ArgListEntry Entry;
01954 
01955   Entry.Ty = IntPtrTy;
01956   Entry.Node = Trmp; Args.push_back(Entry);
01957 
01958   // TrampSize == (isPPC64 ? 48 : 40);
01959   Entry.Node = DAG.getConstant(isPPC64 ? 48 : 40,
01960                                isPPC64 ? MVT::i64 : MVT::i32);
01961   Args.push_back(Entry);
01962 
01963   Entry.Node = FPtr; Args.push_back(Entry);
01964   Entry.Node = Nest; Args.push_back(Entry);
01965 
01966   // Lower to a call to __trampoline_setup(Trmp, TrampSize, FPtr, ctx_reg)
01967   TargetLowering::CallLoweringInfo CLI(DAG);
01968   CLI.setDebugLoc(dl).setChain(Chain)
01969     .setCallee(CallingConv::C, Type::getVoidTy(*DAG.getContext()),
01970                DAG.getExternalSymbol("__trampoline_setup", PtrVT),
01971                std::move(Args), 0);
01972 
01973   std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI);
01974   return CallResult.second;
01975 }
01976 
01977 SDValue PPCTargetLowering::LowerVASTART(SDValue Op, SelectionDAG &DAG,
01978                                         const PPCSubtarget &Subtarget) const {
01979   MachineFunction &MF = DAG.getMachineFunction();
01980   PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
01981 
01982   SDLoc dl(Op);
01983 
01984   if (Subtarget.isDarwinABI() || Subtarget.isPPC64()) {
01985     // vastart just stores the address of the VarArgsFrameIndex slot into the
01986     // memory location argument.
01987     EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
01988     SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT);
01989     const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
01990     return DAG.getStore(Op.getOperand(0), dl, FR, Op.getOperand(1),
01991                         MachinePointerInfo(SV),
01992                         false, false, 0);
01993   }
01994 
01995   // For the 32-bit SVR4 ABI we follow the layout of the va_list struct.
01996   // We suppose the given va_list is already allocated.
01997   //
01998   // typedef struct {
01999   //  char gpr;     /* index into the array of 8 GPRs
02000   //                 * stored in the register save area
02001   //                 * gpr=0 corresponds to r3,
02002   //                 * gpr=1 to r4, etc.
02003   //                 */
02004   //  char fpr;     /* index into the array of 8 FPRs
02005   //                 * stored in the register save area
02006   //                 * fpr=0 corresponds to f1,
02007   //                 * fpr=1 to f2, etc.
02008   //                 */
02009   //  char *overflow_arg_area;
02010   //                /* location on stack that holds
02011   //                 * the next overflow argument
02012   //                 */
02013   //  char *reg_save_area;
02014   //               /* where r3:r10 and f1:f8 (if saved)
02015   //                * are stored
02016   //                */
02017   // } va_list[1];
02018 
02019 
02020   SDValue ArgGPR = DAG.getConstant(FuncInfo->getVarArgsNumGPR(), MVT::i32);
02021   SDValue ArgFPR = DAG.getConstant(FuncInfo->getVarArgsNumFPR(), MVT::i32);
02022 
02023 
02024   EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
02025 
02026   SDValue StackOffsetFI = DAG.getFrameIndex(FuncInfo->getVarArgsStackOffset(),
02027                                             PtrVT);
02028   SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
02029                                  PtrVT);
02030 
02031   uint64_t FrameOffset = PtrVT.getSizeInBits()/8;
02032   SDValue ConstFrameOffset = DAG.getConstant(FrameOffset, PtrVT);
02033 
02034   uint64_t StackOffset = PtrVT.getSizeInBits()/8 - 1;
02035   SDValue ConstStackOffset = DAG.getConstant(StackOffset, PtrVT);
02036 
02037   uint64_t FPROffset = 1;
02038   SDValue ConstFPROffset = DAG.getConstant(FPROffset, PtrVT);
02039 
02040   const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
02041 
02042   // Store first byte : number of int regs
02043   SDValue firstStore = DAG.getTruncStore(Op.getOperand(0), dl, ArgGPR,
02044                                          Op.getOperand(1),
02045                                          MachinePointerInfo(SV),
02046                                          MVT::i8, false, false, 0);
02047   uint64_t nextOffset = FPROffset;
02048   SDValue nextPtr = DAG.getNode(ISD::ADD, dl, PtrVT, Op.getOperand(1),
02049                                   ConstFPROffset);
02050 
02051   // Store second byte : number of float regs
02052   SDValue secondStore =
02053     DAG.getTruncStore(firstStore, dl, ArgFPR, nextPtr,
02054                       MachinePointerInfo(SV, nextOffset), MVT::i8,
02055                       false, false, 0);
02056   nextOffset += StackOffset;
02057   nextPtr = DAG.getNode(ISD::ADD, dl, PtrVT, nextPtr, ConstStackOffset);
02058 
02059   // Store second word : arguments given on stack
02060   SDValue thirdStore =
02061     DAG.getStore(secondStore, dl, StackOffsetFI, nextPtr,
02062                  MachinePointerInfo(SV, nextOffset),
02063                  false, false, 0);
02064   nextOffset += FrameOffset;
02065   nextPtr = DAG.getNode(ISD::ADD, dl, PtrVT, nextPtr, ConstFrameOffset);
02066 
02067   // Store third word : arguments given in registers
02068   return DAG.getStore(thirdStore, dl, FR, nextPtr,
02069                       MachinePointerInfo(SV, nextOffset),
02070                       false, false, 0);
02071 
02072 }
02073 
02074 #include "PPCGenCallingConv.inc"
02075 
02076 // Function whose sole purpose is to kill compiler warnings 
02077 // stemming from unused functions included from PPCGenCallingConv.inc.
02078 CCAssignFn *PPCTargetLowering::useFastISelCCs(unsigned Flag) const {
02079   return Flag ? CC_PPC64_ELF_FIS : RetCC_PPC64_ELF_FIS;
02080 }
02081 
02082 bool llvm::CC_PPC32_SVR4_Custom_Dummy(unsigned &ValNo, MVT &ValVT, MVT &LocVT,
02083                                       CCValAssign::LocInfo &LocInfo,
02084                                       ISD::ArgFlagsTy &ArgFlags,
02085                                       CCState &State) {
02086   return true;
02087 }
02088 
02089 bool llvm::CC_PPC32_SVR4_Custom_AlignArgRegs(unsigned &ValNo, MVT &ValVT,
02090                                              MVT &LocVT,
02091                                              CCValAssign::LocInfo &LocInfo,
02092                                              ISD::ArgFlagsTy &ArgFlags,
02093                                              CCState &State) {
02094   static const MCPhysReg ArgRegs[] = {
02095     PPC::R3, PPC::R4, PPC::R5, PPC::R6,
02096     PPC::R7, PPC::R8, PPC::R9, PPC::R10,
02097   };
02098   const unsigned NumArgRegs = array_lengthof(ArgRegs);
02099 
02100   unsigned RegNum = State.getFirstUnallocated(ArgRegs, NumArgRegs);
02101 
02102   // Skip one register if the first unallocated register has an even register
02103   // number and there are still argument registers available which have not been
02104   // allocated yet. RegNum is actually an index into ArgRegs, which means we
02105   // need to skip a register if RegNum is odd.
02106   if (RegNum != NumArgRegs && RegNum % 2 == 1) {
02107     State.AllocateReg(ArgRegs[RegNum]);
02108   }
02109 
02110   // Always return false here, as this function only makes sure that the first
02111   // unallocated register has an odd register number and does not actually
02112   // allocate a register for the current argument.
02113   return false;
02114 }
02115 
02116 bool llvm::CC_PPC32_SVR4_Custom_AlignFPArgRegs(unsigned &ValNo, MVT &ValVT,
02117                                                MVT &LocVT,
02118                                                CCValAssign::LocInfo &LocInfo,
02119                                                ISD::ArgFlagsTy &ArgFlags,
02120                                                CCState &State) {
02121   static const MCPhysReg ArgRegs[] = {
02122     PPC::F1, PPC::F2, PPC::F3, PPC::F4, PPC::F5, PPC::F6, PPC::F7,
02123     PPC::F8
02124   };
02125 
02126   const unsigned NumArgRegs = array_lengthof(ArgRegs);
02127 
02128   unsigned RegNum = State.getFirstUnallocated(ArgRegs, NumArgRegs);
02129 
02130   // If there is only one Floating-point register left we need to put both f64
02131   // values of a split ppc_fp128 value on the stack.
02132   if (RegNum != NumArgRegs && ArgRegs[RegNum] == PPC::F8) {
02133     State.AllocateReg(ArgRegs[RegNum]);
02134   }
02135 
02136   // Always return false here, as this function only makes sure that the two f64
02137   // values a ppc_fp128 value is split into are both passed in registers or both
02138   // passed on the stack and does not actually allocate a register for the
02139   // current argument.
02140   return false;
02141 }
02142 
02143 /// GetFPR - Get the set of FP registers that should be allocated for arguments,
02144 /// on Darwin.
02145 static const MCPhysReg *GetFPR() {
02146   static const MCPhysReg FPR[] = {
02147     PPC::F1, PPC::F2, PPC::F3, PPC::F4, PPC::F5, PPC::F6, PPC::F7,
02148     PPC::F8, PPC::F9, PPC::F10, PPC::F11, PPC::F12, PPC::F13
02149   };
02150 
02151   return FPR;
02152 }
02153 
02154 /// CalculateStackSlotSize - Calculates the size reserved for this argument on
02155 /// the stack.
02156 static unsigned CalculateStackSlotSize(EVT ArgVT, ISD::ArgFlagsTy Flags,
02157                                        unsigned PtrByteSize) {
02158   unsigned ArgSize = ArgVT.getStoreSize();
02159   if (Flags.isByVal())
02160     ArgSize = Flags.getByValSize();
02161 
02162   // Round up to multiples of the pointer size, except for array members,
02163   // which are always packed.
02164   if (!Flags.isInConsecutiveRegs())
02165     ArgSize = ((ArgSize + PtrByteSize - 1)/PtrByteSize) * PtrByteSize;
02166 
02167   return ArgSize;
02168 }
02169 
02170 /// CalculateStackSlotAlignment - Calculates the alignment of this argument
02171 /// on the stack.
02172 static unsigned CalculateStackSlotAlignment(EVT ArgVT, EVT OrigVT,
02173                                             ISD::ArgFlagsTy Flags,
02174                                             unsigned PtrByteSize) {
02175   unsigned Align = PtrByteSize;
02176 
02177   // Altivec parameters are padded to a 16 byte boundary.
02178   if (ArgVT == MVT::v4f32 || ArgVT == MVT::v4i32 ||
02179       ArgVT == MVT::v8i16 || ArgVT == MVT::v16i8 ||
02180       ArgVT == MVT::v2f64 || ArgVT == MVT::v2i64)
02181     Align = 16;
02182 
02183   // ByVal parameters are aligned as requested.
02184   if (Flags.isByVal()) {
02185     unsigned BVAlign = Flags.getByValAlign();
02186     if (BVAlign > PtrByteSize) {
02187       if (BVAlign % PtrByteSize != 0)
02188           llvm_unreachable(
02189             "ByVal alignment is not a multiple of the pointer size");
02190 
02191       Align = BVAlign;
02192     }
02193   }
02194 
02195   // Array members are always packed to their original alignment.
02196   if (Flags.isInConsecutiveRegs()) {
02197     // If the array member was split into multiple registers, the first
02198     // needs to be aligned to the size of the full type.  (Except for
02199     // ppcf128, which is only aligned as its f64 components.)
02200     if (Flags.isSplit() && OrigVT != MVT::ppcf128)
02201       Align = OrigVT.getStoreSize();
02202     else
02203       Align = ArgVT.getStoreSize();
02204   }
02205 
02206   return Align;
02207 }
02208 
02209 /// CalculateStackSlotUsed - Return whether this argument will use its
02210 /// stack slot (instead of being passed in registers).  ArgOffset,
02211 /// AvailableFPRs, and AvailableVRs must hold the current argument
02212 /// position, and will be updated to account for this argument.
02213 static bool CalculateStackSlotUsed(EVT ArgVT, EVT OrigVT,
02214                                    ISD::ArgFlagsTy Flags,
02215                                    unsigned PtrByteSize,
02216                                    unsigned LinkageSize,
02217                                    unsigned ParamAreaSize,
02218                                    unsigned &ArgOffset,
02219                                    unsigned &AvailableFPRs,
02220                                    unsigned &AvailableVRs) {
02221   bool UseMemory = false;
02222 
02223   // Respect alignment of argument on the stack.
02224   unsigned Align =
02225     CalculateStackSlotAlignment(ArgVT, OrigVT, Flags, PtrByteSize);
02226   ArgOffset = ((ArgOffset + Align - 1) / Align) * Align;
02227   // If there's no space left in the argument save area, we must
02228   // use memory (this check also catches zero-sized arguments).
02229   if (ArgOffset >= LinkageSize + ParamAreaSize)
02230     UseMemory = true;
02231 
02232   // Allocate argument on the stack.
02233   ArgOffset += CalculateStackSlotSize(ArgVT, Flags, PtrByteSize);
02234   if (Flags.isInConsecutiveRegsLast())
02235     ArgOffset = ((ArgOffset + PtrByteSize - 1)/PtrByteSize) * PtrByteSize;
02236   // If we overran the argument save area, we must use memory
02237   // (this check catches arguments passed partially in memory)
02238   if (ArgOffset > LinkageSize + ParamAreaSize)
02239     UseMemory = true;
02240 
02241   // However, if the argument is actually passed in an FPR or a VR,
02242   // we don't use memory after all.
02243   if (!Flags.isByVal()) {
02244     if (ArgVT == MVT::f32 || ArgVT == MVT::f64)
02245       if (AvailableFPRs > 0) {
02246         --AvailableFPRs;
02247         return false;
02248       }
02249     if (ArgVT == MVT::v4f32 || ArgVT == MVT::v4i32 ||
02250         ArgVT == MVT::v8i16 || ArgVT == MVT::v16i8 ||
02251         ArgVT == MVT::v2f64 || ArgVT == MVT::v2i64)
02252       if (AvailableVRs > 0) {
02253         --AvailableVRs;
02254         return false;
02255       }
02256   }
02257 
02258   return UseMemory;
02259 }
02260 
02261 /// EnsureStackAlignment - Round stack frame size up from NumBytes to
02262 /// ensure minimum alignment required for target.
02263 static unsigned EnsureStackAlignment(const TargetMachine &Target,
02264                                      unsigned NumBytes) {
02265   unsigned TargetAlign = Target.getFrameLowering()->getStackAlignment();
02266   unsigned AlignMask = TargetAlign - 1;
02267   NumBytes = (NumBytes + AlignMask) & ~AlignMask;
02268   return NumBytes;
02269 }
02270 
02271 SDValue
02272 PPCTargetLowering::LowerFormalArguments(SDValue Chain,
02273                                         CallingConv::ID CallConv, bool isVarArg,
02274                                         const SmallVectorImpl<ISD::InputArg>
02275                                           &Ins,
02276                                         SDLoc dl, SelectionDAG &DAG,
02277                                         SmallVectorImpl<SDValue> &InVals)
02278                                           const {
02279   if (Subtarget.isSVR4ABI()) {
02280     if (Subtarget.isPPC64())
02281       return LowerFormalArguments_64SVR4(Chain, CallConv, isVarArg, Ins,
02282                                          dl, DAG, InVals);
02283     else
02284       return LowerFormalArguments_32SVR4(Chain, CallConv, isVarArg, Ins,
02285                                          dl, DAG, InVals);
02286   } else {
02287     return LowerFormalArguments_Darwin(Chain, CallConv, isVarArg, Ins,
02288                                        dl, DAG, InVals);
02289   }
02290 }
02291 
02292 SDValue
02293 PPCTargetLowering::LowerFormalArguments_32SVR4(
02294                                       SDValue Chain,
02295                                       CallingConv::ID CallConv, bool isVarArg,
02296                                       const SmallVectorImpl<ISD::InputArg>
02297                                         &Ins,
02298                                       SDLoc dl, SelectionDAG &DAG,
02299                                       SmallVectorImpl<SDValue> &InVals) const {
02300 
02301   // 32-bit SVR4 ABI Stack Frame Layout:
02302   //              +-----------------------------------+
02303   //        +-->  |            Back chain             |
02304   //        |     +-----------------------------------+
02305   //        |     | Floating-point register save area |
02306   //        |     +-----------------------------------+
02307   //        |     |    General register save area     |
02308   //        |     +-----------------------------------+
02309   //        |     |          CR save word             |
02310   //        |     +-----------------------------------+
02311   //        |     |         VRSAVE save word          |
02312   //        |     +-----------------------------------+
02313   //        |     |         Alignment padding         |
02314   //        |     +-----------------------------------+
02315   //        |     |     Vector register save area     |
02316   //        |     +-----------------------------------+
02317   //        |     |       Local variable space        |
02318   //        |     +-----------------------------------+
02319   //        |     |        Parameter list area        |
02320   //        |     +-----------------------------------+
02321   //        |     |           LR save word            |
02322   //        |     +-----------------------------------+
02323   // SP-->  +---  |            Back chain             |
02324   //              +-----------------------------------+
02325   //
02326   // Specifications:
02327   //   System V Application Binary Interface PowerPC Processor Supplement
02328   //   AltiVec Technology Programming Interface Manual
02329 
02330   MachineFunction &MF = DAG.getMachineFunction();
02331   MachineFrameInfo *MFI = MF.getFrameInfo();
02332   PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
02333 
02334   EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
02335   // Potential tail calls could cause overwriting of argument stack slots.
02336   bool isImmutable = !(getTargetMachine().Options.GuaranteedTailCallOpt &&
02337                        (CallConv == CallingConv::Fast));
02338   unsigned PtrByteSize = 4;
02339 
02340   // Assign locations to all of the incoming arguments.
02341   SmallVector<CCValAssign, 16> ArgLocs;
02342   CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(),
02343                  getTargetMachine(), ArgLocs, *DAG.getContext());
02344 
02345   // Reserve space for the linkage area on the stack.
02346   unsigned LinkageSize = PPCFrameLowering::getLinkageSize(false, false, false);
02347   CCInfo.AllocateStack(LinkageSize, PtrByteSize);
02348 
02349   CCInfo.AnalyzeFormalArguments(Ins, CC_PPC32_SVR4);
02350 
02351   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
02352     CCValAssign &VA = ArgLocs[i];
02353 
02354     // Arguments stored in registers.
02355     if (VA.isRegLoc()) {
02356       const TargetRegisterClass *RC;
02357       EVT ValVT = VA.getValVT();
02358 
02359       switch (ValVT.getSimpleVT().SimpleTy) {
02360         default:
02361           llvm_unreachable("ValVT not supported by formal arguments Lowering");
02362         case MVT::i1:
02363         case MVT::i32:
02364           RC = &PPC::GPRCRegClass;
02365           break;
02366         case MVT::f32:
02367           RC = &PPC::F4RCRegClass;
02368           break;
02369         case MVT::f64:
02370           if (Subtarget.hasVSX())
02371             RC = &PPC::VSFRCRegClass;
02372           else
02373             RC = &PPC::F8RCRegClass;
02374           break;
02375         case MVT::v16i8:
02376         case MVT::v8i16:
02377         case MVT::v4i32:
02378         case MVT::v4f32:
02379           RC = &PPC::VRRCRegClass;
02380           break;
02381         case MVT::v2f64:
02382         case MVT::v2i64:
02383           RC = &PPC::VSHRCRegClass;
02384           break;
02385       }
02386 
02387       // Transform the arguments stored in physical registers into virtual ones.
02388       unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
02389       SDValue ArgValue = DAG.getCopyFromReg(Chain, dl, Reg,
02390                                             ValVT == MVT::i1 ? MVT::i32 : ValVT);
02391 
02392       if (ValVT == MVT::i1)
02393         ArgValue = DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, ArgValue);
02394 
02395       InVals.push_back(ArgValue);
02396     } else {
02397       // Argument stored in memory.
02398       assert(VA.isMemLoc());
02399 
02400       unsigned ArgSize = VA.getLocVT().getStoreSize();
02401       int FI = MFI->CreateFixedObject(ArgSize, VA.getLocMemOffset(),
02402                                       isImmutable);
02403 
02404       // Create load nodes to retrieve arguments from the stack.
02405       SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
02406       InVals.push_back(DAG.getLoad(VA.getValVT(), dl, Chain, FIN,
02407                                    MachinePointerInfo(),
02408                                    false, false, false, 0));
02409     }
02410   }
02411 
02412   // Assign locations to all of the incoming aggregate by value arguments.
02413   // Aggregates passed by value are stored in the local variable space of the
02414   // caller's stack frame, right above the parameter list area.
02415   SmallVector<CCValAssign, 16> ByValArgLocs;
02416   CCState CCByValInfo(CallConv, isVarArg, DAG.getMachineFunction(),
02417                       getTargetMachine(), ByValArgLocs, *DAG.getContext());
02418 
02419   // Reserve stack space for the allocations in CCInfo.
02420   CCByValInfo.AllocateStack(CCInfo.getNextStackOffset(), PtrByteSize);
02421 
02422   CCByValInfo.AnalyzeFormalArguments(Ins, CC_PPC32_SVR4_ByVal);
02423 
02424   // Area that is at least reserved in the caller of this function.
02425   unsigned MinReservedArea = CCByValInfo.getNextStackOffset();
02426   MinReservedArea = std::max(MinReservedArea, LinkageSize);
02427 
02428   // Set the size that is at least reserved in caller of this function.  Tail
02429   // call optimized function's reserved stack space needs to be aligned so that
02430   // taking the difference between two stack areas will result in an aligned
02431   // stack.
02432   MinReservedArea = EnsureStackAlignment(MF.getTarget(), MinReservedArea);
02433   FuncInfo->setMinReservedArea(MinReservedArea);
02434 
02435   SmallVector<SDValue, 8> MemOps;
02436 
02437   // If the function takes variable number of arguments, make a frame index for
02438   // the start of the first vararg value... for expansion of llvm.va_start.
02439   if (isVarArg) {
02440     static const MCPhysReg GPArgRegs[] = {
02441       PPC::R3, PPC::R4, PPC::R5, PPC::R6,
02442       PPC::R7, PPC::R8, PPC::R9, PPC::R10,
02443     };
02444     const unsigned NumGPArgRegs = array_lengthof(GPArgRegs);
02445 
02446     static const MCPhysReg FPArgRegs[] = {
02447       PPC::F1, PPC::F2, PPC::F3, PPC::F4, PPC::F5, PPC::F6, PPC::F7,
02448       PPC::F8
02449     };
02450     const unsigned NumFPArgRegs = array_lengthof(FPArgRegs);
02451 
02452     FuncInfo->setVarArgsNumGPR(CCInfo.getFirstUnallocated(GPArgRegs,
02453                                                           NumGPArgRegs));
02454     FuncInfo->setVarArgsNumFPR(CCInfo.getFirstUnallocated(FPArgRegs,
02455                                                           NumFPArgRegs));
02456 
02457     // Make room for NumGPArgRegs and NumFPArgRegs.
02458     int Depth = NumGPArgRegs * PtrVT.getSizeInBits()/8 +
02459                 NumFPArgRegs * EVT(MVT::f64).getSizeInBits()/8;
02460 
02461     FuncInfo->setVarArgsStackOffset(
02462       MFI->CreateFixedObject(PtrVT.getSizeInBits()/8,
02463                              CCInfo.getNextStackOffset(), true));
02464 
02465     FuncInfo->setVarArgsFrameIndex(MFI->CreateStackObject(Depth, 8, false));
02466     SDValue FIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT);
02467 
02468     // The fixed integer arguments of a variadic function are stored to the
02469     // VarArgsFrameIndex on the stack so that they may be loaded by deferencing
02470     // the result of va_next.
02471     for (unsigned GPRIndex = 0; GPRIndex != NumGPArgRegs; ++GPRIndex) {
02472       // Get an existing live-in vreg, or add a new one.
02473       unsigned VReg = MF.getRegInfo().getLiveInVirtReg(GPArgRegs[GPRIndex]);
02474       if (!VReg)
02475         VReg = MF.addLiveIn(GPArgRegs[GPRIndex], &PPC::GPRCRegClass);
02476 
02477       SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT);
02478       SDValue Store = DAG.getStore(Val.getValue(1), dl, Val, FIN,
02479                                    MachinePointerInfo(), false, false, 0);
02480       MemOps.push_back(Store);
02481       // Increment the address by four for the next argument to store
02482       SDValue PtrOff = DAG.getConstant(PtrVT.getSizeInBits()/8, PtrVT);
02483       FIN = DAG.getNode(ISD::ADD, dl, PtrOff.getValueType(), FIN, PtrOff);
02484     }
02485 
02486     // FIXME 32-bit SVR4: We only need to save FP argument registers if CR bit 6
02487     // is set.
02488     // The double arguments are stored to the VarArgsFrameIndex
02489     // on the stack.
02490     for (unsigned FPRIndex = 0; FPRIndex != NumFPArgRegs; ++FPRIndex) {
02491       // Get an existing live-in vreg, or add a new one.
02492       unsigned VReg = MF.getRegInfo().getLiveInVirtReg(FPArgRegs[FPRIndex]);
02493       if (!VReg)
02494         VReg = MF.addLiveIn(FPArgRegs[FPRIndex], &PPC::F8RCRegClass);
02495 
02496       SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::f64);
02497       SDValue Store = DAG.getStore(Val.getValue(1), dl, Val, FIN,
02498                                    MachinePointerInfo(), false, false, 0);
02499       MemOps.push_back(Store);
02500       // Increment the address by eight for the next argument to store
02501       SDValue PtrOff = DAG.getConstant(EVT(MVT::f64).getSizeInBits()/8,
02502                                          PtrVT);
02503       FIN = DAG.getNode(ISD::ADD, dl, PtrOff.getValueType(), FIN, PtrOff);
02504     }
02505   }
02506 
02507   if (!MemOps.empty())
02508     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOps);
02509 
02510   return Chain;
02511 }
02512 
02513 // PPC64 passes i8, i16, and i32 values in i64 registers. Promote
02514 // value to MVT::i64 and then truncate to the correct register size.
02515 SDValue
02516 PPCTargetLowering::extendArgForPPC64(ISD::ArgFlagsTy Flags, EVT ObjectVT,
02517                                      SelectionDAG &DAG, SDValue ArgVal,
02518                                      SDLoc dl) const {
02519   if (Flags.isSExt())
02520     ArgVal = DAG.getNode(ISD::AssertSext, dl, MVT::i64, ArgVal,
02521                          DAG.getValueType(ObjectVT));
02522   else if (Flags.isZExt())
02523     ArgVal = DAG.getNode(ISD::AssertZext, dl, MVT::i64, ArgVal,
02524                          DAG.getValueType(ObjectVT));
02525 
02526   return DAG.getNode(ISD::TRUNCATE, dl, ObjectVT, ArgVal);
02527 }
02528 
02529 SDValue
02530 PPCTargetLowering::LowerFormalArguments_64SVR4(
02531                                       SDValue Chain,
02532                                       CallingConv::ID CallConv, bool isVarArg,
02533                                       const SmallVectorImpl<ISD::InputArg>
02534                                         &Ins,
02535                                       SDLoc dl, SelectionDAG &DAG,
02536                                       SmallVectorImpl<SDValue> &InVals) const {
02537   // TODO: add description of PPC stack frame format, or at least some docs.
02538   //
02539   bool isELFv2ABI = Subtarget.isELFv2ABI();
02540   bool isLittleEndian = Subtarget.isLittleEndian();
02541   MachineFunction &MF = DAG.getMachineFunction();
02542   MachineFrameInfo *MFI = MF.getFrameInfo();
02543   PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
02544 
02545   EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
02546   // Potential tail calls could cause overwriting of argument stack slots.
02547   bool isImmutable = !(getTargetMachine().Options.GuaranteedTailCallOpt &&
02548                        (CallConv == CallingConv::Fast));
02549   unsigned PtrByteSize = 8;
02550 
02551   unsigned LinkageSize = PPCFrameLowering::getLinkageSize(true, false,
02552                                                           isELFv2ABI);
02553 
02554   static const MCPhysReg GPR[] = {
02555     PPC::X3, PPC::X4, PPC::X5, PPC::X6,
02556     PPC::X7, PPC::X8, PPC::X9, PPC::X10,
02557   };
02558 
02559   static const MCPhysReg *FPR = GetFPR();
02560 
02561   static const MCPhysReg VR[] = {
02562     PPC::V2, PPC::V3, PPC::V4, PPC::V5, PPC::V6, PPC::V7, PPC::V8,
02563     PPC::V9, PPC::V10, PPC::V11, PPC::V12, PPC::V13
02564   };
02565   static const MCPhysReg VSRH[] = {
02566     PPC::VSH2, PPC::VSH3, PPC::VSH4, PPC::VSH5, PPC::VSH6, PPC::VSH7, PPC::VSH8,
02567     PPC::VSH9, PPC::VSH10, PPC::VSH11, PPC::VSH12, PPC::VSH13
02568   };
02569 
02570   const unsigned Num_GPR_Regs = array_lengthof(GPR);
02571   const unsigned Num_FPR_Regs = 13;
02572   const unsigned Num_VR_Regs  = array_lengthof(VR);
02573 
02574   // Do a first pass over the arguments to determine whether the ABI
02575   // guarantees that our caller has allocated the parameter save area
02576   // on its stack frame.  In the ELFv1 ABI, this is always the case;
02577   // in the ELFv2 ABI, it is true if this is a vararg function or if
02578   // any parameter is located in a stack slot.
02579 
02580   bool HasParameterArea = !isELFv2ABI || isVarArg;
02581   unsigned ParamAreaSize = Num_GPR_Regs * PtrByteSize;
02582   unsigned NumBytes = LinkageSize;
02583   unsigned AvailableFPRs = Num_FPR_Regs;
02584   unsigned AvailableVRs = Num_VR_Regs;
02585   for (unsigned i = 0, e = Ins.size(); i != e; ++i)
02586     if (CalculateStackSlotUsed(Ins[i].VT, Ins[i].ArgVT, Ins[i].Flags,
02587                                PtrByteSize, LinkageSize, ParamAreaSize,
02588                                NumBytes, AvailableFPRs, AvailableVRs))
02589       HasParameterArea = true;
02590 
02591   // Add DAG nodes to load the arguments or copy them out of registers.  On
02592   // entry to a function on PPC, the arguments start after the linkage area,
02593   // although the first ones are often in registers.
02594 
02595   unsigned ArgOffset = LinkageSize;
02596   unsigned GPR_idx, FPR_idx = 0, VR_idx = 0;
02597   SmallVector<SDValue, 8> MemOps;
02598   Function::const_arg_iterator FuncArg = MF.getFunction()->arg_begin();
02599   unsigned CurArgIdx = 0;
02600   for (unsigned ArgNo = 0, e = Ins.size(); ArgNo != e; ++ArgNo) {
02601     SDValue ArgVal;
02602     bool needsLoad = false;
02603     EVT ObjectVT = Ins[ArgNo].VT;
02604     EVT OrigVT = Ins[ArgNo].ArgVT;
02605     unsigned ObjSize = ObjectVT.getStoreSize();
02606     unsigned ArgSize = ObjSize;
02607     ISD::ArgFlagsTy Flags = Ins[ArgNo].Flags;
02608     std::advance(FuncArg, Ins[ArgNo].OrigArgIndex - CurArgIdx);
02609     CurArgIdx = Ins[ArgNo].OrigArgIndex;
02610 
02611     /* Respect alignment of argument on the stack.  */
02612     unsigned Align =
02613       CalculateStackSlotAlignment(ObjectVT, OrigVT, Flags, PtrByteSize);
02614     ArgOffset = ((ArgOffset + Align - 1) / Align) * Align;
02615     unsigned CurArgOffset = ArgOffset;
02616 
02617     /* Compute GPR index associated with argument offset.  */
02618     GPR_idx = (ArgOffset - LinkageSize) / PtrByteSize;
02619     GPR_idx = std::min(GPR_idx, Num_GPR_Regs);
02620 
02621     // FIXME the codegen can be much improved in some cases.
02622     // We do not have to keep everything in memory.
02623     if (Flags.isByVal()) {
02624       // ObjSize is the true size, ArgSize rounded up to multiple of registers.
02625       ObjSize = Flags.getByValSize();
02626       ArgSize = ((ObjSize + PtrByteSize - 1)/PtrByteSize) * PtrByteSize;
02627       // Empty aggregate parameters do not take up registers.  Examples:
02628       //   struct { } a;
02629       //   union  { } b;
02630       //   int c[0];
02631       // etc.  However, we have to provide a place-holder in InVals, so
02632       // pretend we have an 8-byte item at the current address for that
02633       // purpose.
02634       if (!ObjSize) {
02635         int FI = MFI->CreateFixedObject(PtrByteSize, ArgOffset, true);
02636         SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
02637         InVals.push_back(FIN);
02638         continue;
02639       }
02640 
02641       // Create a stack object covering all stack doublewords occupied
02642       // by the argument.  If the argument is (fully or partially) on
02643       // the stack, or if the argument is fully in registers but the
02644       // caller has allocated the parameter save anyway, we can refer
02645       // directly to the caller's stack frame.  Otherwise, create a
02646       // local copy in our own frame.
02647       int FI;
02648       if (HasParameterArea ||
02649           ArgSize + ArgOffset > LinkageSize + Num_GPR_Regs * PtrByteSize)
02650         FI = MFI->CreateFixedObject(ArgSize, ArgOffset, true);
02651       else
02652         FI = MFI->CreateStackObject(ArgSize, Align, false);
02653       SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
02654 
02655       // Handle aggregates smaller than 8 bytes.
02656       if (ObjSize < PtrByteSize) {
02657         // The value of the object is its address, which differs from the
02658         // address of the enclosing doubleword on big-endian systems.
02659         SDValue Arg = FIN;
02660         if (!isLittleEndian) {
02661           SDValue ArgOff = DAG.getConstant(PtrByteSize - ObjSize, PtrVT);
02662           Arg = DAG.getNode(ISD::ADD, dl, ArgOff.getValueType(), Arg, ArgOff);
02663         }
02664         InVals.push_back(Arg);
02665 
02666         if (GPR_idx != Num_GPR_Regs) {
02667           unsigned VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass);
02668           SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT);
02669           SDValue Store;
02670 
02671           if (ObjSize==1 || ObjSize==2 || ObjSize==4) {
02672             EVT ObjType = (ObjSize == 1 ? MVT::i8 :
02673                            (ObjSize == 2 ? MVT::i16 : MVT::i32));
02674             Store = DAG.getTruncStore(Val.getValue(1), dl, Val, Arg,
02675                                       MachinePointerInfo(FuncArg),
02676                                       ObjType, false, false, 0);
02677           } else {
02678             // For sizes that don't fit a truncating store (3, 5, 6, 7),
02679             // store the whole register as-is to the parameter save area
02680             // slot.
02681             Store = DAG.getStore(Val.getValue(1), dl, Val, FIN,
02682                                  MachinePointerInfo(FuncArg),
02683                                  false, false, 0);
02684           }
02685 
02686           MemOps.push_back(Store);
02687         }
02688         // Whether we copied from a register or not, advance the offset
02689         // into the parameter save area by a full doubleword.
02690         ArgOffset += PtrByteSize;
02691         continue;
02692       }
02693 
02694       // The value of the object is its address, which is the address of
02695       // its first stack doubleword.
02696       InVals.push_back(FIN);
02697 
02698       // Store whatever pieces of the object are in registers to memory.
02699       for (unsigned j = 0; j < ArgSize; j += PtrByteSize) {
02700         if (GPR_idx == Num_GPR_Regs)
02701           break;
02702 
02703         unsigned VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass);
02704         SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT);
02705         SDValue Addr = FIN;
02706         if (j) {
02707           SDValue Off = DAG.getConstant(j, PtrVT);
02708           Addr = DAG.getNode(ISD::ADD, dl, Off.getValueType(), Addr, Off);
02709         }
02710         SDValue Store = DAG.getStore(Val.getValue(1), dl, Val, Addr,
02711                                      MachinePointerInfo(FuncArg, j),
02712                                      false, false, 0);
02713         MemOps.push_back(Store);
02714         ++GPR_idx;
02715       }
02716       ArgOffset += ArgSize;
02717       continue;
02718     }
02719 
02720     switch (ObjectVT.getSimpleVT().SimpleTy) {
02721     default: llvm_unreachable("Unhandled argument type!");
02722     case MVT::i1:
02723     case MVT::i32:
02724     case MVT::i64:
02725       // These can be scalar arguments or elements of an integer array type
02726       // passed directly.  Clang may use those instead of "byval" aggregate
02727       // types to avoid forcing arguments to memory unnecessarily.
02728       if (GPR_idx != Num_GPR_Regs) {
02729         unsigned VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass);
02730         ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i64);
02731 
02732         if (ObjectVT == MVT::i32 || ObjectVT == MVT::i1)
02733           // PPC64 passes i8, i16, and i32 values in i64 registers. Promote
02734           // value to MVT::i64 and then truncate to the correct register size.
02735           ArgVal = extendArgForPPC64(Flags, ObjectVT, DAG, ArgVal, dl);
02736       } else {
02737         needsLoad = true;
02738         ArgSize = PtrByteSize;
02739       }
02740       ArgOffset += 8;
02741       break;
02742 
02743     case MVT::f32:
02744     case MVT::f64:
02745       // These can be scalar arguments or elements of a float array type
02746       // passed directly.  The latter are used to implement ELFv2 homogenous
02747       // float aggregates.
02748       if (FPR_idx != Num_FPR_Regs) {
02749         unsigned VReg;
02750 
02751         if (ObjectVT == MVT::f32)
02752           VReg = MF.addLiveIn(FPR[FPR_idx], &PPC::F4RCRegClass);
02753         else
02754           VReg = MF.addLiveIn(FPR[FPR_idx], Subtarget.hasVSX() ?
02755                                             &PPC::VSFRCRegClass :
02756                                             &PPC::F8RCRegClass);
02757 
02758         ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, ObjectVT);
02759         ++FPR_idx;
02760       } else if (GPR_idx != Num_GPR_Regs) {
02761         // This can only ever happen in the presence of f32 array types,
02762         // since otherwise we never run out of FPRs before running out
02763         // of GPRs.
02764         unsigned VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass);
02765         ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i64);
02766 
02767         if (ObjectVT == MVT::f32) {
02768           if ((ArgOffset % PtrByteSize) == (isLittleEndian ? 4 : 0))
02769             ArgVal = DAG.getNode(ISD::SRL, dl, MVT::i64, ArgVal,
02770                                  DAG.getConstant(32, MVT::i32));
02771           ArgVal = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, ArgVal);
02772         }
02773 
02774         ArgVal = DAG.getNode(ISD::BITCAST, dl, ObjectVT, ArgVal);
02775       } else {
02776         needsLoad = true;
02777       }
02778 
02779       // When passing an array of floats, the array occupies consecutive
02780       // space in the argument area; only round up to the next doubleword
02781       // at the end of the array.  Otherwise, each float takes 8 bytes.
02782       ArgSize = Flags.isInConsecutiveRegs() ? ObjSize : PtrByteSize;
02783       ArgOffset += ArgSize;
02784       if (Flags.isInConsecutiveRegsLast())
02785         ArgOffset = ((ArgOffset + PtrByteSize - 1)/PtrByteSize) * PtrByteSize;
02786       break;
02787     case MVT::v4f32:
02788     case MVT::v4i32:
02789     case MVT::v8i16:
02790     case MVT::v16i8:
02791     case MVT::v2f64:
02792     case MVT::v2i64:
02793       // These can be scalar arguments or elements of a vector array type
02794       // passed directly.  The latter are used to implement ELFv2 homogenous
02795       // vector aggregates.
02796       if (VR_idx != Num_VR_Regs) {
02797         unsigned VReg = (ObjectVT == MVT::v2f64 || ObjectVT == MVT::v2i64) ?
02798                         MF.addLiveIn(VSRH[VR_idx], &PPC::VSHRCRegClass) :
02799                         MF.addLiveIn(VR[VR_idx], &PPC::VRRCRegClass);
02800         ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, ObjectVT);
02801         ++VR_idx;
02802       } else {
02803         needsLoad = true;
02804       }
02805       ArgOffset += 16;
02806       break;
02807     }
02808 
02809     // We need to load the argument to a virtual register if we determined
02810     // above that we ran out of physical registers of the appropriate type.
02811     if (needsLoad) {
02812       if (ObjSize < ArgSize && !isLittleEndian)
02813         CurArgOffset += ArgSize - ObjSize;
02814       int FI = MFI->CreateFixedObject(ObjSize, CurArgOffset, isImmutable);
02815       SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
02816       ArgVal = DAG.getLoad(ObjectVT, dl, Chain, FIN, MachinePointerInfo(),
02817                            false, false, false, 0);
02818     }
02819 
02820     InVals.push_back(ArgVal);
02821   }
02822 
02823   // Area that is at least reserved in the caller of this function.
02824   unsigned MinReservedArea;
02825   if (HasParameterArea)
02826     MinReservedArea = std::max(ArgOffset, LinkageSize + 8 * PtrByteSize);
02827   else
02828     MinReservedArea = LinkageSize;
02829 
02830   // Set the size that is at least reserved in caller of this function.  Tail
02831   // call optimized functions' reserved stack space needs to be aligned so that
02832   // taking the difference between two stack areas will result in an aligned
02833   // stack.
02834   MinReservedArea = EnsureStackAlignment(MF.getTarget(), MinReservedArea);
02835   FuncInfo->setMinReservedArea(MinReservedArea);
02836 
02837   // If the function takes variable number of arguments, make a frame index for
02838   // the start of the first vararg value... for expansion of llvm.va_start.
02839   if (isVarArg) {
02840     int Depth = ArgOffset;
02841 
02842     FuncInfo->setVarArgsFrameIndex(
02843       MFI->CreateFixedObject(PtrByteSize, Depth, true));
02844     SDValue FIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT);
02845 
02846     // If this function is vararg, store any remaining integer argument regs
02847     // to their spots on the stack so that they may be loaded by deferencing the
02848     // result of va_next.
02849     for (GPR_idx = (ArgOffset - LinkageSize) / PtrByteSize;
02850          GPR_idx < Num_GPR_Regs; ++GPR_idx) {
02851       unsigned VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass);
02852       SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT);
02853       SDValue Store = DAG.getStore(Val.getValue(1), dl, Val, FIN,
02854                                    MachinePointerInfo(), false, false, 0);
02855       MemOps.push_back(Store);
02856       // Increment the address by four for the next argument to store
02857       SDValue PtrOff = DAG.getConstant(PtrByteSize, PtrVT);
02858       FIN = DAG.getNode(ISD::ADD, dl, PtrOff.getValueType(), FIN, PtrOff);
02859     }
02860   }
02861 
02862   if (!MemOps.empty())
02863     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOps);
02864 
02865   return Chain;
02866 }
02867 
02868 SDValue
02869 PPCTargetLowering::LowerFormalArguments_Darwin(
02870                                       SDValue Chain,
02871                                       CallingConv::ID CallConv, bool isVarArg,
02872                                       const SmallVectorImpl<ISD::InputArg>
02873                                         &Ins,
02874                                       SDLoc dl, SelectionDAG &DAG,
02875                                       SmallVectorImpl<SDValue> &InVals) const {
02876   // TODO: add description of PPC stack frame format, or at least some docs.
02877   //
02878   MachineFunction &MF = DAG.getMachineFunction();
02879   MachineFrameInfo *MFI = MF.getFrameInfo();
02880   PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
02881 
02882   EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
02883   bool isPPC64 = PtrVT == MVT::i64;
02884   // Potential tail calls could cause overwriting of argument stack slots.
02885   bool isImmutable = !(getTargetMachine().Options.GuaranteedTailCallOpt &&
02886                        (CallConv == CallingConv::Fast));
02887   unsigned PtrByteSize = isPPC64 ? 8 : 4;
02888 
02889   unsigned LinkageSize = PPCFrameLowering::getLinkageSize(isPPC64, true,
02890                                                           false);
02891   unsigned ArgOffset = LinkageSize;
02892   // Area that is at least reserved in caller of this function.
02893   unsigned MinReservedArea = ArgOffset;
02894 
02895   static const MCPhysReg GPR_32[] = {           // 32-bit registers.
02896     PPC::R3, PPC::R4, PPC::R5, PPC::R6,
02897     PPC::R7, PPC::R8, PPC::R9, PPC::R10,
02898   };
02899   static const MCPhysReg GPR_64[] = {           // 64-bit registers.
02900     PPC::X3, PPC::X4, PPC::X5, PPC::X6,
02901     PPC::X7, PPC::X8, PPC::X9, PPC::X10,
02902   };
02903 
02904   static const MCPhysReg *FPR = GetFPR();
02905 
02906   static const MCPhysReg VR[] = {
02907     PPC::V2, PPC::V3, PPC::V4, PPC::V5, PPC::V6, PPC::V7, PPC::V8,
02908     PPC::V9, PPC::V10, PPC::V11, PPC::V12, PPC::V13
02909   };
02910 
02911   const unsigned Num_GPR_Regs = array_lengthof(GPR_32);
02912   const unsigned Num_FPR_Regs = 13;
02913   const unsigned Num_VR_Regs  = array_lengthof( VR);
02914 
02915   unsigned GPR_idx = 0, FPR_idx = 0, VR_idx = 0;
02916 
02917   const MCPhysReg *GPR = isPPC64 ? GPR_64 : GPR_32;
02918 
02919   // In 32-bit non-varargs functions, the stack space for vectors is after the
02920   // stack space for non-vectors.  We do not use this space unless we have
02921   // too many vectors to fit in registers, something that only occurs in
02922   // constructed examples:), but we have to walk the arglist to figure
02923   // that out...for the pathological case, compute VecArgOffset as the
02924   // start of the vector parameter area.  Computing VecArgOffset is the
02925   // entire point of the following loop.
02926   unsigned VecArgOffset = ArgOffset;
02927   if (!isVarArg && !isPPC64) {
02928     for (unsigned ArgNo = 0, e = Ins.size(); ArgNo != e;
02929          ++ArgNo) {
02930       EVT ObjectVT = Ins[ArgNo].VT;
02931       ISD::ArgFlagsTy Flags = Ins[ArgNo].Flags;
02932 
02933       if (Flags.isByVal()) {
02934         // ObjSize is the true size, ArgSize rounded up to multiple of regs.
02935         unsigned ObjSize = Flags.getByValSize();
02936         unsigned ArgSize =
02937                 ((ObjSize + PtrByteSize - 1)/PtrByteSize) * PtrByteSize;
02938         VecArgOffset += ArgSize;
02939         continue;
02940       }
02941 
02942       switch(ObjectVT.getSimpleVT().SimpleTy) {
02943       default: llvm_unreachable("Unhandled argument type!");
02944       case MVT::i1:
02945       case MVT::i32:
02946       case MVT::f32:
02947         VecArgOffset += 4;
02948         break;
02949       case MVT::i64:  // PPC64
02950       case MVT::f64:
02951         // FIXME: We are guaranteed to be !isPPC64 at this point.
02952         // Does MVT::i64 apply?
02953         VecArgOffset += 8;
02954         break;
02955       case MVT::v4f32:
02956       case MVT::v4i32:
02957       case MVT::v8i16:
02958       case MVT::v16i8:
02959         // Nothing to do, we're only looking at Nonvector args here.
02960         break;
02961       }
02962     }
02963   }
02964   // We've found where the vector parameter area in memory is.  Skip the
02965   // first 12 parameters; these don't use that memory.
02966   VecArgOffset = ((VecArgOffset+15)/16)*16;
02967   VecArgOffset += 12*16;
02968 
02969   // Add DAG nodes to load the arguments or copy them out of registers.  On
02970   // entry to a function on PPC, the arguments start after the linkage area,
02971   // although the first ones are often in registers.
02972 
02973   SmallVector<SDValue, 8> MemOps;
02974   unsigned nAltivecParamsAtEnd = 0;
02975   Function::const_arg_iterator FuncArg = MF.getFunction()->arg_begin();
02976   unsigned CurArgIdx = 0;
02977   for (unsigned ArgNo = 0, e = Ins.size(); ArgNo != e; ++ArgNo) {
02978     SDValue ArgVal;
02979     bool needsLoad = false;
02980     EVT ObjectVT = Ins[ArgNo].VT;
02981     unsigned ObjSize = ObjectVT.getSizeInBits()/8;
02982     unsigned ArgSize = ObjSize;
02983     ISD::ArgFlagsTy Flags = Ins[ArgNo].Flags;
02984     std::advance(FuncArg, Ins[ArgNo].OrigArgIndex - CurArgIdx);
02985     CurArgIdx = Ins[ArgNo].OrigArgIndex;
02986 
02987     unsigned CurArgOffset = ArgOffset;
02988 
02989     // Varargs or 64 bit Altivec parameters are padded to a 16 byte boundary.
02990     if (ObjectVT==MVT::v4f32 || ObjectVT==MVT::v4i32 ||
02991         ObjectVT==MVT::v8i16 || ObjectVT==MVT::v16i8) {
02992       if (isVarArg || isPPC64) {
02993         MinReservedArea = ((MinReservedArea+15)/16)*16;
02994         MinReservedArea += CalculateStackSlotSize(ObjectVT,
02995                                                   Flags,
02996                                                   PtrByteSize);
02997       } else  nAltivecParamsAtEnd++;
02998     } else
02999       // Calculate min reserved area.
03000       MinReservedArea += CalculateStackSlotSize(Ins[ArgNo].VT,
03001                                                 Flags,
03002                                                 PtrByteSize);
03003 
03004     // FIXME the codegen can be much improved in some cases.
03005     // We do not have to keep everything in memory.
03006     if (Flags.isByVal()) {
03007       // ObjSize is the true size, ArgSize rounded up to multiple of registers.
03008       ObjSize = Flags.getByValSize();
03009       ArgSize = ((ObjSize + PtrByteSize - 1)/PtrByteSize) * PtrByteSize;
03010       // Objects of size 1 and 2 are right justified, everything else is
03011       // left justified.  This means the memory address is adjusted forwards.
03012       if (ObjSize==1 || ObjSize==2) {
03013         CurArgOffset = CurArgOffset + (4 - ObjSize);
03014       }
03015       // The value of the object is its address.
03016       int FI = MFI->CreateFixedObject(ObjSize, CurArgOffset, true);
03017       SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
03018       InVals.push_back(FIN);
03019       if (ObjSize==1 || ObjSize==2) {
03020         if (GPR_idx != Num_GPR_Regs) {
03021           unsigned VReg;
03022           if (isPPC64)
03023             VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass);
03024           else
03025             VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::GPRCRegClass);
03026           SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT);
03027           EVT ObjType = ObjSize == 1 ? MVT::i8 : MVT::i16;
03028           SDValue Store = DAG.getTruncStore(Val.getValue(1), dl, Val, FIN,
03029                                             MachinePointerInfo(FuncArg),
03030                                             ObjType, false, false, 0);
03031           MemOps.push_back(Store);
03032           ++GPR_idx;
03033         }
03034 
03035         ArgOffset += PtrByteSize;
03036 
03037         continue;
03038       }
03039       for (unsigned j = 0; j < ArgSize; j += PtrByteSize) {
03040         // Store whatever pieces of the object are in registers
03041         // to memory.  ArgOffset will be the address of the beginning
03042         // of the object.
03043         if (GPR_idx != Num_GPR_Regs) {
03044           unsigned VReg;
03045           if (isPPC64)
03046             VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass);
03047           else
03048             VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::GPRCRegClass);
03049           int FI = MFI->CreateFixedObject(PtrByteSize, ArgOffset, true);
03050           SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
03051           SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT);
03052           SDValue Store = DAG.getStore(Val.getValue(1), dl, Val, FIN,
03053                                        MachinePointerInfo(FuncArg, j),
03054                                        false, false, 0);
03055           MemOps.push_back(Store);
03056           ++GPR_idx;
03057           ArgOffset += PtrByteSize;
03058         } else {
03059           ArgOffset += ArgSize - (ArgOffset-CurArgOffset);
03060           break;
03061         }
03062       }
03063       continue;
03064     }
03065 
03066     switch (ObjectVT.getSimpleVT().SimpleTy) {
03067     default: llvm_unreachable("Unhandled argument type!");
03068     case MVT::i1:
03069     case MVT::i32:
03070       if (!isPPC64) {
03071         if (GPR_idx != Num_GPR_Regs) {
03072           unsigned VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::GPRCRegClass);
03073           ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i32);
03074 
03075           if (ObjectVT == MVT::i1)
03076             ArgVal = DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, ArgVal);
03077 
03078           ++GPR_idx;
03079         } else {
03080           needsLoad = true;
03081           ArgSize = PtrByteSize;
03082         }
03083         // All int arguments reserve stack space in the Darwin ABI.
03084         ArgOffset += PtrByteSize;
03085         break;
03086       }
03087       // FALLTHROUGH
03088     case MVT::i64:  // PPC64
03089       if (GPR_idx != Num_GPR_Regs) {
03090         unsigned VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass);
03091         ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i64);
03092 
03093         if (ObjectVT == MVT::i32 || ObjectVT == MVT::i1)
03094           // PPC64 passes i8, i16, and i32 values in i64 registers. Promote
03095           // value to MVT::i64 and then truncate to the correct register size.
03096           ArgVal = extendArgForPPC64(Flags, ObjectVT, DAG, ArgVal, dl);
03097 
03098         ++GPR_idx;
03099       } else {
03100         needsLoad = true;
03101         ArgSize = PtrByteSize;
03102       }
03103       // All int arguments reserve stack space in the Darwin ABI.
03104       ArgOffset += 8;
03105       break;
03106 
03107     case MVT::f32:
03108     case MVT::f64:
03109       // Every 4 bytes of argument space consumes one of the GPRs available for
03110       // argument passing.
03111       if (GPR_idx != Num_GPR_Regs) {
03112         ++GPR_idx;
03113         if (ObjSize == 8 && GPR_idx != Num_GPR_Regs && !isPPC64)
03114           ++GPR_idx;
03115       }
03116       if (FPR_idx != Num_FPR_Regs) {
03117         unsigned VReg;
03118 
03119         if (ObjectVT == MVT::f32)
03120           VReg = MF.addLiveIn(FPR[FPR_idx], &PPC::F4RCRegClass);
03121         else
03122           VReg = MF.addLiveIn(FPR[FPR_idx], &PPC::F8RCRegClass);
03123 
03124         ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, ObjectVT);
03125         ++FPR_idx;
03126       } else {
03127         needsLoad = true;
03128       }
03129 
03130       // All FP arguments reserve stack space in the Darwin ABI.
03131       ArgOffset += isPPC64 ? 8 : ObjSize;
03132       break;
03133     case MVT::v4f32:
03134     case MVT::v4i32:
03135     case MVT::v8i16:
03136     case MVT::v16i8:
03137       // Note that vector arguments in registers don't reserve stack space,
03138       // except in varargs functions.
03139       if (VR_idx != Num_VR_Regs) {
03140         unsigned VReg = MF.addLiveIn(VR[VR_idx], &PPC::VRRCRegClass);
03141         ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, ObjectVT);
03142         if (isVarArg) {
03143           while ((ArgOffset % 16) != 0) {
03144             ArgOffset += PtrByteSize;
03145             if (GPR_idx != Num_GPR_Regs)
03146               GPR_idx++;
03147           }
03148           ArgOffset += 16;
03149           GPR_idx = std::min(GPR_idx+4, Num_GPR_Regs); // FIXME correct for ppc64?
03150         }
03151         ++VR_idx;
03152       } else {
03153         if (!isVarArg && !isPPC64) {
03154           // Vectors go after all the nonvectors.
03155           CurArgOffset = VecArgOffset;
03156           VecArgOffset += 16;
03157         } else {
03158           // Vectors are aligned.
03159           ArgOffset = ((ArgOffset+15)/16)*16;
03160           CurArgOffset = ArgOffset;
03161           ArgOffset += 16;
03162         }
03163         needsLoad = true;
03164       }
03165       break;
03166     }
03167 
03168     // We need to load the argument to a virtual register if we determined above
03169     // that we ran out of physical registers of the appropriate type.
03170     if (needsLoad) {
03171       int FI = MFI->CreateFixedObject(ObjSize,
03172                                       CurArgOffset + (ArgSize - ObjSize),
03173                                       isImmutable);
03174       SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
03175       ArgVal = DAG.getLoad(ObjectVT, dl, Chain, FIN, MachinePointerInfo(),
03176                            false, false, false, 0);
03177     }
03178 
03179     InVals.push_back(ArgVal);
03180   }
03181 
03182   // Allow for Altivec parameters at the end, if needed.
03183   if (nAltivecParamsAtEnd) {
03184     MinReservedArea = ((MinReservedArea+15)/16)*16;
03185     MinReservedArea += 16*nAltivecParamsAtEnd;
03186   }
03187 
03188   // Area that is at least reserved in the caller of this function.
03189   MinReservedArea = std::max(MinReservedArea, LinkageSize + 8 * PtrByteSize);
03190 
03191   // Set the size that is at least reserved in caller of this function.  Tail
03192   // call optimized functions' reserved stack space needs to be aligned so that
03193   // taking the difference between two stack areas will result in an aligned
03194   // stack.
03195   MinReservedArea = EnsureStackAlignment(MF.getTarget(), MinReservedArea);
03196   FuncInfo->setMinReservedArea(MinReservedArea);
03197 
03198   // If the function takes variable number of arguments, make a frame index for
03199   // the start of the first vararg value... for expansion of llvm.va_start.
03200   if (isVarArg) {
03201     int Depth = ArgOffset;
03202 
03203     FuncInfo->setVarArgsFrameIndex(
03204       MFI->CreateFixedObject(PtrVT.getSizeInBits()/8,
03205                              Depth, true));
03206     SDValue FIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT);
03207 
03208     // If this function is vararg, store any remaining integer argument regs
03209     // to their spots on the stack so that they may be loaded by deferencing the
03210     // result of va_next.
03211     for (; GPR_idx != Num_GPR_Regs; ++GPR_idx) {
03212       unsigned VReg;
03213 
03214       if (isPPC64)
03215         VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass);
03216       else
03217         VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::GPRCRegClass);
03218 
03219       SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT);
03220       SDValue Store = DAG.getStore(Val.getValue(1), dl, Val, FIN,
03221                                    MachinePointerInfo(), false, false, 0);
03222       MemOps.push_back(Store);
03223       // Increment the address by four for the next argument to store
03224       SDValue PtrOff = DAG.getConstant(PtrVT.getSizeInBits()/8, PtrVT);
03225       FIN = DAG.getNode(ISD::ADD, dl, PtrOff.getValueType(), FIN, PtrOff);
03226     }
03227   }
03228 
03229   if (!MemOps.empty())
03230     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOps);
03231 
03232   return Chain;
03233 }
03234 
03235 /// CalculateTailCallSPDiff - Get the amount the stack pointer has to be
03236 /// adjusted to accommodate the arguments for the tailcall.
03237 static int CalculateTailCallSPDiff(SelectionDAG& DAG, bool isTailCall,
03238                                    unsigned ParamSize) {
03239 
03240   if (!isTailCall) return 0;
03241 
03242   PPCFunctionInfo *FI = DAG.getMachineFunction().getInfo<PPCFunctionInfo>();
03243   unsigned CallerMinReservedArea = FI->getMinReservedArea();
03244   int SPDiff = (int)CallerMinReservedArea - (int)ParamSize;
03245   // Remember only if the new adjustement is bigger.
03246   if (SPDiff < FI->getTailCallSPDelta())
03247     FI->setTailCallSPDelta(SPDiff);
03248 
03249   return SPDiff;
03250 }
03251 
03252 /// IsEligibleForTailCallOptimization - Check whether the call is eligible
03253 /// for tail call optimization. Targets which want to do tail call
03254 /// optimization should implement this function.
03255 bool
03256 PPCTargetLowering::IsEligibleForTailCallOptimization(SDValue Callee,
03257                                                      CallingConv::ID CalleeCC,
03258                                                      bool isVarArg,
03259                                       const SmallVectorImpl<ISD::InputArg> &Ins,
03260                                                      SelectionDAG& DAG) const {
03261   if (!getTargetMachine().Options.GuaranteedTailCallOpt)
03262     return false;
03263 
03264   // Variable argument functions are not supported.
03265   if (isVarArg)
03266     return false;
03267 
03268   MachineFunction &MF = DAG.getMachineFunction();
03269   CallingConv::ID CallerCC = MF.getFunction()->getCallingConv();
03270   if (CalleeCC == CallingConv::Fast && CallerCC == CalleeCC) {
03271     // Functions containing by val parameters are not supported.
03272     for (unsigned i = 0; i != Ins.size(); i++) {
03273        ISD::ArgFlagsTy Flags = Ins[i].Flags;
03274        if (Flags.isByVal()) return false;
03275     }
03276 
03277     // Non-PIC/GOT tail calls are supported.
03278     if (getTargetMachine().getRelocationModel() != Reloc::PIC_)
03279       return true;
03280 
03281     // At the moment we can only do local tail calls (in same module, hidden
03282     // or protected) if we are generating PIC.
03283     if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee))
03284       return G->getGlobal()->hasHiddenVisibility()
03285           || G->getGlobal()->hasProtectedVisibility();
03286   }
03287 
03288   return false;
03289 }
03290 
03291 /// isCallCompatibleAddress - Return the immediate to use if the specified
03292 /// 32-bit value is representable in the immediate field of a BxA instruction.
03293 static SDNode *isBLACompatibleAddress(SDValue Op, SelectionDAG &DAG) {
03294   ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op);
03295   if (!C) return nullptr;
03296 
03297   int Addr = C->getZExtValue();
03298   if ((Addr & 3) != 0 ||  // Low 2 bits are implicitly zero.
03299       SignExtend32<26>(Addr) != Addr)
03300     return nullptr;  // Top 6 bits have to be sext of immediate.
03301 
03302   return DAG.getConstant((int)C->getZExtValue() >> 2,
03303                          DAG.getTargetLoweringInfo().getPointerTy()).getNode();
03304 }
03305 
03306 namespace {
03307 
03308 struct TailCallArgumentInfo {
03309   SDValue Arg;
03310   SDValue FrameIdxOp;
03311   int       FrameIdx;
03312 
03313   TailCallArgumentInfo() : FrameIdx(0) {}
03314 };
03315 
03316 }
03317 
03318 /// StoreTailCallArgumentsToStackSlot - Stores arguments to their stack slot.
03319 static void
03320 StoreTailCallArgumentsToStackSlot(SelectionDAG &DAG,
03321                                            SDValue Chain,
03322                    const SmallVectorImpl<TailCallArgumentInfo> &TailCallArgs,
03323                    SmallVectorImpl<SDValue> &MemOpChains,
03324                    SDLoc dl) {
03325   for (unsigned i = 0, e = TailCallArgs.size(); i != e; ++i) {
03326     SDValue Arg = TailCallArgs[i].Arg;
03327     SDValue FIN = TailCallArgs[i].FrameIdxOp;
03328     int FI = TailCallArgs[i].FrameIdx;
03329     // Store relative to framepointer.
03330     MemOpChains.push_back(DAG.getStore(Chain, dl, Arg, FIN,
03331                                        MachinePointerInfo::getFixedStack(FI),
03332                                        false, false, 0));
03333   }
03334 }
03335 
03336 /// EmitTailCallStoreFPAndRetAddr - Move the frame pointer and return address to
03337 /// the appropriate stack slot for the tail call optimized function call.
03338 static SDValue EmitTailCallStoreFPAndRetAddr(SelectionDAG &DAG,
03339                                                MachineFunction &MF,
03340                                                SDValue Chain,
03341                                                SDValue OldRetAddr,
03342                                                SDValue OldFP,
03343                                                int SPDiff,
03344                                                bool isPPC64,
03345                                                bool isDarwinABI,
03346                                                SDLoc dl) {
03347   if (SPDiff) {
03348     // Calculate the new stack slot for the return address.
03349     int SlotSize = isPPC64 ? 8 : 4;
03350     int NewRetAddrLoc = SPDiff + PPCFrameLowering::getReturnSaveOffset(isPPC64,
03351                                                                    isDarwinABI);
03352     int NewRetAddr = MF.getFrameInfo()->CreateFixedObject(SlotSize,
03353                                                           NewRetAddrLoc, true);
03354     EVT VT = isPPC64 ? MVT::i64 : MVT::i32;
03355     SDValue NewRetAddrFrIdx = DAG.getFrameIndex(NewRetAddr, VT);
03356     Chain = DAG.getStore(Chain, dl, OldRetAddr, NewRetAddrFrIdx,
03357                          MachinePointerInfo::getFixedStack(NewRetAddr),
03358                          false, false, 0);
03359 
03360     // When using the 32/64-bit SVR4 ABI there is no need to move the FP stack
03361     // slot as the FP is never overwritten.
03362     if (isDarwinABI) {
03363       int NewFPLoc =
03364         SPDiff + PPCFrameLowering::getFramePointerSaveOffset(isPPC64, isDarwinABI);
03365       int NewFPIdx = MF.getFrameInfo()->CreateFixedObject(SlotSize, NewFPLoc,
03366                                                           true);
03367       SDValue NewFramePtrIdx = DAG.getFrameIndex(NewFPIdx, VT);
03368       Chain = DAG.getStore(Chain, dl, OldFP, NewFramePtrIdx,
03369                            MachinePointerInfo::getFixedStack(NewFPIdx),
03370                            false, false, 0);
03371     }
03372   }
03373   return Chain;
03374 }
03375 
03376 /// CalculateTailCallArgDest - Remember Argument for later processing. Calculate
03377 /// the position of the argument.
03378 static void
03379 CalculateTailCallArgDest(SelectionDAG &DAG, MachineFunction &MF, bool isPPC64,
03380                          SDValue Arg, int SPDiff, unsigned ArgOffset,
03381                      SmallVectorImpl<TailCallArgumentInfo>& TailCallArguments) {
03382   int Offset = ArgOffset + SPDiff;
03383   uint32_t OpSize = (Arg.getValueType().getSizeInBits()+7)/8;
03384   int FI = MF.getFrameInfo()->CreateFixedObject(OpSize, Offset, true);
03385   EVT VT = isPPC64 ? MVT::i64 : MVT::i32;
03386   SDValue FIN = DAG.getFrameIndex(FI, VT);
03387   TailCallArgumentInfo Info;
03388   Info.Arg = Arg;
03389   Info.FrameIdxOp = FIN;
03390   Info.FrameIdx = FI;
03391   TailCallArguments.push_back(Info);
03392 }
03393 
03394 /// EmitTCFPAndRetAddrLoad - Emit load from frame pointer and return address
03395 /// stack slot. Returns the chain as result and the loaded frame pointers in
03396 /// LROpOut/FPOpout. Used when tail calling.
03397 SDValue PPCTargetLowering::EmitTailCallLoadFPAndRetAddr(SelectionDAG & DAG,
03398                                                         int SPDiff,
03399                                                         SDValue Chain,
03400                                                         SDValue &LROpOut,
03401                                                         SDValue &FPOpOut,
03402                                                         bool isDarwinABI,
03403                                                         SDLoc dl) const {
03404   if (SPDiff) {
03405     // Load the LR and FP stack slot for later adjusting.
03406     EVT VT = Subtarget.isPPC64() ? MVT::i64 : MVT::i32;
03407     LROpOut = getReturnAddrFrameIndex(DAG);
03408     LROpOut = DAG.getLoad(VT, dl, Chain, LROpOut, MachinePointerInfo(),
03409                           false, false, false, 0);
03410     Chain = SDValue(LROpOut.getNode(), 1);
03411 
03412     // When using the 32/64-bit SVR4 ABI there is no need to load the FP stack
03413     // slot as the FP is never overwritten.
03414     if (isDarwinABI) {
03415       FPOpOut = getFramePointerFrameIndex(DAG);
03416       FPOpOut = DAG.getLoad(VT, dl, Chain, FPOpOut, MachinePointerInfo(),
03417                             false, false, false, 0);
03418       Chain = SDValue(FPOpOut.getNode(), 1);
03419     }
03420   }
03421   return Chain;
03422 }
03423 
03424 /// CreateCopyOfByValArgument - Make a copy of an aggregate at address specified
03425 /// by "Src" to address "Dst" of size "Size".  Alignment information is
03426 /// specified by the specific parameter attribute. The copy will be passed as
03427 /// a byval function parameter.
03428 /// Sometimes what we are copying is the end of a larger object, the part that
03429 /// does not fit in registers.
03430 static SDValue
03431 CreateCopyOfByValArgument(SDValue Src, SDValue Dst, SDValue Chain,
03432                           ISD::ArgFlagsTy Flags, SelectionDAG &DAG,
03433                           SDLoc dl) {
03434   SDValue SizeNode = DAG.getConstant(Flags.getByValSize(), MVT::i32);
03435   return DAG.getMemcpy(Chain, dl, Dst, Src, SizeNode, Flags.getByValAlign(),
03436                        false, false, MachinePointerInfo(),
03437                        MachinePointerInfo());
03438 }
03439 
03440 /// LowerMemOpCallTo - Store the argument to the stack or remember it in case of
03441 /// tail calls.
03442 static void
03443 LowerMemOpCallTo(SelectionDAG &DAG, MachineFunction &MF, SDValue Chain,
03444                  SDValue Arg, SDValue PtrOff, int SPDiff,
03445                  unsigned ArgOffset, bool isPPC64, bool isTailCall,
03446                  bool isVector, SmallVectorImpl<SDValue> &MemOpChains,
03447                  SmallVectorImpl<TailCallArgumentInfo> &TailCallArguments,
03448                  SDLoc dl) {
03449   EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
03450   if (!isTailCall) {
03451     if (isVector) {
03452       SDValue StackPtr;
03453       if (isPPC64)
03454         StackPtr = DAG.getRegister(PPC::X1, MVT::i64);
03455       else
03456         StackPtr = DAG.getRegister(PPC::R1, MVT::i32);
03457       PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr,
03458                            DAG.getConstant(ArgOffset, PtrVT));
03459     }
03460     MemOpChains.push_back(DAG.getStore(Chain, dl, Arg, PtrOff,
03461                                        MachinePointerInfo(), false, false, 0));
03462   // Calculate and remember argument location.
03463   } else CalculateTailCallArgDest(DAG, MF, isPPC64, Arg, SPDiff, ArgOffset,
03464                                   TailCallArguments);
03465 }
03466 
03467 static
03468 void PrepareTailCall(SelectionDAG &DAG, SDValue &InFlag, SDValue &Chain,
03469                      SDLoc dl, bool isPPC64, int SPDiff, unsigned NumBytes,
03470                      SDValue LROp, SDValue FPOp, bool isDarwinABI,
03471                      SmallVectorImpl<TailCallArgumentInfo> &TailCallArguments) {
03472   MachineFunction &MF = DAG.getMachineFunction();
03473 
03474   // Emit a sequence of copyto/copyfrom virtual registers for arguments that
03475   // might overwrite each other in case of tail call optimization.
03476   SmallVector<SDValue, 8> MemOpChains2;
03477   // Do not flag preceding copytoreg stuff together with the following stuff.
03478   InFlag = SDValue();
03479   StoreTailCallArgumentsToStackSlot(DAG, Chain, TailCallArguments,
03480                                     MemOpChains2, dl);
03481   if (!MemOpChains2.empty())
03482     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains2);
03483 
03484   // Store the return address to the appropriate stack slot.
03485   Chain = EmitTailCallStoreFPAndRetAddr(DAG, MF, Chain, LROp, FPOp, SPDiff,
03486                                         isPPC64, isDarwinABI, dl);
03487 
03488   // Emit callseq_end just before tailcall node.
03489   Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, true),
03490                              DAG.getIntPtrConstant(0, true), InFlag, dl);
03491   InFlag = Chain.getValue(1);
03492 }
03493 
03494 static
03495 unsigned PrepareCall(SelectionDAG &DAG, SDValue &Callee, SDValue &InFlag,
03496                      SDValue &Chain, SDLoc dl, int SPDiff, bool isTailCall,
03497                      SmallVectorImpl<std::pair<unsigned, SDValue> > &RegsToPass,
03498                      SmallVectorImpl<SDValue> &Ops, std::vector<EVT> &NodeTys,
03499                      const PPCSubtarget &Subtarget) {
03500 
03501   bool isPPC64 = Subtarget.isPPC64();
03502   bool isSVR4ABI = Subtarget.isSVR4ABI();
03503   bool isELFv2ABI = Subtarget.isELFv2ABI();
03504 
03505   EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
03506   NodeTys.push_back(MVT::Other);   // Returns a chain
03507   NodeTys.push_back(MVT::Glue);    // Returns a flag for retval copy to use.
03508 
03509   unsigned CallOpc = PPCISD::CALL;
03510 
03511   bool needIndirectCall = true;
03512   if (!isSVR4ABI || !isPPC64)
03513     if (SDNode *Dest = isBLACompatibleAddress(Callee, DAG)) {
03514       // If this is an absolute destination address, use the munged value.
03515       Callee = SDValue(Dest, 0);
03516       needIndirectCall = false;
03517     }
03518 
03519   if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
03520     // XXX Work around for http://llvm.org/bugs/show_bug.cgi?id=5201
03521     // Use indirect calls for ALL functions calls in JIT mode, since the
03522     // far-call stubs may be outside relocation limits for a BL instruction.
03523     if (!DAG.getTarget().getSubtarget<PPCSubtarget>().isJITCodeModel()) {
03524       unsigned OpFlags = 0;
03525       if ((DAG.getTarget().getRelocationModel() != Reloc::Static &&
03526           (Subtarget.getTargetTriple().isMacOSX() &&
03527            Subtarget.getTargetTriple().isMacOSXVersionLT(10, 5)) &&
03528           (G->getGlobal()->isDeclaration() ||
03529            G->getGlobal()->isWeakForLinker())) ||
03530           (Subtarget.isTargetELF() && !isPPC64 &&
03531            !G->getGlobal()->hasLocalLinkage() &&
03532            DAG.getTarget().getRelocationModel() == Reloc::PIC_)) {
03533         // PC-relative references to external symbols should go through $stub,
03534         // unless we're building with the leopard linker or later, which
03535         // automatically synthesizes these stubs.
03536         OpFlags = PPCII::MO_PLT_OR_STUB;
03537       }
03538 
03539       // If the callee is a GlobalAddress/ExternalSymbol node (quite common,
03540       // every direct call is) turn it into a TargetGlobalAddress /
03541       // TargetExternalSymbol node so that legalize doesn't hack it.
03542       Callee = DAG.getTargetGlobalAddress(G->getGlobal(), dl,
03543                                           Callee.getValueType(),
03544                                           0, OpFlags);
03545       needIndirectCall = false;
03546     }
03547   }
03548 
03549   if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
03550     unsigned char OpFlags = 0;
03551 
03552     if ((DAG.getTarget().getRelocationModel() != Reloc::Static &&
03553          (Subtarget.getTargetTriple().isMacOSX() &&
03554           Subtarget.getTargetTriple().isMacOSXVersionLT(10, 5))) ||
03555         (Subtarget.isTargetELF() && !isPPC64 &&
03556          DAG.getTarget().getRelocationModel() == Reloc::PIC_) ) {
03557       // PC-relative references to external symbols should go through $stub,
03558       // unless we're building with the leopard linker or later, which
03559       // automatically synthesizes these stubs.
03560       OpFlags = PPCII::MO_PLT_OR_STUB;
03561     }
03562 
03563     Callee = DAG.getTargetExternalSymbol(S->getSymbol(), Callee.getValueType(),
03564                                          OpFlags);
03565     needIndirectCall = false;
03566   }
03567 
03568   if (needIndirectCall) {
03569     // Otherwise, this is an indirect call.  We have to use a MTCTR/BCTRL pair
03570     // to do the call, we can't use PPCISD::CALL.
03571     SDValue MTCTROps[] = {Chain, Callee, InFlag};
03572 
03573     if (isSVR4ABI && isPPC64 && !isELFv2ABI) {
03574       // Function pointers in the 64-bit SVR4 ABI do not point to the function
03575       // entry point, but to the function descriptor (the function entry point
03576       // address is part of the function descriptor though).
03577       // The function descriptor is a three doubleword structure with the
03578       // following fields: function entry point, TOC base address and
03579       // environment pointer.
03580       // Thus for a call through a function pointer, the following actions need
03581       // to be performed:
03582       //   1. Save the TOC of the caller in the TOC save area of its stack
03583       //      frame (this is done in LowerCall_Darwin() or LowerCall_64SVR4()).
03584       //   2. Load the address of the function entry point from the function
03585       //      descriptor.
03586       //   3. Load the TOC of the callee from the function descriptor into r2.
03587       //   4. Load the environment pointer from the function descriptor into
03588       //      r11.
03589       //   5. Branch to the function entry point address.
03590       //   6. On return of the callee, the TOC of the caller needs to be
03591       //      restored (this is done in FinishCall()).
03592       //
03593       // All those operations are flagged together to ensure that no other
03594       // operations can be scheduled in between. E.g. without flagging the
03595       // operations together, a TOC access in the caller could be scheduled
03596       // between the load of the callee TOC and the branch to the callee, which
03597       // results in the TOC access going through the TOC of the callee instead
03598       // of going through the TOC of the caller, which leads to incorrect code.
03599 
03600       // Load the address of the function entry point from the function
03601       // descriptor.
03602       SDVTList VTs = DAG.getVTList(MVT::i64, MVT::Other, MVT::Glue);
03603       SDValue LoadFuncPtr = DAG.getNode(PPCISD::LOAD, dl, VTs,
03604                               makeArrayRef(MTCTROps, InFlag.getNode() ? 3 : 2));
03605       Chain = LoadFuncPtr.getValue(1);
03606       InFlag = LoadFuncPtr.getValue(2);
03607 
03608       // Load environment pointer into r11.
03609       // Offset of the environment pointer within the function descriptor.
03610       SDValue PtrOff = DAG.getIntPtrConstant(16);
03611 
03612       SDValue AddPtr = DAG.getNode(ISD::ADD, dl, MVT::i64, Callee, PtrOff);
03613       SDValue LoadEnvPtr = DAG.getNode(PPCISD::LOAD, dl, VTs, Chain, AddPtr,
03614                                        InFlag);
03615       Chain = LoadEnvPtr.getValue(1);
03616       InFlag = LoadEnvPtr.getValue(2);
03617 
03618       SDValue EnvVal = DAG.getCopyToReg(Chain, dl, PPC::X11, LoadEnvPtr,
03619                                         InFlag);
03620       Chain = EnvVal.getValue(0);
03621       InFlag = EnvVal.getValue(1);
03622 
03623       // Load TOC of the callee into r2. We are using a target-specific load
03624       // with r2 hard coded, because the result of a target-independent load
03625       // would never go directly into r2, since r2 is a reserved register (which
03626       // prevents the register allocator from allocating it), resulting in an
03627       // additional register being allocated and an unnecessary move instruction
03628       // being generated.
03629       VTs = DAG.getVTList(MVT::Other, MVT::Glue);
03630       SDValue TOCOff = DAG.getIntPtrConstant(8);
03631       SDValue AddTOC = DAG.getNode(ISD::ADD, dl, MVT::i64, Callee, TOCOff);
03632       SDValue LoadTOCPtr = DAG.getNode(PPCISD::LOAD_TOC, dl, VTs, Chain,
03633                                        AddTOC, InFlag);
03634       Chain = LoadTOCPtr.getValue(0);
03635       InFlag = LoadTOCPtr.getValue(1);
03636 
03637       MTCTROps[0] = Chain;
03638       MTCTROps[1] = LoadFuncPtr;
03639       MTCTROps[2] = InFlag;
03640     }
03641 
03642     Chain = DAG.getNode(PPCISD::MTCTR, dl, NodeTys,
03643                         makeArrayRef(MTCTROps, InFlag.getNode() ? 3 : 2));
03644     InFlag = Chain.getValue(1);
03645 
03646     NodeTys.clear();
03647     NodeTys.push_back(MVT::Other);
03648     NodeTys.push_back(MVT::Glue);
03649     Ops.push_back(Chain);
03650     CallOpc = PPCISD::BCTRL;
03651     Callee.setNode(nullptr);
03652     // Add use of X11 (holding environment pointer)
03653     if (isSVR4ABI && isPPC64 && !isELFv2ABI)
03654       Ops.push_back(DAG.getRegister(PPC::X11, PtrVT));
03655     // Add CTR register as callee so a bctr can be emitted later.
03656     if (isTailCall)
03657       Ops.push_back(DAG.getRegister(isPPC64 ? PPC::CTR8 : PPC::CTR, PtrVT));
03658   }
03659 
03660   // If this is a direct call, pass the chain and the callee.
03661   if (Callee.getNode()) {
03662     Ops.push_back(Chain);
03663     Ops.push_back(Callee);
03664   }
03665   // If this is a tail call add stack pointer delta.
03666   if (isTailCall)
03667     Ops.push_back(DAG.getConstant(SPDiff, MVT::i32));
03668 
03669   // Add argument registers to the end of the list so that they are known live
03670   // into the call.
03671   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
03672     Ops.push_back(DAG.getRegister(RegsToPass[i].first,
03673                                   RegsToPass[i].second.getValueType()));
03674 
03675   // Direct calls in the ELFv2 ABI need the TOC register live into the call.
03676   if (Callee.getNode() && isELFv2ABI)
03677     Ops.push_back(DAG.getRegister(PPC::X2, PtrVT));
03678 
03679   return CallOpc;
03680 }
03681 
03682 static
03683 bool isLocalCall(const SDValue &Callee)
03684 {
03685   if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee))
03686     return !G->getGlobal()->isDeclaration() &&
03687            !G->getGlobal()->isWeakForLinker();
03688   return false;
03689 }
03690 
03691 SDValue
03692 PPCTargetLowering::LowerCallResult(SDValue Chain, SDValue InFlag,
03693                                    CallingConv::ID CallConv, bool isVarArg,
03694                                    const SmallVectorImpl<ISD::InputArg> &Ins,
03695                                    SDLoc dl, SelectionDAG &DAG,
03696                                    SmallVectorImpl<SDValue> &InVals) const {
03697 
03698   SmallVector<CCValAssign, 16> RVLocs;
03699   CCState CCRetInfo(CallConv, isVarArg, DAG.getMachineFunction(),
03700                     getTargetMachine(), RVLocs, *DAG.getContext());
03701   CCRetInfo.AnalyzeCallResult(Ins, RetCC_PPC);
03702 
03703   // Copy all of the result registers out of their specified physreg.
03704   for (unsigned i = 0, e = RVLocs.size(); i != e; ++i) {
03705     CCValAssign &VA = RVLocs[i];
03706     assert(VA.isRegLoc() && "Can only return in registers!");
03707 
03708     SDValue Val = DAG.getCopyFromReg(Chain, dl,
03709                                      VA.getLocReg(), VA.getLocVT(), InFlag);
03710     Chain = Val.getValue(1);
03711     InFlag = Val.getValue(2);
03712 
03713     switch (VA.getLocInfo()) {
03714     default: llvm_unreachable("Unknown loc info!");
03715     case CCValAssign::Full: break;
03716     case CCValAssign::AExt:
03717       Val = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), Val);
03718       break;
03719     case CCValAssign::ZExt:
03720       Val = DAG.getNode(ISD::AssertZext, dl, VA.getLocVT(), Val,
03721                         DAG.getValueType(VA.getValVT()));
03722       Val = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), Val);
03723       break;
03724     case CCValAssign::SExt:
03725       Val = DAG.getNode(ISD::AssertSext, dl, VA.getLocVT(), Val,
03726                         DAG.getValueType(VA.getValVT()));
03727       Val = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), Val);
03728       break;
03729     }
03730 
03731     InVals.push_back(Val);
03732   }
03733 
03734   return Chain;
03735 }
03736 
03737 SDValue
03738 PPCTargetLowering::FinishCall(CallingConv::ID CallConv, SDLoc dl,
03739                               bool isTailCall, bool isVarArg,
03740                               SelectionDAG &DAG,
03741                               SmallVector<std::pair<unsigned, SDValue>, 8>
03742                                 &RegsToPass,
03743                               SDValue InFlag, SDValue Chain,
03744                               SDValue &Callee,
03745                               int SPDiff, unsigned NumBytes,
03746                               const SmallVectorImpl<ISD::InputArg> &Ins,
03747                               SmallVectorImpl<SDValue> &InVals) const {
03748 
03749   bool isELFv2ABI = Subtarget.isELFv2ABI();
03750   std::vector<EVT> NodeTys;
03751   SmallVector<SDValue, 8> Ops;
03752   unsigned CallOpc = PrepareCall(DAG, Callee, InFlag, Chain, dl, SPDiff,
03753                                  isTailCall, RegsToPass, Ops, NodeTys,
03754                                  Subtarget);
03755 
03756   // Add implicit use of CR bit 6 for 32-bit SVR4 vararg calls
03757   if (isVarArg && Subtarget.isSVR4ABI() && !Subtarget.isPPC64())
03758     Ops.push_back(DAG.getRegister(PPC::CR1EQ, MVT::i32));
03759 
03760   // When performing tail call optimization the callee pops its arguments off
03761   // the stack. Account for this here so these bytes can be pushed back on in
03762   // PPCFrameLowering::eliminateCallFramePseudoInstr.
03763   int BytesCalleePops =
03764     (CallConv == CallingConv::Fast &&
03765      getTargetMachine().Options.GuaranteedTailCallOpt) ? NumBytes : 0;
03766 
03767   // Add a register mask operand representing the call-preserved registers.
03768   const TargetRegisterInfo *TRI = getTargetMachine().getRegisterInfo();
03769   const uint32_t *Mask = TRI->getCallPreservedMask(CallConv);
03770   assert(Mask && "Missing call preserved mask for calling convention");
03771   Ops.push_back(DAG.getRegisterMask(Mask));
03772 
03773   if (InFlag.getNode())
03774     Ops.push_back(InFlag);
03775 
03776   // Emit tail call.
03777   if (isTailCall) {
03778     assert(((Callee.getOpcode() == ISD::Register &&
03779              cast<RegisterSDNode>(Callee)->getReg() == PPC::CTR) ||
03780             Callee.getOpcode() == ISD::TargetExternalSymbol ||
03781             Callee.getOpcode() == ISD::TargetGlobalAddress ||
03782             isa<ConstantSDNode>(Callee)) &&
03783     "Expecting an global address, external symbol, absolute value or register");
03784 
03785     return DAG.getNode(PPCISD::TC_RETURN, dl, MVT::Other, Ops);
03786   }
03787 
03788   // Add a NOP immediately after the branch instruction when using the 64-bit
03789   // SVR4 ABI. At link time, if caller and callee are in a different module and
03790   // thus have a different TOC, the call will be replaced with a call to a stub
03791   // function which saves the current TOC, loads the TOC of the callee and
03792   // branches to the callee. The NOP will be replaced with a load instruction
03793   // which restores the TOC of the caller from the TOC save slot of the current
03794   // stack frame. If caller and callee belong to the same module (and have the
03795   // same TOC), the NOP will remain unchanged.
03796 
03797   bool needsTOCRestore = false;
03798   if (!isTailCall && Subtarget.isSVR4ABI()&& Subtarget.isPPC64()) {
03799     if (CallOpc == PPCISD::BCTRL) {
03800       // This is a call through a function pointer.
03801       // Restore the caller TOC from the save area into R2.
03802       // See PrepareCall() for more information about calls through function
03803       // pointers in the 64-bit SVR4 ABI.
03804       // We are using a target-specific load with r2 hard coded, because the
03805       // result of a target-independent load would never go directly into r2,
03806       // since r2 is a reserved register (which prevents the register allocator
03807       // from allocating it), resulting in an additional register being
03808       // allocated and an unnecessary move instruction being generated.
03809       needsTOCRestore = true;
03810     } else if ((CallOpc == PPCISD::CALL) &&
03811                (!isLocalCall(Callee) ||
03812                 DAG.getTarget().getRelocationModel() == Reloc::PIC_)) {
03813       // Otherwise insert NOP for non-local calls.
03814       CallOpc = PPCISD::CALL_NOP;
03815     }
03816   }
03817 
03818   Chain = DAG.getNode(CallOpc, dl, NodeTys, Ops);
03819   InFlag = Chain.getValue(1);
03820 
03821   if (needsTOCRestore) {
03822     SDVTList VTs = DAG.getVTList(MVT::Other, MVT::Glue);
03823     EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
03824     SDValue StackPtr = DAG.getRegister(PPC::X1, PtrVT);
03825     unsigned TOCSaveOffset = PPCFrameLowering::getTOCSaveOffset(isELFv2ABI);
03826     SDValue TOCOff = DAG.getIntPtrConstant(TOCSaveOffset);
03827     SDValue AddTOC = DAG.getNode(ISD::ADD, dl, MVT::i64, StackPtr, TOCOff);
03828     Chain = DAG.getNode(PPCISD::LOAD_TOC, dl, VTs, Chain, AddTOC, InFlag);
03829     InFlag = Chain.getValue(1);
03830   }
03831 
03832   Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, true),
03833                              DAG.getIntPtrConstant(BytesCalleePops, true),
03834                              InFlag, dl);
03835   if (!Ins.empty())
03836     InFlag = Chain.getValue(1);
03837 
03838   return LowerCallResult(Chain, InFlag, CallConv, isVarArg,
03839                          Ins, dl, DAG, InVals);
03840 }
03841 
03842 SDValue
03843 PPCTargetLowering::LowerCall(TargetLowering::CallLoweringInfo &CLI,
03844                              SmallVectorImpl<SDValue> &InVals) const {
03845   SelectionDAG &DAG                     = CLI.DAG;
03846   SDLoc &dl                             = CLI.DL;
03847   SmallVectorImpl<ISD::OutputArg> &Outs = CLI.Outs;
03848   SmallVectorImpl<SDValue> &OutVals     = CLI.OutVals;
03849   SmallVectorImpl<ISD::InputArg> &Ins   = CLI.Ins;
03850   SDValue Chain                         = CLI.Chain;
03851   SDValue Callee                        = CLI.Callee;
03852   bool &isTailCall                      = CLI.IsTailCall;
03853   CallingConv::ID CallConv              = CLI.CallConv;
03854   bool isVarArg                         = CLI.IsVarArg;
03855 
03856   if (isTailCall)
03857     isTailCall = IsEligibleForTailCallOptimization(Callee, CallConv, isVarArg,
03858                                                    Ins, DAG);
03859 
03860   if (!isTailCall && CLI.CS && CLI.CS->isMustTailCall())
03861     report_fatal_error("failed to perform tail call elimination on a call "
03862                        "site marked musttail");
03863 
03864   if (Subtarget.isSVR4ABI()) {
03865     if (Subtarget.isPPC64())
03866       return LowerCall_64SVR4(Chain, Callee, CallConv, isVarArg,
03867                               isTailCall, Outs, OutVals, Ins,
03868                               dl, DAG, InVals);
03869     else
03870       return LowerCall_32SVR4(Chain, Callee, CallConv, isVarArg,
03871                               isTailCall, Outs, OutVals, Ins,
03872                               dl, DAG, InVals);
03873   }
03874 
03875   return LowerCall_Darwin(Chain, Callee, CallConv, isVarArg,
03876                           isTailCall, Outs, OutVals, Ins,
03877                           dl, DAG, InVals);
03878 }
03879 
03880 SDValue
03881 PPCTargetLowering::LowerCall_32SVR4(SDValue Chain, SDValue Callee,
03882                                     CallingConv::ID CallConv, bool isVarArg,
03883                                     bool isTailCall,
03884                                     const SmallVectorImpl<ISD::OutputArg> &Outs,
03885                                     const SmallVectorImpl<SDValue> &OutVals,
03886                                     const SmallVectorImpl<ISD::InputArg> &Ins,
03887                                     SDLoc dl, SelectionDAG &DAG,
03888                                     SmallVectorImpl<SDValue> &InVals) const {
03889   // See PPCTargetLowering::LowerFormalArguments_32SVR4() for a description
03890   // of the 32-bit SVR4 ABI stack frame layout.
03891 
03892   assert((CallConv == CallingConv::C ||
03893           CallConv == CallingConv::Fast) && "Unknown calling convention!");
03894 
03895   unsigned PtrByteSize = 4;
03896 
03897   MachineFunction &MF = DAG.getMachineFunction();
03898 
03899   // Mark this function as potentially containing a function that contains a
03900   // tail call. As a consequence the frame pointer will be used for dynamicalloc
03901   // and restoring the callers stack pointer in this functions epilog. This is
03902   // done because by tail calling the called function might overwrite the value
03903   // in this function's (MF) stack pointer stack slot 0(SP).
03904   if (getTargetMachine().Options.GuaranteedTailCallOpt &&
03905       CallConv == CallingConv::Fast)
03906     MF.getInfo<PPCFunctionInfo>()->setHasFastCall();
03907 
03908   // Count how many bytes are to be pushed on the stack, including the linkage
03909   // area, parameter list area and the part of the local variable space which
03910   // contains copies of aggregates which are passed by value.
03911 
03912   // Assign locations to all of the outgoing arguments.
03913   SmallVector<CCValAssign, 16> ArgLocs;
03914   CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(),
03915                  getTargetMachine(), ArgLocs, *DAG.getContext());
03916 
03917   // Reserve space for the linkage area on the stack.
03918   CCInfo.AllocateStack(PPCFrameLowering::getLinkageSize(false, false, false),
03919                        PtrByteSize);
03920 
03921   if (isVarArg) {
03922     // Handle fixed and variable vector arguments differently.
03923     // Fixed vector arguments go into registers as long as registers are
03924     // available. Variable vector arguments always go into memory.
03925     unsigned NumArgs = Outs.size();
03926 
03927     for (unsigned i = 0; i != NumArgs; ++i) {
03928       MVT ArgVT = Outs[i].VT;
03929       ISD::ArgFlagsTy ArgFlags = Outs[i].Flags;
03930       bool Result;
03931 
03932       if (Outs[i].IsFixed) {
03933         Result = CC_PPC32_SVR4(i, ArgVT, ArgVT, CCValAssign::Full, ArgFlags,
03934                                CCInfo);
03935       } else {
03936         Result = CC_PPC32_SVR4_VarArg(i, ArgVT, ArgVT, CCValAssign::Full,
03937                                       ArgFlags, CCInfo);
03938       }
03939 
03940       if (Result) {
03941 #ifndef NDEBUG
03942         errs() << "Call operand #" << i << " has unhandled type "
03943              << EVT(ArgVT).getEVTString() << "\n";
03944 #endif
03945         llvm_unreachable(nullptr);
03946       }
03947     }
03948   } else {
03949     // All arguments are treated the same.
03950     CCInfo.AnalyzeCallOperands(Outs, CC_PPC32_SVR4);
03951   }
03952 
03953   // Assign locations to all of the outgoing aggregate by value arguments.
03954   SmallVector<CCValAssign, 16> ByValArgLocs;
03955   CCState CCByValInfo(CallConv, isVarArg, DAG.getMachineFunction(),
03956                       getTargetMachine(), ByValArgLocs, *DAG.getContext());
03957 
03958   // Reserve stack space for the allocations in CCInfo.
03959   CCByValInfo.AllocateStack(CCInfo.getNextStackOffset(), PtrByteSize);
03960 
03961   CCByValInfo.AnalyzeCallOperands(Outs, CC_PPC32_SVR4_ByVal);
03962 
03963   // Size of the linkage area, parameter list area and the part of the local
03964   // space variable where copies of aggregates which are passed by value are
03965   // stored.
03966   unsigned NumBytes = CCByValInfo.getNextStackOffset();
03967 
03968   // Calculate by how many bytes the stack has to be adjusted in case of tail
03969   // call optimization.
03970   int SPDiff = CalculateTailCallSPDiff(DAG, isTailCall, NumBytes);
03971 
03972   // Adjust the stack pointer for the new arguments...
03973   // These operations are automatically eliminated by the prolog/epilog pass
03974   Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(NumBytes, true),
03975                                dl);
03976   SDValue CallSeqStart = Chain;
03977 
03978   // Load the return address and frame pointer so it can be moved somewhere else
03979   // later.
03980   SDValue LROp, FPOp;
03981   Chain = EmitTailCallLoadFPAndRetAddr(DAG, SPDiff, Chain, LROp, FPOp, false,
03982                                        dl);
03983 
03984   // Set up a copy of the stack pointer for use loading and storing any
03985   // arguments that may not fit in the registers available for argument
03986   // passing.
03987   SDValue StackPtr = DAG.getRegister(PPC::R1, MVT::i32);
03988 
03989   SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
03990   SmallVector<TailCallArgumentInfo, 8> TailCallArguments;
03991   SmallVector<SDValue, 8> MemOpChains;
03992 
03993   bool seenFloatArg = false;
03994   // Walk the register/memloc assignments, inserting copies/loads.
03995   for (unsigned i = 0, j = 0, e = ArgLocs.size();
03996        i != e;
03997        ++i) {
03998     CCValAssign &VA = ArgLocs[i];
03999     SDValue Arg = OutVals[i];
04000     ISD::ArgFlagsTy Flags = Outs[i].Flags;
04001 
04002     if (Flags.isByVal()) {
04003       // Argument is an aggregate which is passed by value, thus we need to
04004       // create a copy of it in the local variable space of the current stack
04005       // frame (which is the stack frame of the caller) and pass the address of
04006       // this copy to the callee.
04007       assert((j < ByValArgLocs.size()) && "Index out of bounds!");
04008       CCValAssign &ByValVA = ByValArgLocs[j++];
04009       assert((VA.getValNo() == ByValVA.getValNo()) && "ValNo mismatch!");
04010 
04011       // Memory reserved in the local variable space of the callers stack frame.
04012       unsigned LocMemOffset = ByValVA.getLocMemOffset();
04013 
04014       SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset);
04015       PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, PtrOff);
04016 
04017       // Create a copy of the argument in the local area of the current
04018       // stack frame.
04019       SDValue MemcpyCall =
04020         CreateCopyOfByValArgument(Arg, PtrOff,
04021                                   CallSeqStart.getNode()->getOperand(0),
04022                                   Flags, DAG, dl);
04023 
04024       // This must go outside the CALLSEQ_START..END.
04025       SDValue NewCallSeqStart = DAG.getCALLSEQ_START(MemcpyCall,
04026                            CallSeqStart.getNode()->getOperand(1),
04027                            SDLoc(MemcpyCall));
04028       DAG.ReplaceAllUsesWith(CallSeqStart.getNode(),
04029                              NewCallSeqStart.getNode());
04030       Chain = CallSeqStart = NewCallSeqStart;
04031 
04032       // Pass the address of the aggregate copy on the stack either in a
04033       // physical register or in the parameter list area of the current stack
04034       // frame to the callee.
04035       Arg = PtrOff;
04036     }
04037 
04038     if (VA.isRegLoc()) {
04039       if (Arg.getValueType() == MVT::i1)
04040         Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, Arg);
04041 
04042       seenFloatArg |= VA.getLocVT().isFloatingPoint();
04043       // Put argument in a physical register.
04044       RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
04045     } else {
04046       // Put argument in the parameter list area of the current stack frame.
04047       assert(VA.isMemLoc());
04048       unsigned LocMemOffset = VA.getLocMemOffset();
04049 
04050       if (!isTailCall) {
04051         SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset);
04052         PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, PtrOff);
04053 
04054         MemOpChains.push_back(DAG.getStore(Chain, dl, Arg, PtrOff,
04055                                            MachinePointerInfo(),
04056                                            false, false, 0));
04057       } else {
04058         // Calculate and remember argument location.
04059         CalculateTailCallArgDest(DAG, MF, false, Arg, SPDiff, LocMemOffset,
04060                                  TailCallArguments);
04061       }
04062     }
04063   }
04064 
04065   if (!MemOpChains.empty())
04066     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains);
04067 
04068   // Build a sequence of copy-to-reg nodes chained together with token chain
04069   // and flag operands which copy the outgoing args into the appropriate regs.
04070   SDValue InFlag;
04071   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
04072     Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
04073                              RegsToPass[i].second, InFlag);
04074     InFlag = Chain.getValue(1);
04075   }
04076 
04077   // Set CR bit 6 to true if this is a vararg call with floating args passed in
04078   // registers.
04079   if (isVarArg) {
04080     SDVTList VTs = DAG.getVTList(MVT::Other, MVT::Glue);
04081     SDValue Ops[] = { Chain, InFlag };
04082 
04083     Chain = DAG.getNode(seenFloatArg ? PPCISD::CR6SET : PPCISD::CR6UNSET,
04084                         dl, VTs, makeArrayRef(Ops, InFlag.getNode() ? 2 : 1));
04085 
04086     InFlag = Chain.getValue(1);
04087   }
04088 
04089   if (isTailCall)
04090     PrepareTailCall(DAG, InFlag, Chain, dl, false, SPDiff, NumBytes, LROp, FPOp,
04091                     false, TailCallArguments);
04092 
04093   return FinishCall(CallConv, dl, isTailCall, isVarArg, DAG,
04094                     RegsToPass, InFlag, Chain, Callee, SPDiff, NumBytes,
04095                     Ins, InVals);
04096 }
04097 
04098 // Copy an argument into memory, being careful to do this outside the
04099 // call sequence for the call to which the argument belongs.
04100 SDValue
04101 PPCTargetLowering::createMemcpyOutsideCallSeq(SDValue Arg, SDValue PtrOff,
04102                                               SDValue CallSeqStart,
04103                                               ISD::ArgFlagsTy Flags,
04104                                               SelectionDAG &DAG,
04105                                               SDLoc dl) const {
04106   SDValue MemcpyCall = CreateCopyOfByValArgument(Arg, PtrOff,
04107                         CallSeqStart.getNode()->getOperand(0),
04108                         Flags, DAG, dl);
04109   // The MEMCPY must go outside the CALLSEQ_START..END.
04110   SDValue NewCallSeqStart = DAG.getCALLSEQ_START(MemcpyCall,
04111                              CallSeqStart.getNode()->getOperand(1),
04112                              SDLoc(MemcpyCall));
04113   DAG.ReplaceAllUsesWith(CallSeqStart.getNode(),
04114                          NewCallSeqStart.getNode());
04115   return NewCallSeqStart;
04116 }
04117 
04118 SDValue
04119 PPCTargetLowering::LowerCall_64SVR4(SDValue Chain, SDValue Callee,
04120                                     CallingConv::ID CallConv, bool isVarArg,
04121                                     bool isTailCall,
04122                                     const SmallVectorImpl<ISD::OutputArg> &Outs,
04123                                     const SmallVectorImpl<SDValue> &OutVals,
04124                                     const SmallVectorImpl<ISD::InputArg> &Ins,
04125                                     SDLoc dl, SelectionDAG &DAG,
04126                                     SmallVectorImpl<SDValue> &InVals) const {
04127 
04128   bool isELFv2ABI = Subtarget.isELFv2ABI();
04129   bool isLittleEndian = Subtarget.isLittleEndian();
04130   unsigned NumOps = Outs.size();
04131 
04132   EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
04133   unsigned PtrByteSize = 8;
04134 
04135   MachineFunction &MF = DAG.getMachineFunction();
04136 
04137   // Mark this function as potentially containing a function that contains a
04138   // tail call. As a consequence the frame pointer will be used for dynamicalloc
04139   // and restoring the callers stack pointer in this functions epilog. This is
04140   // done because by tail calling the called function might overwrite the value
04141   // in this function's (MF) stack pointer stack slot 0(SP).
04142   if (getTargetMachine().Options.GuaranteedTailCallOpt &&
04143       CallConv == CallingConv::Fast)
04144     MF.getInfo<PPCFunctionInfo>()->setHasFastCall();
04145 
04146   // Count how many bytes are to be pushed on the stack, including the linkage
04147   // area, and parameter passing area.  On ELFv1, the linkage area is 48 bytes
04148   // reserved space for [SP][CR][LR][2 x unused][TOC]; on ELFv2, the linkage
04149   // area is 32 bytes reserved space for [SP][CR][LR][TOC].
04150   unsigned LinkageSize = PPCFrameLowering::getLinkageSize(true, false,
04151                                                           isELFv2ABI);
04152   unsigned NumBytes = LinkageSize;
04153 
04154   // Add up all the space actually used.
04155   for (unsigned i = 0; i != NumOps; ++i) {
04156     ISD::ArgFlagsTy Flags = Outs[i].Flags;
04157     EVT ArgVT = Outs[i].VT;
04158     EVT OrigVT = Outs[i].ArgVT;
04159 
04160     /* Respect alignment of argument on the stack.  */
04161     unsigned Align =
04162       CalculateStackSlotAlignment(ArgVT, OrigVT, Flags, PtrByteSize);
04163     NumBytes = ((NumBytes + Align - 1) / Align) * Align;
04164 
04165     NumBytes += CalculateStackSlotSize(ArgVT, Flags, PtrByteSize);
04166     if (Flags.isInConsecutiveRegsLast())
04167       NumBytes = ((NumBytes + PtrByteSize - 1)/PtrByteSize) * PtrByteSize;
04168   }
04169 
04170   unsigned NumBytesActuallyUsed = NumBytes;
04171 
04172   // The prolog code of the callee may store up to 8 GPR argument registers to
04173   // the stack, allowing va_start to index over them in memory if its varargs.
04174   // Because we cannot tell if this is needed on the caller side, we have to
04175   // conservatively assume that it is needed.  As such, make sure we have at
04176   // least enough stack space for the caller to store the 8 GPRs.
04177   // FIXME: On ELFv2, it may be unnecessary to allocate the parameter area.
04178   NumBytes = std::max(NumBytes, LinkageSize + 8 * PtrByteSize);
04179 
04180   // Tail call needs the stack to be aligned.
04181   if (getTargetMachine().Options.GuaranteedTailCallOpt &&
04182       CallConv == CallingConv::Fast)
04183     NumBytes = EnsureStackAlignment(MF.getTarget(), NumBytes);
04184 
04185   // Calculate by how many bytes the stack has to be adjusted in case of tail
04186   // call optimization.
04187   int SPDiff = CalculateTailCallSPDiff(DAG, isTailCall, NumBytes);
04188 
04189   // To protect arguments on the stack from being clobbered in a tail call,
04190   // force all the loads to happen before doing any other lowering.
04191   if (isTailCall)
04192     Chain = DAG.getStackArgumentTokenFactor(Chain);
04193 
04194   // Adjust the stack pointer for the new arguments...
04195   // These operations are automatically eliminated by the prolog/epilog pass
04196   Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(NumBytes, true),
04197                                dl);
04198   SDValue CallSeqStart = Chain;
04199 
04200   // Load the return address and frame pointer so it can be move somewhere else
04201   // later.
04202   SDValue LROp, FPOp;
04203   Chain = EmitTailCallLoadFPAndRetAddr(DAG, SPDiff, Chain, LROp, FPOp, true,
04204                                        dl);
04205 
04206   // Set up a copy of the stack pointer for use loading and storing any
04207   // arguments that may not fit in the registers available for argument
04208   // passing.
04209   SDValue StackPtr = DAG.getRegister(PPC::X1, MVT::i64);
04210 
04211   // Figure out which arguments are going to go in registers, and which in
04212   // memory.  Also, if this is a vararg function, floating point operations
04213   // must be stored to our stack, and loaded into integer regs as well, if
04214   // any integer regs are available for argument passing.
04215   unsigned ArgOffset = LinkageSize;
04216   unsigned GPR_idx, FPR_idx = 0, VR_idx = 0;
04217 
04218   static const MCPhysReg GPR[] = {
04219     PPC::X3, PPC::X4, PPC::X5, PPC::X6,
04220     PPC::X7, PPC::X8, PPC::X9, PPC::X10,
04221   };
04222   static const MCPhysReg *FPR = GetFPR();
04223 
04224   static const MCPhysReg VR[] = {
04225     PPC::V2, PPC::V3, PPC::V4, PPC::V5, PPC::V6, PPC::V7, PPC::V8,
04226     PPC::V9, PPC::V10, PPC::V11, PPC::V12, PPC::V13
04227   };
04228   static const MCPhysReg VSRH[] = {
04229     PPC::VSH2, PPC::VSH3, PPC::VSH4, PPC::VSH5, PPC::VSH6, PPC::VSH7, PPC::VSH8,
04230     PPC::VSH9, PPC::VSH10, PPC::VSH11, PPC::VSH12, PPC::VSH13
04231   };
04232 
04233   const unsigned NumGPRs = array_lengthof(GPR);
04234   const unsigned NumFPRs = 13;
04235   const unsigned NumVRs  = array_lengthof(VR);
04236 
04237   SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
04238   SmallVector<TailCallArgumentInfo, 8> TailCallArguments;
04239 
04240   SmallVector<SDValue, 8> MemOpChains;
04241   for (unsigned i = 0; i != NumOps; ++i) {
04242     SDValue Arg = OutVals[i];
04243     ISD::ArgFlagsTy Flags = Outs[i].Flags;
04244     EVT ArgVT = Outs[i].VT;
04245     EVT OrigVT = Outs[i].ArgVT;
04246 
04247     /* Respect alignment of argument on the stack.  */
04248     unsigned Align =
04249       CalculateStackSlotAlignment(ArgVT, OrigVT, Flags, PtrByteSize);
04250     ArgOffset = ((ArgOffset + Align - 1) / Align) * Align;
04251 
04252     /* Compute GPR index associated with argument offset.  */
04253     GPR_idx = (ArgOffset - LinkageSize) / PtrByteSize;
04254     GPR_idx = std::min(GPR_idx, NumGPRs);
04255 
04256     // PtrOff will be used to store the current argument to the stack if a
04257     // register cannot be found for it.
04258     SDValue PtrOff;
04259 
04260     PtrOff = DAG.getConstant(ArgOffset, StackPtr.getValueType());
04261 
04262     PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, PtrOff);
04263 
04264     // Promote integers to 64-bit values.
04265     if (Arg.getValueType() == MVT::i32 || Arg.getValueType() == MVT::i1) {
04266       // FIXME: Should this use ANY_EXTEND if neither sext nor zext?
04267       unsigned ExtOp = Flags.isSExt() ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
04268       Arg = DAG.getNode(ExtOp, dl, MVT::i64, Arg);
04269     }
04270 
04271     // FIXME memcpy is used way more than necessary.  Correctness first.
04272     // Note: "by value" is code for passing a structure by value, not
04273     // basic types.
04274     if (Flags.isByVal()) {
04275       // Note: Size includes alignment padding, so
04276       //   struct x { short a; char b; }
04277       // will have Size = 4.  With #pragma pack(1), it will have Size = 3.
04278       // These are the proper values we need for right-justifying the
04279       // aggregate in a parameter register.
04280       unsigned Size = Flags.getByValSize();
04281 
04282       // An empty aggregate parameter takes up no storage and no
04283       // registers.
04284       if (Size == 0)
04285         continue;
04286 
04287       // All aggregates smaller than 8 bytes must be passed right-justified.
04288       if (Size==1 || Size==2 || Size==4) {
04289         EVT VT = (Size==1) ? MVT::i8 : ((Size==2) ? MVT::i16 : MVT::i32);
04290         if (GPR_idx != NumGPRs) {
04291           SDValue Load = DAG.getExtLoad(ISD::EXTLOAD, dl, PtrVT, Chain, Arg,
04292                                         MachinePointerInfo(), VT,
04293                                         false, false, 0);
04294           MemOpChains.push_back(Load.getValue(1));
04295           RegsToPass.push_back(std::make_pair(GPR[GPR_idx], Load));
04296 
04297           ArgOffset += PtrByteSize;
04298           continue;
04299         }
04300       }
04301 
04302       if (GPR_idx == NumGPRs && Size < 8) {
04303         SDValue AddPtr = PtrOff;
04304         if (!isLittleEndian) {
04305           SDValue Const = DAG.getConstant(PtrByteSize - Size,
04306                                           PtrOff.getValueType());
04307           AddPtr = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, Const);
04308         }
04309         Chain = CallSeqStart = createMemcpyOutsideCallSeq(Arg, AddPtr,
04310                                                           CallSeqStart,
04311                                                           Flags, DAG, dl);
04312         ArgOffset += PtrByteSize;
04313         continue;
04314       }
04315       // Copy entire object into memory.  There are cases where gcc-generated
04316       // code assumes it is there, even if it could be put entirely into
04317       // registers.  (This is not what the doc says.)
04318 
04319       // FIXME: The above statement is likely due to a misunderstanding of the
04320       // documents.  All arguments must be copied into the parameter area BY
04321       // THE CALLEE in the event that the callee takes the address of any
04322       // formal argument.  That has not yet been implemented.  However, it is
04323       // reasonable to use the stack area as a staging area for the register
04324       // load.
04325 
04326       // Skip this for small aggregates, as we will use the same slot for a
04327       // right-justified copy, below.
04328       if (Size >= 8)
04329         Chain = CallSeqStart = createMemcpyOutsideCallSeq(Arg, PtrOff,
04330                                                           CallSeqStart,
04331                                                           Flags, DAG, dl);
04332 
04333       // When a register is available, pass a small aggregate right-justified.
04334       if (Size < 8 && GPR_idx != NumGPRs) {
04335         // The easiest way to get this right-justified in a register
04336         // is to copy the structure into the rightmost portion of a
04337         // local variable slot, then load the whole slot into the
04338         // register.
04339         // FIXME: The memcpy seems to produce pretty awful code for
04340         // small aggregates, particularly for packed ones.
04341         // FIXME: It would be preferable to use the slot in the
04342         // parameter save area instead of a new local variable.
04343         SDValue AddPtr = PtrOff;
04344         if (!isLittleEndian) {
04345           SDValue Const = DAG.getConstant(8 - Size, PtrOff.getValueType());
04346           AddPtr = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, Const);
04347         }
04348         Chain = CallSeqStart = createMemcpyOutsideCallSeq(Arg, AddPtr,
04349                                                           CallSeqStart,
04350                                                           Flags, DAG, dl);
04351 
04352         // Load the slot into the register.
04353         SDValue Load = DAG.getLoad(PtrVT, dl, Chain, PtrOff,
04354                                    MachinePointerInfo(),
04355                                    false, false, false, 0);
04356         MemOpChains.push_back(Load.getValue(1));
04357         RegsToPass.push_back(std::make_pair(GPR[GPR_idx], Load));
04358 
04359         // Done with this argument.
04360         ArgOffset += PtrByteSize;
04361         continue;
04362       }
04363 
04364       // For aggregates larger than PtrByteSize, copy the pieces of the
04365       // object that fit into registers from the parameter save area.
04366       for (unsigned j=0; j<Size; j+=PtrByteSize) {
04367         SDValue Const = DAG.getConstant(j, PtrOff.getValueType());
04368         SDValue AddArg = DAG.getNode(ISD::ADD, dl, PtrVT, Arg, Const);
04369         if (GPR_idx != NumGPRs) {
04370           SDValue Load = DAG.getLoad(PtrVT, dl, Chain, AddArg,
04371                                      MachinePointerInfo(),
04372                                      false, false, false, 0);
04373           MemOpChains.push_back(Load.getValue(1));
04374           RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
04375           ArgOffset += PtrByteSize;
04376         } else {
04377           ArgOffset += ((Size - j + PtrByteSize-1)/PtrByteSize)*PtrByteSize;
04378           break;
04379         }
04380       }
04381       continue;
04382     }
04383 
04384     switch (Arg.getSimpleValueType().SimpleTy) {
04385     default: llvm_unreachable("Unexpected ValueType for argument!");
04386     case MVT::i1:
04387     case MVT::i32:
04388     case MVT::i64:
04389       // These can be scalar arguments or elements of an integer array type
04390       // passed directly.  Clang may use those instead of "byval" aggregate
04391       // types to avoid forcing arguments to memory unnecessarily.
04392       if (GPR_idx != NumGPRs) {
04393         RegsToPass.push_back(std::make_pair(GPR[GPR_idx], Arg));
04394       } else {
04395         LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset,
04396                          true, isTailCall, false, MemOpChains,
04397                          TailCallArguments, dl);
04398       }
04399       ArgOffset += PtrByteSize;
04400       break;
04401     case MVT::f32:
04402     case MVT::f64: {
04403       // These can be scalar arguments or elements of a float array type
04404       // passed directly.  The latter are used to implement ELFv2 homogenous
04405       // float aggregates.
04406 
04407       // Named arguments go into FPRs first, and once they overflow, the
04408       // remaining arguments go into GPRs and then the parameter save area.
04409       // Unnamed arguments for vararg functions always go to GPRs and
04410       // then the parameter save area.  For now, put all arguments to vararg
04411       // routines always in both locations (FPR *and* GPR or stack slot).
04412       bool NeedGPROrStack = isVarArg || FPR_idx == NumFPRs;
04413 
04414       // First load the argument into the next available FPR.
04415       if (FPR_idx != NumFPRs)
04416         RegsToPass.push_back(std::make_pair(FPR[FPR_idx++], Arg));
04417 
04418       // Next, load the argument into GPR or stack slot if needed.
04419       if (!NeedGPROrStack)
04420         ;
04421       else if (GPR_idx != NumGPRs) {
04422         // In the non-vararg case, this can only ever happen in the
04423         // presence of f32 array types, since otherwise we never run
04424         // out of FPRs before running out of GPRs.
04425         SDValue ArgVal;
04426 
04427         // Double values are always passed in a single GPR.
04428         if (Arg.getValueType() != MVT::f32) {
04429           ArgVal = DAG.getNode(ISD::BITCAST, dl, MVT::i64, Arg);
04430 
04431         // Non-array float values are extended and passed in a GPR.
04432         } else if (!Flags.isInConsecutiveRegs()) {
04433           ArgVal = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Arg);
04434           ArgVal = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i64, ArgVal);
04435 
04436         // If we have an array of floats, we collect every odd element
04437         // together with its predecessor into one GPR.
04438         } else if (ArgOffset % PtrByteSize != 0) {
04439           SDValue Lo, Hi;
04440           Lo = DAG.getNode(ISD::BITCAST, dl, MVT::i32, OutVals[i - 1]);
04441           Hi = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Arg);
04442           if (!isLittleEndian)
04443             std::swap(Lo, Hi);
04444           ArgVal = DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Lo, Hi);
04445 
04446         // The final element, if even, goes into the first half of a GPR.
04447         } else if (Flags.isInConsecutiveRegsLast()) {
04448           ArgVal = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Arg);
04449           ArgVal = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i64, ArgVal);
04450           if (!isLittleEndian)
04451             ArgVal = DAG.getNode(ISD::SHL, dl, MVT::i64, ArgVal,
04452                                  DAG.getConstant(32, MVT::i32));
04453 
04454         // Non-final even elements are skipped; they will be handled
04455         // together the with subsequent argument on the next go-around.
04456         } else
04457           ArgVal = SDValue();
04458 
04459         if (ArgVal.getNode())
04460           RegsToPass.push_back(std::make_pair(GPR[GPR_idx], ArgVal));
04461       } else {
04462         // Single-precision floating-point values are mapped to the
04463         // second (rightmost) word of the stack doubleword.
04464         if (Arg.getValueType() == MVT::f32 &&
04465             !isLittleEndian && !Flags.isInConsecutiveRegs()) {
04466           SDValue ConstFour = DAG.getConstant(4, PtrOff.getValueType());
04467           PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, ConstFour);
04468         }
04469 
04470         LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset,
04471                          true, isTailCall, false, MemOpChains,
04472                          TailCallArguments, dl);
04473       }
04474       // When passing an array of floats, the array occupies consecutive
04475       // space in the argument area; only round up to the next doubleword
04476       // at the end of the array.  Otherwise, each float takes 8 bytes.
04477       ArgOffset += (Arg.getValueType() == MVT::f32 &&
04478                     Flags.isInConsecutiveRegs()) ? 4 : 8;
04479       if (Flags.isInConsecutiveRegsLast())
04480         ArgOffset = ((ArgOffset + PtrByteSize - 1)/PtrByteSize) * PtrByteSize;
04481       break;
04482     }
04483     case MVT::v4f32:
04484     case MVT::v4i32:
04485     case MVT::v8i16:
04486     case MVT::v16i8:
04487     case MVT::v2f64:
04488     case MVT::v2i64:
04489       // These can be scalar arguments or elements of a vector array type
04490       // passed directly.  The latter are used to implement ELFv2 homogenous
04491       // vector aggregates.
04492 
04493       // For a varargs call, named arguments go into VRs or on the stack as
04494       // usual; unnamed arguments always go to the stack or the corresponding
04495       // GPRs when within range.  For now, we always put the value in both
04496       // locations (or even all three).
04497       if (isVarArg) {
04498         // We could elide this store in the case where the object fits
04499         // entirely in R registers.  Maybe later.
04500         SDValue Store = DAG.getStore(Chain, dl, Arg, PtrOff,
04501                                      MachinePointerInfo(), false, false, 0);
04502         MemOpChains.push_back(Store);
04503         if (VR_idx != NumVRs) {
04504           SDValue Load = DAG.getLoad(MVT::v4f32, dl, Store, PtrOff,
04505                                      MachinePointerInfo(),
04506                                      false, false, false, 0);
04507           MemOpChains.push_back(Load.getValue(1));
04508 
04509           unsigned VReg = (Arg.getSimpleValueType() == MVT::v2f64 ||
04510                            Arg.getSimpleValueType() == MVT::v2i64) ?
04511                           VSRH[VR_idx] : VR[VR_idx];
04512           ++VR_idx;
04513 
04514           RegsToPass.push_back(std::make_pair(VReg, Load));
04515         }
04516         ArgOffset += 16;
04517         for (unsigned i=0; i<16; i+=PtrByteSize) {
04518           if (GPR_idx == NumGPRs)
04519             break;
04520           SDValue Ix = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff,
04521                                   DAG.getConstant(i, PtrVT));
04522           SDValue Load = DAG.getLoad(PtrVT, dl, Store, Ix, MachinePointerInfo(),
04523                                      false, false, false, 0);
04524           MemOpChains.push_back(Load.getValue(1));
04525           RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
04526         }
04527         break;
04528       }
04529 
04530       // Non-varargs Altivec params go into VRs or on the stack.
04531       if (VR_idx != NumVRs) {
04532         unsigned VReg = (Arg.getSimpleValueType() == MVT::v2f64 ||
04533                          Arg.getSimpleValueType() == MVT::v2i64) ?
04534                         VSRH[VR_idx] : VR[VR_idx];
04535         ++VR_idx;
04536 
04537         RegsToPass.push_back(std::make_pair(VReg, Arg));
04538       } else {
04539         LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset,
04540                          true, isTailCall, true, MemOpChains,
04541                          TailCallArguments, dl);
04542       }
04543       ArgOffset += 16;
04544       break;
04545     }
04546   }
04547 
04548   assert(NumBytesActuallyUsed == ArgOffset);
04549   (void)NumBytesActuallyUsed;
04550 
04551   if (!MemOpChains.empty())
04552     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains);
04553 
04554   // Check if this is an indirect call (MTCTR/BCTRL).
04555   // See PrepareCall() for more information about calls through function
04556   // pointers in the 64-bit SVR4 ABI.
04557   if (!isTailCall &&
04558       !dyn_cast<GlobalAddressSDNode>(Callee) &&
04559       !dyn_cast<ExternalSymbolSDNode>(Callee)) {
04560     // Load r2 into a virtual register and store it to the TOC save area.
04561     SDValue Val = DAG.getCopyFromReg(Chain, dl, PPC::X2, MVT::i64);
04562     // TOC save area offset.
04563     unsigned TOCSaveOffset = PPCFrameLowering::getTOCSaveOffset(isELFv2ABI);
04564     SDValue PtrOff = DAG.getIntPtrConstant(TOCSaveOffset);
04565     SDValue AddPtr = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, PtrOff);
04566     Chain = DAG.getStore(Val.getValue(1), dl, Val, AddPtr, MachinePointerInfo(),
04567                          false, false, 0);
04568     // In the ELFv2 ABI, R12 must contain the address of an indirect callee.
04569     // This does not mean the MTCTR instruction must use R12; it's easier
04570     // to model this as an extra parameter, so do that.
04571     if (isELFv2ABI)
04572       RegsToPass.push_back(std::make_pair((unsigned)PPC::X12, Callee));
04573   }
04574 
04575   // Build a sequence of copy-to-reg nodes chained together with token chain
04576   // and flag operands which copy the outgoing args into the appropriate regs.
04577   SDValue InFlag;
04578   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
04579     Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
04580                              RegsToPass[i].second, InFlag);
04581     InFlag = Chain.getValue(1);
04582   }
04583 
04584   if (isTailCall)
04585     PrepareTailCall(DAG, InFlag, Chain, dl, true, SPDiff, NumBytes, LROp,
04586                     FPOp, true, TailCallArguments);
04587 
04588   return FinishCall(CallConv, dl, isTailCall, isVarArg, DAG,
04589                     RegsToPass, InFlag, Chain, Callee, SPDiff, NumBytes,
04590                     Ins, InVals);
04591 }
04592 
04593 SDValue
04594 PPCTargetLowering::LowerCall_Darwin(SDValue Chain, SDValue Callee,
04595                                     CallingConv::ID CallConv, bool isVarArg,
04596                                     bool isTailCall,
04597                                     const SmallVectorImpl<ISD::OutputArg> &Outs,
04598                                     const SmallVectorImpl<SDValue> &OutVals,
04599                                     const SmallVectorImpl<ISD::InputArg> &Ins,
04600                                     SDLoc dl, SelectionDAG &DAG,
04601                                     SmallVectorImpl<SDValue> &InVals) const {
04602 
04603   unsigned NumOps = Outs.size();
04604 
04605   EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
04606   bool isPPC64 = PtrVT == MVT::i64;
04607   unsigned PtrByteSize = isPPC64 ? 8 : 4;
04608 
04609   MachineFunction &MF = DAG.getMachineFunction();
04610 
04611   // Mark this function as potentially containing a function that contains a
04612   // tail call. As a consequence the frame pointer will be used for dynamicalloc
04613   // and restoring the callers stack pointer in this functions epilog. This is
04614   // done because by tail calling the called function might overwrite the value
04615   // in this function's (MF) stack pointer stack slot 0(SP).
04616   if (getTargetMachine().Options.GuaranteedTailCallOpt &&
04617       CallConv == CallingConv::Fast)
04618     MF.getInfo<PPCFunctionInfo>()->setHasFastCall();
04619 
04620   // Count how many bytes are to be pushed on the stack, including the linkage
04621   // area, and parameter passing area.  We start with 24/48 bytes, which is
04622   // prereserved space for [SP][CR][LR][3 x unused].
04623   unsigned LinkageSize = PPCFrameLowering::getLinkageSize(isPPC64, true,
04624                                                           false);
04625   unsigned NumBytes = LinkageSize;
04626 
04627   // Add up all the space actually used.
04628   // In 32-bit non-varargs calls, Altivec parameters all go at the end; usually
04629   // they all go in registers, but we must reserve stack space for them for
04630   // possible use by the caller.  In varargs or 64-bit calls, parameters are
04631   // assigned stack space in order, with padding so Altivec parameters are
04632   // 16-byte aligned.
04633   unsigned nAltivecParamsAtEnd = 0;
04634   for (unsigned i = 0; i != NumOps; ++i) {
04635     ISD::ArgFlagsTy Flags = Outs[i].Flags;
04636     EVT ArgVT = Outs[i].VT;
04637     // Varargs Altivec parameters are padded to a 16 byte boundary.
04638     if (ArgVT == MVT::v4f32 || ArgVT == MVT::v4i32 ||
04639         ArgVT == MVT::v8i16 || ArgVT == MVT::v16i8 ||
04640         ArgVT == MVT::v2f64 || ArgVT == MVT::v2i64) {
04641       if (!isVarArg && !isPPC64) {
04642         // Non-varargs Altivec parameters go after all the non-Altivec
04643         // parameters; handle those later so we know how much padding we need.
04644         nAltivecParamsAtEnd++;
04645         continue;
04646       }
04647       // Varargs and 64-bit Altivec parameters are padded to 16 byte boundary.
04648       NumBytes = ((NumBytes+15)/16)*16;
04649     }
04650     NumBytes += CalculateStackSlotSize(ArgVT, Flags, PtrByteSize);
04651   }
04652 
04653   // Allow for Altivec parameters at the end, if needed.
04654   if (nAltivecParamsAtEnd) {
04655     NumBytes = ((NumBytes+15)/16)*16;
04656     NumBytes += 16*nAltivecParamsAtEnd;
04657   }
04658 
04659   // The prolog code of the callee may store up to 8 GPR argument registers to
04660   // the stack, allowing va_start to index over them in memory if its varargs.
04661   // Because we cannot tell if this is needed on the caller side, we have to
04662   // conservatively assume that it is needed.  As such, make sure we have at
04663   // least enough stack space for the caller to store the 8 GPRs.
04664   NumBytes = std::max(NumBytes, LinkageSize + 8 * PtrByteSize);
04665 
04666   // Tail call needs the stack to be aligned.
04667   if (getTargetMachine().Options.GuaranteedTailCallOpt &&
04668       CallConv == CallingConv::Fast)
04669     NumBytes = EnsureStackAlignment(MF.getTarget(), NumBytes);
04670 
04671   // Calculate by how many bytes the stack has to be adjusted in case of tail
04672   // call optimization.
04673   int SPDiff = CalculateTailCallSPDiff(DAG, isTailCall, NumBytes);
04674 
04675   // To protect arguments on the stack from being clobbered in a tail call,
04676   // force all the loads to happen before doing any other lowering.
04677   if (isTailCall)
04678     Chain = DAG.getStackArgumentTokenFactor(Chain);
04679 
04680   // Adjust the stack pointer for the new arguments...
04681   // These operations are automatically eliminated by the prolog/epilog pass
04682   Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(NumBytes, true),
04683                                dl);
04684   SDValue CallSeqStart = Chain;
04685 
04686   // Load the return address and frame pointer so it can be move somewhere else
04687   // later.
04688   SDValue LROp, FPOp;
04689   Chain = EmitTailCallLoadFPAndRetAddr(DAG, SPDiff, Chain, LROp, FPOp, true,
04690                                        dl);
04691 
04692   // Set up a copy of the stack pointer for use loading and storing any
04693   // arguments that may not fit in the registers available for argument
04694   // passing.
04695   SDValue StackPtr;
04696   if (isPPC64)
04697     StackPtr = DAG.getRegister(PPC::X1, MVT::i64);
04698   else
04699     StackPtr = DAG.getRegister(PPC::R1, MVT::i32);
04700 
04701   // Figure out which arguments are going to go in registers, and which in
04702   // memory.  Also, if this is a vararg function, floating point operations
04703   // must be stored to our stack, and loaded into integer regs as well, if
04704   // any integer regs are available for argument passing.
04705   unsigned ArgOffset = LinkageSize;
04706   unsigned GPR_idx = 0, FPR_idx = 0, VR_idx = 0;
04707 
04708   static const MCPhysReg GPR_32[] = {           // 32-bit registers.
04709     PPC::R3, PPC::R4, PPC::R5, PPC::R6,
04710     PPC::R7, PPC::R8, PPC::R9, PPC::R10,
04711   };
04712   static const MCPhysReg GPR_64[] = {           // 64-bit registers.
04713     PPC::X3, PPC::X4, PPC::X5, PPC::X6,
04714     PPC::X7, PPC::X8, PPC::X9, PPC::X10,
04715   };
04716   static const MCPhysReg *FPR = GetFPR();
04717 
04718   static const MCPhysReg VR[] = {
04719     PPC::V2, PPC::V3, PPC::V4, PPC::V5, PPC::V6, PPC::V7, PPC::V8,
04720     PPC::V9, PPC::V10, PPC::V11, PPC::V12, PPC::V13
04721   };
04722   const unsigned NumGPRs = array_lengthof(GPR_32);
04723   const unsigned NumFPRs = 13;
04724   const unsigned NumVRs  = array_lengthof(VR);
04725 
04726   const MCPhysReg *GPR = isPPC64 ? GPR_64 : GPR_32;
04727 
04728   SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
04729   SmallVector<TailCallArgumentInfo, 8> TailCallArguments;
04730 
04731   SmallVector<SDValue, 8> MemOpChains;
04732   for (unsigned i = 0; i != NumOps; ++i) {
04733     SDValue Arg = OutVals[i];
04734     ISD::ArgFlagsTy Flags = Outs[i].Flags;
04735 
04736     // PtrOff will be used to store the current argument to the stack if a
04737     // register cannot be found for it.
04738     SDValue PtrOff;
04739 
04740     PtrOff = DAG.getConstant(ArgOffset, StackPtr.getValueType());
04741 
04742     PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, PtrOff);
04743 
04744     // On PPC64, promote integers to 64-bit values.
04745     if (isPPC64 && Arg.getValueType() == MVT::i32) {
04746       // FIXME: Should this use ANY_EXTEND if neither sext nor zext?
04747       unsigned ExtOp = Flags.isSExt() ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
04748       Arg = DAG.getNode(ExtOp, dl, MVT::i64, Arg);
04749     }
04750 
04751     // FIXME memcpy is used way more than necessary.  Correctness first.
04752     // Note: "by value" is code for passing a structure by value, not
04753     // basic types.
04754     if (Flags.isByVal()) {
04755       unsigned Size = Flags.getByValSize();
04756       // Very small objects are passed right-justified.  Everything else is
04757       // passed left-justified.
04758       if (Size==1 || Size==2) {
04759         EVT VT = (Size==1) ? MVT::i8 : MVT::i16;
04760         if (GPR_idx != NumGPRs) {
04761           SDValue Load = DAG.getExtLoad(ISD::EXTLOAD, dl, PtrVT, Chain, Arg,
04762                                         MachinePointerInfo(), VT,
04763                                         false, false, 0);
04764           MemOpChains.push_back(Load.getValue(1));
04765           RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
04766 
04767           ArgOffset += PtrByteSize;
04768         } else {
04769           SDValue Const = DAG.getConstant(PtrByteSize - Size,
04770                                           PtrOff.getValueType());
04771           SDValue AddPtr = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, Const);
04772           Chain = CallSeqStart = createMemcpyOutsideCallSeq(Arg, AddPtr,
04773                                                             CallSeqStart,
04774                                                             Flags, DAG, dl);
04775           ArgOffset += PtrByteSize;
04776         }
04777         continue;
04778       }
04779       // Copy entire object into memory.  There are cases where gcc-generated
04780       // code assumes it is there, even if it could be put entirely into
04781       // registers.  (This is not what the doc says.)
04782       Chain = CallSeqStart = createMemcpyOutsideCallSeq(Arg, PtrOff,
04783                                                         CallSeqStart,
04784                                                         Flags, DAG, dl);
04785 
04786       // For small aggregates (Darwin only) and aggregates >= PtrByteSize,
04787       // copy the pieces of the object that fit into registers from the
04788       // parameter save area.
04789       for (unsigned j=0; j<Size; j+=PtrByteSize) {
04790         SDValue Const = DAG.getConstant(j, PtrOff.getValueType());
04791         SDValue AddArg = DAG.getNode(ISD::ADD, dl, PtrVT, Arg, Const);
04792         if (GPR_idx != NumGPRs) {
04793           SDValue Load = DAG.getLoad(PtrVT, dl, Chain, AddArg,
04794                                      MachinePointerInfo(),
04795                                      false, false, false, 0);
04796           MemOpChains.push_back(Load.getValue(1));
04797           RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
04798           ArgOffset += PtrByteSize;
04799         } else {
04800           ArgOffset += ((Size - j + PtrByteSize-1)/PtrByteSize)*PtrByteSize;
04801           break;
04802         }
04803       }
04804       continue;
04805     }
04806 
04807     switch (Arg.getSimpleValueType().SimpleTy) {
04808     default: llvm_unreachable("Unexpected ValueType for argument!");
04809     case MVT::i1:
04810     case MVT::i32:
04811     case MVT::i64:
04812       if (GPR_idx != NumGPRs) {
04813         if (Arg.getValueType() == MVT::i1)
04814           Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, PtrVT, Arg);
04815 
04816         RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Arg));
04817       } else {
04818         LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset,
04819                          isPPC64, isTailCall, false, MemOpChains,
04820                          TailCallArguments, dl);
04821       }
04822       ArgOffset += PtrByteSize;
04823       break;
04824     case MVT::f32:
04825     case MVT::f64:
04826       if (FPR_idx != NumFPRs) {
04827         RegsToPass.push_back(std::make_pair(FPR[FPR_idx++], Arg));
04828 
04829         if (isVarArg) {
04830           SDValue Store = DAG.getStore(Chain, dl, Arg, PtrOff,
04831                                        MachinePointerInfo(), false, false, 0);
04832           MemOpChains.push_back(Store);
04833 
04834           // Float varargs are always shadowed in available integer registers
04835           if (GPR_idx != NumGPRs) {
04836             SDValue Load = DAG.getLoad(PtrVT, dl, Store, PtrOff,
04837                                        MachinePointerInfo(), false, false,
04838                                        false, 0);
04839             MemOpChains.push_back(Load.getValue(1));
04840             RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
04841           }
04842           if (GPR_idx != NumGPRs && Arg.getValueType() == MVT::f64 && !isPPC64){
04843             SDValue ConstFour = DAG.getConstant(4, PtrOff.getValueType());
04844             PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, ConstFour);
04845             SDValue Load = DAG.getLoad(PtrVT, dl, Store, PtrOff,
04846                                        MachinePointerInfo(),
04847                                        false, false, false, 0);
04848             MemOpChains.push_back(Load.getValue(1));
04849             RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
04850           }
04851         } else {
04852           // If we have any FPRs remaining, we may also have GPRs remaining.
04853           // Args passed in FPRs consume either 1 (f32) or 2 (f64) available
04854           // GPRs.
04855           if (GPR_idx != NumGPRs)
04856             ++GPR_idx;
04857           if (GPR_idx != NumGPRs && Arg.getValueType() == MVT::f64 &&
04858               !isPPC64)  // PPC64 has 64-bit GPR's obviously :)
04859             ++GPR_idx;
04860         }
04861       } else
04862         LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset,
04863                          isPPC64, isTailCall, false, MemOpChains,
04864                          TailCallArguments, dl);
04865       if (isPPC64)
04866         ArgOffset += 8;
04867       else
04868         ArgOffset += Arg.getValueType() == MVT::f32 ? 4 : 8;
04869       break;
04870     case MVT::v4f32:
04871     case MVT::v4i32:
04872     case MVT::v8i16:
04873     case MVT::v16i8:
04874       if (isVarArg) {
04875         // These go aligned on the stack, or in the corresponding R registers
04876         // when within range.  The Darwin PPC ABI doc claims they also go in
04877         // V registers; in fact gcc does this only for arguments that are
04878         // prototyped, not for those that match the ...  We do it for all
04879         // arguments, seems to work.
04880         while (ArgOffset % 16 !=0) {
04881           ArgOffset += PtrByteSize;
04882           if (GPR_idx != NumGPRs)
04883             GPR_idx++;
04884         }
04885         // We could elide this store in the case where the object fits
04886         // entirely in R registers.  Maybe later.
04887         PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr,
04888                             DAG.getConstant(ArgOffset, PtrVT));
04889         SDValue Store = DAG.getStore(Chain, dl, Arg, PtrOff,
04890                                      MachinePointerInfo(), false, false, 0);
04891         MemOpChains.push_back(Store);
04892         if (VR_idx != NumVRs) {
04893           SDValue Load = DAG.getLoad(MVT::v4f32, dl, Store, PtrOff,
04894                                      MachinePointerInfo(),
04895                                      false, false, false, 0);
04896           MemOpChains.push_back(Load.getValue(1));
04897           RegsToPass.push_back(std::make_pair(VR[VR_idx++], Load));
04898         }
04899         ArgOffset += 16;
04900         for (unsigned i=0; i<16; i+=PtrByteSize) {
04901           if (GPR_idx == NumGPRs)
04902             break;
04903           SDValue Ix = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff,
04904                                   DAG.getConstant(i, PtrVT));
04905           SDValue Load = DAG.getLoad(PtrVT, dl, Store, Ix, MachinePointerInfo(),
04906                                      false, false, false, 0);
04907           MemOpChains.push_back(Load.getValue(1));
04908           RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
04909         }
04910         break;
04911       }
04912 
04913       // Non-varargs Altivec params generally go in registers, but have
04914       // stack space allocated at the end.
04915       if (VR_idx != NumVRs) {
04916         // Doesn't have GPR space allocated.
04917         RegsToPass.push_back(std::make_pair(VR[VR_idx++], Arg));
04918       } else if (nAltivecParamsAtEnd==0) {
04919         // We are emitting Altivec params in order.
04920         LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset,
04921                          isPPC64, isTailCall, true, MemOpChains,
04922                          TailCallArguments, dl);
04923         ArgOffset += 16;
04924       }
04925       break;
04926     }
04927   }
04928   // If all Altivec parameters fit in registers, as they usually do,
04929   // they get stack space following the non-Altivec parameters.  We
04930   // don't track this here because nobody below needs it.
04931   // If there are more Altivec parameters than fit in registers emit
04932   // the stores here.
04933   if (!isVarArg && nAltivecParamsAtEnd > NumVRs) {
04934     unsigned j = 0;
04935     // Offset is aligned; skip 1st 12 params which go in V registers.
04936     ArgOffset = ((ArgOffset+15)/16)*16;
04937     ArgOffset += 12*16;
04938     for (unsigned i = 0; i != NumOps; ++i) {
04939       SDValue Arg = OutVals[i];
04940       EVT ArgType = Outs[i].VT;
04941       if (ArgType==MVT::v4f32 || ArgType==MVT::v4i32 ||
04942           ArgType==MVT::v8i16 || ArgType==MVT::v16i8) {
04943         if (++j > NumVRs) {
04944           SDValue PtrOff;
04945           // We are emitting Altivec params in order.
04946           LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset,
04947                            isPPC64, isTailCall, true, MemOpChains,
04948                            TailCallArguments, dl);
04949           ArgOffset += 16;
04950         }
04951       }
04952     }
04953   }
04954 
04955   if (!MemOpChains.empty())
04956     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains);
04957 
04958   // On Darwin, R12 must contain the address of an indirect callee.  This does
04959   // not mean the MTCTR instruction must use R12; it's easier to model this as
04960   // an extra parameter, so do that.
04961   if (!isTailCall &&
04962       !dyn_cast<GlobalAddressSDNode>(Callee) &&
04963       !dyn_cast<ExternalSymbolSDNode>(Callee) &&
04964       !isBLACompatibleAddress(Callee, DAG))
04965     RegsToPass.push_back(std::make_pair((unsigned)(isPPC64 ? PPC::X12 :
04966                                                    PPC::R12), Callee));
04967 
04968   // Build a sequence of copy-to-reg nodes chained together with token chain
04969   // and flag operands which copy the outgoing args into the appropriate regs.
04970   SDValue InFlag;
04971   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
04972     Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
04973                              RegsToPass[i].second, InFlag);
04974     InFlag = Chain.getValue(1);
04975   }
04976 
04977   if (isTailCall)
04978     PrepareTailCall(DAG, InFlag, Chain, dl, isPPC64, SPDiff, NumBytes, LROp,
04979                     FPOp, true, TailCallArguments);
04980 
04981   return FinishCall(CallConv, dl, isTailCall, isVarArg, DAG,
04982                     RegsToPass, InFlag, Chain, Callee, SPDiff, NumBytes,
04983                     Ins, InVals);
04984 }
04985 
04986 bool
04987 PPCTargetLowering::CanLowerReturn(CallingConv::ID CallConv,
04988                                   MachineFunction &MF, bool isVarArg,
04989                                   const SmallVectorImpl<ISD::OutputArg> &Outs,
04990                                   LLVMContext &Context) const {
04991   SmallVector<CCValAssign, 16> RVLocs;
04992   CCState CCInfo(CallConv, isVarArg, MF, getTargetMachine(),
04993                  RVLocs, Context);
04994   return CCInfo.CheckReturn(Outs, RetCC_PPC);
04995 }
04996 
04997 SDValue
04998 PPCTargetLowering::LowerReturn(SDValue Chain,
04999                                CallingConv::ID CallConv, bool isVarArg,
05000                                const SmallVectorImpl<ISD::OutputArg> &Outs,
05001                                const SmallVectorImpl<SDValue> &OutVals,
05002                                SDLoc dl, SelectionDAG &DAG) const {
05003 
05004   SmallVector<CCValAssign, 16> RVLocs;
05005   CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(),
05006                  getTargetMachine(), RVLocs, *DAG.getContext());
05007   CCInfo.AnalyzeReturn(Outs, RetCC_PPC);
05008 
05009   SDValue Flag;
05010   SmallVector<SDValue, 4> RetOps(1, Chain);
05011 
05012   // Copy the result values into the output registers.
05013   for (unsigned i = 0; i != RVLocs.size(); ++i) {
05014     CCValAssign &VA = RVLocs[i];
05015     assert(VA.isRegLoc() && "Can only return in registers!");
05016 
05017     SDValue Arg = OutVals[i];
05018 
05019     switch (VA.getLocInfo()) {
05020     default: llvm_unreachable("Unknown loc info!");
05021     case CCValAssign::Full: break;
05022     case CCValAssign::AExt:
05023       Arg = DAG.getNode(ISD::ANY_EXTEND, dl, VA.getLocVT(), Arg);
05024       break;
05025     case CCValAssign::ZExt:
05026       Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, VA.getLocVT(), Arg);
05027       break;
05028     case CCValAssign::SExt:
05029       Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), Arg);
05030       break;
05031     }
05032 
05033     Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), Arg, Flag);
05034     Flag = Chain.getValue(1);
05035     RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
05036   }
05037 
05038   RetOps[0] = Chain;  // Update chain.
05039 
05040   // Add the flag if we have it.
05041   if (Flag.getNode())
05042     RetOps.push_back(Flag);
05043 
05044   return DAG.getNode(PPCISD::RET_FLAG, dl, MVT::Other, RetOps);
05045 }
05046 
05047 SDValue PPCTargetLowering::LowerSTACKRESTORE(SDValue Op, SelectionDAG &DAG,
05048                                    const PPCSubtarget &Subtarget) const {
05049   // When we pop the dynamic allocation we need to restore the SP link.
05050   SDLoc dl(Op);
05051 
05052   // Get the corect type for pointers.
05053   EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
05054 
05055   // Construct the stack pointer operand.
05056   bool isPPC64 = Subtarget.isPPC64();
05057   unsigned SP = isPPC64 ? PPC::X1 : PPC::R1;
05058   SDValue StackPtr = DAG.getRegister(SP, PtrVT);
05059 
05060   // Get the operands for the STACKRESTORE.
05061   SDValue Chain = Op.getOperand(0);
05062   SDValue SaveSP = Op.getOperand(1);
05063 
05064   // Load the old link SP.
05065   SDValue LoadLinkSP = DAG.getLoad(PtrVT, dl, Chain, StackPtr,
05066                                    MachinePointerInfo(),
05067                                    false, false, false, 0);
05068 
05069   // Restore the stack pointer.
05070   Chain = DAG.getCopyToReg(LoadLinkSP.getValue(1), dl, SP, SaveSP);
05071 
05072   // Store the old link SP.
05073   return DAG.getStore(Chain, dl, LoadLinkSP, StackPtr, MachinePointerInfo(),
05074                       false, false, 0);
05075 }
05076 
05077 
05078 
05079 SDValue
05080 PPCTargetLowering::getReturnAddrFrameIndex(SelectionDAG & DAG) const {
05081   MachineFunction &MF = DAG.getMachineFunction();
05082   bool isPPC64 = Subtarget.isPPC64();
05083   bool isDarwinABI = Subtarget.isDarwinABI();
05084   EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
05085 
05086   // Get current frame pointer save index.  The users of this index will be
05087   // primarily DYNALLOC instructions.
05088   PPCFunctionInfo *FI = MF.getInfo<PPCFunctionInfo>();
05089   int RASI = FI->getReturnAddrSaveIndex();
05090 
05091   // If the frame pointer save index hasn't been defined yet.
05092   if (!RASI) {
05093     // Find out what the fix offset of the frame pointer save area.
05094     int LROffset = PPCFrameLowering::getReturnSaveOffset(isPPC64, isDarwinABI);
05095     // Allocate the frame index for frame pointer save area.
05096     RASI = MF.getFrameInfo()->CreateFixedObject(isPPC64? 8 : 4, LROffset, true);
05097     // Save the result.
05098     FI->setReturnAddrSaveIndex(RASI);
05099   }
05100   return DAG.getFrameIndex(RASI, PtrVT);
05101 }
05102 
05103 SDValue
05104 PPCTargetLowering::getFramePointerFrameIndex(SelectionDAG & DAG) const {
05105   MachineFunction &MF = DAG.getMachineFunction();
05106   bool isPPC64 = Subtarget.isPPC64();
05107   bool isDarwinABI = Subtarget.isDarwinABI();
05108   EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
05109 
05110   // Get current frame pointer save index.  The users of this index will be
05111   // primarily DYNALLOC instructions.
05112   PPCFunctionInfo *FI = MF.getInfo<PPCFunctionInfo>();
05113   int FPSI = FI->getFramePointerSaveIndex();
05114 
05115   // If the frame pointer save index hasn't been defined yet.
05116   if (!FPSI) {
05117     // Find out what the fix offset of the frame pointer save area.
05118     int FPOffset = PPCFrameLowering::getFramePointerSaveOffset(isPPC64,
05119                                                            isDarwinABI);
05120 
05121     // Allocate the frame index for frame pointer save area.
05122     FPSI = MF.getFrameInfo()->CreateFixedObject(isPPC64? 8 : 4, FPOffset, true);
05123     // Save the result.
05124     FI->setFramePointerSaveIndex(FPSI);
05125   }
05126   return DAG.getFrameIndex(FPSI, PtrVT);
05127 }
05128 
05129 SDValue PPCTargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op,
05130                                          SelectionDAG &DAG,
05131                                          const PPCSubtarget &Subtarget) const {
05132   // Get the inputs.
05133   SDValue Chain = Op.getOperand(0);
05134   SDValue Size  = Op.getOperand(1);
05135   SDLoc dl(Op);
05136 
05137   // Get the corect type for pointers.
05138   EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
05139   // Negate the size.
05140   SDValue NegSize = DAG.getNode(ISD::SUB, dl, PtrVT,
05141                                   DAG.getConstant(0, PtrVT), Size);
05142   // Construct a node for the frame pointer save index.
05143   SDValue FPSIdx = getFramePointerFrameIndex(DAG);
05144   // Build a DYNALLOC node.
05145   SDValue Ops[3] = { Chain, NegSize, FPSIdx };
05146   SDVTList VTs = DAG.getVTList(PtrVT, MVT::Other);
05147   return DAG.getNode(PPCISD::DYNALLOC, dl, VTs, Ops);
05148 }
05149 
05150 SDValue PPCTargetLowering::lowerEH_SJLJ_SETJMP(SDValue Op,
05151                                                SelectionDAG &DAG) const {
05152   SDLoc DL(Op);
05153   return DAG.getNode(PPCISD::EH_SJLJ_SETJMP, DL,
05154                      DAG.getVTList(MVT::i32, MVT::Other),
05155                      Op.getOperand(0), Op.getOperand(1));
05156 }
05157 
05158 SDValue PPCTargetLowering::lowerEH_SJLJ_LONGJMP(SDValue Op,
05159                                                 SelectionDAG &DAG) const {
05160   SDLoc DL(Op);
05161   return DAG.getNode(PPCISD::EH_SJLJ_LONGJMP, DL, MVT::Other,
05162                      Op.getOperand(0), Op.getOperand(1));
05163 }
05164 
05165 SDValue PPCTargetLowering::LowerLOAD(SDValue Op, SelectionDAG &DAG) const {
05166   assert(Op.getValueType() == MVT::i1 &&
05167          "Custom lowering only for i1 loads");
05168 
05169   // First, load 8 bits into 32 bits, then truncate to 1 bit.
05170 
05171   SDLoc dl(Op);
05172   LoadSDNode *LD = cast<LoadSDNode>(Op);
05173 
05174   SDValue Chain = LD->getChain();
05175   SDValue BasePtr = LD->getBasePtr();
05176   MachineMemOperand *MMO = LD->getMemOperand();
05177 
05178   SDValue NewLD = DAG.getExtLoad(ISD::EXTLOAD, dl, getPointerTy(), Chain,
05179                                  BasePtr, MVT::i8, MMO);
05180   SDValue Result = DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, NewLD);
05181 
05182   SDValue Ops[] = { Result, SDValue(NewLD.getNode(), 1) };
05183   return DAG.getMergeValues(Ops, dl);
05184 }
05185 
05186 SDValue PPCTargetLowering::LowerSTORE(SDValue Op, SelectionDAG &DAG) const {
05187   assert(Op.getOperand(1).getValueType() == MVT::i1 &&
05188          "Custom lowering only for i1 stores");
05189 
05190   // First, zero extend to 32 bits, then use a truncating store to 8 bits.
05191 
05192   SDLoc dl(Op);
05193   StoreSDNode *ST = cast<StoreSDNode>(Op);
05194 
05195   SDValue Chain = ST->getChain();
05196   SDValue BasePtr = ST->getBasePtr();
05197   SDValue Value = ST->getValue();
05198   MachineMemOperand *MMO = ST->getMemOperand();
05199 
05200   Value = DAG.getNode(ISD::ZERO_EXTEND, dl, getPointerTy(), Value);
05201   return DAG.getTruncStore(Chain, dl, Value, BasePtr, MVT::i8, MMO);
05202 }
05203 
05204 // FIXME: Remove this once the ANDI glue bug is fixed:
05205 SDValue PPCTargetLowering::LowerTRUNCATE(SDValue Op, SelectionDAG &DAG) const {
05206   assert(Op.getValueType() == MVT::i1 &&
05207          "Custom lowering only for i1 results");
05208 
05209   SDLoc DL(Op);
05210   return DAG.getNode(PPCISD::ANDIo_1_GT_BIT, DL, MVT::i1,
05211                      Op.getOperand(0));
05212 }
05213 
05214 /// LowerSELECT_CC - Lower floating point select_cc's into fsel instruction when
05215 /// possible.
05216 SDValue PPCTargetLowering::LowerSELECT_CC(SDValue Op, SelectionDAG &DAG) const {
05217   // Not FP? Not a fsel.
05218   if (!Op.getOperand(0).getValueType().isFloatingPoint() ||
05219       !Op.getOperand(2).getValueType().isFloatingPoint())
05220     return Op;
05221 
05222   // We might be able to do better than this under some circumstances, but in
05223   // general, fsel-based lowering of select is a finite-math-only optimization.
05224   // For more information, see section F.3 of the 2.06 ISA specification.
05225   if (!DAG.getTarget().Options.NoInfsFPMath ||
05226       !DAG.getTarget().Options.NoNaNsFPMath)
05227     return Op;
05228 
05229   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(4))->get();
05230 
05231   EVT ResVT = Op.getValueType();
05232   EVT CmpVT = Op.getOperand(0).getValueType();
05233   SDValue LHS = Op.getOperand(0), RHS = Op.getOperand(1);
05234   SDValue TV  = Op.getOperand(2), FV  = Op.getOperand(3);
05235   SDLoc dl(Op);
05236 
05237   // If the RHS of the comparison is a 0.0, we don't need to do the
05238   // subtraction at all.
05239   SDValue Sel1;
05240   if (isFloatingPointZero(RHS))
05241     switch (CC) {
05242     default: break;       // SETUO etc aren't handled by fsel.
05243     case ISD::SETNE:
05244       std::swap(TV, FV);
05245     case ISD::SETEQ:
05246       if (LHS.getValueType() == MVT::f32)   // Comparison is always 64-bits
05247         LHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, LHS);
05248       Sel1 = DAG.getNode(PPCISD::FSEL, dl, ResVT, LHS, TV, FV);
05249       if (Sel1.getValueType() == MVT::f32)   // Comparison is always 64-bits
05250         Sel1 = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Sel1);
05251       return DAG.getNode(PPCISD::FSEL, dl, ResVT,
05252                          DAG.getNode(ISD::FNEG, dl, MVT::f64, LHS), Sel1, FV);
05253     case ISD::SETULT:
05254     case ISD::SETLT:
05255       std::swap(TV, FV);  // fsel is natively setge, swap operands for setlt
05256     case ISD::SETOGE:
05257     case ISD::SETGE:
05258       if (LHS.getValueType() == MVT::f32)   // Comparison is always 64-bits
05259         LHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, LHS);
05260       return DAG.getNode(PPCISD::FSEL, dl, ResVT, LHS, TV, FV);
05261     case ISD::SETUGT:
05262     case ISD::SETGT:
05263       std::swap(TV, FV);  // fsel is natively setge, swap operands for setlt
05264     case ISD::SETOLE:
05265     case ISD::SETLE:
05266       if (LHS.getValueType() == MVT::f32)   // Comparison is always 64-bits
05267         LHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, LHS);
05268       return DAG.getNode(PPCISD::FSEL, dl, ResVT,
05269                          DAG.getNode(ISD::FNEG, dl, MVT::f64, LHS), TV, FV);
05270     }
05271 
05272   SDValue Cmp;
05273   switch (CC) {
05274   default: break;       // SETUO etc aren't handled by fsel.
05275   case ISD::SETNE:
05276     std::swap(TV, FV);
05277   case ISD::SETEQ:
05278     Cmp = DAG.getNode(ISD::FSUB, dl, CmpVT, LHS, RHS);
05279     if (Cmp.getValueType() == MVT::f32)   // Comparison is always 64-bits
05280       Cmp = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Cmp);
05281     Sel1 = DAG.getNode(PPCISD::FSEL, dl, ResVT, Cmp, TV, FV);
05282     if (Sel1.getValueType() == MVT::f32)   // Comparison is always 64-bits
05283       Sel1 = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Sel1);
05284     return DAG.getNode(PPCISD::FSEL, dl, ResVT,
05285                        DAG.getNode(ISD::FNEG, dl, MVT::f64, Cmp), Sel1, FV);
05286   case ISD::SETULT:
05287   case ISD::SETLT:
05288     Cmp = DAG.getNode(ISD::FSUB, dl, CmpVT, LHS, RHS);
05289     if (Cmp.getValueType() == MVT::f32)   // Comparison is always 64-bits
05290       Cmp = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Cmp);
05291     return DAG.getNode(PPCISD::FSEL, dl, ResVT, Cmp, FV, TV);
05292   case ISD::SETOGE:
05293   case ISD::SETGE:
05294     Cmp = DAG.getNode(ISD::FSUB, dl, CmpVT, LHS, RHS);
05295     if (Cmp.getValueType() == MVT::f32)   // Comparison is always 64-bits
05296       Cmp = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Cmp);
05297     return DAG.getNode(PPCISD::FSEL, dl, ResVT, Cmp, TV, FV);
05298   case ISD::SETUGT:
05299   case ISD::SETGT:
05300     Cmp = DAG.getNode(ISD::FSUB, dl, CmpVT, RHS, LHS);
05301     if (Cmp.getValueType() == MVT::f32)   // Comparison is always 64-bits
05302       Cmp = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Cmp);
05303     return DAG.getNode(PPCISD::FSEL, dl, ResVT, Cmp, FV, TV);
05304   case ISD::SETOLE:
05305   case ISD::SETLE:
05306     Cmp = DAG.getNode(ISD::FSUB, dl, CmpVT, RHS, LHS);
05307     if (Cmp.getValueType() == MVT::f32)   // Comparison is always 64-bits
05308       Cmp = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Cmp);
05309     return DAG.getNode(PPCISD::FSEL, dl, ResVT, Cmp, TV, FV);
05310   }
05311   return Op;
05312 }
05313 
05314 // FIXME: Split this code up when LegalizeDAGTypes lands.
05315 SDValue PPCTargetLowering::LowerFP_TO_INT(SDValue Op, SelectionDAG &DAG,
05316                                            SDLoc dl) const {
05317   assert(Op.getOperand(0).getValueType().isFloatingPoint());
05318   SDValue Src = Op.getOperand(0);
05319   if (Src.getValueType() == MVT::f32)
05320     Src = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Src);
05321 
05322   SDValue Tmp;
05323   switch (Op.getSimpleValueType().SimpleTy) {
05324   default: llvm_unreachable("Unhandled FP_TO_INT type in custom expander!");
05325   case MVT::i32:
05326     Tmp = DAG.getNode(Op.getOpcode()==ISD::FP_TO_SINT ? PPCISD::FCTIWZ :
05327                         (Subtarget.hasFPCVT() ? PPCISD::FCTIWUZ :
05328                                                    PPCISD::FCTIDZ),
05329                       dl, MVT::f64, Src);
05330     break;
05331   case MVT::i64:
05332     assert((Op.getOpcode() == ISD::FP_TO_SINT || Subtarget.hasFPCVT()) &&
05333            "i64 FP_TO_UINT is supported only with FPCVT");
05334     Tmp = DAG.getNode(Op.getOpcode()==ISD::FP_TO_SINT ? PPCISD::FCTIDZ :
05335                                                         PPCISD::FCTIDUZ,
05336                       dl, MVT::f64, Src);
05337     break;
05338   }
05339 
05340   // Convert the FP value to an int value through memory.
05341   bool i32Stack = Op.getValueType() == MVT::i32 && Subtarget.hasSTFIWX() &&
05342     (Op.getOpcode() == ISD::FP_TO_SINT || Subtarget.hasFPCVT());
05343   SDValue FIPtr = DAG.CreateStackTemporary(i32Stack ? MVT::i32 : MVT::f64);
05344   int FI = cast<FrameIndexSDNode>(FIPtr)->getIndex();
05345   MachinePointerInfo MPI = MachinePointerInfo::getFixedStack(FI);
05346 
05347   // Emit a store to the stack slot.
05348   SDValue Chain;
05349   if (i32Stack) {
05350     MachineFunction &MF = DAG.getMachineFunction();
05351     MachineMemOperand *MMO =
05352       MF.getMachineMemOperand(MPI, MachineMemOperand::MOStore, 4, 4);
05353     SDValue Ops[] = { DAG.getEntryNode(), Tmp, FIPtr };
05354     Chain = DAG.getMemIntrinsicNode(PPCISD::STFIWX, dl,
05355               DAG.getVTList(MVT::Other), Ops, MVT::i32, MMO);
05356   } else
05357     Chain = DAG.getStore(DAG.getEntryNode(), dl, Tmp, FIPtr,
05358                          MPI, false, false, 0);
05359 
05360   // Result is a load from the stack slot.  If loading 4 bytes, make sure to
05361   // add in a bias.
05362   if (Op.getValueType() == MVT::i32 && !i32Stack) {
05363     FIPtr = DAG.getNode(ISD::ADD, dl, FIPtr.getValueType(), FIPtr,
05364                         DAG.getConstant(4, FIPtr.getValueType()));
05365     MPI = MachinePointerInfo();
05366   }
05367 
05368   return DAG.getLoad(Op.getValueType(), dl, Chain, FIPtr, MPI,
05369                      false, false, false, 0);
05370 }
05371 
05372 SDValue PPCTargetLowering::LowerINT_TO_FP(SDValue Op,
05373                                            SelectionDAG &DAG) const {
05374   SDLoc dl(Op);
05375   // Don't handle ppc_fp128 here; let it be lowered to a libcall.
05376   if (Op.getValueType() != MVT::f32 && Op.getValueType() != MVT::f64)
05377     return SDValue();
05378 
05379   if (Op.getOperand(0).getValueType() == MVT::i1)
05380     return DAG.getNode(ISD::SELECT, dl, Op.getValueType(), Op.getOperand(0),
05381                        DAG.getConstantFP(1.0, Op.getValueType()),
05382                        DAG.getConstantFP(0.0, Op.getValueType()));
05383 
05384   assert((Op.getOpcode() == ISD::SINT_TO_FP || Subtarget.hasFPCVT()) &&
05385          "UINT_TO_FP is supported only with FPCVT");
05386 
05387   // If we have FCFIDS, then use it when converting to single-precision.
05388   // Otherwise, convert to double-precision and then round.
05389   unsigned FCFOp = (Subtarget.hasFPCVT() && Op.getValueType() == MVT::f32) ?
05390                    (Op.getOpcode() == ISD::UINT_TO_FP ?
05391                     PPCISD::FCFIDUS : PPCISD::FCFIDS) :
05392                    (Op.getOpcode() == ISD::UINT_TO_FP ?
05393                     PPCISD::FCFIDU : PPCISD::FCFID);
05394   MVT      FCFTy = (Subtarget.hasFPCVT() && Op.getValueType() == MVT::f32) ?
05395                    MVT::f32 : MVT::f64;
05396 
05397   if (Op.getOperand(0).getValueType() == MVT::i64) {
05398     SDValue SINT = Op.getOperand(0);
05399     // When converting to single-precision, we actually need to convert
05400     // to double-precision first and then round to single-precision.
05401     // To avoid double-rounding effects during that operation, we have
05402     // to prepare the input operand.  Bits that might be truncated when
05403     // converting to double-precision are replaced by a bit that won't
05404     // be lost at this stage, but is below the single-precision rounding
05405     // position.
05406     //
05407     // However, if -enable-unsafe-fp-math is in effect, accept double
05408     // rounding to avoid the extra overhead.
05409     if (Op.getValueType() == MVT::f32 &&
05410         !Subtarget.hasFPCVT() &&
05411         !DAG.getTarget().Options.UnsafeFPMath) {
05412 
05413       // Twiddle input to make sure the low 11 bits are zero.  (If this
05414       // is the case, we are guaranteed the value will fit into the 53 bit
05415       // mantissa of an IEEE double-precision value without rounding.)
05416       // If any of those low 11 bits were not zero originally, make sure
05417       // bit 12 (value 2048) is set instead, so that the final rounding
05418       // to single-precision gets the correct result.
05419       SDValue Round = DAG.getNode(ISD::AND, dl, MVT::i64,
05420                                   SINT, DAG.getConstant(2047, MVT::i64));
05421       Round = DAG.getNode(ISD::ADD, dl, MVT::i64,
05422                           Round, DAG.getConstant(2047, MVT::i64));
05423       Round = DAG.getNode(ISD::OR, dl, MVT::i64, Round, SINT);
05424       Round = DAG.getNode(ISD::AND, dl, MVT::i64,
05425                           Round, DAG.getConstant(-2048, MVT::i64));
05426 
05427       // However, we cannot use that value unconditionally: if the magnitude
05428       // of the input value is small, the bit-twiddling we did above might
05429       // end up visibly changing the output.  Fortunately, in that case, we
05430       // don't need to twiddle bits since the original input will convert
05431       // exactly to double-precision floating-point already.  Therefore,
05432       // construct a conditional to use the original value if the top 11
05433       // bits are all sign-bit copies, and use the rounded value computed
05434       // above otherwise.
05435       SDValue Cond = DAG.getNode(ISD::SRA, dl, MVT::i64,
05436                                  SINT, DAG.getConstant(53, MVT::i32));
05437       Cond = DAG.getNode(ISD::ADD, dl, MVT::i64,
05438                          Cond, DAG.getConstant(1, MVT::i64));
05439       Cond = DAG.getSetCC(dl, MVT::i32,
05440                           Cond, DAG.getConstant(1, MVT::i64), ISD::SETUGT);
05441 
05442       SINT = DAG.getNode(ISD::SELECT, dl, MVT::i64, Cond, Round, SINT);
05443     }
05444 
05445     SDValue Bits = DAG.getNode(ISD::BITCAST, dl, MVT::f64, SINT);
05446     SDValue FP = DAG.getNode(FCFOp, dl, FCFTy, Bits);
05447 
05448     if (Op.getValueType() == MVT::f32 && !Subtarget.hasFPCVT())
05449       FP = DAG.getNode(ISD::FP_ROUND, dl,
05450                        MVT::f32, FP, DAG.getIntPtrConstant(0));
05451     return FP;
05452   }
05453 
05454   assert(Op.getOperand(0).getValueType() == MVT::i32 &&
05455          "Unhandled INT_TO_FP type in custom expander!");
05456   // Since we only generate this in 64-bit mode, we can take advantage of
05457   // 64-bit registers.  In particular, sign extend the input value into the
05458   // 64-bit register with extsw, store the WHOLE 64-bit value into the stack
05459   // then lfd it and fcfid it.
05460   MachineFunction &MF = DAG.getMachineFunction();
05461   MachineFrameInfo *FrameInfo = MF.getFrameInfo();
05462   EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
05463 
05464   SDValue Ld;
05465   if (Subtarget.hasLFIWAX() || Subtarget.hasFPCVT()) {
05466     int FrameIdx = FrameInfo->CreateStackObject(4, 4, false);
05467     SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT);
05468 
05469     SDValue Store = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0), FIdx,
05470                                  MachinePointerInfo::getFixedStack(FrameIdx),
05471                                  false, false, 0);
05472 
05473     assert(cast<StoreSDNode>(Store)->getMemoryVT() == MVT::i32 &&
05474            "Expected an i32 store");
05475     MachineMemOperand *MMO =
05476       MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(FrameIdx),
05477                               MachineMemOperand::MOLoad, 4, 4);
05478     SDValue Ops[] = { Store, FIdx };
05479     Ld = DAG.getMemIntrinsicNode(Op.getOpcode() == ISD::UINT_TO_FP ?
05480                                    PPCISD::LFIWZX : PPCISD::LFIWAX,
05481                                  dl, DAG.getVTList(MVT::f64, MVT::Other),
05482                                  Ops, MVT::i32, MMO);
05483   } else {
05484     assert(Subtarget.isPPC64() &&
05485            "i32->FP without LFIWAX supported only on PPC64");
05486 
05487     int FrameIdx = FrameInfo->CreateStackObject(8, 8, false);
05488     SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT);
05489 
05490     SDValue Ext64 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::i64,
05491                                 Op.getOperand(0));
05492 
05493     // STD the extended value into the stack slot.
05494     SDValue Store = DAG.getStore(DAG.getEntryNode(), dl, Ext64, FIdx,
05495                                  MachinePointerInfo::getFixedStack(FrameIdx),
05496                                  false, false, 0);
05497 
05498     // Load the value as a double.
05499     Ld = DAG.getLoad(MVT::f64, dl, Store, FIdx,
05500                      MachinePointerInfo::getFixedStack(FrameIdx),
05501                      false, false, false, 0);
05502   }
05503 
05504   // FCFID it and return it.
05505   SDValue FP = DAG.getNode(FCFOp, dl, FCFTy, Ld);
05506   if (Op.getValueType() == MVT::f32 && !Subtarget.hasFPCVT())
05507     FP = DAG.getNode(ISD::FP_ROUND, dl, MVT::f32, FP, DAG.getIntPtrConstant(0));
05508   return FP;
05509 }
05510 
05511 SDValue PPCTargetLowering::LowerFLT_ROUNDS_(SDValue Op,
05512                                             SelectionDAG &DAG) const {
05513   SDLoc dl(Op);
05514   /*
05515    The rounding mode is in bits 30:31 of FPSR, and has the following
05516    settings:
05517      00 Round to nearest
05518      01 Round to 0
05519      10 Round to +inf
05520      11 Round to -inf
05521 
05522   FLT_ROUNDS, on the other hand, expects the following:
05523     -1 Undefined
05524      0 Round to 0
05525      1 Round to nearest
05526      2 Round to +inf
05527      3 Round to -inf
05528 
05529   To perform the conversion, we do:
05530     ((FPSCR & 0x3) ^ ((~FPSCR & 0x3) >> 1))
05531   */
05532 
05533   MachineFunction &MF = DAG.getMachineFunction();
05534   EVT VT = Op.getValueType();
05535   EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
05536 
05537   // Save FP Control Word to register
05538   EVT NodeTys[] = {
05539     MVT::f64,    // return register
05540     MVT::Glue    // unused in this context
05541   };
05542   SDValue Chain = DAG.getNode(PPCISD::MFFS, dl, NodeTys, None);
05543 
05544   // Save FP register to stack slot
05545   int SSFI = MF.getFrameInfo()->CreateStackObject(8, 8, false);
05546   SDValue StackSlot = DAG.getFrameIndex(SSFI, PtrVT);
05547   SDValue Store = DAG.getStore(DAG.getEntryNode(), dl, Chain,
05548                                StackSlot, MachinePointerInfo(), false, false,0);
05549 
05550   // Load FP Control Word from low 32 bits of stack slot.
05551   SDValue Four = DAG.getConstant(4, PtrVT);
05552   SDValue Addr = DAG.getNode(ISD::ADD, dl, PtrVT, StackSlot, Four);
05553   SDValue CWD = DAG.getLoad(MVT::i32, dl, Store, Addr, MachinePointerInfo(),
05554                             false, false, false, 0);
05555 
05556   // Transform as necessary
05557   SDValue CWD1 =
05558     DAG.getNode(ISD::AND, dl, MVT::i32,
05559                 CWD, DAG.getConstant(3, MVT::i32));
05560   SDValue CWD2 =
05561     DAG.getNode(ISD::SRL, dl, MVT::i32,
05562                 DAG.getNode(ISD::AND, dl, MVT::i32,
05563                             DAG.getNode(ISD::XOR, dl, MVT::i32,
05564                                         CWD, DAG.getConstant(3, MVT::i32)),
05565                             DAG.getConstant(3, MVT::i32)),
05566                 DAG.getConstant(1, MVT::i32));
05567 
05568   SDValue RetVal =
05569     DAG.getNode(ISD::XOR, dl, MVT::i32, CWD1, CWD2);
05570 
05571   return DAG.getNode((VT.getSizeInBits() < 16 ?
05572                       ISD::TRUNCATE : ISD::ZERO_EXTEND), dl, VT, RetVal);
05573 }
05574 
05575 SDValue PPCTargetLowering::LowerSHL_PARTS(SDValue Op, SelectionDAG &DAG) const {
05576   EVT VT = Op.getValueType();
05577   unsigned BitWidth = VT.getSizeInBits();
05578   SDLoc dl(Op);
05579   assert(Op.getNumOperands() == 3 &&
05580          VT == Op.getOperand(1).getValueType() &&
05581          "Unexpected SHL!");
05582 
05583   // Expand into a bunch of logical ops.  Note that these ops
05584   // depend on the PPC behavior for oversized shift amounts.
05585   SDValue Lo = Op.getOperand(0);
05586   SDValue Hi = Op.getOperand(1);
05587   SDValue Amt = Op.getOperand(2);
05588   EVT AmtVT = Amt.getValueType();
05589 
05590   SDValue Tmp1 = DAG.getNode(ISD::SUB, dl, AmtVT,
05591                              DAG.getConstant(BitWidth, AmtVT), Amt);
05592   SDValue Tmp2 = DAG.getNode(PPCISD::SHL, dl, VT, Hi, Amt);
05593   SDValue Tmp3 = DAG.getNode(PPCISD::SRL, dl, VT, Lo, Tmp1);
05594   SDValue Tmp4 = DAG.getNode(ISD::OR , dl, VT, Tmp2, Tmp3);
05595   SDValue Tmp5 = DAG.getNode(ISD::ADD, dl, AmtVT, Amt,
05596                              DAG.getConstant(-BitWidth, AmtVT));
05597   SDValue Tmp6 = DAG.getNode(PPCISD::SHL, dl, VT, Lo, Tmp5);
05598   SDValue OutHi = DAG.getNode(ISD::OR, dl, VT, Tmp4, Tmp6);
05599   SDValue OutLo = DAG.getNode(PPCISD::SHL, dl, VT, Lo, Amt);
05600   SDValue OutOps[] = { OutLo, OutHi };
05601   return DAG.getMergeValues(OutOps, dl);
05602 }
05603 
05604 SDValue PPCTargetLowering::LowerSRL_PARTS(SDValue Op, SelectionDAG &DAG) const {
05605   EVT VT = Op.getValueType();
05606   SDLoc dl(Op);
05607   unsigned BitWidth = VT.getSizeInBits();
05608   assert(Op.getNumOperands() == 3 &&
05609          VT == Op.getOperand(1).getValueType() &&
05610          "Unexpected SRL!");
05611 
05612   // Expand into a bunch of logical ops.  Note that these ops
05613   // depend on the PPC behavior for oversized shift amounts.
05614   SDValue Lo = Op.getOperand(0);
05615   SDValue Hi = Op.getOperand(1);
05616   SDValue Amt = Op.getOperand(2);
05617   EVT AmtVT = Amt.getValueType();
05618 
05619   SDValue Tmp1 = DAG.getNode(ISD::SUB, dl, AmtVT,
05620                              DAG.getConstant(BitWidth, AmtVT), Amt);
05621   SDValue Tmp2 = DAG.getNode(PPCISD::SRL, dl, VT, Lo, Amt);
05622   SDValue Tmp3 = DAG.getNode(PPCISD::SHL, dl, VT, Hi, Tmp1);
05623   SDValue Tmp4 = DAG.getNode(ISD::OR, dl, VT, Tmp2, Tmp3);
05624   SDValue Tmp5 = DAG.getNode(ISD::ADD, dl, AmtVT, Amt,
05625                              DAG.getConstant(-BitWidth, AmtVT));
05626   SDValue Tmp6 = DAG.getNode(PPCISD::SRL, dl, VT, Hi, Tmp5);
05627   SDValue OutLo = DAG.getNode(ISD::OR, dl, VT, Tmp4, Tmp6);
05628   SDValue OutHi = DAG.getNode(PPCISD::SRL, dl, VT, Hi, Amt);
05629   SDValue OutOps[] = { OutLo, OutHi };
05630   return DAG.getMergeValues(OutOps, dl);
05631 }
05632 
05633 SDValue PPCTargetLowering::LowerSRA_PARTS(SDValue Op, SelectionDAG &DAG) const {
05634   SDLoc dl(Op);
05635   EVT VT = Op.getValueType();
05636   unsigned BitWidth = VT.getSizeInBits();
05637   assert(Op.getNumOperands() == 3 &&
05638          VT == Op.getOperand(1).getValueType() &&
05639          "Unexpected SRA!");
05640 
05641   // Expand into a bunch of logical ops, followed by a select_cc.
05642   SDValue Lo = Op.getOperand(0);
05643   SDValue Hi = Op.getOperand(1);
05644   SDValue Amt = Op.getOperand(2);
05645   EVT AmtVT = Amt.getValueType();
05646 
05647   SDValue Tmp1 = DAG.getNode(ISD::SUB, dl, AmtVT,
05648                              DAG.getConstant(BitWidth, AmtVT), Amt);
05649   SDValue Tmp2 = DAG.getNode(PPCISD::SRL, dl, VT, Lo, Amt);
05650   SDValue Tmp3 = DAG.getNode(PPCISD::SHL, dl, VT, Hi, Tmp1);
05651   SDValue Tmp4 = DAG.getNode(ISD::OR, dl, VT, Tmp2, Tmp3);
05652   SDValue Tmp5 = DAG.getNode(ISD::ADD, dl, AmtVT, Amt,
05653                              DAG.getConstant(-BitWidth, AmtVT));
05654   SDValue Tmp6 = DAG.getNode(PPCISD::SRA, dl, VT, Hi, Tmp5);
05655   SDValue OutHi = DAG.getNode(PPCISD::SRA, dl, VT, Hi, Amt);
05656   SDValue OutLo = DAG.getSelectCC(dl, Tmp5, DAG.getConstant(0, AmtVT),
05657                                   Tmp4, Tmp6, ISD::SETLE);
05658   SDValue OutOps[] = { OutLo, OutHi };
05659   return DAG.getMergeValues(OutOps, dl);
05660 }
05661 
05662 //===----------------------------------------------------------------------===//
05663 // Vector related lowering.
05664 //
05665 
05666 /// BuildSplatI - Build a canonical splati of Val with an element size of
05667 /// SplatSize.  Cast the result to VT.
05668 static SDValue BuildSplatI(int Val, unsigned SplatSize, EVT VT,
05669                              SelectionDAG &DAG, SDLoc dl) {
05670   assert(Val >= -16 && Val <= 15 && "vsplti is out of range!");
05671 
05672   static const EVT VTys[] = { // canonical VT to use for each size.
05673     MVT::v16i8, MVT::v8i16, MVT::Other, MVT::v4i32
05674   };
05675 
05676   EVT ReqVT = VT != MVT::Other ? VT : VTys[SplatSize-1];
05677 
05678   // Force vspltis[hw] -1 to vspltisb -1 to canonicalize.
05679   if (Val == -1)
05680     SplatSize = 1;
05681 
05682   EVT CanonicalVT = VTys[SplatSize-1];
05683 
05684   // Build a canonical splat for this value.
05685   SDValue Elt = DAG.getConstant(Val, MVT::i32);
05686   SmallVector<SDValue, 8> Ops;
05687   Ops.assign(CanonicalVT.getVectorNumElements(), Elt);
05688   SDValue Res = DAG.getNode(ISD::BUILD_VECTOR, dl, CanonicalVT, Ops);
05689   return DAG.getNode(ISD::BITCAST, dl, ReqVT, Res);
05690 }
05691 
05692 /// BuildIntrinsicOp - Return a unary operator intrinsic node with the
05693 /// specified intrinsic ID.
05694 static SDValue BuildIntrinsicOp(unsigned IID, SDValue Op,
05695                                 SelectionDAG &DAG, SDLoc dl,
05696                                 EVT DestVT = MVT::Other) {
05697   if (DestVT == MVT::Other) DestVT = Op.getValueType();
05698   return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, DestVT,
05699                      DAG.getConstant(IID, MVT::i32), Op);
05700 }
05701 
05702 /// BuildIntrinsicOp - Return a binary operator intrinsic node with the
05703 /// specified intrinsic ID.
05704 static SDValue BuildIntrinsicOp(unsigned IID, SDValue LHS, SDValue RHS,
05705                                 SelectionDAG &DAG, SDLoc dl,
05706                                 EVT DestVT = MVT::Other) {
05707   if (DestVT == MVT::Other) DestVT = LHS.getValueType();
05708   return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, DestVT,
05709                      DAG.getConstant(IID, MVT::i32), LHS, RHS);
05710 }
05711 
05712 /// BuildIntrinsicOp - Return a ternary operator intrinsic node with the
05713 /// specified intrinsic ID.
05714 static SDValue BuildIntrinsicOp(unsigned IID, SDValue Op0, SDValue Op1,
05715                                 SDValue Op2, SelectionDAG &DAG,
05716                                 SDLoc dl, EVT DestVT = MVT::Other) {
05717   if (DestVT == MVT::Other) DestVT = Op0.getValueType();
05718   return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, DestVT,
05719                      DAG.getConstant(IID, MVT::i32), Op0, Op1, Op2);
05720 }
05721 
05722 
05723 /// BuildVSLDOI - Return a VECTOR_SHUFFLE that is a vsldoi of the specified
05724 /// amount.  The result has the specified value type.
05725 static SDValue BuildVSLDOI(SDValue LHS, SDValue RHS, unsigned Amt,
05726                              EVT VT, SelectionDAG &DAG, SDLoc dl) {
05727   // Force LHS/RHS to be the right type.
05728   LHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, LHS);
05729   RHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, RHS);
05730 
05731   int Ops[16];
05732   for (unsigned i = 0; i != 16; ++i)
05733     Ops[i] = i + Amt;
05734   SDValue T = DAG.getVectorShuffle(MVT::v16i8, dl, LHS, RHS, Ops);
05735   return DAG.getNode(ISD::BITCAST, dl, VT, T);
05736 }
05737 
05738 // If this is a case we can't handle, return null and let the default
05739 // expansion code take care of it.  If we CAN select this case, and if it
05740 // selects to a single instruction, return Op.  Otherwise, if we can codegen
05741 // this case more efficiently than a constant pool load, lower it to the
05742 // sequence of ops that should be used.
05743 SDValue PPCTargetLowering::LowerBUILD_VECTOR(SDValue Op,
05744                                              SelectionDAG &DAG) const {
05745   SDLoc dl(Op);
05746   BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(Op.getNode());
05747   assert(BVN && "Expected a BuildVectorSDNode in LowerBUILD_VECTOR");
05748 
05749   // Check if this is a splat of a constant value.
05750   APInt APSplatBits, APSplatUndef;
05751   unsigned SplatBitSize;
05752   bool HasAnyUndefs;
05753   if (! BVN->isConstantSplat(APSplatBits, APSplatUndef, SplatBitSize,
05754                              HasAnyUndefs, 0, true) || SplatBitSize > 32)
05755     return SDValue();
05756 
05757   unsigned SplatBits = APSplatBits.getZExtValue();
05758   unsigned SplatUndef = APSplatUndef.getZExtValue();
05759   unsigned SplatSize = SplatBitSize / 8;
05760 
05761   // First, handle single instruction cases.
05762 
05763   // All zeros?
05764   if (SplatBits == 0) {
05765     // Canonicalize all zero vectors to be v4i32.
05766     if (Op.getValueType() != MVT::v4i32 || HasAnyUndefs) {
05767       SDValue Z = DAG.getConstant(0, MVT::i32);
05768       Z = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Z, Z, Z, Z);
05769       Op = DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Z);
05770     }
05771     return Op;
05772   }
05773 
05774   // If the sign extended value is in the range [-16,15], use VSPLTI[bhw].
05775   int32_t SextVal= (int32_t(SplatBits << (32-SplatBitSize)) >>
05776                     (32-SplatBitSize));
05777   if (SextVal >= -16 && SextVal <= 15)
05778     return BuildSplatI(SextVal, SplatSize, Op.getValueType(), DAG, dl);
05779 
05780 
05781   // Two instruction sequences.
05782 
05783   // If this value is in the range [-32,30] and is even, use:
05784   //     VSPLTI[bhw](val/2) + VSPLTI[bhw](val/2)
05785   // If this value is in the range [17,31] and is odd, use:
05786   //     VSPLTI[bhw](val-16) - VSPLTI[bhw](-16)
05787   // If this value is in the range [-31,-17] and is odd, use:
05788   //     VSPLTI[bhw](val+16) + VSPLTI[bhw](-16)
05789   // Note the last two are three-instruction sequences.
05790   if (SextVal >= -32 && SextVal <= 31) {
05791     // To avoid having these optimizations undone by constant folding,
05792     // we convert to a pseudo that will be expanded later into one of
05793     // the above forms.
05794     SDValue Elt = DAG.getConstant(SextVal, MVT::i32);
05795     EVT VT = (SplatSize == 1 ? MVT::v16i8 :
05796               (SplatSize == 2 ? MVT::v8i16 : MVT::v4i32));
05797     SDValue EltSize = DAG.getConstant(SplatSize, MVT::i32);
05798     SDValue RetVal = DAG.getNode(PPCISD::VADD_SPLAT, dl, VT, Elt, EltSize);
05799     if (VT == Op.getValueType())
05800       return RetVal;
05801     else
05802       return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), RetVal);
05803   }
05804 
05805   // If this is 0x8000_0000 x 4, turn into vspltisw + vslw.  If it is
05806   // 0x7FFF_FFFF x 4, turn it into not(0x8000_0000).  This is important
05807   // for fneg/fabs.
05808   if (SplatSize == 4 && SplatBits == (0x7FFFFFFF&~SplatUndef)) {
05809     // Make -1 and vspltisw -1:
05810     SDValue OnesV = BuildSplatI(-1, 4, MVT::v4i32, DAG, dl);
05811 
05812     // Make the VSLW intrinsic, computing 0x8000_0000.
05813     SDValue Res = BuildIntrinsicOp(Intrinsic::ppc_altivec_vslw, OnesV,
05814                                    OnesV, DAG, dl);
05815 
05816     // xor by OnesV to invert it.
05817     Res = DAG.getNode(ISD::XOR, dl, MVT::v4i32, Res, OnesV);
05818     return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Res);
05819   }
05820 
05821   // The remaining cases assume either big endian element order or
05822   // a splat-size that equates to the element size of the vector
05823   // to be built.  An example that doesn't work for little endian is
05824   // {0, -1, 0, -1, 0, -1, 0, -1} which has a splat size of 32 bits
05825   // and a vector element size of 16 bits.  The code below will
05826   // produce the vector in big endian element order, which for little
05827   // endian is {-1, 0, -1, 0, -1, 0, -1, 0}.
05828 
05829   // For now, just avoid these optimizations in that case.
05830   // FIXME: Develop correct optimizations for LE with mismatched
05831   // splat and element sizes.
05832 
05833   if (Subtarget.isLittleEndian() &&
05834       SplatSize != Op.getValueType().getVectorElementType().getSizeInBits())
05835     return SDValue();
05836 
05837   // Check to see if this is a wide variety of vsplti*, binop self cases.
05838   static const signed char SplatCsts[] = {
05839     -1, 1, -2, 2, -3, 3, -4, 4, -5, 5, -6, 6, -7, 7,
05840     -8, 8, -9, 9, -10, 10, -11, 11, -12, 12, -13, 13, 14, -14, 15, -15, -16
05841   };
05842 
05843   for (unsigned idx = 0; idx < array_lengthof(SplatCsts); ++idx) {
05844     // Indirect through the SplatCsts array so that we favor 'vsplti -1' for
05845     // cases which are ambiguous (e.g. formation of 0x8000_0000).  'vsplti -1'
05846     int i = SplatCsts[idx];
05847 
05848     // Figure out what shift amount will be used by altivec if shifted by i in
05849     // this splat size.
05850     unsigned TypeShiftAmt = i & (SplatBitSize-1);
05851 
05852     // vsplti + shl self.
05853     if (SextVal == (int)((unsigned)i << TypeShiftAmt)) {
05854       SDValue Res = BuildSplatI(i, SplatSize, MVT::Other, DAG, dl);
05855       static const unsigned IIDs[] = { // Intrinsic to use for each size.
05856         Intrinsic::ppc_altivec_vslb, Intrinsic::ppc_altivec_vslh, 0,
05857         Intrinsic::ppc_altivec_vslw
05858       };
05859       Res = BuildIntrinsicOp(IIDs[SplatSize-1], Res, Res, DAG, dl);
05860       return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Res);
05861     }
05862 
05863     // vsplti + srl self.
05864     if (SextVal == (int)((unsigned)i >> TypeShiftAmt)) {
05865       SDValue Res = BuildSplatI(i, SplatSize, MVT::Other, DAG, dl);
05866       static const unsigned IIDs[] = { // Intrinsic to use for each size.
05867         Intrinsic::ppc_altivec_vsrb, Intrinsic::ppc_altivec_vsrh, 0,
05868         Intrinsic::ppc_altivec_vsrw
05869       };
05870       Res = BuildIntrinsicOp(IIDs[SplatSize-1], Res, Res, DAG, dl);
05871       return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Res);
05872     }
05873 
05874     // vsplti + sra self.
05875     if (SextVal == (int)((unsigned)i >> TypeShiftAmt)) {
05876       SDValue Res = BuildSplatI(i, SplatSize, MVT::Other, DAG, dl);
05877       static const unsigned IIDs[] = { // Intrinsic to use for each size.
05878         Intrinsic::ppc_altivec_vsrab, Intrinsic::ppc_altivec_vsrah, 0,
05879         Intrinsic::ppc_altivec_vsraw
05880       };
05881       Res = BuildIntrinsicOp(IIDs[SplatSize-1], Res, Res, DAG, dl);
05882       return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Res);
05883     }
05884 
05885     // vsplti + rol self.
05886     if (SextVal == (int)(((unsigned)i << TypeShiftAmt) |
05887                          ((unsigned)i >> (SplatBitSize-TypeShiftAmt)))) {
05888       SDValue Res = BuildSplatI(i, SplatSize, MVT::Other, DAG, dl);
05889       static const unsigned IIDs[] = { // Intrinsic to use for each size.
05890         Intrinsic::ppc_altivec_vrlb, Intrinsic::ppc_altivec_vrlh, 0,
05891         Intrinsic::ppc_altivec_vrlw
05892       };
05893       Res = BuildIntrinsicOp(IIDs[SplatSize-1], Res, Res, DAG, dl);
05894       return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Res);
05895     }
05896 
05897     // t = vsplti c, result = vsldoi t, t, 1
05898     if (SextVal == (int)(((unsigned)i << 8) | (i < 0 ? 0xFF : 0))) {
05899       SDValue T = BuildSplatI(i, SplatSize, MVT::v16i8, DAG, dl);
05900       return BuildVSLDOI(T, T, 1, Op.getValueType(), DAG, dl);
05901     }
05902     // t = vsplti c, result = vsldoi t, t, 2
05903     if (SextVal == (int)(((unsigned)i << 16) | (i < 0 ? 0xFFFF : 0))) {
05904       SDValue T = BuildSplatI(i, SplatSize, MVT::v16i8, DAG, dl);
05905       return BuildVSLDOI(T, T, 2, Op.getValueType(), DAG, dl);
05906     }
05907     // t = vsplti c, result = vsldoi t, t, 3
05908     if (SextVal == (int)(((unsigned)i << 24) | (i < 0 ? 0xFFFFFF : 0))) {
05909       SDValue T = BuildSplatI(i, SplatSize, MVT::v16i8, DAG, dl);
05910       return BuildVSLDOI(T, T, 3, Op.getValueType(), DAG, dl);
05911     }
05912   }
05913 
05914   return SDValue();
05915 }
05916 
05917 /// GeneratePerfectShuffle - Given an entry in the perfect-shuffle table, emit
05918 /// the specified operations to build the shuffle.
05919 static SDValue GeneratePerfectShuffle(unsigned PFEntry, SDValue LHS,
05920                                       SDValue RHS, SelectionDAG &DAG,
05921                                       SDLoc dl) {
05922   unsigned OpNum = (PFEntry >> 26) & 0x0F;
05923   unsigned LHSID = (PFEntry >> 13) & ((1 << 13)-1);
05924   unsigned RHSID = (PFEntry >>  0) & ((1 << 13)-1);
05925 
05926   enum {
05927     OP_COPY = 0,  // Copy, used for things like <u,u,u,3> to say it is <0,1,2,3>
05928     OP_VMRGHW,
05929     OP_VMRGLW,
05930     OP_VSPLTISW0,
05931     OP_VSPLTISW1,
05932     OP_VSPLTISW2,
05933     OP_VSPLTISW3,
05934     OP_VSLDOI4,
05935     OP_VSLDOI8,
05936     OP_VSLDOI12
05937   };
05938 
05939   if (OpNum == OP_COPY) {
05940     if (LHSID == (1*9+2)*9+3) return LHS;
05941     assert(LHSID == ((4*9+5)*9+6)*9+7 && "Illegal OP_COPY!");
05942     return RHS;
05943   }
05944 
05945   SDValue OpLHS, OpRHS;
05946   OpLHS = GeneratePerfectShuffle(PerfectShuffleTable[LHSID], LHS, RHS, DAG, dl);
05947   OpRHS = GeneratePerfectShuffle(PerfectShuffleTable[RHSID], LHS, RHS, DAG, dl);
05948 
05949   int ShufIdxs[16];
05950   switch (OpNum) {
05951   default: llvm_unreachable("Unknown i32 permute!");
05952   case OP_VMRGHW:
05953     ShufIdxs[ 0] =  0; ShufIdxs[ 1] =  1; ShufIdxs[ 2] =  2; ShufIdxs[ 3] =  3;
05954     ShufIdxs[ 4] = 16; ShufIdxs[ 5] = 17; ShufIdxs[ 6] = 18; ShufIdxs[ 7] = 19;
05955     ShufIdxs[ 8] =  4; ShufIdxs[ 9] =  5; ShufIdxs[10] =  6; ShufIdxs[11] =  7;
05956     ShufIdxs[12] = 20; ShufIdxs[13] = 21; ShufIdxs[14] = 22; ShufIdxs[15] = 23;
05957     break;
05958   case OP_VMRGLW:
05959     ShufIdxs[ 0] =  8; ShufIdxs[ 1] =  9; ShufIdxs[ 2] = 10; ShufIdxs[ 3] = 11;
05960     ShufIdxs[ 4] = 24; ShufIdxs[ 5] = 25; ShufIdxs[ 6] = 26; ShufIdxs[ 7] = 27;
05961     ShufIdxs[ 8] = 12; ShufIdxs[ 9] = 13; ShufIdxs[10] = 14; ShufIdxs[11] = 15;
05962     ShufIdxs[12] = 28; ShufIdxs[13] = 29; ShufIdxs[14] = 30; ShufIdxs[15] = 31;
05963     break;
05964   case OP_VSPLTISW0:
05965     for (unsigned i = 0; i != 16; ++i)
05966       ShufIdxs[i] = (i&3)+0;
05967     break;
05968   case OP_VSPLTISW1:
05969     for (unsigned i = 0; i != 16; ++i)
05970       ShufIdxs[i] = (i&3)+4;
05971     break;
05972   case OP_VSPLTISW2:
05973     for (unsigned i = 0; i != 16; ++i)
05974       ShufIdxs[i] = (i&3)+8;
05975     break;
05976   case OP_VSPLTISW3:
05977     for (unsigned i = 0; i != 16; ++i)
05978       ShufIdxs[i] = (i&3)+12;
05979     break;
05980   case OP_VSLDOI4:
05981     return BuildVSLDOI(OpLHS, OpRHS, 4, OpLHS.getValueType(), DAG, dl);
05982   case OP_VSLDOI8:
05983     return BuildVSLDOI(OpLHS, OpRHS, 8, OpLHS.getValueType(), DAG, dl);
05984   case OP_VSLDOI12:
05985     return BuildVSLDOI(OpLHS, OpRHS, 12, OpLHS.getValueType(), DAG, dl);
05986   }
05987   EVT VT = OpLHS.getValueType();
05988   OpLHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, OpLHS);
05989   OpRHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, OpRHS);
05990   SDValue T = DAG.getVectorShuffle(MVT::v16i8, dl, OpLHS, OpRHS, ShufIdxs);
05991   return DAG.getNode(ISD::BITCAST, dl, VT, T);
05992 }
05993 
05994 /// LowerVECTOR_SHUFFLE - Return the code we lower for VECTOR_SHUFFLE.  If this
05995 /// is a shuffle we can handle in a single instruction, return it.  Otherwise,
05996 /// return the code it can be lowered into.  Worst case, it can always be
05997 /// lowered into a vperm.
05998 SDValue PPCTargetLowering::LowerVECTOR_SHUFFLE(SDValue Op,
05999                                                SelectionDAG &DAG) const {
06000   SDLoc dl(Op);
06001   SDValue V1 = Op.getOperand(0);
06002   SDValue V2 = Op.getOperand(1);
06003   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
06004   EVT VT = Op.getValueType();
06005   bool isLittleEndian = Subtarget.isLittleEndian();
06006 
06007   // Cases that are handled by instructions that take permute immediates
06008   // (such as vsplt*) should be left as VECTOR_SHUFFLE nodes so they can be
06009   // selected by the instruction selector.
06010   if (V2.getOpcode() == ISD::UNDEF) {
06011     if (PPC::isSplatShuffleMask(SVOp, 1) ||
06012         PPC::isSplatShuffleMask(SVOp, 2) ||
06013         PPC::isSplatShuffleMask(SVOp, 4) ||
06014         PPC::isVPKUWUMShuffleMask(SVOp, true, DAG) ||
06015         PPC::isVPKUHUMShuffleMask(SVOp, true, DAG) ||
06016         PPC::isVSLDOIShuffleMask(SVOp, true, DAG) != -1 ||
06017         PPC::isVMRGLShuffleMask(SVOp, 1, true, DAG) ||
06018         PPC::isVMRGLShuffleMask(SVOp, 2, true, DAG) ||
06019         PPC::isVMRGLShuffleMask(SVOp, 4, true, DAG) ||
06020         PPC::isVMRGHShuffleMask(SVOp, 1, true, DAG) ||
06021         PPC::isVMRGHShuffleMask(SVOp, 2, true, DAG) ||
06022         PPC::isVMRGHShuffleMask(SVOp, 4, true, DAG)) {
06023       return Op;
06024     }
06025   }
06026 
06027   // Altivec has a variety of "shuffle immediates" that take two vector inputs
06028   // and produce a fixed permutation.  If any of these match, do not lower to
06029   // VPERM.
06030   if (PPC::isVPKUWUMShuffleMask(SVOp, false, DAG) ||
06031       PPC::isVPKUHUMShuffleMask(SVOp, false, DAG) ||
06032       PPC::isVSLDOIShuffleMask(SVOp, false, DAG) != -1 ||
06033       PPC::isVMRGLShuffleMask(SVOp, 1, false, DAG) ||
06034       PPC::isVMRGLShuffleMask(SVOp, 2, false, DAG) ||
06035       PPC::isVMRGLShuffleMask(SVOp, 4, false, DAG) ||
06036       PPC::isVMRGHShuffleMask(SVOp, 1, false, DAG) ||
06037       PPC::isVMRGHShuffleMask(SVOp, 2, false, DAG) ||
06038       PPC::isVMRGHShuffleMask(SVOp, 4, false, DAG))
06039     return Op;
06040 
06041   // Check to see if this is a shuffle of 4-byte values.  If so, we can use our
06042   // perfect shuffle table to emit an optimal matching sequence.
06043   ArrayRef<int> PermMask = SVOp->getMask();
06044 
06045   unsigned PFIndexes[4];
06046   bool isFourElementShuffle = true;
06047   for (unsigned i = 0; i != 4 && isFourElementShuffle; ++i) { // Element number
06048     unsigned EltNo = 8;   // Start out undef.
06049     for (unsigned j = 0; j != 4; ++j) {  // Intra-element byte.
06050       if (PermMask[i*4+j] < 0)
06051         continue;   // Undef, ignore it.
06052 
06053       unsigned ByteSource = PermMask[i*4+j];
06054       if ((ByteSource & 3) != j) {
06055         isFourElementShuffle = false;
06056         break;
06057       }
06058 
06059       if (EltNo == 8) {
06060         EltNo = ByteSource/4;
06061       } else if (EltNo != ByteSource/4) {
06062         isFourElementShuffle = false;
06063         break;
06064       }
06065     }
06066     PFIndexes[i] = EltNo;
06067   }
06068 
06069   // If this shuffle can be expressed as a shuffle of 4-byte elements, use the
06070   // perfect shuffle vector to determine if it is cost effective to do this as
06071   // discrete instructions, or whether we should use a vperm.
06072   // For now, we skip this for little endian until such time as we have a
06073   // little-endian perfect shuffle table.
06074   if (isFourElementShuffle && !isLittleEndian) {
06075     // Compute the index in the perfect shuffle table.
06076     unsigned PFTableIndex =
06077       PFIndexes[0]*9*9*9+PFIndexes[1]*9*9+PFIndexes[2]*9+PFIndexes[3];
06078 
06079     unsigned PFEntry = PerfectShuffleTable[PFTableIndex];
06080     unsigned Cost  = (PFEntry >> 30);
06081 
06082     // Determining when to avoid vperm is tricky.  Many things affect the cost
06083     // of vperm, particularly how many times the perm mask needs to be computed.
06084     // For example, if the perm mask can be hoisted out of a loop or is already
06085     // used (perhaps because there are multiple permutes with the same shuffle
06086     // mask?) the vperm has a cost of 1.  OTOH, hoisting the permute mask out of
06087     // the loop requires an extra register.
06088     //
06089     // As a compromise, we only emit discrete instructions if the shuffle can be
06090     // generated in 3 or fewer operations.  When we have loop information
06091     // available, if this block is within a loop, we should avoid using vperm
06092     // for 3-operation perms and use a constant pool load instead.
06093     if (Cost < 3)
06094       return GeneratePerfectShuffle(PFEntry, V1, V2, DAG, dl);
06095   }
06096 
06097   // Lower this to a VPERM(V1, V2, V3) expression, where V3 is a constant
06098   // vector that will get spilled to the constant pool.
06099   if (V2.getOpcode() == ISD::UNDEF) V2 = V1;
06100 
06101   // The SHUFFLE_VECTOR mask is almost exactly what we want for vperm, except
06102   // that it is in input element units, not in bytes.  Convert now.
06103 
06104   // For little endian, the order of the input vectors is reversed, and
06105   // the permutation mask is complemented with respect to 31.  This is
06106   // necessary to produce proper semantics with the big-endian-biased vperm
06107   // instruction.
06108   EVT EltVT = V1.getValueType().getVectorElementType();
06109   unsigned BytesPerElement = EltVT.getSizeInBits()/8;
06110 
06111   SmallVector<SDValue, 16> ResultMask;
06112   for (unsigned i = 0, e = VT.getVectorNumElements(); i != e; ++i) {
06113     unsigned SrcElt = PermMask[i] < 0 ? 0 : PermMask[i];
06114 
06115     for (unsigned j = 0; j != BytesPerElement; ++j)
06116       if (isLittleEndian)
06117         ResultMask.push_back(DAG.getConstant(31 - (SrcElt*BytesPerElement+j),
06118                                              MVT::i32));
06119       else
06120         ResultMask.push_back(DAG.getConstant(SrcElt*BytesPerElement+j,
06121                                              MVT::i32));
06122   }
06123 
06124   SDValue VPermMask = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v16i8,
06125                                   ResultMask);
06126   if (isLittleEndian)
06127     return DAG.getNode(PPCISD::VPERM, dl, V1.getValueType(),
06128                        V2, V1, VPermMask);
06129   else
06130     return DAG.getNode(PPCISD::VPERM, dl, V1.getValueType(),
06131                        V1, V2, VPermMask);
06132 }
06133 
06134 /// getAltivecCompareInfo - Given an intrinsic, return false if it is not an
06135 /// altivec comparison.  If it is, return true and fill in Opc/isDot with
06136 /// information about the intrinsic.
06137 static bool getAltivecCompareInfo(SDValue Intrin, int &CompareOpc,
06138                                   bool &isDot) {
06139   unsigned IntrinsicID =
06140     cast<ConstantSDNode>(Intrin.getOperand(0))->getZExtValue();
06141   CompareOpc = -1;
06142   isDot = false;
06143   switch (IntrinsicID) {
06144   default: return false;
06145     // Comparison predicates.
06146   case Intrinsic::ppc_altivec_vcmpbfp_p:  CompareOpc = 966; isDot = 1; break;
06147   case Intrinsic::ppc_altivec_vcmpeqfp_p: CompareOpc = 198; isDot = 1; break;
06148   case Intrinsic::ppc_altivec_vcmpequb_p: CompareOpc =   6; isDot = 1; break;
06149   case Intrinsic::ppc_altivec_vcmpequh_p: CompareOpc =  70; isDot = 1; break;
06150   case Intrinsic::ppc_altivec_vcmpequw_p: CompareOpc = 134; isDot = 1; break;
06151   case Intrinsic::ppc_altivec_vcmpgefp_p: CompareOpc = 454; isDot = 1; break;
06152   case Intrinsic::ppc_altivec_vcmpgtfp_p: CompareOpc = 710; isDot = 1; break;
06153   case Intrinsic::ppc_altivec_vcmpgtsb_p: CompareOpc = 774; isDot = 1; break;
06154   case Intrinsic::ppc_altivec_vcmpgtsh_p: CompareOpc = 838; isDot = 1; break;
06155   case Intrinsic::ppc_altivec_vcmpgtsw_p: CompareOpc = 902; isDot = 1; break;
06156   case Intrinsic::ppc_altivec_vcmpgtub_p: CompareOpc = 518; isDot = 1; break;
06157   case Intrinsic::ppc_altivec_vcmpgtuh_p: CompareOpc = 582; isDot = 1; break;
06158   case Intrinsic::ppc_altivec_vcmpgtuw_p: CompareOpc = 646; isDot = 1; break;
06159 
06160     // Normal Comparisons.
06161   case Intrinsic::ppc_altivec_vcmpbfp:    CompareOpc = 966; isDot = 0; break;
06162   case Intrinsic::ppc_altivec_vcmpeqfp:   CompareOpc = 198; isDot = 0; break;
06163   case Intrinsic::ppc_altivec_vcmpequb:   CompareOpc =   6; isDot = 0; break;
06164   case Intrinsic::ppc_altivec_vcmpequh:   CompareOpc =  70; isDot = 0; break;
06165   case Intrinsic::ppc_altivec_vcmpequw:   CompareOpc = 134; isDot = 0; break;
06166   case Intrinsic::ppc_altivec_vcmpgefp:   CompareOpc = 454; isDot = 0; break;
06167   case Intrinsic::ppc_altivec_vcmpgtfp:   CompareOpc = 710; isDot = 0; break;
06168   case Intrinsic::ppc_altivec_vcmpgtsb:   CompareOpc = 774; isDot = 0; break;
06169   case Intrinsic::ppc_altivec_vcmpgtsh:   CompareOpc = 838; isDot = 0; break;
06170   case Intrinsic::ppc_altivec_vcmpgtsw:   CompareOpc = 902; isDot = 0; break;
06171   case Intrinsic::ppc_altivec_vcmpgtub:   CompareOpc = 518; isDot = 0; break;
06172   case Intrinsic::ppc_altivec_vcmpgtuh:   CompareOpc = 582; isDot = 0; break;
06173   case Intrinsic::ppc_altivec_vcmpgtuw:   CompareOpc = 646; isDot = 0; break;
06174   }
06175   return true;
06176 }
06177 
06178 /// LowerINTRINSIC_WO_CHAIN - If this is an intrinsic that we want to custom
06179 /// lower, do it, otherwise return null.
06180 SDValue PPCTargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op,
06181                                                    SelectionDAG &DAG) const {
06182   // If this is a lowered altivec predicate compare, CompareOpc i