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