LLVM API Documentation

ARMISelLowering.cpp
Go to the documentation of this file.
00001 //===-- ARMISelLowering.cpp - ARM 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 defines the interfaces that ARM uses to lower LLVM code into a
00011 // selection DAG.
00012 //
00013 //===----------------------------------------------------------------------===//
00014 
00015 #include "ARMISelLowering.h"
00016 #include "ARMCallingConv.h"
00017 #include "ARMConstantPoolValue.h"
00018 #include "ARMMachineFunctionInfo.h"
00019 #include "ARMPerfectShuffle.h"
00020 #include "ARMSubtarget.h"
00021 #include "ARMTargetMachine.h"
00022 #include "ARMTargetObjectFile.h"
00023 #include "MCTargetDesc/ARMAddressingModes.h"
00024 #include "llvm/ADT/Statistic.h"
00025 #include "llvm/ADT/StringExtras.h"
00026 #include "llvm/CodeGen/CallingConvLower.h"
00027 #include "llvm/CodeGen/IntrinsicLowering.h"
00028 #include "llvm/CodeGen/MachineBasicBlock.h"
00029 #include "llvm/CodeGen/MachineFrameInfo.h"
00030 #include "llvm/CodeGen/MachineFunction.h"
00031 #include "llvm/CodeGen/MachineInstrBuilder.h"
00032 #include "llvm/CodeGen/MachineJumpTableInfo.h"
00033 #include "llvm/CodeGen/MachineModuleInfo.h"
00034 #include "llvm/CodeGen/MachineRegisterInfo.h"
00035 #include "llvm/CodeGen/SelectionDAG.h"
00036 #include "llvm/IR/CallingConv.h"
00037 #include "llvm/IR/Constants.h"
00038 #include "llvm/IR/Function.h"
00039 #include "llvm/IR/GlobalValue.h"
00040 #include "llvm/IR/IRBuilder.h"
00041 #include "llvm/IR/Instruction.h"
00042 #include "llvm/IR/Instructions.h"
00043 #include "llvm/IR/Intrinsics.h"
00044 #include "llvm/IR/Type.h"
00045 #include "llvm/MC/MCSectionMachO.h"
00046 #include "llvm/Support/CommandLine.h"
00047 #include "llvm/Support/Debug.h"
00048 #include "llvm/Support/ErrorHandling.h"
00049 #include "llvm/Support/MathExtras.h"
00050 #include "llvm/Target/TargetOptions.h"
00051 #include <utility>
00052 using namespace llvm;
00053 
00054 #define DEBUG_TYPE "arm-isel"
00055 
00056 STATISTIC(NumTailCalls, "Number of tail calls");
00057 STATISTIC(NumMovwMovt, "Number of GAs materialized with movw + movt");
00058 STATISTIC(NumLoopByVals, "Number of loops generated for byval arguments");
00059 
00060 cl::opt<bool>
00061 EnableARMLongCalls("arm-long-calls", cl::Hidden,
00062   cl::desc("Generate calls via indirect call instructions"),
00063   cl::init(false));
00064 
00065 static cl::opt<bool>
00066 ARMInterworking("arm-interworking", cl::Hidden,
00067   cl::desc("Enable / disable ARM interworking (for debugging only)"),
00068   cl::init(true));
00069 
00070 namespace {
00071   class ARMCCState : public CCState {
00072   public:
00073     ARMCCState(CallingConv::ID CC, bool isVarArg, MachineFunction &MF,
00074                SmallVectorImpl<CCValAssign> &locs, LLVMContext &C,
00075                ParmContext PC)
00076         : CCState(CC, isVarArg, MF, locs, C) {
00077       assert(((PC == Call) || (PC == Prologue)) &&
00078              "ARMCCState users must specify whether their context is call"
00079              "or prologue generation.");
00080       CallOrPrologue = PC;
00081     }
00082   };
00083 }
00084 
00085 // The APCS parameter registers.
00086 static const MCPhysReg GPRArgRegs[] = {
00087   ARM::R0, ARM::R1, ARM::R2, ARM::R3
00088 };
00089 
00090 void ARMTargetLowering::addTypeForNEON(MVT VT, MVT PromotedLdStVT,
00091                                        MVT PromotedBitwiseVT) {
00092   if (VT != PromotedLdStVT) {
00093     setOperationAction(ISD::LOAD, VT, Promote);
00094     AddPromotedToType (ISD::LOAD, VT, PromotedLdStVT);
00095 
00096     setOperationAction(ISD::STORE, VT, Promote);
00097     AddPromotedToType (ISD::STORE, VT, PromotedLdStVT);
00098   }
00099 
00100   MVT ElemTy = VT.getVectorElementType();
00101   if (ElemTy != MVT::i64 && ElemTy != MVT::f64)
00102     setOperationAction(ISD::SETCC, VT, Custom);
00103   setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Custom);
00104   setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
00105   if (ElemTy == MVT::i32) {
00106     setOperationAction(ISD::SINT_TO_FP, VT, Custom);
00107     setOperationAction(ISD::UINT_TO_FP, VT, Custom);
00108     setOperationAction(ISD::FP_TO_SINT, VT, Custom);
00109     setOperationAction(ISD::FP_TO_UINT, VT, Custom);
00110   } else {
00111     setOperationAction(ISD::SINT_TO_FP, VT, Expand);
00112     setOperationAction(ISD::UINT_TO_FP, VT, Expand);
00113     setOperationAction(ISD::FP_TO_SINT, VT, Expand);
00114     setOperationAction(ISD::FP_TO_UINT, VT, Expand);
00115   }
00116   setOperationAction(ISD::BUILD_VECTOR,      VT, Custom);
00117   setOperationAction(ISD::VECTOR_SHUFFLE,    VT, Custom);
00118   setOperationAction(ISD::CONCAT_VECTORS,    VT, Legal);
00119   setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Legal);
00120   setOperationAction(ISD::SELECT,            VT, Expand);
00121   setOperationAction(ISD::SELECT_CC,         VT, Expand);
00122   setOperationAction(ISD::VSELECT,           VT, Expand);
00123   setOperationAction(ISD::SIGN_EXTEND_INREG, VT, Expand);
00124   if (VT.isInteger()) {
00125     setOperationAction(ISD::SHL, VT, Custom);
00126     setOperationAction(ISD::SRA, VT, Custom);
00127     setOperationAction(ISD::SRL, VT, Custom);
00128   }
00129 
00130   // Promote all bit-wise operations.
00131   if (VT.isInteger() && VT != PromotedBitwiseVT) {
00132     setOperationAction(ISD::AND, VT, Promote);
00133     AddPromotedToType (ISD::AND, VT, PromotedBitwiseVT);
00134     setOperationAction(ISD::OR,  VT, Promote);
00135     AddPromotedToType (ISD::OR,  VT, PromotedBitwiseVT);
00136     setOperationAction(ISD::XOR, VT, Promote);
00137     AddPromotedToType (ISD::XOR, VT, PromotedBitwiseVT);
00138   }
00139 
00140   // Neon does not support vector divide/remainder operations.
00141   setOperationAction(ISD::SDIV, VT, Expand);
00142   setOperationAction(ISD::UDIV, VT, Expand);
00143   setOperationAction(ISD::FDIV, VT, Expand);
00144   setOperationAction(ISD::SREM, VT, Expand);
00145   setOperationAction(ISD::UREM, VT, Expand);
00146   setOperationAction(ISD::FREM, VT, Expand);
00147 }
00148 
00149 void ARMTargetLowering::addDRTypeForNEON(MVT VT) {
00150   addRegisterClass(VT, &ARM::DPRRegClass);
00151   addTypeForNEON(VT, MVT::f64, MVT::v2i32);
00152 }
00153 
00154 void ARMTargetLowering::addQRTypeForNEON(MVT VT) {
00155   addRegisterClass(VT, &ARM::DPairRegClass);
00156   addTypeForNEON(VT, MVT::v2f64, MVT::v4i32);
00157 }
00158 
00159 ARMTargetLowering::ARMTargetLowering(const TargetMachine &TM)
00160     : TargetLowering(TM) {
00161   Subtarget = &TM.getSubtarget<ARMSubtarget>();
00162   RegInfo = TM.getSubtargetImpl()->getRegisterInfo();
00163   Itins = TM.getSubtargetImpl()->getInstrItineraryData();
00164 
00165   setBooleanVectorContents(ZeroOrNegativeOneBooleanContent);
00166 
00167   if (Subtarget->isTargetMachO()) {
00168     // Uses VFP for Thumb libfuncs if available.
00169     if (Subtarget->isThumb() && Subtarget->hasVFP2() &&
00170         Subtarget->hasARMOps() && !TM.Options.UseSoftFloat) {
00171       // Single-precision floating-point arithmetic.
00172       setLibcallName(RTLIB::ADD_F32, "__addsf3vfp");
00173       setLibcallName(RTLIB::SUB_F32, "__subsf3vfp");
00174       setLibcallName(RTLIB::MUL_F32, "__mulsf3vfp");
00175       setLibcallName(RTLIB::DIV_F32, "__divsf3vfp");
00176 
00177       // Double-precision floating-point arithmetic.
00178       setLibcallName(RTLIB::ADD_F64, "__adddf3vfp");
00179       setLibcallName(RTLIB::SUB_F64, "__subdf3vfp");
00180       setLibcallName(RTLIB::MUL_F64, "__muldf3vfp");
00181       setLibcallName(RTLIB::DIV_F64, "__divdf3vfp");
00182 
00183       // Single-precision comparisons.
00184       setLibcallName(RTLIB::OEQ_F32, "__eqsf2vfp");
00185       setLibcallName(RTLIB::UNE_F32, "__nesf2vfp");
00186       setLibcallName(RTLIB::OLT_F32, "__ltsf2vfp");
00187       setLibcallName(RTLIB::OLE_F32, "__lesf2vfp");
00188       setLibcallName(RTLIB::OGE_F32, "__gesf2vfp");
00189       setLibcallName(RTLIB::OGT_F32, "__gtsf2vfp");
00190       setLibcallName(RTLIB::UO_F32,  "__unordsf2vfp");
00191       setLibcallName(RTLIB::O_F32,   "__unordsf2vfp");
00192 
00193       setCmpLibcallCC(RTLIB::OEQ_F32, ISD::SETNE);
00194       setCmpLibcallCC(RTLIB::UNE_F32, ISD::SETNE);
00195       setCmpLibcallCC(RTLIB::OLT_F32, ISD::SETNE);
00196       setCmpLibcallCC(RTLIB::OLE_F32, ISD::SETNE);
00197       setCmpLibcallCC(RTLIB::OGE_F32, ISD::SETNE);
00198       setCmpLibcallCC(RTLIB::OGT_F32, ISD::SETNE);
00199       setCmpLibcallCC(RTLIB::UO_F32,  ISD::SETNE);
00200       setCmpLibcallCC(RTLIB::O_F32,   ISD::SETEQ);
00201 
00202       // Double-precision comparisons.
00203       setLibcallName(RTLIB::OEQ_F64, "__eqdf2vfp");
00204       setLibcallName(RTLIB::UNE_F64, "__nedf2vfp");
00205       setLibcallName(RTLIB::OLT_F64, "__ltdf2vfp");
00206       setLibcallName(RTLIB::OLE_F64, "__ledf2vfp");
00207       setLibcallName(RTLIB::OGE_F64, "__gedf2vfp");
00208       setLibcallName(RTLIB::OGT_F64, "__gtdf2vfp");
00209       setLibcallName(RTLIB::UO_F64,  "__unorddf2vfp");
00210       setLibcallName(RTLIB::O_F64,   "__unorddf2vfp");
00211 
00212       setCmpLibcallCC(RTLIB::OEQ_F64, ISD::SETNE);
00213       setCmpLibcallCC(RTLIB::UNE_F64, ISD::SETNE);
00214       setCmpLibcallCC(RTLIB::OLT_F64, ISD::SETNE);
00215       setCmpLibcallCC(RTLIB::OLE_F64, ISD::SETNE);
00216       setCmpLibcallCC(RTLIB::OGE_F64, ISD::SETNE);
00217       setCmpLibcallCC(RTLIB::OGT_F64, ISD::SETNE);
00218       setCmpLibcallCC(RTLIB::UO_F64,  ISD::SETNE);
00219       setCmpLibcallCC(RTLIB::O_F64,   ISD::SETEQ);
00220 
00221       // Floating-point to integer conversions.
00222       // i64 conversions are done via library routines even when generating VFP
00223       // instructions, so use the same ones.
00224       setLibcallName(RTLIB::FPTOSINT_F64_I32, "__fixdfsivfp");
00225       setLibcallName(RTLIB::FPTOUINT_F64_I32, "__fixunsdfsivfp");
00226       setLibcallName(RTLIB::FPTOSINT_F32_I32, "__fixsfsivfp");
00227       setLibcallName(RTLIB::FPTOUINT_F32_I32, "__fixunssfsivfp");
00228 
00229       // Conversions between floating types.
00230       setLibcallName(RTLIB::FPROUND_F64_F32, "__truncdfsf2vfp");
00231       setLibcallName(RTLIB::FPEXT_F32_F64,   "__extendsfdf2vfp");
00232 
00233       // Integer to floating-point conversions.
00234       // i64 conversions are done via library routines even when generating VFP
00235       // instructions, so use the same ones.
00236       // FIXME: There appears to be some naming inconsistency in ARM libgcc:
00237       // e.g., __floatunsidf vs. __floatunssidfvfp.
00238       setLibcallName(RTLIB::SINTTOFP_I32_F64, "__floatsidfvfp");
00239       setLibcallName(RTLIB::UINTTOFP_I32_F64, "__floatunssidfvfp");
00240       setLibcallName(RTLIB::SINTTOFP_I32_F32, "__floatsisfvfp");
00241       setLibcallName(RTLIB::UINTTOFP_I32_F32, "__floatunssisfvfp");
00242     }
00243   }
00244 
00245   // These libcalls are not available in 32-bit.
00246   setLibcallName(RTLIB::SHL_I128, nullptr);
00247   setLibcallName(RTLIB::SRL_I128, nullptr);
00248   setLibcallName(RTLIB::SRA_I128, nullptr);
00249 
00250   if (Subtarget->isAAPCS_ABI() && !Subtarget->isTargetMachO() &&
00251       !Subtarget->isTargetWindows()) {
00252     static const struct {
00253       const RTLIB::Libcall Op;
00254       const char * const Name;
00255       const CallingConv::ID CC;
00256       const ISD::CondCode Cond;
00257     } LibraryCalls[] = {
00258       // Double-precision floating-point arithmetic helper functions
00259       // RTABI chapter 4.1.2, Table 2
00260       { RTLIB::ADD_F64, "__aeabi_dadd", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
00261       { RTLIB::DIV_F64, "__aeabi_ddiv", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
00262       { RTLIB::MUL_F64, "__aeabi_dmul", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
00263       { RTLIB::SUB_F64, "__aeabi_dsub", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
00264 
00265       // Double-precision floating-point comparison helper functions
00266       // RTABI chapter 4.1.2, Table 3
00267       { RTLIB::OEQ_F64, "__aeabi_dcmpeq", CallingConv::ARM_AAPCS, ISD::SETNE },
00268       { RTLIB::UNE_F64, "__aeabi_dcmpeq", CallingConv::ARM_AAPCS, ISD::SETEQ },
00269       { RTLIB::OLT_F64, "__aeabi_dcmplt", CallingConv::ARM_AAPCS, ISD::SETNE },
00270       { RTLIB::OLE_F64, "__aeabi_dcmple", CallingConv::ARM_AAPCS, ISD::SETNE },
00271       { RTLIB::OGE_F64, "__aeabi_dcmpge", CallingConv::ARM_AAPCS, ISD::SETNE },
00272       { RTLIB::OGT_F64, "__aeabi_dcmpgt", CallingConv::ARM_AAPCS, ISD::SETNE },
00273       { RTLIB::UO_F64,  "__aeabi_dcmpun", CallingConv::ARM_AAPCS, ISD::SETNE },
00274       { RTLIB::O_F64,   "__aeabi_dcmpun", CallingConv::ARM_AAPCS, ISD::SETEQ },
00275 
00276       // Single-precision floating-point arithmetic helper functions
00277       // RTABI chapter 4.1.2, Table 4
00278       { RTLIB::ADD_F32, "__aeabi_fadd", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
00279       { RTLIB::DIV_F32, "__aeabi_fdiv", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
00280       { RTLIB::MUL_F32, "__aeabi_fmul", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
00281       { RTLIB::SUB_F32, "__aeabi_fsub", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
00282 
00283       // Single-precision floating-point comparison helper functions
00284       // RTABI chapter 4.1.2, Table 5
00285       { RTLIB::OEQ_F32, "__aeabi_fcmpeq", CallingConv::ARM_AAPCS, ISD::SETNE },
00286       { RTLIB::UNE_F32, "__aeabi_fcmpeq", CallingConv::ARM_AAPCS, ISD::SETEQ },
00287       { RTLIB::OLT_F32, "__aeabi_fcmplt", CallingConv::ARM_AAPCS, ISD::SETNE },
00288       { RTLIB::OLE_F32, "__aeabi_fcmple", CallingConv::ARM_AAPCS, ISD::SETNE },
00289       { RTLIB::OGE_F32, "__aeabi_fcmpge", CallingConv::ARM_AAPCS, ISD::SETNE },
00290       { RTLIB::OGT_F32, "__aeabi_fcmpgt", CallingConv::ARM_AAPCS, ISD::SETNE },
00291       { RTLIB::UO_F32,  "__aeabi_fcmpun", CallingConv::ARM_AAPCS, ISD::SETNE },
00292       { RTLIB::O_F32,   "__aeabi_fcmpun", CallingConv::ARM_AAPCS, ISD::SETEQ },
00293 
00294       // Floating-point to integer conversions.
00295       // RTABI chapter 4.1.2, Table 6
00296       { RTLIB::FPTOSINT_F64_I32, "__aeabi_d2iz",  CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
00297       { RTLIB::FPTOUINT_F64_I32, "__aeabi_d2uiz", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
00298       { RTLIB::FPTOSINT_F64_I64, "__aeabi_d2lz",  CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
00299       { RTLIB::FPTOUINT_F64_I64, "__aeabi_d2ulz", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
00300       { RTLIB::FPTOSINT_F32_I32, "__aeabi_f2iz",  CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
00301       { RTLIB::FPTOUINT_F32_I32, "__aeabi_f2uiz", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
00302       { RTLIB::FPTOSINT_F32_I64, "__aeabi_f2lz",  CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
00303       { RTLIB::FPTOUINT_F32_I64, "__aeabi_f2ulz", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
00304 
00305       // Conversions between floating types.
00306       // RTABI chapter 4.1.2, Table 7
00307       { RTLIB::FPROUND_F64_F32, "__aeabi_d2f", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
00308       { RTLIB::FPROUND_F64_F16, "__aeabi_d2h", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
00309       { RTLIB::FPEXT_F32_F64,   "__aeabi_f2d", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
00310 
00311       // Integer to floating-point conversions.
00312       // RTABI chapter 4.1.2, Table 8
00313       { RTLIB::SINTTOFP_I32_F64, "__aeabi_i2d",  CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
00314       { RTLIB::UINTTOFP_I32_F64, "__aeabi_ui2d", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
00315       { RTLIB::SINTTOFP_I64_F64, "__aeabi_l2d",  CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
00316       { RTLIB::UINTTOFP_I64_F64, "__aeabi_ul2d", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
00317       { RTLIB::SINTTOFP_I32_F32, "__aeabi_i2f",  CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
00318       { RTLIB::UINTTOFP_I32_F32, "__aeabi_ui2f", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
00319       { RTLIB::SINTTOFP_I64_F32, "__aeabi_l2f",  CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
00320       { RTLIB::UINTTOFP_I64_F32, "__aeabi_ul2f", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
00321 
00322       // Long long helper functions
00323       // RTABI chapter 4.2, Table 9
00324       { RTLIB::MUL_I64, "__aeabi_lmul", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
00325       { RTLIB::SHL_I64, "__aeabi_llsl", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
00326       { RTLIB::SRL_I64, "__aeabi_llsr", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
00327       { RTLIB::SRA_I64, "__aeabi_lasr", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
00328 
00329       // Integer division functions
00330       // RTABI chapter 4.3.1
00331       { RTLIB::SDIV_I8,  "__aeabi_idiv",     CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
00332       { RTLIB::SDIV_I16, "__aeabi_idiv",     CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
00333       { RTLIB::SDIV_I32, "__aeabi_idiv",     CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
00334       { RTLIB::SDIV_I64, "__aeabi_ldivmod",  CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
00335       { RTLIB::UDIV_I8,  "__aeabi_uidiv",    CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
00336       { RTLIB::UDIV_I16, "__aeabi_uidiv",    CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
00337       { RTLIB::UDIV_I32, "__aeabi_uidiv",    CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
00338       { RTLIB::UDIV_I64, "__aeabi_uldivmod", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
00339 
00340       // Memory operations
00341       // RTABI chapter 4.3.4
00342       { RTLIB::MEMCPY,  "__aeabi_memcpy",  CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
00343       { RTLIB::MEMMOVE, "__aeabi_memmove", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
00344       { RTLIB::MEMSET,  "__aeabi_memset",  CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
00345     };
00346 
00347     for (const auto &LC : LibraryCalls) {
00348       setLibcallName(LC.Op, LC.Name);
00349       setLibcallCallingConv(LC.Op, LC.CC);
00350       if (LC.Cond != ISD::SETCC_INVALID)
00351         setCmpLibcallCC(LC.Op, LC.Cond);
00352     }
00353   }
00354 
00355   if (Subtarget->isTargetWindows()) {
00356     static const struct {
00357       const RTLIB::Libcall Op;
00358       const char * const Name;
00359       const CallingConv::ID CC;
00360     } LibraryCalls[] = {
00361       { RTLIB::FPTOSINT_F32_I64, "__stoi64", CallingConv::ARM_AAPCS_VFP },
00362       { RTLIB::FPTOSINT_F64_I64, "__dtoi64", CallingConv::ARM_AAPCS_VFP },
00363       { RTLIB::FPTOUINT_F32_I64, "__stou64", CallingConv::ARM_AAPCS_VFP },
00364       { RTLIB::FPTOUINT_F64_I64, "__dtou64", CallingConv::ARM_AAPCS_VFP },
00365       { RTLIB::SINTTOFP_I64_F32, "__i64tos", CallingConv::ARM_AAPCS_VFP },
00366       { RTLIB::SINTTOFP_I64_F64, "__i64tod", CallingConv::ARM_AAPCS_VFP },
00367       { RTLIB::UINTTOFP_I64_F32, "__u64tos", CallingConv::ARM_AAPCS_VFP },
00368       { RTLIB::UINTTOFP_I64_F64, "__u64tod", CallingConv::ARM_AAPCS_VFP },
00369     };
00370 
00371     for (const auto &LC : LibraryCalls) {
00372       setLibcallName(LC.Op, LC.Name);
00373       setLibcallCallingConv(LC.Op, LC.CC);
00374     }
00375   }
00376 
00377   // Use divmod compiler-rt calls for iOS 5.0 and later.
00378   if (Subtarget->getTargetTriple().isiOS() &&
00379       !Subtarget->getTargetTriple().isOSVersionLT(5, 0)) {
00380     setLibcallName(RTLIB::SDIVREM_I32, "__divmodsi4");
00381     setLibcallName(RTLIB::UDIVREM_I32, "__udivmodsi4");
00382   }
00383 
00384   // The half <-> float conversion functions are always soft-float, but are
00385   // needed for some targets which use a hard-float calling convention by
00386   // default.
00387   if (Subtarget->isAAPCS_ABI()) {
00388     setLibcallCallingConv(RTLIB::FPROUND_F32_F16, CallingConv::ARM_AAPCS);
00389     setLibcallCallingConv(RTLIB::FPROUND_F64_F16, CallingConv::ARM_AAPCS);
00390     setLibcallCallingConv(RTLIB::FPEXT_F16_F32, CallingConv::ARM_AAPCS);
00391   } else {
00392     setLibcallCallingConv(RTLIB::FPROUND_F32_F16, CallingConv::ARM_APCS);
00393     setLibcallCallingConv(RTLIB::FPROUND_F64_F16, CallingConv::ARM_APCS);
00394     setLibcallCallingConv(RTLIB::FPEXT_F16_F32, CallingConv::ARM_APCS);
00395   }
00396 
00397   if (Subtarget->isThumb1Only())
00398     addRegisterClass(MVT::i32, &ARM::tGPRRegClass);
00399   else
00400     addRegisterClass(MVT::i32, &ARM::GPRRegClass);
00401   if (!TM.Options.UseSoftFloat && Subtarget->hasVFP2() &&
00402       !Subtarget->isThumb1Only()) {
00403     addRegisterClass(MVT::f32, &ARM::SPRRegClass);
00404     addRegisterClass(MVT::f64, &ARM::DPRRegClass);
00405   }
00406 
00407   for (unsigned VT = (unsigned)MVT::FIRST_VECTOR_VALUETYPE;
00408        VT <= (unsigned)MVT::LAST_VECTOR_VALUETYPE; ++VT) {
00409     for (unsigned InnerVT = (unsigned)MVT::FIRST_VECTOR_VALUETYPE;
00410          InnerVT <= (unsigned)MVT::LAST_VECTOR_VALUETYPE; ++InnerVT)
00411       setTruncStoreAction((MVT::SimpleValueType)VT,
00412                           (MVT::SimpleValueType)InnerVT, Expand);
00413     setLoadExtAction(ISD::SEXTLOAD, (MVT::SimpleValueType)VT, Expand);
00414     setLoadExtAction(ISD::ZEXTLOAD, (MVT::SimpleValueType)VT, Expand);
00415     setLoadExtAction(ISD::EXTLOAD, (MVT::SimpleValueType)VT, Expand);
00416 
00417     setOperationAction(ISD::MULHS, (MVT::SimpleValueType)VT, Expand);
00418     setOperationAction(ISD::SMUL_LOHI, (MVT::SimpleValueType)VT, Expand);
00419     setOperationAction(ISD::MULHU, (MVT::SimpleValueType)VT, Expand);
00420     setOperationAction(ISD::UMUL_LOHI, (MVT::SimpleValueType)VT, Expand);
00421 
00422     setOperationAction(ISD::BSWAP, (MVT::SimpleValueType)VT, Expand);
00423   }
00424 
00425   setOperationAction(ISD::ConstantFP, MVT::f32, Custom);
00426   setOperationAction(ISD::ConstantFP, MVT::f64, Custom);
00427 
00428   if (Subtarget->hasNEON()) {
00429     addDRTypeForNEON(MVT::v2f32);
00430     addDRTypeForNEON(MVT::v8i8);
00431     addDRTypeForNEON(MVT::v4i16);
00432     addDRTypeForNEON(MVT::v2i32);
00433     addDRTypeForNEON(MVT::v1i64);
00434 
00435     addQRTypeForNEON(MVT::v4f32);
00436     addQRTypeForNEON(MVT::v2f64);
00437     addQRTypeForNEON(MVT::v16i8);
00438     addQRTypeForNEON(MVT::v8i16);
00439     addQRTypeForNEON(MVT::v4i32);
00440     addQRTypeForNEON(MVT::v2i64);
00441 
00442     // v2f64 is legal so that QR subregs can be extracted as f64 elements, but
00443     // neither Neon nor VFP support any arithmetic operations on it.
00444     // The same with v4f32. But keep in mind that vadd, vsub, vmul are natively
00445     // supported for v4f32.
00446     setOperationAction(ISD::FADD, MVT::v2f64, Expand);
00447     setOperationAction(ISD::FSUB, MVT::v2f64, Expand);
00448     setOperationAction(ISD::FMUL, MVT::v2f64, Expand);
00449     // FIXME: Code duplication: FDIV and FREM are expanded always, see
00450     // ARMTargetLowering::addTypeForNEON method for details.
00451     setOperationAction(ISD::FDIV, MVT::v2f64, Expand);
00452     setOperationAction(ISD::FREM, MVT::v2f64, Expand);
00453     // FIXME: Create unittest.
00454     // In another words, find a way when "copysign" appears in DAG with vector
00455     // operands.
00456     setOperationAction(ISD::FCOPYSIGN, MVT::v2f64, Expand);
00457     // FIXME: Code duplication: SETCC has custom operation action, see
00458     // ARMTargetLowering::addTypeForNEON method for details.
00459     setOperationAction(ISD::SETCC, MVT::v2f64, Expand);
00460     // FIXME: Create unittest for FNEG and for FABS.
00461     setOperationAction(ISD::FNEG, MVT::v2f64, Expand);
00462     setOperationAction(ISD::FABS, MVT::v2f64, Expand);
00463     setOperationAction(ISD::FSQRT, MVT::v2f64, Expand);
00464     setOperationAction(ISD::FSIN, MVT::v2f64, Expand);
00465     setOperationAction(ISD::FCOS, MVT::v2f64, Expand);
00466     setOperationAction(ISD::FPOWI, MVT::v2f64, Expand);
00467     setOperationAction(ISD::FPOW, MVT::v2f64, Expand);
00468     setOperationAction(ISD::FLOG, MVT::v2f64, Expand);
00469     setOperationAction(ISD::FLOG2, MVT::v2f64, Expand);
00470     setOperationAction(ISD::FLOG10, MVT::v2f64, Expand);
00471     setOperationAction(ISD::FEXP, MVT::v2f64, Expand);
00472     setOperationAction(ISD::FEXP2, MVT::v2f64, Expand);
00473     // FIXME: Create unittest for FCEIL, FTRUNC, FRINT, FNEARBYINT, FFLOOR.
00474     setOperationAction(ISD::FCEIL, MVT::v2f64, Expand);
00475     setOperationAction(ISD::FTRUNC, MVT::v2f64, Expand);
00476     setOperationAction(ISD::FRINT, MVT::v2f64, Expand);
00477     setOperationAction(ISD::FNEARBYINT, MVT::v2f64, Expand);
00478     setOperationAction(ISD::FFLOOR, MVT::v2f64, Expand);
00479     setOperationAction(ISD::FMA, MVT::v2f64, Expand);
00480 
00481     setOperationAction(ISD::FSQRT, MVT::v4f32, Expand);
00482     setOperationAction(ISD::FSIN, MVT::v4f32, Expand);
00483     setOperationAction(ISD::FCOS, MVT::v4f32, Expand);
00484     setOperationAction(ISD::FPOWI, MVT::v4f32, Expand);
00485     setOperationAction(ISD::FPOW, MVT::v4f32, Expand);
00486     setOperationAction(ISD::FLOG, MVT::v4f32, Expand);
00487     setOperationAction(ISD::FLOG2, MVT::v4f32, Expand);
00488     setOperationAction(ISD::FLOG10, MVT::v4f32, Expand);
00489     setOperationAction(ISD::FEXP, MVT::v4f32, Expand);
00490     setOperationAction(ISD::FEXP2, MVT::v4f32, Expand);
00491     setOperationAction(ISD::FCEIL, MVT::v4f32, Expand);
00492     setOperationAction(ISD::FTRUNC, MVT::v4f32, Expand);
00493     setOperationAction(ISD::FRINT, MVT::v4f32, Expand);
00494     setOperationAction(ISD::FNEARBYINT, MVT::v4f32, Expand);
00495     setOperationAction(ISD::FFLOOR, MVT::v4f32, Expand);
00496 
00497     // Mark v2f32 intrinsics.
00498     setOperationAction(ISD::FSQRT, MVT::v2f32, Expand);
00499     setOperationAction(ISD::FSIN, MVT::v2f32, Expand);
00500     setOperationAction(ISD::FCOS, MVT::v2f32, Expand);
00501     setOperationAction(ISD::FPOWI, MVT::v2f32, Expand);
00502     setOperationAction(ISD::FPOW, MVT::v2f32, Expand);
00503     setOperationAction(ISD::FLOG, MVT::v2f32, Expand);
00504     setOperationAction(ISD::FLOG2, MVT::v2f32, Expand);
00505     setOperationAction(ISD::FLOG10, MVT::v2f32, Expand);
00506     setOperationAction(ISD::FEXP, MVT::v2f32, Expand);
00507     setOperationAction(ISD::FEXP2, MVT::v2f32, Expand);
00508     setOperationAction(ISD::FCEIL, MVT::v2f32, Expand);
00509     setOperationAction(ISD::FTRUNC, MVT::v2f32, Expand);
00510     setOperationAction(ISD::FRINT, MVT::v2f32, Expand);
00511     setOperationAction(ISD::FNEARBYINT, MVT::v2f32, Expand);
00512     setOperationAction(ISD::FFLOOR, MVT::v2f32, Expand);
00513 
00514     // Neon does not support some operations on v1i64 and v2i64 types.
00515     setOperationAction(ISD::MUL, MVT::v1i64, Expand);
00516     // Custom handling for some quad-vector types to detect VMULL.
00517     setOperationAction(ISD::MUL, MVT::v8i16, Custom);
00518     setOperationAction(ISD::MUL, MVT::v4i32, Custom);
00519     setOperationAction(ISD::MUL, MVT::v2i64, Custom);
00520     // Custom handling for some vector types to avoid expensive expansions
00521     setOperationAction(ISD::SDIV, MVT::v4i16, Custom);
00522     setOperationAction(ISD::SDIV, MVT::v8i8, Custom);
00523     setOperationAction(ISD::UDIV, MVT::v4i16, Custom);
00524     setOperationAction(ISD::UDIV, MVT::v8i8, Custom);
00525     setOperationAction(ISD::SETCC, MVT::v1i64, Expand);
00526     setOperationAction(ISD::SETCC, MVT::v2i64, Expand);
00527     // Neon does not have single instruction SINT_TO_FP and UINT_TO_FP with
00528     // a destination type that is wider than the source, and nor does
00529     // it have a FP_TO_[SU]INT instruction with a narrower destination than
00530     // source.
00531     setOperationAction(ISD::SINT_TO_FP, MVT::v4i16, Custom);
00532     setOperationAction(ISD::UINT_TO_FP, MVT::v4i16, Custom);
00533     setOperationAction(ISD::FP_TO_UINT, MVT::v4i16, Custom);
00534     setOperationAction(ISD::FP_TO_SINT, MVT::v4i16, Custom);
00535 
00536     setOperationAction(ISD::FP_ROUND,   MVT::v2f32, Expand);
00537     setOperationAction(ISD::FP_EXTEND,  MVT::v2f64, Expand);
00538 
00539     // NEON does not have single instruction CTPOP for vectors with element
00540     // types wider than 8-bits.  However, custom lowering can leverage the
00541     // v8i8/v16i8 vcnt instruction.
00542     setOperationAction(ISD::CTPOP,      MVT::v2i32, Custom);
00543     setOperationAction(ISD::CTPOP,      MVT::v4i32, Custom);
00544     setOperationAction(ISD::CTPOP,      MVT::v4i16, Custom);
00545     setOperationAction(ISD::CTPOP,      MVT::v8i16, Custom);
00546 
00547     // NEON only has FMA instructions as of VFP4.
00548     if (!Subtarget->hasVFP4()) {
00549       setOperationAction(ISD::FMA, MVT::v2f32, Expand);
00550       setOperationAction(ISD::FMA, MVT::v4f32, Expand);
00551     }
00552 
00553     setTargetDAGCombine(ISD::INTRINSIC_VOID);
00554     setTargetDAGCombine(ISD::INTRINSIC_W_CHAIN);
00555     setTargetDAGCombine(ISD::INTRINSIC_WO_CHAIN);
00556     setTargetDAGCombine(ISD::SHL);
00557     setTargetDAGCombine(ISD::SRL);
00558     setTargetDAGCombine(ISD::SRA);
00559     setTargetDAGCombine(ISD::SIGN_EXTEND);
00560     setTargetDAGCombine(ISD::ZERO_EXTEND);
00561     setTargetDAGCombine(ISD::ANY_EXTEND);
00562     setTargetDAGCombine(ISD::SELECT_CC);
00563     setTargetDAGCombine(ISD::BUILD_VECTOR);
00564     setTargetDAGCombine(ISD::VECTOR_SHUFFLE);
00565     setTargetDAGCombine(ISD::INSERT_VECTOR_ELT);
00566     setTargetDAGCombine(ISD::STORE);
00567     setTargetDAGCombine(ISD::FP_TO_SINT);
00568     setTargetDAGCombine(ISD::FP_TO_UINT);
00569     setTargetDAGCombine(ISD::FDIV);
00570     setTargetDAGCombine(ISD::LOAD);
00571 
00572     // It is legal to extload from v4i8 to v4i16 or v4i32.
00573     MVT Tys[6] = {MVT::v8i8, MVT::v4i8, MVT::v2i8,
00574                   MVT::v4i16, MVT::v2i16,
00575                   MVT::v2i32};
00576     for (unsigned i = 0; i < 6; ++i) {
00577       setLoadExtAction(ISD::EXTLOAD, Tys[i], Legal);
00578       setLoadExtAction(ISD::ZEXTLOAD, Tys[i], Legal);
00579       setLoadExtAction(ISD::SEXTLOAD, Tys[i], Legal);
00580     }
00581   }
00582 
00583   // ARM and Thumb2 support UMLAL/SMLAL.
00584   if (!Subtarget->isThumb1Only())
00585     setTargetDAGCombine(ISD::ADDC);
00586 
00587   if (Subtarget->isFPOnlySP()) {
00588     // When targetting a floating-point unit with only single-precision
00589     // operations, f64 is legal for the few double-precision instructions which
00590     // are present However, no double-precision operations other than moves,
00591     // loads and stores are provided by the hardware.
00592     setOperationAction(ISD::FADD,       MVT::f64, Expand);
00593     setOperationAction(ISD::FSUB,       MVT::f64, Expand);
00594     setOperationAction(ISD::FMUL,       MVT::f64, Expand);
00595     setOperationAction(ISD::FMA,        MVT::f64, Expand);
00596     setOperationAction(ISD::FDIV,       MVT::f64, Expand);
00597     setOperationAction(ISD::FREM,       MVT::f64, Expand);
00598     setOperationAction(ISD::FCOPYSIGN,  MVT::f64, Expand);
00599     setOperationAction(ISD::FGETSIGN,   MVT::f64, Expand);
00600     setOperationAction(ISD::FNEG,       MVT::f64, Expand);
00601     setOperationAction(ISD::FABS,       MVT::f64, Expand);
00602     setOperationAction(ISD::FSQRT,      MVT::f64, Expand);
00603     setOperationAction(ISD::FSIN,       MVT::f64, Expand);
00604     setOperationAction(ISD::FCOS,       MVT::f64, Expand);
00605     setOperationAction(ISD::FPOWI,      MVT::f64, Expand);
00606     setOperationAction(ISD::FPOW,       MVT::f64, Expand);
00607     setOperationAction(ISD::FLOG,       MVT::f64, Expand);
00608     setOperationAction(ISD::FLOG2,      MVT::f64, Expand);
00609     setOperationAction(ISD::FLOG10,     MVT::f64, Expand);
00610     setOperationAction(ISD::FEXP,       MVT::f64, Expand);
00611     setOperationAction(ISD::FEXP2,      MVT::f64, Expand);
00612     setOperationAction(ISD::FCEIL,      MVT::f64, Expand);
00613     setOperationAction(ISD::FTRUNC,     MVT::f64, Expand);
00614     setOperationAction(ISD::FRINT,      MVT::f64, Expand);
00615     setOperationAction(ISD::FNEARBYINT, MVT::f64, Expand);
00616     setOperationAction(ISD::FFLOOR,     MVT::f64, Expand);
00617     setOperationAction(ISD::FP_ROUND,   MVT::f32, Custom);
00618     setOperationAction(ISD::FP_EXTEND,  MVT::f64, Custom);
00619   }
00620 
00621   computeRegisterProperties();
00622 
00623   // ARM does not have floating-point extending loads.
00624   setLoadExtAction(ISD::EXTLOAD, MVT::f32, Expand);
00625   setLoadExtAction(ISD::EXTLOAD, MVT::f16, Expand);
00626 
00627   // ... or truncating stores
00628   setTruncStoreAction(MVT::f64, MVT::f32, Expand);
00629   setTruncStoreAction(MVT::f32, MVT::f16, Expand);
00630   setTruncStoreAction(MVT::f64, MVT::f16, Expand);
00631 
00632   // ARM does not have i1 sign extending load.
00633   setLoadExtAction(ISD::SEXTLOAD, MVT::i1, Promote);
00634 
00635   // ARM supports all 4 flavors of integer indexed load / store.
00636   if (!Subtarget->isThumb1Only()) {
00637     for (unsigned im = (unsigned)ISD::PRE_INC;
00638          im != (unsigned)ISD::LAST_INDEXED_MODE; ++im) {
00639       setIndexedLoadAction(im,  MVT::i1,  Legal);
00640       setIndexedLoadAction(im,  MVT::i8,  Legal);
00641       setIndexedLoadAction(im,  MVT::i16, Legal);
00642       setIndexedLoadAction(im,  MVT::i32, Legal);
00643       setIndexedStoreAction(im, MVT::i1,  Legal);
00644       setIndexedStoreAction(im, MVT::i8,  Legal);
00645       setIndexedStoreAction(im, MVT::i16, Legal);
00646       setIndexedStoreAction(im, MVT::i32, Legal);
00647     }
00648   }
00649 
00650   setOperationAction(ISD::SADDO, MVT::i32, Custom);
00651   setOperationAction(ISD::UADDO, MVT::i32, Custom);
00652   setOperationAction(ISD::SSUBO, MVT::i32, Custom);
00653   setOperationAction(ISD::USUBO, MVT::i32, Custom);
00654 
00655   // i64 operation support.
00656   setOperationAction(ISD::MUL,     MVT::i64, Expand);
00657   setOperationAction(ISD::MULHU,   MVT::i32, Expand);
00658   if (Subtarget->isThumb1Only()) {
00659     setOperationAction(ISD::UMUL_LOHI, MVT::i32, Expand);
00660     setOperationAction(ISD::SMUL_LOHI, MVT::i32, Expand);
00661   }
00662   if (Subtarget->isThumb1Only() || !Subtarget->hasV6Ops()
00663       || (Subtarget->isThumb2() && !Subtarget->hasThumb2DSP()))
00664     setOperationAction(ISD::MULHS, MVT::i32, Expand);
00665 
00666   setOperationAction(ISD::SHL_PARTS, MVT::i32, Custom);
00667   setOperationAction(ISD::SRA_PARTS, MVT::i32, Custom);
00668   setOperationAction(ISD::SRL_PARTS, MVT::i32, Custom);
00669   setOperationAction(ISD::SRL,       MVT::i64, Custom);
00670   setOperationAction(ISD::SRA,       MVT::i64, Custom);
00671 
00672   if (!Subtarget->isThumb1Only()) {
00673     // FIXME: We should do this for Thumb1 as well.
00674     setOperationAction(ISD::ADDC,    MVT::i32, Custom);
00675     setOperationAction(ISD::ADDE,    MVT::i32, Custom);
00676     setOperationAction(ISD::SUBC,    MVT::i32, Custom);
00677     setOperationAction(ISD::SUBE,    MVT::i32, Custom);
00678   }
00679 
00680   // ARM does not have ROTL.
00681   setOperationAction(ISD::ROTL,  MVT::i32, Expand);
00682   setOperationAction(ISD::CTTZ,  MVT::i32, Custom);
00683   setOperationAction(ISD::CTPOP, MVT::i32, Expand);
00684   if (!Subtarget->hasV5TOps() || Subtarget->isThumb1Only())
00685     setOperationAction(ISD::CTLZ, MVT::i32, Expand);
00686 
00687   // These just redirect to CTTZ and CTLZ on ARM.
00688   setOperationAction(ISD::CTTZ_ZERO_UNDEF  , MVT::i32  , Expand);
00689   setOperationAction(ISD::CTLZ_ZERO_UNDEF  , MVT::i32  , Expand);
00690 
00691   setOperationAction(ISD::READCYCLECOUNTER, MVT::i64, Custom);
00692 
00693   // Only ARMv6 has BSWAP.
00694   if (!Subtarget->hasV6Ops())
00695     setOperationAction(ISD::BSWAP, MVT::i32, Expand);
00696 
00697   if (!(Subtarget->hasDivide() && Subtarget->isThumb2()) &&
00698       !(Subtarget->hasDivideInARMMode() && !Subtarget->isThumb())) {
00699     // These are expanded into libcalls if the cpu doesn't have HW divider.
00700     setOperationAction(ISD::SDIV,  MVT::i32, Expand);
00701     setOperationAction(ISD::UDIV,  MVT::i32, Expand);
00702   }
00703 
00704   // FIXME: Also set divmod for SREM on EABI
00705   setOperationAction(ISD::SREM,  MVT::i32, Expand);
00706   setOperationAction(ISD::UREM,  MVT::i32, Expand);
00707   // Register based DivRem for AEABI (RTABI 4.2)
00708   if (Subtarget->isTargetAEABI()) {
00709     setLibcallName(RTLIB::SDIVREM_I8,  "__aeabi_idivmod");
00710     setLibcallName(RTLIB::SDIVREM_I16, "__aeabi_idivmod");
00711     setLibcallName(RTLIB::SDIVREM_I32, "__aeabi_idivmod");
00712     setLibcallName(RTLIB::SDIVREM_I64, "__aeabi_ldivmod");
00713     setLibcallName(RTLIB::UDIVREM_I8,  "__aeabi_uidivmod");
00714     setLibcallName(RTLIB::UDIVREM_I16, "__aeabi_uidivmod");
00715     setLibcallName(RTLIB::UDIVREM_I32, "__aeabi_uidivmod");
00716     setLibcallName(RTLIB::UDIVREM_I64, "__aeabi_uldivmod");
00717 
00718     setLibcallCallingConv(RTLIB::SDIVREM_I8, CallingConv::ARM_AAPCS);
00719     setLibcallCallingConv(RTLIB::SDIVREM_I16, CallingConv::ARM_AAPCS);
00720     setLibcallCallingConv(RTLIB::SDIVREM_I32, CallingConv::ARM_AAPCS);
00721     setLibcallCallingConv(RTLIB::SDIVREM_I64, CallingConv::ARM_AAPCS);
00722     setLibcallCallingConv(RTLIB::UDIVREM_I8, CallingConv::ARM_AAPCS);
00723     setLibcallCallingConv(RTLIB::UDIVREM_I16, CallingConv::ARM_AAPCS);
00724     setLibcallCallingConv(RTLIB::UDIVREM_I32, CallingConv::ARM_AAPCS);
00725     setLibcallCallingConv(RTLIB::UDIVREM_I64, CallingConv::ARM_AAPCS);
00726 
00727     setOperationAction(ISD::SDIVREM, MVT::i32, Custom);
00728     setOperationAction(ISD::UDIVREM, MVT::i32, Custom);
00729   } else {
00730     setOperationAction(ISD::SDIVREM, MVT::i32, Expand);
00731     setOperationAction(ISD::UDIVREM, MVT::i32, Expand);
00732   }
00733 
00734   setOperationAction(ISD::GlobalAddress, MVT::i32,   Custom);
00735   setOperationAction(ISD::ConstantPool,  MVT::i32,   Custom);
00736   setOperationAction(ISD::GLOBAL_OFFSET_TABLE, MVT::i32, Custom);
00737   setOperationAction(ISD::GlobalTLSAddress, MVT::i32, Custom);
00738   setOperationAction(ISD::BlockAddress, MVT::i32, Custom);
00739 
00740   setOperationAction(ISD::TRAP, MVT::Other, Legal);
00741 
00742   // Use the default implementation.
00743   setOperationAction(ISD::VASTART,            MVT::Other, Custom);
00744   setOperationAction(ISD::VAARG,              MVT::Other, Expand);
00745   setOperationAction(ISD::VACOPY,             MVT::Other, Expand);
00746   setOperationAction(ISD::VAEND,              MVT::Other, Expand);
00747   setOperationAction(ISD::STACKSAVE,          MVT::Other, Expand);
00748   setOperationAction(ISD::STACKRESTORE,       MVT::Other, Expand);
00749 
00750   if (!Subtarget->isTargetMachO()) {
00751     // Non-MachO platforms may return values in these registers via the
00752     // personality function.
00753     setExceptionPointerRegister(ARM::R0);
00754     setExceptionSelectorRegister(ARM::R1);
00755   }
00756 
00757   if (Subtarget->getTargetTriple().isWindowsItaniumEnvironment())
00758     setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i32, Custom);
00759   else
00760     setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i32, Expand);
00761 
00762   // ARMv6 Thumb1 (except for CPUs that support dmb / dsb) and earlier use
00763   // the default expansion. If we are targeting a single threaded system,
00764   // then set them all for expand so we can lower them later into their
00765   // non-atomic form.
00766   if (TM.Options.ThreadModel == ThreadModel::Single)
00767     setOperationAction(ISD::ATOMIC_FENCE,   MVT::Other, Expand);
00768   else if (Subtarget->hasAnyDataBarrier() && !Subtarget->isThumb1Only()) {
00769     // ATOMIC_FENCE needs custom lowering; the others should have been expanded
00770     // to ldrex/strex loops already.
00771     setOperationAction(ISD::ATOMIC_FENCE,     MVT::Other, Custom);
00772 
00773     // On v8, we have particularly efficient implementations of atomic fences
00774     // if they can be combined with nearby atomic loads and stores.
00775     if (!Subtarget->hasV8Ops()) {
00776       // Automatically insert fences (dmb ish) around ATOMIC_SWAP etc.
00777       setInsertFencesForAtomic(true);
00778     }
00779   } else {
00780     // If there's anything we can use as a barrier, go through custom lowering
00781     // for ATOMIC_FENCE.
00782     setOperationAction(ISD::ATOMIC_FENCE,   MVT::Other,
00783                        Subtarget->hasAnyDataBarrier() ? Custom : Expand);
00784 
00785     // Set them all for expansion, which will force libcalls.
00786     setOperationAction(ISD::ATOMIC_CMP_SWAP,  MVT::i32, Expand);
00787     setOperationAction(ISD::ATOMIC_SWAP,      MVT::i32, Expand);
00788     setOperationAction(ISD::ATOMIC_LOAD_ADD,  MVT::i32, Expand);
00789     setOperationAction(ISD::ATOMIC_LOAD_SUB,  MVT::i32, Expand);
00790     setOperationAction(ISD::ATOMIC_LOAD_AND,  MVT::i32, Expand);
00791     setOperationAction(ISD::ATOMIC_LOAD_OR,   MVT::i32, Expand);
00792     setOperationAction(ISD::ATOMIC_LOAD_XOR,  MVT::i32, Expand);
00793     setOperationAction(ISD::ATOMIC_LOAD_NAND, MVT::i32, Expand);
00794     setOperationAction(ISD::ATOMIC_LOAD_MIN, MVT::i32, Expand);
00795     setOperationAction(ISD::ATOMIC_LOAD_MAX, MVT::i32, Expand);
00796     setOperationAction(ISD::ATOMIC_LOAD_UMIN, MVT::i32, Expand);
00797     setOperationAction(ISD::ATOMIC_LOAD_UMAX, MVT::i32, Expand);
00798     // Mark ATOMIC_LOAD and ATOMIC_STORE custom so we can handle the
00799     // Unordered/Monotonic case.
00800     setOperationAction(ISD::ATOMIC_LOAD, MVT::i32, Custom);
00801     setOperationAction(ISD::ATOMIC_STORE, MVT::i32, Custom);
00802   }
00803 
00804   setOperationAction(ISD::PREFETCH,         MVT::Other, Custom);
00805 
00806   // Requires SXTB/SXTH, available on v6 and up in both ARM and Thumb modes.
00807   if (!Subtarget->hasV6Ops()) {
00808     setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i16, Expand);
00809     setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i8,  Expand);
00810   }
00811   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1, Expand);
00812 
00813   if (!TM.Options.UseSoftFloat && Subtarget->hasVFP2() &&
00814       !Subtarget->isThumb1Only()) {
00815     // Turn f64->i64 into VMOVRRD, i64 -> f64 to VMOVDRR
00816     // iff target supports vfp2.
00817     setOperationAction(ISD::BITCAST, MVT::i64, Custom);
00818     setOperationAction(ISD::FLT_ROUNDS_, MVT::i32, Custom);
00819   }
00820 
00821   // We want to custom lower some of our intrinsics.
00822   setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
00823   if (Subtarget->isTargetDarwin()) {
00824     setOperationAction(ISD::EH_SJLJ_SETJMP, MVT::i32, Custom);
00825     setOperationAction(ISD::EH_SJLJ_LONGJMP, MVT::Other, Custom);
00826     setLibcallName(RTLIB::UNWIND_RESUME, "_Unwind_SjLj_Resume");
00827   }
00828 
00829   setOperationAction(ISD::SETCC,     MVT::i32, Expand);
00830   setOperationAction(ISD::SETCC,     MVT::f32, Expand);
00831   setOperationAction(ISD::SETCC,     MVT::f64, Expand);
00832   setOperationAction(ISD::SELECT,    MVT::i32, Custom);
00833   setOperationAction(ISD::SELECT,    MVT::f32, Custom);
00834   setOperationAction(ISD::SELECT,    MVT::f64, Custom);
00835   setOperationAction(ISD::SELECT_CC, MVT::i32, Custom);
00836   setOperationAction(ISD::SELECT_CC, MVT::f32, Custom);
00837   setOperationAction(ISD::SELECT_CC, MVT::f64, Custom);
00838 
00839   setOperationAction(ISD::BRCOND,    MVT::Other, Expand);
00840   setOperationAction(ISD::BR_CC,     MVT::i32,   Custom);
00841   setOperationAction(ISD::BR_CC,     MVT::f32,   Custom);
00842   setOperationAction(ISD::BR_CC,     MVT::f64,   Custom);
00843   setOperationAction(ISD::BR_JT,     MVT::Other, Custom);
00844 
00845   // We don't support sin/cos/fmod/copysign/pow
00846   setOperationAction(ISD::FSIN,      MVT::f64, Expand);
00847   setOperationAction(ISD::FSIN,      MVT::f32, Expand);
00848   setOperationAction(ISD::FCOS,      MVT::f32, Expand);
00849   setOperationAction(ISD::FCOS,      MVT::f64, Expand);
00850   setOperationAction(ISD::FSINCOS,   MVT::f64, Expand);
00851   setOperationAction(ISD::FSINCOS,   MVT::f32, Expand);
00852   setOperationAction(ISD::FREM,      MVT::f64, Expand);
00853   setOperationAction(ISD::FREM,      MVT::f32, Expand);
00854   if (!TM.Options.UseSoftFloat && Subtarget->hasVFP2() &&
00855       !Subtarget->isThumb1Only()) {
00856     setOperationAction(ISD::FCOPYSIGN, MVT::f64, Custom);
00857     setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
00858   }
00859   setOperationAction(ISD::FPOW,      MVT::f64, Expand);
00860   setOperationAction(ISD::FPOW,      MVT::f32, Expand);
00861 
00862   if (!Subtarget->hasVFP4()) {
00863     setOperationAction(ISD::FMA, MVT::f64, Expand);
00864     setOperationAction(ISD::FMA, MVT::f32, Expand);
00865   }
00866 
00867   // Various VFP goodness
00868   if (!TM.Options.UseSoftFloat && !Subtarget->isThumb1Only()) {
00869     // int <-> fp are custom expanded into bit_convert + ARMISD ops.
00870     if (Subtarget->hasVFP2()) {
00871       setOperationAction(ISD::SINT_TO_FP, MVT::i32, Custom);
00872       setOperationAction(ISD::UINT_TO_FP, MVT::i32, Custom);
00873       setOperationAction(ISD::FP_TO_UINT, MVT::i32, Custom);
00874       setOperationAction(ISD::FP_TO_SINT, MVT::i32, Custom);
00875     }
00876 
00877     // FP-ARMv8 adds f64 <-> f16 conversion. Before that it should be expanded.
00878     if (!Subtarget->hasFPARMv8() || Subtarget->isFPOnlySP()) {
00879       setOperationAction(ISD::FP16_TO_FP, MVT::f64, Expand);
00880       setOperationAction(ISD::FP_TO_FP16, MVT::f64, Expand);
00881     }
00882 
00883     // fp16 is a special v7 extension that adds f16 <-> f32 conversions.
00884     if (!Subtarget->hasFP16()) {
00885       setOperationAction(ISD::FP16_TO_FP, MVT::f32, Expand);
00886       setOperationAction(ISD::FP_TO_FP16, MVT::f32, Expand);
00887     }
00888   }
00889 
00890   // Combine sin / cos into one node or libcall if possible.
00891   if (Subtarget->hasSinCos()) {
00892     setLibcallName(RTLIB::SINCOS_F32, "sincosf");
00893     setLibcallName(RTLIB::SINCOS_F64, "sincos");
00894     if (Subtarget->getTargetTriple().isiOS()) {
00895       // For iOS, we don't want to the normal expansion of a libcall to
00896       // sincos. We want to issue a libcall to __sincos_stret.
00897       setOperationAction(ISD::FSINCOS, MVT::f64, Custom);
00898       setOperationAction(ISD::FSINCOS, MVT::f32, Custom);
00899     }
00900   }
00901 
00902   // FP-ARMv8 implements a lot of rounding-like FP operations.
00903   if (Subtarget->hasFPARMv8()) {
00904     setOperationAction(ISD::FFLOOR, MVT::f32, Legal);
00905     setOperationAction(ISD::FCEIL, MVT::f32, Legal);
00906     setOperationAction(ISD::FROUND, MVT::f32, Legal);
00907     setOperationAction(ISD::FTRUNC, MVT::f32, Legal);
00908     setOperationAction(ISD::FNEARBYINT, MVT::f32, Legal);
00909     setOperationAction(ISD::FRINT, MVT::f32, Legal);
00910     if (!Subtarget->isFPOnlySP()) {
00911       setOperationAction(ISD::FFLOOR, MVT::f64, Legal);
00912       setOperationAction(ISD::FCEIL, MVT::f64, Legal);
00913       setOperationAction(ISD::FROUND, MVT::f64, Legal);
00914       setOperationAction(ISD::FTRUNC, MVT::f64, Legal);
00915       setOperationAction(ISD::FNEARBYINT, MVT::f64, Legal);
00916       setOperationAction(ISD::FRINT, MVT::f64, Legal);
00917     }
00918   }
00919   // We have target-specific dag combine patterns for the following nodes:
00920   // ARMISD::VMOVRRD  - No need to call setTargetDAGCombine
00921   setTargetDAGCombine(ISD::ADD);
00922   setTargetDAGCombine(ISD::SUB);
00923   setTargetDAGCombine(ISD::MUL);
00924   setTargetDAGCombine(ISD::AND);
00925   setTargetDAGCombine(ISD::OR);
00926   setTargetDAGCombine(ISD::XOR);
00927 
00928   if (Subtarget->hasV6Ops())
00929     setTargetDAGCombine(ISD::SRL);
00930 
00931   setStackPointerRegisterToSaveRestore(ARM::SP);
00932 
00933   if (TM.Options.UseSoftFloat || Subtarget->isThumb1Only() ||
00934       !Subtarget->hasVFP2())
00935     setSchedulingPreference(Sched::RegPressure);
00936   else
00937     setSchedulingPreference(Sched::Hybrid);
00938 
00939   //// temporary - rewrite interface to use type
00940   MaxStoresPerMemset = 8;
00941   MaxStoresPerMemsetOptSize = Subtarget->isTargetDarwin() ? 8 : 4;
00942   MaxStoresPerMemcpy = 4; // For @llvm.memcpy -> sequence of stores
00943   MaxStoresPerMemcpyOptSize = Subtarget->isTargetDarwin() ? 4 : 2;
00944   MaxStoresPerMemmove = 4; // For @llvm.memmove -> sequence of stores
00945   MaxStoresPerMemmoveOptSize = Subtarget->isTargetDarwin() ? 4 : 2;
00946 
00947   // On ARM arguments smaller than 4 bytes are extended, so all arguments
00948   // are at least 4 bytes aligned.
00949   setMinStackArgumentAlignment(4);
00950 
00951   // Prefer likely predicted branches to selects on out-of-order cores.
00952   PredictableSelectIsExpensive = Subtarget->isLikeA9();
00953 
00954   setMinFunctionAlignment(Subtarget->isThumb() ? 1 : 2);
00955 }
00956 
00957 // FIXME: It might make sense to define the representative register class as the
00958 // nearest super-register that has a non-null superset. For example, DPR_VFP2 is
00959 // a super-register of SPR, and DPR is a superset if DPR_VFP2. Consequently,
00960 // SPR's representative would be DPR_VFP2. This should work well if register
00961 // pressure tracking were modified such that a register use would increment the
00962 // pressure of the register class's representative and all of it's super
00963 // classes' representatives transitively. We have not implemented this because
00964 // of the difficulty prior to coalescing of modeling operand register classes
00965 // due to the common occurrence of cross class copies and subregister insertions
00966 // and extractions.
00967 std::pair<const TargetRegisterClass*, uint8_t>
00968 ARMTargetLowering::findRepresentativeClass(MVT VT) const{
00969   const TargetRegisterClass *RRC = nullptr;
00970   uint8_t Cost = 1;
00971   switch (VT.SimpleTy) {
00972   default:
00973     return TargetLowering::findRepresentativeClass(VT);
00974   // Use DPR as representative register class for all floating point
00975   // and vector types. Since there are 32 SPR registers and 32 DPR registers so
00976   // the cost is 1 for both f32 and f64.
00977   case MVT::f32: case MVT::f64: case MVT::v8i8: case MVT::v4i16:
00978   case MVT::v2i32: case MVT::v1i64: case MVT::v2f32:
00979     RRC = &ARM::DPRRegClass;
00980     // When NEON is used for SP, only half of the register file is available
00981     // because operations that define both SP and DP results will be constrained
00982     // to the VFP2 class (D0-D15). We currently model this constraint prior to
00983     // coalescing by double-counting the SP regs. See the FIXME above.
00984     if (Subtarget->useNEONForSinglePrecisionFP())
00985       Cost = 2;
00986     break;
00987   case MVT::v16i8: case MVT::v8i16: case MVT::v4i32: case MVT::v2i64:
00988   case MVT::v4f32: case MVT::v2f64:
00989     RRC = &ARM::DPRRegClass;
00990     Cost = 2;
00991     break;
00992   case MVT::v4i64:
00993     RRC = &ARM::DPRRegClass;
00994     Cost = 4;
00995     break;
00996   case MVT::v8i64:
00997     RRC = &ARM::DPRRegClass;
00998     Cost = 8;
00999     break;
01000   }
01001   return std::make_pair(RRC, Cost);
01002 }
01003 
01004 const char *ARMTargetLowering::getTargetNodeName(unsigned Opcode) const {
01005   switch (Opcode) {
01006   default: return nullptr;
01007   case ARMISD::Wrapper:       return "ARMISD::Wrapper";
01008   case ARMISD::WrapperPIC:    return "ARMISD::WrapperPIC";
01009   case ARMISD::WrapperJT:     return "ARMISD::WrapperJT";
01010   case ARMISD::CALL:          return "ARMISD::CALL";
01011   case ARMISD::CALL_PRED:     return "ARMISD::CALL_PRED";
01012   case ARMISD::CALL_NOLINK:   return "ARMISD::CALL_NOLINK";
01013   case ARMISD::tCALL:         return "ARMISD::tCALL";
01014   case ARMISD::BRCOND:        return "ARMISD::BRCOND";
01015   case ARMISD::BR_JT:         return "ARMISD::BR_JT";
01016   case ARMISD::BR2_JT:        return "ARMISD::BR2_JT";
01017   case ARMISD::RET_FLAG:      return "ARMISD::RET_FLAG";
01018   case ARMISD::INTRET_FLAG:   return "ARMISD::INTRET_FLAG";
01019   case ARMISD::PIC_ADD:       return "ARMISD::PIC_ADD";
01020   case ARMISD::CMP:           return "ARMISD::CMP";
01021   case ARMISD::CMN:           return "ARMISD::CMN";
01022   case ARMISD::CMPZ:          return "ARMISD::CMPZ";
01023   case ARMISD::CMPFP:         return "ARMISD::CMPFP";
01024   case ARMISD::CMPFPw0:       return "ARMISD::CMPFPw0";
01025   case ARMISD::BCC_i64:       return "ARMISD::BCC_i64";
01026   case ARMISD::FMSTAT:        return "ARMISD::FMSTAT";
01027 
01028   case ARMISD::CMOV:          return "ARMISD::CMOV";
01029 
01030   case ARMISD::RBIT:          return "ARMISD::RBIT";
01031 
01032   case ARMISD::FTOSI:         return "ARMISD::FTOSI";
01033   case ARMISD::FTOUI:         return "ARMISD::FTOUI";
01034   case ARMISD::SITOF:         return "ARMISD::SITOF";
01035   case ARMISD::UITOF:         return "ARMISD::UITOF";
01036 
01037   case ARMISD::SRL_FLAG:      return "ARMISD::SRL_FLAG";
01038   case ARMISD::SRA_FLAG:      return "ARMISD::SRA_FLAG";
01039   case ARMISD::RRX:           return "ARMISD::RRX";
01040 
01041   case ARMISD::ADDC:          return "ARMISD::ADDC";
01042   case ARMISD::ADDE:          return "ARMISD::ADDE";
01043   case ARMISD::SUBC:          return "ARMISD::SUBC";
01044   case ARMISD::SUBE:          return "ARMISD::SUBE";
01045 
01046   case ARMISD::VMOVRRD:       return "ARMISD::VMOVRRD";
01047   case ARMISD::VMOVDRR:       return "ARMISD::VMOVDRR";
01048 
01049   case ARMISD::EH_SJLJ_SETJMP: return "ARMISD::EH_SJLJ_SETJMP";
01050   case ARMISD::EH_SJLJ_LONGJMP:return "ARMISD::EH_SJLJ_LONGJMP";
01051 
01052   case ARMISD::TC_RETURN:     return "ARMISD::TC_RETURN";
01053 
01054   case ARMISD::THREAD_POINTER:return "ARMISD::THREAD_POINTER";
01055 
01056   case ARMISD::DYN_ALLOC:     return "ARMISD::DYN_ALLOC";
01057 
01058   case ARMISD::MEMBARRIER_MCR: return "ARMISD::MEMBARRIER_MCR";
01059 
01060   case ARMISD::PRELOAD:       return "ARMISD::PRELOAD";
01061 
01062   case ARMISD::WIN__CHKSTK:   return "ARMISD:::WIN__CHKSTK";
01063 
01064   case ARMISD::VCEQ:          return "ARMISD::VCEQ";
01065   case ARMISD::VCEQZ:         return "ARMISD::VCEQZ";
01066   case ARMISD::VCGE:          return "ARMISD::VCGE";
01067   case ARMISD::VCGEZ:         return "ARMISD::VCGEZ";
01068   case ARMISD::VCLEZ:         return "ARMISD::VCLEZ";
01069   case ARMISD::VCGEU:         return "ARMISD::VCGEU";
01070   case ARMISD::VCGT:          return "ARMISD::VCGT";
01071   case ARMISD::VCGTZ:         return "ARMISD::VCGTZ";
01072   case ARMISD::VCLTZ:         return "ARMISD::VCLTZ";
01073   case ARMISD::VCGTU:         return "ARMISD::VCGTU";
01074   case ARMISD::VTST:          return "ARMISD::VTST";
01075 
01076   case ARMISD::VSHL:          return "ARMISD::VSHL";
01077   case ARMISD::VSHRs:         return "ARMISD::VSHRs";
01078   case ARMISD::VSHRu:         return "ARMISD::VSHRu";
01079   case ARMISD::VRSHRs:        return "ARMISD::VRSHRs";
01080   case ARMISD::VRSHRu:        return "ARMISD::VRSHRu";
01081   case ARMISD::VRSHRN:        return "ARMISD::VRSHRN";
01082   case ARMISD::VQSHLs:        return "ARMISD::VQSHLs";
01083   case ARMISD::VQSHLu:        return "ARMISD::VQSHLu";
01084   case ARMISD::VQSHLsu:       return "ARMISD::VQSHLsu";
01085   case ARMISD::VQSHRNs:       return "ARMISD::VQSHRNs";
01086   case ARMISD::VQSHRNu:       return "ARMISD::VQSHRNu";
01087   case ARMISD::VQSHRNsu:      return "ARMISD::VQSHRNsu";
01088   case ARMISD::VQRSHRNs:      return "ARMISD::VQRSHRNs";
01089   case ARMISD::VQRSHRNu:      return "ARMISD::VQRSHRNu";
01090   case ARMISD::VQRSHRNsu:     return "ARMISD::VQRSHRNsu";
01091   case ARMISD::VGETLANEu:     return "ARMISD::VGETLANEu";
01092   case ARMISD::VGETLANEs:     return "ARMISD::VGETLANEs";
01093   case ARMISD::VMOVIMM:       return "ARMISD::VMOVIMM";
01094   case ARMISD::VMVNIMM:       return "ARMISD::VMVNIMM";
01095   case ARMISD::VMOVFPIMM:     return "ARMISD::VMOVFPIMM";
01096   case ARMISD::VDUP:          return "ARMISD::VDUP";
01097   case ARMISD::VDUPLANE:      return "ARMISD::VDUPLANE";
01098   case ARMISD::VEXT:          return "ARMISD::VEXT";
01099   case ARMISD::VREV64:        return "ARMISD::VREV64";
01100   case ARMISD::VREV32:        return "ARMISD::VREV32";
01101   case ARMISD::VREV16:        return "ARMISD::VREV16";
01102   case ARMISD::VZIP:          return "ARMISD::VZIP";
01103   case ARMISD::VUZP:          return "ARMISD::VUZP";
01104   case ARMISD::VTRN:          return "ARMISD::VTRN";
01105   case ARMISD::VTBL1:         return "ARMISD::VTBL1";
01106   case ARMISD::VTBL2:         return "ARMISD::VTBL2";
01107   case ARMISD::VMULLs:        return "ARMISD::VMULLs";
01108   case ARMISD::VMULLu:        return "ARMISD::VMULLu";
01109   case ARMISD::UMLAL:         return "ARMISD::UMLAL";
01110   case ARMISD::SMLAL:         return "ARMISD::SMLAL";
01111   case ARMISD::BUILD_VECTOR:  return "ARMISD::BUILD_VECTOR";
01112   case ARMISD::FMAX:          return "ARMISD::FMAX";
01113   case ARMISD::FMIN:          return "ARMISD::FMIN";
01114   case ARMISD::VMAXNM:        return "ARMISD::VMAX";
01115   case ARMISD::VMINNM:        return "ARMISD::VMIN";
01116   case ARMISD::BFI:           return "ARMISD::BFI";
01117   case ARMISD::VORRIMM:       return "ARMISD::VORRIMM";
01118   case ARMISD::VBICIMM:       return "ARMISD::VBICIMM";
01119   case ARMISD::VBSL:          return "ARMISD::VBSL";
01120   case ARMISD::VLD2DUP:       return "ARMISD::VLD2DUP";
01121   case ARMISD::VLD3DUP:       return "ARMISD::VLD3DUP";
01122   case ARMISD::VLD4DUP:       return "ARMISD::VLD4DUP";
01123   case ARMISD::VLD1_UPD:      return "ARMISD::VLD1_UPD";
01124   case ARMISD::VLD2_UPD:      return "ARMISD::VLD2_UPD";
01125   case ARMISD::VLD3_UPD:      return "ARMISD::VLD3_UPD";
01126   case ARMISD::VLD4_UPD:      return "ARMISD::VLD4_UPD";
01127   case ARMISD::VLD2LN_UPD:    return "ARMISD::VLD2LN_UPD";
01128   case ARMISD::VLD3LN_UPD:    return "ARMISD::VLD3LN_UPD";
01129   case ARMISD::VLD4LN_UPD:    return "ARMISD::VLD4LN_UPD";
01130   case ARMISD::VLD2DUP_UPD:   return "ARMISD::VLD2DUP_UPD";
01131   case ARMISD::VLD3DUP_UPD:   return "ARMISD::VLD3DUP_UPD";
01132   case ARMISD::VLD4DUP_UPD:   return "ARMISD::VLD4DUP_UPD";
01133   case ARMISD::VST1_UPD:      return "ARMISD::VST1_UPD";
01134   case ARMISD::VST2_UPD:      return "ARMISD::VST2_UPD";
01135   case ARMISD::VST3_UPD:      return "ARMISD::VST3_UPD";
01136   case ARMISD::VST4_UPD:      return "ARMISD::VST4_UPD";
01137   case ARMISD::VST2LN_UPD:    return "ARMISD::VST2LN_UPD";
01138   case ARMISD::VST3LN_UPD:    return "ARMISD::VST3LN_UPD";
01139   case ARMISD::VST4LN_UPD:    return "ARMISD::VST4LN_UPD";
01140   }
01141 }
01142 
01143 EVT ARMTargetLowering::getSetCCResultType(LLVMContext &, EVT VT) const {
01144   if (!VT.isVector()) return getPointerTy();
01145   return VT.changeVectorElementTypeToInteger();
01146 }
01147 
01148 /// getRegClassFor - Return the register class that should be used for the
01149 /// specified value type.
01150 const TargetRegisterClass *ARMTargetLowering::getRegClassFor(MVT VT) const {
01151   // Map v4i64 to QQ registers but do not make the type legal. Similarly map
01152   // v8i64 to QQQQ registers. v4i64 and v8i64 are only used for REG_SEQUENCE to
01153   // load / store 4 to 8 consecutive D registers.
01154   if (Subtarget->hasNEON()) {
01155     if (VT == MVT::v4i64)
01156       return &ARM::QQPRRegClass;
01157     if (VT == MVT::v8i64)
01158       return &ARM::QQQQPRRegClass;
01159   }
01160   return TargetLowering::getRegClassFor(VT);
01161 }
01162 
01163 // Create a fast isel object.
01164 FastISel *
01165 ARMTargetLowering::createFastISel(FunctionLoweringInfo &funcInfo,
01166                                   const TargetLibraryInfo *libInfo) const {
01167   return ARM::createFastISel(funcInfo, libInfo);
01168 }
01169 
01170 /// getMaximalGlobalOffset - Returns the maximal possible offset which can
01171 /// be used for loads / stores from the global.
01172 unsigned ARMTargetLowering::getMaximalGlobalOffset() const {
01173   return (Subtarget->isThumb1Only() ? 127 : 4095);
01174 }
01175 
01176 Sched::Preference ARMTargetLowering::getSchedulingPreference(SDNode *N) const {
01177   unsigned NumVals = N->getNumValues();
01178   if (!NumVals)
01179     return Sched::RegPressure;
01180 
01181   for (unsigned i = 0; i != NumVals; ++i) {
01182     EVT VT = N->getValueType(i);
01183     if (VT == MVT::Glue || VT == MVT::Other)
01184       continue;
01185     if (VT.isFloatingPoint() || VT.isVector())
01186       return Sched::ILP;
01187   }
01188 
01189   if (!N->isMachineOpcode())
01190     return Sched::RegPressure;
01191 
01192   // Load are scheduled for latency even if there instruction itinerary
01193   // is not available.
01194   const TargetInstrInfo *TII =
01195       getTargetMachine().getSubtargetImpl()->getInstrInfo();
01196   const MCInstrDesc &MCID = TII->get(N->getMachineOpcode());
01197 
01198   if (MCID.getNumDefs() == 0)
01199     return Sched::RegPressure;
01200   if (!Itins->isEmpty() &&
01201       Itins->getOperandCycle(MCID.getSchedClass(), 0) > 2)
01202     return Sched::ILP;
01203 
01204   return Sched::RegPressure;
01205 }
01206 
01207 //===----------------------------------------------------------------------===//
01208 // Lowering Code
01209 //===----------------------------------------------------------------------===//
01210 
01211 /// IntCCToARMCC - Convert a DAG integer condition code to an ARM CC
01212 static ARMCC::CondCodes IntCCToARMCC(ISD::CondCode CC) {
01213   switch (CC) {
01214   default: llvm_unreachable("Unknown condition code!");
01215   case ISD::SETNE:  return ARMCC::NE;
01216   case ISD::SETEQ:  return ARMCC::EQ;
01217   case ISD::SETGT:  return ARMCC::GT;
01218   case ISD::SETGE:  return ARMCC::GE;
01219   case ISD::SETLT:  return ARMCC::LT;
01220   case ISD::SETLE:  return ARMCC::LE;
01221   case ISD::SETUGT: return ARMCC::HI;
01222   case ISD::SETUGE: return ARMCC::HS;
01223   case ISD::SETULT: return ARMCC::LO;
01224   case ISD::SETULE: return ARMCC::LS;
01225   }
01226 }
01227 
01228 /// FPCCToARMCC - Convert a DAG fp condition code to an ARM CC.
01229 static void FPCCToARMCC(ISD::CondCode CC, ARMCC::CondCodes &CondCode,
01230                         ARMCC::CondCodes &CondCode2) {
01231   CondCode2 = ARMCC::AL;
01232   switch (CC) {
01233   default: llvm_unreachable("Unknown FP condition!");
01234   case ISD::SETEQ:
01235   case ISD::SETOEQ: CondCode = ARMCC::EQ; break;
01236   case ISD::SETGT:
01237   case ISD::SETOGT: CondCode = ARMCC::GT; break;
01238   case ISD::SETGE:
01239   case ISD::SETOGE: CondCode = ARMCC::GE; break;
01240   case ISD::SETOLT: CondCode = ARMCC::MI; break;
01241   case ISD::SETOLE: CondCode = ARMCC::LS; break;
01242   case ISD::SETONE: CondCode = ARMCC::MI; CondCode2 = ARMCC::GT; break;
01243   case ISD::SETO:   CondCode = ARMCC::VC; break;
01244   case ISD::SETUO:  CondCode = ARMCC::VS; break;
01245   case ISD::SETUEQ: CondCode = ARMCC::EQ; CondCode2 = ARMCC::VS; break;
01246   case ISD::SETUGT: CondCode = ARMCC::HI; break;
01247   case ISD::SETUGE: CondCode = ARMCC::PL; break;
01248   case ISD::SETLT:
01249   case ISD::SETULT: CondCode = ARMCC::LT; break;
01250   case ISD::SETLE:
01251   case ISD::SETULE: CondCode = ARMCC::LE; break;
01252   case ISD::SETNE:
01253   case ISD::SETUNE: CondCode = ARMCC::NE; break;
01254   }
01255 }
01256 
01257 //===----------------------------------------------------------------------===//
01258 //                      Calling Convention Implementation
01259 //===----------------------------------------------------------------------===//
01260 
01261 #include "ARMGenCallingConv.inc"
01262 
01263 /// getEffectiveCallingConv - Get the effective calling convention, taking into
01264 /// account presence of floating point hardware and calling convention
01265 /// limitations, such as support for variadic functions.
01266 CallingConv::ID
01267 ARMTargetLowering::getEffectiveCallingConv(CallingConv::ID CC,
01268                                            bool isVarArg) const {
01269   switch (CC) {
01270   default:
01271     llvm_unreachable("Unsupported calling convention");
01272   case CallingConv::ARM_AAPCS:
01273   case CallingConv::ARM_APCS:
01274   case CallingConv::GHC:
01275     return CC;
01276   case CallingConv::ARM_AAPCS_VFP:
01277     return isVarArg ? CallingConv::ARM_AAPCS : CallingConv::ARM_AAPCS_VFP;
01278   case CallingConv::C:
01279     if (!Subtarget->isAAPCS_ABI())
01280       return CallingConv::ARM_APCS;
01281     else if (Subtarget->hasVFP2() && !Subtarget->isThumb1Only() &&
01282              getTargetMachine().Options.FloatABIType == FloatABI::Hard &&
01283              !isVarArg)
01284       return CallingConv::ARM_AAPCS_VFP;
01285     else
01286       return CallingConv::ARM_AAPCS;
01287   case CallingConv::Fast:
01288     if (!Subtarget->isAAPCS_ABI()) {
01289       if (Subtarget->hasVFP2() && !Subtarget->isThumb1Only() && !isVarArg)
01290         return CallingConv::Fast;
01291       return CallingConv::ARM_APCS;
01292     } else if (Subtarget->hasVFP2() && !Subtarget->isThumb1Only() && !isVarArg)
01293       return CallingConv::ARM_AAPCS_VFP;
01294     else
01295       return CallingConv::ARM_AAPCS;
01296   }
01297 }
01298 
01299 /// CCAssignFnForNode - Selects the correct CCAssignFn for the given
01300 /// CallingConvention.
01301 CCAssignFn *ARMTargetLowering::CCAssignFnForNode(CallingConv::ID CC,
01302                                                  bool Return,
01303                                                  bool isVarArg) const {
01304   switch (getEffectiveCallingConv(CC, isVarArg)) {
01305   default:
01306     llvm_unreachable("Unsupported calling convention");
01307   case CallingConv::ARM_APCS:
01308     return (Return ? RetCC_ARM_APCS : CC_ARM_APCS);
01309   case CallingConv::ARM_AAPCS:
01310     return (Return ? RetCC_ARM_AAPCS : CC_ARM_AAPCS);
01311   case CallingConv::ARM_AAPCS_VFP:
01312     return (Return ? RetCC_ARM_AAPCS_VFP : CC_ARM_AAPCS_VFP);
01313   case CallingConv::Fast:
01314     return (Return ? RetFastCC_ARM_APCS : FastCC_ARM_APCS);
01315   case CallingConv::GHC:
01316     return (Return ? RetCC_ARM_APCS : CC_ARM_APCS_GHC);
01317   }
01318 }
01319 
01320 /// LowerCallResult - Lower the result values of a call into the
01321 /// appropriate copies out of appropriate physical registers.
01322 SDValue
01323 ARMTargetLowering::LowerCallResult(SDValue Chain, SDValue InFlag,
01324                                    CallingConv::ID CallConv, bool isVarArg,
01325                                    const SmallVectorImpl<ISD::InputArg> &Ins,
01326                                    SDLoc dl, SelectionDAG &DAG,
01327                                    SmallVectorImpl<SDValue> &InVals,
01328                                    bool isThisReturn, SDValue ThisVal) const {
01329 
01330   // Assign locations to each value returned by this call.
01331   SmallVector<CCValAssign, 16> RVLocs;
01332   ARMCCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs,
01333                     *DAG.getContext(), Call);
01334   CCInfo.AnalyzeCallResult(Ins,
01335                            CCAssignFnForNode(CallConv, /* Return*/ true,
01336                                              isVarArg));
01337 
01338   // Copy all of the result registers out of their specified physreg.
01339   for (unsigned i = 0; i != RVLocs.size(); ++i) {
01340     CCValAssign VA = RVLocs[i];
01341 
01342     // Pass 'this' value directly from the argument to return value, to avoid
01343     // reg unit interference
01344     if (i == 0 && isThisReturn) {
01345       assert(!VA.needsCustom() && VA.getLocVT() == MVT::i32 &&
01346              "unexpected return calling convention register assignment");
01347       InVals.push_back(ThisVal);
01348       continue;
01349     }
01350 
01351     SDValue Val;
01352     if (VA.needsCustom()) {
01353       // Handle f64 or half of a v2f64.
01354       SDValue Lo = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32,
01355                                       InFlag);
01356       Chain = Lo.getValue(1);
01357       InFlag = Lo.getValue(2);
01358       VA = RVLocs[++i]; // skip ahead to next loc
01359       SDValue Hi = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32,
01360                                       InFlag);
01361       Chain = Hi.getValue(1);
01362       InFlag = Hi.getValue(2);
01363       if (!Subtarget->isLittle())
01364         std::swap (Lo, Hi);
01365       Val = DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi);
01366 
01367       if (VA.getLocVT() == MVT::v2f64) {
01368         SDValue Vec = DAG.getNode(ISD::UNDEF, dl, MVT::v2f64);
01369         Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Vec, Val,
01370                           DAG.getConstant(0, MVT::i32));
01371 
01372         VA = RVLocs[++i]; // skip ahead to next loc
01373         Lo = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32, InFlag);
01374         Chain = Lo.getValue(1);
01375         InFlag = Lo.getValue(2);
01376         VA = RVLocs[++i]; // skip ahead to next loc
01377         Hi = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32, InFlag);
01378         Chain = Hi.getValue(1);
01379         InFlag = Hi.getValue(2);
01380         if (!Subtarget->isLittle())
01381           std::swap (Lo, Hi);
01382         Val = DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi);
01383         Val = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Vec, Val,
01384                           DAG.getConstant(1, MVT::i32));
01385       }
01386     } else {
01387       Val = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), VA.getLocVT(),
01388                                InFlag);
01389       Chain = Val.getValue(1);
01390       InFlag = Val.getValue(2);
01391     }
01392 
01393     switch (VA.getLocInfo()) {
01394     default: llvm_unreachable("Unknown loc info!");
01395     case CCValAssign::Full: break;
01396     case CCValAssign::BCvt:
01397       Val = DAG.getNode(ISD::BITCAST, dl, VA.getValVT(), Val);
01398       break;
01399     }
01400 
01401     InVals.push_back(Val);
01402   }
01403 
01404   return Chain;
01405 }
01406 
01407 /// LowerMemOpCallTo - Store the argument to the stack.
01408 SDValue
01409 ARMTargetLowering::LowerMemOpCallTo(SDValue Chain,
01410                                     SDValue StackPtr, SDValue Arg,
01411                                     SDLoc dl, SelectionDAG &DAG,
01412                                     const CCValAssign &VA,
01413                                     ISD::ArgFlagsTy Flags) const {
01414   unsigned LocMemOffset = VA.getLocMemOffset();
01415   SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset);
01416   PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, PtrOff);
01417   return DAG.getStore(Chain, dl, Arg, PtrOff,
01418                       MachinePointerInfo::getStack(LocMemOffset),
01419                       false, false, 0);
01420 }
01421 
01422 void ARMTargetLowering::PassF64ArgInRegs(SDLoc dl, SelectionDAG &DAG,
01423                                          SDValue Chain, SDValue &Arg,
01424                                          RegsToPassVector &RegsToPass,
01425                                          CCValAssign &VA, CCValAssign &NextVA,
01426                                          SDValue &StackPtr,
01427                                          SmallVectorImpl<SDValue> &MemOpChains,
01428                                          ISD::ArgFlagsTy Flags) const {
01429 
01430   SDValue fmrrd = DAG.getNode(ARMISD::VMOVRRD, dl,
01431                               DAG.getVTList(MVT::i32, MVT::i32), Arg);
01432   unsigned id = Subtarget->isLittle() ? 0 : 1;
01433   RegsToPass.push_back(std::make_pair(VA.getLocReg(), fmrrd.getValue(id)));
01434 
01435   if (NextVA.isRegLoc())
01436     RegsToPass.push_back(std::make_pair(NextVA.getLocReg(), fmrrd.getValue(1-id)));
01437   else {
01438     assert(NextVA.isMemLoc());
01439     if (!StackPtr.getNode())
01440       StackPtr = DAG.getCopyFromReg(Chain, dl, ARM::SP, getPointerTy());
01441 
01442     MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, fmrrd.getValue(1-id),
01443                                            dl, DAG, NextVA,
01444                                            Flags));
01445   }
01446 }
01447 
01448 /// LowerCall - Lowering a call into a callseq_start <-
01449 /// ARMISD:CALL <- callseq_end chain. Also add input and output parameter
01450 /// nodes.
01451 SDValue
01452 ARMTargetLowering::LowerCall(TargetLowering::CallLoweringInfo &CLI,
01453                              SmallVectorImpl<SDValue> &InVals) const {
01454   SelectionDAG &DAG                     = CLI.DAG;
01455   SDLoc &dl                          = CLI.DL;
01456   SmallVectorImpl<ISD::OutputArg> &Outs = CLI.Outs;
01457   SmallVectorImpl<SDValue> &OutVals     = CLI.OutVals;
01458   SmallVectorImpl<ISD::InputArg> &Ins   = CLI.Ins;
01459   SDValue Chain                         = CLI.Chain;
01460   SDValue Callee                        = CLI.Callee;
01461   bool &isTailCall                      = CLI.IsTailCall;
01462   CallingConv::ID CallConv              = CLI.CallConv;
01463   bool doesNotRet                       = CLI.DoesNotReturn;
01464   bool isVarArg                         = CLI.IsVarArg;
01465 
01466   MachineFunction &MF = DAG.getMachineFunction();
01467   bool isStructRet    = (Outs.empty()) ? false : Outs[0].Flags.isSRet();
01468   bool isThisReturn   = false;
01469   bool isSibCall      = false;
01470 
01471   // Disable tail calls if they're not supported.
01472   if (!Subtarget->supportsTailCall() || MF.getTarget().Options.DisableTailCalls)
01473     isTailCall = false;
01474 
01475   if (isTailCall) {
01476     // Check if it's really possible to do a tail call.
01477     isTailCall = IsEligibleForTailCallOptimization(Callee, CallConv,
01478                     isVarArg, isStructRet, MF.getFunction()->hasStructRetAttr(),
01479                                                    Outs, OutVals, Ins, DAG);
01480     if (!isTailCall && CLI.CS && CLI.CS->isMustTailCall())
01481       report_fatal_error("failed to perform tail call elimination on a call "
01482                          "site marked musttail");
01483     // We don't support GuaranteedTailCallOpt for ARM, only automatically
01484     // detected sibcalls.
01485     if (isTailCall) {
01486       ++NumTailCalls;
01487       isSibCall = true;
01488     }
01489   }
01490 
01491   // Analyze operands of the call, assigning locations to each operand.
01492   SmallVector<CCValAssign, 16> ArgLocs;
01493   ARMCCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), ArgLocs,
01494                     *DAG.getContext(), Call);
01495   CCInfo.AnalyzeCallOperands(Outs,
01496                              CCAssignFnForNode(CallConv, /* Return*/ false,
01497                                                isVarArg));
01498 
01499   // Get a count of how many bytes are to be pushed on the stack.
01500   unsigned NumBytes = CCInfo.getNextStackOffset();
01501 
01502   // For tail calls, memory operands are available in our caller's stack.
01503   if (isSibCall)
01504     NumBytes = 0;
01505 
01506   // Adjust the stack pointer for the new arguments...
01507   // These operations are automatically eliminated by the prolog/epilog pass
01508   if (!isSibCall)
01509     Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(NumBytes, true),
01510                                  dl);
01511 
01512   SDValue StackPtr = DAG.getCopyFromReg(Chain, dl, ARM::SP, getPointerTy());
01513 
01514   RegsToPassVector RegsToPass;
01515   SmallVector<SDValue, 8> MemOpChains;
01516 
01517   // Walk the register/memloc assignments, inserting copies/loads.  In the case
01518   // of tail call optimization, arguments are handled later.
01519   for (unsigned i = 0, realArgIdx = 0, e = ArgLocs.size();
01520        i != e;
01521        ++i, ++realArgIdx) {
01522     CCValAssign &VA = ArgLocs[i];
01523     SDValue Arg = OutVals[realArgIdx];
01524     ISD::ArgFlagsTy Flags = Outs[realArgIdx].Flags;
01525     bool isByVal = Flags.isByVal();
01526 
01527     // Promote the value if needed.
01528     switch (VA.getLocInfo()) {
01529     default: llvm_unreachable("Unknown loc info!");
01530     case CCValAssign::Full: break;
01531     case CCValAssign::SExt:
01532       Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), Arg);
01533       break;
01534     case CCValAssign::ZExt:
01535       Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, VA.getLocVT(), Arg);
01536       break;
01537     case CCValAssign::AExt:
01538       Arg = DAG.getNode(ISD::ANY_EXTEND, dl, VA.getLocVT(), Arg);
01539       break;
01540     case CCValAssign::BCvt:
01541       Arg = DAG.getNode(ISD::BITCAST, dl, VA.getLocVT(), Arg);
01542       break;
01543     }
01544 
01545     // f64 and v2f64 might be passed in i32 pairs and must be split into pieces
01546     if (VA.needsCustom()) {
01547       if (VA.getLocVT() == MVT::v2f64) {
01548         SDValue Op0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg,
01549                                   DAG.getConstant(0, MVT::i32));
01550         SDValue Op1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg,
01551                                   DAG.getConstant(1, MVT::i32));
01552 
01553         PassF64ArgInRegs(dl, DAG, Chain, Op0, RegsToPass,
01554                          VA, ArgLocs[++i], StackPtr, MemOpChains, Flags);
01555 
01556         VA = ArgLocs[++i]; // skip ahead to next loc
01557         if (VA.isRegLoc()) {
01558           PassF64ArgInRegs(dl, DAG, Chain, Op1, RegsToPass,
01559                            VA, ArgLocs[++i], StackPtr, MemOpChains, Flags);
01560         } else {
01561           assert(VA.isMemLoc());
01562 
01563           MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, Op1,
01564                                                  dl, DAG, VA, Flags));
01565         }
01566       } else {
01567         PassF64ArgInRegs(dl, DAG, Chain, Arg, RegsToPass, VA, ArgLocs[++i],
01568                          StackPtr, MemOpChains, Flags);
01569       }
01570     } else if (VA.isRegLoc()) {
01571       if (realArgIdx == 0 && Flags.isReturned() && Outs[0].VT == MVT::i32) {
01572         assert(VA.getLocVT() == MVT::i32 &&
01573                "unexpected calling convention register assignment");
01574         assert(!Ins.empty() && Ins[0].VT == MVT::i32 &&
01575                "unexpected use of 'returned'");
01576         isThisReturn = true;
01577       }
01578       RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
01579     } else if (isByVal) {
01580       assert(VA.isMemLoc());
01581       unsigned offset = 0;
01582 
01583       // True if this byval aggregate will be split between registers
01584       // and memory.
01585       unsigned ByValArgsCount = CCInfo.getInRegsParamsCount();
01586       unsigned CurByValIdx = CCInfo.getInRegsParamsProcessed();
01587 
01588       if (CurByValIdx < ByValArgsCount) {
01589 
01590         unsigned RegBegin, RegEnd;
01591         CCInfo.getInRegsParamInfo(CurByValIdx, RegBegin, RegEnd);
01592 
01593         EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
01594         unsigned int i, j;
01595         for (i = 0, j = RegBegin; j < RegEnd; i++, j++) {
01596           SDValue Const = DAG.getConstant(4*i, MVT::i32);
01597           SDValue AddArg = DAG.getNode(ISD::ADD, dl, PtrVT, Arg, Const);
01598           SDValue Load = DAG.getLoad(PtrVT, dl, Chain, AddArg,
01599                                      MachinePointerInfo(),
01600                                      false, false, false,
01601                                      DAG.InferPtrAlignment(AddArg));
01602           MemOpChains.push_back(Load.getValue(1));
01603           RegsToPass.push_back(std::make_pair(j, Load));
01604         }
01605 
01606         // If parameter size outsides register area, "offset" value
01607         // helps us to calculate stack slot for remained part properly.
01608         offset = RegEnd - RegBegin;
01609 
01610         CCInfo.nextInRegsParam();
01611       }
01612 
01613       if (Flags.getByValSize() > 4*offset) {
01614         unsigned LocMemOffset = VA.getLocMemOffset();
01615         SDValue StkPtrOff = DAG.getIntPtrConstant(LocMemOffset);
01616         SDValue Dst = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr,
01617                                   StkPtrOff);
01618         SDValue SrcOffset = DAG.getIntPtrConstant(4*offset);
01619         SDValue Src = DAG.getNode(ISD::ADD, dl, getPointerTy(), Arg, SrcOffset);
01620         SDValue SizeNode = DAG.getConstant(Flags.getByValSize() - 4*offset,
01621                                            MVT::i32);
01622         SDValue AlignNode = DAG.getConstant(Flags.getByValAlign(), MVT::i32);
01623 
01624         SDVTList VTs = DAG.getVTList(MVT::Other, MVT::Glue);
01625         SDValue Ops[] = { Chain, Dst, Src, SizeNode, AlignNode};
01626         MemOpChains.push_back(DAG.getNode(ARMISD::COPY_STRUCT_BYVAL, dl, VTs,
01627                                           Ops));
01628       }
01629     } else if (!isSibCall) {
01630       assert(VA.isMemLoc());
01631 
01632       MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, Arg,
01633                                              dl, DAG, VA, Flags));
01634     }
01635   }
01636 
01637   if (!MemOpChains.empty())
01638     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains);
01639 
01640   // Build a sequence of copy-to-reg nodes chained together with token chain
01641   // and flag operands which copy the outgoing args into the appropriate regs.
01642   SDValue InFlag;
01643   // Tail call byval lowering might overwrite argument registers so in case of
01644   // tail call optimization the copies to registers are lowered later.
01645   if (!isTailCall)
01646     for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
01647       Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
01648                                RegsToPass[i].second, InFlag);
01649       InFlag = Chain.getValue(1);
01650     }
01651 
01652   // For tail calls lower the arguments to the 'real' stack slot.
01653   if (isTailCall) {
01654     // Force all the incoming stack arguments to be loaded from the stack
01655     // before any new outgoing arguments are stored to the stack, because the
01656     // outgoing stack slots may alias the incoming argument stack slots, and
01657     // the alias isn't otherwise explicit. This is slightly more conservative
01658     // than necessary, because it means that each store effectively depends
01659     // on every argument instead of just those arguments it would clobber.
01660 
01661     // Do not flag preceding copytoreg stuff together with the following stuff.
01662     InFlag = SDValue();
01663     for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
01664       Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
01665                                RegsToPass[i].second, InFlag);
01666       InFlag = Chain.getValue(1);
01667     }
01668     InFlag = SDValue();
01669   }
01670 
01671   // If the callee is a GlobalAddress/ExternalSymbol node (quite common, every
01672   // direct call is) turn it into a TargetGlobalAddress/TargetExternalSymbol
01673   // node so that legalize doesn't hack it.
01674   bool isDirect = false;
01675   bool isARMFunc = false;
01676   bool isLocalARMFunc = false;
01677   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
01678 
01679   if (EnableARMLongCalls) {
01680     assert((Subtarget->isTargetWindows() ||
01681             getTargetMachine().getRelocationModel() == Reloc::Static) &&
01682            "long-calls with non-static relocation model!");
01683     // Handle a global address or an external symbol. If it's not one of
01684     // those, the target's already in a register, so we don't need to do
01685     // anything extra.
01686     if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
01687       const GlobalValue *GV = G->getGlobal();
01688       // Create a constant pool entry for the callee address
01689       unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
01690       ARMConstantPoolValue *CPV =
01691         ARMConstantPoolConstant::Create(GV, ARMPCLabelIndex, ARMCP::CPValue, 0);
01692 
01693       // Get the address of the callee into a register
01694       SDValue CPAddr = DAG.getTargetConstantPool(CPV, getPointerTy(), 4);
01695       CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
01696       Callee = DAG.getLoad(getPointerTy(), dl,
01697                            DAG.getEntryNode(), CPAddr,
01698                            MachinePointerInfo::getConstantPool(),
01699                            false, false, false, 0);
01700     } else if (ExternalSymbolSDNode *S=dyn_cast<ExternalSymbolSDNode>(Callee)) {
01701       const char *Sym = S->getSymbol();
01702 
01703       // Create a constant pool entry for the callee address
01704       unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
01705       ARMConstantPoolValue *CPV =
01706         ARMConstantPoolSymbol::Create(*DAG.getContext(), Sym,
01707                                       ARMPCLabelIndex, 0);
01708       // Get the address of the callee into a register
01709       SDValue CPAddr = DAG.getTargetConstantPool(CPV, getPointerTy(), 4);
01710       CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
01711       Callee = DAG.getLoad(getPointerTy(), dl,
01712                            DAG.getEntryNode(), CPAddr,
01713                            MachinePointerInfo::getConstantPool(),
01714                            false, false, false, 0);
01715     }
01716   } else if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
01717     const GlobalValue *GV = G->getGlobal();
01718     isDirect = true;
01719     bool isExt = GV->isDeclaration() || GV->isWeakForLinker();
01720     bool isStub = (isExt && Subtarget->isTargetMachO()) &&
01721                    getTargetMachine().getRelocationModel() != Reloc::Static;
01722     isARMFunc = !Subtarget->isThumb() || (isStub && !Subtarget->isMClass());
01723     // ARM call to a local ARM function is predicable.
01724     isLocalARMFunc = !Subtarget->isThumb() && (!isExt || !ARMInterworking);
01725     // tBX takes a register source operand.
01726     if (isStub && Subtarget->isThumb1Only() && !Subtarget->hasV5TOps()) {
01727       assert(Subtarget->isTargetMachO() && "WrapperPIC use on non-MachO?");
01728       Callee = DAG.getNode(ARMISD::WrapperPIC, dl, getPointerTy(),
01729                            DAG.getTargetGlobalAddress(GV, dl, getPointerTy(),
01730                                                       0, ARMII::MO_NONLAZY));
01731       Callee = DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(), Callee,
01732                            MachinePointerInfo::getGOT(), false, false, true, 0);
01733     } else if (Subtarget->isTargetCOFF()) {
01734       assert(Subtarget->isTargetWindows() &&
01735              "Windows is the only supported COFF target");
01736       unsigned TargetFlags = GV->hasDLLImportStorageClass()
01737                                  ? ARMII::MO_DLLIMPORT
01738                                  : ARMII::MO_NO_FLAG;
01739       Callee = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(), /*Offset=*/0,
01740                                           TargetFlags);
01741       if (GV->hasDLLImportStorageClass())
01742         Callee = DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(),
01743                              DAG.getNode(ARMISD::Wrapper, dl, getPointerTy(),
01744                                          Callee), MachinePointerInfo::getGOT(),
01745                              false, false, false, 0);
01746     } else {
01747       // On ELF targets for PIC code, direct calls should go through the PLT
01748       unsigned OpFlags = 0;
01749       if (Subtarget->isTargetELF() &&
01750           getTargetMachine().getRelocationModel() == Reloc::PIC_)
01751         OpFlags = ARMII::MO_PLT;
01752       Callee = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(), 0, OpFlags);
01753     }
01754   } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
01755     isDirect = true;
01756     bool isStub = Subtarget->isTargetMachO() &&
01757                   getTargetMachine().getRelocationModel() != Reloc::Static;
01758     isARMFunc = !Subtarget->isThumb() || (isStub && !Subtarget->isMClass());
01759     // tBX takes a register source operand.
01760     const char *Sym = S->getSymbol();
01761     if (isARMFunc && Subtarget->isThumb1Only() && !Subtarget->hasV5TOps()) {
01762       unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
01763       ARMConstantPoolValue *CPV =
01764         ARMConstantPoolSymbol::Create(*DAG.getContext(), Sym,
01765                                       ARMPCLabelIndex, 4);
01766       SDValue CPAddr = DAG.getTargetConstantPool(CPV, getPointerTy(), 4);
01767       CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
01768       Callee = DAG.getLoad(getPointerTy(), dl,
01769                            DAG.getEntryNode(), CPAddr,
01770                            MachinePointerInfo::getConstantPool(),
01771                            false, false, false, 0);
01772       SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, MVT::i32);
01773       Callee = DAG.getNode(ARMISD::PIC_ADD, dl,
01774                            getPointerTy(), Callee, PICLabel);
01775     } else {
01776       unsigned OpFlags = 0;
01777       // On ELF targets for PIC code, direct calls should go through the PLT
01778       if (Subtarget->isTargetELF() &&
01779                   getTargetMachine().getRelocationModel() == Reloc::PIC_)
01780         OpFlags = ARMII::MO_PLT;
01781       Callee = DAG.getTargetExternalSymbol(Sym, getPointerTy(), OpFlags);
01782     }
01783   }
01784 
01785   // FIXME: handle tail calls differently.
01786   unsigned CallOpc;
01787   bool HasMinSizeAttr = MF.getFunction()->getAttributes().hasAttribute(
01788       AttributeSet::FunctionIndex, Attribute::MinSize);
01789   if (Subtarget->isThumb()) {
01790     if ((!isDirect || isARMFunc) && !Subtarget->hasV5TOps())
01791       CallOpc = ARMISD::CALL_NOLINK;
01792     else
01793       CallOpc = isARMFunc ? ARMISD::CALL : ARMISD::tCALL;
01794   } else {
01795     if (!isDirect && !Subtarget->hasV5TOps())
01796       CallOpc = ARMISD::CALL_NOLINK;
01797     else if (doesNotRet && isDirect && Subtarget->hasRAS() &&
01798                // Emit regular call when code size is the priority
01799                !HasMinSizeAttr)
01800       // "mov lr, pc; b _foo" to avoid confusing the RSP
01801       CallOpc = ARMISD::CALL_NOLINK;
01802     else
01803       CallOpc = isLocalARMFunc ? ARMISD::CALL_PRED : ARMISD::CALL;
01804   }
01805 
01806   std::vector<SDValue> Ops;
01807   Ops.push_back(Chain);
01808   Ops.push_back(Callee);
01809 
01810   // Add argument registers to the end of the list so that they are known live
01811   // into the call.
01812   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
01813     Ops.push_back(DAG.getRegister(RegsToPass[i].first,
01814                                   RegsToPass[i].second.getValueType()));
01815 
01816   // Add a register mask operand representing the call-preserved registers.
01817   if (!isTailCall) {
01818     const uint32_t *Mask;
01819     const TargetRegisterInfo *TRI =
01820         getTargetMachine().getSubtargetImpl()->getRegisterInfo();
01821     const ARMBaseRegisterInfo *ARI = static_cast<const ARMBaseRegisterInfo*>(TRI);
01822     if (isThisReturn) {
01823       // For 'this' returns, use the R0-preserving mask if applicable
01824       Mask = ARI->getThisReturnPreservedMask(CallConv);
01825       if (!Mask) {
01826         // Set isThisReturn to false if the calling convention is not one that
01827         // allows 'returned' to be modeled in this way, so LowerCallResult does
01828         // not try to pass 'this' straight through
01829         isThisReturn = false;
01830         Mask = ARI->getCallPreservedMask(CallConv);
01831       }
01832     } else
01833       Mask = ARI->getCallPreservedMask(CallConv);
01834 
01835     assert(Mask && "Missing call preserved mask for calling convention");
01836     Ops.push_back(DAG.getRegisterMask(Mask));
01837   }
01838 
01839   if (InFlag.getNode())
01840     Ops.push_back(InFlag);
01841 
01842   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
01843   if (isTailCall)
01844     return DAG.getNode(ARMISD::TC_RETURN, dl, NodeTys, Ops);
01845 
01846   // Returns a chain and a flag for retval copy to use.
01847   Chain = DAG.getNode(CallOpc, dl, NodeTys, Ops);
01848   InFlag = Chain.getValue(1);
01849 
01850   Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, true),
01851                              DAG.getIntPtrConstant(0, true), InFlag, dl);
01852   if (!Ins.empty())
01853     InFlag = Chain.getValue(1);
01854 
01855   // Handle result values, copying them out of physregs into vregs that we
01856   // return.
01857   return LowerCallResult(Chain, InFlag, CallConv, isVarArg, Ins, dl, DAG,
01858                          InVals, isThisReturn,
01859                          isThisReturn ? OutVals[0] : SDValue());
01860 }
01861 
01862 /// HandleByVal - Every parameter *after* a byval parameter is passed
01863 /// on the stack.  Remember the next parameter register to allocate,
01864 /// and then confiscate the rest of the parameter registers to insure
01865 /// this.
01866 void
01867 ARMTargetLowering::HandleByVal(
01868     CCState *State, unsigned &size, unsigned Align) const {
01869   unsigned reg = State->AllocateReg(GPRArgRegs, 4);
01870   assert((State->getCallOrPrologue() == Prologue ||
01871           State->getCallOrPrologue() == Call) &&
01872          "unhandled ParmContext");
01873 
01874   if ((ARM::R0 <= reg) && (reg <= ARM::R3)) {
01875     if (Subtarget->isAAPCS_ABI() && Align > 4) {
01876       unsigned AlignInRegs = Align / 4;
01877       unsigned Waste = (ARM::R4 - reg) % AlignInRegs;
01878       for (unsigned i = 0; i < Waste; ++i)
01879         reg = State->AllocateReg(GPRArgRegs, 4);
01880     }
01881     if (reg != 0) {
01882       unsigned excess = 4 * (ARM::R4 - reg);
01883 
01884       // Special case when NSAA != SP and parameter size greater than size of
01885       // all remained GPR regs. In that case we can't split parameter, we must
01886       // send it to stack. We also must set NCRN to R4, so waste all
01887       // remained registers.
01888       const unsigned NSAAOffset = State->getNextStackOffset();
01889       if (Subtarget->isAAPCS_ABI() && NSAAOffset != 0 && size > excess) {
01890         while (State->AllocateReg(GPRArgRegs, 4))
01891           ;
01892         return;
01893       }
01894 
01895       // First register for byval parameter is the first register that wasn't
01896       // allocated before this method call, so it would be "reg".
01897       // If parameter is small enough to be saved in range [reg, r4), then
01898       // the end (first after last) register would be reg + param-size-in-regs,
01899       // else parameter would be splitted between registers and stack,
01900       // end register would be r4 in this case.
01901       unsigned ByValRegBegin = reg;
01902       unsigned ByValRegEnd = (size < excess) ? reg + size/4 : (unsigned)ARM::R4;
01903       State->addInRegsParamInfo(ByValRegBegin, ByValRegEnd);
01904       // Note, first register is allocated in the beginning of function already,
01905       // allocate remained amount of registers we need.
01906       for (unsigned i = reg+1; i != ByValRegEnd; ++i)
01907         State->AllocateReg(GPRArgRegs, 4);
01908       // A byval parameter that is split between registers and memory needs its
01909       // size truncated here.
01910       // In the case where the entire structure fits in registers, we set the
01911       // size in memory to zero.
01912       if (size < excess)
01913         size = 0;
01914       else
01915         size -= excess;
01916     }
01917   }
01918 }
01919 
01920 /// MatchingStackOffset - Return true if the given stack call argument is
01921 /// already available in the same position (relatively) of the caller's
01922 /// incoming argument stack.
01923 static
01924 bool MatchingStackOffset(SDValue Arg, unsigned Offset, ISD::ArgFlagsTy Flags,
01925                          MachineFrameInfo *MFI, const MachineRegisterInfo *MRI,
01926                          const TargetInstrInfo *TII) {
01927   unsigned Bytes = Arg.getValueType().getSizeInBits() / 8;
01928   int FI = INT_MAX;
01929   if (Arg.getOpcode() == ISD::CopyFromReg) {
01930     unsigned VR = cast<RegisterSDNode>(Arg.getOperand(1))->getReg();
01931     if (!TargetRegisterInfo::isVirtualRegister(VR))
01932       return false;
01933     MachineInstr *Def = MRI->getVRegDef(VR);
01934     if (!Def)
01935       return false;
01936     if (!Flags.isByVal()) {
01937       if (!TII->isLoadFromStackSlot(Def, FI))
01938         return false;
01939     } else {
01940       return false;
01941     }
01942   } else if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Arg)) {
01943     if (Flags.isByVal())
01944       // ByVal argument is passed in as a pointer but it's now being
01945       // dereferenced. e.g.
01946       // define @foo(%struct.X* %A) {
01947       //   tail call @bar(%struct.X* byval %A)
01948       // }
01949       return false;
01950     SDValue Ptr = Ld->getBasePtr();
01951     FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr);
01952     if (!FINode)
01953       return false;
01954     FI = FINode->getIndex();
01955   } else
01956     return false;
01957 
01958   assert(FI != INT_MAX);
01959   if (!MFI->isFixedObjectIndex(FI))
01960     return false;
01961   return Offset == MFI->getObjectOffset(FI) && Bytes == MFI->getObjectSize(FI);
01962 }
01963 
01964 /// IsEligibleForTailCallOptimization - Check whether the call is eligible
01965 /// for tail call optimization. Targets which want to do tail call
01966 /// optimization should implement this function.
01967 bool
01968 ARMTargetLowering::IsEligibleForTailCallOptimization(SDValue Callee,
01969                                                      CallingConv::ID CalleeCC,
01970                                                      bool isVarArg,
01971                                                      bool isCalleeStructRet,
01972                                                      bool isCallerStructRet,
01973                                     const SmallVectorImpl<ISD::OutputArg> &Outs,
01974                                     const SmallVectorImpl<SDValue> &OutVals,
01975                                     const SmallVectorImpl<ISD::InputArg> &Ins,
01976                                                      SelectionDAG& DAG) const {
01977   const Function *CallerF = DAG.getMachineFunction().getFunction();
01978   CallingConv::ID CallerCC = CallerF->getCallingConv();
01979   bool CCMatch = CallerCC == CalleeCC;
01980 
01981   // Look for obvious safe cases to perform tail call optimization that do not
01982   // require ABI changes. This is what gcc calls sibcall.
01983 
01984   // Do not sibcall optimize vararg calls unless the call site is not passing
01985   // any arguments.
01986   if (isVarArg && !Outs.empty())
01987     return false;
01988 
01989   // Exception-handling functions need a special set of instructions to indicate
01990   // a return to the hardware. Tail-calling another function would probably
01991   // break this.
01992   if (CallerF->hasFnAttribute("interrupt"))
01993     return false;
01994 
01995   // Also avoid sibcall optimization if either caller or callee uses struct
01996   // return semantics.
01997   if (isCalleeStructRet || isCallerStructRet)
01998     return false;
01999 
02000   // FIXME: Completely disable sibcall for Thumb1 since Thumb1RegisterInfo::
02001   // emitEpilogue is not ready for them. Thumb tail calls also use t2B, as
02002   // the Thumb1 16-bit unconditional branch doesn't have sufficient relocation
02003   // support in the assembler and linker to be used. This would need to be
02004   // fixed to fully support tail calls in Thumb1.
02005   //
02006   // Doing this is tricky, since the LDM/POP instruction on Thumb doesn't take
02007   // LR.  This means if we need to reload LR, it takes an extra instructions,
02008   // which outweighs the value of the tail call; but here we don't know yet
02009   // whether LR is going to be used.  Probably the right approach is to
02010   // generate the tail call here and turn it back into CALL/RET in
02011   // emitEpilogue if LR is used.
02012 
02013   // Thumb1 PIC calls to external symbols use BX, so they can be tail calls,
02014   // but we need to make sure there are enough registers; the only valid
02015   // registers are the 4 used for parameters.  We don't currently do this
02016   // case.
02017   if (Subtarget->isThumb1Only())
02018     return false;
02019 
02020   // Externally-defined functions with weak linkage should not be
02021   // tail-called on ARM when the OS does not support dynamic
02022   // pre-emption of symbols, as the AAELF spec requires normal calls
02023   // to undefined weak functions to be replaced with a NOP or jump to the
02024   // next instruction. The behaviour of branch instructions in this
02025   // situation (as used for tail calls) is implementation-defined, so we
02026   // cannot rely on the linker replacing the tail call with a return.
02027   if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
02028     const GlobalValue *GV = G->getGlobal();
02029     if (GV->hasExternalWeakLinkage())
02030       return false;
02031   }
02032 
02033   // If the calling conventions do not match, then we'd better make sure the
02034   // results are returned in the same way as what the caller expects.
02035   if (!CCMatch) {
02036     SmallVector<CCValAssign, 16> RVLocs1;
02037     ARMCCState CCInfo1(CalleeCC, false, DAG.getMachineFunction(), RVLocs1,
02038                        *DAG.getContext(), Call);
02039     CCInfo1.AnalyzeCallResult(Ins, CCAssignFnForNode(CalleeCC, true, isVarArg));
02040 
02041     SmallVector<CCValAssign, 16> RVLocs2;
02042     ARMCCState CCInfo2(CallerCC, false, DAG.getMachineFunction(), RVLocs2,
02043                        *DAG.getContext(), Call);
02044     CCInfo2.AnalyzeCallResult(Ins, CCAssignFnForNode(CallerCC, true, isVarArg));
02045 
02046     if (RVLocs1.size() != RVLocs2.size())
02047       return false;
02048     for (unsigned i = 0, e = RVLocs1.size(); i != e; ++i) {
02049       if (RVLocs1[i].isRegLoc() != RVLocs2[i].isRegLoc())
02050         return false;
02051       if (RVLocs1[i].getLocInfo() != RVLocs2[i].getLocInfo())
02052         return false;
02053       if (RVLocs1[i].isRegLoc()) {
02054         if (RVLocs1[i].getLocReg() != RVLocs2[i].getLocReg())
02055           return false;
02056       } else {
02057         if (RVLocs1[i].getLocMemOffset() != RVLocs2[i].getLocMemOffset())
02058           return false;
02059       }
02060     }
02061   }
02062 
02063   // If Caller's vararg or byval argument has been split between registers and
02064   // stack, do not perform tail call, since part of the argument is in caller's
02065   // local frame.
02066   const ARMFunctionInfo *AFI_Caller = DAG.getMachineFunction().
02067                                       getInfo<ARMFunctionInfo>();
02068   if (AFI_Caller->getArgRegsSaveSize())
02069     return false;
02070 
02071   // If the callee takes no arguments then go on to check the results of the
02072   // call.
02073   if (!Outs.empty()) {
02074     // Check if stack adjustment is needed. For now, do not do this if any
02075     // argument is passed on the stack.
02076     SmallVector<CCValAssign, 16> ArgLocs;
02077     ARMCCState CCInfo(CalleeCC, isVarArg, DAG.getMachineFunction(), ArgLocs,
02078                       *DAG.getContext(), Call);
02079     CCInfo.AnalyzeCallOperands(Outs,
02080                                CCAssignFnForNode(CalleeCC, false, isVarArg));
02081     if (CCInfo.getNextStackOffset()) {
02082       MachineFunction &MF = DAG.getMachineFunction();
02083 
02084       // Check if the arguments are already laid out in the right way as
02085       // the caller's fixed stack objects.
02086       MachineFrameInfo *MFI = MF.getFrameInfo();
02087       const MachineRegisterInfo *MRI = &MF.getRegInfo();
02088       const TargetInstrInfo *TII =
02089           getTargetMachine().getSubtargetImpl()->getInstrInfo();
02090       for (unsigned i = 0, realArgIdx = 0, e = ArgLocs.size();
02091            i != e;
02092            ++i, ++realArgIdx) {
02093         CCValAssign &VA = ArgLocs[i];
02094         EVT RegVT = VA.getLocVT();
02095         SDValue Arg = OutVals[realArgIdx];
02096         ISD::ArgFlagsTy Flags = Outs[realArgIdx].Flags;
02097         if (VA.getLocInfo() == CCValAssign::Indirect)
02098           return false;
02099         if (VA.needsCustom()) {
02100           // f64 and vector types are split into multiple registers or
02101           // register/stack-slot combinations.  The types will not match
02102           // the registers; give up on memory f64 refs until we figure
02103           // out what to do about this.
02104           if (!VA.isRegLoc())
02105             return false;
02106           if (!ArgLocs[++i].isRegLoc())
02107             return false;
02108           if (RegVT == MVT::v2f64) {
02109             if (!ArgLocs[++i].isRegLoc())
02110               return false;
02111             if (!ArgLocs[++i].isRegLoc())
02112               return false;
02113           }
02114         } else if (!VA.isRegLoc()) {
02115           if (!MatchingStackOffset(Arg, VA.getLocMemOffset(), Flags,
02116                                    MFI, MRI, TII))
02117             return false;
02118         }
02119       }
02120     }
02121   }
02122 
02123   return true;
02124 }
02125 
02126 bool
02127 ARMTargetLowering::CanLowerReturn(CallingConv::ID CallConv,
02128                                   MachineFunction &MF, bool isVarArg,
02129                                   const SmallVectorImpl<ISD::OutputArg> &Outs,
02130                                   LLVMContext &Context) const {
02131   SmallVector<CCValAssign, 16> RVLocs;
02132   CCState CCInfo(CallConv, isVarArg, MF, RVLocs, Context);
02133   return CCInfo.CheckReturn(Outs, CCAssignFnForNode(CallConv, /*Return=*/true,
02134                                                     isVarArg));
02135 }
02136 
02137 static SDValue LowerInterruptReturn(SmallVectorImpl<SDValue> &RetOps,
02138                                     SDLoc DL, SelectionDAG &DAG) {
02139   const MachineFunction &MF = DAG.getMachineFunction();
02140   const Function *F = MF.getFunction();
02141 
02142   StringRef IntKind = F->getFnAttribute("interrupt").getValueAsString();
02143 
02144   // See ARM ARM v7 B1.8.3. On exception entry LR is set to a possibly offset
02145   // version of the "preferred return address". These offsets affect the return
02146   // instruction if this is a return from PL1 without hypervisor extensions.
02147   //    IRQ/FIQ: +4     "subs pc, lr, #4"
02148   //    SWI:     0      "subs pc, lr, #0"
02149   //    ABORT:   +4     "subs pc, lr, #4"
02150   //    UNDEF:   +4/+2  "subs pc, lr, #0"
02151   // UNDEF varies depending on where the exception came from ARM or Thumb
02152   // mode. Alongside GCC, we throw our hands up in disgust and pretend it's 0.
02153 
02154   int64_t LROffset;
02155   if (IntKind == "" || IntKind == "IRQ" || IntKind == "FIQ" ||
02156       IntKind == "ABORT")
02157     LROffset = 4;
02158   else if (IntKind == "SWI" || IntKind == "UNDEF")
02159     LROffset = 0;
02160   else
02161     report_fatal_error("Unsupported interrupt attribute. If present, value "
02162                        "must be one of: IRQ, FIQ, SWI, ABORT or UNDEF");
02163 
02164   RetOps.insert(RetOps.begin() + 1, DAG.getConstant(LROffset, MVT::i32, false));
02165 
02166   return DAG.getNode(ARMISD::INTRET_FLAG, DL, MVT::Other, RetOps);
02167 }
02168 
02169 SDValue
02170 ARMTargetLowering::LowerReturn(SDValue Chain,
02171                                CallingConv::ID CallConv, bool isVarArg,
02172                                const SmallVectorImpl<ISD::OutputArg> &Outs,
02173                                const SmallVectorImpl<SDValue> &OutVals,
02174                                SDLoc dl, SelectionDAG &DAG) const {
02175 
02176   // CCValAssign - represent the assignment of the return value to a location.
02177   SmallVector<CCValAssign, 16> RVLocs;
02178 
02179   // CCState - Info about the registers and stack slots.
02180   ARMCCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs,
02181                     *DAG.getContext(), Call);
02182 
02183   // Analyze outgoing return values.
02184   CCInfo.AnalyzeReturn(Outs, CCAssignFnForNode(CallConv, /* Return */ true,
02185                                                isVarArg));
02186 
02187   SDValue Flag;
02188   SmallVector<SDValue, 4> RetOps;
02189   RetOps.push_back(Chain); // Operand #0 = Chain (updated below)
02190   bool isLittleEndian = Subtarget->isLittle();
02191 
02192   MachineFunction &MF = DAG.getMachineFunction();
02193   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
02194   AFI->setReturnRegsCount(RVLocs.size());
02195 
02196   // Copy the result values into the output registers.
02197   for (unsigned i = 0, realRVLocIdx = 0;
02198        i != RVLocs.size();
02199        ++i, ++realRVLocIdx) {
02200     CCValAssign &VA = RVLocs[i];
02201     assert(VA.isRegLoc() && "Can only return in registers!");
02202 
02203     SDValue Arg = OutVals[realRVLocIdx];
02204 
02205     switch (VA.getLocInfo()) {
02206     default: llvm_unreachable("Unknown loc info!");
02207     case CCValAssign::Full: break;
02208     case CCValAssign::BCvt:
02209       Arg = DAG.getNode(ISD::BITCAST, dl, VA.getLocVT(), Arg);
02210       break;
02211     }
02212 
02213     if (VA.needsCustom()) {
02214       if (VA.getLocVT() == MVT::v2f64) {
02215         // Extract the first half and return it in two registers.
02216         SDValue Half = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg,
02217                                    DAG.getConstant(0, MVT::i32));
02218         SDValue HalfGPRs = DAG.getNode(ARMISD::VMOVRRD, dl,
02219                                        DAG.getVTList(MVT::i32, MVT::i32), Half);
02220 
02221         Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(),
02222                                  HalfGPRs.getValue(isLittleEndian ? 0 : 1),
02223                                  Flag);
02224         Flag = Chain.getValue(1);
02225         RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
02226         VA = RVLocs[++i]; // skip ahead to next loc
02227         Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(),
02228                                  HalfGPRs.getValue(isLittleEndian ? 1 : 0),
02229                                  Flag);
02230         Flag = Chain.getValue(1);
02231         RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
02232         VA = RVLocs[++i]; // skip ahead to next loc
02233 
02234         // Extract the 2nd half and fall through to handle it as an f64 value.
02235         Arg = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg,
02236                           DAG.getConstant(1, MVT::i32));
02237       }
02238       // Legalize ret f64 -> ret 2 x i32.  We always have fmrrd if f64 is
02239       // available.
02240       SDValue fmrrd = DAG.getNode(ARMISD::VMOVRRD, dl,
02241                                   DAG.getVTList(MVT::i32, MVT::i32), Arg);
02242       Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(),
02243                                fmrrd.getValue(isLittleEndian ? 0 : 1),
02244                                Flag);
02245       Flag = Chain.getValue(1);
02246       RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
02247       VA = RVLocs[++i]; // skip ahead to next loc
02248       Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(),
02249                                fmrrd.getValue(isLittleEndian ? 1 : 0),
02250                                Flag);
02251     } else
02252       Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), Arg, Flag);
02253 
02254     // Guarantee that all emitted copies are
02255     // stuck together, avoiding something bad.
02256     Flag = Chain.getValue(1);
02257     RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
02258   }
02259 
02260   // Update chain and glue.
02261   RetOps[0] = Chain;
02262   if (Flag.getNode())
02263     RetOps.push_back(Flag);
02264 
02265   // CPUs which aren't M-class use a special sequence to return from
02266   // exceptions (roughly, any instruction setting pc and cpsr simultaneously,
02267   // though we use "subs pc, lr, #N").
02268   //
02269   // M-class CPUs actually use a normal return sequence with a special
02270   // (hardware-provided) value in LR, so the normal code path works.
02271   if (DAG.getMachineFunction().getFunction()->hasFnAttribute("interrupt") &&
02272       !Subtarget->isMClass()) {
02273     if (Subtarget->isThumb1Only())
02274       report_fatal_error("interrupt attribute is not supported in Thumb1");
02275     return LowerInterruptReturn(RetOps, dl, DAG);
02276   }
02277 
02278   return DAG.getNode(ARMISD::RET_FLAG, dl, MVT::Other, RetOps);
02279 }
02280 
02281 bool ARMTargetLowering::isUsedByReturnOnly(SDNode *N, SDValue &Chain) const {
02282   if (N->getNumValues() != 1)
02283     return false;
02284   if (!N->hasNUsesOfValue(1, 0))
02285     return false;
02286 
02287   SDValue TCChain = Chain;
02288   SDNode *Copy = *N->use_begin();
02289   if (Copy->getOpcode() == ISD::CopyToReg) {
02290     // If the copy has a glue operand, we conservatively assume it isn't safe to
02291     // perform a tail call.
02292     if (Copy->getOperand(Copy->getNumOperands()-1).getValueType() == MVT::Glue)
02293       return false;
02294     TCChain = Copy->getOperand(0);
02295   } else if (Copy->getOpcode() == ARMISD::VMOVRRD) {
02296     SDNode *VMov = Copy;
02297     // f64 returned in a pair of GPRs.
02298     SmallPtrSet<SDNode*, 2> Copies;
02299     for (SDNode::use_iterator UI = VMov->use_begin(), UE = VMov->use_end();
02300          UI != UE; ++UI) {
02301       if (UI->getOpcode() != ISD::CopyToReg)
02302         return false;
02303       Copies.insert(*UI);
02304     }
02305     if (Copies.size() > 2)
02306       return false;
02307 
02308     for (SDNode::use_iterator UI = VMov->use_begin(), UE = VMov->use_end();
02309          UI != UE; ++UI) {
02310       SDValue UseChain = UI->getOperand(0);
02311       if (Copies.count(UseChain.getNode()))
02312         // Second CopyToReg
02313         Copy = *UI;
02314       else {
02315         // We are at the top of this chain.
02316         // If the copy has a glue operand, we conservatively assume it
02317         // isn't safe to perform a tail call.
02318         if (UI->getOperand(UI->getNumOperands()-1).getValueType() == MVT::Glue)
02319           return false;
02320         // First CopyToReg
02321         TCChain = UseChain;
02322       }
02323     }
02324   } else if (Copy->getOpcode() == ISD::BITCAST) {
02325     // f32 returned in a single GPR.
02326     if (!Copy->hasOneUse())
02327       return false;
02328     Copy = *Copy->use_begin();
02329     if (Copy->getOpcode() != ISD::CopyToReg || !Copy->hasNUsesOfValue(1, 0))
02330       return false;
02331     // If the copy has a glue operand, we conservatively assume it isn't safe to
02332     // perform a tail call.
02333     if (Copy->getOperand(Copy->getNumOperands()-1).getValueType() == MVT::Glue)
02334       return false;
02335     TCChain = Copy->getOperand(0);
02336   } else {
02337     return false;
02338   }
02339 
02340   bool HasRet = false;
02341   for (SDNode::use_iterator UI = Copy->use_begin(), UE = Copy->use_end();
02342        UI != UE; ++UI) {
02343     if (UI->getOpcode() != ARMISD::RET_FLAG &&
02344         UI->getOpcode() != ARMISD::INTRET_FLAG)
02345       return false;
02346     HasRet = true;
02347   }
02348 
02349   if (!HasRet)
02350     return false;
02351 
02352   Chain = TCChain;
02353   return true;
02354 }
02355 
02356 bool ARMTargetLowering::mayBeEmittedAsTailCall(CallInst *CI) const {
02357   if (!Subtarget->supportsTailCall())
02358     return false;
02359 
02360   if (!CI->isTailCall() || getTargetMachine().Options.DisableTailCalls)
02361     return false;
02362 
02363   return !Subtarget->isThumb1Only();
02364 }
02365 
02366 // ConstantPool, JumpTable, GlobalAddress, and ExternalSymbol are lowered as
02367 // their target counterpart wrapped in the ARMISD::Wrapper node. Suppose N is
02368 // one of the above mentioned nodes. It has to be wrapped because otherwise
02369 // Select(N) returns N. So the raw TargetGlobalAddress nodes, etc. can only
02370 // be used to form addressing mode. These wrapped nodes will be selected
02371 // into MOVi.
02372 static SDValue LowerConstantPool(SDValue Op, SelectionDAG &DAG) {
02373   EVT PtrVT = Op.getValueType();
02374   // FIXME there is no actual debug info here
02375   SDLoc dl(Op);
02376   ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
02377   SDValue Res;
02378   if (CP->isMachineConstantPoolEntry())
02379     Res = DAG.getTargetConstantPool(CP->getMachineCPVal(), PtrVT,
02380                                     CP->getAlignment());
02381   else
02382     Res = DAG.getTargetConstantPool(CP->getConstVal(), PtrVT,
02383                                     CP->getAlignment());
02384   return DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Res);
02385 }
02386 
02387 unsigned ARMTargetLowering::getJumpTableEncoding() const {
02388   return MachineJumpTableInfo::EK_Inline;
02389 }
02390 
02391 SDValue ARMTargetLowering::LowerBlockAddress(SDValue Op,
02392                                              SelectionDAG &DAG) const {
02393   MachineFunction &MF = DAG.getMachineFunction();
02394   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
02395   unsigned ARMPCLabelIndex = 0;
02396   SDLoc DL(Op);
02397   EVT PtrVT = getPointerTy();
02398   const BlockAddress *BA = cast<BlockAddressSDNode>(Op)->getBlockAddress();
02399   Reloc::Model RelocM = getTargetMachine().getRelocationModel();
02400   SDValue CPAddr;
02401   if (RelocM == Reloc::Static) {
02402     CPAddr = DAG.getTargetConstantPool(BA, PtrVT, 4);
02403   } else {
02404     unsigned PCAdj = Subtarget->isThumb() ? 4 : 8;
02405     ARMPCLabelIndex = AFI->createPICLabelUId();
02406     ARMConstantPoolValue *CPV =
02407       ARMConstantPoolConstant::Create(BA, ARMPCLabelIndex,
02408                                       ARMCP::CPBlockAddress, PCAdj);
02409     CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4);
02410   }
02411   CPAddr = DAG.getNode(ARMISD::Wrapper, DL, PtrVT, CPAddr);
02412   SDValue Result = DAG.getLoad(PtrVT, DL, DAG.getEntryNode(), CPAddr,
02413                                MachinePointerInfo::getConstantPool(),
02414                                false, false, false, 0);
02415   if (RelocM == Reloc::Static)
02416     return Result;
02417   SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, MVT::i32);
02418   return DAG.getNode(ARMISD::PIC_ADD, DL, PtrVT, Result, PICLabel);
02419 }
02420 
02421 // Lower ISD::GlobalTLSAddress using the "general dynamic" model
02422 SDValue
02423 ARMTargetLowering::LowerToTLSGeneralDynamicModel(GlobalAddressSDNode *GA,
02424                                                  SelectionDAG &DAG) const {
02425   SDLoc dl(GA);
02426   EVT PtrVT = getPointerTy();
02427   unsigned char PCAdj = Subtarget->isThumb() ? 4 : 8;
02428   MachineFunction &MF = DAG.getMachineFunction();
02429   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
02430   unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
02431   ARMConstantPoolValue *CPV =
02432     ARMConstantPoolConstant::Create(GA->getGlobal(), ARMPCLabelIndex,
02433                                     ARMCP::CPValue, PCAdj, ARMCP::TLSGD, true);
02434   SDValue Argument = DAG.getTargetConstantPool(CPV, PtrVT, 4);
02435   Argument = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Argument);
02436   Argument = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Argument,
02437                          MachinePointerInfo::getConstantPool(),
02438                          false, false, false, 0);
02439   SDValue Chain = Argument.getValue(1);
02440 
02441   SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, MVT::i32);
02442   Argument = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Argument, PICLabel);
02443 
02444   // call __tls_get_addr.
02445   ArgListTy Args;
02446   ArgListEntry Entry;
02447   Entry.Node = Argument;
02448   Entry.Ty = (Type *) Type::getInt32Ty(*DAG.getContext());
02449   Args.push_back(Entry);
02450 
02451   // FIXME: is there useful debug info available here?
02452   TargetLowering::CallLoweringInfo CLI(DAG);
02453   CLI.setDebugLoc(dl).setChain(Chain)
02454     .setCallee(CallingConv::C, Type::getInt32Ty(*DAG.getContext()),
02455                DAG.getExternalSymbol("__tls_get_addr", PtrVT), std::move(Args),
02456                0);
02457 
02458   std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI);
02459   return CallResult.first;
02460 }
02461 
02462 // Lower ISD::GlobalTLSAddress using the "initial exec" or
02463 // "local exec" model.
02464 SDValue
02465 ARMTargetLowering::LowerToTLSExecModels(GlobalAddressSDNode *GA,
02466                                         SelectionDAG &DAG,
02467                                         TLSModel::Model model) const {
02468   const GlobalValue *GV = GA->getGlobal();
02469   SDLoc dl(GA);
02470   SDValue Offset;
02471   SDValue Chain = DAG.getEntryNode();
02472   EVT PtrVT = getPointerTy();
02473   // Get the Thread Pointer
02474   SDValue ThreadPointer = DAG.getNode(ARMISD::THREAD_POINTER, dl, PtrVT);
02475 
02476   if (model == TLSModel::InitialExec) {
02477     MachineFunction &MF = DAG.getMachineFunction();
02478     ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
02479     unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
02480     // Initial exec model.
02481     unsigned char PCAdj = Subtarget->isThumb() ? 4 : 8;
02482     ARMConstantPoolValue *CPV =
02483       ARMConstantPoolConstant::Create(GA->getGlobal(), ARMPCLabelIndex,
02484                                       ARMCP::CPValue, PCAdj, ARMCP::GOTTPOFF,
02485                                       true);
02486     Offset = DAG.getTargetConstantPool(CPV, PtrVT, 4);
02487     Offset = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Offset);
02488     Offset = DAG.getLoad(PtrVT, dl, Chain, Offset,
02489                          MachinePointerInfo::getConstantPool(),
02490                          false, false, false, 0);
02491     Chain = Offset.getValue(1);
02492 
02493     SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, MVT::i32);
02494     Offset = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Offset, PICLabel);
02495 
02496     Offset = DAG.getLoad(PtrVT, dl, Chain, Offset,
02497                          MachinePointerInfo::getConstantPool(),
02498                          false, false, false, 0);
02499   } else {
02500     // local exec model
02501     assert(model == TLSModel::LocalExec);
02502     ARMConstantPoolValue *CPV =
02503       ARMConstantPoolConstant::Create(GV, ARMCP::TPOFF);
02504     Offset = DAG.getTargetConstantPool(CPV, PtrVT, 4);
02505     Offset = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Offset);
02506     Offset = DAG.getLoad(PtrVT, dl, Chain, Offset,
02507                          MachinePointerInfo::getConstantPool(),
02508                          false, false, false, 0);
02509   }
02510 
02511   // The address of the thread local variable is the add of the thread
02512   // pointer with the offset of the variable.
02513   return DAG.getNode(ISD::ADD, dl, PtrVT, ThreadPointer, Offset);
02514 }
02515 
02516 SDValue
02517 ARMTargetLowering::LowerGlobalTLSAddress(SDValue Op, SelectionDAG &DAG) const {
02518   // TODO: implement the "local dynamic" model
02519   assert(Subtarget->isTargetELF() &&
02520          "TLS not implemented for non-ELF targets");
02521   GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
02522 
02523   TLSModel::Model model = getTargetMachine().getTLSModel(GA->getGlobal());
02524 
02525   switch (model) {
02526     case TLSModel::GeneralDynamic:
02527     case TLSModel::LocalDynamic:
02528       return LowerToTLSGeneralDynamicModel(GA, DAG);
02529     case TLSModel::InitialExec:
02530     case TLSModel::LocalExec:
02531       return LowerToTLSExecModels(GA, DAG, model);
02532   }
02533   llvm_unreachable("bogus TLS model");
02534 }
02535 
02536 SDValue ARMTargetLowering::LowerGlobalAddressELF(SDValue Op,
02537                                                  SelectionDAG &DAG) const {
02538   EVT PtrVT = getPointerTy();
02539   SDLoc dl(Op);
02540   const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
02541   if (getTargetMachine().getRelocationModel() == Reloc::PIC_) {
02542     bool UseGOTOFF = GV->hasLocalLinkage() || GV->hasHiddenVisibility();
02543     ARMConstantPoolValue *CPV =
02544       ARMConstantPoolConstant::Create(GV,
02545                                       UseGOTOFF ? ARMCP::GOTOFF : ARMCP::GOT);
02546     SDValue CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4);
02547     CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
02548     SDValue Result = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(),
02549                                  CPAddr,
02550                                  MachinePointerInfo::getConstantPool(),
02551                                  false, false, false, 0);
02552     SDValue Chain = Result.getValue(1);
02553     SDValue GOT = DAG.getGLOBAL_OFFSET_TABLE(PtrVT);
02554     Result = DAG.getNode(ISD::ADD, dl, PtrVT, Result, GOT);
02555     if (!UseGOTOFF)
02556       Result = DAG.getLoad(PtrVT, dl, Chain, Result,
02557                            MachinePointerInfo::getGOT(),
02558                            false, false, false, 0);
02559     return Result;
02560   }
02561 
02562   // If we have T2 ops, we can materialize the address directly via movt/movw
02563   // pair. This is always cheaper.
02564   if (Subtarget->useMovt(DAG.getMachineFunction())) {
02565     ++NumMovwMovt;
02566     // FIXME: Once remat is capable of dealing with instructions with register
02567     // operands, expand this into two nodes.
02568     return DAG.getNode(ARMISD::Wrapper, dl, PtrVT,
02569                        DAG.getTargetGlobalAddress(GV, dl, PtrVT));
02570   } else {
02571     SDValue CPAddr = DAG.getTargetConstantPool(GV, PtrVT, 4);
02572     CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
02573     return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), CPAddr,
02574                        MachinePointerInfo::getConstantPool(),
02575                        false, false, false, 0);
02576   }
02577 }
02578 
02579 SDValue ARMTargetLowering::LowerGlobalAddressDarwin(SDValue Op,
02580                                                     SelectionDAG &DAG) const {
02581   EVT PtrVT = getPointerTy();
02582   SDLoc dl(Op);
02583   const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
02584   Reloc::Model RelocM = getTargetMachine().getRelocationModel();
02585 
02586   if (Subtarget->useMovt(DAG.getMachineFunction()))
02587     ++NumMovwMovt;
02588 
02589   // FIXME: Once remat is capable of dealing with instructions with register
02590   // operands, expand this into multiple nodes
02591   unsigned Wrapper =
02592       RelocM == Reloc::PIC_ ? ARMISD::WrapperPIC : ARMISD::Wrapper;
02593 
02594   SDValue G = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, ARMII::MO_NONLAZY);
02595   SDValue Result = DAG.getNode(Wrapper, dl, PtrVT, G);
02596 
02597   if (Subtarget->GVIsIndirectSymbol(GV, RelocM))
02598     Result = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Result,
02599                          MachinePointerInfo::getGOT(), false, false, false, 0);
02600   return Result;
02601 }
02602 
02603 SDValue ARMTargetLowering::LowerGlobalAddressWindows(SDValue Op,
02604                                                      SelectionDAG &DAG) const {
02605   assert(Subtarget->isTargetWindows() && "non-Windows COFF is not supported");
02606   assert(Subtarget->useMovt(DAG.getMachineFunction()) &&
02607          "Windows on ARM expects to use movw/movt");
02608 
02609   const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
02610   const ARMII::TOF TargetFlags =
02611     (GV->hasDLLImportStorageClass() ? ARMII::MO_DLLIMPORT : ARMII::MO_NO_FLAG);
02612   EVT PtrVT = getPointerTy();
02613   SDValue Result;
02614   SDLoc DL(Op);
02615 
02616   ++NumMovwMovt;
02617 
02618   // FIXME: Once remat is capable of dealing with instructions with register
02619   // operands, expand this into two nodes.
02620   Result = DAG.getNode(ARMISD::Wrapper, DL, PtrVT,
02621                        DAG.getTargetGlobalAddress(GV, DL, PtrVT, /*Offset=*/0,
02622                                                   TargetFlags));
02623   if (GV->hasDLLImportStorageClass())
02624     Result = DAG.getLoad(PtrVT, DL, DAG.getEntryNode(), Result,
02625                          MachinePointerInfo::getGOT(), false, false, false, 0);
02626   return Result;
02627 }
02628 
02629 SDValue ARMTargetLowering::LowerGLOBAL_OFFSET_TABLE(SDValue Op,
02630                                                     SelectionDAG &DAG) const {
02631   assert(Subtarget->isTargetELF() &&
02632          "GLOBAL OFFSET TABLE not implemented for non-ELF targets");
02633   MachineFunction &MF = DAG.getMachineFunction();
02634   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
02635   unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
02636   EVT PtrVT = getPointerTy();
02637   SDLoc dl(Op);
02638   unsigned PCAdj = Subtarget->isThumb() ? 4 : 8;
02639   ARMConstantPoolValue *CPV =
02640     ARMConstantPoolSymbol::Create(*DAG.getContext(), "_GLOBAL_OFFSET_TABLE_",
02641                                   ARMPCLabelIndex, PCAdj);
02642   SDValue CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4);
02643   CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
02644   SDValue Result = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), CPAddr,
02645                                MachinePointerInfo::getConstantPool(),
02646                                false, false, false, 0);
02647   SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, MVT::i32);
02648   return DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Result, PICLabel);
02649 }
02650 
02651 SDValue
02652 ARMTargetLowering::LowerEH_SJLJ_SETJMP(SDValue Op, SelectionDAG &DAG) const {
02653   SDLoc dl(Op);
02654   SDValue Val = DAG.getConstant(0, MVT::i32);
02655   return DAG.getNode(ARMISD::EH_SJLJ_SETJMP, dl,
02656                      DAG.getVTList(MVT::i32, MVT::Other), Op.getOperand(0),
02657                      Op.getOperand(1), Val);
02658 }
02659 
02660 SDValue
02661 ARMTargetLowering::LowerEH_SJLJ_LONGJMP(SDValue Op, SelectionDAG &DAG) const {
02662   SDLoc dl(Op);
02663   return DAG.getNode(ARMISD::EH_SJLJ_LONGJMP, dl, MVT::Other, Op.getOperand(0),
02664                      Op.getOperand(1), DAG.getConstant(0, MVT::i32));
02665 }
02666 
02667 SDValue
02668 ARMTargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op, SelectionDAG &DAG,
02669                                           const ARMSubtarget *Subtarget) const {
02670   unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
02671   SDLoc dl(Op);
02672   switch (IntNo) {
02673   default: return SDValue();    // Don't custom lower most intrinsics.
02674   case Intrinsic::arm_rbit: {
02675     assert(Op.getOperand(1).getValueType() == MVT::i32 &&
02676            "RBIT intrinsic must have i32 type!");
02677     return DAG.getNode(ARMISD::RBIT, dl, MVT::i32, Op.getOperand(1));
02678   }
02679   case Intrinsic::arm_thread_pointer: {
02680     EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
02681     return DAG.getNode(ARMISD::THREAD_POINTER, dl, PtrVT);
02682   }
02683   case Intrinsic::eh_sjlj_lsda: {
02684     MachineFunction &MF = DAG.getMachineFunction();
02685     ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
02686     unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
02687     EVT PtrVT = getPointerTy();
02688     Reloc::Model RelocM = getTargetMachine().getRelocationModel();
02689     SDValue CPAddr;
02690     unsigned PCAdj = (RelocM != Reloc::PIC_)
02691       ? 0 : (Subtarget->isThumb() ? 4 : 8);
02692     ARMConstantPoolValue *CPV =
02693       ARMConstantPoolConstant::Create(MF.getFunction(), ARMPCLabelIndex,
02694                                       ARMCP::CPLSDA, PCAdj);
02695     CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4);
02696     CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
02697     SDValue Result =
02698       DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), CPAddr,
02699                   MachinePointerInfo::getConstantPool(),
02700                   false, false, false, 0);
02701 
02702     if (RelocM == Reloc::PIC_) {
02703       SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, MVT::i32);
02704       Result = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Result, PICLabel);
02705     }
02706     return Result;
02707   }
02708   case Intrinsic::arm_neon_vmulls:
02709   case Intrinsic::arm_neon_vmullu: {
02710     unsigned NewOpc = (IntNo == Intrinsic::arm_neon_vmulls)
02711       ? ARMISD::VMULLs : ARMISD::VMULLu;
02712     return DAG.getNode(NewOpc, SDLoc(Op), Op.getValueType(),
02713                        Op.getOperand(1), Op.getOperand(2));
02714   }
02715   }
02716 }
02717 
02718 static SDValue LowerATOMIC_FENCE(SDValue Op, SelectionDAG &DAG,
02719                                  const ARMSubtarget *Subtarget) {
02720   // FIXME: handle "fence singlethread" more efficiently.
02721   SDLoc dl(Op);
02722   if (!Subtarget->hasDataBarrier()) {
02723     // Some ARMv6 cpus can support data barriers with an mcr instruction.
02724     // Thumb1 and pre-v6 ARM mode use a libcall instead and should never get
02725     // here.
02726     assert(Subtarget->hasV6Ops() && !Subtarget->isThumb() &&
02727            "Unexpected ISD::ATOMIC_FENCE encountered. Should be libcall!");
02728     return DAG.getNode(ARMISD::MEMBARRIER_MCR, dl, MVT::Other, Op.getOperand(0),
02729                        DAG.getConstant(0, MVT::i32));
02730   }
02731 
02732   ConstantSDNode *OrdN = cast<ConstantSDNode>(Op.getOperand(1));
02733   AtomicOrdering Ord = static_cast<AtomicOrdering>(OrdN->getZExtValue());
02734   ARM_MB::MemBOpt Domain = ARM_MB::ISH;
02735   if (Subtarget->isMClass()) {
02736     // Only a full system barrier exists in the M-class architectures.
02737     Domain = ARM_MB::SY;
02738   } else if (Subtarget->isSwift() && Ord == Release) {
02739     // Swift happens to implement ISHST barriers in a way that's compatible with
02740     // Release semantics but weaker than ISH so we'd be fools not to use
02741     // it. Beware: other processors probably don't!
02742     Domain = ARM_MB::ISHST;
02743   }
02744 
02745   return DAG.getNode(ISD::INTRINSIC_VOID, dl, MVT::Other, Op.getOperand(0),
02746                      DAG.getConstant(Intrinsic::arm_dmb, MVT::i32),
02747                      DAG.getConstant(Domain, MVT::i32));
02748 }
02749 
02750 static SDValue LowerPREFETCH(SDValue Op, SelectionDAG &DAG,
02751                              const ARMSubtarget *Subtarget) {
02752   // ARM pre v5TE and Thumb1 does not have preload instructions.
02753   if (!(Subtarget->isThumb2() ||
02754         (!Subtarget->isThumb1Only() && Subtarget->hasV5TEOps())))
02755     // Just preserve the chain.
02756     return Op.getOperand(0);
02757 
02758   SDLoc dl(Op);
02759   unsigned isRead = ~cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue() & 1;
02760   if (!isRead &&
02761       (!Subtarget->hasV7Ops() || !Subtarget->hasMPExtension()))
02762     // ARMv7 with MP extension has PLDW.
02763     return Op.getOperand(0);
02764 
02765   unsigned isData = cast<ConstantSDNode>(Op.getOperand(4))->getZExtValue();
02766   if (Subtarget->isThumb()) {
02767     // Invert the bits.
02768     isRead = ~isRead & 1;
02769     isData = ~isData & 1;
02770   }
02771 
02772   return DAG.getNode(ARMISD::PRELOAD, dl, MVT::Other, Op.getOperand(0),
02773                      Op.getOperand(1), DAG.getConstant(isRead, MVT::i32),
02774                      DAG.getConstant(isData, MVT::i32));
02775 }
02776 
02777 static SDValue LowerVASTART(SDValue Op, SelectionDAG &DAG) {
02778   MachineFunction &MF = DAG.getMachineFunction();
02779   ARMFunctionInfo *FuncInfo = MF.getInfo<ARMFunctionInfo>();
02780 
02781   // vastart just stores the address of the VarArgsFrameIndex slot into the
02782   // memory location argument.
02783   SDLoc dl(Op);
02784   EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
02785   SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT);
02786   const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
02787   return DAG.getStore(Op.getOperand(0), dl, FR, Op.getOperand(1),
02788                       MachinePointerInfo(SV), false, false, 0);
02789 }
02790 
02791 SDValue
02792 ARMTargetLowering::GetF64FormalArgument(CCValAssign &VA, CCValAssign &NextVA,
02793                                         SDValue &Root, SelectionDAG &DAG,
02794                                         SDLoc dl) const {
02795   MachineFunction &MF = DAG.getMachineFunction();
02796   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
02797 
02798   const TargetRegisterClass *RC;
02799   if (AFI->isThumb1OnlyFunction())
02800     RC = &ARM::tGPRRegClass;
02801   else
02802     RC = &ARM::GPRRegClass;
02803 
02804   // Transform the arguments stored in physical registers into virtual ones.
02805   unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
02806   SDValue ArgValue = DAG.getCopyFromReg(Root, dl, Reg, MVT::i32);
02807 
02808   SDValue ArgValue2;
02809   if (NextVA.isMemLoc()) {
02810     MachineFrameInfo *MFI = MF.getFrameInfo();
02811     int FI = MFI->CreateFixedObject(4, NextVA.getLocMemOffset(), true);
02812 
02813     // Create load node to retrieve arguments from the stack.
02814     SDValue FIN = DAG.getFrameIndex(FI, getPointerTy());
02815     ArgValue2 = DAG.getLoad(MVT::i32, dl, Root, FIN,
02816                             MachinePointerInfo::getFixedStack(FI),
02817                             false, false, false, 0);
02818   } else {
02819     Reg = MF.addLiveIn(NextVA.getLocReg(), RC);
02820     ArgValue2 = DAG.getCopyFromReg(Root, dl, Reg, MVT::i32);
02821   }
02822   if (!Subtarget->isLittle())
02823     std::swap (ArgValue, ArgValue2);
02824   return DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, ArgValue, ArgValue2);
02825 }
02826 
02827 void
02828 ARMTargetLowering::computeRegArea(CCState &CCInfo, MachineFunction &MF,
02829                                   unsigned InRegsParamRecordIdx,
02830                                   unsigned ArgSize,
02831                                   unsigned &ArgRegsSize,
02832                                   unsigned &ArgRegsSaveSize)
02833   const {
02834   unsigned NumGPRs;
02835   if (InRegsParamRecordIdx < CCInfo.getInRegsParamsCount()) {
02836     unsigned RBegin, REnd;
02837     CCInfo.getInRegsParamInfo(InRegsParamRecordIdx, RBegin, REnd);
02838     NumGPRs = REnd - RBegin;
02839   } else {
02840     unsigned int firstUnalloced;
02841     firstUnalloced = CCInfo.getFirstUnallocated(GPRArgRegs,
02842                                                 sizeof(GPRArgRegs) /
02843                                                 sizeof(GPRArgRegs[0]));
02844     NumGPRs = (firstUnalloced <= 3) ? (4 - firstUnalloced) : 0;
02845   }
02846 
02847   unsigned Align = MF.getTarget()
02848                        .getSubtargetImpl()
02849                        ->getFrameLowering()
02850                        ->getStackAlignment();
02851   ArgRegsSize = NumGPRs * 4;
02852 
02853   // If parameter is split between stack and GPRs...
02854   if (NumGPRs && Align > 4 &&
02855       (ArgRegsSize < ArgSize ||
02856         InRegsParamRecordIdx >= CCInfo.getInRegsParamsCount())) {
02857     // Add padding for part of param recovered from GPRs.  For example,
02858     // if Align == 8, its last byte must be at address K*8 - 1.
02859     // We need to do it, since remained (stack) part of parameter has
02860     // stack alignment, and we need to "attach" "GPRs head" without gaps
02861     // to it:
02862     // Stack:
02863     // |---- 8 bytes block ----| |---- 8 bytes block ----| |---- 8 bytes...
02864     // [ [padding] [GPRs head] ] [        Tail passed via stack       ....
02865     //
02866     ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
02867     unsigned Padding =
02868         OffsetToAlignment(ArgRegsSize + AFI->getArgRegsSaveSize(), Align);
02869     ArgRegsSaveSize = ArgRegsSize + Padding;
02870   } else
02871     // We don't need to extend regs save size for byval parameters if they
02872     // are passed via GPRs only.
02873     ArgRegsSaveSize = ArgRegsSize;
02874 }
02875 
02876 // The remaining GPRs hold either the beginning of variable-argument
02877 // data, or the beginning of an aggregate passed by value (usually
02878 // byval).  Either way, we allocate stack slots adjacent to the data
02879 // provided by our caller, and store the unallocated registers there.
02880 // If this is a variadic function, the va_list pointer will begin with
02881 // these values; otherwise, this reassembles a (byval) structure that
02882 // was split between registers and memory.
02883 // Return: The frame index registers were stored into.
02884 int
02885 ARMTargetLowering::StoreByValRegs(CCState &CCInfo, SelectionDAG &DAG,
02886                                   SDLoc dl, SDValue &Chain,
02887                                   const Value *OrigArg,
02888                                   unsigned InRegsParamRecordIdx,
02889                                   unsigned OffsetFromOrigArg,
02890                                   unsigned ArgOffset,
02891                                   unsigned ArgSize,
02892                                   bool ForceMutable,
02893                                   unsigned ByValStoreOffset,
02894                                   unsigned TotalArgRegsSaveSize) const {
02895 
02896   // Currently, two use-cases possible:
02897   // Case #1. Non-var-args function, and we meet first byval parameter.
02898   //          Setup first unallocated register as first byval register;
02899   //          eat all remained registers
02900   //          (these two actions are performed by HandleByVal method).
02901   //          Then, here, we initialize stack frame with
02902   //          "store-reg" instructions.
02903   // Case #2. Var-args function, that doesn't contain byval parameters.
02904   //          The same: eat all remained unallocated registers,
02905   //          initialize stack frame.
02906 
02907   MachineFunction &MF = DAG.getMachineFunction();
02908   MachineFrameInfo *MFI = MF.getFrameInfo();
02909   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
02910   unsigned firstRegToSaveIndex, lastRegToSaveIndex;
02911   unsigned RBegin, REnd;
02912   if (InRegsParamRecordIdx < CCInfo.getInRegsParamsCount()) {
02913     CCInfo.getInRegsParamInfo(InRegsParamRecordIdx, RBegin, REnd);
02914     firstRegToSaveIndex = RBegin - ARM::R0;
02915     lastRegToSaveIndex = REnd - ARM::R0;
02916   } else {
02917     firstRegToSaveIndex = CCInfo.getFirstUnallocated
02918       (GPRArgRegs, array_lengthof(GPRArgRegs));
02919     lastRegToSaveIndex = 4;
02920   }
02921 
02922   unsigned ArgRegsSize, ArgRegsSaveSize;
02923   computeRegArea(CCInfo, MF, InRegsParamRecordIdx, ArgSize,
02924                  ArgRegsSize, ArgRegsSaveSize);
02925 
02926   // Store any by-val regs to their spots on the stack so that they may be
02927   // loaded by deferencing the result of formal parameter pointer or va_next.
02928   // Note: once stack area for byval/varargs registers
02929   // was initialized, it can't be initialized again.
02930   if (ArgRegsSaveSize) {
02931     unsigned Padding = ArgRegsSaveSize - ArgRegsSize;
02932 
02933     if (Padding) {
02934       assert(AFI->getStoredByValParamsPadding() == 0 &&
02935              "The only parameter may be padded.");
02936       AFI->setStoredByValParamsPadding(Padding);
02937     }
02938 
02939     int FrameIndex = MFI->CreateFixedObject(ArgRegsSaveSize,
02940                                             Padding +
02941                                               ByValStoreOffset -
02942                                               (int64_t)TotalArgRegsSaveSize,
02943                                             false);
02944     SDValue FIN = DAG.getFrameIndex(FrameIndex, getPointerTy());
02945     if (Padding) {
02946        MFI->CreateFixedObject(Padding,
02947                               ArgOffset + ByValStoreOffset -
02948                                 (int64_t)ArgRegsSaveSize,
02949                               false);
02950     }
02951 
02952     SmallVector<SDValue, 4> MemOps;
02953     for (unsigned i = 0; firstRegToSaveIndex < lastRegToSaveIndex;
02954          ++firstRegToSaveIndex, ++i) {
02955       const TargetRegisterClass *RC;
02956       if (AFI->isThumb1OnlyFunction())
02957         RC = &ARM::tGPRRegClass;
02958       else
02959         RC = &ARM::GPRRegClass;
02960 
02961       unsigned VReg = MF.addLiveIn(GPRArgRegs[firstRegToSaveIndex], RC);
02962       SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i32);
02963       SDValue Store =
02964         DAG.getStore(Val.getValue(1), dl, Val, FIN,
02965                      MachinePointerInfo(OrigArg, OffsetFromOrigArg + 4*i),
02966                      false, false, 0);
02967       MemOps.push_back(Store);
02968       FIN = DAG.getNode(ISD::ADD, dl, getPointerTy(), FIN,
02969                         DAG.getConstant(4, getPointerTy()));
02970     }
02971 
02972     AFI->setArgRegsSaveSize(ArgRegsSaveSize + AFI->getArgRegsSaveSize());
02973 
02974     if (!MemOps.empty())
02975       Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOps);
02976     return FrameIndex;
02977   } else {
02978     if (ArgSize == 0) {
02979       // We cannot allocate a zero-byte object for the first variadic argument,
02980       // so just make up a size.
02981       ArgSize = 4;
02982     }
02983     // This will point to the next argument passed via stack.
02984     return MFI->CreateFixedObject(
02985       ArgSize, ArgOffset, !ForceMutable);
02986   }
02987 }
02988 
02989 // Setup stack frame, the va_list pointer will start from.
02990 void
02991 ARMTargetLowering::VarArgStyleRegisters(CCState &CCInfo, SelectionDAG &DAG,
02992                                         SDLoc dl, SDValue &Chain,
02993                                         unsigned ArgOffset,
02994                                         unsigned TotalArgRegsSaveSize,
02995                                         bool ForceMutable) const {
02996   MachineFunction &MF = DAG.getMachineFunction();
02997   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
02998 
02999   // Try to store any remaining integer argument regs
03000   // to their spots on the stack so that they may be loaded by deferencing
03001   // the result of va_next.
03002   // If there is no regs to be stored, just point address after last
03003   // argument passed via stack.
03004   int FrameIndex =
03005     StoreByValRegs(CCInfo, DAG, dl, Chain, nullptr,
03006                    CCInfo.getInRegsParamsCount(), 0, ArgOffset, 0, ForceMutable,
03007                    0, TotalArgRegsSaveSize);
03008 
03009   AFI->setVarArgsFrameIndex(FrameIndex);
03010 }
03011 
03012 SDValue
03013 ARMTargetLowering::LowerFormalArguments(SDValue Chain,
03014                                         CallingConv::ID CallConv, bool isVarArg,
03015                                         const SmallVectorImpl<ISD::InputArg>
03016                                           &Ins,
03017                                         SDLoc dl, SelectionDAG &DAG,
03018                                         SmallVectorImpl<SDValue> &InVals)
03019                                           const {
03020   MachineFunction &MF = DAG.getMachineFunction();
03021   MachineFrameInfo *MFI = MF.getFrameInfo();
03022 
03023   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
03024 
03025   // Assign locations to all of the incoming arguments.
03026   SmallVector<CCValAssign, 16> ArgLocs;
03027   ARMCCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), ArgLocs,
03028                     *DAG.getContext(), Prologue);
03029   CCInfo.AnalyzeFormalArguments(Ins,
03030                                 CCAssignFnForNode(CallConv, /* Return*/ false,
03031                                                   isVarArg));
03032 
03033   SmallVector<SDValue, 16> ArgValues;
03034   int lastInsIndex = -1;
03035   SDValue ArgValue;
03036   Function::const_arg_iterator CurOrigArg = MF.getFunction()->arg_begin();
03037   unsigned CurArgIdx = 0;
03038 
03039   // Initially ArgRegsSaveSize is zero.
03040   // Then we increase this value each time we meet byval parameter.
03041   // We also increase this value in case of varargs function.
03042   AFI->setArgRegsSaveSize(0);
03043 
03044   unsigned ByValStoreOffset = 0;
03045   unsigned TotalArgRegsSaveSize = 0;
03046   unsigned ArgRegsSaveSizeMaxAlign = 4;
03047 
03048   // Calculate the amount of stack space that we need to allocate to store
03049   // byval and variadic arguments that are passed in registers.
03050   // We need to know this before we allocate the first byval or variadic
03051   // argument, as they will be allocated a stack slot below the CFA (Canonical
03052   // Frame Address, the stack pointer at entry to the function).
03053   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
03054     CCValAssign &VA = ArgLocs[i];
03055     if (VA.isMemLoc()) {
03056       int index = VA.getValNo();
03057       if (index != lastInsIndex) {
03058         ISD::ArgFlagsTy Flags = Ins[index].Flags;
03059         if (Flags.isByVal()) {
03060           unsigned ExtraArgRegsSize;
03061           unsigned ExtraArgRegsSaveSize;
03062           computeRegArea(CCInfo, MF, CCInfo.getInRegsParamsProcessed(),
03063                          Flags.getByValSize(),
03064                          ExtraArgRegsSize, ExtraArgRegsSaveSize);
03065 
03066           TotalArgRegsSaveSize += ExtraArgRegsSaveSize;
03067           if (Flags.getByValAlign() > ArgRegsSaveSizeMaxAlign)
03068               ArgRegsSaveSizeMaxAlign = Flags.getByValAlign();
03069           CCInfo.nextInRegsParam();
03070         }
03071         lastInsIndex = index;
03072       }
03073     }
03074   }
03075   CCInfo.rewindByValRegsInfo();
03076   lastInsIndex = -1;
03077   if (isVarArg && MFI->hasVAStart()) {
03078     unsigned ExtraArgRegsSize;
03079     unsigned ExtraArgRegsSaveSize;
03080     computeRegArea(CCInfo, MF, CCInfo.getInRegsParamsCount(), 0,
03081                    ExtraArgRegsSize, ExtraArgRegsSaveSize);
03082     TotalArgRegsSaveSize += ExtraArgRegsSaveSize;
03083   }
03084   // If the arg regs save area contains N-byte aligned values, the
03085   // bottom of it must be at least N-byte aligned.
03086   TotalArgRegsSaveSize = RoundUpToAlignment(TotalArgRegsSaveSize, ArgRegsSaveSizeMaxAlign);
03087   TotalArgRegsSaveSize = std::min(TotalArgRegsSaveSize, 16U);
03088 
03089   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
03090     CCValAssign &VA = ArgLocs[i];
03091     std::advance(CurOrigArg, Ins[VA.getValNo()].OrigArgIndex - CurArgIdx);
03092     CurArgIdx = Ins[VA.getValNo()].OrigArgIndex;
03093     // Arguments stored in registers.
03094     if (VA.isRegLoc()) {
03095       EVT RegVT = VA.getLocVT();
03096 
03097       if (VA.needsCustom()) {
03098         // f64 and vector types are split up into multiple registers or
03099         // combinations of registers and stack slots.
03100         if (VA.getLocVT() == MVT::v2f64) {
03101           SDValue ArgValue1 = GetF64FormalArgument(VA, ArgLocs[++i],
03102                                                    Chain, DAG, dl);
03103           VA = ArgLocs[++i]; // skip ahead to next loc
03104           SDValue ArgValue2;
03105           if (VA.isMemLoc()) {
03106             int FI = MFI->CreateFixedObject(8, VA.getLocMemOffset(), true);
03107             SDValue FIN = DAG.getFrameIndex(FI, getPointerTy());
03108             ArgValue2 = DAG.getLoad(MVT::f64, dl, Chain, FIN,
03109                                     MachinePointerInfo::getFixedStack(FI),
03110                                     false, false, false, 0);
03111           } else {
03112             ArgValue2 = GetF64FormalArgument(VA, ArgLocs[++i],
03113                                              Chain, DAG, dl);
03114           }
03115           ArgValue = DAG.getNode(ISD::UNDEF, dl, MVT::v2f64);
03116           ArgValue = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64,
03117                                  ArgValue, ArgValue1, DAG.getIntPtrConstant(0));
03118           ArgValue = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64,
03119                                  ArgValue, ArgValue2, DAG.getIntPtrConstant(1));
03120         } else
03121           ArgValue = GetF64FormalArgument(VA, ArgLocs[++i], Chain, DAG, dl);
03122 
03123       } else {
03124         const TargetRegisterClass *RC;
03125 
03126         if (RegVT == MVT::f32)
03127           RC = &ARM::SPRRegClass;
03128         else if (RegVT == MVT::f64)
03129           RC = &ARM::DPRRegClass;
03130         else if (RegVT == MVT::v2f64)
03131           RC = &ARM::QPRRegClass;
03132         else if (RegVT == MVT::i32)
03133           RC = AFI->isThumb1OnlyFunction() ? &ARM::tGPRRegClass
03134                                            : &ARM::GPRRegClass;
03135         else
03136           llvm_unreachable("RegVT not supported by FORMAL_ARGUMENTS Lowering");
03137 
03138         // Transform the arguments in physical registers into virtual ones.
03139         unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
03140         ArgValue = DAG.getCopyFromReg(Chain, dl, Reg, RegVT);
03141       }
03142 
03143       // If this is an 8 or 16-bit value, it is really passed promoted
03144       // to 32 bits.  Insert an assert[sz]ext to capture this, then
03145       // truncate to the right size.
03146       switch (VA.getLocInfo()) {
03147       default: llvm_unreachable("Unknown loc info!");
03148       case CCValAssign::Full: break;
03149       case CCValAssign::BCvt:
03150         ArgValue = DAG.getNode(ISD::BITCAST, dl, VA.getValVT(), ArgValue);
03151         break;
03152       case CCValAssign::SExt:
03153         ArgValue = DAG.getNode(ISD::AssertSext, dl, RegVT, ArgValue,
03154                                DAG.getValueType(VA.getValVT()));
03155         ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue);
03156         break;
03157       case CCValAssign::ZExt:
03158         ArgValue = DAG.getNode(ISD::AssertZext, dl, RegVT, ArgValue,
03159                                DAG.getValueType(VA.getValVT()));
03160         ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue);
03161         break;
03162       }
03163 
03164       InVals.push_back(ArgValue);
03165 
03166     } else { // VA.isRegLoc()
03167 
03168       // sanity check
03169       assert(VA.isMemLoc());
03170       assert(VA.getValVT() != MVT::i64 && "i64 should already be lowered");
03171 
03172       int index = ArgLocs[i].getValNo();
03173 
03174       // Some Ins[] entries become multiple ArgLoc[] entries.
03175       // Process them only once.
03176       if (index != lastInsIndex)
03177         {
03178           ISD::ArgFlagsTy Flags = Ins[index].Flags;
03179           // FIXME: For now, all byval parameter objects are marked mutable.
03180           // This can be changed with more analysis.
03181           // In case of tail call optimization mark all arguments mutable.
03182           // Since they could be overwritten by lowering of arguments in case of
03183           // a tail call.
03184           if (Flags.isByVal()) {
03185             unsigned CurByValIndex = CCInfo.getInRegsParamsProcessed();
03186 
03187             ByValStoreOffset = RoundUpToAlignment(ByValStoreOffset, Flags.getByValAlign());
03188             int FrameIndex = StoreByValRegs(
03189                 CCInfo, DAG, dl, Chain, CurOrigArg,
03190                 CurByValIndex,
03191                 Ins[VA.getValNo()].PartOffset,
03192                 VA.getLocMemOffset(),
03193                 Flags.getByValSize(),
03194                 true /*force mutable frames*/,
03195                 ByValStoreOffset,
03196                 TotalArgRegsSaveSize);
03197             ByValStoreOffset += Flags.getByValSize();
03198             ByValStoreOffset = std::min(ByValStoreOffset, 16U);
03199             InVals.push_back(DAG.getFrameIndex(FrameIndex, getPointerTy()));
03200             CCInfo.nextInRegsParam();
03201           } else {
03202             unsigned FIOffset = VA.getLocMemOffset();
03203             int FI = MFI->CreateFixedObject(VA.getLocVT().getSizeInBits()/8,
03204                                             FIOffset, true);
03205 
03206             // Create load nodes to retrieve arguments from the stack.
03207             SDValue FIN = DAG.getFrameIndex(FI, getPointerTy());
03208             InVals.push_back(DAG.getLoad(VA.getValVT(), dl, Chain, FIN,
03209                                          MachinePointerInfo::getFixedStack(FI),
03210                                          false, false, false, 0));
03211           }
03212           lastInsIndex = index;
03213         }
03214     }
03215   }
03216 
03217   // varargs
03218   if (isVarArg && MFI->hasVAStart())
03219     VarArgStyleRegisters(CCInfo, DAG, dl, Chain,
03220                          CCInfo.getNextStackOffset(),
03221                          TotalArgRegsSaveSize);
03222 
03223   AFI->setArgumentStackSize(CCInfo.getNextStackOffset());
03224 
03225   return Chain;
03226 }
03227 
03228 /// isFloatingPointZero - Return true if this is +0.0.
03229 static bool isFloatingPointZero(SDValue Op) {
03230   if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Op))
03231     return CFP->getValueAPF().isPosZero();
03232   else if (ISD::isEXTLoad(Op.getNode()) || ISD::isNON_EXTLoad(Op.getNode())) {
03233     // Maybe this has already been legalized into the constant pool?
03234     if (Op.getOperand(1).getOpcode() == ARMISD::Wrapper) {
03235       SDValue WrapperOp = Op.getOperand(1).getOperand(0);
03236       if (ConstantPoolSDNode *CP = dyn_cast<ConstantPoolSDNode>(WrapperOp))
03237         if (const ConstantFP *CFP = dyn_cast<ConstantFP>(CP->getConstVal()))
03238           return CFP->getValueAPF().isPosZero();
03239     }
03240   } else if (Op->getOpcode() == ISD::BITCAST &&
03241              Op->getValueType(0) == MVT::f64) {
03242     // Handle (ISD::BITCAST (ARMISD::VMOVIMM (ISD::TargetConstant 0)) MVT::f64)
03243     // created by LowerConstantFP().
03244     SDValue BitcastOp = Op->getOperand(0);
03245     if (BitcastOp->getOpcode() == ARMISD::VMOVIMM) {
03246       SDValue MoveOp = BitcastOp->getOperand(0);
03247       if (MoveOp->getOpcode() == ISD::TargetConstant &&
03248           cast<ConstantSDNode>(MoveOp)->getZExtValue() == 0) {
03249         return true;
03250       }
03251     }
03252   }
03253   return false;
03254 }
03255 
03256 /// Returns appropriate ARM CMP (cmp) and corresponding condition code for
03257 /// the given operands.
03258 SDValue
03259 ARMTargetLowering::getARMCmp(SDValue LHS, SDValue RHS, ISD::CondCode CC,
03260                              SDValue &ARMcc, SelectionDAG &DAG,
03261                              SDLoc dl) const {
03262   if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS.getNode())) {
03263     unsigned C = RHSC->getZExtValue();
03264     if (!isLegalICmpImmediate(C)) {
03265       // Constant does not fit, try adjusting it by one?
03266       switch (CC) {
03267       default: break;
03268       case ISD::SETLT:
03269       case ISD::SETGE:
03270         if (C != 0x80000000 && isLegalICmpImmediate(C-1)) {
03271           CC = (CC == ISD::SETLT) ? ISD::SETLE : ISD::SETGT;
03272           RHS = DAG.getConstant(C-1, MVT::i32);
03273         }
03274         break;
03275       case ISD::SETULT:
03276       case ISD::SETUGE:
03277         if (C != 0 && isLegalICmpImmediate(C-1)) {
03278           CC = (CC == ISD::SETULT) ? ISD::SETULE : ISD::SETUGT;
03279           RHS = DAG.getConstant(C-1, MVT::i32);
03280         }
03281         break;
03282       case ISD::SETLE:
03283       case ISD::SETGT:
03284         if (C != 0x7fffffff && isLegalICmpImmediate(C+1)) {
03285           CC = (CC == ISD::SETLE) ? ISD::SETLT : ISD::SETGE;
03286           RHS = DAG.getConstant(C+1, MVT::i32);
03287         }
03288         break;
03289       case ISD::SETULE:
03290       case ISD::SETUGT:
03291         if (C != 0xffffffff && isLegalICmpImmediate(C+1)) {
03292           CC = (CC == ISD::SETULE) ? ISD::SETULT : ISD::SETUGE;
03293           RHS = DAG.getConstant(C+1, MVT::i32);
03294         }
03295         break;
03296       }
03297     }
03298   }
03299 
03300   ARMCC::CondCodes CondCode = IntCCToARMCC(CC);
03301   ARMISD::NodeType CompareType;
03302   switch (CondCode) {
03303   default:
03304     CompareType = ARMISD::CMP;
03305     break;
03306   case ARMCC::EQ:
03307   case ARMCC::NE:
03308     // Uses only Z Flag
03309     CompareType = ARMISD::CMPZ;
03310     break;
03311   }
03312   ARMcc = DAG.getConstant(CondCode, MVT::i32);
03313   return DAG.getNode(CompareType, dl, MVT::Glue, LHS, RHS);
03314 }
03315 
03316 /// Returns a appropriate VFP CMP (fcmp{s|d}+fmstat) for the given operands.
03317 SDValue
03318 ARMTargetLowering::getVFPCmp(SDValue LHS, SDValue RHS, SelectionDAG &DAG,
03319                              SDLoc dl) const {
03320   assert(!Subtarget->isFPOnlySP() || RHS.getValueType() != MVT::f64);
03321   SDValue Cmp;
03322   if (!isFloatingPointZero(RHS))
03323     Cmp = DAG.getNode(ARMISD::CMPFP, dl, MVT::Glue, LHS, RHS);
03324   else
03325     Cmp = DAG.getNode(ARMISD::CMPFPw0, dl, MVT::Glue, LHS);
03326   return DAG.getNode(ARMISD::FMSTAT, dl, MVT::Glue, Cmp);
03327 }
03328 
03329 /// duplicateCmp - Glue values can have only one use, so this function
03330 /// duplicates a comparison node.
03331 SDValue
03332 ARMTargetLowering::duplicateCmp(SDValue Cmp, SelectionDAG &DAG) const {
03333   unsigned Opc = Cmp.getOpcode();
03334   SDLoc DL(Cmp);
03335   if (Opc == ARMISD::CMP || Opc == ARMISD::CMPZ)
03336     return DAG.getNode(Opc, DL, MVT::Glue, Cmp.getOperand(0),Cmp.getOperand(1));
03337 
03338   assert(Opc == ARMISD::FMSTAT && "unexpected comparison operation");
03339   Cmp = Cmp.getOperand(0);
03340   Opc = Cmp.getOpcode();
03341   if (Opc == ARMISD::CMPFP)
03342     Cmp = DAG.getNode(Opc, DL, MVT::Glue, Cmp.getOperand(0),Cmp.getOperand(1));
03343   else {
03344     assert(Opc == ARMISD::CMPFPw0 && "unexpected operand of FMSTAT");
03345     Cmp = DAG.getNode(Opc, DL, MVT::Glue, Cmp.getOperand(0));
03346   }
03347   return DAG.getNode(ARMISD::FMSTAT, DL, MVT::Glue, Cmp);
03348 }
03349 
03350 std::pair<SDValue, SDValue>
03351 ARMTargetLowering::getARMXALUOOp(SDValue Op, SelectionDAG &DAG,
03352                                  SDValue &ARMcc) const {
03353   assert(Op.getValueType() == MVT::i32 &&  "Unsupported value type");
03354 
03355   SDValue Value, OverflowCmp;
03356   SDValue LHS = Op.getOperand(0);
03357   SDValue RHS = Op.getOperand(1);
03358 
03359 
03360   // FIXME: We are currently always generating CMPs because we don't support
03361   // generating CMN through the backend. This is not as good as the natural
03362   // CMP case because it causes a register dependency and cannot be folded
03363   // later.
03364 
03365   switch (Op.getOpcode()) {
03366   default:
03367     llvm_unreachable("Unknown overflow instruction!");
03368   case ISD::SADDO:
03369     ARMcc = DAG.getConstant(ARMCC::VC, MVT::i32);
03370     Value = DAG.getNode(ISD::ADD, SDLoc(Op), Op.getValueType(), LHS, RHS);
03371     OverflowCmp = DAG.getNode(ARMISD::CMP, SDLoc(Op), MVT::Glue, Value, LHS);
03372     break;
03373   case ISD::UADDO:
03374     ARMcc = DAG.getConstant(ARMCC::HS, MVT::i32);
03375     Value = DAG.getNode(ISD::ADD, SDLoc(Op), Op.getValueType(), LHS, RHS);
03376     OverflowCmp = DAG.getNode(ARMISD::CMP, SDLoc(Op), MVT::Glue, Value, LHS);
03377     break;
03378   case ISD::SSUBO:
03379     ARMcc = DAG.getConstant(ARMCC::VC, MVT::i32);
03380     Value = DAG.getNode(ISD::SUB, SDLoc(Op), Op.getValueType(), LHS, RHS);
03381     OverflowCmp = DAG.getNode(ARMISD::CMP, SDLoc(Op), MVT::Glue, LHS, RHS);
03382     break;
03383   case ISD::USUBO:
03384     ARMcc = DAG.getConstant(ARMCC::HS, MVT::i32);
03385     Value = DAG.getNode(ISD::SUB, SDLoc(Op), Op.getValueType(), LHS, RHS);
03386     OverflowCmp = DAG.getNode(ARMISD::CMP, SDLoc(Op), MVT::Glue, LHS, RHS);
03387     break;
03388   } // switch (...)
03389 
03390   return std::make_pair(Value, OverflowCmp);
03391 }
03392 
03393 
03394 SDValue
03395 ARMTargetLowering::LowerXALUO(SDValue Op, SelectionDAG &DAG) const {
03396   // Let legalize expand this if it isn't a legal type yet.
03397   if (!DAG.getTargetLoweringInfo().isTypeLegal(Op.getValueType()))
03398     return SDValue();
03399 
03400   SDValue Value, OverflowCmp;
03401   SDValue ARMcc;
03402   std::tie(Value, OverflowCmp) = getARMXALUOOp(Op, DAG, ARMcc);
03403   SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
03404   // We use 0 and 1 as false and true values.
03405   SDValue TVal = DAG.getConstant(1, MVT::i32);
03406   SDValue FVal = DAG.getConstant(0, MVT::i32);
03407   EVT VT = Op.getValueType();
03408 
03409   SDValue Overflow = DAG.getNode(ARMISD::CMOV, SDLoc(Op), VT, TVal, FVal,
03410                                  ARMcc, CCR, OverflowCmp);
03411 
03412   SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
03413   return DAG.getNode(ISD::MERGE_VALUES, SDLoc(Op), VTs, Value, Overflow);
03414 }
03415 
03416 
03417 SDValue ARMTargetLowering::LowerSELECT(SDValue Op, SelectionDAG &DAG) const {
03418   SDValue Cond = Op.getOperand(0);
03419   SDValue SelectTrue = Op.getOperand(1);
03420   SDValue SelectFalse = Op.getOperand(2);
03421   SDLoc dl(Op);
03422   unsigned Opc = Cond.getOpcode();
03423 
03424   if (Cond.getResNo() == 1 &&
03425       (Opc == ISD::SADDO || Opc == ISD::UADDO || Opc == ISD::SSUBO ||
03426        Opc == ISD::USUBO)) {
03427     if (!DAG.getTargetLoweringInfo().isTypeLegal(Cond->getValueType(0)))
03428       return SDValue();
03429 
03430     SDValue Value, OverflowCmp;
03431     SDValue ARMcc;
03432     std::tie(Value, OverflowCmp) = getARMXALUOOp(Cond, DAG, ARMcc);
03433     SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
03434     EVT VT = Op.getValueType();
03435 
03436     return getCMOV(SDLoc(Op), VT, SelectTrue, SelectFalse, ARMcc, CCR,
03437                    OverflowCmp, DAG);
03438   }
03439 
03440   // Convert:
03441   //
03442   //   (select (cmov 1, 0, cond), t, f) -> (cmov t, f, cond)
03443   //   (select (cmov 0, 1, cond), t, f) -> (cmov f, t, cond)
03444   //
03445   if (Cond.getOpcode() == ARMISD::CMOV && Cond.hasOneUse()) {
03446     const ConstantSDNode *CMOVTrue =
03447       dyn_cast<ConstantSDNode>(Cond.getOperand(0));
03448     const ConstantSDNode *CMOVFalse =
03449       dyn_cast<ConstantSDNode>(Cond.getOperand(1));
03450 
03451     if (CMOVTrue && CMOVFalse) {
03452       unsigned CMOVTrueVal = CMOVTrue->getZExtValue();
03453       unsigned CMOVFalseVal = CMOVFalse->getZExtValue();
03454 
03455       SDValue True;
03456       SDValue False;
03457       if (CMOVTrueVal == 1 && CMOVFalseVal == 0) {
03458         True = SelectTrue;
03459         False = SelectFalse;
03460       } else if (CMOVTrueVal == 0 && CMOVFalseVal == 1) {
03461         True = SelectFalse;
03462         False = SelectTrue;
03463       }
03464 
03465       if (True.getNode() && False.getNode()) {
03466         EVT VT = Op.getValueType();
03467         SDValue ARMcc = Cond.getOperand(2);
03468         SDValue CCR = Cond.getOperand(3);
03469         SDValue Cmp = duplicateCmp(Cond.getOperand(4), DAG);
03470         assert(True.getValueType() == VT);
03471         return getCMOV(dl, VT, True, False, ARMcc, CCR, Cmp, DAG);
03472       }
03473     }
03474   }
03475 
03476   // ARM's BooleanContents value is UndefinedBooleanContent. Mask out the
03477   // undefined bits before doing a full-word comparison with zero.
03478   Cond = DAG.getNode(ISD::AND, dl, Cond.getValueType(), Cond,
03479                      DAG.getConstant(1, Cond.getValueType()));
03480 
03481   return DAG.getSelectCC(dl, Cond,
03482                          DAG.getConstant(0, Cond.getValueType()),
03483                          SelectTrue, SelectFalse, ISD::SETNE);
03484 }
03485 
03486 static ISD::CondCode getInverseCCForVSEL(ISD::CondCode CC) {
03487   if (CC == ISD::SETNE)
03488     return ISD::SETEQ;
03489   return ISD::getSetCCInverse(CC, true);
03490 }
03491 
03492 static void checkVSELConstraints(ISD::CondCode CC, ARMCC::CondCodes &CondCode,
03493                                  bool &swpCmpOps, bool &swpVselOps) {
03494   // Start by selecting the GE condition code for opcodes that return true for
03495   // 'equality'
03496   if (CC == ISD::SETUGE || CC == ISD::SETOGE || CC == ISD::SETOLE ||
03497       CC == ISD::SETULE)
03498     CondCode = ARMCC::GE;
03499 
03500   // and GT for opcodes that return false for 'equality'.
03501   else if (CC == ISD::SETUGT || CC == ISD::SETOGT || CC == ISD::SETOLT ||
03502            CC == ISD::SETULT)
03503     CondCode = ARMCC::GT;
03504 
03505   // Since we are constrained to GE/GT, if the opcode contains 'less', we need
03506   // to swap the compare operands.
03507   if (CC == ISD::SETOLE || CC == ISD::SETULE || CC == ISD::SETOLT ||
03508       CC == ISD::SETULT)
03509     swpCmpOps = true;
03510 
03511   // Both GT and GE are ordered comparisons, and return false for 'unordered'.
03512   // If we have an unordered opcode, we need to swap the operands to the VSEL
03513   // instruction (effectively negating the condition).
03514   //
03515   // This also has the effect of swapping which one of 'less' or 'greater'
03516   // returns true, so we also swap the compare operands. It also switches
03517   // whether we return true for 'equality', so we compensate by picking the
03518   // opposite condition code to our original choice.
03519   if (CC == ISD::SETULE || CC == ISD::SETULT || CC == ISD::SETUGE ||
03520       CC == ISD::SETUGT) {
03521     swpCmpOps = !swpCmpOps;
03522     swpVselOps = !swpVselOps;
03523     CondCode = CondCode == ARMCC::GT ? ARMCC::GE : ARMCC::GT;
03524   }
03525 
03526   // 'ordered' is 'anything but unordered', so use the VS condition code and
03527   // swap the VSEL operands.
03528   if (CC == ISD::SETO) {
03529     CondCode = ARMCC::VS;
03530     swpVselOps = true;
03531   }
03532 
03533   // 'unordered or not equal' is 'anything but equal', so use the EQ condition
03534   // code and swap the VSEL operands.
03535   if (CC == ISD::SETUNE) {
03536     CondCode = ARMCC::EQ;
03537     swpVselOps = true;
03538   }
03539 }
03540 
03541 SDValue ARMTargetLowering::getCMOV(SDLoc dl, EVT VT, SDValue FalseVal,
03542                                    SDValue TrueVal, SDValue ARMcc, SDValue CCR,
03543                                    SDValue Cmp, SelectionDAG &DAG) const {
03544   if (Subtarget->isFPOnlySP() && VT == MVT::f64) {
03545     FalseVal = DAG.getNode(ARMISD::VMOVRRD, dl,
03546                            DAG.getVTList(MVT::i32, MVT::i32), FalseVal);
03547     TrueVal = DAG.getNode(ARMISD::VMOVRRD, dl,
03548                           DAG.getVTList(MVT::i32, MVT::i32), TrueVal);
03549 
03550     SDValue TrueLow = TrueVal.getValue(0);
03551     SDValue TrueHigh = TrueVal.getValue(1);
03552     SDValue FalseLow = FalseVal.getValue(0);
03553     SDValue FalseHigh = FalseVal.getValue(1);
03554 
03555     SDValue Low = DAG.getNode(ARMISD::CMOV, dl, MVT::i32, FalseLow, TrueLow,
03556                               ARMcc, CCR, Cmp);
03557     SDValue High = DAG.getNode(ARMISD::CMOV, dl, MVT::i32, FalseHigh, TrueHigh,
03558                                ARMcc, CCR, duplicateCmp(Cmp, DAG));
03559 
03560     return DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Low, High);
03561   } else {
03562     return DAG.getNode(ARMISD::CMOV, dl, VT, FalseVal, TrueVal, ARMcc, CCR,
03563                        Cmp);
03564   }
03565 }
03566 
03567 SDValue ARMTargetLowering::LowerSELECT_CC(SDValue Op, SelectionDAG &DAG) const {
03568   EVT VT = Op.getValueType();
03569   SDValue LHS = Op.getOperand(0);
03570   SDValue RHS = Op.getOperand(1);
03571   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(4))->get();
03572   SDValue TrueVal = Op.getOperand(2);
03573   SDValue FalseVal = Op.getOperand(3);
03574   SDLoc dl(Op);
03575 
03576   if (Subtarget->isFPOnlySP() && LHS.getValueType() == MVT::f64) {
03577     DAG.getTargetLoweringInfo().softenSetCCOperands(DAG, MVT::f64, LHS, RHS, CC,
03578                                                     dl);
03579 
03580     // If softenSetCCOperands only returned one value, we should compare it to
03581     // zero.
03582     if (!RHS.getNode()) {
03583       RHS = DAG.getConstant(0, LHS.getValueType());
03584       CC = ISD::SETNE;
03585     }
03586   }
03587 
03588   if (LHS.getValueType() == MVT::i32) {
03589     // Try to generate VSEL on ARMv8.
03590     // The VSEL instruction can't use all the usual ARM condition
03591     // codes: it only has two bits to select the condition code, so it's
03592     // constrained to use only GE, GT, VS and EQ.
03593     //
03594     // To implement all the various ISD::SETXXX opcodes, we sometimes need to
03595     // swap the operands of the previous compare instruction (effectively
03596     // inverting the compare condition, swapping 'less' and 'greater') and
03597     // sometimes need to swap the operands to the VSEL (which inverts the
03598     // condition in the sense of firing whenever the previous condition didn't)
03599     if (getSubtarget()->hasFPARMv8() && (TrueVal.getValueType() == MVT::f32 ||
03600                                       TrueVal.getValueType() == MVT::f64)) {
03601       ARMCC::CondCodes CondCode = IntCCToARMCC(CC);
03602       if (CondCode == ARMCC::LT || CondCode == ARMCC::LE ||
03603           CondCode == ARMCC::VC || CondCode == ARMCC::NE) {
03604         CC = getInverseCCForVSEL(CC);
03605         std::swap(TrueVal, FalseVal);
03606       }
03607     }
03608 
03609     SDValue ARMcc;
03610     SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
03611     SDValue Cmp = getARMCmp(LHS, RHS, CC, ARMcc, DAG, dl);
03612     return getCMOV(dl, VT, FalseVal, TrueVal, ARMcc, CCR, Cmp, DAG);
03613   }
03614 
03615   ARMCC::CondCodes CondCode, CondCode2;
03616   FPCCToARMCC(CC, CondCode, CondCode2);
03617 
03618   // Try to generate VSEL on ARMv8.
03619   if (getSubtarget()->hasFPARMv8() && (TrueVal.getValueType() == MVT::f32 ||
03620                                     TrueVal.getValueType() == MVT::f64)) {
03621     // We can select VMAXNM/VMINNM from a compare followed by a select with the
03622     // same operands, as follows:
03623     //   c = fcmp [ogt, olt, ugt, ult] a, b
03624     //   select c, a, b
03625     // We only do this in unsafe-fp-math, because signed zeros and NaNs are
03626     // handled differently than the original code sequence.
03627     if (getTargetMachine().Options.UnsafeFPMath) {
03628       if (LHS == TrueVal && RHS == FalseVal) {
03629         if (CC == ISD::SETOGT || CC == ISD::SETUGT)
03630           return DAG.getNode(ARMISD::VMAXNM, dl, VT, TrueVal, FalseVal);
03631         if (CC == ISD::SETOLT || CC == ISD::SETULT)
03632           return DAG.getNode(ARMISD::VMINNM, dl, VT, TrueVal, FalseVal);
03633       } else if (LHS == FalseVal && RHS == TrueVal) {
03634         if (CC == ISD::SETOLT || CC == ISD::SETULT)
03635           return DAG.getNode(ARMISD::VMAXNM, dl, VT, TrueVal, FalseVal);
03636         if (CC == ISD::SETOGT || CC == ISD::SETUGT)
03637           return DAG.getNode(ARMISD::VMINNM, dl, VT, TrueVal, FalseVal);
03638       }
03639     }
03640 
03641     bool swpCmpOps = false;
03642     bool swpVselOps = false;
03643     checkVSELConstraints(CC, CondCode, swpCmpOps, swpVselOps);
03644 
03645     if (CondCode == ARMCC::GT || CondCode == ARMCC::GE ||
03646         CondCode == ARMCC::VS || CondCode == ARMCC::EQ) {
03647       if (swpCmpOps)
03648         std::swap(LHS, RHS);
03649       if (swpVselOps)
03650         std::swap(TrueVal, FalseVal);
03651     }
03652   }
03653 
03654   SDValue ARMcc = DAG.getConstant(CondCode, MVT::i32);
03655   SDValue Cmp = getVFPCmp(LHS, RHS, DAG, dl);
03656   SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
03657   SDValue Result = getCMOV(dl, VT, FalseVal, TrueVal, ARMcc, CCR, Cmp, DAG);
03658   if (CondCode2 != ARMCC::AL) {
03659     SDValue ARMcc2 = DAG.getConstant(CondCode2, MVT::i32);
03660     // FIXME: Needs another CMP because flag can have but one use.
03661     SDValue Cmp2 = getVFPCmp(LHS, RHS, DAG, dl);
03662     Result = getCMOV(dl, VT, Result, TrueVal, ARMcc2, CCR, Cmp2, DAG);
03663   }
03664   return Result;
03665 }
03666 
03667 /// canChangeToInt - Given the fp compare operand, return true if it is suitable
03668 /// to morph to an integer compare sequence.
03669 static bool canChangeToInt(SDValue Op, bool &SeenZero,
03670                            const ARMSubtarget *Subtarget) {
03671   SDNode *N = Op.getNode();
03672   if (!N->hasOneUse())
03673     // Otherwise it requires moving the value from fp to integer registers.
03674     return false;
03675   if (!N->getNumValues())
03676     return false;
03677   EVT VT = Op.getValueType();
03678   if (VT != MVT::f32 && !Subtarget->isFPBrccSlow())
03679     // f32 case is generally profitable. f64 case only makes sense when vcmpe +
03680     // vmrs are very slow, e.g. cortex-a8.
03681     return false;
03682 
03683   if (isFloatingPointZero(Op)) {
03684     SeenZero = true;
03685     return true;
03686   }
03687   return ISD::isNormalLoad(N);
03688 }
03689 
03690 static SDValue bitcastf32Toi32(SDValue Op, SelectionDAG &DAG) {
03691   if (isFloatingPointZero(Op))
03692     return DAG.getConstant(0, MVT::i32);
03693 
03694   if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Op))
03695     return DAG.getLoad(MVT::i32, SDLoc(Op),
03696                        Ld->getChain(), Ld->getBasePtr(), Ld->getPointerInfo(),
03697                        Ld->isVolatile(), Ld->isNonTemporal(),
03698                        Ld->isInvariant(), Ld->getAlignment());
03699 
03700   llvm_unreachable("Unknown VFP cmp argument!");
03701 }
03702 
03703 static void expandf64Toi32(SDValue Op, SelectionDAG &DAG,
03704                            SDValue &RetVal1, SDValue &RetVal2) {
03705   if (isFloatingPointZero(Op)) {
03706     RetVal1 = DAG.getConstant(0, MVT::i32);
03707     RetVal2 = DAG.getConstant(0, MVT::i32);
03708     return;
03709   }
03710 
03711   if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Op)) {
03712     SDValue Ptr = Ld->getBasePtr();
03713     RetVal1 = DAG.getLoad(MVT::i32, SDLoc(Op),
03714                           Ld->getChain(), Ptr,
03715                           Ld->getPointerInfo(),
03716                           Ld->isVolatile(), Ld->isNonTemporal(),
03717                           Ld->isInvariant(), Ld->getAlignment());
03718 
03719     EVT PtrType = Ptr.getValueType();
03720     unsigned NewAlign = MinAlign(Ld->getAlignment(), 4);
03721     SDValue NewPtr = DAG.getNode(ISD::ADD, SDLoc(Op),
03722                                  PtrType, Ptr, DAG.getConstant(4, PtrType));
03723     RetVal2 = DAG.getLoad(MVT::i32, SDLoc(Op),
03724                           Ld->getChain(), NewPtr,
03725                           Ld->getPointerInfo().getWithOffset(4),
03726                           Ld->isVolatile(), Ld->isNonTemporal(),
03727                           Ld->isInvariant(), NewAlign);
03728     return;
03729   }
03730 
03731   llvm_unreachable("Unknown VFP cmp argument!");
03732 }
03733 
03734 /// OptimizeVFPBrcond - With -enable-unsafe-fp-math, it's legal to optimize some
03735 /// f32 and even f64 comparisons to integer ones.
03736 SDValue
03737 ARMTargetLowering::OptimizeVFPBrcond(SDValue Op, SelectionDAG &DAG) const {
03738   SDValue Chain = Op.getOperand(0);
03739   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(1))->get();
03740   SDValue LHS = Op.getOperand(2);
03741   SDValue RHS = Op.getOperand(3);
03742   SDValue Dest = Op.getOperand(4);
03743   SDLoc dl(Op);
03744 
03745   bool LHSSeenZero = false;
03746   bool LHSOk = canChangeToInt(LHS, LHSSeenZero, Subtarget);
03747   bool RHSSeenZero = false;
03748   bool RHSOk = canChangeToInt(RHS, RHSSeenZero, Subtarget);
03749   if (LHSOk && RHSOk && (LHSSeenZero || RHSSeenZero)) {
03750     // If unsafe fp math optimization is enabled and there are no other uses of
03751     // the CMP operands, and the condition code is EQ or NE, we can optimize it
03752     // to an integer comparison.
03753     if (CC == ISD::SETOEQ)
03754       CC = ISD::SETEQ;
03755     else if (CC == ISD::SETUNE)
03756       CC = ISD::SETNE;
03757 
03758     SDValue Mask = DAG.getConstant(0x7fffffff, MVT::i32);
03759     SDValue ARMcc;
03760     if (LHS.getValueType() == MVT::f32) {
03761       LHS = DAG.getNode(ISD::AND, dl, MVT::i32,
03762                         bitcastf32Toi32(LHS, DAG), Mask);
03763       RHS = DAG.getNode(ISD::AND, dl, MVT::i32,
03764                         bitcastf32Toi32(RHS, DAG), Mask);
03765       SDValue Cmp = getARMCmp(LHS, RHS, CC, ARMcc, DAG, dl);
03766       SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
03767       return DAG.getNode(ARMISD::BRCOND, dl, MVT::Other,
03768                          Chain, Dest, ARMcc, CCR, Cmp);
03769     }
03770 
03771     SDValue LHS1, LHS2;
03772     SDValue RHS1, RHS2;
03773     expandf64Toi32(LHS, DAG, LHS1, LHS2);
03774     expandf64Toi32(RHS, DAG, RHS1, RHS2);
03775     LHS2 = DAG.getNode(ISD::AND, dl, MVT::i32, LHS2, Mask);
03776     RHS2 = DAG.getNode(ISD::AND, dl, MVT::i32, RHS2, Mask);
03777     ARMCC::CondCodes CondCode = IntCCToARMCC(CC);
03778     ARMcc = DAG.getConstant(CondCode, MVT::i32);
03779     SDVTList VTList = DAG.getVTList(MVT::Other, MVT::Glue);
03780     SDValue Ops[] = { Chain, ARMcc, LHS1, LHS2, RHS1, RHS2, Dest };
03781     return DAG.getNode(ARMISD::BCC_i64, dl, VTList, Ops);
03782   }
03783 
03784   return SDValue();
03785 }
03786 
03787 SDValue ARMTargetLowering::LowerBR_CC(SDValue Op, SelectionDAG &DAG) const {
03788   SDValue Chain = Op.getOperand(0);
03789   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(1))->get();
03790   SDValue LHS = Op.getOperand(2);
03791   SDValue RHS = Op.getOperand(3);
03792   SDValue Dest = Op.getOperand(4);
03793   SDLoc dl(Op);
03794 
03795   if (Subtarget->isFPOnlySP() && LHS.getValueType() == MVT::f64) {
03796     DAG.getTargetLoweringInfo().softenSetCCOperands(DAG, MVT::f64, LHS, RHS, CC,
03797                                                     dl);
03798 
03799     // If softenSetCCOperands only returned one value, we should compare it to
03800     // zero.
03801     if (!RHS.getNode()) {
03802       RHS = DAG.getConstant(0, LHS.getValueType());
03803       CC = ISD::SETNE;
03804     }
03805   }
03806 
03807   if (LHS.getValueType() == MVT::i32) {
03808     SDValue ARMcc;
03809     SDValue Cmp = getARMCmp(LHS, RHS, CC, ARMcc, DAG, dl);
03810     SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
03811     return DAG.getNode(ARMISD::BRCOND, dl, MVT::Other,
03812                        Chain, Dest, ARMcc, CCR, Cmp);
03813   }
03814 
03815   assert(LHS.getValueType() == MVT::f32 || LHS.getValueType() == MVT::f64);
03816 
03817   if (getTargetMachine().Options.UnsafeFPMath &&
03818       (CC == ISD::SETEQ || CC == ISD::SETOEQ ||
03819        CC == ISD::SETNE || CC == ISD::SETUNE)) {
03820     SDValue Result = OptimizeVFPBrcond(Op, DAG);
03821     if (Result.getNode())
03822       return Result;
03823   }
03824 
03825   ARMCC::CondCodes CondCode, CondCode2;
03826   FPCCToARMCC(CC, CondCode, CondCode2);
03827 
03828   SDValue ARMcc = DAG.getConstant(CondCode, MVT::i32);
03829   SDValue Cmp = getVFPCmp(LHS, RHS, DAG, dl);
03830   SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
03831   SDVTList VTList = DAG.getVTList(MVT::Other, MVT::Glue);
03832   SDValue Ops[] = { Chain, Dest, ARMcc, CCR, Cmp };
03833   SDValue Res = DAG.getNode(ARMISD::BRCOND, dl, VTList, Ops);
03834   if (CondCode2 != ARMCC::AL) {
03835     ARMcc = DAG.getConstant(CondCode2, MVT::i32);
03836     SDValue Ops[] = { Res, Dest, ARMcc, CCR, Res.getValue(1) };
03837     Res = DAG.getNode(ARMISD::BRCOND, dl, VTList, Ops);
03838   }
03839   return Res;
03840 }
03841 
03842 SDValue ARMTargetLowering::LowerBR_JT(SDValue Op, SelectionDAG &DAG) const {
03843   SDValue Chain = Op.getOperand(0);
03844   SDValue Table = Op.getOperand(1);
03845   SDValue Index = Op.getOperand(2);
03846   SDLoc dl(Op);
03847 
03848   EVT PTy = getPointerTy();
03849   JumpTableSDNode *JT = cast<JumpTableSDNode>(Table);
03850   ARMFunctionInfo *AFI = DAG.getMachineFunction().getInfo<ARMFunctionInfo>();
03851   SDValue UId = DAG.getConstant(AFI->createJumpTableUId(), PTy);
03852   SDValue JTI = DAG.getTargetJumpTable(JT->getIndex(), PTy);
03853   Table = DAG.getNode(ARMISD::WrapperJT, dl, MVT::i32, JTI, UId);
03854   Index = DAG.getNode(ISD::MUL, dl, PTy, Index, DAG.getConstant(4, PTy));
03855   SDValue Addr = DAG.getNode(ISD::ADD, dl, PTy, Index, Table);
03856   if (Subtarget->isThumb2()) {
03857     // Thumb2 uses a two-level jump. That is, it jumps into the jump table
03858     // which does another jump to the destination. This also makes it easier
03859     // to translate it to TBB / TBH later.
03860     // FIXME: This might not work if the function is extremely large.
03861     return DAG.getNode(ARMISD::BR2_JT, dl, MVT::Other, Chain,
03862                        Addr, Op.getOperand(2), JTI, UId);
03863   }
03864   if (getTargetMachine().getRelocationModel() == Reloc::PIC_) {
03865     Addr = DAG.getLoad((EVT)MVT::i32, dl, Chain, Addr,
03866                        MachinePointerInfo::getJumpTable(),
03867                        false, false, false, 0);
03868     Chain = Addr.getValue(1);
03869     Addr = DAG.getNode(ISD::ADD, dl, PTy, Addr, Table);
03870     return DAG.getNode(ARMISD::BR_JT, dl, MVT::Other, Chain, Addr, JTI, UId);
03871   } else {
03872     Addr = DAG.getLoad(PTy, dl, Chain, Addr,
03873                        MachinePointerInfo::getJumpTable(),
03874                        false, false, false, 0);
03875     Chain = Addr.getValue(1);
03876     return DAG.getNode(ARMISD::BR_JT, dl, MVT::Other, Chain, Addr, JTI, UId);
03877   }
03878 }
03879 
03880 static SDValue LowerVectorFP_TO_INT(SDValue Op, SelectionDAG &DAG) {
03881   EVT VT = Op.getValueType();
03882   SDLoc dl(Op);
03883 
03884   if (Op.getValueType().getVectorElementType() == MVT::i32) {
03885     if (Op.getOperand(0).getValueType().getVectorElementType() == MVT::f32)
03886       return Op;
03887     return DAG.UnrollVectorOp(Op.getNode());
03888   }
03889 
03890   assert(Op.getOperand(0).getValueType() == MVT::v4f32 &&
03891          "Invalid type for custom lowering!");
03892   if (VT != MVT::v4i16)
03893     return DAG.UnrollVectorOp(Op.getNode());
03894 
03895   Op = DAG.getNode(Op.getOpcode(), dl, MVT::v4i32, Op.getOperand(0));
03896   return DAG.getNode(ISD::TRUNCATE, dl, VT, Op);
03897 }
03898 
03899 SDValue ARMTargetLowering::LowerFP_TO_INT(SDValue Op, SelectionDAG &DAG) const {
03900   EVT VT = Op.getValueType();
03901   if (VT.isVector())
03902     return LowerVectorFP_TO_INT(Op, DAG);
03903 
03904   if (Subtarget->isFPOnlySP() && Op.getOperand(0).getValueType() == MVT::f64) {
03905     RTLIB::Libcall LC;
03906     if (Op.getOpcode() == ISD::FP_TO_SINT)
03907       LC = RTLIB::getFPTOSINT(Op.getOperand(0).getValueType(),
03908                               Op.getValueType());
03909     else
03910       LC = RTLIB::getFPTOUINT(Op.getOperand(0).getValueType(),
03911                               Op.getValueType());
03912     return makeLibCall(DAG, LC, Op.getValueType(), &Op.getOperand(0), 1,
03913                        /*isSigned*/ false, SDLoc(Op)).first;
03914   }
03915 
03916   SDLoc dl(Op);
03917   unsigned Opc;
03918 
03919   switch (Op.getOpcode()) {
03920   default: llvm_unreachable("Invalid opcode!");
03921   case ISD::FP_TO_SINT:
03922     Opc = ARMISD::FTOSI;
03923     break;
03924   case ISD::FP_TO_UINT:
03925     Opc = ARMISD::FTOUI;
03926     break;
03927   }
03928   Op = DAG.getNode(Opc, dl, MVT::f32, Op.getOperand(0));
03929   return DAG.getNode(ISD::BITCAST, dl, MVT::i32, Op);
03930 }
03931 
03932 static SDValue LowerVectorINT_TO_FP(SDValue Op, SelectionDAG &DAG) {
03933   EVT VT = Op.getValueType();
03934   SDLoc dl(Op);
03935 
03936   if (Op.getOperand(0).getValueType().getVectorElementType() == MVT::i32) {
03937     if (VT.getVectorElementType() == MVT::f32)
03938       return Op;
03939     return DAG.UnrollVectorOp(Op.getNode());
03940   }
03941 
03942   assert(Op.getOperand(0).getValueType() == MVT::v4i16 &&
03943          "Invalid type for custom lowering!");
03944   if (VT != MVT::v4f32)
03945     return DAG.UnrollVectorOp(Op.getNode());
03946 
03947   unsigned CastOpc;
03948   unsigned Opc;
03949   switch (Op.getOpcode()) {
03950   default: llvm_unreachable("Invalid opcode!");
03951   case ISD::SINT_TO_FP:
03952     CastOpc = ISD::SIGN_EXTEND;
03953     Opc = ISD::SINT_TO_FP;
03954     break;
03955   case ISD::UINT_TO_FP:
03956     CastOpc = ISD::ZERO_EXTEND;
03957     Opc = ISD::UINT_TO_FP;
03958     break;
03959   }
03960 
03961   Op = DAG.getNode(CastOpc, dl, MVT::v4i32, Op.getOperand(0));
03962   return DAG.getNode(Opc, dl, VT, Op);
03963 }
03964 
03965 SDValue ARMTargetLowering::LowerINT_TO_FP(SDValue Op, SelectionDAG &DAG) const {
03966   EVT VT = Op.getValueType();
03967   if (VT.isVector())
03968     return LowerVectorINT_TO_FP(Op, DAG);
03969 
03970   if (Subtarget->isFPOnlySP() && Op.getValueType() == MVT::f64) {
03971     RTLIB::Libcall LC;
03972     if (Op.getOpcode() == ISD::SINT_TO_FP)
03973       LC = RTLIB::getSINTTOFP(Op.getOperand(0).getValueType(),
03974                               Op.getValueType());
03975     else
03976       LC = RTLIB::getUINTTOFP(Op.getOperand(0).getValueType(),
03977                               Op.getValueType());
03978     return makeLibCall(DAG, LC, Op.getValueType(), &Op.getOperand(0), 1,
03979                        /*isSigned*/ false, SDLoc(Op)).first;
03980   }
03981 
03982   SDLoc dl(Op);
03983   unsigned Opc;
03984 
03985   switch (Op.getOpcode()) {
03986   default: llvm_unreachable("Invalid opcode!");
03987   case ISD::SINT_TO_FP:
03988     Opc = ARMISD::SITOF;
03989     break;
03990   case ISD::UINT_TO_FP:
03991     Opc = ARMISD::UITOF;
03992     break;
03993   }
03994 
03995   Op = DAG.getNode(ISD::BITCAST, dl, MVT::f32, Op.getOperand(0));
03996   return DAG.getNode(Opc, dl, VT, Op);
03997 }
03998 
03999 SDValue ARMTargetLowering::LowerFCOPYSIGN(SDValue Op, SelectionDAG &DAG) const {
04000   // Implement fcopysign with a fabs and a conditional fneg.
04001   SDValue Tmp0 = Op.getOperand(0);
04002   SDValue Tmp1 = Op.getOperand(1);
04003   SDLoc dl(Op);
04004   EVT VT = Op.getValueType();
04005   EVT SrcVT = Tmp1.getValueType();
04006   bool InGPR = Tmp0.getOpcode() == ISD::BITCAST ||
04007     Tmp0.getOpcode() == ARMISD::VMOVDRR;
04008   bool UseNEON = !InGPR && Subtarget->hasNEON();
04009 
04010   if (UseNEON) {
04011     // Use VBSL to copy the sign bit.
04012     unsigned EncodedVal = ARM_AM::createNEONModImm(0x6, 0x80);
04013     SDValue Mask = DAG.getNode(ARMISD::VMOVIMM, dl, MVT::v2i32,
04014                                DAG.getTargetConstant(EncodedVal, MVT::i32));
04015     EVT OpVT = (VT == MVT::f32) ? MVT::v2i32 : MVT::v1i64;
04016     if (VT == MVT::f64)
04017       Mask = DAG.getNode(ARMISD::VSHL, dl, OpVT,
04018                          DAG.getNode(ISD::BITCAST, dl, OpVT, Mask),
04019                          DAG.getConstant(32, MVT::i32));
04020     else /*if (VT == MVT::f32)*/
04021       Tmp0 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f32, Tmp0);
04022     if (SrcVT == MVT::f32) {
04023       Tmp1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f32, Tmp1);
04024       if (VT == MVT::f64)
04025         Tmp1 = DAG.getNode(ARMISD::VSHL, dl, OpVT,
04026                            DAG.getNode(ISD::BITCAST, dl, OpVT, Tmp1),
04027                            DAG.getConstant(32, MVT::i32));
04028     } else if (VT == MVT::f32)
04029       Tmp1 = DAG.getNode(ARMISD::VSHRu, dl, MVT::v1i64,
04030                          DAG.getNode(ISD::BITCAST, dl, MVT::v1i64, Tmp1),
04031                          DAG.getConstant(32, MVT::i32));
04032     Tmp0 = DAG.getNode(ISD::BITCAST, dl, OpVT, Tmp0);
04033     Tmp1 = DAG.getNode(ISD::BITCAST, dl, OpVT, Tmp1);
04034 
04035     SDValue AllOnes = DAG.getTargetConstant(ARM_AM::createNEONModImm(0xe, 0xff),
04036                                             MVT::i32);
04037     AllOnes = DAG.getNode(ARMISD::VMOVIMM, dl, MVT::v8i8, AllOnes);
04038     SDValue MaskNot = DAG.getNode(ISD::XOR, dl, OpVT, Mask,
04039                                   DAG.getNode(ISD::BITCAST, dl, OpVT, AllOnes));
04040 
04041     SDValue Res = DAG.getNode(ISD::OR, dl, OpVT,
04042                               DAG.getNode(ISD::AND, dl, OpVT, Tmp1, Mask),
04043                               DAG.getNode(ISD::AND, dl, OpVT, Tmp0, MaskNot));
04044     if (VT == MVT::f32) {
04045       Res = DAG.getNode(ISD::BITCAST, dl, MVT::v2f32, Res);
04046       Res = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f32, Res,
04047                         DAG.getConstant(0, MVT::i32));
04048     } else {
04049       Res = DAG.getNode(ISD::BITCAST, dl, MVT::f64, Res);
04050     }
04051 
04052     return Res;
04053   }
04054 
04055   // Bitcast operand 1 to i32.
04056   if (SrcVT == MVT::f64)
04057     Tmp1 = DAG.getNode(ARMISD::VMOVRRD, dl, DAG.getVTList(MVT::i32, MVT::i32),
04058                        Tmp1).getValue(1);
04059   Tmp1 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Tmp1);
04060 
04061   // Or in the signbit with integer operations.
04062   SDValue Mask1 = DAG.getConstant(0x80000000, MVT::i32);
04063   SDValue Mask2 = DAG.getConstant(0x7fffffff, MVT::i32);
04064   Tmp1 = DAG.getNode(ISD::AND, dl, MVT::i32, Tmp1, Mask1);
04065   if (VT == MVT::f32) {
04066     Tmp0 = DAG.getNode(ISD::AND, dl, MVT::i32,
04067                        DAG.getNode(ISD::BITCAST, dl, MVT::i32, Tmp0), Mask2);
04068     return DAG.getNode(ISD::BITCAST, dl, MVT::f32,
04069                        DAG.getNode(ISD::OR, dl, MVT::i32, Tmp0, Tmp1));
04070   }
04071 
04072   // f64: Or the high part with signbit and then combine two parts.
04073   Tmp0 = DAG.getNode(ARMISD::VMOVRRD, dl, DAG.getVTList(MVT::i32, MVT::i32),
04074                      Tmp0);
04075   SDValue Lo = Tmp0.getValue(0);
04076   SDValue Hi = DAG.getNode(ISD::AND, dl, MVT::i32, Tmp0.getValue(1), Mask2);
04077   Hi = DAG.getNode(ISD::OR, dl, MVT::i32, Hi, Tmp1);
04078   return DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi);
04079 }
04080 
04081 SDValue ARMTargetLowering::LowerRETURNADDR(SDValue Op, SelectionDAG &DAG) const{
04082   MachineFunction &MF = DAG.getMachineFunction();
04083   MachineFrameInfo *MFI = MF.getFrameInfo();
04084   MFI->setReturnAddressIsTaken(true);
04085 
04086   if (verifyReturnAddressArgumentIsConstant(Op, DAG))
04087     return SDValue();
04088 
04089   EVT VT = Op.getValueType();
04090   SDLoc dl(Op);
04091   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
04092   if (Depth) {
04093     SDValue FrameAddr = LowerFRAMEADDR(Op, DAG);
04094     SDValue Offset = DAG.getConstant(4, MVT::i32);
04095     return DAG.getLoad(VT, dl, DAG.getEntryNode(),
04096                        DAG.getNode(ISD::ADD, dl, VT, FrameAddr, Offset),
04097                        MachinePointerInfo(), false, false, false, 0);
04098   }
04099 
04100   // Return LR, which contains the return address. Mark it an implicit live-in.
04101   unsigned Reg = MF.addLiveIn(ARM::LR, getRegClassFor(MVT::i32));
04102   return DAG.getCopyFromReg(DAG.getEntryNode(), dl, Reg, VT);
04103 }
04104 
04105 SDValue ARMTargetLowering::LowerFRAMEADDR(SDValue Op, SelectionDAG &DAG) const {
04106   const ARMBaseRegisterInfo &ARI =
04107     *static_cast<const ARMBaseRegisterInfo*>(RegInfo);
04108   MachineFunction &MF = DAG.getMachineFunction();
04109   MachineFrameInfo *MFI = MF.getFrameInfo();
04110   MFI->setFrameAddressIsTaken(true);
04111 
04112   EVT VT = Op.getValueType();
04113   SDLoc dl(Op);  // FIXME probably not meaningful
04114   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
04115   unsigned FrameReg = ARI.getFrameRegister(MF);
04116   SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, VT);
04117   while (Depth--)
04118     FrameAddr = DAG.getLoad(VT, dl, DAG.getEntryNode(), FrameAddr,
04119                             MachinePointerInfo(),
04120                             false, false, false, 0);
04121   return FrameAddr;
04122 }
04123 
04124 // FIXME? Maybe this could be a TableGen attribute on some registers and
04125 // this table could be generated automatically from RegInfo.
04126 unsigned ARMTargetLowering::getRegisterByName(const char* RegName,
04127                                               EVT VT) const {
04128   unsigned Reg = StringSwitch<unsigned>(RegName)
04129                        .Case("sp", ARM::SP)
04130                        .Default(0);
04131   if (Reg)
04132     return Reg;
04133   report_fatal_error("Invalid register name global variable");
04134 }
04135 
04136 /// ExpandBITCAST - If the target supports VFP, this function is called to
04137 /// expand a bit convert where either the source or destination type is i64 to
04138 /// use a VMOVDRR or VMOVRRD node.  This should not be done when the non-i64
04139 /// operand type is illegal (e.g., v2f32 for a target that doesn't support
04140 /// vectors), since the legalizer won't know what to do with that.
04141 static SDValue ExpandBITCAST(SDNode *N, SelectionDAG &DAG) {
04142   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
04143   SDLoc dl(N);
04144   SDValue Op = N->getOperand(0);
04145 
04146   // This function is only supposed to be called for i64 types, either as the
04147   // source or destination of the bit convert.
04148   EVT SrcVT = Op.getValueType();
04149   EVT DstVT = N->getValueType(0);
04150   assert((SrcVT == MVT::i64 || DstVT == MVT::i64) &&
04151          "ExpandBITCAST called for non-i64 type");
04152 
04153   // Turn i64->f64 into VMOVDRR.
04154   if (SrcVT == MVT::i64 && TLI.isTypeLegal(DstVT)) {
04155     SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, Op,
04156                              DAG.getConstant(0, MVT::i32));
04157     SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, Op,
04158                              DAG.getConstant(1, MVT::i32));
04159     return DAG.getNode(ISD::BITCAST, dl, DstVT,
04160                        DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi));
04161   }
04162 
04163   // Turn f64->i64 into VMOVRRD.
04164   if (DstVT == MVT::i64 && TLI.isTypeLegal(SrcVT)) {
04165     SDValue Cvt;
04166     if (TLI.isBigEndian() && SrcVT.isVector() &&
04167         SrcVT.getVectorNumElements() > 1)
04168       Cvt = DAG.getNode(ARMISD::VMOVRRD, dl,
04169                         DAG.getVTList(MVT::i32, MVT::i32),
04170                         DAG.getNode(ARMISD::VREV64, dl, SrcVT, Op));
04171     else
04172       Cvt = DAG.getNode(ARMISD::VMOVRRD, dl,
04173                         DAG.getVTList(MVT::i32, MVT::i32), Op);
04174     // Merge the pieces into a single i64 value.
04175     return DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Cvt, Cvt.getValue(1));
04176   }
04177 
04178   return SDValue();
04179 }
04180 
04181 /// getZeroVector - Returns a vector of specified type with all zero elements.
04182 /// Zero vectors are used to represent vector negation and in those cases
04183 /// will be implemented with the NEON VNEG instruction.  However, VNEG does
04184 /// not support i64 elements, so sometimes the zero vectors will need to be
04185 /// explicitly constructed.  Regardless, use a canonical VMOV to create the
04186 /// zero vector.
04187 static SDValue getZeroVector(EVT VT, SelectionDAG &DAG, SDLoc dl) {
04188   assert(VT.isVector() && "Expected a vector type");
04189   // The canonical modified immediate encoding of a zero vector is....0!
04190   SDValue EncodedVal = DAG.getTargetConstant(0, MVT::i32);
04191   EVT VmovVT = VT.is128BitVector() ? MVT::v4i32 : MVT::v2i32;
04192   SDValue Vmov = DAG.getNode(ARMISD::VMOVIMM, dl, VmovVT, EncodedVal);
04193   return DAG.getNode(ISD::BITCAST, dl, VT, Vmov);
04194 }
04195 
04196 /// LowerShiftRightParts - Lower SRA_PARTS, which returns two
04197 /// i32 values and take a 2 x i32 value to shift plus a shift amount.
04198 SDValue ARMTargetLowering::LowerShiftRightParts(SDValue Op,
04199                                                 SelectionDAG &DAG) const {
04200   assert(Op.getNumOperands() == 3 && "Not a double-shift!");
04201   EVT VT = Op.getValueType();
04202   unsigned VTBits = VT.getSizeInBits();
04203   SDLoc dl(Op);
04204   SDValue ShOpLo = Op.getOperand(0);
04205   SDValue ShOpHi = Op.getOperand(1);
04206   SDValue ShAmt  = Op.getOperand(2);
04207   SDValue ARMcc;
04208   unsigned Opc = (Op.getOpcode() == ISD::SRA_PARTS) ? ISD::SRA : ISD::SRL;
04209 
04210   assert(Op.getOpcode() == ISD::SRA_PARTS || Op.getOpcode() == ISD::SRL_PARTS);
04211 
04212   SDValue RevShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32,
04213                                  DAG.getConstant(VTBits, MVT::i32), ShAmt);
04214   SDValue Tmp1 = DAG.getNode(ISD::SRL, dl, VT, ShOpLo, ShAmt);
04215   SDValue ExtraShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32, ShAmt,
04216                                    DAG.getConstant(VTBits, MVT::i32));
04217   SDValue Tmp2 = DAG.getNode(ISD::SHL, dl, VT, ShOpHi, RevShAmt);
04218   SDValue FalseVal = DAG.getNode(ISD::OR, dl, VT, Tmp1, Tmp2);
04219   SDValue TrueVal = DAG.getNode(Opc, dl, VT, ShOpHi, ExtraShAmt);
04220 
04221   SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
04222   SDValue Cmp = getARMCmp(ExtraShAmt, DAG.getConstant(0, MVT::i32), ISD::SETGE,
04223                           ARMcc, DAG, dl);
04224   SDValue Hi = DAG.getNode(Opc, dl, VT, ShOpHi, ShAmt);
04225   SDValue Lo = DAG.getNode(ARMISD::CMOV, dl, VT, FalseVal, TrueVal, ARMcc,
04226                            CCR, Cmp);
04227 
04228   SDValue Ops[2] = { Lo, Hi };
04229   return DAG.getMergeValues(Ops, dl);
04230 }
04231 
04232 /// LowerShiftLeftParts - Lower SHL_PARTS, which returns two
04233 /// i32 values and take a 2 x i32 value to shift plus a shift amount.
04234 SDValue ARMTargetLowering::LowerShiftLeftParts(SDValue Op,
04235                                                SelectionDAG &DAG) const {
04236   assert(Op.getNumOperands() == 3 && "Not a double-shift!");
04237   EVT VT = Op.getValueType();
04238   unsigned VTBits = VT.getSizeInBits();
04239   SDLoc dl(Op);
04240   SDValue ShOpLo = Op.getOperand(0);
04241   SDValue ShOpHi = Op.getOperand(1);
04242   SDValue ShAmt  = Op.getOperand(2);
04243   SDValue ARMcc;
04244 
04245   assert(Op.getOpcode() == ISD::SHL_PARTS);
04246   SDValue RevShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32,
04247                                  DAG.getConstant(VTBits, MVT::i32), ShAmt);
04248   SDValue Tmp1 = DAG.getNode(ISD::SRL, dl, VT, ShOpLo, RevShAmt);
04249   SDValue ExtraShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32, ShAmt,
04250                                    DAG.getConstant(VTBits, MVT::i32));
04251   SDValue Tmp2 = DAG.getNode(ISD::SHL, dl, VT, ShOpHi, ShAmt);
04252   SDValue Tmp3 = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ExtraShAmt);
04253 
04254   SDValue FalseVal = DAG.getNode(ISD::OR, dl, VT, Tmp1, Tmp2);
04255   SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
04256   SDValue Cmp = getARMCmp(ExtraShAmt, DAG.getConstant(0, MVT::i32), ISD::SETGE,
04257                           ARMcc, DAG, dl);
04258   SDValue Lo = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ShAmt);
04259   SDValue Hi = DAG.getNode(ARMISD::CMOV, dl, VT, FalseVal, Tmp3, ARMcc,
04260                            CCR, Cmp);
04261 
04262   SDValue Ops[2] = { Lo, Hi };
04263   return DAG.getMergeValues(Ops, dl);
04264 }
04265 
04266 SDValue ARMTargetLowering::LowerFLT_ROUNDS_(SDValue Op,
04267                                             SelectionDAG &DAG) const {
04268   // The rounding mode is in bits 23:22 of the FPSCR.
04269   // The ARM rounding mode value to FLT_ROUNDS mapping is 0->1, 1->2, 2->3, 3->0
04270   // The formula we use to implement this is (((FPSCR + 1 << 22) >> 22) & 3)
04271   // so that the shift + and get folded into a bitfield extract.
04272   SDLoc dl(Op);
04273   SDValue FPSCR = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::i32,
04274                               DAG.getConstant(Intrinsic::arm_get_fpscr,
04275                                               MVT::i32));
04276   SDValue FltRounds = DAG.getNode(ISD::ADD, dl, MVT::i32, FPSCR,
04277                                   DAG.getConstant(1U << 22, MVT::i32));
04278   SDValue RMODE = DAG.getNode(ISD::SRL, dl, MVT::i32, FltRounds,
04279                               DAG.getConstant(22, MVT::i32));
04280   return DAG.getNode(ISD::AND, dl, MVT::i32, RMODE,
04281                      DAG.getConstant(3, MVT::i32));
04282 }
04283 
04284 static SDValue LowerCTTZ(SDNode *N, SelectionDAG &DAG,
04285                          const ARMSubtarget *ST) {
04286   EVT VT = N->getValueType(0);
04287   SDLoc dl(N);
04288 
04289   if (!ST->hasV6T2Ops())
04290     return SDValue();
04291 
04292   SDValue rbit = DAG.getNode(ARMISD::RBIT, dl, VT, N->getOperand(0));
04293   return DAG.getNode(ISD::CTLZ, dl, VT, rbit);
04294 }
04295 
04296 /// getCTPOP16BitCounts - Returns a v8i8/v16i8 vector containing the bit-count
04297 /// for each 16-bit element from operand, repeated.  The basic idea is to
04298 /// leverage vcnt to get the 8-bit counts, gather and add the results.
04299 ///
04300 /// Trace for v4i16:
04301 /// input    = [v0    v1    v2    v3   ] (vi 16-bit element)
04302 /// cast: N0 = [w0 w1 w2 w3 w4 w5 w6 w7] (v0 = [w0 w1], wi 8-bit element)
04303 /// vcnt: N1 = [b0 b1 b2 b3 b4 b5 b6 b7] (bi = bit-count of 8-bit element wi)
04304 /// vrev: N2 = [b1 b0 b3 b2 b5 b4 b7 b6]
04305 ///            [b0 b1 b2 b3 b4 b5 b6 b7]
04306 ///           +[b1 b0 b3 b2 b5 b4 b7 b6]
04307 /// N3=N1+N2 = [k0 k0 k1 k1 k2 k2 k3 k3] (k0 = b0+b1 = bit-count of 16-bit v0,
04308 /// vuzp:    = [k0 k1 k2 k3 k0 k1 k2 k3]  each ki is 8-bits)
04309 static SDValue getCTPOP16BitCounts(SDNode *N, SelectionDAG &DAG) {
04310   EVT VT = N->getValueType(0);
04311   SDLoc DL(N);
04312 
04313   EVT VT8Bit = VT.is64BitVector() ? MVT::v8i8 : MVT::v16i8;
04314   SDValue N0 = DAG.getNode(ISD::BITCAST, DL, VT8Bit, N->getOperand(0));
04315   SDValue N1 = DAG.getNode(ISD::CTPOP, DL, VT8Bit, N0);
04316   SDValue N2 = DAG.getNode(ARMISD::VREV16, DL, VT8Bit, N1);
04317   SDValue N3 = DAG.getNode(ISD::ADD, DL, VT8Bit, N1, N2);
04318   return DAG.getNode(ARMISD::VUZP, DL, VT8Bit, N3, N3);
04319 }
04320 
04321 /// lowerCTPOP16BitElements - Returns a v4i16/v8i16 vector containing the
04322 /// bit-count for each 16-bit element from the operand.  We need slightly
04323 /// different sequencing for v4i16 and v8i16 to stay within NEON's available
04324 /// 64/128-bit registers.
04325 ///
04326 /// Trace for v4i16:
04327 /// input           = [v0    v1    v2    v3    ] (vi 16-bit element)
04328 /// v8i8: BitCounts = [k0 k1 k2 k3 k0 k1 k2 k3 ] (ki is the bit-count of vi)
04329 /// v8i16:Extended  = [k0    k1    k2    k3    k0    k1    k2    k3    ]
04330 /// v4i16:Extracted = [k0    k1    k2    k3    ]
04331 static SDValue lowerCTPOP16BitElements(SDNode *N, SelectionDAG &DAG) {
04332   EVT VT = N->getValueType(0);
04333   SDLoc DL(N);
04334 
04335   SDValue BitCounts = getCTPOP16BitCounts(N, DAG);
04336   if (VT.is64BitVector()) {
04337     SDValue Extended = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::v8i16, BitCounts);
04338     return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v4i16, Extended,
04339                        DAG.getIntPtrConstant(0));
04340   } else {
04341     SDValue Extracted = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v8i8,
04342                                     BitCounts, DAG.getIntPtrConstant(0));
04343     return DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::v8i16, Extracted);
04344   }
04345 }
04346 
04347 /// lowerCTPOP32BitElements - Returns a v2i32/v4i32 vector containing the
04348 /// bit-count for each 32-bit element from the operand.  The idea here is
04349 /// to split the vector into 16-bit elements, leverage the 16-bit count
04350 /// routine, and then combine the results.
04351 ///
04352 /// Trace for v2i32 (v4i32 similar with Extracted/Extended exchanged):
04353 /// input    = [v0    v1    ] (vi: 32-bit elements)
04354 /// Bitcast  = [w0 w1 w2 w3 ] (wi: 16-bit elements, v0 = [w0 w1])
04355 /// Counts16 = [k0 k1 k2 k3 ] (ki: 16-bit elements, bit-count of wi)
04356 /// vrev: N0 = [k1 k0 k3 k2 ]
04357 ///            [k0 k1 k2 k3 ]
04358 ///       N1 =+[k1 k0 k3 k2 ]
04359 ///            [k0 k2 k1 k3 ]
04360 ///       N2 =+[k1 k3 k0 k2 ]
04361 ///            [k0    k2    k1    k3    ]
04362 /// Extended =+[k1    k3    k0    k2    ]
04363 ///            [k0    k2    ]
04364 /// Extracted=+[k1    k3    ]
04365 ///
04366 static SDValue lowerCTPOP32BitElements(SDNode *N, SelectionDAG &DAG) {
04367   EVT VT = N->getValueType(0);
04368   SDLoc DL(N);
04369 
04370   EVT VT16Bit = VT.is64BitVector() ? MVT::v4i16 : MVT::v8i16;
04371 
04372   SDValue Bitcast = DAG.getNode(ISD::BITCAST, DL, VT16Bit, N->getOperand(0));
04373   SDValue Counts16 = lowerCTPOP16BitElements(Bitcast.getNode(), DAG);
04374   SDValue N0 = DAG.getNode(ARMISD::VREV32, DL, VT16Bit, Counts16);
04375   SDValue N1 = DAG.getNode(ISD::ADD, DL, VT16Bit, Counts16, N0);
04376   SDValue N2 = DAG.getNode(ARMISD::VUZP, DL, VT16Bit, N1, N1);
04377 
04378   if (VT.is64BitVector()) {
04379     SDValue Extended = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::v4i32, N2);
04380     return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2i32, Extended,
04381                        DAG.getIntPtrConstant(0));
04382   } else {
04383     SDValue Extracted = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v4i16, N2,
04384                                     DAG.getIntPtrConstant(0));
04385     return DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::v4i32, Extracted);
04386   }
04387 }
04388 
04389 static SDValue LowerCTPOP(SDNode *N, SelectionDAG &DAG,
04390                           const ARMSubtarget *ST) {
04391   EVT VT = N->getValueType(0);
04392 
04393   assert(ST->hasNEON() && "Custom ctpop lowering requires NEON.");
04394   assert((VT == MVT::v2i32 || VT == MVT::v4i32 ||
04395           VT == MVT::v4i16 || VT == MVT::v8i16) &&
04396          "Unexpected type for custom ctpop lowering");
04397 
04398   if (VT.getVectorElementType() == MVT::i32)
04399     return lowerCTPOP32BitElements(N, DAG);
04400   else
04401     return lowerCTPOP16BitElements(N, DAG);
04402 }
04403 
04404 static SDValue LowerShift(SDNode *N, SelectionDAG &DAG,
04405                           const ARMSubtarget *ST) {
04406   EVT VT = N->getValueType(0);
04407   SDLoc dl(N);
04408 
04409   if (!VT.isVector())
04410     return SDValue();
04411 
04412   // Lower vector shifts on NEON to use VSHL.
04413   assert(ST->hasNEON() && "unexpected vector shift");
04414 
04415   // Left shifts translate directly to the vshiftu intrinsic.
04416   if (N->getOpcode() == ISD::SHL)
04417     return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
04418                        DAG.getConstant(Intrinsic::arm_neon_vshiftu, MVT::i32),
04419                        N->getOperand(0), N->getOperand(1));
04420 
04421   assert((N->getOpcode() == ISD::SRA ||
04422           N->getOpcode() == ISD::SRL) && "unexpected vector shift opcode");
04423 
04424   // NEON uses the same intrinsics for both left and right shifts.  For
04425   // right shifts, the shift amounts are negative, so negate the vector of
04426   // shift amounts.
04427   EVT ShiftVT = N->getOperand(1).getValueType();
04428   SDValue NegatedCount = DAG.getNode(ISD::SUB, dl, ShiftVT,
04429                                      getZeroVector(ShiftVT, DAG, dl),
04430                                      N->getOperand(1));
04431   Intrinsic::ID vshiftInt = (N->getOpcode() == ISD::SRA ?
04432                              Intrinsic::arm_neon_vshifts :
04433                              Intrinsic::arm_neon_vshiftu);
04434   return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
04435                      DAG.getConstant(vshiftInt, MVT::i32),
04436                      N->getOperand(0), NegatedCount);
04437 }
04438 
04439 static SDValue Expand64BitShift(SDNode *N, SelectionDAG &DAG,
04440                                 const ARMSubtarget *ST) {
04441   EVT VT = N->getValueType(0);
04442   SDLoc dl(N);
04443 
04444   // We can get here for a node like i32 = ISD::SHL i32, i64
04445   if (VT != MVT::i64)
04446     return SDValue();
04447 
04448   assert((N->getOpcode() == ISD::SRL || N->getOpcode() == ISD::SRA) &&
04449          "Unknown shift to lower!");
04450 
04451   // We only lower SRA, SRL of 1 here, all others use generic lowering.
04452   if (!isa<ConstantSDNode>(N->getOperand(1)) ||
04453       cast<ConstantSDNode>(N->getOperand(1))->getZExtValue() != 1)
04454     return SDValue();
04455 
04456   // If we are in thumb mode, we don't have RRX.
04457   if (ST->isThumb1Only()) return SDValue();
04458 
04459   // Okay, we have a 64-bit SRA or SRL of 1.  Lower this to an RRX expr.
04460   SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(0),
04461                            DAG.getConstant(0, MVT::i32));
04462   SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(0),
04463                            DAG.getConstant(1, MVT::i32));
04464 
04465   // First, build a SRA_FLAG/SRL_FLAG op, which shifts the top part by one and
04466   // captures the result into a carry flag.
04467   unsigned Opc = N->getOpcode() == ISD::SRL ? ARMISD::SRL_FLAG:ARMISD::SRA_FLAG;
04468   Hi = DAG.getNode(Opc, dl, DAG.getVTList(MVT::i32, MVT::Glue), Hi);
04469 
04470   // The low part is an ARMISD::RRX operand, which shifts the carry in.
04471   Lo = DAG.getNode(ARMISD::RRX, dl, MVT::i32, Lo, Hi.getValue(1));
04472 
04473   // Merge the pieces into a single i64 value.
04474  return DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Lo, Hi);
04475 }
04476 
04477 static SDValue LowerVSETCC(SDValue Op, SelectionDAG &DAG) {
04478   SDValue TmpOp0, TmpOp1;
04479   bool Invert = false;
04480   bool Swap = false;
04481   unsigned Opc = 0;
04482 
04483   SDValue Op0 = Op.getOperand(0);
04484   SDValue Op1 = Op.getOperand(1);
04485   SDValue CC = Op.getOperand(2);
04486   EVT VT = Op.getValueType();
04487   ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
04488   SDLoc dl(Op);
04489 
04490   if (Op1.getValueType().isFloatingPoint()) {
04491     switch (SetCCOpcode) {
04492     default: llvm_unreachable("Illegal FP comparison");
04493     case ISD::SETUNE:
04494     case ISD::SETNE:  Invert = true; // Fallthrough
04495     case ISD::SETOEQ:
04496     case ISD::SETEQ:  Opc = ARMISD::VCEQ; break;
04497     case ISD::SETOLT:
04498     case ISD::SETLT: Swap = true; // Fallthrough
04499     case ISD::SETOGT:
04500     case ISD::SETGT:  Opc = ARMISD::VCGT; break;
04501     case ISD::SETOLE:
04502     case ISD::SETLE:  Swap = true; // Fallthrough
04503     case ISD::SETOGE:
04504     case ISD::SETGE: Opc = ARMISD::VCGE; break;
04505     case ISD::SETUGE: Swap = true; // Fallthrough
04506     case ISD::SETULE: Invert = true; Opc = ARMISD::VCGT; break;
04507     case ISD::SETUGT: Swap = true; // Fallthrough
04508     case ISD::SETULT: Invert = true; Opc = ARMISD::VCGE; break;
04509     case ISD::SETUEQ: Invert = true; // Fallthrough
04510     case ISD::SETONE:
04511       // Expand this to (OLT | OGT).
04512       TmpOp0 = Op0;
04513       TmpOp1 = Op1;
04514       Opc = ISD::OR;
04515       Op0 = DAG.getNode(ARMISD::VCGT, dl, VT, TmpOp1, TmpOp0);
04516       Op1 = DAG.getNode(ARMISD::VCGT, dl, VT, TmpOp0, TmpOp1);
04517       break;
04518     case ISD::SETUO: Invert = true; // Fallthrough
04519     case ISD::SETO:
04520       // Expand this to (OLT | OGE).
04521       TmpOp0 = Op0;
04522       TmpOp1 = Op1;
04523       Opc = ISD::OR;
04524       Op0 = DAG.getNode(ARMISD::VCGT, dl, VT, TmpOp1, TmpOp0);
04525       Op1 = DAG.getNode(ARMISD::VCGE, dl, VT, TmpOp0, TmpOp1);
04526       break;
04527     }
04528   } else {
04529     // Integer comparisons.
04530     switch (SetCCOpcode) {
04531     default: llvm_unreachable("Illegal integer comparison");
04532     case ISD::SETNE:  Invert = true;
04533     case ISD::SETEQ:  Opc = ARMISD::VCEQ; break;
04534     case ISD::SETLT:  Swap = true;
04535     case ISD::SETGT:  Opc = ARMISD::VCGT; break;
04536     case ISD::SETLE:  Swap = true;
04537     case ISD::SETGE:  Opc = ARMISD::VCGE; break;
04538     case ISD::SETULT: Swap = true;
04539     case ISD::SETUGT: Opc = ARMISD::VCGTU; break;
04540     case ISD::SETULE: Swap = true;
04541     case ISD::SETUGE: Opc = ARMISD::VCGEU; break;
04542     }
04543 
04544     // Detect VTST (Vector Test Bits) = icmp ne (and (op0, op1), zero).
04545     if (Opc == ARMISD::VCEQ) {
04546 
04547       SDValue AndOp;
04548       if (ISD::isBuildVectorAllZeros(Op1.getNode()))
04549         AndOp = Op0;
04550       else if (ISD::isBuildVectorAllZeros(Op0.getNode()))
04551         AndOp = Op1;
04552 
04553       // Ignore bitconvert.
04554       if (AndOp.getNode() && AndOp.getOpcode() == ISD::BITCAST)
04555         AndOp = AndOp.getOperand(0);
04556 
04557       if (AndOp.getNode() && AndOp.getOpcode() == ISD::AND) {
04558         Opc = ARMISD::VTST;
04559         Op0 = DAG.getNode(ISD::BITCAST, dl, VT, AndOp.getOperand(0));
04560         Op1 = DAG.getNode(ISD::BITCAST, dl, VT, AndOp.getOperand(1));
04561         Invert = !Invert;
04562       }
04563     }
04564   }
04565 
04566   if (Swap)
04567     std::swap(Op0, Op1);
04568 
04569   // If one of the operands is a constant vector zero, attempt to fold the
04570   // comparison to a specialized compare-against-zero form.
04571   SDValue SingleOp;
04572   if (ISD::isBuildVectorAllZeros(Op1.getNode()))
04573     SingleOp = Op0;
04574   else if (ISD::isBuildVectorAllZeros(Op0.getNode())) {
04575     if (Opc == ARMISD::VCGE)
04576       Opc = ARMISD::VCLEZ;
04577     else if (Opc == ARMISD::VCGT)
04578       Opc = ARMISD::VCLTZ;
04579     SingleOp = Op1;
04580   }
04581 
04582   SDValue Result;
04583   if (SingleOp.getNode()) {
04584     switch (Opc) {
04585     case ARMISD::VCEQ:
04586       Result = DAG.getNode(ARMISD::VCEQZ, dl, VT, SingleOp); break;
04587     case ARMISD::VCGE:
04588       Result = DAG.getNode(ARMISD::VCGEZ, dl, VT, SingleOp); break;
04589     case ARMISD::VCLEZ:
04590       Result = DAG.getNode(ARMISD::VCLEZ, dl, VT, SingleOp); break;
04591     case ARMISD::VCGT:
04592       Result = DAG.getNode(ARMISD::VCGTZ, dl, VT, SingleOp); break;
04593     case ARMISD::VCLTZ:
04594       Result = DAG.getNode(ARMISD::VCLTZ, dl, VT, SingleOp); break;
04595     default:
04596       Result = DAG.getNode(Opc, dl, VT, Op0, Op1);
04597     }
04598   } else {
04599      Result = DAG.getNode(Opc, dl, VT, Op0, Op1);
04600   }
04601 
04602   if (Invert)
04603     Result = DAG.getNOT(dl, Result, VT);
04604 
04605   return Result;
04606 }
04607 
04608 /// isNEONModifiedImm - Check if the specified splat value corresponds to a
04609 /// valid vector constant for a NEON instruction with a "modified immediate"
04610 /// operand (e.g., VMOV).  If so, return the encoded value.
04611 static SDValue isNEONModifiedImm(uint64_t SplatBits, uint64_t SplatUndef,
04612                                  unsigned SplatBitSize, SelectionDAG &DAG,
04613                                  EVT &VT, bool is128Bits, NEONModImmType type) {
04614   unsigned OpCmode, Imm;
04615 
04616   // SplatBitSize is set to the smallest size that splats the vector, so a
04617   // zero vector will always have SplatBitSize == 8.  However, NEON modified
04618   // immediate instructions others than VMOV do not support the 8-bit encoding
04619   // of a zero vector, and the default encoding of zero is supposed to be the
04620   // 32-bit version.
04621   if (SplatBits == 0)
04622     SplatBitSize = 32;
04623 
04624   switch (SplatBitSize) {
04625   case 8:
04626     if (type != VMOVModImm)
04627       return SDValue();
04628     // Any 1-byte value is OK.  Op=0, Cmode=1110.
04629     assert((SplatBits & ~0xff) == 0 && "one byte splat value is too big");
04630     OpCmode = 0xe;
04631     Imm = SplatBits;
04632     VT = is128Bits ? MVT::v16i8 : MVT::v8i8;
04633     break;
04634 
04635   case 16:
04636     // NEON's 16-bit VMOV supports splat values where only one byte is nonzero.
04637     VT = is128Bits ? MVT::v8i16 : MVT::v4i16;
04638     if ((SplatBits & ~0xff) == 0) {
04639       // Value = 0x00nn: Op=x, Cmode=100x.
04640       OpCmode = 0x8;
04641       Imm = SplatBits;
04642       break;
04643     }
04644     if ((SplatBits & ~0xff00) == 0) {
04645       // Value = 0xnn00: Op=x, Cmode=101x.
04646       OpCmode = 0xa;
04647       Imm = SplatBits >> 8;
04648       break;
04649     }
04650     return SDValue();
04651 
04652   case 32:
04653     // NEON's 32-bit VMOV supports splat values where:
04654     // * only one byte is nonzero, or
04655     // * the least significant byte is 0xff and the second byte is nonzero, or
04656     // * the least significant 2 bytes are 0xff and the third is nonzero.
04657     VT = is128Bits ? MVT::v4i32 : MVT::v2i32;
04658     if ((SplatBits & ~0xff) == 0) {
04659       // Value = 0x000000nn: Op=x, Cmode=000x.
04660       OpCmode = 0;
04661       Imm = SplatBits;
04662       break;
04663     }
04664     if ((SplatBits & ~0xff00) == 0) {
04665       // Value = 0x0000nn00: Op=x, Cmode=001x.
04666       OpCmode = 0x2;
04667       Imm = SplatBits >> 8;
04668       break;
04669     }
04670     if ((SplatBits & ~0xff0000) == 0) {
04671       // Value = 0x00nn0000: Op=x, Cmode=010x.
04672       OpCmode = 0x4;
04673       Imm = SplatBits >> 16;
04674       break;
04675     }
04676     if ((SplatBits & ~0xff000000) == 0) {
04677       // Value = 0xnn000000: Op=x, Cmode=011x.
04678       OpCmode = 0x6;
04679       Imm = SplatBits >> 24;
04680       break;
04681     }
04682 
04683     // cmode == 0b1100 and cmode == 0b1101 are not supported for VORR or VBIC
04684     if (type == OtherModImm) return SDValue();
04685 
04686     if ((SplatBits & ~0xffff) == 0 &&
04687         ((SplatBits | SplatUndef) & 0xff) == 0xff) {
04688       // Value = 0x0000nnff: Op=x, Cmode=1100.
04689       OpCmode = 0xc;
04690       Imm = SplatBits >> 8;
04691       break;
04692     }
04693 
04694     if ((SplatBits & ~0xffffff) == 0 &&
04695         ((SplatBits | SplatUndef) & 0xffff) == 0xffff) {
04696       // Value = 0x00nnffff: Op=x, Cmode=1101.
04697       OpCmode = 0xd;
04698       Imm = SplatBits >> 16;
04699       break;
04700     }
04701 
04702     // Note: there are a few 32-bit splat values (specifically: 00ffff00,
04703     // ff000000, ff0000ff, and ffff00ff) that are valid for VMOV.I64 but not
04704     // VMOV.I32.  A (very) minor optimization would be to replicate the value
04705     // and fall through here to test for a valid 64-bit splat.  But, then the
04706     // caller would also need to check and handle the change in size.
04707     return SDValue();
04708 
04709   case 64: {
04710     if (type != VMOVModImm)
04711       return SDValue();
04712     // NEON has a 64-bit VMOV splat where each byte is either 0 or 0xff.
04713     uint64_t BitMask = 0xff;
04714     uint64_t Val = 0;
04715     unsigned ImmMask = 1;
04716     Imm = 0;
04717     for (int ByteNum = 0; ByteNum < 8; ++ByteNum) {
04718       if (((SplatBits | SplatUndef) & BitMask) == BitMask) {
04719         Val |= BitMask;
04720         Imm |= ImmMask;
04721       } else if ((SplatBits & BitMask) != 0) {
04722         return SDValue();
04723       }
04724       BitMask <<= 8;
04725       ImmMask <<= 1;
04726     }
04727 
04728     if (DAG.getTargetLoweringInfo().isBigEndian())
04729       // swap higher and lower 32 bit word
04730       Imm = ((Imm & 0xf) << 4) | ((Imm & 0xf0) >> 4);
04731 
04732     // Op=1, Cmode=1110.
04733     OpCmode = 0x1e;
04734     VT = is128Bits ? MVT::v2i64 : MVT::v1i64;
04735     break;
04736   }
04737 
04738   default:
04739     llvm_unreachable("unexpected size for isNEONModifiedImm");
04740   }
04741 
04742   unsigned EncodedVal = ARM_AM::createNEONModImm(OpCmode, Imm);
04743   return DAG.getTargetConstant(EncodedVal, MVT::i32);
04744 }
04745 
04746 SDValue ARMTargetLowering::LowerConstantFP(SDValue Op, SelectionDAG &DAG,
04747                                            const ARMSubtarget *ST) const {
04748   if (!ST->hasVFP3())
04749     return SDValue();
04750 
04751   bool IsDouble = Op.getValueType() == MVT::f64;
04752   ConstantFPSDNode *CFP = cast<ConstantFPSDNode>(Op);
04753 
04754   // Use the default (constant pool) lowering for double constants when we have
04755   // an SP-only FPU
04756   if (IsDouble && Subtarget->isFPOnlySP())
04757     return SDValue();
04758 
04759   // Try splatting with a VMOV.f32...
04760   APFloat FPVal = CFP->getValueAPF();
04761   int ImmVal = IsDouble ? ARM_AM::getFP64Imm(FPVal) : ARM_AM::getFP32Imm(FPVal);
04762 
04763   if (ImmVal != -1) {
04764     if (IsDouble || !ST->useNEONForSinglePrecisionFP()) {
04765       // We have code in place to select a valid ConstantFP already, no need to
04766       // do any mangling.
04767       return Op;
04768     }
04769 
04770     // It's a float and we are trying to use NEON operations where
04771     // possible. Lower it to a splat followed by an extract.
04772     SDLoc DL(Op);
04773     SDValue NewVal = DAG.getTargetConstant(ImmVal, MVT::i32);
04774     SDValue VecConstant = DAG.getNode(ARMISD::VMOVFPIMM, DL, MVT::v2f32,
04775                                       NewVal);
04776     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32, VecConstant,
04777                        DAG.getConstant(0, MVT::i32));
04778   }
04779 
04780   // The rest of our options are NEON only, make sure that's allowed before
04781   // proceeding..
04782   if (!ST->hasNEON() || (!IsDouble && !ST->useNEONForSinglePrecisionFP()))
04783     return SDValue();
04784 
04785   EVT VMovVT;
04786   uint64_t iVal = FPVal.bitcastToAPInt().getZExtValue();
04787 
04788   // It wouldn't really be worth bothering for doubles except for one very
04789   // important value, which does happen to match: 0.0. So make sure we don't do
04790   // anything stupid.
04791   if (IsDouble && (iVal & 0xffffffff) != (iVal >> 32))
04792     return SDValue();
04793 
04794   // Try a VMOV.i32 (FIXME: i8, i16, or i64 could work too).
04795   SDValue NewVal = isNEONModifiedImm(iVal & 0xffffffffU, 0, 32, DAG, VMovVT,
04796                                      false, VMOVModImm);
04797   if (NewVal != SDValue()) {
04798     SDLoc DL(Op);
04799     SDValue VecConstant = DAG.getNode(ARMISD::VMOVIMM, DL, VMovVT,
04800                                       NewVal);
04801     if (IsDouble)
04802       return DAG.getNode(ISD::BITCAST, DL, MVT::f64, VecConstant);
04803 
04804     // It's a float: cast and extract a vector element.
04805     SDValue VecFConstant = DAG.getNode(ISD::BITCAST, DL, MVT::v2f32,
04806                                        VecConstant);
04807     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32, VecFConstant,
04808                        DAG.getConstant(0, MVT::i32));
04809   }
04810 
04811   // Finally, try a VMVN.i32
04812   NewVal = isNEONModifiedImm(~iVal & 0xffffffffU, 0, 32, DAG, VMovVT,
04813                              false, VMVNModImm);
04814   if (NewVal != SDValue()) {
04815     SDLoc DL(Op);
04816     SDValue VecConstant = DAG.getNode(ARMISD::VMVNIMM, DL, VMovVT, NewVal);
04817 
04818     if (IsDouble)
04819       return DAG.getNode(ISD::BITCAST, DL, MVT::f64, VecConstant);
04820 
04821     // It's a float: cast and extract a vector element.
04822     SDValue VecFConstant = DAG.getNode(ISD::BITCAST, DL, MVT::v2f32,
04823                                        VecConstant);
04824     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32, VecFConstant,
04825                        DAG.getConstant(0, MVT::i32));
04826   }
04827 
04828   return SDValue();
04829 }
04830 
04831 // check if an VEXT instruction can handle the shuffle mask when the
04832 // vector sources of the shuffle are the same.
04833 static bool isSingletonVEXTMask(ArrayRef<int> M, EVT VT, unsigned &Imm) {
04834   unsigned NumElts = VT.getVectorNumElements();
04835 
04836   // Assume that the first shuffle index is not UNDEF.  Fail if it is.
04837   if (M[0] < 0)
04838     return false;
04839 
04840   Imm = M[0];
04841 
04842   // If this is a VEXT shuffle, the immediate value is the index of the first
04843   // element.  The other shuffle indices must be the successive elements after
04844   // the first one.
04845   unsigned ExpectedElt = Imm;
04846   for (unsigned i = 1; i < NumElts; ++i) {
04847     // Increment the expected index.  If it wraps around, just follow it
04848     // back to index zero and keep going.
04849     ++ExpectedElt;
04850     if (ExpectedElt == NumElts)
04851       ExpectedElt = 0;
04852 
04853     if (M[i] < 0) continue; // ignore UNDEF indices
04854     if (ExpectedElt != static_cast<unsigned>(M[i]))
04855       return false;
04856   }
04857 
04858   return true;
04859 }
04860 
04861 
04862 static bool isVEXTMask(ArrayRef<int> M, EVT VT,
04863                        bool &ReverseVEXT, unsigned &Imm) {
04864   unsigned NumElts = VT.getVectorNumElements();
04865   ReverseVEXT = false;
04866 
04867   // Assume that the first shuffle index is not UNDEF.  Fail if it is.
04868   if (M[0] < 0)
04869     return false;
04870 
04871   Imm = M[0];
04872 
04873   // If this is a VEXT shuffle, the immediate value is the index of the first
04874   // element.  The other shuffle indices must be the successive elements after
04875   // the first one.
04876   unsigned ExpectedElt = Imm;
04877   for (unsigned i = 1; i < NumElts; ++i) {
04878     // Increment the expected index.  If it wraps around, it may still be
04879     // a VEXT but the source vectors must be swapped.
04880     ExpectedElt += 1;
04881     if (ExpectedElt == NumElts * 2) {
04882       ExpectedElt = 0;
04883       ReverseVEXT = true;
04884     }
04885 
04886     if (M[i] < 0) continue; // ignore UNDEF indices
04887     if (ExpectedElt != static_cast<unsigned>(M[i]))
04888       return false;
04889   }
04890 
04891   // Adjust the index value if the source operands will be swapped.
04892   if (ReverseVEXT)
04893     Imm -= NumElts;
04894 
04895   return true;
04896 }
04897 
04898 /// isVREVMask - Check if a vector shuffle corresponds to a VREV
04899 /// instruction with the specified blocksize.  (The order of the elements
04900 /// within each block of the vector is reversed.)
04901 static bool isVREVMask(ArrayRef<int> M, EVT VT, unsigned BlockSize) {
04902   assert((BlockSize==16 || BlockSize==32 || BlockSize==64) &&
04903          "Only possible block sizes for VREV are: 16, 32, 64");
04904 
04905   unsigned EltSz = VT.getVectorElementType().getSizeInBits();
04906   if (EltSz == 64)
04907     return false;
04908 
04909   unsigned NumElts = VT.getVectorNumElements();
04910   unsigned BlockElts = M[0] + 1;
04911   // If the first shuffle index is UNDEF, be optimistic.
04912   if (M[0] < 0)
04913     BlockElts = BlockSize / EltSz;
04914 
04915   if (BlockSize <= EltSz || BlockSize != BlockElts * EltSz)
04916     return false;
04917 
04918   for (unsigned i = 0; i < NumElts; ++i) {
04919     if (M[i] < 0) continue; // ignore UNDEF indices
04920     if ((unsigned) M[i] != (i - i%BlockElts) + (BlockElts - 1 - i%BlockElts))
04921       return false;
04922   }
04923 
04924   return true;
04925 }
04926 
04927 static bool isVTBLMask(ArrayRef<int> M, EVT VT) {
04928   // We can handle <8 x i8> vector shuffles. If the index in the mask is out of
04929   // range, then 0 is placed into the resulting vector. So pretty much any mask
04930   // of 8 elements can work here.
04931   return VT == MVT::v8i8 && M.size() == 8;
04932 }
04933 
04934 static bool isVTRNMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
04935   unsigned EltSz = VT.getVectorElementType().getSizeInBits();
04936   if (EltSz == 64)
04937     return false;
04938 
04939   unsigned NumElts = VT.getVectorNumElements();
04940   WhichResult = (M[0] == 0 ? 0 : 1);
04941   for (unsigned i = 0; i < NumElts; i += 2) {
04942     if ((M[i] >= 0 && (unsigned) M[i] != i + WhichResult) ||
04943         (M[i+1] >= 0 && (unsigned) M[i+1] != i + NumElts + WhichResult))
04944       return false;
04945   }
04946   return true;
04947 }
04948 
04949 /// isVTRN_v_undef_Mask - Special case of isVTRNMask for canonical form of
04950 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef".
04951 /// Mask is e.g., <0, 0, 2, 2> instead of <0, 4, 2, 6>.
04952 static bool isVTRN_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult){
04953   unsigned EltSz = VT.getVectorElementType().getSizeInBits();
04954   if (EltSz == 64)
04955     return false;
04956 
04957   unsigned NumElts = VT.getVectorNumElements();
04958   WhichResult = (M[0] == 0 ? 0 : 1);
04959   for (unsigned i = 0; i < NumElts; i += 2) {
04960     if ((M[i] >= 0 && (unsigned) M[i] != i + WhichResult) ||
04961         (M[i+1] >= 0 && (unsigned) M[i+1] != i + WhichResult))
04962       return false;
04963   }
04964   return true;
04965 }
04966 
04967 static bool isVUZPMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
04968   unsigned EltSz = VT.getVectorElementType().getSizeInBits();
04969   if (EltSz == 64)
04970     return false;
04971 
04972   unsigned NumElts = VT.getVectorNumElements();
04973   WhichResult = (M[0] == 0 ? 0 : 1);
04974   for (unsigned i = 0; i != NumElts; ++i) {
04975     if (M[i] < 0) continue; // ignore UNDEF indices
04976     if ((unsigned) M[i] != 2 * i + WhichResult)
04977       return false;
04978   }
04979 
04980   // VUZP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32.
04981   if (VT.is64BitVector() && EltSz == 32)
04982     return false;
04983 
04984   return true;
04985 }
04986 
04987 /// isVUZP_v_undef_Mask - Special case of isVUZPMask for canonical form of
04988 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef".
04989 /// Mask is e.g., <0, 2, 0, 2> instead of <0, 2, 4, 6>,
04990 static bool isVUZP_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult){
04991   unsigned EltSz = VT.getVectorElementType().getSizeInBits();
04992   if (EltSz == 64)
04993     return false;
04994 
04995   unsigned Half = VT.getVectorNumElements() / 2;
04996   WhichResult = (M[0] == 0 ? 0 : 1);
04997   for (unsigned j = 0; j != 2; ++j) {
04998     unsigned Idx = WhichResult;
04999     for (unsigned i = 0; i != Half; ++i) {
05000       int MIdx = M[i + j * Half];
05001       if (MIdx >= 0 && (unsigned) MIdx != Idx)
05002         return false;
05003       Idx += 2;
05004     }
05005   }
05006 
05007   // VUZP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32.
05008   if (VT.is64BitVector() && EltSz == 32)
05009     return false;
05010 
05011   return true;
05012 }
05013 
05014 static bool isVZIPMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
05015   unsigned EltSz = VT.getVectorElementType().getSizeInBits();
05016   if (EltSz == 64)
05017     return false;
05018 
05019   unsigned NumElts = VT.getVectorNumElements();
05020   WhichResult = (M[0] == 0 ? 0 : 1);
05021   unsigned Idx = WhichResult * NumElts / 2;
05022   for (unsigned i = 0; i != NumElts; i += 2) {
05023     if ((M[i] >= 0 && (unsigned) M[i] != Idx) ||
05024         (M[i+1] >= 0 && (unsigned) M[i+1] != Idx + NumElts))
05025       return false;
05026     Idx += 1;
05027   }
05028 
05029   // VZIP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32.
05030   if (VT.is64BitVector() && EltSz == 32)
05031     return false;
05032 
05033   return true;
05034 }
05035 
05036 /// isVZIP_v_undef_Mask - Special case of isVZIPMask for canonical form of
05037 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef".
05038 /// Mask is e.g., <0, 0, 1, 1> instead of <0, 4, 1, 5>.
05039 static bool isVZIP_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult){
05040   unsigned EltSz = VT.getVectorElementType().getSizeInBits();
05041   if (EltSz == 64)
05042     return false;
05043 
05044   unsigned NumElts = VT.getVectorNumElements();
05045   WhichResult = (M[0] == 0 ? 0 : 1);
05046   unsigned Idx = WhichResult * NumElts / 2;
05047   for (unsigned i = 0; i != NumElts; i += 2) {
05048     if ((M[i] >= 0 && (unsigned) M[i] != Idx) ||
05049         (M[i+1] >= 0 && (unsigned) M[i+1] != Idx))
05050       return false;
05051     Idx += 1;
05052   }
05053 
05054   // VZIP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32.
05055   if (VT.is64BitVector() && EltSz == 32)
05056     return false;
05057 
05058   return true;
05059 }
05060 
05061 /// \return true if this is a reverse operation on an vector.
05062 static bool isReverseMask(ArrayRef<int> M, EVT VT) {
05063   unsigned NumElts = VT.getVectorNumElements();
05064   // Make sure the mask has the right size.
05065   if (NumElts != M.size())
05066       return false;
05067 
05068   // Look for <15, ..., 3, -1, 1, 0>.
05069   for (unsigned i = 0; i != NumElts; ++i)
05070     if (M[i] >= 0 && M[i] != (int) (NumElts - 1 - i))
05071       return false;
05072 
05073   return true;
05074 }
05075 
05076 // If N is an integer constant that can be moved into a register in one
05077 // instruction, return an SDValue of such a constant (will become a MOV
05078 // instruction).  Otherwise return null.
05079 static SDValue IsSingleInstrConstant(SDValue N, SelectionDAG &DAG,
05080                                      const ARMSubtarget *ST, SDLoc dl) {
05081   uint64_t Val;
05082   if (!isa<ConstantSDNode>(N))
05083     return SDValue();
05084   Val = cast<ConstantSDNode>(N)->getZExtValue();
05085 
05086   if (ST->isThumb1Only()) {
05087     if (Val <= 255 || ~Val <= 255)
05088       return DAG.getConstant(Val, MVT::i32);
05089   } else {
05090     if (ARM_AM::getSOImmVal(Val) != -1 || ARM_AM::getSOImmVal(~Val) != -1)
05091       return DAG.getConstant(Val, MVT::i32);
05092   }
05093   return SDValue();
05094 }
05095 
05096 // If this is a case we can't handle, return null and let the default
05097 // expansion code take care of it.
05098 SDValue ARMTargetLowering::LowerBUILD_VECTOR(SDValue Op, SelectionDAG &DAG,
05099                                              const ARMSubtarget *ST) const {
05100   BuildVectorSDNode *BVN = cast<BuildVectorSDNode>(Op.getNode());
05101   SDLoc dl(Op);
05102   EVT VT = Op.getValueType();
05103 
05104   APInt SplatBits, SplatUndef;
05105   unsigned SplatBitSize;
05106   bool HasAnyUndefs;
05107   if (BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs)) {
05108     if (SplatBitSize <= 64) {
05109       // Check if an immediate VMOV works.
05110       EVT VmovVT;
05111       SDValue Val = isNEONModifiedImm(SplatBits.getZExtValue(),
05112                                       SplatUndef.getZExtValue(), SplatBitSize,
05113                                       DAG, VmovVT, VT.is128BitVector(),
05114                                       VMOVModImm);
05115       if (Val.getNode()) {
05116         SDValue Vmov = DAG.getNode(ARMISD::VMOVIMM, dl, VmovVT, Val);
05117         return DAG.getNode(ISD::BITCAST, dl, VT, Vmov);
05118       }
05119 
05120       // Try an immediate VMVN.
05121       uint64_t NegatedImm = (~SplatBits).getZExtValue();
05122       Val = isNEONModifiedImm(NegatedImm,
05123                                       SplatUndef.getZExtValue(), SplatBitSize,
05124                                       DAG, VmovVT, VT.is128BitVector(),
05125                                       VMVNModImm);
05126       if (Val.getNode()) {
05127         SDValue Vmov = DAG.getNode(ARMISD::VMVNIMM, dl, VmovVT, Val);
05128         return DAG.getNode(ISD::BITCAST, dl, VT, Vmov);
05129       }
05130 
05131       // Use vmov.f32 to materialize other v2f32 and v4f32 splats.
05132       if ((VT == MVT::v2f32 || VT == MVT::v4f32) && SplatBitSize == 32) {
05133         int ImmVal = ARM_AM::getFP32Imm(SplatBits);
05134         if (ImmVal != -1) {
05135           SDValue Val = DAG.getTargetConstant(ImmVal, MVT::i32);
05136           return DAG.getNode(ARMISD::VMOVFPIMM, dl, VT, Val);
05137         }
05138       }
05139     }
05140   }
05141 
05142   // Scan through the operands to see if only one value is used.
05143   //
05144   // As an optimisation, even if more than one value is used it may be more
05145   // profitable to splat with one value then change some lanes.
05146   //
05147   // Heuristically we decide to do this if the vector has a "dominant" value,
05148   // defined as splatted to more than half of the lanes.
05149   unsigned NumElts = VT.getVectorNumElements();
05150   bool isOnlyLowElement = true;
05151   bool usesOnlyOneValue = true;
05152   bool hasDominantValue = false;
05153   bool isConstant = true;
05154 
05155   // Map of the number of times a particular SDValue appears in the
05156   // element list.
05157   DenseMap<SDValue, unsigned> ValueCounts;
05158   SDValue Value;
05159   for (unsigned i = 0; i < NumElts; ++i) {
05160     SDValue V = Op.getOperand(i);
05161     if (V.getOpcode() == ISD::UNDEF)
05162       continue;
05163     if (i > 0)
05164       isOnlyLowElement = false;
05165     if (!isa<ConstantFPSDNode>(V) && !isa<ConstantSDNode>(V))
05166       isConstant = false;
05167 
05168     ValueCounts.insert(std::make_pair(V, 0));
05169     unsigned &Count = ValueCounts[V];
05170 
05171     // Is this value dominant? (takes up more than half of the lanes)
05172     if (++Count > (NumElts / 2)) {
05173       hasDominantValue = true;
05174       Value = V;
05175     }
05176   }
05177   if (ValueCounts.size() != 1)
05178     usesOnlyOneValue = false;
05179   if (!Value.getNode() && ValueCounts.size() > 0)
05180     Value = ValueCounts.begin()->first;
05181 
05182   if (ValueCounts.size() == 0)
05183     return DAG.getUNDEF(VT);
05184 
05185   // Loads are better lowered with insert_vector_elt/ARMISD::BUILD_VECTOR.
05186   // Keep going if we are hitting this case.
05187   if (isOnlyLowElement && !ISD::isNormalLoad(Value.getNode()))
05188     return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Value);
05189 
05190   unsigned EltSize = VT.getVectorElementType().getSizeInBits();
05191 
05192   // Use VDUP for non-constant splats.  For f32 constant splats, reduce to
05193   // i32 and try again.
05194   if (hasDominantValue && EltSize <= 32) {
05195     if (!isConstant) {
05196       SDValue N;
05197 
05198       // If we are VDUPing a value that comes directly from a vector, that will
05199       // cause an unnecessary move to and from a GPR, where instead we could
05200       // just use VDUPLANE. We can only do this if the lane being extracted
05201       // is at a constant index, as the VDUP from lane instructions only have
05202       // constant-index forms.
05203       if (Value->getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
05204           isa<ConstantSDNode>(Value->getOperand(1))) {
05205         // We need to create a new undef vector to use for the VDUPLANE if the
05206         // size of the vector from which we get the value is different than the
05207         // size of the vector that we need to create. We will insert the element
05208         // such that the register coalescer will remove unnecessary copies.
05209         if (VT != Value->getOperand(0).getValueType()) {
05210           ConstantSDNode *constIndex;
05211           constIndex = dyn_cast<ConstantSDNode>(Value->getOperand(1));
05212           assert(constIndex && "The index is not a constant!");
05213           unsigned index = constIndex->getAPIntValue().getLimitedValue() %
05214                              VT.getVectorNumElements();
05215           N =  DAG.getNode(ARMISD::VDUPLANE, dl, VT,
05216                  DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, DAG.getUNDEF(VT),
05217                         Value, DAG.getConstant(index, MVT::i32)),
05218                            DAG.getConstant(index, MVT::i32));
05219         } else
05220           N = DAG.getNode(ARMISD::VDUPLANE, dl, VT,
05221                         Value->getOperand(0), Value->getOperand(1));
05222       } else
05223         N = DAG.getNode(ARMISD::VDUP, dl, VT, Value);
05224 
05225       if (!usesOnlyOneValue) {
05226         // The dominant value was splatted as 'N', but we now have to insert
05227         // all differing elements.
05228         for (unsigned I = 0; I < NumElts; ++I) {
05229           if (Op.getOperand(I) == Value)
05230             continue;
05231           SmallVector<SDValue, 3> Ops;
05232           Ops.push_back(N);
05233           Ops.push_back(Op.getOperand(I));
05234           Ops.push_back(DAG.getConstant(I, MVT::i32));
05235           N = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Ops);
05236         }
05237       }
05238       return N;
05239     }
05240     if (VT.getVectorElementType().isFloatingPoint()) {
05241       SmallVector<SDValue, 8> Ops;
05242       for (unsigned i = 0; i < NumElts; ++i)
05243         Ops.push_back(DAG.getNode(ISD::BITCAST, dl, MVT::i32,
05244                                   Op.getOperand(i)));
05245       EVT VecVT = EVT::getVectorVT(*DAG.getContext(), MVT::i32, NumElts);
05246       SDValue Val = DAG.getNode(ISD::BUILD_VECTOR, dl, VecVT, Ops);
05247       Val = LowerBUILD_VECTOR(Val, DAG, ST);
05248       if (Val.getNode())
05249         return DAG.getNode(ISD::BITCAST, dl, VT, Val);
05250     }
05251     if (usesOnlyOneValue) {
05252       SDValue Val = IsSingleInstrConstant(Value, DAG, ST, dl);
05253       if (isConstant && Val.getNode())
05254         return DAG.getNode(ARMISD::VDUP, dl, VT, Val);
05255     }
05256   }
05257 
05258   // If all elements are constants and the case above didn't get hit, fall back
05259   // to the default expansion, which will generate a load from the constant
05260   // pool.
05261   if (isConstant)
05262     return SDValue();
05263 
05264   // Empirical tests suggest this is rarely worth it for vectors of length <= 2.
05265   if (NumElts >= 4) {
05266     SDValue shuffle = ReconstructShuffle(Op, DAG);
05267     if (shuffle != SDValue())
05268       return shuffle;
05269   }
05270 
05271   // Vectors with 32- or 64-bit elements can be built by directly assigning
05272   // the subregisters.  Lower it to an ARMISD::BUILD_VECTOR so the operands
05273   // will be legalized.
05274   if (EltSize >= 32) {
05275     // Do the expansion with floating-point types, since that is what the VFP
05276     // registers are defined to use, and since i64 is not legal.
05277     EVT EltVT = EVT::getFloatingPointVT(EltSize);
05278     EVT VecVT = EVT::getVectorVT(*DAG.getContext(), EltVT, NumElts);
05279     SmallVector<SDValue, 8> Ops;
05280     for (unsigned i = 0; i < NumElts; ++i)
05281       Ops.push_back(DAG.getNode(ISD::BITCAST, dl, EltVT, Op.getOperand(i)));
05282     SDValue Val = DAG.getNode(ARMISD::BUILD_VECTOR, dl, VecVT, Ops);
05283     return DAG.getNode(ISD::BITCAST, dl, VT, Val);
05284   }
05285 
05286   // If all else fails, just use a sequence of INSERT_VECTOR_ELT when we
05287   // know the default expansion would otherwise fall back on something even
05288   // worse. For a vector with one or two non-undef values, that's
05289   // scalar_to_vector for the elements followed by a shuffle (provided the
05290   // shuffle is valid for the target) and materialization element by element
05291   // on the stack followed by a load for everything else.
05292   if (!isConstant && !usesOnlyOneValue) {
05293     SDValue Vec = DAG.getUNDEF(VT);
05294     for (unsigned i = 0 ; i < NumElts; ++i) {
05295       SDValue V = Op.getOperand(i);
05296       if (V.getOpcode() == ISD::UNDEF)
05297         continue;
05298       SDValue LaneIdx = DAG.getConstant(i, MVT::i32);
05299       Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Vec, V, LaneIdx);
05300     }
05301     return Vec;
05302   }
05303 
05304   return SDValue();
05305 }
05306 
05307 // Gather data to see if the operation can be modelled as a
05308 // shuffle in combination with VEXTs.
05309 SDValue ARMTargetLowering::ReconstructShuffle(SDValue Op,
05310                                               SelectionDAG &DAG) const {
05311   SDLoc dl(Op);
05312   EVT VT = Op.getValueType();
05313   unsigned NumElts = VT.getVectorNumElements();
05314 
05315   SmallVector<SDValue, 2> SourceVecs;
05316   SmallVector<unsigned, 2> MinElts;
05317   SmallVector<unsigned, 2> MaxElts;
05318 
05319   for (unsigned i = 0; i < NumElts; ++i) {
05320     SDValue V = Op.getOperand(i);
05321     if (V.getOpcode() == ISD::UNDEF)
05322       continue;
05323     else if (V.getOpcode() != ISD::EXTRACT_VECTOR_ELT) {
05324       // A shuffle can only come from building a vector from various
05325       // elements of other vectors.
05326       return SDValue();
05327     } else if (V.getOperand(0).getValueType().getVectorElementType() !=
05328                VT.getVectorElementType()) {
05329       // This code doesn't know how to handle shuffles where the vector
05330       // element types do not match (this happens because type legalization
05331       // promotes the return type of EXTRACT_VECTOR_ELT).
05332       // FIXME: It might be appropriate to extend this code to handle
05333       // mismatched types.
05334       return SDValue();
05335     }
05336 
05337     // Record this extraction against the appropriate vector if possible...
05338     SDValue SourceVec = V.getOperand(0);
05339     // If the element number isn't a constant, we can't effectively
05340     // analyze what's going on.
05341     if (!isa<ConstantSDNode>(V.getOperand(1)))
05342       return SDValue();
05343     unsigned EltNo = cast<ConstantSDNode>(V.getOperand(1))->getZExtValue();
05344     bool FoundSource = false;
05345     for (unsigned j = 0; j < SourceVecs.size(); ++j) {
05346       if (SourceVecs[j] == SourceVec) {
05347         if (MinElts[j] > EltNo)
05348           MinElts[j] = EltNo;
05349         if (MaxElts[j] < EltNo)
05350           MaxElts[j] = EltNo;
05351         FoundSource = true;
05352         break;
05353       }
05354     }
05355 
05356     // Or record a new source if not...
05357     if (!FoundSource) {
05358       SourceVecs.push_back(SourceVec);
05359       MinElts.push_back(EltNo);
05360       MaxElts.push_back(EltNo);
05361     }
05362   }
05363 
05364   // Currently only do something sane when at most two source vectors
05365   // involved.
05366   if (SourceVecs.size() > 2)
05367     return SDValue();
05368 
05369   SDValue ShuffleSrcs[2] = {DAG.getUNDEF(VT), DAG.getUNDEF(VT) };
05370   int VEXTOffsets[2] = {0, 0};
05371 
05372   // This loop extracts the usage patterns of the source vectors
05373   // and prepares appropriate SDValues for a shuffle if possible.
05374   for (unsigned i = 0; i < SourceVecs.size(); ++i) {
05375     if (SourceVecs[i].getValueType() == VT) {
05376       // No VEXT necessary
05377       ShuffleSrcs[i] = SourceVecs[i];
05378       VEXTOffsets[i] = 0;
05379       continue;
05380     } else if (SourceVecs[i].getValueType().getVectorNumElements() < NumElts) {
05381       // It probably isn't worth padding out a smaller vector just to
05382       // break it down again in a shuffle.
05383       return SDValue();
05384     }
05385 
05386     // Since only 64-bit and 128-bit vectors are legal on ARM and
05387     // we've eliminated the other cases...
05388     assert(SourceVecs[i].getValueType().getVectorNumElements() == 2*NumElts &&
05389            "unexpected vector sizes in ReconstructShuffle");
05390 
05391     if (MaxElts[i] - MinElts[i] >= NumElts) {
05392       // Span too large for a VEXT to cope
05393       return SDValue();
05394     }
05395 
05396     if (MinElts[i] >= NumElts) {
05397       // The extraction can just take the second half
05398       VEXTOffsets[i] = NumElts;
05399       ShuffleSrcs[i] = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT,
05400                                    SourceVecs[i],
05401                                    DAG.getIntPtrConstant(NumElts));
05402     } else if (MaxElts[i] < NumElts) {
05403       // The extraction can just take the first half
05404       VEXTOffsets[i] = 0;
05405       ShuffleSrcs[i] = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT,
05406                                    SourceVecs[i],
05407                                    DAG.getIntPtrConstant(0));
05408     } else {
05409       // An actual VEXT is needed
05410       VEXTOffsets[i] = MinElts[i];
05411       SDValue VEXTSrc1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT,
05412                                      SourceVecs[i],
05413                                      DAG.getIntPtrConstant(0));
05414       SDValue VEXTSrc2 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT,
05415                                      SourceVecs[i],
05416                                      DAG.getIntPtrConstant(NumElts));
05417       ShuffleSrcs[i] = DAG.getNode(ARMISD::VEXT, dl, VT, VEXTSrc1, VEXTSrc2,
05418                                    DAG.getConstant(VEXTOffsets[i], MVT::i32));
05419     }
05420   }
05421 
05422   SmallVector<int, 8> Mask;
05423 
05424   for (unsigned i = 0; i < NumElts; ++i) {
05425     SDValue Entry = Op.getOperand(i);
05426     if (Entry.getOpcode() == ISD::UNDEF) {
05427       Mask.push_back(-1);
05428       continue;
05429     }
05430 
05431     SDValue ExtractVec = Entry.getOperand(0);
05432     int ExtractElt = cast<ConstantSDNode>(Op.getOperand(i)
05433                                           .getOperand(1))->getSExtValue();
05434     if (ExtractVec == SourceVecs[0]) {
05435       Mask.push_back(ExtractElt - VEXTOffsets[0]);
05436     } else {
05437       Mask.push_back(ExtractElt + NumElts - VEXTOffsets[1]);
05438     }
05439   }