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