Home | History | Annotate | Download | only in ARM
      1 //===-- ARMISelLowering.cpp - ARM DAG Lowering Implementation -------------===//
      2 //
      3 //                     The LLVM Compiler Infrastructure
      4 //
      5 // This file is distributed under the University of Illinois Open Source
      6 // License. See LICENSE.TXT for details.
      7 //
      8 //===----------------------------------------------------------------------===//
      9 //
     10 // This file defines the interfaces that ARM uses to lower LLVM code into a
     11 // selection DAG.
     12 //
     13 //===----------------------------------------------------------------------===//
     14 
     15 #define DEBUG_TYPE "arm-isel"
     16 #include "ARMISelLowering.h"
     17 #include "ARM.h"
     18 #include "ARMCallingConv.h"
     19 #include "ARMConstantPoolValue.h"
     20 #include "ARMMachineFunctionInfo.h"
     21 #include "ARMPerfectShuffle.h"
     22 #include "ARMSubtarget.h"
     23 #include "ARMTargetMachine.h"
     24 #include "ARMTargetObjectFile.h"
     25 #include "MCTargetDesc/ARMAddressingModes.h"
     26 #include "llvm/ADT/Statistic.h"
     27 #include "llvm/ADT/StringExtras.h"
     28 #include "llvm/CodeGen/CallingConvLower.h"
     29 #include "llvm/CodeGen/IntrinsicLowering.h"
     30 #include "llvm/CodeGen/MachineBasicBlock.h"
     31 #include "llvm/CodeGen/MachineFrameInfo.h"
     32 #include "llvm/CodeGen/MachineFunction.h"
     33 #include "llvm/CodeGen/MachineInstrBuilder.h"
     34 #include "llvm/CodeGen/MachineModuleInfo.h"
     35 #include "llvm/CodeGen/MachineRegisterInfo.h"
     36 #include "llvm/CodeGen/SelectionDAG.h"
     37 #include "llvm/IR/CallingConv.h"
     38 #include "llvm/IR/Constants.h"
     39 #include "llvm/IR/Function.h"
     40 #include "llvm/IR/GlobalValue.h"
     41 #include "llvm/IR/Instruction.h"
     42 #include "llvm/IR/Instructions.h"
     43 #include "llvm/IR/Intrinsics.h"
     44 #include "llvm/IR/Type.h"
     45 #include "llvm/MC/MCSectionMachO.h"
     46 #include "llvm/Support/CommandLine.h"
     47 #include "llvm/Support/ErrorHandling.h"
     48 #include "llvm/Support/MathExtras.h"
     49 #include "llvm/Support/raw_ostream.h"
     50 #include "llvm/Target/TargetOptions.h"
     51 using namespace llvm;
     52 
     53 STATISTIC(NumTailCalls, "Number of tail calls");
     54 STATISTIC(NumMovwMovt, "Number of GAs materialized with movw + movt");
     55 STATISTIC(NumLoopByVals, "Number of loops generated for byval arguments");
     56 
     57 // This option should go away when tail calls fully work.
     58 static cl::opt<bool>
     59 EnableARMTailCalls("arm-tail-calls", cl::Hidden,
     60   cl::desc("Generate tail calls (TEMPORARY OPTION)."),
     61   cl::init(false));
     62 
     63 cl::opt<bool>
     64 EnableARMLongCalls("arm-long-calls", cl::Hidden,
     65   cl::desc("Generate calls via indirect call instructions"),
     66   cl::init(false));
     67 
     68 static cl::opt<bool>
     69 ARMInterworking("arm-interworking", cl::Hidden,
     70   cl::desc("Enable / disable ARM interworking (for debugging only)"),
     71   cl::init(true));
     72 
     73 namespace {
     74   class ARMCCState : public CCState {
     75   public:
     76     ARMCCState(CallingConv::ID CC, bool isVarArg, MachineFunction &MF,
     77                const TargetMachine &TM, SmallVectorImpl<CCValAssign> &locs,
     78                LLVMContext &C, ParmContext PC)
     79         : CCState(CC, isVarArg, MF, TM, locs, C) {
     80       assert(((PC == Call) || (PC == Prologue)) &&
     81              "ARMCCState users must specify whether their context is call"
     82              "or prologue generation.");
     83       CallOrPrologue = PC;
     84     }
     85   };
     86 }
     87 
     88 // The APCS parameter registers.
     89 static const uint16_t GPRArgRegs[] = {
     90   ARM::R0, ARM::R1, ARM::R2, ARM::R3
     91 };
     92 
     93 void ARMTargetLowering::addTypeForNEON(MVT VT, MVT PromotedLdStVT,
     94                                        MVT PromotedBitwiseVT) {
     95   if (VT != PromotedLdStVT) {
     96     setOperationAction(ISD::LOAD, VT, Promote);
     97     AddPromotedToType (ISD::LOAD, VT, PromotedLdStVT);
     98 
     99     setOperationAction(ISD::STORE, VT, Promote);
    100     AddPromotedToType (ISD::STORE, VT, PromotedLdStVT);
    101   }
    102 
    103   MVT ElemTy = VT.getVectorElementType();
    104   if (ElemTy != MVT::i64 && ElemTy != MVT::f64)
    105     setOperationAction(ISD::SETCC, VT, Custom);
    106   setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Custom);
    107   setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
    108   if (ElemTy == MVT::i32) {
    109     setOperationAction(ISD::SINT_TO_FP, VT, Custom);
    110     setOperationAction(ISD::UINT_TO_FP, VT, Custom);
    111     setOperationAction(ISD::FP_TO_SINT, VT, Custom);
    112     setOperationAction(ISD::FP_TO_UINT, VT, Custom);
    113   } else {
    114     setOperationAction(ISD::SINT_TO_FP, VT, Expand);
    115     setOperationAction(ISD::UINT_TO_FP, VT, Expand);
    116     setOperationAction(ISD::FP_TO_SINT, VT, Expand);
    117     setOperationAction(ISD::FP_TO_UINT, VT, Expand);
    118   }
    119   setOperationAction(ISD::BUILD_VECTOR,      VT, Custom);
    120   setOperationAction(ISD::VECTOR_SHUFFLE,    VT, Custom);
    121   setOperationAction(ISD::CONCAT_VECTORS,    VT, Legal);
    122   setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Legal);
    123   setOperationAction(ISD::SELECT,            VT, Expand);
    124   setOperationAction(ISD::SELECT_CC,         VT, Expand);
    125   setOperationAction(ISD::VSELECT,           VT, Expand);
    126   setOperationAction(ISD::SIGN_EXTEND_INREG, VT, Expand);
    127   if (VT.isInteger()) {
    128     setOperationAction(ISD::SHL, VT, Custom);
    129     setOperationAction(ISD::SRA, VT, Custom);
    130     setOperationAction(ISD::SRL, VT, Custom);
    131   }
    132 
    133   // Promote all bit-wise operations.
    134   if (VT.isInteger() && VT != PromotedBitwiseVT) {
    135     setOperationAction(ISD::AND, VT, Promote);
    136     AddPromotedToType (ISD::AND, VT, PromotedBitwiseVT);
    137     setOperationAction(ISD::OR,  VT, Promote);
    138     AddPromotedToType (ISD::OR,  VT, PromotedBitwiseVT);
    139     setOperationAction(ISD::XOR, VT, Promote);
    140     AddPromotedToType (ISD::XOR, VT, PromotedBitwiseVT);
    141   }
    142 
    143   // Neon does not support vector divide/remainder operations.
    144   setOperationAction(ISD::SDIV, VT, Expand);
    145   setOperationAction(ISD::UDIV, VT, Expand);
    146   setOperationAction(ISD::FDIV, VT, Expand);
    147   setOperationAction(ISD::SREM, VT, Expand);
    148   setOperationAction(ISD::UREM, VT, Expand);
    149   setOperationAction(ISD::FREM, VT, Expand);
    150 }
    151 
    152 void ARMTargetLowering::addDRTypeForNEON(MVT VT) {
    153   addRegisterClass(VT, &ARM::DPRRegClass);
    154   addTypeForNEON(VT, MVT::f64, MVT::v2i32);
    155 }
    156 
    157 void ARMTargetLowering::addQRTypeForNEON(MVT VT) {
    158   addRegisterClass(VT, &ARM::QPRRegClass);
    159   addTypeForNEON(VT, MVT::v2f64, MVT::v4i32);
    160 }
    161 
    162 static TargetLoweringObjectFile *createTLOF(TargetMachine &TM) {
    163   if (TM.getSubtarget<ARMSubtarget>().isTargetDarwin())
    164     return new TargetLoweringObjectFileMachO();
    165 
    166   return new ARMElfTargetObjectFile();
    167 }
    168 
    169 ARMTargetLowering::ARMTargetLowering(TargetMachine &TM)
    170     : TargetLowering(TM, createTLOF(TM)) {
    171   Subtarget = &TM.getSubtarget<ARMSubtarget>();
    172   RegInfo = TM.getRegisterInfo();
    173   Itins = TM.getInstrItineraryData();
    174 
    175   setBooleanVectorContents(ZeroOrNegativeOneBooleanContent);
    176 
    177   if (Subtarget->isTargetDarwin()) {
    178     // Uses VFP for Thumb libfuncs if available.
    179     if (Subtarget->isThumb() && Subtarget->hasVFP2()) {
    180       // Single-precision floating-point arithmetic.
    181       setLibcallName(RTLIB::ADD_F32, "__addsf3vfp");
    182       setLibcallName(RTLIB::SUB_F32, "__subsf3vfp");
    183       setLibcallName(RTLIB::MUL_F32, "__mulsf3vfp");
    184       setLibcallName(RTLIB::DIV_F32, "__divsf3vfp");
    185 
    186       // Double-precision floating-point arithmetic.
    187       setLibcallName(RTLIB::ADD_F64, "__adddf3vfp");
    188       setLibcallName(RTLIB::SUB_F64, "__subdf3vfp");
    189       setLibcallName(RTLIB::MUL_F64, "__muldf3vfp");
    190       setLibcallName(RTLIB::DIV_F64, "__divdf3vfp");
    191 
    192       // Single-precision comparisons.
    193       setLibcallName(RTLIB::OEQ_F32, "__eqsf2vfp");
    194       setLibcallName(RTLIB::UNE_F32, "__nesf2vfp");
    195       setLibcallName(RTLIB::OLT_F32, "__ltsf2vfp");
    196       setLibcallName(RTLIB::OLE_F32, "__lesf2vfp");
    197       setLibcallName(RTLIB::OGE_F32, "__gesf2vfp");
    198       setLibcallName(RTLIB::OGT_F32, "__gtsf2vfp");
    199       setLibcallName(RTLIB::UO_F32,  "__unordsf2vfp");
    200       setLibcallName(RTLIB::O_F32,   "__unordsf2vfp");
    201 
    202       setCmpLibcallCC(RTLIB::OEQ_F32, ISD::SETNE);
    203       setCmpLibcallCC(RTLIB::UNE_F32, ISD::SETNE);
    204       setCmpLibcallCC(RTLIB::OLT_F32, ISD::SETNE);
    205       setCmpLibcallCC(RTLIB::OLE_F32, ISD::SETNE);
    206       setCmpLibcallCC(RTLIB::OGE_F32, ISD::SETNE);
    207       setCmpLibcallCC(RTLIB::OGT_F32, ISD::SETNE);
    208       setCmpLibcallCC(RTLIB::UO_F32,  ISD::SETNE);
    209       setCmpLibcallCC(RTLIB::O_F32,   ISD::SETEQ);
    210 
    211       // Double-precision comparisons.
    212       setLibcallName(RTLIB::OEQ_F64, "__eqdf2vfp");
    213       setLibcallName(RTLIB::UNE_F64, "__nedf2vfp");
    214       setLibcallName(RTLIB::OLT_F64, "__ltdf2vfp");
    215       setLibcallName(RTLIB::OLE_F64, "__ledf2vfp");
    216       setLibcallName(RTLIB::OGE_F64, "__gedf2vfp");
    217       setLibcallName(RTLIB::OGT_F64, "__gtdf2vfp");
    218       setLibcallName(RTLIB::UO_F64,  "__unorddf2vfp");
    219       setLibcallName(RTLIB::O_F64,   "__unorddf2vfp");
    220 
    221       setCmpLibcallCC(RTLIB::OEQ_F64, ISD::SETNE);
    222       setCmpLibcallCC(RTLIB::UNE_F64, ISD::SETNE);
    223       setCmpLibcallCC(RTLIB::OLT_F64, ISD::SETNE);
    224       setCmpLibcallCC(RTLIB::OLE_F64, ISD::SETNE);
    225       setCmpLibcallCC(RTLIB::OGE_F64, ISD::SETNE);
    226       setCmpLibcallCC(RTLIB::OGT_F64, ISD::SETNE);
    227       setCmpLibcallCC(RTLIB::UO_F64,  ISD::SETNE);
    228       setCmpLibcallCC(RTLIB::O_F64,   ISD::SETEQ);
    229 
    230       // Floating-point to integer conversions.
    231       // i64 conversions are done via library routines even when generating VFP
    232       // instructions, so use the same ones.
    233       setLibcallName(RTLIB::FPTOSINT_F64_I32, "__fixdfsivfp");
    234       setLibcallName(RTLIB::FPTOUINT_F64_I32, "__fixunsdfsivfp");
    235       setLibcallName(RTLIB::FPTOSINT_F32_I32, "__fixsfsivfp");
    236       setLibcallName(RTLIB::FPTOUINT_F32_I32, "__fixunssfsivfp");
    237 
    238       // Conversions between floating types.
    239       setLibcallName(RTLIB::FPROUND_F64_F32, "__truncdfsf2vfp");
    240       setLibcallName(RTLIB::FPEXT_F32_F64,   "__extendsfdf2vfp");
    241 
    242       // Integer to floating-point conversions.
    243       // i64 conversions are done via library routines even when generating VFP
    244       // instructions, so use the same ones.
    245       // FIXME: There appears to be some naming inconsistency in ARM libgcc:
    246       // e.g., __floatunsidf vs. __floatunssidfvfp.
    247       setLibcallName(RTLIB::SINTTOFP_I32_F64, "__floatsidfvfp");
    248       setLibcallName(RTLIB::UINTTOFP_I32_F64, "__floatunssidfvfp");
    249       setLibcallName(RTLIB::SINTTOFP_I32_F32, "__floatsisfvfp");
    250       setLibcallName(RTLIB::UINTTOFP_I32_F32, "__floatunssisfvfp");
    251     }
    252   }
    253 
    254   // These libcalls are not available in 32-bit.
    255   setLibcallName(RTLIB::SHL_I128, 0);
    256   setLibcallName(RTLIB::SRL_I128, 0);
    257   setLibcallName(RTLIB::SRA_I128, 0);
    258 
    259   if (Subtarget->isAAPCS_ABI() && !Subtarget->isTargetDarwin()) {
    260     // Double-precision floating-point arithmetic helper functions
    261     // RTABI chapter 4.1.2, Table 2
    262     setLibcallName(RTLIB::ADD_F64, "__aeabi_dadd");
    263     setLibcallName(RTLIB::DIV_F64, "__aeabi_ddiv");
    264     setLibcallName(RTLIB::MUL_F64, "__aeabi_dmul");
    265     setLibcallName(RTLIB::SUB_F64, "__aeabi_dsub");
    266     setLibcallCallingConv(RTLIB::ADD_F64, CallingConv::ARM_AAPCS);
    267     setLibcallCallingConv(RTLIB::DIV_F64, CallingConv::ARM_AAPCS);
    268     setLibcallCallingConv(RTLIB::MUL_F64, CallingConv::ARM_AAPCS);
    269     setLibcallCallingConv(RTLIB::SUB_F64, CallingConv::ARM_AAPCS);
    270 
    271     // Double-precision floating-point comparison helper functions
    272     // RTABI chapter 4.1.2, Table 3
    273     setLibcallName(RTLIB::OEQ_F64, "__aeabi_dcmpeq");
    274     setCmpLibcallCC(RTLIB::OEQ_F64, ISD::SETNE);
    275     setLibcallName(RTLIB::UNE_F64, "__aeabi_dcmpeq");
    276     setCmpLibcallCC(RTLIB::UNE_F64, ISD::SETEQ);
    277     setLibcallName(RTLIB::OLT_F64, "__aeabi_dcmplt");
    278     setCmpLibcallCC(RTLIB::OLT_F64, ISD::SETNE);
    279     setLibcallName(RTLIB::OLE_F64, "__aeabi_dcmple");
    280     setCmpLibcallCC(RTLIB::OLE_F64, ISD::SETNE);
    281     setLibcallName(RTLIB::OGE_F64, "__aeabi_dcmpge");
    282     setCmpLibcallCC(RTLIB::OGE_F64, ISD::SETNE);
    283     setLibcallName(RTLIB::OGT_F64, "__aeabi_dcmpgt");
    284     setCmpLibcallCC(RTLIB::OGT_F64, ISD::SETNE);
    285     setLibcallName(RTLIB::UO_F64,  "__aeabi_dcmpun");
    286     setCmpLibcallCC(RTLIB::UO_F64,  ISD::SETNE);
    287     setLibcallName(RTLIB::O_F64,   "__aeabi_dcmpun");
    288     setCmpLibcallCC(RTLIB::O_F64,   ISD::SETEQ);
    289     setLibcallCallingConv(RTLIB::OEQ_F64, CallingConv::ARM_AAPCS);
    290     setLibcallCallingConv(RTLIB::UNE_F64, CallingConv::ARM_AAPCS);
    291     setLibcallCallingConv(RTLIB::OLT_F64, CallingConv::ARM_AAPCS);
    292     setLibcallCallingConv(RTLIB::OLE_F64, CallingConv::ARM_AAPCS);
    293     setLibcallCallingConv(RTLIB::OGE_F64, CallingConv::ARM_AAPCS);
    294     setLibcallCallingConv(RTLIB::OGT_F64, CallingConv::ARM_AAPCS);
    295     setLibcallCallingConv(RTLIB::UO_F64, CallingConv::ARM_AAPCS);
    296     setLibcallCallingConv(RTLIB::O_F64, CallingConv::ARM_AAPCS);
    297 
    298     // Single-precision floating-point arithmetic helper functions
    299     // RTABI chapter 4.1.2, Table 4
    300     setLibcallName(RTLIB::ADD_F32, "__aeabi_fadd");
    301     setLibcallName(RTLIB::DIV_F32, "__aeabi_fdiv");
    302     setLibcallName(RTLIB::MUL_F32, "__aeabi_fmul");
    303     setLibcallName(RTLIB::SUB_F32, "__aeabi_fsub");
    304     setLibcallCallingConv(RTLIB::ADD_F32, CallingConv::ARM_AAPCS);
    305     setLibcallCallingConv(RTLIB::DIV_F32, CallingConv::ARM_AAPCS);
    306     setLibcallCallingConv(RTLIB::MUL_F32, CallingConv::ARM_AAPCS);
    307     setLibcallCallingConv(RTLIB::SUB_F32, CallingConv::ARM_AAPCS);
    308 
    309     // Single-precision floating-point comparison helper functions
    310     // RTABI chapter 4.1.2, Table 5
    311     setLibcallName(RTLIB::OEQ_F32, "__aeabi_fcmpeq");
    312     setCmpLibcallCC(RTLIB::OEQ_F32, ISD::SETNE);
    313     setLibcallName(RTLIB::UNE_F32, "__aeabi_fcmpeq");
    314     setCmpLibcallCC(RTLIB::UNE_F32, ISD::SETEQ);
    315     setLibcallName(RTLIB::OLT_F32, "__aeabi_fcmplt");
    316     setCmpLibcallCC(RTLIB::OLT_F32, ISD::SETNE);
    317     setLibcallName(RTLIB::OLE_F32, "__aeabi_fcmple");
    318     setCmpLibcallCC(RTLIB::OLE_F32, ISD::SETNE);
    319     setLibcallName(RTLIB::OGE_F32, "__aeabi_fcmpge");
    320     setCmpLibcallCC(RTLIB::OGE_F32, ISD::SETNE);
    321     setLibcallName(RTLIB::OGT_F32, "__aeabi_fcmpgt");
    322     setCmpLibcallCC(RTLIB::OGT_F32, ISD::SETNE);
    323     setLibcallName(RTLIB::UO_F32,  "__aeabi_fcmpun");
    324     setCmpLibcallCC(RTLIB::UO_F32,  ISD::SETNE);
    325     setLibcallName(RTLIB::O_F32,   "__aeabi_fcmpun");
    326     setCmpLibcallCC(RTLIB::O_F32,   ISD::SETEQ);
    327     setLibcallCallingConv(RTLIB::OEQ_F32, CallingConv::ARM_AAPCS);
    328     setLibcallCallingConv(RTLIB::UNE_F32, CallingConv::ARM_AAPCS);
    329     setLibcallCallingConv(RTLIB::OLT_F32, CallingConv::ARM_AAPCS);
    330     setLibcallCallingConv(RTLIB::OLE_F32, CallingConv::ARM_AAPCS);
    331     setLibcallCallingConv(RTLIB::OGE_F32, CallingConv::ARM_AAPCS);
    332     setLibcallCallingConv(RTLIB::OGT_F32, CallingConv::ARM_AAPCS);
    333     setLibcallCallingConv(RTLIB::UO_F32, CallingConv::ARM_AAPCS);
    334     setLibcallCallingConv(RTLIB::O_F32, CallingConv::ARM_AAPCS);
    335 
    336     // Floating-point to integer conversions.
    337     // RTABI chapter 4.1.2, Table 6
    338     setLibcallName(RTLIB::FPTOSINT_F64_I32, "__aeabi_d2iz");
    339     setLibcallName(RTLIB::FPTOUINT_F64_I32, "__aeabi_d2uiz");
    340     setLibcallName(RTLIB::FPTOSINT_F64_I64, "__aeabi_d2lz");
    341     setLibcallName(RTLIB::FPTOUINT_F64_I64, "__aeabi_d2ulz");
    342     setLibcallName(RTLIB::FPTOSINT_F32_I32, "__aeabi_f2iz");
    343     setLibcallName(RTLIB::FPTOUINT_F32_I32, "__aeabi_f2uiz");
    344     setLibcallName(RTLIB::FPTOSINT_F32_I64, "__aeabi_f2lz");
    345     setLibcallName(RTLIB::FPTOUINT_F32_I64, "__aeabi_f2ulz");
    346     setLibcallCallingConv(RTLIB::FPTOSINT_F64_I32, CallingConv::ARM_AAPCS);
    347     setLibcallCallingConv(RTLIB::FPTOUINT_F64_I32, CallingConv::ARM_AAPCS);
    348     setLibcallCallingConv(RTLIB::FPTOSINT_F64_I64, CallingConv::ARM_AAPCS);
    349     setLibcallCallingConv(RTLIB::FPTOUINT_F64_I64, CallingConv::ARM_AAPCS);
    350     setLibcallCallingConv(RTLIB::FPTOSINT_F32_I32, CallingConv::ARM_AAPCS);
    351     setLibcallCallingConv(RTLIB::FPTOUINT_F32_I32, CallingConv::ARM_AAPCS);
    352     setLibcallCallingConv(RTLIB::FPTOSINT_F32_I64, CallingConv::ARM_AAPCS);
    353     setLibcallCallingConv(RTLIB::FPTOUINT_F32_I64, CallingConv::ARM_AAPCS);
    354 
    355     // Conversions between floating types.
    356     // RTABI chapter 4.1.2, Table 7
    357     setLibcallName(RTLIB::FPROUND_F64_F32, "__aeabi_d2f");
    358     setLibcallName(RTLIB::FPEXT_F32_F64,   "__aeabi_f2d");
    359     setLibcallCallingConv(RTLIB::FPROUND_F64_F32, CallingConv::ARM_AAPCS);
    360     setLibcallCallingConv(RTLIB::FPEXT_F32_F64, CallingConv::ARM_AAPCS);
    361 
    362     // Integer to floating-point conversions.
    363     // RTABI chapter 4.1.2, Table 8
    364     setLibcallName(RTLIB::SINTTOFP_I32_F64, "__aeabi_i2d");
    365     setLibcallName(RTLIB::UINTTOFP_I32_F64, "__aeabi_ui2d");
    366     setLibcallName(RTLIB::SINTTOFP_I64_F64, "__aeabi_l2d");
    367     setLibcallName(RTLIB::UINTTOFP_I64_F64, "__aeabi_ul2d");
    368     setLibcallName(RTLIB::SINTTOFP_I32_F32, "__aeabi_i2f");
    369     setLibcallName(RTLIB::UINTTOFP_I32_F32, "__aeabi_ui2f");
    370     setLibcallName(RTLIB::SINTTOFP_I64_F32, "__aeabi_l2f");
    371     setLibcallName(RTLIB::UINTTOFP_I64_F32, "__aeabi_ul2f");
    372     setLibcallCallingConv(RTLIB::SINTTOFP_I32_F64, CallingConv::ARM_AAPCS);
    373     setLibcallCallingConv(RTLIB::UINTTOFP_I32_F64, CallingConv::ARM_AAPCS);
    374     setLibcallCallingConv(RTLIB::SINTTOFP_I64_F64, CallingConv::ARM_AAPCS);
    375     setLibcallCallingConv(RTLIB::UINTTOFP_I64_F64, CallingConv::ARM_AAPCS);
    376     setLibcallCallingConv(RTLIB::SINTTOFP_I32_F32, CallingConv::ARM_AAPCS);
    377     setLibcallCallingConv(RTLIB::UINTTOFP_I32_F32, CallingConv::ARM_AAPCS);
    378     setLibcallCallingConv(RTLIB::SINTTOFP_I64_F32, CallingConv::ARM_AAPCS);
    379     setLibcallCallingConv(RTLIB::UINTTOFP_I64_F32, CallingConv::ARM_AAPCS);
    380 
    381     // Long long helper functions
    382     // RTABI chapter 4.2, Table 9
    383     setLibcallName(RTLIB::MUL_I64,  "__aeabi_lmul");
    384     setLibcallName(RTLIB::SHL_I64, "__aeabi_llsl");
    385     setLibcallName(RTLIB::SRL_I64, "__aeabi_llsr");
    386     setLibcallName(RTLIB::SRA_I64, "__aeabi_lasr");
    387     setLibcallCallingConv(RTLIB::MUL_I64, CallingConv::ARM_AAPCS);
    388     setLibcallCallingConv(RTLIB::SDIV_I64, CallingConv::ARM_AAPCS);
    389     setLibcallCallingConv(RTLIB::UDIV_I64, CallingConv::ARM_AAPCS);
    390     setLibcallCallingConv(RTLIB::SHL_I64, CallingConv::ARM_AAPCS);
    391     setLibcallCallingConv(RTLIB::SRL_I64, CallingConv::ARM_AAPCS);
    392     setLibcallCallingConv(RTLIB::SRA_I64, CallingConv::ARM_AAPCS);
    393 
    394     // Integer division functions
    395     // RTABI chapter 4.3.1
    396     setLibcallName(RTLIB::SDIV_I8,  "__aeabi_idiv");
    397     setLibcallName(RTLIB::SDIV_I16, "__aeabi_idiv");
    398     setLibcallName(RTLIB::SDIV_I32, "__aeabi_idiv");
    399     setLibcallName(RTLIB::SDIV_I64, "__aeabi_ldivmod");
    400     setLibcallName(RTLIB::UDIV_I8,  "__aeabi_uidiv");
    401     setLibcallName(RTLIB::UDIV_I16, "__aeabi_uidiv");
    402     setLibcallName(RTLIB::UDIV_I32, "__aeabi_uidiv");
    403     setLibcallName(RTLIB::UDIV_I64, "__aeabi_uldivmod");
    404     setLibcallCallingConv(RTLIB::SDIV_I8, CallingConv::ARM_AAPCS);
    405     setLibcallCallingConv(RTLIB::SDIV_I16, CallingConv::ARM_AAPCS);
    406     setLibcallCallingConv(RTLIB::SDIV_I32, CallingConv::ARM_AAPCS);
    407     setLibcallCallingConv(RTLIB::SDIV_I64, CallingConv::ARM_AAPCS);
    408     setLibcallCallingConv(RTLIB::UDIV_I8, CallingConv::ARM_AAPCS);
    409     setLibcallCallingConv(RTLIB::UDIV_I16, CallingConv::ARM_AAPCS);
    410     setLibcallCallingConv(RTLIB::UDIV_I32, CallingConv::ARM_AAPCS);
    411     setLibcallCallingConv(RTLIB::UDIV_I64, CallingConv::ARM_AAPCS);
    412 
    413     // Memory operations
    414     // RTABI chapter 4.3.4
    415     setLibcallName(RTLIB::MEMCPY,  "__aeabi_memcpy");
    416     setLibcallName(RTLIB::MEMMOVE, "__aeabi_memmove");
    417     setLibcallName(RTLIB::MEMSET,  "__aeabi_memset");
    418     setLibcallCallingConv(RTLIB::MEMCPY, CallingConv::ARM_AAPCS);
    419     setLibcallCallingConv(RTLIB::MEMMOVE, CallingConv::ARM_AAPCS);
    420     setLibcallCallingConv(RTLIB::MEMSET, CallingConv::ARM_AAPCS);
    421   }
    422 
    423   // Use divmod compiler-rt calls for iOS 5.0 and later.
    424   if (Subtarget->getTargetTriple().getOS() == Triple::IOS &&
    425       !Subtarget->getTargetTriple().isOSVersionLT(5, 0)) {
    426     setLibcallName(RTLIB::SDIVREM_I32, "__divmodsi4");
    427     setLibcallName(RTLIB::UDIVREM_I32, "__udivmodsi4");
    428   }
    429 
    430   if (Subtarget->isThumb1Only())
    431     addRegisterClass(MVT::i32, &ARM::tGPRRegClass);
    432   else
    433     addRegisterClass(MVT::i32, &ARM::GPRRegClass);
    434   if (!TM.Options.UseSoftFloat && Subtarget->hasVFP2() &&
    435       !Subtarget->isThumb1Only()) {
    436     addRegisterClass(MVT::f32, &ARM::SPRRegClass);
    437     if (!Subtarget->isFPOnlySP())
    438       addRegisterClass(MVT::f64, &ARM::DPRRegClass);
    439 
    440     setTruncStoreAction(MVT::f64, MVT::f32, Expand);
    441   }
    442 
    443   for (unsigned VT = (unsigned)MVT::FIRST_VECTOR_VALUETYPE;
    444        VT <= (unsigned)MVT::LAST_VECTOR_VALUETYPE; ++VT) {
    445     for (unsigned InnerVT = (unsigned)MVT::FIRST_VECTOR_VALUETYPE;
    446          InnerVT <= (unsigned)MVT::LAST_VECTOR_VALUETYPE; ++InnerVT)
    447       setTruncStoreAction((MVT::SimpleValueType)VT,
    448                           (MVT::SimpleValueType)InnerVT, Expand);
    449     setLoadExtAction(ISD::SEXTLOAD, (MVT::SimpleValueType)VT, Expand);
    450     setLoadExtAction(ISD::ZEXTLOAD, (MVT::SimpleValueType)VT, Expand);
    451     setLoadExtAction(ISD::EXTLOAD, (MVT::SimpleValueType)VT, Expand);
    452   }
    453 
    454   setOperationAction(ISD::ConstantFP, MVT::f32, Custom);
    455 
    456   if (Subtarget->hasNEON()) {
    457     addDRTypeForNEON(MVT::v2f32);
    458     addDRTypeForNEON(MVT::v8i8);
    459     addDRTypeForNEON(MVT::v4i16);
    460     addDRTypeForNEON(MVT::v2i32);
    461     addDRTypeForNEON(MVT::v1i64);
    462 
    463     addQRTypeForNEON(MVT::v4f32);
    464     addQRTypeForNEON(MVT::v2f64);
    465     addQRTypeForNEON(MVT::v16i8);
    466     addQRTypeForNEON(MVT::v8i16);
    467     addQRTypeForNEON(MVT::v4i32);
    468     addQRTypeForNEON(MVT::v2i64);
    469 
    470     // v2f64 is legal so that QR subregs can be extracted as f64 elements, but
    471     // neither Neon nor VFP support any arithmetic operations on it.
    472     // The same with v4f32. But keep in mind that vadd, vsub, vmul are natively
    473     // supported for v4f32.
    474     setOperationAction(ISD::FADD, MVT::v2f64, Expand);
    475     setOperationAction(ISD::FSUB, MVT::v2f64, Expand);
    476     setOperationAction(ISD::FMUL, MVT::v2f64, Expand);
    477     // FIXME: Code duplication: FDIV and FREM are expanded always, see
    478     // ARMTargetLowering::addTypeForNEON method for details.
    479     setOperationAction(ISD::FDIV, MVT::v2f64, Expand);
    480     setOperationAction(ISD::FREM, MVT::v2f64, Expand);
    481     // FIXME: Create unittest.
    482     // In another words, find a way when "copysign" appears in DAG with vector
    483     // operands.
    484     setOperationAction(ISD::FCOPYSIGN, MVT::v2f64, Expand);
    485     // FIXME: Code duplication: SETCC has custom operation action, see
    486     // ARMTargetLowering::addTypeForNEON method for details.
    487     setOperationAction(ISD::SETCC, MVT::v2f64, Expand);
    488     // FIXME: Create unittest for FNEG and for FABS.
    489     setOperationAction(ISD::FNEG, MVT::v2f64, Expand);
    490     setOperationAction(ISD::FABS, MVT::v2f64, Expand);
    491     setOperationAction(ISD::FSQRT, MVT::v2f64, Expand);
    492     setOperationAction(ISD::FSIN, MVT::v2f64, Expand);
    493     setOperationAction(ISD::FCOS, MVT::v2f64, Expand);
    494     setOperationAction(ISD::FPOWI, MVT::v2f64, Expand);
    495     setOperationAction(ISD::FPOW, MVT::v2f64, Expand);
    496     setOperationAction(ISD::FLOG, MVT::v2f64, Expand);
    497     setOperationAction(ISD::FLOG2, MVT::v2f64, Expand);
    498     setOperationAction(ISD::FLOG10, MVT::v2f64, Expand);
    499     setOperationAction(ISD::FEXP, MVT::v2f64, Expand);
    500     setOperationAction(ISD::FEXP2, MVT::v2f64, Expand);
    501     // FIXME: Create unittest for FCEIL, FTRUNC, FRINT, FNEARBYINT, FFLOOR.
    502     setOperationAction(ISD::FCEIL, MVT::v2f64, Expand);
    503     setOperationAction(ISD::FTRUNC, MVT::v2f64, Expand);
    504     setOperationAction(ISD::FRINT, MVT::v2f64, Expand);
    505     setOperationAction(ISD::FNEARBYINT, MVT::v2f64, Expand);
    506     setOperationAction(ISD::FFLOOR, MVT::v2f64, Expand);
    507     setOperationAction(ISD::FMA, MVT::v2f64, Expand);
    508 
    509     setOperationAction(ISD::FSQRT, MVT::v4f32, Expand);
    510     setOperationAction(ISD::FSIN, MVT::v4f32, Expand);
    511     setOperationAction(ISD::FCOS, MVT::v4f32, Expand);
    512     setOperationAction(ISD::FPOWI, MVT::v4f32, Expand);
    513     setOperationAction(ISD::FPOW, MVT::v4f32, Expand);
    514     setOperationAction(ISD::FLOG, MVT::v4f32, Expand);
    515     setOperationAction(ISD::FLOG2, MVT::v4f32, Expand);
    516     setOperationAction(ISD::FLOG10, MVT::v4f32, Expand);
    517     setOperationAction(ISD::FEXP, MVT::v4f32, Expand);
    518     setOperationAction(ISD::FEXP2, MVT::v4f32, Expand);
    519     setOperationAction(ISD::FCEIL, MVT::v4f32, Expand);
    520     setOperationAction(ISD::FTRUNC, MVT::v4f32, Expand);
    521     setOperationAction(ISD::FRINT, MVT::v4f32, Expand);
    522     setOperationAction(ISD::FNEARBYINT, MVT::v4f32, Expand);
    523     setOperationAction(ISD::FFLOOR, MVT::v4f32, Expand);
    524 
    525     // Mark v2f32 intrinsics.
    526     setOperationAction(ISD::FSQRT, MVT::v2f32, Expand);
    527     setOperationAction(ISD::FSIN, MVT::v2f32, Expand);
    528     setOperationAction(ISD::FCOS, MVT::v2f32, Expand);
    529     setOperationAction(ISD::FPOWI, MVT::v2f32, Expand);
    530     setOperationAction(ISD::FPOW, MVT::v2f32, Expand);
    531     setOperationAction(ISD::FLOG, MVT::v2f32, Expand);
    532     setOperationAction(ISD::FLOG2, MVT::v2f32, Expand);
    533     setOperationAction(ISD::FLOG10, MVT::v2f32, Expand);
    534     setOperationAction(ISD::FEXP, MVT::v2f32, Expand);
    535     setOperationAction(ISD::FEXP2, MVT::v2f32, Expand);
    536     setOperationAction(ISD::FCEIL, MVT::v2f32, Expand);
    537     setOperationAction(ISD::FTRUNC, MVT::v2f32, Expand);
    538     setOperationAction(ISD::FRINT, MVT::v2f32, Expand);
    539     setOperationAction(ISD::FNEARBYINT, MVT::v2f32, Expand);
    540     setOperationAction(ISD::FFLOOR, MVT::v2f32, Expand);
    541 
    542     // Neon does not support some operations on v1i64 and v2i64 types.
    543     setOperationAction(ISD::MUL, MVT::v1i64, Expand);
    544     // Custom handling for some quad-vector types to detect VMULL.
    545     setOperationAction(ISD::MUL, MVT::v8i16, Custom);
    546     setOperationAction(ISD::MUL, MVT::v4i32, Custom);
    547     setOperationAction(ISD::MUL, MVT::v2i64, Custom);
    548     // Custom handling for some vector types to avoid expensive expansions
    549     setOperationAction(ISD::SDIV, MVT::v4i16, Custom);
    550     setOperationAction(ISD::SDIV, MVT::v8i8, Custom);
    551     setOperationAction(ISD::UDIV, MVT::v4i16, Custom);
    552     setOperationAction(ISD::UDIV, MVT::v8i8, Custom);
    553     setOperationAction(ISD::SETCC, MVT::v1i64, Expand);
    554     setOperationAction(ISD::SETCC, MVT::v2i64, Expand);
    555     // Neon does not have single instruction SINT_TO_FP and UINT_TO_FP with
    556     // a destination type that is wider than the source, and nor does
    557     // it have a FP_TO_[SU]INT instruction with a narrower destination than
    558     // source.
    559     setOperationAction(ISD::SINT_TO_FP, MVT::v4i16, Custom);
    560     setOperationAction(ISD::UINT_TO_FP, MVT::v4i16, Custom);
    561     setOperationAction(ISD::FP_TO_UINT, MVT::v4i16, Custom);
    562     setOperationAction(ISD::FP_TO_SINT, MVT::v4i16, Custom);
    563 
    564     setOperationAction(ISD::FP_ROUND,   MVT::v2f32, Expand);
    565     setOperationAction(ISD::FP_EXTEND,  MVT::v2f64, Expand);
    566 
    567     // Custom expand long extensions to vectors.
    568     setOperationAction(ISD::SIGN_EXTEND, MVT::v8i32,  Custom);
    569     setOperationAction(ISD::ZERO_EXTEND, MVT::v8i32,  Custom);
    570     setOperationAction(ISD::SIGN_EXTEND, MVT::v4i64,  Custom);
    571     setOperationAction(ISD::ZERO_EXTEND, MVT::v4i64,  Custom);
    572     setOperationAction(ISD::SIGN_EXTEND, MVT::v16i32, Custom);
    573     setOperationAction(ISD::ZERO_EXTEND, MVT::v16i32, Custom);
    574     setOperationAction(ISD::SIGN_EXTEND, MVT::v8i64,  Custom);
    575     setOperationAction(ISD::ZERO_EXTEND, MVT::v8i64,  Custom);
    576 
    577     // NEON does not have single instruction CTPOP for vectors with element
    578     // types wider than 8-bits.  However, custom lowering can leverage the
    579     // v8i8/v16i8 vcnt instruction.
    580     setOperationAction(ISD::CTPOP,      MVT::v2i32, Custom);
    581     setOperationAction(ISD::CTPOP,      MVT::v4i32, Custom);
    582     setOperationAction(ISD::CTPOP,      MVT::v4i16, Custom);
    583     setOperationAction(ISD::CTPOP,      MVT::v8i16, Custom);
    584 
    585     // NEON only has FMA instructions as of VFP4.
    586     if (!Subtarget->hasVFP4()) {
    587       setOperationAction(ISD::FMA, MVT::v2f32, Expand);
    588       setOperationAction(ISD::FMA, MVT::v4f32, Expand);
    589     }
    590 
    591     setTargetDAGCombine(ISD::INTRINSIC_VOID);
    592     setTargetDAGCombine(ISD::INTRINSIC_W_CHAIN);
    593     setTargetDAGCombine(ISD::INTRINSIC_WO_CHAIN);
    594     setTargetDAGCombine(ISD::SHL);
    595     setTargetDAGCombine(ISD::SRL);
    596     setTargetDAGCombine(ISD::SRA);
    597     setTargetDAGCombine(ISD::SIGN_EXTEND);
    598     setTargetDAGCombine(ISD::ZERO_EXTEND);
    599     setTargetDAGCombine(ISD::ANY_EXTEND);
    600     setTargetDAGCombine(ISD::SELECT_CC);
    601     setTargetDAGCombine(ISD::BUILD_VECTOR);
    602     setTargetDAGCombine(ISD::VECTOR_SHUFFLE);
    603     setTargetDAGCombine(ISD::INSERT_VECTOR_ELT);
    604     setTargetDAGCombine(ISD::STORE);
    605     setTargetDAGCombine(ISD::FP_TO_SINT);
    606     setTargetDAGCombine(ISD::FP_TO_UINT);
    607     setTargetDAGCombine(ISD::FDIV);
    608 
    609     // It is legal to extload from v4i8 to v4i16 or v4i32.
    610     MVT Tys[6] = {MVT::v8i8, MVT::v4i8, MVT::v2i8,
    611                   MVT::v4i16, MVT::v2i16,
    612                   MVT::v2i32};
    613     for (unsigned i = 0; i < 6; ++i) {
    614       setLoadExtAction(ISD::EXTLOAD, Tys[i], Legal);
    615       setLoadExtAction(ISD::ZEXTLOAD, Tys[i], Legal);
    616       setLoadExtAction(ISD::SEXTLOAD, Tys[i], Legal);
    617     }
    618   }
    619 
    620   // ARM and Thumb2 support UMLAL/SMLAL.
    621   if (!Subtarget->isThumb1Only())
    622     setTargetDAGCombine(ISD::ADDC);
    623 
    624 
    625   computeRegisterProperties();
    626 
    627   // ARM does not have f32 extending load.
    628   setLoadExtAction(ISD::EXTLOAD, MVT::f32, Expand);
    629 
    630   // ARM does not have i1 sign extending load.
    631   setLoadExtAction(ISD::SEXTLOAD, MVT::i1, Promote);
    632 
    633   // ARM supports all 4 flavors of integer indexed load / store.
    634   if (!Subtarget->isThumb1Only()) {
    635     for (unsigned im = (unsigned)ISD::PRE_INC;
    636          im != (unsigned)ISD::LAST_INDEXED_MODE; ++im) {
    637       setIndexedLoadAction(im,  MVT::i1,  Legal);
    638       setIndexedLoadAction(im,  MVT::i8,  Legal);
    639       setIndexedLoadAction(im,  MVT::i16, Legal);
    640       setIndexedLoadAction(im,  MVT::i32, Legal);
    641       setIndexedStoreAction(im, MVT::i1,  Legal);
    642       setIndexedStoreAction(im, MVT::i8,  Legal);
    643       setIndexedStoreAction(im, MVT::i16, Legal);
    644       setIndexedStoreAction(im, MVT::i32, Legal);
    645     }
    646   }
    647 
    648   // i64 operation support.
    649   setOperationAction(ISD::MUL,     MVT::i64, Expand);
    650   setOperationAction(ISD::MULHU,   MVT::i32, Expand);
    651   if (Subtarget->isThumb1Only()) {
    652     setOperationAction(ISD::UMUL_LOHI, MVT::i32, Expand);
    653     setOperationAction(ISD::SMUL_LOHI, MVT::i32, Expand);
    654   }
    655   if (Subtarget->isThumb1Only() || !Subtarget->hasV6Ops()
    656       || (Subtarget->isThumb2() && !Subtarget->hasThumb2DSP()))
    657     setOperationAction(ISD::MULHS, MVT::i32, Expand);
    658 
    659   setOperationAction(ISD::SHL_PARTS, MVT::i32, Custom);
    660   setOperationAction(ISD::SRA_PARTS, MVT::i32, Custom);
    661   setOperationAction(ISD::SRL_PARTS, MVT::i32, Custom);
    662   setOperationAction(ISD::SRL,       MVT::i64, Custom);
    663   setOperationAction(ISD::SRA,       MVT::i64, Custom);
    664 
    665   if (!Subtarget->isThumb1Only()) {
    666     // FIXME: We should do this for Thumb1 as well.
    667     setOperationAction(ISD::ADDC,    MVT::i32, Custom);
    668     setOperationAction(ISD::ADDE,    MVT::i32, Custom);
    669     setOperationAction(ISD::SUBC,    MVT::i32, Custom);
    670     setOperationAction(ISD::SUBE,    MVT::i32, Custom);
    671   }
    672 
    673   // ARM does not have ROTL.
    674   setOperationAction(ISD::ROTL,  MVT::i32, Expand);
    675   setOperationAction(ISD::CTTZ,  MVT::i32, Custom);
    676   setOperationAction(ISD::CTPOP, MVT::i32, Expand);
    677   if (!Subtarget->hasV5TOps() || Subtarget->isThumb1Only())
    678     setOperationAction(ISD::CTLZ, MVT::i32, Expand);
    679 
    680   // These just redirect to CTTZ and CTLZ on ARM.
    681   setOperationAction(ISD::CTTZ_ZERO_UNDEF  , MVT::i32  , Expand);
    682   setOperationAction(ISD::CTLZ_ZERO_UNDEF  , MVT::i32  , Expand);
    683 
    684   setOperationAction(ISD::READCYCLECOUNTER, MVT::i64, Custom);
    685 
    686   // Only ARMv6 has BSWAP.
    687   if (!Subtarget->hasV6Ops())
    688     setOperationAction(ISD::BSWAP, MVT::i32, Expand);
    689 
    690   if (!(Subtarget->hasDivide() && Subtarget->isThumb2()) &&
    691       !(Subtarget->hasDivideInARMMode() && !Subtarget->isThumb())) {
    692     // These are expanded into libcalls if the cpu doesn't have HW divider.
    693     setOperationAction(ISD::SDIV,  MVT::i32, Expand);
    694     setOperationAction(ISD::UDIV,  MVT::i32, Expand);
    695   }
    696 
    697   // FIXME: Also set divmod for SREM on EABI
    698   setOperationAction(ISD::SREM,  MVT::i32, Expand);
    699   setOperationAction(ISD::UREM,  MVT::i32, Expand);
    700   // Register based DivRem for AEABI (RTABI 4.2)
    701   if (Subtarget->isTargetAEABI()) {
    702     setLibcallName(RTLIB::SDIVREM_I8,  "__aeabi_idivmod");
    703     setLibcallName(RTLIB::SDIVREM_I16, "__aeabi_idivmod");
    704     setLibcallName(RTLIB::SDIVREM_I32, "__aeabi_idivmod");
    705     setLibcallName(RTLIB::SDIVREM_I64, "__aeabi_ldivmod");
    706     setLibcallName(RTLIB::UDIVREM_I8,  "__aeabi_uidivmod");
    707     setLibcallName(RTLIB::UDIVREM_I16, "__aeabi_uidivmod");
    708     setLibcallName(RTLIB::UDIVREM_I32, "__aeabi_uidivmod");
    709     setLibcallName(RTLIB::UDIVREM_I64, "__aeabi_uldivmod");
    710 
    711     setLibcallCallingConv(RTLIB::SDIVREM_I8, CallingConv::ARM_AAPCS);
    712     setLibcallCallingConv(RTLIB::SDIVREM_I16, CallingConv::ARM_AAPCS);
    713     setLibcallCallingConv(RTLIB::SDIVREM_I32, CallingConv::ARM_AAPCS);
    714     setLibcallCallingConv(RTLIB::SDIVREM_I64, CallingConv::ARM_AAPCS);
    715     setLibcallCallingConv(RTLIB::UDIVREM_I8, CallingConv::ARM_AAPCS);
    716     setLibcallCallingConv(RTLIB::UDIVREM_I16, CallingConv::ARM_AAPCS);
    717     setLibcallCallingConv(RTLIB::UDIVREM_I32, CallingConv::ARM_AAPCS);
    718     setLibcallCallingConv(RTLIB::UDIVREM_I64, CallingConv::ARM_AAPCS);
    719 
    720     setOperationAction(ISD::SDIVREM, MVT::i32, Custom);
    721     setOperationAction(ISD::UDIVREM, MVT::i32, Custom);
    722   } else {
    723     setOperationAction(ISD::SDIVREM, MVT::i32, Expand);
    724     setOperationAction(ISD::UDIVREM, MVT::i32, Expand);
    725   }
    726 
    727   setOperationAction(ISD::GlobalAddress, MVT::i32,   Custom);
    728   setOperationAction(ISD::ConstantPool,  MVT::i32,   Custom);
    729   setOperationAction(ISD::GLOBAL_OFFSET_TABLE, MVT::i32, Custom);
    730   setOperationAction(ISD::GlobalTLSAddress, MVT::i32, Custom);
    731   setOperationAction(ISD::BlockAddress, MVT::i32, Custom);
    732 
    733   setOperationAction(ISD::TRAP, MVT::Other, Legal);
    734 
    735   // Use the default implementation.
    736   setOperationAction(ISD::VASTART,            MVT::Other, Custom);
    737   setOperationAction(ISD::VAARG,              MVT::Other, Expand);
    738   setOperationAction(ISD::VACOPY,             MVT::Other, Expand);
    739   setOperationAction(ISD::VAEND,              MVT::Other, Expand);
    740   setOperationAction(ISD::STACKSAVE,          MVT::Other, Expand);
    741   setOperationAction(ISD::STACKRESTORE,       MVT::Other, Expand);
    742 
    743   if (!Subtarget->isTargetDarwin()) {
    744     // Non-Darwin platforms may return values in these registers via the
    745     // personality function.
    746     setExceptionPointerRegister(ARM::R0);
    747     setExceptionSelectorRegister(ARM::R1);
    748   }
    749 
    750   setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i32, Expand);
    751   // ARMv6 Thumb1 (except for CPUs that support dmb / dsb) and earlier use
    752   // the default expansion.
    753   // FIXME: This should be checking for v6k, not just v6.
    754   if (Subtarget->hasDataBarrier() ||
    755       (Subtarget->hasV6Ops() && !Subtarget->isThumb())) {
    756     // membarrier needs custom lowering; the rest are legal and handled
    757     // normally.
    758     setOperationAction(ISD::ATOMIC_FENCE, MVT::Other, Custom);
    759     // Custom lowering for 64-bit ops
    760     setOperationAction(ISD::ATOMIC_LOAD_ADD,  MVT::i64, Custom);
    761     setOperationAction(ISD::ATOMIC_LOAD_SUB,  MVT::i64, Custom);
    762     setOperationAction(ISD::ATOMIC_LOAD_AND,  MVT::i64, Custom);
    763     setOperationAction(ISD::ATOMIC_LOAD_OR,   MVT::i64, Custom);
    764     setOperationAction(ISD::ATOMIC_LOAD_XOR,  MVT::i64, Custom);
    765     setOperationAction(ISD::ATOMIC_SWAP,      MVT::i64, Custom);
    766     setOperationAction(ISD::ATOMIC_LOAD_MIN,  MVT::i64, Custom);
    767     setOperationAction(ISD::ATOMIC_LOAD_MAX,  MVT::i64, Custom);
    768     setOperationAction(ISD::ATOMIC_LOAD_UMIN, MVT::i64, Custom);
    769     setOperationAction(ISD::ATOMIC_LOAD_UMAX, MVT::i64, Custom);
    770     setOperationAction(ISD::ATOMIC_CMP_SWAP,  MVT::i64, Custom);
    771     // Automatically insert fences (dmb ist) around ATOMIC_SWAP etc.
    772     setInsertFencesForAtomic(true);
    773   } else {
    774     // Set them all for expansion, which will force libcalls.
    775     setOperationAction(ISD::ATOMIC_FENCE,   MVT::Other, Expand);
    776     setOperationAction(ISD::ATOMIC_CMP_SWAP,  MVT::i32, Expand);
    777     setOperationAction(ISD::ATOMIC_SWAP,      MVT::i32, Expand);
    778     setOperationAction(ISD::ATOMIC_LOAD_ADD,  MVT::i32, Expand);
    779     setOperationAction(ISD::ATOMIC_LOAD_SUB,  MVT::i32, Expand);
    780     setOperationAction(ISD::ATOMIC_LOAD_AND,  MVT::i32, Expand);
    781     setOperationAction(ISD::ATOMIC_LOAD_OR,   MVT::i32, Expand);
    782     setOperationAction(ISD::ATOMIC_LOAD_XOR,  MVT::i32, Expand);
    783     setOperationAction(ISD::ATOMIC_LOAD_NAND, MVT::i32, Expand);
    784     setOperationAction(ISD::ATOMIC_LOAD_MIN, MVT::i32, Expand);
    785     setOperationAction(ISD::ATOMIC_LOAD_MAX, MVT::i32, Expand);
    786     setOperationAction(ISD::ATOMIC_LOAD_UMIN, MVT::i32, Expand);
    787     setOperationAction(ISD::ATOMIC_LOAD_UMAX, MVT::i32, Expand);
    788     // Mark ATOMIC_LOAD and ATOMIC_STORE custom so we can handle the
    789     // Unordered/Monotonic case.
    790     setOperationAction(ISD::ATOMIC_LOAD, MVT::i32, Custom);
    791     setOperationAction(ISD::ATOMIC_STORE, MVT::i32, Custom);
    792   }
    793 
    794   setOperationAction(ISD::PREFETCH,         MVT::Other, Custom);
    795 
    796   // Requires SXTB/SXTH, available on v6 and up in both ARM and Thumb modes.
    797   if (!Subtarget->hasV6Ops()) {
    798     setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i16, Expand);
    799     setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i8,  Expand);
    800   }
    801   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1, Expand);
    802 
    803   if (!TM.Options.UseSoftFloat && Subtarget->hasVFP2() &&
    804       !Subtarget->isThumb1Only()) {
    805     // Turn f64->i64 into VMOVRRD, i64 -> f64 to VMOVDRR
    806     // iff target supports vfp2.
    807     setOperationAction(ISD::BITCAST, MVT::i64, Custom);
    808     setOperationAction(ISD::FLT_ROUNDS_, MVT::i32, Custom);
    809   }
    810 
    811   // We want to custom lower some of our intrinsics.
    812   setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
    813   if (Subtarget->isTargetDarwin()) {
    814     setOperationAction(ISD::EH_SJLJ_SETJMP, MVT::i32, Custom);
    815     setOperationAction(ISD::EH_SJLJ_LONGJMP, MVT::Other, Custom);
    816     setLibcallName(RTLIB::UNWIND_RESUME, "_Unwind_SjLj_Resume");
    817   }
    818 
    819   setOperationAction(ISD::SETCC,     MVT::i32, Expand);
    820   setOperationAction(ISD::SETCC,     MVT::f32, Expand);
    821   setOperationAction(ISD::SETCC,     MVT::f64, Expand);
    822   setOperationAction(ISD::SELECT,    MVT::i32, Custom);
    823   setOperationAction(ISD::SELECT,    MVT::f32, Custom);
    824   setOperationAction(ISD::SELECT,    MVT::f64, Custom);
    825   setOperationAction(ISD::SELECT_CC, MVT::i32, Custom);
    826   setOperationAction(ISD::SELECT_CC, MVT::f32, Custom);
    827   setOperationAction(ISD::SELECT_CC, MVT::f64, Custom);
    828 
    829   setOperationAction(ISD::BRCOND,    MVT::Other, Expand);
    830   setOperationAction(ISD::BR_CC,     MVT::i32,   Custom);
    831   setOperationAction(ISD::BR_CC,     MVT::f32,   Custom);
    832   setOperationAction(ISD::BR_CC,     MVT::f64,   Custom);
    833   setOperationAction(ISD::BR_JT,     MVT::Other, Custom);
    834 
    835   // We don't support sin/cos/fmod/copysign/pow
    836   setOperationAction(ISD::FSIN,      MVT::f64, Expand);
    837   setOperationAction(ISD::FSIN,      MVT::f32, Expand);
    838   setOperationAction(ISD::FCOS,      MVT::f32, Expand);
    839   setOperationAction(ISD::FCOS,      MVT::f64, Expand);
    840   setOperationAction(ISD::FSINCOS,   MVT::f64, Expand);
    841   setOperationAction(ISD::FSINCOS,   MVT::f32, Expand);
    842   setOperationAction(ISD::FREM,      MVT::f64, Expand);
    843   setOperationAction(ISD::FREM,      MVT::f32, Expand);
    844   if (!TM.Options.UseSoftFloat && Subtarget->hasVFP2() &&
    845       !Subtarget->isThumb1Only()) {
    846     setOperationAction(ISD::FCOPYSIGN, MVT::f64, Custom);
    847     setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
    848   }
    849   setOperationAction(ISD::FPOW,      MVT::f64, Expand);
    850   setOperationAction(ISD::FPOW,      MVT::f32, Expand);
    851 
    852   if (!Subtarget->hasVFP4()) {
    853     setOperationAction(ISD::FMA, MVT::f64, Expand);
    854     setOperationAction(ISD::FMA, MVT::f32, Expand);
    855   }
    856 
    857   // Various VFP goodness
    858   if (!TM.Options.UseSoftFloat && !Subtarget->isThumb1Only()) {
    859     // int <-> fp are custom expanded into bit_convert + ARMISD ops.
    860     if (Subtarget->hasVFP2()) {
    861       setOperationAction(ISD::SINT_TO_FP, MVT::i32, Custom);
    862       setOperationAction(ISD::UINT_TO_FP, MVT::i32, Custom);
    863       setOperationAction(ISD::FP_TO_UINT, MVT::i32, Custom);
    864       setOperationAction(ISD::FP_TO_SINT, MVT::i32, Custom);
    865     }
    866     // Special handling for half-precision FP.
    867     if (!Subtarget->hasFP16()) {
    868       setOperationAction(ISD::FP16_TO_FP32, MVT::f32, Expand);
    869       setOperationAction(ISD::FP32_TO_FP16, MVT::i32, Expand);
    870     }
    871   }
    872 
    873   // We have target-specific dag combine patterns for the following nodes:
    874   // ARMISD::VMOVRRD  - No need to call setTargetDAGCombine
    875   setTargetDAGCombine(ISD::ADD);
    876   setTargetDAGCombine(ISD::SUB);
    877   setTargetDAGCombine(ISD::MUL);
    878   setTargetDAGCombine(ISD::AND);
    879   setTargetDAGCombine(ISD::OR);
    880   setTargetDAGCombine(ISD::XOR);
    881 
    882   if (Subtarget->hasV6Ops())
    883     setTargetDAGCombine(ISD::SRL);
    884 
    885   setStackPointerRegisterToSaveRestore(ARM::SP);
    886 
    887   if (TM.Options.UseSoftFloat || Subtarget->isThumb1Only() ||
    888       !Subtarget->hasVFP2())
    889     setSchedulingPreference(Sched::RegPressure);
    890   else
    891     setSchedulingPreference(Sched::Hybrid);
    892 
    893   //// temporary - rewrite interface to use type
    894   MaxStoresPerMemset = 8;
    895   MaxStoresPerMemsetOptSize = Subtarget->isTargetDarwin() ? 8 : 4;
    896   MaxStoresPerMemcpy = 4; // For @llvm.memcpy -> sequence of stores
    897   MaxStoresPerMemcpyOptSize = Subtarget->isTargetDarwin() ? 4 : 2;
    898   MaxStoresPerMemmove = 4; // For @llvm.memmove -> sequence of stores
    899   MaxStoresPerMemmoveOptSize = Subtarget->isTargetDarwin() ? 4 : 2;
    900 
    901   // On ARM arguments smaller than 4 bytes are extended, so all arguments
    902   // are at least 4 bytes aligned.
    903   setMinStackArgumentAlignment(4);
    904 
    905   // Prefer likely predicted branches to selects on out-of-order cores.
    906   PredictableSelectIsExpensive = Subtarget->isLikeA9();
    907 
    908   setMinFunctionAlignment(Subtarget->isThumb() ? 1 : 2);
    909 }
    910 
    911 // FIXME: It might make sense to define the representative register class as the
    912 // nearest super-register that has a non-null superset. For example, DPR_VFP2 is
    913 // a super-register of SPR, and DPR is a superset if DPR_VFP2. Consequently,
    914 // SPR's representative would be DPR_VFP2. This should work well if register
    915 // pressure tracking were modified such that a register use would increment the
    916 // pressure of the register class's representative and all of it's super
    917 // classes' representatives transitively. We have not implemented this because
    918 // of the difficulty prior to coalescing of modeling operand register classes
    919 // due to the common occurrence of cross class copies and subregister insertions
    920 // and extractions.
    921 std::pair<const TargetRegisterClass*, uint8_t>
    922 ARMTargetLowering::findRepresentativeClass(MVT VT) const{
    923   const TargetRegisterClass *RRC = 0;
    924   uint8_t Cost = 1;
    925   switch (VT.SimpleTy) {
    926   default:
    927     return TargetLowering::findRepresentativeClass(VT);
    928   // Use DPR as representative register class for all floating point
    929   // and vector types. Since there are 32 SPR registers and 32 DPR registers so
    930   // the cost is 1 for both f32 and f64.
    931   case MVT::f32: case MVT::f64: case MVT::v8i8: case MVT::v4i16:
    932   case MVT::v2i32: case MVT::v1i64: case MVT::v2f32:
    933     RRC = &ARM::DPRRegClass;
    934     // When NEON is used for SP, only half of the register file is available
    935     // because operations that define both SP and DP results will be constrained
    936     // to the VFP2 class (D0-D15). We currently model this constraint prior to
    937     // coalescing by double-counting the SP regs. See the FIXME above.
    938     if (Subtarget->useNEONForSinglePrecisionFP())
    939       Cost = 2;
    940     break;
    941   case MVT::v16i8: case MVT::v8i16: case MVT::v4i32: case MVT::v2i64:
    942   case MVT::v4f32: case MVT::v2f64:
    943     RRC = &ARM::DPRRegClass;
    944     Cost = 2;
    945     break;
    946   case MVT::v4i64:
    947     RRC = &ARM::DPRRegClass;
    948     Cost = 4;
    949     break;
    950   case MVT::v8i64:
    951     RRC = &ARM::DPRRegClass;
    952     Cost = 8;
    953     break;
    954   }
    955   return std::make_pair(RRC, Cost);
    956 }
    957 
    958 const char *ARMTargetLowering::getTargetNodeName(unsigned Opcode) const {
    959   switch (Opcode) {
    960   default: return 0;
    961   case ARMISD::Wrapper:       return "ARMISD::Wrapper";
    962   case ARMISD::WrapperDYN:    return "ARMISD::WrapperDYN";
    963   case ARMISD::WrapperPIC:    return "ARMISD::WrapperPIC";
    964   case ARMISD::WrapperJT:     return "ARMISD::WrapperJT";
    965   case ARMISD::CALL:          return "ARMISD::CALL";
    966   case ARMISD::CALL_PRED:     return "ARMISD::CALL_PRED";
    967   case ARMISD::CALL_NOLINK:   return "ARMISD::CALL_NOLINK";
    968   case ARMISD::tCALL:         return "ARMISD::tCALL";
    969   case ARMISD::BRCOND:        return "ARMISD::BRCOND";
    970   case ARMISD::BR_JT:         return "ARMISD::BR_JT";
    971   case ARMISD::BR2_JT:        return "ARMISD::BR2_JT";
    972   case ARMISD::RET_FLAG:      return "ARMISD::RET_FLAG";
    973   case ARMISD::PIC_ADD:       return "ARMISD::PIC_ADD";
    974   case ARMISD::CMP:           return "ARMISD::CMP";
    975   case ARMISD::CMN:           return "ARMISD::CMN";
    976   case ARMISD::CMPZ:          return "ARMISD::CMPZ";
    977   case ARMISD::CMPFP:         return "ARMISD::CMPFP";
    978   case ARMISD::CMPFPw0:       return "ARMISD::CMPFPw0";
    979   case ARMISD::BCC_i64:       return "ARMISD::BCC_i64";
    980   case ARMISD::FMSTAT:        return "ARMISD::FMSTAT";
    981 
    982   case ARMISD::CMOV:          return "ARMISD::CMOV";
    983 
    984   case ARMISD::RBIT:          return "ARMISD::RBIT";
    985 
    986   case ARMISD::FTOSI:         return "ARMISD::FTOSI";
    987   case ARMISD::FTOUI:         return "ARMISD::FTOUI";
    988   case ARMISD::SITOF:         return "ARMISD::SITOF";
    989   case ARMISD::UITOF:         return "ARMISD::UITOF";
    990 
    991   case ARMISD::SRL_FLAG:      return "ARMISD::SRL_FLAG";
    992   case ARMISD::SRA_FLAG:      return "ARMISD::SRA_FLAG";
    993   case ARMISD::RRX:           return "ARMISD::RRX";
    994 
    995   case ARMISD::ADDC:          return "ARMISD::ADDC";
    996   case ARMISD::ADDE:          return "ARMISD::ADDE";
    997   case ARMISD::SUBC:          return "ARMISD::SUBC";
    998   case ARMISD::SUBE:          return "ARMISD::SUBE";
    999 
   1000   case ARMISD::VMOVRRD:       return "ARMISD::VMOVRRD";
   1001   case ARMISD::VMOVDRR:       return "ARMISD::VMOVDRR";
   1002 
   1003   case ARMISD::EH_SJLJ_SETJMP: return "ARMISD::EH_SJLJ_SETJMP";
   1004   case ARMISD::EH_SJLJ_LONGJMP:return "ARMISD::EH_SJLJ_LONGJMP";
   1005 
   1006   case ARMISD::TC_RETURN:     return "ARMISD::TC_RETURN";
   1007 
   1008   case ARMISD::THREAD_POINTER:return "ARMISD::THREAD_POINTER";
   1009 
   1010   case ARMISD::DYN_ALLOC:     return "ARMISD::DYN_ALLOC";
   1011 
   1012   case ARMISD::MEMBARRIER:    return "ARMISD::MEMBARRIER";
   1013   case ARMISD::MEMBARRIER_MCR: return "ARMISD::MEMBARRIER_MCR";
   1014 
   1015   case ARMISD::PRELOAD:       return "ARMISD::PRELOAD";
   1016 
   1017   case ARMISD::VCEQ:          return "ARMISD::VCEQ";
   1018   case ARMISD::VCEQZ:         return "ARMISD::VCEQZ";
   1019   case ARMISD::VCGE:          return "ARMISD::VCGE";
   1020   case ARMISD::VCGEZ:         return "ARMISD::VCGEZ";
   1021   case ARMISD::VCLEZ:         return "ARMISD::VCLEZ";
   1022   case ARMISD::VCGEU:         return "ARMISD::VCGEU";
   1023   case ARMISD::VCGT:          return "ARMISD::VCGT";
   1024   case ARMISD::VCGTZ:         return "ARMISD::VCGTZ";
   1025   case ARMISD::VCLTZ:         return "ARMISD::VCLTZ";
   1026   case ARMISD::VCGTU:         return "ARMISD::VCGTU";
   1027   case ARMISD::VTST:          return "ARMISD::VTST";
   1028 
   1029   case ARMISD::VSHL:          return "ARMISD::VSHL";
   1030   case ARMISD::VSHRs:         return "ARMISD::VSHRs";
   1031   case ARMISD::VSHRu:         return "ARMISD::VSHRu";
   1032   case ARMISD::VSHLLs:        return "ARMISD::VSHLLs";
   1033   case ARMISD::VSHLLu:        return "ARMISD::VSHLLu";
   1034   case ARMISD::VSHLLi:        return "ARMISD::VSHLLi";
   1035   case ARMISD::VSHRN:         return "ARMISD::VSHRN";
   1036   case ARMISD::VRSHRs:        return "ARMISD::VRSHRs";
   1037   case ARMISD::VRSHRu:        return "ARMISD::VRSHRu";
   1038   case ARMISD::VRSHRN:        return "ARMISD::VRSHRN";
   1039   case ARMISD::VQSHLs:        return "ARMISD::VQSHLs";
   1040   case ARMISD::VQSHLu:        return "ARMISD::VQSHLu";
   1041   case ARMISD::VQSHLsu:       return "ARMISD::VQSHLsu";
   1042   case ARMISD::VQSHRNs:       return "ARMISD::VQSHRNs";
   1043   case ARMISD::VQSHRNu:       return "ARMISD::VQSHRNu";
   1044   case ARMISD::VQSHRNsu:      return "ARMISD::VQSHRNsu";
   1045   case ARMISD::VQRSHRNs:      return "ARMISD::VQRSHRNs";
   1046   case ARMISD::VQRSHRNu:      return "ARMISD::VQRSHRNu";
   1047   case ARMISD::VQRSHRNsu:     return "ARMISD::VQRSHRNsu";
   1048   case ARMISD::VGETLANEu:     return "ARMISD::VGETLANEu";
   1049   case ARMISD::VGETLANEs:     return "ARMISD::VGETLANEs";
   1050   case ARMISD::VMOVIMM:       return "ARMISD::VMOVIMM";
   1051   case ARMISD::VMVNIMM:       return "ARMISD::VMVNIMM";
   1052   case ARMISD::VMOVFPIMM:     return "ARMISD::VMOVFPIMM";
   1053   case ARMISD::VDUP:          return "ARMISD::VDUP";
   1054   case ARMISD::VDUPLANE:      return "ARMISD::VDUPLANE";
   1055   case ARMISD::VEXT:          return "ARMISD::VEXT";
   1056   case ARMISD::VREV64:        return "ARMISD::VREV64";
   1057   case ARMISD::VREV32:        return "ARMISD::VREV32";
   1058   case ARMISD::VREV16:        return "ARMISD::VREV16";
   1059   case ARMISD::VZIP:          return "ARMISD::VZIP";
   1060   case ARMISD::VUZP:          return "ARMISD::VUZP";
   1061   case ARMISD::VTRN:          return "ARMISD::VTRN";
   1062   case ARMISD::VTBL1:         return "ARMISD::VTBL1";
   1063   case ARMISD::VTBL2:         return "ARMISD::VTBL2";
   1064   case ARMISD::VMULLs:        return "ARMISD::VMULLs";
   1065   case ARMISD::VMULLu:        return "ARMISD::VMULLu";
   1066   case ARMISD::UMLAL:         return "ARMISD::UMLAL";
   1067   case ARMISD::SMLAL:         return "ARMISD::SMLAL";
   1068   case ARMISD::BUILD_VECTOR:  return "ARMISD::BUILD_VECTOR";
   1069   case ARMISD::FMAX:          return "ARMISD::FMAX";
   1070   case ARMISD::FMIN:          return "ARMISD::FMIN";
   1071   case ARMISD::BFI:           return "ARMISD::BFI";
   1072   case ARMISD::VORRIMM:       return "ARMISD::VORRIMM";
   1073   case ARMISD::VBICIMM:       return "ARMISD::VBICIMM";
   1074   case ARMISD::VBSL:          return "ARMISD::VBSL";
   1075   case ARMISD::VLD2DUP:       return "ARMISD::VLD2DUP";
   1076   case ARMISD::VLD3DUP:       return "ARMISD::VLD3DUP";
   1077   case ARMISD::VLD4DUP:       return "ARMISD::VLD4DUP";
   1078   case ARMISD::VLD1_UPD:      return "ARMISD::VLD1_UPD";
   1079   case ARMISD::VLD2_UPD:      return "ARMISD::VLD2_UPD";
   1080   case ARMISD::VLD3_UPD:      return "ARMISD::VLD3_UPD";
   1081   case ARMISD::VLD4_UPD:      return "ARMISD::VLD4_UPD";
   1082   case ARMISD::VLD2LN_UPD:    return "ARMISD::VLD2LN_UPD";
   1083   case ARMISD::VLD3LN_UPD:    return "ARMISD::VLD3LN_UPD";
   1084   case ARMISD::VLD4LN_UPD:    return "ARMISD::VLD4LN_UPD";
   1085   case ARMISD::VLD2DUP_UPD:   return "ARMISD::VLD2DUP_UPD";
   1086   case ARMISD::VLD3DUP_UPD:   return "ARMISD::VLD3DUP_UPD";
   1087   case ARMISD::VLD4DUP_UPD:   return "ARMISD::VLD4DUP_UPD";
   1088   case ARMISD::VST1_UPD:      return "ARMISD::VST1_UPD";
   1089   case ARMISD::VST2_UPD:      return "ARMISD::VST2_UPD";
   1090   case ARMISD::VST3_UPD:      return "ARMISD::VST3_UPD";
   1091   case ARMISD::VST4_UPD:      return "ARMISD::VST4_UPD";
   1092   case ARMISD::VST2LN_UPD:    return "ARMISD::VST2LN_UPD";
   1093   case ARMISD::VST3LN_UPD:    return "ARMISD::VST3LN_UPD";
   1094   case ARMISD::VST4LN_UPD:    return "ARMISD::VST4LN_UPD";
   1095 
   1096   case ARMISD::ATOMADD64_DAG:     return "ATOMADD64_DAG";
   1097   case ARMISD::ATOMSUB64_DAG:     return "ATOMSUB64_DAG";
   1098   case ARMISD::ATOMOR64_DAG:      return "ATOMOR64_DAG";
   1099   case ARMISD::ATOMXOR64_DAG:     return "ATOMXOR64_DAG";
   1100   case ARMISD::ATOMAND64_DAG:     return "ATOMAND64_DAG";
   1101   case ARMISD::ATOMNAND64_DAG:    return "ATOMNAND64_DAG";
   1102   case ARMISD::ATOMSWAP64_DAG:    return "ATOMSWAP64_DAG";
   1103   case ARMISD::ATOMCMPXCHG64_DAG: return "ATOMCMPXCHG64_DAG";
   1104   case ARMISD::ATOMMIN64_DAG:     return "ATOMMIN64_DAG";
   1105   case ARMISD::ATOMUMIN64_DAG:    return "ATOMUMIN64_DAG";
   1106   case ARMISD::ATOMMAX64_DAG:     return "ATOMMAX64_DAG";
   1107   case ARMISD::ATOMUMAX64_DAG:    return "ATOMUMAX64_DAG";
   1108   }
   1109 }
   1110 
   1111 EVT ARMTargetLowering::getSetCCResultType(LLVMContext &, EVT VT) const {
   1112   if (!VT.isVector()) return getPointerTy();
   1113   return VT.changeVectorElementTypeToInteger();
   1114 }
   1115 
   1116 /// getRegClassFor - Return the register class that should be used for the
   1117 /// specified value type.
   1118 const TargetRegisterClass *ARMTargetLowering::getRegClassFor(MVT VT) const {
   1119   // Map v4i64 to QQ registers but do not make the type legal. Similarly map
   1120   // v8i64 to QQQQ registers. v4i64 and v8i64 are only used for REG_SEQUENCE to
   1121   // load / store 4 to 8 consecutive D registers.
   1122   if (Subtarget->hasNEON()) {
   1123     if (VT == MVT::v4i64)
   1124       return &ARM::QQPRRegClass;
   1125     if (VT == MVT::v8i64)
   1126       return &ARM::QQQQPRRegClass;
   1127   }
   1128   return TargetLowering::getRegClassFor(VT);
   1129 }
   1130 
   1131 // Create a fast isel object.
   1132 FastISel *
   1133 ARMTargetLowering::createFastISel(FunctionLoweringInfo &funcInfo,
   1134                                   const TargetLibraryInfo *libInfo) const {
   1135   return ARM::createFastISel(funcInfo, libInfo);
   1136 }
   1137 
   1138 /// getMaximalGlobalOffset - Returns the maximal possible offset which can
   1139 /// be used for loads / stores from the global.
   1140 unsigned ARMTargetLowering::getMaximalGlobalOffset() const {
   1141   return (Subtarget->isThumb1Only() ? 127 : 4095);
   1142 }
   1143 
   1144 Sched::Preference ARMTargetLowering::getSchedulingPreference(SDNode *N) const {
   1145   unsigned NumVals = N->getNumValues();
   1146   if (!NumVals)
   1147     return Sched::RegPressure;
   1148 
   1149   for (unsigned i = 0; i != NumVals; ++i) {
   1150     EVT VT = N->getValueType(i);
   1151     if (VT == MVT::Glue || VT == MVT::Other)
   1152       continue;
   1153     if (VT.isFloatingPoint() || VT.isVector())
   1154       return Sched::ILP;
   1155   }
   1156 
   1157   if (!N->isMachineOpcode())
   1158     return Sched::RegPressure;
   1159 
   1160   // Load are scheduled for latency even if there instruction itinerary
   1161   // is not available.
   1162   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
   1163   const MCInstrDesc &MCID = TII->get(N->getMachineOpcode());
   1164 
   1165   if (MCID.getNumDefs() == 0)
   1166     return Sched::RegPressure;
   1167   if (!Itins->isEmpty() &&
   1168       Itins->getOperandCycle(MCID.getSchedClass(), 0) > 2)
   1169     return Sched::ILP;
   1170 
   1171   return Sched::RegPressure;
   1172 }
   1173 
   1174 //===----------------------------------------------------------------------===//
   1175 // Lowering Code
   1176 //===----------------------------------------------------------------------===//
   1177 
   1178 /// IntCCToARMCC - Convert a DAG integer condition code to an ARM CC
   1179 static ARMCC::CondCodes IntCCToARMCC(ISD::CondCode CC) {
   1180   switch (CC) {
   1181   default: llvm_unreachable("Unknown condition code!");
   1182   case ISD::SETNE:  return ARMCC::NE;
   1183   case ISD::SETEQ:  return ARMCC::EQ;
   1184   case ISD::SETGT:  return ARMCC::GT;
   1185   case ISD::SETGE:  return ARMCC::GE;
   1186   case ISD::SETLT:  return ARMCC::LT;
   1187   case ISD::SETLE:  return ARMCC::LE;
   1188   case ISD::SETUGT: return ARMCC::HI;
   1189   case ISD::SETUGE: return ARMCC::HS;
   1190   case ISD::SETULT: return ARMCC::LO;
   1191   case ISD::SETULE: return ARMCC::LS;
   1192   }
   1193 }
   1194 
   1195 /// FPCCToARMCC - Convert a DAG fp condition code to an ARM CC.
   1196 static void FPCCToARMCC(ISD::CondCode CC, ARMCC::CondCodes &CondCode,
   1197                         ARMCC::CondCodes &CondCode2) {
   1198   CondCode2 = ARMCC::AL;
   1199   switch (CC) {
   1200   default: llvm_unreachable("Unknown FP condition!");
   1201   case ISD::SETEQ:
   1202   case ISD::SETOEQ: CondCode = ARMCC::EQ; break;
   1203   case ISD::SETGT:
   1204   case ISD::SETOGT: CondCode = ARMCC::GT; break;
   1205   case ISD::SETGE:
   1206   case ISD::SETOGE: CondCode = ARMCC::GE; break;
   1207   case ISD::SETOLT: CondCode = ARMCC::MI; break;
   1208   case ISD::SETOLE: CondCode = ARMCC::LS; break;
   1209   case ISD::SETONE: CondCode = ARMCC::MI; CondCode2 = ARMCC::GT; break;
   1210   case ISD::SETO:   CondCode = ARMCC::VC; break;
   1211   case ISD::SETUO:  CondCode = ARMCC::VS; break;
   1212   case ISD::SETUEQ: CondCode = ARMCC::EQ; CondCode2 = ARMCC::VS; break;
   1213   case ISD::SETUGT: CondCode = ARMCC::HI; break;
   1214   case ISD::SETUGE: CondCode = ARMCC::PL; break;
   1215   case ISD::SETLT:
   1216   case ISD::SETULT: CondCode = ARMCC::LT; break;
   1217   case ISD::SETLE:
   1218   case ISD::SETULE: CondCode = ARMCC::LE; break;
   1219   case ISD::SETNE:
   1220   case ISD::SETUNE: CondCode = ARMCC::NE; break;
   1221   }
   1222 }
   1223 
   1224 //===----------------------------------------------------------------------===//
   1225 //                      Calling Convention Implementation
   1226 //===----------------------------------------------------------------------===//
   1227 
   1228 #include "ARMGenCallingConv.inc"
   1229 
   1230 /// CCAssignFnForNode - Selects the correct CCAssignFn for a the
   1231 /// given CallingConvention value.
   1232 CCAssignFn *ARMTargetLowering::CCAssignFnForNode(CallingConv::ID CC,
   1233                                                  bool Return,
   1234                                                  bool isVarArg) const {
   1235   switch (CC) {
   1236   default:
   1237     llvm_unreachable("Unsupported calling convention");
   1238   case CallingConv::Fast:
   1239     if (Subtarget->hasVFP2() && !isVarArg) {
   1240       if (!Subtarget->isAAPCS_ABI())
   1241         return (Return ? RetFastCC_ARM_APCS : FastCC_ARM_APCS);
   1242       // For AAPCS ABI targets, just use VFP variant of the calling convention.
   1243       return (Return ? RetCC_ARM_AAPCS_VFP : CC_ARM_AAPCS_VFP);
   1244     }
   1245     // Fallthrough
   1246   case CallingConv::C: {
   1247     // Use target triple & subtarget features to do actual dispatch.
   1248     if (!Subtarget->isAAPCS_ABI())
   1249       return (Return ? RetCC_ARM_APCS : CC_ARM_APCS);
   1250     else if (Subtarget->hasVFP2() &&
   1251              getTargetMachine().Options.FloatABIType == FloatABI::Hard &&
   1252              !isVarArg)
   1253       return (Return ? RetCC_ARM_AAPCS_VFP : CC_ARM_AAPCS_VFP);
   1254     return (Return ? RetCC_ARM_AAPCS : CC_ARM_AAPCS);
   1255   }
   1256   case CallingConv::ARM_AAPCS_VFP:
   1257     if (!isVarArg)
   1258       return (Return ? RetCC_ARM_AAPCS_VFP : CC_ARM_AAPCS_VFP);
   1259     // Fallthrough
   1260   case CallingConv::ARM_AAPCS:
   1261     return (Return ? RetCC_ARM_AAPCS : CC_ARM_AAPCS);
   1262   case CallingConv::ARM_APCS:
   1263     return (Return ? RetCC_ARM_APCS : CC_ARM_APCS);
   1264   case CallingConv::GHC:
   1265     return (Return ? RetCC_ARM_APCS : CC_ARM_APCS_GHC);
   1266   }
   1267 }
   1268 
   1269 /// LowerCallResult - Lower the result values of a call into the
   1270 /// appropriate copies out of appropriate physical registers.
   1271 SDValue
   1272 ARMTargetLowering::LowerCallResult(SDValue Chain, SDValue InFlag,
   1273                                    CallingConv::ID CallConv, bool isVarArg,
   1274                                    const SmallVectorImpl<ISD::InputArg> &Ins,
   1275                                    SDLoc dl, SelectionDAG &DAG,
   1276                                    SmallVectorImpl<SDValue> &InVals,
   1277                                    bool isThisReturn, SDValue ThisVal) const {
   1278 
   1279   // Assign locations to each value returned by this call.
   1280   SmallVector<CCValAssign, 16> RVLocs;
   1281   ARMCCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(),
   1282                     getTargetMachine(), RVLocs, *DAG.getContext(), Call);
   1283   CCInfo.AnalyzeCallResult(Ins,
   1284                            CCAssignFnForNode(CallConv, /* Return*/ true,
   1285                                              isVarArg));
   1286 
   1287   // Copy all of the result registers out of their specified physreg.
   1288   for (unsigned i = 0; i != RVLocs.size(); ++i) {
   1289     CCValAssign VA = RVLocs[i];
   1290 
   1291     // Pass 'this' value directly from the argument to return value, to avoid
   1292     // reg unit interference
   1293     if (i == 0 && isThisReturn) {
   1294       assert(!VA.needsCustom() && VA.getLocVT() == MVT::i32 &&
   1295              "unexpected return calling convention register assignment");
   1296       InVals.push_back(ThisVal);
   1297       continue;
   1298     }
   1299 
   1300     SDValue Val;
   1301     if (VA.needsCustom()) {
   1302       // Handle f64 or half of a v2f64.
   1303       SDValue Lo = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32,
   1304                                       InFlag);
   1305       Chain = Lo.getValue(1);
   1306       InFlag = Lo.getValue(2);
   1307       VA = RVLocs[++i]; // skip ahead to next loc
   1308       SDValue Hi = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32,
   1309                                       InFlag);
   1310       Chain = Hi.getValue(1);
   1311       InFlag = Hi.getValue(2);
   1312       Val = DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi);
   1313 
   1314       if (VA.getLocVT() == MVT::v2f64) {
   1315         SDValue Vec = DAG.getNode(ISD::UNDEF, dl, MVT::v2f64);
   1316         Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Vec, Val,
   1317                           DAG.getConstant(0, MVT::i32));
   1318 
   1319         VA = RVLocs[++i]; // skip ahead to next loc
   1320         Lo = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32, InFlag);
   1321         Chain = Lo.getValue(1);
   1322         InFlag = Lo.getValue(2);
   1323         VA = RVLocs[++i]; // skip ahead to next loc
   1324         Hi = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32, InFlag);
   1325         Chain = Hi.getValue(1);
   1326         InFlag = Hi.getValue(2);
   1327         Val = DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi);
   1328         Val = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Vec, Val,
   1329                           DAG.getConstant(1, MVT::i32));
   1330       }
   1331     } else {
   1332       Val = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), VA.getLocVT(),
   1333                                InFlag);
   1334       Chain = Val.getValue(1);
   1335       InFlag = Val.getValue(2);
   1336     }
   1337 
   1338     switch (VA.getLocInfo()) {
   1339     default: llvm_unreachable("Unknown loc info!");
   1340     case CCValAssign::Full: break;
   1341     case CCValAssign::BCvt:
   1342       Val = DAG.getNode(ISD::BITCAST, dl, VA.getValVT(), Val);
   1343       break;
   1344     }
   1345 
   1346     InVals.push_back(Val);
   1347   }
   1348 
   1349   return Chain;
   1350 }
   1351 
   1352 /// LowerMemOpCallTo - Store the argument to the stack.
   1353 SDValue
   1354 ARMTargetLowering::LowerMemOpCallTo(SDValue Chain,
   1355                                     SDValue StackPtr, SDValue Arg,
   1356                                     SDLoc dl, SelectionDAG &DAG,
   1357                                     const CCValAssign &VA,
   1358                                     ISD::ArgFlagsTy Flags) const {
   1359   unsigned LocMemOffset = VA.getLocMemOffset();
   1360   SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset);
   1361   PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, PtrOff);
   1362   return DAG.getStore(Chain, dl, Arg, PtrOff,
   1363                       MachinePointerInfo::getStack(LocMemOffset),
   1364                       false, false, 0);
   1365 }
   1366 
   1367 void ARMTargetLowering::PassF64ArgInRegs(SDLoc dl, SelectionDAG &DAG,
   1368                                          SDValue Chain, SDValue &Arg,
   1369                                          RegsToPassVector &RegsToPass,
   1370                                          CCValAssign &VA, CCValAssign &NextVA,
   1371                                          SDValue &StackPtr,
   1372                                          SmallVectorImpl<SDValue> &MemOpChains,
   1373                                          ISD::ArgFlagsTy Flags) const {
   1374 
   1375   SDValue fmrrd = DAG.getNode(ARMISD::VMOVRRD, dl,
   1376                               DAG.getVTList(MVT::i32, MVT::i32), Arg);
   1377   RegsToPass.push_back(std::make_pair(VA.getLocReg(), fmrrd));
   1378 
   1379   if (NextVA.isRegLoc())
   1380     RegsToPass.push_back(std::make_pair(NextVA.getLocReg(), fmrrd.getValue(1)));
   1381   else {
   1382     assert(NextVA.isMemLoc());
   1383     if (StackPtr.getNode() == 0)
   1384       StackPtr = DAG.getCopyFromReg(Chain, dl, ARM::SP, getPointerTy());
   1385 
   1386     MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, fmrrd.getValue(1),
   1387                                            dl, DAG, NextVA,
   1388                                            Flags));
   1389   }
   1390 }
   1391 
   1392 /// LowerCall - Lowering a call into a callseq_start <-
   1393 /// ARMISD:CALL <- callseq_end chain. Also add input and output parameter
   1394 /// nodes.
   1395 SDValue
   1396 ARMTargetLowering::LowerCall(TargetLowering::CallLoweringInfo &CLI,
   1397                              SmallVectorImpl<SDValue> &InVals) const {
   1398   SelectionDAG &DAG                     = CLI.DAG;
   1399   SDLoc &dl                          = CLI.DL;
   1400   SmallVectorImpl<ISD::OutputArg> &Outs = CLI.Outs;
   1401   SmallVectorImpl<SDValue> &OutVals     = CLI.OutVals;
   1402   SmallVectorImpl<ISD::InputArg> &Ins   = CLI.Ins;
   1403   SDValue Chain                         = CLI.Chain;
   1404   SDValue Callee                        = CLI.Callee;
   1405   bool &isTailCall                      = CLI.IsTailCall;
   1406   CallingConv::ID CallConv              = CLI.CallConv;
   1407   bool doesNotRet                       = CLI.DoesNotReturn;
   1408   bool isVarArg                         = CLI.IsVarArg;
   1409 
   1410   MachineFunction &MF = DAG.getMachineFunction();
   1411   bool isStructRet    = (Outs.empty()) ? false : Outs[0].Flags.isSRet();
   1412   bool isThisReturn   = false;
   1413   bool isSibCall      = false;
   1414   // Disable tail calls if they're not supported.
   1415   if (!EnableARMTailCalls && !Subtarget->supportsTailCall())
   1416     isTailCall = false;
   1417   if (isTailCall) {
   1418     // Check if it's really possible to do a tail call.
   1419     isTailCall = IsEligibleForTailCallOptimization(Callee, CallConv,
   1420                     isVarArg, isStructRet, MF.getFunction()->hasStructRetAttr(),
   1421                                                    Outs, OutVals, Ins, DAG);
   1422     // We don't support GuaranteedTailCallOpt for ARM, only automatically
   1423     // detected sibcalls.
   1424     if (isTailCall) {
   1425       ++NumTailCalls;
   1426       isSibCall = true;
   1427     }
   1428   }
   1429 
   1430   // Analyze operands of the call, assigning locations to each operand.
   1431   SmallVector<CCValAssign, 16> ArgLocs;
   1432   ARMCCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(),
   1433                  getTargetMachine(), ArgLocs, *DAG.getContext(), Call);
   1434   CCInfo.AnalyzeCallOperands(Outs,
   1435                              CCAssignFnForNode(CallConv, /* Return*/ false,
   1436                                                isVarArg));
   1437 
   1438   // Get a count of how many bytes are to be pushed on the stack.
   1439   unsigned NumBytes = CCInfo.getNextStackOffset();
   1440 
   1441   // For tail calls, memory operands are available in our caller's stack.
   1442   if (isSibCall)
   1443     NumBytes = 0;
   1444 
   1445   // Adjust the stack pointer for the new arguments...
   1446   // These operations are automatically eliminated by the prolog/epilog pass
   1447   if (!isSibCall)
   1448     Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(NumBytes, true),
   1449                                  dl);
   1450 
   1451   SDValue StackPtr = DAG.getCopyFromReg(Chain, dl, ARM::SP, getPointerTy());
   1452 
   1453   RegsToPassVector RegsToPass;
   1454   SmallVector<SDValue, 8> MemOpChains;
   1455 
   1456   // Walk the register/memloc assignments, inserting copies/loads.  In the case
   1457   // of tail call optimization, arguments are handled later.
   1458   for (unsigned i = 0, realArgIdx = 0, e = ArgLocs.size();
   1459        i != e;
   1460        ++i, ++realArgIdx) {
   1461     CCValAssign &VA = ArgLocs[i];
   1462     SDValue Arg = OutVals[realArgIdx];
   1463     ISD::ArgFlagsTy Flags = Outs[realArgIdx].Flags;
   1464     bool isByVal = Flags.isByVal();
   1465 
   1466     // Promote the value if needed.
   1467     switch (VA.getLocInfo()) {
   1468     default: llvm_unreachable("Unknown loc info!");
   1469     case CCValAssign::Full: break;
   1470     case CCValAssign::SExt:
   1471       Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), Arg);
   1472       break;
   1473     case CCValAssign::ZExt:
   1474       Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, VA.getLocVT(), Arg);
   1475       break;
   1476     case CCValAssign::AExt:
   1477       Arg = DAG.getNode(ISD::ANY_EXTEND, dl, VA.getLocVT(), Arg);
   1478       break;
   1479     case CCValAssign::BCvt:
   1480       Arg = DAG.getNode(ISD::BITCAST, dl, VA.getLocVT(), Arg);
   1481       break;
   1482     }
   1483 
   1484     // f64 and v2f64 might be passed in i32 pairs and must be split into pieces
   1485     if (VA.needsCustom()) {
   1486       if (VA.getLocVT() == MVT::v2f64) {
   1487         SDValue Op0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg,
   1488                                   DAG.getConstant(0, MVT::i32));
   1489         SDValue Op1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg,
   1490                                   DAG.getConstant(1, MVT::i32));
   1491 
   1492         PassF64ArgInRegs(dl, DAG, Chain, Op0, RegsToPass,
   1493                          VA, ArgLocs[++i], StackPtr, MemOpChains, Flags);
   1494 
   1495         VA = ArgLocs[++i]; // skip ahead to next loc
   1496         if (VA.isRegLoc()) {
   1497           PassF64ArgInRegs(dl, DAG, Chain, Op1, RegsToPass,
   1498                            VA, ArgLocs[++i], StackPtr, MemOpChains, Flags);
   1499         } else {
   1500           assert(VA.isMemLoc());
   1501 
   1502           MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, Op1,
   1503                                                  dl, DAG, VA, Flags));
   1504         }
   1505       } else {
   1506         PassF64ArgInRegs(dl, DAG, Chain, Arg, RegsToPass, VA, ArgLocs[++i],
   1507                          StackPtr, MemOpChains, Flags);
   1508       }
   1509     } else if (VA.isRegLoc()) {
   1510       if (realArgIdx == 0 && Flags.isReturned() && Outs[0].VT == MVT::i32) {
   1511         assert(VA.getLocVT() == MVT::i32 &&
   1512                "unexpected calling convention register assignment");
   1513         assert(!Ins.empty() && Ins[0].VT == MVT::i32 &&
   1514                "unexpected use of 'returned'");
   1515         isThisReturn = true;
   1516       }
   1517       RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
   1518     } else if (isByVal) {
   1519       assert(VA.isMemLoc());
   1520       unsigned offset = 0;
   1521 
   1522       // True if this byval aggregate will be split between registers
   1523       // and memory.
   1524       unsigned ByValArgsCount = CCInfo.getInRegsParamsCount();
   1525       unsigned CurByValIdx = CCInfo.getInRegsParamsProceed();
   1526 
   1527       if (CurByValIdx < ByValArgsCount) {
   1528 
   1529         unsigned RegBegin, RegEnd;
   1530         CCInfo.getInRegsParamInfo(CurByValIdx, RegBegin, RegEnd);
   1531 
   1532         EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
   1533         unsigned int i, j;
   1534         for (i = 0, j = RegBegin; j < RegEnd; i++, j++) {
   1535           SDValue Const = DAG.getConstant(4*i, MVT::i32);
   1536           SDValue AddArg = DAG.getNode(ISD::ADD, dl, PtrVT, Arg, Const);
   1537           SDValue Load = DAG.getLoad(PtrVT, dl, Chain, AddArg,
   1538                                      MachinePointerInfo(),
   1539                                      false, false, false, 0);
   1540           MemOpChains.push_back(Load.getValue(1));
   1541           RegsToPass.push_back(std::make_pair(j, Load));
   1542         }
   1543 
   1544         // If parameter size outsides register area, "offset" value
   1545         // helps us to calculate stack slot for remained part properly.
   1546         offset = RegEnd - RegBegin;
   1547 
   1548         CCInfo.nextInRegsParam();
   1549       }
   1550 
   1551       if (Flags.getByValSize() > 4*offset) {
   1552         unsigned LocMemOffset = VA.getLocMemOffset();
   1553         SDValue StkPtrOff = DAG.getIntPtrConstant(LocMemOffset);
   1554         SDValue Dst = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr,
   1555                                   StkPtrOff);
   1556         SDValue SrcOffset = DAG.getIntPtrConstant(4*offset);
   1557         SDValue Src = DAG.getNode(ISD::ADD, dl, getPointerTy(), Arg, SrcOffset);
   1558         SDValue SizeNode = DAG.getConstant(Flags.getByValSize() - 4*offset,
   1559                                            MVT::i32);
   1560         SDValue AlignNode = DAG.getConstant(Flags.getByValAlign(), MVT::i32);
   1561 
   1562         SDVTList VTs = DAG.getVTList(MVT::Other, MVT::Glue);
   1563         SDValue Ops[] = { Chain, Dst, Src, SizeNode, AlignNode};
   1564         MemOpChains.push_back(DAG.getNode(ARMISD::COPY_STRUCT_BYVAL, dl, VTs,
   1565                                           Ops, array_lengthof(Ops)));
   1566       }
   1567     } else if (!isSibCall) {
   1568       assert(VA.isMemLoc());
   1569 
   1570       MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, Arg,
   1571                                              dl, DAG, VA, Flags));
   1572     }
   1573   }
   1574 
   1575   if (!MemOpChains.empty())
   1576     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
   1577                         &MemOpChains[0], MemOpChains.size());
   1578 
   1579   // Build a sequence of copy-to-reg nodes chained together with token chain
   1580   // and flag operands which copy the outgoing args into the appropriate regs.
   1581   SDValue InFlag;
   1582   // Tail call byval lowering might overwrite argument registers so in case of
   1583   // tail call optimization the copies to registers are lowered later.
   1584   if (!isTailCall)
   1585     for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
   1586       Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
   1587                                RegsToPass[i].second, InFlag);
   1588       InFlag = Chain.getValue(1);
   1589     }
   1590 
   1591   // For tail calls lower the arguments to the 'real' stack slot.
   1592   if (isTailCall) {
   1593     // Force all the incoming stack arguments to be loaded from the stack
   1594     // before any new outgoing arguments are stored to the stack, because the
   1595     // outgoing stack slots may alias the incoming argument stack slots, and
   1596     // the alias isn't otherwise explicit. This is slightly more conservative
   1597     // than necessary, because it means that each store effectively depends
   1598     // on every argument instead of just those arguments it would clobber.
   1599 
   1600     // Do not flag preceding copytoreg stuff together with the following stuff.
   1601     InFlag = SDValue();
   1602     for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
   1603       Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
   1604                                RegsToPass[i].second, InFlag);
   1605       InFlag = Chain.getValue(1);
   1606     }
   1607     InFlag = SDValue();
   1608   }
   1609 
   1610   // If the callee is a GlobalAddress/ExternalSymbol node (quite common, every
   1611   // direct call is) turn it into a TargetGlobalAddress/TargetExternalSymbol
   1612   // node so that legalize doesn't hack it.
   1613   bool isDirect = false;
   1614   bool isARMFunc = false;
   1615   bool isLocalARMFunc = false;
   1616   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
   1617 
   1618   if (EnableARMLongCalls) {
   1619     assert (getTargetMachine().getRelocationModel() == Reloc::Static
   1620             && "long-calls with non-static relocation model!");
   1621     // Handle a global address or an external symbol. If it's not one of
   1622     // those, the target's already in a register, so we don't need to do
   1623     // anything extra.
   1624     if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
   1625       const GlobalValue *GV = G->getGlobal();
   1626       // Create a constant pool entry for the callee address
   1627       unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
   1628       ARMConstantPoolValue *CPV =
   1629         ARMConstantPoolConstant::Create(GV, ARMPCLabelIndex, ARMCP::CPValue, 0);
   1630 
   1631       // Get the address of the callee into a register
   1632       SDValue CPAddr = DAG.getTargetConstantPool(CPV, getPointerTy(), 4);
   1633       CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
   1634       Callee = DAG.getLoad(getPointerTy(), dl,
   1635                            DAG.getEntryNode(), CPAddr,
   1636                            MachinePointerInfo::getConstantPool(),
   1637                            false, false, false, 0);
   1638     } else if (ExternalSymbolSDNode *S=dyn_cast<ExternalSymbolSDNode>(Callee)) {
   1639       const char *Sym = S->getSymbol();
   1640 
   1641       // Create a constant pool entry for the callee address
   1642       unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
   1643       ARMConstantPoolValue *CPV =
   1644         ARMConstantPoolSymbol::Create(*DAG.getContext(), Sym,
   1645                                       ARMPCLabelIndex, 0);
   1646       // Get the address of the callee into a register
   1647       SDValue CPAddr = DAG.getTargetConstantPool(CPV, getPointerTy(), 4);
   1648       CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
   1649       Callee = DAG.getLoad(getPointerTy(), dl,
   1650                            DAG.getEntryNode(), CPAddr,
   1651                            MachinePointerInfo::getConstantPool(),
   1652                            false, false, false, 0);
   1653     }
   1654   } else if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
   1655     const GlobalValue *GV = G->getGlobal();
   1656     isDirect = true;
   1657     bool isExt = GV->isDeclaration() || GV->isWeakForLinker();
   1658     bool isStub = (isExt && Subtarget->isTargetDarwin()) &&
   1659                    getTargetMachine().getRelocationModel() != Reloc::Static;
   1660     isARMFunc = !Subtarget->isThumb() || isStub;
   1661     // ARM call to a local ARM function is predicable.
   1662     isLocalARMFunc = !Subtarget->isThumb() && (!isExt || !ARMInterworking);
   1663     // tBX takes a register source operand.
   1664     if (isARMFunc && Subtarget->isThumb1Only() && !Subtarget->hasV5TOps()) {
   1665       unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
   1666       ARMConstantPoolValue *CPV =
   1667         ARMConstantPoolConstant::Create(GV, ARMPCLabelIndex, ARMCP::CPValue, 4);
   1668       SDValue CPAddr = DAG.getTargetConstantPool(CPV, getPointerTy(), 4);
   1669       CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
   1670       Callee = DAG.getLoad(getPointerTy(), dl,
   1671                            DAG.getEntryNode(), CPAddr,
   1672                            MachinePointerInfo::getConstantPool(),
   1673                            false, false, false, 0);
   1674       SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, MVT::i32);
   1675       Callee = DAG.getNode(ARMISD::PIC_ADD, dl,
   1676                            getPointerTy(), Callee, PICLabel);
   1677     } else {
   1678       // On ELF targets for PIC code, direct calls should go through the PLT
   1679       unsigned OpFlags = 0;
   1680       if (Subtarget->isTargetELF() &&
   1681           getTargetMachine().getRelocationModel() == Reloc::PIC_)
   1682         OpFlags = ARMII::MO_PLT;
   1683       Callee = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(), 0, OpFlags);
   1684     }
   1685   } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
   1686     isDirect = true;
   1687     bool isStub = Subtarget->isTargetDarwin() &&
   1688                   getTargetMachine().getRelocationModel() != Reloc::Static;
   1689     isARMFunc = !Subtarget->isThumb() || isStub;
   1690     // tBX takes a register source operand.
   1691     const char *Sym = S->getSymbol();
   1692     if (isARMFunc && Subtarget->isThumb1Only() && !Subtarget->hasV5TOps()) {
   1693       unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
   1694       ARMConstantPoolValue *CPV =
   1695         ARMConstantPoolSymbol::Create(*DAG.getContext(), Sym,
   1696                                       ARMPCLabelIndex, 4);
   1697       SDValue CPAddr = DAG.getTargetConstantPool(CPV, getPointerTy(), 4);
   1698       CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
   1699       Callee = DAG.getLoad(getPointerTy(), dl,
   1700                            DAG.getEntryNode(), CPAddr,
   1701                            MachinePointerInfo::getConstantPool(),
   1702                            false, false, false, 0);
   1703       SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, MVT::i32);
   1704       Callee = DAG.getNode(ARMISD::PIC_ADD, dl,
   1705                            getPointerTy(), Callee, PICLabel);
   1706     } else {
   1707       unsigned OpFlags = 0;
   1708       // On ELF targets for PIC code, direct calls should go through the PLT
   1709       if (Subtarget->isTargetELF() &&
   1710                   getTargetMachine().getRelocationModel() == Reloc::PIC_)
   1711         OpFlags = ARMII::MO_PLT;
   1712       Callee = DAG.getTargetExternalSymbol(Sym, getPointerTy(), OpFlags);
   1713     }
   1714   }
   1715 
   1716   // FIXME: handle tail calls differently.
   1717   unsigned CallOpc;
   1718   bool HasMinSizeAttr = MF.getFunction()->getAttributes().
   1719     hasAttribute(AttributeSet::FunctionIndex, Attribute::MinSize);
   1720   if (Subtarget->isThumb()) {
   1721     if ((!isDirect || isARMFunc) && !Subtarget->hasV5TOps())
   1722       CallOpc = ARMISD::CALL_NOLINK;
   1723     else
   1724       CallOpc = isARMFunc ? ARMISD::CALL : ARMISD::tCALL;
   1725   } else {
   1726     if (!isDirect && !Subtarget->hasV5TOps())
   1727       CallOpc = ARMISD::CALL_NOLINK;
   1728     else if (doesNotRet && isDirect && Subtarget->hasRAS() &&
   1729                // Emit regular call when code size is the priority
   1730                !HasMinSizeAttr)
   1731       // "mov lr, pc; b _foo" to avoid confusing the RSP
   1732       CallOpc = ARMISD::CALL_NOLINK;
   1733     else
   1734       CallOpc = isLocalARMFunc ? ARMISD::CALL_PRED : ARMISD::CALL;
   1735   }
   1736 
   1737   std::vector<SDValue> Ops;
   1738   Ops.push_back(Chain);
   1739   Ops.push_back(Callee);
   1740 
   1741   // Add argument registers to the end of the list so that they are known live
   1742   // into the call.
   1743   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
   1744     Ops.push_back(DAG.getRegister(RegsToPass[i].first,
   1745                                   RegsToPass[i].second.getValueType()));
   1746 
   1747   // Add a register mask operand representing the call-preserved registers.
   1748   const uint32_t *Mask;
   1749   const TargetRegisterInfo *TRI = getTargetMachine().getRegisterInfo();
   1750   const ARMBaseRegisterInfo *ARI = static_cast<const ARMBaseRegisterInfo*>(TRI);
   1751   if (isThisReturn) {
   1752     // For 'this' returns, use the R0-preserving mask if applicable
   1753     Mask = ARI->getThisReturnPreservedMask(CallConv);
   1754     if (!Mask) {
   1755       // Set isThisReturn to false if the calling convention is not one that
   1756       // allows 'returned' to be modeled in this way, so LowerCallResult does
   1757       // not try to pass 'this' straight through
   1758       isThisReturn = false;
   1759       Mask = ARI->getCallPreservedMask(CallConv);
   1760     }
   1761   } else
   1762     Mask = ARI->getCallPreservedMask(CallConv);
   1763 
   1764   assert(Mask && "Missing call preserved mask for calling convention");
   1765   Ops.push_back(DAG.getRegisterMask(Mask));
   1766 
   1767   if (InFlag.getNode())
   1768     Ops.push_back(InFlag);
   1769 
   1770   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
   1771   if (isTailCall)
   1772     return DAG.getNode(ARMISD::TC_RETURN, dl, NodeTys, &Ops[0], Ops.size());
   1773 
   1774   // Returns a chain and a flag for retval copy to use.
   1775   Chain = DAG.getNode(CallOpc, dl, NodeTys, &Ops[0], Ops.size());
   1776   InFlag = Chain.getValue(1);
   1777 
   1778   Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, true),
   1779                              DAG.getIntPtrConstant(0, true), InFlag, dl);
   1780   if (!Ins.empty())
   1781     InFlag = Chain.getValue(1);
   1782 
   1783   // Handle result values, copying them out of physregs into vregs that we
   1784   // return.
   1785   return LowerCallResult(Chain, InFlag, CallConv, isVarArg, Ins, dl, DAG,
   1786                          InVals, isThisReturn,
   1787                          isThisReturn ? OutVals[0] : SDValue());
   1788 }
   1789 
   1790 /// HandleByVal - Every parameter *after* a byval parameter is passed
   1791 /// on the stack.  Remember the next parameter register to allocate,
   1792 /// and then confiscate the rest of the parameter registers to insure
   1793 /// this.
   1794 void
   1795 ARMTargetLowering::HandleByVal(
   1796     CCState *State, unsigned &size, unsigned Align) const {
   1797   unsigned reg = State->AllocateReg(GPRArgRegs, 4);
   1798   assert((State->getCallOrPrologue() == Prologue ||
   1799           State->getCallOrPrologue() == Call) &&
   1800          "unhandled ParmContext");
   1801 
   1802   // For in-prologue parameters handling, we also introduce stack offset
   1803   // for byval registers: see CallingConvLower.cpp, CCState::HandleByVal.
   1804   // This behaviour outsides AAPCS rules (5.5 Parameters Passing) of how
   1805   // NSAA should be evaluted (NSAA means "next stacked argument address").
   1806   // So: NextStackOffset = NSAAOffset + SizeOfByValParamsStoredInRegs.
   1807   // Then: NSAAOffset = NextStackOffset - SizeOfByValParamsStoredInRegs.
   1808   unsigned NSAAOffset = State->getNextStackOffset();
   1809   if (State->getCallOrPrologue() != Call) {
   1810     for (unsigned i = 0, e = State->getInRegsParamsCount(); i != e; ++i) {
   1811       unsigned RB, RE;
   1812       State->getInRegsParamInfo(i, RB, RE);
   1813       assert(NSAAOffset >= (RE-RB)*4 &&
   1814              "Stack offset for byval regs doesn't introduced anymore?");
   1815       NSAAOffset -= (RE-RB)*4;
   1816     }
   1817   }
   1818   if ((ARM::R0 <= reg) && (reg <= ARM::R3)) {
   1819     if (Subtarget->isAAPCS_ABI() && Align > 4) {
   1820       unsigned AlignInRegs = Align / 4;
   1821       unsigned Waste = (ARM::R4 - reg) % AlignInRegs;
   1822       for (unsigned i = 0; i < Waste; ++i)
   1823         reg = State->AllocateReg(GPRArgRegs, 4);
   1824     }
   1825     if (reg != 0) {
   1826       unsigned excess = 4 * (ARM::R4 - reg);
   1827 
   1828       // Special case when NSAA != SP and parameter size greater than size of
   1829       // all remained GPR regs. In that case we can't split parameter, we must
   1830       // send it to stack. We also must set NCRN to R4, so waste all
   1831       // remained registers.
   1832       if (Subtarget->isAAPCS_ABI() && NSAAOffset != 0 && size > excess) {
   1833         while (State->AllocateReg(GPRArgRegs, 4))
   1834           ;
   1835         return;
   1836       }
   1837 
   1838       // First register for byval parameter is the first register that wasn't
   1839       // allocated before this method call, so it would be "reg".
   1840       // If parameter is small enough to be saved in range [reg, r4), then
   1841       // the end (first after last) register would be reg + param-size-in-regs,
   1842       // else parameter would be splitted between registers and stack,
   1843       // end register would be r4 in this case.
   1844       unsigned ByValRegBegin = reg;
   1845       unsigned ByValRegEnd = (size < excess) ? reg + size/4 : (unsigned)ARM::R4;
   1846       State->addInRegsParamInfo(ByValRegBegin, ByValRegEnd);
   1847       // Note, first register is allocated in the beginning of function already,
   1848       // allocate remained amount of registers we need.
   1849       for (unsigned i = reg+1; i != ByValRegEnd; ++i)
   1850         State->AllocateReg(GPRArgRegs, 4);
   1851       // At a call site, a byval parameter that is split between
   1852       // registers and memory needs its size truncated here.  In a
   1853       // function prologue, such byval parameters are reassembled in
   1854       // memory, and are not truncated.
   1855       if (State->getCallOrPrologue() == Call) {
   1856         // Make remained size equal to 0 in case, when
   1857         // the whole structure may be stored into registers.
   1858         if (size < excess)
   1859           size = 0;
   1860         else
   1861           size -= excess;
   1862       }
   1863     }
   1864   }
   1865 }
   1866 
   1867 /// MatchingStackOffset - Return true if the given stack call argument is
   1868 /// already available in the same position (relatively) of the caller's
   1869 /// incoming argument stack.
   1870 static
   1871 bool MatchingStackOffset(SDValue Arg, unsigned Offset, ISD::ArgFlagsTy Flags,
   1872                          MachineFrameInfo *MFI, const MachineRegisterInfo *MRI,
   1873                          const TargetInstrInfo *TII) {
   1874   unsigned Bytes = Arg.getValueType().getSizeInBits() / 8;
   1875   int FI = INT_MAX;
   1876   if (Arg.getOpcode() == ISD::CopyFromReg) {
   1877     unsigned VR = cast<RegisterSDNode>(Arg.getOperand(1))->getReg();
   1878     if (!TargetRegisterInfo::isVirtualRegister(VR))
   1879       return false;
   1880     MachineInstr *Def = MRI->getVRegDef(VR);
   1881     if (!Def)
   1882       return false;
   1883     if (!Flags.isByVal()) {
   1884       if (!TII->isLoadFromStackSlot(Def, FI))
   1885         return false;
   1886     } else {
   1887       return false;
   1888     }
   1889   } else if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Arg)) {
   1890     if (Flags.isByVal())
   1891       // ByVal argument is passed in as a pointer but it's now being
   1892       // dereferenced. e.g.
   1893       // define @foo(%struct.X* %A) {
   1894       //   tail call @bar(%struct.X* byval %A)
   1895       // }
   1896       return false;
   1897     SDValue Ptr = Ld->getBasePtr();
   1898     FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr);
   1899     if (!FINode)
   1900       return false;
   1901     FI = FINode->getIndex();
   1902   } else
   1903     return false;
   1904 
   1905   assert(FI != INT_MAX);
   1906   if (!MFI->isFixedObjectIndex(FI))
   1907     return false;
   1908   return Offset == MFI->getObjectOffset(FI) && Bytes == MFI->getObjectSize(FI);
   1909 }
   1910 
   1911 /// IsEligibleForTailCallOptimization - Check whether the call is eligible
   1912 /// for tail call optimization. Targets which want to do tail call
   1913 /// optimization should implement this function.
   1914 bool
   1915 ARMTargetLowering::IsEligibleForTailCallOptimization(SDValue Callee,
   1916                                                      CallingConv::ID CalleeCC,
   1917                                                      bool isVarArg,
   1918                                                      bool isCalleeStructRet,
   1919                                                      bool isCallerStructRet,
   1920                                     const SmallVectorImpl<ISD::OutputArg> &Outs,
   1921                                     const SmallVectorImpl<SDValue> &OutVals,
   1922                                     const SmallVectorImpl<ISD::InputArg> &Ins,
   1923                                                      SelectionDAG& DAG) const {
   1924   const Function *CallerF = DAG.getMachineFunction().getFunction();
   1925   CallingConv::ID CallerCC = CallerF->getCallingConv();
   1926   bool CCMatch = CallerCC == CalleeCC;
   1927 
   1928   // Look for obvious safe cases to perform tail call optimization that do not
   1929   // require ABI changes. This is what gcc calls sibcall.
   1930 
   1931   // Do not sibcall optimize vararg calls unless the call site is not passing
   1932   // any arguments.
   1933   if (isVarArg && !Outs.empty())
   1934     return false;
   1935 
   1936   // Also avoid sibcall optimization if either caller or callee uses struct
   1937   // return semantics.
   1938   if (isCalleeStructRet || isCallerStructRet)
   1939     return false;
   1940 
   1941   // FIXME: Completely disable sibcall for Thumb1 since Thumb1RegisterInfo::
   1942   // emitEpilogue is not ready for them. Thumb tail calls also use t2B, as
   1943   // the Thumb1 16-bit unconditional branch doesn't have sufficient relocation
   1944   // support in the assembler and linker to be used. This would need to be
   1945   // fixed to fully support tail calls in Thumb1.
   1946   //
   1947   // Doing this is tricky, since the LDM/POP instruction on Thumb doesn't take
   1948   // LR.  This means if we need to reload LR, it takes an extra instructions,
   1949   // which outweighs the value of the tail call; but here we don't know yet
   1950   // whether LR is going to be used.  Probably the right approach is to
   1951   // generate the tail call here and turn it back into CALL/RET in
   1952   // emitEpilogue if LR is used.
   1953 
   1954   // Thumb1 PIC calls to external symbols use BX, so they can be tail calls,
   1955   // but we need to make sure there are enough registers; the only valid
   1956   // registers are the 4 used for parameters.  We don't currently do this
   1957   // case.
   1958   if (Subtarget->isThumb1Only())
   1959     return false;
   1960 
   1961   // If the calling conventions do not match, then we'd better make sure the
   1962   // results are returned in the same way as what the caller expects.
   1963   if (!CCMatch) {
   1964     SmallVector<CCValAssign, 16> RVLocs1;
   1965     ARMCCState CCInfo1(CalleeCC, false, DAG.getMachineFunction(),
   1966                        getTargetMachine(), RVLocs1, *DAG.getContext(), Call);
   1967     CCInfo1.AnalyzeCallResult(Ins, CCAssignFnForNode(CalleeCC, true, isVarArg));
   1968 
   1969     SmallVector<CCValAssign, 16> RVLocs2;
   1970     ARMCCState CCInfo2(CallerCC, false, DAG.getMachineFunction(),
   1971                        getTargetMachine(), RVLocs2, *DAG.getContext(), Call);
   1972     CCInfo2.AnalyzeCallResult(Ins, CCAssignFnForNode(CallerCC, true, isVarArg));
   1973 
   1974     if (RVLocs1.size() != RVLocs2.size())
   1975       return false;
   1976     for (unsigned i = 0, e = RVLocs1.size(); i != e; ++i) {
   1977       if (RVLocs1[i].isRegLoc() != RVLocs2[i].isRegLoc())
   1978         return false;
   1979       if (RVLocs1[i].getLocInfo() != RVLocs2[i].getLocInfo())
   1980         return false;
   1981       if (RVLocs1[i].isRegLoc()) {
   1982         if (RVLocs1[i].getLocReg() != RVLocs2[i].getLocReg())
   1983           return false;
   1984       } else {
   1985         if (RVLocs1[i].getLocMemOffset() != RVLocs2[i].getLocMemOffset())
   1986           return false;
   1987       }
   1988     }
   1989   }
   1990 
   1991   // If Caller's vararg or byval argument has been split between registers and
   1992   // stack, do not perform tail call, since part of the argument is in caller's
   1993   // local frame.
   1994   const ARMFunctionInfo *AFI_Caller = DAG.getMachineFunction().
   1995                                       getInfo<ARMFunctionInfo>();
   1996   if (AFI_Caller->getArgRegsSaveSize())
   1997     return false;
   1998 
   1999   // If the callee takes no arguments then go on to check the results of the
   2000   // call.
   2001   if (!Outs.empty()) {
   2002     // Check if stack adjustment is needed. For now, do not do this if any
   2003     // argument is passed on the stack.
   2004     SmallVector<CCValAssign, 16> ArgLocs;
   2005     ARMCCState CCInfo(CalleeCC, isVarArg, DAG.getMachineFunction(),
   2006                       getTargetMachine(), ArgLocs, *DAG.getContext(), Call);
   2007     CCInfo.AnalyzeCallOperands(Outs,
   2008                                CCAssignFnForNode(CalleeCC, false, isVarArg));
   2009     if (CCInfo.getNextStackOffset()) {
   2010       MachineFunction &MF = DAG.getMachineFunction();
   2011 
   2012       // Check if the arguments are already laid out in the right way as
   2013       // the caller's fixed stack objects.
   2014       MachineFrameInfo *MFI = MF.getFrameInfo();
   2015       const MachineRegisterInfo *MRI = &MF.getRegInfo();
   2016       const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
   2017       for (unsigned i = 0, realArgIdx = 0, e = ArgLocs.size();
   2018            i != e;
   2019            ++i, ++realArgIdx) {
   2020         CCValAssign &VA = ArgLocs[i];
   2021         EVT RegVT = VA.getLocVT();
   2022         SDValue Arg = OutVals[realArgIdx];
   2023         ISD::ArgFlagsTy Flags = Outs[realArgIdx].Flags;
   2024         if (VA.getLocInfo() == CCValAssign::Indirect)
   2025           return false;
   2026         if (VA.needsCustom()) {
   2027           // f64 and vector types are split into multiple registers or
   2028           // register/stack-slot combinations.  The types will not match
   2029           // the registers; give up on memory f64 refs until we figure
   2030           // out what to do about this.
   2031           if (!VA.isRegLoc())
   2032             return false;
   2033           if (!ArgLocs[++i].isRegLoc())
   2034             return false;
   2035           if (RegVT == MVT::v2f64) {
   2036             if (!ArgLocs[++i].isRegLoc())
   2037               return false;
   2038             if (!ArgLocs[++i].isRegLoc())
   2039               return false;
   2040           }
   2041         } else if (!VA.isRegLoc()) {
   2042           if (!MatchingStackOffset(Arg, VA.getLocMemOffset(), Flags,
   2043                                    MFI, MRI, TII))
   2044             return false;
   2045         }
   2046       }
   2047     }
   2048   }
   2049 
   2050   return true;
   2051 }
   2052 
   2053 bool
   2054 ARMTargetLowering::CanLowerReturn(CallingConv::ID CallConv,
   2055                                   MachineFunction &MF, bool isVarArg,
   2056                                   const SmallVectorImpl<ISD::OutputArg> &Outs,
   2057                                   LLVMContext &Context) const {
   2058   SmallVector<CCValAssign, 16> RVLocs;
   2059   CCState CCInfo(CallConv, isVarArg, MF, getTargetMachine(), RVLocs, Context);
   2060   return CCInfo.CheckReturn(Outs, CCAssignFnForNode(CallConv, /*Return=*/true,
   2061                                                     isVarArg));
   2062 }
   2063 
   2064 SDValue
   2065 ARMTargetLowering::LowerReturn(SDValue Chain,
   2066                                CallingConv::ID CallConv, bool isVarArg,
   2067                                const SmallVectorImpl<ISD::OutputArg> &Outs,
   2068                                const SmallVectorImpl<SDValue> &OutVals,
   2069                                SDLoc dl, SelectionDAG &DAG) const {
   2070 
   2071   // CCValAssign - represent the assignment of the return value to a location.
   2072   SmallVector<CCValAssign, 16> RVLocs;
   2073 
   2074   // CCState - Info about the registers and stack slots.
   2075   ARMCCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(),
   2076                     getTargetMachine(), RVLocs, *DAG.getContext(), Call);
   2077 
   2078   // Analyze outgoing return values.
   2079   CCInfo.AnalyzeReturn(Outs, CCAssignFnForNode(CallConv, /* Return */ true,
   2080                                                isVarArg));
   2081 
   2082   SDValue Flag;
   2083   SmallVector<SDValue, 4> RetOps;
   2084   RetOps.push_back(Chain); // Operand #0 = Chain (updated below)
   2085 
   2086   // Copy the result values into the output registers.
   2087   for (unsigned i = 0, realRVLocIdx = 0;
   2088        i != RVLocs.size();
   2089        ++i, ++realRVLocIdx) {
   2090     CCValAssign &VA = RVLocs[i];
   2091     assert(VA.isRegLoc() && "Can only return in registers!");
   2092 
   2093     SDValue Arg = OutVals[realRVLocIdx];
   2094 
   2095     switch (VA.getLocInfo()) {
   2096     default: llvm_unreachable("Unknown loc info!");
   2097     case CCValAssign::Full: break;
   2098     case CCValAssign::BCvt:
   2099       Arg = DAG.getNode(ISD::BITCAST, dl, VA.getLocVT(), Arg);
   2100       break;
   2101     }
   2102 
   2103     if (VA.needsCustom()) {
   2104       if (VA.getLocVT() == MVT::v2f64) {
   2105         // Extract the first half and return it in two registers.
   2106         SDValue Half = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg,
   2107                                    DAG.getConstant(0, MVT::i32));
   2108         SDValue HalfGPRs = DAG.getNode(ARMISD::VMOVRRD, dl,
   2109                                        DAG.getVTList(MVT::i32, MVT::i32), Half);
   2110 
   2111         Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), HalfGPRs, Flag);
   2112         Flag = Chain.getValue(1);
   2113         RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
   2114         VA = RVLocs[++i]; // skip ahead to next loc
   2115         Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(),
   2116                                  HalfGPRs.getValue(1), Flag);
   2117         Flag = Chain.getValue(1);
   2118         RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
   2119         VA = RVLocs[++i]; // skip ahead to next loc
   2120 
   2121         // Extract the 2nd half and fall through to handle it as an f64 value.
   2122         Arg = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg,
   2123                           DAG.getConstant(1, MVT::i32));
   2124       }
   2125       // Legalize ret f64 -> ret 2 x i32.  We always have fmrrd if f64 is
   2126       // available.
   2127       SDValue fmrrd = DAG.getNode(ARMISD::VMOVRRD, dl,
   2128                                   DAG.getVTList(MVT::i32, MVT::i32), &Arg, 1);
   2129       Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), fmrrd, Flag);
   2130       Flag = Chain.getValue(1);
   2131       RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
   2132       VA = RVLocs[++i]; // skip ahead to next loc
   2133       Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), fmrrd.getValue(1),
   2134                                Flag);
   2135     } else
   2136       Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), Arg, Flag);
   2137 
   2138     // Guarantee that all emitted copies are
   2139     // stuck together, avoiding something bad.
   2140     Flag = Chain.getValue(1);
   2141     RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
   2142   }
   2143 
   2144   // Update chain and glue.
   2145   RetOps[0] = Chain;
   2146   if (Flag.getNode())
   2147     RetOps.push_back(Flag);
   2148 
   2149   return DAG.getNode(ARMISD::RET_FLAG, dl, MVT::Other,
   2150                      RetOps.data(), RetOps.size());
   2151 }
   2152 
   2153 bool ARMTargetLowering::isUsedByReturnOnly(SDNode *N, SDValue &Chain) const {
   2154   if (N->getNumValues() != 1)
   2155     return false;
   2156   if (!N->hasNUsesOfValue(1, 0))
   2157     return false;
   2158 
   2159   SDValue TCChain = Chain;
   2160   SDNode *Copy = *N->use_begin();
   2161   if (Copy->getOpcode() == ISD::CopyToReg) {
   2162     // If the copy has a glue operand, we conservatively assume it isn't safe to
   2163     // perform a tail call.
   2164     if (Copy->getOperand(Copy->getNumOperands()-1).getValueType() == MVT::Glue)
   2165       return false;
   2166     TCChain = Copy->getOperand(0);
   2167   } else if (Copy->getOpcode() == ARMISD::VMOVRRD) {
   2168     SDNode *VMov = Copy;
   2169     // f64 returned in a pair of GPRs.
   2170     SmallPtrSet<SDNode*, 2> Copies;
   2171     for (SDNode::use_iterator UI = VMov->use_begin(), UE = VMov->use_end();
   2172          UI != UE; ++UI) {
   2173       if (UI->getOpcode() != ISD::CopyToReg)
   2174         return false;
   2175       Copies.insert(*UI);
   2176     }
   2177     if (Copies.size() > 2)
   2178       return false;
   2179 
   2180     for (SDNode::use_iterator UI = VMov->use_begin(), UE = VMov->use_end();
   2181          UI != UE; ++UI) {
   2182       SDValue UseChain = UI->getOperand(0);
   2183       if (Copies.count(UseChain.getNode()))
   2184         // Second CopyToReg
   2185         Copy = *UI;
   2186       else
   2187         // First CopyToReg
   2188         TCChain = UseChain;
   2189     }
   2190   } else if (Copy->getOpcode() == ISD::BITCAST) {
   2191     // f32 returned in a single GPR.
   2192     if (!Copy->hasOneUse())
   2193       return false;
   2194     Copy = *Copy->use_begin();
   2195     if (Copy->getOpcode() != ISD::CopyToReg || !Copy->hasNUsesOfValue(1, 0))
   2196       return false;
   2197     TCChain = Copy->getOperand(0);
   2198   } else {
   2199     return false;
   2200   }
   2201 
   2202   bool HasRet = false;
   2203   for (SDNode::use_iterator UI = Copy->use_begin(), UE = Copy->use_end();
   2204        UI != UE; ++UI) {
   2205     if (UI->getOpcode() != ARMISD::RET_FLAG)
   2206       return false;
   2207     HasRet = true;
   2208   }
   2209 
   2210   if (!HasRet)
   2211     return false;
   2212 
   2213   Chain = TCChain;
   2214   return true;
   2215 }
   2216 
   2217 bool ARMTargetLowering::mayBeEmittedAsTailCall(CallInst *CI) const {
   2218   if (!EnableARMTailCalls && !Subtarget->supportsTailCall())
   2219     return false;
   2220 
   2221   if (!CI->isTailCall())
   2222     return false;
   2223 
   2224   return !Subtarget->isThumb1Only();
   2225 }
   2226 
   2227 // ConstantPool, JumpTable, GlobalAddress, and ExternalSymbol are lowered as
   2228 // their target counterpart wrapped in the ARMISD::Wrapper node. Suppose N is
   2229 // one of the above mentioned nodes. It has to be wrapped because otherwise
   2230 // Select(N) returns N. So the raw TargetGlobalAddress nodes, etc. can only
   2231 // be used to form addressing mode. These wrapped nodes will be selected
   2232 // into MOVi.
   2233 static SDValue LowerConstantPool(SDValue Op, SelectionDAG &DAG) {
   2234   EVT PtrVT = Op.getValueType();
   2235   // FIXME there is no actual debug info here
   2236   SDLoc dl(Op);
   2237   ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
   2238   SDValue Res;
   2239   if (CP->isMachineConstantPoolEntry())
   2240     Res = DAG.getTargetConstantPool(CP->getMachineCPVal(), PtrVT,
   2241                                     CP->getAlignment());
   2242   else
   2243     Res = DAG.getTargetConstantPool(CP->getConstVal(), PtrVT,
   2244                                     CP->getAlignment());
   2245   return DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Res);
   2246 }
   2247 
   2248 unsigned ARMTargetLowering::getJumpTableEncoding() const {
   2249   return MachineJumpTableInfo::EK_Inline;
   2250 }
   2251 
   2252 SDValue ARMTargetLowering::LowerBlockAddress(SDValue Op,
   2253                                              SelectionDAG &DAG) const {
   2254   MachineFunction &MF = DAG.getMachineFunction();
   2255   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
   2256   unsigned ARMPCLabelIndex = 0;
   2257   SDLoc DL(Op);
   2258   EVT PtrVT = getPointerTy();
   2259   const BlockAddress *BA = cast<BlockAddressSDNode>(Op)->getBlockAddress();
   2260   Reloc::Model RelocM = getTargetMachine().getRelocationModel();
   2261   SDValue CPAddr;
   2262   if (RelocM == Reloc::Static) {
   2263     CPAddr = DAG.getTargetConstantPool(BA, PtrVT, 4);
   2264   } else {
   2265     unsigned PCAdj = Subtarget->isThumb() ? 4 : 8;
   2266     ARMPCLabelIndex = AFI->createPICLabelUId();
   2267     ARMConstantPoolValue *CPV =
   2268       ARMConstantPoolConstant::Create(BA, ARMPCLabelIndex,
   2269                                       ARMCP::CPBlockAddress, PCAdj);
   2270     CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4);
   2271   }
   2272   CPAddr = DAG.getNode(ARMISD::Wrapper, DL, PtrVT, CPAddr);
   2273   SDValue Result = DAG.getLoad(PtrVT, DL, DAG.getEntryNode(), CPAddr,
   2274                                MachinePointerInfo::getConstantPool(),
   2275                                false, false, false, 0);
   2276   if (RelocM == Reloc::Static)
   2277     return Result;
   2278   SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, MVT::i32);
   2279   return DAG.getNode(ARMISD::PIC_ADD, DL, PtrVT, Result, PICLabel);
   2280 }
   2281 
   2282 // Lower ISD::GlobalTLSAddress using the "general dynamic" model
   2283 SDValue
   2284 ARMTargetLowering::LowerToTLSGeneralDynamicModel(GlobalAddressSDNode *GA,
   2285                                                  SelectionDAG &DAG) const {
   2286   SDLoc dl(GA);
   2287   EVT PtrVT = getPointerTy();
   2288   unsigned char PCAdj = Subtarget->isThumb() ? 4 : 8;
   2289   MachineFunction &MF = DAG.getMachineFunction();
   2290   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
   2291   unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
   2292   ARMConstantPoolValue *CPV =
   2293     ARMConstantPoolConstant::Create(GA->getGlobal(), ARMPCLabelIndex,
   2294                                     ARMCP::CPValue, PCAdj, ARMCP::TLSGD, true);
   2295   SDValue Argument = DAG.getTargetConstantPool(CPV, PtrVT, 4);
   2296   Argument = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Argument);
   2297   Argument = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Argument,
   2298                          MachinePointerInfo::getConstantPool(),
   2299                          false, false, false, 0);
   2300   SDValue Chain = Argument.getValue(1);
   2301 
   2302   SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, MVT::i32);
   2303   Argument = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Argument, PICLabel);
   2304 
   2305   // call __tls_get_addr.
   2306   ArgListTy Args;
   2307   ArgListEntry Entry;
   2308   Entry.Node = Argument;
   2309   Entry.Ty = (Type *) Type::getInt32Ty(*DAG.getContext());
   2310   Args.push_back(Entry);
   2311   // FIXME: is there useful debug info available here?
   2312   TargetLowering::CallLoweringInfo CLI(Chain,
   2313                 (Type *) Type::getInt32Ty(*DAG.getContext()),
   2314                 false, false, false, false,
   2315                 0, CallingConv::C, /*isTailCall=*/false,
   2316                 /*doesNotRet=*/false, /*isReturnValueUsed=*/true,
   2317                 DAG.getExternalSymbol("__tls_get_addr", PtrVT), Args, DAG, dl);
   2318   std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI);
   2319   return CallResult.first;
   2320 }
   2321 
   2322 // Lower ISD::GlobalTLSAddress using the "initial exec" or
   2323 // "local exec" model.
   2324 SDValue
   2325 ARMTargetLowering::LowerToTLSExecModels(GlobalAddressSDNode *GA,
   2326                                         SelectionDAG &DAG,
   2327                                         TLSModel::Model model) const {
   2328   const GlobalValue *GV = GA->getGlobal();
   2329   SDLoc dl(GA);
   2330   SDValue Offset;
   2331   SDValue Chain = DAG.getEntryNode();
   2332   EVT PtrVT = getPointerTy();
   2333   // Get the Thread Pointer
   2334   SDValue ThreadPointer = DAG.getNode(ARMISD::THREAD_POINTER, dl, PtrVT);
   2335 
   2336   if (model == TLSModel::InitialExec) {
   2337     MachineFunction &MF = DAG.getMachineFunction();
   2338     ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
   2339     unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
   2340     // Initial exec model.
   2341     unsigned char PCAdj = Subtarget->isThumb() ? 4 : 8;
   2342     ARMConstantPoolValue *CPV =
   2343       ARMConstantPoolConstant::Create(GA->getGlobal(), ARMPCLabelIndex,
   2344                                       ARMCP::CPValue, PCAdj, ARMCP::GOTTPOFF,
   2345                                       true);
   2346     Offset = DAG.getTargetConstantPool(CPV, PtrVT, 4);
   2347     Offset = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Offset);
   2348     Offset = DAG.getLoad(PtrVT, dl, Chain, Offset,
   2349                          MachinePointerInfo::getConstantPool(),
   2350                          false, false, false, 0);
   2351     Chain = Offset.getValue(1);
   2352 
   2353     SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, MVT::i32);
   2354     Offset = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Offset, PICLabel);
   2355 
   2356     Offset = DAG.getLoad(PtrVT, dl, Chain, Offset,
   2357                          MachinePointerInfo::getConstantPool(),
   2358                          false, false, false, 0);
   2359   } else {
   2360     // local exec model
   2361     assert(model == TLSModel::LocalExec);
   2362     ARMConstantPoolValue *CPV =
   2363       ARMConstantPoolConstant::Create(GV, ARMCP::TPOFF);
   2364     Offset = DAG.getTargetConstantPool(CPV, PtrVT, 4);
   2365     Offset = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Offset);
   2366     Offset = DAG.getLoad(PtrVT, dl, Chain, Offset,
   2367                          MachinePointerInfo::getConstantPool(),
   2368                          false, false, false, 0);
   2369   }
   2370 
   2371   // The address of the thread local variable is the add of the thread
   2372   // pointer with the offset of the variable.
   2373   return DAG.getNode(ISD::ADD, dl, PtrVT, ThreadPointer, Offset);
   2374 }
   2375 
   2376 SDValue
   2377 ARMTargetLowering::LowerGlobalTLSAddress(SDValue Op, SelectionDAG &DAG) const {
   2378   // TODO: implement the "local dynamic" model
   2379   assert(Subtarget->isTargetELF() &&
   2380          "TLS not implemented for non-ELF targets");
   2381   GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
   2382 
   2383   TLSModel::Model model = getTargetMachine().getTLSModel(GA->getGlobal());
   2384 
   2385   switch (model) {
   2386     case TLSModel::GeneralDynamic:
   2387     case TLSModel::LocalDynamic:
   2388       return LowerToTLSGeneralDynamicModel(GA, DAG);
   2389     case TLSModel::InitialExec:
   2390     case TLSModel::LocalExec:
   2391       return LowerToTLSExecModels(GA, DAG, model);
   2392   }
   2393   llvm_unreachable("bogus TLS model");
   2394 }
   2395 
   2396 SDValue ARMTargetLowering::LowerGlobalAddressELF(SDValue Op,
   2397                                                  SelectionDAG &DAG) const {
   2398   EVT PtrVT = getPointerTy();
   2399   SDLoc dl(Op);
   2400   const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
   2401   if (getTargetMachine().getRelocationModel() == Reloc::PIC_) {
   2402     bool UseGOTOFF = GV->hasLocalLinkage() || GV->hasHiddenVisibility();
   2403     ARMConstantPoolValue *CPV =
   2404       ARMConstantPoolConstant::Create(GV,
   2405                                       UseGOTOFF ? ARMCP::GOTOFF : ARMCP::GOT);
   2406     SDValue CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4);
   2407     CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
   2408     SDValue Result = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(),
   2409                                  CPAddr,
   2410                                  MachinePointerInfo::getConstantPool(),
   2411                                  false, false, false, 0);
   2412     SDValue Chain = Result.getValue(1);
   2413     SDValue GOT = DAG.getGLOBAL_OFFSET_TABLE(PtrVT);
   2414     Result = DAG.getNode(ISD::ADD, dl, PtrVT, Result, GOT);
   2415     if (!UseGOTOFF)
   2416       Result = DAG.getLoad(PtrVT, dl, Chain, Result,
   2417                            MachinePointerInfo::getGOT(),
   2418                            false, false, false, 0);
   2419     return Result;
   2420   }
   2421 
   2422   // If we have T2 ops, we can materialize the address directly via movt/movw
   2423   // pair. This is always cheaper.
   2424   if (Subtarget->useMovt()) {
   2425     ++NumMovwMovt;
   2426     // FIXME: Once remat is capable of dealing with instructions with register
   2427     // operands, expand this into two nodes.
   2428     return DAG.getNode(ARMISD::Wrapper, dl, PtrVT,
   2429                        DAG.getTargetGlobalAddress(GV, dl, PtrVT));
   2430   } else {
   2431     SDValue CPAddr = DAG.getTargetConstantPool(GV, PtrVT, 4);
   2432     CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
   2433     return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), CPAddr,
   2434                        MachinePointerInfo::getConstantPool(),
   2435                        false, false, false, 0);
   2436   }
   2437 }
   2438 
   2439 SDValue ARMTargetLowering::LowerGlobalAddressDarwin(SDValue Op,
   2440                                                     SelectionDAG &DAG) const {
   2441   EVT PtrVT = getPointerTy();
   2442   SDLoc dl(Op);
   2443   const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
   2444   Reloc::Model RelocM = getTargetMachine().getRelocationModel();
   2445 
   2446   // FIXME: Enable this for static codegen when tool issues are fixed.  Also
   2447   // update ARMFastISel::ARMMaterializeGV.
   2448   if (Subtarget->useMovt() && RelocM != Reloc::Static) {
   2449     ++NumMovwMovt;
   2450     // FIXME: Once remat is capable of dealing with instructions with register
   2451     // operands, expand this into two nodes.
   2452     if (RelocM == Reloc::Static)
   2453       return DAG.getNode(ARMISD::Wrapper, dl, PtrVT,
   2454                                  DAG.getTargetGlobalAddress(GV, dl, PtrVT));
   2455 
   2456     unsigned Wrapper = (RelocM == Reloc::PIC_)
   2457       ? ARMISD::WrapperPIC : ARMISD::WrapperDYN;
   2458     SDValue Result = DAG.getNode(Wrapper, dl, PtrVT,
   2459                                  DAG.getTargetGlobalAddress(GV, dl, PtrVT));
   2460     if (Subtarget->GVIsIndirectSymbol(GV, RelocM))
   2461       Result = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Result,
   2462                            MachinePointerInfo::getGOT(),
   2463                            false, false, false, 0);
   2464     return Result;
   2465   }
   2466 
   2467   unsigned ARMPCLabelIndex = 0;
   2468   SDValue CPAddr;
   2469   if (RelocM == Reloc::Static) {
   2470     CPAddr = DAG.getTargetConstantPool(GV, PtrVT, 4);
   2471   } else {
   2472     ARMFunctionInfo *AFI = DAG.getMachineFunction().getInfo<ARMFunctionInfo>();
   2473     ARMPCLabelIndex = AFI->createPICLabelUId();
   2474     unsigned PCAdj = (RelocM != Reloc::PIC_) ? 0 : (Subtarget->isThumb()?4:8);
   2475     ARMConstantPoolValue *CPV =
   2476       ARMConstantPoolConstant::Create(GV, ARMPCLabelIndex, ARMCP::CPValue,
   2477                                       PCAdj);
   2478     CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4);
   2479   }
   2480   CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
   2481 
   2482   SDValue Result = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), CPAddr,
   2483                                MachinePointerInfo::getConstantPool(),
   2484                                false, false, false, 0);
   2485   SDValue Chain = Result.getValue(1);
   2486 
   2487   if (RelocM == Reloc::PIC_) {
   2488     SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, MVT::i32);
   2489     Result = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Result, PICLabel);
   2490   }
   2491 
   2492   if (Subtarget->GVIsIndirectSymbol(GV, RelocM))
   2493     Result = DAG.getLoad(PtrVT, dl, Chain, Result, MachinePointerInfo::getGOT(),
   2494                          false, false, false, 0);
   2495 
   2496   return Result;
   2497 }
   2498 
   2499 SDValue ARMTargetLowering::LowerGLOBAL_OFFSET_TABLE(SDValue Op,
   2500                                                     SelectionDAG &DAG) const {
   2501   assert(Subtarget->isTargetELF() &&
   2502          "GLOBAL OFFSET TABLE not implemented for non-ELF targets");
   2503   MachineFunction &MF = DAG.getMachineFunction();
   2504   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
   2505   unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
   2506   EVT PtrVT = getPointerTy();
   2507   SDLoc dl(Op);
   2508   unsigned PCAdj = Subtarget->isThumb() ? 4 : 8;
   2509   ARMConstantPoolValue *CPV =
   2510     ARMConstantPoolSymbol::Create(*DAG.getContext(), "_GLOBAL_OFFSET_TABLE_",
   2511                                   ARMPCLabelIndex, PCAdj);
   2512   SDValue CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4);
   2513   CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
   2514   SDValue Result = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), CPAddr,
   2515                                MachinePointerInfo::getConstantPool(),
   2516                                false, false, false, 0);
   2517   SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, MVT::i32);
   2518   return DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Result, PICLabel);
   2519 }
   2520 
   2521 SDValue
   2522 ARMTargetLowering::LowerEH_SJLJ_SETJMP(SDValue Op, SelectionDAG &DAG) const {
   2523   SDLoc dl(Op);
   2524   SDValue Val = DAG.getConstant(0, MVT::i32);
   2525   return DAG.getNode(ARMISD::EH_SJLJ_SETJMP, dl,
   2526                      DAG.getVTList(MVT::i32, MVT::Other), Op.getOperand(0),
   2527                      Op.getOperand(1), Val);
   2528 }
   2529 
   2530 SDValue
   2531 ARMTargetLowering::LowerEH_SJLJ_LONGJMP(SDValue Op, SelectionDAG &DAG) const {
   2532   SDLoc dl(Op);
   2533   return DAG.getNode(ARMISD::EH_SJLJ_LONGJMP, dl, MVT::Other, Op.getOperand(0),
   2534                      Op.getOperand(1), DAG.getConstant(0, MVT::i32));
   2535 }
   2536 
   2537 SDValue
   2538 ARMTargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op, SelectionDAG &DAG,
   2539                                           const ARMSubtarget *Subtarget) const {
   2540   unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
   2541   SDLoc dl(Op);
   2542   switch (IntNo) {
   2543   default: return SDValue();    // Don't custom lower most intrinsics.
   2544   case Intrinsic::arm_thread_pointer: {
   2545     EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
   2546     return DAG.getNode(ARMISD::THREAD_POINTER, dl, PtrVT);
   2547   }
   2548   case Intrinsic::eh_sjlj_lsda: {
   2549     MachineFunction &MF = DAG.getMachineFunction();
   2550     ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
   2551     unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
   2552     EVT PtrVT = getPointerTy();
   2553     Reloc::Model RelocM = getTargetMachine().getRelocationModel();
   2554     SDValue CPAddr;
   2555     unsigned PCAdj = (RelocM != Reloc::PIC_)
   2556       ? 0 : (Subtarget->isThumb() ? 4 : 8);
   2557     ARMConstantPoolValue *CPV =
   2558       ARMConstantPoolConstant::Create(MF.getFunction(), ARMPCLabelIndex,
   2559                                       ARMCP::CPLSDA, PCAdj);
   2560     CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4);
   2561     CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
   2562     SDValue Result =
   2563       DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), CPAddr,
   2564                   MachinePointerInfo::getConstantPool(),
   2565                   false, false, false, 0);
   2566 
   2567     if (RelocM == Reloc::PIC_) {
   2568       SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, MVT::i32);
   2569       Result = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Result, PICLabel);
   2570     }
   2571     return Result;
   2572   }
   2573   case Intrinsic::arm_neon_vmulls:
   2574   case Intrinsic::arm_neon_vmullu: {
   2575     unsigned NewOpc = (IntNo == Intrinsic::arm_neon_vmulls)
   2576       ? ARMISD::VMULLs : ARMISD::VMULLu;
   2577     return DAG.getNode(NewOpc, SDLoc(Op), Op.getValueType(),
   2578                        Op.getOperand(1), Op.getOperand(2));
   2579   }
   2580   }
   2581 }
   2582 
   2583 static SDValue LowerATOMIC_FENCE(SDValue Op, SelectionDAG &DAG,
   2584                                  const ARMSubtarget *Subtarget) {
   2585   // FIXME: handle "fence singlethread" more efficiently.
   2586   SDLoc dl(Op);
   2587   if (!Subtarget->hasDataBarrier()) {
   2588     // Some ARMv6 cpus can support data barriers with an mcr instruction.
   2589     // Thumb1 and pre-v6 ARM mode use a libcall instead and should never get
   2590     // here.
   2591     assert(Subtarget->hasV6Ops() && !Subtarget->isThumb() &&
   2592            "Unexpected ISD::MEMBARRIER encountered. Should be libcall!");
   2593     return DAG.getNode(ARMISD::MEMBARRIER_MCR, dl, MVT::Other, Op.getOperand(0),
   2594                        DAG.getConstant(0, MVT::i32));
   2595   }
   2596 
   2597   ConstantSDNode *OrdN = cast<ConstantSDNode>(Op.getOperand(1));
   2598   AtomicOrdering Ord = static_cast<AtomicOrdering>(OrdN->getZExtValue());
   2599   unsigned Domain = ARM_MB::ISH;
   2600   if (Subtarget->isSwift() && Ord == Release) {
   2601     // Swift happens to implement ISHST barriers in a way that's compatible with
   2602     // Release semantics but weaker than ISH so we'd be fools not to use
   2603     // it. Beware: other processors probably don't!
   2604     Domain = ARM_MB::ISHST;
   2605   }
   2606 
   2607   return DAG.getNode(ARMISD::MEMBARRIER, dl, MVT::Other, Op.getOperand(0),
   2608                      DAG.getConstant(Domain, MVT::i32));
   2609 }
   2610 
   2611 static SDValue LowerPREFETCH(SDValue Op, SelectionDAG &DAG,
   2612                              const ARMSubtarget *Subtarget) {
   2613   // ARM pre v5TE and Thumb1 does not have preload instructions.
   2614   if (!(Subtarget->isThumb2() ||
   2615         (!Subtarget->isThumb1Only() && Subtarget->hasV5TEOps())))
   2616     // Just preserve the chain.
   2617     return Op.getOperand(0);
   2618 
   2619   SDLoc dl(Op);
   2620   unsigned isRead = ~cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue() & 1;
   2621   if (!isRead &&
   2622       (!Subtarget->hasV7Ops() || !Subtarget->hasMPExtension()))
   2623     // ARMv7 with MP extension has PLDW.
   2624     return Op.getOperand(0);
   2625 
   2626   unsigned isData = cast<ConstantSDNode>(Op.getOperand(4))->getZExtValue();
   2627   if (Subtarget->isThumb()) {
   2628     // Invert the bits.
   2629     isRead = ~isRead & 1;
   2630     isData = ~isData & 1;
   2631   }
   2632 
   2633   return DAG.getNode(ARMISD::PRELOAD, dl, MVT::Other, Op.getOperand(0),
   2634                      Op.getOperand(1), DAG.getConstant(isRead, MVT::i32),
   2635                      DAG.getConstant(isData, MVT::i32));
   2636 }
   2637 
   2638 static SDValue LowerVASTART(SDValue Op, SelectionDAG &DAG) {
   2639   MachineFunction &MF = DAG.getMachineFunction();
   2640   ARMFunctionInfo *FuncInfo = MF.getInfo<ARMFunctionInfo>();
   2641 
   2642   // vastart just stores the address of the VarArgsFrameIndex slot into the
   2643   // memory location argument.
   2644   SDLoc dl(Op);
   2645   EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
   2646   SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT);
   2647   const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
   2648   return DAG.getStore(Op.getOperand(0), dl, FR, Op.getOperand(1),
   2649                       MachinePointerInfo(SV), false, false, 0);
   2650 }
   2651 
   2652 SDValue
   2653 ARMTargetLowering::GetF64FormalArgument(CCValAssign &VA, CCValAssign &NextVA,
   2654                                         SDValue &Root, SelectionDAG &DAG,
   2655                                         SDLoc dl) const {
   2656   MachineFunction &MF = DAG.getMachineFunction();
   2657   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
   2658 
   2659   const TargetRegisterClass *RC;
   2660   if (AFI->isThumb1OnlyFunction())
   2661     RC = &ARM::tGPRRegClass;
   2662   else
   2663     RC = &ARM::GPRRegClass;
   2664 
   2665   // Transform the arguments stored in physical registers into virtual ones.
   2666   unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
   2667   SDValue ArgValue = DAG.getCopyFromReg(Root, dl, Reg, MVT::i32);
   2668 
   2669   SDValue ArgValue2;
   2670   if (NextVA.isMemLoc()) {
   2671     MachineFrameInfo *MFI = MF.getFrameInfo();
   2672     int FI = MFI->CreateFixedObject(4, NextVA.getLocMemOffset(), true);
   2673 
   2674     // Create load node to retrieve arguments from the stack.
   2675     SDValue FIN = DAG.getFrameIndex(FI, getPointerTy());
   2676     ArgValue2 = DAG.getLoad(MVT::i32, dl, Root, FIN,
   2677                             MachinePointerInfo::getFixedStack(FI),
   2678                             false, false, false, 0);
   2679   } else {
   2680     Reg = MF.addLiveIn(NextVA.getLocReg(), RC);
   2681     ArgValue2 = DAG.getCopyFromReg(Root, dl, Reg, MVT::i32);
   2682   }
   2683 
   2684   return DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, ArgValue, ArgValue2);
   2685 }
   2686 
   2687 void
   2688 ARMTargetLowering::computeRegArea(CCState &CCInfo, MachineFunction &MF,
   2689                                   unsigned InRegsParamRecordIdx,
   2690                                   unsigned ArgSize,
   2691                                   unsigned &ArgRegsSize,
   2692                                   unsigned &ArgRegsSaveSize)
   2693   const {
   2694   unsigned NumGPRs;
   2695   if (InRegsParamRecordIdx < CCInfo.getInRegsParamsCount()) {
   2696     unsigned RBegin, REnd;
   2697     CCInfo.getInRegsParamInfo(InRegsParamRecordIdx, RBegin, REnd);
   2698     NumGPRs = REnd - RBegin;
   2699   } else {
   2700     unsigned int firstUnalloced;
   2701     firstUnalloced = CCInfo.getFirstUnallocated(GPRArgRegs,
   2702                                                 sizeof(GPRArgRegs) /
   2703                                                 sizeof(GPRArgRegs[0]));
   2704     NumGPRs = (firstUnalloced <= 3) ? (4 - firstUnalloced) : 0;
   2705   }
   2706 
   2707   unsigned Align = MF.getTarget().getFrameLowering()->getStackAlignment();
   2708   ArgRegsSize = NumGPRs * 4;
   2709 
   2710   // If parameter is split between stack and GPRs...
   2711   if (NumGPRs && Align == 8 &&
   2712       (ArgRegsSize < ArgSize ||
   2713         InRegsParamRecordIdx >= CCInfo.getInRegsParamsCount())) {
   2714     // Add padding for part of param recovered from GPRs, so
   2715     // its last byte must be at address K*8 - 1.
   2716     // We need to do it, since remained (stack) part of parameter has
   2717     // stack alignment, and we need to "attach" "GPRs head" without gaps
   2718     // to it:
   2719     // Stack:
   2720     // |---- 8 bytes block ----| |---- 8 bytes block ----| |---- 8 bytes...
   2721     // [ [padding] [GPRs head] ] [        Tail passed via stack       ....
   2722     //
   2723     ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
   2724     unsigned Padding =
   2725         ((ArgRegsSize + AFI->getArgRegsSaveSize() + Align - 1) & ~(Align-1)) -
   2726         (ArgRegsSize + AFI->getArgRegsSaveSize());
   2727     ArgRegsSaveSize = ArgRegsSize + Padding;
   2728   } else
   2729     // We don't need to extend regs save size for byval parameters if they
   2730     // are passed via GPRs only.
   2731     ArgRegsSaveSize = ArgRegsSize;
   2732 }
   2733 
   2734 // The remaining GPRs hold either the beginning of variable-argument
   2735 // data, or the beginning of an aggregate passed by value (usually
   2736 // byval).  Either way, we allocate stack slots adjacent to the data
   2737 // provided by our caller, and store the unallocated registers there.
   2738 // If this is a variadic function, the va_list pointer will begin with
   2739 // these values; otherwise, this reassembles a (byval) structure that
   2740 // was split between registers and memory.
   2741 // Return: The frame index registers were stored into.
   2742 int
   2743 ARMTargetLowering::StoreByValRegs(CCState &CCInfo, SelectionDAG &DAG,
   2744                                   SDLoc dl, SDValue &Chain,
   2745                                   const Value *OrigArg,
   2746                                   unsigned InRegsParamRecordIdx,
   2747                                   unsigned OffsetFromOrigArg,
   2748                                   unsigned ArgOffset,
   2749                                   unsigned ArgSize,
   2750                                   bool ForceMutable) const {
   2751 
   2752   // Currently, two use-cases possible:
   2753   // Case #1. Non var-args function, and we meet first byval parameter.
   2754   //          Setup first unallocated register as first byval register;
   2755   //          eat all remained registers
   2756   //          (these two actions are performed by HandleByVal method).
   2757   //          Then, here, we initialize stack frame with
   2758   //          "store-reg" instructions.
   2759   // Case #2. Var-args function, that doesn't contain byval parameters.
   2760   //          The same: eat all remained unallocated registers,
   2761   //          initialize stack frame.
   2762 
   2763   MachineFunction &MF = DAG.getMachineFunction();
   2764   MachineFrameInfo *MFI = MF.getFrameInfo();
   2765   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
   2766   unsigned firstRegToSaveIndex, lastRegToSaveIndex;
   2767   unsigned RBegin, REnd;
   2768   if (InRegsParamRecordIdx < CCInfo.getInRegsParamsCount()) {
   2769     CCInfo.getInRegsParamInfo(InRegsParamRecordIdx, RBegin, REnd);
   2770     firstRegToSaveIndex = RBegin - ARM::R0;
   2771     lastRegToSaveIndex = REnd - ARM::R0;
   2772   } else {
   2773     firstRegToSaveIndex = CCInfo.getFirstUnallocated
   2774       (GPRArgRegs, array_lengthof(GPRArgRegs));
   2775     lastRegToSaveIndex = 4;
   2776   }
   2777 
   2778   unsigned ArgRegsSize, ArgRegsSaveSize;
   2779   computeRegArea(CCInfo, MF, InRegsParamRecordIdx, ArgSize,
   2780                  ArgRegsSize, ArgRegsSaveSize);
   2781 
   2782   // Store any by-val regs to their spots on the stack so that they may be
   2783   // loaded by deferencing the result of formal parameter pointer or va_next.
   2784   // Note: once stack area for byval/varargs registers
   2785   // was initialized, it can't be initialized again.
   2786   if (ArgRegsSaveSize) {
   2787 
   2788     unsigned Padding = ArgRegsSaveSize - ArgRegsSize;
   2789 
   2790     if (Padding) {
   2791       assert(AFI->getStoredByValParamsPadding() == 0 &&
   2792              "The only parameter may be padded.");
   2793       AFI->setStoredByValParamsPadding(Padding);
   2794     }
   2795 
   2796     int FrameIndex = MFI->CreateFixedObject(
   2797                       ArgRegsSaveSize,
   2798                       Padding + ArgOffset,
   2799                       false);
   2800     SDValue FIN = DAG.getFrameIndex(FrameIndex, getPointerTy());
   2801 
   2802     SmallVector<SDValue, 4> MemOps;
   2803     for (unsigned i = 0; firstRegToSaveIndex < lastRegToSaveIndex;
   2804          ++firstRegToSaveIndex, ++i) {
   2805       const TargetRegisterClass *RC;
   2806       if (AFI->isThumb1OnlyFunction())
   2807         RC = &ARM::tGPRRegClass;
   2808       else
   2809         RC = &ARM::GPRRegClass;
   2810 
   2811       unsigned VReg = MF.addLiveIn(GPRArgRegs[firstRegToSaveIndex], RC);
   2812       SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i32);
   2813       SDValue Store =
   2814         DAG.getStore(Val.getValue(1), dl, Val, FIN,
   2815                      MachinePointerInfo(OrigArg, OffsetFromOrigArg + 4*i),
   2816                      false, false, 0);
   2817       MemOps.push_back(Store);
   2818       FIN = DAG.getNode(ISD::ADD, dl, getPointerTy(), FIN,
   2819                         DAG.getConstant(4, getPointerTy()));
   2820     }
   2821 
   2822     AFI->setArgRegsSaveSize(ArgRegsSaveSize + AFI->getArgRegsSaveSize());
   2823 
   2824     if (!MemOps.empty())
   2825       Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
   2826                           &MemOps[0], MemOps.size());
   2827     return FrameIndex;
   2828   } else
   2829     // This will point to the next argument passed via stack.
   2830     return MFI->CreateFixedObject(
   2831         4, AFI->getStoredByValParamsPadding() + ArgOffset, !ForceMutable);
   2832 }
   2833 
   2834 // Setup stack frame, the va_list pointer will start from.
   2835 void
   2836 ARMTargetLowering::VarArgStyleRegisters(CCState &CCInfo, SelectionDAG &DAG,
   2837                                         SDLoc dl, SDValue &Chain,
   2838                                         unsigned ArgOffset,
   2839                                         bool ForceMutable) const {
   2840   MachineFunction &MF = DAG.getMachineFunction();
   2841   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
   2842 
   2843   // Try to store any remaining integer argument regs
   2844   // to their spots on the stack so that they may be loaded by deferencing
   2845   // the result of va_next.
   2846   // If there is no regs to be stored, just point address after last
   2847   // argument passed via stack.
   2848   int FrameIndex =
   2849     StoreByValRegs(CCInfo, DAG, dl, Chain, 0, CCInfo.getInRegsParamsCount(),
   2850                    0, ArgOffset, 0, ForceMutable);
   2851 
   2852   AFI->setVarArgsFrameIndex(FrameIndex);
   2853 }
   2854 
   2855 SDValue
   2856 ARMTargetLowering::LowerFormalArguments(SDValue Chain,
   2857                                         CallingConv::ID CallConv, bool isVarArg,
   2858                                         const SmallVectorImpl<ISD::InputArg>
   2859                                           &Ins,
   2860                                         SDLoc dl, SelectionDAG &DAG,
   2861                                         SmallVectorImpl<SDValue> &InVals)
   2862                                           const {
   2863   MachineFunction &MF = DAG.getMachineFunction();
   2864   MachineFrameInfo *MFI = MF.getFrameInfo();
   2865 
   2866   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
   2867 
   2868   // Assign locations to all of the incoming arguments.
   2869   SmallVector<CCValAssign, 16> ArgLocs;
   2870   ARMCCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(),
   2871                     getTargetMachine(), ArgLocs, *DAG.getContext(), Prologue);
   2872   CCInfo.AnalyzeFormalArguments(Ins,
   2873                                 CCAssignFnForNode(CallConv, /* Return*/ false,
   2874                                                   isVarArg));
   2875 
   2876   SmallVector<SDValue, 16> ArgValues;
   2877   int lastInsIndex = -1;
   2878   SDValue ArgValue;
   2879   Function::const_arg_iterator CurOrigArg = MF.getFunction()->arg_begin();
   2880   unsigned CurArgIdx = 0;
   2881 
   2882   // Initially ArgRegsSaveSize is zero.
   2883   // Then we increase this value each time we meet byval parameter.
   2884   // We also increase this value in case of varargs function.
   2885   AFI->setArgRegsSaveSize(0);
   2886 
   2887   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
   2888     CCValAssign &VA = ArgLocs[i];
   2889     std::advance(CurOrigArg, Ins[VA.getValNo()].OrigArgIndex - CurArgIdx);
   2890     CurArgIdx = Ins[VA.getValNo()].OrigArgIndex;
   2891     // Arguments stored in registers.
   2892     if (VA.isRegLoc()) {
   2893       EVT RegVT = VA.getLocVT();
   2894 
   2895       if (VA.needsCustom()) {
   2896         // f64 and vector types are split up into multiple registers or
   2897         // combinations of registers and stack slots.
   2898         if (VA.getLocVT() == MVT::v2f64) {
   2899           SDValue ArgValue1 = GetF64FormalArgument(VA, ArgLocs[++i],
   2900                                                    Chain, DAG, dl);
   2901           VA = ArgLocs[++i]; // skip ahead to next loc
   2902           SDValue ArgValue2;
   2903           if (VA.isMemLoc()) {
   2904             int FI = MFI->CreateFixedObject(8, VA.getLocMemOffset(), true);
   2905             SDValue FIN = DAG.getFrameIndex(FI, getPointerTy());
   2906             ArgValue2 = DAG.getLoad(MVT::f64, dl, Chain, FIN,
   2907                                     MachinePointerInfo::getFixedStack(FI),
   2908                                     false, false, false, 0);
   2909           } else {
   2910             ArgValue2 = GetF64FormalArgument(VA, ArgLocs[++i],
   2911                                              Chain, DAG, dl);
   2912           }
   2913           ArgValue = DAG.getNode(ISD::UNDEF, dl, MVT::v2f64);
   2914           ArgValue = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64,
   2915                                  ArgValue, ArgValue1, DAG.getIntPtrConstant(0));
   2916           ArgValue = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64,
   2917                                  ArgValue, ArgValue2, DAG.getIntPtrConstant(1));
   2918         } else
   2919           ArgValue = GetF64FormalArgument(VA, ArgLocs[++i], Chain, DAG, dl);
   2920 
   2921       } else {
   2922         const TargetRegisterClass *RC;
   2923 
   2924         if (RegVT == MVT::f32)
   2925           RC = &ARM::SPRRegClass;
   2926         else if (RegVT == MVT::f64)
   2927           RC = &ARM::DPRRegClass;
   2928         else if (RegVT == MVT::v2f64)
   2929           RC = &ARM::QPRRegClass;
   2930         else if (RegVT == MVT::i32)
   2931           RC = AFI->isThumb1OnlyFunction() ?
   2932             (const TargetRegisterClass*)&ARM::tGPRRegClass :
   2933             (const TargetRegisterClass*)&ARM::GPRRegClass;
   2934         else
   2935           llvm_unreachable("RegVT not supported by FORMAL_ARGUMENTS Lowering");
   2936 
   2937         // Transform the arguments in physical registers into virtual ones.
   2938         unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
   2939         ArgValue = DAG.getCopyFromReg(Chain, dl, Reg, RegVT);
   2940       }
   2941 
   2942       // If this is an 8 or 16-bit value, it is really passed promoted
   2943       // to 32 bits.  Insert an assert[sz]ext to capture this, then
   2944       // truncate to the right size.
   2945       switch (VA.getLocInfo()) {
   2946       default: llvm_unreachable("Unknown loc info!");
   2947       case CCValAssign::Full: break;
   2948       case CCValAssign::BCvt:
   2949         ArgValue = DAG.getNode(ISD::BITCAST, dl, VA.getValVT(), ArgValue);
   2950         break;
   2951       case CCValAssign::SExt:
   2952         ArgValue = DAG.getNode(ISD::AssertSext, dl, RegVT, ArgValue,
   2953                                DAG.getValueType(VA.getValVT()));
   2954         ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue);
   2955         break;
   2956       case CCValAssign::ZExt:
   2957         ArgValue = DAG.getNode(ISD::AssertZext, dl, RegVT, ArgValue,
   2958                                DAG.getValueType(VA.getValVT()));
   2959         ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue);
   2960         break;
   2961       }
   2962 
   2963       InVals.push_back(ArgValue);
   2964 
   2965     } else { // VA.isRegLoc()
   2966 
   2967       // sanity check
   2968       assert(VA.isMemLoc());
   2969       assert(VA.getValVT() != MVT::i64 && "i64 should already be lowered");
   2970 
   2971       int index = ArgLocs[i].getValNo();
   2972 
   2973       // Some Ins[] entries become multiple ArgLoc[] entries.
   2974       // Process them only once.
   2975       if (index != lastInsIndex)
   2976         {
   2977           ISD::ArgFlagsTy Flags = Ins[index].Flags;
   2978           // FIXME: For now, all byval parameter objects are marked mutable.
   2979           // This can be changed with more analysis.
   2980           // In case of tail call optimization mark all arguments mutable.
   2981           // Since they could be overwritten by lowering of arguments in case of
   2982           // a tail call.
   2983           if (Flags.isByVal()) {
   2984             unsigned CurByValIndex = CCInfo.getInRegsParamsProceed();
   2985             int FrameIndex = StoreByValRegs(
   2986                 CCInfo, DAG, dl, Chain, CurOrigArg,
   2987                 CurByValIndex,
   2988                 Ins[VA.getValNo()].PartOffset,
   2989                 VA.getLocMemOffset(),
   2990                 Flags.getByValSize(),
   2991                 true /*force mutable frames*/);
   2992             InVals.push_back(DAG.getFrameIndex(FrameIndex, getPointerTy()));
   2993             CCInfo.nextInRegsParam();
   2994           } else {
   2995             unsigned FIOffset = VA.getLocMemOffset() +
   2996                                 AFI->getStoredByValParamsPadding();
   2997             int FI = MFI->CreateFixedObject(VA.getLocVT().getSizeInBits()/8,
   2998                                             FIOffset, true);
   2999 
   3000             // Create load nodes to retrieve arguments from the stack.
   3001             SDValue FIN = DAG.getFrameIndex(FI, getPointerTy());
   3002             InVals.push_back(DAG.getLoad(VA.getValVT(), dl, Chain, FIN,
   3003                                          MachinePointerInfo::getFixedStack(FI),
   3004                                          false, false, false, 0));
   3005           }
   3006           lastInsIndex = index;
   3007         }
   3008     }
   3009   }
   3010 
   3011   // varargs
   3012   if (isVarArg)
   3013     VarArgStyleRegisters(CCInfo, DAG, dl, Chain,
   3014                          CCInfo.getNextStackOffset());
   3015 
   3016   return Chain;
   3017 }
   3018 
   3019 /// isFloatingPointZero - Return true if this is +0.0.
   3020 static bool isFloatingPointZero(SDValue Op) {
   3021   if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Op))
   3022     return CFP->getValueAPF().isPosZero();
   3023   else if (ISD::isEXTLoad(Op.getNode()) || ISD::isNON_EXTLoad(Op.getNode())) {
   3024     // Maybe this has already been legalized into the constant pool?
   3025     if (Op.getOperand(1).getOpcode() == ARMISD::Wrapper) {
   3026       SDValue WrapperOp = Op.getOperand(1).getOperand(0);
   3027       if (ConstantPoolSDNode *CP = dyn_cast<ConstantPoolSDNode>(WrapperOp))
   3028         if (const ConstantFP *CFP = dyn_cast<ConstantFP>(CP->getConstVal()))
   3029           return CFP->getValueAPF().isPosZero();
   3030     }
   3031   }
   3032   return false;
   3033 }
   3034 
   3035 /// Returns appropriate ARM CMP (cmp) and corresponding condition code for
   3036 /// the given operands.
   3037 SDValue
   3038 ARMTargetLowering::getARMCmp(SDValue LHS, SDValue RHS, ISD::CondCode CC,
   3039                              SDValue &ARMcc, SelectionDAG &DAG,
   3040                              SDLoc dl) const {
   3041   if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS.getNode())) {
   3042     unsigned C = RHSC->getZExtValue();
   3043     if (!isLegalICmpImmediate(C)) {
   3044       // Constant does not fit, try adjusting it by one?
   3045       switch (CC) {
   3046       default: break;
   3047       case ISD::SETLT:
   3048       case ISD::SETGE:
   3049         if (C != 0x80000000 && isLegalICmpImmediate(C-1)) {
   3050           CC = (CC == ISD::SETLT) ? ISD::SETLE : ISD::SETGT;
   3051           RHS = DAG.getConstant(C-1, MVT::i32);
   3052         }
   3053         break;
   3054       case ISD::SETULT:
   3055       case ISD::SETUGE:
   3056         if (C != 0 && isLegalICmpImmediate(C-1)) {
   3057           CC = (CC == ISD::SETULT) ? ISD::SETULE : ISD::SETUGT;
   3058           RHS = DAG.getConstant(C-1, MVT::i32);
   3059         }
   3060         break;
   3061       case ISD::SETLE:
   3062       case ISD::SETGT:
   3063         if (C != 0x7fffffff && isLegalICmpImmediate(C+1)) {
   3064           CC = (CC == ISD::SETLE) ? ISD::SETLT : ISD::SETGE;
   3065           RHS = DAG.getConstant(C+1, MVT::i32);
   3066         }
   3067         break;
   3068       case ISD::SETULE:
   3069       case ISD::SETUGT:
   3070         if (C != 0xffffffff && isLegalICmpImmediate(C+1)) {
   3071           CC = (CC == ISD::SETULE) ? ISD::SETULT : ISD::SETUGE;
   3072           RHS = DAG.getConstant(C+1, MVT::i32);
   3073         }
   3074         break;
   3075       }
   3076     }
   3077   }
   3078 
   3079   ARMCC::CondCodes CondCode = IntCCToARMCC(CC);
   3080   ARMISD::NodeType CompareType;
   3081   switch (CondCode) {
   3082   default:
   3083     CompareType = ARMISD::CMP;
   3084     break;
   3085   case ARMCC::EQ:
   3086   case ARMCC::NE:
   3087     // Uses only Z Flag
   3088     CompareType = ARMISD::CMPZ;
   3089     break;
   3090   }
   3091   ARMcc = DAG.getConstant(CondCode, MVT::i32);
   3092   return DAG.getNode(CompareType, dl, MVT::Glue, LHS, RHS);
   3093 }
   3094 
   3095 /// Returns a appropriate VFP CMP (fcmp{s|d}+fmstat) for the given operands.
   3096 SDValue
   3097 ARMTargetLowering::getVFPCmp(SDValue LHS, SDValue RHS, SelectionDAG &DAG,
   3098                              SDLoc dl) const {
   3099   SDValue Cmp;
   3100   if (!isFloatingPointZero(RHS))
   3101     Cmp = DAG.getNode(ARMISD::CMPFP, dl, MVT::Glue, LHS, RHS);
   3102   else
   3103     Cmp = DAG.getNode(ARMISD::CMPFPw0, dl, MVT::Glue, LHS);
   3104   return DAG.getNode(ARMISD::FMSTAT, dl, MVT::Glue, Cmp);
   3105 }
   3106 
   3107 /// duplicateCmp - Glue values can have only one use, so this function
   3108 /// duplicates a comparison node.
   3109 SDValue
   3110 ARMTargetLowering::duplicateCmp(SDValue Cmp, SelectionDAG &DAG) const {
   3111   unsigned Opc = Cmp.getOpcode();
   3112   SDLoc DL(Cmp);
   3113   if (Opc == ARMISD::CMP || Opc == ARMISD::CMPZ)
   3114     return DAG.getNode(Opc, DL, MVT::Glue, Cmp.getOperand(0),Cmp.getOperand(1));
   3115 
   3116   assert(Opc == ARMISD::FMSTAT && "unexpected comparison operation");
   3117   Cmp = Cmp.getOperand(0);
   3118   Opc = Cmp.getOpcode();
   3119   if (Opc == ARMISD::CMPFP)
   3120     Cmp = DAG.getNode(Opc, DL, MVT::Glue, Cmp.getOperand(0),Cmp.getOperand(1));
   3121   else {
   3122     assert(Opc == ARMISD::CMPFPw0 && "unexpected operand of FMSTAT");
   3123     Cmp = DAG.getNode(Opc, DL, MVT::Glue, Cmp.getOperand(0));
   3124   }
   3125   return DAG.getNode(ARMISD::FMSTAT, DL, MVT::Glue, Cmp);
   3126 }
   3127 
   3128 SDValue ARMTargetLowering::LowerSELECT(SDValue Op, SelectionDAG &DAG) const {
   3129   SDValue Cond = Op.getOperand(0);
   3130   SDValue SelectTrue = Op.getOperand(1);
   3131   SDValue SelectFalse = Op.getOperand(2);
   3132   SDLoc dl(Op);
   3133 
   3134   // Convert:
   3135   //
   3136   //   (select (cmov 1, 0, cond), t, f) -> (cmov t, f, cond)
   3137   //   (select (cmov 0, 1, cond), t, f) -> (cmov f, t, cond)
   3138   //
   3139   if (Cond.getOpcode() == ARMISD::CMOV && Cond.hasOneUse()) {
   3140     const ConstantSDNode *CMOVTrue =
   3141       dyn_cast<ConstantSDNode>(Cond.getOperand(0));
   3142     const ConstantSDNode *CMOVFalse =
   3143       dyn_cast<ConstantSDNode>(Cond.getOperand(1));
   3144 
   3145     if (CMOVTrue && CMOVFalse) {
   3146       unsigned CMOVTrueVal = CMOVTrue->getZExtValue();
   3147       unsigned CMOVFalseVal = CMOVFalse->getZExtValue();
   3148 
   3149       SDValue True;
   3150       SDValue False;
   3151       if (CMOVTrueVal == 1 && CMOVFalseVal == 0) {
   3152         True = SelectTrue;
   3153         False = SelectFalse;
   3154       } else if (CMOVTrueVal == 0 && CMOVFalseVal == 1) {
   3155         True = SelectFalse;
   3156         False = SelectTrue;
   3157       }
   3158 
   3159       if (True.getNode() && False.getNode()) {
   3160         EVT VT = Op.getValueType();
   3161         SDValue ARMcc = Cond.getOperand(2);
   3162         SDValue CCR = Cond.getOperand(3);
   3163         SDValue Cmp = duplicateCmp(Cond.getOperand(4), DAG);
   3164         assert(True.getValueType() == VT);
   3165         return DAG.getNode(ARMISD::CMOV, dl, VT, True, False, ARMcc, CCR, Cmp);
   3166       }
   3167     }
   3168   }
   3169 
   3170   // ARM's BooleanContents value is UndefinedBooleanContent. Mask out the
   3171   // undefined bits before doing a full-word comparison with zero.
   3172   Cond = DAG.getNode(ISD::AND, dl, Cond.getValueType(), Cond,
   3173                      DAG.getConstant(1, Cond.getValueType()));
   3174 
   3175   return DAG.getSelectCC(dl, Cond,
   3176                          DAG.getConstant(0, Cond.getValueType()),
   3177                          SelectTrue, SelectFalse, ISD::SETNE);
   3178 }
   3179 
   3180 SDValue ARMTargetLowering::LowerSELECT_CC(SDValue Op, SelectionDAG &DAG) const {
   3181   EVT VT = Op.getValueType();
   3182   SDValue LHS = Op.getOperand(0);
   3183   SDValue RHS = Op.getOperand(1);
   3184   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(4))->get();
   3185   SDValue TrueVal = Op.getOperand(2);
   3186   SDValue FalseVal = Op.getOperand(3);
   3187   SDLoc dl(Op);
   3188 
   3189   if (LHS.getValueType() == MVT::i32) {
   3190     SDValue ARMcc;
   3191     SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
   3192     SDValue Cmp = getARMCmp(LHS, RHS, CC, ARMcc, DAG, dl);
   3193     return DAG.getNode(ARMISD::CMOV, dl, VT, FalseVal, TrueVal, ARMcc, CCR,Cmp);
   3194   }
   3195 
   3196   ARMCC::CondCodes CondCode, CondCode2;
   3197   FPCCToARMCC(CC, CondCode, CondCode2);
   3198 
   3199   SDValue ARMcc = DAG.getConstant(CondCode, MVT::i32);
   3200   SDValue Cmp = getVFPCmp(LHS, RHS, DAG, dl);
   3201   SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
   3202   SDValue Result = DAG.getNode(ARMISD::CMOV, dl, VT, FalseVal, TrueVal,
   3203                                ARMcc, CCR, Cmp);
   3204   if (CondCode2 != ARMCC::AL) {
   3205     SDValue ARMcc2 = DAG.getConstant(CondCode2, MVT::i32);
   3206     // FIXME: Needs another CMP because flag can have but one use.
   3207     SDValue Cmp2 = getVFPCmp(LHS, RHS, DAG, dl);
   3208     Result = DAG.getNode(ARMISD::CMOV, dl, VT,
   3209                          Result, TrueVal, ARMcc2, CCR, Cmp2);
   3210   }
   3211   return Result;
   3212 }
   3213 
   3214 /// canChangeToInt - Given the fp compare operand, return true if it is suitable
   3215 /// to morph to an integer compare sequence.
   3216 static bool canChangeToInt(SDValue Op, bool &SeenZero,
   3217                            const ARMSubtarget *Subtarget) {
   3218   SDNode *N = Op.getNode();
   3219   if (!N->hasOneUse())
   3220     // Otherwise it requires moving the value from fp to integer registers.
   3221     return false;
   3222   if (!N->getNumValues())
   3223     return false;
   3224   EVT VT = Op.getValueType();
   3225   if (VT != MVT::f32 && !Subtarget->isFPBrccSlow())
   3226     // f32 case is generally profitable. f64 case only makes sense when vcmpe +
   3227     // vmrs are very slow, e.g. cortex-a8.
   3228     return false;
   3229 
   3230   if (isFloatingPointZero(Op)) {
   3231     SeenZero = true;
   3232     return true;
   3233   }
   3234   return ISD::isNormalLoad(N);
   3235 }
   3236 
   3237 static SDValue bitcastf32Toi32(SDValue Op, SelectionDAG &DAG) {
   3238   if (isFloatingPointZero(Op))
   3239     return DAG.getConstant(0, MVT::i32);
   3240 
   3241   if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Op))
   3242     return DAG.getLoad(MVT::i32, SDLoc(Op),
   3243                        Ld->getChain(), Ld->getBasePtr(), Ld->getPointerInfo(),
   3244                        Ld->isVolatile(), Ld->isNonTemporal(),
   3245                        Ld->isInvariant(), Ld->getAlignment());
   3246 
   3247   llvm_unreachable("Unknown VFP cmp argument!");
   3248 }
   3249 
   3250 static void expandf64Toi32(SDValue Op, SelectionDAG &DAG,
   3251                            SDValue &RetVal1, SDValue &RetVal2) {
   3252   if (isFloatingPointZero(Op)) {
   3253     RetVal1 = DAG.getConstant(0, MVT::i32);
   3254     RetVal2 = DAG.getConstant(0, MVT::i32);
   3255     return;
   3256   }
   3257 
   3258   if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Op)) {
   3259     SDValue Ptr = Ld->getBasePtr();
   3260     RetVal1 = DAG.getLoad(MVT::i32, SDLoc(Op),
   3261                           Ld->getChain(), Ptr,
   3262                           Ld->getPointerInfo(),
   3263                           Ld->isVolatile(), Ld->isNonTemporal(),
   3264                           Ld->isInvariant(), Ld->getAlignment());
   3265 
   3266     EVT PtrType = Ptr.getValueType();
   3267     unsigned NewAlign = MinAlign(Ld->getAlignment(), 4);
   3268     SDValue NewPtr = DAG.getNode(ISD::ADD, SDLoc(Op),
   3269                                  PtrType, Ptr, DAG.getConstant(4, PtrType));
   3270     RetVal2 = DAG.getLoad(MVT::i32, SDLoc(Op),
   3271                           Ld->getChain(), NewPtr,
   3272                           Ld->getPointerInfo().getWithOffset(4),
   3273                           Ld->isVolatile(), Ld->isNonTemporal(),
   3274                           Ld->isInvariant(), NewAlign);
   3275     return;
   3276   }
   3277 
   3278   llvm_unreachable("Unknown VFP cmp argument!");
   3279 }
   3280 
   3281 /// OptimizeVFPBrcond - With -enable-unsafe-fp-math, it's legal to optimize some
   3282 /// f32 and even f64 comparisons to integer ones.
   3283 SDValue
   3284 ARMTargetLowering::OptimizeVFPBrcond(SDValue Op, SelectionDAG &DAG) const {
   3285   SDValue Chain = Op.getOperand(0);
   3286   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(1))->get();
   3287   SDValue LHS = Op.getOperand(2);
   3288   SDValue RHS = Op.getOperand(3);
   3289   SDValue Dest = Op.getOperand(4);
   3290   SDLoc dl(Op);
   3291 
   3292   bool LHSSeenZero = false;
   3293   bool LHSOk = canChangeToInt(LHS, LHSSeenZero, Subtarget);
   3294   bool RHSSeenZero = false;
   3295   bool RHSOk = canChangeToInt(RHS, RHSSeenZero, Subtarget);
   3296   if (LHSOk && RHSOk && (LHSSeenZero || RHSSeenZero)) {
   3297     // If unsafe fp math optimization is enabled and there are no other uses of
   3298     // the CMP operands, and the condition code is EQ or NE, we can optimize it
   3299     // to an integer comparison.
   3300     if (CC == ISD::SETOEQ)
   3301       CC = ISD::SETEQ;
   3302     else if (CC == ISD::SETUNE)
   3303       CC = ISD::SETNE;
   3304 
   3305     SDValue Mask = DAG.getConstant(0x7fffffff, MVT::i32);
   3306     SDValue ARMcc;
   3307     if (LHS.getValueType() == MVT::f32) {
   3308       LHS = DAG.getNode(ISD::AND, dl, MVT::i32,
   3309                         bitcastf32Toi32(LHS, DAG), Mask);
   3310       RHS = DAG.getNode(ISD::AND, dl, MVT::i32,
   3311                         bitcastf32Toi32(RHS, DAG), Mask);
   3312       SDValue Cmp = getARMCmp(LHS, RHS, CC, ARMcc, DAG, dl);
   3313       SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
   3314       return DAG.getNode(ARMISD::BRCOND, dl, MVT::Other,
   3315                          Chain, Dest, ARMcc, CCR, Cmp);
   3316     }
   3317 
   3318     SDValue LHS1, LHS2;
   3319     SDValue RHS1, RHS2;
   3320     expandf64Toi32(LHS, DAG, LHS1, LHS2);
   3321     expandf64Toi32(RHS, DAG, RHS1, RHS2);
   3322     LHS2 = DAG.getNode(ISD::AND, dl, MVT::i32, LHS2, Mask);
   3323     RHS2 = DAG.getNode(ISD::AND, dl, MVT::i32, RHS2, Mask);
   3324     ARMCC::CondCodes CondCode = IntCCToARMCC(CC);
   3325     ARMcc = DAG.getConstant(CondCode, MVT::i32);
   3326     SDVTList VTList = DAG.getVTList(MVT::Other, MVT::Glue);
   3327     SDValue Ops[] = { Chain, ARMcc, LHS1, LHS2, RHS1, RHS2, Dest };
   3328     return DAG.getNode(ARMISD::BCC_i64, dl, VTList, Ops, 7);
   3329   }
   3330 
   3331   return SDValue();
   3332 }
   3333 
   3334 SDValue ARMTargetLowering::LowerBR_CC(SDValue Op, SelectionDAG &DAG) const {
   3335   SDValue Chain = Op.getOperand(0);
   3336   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(1))->get();
   3337   SDValue LHS = Op.getOperand(2);
   3338   SDValue RHS = Op.getOperand(3);
   3339   SDValue Dest = Op.getOperand(4);
   3340   SDLoc dl(Op);
   3341 
   3342   if (LHS.getValueType() == MVT::i32) {
   3343     SDValue ARMcc;
   3344     SDValue Cmp = getARMCmp(LHS, RHS, CC, ARMcc, DAG, dl);
   3345     SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
   3346     return DAG.getNode(ARMISD::BRCOND, dl, MVT::Other,
   3347                        Chain, Dest, ARMcc, CCR, Cmp);
   3348   }
   3349 
   3350   assert(LHS.getValueType() == MVT::f32 || LHS.getValueType() == MVT::f64);
   3351 
   3352   if (getTargetMachine().Options.UnsafeFPMath &&
   3353       (CC == ISD::SETEQ || CC == ISD::SETOEQ ||
   3354        CC == ISD::SETNE || CC == ISD::SETUNE)) {
   3355     SDValue Result = OptimizeVFPBrcond(Op, DAG);
   3356     if (Result.getNode())
   3357       return Result;
   3358   }
   3359 
   3360   ARMCC::CondCodes CondCode, CondCode2;
   3361   FPCCToARMCC(CC, CondCode, CondCode2);
   3362 
   3363   SDValue ARMcc = DAG.getConstant(CondCode, MVT::i32);
   3364   SDValue Cmp = getVFPCmp(LHS, RHS, DAG, dl);
   3365   SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
   3366   SDVTList VTList = DAG.getVTList(MVT::Other, MVT::Glue);
   3367   SDValue Ops[] = { Chain, Dest, ARMcc, CCR, Cmp };
   3368   SDValue Res = DAG.getNode(ARMISD::BRCOND, dl, VTList, Ops, 5);
   3369   if (CondCode2 != ARMCC::AL) {
   3370     ARMcc = DAG.getConstant(CondCode2, MVT::i32);
   3371     SDValue Ops[] = { Res, Dest, ARMcc, CCR, Res.getValue(1) };
   3372     Res = DAG.getNode(ARMISD::BRCOND, dl, VTList, Ops, 5);
   3373   }
   3374   return Res;
   3375 }
   3376 
   3377 SDValue ARMTargetLowering::LowerBR_JT(SDValue Op, SelectionDAG &DAG) const {
   3378   SDValue Chain = Op.getOperand(0);
   3379   SDValue Table = Op.getOperand(1);
   3380   SDValue Index = Op.getOperand(2);
   3381   SDLoc dl(Op);
   3382 
   3383   EVT PTy = getPointerTy();
   3384   JumpTableSDNode *JT = cast<JumpTableSDNode>(Table);
   3385   ARMFunctionInfo *AFI = DAG.getMachineFunction().getInfo<ARMFunctionInfo>();
   3386   SDValue UId = DAG.getConstant(AFI->createJumpTableUId(), PTy);
   3387   SDValue JTI = DAG.getTargetJumpTable(JT->getIndex(), PTy);
   3388   Table = DAG.getNode(ARMISD::WrapperJT, dl, MVT::i32, JTI, UId);
   3389   Index = DAG.getNode(ISD::MUL, dl, PTy, Index, DAG.getConstant(4, PTy));
   3390   SDValue Addr = DAG.getNode(ISD::ADD, dl, PTy, Index, Table);
   3391   if (Subtarget->isThumb2()) {
   3392     // Thumb2 uses a two-level jump. That is, it jumps into the jump table
   3393     // which does another jump to the destination. This also makes it easier
   3394     // to translate it to TBB / TBH later.
   3395     // FIXME: This might not work if the function is extremely large.
   3396     return DAG.getNode(ARMISD::BR2_JT, dl, MVT::Other, Chain,
   3397                        Addr, Op.getOperand(2), JTI, UId);
   3398   }
   3399   if (getTargetMachine().getRelocationModel() == Reloc::PIC_) {
   3400     Addr = DAG.getLoad((EVT)MVT::i32, dl, Chain, Addr,
   3401                        MachinePointerInfo::getJumpTable(),
   3402                        false, false, false, 0);
   3403     Chain = Addr.getValue(1);
   3404     Addr = DAG.getNode(ISD::ADD, dl, PTy, Addr, Table);
   3405     return DAG.getNode(ARMISD::BR_JT, dl, MVT::Other, Chain, Addr, JTI, UId);
   3406   } else {
   3407     Addr = DAG.getLoad(PTy, dl, Chain, Addr,
   3408                        MachinePointerInfo::getJumpTable(),
   3409                        false, false, false, 0);
   3410     Chain = Addr.getValue(1);
   3411     return DAG.getNode(ARMISD::BR_JT, dl, MVT::Other, Chain, Addr, JTI, UId);
   3412   }
   3413 }
   3414 
   3415 static SDValue LowerVectorFP_TO_INT(SDValue Op, SelectionDAG &DAG) {
   3416   EVT VT = Op.getValueType();
   3417   SDLoc dl(Op);
   3418 
   3419   if (Op.getValueType().getVectorElementType() == MVT::i32) {
   3420     if (Op.getOperand(0).getValueType().getVectorElementType() == MVT::f32)
   3421       return Op;
   3422     return DAG.UnrollVectorOp(Op.getNode());
   3423   }
   3424 
   3425   assert(Op.getOperand(0).getValueType() == MVT::v4f32 &&
   3426          "Invalid type for custom lowering!");
   3427   if (VT != MVT::v4i16)
   3428     return DAG.UnrollVectorOp(Op.getNode());
   3429 
   3430   Op = DAG.getNode(Op.getOpcode(), dl, MVT::v4i32, Op.getOperand(0));
   3431   return DAG.getNode(ISD::TRUNCATE, dl, VT, Op);
   3432 }
   3433 
   3434 static SDValue LowerFP_TO_INT(SDValue Op, SelectionDAG &DAG) {
   3435   EVT VT = Op.getValueType();
   3436   if (VT.isVector())
   3437     return LowerVectorFP_TO_INT(Op, DAG);
   3438 
   3439   SDLoc dl(Op);
   3440   unsigned Opc;
   3441 
   3442   switch (Op.getOpcode()) {
   3443   default: llvm_unreachable("Invalid opcode!");
   3444   case ISD::FP_TO_SINT:
   3445     Opc = ARMISD::FTOSI;
   3446     break;
   3447   case ISD::FP_TO_UINT:
   3448     Opc = ARMISD::FTOUI;
   3449     break;
   3450   }
   3451   Op = DAG.getNode(Opc, dl, MVT::f32, Op.getOperand(0));
   3452   return DAG.getNode(ISD::BITCAST, dl, MVT::i32, Op);
   3453 }
   3454 
   3455 static SDValue LowerVectorINT_TO_FP(SDValue Op, SelectionDAG &DAG) {
   3456   EVT VT = Op.getValueType();
   3457   SDLoc dl(Op);
   3458 
   3459   if (Op.getOperand(0).getValueType().getVectorElementType() == MVT::i32) {
   3460     if (VT.getVectorElementType() == MVT::f32)
   3461       return Op;
   3462     return DAG.UnrollVectorOp(Op.getNode());
   3463   }
   3464 
   3465   assert(Op.getOperand(0).getValueType() == MVT::v4i16 &&
   3466          "Invalid type for custom lowering!");
   3467   if (VT != MVT::v4f32)
   3468     return DAG.UnrollVectorOp(Op.getNode());
   3469 
   3470   unsigned CastOpc;
   3471   unsigned Opc;
   3472   switch (Op.getOpcode()) {
   3473   default: llvm_unreachable("Invalid opcode!");
   3474   case ISD::SINT_TO_FP:
   3475     CastOpc = ISD::SIGN_EXTEND;
   3476     Opc = ISD::SINT_TO_FP;
   3477     break;
   3478   case ISD::UINT_TO_FP:
   3479     CastOpc = ISD::ZERO_EXTEND;
   3480     Opc = ISD::UINT_TO_FP;
   3481     break;
   3482   }
   3483 
   3484   Op = DAG.getNode(CastOpc, dl, MVT::v4i32, Op.getOperand(0));
   3485   return DAG.getNode(Opc, dl, VT, Op);
   3486 }
   3487 
   3488 static SDValue LowerINT_TO_FP(SDValue Op, SelectionDAG &DAG) {
   3489   EVT VT = Op.getValueType();
   3490   if (VT.isVector())
   3491     return LowerVectorINT_TO_FP(Op, DAG);
   3492 
   3493   SDLoc dl(Op);
   3494   unsigned Opc;
   3495 
   3496   switch (Op.getOpcode()) {
   3497   default: llvm_unreachable("Invalid opcode!");
   3498   case ISD::SINT_TO_FP:
   3499     Opc = ARMISD::SITOF;
   3500     break;
   3501   case ISD::UINT_TO_FP:
   3502     Opc = ARMISD::UITOF;
   3503     break;
   3504   }
   3505 
   3506   Op = DAG.getNode(ISD::BITCAST, dl, MVT::f32, Op.getOperand(0));
   3507   return DAG.getNode(Opc, dl, VT, Op);
   3508 }
   3509 
   3510 SDValue ARMTargetLowering::LowerFCOPYSIGN(SDValue Op, SelectionDAG &DAG) const {
   3511   // Implement fcopysign with a fabs and a conditional fneg.
   3512   SDValue Tmp0 = Op.getOperand(0);
   3513   SDValue Tmp1 = Op.getOperand(1);
   3514   SDLoc dl(Op);
   3515   EVT VT = Op.getValueType();
   3516   EVT SrcVT = Tmp1.getValueType();
   3517   bool InGPR = Tmp0.getOpcode() == ISD::BITCAST ||
   3518     Tmp0.getOpcode() == ARMISD::VMOVDRR;
   3519   bool UseNEON = !InGPR && Subtarget->hasNEON();
   3520 
   3521   if (UseNEON) {
   3522     // Use VBSL to copy the sign bit.
   3523     unsigned EncodedVal = ARM_AM::createNEONModImm(0x6, 0x80);
   3524     SDValue Mask = DAG.getNode(ARMISD::VMOVIMM, dl, MVT::v2i32,
   3525                                DAG.getTargetConstant(EncodedVal, MVT::i32));
   3526     EVT OpVT = (VT == MVT::f32) ? MVT::v2i32 : MVT::v1i64;
   3527     if (VT == MVT::f64)
   3528       Mask = DAG.getNode(ARMISD::VSHL, dl, OpVT,
   3529                          DAG.getNode(ISD::BITCAST, dl, OpVT, Mask),
   3530                          DAG.getConstant(32, MVT::i32));
   3531     else /*if (VT == MVT::f32)*/
   3532       Tmp0 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f32, Tmp0);
   3533     if (SrcVT == MVT::f32) {
   3534       Tmp1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f32, Tmp1);
   3535       if (VT == MVT::f64)
   3536         Tmp1 = DAG.getNode(ARMISD::VSHL, dl, OpVT,
   3537                            DAG.getNode(ISD::BITCAST, dl, OpVT, Tmp1),
   3538                            DAG.getConstant(32, MVT::i32));
   3539     } else if (VT == MVT::f32)
   3540       Tmp1 = DAG.getNode(ARMISD::VSHRu, dl, MVT::v1i64,
   3541                          DAG.getNode(ISD::BITCAST, dl, MVT::v1i64, Tmp1),
   3542                          DAG.getConstant(32, MVT::i32));
   3543     Tmp0 = DAG.getNode(ISD::BITCAST, dl, OpVT, Tmp0);
   3544     Tmp1 = DAG.getNode(ISD::BITCAST, dl, OpVT, Tmp1);
   3545 
   3546     SDValue AllOnes = DAG.getTargetConstant(ARM_AM::createNEONModImm(0xe, 0xff),
   3547                                             MVT::i32);
   3548     AllOnes = DAG.getNode(ARMISD::VMOVIMM, dl, MVT::v8i8, AllOnes);
   3549     SDValue MaskNot = DAG.getNode(ISD::XOR, dl, OpVT, Mask,
   3550                                   DAG.getNode(ISD::BITCAST, dl, OpVT, AllOnes));
   3551 
   3552     SDValue Res = DAG.getNode(ISD::OR, dl, OpVT,
   3553                               DAG.getNode(ISD::AND, dl, OpVT, Tmp1, Mask),
   3554                               DAG.getNode(ISD::AND, dl, OpVT, Tmp0, MaskNot));
   3555     if (VT == MVT::f32) {
   3556       Res = DAG.getNode(ISD::BITCAST, dl, MVT::v2f32, Res);
   3557       Res = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f32, Res,
   3558                         DAG.getConstant(0, MVT::i32));
   3559     } else {
   3560       Res = DAG.getNode(ISD::BITCAST, dl, MVT::f64, Res);
   3561     }
   3562 
   3563     return Res;
   3564   }
   3565 
   3566   // Bitcast operand 1 to i32.
   3567   if (SrcVT == MVT::f64)
   3568     Tmp1 = DAG.getNode(ARMISD::VMOVRRD, dl, DAG.getVTList(MVT::i32, MVT::i32),
   3569                        &Tmp1, 1).getValue(1);
   3570   Tmp1 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Tmp1);
   3571 
   3572   // Or in the signbit with integer operations.
   3573   SDValue Mask1 = DAG.getConstant(0x80000000, MVT::i32);
   3574   SDValue Mask2 = DAG.getConstant(0x7fffffff, MVT::i32);
   3575   Tmp1 = DAG.getNode(ISD::AND, dl, MVT::i32, Tmp1, Mask1);
   3576   if (VT == MVT::f32) {
   3577     Tmp0 = DAG.getNode(ISD::AND, dl, MVT::i32,
   3578                        DAG.getNode(ISD::BITCAST, dl, MVT::i32, Tmp0), Mask2);
   3579     return DAG.getNode(ISD::BITCAST, dl, MVT::f32,
   3580                        DAG.getNode(ISD::OR, dl, MVT::i32, Tmp0, Tmp1));
   3581   }
   3582 
   3583   // f64: Or the high part with signbit and then combine two parts.
   3584   Tmp0 = DAG.getNode(ARMISD::VMOVRRD, dl, DAG.getVTList(MVT::i32, MVT::i32),
   3585                      &Tmp0, 1);
   3586   SDValue Lo = Tmp0.getValue(0);
   3587   SDValue Hi = DAG.getNode(ISD::AND, dl, MVT::i32, Tmp0.getValue(1), Mask2);
   3588   Hi = DAG.getNode(ISD::OR, dl, MVT::i32, Hi, Tmp1);
   3589   return DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi);
   3590 }
   3591 
   3592 SDValue ARMTargetLowering::LowerRETURNADDR(SDValue Op, SelectionDAG &DAG) const{
   3593   MachineFunction &MF = DAG.getMachineFunction();
   3594   MachineFrameInfo *MFI = MF.getFrameInfo();
   3595   MFI->setReturnAddressIsTaken(true);
   3596 
   3597   EVT VT = Op.getValueType();
   3598   SDLoc dl(Op);
   3599   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
   3600   if (Depth) {
   3601     SDValue FrameAddr = LowerFRAMEADDR(Op, DAG);
   3602     SDValue Offset = DAG.getConstant(4, MVT::i32);
   3603     return DAG.getLoad(VT, dl, DAG.getEntryNode(),
   3604                        DAG.getNode(ISD::ADD, dl, VT, FrameAddr, Offset),
   3605                        MachinePointerInfo(), false, false, false, 0);
   3606   }
   3607 
   3608   // Return LR, which contains the return address. Mark it an implicit live-in.
   3609   unsigned Reg = MF.addLiveIn(ARM::LR, getRegClassFor(MVT::i32));
   3610   return DAG.getCopyFromReg(DAG.getEntryNode(), dl, Reg, VT);
   3611 }
   3612 
   3613 SDValue ARMTargetLowering::LowerFRAMEADDR(SDValue Op, SelectionDAG &DAG) const {
   3614   MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
   3615   MFI->setFrameAddressIsTaken(true);
   3616 
   3617   EVT VT = Op.getValueType();
   3618   SDLoc dl(Op);  // FIXME probably not meaningful
   3619   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
   3620   unsigned FrameReg = (Subtarget->isThumb() || Subtarget->isTargetDarwin())
   3621     ? ARM::R7 : ARM::R11;
   3622   SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, VT);
   3623   while (Depth--)
   3624     FrameAddr = DAG.getLoad(VT, dl, DAG.getEntryNode(), FrameAddr,
   3625                             MachinePointerInfo(),
   3626                             false, false, false, 0);
   3627   return FrameAddr;
   3628 }
   3629 
   3630 /// Custom Expand long vector extensions, where size(DestVec) > 2*size(SrcVec),
   3631 /// and size(DestVec) > 128-bits.
   3632 /// This is achieved by doing the one extension from the SrcVec, splitting the
   3633 /// result, extending these parts, and then concatenating these into the
   3634 /// destination.
   3635 static SDValue ExpandVectorExtension(SDNode *N, SelectionDAG &DAG) {
   3636   SDValue Op = N->getOperand(0);
   3637   EVT SrcVT = Op.getValueType();
   3638   EVT DestVT = N->getValueType(0);
   3639 
   3640   assert(DestVT.getSizeInBits() > 128 &&
   3641          "Custom sext/zext expansion needs >128-bit vector.");
   3642   // If this is a normal length extension, use the default expansion.
   3643   if (SrcVT.getSizeInBits()*4 != DestVT.getSizeInBits() &&
   3644       SrcVT.getSizeInBits()*8 != DestVT.getSizeInBits())
   3645     return SDValue();
   3646 
   3647   SDLoc dl(N);
   3648   unsigned SrcEltSize = SrcVT.getVectorElementType().getSizeInBits();
   3649   unsigned DestEltSize = DestVT.getVectorElementType().getSizeInBits();
   3650   unsigned NumElts = SrcVT.getVectorNumElements();
   3651   LLVMContext &Ctx = *DAG.getContext();
   3652   SDValue Mid, SplitLo, SplitHi, ExtLo, ExtHi;
   3653 
   3654   EVT MidVT = EVT::getVectorVT(Ctx, EVT::getIntegerVT(Ctx, SrcEltSize*2),
   3655                                NumElts);
   3656   EVT SplitVT = EVT::getVectorVT(Ctx, EVT::getIntegerVT(Ctx, SrcEltSize*2),
   3657                                  NumElts/2);
   3658   EVT ExtVT = EVT::getVectorVT(Ctx, EVT::getIntegerVT(Ctx, DestEltSize),
   3659                                NumElts/2);
   3660 
   3661   Mid = DAG.getNode(N->getOpcode(), dl, MidVT, Op);
   3662   SplitLo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, SplitVT, Mid,
   3663                         DAG.getIntPtrConstant(0));
   3664   SplitHi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, SplitVT, Mid,
   3665                         DAG.getIntPtrConstant(NumElts/2));
   3666   ExtLo = DAG.getNode(N->getOpcode(), dl, ExtVT, SplitLo);
   3667   ExtHi = DAG.getNode(N->getOpcode(), dl, ExtVT, SplitHi);
   3668   return DAG.getNode(ISD::CONCAT_VECTORS, dl, DestVT, ExtLo, ExtHi);
   3669 }
   3670 
   3671 /// ExpandBITCAST - If the target supports VFP, this function is called to
   3672 /// expand a bit convert where either the source or destination type is i64 to
   3673 /// use a VMOVDRR or VMOVRRD node.  This should not be done when the non-i64
   3674 /// operand type is illegal (e.g., v2f32 for a target that doesn't support
   3675 /// vectors), since the legalizer won't know what to do with that.
   3676 static SDValue ExpandBITCAST(SDNode *N, SelectionDAG &DAG) {
   3677   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
   3678   SDLoc dl(N);
   3679   SDValue Op = N->getOperand(0);
   3680 
   3681   // This function is only supposed to be called for i64 types, either as the
   3682   // source or destination of the bit convert.
   3683   EVT SrcVT = Op.getValueType();
   3684   EVT DstVT = N->getValueType(0);
   3685   assert((SrcVT == MVT::i64 || DstVT == MVT::i64) &&
   3686          "ExpandBITCAST called for non-i64 type");
   3687 
   3688   // Turn i64->f64 into VMOVDRR.
   3689   if (SrcVT == MVT::i64 && TLI.isTypeLegal(DstVT)) {
   3690     SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, Op,
   3691                              DAG.getConstant(0, MVT::i32));
   3692     SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, Op,
   3693                              DAG.getConstant(1, MVT::i32));
   3694     return DAG.getNode(ISD::BITCAST, dl, DstVT,
   3695                        DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi));
   3696   }
   3697 
   3698   // Turn f64->i64 into VMOVRRD.
   3699   if (DstVT == MVT::i64 && TLI.isTypeLegal(SrcVT)) {
   3700     SDValue Cvt = DAG.getNode(ARMISD::VMOVRRD, dl,
   3701                               DAG.getVTList(MVT::i32, MVT::i32), &Op, 1);
   3702     // Merge the pieces into a single i64 value.
   3703     return DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Cvt, Cvt.getValue(1));
   3704   }
   3705 
   3706   return SDValue();
   3707 }
   3708 
   3709 /// getZeroVector - Returns a vector of specified type with all zero elements.
   3710 /// Zero vectors are used to represent vector negation and in those cases
   3711 /// will be implemented with the NEON VNEG instruction.  However, VNEG does
   3712 /// not support i64 elements, so sometimes the zero vectors will need to be
   3713 /// explicitly constructed.  Regardless, use a canonical VMOV to create the
   3714 /// zero vector.
   3715 static SDValue getZeroVector(EVT VT, SelectionDAG &DAG, SDLoc dl) {
   3716   assert(VT.isVector() && "Expected a vector type");
   3717   // The canonical modified immediate encoding of a zero vector is....0!
   3718   SDValue EncodedVal = DAG.getTargetConstant(0, MVT::i32);
   3719   EVT VmovVT = VT.is128BitVector() ? MVT::v4i32 : MVT::v2i32;
   3720   SDValue Vmov = DAG.getNode(ARMISD::VMOVIMM, dl, VmovVT, EncodedVal);
   3721   return DAG.getNode(ISD::BITCAST, dl, VT, Vmov);
   3722 }
   3723 
   3724 /// LowerShiftRightParts - Lower SRA_PARTS, which returns two
   3725 /// i32 values and take a 2 x i32 value to shift plus a shift amount.
   3726 SDValue ARMTargetLowering::LowerShiftRightParts(SDValue Op,
   3727                                                 SelectionDAG &DAG) const {
   3728   assert(Op.getNumOperands() == 3 && "Not a double-shift!");
   3729   EVT VT = Op.getValueType();
   3730   unsigned VTBits = VT.getSizeInBits();
   3731   SDLoc dl(Op);
   3732   SDValue ShOpLo = Op.getOperand(0);
   3733   SDValue ShOpHi = Op.getOperand(1);
   3734   SDValue ShAmt  = Op.getOperand(2);
   3735   SDValue ARMcc;
   3736   unsigned Opc = (Op.getOpcode() == ISD::SRA_PARTS) ? ISD::SRA : ISD::SRL;
   3737 
   3738   assert(Op.getOpcode() == ISD::SRA_PARTS || Op.getOpcode() == ISD::SRL_PARTS);
   3739 
   3740   SDValue RevShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32,
   3741                                  DAG.getConstant(VTBits, MVT::i32), ShAmt);
   3742   SDValue Tmp1 = DAG.getNode(ISD::SRL, dl, VT, ShOpLo, ShAmt);
   3743   SDValue ExtraShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32, ShAmt,
   3744                                    DAG.getConstant(VTBits, MVT::i32));
   3745   SDValue Tmp2 = DAG.getNode(ISD::SHL, dl, VT, ShOpHi, RevShAmt);
   3746   SDValue FalseVal = DAG.getNode(ISD::OR, dl, VT, Tmp1, Tmp2);
   3747   SDValue TrueVal = DAG.getNode(Opc, dl, VT, ShOpHi, ExtraShAmt);
   3748 
   3749   SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
   3750   SDValue Cmp = getARMCmp(ExtraShAmt, DAG.getConstant(0, MVT::i32), ISD::SETGE,
   3751                           ARMcc, DAG, dl);
   3752   SDValue Hi = DAG.getNode(Opc, dl, VT, ShOpHi, ShAmt);
   3753   SDValue Lo = DAG.getNode(ARMISD::CMOV, dl, VT, FalseVal, TrueVal, ARMcc,
   3754                            CCR, Cmp);
   3755 
   3756   SDValue Ops[2] = { Lo, Hi };
   3757   return DAG.getMergeValues(Ops, 2, dl);
   3758 }
   3759 
   3760 /// LowerShiftLeftParts - Lower SHL_PARTS, which returns two
   3761 /// i32 values and take a 2 x i32 value to shift plus a shift amount.
   3762 SDValue ARMTargetLowering::LowerShiftLeftParts(SDValue Op,
   3763                                                SelectionDAG &DAG) const {
   3764   assert(Op.getNumOperands() == 3 && "Not a double-shift!");
   3765   EVT VT = Op.getValueType();
   3766   unsigned VTBits = VT.getSizeInBits();
   3767   SDLoc dl(Op);
   3768   SDValue ShOpLo = Op.getOperand(0);
   3769   SDValue ShOpHi = Op.getOperand(1);
   3770   SDValue ShAmt  = Op.getOperand(2);
   3771   SDValue ARMcc;
   3772 
   3773   assert(Op.getOpcode() == ISD::SHL_PARTS);
   3774   SDValue RevShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32,
   3775                                  DAG.getConstant(VTBits, MVT::i32), ShAmt);
   3776   SDValue Tmp1 = DAG.getNode(ISD::SRL, dl, VT, ShOpLo, RevShAmt);
   3777   SDValue ExtraShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32, ShAmt,
   3778                                    DAG.getConstant(VTBits, MVT::i32));
   3779   SDValue Tmp2 = DAG.getNode(ISD::SHL, dl, VT, ShOpHi, ShAmt);
   3780   SDValue Tmp3 = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ExtraShAmt);
   3781 
   3782   SDValue FalseVal = DAG.getNode(ISD::OR, dl, VT, Tmp1, Tmp2);
   3783   SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
   3784   SDValue Cmp = getARMCmp(ExtraShAmt, DAG.getConstant(0, MVT::i32), ISD::SETGE,
   3785                           ARMcc, DAG, dl);
   3786   SDValue Lo = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ShAmt);
   3787   SDValue Hi = DAG.getNode(ARMISD::CMOV, dl, VT, FalseVal, Tmp3, ARMcc,
   3788                            CCR, Cmp);
   3789 
   3790   SDValue Ops[2] = { Lo, Hi };
   3791   return DAG.getMergeValues(Ops, 2, dl);
   3792 }
   3793 
   3794 SDValue ARMTargetLowering::LowerFLT_ROUNDS_(SDValue Op,
   3795                                             SelectionDAG &DAG) const {
   3796   // The rounding mode is in bits 23:22 of the FPSCR.
   3797   // The ARM rounding mode value to FLT_ROUNDS mapping is 0->1, 1->2, 2->3, 3->0
   3798   // The formula we use to implement this is (((FPSCR + 1 << 22) >> 22) & 3)
   3799   // so that the shift + and get folded into a bitfield extract.
   3800   SDLoc dl(Op);
   3801   SDValue FPSCR = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::i32,
   3802                               DAG.getConstant(Intrinsic::arm_get_fpscr,
   3803                                               MVT::i32));
   3804   SDValue FltRounds = DAG.getNode(ISD::ADD, dl, MVT::i32, FPSCR,
   3805                                   DAG.getConstant(1U << 22, MVT::i32));
   3806   SDValue RMODE = DAG.getNode(ISD::SRL, dl, MVT::i32, FltRounds,
   3807                               DAG.getConstant(22, MVT::i32));
   3808   return DAG.getNode(ISD::AND, dl, MVT::i32, RMODE,
   3809                      DAG.getConstant(3, MVT::i32));
   3810 }
   3811 
   3812 static SDValue LowerCTTZ(SDNode *N, SelectionDAG &DAG,
   3813                          const ARMSubtarget *ST) {
   3814   EVT VT = N->getValueType(0);
   3815   SDLoc dl(N);
   3816 
   3817   if (!ST->hasV6T2Ops())
   3818     return SDValue();
   3819 
   3820   SDValue rbit = DAG.getNode(ARMISD::RBIT, dl, VT, N->getOperand(0));
   3821   return DAG.getNode(ISD::CTLZ, dl, VT, rbit);
   3822 }
   3823 
   3824 /// getCTPOP16BitCounts - Returns a v8i8/v16i8 vector containing the bit-count
   3825 /// for each 16-bit element from operand, repeated.  The basic idea is to
   3826 /// leverage vcnt to get the 8-bit counts, gather and add the results.
   3827 ///
   3828 /// Trace for v4i16:
   3829 /// input    = [v0    v1    v2    v3   ] (vi 16-bit element)
   3830 /// cast: N0 = [w0 w1 w2 w3 w4 w5 w6 w7] (v0 = [w0 w1], wi 8-bit element)
   3831 /// vcnt: N1 = [b0 b1 b2 b3 b4 b5 b6 b7] (bi = bit-count of 8-bit element wi)
   3832 /// vrev: N2 = [b1 b0 b3 b2 b5 b4 b7 b6]
   3833 ///            [b0 b1 b2 b3 b4 b5 b6 b7]
   3834 ///           +[b1 b0 b3 b2 b5 b4 b7 b6]
   3835 /// N3=N1+N2 = [k0 k0 k1 k1 k2 k2 k3 k3] (k0 = b0+b1 = bit-count of 16-bit v0,
   3836 /// vuzp:    = [k0 k1 k2 k3 k0 k1 k2 k3]  each ki is 8-bits)
   3837 static SDValue getCTPOP16BitCounts(SDNode *N, SelectionDAG &DAG) {
   3838   EVT VT = N->getValueType(0);
   3839   SDLoc DL(N);
   3840 
   3841   EVT VT8Bit = VT.is64BitVector() ? MVT::v8i8 : MVT::v16i8;
   3842   SDValue N0 = DAG.getNode(ISD::BITCAST, DL, VT8Bit, N->getOperand(0));
   3843   SDValue N1 = DAG.getNode(ISD::CTPOP, DL, VT8Bit, N0);
   3844   SDValue N2 = DAG.getNode(ARMISD::VREV16, DL, VT8Bit, N1);
   3845   SDValue N3 = DAG.getNode(ISD::ADD, DL, VT8Bit, N1, N2);
   3846   return DAG.getNode(ARMISD::VUZP, DL, VT8Bit, N3, N3);
   3847 }
   3848 
   3849 /// lowerCTPOP16BitElements - Returns a v4i16/v8i16 vector containing the
   3850 /// bit-count for each 16-bit element from the operand.  We need slightly
   3851 /// different sequencing for v4i16 and v8i16 to stay within NEON's available
   3852 /// 64/128-bit registers.
   3853 ///
   3854 /// Trace for v4i16:
   3855 /// input           = [v0    v1    v2    v3    ] (vi 16-bit element)
   3856 /// v8i8: BitCounts = [k0 k1 k2 k3 k0 k1 k2 k3 ] (ki is the bit-count of vi)
   3857 /// v8i16:Extended  = [k0    k1    k2    k3    k0    k1    k2    k3    ]
   3858 /// v4i16:Extracted = [k0    k1    k2    k3    ]
   3859 static SDValue lowerCTPOP16BitElements(SDNode *N, SelectionDAG &DAG) {
   3860   EVT VT = N->getValueType(0);
   3861   SDLoc DL(N);
   3862 
   3863   SDValue BitCounts = getCTPOP16BitCounts(N, DAG);
   3864   if (VT.is64BitVector()) {
   3865     SDValue Extended = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::v8i16, BitCounts);
   3866     return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v4i16, Extended,
   3867                        DAG.getIntPtrConstant(0));
   3868   } else {
   3869     SDValue Extracted = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v8i8,
   3870                                     BitCounts, DAG.getIntPtrConstant(0));
   3871     return DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::v8i16, Extracted);
   3872   }
   3873 }
   3874 
   3875 /// lowerCTPOP32BitElements - Returns a v2i32/v4i32 vector containing the
   3876 /// bit-count for each 32-bit element from the operand.  The idea here is
   3877 /// to split the vector into 16-bit elements, leverage the 16-bit count
   3878 /// routine, and then combine the results.
   3879 ///
   3880 /// Trace for v2i32 (v4i32 similar with Extracted/Extended exchanged):
   3881 /// input    = [v0    v1    ] (vi: 32-bit elements)
   3882 /// Bitcast  = [w0 w1 w2 w3 ] (wi: 16-bit elements, v0 = [w0 w1])
   3883 /// Counts16 = [k0 k1 k2 k3 ] (ki: 16-bit elements, bit-count of wi)
   3884 /// vrev: N0 = [k1 k0 k3 k2 ]
   3885 ///            [k0 k1 k2 k3 ]
   3886 ///       N1 =+[k1 k0 k3 k2 ]
   3887 ///            [k0 k2 k1 k3 ]
   3888 ///       N2 =+[k1 k3 k0 k2 ]
   3889 ///            [k0    k2    k1    k3    ]
   3890 /// Extended =+[k1    k3    k0    k2    ]
   3891 ///            [k0    k2    ]
   3892 /// Extracted=+[k1    k3    ]
   3893 ///
   3894 static SDValue lowerCTPOP32BitElements(SDNode *N, SelectionDAG &DAG) {
   3895   EVT VT = N->getValueType(0);
   3896   SDLoc DL(N);
   3897 
   3898   EVT VT16Bit = VT.is64BitVector() ? MVT::v4i16 : MVT::v8i16;
   3899 
   3900   SDValue Bitcast = DAG.getNode(ISD::BITCAST, DL, VT16Bit, N->getOperand(0));
   3901   SDValue Counts16 = lowerCTPOP16BitElements(Bitcast.getNode(), DAG);
   3902   SDValue N0 = DAG.getNode(ARMISD::VREV32, DL, VT16Bit, Counts16);
   3903   SDValue N1 = DAG.getNode(ISD::ADD, DL, VT16Bit, Counts16, N0);
   3904   SDValue N2 = DAG.getNode(ARMISD::VUZP, DL, VT16Bit, N1, N1);
   3905 
   3906   if (VT.is64BitVector()) {
   3907     SDValue Extended = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::v4i32, N2);
   3908     return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2i32, Extended,
   3909                        DAG.getIntPtrConstant(0));
   3910   } else {
   3911     SDValue Extracted = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v4i16, N2,
   3912                                     DAG.getIntPtrConstant(0));
   3913     return DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::v4i32, Extracted);
   3914   }
   3915 }
   3916 
   3917 static SDValue LowerCTPOP(SDNode *N, SelectionDAG &DAG,
   3918                           const ARMSubtarget *ST) {
   3919   EVT VT = N->getValueType(0);
   3920 
   3921   assert(ST->hasNEON() && "Custom ctpop lowering requires NEON.");
   3922   assert((VT == MVT::v2i32 || VT == MVT::v4i32 ||
   3923           VT == MVT::v4i16 || VT == MVT::v8i16) &&
   3924          "Unexpected type for custom ctpop lowering");
   3925 
   3926   if (VT.getVectorElementType() == MVT::i32)
   3927     return lowerCTPOP32BitElements(N, DAG);
   3928   else
   3929     return lowerCTPOP16BitElements(N, DAG);
   3930 }
   3931 
   3932 static SDValue LowerShift(SDNode *N, SelectionDAG &DAG,
   3933                           const ARMSubtarget *ST) {
   3934   EVT VT = N->getValueType(0);
   3935   SDLoc dl(N);
   3936 
   3937   if (!VT.isVector())
   3938     return SDValue();
   3939 
   3940   // Lower vector shifts on NEON to use VSHL.
   3941   assert(ST->hasNEON() && "unexpected vector shift");
   3942 
   3943   // Left shifts translate directly to the vshiftu intrinsic.
   3944   if (N->getOpcode() == ISD::SHL)
   3945     return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
   3946                        DAG.getConstant(Intrinsic::arm_neon_vshiftu, MVT::i32),
   3947                        N->getOperand(0), N->getOperand(1));
   3948 
   3949   assert((N->getOpcode() == ISD::SRA ||
   3950           N->getOpcode() == ISD::SRL) && "unexpected vector shift opcode");
   3951 
   3952   // NEON uses the same intrinsics for both left and right shifts.  For
   3953   // right shifts, the shift amounts are negative, so negate the vector of
   3954   // shift amounts.
   3955   EVT ShiftVT = N->getOperand(1).getValueType();
   3956   SDValue NegatedCount = DAG.getNode(ISD::SUB, dl, ShiftVT,
   3957                                      getZeroVector(ShiftVT, DAG, dl),
   3958                                      N->getOperand(1));
   3959   Intrinsic::ID vshiftInt = (N->getOpcode() == ISD::SRA ?
   3960                              Intrinsic::arm_neon_vshifts :
   3961                              Intrinsic::arm_neon_vshiftu);
   3962   return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
   3963                      DAG.getConstant(vshiftInt, MVT::i32),
   3964                      N->getOperand(0), NegatedCount);
   3965 }
   3966 
   3967 static SDValue Expand64BitShift(SDNode *N, SelectionDAG &DAG,
   3968                                 const ARMSubtarget *ST) {
   3969   EVT VT = N->getValueType(0);
   3970   SDLoc dl(N);
   3971 
   3972   // We can get here for a node like i32 = ISD::SHL i32, i64
   3973   if (VT != MVT::i64)
   3974     return SDValue();
   3975 
   3976   assert((N->getOpcode() == ISD::SRL || N->getOpcode() == ISD::SRA) &&
   3977          "Unknown shift to lower!");
   3978 
   3979   // We only lower SRA, SRL of 1 here, all others use generic lowering.
   3980   if (!isa<ConstantSDNode>(N->getOperand(1)) ||
   3981       cast<ConstantSDNode>(N->getOperand(1))->getZExtValue() != 1)
   3982     return SDValue();
   3983 
   3984   // If we are in thumb mode, we don't have RRX.
   3985   if (ST->isThumb1Only()) return SDValue();
   3986 
   3987   // Okay, we have a 64-bit SRA or SRL of 1.  Lower this to an RRX expr.
   3988   SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(0),
   3989                            DAG.getConstant(0, MVT::i32));
   3990   SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(0),
   3991                            DAG.getConstant(1, MVT::i32));
   3992 
   3993   // First, build a SRA_FLAG/SRL_FLAG op, which shifts the top part by one and
   3994   // captures the result into a carry flag.
   3995   unsigned Opc = N->getOpcode() == ISD::SRL ? ARMISD::SRL_FLAG:ARMISD::SRA_FLAG;
   3996   Hi = DAG.getNode(Opc, dl, DAG.getVTList(MVT::i32, MVT::Glue), &Hi, 1);
   3997 
   3998   // The low part is an ARMISD::RRX operand, which shifts the carry in.
   3999   Lo = DAG.getNode(ARMISD::RRX, dl, MVT::i32, Lo, Hi.getValue(1));
   4000 
   4001   // Merge the pieces into a single i64 value.
   4002  return DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Lo, Hi);
   4003 }
   4004 
   4005 static SDValue LowerVSETCC(SDValue Op, SelectionDAG &DAG) {
   4006   SDValue TmpOp0, TmpOp1;
   4007   bool Invert = false;
   4008   bool Swap = false;
   4009   unsigned Opc = 0;
   4010 
   4011   SDValue Op0 = Op.getOperand(0);
   4012   SDValue Op1 = Op.getOperand(1);
   4013   SDValue CC = Op.getOperand(2);
   4014   EVT VT = Op.getValueType();
   4015   ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
   4016   SDLoc dl(Op);
   4017 
   4018   if (Op.getOperand(1).getValueType().isFloatingPoint()) {
   4019     switch (SetCCOpcode) {
   4020     default: llvm_unreachable("Illegal FP comparison");
   4021     case ISD::SETUNE:
   4022     case ISD::SETNE:  Invert = true; // Fallthrough
   4023     case ISD::SETOEQ:
   4024     case ISD::SETEQ:  Opc = ARMISD::VCEQ; break;
   4025     case ISD::SETOLT:
   4026     case ISD::SETLT: Swap = true; // Fallthrough
   4027     case ISD::SETOGT:
   4028     case ISD::SETGT:  Opc = ARMISD::VCGT; break;
   4029     case ISD::SETOLE:
   4030     case ISD::SETLE:  Swap = true; // Fallthrough
   4031     case ISD::SETOGE:
   4032     case ISD::SETGE: Opc = ARMISD::VCGE; break;
   4033     case ISD::SETUGE: Swap = true; // Fallthrough
   4034     case ISD::SETULE: Invert = true; Opc = ARMISD::VCGT; break;
   4035     case ISD::SETUGT: Swap = true; // Fallthrough
   4036     case ISD::SETULT: Invert = true; Opc = ARMISD::VCGE; break;
   4037     case ISD::SETUEQ: Invert = true; // Fallthrough
   4038     case ISD::SETONE:
   4039       // Expand this to (OLT | OGT).
   4040       TmpOp0 = Op0;
   4041       TmpOp1 = Op1;
   4042       Opc = ISD::OR;
   4043       Op0 = DAG.getNode(ARMISD::VCGT, dl, VT, TmpOp1, TmpOp0);
   4044       Op1 = DAG.getNode(ARMISD::VCGT, dl, VT, TmpOp0, TmpOp1);
   4045       break;
   4046     case ISD::SETUO: Invert = true; // Fallthrough
   4047     case ISD::SETO:
   4048       // Expand this to (OLT | OGE).
   4049       TmpOp0 = Op0;
   4050       TmpOp1 = Op1;
   4051       Opc = ISD::OR;
   4052       Op0 = DAG.getNode(ARMISD::VCGT, dl, VT, TmpOp1, TmpOp0);
   4053       Op1 = DAG.getNode(ARMISD::VCGE, dl, VT, TmpOp0, TmpOp1);
   4054       break;
   4055     }
   4056   } else {
   4057     // Integer comparisons.
   4058     switch (SetCCOpcode) {
   4059     default: llvm_unreachable("Illegal integer comparison");
   4060     case ISD::SETNE:  Invert = true;
   4061     case ISD::SETEQ:  Opc = ARMISD::VCEQ; break;
   4062     case ISD::SETLT:  Swap = true;
   4063     case ISD::SETGT:  Opc = ARMISD::VCGT; break;
   4064     case ISD::SETLE:  Swap = true;
   4065     case ISD::SETGE:  Opc = ARMISD::VCGE; break;
   4066     case ISD::SETULT: Swap = true;
   4067     case ISD::SETUGT: Opc = ARMISD::VCGTU; break;
   4068     case ISD::SETULE: Swap = true;
   4069     case ISD::SETUGE: Opc = ARMISD::VCGEU; break;
   4070     }
   4071 
   4072     // Detect VTST (Vector Test Bits) = icmp ne (and (op0, op1), zero).
   4073     if (Opc == ARMISD::VCEQ) {
   4074 
   4075       SDValue AndOp;
   4076       if (ISD::isBuildVectorAllZeros(Op1.getNode()))
   4077         AndOp = Op0;
   4078       else if (ISD::isBuildVectorAllZeros(Op0.getNode()))
   4079         AndOp = Op1;
   4080 
   4081       // Ignore bitconvert.
   4082       if (AndOp.getNode() && AndOp.getOpcode() == ISD::BITCAST)
   4083         AndOp = AndOp.getOperand(0);
   4084 
   4085       if (AndOp.getNode() && AndOp.getOpcode() == ISD::AND) {
   4086         Opc = ARMISD::VTST;
   4087         Op0 = DAG.getNode(ISD::BITCAST, dl, VT, AndOp.getOperand(0));
   4088         Op1 = DAG.getNode(ISD::BITCAST, dl, VT, AndOp.getOperand(1));
   4089         Invert = !Invert;
   4090       }
   4091     }
   4092   }
   4093 
   4094   if (Swap)
   4095     std::swap(Op0, Op1);
   4096 
   4097   // If one of the operands is a constant vector zero, attempt to fold the
   4098   // comparison to a specialized compare-against-zero form.
   4099   SDValue SingleOp;
   4100   if (ISD::isBuildVectorAllZeros(Op1.getNode()))
   4101     SingleOp = Op0;
   4102   else if (ISD::isBuildVectorAllZeros(Op0.getNode())) {
   4103     if (Opc == ARMISD::VCGE)
   4104       Opc = ARMISD::VCLEZ;
   4105     else if (Opc == ARMISD::VCGT)
   4106       Opc = ARMISD::VCLTZ;
   4107     SingleOp = Op1;
   4108   }
   4109 
   4110   SDValue Result;
   4111   if (SingleOp.getNode()) {
   4112     switch (Opc) {
   4113     case ARMISD::VCEQ:
   4114       Result = DAG.getNode(ARMISD::VCEQZ, dl, VT, SingleOp); break;
   4115     case ARMISD::VCGE:
   4116       Result = DAG.getNode(ARMISD::VCGEZ, dl, VT, SingleOp); break;
   4117     case ARMISD::VCLEZ:
   4118       Result = DAG.getNode(ARMISD::VCLEZ, dl, VT, SingleOp); break;
   4119     case ARMISD::VCGT:
   4120       Result = DAG.getNode(ARMISD::VCGTZ, dl, VT, SingleOp); break;
   4121     case ARMISD::VCLTZ:
   4122       Result = DAG.getNode(ARMISD::VCLTZ, dl, VT, SingleOp); break;
   4123     default:
   4124       Result = DAG.getNode(Opc, dl, VT, Op0, Op1);
   4125     }
   4126   } else {
   4127      Result = DAG.getNode(Opc, dl, VT, Op0, Op1);
   4128   }
   4129 
   4130   if (Invert)
   4131     Result = DAG.getNOT(dl, Result, VT);
   4132 
   4133   return Result;
   4134 }
   4135 
   4136 /// isNEONModifiedImm - Check if the specified splat value corresponds to a
   4137 /// valid vector constant for a NEON instruction with a "modified immediate"
   4138 /// operand (e.g., VMOV).  If so, return the encoded value.
   4139 static SDValue isNEONModifiedImm(uint64_t SplatBits, uint64_t SplatUndef,
   4140                                  unsigned SplatBitSize, SelectionDAG &DAG,
   4141                                  EVT &VT, bool is128Bits, NEONModImmType type) {
   4142   unsigned OpCmode, Imm;
   4143 
   4144   // SplatBitSize is set to the smallest size that splats the vector, so a
   4145   // zero vector will always have SplatBitSize == 8.  However, NEON modified
   4146   // immediate instructions others than VMOV do not support the 8-bit encoding
   4147   // of a zero vector, and the default encoding of zero is supposed to be the
   4148   // 32-bit version.
   4149   if (SplatBits == 0)
   4150     SplatBitSize = 32;
   4151 
   4152   switch (SplatBitSize) {
   4153   case 8:
   4154     if (type != VMOVModImm)
   4155       return SDValue();
   4156     // Any 1-byte value is OK.  Op=0, Cmode=1110.
   4157     assert((SplatBits & ~0xff) == 0 && "one byte splat value is too big");
   4158     OpCmode = 0xe;
   4159     Imm = SplatBits;
   4160     VT = is128Bits ? MVT::v16i8 : MVT::v8i8;
   4161     break;
   4162 
   4163   case 16:
   4164     // NEON's 16-bit VMOV supports splat values where only one byte is nonzero.
   4165     VT = is128Bits ? MVT::v8i16 : MVT::v4i16;
   4166     if ((SplatBits & ~0xff) == 0) {
   4167       // Value = 0x00nn: Op=x, Cmode=100x.
   4168       OpCmode = 0x8;
   4169       Imm = SplatBits;
   4170       break;
   4171     }
   4172     if ((SplatBits & ~0xff00) == 0) {
   4173       // Value = 0xnn00: Op=x, Cmode=101x.
   4174       OpCmode = 0xa;
   4175       Imm = SplatBits >> 8;
   4176       break;
   4177     }
   4178     return SDValue();
   4179 
   4180   case 32:
   4181     // NEON's 32-bit VMOV supports splat values where:
   4182     // * only one byte is nonzero, or
   4183     // * the least significant byte is 0xff and the second byte is nonzero, or
   4184     // * the least significant 2 bytes are 0xff and the third is nonzero.
   4185     VT = is128Bits ? MVT::v4i32 : MVT::v2i32;
   4186     if ((SplatBits & ~0xff) == 0) {
   4187       // Value = 0x000000nn: Op=x, Cmode=000x.
   4188       OpCmode = 0;
   4189       Imm = SplatBits;
   4190       break;
   4191     }
   4192     if ((SplatBits & ~0xff00) == 0) {
   4193       // Value = 0x0000nn00: Op=x, Cmode=001x.
   4194       OpCmode = 0x2;
   4195       Imm = SplatBits >> 8;
   4196       break;
   4197     }
   4198     if ((SplatBits & ~0xff0000) == 0) {
   4199       // Value = 0x00nn0000: Op=x, Cmode=010x.
   4200       OpCmode = 0x4;
   4201       Imm = SplatBits >> 16;
   4202       break;
   4203     }
   4204     if ((SplatBits & ~0xff000000) == 0) {
   4205       // Value = 0xnn000000: Op=x, Cmode=011x.
   4206       OpCmode = 0x6;
   4207       Imm = SplatBits >> 24;
   4208       break;
   4209     }
   4210 
   4211     // cmode == 0b1100 and cmode == 0b1101 are not supported for VORR or VBIC
   4212     if (type == OtherModImm) return SDValue();
   4213 
   4214     if ((SplatBits & ~0xffff) == 0 &&
   4215         ((SplatBits | SplatUndef) & 0xff) == 0xff) {
   4216       // Value = 0x0000nnff: Op=x, Cmode=1100.
   4217       OpCmode = 0xc;
   4218       Imm = SplatBits >> 8;
   4219       SplatBits |= 0xff;
   4220       break;
   4221     }
   4222 
   4223     if ((SplatBits & ~0xffffff) == 0 &&
   4224         ((SplatBits | SplatUndef) & 0xffff) == 0xffff) {
   4225       // Value = 0x00nnffff: Op=x, Cmode=1101.
   4226       OpCmode = 0xd;
   4227       Imm = SplatBits >> 16;
   4228       SplatBits |= 0xffff;
   4229       break;
   4230     }
   4231 
   4232     // Note: there are a few 32-bit splat values (specifically: 00ffff00,
   4233     // ff000000, ff0000ff, and ffff00ff) that are valid for VMOV.I64 but not
   4234     // VMOV.I32.  A (very) minor optimization would be to replicate the value
   4235     // and fall through here to test for a valid 64-bit splat.  But, then the
   4236     // caller would also need to check and handle the change in size.
   4237     return SDValue();
   4238 
   4239   case 64: {
   4240     if (type != VMOVModImm)
   4241       return SDValue();
   4242     // NEON has a 64-bit VMOV splat where each byte is either 0 or 0xff.
   4243     uint64_t BitMask = 0xff;
   4244     uint64_t Val = 0;
   4245     unsigned ImmMask = 1;
   4246     Imm = 0;
   4247     for (int ByteNum = 0; ByteNum < 8; ++ByteNum) {
   4248       if (((SplatBits | SplatUndef) & BitMask) == BitMask) {
   4249         Val |= BitMask;
   4250         Imm |= ImmMask;
   4251       } else if ((SplatBits & BitMask) != 0) {
   4252         return SDValue();
   4253       }
   4254       BitMask <<= 8;
   4255       ImmMask <<= 1;
   4256     }
   4257     // Op=1, Cmode=1110.
   4258     OpCmode = 0x1e;
   4259     SplatBits = Val;
   4260     VT = is128Bits ? MVT::v2i64 : MVT::v1i64;
   4261     break;
   4262   }
   4263 
   4264   default:
   4265     llvm_unreachable("unexpected size for isNEONModifiedImm");
   4266   }
   4267 
   4268   unsigned EncodedVal = ARM_AM::createNEONModImm(OpCmode, Imm);
   4269   return DAG.getTargetConstant(EncodedVal, MVT::i32);
   4270 }
   4271 
   4272 SDValue ARMTargetLowering::LowerConstantFP(SDValue Op, SelectionDAG &DAG,
   4273                                            const ARMSubtarget *ST) const {
   4274   if (!ST->useNEONForSinglePrecisionFP() || !ST->hasVFP3() || ST->hasD16())
   4275     return SDValue();
   4276 
   4277   ConstantFPSDNode *CFP = cast<ConstantFPSDNode>(Op);
   4278   assert(Op.getValueType() == MVT::f32 &&
   4279          "ConstantFP custom lowering should only occur for f32.");
   4280 
   4281   // Try splatting with a VMOV.f32...
   4282   APFloat FPVal = CFP->getValueAPF();
   4283   int ImmVal = ARM_AM::getFP32Imm(FPVal);
   4284   if (ImmVal != -1) {
   4285     SDLoc DL(Op);
   4286     SDValue NewVal = DAG.getTargetConstant(ImmVal, MVT::i32);
   4287     SDValue VecConstant = DAG.getNode(ARMISD::VMOVFPIMM, DL, MVT::v2f32,
   4288                                       NewVal);
   4289     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32, VecConstant,
   4290                        DAG.getConstant(0, MVT::i32));
   4291   }
   4292 
   4293   // If that fails, try a VMOV.i32
   4294   EVT VMovVT;
   4295   unsigned iVal = FPVal.bitcastToAPInt().getZExtValue();
   4296   SDValue NewVal = isNEONModifiedImm(iVal, 0, 32, DAG, VMovVT, false,
   4297                                      VMOVModImm);
   4298   if (NewVal != SDValue()) {
   4299     SDLoc DL(Op);
   4300     SDValue VecConstant = DAG.getNode(ARMISD::VMOVIMM, DL, VMovVT,
   4301                                       NewVal);
   4302     SDValue VecFConstant = DAG.getNode(ISD::BITCAST, DL, MVT::v2f32,
   4303                                        VecConstant);
   4304     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32, VecFConstant,
   4305                        DAG.getConstant(0, MVT::i32));
   4306   }
   4307 
   4308   // Finally, try a VMVN.i32
   4309   NewVal = isNEONModifiedImm(~iVal & 0xffffffff, 0, 32, DAG, VMovVT, false,
   4310                              VMVNModImm);
   4311   if (NewVal != SDValue()) {
   4312     SDLoc DL(Op);
   4313     SDValue VecConstant = DAG.getNode(ARMISD::VMVNIMM, DL, VMovVT, NewVal);
   4314     SDValue VecFConstant = DAG.getNode(ISD::BITCAST, DL, MVT::v2f32,
   4315                                        VecConstant);
   4316     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32, VecFConstant,
   4317                        DAG.getConstant(0, MVT::i32));
   4318   }
   4319 
   4320   return SDValue();
   4321 }
   4322 
   4323 // check if an VEXT instruction can handle the shuffle mask when the
   4324 // vector sources of the shuffle are the same.
   4325 static bool isSingletonVEXTMask(ArrayRef<int> M, EVT VT, unsigned &Imm) {
   4326   unsigned NumElts = VT.getVectorNumElements();
   4327 
   4328   // Assume that the first shuffle index is not UNDEF.  Fail if it is.
   4329   if (M[0] < 0)
   4330     return false;
   4331 
   4332   Imm = M[0];
   4333 
   4334   // If this is a VEXT shuffle, the immediate value is the index of the first
   4335   // element.  The other shuffle indices must be the successive elements after
   4336   // the first one.
   4337   unsigned ExpectedElt = Imm;
   4338   for (unsigned i = 1; i < NumElts; ++i) {
   4339     // Increment the expected index.  If it wraps around, just follow it
   4340     // back to index zero and keep going.
   4341     ++ExpectedElt;
   4342     if (ExpectedElt == NumElts)
   4343       ExpectedElt = 0;
   4344 
   4345     if (M[i] < 0) continue; // ignore UNDEF indices
   4346     if (ExpectedElt != static_cast<unsigned>(M[i]))
   4347       return false;
   4348   }
   4349 
   4350   return true;
   4351 }
   4352 
   4353 
   4354 static bool isVEXTMask(ArrayRef<int> M, EVT VT,
   4355                        bool &ReverseVEXT, unsigned &Imm) {
   4356   unsigned NumElts = VT.getVectorNumElements();
   4357   ReverseVEXT = false;
   4358 
   4359   // Assume that the first shuffle index is not UNDEF.  Fail if it is.
   4360   if (M[0] < 0)
   4361     return false;
   4362 
   4363   Imm = M[0];
   4364 
   4365   // If this is a VEXT shuffle, the immediate value is the index of the first
   4366   // element.  The other shuffle indices must be the successive elements after
   4367   // the first one.
   4368   unsigned ExpectedElt = Imm;
   4369   for (unsigned i = 1; i < NumElts; ++i) {
   4370     // Increment the expected index.  If it wraps around, it may still be
   4371     // a VEXT but the source vectors must be swapped.
   4372     ExpectedElt += 1;
   4373     if (ExpectedElt == NumElts * 2) {
   4374       ExpectedElt = 0;
   4375       ReverseVEXT = true;
   4376     }
   4377 
   4378     if (M[i] < 0) continue; // ignore UNDEF indices
   4379     if (ExpectedElt != static_cast<unsigned>(M[i]))
   4380       return false;
   4381   }
   4382 
   4383   // Adjust the index value if the source operands will be swapped.
   4384   if (ReverseVEXT)
   4385     Imm -= NumElts;
   4386 
   4387   return true;
   4388 }
   4389 
   4390 /// isVREVMask - Check if a vector shuffle corresponds to a VREV
   4391 /// instruction with the specified blocksize.  (The order of the elements
   4392 /// within each block of the vector is reversed.)
   4393 static bool isVREVMask(ArrayRef<int> M, EVT VT, unsigned BlockSize) {
   4394   assert((BlockSize==16 || BlockSize==32 || BlockSize==64) &&
   4395          "Only possible block sizes for VREV are: 16, 32, 64");
   4396 
   4397   unsigned EltSz = VT.getVectorElementType().getSizeInBits();
   4398   if (EltSz == 64)
   4399     return false;
   4400 
   4401   unsigned NumElts = VT.getVectorNumElements();
   4402   unsigned BlockElts = M[0] + 1;
   4403   // If the first shuffle index is UNDEF, be optimistic.
   4404   if (M[0] < 0)
   4405     BlockElts = BlockSize / EltSz;
   4406 
   4407   if (BlockSize <= EltSz || BlockSize != BlockElts * EltSz)
   4408     return false;
   4409 
   4410   for (unsigned i = 0; i < NumElts; ++i) {
   4411     if (M[i] < 0) continue; // ignore UNDEF indices
   4412     if ((unsigned) M[i] != (i - i%BlockElts) + (BlockElts - 1 - i%BlockElts))
   4413       return false;
   4414   }
   4415 
   4416   return true;
   4417 }
   4418 
   4419 static bool isVTBLMask(ArrayRef<int> M, EVT VT) {
   4420   // We can handle <8 x i8> vector shuffles. If the index in the mask is out of
   4421   // range, then 0 is placed into the resulting vector. So pretty much any mask
   4422   // of 8 elements can work here.
   4423   return VT == MVT::v8i8 && M.size() == 8;
   4424 }
   4425 
   4426 static bool isVTRNMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
   4427   unsigned EltSz = VT.getVectorElementType().getSizeInBits();
   4428   if (EltSz == 64)
   4429     return false;
   4430 
   4431   unsigned NumElts = VT.getVectorNumElements();
   4432   WhichResult = (M[0] == 0 ? 0 : 1);
   4433   for (unsigned i = 0; i < NumElts; i += 2) {
   4434     if ((M[i] >= 0 && (unsigned) M[i] != i + WhichResult) ||
   4435         (M[i+1] >= 0 && (unsigned) M[i+1] != i + NumElts + WhichResult))
   4436       return false;
   4437   }
   4438   return true;
   4439 }
   4440 
   4441 /// isVTRN_v_undef_Mask - Special case of isVTRNMask for canonical form of
   4442 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef".
   4443 /// Mask is e.g., <0, 0, 2, 2> instead of <0, 4, 2, 6>.
   4444 static bool isVTRN_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult){
   4445   unsigned EltSz = VT.getVectorElementType().getSizeInBits();
   4446   if (EltSz == 64)
   4447     return false;
   4448 
   4449   unsigned NumElts = VT.getVectorNumElements();
   4450   WhichResult = (M[0] == 0 ? 0 : 1);
   4451   for (unsigned i = 0; i < NumElts; i += 2) {
   4452     if ((M[i] >= 0 && (unsigned) M[i] != i + WhichResult) ||
   4453         (M[i+1] >= 0 && (unsigned) M[i+1] != i + WhichResult))
   4454       return false;
   4455   }
   4456   return true;
   4457 }
   4458 
   4459 static bool isVUZPMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
   4460   unsigned EltSz = VT.getVectorElementType().getSizeInBits();
   4461   if (EltSz == 64)
   4462     return false;
   4463 
   4464   unsigned NumElts = VT.getVectorNumElements();
   4465   WhichResult = (M[0] == 0 ? 0 : 1);
   4466   for (unsigned i = 0; i != NumElts; ++i) {
   4467     if (M[i] < 0) continue; // ignore UNDEF indices
   4468     if ((unsigned) M[i] != 2 * i + WhichResult)
   4469       return false;
   4470   }
   4471 
   4472   // VUZP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32.
   4473   if (VT.is64BitVector() && EltSz == 32)
   4474     return false;
   4475 
   4476   return true;
   4477 }
   4478 
   4479 /// isVUZP_v_undef_Mask - Special case of isVUZPMask for canonical form of
   4480 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef".
   4481 /// Mask is e.g., <0, 2, 0, 2> instead of <0, 2, 4, 6>,
   4482 static bool isVUZP_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult){
   4483   unsigned EltSz = VT.getVectorElementType().getSizeInBits();
   4484   if (EltSz == 64)
   4485     return false;
   4486 
   4487   unsigned Half = VT.getVectorNumElements() / 2;
   4488   WhichResult = (M[0] == 0 ? 0 : 1);
   4489   for (unsigned j = 0; j != 2; ++j) {
   4490     unsigned Idx = WhichResult;
   4491     for (unsigned i = 0; i != Half; ++i) {
   4492       int MIdx = M[i + j * Half];
   4493       if (MIdx >= 0 && (unsigned) MIdx != Idx)
   4494         return false;
   4495       Idx += 2;
   4496     }
   4497   }
   4498 
   4499   // VUZP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32.
   4500   if (VT.is64BitVector() && EltSz == 32)
   4501     return false;
   4502 
   4503   return true;
   4504 }
   4505 
   4506 static bool isVZIPMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
   4507   unsigned EltSz = VT.getVectorElementType().getSizeInBits();
   4508   if (EltSz == 64)
   4509     return false;
   4510 
   4511   unsigned NumElts = VT.getVectorNumElements();
   4512   WhichResult = (M[0] == 0 ? 0 : 1);
   4513   unsigned Idx = WhichResult * NumElts / 2;
   4514   for (unsigned i = 0; i != NumElts; i += 2) {
   4515     if ((M[i] >= 0 && (unsigned) M[i] != Idx) ||
   4516         (M[i+1] >= 0 && (unsigned) M[i+1] != Idx + NumElts))
   4517       return false;
   4518     Idx += 1;
   4519   }
   4520 
   4521   // VZIP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32.
   4522   if (VT.is64BitVector() && EltSz == 32)
   4523     return false;
   4524 
   4525   return true;
   4526 }
   4527 
   4528 /// isVZIP_v_undef_Mask - Special case of isVZIPMask for canonical form of
   4529 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef".
   4530 /// Mask is e.g., <0, 0, 1, 1> instead of <0, 4, 1, 5>.
   4531 static bool isVZIP_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult){
   4532   unsigned EltSz = VT.getVectorElementType().getSizeInBits();
   4533   if (EltSz == 64)
   4534     return false;
   4535 
   4536   unsigned NumElts = VT.getVectorNumElements();
   4537   WhichResult = (M[0] == 0 ? 0 : 1);
   4538   unsigned Idx = WhichResult * NumElts / 2;
   4539   for (unsigned i = 0; i != NumElts; i += 2) {
   4540     if ((M[i] >= 0 && (unsigned) M[i] != Idx) ||
   4541         (M[i+1] >= 0 && (unsigned) M[i+1] != Idx))
   4542       return false;
   4543     Idx += 1;
   4544   }
   4545 
   4546   // VZIP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32.
   4547   if (VT.is64BitVector() && EltSz == 32)
   4548     return false;
   4549 
   4550   return true;
   4551 }
   4552 
   4553 /// \return true if this is a reverse operation on an vector.
   4554 static bool isReverseMask(ArrayRef<int> M, EVT VT) {
   4555   unsigned NumElts = VT.getVectorNumElements();
   4556   // Make sure the mask has the right size.
   4557   if (NumElts != M.size())
   4558       return false;
   4559 
   4560   // Look for <15, ..., 3, -1, 1, 0>.
   4561   for (unsigned i = 0; i != NumElts; ++i)
   4562     if (M[i] >= 0 && M[i] != (int) (NumElts - 1 - i))
   4563       return false;
   4564 
   4565   return true;
   4566 }
   4567 
   4568 // If N is an integer constant that can be moved into a register in one
   4569 // instruction, return an SDValue of such a constant (will become a MOV
   4570 // instruction).  Otherwise return null.
   4571 static SDValue IsSingleInstrConstant(SDValue N, SelectionDAG &DAG,
   4572                                      const ARMSubtarget *ST, SDLoc dl) {
   4573   uint64_t Val;
   4574   if (!isa<ConstantSDNode>(N))
   4575     return SDValue();
   4576   Val = cast<ConstantSDNode>(N)->getZExtValue();
   4577 
   4578   if (ST->isThumb1Only()) {
   4579     if (Val <= 255 || ~Val <= 255)
   4580       return DAG.getConstant(Val, MVT::i32);
   4581   } else {
   4582     if (ARM_AM::getSOImmVal(Val) != -1 || ARM_AM::getSOImmVal(~Val) != -1)
   4583       return DAG.getConstant(Val, MVT::i32);
   4584   }
   4585   return SDValue();
   4586 }
   4587 
   4588 // If this is a case we can't handle, return null and let the default
   4589 // expansion code take care of it.
   4590 SDValue ARMTargetLowering::LowerBUILD_VECTOR(SDValue Op, SelectionDAG &DAG,
   4591                                              const ARMSubtarget *ST) const {
   4592   BuildVectorSDNode *BVN = cast<BuildVectorSDNode>(Op.getNode());
   4593   SDLoc dl(Op);
   4594   EVT VT = Op.getValueType();
   4595 
   4596   APInt SplatBits, SplatUndef;
   4597   unsigned SplatBitSize;
   4598   bool HasAnyUndefs;
   4599   if (BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs)) {
   4600     if (SplatBitSize <= 64) {
   4601       // Check if an immediate VMOV works.
   4602       EVT VmovVT;
   4603       SDValue Val = isNEONModifiedImm(SplatBits.getZExtValue(),
   4604                                       SplatUndef.getZExtValue(), SplatBitSize,
   4605                                       DAG, VmovVT, VT.is128BitVector(),
   4606                                       VMOVModImm);
   4607       if (Val.getNode()) {
   4608         SDValue Vmov = DAG.getNode(ARMISD::VMOVIMM, dl, VmovVT, Val);
   4609         return DAG.getNode(ISD::BITCAST, dl, VT, Vmov);
   4610       }
   4611 
   4612       // Try an immediate VMVN.
   4613       uint64_t NegatedImm = (~SplatBits).getZExtValue();
   4614       Val = isNEONModifiedImm(NegatedImm,
   4615                                       SplatUndef.getZExtValue(), SplatBitSize,
   4616                                       DAG, VmovVT, VT.is128BitVector(),
   4617                                       VMVNModImm);
   4618       if (Val.getNode()) {
   4619         SDValue Vmov = DAG.getNode(ARMISD::VMVNIMM, dl, VmovVT, Val);
   4620         return DAG.getNode(ISD::BITCAST, dl, VT, Vmov);
   4621       }
   4622 
   4623       // Use vmov.f32 to materialize other v2f32 and v4f32 splats.
   4624       if ((VT == MVT::v2f32 || VT == MVT::v4f32) && SplatBitSize == 32) {
   4625         int ImmVal = ARM_AM::getFP32Imm(SplatBits);
   4626         if (ImmVal != -1) {
   4627           SDValue Val = DAG.getTargetConstant(ImmVal, MVT::i32);
   4628           return DAG.getNode(ARMISD::VMOVFPIMM, dl, VT, Val);
   4629         }
   4630       }
   4631     }
   4632   }
   4633 
   4634   // Scan through the operands to see if only one value is used.
   4635   //
   4636   // As an optimisation, even if more than one value is used it may be more
   4637   // profitable to splat with one value then change some lanes.
   4638   //
   4639   // Heuristically we decide to do this if the vector has a "dominant" value,
   4640   // defined as splatted to more than half of the lanes.
   4641   unsigned NumElts = VT.getVectorNumElements();
   4642   bool isOnlyLowElement = true;
   4643   bool usesOnlyOneValue = true;
   4644   bool hasDominantValue = false;
   4645   bool isConstant = true;
   4646 
   4647   // Map of the number of times a particular SDValue appears in the
   4648   // element list.
   4649   DenseMap<SDValue, unsigned> ValueCounts;
   4650   SDValue Value;
   4651   for (unsigned i = 0; i < NumElts; ++i) {
   4652     SDValue V = Op.getOperand(i);
   4653     if (V.getOpcode() == ISD::UNDEF)
   4654       continue;
   4655     if (i > 0)
   4656       isOnlyLowElement = false;
   4657     if (!isa<ConstantFPSDNode>(V) && !isa<ConstantSDNode>(V))
   4658       isConstant = false;
   4659 
   4660     ValueCounts.insert(std::make_pair(V, 0));
   4661     unsigned &Count = ValueCounts[V];
   4662 
   4663     // Is this value dominant? (takes up more than half of the lanes)
   4664     if (++Count > (NumElts / 2)) {
   4665       hasDominantValue = true;
   4666       Value = V;
   4667     }
   4668   }
   4669   if (ValueCounts.size() != 1)
   4670     usesOnlyOneValue = false;
   4671   if (!Value.getNode() && ValueCounts.size() > 0)
   4672     Value = ValueCounts.begin()->first;
   4673 
   4674   if (ValueCounts.size() == 0)
   4675     return DAG.getUNDEF(VT);
   4676 
   4677   // Loads are better lowered with insert_vector_elt/ARMISD::BUILD_VECTOR.
   4678   // Keep going if we are hitting this case.
   4679   if (isOnlyLowElement && !ISD::isNormalLoad(Value.getNode()))
   4680     return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Value);
   4681 
   4682   unsigned EltSize = VT.getVectorElementType().getSizeInBits();
   4683 
   4684   // Use VDUP for non-constant splats.  For f32 constant splats, reduce to
   4685   // i32 and try again.
   4686   if (hasDominantValue && EltSize <= 32) {
   4687     if (!isConstant) {
   4688       SDValue N;
   4689 
   4690       // If we are VDUPing a value that comes directly from a vector, that will
   4691       // cause an unnecessary move to and from a GPR, where instead we could
   4692       // just use VDUPLANE. We can only do this if the lane being extracted
   4693       // is at a constant index, as the VDUP from lane instructions only have
   4694       // constant-index forms.
   4695       if (Value->getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
   4696           isa<ConstantSDNode>(Value->getOperand(1))) {
   4697         // We need to create a new undef vector to use for the VDUPLANE if the
   4698         // size of the vector from which we get the value is different than the
   4699         // size of the vector that we need to create. We will insert the element
   4700         // such that the register coalescer will remove unnecessary copies.
   4701         if (VT != Value->getOperand(0).getValueType()) {
   4702           ConstantSDNode *constIndex;
   4703           constIndex = dyn_cast<ConstantSDNode>(Value->getOperand(1));
   4704           assert(constIndex && "The index is not a constant!");
   4705           unsigned index = constIndex->getAPIntValue().getLimitedValue() %
   4706                              VT.getVectorNumElements();
   4707           N =  DAG.getNode(ARMISD::VDUPLANE, dl, VT,
   4708                  DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, DAG.getUNDEF(VT),
   4709                         Value, DAG.getConstant(index, MVT::i32)),
   4710                            DAG.getConstant(index, MVT::i32));
   4711         } else
   4712           N = DAG.getNode(ARMISD::VDUPLANE, dl, VT,
   4713                         Value->getOperand(0), Value->getOperand(1));
   4714       } else
   4715         N = DAG.getNode(ARMISD::VDUP, dl, VT, Value);
   4716 
   4717       if (!usesOnlyOneValue) {
   4718         // The dominant value was splatted as 'N', but we now have to insert
   4719         // all differing elements.
   4720         for (unsigned I = 0; I < NumElts; ++I) {
   4721           if (Op.getOperand(I) == Value)
   4722             continue;
   4723           SmallVector<SDValue, 3> Ops;
   4724           Ops.push_back(N);
   4725           Ops.push_back(Op.getOperand(I));
   4726           Ops.push_back(DAG.getConstant(I, MVT::i32));
   4727           N = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, &Ops[0], 3);
   4728         }
   4729       }
   4730       return N;
   4731     }
   4732     if (VT.getVectorElementType().isFloatingPoint()) {
   4733       SmallVector<SDValue, 8> Ops;
   4734       for (unsigned i = 0; i < NumElts; ++i)
   4735         Ops.push_back(DAG.getNode(ISD::BITCAST, dl, MVT::i32,
   4736                                   Op.getOperand(i)));
   4737       EVT VecVT = EVT::getVectorVT(*DAG.getContext(), MVT::i32, NumElts);
   4738       SDValue Val = DAG.getNode(ISD::BUILD_VECTOR, dl, VecVT, &Ops[0], NumElts);
   4739       Val = LowerBUILD_VECTOR(Val, DAG, ST);
   4740       if (Val.getNode())
   4741         return DAG.getNode(ISD::BITCAST, dl, VT, Val);
   4742     }
   4743     if (usesOnlyOneValue) {
   4744       SDValue Val = IsSingleInstrConstant(Value, DAG, ST, dl);
   4745       if (isConstant && Val.getNode())
   4746         return DAG.getNode(ARMISD::VDUP, dl, VT, Val);
   4747     }
   4748   }
   4749 
   4750   // If all elements are constants and the case above didn't get hit, fall back
   4751   // to the default expansion, which will generate a load from the constant
   4752   // pool.
   4753   if (isConstant)
   4754     return SDValue();
   4755 
   4756   // Empirical tests suggest this is rarely worth it for vectors of length <= 2.
   4757   if (NumElts >= 4) {
   4758     SDValue shuffle = ReconstructShuffle(Op, DAG);
   4759     if (shuffle != SDValue())
   4760       return shuffle;
   4761   }
   4762 
   4763   // Vectors with 32- or 64-bit elements can be built by directly assigning
   4764   // the subregisters.  Lower it to an ARMISD::BUILD_VECTOR so the operands
   4765   // will be legalized.
   4766   if (EltSize >= 32) {
   4767     // Do the expansion with floating-point types, since that is what the VFP
   4768     // registers are defined to use, and since i64 is not legal.
   4769     EVT EltVT = EVT::getFloatingPointVT(EltSize);
   4770     EVT VecVT = EVT::getVectorVT(*DAG.getContext(), EltVT, NumElts);
   4771     SmallVector<SDValue, 8> Ops;
   4772     for (unsigned i = 0; i < NumElts; ++i)
   4773       Ops.push_back(DAG.getNode(ISD::BITCAST, dl, EltVT, Op.getOperand(i)));
   4774     SDValue Val = DAG.getNode(ARMISD::BUILD_VECTOR, dl, VecVT, &Ops[0],NumElts);
   4775     return DAG.getNode(ISD::BITCAST, dl, VT, Val);
   4776   }
   4777 
   4778   // If all else fails, just use a sequence of INSERT_VECTOR_ELT when we
   4779   // know the default expansion would otherwise fall back on something even
   4780   // worse. For a vector with one or two non-undef values, that's
   4781   // scalar_to_vector for the elements followed by a shuffle (provided the
   4782   // shuffle is valid for the target) and materialization element by element
   4783   // on the stack followed by a load for everything else.
   4784   if (!isConstant && !usesOnlyOneValue) {
   4785     SDValue Vec = DAG.getUNDEF(VT);
   4786     for (unsigned i = 0 ; i < NumElts; ++i) {
   4787       SDValue V = Op.getOperand(i);
   4788       if (V.getOpcode() == ISD::UNDEF)
   4789         continue;
   4790       SDValue LaneIdx = DAG.getConstant(i, MVT::i32);
   4791       Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Vec, V, LaneIdx);
   4792     }
   4793     return Vec;
   4794   }
   4795 
   4796   return SDValue();
   4797 }
   4798 
   4799 // Gather data to see if the operation can be modelled as a
   4800 // shuffle in combination with VEXTs.
   4801 SDValue ARMTargetLowering::ReconstructShuffle(SDValue Op,
   4802                                               SelectionDAG &DAG) const {
   4803   SDLoc dl(Op);
   4804   EVT VT = Op.getValueType();
   4805   unsigned NumElts = VT.getVectorNumElements();
   4806 
   4807   SmallVector<SDValue, 2> SourceVecs;
   4808   SmallVector<unsigned, 2> MinElts;
   4809   SmallVector<unsigned, 2> MaxElts;
   4810 
   4811   for (unsigned i = 0; i < NumElts; ++i) {
   4812     SDValue V = Op.getOperand(i);
   4813     if (V.getOpcode() == ISD::UNDEF)
   4814       continue;
   4815     else if (V.getOpcode() != ISD::EXTRACT_VECTOR_ELT) {
   4816       // A shuffle can only come from building a vector from various
   4817       // elements of other vectors.
   4818       return SDValue();
   4819     } else if (V.getOperand(0).getValueType().getVectorElementType() !=
   4820                VT.getVectorElementType()) {
   4821       // This code doesn't know how to handle shuffles where the vector
   4822       // element types do not match (this happens because type legalization
   4823       // promotes the return type of EXTRACT_VECTOR_ELT).
   4824       // FIXME: It might be appropriate to extend this code to handle
   4825       // mismatched types.
   4826       return SDValue();
   4827     }
   4828 
   4829     // Record this extraction against the appropriate vector if possible...
   4830     SDValue SourceVec = V.getOperand(0);
   4831     // If the element number isn't a constant, we can't effectively
   4832     // analyze what's going on.
   4833     if (!isa<ConstantSDNode>(V.getOperand(1)))
   4834       return SDValue();
   4835     unsigned EltNo = cast<ConstantSDNode>(V.getOperand(1))->getZExtValue();
   4836     bool FoundSource = false;
   4837     for (unsigned j = 0; j < SourceVecs.size(); ++j) {
   4838       if (SourceVecs[j] == SourceVec) {
   4839         if (MinElts[j] > EltNo)
   4840           MinElts[j] = EltNo;
   4841         if (MaxElts[j] < EltNo)
   4842           MaxElts[j] = EltNo;
   4843         FoundSource = true;
   4844         break;
   4845       }
   4846     }
   4847 
   4848     // Or record a new source if not...
   4849     if (!FoundSource) {
   4850       SourceVecs.push_back(SourceVec);
   4851       MinElts.push_back(EltNo);
   4852       MaxElts.push_back(EltNo);
   4853     }
   4854   }
   4855 
   4856   // Currently only do something sane when at most two source vectors
   4857   // involved.
   4858   if (SourceVecs.size() > 2)
   4859     return SDValue();
   4860 
   4861   SDValue ShuffleSrcs[2] = {DAG.getUNDEF(VT), DAG.getUNDEF(VT) };
   4862   int VEXTOffsets[2] = {0, 0};
   4863 
   4864   // This loop extracts the usage patterns of the source vectors
   4865   // and prepares appropriate SDValues for a shuffle if possible.
   4866   for (unsigned i = 0; i < SourceVecs.size(); ++i) {
   4867     if (SourceVecs[i].getValueType() == VT) {
   4868       // No VEXT necessary
   4869       ShuffleSrcs[i] = SourceVecs[i];
   4870       VEXTOffsets[i] = 0;
   4871       continue;
   4872     } else if (SourceVecs[i].getValueType().getVectorNumElements() < NumElts) {
   4873       // It probably isn't worth padding out a smaller vector just to
   4874       // break it down again in a shuffle.
   4875       return SDValue();
   4876     }
   4877 
   4878     // Since only 64-bit and 128-bit vectors are legal on ARM and
   4879     // we've eliminated the other cases...
   4880     assert(SourceVecs[i].getValueType().getVectorNumElements() == 2*NumElts &&
   4881            "unexpected vector sizes in ReconstructShuffle");
   4882 
   4883     if (MaxElts[i] - MinElts[i] >= NumElts) {
   4884       // Span too large for a VEXT to cope
   4885       return SDValue();
   4886     }
   4887 
   4888     if (MinElts[i] >= NumElts) {
   4889       // The extraction can just take the second half
   4890       VEXTOffsets[i] = NumElts;
   4891       ShuffleSrcs[i] = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT,
   4892                                    SourceVecs[i],
   4893                                    DAG.getIntPtrConstant(NumElts));
   4894     } else if (MaxElts[i] < NumElts) {
   4895       // The extraction can just take the first half
   4896       VEXTOffsets[i] = 0;
   4897       ShuffleSrcs[i] = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT,
   4898                                    SourceVecs[i],
   4899                                    DAG.getIntPtrConstant(0));
   4900     } else {
   4901       // An actual VEXT is needed
   4902       VEXTOffsets[i] = MinElts[i];
   4903       SDValue VEXTSrc1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT,
   4904                                      SourceVecs[i],
   4905                                      DAG.getIntPtrConstant(0));
   4906       SDValue VEXTSrc2 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT,
   4907                                      SourceVecs[i],
   4908                                      DAG.getIntPtrConstant(NumElts));
   4909       ShuffleSrcs[i] = DAG.getNode(ARMISD::VEXT, dl, VT, VEXTSrc1, VEXTSrc2,
   4910                                    DAG.getConstant(VEXTOffsets[i], MVT::i32));
   4911     }
   4912   }
   4913 
   4914   SmallVector<int, 8> Mask;
   4915 
   4916   for (unsigned i = 0; i < NumElts; ++i) {
   4917     SDValue Entry = Op.getOperand(i);
   4918     if (Entry.getOpcode() == ISD::UNDEF) {
   4919       Mask.push_back(-1);
   4920       continue;
   4921     }
   4922 
   4923     SDValue ExtractVec = Entry.getOperand(0);
   4924     int ExtractElt = cast<ConstantSDNode>(Op.getOperand(i)
   4925                                           .getOperand(1))->getSExtValue();
   4926     if (ExtractVec == SourceVecs[0]) {
   4927       Mask.push_back(ExtractElt - VEXTOffsets[0]);
   4928     } else {
   4929       Mask.push_back(ExtractElt + NumElts - VEXTOffsets[1]);
   4930     }
   4931   }
   4932 
   4933   // Final check before we try to produce nonsense...
   4934   if (isShuffleMaskLegal(Mask, VT))
   4935     return DAG.getVectorShuffle(VT, dl, ShuffleSrcs[0], ShuffleSrcs[1],
   4936                                 &Mask[0]);
   4937 
   4938   return SDValue();
   4939 }
   4940 
   4941 /// isShuffleMaskLegal - Targets can use this to indicate that they only
   4942 /// support *some* VECTOR_SHUFFLE operations, those with specific masks.
   4943 /// By default, if a target supports the VECTOR_SHUFFLE node, all mask values
   4944 /// are assumed to be legal.
   4945 bool
   4946 ARMTargetLowering::isShuffleMaskLegal(const SmallVectorImpl<int> &M,
   4947                                       EVT VT) const {
   4948   if (VT.getVectorNumElements() == 4 &&
   4949       (VT.is128BitVector() || VT.is64BitVector())) {
   4950     unsigned PFIndexes[4];
   4951     for (unsigned i = 0; i != 4; ++i) {
   4952       if (M[i] < 0)
   4953         PFIndexes[i] = 8;
   4954       else
   4955         PFIndexes[i] = M[i];
   4956     }
   4957 
   4958     // Compute the index in the perfect shuffle table.
   4959     unsigned PFTableIndex =
   4960       PFIndexes[0]*9*9*9+PFIndexes[1]*9*9+PFIndexes[2]*9+PFIndexes[3];
   4961     unsigned PFEntry = PerfectShuffleTable[PFTableIndex];
   4962     unsigned Cost = (PFEntry >> 30);
   4963 
   4964     if (Cost <= 4)
   4965       return true;
   4966   }
   4967 
   4968   bool ReverseVEXT;
   4969   unsigned Imm, WhichResult;
   4970 
   4971   unsigned EltSize = VT.getVectorElementType().getSizeInBits();
   4972   return (EltSize >= 32 ||
   4973           ShuffleVectorSDNode::isSplatMask(&M[0], VT) ||
   4974           isVREVMask(M, VT, 64) ||
   4975           isVREVMask(M, VT, 32) ||
   4976           isVREVMask(M, VT, 16) ||
   4977           isVEXTMask(M, VT, ReverseVEXT, Imm) ||
   4978           isVTBLMask(M, VT) ||
   4979           isVTRNMask(M, VT, WhichResult) ||
   4980           isVUZPMask(M, VT, WhichResult) ||
   4981           isVZIPMask(M, VT, WhichResult) ||
   4982           isVTRN_v_undef_Mask(M, VT, WhichResult) ||
   4983           isVUZP_v_undef_Mask(M, VT, WhichResult) ||
   4984           isVZIP_v_undef_Mask(M, VT, WhichResult) ||
   4985           ((VT == MVT::v8i16 || VT == MVT::v16i8) && isReverseMask(M, VT)));
   4986 }
   4987 
   4988 /// GeneratePerfectShuffle - Given an entry in the perfect-shuffle table, emit
   4989 /// the specified operations to build the shuffle.
   4990 static SDValue GeneratePerfectShuffle(unsigned PFEntry, SDValue LHS,
   4991                                       SDValue RHS, SelectionDAG &DAG,
   4992                                       SDLoc dl) {
   4993   unsigned OpNum = (PFEntry >> 26) & 0x0F;
   4994   unsigned LHSID = (PFEntry >> 13) & ((1 << 13)-1);
   4995   unsigned RHSID = (PFEntry >>  0) & ((1 << 13)-1);
   4996 
   4997   enum {
   4998     OP_COPY = 0, // Copy, used for things like <u,u,u,3> to say it is <0,1,2,3>
   4999     OP_VREV,
   5000     OP_VDUP0,
   5001     OP_VDUP1,
   5002     OP_VDUP2,
   5003     OP_VDUP3,
   5004     OP_VEXT1,
   5005     OP_VEXT2,
   5006     OP_VEXT3,
   5007     OP_VUZPL, // VUZP, left result
   5008     OP_VUZPR, // VUZP, right result
   5009     OP_VZIPL, // VZIP, left result
   5010     OP_VZIPR, // VZIP, right result
   5011     OP_VTRNL, // VTRN, left result
   5012     OP_VTRNR  // VTRN, right result
   5013   };
   5014 
   5015   if (OpNum == OP_COPY) {
   5016     if (LHSID == (1*9+2)*9+3) return LHS;
   5017     assert(LHSID == ((4*9+5)*9+6)*9+7 && "Illegal OP_COPY!");
   5018     return RHS;
   5019   }
   5020 
   5021   SDValue OpLHS, OpRHS;
   5022   OpLHS = GeneratePerfectShuffle(PerfectShuffleTable[LHSID], LHS, RHS, DAG, dl);
   5023   OpRHS = GeneratePerfectShuffle(PerfectShuffleTable[RHSID], LHS, RHS, DAG, dl);
   5024   EVT VT = OpLHS.getValueType();
   5025 
   5026   switch (OpNum) {
   5027   default: llvm_unreachable("Unknown shuffle opcode!");
   5028   case OP_VREV:
   5029     // VREV divides the vector in half and swaps within the half.
   5030     if (VT.getVectorElementType() == MVT::i32 ||
   5031         VT.getVectorElementType() == MVT::f32)
   5032       return DAG.getNode(ARMISD::VREV64, dl, VT, OpLHS);
   5033     // vrev <4 x i16> -> VREV32
   5034     if (VT.getVectorElementType() == MVT::i16)
   5035       return DAG.getNode(ARMISD::VREV32, dl, VT, OpLHS);
   5036     // vrev <4 x i8> -> VREV16
   5037     assert(VT.getVectorElementType() == MVT::i8);
   5038     return DAG.getNode(ARMISD::VREV16, dl, VT, OpLHS);
   5039   case OP_VDUP0:
   5040   case OP_VDUP1:
   5041   case OP_VDUP2:
   5042   case OP_VDUP3:
   5043     return DAG.getNode(ARMISD::VDUPLANE, dl, VT,
   5044                        OpLHS, DAG.getConstant(OpNum-OP_VDUP0, MVT::i32));
   5045   case OP_VEXT1:
   5046   case OP_VEXT2:
   5047   case OP_VEXT3:
   5048     return DAG.getNode(ARMISD::VEXT, dl, VT,
   5049                        OpLHS, OpRHS,
   5050                        DAG.getConstant(OpNum-OP_VEXT1+1, MVT::i32));
   5051   case OP_VUZPL:
   5052   case OP_VUZPR:
   5053     return DAG.getNode(ARMISD::VUZP, dl, DAG.getVTList(VT, VT),
   5054                        OpLHS, OpRHS).getValue(OpNum-OP_VUZPL);
   5055   case OP_VZIPL:
   5056   case OP_VZIPR:
   5057     return DAG.getNode(ARMISD::VZIP, dl, DAG.getVTList(VT, VT),
   5058                        OpLHS, OpRHS).getValue(OpNum-OP_VZIPL);
   5059   case OP_VTRNL:
   5060   case OP_VTRNR:
   5061     return DAG.getNode(ARMISD::VTRN, dl, DAG.getVTList(VT, VT),
   5062                        OpLHS, OpRHS).getValue(OpNum-OP_VTRNL);
   5063   }
   5064 }
   5065 
   5066 static SDValue LowerVECTOR_SHUFFLEv8i8(SDValue Op,
   5067                                        ArrayRef<int> ShuffleMask,
   5068                                        SelectionDAG &DAG) {
   5069   // Check to see if we can use the VTBL instruction.
   5070   SDValue V1 = Op.getOperand(0);
   5071   SDValue V2 = Op.getOperand(1);
   5072   SDLoc DL(Op);
   5073 
   5074   SmallVector<SDValue, 8> VTBLMask;
   5075   for (ArrayRef<int>::iterator
   5076          I = ShuffleMask.begin(), E = ShuffleMask.end(); I != E; ++I)
   5077     VTBLMask.push_back(DAG.getConstant(*I, MVT::i32));
   5078 
   5079   if (V2.getNode()->getOpcode() == ISD::UNDEF)
   5080     return DAG.getNode(ARMISD::VTBL1, DL, MVT::v8i8, V1,
   5081                        DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v8i8,
   5082                                    &VTBLMask[0], 8));
   5083 
   5084   return DAG.getNode(ARMISD::VTBL2, DL, MVT::v8i8, V1, V2,
   5085                      DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v8i8,
   5086                                  &VTBLMask[0], 8));
   5087 }
   5088 
   5089 static SDValue LowerReverse_VECTOR_SHUFFLEv16i8_v8i16(SDValue Op,
   5090                                                       SelectionDAG &DAG) {
   5091   SDLoc DL(Op);
   5092   SDValue OpLHS = Op.getOperand(0);
   5093   EVT VT = OpLHS.getValueType();
   5094 
   5095   assert((VT == MVT::v8i16 || VT == MVT::v16i8) &&
   5096          "Expect an v8i16/v16i8 type");
   5097   OpLHS = DAG.getNode(ARMISD::VREV64, DL, VT, OpLHS);
   5098   // For a v16i8 type: After the VREV, we have got <8, ...15, 8, ..., 0>. Now,
   5099   // extract the first 8 bytes into the top double word and the last 8 bytes
   5100   // into the bottom double word. The v8i16 case is similar.
   5101   unsigned ExtractNum = (VT == MVT::v16i8) ? 8 : 4;
   5102   return DAG.getNode(ARMISD::VEXT, DL, VT, OpLHS, OpLHS,
   5103                      DAG.getConstant(ExtractNum, MVT::i32));
   5104 }
   5105 
   5106 static SDValue LowerVECTOR_SHUFFLE(SDValue Op, SelectionDAG &DAG) {
   5107   SDValue V1 = Op.getOperand(0);
   5108   SDValue V2 = Op.getOperand(1);
   5109   SDLoc dl(Op);
   5110   EVT VT = Op.getValueType();
   5111   ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(Op.getNode());
   5112 
   5113   // Convert shuffles that are directly supported on NEON to target-specific
   5114   // DAG nodes, instead of keeping them as shuffles and matching them again
   5115   // during code selection.  This is more efficient and avoids the possibility
   5116   // of inconsistencies between legalization and selection.
   5117   // FIXME: floating-point vectors should be canonicalized to integer vectors
   5118   // of the same time so that they get CSEd properly.
   5119   ArrayRef<int> ShuffleMask = SVN->getMask();
   5120 
   5121   unsigned EltSize = VT.getVectorElementType().getSizeInBits();
   5122   if (EltSize <= 32) {
   5123     if (ShuffleVectorSDNode::isSplatMask(&ShuffleMask[0], VT)) {
   5124       int Lane = SVN->getSplatIndex();
   5125       // If this is undef splat, generate it via "just" vdup, if possible.
   5126       if (Lane == -1) Lane = 0;
   5127 
   5128       // Test if V1 is a SCALAR_TO_VECTOR.
   5129       if (Lane == 0 && V1.getOpcode() == ISD::SCALAR_TO_VECTOR) {
   5130         return DAG.getNode(ARMISD::VDUP, dl, VT, V1.getOperand(0));
   5131       }
   5132       // Test if V1 is a BUILD_VECTOR which is equivalent to a SCALAR_TO_VECTOR
   5133       // (and probably will turn into a SCALAR_TO_VECTOR once legalization
   5134       // reaches it).
   5135       if (Lane == 0 && V1.getOpcode() == ISD::BUILD_VECTOR &&
   5136           !isa<ConstantSDNode>(V1.getOperand(0))) {
   5137         bool IsScalarToVector = true;
   5138         for (unsigned i = 1, e = V1.getNumOperands(); i != e; ++i)
   5139           if (V1.getOperand(i).getOpcode() != ISD::UNDEF) {
   5140             IsScalarToVector = false;
   5141             break;
   5142           }
   5143         if (IsScalarToVector)
   5144           return DAG.getNode(ARMISD::VDUP, dl, VT, V1.getOperand(0));
   5145       }
   5146       return DAG.getNode(ARMISD::VDUPLANE, dl, VT, V1,
   5147                          DAG.getConstant(Lane, MVT::i32));
   5148     }
   5149 
   5150     bool ReverseVEXT;
   5151     unsigned Imm;
   5152     if (isVEXTMask(ShuffleMask, VT, ReverseVEXT, Imm)) {
   5153       if (ReverseVEXT)
   5154         std::swap(V1, V2);
   5155       return DAG.getNode(ARMISD::VEXT, dl, VT, V1, V2,
   5156                          DAG.getConstant(Imm, MVT::i32));
   5157     }
   5158 
   5159     if (isVREVMask(ShuffleMask, VT, 64))
   5160       return DAG.getNode(ARMISD::VREV64, dl, VT, V1);
   5161     if (isVREVMask(ShuffleMask, VT, 32))
   5162       return DAG.getNode(ARMISD::VREV32, dl, VT, V1);
   5163     if (isVREVMask(ShuffleMask, VT, 16))
   5164       return DAG.getNode(ARMISD::VREV16, dl, VT, V1);
   5165 
   5166     if (V2->getOpcode() == ISD::UNDEF &&
   5167         isSingletonVEXTMask(ShuffleMask, VT, Imm)) {
   5168       return DAG.getNode(ARMISD::VEXT, dl, VT, V1, V1,
   5169                          DAG.getConstant(Imm, MVT::i32));
   5170     }
   5171 
   5172     // Check for Neon shuffles that modify both input vectors in place.
   5173     // If both results are used, i.e., if there are two shuffles with the same
   5174     // source operands and with masks corresponding to both results of one of
   5175     // these operations, DAG memoization will ensure that a single node is
   5176     // used for both shuffles.
   5177     unsigned WhichResult;
   5178     if (isVTRNMask(ShuffleMask, VT, WhichResult))
   5179       return DAG.getNode(ARMISD::VTRN, dl, DAG.getVTList(VT, VT),
   5180                          V1, V2).getValue(WhichResult);
   5181     if (isVUZPMask(ShuffleMask, VT, WhichResult))
   5182       return DAG.getNode(ARMISD::VUZP, dl, DAG.getVTList(VT, VT),
   5183                          V1, V2).getValue(WhichResult);
   5184     if (isVZIPMask(ShuffleMask, VT, WhichResult))
   5185       return DAG.getNode(ARMISD::VZIP, dl, DAG.getVTList(VT, VT),
   5186                          V1, V2).getValue(WhichResult);
   5187 
   5188     if (isVTRN_v_undef_Mask(ShuffleMask, VT, WhichResult))
   5189       return DAG.getNode(ARMISD::VTRN, dl, DAG.getVTList(VT, VT),
   5190                          V1, V1).getValue(WhichResult);
   5191     if (isVUZP_v_undef_Mask(ShuffleMask, VT, WhichResult))
   5192       return DAG.getNode(ARMISD::VUZP, dl, DAG.getVTList(VT, VT),
   5193                          V1, V1).getValue(WhichResult);
   5194     if (isVZIP_v_undef_Mask(ShuffleMask, VT, WhichResult))
   5195       return DAG.getNode(ARMISD::VZIP, dl, DAG.getVTList(VT, VT),
   5196                          V1, V1).getValue(WhichResult);
   5197   }
   5198 
   5199   // If the shuffle is not directly supported and it has 4 elements, use
   5200   // the PerfectShuffle-generated table to synthesize it from other shuffles.
   5201   unsigned NumElts = VT.getVectorNumElements();
   5202   if (NumElts == 4) {
   5203     unsigned PFIndexes[4];
   5204     for (unsigned i = 0; i != 4; ++i) {
   5205       if (ShuffleMask[i] < 0)
   5206         PFIndexes[i] = 8;
   5207       else
   5208         PFIndexes[i] = ShuffleMask[i];
   5209     }
   5210 
   5211     // Compute the index in the perfect shuffle table.
   5212     unsigned PFTableIndex =
   5213       PFIndexes[0]*9*9*9+PFIndexes[1]*9*9+PFIndexes[2]*9+PFIndexes[3];
   5214     unsigned PFEntry = PerfectShuffleTable[PFTableIndex];
   5215     unsigned Cost = (PFEntry >> 30);
   5216 
   5217     if (Cost <= 4)
   5218       return GeneratePerfectShuffle(PFEntry, V1, V2, DAG, dl);
   5219   }
   5220 
   5221   // Implement shuffles with 32- or 64-bit elements as ARMISD::BUILD_VECTORs.
   5222   if (EltSize >= 32) {
   5223     // Do the expansion with floating-point types, since that is what the VFP
   5224     // registers are defined to use, and since i64 is not legal.
   5225     EVT EltVT = EVT::getFloatingPointVT(EltSize);
   5226     EVT VecVT = EVT::getVectorVT(*DAG.getContext(), EltVT, NumElts);
   5227     V1 = DAG.getNode(ISD::BITCAST, dl, VecVT, V1);
   5228     V2 = DAG.getNode(ISD::BITCAST, dl, VecVT, V2);
   5229     SmallVector<SDValue, 8> Ops;
   5230     for (unsigned i = 0; i < NumElts; ++i) {
   5231       if (ShuffleMask[i] < 0)
   5232         Ops.push_back(DAG.getUNDEF(EltVT));
   5233       else
   5234         Ops.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, EltVT,
   5235                                   ShuffleMask[i] < (int)NumElts ? V1 : V2,
   5236                                   DAG.getConstant(ShuffleMask[i] & (NumElts-1),
   5237                                                   MVT::i32)));
   5238     }
   5239     SDValue Val = DAG.getNode(ARMISD::BUILD_VECTOR, dl, VecVT, &Ops[0],NumElts);
   5240     return DAG.getNode(ISD::BITCAST, dl, VT, Val);
   5241   }
   5242 
   5243   if ((VT == MVT::v8i16 || VT == MVT::v16i8) && isReverseMask(ShuffleMask, VT))
   5244     return LowerReverse_VECTOR_SHUFFLEv16i8_v8i16(Op, DAG);
   5245 
   5246   if (VT == MVT::v8i8) {
   5247     SDValue NewOp = LowerVECTOR_SHUFFLEv8i8(Op, ShuffleMask, DAG);
   5248     if (NewOp.getNode())
   5249       return NewOp;
   5250   }
   5251 
   5252   return SDValue();
   5253 }
   5254 
   5255 static SDValue LowerINSERT_VECTOR_ELT(SDValue Op, SelectionDAG &DAG) {
   5256   // INSERT_VECTOR_ELT is legal only for immediate indexes.
   5257   SDValue Lane = Op.getOperand(2);
   5258   if (!isa<ConstantSDNode>(Lane))
   5259     return SDValue();
   5260 
   5261   return Op;
   5262 }
   5263 
   5264 static SDValue LowerEXTRACT_VECTOR_ELT(SDValue Op, SelectionDAG &DAG) {
   5265   // EXTRACT_VECTOR_ELT is legal only for immediate indexes.
   5266   SDValue Lane = Op.getOperand(1);
   5267   if (!isa<ConstantSDNode>(Lane))
   5268     return SDValue();
   5269 
   5270   SDValue Vec = Op.getOperand(0);
   5271   if (Op.getValueType() == MVT::i32 &&
   5272       Vec.getValueType().getVectorElementType().getSizeInBits() < 32) {
   5273     SDLoc dl(Op);
   5274     return DAG.getNode(ARMISD::VGETLANEu, dl, MVT::i32, Vec, Lane);
   5275   }
   5276 
   5277   return Op;
   5278 }
   5279 
   5280 static SDValue LowerCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG) {
   5281   // The only time a CONCAT_VECTORS operation can have legal types is when
   5282   // two 64-bit vectors are concatenated to a 128-bit vector.
   5283   assert(Op.getValueType().is128BitVector() && Op.getNumOperands() == 2 &&
   5284          "unexpected CONCAT_VECTORS");
   5285   SDLoc dl(Op);
   5286   SDValue Val = DAG.getUNDEF(MVT::v2f64);
   5287   SDValue Op0 = Op.getOperand(0);
   5288   SDValue Op1 = Op.getOperand(1);
   5289   if (Op0.getOpcode() != ISD::UNDEF)
   5290     Val = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Val,
   5291                       DAG.getNode(ISD::BITCAST, dl, MVT::f64, Op0),
   5292                       DAG.getIntPtrConstant(0));
   5293   if (Op1.getOpcode() != ISD::UNDEF)
   5294     Val = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Val,
   5295                       DAG.getNode(ISD::BITCAST, dl, MVT::f64, Op1),
   5296                       DAG.getIntPtrConstant(1));
   5297   return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Val);
   5298 }
   5299 
   5300 /// isExtendedBUILD_VECTOR - Check if N is a constant BUILD_VECTOR where each
   5301 /// element has been zero/sign-extended, depending on the isSigned parameter,
   5302 /// from an integer type half its size.
   5303 static bool isExtendedBUILD_VECTOR(SDNode *N, SelectionDAG &DAG,
   5304                                    bool isSigned) {
   5305   // A v2i64 BUILD_VECTOR will have been legalized to a BITCAST from v4i32.
   5306   EVT VT = N->getValueType(0);
   5307   if (VT == MVT::v2i64 && N->getOpcode() == ISD::BITCAST) {
   5308     SDNode *BVN = N->getOperand(0).getNode();
   5309     if (BVN->getValueType(0) != MVT::v4i32 ||
   5310         BVN->getOpcode() != ISD::BUILD_VECTOR)
   5311       return false;
   5312     unsigned LoElt = DAG.getTargetLoweringInfo().isBigEndian() ? 1 : 0;
   5313     unsigned HiElt = 1 - LoElt;
   5314     ConstantSDNode *Lo0 = dyn_cast<ConstantSDNode>(BVN->getOperand(LoElt));
   5315     ConstantSDNode *Hi0 = dyn_cast<ConstantSDNode>(BVN->getOperand(HiElt));
   5316     ConstantSDNode *Lo1 = dyn_cast<ConstantSDNode>(BVN->getOperand(LoElt+2));
   5317     ConstantSDNode *Hi1 = dyn_cast<ConstantSDNode>(BVN->getOperand(HiElt+2));
   5318     if (!Lo0 || !Hi0 || !Lo1 || !Hi1)
   5319       return false;
   5320     if (isSigned) {
   5321       if (Hi0->getSExtValue() == Lo0->getSExtValue() >> 32 &&
   5322           Hi1->getSExtValue() == Lo1->getSExtValue() >> 32)
   5323         return true;
   5324     } else {
   5325       if (Hi0->isNullValue() && Hi1->isNullValue())
   5326         return true;
   5327     }
   5328     return false;
   5329   }
   5330 
   5331   if (N->getOpcode() != ISD::BUILD_VECTOR)
   5332     return false;
   5333 
   5334   for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
   5335     SDNode *Elt = N->getOperand(i).getNode();
   5336     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Elt)) {
   5337       unsigned EltSize = VT.getVectorElementType().getSizeInBits();
   5338       unsigned HalfSize = EltSize / 2;
   5339       if (isSigned) {
   5340         if (!isIntN(HalfSize, C->getSExtValue()))
   5341           return false;
   5342       } else {
   5343         if (!isUIntN(HalfSize, C->getZExtValue()))
   5344           return false;
   5345       }
   5346       continue;
   5347     }
   5348     return false;
   5349   }
   5350 
   5351   return true;
   5352 }
   5353 
   5354 /// isSignExtended - Check if a node is a vector value that is sign-extended
   5355 /// or a constant BUILD_VECTOR with sign-extended elements.
   5356 static bool isSignExtended(SDNode *N, SelectionDAG &DAG) {
   5357   if (N->getOpcode() == ISD::SIGN_EXTEND || ISD::isSEXTLoad(N))
   5358     return true;
   5359   if (isExtendedBUILD_VECTOR(N, DAG, true))
   5360     return true;
   5361   return false;
   5362 }
   5363 
   5364 /// isZeroExtended - Check if a node is a vector value that is zero-extended
   5365 /// or a constant BUILD_VECTOR with zero-extended elements.
   5366 static bool isZeroExtended(SDNode *N, SelectionDAG &DAG) {
   5367   if (N->getOpcode() == ISD::ZERO_EXTEND || ISD::isZEXTLoad(N))
   5368     return true;
   5369   if (isExtendedBUILD_VECTOR(N, DAG, false))
   5370     return true;
   5371   return false;
   5372 }
   5373 
   5374 static EVT getExtensionTo64Bits(const EVT &OrigVT) {
   5375   if (OrigVT.getSizeInBits() >= 64)
   5376     return OrigVT;
   5377 
   5378   assert(OrigVT.isSimple() && "Expecting a simple value type");
   5379 
   5380   MVT::SimpleValueType OrigSimpleTy = OrigVT.getSimpleVT().SimpleTy;
   5381   switch (OrigSimpleTy) {
   5382   default: llvm_unreachable("Unexpected Vector Type");
   5383   case MVT::v2i8:
   5384   case MVT::v2i16:
   5385      return MVT::v2i32;
   5386   case MVT::v4i8:
   5387     return  MVT::v4i16;
   5388   }
   5389 }
   5390 
   5391 /// AddRequiredExtensionForVMULL - Add a sign/zero extension to extend the total
   5392 /// value size to 64 bits. We need a 64-bit D register as an operand to VMULL.
   5393 /// We insert the required extension here to get the vector to fill a D register.
   5394 static SDValue AddRequiredExtensionForVMULL(SDValue N, SelectionDAG &DAG,
   5395                                             const EVT &OrigTy,
   5396                                             const EVT &ExtTy,
   5397                                             unsigned ExtOpcode) {
   5398   // The vector originally had a size of OrigTy. It was then extended to ExtTy.
   5399   // We expect the ExtTy to be 128-bits total. If the OrigTy is less than
   5400   // 64-bits we need to insert a new extension so that it will be 64-bits.
   5401   assert(ExtTy.is128BitVector() && "Unexpected extension size");
   5402   if (OrigTy.getSizeInBits() >= 64)
   5403     return N;
   5404 
   5405   // Must extend size to at least 64 bits to be used as an operand for VMULL.
   5406   EVT NewVT = getExtensionTo64Bits(OrigTy);
   5407 
   5408   return DAG.getNode(ExtOpcode, SDLoc(N), NewVT, N);
   5409 }
   5410 
   5411 /// SkipLoadExtensionForVMULL - return a load of the original vector size that
   5412 /// does not do any sign/zero extension. If the original vector is less
   5413 /// than 64 bits, an appropriate extension will be added after the load to
   5414 /// reach a total size of 64 bits. We have to add the extension separately
   5415 /// because ARM does not have a sign/zero extending load for vectors.
   5416 static SDValue SkipLoadExtensionForVMULL(LoadSDNode *LD, SelectionDAG& DAG) {
   5417   EVT ExtendedTy = getExtensionTo64Bits(LD->getMemoryVT());
   5418 
   5419   // The load already has the right type.
   5420   if (ExtendedTy == LD->getMemoryVT())
   5421     return DAG.getLoad(LD->getMemoryVT(), SDLoc(LD), LD->getChain(),
   5422                 LD->getBasePtr(), LD->getPointerInfo(), LD->isVolatile(),
   5423                 LD->isNonTemporal(), LD->isInvariant(),
   5424                 LD->getAlignment());
   5425 
   5426   // We need to create a zextload/sextload. We cannot just create a load
   5427   // followed by a zext/zext node because LowerMUL is also run during normal
   5428   // operation legalization where we can't create illegal types.
   5429   return DAG.getExtLoad(LD->getExtensionType(), SDLoc(LD), ExtendedTy,
   5430                         LD->getChain(), LD->getBasePtr(), LD->getPointerInfo(),
   5431                         LD->getMemoryVT(), LD->isVolatile(),
   5432                         LD->isNonTemporal(), LD->getAlignment());
   5433 }
   5434 
   5435 /// SkipExtensionForVMULL - For a node that is a SIGN_EXTEND, ZERO_EXTEND,
   5436 /// extending load, or BUILD_VECTOR with extended elements, return the
   5437 /// unextended value. The unextended vector should be 64 bits so that it can
   5438 /// be used as an operand to a VMULL instruction. If the original vector size
   5439 /// before extension is less than 64 bits we add a an extension to resize
   5440 /// the vector to 64 bits.
   5441 static SDValue SkipExtensionForVMULL(SDNode *N, SelectionDAG &DAG) {
   5442   if (N->getOpcode() == ISD::SIGN_EXTEND || N->getOpcode() == ISD::ZERO_EXTEND)
   5443     return AddRequiredExtensionForVMULL(N->getOperand(0), DAG,
   5444                                         N->getOperand(0)->getValueType(0),
   5445                                         N->getValueType(0),
   5446                                         N->getOpcode());
   5447 
   5448   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N))
   5449     return SkipLoadExtensionForVMULL(LD, DAG);
   5450 
   5451   // Otherwise, the value must be a BUILD_VECTOR.  For v2i64, it will
   5452   // have been legalized as a BITCAST from v4i32.
   5453   if (N->getOpcode() == ISD::BITCAST) {
   5454     SDNode *BVN = N->getOperand(0).getNode();
   5455     assert(BVN->getOpcode() == ISD::BUILD_VECTOR &&
   5456            BVN->getValueType(0) == MVT::v4i32 && "expected v4i32 BUILD_VECTOR");
   5457     unsigned LowElt = DAG.getTargetLoweringInfo().isBigEndian() ? 1 : 0;
   5458     return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), MVT::v2i32,
   5459                        BVN->getOperand(LowElt), BVN->getOperand(LowElt+2));
   5460   }
   5461   // Construct a new BUILD_VECTOR with elements truncated to half the size.
   5462   assert(N->getOpcode() == ISD::BUILD_VECTOR && "expected BUILD_VECTOR");
   5463   EVT VT = N->getValueType(0);
   5464   unsigned EltSize = VT.getVectorElementType().getSizeInBits() / 2;
   5465   unsigned NumElts = VT.getVectorNumElements();
   5466   MVT TruncVT = MVT::getIntegerVT(EltSize);
   5467   SmallVector<SDValue, 8> Ops;
   5468   for (unsigned i = 0; i != NumElts; ++i) {
   5469     ConstantSDNode *C = cast<ConstantSDNode>(N->getOperand(i));
   5470     const APInt &CInt = C->getAPIntValue();
   5471     // Element types smaller than 32 bits are not legal, so use i32 elements.
   5472     // The values are implicitly truncated so sext vs. zext doesn't matter.
   5473     Ops.push_back(DAG.getConstant(CInt.zextOrTrunc(32), MVT::i32));
   5474   }
   5475   return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N),
   5476                      MVT::getVectorVT(TruncVT, NumElts), Ops.data(), NumElts);
   5477 }
   5478 
   5479 static bool isAddSubSExt(SDNode *N, SelectionDAG &DAG) {
   5480   unsigned Opcode = N->getOpcode();
   5481   if (Opcode == ISD::ADD || Opcode == ISD::SUB) {
   5482     SDNode *N0 = N->getOperand(0).getNode();
   5483     SDNode *N1 = N->getOperand(1).getNode();
   5484     return N0->hasOneUse() && N1->hasOneUse() &&
   5485       isSignExtended(N0, DAG) && isSignExtended(N1, DAG);
   5486   }
   5487   return false;
   5488 }
   5489 
   5490 static bool isAddSubZExt(SDNode *N, SelectionDAG &DAG) {
   5491   unsigned Opcode = N->getOpcode();
   5492   if (Opcode == ISD::ADD || Opcode == ISD::SUB) {
   5493     SDNode *N0 = N->getOperand(0).getNode();
   5494     SDNode *N1 = N->getOperand(1).getNode();
   5495     return N0->hasOneUse() && N1->hasOneUse() &&
   5496       isZeroExtended(N0, DAG) && isZeroExtended(N1, DAG);
   5497   }
   5498   return false;
   5499 }
   5500 
   5501 static SDValue LowerMUL(SDValue Op, SelectionDAG &DAG) {
   5502   // Multiplications are only custom-lowered for 128-bit vectors so that
   5503   // VMULL can be detected.  Otherwise v2i64 multiplications are not legal.
   5504   EVT VT = Op.getValueType();
   5505   assert(VT.is128BitVector() && VT.isInteger() &&
   5506          "unexpected type for custom-lowering ISD::MUL");
   5507   SDNode *N0 = Op.getOperand(0).getNode();
   5508   SDNode *N1 = Op.getOperand(1).getNode();
   5509   unsigned NewOpc = 0;
   5510   bool isMLA = false;
   5511   bool isN0SExt = isSignExtended(N0, DAG);
   5512   bool isN1SExt = isSignExtended(N1, DAG);
   5513   if (isN0SExt && isN1SExt)
   5514     NewOpc = ARMISD::VMULLs;
   5515   else {
   5516     bool isN0ZExt = isZeroExtended(N0, DAG);
   5517     bool isN1ZExt = isZeroExtended(N1, DAG);
   5518     if (isN0ZExt && isN1ZExt)
   5519       NewOpc = ARMISD::VMULLu;
   5520     else if (isN1SExt || isN1ZExt) {
   5521       // Look for (s/zext A + s/zext B) * (s/zext C). We want to turn these
   5522       // into (s/zext A * s/zext C) + (s/zext B * s/zext C)
   5523       if (isN1SExt && isAddSubSExt(N0, DAG)) {
   5524         NewOpc = ARMISD::VMULLs;
   5525         isMLA = true;
   5526       } else if (isN1ZExt && isAddSubZExt(N0, DAG)) {
   5527         NewOpc = ARMISD::VMULLu;
   5528         isMLA = true;
   5529       } else if (isN0ZExt && isAddSubZExt(N1, DAG)) {
   5530         std::swap(N0, N1);
   5531         NewOpc = ARMISD::VMULLu;
   5532         isMLA = true;
   5533       }
   5534     }
   5535 
   5536     if (!NewOpc) {
   5537       if (VT == MVT::v2i64)
   5538         // Fall through to expand this.  It is not legal.
   5539         return SDValue();
   5540       else
   5541         // Other vector multiplications are legal.
   5542         return Op;
   5543     }
   5544   }
   5545 
   5546   // Legalize to a VMULL instruction.
   5547   SDLoc DL(Op);
   5548   SDValue Op0;
   5549   SDValue Op1 = SkipExtensionForVMULL(N1, DAG);
   5550   if (!isMLA) {
   5551     Op0 = SkipExtensionForVMULL(N0, DAG);
   5552     assert(Op0.getValueType().is64BitVector() &&
   5553            Op1.getValueType().is64BitVector() &&
   5554            "unexpected types for extended operands to VMULL");
   5555     return DAG.getNode(NewOpc, DL, VT, Op0, Op1);
   5556   }
   5557 
   5558   // Optimizing (zext A + zext B) * C, to (VMULL A, C) + (VMULL B, C) during
   5559   // isel lowering to take advantage of no-stall back to back vmul + vmla.
   5560   //   vmull q0, d4, d6
   5561   //   vmlal q0, d5, d6
   5562   // is faster than
   5563   //   vaddl q0, d4, d5
   5564   //   vmovl q1, d6
   5565   //   vmul  q0, q0, q1
   5566   SDValue N00 = SkipExtensionForVMULL(N0->getOperand(0).getNode(), DAG);
   5567   SDValue N01 = SkipExtensionForVMULL(N0->getOperand(1).getNode(), DAG);
   5568   EVT Op1VT = Op1.getValueType();
   5569   return DAG.getNode(N0->getOpcode(), DL, VT,
   5570                      DAG.getNode(NewOpc, DL, VT,
   5571                                DAG.getNode(ISD::BITCAST, DL, Op1VT, N00), Op1),
   5572                      DAG.getNode(NewOpc, DL, VT,
   5573                                DAG.getNode(ISD::BITCAST, DL, Op1VT, N01), Op1));
   5574 }
   5575 
   5576 static SDValue
   5577 LowerSDIV_v4i8(SDValue X, SDValue Y, SDLoc dl, SelectionDAG &DAG) {
   5578   // Convert to float
   5579   // float4 xf = vcvt_f32_s32(vmovl_s16(a.lo));
   5580   // float4 yf = vcvt_f32_s32(vmovl_s16(b.lo));
   5581   X = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, X);
   5582   Y = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, Y);
   5583   X = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, X);
   5584   Y = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, Y);
   5585   // Get reciprocal estimate.
   5586   // float4 recip = vrecpeq_f32(yf);
   5587   Y = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
   5588                    DAG.getConstant(Intrinsic::arm_neon_vrecpe, MVT::i32), Y);
   5589   // Because char has a smaller range than uchar, we can actually get away
   5590   // without any newton steps.  This requires that we use a weird bias
   5591   // of 0xb000, however (again, this has been exhaustively tested).
   5592   // float4 result = as_float4(as_int4(xf*recip) + 0xb000);
   5593   X = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, X, Y);
   5594   X = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, X);
   5595   Y = DAG.getConstant(0xb000, MVT::i32);
   5596   Y = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Y, Y, Y, Y);
   5597   X = DAG.getNode(ISD::ADD, dl, MVT::v4i32, X, Y);
   5598   X = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, X);
   5599   // Convert back to short.
   5600   X = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::v4i32, X);
   5601   X = DAG.getNode(ISD::TRUNCATE, dl, MVT::v4i16, X);
   5602   return X;
   5603 }
   5604 
   5605 static SDValue
   5606 LowerSDIV_v4i16(SDValue N0, SDValue N1, SDLoc dl, SelectionDAG &DAG) {
   5607   SDValue N2;
   5608   // Convert to float.
   5609   // float4 yf = vcvt_f32_s32(vmovl_s16(y));
   5610   // float4 xf = vcvt_f32_s32(vmovl_s16(x));
   5611   N0 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, N0);
   5612   N1 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, N1);
   5613   N0 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N0);
   5614   N1 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N1);
   5615 
   5616   // Use reciprocal estimate and one refinement step.
   5617   // float4 recip = vrecpeq_f32(yf);
   5618   // recip *= vrecpsq_f32(yf, recip);
   5619   N2 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
   5620                    DAG.getConstant(Intrinsic::arm_neon_vrecpe, MVT::i32), N1);
   5621   N1 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
   5622                    DAG.getConstant(Intrinsic::arm_neon_vrecps, MVT::i32),
   5623                    N1, N2);
   5624   N2 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N1, N2);
   5625   // Because short has a smaller range than ushort, we can actually get away
   5626   // with only a single newton step.  This requires that we use a weird bias
   5627   // of 89, however (again, this has been exhaustively tested).
   5628   // float4 result = as_float4(as_int4(xf*recip) + 0x89);
   5629   N0 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N0, N2);
   5630   N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, N0);
   5631   N1 = DAG.getConstant(0x89, MVT::i32);
   5632   N1 = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, N1, N1, N1, N1);
   5633   N0 = DAG.getNode(ISD::ADD, dl, MVT::v4i32, N0, N1);
   5634   N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, N0);
   5635   // Convert back to integer and return.
   5636   // return vmovn_s32(vcvt_s32_f32(result));
   5637   N0 = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::v4i32, N0);
   5638   N0 = DAG.getNode(ISD::TRUNCATE, dl, MVT::v4i16, N0);
   5639   return N0;
   5640 }
   5641 
   5642 static SDValue LowerSDIV(SDValue Op, SelectionDAG &DAG) {
   5643   EVT VT = Op.getValueType();
   5644   assert((VT == MVT::v4i16 || VT == MVT::v8i8) &&
   5645          "unexpected type for custom-lowering ISD::SDIV");
   5646 
   5647   SDLoc dl(Op);
   5648   SDValue N0 = Op.getOperand(0);
   5649   SDValue N1 = Op.getOperand(1);
   5650   SDValue N2, N3;
   5651 
   5652   if (VT == MVT::v8i8) {
   5653     N0 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v8i16, N0);
   5654     N1 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v8i16, N1);
   5655 
   5656     N2 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0,
   5657                      DAG.getIntPtrConstant(4));
   5658     N3 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1,
   5659                      DAG.getIntPtrConstant(4));
   5660     N0 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0,
   5661                      DAG.getIntPtrConstant(0));
   5662     N1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1,
   5663                      DAG.getIntPtrConstant(0));
   5664 
   5665     N0 = LowerSDIV_v4i8(N0, N1, dl, DAG); // v4i16
   5666     N2 = LowerSDIV_v4i8(N2, N3, dl, DAG); // v4i16
   5667 
   5668     N0 = DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v8i16, N0, N2);
   5669     N0 = LowerCONCAT_VECTORS(N0, DAG);
   5670 
   5671     N0 = DAG.getNode(ISD::TRUNCATE, dl, MVT::v8i8, N0);
   5672     return N0;
   5673   }
   5674   return LowerSDIV_v4i16(N0, N1, dl, DAG);
   5675 }
   5676 
   5677 static SDValue LowerUDIV(SDValue Op, SelectionDAG &DAG) {
   5678   EVT VT = Op.getValueType();
   5679   assert((VT == MVT::v4i16 || VT == MVT::v8i8) &&
   5680          "unexpected type for custom-lowering ISD::UDIV");
   5681 
   5682   SDLoc dl(Op);
   5683   SDValue N0 = Op.getOperand(0);
   5684   SDValue N1 = Op.getOperand(1);
   5685   SDValue N2, N3;
   5686 
   5687   if (VT == MVT::v8i8) {
   5688     N0 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v8i16, N0);
   5689     N1 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v8i16, N1);
   5690 
   5691     N2 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0,
   5692                      DAG.getIntPtrConstant(4));
   5693     N3 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1,
   5694                      DAG.getIntPtrConstant(4));
   5695     N0 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0,
   5696                      DAG.getIntPtrConstant(0));
   5697     N1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1,
   5698                      DAG.getIntPtrConstant(0));
   5699 
   5700     N0 = LowerSDIV_v4i16(N0, N1, dl, DAG); // v4i16
   5701     N2 = LowerSDIV_v4i16(N2, N3, dl, DAG); // v4i16
   5702 
   5703     N0 = DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v8i16, N0, N2);
   5704     N0 = LowerCONCAT_VECTORS(N0, DAG);
   5705 
   5706     N0 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v8i8,
   5707                      DAG.getConstant(Intrinsic::arm_neon_vqmovnsu, MVT::i32),
   5708                      N0);
   5709     return N0;
   5710   }
   5711 
   5712   // v4i16 sdiv ... Convert to float.
   5713   // float4 yf = vcvt_f32_s32(vmovl_u16(y));
   5714   // float4 xf = vcvt_f32_s32(vmovl_u16(x));
   5715   N0 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v4i32, N0);
   5716   N1 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v4i32, N1);
   5717   N0 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N0);
   5718   SDValue BN1 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N1);
   5719 
   5720   // Use reciprocal estimate and two refinement steps.
   5721   // float4 recip = vrecpeq_f32(yf);
   5722   // recip *= vrecpsq_f32(yf, recip);
   5723   // recip *= vrecpsq_f32(yf, recip);
   5724   N2 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
   5725                    DAG.getConstant(Intrinsic::arm_neon_vrecpe, MVT::i32), BN1);
   5726   N1 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
   5727                    DAG.getConstant(Intrinsic::arm_neon_vrecps, MVT::i32),
   5728                    BN1, N2);
   5729   N2 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N1, N2);
   5730   N1 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
   5731                    DAG.getConstant(Intrinsic::arm_neon_vrecps, MVT::i32),
   5732                    BN1, N2);
   5733   N2 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N1, N2);
   5734   // Simply multiplying by the reciprocal estimate can leave us a few ulps
   5735   // too low, so we add 2 ulps (exhaustive testing shows that this is enough,
   5736   // and that it will never cause us to return an answer too large).
   5737   // float4 result = as_float4(as_int4(xf*recip) + 2);
   5738   N0 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N0, N2);
   5739   N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, N0);
   5740   N1 = DAG.getConstant(2, MVT::i32);
   5741   N1 = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, N1, N1, N1, N1);
   5742   N0 = DAG.getNode(ISD::ADD, dl, MVT::v4i32, N0, N1);
   5743   N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, N0);
   5744   // Convert back to integer and return.
   5745   // return vmovn_u32(vcvt_s32_f32(result));
   5746   N0 = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::v4i32, N0);
   5747   N0 = DAG.getNode(ISD::TRUNCATE, dl, MVT::v4i16, N0);
   5748   return N0;
   5749 }
   5750 
   5751 static SDValue LowerADDC_ADDE_SUBC_SUBE(SDValue Op, SelectionDAG &DAG) {
   5752   EVT VT = Op.getNode()->getValueType(0);
   5753   SDVTList VTs = DAG.getVTList(VT, MVT::i32);
   5754 
   5755   unsigned Opc;
   5756   bool ExtraOp = false;
   5757   switch (Op.getOpcode()) {
   5758   default: llvm_unreachable("Invalid code");
   5759   case ISD::ADDC: Opc = ARMISD::ADDC; break;
   5760   case ISD::ADDE: Opc = ARMISD::ADDE; ExtraOp = true; break;
   5761   case ISD::SUBC: Opc = ARMISD::SUBC; break;
   5762   case ISD::SUBE: Opc = ARMISD::SUBE; ExtraOp = true; break;
   5763   }
   5764 
   5765   if (!ExtraOp)
   5766     return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0),
   5767                        Op.getOperand(1));
   5768   return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0),
   5769                      Op.getOperand(1), Op.getOperand(2));
   5770 }
   5771 
   5772 static SDValue LowerAtomicLoadStore(SDValue Op, SelectionDAG &DAG) {
   5773   // Monotonic load/store is legal for all targets
   5774   if (cast<AtomicSDNode>(Op)->getOrdering() <= Monotonic)
   5775     return Op;
   5776 
   5777   // Aquire/Release load/store is not legal for targets without a
   5778   // dmb or equivalent available.
   5779   return SDValue();
   5780 }
   5781 
   5782 static void
   5783 ReplaceATOMIC_OP_64(SDNode *Node, SmallVectorImpl<SDValue>& Results,
   5784                     SelectionDAG &DAG, unsigned NewOp) {
   5785   SDLoc dl(Node);
   5786   assert (Node->getValueType(0) == MVT::i64 &&
   5787           "Only know how to expand i64 atomics");
   5788 
   5789   SmallVector<SDValue, 6> Ops;
   5790   Ops.push_back(Node->getOperand(0)); // Chain
   5791   Ops.push_back(Node->getOperand(1)); // Ptr
   5792   // Low part of Val1
   5793   Ops.push_back(DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
   5794                             Node->getOperand(2), DAG.getIntPtrConstant(0)));
   5795   // High part of Val1
   5796   Ops.push_back(DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
   5797                             Node->getOperand(2), DAG.getIntPtrConstant(1)));
   5798   if (NewOp == ARMISD::ATOMCMPXCHG64_DAG) {
   5799     // High part of Val1
   5800     Ops.push_back(DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
   5801                               Node->getOperand(3), DAG.getIntPtrConstant(0)));
   5802     // High part of Val2
   5803     Ops.push_back(DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
   5804                               Node->getOperand(3), DAG.getIntPtrConstant(1)));
   5805   }
   5806   SDVTList Tys = DAG.getVTList(MVT::i32, MVT::i32, MVT::Other);
   5807   SDValue Result =
   5808     DAG.getMemIntrinsicNode(NewOp, dl, Tys, Ops.data(), Ops.size(), MVT::i64,
   5809                             cast<MemSDNode>(Node)->getMemOperand());
   5810   SDValue OpsF[] = { Result.getValue(0), Result.getValue(1) };
   5811   Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, OpsF, 2));
   5812   Results.push_back(Result.getValue(2));
   5813 }
   5814 
   5815 static void ReplaceREADCYCLECOUNTER(SDNode *N,
   5816                                     SmallVectorImpl<SDValue> &Results,
   5817                                     SelectionDAG &DAG,
   5818                                     const ARMSubtarget *Subtarget) {
   5819   SDLoc DL(N);
   5820   SDValue Cycles32, OutChain;
   5821 
   5822   if (Subtarget->hasPerfMon()) {
   5823     // Under Power Management extensions, the cycle-count is:
   5824     //    mrc p15, #0, <Rt>, c9, c13, #0
   5825     SDValue Ops[] = { N->getOperand(0), // Chain
   5826                       DAG.getConstant(Intrinsic::arm_mrc, MVT::i32),
   5827                       DAG.getConstant(15, MVT::i32),
   5828                       DAG.getConstant(0, MVT::i32),
   5829                       DAG.getConstant(9, MVT::i32),
   5830                       DAG.getConstant(13, MVT::i32),
   5831                       DAG.getConstant(0, MVT::i32)
   5832     };
   5833 
   5834     Cycles32 = DAG.getNode(ISD::INTRINSIC_W_CHAIN, DL,
   5835                            DAG.getVTList(MVT::i32, MVT::Other), &Ops[0],
   5836                            array_lengthof(Ops));
   5837     OutChain = Cycles32.getValue(1);
   5838   } else {
   5839     // Intrinsic is defined to return 0 on unsupported platforms. Technically
   5840     // there are older ARM CPUs that have implementation-specific ways of
   5841     // obtaining this information (FIXME!).
   5842     Cycles32 = DAG.getConstant(0, MVT::i32);
   5843     OutChain = DAG.getEntryNode();
   5844   }
   5845 
   5846 
   5847   SDValue Cycles64 = DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64,
   5848                                  Cycles32, DAG.getConstant(0, MVT::i32));
   5849   Results.push_back(Cycles64);
   5850   Results.push_back(OutChain);
   5851 }
   5852 
   5853 SDValue ARMTargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
   5854   switch (Op.getOpcode()) {
   5855   default: llvm_unreachable("Don't know how to custom lower this!");
   5856   case ISD::ConstantPool:  return LowerConstantPool(Op, DAG);
   5857   case ISD::BlockAddress:  return LowerBlockAddress(Op, DAG);
   5858   case ISD::GlobalAddress:
   5859     return Subtarget->isTargetDarwin() ? LowerGlobalAddressDarwin(Op, DAG) :
   5860       LowerGlobalAddressELF(Op, DAG);
   5861   case ISD::GlobalTLSAddress: return LowerGlobalTLSAddress(Op, DAG);
   5862   case ISD::SELECT:        return LowerSELECT(Op, DAG);
   5863   case ISD::SELECT_CC:     return LowerSELECT_CC(Op, DAG);
   5864   case ISD::BR_CC:         return LowerBR_CC(Op, DAG);
   5865   case ISD::BR_JT:         return LowerBR_JT(Op, DAG);
   5866   case ISD::VASTART:       return LowerVASTART(Op, DAG);
   5867   case ISD::ATOMIC_FENCE:  return LowerATOMIC_FENCE(Op, DAG, Subtarget);
   5868   case ISD::PREFETCH:      return LowerPREFETCH(Op, DAG, Subtarget);
   5869   case ISD::SINT_TO_FP:
   5870   case ISD::UINT_TO_FP:    return LowerINT_TO_FP(Op, DAG);
   5871   case ISD::FP_TO_SINT:
   5872   case ISD::FP_TO_UINT:    return LowerFP_TO_INT(Op, DAG);
   5873   case ISD::FCOPYSIGN:     return LowerFCOPYSIGN(Op, DAG);
   5874   case ISD::RETURNADDR:    return LowerRETURNADDR(Op, DAG);
   5875   case ISD::FRAMEADDR:     return LowerFRAMEADDR(Op, DAG);
   5876   case ISD::GLOBAL_OFFSET_TABLE: return LowerGLOBAL_OFFSET_TABLE(Op, DAG);
   5877   case ISD::EH_SJLJ_SETJMP: return LowerEH_SJLJ_SETJMP(Op, DAG);
   5878   case ISD::EH_SJLJ_LONGJMP: return LowerEH_SJLJ_LONGJMP(Op, DAG);
   5879   case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG,
   5880                                                                Subtarget);
   5881   case ISD::BITCAST:       return ExpandBITCAST(Op.getNode(), DAG);
   5882   case ISD::SHL:
   5883   case ISD::SRL:
   5884   case ISD::SRA:           return LowerShift(Op.getNode(), DAG, Subtarget);
   5885   case ISD::SHL_PARTS:     return LowerShiftLeftParts(Op, DAG);
   5886   case ISD::SRL_PARTS:
   5887   case ISD::SRA_PARTS:     return LowerShiftRightParts(Op, DAG);
   5888   case ISD::CTTZ:          return LowerCTTZ(Op.getNode(), DAG, Subtarget);
   5889   case ISD::CTPOP:         return LowerCTPOP(Op.getNode(), DAG, Subtarget);
   5890   case ISD::SETCC:         return LowerVSETCC(Op, DAG);
   5891   case ISD::ConstantFP:    return LowerConstantFP(Op, DAG, Subtarget);
   5892   case ISD::BUILD_VECTOR:  return LowerBUILD_VECTOR(Op, DAG, Subtarget);
   5893   case ISD::VECTOR_SHUFFLE: return LowerVECTOR_SHUFFLE(Op, DAG);
   5894   case ISD::INSERT_VECTOR_ELT: return LowerINSERT_VECTOR_ELT(Op, DAG);
   5895   case ISD::EXTRACT_VECTOR_ELT: return LowerEXTRACT_VECTOR_ELT(Op, DAG);
   5896   case ISD::CONCAT_VECTORS: return LowerCONCAT_VECTORS(Op, DAG);
   5897   case ISD::FLT_ROUNDS_:   return LowerFLT_ROUNDS_(Op, DAG);
   5898   case ISD::MUL:           return LowerMUL(Op, DAG);
   5899   case ISD::SDIV:          return LowerSDIV(Op, DAG);
   5900   case ISD::UDIV:          return LowerUDIV(Op, DAG);
   5901   case ISD::ADDC:
   5902   case ISD::ADDE:
   5903   case ISD::SUBC:
   5904   case ISD::SUBE:          return LowerADDC_ADDE_SUBC_SUBE(Op, DAG);
   5905   case ISD::ATOMIC_LOAD:
   5906   case ISD::ATOMIC_STORE:  return LowerAtomicLoadStore(Op, DAG);
   5907   case ISD::SDIVREM:
   5908   case ISD::UDIVREM:       return LowerDivRem(Op, DAG);
   5909   }
   5910 }
   5911 
   5912 /// ReplaceNodeResults - Replace the results of node with an illegal result
   5913 /// type with new values built out of custom code.
   5914 void ARMTargetLowering::ReplaceNodeResults(SDNode *N,
   5915                                            SmallVectorImpl<SDValue>&Results,
   5916                                            SelectionDAG &DAG) const {
   5917   SDValue Res;
   5918   switch (N->getOpcode()) {
   5919   default:
   5920     llvm_unreachable("Don't know how to custom expand this!");
   5921   case ISD::BITCAST:
   5922     Res = ExpandBITCAST(N, DAG);
   5923     break;
   5924   case ISD::SIGN_EXTEND:
   5925   case ISD::ZERO_EXTEND:
   5926     Res = ExpandVectorExtension(N, DAG);
   5927     break;
   5928   case ISD::SRL:
   5929   case ISD::SRA:
   5930     Res = Expand64BitShift(N, DAG, Subtarget);
   5931     break;
   5932   case ISD::READCYCLECOUNTER:
   5933     ReplaceREADCYCLECOUNTER(N, Results, DAG, Subtarget);
   5934     return;
   5935   case ISD::ATOMIC_LOAD_ADD:
   5936     ReplaceATOMIC_OP_64(N, Results, DAG, ARMISD::ATOMADD64_DAG);
   5937     return;
   5938   case ISD::ATOMIC_LOAD_AND:
   5939     ReplaceATOMIC_OP_64(N, Results, DAG, ARMISD::ATOMAND64_DAG);
   5940     return;
   5941   case ISD::ATOMIC_LOAD_NAND:
   5942     ReplaceATOMIC_OP_64(N, Results, DAG, ARMISD::ATOMNAND64_DAG);
   5943     return;
   5944   case ISD::ATOMIC_LOAD_OR:
   5945     ReplaceATOMIC_OP_64(N, Results, DAG, ARMISD::ATOMOR64_DAG);
   5946     return;
   5947   case ISD::ATOMIC_LOAD_SUB:
   5948     ReplaceATOMIC_OP_64(N, Results, DAG, ARMISD::ATOMSUB64_DAG);
   5949     return;
   5950   case ISD::ATOMIC_LOAD_XOR:
   5951     ReplaceATOMIC_OP_64(N, Results, DAG, ARMISD::ATOMXOR64_DAG);
   5952     return;
   5953   case ISD::ATOMIC_SWAP:
   5954     ReplaceATOMIC_OP_64(N, Results, DAG, ARMISD::ATOMSWAP64_DAG);
   5955     return;
   5956   case ISD::ATOMIC_CMP_SWAP:
   5957     ReplaceATOMIC_OP_64(N, Results, DAG, ARMISD::ATOMCMPXCHG64_DAG);
   5958     return;
   5959   case ISD::ATOMIC_LOAD_MIN:
   5960     ReplaceATOMIC_OP_64(N, Results, DAG, ARMISD::ATOMMIN64_DAG);
   5961     return;
   5962   case ISD::ATOMIC_LOAD_UMIN:
   5963     ReplaceATOMIC_OP_64(N, Results, DAG, ARMISD::ATOMUMIN64_DAG);
   5964     return;
   5965   case ISD::ATOMIC_LOAD_MAX:
   5966     ReplaceATOMIC_OP_64(N, Results, DAG, ARMISD::ATOMMAX64_DAG);
   5967     return;
   5968   case ISD::ATOMIC_LOAD_UMAX:
   5969     ReplaceATOMIC_OP_64(N, Results, DAG, ARMISD::ATOMUMAX64_DAG);
   5970     return;
   5971   }
   5972   if (Res.getNode())
   5973     Results.push_back(Res);
   5974 }
   5975 
   5976 //===----------------------------------------------------------------------===//
   5977 //                           ARM Scheduler Hooks
   5978 //===----------------------------------------------------------------------===//
   5979 
   5980 MachineBasicBlock *
   5981 ARMTargetLowering::EmitAtomicCmpSwap(MachineInstr *MI,
   5982                                      MachineBasicBlock *BB,
   5983                                      unsigned Size) const {
   5984   unsigned dest    = MI->getOperand(0).getReg();
   5985   unsigned ptr     = MI->getOperand(1).getReg();
   5986   unsigned oldval  = MI->getOperand(2).getReg();
   5987   unsigned newval  = MI->getOperand(3).getReg();
   5988   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
   5989   DebugLoc dl = MI->getDebugLoc();
   5990   bool isThumb2 = Subtarget->isThumb2();
   5991 
   5992   MachineRegisterInfo &MRI = BB->getParent()->getRegInfo();
   5993   unsigned scratch = MRI.createVirtualRegister(isThumb2 ?
   5994     (const TargetRegisterClass*)&ARM::rGPRRegClass :
   5995     (const TargetRegisterClass*)&ARM::GPRRegClass);
   5996 
   5997   if (isThumb2) {
   5998     MRI.constrainRegClass(dest, &ARM::rGPRRegClass);
   5999     MRI.constrainRegClass(oldval, &ARM::rGPRRegClass);
   6000     MRI.constrainRegClass(newval, &ARM::rGPRRegClass);
   6001   }
   6002 
   6003   unsigned ldrOpc, strOpc;
   6004   switch (Size) {
   6005   default: llvm_unreachable("unsupported size for AtomicCmpSwap!");
   6006   case 1:
   6007     ldrOpc = isThumb2 ? ARM::t2LDREXB : ARM::LDREXB;
   6008     strOpc = isThumb2 ? ARM::t2STREXB : ARM::STREXB;
   6009     break;
   6010   case 2:
   6011     ldrOpc = isThumb2 ? ARM::t2LDREXH : ARM::LDREXH;
   6012     strOpc = isThumb2 ? ARM::t2STREXH : ARM::STREXH;
   6013     break;
   6014   case 4:
   6015     ldrOpc = isThumb2 ? ARM::t2LDREX : ARM::LDREX;
   6016     strOpc = isThumb2 ? ARM::t2STREX : ARM::STREX;
   6017     break;
   6018   }
   6019 
   6020   MachineFunction *MF = BB->getParent();
   6021   const BasicBlock *LLVM_BB = BB->getBasicBlock();
   6022   MachineFunction::iterator It = BB;
   6023   ++It; // insert the new blocks after the current block
   6024 
   6025   MachineBasicBlock *loop1MBB = MF->CreateMachineBasicBlock(LLVM_BB);
   6026   MachineBasicBlock *loop2MBB = MF->CreateMachineBasicBlock(LLVM_BB);
   6027   MachineBasicBlock *exitMBB = MF->CreateMachineBasicBlock(LLVM_BB);
   6028   MF->insert(It, loop1MBB);
   6029   MF->insert(It, loop2MBB);
   6030   MF->insert(It, exitMBB);
   6031 
   6032   // Transfer the remainder of BB and its successor edges to exitMBB.
   6033   exitMBB->splice(exitMBB->begin(), BB,
   6034                   llvm::next(MachineBasicBlock::iterator(MI)),
   6035                   BB->end());
   6036   exitMBB->transferSuccessorsAndUpdatePHIs(BB);
   6037 
   6038   //  thisMBB:
   6039   //   ...
   6040   //   fallthrough --> loop1MBB
   6041   BB->addSuccessor(loop1MBB);
   6042 
   6043   // loop1MBB:
   6044   //   ldrex dest, [ptr]
   6045   //   cmp dest, oldval
   6046   //   bne exitMBB
   6047   BB = loop1MBB;
   6048   MachineInstrBuilder MIB = BuildMI(BB, dl, TII->get(ldrOpc), dest).addReg(ptr);
   6049   if (ldrOpc == ARM::t2LDREX)
   6050     MIB.addImm(0);
   6051   AddDefaultPred(MIB);
   6052   AddDefaultPred(BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPrr : ARM::CMPrr))
   6053                  .addReg(dest).addReg(oldval));
   6054   BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc))
   6055     .addMBB(exitMBB).addImm(ARMCC::NE).addReg(ARM::CPSR);
   6056   BB->addSuccessor(loop2MBB);
   6057   BB->addSuccessor(exitMBB);
   6058 
   6059   // loop2MBB:
   6060   //   strex scratch, newval, [ptr]
   6061   //   cmp scratch, #0
   6062   //   bne loop1MBB
   6063   BB = loop2MBB;
   6064   MIB = BuildMI(BB, dl, TII->get(strOpc), scratch).addReg(newval).addReg(ptr);
   6065   if (strOpc == ARM::t2STREX)
   6066     MIB.addImm(0);
   6067   AddDefaultPred(MIB);
   6068   AddDefaultPred(BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri))
   6069                  .addReg(scratch).addImm(0));
   6070   BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc))
   6071     .addMBB(loop1MBB).addImm(ARMCC::NE).addReg(ARM::CPSR);
   6072   BB->addSuccessor(loop1MBB);
   6073   BB->addSuccessor(exitMBB);
   6074 
   6075   //  exitMBB:
   6076   //   ...
   6077   BB = exitMBB;
   6078 
   6079   MI->eraseFromParent();   // The instruction is gone now.
   6080 
   6081   return BB;
   6082 }
   6083 
   6084 MachineBasicBlock *
   6085 ARMTargetLowering::EmitAtomicBinary(MachineInstr *MI, MachineBasicBlock *BB,
   6086                                     unsigned Size, unsigned BinOpcode) const {
   6087   // This also handles ATOMIC_SWAP, indicated by BinOpcode==0.
   6088   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
   6089 
   6090   const BasicBlock *LLVM_BB = BB->getBasicBlock();
   6091   MachineFunction *MF = BB->getParent();
   6092   MachineFunction::iterator It = BB;
   6093   ++It;
   6094 
   6095   unsigned dest = MI->getOperand(0).getReg();
   6096   unsigned ptr = MI->getOperand(1).getReg();
   6097   unsigned incr = MI->getOperand(2).getReg();
   6098   DebugLoc dl = MI->getDebugLoc();
   6099   bool isThumb2 = Subtarget->isThumb2();
   6100 
   6101   MachineRegisterInfo &MRI = BB->getParent()->getRegInfo();
   6102   if (isThumb2) {
   6103     MRI.constrainRegClass(dest, &ARM::rGPRRegClass);
   6104     MRI.constrainRegClass(ptr, &ARM::rGPRRegClass);
   6105   }
   6106 
   6107   unsigned ldrOpc, strOpc;
   6108   switch (Size) {
   6109   default: llvm_unreachable("unsupported size for AtomicCmpSwap!");
   6110   case 1:
   6111     ldrOpc = isThumb2 ? ARM::t2LDREXB : ARM::LDREXB;
   6112     strOpc = isThumb2 ? ARM::t2STREXB : ARM::STREXB;
   6113     break;
   6114   case 2:
   6115     ldrOpc = isThumb2 ? ARM::t2LDREXH : ARM::LDREXH;
   6116     strOpc = isThumb2 ? ARM::t2STREXH : ARM::STREXH;
   6117     break;
   6118   case 4:
   6119     ldrOpc = isThumb2 ? ARM::t2LDREX : ARM::LDREX;
   6120     strOpc = isThumb2 ? ARM::t2STREX : ARM::STREX;
   6121     break;
   6122   }
   6123 
   6124   MachineBasicBlock *loopMBB = MF->CreateMachineBasicBlock(LLVM_BB);
   6125   MachineBasicBlock *exitMBB = MF->CreateMachineBasicBlock(LLVM_BB);
   6126   MF->insert(It, loopMBB);
   6127   MF->insert(It, exitMBB);
   6128 
   6129   // Transfer the remainder of BB and its successor edges to exitMBB.
   6130   exitMBB->splice(exitMBB->begin(), BB,
   6131                   llvm::next(MachineBasicBlock::iterator(MI)),
   6132                   BB->end());
   6133   exitMBB->transferSuccessorsAndUpdatePHIs(BB);
   6134 
   6135   const TargetRegisterClass *TRC = isThumb2 ?
   6136     (const TargetRegisterClass*)&ARM::rGPRRegClass :
   6137     (const TargetRegisterClass*)&ARM::GPRRegClass;
   6138   unsigned scratch = MRI.createVirtualRegister(TRC);
   6139   unsigned scratch2 = (!BinOpcode) ? incr : MRI.createVirtualRegister(TRC);
   6140 
   6141   //  thisMBB:
   6142   //   ...
   6143   //   fallthrough --> loopMBB
   6144   BB->addSuccessor(loopMBB);
   6145 
   6146   //  loopMBB:
   6147   //   ldrex dest, ptr
   6148   //   <binop> scratch2, dest, incr
   6149   //   strex scratch, scratch2, ptr
   6150   //   cmp scratch, #0
   6151   //   bne- loopMBB
   6152   //   fallthrough --> exitMBB
   6153   BB = loopMBB;
   6154   MachineInstrBuilder MIB = BuildMI(BB, dl, TII->get(ldrOpc), dest).addReg(ptr);
   6155   if (ldrOpc == ARM::t2LDREX)
   6156     MIB.addImm(0);
   6157   AddDefaultPred(MIB);
   6158   if (BinOpcode) {
   6159     // operand order needs to go the other way for NAND
   6160     if (BinOpcode == ARM::BICrr || BinOpcode == ARM::t2BICrr)
   6161       AddDefaultPred(BuildMI(BB, dl, TII->get(BinOpcode), scratch2).
   6162                      addReg(incr).addReg(dest)).addReg(0);
   6163     else
   6164       AddDefaultPred(BuildMI(BB, dl, TII->get(BinOpcode), scratch2).
   6165                      addReg(dest).addReg(incr)).addReg(0);
   6166   }
   6167 
   6168   MIB = BuildMI(BB, dl, TII->get(strOpc), scratch).addReg(scratch2).addReg(ptr);
   6169   if (strOpc == ARM::t2STREX)
   6170     MIB.addImm(0);
   6171   AddDefaultPred(MIB);
   6172   AddDefaultPred(BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri))
   6173                  .addReg(scratch).addImm(0));
   6174   BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc))
   6175     .addMBB(loopMBB).addImm(ARMCC::NE).addReg(ARM::CPSR);
   6176 
   6177   BB->addSuccessor(loopMBB);
   6178   BB->addSuccessor(exitMBB);
   6179 
   6180   //  exitMBB:
   6181   //   ...
   6182   BB = exitMBB;
   6183 
   6184   MI->eraseFromParent();   // The instruction is gone now.
   6185 
   6186   return BB;
   6187 }
   6188 
   6189 MachineBasicBlock *
   6190 ARMTargetLowering::EmitAtomicBinaryMinMax(MachineInstr *MI,
   6191                                           MachineBasicBlock *BB,
   6192                                           unsigned Size,
   6193                                           bool signExtend,
   6194                                           ARMCC::CondCodes Cond) const {
   6195   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
   6196 
   6197   const BasicBlock *LLVM_BB = BB->getBasicBlock();
   6198   MachineFunction *MF = BB->getParent();
   6199   MachineFunction::iterator It = BB;
   6200   ++It;
   6201 
   6202   unsigned dest = MI->getOperand(0).getReg();
   6203   unsigned ptr = MI->getOperand(1).getReg();
   6204   unsigned incr = MI->getOperand(2).getReg();
   6205   unsigned oldval = dest;
   6206   DebugLoc dl = MI->getDebugLoc();
   6207   bool isThumb2 = Subtarget->isThumb2();
   6208 
   6209   MachineRegisterInfo &MRI = BB->getParent()->getRegInfo();
   6210   if (isThumb2) {
   6211     MRI.constrainRegClass(dest, &ARM::rGPRRegClass);
   6212     MRI.constrainRegClass(ptr, &ARM::rGPRRegClass);
   6213   }
   6214 
   6215   unsigned ldrOpc, strOpc, extendOpc;
   6216   switch (Size) {
   6217   default: llvm_unreachable("unsupported size for AtomicCmpSwap!");
   6218   case 1:
   6219     ldrOpc = isThumb2 ? ARM::t2LDREXB : ARM::LDREXB;
   6220     strOpc = isThumb2 ? ARM::t2STREXB : ARM::STREXB;
   6221     extendOpc = isThumb2 ? ARM::t2SXTB : ARM::SXTB;
   6222     break;
   6223   case 2:
   6224     ldrOpc = isThumb2 ? ARM::t2LDREXH : ARM::LDREXH;
   6225     strOpc = isThumb2 ? ARM::t2STREXH : ARM::STREXH;
   6226     extendOpc = isThumb2 ? ARM::t2SXTH : ARM::SXTH;
   6227     break;
   6228   case 4:
   6229     ldrOpc = isThumb2 ? ARM::t2LDREX : ARM::LDREX;
   6230     strOpc = isThumb2 ? ARM::t2STREX : ARM::STREX;
   6231     extendOpc = 0;
   6232     break;
   6233   }
   6234 
   6235   MachineBasicBlock *loopMBB = MF->CreateMachineBasicBlock(LLVM_BB);
   6236   MachineBasicBlock *exitMBB = MF->CreateMachineBasicBlock(LLVM_BB);
   6237   MF->insert(It, loopMBB);
   6238   MF->insert(It, exitMBB);
   6239 
   6240   // Transfer the remainder of BB and its successor edges to exitMBB.
   6241   exitMBB->splice(exitMBB->begin(), BB,
   6242                   llvm::next(MachineBasicBlock::iterator(MI)),
   6243                   BB->end());
   6244   exitMBB->transferSuccessorsAndUpdatePHIs(BB);
   6245 
   6246   const TargetRegisterClass *TRC = isThumb2 ?
   6247     (const TargetRegisterClass*)&ARM::rGPRRegClass :
   6248     (const TargetRegisterClass*)&ARM::GPRRegClass;
   6249   unsigned scratch = MRI.createVirtualRegister(TRC);
   6250   unsigned scratch2 = MRI.createVirtualRegister(TRC);
   6251 
   6252   //  thisMBB:
   6253   //   ...
   6254   //   fallthrough --> loopMBB
   6255   BB->addSuccessor(loopMBB);
   6256 
   6257   //  loopMBB:
   6258   //   ldrex dest, ptr
   6259   //   (sign extend dest, if required)
   6260   //   cmp dest, incr
   6261   //   cmov.cond scratch2, incr, dest
   6262   //   strex scratch, scratch2, ptr
   6263   //   cmp scratch, #0
   6264   //   bne- loopMBB
   6265   //   fallthrough --> exitMBB
   6266   BB = loopMBB;
   6267   MachineInstrBuilder MIB = BuildMI(BB, dl, TII->get(ldrOpc), dest).addReg(ptr);
   6268   if (ldrOpc == ARM::t2LDREX)
   6269     MIB.addImm(0);
   6270   AddDefaultPred(MIB);
   6271 
   6272   // Sign extend the value, if necessary.
   6273   if (signExtend && extendOpc) {
   6274     oldval = MRI.createVirtualRegister(&ARM::GPRRegClass);
   6275     AddDefaultPred(BuildMI(BB, dl, TII->get(extendOpc), oldval)
   6276                      .addReg(dest)
   6277                      .addImm(0));
   6278   }
   6279 
   6280   // Build compare and cmov instructions.
   6281   AddDefaultPred(BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPrr : ARM::CMPrr))
   6282                  .addReg(oldval).addReg(incr));
   6283   BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2MOVCCr : ARM::MOVCCr), scratch2)
   6284          .addReg(incr).addReg(oldval).addImm(Cond).addReg(ARM::CPSR);
   6285 
   6286   MIB = BuildMI(BB, dl, TII->get(strOpc), scratch).addReg(scratch2).addReg(ptr);
   6287   if (strOpc == ARM::t2STREX)
   6288     MIB.addImm(0);
   6289   AddDefaultPred(MIB);
   6290   AddDefaultPred(BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri))
   6291                  .addReg(scratch).addImm(0));
   6292   BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc))
   6293     .addMBB(loopMBB).addImm(ARMCC::NE).addReg(ARM::CPSR);
   6294 
   6295   BB->addSuccessor(loopMBB);
   6296   BB->addSuccessor(exitMBB);
   6297 
   6298   //  exitMBB:
   6299   //   ...
   6300   BB = exitMBB;
   6301 
   6302   MI->eraseFromParent();   // The instruction is gone now.
   6303 
   6304   return BB;
   6305 }
   6306 
   6307 MachineBasicBlock *
   6308 ARMTargetLowering::EmitAtomicBinary64(MachineInstr *MI, MachineBasicBlock *BB,
   6309                                       unsigned Op1, unsigned Op2,
   6310                                       bool NeedsCarry, bool IsCmpxchg,
   6311                                       bool IsMinMax, ARMCC::CondCodes CC) const {
   6312   // This also handles ATOMIC_SWAP, indicated by Op1==0.
   6313   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
   6314 
   6315   const BasicBlock *LLVM_BB = BB->getBasicBlock();
   6316   MachineFunction *MF = BB->getParent();
   6317   MachineFunction::iterator It = BB;
   6318   ++It;
   6319 
   6320   unsigned destlo = MI->getOperand(0).getReg();
   6321   unsigned desthi = MI->getOperand(1).getReg();
   6322   unsigned ptr = MI->getOperand(2).getReg();
   6323   unsigned vallo = MI->getOperand(3).getReg();
   6324   unsigned valhi = MI->getOperand(4).getReg();
   6325   DebugLoc dl = MI->getDebugLoc();
   6326   bool isThumb2 = Subtarget->isThumb2();
   6327 
   6328   MachineRegisterInfo &MRI = BB->getParent()->getRegInfo();
   6329   if (isThumb2) {
   6330     MRI.constrainRegClass(destlo, &ARM::rGPRRegClass);
   6331     MRI.constrainRegClass(desthi, &ARM::rGPRRegClass);
   6332     MRI.constrainRegClass(ptr, &ARM::rGPRRegClass);
   6333   }
   6334 
   6335   MachineBasicBlock *loopMBB = MF->CreateMachineBasicBlock(LLVM_BB);
   6336   MachineBasicBlock *contBB = 0, *cont2BB = 0;
   6337   if (IsCmpxchg || IsMinMax)
   6338     contBB = MF->CreateMachineBasicBlock(LLVM_BB);
   6339   if (IsCmpxchg)
   6340     cont2BB = MF->CreateMachineBasicBlock(LLVM_BB);
   6341   MachineBasicBlock *exitMBB = MF->CreateMachineBasicBlock(LLVM_BB);
   6342 
   6343   MF->insert(It, loopMBB);
   6344   if (IsCmpxchg || IsMinMax) MF->insert(It, contBB);
   6345   if (IsCmpxchg) MF->insert(It, cont2BB);
   6346   MF->insert(It, exitMBB);
   6347 
   6348   // Transfer the remainder of BB and its successor edges to exitMBB.
   6349   exitMBB->splice(exitMBB->begin(), BB,
   6350                   llvm::next(MachineBasicBlock::iterator(MI)),
   6351                   BB->end());
   6352   exitMBB->transferSuccessorsAndUpdatePHIs(BB);
   6353 
   6354   const TargetRegisterClass *TRC = isThumb2 ?
   6355     (const TargetRegisterClass*)&ARM::tGPRRegClass :
   6356     (const TargetRegisterClass*)&ARM::GPRRegClass;
   6357   unsigned storesuccess = MRI.createVirtualRegister(TRC);
   6358 
   6359   //  thisMBB:
   6360   //   ...
   6361   //   fallthrough --> loopMBB
   6362   BB->addSuccessor(loopMBB);
   6363 
   6364   //  loopMBB:
   6365   //   ldrexd r2, r3, ptr
   6366   //   <binopa> r0, r2, incr
   6367   //   <binopb> r1, r3, incr
   6368   //   strexd storesuccess, r0, r1, ptr
   6369   //   cmp storesuccess, #0
   6370   //   bne- loopMBB
   6371   //   fallthrough --> exitMBB
   6372   BB = loopMBB;
   6373 
   6374   // Load
   6375   if (isThumb2) {
   6376     AddDefaultPred(BuildMI(BB, dl, TII->get(ARM::t2LDREXD))
   6377                    .addReg(destlo, RegState::Define)
   6378                    .addReg(desthi, RegState::Define)
   6379                    .addReg(ptr));
   6380   } else {
   6381     unsigned GPRPair0 = MRI.createVirtualRegister(&ARM::GPRPairRegClass);
   6382     AddDefaultPred(BuildMI(BB, dl, TII->get(ARM::LDREXD))
   6383                    .addReg(GPRPair0, RegState::Define).addReg(ptr));
   6384     // Copy r2/r3 into dest.  (This copy will normally be coalesced.)
   6385     BuildMI(BB, dl, TII->get(TargetOpcode::COPY), destlo)
   6386       .addReg(GPRPair0, 0, ARM::gsub_0);
   6387     BuildMI(BB, dl, TII->get(TargetOpcode::COPY), desthi)
   6388       .addReg(GPRPair0, 0, ARM::gsub_1);
   6389   }
   6390 
   6391   unsigned StoreLo, StoreHi;
   6392   if (IsCmpxchg) {
   6393     // Add early exit
   6394     for (unsigned i = 0; i < 2; i++) {
   6395       AddDefaultPred(BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPrr :
   6396                                                          ARM::CMPrr))
   6397                      .addReg(i == 0 ? destlo : desthi)
   6398                      .addReg(i == 0 ? vallo : valhi));
   6399       BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc))
   6400         .addMBB(exitMBB).addImm(ARMCC::NE).addReg(ARM::CPSR);
   6401       BB->addSuccessor(exitMBB);
   6402       BB->addSuccessor(i == 0 ? contBB : cont2BB);
   6403       BB = (i == 0 ? contBB : cont2BB);
   6404     }
   6405 
   6406     // Copy to physregs for strexd
   6407     StoreLo = MI->getOperand(5).getReg();
   6408     StoreHi = MI->getOperand(6).getReg();
   6409   } else if (Op1) {
   6410     // Perform binary operation
   6411     unsigned tmpRegLo = MRI.createVirtualRegister(TRC);
   6412     AddDefaultPred(BuildMI(BB, dl, TII->get(Op1), tmpRegLo)
   6413                    .addReg(destlo).addReg(vallo))
   6414         .addReg(NeedsCarry ? ARM::CPSR : 0, getDefRegState(NeedsCarry));
   6415     unsigned tmpRegHi = MRI.createVirtualRegister(TRC);
   6416     AddDefaultPred(BuildMI(BB, dl, TII->get(Op2), tmpRegHi)
   6417                    .addReg(desthi).addReg(valhi))
   6418         .addReg(IsMinMax ? ARM::CPSR : 0, getDefRegState(IsMinMax));
   6419 
   6420     StoreLo = tmpRegLo;
   6421     StoreHi = tmpRegHi;
   6422   } else {
   6423     // Copy to physregs for strexd
   6424     StoreLo = vallo;
   6425     StoreHi = valhi;
   6426   }
   6427   if (IsMinMax) {
   6428     // Compare and branch to exit block.
   6429     BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc))
   6430       .addMBB(exitMBB).addImm(CC).addReg(ARM::CPSR);
   6431     BB->addSuccessor(exitMBB);
   6432     BB->addSuccessor(contBB);
   6433     BB = contBB;
   6434     StoreLo = vallo;
   6435     StoreHi = valhi;
   6436   }
   6437 
   6438   // Store
   6439   if (isThumb2) {
   6440     AddDefaultPred(BuildMI(BB, dl, TII->get(ARM::t2STREXD), storesuccess)
   6441                    .addReg(StoreLo).addReg(StoreHi).addReg(ptr));
   6442   } else {
   6443     // Marshal a pair...
   6444     unsigned StorePair = MRI.createVirtualRegister(&ARM::GPRPairRegClass);
   6445     unsigned UndefPair = MRI.createVirtualRegister(&ARM::GPRPairRegClass);
   6446     unsigned r1 = MRI.createVirtualRegister(&ARM::GPRPairRegClass);
   6447     BuildMI(BB, dl, TII->get(TargetOpcode::IMPLICIT_DEF), UndefPair);
   6448     BuildMI(BB, dl, TII->get(TargetOpcode::INSERT_SUBREG), r1)
   6449       .addReg(UndefPair)
   6450       .addReg(StoreLo)
   6451       .addImm(ARM::gsub_0);
   6452     BuildMI(BB, dl, TII->get(TargetOpcode::INSERT_SUBREG), StorePair)
   6453       .addReg(r1)
   6454       .addReg(StoreHi)
   6455       .addImm(ARM::gsub_1);
   6456 
   6457     // ...and store it
   6458     AddDefaultPred(BuildMI(BB, dl, TII->get(ARM::STREXD), storesuccess)
   6459                    .addReg(StorePair).addReg(ptr));
   6460   }
   6461   // Cmp+jump
   6462   AddDefaultPred(BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri))
   6463                  .addReg(storesuccess).addImm(0));
   6464   BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc))
   6465     .addMBB(loopMBB).addImm(ARMCC::NE).addReg(ARM::CPSR);
   6466 
   6467   BB->addSuccessor(loopMBB);
   6468   BB->addSuccessor(exitMBB);
   6469 
   6470   //  exitMBB:
   6471   //   ...
   6472   BB = exitMBB;
   6473 
   6474   MI->eraseFromParent();   // The instruction is gone now.
   6475 
   6476   return BB;
   6477 }
   6478 
   6479 /// SetupEntryBlockForSjLj - Insert code into the entry block that creates and
   6480 /// registers the function context.
   6481 void ARMTargetLowering::
   6482 SetupEntryBlockForSjLj(MachineInstr *MI, MachineBasicBlock *MBB,
   6483                        MachineBasicBlock *DispatchBB, int FI) const {
   6484   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
   6485   DebugLoc dl = MI->getDebugLoc();
   6486   MachineFunction *MF = MBB->getParent();
   6487   MachineRegisterInfo *MRI = &MF->getRegInfo();
   6488   MachineConstantPool *MCP = MF->getConstantPool();
   6489   ARMFunctionInfo *AFI = MF->getInfo<ARMFunctionInfo>();
   6490   const Function *F = MF->getFunction();
   6491 
   6492   bool isThumb = Subtarget->isThumb();
   6493   bool isThumb2 = Subtarget->isThumb2();
   6494 
   6495   unsigned PCLabelId = AFI->createPICLabelUId();
   6496   unsigned PCAdj = (isThumb || isThumb2) ? 4 : 8;
   6497   ARMConstantPoolValue *CPV =
   6498     ARMConstantPoolMBB::Create(F->getContext(), DispatchBB, PCLabelId, PCAdj);
   6499   unsigned CPI = MCP->getConstantPoolIndex(CPV, 4);
   6500 
   6501   const TargetRegisterClass *TRC = isThumb ?
   6502     (const TargetRegisterClass*)&ARM::tGPRRegClass :
   6503     (const TargetRegisterClass*)&ARM::GPRRegClass;
   6504 
   6505   // Grab constant pool and fixed stack memory operands.
   6506   MachineMemOperand *CPMMO =
   6507     MF->getMachineMemOperand(MachinePointerInfo::getConstantPool(),
   6508                              MachineMemOperand::MOLoad, 4, 4);
   6509 
   6510   MachineMemOperand *FIMMOSt =
   6511     MF->getMachineMemOperand(MachinePointerInfo::getFixedStack(FI),
   6512                              MachineMemOperand::MOStore, 4, 4);
   6513 
   6514   // Load the address of the dispatch MBB into the jump buffer.
   6515   if (isThumb2) {
   6516     // Incoming value: jbuf
   6517     //   ldr.n  r5, LCPI1_1
   6518     //   orr    r5, r5, #1
   6519     //   add    r5, pc
   6520     //   str    r5, [$jbuf, #+4] ; &jbuf[1]
   6521     unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
   6522     AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::t2LDRpci), NewVReg1)
   6523                    .addConstantPoolIndex(CPI)
   6524                    .addMemOperand(CPMMO));
   6525     // Set the low bit because of thumb mode.
   6526     unsigned NewVReg2 = MRI->createVirtualRegister(TRC);
   6527     AddDefaultCC(
   6528       AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::t2ORRri), NewVReg2)
   6529                      .addReg(NewVReg1, RegState::Kill)
   6530                      .addImm(0x01)));
   6531     unsigned NewVReg3 = MRI->createVirtualRegister(TRC);
   6532     BuildMI(*MBB, MI, dl, TII->get(ARM::tPICADD), NewVReg3)
   6533       .addReg(NewVReg2, RegState::Kill)
   6534       .addImm(PCLabelId);
   6535     AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::t2STRi12))
   6536                    .addReg(NewVReg3, RegState::Kill)
   6537                    .addFrameIndex(FI)
   6538                    .addImm(36)  // &jbuf[1] :: pc
   6539                    .addMemOperand(FIMMOSt));
   6540   } else if (isThumb) {
   6541     // Incoming value: jbuf
   6542     //   ldr.n  r1, LCPI1_4
   6543     //   add    r1, pc
   6544     //   mov    r2, #1
   6545     //   orrs   r1, r2
   6546     //   add    r2, $jbuf, #+4 ; &jbuf[1]
   6547     //   str    r1, [r2]
   6548     unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
   6549     AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::tLDRpci), NewVReg1)
   6550                    .addConstantPoolIndex(CPI)
   6551                    .addMemOperand(CPMMO));
   6552     unsigned NewVReg2 = MRI->createVirtualRegister(TRC);
   6553     BuildMI(*MBB, MI, dl, TII->get(ARM::tPICADD), NewVReg2)
   6554       .addReg(NewVReg1, RegState::Kill)
   6555       .addImm(PCLabelId);
   6556     // Set the low bit because of thumb mode.
   6557     unsigned NewVReg3 = MRI->createVirtualRegister(TRC);
   6558     AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::tMOVi8), NewVReg3)
   6559                    .addReg(ARM::CPSR, RegState::Define)
   6560                    .addImm(1));
   6561     unsigned NewVReg4 = MRI->createVirtualRegister(TRC);
   6562     AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::tORR), NewVReg4)
   6563                    .addReg(ARM::CPSR, RegState::Define)
   6564                    .addReg(NewVReg2, RegState::Kill)
   6565                    .addReg(NewVReg3, RegState::Kill));
   6566     unsigned NewVReg5 = MRI->createVirtualRegister(TRC);
   6567     AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::tADDrSPi), NewVReg5)
   6568                    .addFrameIndex(FI)
   6569                    .addImm(36)); // &jbuf[1] :: pc
   6570     AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::tSTRi))
   6571                    .addReg(NewVReg4, RegState::Kill)
   6572                    .addReg(NewVReg5, RegState::Kill)
   6573                    .addImm(0)
   6574                    .addMemOperand(FIMMOSt));
   6575   } else {
   6576     // Incoming value: jbuf
   6577     //   ldr  r1, LCPI1_1
   6578     //   add  r1, pc, r1
   6579     //   str  r1, [$jbuf, #+4] ; &jbuf[1]
   6580     unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
   6581     AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::LDRi12),  NewVReg1)
   6582                    .addConstantPoolIndex(CPI)
   6583                    .addImm(0)
   6584                    .addMemOperand(CPMMO));
   6585     unsigned NewVReg2 = MRI->createVirtualRegister(TRC);
   6586     AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::PICADD), NewVReg2)
   6587                    .addReg(NewVReg1, RegState::Kill)
   6588                    .addImm(PCLabelId));
   6589     AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::STRi12))
   6590                    .addReg(NewVReg2, RegState::Kill)
   6591                    .addFrameIndex(FI)
   6592                    .addImm(36)  // &jbuf[1] :: pc
   6593                    .addMemOperand(FIMMOSt));
   6594   }
   6595 }
   6596 
   6597 MachineBasicBlock *ARMTargetLowering::
   6598 EmitSjLjDispatchBlock(MachineInstr *MI, MachineBasicBlock *MBB) const {
   6599   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
   6600   DebugLoc dl = MI->getDebugLoc();
   6601   MachineFunction *MF = MBB->getParent();
   6602   MachineRegisterInfo *MRI = &MF->getRegInfo();
   6603   ARMFunctionInfo *AFI = MF->getInfo<ARMFunctionInfo>();
   6604   MachineFrameInfo *MFI = MF->getFrameInfo();
   6605   int FI = MFI->getFunctionContextIndex();
   6606 
   6607   const TargetRegisterClass *TRC = Subtarget->isThumb() ?
   6608     (const TargetRegisterClass*)&ARM::tGPRRegClass :
   6609     (const TargetRegisterClass*)&ARM::GPRnopcRegClass;
   6610 
   6611   // Get a mapping of the call site numbers to all of the landing pads they're
   6612   // associated with.
   6613   DenseMap<unsigned, SmallVector<MachineBasicBlock*, 2> > CallSiteNumToLPad;
   6614   unsigned MaxCSNum = 0;
   6615   MachineModuleInfo &MMI = MF->getMMI();
   6616   for (MachineFunction::iterator BB = MF->begin(), E = MF->end(); BB != E;
   6617        ++BB) {
   6618     if (!BB->isLandingPad()) continue;
   6619 
   6620     // FIXME: We should assert that the EH_LABEL is the first MI in the landing
   6621     // pad.
   6622     for (MachineBasicBlock::iterator
   6623            II = BB->begin(), IE = BB->end(); II != IE; ++II) {
   6624       if (!II->isEHLabel()) continue;
   6625 
   6626       MCSymbol *Sym = II->getOperand(0).getMCSymbol();
   6627       if (!MMI.hasCallSiteLandingPad(Sym)) continue;
   6628 
   6629       SmallVectorImpl<unsigned> &CallSiteIdxs = MMI.getCallSiteLandingPad(Sym);
   6630       for (SmallVectorImpl<unsigned>::iterator
   6631              CSI = CallSiteIdxs.begin(), CSE = CallSiteIdxs.end();
   6632            CSI != CSE; ++CSI) {
   6633         CallSiteNumToLPad[*CSI].push_back(BB);
   6634         MaxCSNum = std::max(MaxCSNum, *CSI);
   6635       }
   6636       break;
   6637     }
   6638   }
   6639 
   6640   // Get an ordered list of the machine basic blocks for the jump table.
   6641   std::vector<MachineBasicBlock*> LPadList;
   6642   SmallPtrSet<MachineBasicBlock*, 64> InvokeBBs;
   6643   LPadList.reserve(CallSiteNumToLPad.size());
   6644   for (unsigned I = 1; I <= MaxCSNum; ++I) {
   6645     SmallVectorImpl<MachineBasicBlock*> &MBBList = CallSiteNumToLPad[I];
   6646     for (SmallVectorImpl<MachineBasicBlock*>::iterator
   6647            II = MBBList.begin(), IE = MBBList.end(); II != IE; ++II) {
   6648       LPadList.push_back(*II);
   6649       InvokeBBs.insert((*II)->pred_begin(), (*II)->pred_end());
   6650     }
   6651   }
   6652 
   6653   assert(!LPadList.empty() &&
   6654          "No landing pad destinations for the dispatch jump table!");
   6655 
   6656   // Create the jump table and associated information.
   6657   MachineJumpTableInfo *JTI =
   6658     MF->getOrCreateJumpTableInfo(MachineJumpTableInfo::EK_Inline);
   6659   unsigned MJTI = JTI->createJumpTableIndex(LPadList);
   6660   unsigned UId = AFI->createJumpTableUId();
   6661   Reloc::Model RelocM = getTargetMachine().getRelocationModel();
   6662 
   6663   // Create the MBBs for the dispatch code.
   6664 
   6665   // Shove the dispatch's address into the return slot in the function context.
   6666   MachineBasicBlock *DispatchBB = MF->CreateMachineBasicBlock();
   6667   DispatchBB->setIsLandingPad();
   6668 
   6669   MachineBasicBlock *TrapBB = MF->CreateMachineBasicBlock();
   6670   unsigned trap_opcode;
   6671   if (Subtarget->isThumb())
   6672     trap_opcode = ARM::tTRAP;
   6673   else
   6674     trap_opcode = Subtarget->useNaClTrap() ? ARM::TRAPNaCl : ARM::TRAP;
   6675 
   6676   BuildMI(TrapBB, dl, TII->get(trap_opcode));
   6677   DispatchBB->addSuccessor(TrapBB);
   6678 
   6679   MachineBasicBlock *DispContBB = MF->CreateMachineBasicBlock();
   6680   DispatchBB->addSuccessor(DispContBB);
   6681 
   6682   // Insert and MBBs.
   6683   MF->insert(MF->end(), DispatchBB);
   6684   MF->insert(MF->end(), DispContBB);
   6685   MF->insert(MF->end(), TrapBB);
   6686 
   6687   // Insert code into the entry block that creates and registers the function
   6688   // context.
   6689   SetupEntryBlockForSjLj(MI, MBB, DispatchBB, FI);
   6690 
   6691   MachineMemOperand *FIMMOLd =
   6692     MF->getMachineMemOperand(MachinePointerInfo::getFixedStack(FI),
   6693                              MachineMemOperand::MOLoad |
   6694                              MachineMemOperand::MOVolatile, 4, 4);
   6695 
   6696   MachineInstrBuilder MIB;
   6697   MIB = BuildMI(DispatchBB, dl, TII->get(ARM::Int_eh_sjlj_dispatchsetup));
   6698 
   6699   const ARMBaseInstrInfo *AII = static_cast<const ARMBaseInstrInfo*>(TII);
   6700   const ARMBaseRegisterInfo &RI = AII->getRegisterInfo();
   6701 
   6702   // Add a register mask with no preserved registers.  This results in all
   6703   // registers being marked as clobbered.
   6704   MIB.addRegMask(RI.getNoPreservedMask());
   6705 
   6706   unsigned NumLPads = LPadList.size();
   6707   if (Subtarget->isThumb2()) {
   6708     unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
   6709     AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::t2LDRi12), NewVReg1)
   6710                    .addFrameIndex(FI)
   6711                    .addImm(4)
   6712                    .addMemOperand(FIMMOLd));
   6713 
   6714     if (NumLPads < 256) {
   6715       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::t2CMPri))
   6716                      .addReg(NewVReg1)
   6717                      .addImm(LPadList.size()));
   6718     } else {
   6719       unsigned VReg1 = MRI->createVirtualRegister(TRC);
   6720       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::t2MOVi16), VReg1)
   6721                      .addImm(NumLPads & 0xFFFF));
   6722 
   6723       unsigned VReg2 = VReg1;
   6724       if ((NumLPads & 0xFFFF0000) != 0) {
   6725         VReg2 = MRI->createVirtualRegister(TRC);
   6726         AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::t2MOVTi16), VReg2)
   6727                        .addReg(VReg1)
   6728                        .addImm(NumLPads >> 16));
   6729       }
   6730 
   6731       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::t2CMPrr))
   6732                      .addReg(NewVReg1)
   6733                      .addReg(VReg2));
   6734     }
   6735 
   6736     BuildMI(DispatchBB, dl, TII->get(ARM::t2Bcc))
   6737       .addMBB(TrapBB)
   6738       .addImm(ARMCC::HI)
   6739       .addReg(ARM::CPSR);
   6740 
   6741     unsigned NewVReg3 = MRI->createVirtualRegister(TRC);
   6742     AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::t2LEApcrelJT),NewVReg3)
   6743                    .addJumpTableIndex(MJTI)
   6744                    .addImm(UId));
   6745 
   6746     unsigned NewVReg4 = MRI->createVirtualRegister(TRC);
   6747     AddDefaultCC(
   6748       AddDefaultPred(
   6749         BuildMI(DispContBB, dl, TII->get(ARM::t2ADDrs), NewVReg4)
   6750         .addReg(NewVReg3, RegState::Kill)
   6751         .addReg(NewVReg1)
   6752         .addImm(ARM_AM::getSORegOpc(ARM_AM::lsl, 2))));
   6753 
   6754     BuildMI(DispContBB, dl, TII->get(ARM::t2BR_JT))
   6755       .addReg(NewVReg4, RegState::Kill)
   6756       .addReg(NewVReg1)
   6757       .addJumpTableIndex(MJTI)
   6758       .addImm(UId);
   6759   } else if (Subtarget->isThumb()) {
   6760     unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
   6761     AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::tLDRspi), NewVReg1)
   6762                    .addFrameIndex(FI)
   6763                    .addImm(1)
   6764                    .addMemOperand(FIMMOLd));
   6765 
   6766     if (NumLPads < 256) {
   6767       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::tCMPi8))
   6768                      .addReg(NewVReg1)
   6769                      .addImm(NumLPads));
   6770     } else {
   6771       MachineConstantPool *ConstantPool = MF->getConstantPool();
   6772       Type *Int32Ty = Type::getInt32Ty(MF->getFunction()->getContext());
   6773       const Constant *C = ConstantInt::get(Int32Ty, NumLPads);
   6774 
   6775       // MachineConstantPool wants an explicit alignment.
   6776       unsigned Align = getDataLayout()->getPrefTypeAlignment(Int32Ty);
   6777       if (Align == 0)
   6778         Align = getDataLayout()->getTypeAllocSize(C->getType());
   6779       unsigned Idx = ConstantPool->getConstantPoolIndex(C, Align);
   6780 
   6781       unsigned VReg1 = MRI->createVirtualRegister(TRC);
   6782       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::tLDRpci))
   6783                      .addReg(VReg1, RegState::Define)
   6784                      .addConstantPoolIndex(Idx));
   6785       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::tCMPr))
   6786                      .addReg(NewVReg1)
   6787                      .addReg(VReg1));
   6788     }
   6789 
   6790     BuildMI(DispatchBB, dl, TII->get(ARM::tBcc))
   6791       .addMBB(TrapBB)
   6792       .addImm(ARMCC::HI)
   6793       .addReg(ARM::CPSR);
   6794 
   6795     unsigned NewVReg2 = MRI->createVirtualRegister(TRC);
   6796     AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::tLSLri), NewVReg2)
   6797                    .addReg(ARM::CPSR, RegState::Define)
   6798                    .addReg(NewVReg1)
   6799                    .addImm(2));
   6800 
   6801     unsigned NewVReg3 = MRI->createVirtualRegister(TRC);
   6802     AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::tLEApcrelJT), NewVReg3)
   6803                    .addJumpTableIndex(MJTI)
   6804                    .addImm(UId));
   6805 
   6806     unsigned NewVReg4 = MRI->createVirtualRegister(TRC);
   6807     AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::tADDrr), NewVReg4)
   6808                    .addReg(ARM::CPSR, RegState::Define)
   6809                    .addReg(NewVReg2, RegState::Kill)
   6810                    .addReg(NewVReg3));
   6811 
   6812     MachineMemOperand *JTMMOLd =
   6813       MF->getMachineMemOperand(MachinePointerInfo::getJumpTable(),
   6814                                MachineMemOperand::MOLoad, 4, 4);
   6815 
   6816     unsigned NewVReg5 = MRI->createVirtualRegister(TRC);
   6817     AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::tLDRi), NewVReg5)
   6818                    .addReg(NewVReg4, RegState::Kill)
   6819                    .addImm(0)
   6820                    .addMemOperand(JTMMOLd));
   6821 
   6822     unsigned NewVReg6 = NewVReg5;
   6823     if (RelocM == Reloc::PIC_) {
   6824       NewVReg6 = MRI->createVirtualRegister(TRC);
   6825       AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::tADDrr), NewVReg6)
   6826                      .addReg(ARM::CPSR, RegState::Define)
   6827                      .addReg(NewVReg5, RegState::Kill)
   6828                      .addReg(NewVReg3));
   6829     }
   6830 
   6831     BuildMI(DispContBB, dl, TII->get(ARM::tBR_JTr))
   6832       .addReg(NewVReg6, RegState::Kill)
   6833       .addJumpTableIndex(MJTI)
   6834       .addImm(UId);
   6835   } else {
   6836     unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
   6837     AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::LDRi12), NewVReg1)
   6838                    .addFrameIndex(FI)
   6839                    .addImm(4)
   6840                    .addMemOperand(FIMMOLd));
   6841 
   6842     if (NumLPads < 256) {
   6843       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::CMPri))
   6844                      .addReg(NewVReg1)
   6845                      .addImm(NumLPads));
   6846     } else if (Subtarget->hasV6T2Ops() && isUInt<16>(NumLPads)) {
   6847       unsigned VReg1 = MRI->createVirtualRegister(TRC);
   6848       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::MOVi16), VReg1)
   6849                      .addImm(NumLPads & 0xFFFF));
   6850 
   6851       unsigned VReg2 = VReg1;
   6852       if ((NumLPads & 0xFFFF0000) != 0) {
   6853         VReg2 = MRI->createVirtualRegister(TRC);
   6854         AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::MOVTi16), VReg2)
   6855                        .addReg(VReg1)
   6856                        .addImm(NumLPads >> 16));
   6857       }
   6858 
   6859       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::CMPrr))
   6860                      .addReg(NewVReg1)
   6861                      .addReg(VReg2));
   6862     } else {
   6863       MachineConstantPool *ConstantPool = MF->getConstantPool();
   6864       Type *Int32Ty = Type::getInt32Ty(MF->getFunction()->getContext());
   6865       const Constant *C = ConstantInt::get(Int32Ty, NumLPads);
   6866 
   6867       // MachineConstantPool wants an explicit alignment.
   6868       unsigned Align = getDataLayout()->getPrefTypeAlignment(Int32Ty);
   6869       if (Align == 0)
   6870         Align = getDataLayout()->getTypeAllocSize(C->getType());
   6871       unsigned Idx = ConstantPool->getConstantPoolIndex(C, Align);
   6872 
   6873       unsigned VReg1 = MRI->createVirtualRegister(TRC);
   6874       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::LDRcp))
   6875                      .addReg(VReg1, RegState::Define)
   6876                      .addConstantPoolIndex(Idx)
   6877                      .addImm(0));
   6878       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::CMPrr))
   6879                      .addReg(NewVReg1)
   6880                      .addReg(VReg1, RegState::Kill));
   6881     }
   6882 
   6883     BuildMI(DispatchBB, dl, TII->get(ARM::Bcc))
   6884       .addMBB(TrapBB)
   6885       .addImm(ARMCC::HI)
   6886       .addReg(ARM::CPSR);
   6887 
   6888     unsigned NewVReg3 = MRI->createVirtualRegister(TRC);
   6889     AddDefaultCC(
   6890       AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::MOVsi), NewVReg3)
   6891                      .addReg(NewVReg1)
   6892                      .addImm(ARM_AM::getSORegOpc(ARM_AM::lsl, 2))));
   6893     unsigned NewVReg4 = MRI->createVirtualRegister(TRC);
   6894     AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::LEApcrelJT), NewVReg4)
   6895                    .addJumpTableIndex(MJTI)
   6896                    .addImm(UId));
   6897 
   6898     MachineMemOperand *JTMMOLd =
   6899       MF->getMachineMemOperand(MachinePointerInfo::getJumpTable(),
   6900                                MachineMemOperand::MOLoad, 4, 4);
   6901     unsigned NewVReg5 = MRI->createVirtualRegister(TRC);
   6902     AddDefaultPred(
   6903       BuildMI(DispContBB, dl, TII->get(ARM::LDRrs), NewVReg5)
   6904       .addReg(NewVReg3, RegState::Kill)
   6905       .addReg(NewVReg4)
   6906       .addImm(0)
   6907       .addMemOperand(JTMMOLd));
   6908 
   6909     if (RelocM == Reloc::PIC_) {
   6910       BuildMI(DispContBB, dl, TII->get(ARM::BR_JTadd))
   6911         .addReg(NewVReg5, RegState::Kill)
   6912         .addReg(NewVReg4)
   6913         .addJumpTableIndex(MJTI)
   6914         .addImm(UId);
   6915     } else {
   6916       BuildMI(DispContBB, dl, TII->get(ARM::BR_JTr))
   6917         .addReg(NewVReg5, RegState::Kill)
   6918         .addJumpTableIndex(MJTI)
   6919         .addImm(UId);
   6920     }
   6921   }
   6922 
   6923   // Add the jump table entries as successors to the MBB.
   6924   SmallPtrSet<MachineBasicBlock*, 8> SeenMBBs;
   6925   for (std::vector<MachineBasicBlock*>::iterator
   6926          I = LPadList.begin(), E = LPadList.end(); I != E; ++I) {
   6927     MachineBasicBlock *CurMBB = *I;
   6928     if (SeenMBBs.insert(CurMBB))
   6929       DispContBB->addSuccessor(CurMBB);
   6930   }
   6931 
   6932   // N.B. the order the invoke BBs are processed in doesn't matter here.
   6933   const uint16_t *SavedRegs = RI.getCalleeSavedRegs(MF);
   6934   SmallVector<MachineBasicBlock*, 64> MBBLPads;
   6935   for (SmallPtrSet<MachineBasicBlock*, 64>::iterator
   6936          I = InvokeBBs.begin(), E = InvokeBBs.end(); I != E; ++I) {
   6937     MachineBasicBlock *BB = *I;
   6938 
   6939     // Remove the landing pad successor from the invoke block and replace it
   6940     // with the new dispatch block.
   6941     SmallVector<MachineBasicBlock*, 4> Successors(BB->succ_begin(),
   6942                                                   BB->succ_end());
   6943     while (!Successors.empty()) {
   6944       MachineBasicBlock *SMBB = Successors.pop_back_val();
   6945       if (SMBB->isLandingPad()) {
   6946         BB->removeSuccessor(SMBB);
   6947         MBBLPads.push_back(SMBB);
   6948       }
   6949     }
   6950 
   6951     BB->addSuccessor(DispatchBB);
   6952 
   6953     // Find the invoke call and mark all of the callee-saved registers as
   6954     // 'implicit defined' so that they're spilled. This prevents code from
   6955     // moving instructions to before the EH block, where they will never be
   6956     // executed.
   6957     for (MachineBasicBlock::reverse_iterator
   6958            II = BB->rbegin(), IE = BB->rend(); II != IE; ++II) {
   6959       if (!II->isCall()) continue;
   6960 
   6961       DenseMap<unsigned, bool> DefRegs;
   6962       for (MachineInstr::mop_iterator
   6963              OI = II->operands_begin(), OE = II->operands_end();
   6964            OI != OE; ++OI) {
   6965         if (!OI->isReg()) continue;
   6966         DefRegs[OI->getReg()] = true;
   6967       }
   6968 
   6969       MachineInstrBuilder MIB(*MF, &*II);
   6970 
   6971       for (unsigned i = 0; SavedRegs[i] != 0; ++i) {
   6972         unsigned Reg = SavedRegs[i];
   6973         if (Subtarget->isThumb2() &&
   6974             !ARM::tGPRRegClass.contains(Reg) &&
   6975             !ARM::hGPRRegClass.contains(Reg))
   6976           continue;
   6977         if (Subtarget->isThumb1Only() && !ARM::tGPRRegClass.contains(Reg))
   6978           continue;
   6979         if (!Subtarget->isThumb() && !ARM::GPRRegClass.contains(Reg))
   6980           continue;
   6981         if (!DefRegs[Reg])
   6982           MIB.addReg(Reg, RegState::ImplicitDefine | RegState::Dead);
   6983       }
   6984 
   6985       break;
   6986     }
   6987   }
   6988 
   6989   // Mark all former landing pads as non-landing pads. The dispatch is the only
   6990   // landing pad now.
   6991   for (SmallVectorImpl<MachineBasicBlock*>::iterator
   6992          I = MBBLPads.begin(), E = MBBLPads.end(); I != E; ++I)
   6993     (*I)->setIsLandingPad(false);
   6994 
   6995   // The instruction is gone now.
   6996   MI->eraseFromParent();
   6997 
   6998   return MBB;
   6999 }
   7000 
   7001 static
   7002 MachineBasicBlock *OtherSucc(MachineBasicBlock *MBB, MachineBasicBlock *Succ) {
   7003   for (MachineBasicBlock::succ_iterator I = MBB->succ_begin(),
   7004        E = MBB->succ_end(); I != E; ++I)
   7005     if (*I != Succ)
   7006       return *I;
   7007   llvm_unreachable("Expecting a BB with two successors!");
   7008 }
   7009 
   7010 MachineBasicBlock *ARMTargetLowering::
   7011 EmitStructByval(MachineInstr *MI, MachineBasicBlock *BB) const {
   7012   // This pseudo instruction has 3 operands: dst, src, size
   7013   // We expand it to a loop if size > Subtarget->getMaxInlineSizeThreshold().
   7014   // Otherwise, we will generate unrolled scalar copies.
   7015   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
   7016   const BasicBlock *LLVM_BB = BB->getBasicBlock();
   7017   MachineFunction::iterator It = BB;
   7018   ++It;
   7019 
   7020   unsigned dest = MI->getOperand(0).getReg();
   7021   unsigned src = MI->getOperand(1).getReg();
   7022   unsigned SizeVal = MI->getOperand(2).getImm();
   7023   unsigned Align = MI->getOperand(3).getImm();
   7024   DebugLoc dl = MI->getDebugLoc();
   7025 
   7026   bool isThumb2 = Subtarget->isThumb2();
   7027   MachineFunction *MF = BB->getParent();
   7028   MachineRegisterInfo &MRI = MF->getRegInfo();
   7029   unsigned ldrOpc, strOpc, UnitSize = 0;
   7030 
   7031   const TargetRegisterClass *TRC = isThumb2 ?
   7032     (const TargetRegisterClass*)&ARM::tGPRRegClass :
   7033     (const TargetRegisterClass*)&ARM::GPRRegClass;
   7034   const TargetRegisterClass *TRC_Vec = 0;
   7035 
   7036   if (Align & 1) {
   7037     ldrOpc = isThumb2 ? ARM::t2LDRB_POST : ARM::LDRB_POST_IMM;
   7038     strOpc = isThumb2 ? ARM::t2STRB_POST : ARM::STRB_POST_IMM;
   7039     UnitSize = 1;
   7040   } else if (Align & 2) {
   7041     ldrOpc = isThumb2 ? ARM::t2LDRH_POST : ARM::LDRH_POST;
   7042     strOpc = isThumb2 ? ARM::t2STRH_POST : ARM::STRH_POST;
   7043     UnitSize = 2;
   7044   } else {
   7045     // Check whether we can use NEON instructions.
   7046     if (!MF->getFunction()->getAttributes().
   7047           hasAttribute(AttributeSet::FunctionIndex,
   7048                        Attribute::NoImplicitFloat) &&
   7049         Subtarget->hasNEON()) {
   7050       if ((Align % 16 == 0) && SizeVal >= 16) {
   7051         ldrOpc = ARM::VLD1q32wb_fixed;
   7052         strOpc = ARM::VST1q32wb_fixed;
   7053         UnitSize = 16;
   7054         TRC_Vec = (const TargetRegisterClass*)&ARM::DPairRegClass;
   7055       }
   7056       else if ((Align % 8 == 0) && SizeVal >= 8) {
   7057         ldrOpc = ARM::VLD1d32wb_fixed;
   7058         strOpc = ARM::VST1d32wb_fixed;
   7059         UnitSize = 8;
   7060         TRC_Vec = (const TargetRegisterClass*)&ARM::DPRRegClass;
   7061       }
   7062     }
   7063     // Can't use NEON instructions.
   7064     if (UnitSize == 0) {
   7065       ldrOpc = isThumb2 ? ARM::t2LDR_POST : ARM::LDR_POST_IMM;
   7066       strOpc = isThumb2 ? ARM::t2STR_POST : ARM::STR_POST_IMM;
   7067       UnitSize = 4;
   7068     }
   7069   }
   7070 
   7071   unsigned BytesLeft = SizeVal % UnitSize;
   7072   unsigned LoopSize = SizeVal - BytesLeft;
   7073 
   7074   if (SizeVal <= Subtarget->getMaxInlineSizeThreshold()) {
   7075     // Use LDR and STR to copy.
   7076     // [scratch, srcOut] = LDR_POST(srcIn, UnitSize)
   7077     // [destOut] = STR_POST(scratch, destIn, UnitSize)
   7078     unsigned srcIn = src;
   7079     unsigned destIn = dest;
   7080     for (unsigned i = 0; i < LoopSize; i+=UnitSize) {
   7081       unsigned scratch = MRI.createVirtualRegister(UnitSize >= 8 ? TRC_Vec:TRC);
   7082       unsigned srcOut = MRI.createVirtualRegister(TRC);
   7083       unsigned destOut = MRI.createVirtualRegister(TRC);
   7084       if (UnitSize >= 8) {
   7085         AddDefaultPred(BuildMI(*BB, MI, dl,
   7086           TII->get(ldrOpc), scratch)
   7087           .addReg(srcOut, RegState::Define).addReg(srcIn).addImm(0));
   7088 
   7089         AddDefaultPred(BuildMI(*BB, MI, dl, TII->get(strOpc), destOut)
   7090           .addReg(destIn).addImm(0).addReg(scratch));
   7091       } else if (isThumb2) {
   7092         AddDefaultPred(BuildMI(*BB, MI, dl,
   7093           TII->get(ldrOpc), scratch)
   7094           .addReg(srcOut, RegState::Define).addReg(srcIn).addImm(UnitSize));
   7095 
   7096         AddDefaultPred(BuildMI(*BB, MI, dl, TII->get(strOpc), destOut)
   7097           .addReg(scratch).addReg(destIn)
   7098           .addImm(UnitSize));
   7099       } else {
   7100         AddDefaultPred(BuildMI(*BB, MI, dl,
   7101           TII->get(ldrOpc), scratch)
   7102           .addReg(srcOut, RegState::Define).addReg(srcIn).addReg(0)
   7103           .addImm(UnitSize));
   7104 
   7105         AddDefaultPred(BuildMI(*BB, MI, dl, TII->get(strOpc), destOut)
   7106           .addReg(scratch).addReg(destIn)
   7107           .addReg(0).addImm(UnitSize));
   7108       }
   7109       srcIn = srcOut;
   7110       destIn = destOut;
   7111     }
   7112 
   7113     // Handle the leftover bytes with LDRB and STRB.
   7114     // [scratch, srcOut] = LDRB_POST(srcIn, 1)
   7115     // [destOut] = STRB_POST(scratch, destIn, 1)
   7116     ldrOpc = isThumb2 ? ARM::t2LDRB_POST : ARM::LDRB_POST_IMM;
   7117     strOpc = isThumb2 ? ARM::t2STRB_POST : ARM::STRB_POST_IMM;
   7118     for (unsigned i = 0; i < BytesLeft; i++) {
   7119       unsigned scratch = MRI.createVirtualRegister(TRC);
   7120       unsigned srcOut = MRI.createVirtualRegister(TRC);
   7121       unsigned destOut = MRI.createVirtualRegister(TRC);
   7122       if (isThumb2) {
   7123         AddDefaultPred(BuildMI(*BB, MI, dl,
   7124           TII->get(ldrOpc),scratch)
   7125           .addReg(srcOut, RegState::Define).addReg(srcIn).addImm(1));
   7126 
   7127         AddDefaultPred(BuildMI(*BB, MI, dl, TII->get(strOpc), destOut)
   7128           .addReg(scratch).addReg(destIn)
   7129           .addReg(0).addImm(1));
   7130       } else {
   7131         AddDefaultPred(BuildMI(*BB, MI, dl,
   7132           TII->get(ldrOpc),scratch)
   7133           .addReg(srcOut, RegState::Define).addReg(srcIn)
   7134           .addReg(0).addImm(1));
   7135 
   7136         AddDefaultPred(BuildMI(*BB, MI, dl, TII->get(strOpc), destOut)
   7137           .addReg(scratch).addReg(destIn)
   7138           .addReg(0).addImm(1));
   7139       }
   7140       srcIn = srcOut;
   7141       destIn = destOut;
   7142     }
   7143     MI->eraseFromParent();   // The instruction is gone now.
   7144     return BB;
   7145   }
   7146 
   7147   // Expand the pseudo op to a loop.
   7148   // thisMBB:
   7149   //   ...
   7150   //   movw varEnd, # --> with thumb2
   7151   //   movt varEnd, #
   7152   //   ldrcp varEnd, idx --> without thumb2
   7153   //   fallthrough --> loopMBB
   7154   // loopMBB:
   7155   //   PHI varPhi, varEnd, varLoop
   7156   //   PHI srcPhi, src, srcLoop
   7157   //   PHI destPhi, dst, destLoop
   7158   //   [scratch, srcLoop] = LDR_POST(srcPhi, UnitSize)
   7159   //   [destLoop] = STR_POST(scratch, destPhi, UnitSize)
   7160   //   subs varLoop, varPhi, #UnitSize
   7161   //   bne loopMBB
   7162   //   fallthrough --> exitMBB
   7163   // exitMBB:
   7164   //   epilogue to handle left-over bytes
   7165   //   [scratch, srcOut] = LDRB_POST(srcLoop, 1)
   7166   //   [destOut] = STRB_POST(scratch, destLoop, 1)
   7167   MachineBasicBlock *loopMBB = MF->CreateMachineBasicBlock(LLVM_BB);
   7168   MachineBasicBlock *exitMBB = MF->CreateMachineBasicBlock(LLVM_BB);
   7169   MF->insert(It, loopMBB);
   7170   MF->insert(It, exitMBB);
   7171 
   7172   // Transfer the remainder of BB and its successor edges to exitMBB.
   7173   exitMBB->splice(exitMBB->begin(), BB,
   7174                   llvm::next(MachineBasicBlock::iterator(MI)),
   7175                   BB->end());
   7176   exitMBB->transferSuccessorsAndUpdatePHIs(BB);
   7177 
   7178   // Load an immediate to varEnd.
   7179   unsigned varEnd = MRI.createVirtualRegister(TRC);
   7180   if (isThumb2) {
   7181     unsigned VReg1 = varEnd;
   7182     if ((LoopSize & 0xFFFF0000) != 0)
   7183       VReg1 = MRI.createVirtualRegister(TRC);
   7184     AddDefaultPred(BuildMI(BB, dl, TII->get(ARM::t2MOVi16), VReg1)
   7185                    .addImm(LoopSize & 0xFFFF));
   7186 
   7187     if ((LoopSize & 0xFFFF0000) != 0)
   7188       AddDefaultPred(BuildMI(BB, dl, TII->get(ARM::t2MOVTi16), varEnd)
   7189                      .addReg(VReg1)
   7190                      .addImm(LoopSize >> 16));
   7191   } else {
   7192     MachineConstantPool *ConstantPool = MF->getConstantPool();
   7193     Type *Int32Ty = Type::getInt32Ty(MF->getFunction()->getContext());
   7194     const Constant *C = ConstantInt::get(Int32Ty, LoopSize);
   7195 
   7196     // MachineConstantPool wants an explicit alignment.
   7197     unsigned Align = getDataLayout()->getPrefTypeAlignment(Int32Ty);
   7198     if (Align == 0)
   7199       Align = getDataLayout()->getTypeAllocSize(C->getType());
   7200     unsigned Idx = ConstantPool->getConstantPoolIndex(C, Align);
   7201 
   7202     AddDefaultPred(BuildMI(BB, dl, TII->get(ARM::LDRcp))
   7203                    .addReg(varEnd, RegState::Define)
   7204                    .addConstantPoolIndex(Idx)
   7205                    .addImm(0));
   7206   }
   7207   BB->addSuccessor(loopMBB);
   7208 
   7209   // Generate the loop body:
   7210   //   varPhi = PHI(varLoop, varEnd)
   7211   //   srcPhi = PHI(srcLoop, src)
   7212   //   destPhi = PHI(destLoop, dst)
   7213   MachineBasicBlock *entryBB = BB;
   7214   BB = loopMBB;
   7215   unsigned varLoop = MRI.createVirtualRegister(TRC);
   7216   unsigned varPhi = MRI.createVirtualRegister(TRC);
   7217   unsigned srcLoop = MRI.createVirtualRegister(TRC);
   7218   unsigned srcPhi = MRI.createVirtualRegister(TRC);
   7219   unsigned destLoop = MRI.createVirtualRegister(TRC);
   7220   unsigned destPhi = MRI.createVirtualRegister(TRC);
   7221 
   7222   BuildMI(*BB, BB->begin(), dl, TII->get(ARM::PHI), varPhi)
   7223     .addReg(varLoop).addMBB(loopMBB)
   7224     .addReg(varEnd).addMBB(entryBB);
   7225   BuildMI(BB, dl, TII->get(ARM::PHI), srcPhi)
   7226     .addReg(srcLoop).addMBB(loopMBB)
   7227     .addReg(src).addMBB(entryBB);
   7228   BuildMI(BB, dl, TII->get(ARM::PHI), destPhi)
   7229     .addReg(destLoop).addMBB(loopMBB)
   7230     .addReg(dest).addMBB(entryBB);
   7231 
   7232   //   [scratch, srcLoop] = LDR_POST(srcPhi, UnitSize)
   7233   //   [destLoop] = STR_POST(scratch, destPhi, UnitSiz)
   7234   unsigned scratch = MRI.createVirtualRegister(UnitSize >= 8 ? TRC_Vec:TRC);
   7235   if (UnitSize >= 8) {
   7236     AddDefaultPred(BuildMI(BB, dl, TII->get(ldrOpc), scratch)
   7237       .addReg(srcLoop, RegState::Define).addReg(srcPhi).addImm(0));
   7238 
   7239     AddDefaultPred(BuildMI(BB, dl, TII->get(strOpc), destLoop)
   7240       .addReg(destPhi).addImm(0).addReg(scratch));
   7241   } else if (isThumb2) {
   7242     AddDefaultPred(BuildMI(BB, dl, TII->get(ldrOpc), scratch)
   7243       .addReg(srcLoop, RegState::Define).addReg(srcPhi).addImm(UnitSize));
   7244 
   7245     AddDefaultPred(BuildMI(BB, dl, TII->get(strOpc), destLoop)
   7246       .addReg(scratch).addReg(destPhi)
   7247       .addImm(UnitSize));
   7248   } else {
   7249     AddDefaultPred(BuildMI(BB, dl, TII->get(ldrOpc), scratch)
   7250       .addReg(srcLoop, RegState::Define).addReg(srcPhi).addReg(0)
   7251       .addImm(UnitSize));
   7252 
   7253     AddDefaultPred(BuildMI(BB, dl, TII->get(strOpc), destLoop)
   7254       .addReg(scratch).addReg(destPhi)
   7255       .addReg(0).addImm(UnitSize));
   7256   }
   7257 
   7258   // Decrement loop variable by UnitSize.
   7259   MachineInstrBuilder MIB = BuildMI(BB, dl,
   7260     TII->get(isThumb2 ? ARM::t2SUBri : ARM::SUBri), varLoop);
   7261   AddDefaultCC(AddDefaultPred(MIB.addReg(varPhi).addImm(UnitSize)));
   7262   MIB->getOperand(5).setReg(ARM::CPSR);
   7263   MIB->getOperand(5).setIsDef(true);
   7264 
   7265   BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc))
   7266     .addMBB(loopMBB).addImm(ARMCC::NE).addReg(ARM::CPSR);
   7267 
   7268   // loopMBB can loop back to loopMBB or fall through to exitMBB.
   7269   BB->addSuccessor(loopMBB);
   7270   BB->addSuccessor(exitMBB);
   7271 
   7272   // Add epilogue to handle BytesLeft.
   7273   BB = exitMBB;
   7274   MachineInstr *StartOfExit = exitMBB->begin();
   7275   ldrOpc = isThumb2 ? ARM::t2LDRB_POST : ARM::LDRB_POST_IMM;
   7276   strOpc = isThumb2 ? ARM::t2STRB_POST : ARM::STRB_POST_IMM;
   7277 
   7278   //   [scratch, srcOut] = LDRB_POST(srcLoop, 1)
   7279   //   [destOut] = STRB_POST(scratch, destLoop, 1)
   7280   unsigned srcIn = srcLoop;
   7281   unsigned destIn = destLoop;
   7282   for (unsigned i = 0; i < BytesLeft; i++) {
   7283     unsigned scratch = MRI.createVirtualRegister(TRC);
   7284     unsigned srcOut = MRI.createVirtualRegister(TRC);
   7285     unsigned destOut = MRI.createVirtualRegister(TRC);
   7286     if (isThumb2) {
   7287       AddDefaultPred(BuildMI(*BB, StartOfExit, dl,
   7288         TII->get(ldrOpc),scratch)
   7289         .addReg(srcOut, RegState::Define).addReg(srcIn).addImm(1));
   7290 
   7291       AddDefaultPred(BuildMI(*BB, StartOfExit, dl, TII->get(strOpc), destOut)
   7292         .addReg(scratch).addReg(destIn)
   7293         .addImm(1));
   7294     } else {
   7295       AddDefaultPred(BuildMI(*BB, StartOfExit, dl,
   7296         TII->get(ldrOpc),scratch)
   7297         .addReg(srcOut, RegState::Define).addReg(srcIn).addReg(0).addImm(1));
   7298 
   7299       AddDefaultPred(BuildMI(*BB, StartOfExit, dl, TII->get(strOpc), destOut)
   7300         .addReg(scratch).addReg(destIn)
   7301         .addReg(0).addImm(1));
   7302     }
   7303     srcIn = srcOut;
   7304     destIn = destOut;
   7305   }
   7306 
   7307   MI->eraseFromParent();   // The instruction is gone now.
   7308   return BB;
   7309 }
   7310 
   7311 MachineBasicBlock *
   7312 ARMTargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
   7313                                                MachineBasicBlock *BB) const {
   7314   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
   7315   DebugLoc dl = MI->getDebugLoc();
   7316   bool isThumb2 = Subtarget->isThumb2();
   7317   switch (MI->getOpcode()) {
   7318   default: {
   7319     MI->dump();
   7320     llvm_unreachable("Unexpected instr type to insert");
   7321   }
   7322   // The Thumb2 pre-indexed stores have the same MI operands, they just
   7323   // define them differently in the .td files from the isel patterns, so
   7324   // they need pseudos.
   7325   case ARM::t2STR_preidx:
   7326     MI->setDesc(TII->get(ARM::t2STR_PRE));
   7327     return BB;
   7328   case ARM::t2STRB_preidx:
   7329     MI->setDesc(TII->get(ARM::t2STRB_PRE));
   7330     return BB;
   7331   case ARM::t2STRH_preidx:
   7332     MI->setDesc(TII->get(ARM::t2STRH_PRE));
   7333     return BB;
   7334 
   7335   case ARM::STRi_preidx:
   7336   case ARM::STRBi_preidx: {
   7337     unsigned NewOpc = MI->getOpcode() == ARM::STRi_preidx ?
   7338       ARM::STR_PRE_IMM : ARM::STRB_PRE_IMM;
   7339     // Decode the offset.
   7340     unsigned Offset = MI->getOperand(4).getImm();
   7341     bool isSub = ARM_AM::getAM2Op(Offset) == ARM_AM::sub;
   7342     Offset = ARM_AM::getAM2Offset(Offset);
   7343     if (isSub)
   7344       Offset = -Offset;
   7345 
   7346     MachineMemOperand *MMO = *MI->memoperands_begin();
   7347     BuildMI(*BB, MI, dl, TII->get(NewOpc))
   7348       .addOperand(MI->getOperand(0))  // Rn_wb
   7349       .addOperand(MI->getOperand(1))  // Rt
   7350       .addOperand(MI->getOperand(2))  // Rn
   7351       .addImm(Offset)                 // offset (skip GPR==zero_reg)
   7352       .addOperand(MI->getOperand(5))  // pred
   7353       .addOperand(MI->getOperand(6))
   7354       .addMemOperand(MMO);
   7355     MI->eraseFromParent();
   7356     return BB;
   7357   }
   7358   case ARM::STRr_preidx:
   7359   case ARM::STRBr_preidx:
   7360   case ARM::STRH_preidx: {
   7361     unsigned NewOpc;
   7362     switch (MI->getOpcode()) {
   7363     default: llvm_unreachable("unexpected opcode!");
   7364     case ARM::STRr_preidx: NewOpc = ARM::STR_PRE_REG; break;
   7365     case ARM::STRBr_preidx: NewOpc = ARM::STRB_PRE_REG; break;
   7366     case ARM::STRH_preidx: NewOpc = ARM::STRH_PRE; break;
   7367     }
   7368     MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(NewOpc));
   7369     for (unsigned i = 0; i < MI->getNumOperands(); ++i)
   7370       MIB.addOperand(MI->getOperand(i));
   7371     MI->eraseFromParent();
   7372     return BB;
   7373   }
   7374   case ARM::ATOMIC_LOAD_ADD_I8:
   7375      return EmitAtomicBinary(MI, BB, 1, isThumb2 ? ARM::t2ADDrr : ARM::ADDrr);
   7376   case ARM::ATOMIC_LOAD_ADD_I16:
   7377      return EmitAtomicBinary(MI, BB, 2, isThumb2 ? ARM::t2ADDrr : ARM::ADDrr);
   7378   case ARM::ATOMIC_LOAD_ADD_I32:
   7379      return EmitAtomicBinary(MI, BB, 4, isThumb2 ? ARM::t2ADDrr : ARM::ADDrr);
   7380 
   7381   case ARM::ATOMIC_LOAD_AND_I8:
   7382      return EmitAtomicBinary(MI, BB, 1, isThumb2 ? ARM::t2ANDrr : ARM::ANDrr);
   7383   case ARM::ATOMIC_LOAD_AND_I16:
   7384      return EmitAtomicBinary(MI, BB, 2, isThumb2 ? ARM::t2ANDrr : ARM::ANDrr);
   7385   case ARM::ATOMIC_LOAD_AND_I32:
   7386      return EmitAtomicBinary(MI, BB, 4, isThumb2 ? ARM::t2ANDrr : ARM::ANDrr);
   7387 
   7388   case ARM::ATOMIC_LOAD_OR_I8:
   7389      return EmitAtomicBinary(MI, BB, 1, isThumb2 ? ARM::t2ORRrr : ARM::ORRrr);
   7390   case ARM::ATOMIC_LOAD_OR_I16:
   7391      return EmitAtomicBinary(MI, BB, 2, isThumb2 ? ARM::t2ORRrr : ARM::ORRrr);
   7392   case ARM::ATOMIC_LOAD_OR_I32:
   7393      return EmitAtomicBinary(MI, BB, 4, isThumb2 ? ARM::t2ORRrr : ARM::ORRrr);
   7394 
   7395   case ARM::ATOMIC_LOAD_XOR_I8:
   7396      return EmitAtomicBinary(MI, BB, 1, isThumb2 ? ARM::t2EORrr : ARM::EORrr);
   7397   case ARM::ATOMIC_LOAD_XOR_I16:
   7398      return EmitAtomicBinary(MI, BB, 2, isThumb2 ? ARM::t2EORrr : ARM::EORrr);
   7399   case ARM::ATOMIC_LOAD_XOR_I32:
   7400      return EmitAtomicBinary(MI, BB, 4, isThumb2 ? ARM::t2EORrr : ARM::EORrr);
   7401 
   7402   case ARM::ATOMIC_LOAD_NAND_I8:
   7403      return EmitAtomicBinary(MI, BB, 1, isThumb2 ? ARM::t2BICrr : ARM::BICrr);
   7404   case ARM::ATOMIC_LOAD_NAND_I16:
   7405      return EmitAtomicBinary(MI, BB, 2, isThumb2 ? ARM::t2BICrr : ARM::BICrr);
   7406   case ARM::ATOMIC_LOAD_NAND_I32:
   7407      return EmitAtomicBinary(MI, BB, 4, isThumb2 ? ARM::t2BICrr : ARM::BICrr);
   7408 
   7409   case ARM::ATOMIC_LOAD_SUB_I8:
   7410      return EmitAtomicBinary(MI, BB, 1, isThumb2 ? ARM::t2SUBrr : ARM::SUBrr);
   7411   case ARM::ATOMIC_LOAD_SUB_I16:
   7412      return EmitAtomicBinary(MI, BB, 2, isThumb2 ? ARM::t2SUBrr : ARM::SUBrr);
   7413   case ARM::ATOMIC_LOAD_SUB_I32:
   7414      return EmitAtomicBinary(MI, BB, 4, isThumb2 ? ARM::t2SUBrr : ARM::SUBrr);
   7415 
   7416   case ARM::ATOMIC_LOAD_MIN_I8:
   7417      return EmitAtomicBinaryMinMax(MI, BB, 1, true, ARMCC::LT);
   7418   case ARM::ATOMIC_LOAD_MIN_I16:
   7419      return EmitAtomicBinaryMinMax(MI, BB, 2, true, ARMCC::LT);
   7420   case ARM::ATOMIC_LOAD_MIN_I32:
   7421      return EmitAtomicBinaryMinMax(MI, BB, 4, true, ARMCC::LT);
   7422 
   7423   case ARM::ATOMIC_LOAD_MAX_I8:
   7424      return EmitAtomicBinaryMinMax(MI, BB, 1, true, ARMCC::GT);
   7425   case ARM::ATOMIC_LOAD_MAX_I16:
   7426      return EmitAtomicBinaryMinMax(MI, BB, 2, true, ARMCC::GT);
   7427   case ARM::ATOMIC_LOAD_MAX_I32:
   7428      return EmitAtomicBinaryMinMax(MI, BB, 4, true, ARMCC::GT);
   7429 
   7430   case ARM::ATOMIC_LOAD_UMIN_I8:
   7431      return EmitAtomicBinaryMinMax(MI, BB, 1, false, ARMCC::LO);
   7432   case ARM::ATOMIC_LOAD_UMIN_I16:
   7433      return EmitAtomicBinaryMinMax(MI, BB, 2, false, ARMCC::LO);
   7434   case ARM::ATOMIC_LOAD_UMIN_I32:
   7435      return EmitAtomicBinaryMinMax(MI, BB, 4, false, ARMCC::LO);
   7436 
   7437   case ARM::ATOMIC_LOAD_UMAX_I8:
   7438      return EmitAtomicBinaryMinMax(MI, BB, 1, false, ARMCC::HI);
   7439   case ARM::ATOMIC_LOAD_UMAX_I16:
   7440      return EmitAtomicBinaryMinMax(MI, BB, 2, false, ARMCC::HI);
   7441   case ARM::ATOMIC_LOAD_UMAX_I32:
   7442      return EmitAtomicBinaryMinMax(MI, BB, 4, false, ARMCC::HI);
   7443 
   7444   case ARM::ATOMIC_SWAP_I8:  return EmitAtomicBinary(MI, BB, 1, 0);
   7445   case ARM::ATOMIC_SWAP_I16: return EmitAtomicBinary(MI, BB, 2, 0);
   7446   case ARM::ATOMIC_SWAP_I32: return EmitAtomicBinary(MI, BB, 4, 0);
   7447 
   7448   case ARM::ATOMIC_CMP_SWAP_I8:  return EmitAtomicCmpSwap(MI, BB, 1);
   7449   case ARM::ATOMIC_CMP_SWAP_I16: return EmitAtomicCmpSwap(MI, BB, 2);
   7450   case ARM::ATOMIC_CMP_SWAP_I32: return EmitAtomicCmpSwap(MI, BB, 4);
   7451 
   7452 
   7453   case ARM::ATOMADD6432:
   7454     return EmitAtomicBinary64(MI, BB, isThumb2 ? ARM::t2ADDrr : ARM::ADDrr,
   7455                               isThumb2 ? ARM::t2ADCrr : ARM::ADCrr,
   7456                               /*NeedsCarry*/ true);
   7457   case ARM::ATOMSUB6432:
   7458     return EmitAtomicBinary64(MI, BB, isThumb2 ? ARM::t2SUBrr : ARM::SUBrr,
   7459                               isThumb2 ? ARM::t2SBCrr : ARM::SBCrr,
   7460                               /*NeedsCarry*/ true);
   7461   case ARM::ATOMOR6432:
   7462     return EmitAtomicBinary64(MI, BB, isThumb2 ? ARM::t2ORRrr : ARM::ORRrr,
   7463                               isThumb2 ? ARM::t2ORRrr : ARM::ORRrr);
   7464   case ARM::ATOMXOR6432:
   7465     return EmitAtomicBinary64(MI, BB, isThumb2 ? ARM::t2EORrr : ARM::EORrr,
   7466                               isThumb2 ? ARM::t2EORrr : ARM::EORrr);
   7467   case ARM::ATOMAND6432:
   7468     return EmitAtomicBinary64(MI, BB, isThumb2 ? ARM::t2ANDrr : ARM::ANDrr,
   7469                               isThumb2 ? ARM::t2ANDrr : ARM::ANDrr);
   7470   case ARM::ATOMSWAP6432:
   7471     return EmitAtomicBinary64(MI, BB, 0, 0, false);
   7472   case ARM::ATOMCMPXCHG6432:
   7473     return EmitAtomicBinary64(MI, BB, isThumb2 ? ARM::t2SUBrr : ARM::SUBrr,
   7474                               isThumb2 ? ARM::t2SBCrr : ARM::SBCrr,
   7475                               /*NeedsCarry*/ false, /*IsCmpxchg*/true);
   7476   case ARM::ATOMMIN6432:
   7477     return EmitAtomicBinary64(MI, BB, isThumb2 ? ARM::t2SUBrr : ARM::SUBrr,
   7478                               isThumb2 ? ARM::t2SBCrr : ARM::SBCrr,
   7479                               /*NeedsCarry*/ true, /*IsCmpxchg*/false,
   7480                               /*IsMinMax*/ true, ARMCC::LT);
   7481   case ARM::ATOMMAX6432:
   7482     return EmitAtomicBinary64(MI, BB, isThumb2 ? ARM::t2SUBrr : ARM::SUBrr,
   7483                               isThumb2 ? ARM::t2SBCrr : ARM::SBCrr,
   7484                               /*NeedsCarry*/ true, /*IsCmpxchg*/false,
   7485                               /*IsMinMax*/ true, ARMCC::GE);
   7486   case ARM::ATOMUMIN6432:
   7487     return EmitAtomicBinary64(MI, BB, isThumb2 ? ARM::t2SUBrr : ARM::SUBrr,
   7488                               isThumb2 ? ARM::t2SBCrr : ARM::SBCrr,
   7489                               /*NeedsCarry*/ true, /*IsCmpxchg*/false,
   7490                               /*IsMinMax*/ true, ARMCC::LO);
   7491   case ARM::ATOMUMAX6432:
   7492     return EmitAtomicBinary64(MI, BB, isThumb2 ? ARM::t2SUBrr : ARM::SUBrr,
   7493                               isThumb2 ? ARM::t2SBCrr : ARM::SBCrr,
   7494                               /*NeedsCarry*/ true, /*IsCmpxchg*/false,
   7495                               /*IsMinMax*/ true, ARMCC::HS);
   7496 
   7497   case ARM::tMOVCCr_pseudo: {
   7498     // To "insert" a SELECT_CC instruction, we actually have to insert the
   7499     // diamond control-flow pattern.  The incoming instruction knows the
   7500     // destination vreg to set, the condition code register to branch on, the
   7501     // true/false values to select between, and a branch opcode to use.
   7502     const BasicBlock *LLVM_BB = BB->getBasicBlock();
   7503     MachineFunction::iterator It = BB;
   7504     ++It;
   7505 
   7506     //  thisMBB:
   7507     //  ...
   7508     //   TrueVal = ...
   7509     //   cmpTY ccX, r1, r2
   7510     //   bCC copy1MBB
   7511     //   fallthrough --> copy0MBB
   7512     MachineBasicBlock *thisMBB  = BB;
   7513     MachineFunction *F = BB->getParent();
   7514     MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
   7515     MachineBasicBlock *sinkMBB  = F->CreateMachineBasicBlock(LLVM_BB);
   7516     F->insert(It, copy0MBB);
   7517     F->insert(It, sinkMBB);
   7518 
   7519     // Transfer the remainder of BB and its successor edges to sinkMBB.
   7520     sinkMBB->splice(sinkMBB->begin(), BB,
   7521                     llvm::next(MachineBasicBlock::iterator(MI)),
   7522                     BB->end());
   7523     sinkMBB->transferSuccessorsAndUpdatePHIs(BB);
   7524 
   7525     BB->addSuccessor(copy0MBB);
   7526     BB->addSuccessor(sinkMBB);
   7527 
   7528     BuildMI(BB, dl, TII->get(ARM::tBcc)).addMBB(sinkMBB)
   7529       .addImm(MI->getOperand(3).getImm()).addReg(MI->getOperand(4).getReg());
   7530 
   7531     //  copy0MBB:
   7532     //   %FalseValue = ...
   7533     //   # fallthrough to sinkMBB
   7534     BB = copy0MBB;
   7535 
   7536     // Update machine-CFG edges
   7537     BB->addSuccessor(sinkMBB);
   7538 
   7539     //  sinkMBB:
   7540     //   %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
   7541     //  ...
   7542     BB = sinkMBB;
   7543     BuildMI(*BB, BB->begin(), dl,
   7544             TII->get(ARM::PHI), MI->getOperand(0).getReg())
   7545       .addReg(MI->getOperand(1).getReg()).addMBB(copy0MBB)
   7546       .addReg(MI->getOperand(2).getReg()).addMBB(thisMBB);
   7547 
   7548     MI->eraseFromParent();   // The pseudo instruction is gone now.
   7549     return BB;
   7550   }
   7551 
   7552   case ARM::BCCi64:
   7553   case ARM::BCCZi64: {
   7554     // If there is an unconditional branch to the other successor, remove it.
   7555     BB->erase(llvm::next(MachineBasicBlock::iterator(MI)), BB->end());
   7556 
   7557     // Compare both parts that make up the double comparison separately for
   7558     // equality.
   7559     bool RHSisZero = MI->getOpcode() == ARM::BCCZi64;
   7560 
   7561     unsigned LHS1 = MI->getOperand(1).getReg();
   7562     unsigned LHS2 = MI->getOperand(2).getReg();
   7563     if (RHSisZero) {
   7564       AddDefaultPred(BuildMI(BB, dl,
   7565                              TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri))
   7566                      .addReg(LHS1).addImm(0));
   7567       BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri))
   7568         .addReg(LHS2).addImm(0)
   7569         .addImm(ARMCC::EQ).addReg(ARM::CPSR);
   7570     } else {
   7571       unsigned RHS1 = MI->getOperand(3).getReg();
   7572       unsigned RHS2 = MI->getOperand(4).getReg();
   7573       AddDefaultPred(BuildMI(BB, dl,
   7574                              TII->get(isThumb2 ? ARM::t2CMPrr : ARM::CMPrr))
   7575                      .addReg(LHS1).addReg(RHS1));
   7576       BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPrr : ARM::CMPrr))
   7577         .addReg(LHS2).addReg(RHS2)
   7578         .addImm(ARMCC::EQ).addReg(ARM::CPSR);
   7579     }
   7580 
   7581     MachineBasicBlock *destMBB = MI->getOperand(RHSisZero ? 3 : 5).getMBB();
   7582     MachineBasicBlock *exitMBB = OtherSucc(BB, destMBB);
   7583     if (MI->getOperand(0).getImm() == ARMCC::NE)
   7584       std::swap(destMBB, exitMBB);
   7585 
   7586     BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc))
   7587       .addMBB(destMBB).addImm(ARMCC::EQ).addReg(ARM::CPSR);
   7588     if (isThumb2)
   7589       AddDefaultPred(BuildMI(BB, dl, TII->get(ARM::t2B)).addMBB(exitMBB));
   7590     else
   7591       BuildMI(BB, dl, TII->get(ARM::B)) .addMBB(exitMBB);
   7592 
   7593     MI->eraseFromParent();   // The pseudo instruction is gone now.
   7594     return BB;
   7595   }
   7596 
   7597   case ARM::Int_eh_sjlj_setjmp:
   7598   case ARM::Int_eh_sjlj_setjmp_nofp:
   7599   case ARM::tInt_eh_sjlj_setjmp:
   7600   case ARM::t2Int_eh_sjlj_setjmp:
   7601   case ARM::t2Int_eh_sjlj_setjmp_nofp:
   7602     EmitSjLjDispatchBlock(MI, BB);
   7603     return BB;
   7604 
   7605   case ARM::ABS:
   7606   case ARM::t2ABS: {
   7607     // To insert an ABS instruction, we have to insert the
   7608     // diamond control-flow pattern.  The incoming instruction knows the
   7609     // source vreg to test against 0, the destination vreg to set,
   7610     // the condition code register to branch on, the
   7611     // true/false values to select between, and a branch opcode to use.
   7612     // It transforms
   7613     //     V1 = ABS V0
   7614     // into
   7615     //     V2 = MOVS V0
   7616     //     BCC                      (branch to SinkBB if V0 >= 0)
   7617     //     RSBBB: V3 = RSBri V2, 0  (compute ABS if V2 < 0)
   7618     //     SinkBB: V1 = PHI(V2, V3)
   7619     const BasicBlock *LLVM_BB = BB->getBasicBlock();
   7620     MachineFunction::iterator BBI = BB;
   7621     ++BBI;
   7622     MachineFunction *Fn = BB->getParent();
   7623     MachineBasicBlock *RSBBB = Fn->CreateMachineBasicBlock(LLVM_BB);
   7624     MachineBasicBlock *SinkBB  = Fn->CreateMachineBasicBlock(LLVM_BB);
   7625     Fn->insert(BBI, RSBBB);
   7626     Fn->insert(BBI, SinkBB);
   7627 
   7628     unsigned int ABSSrcReg = MI->getOperand(1).getReg();
   7629     unsigned int ABSDstReg = MI->getOperand(0).getReg();
   7630     bool isThumb2 = Subtarget->isThumb2();
   7631     MachineRegisterInfo &MRI = Fn->getRegInfo();
   7632     // In Thumb mode S must not be specified if source register is the SP or
   7633     // PC and if destination register is the SP, so restrict register class
   7634     unsigned NewRsbDstReg = MRI.createVirtualRegister(isThumb2 ?
   7635       (const TargetRegisterClass*)&ARM::rGPRRegClass :
   7636       (const TargetRegisterClass*)&ARM::GPRRegClass);
   7637 
   7638     // Transfer the remainder of BB and its successor edges to sinkMBB.
   7639     SinkBB->splice(SinkBB->begin(), BB,
   7640       llvm::next(MachineBasicBlock::iterator(MI)),
   7641       BB->end());
   7642     SinkBB->transferSuccessorsAndUpdatePHIs(BB);
   7643 
   7644     BB->addSuccessor(RSBBB);
   7645     BB->addSuccessor(SinkBB);
   7646 
   7647     // fall through to SinkMBB
   7648     RSBBB->addSuccessor(SinkBB);
   7649 
   7650     // insert a cmp at the end of BB
   7651     AddDefaultPred(BuildMI(BB, dl,
   7652                            TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri))
   7653                    .addReg(ABSSrcReg).addImm(0));
   7654 
   7655     // insert a bcc with opposite CC to ARMCC::MI at the end of BB
   7656     BuildMI(BB, dl,
   7657       TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc)).addMBB(SinkBB)
   7658       .addImm(ARMCC::getOppositeCondition(ARMCC::MI)).addReg(ARM::CPSR);
   7659 
   7660     // insert rsbri in RSBBB
   7661     // Note: BCC and rsbri will be converted into predicated rsbmi
   7662     // by if-conversion pass
   7663     BuildMI(*RSBBB, RSBBB->begin(), dl,
   7664       TII->get(isThumb2 ? ARM::t2RSBri : ARM::RSBri), NewRsbDstReg)
   7665       .addReg(ABSSrcReg, RegState::Kill)
   7666       .addImm(0).addImm((unsigned)ARMCC::AL).addReg(0).addReg(0);
   7667 
   7668     // insert PHI in SinkBB,
   7669     // reuse ABSDstReg to not change uses of ABS instruction
   7670     BuildMI(*SinkBB, SinkBB->begin(), dl,
   7671       TII->get(ARM::PHI), ABSDstReg)
   7672       .addReg(NewRsbDstReg).addMBB(RSBBB)
   7673       .addReg(ABSSrcReg).addMBB(BB);
   7674 
   7675     // remove ABS instruction
   7676     MI->eraseFromParent();
   7677 
   7678     // return last added BB
   7679     return SinkBB;
   7680   }
   7681   case ARM::COPY_STRUCT_BYVAL_I32:
   7682     ++NumLoopByVals;
   7683     return EmitStructByval(MI, BB);
   7684   }
   7685 }
   7686 
   7687 void ARMTargetLowering::AdjustInstrPostInstrSelection(MachineInstr *MI,
   7688                                                       SDNode *Node) const {
   7689   if (!MI->hasPostISelHook()) {
   7690     assert(!convertAddSubFlagsOpcode(MI->getOpcode()) &&
   7691            "Pseudo flag-setting opcodes must be marked with 'hasPostISelHook'");
   7692     return;
   7693   }
   7694 
   7695   const MCInstrDesc *MCID = &MI->getDesc();
   7696   // Adjust potentially 's' setting instructions after isel, i.e. ADC, SBC, RSB,
   7697   // RSC. Coming out of isel, they have an implicit CPSR def, but the optional
   7698   // operand is still set to noreg. If needed, set the optional operand's
   7699   // register to CPSR, and remove the redundant implicit def.
   7700   //
   7701   // e.g. ADCS (..., CPSR<imp-def>) -> ADC (... opt:CPSR<def>).
   7702 
   7703   // Rename pseudo opcodes.
   7704   unsigned NewOpc = convertAddSubFlagsOpcode(MI->getOpcode());
   7705   if (NewOpc) {
   7706     const ARMBaseInstrInfo *TII =
   7707       static_cast<const ARMBaseInstrInfo*>(getTargetMachine().getInstrInfo());
   7708     MCID = &TII->get(NewOpc);
   7709 
   7710     assert(MCID->getNumOperands() == MI->getDesc().getNumOperands() + 1 &&
   7711            "converted opcode should be the same except for cc_out");
   7712 
   7713     MI->setDesc(*MCID);
   7714 
   7715     // Add the optional cc_out operand
   7716     MI->addOperand(MachineOperand::CreateReg(0, /*isDef=*/true));
   7717   }
   7718   unsigned ccOutIdx = MCID->getNumOperands() - 1;
   7719 
   7720   // Any ARM instruction that sets the 's' bit should specify an optional
   7721   // "cc_out" operand in the last operand position.
   7722   if (!MI->hasOptionalDef() || !MCID->OpInfo[ccOutIdx].isOptionalDef()) {
   7723     assert(!NewOpc && "Optional cc_out operand required");
   7724     return;
   7725   }
   7726   // Look for an implicit def of CPSR added by MachineInstr ctor. Remove it
   7727   // since we already have an optional CPSR def.
   7728   bool definesCPSR = false;
   7729   bool deadCPSR = false;
   7730   for (unsigned i = MCID->getNumOperands(), e = MI->getNumOperands();
   7731        i != e; ++i) {
   7732     const MachineOperand &MO = MI->getOperand(i);
   7733     if (MO.isReg() && MO.isDef() && MO.getReg() == ARM::CPSR) {
   7734       definesCPSR = true;
   7735       if (MO.isDead())
   7736         deadCPSR = true;
   7737       MI->RemoveOperand(i);
   7738       break;
   7739     }
   7740   }
   7741   if (!definesCPSR) {
   7742     assert(!NewOpc && "Optional cc_out operand required");
   7743     return;
   7744   }
   7745   assert(deadCPSR == !Node->hasAnyUseOfValue(1) && "inconsistent dead flag");
   7746   if (deadCPSR) {
   7747     assert(!MI->getOperand(ccOutIdx).getReg() &&
   7748            "expect uninitialized optional cc_out operand");
   7749     return;
   7750   }
   7751 
   7752   // If this instruction was defined with an optional CPSR def and its dag node
   7753   // had a live implicit CPSR def, then activate the optional CPSR def.
   7754   MachineOperand &MO = MI->getOperand(ccOutIdx);
   7755   MO.setReg(ARM::CPSR);
   7756   MO.setIsDef(true);
   7757 }
   7758 
   7759 //===----------------------------------------------------------------------===//
   7760 //                           ARM Optimization Hooks
   7761 //===----------------------------------------------------------------------===//
   7762 
   7763 // Helper function that checks if N is a null or all ones constant.
   7764 static inline bool isZeroOrAllOnes(SDValue N, bool AllOnes) {
   7765   ConstantSDNode *C = dyn_cast<ConstantSDNode>(N);
   7766   if (!C)
   7767     return false;
   7768   return AllOnes ? C->isAllOnesValue() : C->isNullValue();
   7769 }
   7770 
   7771 // Return true if N is conditionally 0 or all ones.
   7772 // Detects these expressions where cc is an i1 value:
   7773 //
   7774 //   (select cc 0, y)   [AllOnes=0]
   7775 //   (select cc y, 0)   [AllOnes=0]
   7776 //   (zext cc)          [AllOnes=0]
   7777 //   (sext cc)          [AllOnes=0/1]
   7778 //   (select cc -1, y)  [AllOnes=1]
   7779 //   (select cc y, -1)  [AllOnes=1]
   7780 //
   7781 // Invert is set when N is the null/all ones constant when CC is false.
   7782 // OtherOp is set to the alternative value of N.
   7783 static bool isConditionalZeroOrAllOnes(SDNode *N, bool AllOnes,
   7784                                        SDValue &CC, bool &Invert,
   7785                                        SDValue &OtherOp,
   7786                                        SelectionDAG &DAG) {
   7787   switch (N->getOpcode()) {
   7788   default: return false;
   7789   case ISD::SELECT: {
   7790     CC = N->getOperand(0);
   7791     SDValue N1 = N->getOperand(1);
   7792     SDValue N2 = N->getOperand(2);
   7793     if (isZeroOrAllOnes(N1, AllOnes)) {
   7794       Invert = false;
   7795       OtherOp = N2;
   7796       return true;
   7797     }
   7798     if (isZeroOrAllOnes(N2, AllOnes)) {
   7799       Invert = true;
   7800       OtherOp = N1;
   7801       return true;
   7802     }
   7803     return false;
   7804   }
   7805   case ISD::ZERO_EXTEND:
   7806     // (zext cc) can never be the all ones value.
   7807     if (AllOnes)
   7808       return false;
   7809     // Fall through.
   7810   case ISD::SIGN_EXTEND: {
   7811     EVT VT = N->getValueType(0);
   7812     CC = N->getOperand(0);
   7813     if (CC.getValueType() != MVT::i1)
   7814       return false;
   7815     Invert = !AllOnes;
   7816     if (AllOnes)
   7817       // When looking for an AllOnes constant, N is an sext, and the 'other'
   7818       // value is 0.
   7819       OtherOp = DAG.getConstant(0, VT);
   7820     else if (N->getOpcode() == ISD::ZERO_EXTEND)
   7821       // When looking for a 0 constant, N can be zext or sext.
   7822       OtherOp = DAG.getConstant(1, VT);
   7823     else
   7824       OtherOp = DAG.getConstant(APInt::getAllOnesValue(VT.getSizeInBits()), VT);
   7825     return true;
   7826   }
   7827   }
   7828 }
   7829 
   7830 // Combine a constant select operand into its use:
   7831 //
   7832 //   (add (select cc, 0, c), x)  -> (select cc, x, (add, x, c))
   7833 //   (sub x, (select cc, 0, c))  -> (select cc, x, (sub, x, c))
   7834 //   (and (select cc, -1, c), x) -> (select cc, x, (and, x, c))  [AllOnes=1]
   7835 //   (or  (select cc, 0, c), x)  -> (select cc, x, (or, x, c))
   7836 //   (xor (select cc, 0, c), x)  -> (select cc, x, (xor, x, c))
   7837 //
   7838 // The transform is rejected if the select doesn't have a constant operand that
   7839 // is null, or all ones when AllOnes is set.
   7840 //
   7841 // Also recognize sext/zext from i1:
   7842 //
   7843 //   (add (zext cc), x) -> (select cc (add x, 1), x)
   7844 //   (add (sext cc), x) -> (select cc (add x, -1), x)
   7845 //
   7846 // These transformations eventually create predicated instructions.
   7847 //
   7848 // @param N       The node to transform.
   7849 // @param Slct    The N operand that is a select.
   7850 // @param OtherOp The other N operand (x above).
   7851 // @param DCI     Context.
   7852 // @param AllOnes Require the select constant to be all ones instead of null.
   7853 // @returns The new node, or SDValue() on failure.
   7854 static
   7855 SDValue combineSelectAndUse(SDNode *N, SDValue Slct, SDValue OtherOp,
   7856                             TargetLowering::DAGCombinerInfo &DCI,
   7857                             bool AllOnes = false) {
   7858   SelectionDAG &DAG = DCI.DAG;
   7859   EVT VT = N->getValueType(0);
   7860   SDValue NonConstantVal;
   7861   SDValue CCOp;
   7862   bool SwapSelectOps;
   7863   if (!isConditionalZeroOrAllOnes(Slct.getNode(), AllOnes, CCOp, SwapSelectOps,
   7864                                   NonConstantVal, DAG))
   7865     return SDValue();
   7866 
   7867   // Slct is now know to be the desired identity constant when CC is true.
   7868   SDValue TrueVal = OtherOp;
   7869   SDValue FalseVal = DAG.getNode(N->getOpcode(), SDLoc(N), VT,
   7870                                  OtherOp, NonConstantVal);
   7871   // Unless SwapSelectOps says CC should be false.
   7872   if (SwapSelectOps)
   7873     std::swap(TrueVal, FalseVal);
   7874 
   7875   return DAG.getNode(ISD::SELECT, SDLoc(N), VT,
   7876                      CCOp, TrueVal, FalseVal);
   7877 }
   7878 
   7879 // Attempt combineSelectAndUse on each operand of a commutative operator N.
   7880 static
   7881 SDValue combineSelectAndUseCommutative(SDNode *N, bool AllOnes,
   7882                                        TargetLowering::DAGCombinerInfo &DCI) {
   7883   SDValue N0 = N->getOperand(0);
   7884   SDValue N1 = N->getOperand(1);
   7885   if (N0.getNode()->hasOneUse()) {
   7886     SDValue Result = combineSelectAndUse(N, N0, N1, DCI, AllOnes);
   7887     if (Result.getNode())
   7888       return Result;
   7889   }
   7890   if (N1.getNode()->hasOneUse()) {
   7891     SDValue Result = combineSelectAndUse(N, N1, N0, DCI, AllOnes);
   7892     if (Result.getNode())
   7893       return Result;
   7894   }
   7895   return SDValue();
   7896 }
   7897 
   7898 // AddCombineToVPADDL- For pair-wise add on neon, use the vpaddl instruction
   7899 // (only after legalization).
   7900 static SDValue AddCombineToVPADDL(SDNode *N, SDValue N0, SDValue N1,
   7901                                  TargetLowering::DAGCombinerInfo &DCI,
   7902                                  const ARMSubtarget *Subtarget) {
   7903 
   7904   // Only perform optimization if after legalize, and if NEON is available. We
   7905   // also expected both operands to be BUILD_VECTORs.
   7906   if (DCI.isBeforeLegalize() || !Subtarget->hasNEON()
   7907       || N0.getOpcode() != ISD::BUILD_VECTOR
   7908       || N1.getOpcode() != ISD::BUILD_VECTOR)
   7909     return SDValue();
   7910 
   7911   // Check output type since VPADDL operand elements can only be 8, 16, or 32.
   7912   EVT VT = N->getValueType(0);
   7913   if (!VT.isInteger() || VT.getVectorElementType() == MVT::i64)
   7914     return SDValue();
   7915 
   7916   // Check that the vector operands are of the right form.
   7917   // N0 and N1 are BUILD_VECTOR nodes with N number of EXTRACT_VECTOR
   7918   // operands, where N is the size of the formed vector.
   7919   // Each EXTRACT_VECTOR should have the same input vector and odd or even
   7920   // index such that we have a pair wise add pattern.
   7921 
   7922   // Grab the vector that all EXTRACT_VECTOR nodes should be referencing.
   7923   if (N0->getOperand(0)->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
   7924     return SDValue();
   7925   SDValue Vec = N0->getOperand(0)->getOperand(0);
   7926   SDNode *V = Vec.getNode();
   7927   unsigned nextIndex = 0;
   7928 
   7929   // For each operands to the ADD which are BUILD_VECTORs,
   7930   // check to see if each of their operands are an EXTRACT_VECTOR with
   7931   // the same vector and appropriate index.
   7932   for (unsigned i = 0, e = N0->getNumOperands(); i != e; ++i) {
   7933     if (N0->getOperand(i)->getOpcode() == ISD::EXTRACT_VECTOR_ELT
   7934         && N1->getOperand(i)->getOpcode() == ISD::EXTRACT_VECTOR_ELT) {
   7935 
   7936       SDValue ExtVec0 = N0->getOperand(i);
   7937       SDValue ExtVec1 = N1->getOperand(i);
   7938 
   7939       // First operand is the vector, verify its the same.
   7940       if (V != ExtVec0->getOperand(0).getNode() ||
   7941           V != ExtVec1->getOperand(0).getNode())
   7942         return SDValue();
   7943 
   7944       // Second is the constant, verify its correct.
   7945       ConstantSDNode *C0 = dyn_cast<ConstantSDNode>(ExtVec0->getOperand(1));
   7946       ConstantSDNode *C1 = dyn_cast<ConstantSDNode>(ExtVec1->getOperand(1));
   7947 
   7948       // For the constant, we want to see all the even or all the odd.
   7949       if (!C0 || !C1 || C0->getZExtValue() != nextIndex
   7950           || C1->getZExtValue() != nextIndex+1)
   7951         return SDValue();
   7952 
   7953       // Increment index.
   7954       nextIndex+=2;
   7955     } else
   7956       return SDValue();
   7957   }
   7958 
   7959   // Create VPADDL node.
   7960   SelectionDAG &DAG = DCI.DAG;
   7961   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
   7962 
   7963   // Build operand list.
   7964   SmallVector<SDValue, 8> Ops;
   7965   Ops.push_back(DAG.getConstant(Intrinsic::arm_neon_vpaddls,
   7966                                 TLI.getPointerTy()));
   7967 
   7968   // Input is the vector.
   7969   Ops.push_back(Vec);
   7970 
   7971   // Get widened type and narrowed type.
   7972   MVT widenType;
   7973   unsigned numElem = VT.getVectorNumElements();
   7974   switch (VT.getVectorElementType().getSimpleVT().SimpleTy) {
   7975     case MVT::i8: widenType = MVT::getVectorVT(MVT::i16, numElem); break;
   7976     case MVT::i16: widenType = MVT::getVectorVT(MVT::i32, numElem); break;
   7977     case MVT::i32: widenType = MVT::getVectorVT(MVT::i64, numElem); break;
   7978     default:
   7979       llvm_unreachable("Invalid vector element type for padd optimization.");
   7980   }
   7981 
   7982   SDValue tmp = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, SDLoc(N),
   7983                             widenType, &Ops[0], Ops.size());
   7984   return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, tmp);
   7985 }
   7986 
   7987 static SDValue findMUL_LOHI(SDValue V) {
   7988   if (V->getOpcode() == ISD::UMUL_LOHI ||
   7989       V->getOpcode() == ISD::SMUL_LOHI)
   7990     return V;
   7991   return SDValue();
   7992 }
   7993 
   7994 static SDValue AddCombineTo64bitMLAL(SDNode *AddcNode,
   7995                                      TargetLowering::DAGCombinerInfo &DCI,
   7996                                      const ARMSubtarget *Subtarget) {
   7997 
   7998   if (Subtarget->isThumb1Only()) return SDValue();
   7999 
   8000   // Only perform the checks after legalize when the pattern is available.
   8001   if (DCI.isBeforeLegalize()) return SDValue();
   8002 
   8003   // Look for multiply add opportunities.
   8004   // The pattern is a ISD::UMUL_LOHI followed by two add nodes, where
   8005   // each add nodes consumes a value from ISD::UMUL_LOHI and there is
   8006   // a glue link from the first add to the second add.
   8007   // If we find this pattern, we can replace the U/SMUL_LOHI, ADDC, and ADDE by
   8008   // a S/UMLAL instruction.
   8009   //          loAdd   UMUL_LOHI
   8010   //            \    / :lo    \ :hi
   8011   //             \  /          \          [no multiline comment]
   8012   //              ADDC         |  hiAdd
   8013   //                 \ :glue  /  /
   8014   //                  \      /  /
   8015   //                    ADDE
   8016   //
   8017   assert(AddcNode->getOpcode() == ISD::ADDC && "Expect an ADDC");
   8018   SDValue AddcOp0 = AddcNode->getOperand(0);
   8019   SDValue AddcOp1 = AddcNode->getOperand(1);
   8020 
   8021   // Check if the two operands are from the same mul_lohi node.
   8022   if (AddcOp0.getNode() == AddcOp1.getNode())
   8023     return SDValue();
   8024 
   8025   assert(AddcNode->getNumValues() == 2 &&
   8026          AddcNode->getValueType(0) == MVT::i32 &&
   8027          "Expect ADDC with two result values. First: i32");
   8028 
   8029   // Check that we have a glued ADDC node.
   8030   if (AddcNode->getValueType(1) != MVT::Glue)
   8031     return SDValue();
   8032 
   8033   // Check that the ADDC adds the low result of the S/UMUL_LOHI.
   8034   if (AddcOp0->getOpcode() != ISD::UMUL_LOHI &&
   8035       AddcOp0->getOpcode() != ISD::SMUL_LOHI &&
   8036       AddcOp1->getOpcode() != ISD::UMUL_LOHI &&
   8037       AddcOp1->getOpcode() != ISD::SMUL_LOHI)
   8038     return SDValue();
   8039 
   8040   // Look for the glued ADDE.
   8041   SDNode* AddeNode = AddcNode->getGluedUser();
   8042   if (AddeNode == NULL)
   8043     return SDValue();
   8044 
   8045   // Make sure it is really an ADDE.
   8046   if (AddeNode->getOpcode() != ISD::ADDE)
   8047     return SDValue();
   8048 
   8049   assert(AddeNode->getNumOperands() == 3 &&
   8050          AddeNode->getOperand(2).getValueType() == MVT::Glue &&
   8051          "ADDE node has the wrong inputs");
   8052 
   8053   // Check for the triangle shape.
   8054   SDValue AddeOp0 = AddeNode->getOperand(0);
   8055   SDValue AddeOp1 = AddeNode->getOperand(1);
   8056 
   8057   // Make sure that the ADDE operands are not coming from the same node.
   8058   if (AddeOp0.getNode() == AddeOp1.getNode())
   8059     return SDValue();
   8060 
   8061   // Find the MUL_LOHI node walking up ADDE's operands.
   8062   bool IsLeftOperandMUL = false;
   8063   SDValue MULOp = findMUL_LOHI(AddeOp0);
   8064   if (MULOp == SDValue())
   8065    MULOp = findMUL_LOHI(AddeOp1);
   8066   else
   8067     IsLeftOperandMUL = true;
   8068   if (MULOp == SDValue())
   8069      return SDValue();
   8070 
   8071   // Figure out the right opcode.
   8072   unsigned Opc = MULOp->getOpcode();
   8073   unsigned FinalOpc = (Opc == ISD::SMUL_LOHI) ? ARMISD::SMLAL : ARMISD::UMLAL;
   8074 
   8075   // Figure out the high and low input values to the MLAL node.
   8076   SDValue* HiMul = &MULOp;
   8077   SDValue* HiAdd = NULL;
   8078   SDValue* LoMul = NULL;
   8079   SDValue* LowAdd = NULL;
   8080 
   8081   if (IsLeftOperandMUL)
   8082     HiAdd = &AddeOp1;
   8083   else
   8084     HiAdd = &AddeOp0;
   8085 
   8086 
   8087   if (AddcOp0->getOpcode() == Opc) {
   8088     LoMul = &AddcOp0;
   8089     LowAdd = &AddcOp1;
   8090   }
   8091   if (AddcOp1->getOpcode() == Opc) {
   8092     LoMul = &AddcOp1;
   8093     LowAdd = &AddcOp0;
   8094   }
   8095 
   8096   if (LoMul == NULL)
   8097     return SDValue();
   8098 
   8099   if (LoMul->getNode() != HiMul->getNode())
   8100     return SDValue();
   8101 
   8102   // Create the merged node.
   8103   SelectionDAG &DAG = DCI.DAG;
   8104 
   8105   // Build operand list.
   8106   SmallVector<SDValue, 8> Ops;
   8107   Ops.push_back(LoMul->getOperand(0));
   8108   Ops.push_back(LoMul->getOperand(1));
   8109   Ops.push_back(*LowAdd);
   8110   Ops.push_back(*HiAdd);
   8111 
   8112   SDValue MLALNode =  DAG.getNode(FinalOpc, SDLoc(AddcNode),
   8113                                  DAG.getVTList(MVT::i32, MVT::i32),
   8114                                  &Ops[0], Ops.size());
   8115 
   8116   // Replace the ADDs' nodes uses by the MLA node's values.
   8117   SDValue HiMLALResult(MLALNode.getNode(), 1);
   8118   DAG.ReplaceAllUsesOfValueWith(SDValue(AddeNode, 0), HiMLALResult);
   8119 
   8120   SDValue LoMLALResult(MLALNode.getNode(), 0);
   8121   DAG.ReplaceAllUsesOfValueWith(SDValue(AddcNode, 0), LoMLALResult);
   8122 
   8123   // Return original node to notify the driver to stop replacing.
   8124   SDValue resNode(AddcNode, 0);
   8125   return resNode;
   8126 }
   8127 
   8128 /// PerformADDCCombine - Target-specific dag combine transform from
   8129 /// ISD::ADDC, ISD::ADDE, and ISD::MUL_LOHI to MLAL.
   8130 static SDValue PerformADDCCombine(SDNode *N,
   8131                                  TargetLowering::DAGCombinerInfo &DCI,
   8132                                  const ARMSubtarget *Subtarget) {
   8133 
   8134   return AddCombineTo64bitMLAL(N, DCI, Subtarget);
   8135 
   8136 }
   8137 
   8138 /// PerformADDCombineWithOperands - Try DAG combinations for an ADD with
   8139 /// operands N0 and N1.  This is a helper for PerformADDCombine that is
   8140 /// called with the default operands, and if that fails, with commuted
   8141 /// operands.
   8142 static SDValue PerformADDCombineWithOperands(SDNode *N, SDValue N0, SDValue N1,
   8143                                           TargetLowering::DAGCombinerInfo &DCI,
   8144                                           const ARMSubtarget *Subtarget){
   8145 
   8146   // Attempt to create vpaddl for this add.
   8147   SDValue Result = AddCombineToVPADDL(N, N0, N1, DCI, Subtarget);
   8148   if (Result.getNode())
   8149     return Result;
   8150 
   8151   // fold (add (select cc, 0, c), x) -> (select cc, x, (add, x, c))
   8152   if (N0.getNode()->hasOneUse()) {
   8153     SDValue Result = combineSelectAndUse(N, N0, N1, DCI);
   8154     if (Result.getNode()) return Result;
   8155   }
   8156   return SDValue();
   8157 }
   8158 
   8159 /// PerformADDCombine - Target-specific dag combine xforms for ISD::ADD.
   8160 ///
   8161 static SDValue PerformADDCombine(SDNode *N,
   8162                                  TargetLowering::DAGCombinerInfo &DCI,
   8163                                  const ARMSubtarget *Subtarget) {
   8164   SDValue N0 = N->getOperand(0);
   8165   SDValue N1 = N->getOperand(1);
   8166 
   8167   // First try with the default operand order.
   8168   SDValue Result = PerformADDCombineWithOperands(N, N0, N1, DCI, Subtarget);
   8169   if (Result.getNode())
   8170     return Result;
   8171 
   8172   // If that didn't work, try again with the operands commuted.
   8173   return PerformADDCombineWithOperands(N, N1, N0, DCI, Subtarget);
   8174 }
   8175 
   8176 /// PerformSUBCombine - Target-specific dag combine xforms for ISD::SUB.
   8177 ///
   8178 static SDValue PerformSUBCombine(SDNode *N,
   8179                                  TargetLowering::DAGCombinerInfo &DCI) {
   8180   SDValue N0 = N->getOperand(0);
   8181   SDValue N1 = N->getOperand(1);
   8182 
   8183   // fold (sub x, (select cc, 0, c)) -> (select cc, x, (sub, x, c))
   8184   if (N1.getNode()->hasOneUse()) {
   8185     SDValue Result = combineSelectAndUse(N, N1, N0, DCI);
   8186     if (Result.getNode()) return Result;
   8187   }
   8188 
   8189   return SDValue();
   8190 }
   8191 
   8192 /// PerformVMULCombine
   8193 /// Distribute (A + B) * C to (A * C) + (B * C) to take advantage of the
   8194 /// special multiplier accumulator forwarding.
   8195 ///   vmul d3, d0, d2
   8196 ///   vmla d3, d1, d2
   8197 /// is faster than
   8198 ///   vadd d3, d0, d1
   8199 ///   vmul d3, d3, d2
   8200 static SDValue PerformVMULCombine(SDNode *N,
   8201                                   TargetLowering::DAGCombinerInfo &DCI,
   8202                                   const ARMSubtarget *Subtarget) {
   8203   if (!Subtarget->hasVMLxForwarding())
   8204     return SDValue();
   8205 
   8206   SelectionDAG &DAG = DCI.DAG;
   8207   SDValue N0 = N->getOperand(0);
   8208   SDValue N1 = N->getOperand(1);
   8209   unsigned Opcode = N0.getOpcode();
   8210   if (Opcode != ISD::ADD && Opcode != ISD::SUB &&
   8211       Opcode != ISD::FADD && Opcode != ISD::FSUB) {
   8212     Opcode = N1.getOpcode();
   8213     if (Opcode != ISD::ADD && Opcode != ISD::SUB &&
   8214         Opcode != ISD::FADD && Opcode != ISD::FSUB)
   8215       return SDValue();
   8216     std::swap(N0, N1);
   8217   }
   8218 
   8219   EVT VT = N->getValueType(0);
   8220   SDLoc DL(N);
   8221   SDValue N00 = N0->getOperand(0);
   8222   SDValue N01 = N0->getOperand(1);
   8223   return DAG.getNode(Opcode, DL, VT,
   8224                      DAG.getNode(ISD::MUL, DL, VT, N00, N1),
   8225                      DAG.getNode(ISD::MUL, DL, VT, N01, N1));
   8226 }
   8227 
   8228 static SDValue PerformMULCombine(SDNode *N,
   8229                                  TargetLowering::DAGCombinerInfo &DCI,
   8230                                  const ARMSubtarget *Subtarget) {
   8231   SelectionDAG &DAG = DCI.DAG;
   8232 
   8233   if (Subtarget->isThumb1Only())
   8234     return SDValue();
   8235 
   8236   if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
   8237     return SDValue();
   8238 
   8239   EVT VT = N->getValueType(0);
   8240   if (VT.is64BitVector() || VT.is128BitVector())
   8241     return PerformVMULCombine(N, DCI, Subtarget);
   8242   if (VT != MVT::i32)
   8243     return SDValue();
   8244 
   8245   ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(1));
   8246   if (!C)
   8247     return SDValue();
   8248 
   8249   int64_t MulAmt = C->getSExtValue();
   8250   unsigned ShiftAmt = countTrailingZeros<uint64_t>(MulAmt);
   8251 
   8252   ShiftAmt = ShiftAmt & (32 - 1);
   8253   SDValue V = N->getOperand(0);
   8254   SDLoc DL(N);
   8255 
   8256   SDValue Res;
   8257   MulAmt >>= ShiftAmt;
   8258 
   8259   if (MulAmt >= 0) {
   8260     if (isPowerOf2_32(MulAmt - 1)) {
   8261       // (mul x, 2^N + 1) => (add (shl x, N), x)
   8262       Res = DAG.getNode(ISD::ADD, DL, VT,
   8263                         V,
   8264                         DAG.getNode(ISD::SHL, DL, VT,
   8265                                     V,
   8266                                     DAG.getConstant(Log2_32(MulAmt - 1),
   8267                                                     MVT::i32)));
   8268     } else if (isPowerOf2_32(MulAmt + 1)) {
   8269       // (mul x, 2^N - 1) => (sub (shl x, N), x)
   8270       Res = DAG.getNode(ISD::SUB, DL, VT,
   8271                         DAG.getNode(ISD::SHL, DL, VT,
   8272                                     V,
   8273                                     DAG.getConstant(Log2_32(MulAmt + 1),
   8274                                                     MVT::i32)),
   8275                         V);
   8276     } else
   8277       return SDValue();
   8278   } else {
   8279     uint64_t MulAmtAbs = -MulAmt;
   8280     if (isPowerOf2_32(MulAmtAbs + 1)) {
   8281       // (mul x, -(2^N - 1)) => (sub x, (shl x, N))
   8282       Res = DAG.getNode(ISD::SUB, DL, VT,
   8283                         V,
   8284                         DAG.getNode(ISD::SHL, DL, VT,
   8285                                     V,
   8286                                     DAG.getConstant(Log2_32(MulAmtAbs + 1),
   8287                                                     MVT::i32)));
   8288     } else if (isPowerOf2_32(MulAmtAbs - 1)) {
   8289       // (mul x, -(2^N + 1)) => - (add (shl x, N), x)
   8290       Res = DAG.getNode(ISD::ADD, DL, VT,
   8291                         V,
   8292                         DAG.getNode(ISD::SHL, DL, VT,
   8293                                     V,
   8294                                     DAG.getConstant(Log2_32(MulAmtAbs-1),
   8295                                                     MVT::i32)));
   8296       Res = DAG.getNode(ISD::SUB, DL, VT,
   8297                         DAG.getConstant(0, MVT::i32),Res);
   8298 
   8299     } else
   8300       return SDValue();
   8301   }
   8302 
   8303   if (ShiftAmt != 0)
   8304     Res = DAG.getNode(ISD::SHL, DL, VT,
   8305                       Res, DAG.getConstant(ShiftAmt, MVT::i32));
   8306 
   8307   // Do not add new nodes to DAG combiner worklist.
   8308   DCI.CombineTo(N, Res, false);
   8309   return SDValue();
   8310 }
   8311 
   8312 static SDValue PerformANDCombine(SDNode *N,
   8313                                  TargetLowering::DAGCombinerInfo &DCI,
   8314                                  const ARMSubtarget *Subtarget) {
   8315 
   8316   // Attempt to use immediate-form VBIC
   8317   BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(N->getOperand(1));
   8318   SDLoc dl(N);
   8319   EVT VT = N->getValueType(0);
   8320   SelectionDAG &DAG = DCI.DAG;
   8321 
   8322   if(!DAG.getTargetLoweringInfo().isTypeLegal(VT))
   8323     return SDValue();
   8324 
   8325   APInt SplatBits, SplatUndef;
   8326   unsigned SplatBitSize;
   8327   bool HasAnyUndefs;
   8328   if (BVN &&
   8329       BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs)) {
   8330     if (SplatBitSize <= 64) {
   8331       EVT VbicVT;
   8332       SDValue Val = isNEONModifiedImm((~SplatBits).getZExtValue(),
   8333                                       SplatUndef.getZExtValue(), SplatBitSize,
   8334                                       DAG, VbicVT, VT.is128BitVector(),
   8335                                       OtherModImm);
   8336       if (Val.getNode()) {
   8337         SDValue Input =
   8338           DAG.getNode(ISD::BITCAST, dl, VbicVT, N->getOperand(0));
   8339         SDValue Vbic = DAG.getNode(ARMISD::VBICIMM, dl, VbicVT, Input, Val);
   8340         return DAG.getNode(ISD::BITCAST, dl, VT, Vbic);
   8341       }
   8342     }
   8343   }
   8344 
   8345   if (!Subtarget->isThumb1Only()) {
   8346     // fold (and (select cc, -1, c), x) -> (select cc, x, (and, x, c))
   8347     SDValue Result = combineSelectAndUseCommutative(N, true, DCI);
   8348     if (Result.getNode())
   8349       return Result;
   8350   }
   8351 
   8352   return SDValue();
   8353 }
   8354 
   8355 /// PerformORCombine - Target-specific dag combine xforms for ISD::OR
   8356 static SDValue PerformORCombine(SDNode *N,
   8357                                 TargetLowering::DAGCombinerInfo &DCI,
   8358                                 const ARMSubtarget *Subtarget) {
   8359   // Attempt to use immediate-form VORR
   8360   BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(N->getOperand(1));
   8361   SDLoc dl(N);
   8362   EVT VT = N->getValueType(0);
   8363   SelectionDAG &DAG = DCI.DAG;
   8364 
   8365   if(!DAG.getTargetLoweringInfo().isTypeLegal(VT))
   8366     return SDValue();
   8367 
   8368   APInt SplatBits, SplatUndef;
   8369   unsigned SplatBitSize;
   8370   bool HasAnyUndefs;
   8371   if (BVN && Subtarget->hasNEON() &&
   8372       BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs)) {
   8373     if (SplatBitSize <= 64) {
   8374       EVT VorrVT;
   8375       SDValue Val = isNEONModifiedImm(SplatBits.getZExtValue(),
   8376                                       SplatUndef.getZExtValue(), SplatBitSize,
   8377                                       DAG, VorrVT, VT.is128BitVector(),
   8378                                       OtherModImm);
   8379       if (Val.getNode()) {
   8380         SDValue Input =
   8381           DAG.getNode(ISD::BITCAST, dl, VorrVT, N->getOperand(0));
   8382         SDValue Vorr = DAG.getNode(ARMISD::VORRIMM, dl, VorrVT, Input, Val);
   8383         return DAG.getNode(ISD::BITCAST, dl, VT, Vorr);
   8384       }
   8385     }
   8386   }
   8387 
   8388   if (!Subtarget->isThumb1Only()) {
   8389     // fold (or (select cc, 0, c), x) -> (select cc, x, (or, x, c))
   8390     SDValue Result = combineSelectAndUseCommutative(N, false, DCI);
   8391     if (Result.getNode())
   8392       return Result;
   8393   }
   8394 
   8395   // The code below optimizes (or (and X, Y), Z).
   8396   // The AND operand needs to have a single user to make these optimizations
   8397   // profitable.
   8398   SDValue N0 = N->getOperand(0);
   8399   if (N0.getOpcode() != ISD::AND || !N0.hasOneUse())
   8400     return SDValue();
   8401   SDValue N1 = N->getOperand(1);
   8402 
   8403   // (or (and B, A), (and C, ~A)) => (VBSL A, B, C) when A is a constant.
   8404   if (Subtarget->hasNEON() && N1.getOpcode() == ISD::AND && VT.isVector() &&
   8405       DAG.getTargetLoweringInfo().isTypeLegal(VT)) {
   8406     APInt SplatUndef;
   8407     unsigned SplatBitSize;
   8408     bool HasAnyUndefs;
   8409 
   8410     APInt SplatBits0, SplatBits1;
   8411     BuildVectorSDNode *BVN0 = dyn_cast<BuildVectorSDNode>(N0->getOperand(1));
   8412     BuildVectorSDNode *BVN1 = dyn_cast<BuildVectorSDNode>(N1->getOperand(1));
   8413     // Ensure that the second operand of both ands are constants
   8414     if (BVN0 && BVN0->isConstantSplat(SplatBits0, SplatUndef, SplatBitSize,
   8415                                       HasAnyUndefs) && !HasAnyUndefs) {
   8416         if (BVN1 && BVN1->isConstantSplat(SplatBits1, SplatUndef, SplatBitSize,
   8417                                           HasAnyUndefs) && !HasAnyUndefs) {
   8418             // Ensure that the bit width of the constants are the same and that
   8419             // the splat arguments are logical inverses as per the pattern we
   8420             // are trying to simplify.
   8421             if (SplatBits0.getBitWidth() == SplatBits1.getBitWidth() &&
   8422                 SplatBits0 == ~SplatBits1) {
   8423                 // Canonicalize the vector type to make instruction selection
   8424                 // simpler.
   8425                 EVT CanonicalVT = VT.is128BitVector() ? MVT::v4i32 : MVT::v2i32;
   8426                 SDValue Result = DAG.getNode(ARMISD::VBSL, dl, CanonicalVT,
   8427                                              N0->getOperand(1),
   8428                                              N0->getOperand(0),
   8429                                              N1->getOperand(0));
   8430                 return DAG.getNode(ISD::BITCAST, dl, VT, Result);
   8431             }
   8432         }
   8433     }
   8434   }
   8435 
   8436   // Try to use the ARM/Thumb2 BFI (bitfield insert) instruction when
   8437   // reasonable.
   8438 
   8439   // BFI is only available on V6T2+
   8440   if (Subtarget->isThumb1Only() || !Subtarget->hasV6T2Ops())
   8441     return SDValue();
   8442 
   8443   SDLoc DL(N);
   8444   // 1) or (and A, mask), val => ARMbfi A, val, mask
   8445   //      iff (val & mask) == val
   8446   //
   8447   // 2) or (and A, mask), (and B, mask2) => ARMbfi A, (lsr B, amt), mask
   8448   //  2a) iff isBitFieldInvertedMask(mask) && isBitFieldInvertedMask(~mask2)
   8449   //          && mask == ~mask2
   8450   //  2b) iff isBitFieldInvertedMask(~mask) && isBitFieldInvertedMask(mask2)
   8451   //          && ~mask == mask2
   8452   //  (i.e., copy a bitfield value into another bitfield of the same width)
   8453 
   8454   if (VT != MVT::i32)
   8455     return SDValue();
   8456 
   8457   SDValue N00 = N0.getOperand(0);
   8458 
   8459   // The value and the mask need to be constants so we can verify this is
   8460   // actually a bitfield set. If the mask is 0xffff, we can do better
   8461   // via a movt instruction, so don't use BFI in that case.
   8462   SDValue MaskOp = N0.getOperand(1);
   8463   ConstantSDNode *MaskC = dyn_cast<ConstantSDNode>(MaskOp);
   8464   if (!MaskC)
   8465     return SDValue();
   8466   unsigned Mask = MaskC->getZExtValue();
   8467   if (Mask == 0xffff)
   8468     return SDValue();
   8469   SDValue Res;
   8470   // Case (1): or (and A, mask), val => ARMbfi A, val, mask
   8471   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
   8472   if (N1C) {
   8473     unsigned Val = N1C->getZExtValue();
   8474     if ((Val & ~Mask) != Val)
   8475       return SDValue();
   8476 
   8477     if (ARM::isBitFieldInvertedMask(Mask)) {
   8478       Val >>= countTrailingZeros(~Mask);
   8479 
   8480       Res = DAG.getNode(ARMISD::BFI, DL, VT, N00,
   8481                         DAG.getConstant(Val, MVT::i32),
   8482                         DAG.getConstant(Mask, MVT::i32));
   8483 
   8484       // Do not add new nodes to DAG combiner worklist.
   8485       DCI.CombineTo(N, Res, false);
   8486       return SDValue();
   8487     }
   8488   } else if (N1.getOpcode() == ISD::AND) {
   8489     // case (2) or (and A, mask), (and B, mask2) => ARMbfi A, (lsr B, amt), mask
   8490     ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1));
   8491     if (!N11C)
   8492       return SDValue();
   8493     unsigned Mask2 = N11C->getZExtValue();
   8494 
   8495     // Mask and ~Mask2 (or reverse) must be equivalent for the BFI pattern
   8496     // as is to match.
   8497     if (ARM::isBitFieldInvertedMask(Mask) &&
   8498         (Mask == ~Mask2)) {
   8499       // The pack halfword instruction works better for masks that fit it,
   8500       // so use that when it's available.
   8501       if (Subtarget->hasT2ExtractPack() &&
   8502           (Mask == 0xffff || Mask == 0xffff0000))
   8503         return SDValue();
   8504       // 2a
   8505       unsigned amt = countTrailingZeros(Mask2);
   8506       Res = DAG.getNode(ISD::SRL, DL, VT, N1.getOperand(0),
   8507                         DAG.getConstant(amt, MVT::i32));
   8508       Res = DAG.getNode(ARMISD::BFI, DL, VT, N00, Res,
   8509                         DAG.getConstant(Mask, MVT::i32));
   8510       // Do not add new nodes to DAG combiner worklist.
   8511       DCI.CombineTo(N, Res, false);
   8512       return SDValue();
   8513     } else if (ARM::isBitFieldInvertedMask(~Mask) &&
   8514                (~Mask == Mask2)) {
   8515       // The pack halfword instruction works better for masks that fit it,
   8516       // so use that when it's available.
   8517       if (Subtarget->hasT2ExtractPack() &&
   8518           (Mask2 == 0xffff || Mask2 == 0xffff0000))
   8519         return SDValue();
   8520       // 2b
   8521       unsigned lsb = countTrailingZeros(Mask);
   8522       Res = DAG.getNode(ISD::SRL, DL, VT, N00,
   8523                         DAG.getConstant(lsb, MVT::i32));
   8524       Res = DAG.getNode(ARMISD::BFI, DL, VT, N1.getOperand(0), Res,
   8525                         DAG.getConstant(Mask2, MVT::i32));
   8526       // Do not add new nodes to DAG combiner worklist.
   8527       DCI.CombineTo(N, Res, false);
   8528       return SDValue();
   8529     }
   8530   }
   8531 
   8532   if (DAG.MaskedValueIsZero(N1, MaskC->getAPIntValue()) &&
   8533       N00.getOpcode() == ISD::SHL && isa<ConstantSDNode>(N00.getOperand(1)) &&
   8534       ARM::isBitFieldInvertedMask(~Mask)) {
   8535     // Case (3): or (and (shl A, #shamt), mask), B => ARMbfi B, A, ~mask
   8536     // where lsb(mask) == #shamt and masked bits of B are known zero.
   8537     SDValue ShAmt = N00.getOperand(1);
   8538     unsigned ShAmtC = cast<ConstantSDNode>(ShAmt)->getZExtValue();
   8539     unsigned LSB = countTrailingZeros(Mask);
   8540     if (ShAmtC != LSB)
   8541       return SDValue();
   8542 
   8543     Res = DAG.getNode(ARMISD::BFI, DL, VT, N1, N00.getOperand(0),
   8544                       DAG.getConstant(~Mask, MVT::i32));
   8545 
   8546     // Do not add new nodes to DAG combiner worklist.
   8547     DCI.CombineTo(N, Res, false);
   8548   }
   8549 
   8550   return SDValue();
   8551 }
   8552 
   8553 static SDValue PerformXORCombine(SDNode *N,
   8554                                  TargetLowering::DAGCombinerInfo &DCI,
   8555                                  const ARMSubtarget *Subtarget) {
   8556   EVT VT = N->getValueType(0);
   8557   SelectionDAG &DAG = DCI.DAG;
   8558 
   8559   if(!DAG.getTargetLoweringInfo().isTypeLegal(VT))
   8560     return SDValue();
   8561 
   8562   if (!Subtarget->isThumb1Only()) {
   8563     // fold (xor (select cc, 0, c), x) -> (select cc, x, (xor, x, c))
   8564     SDValue Result = combineSelectAndUseCommutative(N, false, DCI);
   8565     if (Result.getNode())
   8566       return Result;
   8567   }
   8568 
   8569   return SDValue();
   8570 }
   8571 
   8572 /// PerformBFICombine - (bfi A, (and B, Mask1), Mask2) -> (bfi A, B, Mask2) iff
   8573 /// the bits being cleared by the AND are not demanded by the BFI.
   8574 static SDValue PerformBFICombine(SDNode *N,
   8575                                  TargetLowering::DAGCombinerInfo &DCI) {
   8576   SDValue N1 = N->getOperand(1);
   8577   if (N1.getOpcode() == ISD::AND) {
   8578     ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1));
   8579     if (!N11C)
   8580       return SDValue();
   8581     unsigned InvMask = cast<ConstantSDNode>(N->getOperand(2))->getZExtValue();
   8582     unsigned LSB = countTrailingZeros(~InvMask);
   8583     unsigned Width = (32 - countLeadingZeros(~InvMask)) - LSB;
   8584     unsigned Mask = (1 << Width)-1;
   8585     unsigned Mask2 = N11C->getZExtValue();
   8586     if ((Mask & (~Mask2)) == 0)
   8587       return DCI.DAG.getNode(ARMISD::BFI, SDLoc(N), N->getValueType(0),
   8588                              N->getOperand(0), N1.getOperand(0),
   8589                              N->getOperand(2));
   8590   }
   8591   return SDValue();
   8592 }
   8593 
   8594 /// PerformVMOVRRDCombine - Target-specific dag combine xforms for
   8595 /// ARMISD::VMOVRRD.
   8596 static SDValue PerformVMOVRRDCombine(SDNode *N,
   8597                                      TargetLowering::DAGCombinerInfo &DCI) {
   8598   // vmovrrd(vmovdrr x, y) -> x,y
   8599   SDValue InDouble = N->getOperand(0);
   8600   if (InDouble.getOpcode() == ARMISD::VMOVDRR)
   8601     return DCI.CombineTo(N, InDouble.getOperand(0), InDouble.getOperand(1));
   8602 
   8603   // vmovrrd(load f64) -> (load i32), (load i32)
   8604   SDNode *InNode = InDouble.getNode();
   8605   if (ISD::isNormalLoad(InNode) && InNode->hasOneUse() &&
   8606       InNode->getValueType(0) == MVT::f64 &&
   8607       InNode->getOperand(1).getOpcode() == ISD::FrameIndex &&
   8608       !cast<LoadSDNode>(InNode)->isVolatile()) {
   8609     // TODO: Should this be done for non-FrameIndex operands?
   8610     LoadSDNode *LD = cast<LoadSDNode>(InNode);
   8611 
   8612     SelectionDAG &DAG = DCI.DAG;
   8613     SDLoc DL(LD);
   8614     SDValue BasePtr = LD->getBasePtr();
   8615     SDValue NewLD1 = DAG.getLoad(MVT::i32, DL, LD->getChain(), BasePtr,
   8616                                  LD->getPointerInfo(), LD->isVolatile(),
   8617                                  LD->isNonTemporal(), LD->isInvariant(),
   8618                                  LD->getAlignment());
   8619 
   8620     SDValue OffsetPtr = DAG.getNode(ISD::ADD, DL, MVT::i32, BasePtr,
   8621                                     DAG.getConstant(4, MVT::i32));
   8622     SDValue NewLD2 = DAG.getLoad(MVT::i32, DL, NewLD1.getValue(1), OffsetPtr,
   8623                                  LD->getPointerInfo(), LD->isVolatile(),
   8624                                  LD->isNonTemporal(), LD->isInvariant(),
   8625                                  std::min(4U, LD->getAlignment() / 2));
   8626 
   8627     DAG.ReplaceAllUsesOfValueWith(SDValue(LD, 1), NewLD2.getValue(1));
   8628     SDValue Result = DCI.CombineTo(N, NewLD1, NewLD2);
   8629     DCI.RemoveFromWorklist(LD);
   8630     DAG.DeleteNode(LD);
   8631     return Result;
   8632   }
   8633 
   8634   return SDValue();
   8635 }
   8636 
   8637 /// PerformVMOVDRRCombine - Target-specific dag combine xforms for
   8638 /// ARMISD::VMOVDRR.  This is also used for BUILD_VECTORs with 2 operands.
   8639 static SDValue PerformVMOVDRRCombine(SDNode *N, SelectionDAG &DAG) {
   8640   // N=vmovrrd(X); vmovdrr(N:0, N:1) -> bit_convert(X)
   8641   SDValue Op0 = N->getOperand(0);
   8642   SDValue Op1 = N->getOperand(1);
   8643   if (Op0.getOpcode() == ISD::BITCAST)
   8644     Op0 = Op0.getOperand(0);
   8645   if (Op1.getOpcode() == ISD::BITCAST)
   8646     Op1 = Op1.getOperand(0);
   8647   if (Op0.getOpcode() == ARMISD::VMOVRRD &&
   8648       Op0.getNode() == Op1.getNode() &&
   8649       Op0.getResNo() == 0 && Op1.getResNo() == 1)
   8650     return DAG.getNode(ISD::BITCAST, SDLoc(N),
   8651                        N->getValueType(0), Op0.getOperand(0));
   8652   return SDValue();
   8653 }
   8654 
   8655 /// PerformSTORECombine - Target-specific dag combine xforms for
   8656 /// ISD::STORE.
   8657 static SDValue PerformSTORECombine(SDNode *N,
   8658                                    TargetLowering::DAGCombinerInfo &DCI) {
   8659   StoreSDNode *St = cast<StoreSDNode>(N);
   8660   if (St->isVolatile())
   8661     return SDValue();
   8662 
   8663   // Optimize trunc store (of multiple scalars) to shuffle and store.  First,
   8664   // pack all of the elements in one place.  Next, store to memory in fewer
   8665   // chunks.
   8666   SDValue StVal = St->getValue();
   8667   EVT VT = StVal.getValueType();
   8668   if (St->isTruncatingStore() && VT.isVector()) {
   8669     SelectionDAG &DAG = DCI.DAG;
   8670     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
   8671     EVT StVT = St->getMemoryVT();
   8672     unsigned NumElems = VT.getVectorNumElements();
   8673     assert(StVT != VT && "Cannot truncate to the same type");
   8674     unsigned FromEltSz = VT.getVectorElementType().getSizeInBits();
   8675     unsigned ToEltSz = StVT.getVectorElementType().getSizeInBits();
   8676 
   8677     // From, To sizes and ElemCount must be pow of two
   8678     if (!isPowerOf2_32(NumElems * FromEltSz * ToEltSz)) return SDValue();
   8679 
   8680     // We are going to use the original vector elt for storing.
   8681     // Accumulated smaller vector elements must be a multiple of the store size.
   8682     if (0 != (NumElems * FromEltSz) % ToEltSz) return SDValue();
   8683 
   8684     unsigned SizeRatio  = FromEltSz / ToEltSz;
   8685     assert(SizeRatio * NumElems * ToEltSz == VT.getSizeInBits());
   8686 
   8687     // Create a type on which we perform the shuffle.
   8688     EVT WideVecVT = EVT::getVectorVT(*DAG.getContext(), StVT.getScalarType(),
   8689                                      NumElems*SizeRatio);
   8690     assert(WideVecVT.getSizeInBits() == VT.getSizeInBits());
   8691 
   8692     SDLoc DL(St);
   8693     SDValue WideVec = DAG.getNode(ISD::BITCAST, DL, WideVecVT, StVal);
   8694     SmallVector<int, 8> ShuffleVec(NumElems * SizeRatio, -1);
   8695     for (unsigned i = 0; i < NumElems; ++i) ShuffleVec[i] = i * SizeRatio;
   8696 
   8697     // Can't shuffle using an illegal type.
   8698     if (!TLI.isTypeLegal(WideVecVT)) return SDValue();
   8699 
   8700     SDValue Shuff = DAG.getVectorShuffle(WideVecVT, DL, WideVec,
   8701                                 DAG.getUNDEF(WideVec.getValueType()),
   8702                                 ShuffleVec.data());
   8703     // At this point all of the data is stored at the bottom of the
   8704     // register. We now need to save it to mem.
   8705 
   8706     // Find the largest store unit
   8707     MVT StoreType = MVT::i8;
   8708     for (unsigned tp = MVT::FIRST_INTEGER_VALUETYPE;
   8709          tp < MVT::LAST_INTEGER_VALUETYPE; ++tp) {
   8710       MVT Tp = (MVT::SimpleValueType)tp;
   8711       if (TLI.isTypeLegal(Tp) && Tp.getSizeInBits() <= NumElems * ToEltSz)
   8712         StoreType = Tp;
   8713     }
   8714     // Didn't find a legal store type.
   8715     if (!TLI.isTypeLegal(StoreType))
   8716       return SDValue();
   8717 
   8718     // Bitcast the original vector into a vector of store-size units
   8719     EVT StoreVecVT = EVT::getVectorVT(*DAG.getContext(),
   8720             StoreType, VT.getSizeInBits()/EVT(StoreType).getSizeInBits());
   8721     assert(StoreVecVT.getSizeInBits() == VT.getSizeInBits());
   8722     SDValue ShuffWide = DAG.getNode(ISD::BITCAST, DL, StoreVecVT, Shuff);
   8723     SmallVector<SDValue, 8> Chains;
   8724     SDValue Increment = DAG.getConstant(StoreType.getSizeInBits()/8,
   8725                                         TLI.getPointerTy());
   8726     SDValue BasePtr = St->getBasePtr();
   8727 
   8728     // Perform one or more big stores into memory.
   8729     unsigned E = (ToEltSz*NumElems)/StoreType.getSizeInBits();
   8730     for (unsigned I = 0; I < E; I++) {
   8731       SDValue SubVec = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL,
   8732                                    StoreType, ShuffWide,
   8733                                    DAG.getIntPtrConstant(I));
   8734       SDValue Ch = DAG.getStore(St->getChain(), DL, SubVec, BasePtr,
   8735                                 St->getPointerInfo(), St->isVolatile(),
   8736                                 St->isNonTemporal(), St->getAlignment());
   8737       BasePtr = DAG.getNode(ISD::ADD, DL, BasePtr.getValueType(), BasePtr,
   8738                             Increment);
   8739       Chains.push_back(Ch);
   8740     }
   8741     return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, &Chains[0],
   8742                        Chains.size());
   8743   }
   8744 
   8745   if (!ISD::isNormalStore(St))
   8746     return SDValue();
   8747 
   8748   // Split a store of a VMOVDRR into two integer stores to avoid mixing NEON and
   8749   // ARM stores of arguments in the same cache line.
   8750   if (StVal.getNode()->getOpcode() == ARMISD::VMOVDRR &&
   8751       StVal.getNode()->hasOneUse()) {
   8752     SelectionDAG  &DAG = DCI.DAG;
   8753     SDLoc DL(St);
   8754     SDValue BasePtr = St->getBasePtr();
   8755     SDValue NewST1 = DAG.getStore(St->getChain(), DL,
   8756                                   StVal.getNode()->getOperand(0), BasePtr,
   8757                                   St->getPointerInfo(), St->isVolatile(),
   8758                                   St->isNonTemporal(), St->getAlignment());
   8759 
   8760     SDValue OffsetPtr = DAG.getNode(ISD::ADD, DL, MVT::i32, BasePtr,
   8761                                     DAG.getConstant(4, MVT::i32));
   8762     return DAG.getStore(NewST1.getValue(0), DL, StVal.getNode()->getOperand(1),
   8763                         OffsetPtr, St->getPointerInfo(), St->isVolatile(),
   8764                         St->isNonTemporal(),
   8765                         std::min(4U, St->getAlignment() / 2));
   8766   }
   8767 
   8768   if (StVal.getValueType() != MVT::i64 ||
   8769       StVal.getNode()->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
   8770     return SDValue();
   8771 
   8772   // Bitcast an i64 store extracted from a vector to f64.
   8773   // Otherwise, the i64 value will be legalized to a pair of i32 values.
   8774   SelectionDAG &DAG = DCI.DAG;
   8775   SDLoc dl(StVal);
   8776   SDValue IntVec = StVal.getOperand(0);
   8777   EVT FloatVT = EVT::getVectorVT(*DAG.getContext(), MVT::f64,
   8778                                  IntVec.getValueType().getVectorNumElements());
   8779   SDValue Vec = DAG.getNode(ISD::BITCAST, dl, FloatVT, IntVec);
   8780   SDValue ExtElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
   8781                                Vec, StVal.getOperand(1));
   8782   dl = SDLoc(N);
   8783   SDValue V = DAG.getNode(ISD::BITCAST, dl, MVT::i64, ExtElt);
   8784   // Make the DAGCombiner fold the bitcasts.
   8785   DCI.AddToWorklist(Vec.getNode());
   8786   DCI.AddToWorklist(ExtElt.getNode());
   8787   DCI.AddToWorklist(V.getNode());
   8788   return DAG.getStore(St->getChain(), dl, V, St->getBasePtr(),
   8789                       St->getPointerInfo(), St->isVolatile(),
   8790                       St->isNonTemporal(), St->getAlignment(),
   8791                       St->getTBAAInfo());
   8792 }
   8793 
   8794 /// hasNormalLoadOperand - Check if any of the operands of a BUILD_VECTOR node
   8795 /// are normal, non-volatile loads.  If so, it is profitable to bitcast an
   8796 /// i64 vector to have f64 elements, since the value can then be loaded
   8797 /// directly into a VFP register.
   8798 static bool hasNormalLoadOperand(SDNode *N) {
   8799   unsigned NumElts = N->getValueType(0).getVectorNumElements();
   8800   for (unsigned i = 0; i < NumElts; ++i) {
   8801     SDNode *Elt = N->getOperand(i).getNode();
   8802     if (ISD::isNormalLoad(Elt) && !cast<LoadSDNode>(Elt)->isVolatile())
   8803       return true;
   8804   }
   8805   return false;
   8806 }
   8807 
   8808 /// PerformBUILD_VECTORCombine - Target-specific dag combine xforms for
   8809 /// ISD::BUILD_VECTOR.
   8810 static SDValue PerformBUILD_VECTORCombine(SDNode *N,
   8811                                           TargetLowering::DAGCombinerInfo &DCI){
   8812   // build_vector(N=ARMISD::VMOVRRD(X), N:1) -> bit_convert(X):
   8813   // VMOVRRD is introduced when legalizing i64 types.  It forces the i64 value
   8814   // into a pair of GPRs, which is fine when the value is used as a scalar,
   8815   // but if the i64 value is converted to a vector, we need to undo the VMOVRRD.
   8816   SelectionDAG &DAG = DCI.DAG;
   8817   if (N->getNumOperands() == 2) {
   8818     SDValue RV = PerformVMOVDRRCombine(N, DAG);
   8819     if (RV.getNode())
   8820       return RV;
   8821   }
   8822 
   8823   // Load i64 elements as f64 values so that type legalization does not split
   8824   // them up into i32 values.
   8825   EVT VT = N->getValueType(0);
   8826   if (VT.getVectorElementType() != MVT::i64 || !hasNormalLoadOperand(N))
   8827     return SDValue();
   8828   SDLoc dl(N);
   8829   SmallVector<SDValue, 8> Ops;
   8830   unsigned NumElts = VT.getVectorNumElements();
   8831   for (unsigned i = 0; i < NumElts; ++i) {
   8832     SDValue V = DAG.getNode(ISD::BITCAST, dl, MVT::f64, N->getOperand(i));
   8833     Ops.push_back(V);
   8834     // Make the DAGCombiner fold the bitcast.
   8835     DCI.AddToWorklist(V.getNode());
   8836   }
   8837   EVT FloatVT = EVT::getVectorVT(*DAG.getContext(), MVT::f64, NumElts);
   8838   SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, FloatVT, Ops.data(), NumElts);
   8839   return DAG.getNode(ISD::BITCAST, dl, VT, BV);
   8840 }
   8841 
   8842 /// \brief Target-specific dag combine xforms for ARMISD::BUILD_VECTOR.
   8843 static SDValue
   8844 PerformARMBUILD_VECTORCombine(SDNode *N, TargetLowering::DAGCombinerInfo &DCI) {
   8845   // ARMISD::BUILD_VECTOR is introduced when legalizing ISD::BUILD_VECTOR.
   8846   // At that time, we may have inserted bitcasts from integer to float.
   8847   // If these bitcasts have survived DAGCombine, change the lowering of this
   8848   // BUILD_VECTOR in something more vector friendly, i.e., that does not
   8849   // force to use floating point types.
   8850 
   8851   // Make sure we can change the type of the vector.
   8852   // This is possible iff:
   8853   // 1. The vector is only used in a bitcast to a integer type. I.e.,
   8854   //    1.1. Vector is used only once.
   8855   //    1.2. Use is a bit convert to an integer type.
   8856   // 2. The size of its operands are 32-bits (64-bits are not legal).
   8857   EVT VT = N->getValueType(0);
   8858   EVT EltVT = VT.getVectorElementType();
   8859 
   8860   // Check 1.1. and 2.
   8861   if (EltVT.getSizeInBits() != 32 || !N->hasOneUse())
   8862     return SDValue();
   8863 
   8864   // By construction, the input type must be float.
   8865   assert(EltVT == MVT::f32 && "Unexpected type!");
   8866 
   8867   // Check 1.2.
   8868   SDNode *Use = *N->use_begin();
   8869   if (Use->getOpcode() != ISD::BITCAST ||
   8870       Use->getValueType(0).isFloatingPoint())
   8871     return SDValue();
   8872 
   8873   // Check profitability.
   8874   // Model is, if more than half of the relevant operands are bitcast from
   8875   // i32, turn the build_vector into a sequence of insert_vector_elt.
   8876   // Relevant operands are everything that is not statically
   8877   // (i.e., at compile time) bitcasted.
   8878   unsigned NumOfBitCastedElts = 0;
   8879   unsigned NumElts = VT.getVectorNumElements();
   8880   unsigned NumOfRelevantElts = NumElts;
   8881   for (unsigned Idx = 0; Idx < NumElts; ++Idx) {
   8882     SDValue Elt = N->getOperand(Idx);
   8883     if (Elt->getOpcode() == ISD::BITCAST) {
   8884       // Assume only bit cast to i32 will go away.
   8885       if (Elt->getOperand(0).getValueType() == MVT::i32)
   8886         ++NumOfBitCastedElts;
   8887     } else if (Elt.getOpcode() == ISD::UNDEF || isa<ConstantSDNode>(Elt))
   8888       // Constants are statically casted, thus do not count them as
   8889       // relevant operands.
   8890       --NumOfRelevantElts;
   8891   }
   8892 
   8893   // Check if more than half of the elements require a non-free bitcast.
   8894   if (NumOfBitCastedElts <= NumOfRelevantElts / 2)
   8895     return SDValue();
   8896 
   8897   SelectionDAG &DAG = DCI.DAG;
   8898   // Create the new vector type.
   8899   EVT VecVT = EVT::getVectorVT(*DAG.getContext(), MVT::i32, NumElts);
   8900   // Check if the type is legal.
   8901   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
   8902   if (!TLI.isTypeLegal(VecVT))
   8903     return SDValue();
   8904 
   8905   // Combine:
   8906   // ARMISD::BUILD_VECTOR E1, E2, ..., EN.
   8907   // => BITCAST INSERT_VECTOR_ELT
   8908   //                      (INSERT_VECTOR_ELT (...), (BITCAST EN-1), N-1),
   8909   //                      (BITCAST EN), N.
   8910   SDValue Vec = DAG.getUNDEF(VecVT);
   8911   SDLoc dl(N);
   8912   for (unsigned Idx = 0 ; Idx < NumElts; ++Idx) {
   8913     SDValue V = N->getOperand(Idx);
   8914     if (V.getOpcode() == ISD::UNDEF)
   8915       continue;
   8916     if (V.getOpcode() == ISD::BITCAST &&
   8917         V->getOperand(0).getValueType() == MVT::i32)
   8918       // Fold obvious case.
   8919       V = V.getOperand(0);
   8920     else {
   8921       V = DAG.getNode(ISD::BITCAST, SDLoc(V), MVT::i32, V);
   8922       // Make the DAGCombiner fold the bitcasts.
   8923       DCI.AddToWorklist(V.getNode());
   8924     }
   8925     SDValue LaneIdx = DAG.getConstant(Idx, MVT::i32);
   8926     Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VecVT, Vec, V, LaneIdx);
   8927   }
   8928   Vec = DAG.getNode(ISD::BITCAST, dl, VT, Vec);
   8929   // Make the DAGCombiner fold the bitcasts.
   8930   DCI.AddToWorklist(Vec.getNode());
   8931   return Vec;
   8932 }
   8933 
   8934 /// PerformInsertEltCombine - Target-specific dag combine xforms for
   8935 /// ISD::INSERT_VECTOR_ELT.
   8936 static SDValue PerformInsertEltCombine(SDNode *N,
   8937                                        TargetLowering::DAGCombinerInfo &DCI) {
   8938   // Bitcast an i64 load inserted into a vector to f64.
   8939   // Otherwise, the i64 value will be legalized to a pair of i32 values.
   8940   EVT VT = N->getValueType(0);
   8941   SDNode *Elt = N->getOperand(1).getNode();
   8942   if (VT.getVectorElementType() != MVT::i64 ||
   8943       !ISD::isNormalLoad(Elt) || cast<LoadSDNode>(Elt)->isVolatile())
   8944     return SDValue();
   8945 
   8946   SelectionDAG &DAG = DCI.DAG;
   8947   SDLoc dl(N);
   8948   EVT FloatVT = EVT::getVectorVT(*DAG.getContext(), MVT::f64,
   8949                                  VT.getVectorNumElements());
   8950   SDValue Vec = DAG.getNode(ISD::BITCAST, dl, FloatVT, N->getOperand(0));
   8951   SDValue V = DAG.getNode(ISD::BITCAST, dl, MVT::f64, N->getOperand(1));
   8952   // Make the DAGCombiner fold the bitcasts.
   8953   DCI.AddToWorklist(Vec.getNode());
   8954   DCI.AddToWorklist(V.getNode());
   8955   SDValue InsElt = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, FloatVT,
   8956                                Vec, V, N->getOperand(2));
   8957   return DAG.getNode(ISD::BITCAST, dl, VT, InsElt);
   8958 }
   8959 
   8960 /// PerformVECTOR_SHUFFLECombine - Target-specific dag combine xforms for
   8961 /// ISD::VECTOR_SHUFFLE.
   8962 static SDValue PerformVECTOR_SHUFFLECombine(SDNode *N, SelectionDAG &DAG) {
   8963   // The LLVM shufflevector instruction does not require the shuffle mask
   8964   // length to match the operand vector length, but ISD::VECTOR_SHUFFLE does
   8965   // have that requirement.  When translating to ISD::VECTOR_SHUFFLE, if the
   8966   // operands do not match the mask length, they are extended by concatenating
   8967   // them with undef vectors.  That is probably the right thing for other
   8968   // targets, but for NEON it is better to concatenate two double-register
   8969   // size vector operands into a single quad-register size vector.  Do that
   8970   // transformation here:
   8971   //   shuffle(concat(v1, undef), concat(v2, undef)) ->
   8972   //   shuffle(concat(v1, v2), undef)
   8973   SDValue Op0 = N->getOperand(0);
   8974   SDValue Op1 = N->getOperand(1);
   8975   if (Op0.getOpcode() != ISD::CONCAT_VECTORS ||
   8976       Op1.getOpcode() != ISD::CONCAT_VECTORS ||
   8977       Op0.getNumOperands() != 2 ||
   8978       Op1.getNumOperands() != 2)
   8979     return SDValue();
   8980   SDValue Concat0Op1 = Op0.getOperand(1);
   8981   SDValue Concat1Op1 = Op1.getOperand(1);
   8982   if (Concat0Op1.getOpcode() != ISD::UNDEF ||
   8983       Concat1Op1.getOpcode() != ISD::UNDEF)
   8984     return SDValue();
   8985   // Skip the transformation if any of the types are illegal.
   8986   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
   8987   EVT VT = N->getValueType(0);
   8988   if (!TLI.isTypeLegal(VT) ||
   8989       !TLI.isTypeLegal(Concat0Op1.getValueType()) ||
   8990       !TLI.isTypeLegal(Concat1Op1.getValueType()))
   8991     return SDValue();
   8992 
   8993   SDValue NewConcat = DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT,
   8994                                   Op0.getOperand(0), Op1.getOperand(0));
   8995   // Translate the shuffle mask.
   8996   SmallVector<int, 16> NewMask;
   8997   unsigned NumElts = VT.getVectorNumElements();
   8998   unsigned HalfElts = NumElts/2;
   8999   ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N);
   9000   for (unsigned n = 0; n < NumElts; ++n) {
   9001     int MaskElt = SVN->getMaskElt(n);
   9002     int NewElt = -1;
   9003     if (MaskElt < (int)HalfElts)
   9004       NewElt = MaskElt;
   9005     else if (MaskElt >= (int)NumElts && MaskElt < (int)(NumElts + HalfElts))
   9006       NewElt = HalfElts + MaskElt - NumElts;
   9007     NewMask.push_back(NewElt);
   9008   }
   9009   return DAG.getVectorShuffle(VT, SDLoc(N), NewConcat,
   9010                               DAG.getUNDEF(VT), NewMask.data());
   9011 }
   9012 
   9013 /// CombineBaseUpdate - Target-specific DAG combine function for VLDDUP and
   9014 /// NEON load/store intrinsics to merge base address updates.
   9015 static SDValue CombineBaseUpdate(SDNode *N,
   9016                                  TargetLowering::DAGCombinerInfo &DCI) {
   9017   if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
   9018     return SDValue();
   9019 
   9020   SelectionDAG &DAG = DCI.DAG;
   9021   bool isIntrinsic = (N->getOpcode() == ISD::INTRINSIC_VOID ||
   9022                       N->getOpcode() == ISD::INTRINSIC_W_CHAIN);
   9023   unsigned AddrOpIdx = (isIntrinsic ? 2 : 1);
   9024   SDValue Addr = N->getOperand(AddrOpIdx);
   9025 
   9026   // Search for a use of the address operand that is an increment.
   9027   for (SDNode::use_iterator UI = Addr.getNode()->use_begin(),
   9028          UE = Addr.getNode()->use_end(); UI != UE; ++UI) {
   9029     SDNode *User = *UI;
   9030     if (User->getOpcode() != ISD::ADD ||
   9031         UI.getUse().getResNo() != Addr.getResNo())
   9032       continue;
   9033 
   9034     // Check that the add is independent of the load/store.  Otherwise, folding
   9035     // it would create a cycle.
   9036     if (User->isPredecessorOf(N) || N->isPredecessorOf(User))
   9037       continue;
   9038 
   9039     // Find the new opcode for the updating load/store.
   9040     bool isLoad = true;
   9041     bool isLaneOp = false;
   9042     unsigned NewOpc = 0;
   9043     unsigned NumVecs = 0;
   9044     if (isIntrinsic) {
   9045       unsigned IntNo = cast<ConstantSDNode>(N->getOperand(1))->getZExtValue();
   9046       switch (IntNo) {
   9047       default: llvm_unreachable("unexpected intrinsic for Neon base update");
   9048       case Intrinsic::arm_neon_vld1:     NewOpc = ARMISD::VLD1_UPD;
   9049         NumVecs = 1; break;
   9050       case Intrinsic::arm_neon_vld2:     NewOpc = ARMISD::VLD2_UPD;
   9051         NumVecs = 2; break;
   9052       case Intrinsic::arm_neon_vld3:     NewOpc = ARMISD::VLD3_UPD;
   9053         NumVecs = 3; break;
   9054       case Intrinsic::arm_neon_vld4:     NewOpc = ARMISD::VLD4_UPD;
   9055         NumVecs = 4; break;
   9056       case Intrinsic::arm_neon_vld2lane: NewOpc = ARMISD::VLD2LN_UPD;
   9057         NumVecs = 2; isLaneOp = true; break;
   9058       case Intrinsic::arm_neon_vld3lane: NewOpc = ARMISD::VLD3LN_UPD;
   9059         NumVecs = 3; isLaneOp = true; break;
   9060       case Intrinsic::arm_neon_vld4lane: NewOpc = ARMISD::VLD4LN_UPD;
   9061         NumVecs = 4; isLaneOp = true; break;
   9062       case Intrinsic::arm_neon_vst1:     NewOpc = ARMISD::VST1_UPD;
   9063         NumVecs = 1; isLoad = false; break;
   9064       case Intrinsic::arm_neon_vst2:     NewOpc = ARMISD::VST2_UPD;
   9065         NumVecs = 2; isLoad = false; break;
   9066       case Intrinsic::arm_neon_vst3:     NewOpc = ARMISD::VST3_UPD;
   9067         NumVecs = 3; isLoad = false; break;
   9068       case Intrinsic::arm_neon_vst4:     NewOpc = ARMISD::VST4_UPD;
   9069         NumVecs = 4; isLoad = false; break;
   9070       case Intrinsic::arm_neon_vst2lane: NewOpc = ARMISD::VST2LN_UPD;
   9071         NumVecs = 2; isLoad = false; isLaneOp = true; break;
   9072       case Intrinsic::arm_neon_vst3lane: NewOpc = ARMISD::VST3LN_UPD;
   9073         NumVecs = 3; isLoad = false; isLaneOp = true; break;
   9074       case Intrinsic::arm_neon_vst4lane: NewOpc = ARMISD::VST4LN_UPD;
   9075         NumVecs = 4; isLoad = false; isLaneOp = true; break;
   9076       }
   9077     } else {
   9078       isLaneOp = true;
   9079       switch (N->getOpcode()) {
   9080       default: llvm_unreachable("unexpected opcode for Neon base update");
   9081       case ARMISD::VLD2DUP: NewOpc = ARMISD::VLD2DUP_UPD; NumVecs = 2; break;
   9082       case ARMISD::VLD3DUP: NewOpc = ARMISD::VLD3DUP_UPD; NumVecs = 3; break;
   9083       case ARMISD::VLD4DUP: NewOpc = ARMISD::VLD4DUP_UPD; NumVecs = 4; break;
   9084       }
   9085     }
   9086 
   9087     // Find the size of memory referenced by the load/store.
   9088     EVT VecTy;
   9089     if (isLoad)
   9090       VecTy = N->getValueType(0);
   9091     else
   9092       VecTy = N->getOperand(AddrOpIdx+1).getValueType();
   9093     unsigned NumBytes = NumVecs * VecTy.getSizeInBits() / 8;
   9094     if (isLaneOp)
   9095       NumBytes /= VecTy.getVectorNumElements();
   9096 
   9097     // If the increment is a constant, it must match the memory ref size.
   9098     SDValue Inc = User->getOperand(User->getOperand(0) == Addr ? 1 : 0);
   9099     if (ConstantSDNode *CInc = dyn_cast<ConstantSDNode>(Inc.getNode())) {
   9100       uint64_t IncVal = CInc->getZExtValue();
   9101       if (IncVal != NumBytes)
   9102         continue;
   9103     } else if (NumBytes >= 3 * 16) {
   9104       // VLD3/4 and VST3/4 for 128-bit vectors are implemented with two
   9105       // separate instructions that make it harder to use a non-constant update.
   9106       continue;
   9107     }
   9108 
   9109     // Create the new updating load/store node.
   9110     EVT Tys[6];
   9111     unsigned NumResultVecs = (isLoad ? NumVecs : 0);
   9112     unsigned n;
   9113     for (n = 0; n < NumResultVecs; ++n)
   9114       Tys[n] = VecTy;
   9115     Tys[n++] = MVT::i32;
   9116     Tys[n] = MVT::Other;
   9117     SDVTList SDTys = DAG.getVTList(Tys, NumResultVecs+2);
   9118     SmallVector<SDValue, 8> Ops;
   9119     Ops.push_back(N->getOperand(0)); // incoming chain
   9120     Ops.push_back(N->getOperand(AddrOpIdx));
   9121     Ops.push_back(Inc);
   9122     for (unsigned i = AddrOpIdx + 1; i < N->getNumOperands(); ++i) {
   9123       Ops.push_back(N->getOperand(i));
   9124     }
   9125     MemIntrinsicSDNode *MemInt = cast<MemIntrinsicSDNode>(N);
   9126     SDValue UpdN = DAG.getMemIntrinsicNode(NewOpc, SDLoc(N), SDTys,
   9127                                            Ops.data(), Ops.size(),
   9128                                            MemInt->getMemoryVT(),
   9129                                            MemInt->getMemOperand());
   9130 
   9131     // Update the uses.
   9132     std::vector<SDValue> NewResults;
   9133     for (unsigned i = 0; i < NumResultVecs; ++i) {
   9134       NewResults.push_back(SDValue(UpdN.getNode(), i));
   9135     }
   9136     NewResults.push_back(SDValue(UpdN.getNode(), NumResultVecs+1)); // chain
   9137     DCI.CombineTo(N, NewResults);
   9138     DCI.CombineTo(User, SDValue(UpdN.getNode(), NumResultVecs));
   9139 
   9140     break;
   9141   }
   9142   return SDValue();
   9143 }
   9144 
   9145 /// CombineVLDDUP - For a VDUPLANE node N, check if its source operand is a
   9146 /// vldN-lane (N > 1) intrinsic, and if all the other uses of that intrinsic
   9147 /// are also VDUPLANEs.  If so, combine them to a vldN-dup operation and
   9148 /// return true.
   9149 static bool CombineVLDDUP(SDNode *N, TargetLowering::DAGCombinerInfo &DCI) {
   9150   SelectionDAG &DAG = DCI.DAG;
   9151   EVT VT = N->getValueType(0);
   9152   // vldN-dup instructions only support 64-bit vectors for N > 1.
   9153   if (!VT.is64BitVector())
   9154     return false;
   9155 
   9156   // Check if the VDUPLANE operand is a vldN-dup intrinsic.
   9157   SDNode *VLD = N->getOperand(0).getNode();
   9158   if (VLD->getOpcode() != ISD::INTRINSIC_W_CHAIN)
   9159     return false;
   9160   unsigned NumVecs = 0;
   9161   unsigned NewOpc = 0;
   9162   unsigned IntNo = cast<ConstantSDNode>(VLD->getOperand(1))->getZExtValue();
   9163   if (IntNo == Intrinsic::arm_neon_vld2lane) {
   9164     NumVecs = 2;
   9165     NewOpc = ARMISD::VLD2DUP;
   9166   } else if (IntNo == Intrinsic::arm_neon_vld3lane) {
   9167     NumVecs = 3;
   9168     NewOpc = ARMISD::VLD3DUP;
   9169   } else if (IntNo == Intrinsic::arm_neon_vld4lane) {
   9170     NumVecs = 4;
   9171     NewOpc = ARMISD::VLD4DUP;
   9172   } else {
   9173     return false;
   9174   }
   9175 
   9176   // First check that all the vldN-lane uses are VDUPLANEs and that the lane
   9177   // numbers match the load.
   9178   unsigned VLDLaneNo =
   9179     cast<ConstantSDNode>(VLD->getOperand(NumVecs+3))->getZExtValue();
   9180   for (SDNode::use_iterator UI = VLD->use_begin(), UE = VLD->use_end();
   9181        UI != UE; ++UI) {
   9182     // Ignore uses of the chain result.
   9183     if (UI.getUse().getResNo() == NumVecs)
   9184       continue;
   9185     SDNode *User = *UI;
   9186     if (User->getOpcode() != ARMISD::VDUPLANE ||
   9187         VLDLaneNo != cast<ConstantSDNode>(User->getOperand(1))->getZExtValue())
   9188       return false;
   9189   }
   9190 
   9191   // Create the vldN-dup node.
   9192   EVT Tys[5];
   9193   unsigned n;
   9194   for (n = 0; n < NumVecs; ++n)
   9195     Tys[n] = VT;
   9196   Tys[n] = MVT::Other;
   9197   SDVTList SDTys = DAG.getVTList(Tys, NumVecs+1);
   9198   SDValue Ops[] = { VLD->getOperand(0), VLD->getOperand(2) };
   9199   MemIntrinsicSDNode *VLDMemInt = cast<MemIntrinsicSDNode>(VLD);
   9200   SDValue VLDDup = DAG.getMemIntrinsicNode(NewOpc, SDLoc(VLD), SDTys,
   9201                                            Ops, 2, VLDMemInt->getMemoryVT(),
   9202                                            VLDMemInt->getMemOperand());
   9203 
   9204   // Update the uses.
   9205   for (SDNode::use_iterator UI = VLD->use_begin(), UE = VLD->use_end();
   9206        UI != UE; ++UI) {
   9207     unsigned ResNo = UI.getUse().getResNo();
   9208     // Ignore uses of the chain result.
   9209     if (ResNo == NumVecs)
   9210       continue;
   9211     SDNode *User = *UI;
   9212     DCI.CombineTo(User, SDValue(VLDDup.getNode(), ResNo));
   9213   }
   9214 
   9215   // Now the vldN-lane intrinsic is dead except for its chain result.
   9216   // Update uses of the chain.
   9217   std::vector<SDValue> VLDDupResults;
   9218   for (unsigned n = 0; n < NumVecs; ++n)
   9219     VLDDupResults.push_back(SDValue(VLDDup.getNode(), n));
   9220   VLDDupResults.push_back(SDValue(VLDDup.getNode(), NumVecs));
   9221   DCI.CombineTo(VLD, VLDDupResults);
   9222 
   9223   return true;
   9224 }
   9225 
   9226 /// PerformVDUPLANECombine - Target-specific dag combine xforms for
   9227 /// ARMISD::VDUPLANE.
   9228 static SDValue PerformVDUPLANECombine(SDNode *N,
   9229                                       TargetLowering::DAGCombinerInfo &DCI) {
   9230   SDValue Op = N->getOperand(0);
   9231 
   9232   // If the source is a vldN-lane (N > 1) intrinsic, and all the other uses
   9233   // of that intrinsic are also VDUPLANEs, combine them to a vldN-dup operation.
   9234   if (CombineVLDDUP(N, DCI))
   9235     return SDValue(N, 0);
   9236 
   9237   // If the source is already a VMOVIMM or VMVNIMM splat, the VDUPLANE is
   9238   // redundant.  Ignore bit_converts for now; element sizes are checked below.
   9239   while (Op.getOpcode() == ISD::BITCAST)
   9240     Op = Op.getOperand(0);
   9241   if (Op.getOpcode() != ARMISD::VMOVIMM && Op.getOpcode() != ARMISD::VMVNIMM)
   9242     return SDValue();
   9243 
   9244   // Make sure the VMOV element size is not bigger than the VDUPLANE elements.
   9245   unsigned EltSize = Op.getValueType().getVectorElementType().getSizeInBits();
   9246   // The canonical VMOV for a zero vector uses a 32-bit element size.
   9247   unsigned Imm = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
   9248   unsigned EltBits;
   9249   if (ARM_AM::decodeNEONModImm(Imm, EltBits) == 0)
   9250     EltSize = 8;
   9251   EVT VT = N->getValueType(0);
   9252   if (EltSize > VT.getVectorElementType().getSizeInBits())
   9253     return SDValue();
   9254 
   9255   return DCI.DAG.getNode(ISD::BITCAST, SDLoc(N), VT, Op);
   9256 }
   9257 
   9258 // isConstVecPow2 - Return true if each vector element is a power of 2, all
   9259 // elements are the same constant, C, and Log2(C) ranges from 1 to 32.
   9260 static bool isConstVecPow2(SDValue ConstVec, bool isSigned, uint64_t &C)
   9261 {
   9262   integerPart cN;
   9263   integerPart c0 = 0;
   9264   for (unsigned I = 0, E = ConstVec.getValueType().getVectorNumElements();
   9265        I != E; I++) {
   9266     ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(ConstVec.getOperand(I));
   9267     if (!C)
   9268       return false;
   9269 
   9270     bool isExact;
   9271     APFloat APF = C->getValueAPF();
   9272     if (APF.convertToInteger(&cN, 64, isSigned, APFloat::rmTowardZero, &isExact)
   9273         != APFloat::opOK || !isExact)
   9274       return false;
   9275 
   9276     c0 = (I == 0) ? cN : c0;
   9277     if (!isPowerOf2_64(cN) || c0 != cN || Log2_64(c0) < 1 || Log2_64(c0) > 32)
   9278       return false;
   9279   }
   9280   C = c0;
   9281   return true;
   9282 }
   9283 
   9284 /// PerformVCVTCombine - VCVT (floating-point to fixed-point, Advanced SIMD)
   9285 /// can replace combinations of VMUL and VCVT (floating-point to integer)
   9286 /// when the VMUL has a constant operand that is a power of 2.
   9287 ///
   9288 /// Example (assume d17 = <float 8.000000e+00, float 8.000000e+00>):
   9289 ///  vmul.f32        d16, d17, d16
   9290 ///  vcvt.s32.f32    d16, d16
   9291 /// becomes:
   9292 ///  vcvt.s32.f32    d16, d16, #3
   9293 static SDValue PerformVCVTCombine(SDNode *N,
   9294                                   TargetLowering::DAGCombinerInfo &DCI,
   9295                                   const ARMSubtarget *Subtarget) {
   9296   SelectionDAG &DAG = DCI.DAG;
   9297   SDValue Op = N->getOperand(0);
   9298 
   9299   if (!Subtarget->hasNEON() || !Op.getValueType().isVector() ||
   9300       Op.getOpcode() != ISD::FMUL)
   9301     return SDValue();
   9302 
   9303   uint64_t C;
   9304   SDValue N0 = Op->getOperand(0);
   9305   SDValue ConstVec = Op->getOperand(1);
   9306   bool isSigned = N->getOpcode() == ISD::FP_TO_SINT;
   9307 
   9308   if (ConstVec.getOpcode() != ISD::BUILD_VECTOR ||
   9309       !isConstVecPow2(ConstVec, isSigned, C))
   9310     return SDValue();
   9311 
   9312   MVT FloatTy = Op.getSimpleValueType().getVectorElementType();
   9313   MVT IntTy = N->getSimpleValueType(0).getVectorElementType();
   9314   if (FloatTy.getSizeInBits() != 32 || IntTy.getSizeInBits() > 32) {
   9315     // These instructions only exist converting from f32 to i32. We can handle
   9316     // smaller integers by generating an extra truncate, but larger ones would
   9317     // be lossy.
   9318     return SDValue();
   9319   }
   9320 
   9321   unsigned IntrinsicOpcode = isSigned ? Intrinsic::arm_neon_vcvtfp2fxs :
   9322     Intrinsic::arm_neon_vcvtfp2fxu;
   9323   unsigned NumLanes = Op.getValueType().getVectorNumElements();
   9324   SDValue FixConv =  DAG.getNode(ISD::INTRINSIC_WO_CHAIN, SDLoc(N),
   9325                                  NumLanes == 2 ? MVT::v2i32 : MVT::v4i32,
   9326                                  DAG.getConstant(IntrinsicOpcode, MVT::i32), N0,
   9327                                  DAG.getConstant(Log2_64(C), MVT::i32));
   9328 
   9329   if (IntTy.getSizeInBits() < FloatTy.getSizeInBits())
   9330     FixConv = DAG.getNode(ISD::TRUNCATE, SDLoc(N), N->getValueType(0), FixConv);
   9331 
   9332   return FixConv;
   9333 }
   9334 
   9335 /// PerformVDIVCombine - VCVT (fixed-point to floating-point, Advanced SIMD)
   9336 /// can replace combinations of VCVT (integer to floating-point) and VDIV
   9337 /// when the VDIV has a constant operand that is a power of 2.
   9338 ///
   9339 /// Example (assume d17 = <float 8.000000e+00, float 8.000000e+00>):
   9340 ///  vcvt.f32.s32    d16, d16
   9341 ///  vdiv.f32        d16, d17, d16
   9342 /// becomes:
   9343 ///  vcvt.f32.s32    d16, d16, #3
   9344 static SDValue PerformVDIVCombine(SDNode *N,
   9345                                   TargetLowering::DAGCombinerInfo &DCI,
   9346                                   const ARMSubtarget *Subtarget) {
   9347   SelectionDAG &DAG = DCI.DAG;
   9348   SDValue Op = N->getOperand(0);
   9349   unsigned OpOpcode = Op.getNode()->getOpcode();
   9350 
   9351   if (!Subtarget->hasNEON() || !N->getValueType(0).isVector() ||
   9352       (OpOpcode != ISD::SINT_TO_FP && OpOpcode != ISD::UINT_TO_FP))
   9353     return SDValue();
   9354 
   9355   uint64_t C;
   9356   SDValue ConstVec = N->getOperand(1);
   9357   bool isSigned = OpOpcode == ISD::SINT_TO_FP;
   9358 
   9359   if (ConstVec.getOpcode() != ISD::BUILD_VECTOR ||
   9360       !isConstVecPow2(ConstVec, isSigned, C))
   9361     return SDValue();
   9362 
   9363   MVT FloatTy = N->getSimpleValueType(0).getVectorElementType();
   9364   MVT IntTy = Op.getOperand(0).getSimpleValueType().getVectorElementType();
   9365   if (FloatTy.getSizeInBits() != 32 || IntTy.getSizeInBits() > 32) {
   9366     // These instructions only exist converting from i32 to f32. We can handle
   9367     // smaller integers by generating an extra extend, but larger ones would
   9368     // be lossy.
   9369     return SDValue();
   9370   }
   9371 
   9372   SDValue ConvInput = Op.getOperand(0);
   9373   unsigned NumLanes = Op.getValueType().getVectorNumElements();
   9374   if (IntTy.getSizeInBits() < FloatTy.getSizeInBits())
   9375     ConvInput = DAG.getNode(isSigned ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND,
   9376                             SDLoc(N), NumLanes == 2 ? MVT::v2i32 : MVT::v4i32,
   9377                             ConvInput);
   9378 
   9379   unsigned IntrinsicOpcode = isSigned ? Intrinsic::arm_neon_vcvtfxs2fp :
   9380     Intrinsic::arm_neon_vcvtfxu2fp;
   9381   return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, SDLoc(N),
   9382                      Op.getValueType(),
   9383                      DAG.getConstant(IntrinsicOpcode, MVT::i32),
   9384                      ConvInput, DAG.getConstant(Log2_64(C), MVT::i32));
   9385 }
   9386 
   9387 /// Getvshiftimm - Check if this is a valid build_vector for the immediate
   9388 /// operand of a vector shift operation, where all the elements of the
   9389 /// build_vector must have the same constant integer value.
   9390 static bool getVShiftImm(SDValue Op, unsigned ElementBits, int64_t &Cnt) {
   9391   // Ignore bit_converts.
   9392   while (Op.getOpcode() == ISD::BITCAST)
   9393     Op = Op.getOperand(0);
   9394   BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(Op.getNode());
   9395   APInt SplatBits, SplatUndef;
   9396   unsigned SplatBitSize;
   9397   bool HasAnyUndefs;
   9398   if (! BVN || ! BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize,
   9399                                       HasAnyUndefs, ElementBits) ||
   9400       SplatBitSize > ElementBits)
   9401     return false;
   9402   Cnt = SplatBits.getSExtValue();
   9403   return true;
   9404 }
   9405 
   9406 /// isVShiftLImm - Check if this is a valid build_vector for the immediate
   9407 /// operand of a vector shift left operation.  That value must be in the range:
   9408 ///   0 <= Value < ElementBits for a left shift; or
   9409 ///   0 <= Value <= ElementBits for a long left shift.
   9410 static bool isVShiftLImm(SDValue Op, EVT VT, bool isLong, int64_t &Cnt) {
   9411   assert(VT.isVector() && "vector shift count is not a vector type");
   9412   unsigned ElementBits = VT.getVectorElementType().getSizeInBits();
   9413   if (! getVShiftImm(Op, ElementBits, Cnt))
   9414     return false;
   9415   return (Cnt >= 0 && (isLong ? Cnt-1 : Cnt) < ElementBits);
   9416 }
   9417 
   9418 /// isVShiftRImm - Check if this is a valid build_vector for the immediate
   9419 /// operand of a vector shift right operation.  For a shift opcode, the value
   9420 /// is positive, but for an intrinsic the value count must be negative. The
   9421 /// absolute value must be in the range:
   9422 ///   1 <= |Value| <= ElementBits for a right shift; or
   9423 ///   1 <= |Value| <= ElementBits/2 for a narrow right shift.
   9424 static bool isVShiftRImm(SDValue Op, EVT VT, bool isNarrow, bool isIntrinsic,
   9425                          int64_t &Cnt) {
   9426   assert(VT.isVector() && "vector shift count is not a vector type");
   9427   unsigned ElementBits = VT.getVectorElementType().getSizeInBits();
   9428   if (! getVShiftImm(Op, ElementBits, Cnt))
   9429     return false;
   9430   if (isIntrinsic)
   9431     Cnt = -Cnt;
   9432   return (Cnt >= 1 && Cnt <= (isNarrow ? ElementBits/2 : ElementBits));
   9433 }
   9434 
   9435 /// PerformIntrinsicCombine - ARM-specific DAG combining for intrinsics.
   9436 static SDValue PerformIntrinsicCombine(SDNode *N, SelectionDAG &DAG) {
   9437   unsigned IntNo = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue();
   9438   switch (IntNo) {
   9439   default:
   9440     // Don't do anything for most intrinsics.
   9441     break;
   9442 
   9443   // Vector shifts: check for immediate versions and lower them.
   9444   // Note: This is done during DAG combining instead of DAG legalizing because
   9445   // the build_vectors for 64-bit vector element shift counts are generally
   9446   // not legal, and it is hard to see their values after they get legalized to
   9447   // loads from a constant pool.
   9448   case Intrinsic::arm_neon_vshifts:
   9449   case Intrinsic::arm_neon_vshiftu:
   9450   case Intrinsic::arm_neon_vshiftls:
   9451   case Intrinsic::arm_neon_vshiftlu:
   9452   case Intrinsic::arm_neon_vshiftn:
   9453   case Intrinsic::arm_neon_vrshifts:
   9454   case Intrinsic::arm_neon_vrshiftu:
   9455   case Intrinsic::arm_neon_vrshiftn:
   9456   case Intrinsic::arm_neon_vqshifts:
   9457   case Intrinsic::arm_neon_vqshiftu:
   9458   case Intrinsic::arm_neon_vqshiftsu:
   9459   case Intrinsic::arm_neon_vqshiftns:
   9460   case Intrinsic::arm_neon_vqshiftnu:
   9461   case Intrinsic::arm_neon_vqshiftnsu:
   9462   case Intrinsic::arm_neon_vqrshiftns:
   9463   case Intrinsic::arm_neon_vqrshiftnu:
   9464   case Intrinsic::arm_neon_vqrshiftnsu: {
   9465     EVT VT = N->getOperand(1).getValueType();
   9466     int64_t Cnt;
   9467     unsigned VShiftOpc = 0;
   9468 
   9469     switch (IntNo) {
   9470     case Intrinsic::arm_neon_vshifts:
   9471     case Intrinsic::arm_neon_vshiftu:
   9472       if (isVShiftLImm(N->getOperand(2), VT, false, Cnt)) {
   9473         VShiftOpc = ARMISD::VSHL;
   9474         break;
   9475       }
   9476       if (isVShiftRImm(N->getOperand(2), VT, false, true, Cnt)) {
   9477         VShiftOpc = (IntNo == Intrinsic::arm_neon_vshifts ?
   9478                      ARMISD::VSHRs : ARMISD::VSHRu);
   9479         break;
   9480       }
   9481       return SDValue();
   9482 
   9483     case Intrinsic::arm_neon_vshiftls:
   9484     case Intrinsic::arm_neon_vshiftlu:
   9485       if (isVShiftLImm(N->getOperand(2), VT, true, Cnt))
   9486         break;
   9487       llvm_unreachable("invalid shift count for vshll intrinsic");
   9488 
   9489     case Intrinsic::arm_neon_vrshifts:
   9490     case Intrinsic::arm_neon_vrshiftu:
   9491       if (isVShiftRImm(N->getOperand(2), VT, false, true, Cnt))
   9492         break;
   9493       return SDValue();
   9494 
   9495     case Intrinsic::arm_neon_vqshifts:
   9496     case Intrinsic::arm_neon_vqshiftu:
   9497       if (isVShiftLImm(N->getOperand(2), VT, false, Cnt))
   9498         break;
   9499       return SDValue();
   9500 
   9501     case Intrinsic::arm_neon_vqshiftsu:
   9502       if (isVShiftLImm(N->getOperand(2), VT, false, Cnt))
   9503         break;
   9504       llvm_unreachable("invalid shift count for vqshlu intrinsic");
   9505 
   9506     case Intrinsic::arm_neon_vshiftn:
   9507     case Intrinsic::arm_neon_vrshiftn:
   9508     case Intrinsic::arm_neon_vqshiftns:
   9509     case Intrinsic::arm_neon_vqshiftnu:
   9510     case Intrinsic::arm_neon_vqshiftnsu:
   9511     case Intrinsic::arm_neon_vqrshiftns:
   9512     case Intrinsic::arm_neon_vqrshiftnu:
   9513     case Intrinsic::arm_neon_vqrshiftnsu:
   9514       // Narrowing shifts require an immediate right shift.
   9515       if (isVShiftRImm(N->getOperand(2), VT, true, true, Cnt))
   9516         break;
   9517       llvm_unreachable("invalid shift count for narrowing vector shift "
   9518                        "intrinsic");
   9519 
   9520     default:
   9521       llvm_unreachable("unhandled vector shift");
   9522     }
   9523 
   9524     switch (IntNo) {
   9525     case Intrinsic::arm_neon_vshifts:
   9526     case Intrinsic::arm_neon_vshiftu:
   9527       // Opcode already set above.
   9528       break;
   9529     case Intrinsic::arm_neon_vshiftls:
   9530     case Intrinsic::arm_neon_vshiftlu:
   9531       if (Cnt == VT.getVectorElementType().getSizeInBits())
   9532         VShiftOpc = ARMISD::VSHLLi;
   9533       else
   9534         VShiftOpc = (IntNo == Intrinsic::arm_neon_vshiftls ?
   9535                      ARMISD::VSHLLs : ARMISD::VSHLLu);
   9536       break;
   9537     case Intrinsic::arm_neon_vshiftn:
   9538       VShiftOpc = ARMISD::VSHRN; break;
   9539     case Intrinsic::arm_neon_vrshifts:
   9540       VShiftOpc = ARMISD::VRSHRs; break;
   9541     case Intrinsic::arm_neon_vrshiftu:
   9542       VShiftOpc = ARMISD::VRSHRu; break;
   9543     case Intrinsic::arm_neon_vrshiftn:
   9544       VShiftOpc = ARMISD::VRSHRN; break;
   9545     case Intrinsic::arm_neon_vqshifts:
   9546       VShiftOpc = ARMISD::VQSHLs; break;
   9547     case Intrinsic::arm_neon_vqshiftu:
   9548       VShiftOpc = ARMISD::VQSHLu; break;
   9549     case Intrinsic::arm_neon_vqshiftsu:
   9550       VShiftOpc = ARMISD::VQSHLsu; break;
   9551     case Intrinsic::arm_neon_vqshiftns:
   9552       VShiftOpc = ARMISD::VQSHRNs; break;
   9553     case Intrinsic::arm_neon_vqshiftnu:
   9554       VShiftOpc = ARMISD::VQSHRNu; break;
   9555     case Intrinsic::arm_neon_vqshiftnsu:
   9556       VShiftOpc = ARMISD::VQSHRNsu; break;
   9557     case Intrinsic::arm_neon_vqrshiftns:
   9558       VShiftOpc = ARMISD::VQRSHRNs; break;
   9559     case Intrinsic::arm_neon_vqrshiftnu:
   9560       VShiftOpc = ARMISD::VQRSHRNu; break;
   9561     case Intrinsic::arm_neon_vqrshiftnsu:
   9562       VShiftOpc = ARMISD::VQRSHRNsu; break;
   9563     }
   9564 
   9565     return DAG.getNode(VShiftOpc, SDLoc(N), N->getValueType(0),
   9566                        N->getOperand(1), DAG.getConstant(Cnt, MVT::i32));
   9567   }
   9568 
   9569   case Intrinsic::arm_neon_vshiftins: {
   9570     EVT VT = N->getOperand(1).getValueType();
   9571     int64_t Cnt;
   9572     unsigned VShiftOpc = 0;
   9573 
   9574     if (isVShiftLImm(N->getOperand(3), VT, false, Cnt))
   9575       VShiftOpc = ARMISD::VSLI;
   9576     else if (isVShiftRImm(N->getOperand(3), VT, false, true, Cnt))
   9577       VShiftOpc = ARMISD::VSRI;
   9578     else {
   9579       llvm_unreachable("invalid shift count for vsli/vsri intrinsic");
   9580     }
   9581 
   9582     return DAG.getNode(VShiftOpc, SDLoc(N), N->getValueType(0),
   9583                        N->getOperand(1), N->getOperand(2),
   9584                        DAG.getConstant(Cnt, MVT::i32));
   9585   }
   9586 
   9587   case Intrinsic::arm_neon_vqrshifts:
   9588   case Intrinsic::arm_neon_vqrshiftu:
   9589     // No immediate versions of these to check for.
   9590     break;
   9591   }
   9592 
   9593   return SDValue();
   9594 }
   9595 
   9596 /// PerformShiftCombine - Checks for immediate versions of vector shifts and
   9597 /// lowers them.  As with the vector shift intrinsics, this is done during DAG
   9598 /// combining instead of DAG legalizing because the build_vectors for 64-bit
   9599 /// vector element shift counts are generally not legal, and it is hard to see
   9600 /// their values after they get legalized to loads from a constant pool.
   9601 static SDValue PerformShiftCombine(SDNode *N, SelectionDAG &DAG,
   9602                                    const ARMSubtarget *ST) {
   9603   EVT VT = N->getValueType(0);
   9604   if (N->getOpcode() == ISD::SRL && VT == MVT::i32 && ST->hasV6Ops()) {
   9605     // Canonicalize (srl (bswap x), 16) to (rotr (bswap x), 16) if the high
   9606     // 16-bits of x is zero. This optimizes rev + lsr 16 to rev16.
   9607     SDValue N1 = N->getOperand(1);
   9608     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(N1)) {
   9609       SDValue N0 = N->getOperand(0);
   9610       if (C->getZExtValue() == 16 && N0.getOpcode() == ISD::BSWAP &&
   9611           DAG.MaskedValueIsZero(N0.getOperand(0),
   9612                                 APInt::getHighBitsSet(32, 16)))
   9613         return DAG.getNode(ISD::ROTR, SDLoc(N), VT, N0, N1);
   9614     }
   9615   }
   9616 
   9617   // Nothing to be done for scalar shifts.
   9618   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
   9619   if (!VT.isVector() || !TLI.isTypeLegal(VT))
   9620     return SDValue();
   9621 
   9622   assert(ST->hasNEON() && "unexpected vector shift");
   9623   int64_t Cnt;
   9624 
   9625   switch (N->getOpcode()) {
   9626   default: llvm_unreachable("unexpected shift opcode");
   9627 
   9628   case ISD::SHL:
   9629     if (isVShiftLImm(N->getOperand(1), VT, false, Cnt))
   9630       return DAG.getNode(ARMISD::VSHL, SDLoc(N), VT, N->getOperand(0),
   9631                          DAG.getConstant(Cnt, MVT::i32));
   9632     break;
   9633 
   9634   case ISD::SRA:
   9635   case ISD::SRL:
   9636     if (isVShiftRImm(N->getOperand(1), VT, false, false, Cnt)) {
   9637       unsigned VShiftOpc = (N->getOpcode() == ISD::SRA ?
   9638                             ARMISD::VSHRs : ARMISD::VSHRu);
   9639       return DAG.getNode(VShiftOpc, SDLoc(N), VT, N->getOperand(0),
   9640                          DAG.getConstant(Cnt, MVT::i32));
   9641     }
   9642   }
   9643   return SDValue();
   9644 }
   9645 
   9646 /// PerformExtendCombine - Target-specific DAG combining for ISD::SIGN_EXTEND,
   9647 /// ISD::ZERO_EXTEND, and ISD::ANY_EXTEND.
   9648 static SDValue PerformExtendCombine(SDNode *N, SelectionDAG &DAG,
   9649                                     const ARMSubtarget *ST) {
   9650   SDValue N0 = N->getOperand(0);
   9651 
   9652   // Check for sign- and zero-extensions of vector extract operations of 8-
   9653   // and 16-bit vector elements.  NEON supports these directly.  They are
   9654   // handled during DAG combining because type legalization will promote them
   9655   // to 32-bit types and it is messy to recognize the operations after that.
   9656   if (ST->hasNEON() && N0.getOpcode() == ISD::EXTRACT_VECTOR_ELT) {
   9657     SDValue Vec = N0.getOperand(0);
   9658     SDValue Lane = N0.getOperand(1);
   9659     EVT VT = N->getValueType(0);
   9660     EVT EltVT = N0.getValueType();
   9661     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
   9662 
   9663     if (VT == MVT::i32 &&
   9664         (EltVT == MVT::i8 || EltVT == MVT::i16) &&
   9665         TLI.isTypeLegal(Vec.getValueType()) &&
   9666         isa<ConstantSDNode>(Lane)) {
   9667 
   9668       unsigned Opc = 0;
   9669       switch (N->getOpcode()) {
   9670       default: llvm_unreachable("unexpected opcode");
   9671       case ISD::SIGN_EXTEND:
   9672         Opc = ARMISD::VGETLANEs;
   9673         break;
   9674       case ISD::ZERO_EXTEND:
   9675       case ISD::ANY_EXTEND:
   9676         Opc = ARMISD::VGETLANEu;
   9677         break;
   9678       }
   9679       return DAG.getNode(Opc, SDLoc(N), VT, Vec, Lane);
   9680     }
   9681   }
   9682 
   9683   return SDValue();
   9684 }
   9685 
   9686 /// PerformSELECT_CCCombine - Target-specific DAG combining for ISD::SELECT_CC
   9687 /// to match f32 max/min patterns to use NEON vmax/vmin instructions.
   9688 static SDValue PerformSELECT_CCCombine(SDNode *N, SelectionDAG &DAG,
   9689                                        const ARMSubtarget *ST) {
   9690   // If the target supports NEON, try to use vmax/vmin instructions for f32
   9691   // selects like "x < y ? x : y".  Unless the NoNaNsFPMath option is set,
   9692   // be careful about NaNs:  NEON's vmax/vmin return NaN if either operand is
   9693   // a NaN; only do the transformation when it matches that behavior.
   9694 
   9695   // For now only do this when using NEON for FP operations; if using VFP, it
   9696   // is not obvious that the benefit outweighs the cost of switching to the
   9697   // NEON pipeline.
   9698   if (!ST->hasNEON() || !ST->useNEONForSinglePrecisionFP() ||
   9699       N->getValueType(0) != MVT::f32)
   9700     return SDValue();
   9701 
   9702   SDValue CondLHS = N->getOperand(0);
   9703   SDValue CondRHS = N->getOperand(1);
   9704   SDValue LHS = N->getOperand(2);
   9705   SDValue RHS = N->getOperand(3);
   9706   ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(4))->get();
   9707 
   9708   unsigned Opcode = 0;
   9709   bool IsReversed;
   9710   if (DAG.isEqualTo(LHS, CondLHS) && DAG.isEqualTo(RHS, CondRHS)) {
   9711     IsReversed = false; // x CC y ? x : y
   9712   } else if (DAG.isEqualTo(LHS, CondRHS) && DAG.isEqualTo(RHS, CondLHS)) {
   9713     IsReversed = true ; // x CC y ? y : x
   9714   } else {
   9715     return SDValue();
   9716   }
   9717 
   9718   bool IsUnordered;
   9719   switch (CC) {
   9720   default: break;
   9721   case ISD::SETOLT:
   9722   case ISD::SETOLE:
   9723   case ISD::SETLT:
   9724   case ISD::SETLE:
   9725   case ISD::SETULT:
   9726   case ISD::SETULE:
   9727     // If LHS is NaN, an ordered comparison will be false and the result will
   9728     // be the RHS, but vmin(NaN, RHS) = NaN.  Avoid this by checking that LHS
   9729     // != NaN.  Likewise, for unordered comparisons, check for RHS != NaN.
   9730     IsUnordered = (CC == ISD::SETULT || CC == ISD::SETULE);
   9731     if (!DAG.isKnownNeverNaN(IsUnordered ? RHS : LHS))
   9732       break;
   9733     // For less-than-or-equal comparisons, "+0 <= -0" will be true but vmin
   9734     // will return -0, so vmin can only be used for unsafe math or if one of
   9735     // the operands is known to be nonzero.
   9736     if ((CC == ISD::SETLE || CC == ISD::SETOLE || CC == ISD::SETULE) &&
   9737         !DAG.getTarget().Options.UnsafeFPMath &&
   9738         !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
   9739       break;
   9740     Opcode = IsReversed ? ARMISD::FMAX : ARMISD::FMIN;
   9741     break;
   9742 
   9743   case ISD::SETOGT:
   9744   case ISD::SETOGE:
   9745   case ISD::SETGT:
   9746   case ISD::SETGE:
   9747   case ISD::SETUGT:
   9748   case ISD::SETUGE:
   9749     // If LHS is NaN, an ordered comparison will be false and the result will
   9750     // be the RHS, but vmax(NaN, RHS) = NaN.  Avoid this by checking that LHS
   9751     // != NaN.  Likewise, for unordered comparisons, check for RHS != NaN.
   9752     IsUnordered = (CC == ISD::SETUGT || CC == ISD::SETUGE);
   9753     if (!DAG.isKnownNeverNaN(IsUnordered ? RHS : LHS))
   9754       break;
   9755     // For greater-than-or-equal comparisons, "-0 >= +0" will be true but vmax
   9756     // will return +0, so vmax can only be used for unsafe math or if one of
   9757     // the operands is known to be nonzero.
   9758     if ((CC == ISD::SETGE || CC == ISD::SETOGE || CC == ISD::SETUGE) &&
   9759         !DAG.getTarget().Options.UnsafeFPMath &&
   9760         !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
   9761       break;
   9762     Opcode = IsReversed ? ARMISD::FMIN : ARMISD::FMAX;
   9763     break;
   9764   }
   9765 
   9766   if (!Opcode)
   9767     return SDValue();
   9768   return DAG.getNode(Opcode, SDLoc(N), N->getValueType(0), LHS, RHS);
   9769 }
   9770 
   9771 /// PerformCMOVCombine - Target-specific DAG combining for ARMISD::CMOV.
   9772 SDValue
   9773 ARMTargetLowering::PerformCMOVCombine(SDNode *N, SelectionDAG &DAG) const {
   9774   SDValue Cmp = N->getOperand(4);
   9775   if (Cmp.getOpcode() != ARMISD::CMPZ)
   9776     // Only looking at EQ and NE cases.
   9777     return SDValue();
   9778 
   9779   EVT VT = N->getValueType(0);
   9780   SDLoc dl(N);
   9781   SDValue LHS = Cmp.getOperand(0);
   9782   SDValue RHS = Cmp.getOperand(1);
   9783   SDValue FalseVal = N->getOperand(0);
   9784   SDValue TrueVal = N->getOperand(1);
   9785   SDValue ARMcc = N->getOperand(2);
   9786   ARMCC::CondCodes CC =
   9787     (ARMCC::CondCodes)cast<ConstantSDNode>(ARMcc)->getZExtValue();
   9788 
   9789   // Simplify
   9790   //   mov     r1, r0
   9791   //   cmp     r1, x
   9792   //   mov     r0, y
   9793   //   moveq   r0, x
   9794   // to
   9795   //   cmp     r0, x
   9796   //   movne   r0, y
   9797   //
   9798   //   mov     r1, r0
   9799   //   cmp     r1, x
   9800   //   mov     r0, x
   9801   //   movne   r0, y
   9802   // to
   9803   //   cmp     r0, x
   9804   //   movne   r0, y
   9805   /// FIXME: Turn this into a target neutral optimization?
   9806   SDValue Res;
   9807   if (CC == ARMCC::NE && FalseVal == RHS && FalseVal != LHS) {
   9808     Res = DAG.getNode(ARMISD::CMOV, dl, VT, LHS, TrueVal, ARMcc,
   9809                       N->getOperand(3), Cmp);
   9810   } else if (CC == ARMCC::EQ && TrueVal == RHS) {
   9811     SDValue ARMcc;
   9812     SDValue NewCmp = getARMCmp(LHS, RHS, ISD::SETNE, ARMcc, DAG, dl);
   9813     Res = DAG.getNode(ARMISD::CMOV, dl, VT, LHS, FalseVal, ARMcc,
   9814                       N->getOperand(3), NewCmp);
   9815   }
   9816 
   9817   if (Res.getNode()) {
   9818     APInt KnownZero, KnownOne;
   9819     DAG.ComputeMaskedBits(SDValue(N,0), KnownZero, KnownOne);
   9820     // Capture demanded bits information that would be otherwise lost.
   9821     if (KnownZero == 0xfffffffe)
   9822       Res = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Res,
   9823                         DAG.getValueType(MVT::i1));
   9824     else if (KnownZero == 0xffffff00)
   9825       Res = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Res,
   9826                         DAG.getValueType(MVT::i8));
   9827     else if (KnownZero == 0xffff0000)
   9828       Res = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Res,
   9829                         DAG.getValueType(MVT::i16));
   9830   }
   9831 
   9832   return Res;
   9833 }
   9834 
   9835 SDValue ARMTargetLowering::PerformDAGCombine(SDNode *N,
   9836                                              DAGCombinerInfo &DCI) const {
   9837   switch (N->getOpcode()) {
   9838   default: break;
   9839   case ISD::ADDC:       return PerformADDCCombine(N, DCI, Subtarget);
   9840   case ISD::ADD:        return PerformADDCombine(N, DCI, Subtarget);
   9841   case ISD::SUB:        return PerformSUBCombine(N, DCI);
   9842   case ISD::MUL:        return PerformMULCombine(N, DCI, Subtarget);
   9843   case ISD::OR:         return PerformORCombine(N, DCI, Subtarget);
   9844   case ISD::XOR:        return PerformXORCombine(N, DCI, Subtarget);
   9845   case ISD::AND:        return PerformANDCombine(N, DCI, Subtarget);
   9846   case ARMISD::BFI:     return PerformBFICombine(N, DCI);
   9847   case ARMISD::VMOVRRD: return PerformVMOVRRDCombine(N, DCI);
   9848   case ARMISD::VMOVDRR: return PerformVMOVDRRCombine(N, DCI.DAG);
   9849   case ISD::STORE:      return PerformSTORECombine(N, DCI);
   9850   case ISD::BUILD_VECTOR: return PerformBUILD_VECTORCombine(N, DCI);
   9851   case ISD::INSERT_VECTOR_ELT: return PerformInsertEltCombine(N, DCI);
   9852   case ISD::VECTOR_SHUFFLE: return PerformVECTOR_SHUFFLECombine(N, DCI.DAG);
   9853   case ARMISD::VDUPLANE: return PerformVDUPLANECombine(N, DCI);
   9854   case ISD::FP_TO_SINT:
   9855   case ISD::FP_TO_UINT: return PerformVCVTCombine(N, DCI, Subtarget);
   9856   case ISD::FDIV:       return PerformVDIVCombine(N, DCI, Subtarget);
   9857   case ISD::INTRINSIC_WO_CHAIN: return PerformIntrinsicCombine(N, DCI.DAG);
   9858   case ISD::SHL:
   9859   case ISD::SRA:
   9860   case ISD::SRL:        return PerformShiftCombine(N, DCI.DAG, Subtarget);
   9861   case ISD::SIGN_EXTEND:
   9862   case ISD::ZERO_EXTEND:
   9863   case ISD::ANY_EXTEND: return PerformExtendCombine(N, DCI.DAG, Subtarget);
   9864   case ISD::SELECT_CC:  return PerformSELECT_CCCombine(N, DCI.DAG, Subtarget);
   9865   case ARMISD::CMOV: return PerformCMOVCombine(N, DCI.DAG);
   9866   case ARMISD::VLD2DUP:
   9867   case ARMISD::VLD3DUP:
   9868   case ARMISD::VLD4DUP:
   9869     return CombineBaseUpdate(N, DCI);
   9870   case ARMISD::BUILD_VECTOR:
   9871     return PerformARMBUILD_VECTORCombine(N, DCI);
   9872   case ISD::INTRINSIC_VOID:
   9873   case ISD::INTRINSIC_W_CHAIN:
   9874     switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) {
   9875     case Intrinsic::arm_neon_vld1:
   9876     case Intrinsic::arm_neon_vld2:
   9877     case Intrinsic::arm_neon_vld3:
   9878     case Intrinsic::arm_neon_vld4:
   9879     case Intrinsic::arm_neon_vld2lane:
   9880     case Intrinsic::arm_neon_vld3lane:
   9881     case Intrinsic::arm_neon_vld4lane:
   9882     case Intrinsic::arm_neon_vst1:
   9883     case Intrinsic::arm_neon_vst2:
   9884     case Intrinsic::arm_neon_vst3:
   9885     case Intrinsic::arm_neon_vst4:
   9886     case Intrinsic::arm_neon_vst2lane:
   9887     case Intrinsic::arm_neon_vst3lane:
   9888     case Intrinsic::arm_neon_vst4lane:
   9889       return CombineBaseUpdate(N, DCI);
   9890     default: break;
   9891     }
   9892     break;
   9893   }
   9894   return SDValue();
   9895 }
   9896 
   9897 bool ARMTargetLowering::isDesirableToTransformToIntegerOp(unsigned Opc,
   9898                                                           EVT VT) const {
   9899   return (VT == MVT::f32) && (Opc == ISD::LOAD || Opc == ISD::STORE);
   9900 }
   9901 
   9902 bool ARMTargetLowering::allowsUnalignedMemoryAccesses(EVT VT, bool *Fast) const {
   9903   // The AllowsUnaliged flag models the SCTLR.A setting in ARM cpus
   9904   bool AllowsUnaligned = Subtarget->allowsUnalignedMem();
   9905 
   9906   switch (VT.getSimpleVT().SimpleTy) {
   9907   default:
   9908     return false;
   9909   case MVT::i8:
   9910   case MVT::i16:
   9911   case MVT::i32: {
   9912     // Unaligned access can use (for example) LRDB, LRDH, LDR
   9913     if (AllowsUnaligned) {
   9914       if (Fast)
   9915         *Fast = Subtarget->hasV7Ops();
   9916       return true;
   9917     }
   9918     return false;
   9919   }
   9920   case MVT::f64:
   9921   case MVT::v2f64: {
   9922     // For any little-endian targets with neon, we can support unaligned ld/st
   9923     // of D and Q (e.g. {D0,D1}) registers by using vld1.i8/vst1.i8.
   9924     // A big-endian target may also explictly support unaligned accesses
   9925     if (Subtarget->hasNEON() && (AllowsUnaligned || isLittleEndian())) {
   9926       if (Fast)
   9927         *Fast = true;
   9928       return true;
   9929     }
   9930     return false;
   9931   }
   9932   }
   9933 }
   9934 
   9935 static bool memOpAlign(unsigned DstAlign, unsigned SrcAlign,
   9936                        unsigned AlignCheck) {
   9937   return ((SrcAlign == 0 || SrcAlign % AlignCheck == 0) &&
   9938           (DstAlign == 0 || DstAlign % AlignCheck == 0));
   9939 }
   9940 
   9941 EVT ARMTargetLowering::getOptimalMemOpType(uint64_t Size,
   9942                                            unsigned DstAlign, unsigned SrcAlign,
   9943                                            bool IsMemset, bool ZeroMemset,
   9944                                            bool MemcpyStrSrc,
   9945                                            MachineFunction &MF) const {
   9946   const Function *F = MF.getFunction();
   9947 
   9948   // See if we can use NEON instructions for this...
   9949   if ((!IsMemset || ZeroMemset) &&
   9950       Subtarget->hasNEON() &&
   9951       !F->getAttributes().hasAttribute(AttributeSet::FunctionIndex,
   9952                                        Attribute::NoImplicitFloat)) {
   9953     bool Fast;
   9954     if (Size >= 16 &&
   9955         (memOpAlign(SrcAlign, DstAlign, 16) ||
   9956          (allowsUnalignedMemoryAccesses(MVT::v2f64, &Fast) && Fast))) {
   9957       return MVT::v2f64;
   9958     } else if (Size >= 8 &&
   9959                (memOpAlign(SrcAlign, DstAlign, 8) ||
   9960                 (allowsUnalignedMemoryAccesses(MVT::f64, &Fast) && Fast))) {
   9961       return MVT::f64;
   9962     }
   9963   }
   9964 
   9965   // Lowering to i32/i16 if the size permits.
   9966   if (Size >= 4)
   9967     return MVT::i32;
   9968   else if (Size >= 2)
   9969     return MVT::i16;
   9970 
   9971   // Let the target-independent logic figure it out.
   9972   return MVT::Other;
   9973 }
   9974 
   9975 bool ARMTargetLowering::isZExtFree(SDValue Val, EVT VT2) const {
   9976   if (Val.getOpcode() != ISD::LOAD)
   9977     return false;
   9978 
   9979   EVT VT1 = Val.getValueType();
   9980   if (!VT1.isSimple() || !VT1.isInteger() ||
   9981       !VT2.isSimple() || !VT2.isInteger())
   9982     return false;
   9983 
   9984   switch (VT1.getSimpleVT().SimpleTy) {
   9985   default: break;
   9986   case MVT::i1:
   9987   case MVT::i8:
   9988   case MVT::i16:
   9989     // 8-bit and 16-bit loads implicitly zero-extend to 32-bits.
   9990     return true;
   9991   }
   9992 
   9993   return false;
   9994 }
   9995 
   9996 bool ARMTargetLowering::allowTruncateForTailCall(Type *Ty1, Type *Ty2) const {
   9997   if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
   9998     return false;
   9999 
   10000   if (!isTypeLegal(EVT::getEVT(Ty1)))
   10001     return false;
   10002 
   10003   assert(Ty1->getPrimitiveSizeInBits() <= 64 && "i128 is probably not a noop");
   10004 
   10005   // Assuming the caller doesn't have a zeroext or signext return parameter,
   10006   // truncation all the way down to i1 is valid.
   10007   return true;
   10008 }
   10009 
   10010 
   10011 static bool isLegalT1AddressImmediate(int64_t V, EVT VT) {
   10012   if (V < 0)
   10013     return false;
   10014 
   10015   unsigned Scale = 1;
   10016   switch (VT.getSimpleVT().SimpleTy) {
   10017   default: return false;
   10018   case MVT::i1:
   10019   case MVT::i8:
   10020     // Scale == 1;
   10021     break;
   10022   case MVT::i16:
   10023     // Scale == 2;
   10024     Scale = 2;
   10025     break;
   10026   case MVT::i32:
   10027     // Scale == 4;
   10028     Scale = 4;
   10029     break;
   10030   }
   10031 
   10032   if ((V & (Scale - 1)) != 0)
   10033     return false;
   10034   V /= Scale;
   10035   return V == (V & ((1LL << 5) - 1));
   10036 }
   10037 
   10038 static bool isLegalT2AddressImmediate(int64_t V, EVT VT,
   10039                                       const ARMSubtarget *Subtarget) {
   10040   bool isNeg = false;
   10041   if (V < 0) {
   10042     isNeg = true;
   10043     V = - V;
   10044   }
   10045 
   10046   switch (VT.getSimpleVT().SimpleTy) {
   10047   default: return false;
   10048   case MVT::i1:
   10049   case MVT::i8:
   10050   case MVT::i16:
   10051   case MVT::i32:
   10052     // + imm12 or - imm8
   10053     if (isNeg)
   10054       return V == (V & ((1LL << 8) - 1));
   10055     return V == (V & ((1LL << 12) - 1));
   10056   case MVT::f32:
   10057   case MVT::f64:
   10058     // Same as ARM mode. FIXME: NEON?
   10059     if (!Subtarget->hasVFP2())
   10060       return false;
   10061     if ((V & 3) != 0)
   10062       return false;
   10063     V >>= 2;
   10064     return V == (V & ((1LL << 8) - 1));
   10065   }
   10066 }
   10067 
   10068 /// isLegalAddressImmediate - Return true if the integer value can be used
   10069 /// as the offset of the target addressing mode for load / store of the
   10070 /// given type.
   10071 static bool isLegalAddressImmediate(int64_t V, EVT VT,
   10072                                     const ARMSubtarget *Subtarget) {
   10073   if (V == 0)
   10074     return true;
   10075 
   10076   if (!VT.isSimple())
   10077     return false;
   10078 
   10079   if (Subtarget->isThumb1Only())
   10080     return isLegalT1AddressImmediate(V, VT);
   10081   else if (Subtarget->isThumb2())
   10082     return isLegalT2AddressImmediate(V, VT, Subtarget);
   10083 
   10084   // ARM mode.
   10085   if (V < 0)
   10086     V = - V;
   10087   switch (VT.getSimpleVT().SimpleTy) {
   10088   default: return false;
   10089   case MVT::i1:
   10090   case MVT::i8:
   10091   case MVT::i32:
   10092     // +- imm12
   10093     return V == (V & ((1LL << 12) - 1));
   10094   case MVT::i16:
   10095     // +- imm8
   10096     return V == (V & ((1LL << 8) - 1));
   10097   case MVT::f32:
   10098   case MVT::f64:
   10099     if (!Subtarget->hasVFP2()) // FIXME: NEON?
   10100       return false;
   10101     if ((V & 3) != 0)
   10102       return false;
   10103     V >>= 2;
   10104     return V == (V & ((1LL << 8) - 1));
   10105   }
   10106 }
   10107 
   10108 bool ARMTargetLowering::isLegalT2ScaledAddressingMode(const AddrMode &AM,
   10109                                                       EVT VT) const {
   10110   int Scale = AM.Scale;
   10111   if (Scale < 0)
   10112     return false;
   10113 
   10114   switch (VT.getSimpleVT().SimpleTy) {
   10115   default: return false;
   10116   case MVT::i1:
   10117   case MVT::i8:
   10118   case MVT::i16:
   10119   case MVT::i32:
   10120     if (Scale == 1)
   10121       return true;
   10122     // r + r << imm
   10123     Scale = Scale & ~1;
   10124     return Scale == 2 || Scale == 4 || Scale == 8;
   10125   case MVT::i64:
   10126     // r + r
   10127     if (((unsigned)AM.HasBaseReg + Scale) <= 2)
   10128       return true;
   10129     return false;
   10130   case MVT::isVoid:
   10131     // Note, we allow "void" uses (basically, uses that aren't loads or
   10132     // stores), because arm allows folding a scale into many arithmetic
   10133     // operations.  This should be made more precise and revisited later.
   10134 
   10135     // Allow r << imm, but the imm has to be a multiple of two.
   10136     if (Scale & 1) return false;
   10137     return isPowerOf2_32(Scale);
   10138   }
   10139 }
   10140 
   10141 /// isLegalAddressingMode - Return true if the addressing mode represented
   10142 /// by AM is legal for this target, for a load/store of the specified type.
   10143 bool ARMTargetLowering::isLegalAddressingMode(const AddrMode &AM,
   10144                                               Type *Ty) const {
   10145   EVT VT = getValueType(Ty, true);
   10146   if (!isLegalAddressImmediate(AM.BaseOffs, VT, Subtarget))
   10147     return false;
   10148 
   10149   // Can never fold addr of global into load/store.
   10150   if (AM.BaseGV)
   10151     return false;
   10152 
   10153   switch (AM.Scale) {
   10154   case 0:  // no scale reg, must be "r+i" or "r", or "i".
   10155     break;
   10156   case 1:
   10157     if (Subtarget->isThumb1Only())
   10158       return false;
   10159     // FALL THROUGH.
   10160   default:
   10161     // ARM doesn't support any R+R*scale+imm addr modes.
   10162     if (AM.BaseOffs)
   10163       return false;
   10164 
   10165     if (!VT.isSimple())
   10166       return false;
   10167 
   10168     if (Subtarget->isThumb2())
   10169       return isLegalT2ScaledAddressingMode(AM, VT);
   10170 
   10171     int Scale = AM.Scale;
   10172     switch (VT.getSimpleVT().SimpleTy) {
   10173     default: return false;
   10174     case MVT::i1:
   10175     case MVT::i8:
   10176     case MVT::i32:
   10177       if (Scale < 0) Scale = -Scale;
   10178       if (Scale == 1)
   10179         return true;
   10180       // r + r << imm
   10181       return isPowerOf2_32(Scale & ~1);
   10182     case MVT::i16:
   10183     case MVT::i64:
   10184       // r + r
   10185       if (((unsigned)AM.HasBaseReg + Scale) <= 2)
   10186         return true;
   10187       return false;
   10188 
   10189     case MVT::isVoid:
   10190       // Note, we allow "void" uses (basically, uses that aren't loads or
   10191       // stores), because arm allows folding a scale into many arithmetic
   10192       // operations.  This should be made more precise and revisited later.
   10193 
   10194       // Allow r << imm, but the imm has to be a multiple of two.
   10195       if (Scale & 1) return false;
   10196       return isPowerOf2_32(Scale);
   10197     }
   10198   }
   10199   return true;
   10200 }
   10201 
   10202 /// isLegalICmpImmediate - Return true if the specified immediate is legal
   10203 /// icmp immediate, that is the target has icmp instructions which can compare
   10204 /// a register against the immediate without having to materialize the
   10205 /// immediate into a register.
   10206 bool ARMTargetLowering::isLegalICmpImmediate(int64_t Imm) const {
   10207   // Thumb2 and ARM modes can use cmn for negative immediates.
   10208   if (!Subtarget->isThumb())
   10209     return ARM_AM::getSOImmVal(llvm::abs64(Imm)) != -1;
   10210   if (Subtarget->isThumb2())
   10211     return ARM_AM::getT2SOImmVal(llvm::abs64(Imm)) != -1;
   10212   // Thumb1 doesn't have cmn, and only 8-bit immediates.
   10213   return Imm >= 0 && Imm <= 255;
   10214 }
   10215 
   10216 /// isLegalAddImmediate - Return true if the specified immediate is a legal add
   10217 /// *or sub* immediate, that is the target has add or sub instructions which can
   10218 /// add a register with the immediate without having to materialize the
   10219 /// immediate into a register.
   10220 bool ARMTargetLowering::isLegalAddImmediate(int64_t Imm) const {
   10221   // Same encoding for add/sub, just flip the sign.
   10222   int64_t AbsImm = llvm::abs64(Imm);
   10223   if (!Subtarget->isThumb())
   10224     return ARM_AM::getSOImmVal(AbsImm) != -1;
   10225   if (Subtarget->isThumb2())
   10226     return ARM_AM::getT2SOImmVal(AbsImm) != -1;
   10227   // Thumb1 only has 8-bit unsigned immediate.
   10228   return AbsImm >= 0 && AbsImm <= 255;
   10229 }
   10230 
   10231 static bool getARMIndexedAddressParts(SDNode *Ptr, EVT VT,
   10232                                       bool isSEXTLoad, SDValue &Base,
   10233                                       SDValue &Offset, bool &isInc,
   10234                                       SelectionDAG &DAG) {
   10235   if (Ptr->getOpcode() != ISD::ADD && Ptr->getOpcode() != ISD::SUB)
   10236     return false;
   10237 
   10238   if (VT == MVT::i16 || ((VT == MVT::i8 || VT == MVT::i1) && isSEXTLoad)) {
   10239     // AddressingMode 3
   10240     Base = Ptr->getOperand(0);
   10241     if (ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(Ptr->getOperand(1))) {
   10242       int RHSC = (int)RHS->getZExtValue();
   10243       if (RHSC < 0 && RHSC > -256) {
   10244         assert(Ptr->getOpcode() == ISD::ADD);
   10245         isInc = false;
   10246         Offset = DAG.getConstant(-RHSC, RHS->getValueType(0));
   10247         return true;
   10248       }
   10249     }
   10250     isInc = (Ptr->getOpcode() == ISD::ADD);
   10251     Offset = Ptr->getOperand(1);
   10252     return true;
   10253   } else if (VT == MVT::i32 || VT == MVT::i8 || VT == MVT::i1) {
   10254     // AddressingMode 2
   10255     if (ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(Ptr->getOperand(1))) {
   10256       int RHSC = (int)RHS->getZExtValue();
   10257       if (RHSC < 0 && RHSC > -0x1000) {
   10258         assert(Ptr->getOpcode() == ISD::ADD);
   10259         isInc = false;
   10260         Offset = DAG.getConstant(-RHSC, RHS->getValueType(0));
   10261         Base = Ptr->getOperand(0);
   10262         return true;
   10263       }
   10264     }
   10265 
   10266     if (Ptr->getOpcode() == ISD::ADD) {
   10267       isInc = true;
   10268       ARM_AM::ShiftOpc ShOpcVal=
   10269         ARM_AM::getShiftOpcForNode(Ptr->getOperand(0).getOpcode());
   10270       if (ShOpcVal != ARM_AM::no_shift) {
   10271         Base = Ptr->getOperand(1);
   10272         Offset = Ptr->getOperand(0);
   10273       } else {
   10274         Base = Ptr->getOperand(0);
   10275         Offset = Ptr->getOperand(1);
   10276       }
   10277       return true;
   10278     }
   10279 
   10280     isInc = (Ptr->getOpcode() == ISD::ADD);
   10281     Base = Ptr->getOperand(0);
   10282     Offset = Ptr->getOperand(1);
   10283     return true;
   10284   }
   10285 
   10286   // FIXME: Use VLDM / VSTM to emulate indexed FP load / store.
   10287   return false;
   10288 }
   10289 
   10290 static bool getT2IndexedAddressParts(SDNode *Ptr, EVT VT,
   10291                                      bool isSEXTLoad, SDValue &Base,
   10292                                      SDValue &Offset, bool &isInc,
   10293                                      SelectionDAG &DAG) {
   10294   if (Ptr->getOpcode() != ISD::ADD && Ptr->getOpcode() != ISD::SUB)
   10295     return false;
   10296 
   10297   Base = Ptr->getOperand(0);
   10298   if (ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(Ptr->getOperand(1))) {
   10299     int RHSC = (int)RHS->getZExtValue();
   10300     if (RHSC < 0 && RHSC > -0x100) { // 8 bits.
   10301       assert(Ptr->getOpcode() == ISD::ADD);
   10302       isInc = false;
   10303       Offset = DAG.getConstant(-RHSC, RHS->getValueType(0));
   10304       return true;
   10305     } else if (RHSC > 0 && RHSC < 0x100) { // 8 bit, no zero.
   10306       isInc = Ptr->getOpcode() == ISD::ADD;
   10307       Offset = DAG.getConstant(RHSC, RHS->getValueType(0));
   10308       return true;
   10309     }
   10310   }
   10311 
   10312   return false;
   10313 }
   10314 
   10315 /// getPreIndexedAddressParts - returns true by value, base pointer and
   10316 /// offset pointer and addressing mode by reference if the node's address
   10317 /// can be legally represented as pre-indexed load / store address.
   10318 bool
   10319 ARMTargetLowering::getPreIndexedAddressParts(SDNode *N, SDValue &Base,
   10320                                              SDValue &Offset,
   10321                                              ISD::MemIndexedMode &AM,
   10322                                              SelectionDAG &DAG) const {
   10323   if (Subtarget->isThumb1Only())
   10324     return false;
   10325 
   10326   EVT VT;
   10327   SDValue Ptr;
   10328   bool isSEXTLoad = false;
   10329   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
   10330     Ptr = LD->getBasePtr();
   10331     VT  = LD->getMemoryVT();
   10332     isSEXTLoad = LD->getExtensionType() == ISD::SEXTLOAD;
   10333   } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
   10334     Ptr = ST->getBasePtr();
   10335     VT  = ST->getMemoryVT();
   10336   } else
   10337     return false;
   10338 
   10339   bool isInc;
   10340   bool isLegal = false;
   10341   if (Subtarget->isThumb2())
   10342     isLegal = getT2IndexedAddressParts(Ptr.getNode(), VT, isSEXTLoad, Base,
   10343                                        Offset, isInc, DAG);
   10344   else
   10345     isLegal = getARMIndexedAddressParts(Ptr.getNode(), VT, isSEXTLoad, Base,
   10346                                         Offset, isInc, DAG);
   10347   if (!isLegal)
   10348     return false;
   10349 
   10350   AM = isInc ? ISD::PRE_INC : ISD::PRE_DEC;
   10351   return true;
   10352 }
   10353 
   10354 /// getPostIndexedAddressParts - returns true by value, base pointer and
   10355 /// offset pointer and addressing mode by reference if this node can be
   10356 /// combined with a load / store to form a post-indexed load / store.
   10357 bool ARMTargetLowering::getPostIndexedAddressParts(SDNode *N, SDNode *Op,
   10358                                                    SDValue &Base,
   10359                                                    SDValue &Offset,
   10360                                                    ISD::MemIndexedMode &AM,
   10361                                                    SelectionDAG &DAG) const {
   10362   if (Subtarget->isThumb1Only())
   10363     return false;
   10364 
   10365   EVT VT;
   10366   SDValue Ptr;
   10367   bool isSEXTLoad = false;
   10368   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
   10369     VT  = LD->getMemoryVT();
   10370     Ptr = LD->getBasePtr();
   10371     isSEXTLoad = LD->getExtensionType() == ISD::SEXTLOAD;
   10372   } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
   10373     VT  = ST->getMemoryVT();
   10374     Ptr = ST->getBasePtr();
   10375   } else
   10376     return false;
   10377 
   10378   bool isInc;
   10379   bool isLegal = false;
   10380   if (Subtarget->isThumb2())
   10381     isLegal = getT2IndexedAddressParts(Op, VT, isSEXTLoad, Base, Offset,
   10382                                        isInc, DAG);
   10383   else
   10384     isLegal = getARMIndexedAddressParts(Op, VT, isSEXTLoad, Base, Offset,
   10385                                         isInc, DAG);
   10386   if (!isLegal)
   10387     return false;
   10388 
   10389   if (Ptr != Base) {
   10390     // Swap base ptr and offset to catch more post-index load / store when
   10391     // it's legal. In Thumb2 mode, offset must be an immediate.
   10392     if (Ptr == Offset && Op->getOpcode() == ISD::ADD &&
   10393         !Subtarget->isThumb2())
   10394       std::swap(Base, Offset);
   10395 
   10396     // Post-indexed load / store update the base pointer.
   10397     if (Ptr != Base)
   10398       return false;
   10399   }
   10400 
   10401   AM = isInc ? ISD::POST_INC : ISD::POST_DEC;
   10402   return true;
   10403 }
   10404 
   10405 void ARMTargetLowering::computeMaskedBitsForTargetNode(const SDValue Op,
   10406                                                        APInt &KnownZero,
   10407                                                        APInt &KnownOne,
   10408                                                        const SelectionDAG &DAG,
   10409                                                        unsigned Depth) const {
   10410   unsigned BitWidth = KnownOne.getBitWidth();
   10411   KnownZero = KnownOne = APInt(BitWidth, 0);
   10412   switch (Op.getOpcode()) {
   10413   default: break;
   10414   case ARMISD::ADDC:
   10415   case ARMISD::ADDE:
   10416   case ARMISD::SUBC:
   10417   case ARMISD::SUBE:
   10418     // These nodes' second result is a boolean
   10419     if (Op.getResNo() == 0)
   10420       break;
   10421     KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - 1);
   10422     break;
   10423   case ARMISD::CMOV: {
   10424     // Bits are known zero/one if known on the LHS and RHS.
   10425     DAG.ComputeMaskedBits(Op.getOperand(0), KnownZero, KnownOne, Depth+1);
   10426     if (KnownZero == 0 && KnownOne == 0) return;
   10427 
   10428     APInt KnownZeroRHS, KnownOneRHS;
   10429     DAG.ComputeMaskedBits(Op.getOperand(1), KnownZeroRHS, KnownOneRHS, Depth+1);
   10430     KnownZero &= KnownZeroRHS;
   10431     KnownOne  &= KnownOneRHS;
   10432     return;
   10433   }
   10434   }
   10435 }
   10436 
   10437 //===----------------------------------------------------------------------===//
   10438 //                           ARM Inline Assembly Support
   10439 //===----------------------------------------------------------------------===//
   10440 
   10441 bool ARMTargetLowering::ExpandInlineAsm(CallInst *CI) const {
   10442   // Looking for "rev" which is V6+.
   10443   if (!Subtarget->hasV6Ops())
   10444     return false;
   10445 
   10446   InlineAsm *IA = cast<InlineAsm>(CI->getCalledValue());
   10447   std::string AsmStr = IA->getAsmString();
   10448   SmallVector<StringRef, 4> AsmPieces;
   10449   SplitString(AsmStr, AsmPieces, ";\n");
   10450 
   10451   switch (AsmPieces.size()) {
   10452   default: return false;
   10453   case 1:
   10454     AsmStr = AsmPieces[0];
   10455     AsmPieces.clear();
   10456     SplitString(AsmStr, AsmPieces, " \t,");
   10457 
   10458     // rev $0, $1
   10459     if (AsmPieces.size() == 3 &&
   10460         AsmPieces[0] == "rev" && AsmPieces[1] == "$0" && AsmPieces[2] == "$1" &&
   10461         IA->getConstraintString().compare(0, 4, "=l,l") == 0) {
   10462       IntegerType *Ty = dyn_cast<IntegerType>(CI->getType());
   10463       if (Ty && Ty->getBitWidth() == 32)
   10464         return IntrinsicLowering::LowerToByteSwap(CI);
   10465     }
   10466     break;
   10467   }
   10468 
   10469   return false;
   10470 }
   10471 
   10472 /// getConstraintType - Given a constraint letter, return the type of
   10473 /// constraint it is for this target.
   10474 ARMTargetLowering::ConstraintType
   10475 ARMTargetLowering::getConstraintType(const std::string &Constraint) const {
   10476   if (Constraint.size() == 1) {
   10477     switch (Constraint[0]) {
   10478     default:  break;
   10479     case 'l': return C_RegisterClass;
   10480     case 'w': return C_RegisterClass;
   10481     case 'h': return C_RegisterClass;
   10482     case 'x': return C_RegisterClass;
   10483     case 't': return C_RegisterClass;
   10484     case 'j': return C_Other; // Constant for movw.
   10485       // An address with a single base register. Due to the way we
   10486       // currently handle addresses it is the same as an 'r' memory constraint.
   10487     case 'Q': return C_Memory;
   10488     }
   10489   } else if (Constraint.size() == 2) {
   10490     switch (Constraint[0]) {
   10491     default: break;
   10492     // All 'U+' constraints are addresses.
   10493     case 'U': return C_Memory;
   10494     }
   10495   }
   10496   return TargetLowering::getConstraintType(Constraint);
   10497 }
   10498 
   10499 /// Examine constraint type and operand type and determine a weight value.
   10500 /// This object must already have been set up with the operand type
   10501 /// and the current alternative constraint selected.
   10502 TargetLowering::ConstraintWeight
   10503 ARMTargetLowering::getSingleConstraintMatchWeight(
   10504     AsmOperandInfo &info, const char *constraint) const {
   10505   ConstraintWeight weight = CW_Invalid;
   10506   Value *CallOperandVal = info.CallOperandVal;
   10507     // If we don't have a value, we can't do a match,
   10508     // but allow it at the lowest weight.
   10509   if (CallOperandVal == NULL)
   10510     return CW_Default;
   10511   Type *type = CallOperandVal->getType();
   10512   // Look at the constraint type.
   10513   switch (*constraint) {
   10514   default:
   10515     weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint);
   10516     break;
   10517   case 'l':
   10518     if (type->isIntegerTy()) {
   10519       if (Subtarget->isThumb())
   10520         weight = CW_SpecificReg;
   10521       else
   10522         weight = CW_Register;
   10523     }
   10524     break;
   10525   case 'w':
   10526     if (type->isFloatingPointTy())
   10527       weight = CW_Register;
   10528     break;
   10529   }
   10530   return weight;
   10531 }
   10532 
   10533 typedef std::pair<unsigned, const TargetRegisterClass*> RCPair;
   10534 RCPair
   10535 ARMTargetLowering::getRegForInlineAsmConstraint(const std::string &Constraint,
   10536                                                 MVT VT) const {
   10537   if (Constraint.size() == 1) {
   10538     // GCC ARM Constraint Letters
   10539     switch (Constraint[0]) {
   10540     case 'l': // Low regs or general regs.
   10541       if (Subtarget->isThumb())
   10542         return RCPair(0U, &ARM::tGPRRegClass);
   10543       return RCPair(0U, &ARM::GPRRegClass);
   10544     case 'h': // High regs or no regs.
   10545       if (Subtarget->isThumb())
   10546         return RCPair(0U, &ARM::hGPRRegClass);
   10547       break;
   10548     case 'r':
   10549       return RCPair(0U, &ARM::GPRRegClass);
   10550     case 'w':
   10551       if (VT == MVT::f32)
   10552         return RCPair(0U, &ARM::SPRRegClass);
   10553       if (VT.getSizeInBits() == 64)
   10554         return RCPair(0U, &ARM::DPRRegClass);
   10555       if (VT.getSizeInBits() == 128)
   10556         return RCPair(0U, &ARM::QPRRegClass);
   10557       break;
   10558     case 'x':
   10559       if (VT == MVT::f32)
   10560         return RCPair(0U, &ARM::SPR_8RegClass);
   10561       if (VT.getSizeInBits() == 64)
   10562         return RCPair(0U, &ARM::DPR_8RegClass);
   10563       if (VT.getSizeInBits() == 128)
   10564         return RCPair(0U, &ARM::QPR_8RegClass);
   10565       break;
   10566     case 't':
   10567       if (VT == MVT::f32)
   10568         return RCPair(0U, &ARM::SPRRegClass);
   10569       break;
   10570     }
   10571   }
   10572   if (StringRef("{cc}").equals_lower(Constraint))
   10573     return std::make_pair(unsigned(ARM::CPSR), &ARM::CCRRegClass);
   10574 
   10575   return TargetLowering::getRegForInlineAsmConstraint(Constraint, VT);
   10576 }
   10577 
   10578 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
   10579 /// vector.  If it is invalid, don't add anything to Ops.
   10580 void ARMTargetLowering::LowerAsmOperandForConstraint(SDValue Op,
   10581                                                      std::string &Constraint,
   10582                                                      std::vector<SDValue>&Ops,
   10583                                                      SelectionDAG &DAG) const {
   10584   SDValue Result(0, 0);
   10585 
   10586   // Currently only support length 1 constraints.
   10587   if (Constraint.length() != 1) return;
   10588 
   10589   char ConstraintLetter = Constraint[0];
   10590   switch (ConstraintLetter) {
   10591   default: break;
   10592   case 'j':
   10593   case 'I': case 'J': case 'K': case 'L':
   10594   case 'M': case 'N': case 'O':
   10595     ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op);
   10596     if (!C)
   10597       return;
   10598 
   10599     int64_t CVal64 = C->getSExtValue();
   10600     int CVal = (int) CVal64;
   10601     // None of these constraints allow values larger than 32 bits.  Check
   10602     // that the value fits in an int.
   10603     if (CVal != CVal64)
   10604       return;
   10605 
   10606     switch (ConstraintLetter) {
   10607       case 'j':
   10608         // Constant suitable for movw, must be between 0 and
   10609         // 65535.
   10610         if (Subtarget->hasV6T2Ops())
   10611           if (CVal >= 0 && CVal <= 65535)
   10612             break;
   10613         return;
   10614       case 'I':
   10615         if (Subtarget->isThumb1Only()) {
   10616           // This must be a constant between 0 and 255, for ADD
   10617           // immediates.
   10618           if (CVal >= 0 && CVal <= 255)
   10619             break;
   10620         } else if (Subtarget->isThumb2()) {
   10621           // A constant that can be used as an immediate value in a
   10622           // data-processing instruction.
   10623           if (ARM_AM::getT2SOImmVal(CVal) != -1)
   10624             break;
   10625         } else {
   10626           // A constant that can be used as an immediate value in a
   10627           // data-processing instruction.
   10628           if (ARM_AM::getSOImmVal(CVal) != -1)
   10629             break;
   10630         }
   10631         return;
   10632 
   10633       case 'J':
   10634         if (Subtarget->isThumb()) {  // FIXME thumb2
   10635           // This must be a constant between -255 and -1, for negated ADD
   10636           // immediates. This can be used in GCC with an "n" modifier that
   10637           // prints the negated value, for use with SUB instructions. It is
   10638           // not useful otherwise but is implemented for compatibility.
   10639           if (CVal >= -255 && CVal <= -1)
   10640             break;
   10641         } else {
   10642           // This must be a constant between -4095 and 4095. It is not clear
   10643           // what this constraint is intended for. Implemented for
   10644           // compatibility with GCC.
   10645           if (CVal >= -4095 && CVal <= 4095)
   10646             break;
   10647         }
   10648         return;
   10649 
   10650       case 'K':
   10651         if (Subtarget->isThumb1Only()) {
   10652           // A 32-bit value where only one byte has a nonzero value. Exclude
   10653           // zero to match GCC. This constraint is used by GCC internally for
   10654           // constants that can be loaded with a move/shift combination.
   10655           // It is not useful otherwise but is implemented for compatibility.
   10656           if (CVal != 0 && ARM_AM::isThumbImmShiftedVal(CVal))
   10657             break;
   10658         } else if (Subtarget->isThumb2()) {
   10659           // A constant whose bitwise inverse can be used as an immediate
   10660           // value in a data-processing instruction. This can be used in GCC
   10661           // with a "B" modifier that prints the inverted value, for use with
   10662           // BIC and MVN instructions. It is not useful otherwise but is
   10663           // implemented for compatibility.
   10664           if (ARM_AM::getT2SOImmVal(~CVal) != -1)
   10665             break;
   10666         } else {
   10667           // A constant whose bitwise inverse can be used as an immediate
   10668           // value in a data-processing instruction. This can be used in GCC
   10669           // with a "B" modifier that prints the inverted value, for use with
   10670           // BIC and MVN instructions. It is not useful otherwise but is
   10671           // implemented for compatibility.
   10672           if (ARM_AM::getSOImmVal(~CVal) != -1)
   10673             break;
   10674         }
   10675         return;
   10676 
   10677       case 'L':
   10678         if (Subtarget->isThumb1Only()) {
   10679           // This must be a constant between -7 and 7,
   10680           // for 3-operand ADD/SUB immediate instructions.
   10681           if (CVal >= -7 && CVal < 7)
   10682             break;
   10683         } else if (Subtarget->isThumb2()) {
   10684           // A constant whose negation can be used as an immediate value in a
   10685           // data-processing instruction. This can be used in GCC with an "n"
   10686           // modifier that prints the negated value, for use with SUB
   10687           // instructions. It is not useful otherwise but is implemented for
   10688           // compatibility.
   10689           if (ARM_AM::getT2SOImmVal(-CVal) != -1)
   10690             break;
   10691         } else {
   10692           // A constant whose negation can be used as an immediate value in a
   10693           // data-processing instruction. This can be used in GCC with an "n"
   10694           // modifier that prints the negated value, for use with SUB
   10695           // instructions. It is not useful otherwise but is implemented for
   10696           // compatibility.
   10697           if (ARM_AM::getSOImmVal(-CVal) != -1)
   10698             break;
   10699         }
   10700         return;
   10701 
   10702       case 'M':
   10703         if (Subtarget->isThumb()) { // FIXME thumb2
   10704           // This must be a multiple of 4 between 0 and 1020, for
   10705           // ADD sp + immediate.
   10706           if ((CVal >= 0 && CVal <= 1020) && ((CVal & 3) == 0))
   10707             break;
   10708         } else {
   10709           // A power of two or a constant between 0 and 32.  This is used in
   10710           // GCC for the shift amount on shifted register operands, but it is
   10711           // useful in general for any shift amounts.
   10712           if ((CVal >= 0 && CVal <= 32) || ((CVal & (CVal - 1)) == 0))
   10713             break;
   10714         }
   10715         return;
   10716 
   10717       case 'N':
   10718         if (Subtarget->isThumb()) {  // FIXME thumb2
   10719           // This must be a constant between 0 and 31, for shift amounts.
   10720           if (CVal >= 0 && CVal <= 31)
   10721             break;
   10722         }
   10723         return;
   10724 
   10725       case 'O':
   10726         if (Subtarget->isThumb()) {  // FIXME thumb2
   10727           // This must be a multiple of 4 between -508 and 508, for
   10728           // ADD/SUB sp = sp + immediate.
   10729           if ((CVal >= -508 && CVal <= 508) && ((CVal & 3) == 0))
   10730             break;
   10731         }
   10732         return;
   10733     }
   10734     Result = DAG.getTargetConstant(CVal, Op.getValueType());
   10735     break;
   10736   }
   10737 
   10738   if (Result.getNode()) {
   10739     Ops.push_back(Result);
   10740     return;
   10741   }
   10742   return TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
   10743 }
   10744 
   10745 SDValue ARMTargetLowering::LowerDivRem(SDValue Op, SelectionDAG &DAG) const {
   10746   assert(Subtarget->isTargetAEABI() && "Register-based DivRem lowering only");
   10747   unsigned Opcode = Op->getOpcode();
   10748   assert((Opcode == ISD::SDIVREM || Opcode == ISD::UDIVREM) &&
   10749       "Invalid opcode for Div/Rem lowering");
   10750   bool isSigned = (Opcode == ISD::SDIVREM);
   10751   EVT VT = Op->getValueType(0);
   10752   Type *Ty = VT.getTypeForEVT(*DAG.getContext());
   10753 
   10754   RTLIB::Libcall LC;
   10755   switch (VT.getSimpleVT().SimpleTy) {
   10756   default: llvm_unreachable("Unexpected request for libcall!");
   10757   case MVT::i8:   LC= isSigned ? RTLIB::SDIVREM_I8  : RTLIB::UDIVREM_I8;  break;
   10758   case MVT::i16:  LC= isSigned ? RTLIB::SDIVREM_I16 : RTLIB::UDIVREM_I16; break;
   10759   case MVT::i32:  LC= isSigned ? RTLIB::SDIVREM_I32 : RTLIB::UDIVREM_I32; break;
   10760   case MVT::i64:  LC= isSigned ? RTLIB::SDIVREM_I64 : RTLIB::UDIVREM_I64; break;
   10761   }
   10762 
   10763   SDValue InChain = DAG.getEntryNode();
   10764 
   10765   TargetLowering::ArgListTy Args;
   10766   TargetLowering::ArgListEntry Entry;
   10767   for (unsigned i = 0, e = Op->getNumOperands(); i != e; ++i) {
   10768     EVT ArgVT = Op->getOperand(i).getValueType();
   10769     Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
   10770     Entry.Node = Op->getOperand(i);
   10771     Entry.Ty = ArgTy;
   10772     Entry.isSExt = isSigned;
   10773     Entry.isZExt = !isSigned;
   10774     Args.push_back(Entry);
   10775   }
   10776 
   10777   SDValue Callee = DAG.getExternalSymbol(getLibcallName(LC),
   10778                                          getPointerTy());
   10779 
   10780   Type *RetTy = (Type*)StructType::get(Ty, Ty, NULL);
   10781 
   10782   SDLoc dl(Op);
   10783   TargetLowering::
   10784   CallLoweringInfo CLI(InChain, RetTy, isSigned, !isSigned, false, true,
   10785                     0, getLibcallCallingConv(LC), /*isTailCall=*/false,
   10786                     /*doesNotReturn=*/false, /*isReturnValueUsed=*/true,
   10787                     Callee, Args, DAG, dl);
   10788   std::pair<SDValue, SDValue> CallInfo = LowerCallTo(CLI);
   10789 
   10790   return CallInfo.first;
   10791 }
   10792 
   10793 bool
   10794 ARMTargetLowering::isOffsetFoldingLegal(const GlobalAddressSDNode *GA) const {
   10795   // The ARM target isn't yet aware of offsets.
   10796   return false;
   10797 }
   10798 
   10799 bool ARM::isBitFieldInvertedMask(unsigned v) {
   10800   if (v == 0xffffffff)
   10801     return false;
   10802 
   10803   // there can be 1's on either or both "outsides", all the "inside"
   10804   // bits must be 0's
   10805   unsigned TO = CountTrailingOnes_32(v);
   10806   unsigned LO = CountLeadingOnes_32(v);
   10807   v = (v >> TO) << TO;
   10808   v = (v << LO) >> LO;
   10809   return v == 0;
   10810 }
   10811 
   10812 /// isFPImmLegal - Returns true if the target can instruction select the
   10813 /// specified FP immediate natively. If false, the legalizer will
   10814 /// materialize the FP immediate as a load from a constant pool.
   10815 bool ARMTargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT) const {
   10816   if (!Subtarget->hasVFP3())
   10817     return false;
   10818   if (VT == MVT::f32)
   10819     return ARM_AM::getFP32Imm(Imm) != -1;
   10820   if (VT == MVT::f64)
   10821     return ARM_AM::getFP64Imm(Imm) != -1;
   10822   return false;
   10823 }
   10824 
   10825 /// getTgtMemIntrinsic - Represent NEON load and store intrinsics as
   10826 /// MemIntrinsicNodes.  The associated MachineMemOperands record the alignment
   10827 /// specified in the intrinsic calls.
   10828 bool ARMTargetLowering::getTgtMemIntrinsic(IntrinsicInfo &Info,
   10829                                            const CallInst &I,
   10830                                            unsigned Intrinsic) const {
   10831   switch (Intrinsic) {
   10832   case Intrinsic::arm_neon_vld1:
   10833   case Intrinsic::arm_neon_vld2:
   10834   case Intrinsic::arm_neon_vld3:
   10835   case Intrinsic::arm_neon_vld4:
   10836   case Intrinsic::arm_neon_vld2lane:
   10837   case Intrinsic::arm_neon_vld3lane:
   10838   case Intrinsic::arm_neon_vld4lane: {
   10839     Info.opc = ISD::INTRINSIC_W_CHAIN;
   10840     // Conservatively set memVT to the entire set of vectors loaded.
   10841     uint64_t NumElts = getDataLayout()->getTypeAllocSize(I.getType()) / 8;
   10842     Info.memVT = EVT::getVectorVT(I.getType()->getContext(), MVT::i64, NumElts);
   10843     Info.ptrVal = I.getArgOperand(0);
   10844     Info.offset = 0;
   10845     Value *AlignArg = I.getArgOperand(I.getNumArgOperands() - 1);
   10846     Info.align = cast<ConstantInt>(AlignArg)->getZExtValue();
   10847     Info.vol = false; // volatile loads with NEON intrinsics not supported
   10848     Info.readMem = true;
   10849     Info.writeMem = false;
   10850     return true;
   10851   }
   10852   case Intrinsic::arm_neon_vst1:
   10853   case Intrinsic::arm_neon_vst2:
   10854   case Intrinsic::arm_neon_vst3:
   10855   case Intrinsic::arm_neon_vst4:
   10856   case Intrinsic::arm_neon_vst2lane:
   10857   case Intrinsic::arm_neon_vst3lane:
   10858   case Intrinsic::arm_neon_vst4lane: {
   10859     Info.opc = ISD::INTRINSIC_VOID;
   10860     // Conservatively set memVT to the entire set of vectors stored.
   10861     unsigned NumElts = 0;
   10862     for (unsigned ArgI = 1, ArgE = I.getNumArgOperands(); ArgI < ArgE; ++ArgI) {
   10863       Type *ArgTy = I.getArgOperand(ArgI)->getType();
   10864       if (!ArgTy->isVectorTy())
   10865         break;
   10866       NumElts += getDataLayout()->getTypeAllocSize(ArgTy) / 8;
   10867     }
   10868     Info.memVT = EVT::getVectorVT(I.getType()->getContext(), MVT::i64, NumElts);
   10869     Info.ptrVal = I.getArgOperand(0);
   10870     Info.offset = 0;
   10871     Value *AlignArg = I.getArgOperand(I.getNumArgOperands() - 1);
   10872     Info.align = cast<ConstantInt>(AlignArg)->getZExtValue();
   10873     Info.vol = false; // volatile stores with NEON intrinsics not supported
   10874     Info.readMem = false;
   10875     Info.writeMem = true;
   10876     return true;
   10877   }
   10878   case Intrinsic::arm_ldrex: {
   10879     PointerType *PtrTy = cast<PointerType>(I.getArgOperand(0)->getType());
   10880     Info.opc = ISD::INTRINSIC_W_CHAIN;
   10881     Info.memVT = MVT::getVT(PtrTy->getElementType());
   10882     Info.ptrVal = I.getArgOperand(0);
   10883     Info.offset = 0;
   10884     Info.align = getDataLayout()->getABITypeAlignment(PtrTy->getElementType());
   10885     Info.vol = true;
   10886     Info.readMem = true;
   10887     Info.writeMem = false;
   10888     return true;
   10889   }
   10890   case Intrinsic::arm_strex: {
   10891     PointerType *PtrTy = cast<PointerType>(I.getArgOperand(1)->getType());
   10892     Info.opc = ISD::INTRINSIC_W_CHAIN;
   10893     Info.memVT = MVT::getVT(PtrTy->getElementType());
   10894     Info.ptrVal = I.getArgOperand(1);
   10895     Info.offset = 0;
   10896     Info.align = getDataLayout()->getABITypeAlignment(PtrTy->getElementType());
   10897     Info.vol = true;
   10898     Info.readMem = false;
   10899     Info.writeMem = true;
   10900     return true;
   10901   }
   10902   case Intrinsic::arm_strexd: {
   10903     Info.opc = ISD::INTRINSIC_W_CHAIN;
   10904     Info.memVT = MVT::i64;
   10905     Info.ptrVal = I.getArgOperand(2);
   10906     Info.offset = 0;
   10907     Info.align = 8;
   10908     Info.vol = true;
   10909     Info.readMem = false;
   10910     Info.writeMem = true;
   10911     return true;
   10912   }
   10913   case Intrinsic::arm_ldrexd: {
   10914     Info.opc = ISD::INTRINSIC_W_CHAIN;
   10915     Info.memVT = MVT::i64;
   10916     Info.ptrVal = I.getArgOperand(0);
   10917     Info.offset = 0;
   10918     Info.align = 8;
   10919     Info.vol = true;
   10920     Info.readMem = true;
   10921     Info.writeMem = false;
   10922     return true;
   10923   }
   10924   default:
   10925     break;
   10926   }
   10927 
   10928   return false;
   10929 }
   10930