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