LCOV - code coverage report
Current view: top level - lib/Target/ARM - ARMISelLowering.cpp (source / functions) Hit Total Coverage
Test: llvm-toolchain.info Lines: 5811 6307 92.1 %
Date: 2018-07-13 00:08:38 Functions: 296 297 99.7 %
Legend: Lines: hit not hit

          Line data    Source code
       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             : #include "ARMISelLowering.h"
      16             : #include "ARMBaseInstrInfo.h"
      17             : #include "ARMBaseRegisterInfo.h"
      18             : #include "ARMCallingConv.h"
      19             : #include "ARMConstantPoolValue.h"
      20             : #include "ARMMachineFunctionInfo.h"
      21             : #include "ARMPerfectShuffle.h"
      22             : #include "ARMRegisterInfo.h"
      23             : #include "ARMSelectionDAGInfo.h"
      24             : #include "ARMSubtarget.h"
      25             : #include "MCTargetDesc/ARMAddressingModes.h"
      26             : #include "MCTargetDesc/ARMBaseInfo.h"
      27             : #include "Utils/ARMBaseInfo.h"
      28             : #include "llvm/ADT/APFloat.h"
      29             : #include "llvm/ADT/APInt.h"
      30             : #include "llvm/ADT/ArrayRef.h"
      31             : #include "llvm/ADT/BitVector.h"
      32             : #include "llvm/ADT/DenseMap.h"
      33             : #include "llvm/ADT/STLExtras.h"
      34             : #include "llvm/ADT/SmallPtrSet.h"
      35             : #include "llvm/ADT/SmallVector.h"
      36             : #include "llvm/ADT/Statistic.h"
      37             : #include "llvm/ADT/StringExtras.h"
      38             : #include "llvm/ADT/StringRef.h"
      39             : #include "llvm/ADT/StringSwitch.h"
      40             : #include "llvm/ADT/Triple.h"
      41             : #include "llvm/ADT/Twine.h"
      42             : #include "llvm/Analysis/VectorUtils.h"
      43             : #include "llvm/CodeGen/CallingConvLower.h"
      44             : #include "llvm/CodeGen/ISDOpcodes.h"
      45             : #include "llvm/CodeGen/IntrinsicLowering.h"
      46             : #include "llvm/CodeGen/MachineBasicBlock.h"
      47             : #include "llvm/CodeGen/MachineConstantPool.h"
      48             : #include "llvm/CodeGen/MachineFrameInfo.h"
      49             : #include "llvm/CodeGen/MachineFunction.h"
      50             : #include "llvm/CodeGen/MachineInstr.h"
      51             : #include "llvm/CodeGen/MachineInstrBuilder.h"
      52             : #include "llvm/CodeGen/MachineJumpTableInfo.h"
      53             : #include "llvm/CodeGen/MachineMemOperand.h"
      54             : #include "llvm/CodeGen/MachineOperand.h"
      55             : #include "llvm/CodeGen/MachineRegisterInfo.h"
      56             : #include "llvm/CodeGen/RuntimeLibcalls.h"
      57             : #include "llvm/CodeGen/SelectionDAG.h"
      58             : #include "llvm/CodeGen/SelectionDAGNodes.h"
      59             : #include "llvm/CodeGen/TargetInstrInfo.h"
      60             : #include "llvm/CodeGen/TargetLowering.h"
      61             : #include "llvm/CodeGen/TargetOpcodes.h"
      62             : #include "llvm/CodeGen/TargetRegisterInfo.h"
      63             : #include "llvm/CodeGen/TargetSubtargetInfo.h"
      64             : #include "llvm/CodeGen/ValueTypes.h"
      65             : #include "llvm/IR/Attributes.h"
      66             : #include "llvm/IR/CallingConv.h"
      67             : #include "llvm/IR/Constant.h"
      68             : #include "llvm/IR/Constants.h"
      69             : #include "llvm/IR/DataLayout.h"
      70             : #include "llvm/IR/DebugLoc.h"
      71             : #include "llvm/IR/DerivedTypes.h"
      72             : #include "llvm/IR/Function.h"
      73             : #include "llvm/IR/GlobalAlias.h"
      74             : #include "llvm/IR/GlobalValue.h"
      75             : #include "llvm/IR/GlobalVariable.h"
      76             : #include "llvm/IR/IRBuilder.h"
      77             : #include "llvm/IR/InlineAsm.h"
      78             : #include "llvm/IR/Instruction.h"
      79             : #include "llvm/IR/Instructions.h"
      80             : #include "llvm/IR/IntrinsicInst.h"
      81             : #include "llvm/IR/Intrinsics.h"
      82             : #include "llvm/IR/Module.h"
      83             : #include "llvm/IR/Type.h"
      84             : #include "llvm/IR/User.h"
      85             : #include "llvm/IR/Value.h"
      86             : #include "llvm/MC/MCInstrDesc.h"
      87             : #include "llvm/MC/MCInstrItineraries.h"
      88             : #include "llvm/MC/MCRegisterInfo.h"
      89             : #include "llvm/MC/MCSchedule.h"
      90             : #include "llvm/Support/AtomicOrdering.h"
      91             : #include "llvm/Support/BranchProbability.h"
      92             : #include "llvm/Support/Casting.h"
      93             : #include "llvm/Support/CodeGen.h"
      94             : #include "llvm/Support/CommandLine.h"
      95             : #include "llvm/Support/Compiler.h"
      96             : #include "llvm/Support/Debug.h"
      97             : #include "llvm/Support/ErrorHandling.h"
      98             : #include "llvm/Support/KnownBits.h"
      99             : #include "llvm/Support/MachineValueType.h"
     100             : #include "llvm/Support/MathExtras.h"
     101             : #include "llvm/Support/raw_ostream.h"
     102             : #include "llvm/Target/TargetMachine.h"
     103             : #include "llvm/Target/TargetOptions.h"
     104             : #include <algorithm>
     105             : #include <cassert>
     106             : #include <cstdint>
     107             : #include <cstdlib>
     108             : #include <iterator>
     109             : #include <limits>
     110             : #include <string>
     111             : #include <tuple>
     112             : #include <utility>
     113             : #include <vector>
     114             : 
     115             : using namespace llvm;
     116             : 
     117             : #define DEBUG_TYPE "arm-isel"
     118             : 
     119             : STATISTIC(NumTailCalls, "Number of tail calls");
     120             : STATISTIC(NumMovwMovt, "Number of GAs materialized with movw + movt");
     121             : STATISTIC(NumLoopByVals, "Number of loops generated for byval arguments");
     122             : STATISTIC(NumConstpoolPromoted,
     123             :   "Number of constants with their storage promoted into constant pools");
     124             : 
     125             : static cl::opt<bool>
     126       99743 : ARMInterworking("arm-interworking", cl::Hidden,
     127       99743 :   cl::desc("Enable / disable ARM interworking (for debugging only)"),
     128      299229 :   cl::init(true));
     129             : 
     130       99743 : static cl::opt<bool> EnableConstpoolPromotion(
     131             :     "arm-promote-constant", cl::Hidden,
     132       99743 :     cl::desc("Enable / disable promotion of unnamed_addr constants into "
     133             :              "constant pools"),
     134      299229 :     cl::init(false)); // FIXME: set to true by default once PR32780 is fixed
     135       99743 : static cl::opt<unsigned> ConstpoolPromotionMaxSize(
     136             :     "arm-promote-constant-max-size", cl::Hidden,
     137       99743 :     cl::desc("Maximum size of constant to promote into a constant pool"),
     138      299229 :     cl::init(64));
     139       99743 : static cl::opt<unsigned> ConstpoolPromotionMaxTotal(
     140             :     "arm-promote-constant-max-total", cl::Hidden,
     141       99743 :     cl::desc("Maximum size of ALL constants to promote into a constant pool"),
     142      299229 :     cl::init(128));
     143             : 
     144             : // The APCS parameter registers.
     145             : static const MCPhysReg GPRArgRegs[] = {
     146             :   ARM::R0, ARM::R1, ARM::R2, ARM::R3
     147             : };
     148             : 
     149       27743 : void ARMTargetLowering::addTypeForNEON(MVT VT, MVT PromotedLdStVT,
     150             :                                        MVT PromotedBitwiseVT) {
     151       27743 :   if (VT != PromotedLdStVT) {
     152             :     setOperationAction(ISD::LOAD, VT, Promote);
     153             :     AddPromotedToType (ISD::LOAD, VT, PromotedLdStVT);
     154             : 
     155             :     setOperationAction(ISD::STORE, VT, Promote);
     156             :     AddPromotedToType (ISD::STORE, VT, PromotedLdStVT);
     157             :   }
     158             : 
     159       27743 :   MVT ElemTy = VT.getVectorElementType();
     160       27743 :   if (ElemTy != MVT::f64)
     161             :     setOperationAction(ISD::SETCC, VT, Custom);
     162             :   setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Custom);
     163             :   setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
     164       27743 :   if (ElemTy == MVT::i32) {
     165             :     setOperationAction(ISD::SINT_TO_FP, VT, Custom);
     166             :     setOperationAction(ISD::UINT_TO_FP, VT, Custom);
     167             :     setOperationAction(ISD::FP_TO_SINT, VT, Custom);
     168             :     setOperationAction(ISD::FP_TO_UINT, VT, Custom);
     169             :   } else {
     170             :     setOperationAction(ISD::SINT_TO_FP, VT, Expand);
     171             :     setOperationAction(ISD::UINT_TO_FP, VT, Expand);
     172             :     setOperationAction(ISD::FP_TO_SINT, VT, Expand);
     173             :     setOperationAction(ISD::FP_TO_UINT, VT, Expand);
     174             :   }
     175             :   setOperationAction(ISD::BUILD_VECTOR,      VT, Custom);
     176             :   setOperationAction(ISD::VECTOR_SHUFFLE,    VT, Custom);
     177             :   setOperationAction(ISD::CONCAT_VECTORS,    VT, Legal);
     178             :   setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Legal);
     179             :   setOperationAction(ISD::SELECT,            VT, Expand);
     180             :   setOperationAction(ISD::SELECT_CC,         VT, Expand);
     181             :   setOperationAction(ISD::VSELECT,           VT, Expand);
     182             :   setOperationAction(ISD::SIGN_EXTEND_INREG, VT, Expand);
     183       27743 :   if (VT.isInteger()) {
     184             :     setOperationAction(ISD::SHL, VT, Custom);
     185             :     setOperationAction(ISD::SRA, VT, Custom);
     186             :     setOperationAction(ISD::SRL, VT, Custom);
     187             :   }
     188             : 
     189             :   // Promote all bit-wise operations.
     190       47879 :   if (VT.isInteger() && VT != PromotedBitwiseVT) {
     191             :     setOperationAction(ISD::AND, VT, Promote);
     192             :     AddPromotedToType (ISD::AND, VT, PromotedBitwiseVT);
     193             :     setOperationAction(ISD::OR,  VT, Promote);
     194             :     AddPromotedToType (ISD::OR,  VT, PromotedBitwiseVT);
     195             :     setOperationAction(ISD::XOR, VT, Promote);
     196             :     AddPromotedToType (ISD::XOR, VT, PromotedBitwiseVT);
     197             :   }
     198             : 
     199             :   // Neon does not support vector divide/remainder operations.
     200             :   setOperationAction(ISD::SDIV, VT, Expand);
     201             :   setOperationAction(ISD::UDIV, VT, Expand);
     202             :   setOperationAction(ISD::FDIV, VT, Expand);
     203             :   setOperationAction(ISD::SREM, VT, Expand);
     204             :   setOperationAction(ISD::UREM, VT, Expand);
     205             :   setOperationAction(ISD::FREM, VT, Expand);
     206             : 
     207       20136 :   if (!VT.isFloatingPoint() &&
     208       45362 :       VT != MVT::v2i64 && VT != MVT::v1i64)
     209      166122 :     for (auto Opcode : {ISD::ABS, ISD::SMIN, ISD::SMAX, ISD::UMIN, ISD::UMAX})
     210             :       setOperationAction(Opcode, VT, Legal);
     211       27743 : }
     212             : 
     213       12613 : void ARMTargetLowering::addDRTypeForNEON(MVT VT) {
     214             :   addRegisterClass(VT, &ARM::DPRRegClass);
     215       12613 :   addTypeForNEON(VT, MVT::f64, MVT::v2i32);
     216       12613 : }
     217             : 
     218       15130 : void ARMTargetLowering::addQRTypeForNEON(MVT VT) {
     219             :   addRegisterClass(VT, &ARM::DPairRegClass);
     220       15130 :   addTypeForNEON(VT, MVT::v2f64, MVT::v4i32);
     221       15130 : }
     222             : 
     223        4835 : ARMTargetLowering::ARMTargetLowering(const TargetMachine &TM,
     224        4835 :                                      const ARMSubtarget &STI)
     225        4835 :     : TargetLowering(TM), Subtarget(&STI) {
     226        4835 :   RegInfo = Subtarget->getRegisterInfo();
     227        4835 :   Itins = Subtarget->getInstrItineraryData();
     228             : 
     229             :   setBooleanContents(ZeroOrOneBooleanContent);
     230             :   setBooleanVectorContents(ZeroOrNegativeOneBooleanContent);
     231             : 
     232        4835 :   if (!Subtarget->isTargetDarwin() && !Subtarget->isTargetIOS() &&
     233             :       !Subtarget->isTargetWatchOS()) {
     234        4059 :     bool IsHFTarget = TM.Options.FloatABIType == FloatABI::Hard;
     235     3754575 :     for (int LCID = 0; LCID < RTLIB::UNKNOWN_LIBCALL; ++LCID)
     236     1875258 :       setLibcallCallingConv(static_cast<RTLIB::Libcall>(LCID),
     237             :                             IsHFTarget ? CallingConv::ARM_AAPCS_VFP
     238             :                                        : CallingConv::ARM_AAPCS);
     239             :   }
     240             : 
     241        9670 :   if (Subtarget->isTargetMachO()) {
     242             :     // Uses VFP for Thumb libfuncs if available.
     243        1645 :     if (Subtarget->isThumb() && Subtarget->hasVFP2() &&
     244        1532 :         Subtarget->hasARMOps() && !Subtarget->useSoftFloat()) {
     245             :       static const struct {
     246             :         const RTLIB::Libcall Op;
     247             :         const char * const Name;
     248             :         const ISD::CondCode Cond;
     249             :       } LibraryCalls[] = {
     250             :         // Single-precision floating-point arithmetic.
     251             :         { RTLIB::ADD_F32, "__addsf3vfp", ISD::SETCC_INVALID },
     252             :         { RTLIB::SUB_F32, "__subsf3vfp", ISD::SETCC_INVALID },
     253             :         { RTLIB::MUL_F32, "__mulsf3vfp", ISD::SETCC_INVALID },
     254             :         { RTLIB::DIV_F32, "__divsf3vfp", ISD::SETCC_INVALID },
     255             : 
     256             :         // Double-precision floating-point arithmetic.
     257             :         { RTLIB::ADD_F64, "__adddf3vfp", ISD::SETCC_INVALID },
     258             :         { RTLIB::SUB_F64, "__subdf3vfp", ISD::SETCC_INVALID },
     259             :         { RTLIB::MUL_F64, "__muldf3vfp", ISD::SETCC_INVALID },
     260             :         { RTLIB::DIV_F64, "__divdf3vfp", ISD::SETCC_INVALID },
     261             : 
     262             :         // Single-precision comparisons.
     263             :         { RTLIB::OEQ_F32, "__eqsf2vfp",    ISD::SETNE },
     264             :         { RTLIB::UNE_F32, "__nesf2vfp",    ISD::SETNE },
     265             :         { RTLIB::OLT_F32, "__ltsf2vfp",    ISD::SETNE },
     266             :         { RTLIB::OLE_F32, "__lesf2vfp",    ISD::SETNE },
     267             :         { RTLIB::OGE_F32, "__gesf2vfp",    ISD::SETNE },
     268             :         { RTLIB::OGT_F32, "__gtsf2vfp",    ISD::SETNE },
     269             :         { RTLIB::UO_F32,  "__unordsf2vfp", ISD::SETNE },
     270             :         { RTLIB::O_F32,   "__unordsf2vfp", ISD::SETEQ },
     271             : 
     272             :         // Double-precision comparisons.
     273             :         { RTLIB::OEQ_F64, "__eqdf2vfp",    ISD::SETNE },
     274             :         { RTLIB::UNE_F64, "__nedf2vfp",    ISD::SETNE },
     275             :         { RTLIB::OLT_F64, "__ltdf2vfp",    ISD::SETNE },
     276             :         { RTLIB::OLE_F64, "__ledf2vfp",    ISD::SETNE },
     277             :         { RTLIB::OGE_F64, "__gedf2vfp",    ISD::SETNE },
     278             :         { RTLIB::OGT_F64, "__gtdf2vfp",    ISD::SETNE },
     279             :         { RTLIB::UO_F64,  "__unorddf2vfp", ISD::SETNE },
     280             :         { RTLIB::O_F64,   "__unorddf2vfp", ISD::SETEQ },
     281             : 
     282             :         // Floating-point to integer conversions.
     283             :         // i64 conversions are done via library routines even when generating VFP
     284             :         // instructions, so use the same ones.
     285             :         { RTLIB::FPTOSINT_F64_I32, "__fixdfsivfp",    ISD::SETCC_INVALID },
     286             :         { RTLIB::FPTOUINT_F64_I32, "__fixunsdfsivfp", ISD::SETCC_INVALID },
     287             :         { RTLIB::FPTOSINT_F32_I32, "__fixsfsivfp",    ISD::SETCC_INVALID },
     288             :         { RTLIB::FPTOUINT_F32_I32, "__fixunssfsivfp", ISD::SETCC_INVALID },
     289             : 
     290             :         // Conversions between floating types.
     291             :         { RTLIB::FPROUND_F64_F32, "__truncdfsf2vfp",  ISD::SETCC_INVALID },
     292             :         { RTLIB::FPEXT_F32_F64,   "__extendsfdf2vfp", ISD::SETCC_INVALID },
     293             : 
     294             :         // Integer to floating-point conversions.
     295             :         // i64 conversions are done via library routines even when generating VFP
     296             :         // instructions, so use the same ones.
     297             :         // FIXME: There appears to be some naming inconsistency in ARM libgcc:
     298             :         // e.g., __floatunsidf vs. __floatunssidfvfp.
     299             :         { RTLIB::SINTTOFP_I32_F64, "__floatsidfvfp",    ISD::SETCC_INVALID },
     300             :         { RTLIB::UINTTOFP_I32_F64, "__floatunssidfvfp", ISD::SETCC_INVALID },
     301             :         { RTLIB::SINTTOFP_I32_F32, "__floatsisfvfp",    ISD::SETCC_INVALID },
     302             :         { RTLIB::UINTTOFP_I32_F32, "__floatunssisfvfp", ISD::SETCC_INVALID },
     303             :       };
     304             : 
     305       24426 :       for (const auto &LC : LibraryCalls) {
     306       12036 :         setLibcallName(LC.Op, LC.Name);
     307       12036 :         if (LC.Cond != ISD::SETCC_INVALID)
     308        5664 :           setCmpLibcallCC(LC.Op, LC.Cond);
     309             :       }
     310             :     }
     311             : 
     312             :     // Set the correct calling convention for ARMv7k WatchOS. It's just
     313             :     // AAPCS_VFP for functions as simple as libcalls.
     314        1632 :     if (Subtarget->isTargetWatchABI()) {
     315       23125 :       for (int i = 0; i < RTLIB::UNKNOWN_LIBCALL; ++i)
     316             :         setLibcallCallingConv((RTLIB::Libcall)i, CallingConv::ARM_AAPCS_VFP);
     317             :     }
     318             :   }
     319             : 
     320             :   // These libcalls are not available in 32-bit.
     321             :   setLibcallName(RTLIB::SHL_I128, nullptr);
     322             :   setLibcallName(RTLIB::SRL_I128, nullptr);
     323             :   setLibcallName(RTLIB::SRA_I128, nullptr);
     324             : 
     325             :   // RTLIB
     326        4835 :   if (Subtarget->isAAPCS_ABI() &&
     327        4087 :       (Subtarget->isTargetAEABI() || Subtarget->isTargetGNUAEABI() ||
     328         942 :        Subtarget->isTargetMuslAEABI() || Subtarget->isTargetAndroid())) {
     329             :     static const struct {
     330             :       const RTLIB::Libcall Op;
     331             :       const char * const Name;
     332             :       const CallingConv::ID CC;
     333             :       const ISD::CondCode Cond;
     334             :     } LibraryCalls[] = {
     335             :       // Double-precision floating-point arithmetic helper functions
     336             :       // RTABI chapter 4.1.2, Table 2
     337             :       { RTLIB::ADD_F64, "__aeabi_dadd", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
     338             :       { RTLIB::DIV_F64, "__aeabi_ddiv", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
     339             :       { RTLIB::MUL_F64, "__aeabi_dmul", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
     340             :       { RTLIB::SUB_F64, "__aeabi_dsub", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
     341             : 
     342             :       // Double-precision floating-point comparison helper functions
     343             :       // RTABI chapter 4.1.2, Table 3
     344             :       { RTLIB::OEQ_F64, "__aeabi_dcmpeq", CallingConv::ARM_AAPCS, ISD::SETNE },
     345             :       { RTLIB::UNE_F64, "__aeabi_dcmpeq", CallingConv::ARM_AAPCS, ISD::SETEQ },
     346             :       { RTLIB::OLT_F64, "__aeabi_dcmplt", CallingConv::ARM_AAPCS, ISD::SETNE },
     347             :       { RTLIB::OLE_F64, "__aeabi_dcmple", CallingConv::ARM_AAPCS, ISD::SETNE },
     348             :       { RTLIB::OGE_F64, "__aeabi_dcmpge", CallingConv::ARM_AAPCS, ISD::SETNE },
     349             :       { RTLIB::OGT_F64, "__aeabi_dcmpgt", CallingConv::ARM_AAPCS, ISD::SETNE },
     350             :       { RTLIB::UO_F64,  "__aeabi_dcmpun", CallingConv::ARM_AAPCS, ISD::SETNE },
     351             :       { RTLIB::O_F64,   "__aeabi_dcmpun", CallingConv::ARM_AAPCS, ISD::SETEQ },
     352             : 
     353             :       // Single-precision floating-point arithmetic helper functions
     354             :       // RTABI chapter 4.1.2, Table 4
     355             :       { RTLIB::ADD_F32, "__aeabi_fadd", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
     356             :       { RTLIB::DIV_F32, "__aeabi_fdiv", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
     357             :       { RTLIB::MUL_F32, "__aeabi_fmul", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
     358             :       { RTLIB::SUB_F32, "__aeabi_fsub", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
     359             : 
     360             :       // Single-precision floating-point comparison helper functions
     361             :       // RTABI chapter 4.1.2, Table 5
     362             :       { RTLIB::OEQ_F32, "__aeabi_fcmpeq", CallingConv::ARM_AAPCS, ISD::SETNE },
     363             :       { RTLIB::UNE_F32, "__aeabi_fcmpeq", CallingConv::ARM_AAPCS, ISD::SETEQ },
     364             :       { RTLIB::OLT_F32, "__aeabi_fcmplt", CallingConv::ARM_AAPCS, ISD::SETNE },
     365             :       { RTLIB::OLE_F32, "__aeabi_fcmple", CallingConv::ARM_AAPCS, ISD::SETNE },
     366             :       { RTLIB::OGE_F32, "__aeabi_fcmpge", CallingConv::ARM_AAPCS, ISD::SETNE },
     367             :       { RTLIB::OGT_F32, "__aeabi_fcmpgt", CallingConv::ARM_AAPCS, ISD::SETNE },
     368             :       { RTLIB::UO_F32,  "__aeabi_fcmpun", CallingConv::ARM_AAPCS, ISD::SETNE },
     369             :       { RTLIB::O_F32,   "__aeabi_fcmpun", CallingConv::ARM_AAPCS, ISD::SETEQ },
     370             : 
     371             :       // Floating-point to integer conversions.
     372             :       // RTABI chapter 4.1.2, Table 6
     373             :       { RTLIB::FPTOSINT_F64_I32, "__aeabi_d2iz",  CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
     374             :       { RTLIB::FPTOUINT_F64_I32, "__aeabi_d2uiz", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
     375             :       { RTLIB::FPTOSINT_F64_I64, "__aeabi_d2lz",  CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
     376             :       { RTLIB::FPTOUINT_F64_I64, "__aeabi_d2ulz", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
     377             :       { RTLIB::FPTOSINT_F32_I32, "__aeabi_f2iz",  CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
     378             :       { RTLIB::FPTOUINT_F32_I32, "__aeabi_f2uiz", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
     379             :       { RTLIB::FPTOSINT_F32_I64, "__aeabi_f2lz",  CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
     380             :       { RTLIB::FPTOUINT_F32_I64, "__aeabi_f2ulz", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
     381             : 
     382             :       // Conversions between floating types.
     383             :       // RTABI chapter 4.1.2, Table 7
     384             :       { RTLIB::FPROUND_F64_F32, "__aeabi_d2f", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
     385             :       { RTLIB::FPROUND_F64_F16, "__aeabi_d2h", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
     386             :       { RTLIB::FPEXT_F32_F64,   "__aeabi_f2d", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
     387             : 
     388             :       // Integer to floating-point conversions.
     389             :       // RTABI chapter 4.1.2, Table 8
     390             :       { RTLIB::SINTTOFP_I32_F64, "__aeabi_i2d",  CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
     391             :       { RTLIB::UINTTOFP_I32_F64, "__aeabi_ui2d", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
     392             :       { RTLIB::SINTTOFP_I64_F64, "__aeabi_l2d",  CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
     393             :       { RTLIB::UINTTOFP_I64_F64, "__aeabi_ul2d", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
     394             :       { RTLIB::SINTTOFP_I32_F32, "__aeabi_i2f",  CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
     395             :       { RTLIB::UINTTOFP_I32_F32, "__aeabi_ui2f", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
     396             :       { RTLIB::SINTTOFP_I64_F32, "__aeabi_l2f",  CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
     397             :       { RTLIB::UINTTOFP_I64_F32, "__aeabi_ul2f", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
     398             : 
     399             :       // Long long helper functions
     400             :       // RTABI chapter 4.2, Table 9
     401             :       { RTLIB::MUL_I64, "__aeabi_lmul", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
     402             :       { RTLIB::SHL_I64, "__aeabi_llsl", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
     403             :       { RTLIB::SRL_I64, "__aeabi_llsr", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
     404             :       { RTLIB::SRA_I64, "__aeabi_lasr", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
     405             : 
     406             :       // Integer division functions
     407             :       // RTABI chapter 4.3.1
     408             :       { RTLIB::SDIV_I8,  "__aeabi_idiv",     CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
     409             :       { RTLIB::SDIV_I16, "__aeabi_idiv",     CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
     410             :       { RTLIB::SDIV_I32, "__aeabi_idiv",     CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
     411             :       { RTLIB::SDIV_I64, "__aeabi_ldivmod",  CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
     412             :       { RTLIB::UDIV_I8,  "__aeabi_uidiv",    CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
     413             :       { RTLIB::UDIV_I16, "__aeabi_uidiv",    CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
     414             :       { RTLIB::UDIV_I32, "__aeabi_uidiv",    CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
     415             :       { RTLIB::UDIV_I64, "__aeabi_uldivmod", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
     416             :     };
     417             : 
     418      358086 :     for (const auto &LC : LibraryCalls) {
     419      177430 :       setLibcallName(LC.Op, LC.Name);
     420      177430 :       setLibcallCallingConv(LC.Op, LC.CC);
     421      177430 :       if (LC.Cond != ISD::SETCC_INVALID)
     422       51616 :         setCmpLibcallCC(LC.Op, LC.Cond);
     423             :     }
     424             : 
     425             :     // EABI dependent RTLIB
     426        3226 :     if (TM.Options.EABIVersion == EABI::EABI4 ||
     427             :         TM.Options.EABIVersion == EABI::EABI5) {
     428             :       static const struct {
     429             :         const RTLIB::Libcall Op;
     430             :         const char *const Name;
     431             :         const CallingConv::ID CC;
     432             :         const ISD::CondCode Cond;
     433             :       } MemOpsLibraryCalls[] = {
     434             :         // Memory operations
     435             :         // RTABI chapter 4.3.4
     436             :         { RTLIB::MEMCPY,  "__aeabi_memcpy",  CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
     437             :         { RTLIB::MEMMOVE, "__aeabi_memmove", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
     438             :         { RTLIB::MEMSET,  "__aeabi_memset",  CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
     439             :       };
     440             : 
     441       13377 :       for (const auto &LC : MemOpsLibraryCalls) {
     442        5733 :         setLibcallName(LC.Op, LC.Name);
     443        5733 :         setLibcallCallingConv(LC.Op, LC.CC);
     444        5733 :         if (LC.Cond != ISD::SETCC_INVALID)
     445           0 :           setCmpLibcallCC(LC.Op, LC.Cond);
     446             :       }
     447             :     }
     448             :   }
     449             : 
     450        9670 :   if (Subtarget->isTargetWindows()) {
     451             :     static const struct {
     452             :       const RTLIB::Libcall Op;
     453             :       const char * const Name;
     454             :       const CallingConv::ID CC;
     455             :     } LibraryCalls[] = {
     456             :       { RTLIB::FPTOSINT_F32_I64, "__stoi64", CallingConv::ARM_AAPCS_VFP },
     457             :       { RTLIB::FPTOSINT_F64_I64, "__dtoi64", CallingConv::ARM_AAPCS_VFP },
     458             :       { RTLIB::FPTOUINT_F32_I64, "__stou64", CallingConv::ARM_AAPCS_VFP },
     459             :       { RTLIB::FPTOUINT_F64_I64, "__dtou64", CallingConv::ARM_AAPCS_VFP },
     460             :       { RTLIB::SINTTOFP_I64_F32, "__i64tos", CallingConv::ARM_AAPCS_VFP },
     461             :       { RTLIB::SINTTOFP_I64_F64, "__i64tod", CallingConv::ARM_AAPCS_VFP },
     462             :       { RTLIB::UINTTOFP_I64_F32, "__u64tos", CallingConv::ARM_AAPCS_VFP },
     463             :       { RTLIB::UINTTOFP_I64_F64, "__u64tod", CallingConv::ARM_AAPCS_VFP },
     464             :     };
     465             : 
     466        1377 :     for (const auto &LC : LibraryCalls) {
     467         648 :       setLibcallName(LC.Op, LC.Name);
     468         648 :       setLibcallCallingConv(LC.Op, LC.CC);
     469             :     }
     470             :   }
     471             : 
     472             :   // Use divmod compiler-rt calls for iOS 5.0 and later.
     473        4835 :   if (Subtarget->isTargetMachO() &&
     474         382 :       !(Subtarget->isTargetIOS() &&
     475         382 :         Subtarget->getTargetTriple().isOSVersionLT(5, 0))) {
     476             :     setLibcallName(RTLIB::SDIVREM_I32, "__divmodsi4");
     477             :     setLibcallName(RTLIB::UDIVREM_I32, "__udivmodsi4");
     478             :   }
     479             : 
     480             :   // The half <-> float conversion functions are always soft-float on
     481             :   // non-watchos platforms, but are needed for some targets which use a
     482             :   // hard-float calling convention by default.
     483        9670 :   if (!Subtarget->isTargetWatchABI()) {
     484        4810 :     if (Subtarget->isAAPCS_ABI()) {
     485             :       setLibcallCallingConv(RTLIB::FPROUND_F32_F16, CallingConv::ARM_AAPCS);
     486             :       setLibcallCallingConv(RTLIB::FPROUND_F64_F16, CallingConv::ARM_AAPCS);
     487             :       setLibcallCallingConv(RTLIB::FPEXT_F16_F32, CallingConv::ARM_AAPCS);
     488             :     } else {
     489             :       setLibcallCallingConv(RTLIB::FPROUND_F32_F16, CallingConv::ARM_APCS);
     490             :       setLibcallCallingConv(RTLIB::FPROUND_F64_F16, CallingConv::ARM_APCS);
     491             :       setLibcallCallingConv(RTLIB::FPEXT_F16_F32, CallingConv::ARM_APCS);
     492             :     }
     493             :   }
     494             : 
     495             :   // In EABI, these functions have an __aeabi_ prefix, but in GNUEABI they have
     496             :   // a __gnu_ prefix (which is the default).
     497        4835 :   if (Subtarget->isTargetAEABI()) {
     498             :     static const struct {
     499             :       const RTLIB::Libcall Op;
     500             :       const char * const Name;
     501             :       const CallingConv::ID CC;
     502             :     } LibraryCalls[] = {
     503             :       { RTLIB::FPROUND_F32_F16, "__aeabi_f2h", CallingConv::ARM_AAPCS },
     504             :       { RTLIB::FPROUND_F64_F16, "__aeabi_d2h", CallingConv::ARM_AAPCS },
     505             :       { RTLIB::FPEXT_F16_F32, "__aeabi_h2f", CallingConv::ARM_AAPCS },
     506             :     };
     507             : 
     508       12768 :     for (const auto &LC : LibraryCalls) {
     509        5472 :       setLibcallName(LC.Op, LC.Name);
     510        5472 :       setLibcallCallingConv(LC.Op, LC.CC);
     511             :     }
     512             :   }
     513             : 
     514        4835 :   if (Subtarget->isThumb1Only())
     515             :     addRegisterClass(MVT::i32, &ARM::tGPRRegClass);
     516             :   else
     517             :     addRegisterClass(MVT::i32, &ARM::GPRRegClass);
     518             : 
     519        4835 :   if (!Subtarget->useSoftFloat() && Subtarget->hasVFP2() &&
     520        2905 :       !Subtarget->isThumb1Only()) {
     521             :     addRegisterClass(MVT::f32, &ARM::SPRRegClass);
     522             :     addRegisterClass(MVT::f64, &ARM::DPRRegClass);
     523             :   }
     524             : 
     525        4835 :   if (Subtarget->hasFullFP16()) {
     526             :     addRegisterClass(MVT::f16, &ARM::HPRRegClass);
     527             :     setOperationAction(ISD::BITCAST, MVT::i16, Custom);
     528             :     setOperationAction(ISD::BITCAST, MVT::i32, Custom);
     529             :     setOperationAction(ISD::BITCAST, MVT::f16, Custom);
     530             : 
     531             :     setOperationAction(ISD::FMINNUM, MVT::f16, Legal);
     532             :     setOperationAction(ISD::FMAXNUM, MVT::f16, Legal);
     533             :   }
     534             : 
     535      464160 :   for (MVT VT : MVT::vector_valuetypes()) {
     536    44095200 :     for (MVT InnerVT : MVT::vector_valuetypes()) {
     537             :       setTruncStoreAction(VT, InnerVT, Expand);
     538             :       setLoadExtAction(ISD::SEXTLOAD, VT, InnerVT, Expand);
     539             :       setLoadExtAction(ISD::ZEXTLOAD, VT, InnerVT, Expand);
     540             :       setLoadExtAction(ISD::EXTLOAD, VT, InnerVT, Expand);
     541             :     }
     542             : 
     543             :     setOperationAction(ISD::MULHS, VT, Expand);
     544             :     setOperationAction(ISD::SMUL_LOHI, VT, Expand);
     545             :     setOperationAction(ISD::MULHU, VT, Expand);
     546             :     setOperationAction(ISD::UMUL_LOHI, VT, Expand);
     547             : 
     548             :     setOperationAction(ISD::BSWAP, VT, Expand);
     549             :   }
     550             : 
     551             :   setOperationAction(ISD::ConstantFP, MVT::f32, Custom);
     552             :   setOperationAction(ISD::ConstantFP, MVT::f64, Custom);
     553             : 
     554             :   setOperationAction(ISD::READ_REGISTER, MVT::i64, Custom);
     555             :   setOperationAction(ISD::WRITE_REGISTER, MVT::i64, Custom);
     556             : 
     557        4835 :   if (Subtarget->hasNEON()) {
     558        2517 :     addDRTypeForNEON(MVT::v2f32);
     559        2517 :     addDRTypeForNEON(MVT::v8i8);
     560        2517 :     addDRTypeForNEON(MVT::v4i16);
     561        2517 :     addDRTypeForNEON(MVT::v2i32);
     562        2517 :     addDRTypeForNEON(MVT::v1i64);
     563             : 
     564        2517 :     addQRTypeForNEON(MVT::v4f32);
     565        2517 :     addQRTypeForNEON(MVT::v2f64);
     566        2517 :     addQRTypeForNEON(MVT::v16i8);
     567        2517 :     addQRTypeForNEON(MVT::v8i16);
     568        2517 :     addQRTypeForNEON(MVT::v4i32);
     569        2517 :     addQRTypeForNEON(MVT::v2i64);
     570             : 
     571        2517 :     if (Subtarget->hasFullFP16()) {
     572          28 :       addQRTypeForNEON(MVT::v8f16);
     573          28 :       addDRTypeForNEON(MVT::v4f16);
     574             :     }
     575             : 
     576             :     // v2f64 is legal so that QR subregs can be extracted as f64 elements, but
     577             :     // neither Neon nor VFP support any arithmetic operations on it.
     578             :     // The same with v4f32. But keep in mind that vadd, vsub, vmul are natively
     579             :     // supported for v4f32.
     580             :     setOperationAction(ISD::FADD, MVT::v2f64, Expand);
     581             :     setOperationAction(ISD::FSUB, MVT::v2f64, Expand);
     582             :     setOperationAction(ISD::FMUL, MVT::v2f64, Expand);
     583             :     // FIXME: Code duplication: FDIV and FREM are expanded always, see
     584             :     // ARMTargetLowering::addTypeForNEON method for details.
     585             :     setOperationAction(ISD::FDIV, MVT::v2f64, Expand);
     586             :     setOperationAction(ISD::FREM, MVT::v2f64, Expand);
     587             :     // FIXME: Create unittest.
     588             :     // In another words, find a way when "copysign" appears in DAG with vector
     589             :     // operands.
     590             :     setOperationAction(ISD::FCOPYSIGN, MVT::v2f64, Expand);
     591             :     // FIXME: Code duplication: SETCC has custom operation action, see
     592             :     // ARMTargetLowering::addTypeForNEON method for details.
     593             :     setOperationAction(ISD::SETCC, MVT::v2f64, Expand);
     594             :     // FIXME: Create unittest for FNEG and for FABS.
     595             :     setOperationAction(ISD::FNEG, MVT::v2f64, Expand);
     596             :     setOperationAction(ISD::FABS, MVT::v2f64, Expand);
     597             :     setOperationAction(ISD::FSQRT, MVT::v2f64, Expand);
     598             :     setOperationAction(ISD::FSIN, MVT::v2f64, Expand);
     599             :     setOperationAction(ISD::FCOS, MVT::v2f64, Expand);
     600             :     setOperationAction(ISD::FPOW, MVT::v2f64, Expand);
     601             :     setOperationAction(ISD::FLOG, MVT::v2f64, Expand);
     602             :     setOperationAction(ISD::FLOG2, MVT::v2f64, Expand);
     603             :     setOperationAction(ISD::FLOG10, MVT::v2f64, Expand);
     604             :     setOperationAction(ISD::FEXP, MVT::v2f64, Expand);
     605             :     setOperationAction(ISD::FEXP2, MVT::v2f64, Expand);
     606             :     // FIXME: Create unittest for FCEIL, FTRUNC, FRINT, FNEARBYINT, FFLOOR.
     607             :     setOperationAction(ISD::FCEIL, MVT::v2f64, Expand);
     608             :     setOperationAction(ISD::FTRUNC, MVT::v2f64, Expand);
     609             :     setOperationAction(ISD::FRINT, MVT::v2f64, Expand);
     610             :     setOperationAction(ISD::FNEARBYINT, MVT::v2f64, Expand);
     611             :     setOperationAction(ISD::FFLOOR, MVT::v2f64, Expand);
     612             :     setOperationAction(ISD::FMA, MVT::v2f64, Expand);
     613             : 
     614             :     setOperationAction(ISD::FSQRT, MVT::v4f32, Expand);
     615             :     setOperationAction(ISD::FSIN, MVT::v4f32, Expand);
     616             :     setOperationAction(ISD::FCOS, MVT::v4f32, Expand);
     617             :     setOperationAction(ISD::FPOW, MVT::v4f32, Expand);
     618             :     setOperationAction(ISD::FLOG, MVT::v4f32, Expand);
     619             :     setOperationAction(ISD::FLOG2, MVT::v4f32, Expand);
     620             :     setOperationAction(ISD::FLOG10, MVT::v4f32, Expand);
     621             :     setOperationAction(ISD::FEXP, MVT::v4f32, Expand);
     622             :     setOperationAction(ISD::FEXP2, MVT::v4f32, Expand);
     623             :     setOperationAction(ISD::FCEIL, MVT::v4f32, Expand);
     624             :     setOperationAction(ISD::FTRUNC, MVT::v4f32, Expand);
     625             :     setOperationAction(ISD::FRINT, MVT::v4f32, Expand);
     626             :     setOperationAction(ISD::FNEARBYINT, MVT::v4f32, Expand);
     627             :     setOperationAction(ISD::FFLOOR, MVT::v4f32, Expand);
     628             : 
     629             :     // Mark v2f32 intrinsics.
     630             :     setOperationAction(ISD::FSQRT, MVT::v2f32, Expand);
     631             :     setOperationAction(ISD::FSIN, MVT::v2f32, Expand);
     632             :     setOperationAction(ISD::FCOS, MVT::v2f32, Expand);
     633             :     setOperationAction(ISD::FPOW, MVT::v2f32, Expand);
     634             :     setOperationAction(ISD::FLOG, MVT::v2f32, Expand);
     635             :     setOperationAction(ISD::FLOG2, MVT::v2f32, Expand);
     636             :     setOperationAction(ISD::FLOG10, MVT::v2f32, Expand);
     637             :     setOperationAction(ISD::FEXP, MVT::v2f32, Expand);
     638             :     setOperationAction(ISD::FEXP2, MVT::v2f32, Expand);
     639             :     setOperationAction(ISD::FCEIL, MVT::v2f32, Expand);
     640             :     setOperationAction(ISD::FTRUNC, MVT::v2f32, Expand);
     641             :     setOperationAction(ISD::FRINT, MVT::v2f32, Expand);
     642             :     setOperationAction(ISD::FNEARBYINT, MVT::v2f32, Expand);
     643             :     setOperationAction(ISD::FFLOOR, MVT::v2f32, Expand);
     644             : 
     645             :     // Neon does not support some operations on v1i64 and v2i64 types.
     646             :     setOperationAction(ISD::MUL, MVT::v1i64, Expand);
     647             :     // Custom handling for some quad-vector types to detect VMULL.
     648             :     setOperationAction(ISD::MUL, MVT::v8i16, Custom);
     649             :     setOperationAction(ISD::MUL, MVT::v4i32, Custom);
     650             :     setOperationAction(ISD::MUL, MVT::v2i64, Custom);
     651             :     // Custom handling for some vector types to avoid expensive expansions
     652             :     setOperationAction(ISD::SDIV, MVT::v4i16, Custom);
     653             :     setOperationAction(ISD::SDIV, MVT::v8i8, Custom);
     654             :     setOperationAction(ISD::UDIV, MVT::v4i16, Custom);
     655             :     setOperationAction(ISD::UDIV, MVT::v8i8, Custom);
     656             :     // Neon does not have single instruction SINT_TO_FP and UINT_TO_FP with
     657             :     // a destination type that is wider than the source, and nor does
     658             :     // it have a FP_TO_[SU]INT instruction with a narrower destination than
     659             :     // source.
     660             :     setOperationAction(ISD::SINT_TO_FP, MVT::v4i16, Custom);
     661             :     setOperationAction(ISD::UINT_TO_FP, MVT::v4i16, Custom);
     662             :     setOperationAction(ISD::FP_TO_UINT, MVT::v4i16, Custom);
     663             :     setOperationAction(ISD::FP_TO_SINT, MVT::v4i16, Custom);
     664             : 
     665             :     setOperationAction(ISD::FP_ROUND,   MVT::v2f32, Expand);
     666             :     setOperationAction(ISD::FP_EXTEND,  MVT::v2f64, Expand);
     667             : 
     668             :     // NEON does not have single instruction CTPOP for vectors with element
     669             :     // types wider than 8-bits.  However, custom lowering can leverage the
     670             :     // v8i8/v16i8 vcnt instruction.
     671             :     setOperationAction(ISD::CTPOP,      MVT::v2i32, Custom);
     672             :     setOperationAction(ISD::CTPOP,      MVT::v4i32, Custom);
     673             :     setOperationAction(ISD::CTPOP,      MVT::v4i16, Custom);
     674             :     setOperationAction(ISD::CTPOP,      MVT::v8i16, Custom);
     675             :     setOperationAction(ISD::CTPOP,      MVT::v1i64, Expand);
     676             :     setOperationAction(ISD::CTPOP,      MVT::v2i64, Expand);
     677             : 
     678             :     setOperationAction(ISD::CTLZ,       MVT::v1i64, Expand);
     679             :     setOperationAction(ISD::CTLZ,       MVT::v2i64, Expand);
     680             : 
     681             :     // NEON does not have single instruction CTTZ for vectors.
     682             :     setOperationAction(ISD::CTTZ, MVT::v8i8, Custom);
     683             :     setOperationAction(ISD::CTTZ, MVT::v4i16, Custom);
     684             :     setOperationAction(ISD::CTTZ, MVT::v2i32, Custom);
     685             :     setOperationAction(ISD::CTTZ, MVT::v1i64, Custom);
     686             : 
     687             :     setOperationAction(ISD::CTTZ, MVT::v16i8, Custom);
     688             :     setOperationAction(ISD::CTTZ, MVT::v8i16, Custom);
     689             :     setOperationAction(ISD::CTTZ, MVT::v4i32, Custom);
     690             :     setOperationAction(ISD::CTTZ, MVT::v2i64, Custom);
     691             : 
     692             :     setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::v8i8, Custom);
     693             :     setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::v4i16, Custom);
     694             :     setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::v2i32, Custom);
     695             :     setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::v1i64, Custom);
     696             : 
     697             :     setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::v16i8, Custom);
     698             :     setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::v8i16, Custom);
     699             :     setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::v4i32, Custom);
     700             :     setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::v2i64, Custom);
     701             : 
     702             :     // NEON only has FMA instructions as of VFP4.
     703        2517 :     if (!Subtarget->hasVFP4()) {
     704             :       setOperationAction(ISD::FMA, MVT::v2f32, Expand);
     705             :       setOperationAction(ISD::FMA, MVT::v4f32, Expand);
     706             :     }
     707             : 
     708             :     setTargetDAGCombine(ISD::INTRINSIC_VOID);
     709             :     setTargetDAGCombine(ISD::INTRINSIC_W_CHAIN);
     710             :     setTargetDAGCombine(ISD::INTRINSIC_WO_CHAIN);
     711             :     setTargetDAGCombine(ISD::SHL);
     712             :     setTargetDAGCombine(ISD::SRL);
     713             :     setTargetDAGCombine(ISD::SRA);
     714             :     setTargetDAGCombine(ISD::SIGN_EXTEND);
     715             :     setTargetDAGCombine(ISD::ZERO_EXTEND);
     716             :     setTargetDAGCombine(ISD::ANY_EXTEND);
     717             :     setTargetDAGCombine(ISD::BUILD_VECTOR);
     718             :     setTargetDAGCombine(ISD::VECTOR_SHUFFLE);
     719             :     setTargetDAGCombine(ISD::INSERT_VECTOR_ELT);
     720             :     setTargetDAGCombine(ISD::STORE);
     721             :     setTargetDAGCombine(ISD::FP_TO_SINT);
     722             :     setTargetDAGCombine(ISD::FP_TO_UINT);
     723             :     setTargetDAGCombine(ISD::FDIV);
     724             :     setTargetDAGCombine(ISD::LOAD);
     725             : 
     726             :     // It is legal to extload from v4i8 to v4i16 or v4i32.
     727       15102 :     for (MVT Ty : {MVT::v8i8, MVT::v4i8, MVT::v2i8, MVT::v4i16, MVT::v2i16,
     728       17619 :                    MVT::v2i32}) {
     729     1087344 :       for (MVT VT : MVT::integer_vector_valuetypes()) {
     730             :         setLoadExtAction(ISD::EXTLOAD, VT, Ty, Legal);
     731             :         setLoadExtAction(ISD::ZEXTLOAD, VT, Ty, Legal);
     732             :         setLoadExtAction(ISD::SEXTLOAD, VT, Ty, Legal);
     733             :       }
     734             :     }
     735             :   }
     736             : 
     737        4835 :   if (Subtarget->isFPOnlySP()) {
     738             :     // When targeting a floating-point unit with only single-precision
     739             :     // operations, f64 is legal for the few double-precision instructions which
     740             :     // are present However, no double-precision operations other than moves,
     741             :     // loads and stores are provided by the hardware.
     742             :     setOperationAction(ISD::FADD,       MVT::f64, Expand);
     743             :     setOperationAction(ISD::FSUB,       MVT::f64, Expand);
     744             :     setOperationAction(ISD::FMUL,       MVT::f64, Expand);
     745             :     setOperationAction(ISD::FMA,        MVT::f64, Expand);
     746             :     setOperationAction(ISD::FDIV,       MVT::f64, Expand);
     747             :     setOperationAction(ISD::FREM,       MVT::f64, Expand);
     748             :     setOperationAction(ISD::FCOPYSIGN,  MVT::f64, Expand);
     749             :     setOperationAction(ISD::FGETSIGN,   MVT::f64, Expand);
     750             :     setOperationAction(ISD::FNEG,       MVT::f64, Expand);
     751             :     setOperationAction(ISD::FABS,       MVT::f64, Expand);
     752             :     setOperationAction(ISD::FSQRT,      MVT::f64, Expand);
     753             :     setOperationAction(ISD::FSIN,       MVT::f64, Expand);
     754             :     setOperationAction(ISD::FCOS,       MVT::f64, Expand);
     755             :     setOperationAction(ISD::FPOW,       MVT::f64, Expand);
     756             :     setOperationAction(ISD::FLOG,       MVT::f64, Expand);
     757             :     setOperationAction(ISD::FLOG2,      MVT::f64, Expand);
     758             :     setOperationAction(ISD::FLOG10,     MVT::f64, Expand);
     759             :     setOperationAction(ISD::FEXP,       MVT::f64, Expand);
     760             :     setOperationAction(ISD::FEXP2,      MVT::f64, Expand);
     761             :     setOperationAction(ISD::FCEIL,      MVT::f64, Expand);
     762             :     setOperationAction(ISD::FTRUNC,     MVT::f64, Expand);
     763             :     setOperationAction(ISD::FRINT,      MVT::f64, Expand);
     764             :     setOperationAction(ISD::FNEARBYINT, MVT::f64, Expand);
     765             :     setOperationAction(ISD::FFLOOR,     MVT::f64, Expand);
     766             :     setOperationAction(ISD::SINT_TO_FP, MVT::i32, Custom);
     767             :     setOperationAction(ISD::UINT_TO_FP, MVT::i32, Custom);
     768             :     setOperationAction(ISD::FP_TO_SINT, MVT::i32, Custom);
     769             :     setOperationAction(ISD::FP_TO_UINT, MVT::i32, Custom);
     770             :     setOperationAction(ISD::FP_TO_SINT, MVT::f64, Custom);
     771             :     setOperationAction(ISD::FP_TO_UINT, MVT::f64, Custom);
     772             :     setOperationAction(ISD::FP_ROUND,   MVT::f32, Custom);
     773             :     setOperationAction(ISD::FP_EXTEND,  MVT::f64, Custom);
     774             :   }
     775             : 
     776        4835 :   computeRegisterProperties(Subtarget->getRegisterInfo());
     777             : 
     778             :   // ARM does not have floating-point extending loads.
     779       33845 :   for (MVT VT : MVT::fp_valuetypes()) {
     780             :     setLoadExtAction(ISD::EXTLOAD, VT, MVT::f32, Expand);
     781             :     setLoadExtAction(ISD::EXTLOAD, VT, MVT::f16, Expand);
     782             :   }
     783             : 
     784             :   // ... or truncating stores
     785             :   setTruncStoreAction(MVT::f64, MVT::f32, Expand);
     786             :   setTruncStoreAction(MVT::f32, MVT::f16, Expand);
     787             :   setTruncStoreAction(MVT::f64, MVT::f16, Expand);
     788             : 
     789             :   // ARM does not have i1 sign extending load.
     790       33845 :   for (MVT VT : MVT::integer_valuetypes())
     791             :     setLoadExtAction(ISD::SEXTLOAD, VT, MVT::i1, Promote);
     792             : 
     793             :   // ARM supports all 4 flavors of integer indexed load / store.
     794        4835 :   if (!Subtarget->isThumb1Only()) {
     795       17448 :     for (unsigned im = (unsigned)ISD::PRE_INC;
     796       21810 :          im != (unsigned)ISD::LAST_INDEXED_MODE; ++im) {
     797             :       setIndexedLoadAction(im,  MVT::i1,  Legal);
     798             :       setIndexedLoadAction(im,  MVT::i8,  Legal);
     799             :       setIndexedLoadAction(im,  MVT::i16, Legal);
     800             :       setIndexedLoadAction(im,  MVT::i32, Legal);
     801             :       setIndexedStoreAction(im, MVT::i1,  Legal);
     802             :       setIndexedStoreAction(im, MVT::i8,  Legal);
     803             :       setIndexedStoreAction(im, MVT::i16, Legal);
     804             :       setIndexedStoreAction(im, MVT::i32, Legal);
     805             :     }
     806             :   } else {
     807             :     // Thumb-1 has limited post-inc load/store support - LDM r0!, {r1}.
     808             :     setIndexedLoadAction(ISD::POST_INC, MVT::i32,  Legal);
     809             :     setIndexedStoreAction(ISD::POST_INC, MVT::i32,  Legal);
     810             :   }
     811             : 
     812             :   setOperationAction(ISD::SADDO, MVT::i32, Custom);
     813             :   setOperationAction(ISD::UADDO, MVT::i32, Custom);
     814             :   setOperationAction(ISD::SSUBO, MVT::i32, Custom);
     815             :   setOperationAction(ISD::USUBO, MVT::i32, Custom);
     816             : 
     817             :   setOperationAction(ISD::ADDCARRY, MVT::i32, Custom);
     818             :   setOperationAction(ISD::SUBCARRY, MVT::i32, Custom);
     819             : 
     820             :   // i64 operation support.
     821             :   setOperationAction(ISD::MUL,     MVT::i64, Expand);
     822             :   setOperationAction(ISD::MULHU,   MVT::i32, Expand);
     823        4835 :   if (Subtarget->isThumb1Only()) {
     824             :     setOperationAction(ISD::UMUL_LOHI, MVT::i32, Expand);
     825             :     setOperationAction(ISD::SMUL_LOHI, MVT::i32, Expand);
     826             :   }
     827        9197 :   if (Subtarget->isThumb1Only() || !Subtarget->hasV6Ops()
     828        1453 :       || (Subtarget->isThumb2() && !Subtarget->hasDSP()))
     829             :     setOperationAction(ISD::MULHS, MVT::i32, Expand);
     830             : 
     831             :   setOperationAction(ISD::SHL_PARTS, MVT::i32, Custom);
     832             :   setOperationAction(ISD::SRA_PARTS, MVT::i32, Custom);
     833             :   setOperationAction(ISD::SRL_PARTS, MVT::i32, Custom);
     834             :   setOperationAction(ISD::SRL,       MVT::i64, Custom);
     835             :   setOperationAction(ISD::SRA,       MVT::i64, Custom);
     836             :   setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::i64, Custom);
     837             : 
     838             :   // Expand to __aeabi_l{lsl,lsr,asr} calls for Thumb1.
     839        4835 :   if (Subtarget->isThumb1Only()) {
     840             :     setOperationAction(ISD::SHL_PARTS, MVT::i32, Expand);
     841             :     setOperationAction(ISD::SRA_PARTS, MVT::i32, Expand);
     842             :     setOperationAction(ISD::SRL_PARTS, MVT::i32, Expand);
     843             :   }
     844             : 
     845        9197 :   if (!Subtarget->isThumb1Only() && Subtarget->hasV6T2Ops())
     846             :     setOperationAction(ISD::BITREVERSE, MVT::i32, Legal);
     847             : 
     848             :   // ARM does not have ROTL.
     849             :   setOperationAction(ISD::ROTL, MVT::i32, Expand);
     850      464160 :   for (MVT VT : MVT::vector_valuetypes()) {
     851             :     setOperationAction(ISD::ROTL, VT, Expand);
     852             :     setOperationAction(ISD::ROTR, VT, Expand);
     853             :   }
     854             :   setOperationAction(ISD::CTTZ,  MVT::i32, Custom);
     855             :   setOperationAction(ISD::CTPOP, MVT::i32, Expand);
     856        4835 :   if (!Subtarget->hasV5TOps() || Subtarget->isThumb1Only())
     857             :     setOperationAction(ISD::CTLZ, MVT::i32, Expand);
     858             : 
     859             :   // @llvm.readcyclecounter requires the Performance Monitors extension.
     860             :   // Default to the 0 expansion on unsupported platforms.
     861             :   // FIXME: Technically there are older ARM CPUs that have
     862             :   // implementation-specific ways of obtaining this information.
     863        4835 :   if (Subtarget->hasPerfMon())
     864             :     setOperationAction(ISD::READCYCLECOUNTER, MVT::i64, Custom);
     865             : 
     866             :   // Only ARMv6 has BSWAP.
     867        4835 :   if (!Subtarget->hasV6Ops())
     868             :     setOperationAction(ISD::BSWAP, MVT::i32, Expand);
     869             : 
     870        4835 :   bool hasDivide = Subtarget->isThumb() ? Subtarget->hasDivideInThumbMode()
     871             :                                         : Subtarget->hasDivideInARMMode();
     872        4835 :   if (!hasDivide) {
     873             :     // These are expanded into libcalls if the cpu doesn't have HW divider.
     874             :     setOperationAction(ISD::SDIV,  MVT::i32, LibCall);
     875             :     setOperationAction(ISD::UDIV,  MVT::i32, LibCall);
     876             :   }
     877             : 
     878        4835 :   if (Subtarget->isTargetWindows() && !Subtarget->hasDivideInThumbMode()) {
     879             :     setOperationAction(ISD::SDIV, MVT::i32, Custom);
     880             :     setOperationAction(ISD::UDIV, MVT::i32, Custom);
     881             : 
     882             :     setOperationAction(ISD::SDIV, MVT::i64, Custom);
     883             :     setOperationAction(ISD::UDIV, MVT::i64, Custom);
     884             :   }
     885             : 
     886             :   setOperationAction(ISD::SREM,  MVT::i32, Expand);
     887             :   setOperationAction(ISD::UREM,  MVT::i32, Expand);
     888             : 
     889             :   // Register based DivRem for AEABI (RTABI 4.2)
     890        7846 :   if (Subtarget->isTargetAEABI() || Subtarget->isTargetAndroid() ||
     891        1607 :       Subtarget->isTargetGNUAEABI() || Subtarget->isTargetMuslAEABI() ||
     892             :       Subtarget->isTargetWindows()) {
     893             :     setOperationAction(ISD::SREM, MVT::i64, Custom);
     894             :     setOperationAction(ISD::UREM, MVT::i64, Custom);
     895        3309 :     HasStandaloneRem = false;
     896             : 
     897        3309 :     if (Subtarget->isTargetWindows()) {
     898             :       const struct {
     899             :         const RTLIB::Libcall Op;
     900             :         const char * const Name;
     901             :         const CallingConv::ID CC;
     902          81 :       } LibraryCalls[] = {
     903             :         { RTLIB::SDIVREM_I8, "__rt_sdiv", CallingConv::ARM_AAPCS },
     904             :         { RTLIB::SDIVREM_I16, "__rt_sdiv", CallingConv::ARM_AAPCS },
     905             :         { RTLIB::SDIVREM_I32, "__rt_sdiv", CallingConv::ARM_AAPCS },
     906             :         { RTLIB::SDIVREM_I64, "__rt_sdiv64", CallingConv::ARM_AAPCS },
     907             : 
     908             :         { RTLIB::UDIVREM_I8, "__rt_udiv", CallingConv::ARM_AAPCS },
     909             :         { RTLIB::UDIVREM_I16, "__rt_udiv", CallingConv::ARM_AAPCS },
     910             :         { RTLIB::UDIVREM_I32, "__rt_udiv", CallingConv::ARM_AAPCS },
     911             :         { RTLIB::UDIVREM_I64, "__rt_udiv64", CallingConv::ARM_AAPCS },
     912             :       };
     913             : 
     914        1377 :       for (const auto &LC : LibraryCalls) {
     915         648 :         setLibcallName(LC.Op, LC.Name);
     916         648 :         setLibcallCallingConv(LC.Op, LC.CC);
     917             :       }
     918             :     } else {
     919             :       const struct {
     920             :         const RTLIB::Libcall Op;
     921             :         const char * const Name;
     922             :         const CallingConv::ID CC;
     923        3228 :       } LibraryCalls[] = {
     924             :         { RTLIB::SDIVREM_I8, "__aeabi_idivmod", CallingConv::ARM_AAPCS },
     925             :         { RTLIB::SDIVREM_I16, "__aeabi_idivmod", CallingConv::ARM_AAPCS },
     926             :         { RTLIB::SDIVREM_I32, "__aeabi_idivmod", CallingConv::ARM_AAPCS },
     927             :         { RTLIB::SDIVREM_I64, "__aeabi_ldivmod", CallingConv::ARM_AAPCS },
     928             : 
     929             :         { RTLIB::UDIVREM_I8, "__aeabi_uidivmod", CallingConv::ARM_AAPCS },
     930             :         { RTLIB::UDIVREM_I16, "__aeabi_uidivmod", CallingConv::ARM_AAPCS },
     931             :         { RTLIB::UDIVREM_I32, "__aeabi_uidivmod", CallingConv::ARM_AAPCS },
     932             :         { RTLIB::UDIVREM_I64, "__aeabi_uldivmod", CallingConv::ARM_AAPCS },
     933             :       };
     934             : 
     935       54876 :       for (const auto &LC : LibraryCalls) {
     936       25824 :         setLibcallName(LC.Op, LC.Name);
     937       25824 :         setLibcallCallingConv(LC.Op, LC.CC);
     938             :       }
     939             :     }
     940             : 
     941             :     setOperationAction(ISD::SDIVREM, MVT::i32, Custom);
     942             :     setOperationAction(ISD::UDIVREM, MVT::i32, Custom);
     943             :     setOperationAction(ISD::SDIVREM, MVT::i64, Custom);
     944             :     setOperationAction(ISD::UDIVREM, MVT::i64, Custom);
     945             :   } else {
     946             :     setOperationAction(ISD::SDIVREM, MVT::i32, Expand);
     947             :     setOperationAction(ISD::UDIVREM, MVT::i32, Expand);
     948             :   }
     949             : 
     950        9670 :   if (Subtarget->isTargetWindows() && Subtarget->getTargetTriple().isOSMSVCRT())
     951         405 :     for (auto &VT : {MVT::f32, MVT::f64})
     952         162 :       setOperationAction(ISD::FPOWI, VT, Custom);
     953             : 
     954             :   setOperationAction(ISD::GlobalAddress, MVT::i32,   Custom);
     955             :   setOperationAction(ISD::ConstantPool,  MVT::i32,   Custom);
     956             :   setOperationAction(ISD::GlobalTLSAddress, MVT::i32, Custom);
     957             :   setOperationAction(ISD::BlockAddress, MVT::i32, Custom);
     958             : 
     959             :   setOperationAction(ISD::TRAP, MVT::Other, Legal);
     960             : 
     961             :   // Use the default implementation.
     962             :   setOperationAction(ISD::VASTART,            MVT::Other, Custom);
     963             :   setOperationAction(ISD::VAARG,              MVT::Other, Expand);
     964             :   setOperationAction(ISD::VACOPY,             MVT::Other, Expand);
     965             :   setOperationAction(ISD::VAEND,              MVT::Other, Expand);
     966             :   setOperationAction(ISD::STACKSAVE,          MVT::Other, Expand);
     967             :   setOperationAction(ISD::STACKRESTORE,       MVT::Other, Expand);
     968             : 
     969        9670 :   if (Subtarget->isTargetWindows())
     970             :     setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i32, Custom);
     971             :   else
     972             :     setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i32, Expand);
     973             : 
     974             :   // ARMv6 Thumb1 (except for CPUs that support dmb / dsb) and earlier use
     975             :   // the default expansion.
     976        4835 :   InsertFencesForAtomic = false;
     977        3241 :   if (Subtarget->hasAnyDataBarrier() &&
     978        4731 :       (!Subtarget->isThumb() || Subtarget->hasV8MBaselineOps())) {
     979             :     // ATOMIC_FENCE needs custom lowering; the others should have been expanded
     980             :     // to ldrex/strex loops already.
     981             :     setOperationAction(ISD::ATOMIC_FENCE,     MVT::Other, Custom);
     982        4351 :     if (!Subtarget->isThumb() || !Subtarget->isMClass())
     983             :       setOperationAction(ISD::ATOMIC_CMP_SWAP,  MVT::i64, Custom);
     984             : 
     985             :     // On v8, we have particularly efficient implementations of atomic fences
     986             :     // if they can be combined with nearby atomic loads and stores.
     987        3051 :     if (!Subtarget->hasV8Ops() || getTargetMachine().getOptLevel() == 0) {
     988             :       // Automatically insert fences (dmb ish) around ATOMIC_SWAP etc.
     989        2766 :       InsertFencesForAtomic = true;
     990             :     }
     991             :   } else {
     992             :     // If there's anything we can use as a barrier, go through custom lowering
     993             :     // for ATOMIC_FENCE.
     994             :     // If target has DMB in thumb, Fences can be inserted.
     995        1784 :     if (Subtarget->hasDataBarrier())
     996         190 :       InsertFencesForAtomic = true;
     997             : 
     998             :     setOperationAction(ISD::ATOMIC_FENCE,   MVT::Other,
     999             :                        Subtarget->hasAnyDataBarrier() ? Custom : Expand);
    1000             : 
    1001             :     // Set them all for expansion, which will force libcalls.
    1002             :     setOperationAction(ISD::ATOMIC_CMP_SWAP,  MVT::i32, Expand);
    1003             :     setOperationAction(ISD::ATOMIC_SWAP,      MVT::i32, Expand);
    1004             :     setOperationAction(ISD::ATOMIC_LOAD_ADD,  MVT::i32, Expand);
    1005             :     setOperationAction(ISD::ATOMIC_LOAD_SUB,  MVT::i32, Expand);
    1006             :     setOperationAction(ISD::ATOMIC_LOAD_AND,  MVT::i32, Expand);
    1007             :     setOperationAction(ISD::ATOMIC_LOAD_OR,   MVT::i32, Expand);
    1008             :     setOperationAction(ISD::ATOMIC_LOAD_XOR,  MVT::i32, Expand);
    1009             :     setOperationAction(ISD::ATOMIC_LOAD_NAND, MVT::i32, Expand);
    1010             :     setOperationAction(ISD::ATOMIC_LOAD_MIN, MVT::i32, Expand);
    1011             :     setOperationAction(ISD::ATOMIC_LOAD_MAX, MVT::i32, Expand);
    1012             :     setOperationAction(ISD::ATOMIC_LOAD_UMIN, MVT::i32, Expand);
    1013             :     setOperationAction(ISD::ATOMIC_LOAD_UMAX, MVT::i32, Expand);
    1014             :     // Mark ATOMIC_LOAD and ATOMIC_STORE custom so we can handle the
    1015             :     // Unordered/Monotonic case.
    1016        1784 :     if (!InsertFencesForAtomic) {
    1017             :       setOperationAction(ISD::ATOMIC_LOAD, MVT::i32, Custom);
    1018             :       setOperationAction(ISD::ATOMIC_STORE, MVT::i32, Custom);
    1019             :     }
    1020             :   }
    1021             : 
    1022             :   setOperationAction(ISD::PREFETCH,         MVT::Other, Custom);
    1023             : 
    1024             :   // Requires SXTB/SXTH, available on v6 and up in both ARM and Thumb modes.
    1025        4835 :   if (!Subtarget->hasV6Ops()) {
    1026             :     setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i16, Expand);
    1027             :     setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i8,  Expand);
    1028             :   }
    1029             :   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1, Expand);
    1030             : 
    1031        4835 :   if (!Subtarget->useSoftFloat() && Subtarget->hasVFP2() &&
    1032        2905 :       !Subtarget->isThumb1Only()) {
    1033             :     // Turn f64->i64 into VMOVRRD, i64 -> f64 to VMOVDRR
    1034             :     // iff target supports vfp2.
    1035             :     setOperationAction(ISD::BITCAST, MVT::i64, Custom);
    1036             :     setOperationAction(ISD::FLT_ROUNDS_, MVT::i32, Custom);
    1037             :   }
    1038             : 
    1039             :   // We want to custom lower some of our intrinsics.
    1040             :   setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
    1041             :   setOperationAction(ISD::EH_SJLJ_SETJMP, MVT::i32, Custom);
    1042             :   setOperationAction(ISD::EH_SJLJ_LONGJMP, MVT::Other, Custom);
    1043             :   setOperationAction(ISD::EH_SJLJ_SETUP_DISPATCH, MVT::Other, Custom);
    1044        4835 :   if (Subtarget->useSjLjEH())
    1045             :     setLibcallName(RTLIB::UNWIND_RESUME, "_Unwind_SjLj_Resume");
    1046             : 
    1047             :   setOperationAction(ISD::SETCC,     MVT::i32, Expand);
    1048             :   setOperationAction(ISD::SETCC,     MVT::f32, Expand);
    1049             :   setOperationAction(ISD::SETCC,     MVT::f64, Expand);
    1050             :   setOperationAction(ISD::SELECT,    MVT::i32, Custom);
    1051             :   setOperationAction(ISD::SELECT,    MVT::f32, Custom);
    1052             :   setOperationAction(ISD::SELECT,    MVT::f64, Custom);
    1053             :   setOperationAction(ISD::SELECT_CC, MVT::i32, Custom);
    1054             :   setOperationAction(ISD::SELECT_CC, MVT::f32, Custom);
    1055             :   setOperationAction(ISD::SELECT_CC, MVT::f64, Custom);
    1056        4835 :   if (Subtarget->hasFullFP16()) {
    1057             :     setOperationAction(ISD::SETCC,     MVT::f16, Expand);
    1058             :     setOperationAction(ISD::SELECT,    MVT::f16, Custom);
    1059             :     setOperationAction(ISD::SELECT_CC, MVT::f16, Custom);
    1060             :   }
    1061             : 
    1062             :   setOperationAction(ISD::SETCCCARRY, MVT::i32, Custom);
    1063             : 
    1064             :   setOperationAction(ISD::BRCOND,    MVT::Other, Custom);
    1065             :   setOperationAction(ISD::BR_CC,     MVT::i32,   Custom);
    1066        4835 :   if (Subtarget->hasFullFP16())
    1067             :       setOperationAction(ISD::BR_CC, MVT::f16,   Custom);
    1068             :   setOperationAction(ISD::BR_CC,     MVT::f32,   Custom);
    1069             :   setOperationAction(ISD::BR_CC,     MVT::f64,   Custom);
    1070             :   setOperationAction(ISD::BR_JT,     MVT::Other, Custom);
    1071             : 
    1072             :   // We don't support sin/cos/fmod/copysign/pow
    1073             :   setOperationAction(ISD::FSIN,      MVT::f64, Expand);
    1074             :   setOperationAction(ISD::FSIN,      MVT::f32, Expand);
    1075             :   setOperationAction(ISD::FCOS,      MVT::f32, Expand);
    1076             :   setOperationAction(ISD::FCOS,      MVT::f64, Expand);
    1077             :   setOperationAction(ISD::FSINCOS,   MVT::f64, Expand);
    1078             :   setOperationAction(ISD::FSINCOS,   MVT::f32, Expand);
    1079             :   setOperationAction(ISD::FREM,      MVT::f64, Expand);
    1080             :   setOperationAction(ISD::FREM,      MVT::f32, Expand);
    1081        4835 :   if (!Subtarget->useSoftFloat() && Subtarget->hasVFP2() &&
    1082        2905 :       !Subtarget->isThumb1Only()) {
    1083             :     setOperationAction(ISD::FCOPYSIGN, MVT::f64, Custom);
    1084             :     setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
    1085             :   }
    1086             :   setOperationAction(ISD::FPOW,      MVT::f64, Expand);
    1087             :   setOperationAction(ISD::FPOW,      MVT::f32, Expand);
    1088             : 
    1089        4835 :   if (!Subtarget->hasVFP4()) {
    1090             :     setOperationAction(ISD::FMA, MVT::f64, Expand);
    1091             :     setOperationAction(ISD::FMA, MVT::f32, Expand);
    1092             :   }
    1093             : 
    1094             :   // Various VFP goodness
    1095        4835 :   if (!Subtarget->useSoftFloat() && !Subtarget->isThumb1Only()) {
    1096             :     // FP-ARMv8 adds f64 <-> f16 conversion. Before that it should be expanded.
    1097        4326 :     if (!Subtarget->hasFPARMv8() || Subtarget->isFPOnlySP()) {
    1098             :       setOperationAction(ISD::FP16_TO_FP, MVT::f64, Expand);
    1099             :       setOperationAction(ISD::FP_TO_FP16, MVT::f64, Expand);
    1100             :     }
    1101             : 
    1102             :     // fp16 is a special v7 extension that adds f16 <-> f32 conversions.
    1103        4326 :     if (!Subtarget->hasFP16()) {
    1104             :       setOperationAction(ISD::FP16_TO_FP, MVT::f32, Expand);
    1105             :       setOperationAction(ISD::FP_TO_FP16, MVT::f32, Expand);
    1106             :     }
    1107             :   }
    1108             : 
    1109             :   // Use __sincos_stret if available.
    1110        4907 :   if (getLibcallName(RTLIB::SINCOS_STRET_F32) != nullptr &&
    1111             :       getLibcallName(RTLIB::SINCOS_STRET_F64) != nullptr) {
    1112             :     setOperationAction(ISD::FSINCOS, MVT::f64, Custom);
    1113             :     setOperationAction(ISD::FSINCOS, MVT::f32, Custom);
    1114             :   }
    1115             : 
    1116             :   // FP-ARMv8 implements a lot of rounding-like FP operations.
    1117        4835 :   if (Subtarget->hasFPARMv8()) {
    1118             :     setOperationAction(ISD::FFLOOR, MVT::f32, Legal);
    1119             :     setOperationAction(ISD::FCEIL, MVT::f32, Legal);
    1120             :     setOperationAction(ISD::FROUND, MVT::f32, Legal);
    1121             :     setOperationAction(ISD::FTRUNC, MVT::f32, Legal);
    1122             :     setOperationAction(ISD::FNEARBYINT, MVT::f32, Legal);
    1123             :     setOperationAction(ISD::FRINT, MVT::f32, Legal);
    1124             :     setOperationAction(ISD::FMINNUM, MVT::f32, Legal);
    1125             :     setOperationAction(ISD::FMAXNUM, MVT::f32, Legal);
    1126             :     setOperationAction(ISD::FMINNUM, MVT::v2f32, Legal);
    1127             :     setOperationAction(ISD::FMAXNUM, MVT::v2f32, Legal);
    1128             :     setOperationAction(ISD::FMINNUM, MVT::v4f32, Legal);
    1129             :     setOperationAction(ISD::FMAXNUM, MVT::v4f32, Legal);
    1130             : 
    1131         393 :     if (!Subtarget->isFPOnlySP()) {
    1132             :       setOperationAction(ISD::FFLOOR, MVT::f64, Legal);
    1133             :       setOperationAction(ISD::FCEIL, MVT::f64, Legal);
    1134             :       setOperationAction(ISD::FROUND, MVT::f64, Legal);
    1135             :       setOperationAction(ISD::FTRUNC, MVT::f64, Legal);
    1136             :       setOperationAction(ISD::FNEARBYINT, MVT::f64, Legal);
    1137             :       setOperationAction(ISD::FRINT, MVT::f64, Legal);
    1138             :       setOperationAction(ISD::FMINNUM, MVT::f64, Legal);
    1139             :       setOperationAction(ISD::FMAXNUM, MVT::f64, Legal);
    1140             :     }
    1141             :   }
    1142             : 
    1143        4835 :   if (Subtarget->hasNEON()) {
    1144             :     // vmin and vmax aren't available in a scalar form, so we use
    1145             :     // a NEON instruction with an undef lane instead.
    1146             :     setOperationAction(ISD::FMINNAN, MVT::f16, Legal);
    1147             :     setOperationAction(ISD::FMAXNAN, MVT::f16, Legal);
    1148             :     setOperationAction(ISD::FMINNAN, MVT::f32, Legal);
    1149             :     setOperationAction(ISD::FMAXNAN, MVT::f32, Legal);
    1150             :     setOperationAction(ISD::FMINNAN, MVT::v2f32, Legal);
    1151             :     setOperationAction(ISD::FMAXNAN, MVT::v2f32, Legal);
    1152             :     setOperationAction(ISD::FMINNAN, MVT::v4f32, Legal);
    1153             :     setOperationAction(ISD::FMAXNAN, MVT::v4f32, Legal);
    1154             :   }
    1155             : 
    1156             :   // We have target-specific dag combine patterns for the following nodes:
    1157             :   // ARMISD::VMOVRRD  - No need to call setTargetDAGCombine
    1158             :   setTargetDAGCombine(ISD::ADD);
    1159             :   setTargetDAGCombine(ISD::SUB);
    1160             :   setTargetDAGCombine(ISD::MUL);
    1161             :   setTargetDAGCombine(ISD::AND);
    1162             :   setTargetDAGCombine(ISD::OR);
    1163             :   setTargetDAGCombine(ISD::XOR);
    1164             : 
    1165        4835 :   if (Subtarget->hasV6Ops())
    1166             :     setTargetDAGCombine(ISD::SRL);
    1167             : 
    1168             :   setStackPointerRegisterToSaveRestore(ARM::SP);
    1169             : 
    1170        9161 :   if (Subtarget->useSoftFloat() || Subtarget->isThumb1Only() ||
    1171        4326 :       !Subtarget->hasVFP2())
    1172             :     setSchedulingPreference(Sched::RegPressure);
    1173             :   else
    1174             :     setSchedulingPreference(Sched::Hybrid);
    1175             : 
    1176             :   //// temporary - rewrite interface to use type
    1177        4835 :   MaxStoresPerMemset = 8;
    1178        4835 :   MaxStoresPerMemsetOptSize = 4;
    1179        4835 :   MaxStoresPerMemcpy = 4; // For @llvm.memcpy -> sequence of stores
    1180        4835 :   MaxStoresPerMemcpyOptSize = 2;
    1181        4835 :   MaxStoresPerMemmove = 4; // For @llvm.memmove -> sequence of stores
    1182        4835 :   MaxStoresPerMemmoveOptSize = 2;
    1183             : 
    1184             :   // On ARM arguments smaller than 4 bytes are extended, so all arguments
    1185             :   // are at least 4 bytes aligned.
    1186             :   setMinStackArgumentAlignment(4);
    1187             : 
    1188             :   // Prefer likely predicted branches to selects on out-of-order cores.
    1189        9670 :   PredictableSelectIsExpensive = Subtarget->getSchedModel().isOutOfOrder();
    1190             : 
    1191        4835 :   setMinFunctionAlignment(Subtarget->isThumb() ? 1 : 2);
    1192        4835 : }
    1193             : 
    1194        3962 : bool ARMTargetLowering::useSoftFloat() const {
    1195        3962 :   return Subtarget->useSoftFloat();
    1196             : }
    1197             : 
    1198             : // FIXME: It might make sense to define the representative register class as the
    1199             : // nearest super-register that has a non-null superset. For example, DPR_VFP2 is
    1200             : // a super-register of SPR, and DPR is a superset if DPR_VFP2. Consequently,
    1201             : // SPR's representative would be DPR_VFP2. This should work well if register
    1202             : // pressure tracking were modified such that a register use would increment the
    1203             : // pressure of the register class's representative and all of it's super
    1204             : // classes' representatives transitively. We have not implemented this because
    1205             : // of the difficulty prior to coalescing of modeling operand register classes
    1206             : // due to the common occurrence of cross class copies and subregister insertions
    1207             : // and extractions.
    1208             : std::pair<const TargetRegisterClass *, uint8_t>
    1209      551190 : ARMTargetLowering::findRepresentativeClass(const TargetRegisterInfo *TRI,
    1210             :                                            MVT VT) const {
    1211             :   const TargetRegisterClass *RRC = nullptr;
    1212             :   uint8_t Cost = 1;
    1213      551190 :   switch (VT.SimpleTy) {
    1214      478665 :   default:
    1215      478665 :     return TargetLowering::findRepresentativeClass(TRI, VT);
    1216             :   // Use DPR as representative register class for all floating point
    1217             :   // and vector types. Since there are 32 SPR registers and 32 DPR registers so
    1218             :   // the cost is 1 for both f32 and f64.
    1219       33845 :   case MVT::f32: case MVT::f64: case MVT::v8i8: case MVT::v4i16:
    1220             :   case MVT::v2i32: case MVT::v1i64: case MVT::v2f32:
    1221             :     RRC = &ARM::DPRRegClass;
    1222             :     // When NEON is used for SP, only half of the register file is available
    1223             :     // because operations that define both SP and DP results will be constrained
    1224             :     // to the VFP2 class (D0-D15). We currently model this constraint prior to
    1225             :     // coalescing by double-counting the SP regs. See the FIXME above.
    1226       33845 :     if (Subtarget->useNEONForSinglePrecisionFP())
    1227             :       Cost = 2;
    1228             :     break;
    1229             :   case MVT::v16i8: case MVT::v8i16: case MVT::v4i32: case MVT::v2i64:
    1230             :   case MVT::v4f32: case MVT::v2f64:
    1231             :     RRC = &ARM::DPRRegClass;
    1232             :     Cost = 2;
    1233             :     break;
    1234        4835 :   case MVT::v4i64:
    1235             :     RRC = &ARM::DPRRegClass;
    1236             :     Cost = 4;
    1237        4835 :     break;
    1238        4835 :   case MVT::v8i64:
    1239             :     RRC = &ARM::DPRRegClass;
    1240             :     Cost = 8;
    1241        4835 :     break;
    1242             :   }
    1243             :   return std::make_pair(RRC, Cost);
    1244             : }
    1245             : 
    1246           0 : const char *ARMTargetLowering::getTargetNodeName(unsigned Opcode) const {
    1247           0 :   switch ((ARMISD::NodeType)Opcode) {
    1248             :   case ARMISD::FIRST_NUMBER:  break;
    1249             :   case ARMISD::Wrapper:       return "ARMISD::Wrapper";
    1250           0 :   case ARMISD::WrapperPIC:    return "ARMISD::WrapperPIC";
    1251           0 :   case ARMISD::WrapperJT:     return "ARMISD::WrapperJT";
    1252           0 :   case ARMISD::COPY_STRUCT_BYVAL: return "ARMISD::COPY_STRUCT_BYVAL";
    1253           0 :   case ARMISD::CALL:          return "ARMISD::CALL";
    1254           0 :   case ARMISD::CALL_PRED:     return "ARMISD::CALL_PRED";
    1255           0 :   case ARMISD::CALL_NOLINK:   return "ARMISD::CALL_NOLINK";
    1256           0 :   case ARMISD::BRCOND:        return "ARMISD::BRCOND";
    1257           0 :   case ARMISD::BR_JT:         return "ARMISD::BR_JT";
    1258           0 :   case ARMISD::BR2_JT:        return "ARMISD::BR2_JT";
    1259           0 :   case ARMISD::RET_FLAG:      return "ARMISD::RET_FLAG";
    1260           0 :   case ARMISD::INTRET_FLAG:   return "ARMISD::INTRET_FLAG";
    1261           0 :   case ARMISD::PIC_ADD:       return "ARMISD::PIC_ADD";
    1262           0 :   case ARMISD::CMP:           return "ARMISD::CMP";
    1263           0 :   case ARMISD::CMN:           return "ARMISD::CMN";
    1264           0 :   case ARMISD::CMPZ:          return "ARMISD::CMPZ";
    1265           0 :   case ARMISD::CMPFP:         return "ARMISD::CMPFP";
    1266           0 :   case ARMISD::CMPFPw0:       return "ARMISD::CMPFPw0";
    1267           0 :   case ARMISD::BCC_i64:       return "ARMISD::BCC_i64";
    1268           0 :   case ARMISD::FMSTAT:        return "ARMISD::FMSTAT";
    1269             : 
    1270           0 :   case ARMISD::CMOV:          return "ARMISD::CMOV";
    1271             : 
    1272           0 :   case ARMISD::SSAT:          return "ARMISD::SSAT";
    1273           0 :   case ARMISD::USAT:          return "ARMISD::USAT";
    1274             : 
    1275           0 :   case ARMISD::SRL_FLAG:      return "ARMISD::SRL_FLAG";
    1276           0 :   case ARMISD::SRA_FLAG:      return "ARMISD::SRA_FLAG";
    1277           0 :   case ARMISD::RRX:           return "ARMISD::RRX";
    1278             : 
    1279           0 :   case ARMISD::ADDC:          return "ARMISD::ADDC";
    1280           0 :   case ARMISD::ADDE:          return "ARMISD::ADDE";
    1281           0 :   case ARMISD::SUBC:          return "ARMISD::SUBC";
    1282           0 :   case ARMISD::SUBE:          return "ARMISD::SUBE";
    1283             : 
    1284           0 :   case ARMISD::VMOVRRD:       return "ARMISD::VMOVRRD";
    1285           0 :   case ARMISD::VMOVDRR:       return "ARMISD::VMOVDRR";
    1286           0 :   case ARMISD::VMOVhr:        return "ARMISD::VMOVhr";
    1287           0 :   case ARMISD::VMOVrh:        return "ARMISD::VMOVrh";
    1288           0 :   case ARMISD::VMOVSR:        return "ARMISD::VMOVSR";
    1289             : 
    1290           0 :   case ARMISD::EH_SJLJ_SETJMP: return "ARMISD::EH_SJLJ_SETJMP";
    1291           0 :   case ARMISD::EH_SJLJ_LONGJMP: return "ARMISD::EH_SJLJ_LONGJMP";
    1292           0 :   case ARMISD::EH_SJLJ_SETUP_DISPATCH: return "ARMISD::EH_SJLJ_SETUP_DISPATCH";
    1293             : 
    1294           0 :   case ARMISD::TC_RETURN:     return "ARMISD::TC_RETURN";
    1295             : 
    1296           0 :   case ARMISD::THREAD_POINTER:return "ARMISD::THREAD_POINTER";
    1297             : 
    1298           0 :   case ARMISD::DYN_ALLOC:     return "ARMISD::DYN_ALLOC";
    1299             : 
    1300           0 :   case ARMISD::MEMBARRIER_MCR: return "ARMISD::MEMBARRIER_MCR";
    1301             : 
    1302           0 :   case ARMISD::PRELOAD:       return "ARMISD::PRELOAD";
    1303             : 
    1304           0 :   case ARMISD::WIN__CHKSTK:   return "ARMISD::WIN__CHKSTK";
    1305           0 :   case ARMISD::WIN__DBZCHK:   return "ARMISD::WIN__DBZCHK";
    1306             : 
    1307           0 :   case ARMISD::VCEQ:          return "ARMISD::VCEQ";
    1308           0 :   case ARMISD::VCEQZ:         return "ARMISD::VCEQZ";
    1309           0 :   case ARMISD::VCGE:          return "ARMISD::VCGE";
    1310           0 :   case ARMISD::VCGEZ:         return "ARMISD::VCGEZ";
    1311           0 :   case ARMISD::VCLEZ:         return "ARMISD::VCLEZ";
    1312           0 :   case ARMISD::VCGEU:         return "ARMISD::VCGEU";
    1313           0 :   case ARMISD::VCGT:          return "ARMISD::VCGT";
    1314           0 :   case ARMISD::VCGTZ:         return "ARMISD::VCGTZ";
    1315           0 :   case ARMISD::VCLTZ:         return "ARMISD::VCLTZ";
    1316           0 :   case ARMISD::VCGTU:         return "ARMISD::VCGTU";
    1317           0 :   case ARMISD::VTST:          return "ARMISD::VTST";
    1318             : 
    1319           0 :   case ARMISD::VSHL:          return "ARMISD::VSHL";
    1320           0 :   case ARMISD::VSHRs:         return "ARMISD::VSHRs";
    1321           0 :   case ARMISD::VSHRu:         return "ARMISD::VSHRu";
    1322           0 :   case ARMISD::VRSHRs:        return "ARMISD::VRSHRs";
    1323           0 :   case ARMISD::VRSHRu:        return "ARMISD::VRSHRu";
    1324           0 :   case ARMISD::VRSHRN:        return "ARMISD::VRSHRN";
    1325           0 :   case ARMISD::VQSHLs:        return "ARMISD::VQSHLs";
    1326           0 :   case ARMISD::VQSHLu:        return "ARMISD::VQSHLu";
    1327           0 :   case ARMISD::VQSHLsu:       return "ARMISD::VQSHLsu";
    1328           0 :   case ARMISD::VQSHRNs:       return "ARMISD::VQSHRNs";
    1329           0 :   case ARMISD::VQSHRNu:       return "ARMISD::VQSHRNu";
    1330           0 :   case ARMISD::VQSHRNsu:      return "ARMISD::VQSHRNsu";
    1331           0 :   case ARMISD::VQRSHRNs:      return "ARMISD::VQRSHRNs";
    1332           0 :   case ARMISD::VQRSHRNu:      return "ARMISD::VQRSHRNu";
    1333           0 :   case ARMISD::VQRSHRNsu:     return "ARMISD::VQRSHRNsu";
    1334           0 :   case ARMISD::VSLI:          return "ARMISD::VSLI";
    1335           0 :   case ARMISD::VSRI:          return "ARMISD::VSRI";
    1336           0 :   case ARMISD::VGETLANEu:     return "ARMISD::VGETLANEu";
    1337           0 :   case ARMISD::VGETLANEs:     return "ARMISD::VGETLANEs";
    1338           0 :   case ARMISD::VMOVIMM:       return "ARMISD::VMOVIMM";
    1339           0 :   case ARMISD::VMVNIMM:       return "ARMISD::VMVNIMM";
    1340           0 :   case ARMISD::VMOVFPIMM:     return "ARMISD::VMOVFPIMM";
    1341           0 :   case ARMISD::VDUP:          return "ARMISD::VDUP";
    1342           0 :   case ARMISD::VDUPLANE:      return "ARMISD::VDUPLANE";
    1343           0 :   case ARMISD::VEXT:          return "ARMISD::VEXT";
    1344           0 :   case ARMISD::VREV64:        return "ARMISD::VREV64";
    1345           0 :   case ARMISD::VREV32:        return "ARMISD::VREV32";
    1346           0 :   case ARMISD::VREV16:        return "ARMISD::VREV16";
    1347           0 :   case ARMISD::VZIP:          return "ARMISD::VZIP";
    1348           0 :   case ARMISD::VUZP:          return "ARMISD::VUZP";
    1349           0 :   case ARMISD::VTRN:          return "ARMISD::VTRN";
    1350           0 :   case ARMISD::VTBL1:         return "ARMISD::VTBL1";
    1351           0 :   case ARMISD::VTBL2:         return "ARMISD::VTBL2";
    1352           0 :   case ARMISD::VMULLs:        return "ARMISD::VMULLs";
    1353           0 :   case ARMISD::VMULLu:        return "ARMISD::VMULLu";
    1354           0 :   case ARMISD::UMAAL:         return "ARMISD::UMAAL";
    1355           0 :   case ARMISD::UMLAL:         return "ARMISD::UMLAL";
    1356           0 :   case ARMISD::SMLAL:         return "ARMISD::SMLAL";
    1357           0 :   case ARMISD::SMLALBB:       return "ARMISD::SMLALBB";
    1358           0 :   case ARMISD::SMLALBT:       return "ARMISD::SMLALBT";
    1359           0 :   case ARMISD::SMLALTB:       return "ARMISD::SMLALTB";
    1360           0 :   case ARMISD::SMLALTT:       return "ARMISD::SMLALTT";
    1361           0 :   case ARMISD::SMULWB:        return "ARMISD::SMULWB";
    1362           0 :   case ARMISD::SMULWT:        return "ARMISD::SMULWT";
    1363           0 :   case ARMISD::SMLALD:        return "ARMISD::SMLALD";
    1364           0 :   case ARMISD::SMLALDX:       return "ARMISD::SMLALDX";
    1365           0 :   case ARMISD::SMLSLD:        return "ARMISD::SMLSLD";
    1366           0 :   case ARMISD::SMLSLDX:       return "ARMISD::SMLSLDX";
    1367           0 :   case ARMISD::SMMLAR:        return "ARMISD::SMMLAR";
    1368           0 :   case ARMISD::SMMLSR:        return "ARMISD::SMMLSR";
    1369           0 :   case ARMISD::BUILD_VECTOR:  return "ARMISD::BUILD_VECTOR";
    1370           0 :   case ARMISD::BFI:           return "ARMISD::BFI";
    1371           0 :   case ARMISD::VORRIMM:       return "ARMISD::VORRIMM";
    1372           0 :   case ARMISD::VBICIMM:       return "ARMISD::VBICIMM";
    1373           0 :   case ARMISD::VBSL:          return "ARMISD::VBSL";
    1374           0 :   case ARMISD::MEMCPY:        return "ARMISD::MEMCPY";
    1375           0 :   case ARMISD::VLD1DUP:       return "ARMISD::VLD1DUP";
    1376           0 :   case ARMISD::VLD2DUP:       return "ARMISD::VLD2DUP";
    1377           0 :   case ARMISD::VLD3DUP:       return "ARMISD::VLD3DUP";
    1378           0 :   case ARMISD::VLD4DUP:       return "ARMISD::VLD4DUP";
    1379           0 :   case ARMISD::VLD1_UPD:      return "ARMISD::VLD1_UPD";
    1380           0 :   case ARMISD::VLD2_UPD:      return "ARMISD::VLD2_UPD";
    1381           0 :   case ARMISD::VLD3_UPD:      return "ARMISD::VLD3_UPD";
    1382           0 :   case ARMISD::VLD4_UPD:      return "ARMISD::VLD4_UPD";
    1383           0 :   case ARMISD::VLD2LN_UPD:    return "ARMISD::VLD2LN_UPD";
    1384           0 :   case ARMISD::VLD3LN_UPD:    return "ARMISD::VLD3LN_UPD";
    1385           0 :   case ARMISD::VLD4LN_UPD:    return "ARMISD::VLD4LN_UPD";
    1386           0 :   case ARMISD::VLD1DUP_UPD:   return "ARMISD::VLD1DUP_UPD";
    1387           0 :   case ARMISD::VLD2DUP_UPD:   return "ARMISD::VLD2DUP_UPD";
    1388           0 :   case ARMISD::VLD3DUP_UPD:   return "ARMISD::VLD3DUP_UPD";
    1389           0 :   case ARMISD::VLD4DUP_UPD:   return "ARMISD::VLD4DUP_UPD";
    1390           0 :   case ARMISD::VST1_UPD:      return "ARMISD::VST1_UPD";
    1391           0 :   case ARMISD::VST2_UPD:      return "ARMISD::VST2_UPD";
    1392           0 :   case ARMISD::VST3_UPD:      return "ARMISD::VST3_UPD";
    1393           0 :   case ARMISD::VST4_UPD:      return "ARMISD::VST4_UPD";
    1394           0 :   case ARMISD::VST2LN_UPD:    return "ARMISD::VST2LN_UPD";
    1395           0 :   case ARMISD::VST3LN_UPD:    return "ARMISD::VST3LN_UPD";
    1396           0 :   case ARMISD::VST4LN_UPD:    return "ARMISD::VST4LN_UPD";
    1397             :   }
    1398           0 :   return nullptr;
    1399             : }
    1400             : 
    1401        9085 : EVT ARMTargetLowering::getSetCCResultType(const DataLayout &DL, LLVMContext &,
    1402             :                                           EVT VT) const {
    1403        9085 :   if (!VT.isVector())
    1404        8918 :     return getPointerTy(DL);
    1405         167 :   return VT.changeVectorElementTypeToInteger();
    1406             : }
    1407             : 
    1408             : /// getRegClassFor - Return the register class that should be used for the
    1409             : /// specified value type.
    1410      208651 : const TargetRegisterClass *ARMTargetLowering::getRegClassFor(MVT VT) const {
    1411             :   // Map v4i64 to QQ registers but do not make the type legal. Similarly map
    1412             :   // v8i64 to QQQQ registers. v4i64 and v8i64 are only used for REG_SEQUENCE to
    1413             :   // load / store 4 to 8 consecutive D registers.
    1414      208651 :   if (Subtarget->hasNEON()) {
    1415      134953 :     if (VT == MVT::v4i64)
    1416             :       return &ARM::QQPRRegClass;
    1417      134953 :     if (VT == MVT::v8i64)
    1418             :       return &ARM::QQQQPRRegClass;
    1419             :   }
    1420      208617 :   return TargetLowering::getRegClassFor(VT);
    1421             : }
    1422             : 
    1423             : // memcpy, and other memory intrinsics, typically tries to use LDM/STM if the
    1424             : // source/dest is aligned and the copy size is large enough. We therefore want
    1425             : // to align such objects passed to memory intrinsics.
    1426       10386 : bool ARMTargetLowering::shouldAlignPointerArgs(CallInst *CI, unsigned &MinSize,
    1427             :                                                unsigned &PrefAlign) const {
    1428       10386 :   if (!isa<MemIntrinsic>(CI))
    1429             :     return false;
    1430         664 :   MinSize = 8;
    1431             :   // On ARM11 onwards (excluding M class) 8-byte aligned LDM is typically 1
    1432             :   // cycle faster than 4-byte aligned LDM.
    1433         664 :   PrefAlign = (Subtarget->hasV6Ops() && !Subtarget->isMClass() ? 8 : 4);
    1434         664 :   return true;
    1435             : }
    1436             : 
    1437             : // Create a fast isel object.
    1438             : FastISel *
    1439        1217 : ARMTargetLowering::createFastISel(FunctionLoweringInfo &funcInfo,
    1440             :                                   const TargetLibraryInfo *libInfo) const {
    1441        1217 :   return ARM::createFastISel(funcInfo, libInfo);
    1442             : }
    1443             : 
    1444      134990 : Sched::Preference ARMTargetLowering::getSchedulingPreference(SDNode *N) const {
    1445      134990 :   unsigned NumVals = N->getNumValues();
    1446      134990 :   if (!NumVals)
    1447             :     return Sched::RegPressure;
    1448             : 
    1449      492634 :   for (unsigned i = 0; i != NumVals; ++i) {
    1450      408156 :     EVT VT = N->getValueType(i);
    1451      104809 :     if (VT == MVT::Glue || VT == MVT::Other)
    1452      104809 :       continue;
    1453      178186 :     if (VT.isFloatingPoint() || VT.isVector())
    1454       25256 :       return Sched::ILP;
    1455             :   }
    1456             : 
    1457      109734 :   if (!N->isMachineOpcode())
    1458             :     return Sched::RegPressure;
    1459             : 
    1460             :   // Load are scheduled for latency even if there instruction itinerary
    1461             :   // is not available.
    1462       70228 :   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
    1463      140456 :   const MCInstrDesc &MCID = TII->get(N->getMachineOpcode());
    1464             : 
    1465       70228 :   if (MCID.getNumDefs() == 0)
    1466             :     return Sched::RegPressure;
    1467       62844 :   if (!Itins->isEmpty() &&
    1468       31647 :       Itins->getOperandCycle(MCID.getSchedClass(), 0) > 2)
    1469             :     return Sched::ILP;
    1470             : 
    1471             :   return Sched::RegPressure;
    1472             : }
    1473             : 
    1474             : //===----------------------------------------------------------------------===//
    1475             : // Lowering Code
    1476             : //===----------------------------------------------------------------------===//
    1477             : 
    1478        1463 : static bool isSRL16(const SDValue &Op) {
    1479        2926 :   if (Op.getOpcode() != ISD::SRL)
    1480             :     return false;
    1481             :   if (auto Const = dyn_cast<ConstantSDNode>(Op.getOperand(1)))
    1482         118 :     return Const->getZExtValue() == 16;
    1483             :   return false;
    1484             : }
    1485             : 
    1486         228 : static bool isSRA16(const SDValue &Op) {
    1487         456 :   if (Op.getOpcode() != ISD::SRA)
    1488             :     return false;
    1489             :   if (auto Const = dyn_cast<ConstantSDNode>(Op.getOperand(1)))
    1490         282 :     return Const->getZExtValue() == 16;
    1491             :   return false;
    1492             : }
    1493             : 
    1494         111 : static bool isSHL16(const SDValue &Op) {
    1495         222 :   if (Op.getOpcode() != ISD::SHL)
    1496             :     return false;
    1497             :   if (auto Const = dyn_cast<ConstantSDNode>(Op.getOperand(1)))
    1498          64 :     return Const->getZExtValue() == 16;
    1499             :   return false;
    1500             : }
    1501             : 
    1502             : // Check for a signed 16-bit value. We special case SRA because it makes it
    1503             : // more simple when also looking for SRAs that aren't sign extending a
    1504             : // smaller value. Without the check, we'd need to take extra care with
    1505             : // checking order for some operations.
    1506         167 : static bool isS16(const SDValue &Op, SelectionDAG &DAG) {
    1507         167 :   if (isSRA16(Op))
    1508         160 :     return isSHL16(Op.getOperand(0));
    1509          87 :   return DAG.ComputeNumSignBits(Op) == 17;
    1510             : }
    1511             : 
    1512             : /// IntCCToARMCC - Convert a DAG integer condition code to an ARM CC
    1513        2955 : static ARMCC::CondCodes IntCCToARMCC(ISD::CondCode CC) {
    1514        2955 :   switch (CC) {
    1515           0 :   default: llvm_unreachable("Unknown condition code!");
    1516             :   case ISD::SETNE:  return ARMCC::NE;
    1517         848 :   case ISD::SETEQ:  return ARMCC::EQ;
    1518         143 :   case ISD::SETGT:  return ARMCC::GT;
    1519         120 :   case ISD::SETGE:  return ARMCC::GE;
    1520         266 :   case ISD::SETLT:  return ARMCC::LT;
    1521          41 :   case ISD::SETLE:  return ARMCC::LE;
    1522          92 :   case ISD::SETUGT: return ARMCC::HI;
    1523          22 :   case ISD::SETUGE: return ARMCC::HS;
    1524          55 :   case ISD::SETULT: return ARMCC::LO;
    1525          42 :   case ISD::SETULE: return ARMCC::LS;
    1526             :   }
    1527             : }
    1528             : 
    1529             : /// FPCCToARMCC - Convert a DAG fp condition code to an ARM CC.
    1530         570 : static void FPCCToARMCC(ISD::CondCode CC, ARMCC::CondCodes &CondCode,
    1531             :                         ARMCC::CondCodes &CondCode2, bool &InvalidOnQNaN) {
    1532         570 :   CondCode2 = ARMCC::AL;
    1533         570 :   InvalidOnQNaN = true;
    1534         570 :   switch (CC) {
    1535           0 :   default: llvm_unreachable("Unknown FP condition!");
    1536          47 :   case ISD::SETEQ:
    1537             :   case ISD::SETOEQ:
    1538          47 :     CondCode = ARMCC::EQ;
    1539          47 :     InvalidOnQNaN = false;
    1540          47 :     break;
    1541          61 :   case ISD::SETGT:
    1542          61 :   case ISD::SETOGT: CondCode = ARMCC::GT; break;
    1543          44 :   case ISD::SETGE:
    1544          44 :   case ISD::SETOGE: CondCode = ARMCC::GE; break;
    1545         113 :   case ISD::SETOLT: CondCode = ARMCC::MI; break;
    1546          40 :   case ISD::SETOLE: CondCode = ARMCC::LS; break;
    1547           7 :   case ISD::SETONE:
    1548           7 :     CondCode = ARMCC::MI;
    1549           7 :     CondCode2 = ARMCC::GT;
    1550           7 :     InvalidOnQNaN = false;
    1551           7 :     break;
    1552           7 :   case ISD::SETO:   CondCode = ARMCC::VC; break;
    1553          17 :   case ISD::SETUO:  CondCode = ARMCC::VS; break;
    1554          24 :   case ISD::SETUEQ:
    1555          24 :     CondCode = ARMCC::EQ;
    1556          24 :     CondCode2 = ARMCC::VS;
    1557          24 :     InvalidOnQNaN = false;
    1558          24 :     break;
    1559          30 :   case ISD::SETUGT: CondCode = ARMCC::HI; break;
    1560          38 :   case ISD::SETUGE: CondCode = ARMCC::PL; break;
    1561          31 :   case ISD::SETLT:
    1562          31 :   case ISD::SETULT: CondCode = ARMCC::LT; break;
    1563          51 :   case ISD::SETLE:
    1564          51 :   case ISD::SETULE: CondCode = ARMCC::LE; break;
    1565          60 :   case ISD::SETNE:
    1566             :   case ISD::SETUNE:
    1567          60 :     CondCode = ARMCC::NE;
    1568          60 :     InvalidOnQNaN = false;
    1569          60 :     break;
    1570             :   }
    1571         570 : }
    1572             : 
    1573             : //===----------------------------------------------------------------------===//
    1574             : //                      Calling Convention Implementation
    1575             : //===----------------------------------------------------------------------===//
    1576             : 
    1577             : #include "ARMGenCallingConv.inc"
    1578             : 
    1579             : /// getEffectiveCallingConv - Get the effective calling convention, taking into
    1580             : /// account presence of floating point hardware and calling convention
    1581             : /// limitations, such as support for variadic functions.
    1582             : CallingConv::ID
    1583       97124 : ARMTargetLowering::getEffectiveCallingConv(CallingConv::ID CC,
    1584             :                                            bool isVarArg) const {
    1585       97124 :   switch (CC) {
    1586           0 :   default:
    1587           0 :     report_fatal_error("Unsupported calling convention");
    1588             :   case CallingConv::ARM_AAPCS:
    1589             :   case CallingConv::ARM_APCS:
    1590             :   case CallingConv::GHC:
    1591             :     return CC;
    1592           0 :   case CallingConv::PreserveMost:
    1593           0 :     return CallingConv::PreserveMost;
    1594        5144 :   case CallingConv::ARM_AAPCS_VFP:
    1595             :   case CallingConv::Swift:
    1596        5144 :     return isVarArg ? CallingConv::ARM_AAPCS : CallingConv::ARM_AAPCS_VFP;
    1597       78065 :   case CallingConv::C:
    1598       78065 :     if (!Subtarget->isAAPCS_ABI())
    1599             :       return CallingConv::ARM_APCS;
    1600      126402 :     else if (Subtarget->hasVFP2() && !Subtarget->isThumb1Only() &&
    1601      101407 :              getTargetMachine().Options.FloatABIType == FloatABI::Hard &&
    1602             :              !isVarArg)
    1603             :       return CallingConv::ARM_AAPCS_VFP;
    1604             :     else
    1605             :       return CallingConv::ARM_AAPCS;
    1606         836 :   case CallingConv::Fast:
    1607             :   case CallingConv::CXX_FAST_TLS:
    1608         836 :     if (!Subtarget->isAAPCS_ABI()) {
    1609         963 :       if (Subtarget->hasVFP2() && !Subtarget->isThumb1Only() && !isVarArg)
    1610             :         return CallingConv::Fast;
    1611             :       return CallingConv::ARM_APCS;
    1612         433 :     } else if (Subtarget->hasVFP2() && !Subtarget->isThumb1Only() && !isVarArg)
    1613             :       return CallingConv::ARM_AAPCS_VFP;
    1614             :     else
    1615             :       return CallingConv::ARM_AAPCS;
    1616             :   }
    1617             : }
    1618             : 
    1619       21244 : CCAssignFn *ARMTargetLowering::CCAssignFnForCall(CallingConv::ID CC,
    1620             :                                                  bool isVarArg) const {
    1621       21244 :   return CCAssignFnForNode(CC, false, isVarArg);
    1622             : }
    1623             : 
    1624       42810 : CCAssignFn *ARMTargetLowering::CCAssignFnForReturn(CallingConv::ID CC,
    1625             :                                                    bool isVarArg) const {
    1626       42810 :   return CCAssignFnForNode(CC, true, isVarArg);
    1627             : }
    1628             : 
    1629             : /// CCAssignFnForNode - Selects the correct CCAssignFn for the given
    1630             : /// CallingConvention.
    1631       64054 : CCAssignFn *ARMTargetLowering::CCAssignFnForNode(CallingConv::ID CC,
    1632             :                                                  bool Return,
    1633             :                                                  bool isVarArg) const {
    1634       64054 :   switch (getEffectiveCallingConv(CC, isVarArg)) {
    1635           0 :   default:
    1636           0 :     report_fatal_error("Unsupported calling convention");
    1637       13491 :   case CallingConv::ARM_APCS:
    1638       13491 :     return (Return ? RetCC_ARM_APCS : CC_ARM_APCS);
    1639       39900 :   case CallingConv::ARM_AAPCS:
    1640       39900 :     return (Return ? RetCC_ARM_AAPCS : CC_ARM_AAPCS);
    1641       10375 :   case CallingConv::ARM_AAPCS_VFP:
    1642       10375 :     return (Return ? RetCC_ARM_AAPCS_VFP : CC_ARM_AAPCS_VFP);
    1643         276 :   case CallingConv::Fast:
    1644         276 :     return (Return ? RetFastCC_ARM_APCS : FastCC_ARM_APCS);
    1645          12 :   case CallingConv::GHC:
    1646          12 :     return (Return ? RetCC_ARM_APCS : CC_ARM_APCS_GHC);
    1647           0 :   case CallingConv::PreserveMost:
    1648           0 :     return (Return ? RetCC_ARM_AAPCS : CC_ARM_AAPCS);
    1649             :   }
    1650             : }
    1651             : 
    1652             : /// LowerCallResult - Lower the result values of a call into the
    1653             : /// appropriate copies out of appropriate physical registers.
    1654        6873 : SDValue ARMTargetLowering::LowerCallResult(
    1655             :     SDValue Chain, SDValue InFlag, CallingConv::ID CallConv, bool isVarArg,
    1656             :     const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl,
    1657             :     SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals, bool isThisReturn,
    1658             :     SDValue ThisVal) const {
    1659             :   // Assign locations to each value returned by this call.
    1660             :   SmallVector<CCValAssign, 16> RVLocs;
    1661             :   CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs,
    1662       13746 :                  *DAG.getContext());
    1663        6873 :   CCInfo.AnalyzeCallResult(Ins, CCAssignFnForReturn(CallConv, isVarArg));
    1664             : 
    1665             :   // Copy all of the result registers out of their specified physreg.
    1666       29517 :   for (unsigned i = 0; i != RVLocs.size(); ++i) {
    1667        5257 :     CCValAssign VA = RVLocs[i];
    1668             : 
    1669             :     // Pass 'this' value directly from the argument to return value, to avoid
    1670             :     // reg unit interference
    1671        5309 :     if (i == 0 && isThisReturn) {
    1672             :       assert(!VA.needsCustom() && VA.getLocVT() == MVT::i32 &&
    1673             :              "unexpected return calling convention register assignment");
    1674          52 :       InVals.push_back(ThisVal);
    1675          52 :       continue;
    1676             :     }
    1677             : 
    1678        5205 :     SDValue Val;
    1679        5205 :     if (VA.needsCustom()) {
    1680             :       // Handle f64 or half of a v2f64.
    1681             :       SDValue Lo = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32,
    1682         191 :                                       InFlag);
    1683             :       Chain = Lo.getValue(1);
    1684         191 :       InFlag = Lo.getValue(2);
    1685         382 :       VA = RVLocs[++i]; // skip ahead to next loc
    1686             :       SDValue Hi = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32,
    1687         191 :                                       InFlag);
    1688             :       Chain = Hi.getValue(1);
    1689         191 :       InFlag = Hi.getValue(2);
    1690         191 :       if (!Subtarget->isLittle())
    1691             :         std::swap (Lo, Hi);
    1692         191 :       Val = DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi);
    1693             : 
    1694         191 :       if (VA.getLocVT() == MVT::v2f64) {
    1695          43 :         SDValue Vec = DAG.getNode(ISD::UNDEF, dl, MVT::v2f64);
    1696          43 :         Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Vec, Val,
    1697          86 :                           DAG.getConstant(0, dl, MVT::i32));
    1698             : 
    1699          86 :         VA = RVLocs[++i]; // skip ahead to next loc
    1700          43 :         Lo = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32, InFlag);
    1701             :         Chain = Lo.getValue(1);
    1702          43 :         InFlag = Lo.getValue(2);
    1703          86 :         VA = RVLocs[++i]; // skip ahead to next loc
    1704          43 :         Hi = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32, InFlag);
    1705             :         Chain = Hi.getValue(1);
    1706          43 :         InFlag = Hi.getValue(2);
    1707          43 :         if (!Subtarget->isLittle())
    1708             :           std::swap (Lo, Hi);
    1709          43 :         Val = DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi);
    1710          43 :         Val = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Vec, Val,
    1711          86 :                           DAG.getConstant(1, dl, MVT::i32));
    1712             :       }
    1713             :     } else {
    1714        5014 :       Val = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), VA.getLocVT(),
    1715        5014 :                                InFlag);
    1716        5014 :       Chain = Val.getValue(1);
    1717        5014 :       InFlag = Val.getValue(2);
    1718             :     }
    1719             : 
    1720        5205 :     switch (VA.getLocInfo()) {
    1721           0 :     default: llvm_unreachable("Unknown loc info!");
    1722             :     case CCValAssign::Full: break;
    1723             :     case CCValAssign::BCvt:
    1724         615 :       Val = DAG.getNode(ISD::BITCAST, dl, VA.getValVT(), Val);
    1725         615 :       break;
    1726             :     }
    1727             : 
    1728        5205 :     InVals.push_back(Val);
    1729             :   }
    1730             : 
    1731       13746 :   return Chain;
    1732             : }
    1733             : 
    1734             : /// LowerMemOpCallTo - Store the argument to the stack.
    1735         912 : SDValue ARMTargetLowering::LowerMemOpCallTo(SDValue Chain, SDValue StackPtr,
    1736             :                                             SDValue Arg, const SDLoc &dl,
    1737             :                                             SelectionDAG &DAG,
    1738             :                                             const CCValAssign &VA,
    1739             :                                             ISD::ArgFlagsTy Flags) const {
    1740         912 :   unsigned LocMemOffset = VA.getLocMemOffset();
    1741         912 :   SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset, dl);
    1742         912 :   PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(DAG.getDataLayout()),
    1743        1824 :                        StackPtr, PtrOff);
    1744             :   return DAG.getStore(
    1745             :       Chain, dl, Arg, PtrOff,
    1746         912 :       MachinePointerInfo::getStack(DAG.getMachineFunction(), LocMemOffset));
    1747             : }
    1748             : 
    1749         446 : void ARMTargetLowering::PassF64ArgInRegs(const SDLoc &dl, SelectionDAG &DAG,
    1750             :                                          SDValue Chain, SDValue &Arg,
    1751             :                                          RegsToPassVector &RegsToPass,
    1752             :                                          CCValAssign &VA, CCValAssign &NextVA,
    1753             :                                          SDValue &StackPtr,
    1754             :                                          SmallVectorImpl<SDValue> &MemOpChains,
    1755             :                                          ISD::ArgFlagsTy Flags) const {
    1756             :   SDValue fmrrd = DAG.getNode(ARMISD::VMOVRRD, dl,
    1757         446 :                               DAG.getVTList(MVT::i32, MVT::i32), Arg);
    1758         446 :   unsigned id = Subtarget->isLittle() ? 0 : 1;
    1759         892 :   RegsToPass.push_back(std::make_pair(VA.getLocReg(), fmrrd.getValue(id)));
    1760             : 
    1761         446 :   if (NextVA.isRegLoc())
    1762         876 :     RegsToPass.push_back(std::make_pair(NextVA.getLocReg(), fmrrd.getValue(1-id)));
    1763             :   else {
    1764             :     assert(NextVA.isMemLoc());
    1765           8 :     if (!StackPtr.getNode())
    1766           0 :       StackPtr = DAG.getCopyFromReg(Chain, dl, ARM::SP,
    1767           0 :                                     getPointerTy(DAG.getDataLayout()));
    1768             : 
    1769          16 :     MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, fmrrd.getValue(1-id),
    1770             :                                            dl, DAG, NextVA,
    1771           8 :                                            Flags));
    1772             :   }
    1773         446 : }
    1774             : 
    1775             : /// LowerCall - Lowering a call into a callseq_start <-
    1776             : /// ARMISD:CALL <- callseq_end chain. Also add input and output parameter
    1777             : /// nodes.
    1778             : SDValue
    1779        7433 : ARMTargetLowering::LowerCall(TargetLowering::CallLoweringInfo &CLI,
    1780             :                              SmallVectorImpl<SDValue> &InVals) const {
    1781        7433 :   SelectionDAG &DAG                     = CLI.DAG;
    1782        7433 :   SDLoc &dl                             = CLI.DL;
    1783        7433 :   SmallVectorImpl<ISD::OutputArg> &Outs = CLI.Outs;
    1784        7433 :   SmallVectorImpl<SDValue> &OutVals     = CLI.OutVals;
    1785        7433 :   SmallVectorImpl<ISD::InputArg> &Ins   = CLI.Ins;
    1786        7433 :   SDValue Chain                         = CLI.Chain;
    1787        7433 :   SDValue Callee                        = CLI.Callee;
    1788             :   bool &isTailCall                      = CLI.IsTailCall;
    1789        7433 :   CallingConv::ID CallConv              = CLI.CallConv;
    1790        7433 :   bool doesNotRet                       = CLI.DoesNotReturn;
    1791        7433 :   bool isVarArg                         = CLI.IsVarArg;
    1792             : 
    1793        7433 :   MachineFunction &MF = DAG.getMachineFunction();
    1794        7433 :   bool isStructRet    = (Outs.empty()) ? false : Outs[0].Flags.isSRet();
    1795             :   bool isThisReturn   = false;
    1796             :   bool isSibCall      = false;
    1797       14866 :   auto Attr = MF.getFunction().getFnAttribute("disable-tail-calls");
    1798             : 
    1799             :   // Disable tail calls if they're not supported.
    1800        7433 :   if (!Subtarget->supportsTailCall() || Attr.getValueAsString() == "true")
    1801        2361 :     isTailCall = false;
    1802             : 
    1803        7433 :   if (isTailCall) {
    1804             :     // Check if it's really possible to do a tail call.
    1805         632 :     isTailCall = IsEligibleForTailCallOptimization(Callee, CallConv,
    1806         632 :                     isVarArg, isStructRet, MF.getFunction().hasStructRetAttr(),
    1807             :                                                    Outs, OutVals, Ins, DAG);
    1808         704 :     if (!isTailCall && CLI.CS && CLI.CS.isMustTailCall())
    1809           0 :       report_fatal_error("failed to perform tail call elimination on a call "
    1810             :                          "site marked musttail");
    1811             :     // We don't support GuaranteedTailCallOpt for ARM, only automatically
    1812             :     // detected sibcalls.
    1813         632 :     if (isTailCall) {
    1814             :       ++NumTailCalls;
    1815             :       isSibCall = true;
    1816             :     }
    1817             :   }
    1818             : 
    1819             :   // Analyze operands of the call, assigning locations to each operand.
    1820             :   SmallVector<CCValAssign, 16> ArgLocs;
    1821             :   CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), ArgLocs,
    1822       14866 :                  *DAG.getContext());
    1823        7433 :   CCInfo.AnalyzeCallOperands(Outs, CCAssignFnForCall(CallConv, isVarArg));
    1824             : 
    1825             :   // Get a count of how many bytes are to be pushed on the stack.
    1826        7433 :   unsigned NumBytes = CCInfo.getNextStackOffset();
    1827             : 
    1828             :   // For tail calls, memory operands are available in our caller's stack.
    1829        7433 :   if (isSibCall)
    1830             :     NumBytes = 0;
    1831             : 
    1832             :   // Adjust the stack pointer for the new arguments...
    1833             :   // These operations are automatically eliminated by the prolog/epilog pass
    1834        7433 :   if (!isSibCall)
    1835        6873 :     Chain = DAG.getCALLSEQ_START(Chain, NumBytes, 0, dl);
    1836             : 
    1837             :   SDValue StackPtr =
    1838       14866 :       DAG.getCopyFromReg(Chain, dl, ARM::SP, getPointerTy(DAG.getDataLayout()));
    1839             : 
    1840             :   RegsToPassVector RegsToPass;
    1841             :   SmallVector<SDValue, 8> MemOpChains;
    1842             : 
    1843             :   // Walk the register/memloc assignments, inserting copies/loads.  In the case
    1844             :   // of tail call optimization, arguments are handled later.
    1845       20838 :   for (unsigned i = 0, realArgIdx = 0, e = ArgLocs.size();
    1846       20838 :        i != e;
    1847             :        ++i, ++realArgIdx) {
    1848       13405 :     CCValAssign &VA = ArgLocs[i];
    1849       26810 :     SDValue Arg = OutVals[realArgIdx];
    1850       13405 :     ISD::ArgFlagsTy Flags = Outs[realArgIdx].Flags;
    1851             :     bool isByVal = Flags.isByVal();
    1852             : 
    1853             :     // Promote the value if needed.
    1854       13405 :     switch (VA.getLocInfo()) {
    1855           0 :     default: llvm_unreachable("Unknown loc info!");
    1856             :     case CCValAssign::Full: break;
    1857             :     case CCValAssign::SExt:
    1858           0 :       Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), Arg);
    1859           0 :       break;
    1860             :     case CCValAssign::ZExt:
    1861           0 :       Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, VA.getLocVT(), Arg);
    1862           0 :       break;
    1863             :     case CCValAssign::AExt:
    1864           0 :       Arg = DAG.getNode(ISD::ANY_EXTEND, dl, VA.getLocVT(), Arg);
    1865           0 :       break;
    1866             :     case CCValAssign::BCvt:
    1867        1175 :       Arg = DAG.getNode(ISD::BITCAST, dl, VA.getLocVT(), Arg);
    1868        1175 :       break;
    1869             :     }
    1870             : 
    1871             :     // f64 and v2f64 might be passed in i32 pairs and must be split into pieces
    1872       13405 :     if (VA.needsCustom()) {
    1873         399 :       if (VA.getLocVT() == MVT::v2f64) {
    1874             :         SDValue Op0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg,
    1875          96 :                                   DAG.getConstant(0, dl, MVT::i32));
    1876             :         SDValue Op1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg,
    1877          96 :                                   DAG.getConstant(1, dl, MVT::i32));
    1878             : 
    1879          96 :         PassF64ArgInRegs(dl, DAG, Chain, Op0, RegsToPass,
    1880          48 :                          VA, ArgLocs[++i], StackPtr, MemOpChains, Flags);
    1881             : 
    1882          96 :         VA = ArgLocs[++i]; // skip ahead to next loc
    1883          48 :         if (VA.isRegLoc()) {
    1884          94 :           PassF64ArgInRegs(dl, DAG, Chain, Op1, RegsToPass,
    1885          47 :                            VA, ArgLocs[++i], StackPtr, MemOpChains, Flags);
    1886             :         } else {
    1887             :           assert(VA.isMemLoc());
    1888             : 
    1889           1 :           MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, Op1,
    1890             :                                                  dl, DAG, VA, Flags));
    1891             :         }
    1892             :       } else {
    1893         702 :         PassF64ArgInRegs(dl, DAG, Chain, Arg, RegsToPass, VA, ArgLocs[++i],
    1894             :                          StackPtr, MemOpChains, Flags);
    1895             :       }
    1896       13006 :     } else if (VA.isRegLoc()) {
    1897       17696 :       if (realArgIdx == 0 && Flags.isReturned() && !Flags.isSwiftSelf() &&
    1898             :           Outs[0].VT == MVT::i32) {
    1899             :         assert(VA.getLocVT() == MVT::i32 &&
    1900             :                "unexpected calling convention register assignment");
    1901             :         assert(!Ins.empty() && Ins[0].VT == MVT::i32 &&
    1902             :                "unexpected use of 'returned'");
    1903             :         isThisReturn = true;
    1904             :       }
    1905       23458 :       RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
    1906        1277 :     } else if (isByVal) {
    1907             :       assert(VA.isMemLoc());
    1908             :       unsigned offset = 0;
    1909             : 
    1910             :       // True if this byval aggregate will be split between registers
    1911             :       // and memory.
    1912             :       unsigned ByValArgsCount = CCInfo.getInRegsParamsCount();
    1913         369 :       unsigned CurByValIdx = CCInfo.getInRegsParamsProcessed();
    1914             : 
    1915         369 :       if (CurByValIdx < ByValArgsCount) {
    1916             : 
    1917             :         unsigned RegBegin, RegEnd;
    1918             :         CCInfo.getInRegsParamInfo(CurByValIdx, RegBegin, RegEnd);
    1919             : 
    1920             :         EVT PtrVT =
    1921         356 :             DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout());
    1922             :         unsigned int i, j;
    1923        3082 :         for (i = 0, j = RegBegin; j < RegEnd; i++, j++) {
    1924        1363 :           SDValue Const = DAG.getConstant(4*i, dl, MVT::i32);
    1925        1363 :           SDValue AddArg = DAG.getNode(ISD::ADD, dl, PtrVT, Arg, Const);
    1926             :           SDValue Load = DAG.getLoad(PtrVT, dl, Chain, AddArg,
    1927             :                                      MachinePointerInfo(),
    1928        2726 :                                      DAG.InferPtrAlignment(AddArg));
    1929        1363 :           MemOpChains.push_back(Load.getValue(1));
    1930        1363 :           RegsToPass.push_back(std::make_pair(j, Load));
    1931             :         }
    1932             : 
    1933             :         // If parameter size outsides register area, "offset" value
    1934             :         // helps us to calculate stack slot for remained part properly.
    1935         356 :         offset = RegEnd - RegBegin;
    1936             : 
    1937             :         CCInfo.nextInRegsParam();
    1938             :       }
    1939             : 
    1940         369 :       if (Flags.getByValSize() > 4*offset) {
    1941         360 :         auto PtrVT = getPointerTy(DAG.getDataLayout());
    1942         360 :         unsigned LocMemOffset = VA.getLocMemOffset();
    1943         360 :         SDValue StkPtrOff = DAG.getIntPtrConstant(LocMemOffset, dl);
    1944         360 :         SDValue Dst = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, StkPtrOff);
    1945         360 :         SDValue SrcOffset = DAG.getIntPtrConstant(4*offset, dl);
    1946         360 :         SDValue Src = DAG.getNode(ISD::ADD, dl, PtrVT, Arg, SrcOffset);
    1947         360 :         SDValue SizeNode = DAG.getConstant(Flags.getByValSize() - 4*offset, dl,
    1948         360 :                                            MVT::i32);
    1949             :         SDValue AlignNode = DAG.getConstant(Flags.getByValAlign(), dl,
    1950         360 :                                             MVT::i32);
    1951             : 
    1952         360 :         SDVTList VTs = DAG.getVTList(MVT::Other, MVT::Glue);
    1953         360 :         SDValue Ops[] = { Chain, Dst, Src, SizeNode, AlignNode};
    1954         360 :         MemOpChains.push_back(DAG.getNode(ARMISD::COPY_STRUCT_BYVAL, dl, VTs,
    1955         360 :                                           Ops));
    1956             :       }
    1957         908 :     } else if (!isSibCall) {
    1958             :       assert(VA.isMemLoc());
    1959             : 
    1960         903 :       MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, Arg,
    1961             :                                              dl, DAG, VA, Flags));
    1962             :     }
    1963             :   }
    1964             : 
    1965        7433 :   if (!MemOpChains.empty())
    1966         701 :     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains);
    1967             : 
    1968             :   // Build a sequence of copy-to-reg nodes chained together with token chain
    1969             :   // and flag operands which copy the outgoing args into the appropriate regs.
    1970        7433 :   SDValue InFlag;
    1971             :   // Tail call byval lowering might overwrite argument registers so in case of
    1972             :   // tail call optimization the copies to registers are lowered later.
    1973        7433 :   if (!isTailCall)
    1974       20251 :     for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
    1975       13378 :       Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
    1976       26756 :                                RegsToPass[i].second, InFlag);
    1977       13378 :       InFlag = Chain.getValue(1);
    1978             :     }
    1979             : 
    1980             :   // For tail calls lower the arguments to the 'real' stack slot.
    1981        7433 :   if (isTailCall) {
    1982             :     // Force all the incoming stack arguments to be loaded from the stack
    1983             :     // before any new outgoing arguments are stored to the stack, because the
    1984             :     // outgoing stack slots may alias the incoming argument stack slots, and
    1985             :     // the alias isn't otherwise explicit. This is slightly more conservative
    1986             :     // than necessary, because it means that each store effectively depends
    1987             :     // on every argument instead of just those arguments it would clobber.
    1988             : 
    1989             :     // Do not flag preceding copytoreg stuff together with the following stuff.
    1990         560 :     InFlag = SDValue();
    1991        1158 :     for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
    1992         598 :       Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
    1993        1196 :                                RegsToPass[i].second, InFlag);
    1994         598 :       InFlag = Chain.getValue(1);
    1995             :     }
    1996         560 :     InFlag = SDValue();
    1997             :   }
    1998             : 
    1999             :   // If the callee is a GlobalAddress/ExternalSymbol node (quite common, every
    2000             :   // direct call is) turn it into a TargetGlobalAddress/TargetExternalSymbol
    2001             :   // node so that legalize doesn't hack it.
    2002             :   bool isDirect = false;
    2003             : 
    2004        7433 :   const TargetMachine &TM = getTargetMachine();
    2005        7433 :   const Module *Mod = MF.getFunction().getParent();
    2006             :   const GlobalValue *GV = nullptr;
    2007             :   if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee))
    2008        4266 :     GV = G->getGlobal();
    2009             :   bool isStub =
    2010       10373 :       !TM.shouldAssumeDSOLocal(*Mod, GV) && Subtarget->isTargetMachO();
    2011             : 
    2012        7433 :   bool isARMFunc = !Subtarget->isThumb() || (isStub && !Subtarget->isMClass());
    2013             :   bool isLocalARMFunc = false;
    2014        7433 :   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
    2015        7433 :   auto PtrVt = getPointerTy(DAG.getDataLayout());
    2016             : 
    2017        7433 :   if (Subtarget->genLongCalls()) {
    2018             :     assert((!isPositionIndependent() || Subtarget->isTargetWindows()) &&
    2019             :            "long-calls codegen is not position independent!");
    2020             :     // Handle a global address or an external symbol. If it's not one of
    2021             :     // those, the target's already in a register, so we don't need to do
    2022             :     // anything extra.
    2023             :     if (isa<GlobalAddressSDNode>(Callee)) {
    2024             :       // Create a constant pool entry for the callee address
    2025             :       unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
    2026             :       ARMConstantPoolValue *CPV =
    2027           7 :         ARMConstantPoolConstant::Create(GV, ARMPCLabelIndex, ARMCP::CPValue, 0);
    2028             : 
    2029             :       // Get the address of the callee into a register
    2030           7 :       SDValue CPAddr = DAG.getTargetConstantPool(CPV, PtrVt, 4);
    2031           7 :       CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
    2032           7 :       Callee = DAG.getLoad(
    2033             :           PtrVt, dl, DAG.getEntryNode(), CPAddr,
    2034          14 :           MachinePointerInfo::getConstantPool(DAG.getMachineFunction()));
    2035             :     } else if (ExternalSymbolSDNode *S=dyn_cast<ExternalSymbolSDNode>(Callee)) {
    2036           0 :       const char *Sym = S->getSymbol();
    2037             : 
    2038             :       // Create a constant pool entry for the callee address
    2039             :       unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
    2040             :       ARMConstantPoolValue *CPV =
    2041           0 :         ARMConstantPoolSymbol::Create(*DAG.getContext(), Sym,
    2042           0 :                                       ARMPCLabelIndex, 0);
    2043             :       // Get the address of the callee into a register
    2044           0 :       SDValue CPAddr = DAG.getTargetConstantPool(CPV, PtrVt, 4);
    2045           0 :       CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
    2046           0 :       Callee = DAG.getLoad(
    2047             :           PtrVt, dl, DAG.getEntryNode(), CPAddr,
    2048           0 :           MachinePointerInfo::getConstantPool(DAG.getMachineFunction()));
    2049             :     }
    2050             :   } else if (isa<GlobalAddressSDNode>(Callee)) {
    2051             :     // If we're optimizing for minimum size and the function is called three or
    2052             :     // more times in this block, we can improve codesize by calling indirectly
    2053             :     // as BLXr has a 16-bit encoding.
    2054        4259 :     auto *GV = cast<GlobalAddressSDNode>(Callee)->getGlobal();
    2055        4259 :     auto *BB = CLI.CS.getParent();
    2056             :     bool PreferIndirect =
    2057        6446 :         Subtarget->isThumb() && MF.getFunction().optForMinSize() &&
    2058         341 :         count_if(GV->users(), [&BB](const User *U) {
    2059         687 :           return isa<Instruction>(U) && cast<Instruction>(U)->getParent() == BB;
    2060             :         }) > 2;
    2061             : 
    2062             :     if (!PreferIndirect) {
    2063             :       isDirect = true;
    2064        4256 :       bool isDef = GV->isStrongDefinitionForLinker();
    2065             : 
    2066             :       // ARM call to a local ARM function is predicable.
    2067        6249 :       isLocalARMFunc = !Subtarget->isThumb() && (isDef || !ARMInterworking);
    2068             :       // tBX takes a register source operand.
    2069        4402 :       if (isStub && Subtarget->isThumb1Only() && !Subtarget->hasV5TOps()) {
    2070             :         assert(Subtarget->isTargetMachO() && "WrapperPIC use on non-MachO?");
    2071          50 :         Callee = DAG.getNode(
    2072             :             ARMISD::WrapperPIC, dl, PtrVt,
    2073          50 :             DAG.getTargetGlobalAddress(GV, dl, PtrVt, 0, ARMII::MO_NONLAZY));
    2074          50 :         Callee = DAG.getLoad(
    2075             :             PtrVt, dl, DAG.getEntryNode(), Callee,
    2076             :             MachinePointerInfo::getGOT(DAG.getMachineFunction()),
    2077             :             /* Alignment = */ 0, MachineMemOperand::MODereferenceable |
    2078         100 :                                      MachineMemOperand::MOInvariant);
    2079        4206 :       } else if (Subtarget->isTargetCOFF()) {
    2080             :         assert(Subtarget->isTargetWindows() &&
    2081             :                "Windows is the only supported COFF target");
    2082             :         unsigned TargetFlags = GV->hasDLLImportStorageClass()
    2083          51 :                                    ? ARMII::MO_DLLIMPORT
    2084             :                                    : ARMII::MO_NO_FLAG;
    2085          51 :         Callee = DAG.getTargetGlobalAddress(GV, dl, PtrVt, /*Offset=*/0,
    2086          51 :                                             TargetFlags);
    2087          51 :         if (GV->hasDLLImportStorageClass())
    2088           3 :           Callee =
    2089           6 :               DAG.getLoad(PtrVt, dl, DAG.getEntryNode(),
    2090             :                           DAG.getNode(ARMISD::Wrapper, dl, PtrVt, Callee),
    2091           9 :                           MachinePointerInfo::getGOT(DAG.getMachineFunction()));
    2092             :       } else {
    2093        4155 :         Callee = DAG.getTargetGlobalAddress(GV, dl, PtrVt, 0, 0);
    2094             :       }
    2095             :     }
    2096             :   } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
    2097             :     isDirect = true;
    2098             :     // tBX takes a register source operand.
    2099        3076 :     const char *Sym = S->getSymbol();
    2100        3143 :     if (isARMFunc && Subtarget->isThumb1Only() && !Subtarget->hasV5TOps()) {
    2101             :       unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
    2102             :       ARMConstantPoolValue *CPV =
    2103          18 :         ARMConstantPoolSymbol::Create(*DAG.getContext(), Sym,
    2104           9 :                                       ARMPCLabelIndex, 4);
    2105           9 :       SDValue CPAddr = DAG.getTargetConstantPool(CPV, PtrVt, 4);
    2106           9 :       CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
    2107           9 :       Callee = DAG.getLoad(
    2108             :           PtrVt, dl, DAG.getEntryNode(), CPAddr,
    2109          18 :           MachinePointerInfo::getConstantPool(DAG.getMachineFunction()));
    2110           9 :       SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, dl, MVT::i32);
    2111           9 :       Callee = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVt, Callee, PICLabel);
    2112             :     } else {
    2113        3067 :       Callee = DAG.getTargetExternalSymbol(Sym, PtrVt, 0);
    2114             :     }
    2115             :   }
    2116             : 
    2117             :   // FIXME: handle tail calls differently.
    2118             :   unsigned CallOpc;
    2119        7433 :   if (Subtarget->isThumb()) {
    2120        3211 :     if ((!isDirect || isARMFunc) && !Subtarget->hasV5TOps())
    2121             :       CallOpc = ARMISD::CALL_NOLINK;
    2122             :     else
    2123             :       CallOpc = ARMISD::CALL;
    2124             :   } else {
    2125        4222 :     if (!isDirect && !Subtarget->hasV5TOps())
    2126             :       CallOpc = ARMISD::CALL_NOLINK;
    2127        4225 :     else if (doesNotRet && isDirect && Subtarget->hasRetAddrStack() &&
    2128             :              // Emit regular call when code size is the priority
    2129          20 :              !MF.getFunction().optForMinSize())
    2130             :       // "mov lr, pc; b _foo" to avoid confusing the RSP
    2131             :       CallOpc = ARMISD::CALL_NOLINK;
    2132             :     else
    2133        4189 :       CallOpc = isLocalARMFunc ? ARMISD::CALL_PRED : ARMISD::CALL;
    2134             :   }
    2135             : 
    2136             :   std::vector<SDValue> Ops;
    2137        7433 :   Ops.push_back(Chain);
    2138        7433 :   Ops.push_back(Callee);
    2139             : 
    2140             :   // Add argument registers to the end of the list so that they are known live
    2141             :   // into the call.
    2142       21409 :   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
    2143       27952 :     Ops.push_back(DAG.getRegister(RegsToPass[i].first,
    2144       41928 :                                   RegsToPass[i].second.getValueType()));
    2145             : 
    2146             :   // Add a register mask operand representing the call-preserved registers.
    2147        7433 :   if (!isTailCall) {
    2148             :     const uint32_t *Mask;
    2149        6873 :     const ARMBaseRegisterInfo *ARI = Subtarget->getRegisterInfo();
    2150        6873 :     if (isThisReturn) {
    2151             :       // For 'this' returns, use the R0-preserving mask if applicable
    2152          52 :       Mask = ARI->getThisReturnPreservedMask(MF, CallConv);
    2153          52 :       if (!Mask) {
    2154             :         // Set isThisReturn to false if the calling convention is not one that
    2155             :         // allows 'returned' to be modeled in this way, so LowerCallResult does
    2156             :         // not try to pass 'this' straight through
    2157             :         isThisReturn = false;
    2158           0 :         Mask = ARI->getCallPreservedMask(MF, CallConv);
    2159             :       }
    2160             :     } else
    2161        6821 :       Mask = ARI->getCallPreservedMask(MF, CallConv);
    2162             : 
    2163             :     assert(Mask && "Missing call preserved mask for calling convention");
    2164       13746 :     Ops.push_back(DAG.getRegisterMask(Mask));
    2165             :   }
    2166             : 
    2167        7433 :   if (InFlag.getNode())
    2168        6049 :     Ops.push_back(InFlag);
    2169             : 
    2170        7433 :   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
    2171        7433 :   if (isTailCall) {
    2172         560 :     MF.getFrameInfo().setHasTailCall();
    2173         560 :     return DAG.getNode(ARMISD::TC_RETURN, dl, NodeTys, Ops);
    2174             :   }
    2175             : 
    2176             :   // Returns a chain and a flag for retval copy to use.
    2177        6873 :   Chain = DAG.getNode(CallOpc, dl, NodeTys, Ops);
    2178        6873 :   InFlag = Chain.getValue(1);
    2179             : 
    2180        6873 :   Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, dl, true),
    2181        6873 :                              DAG.getIntPtrConstant(0, dl, true), InFlag, dl);
    2182        6873 :   if (!Ins.empty())
    2183        4359 :     InFlag = Chain.getValue(1);
    2184             : 
    2185             :   // Handle result values, copying them out of physregs into vregs that we
    2186             :   // return.
    2187             :   return LowerCallResult(Chain, InFlag, CallConv, isVarArg, Ins, dl, DAG,
    2188             :                          InVals, isThisReturn,
    2189        6925 :                          isThisReturn ? OutVals[0] : SDValue());
    2190             : }
    2191             : 
    2192             : /// HandleByVal - Every parameter *after* a byval parameter is passed
    2193             : /// on the stack.  Remember the next parameter register to allocate,
    2194             : /// and then confiscate the rest of the parameter registers to insure
    2195             : /// this.
    2196         419 : void ARMTargetLowering::HandleByVal(CCState *State, unsigned &Size,
    2197             :                                     unsigned Align) const {
    2198             :   // Byval (as with any stack) slots are always at least 4 byte aligned.
    2199         838 :   Align = std::max(Align, 4U);
    2200             : 
    2201         419 :   unsigned Reg = State->AllocateReg(GPRArgRegs);
    2202         419 :   if (!Reg)
    2203             :     return;
    2204             : 
    2205         399 :   unsigned AlignInRegs = Align / 4;
    2206         399 :   unsigned Waste = (ARM::R4 - Reg) % AlignInRegs;
    2207         431 :   for (unsigned i = 0; i < Waste; ++i)
    2208          16 :     Reg = State->AllocateReg(GPRArgRegs);
    2209             : 
    2210         399 :   if (!Reg)
    2211             :     return;
    2212             : 
    2213         395 :   unsigned Excess = 4 * (ARM::R4 - Reg);
    2214             : 
    2215             :   // Special case when NSAA != SP and parameter size greater than size of
    2216             :   // all remained GPR regs. In that case we can't split parameter, we must
    2217             :   // send it to stack. We also must set NCRN to R4, so waste all
    2218             :   // remained registers.
    2219         395 :   const unsigned NSAAOffset = State->getNextStackOffset();
    2220         395 :   if (NSAAOffset != 0 && Size > Excess) {
    2221          15 :     while (State->AllocateReg(GPRArgRegs))
    2222             :       ;
    2223             :     return;
    2224             :   }
    2225             : 
    2226             :   // First register for byval parameter is the first register that wasn't
    2227             :   // allocated before this method call, so it would be "reg".
    2228             :   // If parameter is small enough to be saved in range [reg, r4), then
    2229             :   // the end (first after last) register would be reg + param-size-in-regs,
    2230             :   // else parameter would be splitted between registers and stack,
    2231             :   // end register would be r4 in this case.
    2232             :   unsigned ByValRegBegin = Reg;
    2233         780 :   unsigned ByValRegEnd = std::min<unsigned>(Reg + Size / 4, ARM::R4);
    2234             :   State->addInRegsParamInfo(ByValRegBegin, ByValRegEnd);
    2235             :   // Note, first register is allocated in the beginning of function already,
    2236             :   // allocate remained amount of registers we need.
    2237        1439 :   for (unsigned i = Reg + 1; i != ByValRegEnd; ++i)
    2238        1049 :     State->AllocateReg(GPRArgRegs);
    2239             :   // A byval parameter that is split between registers and memory needs its
    2240             :   // size truncated here.
    2241             :   // In the case where the entire structure fits in registers, we set the
    2242             :   // size in memory to zero.
    2243         780 :   Size = std::max<int>(Size - Excess, 0);
    2244             : }
    2245             : 
    2246             : /// MatchingStackOffset - Return true if the given stack call argument is
    2247             : /// already available in the same position (relatively) of the caller's
    2248             : /// incoming argument stack.
    2249             : static
    2250          23 : bool MatchingStackOffset(SDValue Arg, unsigned Offset, ISD::ArgFlagsTy Flags,
    2251             :                          MachineFrameInfo &MFI, const MachineRegisterInfo *MRI,
    2252             :                          const TargetInstrInfo *TII) {
    2253          23 :   unsigned Bytes = Arg.getValueSizeInBits() / 8;
    2254          23 :   int FI = std::numeric_limits<int>::max();
    2255          46 :   if (Arg.getOpcode() == ISD::CopyFromReg) {
    2256           6 :     unsigned VR = cast<RegisterSDNode>(Arg.getOperand(1))->getReg();
    2257           6 :     if (!TargetRegisterInfo::isVirtualRegister(VR))
    2258             :       return false;
    2259           6 :     MachineInstr *Def = MRI->getVRegDef(VR);
    2260           6 :     if (!Def)
    2261             :       return false;
    2262           1 :     if (!Flags.isByVal()) {
    2263           1 :       if (!TII->isLoadFromStackSlot(*Def, FI))
    2264             :         return false;
    2265             :     } else {
    2266             :       return false;
    2267             :     }
    2268             :   } else if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Arg)) {
    2269           5 :     if (Flags.isByVal())
    2270             :       // ByVal argument is passed in as a pointer but it's now being
    2271             :       // dereferenced. e.g.
    2272             :       // define @foo(%struct.X* %A) {
    2273             :       //   tail call @bar(%struct.X* byval %A)
    2274             :       // }
    2275             :       return false;
    2276           5 :     SDValue Ptr = Ld->getBasePtr();
    2277             :     FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr);
    2278             :     if (!FINode)
    2279             :       return false;
    2280           5 :     FI = FINode->getIndex();
    2281             :   } else
    2282             :     return false;
    2283             : 
    2284             :   assert(FI != std::numeric_limits<int>::max());
    2285           6 :   if (!MFI.isFixedObjectIndex(FI))
    2286             :     return false;
    2287          17 :   return Offset == MFI.getObjectOffset(FI) && Bytes == MFI.getObjectSize(FI);
    2288             : }
    2289             : 
    2290             : /// IsEligibleForTailCallOptimization - Check whether the call is eligible
    2291             : /// for tail call optimization. Targets which want to do tail call
    2292             : /// optimization should implement this function.
    2293             : bool
    2294         632 : ARMTargetLowering::IsEligibleForTailCallOptimization(SDValue Callee,
    2295             :                                                      CallingConv::ID CalleeCC,
    2296             :                                                      bool isVarArg,
    2297             :                                                      bool isCalleeStructRet,
    2298             :                                                      bool isCallerStructRet,
    2299             :                                     const SmallVectorImpl<ISD::OutputArg> &Outs,
    2300             :                                     const SmallVectorImpl<SDValue> &OutVals,
    2301             :                                     const SmallVectorImpl<ISD::InputArg> &Ins,
    2302             :                                                      SelectionDAG& DAG) const {
    2303         632 :   MachineFunction &MF = DAG.getMachineFunction();
    2304         632 :   const Function &CallerF = MF.getFunction();
    2305             :   CallingConv::ID CallerCC = CallerF.getCallingConv();
    2306             : 
    2307             :   assert(Subtarget->supportsTailCall());
    2308             : 
    2309             :   // Tail calls to function pointers cannot be optimized for Thumb1 if the args
    2310             :   // to the call take up r0-r3. The reason is that there are no legal registers
    2311             :   // left to hold the pointer to the function to be called.
    2312         644 :   if (Subtarget->isThumb1Only() && Outs.size() >= 4 &&
    2313             :       !isa<GlobalAddressSDNode>(Callee.getNode()))
    2314             :       return false;
    2315             : 
    2316             :   // Look for obvious safe cases to perform tail call optimization that do not
    2317             :   // require ABI changes. This is what gcc calls sibcall.
    2318             : 
    2319             :   // Exception-handling functions need a special set of instructions to indicate
    2320             :   // a return to the hardware. Tail-calling another function would probably
    2321             :   // break this.
    2322         630 :   if (CallerF.hasFnAttribute("interrupt"))
    2323             :     return false;
    2324             : 
    2325             :   // Also avoid sibcall optimization if either caller or callee uses struct
    2326             :   // return semantics.
    2327         630 :   if (isCalleeStructRet || isCallerStructRet)
    2328             :     return false;
    2329             : 
    2330             :   // Externally-defined functions with weak linkage should not be
    2331             :   // tail-called on ARM when the OS does not support dynamic
    2332             :   // pre-emption of symbols, as the AAELF spec requires normal calls
    2333             :   // to undefined weak functions to be replaced with a NOP or jump to the
    2334             :   // next instruction. The behaviour of branch instructions in this
    2335             :   // situation (as used for tail calls) is implementation-defined, so we
    2336             :   // cannot rely on the linker replacing the tail call with a return.
    2337             :   if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
    2338         376 :     const GlobalValue *GV = G->getGlobal();
    2339         376 :     const Triple &TT = getTargetMachine().getTargetTriple();
    2340         382 :     if (GV->hasExternalWeakLinkage() &&
    2341           1 :         (!TT.isOSWindows() || TT.isOSBinFormatELF() || TT.isOSBinFormatMachO()))
    2342             :       return false;
    2343             :   }
    2344             : 
    2345             :   // Check that the call results are passed in the same way.
    2346         624 :   LLVMContext &C = *DAG.getContext();
    2347         624 :   if (!CCState::resultsCompatible(CalleeCC, CallerCC, MF, C, Ins,
    2348             :                                   CCAssignFnForReturn(CalleeCC, isVarArg),
    2349             :                                   CCAssignFnForReturn(CallerCC, isVarArg)))
    2350             :     return false;
    2351             :   // The callee has to preserve all registers the caller needs to preserve.
    2352         606 :   const ARMBaseRegisterInfo *TRI = Subtarget->getRegisterInfo();
    2353         606 :   const uint32_t *CallerPreserved = TRI->getCallPreservedMask(MF, CallerCC);
    2354         606 :   if (CalleeCC != CallerCC) {
    2355         221 :     const uint32_t *CalleePreserved = TRI->getCallPreservedMask(MF, CalleeCC);
    2356         221 :     if (!TRI->regmaskSubsetEqual(CallerPreserved, CalleePreserved))
    2357             :       return false;
    2358             :   }
    2359             : 
    2360             :   // If Caller's vararg or byval argument has been split between registers and
    2361             :   // stack, do not perform tail call, since part of the argument is in caller's
    2362             :   // local frame.
    2363         592 :   const ARMFunctionInfo *AFI_Caller = MF.getInfo<ARMFunctionInfo>();
    2364         592 :   if (AFI_Caller->getArgRegsSaveSize())
    2365             :     return false;
    2366             : 
    2367             :   // If the callee takes no arguments then go on to check the results of the
    2368             :   // call.
    2369         581 :   if (!Outs.empty()) {
    2370             :     // Check if stack adjustment is needed. For now, do not do this if any
    2371             :     // argument is passed on the stack.
    2372             :     SmallVector<CCValAssign, 16> ArgLocs;
    2373         851 :     CCState CCInfo(CalleeCC, isVarArg, MF, ArgLocs, C);
    2374         436 :     CCInfo.AnalyzeCallOperands(Outs, CCAssignFnForCall(CalleeCC, isVarArg));
    2375         436 :     if (CCInfo.getNextStackOffset()) {
    2376             :       // Check if the arguments are already laid out in the right way as
    2377             :       // the caller's fixed stack objects.
    2378          21 :       MachineFrameInfo &MFI = MF.getFrameInfo();
    2379          21 :       const MachineRegisterInfo *MRI = &MF.getRegInfo();
    2380          21 :       const TargetInstrInfo *TII = Subtarget->getInstrInfo();
    2381         121 :       for (unsigned i = 0, realArgIdx = 0, e = ArgLocs.size();
    2382         121 :            i != e;
    2383             :            ++i, ++realArgIdx) {
    2384         118 :         CCValAssign &VA = ArgLocs[i];
    2385             :         EVT RegVT = VA.getLocVT();
    2386         236 :         SDValue Arg = OutVals[realArgIdx];
    2387         118 :         ISD::ArgFlagsTy Flags = Outs[realArgIdx].Flags;
    2388         118 :         if (VA.getLocInfo() == CCValAssign::Indirect)
    2389          18 :           return false;
    2390         118 :         if (VA.needsCustom()) {
    2391             :           // f64 and vector types are split into multiple registers or
    2392             :           // register/stack-slot combinations.  The types will not match
    2393             :           // the registers; give up on memory f64 refs until we figure
    2394             :           // out what to do about this.
    2395           2 :           if (!VA.isRegLoc())
    2396             :             return false;
    2397           4 :           if (!ArgLocs[++i].isRegLoc())
    2398             :             return false;
    2399             :           if (RegVT == MVT::v2f64) {
    2400           0 :             if (!ArgLocs[++i].isRegLoc())
    2401             :               return false;
    2402           0 :             if (!ArgLocs[++i].isRegLoc())
    2403             :               return false;
    2404             :           }
    2405         116 :         } else if (!VA.isRegLoc()) {
    2406          23 :           if (!MatchingStackOffset(Arg, VA.getLocMemOffset(), Flags,
    2407             :                                    MFI, MRI, TII))
    2408             :             return false;
    2409             :         }
    2410             :       }
    2411             :     }
    2412             : 
    2413         418 :     const MachineRegisterInfo &MRI = MF.getRegInfo();
    2414         418 :     if (!parametersInCSRMatch(MRI, CallerPreserved, ArgLocs, OutVals))
    2415             :       return false;
    2416             :   }
    2417             : 
    2418             :   return true;
    2419             : }
    2420             : 
    2421             : bool
    2422       21612 : ARMTargetLowering::CanLowerReturn(CallingConv::ID CallConv,
    2423             :                                   MachineFunction &MF, bool isVarArg,
    2424             :                                   const SmallVectorImpl<ISD::OutputArg> &Outs,
    2425             :                                   LLVMContext &Context) const {
    2426             :   SmallVector<CCValAssign, 16> RVLocs;
    2427       43224 :   CCState CCInfo(CallConv, isVarArg, MF, RVLocs, Context);
    2428       43224 :   return CCInfo.CheckReturn(Outs, CCAssignFnForReturn(CallConv, isVarArg));
    2429             : }
    2430             : 
    2431          12 : static SDValue LowerInterruptReturn(SmallVectorImpl<SDValue> &RetOps,
    2432             :                                     const SDLoc &DL, SelectionDAG &DAG) {
    2433          12 :   const MachineFunction &MF = DAG.getMachineFunction();
    2434          12 :   const Function &F = MF.getFunction();
    2435             : 
    2436          12 :   StringRef IntKind = F.getFnAttribute("interrupt").getValueAsString();
    2437             : 
    2438             :   // See ARM ARM v7 B1.8.3. On exception entry LR is set to a possibly offset
    2439             :   // version of the "preferred return address". These offsets affect the return
    2440             :   // instruction if this is a return from PL1 without hypervisor extensions.
    2441             :   //    IRQ/FIQ: +4     "subs pc, lr, #4"
    2442             :   //    SWI:     0      "subs pc, lr, #0"
    2443             :   //    ABORT:   +4     "subs pc, lr, #4"
    2444             :   //    UNDEF:   +4/+2  "subs pc, lr, #0"
    2445             :   // UNDEF varies depending on where the exception came from ARM or Thumb
    2446             :   // mode. Alongside GCC, we throw our hands up in disgust and pretend it's 0.
    2447             : 
    2448             :   int64_t LROffset;
    2449             :   if (IntKind == "" || IntKind == "IRQ" || IntKind == "FIQ" ||
    2450             :       IntKind == "ABORT")
    2451             :     LROffset = 4;
    2452             :   else if (IntKind == "SWI" || IntKind == "UNDEF")
    2453             :     LROffset = 0;
    2454             :   else
    2455           0 :     report_fatal_error("Unsupported interrupt attribute. If present, value "
    2456             :                        "must be one of: IRQ, FIQ, SWI, ABORT or UNDEF");
    2457             : 
    2458          12 :   RetOps.insert(RetOps.begin() + 1,
    2459          24 :                 DAG.getConstant(LROffset, DL, MVT::i32, false));
    2460             : 
    2461          12 :   return DAG.getNode(ARMISD::INTRET_FLAG, DL, MVT::Other, RetOps);
    2462             : }
    2463             : 
    2464             : SDValue
    2465       12595 : ARMTargetLowering::LowerReturn(SDValue Chain, CallingConv::ID CallConv,
    2466             :                                bool isVarArg,
    2467             :                                const SmallVectorImpl<ISD::OutputArg> &Outs,
    2468             :                                const SmallVectorImpl<SDValue> &OutVals,
    2469             :                                const SDLoc &dl, SelectionDAG &DAG) const {
    2470             :   // CCValAssign - represent the assignment of the return value to a location.
    2471             :   SmallVector<CCValAssign, 16> RVLocs;
    2472             : 
    2473             :   // CCState - Info about the registers and stack slots.
    2474             :   CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs,
    2475       25190 :                  *DAG.getContext());
    2476             : 
    2477             :   // Analyze outgoing return values.
    2478       12595 :   CCInfo.AnalyzeReturn(Outs, CCAssignFnForReturn(CallConv, isVarArg));
    2479             : 
    2480       12595 :   SDValue Flag;
    2481             :   SmallVector<SDValue, 4> RetOps;
    2482       12595 :   RetOps.push_back(Chain); // Operand #0 = Chain (updated below)
    2483       12595 :   bool isLittleEndian = Subtarget->isLittle();
    2484             : 
    2485       12595 :   MachineFunction &MF = DAG.getMachineFunction();
    2486       12595 :   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
    2487       12595 :   AFI->setReturnRegsCount(RVLocs.size());
    2488             : 
    2489             :   // Copy the result values into the output registers.
    2490       10151 :   for (unsigned i = 0, realRVLocIdx = 0;
    2491       45492 :        i != RVLocs.size();
    2492             :        ++i, ++realRVLocIdx) {
    2493             :     CCValAssign &VA = RVLocs[i];
    2494             :     assert(VA.isRegLoc() && "Can only return in registers!");
    2495             : 
    2496       20302 :     SDValue Arg = OutVals[realRVLocIdx];
    2497             :     bool ReturnF16 = false;
    2498             : 
    2499       10151 :     if (Subtarget->hasFullFP16() && Subtarget->isTargetHardFloat()) {
    2500             :       // Half-precision return values can be returned like this:
    2501             :       //
    2502             :       // t11 f16 = fadd ...
    2503             :       // t12: i16 = bitcast t11
    2504             :       //   t13: i32 = zero_extend t12
    2505             :       // t14: f32 = bitcast t13  <~~~~~~~ Arg
    2506             :       //
    2507             :       // to avoid code generation for bitcasts, we simply set Arg to the node
    2508             :       // that produces the f16 value, t11 in this case.
    2509             :       //
    2510          76 :       if (Arg.getValueType() == MVT::f32 && Arg.getOpcode() == ISD::BITCAST) {
    2511          68 :         SDValue ZE = Arg.getOperand(0);
    2512          68 :         if (ZE.getOpcode() == ISD::ZERO_EXTEND && ZE.getValueType() == MVT::i32) {
    2513          68 :           SDValue BC = ZE.getOperand(0);
    2514          68 :           if (BC.getOpcode() == ISD::BITCAST && BC.getValueType() == MVT::i16) {
    2515          68 :             Arg = BC.getOperand(0);
    2516             :             ReturnF16 = true;
    2517             :           }
    2518             :         }
    2519             :       }
    2520             :     }
    2521             : 
    2522       10151 :     switch (VA.getLocInfo()) {
    2523           0 :     default: llvm_unreachable("Unknown loc info!");
    2524             :     case CCValAssign::Full: break;
    2525        2252 :     case CCValAssign::BCvt:
    2526        2252 :       if (!ReturnF16)
    2527        2252 :         Arg = DAG.getNode(ISD::BITCAST, dl, VA.getLocVT(), Arg);
    2528             :       break;
    2529             :     }
    2530             : 
    2531       10151 :     if (VA.needsCustom()) {
    2532        1768 :       if (VA.getLocVT() == MVT::v2f64) {
    2533             :         // Extract the first half and return it in two registers.
    2534             :         SDValue Half = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg,
    2535        1582 :                                    DAG.getConstant(0, dl, MVT::i32));
    2536             :         SDValue HalfGPRs = DAG.getNode(ARMISD::VMOVRRD, dl,
    2537         791 :                                        DAG.getVTList(MVT::i32, MVT::i32), Half);
    2538             : 
    2539         791 :         Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(),
    2540             :                                  HalfGPRs.getValue(isLittleEndian ? 0 : 1),
    2541         791 :                                  Flag);
    2542         791 :         Flag = Chain.getValue(1);
    2543         791 :         RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
    2544        1582 :         VA = RVLocs[++i]; // skip ahead to next loc
    2545         791 :         Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(),
    2546             :                                  HalfGPRs.getValue(isLittleEndian ? 1 : 0),
    2547         791 :                                  Flag);
    2548         791 :         Flag = Chain.getValue(1);
    2549         791 :         RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
    2550        1582 :         VA = RVLocs[++i]; // skip ahead to next loc
    2551             : 
    2552             :         // Extract the 2nd half and fall through to handle it as an f64 value.
    2553         791 :         Arg = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg,
    2554        1582 :                           DAG.getConstant(1, dl, MVT::i32));
    2555             :       }
    2556             :       // Legalize ret f64 -> ret 2 x i32.  We always have fmrrd if f64 is
    2557             :       // available.
    2558             :       SDValue fmrrd = DAG.getNode(ARMISD::VMOVRRD, dl,
    2559        1768 :                                   DAG.getVTList(MVT::i32, MVT::i32), Arg);
    2560        1768 :       Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(),
    2561             :                                fmrrd.getValue(isLittleEndian ? 0 : 1),
    2562        1768 :                                Flag);
    2563        1768 :       Flag = Chain.getValue(1);
    2564        1768 :       RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
    2565        3536 :       VA = RVLocs[++i]; // skip ahead to next loc
    2566        1768 :       Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(),
    2567             :                                fmrrd.getValue(isLittleEndian ? 1 : 0),
    2568        1768 :                                Flag);
    2569             :     } else
    2570        8383 :       Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), Arg, Flag);
    2571             : 
    2572             :     // Guarantee that all emitted copies are
    2573             :     // stuck together, avoiding something bad.
    2574       10151 :     Flag = Chain.getValue(1);
    2575       10151 :     RetOps.push_back(DAG.getRegister(VA.getLocReg(),
    2576       30453 :                                      ReturnF16 ? MVT::f16 : VA.getLocVT()));
    2577             :   }
    2578       12595 :   const ARMBaseRegisterInfo *TRI = Subtarget->getRegisterInfo();
    2579             :   const MCPhysReg *I =
    2580       12595 :       TRI->getCalleeSavedRegsViaCopy(&DAG.getMachineFunction());
    2581       12595 :   if (I) {
    2582        1185 :     for (; *I; ++I) {
    2583        1170 :       if (ARM::GPRRegClass.contains(*I))
    2584         105 :         RetOps.push_back(DAG.getRegister(*I, MVT::i32));
    2585         960 :       else if (ARM::DPRRegClass.contains(*I))
    2586         480 :         RetOps.push_back(DAG.getRegister(*I, MVT::getFloatingPointVT(64)));
    2587             :       else
    2588           0 :         llvm_unreachable("Unexpected register class in CSRsViaCopy!");
    2589             :     }
    2590             :   }
    2591             : 
    2592             :   // Update chain and glue.
    2593       12595 :   RetOps[0] = Chain;
    2594       12595 :   if (Flag.getNode())
    2595        9221 :     RetOps.push_back(Flag);
    2596             : 
    2597             :   // CPUs which aren't M-class use a special sequence to return from
    2598             :   // exceptions (roughly, any instruction setting pc and cpsr simultaneously,
    2599             :   // though we use "subs pc, lr, #N").
    2600             :   //
    2601             :   // M-class CPUs actually use a normal return sequence with a special
    2602             :   // (hardware-provided) value in LR, so the normal code path works.
    2603       25208 :   if (DAG.getMachineFunction().getFunction().hasFnAttribute("interrupt") &&
    2604          18 :       !Subtarget->isMClass()) {
    2605          12 :     if (Subtarget->isThumb1Only())
    2606           0 :       report_fatal_error("interrupt attribute is not supported in Thumb1");
    2607          12 :     return LowerInterruptReturn(RetOps, dl, DAG);
    2608             :   }
    2609             : 
    2610       12583 :   return DAG.getNode(ARMISD::RET_FLAG, dl, MVT::Other, RetOps);
    2611             : }
    2612             : 
    2613         905 : bool ARMTargetLowering::isUsedByReturnOnly(SDNode *N, SDValue &Chain) const {
    2614         905 :   if (N->getNumValues() != 1)
    2615             :     return false;
    2616         905 :   if (!N->hasNUsesOfValue(1, 0))
    2617             :     return false;
    2618             : 
    2619         881 :   SDValue TCChain = Chain;
    2620         881 :   SDNode *Copy = *N->use_begin();
    2621        1762 :   if (Copy->getOpcode() == ISD::CopyToReg) {
    2622             :     // If the copy has a glue operand, we conservatively assume it isn't safe to
    2623             :     // perform a tail call.
    2624         732 :     if (Copy->getOperand(Copy->getNumOperands()-1).getValueType() == MVT::Glue)
    2625             :       return false;
    2626         237 :     TCChain = Copy->getOperand(0);
    2627         637 :   } else if (Copy->getOpcode() == ARMISD::VMOVRRD) {
    2628             :     SDNode *VMov = Copy;
    2629             :     // f64 returned in a pair of GPRs.
    2630             :     SmallPtrSet<SDNode*, 2> Copies;
    2631          22 :     for (SDNode::use_iterator UI = VMov->use_begin(), UE = VMov->use_end();
    2632          66 :          UI != UE; ++UI) {
    2633          44 :       if (UI->getOpcode() != ISD::CopyToReg)
    2634             :         return false;
    2635          44 :       Copies.insert(*UI);
    2636             :     }
    2637          44 :     if (Copies.size() > 2)
    2638             :       return false;
    2639             : 
    2640          22 :     for (SDNode::use_iterator UI = VMov->use_begin(), UE = VMov->use_end();
    2641          66 :          UI != UE; ++UI) {
    2642          44 :       SDValue UseChain = UI->getOperand(0);
    2643          44 :       if (Copies.count(UseChain.getNode()))
    2644             :         // Second CopyToReg
    2645             :         Copy = *UI;
    2646             :       else {
    2647             :         // We are at the top of this chain.
    2648             :         // If the copy has a glue operand, we conservatively assume it
    2649             :         // isn't safe to perform a tail call.
    2650          66 :         if (UI->getOperand(UI->getNumOperands()-1).getValueType() == MVT::Glue)
    2651             :           return false;
    2652             :         // First CopyToReg
    2653             :         TCChain = UseChain;
    2654             :       }
    2655             :     }
    2656         615 :   } else if (Copy->getOpcode() == ISD::BITCAST) {
    2657             :     // f32 returned in a single GPR.
    2658             :     if (!Copy->hasOneUse())
    2659             :       return false;
    2660             :     Copy = *Copy->use_begin();
    2661          46 :     if (Copy->getOpcode() != ISD::CopyToReg || !Copy->hasNUsesOfValue(1, 0))
    2662             :       return false;
    2663             :     // If the copy has a glue operand, we conservatively assume it isn't safe to
    2664             :     // perform a tail call.
    2665         132 :     if (Copy->getOperand(Copy->getNumOperands()-1).getValueType() == MVT::Glue)
    2666             :       return false;
    2667          42 :     TCChain = Copy->getOperand(0);
    2668             :   } else {
    2669             :     return false;
    2670             :   }
    2671             : 
    2672             :   bool HasRet = false;
    2673         301 :   for (SDNode::use_iterator UI = Copy->use_begin(), UE = Copy->use_end();
    2674         797 :        UI != UE; ++UI) {
    2675        1096 :     if (UI->getOpcode() != ARMISD::RET_FLAG &&
    2676             :         UI->getOpcode() != ARMISD::INTRET_FLAG)
    2677             :       return false;
    2678             :     HasRet = true;
    2679             :   }
    2680             : 
    2681         249 :   if (!HasRet)
    2682             :     return false;
    2683             : 
    2684         248 :   Chain = TCChain;
    2685         248 :   return true;
    2686             : }
    2687             : 
    2688         124 : bool ARMTargetLowering::mayBeEmittedAsTailCall(const CallInst *CI) const {
    2689         124 :   if (!Subtarget->supportsTailCall())
    2690             :     return false;
    2691             : 
    2692             :   auto Attr =
    2693         206 :       CI->getParent()->getParent()->getFnAttribute("disable-tail-calls");
    2694         103 :   if (!CI->isTailCall() || Attr.getValueAsString() == "true")
    2695             :     return false;
    2696             : 
    2697             :   return true;
    2698             : }
    2699             : 
    2700             : // Trying to write a 64 bit value so need to split into two 32 bit values first,
    2701             : // and pass the lower and high parts through.
    2702           2 : static SDValue LowerWRITE_REGISTER(SDValue Op, SelectionDAG &DAG) {
    2703             :   SDLoc DL(Op);
    2704           2 :   SDValue WriteValue = Op->getOperand(2);
    2705             : 
    2706             :   // This function is only supposed to be called for i64 type argument.
    2707             :   assert(WriteValue.getValueType() == MVT::i64
    2708             :           && "LowerWRITE_REGISTER called for non-i64 type argument.");
    2709             : 
    2710             :   SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, WriteValue,
    2711           4 :                            DAG.getConstant(0, DL, MVT::i32));
    2712             :   SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, WriteValue,
    2713           4 :                            DAG.getConstant(1, DL, MVT::i32));
    2714           2 :   SDValue Ops[] = { Op->getOperand(0), Op->getOperand(1), Lo, Hi };
    2715           4 :   return DAG.getNode(ISD::WRITE_REGISTER, DL, MVT::Other, Ops);
    2716             : }
    2717             : 
    2718             : // ConstantPool, JumpTable, GlobalAddress, and ExternalSymbol are lowered as
    2719             : // their target counterpart wrapped in the ARMISD::Wrapper node. Suppose N is
    2720             : // one of the above mentioned nodes. It has to be wrapped because otherwise
    2721             : // Select(N) returns N. So the raw TargetGlobalAddress nodes, etc. can only
    2722             : // be used to form addressing mode. These wrapped nodes will be selected
    2723             : // into MOVi.
    2724        1233 : SDValue ARMTargetLowering::LowerConstantPool(SDValue Op,
    2725             :                                              SelectionDAG &DAG) const {
    2726             :   EVT PtrVT = Op.getValueType();
    2727             :   // FIXME there is no actual debug info here
    2728             :   SDLoc dl(Op);
    2729             :   ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
    2730        1233 :   SDValue Res;
    2731             : 
    2732             :   // When generating execute-only code Constant Pools must be promoted to the
    2733             :   // global data section. It's a bit ugly that we can't share them across basic
    2734             :   // blocks, but this way we guarantee that execute-only behaves correct with
    2735             :   // position-independent addressing modes.
    2736        1233 :   if (Subtarget->genExecuteOnly()) {
    2737           6 :     auto AFI = DAG.getMachineFunction().getInfo<ARMFunctionInfo>();
    2738           6 :     auto T = const_cast<Type*>(CP->getType());
    2739           6 :     auto C = const_cast<Constant*>(CP->getConstVal());
    2740           6 :     auto M = const_cast<Module*>(DAG.getMachineFunction().
    2741           6 :                                  getFunction().getParent());
    2742             :     auto GV = new GlobalVariable(
    2743             :                     *M, T, /*isConst=*/true, GlobalVariable::InternalLinkage, C,
    2744          12 :                     Twine(DAG.getDataLayout().getPrivateGlobalPrefix()) + "CP" +
    2745          18 :                     Twine(DAG.getMachineFunction().getFunctionNumber()) + "_" +
    2746           6 :                     Twine(AFI->createPICLabelUId())
    2747           6 :                   );
    2748             :     SDValue GA = DAG.getTargetGlobalAddress(dyn_cast<GlobalValue>(GV),
    2749           6 :                                             dl, PtrVT);
    2750           6 :     return LowerGlobalAddress(GA, DAG);
    2751             :   }
    2752             : 
    2753        1227 :   if (CP->isMachineConstantPoolEntry())
    2754           0 :     Res = DAG.getTargetConstantPool(CP->getMachineCPVal(), PtrVT,
    2755           0 :                                     CP->getAlignment());
    2756             :   else
    2757        1227 :     Res = DAG.getTargetConstantPool(CP->getConstVal(), PtrVT,
    2758        1227 :                                     CP->getAlignment());
    2759        1227 :   return DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Res);
    2760             : }
    2761             : 
    2762          37 : unsigned ARMTargetLowering::getJumpTableEncoding() const {
    2763          37 :   return MachineJumpTableInfo::EK_Inline;
    2764             : }
    2765             : 
    2766          37 : SDValue ARMTargetLowering::LowerBlockAddress(SDValue Op,
    2767             :                                              SelectionDAG &DAG) const {
    2768          37 :   MachineFunction &MF = DAG.getMachineFunction();
    2769          37 :   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
    2770             :   unsigned ARMPCLabelIndex = 0;
    2771             :   SDLoc DL(Op);
    2772          37 :   EVT PtrVT = getPointerTy(DAG.getDataLayout());
    2773          37 :   const BlockAddress *BA = cast<BlockAddressSDNode>(Op)->getBlockAddress();
    2774          37 :   SDValue CPAddr;
    2775          37 :   bool IsPositionIndependent = isPositionIndependent() || Subtarget->isROPI();
    2776             :   if (!IsPositionIndependent) {
    2777          19 :     CPAddr = DAG.getTargetConstantPool(BA, PtrVT, 4);
    2778             :   } else {
    2779          18 :     unsigned PCAdj = Subtarget->isThumb() ? 4 : 8;
    2780             :     ARMPCLabelIndex = AFI->createPICLabelUId();
    2781             :     ARMConstantPoolValue *CPV =
    2782          18 :       ARMConstantPoolConstant::Create(BA, ARMPCLabelIndex,
    2783          18 :                                       ARMCP::CPBlockAddress, PCAdj);
    2784          18 :     CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4);
    2785             :   }
    2786          37 :   CPAddr = DAG.getNode(ARMISD::Wrapper, DL, PtrVT, CPAddr);
    2787             :   SDValue Result = DAG.getLoad(
    2788             :       PtrVT, DL, DAG.getEntryNode(), CPAddr,
    2789          74 :       MachinePointerInfo::getConstantPool(DAG.getMachineFunction()));
    2790          37 :   if (!IsPositionIndependent)
    2791          19 :     return Result;
    2792          18 :   SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, DL, MVT::i32);
    2793          18 :   return DAG.getNode(ARMISD::PIC_ADD, DL, PtrVT, Result, PICLabel);
    2794             : }
    2795             : 
    2796             : /// Convert a TLS address reference into the correct sequence of loads
    2797             : /// and calls to compute the variable's address for Darwin, and return an
    2798             : /// SDValue containing the final node.
    2799             : 
    2800             : /// Darwin only has one TLS scheme which must be capable of dealing with the
    2801             : /// fully general situation, in the worst case. This means:
    2802             : ///     + "extern __thread" declaration.
    2803             : ///     + Defined in a possibly unknown dynamic library.
    2804             : ///
    2805             : /// The general system is that each __thread variable has a [3 x i32] descriptor
    2806             : /// which contains information used by the runtime to calculate the address. The
    2807             : /// only part of this the compiler needs to know about is the first word, which
    2808             : /// contains a function pointer that must be called with the address of the
    2809             : /// entire descriptor in "r0".
    2810             : ///
    2811             : /// Since this descriptor may be in a different unit, in general access must
    2812             : /// proceed along the usual ARM rules. A common sequence to produce is:
    2813             : ///
    2814             : ///     movw rT1, :lower16:_var$non_lazy_ptr
    2815             : ///     movt rT1, :upper16:_var$non_lazy_ptr
    2816             : ///     ldr r0, [rT1]
    2817             : ///     ldr rT2, [r0]
    2818             : ///     blx rT2
    2819             : ///     [...address now in r0...]
    2820             : SDValue
    2821          79 : ARMTargetLowering::LowerGlobalTLSAddressDarwin(SDValue Op,
    2822             :                                                SelectionDAG &DAG) const {
    2823             :   assert(Subtarget->isTargetDarwin() &&
    2824             :          "This function expects a Darwin target");
    2825             :   SDLoc DL(Op);
    2826             : 
    2827             :   // First step is to get the address of the actua global symbol. This is where
    2828             :   // the TLS descriptor lives.
    2829          79 :   SDValue DescAddr = LowerGlobalAddressDarwin(Op, DAG);
    2830             : 
    2831             :   // The first entry in the descriptor is a function pointer that we must call
    2832             :   // to obtain the address of the variable.
    2833          79 :   SDValue Chain = DAG.getEntryNode();
    2834             :   SDValue FuncTLVGet = DAG.getLoad(
    2835             :       MVT::i32, DL, Chain, DescAddr,
    2836             :       MachinePointerInfo::getGOT(DAG.getMachineFunction()),
    2837             :       /* Alignment = */ 4,
    2838             :       MachineMemOperand::MONonTemporal | MachineMemOperand::MODereferenceable |
    2839         158 :           MachineMemOperand::MOInvariant);
    2840          79 :   Chain = FuncTLVGet.getValue(1);
    2841             : 
    2842          79 :   MachineFunction &F = DAG.getMachineFunction();
    2843          79 :   MachineFrameInfo &MFI = F.getFrameInfo();
    2844             :   MFI.setAdjustsStack(true);
    2845             : 
    2846             :   // TLS calls preserve all registers except those that absolutely must be
    2847             :   // trashed: R0 (it takes an argument), LR (it's a call) and CPSR (let's not be
    2848             :   // silly).
    2849             :   auto TRI =
    2850          79 :       getTargetMachine().getSubtargetImpl(F.getFunction())->getRegisterInfo();
    2851             :   auto ARI = static_cast<const ARMRegisterInfo *>(TRI);
    2852          79 :   const uint32_t *Mask = ARI->getTLSCallPreservedMask(DAG.getMachineFunction());
    2853             : 
    2854             :   // Finally, we can make the call. This is just a degenerate version of a
    2855             :   // normal AArch64 call node: r0 takes the address of the descriptor, and
    2856             :   // returns the address of the variable in this thread.
    2857          79 :   Chain = DAG.getCopyToReg(Chain, DL, ARM::R0, DescAddr, SDValue());
    2858          79 :   Chain =
    2859         158 :       DAG.getNode(ARMISD::CALL, DL, DAG.getVTList(MVT::Other, MVT::Glue),
    2860             :                   Chain, FuncTLVGet, DAG.getRegister(ARM::R0, MVT::i32),
    2861         316 :                   DAG.getRegisterMask(Mask), Chain.getValue(1));
    2862         158 :   return DAG.getCopyFromReg(Chain, DL, ARM::R0, MVT::i32, Chain.getValue(1));
    2863             : }
    2864             : 
    2865             : SDValue
    2866           7 : ARMTargetLowering::LowerGlobalTLSAddressWindows(SDValue Op,
    2867             :                                                 SelectionDAG &DAG) const {
    2868             :   assert(Subtarget->isTargetWindows() && "Windows specific TLS lowering");
    2869             : 
    2870           7 :   SDValue Chain = DAG.getEntryNode();
    2871           7 :   EVT PtrVT = getPointerTy(DAG.getDataLayout());
    2872             :   SDLoc DL(Op);
    2873             : 
    2874             :   // Load the current TEB (thread environment block)
    2875             :   SDValue Ops[] = {Chain,
    2876           7 :                    DAG.getConstant(Intrinsic::arm_mrc, DL, MVT::i32),
    2877           7 :                    DAG.getConstant(15, DL, MVT::i32),
    2878           7 :                    DAG.getConstant(0, DL, MVT::i32),
    2879           7 :                    DAG.getConstant(13, DL, MVT::i32),
    2880           7 :                    DAG.getConstant(0, DL, MVT::i32),
    2881          49 :                    DAG.getConstant(2, DL, MVT::i32)};
    2882             :   SDValue CurrentTEB = DAG.getNode(ISD::INTRINSIC_W_CHAIN, DL,
    2883           7 :                                    DAG.getVTList(MVT::i32, MVT::Other), Ops);
    2884             : 
    2885           7 :   SDValue TEB = CurrentTEB.getValue(0);
    2886             :   Chain = CurrentTEB.getValue(1);
    2887             : 
    2888             :   // Load the ThreadLocalStoragePointer from the TEB
    2889             :   // A pointer to the TLS array is located at offset 0x2c from the TEB.
    2890             :   SDValue TLSArray =
    2891           7 :       DAG.getNode(ISD::ADD, DL, PtrVT, TEB, DAG.getIntPtrConstant(0x2c, DL));
    2892           7 :   TLSArray = DAG.getLoad(PtrVT, DL, Chain, TLSArray, MachinePointerInfo());
    2893             : 
    2894             :   // The pointer to the thread's TLS data area is at the TLS Index scaled by 4
    2895             :   // offset into the TLSArray.
    2896             : 
    2897             :   // Load the TLS index from the C runtime
    2898             :   SDValue TLSIndex =
    2899           7 :       DAG.getTargetExternalSymbol("_tls_index", PtrVT, ARMII::MO_NO_FLAG);
    2900           7 :   TLSIndex = DAG.getNode(ARMISD::Wrapper, DL, PtrVT, TLSIndex);
    2901           7 :   TLSIndex = DAG.getLoad(PtrVT, DL, Chain, TLSIndex, MachinePointerInfo());
    2902             : 
    2903             :   SDValue Slot = DAG.getNode(ISD::SHL, DL, PtrVT, TLSIndex,
    2904           7 :                               DAG.getConstant(2, DL, MVT::i32));
    2905             :   SDValue TLS = DAG.getLoad(PtrVT, DL, Chain,
    2906             :                             DAG.getNode(ISD::ADD, DL, PtrVT, TLSArray, Slot),
    2907           7 :                             MachinePointerInfo());
    2908             : 
    2909             :   // Get the offset of the start of the .tls section (section base)
    2910             :   const auto *GA = cast<GlobalAddressSDNode>(Op);
    2911           7 :   auto *CPV = ARMConstantPoolConstant::Create(GA->getGlobal(), ARMCP::SECREL);
    2912             :   SDValue Offset = DAG.getLoad(
    2913             :       PtrVT, DL, Chain, DAG.getNode(ARMISD::Wrapper, DL, MVT::i32,
    2914             :                                     DAG.getTargetConstantPool(CPV, PtrVT, 4)),
    2915          14 :       MachinePointerInfo::getConstantPool(DAG.getMachineFunction()));
    2916             : 
    2917          14 :   return DAG.getNode(ISD::ADD, DL, PtrVT, TLS, Offset);
    2918             : }
    2919             : 
    2920             : // Lower ISD::GlobalTLSAddress using the "general dynamic" model
    2921             : SDValue
    2922          15 : ARMTargetLowering::LowerToTLSGeneralDynamicModel(GlobalAddressSDNode *GA,
    2923             :                                                  SelectionDAG &DAG) const {
    2924             :   SDLoc dl(GA);
    2925          15 :   EVT PtrVT = getPointerTy(DAG.getDataLayout());
    2926          15 :   unsigned char PCAdj = Subtarget->isThumb() ? 4 : 8;
    2927          15 :   MachineFunction &MF = DAG.getMachineFunction();
    2928          15 :   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
    2929             :   unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
    2930             :   ARMConstantPoolValue *CPV =
    2931          15 :     ARMConstantPoolConstant::Create(GA->getGlobal(), ARMPCLabelIndex,
    2932          15 :                                     ARMCP::CPValue, PCAdj, ARMCP::TLSGD, true);
    2933          15 :   SDValue Argument = DAG.getTargetConstantPool(CPV, PtrVT, 4);
    2934          15 :   Argument = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Argument);
    2935          15 :   Argument = DAG.getLoad(
    2936             :       PtrVT, dl, DAG.getEntryNode(), Argument,
    2937          30 :       MachinePointerInfo::getConstantPool(DAG.getMachineFunction()));
    2938             :   SDValue Chain = Argument.getValue(1);
    2939             : 
    2940          15 :   SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, dl, MVT::i32);
    2941          15 :   Argument = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Argument, PICLabel);
    2942             : 
    2943             :   // call __tls_get_addr.
    2944             :   ArgListTy Args;
    2945             :   ArgListEntry Entry;
    2946          15 :   Entry.Node = Argument;
    2947          15 :   Entry.Ty = (Type *) Type::getInt32Ty(*DAG.getContext());
    2948          15 :   Args.push_back(Entry);
    2949             : 
    2950             :   // FIXME: is there useful debug info available here?
    2951          30 :   TargetLowering::CallLoweringInfo CLI(DAG);
    2952          15 :   CLI.setDebugLoc(dl).setChain(Chain).setLibCallee(
    2953          15 :       CallingConv::C, Type::getInt32Ty(*DAG.getContext()),
    2954          15 :       DAG.getExternalSymbol("__tls_get_addr", PtrVT), std::move(Args));
    2955             : 
    2956          15 :   std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI);
    2957          30 :   return CallResult.first;
    2958             : }
    2959             : 
    2960             : // Lower ISD::GlobalTLSAddress using the "initial exec" or
    2961             : // "local exec" model.
    2962             : SDValue
    2963          39 : ARMTargetLowering::LowerToTLSExecModels(GlobalAddressSDNode *GA,
    2964             :                                         SelectionDAG &DAG,
    2965             :                                         TLSModel::Model model) const {
    2966          39 :   const GlobalValue *GV = GA->getGlobal();
    2967             :   SDLoc dl(GA);
    2968          39 :   SDValue Offset;
    2969          39 :   SDValue Chain = DAG.getEntryNode();
    2970          39 :   EVT PtrVT = getPointerTy(DAG.getDataLayout());
    2971             :   // Get the Thread Pointer
    2972          39 :   SDValue ThreadPointer = DAG.getNode(ARMISD::THREAD_POINTER, dl, PtrVT);
    2973             : 
    2974          39 :   if (model == TLSModel::InitialExec) {
    2975          18 :     MachineFunction &MF = DAG.getMachineFunction();
    2976          18 :     ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
    2977             :     unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
    2978             :     // Initial exec model.
    2979          18 :     unsigned char PCAdj = Subtarget->isThumb() ? 4 : 8;
    2980             :     ARMConstantPoolValue *CPV =
    2981          18 :       ARMConstantPoolConstant::Create(GA->getGlobal(), ARMPCLabelIndex,
    2982             :                                       ARMCP::CPValue, PCAdj, ARMCP::GOTTPOFF,
    2983          18 :                                       true);
    2984          18 :     Offset = DAG.getTargetConstantPool(CPV, PtrVT, 4);
    2985          18 :     Offset = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Offset);
    2986          18 :     Offset = DAG.getLoad(
    2987             :         PtrVT, dl, Chain, Offset,
    2988          36 :         MachinePointerInfo::getConstantPool(DAG.getMachineFunction()));
    2989          18 :     Chain = Offset.getValue(1);
    2990             : 
    2991          18 :     SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, dl, MVT::i32);
    2992          18 :     Offset = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Offset, PICLabel);
    2993             : 
    2994          18 :     Offset = DAG.getLoad(
    2995             :         PtrVT, dl, Chain, Offset,
    2996          36 :         MachinePointerInfo::getConstantPool(DAG.getMachineFunction()));
    2997             :   } else {
    2998             :     // local exec model
    2999             :     assert(model == TLSModel::LocalExec);
    3000             :     ARMConstantPoolValue *CPV =
    3001          21 :       ARMConstantPoolConstant::Create(GV, ARMCP::TPOFF);
    3002          21 :     Offset = DAG.getTargetConstantPool(CPV, PtrVT, 4);
    3003          21 :     Offset = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Offset);
    3004          21 :     Offset = DAG.getLoad(
    3005             :         PtrVT, dl, Chain, Offset,
    3006          42 :         MachinePointerInfo::getConstantPool(DAG.getMachineFunction()));
    3007             :   }
    3008             : 
    3009             :   // The address of the thread local variable is the add of the thread
    3010             :   // pointer with the offset of the variable.
    3011          78 :   return DAG.getNode(ISD::ADD, dl, PtrVT, ThreadPointer, Offset);
    3012             : }
    3013             : 
    3014             : SDValue
    3015         219 : ARMTargetLowering::LowerGlobalTLSAddress(SDValue Op, SelectionDAG &DAG) const {
    3016             :   GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
    3017         219 :   if (DAG.getTarget().useEmulatedTLS())
    3018          79 :     return LowerToTLSEmulatedModel(GA, DAG);
    3019             : 
    3020         140 :   if (Subtarget->isTargetDarwin())
    3021          79 :     return LowerGlobalTLSAddressDarwin(Op, DAG);
    3022             : 
    3023          61 :   if (Subtarget->isTargetWindows())
    3024           7 :     return LowerGlobalTLSAddressWindows(Op, DAG);
    3025             : 
    3026             :   // TODO: implement the "local dynamic" model
    3027             :   assert(Subtarget->isTargetELF() && "Only ELF implemented here");
    3028          54 :   TLSModel::Model model = getTargetMachine().getTLSModel(GA->getGlobal());
    3029             : 
    3030          54 :   switch (model) {
    3031          15 :     case TLSModel::GeneralDynamic:
    3032             :     case TLSModel::LocalDynamic:
    3033          15 :       return LowerToTLSGeneralDynamicModel(GA, DAG);
    3034          39 :     case TLSModel::InitialExec:
    3035             :     case TLSModel::LocalExec:
    3036          39 :       return LowerToTLSExecModels(GA, DAG, model);
    3037             :   }
    3038           0 :   llvm_unreachable("bogus TLS model");
    3039             : }
    3040             : 
    3041             : /// Return true if all users of V are within function F, looking through
    3042             : /// ConstantExprs.
    3043         130 : static bool allUsersAreInFunction(const Value *V, const Function *F) {
    3044             :   SmallVector<const User*,4> Worklist;
    3045         394 :   for (auto *U : V->users())
    3046         132 :     Worklist.push_back(U);
    3047         340 :   while (!Worklist.empty()) {
    3048             :     auto *U = Worklist.pop_back_val();
    3049         308 :     if (isa<ConstantExpr>(U)) {
    3050         675 :       for (auto *UU : U->users())
    3051         273 :         Worklist.push_back(UU);
    3052         129 :       continue;
    3053             :     }
    3054             : 
    3055             :     auto *I = dyn_cast<Instruction>(U);
    3056         167 :     if (!I || I->getParent()->getParent() != F)
    3057             :       return false;
    3058             :   }
    3059             :   return true;
    3060             : }
    3061             : 
    3062             : /// Return true if all users of V are within some (any) function, looking through
    3063             : /// ConstantExprs. In other words, are there any global constant users?
    3064          74 : static bool allUsersAreInFunctions(const Value *V) {
    3065             :   SmallVector<const User*,4> Worklist;
    3066         226 :   for (auto *U : V->users())
    3067          76 :     Worklist.push_back(U);
    3068         310 :   while (!Worklist.empty()) {
    3069             :     auto *U = Worklist.pop_back_val();
    3070         248 :     if (isa<ConstantExpr>(U)) {
    3071         444 :       for (auto *UU : U->users())
    3072         184 :         Worklist.push_back(UU);
    3073          76 :       continue;
    3074             :     }
    3075             : 
    3076         172 :     if (!isa<Instruction>(U))
    3077             :       return false;
    3078             :   }
    3079             :   return true;
    3080             : }
    3081             : 
    3082             : // Return true if T is an integer, float or an array/vector of either.
    3083         194 : static bool isSimpleType(Type *T) {
    3084         194 :   if (T->isIntegerTy() || T->isFloatingPointTy())
    3085             :     return true;
    3086             :   Type *SubT = nullptr;
    3087         192 :   if (T->isArrayTy())
    3088         192 :     SubT = T->getArrayElementType();
    3089           0 :   else if (T->isVectorTy())
    3090           0 :     SubT = T->getVectorElementType();
    3091             :   else
    3092             :     return false;
    3093         192 :   return SubT->isIntegerTy() || SubT->isFloatingPointTy();
    3094             : }
    3095             : 
    3096        1309 : static SDValue promoteToConstantPool(const GlobalValue *GV, SelectionDAG &DAG,
    3097             :                                      EVT PtrVT, const SDLoc &dl) {
    3098             :   // If we're creating a pool entry for a constant global with unnamed address,
    3099             :   // and the global is small enough, we can emit it inline into the constant pool
    3100             :   // to save ourselves an indirection.
    3101             :   //
    3102             :   // This is a win if the constant is only used in one function (so it doesn't
    3103             :   // need to be duplicated) or duplicating the constant wouldn't increase code
    3104             :   // size (implying the constant is no larger than 4 bytes).
    3105        1309 :   const Function &F = DAG.getMachineFunction().getFunction();
    3106             :   
    3107             :   // We rely on this decision to inline being idemopotent and unrelated to the
    3108             :   // use-site. We know that if we inline a variable at one use site, we'll
    3109             :   // inline it elsewhere too (and reuse the constant pool entry). Fast-isel
    3110             :   // doesn't know about this optimization, so bail out if it's enabled else
    3111             :   // we could decide to inline here (and thus never emit the GV) but require
    3112             :   // the GV from fast-isel generated code.
    3113        1503 :   if (!EnableConstpoolPromotion ||
    3114         194 :       DAG.getMachineFunction().getTarget().Options.EnableFastISel)
    3115        1115 :       return SDValue();
    3116             : 
    3117             :   auto *GVar = dyn_cast<GlobalVariable>(GV);
    3118         388 :   if (!GVar || !GVar->hasInitializer() ||
    3119         194 :       !GVar->isConstant() || !GVar->hasGlobalUnnamedAddr() ||
    3120             :       !GVar->hasLocalLinkage())
    3121           0 :     return SDValue();
    3122             : 
    3123             :   // Ensure that we don't try and inline any type that contains pointers. If
    3124             :   // we inline a value that contains relocations, we move the relocations from
    3125             :   // .data to .text which is not ideal.
    3126             :   auto *Init = GVar->getInitializer();
    3127         194 :   if (!isSimpleType(Init->getType()))
    3128          12 :     return SDValue();
    3129             : 
    3130             :   // The constant islands pass can only really deal with alignment requests
    3131             :   // <= 4 bytes and cannot pad constants itself. Therefore we cannot promote
    3132             :   // any type wanting greater alignment requirements than 4 bytes. We also
    3133             :   // can only promote constants that are multiples of 4 bytes in size or
    3134             :   // are paddable to a multiple of 4. Currently we only try and pad constants
    3135             :   // that are strings for simplicity.
    3136             :   auto *CDAInit = dyn_cast<ConstantDataArray>(Init);
    3137         364 :   unsigned Size = DAG.getDataLayout().getTypeAllocSize(Init->getType());
    3138             :   unsigned Align = GVar->getAlignment();
    3139         182 :   unsigned RequiredPadding = 4 - (Size % 4);
    3140             :   bool PaddingPossible =
    3141         182 :     RequiredPadding == 4 || (CDAInit && CDAInit->isString());
    3142         336 :   if (!PaddingPossible || Align > 4 || Size > ConstpoolPromotionMaxSize ||
    3143             :       Size == 0)
    3144          52 :     return SDValue();
    3145             : 
    3146         260 :   unsigned PaddedSize = Size + ((RequiredPadding == 4) ? 0 : RequiredPadding);
    3147         130 :   MachineFunction &MF = DAG.getMachineFunction();
    3148         130 :   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
    3149             : 
    3150             :   // We can't bloat the constant pool too much, else the ConstantIslands pass
    3151             :   // may fail to converge. If we haven't promoted this global yet (it may have
    3152             :   // multiple uses), and promoting it would increase the constant pool size (Sz
    3153             :   // > 4), ensure we have space to do so up to MaxTotal.
    3154         130 :   if (!AFI->getGlobalsPromotedToConstantPool().count(GVar) && Size > 4)
    3155         108 :     if (AFI->getPromotedConstpoolIncrease() + PaddedSize - 4 >=
    3156             :         ConstpoolPromotionMaxTotal)
    3157           0 :       return SDValue();
    3158             : 
    3159             :   // This is only valid if all users are in a single function OR it has users
    3160             :   // in multiple functions but it no larger than a pointer. We also check if
    3161             :   // GVar has constant (non-ConstantExpr) users. If so, it essentially has its
    3162             :   // address taken.
    3163         130 :   if (!allUsersAreInFunction(GVar, &F) &&
    3164          74 :       !(Size <= 4 && allUsersAreInFunctions(GVar)))
    3165          36 :     return SDValue();
    3166             : 
    3167             :   // We're going to inline this global. Pad it out if needed.
    3168          94 :   if (RequiredPadding != 4) {
    3169          48 :     StringRef S = CDAInit->getAsString();
    3170             : 
    3171          96 :     SmallVector<uint8_t,16> V(S.size());
    3172             :     std::copy(S.bytes_begin(), S.bytes_end(), V.begin());
    3173         216 :     while (RequiredPadding--)
    3174          84 :       V.push_back(0);
    3175          48 :     Init = ConstantDataArray::get(*DAG.getContext(), V);
    3176             :   }
    3177             : 
    3178          94 :   auto CPVal = ARMConstantPoolConstant::Create(GVar, Init);
    3179             :   SDValue CPAddr =
    3180          94 :     DAG.getTargetConstantPool(CPVal, PtrVT, /*Align=*/4);
    3181          94 :   if (!AFI->getGlobalsPromotedToConstantPool().count(GVar)) {
    3182             :     AFI->markGlobalAsPromotedToConstantPool(GVar);
    3183         188 :     AFI->setPromotedConstpoolIncrease(AFI->getPromotedConstpoolIncrease() +
    3184          94 :                                       PaddedSize - 4);
    3185             :   }
    3186             :   ++NumConstpoolPromoted;
    3187          94 :   return DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
    3188             : }
    3189             : 
    3190        1521 : bool ARMTargetLowering::isReadOnly(const GlobalValue *GV) const {
    3191             :   if (const GlobalAlias *GA = dyn_cast<GlobalAlias>(GV))
    3192           4 :     GV = GA->getBaseObject();
    3193        3019 :   return (isa<GlobalVariable>(GV) && cast<GlobalVariable>(GV)->isConstant()) ||
    3194        1521 :          isa<Function>(GV);
    3195             : }
    3196             : 
    3197        2089 : SDValue ARMTargetLowering::LowerGlobalAddress(SDValue Op,
    3198             :                                               SelectionDAG &DAG) const {
    3199        2089 :   switch (Subtarget->getTargetTriple().getObjectFormat()) {
    3200           0 :   default: llvm_unreachable("unknown object format");
    3201          44 :   case Triple::COFF:
    3202          44 :     return LowerGlobalAddressWindows(Op, DAG);
    3203        1457 :   case Triple::ELF:
    3204        1457 :     return LowerGlobalAddressELF(Op, DAG);
    3205         588 :   case Triple::MachO:
    3206         588 :     return LowerGlobalAddressDarwin(Op, DAG);
    3207             :   }
    3208             : }
    3209             : 
    3210        1457 : SDValue ARMTargetLowering::LowerGlobalAddressELF(SDValue Op,
    3211             :                                                  SelectionDAG &DAG) const {
    3212        1457 :   EVT PtrVT = getPointerTy(DAG.getDataLayout());
    3213             :   SDLoc dl(Op);
    3214        1457 :   const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
    3215        1457 :   const TargetMachine &TM = getTargetMachine();
    3216        1457 :   bool IsRO = isReadOnly(GV);
    3217             : 
    3218             :   // promoteToConstantPool only if not generating XO text section
    3219        1457 :   if (TM.shouldAssumeDSOLocal(*GV->getParent(), GV) && !Subtarget->genExecuteOnly())
    3220        1309 :     if (SDValue V = promoteToConstantPool(GV, DAG, PtrVT, dl))
    3221          94 :       return V;
    3222             : 
    3223        1363 :   if (isPositionIndependent()) {
    3224         110 :     bool UseGOT_PREL = !TM.shouldAssumeDSOLocal(*GV->getParent(), GV);
    3225             :     SDValue G = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0,
    3226         220 :                                            UseGOT_PREL ? ARMII::MO_GOT : 0);
    3227         110 :     SDValue Result = DAG.getNode(ARMISD::WrapperPIC, dl, PtrVT, G);
    3228         110 :     if (UseGOT_PREL)
    3229          58 :       Result =
    3230         116 :           DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Result,
    3231         116 :                       MachinePointerInfo::getGOT(DAG.getMachineFunction()));
    3232         110 :     return Result;
    3233        1253 :   } else if (Subtarget->isROPI() && IsRO) {
    3234             :     // PC-relative.
    3235          51 :     SDValue G = DAG.getTargetGlobalAddress(GV, dl, PtrVT);
    3236          51 :     SDValue Result = DAG.getNode(ARMISD::WrapperPIC, dl, PtrVT, G);
    3237          51 :     return Result;
    3238        1272 :   } else if (Subtarget->isRWPI() && !IsRO) {
    3239             :     // SB-relative.
    3240          30 :     SDValue RelAddr;
    3241          30 :     if (Subtarget->useMovt(DAG.getMachineFunction())) {
    3242             :       ++NumMovwMovt;
    3243          12 :       SDValue G = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, ARMII::MO_SBREL);
    3244          12 :       RelAddr = DAG.getNode(ARMISD::Wrapper, dl, PtrVT, G);
    3245             :     } else { // use literal pool for address constant
    3246             :       ARMConstantPoolValue *CPV =
    3247          18 :         ARMConstantPoolConstant::Create(GV, ARMCP::SBREL);
    3248          18 :       SDValue CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4);
    3249          18 :       CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
    3250          18 :       RelAddr = DAG.getLoad(
    3251             :           PtrVT, dl, DAG.getEntryNode(), CPAddr,
    3252          36 :           MachinePointerInfo::getConstantPool(DAG.getMachineFunction()));
    3253             :     }
    3254          30 :     SDValue SB = DAG.getCopyFromReg(DAG.getEntryNode(), dl, ARM::R9, PtrVT);
    3255          30 :     SDValue Result = DAG.getNode(ISD::ADD, dl, PtrVT, SB, RelAddr);
    3256          30 :     return Result;
    3257             :   }
    3258             : 
    3259             :   // If we have T2 ops, we can materialize the address directly via movt/movw
    3260             :   // pair. This is always cheaper.
    3261        1172 :   if (Subtarget->useMovt(DAG.getMachineFunction())) {
    3262             :     ++NumMovwMovt;
    3263             :     // FIXME: Once remat is capable of dealing with instructions with register
    3264             :     // operands, expand this into two nodes.
    3265             :     return DAG.getNode(ARMISD::Wrapper, dl, PtrVT,
    3266         724 :                        DAG.getTargetGlobalAddress(GV, dl, PtrVT));
    3267             :   } else {
    3268         448 :     SDValue CPAddr = DAG.getTargetConstantPool(GV, PtrVT, 4);
    3269         448 :     CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
    3270             :     return DAG.getLoad(
    3271             :         PtrVT, dl, DAG.getEntryNode(), CPAddr,
    3272         896 :         MachinePointerInfo::getConstantPool(DAG.getMachineFunction()));
    3273             :   }
    3274             : }
    3275             : 
    3276         667 : SDValue ARMTargetLowering::LowerGlobalAddressDarwin(SDValue Op,
    3277             :                                                     SelectionDAG &DAG) const {
    3278             :   assert(!Subtarget->isROPI() && !Subtarget->isRWPI() &&
    3279             :          "ROPI/RWPI not currently supported for Darwin");
    3280         667 :   EVT PtrVT = getPointerTy(DAG.getDataLayout());
    3281             :   SDLoc dl(Op);
    3282         667 :   const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
    3283             : 
    3284         667 :   if (Subtarget->useMovt(DAG.getMachineFunction()))
    3285             :     ++NumMovwMovt;
    3286             : 
    3287             :   // FIXME: Once remat is capable of dealing with instructions with register
    3288             :   // operands, expand this into multiple nodes
    3289             :   unsigned Wrapper =
    3290         667 :       isPositionIndependent() ? ARMISD::WrapperPIC : ARMISD::Wrapper;
    3291             : 
    3292         667 :   SDValue G = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, ARMII::MO_NONLAZY);
    3293         667 :   SDValue Result = DAG.getNode(Wrapper, dl, PtrVT, G);
    3294             : 
    3295         667 :   if (Subtarget->isGVIndirectSymbol(GV))
    3296         376 :     Result = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Result,
    3297         752 :                          MachinePointerInfo::getGOT(DAG.getMachineFunction()));
    3298        1334 :   return Result;
    3299             : }
    3300             : 
    3301          44 : SDValue ARMTargetLowering::LowerGlobalAddressWindows(SDValue Op,
    3302             :                                                      SelectionDAG &DAG) const {
    3303             :   assert(Subtarget->isTargetWindows() && "non-Windows COFF is not supported");
    3304             :   assert(Subtarget->useMovt(DAG.getMachineFunction()) &&
    3305             :          "Windows on ARM expects to use movw/movt");
    3306             :   assert(!Subtarget->isROPI() && !Subtarget->isRWPI() &&
    3307             :          "ROPI/RWPI not currently supported for Windows");
    3308             : 
    3309          44 :   const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
    3310             :   const ARMII::TOF TargetFlags =
    3311          44 :     (GV->hasDLLImportStorageClass() ? ARMII::MO_DLLIMPORT : ARMII::MO_NO_FLAG);
    3312          44 :   EVT PtrVT = getPointerTy(DAG.getDataLayout());
    3313             :   SDValue Result;
    3314             :   SDLoc DL(Op);
    3315             : 
    3316             :   ++NumMovwMovt;
    3317             : 
    3318             :   // FIXME: Once remat is capable of dealing with instructions with register
    3319             :   // operands, expand this into two nodes.
    3320          44 :   Result = DAG.getNode(ARMISD::Wrapper, DL, PtrVT,
    3321             :                        DAG.getTargetGlobalAddress(GV, DL, PtrVT, /*Offset=*/0,
    3322          88 :                                                   TargetFlags));
    3323          44 :   if (GV->hasDLLImportStorageClass())
    3324           2 :     Result = DAG.getLoad(PtrVT, DL, DAG.getEntryNode(), Result,
    3325           4 :                          MachinePointerInfo::getGOT(DAG.getMachineFunction()));
    3326          88 :   return Result;
    3327             : }
    3328             : 
    3329             : SDValue
    3330           8 : ARMTargetLowering::LowerEH_SJLJ_SETJMP(SDValue Op, SelectionDAG &DAG) const {
    3331             :   SDLoc dl(Op);
    3332           8 :   SDValue Val = DAG.getConstant(0, dl, MVT::i32);
    3333             :   return DAG.getNode(ARMISD::EH_SJLJ_SETJMP, dl,
    3334             :                      DAG.getVTList(MVT::i32, MVT::Other), Op.getOperand(0),
    3335          16 :                      Op.getOperand(1), Val);
    3336             : }
    3337             : 
    3338             : SDValue
    3339           9 : ARMTargetLowering::LowerEH_SJLJ_LONGJMP(SDValue Op, SelectionDAG &DAG) const {
    3340             :   SDLoc dl(Op);
    3341             :   return DAG.getNode(ARMISD::EH_SJLJ_LONGJMP, dl, MVT::Other, Op.getOperand(0),
    3342          27 :                      Op.getOperand(1), DAG.getConstant(0, dl, MVT::i32));
    3343             : }
    3344             : 
    3345          32 : SDValue ARMTargetLowering::LowerEH_SJLJ_SETUP_DISPATCH(SDValue Op,
    3346             :                                                       SelectionDAG &DAG) const {
    3347             :   SDLoc dl(Op);
    3348             :   return DAG.getNode(ARMISD::EH_SJLJ_SETUP_DISPATCH, dl, MVT::Other,
    3349          64 :                      Op.getOperand(0));
    3350             : }
    3351             : 
    3352             : SDValue
    3353        2149 : ARMTargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op, SelectionDAG &DAG,
    3354             :                                           const ARMSubtarget *Subtarget) const {
    3355        4298 :   unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
    3356             :   SDLoc dl(Op);
    3357        2149 :   switch (IntNo) {
    3358        2042 :   default: return SDValue();    // Don't custom lower most intrinsics.
    3359           1 :   case Intrinsic::thread_pointer: {
    3360           1 :     EVT PtrVT = getPointerTy(DAG.getDataLayout());
    3361           1 :     return DAG.getNode(ARMISD::THREAD_POINTER, dl, PtrVT);
    3362             :   }
    3363          32 :   case Intrinsic::eh_sjlj_lsda: {
    3364          32 :     MachineFunction &MF = DAG.getMachineFunction();
    3365          32 :     ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
    3366             :     unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
    3367          32 :     EVT PtrVT = getPointerTy(DAG.getDataLayout());
    3368             :     SDValue CPAddr;
    3369          32 :     bool IsPositionIndependent = isPositionIndependent();
    3370          32 :     unsigned PCAdj = IsPositionIndependent ? (Subtarget->isThumb() ? 4 : 8) : 0;
    3371             :     ARMConstantPoolValue *CPV =
    3372          32 :       ARMConstantPoolConstant::Create(&MF.getFunction(), ARMPCLabelIndex,
    3373          32 :                                       ARMCP::CPLSDA, PCAdj);
    3374          32 :     CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4);
    3375          32 :     CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
    3376             :     SDValue Result = DAG.getLoad(
    3377             :         PtrVT, dl, DAG.getEntryNode(), CPAddr,
    3378          64 :         MachinePointerInfo::getConstantPool(DAG.getMachineFunction()));
    3379             : 
    3380          32 :     if (IsPositionIndependent) {
    3381          25 :       SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, dl, MVT::i32);
    3382          25 :       Result = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Result, PICLabel);
    3383             :     }
    3384          32 :     return Result;
    3385             :   }
    3386             :   case Intrinsic::arm_neon_vabs:
    3387          16 :     return DAG.getNode(ISD::ABS, SDLoc(Op), Op.getValueType(),
    3388          32 :                         Op.getOperand(1));
    3389          15 :   case Intrinsic::arm_neon_vmulls:
    3390             :   case Intrinsic::arm_neon_vmullu: {
    3391             :     unsigned NewOpc = (IntNo == Intrinsic::arm_neon_vmulls)
    3392          15 :       ? ARMISD::VMULLs : ARMISD::VMULLu;
    3393          15 :     return DAG.getNode(NewOpc, SDLoc(Op), Op.getValueType(),
    3394          30 :                        Op.getOperand(1), Op.getOperand(2));
    3395             :   }
    3396           4 :   case Intrinsic::arm_neon_vminnm:
    3397             :   case Intrinsic::arm_neon_vmaxnm: {
    3398             :     unsigned NewOpc = (IntNo == Intrinsic::arm_neon_vminnm)
    3399           4 :       ? ISD::FMINNUM : ISD::FMAXNUM;
    3400           4 :     return DAG.getNode(NewOpc, SDLoc(Op), Op.getValueType(),
    3401           8 :                        Op.getOperand(1), Op.getOperand(2));
    3402             :   }
    3403          16 :   case Intrinsic::arm_neon_vminu:
    3404             :   case Intrinsic::arm_neon_vmaxu: {
    3405          16 :     if (Op.getValueType().isFloatingPoint())
    3406           0 :       return SDValue();
    3407             :     unsigned NewOpc = (IntNo == Intrinsic::arm_neon_vminu)
    3408          16 :       ? ISD::UMIN : ISD::UMAX;
    3409          16 :     return DAG.getNode(NewOpc, SDLoc(Op), Op.getValueType(),
    3410          32 :                          Op.getOperand(1), Op.getOperand(2));
    3411             :   }
    3412          18 :   case Intrinsic::arm_neon_vmins:
    3413             :   case Intrinsic::arm_neon_vmaxs: {
    3414             :     // v{min,max}s is overloaded between signed integers and floats.
    3415          18 :     if (!Op.getValueType().isFloatingPoint()) {
    3416             :       unsigned NewOpc = (IntNo == Intrinsic::arm_neon_vmins)
    3417          12 :         ? ISD::SMIN : ISD::SMAX;
    3418          12 :       return DAG.getNode(NewOpc, SDLoc(Op), Op.getValueType(),
    3419          24 :                          Op.getOperand(1), Op.getOperand(2));
    3420             :     }
    3421             :     unsigned NewOpc = (IntNo == Intrinsic::arm_neon_vmins)
    3422           6 :       ? ISD::FMINNAN : ISD::FMAXNAN;
    3423           6 :     return DAG.getNode(NewOpc, SDLoc(Op), Op.getValueType(),
    3424          12 :                        Op.getOperand(1), Op.getOperand(2));
    3425             :   }
    3426             :   case Intrinsic::arm_neon_vtbl1:
    3427           1 :     return DAG.getNode(ARMISD::VTBL1, SDLoc(Op), Op.getValueType(),
    3428           2 :                        Op.getOperand(1), Op.getOperand(2));
    3429             :   case Intrinsic::arm_neon_vtbl2:
    3430           4 :     return DAG.getNode(ARMISD::VTBL2, SDLoc(Op), Op.getValueType(),
    3431           8 :                        Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
    3432             :   }
    3433             : }
    3434             : 
    3435          21 : static SDValue LowerATOMIC_FENCE(SDValue Op, SelectionDAG &DAG,
    3436             :                                  const ARMSubtarget *Subtarget) {
    3437             :   SDLoc dl(Op);
    3438             :   ConstantSDNode *SSIDNode = cast<ConstantSDNode>(Op.getOperand(2));
    3439          42 :   auto SSID = static_cast<SyncScope::ID>(SSIDNode->getZExtValue());
    3440          21 :   if (SSID == SyncScope::SingleThread)
    3441           6 :     return Op;
    3442             : 
    3443          15 :   if (!Subtarget->hasDataBarrier()) {
    3444             :     // Some ARMv6 cpus can support data barriers with an mcr instruction.
    3445             :     // Thumb1 and pre-v6 ARM mode use a libcall instead and should never get
    3446             :     // here.
    3447             :     assert(Subtarget->hasV6Ops() && !Subtarget->isThumb() &&
    3448             :            "Unexpected ISD::ATOMIC_FENCE encountered. Should be libcall!");
    3449             :     return DAG.getNode(ARMISD::MEMBARRIER_MCR, dl, MVT::Other, Op.getOperand(0),
    3450           0 :                        DAG.getConstant(0, dl, MVT::i32));
    3451             :   }
    3452             : 
    3453             :   ConstantSDNode *OrdN = cast<ConstantSDNode>(Op.getOperand(1));
    3454          30 :   AtomicOrdering Ord = static_cast<AtomicOrdering>(OrdN->getZExtValue());
    3455             :   ARM_MB::MemBOpt Domain = ARM_MB::ISH;
    3456          15 :   if (Subtarget->isMClass()) {
    3457             :     // Only a full system barrier exists in the M-class architectures.
    3458             :     Domain = ARM_MB::SY;
    3459          13 :   } else if (Subtarget->preferISHSTBarriers() &&
    3460             :              Ord == AtomicOrdering::Release) {
    3461             :     // Swift happens to implement ISHST barriers in a way that's compatible with
    3462             :     // Release semantics but weaker than ISH so we'd be fools not to use
    3463             :     // it. Beware: other processors probably don't!
    3464             :     Domain = ARM_MB::ISHST;
    3465             :   }
    3466             : 
    3467             :   return DAG.getNode(ISD::INTRINSIC_VOID, dl, MVT::Other, Op.getOperand(0),
    3468             :                      DAG.getConstant(Intrinsic::arm_dmb, dl, MVT::i32),
    3469          45 :                      DAG.getConstant(Domain, dl, MVT::i32));
    3470             : }
    3471             : 
    3472          32 : static SDValue LowerPREFETCH(SDValue Op, SelectionDAG &DAG,
    3473             :                              const ARMSubtarget *Subtarget) {
    3474             :   // ARM pre v5TE and Thumb1 does not have preload instructions.
    3475          32 :   if (!(Subtarget->isThumb2() ||
    3476          16 :         (!Subtarget->isThumb1Only() && Subtarget->hasV5TEOps())))
    3477             :     // Just preserve the chain.
    3478           8 :     return Op.getOperand(0);
    3479             : 
    3480             :   SDLoc dl(Op);
    3481          48 :   unsigned isRead = ~cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue() & 1;
    3482          27 :   if (!isRead &&
    3483           6 :       (!Subtarget->hasV7Ops() || !Subtarget->hasMPExtension()))
    3484             :     // ARMv7 with MP extension has PLDW.
    3485           2 :     return Op.getOperand(0);
    3486             : 
    3487          44 :   unsigned isData = cast<ConstantSDNode>(Op.getOperand(4))->getZExtValue();
    3488          22 :   if (Subtarget->isThumb()) {
    3489             :     // Invert the bits.
    3490           7 :     isRead = ~isRead & 1;
    3491           7 :     isData = ~isData & 1;
    3492             :   }
    3493             : 
    3494             :   return DAG.getNode(ARMISD::PRELOAD, dl, MVT::Other, Op.getOperand(0),
    3495             :                      Op.getOperand(1), DAG.getConstant(isRead, dl, MVT::i32),
    3496          66 :                      DAG.getConstant(isData, dl, MVT::i32));
    3497             : }
    3498             : 
    3499          34 : static SDValue LowerVASTART(SDValue Op, SelectionDAG &DAG) {
    3500          34 :   MachineFunction &MF = DAG.getMachineFunction();
    3501          34 :   ARMFunctionInfo *FuncInfo = MF.getInfo<ARMFunctionInfo>();
    3502             : 
    3503             :   // vastart just stores the address of the VarArgsFrameIndex slot into the
    3504             :   // memory location argument.
    3505             :   SDLoc dl(Op);
    3506          34 :   EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout());
    3507          34 :   SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT);
    3508          34 :   const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
    3509             :   return DAG.getStore(Op.getOperand(0), dl, FR, Op.getOperand(1),
    3510          68 :                       MachinePointerInfo(SV));
    3511             : }
    3512             : 
    3513        1005 : SDValue ARMTargetLowering::GetF64FormalArgument(CCValAssign &VA,
    3514             :                                                 CCValAssign &NextVA,
    3515             :                                                 SDValue &Root,
    3516             :                                                 SelectionDAG &DAG,
    3517             :                                                 const SDLoc &dl) const {
    3518        1005 :   MachineFunction &MF = DAG.getMachineFunction();
    3519        1005 :   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
    3520             : 
    3521             :   const TargetRegisterClass *RC;
    3522        1005 :   if (AFI->isThumb1OnlyFunction())
    3523             :     RC = &ARM::tGPRRegClass;
    3524             :   else
    3525             :     RC = &ARM::GPRRegClass;
    3526             : 
    3527             :   // Transform the arguments stored in physical registers into virtual ones.
    3528        1005 :   unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
    3529        1005 :   SDValue ArgValue = DAG.getCopyFromReg(Root, dl, Reg, MVT::i32);
    3530             : 
    3531             :   SDValue ArgValue2;
    3532        1005 :   if (NextVA.isMemLoc()) {
    3533          29 :     MachineFrameInfo &MFI = MF.getFrameInfo();
    3534          29 :     int FI = MFI.CreateFixedObject(4, NextVA.getLocMemOffset(), true);
    3535             : 
    3536             :     // Create load node to retrieve arguments from the stack.
    3537          58 :     SDValue FIN = DAG.getFrameIndex(FI, getPointerTy(DAG.getDataLayout()));
    3538          29 :     ArgValue2 = DAG.getLoad(
    3539             :         MVT::i32, dl, Root, FIN,
    3540          58 :         MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI));
    3541             :   } else {
    3542         976 :     Reg = MF.addLiveIn(NextVA.getLocReg(), RC);
    3543         976 :     ArgValue2 = DAG.getCopyFromReg(Root, dl, Reg, MVT::i32);
    3544             :   }
    3545        1005 :   if (!Subtarget->isLittle())
    3546             :     std::swap (ArgValue, ArgValue2);
    3547        1005 :   return DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, ArgValue, ArgValue2);
    3548             : }
    3549             : 
    3550             : // The remaining GPRs hold either the beginning of variable-argument
    3551             : // data, or the beginning of an aggregate passed by value (usually
    3552             : // byval).  Either way, we allocate stack slots adjacent to the data
    3553             : // provided by our caller, and store the unallocated registers there.
    3554             : // If this is a variadic function, the va_list pointer will begin with
    3555             : // these values; otherwise, this reassembles a (byval) structure that
    3556             : // was split between registers and memory.
    3557             : // Return: The frame index registers were stored into.
    3558          81 : int ARMTargetLowering::StoreByValRegs(CCState &CCInfo, SelectionDAG &DAG,
    3559             :                                       const SDLoc &dl, SDValue &Chain,
    3560             :                                       const Value *OrigArg,
    3561             :                                       unsigned InRegsParamRecordIdx,
    3562             :                                       int ArgOffset, unsigned ArgSize) const {
    3563             :   // Currently, two use-cases possible:
    3564             :   // Case #1. Non-var-args function, and we meet first byval parameter.
    3565             :   //          Setup first unallocated register as first byval register;
    3566             :   //          eat all remained registers
    3567             :   //          (these two actions are performed by HandleByVal method).
    3568             :   //          Then, here, we initialize stack frame with
    3569             :   //          "store-reg" instructions.
    3570             :   // Case #2. Var-args function, that doesn't contain byval parameters.
    3571             :   //          The same: eat all remained unallocated registers,
    3572             :   //          initialize stack frame.
    3573             : 
    3574          81 :   MachineFunction &MF = DAG.getMachineFunction();
    3575          81 :   MachineFrameInfo &MFI = MF.getFrameInfo();
    3576          81 :   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
    3577             :   unsigned RBegin, REnd;
    3578          81 :   if (InRegsParamRecordIdx < CCInfo.getInRegsParamsCount()) {
    3579             :     CCInfo.getInRegsParamInfo(InRegsParamRecordIdx, RBegin, REnd);
    3580             :   } else {
    3581             :     unsigned RBeginIdx = CCInfo.getFirstUnallocated(GPRArgRegs);
    3582          47 :     RBegin = RBeginIdx == 4 ? (unsigned)ARM::R4 : GPRArgRegs[RBeginIdx];
    3583             :     REnd = ARM::R4;
    3584             :   }
    3585             : 
    3586          81 :   if (REnd != RBegin)
    3587          67 :     ArgOffset = -4 * (ARM::R4 - RBegin);
    3588             : 
    3589          81 :   auto PtrVT = getPointerTy(DAG.getDataLayout());
    3590          81 :   int FrameIndex = MFI.CreateFixedObject(ArgSize, ArgOffset, false);
    3591          81 :   SDValue FIN = DAG.getFrameIndex(FrameIndex, PtrVT);
    3592             : 
    3593             :   SmallVector<SDValue, 4> MemOps;
    3594             :   const TargetRegisterClass *RC =
    3595          81 :       AFI->isThumb1OnlyFunction() ? &ARM::tGPRRegClass : &ARM::GPRRegClass;
    3596             : 
    3597         441 :   for (unsigned Reg = RBegin, i = 0; Reg < REnd; ++Reg, ++i) {
    3598         180 :     unsigned VReg = MF.addLiveIn(Reg, RC);
    3599         180 :     SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i32);
    3600             :     SDValue Store = DAG.getStore(Val.getValue(1), dl, Val, FIN,
    3601         360 :                                  MachinePointerInfo(OrigArg, 4 * i));
    3602         180 :     MemOps.push_back(Store);
    3603         360 :     FIN = DAG.getNode(ISD::ADD, dl, PtrVT, FIN, DAG.getConstant(4, dl, PtrVT));
    3604             :   }
    3605             : 
    3606          81 :   if (!MemOps.empty())
    3607          67 :     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOps);
    3608          81 :   return FrameIndex;
    3609             : }
    3610             : 
    3611             : // Setup stack frame, the va_list pointer will start from.
    3612          34 : void ARMTargetLowering::VarArgStyleRegisters(CCState &CCInfo, SelectionDAG &DAG,
    3613             :                                              const SDLoc &dl, SDValue &Chain,
    3614             :                                              unsigned ArgOffset,
    3615             :                                              unsigned TotalArgRegsSaveSize,
    3616             :                                              bool ForceMutable) const {
    3617          34 :   MachineFunction &MF = DAG.getMachineFunction();
    3618          34 :   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
    3619             : 
    3620             :   // Try to store any remaining integer argument regs
    3621             :   // to their spots on the stack so that they may be loaded by dereferencing
    3622             :   // the result of va_next.
    3623             :   // If there is no regs to be stored, just point address after last
    3624             :   // argument passed via stack.
    3625          34 :   int FrameIndex = StoreByValRegs(CCInfo, DAG, dl, Chain, nullptr,
    3626             :                                   CCInfo.getInRegsParamsCount(),
    3627          68 :                                   CCInfo.getNextStackOffset(), 4);
    3628             :   AFI->setVarArgsFrameIndex(FrameIndex);
    3629          34 : }
    3630             : 
    3631       12914 : SDValue ARMTargetLowering::LowerFormalArguments(
    3632             :     SDValue Chain, CallingConv::ID CallConv, bool isVarArg,
    3633             :     const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl,
    3634             :     SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const {
    3635       12914 :   MachineFunction &MF = DAG.getMachineFunction();
    3636       12914 :   MachineFrameInfo &MFI = MF.getFrameInfo();
    3637             : 
    3638       12914 :   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
    3639             : 
    3640             :   // Assign locations to all of the incoming arguments.
    3641             :   SmallVector<CCValAssign, 16> ArgLocs;
    3642             :   CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), ArgLocs,
    3643       25828 :                  *DAG.getContext());
    3644       12914 :   CCInfo.AnalyzeFormalArguments(Ins, CCAssignFnForCall(CallConv, isVarArg));
    3645             : 
    3646             :   SmallVector<SDValue, 16> ArgValues;
    3647       12914 :   SDValue ArgValue;
    3648       12914 :   Function::const_arg_iterator CurOrigArg = MF.getFunction().arg_begin();
    3649             :   unsigned CurArgIdx = 0;
    3650             : 
    3651             :   // Initially ArgRegsSaveSize is zero.
    3652             :   // Then we increase this value each time we meet byval parameter.
    3653             :   // We also increase this value in case of varargs function.
    3654             :   AFI->setArgRegsSaveSize(0);
    3655             : 
    3656             :   // Calculate the amount of stack space that we need to allocate to store
    3657             :   // byval and variadic arguments that are passed in registers.
    3658             :   // We need to know this before we allocate the first byval or variadic
    3659             :   // argument, as they will be allocated a stack slot below the CFA (Canonical
    3660             :   // Frame Address, the stack pointer at entry to the function).
    3661       12914 :   unsigned ArgRegBegin = ARM::R4;
    3662       12968 :   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
    3663       21052 :     if (CCInfo.getInRegsParamsProcessed() >= CCInfo.getInRegsParamsCount())
    3664             :       break;
    3665             : 
    3666          54 :     CCValAssign &VA = ArgLocs[i];
    3667          54 :     unsigned Index = VA.getValNo();
    3668         108 :     ISD::ArgFlagsTy Flags = Ins[Index].Flags;
    3669          54 :     if (!Flags.isByVal())
    3670          20 :       continue;
    3671             : 
    3672             :     assert(VA.isMemLoc() && "unexpected byval pointer in reg");
    3673             :     unsigned RBegin, REnd;
    3674             :     CCInfo.getInRegsParamInfo(CCInfo.getInRegsParamsProcessed(), RBegin, REnd);
    3675          34 :     ArgRegBegin = std::min(ArgRegBegin, RBegin);
    3676             : 
    3677             :     CCInfo.nextInRegsParam();
    3678             :   }
    3679             :   CCInfo.rewindByValRegsInfo();
    3680             : 
    3681             :   int lastInsIndex = -1;
    3682       12914 :   if (isVarArg && MFI.hasVAStart()) {
    3683             :     unsigned RegIdx = CCInfo.getFirstUnallocated(GPRArgRegs);
    3684          34 :     if (RegIdx != array_lengthof(GPRArgRegs))
    3685          66 :       ArgRegBegin = std::min(ArgRegBegin, (unsigned)GPRArgRegs[RegIdx]);
    3686             :   }
    3687             : 
    3688       12914 :   unsigned TotalArgRegsSaveSize = 4 * (ARM::R4 - ArgRegBegin);
    3689             :   AFI->setArgRegsSaveSize(TotalArgRegsSaveSize);
    3690       12914 :   auto PtrVT = getPointerTy(DAG.getDataLayout());
    3691             : 
    3692       34275 :   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
    3693       21361 :     CCValAssign &VA = ArgLocs[i];
    3694       42722 :     if (Ins[VA.getValNo()].isOrigArg()) {
    3695       21106 :       std::advance(CurOrigArg,
    3696             :                    Ins[VA.getValNo()].getOrigArgIndex() - CurArgIdx);
    3697             :       CurArgIdx = Ins[VA.getValNo()].getOrigArgIndex();
    3698             :     }
    3699             :     // Arguments stored in registers.
    3700       21361 :     if (VA.isRegLoc()) {
    3701             :       EVT RegVT = VA.getLocVT();
    3702             : 
    3703       19890 :       if (VA.needsCustom()) {
    3704             :         // f64 and vector types are split up into multiple registers or
    3705             :         // combinations of registers and stack slots.
    3706         808 :         if (VA.getLocVT() == MVT::v2f64) {
    3707         216 :           SDValue ArgValue1 = GetF64FormalArgument(VA, ArgLocs[++i],
    3708         432 :                                                    Chain, DAG, dl);
    3709         432 :           VA = ArgLocs[++i]; // skip ahead to next loc
    3710         216 :           SDValue ArgValue2;
    3711         216 :           if (VA.isMemLoc()) {
    3712          19 :             int FI = MFI.CreateFixedObject(8, VA.getLocMemOffset(), true);
    3713          19 :             SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
    3714          19 :             ArgValue2 = DAG.getLoad(MVT::f64, dl, Chain, FIN,
    3715             :                                     MachinePointerInfo::getFixedStack(
    3716          38 :                                         DAG.getMachineFunction(), FI));
    3717             :           } else {
    3718         394 :             ArgValue2 = GetF64FormalArgument(VA, ArgLocs[++i],
    3719             :                                              Chain, DAG, dl);
    3720             :           }
    3721         216 :           ArgValue = DAG.getNode(ISD::UNDEF, dl, MVT::v2f64);
    3722         216 :           ArgValue = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64,
    3723             :                                  ArgValue, ArgValue1,
    3724         432 :                                  DAG.getIntPtrConstant(0, dl));
    3725         216 :           ArgValue = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64,
    3726             :                                  ArgValue, ArgValue2,
    3727         432 :                                  DAG.getIntPtrConstant(1, dl));
    3728             :         } else
    3729        1184 :           ArgValue = GetF64FormalArgument(VA, ArgLocs[++i], Chain, DAG, dl);
    3730             :       } else {
    3731             :         const TargetRegisterClass *RC;
    3732             : 
    3733             : 
    3734             :         if (RegVT == MVT::f16)
    3735             :           RC = &ARM::HPRRegClass;
    3736             :         else if (RegVT == MVT::f32)
    3737             :           RC = &ARM::SPRRegClass;
    3738             :         else if (RegVT == MVT::f64 || RegVT == MVT::v4f16)
    3739             :           RC = &ARM::DPRRegClass;
    3740             :         else if (RegVT == MVT::v2f64 || RegVT == MVT::v8f16)
    3741             :           RC = &ARM::QPRRegClass;
    3742             :         else if (RegVT == MVT::i32)
    3743       16918 :           RC = AFI->isThumb1OnlyFunction() ? &ARM::tGPRRegClass
    3744             :                                            : &ARM::GPRRegClass;
    3745             :         else
    3746           0 :           llvm_unreachable("RegVT not supported by FORMAL_ARGUMENTS Lowering");
    3747             : 
    3748             :         // Transform the arguments in physical registers into virtual ones.
    3749       19082 :         unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
    3750       19082 :         ArgValue = DAG.getCopyFromReg(Chain, dl, Reg, RegVT);
    3751             :       }
    3752             : 
    3753             :       // If this is an 8 or 16-bit value, it is really passed promoted
    3754             :       // to 32 bits.  Insert an assert[sz]ext to capture this, then
    3755             :       // truncate to the right size.
    3756       19890 :       switch (VA.getLocInfo()) {
    3757           0 :       default: llvm_unreachable("Unknown loc info!");
    3758             :       case CCValAssign::Full: break;
    3759             :       case CCValAssign::BCvt:
    3760        1599 :         ArgValue = DAG.getNode(ISD::BITCAST, dl, VA.getValVT(), ArgValue);
    3761        1599 :         break;
    3762             :       case CCValAssign::SExt:
    3763           0 :         ArgValue = DAG.getNode(ISD::AssertSext, dl, RegVT, ArgValue,
    3764           0 :                                DAG.getValueType(VA.getValVT()));
    3765           0 :         ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue);
    3766           0 :         break;
    3767             :       case CCValAssign::ZExt:
    3768           0 :         ArgValue = DAG.getNode(ISD::AssertZext, dl, RegVT, ArgValue,
    3769           0 :                                DAG.getValueType(VA.getValVT()));
    3770           0 :         ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue);
    3771           0 :         break;
    3772             :       }
    3773             : 
    3774       19890 :       InVals.push_back(ArgValue);
    3775             :     } else { // VA.isRegLoc()
    3776             :       // sanity check
    3777             :       assert(VA.isMemLoc());
    3778             :       assert(VA.getValVT() != MVT::i64 && "i64 should already be lowered");
    3779             : 
    3780        1471 :       int index = VA.getValNo();
    3781             : 
    3782             :       // Some Ins[] entries become multiple ArgLoc[] entries.
    3783             :       // Process them only once.
    3784        1471 :       if (index != lastInsIndex)
    3785             :         {
    3786        2942 :           ISD::ArgFlagsTy Flags = Ins[index].Flags;
    3787             :           // FIXME: For now, all byval parameter objects are marked mutable.
    3788             :           // This can be changed with more analysis.
    3789             :           // In case of tail call optimization mark all arguments mutable.
    3790             :           // Since they could be overwritten by lowering of arguments in case of
    3791             :           // a tail call.
    3792        1471 :           if (Flags.isByVal()) {
    3793             :             assert(Ins[index].isOrigArg() &&
    3794             :                    "Byval arguments cannot be implicit");
    3795          47 :             unsigned CurByValIndex = CCInfo.getInRegsParamsProcessed();
    3796             : 
    3797          47 :             int FrameIndex = StoreByValRegs(
    3798             :                 CCInfo, DAG, dl, Chain, &*CurOrigArg, CurByValIndex,
    3799          94 :                 VA.getLocMemOffset(), Flags.getByValSize());
    3800          94 :             InVals.push_back(DAG.getFrameIndex(FrameIndex, PtrVT));
    3801             :             CCInfo.nextInRegsParam();
    3802             :           } else {
    3803        1424 :             unsigned FIOffset = VA.getLocMemOffset();
    3804        2848 :             int FI = MFI.CreateFixedObject(VA.getLocVT().getSizeInBits()/8,
    3805        1424 :                                            FIOffset, true);
    3806             : 
    3807             :             // Create load nodes to retrieve arguments from the stack.
    3808        1424 :             SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
    3809        2848 :             InVals.push_back(DAG.getLoad(VA.getValVT(), dl, Chain, FIN,
    3810             :                                          MachinePointerInfo::getFixedStack(
    3811        2848 :                                              DAG.getMachineFunction(), FI)));
    3812             :           }
    3813             :           lastInsIndex = index;
    3814             :         }
    3815             :     }
    3816             :   }
    3817             : 
    3818             :   // varargs
    3819       12914 :   if (isVarArg && MFI.hasVAStart())
    3820          34 :     VarArgStyleRegisters(CCInfo, DAG, dl, Chain,
    3821             :                          CCInfo.getNextStackOffset(),
    3822             :                          TotalArgRegsSaveSize);
    3823             : 
    3824       12914 :   AFI->setArgumentStackSize(CCInfo.getNextStackOffset());
    3825             : 
    3826       25828 :   return Chain;
    3827             : }
    3828             : 
    3829             : /// isFloatingPointZero - Return true if this is +0.0.
    3830         834 : static bool isFloatingPointZero(SDValue Op) {
    3831             :   if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Op))
    3832         666 :     return CFP->getValueAPF().isPosZero();
    3833             :   else if (ISD::isEXTLoad(Op.getNode()) || ISD::isNON_EXTLoad(Op.getNode())) {
    3834             :     // Maybe this has already been legalized into the constant pool?
    3835         170 :     if (Op.getOperand(1).getOpcode() == ARMISD::Wrapper) {
    3836          73 :       SDValue WrapperOp = Op.getOperand(1).getOperand(0);
    3837             :       if (ConstantPoolSDNode *CP = dyn_cast<ConstantPoolSDNode>(WrapperOp))
    3838          73 :         if (const ConstantFP *CFP = dyn_cast<ConstantFP>(CP->getConstVal()))
    3839          73 :           return CFP->getValueAPF().isPosZero();
    3840             :     }
    3841         416 :   } else if (Op->getOpcode() == ISD::BITCAST &&
    3842          55 :              Op->getValueType(0) == MVT::f64) {
    3843             :     // Handle (ISD::BITCAST (ARMISD::VMOVIMM (ISD::TargetConstant 0)) MVT::f64)
    3844             :     // created by LowerConstantFP().
    3845           2 :     SDValue BitcastOp = Op->getOperand(0);
    3846           4 :     if (BitcastOp->getOpcode() == ARMISD::VMOVIMM &&
    3847           4 :         isNullConstant(BitcastOp->getOperand(0)))
    3848             :       return true;
    3849             :   }
    3850             :   return false;
    3851             : }
    3852             : 
    3853             : /// Returns appropriate ARM CMP (cmp) and corresponding condition code for
    3854             : /// the given operands.
    3855        2851 : SDValue ARMTargetLowering::getARMCmp(SDValue LHS, SDValue RHS, ISD::CondCode CC,
    3856             :                                      SDValue &ARMcc, SelectionDAG &DAG,
    3857             :                                      const SDLoc &dl) const {
    3858             :   if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS.getNode())) {
    3859        4744 :     unsigned C = RHSC->getZExtValue();
    3860        2372 :     if (!isLegalICmpImmediate(C)) {
    3861             :       // Constant does not fit, try adjusting it by one?
    3862         160 :       switch (CC) {
    3863             :       default: break;
    3864          46 :       case ISD::SETLT:
    3865             :       case ISD::SETGE:
    3866          46 :         if (C != 0x80000000 && isLegalICmpImmediate(C-1)) {
    3867           3 :           CC = (CC == ISD::SETLT) ? ISD::SETLE : ISD::SETGT;
    3868           3 :           RHS = DAG.getConstant(C - 1, dl, MVT::i32);
    3869             :         }
    3870             :         break;
    3871           1 :       case ISD::SETULT:
    3872             :       case ISD::SETUGE:
    3873           1 :         if (C != 0 && isLegalICmpImmediate(C-1)) {
    3874           1 :           CC = (CC == ISD::SETULT) ? ISD::SETULE : ISD::SETUGT;
    3875           1 :           RHS = DAG.getConstant(C - 1, dl, MVT::i32);
    3876             :         }
    3877             :         break;
    3878          71 :       case ISD::SETLE:
    3879             :       case ISD::SETGT:
    3880          71 :         if (C != 0x7fffffff && isLegalICmpImmediate(C+1)) {
    3881          57 :           CC = (CC == ISD::SETLE) ? ISD::SETLT : ISD::SETGE;
    3882          57 :           RHS = DAG.getConstant(C + 1, dl, MVT::i32);
    3883             :         }
    3884             :         break;
    3885           1 :       case ISD::SETULE:
    3886             :       case ISD::SETUGT:
    3887           1 :         if (C != 0xffffffff && isLegalICmpImmediate(C+1)) {
    3888           0 :           CC = (CC == ISD::SETULE) ? ISD::SETULT : ISD::SETUGE;
    3889           0 :           RHS = DAG.getConstant(C + 1, dl, MVT::i32);
    3890             :         }
    3891             :         break;
    3892             :       }
    3893             :     }
    3894          20 :   } else if ((ARM_AM::getShiftOpcForNode(LHS.getOpcode()) != ARM_AM::no_shift) &&
    3895             :              (ARM_AM::getShiftOpcForNode(RHS.getOpcode()) == ARM_AM::no_shift)) {
    3896             :     // In ARM and Thumb-2, the compare instructions can shift their second
    3897             :     // operand.
    3898          20 :     CC = ISD::getSetCCSwappedOperands(CC);
    3899             :     std::swap(LHS, RHS);
    3900             :   }
    3901             : 
    3902        2851 :   ARMCC::CondCodes CondCode = IntCCToARMCC(CC);
    3903             :   ARMISD::NodeType CompareType;
    3904        2851 :   switch (CondCode) {
    3905             :   default:
    3906             :     CompareType = ARMISD::CMP;
    3907             :     break;
    3908        2167 :   case ARMCC::EQ:
    3909             :   case ARMCC::NE:
    3910             :     // Uses only Z Flag
    3911             :     CompareType = ARMISD::CMPZ;
    3912        2167 :     break;
    3913             :   }
    3914        2851 :   ARMcc = DAG.getConstant(CondCode, dl, MVT::i32);
    3915        2851 :   return DAG.getNode(CompareType, dl, MVT::Glue, LHS, RHS);
    3916             : }
    3917             : 
    3918             : /// Returns a appropriate VFP CMP (fcmp{s|d}+fmstat) for the given operands.
    3919         599 : SDValue ARMTargetLowering::getVFPCmp(SDValue LHS, SDValue RHS,
    3920             :                                      SelectionDAG &DAG, const SDLoc &dl,
    3921             :                                      bool InvalidOnQNaN) const {
    3922             :   assert(!Subtarget->isFPOnlySP() || RHS.getValueType() != MVT::f64);
    3923         599 :   SDValue Cmp;
    3924         599 :   SDValue C = DAG.getConstant(InvalidOnQNaN, dl, MVT::i32);
    3925         599 :   if (!isFloatingPointZero(RHS))
    3926         517 :     Cmp = DAG.getNode(ARMISD::CMPFP, dl, MVT::Glue, LHS, RHS, C);
    3927             :   else
    3928          82 :     Cmp = DAG.getNode(ARMISD::CMPFPw0, dl, MVT::Glue, LHS, C);
    3929         599 :   return DAG.getNode(ARMISD::FMSTAT, dl, MVT::Glue, Cmp);
    3930             : }
    3931             : 
    3932             : /// duplicateCmp - Glue values can have only one use, so this function
    3933             : /// duplicates a comparison node.
    3934             : SDValue
    3935           2 : ARMTargetLowering::duplicateCmp(SDValue Cmp, SelectionDAG &DAG) const {
    3936             :   unsigned Opc = Cmp.getOpcode();
    3937             :   SDLoc DL(Cmp);
    3938           2 :   if (Opc == ARMISD::CMP || Opc == ARMISD::CMPZ)
    3939           1 :     return DAG.getNode(Opc, DL, MVT::Glue, Cmp.getOperand(0),Cmp.getOperand(1));
    3940             : 
    3941             :   assert(Opc == ARMISD::FMSTAT && "unexpected comparison operation");
    3942           1 :   Cmp = Cmp.getOperand(0);
    3943             :   Opc = Cmp.getOpcode();
    3944           1 :   if (Opc == ARMISD::CMPFP)
    3945           0 :     Cmp = DAG.getNode(Opc, DL, MVT::Glue, Cmp.getOperand(0),
    3946           0 :                       Cmp.getOperand(1), Cmp.getOperand(2));
    3947             :   else {
    3948             :     assert(Opc == ARMISD::CMPFPw0 && "unexpected operand of FMSTAT");
    3949           1 :     Cmp = DAG.getNode(Opc, DL, MVT::Glue, Cmp.getOperand(0),
    3950           1 :                       Cmp.getOperand(1));
    3951             :   }
    3952           1 :   return DAG.getNode(ARMISD::FMSTAT, DL, MVT::Glue, Cmp);
    3953             : }
    3954             : 
    3955             : // This function returns three things: the arithmetic computation itself
    3956             : // (Value), a comparison (OverflowCmp), and a condition code (ARMcc).  The
    3957             : // comparison and the condition code define the case in which the arithmetic
    3958             : // computation *does not* overflow.
    3959             : std::pair<SDValue, SDValue>
    3960          36 : ARMTargetLowering::getARMXALUOOp(SDValue Op, SelectionDAG &DAG,
    3961             :                                  SDValue &ARMcc) const {
    3962             :   assert(Op.getValueType() == MVT::i32 &&  "Unsupported value type");
    3963             : 
    3964             :   SDValue Value, OverflowCmp;
    3965          36 :   SDValue LHS = Op.getOperand(0);
    3966          36 :   SDValue RHS = Op.getOperand(1);
    3967             :   SDLoc dl(Op);
    3968             : 
    3969             :   // FIXME: We are currently always generating CMPs because we don't support
    3970             :   // generating CMN through the backend. This is not as good as the natural
    3971             :   // CMP case because it causes a register dependency and cannot be folded
    3972             :   // later.
    3973             : 
    3974          36 :   switch (Op.getOpcode()) {
    3975           0 :   default:
    3976           0 :     llvm_unreachable("Unknown overflow instruction!");
    3977             :   case ISD::SADDO:
    3978          19 :     ARMcc = DAG.getConstant(ARMCC::VC, dl, MVT::i32);
    3979          19 :     Value = DAG.getNode(ISD::ADD, dl, Op.getValueType(), LHS, RHS);
    3980          19 :     OverflowCmp = DAG.getNode(ARMISD::CMP, dl, MVT::Glue, Value, LHS);
    3981          19 :     break;
    3982             :   case ISD::UADDO:
    3983           2 :     ARMcc = DAG.getConstant(ARMCC::HS, dl, MVT::i32);
    3984             :     // We use ADDC here to correspond to its use in LowerUnsignedALUO.
    3985             :     // We do not use it in the USUBO case as Value may not be used.
    3986           4 :     Value = DAG.getNode(ARMISD::ADDC, dl,
    3987           4 :                         DAG.getVTList(Op.getValueType(), MVT::i32), LHS, RHS)
    3988           2 :                 .getValue(0);
    3989           2 :     OverflowCmp = DAG.getNode(ARMISD::CMP, dl, MVT::Glue, Value, LHS);
    3990           2 :     break;
    3991             :   case ISD::SSUBO:
    3992          11 :     ARMcc = DAG.getConstant(ARMCC::VC, dl, MVT::i32);
    3993          11 :     Value = DAG.getNode(ISD::SUB, dl, Op.getValueType(), LHS, RHS);
    3994          11 :     OverflowCmp = DAG.getNode(ARMISD::CMP, dl, MVT::Glue, LHS, RHS);
    3995          11 :     break;
    3996             :   case ISD::USUBO:
    3997           2 :     ARMcc = DAG.getConstant(ARMCC::HS, dl, MVT::i32);
    3998           2 :     Value = DAG.getNode(ISD::SUB, dl, Op.getValueType(), LHS, RHS);
    3999           2 :     OverflowCmp = DAG.getNode(ARMISD::CMP, dl, MVT::Glue, LHS, RHS);
    4000           2 :     break;
    4001             :   case ISD::UMULO:
    4002             :     // We generate a UMUL_LOHI and then check if the high word is 0.
    4003           1 :     ARMcc = DAG.getConstant(ARMCC::EQ, dl, MVT::i32);
    4004           1 :     Value = DAG.getNode(ISD::UMUL_LOHI, dl,
    4005             :                         DAG.getVTList(Op.getValueType(), Op.getValueType()),
    4006           1 :                         LHS, RHS);
    4007           1 :     OverflowCmp = DAG.getNode(ARMISD::CMP, dl, MVT::Glue, Value.getValue(1),
    4008           2 :                               DAG.getConstant(0, dl, MVT::i32));
    4009             :     Value = Value.getValue(0); // We only want the low 32 bits for the result.
    4010           1 :     break;
    4011             :   case ISD::SMULO:
    4012             :     // We generate a SMUL_LOHI and then check if all the bits of the high word
    4013             :     // are the same as the sign bit of the low word.
    4014           1 :     ARMcc = DAG.getConstant(ARMCC::EQ, dl, MVT::i32);
    4015           1 :     Value = DAG.getNode(ISD::SMUL_LOHI, dl,
    4016             :                         DAG.getVTList(Op.getValueType(), Op.getValueType()),
    4017           1 :                         LHS, RHS);
    4018           1 :     OverflowCmp = DAG.getNode(ARMISD::CMP, dl, MVT::Glue, Value.getValue(1),
    4019             :                               DAG.getNode(ISD::SRA, dl, Op.getValueType(),
    4020             :                                           Value.getValue(0),
    4021           3 :                                           DAG.getConstant(31, dl, MVT::i32)));
    4022             :     Value = Value.getValue(0); // We only want the low 32 bits for the result.
    4023           1 :     break;
    4024             :   } // switch (...)
    4025             : 
    4026          36 :   return std::make_pair(Value, OverflowCmp);
    4027             : }
    4028             : 
    4029             : SDValue
    4030          18 : ARMTargetLowering::LowerSignedALUO(SDValue Op, SelectionDAG &DAG) const {
    4031             :   // Let legalize expand this if it isn't a legal type yet.
    4032          18 :   if (!DAG.getTargetLoweringInfo().isTypeLegal(Op.getValueType()))
    4033           0 :     return SDValue();
    4034             : 
    4035             :   SDValue Value, OverflowCmp;
    4036          18 :   SDValue ARMcc;
    4037          36 :   std::tie(Value, OverflowCmp) = getARMXALUOOp(Op, DAG, ARMcc);
    4038          18 :   SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
    4039             :   SDLoc dl(Op);
    4040             :   // We use 0 and 1 as false and true values.
    4041          18 :   SDValue TVal = DAG.getConstant(1, dl, MVT::i32);
    4042          18 :   SDValue FVal = DAG.getConstant(0, dl, MVT::i32);
    4043          18 :   EVT VT = Op.getValueType();
    4044             : 
    4045             :   SDValue Overflow = DAG.getNode(ARMISD::CMOV, dl, VT, TVal, FVal,
    4046          18 :                                  ARMcc, CCR, OverflowCmp);
    4047             : 
    4048          18 :   SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
    4049          18 :   return DAG.getNode(ISD::MERGE_VALUES, dl, VTs, Value, Overflow);
    4050             : }
    4051             : 
    4052         644 : static SDValue ConvertBooleanCarryToCarryFlag(SDValue BoolCarry,
    4053             :                                               SelectionDAG &DAG) {
    4054             :   SDLoc DL(BoolCarry);
    4055         644 :   EVT CarryVT = BoolCarry.getValueType();
    4056             : 
    4057             :   // This converts the boolean value carry into the carry flag by doing
    4058             :   // ARMISD::SUBC Carry, 1
    4059             :   SDValue Carry = DAG.getNode(ARMISD::SUBC, DL,
    4060             :                               DAG.getVTList(CarryVT, MVT::i32),
    4061        1288 :                               BoolCarry, DAG.getConstant(1, DL, CarryVT));
    4062        1288 :   return Carry.getValue(1);
    4063             : }
    4064             : 
    4065        1191 : static SDValue ConvertCarryFlagToBooleanCarry(SDValue Flags, EVT VT,
    4066             :                                               SelectionDAG &DAG) {
    4067             :   SDLoc DL(Flags);
    4068             : 
    4069             :   // Now convert the carry flag into a boolean carry. We do this
    4070             :   // using ARMISD:ADDE 0, 0, Carry
    4071             :   return DAG.getNode(ARMISD::ADDE, DL, DAG.getVTList(VT, MVT::i32),
    4072             :                      DAG.getConstant(0, DL, MVT::i32),
    4073        4764 :                      DAG.getConstant(0, DL, MVT::i32), Flags);
    4074             : }
    4075             : 
    4076         634 : SDValue ARMTargetLowering::LowerUnsignedALUO(SDValue Op,
    4077             :                                              SelectionDAG &DAG) const {
    4078             :   // Let legalize expand this if it isn't a legal type yet.
    4079         634 :   if (!DAG.getTargetLoweringInfo().isTypeLegal(Op.getValueType()))
    4080           0 :     return SDValue();
    4081             : 
    4082         634 :   SDValue LHS = Op.getOperand(0);
    4083         634 :   SDValue RHS = Op.getOperand(1);
    4084             :   SDLoc dl(Op);
    4085             : 
    4086         634 :   EVT VT = Op.getValueType();
    4087         634 :   SDVTList VTs = DAG.getVTList(VT, MVT::i32);
    4088         634 :   SDValue Value;
    4089         634 :   SDValue Overflow;
    4090         634 :   switch (Op.getOpcode()) {
    4091           0 :   default:
    4092           0 :     llvm_unreachable("Unknown overflow instruction!");
    4093         433 :   case ISD::UADDO:
    4094         433 :     Value = DAG.getNode(ARMISD::ADDC, dl, VTs, LHS, RHS);
    4095             :     // Convert the carry flag into a boolean value.
    4096         433 :     Overflow = ConvertCarryFlagToBooleanCarry(Value.getValue(1), VT, DAG);
    4097         433 :     break;
    4098         201 :   case ISD::USUBO: {
    4099         201 :     Value = DAG.getNode(ARMISD::SUBC, dl, VTs, LHS, RHS);
    4100             :     // Convert the carry flag into a boolean value.
    4101         201 :     Overflow = ConvertCarryFlagToBooleanCarry(Value.getValue(1), VT, DAG);
    4102             :     // ARMISD::SUBC returns 0 when we have to borrow, so make it an overflow
    4103             :     // value. So compute 1 - C.
    4104         201 :     Overflow = DAG.getNode(ISD::SUB, dl, MVT::i32,
    4105         402 :                            DAG.getConstant(1, dl, MVT::i32), Overflow);
    4106         201 :     break;
    4107             :   }
    4108             :   }
    4109             : 
    4110         634 :   return DAG.getNode(ISD::MERGE_VALUES, dl, VTs, Value, Overflow);
    4111             : }
    4112             : 
    4113         146 : SDValue ARMTargetLowering::LowerSELECT(SDValue Op, SelectionDAG &DAG) const {
    4114         146 :   SDValue Cond = Op.getOperand(0);
    4115         146 :   SDValue SelectTrue = Op.getOperand(1);
    4116         146 :   SDValue SelectFalse = Op.getOperand(2);
    4117             :   SDLoc dl(Op);
    4118             :   unsigned Opc = Cond.getOpcode();
    4119             : 
    4120         147 :   if (Cond.getResNo() == 1 &&
    4121           1 :       (Opc == ISD::SADDO || Opc == ISD::UADDO || Opc == ISD::SSUBO ||
    4122             :        Opc == ISD::USUBO)) {
    4123           0 :     if (!DAG.getTargetLoweringInfo().isTypeLegal(Cond->getValueType(0)))
    4124           0 :       return SDValue();
    4125             : 
    4126             :     SDValue Value, OverflowCmp;
    4127           0 :     SDValue ARMcc;
    4128           0 :     std::tie(Value, OverflowCmp) = getARMXALUOOp(Cond, DAG, ARMcc);
    4129           0 :     SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
    4130           0 :     EVT VT = Op.getValueType();
    4131             : 
    4132             :     return getCMOV(dl, VT, SelectTrue, SelectFalse, ARMcc, CCR,
    4133           0 :                    OverflowCmp, DAG);
    4134             :   }
    4135             : 
    4136             :   // Convert:
    4137             :   //
    4138             :   //   (select (cmov 1, 0, cond), t, f) -> (cmov t, f, cond)
    4139             :   //   (select (cmov 0, 1, cond), t, f) -> (cmov f, t, cond)
    4140             :   //
    4141         146 :   if (Cond.getOpcode() == ARMISD::CMOV && Cond.hasOneUse()) {
    4142             :     const ConstantSDNode *CMOVTrue =
    4143             :       dyn_cast<ConstantSDNode>(Cond.getOperand(0));
    4144             :     const ConstantSDNode *CMOVFalse =
    4145             :       dyn_cast<ConstantSDNode>(Cond.getOperand(1));
    4146             : 
    4147           0 :     if (CMOVTrue && CMOVFalse) {
    4148           0 :       unsigned CMOVTrueVal = CMOVTrue->getZExtValue();
    4149           0 :       unsigned CMOVFalseVal = CMOVFalse->getZExtValue();
    4150             : 
    4151           0 :       SDValue True;
    4152           0 :       SDValue False;
    4153           0 :       if (CMOVTrueVal == 1 && CMOVFalseVal == 0) {
    4154           0 :         True = SelectTrue;
    4155           0 :         False = SelectFalse;
    4156           0 :       } else if (CMOVTrueVal == 0 && CMOVFalseVal == 1) {
    4157           0 :         True = SelectFalse;
    4158           0 :         False = SelectTrue;
    4159             :       }
    4160             : 
    4161           0 :       if (True.getNode() && False.getNode()) {
    4162           0 :         EVT VT = Op.getValueType();
    4163           0 :         SDValue ARMcc = Cond.getOperand(2);
    4164           0 :         SDValue CCR = Cond.getOperand(3);
    4165           0 :         SDValue Cmp = duplicateCmp(Cond.getOperand(4), DAG);
    4166             :         assert(True.getValueType() == VT);
    4167           0 :         return getCMOV(dl, VT, True, False, ARMcc, CCR, Cmp, DAG);
    4168             :       }
    4169             :     }
    4170             :   }
    4171             : 
    4172             :   // ARM's BooleanContents value is UndefinedBooleanContent. Mask out the
    4173             :   // undefined bits before doing a full-word comparison with zero.
    4174         146 :   Cond = DAG.getNode(ISD::AND, dl, Cond.getValueType(), Cond,
    4175         292 :                      DAG.getConstant(1, dl, Cond.getValueType()));
    4176             : 
    4177             :   return DAG.getSelectCC(dl, Cond,
    4178             :                          DAG.getConstant(0, dl, Cond.getValueType()),
    4179         146 :                          SelectTrue, SelectFalse, ISD::SETNE);
    4180             : }
    4181             : 
    4182         156 : static void checkVSELConstraints(ISD::CondCode CC, ARMCC::CondCodes &CondCode,
    4183             :                                  bool &swpCmpOps, bool &swpVselOps) {
    4184             :   // Start by selecting the GE condition code for opcodes that return true for
    4185             :   // 'equality'
    4186         281 :   if (CC == ISD::SETUGE || CC == ISD::SETOGE || CC == ISD::SETOLE ||
    4187         125 :       CC == ISD::SETULE)
    4188          60 :     CondCode = ARMCC::GE;
    4189             : 
    4190             :   // and GT for opcodes that return false for 'equality'.
    4191         160 :   else if (CC == ISD::SETUGT || CC == ISD::SETOGT || CC == ISD::SETOLT ||
    4192          64 :            CC == ISD::SETULT)
    4193          72 :     CondCode = ARMCC::GT;
    4194             : 
    4195             :   // Since we are constrained to GE/GT, if the opcode contains 'less', we need
    4196             :   // to swap the compare operands.
    4197         283 :   if (CC == ISD::SETOLE || CC == ISD::SETULE || CC == ISD::SETOLT ||
    4198         127 :       CC == ISD::SETULT)
    4199          69 :     swpCmpOps = true;
    4200             : 
    4201             :   // Both GT and GE are ordered comparisons, and return false for 'unordered'.
    4202             :   // If we have an unordered opcode, we need to swap the operands to the VSEL
    4203             :   // instruction (effectively negating the condition).
    4204             :   //
    4205             :   // This also has the effect of swapping which one of 'less' or 'greater'
    4206             :   // returns true, so we also swap the compare operands. It also switches
    4207             :   // whether we return true for 'equality', so we compensate by picking the
    4208             :   // opposite condition code to our original choice.
    4209         156 :   if (CC == ISD::SETULE || CC == ISD::SETULT || CC == ISD::SETUGE ||
    4210             :       CC == ISD::SETUGT) {
    4211          62 :     swpCmpOps = !swpCmpOps;
    4212          62 :     swpVselOps = !swpVselOps;
    4213          62 :     CondCode = CondCode == ARMCC::GT ? ARMCC::GE : ARMCC::GT;
    4214             :   }
    4215             : 
    4216             :   // 'ordered' is 'anything but unordered', so use the VS condition code and
    4217             :   // swap the VSEL operands.
    4218         156 :   if (CC == ISD::SETO) {
    4219           2 :     CondCode = ARMCC::VS;
    4220           2 :     swpVselOps = true;
    4221             :   }
    4222             : 
    4223             :   // 'unordered or not equal' is 'anything but equal', so use the EQ condition
    4224             :   // code and swap the VSEL operands.
    4225         156 :   if (CC == ISD::SETUNE) {
    4226           2 :     CondCode = ARMCC::EQ;
    4227           2 :     swpVselOps = true;
    4228             :   }
    4229         156 : }
    4230             : 
    4231        1603 : SDValue ARMTargetLowering::getCMOV(const SDLoc &dl, EVT VT, SDValue FalseVal,
    4232             :                                    SDValue TrueVal, SDValue ARMcc, SDValue CCR,
    4233             :                                    SDValue Cmp, SelectionDAG &DAG) const {
    4234        1603 :   if (Subtarget->isFPOnlySP() && VT == MVT::f64) {
    4235           2 :     FalseVal = DAG.getNode(ARMISD::VMOVRRD, dl,
    4236           4 :                            DAG.getVTList(MVT::i32, MVT::i32), FalseVal);
    4237           2 :     TrueVal = DAG.getNode(ARMISD::VMOVRRD, dl,
    4238           4 :                           DAG.getVTList(MVT::i32, MVT::i32), TrueVal);
    4239             : 
    4240           2 :     SDValue TrueLow = TrueVal.getValue(0);
    4241           2 :     SDValue TrueHigh = TrueVal.getValue(1);
    4242           2 :     SDValue FalseLow = FalseVal.getValue(0);
    4243           2 :     SDValue FalseHigh = FalseVal.getValue(1);
    4244             : 
    4245             :     SDValue Low = DAG.getNode(ARMISD::CMOV, dl, MVT::i32, FalseLow, TrueLow,
    4246           2 :                               ARMcc, CCR, Cmp);
    4247             :     SDValue High = DAG.getNode(ARMISD::CMOV, dl, MVT::i32, FalseHigh, TrueHigh,
    4248           4 :                                ARMcc, CCR, duplicateCmp(Cmp, DAG));
    4249             : 
    4250           2 :     return DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Low, High);
    4251             :   } else {
    4252             :     return DAG.getNode(ARMISD::CMOV, dl, VT, FalseVal, TrueVal, ARMcc, CCR,
    4253        1601 :                        Cmp);
    4254             :   }
    4255             : }
    4256             : 
    4257             : static bool isGTorGE(ISD::CondCode CC) {
    4258         170 :   return CC == ISD::SETGT || CC == ISD::SETGE;
    4259             : }
    4260             : 
    4261             : static bool isLTorLE(ISD::CondCode CC) {
    4262         124 :   return CC == ISD::SETLT || CC == ISD::SETLE;
    4263             : }
    4264             : 
    4265             : // See if a conditional (LHS CC RHS ? TrueVal : FalseVal) is lower-saturating.
    4266             : // All of these conditions (and their <= and >= counterparts) will do:
    4267             : //          x < k ? k : x
    4268             : //          x > k ? x : k
    4269             : //          k < x ? x : k
    4270             : //          k > x ? k : x
    4271         118 : static bool isLowerSaturate(const SDValue LHS, const SDValue RHS,
    4272             :                             const SDValue TrueVal, const SDValue FalseVal,
    4273             :                             const ISD::CondCode CC, const SDValue K) {
    4274             :   return (isGTorGE(CC) &&
    4275         215 :           ((K == LHS && K == TrueVal) || (K == RHS && K == FalseVal))) ||
    4276             :          (isLTorLE(CC) &&
    4277         118 :           ((K == RHS && K == TrueVal) || (K == LHS && K == FalseVal)));
    4278             : }
    4279             : 
    4280             : // Similar to isLowerSaturate(), but checks for upper-saturating conditions.
    4281          52 : static bool isUpperSaturate(const SDValue LHS, const SDValue RHS,
    4282             :                             const SDValue TrueVal, const SDValue FalseVal,
    4283             :                             const ISD::CondCode CC, const SDValue K) {
    4284             :   return (isGTorGE(CC) &&
    4285          79 :           ((K == RHS && K == TrueVal) || (K == LHS && K == FalseVal))) ||
    4286             :          (isLTorLE(CC) &&
    4287          52 :           ((K == LHS && K == TrueVal) || (K == RHS && K == FalseVal)));
    4288             : }
    4289             : 
    4290             : // Check if two chained conditionals could be converted into SSAT or USAT.
    4291             : //
    4292             : // SSAT can replace a set of two conditional selectors that bound a number to an
    4293             : // interval of type [k, ~k] when k + 1 is a power of 2. Here are some examples:
    4294             : //
    4295             : //     x < -k ? -k : (x > k ? k : x)
    4296             : //     x < -k ? -k : (x < k ? x : k)
    4297             : //     x > -k ? (x > k ? k : x) : -k
    4298             : //     x < k ? (x < -k ? -k : x) : k
    4299             : //     etc.
    4300             : //
    4301             : // USAT works similarily to SSAT but bounds on the interval [0, k] where k + 1 is
    4302             : // a power of 2.
    4303             : //
    4304             : // It returns true if the conversion can be done, false otherwise.
    4305             : // Additionally, the variable is returned in parameter V, the constant in K and
    4306             : // usat is set to true if the conditional represents an unsigned saturation
    4307        1034 : static bool isSaturatingConditional(const SDValue &Op, SDValue &V,
    4308             :                                     uint64_t &K, bool &usat) {
    4309        2068 :   SDValue LHS1 = Op.getOperand(0);
    4310        1034 :   SDValue RHS1 = Op.getOperand(1);
    4311        1034 :   SDValue TrueVal1 = Op.getOperand(2);
    4312        1034 :   SDValue FalseVal1 = Op.getOperand(3);
    4313        1034 :   ISD::CondCode CC1 = cast<CondCodeSDNode>(Op.getOperand(4))->get();
    4314             : 
    4315        1034 :   const SDValue Op2 = isa<ConstantSDNode>(TrueVal1) ? FalseVal1 : TrueVal1;
    4316        2068 :   if (Op2.getOpcode() != ISD::SELECT_CC)
    4317             :     return false;
    4318             : 
    4319          47 :   SDValue LHS2 = Op2.getOperand(0);
    4320          47 :   SDValue RHS2 = Op2.getOperand(1);
    4321          47 :   SDValue TrueVal2 = Op2.getOperand(2);
    4322          47 :   SDValue FalseVal2 = Op2.getOperand(3);
    4323          47 :   ISD::CondCode CC2 = cast<CondCodeSDNode>(Op2.getOperand(4))->get();
    4324             : 
    4325             :   // Find out which are the constants and which are the variables
    4326             :   // in each conditional
    4327             :   SDValue *K1 = isa<ConstantSDNode>(LHS1) ? &LHS1 : isa<ConstantSDNode>(RHS1)
    4328             :                                                         ? &RHS1
    4329             :                                                         : nullptr;
    4330             :   SDValue *K2 = isa<ConstantSDNode>(LHS2) ? &LHS2 : isa<ConstantSDNode>(RHS2)
    4331             :                                                         ? &RHS2
    4332             :                                                         : nullptr;
    4333          47 :   SDValue K2Tmp = isa<ConstantSDNode>(TrueVal2) ? TrueVal2 : FalseVal2;
    4334          94 :   SDValue V1Tmp = (K1 && *K1 == LHS1) ? RHS1 : LHS1;
    4335          94 :   SDValue V2Tmp = (K2 && *K2 == LHS2) ? RHS2 : LHS2;
    4336          47 :   SDValue V2 = (K2Tmp == TrueVal2) ? FalseVal2 : TrueVal2;
    4337             : 
    4338             :   // We must detect cases where the original operations worked with 16- or
    4339             :   // 8-bit values. In such case, V2Tmp != V2 because the comparison operations
    4340             :   // must work with sign-extended values but the select operations return
    4341             :   // the original non-extended value.
    4342             :   SDValue V2TmpReg = V2Tmp;
    4343          47 :   if (V2Tmp->getOpcode() == ISD::SIGN_EXTEND_INREG)
    4344           6 :     V2TmpReg = V2Tmp->getOperand(0);
    4345             : 
    4346             :   // Check that the registers and the constants have the correct values
    4347             :   // in both conditionals
    4348          47 :   if (!K1 || !K2 || *K1 == Op2 || *K2 != K2Tmp || V1Tmp != V2Tmp ||
    4349             :       V2TmpReg != V2)
    4350             :     return false;
    4351             : 
    4352             :   // Figure out which conditional is saturating the lower/upper bound.
    4353             :   const SDValue *LowerCheckOp =
    4354          34 :       isLowerSaturate(LHS1, RHS1, TrueVal1, FalseVal1, CC1, *K1)
    4355          34 :           ? &Op
    4356          16 :           : isLowerSaturate(LHS2, RHS2, TrueVal2, FalseVal2, CC2, *K2)
    4357          16 :                 ? &Op2
    4358             :                 : nullptr;
    4359             :   const SDValue *UpperCheckOp =
    4360          34 :       isUpperSaturate(LHS1, RHS1, TrueVal1, FalseVal1, CC1, *K1)
    4361          34 :           ? &Op
    4362          18 :           : isUpperSaturate(LHS2, RHS2, TrueVal2, FalseVal2, CC2, *K2)
    4363          18 :                 ? &Op2
    4364             :                 : nullptr;
    4365             : 
    4366          34 :   if (!UpperCheckOp || !LowerCheckOp || LowerCheckOp == UpperCheckOp)
    4367             :     return false;
    4368             : 
    4369             :   // Check that the constant in the lower-bound check is
    4370             :   // the opposite of the constant in the upper-bound check
    4371             :   // in 1's complement.
    4372          56 :   int64_t Val1 = cast<ConstantSDNode>(*K1)->getSExtValue();
    4373          56 :   int64_t Val2 = cast<ConstantSDNode>(*K2)->getSExtValue();
    4374          28 :   int64_t PosVal = std::max(Val1, Val2);
    4375          28 :   int64_t NegVal = std::min(Val1, Val2);
    4376             : 
    4377          13 :   if (((Val1 > Val2 && UpperCheckOp == &Op) ||
    4378          43 :        (Val1 < Val2 && UpperCheckOp == &Op2)) &&
    4379          28 :       isPowerOf2_64(PosVal + 1)) {
    4380             : 
    4381             :     // Handle the difference between USAT (unsigned) and SSAT (signed) saturation
    4382          28 :     if (Val1 == ~Val2)
    4383           9 :       usat = false;
    4384          19 :     else if (NegVal == 0)
    4385          16 :       usat = true;
    4386             :     else
    4387             :       return false;
    4388             : 
    4389          25 :     V = V2;
    4390          25 :     K = (uint64_t)PosVal; // At this point, PosVal is guaranteed to be positive
    4391             : 
    4392          25 :     return true;
    4393             :   }
    4394             : 
    4395             :   return false;
    4396             : }
    4397             : 
    4398             : // Check if a condition of the type x < k ? k : x can be converted into a
    4399             : // bit operation instead of conditional moves.
    4400             : // Currently this is allowed given:
    4401             : // - The conditions and values match up
    4402             : // - k is 0 or -1 (all ones)
    4403             : // This function will not check the last condition, thats up to the caller
    4404             : // It returns true if the transformation can be made, and in such case
    4405             : // returns x in V, and k in SatK.
    4406        1295 : static bool isLowerSaturatingConditional(const SDValue &Op, SDValue &V,
    4407             :                                          SDValue &SatK)
    4408             : {
    4409        2590 :   SDValue LHS = Op.getOperand(0);
    4410        1295 :   SDValue RHS = Op.getOperand(1);
    4411        1295 :   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(4))->get();
    4412        1295 :   SDValue TrueVal = Op.getOperand(2);
    4413        1295 :   SDValue FalseVal = Op.getOperand(3);
    4414             : 
    4415             :   SDValue *K = isa<ConstantSDNode>(LHS) ? &LHS : isa<ConstantSDNode>(RHS)
    4416             :                                                ? &RHS
    4417             :                                                : nullptr;
    4418             : 
    4419             :   // No constant operation in comparison, early out
    4420             :   if (!K)
    4421             :     return false;
    4422             : 
    4423         738 :   SDValue KTmp = isa<ConstantSDNode>(TrueVal) ? TrueVal : FalseVal;
    4424         738 :   V = (KTmp == TrueVal) ? FalseVal : TrueVal;
    4425         738 :   SDValue VTmp = (K && *K == LHS) ? RHS : LHS;
    4426             : 
    4427             :   // If the constant on left and right side, or variable on left and right,
    4428             :   // does not match, early out
    4429             :   if (*K != KTmp || V != VTmp)
    4430             :     return false;
    4431             : 
    4432          68 :   if (isLowerSaturate(LHS, RHS, TrueVal, FalseVal, CC, *K)) {
    4433          38 :     SatK = *K;
    4434          38 :     return true;
    4435             :   }
    4436             : 
    4437             :   return false;
    4438             : }
    4439             : 
    4440        1622 : SDValue ARMTargetLowering::LowerSELECT_CC(SDValue Op, SelectionDAG &DAG) const {
    4441        3244 :   EVT VT = Op.getValueType();
    4442             :   SDLoc dl(Op);
    4443             : 
    4444             :   // Try to convert two saturating conditional selects into a single SSAT
    4445        1622 :   SDValue SatValue;
    4446             :   uint64_t SatConstant;
    4447             :   bool SatUSat;
    4448        2656 :   if (((!Subtarget->isThumb() && Subtarget->hasV6Ops()) || Subtarget->isThumb2()) &&
    4449        1034 :       isSaturatingConditional(Op, SatValue, SatConstant, SatUSat)) {
    4450          25 :     if (SatUSat)
    4451             :       return DAG.getNode(ARMISD::USAT, dl, VT, SatValue,
    4452          32 :                          DAG.getConstant(countTrailingOnes(SatConstant), dl, VT));
    4453             :     else
    4454             :       return DAG.getNode(ARMISD::SSAT, dl, VT, SatValue,
    4455          18 :                          DAG.getConstant(countTrailingOnes(SatConstant), dl, VT));
    4456             :   }
    4457             : 
    4458             :   // Try to convert expressions of the form x < k ? k : x (and similar forms)
    4459             :   // into more efficient bit operations, which is possible when k is 0 or -1
    4460             :   // On ARM and Thumb-2 which have flexible operand 2 this will result in
    4461             :   // single instructions. On Thumb the shift and the bit operation will be two
    4462             :   // instructions.
    4463             :   // Only allow this transformation on full-width (32-bit) operations
    4464        1597 :   SDValue LowerSatConstant;
    4465        1295 :   if (VT == MVT::i32 &&
    4466        1295 :       isLowerSaturatingConditional(Op, SatValue, LowerSatConstant)) {
    4467             :     SDValue ShiftV = DAG.getNode(ISD::SRA, dl, VT, SatValue,
    4468          38 :                                  DAG.getConstant(31, dl, VT));
    4469          38 :     if (isNullConstant(LowerSatConstant)) {
    4470             :       SDValue NotShiftV = DAG.getNode(ISD::XOR, dl, VT, ShiftV,
    4471          17 :                                       DAG.getAllOnesConstant(dl, VT));
    4472          17 :       return DAG.getNode(ISD::AND, dl, VT, SatValue, NotShiftV);
    4473          21 :     } else if (isAllOnesConstant(LowerSatConstant))
    4474           6 :       return DAG.getNode(ISD::OR, dl, VT, SatValue, ShiftV);
    4475             :   }
    4476             : 
    4477        3148 :   SDValue LHS = Op.getOperand(0);
    4478        1574 :   SDValue RHS = Op.getOperand(1);
    4479        1574 :   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(4))->get();
    4480        1574 :   SDValue TrueVal = Op.getOperand(2);
    4481        1574 :   SDValue FalseVal = Op.getOperand(3);
    4482             : 
    4483        1574 :   if (Subtarget->isFPOnlySP() && LHS.getValueType() == MVT::f64) {
    4484          56 :     DAG.getTargetLoweringInfo().softenSetCCOperands(DAG, MVT::f64, LHS, RHS, CC,
    4485             :                                                     dl);
    4486             : 
    4487             :     // If softenSetCCOperands only returned one value, we should compare it to
    4488             :     // zero.
    4489          28 :     if (!RHS.getNode()) {
    4490           4 :       RHS = DAG.getConstant(0, dl, LHS.getValueType());
    4491           2 :       CC = ISD::SETNE;
    4492             :     }
    4493             :   }
    4494             : 
    4495        1574 :   if (LHS.getValueType() == MVT::i32) {
    4496             :     // Try to generate VSEL on ARMv8.
    4497             :     // The VSEL instruction can't use all the usual ARM condition
    4498             :     // codes: it only has two bits to select the condition code, so it's
    4499             :     // constrained to use only GE, GT, VS and EQ.
    4500             :     //
    4501             :     // To implement all the various ISD::SETXXX opcodes, we sometimes need to
    4502             :     // swap the operands of the previous compare instruction (effectively
    4503             :     // inverting the compare condition, swapping 'less' and 'greater') and
    4504             :     // sometimes need to swap the operands to the VSEL (which inverts the
    4505             :     // condition in the sense of firing whenever the previous condition didn't)
    4506        1055 :     if (Subtarget->hasFPARMv8() && (TrueVal.getValueType() == MVT::f32 ||
    4507             :                                     TrueVal.getValueType() == MVT::f64)) {
    4508          16 :       ARMCC::CondCodes CondCode = IntCCToARMCC(CC);
    4509          16 :       if (CondCode == ARMCC::LT || CondCode == ARMCC::LE ||
    4510          12 :           CondCode == ARMCC::VC || CondCode == ARMCC::NE) {
    4511           6 :         CC = ISD::getSetCCInverse(CC, true);
    4512             :         std::swap(TrueVal, FalseVal);
    4513             :       }
    4514             :     }
    4515             : 
    4516        1055 :     SDValue ARMcc;
    4517        1055 :     SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
    4518        1055 :     SDValue Cmp = getARMCmp(LHS, RHS, CC, ARMcc, DAG, dl);
    4519        1055 :     return getCMOV(dl, VT, FalseVal, TrueVal, ARMcc, CCR, Cmp, DAG);
    4520             :   }
    4521             : 
    4522             :   ARMCC::CondCodes CondCode, CondCode2;
    4523             :   bool InvalidOnQNaN;
    4524         519 :   FPCCToARMCC(CC, CondCode, CondCode2, InvalidOnQNaN);
    4525             : 
    4526             :   // Normalize the fp compare. If RHS is zero we keep it there so we match
    4527             :   // CMPFPw0 instead of CMPFP.
    4528         744 :   if (Subtarget->hasFPARMv8() && !isFloatingPointZero(RHS) &&
    4529             :      (TrueVal.getValueType() == MVT::f16 ||
    4530             :       TrueVal.getValueType() == MVT::f32 ||
    4531             :       TrueVal.getValueType() == MVT::f64)) {
    4532         156 :     bool swpCmpOps = false;
    4533         156 :     bool swpVselOps = false;
    4534         156 :     checkVSELConstraints(CC, CondCode, swpCmpOps, swpVselOps);
    4535             : 
    4536         156 :     if (CondCode == ARMCC::GT || CondCode == ARMCC::GE ||
    4537          20 :         CondCode == ARMCC::VS || CondCode == ARMCC::EQ) {
    4538         156 :       if (swpCmpOps)
    4539             :         std::swap(LHS, RHS);
    4540         156 :       if (swpVselOps)
    4541             :         std::swap(TrueVal, FalseVal);
    4542             :     }
    4543             :   }
    4544             : 
    4545         519 :   SDValue ARMcc = DAG.getConstant(CondCode, dl, MVT::i32);
    4546         519 :   SDValue Cmp = getVFPCmp(LHS, RHS, DAG, dl, InvalidOnQNaN);
    4547         519 :   SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
    4548         519 :   SDValue Result = getCMOV(dl, VT, FalseVal, TrueVal, ARMcc, CCR, Cmp, DAG);
    4549         519 :   if (CondCode2 != ARMCC::AL) {
    4550          29 :     SDValue ARMcc2 = DAG.getConstant(CondCode2, dl, MVT::i32);
    4551             :     // FIXME: Needs another CMP because flag can have but one use.
    4552          29 :     SDValue Cmp2 = getVFPCmp(LHS, RHS, DAG, dl, InvalidOnQNaN);
    4553          29 :     Result = getCMOV(dl, VT, Result, TrueVal, ARMcc2, CCR, Cmp2, DAG);
    4554             :   }
    4555         519 :   return Result;
    4556             : }
    4557             : 
    4558             : /// canChangeToInt - Given the fp compare operand, return true if it is suitable
    4559             : /// to morph to an integer compare sequence.
    4560           6 : static bool canChangeToInt(SDValue Op, bool &SeenZero,
    4561             :                            const ARMSubtarget *Subtarget) {
    4562             :   SDNode *N = Op.getNode();
    4563             :   if (!N->hasOneUse())
    4564             :     // Otherwise it requires moving the value from fp to integer registers.
    4565             :     return false;
    4566           6 :   if (!N->getNumValues())
    4567             :     return false;
    4568           6 :   EVT VT = Op.getValueType();
    4569           2 :   if (VT != MVT::f32 && !Subtarget->isFPBrccSlow())
    4570             :     // f32 case is generally profitable. f64 case only makes sense when vcmpe +
    4571             :     // vmrs are very slow, e.g. cortex-a8.
    4572             :     return false;
    4573             : 
    4574           6 :   if (isFloatingPointZero(Op)) {
    4575           2 :     SeenZero = true;
    4576             :     return true;
    4577             :   }
    4578             :   return ISD::isNormalLoad(N);
    4579             : }
    4580             : 
    4581           2 : static SDValue bitcastf32Toi32(SDValue Op, SelectionDAG &DAG) {
    4582           2 :   if (isFloatingPointZero(Op))
    4583           2 :     return DAG.getConstant(0, SDLoc(Op), MVT::i32);
    4584             : 
    4585             :   if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Op))
    4586           1 :     return DAG.getLoad(MVT::i32, SDLoc(Op), Ld->getChain(), Ld->getBasePtr(),
    4587           1 :                        Ld->getPointerInfo(), Ld->getAlignment(),
    4588           3 :                        Ld->getMemOperand()->getFlags());
    4589             : 
    4590           0 :   llvm_unreachable("Unknown VFP cmp argument!");
    4591             : }
    4592             : 
    4593           2 : static void expandf64Toi32(SDValue Op, SelectionDAG &DAG,
    4594             :                            SDValue &RetVal1, SDValue &RetVal2) {
    4595             :   SDLoc dl(Op);
    4596             : 
    4597           2 :   if (isFloatingPointZero(Op)) {
    4598           1 :     RetVal1 = DAG.getConstant(0, dl, MVT::i32);
    4599           1 :     RetVal2 = DAG.getConstant(0, dl, MVT::i32);
    4600             :     return;
    4601             :   }
    4602             : 
    4603             :   if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Op)) {
    4604           1 :     SDValue Ptr = Ld->getBasePtr();
    4605           1 :     RetVal1 =
    4606           3 :         DAG.getLoad(MVT::i32, dl, Ld->getChain(), Ptr, Ld->getPointerInfo(),
    4607           2 :                     Ld->getAlignment(), Ld->getMemOperand()->getFlags());
    4608             : 
    4609           1 :     EVT PtrType = Ptr.getValueType();
    4610           2 :     unsigned NewAlign = MinAlign(Ld->getAlignment(), 4);
    4611             :     SDValue NewPtr = DAG.getNode(ISD::ADD, dl,
    4612           1 :                                  PtrType, Ptr, DAG.getConstant(4, dl, PtrType));
    4613           1 :     RetVal2 = DAG.getLoad(MVT::i32, dl, Ld->getChain(), NewPtr,
    4614             :                           Ld->getPointerInfo().getWithOffset(4), NewAlign,
    4615           3 :                           Ld->getMemOperand()->getFlags());
    4616             :     return;
    4617             :   }
    4618             : 
    4619           0 :   llvm_unreachable("Unknown VFP cmp argument!");
    4620             : }
    4621             : 
    4622             : /// OptimizeVFPBrcond - With -enable-unsafe-fp-math, it's legal to optimize some
    4623             : /// f32 and even f64 comparisons to integer ones.
    4624             : SDValue
    4625           3 : ARMTargetLowering::OptimizeVFPBrcond(SDValue Op, SelectionDAG &DAG) const {
    4626           3 :   SDValue Chain = Op.getOperand(0);
    4627           3 :   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(1))->get();
    4628           3 :   SDValue LHS = Op.getOperand(2);
    4629           3 :   SDValue RHS = Op.getOperand(3);
    4630           3 :   SDValue Dest = Op.getOperand(4);
    4631             :   SDLoc dl(Op);
    4632             : 
    4633           3 :   bool LHSSeenZero = false;
    4634           3 :   bool LHSOk = canChangeToInt(LHS, LHSSeenZero, Subtarget);
    4635           3 :   bool RHSSeenZero = false;
    4636           3 :   bool RHSOk = canChangeToInt(RHS, RHSSeenZero, Subtarget);
    4637           3 :   if (LHSOk && RHSOk && (LHSSeenZero || RHSSeenZero)) {
    4638             :     // If unsafe fp math optimization is enabled and there are no other uses of
    4639             :     // the CMP operands, and the condition code is EQ or NE, we can optimize it
    4640             :     // to an integer comparison.
    4641           2 :     if (CC == ISD::SETOEQ)
    4642             :       CC = ISD::SETEQ;
    4643           2 :     else if (CC == ISD::SETUNE)
    4644             :       CC = ISD::SETNE;
    4645             : 
    4646           2 :     SDValue Mask = DAG.getConstant(0x7fffffff, dl, MVT::i32);
    4647           2 :     SDValue ARMcc;
    4648             :     if (LHS.getValueType() == MVT::f32) {
    4649           1 :       LHS = DAG.getNode(ISD::AND, dl, MVT::i32,
    4650           2 :                         bitcastf32Toi32(LHS, DAG), Mask);
    4651           1 :       RHS = DAG.getNode(ISD::AND, dl, MVT::i32,
    4652           2 :                         bitcastf32Toi32(RHS, DAG), Mask);
    4653           1 :       SDValue Cmp = getARMCmp(LHS, RHS, CC, ARMcc, DAG, dl);
    4654           1 :       SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
    4655             :       return DAG.getNode(ARMISD::BRCOND, dl, MVT::Other,
    4656           1 :                          Chain, Dest, ARMcc, CCR, Cmp);
    4657             :     }
    4658             : 
    4659           1 :     SDValue LHS1, LHS2;
    4660           1 :     SDValue RHS1, RHS2;
    4661           1 :     expandf64Toi32(LHS, DAG, LHS1, LHS2);
    4662           1 :     expandf64Toi32(RHS, DAG, RHS1, RHS2);
    4663           1 :     LHS2 = DAG.getNode(ISD::AND, dl, MVT::i32, LHS2, Mask);
    4664           1 :     RHS2 = DAG.getNode(ISD::AND, dl, MVT::i32, RHS2, Mask);
    4665           1 :     ARMCC::CondCodes CondCode = IntCCToARMCC(CC);
    4666           1 :     ARMcc = DAG.getConstant(CondCode, dl, MVT::i32);
    4667           1 :     SDVTList VTList = DAG.getVTList(MVT::Other, MVT::Glue);
    4668           1 :     SDValue Ops[] = { Chain, ARMcc, LHS1, LHS2, RHS1, RHS2, Dest };
    4669           1 :     return DAG.getNode(ARMISD::BCC_i64, dl, VTList, Ops);
    4670             :   }
    4671             : 
    4672           1 :   return SDValue();
    4673             : }
    4674             : 
    4675         269 : SDValue ARMTargetLowering::LowerBRCOND(SDValue Op, SelectionDAG &DAG) const {
    4676         269 :   SDValue Chain = Op.getOperand(0);
    4677         269 :   SDValue Cond = Op.getOperand(1);
    4678         269 :   SDValue Dest = Op.getOperand(2);
    4679             :   SDLoc dl(Op);
    4680             : 
    4681             :   // Optimize {s|u}{add|sub|mul}.with.overflow feeding into a branch
    4682             :   // instruction.
    4683             :   unsigned Opc = Cond.getOpcode();
    4684         269 :   bool OptimizeMul = (Opc == ISD::SMULO || Opc == ISD::UMULO) &&
    4685           0 :                       !Subtarget->isThumb1Only();
    4686         275 :   if (Cond.getResNo() == 1 &&
    4687           6 :       (Opc == ISD::SADDO || Opc == ISD::UADDO || Opc == ISD::SSUBO ||
    4688           0 :        Opc == ISD::USUBO || OptimizeMul)) {
    4689             :     // Only lower legal XALUO ops.
    4690           6 :     if (!DAG.getTargetLoweringInfo().isTypeLegal(Cond->getValueType(0)))
    4691           0 :       return SDValue();
    4692             : 
    4693             :     // The actual operation with overflow check.
    4694             :     SDValue Value, OverflowCmp;
    4695           6 :     SDValue ARMcc;
    4696          12 :     std::tie(Value, OverflowCmp) = getARMXALUOOp(Cond, DAG, ARMcc);
    4697             : 
    4698             :     // Reverse the condition code.
    4699             :     ARMCC::CondCodes CondCode =
    4700          12 :         (ARMCC::CondCodes)cast<const ConstantSDNode>(ARMcc)->getZExtValue();
    4701           6 :     CondCode = ARMCC::getOppositeCondition(CondCode);
    4702          12 :     ARMcc = DAG.getConstant(CondCode, SDLoc(ARMcc), MVT::i32);
    4703           6 :     SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
    4704             : 
    4705             :     return DAG.getNode(ARMISD::BRCOND, dl, MVT::Other, Chain, Dest, ARMcc, CCR,
    4706           6 :                        OverflowCmp);
    4707             :   }
    4708             : 
    4709         263 :   return SDValue();
    4710             : }
    4711             : 
    4712        1834 : SDValue ARMTargetLowering::LowerBR_CC(SDValue Op, SelectionDAG &DAG) const {
    4713        1834 :   SDValue Chain = Op.getOperand(0);
    4714        1834 :   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(1))->get();
    4715        1834 :   SDValue LHS = Op.getOperand(2);
    4716        1834 :   SDValue RHS = Op.getOperand(3);
    4717        1834 :   SDValue Dest = Op.getOperand(4);
    4718             :   SDLoc dl(Op);
    4719             : 
    4720        1834 :   if (Subtarget->isFPOnlySP() && LHS.getValueType() == MVT::f64) {
    4721           0 :     DAG.getTargetLoweringInfo().softenSetCCOperands(DAG, MVT::f64, LHS, RHS, CC,
    4722             :                                                     dl);
    4723             : 
    4724             :     // If softenSetCCOperands only returned one value, we should compare it to
    4725             :     // zero.
    4726           0 :     if (!RHS.getNode()) {
    4727           0 :       RHS = DAG.getConstant(0, dl, LHS.getValueType());
    4728           0 :       CC = ISD::SETNE;
    4729             :     }
    4730             :   }
    4731             : 
    4732             :   // Optimize {s|u}{add|sub|mul}.with.overflow feeding into a branch
    4733             :   // instruction.
    4734        1834 :   unsigned Opc = LHS.getOpcode();
    4735        1834 :   bool OptimizeMul = (Opc == ISD::SMULO || Opc == ISD::UMULO) &&
    4736           4 :                       !Subtarget->isThumb1Only();
    4737        1862 :   if (LHS.getResNo() == 1 && (isOneConstant(RHS) || isNullConstant(RHS)) &&
    4738          14 :       (Opc == ISD::SADDO || Opc == ISD::UADDO || Opc == ISD::SSUBO ||
    4739        1850 :        Opc == ISD::USUBO || OptimizeMul) &&
    4740          12 :       (CC == ISD::SETEQ || CC == ISD::SETNE)) {
    4741             :     // Only lower legal XALUO ops.
    4742          12 :     if (!DAG.getTargetLoweringInfo().isTypeLegal(LHS->getValueType(0)))
    4743           0 :       return SDValue();
    4744             : 
    4745             :     // The actual operation with overflow check.
    4746             :     SDValue Value, OverflowCmp;
    4747          12 :     SDValue ARMcc;
    4748          24 :     std::tie(Value, OverflowCmp) = getARMXALUOOp(LHS.getValue(0), DAG, ARMcc);
    4749             : 
    4750          12 :     if ((CC == ISD::SETNE) != isOneConstant(RHS)) {
    4751             :       // Reverse the condition code.
    4752             :       ARMCC::CondCodes CondCode =
    4753           0 :           (ARMCC::CondCodes)cast<const ConstantSDNode>(ARMcc)->getZExtValue();
    4754           0 :       CondCode = ARMCC::getOppositeCondition(CondCode);
    4755           0 :       ARMcc = DAG.getConstant(CondCode, SDLoc(ARMcc), MVT::i32);
    4756             :     }
    4757          12 :     SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
    4758             : 
    4759             :     return DAG.getNode(ARMISD::BRCOND, dl, MVT::Other, Chain, Dest, ARMcc, CCR,
    4760          12 :                        OverflowCmp);
    4761             :   }
    4762             : 
    4763        1822 :   if (LHS.getValueType() == MVT::i32) {
    4764        1769 :     SDValue ARMcc;
    4765        1769 :     SDValue Cmp = getARMCmp(LHS, RHS, CC, ARMcc, DAG, dl);
    4766        1769 :     SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
    4767             :     return DAG.getNode(ARMISD::BRCOND, dl, MVT::Other,
    4768        1769 :                        Chain, Dest, ARMcc, CCR, Cmp);
    4769             :   }
    4770             : 
    4771         109 :   if (getTargetMachine().Options.UnsafeFPMath &&
    4772           5 :       (CC == ISD::SETEQ || CC == ISD::SETOEQ ||
    4773          55 :        CC == ISD::SETNE || CC == ISD::SETUNE)) {
    4774           3 :     if (SDValue Result = OptimizeVFPBrcond(Op, DAG))
    4775           2 :       return Result;
    4776             :   }
    4777             : 
    4778             :   ARMCC::CondCodes CondCode, CondCode2;
    4779             :   bool InvalidOnQNaN;
    4780          51 :   FPCCToARMCC(CC, CondCode, CondCode2, InvalidOnQNaN);
    4781             : 
    4782          51 :   SDValue ARMcc = DAG.getConstant(CondCode, dl, MVT::i32);
    4783          51 :   SDValue Cmp = getVFPCmp(LHS, RHS, DAG, dl, InvalidOnQNaN);
    4784          51 :   SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
    4785          51 :   SDVTList VTList = DAG.getVTList(MVT::Other, MVT::Glue);
    4786          51 :   SDValue Ops[] = { Chain, Dest, ARMcc, CCR, Cmp };
    4787          51 :   SDValue Res = DAG.getNode(ARMISD::BRCOND, dl, VTList, Ops);
    4788          51 :   if (CondCode2 != ARMCC::AL) {
    4789           2 :     ARMcc = DAG.getConstant(CondCode2, dl, MVT::i32);
    4790           2 :     SDValue Ops[] = { Res, Dest, ARMcc, CCR, Res.getValue(1) };
    4791           2 :     Res = DAG.getNode(ARMISD::BRCOND, dl, VTList, Ops);
    4792             :   }
    4793          51 :   return Res;
    4794             : }
    4795             : 
    4796          37 : SDValue ARMTargetLowering::LowerBR_JT(SDValue Op, SelectionDAG &DAG) const {
    4797          37 :   SDValue Chain = Op.getOperand(0);
    4798          37 :   SDValue Table = Op.getOperand(1);
    4799          37 :   SDValue Index = Op.getOperand(2);
    4800             :   SDLoc dl(Op);
    4801             : 
    4802          37 :   EVT PTy = getPointerTy(DAG.getDataLayout());
    4803             :   JumpTableSDNode *JT = cast<JumpTableSDNode>(Table);
    4804          74 :   SDValue JTI = DAG.getTargetJumpTable(JT->getIndex(), PTy);
    4805          37 :   Table = DAG.getNode(ARMISD::WrapperJT, dl, MVT::i32, JTI);
    4806          37 :   Index = DAG.getNode(ISD::MUL, dl, PTy, Index, DAG.getConstant(4, dl, PTy));
    4807          37 :   SDValue Addr = DAG.getNode(ISD::ADD, dl, PTy, Table, Index);
    4808          59 :   if (Subtarget->isThumb2() || (Subtarget->hasV8MBaselineOps() && Subtarget->isThumb())) {
    4809             :     // Thumb2 and ARMv8-M use a two-level jump. That is, it jumps into the jump table
    4810             :     // which does another jump to the destination. This also makes it easier
    4811             :     // to translate it to TBB / TBH later (Thumb2 only).
    4812             :     // FIXME: This might not work if the function is extremely large.
    4813             :     return DAG.getNode(ARMISD::BR2_JT, dl, MVT::Other, Chain,
    4814          18 :                        Addr, Op.getOperand(2), JTI);
    4815             :   }
    4816          19 :   if (isPositionIndependent() || Subtarget->isROPI()) {
    4817          11 :     Addr =
    4818          22 :         DAG.getLoad((EVT)MVT::i32, dl, Chain, Addr,
    4819          22 :                     MachinePointerInfo::getJumpTable(DAG.getMachineFunction()));
    4820          11 :     Chain = Addr.getValue(1);
    4821          11 :     Addr = DAG.getNode(ISD::ADD, dl, PTy, Table, Addr);
    4822          11 :     return DAG.getNode(ARMISD::BR_JT, dl, MVT::Other, Chain, Addr, JTI);
    4823             :   } else {
    4824           8 :     Addr =
    4825          16 :         DAG.getLoad(PTy, dl, Chain, Addr,
    4826          16 :                     MachinePointerInfo::getJumpTable(DAG.getMachineFunction()));
    4827           8 :     Chain = Addr.getValue(1);
    4828           8 :     return DAG.getNode(ARMISD::BR_JT, dl, MVT::Other, Chain, Addr, JTI);
    4829             :   }
    4830             : }
    4831             : 
    4832          79 : static SDValue LowerVectorFP_TO_INT(SDValue Op, SelectionDAG &DAG) {
    4833          79 :   EVT VT = Op.getValueType();
    4834             :   SDLoc dl(Op);
    4835             : 
    4836         158 :   if (Op.getValueType().getVectorElementType() == MVT::i32) {
    4837         234 :     if (Op.getOperand(0).getValueType().getVectorElementType() == MVT::f32)
    4838          72 :       return Op;
    4839           6 :     return DAG.UnrollVectorOp(Op.getNode());
    4840             :   }
    4841             : 
    4842             :   assert(Op.getOperand(0).getValueType() == MVT::v4f32 &&
    4843             :          "Invalid type for custom lowering!");
    4844             :   if (VT != MVT::v4i16)
    4845           0 :     return DAG.UnrollVectorOp(Op.getNode());
    4846             : 
    4847           1 :   Op = DAG.getNode(Op.getOpcode(), dl, MVT::v4i32, Op.getOperand(0));
    4848           1 :   return DAG.getNode(ISD::TRUNCATE, dl, VT, Op);
    4849             : }
    4850             : 
    4851          99 : SDValue ARMTargetLowering::LowerFP_TO_INT(SDValue Op, SelectionDAG &DAG) const {
    4852          99 :   EVT VT = Op.getValueType();
    4853          99 :   if (VT.isVector())
    4854          79 :     return LowerVectorFP_TO_INT(Op, DAG);
    4855          40 :   if (Subtarget->isFPOnlySP() && Op.getOperand(0).getValueType() == MVT::f64) {
    4856             :     RTLIB::Libcall LC;
    4857           8 :     if (Op.getOpcode() == ISD::FP_TO_SINT)
    4858           3 :       LC = RTLIB::getFPTOSINT(Op.getOperand(0).getValueType(),
    4859             :                               Op.getValueType());
    4860             :     else
    4861           5 :       LC = RTLIB::getFPTOUINT(Op.getOperand(0).getValueType(),
    4862             :                               Op.getValueType());
    4863          16 :     return makeLibCall(DAG, LC, Op.getValueType(), Op.getOperand(0),
    4864          32 :                        /*isSigned*/ false, SDLoc(Op)).first;
    4865             :   }
    4866             : 
    4867          12 :   return Op;
    4868             : }
    4869             : 
    4870         148 : static SDValue LowerVectorINT_TO_FP(SDValue Op, SelectionDAG &DAG) {
    4871         148 :   EVT VT = Op.getValueType();
    4872             :   SDLoc dl(Op);
    4873             : 
    4874         444 :   if (Op.getOperand(0).getValueType().getVectorElementType() == MVT::i32) {
    4875         282 :     if (VT.getVectorElementType() == MVT::f32)
    4876         129 :       return Op;
    4877          12 :     return DAG.UnrollVectorOp(Op.getNode());
    4878             :   }
    4879             : 
    4880             :   assert(Op.getOperand(0).getValueType() == MVT::v4i16 &&
    4881             :          "Invalid type for custom lowering!");
    4882           7 :   if (VT != MVT::v4f32)
    4883           0 :     return DAG.UnrollVectorOp(Op.getNode());
    4884             : 
    4885             :   unsigned CastOpc;
    4886             :   unsigned Opc;
    4887           7 :   switch (Op.getOpcode()) {
    4888           0 :   default: llvm_unreachable("Invalid opcode!");
    4889             :   case ISD::SINT_TO_FP:
    4890             :     CastOpc = ISD::SIGN_EXTEND;
    4891             :     Opc = ISD::SINT_TO_FP;
    4892             :     break;
    4893           4 :   case ISD::UINT_TO_FP:
    4894             :     CastOpc = ISD::ZERO_EXTEND;
    4895             :     Opc = ISD::UINT_TO_FP;
    4896           4 :     break;
    4897             :   }
    4898             : 
    4899           7 :   Op = DAG.getNode(CastOpc, dl, MVT::v4i32, Op.getOperand(0));
    4900           7 :   return DAG.getNode(Opc, dl, VT, Op);
    4901             : }
    4902             : 
    4903         168 : SDValue ARMTargetLowering::LowerINT_TO_FP(SDValue Op, SelectionDAG &DAG) const {
    4904         168 :   EVT VT = Op.getValueType();
    4905         168 :   if (VT.isVector())
    4906         148 :     return LowerVectorINT_TO_FP(Op, DAG);
    4907          20 :   if (Subtarget->isFPOnlySP() && Op.getValueType() == MVT::f64) {
    4908             :     RTLIB::Libcall LC;
    4909           8 :     if (Op.getOpcode() == ISD::SINT_TO_FP)
    4910          10 :       LC = RTLIB::getSINTTOFP(Op.getOperand(0).getValueType(),
    4911             :                               Op.getValueType());
    4912             :     else
    4913           6 :       LC = RTLIB::getUINTTOFP(Op.getOperand(0).getValueType(),
    4914             :                               Op.getValueType());
    4915          16 :     return makeLibCall(DAG, LC, Op.getValueType(), Op.getOperand(0),
    4916          32 :                        /*isSigned*/ false, SDLoc(Op)).first;
    4917             :   }
    4918             : 
    4919          12 :   return Op;
    4920             : }
    4921             : 
    4922          22 : SDValue ARMTargetLowering::LowerFCOPYSIGN(SDValue Op, SelectionDAG &DAG) const {
    4923             :   // Implement fcopysign with a fabs and a conditional fneg.
    4924          22 :   SDValue Tmp0 = Op.getOperand(0);
    4925          22 :   SDValue Tmp1 = Op.getOperand(1);
    4926             :   SDLoc dl(Op);
    4927             :   EVT VT = Op.getValueType();
    4928             :   EVT SrcVT = Tmp1.getValueType();
    4929          22 :   bool InGPR = Tmp0.getOpcode() == ISD::BITCAST ||
    4930             :     Tmp0.getOpcode() == ARMISD::VMOVDRR;
    4931          20 :   bool UseNEON = !InGPR && Subtarget->hasNEON();
    4932             : 
    4933             :   if (UseNEON) {
    4934             :     // Use VBSL to copy the sign bit.
    4935             :     unsigned EncodedVal = ARM_AM::createNEONModImm(0x6, 0x80);
    4936             :     SDValue Mask = DAG.getNode(ARMISD::VMOVIMM, dl, MVT::v2i32,
    4937          12 :                                DAG.getTargetConstant(EncodedVal, dl, MVT::i32));
    4938             :     EVT OpVT = (VT == MVT::f32) ? MVT::v2i32 : MVT::v1i64;
    4939             :     if (VT == MVT::f64)
    4940           5 :       Mask = DAG.getNode(ARMISD::VSHL, dl, OpVT,
    4941             :                          DAG.getNode(ISD::BITCAST, dl, OpVT, Mask),
    4942          15 :                          DAG.getConstant(32, dl, MVT::i32));
    4943             :     else /*if (VT == MVT::f32)*/
    4944           7 :       Tmp0 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f32, Tmp0);
    4945             :     if (SrcVT == MVT::f32) {
    4946           5 :       Tmp1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f32, Tmp1);
    4947             :       if (VT == MVT::f64)
    4948           0 :         Tmp1 = DAG.getNode(ARMISD::VSHL, dl, OpVT,
    4949             :                            DAG.getNode(ISD::BITCAST, dl, OpVT, Tmp1),
    4950           0 :                            DAG.getConstant(32, dl, MVT::i32));
    4951             :     } else if (VT == MVT::f32)
    4952           2 :       Tmp1 = DAG.getNode(ARMISD::VSHRu, dl, MVT::v1i64,
    4953             :                          DAG.getNode(ISD::BITCAST, dl, MVT::v1i64, Tmp1),
    4954           6 :                          DAG.getConstant(32, dl, MVT::i32));
    4955          12 :     Tmp0 = DAG.getNode(ISD::BITCAST, dl, OpVT, Tmp0);
    4956          12 :     Tmp1 = DAG.getNode(ISD::BITCAST, dl, OpVT, Tmp1);
    4957             : 
    4958             :     SDValue AllOnes = DAG.getTargetConstant(ARM_AM::createNEONModImm(0xe, 0xff),
    4959          12 :                                             dl, MVT::i32);
    4960          12 :     AllOnes = DAG.getNode(ARMISD::VMOVIMM, dl, MVT::v8i8, AllOnes);
    4961             :     SDValue MaskNot = DAG.getNode(ISD::XOR, dl, OpVT, Mask,
    4962          12 :                                   DAG.getNode(ISD::BITCAST, dl, OpVT, AllOnes));
    4963             : 
    4964             :     SDValue Res = DAG.getNode(ISD::OR, dl, OpVT,
    4965             :                               DAG.getNode(ISD::AND, dl, OpVT, Tmp1, Mask),
    4966          24 :                               DAG.getNode(ISD::AND, dl, OpVT, Tmp0, MaskNot));
    4967             :     if (VT == MVT::f32) {
    4968           7 :       Res = DAG.getNode(ISD::BITCAST, dl, MVT::v2f32, Res);
    4969           7 :       Res = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f32, Res,
    4970          14 :                         DAG.getConstant(0, dl, MVT::i32));
    4971             :     } else {
    4972           5 :       Res = DAG.getNode(ISD::BITCAST, dl, MVT::f64, Res);
    4973             :     }
    4974             : 
    4975          12 :     return Res;
    4976             :   }
    4977             : 
    4978             :   // Bitcast operand 1 to i32.
    4979             :   if (SrcVT == MVT::f64)
    4980          12 :     Tmp1 = DAG.getNode(ARMISD::VMOVRRD, dl, DAG.getVTList(MVT::i32, MVT::i32),
    4981          18 :                        Tmp1).getValue(1);
    4982          10 :   Tmp1 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Tmp1);
    4983             : 
    4984             :   // Or in the signbit with integer operations.
    4985          10 :   SDValue Mask1 = DAG.getConstant(0x80000000, dl, MVT::i32);
    4986          10 :   SDValue Mask2 = DAG.getConstant(0x7fffffff, dl, MVT::i32);
    4987          10 :   Tmp1 = DAG.getNode(ISD::AND, dl, MVT::i32, Tmp1, Mask1);
    4988             :   if (VT == MVT::f32) {
    4989           4 :     Tmp0 = DAG.getNode(ISD::AND, dl, MVT::i32,
    4990           8 :                        DAG.getNode(ISD::BITCAST, dl, MVT::i32, Tmp0), Mask2);
    4991             :     return DAG.getNode(ISD::BITCAST, dl, MVT::f32,
    4992           8 :                        DAG.getNode(ISD::OR, dl, MVT::i32, Tmp0, Tmp1));
    4993             :   }
    4994             : 
    4995             :   // f64: Or the high part with signbit and then combine two parts.
    4996           6 :   Tmp0 = DAG.getNode(ARMISD::VMOVRRD, dl, DAG.getVTList(MVT::i32, MVT::i32),
    4997          12 :                      Tmp0);
    4998           6 :   SDValue Lo = Tmp0.getValue(0);
    4999           6 :   SDValue Hi = DAG.getNode(ISD::AND, dl, MVT::i32, Tmp0.getValue(1), Mask2);
    5000           6 :   Hi = DAG.getNode(ISD::OR, dl, MVT::i32, Hi, Tmp1);
    5001           6 :   return DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi);
    5002             : }
    5003             : 
    5004          12 : SDValue ARMTargetLowering::LowerRETURNADDR(SDValue Op, SelectionDAG &DAG) const{
    5005          12 :   MachineFunction &MF = DAG.getMachineFunction();
    5006          12 :   MachineFrameInfo &MFI = MF.getFrameInfo();
    5007             :   MFI.setReturnAddressIsTaken(true);
    5008             : 
    5009          12 :   if (verifyReturnAddressArgumentIsConstant(Op, DAG))
    5010           0 :     return SDValue();
    5011             : 
    5012          12 :   EVT VT = Op.getValueType();
    5013             :   SDLoc dl(Op);
    5014          24 :   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
    5015          12 :   if (Depth) {
    5016           4 :     SDValue FrameAddr = LowerFRAMEADDR(Op, DAG);
    5017           4 :     SDValue Offset = DAG.getConstant(4, dl, MVT::i32);
    5018             :     return DAG.getLoad(VT, dl, DAG.getEntryNode(),
    5019             :                        DAG.getNode(ISD::ADD, dl, VT, FrameAddr, Offset),
    5020           8 :                        MachinePointerInfo());
    5021             :   }
    5022             : 
    5023             :   // Return LR, which contains the return address. Mark it an implicit live-in.
    5024          16 :   unsigned Reg = MF.addLiveIn(ARM::LR, getRegClassFor(MVT::i32));
    5025           8 :   return DAG.getCopyFromReg(DAG.getEntryNode(), dl, Reg, VT);
    5026             : }
    5027             : 
    5028          48 : SDValue ARMTargetLowering::LowerFRAMEADDR(SDValue Op, SelectionDAG &DAG) const {
    5029          48 :   const ARMBaseRegisterInfo &ARI =
    5030             :     *static_cast<const ARMBaseRegisterInfo*>(RegInfo);
    5031          48 :   MachineFunction &MF = DAG.getMachineFunction();
    5032          48 :   MachineFrameInfo &MFI = MF.getFrameInfo();
    5033             :   MFI.setFrameAddressIsTaken(true);
    5034             : 
    5035          48 :   EVT VT = Op.getValueType();
    5036             :   SDLoc dl(Op);  // FIXME probably not meaningful
    5037          96 :   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
    5038          48 :   unsigned FrameReg = ARI.getFrameRegister(MF);
    5039          48 :   SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, VT);
    5040          72 :   while (Depth--)
    5041          12 :     FrameAddr = DAG.getLoad(VT, dl, DAG.getEntryNode(), FrameAddr,
    5042          12 :                             MachinePointerInfo());
    5043          96 :   return FrameAddr;
    5044             : }
    5045             : 
    5046             : // FIXME? Maybe this could be a TableGen attribute on some registers and
    5047             : // this table could be generated automatically from RegInfo.
    5048          13 : unsigned ARMTargetLowering::getRegisterByName(const char* RegName, EVT VT,
    5049             :                                               SelectionDAG &DAG) const {
    5050          13 :   unsigned Reg = StringSwitch<unsigned>(RegName)
    5051             :                        .Case("sp", ARM::SP)
    5052             :                        .Default(0);
    5053           4 :   if (Reg)
    5054           4 :     return Reg;
    5055           9 :   report_fatal_error(Twine("Invalid register name \""
    5056             :                               + StringRef(RegName)  + "\"."));
    5057             : }
    5058             : 
    5059             : // Result is 64 bit value so split into two 32 bit values and return as a
    5060             : // pair of values.
    5061           2 : static void ExpandREAD_REGISTER(SDNode *N, SmallVectorImpl<SDValue> &Results,
    5062             :                                 SelectionDAG &DAG) {
    5063             :   SDLoc DL(N);
    5064             : 
    5065             :   // This function is only supposed to be called for i64 type destination.
    5066             :   assert(N->getValueType(0) == MVT::i64
    5067             :           && "ExpandREAD_REGISTER called for non-i64 type result.");
    5068             : 
    5069             :   SDValue Read = DAG.getNode(ISD::READ_REGISTER, DL,
    5070             :                              DAG.getVTList(MVT::i32, MVT::i32, MVT::Other),
    5071             :                              N->getOperand(0),
    5072           4 :                              N->getOperand(1));
    5073             : 
    5074           4 :   Results.push_back(DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, Read.getValue(0),
    5075           2 :                     Read.getValue(1)));
    5076           2 :   Results.push_back(Read.getOperand(0));
    5077           2 : }
    5078             : 
    5079             : /// \p BC is a bitcast that is about to be turned into a VMOVDRR.
    5080             : /// When \p DstVT, the destination type of \p BC, is on the vector
    5081             : /// register bank and the source of bitcast, \p Op, operates on the same bank,
    5082             : /// it might be possible to combine them, such that everything stays on the
    5083             : /// vector register bank.
    5084             : /// \p return The node that would replace \p BT, if the combine
    5085             : /// is possible.
    5086          55 : static SDValue CombineVMOVDRRCandidateWithVecOp(const SDNode *BC,
    5087             :                                                 SelectionDAG &DAG) {
    5088          55 :   SDValue Op = BC->getOperand(0);
    5089         110 :   EVT DstVT = BC->getValueType(0);
    5090             : 
    5091             :   // The only vector instruction that can produce a scalar (remember,
    5092             :   // since the bitcast was about to be turned into VMOVDRR, the source
    5093             :   // type is i64) from a vector is EXTRACT_VECTOR_ELT.
    5094             :   // Moreover, we can do this combine only if there is one use.
    5095             :   // Finally, if the destination type is not a vector, there is not
    5096             :   // much point on forcing everything on the vector bank.
    5097         101 :   if (!DstVT.isVector() || Op.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
    5098             :       !Op.hasOneUse())
    5099          50 :     return SDValue();
    5100             : 
    5101             :   // If the index is not constant, we will introduce an additional
    5102             :   // multiply that will stick.
    5103             :   // Give up in that case.
    5104             :   ConstantSDNode *Index = dyn_cast<ConstantSDNode>(Op.getOperand(1));
    5105             :   if (!Index)
    5106           1 :     return SDValue();
    5107           4 :   unsigned DstNumElt = DstVT.getVectorNumElements();
    5108             : 
    5109             :   // Compute the new index.
    5110           4 :   const APInt &APIntIndex = Index->getAPIntValue();
    5111           4 :   APInt NewIndex(APIntIndex.getBitWidth(), DstNumElt);
    5112           4 :   NewIndex *= APIntIndex;
    5113             :   // Check if the new constant index fits into i32.
    5114           4 :   if (NewIndex.getBitWidth() > 32)
    5115           0 :     return SDValue();
    5116             : 
    5117             :   // vMTy bitcast(i64 extractelt vNi64 src, i32 index) ->
    5118             :   // vMTy extractsubvector vNxMTy (bitcast vNi64 src), i32 index*M)
    5119             :   SDLoc dl(Op);
    5120           4 :   SDValue ExtractSrc = Op.getOperand(0);
    5121             :   EVT VecVT = EVT::getVectorVT(
    5122           4 :       *DAG.getContext(), DstVT.getScalarType(),
    5123           8 :       ExtractSrc.getValueType().getVectorNumElements() * DstNumElt);
    5124           4 :   SDValue BitCast = DAG.getNode(ISD::BITCAST, dl, VecVT, ExtractSrc);
    5125             :   return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DstVT, BitCast,
    5126           4 :                      DAG.getConstant(NewIndex.getZExtValue(), dl, MVT::i32));
    5127             : }
    5128             : 
    5129             : /// ExpandBITCAST - If the target supports VFP, this function is called to
    5130             : /// expand a bit convert where either the source or destination type is i64 to
    5131             : /// use a VMOVDRR or VMOVRRD node.  This should not be done when the non-i64
    5132             : /// operand type is illegal (e.g., v2f32 for a target that doesn't support
    5133             : /// vectors), since the legalizer won't know what to do with that.
    5134         894 : static SDValue ExpandBITCAST(SDNode *N, SelectionDAG &DAG,
    5135             :                              const ARMSubtarget *Subtarget) {
    5136         894 :   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
    5137             :   SDLoc dl(N);
    5138         894 :   SDValue Op = N->getOperand(0);
    5139             : 
    5140             :   // This function is only supposed to be called for i64 types, either as the
    5141             :   // source or destination of the bit convert.
    5142         894 :   EVT SrcVT = Op.getValueType();
    5143        1788 :   EVT DstVT = N->getValueType(0);
    5144         894 :   const bool HasFullFP16 = Subtarget->hasFullFP16();
    5145             : 
    5146             :   if (SrcVT == MVT::f32 && DstVT == MVT::i32) {
    5147             :      // FullFP16: half values are passed in S-registers, and we don't
    5148             :      // need any of the bitcast and moves:
    5149             :      //
    5150             :      // t2: f32,ch = CopyFromReg t0, Register:f32 %0
    5151             :      //   t5: i32 = bitcast t2
    5152             :      // t18: f16 = ARMISD::VMOVhr t5
    5153         172 :      if (Op.getOpcode() != ISD::CopyFromReg ||
    5154             :          Op.getValueType() != MVT::f32)
    5155           4 :        return SDValue();
    5156             : 
    5157         168 :      auto Move = N->use_begin();
    5158         168 :      if (Move->getOpcode() != ARMISD::VMOVhr)
    5159           0 :        return SDValue();
    5160             : 
    5161         168 :      SDValue Ops[] = { Op.getOperand(0), Op.getOperand(1) };
    5162         336 :      SDValue Copy = DAG.getNode(ISD::CopyFromReg, SDLoc(Op), MVT::f16, Ops);
    5163         168 :      DAG.ReplaceAllUsesWith(*Move, &Copy);
    5164         168 :      return Copy;
    5165             :   }
    5166             : 
    5167             :   if (SrcVT == MVT::i16 && DstVT == MVT::f16) {
    5168         540 :     if (!HasFullFP16)
    5169           0 :       return SDValue();
    5170             :     // SoftFP: read half-precision arguments:
    5171             :     //
    5172             :     // t2: i32,ch = ... 
    5173             :     //        t7: i16 = truncate t2 <~~~~ Op
    5174             :     //      t8: f16 = bitcast t7    <~~~~ N
    5175             :     //
    5176         540 :     if (Op.getOperand(0).getValueType() == MVT::i32)
    5177         540 :       return DAG.getNode(ARMISD::VMOVhr, SDLoc(Op),
    5178        1080 :                          MVT::f16, Op.getOperand(0));
    5179             : 
    5180           0 :     return SDValue();
    5181             :   }
    5182             : 
    5183             :   // Half-precision return values 
    5184             :   if (SrcVT == MVT::f16 && DstVT == MVT::i16) {
    5185         100 :     if (!HasFullFP16)
    5186           0 :       return SDValue();
    5187             :     //
    5188             :     //          t11: f16 = fadd t8, t10
    5189             :     //        t12: i16 = bitcast t11       <~~~ SDNode N
    5190             :     //      t13: i32 = zero_extend t12
    5191             :     //    t16: ch,glue = CopyToReg t0, Register:i32 %r0, t13
    5192             :     //  t17: ch = ARMISD::RET_FLAG t16, Register:i32 %r0, t16:1
    5193             :     //
    5194             :     // transform this into:
    5195             :     //
    5196             :     //    t20: i32 = ARMISD::VMOVrh t11
    5197             :     //  t16: ch,glue = CopyToReg t0, Register:i32 %r0, t20
    5198             :     //
    5199         100 :     auto ZeroExtend = N->use_begin();
    5200         200 :     if (N->use_size() != 1 || ZeroExtend->getOpcode() != ISD::ZERO_EXTEND ||
    5201         100 :         ZeroExtend->getValueType(0) != MVT::i32)
    5202           0 :       return SDValue();
    5203             : 
    5204         100 :     auto Copy = ZeroExtend->use_begin();
    5205         200 :     if (Copy->getOpcode() == ISD::CopyToReg &&
    5206         200 :         Copy->use_begin()->getOpcode() == ARMISD::RET_FLAG) {
    5207         200 :       SDValue Cvt = DAG.getNode(ARMISD::VMOVrh, SDLoc(Op), MVT::i32, Op);
    5208         100 :       DAG.ReplaceAllUsesWith(*ZeroExtend, &Cvt);
    5209         100 :       return Cvt;
    5210             :     }
    5211           0 :     return SDValue();
    5212             :   }
    5213             : 
    5214             :   if (!(SrcVT == MVT::i64 || DstVT == MVT::i64))
    5215           0 :     return SDValue();
    5216             : 
    5217             :   // Turn i64->f64 into VMOVDRR.
    5218             :   if (SrcVT == MVT::i64 && TLI.isTypeLegal(DstVT)) {
    5219             :     // Do not force values to GPRs (this is what VMOVDRR does for the inputs)
    5220             :     // if we can combine the bitcast with its source.
    5221          55 :     if (SDValue Val = CombineVMOVDRRCandidateWithVecOp(N, DAG))
    5222           4 :       return Val;
    5223             : 
    5224             :     SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, Op,
    5225         102 :                              DAG.getConstant(0, dl, MVT::i32));
    5226             :     SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, Op,
    5227         102 :                              DAG.getConstant(1, dl, MVT::i32));
    5228             :     return DAG.getNode(ISD::BITCAST, dl, DstVT,
    5229          51 :                        DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi));
    5230             :   }
    5231             : 
    5232             :   // Turn f64->i64 into VMOVRRD.
    5233             :   if (DstVT == MVT::i64 && TLI.isTypeLegal(SrcVT)) {
    5234          27 :     SDValue Cvt;
    5235          92 :     if (DAG.getDataLayout().isBigEndian() && SrcVT.isVector() &&
    5236          18 :         SrcVT.getVectorNumElements() > 1)
    5237          16 :       Cvt = DAG.getNode(ARMISD::VMOVRRD, dl,
    5238             :                         DAG.getVTList(MVT::i32, MVT::i32),
    5239          48 :                         DAG.getNode(ARMISD::VREV64, dl, SrcVT, Op));
    5240             :     else
    5241          11 :       Cvt = DAG.getNode(ARMISD::VMOVRRD, dl,
    5242          22 :                         DAG.getVTList(MVT::i32, MVT::i32), Op);
    5243             :     // Merge the pieces into a single i64 value.
    5244          27 :     return DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Cvt, Cvt.getValue(1));
    5245             :   }
    5246             : 
    5247           0 :   return SDValue();
    5248             : }
    5249             : 
    5250             : /// getZeroVector - Returns a vector of specified type with all zero elements.
    5251             : /// Zero vectors are used to represent vector negation and in those cases
    5252             : /// will be implemented with the NEON VNEG instruction.  However, VNEG does
    5253             : /// not support i64 elements, so sometimes the zero vectors will need to be
    5254             : /// explicitly constructed.  Regardless, use a canonical VMOV to create the
    5255             : /// zero vector.
    5256          47 : static SDValue getZeroVector(EVT VT, SelectionDAG &DAG, const SDLoc &dl) {
    5257             :   assert(VT.isVector() && "Expected a vector type");
    5258             :   // The canonical modified immediate encoding of a zero vector is....0!
    5259          47 :   SDValue EncodedVal = DAG.getTargetConstant(0, dl, MVT::i32);
    5260          47 :   EVT VmovVT = VT.is128BitVector() ? MVT::v4i32 : MVT::v2i32;
    5261          47 :   SDValue Vmov = DAG.getNode(ARMISD::VMOVIMM, dl, VmovVT, EncodedVal);
    5262          47 :   return DAG.getNode(ISD::BITCAST, dl, VT, Vmov);
    5263             : }
    5264             : 
    5265             : /// LowerShiftRightParts - Lower SRA_PARTS, which returns two
    5266             : /// i32 values and take a 2 x i32 value to shift plus a shift amount.
    5267           6 : SDValue ARMTargetLowering::LowerShiftRightParts(SDValue Op,
    5268             :                                                 SelectionDAG &DAG) const {
    5269             :   assert(Op.getNumOperands() == 3 && "Not a double-shift!");
    5270           6 :   EVT VT = Op.getValueType();
    5271           6 :   unsigned VTBits = VT.getSizeInBits();
    5272             :   SDLoc dl(Op);
    5273           6 :   SDValue ShOpLo = Op.getOperand(0);
    5274           6 :   SDValue ShOpHi = Op.getOperand(1);
    5275           6 :   SDValue ShAmt  = Op.getOperand(2);
    5276           6 :   SDValue ARMcc;
    5277           6 :   SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
    5278           6 :   unsigned Opc = (Op.getOpcode() == ISD::SRA_PARTS) ? ISD::SRA : ISD::SRL;
    5279             : 
    5280             :   assert(Op.getOpcode() == ISD::SRA_PARTS || Op.getOpcode() == ISD::SRL_PARTS);
    5281             : 
    5282             :   SDValue RevShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32,
    5283          12 :                                  DAG.getConstant(VTBits, dl, MVT::i32), ShAmt);
    5284           6 :   SDValue Tmp1 = DAG.getNode(ISD::SRL, dl, VT, ShOpLo, ShAmt);
    5285             :   SDValue ExtraShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32, ShAmt,
    5286          12 :                                    DAG.getConstant(VTBits, dl, MVT::i32));
    5287           6 :   SDValue Tmp2 = DAG.getNode(ISD::SHL, dl, VT, ShOpHi, RevShAmt);
    5288           6 :   SDValue LoSmallShift = DAG.getNode(ISD::OR, dl, VT, Tmp1, Tmp2);
    5289           6 :   SDValue LoBigShift = DAG.getNode(Opc, dl, VT, ShOpHi, ExtraShAmt);
    5290             :   SDValue CmpLo = getARMCmp(ExtraShAmt, DAG.getConstant(0, dl, MVT::i32),
    5291           6 :                             ISD::SETGE, ARMcc, DAG, dl);
    5292             :   SDValue Lo = DAG.getNode(ARMISD::CMOV, dl, VT, LoSmallShift, LoBigShift,
    5293           6 :                            ARMcc, CCR, CmpLo);
    5294             : 
    5295           6 :   SDValue HiSmallShift = DAG.getNode(Opc, dl, VT, ShOpHi, ShAmt);
    5296             :   SDValue HiBigShift = Opc == ISD::SRA
    5297             :                            ? DAG.getNode(Opc, dl, VT, ShOpHi,
    5298           9 :                                          DAG.getConstant(VTBits - 1, dl, VT))
    5299           9 :                            : DAG.getConstant(0, dl, VT);
    5300             :   SDValue CmpHi = getARMCmp(ExtraShAmt, DAG.getConstant(0, dl, MVT::i32),
    5301           6 :                             ISD::SETGE, ARMcc, DAG, dl);
    5302             :   SDValue Hi = DAG.getNode(ARMISD::CMOV, dl, VT, HiSmallShift, HiBigShift,
    5303           6 :                            ARMcc, CCR, CmpHi);
    5304             : 
    5305           6 :   SDValue Ops[2] = { Lo, Hi };
    5306          12 :   return DAG.getMergeValues(Ops, dl);
    5307             : }
    5308             : 
    5309             : /// LowerShiftLeftParts - Lower SHL_PARTS, which returns two
    5310             : /// i32 values and take a 2 x i32 value to shift plus a shift amount.
    5311           3 : SDValue ARMTargetLowering::LowerShiftLeftParts(SDValue Op,
    5312             :                                                SelectionDAG &DAG) const {
    5313             :   assert(Op.getNumOperands() == 3 && "Not a double-shift!");
    5314           3 :   EVT VT = Op.getValueType();
    5315           3 :   unsigned VTBits = VT.getSizeInBits();
    5316             :   SDLoc dl(Op);
    5317           3 :   SDValue ShOpLo = Op.getOperand(0);
    5318           3 :   SDValue ShOpHi = Op.getOperand(1);
    5319           3 :   SDValue ShAmt  = Op.getOperand(2);
    5320           3 :   SDValue ARMcc;
    5321           3 :   SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
    5322             : 
    5323             :   assert(Op.getOpcode() == ISD::SHL_PARTS);
    5324             :   SDValue RevShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32,
    5325           6 :                                  DAG.getConstant(VTBits, dl, MVT::i32), ShAmt);
    5326           3 :   SDValue Tmp1 = DAG.getNode(ISD::SRL, dl, VT, ShOpLo, RevShAmt);
    5327           3 :   SDValue Tmp2 = DAG.getNode(ISD::SHL, dl, VT, ShOpHi, ShAmt);
    5328           3 :   SDValue HiSmallShift = DAG.getNode(ISD::OR, dl, VT, Tmp1, Tmp2);
    5329             : 
    5330             :   SDValue ExtraShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32, ShAmt,
    5331           6 :                                    DAG.getConstant(VTBits, dl, MVT::i32));
    5332           3 :   SDValue HiBigShift = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ExtraShAmt);
    5333             :   SDValue CmpHi = getARMCmp(ExtraShAmt, DAG.getConstant(0, dl, MVT::i32),
    5334           3 :                             ISD::SETGE, ARMcc, DAG, dl);
    5335             :   SDValue Hi = DAG.getNode(ARMISD::CMOV, dl, VT, HiSmallShift, HiBigShift,
    5336           3 :                            ARMcc, CCR, CmpHi);
    5337             : 
    5338             :   SDValue CmpLo = getARMCmp(ExtraShAmt, DAG.getConstant(0, dl, MVT::i32),
    5339           3 :                           ISD::SETGE, ARMcc, DAG, dl);
    5340           3 :   SDValue LoSmallShift = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ShAmt);
    5341             :   SDValue Lo = DAG.getNode(ARMISD::CMOV, dl, VT, LoSmallShift,
    5342           3 :                            DAG.getConstant(0, dl, VT), ARMcc, CCR, CmpLo);
    5343             : 
    5344           3 :   SDValue Ops[2] = { Lo, Hi };
    5345           6 :   return DAG.getMergeValues(Ops, dl);
    5346             : }
    5347             : 
    5348           3 : SDValue ARMTargetLowering::LowerFLT_ROUNDS_(SDValue Op,
    5349             :                                             SelectionDAG &DAG) const {
    5350             :   // The rounding mode is in bits 23:22 of the FPSCR.
    5351             :   // The ARM rounding mode value to FLT_ROUNDS mapping is 0->1, 1->2, 2->3, 3->0
    5352             :   // The formula we use to implement this is (((FPSCR + 1 << 22) >> 22) & 3)
    5353             :   // so that the shift + and get folded into a bitfield extract.
    5354             :   SDLoc dl(Op);
    5355             :   SDValue Ops[] = { DAG.getEntryNode(),
    5356           6 :                     DAG.getConstant(Intrinsic::arm_get_fpscr, dl, MVT::i32) };
    5357             : 
    5358           3 :   SDValue FPSCR = DAG.getNode(ISD::INTRINSIC_W_CHAIN, dl, MVT::i32, Ops);
    5359             :   SDValue FltRounds = DAG.getNode(ISD::ADD, dl, MVT::i32, FPSCR,
    5360           6 :                                   DAG.getConstant(1U << 22, dl, MVT::i32));
    5361             :   SDValue RMODE = DAG.getNode(ISD::SRL, dl, MVT::i32, FltRounds,
    5362           6 :                               DAG.getConstant(22, dl, MVT::i32));
    5363             :   return DAG.getNode(ISD::AND, dl, MVT::i32, RMODE,
    5364           9 :                      DAG.getConstant(3, dl, MVT::i32));
    5365             : }
    5366             : 
    5367          48 : static SDValue LowerCTTZ(SDNode *N, SelectionDAG &DAG,
    5368             :                          const ARMSubtarget *ST) {
    5369             :   SDLoc dl(N);
    5370          96 :   EVT VT = N->getValueType(0);
    5371          48 :   if (VT.isVector()) {
    5372             :     assert(ST->hasNEON());
    5373             : 
    5374             :     // Compute the least significant set bit: LSB = X & -X
    5375          22 :     SDValue X = N->getOperand(0);
    5376          22 :     SDValue NX = DAG.getNode(ISD::SUB, dl, VT, getZeroVector(VT, DAG, dl), X);
    5377          22 :     SDValue LSB = DAG.getNode(ISD::AND, dl, VT, X, NX);
    5378             : 
    5379          22 :     EVT ElemTy = VT.getVectorElementType();
    5380             : 
    5381             :     if (ElemTy == MVT::i8) {
    5382             :       // Compute with: cttz(x) = ctpop(lsb - 1)
    5383             :       SDValue One = DAG.getNode(ARMISD::VMOVIMM, dl, VT,
    5384           4 :                                 DAG.getTargetConstant(1, dl, ElemTy));
    5385           4 :       SDValue Bits = DAG.getNode(ISD::SUB, dl, VT, LSB, One);
    5386           4 :       return DAG.getNode(ISD::CTPOP, dl, VT, Bits);
    5387             :     }
    5388             : 
    5389          14 :     if ((ElemTy == MVT::i16 || ElemTy == MVT::i32) &&
    5390          14 :         (N->getOpcode() == ISD::CTTZ_ZERO_UNDEF)) {
    5391             :       // Compute with: cttz(x) = (width - 1) - ctlz(lsb), if x != 0
    5392           7 :       unsigned NumBits = ElemTy.getSizeInBits();
    5393             :       SDValue WidthMinus1 =
    5394             :           DAG.getNode(ARMISD::VMOVIMM, dl, VT,
    5395          14 :                       DAG.getTargetConstant(NumBits - 1, dl, ElemTy));
    5396           7 :       SDValue CTLZ = DAG.getNode(ISD::CTLZ, dl, VT, LSB);
    5397           7 :       return DAG.getNode(ISD::SUB, dl, VT, WidthMinus1, CTLZ);
    5398             :     }
    5399             : 
    5400             :     // Compute with: cttz(x) = ctpop(lsb - 1)
    5401             : 
    5402             :     // Since we can only compute the number of bits in a byte with vcnt.8, we
    5403             :     // have to gather the result with pairwise addition (vpaddl) for i16, i32,
    5404             :     // and i64.
    5405             : 
    5406             :     // Compute LSB - 1.
    5407          11 :     SDValue Bits;
    5408             :     if (ElemTy == MVT::i64) {
    5409             :       // Load constant 0xffff'ffff'ffff'ffff to register.
    5410             :       SDValue FF = DAG.getNode(ARMISD::VMOVIMM, dl, VT,
    5411           4 :                                DAG.getTargetConstant(0x1eff, dl, MVT::i32));
    5412           4 :       Bits = DAG.getNode(ISD::ADD, dl, VT, LSB, FF);
    5413             :     } else {
    5414             :       SDValue One = DAG.getNode(ARMISD::VMOVIMM, dl, VT,
    5415           7 :                                 DAG.getTargetConstant(1, dl, ElemTy));
    5416           7 :       Bits = DAG.getNode(ISD::SUB, dl, VT, LSB, One);
    5417             :     }
    5418             : 
    5419             :     // Count #bits with vcnt.8.
    5420          11 :     EVT VT8Bit = VT.is64BitVector() ? MVT::v8i8 : MVT::v16i8;
    5421          11 :     SDValue BitsVT8 = DAG.getNode(ISD::BITCAST, dl, VT8Bit, Bits);
    5422          11 :     SDValue Cnt8 = DAG.getNode(ISD::CTPOP, dl, VT8Bit, BitsVT8);
    5423             : 
    5424             :     // Gather the #bits with vpaddl (pairwise add.)
    5425          11 :     EVT VT16Bit = VT.is64BitVector() ? MVT::v4i16 : MVT::v8i16;
    5426             :     SDValue Cnt16 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT16Bit,
    5427             :         DAG.getTargetConstant(Intrinsic::arm_neon_vpaddlu, dl, MVT::i32),
    5428          11 :         Cnt8);
    5429             :     if (ElemTy == MVT::i16)
    5430           3 :       return Cnt16;
    5431             : 
    5432           8 :     EVT VT32Bit = VT.is64BitVector() ? MVT::v2i32 : MVT::v4i32;
    5433             :     SDValue Cnt32 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT32Bit,
    5434             :         DAG.getTargetConstant(Intrinsic::arm_neon_vpaddlu, dl, MVT::i32),
    5435           8 :         Cnt16);
    5436             :     if (ElemTy == MVT::i32)
    5437           4 :       return Cnt32;
    5438             : 
    5439             :     assert(ElemTy == MVT::i64);
    5440             :     SDValue Cnt64 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
    5441             :         DAG.getTargetConstant(Intrinsic::arm_neon_vpaddlu, dl, MVT::i32),
    5442           4 :         Cnt32);
    5443           4 :     return Cnt64;
    5444             :   }
    5445             : 
    5446          26 :   if (!ST->hasV6T2Ops())
    5447           0 :     return SDValue();
    5448             : 
    5449          52 :   SDValue rbit = DAG.getNode(ISD::BITREVERSE, dl, VT, N->getOperand(0));
    5450          26 :   return DAG.getNode(ISD::CTLZ, dl, VT, rbit);
    5451             : }
    5452             : 
    5453             : /// getCTPOP16BitCounts - Returns a v8i8/v16i8 vector containing the bit-count
    5454             : /// for each 16-bit element from operand, repeated.  The basic idea is to
    5455             : /// leverage vcnt to get the 8-bit counts, gather and add the results.
    5456             : ///
    5457             : /// Trace for v4i16:
    5458             : /// input    = [v0    v1    v2    v3   ] (vi 16-bit element)
    5459             : /// cast: N0 = [w0 w1 w2 w3 w4 w5 w6 w7] (v0 = [w0 w1], wi 8-bit element)
    5460             : /// vcnt: N1 = [b0 b1 b2 b3 b4 b5 b6 b7] (bi = bit-count of 8-bit element wi)
    5461             : /// vrev: N2 = [b1 b0 b3 b2 b5 b4 b7 b6]
    5462             : ///            [b0 b1 b2 b3 b4 b5 b6 b7]
    5463             : ///           +[b1 b0 b3 b2 b5 b4 b7 b6]
    5464             : /// N3=N1+N2 = [k0 k0 k1 k1 k2 k2 k3 k3] (k0 = b0+b1 = bit-count of 16-bit v0,
    5465             : /// vuzp:    = [k0 k1 k2 k3 k0 k1 k2 k3]  each ki is 8-bits)
    5466           4 : static SDValue getCTPOP16BitCounts(SDNode *N, SelectionDAG &DAG) {
    5467           8 :   EVT VT = N->getValueType(0);
    5468             :   SDLoc DL(N);
    5469             : 
    5470           4 :   EVT VT8Bit = VT.is64BitVector() ? MVT::v8i8 : MVT::v16i8;
    5471           8 :   SDValue N0 = DAG.getNode(ISD::BITCAST, DL, VT8Bit, N->getOperand(0));
    5472           4 :   SDValue N1 = DAG.getNode(ISD::CTPOP, DL, VT8Bit, N0);
    5473           4 :   SDValue N2 = DAG.getNode(ARMISD::VREV16, DL, VT8Bit, N1);
    5474           4 :   SDValue N3 = DAG.getNode(ISD::ADD, DL, VT8Bit, N1, N2);
    5475           8 :   return DAG.getNode(ARMISD::VUZP, DL, VT8Bit, N3, N3);
    5476             : }
    5477             : 
    5478             : /// lowerCTPOP16BitElements - Returns a v4i16/v8i16 vector containing the
    5479             : /// bit-count for each 16-bit element from the operand.  We need slightly
    5480             : /// different sequencing for v4i16 and v8i16 to stay within NEON's available
    5481             : /// 64/128-bit registers.
    5482             : ///
    5483             : /// Trace for v4i16:
    5484             : /// input           = [v0    v1    v2    v3    ] (vi 16-bit element)
    5485             : /// v8i8: BitCounts = [k0 k1 k2 k3 k0 k1 k2 k3 ] (ki is the bit-count of vi)
    5486             : /// v8i16:Extended  = [k0    k1    k2    k3    k0    k1    k2    k3    ]
    5487             : /// v4i16:Extracted = [k0    k1    k2    k3    ]
    5488           4 : static SDValue lowerCTPOP16BitElements(SDNode *N, SelectionDAG &DAG) {
    5489           8 :   EVT VT = N->getValueType(0);
    5490             :   SDLoc DL(N);
    5491             : 
    5492           4 :   SDValue BitCounts = getCTPOP16BitCounts(N, DAG);
    5493           4 :   if (VT.is64BitVector()) {
    5494           2 :     SDValue Extended = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::v8i16, BitCounts);
    5495             :     return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v4i16, Extended,
    5496           4 :                        DAG.getIntPtrConstant(0, DL));
    5497             :   } else {
    5498             :     SDValue Extracted = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v8i8,
    5499           4 :                                     BitCounts, DAG.getIntPtrConstant(0, DL));
    5500           2 :     return DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::v8i16, Extracted);
    5501             :   }
    5502             : }
    5503             : 
    5504             : /// lowerCTPOP32BitElements - Returns a v2i32/v4i32 vector containing the
    5505             : /// bit-count for each 32-bit element from the operand.  The idea here is
    5506             : /// to split the vector into 16-bit elements, leverage the 16-bit count
    5507             : /// routine, and then combine the results.
    5508             : ///
    5509             : /// Trace for v2i32 (v4i32 similar with Extracted/Extended exchanged):
    5510             : /// input    = [v0    v1    ] (vi: 32-bit elements)
    5511             : /// Bitcast  = [w0 w1 w2 w3 ] (wi: 16-bit elements, v0 = [w0 w1])
    5512             : /// Counts16 = [k0 k1 k2 k3 ] (ki: 16-bit elements, bit-count of wi)
    5513             : /// vrev: N0 = [k1 k0 k3 k2 ]
    5514             : ///            [k0 k1 k2 k3 ]
    5515             : ///       N1 =+[k1 k0 k3 k2 ]
    5516             : ///            [k0 k2 k1 k3 ]
    5517             : ///       N2 =+[k1 k3 k0 k2 ]
    5518             : ///            [k0    k2    k1    k3    ]
    5519             : /// Extended =+[k1    k3    k0    k2    ]
    5520             : ///            [k0    k2    ]
    5521             : /// Extracted=+[k1    k3    ]
    5522             : ///
    5523           2 : static SDValue lowerCTPOP32BitElements(SDNode *N, SelectionDAG &DAG) {
    5524           4 :   EVT VT = N->getValueType(0);
    5525             :   SDLoc DL(N);
    5526             : 
    5527           2 :   EVT VT16Bit = VT.is64BitVector() ? MVT::v4i16 : MVT::v8i16;
    5528             : 
    5529           4 :   SDValue Bitcast = DAG.getNode(ISD::BITCAST, DL, VT16Bit, N->getOperand(0));
    5530           2 :   SDValue Counts16 = lowerCTPOP16BitElements(Bitcast.getNode(), DAG);
    5531           2 :   SDValue N0 = DAG.getNode(ARMISD::VREV32, DL, VT16Bit, Counts16);
    5532           2 :   SDValue N1 = DAG.getNode(ISD::ADD, DL, VT16Bit, Counts16, N0);
    5533           2 :   SDValue N2 = DAG.getNode(ARMISD::VUZP, DL, VT16Bit, N1, N1);
    5534             : 
    5535           2 :   if (VT.is64BitVector()) {
    5536           1 :     SDValue Extended = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::v4i32, N2);
    5537             :     return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2i32, Extended,
    5538           2 :                        DAG.getIntPtrConstant(0, DL));
    5539             :   } else {
    5540             :     SDValue Extracted = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v4i16, N2,
    5541           2 :                                     DAG.getIntPtrConstant(0, DL));
    5542           1 :     return DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::v4i32, Extracted);
    5543             :   }
    5544             : }
    5545             : 
    5546           4 : static SDValue LowerCTPOP(SDNode *N, SelectionDAG &DAG,
    5547             :                           const ARMSubtarget *ST) {
    5548           8 :   EVT VT = N->getValueType(0);
    5549             : 
    5550             :   assert(ST->hasNEON() && "Custom ctpop lowering requires NEON.");
    5551             :   assert((VT == MVT::v2i32 || VT == MVT::v4i32 ||
    5552             :           VT == MVT::v4i16 || VT == MVT::v8i16) &&
    5553             :          "Unexpected type for custom ctpop lowering");
    5554             : 
    5555           8 :   if (VT.getVectorElementType() == MVT::i32)
    5556           2 :     return lowerCTPOP32BitElements(N, DAG);
    5557             :   else
    5558           2 :     return lowerCTPOP16BitElements(N, DAG);
    5559             : }
    5560             : 
    5561          41 : static SDValue LowerShift(SDNode *N, SelectionDAG &DAG,
    5562             :                           const ARMSubtarget *ST) {
    5563          82 :   EVT VT = N->getValueType(0);
    5564             :   SDLoc dl(N);
    5565             : 
    5566          41 :   if (!VT.isVector())
    5567           0 :     return SDValue();
    5568             : 
    5569             :   // Lower vector shifts on NEON to use VSHL.
    5570             :   assert(ST->hasNEON() && "unexpected vector shift");
    5571             : 
    5572             :   // Left shifts translate directly to the vshiftu intrinsic.
    5573          41 :   if (N->getOpcode() == ISD::SHL)
    5574             :     return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
    5575             :                        DAG.getConstant(Intrinsic::arm_neon_vshiftu, dl,
    5576             :                                        MVT::i32),
    5577          32 :                        N->getOperand(0), N->getOperand(1));
    5578             : 
    5579             :   assert((N->getOpcode() == ISD::SRA ||
    5580             :           N->getOpcode() == ISD::SRL) && "unexpected vector shift opcode");
    5581             : 
    5582             :   // NEON uses the same intrinsics for both left and right shifts.  For
    5583             :   // right shifts, the shift amounts are negative, so negate the vector of
    5584             :   // shift amounts.
    5585          50 :   EVT ShiftVT = N->getOperand(1).getValueType();
    5586             :   SDValue NegatedCount = DAG.getNode(ISD::SUB, dl, ShiftVT,
    5587             :                                      getZeroVector(ShiftVT, DAG, dl),
    5588          25 :                                      N->getOperand(1));
    5589          25 :   Intrinsic::ID vshiftInt = (N->getOpcode() == ISD::SRA ?
    5590             :                              Intrinsic::arm_neon_vshifts :
    5591             :                              Intrinsic::arm_neon_vshiftu);
    5592             :   return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
    5593             :                      DAG.getConstant(vshiftInt, dl, MVT::i32),
    5594          50 :                      N->getOperand(0), NegatedCount);
    5595             : }
    5596             : 
    5597         767 : static SDValue Expand64BitShift(SDNode *N, SelectionDAG &DAG,
    5598             :                                 const ARMSubtarget *ST) {
    5599         767 :   EVT VT = N->getValueType(0);
    5600             :   SDLoc dl(N);
    5601             : 
    5602             :   // We can get here for a node like i32 = ISD::SHL i32, i64
    5603             :   if (VT != MVT::i64)
    5604           0 :     return SDValue();
    5605             : 
    5606             :   assert((N->getOpcode() == ISD::SRL || N->getOpcode() == ISD::SRA) &&
    5607             :          "Unknown shift to lower!");
    5608             : 
    5609             :   // We only lower SRA, SRL of 1 here, all others use generic lowering.
    5610        1534 :   if (!isOneConstant(N->getOperand(1)))
    5611         759 :     return SDValue();
    5612             : 
    5613             :   // If we are in thumb mode, we don't have RRX.
    5614           9 :   if (ST->isThumb1Only()) return SDValue();
    5615             : 
    5616             :   // Okay, we have a 64-bit SRA or SRL of 1.  Lower this to an RRX expr.
    5617           7 :   SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(0),
    5618          14 :                            DAG.getConstant(0, dl, MVT::i32));
    5619           7 :   SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(0),
    5620          14 :                            DAG.getConstant(1, dl, MVT::i32));
    5621             : 
    5622             :   // First, build a SRA_FLAG/SRL_FLAG op, which shifts the top part by one and
    5623             :   // captures the result into a carry flag.
    5624           7 :   unsigned Opc = N->getOpcode() == ISD::SRL ? ARMISD::SRL_FLAG:ARMISD::SRA_FLAG;
    5625           7 :   Hi = DAG.getNode(Opc, dl, DAG.getVTList(MVT::i32, MVT::Glue), Hi);
    5626             : 
    5627             :   // The low part is an ARMISD::RRX operand, which shifts the carry in.
    5628           7 :   Lo = DAG.getNode(ARMISD::RRX, dl, MVT::i32, Lo, Hi.getValue(1));
    5629             : 
    5630             :   // Merge the pieces into a single i64 value.
    5631           7 :  return DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Lo, Hi);
    5632             : }
    5633             : 
    5634         126 : static SDValue LowerVSETCC(SDValue Op, SelectionDAG &DAG) {
    5635         126 :   SDValue TmpOp0, TmpOp1;
    5636             :   bool Invert = false;
    5637             :   bool Swap = false;
    5638             :   unsigned Opc = 0;
    5639             : 
    5640         126 :   SDValue Op0 = Op.getOperand(0);
    5641         126 :   SDValue Op1 = Op.getOperand(1);
    5642         126 :   SDValue CC = Op.getOperand(2);
    5643         126 :   EVT CmpVT = Op0.getValueType().changeVectorElementTypeToInteger();
    5644         126 :   EVT VT = Op.getValueType();
    5645         126 :   ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
    5646             :   SDLoc dl(Op);
    5647             : 
    5648         145 :   if (Op0.getValueType().getVectorElementType() == MVT::i64 &&
    5649          17 :       (SetCCOpcode == ISD::SETEQ || SetCCOpcode == ISD::SETNE)) {
    5650             :     // Special-case integer 64-bit equality comparisons. They aren't legal,
    5651             :     // but they can be lowered with a few vector instructions.
    5652           2 :     unsigned CmpElements = CmpVT.getVectorNumElements() * 2;
    5653           2 :     EVT SplitVT = EVT::getVectorVT(*DAG.getContext(), MVT::i32, CmpElements);
    5654           2 :     SDValue CastOp0 = DAG.getNode(ISD::BITCAST, dl, SplitVT, Op0);
    5655           2 :     SDValue CastOp1 = DAG.getNode(ISD::BITCAST, dl, SplitVT, Op1);
    5656             :     SDValue Cmp = DAG.getNode(ISD::SETCC, dl, SplitVT, CastOp0, CastOp1,
    5657           2 :                               DAG.getCondCode(ISD::SETEQ));
    5658           2 :     SDValue Reversed = DAG.getNode(ARMISD::VREV64, dl, SplitVT, Cmp);
    5659           2 :     SDValue Merged = DAG.getNode(ISD::AND, dl, SplitVT, Cmp, Reversed);
    5660           2 :     Merged = DAG.getNode(ISD::BITCAST, dl, CmpVT, Merged);
    5661           2 :     if (SetCCOpcode == ISD::SETNE)
    5662           1 :       Merged = DAG.getNOT(dl, Merged, CmpVT);
    5663           2 :     Merged = DAG.getSExtOrTrunc(Merged, dl, VT);
    5664           2 :     return Merged;
    5665             :   }
    5666             : 
    5667         248 :   if (CmpVT.getVectorElementType() == MVT::i64)
    5668             :     // 64-bit comparisons are not legal in general.
    5669          16 :     return SDValue();
    5670             : 
    5671         108 :   if (Op1.getValueType().isFloatingPoint()) {
    5672          24 :     switch (SetCCOpcode) {
    5673           0 :     default: llvm_unreachable("Illegal FP comparison");
    5674           1 :     case ISD::SETUNE:
    5675             :     case ISD::SETNE:  Invert = true; LLVM_FALLTHROUGH;
    5676             :     case ISD::SETOEQ:
    5677             :     case ISD::SETEQ:  Opc = ARMISD::VCEQ; break;
    5678           1 :     case ISD::SETOLT:
    5679             :     case ISD::SETLT: Swap = true; LLVM_FALLTHROUGH;
    5680             :     case ISD::SETOGT:
    5681             :     case ISD::SETGT:  Opc = ARMISD::VCGT; break;
    5682           2 :     case ISD::SETOLE:
    5683             :     case ISD::SETLE:  Swap = true; LLVM_FALLTHROUGH;
    5684             :     case ISD::SETOGE:
    5685             :     case ISD::SETGE: Opc = ARMISD::VCGE; break;
    5686           1 :     case ISD::SETUGE: Swap = true; LLVM_FALLTHROUGH;
    5687             :     case ISD::SETULE: Invert = true; Opc = ARMISD::VCGT; break;
    5688           1 :     case ISD::SETUGT: Swap = true; LLVM_FALLTHROUGH;
    5689             :     case ISD::SETULT: Invert = true; Opc = ARMISD::VCGE; break;
    5690           1 :     case ISD::SETUEQ: Invert = true; LLVM_FALLTHROUGH;
    5691           2 :     case ISD::SETONE:
    5692             :       // Expand this to (OLT | OGT).
    5693           2 :       TmpOp0 = Op0;
    5694           2 :       TmpOp1 = Op1;
    5695             :       Opc = ISD::OR;
    5696           2 :       Op0 = DAG.getNode(ARMISD::VCGT, dl, CmpVT, TmpOp1, TmpOp0);
    5697           2 :       Op1 = DAG.getNode(ARMISD::VCGT, dl, CmpVT, TmpOp0, TmpOp1);
    5698             :       break;
    5699           1 :     case ISD::SETUO:
    5700             :       Invert = true;
    5701             :       LLVM_FALLTHROUGH;
    5702           2 :     case ISD::SETO:
    5703             :       // Expand this to (OLT | OGE).
    5704           2 :       TmpOp0 = Op0;
    5705           2 :       TmpOp1 = Op1;
    5706             :       Opc = ISD::OR;
    5707           2 :       Op0 = DAG.getNode(ARMISD::VCGT, dl, CmpVT, TmpOp1, TmpOp0);
    5708           2 :       Op1 = DAG.getNode(ARMISD::VCGE, dl, CmpVT, TmpOp0, TmpOp1);
    5709             :       break;
    5710             :     }
    5711             :   } else {
    5712             :     // Integer comparisons.
    5713          84 :     switch (SetCCOpcode) {
    5714           0 :     default: llvm_unreachable("Illegal integer comparison");
    5715          14 :     case ISD::SETNE:  Invert = true; LLVM_FALLTHROUGH;
    5716             :     case ISD::SETEQ:  Opc = ARMISD::VCEQ; break;
    5717           3 :     case ISD::SETLT:  Swap = true; LLVM_FALLTHROUGH;
    5718             :     case ISD::SETGT:  Opc = ARMISD::VCGT; break;
    5719           3 :     case ISD::SETLE:  Swap = true; LLVM_FALLTHROUGH;
    5720             :     case ISD::SETGE:  Opc = ARMISD::VCGE; break;
    5721          11 :     case ISD::SETULT: Swap = true; LLVM_FALLTHROUGH;
    5722             :     case ISD::SETUGT: Opc = ARMISD::VCGTU; break;
    5723           1 :     case ISD::SETULE: Swap = true; LLVM_FALLTHROUGH;
    5724             :     case ISD::SETUGE: Opc = ARMISD::VCGEU; break;
    5725             :     }
    5726             : 
    5727             :     // Detect VTST (Vector Test Bits) = icmp ne (and (op0, op1), zero).
    5728          84 :     if (Opc == ARMISD::VCEQ) {
    5729             :       SDValue AndOp;
    5730          27 :       if (ISD::isBuildVectorAllZeros(Op1.getNode()))
    5731             :         AndOp = Op0;
    5732          20 :       else if (ISD::isBuildVectorAllZeros(Op0.getNode()))
    5733             :         AndOp = Op1;
    5734             : 
    5735             :       // Ignore bitconvert.
    5736          34 :       if (AndOp.getNode() && AndOp.getOpcode() == ISD::BITCAST)
    5737           4 :         AndOp = AndOp.getOperand(0);
    5738             : 
    5739          34 :       if (AndOp.getNode() && AndOp.getOpcode() == ISD::AND) {
    5740             :         Opc = ARMISD::VTST;
    5741           6 :         Op0 = DAG.getNode(ISD::BITCAST, dl, CmpVT, AndOp.getOperand(0));
    5742           6 :         Op1 = DAG.getNode(ISD::BITCAST, dl, CmpVT, AndOp.getOperand(1));
    5743           6 :         Invert = !Invert;
    5744             :       }
    5745             :     }
    5746             :   }
    5747             : 
    5748         108 :   if (Swap)
    5749             :     std::swap(Op0, Op1);
    5750             : 
    5751             :   // If one of the operands is a constant vector zero, attempt to fold the
    5752             :   // comparison to a specialized compare-against-zero form.
    5753         108 :   SDValue SingleOp;
    5754         108 :   if (ISD::isBuildVectorAllZeros(Op1.getNode()))
    5755           4 :     SingleOp = Op0;
    5756         104 :   else if (ISD::isBuildVectorAllZeros(Op0.getNode())) {
    5757           4 :     if (Opc == ARMISD::VCGE)
    5758             :       Opc = ARMISD::VCLEZ;
    5759           2 :     else if (Opc == ARMISD::VCGT)
    5760             :       Opc = ARMISD::VCLTZ;
    5761           4 :     SingleOp = Op1;
    5762             :   }
    5763             : 
    5764             :   SDValue Result;
    5765         108 :   if (SingleOp.getNode()) {
    5766           8 :     switch (Opc) {
    5767             :     case ARMISD::VCEQ:
    5768           1 :       Result = DAG.getNode(ARMISD::VCEQZ, dl, CmpVT, SingleOp); break;
    5769             :     case ARMISD::VCGE:
    5770           1 :       Result = DAG.getNode(ARMISD::VCGEZ, dl, CmpVT, SingleOp); break;
    5771             :     case ARMISD::VCLEZ:
    5772           2 :       Result = DAG.getNode(ARMISD::VCLEZ, dl, CmpVT, SingleOp); break;
    5773             :     case ARMISD::VCGT:
    5774           2 :       Result = DAG.getNode(ARMISD::VCGTZ, dl, CmpVT, SingleOp); break;
    5775             :     case ARMISD::VCLTZ:
    5776           2 :       Result = DAG.getNode(ARMISD::VCLTZ, dl, CmpVT, SingleOp); break;
    5777             :     default:
    5778           0 :       Result = DAG.getNode(Opc, dl, CmpVT, Op0, Op1);
    5779             :     }
    5780             :   } else {
    5781         100 :      Result = DAG.getNode(Opc, dl, CmpVT, Op0, Op1);
    5782             :   }
    5783             : 
    5784         108 :   Result = DAG.getSExtOrTrunc(Result, dl, VT);
    5785             : 
    5786         108 :   if (Invert)
    5787          15 :     Result = DAG.getNOT(dl, Result, VT);
    5788             : 
    5789         108 :   return Result;
    5790             : }
    5791             : 
    5792          87 : static SDValue LowerSETCCCARRY(SDValue Op, SelectionDAG &DAG) {
    5793          87 :   SDValue LHS = Op.getOperand(0);
    5794          87 :   SDValue RHS = Op.getOperand(1);
    5795          87 :   SDValue Carry = Op.getOperand(2);
    5796          87 :   SDValue Cond = Op.getOperand(3);
    5797             :   SDLoc DL(Op);
    5798             : 
    5799             :   assert(LHS.getSimpleValueType().isInteger() && "SETCCCARRY is integer only.");
    5800             : 
    5801             :   // ARMISD::SUBE expects a carry not a borrow like ISD::SUBCARRY so we
    5802             :   // have to invert the carry first.
    5803          87 :   Carry = DAG.getNode(ISD::SUB, DL, MVT::i32,
    5804         174 :                       DAG.getConstant(1, DL, MVT::i32), Carry);
    5805             :   // This converts the boolean value carry into the carry flag.
    5806          87 :   Carry = ConvertBooleanCarryToCarryFlag(Carry, DAG);
    5807             : 
    5808          87 :   SDVTList VTs = DAG.getVTList(LHS.getValueType(), MVT::i32);
    5809          87 :   SDValue Cmp = DAG.getNode(ARMISD::SUBE, DL, VTs, LHS, RHS, Carry);
    5810             : 
    5811          87 :   SDValue FVal = DAG.getConstant(0, DL, MVT::i32);
    5812          87 :   SDValue TVal = DAG.getConstant(1, DL, MVT::i32);
    5813             :   SDValue ARMcc = DAG.getConstant(
    5814          87 :       IntCCToARMCC(cast<CondCodeSDNode>(Cond)->get()), DL, MVT::i32);
    5815          87 :   SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
    5816             :   SDValue Chain = DAG.getCopyToReg(DAG.getEntryNode(), DL, ARM::CPSR,
    5817         174 :                                    Cmp.getValue(1), SDValue());
    5818             :   return DAG.getNode(ARMISD::CMOV, DL, Op.getValueType(), FVal, TVal, ARMcc,
    5819         261 :                      CCR, Chain.getValue(1));
    5820             : }
    5821             : 
    5822             : /// isNEONModifiedImm - Check if the specified splat value corresponds to a
    5823             : /// valid vector constant for a NEON instruction with a "modified immediate"
    5824             : /// operand (e.g., VMOV).  If so, return the encoded value.
    5825         983 : static SDValue isNEONModifiedImm(uint64_t SplatBits, uint64_t SplatUndef,
    5826             :                                  unsigned SplatBitSize, SelectionDAG &DAG,
    5827             :                                  const SDLoc &dl, EVT &VT, bool is128Bits,
    5828             :                                  NEONModImmType type) {
    5829             :   unsigned OpCmode, Imm;
    5830             : 
    5831             :   // SplatBitSize is set to the smallest size that splats the vector, so a
    5832             :   // zero vector will always have SplatBitSize == 8.  However, NEON modified
    5833             :   // immediate instructions others than VMOV do not support the 8-bit encoding
    5834             :   // of a zero vector, and the default encoding of zero is supposed to be the
    5835             :   // 32-bit version.
    5836         983 :   if (SplatBits == 0)
    5837             :     SplatBitSize = 32;
    5838             : 
    5839         901 :   switch (SplatBitSize) {
    5840          75 :   case 8:
    5841          75 :     if (type != VMOVModImm)
    5842           0 :       return SDValue();
    5843             :     // Any 1-byte value is OK.  Op=0, Cmode=1110.
    5844             :     assert((SplatBits & ~0xff) == 0 && "one byte splat value is too big");
    5845             :     OpCmode = 0xe;
    5846          75 :     Imm = SplatBits;
    5847          75 :     VT = is128Bits ? MVT::v16i8 : MVT::v8i8;
    5848          75 :     break;
    5849             : 
    5850          34 :   case 16:
    5851             :     // NEON's 16-bit VMOV supports splat values where only one byte is nonzero.
    5852          34 :     VT = is128Bits ? MVT::v8i16 : MVT::v4i16;
    5853          34 :     if ((SplatBits & ~0xff) == 0) {
    5854             :       // Value = 0x00nn: Op=x, Cmode=100x.
    5855             :       OpCmode = 0x8;
    5856          16 :       Imm = SplatBits;
    5857          16 :       break;
    5858             :     }
    5859          18 :     if ((SplatBits & ~0xff00) == 0) {
    5860             :       // Value = 0xnn00: Op=x, Cmode=101x.
    5861             :       OpCmode = 0xa;
    5862           6 :       Imm = SplatBits >> 8;
    5863           6 :       break;
    5864             :     }
    5865          12 :     return SDValue();
    5866             : 
    5867         826 :   case 32:
    5868             :     // NEON's 32-bit VMOV supports splat values where:
    5869             :     // * only one byte is nonzero, or
    5870             :     // * the least significant byte is 0xff and the second byte is nonzero, or
    5871             :     // * the least significant 2 bytes are 0xff and the third is nonzero.
    5872         826 :     VT = is128Bits ? MVT::v4i32 : MVT::v2i32;
    5873         826 :     if ((SplatBits & ~0xff) == 0) {
    5874             :       // Value = 0x000000nn: Op=x, Cmode=000x.
    5875             :       OpCmode = 0;
    5876         108 :       Imm = SplatBits;
    5877         108 :       break;
    5878             :     }
    5879         718 :     if ((SplatBits & ~0xff00) == 0) {
    5880             :       // Value = 0x0000nn00: Op=x, Cmode=001x.
    5881             :       OpCmode = 0x2;
    5882           6 :       Imm = SplatBits >> 8;
    5883           6 :       break;
    5884             :     }
    5885         712 :     if ((SplatBits & ~0xff0000) == 0) {
    5886             :       // Value = 0x00nn0000: Op=x, Cmode=010x.
    5887             :       OpCmode = 0x4;
    5888           5 :       Imm = SplatBits >> 16;
    5889           5 :       break;
    5890             :     }
    5891         707 :     if ((SplatBits & ~0xff000000) == 0) {
    5892             :       // Value = 0xnn000000: Op=x, Cmode=011x.
    5893             :       OpCmode = 0x6;
    5894          15 :       Imm = SplatBits >> 24;
    5895          15 :       break;
    5896             :     }
    5897             : 
    5898             :     // cmode == 0b1100 and cmode == 0b1101 are not supported for VORR or VBIC
    5899         692 :     if (type == OtherModImm) return SDValue();
    5900             : 
    5901         677 :     if ((SplatBits & ~0xffff) == 0 &&
    5902           5 :         ((SplatBits | SplatUndef) & 0xff) == 0xff) {
    5903             :       // Value = 0x0000nnff: Op=x, Cmode=1100.
    5904             :       OpCmode = 0xc;
    5905           3 :       Imm = SplatBits >> 8;
    5906           3 :       break;
    5907             :     }
    5908             : 
    5909         675 :     if ((SplatBits & ~0xffffff) == 0 &&
    5910           6 :         ((SplatBits | SplatUndef) & 0xffff) == 0xffff) {
    5911             :       // Value = 0x00nnffff: Op=x, Cmode=1101.
    5912             :       OpCmode = 0xd;
    5913           4 :       Imm = SplatBits >> 16;
    5914           4 :       break;
    5915             :     }
    5916             : 
    5917             :     // Note: there are a few 32-bit splat values (specifically: 00ffff00,
    5918             :     // ff000000, ff0000ff, and ffff00ff) that are valid for VMOV.I64 but not
    5919             :     // VMOV.I32.  A (very) minor optimization would be to replicate the value
    5920             :     // and fall through here to test for a valid 64-bit splat.  But, then the
    5921             :     // caller would also need to check and handle the change in size.
    5922         665 :     return SDValue();
    5923             : 
    5924          48 :   case 64: {
    5925          48 :     if (type != VMOVModImm)
    5926          23 :       return SDValue();
    5927             :     // NEON has a 64-bit VMOV splat where each byte is either 0 or 0xff.
    5928             :     uint64_t BitMask = 0xff;
    5929             :     uint64_t Val = 0;
    5930             :     unsigned ImmMask = 1;
    5931             :     Imm = 0;
    5932         131 :     for (int ByteNum = 0; ByteNum < 8; ++ByteNum) {
    5933          75 :       if (((SplatBits | SplatUndef) & BitMask) == BitMask) {
    5934             :         Val |= BitMask;
    5935          23 :         Imm |= ImmMask;
    5936          52 :       } else if ((SplatBits & BitMask) != 0) {
    5937          22 :         return SDValue();
    5938             :       }
    5939          53 :       BitMask <<= 8;
    5940          53 :       ImmMask <<= 1;
    5941             :     }
    5942             : 
    5943           6 :     if (DAG.getDataLayout().isBigEndian())
    5944             :       // swap higher and lower 32 bit word
    5945           0 :       Imm = ((Imm & 0xf) << 4) | ((Imm & 0xf0) >> 4);
    5946             : 
    5947             :     // Op=1, Cmode=1110.
    5948             :     OpCmode = 0x1e;
    5949           3 :     VT = is128Bits ? MVT::v2i64 : MVT::v1i64;
    5950           3 :     break;
    5951             :   }
    5952             : 
    5953           0 :   default:
    5954           0 :     llvm_unreachable("unexpected size for isNEONModifiedImm");
    5955             :   }
    5956             : 
    5957             :   unsigned EncodedVal = ARM_AM::createNEONModImm(OpCmode, Imm);
    5958         241 :   return DAG.getTargetConstant(EncodedVal, dl, MVT::i32);
    5959             : }
    5960             : 
    5961        1293 : SDValue ARMTargetLowering::LowerConstantFP(SDValue Op, SelectionDAG &DAG,
    5962             :                                            const ARMSubtarget *ST) const {
    5963        1293 :   EVT VT = Op.getValueType();
    5964             :   bool IsDouble = (VT == MVT::f64);
    5965             :   ConstantFPSDNode *CFP = cast<ConstantFPSDNode>(Op);
    5966        1293 :   const APFloat &FPVal = CFP->getValueAPF();
    5967             : 
    5968             :   // Prevent floating-point constants from using literal loads
    5969             :   // when execute-only is enabled.
    5970        1293 :   if (ST->genExecuteOnly()) {
    5971             :     // If we can represent the constant as an immediate, don't lower it
    5972         115 :     if (isFPImmLegal(FPVal, VT))
    5973          66 :       return Op;
    5974             :     // Otherwise, construct as integer, and move to float register
    5975          49 :     APInt INTVal = FPVal.bitcastToAPInt();
    5976             :     SDLoc DL(CFP);
    5977          49 :     switch (VT.getSimpleVT().SimpleTy) {
    5978           0 :       default:
    5979           0 :         llvm_unreachable("Unknown floating point type!");
    5980             :         break;
    5981             :       case MVT::f64: {
    5982          58 :         SDValue Lo = DAG.getConstant(INTVal.trunc(32), DL, MVT::i32);
    5983          87 :         SDValue Hi = DAG.getConstant(INTVal.lshr(32).trunc(32), DL, MVT::i32);
    5984          29 :         if (!ST->isLittle())
    5985             :           std::swap(Lo, Hi);
    5986          29 :         return DAG.getNode(ARMISD::VMOVDRR, DL, MVT::f64, Lo, Hi);
    5987             :       }
    5988             :       case MVT::f32:
    5989             :           return DAG.getNode(ARMISD::VMOVSR, DL, VT,
    5990          20 :               DAG.getConstant(INTVal, DL, MVT::i32));
    5991             :     }
    5992             :   }
    5993             : 
    5994        1178 :   if (!ST->hasVFP3())
    5995          28 :     return SDValue();
    5996             : 
    5997             :   // Use the default (constant pool) lowering for double constants when we have
    5998             :   // an SP-only FPU
    5999        1150 :   if (IsDouble && Subtarget->isFPOnlySP())
    6000           8 :     return SDValue();
    6001             : 
    6002             :   // Try splatting with a VMOV.f32...
    6003        1142 :   int ImmVal = IsDouble ? ARM_AM::getFP64Imm(FPVal) : ARM_AM::getFP32Imm(FPVal);
    6004             : 
    6005        1142 :   if (ImmVal != -1) {
    6006         429 :     if (IsDouble || !ST->useNEONForSinglePrecisionFP()) {
    6007             :       // We have code in place to select a valid ConstantFP already, no need to
    6008             :       // do any mangling.
    6009         396 :       return Op;
    6010             :     }
    6011             : 
    6012             :     // It's a float and we are trying to use NEON operations where
    6013             :     // possible. Lower it to a splat followed by an extract.
    6014             :     SDLoc DL(Op);
    6015          66 :     SDValue NewVal = DAG.getTargetConstant(ImmVal, DL, MVT::i32);
    6016             :     SDValue VecConstant = DAG.getNode(ARMISD::VMOVFPIMM, DL, MVT::v2f32,
    6017          33 :                                       NewVal);
    6018             :     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32, VecConstant,
    6019          66 :                        DAG.getConstant(0, DL, MVT::i32));
    6020             :   }
    6021             : 
    6022             :   // The rest of our options are NEON only, make sure that's allowed before
    6023             :   // proceeding..
    6024         713 :   if (!ST->hasNEON() || (!IsDouble && !ST->useNEONForSinglePrecisionFP()))
    6025         308 :     return SDValue();
    6026             : 
    6027         405 :   EVT VMovVT;
    6028         810 :   uint64_t iVal = FPVal.bitcastToAPInt().getZExtValue();
    6029             : 
    6030             :   // It wouldn't really be worth bothering for doubles except for one very
    6031             :   // important value, which does happen to match: 0.0. So make sure we don't do
    6032             :   // anything stupid.
    6033         405 :   if (IsDouble && (iVal & 0xffffffff) != (iVal >> 32))
    6034          81 :     return SDValue();
    6035             : 
    6036             :   // Try a VMOV.i32 (FIXME: i8, i16, or i64 could work too).
    6037         324 :   SDValue NewVal = isNEONModifiedImm(iVal & 0xffffffffU, 0, 32, DAG, SDLoc(Op),
    6038         324 :                                      VMovVT, false, VMOVModImm);
    6039             :   if (NewVal != SDValue()) {
    6040             :     SDLoc DL(Op);
    6041             :     SDValue VecConstant = DAG.getNode(ARMISD::VMOVIMM, DL, VMovVT,
    6042          19 :                                       NewVal);
    6043          19 :     if (IsDouble)
    6044          13 :       return DAG.getNode(ISD::BITCAST, DL, MVT::f64, VecConstant);
    6045             : 
    6046             :     // It's a float: cast and extract a vector element.
    6047             :     SDValue VecFConstant = DAG.getNode(ISD::BITCAST, DL, MVT::v2f32,
    6048           6 :                                        VecConstant);
    6049             :     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32, VecFConstant,
    6050          12 :                        DAG.getConstant(0, DL, MVT::i32));
    6051             :   }
    6052             : 
    6053             :   // Finally, try a VMVN.i32
    6054         915 :   NewVal = isNEONModifiedImm(~iVal & 0xffffffffU, 0, 32, DAG, SDLoc(Op), VMovVT,
    6055         305 :                              false, VMVNModImm);
    6056             :   if (NewVal != SDValue()) {
    6057             :     SDLoc DL(Op);
    6058           3 :     SDValue VecConstant = DAG.getNode(ARMISD::VMVNIMM, DL, VMovVT, NewVal);
    6059             : 
    6060           3 :     if (IsDouble)
    6061           2 :       return DAG.getNode(ISD::BITCAST, DL, MVT::f64, VecConstant);
    6062             : 
    6063             :     // It's a float: cast and extract a vector element.
    6064             :     SDValue VecFConstant = DAG.getNode(ISD::BITCAST, DL, MVT::v2f32,
    6065           1 :                                        VecConstant);
    6066             :     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32, VecFConstant,
    6067           2 :                        DAG.getConstant(0, DL, MVT::i32));
    6068             :   }
    6069             : 
    6070         302 :   return SDValue();
    6071             : }
    6072             : 
    6073             : // check if an VEXT instruction can handle the shuffle mask when the
    6074             : // vector sources of the shuffle are the same.
    6075          63 : static bool isSingletonVEXTMask(ArrayRef<int> M, EVT VT, unsigned &Imm) {
    6076          63 :   unsigned NumElts = VT.getVectorNumElements();
    6077             : 
    6078             :   // Assume that the first shuffle index is not UNDEF.  Fail if it is.
    6079          63 :   if (M[0] < 0)
    6080             :     return false;
    6081             : 
    6082          55 :   Imm = M[0];
    6083             : 
    6084             :   // If this is a VEXT shuffle, the immediate value is the index of the first
    6085             :   // element.  The other shuffle indices must be the successive elements after
    6086             :   // the first one.
    6087             :   unsigned ExpectedElt = Imm;
    6088         157 :   for (unsigned i = 1; i < NumElts; ++i) {
    6089             :     // Increment the expected index.  If it wraps around, just follow it
    6090             :     // back to index zero and keep going.
    6091         102 :     ++ExpectedElt;
    6092         102 :     if (ExpectedElt == NumElts)
    6093             :       ExpectedElt = 0;
    6094             : 
    6095         204 :     if (M[i] < 0) continue; // ignore UNDEF indices
    6096          94 :     if (ExpectedElt != static_cast<unsigned>(M[i]))
    6097             :       return false;
    6098             :   }
    6099             : 
    6100             :   return true;
    6101             : }
    6102             : 
    6103         261 : static bool isVEXTMask(ArrayRef<int> M, EVT VT,
    6104             :                        bool &ReverseVEXT, unsigned &Imm) {
    6105         261 :   unsigned NumElts = VT.getVectorNumElements();
    6106         261 :   ReverseVEXT = false;
    6107             : 
    6108             :   // Assume that the first shuffle index is not UNDEF.  Fail if it is.
    6109         261 :   if (M[0] < 0)
    6110             :     return false;
    6111             : 
    6112         242 :   Imm = M[0];
    6113             : 
    6114             :   // If this is a VEXT shuffle, the immediate value is the index of the first
    6115             :   // element.  The other shuffle indices must be the successive elements after
    6116             :   // the first one.
    6117             :   unsigned ExpectedElt = Imm;
    6118         756 :   for (unsigned i = 1; i < NumElts; ++i) {
    6119             :     // Increment the expected index.  If it wraps around, it may still be
    6120             :     // a VEXT but the source vectors must be swapped.
    6121         485 :     ExpectedElt += 1;
    6122         485 :     if (ExpectedElt == NumElts * 2) {
    6123             :       ExpectedElt = 0;
    6124           3 :       ReverseVEXT = true;
    6125             :     }
    6126             : 
    6127         970 :     if (M[i] < 0) continue; // ignore UNDEF indices
    6128         414 :     if (ExpectedElt != static_cast<unsigned>(M[i]))
    6129             :       return false;
    6130             :   }
    6131             : 
    6132             :   // Adjust the index value if the source operands will be swapped.
    6133          14 :   if (ReverseVEXT)
    6134           3 :     Imm -= NumElts;
    6135             : 
    6136             :   return true;
    6137             : }
    6138             : 
    6139             : /// isVREVMask - Check if a vector shuffle corresponds to a VREV
    6140             : /// instruction with the specified blocksize.  (The order of the elements
    6141             : /// within each block of the vector is reversed.)
    6142         732 : static bool isVREVMask(ArrayRef<int> M, EVT VT, unsigned BlockSize) {
    6143             :   assert((BlockSize==16 || BlockSize==32 || BlockSize==64) &&
    6144             :          "Only possible block sizes for VREV are: 16, 32, 64");
    6145             : 
    6146             :   unsigned EltSz = VT.getScalarSizeInBits();
    6147         732 :   if (EltSz == 64)
    6148             :     return false;
    6149             : 
    6150         732 :   unsigned NumElts = VT.getVectorNumElements();
    6151         732 :   unsigned BlockElts = M[0] + 1;
    6152             :   // If the first shuffle index is UNDEF, be optimistic.
    6153         732 :   if (M[0] < 0)
    6154          56 :     BlockElts = BlockSize / EltSz;
    6155             : 
    6156         732 :   if (BlockSize <= EltSz || BlockSize != BlockElts * EltSz)
    6157             :     return false;
    6158             : 
    6159         859 :   for (unsigned i = 0; i < NumElts; ++i) {
    6160         934 :     if (M[i] < 0) continue; // ignore UNDEF indices
    6161         317 :     if ((unsigned) M[i] != (i - i%BlockElts) + (BlockElts - 1 - i%BlockElts))
    6162             :       return false;
    6163             :   }
    6164             : 
    6165             :   return true;
    6166             : }
    6167             : 
    6168             : static bool isVTBLMask(ArrayRef<int> M, EVT VT) {
    6169             :   // We can handle <8 x i8> vector shuffles. If the index in the mask is out of
    6170             :   // range, then 0 is placed into the resulting vector. So pretty much any mask
    6171             :   // of 8 elements can work here.
    6172           8 :   return VT == MVT::v8i8 && M.size() == 8;
    6173             : }
    6174             : 
    6175             : static unsigned SelectPairHalf(unsigned Elements, ArrayRef<int> Mask,
    6176             :                                unsigned Index) {
    6177         851 :   if (Mask.size() == Elements * 2)
    6178         130 :     return Index / Elements;
    6179         721 :   return Mask[Index] == 0 ? 0 : 1;
    6180             : }
    6181             : 
    6182             : // Checks whether the shuffle mask represents a vector transpose (VTRN) by
    6183             : // checking that pairs of elements in the shuffle mask represent the same index
    6184             : // in each vector, incrementing the expected index by 2 at each step.
    6185             : // e.g. For v1,v2 of type v4i32 a valid shuffle mask is: [0, 4, 2, 6]
    6186             : //  v1={a,b,c,d} => x=shufflevector v1, v2 shufflemask => x={a,e,c,g}
    6187             : //  v2={e,f,g,h}
    6188             : // WhichResult gives the offset for each element in the mask based on which
    6189             : // of the two results it belongs to.
    6190             : //
    6191             : // The transpose can be represented either as:
    6192             : // result1 = shufflevector v1, v2, result1_shuffle_mask
    6193             : // result2 = shufflevector v1, v2, result2_shuffle_mask
    6194             : // where v1/v2 and the shuffle masks have the same number of elements
    6195             : // (here WhichResult (see below) indicates which result is being checked)
    6196             : //
    6197             : // or as:
    6198             : // results = shufflevector v1, v2, shuffle_mask
    6199             : // where both results are returned in one vector and the shuffle mask has twice
    6200             : // as many elements as v1/v2 (here WhichResult will always be 0 if true) here we
    6201             : // want to check the low half and high half of the shuffle mask as if it were
    6202             : // the other case
    6203         241 : static bool isVTRNMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
    6204             :   unsigned EltSz = VT.getScalarSizeInBits();
    6205         241 :   if (EltSz == 64)
    6206             :     return false;
    6207             : 
    6208         241 :   unsigned NumElts = VT.getVectorNumElements();
    6209         241 :   if (M.size() != NumElts && M.size() != NumElts*2)
    6210             :     return false;
    6211             : 
    6212             :   // If the mask is twice as long as the input vector then we need to check the
    6213             :   // upper and lower parts of the mask with a matching value for WhichResult
    6214             :   // FIXME: A mask with only even values will be rejected in case the first
    6215             :   // element is undefined, e.g. [-1, 4, 2, 6] will be rejected, because only
    6216             :   // M[0] is used to determine WhichResult
    6217         363 :   for (unsigned i = 0; i < M.size(); i += NumElts) {
    6218         251 :     WhichResult = SelectPairHalf(NumElts, M, i);
    6219         681 :     for (unsigned j = 0; j < NumElts; j += 2) {
    6220        1144 :       if ((M[i+j] >= 0 && (unsigned) M[i+j] != j + WhichResult) ||
    6221         948 :           (M[i+j+1] >= 0 && (unsigned) M[i+j+1] != j + NumElts + WhichResult))
    6222             :         return false;
    6223             :     }
    6224             :   }
    6225             : 
    6226          51 :   if (M.size() == NumElts*2)
    6227           6 :     WhichResult = 0;
    6228             : 
    6229             :   return true;
    6230             : }
    6231             : 
    6232             : /// isVTRN_v_undef_Mask - Special case of isVTRNMask for canonical form of
    6233             : /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef".
    6234             : /// Mask is e.g., <0, 0, 2, 2> instead of <0, 4, 2, 6>.
    6235          90 : static bool isVTRN_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult){
    6236             :   unsigned EltSz = VT.getScalarSizeInBits();
    6237          90 :   if (EltSz == 64)
    6238             :     return false;
    6239             : 
    6240          90 :   unsigned NumElts = VT.getVectorNumElements();
    6241          90 :   if (M.size() != NumElts && M.size() != NumElts*2)
    6242             :     return false;
    6243             : 
    6244         110 :   for (unsigned i = 0; i < M.size(); i += NumElts) {
    6245          96 :     WhichResult = SelectPairHalf(NumElts, M, i);
    6246         206 :     for (unsigned j = 0; j < NumElts; j += 2) {
    6247         377 :       if ((M[i+j] >= 0 && (unsigned) M[i+j] != j + WhichResult) ||
    6248         255 :           (M[i+j+1] >= 0 && (unsigned) M[i+j+1] != j + WhichResult))
    6249             :         return false;
    6250             :     }
    6251             :   }
    6252             : 
    6253           4 :   if (M.size() == NumElts*2)
    6254           0 :     WhichResult = 0;
    6255             : 
    6256             :   return true;
    6257             : }
    6258             : 
    6259             : // Checks whether the shuffle mask represents a vector unzip (VUZP) by checking
    6260             : // that the mask elements are either all even and in steps of size 2 or all odd
    6261             : // and in steps of size 2.
    6262             : // e.g. For v1,v2 of type v4i32 a valid shuffle mask is: [0, 2, 4, 6]
    6263             : //  v1={a,b,c,d} => x=shufflevector v1, v2 shufflemask => x={a,c,e,g}
    6264             : //  v2={e,f,g,h}
    6265             : // Requires similar checks to that of isVTRNMask with
    6266             : // respect the how results are returned.
    6267         190 : static bool isVUZPMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
    6268             :   unsigned EltSz = VT.getScalarSizeInBits();
    6269         190 :   if (EltSz == 64)
    6270             :     return false;
    6271             : 
    6272         190 :   unsigned NumElts = VT.getVectorNumElements();
    6273         190 :   if (M.size() != NumElts && M.size() != NumElts*2)
    6274             :     return false;
    6275             : 
    6276         340 :   for (unsigned i = 0; i < M.size(); i += NumElts) {
    6277         196 :     WhichResult = SelectPairHalf(NumElts, M, i);
    6278        1512 :     for (unsigned j = 0; j < NumElts; ++j) {
    6279        1558 :       if (M[i+j] >= 0 && (unsigned) M[i+j] != 2 * j + WhichResult)
    6280             :         return false;
    6281             :     }
    6282             :   }
    6283             : 
    6284          69 :   if (M.size() == NumElts*2)
    6285           3 :     WhichResult = 0;
    6286             : 
    6287             :   // VUZP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32.
    6288          69 :   if (VT.is64BitVector() && EltSz == 32)
    6289             :     return false;
    6290             : 
    6291             :   return true;
    6292             : }
    6293             : 
    6294             : /// isVUZP_v_undef_Mask - Special case of isVUZPMask for canonical form of
    6295             : /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef".
    6296             : /// Mask is e.g., <0, 2, 0, 2> instead of <0, 2, 4, 6>,
    6297          86 : static bool isVUZP_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult){
    6298             :   unsigned EltSz = VT.getScalarSizeInBits();
    6299          86 :   if (EltSz == 64)
    6300             :     return false;
    6301             : 
    6302          86 :   unsigned NumElts = VT.getVectorNumElements();
    6303          86 :   if (M.size() != NumElts && M.size() != NumElts*2)
    6304             :     return false;
    6305             : 
    6306          86 :   unsigned Half = NumElts / 2;
    6307         104 :   for (unsigned i = 0; i < M.size(); i += NumElts) {
    6308          92 :     WhichResult = SelectPairHalf(NumElts, M, i);
    6309         170 :     for (unsigned j = 0; j < NumElts; j += Half) {
    6310             :       unsigned Idx = WhichResult;
    6311         434 :       for (unsigned k = 0; k < Half; ++k) {
    6312         478 :         int MIdx = M[i + j + k];
    6313         239 :         if (MIdx >= 0 && (unsigned) MIdx != Idx)
    6314             :           return false;
    6315         156 :         Idx += 2;
    6316             :       }
    6317             :     }
    6318             :   }
    6319             : 
    6320           3 :   if (M.size() == NumElts*2)
    6321           0 :     WhichResult = 0;
    6322             : 
    6323             :   // VUZP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32.
    6324           3 :   if (VT.is64BitVector() && EltSz == 32)
    6325             :     return false;
    6326             : 
    6327             :   return true;
    6328             : }
    6329             : 
    6330             : // Checks whether the shuffle mask represents a vector zip (VZIP) by checking
    6331             : // that pairs of elements of the shufflemask represent the same index in each
    6332             : // vector incrementing sequentially through the vectors.
    6333             : // e.g. For v1,v2 of type v4i32 a valid shuffle mask is: [0, 4, 1, 5]
    6334             : //  v1={a,b,c,d} => x=shufflevector v1, v2 shufflemask => x={a,e,b,f}
    6335             : //  v2={e,f,g,h}
    6336             : // Requires similar checks to that of isVTRNMask with respect the how results
    6337             : // are returned.
    6338         121 : static bool isVZIPMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
    6339             :   unsigned EltSz = VT.getScalarSizeInBits();
    6340         121 :   if (EltSz == 64)
    6341             :     return false;
    6342             : 
    6343         121 :   unsigned NumElts = VT.getVectorNumElements();
    6344         121 :   if (M.size() != NumElts && M.size() != NumElts*2)
    6345             :     return false;
    6346             : 
    6347         195 :   for (unsigned i = 0; i < M.size(); i += NumElts) {
    6348         127 :     WhichResult = SelectPairHalf(NumElts, M, i);
    6349         127 :     unsigned Idx = WhichResult * NumElts / 2;
    6350         477 :     for (unsigned j = 0; j < NumElts; j += 2) {
    6351         749 :       if ((M[i+j] >= 0 && (unsigned) M[i+j] != Idx) ||
    6352         613 :           (M[i+j+1] >= 0 && (unsigned) M[i+j+1] != Idx + NumElts))
    6353             :         return false;
    6354         175 :       Idx += 1;
    6355             :     }
    6356             :   }
    6357             : 
    6358          31 :   if (M.size() == NumElts*2)
    6359           4 :     WhichResult = 0;
    6360             : 
    6361             :   // VZIP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32.
    6362          31 :   if (VT.is64BitVector() && EltSz == 32)
    6363             :     return false;
    6364             : 
    6365             :   return true;
    6366             : }
    6367             : 
    6368             : /// isVZIP_v_undef_Mask - Special case of isVZIPMask for canonical form of
    6369             : /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef".
    6370             : /// Mask is e.g., <0, 0, 1, 1> instead of <0, 4, 1, 5>.
    6371          83 : static bool isVZIP_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult){
    6372             :   unsigned EltSz = VT.getScalarSizeInBits();
    6373          83 :   if (EltSz == 64)
    6374             :     return false;
    6375             : 
    6376          83 :   unsigned NumElts = VT.getVectorNumElements();
    6377          83 :   if (M.size() != NumElts && M.size() != NumElts*2)
    6378             :     return false;
    6379             : 
    6380          97 :   for (unsigned i = 0; i < M.size(); i += NumElts) {
    6381          89 :     WhichResult = SelectPairHalf(NumElts, M, i);
    6382          89 :     unsigned Idx = WhichResult * NumElts / 2;
    6383         165 :     for (unsigned j = 0; j < NumElts; j += 2) {
    6384         316 :       if ((M[i+j] >= 0 && (unsigned) M[i+j] != Idx) ||
    6385         200 :           (M[i+j+1] >= 0 && (unsigned) M[i+j+1] != Idx))
    6386             :         return false;
    6387          38 :       Idx += 1;
    6388             :     }
    6389             :   }
    6390             : 
    6391           1 :   if (M.size() == NumElts*2)
    6392           0 :     WhichResult = 0;
    6393             : 
    6394             :   // VZIP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32.
    6395           1 :   if (VT.is64BitVector() && EltSz == 32)
    6396             :     return false;
    6397             : 
    6398             :   return true;
    6399             : }
    6400             : 
    6401             : /// Check if \p ShuffleMask is a NEON two-result shuffle (VZIP, VUZP, VTRN),
    6402             : /// and return the corresponding ARMISD opcode if it is, or 0 if it isn't.
    6403         241 : static unsigned isNEONTwoResultShuffleMask(ArrayRef<int> ShuffleMask, EVT VT,
    6404             :                                            unsigned &WhichResult,
    6405             :                                            bool &isV_UNDEF) {
    6406         241 :   isV_UNDEF = false;
    6407         241 :   if (isVTRNMask(ShuffleMask, VT, WhichResult))
    6408             :     return ARMISD::VTRN;
    6409         190 :   if (isVUZPMask(ShuffleMask, VT, WhichResult))
    6410             :     return ARMISD::VUZP;
    6411         121 :   if (isVZIPMask(ShuffleMask, VT, WhichResult))
    6412             :     return ARMISD::VZIP;
    6413             : 
    6414          90 :   isV_UNDEF = true;
    6415          90 :   if (isVTRN_v_undef_Mask(ShuffleMask, VT, WhichResult))
    6416             :     return ARMISD::VTRN;
    6417          86 :   if (isVUZP_v_undef_Mask(ShuffleMask, VT, WhichResult))
    6418             :     return ARMISD::VUZP;
    6419          83 :   if (isVZIP_v_undef_Mask(ShuffleMask, VT, WhichResult))
    6420             :     return ARMISD::VZIP;
    6421             : 
    6422          82 :   return 0;
    6423             : }
    6424             : 
    6425             : /// \return true if this is a reverse operation on an vector.
    6426          35 : static bool isReverseMask(ArrayRef<int> M, EVT VT) {
    6427          35 :   unsigned NumElts = VT.getVectorNumElements();
    6428             :   // Make sure the mask has the right size.
    6429          35 :   if (NumElts != M.size())
    6430             :       return false;
    6431             : 
    6432             :   // Look for <15, ..., 3, -1, 1, 0>.
    6433         127 :   for (unsigned i = 0; i != NumElts; ++i)
    6434         158 :     if (M[i] >= 0 && M[i] != (int) (NumElts - 1 - i))
    6435             :       return false;
    6436             : 
    6437             :   return true;
    6438             : }
    6439             : 
    6440             : // If N is an integer constant that can be moved into a register in one
    6441             : // instruction, return an SDValue of such a constant (will become a MOV
    6442             : // instruction).  Otherwise return null.
    6443          19 : static SDValue IsSingleInstrConstant(SDValue N, SelectionDAG &DAG,
    6444             :                                      const ARMSubtarget *ST, const SDLoc &dl) {
    6445             :   uint64_t Val;
    6446             :   if (!isa<ConstantSDNode>(N))
    6447           7 :     return SDValue();
    6448          12 :   Val = cast<ConstantSDNode>(N)->getZExtValue();
    6449             : 
    6450          12 :   if (ST->isThumb1Only()) {
    6451           0 :     if (Val <= 255 || ~Val <= 255)
    6452           0 :       return DAG.getConstant(Val, dl, MVT::i32);
    6453             :   } else {
    6454          24 :     if (ARM_AM::getSOImmVal(Val) != -1 || ARM_AM::getSOImmVal(~Val) != -1)
    6455           0 :       return DAG.getConstant(Val, dl, MVT::i32);
    6456             :   }
    6457          12 :   return SDValue();
    6458             : }
    6459             : 
    6460             : // If this is a case we can't handle, return null and let the default
    6461             : // expansion code take care of it.
    6462        1134 : SDValue ARMTargetLowering::LowerBUILD_VECTOR(SDValue Op, SelectionDAG &DAG,
    6463             :                                              const ARMSubtarget *ST) const {
    6464             :   BuildVectorSDNode *BVN = cast<BuildVectorSDNode>(Op.getNode());
    6465             :   SDLoc dl(Op);
    6466        1134 :   EVT VT = Op.getValueType();
    6467             : 
    6468             :   APInt SplatBits, SplatUndef;
    6469             :   unsigned SplatBitSize;
    6470             :   bool HasAnyUndefs;
    6471        1134 :   if (BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs)) {
    6472         435 :     if (SplatUndef.isAllOnesValue())
    6473           9 :       return DAG.getUNDEF(VT);
    6474             : 
    6475         426 :     if (SplatBitSize <= 64) {
    6476             :       // Check if an immediate VMOV works.
    6477         257 :       EVT VmovVT;
    6478             :       SDValue Val = isNEONModifiedImm(SplatBits.getZExtValue(),
    6479             :                                       SplatUndef.getZExtValue(), SplatBitSize,
    6480         257 :                                       DAG, dl, VmovVT, VT.is128BitVector(),
    6481         514 :                                       VMOVModImm);
    6482         257 :       if (Val.getNode()) {
    6483         196 :         SDValue Vmov = DAG.getNode(ARMISD::VMOVIMM, dl, VmovVT, Val);
    6484         196 :         return DAG.getNode(ISD::BITCAST, dl, VT, Vmov);
    6485             :       }
    6486             : 
    6487             :       // Try an immediate VMVN.
    6488          61 :       uint64_t NegatedImm = (~SplatBits).getZExtValue();
    6489          61 :       Val = isNEONModifiedImm(NegatedImm,
    6490             :                                       SplatUndef.getZExtValue(), SplatBitSize,
    6491          61 :                                       DAG, dl, VmovVT, VT.is128BitVector(),
    6492          61 :                                       VMVNModImm);
    6493          61 :       if (Val.getNode()) {
    6494          10 :         SDValue Vmov = DAG.getNode(ARMISD::VMVNIMM, dl, VmovVT, Val);
    6495          10 :         return DAG.getNode(ISD::BITCAST, dl, VT, Vmov);
    6496             :       }
    6497             : 
    6498             :       // Use vmov.f32 to materialize other v2f32 and v4f32 splats.
    6499          17 :       if ((VT == MVT::v2f32 || VT == MVT::v4f32) && SplatBitSize == 32) {
    6500          17 :         int ImmVal = ARM_AM::getFP32Imm(SplatBits);
    6501          17 :         if (ImmVal != -1) {
    6502          10 :           SDValue Val = DAG.getTargetConstant(ImmVal, dl, MVT::i32);
    6503           5 :           return DAG.getNode(ARMISD::VMOVFPIMM, dl, VT, Val);
    6504             :         }
    6505             :       }
    6506             :     }
    6507             :   }
    6508             : 
    6509             :   // Scan through the operands to see if only one value is used.
    6510             :   //
    6511             :   // As an optimisation, even if more than one value is used it may be more
    6512             :   // profitable to splat with one value then change some lanes.
    6513             :   //
    6514             :   // Heuristically we decide to do this if the vector has a "dominant" value,
    6515             :   // defined as splatted to more than half of the lanes.
    6516         914 :   unsigned NumElts = VT.getVectorNumElements();
    6517             :   bool isOnlyLowElement = true;
    6518             :   bool usesOnlyOneValue = true;
    6519             :   bool hasDominantValue = false;
    6520             :   bool isConstant = true;
    6521             : 
    6522             :   // Map of the number of times a particular SDValue appears in the
    6523             :   // element list.
    6524             :   DenseMap<SDValue, unsigned> ValueCounts;
    6525             :   SDValue Value;
    6526        6798 :   for (unsigned i = 0; i < NumElts; ++i) {
    6527        2942 :     SDValue V = Op.getOperand(i);
    6528        5884 :     if (V.isUndef())
    6529         231 :       continue;
    6530        2711 :     if (i > 0)
    6531             :       isOnlyLowElement = false;
    6532             :     if (!isa<ConstantFPSDNode>(V) && !isa<ConstantSDNode>(V))
    6533             :       isConstant = false;
    6534             : 
    6535        2711 :     ValueCounts.insert(std::make_pair(V, 0));
    6536             :     unsigned &Count = ValueCounts[V];
    6537             : 
    6538             :     // Is this value dominant? (takes up more than half of the lanes)
    6539        2711 :     if (++Count > (NumElts / 2)) {
    6540             :       hasDominantValue = true;
    6541         251 :       Value = V;
    6542             :     }
    6543             :   }
    6544         914 :   if (ValueCounts.size() != 1)
    6545             :     usesOnlyOneValue = false;
    6546         914 :   if (!Value.getNode() && !ValueCounts.empty())
    6547         794 :     Value = ValueCounts.begin()->first;
    6548             : 
    6549         914 :   if (ValueCounts.empty())
    6550           0 :     return DAG.getUNDEF(VT);
    6551             : 
    6552             :   // Loads are better lowered with insert_vector_elt/ARMISD::BUILD_VECTOR.
    6553             :   // Keep going if we are hitting this case.
    6554         914 :   if (isOnlyLowElement && !ISD::isNormalLoad(Value.getNode()))
    6555          15 :     return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Value);
    6556             : 
    6557             :   unsigned EltSize = VT.getScalarSizeInBits();
    6558             : 
    6559             :   // Use VDUP for non-constant splats.  For f32 constant splats, reduce to
    6560             :   // i32 and try again.
    6561         899 :   if (hasDominantValue && EltSize <= 32) {
    6562         119 :     if (!isConstant) {
    6563          96 :       SDValue N;
    6564             : 
    6565             :       // If we are VDUPing a value that comes directly from a vector, that will
    6566             :       // cause an unnecessary move to and from a GPR, where instead we could
    6567             :       // just use VDUPLANE. We can only do this if the lane being extracted
    6568             :       // is at a constant index, as the VDUP from lane instructions only have
    6569             :       // constant-index forms.
    6570             :       ConstantSDNode *constIndex;
    6571          96 :       if (Value->getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
    6572           2 :           (constIndex = dyn_cast<ConstantSDNode>(Value->getOperand(1)))) {
    6573             :         // We need to create a new undef vector to use for the VDUPLANE if the
    6574             :         // size of the vector from which we get the value is different than the
    6575             :         // size of the vector that we need to create. We will insert the element
    6576             :         // such that the register coalescer will remove unnecessary copies.
    6577           2 :         if (VT != Value->getOperand(0).getValueType()) {
    6578           0 :           unsigned index = constIndex->getAPIntValue().getLimitedValue() %
    6579           0 :                              VT.getVectorNumElements();
    6580           0 :           N =  DAG.getNode(ARMISD::VDUPLANE, dl, VT,
    6581             :                  DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, DAG.getUNDEF(VT),
    6582             :                         Value, DAG.getConstant(index, dl, MVT::i32)),
    6583           0 :                            DAG.getConstant(index, dl, MVT::i32));
    6584             :         } else
    6585           1 :           N = DAG.getNode(ARMISD::VDUPLANE, dl, VT,
    6586           1 :                         Value->getOperand(0), Value->getOperand(1));
    6587             :       } else
    6588          95 :         N = DAG.getNode(ARMISD::VDUP, dl, VT, Value);
    6589             : 
    6590          96 :       if (!usesOnlyOneValue) {
    6591             :         // The dominant value was splatted as 'N', but we now have to insert
    6592             :         // all differing elements.
    6593          27 :         for (unsigned I = 0; I < NumElts; ++I) {
    6594           9 :           if (Op.getOperand(I) == Value)
    6595           9 :             continue;
    6596             :           SmallVector<SDValue, 3> Ops;
    6597           3 :           Ops.push_back(N);
    6598           3 :           Ops.push_back(Op.getOperand(I));
    6599           3 :           Ops.push_back(DAG.getConstant(I, dl, MVT::i32));
    6600           3 :           N = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Ops);
    6601             :         }
    6602             :       }
    6603          96 :       return N;
    6604             :     }
    6605          23 :     if (VT.getVectorElementType().isFloatingPoint()) {
    6606             :       SmallVector<SDValue, 8> Ops;
    6607          77 :       for (unsigned i = 0; i < NumElts; ++i)
    6608          34 :         Ops.push_back(DAG.getNode(ISD::BITCAST, dl, MVT::i32,
    6609          34 :                                   Op.getOperand(i)));
    6610           9 :       EVT VecVT = EVT::getVectorVT(*DAG.getContext(), MVT::i32, NumElts);
    6611           9 :       SDValue Val = DAG.getBuildVector(VecVT, dl, Ops);
    6612           9 :       Val = LowerBUILD_VECTOR(Val, DAG, ST);
    6613           9 :       if (Val.getNode())
    6614           0 :         return DAG.getNode(ISD::BITCAST, dl, VT, Val);
    6615             :     }
    6616          23 :     if (usesOnlyOneValue) {
    6617          19 :       SDValue Val = IsSingleInstrConstant(Value, DAG, ST, dl);
    6618          19 :       if (isConstant && Val.getNode())
    6619           0 :         return DAG.getNode(ARMISD::VDUP, dl, VT, Val);
    6620             :     }
    6621             :   }
    6622             : 
    6623             :   // If all elements are constants and the case above didn't get hit, fall back
    6624             :   // to the default expansion, which will generate a load from the constant
    6625             :   // pool.
    6626         803 :   if (isConstant)
    6627         213 :     return SDValue();
    6628             : 
    6629             :   // Empirical tests suggest this is rarely worth it for vectors of length <= 2.
    6630         590 :   if (NumElts >= 4) {
    6631         156 :     SDValue shuffle = ReconstructShuffle(Op, DAG);
    6632             :     if (shuffle != SDValue())
    6633          20 :       return shuffle;
    6634             :   }
    6635             : 
    6636         570 :   if (VT.is128BitVector() && VT != MVT::v2f64 && VT != MVT::v4f32) {
    6637             :     // If we haven't found an efficient lowering, try splitting a 128-bit vector
    6638             :     // into two 64-bit vectors; we might discover a better way to lower it.
    6639          77 :     SmallVector<SDValue, 64> Ops(Op->op_begin(), Op->op_begin() + NumElts);
    6640          77 :     EVT ExtVT = VT.getVectorElementType();
    6641          77 :     EVT HVT = EVT::getVectorVT(*DAG.getContext(), ExtVT, NumElts / 2);
    6642             :     SDValue Lower =
    6643         154 :         DAG.getBuildVector(HVT, dl, makeArrayRef(&Ops[0], NumElts / 2));
    6644          77 :     if (Lower.getOpcode() == ISD::BUILD_VECTOR)
    6645          77 :       Lower = LowerBUILD_VECTOR(Lower, DAG, ST);
    6646             :     SDValue Upper = DAG.getBuildVector(
    6647          77 :         HVT, dl, makeArrayRef(&Ops[NumElts / 2], NumElts / 2));
    6648          77 :     if (Upper.getOpcode() == ISD::BUILD_VECTOR)
    6649          77 :       Upper = LowerBUILD_VECTOR(Upper, DAG, ST);
    6650          77 :     if (Lower && Upper)
    6651          76 :       return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, Lower, Upper);
    6652             :   }
    6653             : 
    6654             :   // Vectors with 32- or 64-bit elements can be built by directly assigning
    6655             :   // the subregisters.  Lower it to an ARMISD::BUILD_VECTOR so the operands
    6656             :   // will be legalized.
    6657         494 :   if (EltSize >= 32) {
    6658             :     // Do the expansion with floating-point types, since that is what the VFP
    6659             :     // registers are defined to use, and since i64 is not legal.
    6660         487 :     EVT EltVT = EVT::getFloatingPointVT(EltSize);
    6661         487 :     EVT VecVT = EVT::getVectorVT(*DAG.getContext(), EltVT, NumElts);
    6662             :     SmallVector<SDValue, 8> Ops;
    6663        2647 :     for (unsigned i = 0; i < NumElts; ++i)
    6664        1080 :       Ops.push_back(DAG.getNode(ISD::BITCAST, dl, EltVT, Op.getOperand(i)));
    6665         487 :     SDValue Val = DAG.getNode(ARMISD::BUILD_VECTOR, dl, VecVT, Ops);
    6666         487 :     return DAG.getNode(ISD::BITCAST, dl, VT, Val);
    6667             :   }
    6668             : 
    6669             :   // If all else fails, just use a sequence of INSERT_VECTOR_ELT when we
    6670             :   // know the default expansion would otherwise fall back on something even
    6671             :   // worse. For a vector with one or two non-undef values, that's
    6672             :   // scalar_to_vector for the elements followed by a shuffle (provided the
    6673             :   // shuffle is valid for the target) and materialization element by element
    6674             :   // on the stack followed by a load for everything else.
    6675           7 :   if (!isConstant && !usesOnlyOneValue) {
    6676           4 :     SDValue Vec = DAG.getUNDEF(VT);
    6677          44 :     for (unsigned i = 0 ; i < NumElts; ++i) {
    6678          20 :       SDValue V = Op.getOperand(i);
    6679          20 :       if (V.isUndef())
    6680           8 :         continue;
    6681          12 :       SDValue LaneIdx = DAG.getConstant(i, dl, MVT::i32);
    6682          12 :       Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Vec, V, LaneIdx);
    6683             :     }
    6684           4 :     return Vec;
    6685             :   }
    6686             : 
    6687           3 :   return SDValue();
    6688             : }
    6689             : 
    6690             : // Gather data to see if the operation can be modelled as a
    6691             : // shuffle in combination with VEXTs.
    6692         156 : SDValue ARMTargetLowering::ReconstructShuffle(SDValue Op,
    6693             :                                               SelectionDAG &DAG) const {
    6694             :   assert(Op.getOpcode() == ISD::BUILD_VECTOR && "Unknown opcode!");
    6695             :   SDLoc dl(Op);
    6696         156 :   EVT VT = Op.getValueType();
    6697         156 :   unsigned NumElts = VT.getVectorNumElements();
    6698             : 
    6699             :   struct ShuffleSourceInfo {
    6700             :     SDValue Vec;
    6701             :     unsigned MinElt = std::numeric_limits<unsigned>::max();
    6702             :     unsigned MaxElt = 0;
    6703             : 
    6704             :     // We may insert some combination of BITCASTs and VEXT nodes to force Vec to
    6705             :     // be compatible with the shuffle we intend to construct. As a result
    6706             :     // ShuffleVec will be some sliding window into the original Vec.
    6707             :     SDValue ShuffleVec;
    6708             : 
    6709             :     // Code should guarantee that element i in Vec starts at element "WindowBase
    6710             :     // + i * WindowScale in ShuffleVec".
    6711             :     int WindowBase = 0;
    6712             :     int WindowScale = 1;
    6713             : 
    6714          56 :     ShuffleSourceInfo(SDValue Vec) : Vec(Vec), ShuffleVec(Vec) {}
    6715             : 
    6716             :     bool operator ==(SDValue OtherVec) { return Vec == OtherVec; }
    6717             :   };
    6718             : 
    6719             :   // First gather all vectors used as an immediate source for this BUILD_VECTOR
    6720             :   // node.
    6721             :   SmallVector<ShuffleSourceInfo, 2> Sources;
    6722         654 :   for (unsigned i = 0; i < NumElts; ++i) {
    6723         374 :     SDValue V = Op.getOperand(i);
    6724         374 :     if (V.isUndef())
    6725          97 :       continue;
    6726         277 :     else if (V.getOpcode() != ISD::EXTRACT_VECTOR_ELT) {
    6727             :       // A shuffle can only come from building a vector from various
    6728             :       // elements of other vectors.
    6729         124 :       return SDValue();
    6730             :     } else if (!isa<ConstantSDNode>(V.getOperand(1))) {
    6731             :       // Furthermore, shuffles require a constant mask, whereas extractelts
    6732             :       // accept variable indices.
    6733           1 :       return SDValue();
    6734             :     }
    6735             : 
    6736             :     // Add this element source to the list if it's not already there.
    6737         152 :     SDValue SourceVec = V.getOperand(0);
    6738             :     auto Source = llvm::find(Sources, SourceVec);
    6739         152 :     if (Source == Sources.end())
    6740          56 :       Source = Sources.insert(Sources.end(), ShuffleSourceInfo(SourceVec));
    6741             : 
    6742             :     // Update the minimum and maximum lane number seen.
    6743         304 :     unsigned EltNo = cast<ConstantSDNode>(V.getOperand(1))->getZExtValue();
    6744         304 :     Source->MinElt = std::min(Source->MinElt, EltNo);
    6745         304 :     Source->MaxElt = std::max(Source->MaxElt, EltNo);
    6746             :   }
    6747             : 
    6748             :   // Currently only do something sane when at most two source vectors
    6749             :   // are involved.
    6750          31 :   if (Sources.size() > 2)
    6751           0 :     return SDValue();
    6752             : 
    6753             :   // Find out the smallest element size among result and two sources, and use
    6754             :   // it as element size to build the shuffle_vector.
    6755          31 :   EVT SmallestEltTy = VT.getVectorElementType();
    6756         137 :   for (auto &Source : Sources) {
    6757         106 :     EVT SrcEltTy = Source.Vec.getValueType().getVectorElementType();
    6758          53 :     if (SrcEltTy.bitsLT(SmallestEltTy))
    6759           4 :       SmallestEltTy = SrcEltTy;
    6760             :   }
    6761             :   unsigned ResMultiplier =
    6762          31 :       VT.getScalarSizeInBits() / SmallestEltTy.getSizeInBits();
    6763          31 :   NumElts = VT.getSizeInBits() / SmallestEltTy.getSizeInBits();
    6764          31 :   EVT ShuffleVT = EVT::getVectorVT(*DAG.getContext(), SmallestEltTy, NumElts);
    6765             : 
    6766             :   // If the source vector is too wide or too narrow, we may nevertheless be able
    6767             :   // to construct a compatible shuffle either by concatenating it with UNDEF or
    6768             :   // extracting a suitable range of elements.
    6769         127 :   for (auto &Src : Sources) {
    6770         102 :     EVT SrcVT = Src.ShuffleVec.getValueType();
    6771             : 
    6772          51 :     if (SrcVT.getSizeInBits() == VT.getSizeInBits())
    6773          68 :       continue;
    6774             : 
    6775             :     // This stage of the search produces a source with the same element type as
    6776             :     // the original, but with a total width matching the BUILD_VECTOR output.
    6777          21 :     EVT EltVT = SrcVT.getVectorElementType();
    6778          21 :     unsigned NumSrcElts = VT.getSizeInBits() / EltVT.getSizeInBits();
    6779          21 :     EVT DestVT = EVT::getVectorVT(*DAG.getContext(), EltVT, NumSrcElts);
    6780             : 
    6781          29 :     if (SrcVT.getSizeInBits() < VT.getSizeInBits()) {
    6782           8 :       if (2 * SrcVT.getSizeInBits() != VT.getSizeInBits())
    6783           0 :         return SDValue();
    6784             :       // We can pad out the smaller vector for free, so if it's part of a
    6785             :       // shuffle...
    6786           8 :       Src.ShuffleVec =
    6787          16 :           DAG.getNode(ISD::CONCAT_VECTORS, dl, DestVT, Src.ShuffleVec,
    6788          24 :                       DAG.getUNDEF(Src.ShuffleVec.getValueType()));
    6789           8 :       continue;
    6790             :     }
    6791             : 
    6792          13 :     if (SrcVT.getSizeInBits() != 2 * VT.getSizeInBits())
    6793           0 :       return SDValue();
    6794             : 
    6795          13 :     if (Src.MaxElt - Src.MinElt >= NumSrcElts) {
    6796             :       // Span too large for a VEXT to cope
    6797           3 :       return SDValue();
    6798             :     }
    6799             : 
    6800          10 :     if (Src.MinElt >= NumSrcElts) {
    6801             :       // The extraction can just take the second half
    6802           0 :       Src.ShuffleVec =
    6803           0 :           DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DestVT, Src.ShuffleVec,
    6804           0 :                       DAG.getConstant(NumSrcElts, dl, MVT::i32));
    6805           0 :       Src.WindowBase = -NumSrcElts;
    6806          10 :     } else if (Src.MaxElt < NumSrcElts) {
    6807             :       // The extraction can just take the first half
    6808           9 :       Src.ShuffleVec =
    6809          18 :           DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DestVT, Src.ShuffleVec,
    6810          18 :                       DAG.getConstant(0, dl, MVT::i32));
    6811             :     } else {
    6812             :       // An actual VEXT is needed
    6813             :       SDValue VEXTSrc1 =
    6814             :           DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DestVT, Src.ShuffleVec,
    6815           1 :                       DAG.getConstant(0, dl, MVT::i32));
    6816             :       SDValue VEXTSrc2 =
    6817             :           DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DestVT, Src.ShuffleVec,
    6818           1 :                       DAG.getConstant(NumSrcElts, dl, MVT::i32));
    6819             : 
    6820           1 :       Src.ShuffleVec = DAG.getNode(ARMISD::VEXT, dl, DestVT, VEXTSrc1,
    6821             :                                    VEXTSrc2,
    6822           2 :                                    DAG.getConstant(Src.MinElt, dl, MVT::i32));
    6823           1 :       Src.WindowBase = -Src.MinElt;
    6824             :     }
    6825             :   }
    6826             : 
    6827             :   // Another possible incompatibility occurs from the vector element types. We
    6828             :   // can fix this by bitcasting the source vectors to the same type we intend
    6829             :   // for the shuffle.
    6830         124 :   for (auto &Src : Sources) {
    6831          96 :     EVT SrcEltTy = Src.ShuffleVec.getValueType().getVectorElementType();
    6832          48 :     if (SrcEltTy == SmallestEltTy)
    6833          36 :       continue;
    6834             :     assert(ShuffleVT.getVectorElementType() == SmallestEltTy);
    6835          12 :     Src.ShuffleVec = DAG.getNode(ISD::BITCAST, dl, ShuffleVT, Src.ShuffleVec);
    6836          12 :     Src.WindowScale = SrcEltTy.getSizeInBits() / SmallestEltTy.getSizeInBits();
    6837          12 :     Src.WindowBase *= Src.WindowScale;
    6838             :   }
    6839             : 
    6840             :   // Final sanity check before we try to actually produce a shuffle.
    6841             :   LLVM_DEBUG(for (auto Src
    6842             :                   : Sources)
    6843             :                  assert(Src.ShuffleVec.getValueType() == ShuffleVT););
    6844             : 
    6845             :   // The stars all align, our next step is to produce the mask for the shuffle.
    6846          56 :   SmallVector<int, 8> Mask(ShuffleVT.getVectorNumElements(), -1);
    6847          28 :   int BitsPerShuffleLane = ShuffleVT.getScalarSizeInBits();
    6848         396 :   for (unsigned i = 0; i < VT.getVectorNumElements(); ++i) {
    6849         184 :     SDValue Entry = Op.getOperand(i);
    6850         184 :     if (Entry.isUndef())
    6851          52 :       continue;
    6852             : 
    6853             :     auto Src = llvm::find(Sources, Entry.getOperand(0));
    6854         264 :     int EltNo = cast<ConstantSDNode>(Entry.getOperand(1))->getSExtValue();
    6855             : 
    6856             :     // EXTRACT_VECTOR_ELT performs an implicit any_ext; BUILD_VECTOR an implicit
    6857             :     // trunc. So only std::min(SrcBits, DestBits) actually get defined in this
    6858             :     // segment.
    6859         264 :     EVT OrigEltTy = Entry.getOperand(0).getValueType().getVectorElementType();
    6860         396 :     int BitsDefined = std::min(OrigEltTy.getSizeInBits(),
    6861         396 :                                VT.getScalarSizeInBits());
    6862         132 :     int LanesDefined = BitsDefined / BitsPerShuffleLane;
    6863             : 
    6864             :     // This source is expected to fill ResMultiplier lanes of the final shuffle,
    6865             :     // starting at the appropriate offset.
    6866         132 :     int *LaneMask = &Mask[i * ResMultiplier];
    6867             : 
    6868         132 :     int ExtractBase = EltNo * Src->WindowScale + Src->WindowBase;
    6869         264 :     ExtractBase += NumElts * (Src - Sources.begin());
    6870         396 :     for (int j = 0; j < LanesDefined; ++j)
    6871         132 :       LaneMask[j] = ExtractBase + j;
    6872             :   }
    6873             : 
    6874             :   // Final check before we try to produce nonsense...
    6875          56 :   if (!isShuffleMaskLegal(Mask, ShuffleVT))
    6876           8 :     return SDValue();
    6877             : 
    6878             :   // We can't handle more than two sources. This should have already
    6879             :   // been checked before this point.
    6880             :   assert(Sources.size() <= 2 && "Too many sources!");
    6881             : 
    6882          20 :   SDValue ShuffleOps[] = { DAG.getUNDEF(ShuffleVT), DAG.getUNDEF(ShuffleVT) };
    6883         136 :   for (unsigned i = 0; i < Sources.size(); ++i)
    6884          32 :     ShuffleOps[i] = Sources[i].ShuffleVec;
    6885             : 
    6886             :   SDValue Shuffle = DAG.getVectorShuffle(ShuffleVT, dl, ShuffleOps[0],
    6887          20 :                                          ShuffleOps[1], Mask);
    6888          20 :   return DAG.getNode(ISD::BITCAST, dl, VT, Shuffle);
    6889             : }
    6890             : 
    6891             : /// isShuffleMaskLegal - Targets can use this to indicate that they only
    6892             : /// support *some* VECTOR_SHUFFLE operations, those with specific masks.
    6893             : /// By default, if a target supports the VECTOR_SHUFFLE node, all mask values
    6894             : /// are assumed to be legal.
    6895          91 : bool ARMTargetLowering::isShuffleMaskLegal(ArrayRef<int> M, EVT VT) const {
    6896         116 :   if (VT.getVectorNumElements() == 4 &&
    6897          33 :       (VT.is128BitVector() || VT.is64BitVector())) {
    6898             :     unsigned PFIndexes[4];
    6899             :     for (unsigned i = 0; i != 4; ++i) {
    6900             :       if (M[i] < 0)
    6901             :         PFIndexes[i] = 8;
    6902             :       else
    6903             :         PFIndexes[i] = M[i];
    6904             :     }
    6905             : 
    6906             :     // Compute the index in the perfect shuffle table.
    6907             :     unsigned PFTableIndex =
    6908             :       PFIndexes[0]*9*9*9+PFIndexes[1]*9*9+PFIndexes[2]*9+PFIndexes[3];
    6909             :     unsigned PFEntry = PerfectShuffleTable[PFTableIndex];
    6910             :     unsigned Cost = (PFEntry >> 30);
    6911             : 
    6912             :     if (Cost <= 4)
    6913             :       return true;
    6914             :   }
    6915             : 
    6916             :   bool ReverseVEXT, isV_UNDEF;
    6917             :   unsigned Imm, WhichResult;
    6918             : 
    6919             :   unsigned EltSize = VT.getScalarSizeInBits();
    6920          42 :   return (EltSize >= 32 ||
    6921          82 :           ShuffleVectorSDNode::isSplatMask(&M[0], VT) ||
    6922          80 :           isVREVMask(M, VT, 64) ||
    6923          79 :           isVREVMask(M, VT, 32) ||
    6924          76 :           isVREVMask(M, VT, 16) ||
    6925          37 :           isVEXTMask(M, VT, ReverseVEXT, Imm) ||
    6926          60 :           isVTBLMask(M, VT) ||
    6927          92 :           isNEONTwoResultShuffleMask(M, VT, WhichResult, isV_UNDEF) ||
    6928          26 :           ((VT == MVT::v8i16 || VT == MVT::v16i8) && isReverseMask(M, VT)));
    6929             : }
    6930             : 
    6931             : /// GeneratePerfectShuffle - Given an entry in the perfect-shuffle table, emit
    6932             : /// the specified operations to build the shuffle.
    6933         100 : static SDValue GeneratePerfectShuffle(unsigned PFEntry, SDValue LHS,
    6934             :                                       SDValue RHS, SelectionDAG &DAG,
    6935             :                                       const SDLoc &dl) {
    6936         100 :   unsigned OpNum = (PFEntry >> 26) & 0x0F;
    6937         100 :   unsigned LHSID = (PFEntry >> 13) & ((1 << 13)-1);
    6938         100 :   unsigned RHSID = (PFEntry >>  0) & ((1 << 13)-1);
    6939             : 
    6940             :   enum {
    6941             :     OP_COPY = 0, // Copy, used for things like <u,u,u,3> to say it is <0,1,2,3>
    6942             :     OP_VREV,
    6943             :     OP_VDUP0,
    6944             :     OP_VDUP1,
    6945             :     OP_VDUP2,
    6946             :     OP_VDUP3,
    6947             :     OP_VEXT1,
    6948             :     OP_VEXT2,
    6949             :     OP_VEXT3,
    6950             :     OP_VUZPL, // VUZP, left result
    6951             :     OP_VUZPR, // VUZP, right result
    6952             :     OP_VZIPL, // VZIP, left result
    6953             :     OP_VZIPR, // VZIP, right result
    6954             :     OP_VTRNL, // VTRN, left result
    6955             :     OP_VTRNR  // VTRN, right result
    6956             :   };
    6957             : 
    6958         100 :   if (OpNum == OP_COPY) {
    6959          58 :     if (LHSID == (1*9+2)*9+3) return LHS;
    6960             :     assert(LHSID == ((4*9+5)*9+6)*9+7 && "Illegal OP_COPY!");
    6961          13 :     return RHS;
    6962             :   }
    6963             : 
    6964             :   SDValue OpLHS, OpRHS;
    6965          42 :   OpLHS = GeneratePerfectShuffle(PerfectShuffleTable[LHSID], LHS, RHS, DAG, dl);
    6966          42 :   OpRHS = GeneratePerfectShuffle(PerfectShuffleTable[RHSID], LHS, RHS, DAG, dl);
    6967          42 :   EVT VT = OpLHS.getValueType();
    6968             : 
    6969          42 :   switch (OpNum) {
    6970           0 :   default: llvm_unreachable("Unknown shuffle opcode!");
    6971             :   case OP_VREV:
    6972             :     // VREV divides the vector in half and swaps within the half.
    6973           6 :     if (VT.getVectorElementType() == MVT::i32 ||
    6974           4 :         VT.getVectorElementType() == MVT::f32)
    6975           3 :       return DAG.getNode(ARMISD::VREV64, dl, VT, OpLHS);
    6976             :     // vrev <4 x i16> -> VREV32
    6977           0 :     if (VT.getVectorElementType() == MVT::i16)
    6978           0 :       return DAG.getNode(ARMISD::VREV32, dl, VT, OpLHS);
    6979             :     // vrev <4 x i8> -> VREV16
    6980             :     assert(VT.getVectorElementType() == MVT::i8);
    6981           0 :     return DAG.getNode(ARMISD::VREV16, dl, VT, OpLHS);
    6982             :   case OP_VDUP0:
    6983             :   case OP_VDUP1:
    6984             :   case OP_VDUP2:
    6985             :   case OP_VDUP3:
    6986             :     return DAG.getNode(ARMISD::VDUPLANE, dl, VT,
    6987           7 :                        OpLHS, DAG.getConstant(OpNum-OP_VDUP0, dl, MVT::i32));
    6988             :   case OP_VEXT1:
    6989             :   case OP_VEXT2:
    6990             :   case OP_VEXT3:
    6991             :     return DAG.getNode(ARMISD::VEXT, dl, VT,
    6992             :                        OpLHS, OpRHS,
    6993          17 :                        DAG.getConstant(OpNum - OP_VEXT1 + 1, dl, MVT::i32));
    6994           6 :   case OP_VUZPL:
    6995             :   case OP_VUZPR:
    6996          12 :     return DAG.getNode(ARMISD::VUZP, dl, DAG.getVTList(VT, VT),
    6997          12 :                        OpLHS, OpRHS).getValue(OpNum-OP_VUZPL);
    6998           8 :   case OP_VZIPL:
    6999             :   case OP_VZIPR:
    7000          16 :     return DAG.getNode(ARMISD::VZIP, dl, DAG.getVTList(VT, VT),
    7001          16 :                        OpLHS, OpRHS).getValue(OpNum-OP_VZIPL);
    7002           1 :   case OP_VTRNL:
    7003             :   case OP_VTRNR:
    7004           2 :     return DAG.getNode(ARMISD::VTRN, dl, DAG.getVTList(VT, VT),
    7005           2 :                        OpLHS, OpRHS).getValue(OpNum-OP_VTRNL);
    7006             :   }
    7007             : }
    7008             : 
    7009           7 : static SDValue LowerVECTOR_SHUFFLEv8i8(SDValue Op,
    7010             :                                        ArrayRef<int> ShuffleMask,
    7011             :                                        SelectionDAG &DAG) {
    7012             :   // Check to see if we can use the VTBL instruction.
    7013           7 :   SDValue V1 = Op.getOperand(0);
    7014           7 :   SDValue V2 = Op.getOperand(1);
    7015             :   SDLoc DL(Op);
    7016             : 
    7017             :   SmallVector<SDValue, 8> VTBLMask;
    7018          56 :   for (ArrayRef<int>::iterator
    7019          63 :          I = ShuffleMask.begin(), E = ShuffleMask.end(); I != E; ++I)
    7020          56 :     VTBLMask.push_back(DAG.getConstant(*I, DL, MVT::i32));
    7021             : 
    7022           7 :   if (V2.getNode()->isUndef())
    7023             :     return DAG.getNode(ARMISD::VTBL1, DL, MVT::v8i8, V1,
    7024          10 :                        DAG.getBuildVector(MVT::v8i8, DL, VTBLMask));
    7025             : 
    7026             :   return DAG.getNode(ARMISD::VTBL2, DL, MVT::v8i8, V1, V2,
    7027           4 :                      DAG.getBuildVector(MVT::v8i8, DL, VTBLMask));
    7028             : }
    7029             : 
    7030           2 : static SDValue LowerReverse_VECTOR_SHUFFLEv16i8_v8i16(SDValue Op,
    7031             :                                                       SelectionDAG &DAG) {
    7032             :   SDLoc DL(Op);
    7033           2 :   SDValue OpLHS = Op.getOperand(0);
    7034           2 :   EVT VT = OpLHS.getValueType();
    7035             : 
    7036             :   assert((VT == MVT::v8i16 || VT == MVT::v16i8) &&
    7037             :          "Expect an v8i16/v16i8 type");
    7038           2 :   OpLHS = DAG.getNode(ARMISD::VREV64, DL, VT, OpLHS);
    7039             :   // For a v16i8 type: After the VREV, we have got <8, ...15, 8, ..., 0>. Now,
    7040             :   // extract the first 8 bytes into the top double word and the last 8 bytes
    7041             :   // into the bottom double word. The v8i16 case is similar.
    7042             :   unsigned ExtractNum = (VT == MVT::v16i8) ? 8 : 4;
    7043             :   return DAG.getNode(ARMISD::VEXT, DL, VT, OpLHS, OpLHS,
    7044           4 :                      DAG.getConstant(ExtractNum, DL, MVT::i32));
    7045             : }
    7046             : 
    7047         355 : static SDValue LowerVECTOR_SHUFFLE(SDValue Op, SelectionDAG &DAG) {
    7048         355 :   SDValue V1 = Op.getOperand(0);
    7049         355 :   SDValue V2 = Op.getOperand(1);
    7050             :   SDLoc dl(Op);
    7051         355 :   EVT VT = Op.getValueType();
    7052             :   ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(Op.getNode());
    7053             : 
    7054             :   // Convert shuffles that are directly supported on NEON to target-specific
    7055             :   // DAG nodes, instead of keeping them as shuffles and matching them again
    7056             :   // during code selection.  This is more efficient and avoids the possibility
    7057             :   // of inconsistencies between legalization and selection.
    7058             :   // FIXME: floating-point vectors should be canonicalized to integer vectors
    7059             :   // of the same time so that they get CSEd properly.
    7060         355 :   ArrayRef<int> ShuffleMask = SVN->getMask();
    7061             : 
    7062             :   unsigned EltSize = VT.getScalarSizeInBits();
    7063         355 :   if (EltSize <= 32) {
    7064         326 :     if (SVN->isSplat()) {
    7065         102 :       int Lane = SVN->getSplatIndex();
    7066             :       // If this is undef splat, generate it via "just" vdup, if possible.
    7067         102 :       if (Lane == -1) Lane = 0;
    7068             : 
    7069             :       // Test if V1 is a SCALAR_TO_VECTOR.
    7070         140 :       if (Lane == 0 && V1.getOpcode() == ISD::SCALAR_TO_VECTOR) {
    7071           2 :         return DAG.getNode(ARMISD::VDUP, dl, VT, V1.getOperand(0));
    7072             :       }
    7073             :       // Test if V1 is a BUILD_VECTOR which is equivalent to a SCALAR_TO_VECTOR
    7074             :       // (and probably will turn into a SCALAR_TO_VECTOR once legalization
    7075             :       // reaches it).
    7076         172 :       if (Lane == 0 && V1.getOpcode() == ISD::BUILD_VECTOR &&
    7077             :           !isa<ConstantSDNode>(V1.getOperand(0))) {
    7078             :         bool IsScalarToVector = true;
    7079           0 :         for (unsigned i = 1, e = V1.getNumOperands(); i != e; ++i)
    7080           0 :           if (!V1.getOperand(i).isUndef()) {
    7081             :             IsScalarToVector = false;
    7082             :             break;
    7083             :           }
    7084           0 :         if (IsScalarToVector)
    7085           0 :           return DAG.getNode(ARMISD::VDUP, dl, VT, V1.getOperand(0));
    7086             :       }
    7087             :       return DAG.getNode(ARMISD::VDUPLANE, dl, VT, V1,
    7088         100 :                          DAG.getConstant(Lane, dl, MVT::i32));
    7089             :     }
    7090             : 
    7091             :     bool ReverseVEXT;
    7092             :     unsigned Imm;
    7093         224 :     if (isVEXTMask(ShuffleMask, VT, ReverseVEXT, Imm)) {
    7094          11 :       if (ReverseVEXT)
    7095             :         std::swap(V1, V2);
    7096             :       return DAG.getNode(ARMISD::VEXT, dl, VT, V1, V2,
    7097          11 :                          DAG.getConstant(Imm, dl, MVT::i32));
    7098             :     }
    7099             : 
    7100         213 :     if (isVREVMask(ShuffleMask, VT, 64))
    7101          10 :       return DAG.getNode(ARMISD::VREV64, dl, VT, V1);
    7102         203 :     if (isVREVMask(ShuffleMask, VT, 32))
    7103           6 :       return DAG.getNode(ARMISD::VREV32, dl, VT, V1);
    7104         197 :     if (isVREVMask(ShuffleMask, VT, 16))
    7105           2 :       return DAG.getNode(ARMISD::VREV16, dl, VT, V1);
    7106             : 
    7107         195 :     if (V2->isUndef() && isSingletonVEXTMask(ShuffleMask, VT, Imm)) {
    7108             :       return DAG.getNode(ARMISD::VEXT, dl, VT, V1, V1,
    7109           4 :                          DAG.getConstant(Imm, dl, MVT::i32));
    7110             :     }
    7111             : 
    7112             :     // Check for Neon shuffles that modify both input vectors in place.
    7113             :     // If both results are used, i.e., if there are two shuffles with the same
    7114             :     // source operands and with masks corresponding to both results of one of
    7115             :     // these operations, DAG memoization will ensure that a single node is
    7116             :     // used for both shuffles.
    7117             :     unsigned WhichResult;
    7118             :     bool isV_UNDEF;
    7119         191 :     if (unsigned ShuffleOpc = isNEONTwoResultShuffleMask(
    7120         191 :             ShuffleMask, VT, WhichResult, isV_UNDEF)) {
    7121         146 :       if (isV_UNDEF)
    7122           8 :         V2 = V1;
    7123         292 :       return DAG.getNode(ShuffleOpc, dl, DAG.getVTList(VT, VT), V1, V2)
    7124         146 :           .getValue(WhichResult);
    7125             :     }
    7126             : 
    7127             :     // Also check for these shuffles through CONCAT_VECTORS: we canonicalize
    7128             :     // shuffles that produce a result larger than their operands with:
    7129             :     //   shuffle(concat(v1, undef), concat(v2, undef))
    7130             :     // ->
    7131             :     //   shuffle(concat(v1, v2), undef)
    7132             :     // because we can access quad vectors (see PerformVECTOR_SHUFFLECombine).
    7133             :     //
    7134             :     // This is useful in the general case, but there are special cases where
    7135             :     // native shuffles produce larger results: the two-result ops.
    7136             :     //
    7137             :     // Look through the concat when lowering them:
    7138             :     //   shuffle(concat(v1, v2), undef)
    7139             :     // ->
    7140             :     //   concat(VZIP(v1, v2):0, :1)
    7141             :     //
    7142          45 :     if (V1->getOpcode() == ISD::CONCAT_VECTORS && V2->isUndef()) {
    7143          24 :       SDValue SubV1 = V1->getOperand(0);
    7144          24 :       SDValue SubV2 = V1->getOperand(1);
    7145          24 :       EVT SubVT = SubV1.getValueType();
    7146             : 
    7147             :       // We expect these to have been canonicalized to -1.
    7148             :       assert(llvm::all_of(ShuffleMask, [&](int i) {
    7149             :         return i < (int)VT.getVectorNumElements();
    7150             :       }) && "Unexpected shuffle index into UNDEF operand!");
    7151             : 
    7152          24 :       if (unsigned ShuffleOpc = isNEONTwoResultShuffleMask(
    7153          24 :               ShuffleMask, SubVT, WhichResult, isV_UNDEF)) {
    7154          13 :         if (isV_UNDEF)
    7155           0 :           SubV2 = SubV1;
    7156             :         assert((WhichResult == 0) &&
    7157             :                "In-place shuffle of concat can only have one result!");
    7158             :         SDValue Res = DAG.getNode(ShuffleOpc, dl, DAG.getVTList(SubVT, SubVT),
    7159          13 :                                   SubV1, SubV2);
    7160             :         return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, Res.getValue(0),
    7161          13 :                            Res.getValue(1));
    7162             :       }
    7163             :     }
    7164             :   }
    7165             : 
    7166             :   // If the shuffle is not directly supported and it has 4 elements, use
    7167             :   // the PerfectShuffle-generated table to synthesize it from other shuffles.
    7168          61 :   unsigned NumElts = VT.getVectorNumElements();
    7169          61 :   if (NumElts == 4) {
    7170             :     unsigned PFIndexes[4];
    7171         144 :     for (unsigned i = 0; i != 4; ++i) {
    7172         128 :       if (ShuffleMask[i] < 0)
    7173           6 :         PFIndexes[i] = 8;
    7174             :       else
    7175          58 :         PFIndexes[i] = ShuffleMask[i];
    7176             :     }
    7177             : 
    7178             :     // Compute the index in the perfect shuffle table.
    7179          16 :     unsigned PFTableIndex =
    7180          16 :       PFIndexes[0]*9*9*9+PFIndexes[1]*9*9+PFIndexes[2]*9+PFIndexes[3];
    7181          16 :     unsigned PFEntry = PerfectShuffleTable[PFTableIndex];
    7182             :     unsigned Cost = (PFEntry >> 30);
    7183             : 
    7184             :     if (Cost <= 4)
    7185          16 :       return GeneratePerfectShuffle(PFEntry, V1, V2, DAG, dl);
    7186             :   }
    7187             : 
    7188             :   // Implement shuffles with 32- or 64-bit elements as ARMISD::BUILD_VECTORs.
    7189          45 :   if (EltSize >= 32) {
    7190             :     // Do the expansion with floating-point types, since that is what the VFP
    7191             :     // registers are defined to use, and since i64 is not legal.
    7192          29 :     EVT EltVT = EVT::getFloatingPointVT(EltSize);
    7193          29 :     EVT VecVT = EVT::getVectorVT(*DAG.getContext(), EltVT, NumElts);
    7194          29 :     V1 = DAG.getNode(ISD::BITCAST, dl, VecVT, V1);
    7195          29 :     V2 = DAG.getNode(ISD::BITCAST, dl, VecVT, V2);
    7196             :     SmallVector<SDValue, 8> Ops;
    7197         145 :     for (unsigned i = 0; i < NumElts; ++i) {
    7198         116 :       if (ShuffleMask[i] < 0)
    7199           8 :         Ops.push_back(DAG.getUNDEF(EltVT));
    7200             :       else
    7201          50 :         Ops.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, EltVT,
    7202          50 :                                   ShuffleMask[i] < (int)NumElts ? V1 : V2,
    7203          50 :                                   DAG.getConstant(ShuffleMask[i] & (NumElts-1),
    7204         100 :                                                   dl, MVT::i32)));
    7205             :     }
    7206          29 :     SDValue Val = DAG.getNode(ARMISD::BUILD_VECTOR, dl, VecVT, Ops);
    7207          29 :     return DAG.getNode(ISD::BITCAST, dl, VT, Val);
    7208             :   }
    7209             : 
    7210           9 :   if ((VT == MVT::v8i16 || VT == MVT::v16i8) && isReverseMask(ShuffleMask, VT))
    7211           2 :     return LowerReverse_VECTOR_SHUFFLEv16i8_v8i16(Op, DAG);
    7212             : 
    7213             :   if (VT == MVT::v8i8)
    7214           7 :     if (SDValue NewOp = LowerVECTOR_SHUFFLEv8i8(Op, ShuffleMask, DAG))
    7215           7 :       return NewOp;
    7216             : 
    7217           7 :   return SDValue();
    7218             : }
    7219             : 
    7220             : static SDValue LowerINSERT_VECTOR_ELT(SDValue Op, SelectionDAG &DAG) {
    7221             :   // INSERT_VECTOR_ELT is legal only for immediate indexes.
    7222         932 :   SDValue Lane = Op.getOperand(2);
    7223             :   if (!isa<ConstantSDNode>(Lane))
    7224             :     return SDValue();
    7225             : 
    7226             :   return Op;
    7227             : }
    7228             : 
    7229        5547 : static SDValue LowerEXTRACT_VECTOR_ELT(SDValue Op, SelectionDAG &DAG) {
    7230             :   // EXTRACT_VECTOR_ELT is legal only for immediate indexes.
    7231        5547 :   SDValue Lane = Op.getOperand(1);
    7232             :   if (!isa<ConstantSDNode>(Lane))
    7233           8 :     return SDValue();
    7234             : 
    7235        5539 :   SDValue Vec = Op.getOperand(0);
    7236         897 :   if (Op.getValueType() == MVT::i32 && Vec.getScalarValueSizeInBits() < 32) {
    7237             :     SDLoc dl(Op);
    7238          77 :     return DAG.getNode(ARMISD::VGETLANEu, dl, MVT::i32, Vec, Lane);
    7239             :   }
    7240             : 
    7241        5462 :   return Op;
    7242             : }
    7243             : 
    7244           4 : static SDValue LowerCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG) {
    7245             :   // The only time a CONCAT_VECTORS operation can have legal types is when
    7246             :   // two 64-bit vectors are concatenated to a 128-bit vector.
    7247             :   assert(Op.getValueType().is128BitVector() && Op.getNumOperands() == 2 &&
    7248             :          "unexpected CONCAT_VECTORS");
    7249             :   SDLoc dl(Op);
    7250           4 :   SDValue Val = DAG.getUNDEF(MVT::v2f64);
    7251           4 :   SDValue Op0 = Op.getOperand(0);
    7252           4 :   SDValue Op1 = Op.getOperand(1);
    7253           4 :   if (!Op0.isUndef())
    7254           4 :     Val = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Val,
    7255             :                       DAG.getNode(ISD::BITCAST, dl, MVT::f64, Op0),
    7256          12 :                       DAG.getIntPtrConstant(0, dl));
    7257           4 :   if (!Op1.isUndef())
    7258           4 :     Val = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Val,
    7259             :                       DAG.getNode(ISD::BITCAST, dl, MVT::f64, Op1),
    7260          12 :                       DAG.getIntPtrConstant(1, dl));
    7261           8 :   return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Val);
    7262             : }
    7263             : 
    7264             : /// isExtendedBUILD_VECTOR - Check if N is a constant BUILD_VECTOR where each
    7265             : /// element has been zero/sign-extended, depending on the isSigned parameter,
    7266             : /// from an integer type half its size.
    7267         518 : static bool isExtendedBUILD_VECTOR(SDNode *N, SelectionDAG &DAG,
    7268             :                                    bool isSigned) {
    7269             :   // A v2i64 BUILD_VECTOR will have been legalized to a BITCAST from v4i32.
    7270        1036 :   EVT VT = N->getValueType(0);
    7271          18 :   if (VT == MVT::v2i64 && N->getOpcode() == ISD::BITCAST) {
    7272           5 :     SDNode *BVN = N->getOperand(0).getNode();
    7273          10 :     if (BVN->getValueType(0) != MVT::v4i32 ||
    7274           5 :         BVN->getOpcode() != ISD::BUILD_VECTOR)
    7275             :       return false;
    7276          10 :     unsigned LoElt = DAG.getDataLayout().isBigEndian() ? 1 : 0;
    7277           5 :     unsigned HiElt = 1 - LoElt;
    7278           5 :     ConstantSDNode *Lo0 = dyn_cast<ConstantSDNode>(BVN->getOperand(LoElt));
    7279             :     ConstantSDNode *Hi0 = dyn_cast<ConstantSDNode>(BVN->getOperand(HiElt));
    7280           5 :     ConstantSDNode *Lo1 = dyn_cast<ConstantSDNode>(BVN->getOperand(LoElt+2));
    7281           5 :     ConstantSDNode *Hi1 = dyn_cast<ConstantSDNode>(BVN->getOperand(HiElt+2));
    7282           5 :     if (!Lo0 || !Hi0 || !Lo1 || !Hi1)
    7283             :       return false;
    7284           5 :     if (isSigned) {
    7285          16 :       if (Hi0->getSExtValue() == Lo0->getSExtValue() >> 32 &&
    7286          12 :           Hi1->getSExtValue() == Lo1->getSExtValue() >> 32)
    7287             :         return true;
    7288             :     } else {
    7289           3 :       if (Hi0->isNullValue() && Hi1->isNullValue())
    7290             :         return true;
    7291             :     }
    7292             :     return false;
    7293             :   }
    7294             : 
    7295         513 :   if (N->getOpcode() != ISD::BUILD_VECTOR)
    7296             :     return false;
    7297             : 
    7298         174 :   for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
    7299         156 :     SDNode *Elt = N->getOperand(i).getNode();
    7300             :     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Elt)) {
    7301             :       unsigned EltSize = VT.getScalarSizeInBits();
    7302          66 :       unsigned HalfSize = EltSize / 2;
    7303          66 :       if (isSigned) {
    7304          34 :         if (!isIntN(HalfSize, C->getSExtValue()))
    7305             :           return false;
    7306             :       } else {
    7307          32 :         if (!isUIntN(HalfSize, C->getZExtValue()))
    7308             :           return false;
    7309             :       }
    7310          56 :       continue;
    7311             :     }
    7312             :     return false;
    7313             :   }
    7314             : 
    7315             :   return true;
    7316             : }
    7317             : 
    7318             : /// isSignExtended - Check if a node is a vector value that is sign-extended
    7319             : /// or a constant BUILD_VECTOR with sign-extended elements.
    7320         354 : static bool isSignExtended(SDNode *N, SelectionDAG &DAG) {
    7321         708 :   if (N->getOpcode() == ISD::SIGN_EXTEND || ISD::isSEXTLoad(N))
    7322             :     return true;
    7323         274 :   if (isExtendedBUILD_VECTOR(N, DAG, true))
    7324             :     return true;
    7325         265 :   return false;
    7326             : }
    7327             : 
    7328             : /// isZeroExtended - Check if a node is a vector value that is zero-extended
    7329             : /// or a constant BUILD_VECTOR with zero-extended elements.
    7330         292 : static bool isZeroExtended(SDNode *N, SelectionDAG &DAG) {
    7331         584 :   if (N->getOpcode() == ISD::ZERO_EXTEND || ISD::isZEXTLoad(N))
    7332             :     return true;
    7333         244 :   if (isExtendedBUILD_VECTOR(N, DAG, false))
    7334             :     return true;
    7335         239 :   return false;
    7336             : }
    7337             : 
    7338          59 : static EVT getExtensionTo64Bits(const EVT &OrigVT) {
    7339          59 :   if (OrigVT.getSizeInBits() >= 64)
    7340          46 :     return OrigVT;
    7341             : 
    7342             :   assert(OrigVT.isSimple() && "Expecting a simple value type");
    7343             : 
    7344             :   MVT::SimpleValueType OrigSimpleTy = OrigVT.getSimpleVT().SimpleTy;
    7345          13 :   switch (OrigSimpleTy) {
    7346           0 :   default: llvm_unreachable("Unexpected Vector Type");
    7347             :   case MVT::v2i8:
    7348             :   case MVT::v2i16:
    7349           9 :      return MVT::v2i32;
    7350             :   case MVT::v4i8:
    7351           4 :     return  MVT::v4i16;
    7352             :   }
    7353             : }
    7354             : 
    7355             : /// AddRequiredExtensionForVMULL - Add a sign/zero extension to extend the total
    7356             : /// value size to 64 bits. We need a 64-bit D register as an operand to VMULL.
    7357             : /// We insert the required extension here to get the vector to fill a D register.
    7358          38 : static SDValue AddRequiredExtensionForVMULL(SDValue N, SelectionDAG &DAG,
    7359             :                                             const EVT &OrigTy,
    7360             :                                             const EVT &ExtTy,
    7361             :                                             unsigned ExtOpcode) {
    7362             :   // The vector originally had a size of OrigTy. It was then extended to ExtTy.
    7363             :   // We expect the ExtTy to be 128-bits total. If the OrigTy is less than
    7364             :   // 64-bits we need to insert a new extension so that it will be 64-bits.
    7365             :   assert(ExtTy.is128BitVector() && "Unexpected extension size");
    7366          38 :   if (OrigTy.getSizeInBits() >= 64)
    7367          38 :     return N;
    7368             : 
    7369             :   // Must extend size to at least 64 bits to be used as an operand for VMULL.
    7370           0 :   EVT NewVT = getExtensionTo64Bits(OrigTy);
    7371             : 
    7372           0 :   return DAG.getNode(ExtOpcode, SDLoc(N), NewVT, N);
    7373             : }
    7374             : 
    7375             : /// SkipLoadExtensionForVMULL - return a load of the original vector size that
    7376             : /// does not do any sign/zero extension. If the original vector is less
    7377             : /// than 64 bits, an appropriate extension will be added after the load to
    7378             : /// reach a total size of 64 bits. We have to add the extension separately
    7379             : /// because ARM does not have a sign/zero extending load for vectors.
    7380          59 : static SDValue SkipLoadExtensionForVMULL(LoadSDNode *LD, SelectionDAG& DAG) {
    7381          59 :   EVT ExtendedTy = getExtensionTo64Bits(LD->getMemoryVT());
    7382             : 
    7383             :   // The load already has the right type.
    7384           0 :   if (ExtendedTy == LD->getMemoryVT())
    7385          46 :     return DAG.getLoad(LD->getMemoryVT(), SDLoc(LD), LD->getChain(),
    7386          46 :                        LD->getBasePtr(), LD->getPointerInfo(),
    7387         138 :                        LD->getAlignment(), LD->getMemOperand()->getFlags());
    7388             : 
    7389             :   // We need to create a zextload/sextload. We cannot just create a load
    7390             :   // followed by a zext/zext node because LowerMUL is also run during normal
    7391             :   // operation legalization where we can't create illegal types.
    7392          13 :   return DAG.getExtLoad(LD->getExtensionType(), SDLoc(LD), ExtendedTy,
    7393          13 :                         LD->getChain(), LD->getBasePtr(), LD->getPointerInfo(),
    7394             :                         LD->getMemoryVT(), LD->getAlignment(),
    7395          39 :                         LD->getMemOperand()->getFlags());
    7396             : }
    7397             : 
    7398             : /// SkipExtensionForVMULL - For a node that is a SIGN_EXTEND, ZERO_EXTEND,
    7399             : /// extending load, or BUILD_VECTOR with extended elements, return the
    7400             : /// unextended value. The unextended vector should be 64 bits so that it can
    7401             : /// be used as an operand to a VMULL instruction. If the original vector size
    7402             : /// before extension is less than 64 bits we add a an extension to resize
    7403             : /// the vector to 64 bits.
    7404         106 : static SDValue SkipExtensionForVMULL(SDNode *N, SelectionDAG &DAG) {
    7405         212 :   if (N->getOpcode() == ISD::SIGN_EXTEND || N->getOpcode() == ISD::ZERO_EXTEND)
    7406             :     return AddRequiredExtensionForVMULL(N->getOperand(0), DAG,
    7407         114 :                                         N->getOperand(0)->getValueType(0),
    7408             :                                         N->getValueType(0),
    7409          38 :                                         N->getOpcode());
    7410             : 
    7411             :   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
    7412             :     assert((ISD::isSEXTLoad(LD) || ISD::isZEXTLoad(LD)) &&
    7413             :            "Expected extending load");
    7414             : 
    7415          59 :     SDValue newLoad = SkipLoadExtensionForVMULL(LD, DAG);
    7416          59 :     DAG.ReplaceAllUsesOfValueWith(SDValue(LD, 1), newLoad.getValue(1));
    7417             :     unsigned Opcode = ISD::isSEXTLoad(LD) ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
    7418             :     SDValue extLoad =
    7419         177 :         DAG.getNode(Opcode, SDLoc(newLoad), LD->getValueType(0), newLoad);
    7420          59 :     DAG.ReplaceAllUsesOfValueWith(SDValue(LD, 0), extLoad);
    7421             : 
    7422          59 :     return newLoad;
    7423             :   }
    7424             : 
    7425             :   // Otherwise, the value must be a BUILD_VECTOR.  For v2i64, it will
    7426             :   // have been legalized as a BITCAST from v4i32.
    7427           9 :   if (N->getOpcode() == ISD::BITCAST) {
    7428           4 :     SDNode *BVN = N->getOperand(0).getNode();
    7429             :     assert(BVN->getOpcode() == ISD::BUILD_VECTOR &&
    7430             :            BVN->getValueType(0) == MVT::v4i32 && "expected v4i32 BUILD_VECTOR");
    7431           8 :     unsigned LowElt = DAG.getDataLayout().isBigEndian() ? 1 : 0;
    7432             :     return DAG.getBuildVector(
    7433           4 :         MVT::v2i32, SDLoc(N),
    7434          20 :         {BVN->getOperand(LowElt), BVN->getOperand(LowElt + 2)});
    7435             :   }
    7436             :   // Construct a new BUILD_VECTOR with elements truncated to half the size.
    7437             :   assert(N->getOpcode() == ISD::BUILD_VECTOR && "expected BUILD_VECTOR");
    7438          10 :   EVT VT = N->getValueType(0);
    7439           5 :   unsigned EltSize = VT.getScalarSizeInBits() / 2;
    7440           5 :   unsigned NumElts = VT.getVectorNumElements();
    7441           5 :   MVT TruncVT = MVT::getIntegerVT(EltSize);
    7442             :   SmallVector<SDValue, 8> Ops;
    7443             :   SDLoc dl(N);
    7444          61 :   for (unsigned i = 0; i != NumElts; ++i) {
    7445          28 :     ConstantSDNode *C = cast<ConstantSDNode>(N->getOperand(i));
    7446          28 :     const APInt &CInt = C->getAPIntValue();
    7447             :     // Element types smaller than 32 bits are not legal, so use i32 elements.
    7448             :     // The values are implicitly truncated so sext vs. zext doesn't matter.
    7449          56 :     Ops.push_back(DAG.getConstant(CInt.zextOrTrunc(32), dl, MVT::i32));
    7450             :   }
    7451          10 :   return DAG.getBuildVector(MVT::getVectorVT(TruncVT, NumElts), dl, Ops);
    7452             : }
    7453             : 
    7454          16 : static bool isAddSubSExt(SDNode *N, SelectionDAG &DAG) {
    7455          16 :   unsigned Opcode = N->getOpcode();
    7456          16 :   if (Opcode == ISD::ADD || Opcode == ISD::SUB) {
    7457           0 :     SDNode *N0 = N->getOperand(0).getNode();
    7458           0 :     SDNode *N1 = N->getOperand(1).getNode();
    7459           0 :     return N0->hasOneUse() && N1->hasOneUse() &&
    7460           0 :       isSignExtended(N0, DAG) && isSignExtended(N1, DAG);
    7461             :   }
    7462             :   return false;
    7463             : }
    7464             : 
    7465           6 : static bool isAddSubZExt(SDNode *N, SelectionDAG &DAG) {
    7466           6 :   unsigned Opcode = N->getOpcode();
    7467           6 :   if (Opcode == ISD::ADD || Opcode == ISD::SUB) {
    7468           0 :     SDNode *N0 = N->getOperand(0).getNode();
    7469           0 :     SDNode *N1 = N->getOperand(1).getNode();
    7470           0 :     return N0->hasOneUse() && N1->hasOneUse() &&
    7471           0 :       isZeroExtended(N0, DAG) && isZeroExtended(N1, DAG);
    7472             :   }
    7473             :   return false;
    7474             : }
    7475             : 
    7476         177 : static SDValue LowerMUL(SDValue Op, SelectionDAG &DAG) {
    7477             :   // Multiplications are only custom-lowered for 128-bit vectors so that
    7478             :   // VMULL can be detected.  Otherwise v2i64 multiplications are not legal.
    7479         177 :   EVT VT = Op.getValueType();
    7480             :   assert(VT.is128BitVector() && VT.isInteger() &&
    7481             :          "unexpected type for custom-lowering ISD::MUL");
    7482         177 :   SDNode *N0 = Op.getOperand(0).getNode();
    7483         177 :   SDNode *N1 = Op.getOperand(1).getNode();
    7484             :   unsigned NewOpc = 0;
    7485             :   bool isMLA = false;
    7486         177 :   bool isN0SExt = isSignExtended(N0, DAG);
    7487         177 :   bool isN1SExt = isSignExtended(N1, DAG);
    7488         177 :   if (isN0SExt && isN1SExt)
    7489             :     NewOpc = ARMISD::VMULLs;
    7490             :   else {
    7491         146 :     bool isN0ZExt = isZeroExtended(N0, DAG);
    7492         146 :     bool isN1ZExt = isZeroExtended(N1, DAG);
    7493         146 :     if (isN0ZExt && isN1ZExt)
    7494             :       NewOpc = ARMISD::VMULLu;
    7495         124 :     else if (isN1SExt || isN1ZExt) {
    7496             :       // Look for (s/zext A + s/zext B) * (s/zext C). We want to turn these
    7497             :       // into (s/zext A * s/zext C) + (s/zext B * s/zext C)
    7498          18 :       if (isN1SExt && isAddSubSExt(N0, DAG)) {
    7499             :         NewOpc = ARMISD::VMULLs;
    7500             :         isMLA = true;
    7501          18 :       } else if (isN1ZExt && isAddSubZExt(N0, DAG)) {
    7502             :         NewOpc = ARMISD::VMULLu;
    7503             :         isMLA = true;
    7504          18 :       } else if (isN0ZExt && isAddSubZExt(N1, DAG)) {
    7505             :         std::swap(N0, N1);
    7506             :         NewOpc = ARMISD::VMULLu;
    7507             :         isMLA = true;
    7508             :       }
    7509             :     }
    7510             : 
    7511         146 :     if (!NewOpc) {
    7512             :       if (VT == MVT::v2i64)
    7513             :         // Fall through to expand this.  It is not legal.
    7514           0 :         return SDValue();
    7515             :       else
    7516             :         // Other vector multiplications are legal.
    7517         124 :         return Op;
    7518             :     }
    7519             :   }
    7520             : 
    7521             :   // Legalize to a VMULL instruction.
    7522             :   SDLoc DL(Op);
    7523          53 :   SDValue Op0;
    7524          53 :   SDValue Op1 = SkipExtensionForVMULL(N1, DAG);
    7525          53 :   if (!isMLA) {
    7526          53 :     Op0 = SkipExtensionForVMULL(N0, DAG);
    7527             :     assert(Op0.getValueType().is64BitVector() &&
    7528             :            Op1.getValueType().is64BitVector() &&
    7529             :            "unexpected types for extended operands to VMULL");
    7530          53 :     return DAG.getNode(NewOpc, DL, VT, Op0, Op1);
    7531             :   }
    7532             : 
    7533             :   // Optimizing (zext A + zext B) * C, to (VMULL A, C) + (VMULL B, C) during
    7534             :   // isel lowering to take advantage of no-stall back to back vmul + vmla.
    7535             :   //   vmull q0, d4, d6
    7536             :   //   vmlal q0, d5, d6
    7537             :   // is faster than
    7538             :   //   vaddl q0, d4, d5
    7539             :   //   vmovl q1, d6
    7540             :   //   vmul  q0, q0, q1
    7541           0 :   SDValue N00 = SkipExtensionForVMULL(N0->getOperand(0).getNode(), DAG);
    7542           0 :   SDValue N01 = SkipExtensionForVMULL(N0->getOperand(1).getNode(), DAG);
    7543           0 :   EVT Op1VT = Op1.getValueType();
    7544             :   return DAG.getNode(N0->getOpcode(), DL, VT,
    7545             :                      DAG.getNode(NewOpc, DL, VT,
    7546             :                                DAG.getNode(ISD::BITCAST, DL, Op1VT, N00), Op1),
    7547             :                      DAG.getNode(NewOpc, DL, VT,
    7548           0 :                                DAG.getNode(ISD::BITCAST, DL, Op1VT, N01), Op1));
    7549             : }
    7550             : 
    7551           4 : static SDValue LowerSDIV_v4i8(SDValue X, SDValue Y, const SDLoc &dl,
    7552             :                               SelectionDAG &DAG) {
    7553             :   // TODO: Should this propagate fast-math-flags?
    7554             : 
    7555             :   // Convert to float
    7556             :   // float4 xf = vcvt_f32_s32(vmovl_s16(a.lo));
    7557             :   // float4 yf = vcvt_f32_s32(vmovl_s16(b.lo));
    7558           4 :   X = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, X);
    7559           4 :   Y = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, Y);
    7560           4 :   X = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, X);
    7561           4 :   Y = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, Y);
    7562             :   // Get reciprocal estimate.
    7563             :   // float4 recip = vrecpeq_f32(yf);
    7564           4 :   Y = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
    7565             :                    DAG.getConstant(Intrinsic::arm_neon_vrecpe, dl, MVT::i32),
    7566           8 :                    Y);
    7567             :   // Because char has a smaller range than uchar, we can actually get away
    7568             :   // without any newton steps.  This requires that we use a weird bias
    7569             :   // of 0xb000, however (again, this has been exhaustively tested).
    7570             :   // float4 result = as_float4(as_int4(xf*recip) + 0xb000);
    7571           4 :   X = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, X, Y);
    7572           4 :   X = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, X);
    7573           4 :   Y = DAG.getConstant(0xb000, dl, MVT::v4i32);
    7574           4 :   X = DAG.getNode(ISD::ADD, dl, MVT::v4i32, X, Y);
    7575           4 :   X = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, X);
    7576             :   // Convert back to short.
    7577           4 :   X = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::v4i32, X);
    7578           4 :   X = DAG.getNode(ISD::TRUNCATE, dl, MVT::v4i16, X);
    7579           4 :   return X;
    7580             : }
    7581             : 
    7582           8 : static SDValue LowerSDIV_v4i16(SDValue N0, SDValue N1, const SDLoc &dl,
    7583             :                                SelectionDAG &DAG) {
    7584             :   // TODO: Should this propagate fast-math-flags?
    7585             : 
    7586             :   SDValue N2;
    7587             :   // Convert to float.
    7588             :   // float4 yf = vcvt_f32_s32(vmovl_s16(y));
    7589             :   // float4 xf = vcvt_f32_s32(vmovl_s16(x));
    7590           8 :   N0 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, N0);
    7591           8 :   N1 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, N1);
    7592           8 :   N0 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N0);
    7593           8 :   N1 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N1);
    7594             : 
    7595             :   // Use reciprocal estimate and one refinement step.
    7596             :   // float4 recip = vrecpeq_f32(yf);
    7597             :   // recip *= vrecpsq_f32(yf, recip);
    7598           8 :   N2 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
    7599             :                    DAG.getConstant(Intrinsic::arm_neon_vrecpe, dl, MVT::i32),
    7600          16 :                    N1);
    7601           8 :   N1 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
    7602             :                    DAG.getConstant(Intrinsic::arm_neon_vrecps, dl, MVT::i32),
    7603          16 :                    N1, N2);
    7604           8 :   N2 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N1, N2);
    7605             :   // Because short has a smaller range than ushort, we can actually get away
    7606             :   // with only a single newton step.  This requires that we use a weird bias
    7607             :   // of 89, however (again, this has been exhaustively tested).
    7608             :   // float4 result = as_float4(as_int4(xf*recip) + 0x89);
    7609           8 :   N0 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N0, N2);
    7610           8 :   N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, N0);
    7611           8 :   N1 = DAG.getConstant(0x89, dl, MVT::v4i32);
    7612           8 :   N0 = DAG.getNode(ISD::ADD, dl, MVT::v4i32, N0, N1);
    7613           8 :   N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, N0);
    7614             :   // Convert back to integer and return.
    7615             :   // return vmovn_s32(vcvt_s32_f32(result));
    7616           8 :   N0 = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::v4i32, N0);
    7617           8 :   N0 = DAG.getNode(ISD::TRUNCATE, dl, MVT::v4i16, N0);
    7618           8 :   return N0;
    7619             : }
    7620             : 
    7621           6 : static SDValue LowerSDIV(SDValue Op, SelectionDAG &DAG) {
    7622             :   EVT VT = Op.getValueType();
    7623             :   assert((VT == MVT::v4i16 || VT == MVT::v8i8) &&
    7624             :          "unexpected type for custom-lowering ISD::SDIV");
    7625             : 
    7626             :   SDLoc dl(Op);
    7627           6 :   SDValue N0 = Op.getOperand(0);
    7628           6 :   SDValue N1 = Op.getOperand(1);
    7629           6 :   SDValue N2, N3;
    7630             : 
    7631             :   if (VT == MVT::v8i8) {
    7632           2 :     N0 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v8i16, N0);
    7633           2 :     N1 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v8i16, N1);
    7634             : 
    7635           2 :     N2 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0,
    7636           4 :                      DAG.getIntPtrConstant(4, dl));
    7637           2 :     N3 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1,
    7638           4 :                      DAG.getIntPtrConstant(4, dl));
    7639           2 :     N0 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0,
    7640           4 :                      DAG.getIntPtrConstant(0, dl));
    7641           2 :     N1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1,
    7642           4 :                      DAG.getIntPtrConstant(0, dl));
    7643             : 
    7644           2 :     N0 = LowerSDIV_v4i8(N0, N1, dl, DAG); // v4i16
    7645           2 :     N2 = LowerSDIV_v4i8(N2, N3, dl, DAG); // v4i16
    7646             : 
    7647           2 :     N0 = DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v8i16, N0, N2);
    7648           2 :     N0 = LowerCONCAT_VECTORS(N0, DAG);
    7649             : 
    7650           2 :     N0 = DAG.getNode(ISD::TRUNCATE, dl, MVT::v8i8, N0);
    7651           2 :     return N0;
    7652             :   }
    7653           4 :   return LowerSDIV_v4i16(N0, N1, dl, DAG);
    7654             : }
    7655             : 
    7656           5 : static SDValue LowerUDIV(SDValue Op, SelectionDAG &DAG) {
    7657             :   // TODO: Should this propagate fast-math-flags?
    7658             :   EVT VT = Op.getValueType();
    7659             :   assert((VT == MVT::v4i16 || VT == MVT::v8i8) &&
    7660             :          "unexpected type for custom-lowering ISD::UDIV");
    7661             : 
    7662             :   SDLoc dl(Op);
    7663           5 :   SDValue N0 = Op.getOperand(0);
    7664           5 :   SDValue N1 = Op.getOperand(1);
    7665           5 :   SDValue N2, N3;
    7666             : 
    7667             :   if (VT == MVT::v8i8) {
    7668           2 :     N0 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v8i16, N0);
    7669           2 :     N1 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v8i16, N1);
    7670             : 
    7671           2 :     N2 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0,
    7672           4 :                      DAG.getIntPtrConstant(4, dl));
    7673           2 :     N3 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1,
    7674           4 :                      DAG.getIntPtrConstant(4, dl));
    7675           2 :     N0 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0,
    7676           4 :                      DAG.getIntPtrConstant(0, dl));
    7677           2 :     N1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1,
    7678           4 :                      DAG.getIntPtrConstant(0, dl));
    7679             : 
    7680           2 :     N0 = LowerSDIV_v4i16(N0, N1, dl, DAG); // v4i16
    7681           2 :     N2 = LowerSDIV_v4i16(N2, N3, dl, DAG); // v4i16
    7682             : 
    7683           2 :     N0 = DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v8i16, N0, N2);
    7684           2 :     N0 = LowerCONCAT_VECTORS(N0, DAG);
    7685             : 
    7686           2 :     N0 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v8i8,
    7687             :                      DAG.getConstant(Intrinsic::arm_neon_vqmovnsu, dl,
    7688             :                                      MVT::i32),
    7689           4 :                      N0);
    7690           2 :     return N0;
    7691             :   }
    7692             : 
    7693             :   // v4i16 sdiv ... Convert to float.
    7694             :   // float4 yf = vcvt_f32_s32(vmovl_u16(y));
    7695             :   // float4 xf = vcvt_f32_s32(vmovl_u16(x));
    7696           3 :   N0 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v4i32, N0);
    7697           3 :   N1 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v4i32, N1);
    7698           3 :   N0 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N0);
    7699           3 :   SDValue BN1 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N1);
    7700             : 
    7701             :   // Use reciprocal estimate and two refinement steps.
    7702             :   // float4 recip = vrecpeq_f32(yf);
    7703             :   // recip *= vrecpsq_f32(yf, recip);
    7704             :   // recip *= vrecpsq_f32(yf, recip);
    7705           3 :   N2 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
    7706             :                    DAG.getConstant(Intrinsic::arm_neon_vrecpe, dl, MVT::i32),
    7707           6 :                    BN1);
    7708           3 :   N1 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
    7709             :                    DAG.getConstant(Intrinsic::arm_neon_vrecps, dl, MVT::i32),
    7710           6 :                    BN1, N2);
    7711           3 :   N2 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N1, N2);
    7712           3 :   N1 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
    7713             :                    DAG.getConstant(Intrinsic::arm_neon_vrecps, dl, MVT::i32),
    7714           6 :                    BN1, N2);
    7715           3 :   N2 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N1, N2);
    7716             :   // Simply multiplying by the reciprocal estimate can leave us a few ulps
    7717             :   // too low, so we add 2 ulps (exhaustive testing shows that this is enough,
    7718             :   // and that it will never cause us to return an answer too large).
    7719             :   // float4 result = as_float4(as_int4(xf*recip) + 2);
    7720           3 :   N0 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N0, N2);
    7721           3 :   N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, N0);
    7722           3 :   N1 = DAG.getConstant(2, dl, MVT::v4i32);
    7723           3 :   N0 = DAG.getNode(ISD::ADD, dl, MVT::v4i32, N0, N1);
    7724           3 :   N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, N0);
    7725             :   // Convert back to integer and return.
    7726             :   // return vmovn_u32(vcvt_s32_f32(result));
    7727           3 :   N0 = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::v4i32, N0);
    7728           3 :   N0 = DAG.getNode(ISD::TRUNCATE, dl, MVT::v4i16, N0);
    7729           3 :   return N0;
    7730             : }
    7731             : 
    7732         557 : static SDValue LowerADDSUBCARRY(SDValue Op, SelectionDAG &DAG) {
    7733             :   SDNode *N = Op.getNode();
    7734        1114 :   EVT VT = N->getValueType(0);
    7735         557 :   SDVTList VTs = DAG.getVTList(VT, MVT::i32);
    7736             : 
    7737         557 :   SDValue Carry = Op.getOperand(2);
    7738             : 
    7739             :   SDLoc DL(Op);
    7740             : 
    7741         557 :   SDValue Result;
    7742         557 :   if (Op.getOpcode() == ISD::ADDCARRY) {
    7743             :     // This converts the boolean value carry into the carry flag.
    7744         502 :     Carry = ConvertBooleanCarryToCarryFlag(Carry, DAG);
    7745             : 
    7746             :     // Do the addition proper using the carry flag we wanted.
    7747         502 :     Result = DAG.getNode(ARMISD::ADDE, DL, VTs, Op.getOperand(0),
    7748             :                          Op.getOperand(1), Carry);
    7749             : 
    7750             :     // Now convert the carry flag into a boolean value.
    7751         502 :     Carry = ConvertCarryFlagToBooleanCarry(Result.getValue(1), VT, DAG);
    7752             :   } else {
    7753             :     // ARMISD::SUBE expects a carry not a borrow like ISD::SUBCARRY so we
    7754             :     // have to invert the carry first.
    7755          55 :     Carry = DAG.getNode(ISD::SUB, DL, MVT::i32,
    7756         110 :                         DAG.getConstant(1, DL, MVT::i32), Carry);
    7757             :     // This converts the boolean value carry into the carry flag.
    7758          55 :     Carry = ConvertBooleanCarryToCarryFlag(Carry, DAG);
    7759             : 
    7760             :     // Do the subtraction proper using the carry flag we wanted.
    7761          55 :     Result = DAG.getNode(ARMISD::SUBE, DL, VTs, Op.getOperand(0),
    7762             :                          Op.getOperand(1), Carry);
    7763             : 
    7764             :     // Now convert the carry flag into a boolean value.
    7765          55 :     Carry = ConvertCarryFlagToBooleanCarry(Result.getValue(1), VT, DAG);
    7766             :     // But the carry returned by ARMISD::SUBE is not a borrow as expected
    7767             :     // by ISD::SUBCARRY, so compute 1 - C.
    7768          55 :     Carry = DAG.getNode(ISD::SUB, DL, MVT::i32,
    7769         110 :                         DAG.getConstant(1, DL, MVT::i32), Carry);
    7770             :   }
    7771             : 
    7772             :   // Return both values.
    7773        1671 :   return DAG.getNode(ISD::MERGE_VALUES, DL, N->getVTList(), Result, Carry);
    7774             : }
    7775             : 
    7776           5 : SDValue ARMTargetLowering::LowerFSINCOS(SDValue Op, SelectionDAG &DAG) const {
    7777             :   assert(Subtarget->isTargetDarwin());
    7778             : 
    7779             :   // For iOS, we want to call an alternative entry point: __sincos_stret,
    7780             :   // return values are passed via sret.
    7781             :   SDLoc dl(Op);
    7782           5 :   SDValue Arg = Op.getOperand(0);
    7783           5 :   EVT ArgVT = Arg.getValueType();
    7784           5 :   Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
    7785           5 :   auto PtrVT = getPointerTy(DAG.getDataLayout());
    7786             : 
    7787           5 :   MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo();
    7788             :   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
    7789             : 
    7790             :   // Pair of floats / doubles used to pass the result.
    7791           5 :   Type *RetTy = StructType::get(ArgTy, ArgTy);
    7792           5 :   auto &DL = DAG.getDataLayout();
    7793             : 
    7794             :   ArgListTy Args;
    7795           5 :   bool ShouldUseSRet = Subtarget->isAPCS_ABI();
    7796             :   SDValue SRet;
    7797           5 :   if (ShouldUseSRet) {
    7798             :     // Create stack object for sret.
    7799           2 :     const uint64_t ByteSize = DL.getTypeAllocSize(RetTy);
    7800           2 :     const unsigned StackAlign = DL.getPrefTypeAlignment(RetTy);
    7801           2 :     int FrameIdx = MFI.CreateStackObject(ByteSize, StackAlign, false);
    7802           2 :     SRet = DAG.getFrameIndex(FrameIdx, TLI.getPointerTy(DL));
    7803             : 
    7804             :     ArgListEntry Entry;
    7805           2 :     Entry.Node = SRet;
    7806           2 :     Entry.Ty = RetTy->getPointerTo();
    7807           2 :     Entry.IsSExt = false;
    7808           2 :     Entry.IsZExt = false;
    7809           2 :     Entry.IsSRet = true;
    7810           2 :     Args.push_back(Entry);
    7811           2 :     RetTy = Type::getVoidTy(*DAG.getContext());
    7812             :   }
    7813             : 
    7814             :   ArgListEntry Entry;
    7815           5 :   Entry.Node = Arg;
    7816           5 :   Entry.Ty = ArgTy;
    7817             :   Entry.IsSExt = false;
    7818             :   Entry.IsZExt = false;
    7819           5 :   Args.push_back(Entry);
    7820             : 
    7821             :   RTLIB::Libcall LC =
    7822             :       (ArgVT == MVT::f64) ? RTLIB::SINCOS_STRET_F64 : RTLIB::SINCOS_STRET_F32;
    7823             :   const char *LibcallName = getLibcallName(LC);
    7824             :   CallingConv::ID CC = getLibcallCallingConv(LC);
    7825           5 :   SDValue Callee = DAG.getExternalSymbol(LibcallName, getPointerTy(DL));
    7826             : 
    7827          10 :   TargetLowering::CallLoweringInfo CLI(DAG);
    7828             :   CLI.setDebugLoc(dl)
    7829             :       .setChain(DAG.getEntryNode())
    7830             :       .setCallee(CC, RetTy, Callee, std::move(Args))
    7831             :       .setDiscardResult(ShouldUseSRet);
    7832           5 :   std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI);
    7833             : 
    7834           5 :   if (!ShouldUseSRet)
    7835           3 :     return CallResult.first;
    7836             : 
    7837             :   SDValue LoadSin =
    7838           2 :       DAG.getLoad(ArgVT, dl, CallResult.second, SRet, MachinePointerInfo());
    7839             : 
    7840             :   // Address of cos field.
    7841             :   SDValue Add = DAG.getNode(ISD::ADD, dl, PtrVT, SRet,
    7842           4 :                             DAG.getIntPtrConstant(ArgVT.getStoreSize(), dl));
    7843             :   SDValue LoadCos =
    7844           2 :       DAG.getLoad(ArgVT, dl, LoadSin.getValue(1), Add, MachinePointerInfo());
    7845             : 
    7846           2 :   SDVTList Tys = DAG.getVTList(ArgVT, ArgVT);
    7847             :   return DAG.getNode(ISD::MERGE_VALUES, dl, Tys,
    7848           2 :                      LoadSin.getValue(0), LoadCos.getValue(0));
    7849             : }
    7850             : 
    7851          27 : SDValue ARMTargetLowering::LowerWindowsDIVLibCall(SDValue Op, SelectionDAG &DAG,
    7852             :                                                   bool Signed,
    7853             :                                                   SDValue &Chain) const {
    7854          27 :   EVT VT = Op.getValueType();
    7855             :   assert((VT == MVT::i32 || VT == MVT::i64) &&
    7856             :          "unexpected type for custom lowering DIV");
    7857             :   SDLoc dl(Op);
    7858             : 
    7859          27 :   const auto &DL = DAG.getDataLayout();
    7860             :   const auto &TLI = DAG.getTargetLoweringInfo();
    7861             : 
    7862             :   const char *Name = nullptr;
    7863          27 :   if (Signed)
    7864             :     Name = (VT == MVT::i32) ? "__rt_sdiv" : "__rt_sdiv64";
    7865             :   else
    7866             :     Name = (VT == MVT::i32) ? "__rt_udiv" : "__rt_udiv64";
    7867             : 
    7868          27 :   SDValue ES = DAG.getExternalSymbol(Name, TLI.getPointerTy(DL));
    7869             : 
    7870             :   ARMTargetLowering::ArgListTy Args;
    7871             : 
    7872         135 :   for (auto AI : {1, 0}) {
    7873             :     ArgListEntry Arg;
    7874         108 :     Arg.Node = Op.getOperand(AI);
    7875         108 :     Arg.Ty = Arg.Node.getValueType().getTypeForEVT(*DAG.getContext());
    7876          54 :     Args.push_back(Arg);
    7877             :   }
    7878             : 
    7879          54 :   CallLoweringInfo CLI(DAG);
    7880             :   CLI.setDebugLoc(dl)
    7881             :     .setChain(Chain)
    7882          27 :     .setCallee(CallingConv::ARM_AAPCS_VFP, VT.getTypeForEVT(*DAG.getContext()),
    7883          27 :                ES, std::move(Args));
    7884             : 
    7885          54 :   return LowerCallTo(CLI).first;
    7886             : }
    7887             : 
    7888          23 : SDValue ARMTargetLowering::LowerDIV_Windows(SDValue Op, SelectionDAG &DAG,
    7889             :                                             bool Signed) const {
    7890             :   assert(Op.getValueType() == MVT::i32 &&
    7891             :          "unexpected type for custom lowering DIV");
    7892             :   SDLoc dl(Op);
    7893             : 
    7894             :   SDValue DBZCHK = DAG.getNode(ARMISD::WIN__DBZCHK, dl, MVT::Other,
    7895          23 :                                DAG.getEntryNode(), Op.getOperand(1));
    7896             : 
    7897          46 :   return LowerWindowsDIVLibCall(Op, DAG, Signed, DBZCHK);
    7898             : }
    7899             : 
    7900          45 : static SDValue WinDBZCheckDenominator(SelectionDAG &DAG, SDNode *N, SDValue InChain) {
    7901             :   SDLoc DL(N);
    7902          45 :   SDValue Op = N->getOperand(1);
    7903          45 :   if (N->getValueType(0) == MVT::i32)
    7904          39 :     return DAG.getNode(ARMISD::WIN__DBZCHK, DL, MVT::Other, InChain, Op);
    7905             :   SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, Op,
    7906          12 :                            DAG.getConstant(0, DL, MVT::i32));
    7907             :   SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, Op,
    7908          12 :                            DAG.getConstant(1, DL, MVT::i32));
    7909             :   return DAG.getNode(ARMISD::WIN__DBZCHK, DL, MVT::Other, InChain,
    7910          12 :                      DAG.getNode(ISD::OR, DL, MVT::i32, Lo, Hi));
    7911             : }
    7912             : 
    7913           4 : void ARMTargetLowering::ExpandDIV_Windows(
    7914             :     SDValue Op, SelectionDAG &DAG, bool Signed,
    7915             :     SmallVectorImpl<SDValue> &Results) const {
    7916           4 :   const auto &DL = DAG.getDataLayout();
    7917             :   const auto &TLI = DAG.getTargetLoweringInfo();
    7918             : 
    7919             :   assert(Op.getValueType() == MVT::i64 &&
    7920             :          "unexpected type for custom lowering DIV");
    7921             :   SDLoc dl(Op);
    7922             : 
    7923           4 :   SDValue DBZCHK = WinDBZCheckDenominator(DAG, Op.getNode(), DAG.getEntryNode());
    7924             : 
    7925           4 :   SDValue Result = LowerWindowsDIVLibCall(Op, DAG, Signed, DBZCHK);
    7926             : 
    7927           4 :   SDValue Lower = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, Result);
    7928             :   SDValue Upper = DAG.getNode(ISD::SRL, dl, MVT::i64, Result,
    7929           8 :                               DAG.getConstant(32, dl, TLI.getPointerTy(DL)));
    7930           4 :   Upper = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, Upper);
    7931             : 
    7932           4 :   Results.push_back(Lower);
    7933           4 :   Results.push_back(Upper);
    7934           4 : }
    7935             : 
    7936             : static SDValue LowerAtomicLoadStore(SDValue Op, SelectionDAG &DAG) {
    7937          48 :   if (isStrongerThanMonotonic(cast<AtomicSDNode>(Op)->getOrdering()))
    7938             :     // Acquire/Release load/store is not legal for targets without a dmb or
    7939             :     // equivalent available.
    7940             :     return SDValue();
    7941             : 
    7942             :   // Monotonic load/store is legal for all targets.
    7943             :   return Op;
    7944             : }
    7945             : 
    7946           2 : static void ReplaceREADCYCLECOUNTER(SDNode *N,
    7947             :                                     SmallVectorImpl<SDValue> &Results,
    7948             :                                     SelectionDAG &DAG,
    7949             :                                     const ARMSubtarget *Subtarget) {
    7950             :   SDLoc DL(N);
    7951             :   // Under Power Management extensions, the cycle-count is:
    7952             :   //    mrc p15, #0, <Rt>, c9, c13, #0
    7953           2 :   SDValue Ops[] = { N->getOperand(0), // Chain
    7954           2 :                     DAG.getConstant(Intrinsic::arm_mrc, DL, MVT::i32),
    7955           2 :                     DAG.getConstant(15, DL, MVT::i32),
    7956           2 :                     DAG.getConstant(0, DL, MVT::i32),
    7957           2 :                     DAG.getConstant(9, DL, MVT::i32),
    7958           2 :                     DAG.getConstant(13, DL, MVT::i32),
    7959           2 :                     DAG.getConstant(0, DL, MVT::i32)
    7960          14 :   };
    7961             : 
    7962             :   SDValue Cycles32 = DAG.getNode(ISD::INTRINSIC_W_CHAIN, DL,
    7963           2 :                                  DAG.getVTList(MVT::i32, MVT::Other), Ops);
    7964           4 :   Results.push_back(DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, Cycles32,
    7965           4 :                                 DAG.getConstant(0, DL, MVT::i32)));
    7966           2 :   Results.push_back(Cycles32.getValue(1));
    7967           2 : }
    7968             : 
    7969          14 : static SDValue createGPRPairNode(SelectionDAG &DAG, SDValue V) {
    7970          14 :   SDLoc dl(V.getNode());
    7971          14 :   SDValue VLo = DAG.getAnyExtOrTrunc(V, dl, MVT::i32);
    7972             :   SDValue VHi = DAG.getAnyExtOrTrunc(
    7973             :       DAG.getNode(ISD::SRL, dl, MVT::i64, V, DAG.getConstant(32, dl, MVT::i32)),
    7974          28 :       dl, MVT::i32);
    7975          28 :   bool isBigEndian = DAG.getDataLayout().isBigEndian();
    7976          14 :   if (isBigEndian)
    7977             :     std::swap (VLo, VHi);
    7978             :   SDValue RegClass =
    7979             :       DAG.getTargetConstant(ARM::GPRPairRegClassID, dl, MVT::i32);
    7980             :   SDValue SubReg0 = DAG.getTargetConstant(ARM::gsub_0, dl, MVT::i32);
    7981             :   SDValue SubReg1 = DAG.getTargetConstant(ARM::gsub_1, dl, MVT::i32);
    7982          14 :   const SDValue Ops[] = { RegClass, VLo, SubReg0, VHi, SubReg1 };
    7983             :   return SDValue(
    7984          28 :       DAG.getMachineNode(TargetOpcode::REG_SEQUENCE, dl, MVT::Untyped, Ops), 0);
    7985             : }
    7986             : 
    7987           7 : static void ReplaceCMP_SWAP_64Results(SDNode *N,
    7988             :                                        SmallVectorImpl<SDValue> & Results,
    7989             :                                        SelectionDAG &DAG) {
    7990             :   assert(N->getValueType(0) == MVT::i64 &&
    7991             :          "AtomicCmpSwap on types less than 64 should be legal");
    7992           7 :   SDValue Ops[] = {N->getOperand(1),
    7993             :                    createGPRPairNode(DAG, N->getOperand(2)),
    7994           7 :                    createGPRPairNode(DAG, N->getOperand(3)),
    7995          21 :                    N->getOperand(0)};
    7996          14 :   SDNode *CmpSwap = DAG.getMachineNode(
    7997           7 :       ARM::CMP_SWAP_64, SDLoc(N),
    7998           7 :       DAG.getVTList(MVT::Untyped, MVT::i32, MVT::Other), Ops);
    7999             : 
    8000           7 :   MachineFunction &MF = DAG.getMachineFunction();
    8001           7 :   MachineSDNode::mmo_iterator MemOp = MF.allocateMemRefsArray(1);
    8002           7 :   MemOp[0] = cast<MemSDNode>(N)->getMemOperand();
    8003           7 :   cast<MachineSDNode>(CmpSwap)->setMemRefs(MemOp, MemOp + 1);
    8004             : 
    8005          14 :   bool isBigEndian = DAG.getDataLayout().isBigEndian();
    8006             : 
    8007          14 :   Results.push_back(
    8008          14 :       DAG.getTargetExtractSubreg(isBigEndian ? ARM::gsub_1 : ARM::gsub_0,
    8009          14 :                                  SDLoc(N), MVT::i32, SDValue(CmpSwap, 0)));
    8010           7 :   Results.push_back(
    8011          14 :       DAG.getTargetExtractSubreg(isBigEndian ? ARM::gsub_0 : ARM::gsub_1,
    8012          14 :                                  SDLoc(N), MVT::i32, SDValue(CmpSwap, 0)));
    8013           7 :   Results.push_back(SDValue(CmpSwap, 2));
    8014           7 : }
    8015             : 
    8016           4 : static SDValue LowerFPOWI(SDValue Op, const ARMSubtarget &Subtarget,
    8017             :                           SelectionDAG &DAG) {
    8018           4 :   const auto &TLI = DAG.getTargetLoweringInfo();
    8019             : 
    8020             :   assert(Subtarget.getTargetTriple().isOSMSVCRT() &&
    8021             :          "Custom lowering is MSVCRT specific!");
    8022             : 
    8023             :   SDLoc dl(Op);
    8024           4 :   SDValue Val = Op.getOperand(0);
    8025             :   MVT Ty = Val->getSimpleValueType(0);
    8026           4 :   SDValue Exponent = DAG.getNode(ISD::SINT_TO_FP, dl, Ty, Op.getOperand(1));
    8027             :   SDValue Callee = DAG.getExternalSymbol(Ty == MVT::f32 ? "powf" : "pow",
    8028           8 :                                          TLI.getPointerTy(DAG.getDataLayout()));
    8029             : 
    8030             :   TargetLowering::ArgListTy Args;
    8031             :   TargetLowering::ArgListEntry Entry;
    8032             : 
    8033           4 :   Entry.Node = Val;
    8034           4 :   Entry.Ty = Val.getValueType().getTypeForEVT(*DAG.getContext());
    8035           4 :   Entry.IsZExt = true;
    8036           4 :   Args.push_back(Entry);
    8037             : 
    8038           4 :   Entry.Node = Exponent;
    8039           8 :   Entry.Ty = Exponent.getValueType().getTypeForEVT(*DAG.getContext());
    8040           4 :   Entry.IsZExt = true;
    8041           4 :   Args.push_back(Entry);
    8042             : 
    8043           4 :   Type *LCRTy = Val.getValueType().getTypeForEVT(*DAG.getContext());
    8044             : 
    8045             :   // In the in-chain to the call is the entry node  If we are emitting a
    8046             :   // tailcall, the chain will be mutated if the node has a non-entry input
    8047             :   // chain.
    8048             :   SDValue InChain = DAG.getEntryNode();
    8049           4 :   SDValue TCChain = InChain;
    8050             : 
    8051           4 :   const Function &F = DAG.getMachineFunction().getFunction();
    8052           6 :   bool IsTC = TLI.isInTailCallPosition(DAG, Op.getNode(), TCChain) &&
    8053             :               F.getReturnType() == LCRTy;
    8054             :   if (IsTC)
    8055           2 :     InChain = TCChain;
    8056             : 
    8057           8 :   TargetLowering::CallLoweringInfo CLI(DAG);
    8058             :   CLI.setDebugLoc(dl)
    8059             :       .setChain(InChain)
    8060             :       .setCallee(CallingConv::ARM_AAPCS_VFP, LCRTy, Callee, std::move(Args))
    8061             :       .setTailCall(IsTC);
    8062           4 :   std::pair<SDValue, SDValue> CI = TLI.LowerCallTo(CLI);
    8063             : 
    8064             :   // Return the chain (the DAG root) if it is a tail call
    8065          12 :   return !CI.second.getNode() ? DAG.getRoot() : CI.first;
    8066             : }
    8067             : 
    8068       21958 : SDValue ARMTargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
    8069             :   LLVM_DEBUG(dbgs() << "Lowering node: "; Op.dump());
    8070       21958 :   switch (Op.getOpcode()) {
    8071           0 :   default: llvm_unreachable("Don't know how to custom lower this!");
    8072           2 :   case ISD::WRITE_REGISTER: return LowerWRITE_REGISTER(Op, DAG);
    8073        1233 :   case ISD::ConstantPool: return LowerConstantPool(Op, DAG);
    8074          37 :   case ISD::BlockAddress:  return LowerBlockAddress(Op, DAG);
    8075        2083 :   case ISD::GlobalAddress: return LowerGlobalAddress(Op, DAG);
    8076         219 :   case ISD::GlobalTLSAddress: return LowerGlobalTLSAddress(Op, DAG);
    8077         146 :   case ISD::SELECT:        return LowerSELECT(Op, DAG);
    8078        1622 :   case ISD::SELECT_CC:     return LowerSELECT_CC(Op, DAG);
    8079         269 :   case ISD::BRCOND:        return LowerBRCOND(Op, DAG);
    8080        1834 :   case ISD::BR_CC:         return LowerBR_CC(Op, DAG);
    8081          37 :   case ISD::BR_JT:         return LowerBR_JT(Op, DAG);
    8082          34 :   case ISD::VASTART:       return LowerVASTART(Op, DAG);
    8083          21 :   case ISD::ATOMIC_FENCE:  return LowerATOMIC_FENCE(Op, DAG, Subtarget);
    8084          32 :   case ISD::PREFETCH:      return LowerPREFETCH(Op, DAG, Subtarget);
    8085         168 :   case ISD::SINT_TO_FP:
    8086         168 :   case ISD::UINT_TO_FP:    return LowerINT_TO_FP(Op, DAG);
    8087          99 :   case ISD::FP_TO_SINT:
    8088          99 :   case ISD::FP_TO_UINT:    return LowerFP_TO_INT(Op, DAG);
    8089          22 :   case ISD::FCOPYSIGN:     return LowerFCOPYSIGN(Op, DAG);
    8090          12 :   case ISD::RETURNADDR:    return LowerRETURNADDR(Op, DAG);
    8091          44 :   case ISD::FRAMEADDR:     return LowerFRAMEADDR(Op, DAG);
    8092           8 :   case ISD::EH_SJLJ_SETJMP: return LowerEH_SJLJ_SETJMP(Op, DAG);
    8093           9 :   case ISD::EH_SJLJ_LONGJMP: return LowerEH_SJLJ_LONGJMP(Op, DAG);
    8094          32 :   case ISD::EH_SJLJ_SETUP_DISPATCH: return LowerEH_SJLJ_SETUP_DISPATCH(Op, DAG);
    8095        2149 :   case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG,
    8096        2149 :                                                                Subtarget);
    8097         767 :   case ISD::BITCAST:       return ExpandBITCAST(Op.getNode(), DAG, Subtarget);
    8098          41 :   case ISD::SHL:
    8099             :   case ISD::SRL:
    8100          41 :   case ISD::SRA:           return LowerShift(Op.getNode(), DAG, Subtarget);
    8101           0 :   case ISD::SREM:          return LowerREM(Op.getNode(), DAG);
    8102           0 :   case ISD::UREM:          return LowerREM(Op.getNode(), DAG);
    8103           3 :   case ISD::SHL_PARTS:     return LowerShiftLeftParts(Op, DAG);
    8104           6 :   case ISD::SRL_PARTS:
    8105           6 :   case ISD::SRA_PARTS:     return LowerShiftRightParts(Op, DAG);
    8106          48 :   case ISD::CTTZ:
    8107          48 :   case ISD::CTTZ_ZERO_UNDEF: return LowerCTTZ(Op.getNode(), DAG, Subtarget);
    8108           4 :   case ISD::CTPOP:         return LowerCTPOP(Op.getNode(), DAG, Subtarget);
    8109         126 :   case ISD::SETCC:         return LowerVSETCC(Op, DAG);
    8110          87 :   case ISD::SETCCCARRY:    return LowerSETCCCARRY(Op, DAG);
    8111        1293 :   case ISD::ConstantFP:    return LowerConstantFP(Op, DAG, Subtarget);
    8112         971 :   case ISD::BUILD_VECTOR:  return LowerBUILD_VECTOR(Op, DAG, Subtarget);
    8113         355 :   case ISD::VECTOR_SHUFFLE: return LowerVECTOR_SHUFFLE(Op, DAG);
    8114         932 :   case ISD::INSERT_VECTOR_ELT: return LowerINSERT_VECTOR_ELT(Op, DAG);
    8115        5547 :   case ISD::EXTRACT_VECTOR_ELT: return LowerEXTRACT_VECTOR_ELT(Op, DAG);
    8116           0 :   case ISD::CONCAT_VECTORS: return LowerCONCAT_VECTORS(Op, DAG);
    8117           3 :   case ISD::FLT_ROUNDS_:   return LowerFLT_ROUNDS_(Op, DAG);
    8118         177 :   case ISD::MUL:           return LowerMUL(Op, DAG);
    8119          25 :   case ISD::SDIV:
    8120          98 :     if (Subtarget->isTargetWindows() && !Op.getValueType().isVector())
    8121          19 :       return LowerDIV_Windows(Op, DAG, /* Signed */ true);
    8122           6 :     return LowerSDIV(Op, DAG);
    8123           9 :   case ISD::UDIV:
    8124          34 :     if (Subtarget->isTargetWindows() && !Op.getValueType().isVector())
    8125           4 :       return LowerDIV_Windows(Op, DAG, /* Signed */ false);
    8126           5 :     return LowerUDIV(Op, DAG);
    8127         557 :   case ISD::ADDCARRY:
    8128         557 :   case ISD::SUBCARRY:      return LowerADDSUBCARRY(Op, DAG);
    8129          18 :   case ISD::SADDO:
    8130             :   case ISD::SSUBO:
    8131          18 :     return LowerSignedALUO(Op, DAG);
    8132         634 :   case ISD::UADDO:
    8133             :   case ISD::USUBO:
    8134         634 :     return LowerUnsignedALUO(Op, DAG);
    8135          24 :   case ISD::ATOMIC_LOAD:
    8136             :   case ISD::ATOMIC_STORE:  return LowerAtomicLoadStore(Op, DAG);
    8137           5 :   case ISD::FSINCOS:       return LowerFSINCOS(Op, DAG);
    8138         190 :   case ISD::SDIVREM:
    8139         190 :   case ISD::UDIVREM:       return LowerDivRem(Op, DAG);
    8140           8 :   case ISD::DYNAMIC_STACKALLOC:
    8141          16 :     if (Subtarget->isTargetWindows())
    8142           8 :       return LowerDYNAMIC_STACKALLOC(Op, DAG);
    8143           0 :     llvm_unreachable("Don't know how to custom lower this!");
    8144           5 :   case ISD::FP_ROUND: return LowerFP_ROUND(Op, DAG);
    8145           7 :   case ISD::FP_EXTEND: return LowerFP_EXTEND(Op, DAG);
    8146           4 :   case ISD::FPOWI: return LowerFPOWI(Op, *Subtarget, DAG);
    8147           0 :   case ARMISD::WIN__DBZCHK: return SDValue();
    8148             :   }
    8149             : }
    8150             : 
    8151          24 : static void ReplaceLongIntrinsic(SDNode *N, SmallVectorImpl<SDValue> &Results,
    8152             :                                  SelectionDAG &DAG) {
    8153          72 :   unsigned IntNo = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue();
    8154             :   unsigned Opc = 0;
    8155          24 :   if (IntNo == Intrinsic::arm_smlald)
    8156             :     Opc = ARMISD::SMLALD;
    8157          18 :   else if (IntNo == Intrinsic::arm_smlaldx)
    8158             :     Opc = ARMISD::SMLALDX;
    8159          12 :   else if (IntNo == Intrinsic::arm_smlsld)
    8160             :     Opc = ARMISD::SMLSLD;
    8161           6 :   else if (IntNo == Intrinsic::arm_smlsldx)
    8162             :     Opc = ARMISD::SMLSLDX;
    8163             :   else
    8164           0 :     return;
    8165             : 
    8166             :   SDLoc dl(N);
    8167             :   SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
    8168          24 :                            N->getOperand(3),
    8169          48 :                            DAG.getConstant(0, dl, MVT::i32));
    8170             :   SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
    8171          24 :                            N->getOperand(3),
    8172          48 :                            DAG.getConstant(1, dl, MVT::i32));
    8173             : 
    8174             :   SDValue LongMul = DAG.getNode(Opc, dl,
    8175             :                                 DAG.getVTList(MVT::i32, MVT::i32),
    8176          24 :                                 N->getOperand(1), N->getOperand(2),
    8177          24 :                                 Lo, Hi);
    8178          24 :   Results.push_back(LongMul.getValue(0));
    8179          24 :   Results.push_back(LongMul.getValue(1));
    8180             : }
    8181             : 
    8182             : /// ReplaceNodeResults - Replace the results of node with an illegal result
    8183             : /// type with new values built out of custom code.
    8184         951 : void ARMTargetLowering::ReplaceNodeResults(SDNode *N,
    8185             :                                            SmallVectorImpl<SDValue> &Results,
    8186             :                                            SelectionDAG &DAG) const {
    8187         951 :   SDValue Res;
    8188        1902 :   switch (N->getOpcode()) {
    8189           0 :   default:
    8190           0 :     llvm_unreachable("Don't know how to custom expand this!");
    8191           2 :   case ISD::READ_REGISTER:
    8192           2 :     ExpandREAD_REGISTER(N, Results, DAG);
    8193           2 :     break;
    8194         127 :   case ISD::BITCAST:
    8195         127 :     Res = ExpandBITCAST(N, DAG, Subtarget);
    8196         127 :     break;
    8197         767 :   case ISD::SRL:
    8198             :   case ISD::SRA:
    8199         767 :     Res = Expand64BitShift(N, DAG, Subtarget);
    8200         767 :     break;
    8201           4 :   case ISD::SREM:
    8202             :   case ISD::UREM:
    8203           4 :     Res = LowerREM(N, DAG);
    8204           4 :     break;
    8205             :   case ISD::SDIVREM:
    8206             :   case ISD::UDIVREM:
    8207          14 :     Res = LowerDivRem(SDValue(N, 0), DAG);
    8208             :     assert(Res.getNumOperands() == 2 && "DivRem needs two values");
    8209          14 :     Results.push_back(Res.getValue(0));
    8210          14 :     Results.push_back(Res.getValue(1));
    8211          65 :     return;
    8212           2 :   case ISD::READCYCLECOUNTER:
    8213           2 :     ReplaceREADCYCLECOUNTER(N, Results, DAG, Subtarget);
    8214           2 :     return;
    8215           4 :   case ISD::UDIV:
    8216             :   case ISD::SDIV:
    8217             :     assert(Subtarget->isTargetWindows() && "can only expand DIV on Windows");
    8218           8 :     return ExpandDIV_Windows(SDValue(N, 0), DAG, N->getOpcode() == ISD::SDIV,
    8219           4 :                              Results);
    8220           7 :   case ISD::ATOMIC_CMP_SWAP:
    8221           7 :     ReplaceCMP_SWAP_64Results(N, Results, DAG);
    8222           7 :     return;
    8223          24 :   case ISD::INTRINSIC_WO_CHAIN:
    8224          24 :     return ReplaceLongIntrinsic(N, Results, DAG);
    8225             :   }
    8226         900 :   if (Res.getNode())
    8227         138 :     Results.push_back(Res);
    8228             : }
    8229             : 
    8230             : //===----------------------------------------------------------------------===//
    8231             : //                           ARM Scheduler Hooks
    8232             : //===----------------------------------------------------------------------===//
    8233             : 
    8234             : /// SetupEntryBlockForSjLj - Insert code into the entry block that creates and
    8235             : /// registers the function context.
    8236          32 : void ARMTargetLowering::SetupEntryBlockForSjLj(MachineInstr &MI,
    8237             :                                                MachineBasicBlock *MBB,
    8238             :                                                MachineBasicBlock *DispatchBB,
    8239             :                                                int FI) const {
    8240             :   assert(!Subtarget->isROPI() && !Subtarget->isRWPI() &&
    8241             :          "ROPI/RWPI not currently supported with SjLj");
    8242          32 :   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
    8243             :   DebugLoc dl = MI.getDebugLoc();
    8244          32 :   MachineFunction *MF = MBB->getParent();
    8245          32 :   MachineRegisterInfo *MRI = &MF->getRegInfo();
    8246          32 :   MachineConstantPool *MCP = MF->getConstantPool();
    8247          32 :   ARMFunctionInfo *AFI = MF->getInfo<ARMFunctionInfo>();
    8248          32 :   const Function &F = MF->getFunction();
    8249             : 
    8250          32 :   bool isThumb = Subtarget->isThumb();
    8251             :   bool isThumb2 = Subtarget->isThumb2();
    8252             : 
    8253             :   unsigned PCLabelId = AFI->createPICLabelUId();
    8254          32 :   unsigned PCAdj = (isThumb || isThumb2) ? 4 : 8;
    8255             :   ARMConstantPoolValue *CPV =
    8256          32 :     ARMConstantPoolMBB::Create(F.getContext(), DispatchBB, PCLabelId, PCAdj);
    8257          32 :   unsigned CPI = MCP->getConstantPoolIndex(CPV, 4);
    8258             : 
    8259          32 :   const TargetRegisterClass *TRC = isThumb ? &ARM::tGPRRegClass
    8260             :                                            : &ARM::GPRRegClass;
    8261             : 
    8262             :   // Grab constant pool and fixed stack memory operands.
    8263             :   MachineMemOperand *CPMMO =
    8264          64 :       MF->getMachineMemOperand(MachinePointerInfo::getConstantPool(*MF),
    8265          32 :                                MachineMemOperand::MOLoad, 4, 4);
    8266             : 
    8267             :   MachineMemOperand *FIMMOSt =
    8268          64 :       MF->getMachineMemOperand(MachinePointerInfo::getFixedStack(*MF, FI),
    8269          32 :                                MachineMemOperand::MOStore, 4, 4);
    8270             : 
    8271             :   // Load the address of the dispatch MBB into the jump buffer.
    8272          32 :   if (isThumb2) {
    8273             :     // Incoming value: jbuf
    8274             :     //   ldr.n  r5, LCPI1_1
    8275             :     //   orr    r5, r5, #1
    8276             :     //   add    r5, pc
    8277             :     //   str    r5, [$jbuf, #+4] ; &jbuf[1]
    8278          11 :     unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
    8279          22 :     BuildMI(*MBB, MI, dl, TII->get(ARM::t2LDRpci), NewVReg1)
    8280             :         .addConstantPoolIndex(CPI)
    8281             :         .addMemOperand(CPMMO)
    8282          11 :         .add(predOps(ARMCC::AL));
    8283             :     // Set the low bit because of thumb mode.
    8284          11 :     unsigned NewVReg2 = MRI->createVirtualRegister(TRC);
    8285          33 :     BuildMI(*MBB, MI, dl, TII->get(ARM::t2ORRri), NewVReg2)
    8286          11 :         .addReg(NewVReg1, RegState::Kill)
    8287             :         .addImm(0x01)
    8288          11 :         .add(predOps(ARMCC::AL))
    8289          11 :         .add(condCodeOp());
    8290          11 :     unsigned NewVReg3 = MRI->createVirtualRegister(TRC);
    8291          33 :     BuildMI(*MBB, MI, dl, TII->get(ARM::tPICADD), NewVReg3)
    8292          11 :       .addReg(NewVReg2, RegState::Kill)
    8293          11 :       .addImm(PCLabelId);
    8294          33 :     BuildMI(*MBB, MI, dl, TII->get(ARM::t2STRi12))
    8295          11 :         .addReg(NewVReg3, RegState::Kill)
    8296             :         .addFrameIndex(FI)
    8297             :         .addImm(36) // &jbuf[1] :: pc
    8298             :         .addMemOperand(FIMMOSt)
    8299          11 :         .add(predOps(ARMCC::AL));
    8300          21 :   } else if (isThumb) {
    8301             :     // Incoming value: jbuf
    8302             :     //   ldr.n  r1, LCPI1_4
    8303             :     //   add    r1, pc
    8304             :     //   mov    r2, #1
    8305             :     //   orrs   r1, r2
    8306             :     //   add    r2, $jbuf, #+4 ; &jbuf[1]
    8307             :     //   str    r1, [r2]
    8308           4 :     unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
    8309           8 :     BuildMI(*MBB, MI, dl, TII->get(ARM::tLDRpci), NewVReg1)
    8310             :         .addConstantPoolIndex(CPI)
    8311             :         .addMemOperand(CPMMO)
    8312           4 :         .add(predOps(ARMCC::AL));
    8313           4 :     unsigned NewVReg2 = MRI->createVirtualRegister(TRC);
    8314          12 :     BuildMI(*MBB, MI, dl, TII->get(ARM::tPICADD), NewVReg2)
    8315           4 :       .addReg(NewVReg1, RegState::Kill)
    8316           4 :       .addImm(PCLabelId);
    8317             :     // Set the low bit because of thumb mode.
    8318           4 :     unsigned NewVReg3 = MRI->createVirtualRegister(TRC);
    8319          12 :     BuildMI(*MBB, MI, dl, TII->get(ARM::tMOVi8), NewVReg3)
    8320           4 :         .addReg(ARM::CPSR, RegState::Define)
    8321             :         .addImm(1)
    8322           4 :         .add(predOps(ARMCC::AL));
    8323           4 :     unsigned NewVReg4 = MRI->createVirtualRegister(TRC);
    8324          12 :     BuildMI(*MBB, MI, dl, TII->get(ARM::tORR), NewVReg4)
    8325           4 :         .addReg(ARM::CPSR, RegState::Define)
    8326           4 :         .addReg(NewVReg2, RegState::Kill)
    8327           4 :         .addReg(NewVReg3, RegState::Kill)
    8328           4 :         .add(predOps(ARMCC::AL));
    8329           4 :     unsigned NewVReg5 = MRI->createVirtualRegister(TRC);
    8330           8 :     BuildMI(*MBB, MI, dl, TII->get(ARM::tADDframe), NewVReg5)
    8331             :             .addFrameIndex(FI)
    8332             :             .addImm(36); // &jbuf[1] :: pc
    8333          12 :     BuildMI(*MBB, MI, dl, TII->get(ARM::tSTRi))
    8334           4 :         .addReg(NewVReg4, RegState::Kill)
    8335           4 :         .addReg(NewVReg5, RegState::Kill)
    8336             :         .addImm(0)
    8337             :         .addMemOperand(FIMMOSt)
    8338           4 :         .add(predOps(ARMCC::AL));
    8339             :   } else {
    8340             :     // Incoming value: jbuf
    8341             :     //   ldr  r1, LCPI1_1
    8342             :     //   add  r1, pc, r1
    8343             :     //   str  r1, [$jbuf, #+4] ; &jbuf[1]
    8344          17 :     unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
    8345          34 :     BuildMI(*MBB, MI, dl, TII->get(ARM::LDRi12), NewVReg1)
    8346             :         .addConstantPoolIndex(CPI)
    8347             :         .addImm(0)
    8348             :         .addMemOperand(CPMMO)
    8349          17 :         .add(predOps(ARMCC::AL));
    8350          17 :     unsigned NewVReg2 = MRI->createVirtualRegister(TRC);
    8351          51 :     BuildMI(*MBB, MI, dl, TII->get(ARM::PICADD), NewVReg2)
    8352          17 :         .addReg(NewVReg1, RegState::Kill)
    8353          17 :         .addImm(PCLabelId)
    8354          17 :         .add(predOps(ARMCC::AL));
    8355          51 :     BuildMI(*MBB, MI, dl, TII->get(ARM::STRi12))
    8356          17 :         .addReg(NewVReg2, RegState::Kill)
    8357             :         .addFrameIndex(FI)
    8358             :         .addImm(36) // &jbuf[1] :: pc
    8359             :         .addMemOperand(FIMMOSt)
    8360          17 :         .add(predOps(ARMCC::AL));
    8361             :   }
    8362          32 : }
    8363             : 
    8364          32 : void ARMTargetLowering::EmitSjLjDispatchBlock(MachineInstr &MI,
    8365             :                                               MachineBasicBlock *MBB) const {
    8366          32 :   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
    8367             :   DebugLoc dl = MI.getDebugLoc();
    8368          32 :   MachineFunction *MF = MBB->getParent();
    8369          32 :   MachineRegisterInfo *MRI = &MF->getRegInfo();
    8370          32 :   MachineFrameInfo &MFI = MF->getFrameInfo();
    8371          32 :   int FI = MFI.getFunctionContextIndex();
    8372             : 
    8373          32 :   const TargetRegisterClass *TRC = Subtarget->isThumb() ? &ARM::tGPRRegClass
    8374             :                                                         : &ARM::GPRnopcRegClass;
    8375             : 
    8376             :   // Get a mapping of the call site numbers to all of the landing pads they're
    8377             :   // associated with.
    8378             :   DenseMap<unsigned, SmallVector<MachineBasicBlock*, 2>> CallSiteNumToLPad;
    8379          32 :   unsigned MaxCSNum = 0;
    8380         390 :   for (MachineFunction::iterator BB = MF->begin(), E = MF->end(); BB != E;
    8381             :        ++BB) {
    8382         358 :     if (!BB->isEHPad()) continue;
    8383             : 
    8384             :     // FIXME: We should assert that the EH_LABEL is the first MI in the landing
    8385             :     // pad.
    8386             :     for (MachineBasicBlock::iterator
    8387         248 :            II = BB->begin(), IE = BB->end(); II != IE; ++II) {
    8388         124 :       if (!II->isEHLabel()) continue;
    8389             : 
    8390         124 :       MCSymbol *Sym = II->getOperand(0).getMCSymbol();
    8391         124 :       if (!MF->hasCallSiteLandingPad(Sym)) continue;
    8392             : 
    8393             :       SmallVectorImpl<unsigned> &CallSiteIdxs = MF->getCallSiteLandingPad(Sym);
    8394         171 :       for (SmallVectorImpl<unsigned>::iterator
    8395             :              CSI = CallSiteIdxs.begin(), CSE = CallSiteIdxs.end();
    8396         295 :            CSI != CSE; ++CSI) {
    8397         171 :         CallSiteNumToLPad[*CSI].push_back(&*BB);
    8398         171 :         MaxCSNum = std::max(MaxCSNum, *CSI);
    8399             :       }
    8400             :       break;
    8401             :     }
    8402             :   }
    8403             : 
    8404             :   // Get an ordered list of the machine basic blocks for the jump table.
    8405             :   std::vector<MachineBasicBlock*> LPadList;
    8406             :   SmallPtrSet<MachineBasicBlock*, 32> InvokeBBs;
    8407          32 :   LPadList.reserve(CallSiteNumToLPad.size());
    8408         203 :   for (unsigned I = 1; I <= MaxCSNum; ++I) {
    8409             :     SmallVectorImpl<MachineBasicBlock*> &MBBList = CallSiteNumToLPad[I];
    8410         171 :     for (SmallVectorImpl<MachineBasicBlock*>::iterator
    8411         342 :            II = MBBList.begin(), IE = MBBList.end(); II != IE; ++II) {
    8412         171 :       LPadList.push_back(*II);
    8413         171 :       InvokeBBs.insert((*II)->pred_begin(), (*II)->pred_end());
    8414             :     }
    8415             :   }
    8416             : 
    8417             :   assert(!LPadList.empty() &&
    8418             :          "No landing pad destinations for the dispatch jump table!");
    8419             : 
    8420             :   // Create the jump table and associated information.
    8421             :   MachineJumpTableInfo *JTI =
    8422          32 :     MF->getOrCreateJumpTableInfo(MachineJumpTableInfo::EK_Inline);
    8423          32 :   unsigned MJTI = JTI->createJumpTableIndex(LPadList);
    8424             : 
    8425             :   // Create the MBBs for the dispatch code.
    8426             : 
    8427             :   // Shove the dispatch's address into the return slot in the function context.
    8428          32 :   MachineBasicBlock *DispatchBB = MF->CreateMachineBasicBlock();
    8429             :   DispatchBB->setIsEHPad();
    8430             : 
    8431          32 :   MachineBasicBlock *TrapBB = MF->CreateMachineBasicBlock();
    8432             :   unsigned trap_opcode;
    8433          32 :   if (Subtarget->isThumb())
    8434             :     trap_opcode = ARM::tTRAP;
    8435             :   else
    8436          17 :     trap_opcode = Subtarget->useNaClTrap() ? ARM::TRAPNaCl : ARM::TRAP;
    8437             : 
    8438          32 :   BuildMI(TrapBB, dl, TII->get(trap_opcode));
    8439          32 :   DispatchBB->addSuccessor(TrapBB);
    8440             : 
    8441          32 :   MachineBasicBlock *DispContBB = MF->CreateMachineBasicBlock();
    8442          32 :   DispatchBB->addSuccessor(DispContBB);
    8443             : 
    8444             :   // Insert and MBBs.
    8445             :   MF->insert(MF->end(), DispatchBB);
    8446             :   MF->insert(MF->end(), DispContBB);
    8447             :   MF->insert(MF->end(), TrapBB);
    8448             : 
    8449             :   // Insert code into the entry block that creates and registers the function
    8450             :   // context.
    8451          32 :   SetupEntryBlockForSjLj(MI, MBB, DispatchBB, FI);
    8452             : 
    8453          64 :   MachineMemOperand *FIMMOLd = MF->getMachineMemOperand(
    8454             :       MachinePointerInfo::getFixedStack(*MF, FI),
    8455          32 :       MachineMemOperand::MOLoad | MachineMemOperand::MOVolatile, 4, 4);
    8456             : 
    8457             :   MachineInstrBuilder MIB;
    8458          32 :   MIB = BuildMI(DispatchBB, dl, TII->get(ARM::Int_eh_sjlj_dispatchsetup));
    8459             : 
    8460             :   const ARMBaseInstrInfo *AII = static_cast<const ARMBaseInstrInfo*>(TII);
    8461          32 :   const ARMBaseRegisterInfo &RI = AII->getRegisterInfo();
    8462             : 
    8463             :   // Add a register mask with no preserved registers.  This results in all
    8464             :   // registers being marked as clobbered. This can't work if the dispatch block
    8465             :   // is in a Thumb1 function and is linked with ARM code which uses the FP
    8466             :   // registers, as there is no way to preserve the FP registers in Thumb1 mode.
    8467          32 :   MIB.addRegMask(RI.getSjLjDispatchPreservedMask(*MF));
    8468             : 
    8469          32 :   bool IsPositionIndependent = isPositionIndependent();
    8470          64 :   unsigned NumLPads = LPadList.size();
    8471          32 :   if (Subtarget->isThumb2()) {
    8472          11 :     unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
    8473          11 :     BuildMI(DispatchBB, dl, TII->get(ARM::t2LDRi12), NewVReg1)
    8474             :         .addFrameIndex(FI)
    8475             :         .addImm(4)
    8476             :         .addMemOperand(FIMMOLd)
    8477          11 :         .add(predOps(ARMCC::AL));
    8478             : 
    8479          11 :     if (NumLPads < 256) {
    8480          33 :       BuildMI(DispatchBB, dl, TII->get(ARM::t2CMPri))
    8481          11 :           .addReg(NewVReg1)
    8482          11 :           .addImm(LPadList.size())
    8483          11 :           .add(predOps(ARMCC::AL));
    8484             :     } else {
    8485           0 :       unsigned VReg1 = MRI->createVirtualRegister(TRC);
    8486           0 :       BuildMI(DispatchBB, dl, TII->get(ARM::t2MOVi16), VReg1)
    8487           0 :           .addImm(NumLPads & 0xFFFF)
    8488           0 :           .add(predOps(ARMCC::AL));
    8489             : 
    8490             :       unsigned VReg2 = VReg1;
    8491           0 :       if ((NumLPads & 0xFFFF0000) != 0) {
    8492           0 :         VReg2 = MRI->createVirtualRegister(TRC);
    8493           0 :         BuildMI(DispatchBB, dl, TII->get(ARM::t2MOVTi16), VReg2)
    8494           0 :             .addReg(VReg1)
    8495           0 :             .addImm(NumLPads >> 16)
    8496           0 :             .add(predOps(ARMCC::AL));
    8497             :       }
    8498             : 
    8499           0 :       BuildMI(DispatchBB, dl, TII->get(ARM::t2CMPrr))
    8500           0 :           .addReg(NewVReg1)
    8501           0 :           .addReg(VReg2)
    8502           0 :           .add(predOps(ARMCC::AL));
    8503             :     }
    8504             : 
    8505          33 :     BuildMI(DispatchBB, dl, TII->get(ARM::t2Bcc))
    8506             :       .addMBB(TrapBB)
    8507             :       .addImm(ARMCC::HI)
    8508          11 :       .addReg(ARM::CPSR);
    8509             : 
    8510          11 :     unsigned NewVReg3 = MRI->createVirtualRegister(TRC);
    8511          11 :     BuildMI(DispContBB, dl, TII->get(ARM::t2LEApcrelJT), NewVReg3)
    8512             :         .addJumpTableIndex(MJTI)
    8513          11 :         .add(predOps(ARMCC::AL));
    8514             : 
    8515          11 :     unsigned NewVReg4 = MRI->createVirtualRegister(TRC);
    8516          33 :     BuildMI(DispContBB, dl, TII->get(ARM::t2ADDrs), NewVReg4)
    8517          11 :         .addReg(NewVReg3, RegState::Kill)
    8518          11 :         .addReg(NewVReg1)
    8519             :         .addImm(ARM_AM::getSORegOpc(ARM_AM::lsl, 2))
    8520          11 :         .add(predOps(ARMCC::AL))
    8521          11 :         .add(condCodeOp());
    8522             : 
    8523          33 :     BuildMI(DispContBB, dl, TII->get(ARM::t2BR_JT))
    8524          11 :       .addReg(NewVReg4, RegState::Kill)
    8525          11 :       .addReg(NewVReg1)
    8526             :       .addJumpTableIndex(MJTI);
    8527          21 :   } else if (Subtarget->isThumb()) {
    8528           4 :     unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
    8529           4 :     BuildMI(DispatchBB, dl, TII->get(ARM::tLDRspi), NewVReg1)
    8530             :         .addFrameIndex(FI)
    8531             :         .addImm(1)
    8532             :         .addMemOperand(FIMMOLd)
    8533           4 :         .add(predOps(ARMCC::AL));
    8534             : 
    8535           4 :     if (NumLPads < 256) {
    8536          12 :       BuildMI(DispatchBB, dl, TII->get(ARM::tCMPi8))
    8537           4 :           .addReg(NewVReg1)
    8538             :           .addImm(NumLPads)
    8539           4 :           .add(predOps(ARMCC::AL));
    8540             :     } else {
    8541           0 :       MachineConstantPool *ConstantPool = MF->getConstantPool();
    8542           0 :       Type *Int32Ty = Type::getInt32Ty(MF->getFunction().getContext());
    8543           0 :       const Constant *C = ConstantInt::get(Int32Ty, NumLPads);
    8544             : 
    8545             :       // MachineConstantPool wants an explicit alignment.
    8546           0 :       unsigned Align = MF->getDataLayout().getPrefTypeAlignment(Int32Ty);
    8547           0 :       if (Align == 0)
    8548           0 :         Align = MF->getDataLayout().getTypeAllocSize(C->getType());
    8549           0 :       unsigned Idx = ConstantPool->getConstantPoolIndex(C, Align);
    8550             : 
    8551           0 :       unsigned VReg1 = MRI->createVirtualRegister(TRC);
    8552           0 :       BuildMI(DispatchBB, dl, TII->get(ARM::tLDRpci))
    8553           0 :           .addReg(VReg1, RegState::Define)
    8554             :           .addConstantPoolIndex(Idx)
    8555           0 :           .add(predOps(ARMCC::AL));
    8556           0 :       BuildMI(DispatchBB, dl, TII->get(ARM::tCMPr))
    8557           0 :           .addReg(NewVReg1)
    8558           0 :           .addReg(VReg1)
    8559           0 :           .add(predOps(ARMCC::AL));
    8560             :     }
    8561             : 
    8562          12 :     BuildMI(DispatchBB, dl, TII->get(ARM::tBcc))
    8563             :       .addMBB(TrapBB)
    8564             :       .addImm(ARMCC::HI)
    8565           4 :       .addReg(ARM::CPSR);
    8566             : 
    8567           4 :     unsigned NewVReg2 = MRI->createVirtualRegister(TRC);
    8568          12 :     BuildMI(DispContBB, dl, TII->get(ARM::tLSLri), NewVReg2)
    8569           4 :         .addReg(ARM::CPSR, RegState::Define)
    8570           4 :         .addReg(NewVReg1)
    8571             :         .addImm(2)
    8572           4 :         .add(predOps(ARMCC::AL));
    8573             : 
    8574           4 :     unsigned NewVReg3 = MRI->createVirtualRegister(TRC);
    8575           4 :     BuildMI(DispContBB, dl, TII->get(ARM::tLEApcrelJT), NewVReg3)
    8576             :         .addJumpTableIndex(MJTI)
    8577           4 :         .add(predOps(ARMCC::AL));
    8578             : 
    8579           4 :     unsigned NewVReg4 = MRI->createVirtualRegister(TRC);
    8580          12 :     BuildMI(DispContBB, dl, TII->get(ARM::tADDrr), NewVReg4)
    8581           4 :         .addReg(ARM::CPSR, RegState::Define)
    8582           4 :         .addReg(NewVReg2, RegState::Kill)
    8583           4 :         .addReg(NewVReg3)
    8584           4 :         .add(predOps(ARMCC::AL));
    8585             : 
    8586           8 :     MachineMemOperand *JTMMOLd = MF->getMachineMemOperand(
    8587           4 :         MachinePointerInfo::getJumpTable(*MF), MachineMemOperand::MOLoad, 4, 4);
    8588             : 
    8589           4 :     unsigned NewVReg5 = MRI->createVirtualRegister(TRC);
    8590          12 :     BuildMI(DispContBB, dl, TII->get(ARM::tLDRi), NewVReg5)
    8591           4 :         .addReg(NewVReg4, RegState::Kill)
    8592             :         .addImm(0)
    8593             :         .addMemOperand(JTMMOLd)
    8594           4 :         .add(predOps(ARMCC::AL));
    8595             : 
    8596             :     unsigned NewVReg6 = NewVReg5;
    8597           4 :     if (IsPositionIndependent) {
    8598           2 :       NewVReg6 = MRI->createVirtualRegister(TRC);
    8599           6 :       BuildMI(DispContBB, dl, TII->get(ARM::tADDrr), NewVReg6)
    8600           2 :           .addReg(ARM::CPSR, RegState::Define)
    8601           2 :           .addReg(NewVReg5, RegState::Kill)
    8602           2 :           .addReg(NewVReg3)
    8603           2 :           .add(predOps(ARMCC::AL));
    8604             :     }
    8605             : 
    8606          12 :     BuildMI(DispContBB, dl, TII->get(ARM::tBR_JTr))
    8607           4 :       .addReg(NewVReg6, RegState::Kill)
    8608             :       .addJumpTableIndex(MJTI);
    8609             :   } else {
    8610          17 :     unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
    8611          17 :     BuildMI(DispatchBB, dl, TII->get(ARM::LDRi12), NewVReg1)
    8612             :         .addFrameIndex(FI)
    8613             :         .addImm(4)
    8614             :         .addMemOperand(FIMMOLd)
    8615          17 :         .add(predOps(ARMCC::AL));
    8616             : 
    8617          17 :     if (NumLPads < 256) {
    8618          51 :       BuildMI(DispatchBB, dl, TII->get(ARM::CMPri))
    8619          17 :           .addReg(NewVReg1)
    8620             :           .addImm(NumLPads)
    8621          17 :           .add(predOps(ARMCC::AL));
    8622           0 :     } else if (Subtarget->hasV6T2Ops() && isUInt<16>(NumLPads)) {
    8623           0 :       unsigned VReg1 = MRI->createVirtualRegister(TRC);
    8624           0 :       BuildMI(DispatchBB, dl, TII->get(ARM::MOVi16), VReg1)
    8625           0 :           .addImm(NumLPads & 0xFFFF)
    8626           0 :           .add(predOps(ARMCC::AL));
    8627             : 
    8628             :       unsigned VReg2 = VReg1;
    8629           0 :       if ((NumLPads & 0xFFFF0000) != 0) {
    8630           0 :         VReg2 = MRI->createVirtualRegister(TRC);
    8631           0 :         BuildMI(DispatchBB, dl, TII->get(ARM::MOVTi16), VReg2)
    8632           0 :             .addReg(VReg1)
    8633           0 :             .addImm(NumLPads >> 16)
    8634           0 :             .add(predOps(ARMCC::AL));
    8635             :       }
    8636             : 
    8637           0 :       BuildMI(DispatchBB, dl, TII->get(ARM::CMPrr))
    8638           0 :           .addReg(NewVReg1)
    8639           0 :           .addReg(VReg2)
    8640           0 :           .add(predOps(ARMCC::AL));
    8641             :     } else {
    8642           0 :       MachineConstantPool *ConstantPool = MF->getConstantPool();
    8643           0 :       Type *Int32Ty = Type::getInt32Ty(MF->getFunction().getContext());
    8644           0 :       const Constant *C = ConstantInt::get(Int32Ty, NumLPads);
    8645             : 
    8646             :       // MachineConstantPool wants an explicit alignment.
    8647           0 :       unsigned Align = MF->getDataLayout().getPrefTypeAlignment(Int32Ty);
    8648           0 :       if (Align == 0)
    8649           0 :         Align = MF->getDataLayout().getTypeAllocSize(C->getType());
    8650           0 :       unsigned Idx = ConstantPool->getConstantPoolIndex(C, Align);
    8651             : 
    8652           0 :       unsigned VReg1 = MRI->createVirtualRegister(TRC);
    8653           0 :       BuildMI(DispatchBB, dl, TII->get(ARM::LDRcp))
    8654           0 :           .addReg(VReg1, RegState::Define)
    8655             :           .addConstantPoolIndex(Idx)
    8656             :           .addImm(0)
    8657           0 :           .add(predOps(ARMCC::AL));
    8658           0 :       BuildMI(DispatchBB, dl, TII->get(ARM::CMPrr))
    8659           0 :           .addReg(NewVReg1)
    8660           0 :           .addReg(VReg1, RegState::Kill)
    8661           0 :           .add(predOps(ARMCC::AL));
    8662             :     }
    8663             : 
    8664          51 :     BuildMI(DispatchBB, dl, TII->get(ARM::Bcc))
    8665             :       .addMBB(TrapBB)
    8666             :       .addImm(ARMCC::HI)
    8667          17 :       .addReg(ARM::CPSR);
    8668             : 
    8669          17 :     unsigned NewVReg3 = MRI->createVirtualRegister(TRC);
    8670          51 :     BuildMI(DispContBB, dl, TII->get(ARM::MOVsi), NewVReg3)
    8671          17 :         .addReg(NewVReg1)
    8672             :         .addImm(ARM_AM::getSORegOpc(ARM_AM::lsl, 2))
    8673          17 :         .add(predOps(ARMCC::AL))
    8674          17 :         .add(condCodeOp());
    8675          17 :     unsigned NewVReg4 = MRI->createVirtualRegister(TRC);
    8676          17 :     BuildMI(DispContBB, dl, TII->get(ARM::LEApcrelJT), NewVReg4)
    8677             :         .addJumpTableIndex(MJTI)
    8678          17 :         .add(predOps(ARMCC::AL));
    8679             : 
    8680          34 :     MachineMemOperand *JTMMOLd = MF->getMachineMemOperand(
    8681          17 :         MachinePointerInfo::getJumpTable(*MF), MachineMemOperand::MOLoad, 4, 4);
    8682          17 :     unsigned NewVReg5 = MRI->createVirtualRegister(TRC);
    8683          51 :     BuildMI(DispContBB, dl, TII->get(ARM::LDRrs), NewVReg5)
    8684          17 :         .addReg(NewVReg3, RegState::Kill)
    8685          17 :         .addReg(NewVReg4)
    8686             :         .addImm(0)
    8687             :         .addMemOperand(JTMMOLd)
    8688          17 :         .add(predOps(ARMCC::AL));
    8689             : 
    8690          17 :     if (IsPositionIndependent) {
    8691          39 :       BuildMI(DispContBB, dl, TII->get(ARM::BR_JTadd))
    8692          13 :         .addReg(NewVReg5, RegState::Kill)
    8693          13 :         .addReg(NewVReg4)
    8694             :         .addJumpTableIndex(MJTI);
    8695             :     } else {
    8696          12 :       BuildMI(DispContBB, dl, TII->get(ARM::BR_JTr))
    8697           4 :         .addReg(NewVReg5, RegState::Kill)
    8698             :         .addJumpTableIndex(MJTI);
    8699             :     }
    8700             :   }
    8701             : 
    8702             :   // Add the jump table entries as successors to the MBB.
    8703             :   SmallPtrSet<MachineBasicBlock*, 8> SeenMBBs;
    8704             :   for (std::vector<MachineBasicBlock*>::iterator
    8705         203 :          I = LPadList.begin(), E = LPadList.end(); I != E; ++I) {
    8706         171 :     MachineBasicBlock *CurMBB = *I;
    8707         171 :     if (SeenMBBs.insert(CurMBB).second)
    8708         124 :       DispContBB->addSuccessor(CurMBB);
    8709             :   }
    8710             : 
    8711             :   // N.B. the order the invoke BBs are processed in doesn't matter here.
    8712          32 :   const MCPhysReg *SavedRegs = RI.getCalleeSavedRegs(MF);
    8713             :   SmallVector<MachineBasicBlock*, 64> MBBLPads;
    8714          32 :   for (MachineBasicBlock *BB : InvokeBBs) {
    8715             : 
    8716             :     // Remove the landing pad successor from the invoke block and replace it
    8717             :     // with the new dispatch block.
    8718             :     SmallVector<MachineBasicBlock*, 4> Successors(BB->succ_begin(),
    8719             :                                                   BB->succ_end());
    8720         855 :     while (!Successors.empty()) {
    8721         342 :       MachineBasicBlock *SMBB = Successors.pop_back_val();
    8722         342 :       if (SMBB->isEHPad()) {
    8723         171 :         BB->removeSuccessor(SMBB);
    8724         171 :         MBBLPads.push_back(SMBB);
    8725             :       }
    8726             :     }
    8727             : 
    8728         171 :     BB->addSuccessor(DispatchBB, BranchProbability::getZero());
    8729             :     BB->normalizeSuccProbs();
    8730             : 
    8731             :     // Find the invoke call and mark all of the callee-saved registers as
    8732             :     // 'implicit defined' so that they're spilled. This prevents code from
    8733             :     // moving instructions to before the EH block, where they will never be
    8734             :     // executed.
    8735             :     for (MachineBasicBlock::reverse_iterator
    8736         950 :            II = BB->rbegin(), IE = BB->rend(); II != IE; ++II) {
    8737         779 :       if (!II->isCall()) continue;
    8738             : 
    8739             :       DenseMap<unsigned, bool> DefRegs;
    8740        1510 :       for (MachineInstr::mop_iterator
    8741         171 :              OI = II->operands_begin(), OE = II->operands_end();
    8742        1681 :            OI != OE; ++OI) {
    8743        1510 :         if (!OI->isReg()) continue;
    8744        2158 :         DefRegs[OI->getReg()] = true;
    8745             :       }
    8746             : 
    8747             :       MachineInstrBuilder MIB(*MF, &*II);
    8748             : 
    8749        5649 :       for (unsigned i = 0; SavedRegs[i] != 0; ++i) {
    8750        2739 :         unsigned Reg = SavedRegs[i];
    8751        4828 :         if (Subtarget->isThumb2() &&
    8752        2438 :             !ARM::tGPRRegClass.contains(Reg) &&
    8753        1045 :             !ARM::hGPRRegClass.contains(Reg))
    8754        2080 :           continue;
    8755         176 :         if (Subtarget->isThumb1Only() && !ARM::tGPRRegClass.contains(Reg))
    8756          48 :           continue;
    8757        5199 :         if (!Subtarget->isThumb() && !ARM::GPRRegClass.contains(Reg))
    8758         640 :           continue;
    8759        1355 :         if (!DefRegs[Reg])
    8760        1188 :           MIB.addReg(Reg, RegState::ImplicitDefine | RegState::Dead);
    8761             :       }
    8762             : 
    8763             :       break;
    8764             :     }
    8765             :   }
    8766             : 
    8767             :   // Mark all former landing pads as non-landing pads. The dispatch is the only
    8768             :   // landing pad now.
    8769         171 :   for (SmallVectorImpl<MachineBasicBlock*>::iterator
    8770         203 :          I = MBBLPads.begin(), E = MBBLPads.end(); I != E; ++I)
    8771         171 :     (*I)->setIsEHPad(false);
    8772             : 
    8773             :   // The instruction is gone now.
    8774          32 :   MI.eraseFromParent();
    8775          32 : }
    8776             : 
    8777             : static
    8778             : MachineBasicBlock *OtherSucc(MachineBasicBlock *MBB, MachineBasicBlock *Succ) {
    8779             :   for (MachineBasicBlock::succ_iterator I = MBB->succ_begin(),
    8780           1 :        E = MBB->succ_end(); I != E; ++I)
    8781           1 :     if (*I != Succ)
    8782             :       return *I;
    8783           0 :   llvm_unreachable("Expecting a BB with two successors!");
    8784             : }
    8785             : 
    8786             : /// Return the load opcode for a given load size. If load size >= 8,
    8787             : /// neon opcode will be returned.
    8788        2532 : static unsigned getLdOpcode(unsigned LdSize, bool IsThumb1, bool IsThumb2) {
    8789        2532 :   if (LdSize >= 8)
    8790          83 :     return LdSize == 16 ? ARM::VLD1q32wb_fixed
    8791             :                         : LdSize == 8 ? ARM::VLD1d32wb_fixed : 0;
    8792        2449 :   if (IsThumb1)
    8793         921 :     return LdSize == 4 ? ARM::tLDRi
    8794             :                        : LdSize == 2 ? ARM::tLDRHi
    8795             :                                      : LdSize == 1 ? ARM::tLDRBi : 0;
    8796        1528 :   if (IsThumb2)
    8797         512 :     return LdSize == 4 ? ARM::t2LDR_POST
    8798             :                        : LdSize == 2 ? ARM::t2LDRH_POST
    8799             :                                      : LdSize == 1 ? ARM::t2LDRB_POST : 0;
    8800        1016 :   return LdSize == 4 ? ARM::LDR_POST_IMM
    8801             :                      : LdSize == 2 ? ARM::LDRH_POST
    8802             :                                    : LdSize == 1 ? ARM::LDRB_POST_IMM : 0;
    8803             : }
    8804             : 
    8805             : /// Return the store opcode for a given store size. If store size >= 8,
    8806             : /// neon opcode will be returned.
    8807        2532 : static unsigned getStOpcode(unsigned StSize, bool IsThumb1, bool IsThumb2) {
    8808        2532 :   if (StSize >= 8)
    8809          83 :     return StSize == 16 ? ARM::VST1q32wb_fixed
    8810             :                         : StSize == 8 ? ARM::VST1d32wb_fixed : 0;
    8811        2449 :   if (IsThumb1)
    8812         921 :     return StSize == 4 ? ARM::tSTRi
    8813             :                        : StSize == 2 ? ARM::tSTRHi
    8814             :                                      : StSize == 1 ? ARM::tSTRBi : 0;
    8815        1528 :   if (IsThumb2)
    8816         512 :     return StSize == 4 ? ARM::t2STR_POST
    8817             :                        : StSize == 2 ? ARM::t2STRH_POST
    8818             :                                      : StSize == 1 ? ARM::t2STRB_POST : 0;
    8819        1016 :   return StSize == 4 ? ARM::STR_POST_IMM
    8820             :                      : StSize == 2 ? ARM::STRH_POST
    8821             :                                    : StSize == 1 ? ARM::STRB_POST_IMM : 0;
    8822             : }
    8823             : 
    8824             : /// Emit a post-increment load operation with given size. The instructions
    8825             : /// will be added to BB at Pos.
    8826        2532 : static void emitPostLd(MachineBasicBlock *BB, MachineBasicBlock::iterator Pos,
    8827             :                        const TargetInstrInfo *TII, const DebugLoc &dl,
    8828             :                        unsigned LdSize, unsigned Data, unsigned AddrIn,
    8829             :                        unsigned AddrOut, bool IsThumb1, bool IsThumb2) {
    8830        2532 :   unsigned LdOpc = getLdOpcode(LdSize, IsThumb1, IsThumb2);
    8831             :   assert(LdOpc != 0 && "Should have a load opcode");
    8832        2532 :   if (LdSize >= 8) {
    8833         249 :     BuildMI(*BB, Pos, dl, TII->get(LdOpc), Data)
    8834          83 :         .addReg(AddrOut, RegState::Define)
    8835          83 :         .addReg(AddrIn)
    8836             :         .addImm(0)
    8837          83 :         .add(predOps(ARMCC::AL));
    8838        2449 :   } else if (IsThumb1) {
    8839             :     // load + update AddrIn
    8840        2763 :     BuildMI(*BB, Pos, dl, TII->get(LdOpc), Data)
    8841         921 :         .addReg(AddrIn)
    8842             :         .addImm(0)
    8843         921 :         .add(predOps(ARMCC::AL));
    8844        2763 :     BuildMI(*BB, Pos, dl, TII->get(ARM::tADDi8), AddrOut)
    8845         921 :         .add(t1CondCodeOp())
    8846         921 :         .addReg(AddrIn)
    8847         921 :         .addImm(LdSize)
    8848         921 :         .add(predOps(ARMCC::AL));
    8849        1528 :   } else if (IsThumb2) {
    8850        1536 :     BuildMI(*BB, Pos, dl, TII->get(LdOpc), Data)
    8851         512 :         .addReg(AddrOut, RegState::Define)
    8852         512 :         .addReg(AddrIn)
    8853         512 :         .addImm(LdSize)
    8854         512 :         .add(predOps(ARMCC::AL));
    8855             :   } else { // arm
    8856        3048 :     BuildMI(*BB, Pos, dl, TII->get(LdOpc), Data)
    8857        1016 :         .addReg(AddrOut, RegState::Define)
    8858        1016 :         .addReg(AddrIn)
    8859        1016 :         .addReg(0)
    8860        1016 :         .addImm(LdSize)
    8861        1016 :         .add(predOps(ARMCC::AL));
    8862             :   }
    8863        2532 : }
    8864             : 
    8865             : /// Emit a post-increment store operation with given size. The instructions
    8866             : /// will be added to BB at Pos.
    8867        2532 : static void emitPostSt(MachineBasicBlock *BB, MachineBasicBlock::iterator Pos,
    8868             :                        const TargetInstrInfo *TII, const DebugLoc &dl,
    8869             :                        unsigned StSize, unsigned Data, unsigned AddrIn,
    8870             :                        unsigned AddrOut, bool IsThumb1, bool IsThumb2) {
    8871        2532 :   unsigned StOpc = getStOpcode(StSize, IsThumb1, IsThumb2);
    8872             :   assert(StOpc != 0 && "Should have a store opcode");
    8873        2532 :   if (StSize >= 8) {
    8874         249 :     BuildMI(*BB, Pos, dl, TII->get(StOpc), AddrOut)
    8875          83 :         .addReg(AddrIn)
    8876             :         .addImm(0)
    8877          83 :         .addReg(Data)
    8878          83 :         .add(predOps(ARMCC::AL));
    8879        2449 :   } else if (IsThumb1) {
    8880             :     // store + update AddrIn
    8881        2763 :     BuildMI(*BB, Pos, dl, TII->get(StOpc))
    8882         921 :         .addReg(Data)
    8883         921 :         .addReg(AddrIn)
    8884             :         .addImm(0)
    8885         921 :         .add(predOps(ARMCC::AL));
    8886        2763 :     BuildMI(*BB, Pos, dl, TII->get(ARM::tADDi8), AddrOut)
    8887         921 :         .add(t1CondCodeOp())
    8888         921 :         .addReg(AddrIn)
    8889         921 :         .addImm(StSize)
    8890         921 :         .add(predOps(ARMCC::AL));
    8891        1528 :   } else if (IsThumb2) {
    8892        1536 :     BuildMI(*BB, Pos, dl, TII->get(StOpc), AddrOut)
    8893         512 :         .addReg(Data)
    8894         512 :         .addReg(AddrIn)
    8895         512 :         .addImm(StSize)
    8896         512 :         .add(predOps(ARMCC::AL));
    8897             :   } else { // arm
    8898        3048 :     BuildMI(*BB, Pos, dl, TII->get(StOpc), AddrOut)
    8899        1016 :         .addReg(Data)
    8900        1016 :         .addReg(AddrIn)
    8901        1016 :         .addReg(0)
    8902        1016 :         .addImm(StSize)
    8903        1016 :         .add(predOps(ARMCC::AL));
    8904             :   }
    8905        2532 : }
    8906             : 
    8907             : MachineBasicBlock *
    8908         360 : ARMTargetLowering::EmitStructByval(MachineInstr &MI,
    8909             :                                    MachineBasicBlock *BB) const {
    8910             :   // This pseudo instruction has 3 operands: dst, src, size
    8911             :   // We expand it to a loop if size > Subtarget->getMaxInlineSizeThreshold().
    8912             :   // Otherwise, we will generate unrolled scalar copies.
    8913         360 :   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
    8914         360 :   const BasicBlock *LLVM_BB = BB->getBasicBlock();
    8915         360 :   MachineFunction::iterator It = ++BB->getIterator();
    8916             : 
    8917         360 :   unsigned dest = MI.getOperand(0).getReg();
    8918         360 :   unsigned src = MI.getOperand(1).getReg();
    8919         360 :   unsigned SizeVal = MI.getOperand(2).getImm();
    8920         360 :   unsigned Align = MI.getOperand(3).getImm();
    8921             :   DebugLoc dl = MI.getDebugLoc();
    8922             : 
    8923         360 :   MachineFunction *MF = BB->getParent();
    8924         360 :   MachineRegisterInfo &MRI = MF->getRegInfo();
    8925             :   unsigned UnitSize = 0;
    8926             :   const TargetRegisterClass *TRC = nullptr;
    8927             :   const TargetRegisterClass *VecTRC = nullptr;
    8928             : 
    8929         360 :   bool IsThumb1 = Subtarget->isThumb1Only();
    8930             :   bool IsThumb2 = Subtarget->isThumb2();
    8931             :   bool IsThumb = Subtarget->isThumb();
    8932             : 
    8933         360 :   if (Align & 1) {
    8934             :     UnitSize = 1;
    8935         287 :   } else if (Align & 2) {
    8936             :     UnitSize = 2;
    8937             :   } else {
    8938             :     // Check whether we can use NEON instructions.
    8939         675 :     if (!MF->getFunction().hasFnAttribute(Attribute::NoImplicitFloat) &&
    8940         225 :         Subtarget->hasNEON()) {
    8941         102 :       if ((Align % 16 == 0) && SizeVal >= 16)
    8942             :         UnitSize = 16;
    8943          71 :       else if ((Align % 8 == 0) && SizeVal >= 8)
    8944             :         UnitSize = 8;
    8945             :     }
    8946             :     // Can't use NEON instructions.
    8947             :     if (UnitSize == 0)
    8948             :       UnitSize = 4;
    8949             :   }
    8950             : 
    8951             :   // Select the correct opcode and register class for unit size load/store
    8952             :   bool IsNeon = UnitSize >= 8;
    8953         360 :   TRC = IsThumb ? &ARM::tGPRRegClass : &ARM::GPRRegClass;
    8954         360 :   if (IsNeon)
    8955          57 :     VecTRC = UnitSize == 16 ? &ARM::DPairRegClass
    8956          26 :                             : UnitSize == 8 ? &ARM::DPRRegClass
    8957             :                                             : nullptr;
    8958             : 
    8959         360 :   unsigned BytesLeft = SizeVal % UnitSize;
    8960         360 :   unsigned LoopSize = SizeVal - BytesLeft;
    8961             : 
    8962         360 :   if (SizeVal <= Subtarget->getMaxInlineSizeThreshold()) {
    8963             :     // Use LDR and STR to copy.
    8964             :     // [scratch, srcOut] = LDR_POST(srcIn, UnitSize)
    8965             :     // [destOut] = STR_POST(scratch, destIn, UnitSize)
    8966             :     unsigned srcIn = src;
    8967             :     unsigned destIn = dest;
    8968        4197 :     for (unsigned i = 0; i < LoopSize; i+=UnitSize) {
    8969        2011 :       unsigned srcOut = MRI.createVirtualRegister(TRC);
    8970        2011 :       unsigned destOut = MRI.createVirtualRegister(TRC);
    8971        2011 :       unsigned scratch = MRI.createVirtualRegister(IsNeon ? VecTRC : TRC);
    8972        4022 :       emitPostLd(BB, MI, TII, dl, UnitSize, scratch, srcIn, srcOut,
    8973             :                  IsThumb1, IsThumb2);
    8974        2011 :       emitPostSt(BB, MI, TII, dl, UnitSize, scratch, destIn, destOut,
    8975             :                  IsThumb1, IsThumb2);
    8976             :       srcIn = srcOut;
    8977             :       destIn = destOut;
    8978             :     }
    8979             : 
    8980             :     // Handle the leftover bytes with LDRB and STRB.
    8981             :     // [scratch, srcOut] = LDRB_POST(srcIn, 1)
    8982             :     // [destOut] = STRB_POST(scratch, destIn, 1)
    8983         643 :     for (unsigned i = 0; i < BytesLeft; i++) {
    8984         234 :       unsigned srcOut = MRI.createVirtualRegister(TRC);
    8985         234 :       unsigned destOut = MRI.createVirtualRegister(TRC);
    8986         234 :       unsigned scratch = MRI.createVirtualRegister(TRC);
    8987         468 :       emitPostLd(BB, MI, TII, dl, 1, scratch, srcIn, srcOut,
    8988             :                  IsThumb1, IsThumb2);
    8989         234 :       emitPostSt(BB, MI, TII, dl, 1, scratch, destIn, destOut,
    8990             :                  IsThumb1, IsThumb2);
    8991             :       srcIn = srcOut;
    8992             :       destIn = destOut;
    8993             :     }
    8994         175 :     MI.eraseFromParent(); // The instruction is gone now.
    8995         175 :     return BB;
    8996             :   }
    8997             : 
    8998             :   // Expand the pseudo op to a loop.
    8999             :   // thisMBB:
    9000             :   //   ...
    9001             :   //   movw varEnd, # --> with thumb2
    9002             :   //   movt varEnd, #
    9003             :   //   ldrcp varEnd, idx --> without thumb2
    9004             :   //   fallthrough --> loopMBB
    9005             :   // loopMBB:
    9006             :   //   PHI varPhi, varEnd, varLoop
    9007             :   //   PHI srcPhi, src, srcLoop
    9008             :   //   PHI destPhi, dst, destLoop
    9009             :   //   [scratch, srcLoop] = LDR_POST(srcPhi, UnitSize)
    9010             :   //   [destLoop] = STR_POST(scratch, destPhi, UnitSize)
    9011             :   //   subs varLoop, varPhi, #UnitSize
    9012             :   //   bne loopMBB
    9013             :   //   fallthrough --> exitMBB
    9014             :   // exitMBB:
    9015             :   //   epilogue to handle left-over bytes
    9016             :   //   [scratch, srcOut] = LDRB_POST(srcLoop, 1)
    9017             :   //   [destOut] = STRB_POST(scratch, destLoop, 1)
    9018         185 :   MachineBasicBlock *loopMBB = MF->CreateMachineBasicBlock(LLVM_BB);
    9019         185 :   MachineBasicBlock *exitMBB = MF->CreateMachineBasicBlock(LLVM_BB);
    9020             :   MF->insert(It, loopMBB);
    9021             :   MF->insert(It, exitMBB);
    9022             : 
    9023             :   // Transfer the remainder of BB and its successor edges to exitMBB.
    9024             :   exitMBB->splice(exitMBB->begin(), BB,
    9025             :                   std::next(MachineBasicBlock::iterator(MI)), BB->end());
    9026         185 :   exitMBB->transferSuccessorsAndUpdatePHIs(BB);
    9027             : 
    9028             :   // Load an immediate to varEnd.
    9029         185 :   unsigned varEnd = MRI.createVirtualRegister(TRC);
    9030         185 :   if (Subtarget->useMovt(*MF)) {
    9031             :     unsigned Vtmp = varEnd;
    9032         138 :     if ((LoopSize & 0xFFFF0000) != 0)
    9033           0 :       Vtmp = MRI.createVirtualRegister(TRC);
    9034         138 :     BuildMI(BB, dl, TII->get(IsThumb ? ARM::t2MOVi16 : ARM::MOVi16), Vtmp)
    9035         138 :         .addImm(LoopSize & 0xFFFF)
    9036         138 :         .add(predOps(ARMCC::AL));
    9037             : 
    9038         138 :     if ((LoopSize & 0xFFFF0000) != 0)
    9039           0 :       BuildMI(BB, dl, TII->get(IsThumb ? ARM::t2MOVTi16 : ARM::MOVTi16), varEnd)
    9040           0 :           .addReg(Vtmp)
    9041           0 :           .addImm(LoopSize >> 16)
    9042           0 :           .add(predOps(ARMCC::AL));
    9043             :   } else {
    9044          47 :     MachineConstantPool *ConstantPool = MF->getConstantPool();
    9045          47 :     Type *Int32Ty = Type::getInt32Ty(MF->getFunction().getContext());
    9046          47 :     const Constant *C = ConstantInt::get(Int32Ty, LoopSize);
    9047             : 
    9048             :     // MachineConstantPool wants an explicit alignment.
    9049          47 :     unsigned Align = MF->getDataLayout().getPrefTypeAlignment(Int32Ty);
    9050          47 :     if (Align == 0)
    9051           0 :       Align = MF->getDataLayout().getTypeAllocSize(C->getType());
    9052          47 :     unsigned Idx = ConstantPool->getConstantPoolIndex(C, Align);
    9053             : 
    9054          47 :     if (IsThumb)
    9055         132 :       BuildMI(*BB, MI, dl, TII->get(ARM::tLDRpci))
    9056          44 :           .addReg(varEnd, RegState::Define)
    9057             :           .addConstantPoolIndex(Idx)
    9058          44 :           .add(predOps(ARMCC::AL));
    9059             :     else
    9060           9 :       BuildMI(*BB, MI, dl, TII->get(ARM::LDRcp))
    9061           3 :           .addReg(varEnd, RegState::Define)
    9062             :           .addConstantPoolIndex(Idx)
    9063             :           .addImm(0)
    9064           3 :           .add(predOps(ARMCC::AL));
    9065             :   }
    9066         185 :   BB->addSuccessor(loopMBB);
    9067             : 
    9068             :   // Generate the loop body:
    9069             :   //   varPhi = PHI(varLoop, varEnd)
    9070             :   //   srcPhi = PHI(srcLoop, src)
    9071             :   //   destPhi = PHI(destLoop, dst)
    9072             :   MachineBasicBlock *entryBB = BB;
    9073             :   BB = loopMBB;
    9074         185 :   unsigned varLoop = MRI.createVirtualRegister(TRC);
    9075         185 :   unsigned varPhi = MRI.createVirtualRegister(TRC);
    9076         185 :   unsigned srcLoop = MRI.createVirtualRegister(TRC);
    9077         185 :   unsigned srcPhi = MRI.createVirtualRegister(TRC);
    9078         185 :   unsigned destLoop = MRI.createVirtualRegister(TRC);
    9079         185 :   unsigned destPhi = MRI.createVirtualRegister(TRC);
    9080             : 
    9081         555 :   BuildMI(*BB, BB->begin(), dl, TII->get(ARM::PHI), varPhi)
    9082         185 :     .addReg(varLoop).addMBB(loopMBB)
    9083         185 :     .addReg(varEnd).addMBB(entryBB);
    9084         555 :   BuildMI(BB, dl, TII->get(ARM::PHI), srcPhi)
    9085         185 :     .addReg(srcLoop).addMBB(loopMBB)
    9086         185 :     .addReg(src).addMBB(entryBB);
    9087         555 :   BuildMI(BB, dl, TII->get(ARM::PHI), destPhi)
    9088         185 :     .addReg(destLoop).addMBB(loopMBB)
    9089         185 :     .addReg(dest).addMBB(entryBB);
    9090             : 
    9091             :   //   [scratch, srcLoop] = LDR_POST(srcPhi, UnitSize)
    9092             :   //   [destLoop] = STR_POST(scratch, destPhi, UnitSiz)
    9093         185 :   unsigned scratch = MRI.createVirtualRegister(IsNeon ? VecTRC : TRC);
    9094         185 :   emitPostLd(BB, BB->end(), TII, dl, UnitSize, scratch, srcPhi, srcLoop,
    9095             :              IsThumb1, IsThumb2);
    9096         185 :   emitPostSt(BB, BB->end(), TII, dl, UnitSize, scratch, destPhi, destLoop,
    9097             :              IsThumb1, IsThumb2);
    9098             : 
    9099             :   // Decrement loop variable by UnitSize.
    9100         185 :   if (IsThumb1) {
    9101         225 :     BuildMI(*BB, BB->end(), dl, TII->get(ARM::tSUBi8), varLoop)
    9102          75 :         .add(t1CondCodeOp())
    9103          75 :         .addReg(varPhi)
    9104          75 :         .addImm(UnitSize)
    9105          75 :         .add(predOps(ARMCC::AL));
    9106             :   } else {
    9107             :     MachineInstrBuilder MIB =
    9108             :         BuildMI(*BB, BB->end(), dl,
    9109         220 :                 TII->get(IsThumb2 ? ARM::t2SUBri : ARM::SUBri), varLoop);
    9110         110 :     MIB.addReg(varPhi)
    9111         110 :         .addImm(UnitSize)
    9112         110 :         .add(predOps(ARMCC::AL))
    9113         110 :         .add(condCodeOp());
    9114         220 :     MIB->getOperand(5).setReg(ARM::CPSR);
    9115         220 :     MIB->getOperand(5).setIsDef(true);
    9116             :   }
    9117         370 :   BuildMI(*BB, BB->end(), dl,
    9118         185 :           TII->get(IsThumb1 ? ARM::tBcc : IsThumb2 ? ARM::t2Bcc : ARM::Bcc))
    9119         185 :       .addMBB(loopMBB).addImm(ARMCC::NE).addReg(ARM::CPSR);
    9120             : 
    9121             :   // loopMBB can loop back to loopMBB or fall through to exitMBB.
    9122         185 :   BB->addSuccessor(loopMBB);
    9123         185 :   BB->addSuccessor(exitMBB);
    9124             : 
    9125             :   // Add epilogue to handle BytesLeft.
    9126             :   BB = exitMBB;
    9127         185 :   auto StartOfExit = exitMBB->begin();
    9128             : 
    9129             :   //   [scratch, srcOut] = LDRB_POST(srcLoop, 1)
    9130             :   //   [destOut] = STRB_POST(scratch, destLoop, 1)
    9131             :   unsigned srcIn = srcLoop;
    9132             :   unsigned destIn = destLoop;
    9133         389 :   for (unsigned i = 0; i < BytesLeft; i++) {
    9134         102 :     unsigned srcOut = MRI.createVirtualRegister(TRC);
    9135         102 :     unsigned destOut = MRI.createVirtualRegister(TRC);
    9136         102 :     unsigned scratch = MRI.createVirtualRegister(TRC);
    9137         102 :     emitPostLd(BB, StartOfExit, TII, dl, 1, scratch, srcIn, srcOut,
    9138             :                IsThumb1, IsThumb2);
    9139         102 :     emitPostSt(BB, StartOfExit, TII, dl, 1, scratch, destIn, destOut,
    9140             :                IsThumb1, IsThumb2);
    9141             :     srcIn = srcOut;
    9142             :     destIn = destOut;
    9143             :   }
    9144             : 
    9145         185 :   MI.eraseFromParent(); // The instruction is gone now.
    9146         185 :   return BB;
    9147             : }
    9148             : 
    9149             : MachineBasicBlock *
    9150           7 : ARMTargetLowering::EmitLowered__chkstk(MachineInstr &MI,
    9151             :                                        MachineBasicBlock *MBB) const {
    9152           7 :   const TargetMachine &TM = getTargetMachine();
    9153           7 :   const TargetInstrInfo &TII = *Subtarget->getInstrInfo();
    9154             :   DebugLoc DL = MI.getDebugLoc();
    9155             : 
    9156             :   assert(Subtarget->isTargetWindows() &&
    9157             :          "__chkstk is only supported on Windows");
    9158             :   assert(Subtarget->isThumb2() && "Windows on ARM requires Thumb-2 mode");
    9159             : 
    9160             :   // __chkstk takes the number of words to allocate on the stack in R4, and
    9161             :   // returns the stack adjustment in number of bytes in R4.  This will not
    9162             :   // clober any other registers (other than the obvious lr).
    9163             :   //
    9164             :   // Although, technically, IP should be considered a register which may be
    9165             :   // clobbered, the call itself will not touch it.  Windows on ARM is a pure
    9166             :   // thumb-2 environment, so there is no interworking required.  As a result, we
    9167             :   // do not expect a veneer to be emitted by the linker, clobbering IP.
    9168             :   //
    9169             :   // Each module receives its own copy of __chkstk, so no import thunk is
    9170             :   // required, again, ensuring that IP is not clobbered.
    9171             :   //
    9172             :   // Finally, although some linkers may theoretically provide a trampoline for
    9173             :   // out of range calls (which is quite common due to a 32M range limitation of
    9174             :   // branches for Thumb), we can generate the long-call version via
    9175             :   // -mcmodel=large, alleviating the need for the trampoline which may clobber
    9176             :   // IP.
    9177             : 
    9178           7 :   switch (TM.getCodeModel()) {
    9179           6 :   case CodeModel::Small:
    9180             :   case CodeModel::Medium:
    9181             :   case CodeModel::Kernel:
    9182          18 :     BuildMI(*MBB, MI, DL, TII.get(ARM::tBL))
    9183           6 :         .add(predOps(ARMCC::AL))
    9184             :         .addExternalSymbol("__chkstk")
    9185           6 :         .addReg(ARM::R4, RegState::Implicit | RegState::Kill)
    9186           6 :         .addReg(ARM::R4, RegState::Implicit | RegState::Define)
    9187             :         .addReg(ARM::R12,
    9188           6 :                 RegState::Implicit | RegState::Define | RegState::Dead)
    9189           6 :         .addReg(ARM::CPSR,
    9190             :                 RegState::Implicit | RegState::Define | RegState::Dead);
    9191           6 :     break;
    9192           1 :   case CodeModel::Large: {
    9193           1 :     MachineRegisterInfo &MRI = MBB->getParent()->getRegInfo();
    9194           1 :     unsigned Reg = MRI.createVirtualRegister(&ARM::rGPRRegClass);
    9195             : 
    9196           3 :     BuildMI(*MBB, MI, DL, TII.get(ARM::t2MOVi32imm), Reg)
    9197             :       .addExternalSymbol("__chkstk");
    9198           3 :     BuildMI(*MBB, MI, DL, TII.get(ARM::tBLXr))
    9199           1 :         .add(predOps(ARMCC::AL))
    9200           1 :         .addReg(Reg, RegState::Kill)
    9201           1 :         .addReg(ARM::R4, RegState::Implicit | RegState::Kill)
    9202           1 :         .addReg(ARM::R4, RegState::Implicit | RegState::Define)
    9203             :         .addReg(ARM::R12,
    9204           1 :                 RegState::Implicit | RegState::Define | RegState::Dead)
    9205           1 :         .addReg(ARM::CPSR,
    9206             :                 RegState::Implicit | RegState::Define | RegState::Dead);
    9207           1 :     break;
    9208             :   }
    9209             :   }
    9210             : 
    9211          21 :   BuildMI(*MBB, MI, DL, TII.get(ARM::t2SUBrr), ARM::SP)
    9212           7 :       .addReg(ARM::SP, RegState::Kill)
    9213           7 :       .addReg(ARM::R4, RegState::Kill)
    9214             :       .setMIFlags(MachineInstr::FrameSetup)
    9215           7 :       .add(predOps(ARMCC::AL))
    9216           7 :       .add(condCodeOp());
    9217             : 
    9218           7 :   MI.eraseFromParent();
    9219           7 :   return MBB;
    9220             : }
    9221             : 
    9222             : MachineBasicBlock *
    9223          58 : ARMTargetLowering::EmitLowered__dbzchk(MachineInstr &MI,
    9224             :                                        MachineBasicBlock *MBB) const {
    9225             :   DebugLoc DL = MI.getDebugLoc();
    9226          58 :   MachineFunction *MF = MBB->getParent();
    9227          58 :   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
    9228             : 
    9229          58 :   MachineBasicBlock *ContBB = MF->CreateMachineBasicBlock();
    9230          58 :   MF->insert(++MBB->getIterator(), ContBB);
    9231             :   ContBB->splice(ContBB->begin(), MBB,
    9232             :                  std::next(MachineBasicBlock::iterator(MI)), MBB->end());
    9233          58 :   ContBB->transferSuccessorsAndUpdatePHIs(MBB);
    9234          58 :   MBB->addSuccessor(ContBB);
    9235             : 
    9236          58 :   MachineBasicBlock *TrapBB = MF->CreateMachineBasicBlock();
    9237          58 :   BuildMI(TrapBB, DL, TII->get(ARM::t__brkdiv0));
    9238             :   MF->push_back(TrapBB);
    9239          58 :   MBB->addSuccessor(TrapBB);
    9240             : 
    9241         174 :   BuildMI(*MBB, MI, DL, TII->get(ARM::tCMPi8))
    9242          58 :       .addReg(MI.getOperand(0).getReg())
    9243             :       .addImm(0)
    9244          58 :       .add(predOps(ARMCC::AL));
    9245         174 :   BuildMI(*MBB, MI, DL, TII->get(ARM::t2Bcc))
    9246             :       .addMBB(TrapBB)
    9247             :       .addImm(ARMCC::EQ)
    9248          58 :       .addReg(ARM::CPSR);
    9249             : 
    9250          58 :   MI.eraseFromParent();
    9251          58 :   return ContBB;
    9252             : }
    9253             : 
    9254             : MachineBasicBlock *
    9255         579 : ARMTargetLowering::EmitInstrWithCustomInserter(MachineInstr &MI,
    9256             :                                                MachineBasicBlock *BB) const {
    9257         579 :   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
    9258             :   DebugLoc dl = MI.getDebugLoc();
    9259         579 :   bool isThumb2 = Subtarget->isThumb2();
    9260        1158 :   switch (MI.getOpcode()) {
    9261           0 :   default: {
    9262           0 :     MI.print(errs());
    9263           0 :     llvm_unreachable("Unexpected instr type to insert");
    9264             :   }
    9265             : 
    9266             :   // Thumb1 post-indexed loads are really just single-register LDMs.
    9267           3 :   case ARM::tLDR_postidx: {
    9268           3 :     MachineOperand Def(MI.getOperand(1));
    9269           6 :     BuildMI(*BB, MI, dl, TII->get(ARM::tLDMIA_UPD))
    9270             :         .add(Def)  // Rn_wb
    9271           3 :         .add(MI.getOperand(2))  // Rn
    9272           3 :         .add(MI.getOperand(3))  // PredImm
    9273           3 :         .add(MI.getOperand(4))  // PredReg
    9274           3 :         .add(MI.getOperand(0)); // Rt
    9275           3 :     MI.eraseFromParent();
    9276             :     return BB;
    9277             :   }
    9278             : 
    9279             :   // The Thumb2 pre-indexed stores have the same MI operands, they just
    9280             :   // define them differently in the .td files from the isel patterns, so
    9281             :   // they need pseudos.
    9282           4 :   case ARM::t2STR_preidx:
    9283           4 :     MI.setDesc(TII->get(ARM::t2STR_PRE));
    9284           4 :     return BB;
    9285           0 :   case ARM::t2STRB_preidx:
    9286           0 :     MI.setDesc(TII->get(ARM::t2STRB_PRE));
    9287           0 :     return BB;
    9288           1 :   case ARM::t2STRH_preidx:
    9289           1 :     MI.setDesc(TII->get(ARM::t2STRH_PRE));
    9290           1 :     return BB;
    9291             : 
    9292          10 :   case ARM::STRi_preidx:
    9293             :   case ARM::STRBi_preidx: {
    9294          10 :     unsigned NewOpc = MI.getOpcode() == ARM::STRi_preidx ? ARM::STR_PRE_IMM
    9295             :                                                          : ARM::STRB_PRE_IMM;
    9296             :     // Decode the offset.
    9297          10 :     unsigned Offset = MI.getOperand(4).getImm();
    9298             :     bool isSub = ARM_AM::getAM2Op(Offset) == ARM_AM::sub;
    9299             :     Offset = ARM_AM::getAM2Offset(Offset);
    9300             :     if (isSub)
    9301           0 :       Offset = -Offset;
    9302             : 
    9303          10 :     MachineMemOperand *MMO = *MI.memoperands_begin();
    9304          20 :     BuildMI(*BB, MI, dl, TII->get(NewOpc))
    9305          10 :         .add(MI.getOperand(0)) // Rn_wb
    9306          10 :         .add(MI.getOperand(1)) // Rt
    9307          10 :         .add(MI.getOperand(2)) // Rn
    9308          10 :         .addImm(Offset)        // offset (skip GPR==zero_reg)
    9309          10 :         .add(MI.getOperand(5)) // pred
    9310          10 :         .add(MI.getOperand(6))
    9311             :         .addMemOperand(MMO);
    9312          10 :     MI.eraseFromParent();
    9313          10 :     return BB;
    9314             :   }
    9315           3 :   case ARM::STRr_preidx:
    9316             :   case ARM::STRBr_preidx:
    9317             :   case ARM::STRH_preidx: {
    9318             :     unsigned NewOpc;
    9319           3 :     switch (MI.getOpcode()) {
    9320           0 :     default: llvm_unreachable("unexpected opcode!");
    9321             :     case ARM::STRr_preidx: NewOpc = ARM::STR_PRE_REG; break;
    9322           0 :     case ARM::STRBr_preidx: NewOpc = ARM::STRB_PRE_REG; break;
    9323           1 :     case ARM::STRH_preidx: NewOpc = ARM::STRH_PRE; break;
    9324             :     }
    9325           6 :     MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(NewOpc));
    9326          45 :     for (unsigned i = 0; i < MI.getNumOperands(); ++i)
    9327          21 :       MIB.add(MI.getOperand(i));
    9328           3 :     MI.eraseFromParent();
    9329             :     return BB;
    9330             :   }
    9331             : 
    9332          84 :   case ARM::tMOVCCr_pseudo: {
    9333             :     // To "insert" a SELECT_CC instruction, we actually have to insert the
    9334             :     // diamond control-flow pattern.  The incoming instruction knows the
    9335             :     // destination vreg to set, the condition code register to branch on, the
    9336             :     // true/false values to select between, and a branch opcode to use.
    9337          84 :     const BasicBlock *LLVM_BB = BB->getBasicBlock();
    9338          84 :     MachineFunction::iterator It = ++BB->getIterator();
    9339             : 
    9340             :     //  thisMBB:
    9341             :     //  ...
    9342             :     //   TrueVal = ...
    9343             :     //   cmpTY ccX, r1, r2
    9344             :     //   bCC copy1MBB
    9345             :     //   fallthrough --> copy0MBB
    9346             :     MachineBasicBlock *thisMBB  = BB;
    9347          84 :     MachineFunction *F = BB->getParent();
    9348          84 :     MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
    9349          84 :     MachineBasicBlock *sinkMBB  = F->CreateMachineBasicBlock(LLVM_BB);
    9350             :     F->insert(It, copy0MBB);
    9351             :     F->insert(It, sinkMBB);
    9352             : 
    9353             :     // Transfer the remainder of BB and its successor edges to sinkMBB.
    9354             :     sinkMBB->splice(sinkMBB->begin(), BB,
    9355             :                     std::next(MachineBasicBlock::iterator(MI)), BB->end());
    9356          84 :     sinkMBB->transferSuccessorsAndUpdatePHIs(BB);
    9357             : 
    9358          84 :     BB->addSuccessor(copy0MBB);
    9359          84 :     BB->addSuccessor(sinkMBB);
    9360             : 
    9361         252 :     BuildMI(BB, dl, TII->get(ARM::tBcc))
    9362             :         .addMBB(sinkMBB)
    9363          84 :         .addImm(MI.getOperand(3).getImm())
    9364          84 :         .addReg(MI.getOperand(4).getReg());
    9365             : 
    9366             :     //  copy0MBB:
    9367             :     //   %FalseValue = ...
    9368             :     //   # fallthrough to sinkMBB
    9369             :     BB = copy0MBB;
    9370             : 
    9371             :     // Update machine-CFG edges
    9372          84 :     BB->addSuccessor(sinkMBB);
    9373             : 
    9374             :     //  sinkMBB:
    9375             :     //   %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
    9376             :     //  ...
    9377             :     BB = sinkMBB;
    9378         252 :     BuildMI(*BB, BB->begin(), dl, TII->get(ARM::PHI), MI.getOperand(0).getReg())
    9379          84 :         .addReg(MI.getOperand(1).getReg())
    9380             :         .addMBB(copy0MBB)
    9381          84 :         .addReg(MI.getOperand(2).getReg())
    9382             :         .addMBB(thisMBB);
    9383             : 
    9384          84 :     MI.eraseFromParent(); // The pseudo instruction is gone now.
    9385             :     return BB;
    9386             :   }
    9387             : 
    9388             :   case ARM::BCCi64:
    9389             :   case ARM::BCCZi64: {
    9390             :     // If there is an unconditional branch to the other successor, remove it.
    9391             :     BB->erase(std::next(MachineBasicBlock::iterator(MI)), BB->end());
    9392             : 
    9393             :     // Compare both parts that make up the double comparison separately for
    9394             :     // equality.
    9395           1 :     bool RHSisZero = MI.getOpcode() == ARM::BCCZi64;
    9396             : 
    9397           1 :     unsigned LHS1 = MI.getOperand(1).getReg();
    9398           1 :     unsigned LHS2 = MI.getOperand(2).getReg();
    9399           1 :     if (RHSisZero) {
    9400           3 :       BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri))
    9401           1 :           .addReg(LHS1)
    9402             :           .addImm(0)
    9403           1 :           .add(predOps(ARMCC::AL));
    9404           3 :       BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri))
    9405           1 :         .addReg(LHS2).addImm(0)
    9406           1 :         .addImm(ARMCC::EQ).addReg(ARM::CPSR);
    9407             :     } else {
    9408           0 :       unsigned RHS1 = MI.getOperand(3).getReg();
    9409           0 :       unsigned RHS2 = MI.getOperand(4).getReg();
    9410           0 :       BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPrr : ARM::CMPrr))
    9411           0 :           .addReg(LHS1)
    9412           0 :           .addReg(RHS1)
    9413           0 :           .add(predOps(ARMCC::AL));
    9414           0 :       BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPrr : ARM::CMPrr))
    9415           0 :         .addReg(LHS2).addReg(RHS2)
    9416           0 :         .addImm(ARMCC::EQ).addReg(ARM::CPSR);
    9417             :     }
    9418             : 
    9419           2 :     MachineBasicBlock *destMBB = MI.getOperand(RHSisZero ? 3 : 5).getMBB();
    9420             :     MachineBasicBlock *exitMBB = OtherSucc(BB, destMBB);
    9421           1 :     if (MI.getOperand(0).getImm() == ARMCC::NE)
    9422             :       std::swap(destMBB, exitMBB);
    9423             : 
    9424           3 :     BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc))
    9425           1 :       .addMBB(destMBB).addImm(ARMCC::EQ).addReg(ARM::CPSR);
    9426           1 :     if (isThumb2)
    9427           0 :       BuildMI(BB, dl, TII->get(ARM::t2B))
    9428             :           .addMBB(exitMBB)
    9429           0 :           .add(predOps(ARMCC::AL));
    9430             :     else
    9431           1 :       BuildMI(BB, dl, TII->get(ARM::B)) .addMBB(exitMBB);
    9432             : 
    9433           1 :     MI.eraseFromParent(); // The pseudo instruction is gone now.
    9434             :     return BB;
    9435             :   }
    9436             : 
    9437             :   case ARM::Int_eh_sjlj_setjmp:
    9438             :   case ARM::Int_eh_sjlj_setjmp_nofp:
    9439             :   case ARM::tInt_eh_sjlj_setjmp:
    9440             :   case ARM::t2Int_eh_sjlj_setjmp:
    9441             :   case ARM::t2Int_eh_sjlj_setjmp_nofp:
    9442             :     return BB;
    9443             : 
    9444          32 :   case ARM::Int_eh_sjlj_setup_dispatch:
    9445          32 :     EmitSjLjDispatchBlock(MI, BB);
    9446          32 :     return BB;
    9447             : 
    9448           8 :   case ARM::ABS:
    9449             :   case ARM::t2ABS: {
    9450             :     // To insert an ABS instruction, we have to insert the
    9451             :     // diamond control-flow pattern.  The incoming instruction knows the
    9452             :     // source vreg to test against 0, the destination vreg to set,
    9453             :     // the condition code register to branch on, the
    9454             :     // true/false values to select between, and a branch opcode to use.
    9455             :     // It transforms
    9456             :     //     V1 = ABS V0
    9457             :     // into
    9458             :     //     V2 = MOVS V0
    9459             :     //     BCC                      (branch to SinkBB if V0 >= 0)
    9460             :     //     RSBBB: V3 = RSBri V2, 0  (compute ABS if V2 < 0)
    9461             :     //     SinkBB: V1 = PHI(V2, V3)
    9462           8 :     const BasicBlock *LLVM_BB = BB->getBasicBlock();
    9463           8 :     MachineFunction::iterator BBI = ++BB->getIterator();
    9464           8 :     MachineFunction *Fn = BB->getParent();
    9465           8 :     MachineBasicBlock *RSBBB = Fn->CreateMachineBasicBlock(LLVM_BB);
    9466           8 :     MachineBasicBlock *SinkBB  = Fn->CreateMachineBasicBlock(LLVM_BB);
    9467             :     Fn->insert(BBI, RSBBB);
    9468             :     Fn->insert(BBI, SinkBB);
    9469             : 
    9470           8 :     unsigned int ABSSrcReg = MI.getOperand(1).getReg();
    9471           8 :     unsigned int ABSDstReg = MI.getOperand(0).getReg();
    9472             :     bool ABSSrcKIll = MI.getOperand(1).isKill();
    9473           8 :     bool isThumb2 = Subtarget->isThumb2();
    9474           8 :     MachineRegisterInfo &MRI = Fn->getRegInfo();
    9475             :     // In Thumb mode S must not be specified if source register is the SP or
    9476             :     // PC and if destination register is the SP, so restrict register class
    9477             :     unsigned NewRsbDstReg =
    9478           8 :       MRI.createVirtualRegister(isThumb2 ? &ARM::rGPRRegClass : &ARM::GPRRegClass);
    9479             : 
    9480             :     // Transfer the remainder of BB and its successor edges to sinkMBB.
    9481             :     SinkBB->splice(SinkBB->begin(), BB,
    9482             :                    std::next(MachineBasicBlock::iterator(MI)), BB->end());
    9483           8 :     SinkBB->transferSuccessorsAndUpdatePHIs(BB);
    9484             : 
    9485           8 :     BB->addSuccessor(RSBBB);
    9486           8 :     BB->addSuccessor(SinkBB);
    9487             : 
    9488             :     // fall through to SinkMBB
    9489           8 :     RSBBB->addSuccessor(SinkBB);
    9490             : 
    9491             :     // insert a cmp at the end of BB
    9492          24 :     BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri))
    9493           8 :         .addReg(ABSSrcReg)
    9494             :         .addImm(0)
    9495           8 :         .add(predOps(ARMCC::AL));
    9496             : 
    9497             :     // insert a bcc with opposite CC to ARMCC::MI at the end of BB
    9498          16 :     BuildMI(BB, dl,
    9499           8 :       TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc)).addMBB(SinkBB)
    9500           8 :       .addImm(ARMCC::getOppositeCondition(ARMCC::MI)).addReg(ARM::CPSR);
    9501             : 
    9502             :     // insert rsbri in RSBBB
    9503             :     // Note: BCC and rsbri will be converted into predicated rsbmi
    9504             :     // by if-conversion pass
    9505          16 :     BuildMI(*RSBBB, RSBBB->begin(), dl,
    9506           8 :             TII->get(isThumb2 ? ARM::t2RSBri : ARM::RSBri), NewRsbDstReg)
    9507           8 :         .addReg(ABSSrcReg, ABSSrcKIll ? RegState::Kill : 0)
    9508             :         .addImm(0)
    9509           8 :         .add(predOps(ARMCC::AL))
    9510           8 :         .add(condCodeOp());
    9511             : 
    9512             :     // insert PHI in SinkBB,
    9513             :     // reuse ABSDstReg to not change uses of ABS instruction
    9514          16 :     BuildMI(*SinkBB, SinkBB->begin(), dl,
    9515           8 :       TII->get(ARM::PHI), ABSDstReg)
    9516           8 :       .addReg(NewRsbDstReg).addMBB(RSBBB)
    9517           8 :       .addReg(ABSSrcReg).addMBB(BB);
    9518             : 
    9519             :     // remove ABS instruction
    9520           8 :     MI.eraseFromParent();
    9521             : 
    9522             :     // return last added BB
    9523             :     return SinkBB;
    9524             :   }
    9525             :   case ARM::COPY_STRUCT_BYVAL_I32:
    9526             :     ++NumLoopByVals;
    9527         360 :     return EmitStructByval(MI, BB);
    9528           7 :   case ARM::WIN__CHKSTK:
    9529           7 :     return EmitLowered__chkstk(MI, BB);
    9530          58 :   case ARM::WIN__DBZCHK:
    9531          58 :     return EmitLowered__dbzchk(MI, BB);
    9532             :   }
    9533             : }
    9534             : 
    9535             : /// Attaches vregs to MEMCPY that it will use as scratch registers
    9536             : /// when it is expanded into LDM/STM. This is done as a post-isel lowering
    9537             : /// instead of as a custom inserter because we need the use list from the SDNode.
    9538          56 : static void attachMEMCPYScratchRegs(const ARMSubtarget *Subtarget,
    9539             :                                     MachineInstr &MI, const SDNode *Node) {
    9540          56 :   bool isThumb1 = Subtarget->isThumb1Only();
    9541             : 
    9542             :   DebugLoc DL = MI.getDebugLoc();
    9543          56 :   MachineFunction *MF = MI.getParent()->getParent();
    9544          56 :   MachineRegisterInfo &MRI = MF->getRegInfo();
    9545             :   MachineInstrBuilder MIB(*MF, MI);
    9546             : 
    9547             :   // If the new dst/src is unused mark it as dead.
    9548          56 :   if (!Node->hasAnyUseOfValue(0)) {
    9549          26 :     MI.getOperand(0).setIsDead(true);
    9550             :   }
    9551          56 :   if (!Node->hasAnyUseOfValue(1)) {
    9552          26 :     MI.getOperand(1).setIsDead(true);
    9553             :   }
    9554             : 
    9555             :   // The MEMCPY both defines and kills the scratch registers.
    9556         514 :   for (unsigned I = 0; I != MI.getOperand(4).getImm(); ++I) {
    9557         458 :     unsigned TmpReg = MRI.createVirtualRegister(isThumb1 ? &ARM::tGPRRegClass
    9558         229 :                                                          : &ARM::GPRRegClass);
    9559         229 :     MIB.addReg(TmpReg, RegState::Define|RegState::Dead);
    9560             :   }
    9561          56 : }
    9562             : 
    9563        1063 : void ARMTargetLowering::AdjustInstrPostInstrSelection(MachineInstr &MI,
    9564             :                                                       SDNode *Node) const {
    9565        2126 :   if (MI.getOpcode() == ARM::MEMCPY) {
    9566          56 :     attachMEMCPYScratchRegs(Subtarget, MI, Node);
    9567          56 :     return;
    9568             :   }
    9569             : 
    9570             :   const MCInstrDesc *MCID = &MI.getDesc();
    9571             :   // Adjust potentially 's' setting instructions after isel, i.e. ADC, SBC, RSB,
    9572             :   // RSC. Coming out of isel, they have an implicit CPSR def, but the optional
    9573             :   // operand is still set to noreg. If needed, set the optional operand's
    9574             :   // register to CPSR, and remove the redundant implicit def.
    9575             :   //
    9576             :   // e.g. ADCS (..., implicit-def CPSR) -> ADC (... opt:def CPSR).
    9577             : 
    9578             :   // Rename pseudo opcodes.
    9579        1007 :   unsigned NewOpc = convertAddSubFlagsOpcode(MI.getOpcode());
    9580             :   unsigned ccOutIdx;
    9581        1007 :   if (NewOpc) {
    9582         629 :     const ARMBaseInstrInfo *TII = Subtarget->getInstrInfo();
    9583         629 :     MCID = &TII->get(NewOpc);
    9584             : 
    9585             :     assert(MCID->getNumOperands() ==
    9586             :            MI.getDesc().getNumOperands() + 5 - MI.getDesc().getSize()
    9587             :         && "converted opcode should be the same except for cc_out"
    9588             :            " (and, on Thumb1, pred)");
    9589             : 
    9590             :     MI.setDesc(*MCID);
    9591             : 
    9592             :     // Add the optional cc_out operand
    9593         629 :     MI.addOperand(MachineOperand::CreateReg(0, /*isDef=*/true));
    9594             : 
    9595             :     // On Thumb1, move all input operands to the end, then add the predicate
    9596         629 :     if (Subtarget->isThumb1Only()) {
    9597        1144 :       for (unsigned c = MCID->getNumOperands() - 4; c--;) {
    9598        1144 :         MI.addOperand(MI.getOperand(1));
    9599         572 :         MI.RemoveOperand(1);
    9600             :       }
    9601             : 
    9602             :       // Restore the ties
    9603         286 :       for (unsigned i = MI.getNumOperands(); i--;) {
    9604        1576 :         const MachineOperand& op = MI.getOperand(i);
    9605        3118 :         if (op.isReg() && op.isUse()) {
    9606         684 :           int DefIdx = MCID->getOperandConstraint(i, MCOI::TIED_TO);
    9607             :           if (DefIdx != -1)
    9608         158 :             MI.tieOperands(DefIdx, i);
    9609             :         }
    9610             :       }
    9611             : 
    9612         286 :       MI.addOperand(MachineOperand::CreateImm(ARMCC::AL));
    9613         286 :       MI.addOperand(MachineOperand::CreateReg(0, /*isDef=*/false));
    9614             :       ccOutIdx = 1;
    9615             :     } else
    9616         686 :       ccOutIdx = MCID->getNumOperands() - 1;
    9617             :   } else
    9618         756 :     ccOutIdx = MCID->getNumOperands() - 1;
    9619             : 
    9620             :   // Any ARM instruction that sets the 's' bit should specify an optional
    9621             :   // "cc_out" operand in the last operand position.
    9622        1007 :   if (!MI.hasOptionalDef() || !MCID->OpInfo[ccOutIdx].isOptionalDef()) {
    9623             :     assert(!NewOpc && "Optional cc_out operand required");
    9624             :     return;
    9625             :   }
    9626             :   // Look for an implicit def of CPSR added by MachineInstr ctor. Remove it
    9627             :   // since we already have an optional CPSR def.
    9628             :   bool definesCPSR = false;
    9629             :   bool deadCPSR = false;
    9630        2014 :   for (unsigned i = MCID->getNumOperands(), e = MI.getNumOperands(); i != e;
    9631             :        ++i) {
    9632        1007 :     const MachineOperand &MO = MI.getOperand(i);
    9633        2014 :     if (MO.isReg() && MO.isDef() && MO.getReg() == ARM::CPSR) {
    9634             :       definesCPSR = true;
    9635        1007 :       if (MO.isDead())
    9636             :         deadCPSR = true;
    9637        1007 :       MI.RemoveOperand(i);
    9638        1007 :       break;
    9639             :     }
    9640             :   }
    9641        1007 :   if (!definesCPSR) {
    9642             :     assert(!NewOpc && "Optional cc_out operand required");
    9643             :     return;
    9644             :   }
    9645             :   assert(deadCPSR == !Node->hasAnyUseOfValue(1) && "inconsistent dead flag");
    9646        1007 :   if (deadCPSR) {
    9647             :     assert(!MI.getOperand(ccOutIdx).getReg() &&
    9648             :            "expect uninitialized optional cc_out operand");
    9649             :     // Thumb1 instructions must have the S bit even if the CPSR is dead.
    9650         399 :     if (!Subtarget->isThumb1Only())
    9651             :       return;
    9652             :   }
    9653             : 
    9654             :   // If this instruction was defined with an optional CPSR def and its dag node
    9655             :   // had a live implicit CPSR def, then activate the optional CPSR def.
    9656         742 :   MachineOperand &MO = MI.getOperand(ccOutIdx);
    9657         742 :   MO.setReg(ARM::CPSR);
    9658         742 :   MO.setIsDef(true);
    9659             : }
    9660             : 
    9661             : //===----------------------------------------------------------------------===//
    9662             : //                           ARM Optimization Hooks
    9663             : //===----------------------------------------------------------------------===//
    9664             : 
    9665             : // Helper function that checks if N is a null or all ones constant.
    9666             : static inline bool isZeroOrAllOnes(SDValue N, bool AllOnes) {
    9667         217 :   return AllOnes ? isAllOnesConstant(N) : isNullConstant(N);
    9668             : }
    9669             : 
    9670             : // Return true if N is conditionally 0 or all ones.
    9671             : // Detects these expressions where cc is an i1 value:
    9672             : //
    9673             : //   (select cc 0, y)   [AllOnes=0]
    9674             : //   (select cc y, 0)   [AllOnes=0]
    9675             : //   (zext cc)          [AllOnes=0]
    9676             : //   (sext cc)          [AllOnes=0/1]
    9677             : //   (select cc -1, y)  [AllOnes=1]
    9678             : //   (select cc y, -1)  [AllOnes=1]
    9679             : //
    9680             : // Invert is set when N is the null/all ones constant when CC is false.
    9681             : // OtherOp is set to the alternative value of N.
    9682       31512 : static bool isConditionalZeroOrAllOnes(SDNode *N, bool AllOnes,
    9683             :                                        SDValue &CC, bool &Invert,
    9684             :                                        SDValue &OtherOp,
    9685             :                                        SelectionDAG &DAG) {
    9686       63024 :   switch (N->getOpcode()) {
    9687             :   default: return false;
    9688         116 :   case ISD::SELECT: {
    9689         116 :     CC = N->getOperand(0);
    9690         116 :     SDValue N1 = N->getOperand(1);
    9691         116 :     SDValue N2 = N->getOperand(2);
    9692         116 :     if (isZeroOrAllOnes(N1, AllOnes)) {
    9693          15 :       Invert = false;
    9694          15 :       OtherOp = N2;
    9695          15 :       return true;
    9696             :     }
    9697         101 :     if (isZeroOrAllOnes(N2, AllOnes)) {
    9698          24 :       Invert = true;
    9699          24 :       OtherOp = N1;
    9700          24 :       return true;
    9701             :     }
    9702             :     return false;
    9703             :   }
    9704         251 :   case ISD::ZERO_EXTEND:
    9705             :     // (zext cc) can never be the all ones value.
    9706         251 :     if (AllOnes)
    9707             :       return false;
    9708             :     LLVM_FALLTHROUGH;
    9709             :   case ISD::SIGN_EXTEND: {
    9710             :     SDLoc dl(N);
    9711         864 :     EVT VT = N->getValueType(0);
    9712         432 :     CC = N->getOperand(0);
    9713         449 :     if (CC.getValueType() != MVT::i1 || CC.getOpcode() != ISD::SETCC)
    9714             :       return false;
    9715          13 :     Invert = !AllOnes;
    9716          13 :     if (AllOnes)
    9717             :       // When looking for an AllOnes constant, N is an sext, and the 'other'
    9718             :       // value is 0.
    9719           0 :       OtherOp = DAG.getConstant(0, dl, VT);
    9720          13 :     else if (N->getOpcode() == ISD::ZERO_EXTEND)
    9721             :       // When looking for a 0 constant, N can be zext or sext.
    9722          13 :       OtherOp = DAG.getConstant(1, dl, VT);
    9723             :     else
    9724           0 :       OtherOp = DAG.getConstant(APInt::getAllOnesValue(VT.getSizeInBits()), dl,
    9725             :                                 VT);
    9726             :     return true;
    9727             :   }
    9728             :   }
    9729             : }
    9730             : 
    9731             : // Combine a constant select operand into its use:
    9732             : //
    9733             : //   (add (select cc, 0, c), x)  -> (select cc, x, (add, x, c))
    9734             : //   (sub x, (select cc, 0, c))  -> (select cc, x, (sub, x, c))
    9735             : //   (and (select cc, -1, c), x) -> (select cc, x, (and, x, c))  [AllOnes=1]
    9736             : //   (or  (select cc, 0, c), x)  -> (select cc, x, (or, x, c))
    9737             : //   (xor (select cc, 0, c), x)  -> (select cc, x, (xor, x, c))
    9738             : //
    9739             : // The transform is rejected if the select doesn't have a constant operand that
    9740             : // is null, or all ones when AllOnes is set.
    9741             : //
    9742             : // Also recognize sext/zext from i1:
    9743             : //
    9744             : //   (add (zext cc), x) -> (select cc (add x, 1), x)
    9745             : //   (add (sext cc), x) -> (select cc (add x, -1), x)
    9746             : //
    9747             : // These transformations eventually create predicated instructions.
    9748             : //
    9749             : // @param N       The node to transform.
    9750             : // @param Slct    The N operand that is a select.
    9751             : // @param OtherOp The other N operand (x above).
    9752             : // @param DCI     Context.
    9753             : // @param AllOnes Require the select constant to be all ones instead of null.
    9754             : // @returns The new node, or SDValue() on failure.
    9755             : static
    9756       31512 : SDValue combineSelectAndUse(SDNode *N, SDValue Slct, SDValue OtherOp,
    9757             :                             TargetLowering::DAGCombinerInfo &DCI,
    9758             :                             bool AllOnes = false) {
    9759       31512 :   SelectionDAG &DAG = DCI.DAG;
    9760       63024 :   EVT VT = N->getValueType(0);
    9761       31512 :   SDValue NonConstantVal;
    9762       31512 :   SDValue CCOp;
    9763             :   bool SwapSelectOps;
    9764       31512 :   if (!isConditionalZeroOrAllOnes(Slct.getNode(), AllOnes, CCOp, SwapSelectOps,
    9765             :                                   NonConstantVal, DAG))
    9766       31460 :     return SDValue();
    9767             : 
    9768             :   // Slct is now know to be the desired identity constant when CC is true.
    9769          52 :   SDValue TrueVal = OtherOp;
    9770          52 :   SDValue FalseVal = DAG.getNode(N->getOpcode(), SDLoc(N), VT,
    9771         156 :                                  OtherOp, NonConstantVal);
    9772             :   // Unless SwapSelectOps says CC should be false.
    9773          52 :   if (SwapSelectOps)
    9774             :     std::swap(TrueVal, FalseVal);
    9775             : 
    9776          52 :   return DAG.getNode(ISD::SELECT, SDLoc(N), VT,
    9777         104 :                      CCOp, TrueVal, FalseVal);
    9778             : }
    9779             : 
    9780             : // Attempt combineSelectAndUse on each operand of a commutative operator N.
    9781             : static
    9782        6930 : SDValue combineSelectAndUseCommutative(SDNode *N, bool AllOnes,
    9783             :                                        TargetLowering::DAGCombinerInfo &DCI) {
    9784        6930 :   SDValue N0 = N->getOperand(0);
    9785        6930 :   SDValue N1 = N->getOperand(1);
    9786             :   if (N0.getNode()->hasOneUse())
    9787        5230 :     if (SDValue Result = combineSelectAndUse(N, N0, N1, DCI, AllOnes))
    9788          12 :       return Result;
    9789             :   if (N1.getNode()->hasOneUse())
    9790        5108 :     if (SDValue Result = combineSelectAndUse(N, N1, N0, DCI, AllOnes))
    9791           2 :       return Result;
    9792        6916 :   return SDValue();
    9793             : }
    9794             : 
    9795             : static bool IsVUZPShuffleNode(SDNode *N) {
    9796             :   // VUZP shuffle node.
    9797       80548 :   if (N->getOpcode() == ARMISD::VUZP)
    9798             :     return true;
    9799             : 
    9800             :   // "VUZP" on i32 is an alias for VTRN.
    9801       40257 :   if (N->getOpcode() == ARMISD::VTRN && N->getValueType(0) == MVT::v2i32)
    9802             :     return true;
    9803             : 
    9804             :   return false;
    9805             : }
    9806             : 
    9807       40182 : static SDValue AddCombineToVPADD(SDNode *N, SDValue N0, SDValue N1,
    9808             :                                  TargetLowering::DAGCombinerInfo &DCI,
    9809             :                                  const ARMSubtarget *Subtarget) {
    9810             :   // Look for ADD(VUZP.0, VUZP.1).
    9811          14 :   if (!IsVUZPShuffleNode(N0.getNode()) || N0.getNode() != N1.getNode() ||
    9812             :       N0 == N1)
    9813       40168 :    return SDValue();
    9814             : 
    9815             :   // Make sure the ADD is a 64-bit add; there is no 128-bit VPADD.
    9816          28 :   if (!N->getValueType(0).is64BitVector())
    9817          10 :     return SDValue();
    9818             : 
    9819             :   // Generate vpadd.
    9820           4 :   SelectionDAG &DAG = DCI.DAG;
    9821             :   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
    9822             :   SDLoc dl(N);
    9823             :   SDNode *Unzip = N0.getNode();
    9824           8 :   EVT VT = N->getValueType(0);
    9825             : 
    9826             :   SmallVector<SDValue, 8> Ops;
    9827           4 :   Ops.push_back(DAG.getConstant(Intrinsic::arm_neon_vpadd, dl,
    9828           8 :                                 TLI.getPointerTy(DAG.getDataLayout())));
    9829           8 :   Ops.push_back(Unzip->getOperand(0));
    9830           8 :   Ops.push_back(Unzip->getOperand(1));
    9831             : 
    9832           4 :   return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT, Ops);
    9833             : }
    9834             : 
    9835       40178 : static SDValue AddCombineVUZPToVPADDL(SDNode *N, SDValue N0, SDValue N1,
    9836             :                                       TargetLowering::DAGCombinerInfo &DCI,
    9837             :                                       const ARMSubtarget *Subtarget) {
    9838             :   // Check for two extended operands.
    9839         184 :   if (!(N0.getOpcode() == ISD::SIGN_EXTEND &&
    9840       80327 :         N1.getOpcode() == ISD::SIGN_EXTEND) &&
    9841         206 :       !(N0.getOpcode() == ISD::ZERO_EXTEND &&
    9842             :         N1.getOpcode() == ISD::ZERO_EXTEND))
    9843       40086 :     return SDValue();
    9844             : 
    9845          92 :   SDValue N00 = N0.getOperand(0);
    9846          92 :   SDValue N10 = N1.getOperand(0);
    9847             : 
    9848             :   // Look for ADD(SEXT(VUZP.0), SEXT(VUZP.1))
    9849           6 :   if (!IsVUZPShuffleNode(N00.getNode()) || N00.getNode() != N10.getNode() ||
    9850             :       N00 == N10)
    9851          86 :     return SDValue();