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 "ARMCallingConv.h" 17 #include "ARMConstantPoolValue.h" 18 #include "ARMMachineFunctionInfo.h" 19 #include "ARMPerfectShuffle.h" 20 #include "ARMSubtarget.h" 21 #include "ARMTargetMachine.h" 22 #include "ARMTargetObjectFile.h" 23 #include "MCTargetDesc/ARMAddressingModes.h" 24 #include "llvm/ADT/Statistic.h" 25 #include "llvm/ADT/StringExtras.h" 26 #include "llvm/ADT/StringSwitch.h" 27 #include "llvm/CodeGen/CallingConvLower.h" 28 #include "llvm/CodeGen/IntrinsicLowering.h" 29 #include "llvm/CodeGen/MachineBasicBlock.h" 30 #include "llvm/CodeGen/MachineFrameInfo.h" 31 #include "llvm/CodeGen/MachineFunction.h" 32 #include "llvm/CodeGen/MachineInstrBuilder.h" 33 #include "llvm/CodeGen/MachineJumpTableInfo.h" 34 #include "llvm/CodeGen/MachineModuleInfo.h" 35 #include "llvm/CodeGen/MachineRegisterInfo.h" 36 #include "llvm/CodeGen/SelectionDAG.h" 37 #include "llvm/IR/CallingConv.h" 38 #include "llvm/IR/Constants.h" 39 #include "llvm/IR/Function.h" 40 #include "llvm/IR/GlobalValue.h" 41 #include "llvm/IR/IRBuilder.h" 42 #include "llvm/IR/Instruction.h" 43 #include "llvm/IR/Instructions.h" 44 #include "llvm/IR/IntrinsicInst.h" 45 #include "llvm/IR/Intrinsics.h" 46 #include "llvm/IR/Type.h" 47 #include "llvm/MC/MCSectionMachO.h" 48 #include "llvm/Support/CommandLine.h" 49 #include "llvm/Support/Debug.h" 50 #include "llvm/Support/ErrorHandling.h" 51 #include "llvm/Support/MathExtras.h" 52 #include "llvm/Support/raw_ostream.h" 53 #include "llvm/Target/TargetOptions.h" 54 #include <utility> 55 using namespace llvm; 56 57 #define DEBUG_TYPE "arm-isel" 58 59 STATISTIC(NumTailCalls, "Number of tail calls"); 60 STATISTIC(NumMovwMovt, "Number of GAs materialized with movw + movt"); 61 STATISTIC(NumLoopByVals, "Number of loops generated for byval arguments"); 62 63 static cl::opt<bool> 64 ARMInterworking("arm-interworking", cl::Hidden, 65 cl::desc("Enable / disable ARM interworking (for debugging only)"), 66 cl::init(true)); 67 68 namespace { 69 class ARMCCState : public CCState { 70 public: 71 ARMCCState(CallingConv::ID CC, bool isVarArg, MachineFunction &MF, 72 SmallVectorImpl<CCValAssign> &locs, LLVMContext &C, 73 ParmContext PC) 74 : CCState(CC, isVarArg, MF, locs, C) { 75 assert(((PC == Call) || (PC == Prologue)) && 76 "ARMCCState users must specify whether their context is call" 77 "or prologue generation."); 78 CallOrPrologue = PC; 79 } 80 }; 81 } 82 83 // The APCS parameter registers. 84 static const MCPhysReg GPRArgRegs[] = { 85 ARM::R0, ARM::R1, ARM::R2, ARM::R3 86 }; 87 88 void ARMTargetLowering::addTypeForNEON(MVT VT, MVT PromotedLdStVT, 89 MVT PromotedBitwiseVT) { 90 if (VT != PromotedLdStVT) { 91 setOperationAction(ISD::LOAD, VT, Promote); 92 AddPromotedToType (ISD::LOAD, VT, PromotedLdStVT); 93 94 setOperationAction(ISD::STORE, VT, Promote); 95 AddPromotedToType (ISD::STORE, VT, PromotedLdStVT); 96 } 97 98 MVT ElemTy = VT.getVectorElementType(); 99 if (ElemTy != MVT::i64 && ElemTy != MVT::f64) 100 setOperationAction(ISD::SETCC, VT, Custom); 101 setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Custom); 102 setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom); 103 if (ElemTy == MVT::i32) { 104 setOperationAction(ISD::SINT_TO_FP, VT, Custom); 105 setOperationAction(ISD::UINT_TO_FP, VT, Custom); 106 setOperationAction(ISD::FP_TO_SINT, VT, Custom); 107 setOperationAction(ISD::FP_TO_UINT, VT, Custom); 108 } else { 109 setOperationAction(ISD::SINT_TO_FP, VT, Expand); 110 setOperationAction(ISD::UINT_TO_FP, VT, Expand); 111 setOperationAction(ISD::FP_TO_SINT, VT, Expand); 112 setOperationAction(ISD::FP_TO_UINT, VT, Expand); 113 } 114 setOperationAction(ISD::BUILD_VECTOR, VT, Custom); 115 setOperationAction(ISD::VECTOR_SHUFFLE, VT, Custom); 116 setOperationAction(ISD::CONCAT_VECTORS, VT, Legal); 117 setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Legal); 118 setOperationAction(ISD::SELECT, VT, Expand); 119 setOperationAction(ISD::SELECT_CC, VT, Expand); 120 setOperationAction(ISD::VSELECT, VT, Expand); 121 setOperationAction(ISD::SIGN_EXTEND_INREG, VT, Expand); 122 if (VT.isInteger()) { 123 setOperationAction(ISD::SHL, VT, Custom); 124 setOperationAction(ISD::SRA, VT, Custom); 125 setOperationAction(ISD::SRL, VT, Custom); 126 } 127 128 // Promote all bit-wise operations. 129 if (VT.isInteger() && VT != PromotedBitwiseVT) { 130 setOperationAction(ISD::AND, VT, Promote); 131 AddPromotedToType (ISD::AND, VT, PromotedBitwiseVT); 132 setOperationAction(ISD::OR, VT, Promote); 133 AddPromotedToType (ISD::OR, VT, PromotedBitwiseVT); 134 setOperationAction(ISD::XOR, VT, Promote); 135 AddPromotedToType (ISD::XOR, VT, PromotedBitwiseVT); 136 } 137 138 // Neon does not support vector divide/remainder operations. 139 setOperationAction(ISD::SDIV, VT, Expand); 140 setOperationAction(ISD::UDIV, VT, Expand); 141 setOperationAction(ISD::FDIV, VT, Expand); 142 setOperationAction(ISD::SREM, VT, Expand); 143 setOperationAction(ISD::UREM, VT, Expand); 144 setOperationAction(ISD::FREM, VT, Expand); 145 146 if (VT.isInteger()) { 147 setOperationAction(ISD::SABSDIFF, VT, Legal); 148 setOperationAction(ISD::UABSDIFF, VT, Legal); 149 } 150 if (!VT.isFloatingPoint() && 151 VT != MVT::v2i64 && VT != MVT::v1i64) 152 for (unsigned Opcode : {ISD::SMIN, ISD::SMAX, ISD::UMIN, ISD::UMAX}) 153 setOperationAction(Opcode, VT, Legal); 154 155 } 156 157 void ARMTargetLowering::addDRTypeForNEON(MVT VT) { 158 addRegisterClass(VT, &ARM::DPRRegClass); 159 addTypeForNEON(VT, MVT::f64, MVT::v2i32); 160 } 161 162 void ARMTargetLowering::addQRTypeForNEON(MVT VT) { 163 addRegisterClass(VT, &ARM::DPairRegClass); 164 addTypeForNEON(VT, MVT::v2f64, MVT::v4i32); 165 } 166 167 ARMTargetLowering::ARMTargetLowering(const TargetMachine &TM, 168 const ARMSubtarget &STI) 169 : TargetLowering(TM), Subtarget(&STI) { 170 RegInfo = Subtarget->getRegisterInfo(); 171 Itins = Subtarget->getInstrItineraryData(); 172 173 setBooleanVectorContents(ZeroOrNegativeOneBooleanContent); 174 175 if (Subtarget->isTargetMachO()) { 176 // Uses VFP for Thumb libfuncs if available. 177 if (Subtarget->isThumb() && Subtarget->hasVFP2() && 178 Subtarget->hasARMOps() && !Subtarget->useSoftFloat()) { 179 static const struct { 180 const RTLIB::Libcall Op; 181 const char * const Name; 182 const ISD::CondCode Cond; 183 } LibraryCalls[] = { 184 // Single-precision floating-point arithmetic. 185 { RTLIB::ADD_F32, "__addsf3vfp", ISD::SETCC_INVALID }, 186 { RTLIB::SUB_F32, "__subsf3vfp", ISD::SETCC_INVALID }, 187 { RTLIB::MUL_F32, "__mulsf3vfp", ISD::SETCC_INVALID }, 188 { RTLIB::DIV_F32, "__divsf3vfp", ISD::SETCC_INVALID }, 189 190 // Double-precision floating-point arithmetic. 191 { RTLIB::ADD_F64, "__adddf3vfp", ISD::SETCC_INVALID }, 192 { RTLIB::SUB_F64, "__subdf3vfp", ISD::SETCC_INVALID }, 193 { RTLIB::MUL_F64, "__muldf3vfp", ISD::SETCC_INVALID }, 194 { RTLIB::DIV_F64, "__divdf3vfp", ISD::SETCC_INVALID }, 195 196 // Single-precision comparisons. 197 { RTLIB::OEQ_F32, "__eqsf2vfp", ISD::SETNE }, 198 { RTLIB::UNE_F32, "__nesf2vfp", ISD::SETNE }, 199 { RTLIB::OLT_F32, "__ltsf2vfp", ISD::SETNE }, 200 { RTLIB::OLE_F32, "__lesf2vfp", ISD::SETNE }, 201 { RTLIB::OGE_F32, "__gesf2vfp", ISD::SETNE }, 202 { RTLIB::OGT_F32, "__gtsf2vfp", ISD::SETNE }, 203 { RTLIB::UO_F32, "__unordsf2vfp", ISD::SETNE }, 204 { RTLIB::O_F32, "__unordsf2vfp", ISD::SETEQ }, 205 206 // Double-precision comparisons. 207 { RTLIB::OEQ_F64, "__eqdf2vfp", ISD::SETNE }, 208 { RTLIB::UNE_F64, "__nedf2vfp", ISD::SETNE }, 209 { RTLIB::OLT_F64, "__ltdf2vfp", ISD::SETNE }, 210 { RTLIB::OLE_F64, "__ledf2vfp", ISD::SETNE }, 211 { RTLIB::OGE_F64, "__gedf2vfp", ISD::SETNE }, 212 { RTLIB::OGT_F64, "__gtdf2vfp", ISD::SETNE }, 213 { RTLIB::UO_F64, "__unorddf2vfp", ISD::SETNE }, 214 { RTLIB::O_F64, "__unorddf2vfp", ISD::SETEQ }, 215 216 // Floating-point to integer conversions. 217 // i64 conversions are done via library routines even when generating VFP 218 // instructions, so use the same ones. 219 { RTLIB::FPTOSINT_F64_I32, "__fixdfsivfp", ISD::SETCC_INVALID }, 220 { RTLIB::FPTOUINT_F64_I32, "__fixunsdfsivfp", ISD::SETCC_INVALID }, 221 { RTLIB::FPTOSINT_F32_I32, "__fixsfsivfp", ISD::SETCC_INVALID }, 222 { RTLIB::FPTOUINT_F32_I32, "__fixunssfsivfp", ISD::SETCC_INVALID }, 223 224 // Conversions between floating types. 225 { RTLIB::FPROUND_F64_F32, "__truncdfsf2vfp", ISD::SETCC_INVALID }, 226 { RTLIB::FPEXT_F32_F64, "__extendsfdf2vfp", ISD::SETCC_INVALID }, 227 228 // Integer to floating-point conversions. 229 // i64 conversions are done via library routines even when generating VFP 230 // instructions, so use the same ones. 231 // FIXME: There appears to be some naming inconsistency in ARM libgcc: 232 // e.g., __floatunsidf vs. __floatunssidfvfp. 233 { RTLIB::SINTTOFP_I32_F64, "__floatsidfvfp", ISD::SETCC_INVALID }, 234 { RTLIB::UINTTOFP_I32_F64, "__floatunssidfvfp", ISD::SETCC_INVALID }, 235 { RTLIB::SINTTOFP_I32_F32, "__floatsisfvfp", ISD::SETCC_INVALID }, 236 { RTLIB::UINTTOFP_I32_F32, "__floatunssisfvfp", ISD::SETCC_INVALID }, 237 }; 238 239 for (const auto &LC : LibraryCalls) { 240 setLibcallName(LC.Op, LC.Name); 241 if (LC.Cond != ISD::SETCC_INVALID) 242 setCmpLibcallCC(LC.Op, LC.Cond); 243 } 244 } 245 246 // Set the correct calling convention for ARMv7k WatchOS. It's just 247 // AAPCS_VFP for functions as simple as libcalls. 248 if (Subtarget->isTargetWatchOS()) { 249 for (int i = 0; i < RTLIB::UNKNOWN_LIBCALL; ++i) 250 setLibcallCallingConv((RTLIB::Libcall)i, CallingConv::ARM_AAPCS_VFP); 251 } 252 } 253 254 // These libcalls are not available in 32-bit. 255 setLibcallName(RTLIB::SHL_I128, nullptr); 256 setLibcallName(RTLIB::SRL_I128, nullptr); 257 setLibcallName(RTLIB::SRA_I128, nullptr); 258 259 // RTLIB 260 if (Subtarget->isAAPCS_ABI() && 261 (Subtarget->isTargetAEABI() || Subtarget->isTargetGNUAEABI() || 262 Subtarget->isTargetAndroid())) { 263 static const struct { 264 const RTLIB::Libcall Op; 265 const char * const Name; 266 const CallingConv::ID CC; 267 const ISD::CondCode Cond; 268 } LibraryCalls[] = { 269 // Double-precision floating-point arithmetic helper functions 270 // RTABI chapter 4.1.2, Table 2 271 { RTLIB::ADD_F64, "__aeabi_dadd", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 272 { RTLIB::DIV_F64, "__aeabi_ddiv", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 273 { RTLIB::MUL_F64, "__aeabi_dmul", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 274 { RTLIB::SUB_F64, "__aeabi_dsub", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 275 276 // Double-precision floating-point comparison helper functions 277 // RTABI chapter 4.1.2, Table 3 278 { RTLIB::OEQ_F64, "__aeabi_dcmpeq", CallingConv::ARM_AAPCS, ISD::SETNE }, 279 { RTLIB::UNE_F64, "__aeabi_dcmpeq", CallingConv::ARM_AAPCS, ISD::SETEQ }, 280 { RTLIB::OLT_F64, "__aeabi_dcmplt", CallingConv::ARM_AAPCS, ISD::SETNE }, 281 { RTLIB::OLE_F64, "__aeabi_dcmple", CallingConv::ARM_AAPCS, ISD::SETNE }, 282 { RTLIB::OGE_F64, "__aeabi_dcmpge", CallingConv::ARM_AAPCS, ISD::SETNE }, 283 { RTLIB::OGT_F64, "__aeabi_dcmpgt", CallingConv::ARM_AAPCS, ISD::SETNE }, 284 { RTLIB::UO_F64, "__aeabi_dcmpun", CallingConv::ARM_AAPCS, ISD::SETNE }, 285 { RTLIB::O_F64, "__aeabi_dcmpun", CallingConv::ARM_AAPCS, ISD::SETEQ }, 286 287 // Single-precision floating-point arithmetic helper functions 288 // RTABI chapter 4.1.2, Table 4 289 { RTLIB::ADD_F32, "__aeabi_fadd", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 290 { RTLIB::DIV_F32, "__aeabi_fdiv", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 291 { RTLIB::MUL_F32, "__aeabi_fmul", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 292 { RTLIB::SUB_F32, "__aeabi_fsub", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 293 294 // Single-precision floating-point comparison helper functions 295 // RTABI chapter 4.1.2, Table 5 296 { RTLIB::OEQ_F32, "__aeabi_fcmpeq", CallingConv::ARM_AAPCS, ISD::SETNE }, 297 { RTLIB::UNE_F32, "__aeabi_fcmpeq", CallingConv::ARM_AAPCS, ISD::SETEQ }, 298 { RTLIB::OLT_F32, "__aeabi_fcmplt", CallingConv::ARM_AAPCS, ISD::SETNE }, 299 { RTLIB::OLE_F32, "__aeabi_fcmple", CallingConv::ARM_AAPCS, ISD::SETNE }, 300 { RTLIB::OGE_F32, "__aeabi_fcmpge", CallingConv::ARM_AAPCS, ISD::SETNE }, 301 { RTLIB::OGT_F32, "__aeabi_fcmpgt", CallingConv::ARM_AAPCS, ISD::SETNE }, 302 { RTLIB::UO_F32, "__aeabi_fcmpun", CallingConv::ARM_AAPCS, ISD::SETNE }, 303 { RTLIB::O_F32, "__aeabi_fcmpun", CallingConv::ARM_AAPCS, ISD::SETEQ }, 304 305 // Floating-point to integer conversions. 306 // RTABI chapter 4.1.2, Table 6 307 { RTLIB::FPTOSINT_F64_I32, "__aeabi_d2iz", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 308 { RTLIB::FPTOUINT_F64_I32, "__aeabi_d2uiz", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 309 { RTLIB::FPTOSINT_F64_I64, "__aeabi_d2lz", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 310 { RTLIB::FPTOUINT_F64_I64, "__aeabi_d2ulz", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 311 { RTLIB::FPTOSINT_F32_I32, "__aeabi_f2iz", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 312 { RTLIB::FPTOUINT_F32_I32, "__aeabi_f2uiz", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 313 { RTLIB::FPTOSINT_F32_I64, "__aeabi_f2lz", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 314 { RTLIB::FPTOUINT_F32_I64, "__aeabi_f2ulz", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 315 316 // Conversions between floating types. 317 // RTABI chapter 4.1.2, Table 7 318 { RTLIB::FPROUND_F64_F32, "__aeabi_d2f", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 319 { RTLIB::FPROUND_F64_F16, "__aeabi_d2h", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 320 { RTLIB::FPEXT_F32_F64, "__aeabi_f2d", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 321 322 // Integer to floating-point conversions. 323 // RTABI chapter 4.1.2, Table 8 324 { RTLIB::SINTTOFP_I32_F64, "__aeabi_i2d", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 325 { RTLIB::UINTTOFP_I32_F64, "__aeabi_ui2d", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 326 { RTLIB::SINTTOFP_I64_F64, "__aeabi_l2d", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 327 { RTLIB::UINTTOFP_I64_F64, "__aeabi_ul2d", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 328 { RTLIB::SINTTOFP_I32_F32, "__aeabi_i2f", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 329 { RTLIB::UINTTOFP_I32_F32, "__aeabi_ui2f", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 330 { RTLIB::SINTTOFP_I64_F32, "__aeabi_l2f", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 331 { RTLIB::UINTTOFP_I64_F32, "__aeabi_ul2f", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 332 333 // Long long helper functions 334 // RTABI chapter 4.2, Table 9 335 { RTLIB::MUL_I64, "__aeabi_lmul", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 336 { RTLIB::SHL_I64, "__aeabi_llsl", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 337 { RTLIB::SRL_I64, "__aeabi_llsr", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 338 { RTLIB::SRA_I64, "__aeabi_lasr", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 339 340 // Integer division functions 341 // RTABI chapter 4.3.1 342 { RTLIB::SDIV_I8, "__aeabi_idiv", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 343 { RTLIB::SDIV_I16, "__aeabi_idiv", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 344 { RTLIB::SDIV_I32, "__aeabi_idiv", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 345 { RTLIB::SDIV_I64, "__aeabi_ldivmod", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 346 { RTLIB::UDIV_I8, "__aeabi_uidiv", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 347 { RTLIB::UDIV_I16, "__aeabi_uidiv", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 348 { RTLIB::UDIV_I32, "__aeabi_uidiv", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 349 { RTLIB::UDIV_I64, "__aeabi_uldivmod", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 350 }; 351 352 for (const auto &LC : LibraryCalls) { 353 setLibcallName(LC.Op, LC.Name); 354 setLibcallCallingConv(LC.Op, LC.CC); 355 if (LC.Cond != ISD::SETCC_INVALID) 356 setCmpLibcallCC(LC.Op, LC.Cond); 357 } 358 359 // EABI dependent RTLIB 360 if (TM.Options.EABIVersion == EABI::EABI4 || 361 TM.Options.EABIVersion == EABI::EABI5) { 362 static const struct { 363 const RTLIB::Libcall Op; 364 const char *const Name; 365 const CallingConv::ID CC; 366 const ISD::CondCode Cond; 367 } MemOpsLibraryCalls[] = { 368 // Memory operations 369 // RTABI chapter 4.3.4 370 { RTLIB::MEMCPY, "__aeabi_memcpy", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 371 { RTLIB::MEMMOVE, "__aeabi_memmove", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 372 { RTLIB::MEMSET, "__aeabi_memset", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 373 }; 374 375 for (const auto &LC : MemOpsLibraryCalls) { 376 setLibcallName(LC.Op, LC.Name); 377 setLibcallCallingConv(LC.Op, LC.CC); 378 if (LC.Cond != ISD::SETCC_INVALID) 379 setCmpLibcallCC(LC.Op, LC.Cond); 380 } 381 } 382 } 383 384 if (Subtarget->isTargetWindows()) { 385 static const struct { 386 const RTLIB::Libcall Op; 387 const char * const Name; 388 const CallingConv::ID CC; 389 } LibraryCalls[] = { 390 { RTLIB::FPTOSINT_F32_I64, "__stoi64", CallingConv::ARM_AAPCS_VFP }, 391 { RTLIB::FPTOSINT_F64_I64, "__dtoi64", CallingConv::ARM_AAPCS_VFP }, 392 { RTLIB::FPTOUINT_F32_I64, "__stou64", CallingConv::ARM_AAPCS_VFP }, 393 { RTLIB::FPTOUINT_F64_I64, "__dtou64", CallingConv::ARM_AAPCS_VFP }, 394 { RTLIB::SINTTOFP_I64_F32, "__i64tos", CallingConv::ARM_AAPCS_VFP }, 395 { RTLIB::SINTTOFP_I64_F64, "__i64tod", CallingConv::ARM_AAPCS_VFP }, 396 { RTLIB::UINTTOFP_I64_F32, "__u64tos", CallingConv::ARM_AAPCS_VFP }, 397 { RTLIB::UINTTOFP_I64_F64, "__u64tod", CallingConv::ARM_AAPCS_VFP }, 398 { RTLIB::SDIV_I32, "__rt_sdiv", CallingConv::ARM_AAPCS_VFP }, 399 { RTLIB::UDIV_I32, "__rt_udiv", CallingConv::ARM_AAPCS_VFP }, 400 { RTLIB::SDIV_I64, "__rt_sdiv64", CallingConv::ARM_AAPCS_VFP }, 401 { RTLIB::UDIV_I64, "__rt_udiv64", CallingConv::ARM_AAPCS_VFP }, 402 }; 403 404 for (const auto &LC : LibraryCalls) { 405 setLibcallName(LC.Op, LC.Name); 406 setLibcallCallingConv(LC.Op, LC.CC); 407 } 408 } 409 410 // Use divmod compiler-rt calls for iOS 5.0 and later. 411 if (Subtarget->isTargetWatchOS() || 412 (Subtarget->isTargetIOS() && 413 !Subtarget->getTargetTriple().isOSVersionLT(5, 0))) { 414 setLibcallName(RTLIB::SDIVREM_I32, "__divmodsi4"); 415 setLibcallName(RTLIB::UDIVREM_I32, "__udivmodsi4"); 416 } 417 418 // The half <-> float conversion functions are always soft-float, but are 419 // needed for some targets which use a hard-float calling convention by 420 // default. 421 if (Subtarget->isAAPCS_ABI()) { 422 setLibcallCallingConv(RTLIB::FPROUND_F32_F16, CallingConv::ARM_AAPCS); 423 setLibcallCallingConv(RTLIB::FPROUND_F64_F16, CallingConv::ARM_AAPCS); 424 setLibcallCallingConv(RTLIB::FPEXT_F16_F32, CallingConv::ARM_AAPCS); 425 } else { 426 setLibcallCallingConv(RTLIB::FPROUND_F32_F16, CallingConv::ARM_APCS); 427 setLibcallCallingConv(RTLIB::FPROUND_F64_F16, CallingConv::ARM_APCS); 428 setLibcallCallingConv(RTLIB::FPEXT_F16_F32, CallingConv::ARM_APCS); 429 } 430 431 // In EABI, these functions have an __aeabi_ prefix, but in GNUEABI they have 432 // a __gnu_ prefix (which is the default). 433 if (Subtarget->isTargetAEABI()) { 434 setLibcallName(RTLIB::FPROUND_F32_F16, "__aeabi_f2h"); 435 setLibcallName(RTLIB::FPROUND_F64_F16, "__aeabi_d2h"); 436 setLibcallName(RTLIB::FPEXT_F16_F32, "__aeabi_h2f"); 437 } 438 439 if (Subtarget->isThumb1Only()) 440 addRegisterClass(MVT::i32, &ARM::tGPRRegClass); 441 else 442 addRegisterClass(MVT::i32, &ARM::GPRRegClass); 443 if (!Subtarget->useSoftFloat() && Subtarget->hasVFP2() && 444 !Subtarget->isThumb1Only()) { 445 addRegisterClass(MVT::f32, &ARM::SPRRegClass); 446 addRegisterClass(MVT::f64, &ARM::DPRRegClass); 447 } 448 449 for (MVT VT : MVT::vector_valuetypes()) { 450 for (MVT InnerVT : MVT::vector_valuetypes()) { 451 setTruncStoreAction(VT, InnerVT, Expand); 452 setLoadExtAction(ISD::SEXTLOAD, VT, InnerVT, Expand); 453 setLoadExtAction(ISD::ZEXTLOAD, VT, InnerVT, Expand); 454 setLoadExtAction(ISD::EXTLOAD, VT, InnerVT, Expand); 455 } 456 457 setOperationAction(ISD::MULHS, VT, Expand); 458 setOperationAction(ISD::SMUL_LOHI, VT, Expand); 459 setOperationAction(ISD::MULHU, VT, Expand); 460 setOperationAction(ISD::UMUL_LOHI, VT, Expand); 461 462 setOperationAction(ISD::BSWAP, VT, Expand); 463 } 464 465 setOperationAction(ISD::ConstantFP, MVT::f32, Custom); 466 setOperationAction(ISD::ConstantFP, MVT::f64, Custom); 467 468 setOperationAction(ISD::READ_REGISTER, MVT::i64, Custom); 469 setOperationAction(ISD::WRITE_REGISTER, MVT::i64, Custom); 470 471 if (Subtarget->hasNEON()) { 472 addDRTypeForNEON(MVT::v2f32); 473 addDRTypeForNEON(MVT::v8i8); 474 addDRTypeForNEON(MVT::v4i16); 475 addDRTypeForNEON(MVT::v2i32); 476 addDRTypeForNEON(MVT::v1i64); 477 478 addQRTypeForNEON(MVT::v4f32); 479 addQRTypeForNEON(MVT::v2f64); 480 addQRTypeForNEON(MVT::v16i8); 481 addQRTypeForNEON(MVT::v8i16); 482 addQRTypeForNEON(MVT::v4i32); 483 addQRTypeForNEON(MVT::v2i64); 484 485 // v2f64 is legal so that QR subregs can be extracted as f64 elements, but 486 // neither Neon nor VFP support any arithmetic operations on it. 487 // The same with v4f32. But keep in mind that vadd, vsub, vmul are natively 488 // supported for v4f32. 489 setOperationAction(ISD::FADD, MVT::v2f64, Expand); 490 setOperationAction(ISD::FSUB, MVT::v2f64, Expand); 491 setOperationAction(ISD::FMUL, MVT::v2f64, Expand); 492 // FIXME: Code duplication: FDIV and FREM are expanded always, see 493 // ARMTargetLowering::addTypeForNEON method for details. 494 setOperationAction(ISD::FDIV, MVT::v2f64, Expand); 495 setOperationAction(ISD::FREM, MVT::v2f64, Expand); 496 // FIXME: Create unittest. 497 // In another words, find a way when "copysign" appears in DAG with vector 498 // operands. 499 setOperationAction(ISD::FCOPYSIGN, MVT::v2f64, Expand); 500 // FIXME: Code duplication: SETCC has custom operation action, see 501 // ARMTargetLowering::addTypeForNEON method for details. 502 setOperationAction(ISD::SETCC, MVT::v2f64, Expand); 503 // FIXME: Create unittest for FNEG and for FABS. 504 setOperationAction(ISD::FNEG, MVT::v2f64, Expand); 505 setOperationAction(ISD::FABS, MVT::v2f64, Expand); 506 setOperationAction(ISD::FSQRT, MVT::v2f64, Expand); 507 setOperationAction(ISD::FSIN, MVT::v2f64, Expand); 508 setOperationAction(ISD::FCOS, MVT::v2f64, Expand); 509 setOperationAction(ISD::FPOWI, MVT::v2f64, Expand); 510 setOperationAction(ISD::FPOW, MVT::v2f64, Expand); 511 setOperationAction(ISD::FLOG, MVT::v2f64, Expand); 512 setOperationAction(ISD::FLOG2, MVT::v2f64, Expand); 513 setOperationAction(ISD::FLOG10, MVT::v2f64, Expand); 514 setOperationAction(ISD::FEXP, MVT::v2f64, Expand); 515 setOperationAction(ISD::FEXP2, MVT::v2f64, Expand); 516 // FIXME: Create unittest for FCEIL, FTRUNC, FRINT, FNEARBYINT, FFLOOR. 517 setOperationAction(ISD::FCEIL, MVT::v2f64, Expand); 518 setOperationAction(ISD::FTRUNC, MVT::v2f64, Expand); 519 setOperationAction(ISD::FRINT, MVT::v2f64, Expand); 520 setOperationAction(ISD::FNEARBYINT, MVT::v2f64, Expand); 521 setOperationAction(ISD::FFLOOR, MVT::v2f64, Expand); 522 setOperationAction(ISD::FMA, MVT::v2f64, Expand); 523 524 setOperationAction(ISD::FSQRT, MVT::v4f32, Expand); 525 setOperationAction(ISD::FSIN, MVT::v4f32, Expand); 526 setOperationAction(ISD::FCOS, MVT::v4f32, Expand); 527 setOperationAction(ISD::FPOWI, MVT::v4f32, Expand); 528 setOperationAction(ISD::FPOW, MVT::v4f32, Expand); 529 setOperationAction(ISD::FLOG, MVT::v4f32, Expand); 530 setOperationAction(ISD::FLOG2, MVT::v4f32, Expand); 531 setOperationAction(ISD::FLOG10, MVT::v4f32, Expand); 532 setOperationAction(ISD::FEXP, MVT::v4f32, Expand); 533 setOperationAction(ISD::FEXP2, MVT::v4f32, Expand); 534 setOperationAction(ISD::FCEIL, MVT::v4f32, Expand); 535 setOperationAction(ISD::FTRUNC, MVT::v4f32, Expand); 536 setOperationAction(ISD::FRINT, MVT::v4f32, Expand); 537 setOperationAction(ISD::FNEARBYINT, MVT::v4f32, Expand); 538 setOperationAction(ISD::FFLOOR, MVT::v4f32, Expand); 539 540 // Mark v2f32 intrinsics. 541 setOperationAction(ISD::FSQRT, MVT::v2f32, Expand); 542 setOperationAction(ISD::FSIN, MVT::v2f32, Expand); 543 setOperationAction(ISD::FCOS, MVT::v2f32, Expand); 544 setOperationAction(ISD::FPOWI, MVT::v2f32, Expand); 545 setOperationAction(ISD::FPOW, MVT::v2f32, Expand); 546 setOperationAction(ISD::FLOG, MVT::v2f32, Expand); 547 setOperationAction(ISD::FLOG2, MVT::v2f32, Expand); 548 setOperationAction(ISD::FLOG10, MVT::v2f32, Expand); 549 setOperationAction(ISD::FEXP, MVT::v2f32, Expand); 550 setOperationAction(ISD::FEXP2, MVT::v2f32, Expand); 551 setOperationAction(ISD::FCEIL, MVT::v2f32, Expand); 552 setOperationAction(ISD::FTRUNC, MVT::v2f32, Expand); 553 setOperationAction(ISD::FRINT, MVT::v2f32, Expand); 554 setOperationAction(ISD::FNEARBYINT, MVT::v2f32, Expand); 555 setOperationAction(ISD::FFLOOR, MVT::v2f32, Expand); 556 557 // Neon does not support some operations on v1i64 and v2i64 types. 558 setOperationAction(ISD::MUL, MVT::v1i64, Expand); 559 // Custom handling for some quad-vector types to detect VMULL. 560 setOperationAction(ISD::MUL, MVT::v8i16, Custom); 561 setOperationAction(ISD::MUL, MVT::v4i32, Custom); 562 setOperationAction(ISD::MUL, MVT::v2i64, Custom); 563 // Custom handling for some vector types to avoid expensive expansions 564 setOperationAction(ISD::SDIV, MVT::v4i16, Custom); 565 setOperationAction(ISD::SDIV, MVT::v8i8, Custom); 566 setOperationAction(ISD::UDIV, MVT::v4i16, Custom); 567 setOperationAction(ISD::UDIV, MVT::v8i8, Custom); 568 setOperationAction(ISD::SETCC, MVT::v1i64, Expand); 569 setOperationAction(ISD::SETCC, MVT::v2i64, Expand); 570 // Neon does not have single instruction SINT_TO_FP and UINT_TO_FP with 571 // a destination type that is wider than the source, and nor does 572 // it have a FP_TO_[SU]INT instruction with a narrower destination than 573 // source. 574 setOperationAction(ISD::SINT_TO_FP, MVT::v4i16, Custom); 575 setOperationAction(ISD::UINT_TO_FP, MVT::v4i16, Custom); 576 setOperationAction(ISD::FP_TO_UINT, MVT::v4i16, Custom); 577 setOperationAction(ISD::FP_TO_SINT, MVT::v4i16, Custom); 578 579 setOperationAction(ISD::FP_ROUND, MVT::v2f32, Expand); 580 setOperationAction(ISD::FP_EXTEND, MVT::v2f64, Expand); 581 582 // NEON does not have single instruction CTPOP for vectors with element 583 // types wider than 8-bits. However, custom lowering can leverage the 584 // v8i8/v16i8 vcnt instruction. 585 setOperationAction(ISD::CTPOP, MVT::v2i32, Custom); 586 setOperationAction(ISD::CTPOP, MVT::v4i32, Custom); 587 setOperationAction(ISD::CTPOP, MVT::v4i16, Custom); 588 setOperationAction(ISD::CTPOP, MVT::v8i16, Custom); 589 590 // NEON does not have single instruction CTTZ for vectors. 591 setOperationAction(ISD::CTTZ, MVT::v8i8, Custom); 592 setOperationAction(ISD::CTTZ, MVT::v4i16, Custom); 593 setOperationAction(ISD::CTTZ, MVT::v2i32, Custom); 594 setOperationAction(ISD::CTTZ, MVT::v1i64, Custom); 595 596 setOperationAction(ISD::CTTZ, MVT::v16i8, Custom); 597 setOperationAction(ISD::CTTZ, MVT::v8i16, Custom); 598 setOperationAction(ISD::CTTZ, MVT::v4i32, Custom); 599 setOperationAction(ISD::CTTZ, MVT::v2i64, Custom); 600 601 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::v8i8, Custom); 602 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::v4i16, Custom); 603 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::v2i32, Custom); 604 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::v1i64, Custom); 605 606 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::v16i8, Custom); 607 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::v8i16, Custom); 608 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::v4i32, Custom); 609 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::v2i64, Custom); 610 611 // NEON only has FMA instructions as of VFP4. 612 if (!Subtarget->hasVFP4()) { 613 setOperationAction(ISD::FMA, MVT::v2f32, Expand); 614 setOperationAction(ISD::FMA, MVT::v4f32, Expand); 615 } 616 617 setTargetDAGCombine(ISD::INTRINSIC_VOID); 618 setTargetDAGCombine(ISD::INTRINSIC_W_CHAIN); 619 setTargetDAGCombine(ISD::INTRINSIC_WO_CHAIN); 620 setTargetDAGCombine(ISD::SHL); 621 setTargetDAGCombine(ISD::SRL); 622 setTargetDAGCombine(ISD::SRA); 623 setTargetDAGCombine(ISD::SIGN_EXTEND); 624 setTargetDAGCombine(ISD::ZERO_EXTEND); 625 setTargetDAGCombine(ISD::ANY_EXTEND); 626 setTargetDAGCombine(ISD::BUILD_VECTOR); 627 setTargetDAGCombine(ISD::VECTOR_SHUFFLE); 628 setTargetDAGCombine(ISD::INSERT_VECTOR_ELT); 629 setTargetDAGCombine(ISD::STORE); 630 setTargetDAGCombine(ISD::FP_TO_SINT); 631 setTargetDAGCombine(ISD::FP_TO_UINT); 632 setTargetDAGCombine(ISD::FDIV); 633 setTargetDAGCombine(ISD::LOAD); 634 635 // It is legal to extload from v4i8 to v4i16 or v4i32. 636 for (MVT Ty : {MVT::v8i8, MVT::v4i8, MVT::v2i8, MVT::v4i16, MVT::v2i16, 637 MVT::v2i32}) { 638 for (MVT VT : MVT::integer_vector_valuetypes()) { 639 setLoadExtAction(ISD::EXTLOAD, VT, Ty, Legal); 640 setLoadExtAction(ISD::ZEXTLOAD, VT, Ty, Legal); 641 setLoadExtAction(ISD::SEXTLOAD, VT, Ty, Legal); 642 } 643 } 644 } 645 646 // ARM and Thumb2 support UMLAL/SMLAL. 647 if (!Subtarget->isThumb1Only()) 648 setTargetDAGCombine(ISD::ADDC); 649 650 if (Subtarget->isFPOnlySP()) { 651 // When targeting a floating-point unit with only single-precision 652 // operations, f64 is legal for the few double-precision instructions which 653 // are present However, no double-precision operations other than moves, 654 // loads and stores are provided by the hardware. 655 setOperationAction(ISD::FADD, MVT::f64, Expand); 656 setOperationAction(ISD::FSUB, MVT::f64, Expand); 657 setOperationAction(ISD::FMUL, MVT::f64, Expand); 658 setOperationAction(ISD::FMA, MVT::f64, Expand); 659 setOperationAction(ISD::FDIV, MVT::f64, Expand); 660 setOperationAction(ISD::FREM, MVT::f64, Expand); 661 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand); 662 setOperationAction(ISD::FGETSIGN, MVT::f64, Expand); 663 setOperationAction(ISD::FNEG, MVT::f64, Expand); 664 setOperationAction(ISD::FABS, MVT::f64, Expand); 665 setOperationAction(ISD::FSQRT, MVT::f64, Expand); 666 setOperationAction(ISD::FSIN, MVT::f64, Expand); 667 setOperationAction(ISD::FCOS, MVT::f64, Expand); 668 setOperationAction(ISD::FPOWI, MVT::f64, Expand); 669 setOperationAction(ISD::FPOW, MVT::f64, Expand); 670 setOperationAction(ISD::FLOG, MVT::f64, Expand); 671 setOperationAction(ISD::FLOG2, MVT::f64, Expand); 672 setOperationAction(ISD::FLOG10, MVT::f64, Expand); 673 setOperationAction(ISD::FEXP, MVT::f64, Expand); 674 setOperationAction(ISD::FEXP2, MVT::f64, Expand); 675 setOperationAction(ISD::FCEIL, MVT::f64, Expand); 676 setOperationAction(ISD::FTRUNC, MVT::f64, Expand); 677 setOperationAction(ISD::FRINT, MVT::f64, Expand); 678 setOperationAction(ISD::FNEARBYINT, MVT::f64, Expand); 679 setOperationAction(ISD::FFLOOR, MVT::f64, Expand); 680 setOperationAction(ISD::SINT_TO_FP, MVT::i32, Custom); 681 setOperationAction(ISD::UINT_TO_FP, MVT::i32, Custom); 682 setOperationAction(ISD::FP_TO_SINT, MVT::i32, Custom); 683 setOperationAction(ISD::FP_TO_UINT, MVT::i32, Custom); 684 setOperationAction(ISD::FP_TO_SINT, MVT::f64, Custom); 685 setOperationAction(ISD::FP_TO_UINT, MVT::f64, Custom); 686 setOperationAction(ISD::FP_ROUND, MVT::f32, Custom); 687 setOperationAction(ISD::FP_EXTEND, MVT::f64, Custom); 688 } 689 690 computeRegisterProperties(Subtarget->getRegisterInfo()); 691 692 // ARM does not have floating-point extending loads. 693 for (MVT VT : MVT::fp_valuetypes()) { 694 setLoadExtAction(ISD::EXTLOAD, VT, MVT::f32, Expand); 695 setLoadExtAction(ISD::EXTLOAD, VT, MVT::f16, Expand); 696 } 697 698 // ... or truncating stores 699 setTruncStoreAction(MVT::f64, MVT::f32, Expand); 700 setTruncStoreAction(MVT::f32, MVT::f16, Expand); 701 setTruncStoreAction(MVT::f64, MVT::f16, Expand); 702 703 // ARM does not have i1 sign extending load. 704 for (MVT VT : MVT::integer_valuetypes()) 705 setLoadExtAction(ISD::SEXTLOAD, VT, MVT::i1, Promote); 706 707 // ARM supports all 4 flavors of integer indexed load / store. 708 if (!Subtarget->isThumb1Only()) { 709 for (unsigned im = (unsigned)ISD::PRE_INC; 710 im != (unsigned)ISD::LAST_INDEXED_MODE; ++im) { 711 setIndexedLoadAction(im, MVT::i1, Legal); 712 setIndexedLoadAction(im, MVT::i8, Legal); 713 setIndexedLoadAction(im, MVT::i16, Legal); 714 setIndexedLoadAction(im, MVT::i32, Legal); 715 setIndexedStoreAction(im, MVT::i1, Legal); 716 setIndexedStoreAction(im, MVT::i8, Legal); 717 setIndexedStoreAction(im, MVT::i16, Legal); 718 setIndexedStoreAction(im, MVT::i32, Legal); 719 } 720 } 721 722 setOperationAction(ISD::SADDO, MVT::i32, Custom); 723 setOperationAction(ISD::UADDO, MVT::i32, Custom); 724 setOperationAction(ISD::SSUBO, MVT::i32, Custom); 725 setOperationAction(ISD::USUBO, MVT::i32, Custom); 726 727 // i64 operation support. 728 setOperationAction(ISD::MUL, MVT::i64, Expand); 729 setOperationAction(ISD::MULHU, MVT::i32, Expand); 730 if (Subtarget->isThumb1Only()) { 731 setOperationAction(ISD::UMUL_LOHI, MVT::i32, Expand); 732 setOperationAction(ISD::SMUL_LOHI, MVT::i32, Expand); 733 } 734 if (Subtarget->isThumb1Only() || !Subtarget->hasV6Ops() 735 || (Subtarget->isThumb2() && !Subtarget->hasDSP())) 736 setOperationAction(ISD::MULHS, MVT::i32, Expand); 737 738 setOperationAction(ISD::SHL_PARTS, MVT::i32, Custom); 739 setOperationAction(ISD::SRA_PARTS, MVT::i32, Custom); 740 setOperationAction(ISD::SRL_PARTS, MVT::i32, Custom); 741 setOperationAction(ISD::SRL, MVT::i64, Custom); 742 setOperationAction(ISD::SRA, MVT::i64, Custom); 743 744 if (!Subtarget->isThumb1Only()) { 745 // FIXME: We should do this for Thumb1 as well. 746 setOperationAction(ISD::ADDC, MVT::i32, Custom); 747 setOperationAction(ISD::ADDE, MVT::i32, Custom); 748 setOperationAction(ISD::SUBC, MVT::i32, Custom); 749 setOperationAction(ISD::SUBE, MVT::i32, Custom); 750 } 751 752 if (!Subtarget->isThumb1Only()) 753 setOperationAction(ISD::BITREVERSE, MVT::i32, Legal); 754 755 // ARM does not have ROTL. 756 setOperationAction(ISD::ROTL, MVT::i32, Expand); 757 for (MVT VT : MVT::vector_valuetypes()) { 758 setOperationAction(ISD::ROTL, VT, Expand); 759 setOperationAction(ISD::ROTR, VT, Expand); 760 } 761 setOperationAction(ISD::CTTZ, MVT::i32, Custom); 762 setOperationAction(ISD::CTPOP, MVT::i32, Expand); 763 if (!Subtarget->hasV5TOps() || Subtarget->isThumb1Only()) 764 setOperationAction(ISD::CTLZ, MVT::i32, Expand); 765 766 // These just redirect to CTTZ and CTLZ on ARM. 767 setOperationAction(ISD::CTTZ_ZERO_UNDEF , MVT::i32 , Expand); 768 setOperationAction(ISD::CTLZ_ZERO_UNDEF , MVT::i32 , Expand); 769 770 // @llvm.readcyclecounter requires the Performance Monitors extension. 771 // Default to the 0 expansion on unsupported platforms. 772 // FIXME: Technically there are older ARM CPUs that have 773 // implementation-specific ways of obtaining this information. 774 if (Subtarget->hasPerfMon()) 775 setOperationAction(ISD::READCYCLECOUNTER, MVT::i64, Custom); 776 777 // Only ARMv6 has BSWAP. 778 if (!Subtarget->hasV6Ops()) 779 setOperationAction(ISD::BSWAP, MVT::i32, Expand); 780 781 if (!(Subtarget->hasDivide() && Subtarget->isThumb2()) && 782 !(Subtarget->hasDivideInARMMode() && !Subtarget->isThumb())) { 783 // These are expanded into libcalls if the cpu doesn't have HW divider. 784 setOperationAction(ISD::SDIV, MVT::i32, LibCall); 785 setOperationAction(ISD::UDIV, MVT::i32, LibCall); 786 } 787 788 setOperationAction(ISD::SREM, MVT::i32, Expand); 789 setOperationAction(ISD::UREM, MVT::i32, Expand); 790 // Register based DivRem for AEABI (RTABI 4.2) 791 if (Subtarget->isTargetAEABI() || Subtarget->isTargetAndroid()) { 792 setOperationAction(ISD::SREM, MVT::i64, Custom); 793 setOperationAction(ISD::UREM, MVT::i64, Custom); 794 795 setLibcallName(RTLIB::SDIVREM_I8, "__aeabi_idivmod"); 796 setLibcallName(RTLIB::SDIVREM_I16, "__aeabi_idivmod"); 797 setLibcallName(RTLIB::SDIVREM_I32, "__aeabi_idivmod"); 798 setLibcallName(RTLIB::SDIVREM_I64, "__aeabi_ldivmod"); 799 setLibcallName(RTLIB::UDIVREM_I8, "__aeabi_uidivmod"); 800 setLibcallName(RTLIB::UDIVREM_I16, "__aeabi_uidivmod"); 801 setLibcallName(RTLIB::UDIVREM_I32, "__aeabi_uidivmod"); 802 setLibcallName(RTLIB::UDIVREM_I64, "__aeabi_uldivmod"); 803 804 setLibcallCallingConv(RTLIB::SDIVREM_I8, CallingConv::ARM_AAPCS); 805 setLibcallCallingConv(RTLIB::SDIVREM_I16, CallingConv::ARM_AAPCS); 806 setLibcallCallingConv(RTLIB::SDIVREM_I32, CallingConv::ARM_AAPCS); 807 setLibcallCallingConv(RTLIB::SDIVREM_I64, CallingConv::ARM_AAPCS); 808 setLibcallCallingConv(RTLIB::UDIVREM_I8, CallingConv::ARM_AAPCS); 809 setLibcallCallingConv(RTLIB::UDIVREM_I16, CallingConv::ARM_AAPCS); 810 setLibcallCallingConv(RTLIB::UDIVREM_I32, CallingConv::ARM_AAPCS); 811 setLibcallCallingConv(RTLIB::UDIVREM_I64, CallingConv::ARM_AAPCS); 812 813 setOperationAction(ISD::SDIVREM, MVT::i32, Custom); 814 setOperationAction(ISD::UDIVREM, MVT::i32, Custom); 815 } else { 816 setOperationAction(ISD::SDIVREM, MVT::i32, Expand); 817 setOperationAction(ISD::UDIVREM, MVT::i32, Expand); 818 } 819 820 setOperationAction(ISD::GlobalAddress, MVT::i32, Custom); 821 setOperationAction(ISD::ConstantPool, MVT::i32, Custom); 822 setOperationAction(ISD::GlobalTLSAddress, MVT::i32, Custom); 823 setOperationAction(ISD::BlockAddress, MVT::i32, Custom); 824 825 setOperationAction(ISD::TRAP, MVT::Other, Legal); 826 827 // Use the default implementation. 828 setOperationAction(ISD::VASTART, MVT::Other, Custom); 829 setOperationAction(ISD::VAARG, MVT::Other, Expand); 830 setOperationAction(ISD::VACOPY, MVT::Other, Expand); 831 setOperationAction(ISD::VAEND, MVT::Other, Expand); 832 setOperationAction(ISD::STACKSAVE, MVT::Other, Expand); 833 setOperationAction(ISD::STACKRESTORE, MVT::Other, Expand); 834 835 if (Subtarget->getTargetTriple().isWindowsItaniumEnvironment()) 836 setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i32, Custom); 837 else 838 setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i32, Expand); 839 840 // ARMv6 Thumb1 (except for CPUs that support dmb / dsb) and earlier use 841 // the default expansion. If we are targeting a single threaded system, 842 // then set them all for expand so we can lower them later into their 843 // non-atomic form. 844 if (TM.Options.ThreadModel == ThreadModel::Single) 845 setOperationAction(ISD::ATOMIC_FENCE, MVT::Other, Expand); 846 else if (Subtarget->hasAnyDataBarrier() && !Subtarget->isThumb1Only()) { 847 // ATOMIC_FENCE needs custom lowering; the others should have been expanded 848 // to ldrex/strex loops already. 849 setOperationAction(ISD::ATOMIC_FENCE, MVT::Other, Custom); 850 851 // On v8, we have particularly efficient implementations of atomic fences 852 // if they can be combined with nearby atomic loads and stores. 853 if (!Subtarget->hasV8Ops()) { 854 // Automatically insert fences (dmb ish) around ATOMIC_SWAP etc. 855 setInsertFencesForAtomic(true); 856 } 857 } else { 858 // If there's anything we can use as a barrier, go through custom lowering 859 // for ATOMIC_FENCE. 860 setOperationAction(ISD::ATOMIC_FENCE, MVT::Other, 861 Subtarget->hasAnyDataBarrier() ? Custom : Expand); 862 863 // Set them all for expansion, which will force libcalls. 864 setOperationAction(ISD::ATOMIC_CMP_SWAP, MVT::i32, Expand); 865 setOperationAction(ISD::ATOMIC_SWAP, MVT::i32, Expand); 866 setOperationAction(ISD::ATOMIC_LOAD_ADD, MVT::i32, Expand); 867 setOperationAction(ISD::ATOMIC_LOAD_SUB, MVT::i32, Expand); 868 setOperationAction(ISD::ATOMIC_LOAD_AND, MVT::i32, Expand); 869 setOperationAction(ISD::ATOMIC_LOAD_OR, MVT::i32, Expand); 870 setOperationAction(ISD::ATOMIC_LOAD_XOR, MVT::i32, Expand); 871 setOperationAction(ISD::ATOMIC_LOAD_NAND, MVT::i32, Expand); 872 setOperationAction(ISD::ATOMIC_LOAD_MIN, MVT::i32, Expand); 873 setOperationAction(ISD::ATOMIC_LOAD_MAX, MVT::i32, Expand); 874 setOperationAction(ISD::ATOMIC_LOAD_UMIN, MVT::i32, Expand); 875 setOperationAction(ISD::ATOMIC_LOAD_UMAX, MVT::i32, Expand); 876 // Mark ATOMIC_LOAD and ATOMIC_STORE custom so we can handle the 877 // Unordered/Monotonic case. 878 setOperationAction(ISD::ATOMIC_LOAD, MVT::i32, Custom); 879 setOperationAction(ISD::ATOMIC_STORE, MVT::i32, Custom); 880 } 881 882 setOperationAction(ISD::PREFETCH, MVT::Other, Custom); 883 884 // Requires SXTB/SXTH, available on v6 and up in both ARM and Thumb modes. 885 if (!Subtarget->hasV6Ops()) { 886 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i16, Expand); 887 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i8, Expand); 888 } 889 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1, Expand); 890 891 if (!Subtarget->useSoftFloat() && Subtarget->hasVFP2() && 892 !Subtarget->isThumb1Only()) { 893 // Turn f64->i64 into VMOVRRD, i64 -> f64 to VMOVDRR 894 // iff target supports vfp2. 895 setOperationAction(ISD::BITCAST, MVT::i64, Custom); 896 setOperationAction(ISD::FLT_ROUNDS_, MVT::i32, Custom); 897 } 898 899 // We want to custom lower some of our intrinsics. 900 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom); 901 setOperationAction(ISD::EH_SJLJ_SETJMP, MVT::i32, Custom); 902 setOperationAction(ISD::EH_SJLJ_LONGJMP, MVT::Other, Custom); 903 setOperationAction(ISD::EH_SJLJ_SETUP_DISPATCH, MVT::Other, Custom); 904 if (Subtarget->useSjLjEH()) 905 setLibcallName(RTLIB::UNWIND_RESUME, "_Unwind_SjLj_Resume"); 906 907 setOperationAction(ISD::SETCC, MVT::i32, Expand); 908 setOperationAction(ISD::SETCC, MVT::f32, Expand); 909 setOperationAction(ISD::SETCC, MVT::f64, Expand); 910 setOperationAction(ISD::SELECT, MVT::i32, Custom); 911 setOperationAction(ISD::SELECT, MVT::f32, Custom); 912 setOperationAction(ISD::SELECT, MVT::f64, Custom); 913 setOperationAction(ISD::SELECT_CC, MVT::i32, Custom); 914 setOperationAction(ISD::SELECT_CC, MVT::f32, Custom); 915 setOperationAction(ISD::SELECT_CC, MVT::f64, Custom); 916 917 setOperationAction(ISD::BRCOND, MVT::Other, Expand); 918 setOperationAction(ISD::BR_CC, MVT::i32, Custom); 919 setOperationAction(ISD::BR_CC, MVT::f32, Custom); 920 setOperationAction(ISD::BR_CC, MVT::f64, Custom); 921 setOperationAction(ISD::BR_JT, MVT::Other, Custom); 922 923 // We don't support sin/cos/fmod/copysign/pow 924 setOperationAction(ISD::FSIN, MVT::f64, Expand); 925 setOperationAction(ISD::FSIN, MVT::f32, Expand); 926 setOperationAction(ISD::FCOS, MVT::f32, Expand); 927 setOperationAction(ISD::FCOS, MVT::f64, Expand); 928 setOperationAction(ISD::FSINCOS, MVT::f64, Expand); 929 setOperationAction(ISD::FSINCOS, MVT::f32, Expand); 930 setOperationAction(ISD::FREM, MVT::f64, Expand); 931 setOperationAction(ISD::FREM, MVT::f32, Expand); 932 if (!Subtarget->useSoftFloat() && Subtarget->hasVFP2() && 933 !Subtarget->isThumb1Only()) { 934 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Custom); 935 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom); 936 } 937 setOperationAction(ISD::FPOW, MVT::f64, Expand); 938 setOperationAction(ISD::FPOW, MVT::f32, Expand); 939 940 if (!Subtarget->hasVFP4()) { 941 setOperationAction(ISD::FMA, MVT::f64, Expand); 942 setOperationAction(ISD::FMA, MVT::f32, Expand); 943 } 944 945 // Various VFP goodness 946 if (!Subtarget->useSoftFloat() && !Subtarget->isThumb1Only()) { 947 // FP-ARMv8 adds f64 <-> f16 conversion. Before that it should be expanded. 948 if (!Subtarget->hasFPARMv8() || Subtarget->isFPOnlySP()) { 949 setOperationAction(ISD::FP16_TO_FP, MVT::f64, Expand); 950 setOperationAction(ISD::FP_TO_FP16, MVT::f64, Expand); 951 } 952 953 // fp16 is a special v7 extension that adds f16 <-> f32 conversions. 954 if (!Subtarget->hasFP16()) { 955 setOperationAction(ISD::FP16_TO_FP, MVT::f32, Expand); 956 setOperationAction(ISD::FP_TO_FP16, MVT::f32, Expand); 957 } 958 } 959 960 // Combine sin / cos into one node or libcall if possible. 961 if (Subtarget->hasSinCos()) { 962 setLibcallName(RTLIB::SINCOS_F32, "sincosf"); 963 setLibcallName(RTLIB::SINCOS_F64, "sincos"); 964 if (Subtarget->isTargetWatchOS()) { 965 setLibcallCallingConv(RTLIB::SINCOS_F32, CallingConv::ARM_AAPCS_VFP); 966 setLibcallCallingConv(RTLIB::SINCOS_F64, CallingConv::ARM_AAPCS_VFP); 967 } 968 if (Subtarget->isTargetIOS() || Subtarget->isTargetWatchOS()) { 969 // For iOS, we don't want to the normal expansion of a libcall to 970 // sincos. We want to issue a libcall to __sincos_stret. 971 setOperationAction(ISD::FSINCOS, MVT::f64, Custom); 972 setOperationAction(ISD::FSINCOS, MVT::f32, Custom); 973 } 974 } 975 976 // FP-ARMv8 implements a lot of rounding-like FP operations. 977 if (Subtarget->hasFPARMv8()) { 978 setOperationAction(ISD::FFLOOR, MVT::f32, Legal); 979 setOperationAction(ISD::FCEIL, MVT::f32, Legal); 980 setOperationAction(ISD::FROUND, MVT::f32, Legal); 981 setOperationAction(ISD::FTRUNC, MVT::f32, Legal); 982 setOperationAction(ISD::FNEARBYINT, MVT::f32, Legal); 983 setOperationAction(ISD::FRINT, MVT::f32, Legal); 984 setOperationAction(ISD::FMINNUM, MVT::f32, Legal); 985 setOperationAction(ISD::FMAXNUM, MVT::f32, Legal); 986 setOperationAction(ISD::FMINNUM, MVT::v2f32, Legal); 987 setOperationAction(ISD::FMAXNUM, MVT::v2f32, Legal); 988 setOperationAction(ISD::FMINNUM, MVT::v4f32, Legal); 989 setOperationAction(ISD::FMAXNUM, MVT::v4f32, Legal); 990 991 if (!Subtarget->isFPOnlySP()) { 992 setOperationAction(ISD::FFLOOR, MVT::f64, Legal); 993 setOperationAction(ISD::FCEIL, MVT::f64, Legal); 994 setOperationAction(ISD::FROUND, MVT::f64, Legal); 995 setOperationAction(ISD::FTRUNC, MVT::f64, Legal); 996 setOperationAction(ISD::FNEARBYINT, MVT::f64, Legal); 997 setOperationAction(ISD::FRINT, MVT::f64, Legal); 998 setOperationAction(ISD::FMINNUM, MVT::f64, Legal); 999 setOperationAction(ISD::FMAXNUM, MVT::f64, Legal); 1000 } 1001 } 1002 1003 if (Subtarget->hasNEON()) { 1004 // vmin and vmax aren't available in a scalar form, so we use 1005 // a NEON instruction with an undef lane instead. 1006 setOperationAction(ISD::FMINNAN, MVT::f32, Legal); 1007 setOperationAction(ISD::FMAXNAN, MVT::f32, Legal); 1008 setOperationAction(ISD::FMINNAN, MVT::v2f32, Legal); 1009 setOperationAction(ISD::FMAXNAN, MVT::v2f32, Legal); 1010 setOperationAction(ISD::FMINNAN, MVT::v4f32, Legal); 1011 setOperationAction(ISD::FMAXNAN, MVT::v4f32, Legal); 1012 } 1013 1014 // We have target-specific dag combine patterns for the following nodes: 1015 // ARMISD::VMOVRRD - No need to call setTargetDAGCombine 1016 setTargetDAGCombine(ISD::ADD); 1017 setTargetDAGCombine(ISD::SUB); 1018 setTargetDAGCombine(ISD::MUL); 1019 setTargetDAGCombine(ISD::AND); 1020 setTargetDAGCombine(ISD::OR); 1021 setTargetDAGCombine(ISD::XOR); 1022 1023 if (Subtarget->hasV6Ops()) 1024 setTargetDAGCombine(ISD::SRL); 1025 1026 setStackPointerRegisterToSaveRestore(ARM::SP); 1027 1028 if (Subtarget->useSoftFloat() || Subtarget->isThumb1Only() || 1029 !Subtarget->hasVFP2()) 1030 setSchedulingPreference(Sched::RegPressure); 1031 else 1032 setSchedulingPreference(Sched::Hybrid); 1033 1034 //// temporary - rewrite interface to use type 1035 MaxStoresPerMemset = 8; 1036 MaxStoresPerMemsetOptSize = 4; 1037 MaxStoresPerMemcpy = 4; // For @llvm.memcpy -> sequence of stores 1038 MaxStoresPerMemcpyOptSize = 2; 1039 MaxStoresPerMemmove = 4; // For @llvm.memmove -> sequence of stores 1040 MaxStoresPerMemmoveOptSize = 2; 1041 1042 // On ARM arguments smaller than 4 bytes are extended, so all arguments 1043 // are at least 4 bytes aligned. 1044 setMinStackArgumentAlignment(4); 1045 1046 // Prefer likely predicted branches to selects on out-of-order cores. 1047 PredictableSelectIsExpensive = Subtarget->isLikeA9(); 1048 1049 setMinFunctionAlignment(Subtarget->isThumb() ? 1 : 2); 1050 } 1051 1052 bool ARMTargetLowering::useSoftFloat() const { 1053 return Subtarget->useSoftFloat(); 1054 } 1055 1056 // FIXME: It might make sense to define the representative register class as the 1057 // nearest super-register that has a non-null superset. For example, DPR_VFP2 is 1058 // a super-register of SPR, and DPR is a superset if DPR_VFP2. Consequently, 1059 // SPR's representative would be DPR_VFP2. This should work well if register 1060 // pressure tracking were modified such that a register use would increment the 1061 // pressure of the register class's representative and all of it's super 1062 // classes' representatives transitively. We have not implemented this because 1063 // of the difficulty prior to coalescing of modeling operand register classes 1064 // due to the common occurrence of cross class copies and subregister insertions 1065 // and extractions. 1066 std::pair<const TargetRegisterClass *, uint8_t> 1067 ARMTargetLowering::findRepresentativeClass(const TargetRegisterInfo *TRI, 1068 MVT VT) const { 1069 const TargetRegisterClass *RRC = nullptr; 1070 uint8_t Cost = 1; 1071 switch (VT.SimpleTy) { 1072 default: 1073 return TargetLowering::findRepresentativeClass(TRI, VT); 1074 // Use DPR as representative register class for all floating point 1075 // and vector types. Since there are 32 SPR registers and 32 DPR registers so 1076 // the cost is 1 for both f32 and f64. 1077 case MVT::f32: case MVT::f64: case MVT::v8i8: case MVT::v4i16: 1078 case MVT::v2i32: case MVT::v1i64: case MVT::v2f32: 1079 RRC = &ARM::DPRRegClass; 1080 // When NEON is used for SP, only half of the register file is available 1081 // because operations that define both SP and DP results will be constrained 1082 // to the VFP2 class (D0-D15). We currently model this constraint prior to 1083 // coalescing by double-counting the SP regs. See the FIXME above. 1084 if (Subtarget->useNEONForSinglePrecisionFP()) 1085 Cost = 2; 1086 break; 1087 case MVT::v16i8: case MVT::v8i16: case MVT::v4i32: case MVT::v2i64: 1088 case MVT::v4f32: case MVT::v2f64: 1089 RRC = &ARM::DPRRegClass; 1090 Cost = 2; 1091 break; 1092 case MVT::v4i64: 1093 RRC = &ARM::DPRRegClass; 1094 Cost = 4; 1095 break; 1096 case MVT::v8i64: 1097 RRC = &ARM::DPRRegClass; 1098 Cost = 8; 1099 break; 1100 } 1101 return std::make_pair(RRC, Cost); 1102 } 1103 1104 const char *ARMTargetLowering::getTargetNodeName(unsigned Opcode) const { 1105 switch ((ARMISD::NodeType)Opcode) { 1106 case ARMISD::FIRST_NUMBER: break; 1107 case ARMISD::Wrapper: return "ARMISD::Wrapper"; 1108 case ARMISD::WrapperPIC: return "ARMISD::WrapperPIC"; 1109 case ARMISD::WrapperJT: return "ARMISD::WrapperJT"; 1110 case ARMISD::COPY_STRUCT_BYVAL: return "ARMISD::COPY_STRUCT_BYVAL"; 1111 case ARMISD::CALL: return "ARMISD::CALL"; 1112 case ARMISD::CALL_PRED: return "ARMISD::CALL_PRED"; 1113 case ARMISD::CALL_NOLINK: return "ARMISD::CALL_NOLINK"; 1114 case ARMISD::tCALL: return "ARMISD::tCALL"; 1115 case ARMISD::BRCOND: return "ARMISD::BRCOND"; 1116 case ARMISD::BR_JT: return "ARMISD::BR_JT"; 1117 case ARMISD::BR2_JT: return "ARMISD::BR2_JT"; 1118 case ARMISD::RET_FLAG: return "ARMISD::RET_FLAG"; 1119 case ARMISD::INTRET_FLAG: return "ARMISD::INTRET_FLAG"; 1120 case ARMISD::PIC_ADD: return "ARMISD::PIC_ADD"; 1121 case ARMISD::CMP: return "ARMISD::CMP"; 1122 case ARMISD::CMN: return "ARMISD::CMN"; 1123 case ARMISD::CMPZ: return "ARMISD::CMPZ"; 1124 case ARMISD::CMPFP: return "ARMISD::CMPFP"; 1125 case ARMISD::CMPFPw0: return "ARMISD::CMPFPw0"; 1126 case ARMISD::BCC_i64: return "ARMISD::BCC_i64"; 1127 case ARMISD::FMSTAT: return "ARMISD::FMSTAT"; 1128 1129 case ARMISD::CMOV: return "ARMISD::CMOV"; 1130 1131 case ARMISD::SRL_FLAG: return "ARMISD::SRL_FLAG"; 1132 case ARMISD::SRA_FLAG: return "ARMISD::SRA_FLAG"; 1133 case ARMISD::RRX: return "ARMISD::RRX"; 1134 1135 case ARMISD::ADDC: return "ARMISD::ADDC"; 1136 case ARMISD::ADDE: return "ARMISD::ADDE"; 1137 case ARMISD::SUBC: return "ARMISD::SUBC"; 1138 case ARMISD::SUBE: return "ARMISD::SUBE"; 1139 1140 case ARMISD::VMOVRRD: return "ARMISD::VMOVRRD"; 1141 case ARMISD::VMOVDRR: return "ARMISD::VMOVDRR"; 1142 1143 case ARMISD::EH_SJLJ_SETJMP: return "ARMISD::EH_SJLJ_SETJMP"; 1144 case ARMISD::EH_SJLJ_LONGJMP: return "ARMISD::EH_SJLJ_LONGJMP"; 1145 case ARMISD::EH_SJLJ_SETUP_DISPATCH: return "ARMISD::EH_SJLJ_SETUP_DISPATCH"; 1146 1147 case ARMISD::TC_RETURN: return "ARMISD::TC_RETURN"; 1148 1149 case ARMISD::THREAD_POINTER:return "ARMISD::THREAD_POINTER"; 1150 1151 case ARMISD::DYN_ALLOC: return "ARMISD::DYN_ALLOC"; 1152 1153 case ARMISD::MEMBARRIER_MCR: return "ARMISD::MEMBARRIER_MCR"; 1154 1155 case ARMISD::PRELOAD: return "ARMISD::PRELOAD"; 1156 1157 case ARMISD::WIN__CHKSTK: return "ARMISD:::WIN__CHKSTK"; 1158 case ARMISD::WIN__DBZCHK: return "ARMISD::WIN__DBZCHK"; 1159 1160 case ARMISD::VCEQ: return "ARMISD::VCEQ"; 1161 case ARMISD::VCEQZ: return "ARMISD::VCEQZ"; 1162 case ARMISD::VCGE: return "ARMISD::VCGE"; 1163 case ARMISD::VCGEZ: return "ARMISD::VCGEZ"; 1164 case ARMISD::VCLEZ: return "ARMISD::VCLEZ"; 1165 case ARMISD::VCGEU: return "ARMISD::VCGEU"; 1166 case ARMISD::VCGT: return "ARMISD::VCGT"; 1167 case ARMISD::VCGTZ: return "ARMISD::VCGTZ"; 1168 case ARMISD::VCLTZ: return "ARMISD::VCLTZ"; 1169 case ARMISD::VCGTU: return "ARMISD::VCGTU"; 1170 case ARMISD::VTST: return "ARMISD::VTST"; 1171 1172 case ARMISD::VSHL: return "ARMISD::VSHL"; 1173 case ARMISD::VSHRs: return "ARMISD::VSHRs"; 1174 case ARMISD::VSHRu: return "ARMISD::VSHRu"; 1175 case ARMISD::VRSHRs: return "ARMISD::VRSHRs"; 1176 case ARMISD::VRSHRu: return "ARMISD::VRSHRu"; 1177 case ARMISD::VRSHRN: return "ARMISD::VRSHRN"; 1178 case ARMISD::VQSHLs: return "ARMISD::VQSHLs"; 1179 case ARMISD::VQSHLu: return "ARMISD::VQSHLu"; 1180 case ARMISD::VQSHLsu: return "ARMISD::VQSHLsu"; 1181 case ARMISD::VQSHRNs: return "ARMISD::VQSHRNs"; 1182 case ARMISD::VQSHRNu: return "ARMISD::VQSHRNu"; 1183 case ARMISD::VQSHRNsu: return "ARMISD::VQSHRNsu"; 1184 case ARMISD::VQRSHRNs: return "ARMISD::VQRSHRNs"; 1185 case ARMISD::VQRSHRNu: return "ARMISD::VQRSHRNu"; 1186 case ARMISD::VQRSHRNsu: return "ARMISD::VQRSHRNsu"; 1187 case ARMISD::VSLI: return "ARMISD::VSLI"; 1188 case ARMISD::VSRI: return "ARMISD::VSRI"; 1189 case ARMISD::VGETLANEu: return "ARMISD::VGETLANEu"; 1190 case ARMISD::VGETLANEs: return "ARMISD::VGETLANEs"; 1191 case ARMISD::VMOVIMM: return "ARMISD::VMOVIMM"; 1192 case ARMISD::VMVNIMM: return "ARMISD::VMVNIMM"; 1193 case ARMISD::VMOVFPIMM: return "ARMISD::VMOVFPIMM"; 1194 case ARMISD::VDUP: return "ARMISD::VDUP"; 1195 case ARMISD::VDUPLANE: return "ARMISD::VDUPLANE"; 1196 case ARMISD::VEXT: return "ARMISD::VEXT"; 1197 case ARMISD::VREV64: return "ARMISD::VREV64"; 1198 case ARMISD::VREV32: return "ARMISD::VREV32"; 1199 case ARMISD::VREV16: return "ARMISD::VREV16"; 1200 case ARMISD::VZIP: return "ARMISD::VZIP"; 1201 case ARMISD::VUZP: return "ARMISD::VUZP"; 1202 case ARMISD::VTRN: return "ARMISD::VTRN"; 1203 case ARMISD::VTBL1: return "ARMISD::VTBL1"; 1204 case ARMISD::VTBL2: return "ARMISD::VTBL2"; 1205 case ARMISD::VMULLs: return "ARMISD::VMULLs"; 1206 case ARMISD::VMULLu: return "ARMISD::VMULLu"; 1207 case ARMISD::UMLAL: return "ARMISD::UMLAL"; 1208 case ARMISD::SMLAL: return "ARMISD::SMLAL"; 1209 case ARMISD::BUILD_VECTOR: return "ARMISD::BUILD_VECTOR"; 1210 case ARMISD::BFI: return "ARMISD::BFI"; 1211 case ARMISD::VORRIMM: return "ARMISD::VORRIMM"; 1212 case ARMISD::VBICIMM: return "ARMISD::VBICIMM"; 1213 case ARMISD::VBSL: return "ARMISD::VBSL"; 1214 case ARMISD::MEMCPY: return "ARMISD::MEMCPY"; 1215 case ARMISD::VLD2DUP: return "ARMISD::VLD2DUP"; 1216 case ARMISD::VLD3DUP: return "ARMISD::VLD3DUP"; 1217 case ARMISD::VLD4DUP: return "ARMISD::VLD4DUP"; 1218 case ARMISD::VLD1_UPD: return "ARMISD::VLD1_UPD"; 1219 case ARMISD::VLD2_UPD: return "ARMISD::VLD2_UPD"; 1220 case ARMISD::VLD3_UPD: return "ARMISD::VLD3_UPD"; 1221 case ARMISD::VLD4_UPD: return "ARMISD::VLD4_UPD"; 1222 case ARMISD::VLD2LN_UPD: return "ARMISD::VLD2LN_UPD"; 1223 case ARMISD::VLD3LN_UPD: return "ARMISD::VLD3LN_UPD"; 1224 case ARMISD::VLD4LN_UPD: return "ARMISD::VLD4LN_UPD"; 1225 case ARMISD::VLD2DUP_UPD: return "ARMISD::VLD2DUP_UPD"; 1226 case ARMISD::VLD3DUP_UPD: return "ARMISD::VLD3DUP_UPD"; 1227 case ARMISD::VLD4DUP_UPD: return "ARMISD::VLD4DUP_UPD"; 1228 case ARMISD::VST1_UPD: return "ARMISD::VST1_UPD"; 1229 case ARMISD::VST2_UPD: return "ARMISD::VST2_UPD"; 1230 case ARMISD::VST3_UPD: return "ARMISD::VST3_UPD"; 1231 case ARMISD::VST4_UPD: return "ARMISD::VST4_UPD"; 1232 case ARMISD::VST2LN_UPD: return "ARMISD::VST2LN_UPD"; 1233 case ARMISD::VST3LN_UPD: return "ARMISD::VST3LN_UPD"; 1234 case ARMISD::VST4LN_UPD: return "ARMISD::VST4LN_UPD"; 1235 } 1236 return nullptr; 1237 } 1238 1239 EVT ARMTargetLowering::getSetCCResultType(const DataLayout &DL, LLVMContext &, 1240 EVT VT) const { 1241 if (!VT.isVector()) 1242 return getPointerTy(DL); 1243 return VT.changeVectorElementTypeToInteger(); 1244 } 1245 1246 /// getRegClassFor - Return the register class that should be used for the 1247 /// specified value type. 1248 const TargetRegisterClass *ARMTargetLowering::getRegClassFor(MVT VT) const { 1249 // Map v4i64 to QQ registers but do not make the type legal. Similarly map 1250 // v8i64 to QQQQ registers. v4i64 and v8i64 are only used for REG_SEQUENCE to 1251 // load / store 4 to 8 consecutive D registers. 1252 if (Subtarget->hasNEON()) { 1253 if (VT == MVT::v4i64) 1254 return &ARM::QQPRRegClass; 1255 if (VT == MVT::v8i64) 1256 return &ARM::QQQQPRRegClass; 1257 } 1258 return TargetLowering::getRegClassFor(VT); 1259 } 1260 1261 // memcpy, and other memory intrinsics, typically tries to use LDM/STM if the 1262 // source/dest is aligned and the copy size is large enough. We therefore want 1263 // to align such objects passed to memory intrinsics. 1264 bool ARMTargetLowering::shouldAlignPointerArgs(CallInst *CI, unsigned &MinSize, 1265 unsigned &PrefAlign) const { 1266 if (!isa<MemIntrinsic>(CI)) 1267 return false; 1268 MinSize = 8; 1269 // On ARM11 onwards (excluding M class) 8-byte aligned LDM is typically 1 1270 // cycle faster than 4-byte aligned LDM. 1271 PrefAlign = (Subtarget->hasV6Ops() && !Subtarget->isMClass() ? 8 : 4); 1272 return true; 1273 } 1274 1275 // Create a fast isel object. 1276 FastISel * 1277 ARMTargetLowering::createFastISel(FunctionLoweringInfo &funcInfo, 1278 const TargetLibraryInfo *libInfo) const { 1279 return ARM::createFastISel(funcInfo, libInfo); 1280 } 1281 1282 Sched::Preference ARMTargetLowering::getSchedulingPreference(SDNode *N) const { 1283 unsigned NumVals = N->getNumValues(); 1284 if (!NumVals) 1285 return Sched::RegPressure; 1286 1287 for (unsigned i = 0; i != NumVals; ++i) { 1288 EVT VT = N->getValueType(i); 1289 if (VT == MVT::Glue || VT == MVT::Other) 1290 continue; 1291 if (VT.isFloatingPoint() || VT.isVector()) 1292 return Sched::ILP; 1293 } 1294 1295 if (!N->isMachineOpcode()) 1296 return Sched::RegPressure; 1297 1298 // Load are scheduled for latency even if there instruction itinerary 1299 // is not available. 1300 const TargetInstrInfo *TII = Subtarget->getInstrInfo(); 1301 const MCInstrDesc &MCID = TII->get(N->getMachineOpcode()); 1302 1303 if (MCID.getNumDefs() == 0) 1304 return Sched::RegPressure; 1305 if (!Itins->isEmpty() && 1306 Itins->getOperandCycle(MCID.getSchedClass(), 0) > 2) 1307 return Sched::ILP; 1308 1309 return Sched::RegPressure; 1310 } 1311 1312 //===----------------------------------------------------------------------===// 1313 // Lowering Code 1314 //===----------------------------------------------------------------------===// 1315 1316 /// IntCCToARMCC - Convert a DAG integer condition code to an ARM CC 1317 static ARMCC::CondCodes IntCCToARMCC(ISD::CondCode CC) { 1318 switch (CC) { 1319 default: llvm_unreachable("Unknown condition code!"); 1320 case ISD::SETNE: return ARMCC::NE; 1321 case ISD::SETEQ: return ARMCC::EQ; 1322 case ISD::SETGT: return ARMCC::GT; 1323 case ISD::SETGE: return ARMCC::GE; 1324 case ISD::SETLT: return ARMCC::LT; 1325 case ISD::SETLE: return ARMCC::LE; 1326 case ISD::SETUGT: return ARMCC::HI; 1327 case ISD::SETUGE: return ARMCC::HS; 1328 case ISD::SETULT: return ARMCC::LO; 1329 case ISD::SETULE: return ARMCC::LS; 1330 } 1331 } 1332 1333 /// FPCCToARMCC - Convert a DAG fp condition code to an ARM CC. 1334 static void FPCCToARMCC(ISD::CondCode CC, ARMCC::CondCodes &CondCode, 1335 ARMCC::CondCodes &CondCode2) { 1336 CondCode2 = ARMCC::AL; 1337 switch (CC) { 1338 default: llvm_unreachable("Unknown FP condition!"); 1339 case ISD::SETEQ: 1340 case ISD::SETOEQ: CondCode = ARMCC::EQ; break; 1341 case ISD::SETGT: 1342 case ISD::SETOGT: CondCode = ARMCC::GT; break; 1343 case ISD::SETGE: 1344 case ISD::SETOGE: CondCode = ARMCC::GE; break; 1345 case ISD::SETOLT: CondCode = ARMCC::MI; break; 1346 case ISD::SETOLE: CondCode = ARMCC::LS; break; 1347 case ISD::SETONE: CondCode = ARMCC::MI; CondCode2 = ARMCC::GT; break; 1348 case ISD::SETO: CondCode = ARMCC::VC; break; 1349 case ISD::SETUO: CondCode = ARMCC::VS; break; 1350 case ISD::SETUEQ: CondCode = ARMCC::EQ; CondCode2 = ARMCC::VS; break; 1351 case ISD::SETUGT: CondCode = ARMCC::HI; break; 1352 case ISD::SETUGE: CondCode = ARMCC::PL; break; 1353 case ISD::SETLT: 1354 case ISD::SETULT: CondCode = ARMCC::LT; break; 1355 case ISD::SETLE: 1356 case ISD::SETULE: CondCode = ARMCC::LE; break; 1357 case ISD::SETNE: 1358 case ISD::SETUNE: CondCode = ARMCC::NE; break; 1359 } 1360 } 1361 1362 //===----------------------------------------------------------------------===// 1363 // Calling Convention Implementation 1364 //===----------------------------------------------------------------------===// 1365 1366 #include "ARMGenCallingConv.inc" 1367 1368 /// getEffectiveCallingConv - Get the effective calling convention, taking into 1369 /// account presence of floating point hardware and calling convention 1370 /// limitations, such as support for variadic functions. 1371 CallingConv::ID 1372 ARMTargetLowering::getEffectiveCallingConv(CallingConv::ID CC, 1373 bool isVarArg) const { 1374 switch (CC) { 1375 default: 1376 llvm_unreachable("Unsupported calling convention"); 1377 case CallingConv::ARM_AAPCS: 1378 case CallingConv::ARM_APCS: 1379 case CallingConv::GHC: 1380 return CC; 1381 case CallingConv::ARM_AAPCS_VFP: 1382 return isVarArg ? CallingConv::ARM_AAPCS : CallingConv::ARM_AAPCS_VFP; 1383 case CallingConv::C: 1384 if (!Subtarget->isAAPCS_ABI()) 1385 return CallingConv::ARM_APCS; 1386 else if (Subtarget->hasVFP2() && !Subtarget->isThumb1Only() && 1387 getTargetMachine().Options.FloatABIType == FloatABI::Hard && 1388 !isVarArg) 1389 return CallingConv::ARM_AAPCS_VFP; 1390 else 1391 return CallingConv::ARM_AAPCS; 1392 case CallingConv::Fast: 1393 if (!Subtarget->isAAPCS_ABI()) { 1394 if (Subtarget->hasVFP2() && !Subtarget->isThumb1Only() && !isVarArg) 1395 return CallingConv::Fast; 1396 return CallingConv::ARM_APCS; 1397 } else if (Subtarget->hasVFP2() && !Subtarget->isThumb1Only() && !isVarArg) 1398 return CallingConv::ARM_AAPCS_VFP; 1399 else 1400 return CallingConv::ARM_AAPCS; 1401 } 1402 } 1403 1404 /// CCAssignFnForNode - Selects the correct CCAssignFn for the given 1405 /// CallingConvention. 1406 CCAssignFn *ARMTargetLowering::CCAssignFnForNode(CallingConv::ID CC, 1407 bool Return, 1408 bool isVarArg) const { 1409 switch (getEffectiveCallingConv(CC, isVarArg)) { 1410 default: 1411 llvm_unreachable("Unsupported calling convention"); 1412 case CallingConv::ARM_APCS: 1413 return (Return ? RetCC_ARM_APCS : CC_ARM_APCS); 1414 case CallingConv::ARM_AAPCS: 1415 return (Return ? RetCC_ARM_AAPCS : CC_ARM_AAPCS); 1416 case CallingConv::ARM_AAPCS_VFP: 1417 return (Return ? RetCC_ARM_AAPCS_VFP : CC_ARM_AAPCS_VFP); 1418 case CallingConv::Fast: 1419 return (Return ? RetFastCC_ARM_APCS : FastCC_ARM_APCS); 1420 case CallingConv::GHC: 1421 return (Return ? RetCC_ARM_APCS : CC_ARM_APCS_GHC); 1422 } 1423 } 1424 1425 /// LowerCallResult - Lower the result values of a call into the 1426 /// appropriate copies out of appropriate physical registers. 1427 SDValue 1428 ARMTargetLowering::LowerCallResult(SDValue Chain, SDValue InFlag, 1429 CallingConv::ID CallConv, bool isVarArg, 1430 const SmallVectorImpl<ISD::InputArg> &Ins, 1431 SDLoc dl, SelectionDAG &DAG, 1432 SmallVectorImpl<SDValue> &InVals, 1433 bool isThisReturn, SDValue ThisVal) const { 1434 1435 // Assign locations to each value returned by this call. 1436 SmallVector<CCValAssign, 16> RVLocs; 1437 ARMCCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs, 1438 *DAG.getContext(), Call); 1439 CCInfo.AnalyzeCallResult(Ins, 1440 CCAssignFnForNode(CallConv, /* Return*/ true, 1441 isVarArg)); 1442 1443 // Copy all of the result registers out of their specified physreg. 1444 for (unsigned i = 0; i != RVLocs.size(); ++i) { 1445 CCValAssign VA = RVLocs[i]; 1446 1447 // Pass 'this' value directly from the argument to return value, to avoid 1448 // reg unit interference 1449 if (i == 0 && isThisReturn) { 1450 assert(!VA.needsCustom() && VA.getLocVT() == MVT::i32 && 1451 "unexpected return calling convention register assignment"); 1452 InVals.push_back(ThisVal); 1453 continue; 1454 } 1455 1456 SDValue Val; 1457 if (VA.needsCustom()) { 1458 // Handle f64 or half of a v2f64. 1459 SDValue Lo = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32, 1460 InFlag); 1461 Chain = Lo.getValue(1); 1462 InFlag = Lo.getValue(2); 1463 VA = RVLocs[++i]; // skip ahead to next loc 1464 SDValue Hi = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32, 1465 InFlag); 1466 Chain = Hi.getValue(1); 1467 InFlag = Hi.getValue(2); 1468 if (!Subtarget->isLittle()) 1469 std::swap (Lo, Hi); 1470 Val = DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi); 1471 1472 if (VA.getLocVT() == MVT::v2f64) { 1473 SDValue Vec = DAG.getNode(ISD::UNDEF, dl, MVT::v2f64); 1474 Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Vec, Val, 1475 DAG.getConstant(0, dl, MVT::i32)); 1476 1477 VA = RVLocs[++i]; // skip ahead to next loc 1478 Lo = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32, InFlag); 1479 Chain = Lo.getValue(1); 1480 InFlag = Lo.getValue(2); 1481 VA = RVLocs[++i]; // skip ahead to next loc 1482 Hi = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32, InFlag); 1483 Chain = Hi.getValue(1); 1484 InFlag = Hi.getValue(2); 1485 if (!Subtarget->isLittle()) 1486 std::swap (Lo, Hi); 1487 Val = DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi); 1488 Val = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Vec, Val, 1489 DAG.getConstant(1, dl, MVT::i32)); 1490 } 1491 } else { 1492 Val = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), VA.getLocVT(), 1493 InFlag); 1494 Chain = Val.getValue(1); 1495 InFlag = Val.getValue(2); 1496 } 1497 1498 switch (VA.getLocInfo()) { 1499 default: llvm_unreachable("Unknown loc info!"); 1500 case CCValAssign::Full: break; 1501 case CCValAssign::BCvt: 1502 Val = DAG.getNode(ISD::BITCAST, dl, VA.getValVT(), Val); 1503 break; 1504 } 1505 1506 InVals.push_back(Val); 1507 } 1508 1509 return Chain; 1510 } 1511 1512 /// LowerMemOpCallTo - Store the argument to the stack. 1513 SDValue 1514 ARMTargetLowering::LowerMemOpCallTo(SDValue Chain, 1515 SDValue StackPtr, SDValue Arg, 1516 SDLoc dl, SelectionDAG &DAG, 1517 const CCValAssign &VA, 1518 ISD::ArgFlagsTy Flags) const { 1519 unsigned LocMemOffset = VA.getLocMemOffset(); 1520 SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset, dl); 1521 PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(DAG.getDataLayout()), 1522 StackPtr, PtrOff); 1523 return DAG.getStore( 1524 Chain, dl, Arg, PtrOff, 1525 MachinePointerInfo::getStack(DAG.getMachineFunction(), LocMemOffset), 1526 false, false, 0); 1527 } 1528 1529 void ARMTargetLowering::PassF64ArgInRegs(SDLoc dl, SelectionDAG &DAG, 1530 SDValue Chain, SDValue &Arg, 1531 RegsToPassVector &RegsToPass, 1532 CCValAssign &VA, CCValAssign &NextVA, 1533 SDValue &StackPtr, 1534 SmallVectorImpl<SDValue> &MemOpChains, 1535 ISD::ArgFlagsTy Flags) const { 1536 1537 SDValue fmrrd = DAG.getNode(ARMISD::VMOVRRD, dl, 1538 DAG.getVTList(MVT::i32, MVT::i32), Arg); 1539 unsigned id = Subtarget->isLittle() ? 0 : 1; 1540 RegsToPass.push_back(std::make_pair(VA.getLocReg(), fmrrd.getValue(id))); 1541 1542 if (NextVA.isRegLoc()) 1543 RegsToPass.push_back(std::make_pair(NextVA.getLocReg(), fmrrd.getValue(1-id))); 1544 else { 1545 assert(NextVA.isMemLoc()); 1546 if (!StackPtr.getNode()) 1547 StackPtr = DAG.getCopyFromReg(Chain, dl, ARM::SP, 1548 getPointerTy(DAG.getDataLayout())); 1549 1550 MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, fmrrd.getValue(1-id), 1551 dl, DAG, NextVA, 1552 Flags)); 1553 } 1554 } 1555 1556 /// LowerCall - Lowering a call into a callseq_start <- 1557 /// ARMISD:CALL <- callseq_end chain. Also add input and output parameter 1558 /// nodes. 1559 SDValue 1560 ARMTargetLowering::LowerCall(TargetLowering::CallLoweringInfo &CLI, 1561 SmallVectorImpl<SDValue> &InVals) const { 1562 SelectionDAG &DAG = CLI.DAG; 1563 SDLoc &dl = CLI.DL; 1564 SmallVectorImpl<ISD::OutputArg> &Outs = CLI.Outs; 1565 SmallVectorImpl<SDValue> &OutVals = CLI.OutVals; 1566 SmallVectorImpl<ISD::InputArg> &Ins = CLI.Ins; 1567 SDValue Chain = CLI.Chain; 1568 SDValue Callee = CLI.Callee; 1569 bool &isTailCall = CLI.IsTailCall; 1570 CallingConv::ID CallConv = CLI.CallConv; 1571 bool doesNotRet = CLI.DoesNotReturn; 1572 bool isVarArg = CLI.IsVarArg; 1573 1574 MachineFunction &MF = DAG.getMachineFunction(); 1575 bool isStructRet = (Outs.empty()) ? false : Outs[0].Flags.isSRet(); 1576 bool isThisReturn = false; 1577 bool isSibCall = false; 1578 auto Attr = MF.getFunction()->getFnAttribute("disable-tail-calls"); 1579 1580 // Disable tail calls if they're not supported. 1581 if (!Subtarget->supportsTailCall() || Attr.getValueAsString() == "true") 1582 isTailCall = false; 1583 1584 if (isTailCall) { 1585 // Check if it's really possible to do a tail call. 1586 isTailCall = IsEligibleForTailCallOptimization(Callee, CallConv, 1587 isVarArg, isStructRet, MF.getFunction()->hasStructRetAttr(), 1588 Outs, OutVals, Ins, DAG); 1589 if (!isTailCall && CLI.CS && CLI.CS->isMustTailCall()) 1590 report_fatal_error("failed to perform tail call elimination on a call " 1591 "site marked musttail"); 1592 // We don't support GuaranteedTailCallOpt for ARM, only automatically 1593 // detected sibcalls. 1594 if (isTailCall) { 1595 ++NumTailCalls; 1596 isSibCall = true; 1597 } 1598 } 1599 1600 // Analyze operands of the call, assigning locations to each operand. 1601 SmallVector<CCValAssign, 16> ArgLocs; 1602 ARMCCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), ArgLocs, 1603 *DAG.getContext(), Call); 1604 CCInfo.AnalyzeCallOperands(Outs, 1605 CCAssignFnForNode(CallConv, /* Return*/ false, 1606 isVarArg)); 1607 1608 // Get a count of how many bytes are to be pushed on the stack. 1609 unsigned NumBytes = CCInfo.getNextStackOffset(); 1610 1611 // For tail calls, memory operands are available in our caller's stack. 1612 if (isSibCall) 1613 NumBytes = 0; 1614 1615 // Adjust the stack pointer for the new arguments... 1616 // These operations are automatically eliminated by the prolog/epilog pass 1617 if (!isSibCall) 1618 Chain = DAG.getCALLSEQ_START(Chain, 1619 DAG.getIntPtrConstant(NumBytes, dl, true), dl); 1620 1621 SDValue StackPtr = 1622 DAG.getCopyFromReg(Chain, dl, ARM::SP, getPointerTy(DAG.getDataLayout())); 1623 1624 RegsToPassVector RegsToPass; 1625 SmallVector<SDValue, 8> MemOpChains; 1626 1627 // Walk the register/memloc assignments, inserting copies/loads. In the case 1628 // of tail call optimization, arguments are handled later. 1629 for (unsigned i = 0, realArgIdx = 0, e = ArgLocs.size(); 1630 i != e; 1631 ++i, ++realArgIdx) { 1632 CCValAssign &VA = ArgLocs[i]; 1633 SDValue Arg = OutVals[realArgIdx]; 1634 ISD::ArgFlagsTy Flags = Outs[realArgIdx].Flags; 1635 bool isByVal = Flags.isByVal(); 1636 1637 // Promote the value if needed. 1638 switch (VA.getLocInfo()) { 1639 default: llvm_unreachable("Unknown loc info!"); 1640 case CCValAssign::Full: break; 1641 case CCValAssign::SExt: 1642 Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), Arg); 1643 break; 1644 case CCValAssign::ZExt: 1645 Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, VA.getLocVT(), Arg); 1646 break; 1647 case CCValAssign::AExt: 1648 Arg = DAG.getNode(ISD::ANY_EXTEND, dl, VA.getLocVT(), Arg); 1649 break; 1650 case CCValAssign::BCvt: 1651 Arg = DAG.getNode(ISD::BITCAST, dl, VA.getLocVT(), Arg); 1652 break; 1653 } 1654 1655 // f64 and v2f64 might be passed in i32 pairs and must be split into pieces 1656 if (VA.needsCustom()) { 1657 if (VA.getLocVT() == MVT::v2f64) { 1658 SDValue Op0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg, 1659 DAG.getConstant(0, dl, MVT::i32)); 1660 SDValue Op1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg, 1661 DAG.getConstant(1, dl, MVT::i32)); 1662 1663 PassF64ArgInRegs(dl, DAG, Chain, Op0, RegsToPass, 1664 VA, ArgLocs[++i], StackPtr, MemOpChains, Flags); 1665 1666 VA = ArgLocs[++i]; // skip ahead to next loc 1667 if (VA.isRegLoc()) { 1668 PassF64ArgInRegs(dl, DAG, Chain, Op1, RegsToPass, 1669 VA, ArgLocs[++i], StackPtr, MemOpChains, Flags); 1670 } else { 1671 assert(VA.isMemLoc()); 1672 1673 MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, Op1, 1674 dl, DAG, VA, Flags)); 1675 } 1676 } else { 1677 PassF64ArgInRegs(dl, DAG, Chain, Arg, RegsToPass, VA, ArgLocs[++i], 1678 StackPtr, MemOpChains, Flags); 1679 } 1680 } else if (VA.isRegLoc()) { 1681 if (realArgIdx == 0 && Flags.isReturned() && Outs[0].VT == MVT::i32) { 1682 assert(VA.getLocVT() == MVT::i32 && 1683 "unexpected calling convention register assignment"); 1684 assert(!Ins.empty() && Ins[0].VT == MVT::i32 && 1685 "unexpected use of 'returned'"); 1686 isThisReturn = true; 1687 } 1688 RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg)); 1689 } else if (isByVal) { 1690 assert(VA.isMemLoc()); 1691 unsigned offset = 0; 1692 1693 // True if this byval aggregate will be split between registers 1694 // and memory. 1695 unsigned ByValArgsCount = CCInfo.getInRegsParamsCount(); 1696 unsigned CurByValIdx = CCInfo.getInRegsParamsProcessed(); 1697 1698 if (CurByValIdx < ByValArgsCount) { 1699 1700 unsigned RegBegin, RegEnd; 1701 CCInfo.getInRegsParamInfo(CurByValIdx, RegBegin, RegEnd); 1702 1703 EVT PtrVT = 1704 DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout()); 1705 unsigned int i, j; 1706 for (i = 0, j = RegBegin; j < RegEnd; i++, j++) { 1707 SDValue Const = DAG.getConstant(4*i, dl, MVT::i32); 1708 SDValue AddArg = DAG.getNode(ISD::ADD, dl, PtrVT, Arg, Const); 1709 SDValue Load = DAG.getLoad(PtrVT, dl, Chain, AddArg, 1710 MachinePointerInfo(), 1711 false, false, false, 1712 DAG.InferPtrAlignment(AddArg)); 1713 MemOpChains.push_back(Load.getValue(1)); 1714 RegsToPass.push_back(std::make_pair(j, Load)); 1715 } 1716 1717 // If parameter size outsides register area, "offset" value 1718 // helps us to calculate stack slot for remained part properly. 1719 offset = RegEnd - RegBegin; 1720 1721 CCInfo.nextInRegsParam(); 1722 } 1723 1724 if (Flags.getByValSize() > 4*offset) { 1725 auto PtrVT = getPointerTy(DAG.getDataLayout()); 1726 unsigned LocMemOffset = VA.getLocMemOffset(); 1727 SDValue StkPtrOff = DAG.getIntPtrConstant(LocMemOffset, dl); 1728 SDValue Dst = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, StkPtrOff); 1729 SDValue SrcOffset = DAG.getIntPtrConstant(4*offset, dl); 1730 SDValue Src = DAG.getNode(ISD::ADD, dl, PtrVT, Arg, SrcOffset); 1731 SDValue SizeNode = DAG.getConstant(Flags.getByValSize() - 4*offset, dl, 1732 MVT::i32); 1733 SDValue AlignNode = DAG.getConstant(Flags.getByValAlign(), dl, 1734 MVT::i32); 1735 1736 SDVTList VTs = DAG.getVTList(MVT::Other, MVT::Glue); 1737 SDValue Ops[] = { Chain, Dst, Src, SizeNode, AlignNode}; 1738 MemOpChains.push_back(DAG.getNode(ARMISD::COPY_STRUCT_BYVAL, dl, VTs, 1739 Ops)); 1740 } 1741 } else if (!isSibCall) { 1742 assert(VA.isMemLoc()); 1743 1744 MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, Arg, 1745 dl, DAG, VA, Flags)); 1746 } 1747 } 1748 1749 if (!MemOpChains.empty()) 1750 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains); 1751 1752 // Build a sequence of copy-to-reg nodes chained together with token chain 1753 // and flag operands which copy the outgoing args into the appropriate regs. 1754 SDValue InFlag; 1755 // Tail call byval lowering might overwrite argument registers so in case of 1756 // tail call optimization the copies to registers are lowered later. 1757 if (!isTailCall) 1758 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) { 1759 Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first, 1760 RegsToPass[i].second, InFlag); 1761 InFlag = Chain.getValue(1); 1762 } 1763 1764 // For tail calls lower the arguments to the 'real' stack slot. 1765 if (isTailCall) { 1766 // Force all the incoming stack arguments to be loaded from the stack 1767 // before any new outgoing arguments are stored to the stack, because the 1768 // outgoing stack slots may alias the incoming argument stack slots, and 1769 // the alias isn't otherwise explicit. This is slightly more conservative 1770 // than necessary, because it means that each store effectively depends 1771 // on every argument instead of just those arguments it would clobber. 1772 1773 // Do not flag preceding copytoreg stuff together with the following stuff. 1774 InFlag = SDValue(); 1775 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) { 1776 Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first, 1777 RegsToPass[i].second, InFlag); 1778 InFlag = Chain.getValue(1); 1779 } 1780 InFlag = SDValue(); 1781 } 1782 1783 // If the callee is a GlobalAddress/ExternalSymbol node (quite common, every 1784 // direct call is) turn it into a TargetGlobalAddress/TargetExternalSymbol 1785 // node so that legalize doesn't hack it. 1786 bool isDirect = false; 1787 bool isARMFunc = false; 1788 bool isLocalARMFunc = false; 1789 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>(); 1790 auto PtrVt = getPointerTy(DAG.getDataLayout()); 1791 1792 if (Subtarget->genLongCalls()) { 1793 assert((Subtarget->isTargetWindows() || 1794 getTargetMachine().getRelocationModel() == Reloc::Static) && 1795 "long-calls with non-static relocation model!"); 1796 // Handle a global address or an external symbol. If it's not one of 1797 // those, the target's already in a register, so we don't need to do 1798 // anything extra. 1799 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) { 1800 const GlobalValue *GV = G->getGlobal(); 1801 // Create a constant pool entry for the callee address 1802 unsigned ARMPCLabelIndex = AFI->createPICLabelUId(); 1803 ARMConstantPoolValue *CPV = 1804 ARMConstantPoolConstant::Create(GV, ARMPCLabelIndex, ARMCP::CPValue, 0); 1805 1806 // Get the address of the callee into a register 1807 SDValue CPAddr = DAG.getTargetConstantPool(CPV, PtrVt, 4); 1808 CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr); 1809 Callee = DAG.getLoad( 1810 PtrVt, dl, DAG.getEntryNode(), CPAddr, 1811 MachinePointerInfo::getConstantPool(DAG.getMachineFunction()), false, 1812 false, false, 0); 1813 } else if (ExternalSymbolSDNode *S=dyn_cast<ExternalSymbolSDNode>(Callee)) { 1814 const char *Sym = S->getSymbol(); 1815 1816 // Create a constant pool entry for the callee address 1817 unsigned ARMPCLabelIndex = AFI->createPICLabelUId(); 1818 ARMConstantPoolValue *CPV = 1819 ARMConstantPoolSymbol::Create(*DAG.getContext(), Sym, 1820 ARMPCLabelIndex, 0); 1821 // Get the address of the callee into a register 1822 SDValue CPAddr = DAG.getTargetConstantPool(CPV, PtrVt, 4); 1823 CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr); 1824 Callee = DAG.getLoad( 1825 PtrVt, dl, DAG.getEntryNode(), CPAddr, 1826 MachinePointerInfo::getConstantPool(DAG.getMachineFunction()), false, 1827 false, false, 0); 1828 } 1829 } else if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) { 1830 const GlobalValue *GV = G->getGlobal(); 1831 isDirect = true; 1832 bool isDef = GV->isStrongDefinitionForLinker(); 1833 bool isStub = (!isDef && Subtarget->isTargetMachO()) && 1834 getTargetMachine().getRelocationModel() != Reloc::Static; 1835 isARMFunc = !Subtarget->isThumb() || (isStub && !Subtarget->isMClass()); 1836 // ARM call to a local ARM function is predicable. 1837 isLocalARMFunc = !Subtarget->isThumb() && (isDef || !ARMInterworking); 1838 // tBX takes a register source operand. 1839 if (isStub && Subtarget->isThumb1Only() && !Subtarget->hasV5TOps()) { 1840 assert(Subtarget->isTargetMachO() && "WrapperPIC use on non-MachO?"); 1841 Callee = DAG.getNode( 1842 ARMISD::WrapperPIC, dl, PtrVt, 1843 DAG.getTargetGlobalAddress(GV, dl, PtrVt, 0, ARMII::MO_NONLAZY)); 1844 Callee = DAG.getLoad(PtrVt, dl, DAG.getEntryNode(), Callee, 1845 MachinePointerInfo::getGOT(DAG.getMachineFunction()), 1846 false, false, true, 0); 1847 } else if (Subtarget->isTargetCOFF()) { 1848 assert(Subtarget->isTargetWindows() && 1849 "Windows is the only supported COFF target"); 1850 unsigned TargetFlags = GV->hasDLLImportStorageClass() 1851 ? ARMII::MO_DLLIMPORT 1852 : ARMII::MO_NO_FLAG; 1853 Callee = 1854 DAG.getTargetGlobalAddress(GV, dl, PtrVt, /*Offset=*/0, TargetFlags); 1855 if (GV->hasDLLImportStorageClass()) 1856 Callee = 1857 DAG.getLoad(PtrVt, dl, DAG.getEntryNode(), 1858 DAG.getNode(ARMISD::Wrapper, dl, PtrVt, Callee), 1859 MachinePointerInfo::getGOT(DAG.getMachineFunction()), 1860 false, false, false, 0); 1861 } else { 1862 // On ELF targets for PIC code, direct calls should go through the PLT 1863 unsigned OpFlags = 0; 1864 if (Subtarget->isTargetELF() && 1865 getTargetMachine().getRelocationModel() == Reloc::PIC_) 1866 OpFlags = ARMII::MO_PLT; 1867 Callee = DAG.getTargetGlobalAddress(GV, dl, PtrVt, 0, OpFlags); 1868 } 1869 } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) { 1870 isDirect = true; 1871 bool isStub = Subtarget->isTargetMachO() && 1872 getTargetMachine().getRelocationModel() != Reloc::Static; 1873 isARMFunc = !Subtarget->isThumb() || (isStub && !Subtarget->isMClass()); 1874 // tBX takes a register source operand. 1875 const char *Sym = S->getSymbol(); 1876 if (isARMFunc && Subtarget->isThumb1Only() && !Subtarget->hasV5TOps()) { 1877 unsigned ARMPCLabelIndex = AFI->createPICLabelUId(); 1878 ARMConstantPoolValue *CPV = 1879 ARMConstantPoolSymbol::Create(*DAG.getContext(), Sym, 1880 ARMPCLabelIndex, 4); 1881 SDValue CPAddr = DAG.getTargetConstantPool(CPV, PtrVt, 4); 1882 CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr); 1883 Callee = DAG.getLoad( 1884 PtrVt, dl, DAG.getEntryNode(), CPAddr, 1885 MachinePointerInfo::getConstantPool(DAG.getMachineFunction()), false, 1886 false, false, 0); 1887 SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, dl, MVT::i32); 1888 Callee = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVt, Callee, PICLabel); 1889 } else { 1890 unsigned OpFlags = 0; 1891 // On ELF targets for PIC code, direct calls should go through the PLT 1892 if (Subtarget->isTargetELF() && 1893 getTargetMachine().getRelocationModel() == Reloc::PIC_) 1894 OpFlags = ARMII::MO_PLT; 1895 Callee = DAG.getTargetExternalSymbol(Sym, PtrVt, OpFlags); 1896 } 1897 } 1898 1899 // FIXME: handle tail calls differently. 1900 unsigned CallOpc; 1901 if (Subtarget->isThumb()) { 1902 if ((!isDirect || isARMFunc) && !Subtarget->hasV5TOps()) 1903 CallOpc = ARMISD::CALL_NOLINK; 1904 else 1905 CallOpc = isARMFunc ? ARMISD::CALL : ARMISD::tCALL; 1906 } else { 1907 if (!isDirect && !Subtarget->hasV5TOps()) 1908 CallOpc = ARMISD::CALL_NOLINK; 1909 else if (doesNotRet && isDirect && Subtarget->hasRAS() && 1910 // Emit regular call when code size is the priority 1911 !MF.getFunction()->optForMinSize()) 1912 // "mov lr, pc; b _foo" to avoid confusing the RSP 1913 CallOpc = ARMISD::CALL_NOLINK; 1914 else 1915 CallOpc = isLocalARMFunc ? ARMISD::CALL_PRED : ARMISD::CALL; 1916 } 1917 1918 std::vector<SDValue> Ops; 1919 Ops.push_back(Chain); 1920 Ops.push_back(Callee); 1921 1922 // Add argument registers to the end of the list so that they are known live 1923 // into the call. 1924 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) 1925 Ops.push_back(DAG.getRegister(RegsToPass[i].first, 1926 RegsToPass[i].second.getValueType())); 1927 1928 // Add a register mask operand representing the call-preserved registers. 1929 if (!isTailCall) { 1930 const uint32_t *Mask; 1931 const ARMBaseRegisterInfo *ARI = Subtarget->getRegisterInfo(); 1932 if (isThisReturn) { 1933 // For 'this' returns, use the R0-preserving mask if applicable 1934 Mask = ARI->getThisReturnPreservedMask(MF, CallConv); 1935 if (!Mask) { 1936 // Set isThisReturn to false if the calling convention is not one that 1937 // allows 'returned' to be modeled in this way, so LowerCallResult does 1938 // not try to pass 'this' straight through 1939 isThisReturn = false; 1940 Mask = ARI->getCallPreservedMask(MF, CallConv); 1941 } 1942 } else 1943 Mask = ARI->getCallPreservedMask(MF, CallConv); 1944 1945 assert(Mask && "Missing call preserved mask for calling convention"); 1946 Ops.push_back(DAG.getRegisterMask(Mask)); 1947 } 1948 1949 if (InFlag.getNode()) 1950 Ops.push_back(InFlag); 1951 1952 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue); 1953 if (isTailCall) { 1954 MF.getFrameInfo()->setHasTailCall(); 1955 return DAG.getNode(ARMISD::TC_RETURN, dl, NodeTys, Ops); 1956 } 1957 1958 // Returns a chain and a flag for retval copy to use. 1959 Chain = DAG.getNode(CallOpc, dl, NodeTys, Ops); 1960 InFlag = Chain.getValue(1); 1961 1962 Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, dl, true), 1963 DAG.getIntPtrConstant(0, dl, true), InFlag, dl); 1964 if (!Ins.empty()) 1965 InFlag = Chain.getValue(1); 1966 1967 // Handle result values, copying them out of physregs into vregs that we 1968 // return. 1969 return LowerCallResult(Chain, InFlag, CallConv, isVarArg, Ins, dl, DAG, 1970 InVals, isThisReturn, 1971 isThisReturn ? OutVals[0] : SDValue()); 1972 } 1973 1974 /// HandleByVal - Every parameter *after* a byval parameter is passed 1975 /// on the stack. Remember the next parameter register to allocate, 1976 /// and then confiscate the rest of the parameter registers to insure 1977 /// this. 1978 void ARMTargetLowering::HandleByVal(CCState *State, unsigned &Size, 1979 unsigned Align) const { 1980 assert((State->getCallOrPrologue() == Prologue || 1981 State->getCallOrPrologue() == Call) && 1982 "unhandled ParmContext"); 1983 1984 // Byval (as with any stack) slots are always at least 4 byte aligned. 1985 Align = std::max(Align, 4U); 1986 1987 unsigned Reg = State->AllocateReg(GPRArgRegs); 1988 if (!Reg) 1989 return; 1990 1991 unsigned AlignInRegs = Align / 4; 1992 unsigned Waste = (ARM::R4 - Reg) % AlignInRegs; 1993 for (unsigned i = 0; i < Waste; ++i) 1994 Reg = State->AllocateReg(GPRArgRegs); 1995 1996 if (!Reg) 1997 return; 1998 1999 unsigned Excess = 4 * (ARM::R4 - Reg); 2000 2001 // Special case when NSAA != SP and parameter size greater than size of 2002 // all remained GPR regs. In that case we can't split parameter, we must 2003 // send it to stack. We also must set NCRN to R4, so waste all 2004 // remained registers. 2005 const unsigned NSAAOffset = State->getNextStackOffset(); 2006 if (NSAAOffset != 0 && Size > Excess) { 2007 while (State->AllocateReg(GPRArgRegs)) 2008 ; 2009 return; 2010 } 2011 2012 // First register for byval parameter is the first register that wasn't 2013 // allocated before this method call, so it would be "reg". 2014 // If parameter is small enough to be saved in range [reg, r4), then 2015 // the end (first after last) register would be reg + param-size-in-regs, 2016 // else parameter would be splitted between registers and stack, 2017 // end register would be r4 in this case. 2018 unsigned ByValRegBegin = Reg; 2019 unsigned ByValRegEnd = std::min<unsigned>(Reg + Size / 4, ARM::R4); 2020 State->addInRegsParamInfo(ByValRegBegin, ByValRegEnd); 2021 // Note, first register is allocated in the beginning of function already, 2022 // allocate remained amount of registers we need. 2023 for (unsigned i = Reg + 1; i != ByValRegEnd; ++i) 2024 State->AllocateReg(GPRArgRegs); 2025 // A byval parameter that is split between registers and memory needs its 2026 // size truncated here. 2027 // In the case where the entire structure fits in registers, we set the 2028 // size in memory to zero. 2029 Size = std::max<int>(Size - Excess, 0); 2030 } 2031 2032 /// MatchingStackOffset - Return true if the given stack call argument is 2033 /// already available in the same position (relatively) of the caller's 2034 /// incoming argument stack. 2035 static 2036 bool MatchingStackOffset(SDValue Arg, unsigned Offset, ISD::ArgFlagsTy Flags, 2037 MachineFrameInfo *MFI, const MachineRegisterInfo *MRI, 2038 const TargetInstrInfo *TII) { 2039 unsigned Bytes = Arg.getValueType().getSizeInBits() / 8; 2040 int FI = INT_MAX; 2041 if (Arg.getOpcode() == ISD::CopyFromReg) { 2042 unsigned VR = cast<RegisterSDNode>(Arg.getOperand(1))->getReg(); 2043 if (!TargetRegisterInfo::isVirtualRegister(VR)) 2044 return false; 2045 MachineInstr *Def = MRI->getVRegDef(VR); 2046 if (!Def) 2047 return false; 2048 if (!Flags.isByVal()) { 2049 if (!TII->isLoadFromStackSlot(Def, FI)) 2050 return false; 2051 } else { 2052 return false; 2053 } 2054 } else if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Arg)) { 2055 if (Flags.isByVal()) 2056 // ByVal argument is passed in as a pointer but it's now being 2057 // dereferenced. e.g. 2058 // define @foo(%struct.X* %A) { 2059 // tail call @bar(%struct.X* byval %A) 2060 // } 2061 return false; 2062 SDValue Ptr = Ld->getBasePtr(); 2063 FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr); 2064 if (!FINode) 2065 return false; 2066 FI = FINode->getIndex(); 2067 } else 2068 return false; 2069 2070 assert(FI != INT_MAX); 2071 if (!MFI->isFixedObjectIndex(FI)) 2072 return false; 2073 return Offset == MFI->getObjectOffset(FI) && Bytes == MFI->getObjectSize(FI); 2074 } 2075 2076 /// IsEligibleForTailCallOptimization - Check whether the call is eligible 2077 /// for tail call optimization. Targets which want to do tail call 2078 /// optimization should implement this function. 2079 bool 2080 ARMTargetLowering::IsEligibleForTailCallOptimization(SDValue Callee, 2081 CallingConv::ID CalleeCC, 2082 bool isVarArg, 2083 bool isCalleeStructRet, 2084 bool isCallerStructRet, 2085 const SmallVectorImpl<ISD::OutputArg> &Outs, 2086 const SmallVectorImpl<SDValue> &OutVals, 2087 const SmallVectorImpl<ISD::InputArg> &Ins, 2088 SelectionDAG& DAG) const { 2089 const Function *CallerF = DAG.getMachineFunction().getFunction(); 2090 CallingConv::ID CallerCC = CallerF->getCallingConv(); 2091 bool CCMatch = CallerCC == CalleeCC; 2092 2093 assert(Subtarget->supportsTailCall()); 2094 2095 // Look for obvious safe cases to perform tail call optimization that do not 2096 // require ABI changes. This is what gcc calls sibcall. 2097 2098 // Do not sibcall optimize vararg calls unless the call site is not passing 2099 // any arguments. 2100 if (isVarArg && !Outs.empty()) 2101 return false; 2102 2103 // Exception-handling functions need a special set of instructions to indicate 2104 // a return to the hardware. Tail-calling another function would probably 2105 // break this. 2106 if (CallerF->hasFnAttribute("interrupt")) 2107 return false; 2108 2109 // Also avoid sibcall optimization if either caller or callee uses struct 2110 // return semantics. 2111 if (isCalleeStructRet || isCallerStructRet) 2112 return false; 2113 2114 // Externally-defined functions with weak linkage should not be 2115 // tail-called on ARM when the OS does not support dynamic 2116 // pre-emption of symbols, as the AAELF spec requires normal calls 2117 // to undefined weak functions to be replaced with a NOP or jump to the 2118 // next instruction. The behaviour of branch instructions in this 2119 // situation (as used for tail calls) is implementation-defined, so we 2120 // cannot rely on the linker replacing the tail call with a return. 2121 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) { 2122 const GlobalValue *GV = G->getGlobal(); 2123 const Triple &TT = getTargetMachine().getTargetTriple(); 2124 if (GV->hasExternalWeakLinkage() && 2125 (!TT.isOSWindows() || TT.isOSBinFormatELF() || TT.isOSBinFormatMachO())) 2126 return false; 2127 } 2128 2129 // If the calling conventions do not match, then we'd better make sure the 2130 // results are returned in the same way as what the caller expects. 2131 if (!CCMatch) { 2132 SmallVector<CCValAssign, 16> RVLocs1; 2133 ARMCCState CCInfo1(CalleeCC, false, DAG.getMachineFunction(), RVLocs1, 2134 *DAG.getContext(), Call); 2135 CCInfo1.AnalyzeCallResult(Ins, CCAssignFnForNode(CalleeCC, true, isVarArg)); 2136 2137 SmallVector<CCValAssign, 16> RVLocs2; 2138 ARMCCState CCInfo2(CallerCC, false, DAG.getMachineFunction(), RVLocs2, 2139 *DAG.getContext(), Call); 2140 CCInfo2.AnalyzeCallResult(Ins, CCAssignFnForNode(CallerCC, true, isVarArg)); 2141 2142 if (RVLocs1.size() != RVLocs2.size()) 2143 return false; 2144 for (unsigned i = 0, e = RVLocs1.size(); i != e; ++i) { 2145 if (RVLocs1[i].isRegLoc() != RVLocs2[i].isRegLoc()) 2146 return false; 2147 if (RVLocs1[i].getLocInfo() != RVLocs2[i].getLocInfo()) 2148 return false; 2149 if (RVLocs1[i].isRegLoc()) { 2150 if (RVLocs1[i].getLocReg() != RVLocs2[i].getLocReg()) 2151 return false; 2152 } else { 2153 if (RVLocs1[i].getLocMemOffset() != RVLocs2[i].getLocMemOffset()) 2154 return false; 2155 } 2156 } 2157 } 2158 2159 // If Caller's vararg or byval argument has been split between registers and 2160 // stack, do not perform tail call, since part of the argument is in caller's 2161 // local frame. 2162 const ARMFunctionInfo *AFI_Caller = DAG.getMachineFunction(). 2163 getInfo<ARMFunctionInfo>(); 2164 if (AFI_Caller->getArgRegsSaveSize()) 2165 return false; 2166 2167 // If the callee takes no arguments then go on to check the results of the 2168 // call. 2169 if (!Outs.empty()) { 2170 // Check if stack adjustment is needed. For now, do not do this if any 2171 // argument is passed on the stack. 2172 SmallVector<CCValAssign, 16> ArgLocs; 2173 ARMCCState CCInfo(CalleeCC, isVarArg, DAG.getMachineFunction(), ArgLocs, 2174 *DAG.getContext(), Call); 2175 CCInfo.AnalyzeCallOperands(Outs, 2176 CCAssignFnForNode(CalleeCC, false, isVarArg)); 2177 if (CCInfo.getNextStackOffset()) { 2178 MachineFunction &MF = DAG.getMachineFunction(); 2179 2180 // Check if the arguments are already laid out in the right way as 2181 // the caller's fixed stack objects. 2182 MachineFrameInfo *MFI = MF.getFrameInfo(); 2183 const MachineRegisterInfo *MRI = &MF.getRegInfo(); 2184 const TargetInstrInfo *TII = Subtarget->getInstrInfo(); 2185 for (unsigned i = 0, realArgIdx = 0, e = ArgLocs.size(); 2186 i != e; 2187 ++i, ++realArgIdx) { 2188 CCValAssign &VA = ArgLocs[i]; 2189 EVT RegVT = VA.getLocVT(); 2190 SDValue Arg = OutVals[realArgIdx]; 2191 ISD::ArgFlagsTy Flags = Outs[realArgIdx].Flags; 2192 if (VA.getLocInfo() == CCValAssign::Indirect) 2193 return false; 2194 if (VA.needsCustom()) { 2195 // f64 and vector types are split into multiple registers or 2196 // register/stack-slot combinations. The types will not match 2197 // the registers; give up on memory f64 refs until we figure 2198 // out what to do about this. 2199 if (!VA.isRegLoc()) 2200 return false; 2201 if (!ArgLocs[++i].isRegLoc()) 2202 return false; 2203 if (RegVT == MVT::v2f64) { 2204 if (!ArgLocs[++i].isRegLoc()) 2205 return false; 2206 if (!ArgLocs[++i].isRegLoc()) 2207 return false; 2208 } 2209 } else if (!VA.isRegLoc()) { 2210 if (!MatchingStackOffset(Arg, VA.getLocMemOffset(), Flags, 2211 MFI, MRI, TII)) 2212 return false; 2213 } 2214 } 2215 } 2216 } 2217 2218 return true; 2219 } 2220 2221 bool 2222 ARMTargetLowering::CanLowerReturn(CallingConv::ID CallConv, 2223 MachineFunction &MF, bool isVarArg, 2224 const SmallVectorImpl<ISD::OutputArg> &Outs, 2225 LLVMContext &Context) const { 2226 SmallVector<CCValAssign, 16> RVLocs; 2227 CCState CCInfo(CallConv, isVarArg, MF, RVLocs, Context); 2228 return CCInfo.CheckReturn(Outs, CCAssignFnForNode(CallConv, /*Return=*/true, 2229 isVarArg)); 2230 } 2231 2232 static SDValue LowerInterruptReturn(SmallVectorImpl<SDValue> &RetOps, 2233 SDLoc DL, SelectionDAG &DAG) { 2234 const MachineFunction &MF = DAG.getMachineFunction(); 2235 const Function *F = MF.getFunction(); 2236 2237 StringRef IntKind = F->getFnAttribute("interrupt").getValueAsString(); 2238 2239 // See ARM ARM v7 B1.8.3. On exception entry LR is set to a possibly offset 2240 // version of the "preferred return address". These offsets affect the return 2241 // instruction if this is a return from PL1 without hypervisor extensions. 2242 // IRQ/FIQ: +4 "subs pc, lr, #4" 2243 // SWI: 0 "subs pc, lr, #0" 2244 // ABORT: +4 "subs pc, lr, #4" 2245 // UNDEF: +4/+2 "subs pc, lr, #0" 2246 // UNDEF varies depending on where the exception came from ARM or Thumb 2247 // mode. Alongside GCC, we throw our hands up in disgust and pretend it's 0. 2248 2249 int64_t LROffset; 2250 if (IntKind == "" || IntKind == "IRQ" || IntKind == "FIQ" || 2251 IntKind == "ABORT") 2252 LROffset = 4; 2253 else if (IntKind == "SWI" || IntKind == "UNDEF") 2254 LROffset = 0; 2255 else 2256 report_fatal_error("Unsupported interrupt attribute. If present, value " 2257 "must be one of: IRQ, FIQ, SWI, ABORT or UNDEF"); 2258 2259 RetOps.insert(RetOps.begin() + 1, 2260 DAG.getConstant(LROffset, DL, MVT::i32, false)); 2261 2262 return DAG.getNode(ARMISD::INTRET_FLAG, DL, MVT::Other, RetOps); 2263 } 2264 2265 SDValue 2266 ARMTargetLowering::LowerReturn(SDValue Chain, 2267 CallingConv::ID CallConv, bool isVarArg, 2268 const SmallVectorImpl<ISD::OutputArg> &Outs, 2269 const SmallVectorImpl<SDValue> &OutVals, 2270 SDLoc dl, SelectionDAG &DAG) const { 2271 2272 // CCValAssign - represent the assignment of the return value to a location. 2273 SmallVector<CCValAssign, 16> RVLocs; 2274 2275 // CCState - Info about the registers and stack slots. 2276 ARMCCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs, 2277 *DAG.getContext(), Call); 2278 2279 // Analyze outgoing return values. 2280 CCInfo.AnalyzeReturn(Outs, CCAssignFnForNode(CallConv, /* Return */ true, 2281 isVarArg)); 2282 2283 SDValue Flag; 2284 SmallVector<SDValue, 4> RetOps; 2285 RetOps.push_back(Chain); // Operand #0 = Chain (updated below) 2286 bool isLittleEndian = Subtarget->isLittle(); 2287 2288 MachineFunction &MF = DAG.getMachineFunction(); 2289 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>(); 2290 AFI->setReturnRegsCount(RVLocs.size()); 2291 2292 // Copy the result values into the output registers. 2293 for (unsigned i = 0, realRVLocIdx = 0; 2294 i != RVLocs.size(); 2295 ++i, ++realRVLocIdx) { 2296 CCValAssign &VA = RVLocs[i]; 2297 assert(VA.isRegLoc() && "Can only return in registers!"); 2298 2299 SDValue Arg = OutVals[realRVLocIdx]; 2300 2301 switch (VA.getLocInfo()) { 2302 default: llvm_unreachable("Unknown loc info!"); 2303 case CCValAssign::Full: break; 2304 case CCValAssign::BCvt: 2305 Arg = DAG.getNode(ISD::BITCAST, dl, VA.getLocVT(), Arg); 2306 break; 2307 } 2308 2309 if (VA.needsCustom()) { 2310 if (VA.getLocVT() == MVT::v2f64) { 2311 // Extract the first half and return it in two registers. 2312 SDValue Half = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg, 2313 DAG.getConstant(0, dl, MVT::i32)); 2314 SDValue HalfGPRs = DAG.getNode(ARMISD::VMOVRRD, dl, 2315 DAG.getVTList(MVT::i32, MVT::i32), Half); 2316 2317 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), 2318 HalfGPRs.getValue(isLittleEndian ? 0 : 1), 2319 Flag); 2320 Flag = Chain.getValue(1); 2321 RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT())); 2322 VA = RVLocs[++i]; // skip ahead to next loc 2323 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), 2324 HalfGPRs.getValue(isLittleEndian ? 1 : 0), 2325 Flag); 2326 Flag = Chain.getValue(1); 2327 RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT())); 2328 VA = RVLocs[++i]; // skip ahead to next loc 2329 2330 // Extract the 2nd half and fall through to handle it as an f64 value. 2331 Arg = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg, 2332 DAG.getConstant(1, dl, MVT::i32)); 2333 } 2334 // Legalize ret f64 -> ret 2 x i32. We always have fmrrd if f64 is 2335 // available. 2336 SDValue fmrrd = DAG.getNode(ARMISD::VMOVRRD, dl, 2337 DAG.getVTList(MVT::i32, MVT::i32), Arg); 2338 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), 2339 fmrrd.getValue(isLittleEndian ? 0 : 1), 2340 Flag); 2341 Flag = Chain.getValue(1); 2342 RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT())); 2343 VA = RVLocs[++i]; // skip ahead to next loc 2344 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), 2345 fmrrd.getValue(isLittleEndian ? 1 : 0), 2346 Flag); 2347 } else 2348 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), Arg, Flag); 2349 2350 // Guarantee that all emitted copies are 2351 // stuck together, avoiding something bad. 2352 Flag = Chain.getValue(1); 2353 RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT())); 2354 } 2355 2356 // Update chain and glue. 2357 RetOps[0] = Chain; 2358 if (Flag.getNode()) 2359 RetOps.push_back(Flag); 2360 2361 // CPUs which aren't M-class use a special sequence to return from 2362 // exceptions (roughly, any instruction setting pc and cpsr simultaneously, 2363 // though we use "subs pc, lr, #N"). 2364 // 2365 // M-class CPUs actually use a normal return sequence with a special 2366 // (hardware-provided) value in LR, so the normal code path works. 2367 if (DAG.getMachineFunction().getFunction()->hasFnAttribute("interrupt") && 2368 !Subtarget->isMClass()) { 2369 if (Subtarget->isThumb1Only()) 2370 report_fatal_error("interrupt attribute is not supported in Thumb1"); 2371 return LowerInterruptReturn(RetOps, dl, DAG); 2372 } 2373 2374 return DAG.getNode(ARMISD::RET_FLAG, dl, MVT::Other, RetOps); 2375 } 2376 2377 bool ARMTargetLowering::isUsedByReturnOnly(SDNode *N, SDValue &Chain) const { 2378 if (N->getNumValues() != 1) 2379 return false; 2380 if (!N->hasNUsesOfValue(1, 0)) 2381 return false; 2382 2383 SDValue TCChain = Chain; 2384 SDNode *Copy = *N->use_begin(); 2385 if (Copy->getOpcode() == ISD::CopyToReg) { 2386 // If the copy has a glue operand, we conservatively assume it isn't safe to 2387 // perform a tail call. 2388 if (Copy->getOperand(Copy->getNumOperands()-1).getValueType() == MVT::Glue) 2389 return false; 2390 TCChain = Copy->getOperand(0); 2391 } else if (Copy->getOpcode() == ARMISD::VMOVRRD) { 2392 SDNode *VMov = Copy; 2393 // f64 returned in a pair of GPRs. 2394 SmallPtrSet<SDNode*, 2> Copies; 2395 for (SDNode::use_iterator UI = VMov->use_begin(), UE = VMov->use_end(); 2396 UI != UE; ++UI) { 2397 if (UI->getOpcode() != ISD::CopyToReg) 2398 return false; 2399 Copies.insert(*UI); 2400 } 2401 if (Copies.size() > 2) 2402 return false; 2403 2404 for (SDNode::use_iterator UI = VMov->use_begin(), UE = VMov->use_end(); 2405 UI != UE; ++UI) { 2406 SDValue UseChain = UI->getOperand(0); 2407 if (Copies.count(UseChain.getNode())) 2408 // Second CopyToReg 2409 Copy = *UI; 2410 else { 2411 // We are at the top of this chain. 2412 // If the copy has a glue operand, we conservatively assume it 2413 // isn't safe to perform a tail call. 2414 if (UI->getOperand(UI->getNumOperands()-1).getValueType() == MVT::Glue) 2415 return false; 2416 // First CopyToReg 2417 TCChain = UseChain; 2418 } 2419 } 2420 } else if (Copy->getOpcode() == ISD::BITCAST) { 2421 // f32 returned in a single GPR. 2422 if (!Copy->hasOneUse()) 2423 return false; 2424 Copy = *Copy->use_begin(); 2425 if (Copy->getOpcode() != ISD::CopyToReg || !Copy->hasNUsesOfValue(1, 0)) 2426 return false; 2427 // If the copy has a glue operand, we conservatively assume it isn't safe to 2428 // perform a tail call. 2429 if (Copy->getOperand(Copy->getNumOperands()-1).getValueType() == MVT::Glue) 2430 return false; 2431 TCChain = Copy->getOperand(0); 2432 } else { 2433 return false; 2434 } 2435 2436 bool HasRet = false; 2437 for (SDNode::use_iterator UI = Copy->use_begin(), UE = Copy->use_end(); 2438 UI != UE; ++UI) { 2439 if (UI->getOpcode() != ARMISD::RET_FLAG && 2440 UI->getOpcode() != ARMISD::INTRET_FLAG) 2441 return false; 2442 HasRet = true; 2443 } 2444 2445 if (!HasRet) 2446 return false; 2447 2448 Chain = TCChain; 2449 return true; 2450 } 2451 2452 bool ARMTargetLowering::mayBeEmittedAsTailCall(CallInst *CI) const { 2453 if (!Subtarget->supportsTailCall()) 2454 return false; 2455 2456 auto Attr = 2457 CI->getParent()->getParent()->getFnAttribute("disable-tail-calls"); 2458 if (!CI->isTailCall() || Attr.getValueAsString() == "true") 2459 return false; 2460 2461 return true; 2462 } 2463 2464 // Trying to write a 64 bit value so need to split into two 32 bit values first, 2465 // and pass the lower and high parts through. 2466 static SDValue LowerWRITE_REGISTER(SDValue Op, SelectionDAG &DAG) { 2467 SDLoc DL(Op); 2468 SDValue WriteValue = Op->getOperand(2); 2469 2470 // This function is only supposed to be called for i64 type argument. 2471 assert(WriteValue.getValueType() == MVT::i64 2472 && "LowerWRITE_REGISTER called for non-i64 type argument."); 2473 2474 SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, WriteValue, 2475 DAG.getConstant(0, DL, MVT::i32)); 2476 SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, WriteValue, 2477 DAG.getConstant(1, DL, MVT::i32)); 2478 SDValue Ops[] = { Op->getOperand(0), Op->getOperand(1), Lo, Hi }; 2479 return DAG.getNode(ISD::WRITE_REGISTER, DL, MVT::Other, Ops); 2480 } 2481 2482 // ConstantPool, JumpTable, GlobalAddress, and ExternalSymbol are lowered as 2483 // their target counterpart wrapped in the ARMISD::Wrapper node. Suppose N is 2484 // one of the above mentioned nodes. It has to be wrapped because otherwise 2485 // Select(N) returns N. So the raw TargetGlobalAddress nodes, etc. can only 2486 // be used to form addressing mode. These wrapped nodes will be selected 2487 // into MOVi. 2488 static SDValue LowerConstantPool(SDValue Op, SelectionDAG &DAG) { 2489 EVT PtrVT = Op.getValueType(); 2490 // FIXME there is no actual debug info here 2491 SDLoc dl(Op); 2492 ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op); 2493 SDValue Res; 2494 if (CP->isMachineConstantPoolEntry()) 2495 Res = DAG.getTargetConstantPool(CP->getMachineCPVal(), PtrVT, 2496 CP->getAlignment()); 2497 else 2498 Res = DAG.getTargetConstantPool(CP->getConstVal(), PtrVT, 2499 CP->getAlignment()); 2500 return DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Res); 2501 } 2502 2503 unsigned ARMTargetLowering::getJumpTableEncoding() const { 2504 return MachineJumpTableInfo::EK_Inline; 2505 } 2506 2507 SDValue ARMTargetLowering::LowerBlockAddress(SDValue Op, 2508 SelectionDAG &DAG) const { 2509 MachineFunction &MF = DAG.getMachineFunction(); 2510 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>(); 2511 unsigned ARMPCLabelIndex = 0; 2512 SDLoc DL(Op); 2513 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 2514 const BlockAddress *BA = cast<BlockAddressSDNode>(Op)->getBlockAddress(); 2515 Reloc::Model RelocM = getTargetMachine().getRelocationModel(); 2516 SDValue CPAddr; 2517 if (RelocM == Reloc::Static) { 2518 CPAddr = DAG.getTargetConstantPool(BA, PtrVT, 4); 2519 } else { 2520 unsigned PCAdj = Subtarget->isThumb() ? 4 : 8; 2521 ARMPCLabelIndex = AFI->createPICLabelUId(); 2522 ARMConstantPoolValue *CPV = 2523 ARMConstantPoolConstant::Create(BA, ARMPCLabelIndex, 2524 ARMCP::CPBlockAddress, PCAdj); 2525 CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4); 2526 } 2527 CPAddr = DAG.getNode(ARMISD::Wrapper, DL, PtrVT, CPAddr); 2528 SDValue Result = 2529 DAG.getLoad(PtrVT, DL, DAG.getEntryNode(), CPAddr, 2530 MachinePointerInfo::getConstantPool(DAG.getMachineFunction()), 2531 false, false, false, 0); 2532 if (RelocM == Reloc::Static) 2533 return Result; 2534 SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, DL, MVT::i32); 2535 return DAG.getNode(ARMISD::PIC_ADD, DL, PtrVT, Result, PICLabel); 2536 } 2537 2538 // Lower ISD::GlobalTLSAddress using the "general dynamic" model 2539 SDValue 2540 ARMTargetLowering::LowerToTLSGeneralDynamicModel(GlobalAddressSDNode *GA, 2541 SelectionDAG &DAG) const { 2542 SDLoc dl(GA); 2543 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 2544 unsigned char PCAdj = Subtarget->isThumb() ? 4 : 8; 2545 MachineFunction &MF = DAG.getMachineFunction(); 2546 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>(); 2547 unsigned ARMPCLabelIndex = AFI->createPICLabelUId(); 2548 ARMConstantPoolValue *CPV = 2549 ARMConstantPoolConstant::Create(GA->getGlobal(), ARMPCLabelIndex, 2550 ARMCP::CPValue, PCAdj, ARMCP::TLSGD, true); 2551 SDValue Argument = DAG.getTargetConstantPool(CPV, PtrVT, 4); 2552 Argument = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Argument); 2553 Argument = 2554 DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Argument, 2555 MachinePointerInfo::getConstantPool(DAG.getMachineFunction()), 2556 false, false, false, 0); 2557 SDValue Chain = Argument.getValue(1); 2558 2559 SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, dl, MVT::i32); 2560 Argument = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Argument, PICLabel); 2561 2562 // call __tls_get_addr. 2563 ArgListTy Args; 2564 ArgListEntry Entry; 2565 Entry.Node = Argument; 2566 Entry.Ty = (Type *) Type::getInt32Ty(*DAG.getContext()); 2567 Args.push_back(Entry); 2568 2569 // FIXME: is there useful debug info available here? 2570 TargetLowering::CallLoweringInfo CLI(DAG); 2571 CLI.setDebugLoc(dl).setChain(Chain) 2572 .setCallee(CallingConv::C, Type::getInt32Ty(*DAG.getContext()), 2573 DAG.getExternalSymbol("__tls_get_addr", PtrVT), std::move(Args), 2574 0); 2575 2576 std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI); 2577 return CallResult.first; 2578 } 2579 2580 // Lower ISD::GlobalTLSAddress using the "initial exec" or 2581 // "local exec" model. 2582 SDValue 2583 ARMTargetLowering::LowerToTLSExecModels(GlobalAddressSDNode *GA, 2584 SelectionDAG &DAG, 2585 TLSModel::Model model) const { 2586 const GlobalValue *GV = GA->getGlobal(); 2587 SDLoc dl(GA); 2588 SDValue Offset; 2589 SDValue Chain = DAG.getEntryNode(); 2590 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 2591 // Get the Thread Pointer 2592 SDValue ThreadPointer = DAG.getNode(ARMISD::THREAD_POINTER, dl, PtrVT); 2593 2594 if (model == TLSModel::InitialExec) { 2595 MachineFunction &MF = DAG.getMachineFunction(); 2596 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>(); 2597 unsigned ARMPCLabelIndex = AFI->createPICLabelUId(); 2598 // Initial exec model. 2599 unsigned char PCAdj = Subtarget->isThumb() ? 4 : 8; 2600 ARMConstantPoolValue *CPV = 2601 ARMConstantPoolConstant::Create(GA->getGlobal(), ARMPCLabelIndex, 2602 ARMCP::CPValue, PCAdj, ARMCP::GOTTPOFF, 2603 true); 2604 Offset = DAG.getTargetConstantPool(CPV, PtrVT, 4); 2605 Offset = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Offset); 2606 Offset = DAG.getLoad( 2607 PtrVT, dl, Chain, Offset, 2608 MachinePointerInfo::getConstantPool(DAG.getMachineFunction()), false, 2609 false, false, 0); 2610 Chain = Offset.getValue(1); 2611 2612 SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, dl, MVT::i32); 2613 Offset = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Offset, PICLabel); 2614 2615 Offset = DAG.getLoad( 2616 PtrVT, dl, Chain, Offset, 2617 MachinePointerInfo::getConstantPool(DAG.getMachineFunction()), false, 2618 false, false, 0); 2619 } else { 2620 // local exec model 2621 assert(model == TLSModel::LocalExec); 2622 ARMConstantPoolValue *CPV = 2623 ARMConstantPoolConstant::Create(GV, ARMCP::TPOFF); 2624 Offset = DAG.getTargetConstantPool(CPV, PtrVT, 4); 2625 Offset = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Offset); 2626 Offset = DAG.getLoad( 2627 PtrVT, dl, Chain, Offset, 2628 MachinePointerInfo::getConstantPool(DAG.getMachineFunction()), false, 2629 false, false, 0); 2630 } 2631 2632 // The address of the thread local variable is the add of the thread 2633 // pointer with the offset of the variable. 2634 return DAG.getNode(ISD::ADD, dl, PtrVT, ThreadPointer, Offset); 2635 } 2636 2637 SDValue 2638 ARMTargetLowering::LowerGlobalTLSAddress(SDValue Op, SelectionDAG &DAG) const { 2639 // TODO: implement the "local dynamic" model 2640 assert(Subtarget->isTargetELF() && 2641 "TLS not implemented for non-ELF targets"); 2642 GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op); 2643 if (DAG.getTarget().Options.EmulatedTLS) 2644 return LowerToTLSEmulatedModel(GA, DAG); 2645 2646 TLSModel::Model model = getTargetMachine().getTLSModel(GA->getGlobal()); 2647 2648 switch (model) { 2649 case TLSModel::GeneralDynamic: 2650 case TLSModel::LocalDynamic: 2651 return LowerToTLSGeneralDynamicModel(GA, DAG); 2652 case TLSModel::InitialExec: 2653 case TLSModel::LocalExec: 2654 return LowerToTLSExecModels(GA, DAG, model); 2655 } 2656 llvm_unreachable("bogus TLS model"); 2657 } 2658 2659 SDValue ARMTargetLowering::LowerGlobalAddressELF(SDValue Op, 2660 SelectionDAG &DAG) const { 2661 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 2662 SDLoc dl(Op); 2663 const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal(); 2664 if (getTargetMachine().getRelocationModel() == Reloc::PIC_) { 2665 bool UseGOT_PREL = 2666 !(GV->hasHiddenVisibility() || GV->hasLocalLinkage()); 2667 2668 MachineFunction &MF = DAG.getMachineFunction(); 2669 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>(); 2670 unsigned ARMPCLabelIndex = AFI->createPICLabelUId(); 2671 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 2672 SDLoc dl(Op); 2673 unsigned PCAdj = Subtarget->isThumb() ? 4 : 8; 2674 ARMConstantPoolValue *CPV = ARMConstantPoolConstant::Create( 2675 GV, ARMPCLabelIndex, ARMCP::CPValue, PCAdj, 2676 UseGOT_PREL ? ARMCP::GOT_PREL : ARMCP::no_modifier, 2677 /*AddCurrentAddress=*/UseGOT_PREL); 2678 SDValue CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4); 2679 CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr); 2680 SDValue Result = DAG.getLoad( 2681 PtrVT, dl, DAG.getEntryNode(), CPAddr, 2682 MachinePointerInfo::getConstantPool(DAG.getMachineFunction()), false, 2683 false, false, 0); 2684 SDValue Chain = Result.getValue(1); 2685 SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, dl, MVT::i32); 2686 Result = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Result, PICLabel); 2687 if (UseGOT_PREL) 2688 Result = DAG.getLoad(PtrVT, dl, Chain, Result, 2689 MachinePointerInfo::getGOT(DAG.getMachineFunction()), 2690 false, false, false, 0); 2691 return Result; 2692 } 2693 2694 // If we have T2 ops, we can materialize the address directly via movt/movw 2695 // pair. This is always cheaper. 2696 if (Subtarget->useMovt(DAG.getMachineFunction())) { 2697 ++NumMovwMovt; 2698 // FIXME: Once remat is capable of dealing with instructions with register 2699 // operands, expand this into two nodes. 2700 return DAG.getNode(ARMISD::Wrapper, dl, PtrVT, 2701 DAG.getTargetGlobalAddress(GV, dl, PtrVT)); 2702 } else { 2703 SDValue CPAddr = DAG.getTargetConstantPool(GV, PtrVT, 4); 2704 CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr); 2705 return DAG.getLoad( 2706 PtrVT, dl, DAG.getEntryNode(), CPAddr, 2707 MachinePointerInfo::getConstantPool(DAG.getMachineFunction()), false, 2708 false, false, 0); 2709 } 2710 } 2711 2712 SDValue ARMTargetLowering::LowerGlobalAddressDarwin(SDValue Op, 2713 SelectionDAG &DAG) const { 2714 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 2715 SDLoc dl(Op); 2716 const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal(); 2717 Reloc::Model RelocM = getTargetMachine().getRelocationModel(); 2718 2719 if (Subtarget->useMovt(DAG.getMachineFunction())) 2720 ++NumMovwMovt; 2721 2722 // FIXME: Once remat is capable of dealing with instructions with register 2723 // operands, expand this into multiple nodes 2724 unsigned Wrapper = 2725 RelocM == Reloc::PIC_ ? ARMISD::WrapperPIC : ARMISD::Wrapper; 2726 2727 SDValue G = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, ARMII::MO_NONLAZY); 2728 SDValue Result = DAG.getNode(Wrapper, dl, PtrVT, G); 2729 2730 if (Subtarget->GVIsIndirectSymbol(GV, RelocM)) 2731 Result = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Result, 2732 MachinePointerInfo::getGOT(DAG.getMachineFunction()), 2733 false, false, false, 0); 2734 return Result; 2735 } 2736 2737 SDValue ARMTargetLowering::LowerGlobalAddressWindows(SDValue Op, 2738 SelectionDAG &DAG) const { 2739 assert(Subtarget->isTargetWindows() && "non-Windows COFF is not supported"); 2740 assert(Subtarget->useMovt(DAG.getMachineFunction()) && 2741 "Windows on ARM expects to use movw/movt"); 2742 2743 const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal(); 2744 const ARMII::TOF TargetFlags = 2745 (GV->hasDLLImportStorageClass() ? ARMII::MO_DLLIMPORT : ARMII::MO_NO_FLAG); 2746 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 2747 SDValue Result; 2748 SDLoc DL(Op); 2749 2750 ++NumMovwMovt; 2751 2752 // FIXME: Once remat is capable of dealing with instructions with register 2753 // operands, expand this into two nodes. 2754 Result = DAG.getNode(ARMISD::Wrapper, DL, PtrVT, 2755 DAG.getTargetGlobalAddress(GV, DL, PtrVT, /*Offset=*/0, 2756 TargetFlags)); 2757 if (GV->hasDLLImportStorageClass()) 2758 Result = DAG.getLoad(PtrVT, DL, DAG.getEntryNode(), Result, 2759 MachinePointerInfo::getGOT(DAG.getMachineFunction()), 2760 false, false, false, 0); 2761 return Result; 2762 } 2763 2764 SDValue 2765 ARMTargetLowering::LowerEH_SJLJ_SETJMP(SDValue Op, SelectionDAG &DAG) const { 2766 SDLoc dl(Op); 2767 SDValue Val = DAG.getConstant(0, dl, MVT::i32); 2768 return DAG.getNode(ARMISD::EH_SJLJ_SETJMP, dl, 2769 DAG.getVTList(MVT::i32, MVT::Other), Op.getOperand(0), 2770 Op.getOperand(1), Val); 2771 } 2772 2773 SDValue 2774 ARMTargetLowering::LowerEH_SJLJ_LONGJMP(SDValue Op, SelectionDAG &DAG) const { 2775 SDLoc dl(Op); 2776 return DAG.getNode(ARMISD::EH_SJLJ_LONGJMP, dl, MVT::Other, Op.getOperand(0), 2777 Op.getOperand(1), DAG.getConstant(0, dl, MVT::i32)); 2778 } 2779 2780 SDValue ARMTargetLowering::LowerEH_SJLJ_SETUP_DISPATCH(SDValue Op, 2781 SelectionDAG &DAG) const { 2782 SDLoc dl(Op); 2783 return DAG.getNode(ARMISD::EH_SJLJ_SETUP_DISPATCH, dl, MVT::Other, 2784 Op.getOperand(0)); 2785 } 2786 2787 SDValue 2788 ARMTargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op, SelectionDAG &DAG, 2789 const ARMSubtarget *Subtarget) const { 2790 unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue(); 2791 SDLoc dl(Op); 2792 switch (IntNo) { 2793 default: return SDValue(); // Don't custom lower most intrinsics. 2794 case Intrinsic::arm_rbit: { 2795 assert(Op.getOperand(1).getValueType() == MVT::i32 && 2796 "RBIT intrinsic must have i32 type!"); 2797 return DAG.getNode(ISD::BITREVERSE, dl, MVT::i32, Op.getOperand(1)); 2798 } 2799 case Intrinsic::arm_thread_pointer: { 2800 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 2801 return DAG.getNode(ARMISD::THREAD_POINTER, dl, PtrVT); 2802 } 2803 case Intrinsic::eh_sjlj_lsda: { 2804 MachineFunction &MF = DAG.getMachineFunction(); 2805 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>(); 2806 unsigned ARMPCLabelIndex = AFI->createPICLabelUId(); 2807 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 2808 Reloc::Model RelocM = getTargetMachine().getRelocationModel(); 2809 SDValue CPAddr; 2810 unsigned PCAdj = (RelocM != Reloc::PIC_) 2811 ? 0 : (Subtarget->isThumb() ? 4 : 8); 2812 ARMConstantPoolValue *CPV = 2813 ARMConstantPoolConstant::Create(MF.getFunction(), ARMPCLabelIndex, 2814 ARMCP::CPLSDA, PCAdj); 2815 CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4); 2816 CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr); 2817 SDValue Result = DAG.getLoad( 2818 PtrVT, dl, DAG.getEntryNode(), CPAddr, 2819 MachinePointerInfo::getConstantPool(DAG.getMachineFunction()), false, 2820 false, false, 0); 2821 2822 if (RelocM == Reloc::PIC_) { 2823 SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, dl, MVT::i32); 2824 Result = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Result, PICLabel); 2825 } 2826 return Result; 2827 } 2828 case Intrinsic::arm_neon_vmulls: 2829 case Intrinsic::arm_neon_vmullu: { 2830 unsigned NewOpc = (IntNo == Intrinsic::arm_neon_vmulls) 2831 ? ARMISD::VMULLs : ARMISD::VMULLu; 2832 return DAG.getNode(NewOpc, SDLoc(Op), Op.getValueType(), 2833 Op.getOperand(1), Op.getOperand(2)); 2834 } 2835 case Intrinsic::arm_neon_vminnm: 2836 case Intrinsic::arm_neon_vmaxnm: { 2837 unsigned NewOpc = (IntNo == Intrinsic::arm_neon_vminnm) 2838 ? ISD::FMINNUM : ISD::FMAXNUM; 2839 return DAG.getNode(NewOpc, SDLoc(Op), Op.getValueType(), 2840 Op.getOperand(1), Op.getOperand(2)); 2841 } 2842 case Intrinsic::arm_neon_vminu: 2843 case Intrinsic::arm_neon_vmaxu: { 2844 if (Op.getValueType().isFloatingPoint()) 2845 return SDValue(); 2846 unsigned NewOpc = (IntNo == Intrinsic::arm_neon_vminu) 2847 ? ISD::UMIN : ISD::UMAX; 2848 return DAG.getNode(NewOpc, SDLoc(Op), Op.getValueType(), 2849 Op.getOperand(1), Op.getOperand(2)); 2850 } 2851 case Intrinsic::arm_neon_vmins: 2852 case Intrinsic::arm_neon_vmaxs: { 2853 // v{min,max}s is overloaded between signed integers and floats. 2854 if (!Op.getValueType().isFloatingPoint()) { 2855 unsigned NewOpc = (IntNo == Intrinsic::arm_neon_vmins) 2856 ? ISD::SMIN : ISD::SMAX; 2857 return DAG.getNode(NewOpc, SDLoc(Op), Op.getValueType(), 2858 Op.getOperand(1), Op.getOperand(2)); 2859 } 2860 unsigned NewOpc = (IntNo == Intrinsic::arm_neon_vmins) 2861 ? ISD::FMINNAN : ISD::FMAXNAN; 2862 return DAG.getNode(NewOpc, SDLoc(Op), Op.getValueType(), 2863 Op.getOperand(1), Op.getOperand(2)); 2864 } 2865 } 2866 } 2867 2868 static SDValue LowerATOMIC_FENCE(SDValue Op, SelectionDAG &DAG, 2869 const ARMSubtarget *Subtarget) { 2870 // FIXME: handle "fence singlethread" more efficiently. 2871 SDLoc dl(Op); 2872 if (!Subtarget->hasDataBarrier()) { 2873 // Some ARMv6 cpus can support data barriers with an mcr instruction. 2874 // Thumb1 and pre-v6 ARM mode use a libcall instead and should never get 2875 // here. 2876 assert(Subtarget->hasV6Ops() && !Subtarget->isThumb() && 2877 "Unexpected ISD::ATOMIC_FENCE encountered. Should be libcall!"); 2878 return DAG.getNode(ARMISD::MEMBARRIER_MCR, dl, MVT::Other, Op.getOperand(0), 2879 DAG.getConstant(0, dl, MVT::i32)); 2880 } 2881 2882 ConstantSDNode *OrdN = cast<ConstantSDNode>(Op.getOperand(1)); 2883 AtomicOrdering Ord = static_cast<AtomicOrdering>(OrdN->getZExtValue()); 2884 ARM_MB::MemBOpt Domain = ARM_MB::ISH; 2885 if (Subtarget->isMClass()) { 2886 // Only a full system barrier exists in the M-class architectures. 2887 Domain = ARM_MB::SY; 2888 } else if (Subtarget->isSwift() && Ord == Release) { 2889 // Swift happens to implement ISHST barriers in a way that's compatible with 2890 // Release semantics but weaker than ISH so we'd be fools not to use 2891 // it. Beware: other processors probably don't! 2892 Domain = ARM_MB::ISHST; 2893 } 2894 2895 return DAG.getNode(ISD::INTRINSIC_VOID, dl, MVT::Other, Op.getOperand(0), 2896 DAG.getConstant(Intrinsic::arm_dmb, dl, MVT::i32), 2897 DAG.getConstant(Domain, dl, MVT::i32)); 2898 } 2899 2900 static SDValue LowerPREFETCH(SDValue Op, SelectionDAG &DAG, 2901 const ARMSubtarget *Subtarget) { 2902 // ARM pre v5TE and Thumb1 does not have preload instructions. 2903 if (!(Subtarget->isThumb2() || 2904 (!Subtarget->isThumb1Only() && Subtarget->hasV5TEOps()))) 2905 // Just preserve the chain. 2906 return Op.getOperand(0); 2907 2908 SDLoc dl(Op); 2909 unsigned isRead = ~cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue() & 1; 2910 if (!isRead && 2911 (!Subtarget->hasV7Ops() || !Subtarget->hasMPExtension())) 2912 // ARMv7 with MP extension has PLDW. 2913 return Op.getOperand(0); 2914 2915 unsigned isData = cast<ConstantSDNode>(Op.getOperand(4))->getZExtValue(); 2916 if (Subtarget->isThumb()) { 2917 // Invert the bits. 2918 isRead = ~isRead & 1; 2919 isData = ~isData & 1; 2920 } 2921 2922 return DAG.getNode(ARMISD::PRELOAD, dl, MVT::Other, Op.getOperand(0), 2923 Op.getOperand(1), DAG.getConstant(isRead, dl, MVT::i32), 2924 DAG.getConstant(isData, dl, MVT::i32)); 2925 } 2926 2927 static SDValue LowerVASTART(SDValue Op, SelectionDAG &DAG) { 2928 MachineFunction &MF = DAG.getMachineFunction(); 2929 ARMFunctionInfo *FuncInfo = MF.getInfo<ARMFunctionInfo>(); 2930 2931 // vastart just stores the address of the VarArgsFrameIndex slot into the 2932 // memory location argument. 2933 SDLoc dl(Op); 2934 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout()); 2935 SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT); 2936 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue(); 2937 return DAG.getStore(Op.getOperand(0), dl, FR, Op.getOperand(1), 2938 MachinePointerInfo(SV), false, false, 0); 2939 } 2940 2941 SDValue 2942 ARMTargetLowering::GetF64FormalArgument(CCValAssign &VA, CCValAssign &NextVA, 2943 SDValue &Root, SelectionDAG &DAG, 2944 SDLoc dl) const { 2945 MachineFunction &MF = DAG.getMachineFunction(); 2946 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>(); 2947 2948 const TargetRegisterClass *RC; 2949 if (AFI->isThumb1OnlyFunction()) 2950 RC = &ARM::tGPRRegClass; 2951 else 2952 RC = &ARM::GPRRegClass; 2953 2954 // Transform the arguments stored in physical registers into virtual ones. 2955 unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC); 2956 SDValue ArgValue = DAG.getCopyFromReg(Root, dl, Reg, MVT::i32); 2957 2958 SDValue ArgValue2; 2959 if (NextVA.isMemLoc()) { 2960 MachineFrameInfo *MFI = MF.getFrameInfo(); 2961 int FI = MFI->CreateFixedObject(4, NextVA.getLocMemOffset(), true); 2962 2963 // Create load node to retrieve arguments from the stack. 2964 SDValue FIN = DAG.getFrameIndex(FI, getPointerTy(DAG.getDataLayout())); 2965 ArgValue2 = DAG.getLoad( 2966 MVT::i32, dl, Root, FIN, 2967 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI), false, 2968 false, false, 0); 2969 } else { 2970 Reg = MF.addLiveIn(NextVA.getLocReg(), RC); 2971 ArgValue2 = DAG.getCopyFromReg(Root, dl, Reg, MVT::i32); 2972 } 2973 if (!Subtarget->isLittle()) 2974 std::swap (ArgValue, ArgValue2); 2975 return DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, ArgValue, ArgValue2); 2976 } 2977 2978 // The remaining GPRs hold either the beginning of variable-argument 2979 // data, or the beginning of an aggregate passed by value (usually 2980 // byval). Either way, we allocate stack slots adjacent to the data 2981 // provided by our caller, and store the unallocated registers there. 2982 // If this is a variadic function, the va_list pointer will begin with 2983 // these values; otherwise, this reassembles a (byval) structure that 2984 // was split between registers and memory. 2985 // Return: The frame index registers were stored into. 2986 int 2987 ARMTargetLowering::StoreByValRegs(CCState &CCInfo, SelectionDAG &DAG, 2988 SDLoc dl, SDValue &Chain, 2989 const Value *OrigArg, 2990 unsigned InRegsParamRecordIdx, 2991 int ArgOffset, 2992 unsigned ArgSize) const { 2993 // Currently, two use-cases possible: 2994 // Case #1. Non-var-args function, and we meet first byval parameter. 2995 // Setup first unallocated register as first byval register; 2996 // eat all remained registers 2997 // (these two actions are performed by HandleByVal method). 2998 // Then, here, we initialize stack frame with 2999 // "store-reg" instructions. 3000 // Case #2. Var-args function, that doesn't contain byval parameters. 3001 // The same: eat all remained unallocated registers, 3002 // initialize stack frame. 3003 3004 MachineFunction &MF = DAG.getMachineFunction(); 3005 MachineFrameInfo *MFI = MF.getFrameInfo(); 3006 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>(); 3007 unsigned RBegin, REnd; 3008 if (InRegsParamRecordIdx < CCInfo.getInRegsParamsCount()) { 3009 CCInfo.getInRegsParamInfo(InRegsParamRecordIdx, RBegin, REnd); 3010 } else { 3011 unsigned RBeginIdx = CCInfo.getFirstUnallocated(GPRArgRegs); 3012 RBegin = RBeginIdx == 4 ? (unsigned)ARM::R4 : GPRArgRegs[RBeginIdx]; 3013 REnd = ARM::R4; 3014 } 3015 3016 if (REnd != RBegin) 3017 ArgOffset = -4 * (ARM::R4 - RBegin); 3018 3019 auto PtrVT = getPointerTy(DAG.getDataLayout()); 3020 int FrameIndex = MFI->CreateFixedObject(ArgSize, ArgOffset, false); 3021 SDValue FIN = DAG.getFrameIndex(FrameIndex, PtrVT); 3022 3023 SmallVector<SDValue, 4> MemOps; 3024 const TargetRegisterClass *RC = 3025 AFI->isThumb1OnlyFunction() ? &ARM::tGPRRegClass : &ARM::GPRRegClass; 3026 3027 for (unsigned Reg = RBegin, i = 0; Reg < REnd; ++Reg, ++i) { 3028 unsigned VReg = MF.addLiveIn(Reg, RC); 3029 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i32); 3030 SDValue Store = 3031 DAG.getStore(Val.getValue(1), dl, Val, FIN, 3032 MachinePointerInfo(OrigArg, 4 * i), false, false, 0); 3033 MemOps.push_back(Store); 3034 FIN = DAG.getNode(ISD::ADD, dl, PtrVT, FIN, DAG.getConstant(4, dl, PtrVT)); 3035 } 3036 3037 if (!MemOps.empty()) 3038 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOps); 3039 return FrameIndex; 3040 } 3041 3042 // Setup stack frame, the va_list pointer will start from. 3043 void 3044 ARMTargetLowering::VarArgStyleRegisters(CCState &CCInfo, SelectionDAG &DAG, 3045 SDLoc dl, SDValue &Chain, 3046 unsigned ArgOffset, 3047 unsigned TotalArgRegsSaveSize, 3048 bool ForceMutable) const { 3049 MachineFunction &MF = DAG.getMachineFunction(); 3050 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>(); 3051 3052 // Try to store any remaining integer argument regs 3053 // to their spots on the stack so that they may be loaded by deferencing 3054 // the result of va_next. 3055 // If there is no regs to be stored, just point address after last 3056 // argument passed via stack. 3057 int FrameIndex = StoreByValRegs(CCInfo, DAG, dl, Chain, nullptr, 3058 CCInfo.getInRegsParamsCount(), 3059 CCInfo.getNextStackOffset(), 4); 3060 AFI->setVarArgsFrameIndex(FrameIndex); 3061 } 3062 3063 SDValue 3064 ARMTargetLowering::LowerFormalArguments(SDValue Chain, 3065 CallingConv::ID CallConv, bool isVarArg, 3066 const SmallVectorImpl<ISD::InputArg> 3067 &Ins, 3068 SDLoc dl, SelectionDAG &DAG, 3069 SmallVectorImpl<SDValue> &InVals) 3070 const { 3071 MachineFunction &MF = DAG.getMachineFunction(); 3072 MachineFrameInfo *MFI = MF.getFrameInfo(); 3073 3074 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>(); 3075 3076 // Assign locations to all of the incoming arguments. 3077 SmallVector<CCValAssign, 16> ArgLocs; 3078 ARMCCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), ArgLocs, 3079 *DAG.getContext(), Prologue); 3080 CCInfo.AnalyzeFormalArguments(Ins, 3081 CCAssignFnForNode(CallConv, /* Return*/ false, 3082 isVarArg)); 3083 3084 SmallVector<SDValue, 16> ArgValues; 3085 SDValue ArgValue; 3086 Function::const_arg_iterator CurOrigArg = MF.getFunction()->arg_begin(); 3087 unsigned CurArgIdx = 0; 3088 3089 // Initially ArgRegsSaveSize is zero. 3090 // Then we increase this value each time we meet byval parameter. 3091 // We also increase this value in case of varargs function. 3092 AFI->setArgRegsSaveSize(0); 3093 3094 // Calculate the amount of stack space that we need to allocate to store 3095 // byval and variadic arguments that are passed in registers. 3096 // We need to know this before we allocate the first byval or variadic 3097 // argument, as they will be allocated a stack slot below the CFA (Canonical 3098 // Frame Address, the stack pointer at entry to the function). 3099 unsigned ArgRegBegin = ARM::R4; 3100 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) { 3101 if (CCInfo.getInRegsParamsProcessed() >= CCInfo.getInRegsParamsCount()) 3102 break; 3103 3104 CCValAssign &VA = ArgLocs[i]; 3105 unsigned Index = VA.getValNo(); 3106 ISD::ArgFlagsTy Flags = Ins[Index].Flags; 3107 if (!Flags.isByVal()) 3108 continue; 3109 3110 assert(VA.isMemLoc() && "unexpected byval pointer in reg"); 3111 unsigned RBegin, REnd; 3112 CCInfo.getInRegsParamInfo(CCInfo.getInRegsParamsProcessed(), RBegin, REnd); 3113 ArgRegBegin = std::min(ArgRegBegin, RBegin); 3114 3115 CCInfo.nextInRegsParam(); 3116 } 3117 CCInfo.rewindByValRegsInfo(); 3118 3119 int lastInsIndex = -1; 3120 if (isVarArg && MFI->hasVAStart()) { 3121 unsigned RegIdx = CCInfo.getFirstUnallocated(GPRArgRegs); 3122 if (RegIdx != array_lengthof(GPRArgRegs)) 3123 ArgRegBegin = std::min(ArgRegBegin, (unsigned)GPRArgRegs[RegIdx]); 3124 } 3125 3126 unsigned TotalArgRegsSaveSize = 4 * (ARM::R4 - ArgRegBegin); 3127 AFI->setArgRegsSaveSize(TotalArgRegsSaveSize); 3128 auto PtrVT = getPointerTy(DAG.getDataLayout()); 3129 3130 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) { 3131 CCValAssign &VA = ArgLocs[i]; 3132 if (Ins[VA.getValNo()].isOrigArg()) { 3133 std::advance(CurOrigArg, 3134 Ins[VA.getValNo()].getOrigArgIndex() - CurArgIdx); 3135 CurArgIdx = Ins[VA.getValNo()].getOrigArgIndex(); 3136 } 3137 // Arguments stored in registers. 3138 if (VA.isRegLoc()) { 3139 EVT RegVT = VA.getLocVT(); 3140 3141 if (VA.needsCustom()) { 3142 // f64 and vector types are split up into multiple registers or 3143 // combinations of registers and stack slots. 3144 if (VA.getLocVT() == MVT::v2f64) { 3145 SDValue ArgValue1 = GetF64FormalArgument(VA, ArgLocs[++i], 3146 Chain, DAG, dl); 3147 VA = ArgLocs[++i]; // skip ahead to next loc 3148 SDValue ArgValue2; 3149 if (VA.isMemLoc()) { 3150 int FI = MFI->CreateFixedObject(8, VA.getLocMemOffset(), true); 3151 SDValue FIN = DAG.getFrameIndex(FI, PtrVT); 3152 ArgValue2 = DAG.getLoad( 3153 MVT::f64, dl, Chain, FIN, 3154 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI), 3155 false, false, false, 0); 3156 } else { 3157 ArgValue2 = GetF64FormalArgument(VA, ArgLocs[++i], 3158 Chain, DAG, dl); 3159 } 3160 ArgValue = DAG.getNode(ISD::UNDEF, dl, MVT::v2f64); 3161 ArgValue = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, 3162 ArgValue, ArgValue1, 3163 DAG.getIntPtrConstant(0, dl)); 3164 ArgValue = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, 3165 ArgValue, ArgValue2, 3166 DAG.getIntPtrConstant(1, dl)); 3167 } else 3168 ArgValue = GetF64FormalArgument(VA, ArgLocs[++i], Chain, DAG, dl); 3169 3170 } else { 3171 const TargetRegisterClass *RC; 3172 3173 if (RegVT == MVT::f32) 3174 RC = &ARM::SPRRegClass; 3175 else if (RegVT == MVT::f64) 3176 RC = &ARM::DPRRegClass; 3177 else if (RegVT == MVT::v2f64) 3178 RC = &ARM::QPRRegClass; 3179 else if (RegVT == MVT::i32) 3180 RC = AFI->isThumb1OnlyFunction() ? &ARM::tGPRRegClass 3181 : &ARM::GPRRegClass; 3182 else 3183 llvm_unreachable("RegVT not supported by FORMAL_ARGUMENTS Lowering"); 3184 3185 // Transform the arguments in physical registers into virtual ones. 3186 unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC); 3187 ArgValue = DAG.getCopyFromReg(Chain, dl, Reg, RegVT); 3188 } 3189 3190 // If this is an 8 or 16-bit value, it is really passed promoted 3191 // to 32 bits. Insert an assert[sz]ext to capture this, then 3192 // truncate to the right size. 3193 switch (VA.getLocInfo()) { 3194 default: llvm_unreachable("Unknown loc info!"); 3195 case CCValAssign::Full: break; 3196 case CCValAssign::BCvt: 3197 ArgValue = DAG.getNode(ISD::BITCAST, dl, VA.getValVT(), ArgValue); 3198 break; 3199 case CCValAssign::SExt: 3200 ArgValue = DAG.getNode(ISD::AssertSext, dl, RegVT, ArgValue, 3201 DAG.getValueType(VA.getValVT())); 3202 ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue); 3203 break; 3204 case CCValAssign::ZExt: 3205 ArgValue = DAG.getNode(ISD::AssertZext, dl, RegVT, ArgValue, 3206 DAG.getValueType(VA.getValVT())); 3207 ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue); 3208 break; 3209 } 3210 3211 InVals.push_back(ArgValue); 3212 3213 } else { // VA.isRegLoc() 3214 3215 // sanity check 3216 assert(VA.isMemLoc()); 3217 assert(VA.getValVT() != MVT::i64 && "i64 should already be lowered"); 3218 3219 int index = VA.getValNo(); 3220 3221 // Some Ins[] entries become multiple ArgLoc[] entries. 3222 // Process them only once. 3223 if (index != lastInsIndex) 3224 { 3225 ISD::ArgFlagsTy Flags = Ins[index].Flags; 3226 // FIXME: For now, all byval parameter objects are marked mutable. 3227 // This can be changed with more analysis. 3228 // In case of tail call optimization mark all arguments mutable. 3229 // Since they could be overwritten by lowering of arguments in case of 3230 // a tail call. 3231 if (Flags.isByVal()) { 3232 assert(Ins[index].isOrigArg() && 3233 "Byval arguments cannot be implicit"); 3234 unsigned CurByValIndex = CCInfo.getInRegsParamsProcessed(); 3235 3236 int FrameIndex = StoreByValRegs( 3237 CCInfo, DAG, dl, Chain, &*CurOrigArg, CurByValIndex, 3238 VA.getLocMemOffset(), Flags.getByValSize()); 3239 InVals.push_back(DAG.getFrameIndex(FrameIndex, PtrVT)); 3240 CCInfo.nextInRegsParam(); 3241 } else { 3242 unsigned FIOffset = VA.getLocMemOffset(); 3243 int FI = MFI->CreateFixedObject(VA.getLocVT().getSizeInBits()/8, 3244 FIOffset, true); 3245 3246 // Create load nodes to retrieve arguments from the stack. 3247 SDValue FIN = DAG.getFrameIndex(FI, PtrVT); 3248 InVals.push_back(DAG.getLoad( 3249 VA.getValVT(), dl, Chain, FIN, 3250 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI), 3251 false, false, false, 0)); 3252 } 3253 lastInsIndex = index; 3254 } 3255 } 3256 } 3257 3258 // varargs 3259 if (isVarArg && MFI->hasVAStart()) 3260 VarArgStyleRegisters(CCInfo, DAG, dl, Chain, 3261 CCInfo.getNextStackOffset(), 3262 TotalArgRegsSaveSize); 3263 3264 AFI->setArgumentStackSize(CCInfo.getNextStackOffset()); 3265 3266 return Chain; 3267 } 3268 3269 /// isFloatingPointZero - Return true if this is +0.0. 3270 static bool isFloatingPointZero(SDValue Op) { 3271 if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Op)) 3272 return CFP->getValueAPF().isPosZero(); 3273 else if (ISD::isEXTLoad(Op.getNode()) || ISD::isNON_EXTLoad(Op.getNode())) { 3274 // Maybe this has already been legalized into the constant pool? 3275 if (Op.getOperand(1).getOpcode() == ARMISD::Wrapper) { 3276 SDValue WrapperOp = Op.getOperand(1).getOperand(0); 3277 if (ConstantPoolSDNode *CP = dyn_cast<ConstantPoolSDNode>(WrapperOp)) 3278 if (const ConstantFP *CFP = dyn_cast<ConstantFP>(CP->getConstVal())) 3279 return CFP->getValueAPF().isPosZero(); 3280 } 3281 } else if (Op->getOpcode() == ISD::BITCAST && 3282 Op->getValueType(0) == MVT::f64) { 3283 // Handle (ISD::BITCAST (ARMISD::VMOVIMM (ISD::TargetConstant 0)) MVT::f64) 3284 // created by LowerConstantFP(). 3285 SDValue BitcastOp = Op->getOperand(0); 3286 if (BitcastOp->getOpcode() == ARMISD::VMOVIMM && 3287 isNullConstant(BitcastOp->getOperand(0))) 3288 return true; 3289 } 3290 return false; 3291 } 3292 3293 /// Returns appropriate ARM CMP (cmp) and corresponding condition code for 3294 /// the given operands. 3295 SDValue 3296 ARMTargetLowering::getARMCmp(SDValue LHS, SDValue RHS, ISD::CondCode CC, 3297 SDValue &ARMcc, SelectionDAG &DAG, 3298 SDLoc dl) const { 3299 if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS.getNode())) { 3300 unsigned C = RHSC->getZExtValue(); 3301 if (!isLegalICmpImmediate(C)) { 3302 // Constant does not fit, try adjusting it by one? 3303 switch (CC) { 3304 default: break; 3305 case ISD::SETLT: 3306 case ISD::SETGE: 3307 if (C != 0x80000000 && isLegalICmpImmediate(C-1)) { 3308 CC = (CC == ISD::SETLT) ? ISD::SETLE : ISD::SETGT; 3309 RHS = DAG.getConstant(C - 1, dl, MVT::i32); 3310 } 3311 break; 3312 case ISD::SETULT: 3313 case ISD::SETUGE: 3314 if (C != 0 && isLegalICmpImmediate(C-1)) { 3315 CC = (CC == ISD::SETULT) ? ISD::SETULE : ISD::SETUGT; 3316 RHS = DAG.getConstant(C - 1, dl, MVT::i32); 3317 } 3318 break; 3319 case ISD::SETLE: 3320 case ISD::SETGT: 3321 if (C != 0x7fffffff && isLegalICmpImmediate(C+1)) { 3322 CC = (CC == ISD::SETLE) ? ISD::SETLT : ISD::SETGE; 3323 RHS = DAG.getConstant(C + 1, dl, MVT::i32); 3324 } 3325 break; 3326 case ISD::SETULE: 3327 case ISD::SETUGT: 3328 if (C != 0xffffffff && isLegalICmpImmediate(C+1)) { 3329 CC = (CC == ISD::SETULE) ? ISD::SETULT : ISD::SETUGE; 3330 RHS = DAG.getConstant(C + 1, dl, MVT::i32); 3331 } 3332 break; 3333 } 3334 } 3335 } 3336 3337 ARMCC::CondCodes CondCode = IntCCToARMCC(CC); 3338 ARMISD::NodeType CompareType; 3339 switch (CondCode) { 3340 default: 3341 CompareType = ARMISD::CMP; 3342 break; 3343 case ARMCC::EQ: 3344 case ARMCC::NE: 3345 // Uses only Z Flag 3346 CompareType = ARMISD::CMPZ; 3347 break; 3348 } 3349 ARMcc = DAG.getConstant(CondCode, dl, MVT::i32); 3350 return DAG.getNode(CompareType, dl, MVT::Glue, LHS, RHS); 3351 } 3352 3353 /// Returns a appropriate VFP CMP (fcmp{s|d}+fmstat) for the given operands. 3354 SDValue 3355 ARMTargetLowering::getVFPCmp(SDValue LHS, SDValue RHS, SelectionDAG &DAG, 3356 SDLoc dl) const { 3357 assert(!Subtarget->isFPOnlySP() || RHS.getValueType() != MVT::f64); 3358 SDValue Cmp; 3359 if (!isFloatingPointZero(RHS)) 3360 Cmp = DAG.getNode(ARMISD::CMPFP, dl, MVT::Glue, LHS, RHS); 3361 else 3362 Cmp = DAG.getNode(ARMISD::CMPFPw0, dl, MVT::Glue, LHS); 3363 return DAG.getNode(ARMISD::FMSTAT, dl, MVT::Glue, Cmp); 3364 } 3365 3366 /// duplicateCmp - Glue values can have only one use, so this function 3367 /// duplicates a comparison node. 3368 SDValue 3369 ARMTargetLowering::duplicateCmp(SDValue Cmp, SelectionDAG &DAG) const { 3370 unsigned Opc = Cmp.getOpcode(); 3371 SDLoc DL(Cmp); 3372 if (Opc == ARMISD::CMP || Opc == ARMISD::CMPZ) 3373 return DAG.getNode(Opc, DL, MVT::Glue, Cmp.getOperand(0),Cmp.getOperand(1)); 3374 3375 assert(Opc == ARMISD::FMSTAT && "unexpected comparison operation"); 3376 Cmp = Cmp.getOperand(0); 3377 Opc = Cmp.getOpcode(); 3378 if (Opc == ARMISD::CMPFP) 3379 Cmp = DAG.getNode(Opc, DL, MVT::Glue, Cmp.getOperand(0),Cmp.getOperand(1)); 3380 else { 3381 assert(Opc == ARMISD::CMPFPw0 && "unexpected operand of FMSTAT"); 3382 Cmp = DAG.getNode(Opc, DL, MVT::Glue, Cmp.getOperand(0)); 3383 } 3384 return DAG.getNode(ARMISD::FMSTAT, DL, MVT::Glue, Cmp); 3385 } 3386 3387 std::pair<SDValue, SDValue> 3388 ARMTargetLowering::getARMXALUOOp(SDValue Op, SelectionDAG &DAG, 3389 SDValue &ARMcc) const { 3390 assert(Op.getValueType() == MVT::i32 && "Unsupported value type"); 3391 3392 SDValue Value, OverflowCmp; 3393 SDValue LHS = Op.getOperand(0); 3394 SDValue RHS = Op.getOperand(1); 3395 SDLoc dl(Op); 3396 3397 // FIXME: We are currently always generating CMPs because we don't support 3398 // generating CMN through the backend. This is not as good as the natural 3399 // CMP case because it causes a register dependency and cannot be folded 3400 // later. 3401 3402 switch (Op.getOpcode()) { 3403 default: 3404 llvm_unreachable("Unknown overflow instruction!"); 3405 case ISD::SADDO: 3406 ARMcc = DAG.getConstant(ARMCC::VC, dl, MVT::i32); 3407 Value = DAG.getNode(ISD::ADD, dl, Op.getValueType(), LHS, RHS); 3408 OverflowCmp = DAG.getNode(ARMISD::CMP, dl, MVT::Glue, Value, LHS); 3409 break; 3410 case ISD::UADDO: 3411 ARMcc = DAG.getConstant(ARMCC::HS, dl, MVT::i32); 3412 Value = DAG.getNode(ISD::ADD, dl, Op.getValueType(), LHS, RHS); 3413 OverflowCmp = DAG.getNode(ARMISD::CMP, dl, MVT::Glue, Value, LHS); 3414 break; 3415 case ISD::SSUBO: 3416 ARMcc = DAG.getConstant(ARMCC::VC, dl, MVT::i32); 3417 Value = DAG.getNode(ISD::SUB, dl, Op.getValueType(), LHS, RHS); 3418 OverflowCmp = DAG.getNode(ARMISD::CMP, dl, MVT::Glue, LHS, RHS); 3419 break; 3420 case ISD::USUBO: 3421 ARMcc = DAG.getConstant(ARMCC::HS, dl, MVT::i32); 3422 Value = DAG.getNode(ISD::SUB, dl, Op.getValueType(), LHS, RHS); 3423 OverflowCmp = DAG.getNode(ARMISD::CMP, dl, MVT::Glue, LHS, RHS); 3424 break; 3425 } // switch (...) 3426 3427 return std::make_pair(Value, OverflowCmp); 3428 } 3429 3430 3431 SDValue 3432 ARMTargetLowering::LowerXALUO(SDValue Op, SelectionDAG &DAG) const { 3433 // Let legalize expand this if it isn't a legal type yet. 3434 if (!DAG.getTargetLoweringInfo().isTypeLegal(Op.getValueType())) 3435 return SDValue(); 3436 3437 SDValue Value, OverflowCmp; 3438 SDValue ARMcc; 3439 std::tie(Value, OverflowCmp) = getARMXALUOOp(Op, DAG, ARMcc); 3440 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32); 3441 SDLoc dl(Op); 3442 // We use 0 and 1 as false and true values. 3443 SDValue TVal = DAG.getConstant(1, dl, MVT::i32); 3444 SDValue FVal = DAG.getConstant(0, dl, MVT::i32); 3445 EVT VT = Op.getValueType(); 3446 3447 SDValue Overflow = DAG.getNode(ARMISD::CMOV, dl, VT, TVal, FVal, 3448 ARMcc, CCR, OverflowCmp); 3449 3450 SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32); 3451 return DAG.getNode(ISD::MERGE_VALUES, dl, VTs, Value, Overflow); 3452 } 3453 3454 3455 SDValue ARMTargetLowering::LowerSELECT(SDValue Op, SelectionDAG &DAG) const { 3456 SDValue Cond = Op.getOperand(0); 3457 SDValue SelectTrue = Op.getOperand(1); 3458 SDValue SelectFalse = Op.getOperand(2); 3459 SDLoc dl(Op); 3460 unsigned Opc = Cond.getOpcode(); 3461 3462 if (Cond.getResNo() == 1 && 3463 (Opc == ISD::SADDO || Opc == ISD::UADDO || Opc == ISD::SSUBO || 3464 Opc == ISD::USUBO)) { 3465 if (!DAG.getTargetLoweringInfo().isTypeLegal(Cond->getValueType(0))) 3466 return SDValue(); 3467 3468 SDValue Value, OverflowCmp; 3469 SDValue ARMcc; 3470 std::tie(Value, OverflowCmp) = getARMXALUOOp(Cond, DAG, ARMcc); 3471 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32); 3472 EVT VT = Op.getValueType(); 3473 3474 return getCMOV(dl, VT, SelectTrue, SelectFalse, ARMcc, CCR, 3475 OverflowCmp, DAG); 3476 } 3477 3478 // Convert: 3479 // 3480 // (select (cmov 1, 0, cond), t, f) -> (cmov t, f, cond) 3481 // (select (cmov 0, 1, cond), t, f) -> (cmov f, t, cond) 3482 // 3483 if (Cond.getOpcode() == ARMISD::CMOV && Cond.hasOneUse()) { 3484 const ConstantSDNode *CMOVTrue = 3485 dyn_cast<ConstantSDNode>(Cond.getOperand(0)); 3486 const ConstantSDNode *CMOVFalse = 3487 dyn_cast<ConstantSDNode>(Cond.getOperand(1)); 3488 3489 if (CMOVTrue && CMOVFalse) { 3490 unsigned CMOVTrueVal = CMOVTrue->getZExtValue(); 3491 unsigned CMOVFalseVal = CMOVFalse->getZExtValue(); 3492 3493 SDValue True; 3494 SDValue False; 3495 if (CMOVTrueVal == 1 && CMOVFalseVal == 0) { 3496 True = SelectTrue; 3497 False = SelectFalse; 3498 } else if (CMOVTrueVal == 0 && CMOVFalseVal == 1) { 3499 True = SelectFalse; 3500 False = SelectTrue; 3501 } 3502 3503 if (True.getNode() && False.getNode()) { 3504 EVT VT = Op.getValueType(); 3505 SDValue ARMcc = Cond.getOperand(2); 3506 SDValue CCR = Cond.getOperand(3); 3507 SDValue Cmp = duplicateCmp(Cond.getOperand(4), DAG); 3508 assert(True.getValueType() == VT); 3509 return getCMOV(dl, VT, True, False, ARMcc, CCR, Cmp, DAG); 3510 } 3511 } 3512 } 3513 3514 // ARM's BooleanContents value is UndefinedBooleanContent. Mask out the 3515 // undefined bits before doing a full-word comparison with zero. 3516 Cond = DAG.getNode(ISD::AND, dl, Cond.getValueType(), Cond, 3517 DAG.getConstant(1, dl, Cond.getValueType())); 3518 3519 return DAG.getSelectCC(dl, Cond, 3520 DAG.getConstant(0, dl, Cond.getValueType()), 3521 SelectTrue, SelectFalse, ISD::SETNE); 3522 } 3523 3524 static void checkVSELConstraints(ISD::CondCode CC, ARMCC::CondCodes &CondCode, 3525 bool &swpCmpOps, bool &swpVselOps) { 3526 // Start by selecting the GE condition code for opcodes that return true for 3527 // 'equality' 3528 if (CC == ISD::SETUGE || CC == ISD::SETOGE || CC == ISD::SETOLE || 3529 CC == ISD::SETULE) 3530 CondCode = ARMCC::GE; 3531 3532 // and GT for opcodes that return false for 'equality'. 3533 else if (CC == ISD::SETUGT || CC == ISD::SETOGT || CC == ISD::SETOLT || 3534 CC == ISD::SETULT) 3535 CondCode = ARMCC::GT; 3536 3537 // Since we are constrained to GE/GT, if the opcode contains 'less', we need 3538 // to swap the compare operands. 3539 if (CC == ISD::SETOLE || CC == ISD::SETULE || CC == ISD::SETOLT || 3540 CC == ISD::SETULT) 3541 swpCmpOps = true; 3542 3543 // Both GT and GE are ordered comparisons, and return false for 'unordered'. 3544 // If we have an unordered opcode, we need to swap the operands to the VSEL 3545 // instruction (effectively negating the condition). 3546 // 3547 // This also has the effect of swapping which one of 'less' or 'greater' 3548 // returns true, so we also swap the compare operands. It also switches 3549 // whether we return true for 'equality', so we compensate by picking the 3550 // opposite condition code to our original choice. 3551 if (CC == ISD::SETULE || CC == ISD::SETULT || CC == ISD::SETUGE || 3552 CC == ISD::SETUGT) { 3553 swpCmpOps = !swpCmpOps; 3554 swpVselOps = !swpVselOps; 3555 CondCode = CondCode == ARMCC::GT ? ARMCC::GE : ARMCC::GT; 3556 } 3557 3558 // 'ordered' is 'anything but unordered', so use the VS condition code and 3559 // swap the VSEL operands. 3560 if (CC == ISD::SETO) { 3561 CondCode = ARMCC::VS; 3562 swpVselOps = true; 3563 } 3564 3565 // 'unordered or not equal' is 'anything but equal', so use the EQ condition 3566 // code and swap the VSEL operands. 3567 if (CC == ISD::SETUNE) { 3568 CondCode = ARMCC::EQ; 3569 swpVselOps = true; 3570 } 3571 } 3572 3573 SDValue ARMTargetLowering::getCMOV(SDLoc dl, EVT VT, SDValue FalseVal, 3574 SDValue TrueVal, SDValue ARMcc, SDValue CCR, 3575 SDValue Cmp, SelectionDAG &DAG) const { 3576 if (Subtarget->isFPOnlySP() && VT == MVT::f64) { 3577 FalseVal = DAG.getNode(ARMISD::VMOVRRD, dl, 3578 DAG.getVTList(MVT::i32, MVT::i32), FalseVal); 3579 TrueVal = DAG.getNode(ARMISD::VMOVRRD, dl, 3580 DAG.getVTList(MVT::i32, MVT::i32), TrueVal); 3581 3582 SDValue TrueLow = TrueVal.getValue(0); 3583 SDValue TrueHigh = TrueVal.getValue(1); 3584 SDValue FalseLow = FalseVal.getValue(0); 3585 SDValue FalseHigh = FalseVal.getValue(1); 3586 3587 SDValue Low = DAG.getNode(ARMISD::CMOV, dl, MVT::i32, FalseLow, TrueLow, 3588 ARMcc, CCR, Cmp); 3589 SDValue High = DAG.getNode(ARMISD::CMOV, dl, MVT::i32, FalseHigh, TrueHigh, 3590 ARMcc, CCR, duplicateCmp(Cmp, DAG)); 3591 3592 return DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Low, High); 3593 } else { 3594 return DAG.getNode(ARMISD::CMOV, dl, VT, FalseVal, TrueVal, ARMcc, CCR, 3595 Cmp); 3596 } 3597 } 3598 3599 SDValue ARMTargetLowering::LowerSELECT_CC(SDValue Op, SelectionDAG &DAG) const { 3600 EVT VT = Op.getValueType(); 3601 SDValue LHS = Op.getOperand(0); 3602 SDValue RHS = Op.getOperand(1); 3603 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(4))->get(); 3604 SDValue TrueVal = Op.getOperand(2); 3605 SDValue FalseVal = Op.getOperand(3); 3606 SDLoc dl(Op); 3607 3608 if (Subtarget->isFPOnlySP() && LHS.getValueType() == MVT::f64) { 3609 DAG.getTargetLoweringInfo().softenSetCCOperands(DAG, MVT::f64, LHS, RHS, CC, 3610 dl); 3611 3612 // If softenSetCCOperands only returned one value, we should compare it to 3613 // zero. 3614 if (!RHS.getNode()) { 3615 RHS = DAG.getConstant(0, dl, LHS.getValueType()); 3616 CC = ISD::SETNE; 3617 } 3618 } 3619 3620 if (LHS.getValueType() == MVT::i32) { 3621 // Try to generate VSEL on ARMv8. 3622 // The VSEL instruction can't use all the usual ARM condition 3623 // codes: it only has two bits to select the condition code, so it's 3624 // constrained to use only GE, GT, VS and EQ. 3625 // 3626 // To implement all the various ISD::SETXXX opcodes, we sometimes need to 3627 // swap the operands of the previous compare instruction (effectively 3628 // inverting the compare condition, swapping 'less' and 'greater') and 3629 // sometimes need to swap the operands to the VSEL (which inverts the 3630 // condition in the sense of firing whenever the previous condition didn't) 3631 if (Subtarget->hasFPARMv8() && (TrueVal.getValueType() == MVT::f32 || 3632 TrueVal.getValueType() == MVT::f64)) { 3633 ARMCC::CondCodes CondCode = IntCCToARMCC(CC); 3634 if (CondCode == ARMCC::LT || CondCode == ARMCC::LE || 3635 CondCode == ARMCC::VC || CondCode == ARMCC::NE) { 3636 CC = ISD::getSetCCInverse(CC, true); 3637 std::swap(TrueVal, FalseVal); 3638 } 3639 } 3640 3641 SDValue ARMcc; 3642 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32); 3643 SDValue Cmp = getARMCmp(LHS, RHS, CC, ARMcc, DAG, dl); 3644 return getCMOV(dl, VT, FalseVal, TrueVal, ARMcc, CCR, Cmp, DAG); 3645 } 3646 3647 ARMCC::CondCodes CondCode, CondCode2; 3648 FPCCToARMCC(CC, CondCode, CondCode2); 3649 3650 // Try to generate VMAXNM/VMINNM on ARMv8. 3651 if (Subtarget->hasFPARMv8() && (TrueVal.getValueType() == MVT::f32 || 3652 TrueVal.getValueType() == MVT::f64)) { 3653 bool swpCmpOps = false; 3654 bool swpVselOps = false; 3655 checkVSELConstraints(CC, CondCode, swpCmpOps, swpVselOps); 3656 3657 if (CondCode == ARMCC::GT || CondCode == ARMCC::GE || 3658 CondCode == ARMCC::VS || CondCode == ARMCC::EQ) { 3659 if (swpCmpOps) 3660 std::swap(LHS, RHS); 3661 if (swpVselOps) 3662 std::swap(TrueVal, FalseVal); 3663 } 3664 } 3665 3666 SDValue ARMcc = DAG.getConstant(CondCode, dl, MVT::i32); 3667 SDValue Cmp = getVFPCmp(LHS, RHS, DAG, dl); 3668 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32); 3669 SDValue Result = getCMOV(dl, VT, FalseVal, TrueVal, ARMcc, CCR, Cmp, DAG); 3670 if (CondCode2 != ARMCC::AL) { 3671 SDValue ARMcc2 = DAG.getConstant(CondCode2, dl, MVT::i32); 3672 // FIXME: Needs another CMP because flag can have but one use. 3673 SDValue Cmp2 = getVFPCmp(LHS, RHS, DAG, dl); 3674 Result = getCMOV(dl, VT, Result, TrueVal, ARMcc2, CCR, Cmp2, DAG); 3675 } 3676 return Result; 3677 } 3678 3679 /// canChangeToInt - Given the fp compare operand, return true if it is suitable 3680 /// to morph to an integer compare sequence. 3681 static bool canChangeToInt(SDValue Op, bool &SeenZero, 3682 const ARMSubtarget *Subtarget) { 3683 SDNode *N = Op.getNode(); 3684 if (!N->hasOneUse()) 3685 // Otherwise it requires moving the value from fp to integer registers. 3686 return false; 3687 if (!N->getNumValues()) 3688 return false; 3689 EVT VT = Op.getValueType(); 3690 if (VT != MVT::f32 && !Subtarget->isFPBrccSlow()) 3691 // f32 case is generally profitable. f64 case only makes sense when vcmpe + 3692 // vmrs are very slow, e.g. cortex-a8. 3693 return false; 3694 3695 if (isFloatingPointZero(Op)) { 3696 SeenZero = true; 3697 return true; 3698 } 3699 return ISD::isNormalLoad(N); 3700 } 3701 3702 static SDValue bitcastf32Toi32(SDValue Op, SelectionDAG &DAG) { 3703 if (isFloatingPointZero(Op)) 3704 return DAG.getConstant(0, SDLoc(Op), MVT::i32); 3705 3706 if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Op)) 3707 return DAG.getLoad(MVT::i32, SDLoc(Op), 3708 Ld->getChain(), Ld->getBasePtr(), Ld->getPointerInfo(), 3709 Ld->isVolatile(), Ld->isNonTemporal(), 3710 Ld->isInvariant(), Ld->getAlignment()); 3711 3712 llvm_unreachable("Unknown VFP cmp argument!"); 3713 } 3714 3715 static void expandf64Toi32(SDValue Op, SelectionDAG &DAG, 3716 SDValue &RetVal1, SDValue &RetVal2) { 3717 SDLoc dl(Op); 3718 3719 if (isFloatingPointZero(Op)) { 3720 RetVal1 = DAG.getConstant(0, dl, MVT::i32); 3721 RetVal2 = DAG.getConstant(0, dl, MVT::i32); 3722 return; 3723 } 3724 3725 if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Op)) { 3726 SDValue Ptr = Ld->getBasePtr(); 3727 RetVal1 = DAG.getLoad(MVT::i32, dl, 3728 Ld->getChain(), Ptr, 3729 Ld->getPointerInfo(), 3730 Ld->isVolatile(), Ld->isNonTemporal(), 3731 Ld->isInvariant(), Ld->getAlignment()); 3732 3733 EVT PtrType = Ptr.getValueType(); 3734 unsigned NewAlign = MinAlign(Ld->getAlignment(), 4); 3735 SDValue NewPtr = DAG.getNode(ISD::ADD, dl, 3736 PtrType, Ptr, DAG.getConstant(4, dl, PtrType)); 3737 RetVal2 = DAG.getLoad(MVT::i32, dl, 3738 Ld->getChain(), NewPtr, 3739 Ld->getPointerInfo().getWithOffset(4), 3740 Ld->isVolatile(), Ld->isNonTemporal(), 3741 Ld->isInvariant(), NewAlign); 3742 return; 3743 } 3744 3745 llvm_unreachable("Unknown VFP cmp argument!"); 3746 } 3747 3748 /// OptimizeVFPBrcond - With -enable-unsafe-fp-math, it's legal to optimize some 3749 /// f32 and even f64 comparisons to integer ones. 3750 SDValue 3751 ARMTargetLowering::OptimizeVFPBrcond(SDValue Op, SelectionDAG &DAG) const { 3752 SDValue Chain = Op.getOperand(0); 3753 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(1))->get(); 3754 SDValue LHS = Op.getOperand(2); 3755 SDValue RHS = Op.getOperand(3); 3756 SDValue Dest = Op.getOperand(4); 3757 SDLoc dl(Op); 3758 3759 bool LHSSeenZero = false; 3760 bool LHSOk = canChangeToInt(LHS, LHSSeenZero, Subtarget); 3761 bool RHSSeenZero = false; 3762 bool RHSOk = canChangeToInt(RHS, RHSSeenZero, Subtarget); 3763 if (LHSOk && RHSOk && (LHSSeenZero || RHSSeenZero)) { 3764 // If unsafe fp math optimization is enabled and there are no other uses of 3765 // the CMP operands, and the condition code is EQ or NE, we can optimize it 3766 // to an integer comparison. 3767 if (CC == ISD::SETOEQ) 3768 CC = ISD::SETEQ; 3769 else if (CC == ISD::SETUNE) 3770 CC = ISD::SETNE; 3771 3772 SDValue Mask = DAG.getConstant(0x7fffffff, dl, MVT::i32); 3773 SDValue ARMcc; 3774 if (LHS.getValueType() == MVT::f32) { 3775 LHS = DAG.getNode(ISD::AND, dl, MVT::i32, 3776 bitcastf32Toi32(LHS, DAG), Mask); 3777 RHS = DAG.getNode(ISD::AND, dl, MVT::i32, 3778 bitcastf32Toi32(RHS, DAG), Mask); 3779 SDValue Cmp = getARMCmp(LHS, RHS, CC, ARMcc, DAG, dl); 3780 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32); 3781 return DAG.getNode(ARMISD::BRCOND, dl, MVT::Other, 3782 Chain, Dest, ARMcc, CCR, Cmp); 3783 } 3784 3785 SDValue LHS1, LHS2; 3786 SDValue RHS1, RHS2; 3787 expandf64Toi32(LHS, DAG, LHS1, LHS2); 3788 expandf64Toi32(RHS, DAG, RHS1, RHS2); 3789 LHS2 = DAG.getNode(ISD::AND, dl, MVT::i32, LHS2, Mask); 3790 RHS2 = DAG.getNode(ISD::AND, dl, MVT::i32, RHS2, Mask); 3791 ARMCC::CondCodes CondCode = IntCCToARMCC(CC); 3792 ARMcc = DAG.getConstant(CondCode, dl, MVT::i32); 3793 SDVTList VTList = DAG.getVTList(MVT::Other, MVT::Glue); 3794 SDValue Ops[] = { Chain, ARMcc, LHS1, LHS2, RHS1, RHS2, Dest }; 3795 return DAG.getNode(ARMISD::BCC_i64, dl, VTList, Ops); 3796 } 3797 3798 return SDValue(); 3799 } 3800 3801 SDValue ARMTargetLowering::LowerBR_CC(SDValue Op, SelectionDAG &DAG) const { 3802 SDValue Chain = Op.getOperand(0); 3803 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(1))->get(); 3804 SDValue LHS = Op.getOperand(2); 3805 SDValue RHS = Op.getOperand(3); 3806 SDValue Dest = Op.getOperand(4); 3807 SDLoc dl(Op); 3808 3809 if (Subtarget->isFPOnlySP() && LHS.getValueType() == MVT::f64) { 3810 DAG.getTargetLoweringInfo().softenSetCCOperands(DAG, MVT::f64, LHS, RHS, CC, 3811 dl); 3812 3813 // If softenSetCCOperands only returned one value, we should compare it to 3814 // zero. 3815 if (!RHS.getNode()) { 3816 RHS = DAG.getConstant(0, dl, LHS.getValueType()); 3817 CC = ISD::SETNE; 3818 } 3819 } 3820 3821 if (LHS.getValueType() == MVT::i32) { 3822 SDValue ARMcc; 3823 SDValue Cmp = getARMCmp(LHS, RHS, CC, ARMcc, DAG, dl); 3824 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32); 3825 return DAG.getNode(ARMISD::BRCOND, dl, MVT::Other, 3826 Chain, Dest, ARMcc, CCR, Cmp); 3827 } 3828 3829 assert(LHS.getValueType() == MVT::f32 || LHS.getValueType() == MVT::f64); 3830 3831 if (getTargetMachine().Options.UnsafeFPMath && 3832 (CC == ISD::SETEQ || CC == ISD::SETOEQ || 3833 CC == ISD::SETNE || CC == ISD::SETUNE)) { 3834 SDValue Result = OptimizeVFPBrcond(Op, DAG); 3835 if (Result.getNode()) 3836 return Result; 3837 } 3838 3839 ARMCC::CondCodes CondCode, CondCode2; 3840 FPCCToARMCC(CC, CondCode, CondCode2); 3841 3842 SDValue ARMcc = DAG.getConstant(CondCode, dl, MVT::i32); 3843 SDValue Cmp = getVFPCmp(LHS, RHS, DAG, dl); 3844 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32); 3845 SDVTList VTList = DAG.getVTList(MVT::Other, MVT::Glue); 3846 SDValue Ops[] = { Chain, Dest, ARMcc, CCR, Cmp }; 3847 SDValue Res = DAG.getNode(ARMISD::BRCOND, dl, VTList, Ops); 3848 if (CondCode2 != ARMCC::AL) { 3849 ARMcc = DAG.getConstant(CondCode2, dl, MVT::i32); 3850 SDValue Ops[] = { Res, Dest, ARMcc, CCR, Res.getValue(1) }; 3851 Res = DAG.getNode(ARMISD::BRCOND, dl, VTList, Ops); 3852 } 3853 return Res; 3854 } 3855 3856 SDValue ARMTargetLowering::LowerBR_JT(SDValue Op, SelectionDAG &DAG) const { 3857 SDValue Chain = Op.getOperand(0); 3858 SDValue Table = Op.getOperand(1); 3859 SDValue Index = Op.getOperand(2); 3860 SDLoc dl(Op); 3861 3862 EVT PTy = getPointerTy(DAG.getDataLayout()); 3863 JumpTableSDNode *JT = cast<JumpTableSDNode>(Table); 3864 SDValue JTI = DAG.getTargetJumpTable(JT->getIndex(), PTy); 3865 Table = DAG.getNode(ARMISD::WrapperJT, dl, MVT::i32, JTI); 3866 Index = DAG.getNode(ISD::MUL, dl, PTy, Index, DAG.getConstant(4, dl, PTy)); 3867 SDValue Addr = DAG.getNode(ISD::ADD, dl, PTy, Index, Table); 3868 if (Subtarget->isThumb2()) { 3869 // Thumb2 uses a two-level jump. That is, it jumps into the jump table 3870 // which does another jump to the destination. This also makes it easier 3871 // to translate it to TBB / TBH later. 3872 // FIXME: This might not work if the function is extremely large. 3873 return DAG.getNode(ARMISD::BR2_JT, dl, MVT::Other, Chain, 3874 Addr, Op.getOperand(2), JTI); 3875 } 3876 if (getTargetMachine().getRelocationModel() == Reloc::PIC_) { 3877 Addr = 3878 DAG.getLoad((EVT)MVT::i32, dl, Chain, Addr, 3879 MachinePointerInfo::getJumpTable(DAG.getMachineFunction()), 3880 false, false, false, 0); 3881 Chain = Addr.getValue(1); 3882 Addr = DAG.getNode(ISD::ADD, dl, PTy, Addr, Table); 3883 return DAG.getNode(ARMISD::BR_JT, dl, MVT::Other, Chain, Addr, JTI); 3884 } else { 3885 Addr = 3886 DAG.getLoad(PTy, dl, Chain, Addr, 3887 MachinePointerInfo::getJumpTable(DAG.getMachineFunction()), 3888 false, false, false, 0); 3889 Chain = Addr.getValue(1); 3890 return DAG.getNode(ARMISD::BR_JT, dl, MVT::Other, Chain, Addr, JTI); 3891 } 3892 } 3893 3894 static SDValue LowerVectorFP_TO_INT(SDValue Op, SelectionDAG &DAG) { 3895 EVT VT = Op.getValueType(); 3896 SDLoc dl(Op); 3897 3898 if (Op.getValueType().getVectorElementType() == MVT::i32) { 3899 if (Op.getOperand(0).getValueType().getVectorElementType() == MVT::f32) 3900 return Op; 3901 return DAG.UnrollVectorOp(Op.getNode()); 3902 } 3903 3904 assert(Op.getOperand(0).getValueType() == MVT::v4f32 && 3905 "Invalid type for custom lowering!"); 3906 if (VT != MVT::v4i16) 3907 return DAG.UnrollVectorOp(Op.getNode()); 3908 3909 Op = DAG.getNode(Op.getOpcode(), dl, MVT::v4i32, Op.getOperand(0)); 3910 return DAG.getNode(ISD::TRUNCATE, dl, VT, Op); 3911 } 3912 3913 SDValue ARMTargetLowering::LowerFP_TO_INT(SDValue Op, SelectionDAG &DAG) const { 3914 EVT VT = Op.getValueType(); 3915 if (VT.isVector()) 3916 return LowerVectorFP_TO_INT(Op, DAG); 3917 if (Subtarget->isFPOnlySP() && Op.getOperand(0).getValueType() == MVT::f64) { 3918 RTLIB::Libcall LC; 3919 if (Op.getOpcode() == ISD::FP_TO_SINT) 3920 LC = RTLIB::getFPTOSINT(Op.getOperand(0).getValueType(), 3921 Op.getValueType()); 3922 else 3923 LC = RTLIB::getFPTOUINT(Op.getOperand(0).getValueType(), 3924 Op.getValueType()); 3925 return makeLibCall(DAG, LC, Op.getValueType(), Op.getOperand(0), 3926 /*isSigned*/ false, SDLoc(Op)).first; 3927 } 3928 3929 return Op; 3930 } 3931 3932 static SDValue LowerVectorINT_TO_FP(SDValue Op, SelectionDAG &DAG) { 3933 EVT VT = Op.getValueType(); 3934 SDLoc dl(Op); 3935 3936 if (Op.getOperand(0).getValueType().getVectorElementType() == MVT::i32) { 3937 if (VT.getVectorElementType() == MVT::f32) 3938 return Op; 3939 return DAG.UnrollVectorOp(Op.getNode()); 3940 } 3941 3942 assert(Op.getOperand(0).getValueType() == MVT::v4i16 && 3943 "Invalid type for custom lowering!"); 3944 if (VT != MVT::v4f32) 3945 return DAG.UnrollVectorOp(Op.getNode()); 3946 3947 unsigned CastOpc; 3948 unsigned Opc; 3949 switch (Op.getOpcode()) { 3950 default: llvm_unreachable("Invalid opcode!"); 3951 case ISD::SINT_TO_FP: 3952 CastOpc = ISD::SIGN_EXTEND; 3953 Opc = ISD::SINT_TO_FP; 3954 break; 3955 case ISD::UINT_TO_FP: 3956 CastOpc = ISD::ZERO_EXTEND; 3957 Opc = ISD::UINT_TO_FP; 3958 break; 3959 } 3960 3961 Op = DAG.getNode(CastOpc, dl, MVT::v4i32, Op.getOperand(0)); 3962 return DAG.getNode(Opc, dl, VT, Op); 3963 } 3964 3965 SDValue ARMTargetLowering::LowerINT_TO_FP(SDValue Op, SelectionDAG &DAG) const { 3966 EVT VT = Op.getValueType(); 3967 if (VT.isVector()) 3968 return LowerVectorINT_TO_FP(Op, DAG); 3969 if (Subtarget->isFPOnlySP() && Op.getValueType() == MVT::f64) { 3970 RTLIB::Libcall LC; 3971 if (Op.getOpcode() == ISD::SINT_TO_FP) 3972 LC = RTLIB::getSINTTOFP(Op.getOperand(0).getValueType(), 3973 Op.getValueType()); 3974 else 3975 LC = RTLIB::getUINTTOFP(Op.getOperand(0).getValueType(), 3976 Op.getValueType()); 3977 return makeLibCall(DAG, LC, Op.getValueType(), Op.getOperand(0), 3978 /*isSigned*/ false, SDLoc(Op)).first; 3979 } 3980 3981 return Op; 3982 } 3983 3984 SDValue ARMTargetLowering::LowerFCOPYSIGN(SDValue Op, SelectionDAG &DAG) const { 3985 // Implement fcopysign with a fabs and a conditional fneg. 3986 SDValue Tmp0 = Op.getOperand(0); 3987 SDValue Tmp1 = Op.getOperand(1); 3988 SDLoc dl(Op); 3989 EVT VT = Op.getValueType(); 3990 EVT SrcVT = Tmp1.getValueType(); 3991 bool InGPR = Tmp0.getOpcode() == ISD::BITCAST || 3992 Tmp0.getOpcode() == ARMISD::VMOVDRR; 3993 bool UseNEON = !InGPR && Subtarget->hasNEON(); 3994 3995 if (UseNEON) { 3996 // Use VBSL to copy the sign bit. 3997 unsigned EncodedVal = ARM_AM::createNEONModImm(0x6, 0x80); 3998 SDValue Mask = DAG.getNode(ARMISD::VMOVIMM, dl, MVT::v2i32, 3999 DAG.getTargetConstant(EncodedVal, dl, MVT::i32)); 4000 EVT OpVT = (VT == MVT::f32) ? MVT::v2i32 : MVT::v1i64; 4001 if (VT == MVT::f64) 4002 Mask = DAG.getNode(ARMISD::VSHL, dl, OpVT, 4003 DAG.getNode(ISD::BITCAST, dl, OpVT, Mask), 4004 DAG.getConstant(32, dl, MVT::i32)); 4005 else /*if (VT == MVT::f32)*/ 4006 Tmp0 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f32, Tmp0); 4007 if (SrcVT == MVT::f32) { 4008 Tmp1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f32, Tmp1); 4009 if (VT == MVT::f64) 4010 Tmp1 = DAG.getNode(ARMISD::VSHL, dl, OpVT, 4011 DAG.getNode(ISD::BITCAST, dl, OpVT, Tmp1), 4012 DAG.getConstant(32, dl, MVT::i32)); 4013 } else if (VT == MVT::f32) 4014 Tmp1 = DAG.getNode(ARMISD::VSHRu, dl, MVT::v1i64, 4015 DAG.getNode(ISD::BITCAST, dl, MVT::v1i64, Tmp1), 4016 DAG.getConstant(32, dl, MVT::i32)); 4017 Tmp0 = DAG.getNode(ISD::BITCAST, dl, OpVT, Tmp0); 4018 Tmp1 = DAG.getNode(ISD::BITCAST, dl, OpVT, Tmp1); 4019 4020 SDValue AllOnes = DAG.getTargetConstant(ARM_AM::createNEONModImm(0xe, 0xff), 4021 dl, MVT::i32); 4022 AllOnes = DAG.getNode(ARMISD::VMOVIMM, dl, MVT::v8i8, AllOnes); 4023 SDValue MaskNot = DAG.getNode(ISD::XOR, dl, OpVT, Mask, 4024 DAG.getNode(ISD::BITCAST, dl, OpVT, AllOnes)); 4025 4026 SDValue Res = DAG.getNode(ISD::OR, dl, OpVT, 4027 DAG.getNode(ISD::AND, dl, OpVT, Tmp1, Mask), 4028 DAG.getNode(ISD::AND, dl, OpVT, Tmp0, MaskNot)); 4029 if (VT == MVT::f32) { 4030 Res = DAG.getNode(ISD::BITCAST, dl, MVT::v2f32, Res); 4031 Res = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f32, Res, 4032 DAG.getConstant(0, dl, MVT::i32)); 4033 } else { 4034 Res = DAG.getNode(ISD::BITCAST, dl, MVT::f64, Res); 4035 } 4036 4037 return Res; 4038 } 4039 4040 // Bitcast operand 1 to i32. 4041 if (SrcVT == MVT::f64) 4042 Tmp1 = DAG.getNode(ARMISD::VMOVRRD, dl, DAG.getVTList(MVT::i32, MVT::i32), 4043 Tmp1).getValue(1); 4044 Tmp1 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Tmp1); 4045 4046 // Or in the signbit with integer operations. 4047 SDValue Mask1 = DAG.getConstant(0x80000000, dl, MVT::i32); 4048 SDValue Mask2 = DAG.getConstant(0x7fffffff, dl, MVT::i32); 4049 Tmp1 = DAG.getNode(ISD::AND, dl, MVT::i32, Tmp1, Mask1); 4050 if (VT == MVT::f32) { 4051 Tmp0 = DAG.getNode(ISD::AND, dl, MVT::i32, 4052 DAG.getNode(ISD::BITCAST, dl, MVT::i32, Tmp0), Mask2); 4053 return DAG.getNode(ISD::BITCAST, dl, MVT::f32, 4054 DAG.getNode(ISD::OR, dl, MVT::i32, Tmp0, Tmp1)); 4055 } 4056 4057 // f64: Or the high part with signbit and then combine two parts. 4058 Tmp0 = DAG.getNode(ARMISD::VMOVRRD, dl, DAG.getVTList(MVT::i32, MVT::i32), 4059 Tmp0); 4060 SDValue Lo = Tmp0.getValue(0); 4061 SDValue Hi = DAG.getNode(ISD::AND, dl, MVT::i32, Tmp0.getValue(1), Mask2); 4062 Hi = DAG.getNode(ISD::OR, dl, MVT::i32, Hi, Tmp1); 4063 return DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi); 4064 } 4065 4066 SDValue ARMTargetLowering::LowerRETURNADDR(SDValue Op, SelectionDAG &DAG) const{ 4067 MachineFunction &MF = DAG.getMachineFunction(); 4068 MachineFrameInfo *MFI = MF.getFrameInfo(); 4069 MFI->setReturnAddressIsTaken(true); 4070 4071 if (verifyReturnAddressArgumentIsConstant(Op, DAG)) 4072 return SDValue(); 4073 4074 EVT VT = Op.getValueType(); 4075 SDLoc dl(Op); 4076 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue(); 4077 if (Depth) { 4078 SDValue FrameAddr = LowerFRAMEADDR(Op, DAG); 4079 SDValue Offset = DAG.getConstant(4, dl, MVT::i32); 4080 return DAG.getLoad(VT, dl, DAG.getEntryNode(), 4081 DAG.getNode(ISD::ADD, dl, VT, FrameAddr, Offset), 4082 MachinePointerInfo(), false, false, false, 0); 4083 } 4084 4085 // Return LR, which contains the return address. Mark it an implicit live-in. 4086 unsigned Reg = MF.addLiveIn(ARM::LR, getRegClassFor(MVT::i32)); 4087 return DAG.getCopyFromReg(DAG.getEntryNode(), dl, Reg, VT); 4088 } 4089 4090 SDValue ARMTargetLowering::LowerFRAMEADDR(SDValue Op, SelectionDAG &DAG) const { 4091 const ARMBaseRegisterInfo &ARI = 4092 *static_cast<const ARMBaseRegisterInfo*>(RegInfo); 4093 MachineFunction &MF = DAG.getMachineFunction(); 4094 MachineFrameInfo *MFI = MF.getFrameInfo(); 4095 MFI->setFrameAddressIsTaken(true); 4096 4097 EVT VT = Op.getValueType(); 4098 SDLoc dl(Op); // FIXME probably not meaningful 4099 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue(); 4100 unsigned FrameReg = ARI.getFrameRegister(MF); 4101 SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, VT); 4102 while (Depth--) 4103 FrameAddr = DAG.getLoad(VT, dl, DAG.getEntryNode(), FrameAddr, 4104 MachinePointerInfo(), 4105 false, false, false, 0); 4106 return FrameAddr; 4107 } 4108 4109 // FIXME? Maybe this could be a TableGen attribute on some registers and 4110 // this table could be generated automatically from RegInfo. 4111 unsigned ARMTargetLowering::getRegisterByName(const char* RegName, EVT VT, 4112 SelectionDAG &DAG) const { 4113 unsigned Reg = StringSwitch<unsigned>(RegName) 4114 .Case("sp", ARM::SP) 4115 .Default(0); 4116 if (Reg) 4117 return Reg; 4118 report_fatal_error(Twine("Invalid register name \"" 4119 + StringRef(RegName) + "\".")); 4120 } 4121 4122 // Result is 64 bit value so split into two 32 bit values and return as a 4123 // pair of values. 4124 static void ExpandREAD_REGISTER(SDNode *N, SmallVectorImpl<SDValue> &Results, 4125 SelectionDAG &DAG) { 4126 SDLoc DL(N); 4127 4128 // This function is only supposed to be called for i64 type destination. 4129 assert(N->getValueType(0) == MVT::i64 4130 && "ExpandREAD_REGISTER called for non-i64 type result."); 4131 4132 SDValue Read = DAG.getNode(ISD::READ_REGISTER, DL, 4133 DAG.getVTList(MVT::i32, MVT::i32, MVT::Other), 4134 N->getOperand(0), 4135 N->getOperand(1)); 4136 4137 Results.push_back(DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, Read.getValue(0), 4138 Read.getValue(1))); 4139 Results.push_back(Read.getOperand(0)); 4140 } 4141 4142 /// \p BC is a bitcast that is about to be turned into a VMOVDRR. 4143 /// When \p DstVT, the destination type of \p BC, is on the vector 4144 /// register bank and the source of bitcast, \p Op, operates on the same bank, 4145 /// it might be possible to combine them, such that everything stays on the 4146 /// vector register bank. 4147 /// \p return The node that would replace \p BT, if the combine 4148 /// is possible. 4149 static SDValue CombineVMOVDRRCandidateWithVecOp(const SDNode *BC, 4150 SelectionDAG &DAG) { 4151 SDValue Op = BC->getOperand(0); 4152 EVT DstVT = BC->getValueType(0); 4153 4154 // The only vector instruction that can produce a scalar (remember, 4155 // since the bitcast was about to be turned into VMOVDRR, the source 4156 // type is i64) from a vector is EXTRACT_VECTOR_ELT. 4157 // Moreover, we can do this combine only if there is one use. 4158 // Finally, if the destination type is not a vector, there is not 4159 // much point on forcing everything on the vector bank. 4160 if (!DstVT.isVector() || Op.getOpcode() != ISD::EXTRACT_VECTOR_ELT || 4161 !Op.hasOneUse()) 4162 return SDValue(); 4163 4164 // If the index is not constant, we will introduce an additional 4165 // multiply that will stick. 4166 // Give up in that case. 4167 ConstantSDNode *Index = dyn_cast<ConstantSDNode>(Op.getOperand(1)); 4168 if (!Index) 4169 return SDValue(); 4170 unsigned DstNumElt = DstVT.getVectorNumElements(); 4171 4172 // Compute the new index. 4173 const APInt &APIntIndex = Index->getAPIntValue(); 4174 APInt NewIndex(APIntIndex.getBitWidth(), DstNumElt); 4175 NewIndex *= APIntIndex; 4176 // Check if the new constant index fits into i32. 4177 if (NewIndex.getBitWidth() > 32) 4178 return SDValue(); 4179 4180 // vMTy bitcast(i64 extractelt vNi64 src, i32 index) -> 4181 // vMTy extractsubvector vNxMTy (bitcast vNi64 src), i32 index*M) 4182 SDLoc dl(Op); 4183 SDValue ExtractSrc = Op.getOperand(0); 4184 EVT VecVT = EVT::getVectorVT( 4185 *DAG.getContext(), DstVT.getScalarType(), 4186 ExtractSrc.getValueType().getVectorNumElements() * DstNumElt); 4187 SDValue BitCast = DAG.getNode(ISD::BITCAST, dl, VecVT, ExtractSrc); 4188 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DstVT, BitCast, 4189 DAG.getConstant(NewIndex.getZExtValue(), dl, MVT::i32)); 4190 } 4191 4192 /// ExpandBITCAST - If the target supports VFP, this function is called to 4193 /// expand a bit convert where either the source or destination type is i64 to 4194 /// use a VMOVDRR or VMOVRRD node. This should not be done when the non-i64 4195 /// operand type is illegal (e.g., v2f32 for a target that doesn't support 4196 /// vectors), since the legalizer won't know what to do with that. 4197 static SDValue ExpandBITCAST(SDNode *N, SelectionDAG &DAG) { 4198 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 4199 SDLoc dl(N); 4200 SDValue Op = N->getOperand(0); 4201 4202 // This function is only supposed to be called for i64 types, either as the 4203 // source or destination of the bit convert. 4204 EVT SrcVT = Op.getValueType(); 4205 EVT DstVT = N->getValueType(0); 4206 assert((SrcVT == MVT::i64 || DstVT == MVT::i64) && 4207 "ExpandBITCAST called for non-i64 type"); 4208 4209 // Turn i64->f64 into VMOVDRR. 4210 if (SrcVT == MVT::i64 && TLI.isTypeLegal(DstVT)) { 4211 // Do not force values to GPRs (this is what VMOVDRR does for the inputs) 4212 // if we can combine the bitcast with its source. 4213 if (SDValue Val = CombineVMOVDRRCandidateWithVecOp(N, DAG)) 4214 return Val; 4215 4216 SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, Op, 4217 DAG.getConstant(0, dl, MVT::i32)); 4218 SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, Op, 4219 DAG.getConstant(1, dl, MVT::i32)); 4220 return DAG.getNode(ISD::BITCAST, dl, DstVT, 4221 DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi)); 4222 } 4223 4224 // Turn f64->i64 into VMOVRRD. 4225 if (DstVT == MVT::i64 && TLI.isTypeLegal(SrcVT)) { 4226 SDValue Cvt; 4227 if (DAG.getDataLayout().isBigEndian() && SrcVT.isVector() && 4228 SrcVT.getVectorNumElements() > 1) 4229 Cvt = DAG.getNode(ARMISD::VMOVRRD, dl, 4230 DAG.getVTList(MVT::i32, MVT::i32), 4231 DAG.getNode(ARMISD::VREV64, dl, SrcVT, Op)); 4232 else 4233 Cvt = DAG.getNode(ARMISD::VMOVRRD, dl, 4234 DAG.getVTList(MVT::i32, MVT::i32), Op); 4235 // Merge the pieces into a single i64 value. 4236 return DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Cvt, Cvt.getValue(1)); 4237 } 4238 4239 return SDValue(); 4240 } 4241 4242 /// getZeroVector - Returns a vector of specified type with all zero elements. 4243 /// Zero vectors are used to represent vector negation and in those cases 4244 /// will be implemented with the NEON VNEG instruction. However, VNEG does 4245 /// not support i64 elements, so sometimes the zero vectors will need to be 4246 /// explicitly constructed. Regardless, use a canonical VMOV to create the 4247 /// zero vector. 4248 static SDValue getZeroVector(EVT VT, SelectionDAG &DAG, SDLoc dl) { 4249 assert(VT.isVector() && "Expected a vector type"); 4250 // The canonical modified immediate encoding of a zero vector is....0! 4251 SDValue EncodedVal = DAG.getTargetConstant(0, dl, MVT::i32); 4252 EVT VmovVT = VT.is128BitVector() ? MVT::v4i32 : MVT::v2i32; 4253 SDValue Vmov = DAG.getNode(ARMISD::VMOVIMM, dl, VmovVT, EncodedVal); 4254 return DAG.getNode(ISD::BITCAST, dl, VT, Vmov); 4255 } 4256 4257 /// LowerShiftRightParts - Lower SRA_PARTS, which returns two 4258 /// i32 values and take a 2 x i32 value to shift plus a shift amount. 4259 SDValue ARMTargetLowering::LowerShiftRightParts(SDValue Op, 4260 SelectionDAG &DAG) const { 4261 assert(Op.getNumOperands() == 3 && "Not a double-shift!"); 4262 EVT VT = Op.getValueType(); 4263 unsigned VTBits = VT.getSizeInBits(); 4264 SDLoc dl(Op); 4265 SDValue ShOpLo = Op.getOperand(0); 4266 SDValue ShOpHi = Op.getOperand(1); 4267 SDValue ShAmt = Op.getOperand(2); 4268 SDValue ARMcc; 4269 unsigned Opc = (Op.getOpcode() == ISD::SRA_PARTS) ? ISD::SRA : ISD::SRL; 4270 4271 assert(Op.getOpcode() == ISD::SRA_PARTS || Op.getOpcode() == ISD::SRL_PARTS); 4272 4273 SDValue RevShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32, 4274 DAG.getConstant(VTBits, dl, MVT::i32), ShAmt); 4275 SDValue Tmp1 = DAG.getNode(ISD::SRL, dl, VT, ShOpLo, ShAmt); 4276 SDValue ExtraShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32, ShAmt, 4277 DAG.getConstant(VTBits, dl, MVT::i32)); 4278 SDValue Tmp2 = DAG.getNode(ISD::SHL, dl, VT, ShOpHi, RevShAmt); 4279 SDValue FalseVal = DAG.getNode(ISD::OR, dl, VT, Tmp1, Tmp2); 4280 SDValue TrueVal = DAG.getNode(Opc, dl, VT, ShOpHi, ExtraShAmt); 4281 4282 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32); 4283 SDValue Cmp = getARMCmp(ExtraShAmt, DAG.getConstant(0, dl, MVT::i32), 4284 ISD::SETGE, ARMcc, DAG, dl); 4285 SDValue Hi = DAG.getNode(Opc, dl, VT, ShOpHi, ShAmt); 4286 SDValue Lo = DAG.getNode(ARMISD::CMOV, dl, VT, FalseVal, TrueVal, ARMcc, 4287 CCR, Cmp); 4288 4289 SDValue Ops[2] = { Lo, Hi }; 4290 return DAG.getMergeValues(Ops, dl); 4291 } 4292 4293 /// LowerShiftLeftParts - Lower SHL_PARTS, which returns two 4294 /// i32 values and take a 2 x i32 value to shift plus a shift amount. 4295 SDValue ARMTargetLowering::LowerShiftLeftParts(SDValue Op, 4296 SelectionDAG &DAG) const { 4297 assert(Op.getNumOperands() == 3 && "Not a double-shift!"); 4298 EVT VT = Op.getValueType(); 4299 unsigned VTBits = VT.getSizeInBits(); 4300 SDLoc dl(Op); 4301 SDValue ShOpLo = Op.getOperand(0); 4302 SDValue ShOpHi = Op.getOperand(1); 4303 SDValue ShAmt = Op.getOperand(2); 4304 SDValue ARMcc; 4305 4306 assert(Op.getOpcode() == ISD::SHL_PARTS); 4307 SDValue RevShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32, 4308 DAG.getConstant(VTBits, dl, MVT::i32), ShAmt); 4309 SDValue Tmp1 = DAG.getNode(ISD::SRL, dl, VT, ShOpLo, RevShAmt); 4310 SDValue ExtraShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32, ShAmt, 4311 DAG.getConstant(VTBits, dl, MVT::i32)); 4312 SDValue Tmp2 = DAG.getNode(ISD::SHL, dl, VT, ShOpHi, ShAmt); 4313 SDValue Tmp3 = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ExtraShAmt); 4314 4315 SDValue FalseVal = DAG.getNode(ISD::OR, dl, VT, Tmp1, Tmp2); 4316 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32); 4317 SDValue Cmp = getARMCmp(ExtraShAmt, DAG.getConstant(0, dl, MVT::i32), 4318 ISD::SETGE, ARMcc, DAG, dl); 4319 SDValue Lo = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ShAmt); 4320 SDValue Hi = DAG.getNode(ARMISD::CMOV, dl, VT, FalseVal, Tmp3, ARMcc, 4321 CCR, Cmp); 4322 4323 SDValue Ops[2] = { Lo, Hi }; 4324 return DAG.getMergeValues(Ops, dl); 4325 } 4326 4327 SDValue ARMTargetLowering::LowerFLT_ROUNDS_(SDValue Op, 4328 SelectionDAG &DAG) const { 4329 // The rounding mode is in bits 23:22 of the FPSCR. 4330 // The ARM rounding mode value to FLT_ROUNDS mapping is 0->1, 1->2, 2->3, 3->0 4331 // The formula we use to implement this is (((FPSCR + 1 << 22) >> 22) & 3) 4332 // so that the shift + and get folded into a bitfield extract. 4333 SDLoc dl(Op); 4334 SDValue FPSCR = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::i32, 4335 DAG.getConstant(Intrinsic::arm_get_fpscr, dl, 4336 MVT::i32)); 4337 SDValue FltRounds = DAG.getNode(ISD::ADD, dl, MVT::i32, FPSCR, 4338 DAG.getConstant(1U << 22, dl, MVT::i32)); 4339 SDValue RMODE = DAG.getNode(ISD::SRL, dl, MVT::i32, FltRounds, 4340 DAG.getConstant(22, dl, MVT::i32)); 4341 return DAG.getNode(ISD::AND, dl, MVT::i32, RMODE, 4342 DAG.getConstant(3, dl, MVT::i32)); 4343 } 4344 4345 static SDValue LowerCTTZ(SDNode *N, SelectionDAG &DAG, 4346 const ARMSubtarget *ST) { 4347 SDLoc dl(N); 4348 EVT VT = N->getValueType(0); 4349 if (VT.isVector()) { 4350 assert(ST->hasNEON()); 4351 4352 // Compute the least significant set bit: LSB = X & -X 4353 SDValue X = N->getOperand(0); 4354 SDValue NX = DAG.getNode(ISD::SUB, dl, VT, getZeroVector(VT, DAG, dl), X); 4355 SDValue LSB = DAG.getNode(ISD::AND, dl, VT, X, NX); 4356 4357 EVT ElemTy = VT.getVectorElementType(); 4358 4359 if (ElemTy == MVT::i8) { 4360 // Compute with: cttz(x) = ctpop(lsb - 1) 4361 SDValue One = DAG.getNode(ARMISD::VMOVIMM, dl, VT, 4362 DAG.getTargetConstant(1, dl, ElemTy)); 4363 SDValue Bits = DAG.getNode(ISD::SUB, dl, VT, LSB, One); 4364 return DAG.getNode(ISD::CTPOP, dl, VT, Bits); 4365 } 4366 4367 if ((ElemTy == MVT::i16 || ElemTy == MVT::i32) && 4368 (N->getOpcode() == ISD::CTTZ_ZERO_UNDEF)) { 4369 // Compute with: cttz(x) = (width - 1) - ctlz(lsb), if x != 0 4370 unsigned NumBits = ElemTy.getSizeInBits(); 4371 SDValue WidthMinus1 = 4372 DAG.getNode(ARMISD::VMOVIMM, dl, VT, 4373 DAG.getTargetConstant(NumBits - 1, dl, ElemTy)); 4374 SDValue CTLZ = DAG.getNode(ISD::CTLZ, dl, VT, LSB); 4375 return DAG.getNode(ISD::SUB, dl, VT, WidthMinus1, CTLZ); 4376 } 4377 4378 // Compute with: cttz(x) = ctpop(lsb - 1) 4379 4380 // Since we can only compute the number of bits in a byte with vcnt.8, we 4381 // have to gather the result with pairwise addition (vpaddl) for i16, i32, 4382 // and i64. 4383 4384 // Compute LSB - 1. 4385 SDValue Bits; 4386 if (ElemTy == MVT::i64) { 4387 // Load constant 0xffff'ffff'ffff'ffff to register. 4388 SDValue FF = DAG.getNode(ARMISD::VMOVIMM, dl, VT, 4389 DAG.getTargetConstant(0x1eff, dl, MVT::i32)); 4390 Bits = DAG.getNode(ISD::ADD, dl, VT, LSB, FF); 4391 } else { 4392 SDValue One = DAG.getNode(ARMISD::VMOVIMM, dl, VT, 4393 DAG.getTargetConstant(1, dl, ElemTy)); 4394 Bits = DAG.getNode(ISD::SUB, dl, VT, LSB, One); 4395 } 4396 4397 // Count #bits with vcnt.8. 4398 EVT VT8Bit = VT.is64BitVector() ? MVT::v8i8 : MVT::v16i8; 4399 SDValue BitsVT8 = DAG.getNode(ISD::BITCAST, dl, VT8Bit, Bits); 4400 SDValue Cnt8 = DAG.getNode(ISD::CTPOP, dl, VT8Bit, BitsVT8); 4401 4402 // Gather the #bits with vpaddl (pairwise add.) 4403 EVT VT16Bit = VT.is64BitVector() ? MVT::v4i16 : MVT::v8i16; 4404 SDValue Cnt16 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT16Bit, 4405 DAG.getTargetConstant(Intrinsic::arm_neon_vpaddlu, dl, MVT::i32), 4406 Cnt8); 4407 if (ElemTy == MVT::i16) 4408 return Cnt16; 4409 4410 EVT VT32Bit = VT.is64BitVector() ? MVT::v2i32 : MVT::v4i32; 4411 SDValue Cnt32 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT32Bit, 4412 DAG.getTargetConstant(Intrinsic::arm_neon_vpaddlu, dl, MVT::i32), 4413 Cnt16); 4414 if (ElemTy == MVT::i32) 4415 return Cnt32; 4416 4417 assert(ElemTy == MVT::i64); 4418 SDValue Cnt64 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT, 4419 DAG.getTargetConstant(Intrinsic::arm_neon_vpaddlu, dl, MVT::i32), 4420 Cnt32); 4421 return Cnt64; 4422 } 4423 4424 if (!ST->hasV6T2Ops()) 4425 return SDValue(); 4426 4427 SDValue rbit = DAG.getNode(ISD::BITREVERSE, dl, VT, N->getOperand(0)); 4428 return DAG.getNode(ISD::CTLZ, dl, VT, rbit); 4429 } 4430 4431 /// getCTPOP16BitCounts - Returns a v8i8/v16i8 vector containing the bit-count 4432 /// for each 16-bit element from operand, repeated. The basic idea is to 4433 /// leverage vcnt to get the 8-bit counts, gather and add the results. 4434 /// 4435 /// Trace for v4i16: 4436 /// input = [v0 v1 v2 v3 ] (vi 16-bit element) 4437 /// cast: N0 = [w0 w1 w2 w3 w4 w5 w6 w7] (v0 = [w0 w1], wi 8-bit element) 4438 /// vcnt: N1 = [b0 b1 b2 b3 b4 b5 b6 b7] (bi = bit-count of 8-bit element wi) 4439 /// vrev: N2 = [b1 b0 b3 b2 b5 b4 b7 b6] 4440 /// [b0 b1 b2 b3 b4 b5 b6 b7] 4441 /// +[b1 b0 b3 b2 b5 b4 b7 b6] 4442 /// N3=N1+N2 = [k0 k0 k1 k1 k2 k2 k3 k3] (k0 = b0+b1 = bit-count of 16-bit v0, 4443 /// vuzp: = [k0 k1 k2 k3 k0 k1 k2 k3] each ki is 8-bits) 4444 static SDValue getCTPOP16BitCounts(SDNode *N, SelectionDAG &DAG) { 4445 EVT VT = N->getValueType(0); 4446 SDLoc DL(N); 4447 4448 EVT VT8Bit = VT.is64BitVector() ? MVT::v8i8 : MVT::v16i8; 4449 SDValue N0 = DAG.getNode(ISD::BITCAST, DL, VT8Bit, N->getOperand(0)); 4450 SDValue N1 = DAG.getNode(ISD::CTPOP, DL, VT8Bit, N0); 4451 SDValue N2 = DAG.getNode(ARMISD::VREV16, DL, VT8Bit, N1); 4452 SDValue N3 = DAG.getNode(ISD::ADD, DL, VT8Bit, N1, N2); 4453 return DAG.getNode(ARMISD::VUZP, DL, VT8Bit, N3, N3); 4454 } 4455 4456 /// lowerCTPOP16BitElements - Returns a v4i16/v8i16 vector containing the 4457 /// bit-count for each 16-bit element from the operand. We need slightly 4458 /// different sequencing for v4i16 and v8i16 to stay within NEON's available 4459 /// 64/128-bit registers. 4460 /// 4461 /// Trace for v4i16: 4462 /// input = [v0 v1 v2 v3 ] (vi 16-bit element) 4463 /// v8i8: BitCounts = [k0 k1 k2 k3 k0 k1 k2 k3 ] (ki is the bit-count of vi) 4464 /// v8i16:Extended = [k0 k1 k2 k3 k0 k1 k2 k3 ] 4465 /// v4i16:Extracted = [k0 k1 k2 k3 ] 4466 static SDValue lowerCTPOP16BitElements(SDNode *N, SelectionDAG &DAG) { 4467 EVT VT = N->getValueType(0); 4468 SDLoc DL(N); 4469 4470 SDValue BitCounts = getCTPOP16BitCounts(N, DAG); 4471 if (VT.is64BitVector()) { 4472 SDValue Extended = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::v8i16, BitCounts); 4473 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v4i16, Extended, 4474 DAG.getIntPtrConstant(0, DL)); 4475 } else { 4476 SDValue Extracted = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v8i8, 4477 BitCounts, DAG.getIntPtrConstant(0, DL)); 4478 return DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::v8i16, Extracted); 4479 } 4480 } 4481 4482 /// lowerCTPOP32BitElements - Returns a v2i32/v4i32 vector containing the 4483 /// bit-count for each 32-bit element from the operand. The idea here is 4484 /// to split the vector into 16-bit elements, leverage the 16-bit count 4485 /// routine, and then combine the results. 4486 /// 4487 /// Trace for v2i32 (v4i32 similar with Extracted/Extended exchanged): 4488 /// input = [v0 v1 ] (vi: 32-bit elements) 4489 /// Bitcast = [w0 w1 w2 w3 ] (wi: 16-bit elements, v0 = [w0 w1]) 4490 /// Counts16 = [k0 k1 k2 k3 ] (ki: 16-bit elements, bit-count of wi) 4491 /// vrev: N0 = [k1 k0 k3 k2 ] 4492 /// [k0 k1 k2 k3 ] 4493 /// N1 =+[k1 k0 k3 k2 ] 4494 /// [k0 k2 k1 k3 ] 4495 /// N2 =+[k1 k3 k0 k2 ] 4496 /// [k0 k2 k1 k3 ] 4497 /// Extended =+[k1 k3 k0 k2 ] 4498 /// [k0 k2 ] 4499 /// Extracted=+[k1 k3 ] 4500 /// 4501 static SDValue lowerCTPOP32BitElements(SDNode *N, SelectionDAG &DAG) { 4502 EVT VT = N->getValueType(0); 4503 SDLoc DL(N); 4504 4505 EVT VT16Bit = VT.is64BitVector() ? MVT::v4i16 : MVT::v8i16; 4506 4507 SDValue Bitcast = DAG.getNode(ISD::BITCAST, DL, VT16Bit, N->getOperand(0)); 4508 SDValue Counts16 = lowerCTPOP16BitElements(Bitcast.getNode(), DAG); 4509 SDValue N0 = DAG.getNode(ARMISD::VREV32, DL, VT16Bit, Counts16); 4510 SDValue N1 = DAG.getNode(ISD::ADD, DL, VT16Bit, Counts16, N0); 4511 SDValue N2 = DAG.getNode(ARMISD::VUZP, DL, VT16Bit, N1, N1); 4512 4513 if (VT.is64BitVector()) { 4514 SDValue Extended = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::v4i32, N2); 4515 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2i32, Extended, 4516 DAG.getIntPtrConstant(0, DL)); 4517 } else { 4518 SDValue Extracted = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v4i16, N2, 4519 DAG.getIntPtrConstant(0, DL)); 4520 return DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::v4i32, Extracted); 4521 } 4522 } 4523 4524 static SDValue LowerCTPOP(SDNode *N, SelectionDAG &DAG, 4525 const ARMSubtarget *ST) { 4526 EVT VT = N->getValueType(0); 4527 4528 assert(ST->hasNEON() && "Custom ctpop lowering requires NEON."); 4529 assert((VT == MVT::v2i32 || VT == MVT::v4i32 || 4530 VT == MVT::v4i16 || VT == MVT::v8i16) && 4531 "Unexpected type for custom ctpop lowering"); 4532 4533 if (VT.getVectorElementType() == MVT::i32) 4534 return lowerCTPOP32BitElements(N, DAG); 4535 else 4536 return lowerCTPOP16BitElements(N, DAG); 4537 } 4538 4539 static SDValue LowerShift(SDNode *N, SelectionDAG &DAG, 4540 const ARMSubtarget *ST) { 4541 EVT VT = N->getValueType(0); 4542 SDLoc dl(N); 4543 4544 if (!VT.isVector()) 4545 return SDValue(); 4546 4547 // Lower vector shifts on NEON to use VSHL. 4548 assert(ST->hasNEON() && "unexpected vector shift"); 4549 4550 // Left shifts translate directly to the vshiftu intrinsic. 4551 if (N->getOpcode() == ISD::SHL) 4552 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT, 4553 DAG.getConstant(Intrinsic::arm_neon_vshiftu, dl, 4554 MVT::i32), 4555 N->getOperand(0), N->getOperand(1)); 4556 4557 assert((N->getOpcode() == ISD::SRA || 4558 N->getOpcode() == ISD::SRL) && "unexpected vector shift opcode"); 4559 4560 // NEON uses the same intrinsics for both left and right shifts. For 4561 // right shifts, the shift amounts are negative, so negate the vector of 4562 // shift amounts. 4563 EVT ShiftVT = N->getOperand(1).getValueType(); 4564 SDValue NegatedCount = DAG.getNode(ISD::SUB, dl, ShiftVT, 4565 getZeroVector(ShiftVT, DAG, dl), 4566 N->getOperand(1)); 4567 Intrinsic::ID vshiftInt = (N->getOpcode() == ISD::SRA ? 4568 Intrinsic::arm_neon_vshifts : 4569 Intrinsic::arm_neon_vshiftu); 4570 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT, 4571 DAG.getConstant(vshiftInt, dl, MVT::i32), 4572 N->getOperand(0), NegatedCount); 4573 } 4574 4575 static SDValue Expand64BitShift(SDNode *N, SelectionDAG &DAG, 4576 const ARMSubtarget *ST) { 4577 EVT VT = N->getValueType(0); 4578 SDLoc dl(N); 4579 4580 // We can get here for a node like i32 = ISD::SHL i32, i64 4581 if (VT != MVT::i64) 4582 return SDValue(); 4583 4584 assert((N->getOpcode() == ISD::SRL || N->getOpcode() == ISD::SRA) && 4585 "Unknown shift to lower!"); 4586 4587 // We only lower SRA, SRL of 1 here, all others use generic lowering. 4588 if (!isOneConstant(N->getOperand(1))) 4589 return SDValue(); 4590 4591 // If we are in thumb mode, we don't have RRX. 4592 if (ST->isThumb1Only()) return SDValue(); 4593 4594 // Okay, we have a 64-bit SRA or SRL of 1. Lower this to an RRX expr. 4595 SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(0), 4596 DAG.getConstant(0, dl, MVT::i32)); 4597 SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(0), 4598 DAG.getConstant(1, dl, MVT::i32)); 4599 4600 // First, build a SRA_FLAG/SRL_FLAG op, which shifts the top part by one and 4601 // captures the result into a carry flag. 4602 unsigned Opc = N->getOpcode() == ISD::SRL ? ARMISD::SRL_FLAG:ARMISD::SRA_FLAG; 4603 Hi = DAG.getNode(Opc, dl, DAG.getVTList(MVT::i32, MVT::Glue), Hi); 4604 4605 // The low part is an ARMISD::RRX operand, which shifts the carry in. 4606 Lo = DAG.getNode(ARMISD::RRX, dl, MVT::i32, Lo, Hi.getValue(1)); 4607 4608 // Merge the pieces into a single i64 value. 4609 return DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Lo, Hi); 4610 } 4611 4612 static SDValue LowerVSETCC(SDValue Op, SelectionDAG &DAG) { 4613 SDValue TmpOp0, TmpOp1; 4614 bool Invert = false; 4615 bool Swap = false; 4616 unsigned Opc = 0; 4617 4618 SDValue Op0 = Op.getOperand(0); 4619 SDValue Op1 = Op.getOperand(1); 4620 SDValue CC = Op.getOperand(2); 4621 EVT CmpVT = Op0.getValueType().changeVectorElementTypeToInteger(); 4622 EVT VT = Op.getValueType(); 4623 ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get(); 4624 SDLoc dl(Op); 4625 4626 if (CmpVT.getVectorElementType() == MVT::i64) 4627 // 64-bit comparisons are not legal. We've marked SETCC as non-Custom, 4628 // but it's possible that our operands are 64-bit but our result is 32-bit. 4629 // Bail in this case. 4630 return SDValue(); 4631 4632 if (Op1.getValueType().isFloatingPoint()) { 4633 switch (SetCCOpcode) { 4634 default: llvm_unreachable("Illegal FP comparison"); 4635 case ISD::SETUNE: 4636 case ISD::SETNE: Invert = true; // Fallthrough 4637 case ISD::SETOEQ: 4638 case ISD::SETEQ: Opc = ARMISD::VCEQ; break; 4639 case ISD::SETOLT: 4640 case ISD::SETLT: Swap = true; // Fallthrough 4641 case ISD::SETOGT: 4642 case ISD::SETGT: Opc = ARMISD::VCGT; break; 4643 case ISD::SETOLE: 4644 case ISD::SETLE: Swap = true; // Fallthrough 4645 case ISD::SETOGE: 4646 case ISD::SETGE: Opc = ARMISD::VCGE; break; 4647 case ISD::SETUGE: Swap = true; // Fallthrough 4648 case ISD::SETULE: Invert = true; Opc = ARMISD::VCGT; break; 4649 case ISD::SETUGT: Swap = true; // Fallthrough 4650 case ISD::SETULT: Invert = true; Opc = ARMISD::VCGE; break; 4651 case ISD::SETUEQ: Invert = true; // Fallthrough 4652 case ISD::SETONE: 4653 // Expand this to (OLT | OGT). 4654 TmpOp0 = Op0; 4655 TmpOp1 = Op1; 4656 Opc = ISD::OR; 4657 Op0 = DAG.getNode(ARMISD::VCGT, dl, CmpVT, TmpOp1, TmpOp0); 4658 Op1 = DAG.getNode(ARMISD::VCGT, dl, CmpVT, TmpOp0, TmpOp1); 4659 break; 4660 case ISD::SETUO: Invert = true; // Fallthrough 4661 case ISD::SETO: 4662 // Expand this to (OLT | OGE). 4663 TmpOp0 = Op0; 4664 TmpOp1 = Op1; 4665 Opc = ISD::OR; 4666 Op0 = DAG.getNode(ARMISD::VCGT, dl, CmpVT, TmpOp1, TmpOp0); 4667 Op1 = DAG.getNode(ARMISD::VCGE, dl, CmpVT, TmpOp0, TmpOp1); 4668 break; 4669 } 4670 } else { 4671 // Integer comparisons. 4672 switch (SetCCOpcode) { 4673 default: llvm_unreachable("Illegal integer comparison"); 4674 case ISD::SETNE: Invert = true; 4675 case ISD::SETEQ: Opc = ARMISD::VCEQ; break; 4676 case ISD::SETLT: Swap = true; 4677 case ISD::SETGT: Opc = ARMISD::VCGT; break; 4678 case ISD::SETLE: Swap = true; 4679 case ISD::SETGE: Opc = ARMISD::VCGE; break; 4680 case ISD::SETULT: Swap = true; 4681 case ISD::SETUGT: Opc = ARMISD::VCGTU; break; 4682 case ISD::SETULE: Swap = true; 4683 case ISD::SETUGE: Opc = ARMISD::VCGEU; break; 4684 } 4685 4686 // Detect VTST (Vector Test Bits) = icmp ne (and (op0, op1), zero). 4687 if (Opc == ARMISD::VCEQ) { 4688 4689 SDValue AndOp; 4690 if (ISD::isBuildVectorAllZeros(Op1.getNode())) 4691 AndOp = Op0; 4692 else if (ISD::isBuildVectorAllZeros(Op0.getNode())) 4693 AndOp = Op1; 4694 4695 // Ignore bitconvert. 4696 if (AndOp.getNode() && AndOp.getOpcode() == ISD::BITCAST) 4697 AndOp = AndOp.getOperand(0); 4698 4699 if (AndOp.getNode() && AndOp.getOpcode() == ISD::AND) { 4700 Opc = ARMISD::VTST; 4701 Op0 = DAG.getNode(ISD::BITCAST, dl, CmpVT, AndOp.getOperand(0)); 4702 Op1 = DAG.getNode(ISD::BITCAST, dl, CmpVT, AndOp.getOperand(1)); 4703 Invert = !Invert; 4704 } 4705 } 4706 } 4707 4708 if (Swap) 4709 std::swap(Op0, Op1); 4710 4711 // If one of the operands is a constant vector zero, attempt to fold the 4712 // comparison to a specialized compare-against-zero form. 4713 SDValue SingleOp; 4714 if (ISD::isBuildVectorAllZeros(Op1.getNode())) 4715 SingleOp = Op0; 4716 else if (ISD::isBuildVectorAllZeros(Op0.getNode())) { 4717 if (Opc == ARMISD::VCGE) 4718 Opc = ARMISD::VCLEZ; 4719 else if (Opc == ARMISD::VCGT) 4720 Opc = ARMISD::VCLTZ; 4721 SingleOp = Op1; 4722 } 4723 4724 SDValue Result; 4725 if (SingleOp.getNode()) { 4726 switch (Opc) { 4727 case ARMISD::VCEQ: 4728 Result = DAG.getNode(ARMISD::VCEQZ, dl, CmpVT, SingleOp); break; 4729 case ARMISD::VCGE: 4730 Result = DAG.getNode(ARMISD::VCGEZ, dl, CmpVT, SingleOp); break; 4731 case ARMISD::VCLEZ: 4732 Result = DAG.getNode(ARMISD::VCLEZ, dl, CmpVT, SingleOp); break; 4733 case ARMISD::VCGT: 4734 Result = DAG.getNode(ARMISD::VCGTZ, dl, CmpVT, SingleOp); break; 4735 case ARMISD::VCLTZ: 4736 Result = DAG.getNode(ARMISD::VCLTZ, dl, CmpVT, SingleOp); break; 4737 default: 4738 Result = DAG.getNode(Opc, dl, CmpVT, Op0, Op1); 4739 } 4740 } else { 4741 Result = DAG.getNode(Opc, dl, CmpVT, Op0, Op1); 4742 } 4743 4744 Result = DAG.getSExtOrTrunc(Result, dl, VT); 4745 4746 if (Invert) 4747 Result = DAG.getNOT(dl, Result, VT); 4748 4749 return Result; 4750 } 4751 4752 /// isNEONModifiedImm - Check if the specified splat value corresponds to a 4753 /// valid vector constant for a NEON instruction with a "modified immediate" 4754 /// operand (e.g., VMOV). If so, return the encoded value. 4755 static SDValue isNEONModifiedImm(uint64_t SplatBits, uint64_t SplatUndef, 4756 unsigned SplatBitSize, SelectionDAG &DAG, 4757 SDLoc dl, EVT &VT, bool is128Bits, 4758 NEONModImmType type) { 4759 unsigned OpCmode, Imm; 4760 4761 // SplatBitSize is set to the smallest size that splats the vector, so a 4762 // zero vector will always have SplatBitSize == 8. However, NEON modified 4763 // immediate instructions others than VMOV do not support the 8-bit encoding 4764 // of a zero vector, and the default encoding of zero is supposed to be the 4765 // 32-bit version. 4766 if (SplatBits == 0) 4767 SplatBitSize = 32; 4768 4769 switch (SplatBitSize) { 4770 case 8: 4771 if (type != VMOVModImm) 4772 return SDValue(); 4773 // Any 1-byte value is OK. Op=0, Cmode=1110. 4774 assert((SplatBits & ~0xff) == 0 && "one byte splat value is too big"); 4775 OpCmode = 0xe; 4776 Imm = SplatBits; 4777 VT = is128Bits ? MVT::v16i8 : MVT::v8i8; 4778 break; 4779 4780 case 16: 4781 // NEON's 16-bit VMOV supports splat values where only one byte is nonzero. 4782 VT = is128Bits ? MVT::v8i16 : MVT::v4i16; 4783 if ((SplatBits & ~0xff) == 0) { 4784 // Value = 0x00nn: Op=x, Cmode=100x. 4785 OpCmode = 0x8; 4786 Imm = SplatBits; 4787 break; 4788 } 4789 if ((SplatBits & ~0xff00) == 0) { 4790 // Value = 0xnn00: Op=x, Cmode=101x. 4791 OpCmode = 0xa; 4792 Imm = SplatBits >> 8; 4793 break; 4794 } 4795 return SDValue(); 4796 4797 case 32: 4798 // NEON's 32-bit VMOV supports splat values where: 4799 // * only one byte is nonzero, or 4800 // * the least significant byte is 0xff and the second byte is nonzero, or 4801 // * the least significant 2 bytes are 0xff and the third is nonzero. 4802 VT = is128Bits ? MVT::v4i32 : MVT::v2i32; 4803 if ((SplatBits & ~0xff) == 0) { 4804 // Value = 0x000000nn: Op=x, Cmode=000x. 4805 OpCmode = 0; 4806 Imm = SplatBits; 4807 break; 4808 } 4809 if ((SplatBits & ~0xff00) == 0) { 4810 // Value = 0x0000nn00: Op=x, Cmode=001x. 4811 OpCmode = 0x2; 4812 Imm = SplatBits >> 8; 4813 break; 4814 } 4815 if ((SplatBits & ~0xff0000) == 0) { 4816 // Value = 0x00nn0000: Op=x, Cmode=010x. 4817 OpCmode = 0x4; 4818 Imm = SplatBits >> 16; 4819 break; 4820 } 4821 if ((SplatBits & ~0xff000000) == 0) { 4822 // Value = 0xnn000000: Op=x, Cmode=011x. 4823 OpCmode = 0x6; 4824 Imm = SplatBits >> 24; 4825 break; 4826 } 4827 4828 // cmode == 0b1100 and cmode == 0b1101 are not supported for VORR or VBIC 4829 if (type == OtherModImm) return SDValue(); 4830 4831 if ((SplatBits & ~0xffff) == 0 && 4832 ((SplatBits | SplatUndef) & 0xff) == 0xff) { 4833 // Value = 0x0000nnff: Op=x, Cmode=1100. 4834 OpCmode = 0xc; 4835 Imm = SplatBits >> 8; 4836 break; 4837 } 4838 4839 if ((SplatBits & ~0xffffff) == 0 && 4840 ((SplatBits | SplatUndef) & 0xffff) == 0xffff) { 4841 // Value = 0x00nnffff: Op=x, Cmode=1101. 4842 OpCmode = 0xd; 4843 Imm = SplatBits >> 16; 4844 break; 4845 } 4846 4847 // Note: there are a few 32-bit splat values (specifically: 00ffff00, 4848 // ff000000, ff0000ff, and ffff00ff) that are valid for VMOV.I64 but not 4849 // VMOV.I32. A (very) minor optimization would be to replicate the value 4850 // and fall through here to test for a valid 64-bit splat. But, then the 4851 // caller would also need to check and handle the change in size. 4852 return SDValue(); 4853 4854 case 64: { 4855 if (type != VMOVModImm) 4856 return SDValue(); 4857 // NEON has a 64-bit VMOV splat where each byte is either 0 or 0xff. 4858 uint64_t BitMask = 0xff; 4859 uint64_t Val = 0; 4860 unsigned ImmMask = 1; 4861 Imm = 0; 4862 for (int ByteNum = 0; ByteNum < 8; ++ByteNum) { 4863 if (((SplatBits | SplatUndef) & BitMask) == BitMask) { 4864 Val |= BitMask; 4865 Imm |= ImmMask; 4866 } else if ((SplatBits & BitMask) != 0) { 4867 return SDValue(); 4868 } 4869 BitMask <<= 8; 4870 ImmMask <<= 1; 4871 } 4872 4873 if (DAG.getDataLayout().isBigEndian()) 4874 // swap higher and lower 32 bit word 4875 Imm = ((Imm & 0xf) << 4) | ((Imm & 0xf0) >> 4); 4876 4877 // Op=1, Cmode=1110. 4878 OpCmode = 0x1e; 4879 VT = is128Bits ? MVT::v2i64 : MVT::v1i64; 4880 break; 4881 } 4882 4883 default: 4884 llvm_unreachable("unexpected size for isNEONModifiedImm"); 4885 } 4886 4887 unsigned EncodedVal = ARM_AM::createNEONModImm(OpCmode, Imm); 4888 return DAG.getTargetConstant(EncodedVal, dl, MVT::i32); 4889 } 4890 4891 SDValue ARMTargetLowering::LowerConstantFP(SDValue Op, SelectionDAG &DAG, 4892 const ARMSubtarget *ST) const { 4893 if (!ST->hasVFP3()) 4894 return SDValue(); 4895 4896 bool IsDouble = Op.getValueType() == MVT::f64; 4897 ConstantFPSDNode *CFP = cast<ConstantFPSDNode>(Op); 4898 4899 // Use the default (constant pool) lowering for double constants when we have 4900 // an SP-only FPU 4901 if (IsDouble && Subtarget->isFPOnlySP()) 4902 return SDValue(); 4903 4904 // Try splatting with a VMOV.f32... 4905 APFloat FPVal = CFP->getValueAPF(); 4906 int ImmVal = IsDouble ? ARM_AM::getFP64Imm(FPVal) : ARM_AM::getFP32Imm(FPVal); 4907 4908 if (ImmVal != -1) { 4909 if (IsDouble || !ST->useNEONForSinglePrecisionFP()) { 4910 // We have code in place to select a valid ConstantFP already, no need to 4911 // do any mangling. 4912 return Op; 4913 } 4914 4915 // It's a float and we are trying to use NEON operations where 4916 // possible. Lower it to a splat followed by an extract. 4917 SDLoc DL(Op); 4918 SDValue NewVal = DAG.getTargetConstant(ImmVal, DL, MVT::i32); 4919 SDValue VecConstant = DAG.getNode(ARMISD::VMOVFPIMM, DL, MVT::v2f32, 4920 NewVal); 4921 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32, VecConstant, 4922 DAG.getConstant(0, DL, MVT::i32)); 4923 } 4924 4925 // The rest of our options are NEON only, make sure that's allowed before 4926 // proceeding.. 4927 if (!ST->hasNEON() || (!IsDouble && !ST->useNEONForSinglePrecisionFP())) 4928 return SDValue(); 4929 4930 EVT VMovVT; 4931 uint64_t iVal = FPVal.bitcastToAPInt().getZExtValue(); 4932 4933 // It wouldn't really be worth bothering for doubles except for one very 4934 // important value, which does happen to match: 0.0. So make sure we don't do 4935 // anything stupid. 4936 if (IsDouble && (iVal & 0xffffffff) != (iVal >> 32)) 4937 return SDValue(); 4938 4939 // Try a VMOV.i32 (FIXME: i8, i16, or i64 could work too). 4940 SDValue NewVal = isNEONModifiedImm(iVal & 0xffffffffU, 0, 32, DAG, SDLoc(Op), 4941 VMovVT, false, VMOVModImm); 4942 if (NewVal != SDValue()) { 4943 SDLoc DL(Op); 4944 SDValue VecConstant = DAG.getNode(ARMISD::VMOVIMM, DL, VMovVT, 4945 NewVal); 4946 if (IsDouble) 4947 return DAG.getNode(ISD::BITCAST, DL, MVT::f64, VecConstant); 4948 4949 // It's a float: cast and extract a vector element. 4950 SDValue VecFConstant = DAG.getNode(ISD::BITCAST, DL, MVT::v2f32, 4951 VecConstant); 4952 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32, VecFConstant, 4953 DAG.getConstant(0, DL, MVT::i32)); 4954 } 4955 4956 // Finally, try a VMVN.i32 4957 NewVal = isNEONModifiedImm(~iVal & 0xffffffffU, 0, 32, DAG, SDLoc(Op), VMovVT, 4958 false, VMVNModImm); 4959 if (NewVal != SDValue()) { 4960 SDLoc DL(Op); 4961 SDValue VecConstant = DAG.getNode(ARMISD::VMVNIMM, DL, VMovVT, NewVal); 4962 4963 if (IsDouble) 4964 return DAG.getNode(ISD::BITCAST, DL, MVT::f64, VecConstant); 4965 4966 // It's a float: cast and extract a vector element. 4967 SDValue VecFConstant = DAG.getNode(ISD::BITCAST, DL, MVT::v2f32, 4968 VecConstant); 4969 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32, VecFConstant, 4970 DAG.getConstant(0, DL, MVT::i32)); 4971 } 4972 4973 return SDValue(); 4974 } 4975 4976 // check if an VEXT instruction can handle the shuffle mask when the 4977 // vector sources of the shuffle are the same. 4978 static bool isSingletonVEXTMask(ArrayRef<int> M, EVT VT, unsigned &Imm) { 4979 unsigned NumElts = VT.getVectorNumElements(); 4980 4981 // Assume that the first shuffle index is not UNDEF. Fail if it is. 4982 if (M[0] < 0) 4983 return false; 4984 4985 Imm = M[0]; 4986 4987 // If this is a VEXT shuffle, the immediate value is the index of the first 4988 // element. The other shuffle indices must be the successive elements after 4989 // the first one. 4990 unsigned ExpectedElt = Imm; 4991 for (unsigned i = 1; i < NumElts; ++i) { 4992 // Increment the expected index. If it wraps around, just follow it 4993 // back to index zero and keep going. 4994 ++ExpectedElt; 4995 if (ExpectedElt == NumElts) 4996 ExpectedElt = 0; 4997 4998 if (M[i] < 0) continue; // ignore UNDEF indices 4999 if (ExpectedElt != static_cast<unsigned>(M[i])) 5000 return false; 5001 } 5002 5003 return true; 5004 } 5005 5006 5007 static bool isVEXTMask(ArrayRef<int> M, EVT VT, 5008 bool &ReverseVEXT, unsigned &Imm) { 5009 unsigned NumElts = VT.getVectorNumElements(); 5010 ReverseVEXT = false; 5011 5012 // Assume that the first shuffle index is not UNDEF. Fail if it is. 5013 if (M[0] < 0) 5014 return false; 5015 5016 Imm = M[0]; 5017 5018 // If this is a VEXT shuffle, the immediate value is the index of the first 5019 // element. The other shuffle indices must be the successive elements after 5020 // the first one. 5021 unsigned ExpectedElt = Imm; 5022 for (unsigned i = 1; i < NumElts; ++i) { 5023 // Increment the expected index. If it wraps around, it may still be 5024 // a VEXT but the source vectors must be swapped. 5025 ExpectedElt += 1; 5026 if (ExpectedElt == NumElts * 2) { 5027 ExpectedElt = 0; 5028 ReverseVEXT = true; 5029 } 5030 5031 if (M[i] < 0) continue; // ignore UNDEF indices 5032 if (ExpectedElt != static_cast<unsigned>(M[i])) 5033 return false; 5034 } 5035 5036 // Adjust the index value if the source operands will be swapped. 5037 if (ReverseVEXT) 5038 Imm -= NumElts; 5039 5040 return true; 5041 } 5042 5043 /// isVREVMask - Check if a vector shuffle corresponds to a VREV 5044 /// instruction with the specified blocksize. (The order of the elements 5045 /// within each block of the vector is reversed.) 5046 static bool isVREVMask(ArrayRef<int> M, EVT VT, unsigned BlockSize) { 5047 assert((BlockSize==16 || BlockSize==32 || BlockSize==64) && 5048 "Only possible block sizes for VREV are: 16, 32, 64"); 5049 5050 unsigned EltSz = VT.getVectorElementType().getSizeInBits(); 5051 if (EltSz == 64) 5052 return false; 5053 5054 unsigned NumElts = VT.getVectorNumElements(); 5055 unsigned BlockElts = M[0] + 1; 5056 // If the first shuffle index is UNDEF, be optimistic. 5057 if (M[0] < 0) 5058 BlockElts = BlockSize / EltSz; 5059 5060 if (BlockSize <= EltSz || BlockSize != BlockElts * EltSz) 5061 return false; 5062 5063 for (unsigned i = 0; i < NumElts; ++i) { 5064 if (M[i] < 0) continue; // ignore UNDEF indices 5065 if ((unsigned) M[i] != (i - i%BlockElts) + (BlockElts - 1 - i%BlockElts)) 5066 return false; 5067 } 5068 5069 return true; 5070 } 5071 5072 static bool isVTBLMask(ArrayRef<int> M, EVT VT) { 5073 // We can handle <8 x i8> vector shuffles. If the index in the mask is out of 5074 // range, then 0 is placed into the resulting vector. So pretty much any mask 5075 // of 8 elements can work here. 5076 return VT == MVT::v8i8 && M.size() == 8; 5077 } 5078 5079 // Checks whether the shuffle mask represents a vector transpose (VTRN) by 5080 // checking that pairs of elements in the shuffle mask represent the same index 5081 // in each vector, incrementing the expected index by 2 at each step. 5082 // e.g. For v1,v2 of type v4i32 a valid shuffle mask is: [0, 4, 2, 6] 5083 // v1={a,b,c,d} => x=shufflevector v1, v2 shufflemask => x={a,e,c,g} 5084 // v2={e,f,g,h} 5085 // WhichResult gives the offset for each element in the mask based on which 5086 // of the two results it belongs to. 5087 // 5088 // The transpose can be represented either as: 5089 // result1 = shufflevector v1, v2, result1_shuffle_mask 5090 // result2 = shufflevector v1, v2, result2_shuffle_mask 5091 // where v1/v2 and the shuffle masks have the same number of elements 5092 // (here WhichResult (see below) indicates which result is being checked) 5093 // 5094 // or as: 5095 // results = shufflevector v1, v2, shuffle_mask 5096 // where both results are returned in one vector and the shuffle mask has twice 5097 // as many elements as v1/v2 (here WhichResult will always be 0 if true) here we 5098 // want to check the low half and high half of the shuffle mask as if it were 5099 // the other case 5100 static bool isVTRNMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) { 5101 unsigned EltSz = VT.getVectorElementType().getSizeInBits(); 5102 if (EltSz == 64) 5103 return false; 5104 5105 unsigned NumElts = VT.getVectorNumElements(); 5106 if (M.size() != NumElts && M.size() != NumElts*2) 5107 return false; 5108 5109 // If the mask is twice as long as the input vector then we need to check the 5110 // upper and lower parts of the mask with a matching value for WhichResult 5111 // FIXME: A mask with only even values will be rejected in case the first 5112 // element is undefined, e.g. [-1, 4, 2, 6] will be rejected, because only 5113 // M[0] is used to determine WhichResult 5114 for (unsigned i = 0; i < M.size(); i += NumElts) { 5115 if (M.size() == NumElts * 2) 5116 WhichResult = i / NumElts; 5117 else 5118 WhichResult = M[i] == 0 ? 0 : 1; 5119 for (unsigned j = 0; j < NumElts; j += 2) { 5120 if ((M[i+j] >= 0 && (unsigned) M[i+j] != j + WhichResult) || 5121 (M[i+j+1] >= 0 && (unsigned) M[i+j+1] != j + NumElts + WhichResult)) 5122 return false; 5123 } 5124 } 5125 5126 if (M.size() == NumElts*2) 5127 WhichResult = 0; 5128 5129 return true; 5130 } 5131 5132 /// isVTRN_v_undef_Mask - Special case of isVTRNMask for canonical form of 5133 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef". 5134 /// Mask is e.g., <0, 0, 2, 2> instead of <0, 4, 2, 6>. 5135 static bool isVTRN_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult){ 5136 unsigned EltSz = VT.getVectorElementType().getSizeInBits(); 5137 if (EltSz == 64) 5138 return false; 5139 5140 unsigned NumElts = VT.getVectorNumElements(); 5141 if (M.size() != NumElts && M.size() != NumElts*2) 5142 return false; 5143 5144 for (unsigned i = 0; i < M.size(); i += NumElts) { 5145 if (M.size() == NumElts * 2) 5146 WhichResult = i / NumElts; 5147 else 5148 WhichResult = M[i] == 0 ? 0 : 1; 5149 for (unsigned j = 0; j < NumElts; j += 2) { 5150 if ((M[i+j] >= 0 && (unsigned) M[i+j] != j + WhichResult) || 5151 (M[i+j+1] >= 0 && (unsigned) M[i+j+1] != j + WhichResult)) 5152 return false; 5153 } 5154 } 5155 5156 if (M.size() == NumElts*2) 5157 WhichResult = 0; 5158 5159 return true; 5160 } 5161 5162 // Checks whether the shuffle mask represents a vector unzip (VUZP) by checking 5163 // that the mask elements are either all even and in steps of size 2 or all odd 5164 // and in steps of size 2. 5165 // e.g. For v1,v2 of type v4i32 a valid shuffle mask is: [0, 2, 4, 6] 5166 // v1={a,b,c,d} => x=shufflevector v1, v2 shufflemask => x={a,c,e,g} 5167 // v2={e,f,g,h} 5168 // Requires similar checks to that of isVTRNMask with 5169 // respect the how results are returned. 5170 static bool isVUZPMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) { 5171 unsigned EltSz = VT.getVectorElementType().getSizeInBits(); 5172 if (EltSz == 64) 5173 return false; 5174 5175 unsigned NumElts = VT.getVectorNumElements(); 5176 if (M.size() != NumElts && M.size() != NumElts*2) 5177 return false; 5178 5179 for (unsigned i = 0; i < M.size(); i += NumElts) { 5180 WhichResult = M[i] == 0 ? 0 : 1; 5181 for (unsigned j = 0; j < NumElts; ++j) { 5182 if (M[i+j] >= 0 && (unsigned) M[i+j] != 2 * j + WhichResult) 5183 return false; 5184 } 5185 } 5186 5187 if (M.size() == NumElts*2) 5188 WhichResult = 0; 5189 5190 // VUZP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32. 5191 if (VT.is64BitVector() && EltSz == 32) 5192 return false; 5193 5194 return true; 5195 } 5196 5197 /// isVUZP_v_undef_Mask - Special case of isVUZPMask for canonical form of 5198 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef". 5199 /// Mask is e.g., <0, 2, 0, 2> instead of <0, 2, 4, 6>, 5200 static bool isVUZP_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult){ 5201 unsigned EltSz = VT.getVectorElementType().getSizeInBits(); 5202 if (EltSz == 64) 5203 return false; 5204 5205 unsigned NumElts = VT.getVectorNumElements(); 5206 if (M.size() != NumElts && M.size() != NumElts*2) 5207 return false; 5208 5209 unsigned Half = NumElts / 2; 5210 for (unsigned i = 0; i < M.size(); i += NumElts) { 5211 WhichResult = M[i] == 0 ? 0 : 1; 5212 for (unsigned j = 0; j < NumElts; j += Half) { 5213 unsigned Idx = WhichResult; 5214 for (unsigned k = 0; k < Half; ++k) { 5215 int MIdx = M[i + j + k]; 5216 if (MIdx >= 0 && (unsigned) MIdx != Idx) 5217 return false; 5218 Idx += 2; 5219 } 5220 } 5221 } 5222 5223 if (M.size() == NumElts*2) 5224 WhichResult = 0; 5225 5226 // VUZP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32. 5227 if (VT.is64BitVector() && EltSz == 32) 5228 return false; 5229 5230 return true; 5231 } 5232 5233 // Checks whether the shuffle mask represents a vector zip (VZIP) by checking 5234 // that pairs of elements of the shufflemask represent the same index in each 5235 // vector incrementing sequentially through the vectors. 5236 // e.g. For v1,v2 of type v4i32 a valid shuffle mask is: [0, 4, 1, 5] 5237 // v1={a,b,c,d} => x=shufflevector v1, v2 shufflemask => x={a,e,b,f} 5238 // v2={e,f,g,h} 5239 // Requires similar checks to that of isVTRNMask with respect the how results 5240 // are returned. 5241 static bool isVZIPMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) { 5242 unsigned EltSz = VT.getVectorElementType().getSizeInBits(); 5243 if (EltSz == 64) 5244 return false; 5245 5246 unsigned NumElts = VT.getVectorNumElements(); 5247 if (M.size() != NumElts && M.size() != NumElts*2) 5248 return false; 5249 5250 for (unsigned i = 0; i < M.size(); i += NumElts) { 5251 WhichResult = M[i] == 0 ? 0 : 1; 5252 unsigned Idx = WhichResult * NumElts / 2; 5253 for (unsigned j = 0; j < NumElts; j += 2) { 5254 if ((M[i+j] >= 0 && (unsigned) M[i+j] != Idx) || 5255 (M[i+j+1] >= 0 && (unsigned) M[i+j+1] != Idx + NumElts)) 5256 return false; 5257 Idx += 1; 5258 } 5259 } 5260 5261 if (M.size() == NumElts*2) 5262 WhichResult = 0; 5263 5264 // VZIP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32. 5265 if (VT.is64BitVector() && EltSz == 32) 5266 return false; 5267 5268 return true; 5269 } 5270 5271 /// isVZIP_v_undef_Mask - Special case of isVZIPMask for canonical form of 5272 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef". 5273 /// Mask is e.g., <0, 0, 1, 1> instead of <0, 4, 1, 5>. 5274 static bool isVZIP_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult){ 5275 unsigned EltSz = VT.getVectorElementType().getSizeInBits(); 5276 if (EltSz == 64) 5277 return false; 5278 5279 unsigned NumElts = VT.getVectorNumElements(); 5280 if (M.size() != NumElts && M.size() != NumElts*2) 5281 return false; 5282 5283 for (unsigned i = 0; i < M.size(); i += NumElts) { 5284 WhichResult = M[i] == 0 ? 0 : 1; 5285 unsigned Idx = WhichResult * NumElts / 2; 5286 for (unsigned j = 0; j < NumElts; j += 2) { 5287 if ((M[i+j] >= 0 && (unsigned) M[i+j] != Idx) || 5288 (M[i+j+1] >= 0 && (unsigned) M[i+j+1] != Idx)) 5289 return false; 5290 Idx += 1; 5291 } 5292 } 5293 5294 if (M.size() == NumElts*2) 5295 WhichResult = 0; 5296 5297 // VZIP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32. 5298 if (VT.is64BitVector() && EltSz == 32) 5299 return false; 5300 5301 return true; 5302 } 5303 5304 /// Check if \p ShuffleMask is a NEON two-result shuffle (VZIP, VUZP, VTRN), 5305 /// and return the corresponding ARMISD opcode if it is, or 0 if it isn't. 5306 static unsigned isNEONTwoResultShuffleMask(ArrayRef<int> ShuffleMask, EVT VT, 5307 unsigned &WhichResult, 5308 bool &isV_UNDEF) { 5309 isV_UNDEF = false; 5310 if (isVTRNMask(ShuffleMask, VT, WhichResult)) 5311 return ARMISD::VTRN; 5312 if (isVUZPMask(ShuffleMask, VT, WhichResult)) 5313 return ARMISD::VUZP; 5314 if (isVZIPMask(ShuffleMask, VT, WhichResult)) 5315 return ARMISD::VZIP; 5316 5317 isV_UNDEF = true; 5318 if (isVTRN_v_undef_Mask(ShuffleMask, VT, WhichResult)) 5319 return ARMISD::VTRN; 5320 if (isVUZP_v_undef_Mask(ShuffleMask, VT, WhichResult)) 5321 return ARMISD::VUZP; 5322 if (isVZIP_v_undef_Mask(ShuffleMask, VT, WhichResult)) 5323 return ARMISD::VZIP; 5324 5325 return 0; 5326 } 5327 5328 /// \return true if this is a reverse operation on an vector. 5329 static bool isReverseMask(ArrayRef<int> M, EVT VT) { 5330 unsigned NumElts = VT.getVectorNumElements(); 5331 // Make sure the mask has the right size. 5332 if (NumElts != M.size()) 5333 return false; 5334 5335 // Look for <15, ..., 3, -1, 1, 0>. 5336 for (unsigned i = 0; i != NumElts; ++i) 5337 if (M[i] >= 0 && M[i] != (int) (NumElts - 1 - i)) 5338 return false; 5339 5340 return true; 5341 } 5342 5343 // If N is an integer constant that can be moved into a register in one 5344 // instruction, return an SDValue of such a constant (will become a MOV 5345 // instruction). Otherwise return null. 5346 static SDValue IsSingleInstrConstant(SDValue N, SelectionDAG &DAG, 5347 const ARMSubtarget *ST, SDLoc dl) { 5348 uint64_t Val; 5349 if (!isa<ConstantSDNode>(N)) 5350 return SDValue(); 5351 Val = cast<ConstantSDNode>(N)->getZExtValue(); 5352 5353 if (ST->isThumb1Only()) { 5354 if (Val <= 255 || ~Val <= 255) 5355 return DAG.getConstant(Val, dl, MVT::i32); 5356 } else { 5357 if (ARM_AM::getSOImmVal(Val) != -1 || ARM_AM::getSOImmVal(~Val) != -1) 5358 return DAG.getConstant(Val, dl, MVT::i32); 5359 } 5360 return SDValue(); 5361 } 5362 5363 // If this is a case we can't handle, return null and let the default 5364 // expansion code take care of it. 5365 SDValue ARMTargetLowering::LowerBUILD_VECTOR(SDValue Op, SelectionDAG &DAG, 5366 const ARMSubtarget *ST) const { 5367 BuildVectorSDNode *BVN = cast<BuildVectorSDNode>(Op.getNode()); 5368 SDLoc dl(Op); 5369 EVT VT = Op.getValueType(); 5370 5371 APInt SplatBits, SplatUndef; 5372 unsigned SplatBitSize; 5373 bool HasAnyUndefs; 5374 if (BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs)) { 5375 if (SplatBitSize <= 64) { 5376 // Check if an immediate VMOV works. 5377 EVT VmovVT; 5378 SDValue Val = isNEONModifiedImm(SplatBits.getZExtValue(), 5379 SplatUndef.getZExtValue(), SplatBitSize, 5380 DAG, dl, VmovVT, VT.is128BitVector(), 5381 VMOVModImm); 5382 if (Val.getNode()) { 5383 SDValue Vmov = DAG.getNode(ARMISD::VMOVIMM, dl, VmovVT, Val); 5384 return DAG.getNode(ISD::BITCAST, dl, VT, Vmov); 5385 } 5386 5387 // Try an immediate VMVN. 5388 uint64_t NegatedImm = (~SplatBits).getZExtValue(); 5389 Val = isNEONModifiedImm(NegatedImm, 5390 SplatUndef.getZExtValue(), SplatBitSize, 5391 DAG, dl, VmovVT, VT.is128BitVector(), 5392 VMVNModImm); 5393 if (Val.getNode()) { 5394 SDValue Vmov = DAG.getNode(ARMISD::VMVNIMM, dl, VmovVT, Val); 5395 return DAG.getNode(ISD::BITCAST, dl, VT, Vmov); 5396 } 5397 5398 // Use vmov.f32 to materialize other v2f32 and v4f32 splats. 5399 if ((VT == MVT::v2f32 || VT == MVT::v4f32) && SplatBitSize == 32) { 5400 int ImmVal = ARM_AM::getFP32Imm(SplatBits); 5401 if (ImmVal != -1) { 5402 SDValue Val = DAG.getTargetConstant(ImmVal, dl, MVT::i32); 5403 return DAG.getNode(ARMISD::VMOVFPIMM, dl, VT, Val); 5404 } 5405 } 5406 } 5407 } 5408 5409 // Scan through the operands to see if only one value is used. 5410 // 5411 // As an optimisation, even if more than one value is used it may be more 5412 // profitable to splat with one value then change some lanes. 5413 // 5414 // Heuristically we decide to do this if the vector has a "dominant" value, 5415 // defined as splatted to more than half of the lanes. 5416 unsigned NumElts = VT.getVectorNumElements(); 5417 bool isOnlyLowElement = true; 5418 bool usesOnlyOneValue = true; 5419 bool hasDominantValue = false; 5420 bool isConstant = true; 5421 5422 // Map of the number of times a particular SDValue appears in the 5423 // element list. 5424 DenseMap<SDValue, unsigned> ValueCounts; 5425 SDValue Value; 5426 for (unsigned i = 0; i < NumElts; ++i) { 5427 SDValue V = Op.getOperand(i); 5428 if (V.getOpcode() == ISD::UNDEF) 5429 continue; 5430 if (i > 0) 5431 isOnlyLowElement = false; 5432 if (!isa<ConstantFPSDNode>(V) && !isa<ConstantSDNode>(V)) 5433 isConstant = false; 5434 5435 ValueCounts.insert(std::make_pair(V, 0)); 5436 unsigned &Count = ValueCounts[V]; 5437 5438 // Is this value dominant? (takes up more than half of the lanes) 5439 if (++Count > (NumElts / 2)) { 5440 hasDominantValue = true; 5441 Value = V; 5442 } 5443 } 5444 if (ValueCounts.size() != 1) 5445 usesOnlyOneValue = false; 5446 if (!Value.getNode() && ValueCounts.size() > 0) 5447 Value = ValueCounts.begin()->first; 5448 5449 if (ValueCounts.size() == 0) 5450 return DAG.getUNDEF(VT); 5451 5452 // Loads are better lowered with insert_vector_elt/ARMISD::BUILD_VECTOR. 5453 // Keep going if we are hitting this case. 5454 if (isOnlyLowElement && !ISD::isNormalLoad(Value.getNode())) 5455 return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Value); 5456 5457 unsigned EltSize = VT.getVectorElementType().getSizeInBits(); 5458 5459 // Use VDUP for non-constant splats. For f32 constant splats, reduce to 5460 // i32 and try again. 5461 if (hasDominantValue && EltSize <= 32) { 5462 if (!isConstant) { 5463 SDValue N; 5464 5465 // If we are VDUPing a value that comes directly from a vector, that will 5466 // cause an unnecessary move to and from a GPR, where instead we could 5467 // just use VDUPLANE. We can only do this if the lane being extracted 5468 // is at a constant index, as the VDUP from lane instructions only have 5469 // constant-index forms. 5470 ConstantSDNode *constIndex; 5471 if (Value->getOpcode() == ISD::EXTRACT_VECTOR_ELT && 5472 (constIndex = dyn_cast<ConstantSDNode>(Value->getOperand(1)))) { 5473 // We need to create a new undef vector to use for the VDUPLANE if the 5474 // size of the vector from which we get the value is different than the 5475 // size of the vector that we need to create. We will insert the element 5476 // such that the register coalescer will remove unnecessary copies. 5477 if (VT != Value->getOperand(0).getValueType()) { 5478 unsigned index = constIndex->getAPIntValue().getLimitedValue() % 5479 VT.getVectorNumElements(); 5480 N = DAG.getNode(ARMISD::VDUPLANE, dl, VT, 5481 DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, DAG.getUNDEF(VT), 5482 Value, DAG.getConstant(index, dl, MVT::i32)), 5483 DAG.getConstant(index, dl, MVT::i32)); 5484 } else 5485 N = DAG.getNode(ARMISD::VDUPLANE, dl, VT, 5486 Value->getOperand(0), Value->getOperand(1)); 5487 } else 5488 N = DAG.getNode(ARMISD::VDUP, dl, VT, Value); 5489 5490 if (!usesOnlyOneValue) { 5491 // The dominant value was splatted as 'N', but we now have to insert 5492 // all differing elements. 5493 for (unsigned I = 0; I < NumElts; ++I) { 5494 if (Op.getOperand(I) == Value) 5495 continue; 5496 SmallVector<SDValue, 3> Ops; 5497 Ops.push_back(N); 5498 Ops.push_back(Op.getOperand(I)); 5499 Ops.push_back(DAG.getConstant(I, dl, MVT::i32)); 5500 N = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Ops); 5501 } 5502 } 5503 return N; 5504 } 5505 if (VT.getVectorElementType().isFloatingPoint()) { 5506 SmallVector<SDValue, 8> Ops; 5507 for (unsigned i = 0; i < NumElts; ++i) 5508 Ops.push_back(DAG.getNode(ISD::BITCAST, dl, MVT::i32, 5509 Op.getOperand(i))); 5510 EVT VecVT = EVT::getVectorVT(*DAG.getContext(), MVT::i32, NumElts); 5511 SDValue Val = DAG.getNode(ISD::BUILD_VECTOR, dl, VecVT, Ops); 5512 Val = LowerBUILD_VECTOR(Val, DAG, ST); 5513 if (Val.getNode()) 5514 return DAG.getNode(ISD::BITCAST, dl, VT, Val); 5515 } 5516 if (usesOnlyOneValue) { 5517 SDValue Val = IsSingleInstrConstant(Value, DAG, ST, dl); 5518 if (isConstant && Val.getNode()) 5519 return DAG.getNode(ARMISD::VDUP, dl, VT, Val); 5520 } 5521 } 5522 5523 // If all elements are constants and the case above didn't get hit, fall back 5524 // to the default expansion, which will generate a load from the constant 5525 // pool. 5526 if (isConstant) 5527 return SDValue(); 5528 5529 // Empirical tests suggest this is rarely worth it for vectors of length <= 2. 5530 if (NumElts >= 4) { 5531 SDValue shuffle = ReconstructShuffle(Op, DAG); 5532 if (shuffle != SDValue()) 5533 return shuffle; 5534 } 5535 5536 // Vectors with 32- or 64-bit elements can be built by directly assigning 5537 // the subregisters. Lower it to an ARMISD::BUILD_VECTOR so the operands 5538 // will be legalized. 5539 if (EltSize >= 32) { 5540 // Do the expansion with floating-point types, since that is what the VFP 5541 // registers are defined to use, and since i64 is not legal. 5542 EVT EltVT = EVT::getFloatingPointVT(EltSize); 5543 EVT VecVT = EVT::getVectorVT(*DAG.getContext(), EltVT, NumElts); 5544 SmallVector<SDValue, 8> Ops; 5545 for (unsigned i = 0; i < NumElts; ++i) 5546 Ops.push_back(DAG.getNode(ISD::BITCAST, dl, EltVT, Op.getOperand(i))); 5547 SDValue Val = DAG.getNode(ARMISD::BUILD_VECTOR, dl, VecVT, Ops); 5548 return DAG.getNode(ISD::BITCAST, dl, VT, Val); 5549 } 5550 5551 // If all else fails, just use a sequence of INSERT_VECTOR_ELT when we 5552 // know the default expansion would otherwise fall back on something even 5553 // worse. For a vector with one or two non-undef values, that's 5554 // scalar_to_vector for the elements followed by a shuffle (provided the 5555 // shuffle is valid for the target) and materialization element by element 5556 // on the stack followed by a load for everything else. 5557 if (!isConstant && !usesOnlyOneValue) { 5558 SDValue Vec = DAG.getUNDEF(VT); 5559 for (unsigned i = 0 ; i < NumElts; ++i) { 5560 SDValue V = Op.getOperand(i); 5561 if (V.getOpcode() == ISD::UNDEF) 5562 continue; 5563 SDValue LaneIdx = DAG.getConstant(i, dl, MVT::i32); 5564 Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Vec, V, LaneIdx); 5565 } 5566 return Vec; 5567 } 5568 5569 return SDValue(); 5570 } 5571 5572 // Gather data to see if the operation can be modelled as a 5573 // shuffle in combination with VEXTs. 5574 SDValue ARMTargetLowering::ReconstructShuffle(SDValue Op, 5575 SelectionDAG &DAG) const { 5576 assert(Op.getOpcode() == ISD::BUILD_VECTOR && "Unknown opcode!"); 5577 SDLoc dl(Op); 5578 EVT VT = Op.getValueType(); 5579 unsigned NumElts = VT.getVectorNumElements(); 5580 5581 struct ShuffleSourceInfo { 5582 SDValue Vec; 5583 unsigned MinElt; 5584 unsigned MaxElt; 5585 5586 // We may insert some combination of BITCASTs and VEXT nodes to force Vec to 5587 // be compatible with the shuffle we intend to construct. As a result 5588 // ShuffleVec will be some sliding window into the original Vec. 5589 SDValue ShuffleVec; 5590 5591 // Code should guarantee that element i in Vec starts at element "WindowBase 5592 // + i * WindowScale in ShuffleVec". 5593 int WindowBase; 5594 int WindowScale; 5595 5596 bool operator ==(SDValue OtherVec) { return Vec == OtherVec; } 5597 ShuffleSourceInfo(SDValue Vec) 5598 : Vec(Vec), MinElt(UINT_MAX), MaxElt(0), ShuffleVec(Vec), WindowBase(0), 5599 WindowScale(1) {} 5600 }; 5601 5602 // First gather all vectors used as an immediate source for this BUILD_VECTOR 5603 // node. 5604 SmallVector<ShuffleSourceInfo, 2> Sources; 5605 for (unsigned i = 0; i < NumElts; ++i) { 5606 SDValue V = Op.getOperand(i); 5607 if (V.getOpcode() == ISD::UNDEF) 5608 continue; 5609 else if (V.getOpcode() != ISD::EXTRACT_VECTOR_ELT) { 5610 // A shuffle can only come from building a vector from various 5611 // elements of other vectors. 5612 return SDValue(); 5613 } else if (!isa<ConstantSDNode>(V.getOperand(1))) { 5614 // Furthermore, shuffles require a constant mask, whereas extractelts 5615 // accept variable indices. 5616 return SDValue(); 5617 } 5618 5619 // Add this element source to the list if it's not already there. 5620 SDValue SourceVec = V.getOperand(0); 5621 auto Source = std::find(Sources.begin(), Sources.end(), SourceVec); 5622 if (Source == Sources.end()) 5623 Source = Sources.insert(Sources.end(), ShuffleSourceInfo(SourceVec)); 5624 5625 // Update the minimum and maximum lane number seen. 5626 unsigned EltNo = cast<ConstantSDNode>(V.getOperand(1))->getZExtValue(); 5627 Source->MinElt = std::min(Source->MinElt, EltNo); 5628 Source->MaxElt = std::max(Source->MaxElt, EltNo); 5629 } 5630 5631 // Currently only do something sane when at most two source vectors 5632 // are involved. 5633 if (Sources.size() > 2) 5634 return SDValue(); 5635 5636 // Find out the smallest element size among result and two sources, and use 5637 // it as element size to build the shuffle_vector. 5638 EVT SmallestEltTy = VT.getVectorElementType(); 5639 for (auto &Source : Sources) { 5640 EVT SrcEltTy = Source.Vec.getValueType().getVectorElementType(); 5641 if (SrcEltTy.bitsLT(SmallestEltTy)) 5642 SmallestEltTy = SrcEltTy; 5643 } 5644 unsigned ResMultiplier = 5645 VT.getVectorElementType().getSizeInBits() / SmallestEltTy.getSizeInBits(); 5646 NumElts = VT.getSizeInBits() / SmallestEltTy.getSizeInBits(); 5647 EVT ShuffleVT = EVT::getVectorVT(*DAG.getContext(), SmallestEltTy, NumElts); 5648 5649 // If the source vector is too wide or too narrow, we may nevertheless be able 5650 // to construct a compatible shuffle either by concatenating it with UNDEF or 5651 // extracting a suitable range of elements. 5652 for (auto &Src : Sources) { 5653 EVT SrcVT = Src.ShuffleVec.getValueType(); 5654 5655 if (SrcVT.getSizeInBits() == VT.getSizeInBits()) 5656 continue; 5657 5658 // This stage of the search produces a source with the same element type as 5659 // the original, but with a total width matching the BUILD_VECTOR output. 5660 EVT EltVT = SrcVT.getVectorElementType(); 5661 unsigned NumSrcElts = VT.getSizeInBits() / EltVT.getSizeInBits(); 5662 EVT DestVT = EVT::getVectorVT(*DAG.getContext(), EltVT, NumSrcElts); 5663 5664 if (SrcVT.getSizeInBits() < VT.getSizeInBits()) { 5665 if (2 * SrcVT.getSizeInBits() != VT.getSizeInBits()) 5666 return SDValue(); 5667 // We can pad out the smaller vector for free, so if it's part of a 5668 // shuffle... 5669 Src.ShuffleVec = 5670 DAG.getNode(ISD::CONCAT_VECTORS, dl, DestVT, Src.ShuffleVec, 5671 DAG.getUNDEF(Src.ShuffleVec.getValueType())); 5672 continue; 5673 } 5674 5675 if (SrcVT.getSizeInBits() != 2 * VT.getSizeInBits()) 5676 return SDValue(); 5677 5678 if (Src.MaxElt - Src.MinElt >= NumSrcElts) { 5679 // Span too large for a VEXT to cope 5680 return SDValue(); 5681 } 5682 5683 if (Src.MinElt >= NumSrcElts) { 5684 // The extraction can just take the second half 5685 Src.ShuffleVec = 5686 DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DestVT, Src.ShuffleVec, 5687 DAG.getConstant(NumSrcElts, dl, MVT::i32)); 5688 Src.WindowBase = -NumSrcElts; 5689 } else if (Src.MaxElt < NumSrcElts) { 5690 // The extraction can just take the first half 5691 Src.ShuffleVec = 5692 DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DestVT, Src.ShuffleVec, 5693 DAG.getConstant(0, dl, MVT::i32)); 5694 } else { 5695 // An actual VEXT is needed 5696 SDValue VEXTSrc1 = 5697 DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DestVT, Src.ShuffleVec, 5698 DAG.getConstant(0, dl, MVT::i32)); 5699 SDValue VEXTSrc2 = 5700 DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DestVT, Src.ShuffleVec, 5701 DAG.getConstant(NumSrcElts, dl, MVT::i32)); 5702 5703 Src.ShuffleVec = DAG.getNode(ARMISD::VEXT, dl, DestVT, VEXTSrc1, 5704 VEXTSrc2, 5705 DAG.getConstant(Src.MinElt, dl, MVT::i32)); 5706 Src.WindowBase = -Src.MinElt; 5707 } 5708 } 5709 5710 // Another possible incompatibility occurs from the vector element types. We 5711 // can fix this by bitcasting the source vectors to the same type we intend 5712 // for the shuffle. 5713 for (auto &Src : Sources) { 5714 EVT SrcEltTy = Src.ShuffleVec.getValueType().getVectorElementType(); 5715 if (SrcEltTy == SmallestEltTy) 5716 continue; 5717 assert(ShuffleVT.getVectorElementType() == SmallestEltTy); 5718 Src.ShuffleVec = DAG.getNode(ISD::BITCAST, dl, ShuffleVT, Src.ShuffleVec); 5719 Src.WindowScale = SrcEltTy.getSizeInBits() / SmallestEltTy.getSizeInBits(); 5720 Src.WindowBase *= Src.WindowScale; 5721 } 5722 5723 // Final sanity check before we try to actually produce a shuffle. 5724 DEBUG( 5725 for (auto Src : Sources) 5726 assert(Src.ShuffleVec.getValueType() == ShuffleVT); 5727 ); 5728 5729 // The stars all align, our next step is to produce the mask for the shuffle. 5730 SmallVector<int, 8> Mask(ShuffleVT.getVectorNumElements(), -1); 5731 int BitsPerShuffleLane = ShuffleVT.getVectorElementType().getSizeInBits(); 5732 for (unsigned i = 0; i < VT.getVectorNumElements(); ++i) { 5733 SDValue Entry = Op.getOperand(i); 5734 if (Entry.getOpcode() == ISD::UNDEF) 5735 continue; 5736 5737 auto Src = std::find(Sources.begin(), Sources.end(), Entry.getOperand(0)); 5738 int EltNo = cast<ConstantSDNode>(Entry.getOperand(1))->getSExtValue(); 5739 5740 // EXTRACT_VECTOR_ELT performs an implicit any_ext; BUILD_VECTOR an implicit 5741 // trunc. So only std::min(SrcBits, DestBits) actually get defined in this 5742 // segment. 5743 EVT OrigEltTy = Entry.getOperand(0).getValueType().getVectorElementType(); 5744 int BitsDefined = std::min(OrigEltTy.getSizeInBits(), 5745 VT.getVectorElementType().getSizeInBits()); 5746 int LanesDefined = BitsDefined / BitsPerShuffleLane; 5747 5748 // This source is expected to fill ResMultiplier lanes of the final shuffle, 5749 // starting at the appropriate offset. 5750 int *LaneMask = &Mask[i * ResMultiplier]; 5751 5752 int ExtractBase = EltNo * Src->WindowScale + Src->WindowBase; 5753 ExtractBase += NumElts * (Src - Sources.begin()); 5754 for (int j = 0; j < LanesDefined; ++j) 5755 LaneMask[j] = ExtractBase + j; 5756 } 5757 5758 // Final check before we try to produce nonsense... 5759 if (!isShuffleMaskLegal(Mask, ShuffleVT)) 5760 return SDValue(); 5761 5762 // We can't handle more than two sources. This should have already 5763 // been checked before this point. 5764 assert(Sources.size() <= 2 && "Too many sources!"); 5765 5766 SDValue ShuffleOps[] = { DAG.getUNDEF(ShuffleVT), DAG.getUNDEF(ShuffleVT) }; 5767 for (unsigned i = 0; i < Sources.size(); ++i) 5768 ShuffleOps[i] = Sources[i].ShuffleVec; 5769 5770 SDValue Shuffle = DAG.getVectorShuffle(ShuffleVT, dl, ShuffleOps[0], 5771 ShuffleOps[1], &Mask[0]); 5772 return DAG.getNode(ISD::BITCAST, dl, VT, Shuffle); 5773 } 5774 5775 /// isShuffleMaskLegal - Targets can use this to indicate that they only 5776 /// support *some* VECTOR_SHUFFLE operations, those with specific masks. 5777 /// By default, if a target supports the VECTOR_SHUFFLE node, all mask values 5778 /// are assumed to be legal. 5779 bool 5780 ARMTargetLowering::isShuffleMaskLegal(const SmallVectorImpl<int> &M, 5781 EVT VT) const { 5782 if (VT.getVectorNumElements() == 4 && 5783 (VT.is128BitVector() || VT.is64BitVector())) { 5784 unsigned PFIndexes[4]; 5785 for (unsigned i = 0; i != 4; ++i) { 5786 if (M[i] < 0) 5787 PFIndexes[i] = 8; 5788 else 5789 PFIndexes[i] = M[i]; 5790 } 5791 5792 // Compute the index in the perfect shuffle table. 5793 unsigned PFTableIndex = 5794 PFIndexes[0]*9*9*9+PFIndexes[1]*9*9+PFIndexes[2]*9+PFIndexes[3]; 5795 unsigned PFEntry = PerfectShuffleTable[PFTableIndex]; 5796 unsigned Cost = (PFEntry >> 30); 5797 5798 if (Cost <= 4) 5799 return true; 5800 } 5801 5802 bool ReverseVEXT, isV_UNDEF; 5803 unsigned Imm, WhichResult; 5804 5805 unsigned EltSize = VT.getVectorElementType().getSizeInBits(); 5806 return (EltSize >= 32 || 5807 ShuffleVectorSDNode::isSplatMask(&M[0], VT) || 5808 isVREVMask(M, VT, 64) || 5809 isVREVMask(M, VT, 32) || 5810 isVREVMask(M, VT, 16) || 5811 isVEXTMask(M, VT, ReverseVEXT, Imm) || 5812 isVTBLMask(M, VT) || 5813 isNEONTwoResultShuffleMask(M, VT, WhichResult, isV_UNDEF) || 5814 ((VT == MVT::v8i16 || VT == MVT::v16i8) && isReverseMask(M, VT))); 5815 } 5816 5817 /// GeneratePerfectShuffle - Given an entry in the perfect-shuffle table, emit 5818 /// the specified operations to build the shuffle. 5819 static SDValue GeneratePerfectShuffle(unsigned PFEntry, SDValue LHS, 5820 SDValue RHS, SelectionDAG &DAG, 5821 SDLoc dl) { 5822 unsigned OpNum = (PFEntry >> 26) & 0x0F; 5823 unsigned LHSID = (PFEntry >> 13) & ((1 << 13)-1); 5824 unsigned RHSID = (PFEntry >> 0) & ((1 << 13)-1); 5825 5826 enum { 5827 OP_COPY = 0, // Copy, used for things like <u,u,u,3> to say it is <0,1,2,3> 5828 OP_VREV, 5829 OP_VDUP0, 5830 OP_VDUP1, 5831 OP_VDUP2, 5832 OP_VDUP3, 5833 OP_VEXT1, 5834 OP_VEXT2, 5835 OP_VEXT3, 5836 OP_VUZPL, // VUZP, left result 5837 OP_VUZPR, // VUZP, right result 5838 OP_VZIPL, // VZIP, left result 5839 OP_VZIPR, // VZIP, right result 5840 OP_VTRNL, // VTRN, left result 5841 OP_VTRNR // VTRN, right result 5842 }; 5843 5844 if (OpNum == OP_COPY) { 5845 if (LHSID == (1*9+2)*9+3) return LHS; 5846 assert(LHSID == ((4*9+5)*9+6)*9+7 && "Illegal OP_COPY!"); 5847 return RHS; 5848 } 5849 5850 SDValue OpLHS, OpRHS; 5851 OpLHS = GeneratePerfectShuffle(PerfectShuffleTable[LHSID], LHS, RHS, DAG, dl); 5852 OpRHS = GeneratePerfectShuffle(PerfectShuffleTable[RHSID], LHS, RHS, DAG, dl); 5853 EVT VT = OpLHS.getValueType(); 5854 5855 switch (OpNum) { 5856 default: llvm_unreachable("Unknown shuffle opcode!"); 5857 case OP_VREV: 5858 // VREV divides the vector in half and swaps within the half. 5859 if (VT.getVectorElementType() == MVT::i32 || 5860 VT.getVectorElementType() == MVT::f32) 5861 return DAG.getNode(ARMISD::VREV64, dl, VT, OpLHS); 5862 // vrev <4 x i16> -> VREV32 5863 if (VT.getVectorElementType() == MVT::i16) 5864 return DAG.getNode(ARMISD::VREV32, dl, VT, OpLHS); 5865 // vrev <4 x i8> -> VREV16 5866 assert(VT.getVectorElementType() == MVT::i8); 5867 return DAG.getNode(ARMISD::VREV16, dl, VT, OpLHS); 5868 case OP_VDUP0: 5869 case OP_VDUP1: 5870 case OP_VDUP2: 5871 case OP_VDUP3: 5872 return DAG.getNode(ARMISD::VDUPLANE, dl, VT, 5873 OpLHS, DAG.getConstant(OpNum-OP_VDUP0, dl, MVT::i32)); 5874 case OP_VEXT1: 5875 case OP_VEXT2: 5876 case OP_VEXT3: 5877 return DAG.getNode(ARMISD::VEXT, dl, VT, 5878 OpLHS, OpRHS, 5879 DAG.getConstant(OpNum - OP_VEXT1 + 1, dl, MVT::i32)); 5880 case OP_VUZPL: 5881 case OP_VUZPR: 5882 return DAG.getNode(ARMISD::VUZP, dl, DAG.getVTList(VT, VT), 5883 OpLHS, OpRHS).getValue(OpNum-OP_VUZPL); 5884 case OP_VZIPL: 5885 case OP_VZIPR: 5886 return DAG.getNode(ARMISD::VZIP, dl, DAG.getVTList(VT, VT), 5887 OpLHS, OpRHS).getValue(OpNum-OP_VZIPL); 5888 case OP_VTRNL: 5889 case OP_VTRNR: 5890 return DAG.getNode(ARMISD::VTRN, dl, DAG.getVTList(VT, VT), 5891 OpLHS, OpRHS).getValue(OpNum-OP_VTRNL); 5892 } 5893 } 5894 5895 static SDValue LowerVECTOR_SHUFFLEv8i8(SDValue Op, 5896 ArrayRef<int> ShuffleMask, 5897 SelectionDAG &DAG) { 5898 // Check to see if we can use the VTBL instruction. 5899 SDValue V1 = Op.getOperand(0); 5900 SDValue V2 = Op.getOperand(1); 5901 SDLoc DL(Op); 5902 5903 SmallVector<SDValue, 8> VTBLMask; 5904 for (ArrayRef<int>::iterator 5905 I = ShuffleMask.begin(), E = ShuffleMask.end(); I != E; ++I) 5906 VTBLMask.push_back(DAG.getConstant(*I, DL, MVT::i32)); 5907 5908 if (V2.getNode()->getOpcode() == ISD::UNDEF) 5909 return DAG.getNode(ARMISD::VTBL1, DL, MVT::v8i8, V1, 5910 DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v8i8, VTBLMask)); 5911 5912 return DAG.getNode(ARMISD::VTBL2, DL, MVT::v8i8, V1, V2, 5913 DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v8i8, VTBLMask)); 5914 } 5915 5916 static SDValue LowerReverse_VECTOR_SHUFFLEv16i8_v8i16(SDValue Op, 5917 SelectionDAG &DAG) { 5918 SDLoc DL(Op); 5919 SDValue OpLHS = Op.getOperand(0); 5920 EVT VT = OpLHS.getValueType(); 5921 5922 assert((VT == MVT::v8i16 || VT == MVT::v16i8) && 5923 "Expect an v8i16/v16i8 type"); 5924 OpLHS = DAG.getNode(ARMISD::VREV64, DL, VT, OpLHS); 5925 // For a v16i8 type: After the VREV, we have got <8, ...15, 8, ..., 0>. Now, 5926 // extract the first 8 bytes into the top double word and the last 8 bytes 5927 // into the bottom double word. The v8i16 case is similar. 5928 unsigned ExtractNum = (VT == MVT::v16i8) ? 8 : 4; 5929 return DAG.getNode(ARMISD::VEXT, DL, VT, OpLHS, OpLHS, 5930 DAG.getConstant(ExtractNum, DL, MVT::i32)); 5931 } 5932 5933 static SDValue LowerVECTOR_SHUFFLE(SDValue Op, SelectionDAG &DAG) { 5934 SDValue V1 = Op.getOperand(0); 5935 SDValue V2 = Op.getOperand(1); 5936 SDLoc dl(Op); 5937 EVT VT = Op.getValueType(); 5938 ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(Op.getNode()); 5939 5940 // Convert shuffles that are directly supported on NEON to target-specific 5941 // DAG nodes, instead of keeping them as shuffles and matching them again 5942 // during code selection. This is more efficient and avoids the possibility 5943 // of inconsistencies between legalization and selection. 5944 // FIXME: floating-point vectors should be canonicalized to integer vectors 5945 // of the same time so that they get CSEd properly. 5946 ArrayRef<int> ShuffleMask = SVN->getMask(); 5947 5948 unsigned EltSize = VT.getVectorElementType().getSizeInBits(); 5949 if (EltSize <= 32) { 5950 if (ShuffleVectorSDNode::isSplatMask(&ShuffleMask[0], VT)) { 5951 int Lane = SVN->getSplatIndex(); 5952 // If this is undef splat, generate it via "just" vdup, if possible. 5953 if (Lane == -1) Lane = 0; 5954 5955 // Test if V1 is a SCALAR_TO_VECTOR. 5956 if (Lane == 0 && V1.getOpcode() == ISD::SCALAR_TO_VECTOR) { 5957 return DAG.getNode(ARMISD::VDUP, dl, VT, V1.getOperand(0)); 5958 } 5959 // Test if V1 is a BUILD_VECTOR which is equivalent to a SCALAR_TO_VECTOR 5960 // (and probably will turn into a SCALAR_TO_VECTOR once legalization 5961 // reaches it). 5962 if (Lane == 0 && V1.getOpcode() == ISD::BUILD_VECTOR && 5963 !isa<ConstantSDNode>(V1.getOperand(0))) { 5964 bool IsScalarToVector = true; 5965 for (unsigned i = 1, e = V1.getNumOperands(); i != e; ++i) 5966 if (V1.getOperand(i).getOpcode() != ISD::UNDEF) { 5967 IsScalarToVector = false; 5968 break; 5969 } 5970 if (IsScalarToVector) 5971 return DAG.getNode(ARMISD::VDUP, dl, VT, V1.getOperand(0)); 5972 } 5973 return DAG.getNode(ARMISD::VDUPLANE, dl, VT, V1, 5974 DAG.getConstant(Lane, dl, MVT::i32)); 5975 } 5976 5977 bool ReverseVEXT; 5978 unsigned Imm; 5979 if (isVEXTMask(ShuffleMask, VT, ReverseVEXT, Imm)) { 5980 if (ReverseVEXT) 5981 std::swap(V1, V2); 5982 return DAG.getNode(ARMISD::VEXT, dl, VT, V1, V2, 5983 DAG.getConstant(Imm, dl, MVT::i32)); 5984 } 5985 5986 if (isVREVMask(ShuffleMask, VT, 64)) 5987 return DAG.getNode(ARMISD::VREV64, dl, VT, V1); 5988 if (isVREVMask(ShuffleMask, VT, 32)) 5989 return DAG.getNode(ARMISD::VREV32, dl, VT, V1); 5990 if (isVREVMask(ShuffleMask, VT, 16)) 5991 return DAG.getNode(ARMISD::VREV16, dl, VT, V1); 5992 5993 if (V2->getOpcode() == ISD::UNDEF && 5994 isSingletonVEXTMask(ShuffleMask, VT, Imm)) { 5995 return DAG.getNode(ARMISD::VEXT, dl, VT, V1, V1, 5996 DAG.getConstant(Imm, dl, MVT::i32)); 5997 } 5998 5999 // Check for Neon shuffles that modify both input vectors in place. 6000 // If both results are used, i.e., if there are two shuffles with the same 6001 // source operands and with masks corresponding to both results of one of 6002 // these operations, DAG memoization will ensure that a single node is 6003 // used for both shuffles. 6004 unsigned WhichResult; 6005 bool isV_UNDEF; 6006 if (unsigned ShuffleOpc = isNEONTwoResultShuffleMask( 6007 ShuffleMask, VT, WhichResult, isV_UNDEF)) { 6008 if (isV_UNDEF) 6009 V2 = V1; 6010 return DAG.getNode(ShuffleOpc, dl, DAG.getVTList(VT, VT), V1, V2) 6011 .getValue(WhichResult); 6012 } 6013 6014 // Also check for these shuffles through CONCAT_VECTORS: we canonicalize 6015 // shuffles that produce a result larger than their operands with: 6016 // shuffle(concat(v1, undef), concat(v2, undef)) 6017 // -> 6018 // shuffle(concat(v1, v2), undef) 6019 // because we can access quad vectors (see PerformVECTOR_SHUFFLECombine). 6020 // 6021 // This is useful in the general case, but there are special cases where 6022 // native shuffles produce larger results: the two-result ops. 6023 // 6024 // Look through the concat when lowering them: 6025 // shuffle(concat(v1, v2), undef) 6026 // -> 6027 // concat(VZIP(v1, v2):0, :1) 6028 // 6029 if (V1->getOpcode() == ISD::CONCAT_VECTORS && 6030 V2->getOpcode() == ISD::UNDEF) { 6031 SDValue SubV1 = V1->getOperand(0); 6032 SDValue SubV2 = V1->getOperand(1); 6033 EVT SubVT = SubV1.getValueType(); 6034 6035 // We expect these to have been canonicalized to -1. 6036 assert(std::all_of(ShuffleMask.begin(), ShuffleMask.end(), [&](int i) { 6037 return i < (int)VT.getVectorNumElements(); 6038 }) && "Unexpected shuffle index into UNDEF operand!"); 6039 6040 if (unsigned ShuffleOpc = isNEONTwoResultShuffleMask( 6041 ShuffleMask, SubVT, WhichResult, isV_UNDEF)) { 6042 if (isV_UNDEF) 6043 SubV2 = SubV1; 6044 assert((WhichResult == 0) && 6045 "In-place shuffle of concat can only have one result!"); 6046 SDValue Res = DAG.getNode(ShuffleOpc, dl, DAG.getVTList(SubVT, SubVT), 6047 SubV1, SubV2); 6048 return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, Res.getValue(0), 6049 Res.getValue(1)); 6050 } 6051 } 6052 } 6053 6054 // If the shuffle is not directly supported and it has 4 elements, use 6055 // the PerfectShuffle-generated table to synthesize it from other shuffles. 6056 unsigned NumElts = VT.getVectorNumElements(); 6057 if (NumElts == 4) { 6058 unsigned PFIndexes[4]; 6059 for (unsigned i = 0; i != 4; ++i) { 6060 if (ShuffleMask[i] < 0) 6061 PFIndexes[i] = 8; 6062 else 6063 PFIndexes[i] = ShuffleMask[i]; 6064 } 6065 6066 // Compute the index in the perfect shuffle table. 6067 unsigned PFTableIndex = 6068 PFIndexes[0]*9*9*9+PFIndexes[1]*9*9+PFIndexes[2]*9+PFIndexes[3]; 6069 unsigned PFEntry = PerfectShuffleTable[PFTableIndex]; 6070 unsigned Cost = (PFEntry >> 30); 6071 6072 if (Cost <= 4) 6073 return GeneratePerfectShuffle(PFEntry, V1, V2, DAG, dl); 6074 } 6075 6076 // Implement shuffles with 32- or 64-bit elements as ARMISD::BUILD_VECTORs. 6077 if (EltSize >= 32) { 6078 // Do the expansion with floating-point types, since that is what the VFP 6079 // registers are defined to use, and since i64 is not legal. 6080 EVT EltVT = EVT::getFloatingPointVT(EltSize); 6081 EVT VecVT = EVT::getVectorVT(*DAG.getContext(), EltVT, NumElts); 6082 V1 = DAG.getNode(ISD::BITCAST, dl, VecVT, V1); 6083 V2 = DAG.getNode(ISD::BITCAST, dl, VecVT, V2); 6084 SmallVector<SDValue, 8> Ops; 6085 for (unsigned i = 0; i < NumElts; ++i) { 6086 if (ShuffleMask[i] < 0) 6087 Ops.push_back(DAG.getUNDEF(EltVT)); 6088 else 6089 Ops.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, EltVT, 6090 ShuffleMask[i] < (int)NumElts ? V1 : V2, 6091 DAG.getConstant(ShuffleMask[i] & (NumElts-1), 6092 dl, MVT::i32))); 6093 } 6094 SDValue Val = DAG.getNode(ARMISD::BUILD_VECTOR, dl, VecVT, Ops); 6095 return DAG.getNode(ISD::BITCAST, dl, VT, Val); 6096 } 6097 6098 if ((VT == MVT::v8i16 || VT == MVT::v16i8) && isReverseMask(ShuffleMask, VT)) 6099 return LowerReverse_VECTOR_SHUFFLEv16i8_v8i16(Op, DAG); 6100 6101 if (VT == MVT::v8i8) { 6102 SDValue NewOp = LowerVECTOR_SHUFFLEv8i8(Op, ShuffleMask, DAG); 6103 if (NewOp.getNode()) 6104 return NewOp; 6105 } 6106 6107 return SDValue(); 6108 } 6109 6110 static SDValue LowerINSERT_VECTOR_ELT(SDValue Op, SelectionDAG &DAG) { 6111 // INSERT_VECTOR_ELT is legal only for immediate indexes. 6112 SDValue Lane = Op.getOperand(2); 6113 if (!isa<ConstantSDNode>(Lane)) 6114 return SDValue(); 6115 6116 return Op; 6117 } 6118 6119 static SDValue LowerEXTRACT_VECTOR_ELT(SDValue Op, SelectionDAG &DAG) { 6120 // EXTRACT_VECTOR_ELT is legal only for immediate indexes. 6121 SDValue Lane = Op.getOperand(1); 6122 if (!isa<ConstantSDNode>(Lane)) 6123 return SDValue(); 6124 6125 SDValue Vec = Op.getOperand(0); 6126 if (Op.getValueType() == MVT::i32 && 6127 Vec.getValueType().getVectorElementType().getSizeInBits() < 32) { 6128 SDLoc dl(Op); 6129 return DAG.getNode(ARMISD::VGETLANEu, dl, MVT::i32, Vec, Lane); 6130 } 6131 6132 return Op; 6133 } 6134 6135 static SDValue LowerCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG) { 6136 // The only time a CONCAT_VECTORS operation can have legal types is when 6137 // two 64-bit vectors are concatenated to a 128-bit vector. 6138 assert(Op.getValueType().is128BitVector() && Op.getNumOperands() == 2 && 6139 "unexpected CONCAT_VECTORS"); 6140 SDLoc dl(Op); 6141 SDValue Val = DAG.getUNDEF(MVT::v2f64); 6142 SDValue Op0 = Op.getOperand(0); 6143 SDValue Op1 = Op.getOperand(1); 6144 if (Op0.getOpcode() != ISD::UNDEF) 6145 Val = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Val, 6146 DAG.getNode(ISD::BITCAST, dl, MVT::f64, Op0), 6147 DAG.getIntPtrConstant(0, dl)); 6148 if (Op1.getOpcode() != ISD::UNDEF) 6149 Val = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Val, 6150 DAG.getNode(ISD::BITCAST, dl, MVT::f64, Op1), 6151 DAG.getIntPtrConstant(1, dl)); 6152 return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Val); 6153 } 6154 6155 /// isExtendedBUILD_VECTOR - Check if N is a constant BUILD_VECTOR where each 6156 /// element has been zero/sign-extended, depending on the isSigned parameter, 6157 /// from an integer type half its size. 6158 static bool isExtendedBUILD_VECTOR(SDNode *N, SelectionDAG &DAG, 6159 bool isSigned) { 6160 // A v2i64 BUILD_VECTOR will have been legalized to a BITCAST from v4i32. 6161 EVT VT = N->getValueType(0); 6162 if (VT == MVT::v2i64 && N->getOpcode() == ISD::BITCAST) { 6163 SDNode *BVN = N->getOperand(0).getNode(); 6164 if (BVN->getValueType(0) != MVT::v4i32 || 6165 BVN->getOpcode() != ISD::BUILD_VECTOR) 6166 return false; 6167 unsigned LoElt = DAG.getDataLayout().isBigEndian() ? 1 : 0; 6168 unsigned HiElt = 1 - LoElt; 6169 ConstantSDNode *Lo0 = dyn_cast<ConstantSDNode>(BVN->getOperand(LoElt)); 6170 ConstantSDNode *Hi0 = dyn_cast<ConstantSDNode>(BVN->getOperand(HiElt)); 6171 ConstantSDNode *Lo1 = dyn_cast<ConstantSDNode>(BVN->getOperand(LoElt+2)); 6172 ConstantSDNode *Hi1 = dyn_cast<ConstantSDNode>(BVN->getOperand(HiElt+2)); 6173 if (!Lo0 || !Hi0 || !Lo1 || !Hi1) 6174 return false; 6175 if (isSigned) { 6176 if (Hi0->getSExtValue() == Lo0->getSExtValue() >> 32 && 6177 Hi1->getSExtValue() == Lo1->getSExtValue() >> 32) 6178 return true; 6179 } else { 6180 if (Hi0->isNullValue() && Hi1->isNullValue()) 6181 return true; 6182 } 6183 return false; 6184 } 6185 6186 if (N->getOpcode() != ISD::BUILD_VECTOR) 6187 return false; 6188 6189 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) { 6190 SDNode *Elt = N->getOperand(i).getNode(); 6191 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Elt)) { 6192 unsigned EltSize = VT.getVectorElementType().getSizeInBits(); 6193 unsigned HalfSize = EltSize / 2; 6194 if (isSigned) { 6195 if (!isIntN(HalfSize, C->getSExtValue())) 6196 return false; 6197 } else { 6198 if (!isUIntN(HalfSize, C->getZExtValue())) 6199 return false; 6200 } 6201 continue; 6202 } 6203 return false; 6204 } 6205 6206 return true; 6207 } 6208 6209 /// isSignExtended - Check if a node is a vector value that is sign-extended 6210 /// or a constant BUILD_VECTOR with sign-extended elements. 6211 static bool isSignExtended(SDNode *N, SelectionDAG &DAG) { 6212 if (N->getOpcode() == ISD::SIGN_EXTEND || ISD::isSEXTLoad(N)) 6213 return true; 6214 if (isExtendedBUILD_VECTOR(N, DAG, true)) 6215 return true; 6216 return false; 6217 } 6218 6219 /// isZeroExtended - Check if a node is a vector value that is zero-extended 6220 /// or a constant BUILD_VECTOR with zero-extended elements. 6221 static bool isZeroExtended(SDNode *N, SelectionDAG &DAG) { 6222 if (N->getOpcode() == ISD::ZERO_EXTEND || ISD::isZEXTLoad(N)) 6223 return true; 6224 if (isExtendedBUILD_VECTOR(N, DAG, false)) 6225 return true; 6226 return false; 6227 } 6228 6229 static EVT getExtensionTo64Bits(const EVT &OrigVT) { 6230 if (OrigVT.getSizeInBits() >= 64) 6231 return OrigVT; 6232 6233 assert(OrigVT.isSimple() && "Expecting a simple value type"); 6234 6235 MVT::SimpleValueType OrigSimpleTy = OrigVT.getSimpleVT().SimpleTy; 6236 switch (OrigSimpleTy) { 6237 default: llvm_unreachable("Unexpected Vector Type"); 6238 case MVT::v2i8: 6239 case MVT::v2i16: 6240 return MVT::v2i32; 6241 case MVT::v4i8: 6242 return MVT::v4i16; 6243 } 6244 } 6245 6246 /// AddRequiredExtensionForVMULL - Add a sign/zero extension to extend the total 6247 /// value size to 64 bits. We need a 64-bit D register as an operand to VMULL. 6248 /// We insert the required extension here to get the vector to fill a D register. 6249 static SDValue AddRequiredExtensionForVMULL(SDValue N, SelectionDAG &DAG, 6250 const EVT &OrigTy, 6251 const EVT &ExtTy, 6252 unsigned ExtOpcode) { 6253 // The vector originally had a size of OrigTy. It was then extended to ExtTy. 6254 // We expect the ExtTy to be 128-bits total. If the OrigTy is less than 6255 // 64-bits we need to insert a new extension so that it will be 64-bits. 6256 assert(ExtTy.is128BitVector() && "Unexpected extension size"); 6257 if (OrigTy.getSizeInBits() >= 64) 6258 return N; 6259 6260 // Must extend size to at least 64 bits to be used as an operand for VMULL. 6261 EVT NewVT = getExtensionTo64Bits(OrigTy); 6262 6263 return DAG.getNode(ExtOpcode, SDLoc(N), NewVT, N); 6264 } 6265 6266 /// SkipLoadExtensionForVMULL - return a load of the original vector size that 6267 /// does not do any sign/zero extension. If the original vector is less 6268 /// than 64 bits, an appropriate extension will be added after the load to 6269 /// reach a total size of 64 bits. We have to add the extension separately 6270 /// because ARM does not have a sign/zero extending load for vectors. 6271 static SDValue SkipLoadExtensionForVMULL(LoadSDNode *LD, SelectionDAG& DAG) { 6272 EVT ExtendedTy = getExtensionTo64Bits(LD->getMemoryVT()); 6273 6274 // The load already has the right type. 6275 if (ExtendedTy == LD->getMemoryVT()) 6276 return DAG.getLoad(LD->getMemoryVT(), SDLoc(LD), LD->getChain(), 6277 LD->getBasePtr(), LD->getPointerInfo(), LD->isVolatile(), 6278 LD->isNonTemporal(), LD->isInvariant(), 6279 LD->getAlignment()); 6280 6281 // We need to create a zextload/sextload. We cannot just create a load 6282 // followed by a zext/zext node because LowerMUL is also run during normal 6283 // operation legalization where we can't create illegal types. 6284 return DAG.getExtLoad(LD->getExtensionType(), SDLoc(LD), ExtendedTy, 6285 LD->getChain(), LD->getBasePtr(), LD->getPointerInfo(), 6286 LD->getMemoryVT(), LD->isVolatile(), LD->isInvariant(), 6287 LD->isNonTemporal(), LD->getAlignment()); 6288 } 6289 6290 /// SkipExtensionForVMULL - For a node that is a SIGN_EXTEND, ZERO_EXTEND, 6291 /// extending load, or BUILD_VECTOR with extended elements, return the 6292 /// unextended value. The unextended vector should be 64 bits so that it can 6293 /// be used as an operand to a VMULL instruction. If the original vector size 6294 /// before extension is less than 64 bits we add a an extension to resize 6295 /// the vector to 64 bits. 6296 static SDValue SkipExtensionForVMULL(SDNode *N, SelectionDAG &DAG) { 6297 if (N->getOpcode() == ISD::SIGN_EXTEND || N->getOpcode() == ISD::ZERO_EXTEND) 6298 return AddRequiredExtensionForVMULL(N->getOperand(0), DAG, 6299 N->getOperand(0)->getValueType(0), 6300 N->getValueType(0), 6301 N->getOpcode()); 6302 6303 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) 6304 return SkipLoadExtensionForVMULL(LD, DAG); 6305 6306 // Otherwise, the value must be a BUILD_VECTOR. For v2i64, it will 6307 // have been legalized as a BITCAST from v4i32. 6308 if (N->getOpcode() == ISD::BITCAST) { 6309 SDNode *BVN = N->getOperand(0).getNode(); 6310 assert(BVN->getOpcode() == ISD::BUILD_VECTOR && 6311 BVN->getValueType(0) == MVT::v4i32 && "expected v4i32 BUILD_VECTOR"); 6312 unsigned LowElt = DAG.getDataLayout().isBigEndian() ? 1 : 0; 6313 return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), MVT::v2i32, 6314 BVN->getOperand(LowElt), BVN->getOperand(LowElt+2)); 6315 } 6316 // Construct a new BUILD_VECTOR with elements truncated to half the size. 6317 assert(N->getOpcode() == ISD::BUILD_VECTOR && "expected BUILD_VECTOR"); 6318 EVT VT = N->getValueType(0); 6319 unsigned EltSize = VT.getVectorElementType().getSizeInBits() / 2; 6320 unsigned NumElts = VT.getVectorNumElements(); 6321 MVT TruncVT = MVT::getIntegerVT(EltSize); 6322 SmallVector<SDValue, 8> Ops; 6323 SDLoc dl(N); 6324 for (unsigned i = 0; i != NumElts; ++i) { 6325 ConstantSDNode *C = cast<ConstantSDNode>(N->getOperand(i)); 6326 const APInt &CInt = C->getAPIntValue(); 6327 // Element types smaller than 32 bits are not legal, so use i32 elements. 6328 // The values are implicitly truncated so sext vs. zext doesn't matter. 6329 Ops.push_back(DAG.getConstant(CInt.zextOrTrunc(32), dl, MVT::i32)); 6330 } 6331 return DAG.getNode(ISD::BUILD_VECTOR, dl, 6332 MVT::getVectorVT(TruncVT, NumElts), Ops); 6333 } 6334 6335 static bool isAddSubSExt(SDNode *N, SelectionDAG &DAG) { 6336 unsigned Opcode = N->getOpcode(); 6337 if (Opcode == ISD::ADD || Opcode == ISD::SUB) { 6338 SDNode *N0 = N->getOperand(0).getNode(); 6339 SDNode *N1 = N->getOperand(1).getNode(); 6340 return N0->hasOneUse() && N1->hasOneUse() && 6341 isSignExtended(N0, DAG) && isSignExtended(N1, DAG); 6342 } 6343 return false; 6344 } 6345 6346 static bool isAddSubZExt(SDNode *N, SelectionDAG &DAG) { 6347 unsigned Opcode = N->getOpcode(); 6348 if (Opcode == ISD::ADD || Opcode == ISD::SUB) { 6349 SDNode *N0 = N->getOperand(0).getNode(); 6350 SDNode *N1 = N->getOperand(1).getNode(); 6351 return N0->hasOneUse() && N1->hasOneUse() && 6352 isZeroExtended(N0, DAG) && isZeroExtended(N1, DAG); 6353 } 6354 return false; 6355 } 6356 6357 static SDValue LowerMUL(SDValue Op, SelectionDAG &DAG) { 6358 // Multiplications are only custom-lowered for 128-bit vectors so that 6359 // VMULL can be detected. Otherwise v2i64 multiplications are not legal. 6360 EVT VT = Op.getValueType(); 6361 assert(VT.is128BitVector() && VT.isInteger() && 6362 "unexpected type for custom-lowering ISD::MUL"); 6363 SDNode *N0 = Op.getOperand(0).getNode(); 6364 SDNode *N1 = Op.getOperand(1).getNode(); 6365 unsigned NewOpc = 0; 6366 bool isMLA = false; 6367 bool isN0SExt = isSignExtended(N0, DAG); 6368 bool isN1SExt = isSignExtended(N1, DAG); 6369 if (isN0SExt && isN1SExt) 6370 NewOpc = ARMISD::VMULLs; 6371 else { 6372 bool isN0ZExt = isZeroExtended(N0, DAG); 6373 bool isN1ZExt = isZeroExtended(N1, DAG); 6374 if (isN0ZExt && isN1ZExt) 6375 NewOpc = ARMISD::VMULLu; 6376 else if (isN1SExt || isN1ZExt) { 6377 // Look for (s/zext A + s/zext B) * (s/zext C). We want to turn these 6378 // into (s/zext A * s/zext C) + (s/zext B * s/zext C) 6379 if (isN1SExt && isAddSubSExt(N0, DAG)) { 6380 NewOpc = ARMISD::VMULLs; 6381 isMLA = true; 6382 } else if (isN1ZExt && isAddSubZExt(N0, DAG)) { 6383 NewOpc = ARMISD::VMULLu; 6384 isMLA = true; 6385 } else if (isN0ZExt && isAddSubZExt(N1, DAG)) { 6386 std::swap(N0, N1); 6387 NewOpc = ARMISD::VMULLu; 6388 isMLA = true; 6389 } 6390 } 6391 6392 if (!NewOpc) { 6393 if (VT == MVT::v2i64) 6394 // Fall through to expand this. It is not legal. 6395 return SDValue(); 6396 else 6397 // Other vector multiplications are legal. 6398 return Op; 6399 } 6400 } 6401 6402 // Legalize to a VMULL instruction. 6403 SDLoc DL(Op); 6404 SDValue Op0; 6405 SDValue Op1 = SkipExtensionForVMULL(N1, DAG); 6406 if (!isMLA) { 6407 Op0 = SkipExtensionForVMULL(N0, DAG); 6408 assert(Op0.getValueType().is64BitVector() && 6409 Op1.getValueType().is64BitVector() && 6410 "unexpected types for extended operands to VMULL"); 6411 return DAG.getNode(NewOpc, DL, VT, Op0, Op1); 6412 } 6413 6414 // Optimizing (zext A + zext B) * C, to (VMULL A, C) + (VMULL B, C) during 6415 // isel lowering to take advantage of no-stall back to back vmul + vmla. 6416 // vmull q0, d4, d6 6417 // vmlal q0, d5, d6 6418 // is faster than 6419 // vaddl q0, d4, d5 6420 // vmovl q1, d6 6421 // vmul q0, q0, q1 6422 SDValue N00 = SkipExtensionForVMULL(N0->getOperand(0).getNode(), DAG); 6423 SDValue N01 = SkipExtensionForVMULL(N0->getOperand(1).getNode(), DAG); 6424 EVT Op1VT = Op1.getValueType(); 6425 return DAG.getNode(N0->getOpcode(), DL, VT, 6426 DAG.getNode(NewOpc, DL, VT, 6427 DAG.getNode(ISD::BITCAST, DL, Op1VT, N00), Op1), 6428 DAG.getNode(NewOpc, DL, VT, 6429 DAG.getNode(ISD::BITCAST, DL, Op1VT, N01), Op1)); 6430 } 6431 6432 static SDValue 6433 LowerSDIV_v4i8(SDValue X, SDValue Y, SDLoc dl, SelectionDAG &DAG) { 6434 // TODO: Should this propagate fast-math-flags? 6435 6436 // Convert to float 6437 // float4 xf = vcvt_f32_s32(vmovl_s16(a.lo)); 6438 // float4 yf = vcvt_f32_s32(vmovl_s16(b.lo)); 6439 X = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, X); 6440 Y = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, Y); 6441 X = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, X); 6442 Y = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, Y); 6443 // Get reciprocal estimate. 6444 // float4 recip = vrecpeq_f32(yf); 6445 Y = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32, 6446 DAG.getConstant(Intrinsic::arm_neon_vrecpe, dl, MVT::i32), 6447 Y); 6448 // Because char has a smaller range than uchar, we can actually get away 6449 // without any newton steps. This requires that we use a weird bias 6450 // of 0xb000, however (again, this has been exhaustively tested). 6451 // float4 result = as_float4(as_int4(xf*recip) + 0xb000); 6452 X = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, X, Y); 6453 X = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, X); 6454 Y = DAG.getConstant(0xb000, dl, MVT::i32); 6455 Y = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Y, Y, Y, Y); 6456 X = DAG.getNode(ISD::ADD, dl, MVT::v4i32, X, Y); 6457 X = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, X); 6458 // Convert back to short. 6459 X = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::v4i32, X); 6460 X = DAG.getNode(ISD::TRUNCATE, dl, MVT::v4i16, X); 6461 return X; 6462 } 6463 6464 static SDValue 6465 LowerSDIV_v4i16(SDValue N0, SDValue N1, SDLoc dl, SelectionDAG &DAG) { 6466 // TODO: Should this propagate fast-math-flags? 6467 6468 SDValue N2; 6469 // Convert to float. 6470 // float4 yf = vcvt_f32_s32(vmovl_s16(y)); 6471 // float4 xf = vcvt_f32_s32(vmovl_s16(x)); 6472 N0 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, N0); 6473 N1 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, N1); 6474 N0 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N0); 6475 N1 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N1); 6476 6477 // Use reciprocal estimate and one refinement step. 6478 // float4 recip = vrecpeq_f32(yf); 6479 // recip *= vrecpsq_f32(yf, recip); 6480 N2 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32, 6481 DAG.getConstant(Intrinsic::arm_neon_vrecpe, dl, MVT::i32), 6482 N1); 6483 N1 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32, 6484 DAG.getConstant(Intrinsic::arm_neon_vrecps, dl, MVT::i32), 6485 N1, N2); 6486 N2 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N1, N2); 6487 // Because short has a smaller range than ushort, we can actually get away 6488 // with only a single newton step. This requires that we use a weird bias 6489 // of 89, however (again, this has been exhaustively tested). 6490 // float4 result = as_float4(as_int4(xf*recip) + 0x89); 6491 N0 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N0, N2); 6492 N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, N0); 6493 N1 = DAG.getConstant(0x89, dl, MVT::i32); 6494 N1 = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, N1, N1, N1, N1); 6495 N0 = DAG.getNode(ISD::ADD, dl, MVT::v4i32, N0, N1); 6496 N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, N0); 6497 // Convert back to integer and return. 6498 // return vmovn_s32(vcvt_s32_f32(result)); 6499 N0 = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::v4i32, N0); 6500 N0 = DAG.getNode(ISD::TRUNCATE, dl, MVT::v4i16, N0); 6501 return N0; 6502 } 6503 6504 static SDValue LowerSDIV(SDValue Op, SelectionDAG &DAG) { 6505 EVT VT = Op.getValueType(); 6506 assert((VT == MVT::v4i16 || VT == MVT::v8i8) && 6507 "unexpected type for custom-lowering ISD::SDIV"); 6508 6509 SDLoc dl(Op); 6510 SDValue N0 = Op.getOperand(0); 6511 SDValue N1 = Op.getOperand(1); 6512 SDValue N2, N3; 6513 6514 if (VT == MVT::v8i8) { 6515 N0 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v8i16, N0); 6516 N1 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v8i16, N1); 6517 6518 N2 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0, 6519 DAG.getIntPtrConstant(4, dl)); 6520 N3 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1, 6521 DAG.getIntPtrConstant(4, dl)); 6522 N0 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0, 6523 DAG.getIntPtrConstant(0, dl)); 6524 N1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1, 6525 DAG.getIntPtrConstant(0, dl)); 6526 6527 N0 = LowerSDIV_v4i8(N0, N1, dl, DAG); // v4i16 6528 N2 = LowerSDIV_v4i8(N2, N3, dl, DAG); // v4i16 6529 6530 N0 = DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v8i16, N0, N2); 6531 N0 = LowerCONCAT_VECTORS(N0, DAG); 6532 6533 N0 = DAG.getNode(ISD::TRUNCATE, dl, MVT::v8i8, N0); 6534 return N0; 6535 } 6536 return LowerSDIV_v4i16(N0, N1, dl, DAG); 6537 } 6538 6539 static SDValue LowerUDIV(SDValue Op, SelectionDAG &DAG) { 6540 // TODO: Should this propagate fast-math-flags? 6541 EVT VT = Op.getValueType(); 6542 assert((VT == MVT::v4i16 || VT == MVT::v8i8) && 6543 "unexpected type for custom-lowering ISD::UDIV"); 6544 6545 SDLoc dl(Op); 6546 SDValue N0 = Op.getOperand(0); 6547 SDValue N1 = Op.getOperand(1); 6548 SDValue N2, N3; 6549 6550 if (VT == MVT::v8i8) { 6551 N0 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v8i16, N0); 6552 N1 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v8i16, N1); 6553 6554 N2 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0, 6555 DAG.getIntPtrConstant(4, dl)); 6556 N3 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1, 6557 DAG.getIntPtrConstant(4, dl)); 6558 N0 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0, 6559 DAG.getIntPtrConstant(0, dl)); 6560 N1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1, 6561 DAG.getIntPtrConstant(0, dl)); 6562 6563 N0 = LowerSDIV_v4i16(N0, N1, dl, DAG); // v4i16 6564 N2 = LowerSDIV_v4i16(N2, N3, dl, DAG); // v4i16 6565 6566 N0 = DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v8i16, N0, N2); 6567 N0 = LowerCONCAT_VECTORS(N0, DAG); 6568 6569 N0 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v8i8, 6570 DAG.getConstant(Intrinsic::arm_neon_vqmovnsu, dl, 6571 MVT::i32), 6572 N0); 6573 return N0; 6574 } 6575 6576 // v4i16 sdiv ... Convert to float. 6577 // float4 yf = vcvt_f32_s32(vmovl_u16(y)); 6578 // float4 xf = vcvt_f32_s32(vmovl_u16(x)); 6579 N0 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v4i32, N0); 6580 N1 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v4i32, N1); 6581 N0 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N0); 6582 SDValue BN1 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N1); 6583 6584 // Use reciprocal estimate and two refinement steps. 6585 // float4 recip = vrecpeq_f32(yf); 6586 // recip *= vrecpsq_f32(yf, recip); 6587 // recip *= vrecpsq_f32(yf, recip); 6588 N2 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32, 6589 DAG.getConstant(Intrinsic::arm_neon_vrecpe, dl, MVT::i32), 6590 BN1); 6591 N1 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32, 6592 DAG.getConstant(Intrinsic::arm_neon_vrecps, dl, MVT::i32), 6593 BN1, N2); 6594 N2 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N1, N2); 6595 N1 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32, 6596 DAG.getConstant(Intrinsic::arm_neon_vrecps, dl, MVT::i32), 6597 BN1, N2); 6598 N2 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N1, N2); 6599 // Simply multiplying by the reciprocal estimate can leave us a few ulps 6600 // too low, so we add 2 ulps (exhaustive testing shows that this is enough, 6601 // and that it will never cause us to return an answer too large). 6602 // float4 result = as_float4(as_int4(xf*recip) + 2); 6603 N0 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N0, N2); 6604 N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, N0); 6605 N1 = DAG.getConstant(2, dl, MVT::i32); 6606 N1 = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, N1, N1, N1, N1); 6607 N0 = DAG.getNode(ISD::ADD, dl, MVT::v4i32, N0, N1); 6608 N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, N0); 6609 // Convert back to integer and return. 6610 // return vmovn_u32(vcvt_s32_f32(result)); 6611 N0 = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::v4i32, N0); 6612 N0 = DAG.getNode(ISD::TRUNCATE, dl, MVT::v4i16, N0); 6613 return N0; 6614 } 6615 6616 static SDValue LowerADDC_ADDE_SUBC_SUBE(SDValue Op, SelectionDAG &DAG) { 6617 EVT VT = Op.getNode()->getValueType(0); 6618 SDVTList VTs = DAG.getVTList(VT, MVT::i32); 6619 6620 unsigned Opc; 6621 bool ExtraOp = false; 6622 switch (Op.getOpcode()) { 6623 default: llvm_unreachable("Invalid code"); 6624 case ISD::ADDC: Opc = ARMISD::ADDC; break; 6625 case ISD::ADDE: Opc = ARMISD::ADDE; ExtraOp = true; break; 6626 case ISD::SUBC: Opc = ARMISD::SUBC; break; 6627 case ISD::SUBE: Opc = ARMISD::SUBE; ExtraOp = true; break; 6628 } 6629 6630 if (!ExtraOp) 6631 return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0), 6632 Op.getOperand(1)); 6633 return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0), 6634 Op.getOperand(1), Op.getOperand(2)); 6635 } 6636 6637 SDValue ARMTargetLowering::LowerFSINCOS(SDValue Op, SelectionDAG &DAG) const { 6638 assert(Subtarget->isTargetDarwin()); 6639 6640 // For iOS, we want to call an alternative entry point: __sincos_stret, 6641 // return values are passed via sret. 6642 SDLoc dl(Op); 6643 SDValue Arg = Op.getOperand(0); 6644 EVT ArgVT = Arg.getValueType(); 6645 Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext()); 6646 auto PtrVT = getPointerTy(DAG.getDataLayout()); 6647 6648 MachineFrameInfo *FrameInfo = DAG.getMachineFunction().getFrameInfo(); 6649 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 6650 6651 // Pair of floats / doubles used to pass the result. 6652 Type *RetTy = StructType::get(ArgTy, ArgTy, nullptr); 6653 auto &DL = DAG.getDataLayout(); 6654 6655 ArgListTy Args; 6656 bool ShouldUseSRet = Subtarget->isAPCS_ABI(); 6657 SDValue SRet; 6658 if (ShouldUseSRet) { 6659 // Create stack object for sret. 6660 const uint64_t ByteSize = DL.getTypeAllocSize(RetTy); 6661 const unsigned StackAlign = DL.getPrefTypeAlignment(RetTy); 6662 int FrameIdx = FrameInfo->CreateStackObject(ByteSize, StackAlign, false); 6663 SRet = DAG.getFrameIndex(FrameIdx, TLI.getPointerTy(DL)); 6664 6665 ArgListEntry Entry; 6666 Entry.Node = SRet; 6667 Entry.Ty = RetTy->getPointerTo(); 6668 Entry.isSExt = false; 6669 Entry.isZExt = false; 6670 Entry.isSRet = true; 6671 Args.push_back(Entry); 6672 RetTy = Type::getVoidTy(*DAG.getContext()); 6673 } 6674 6675 ArgListEntry Entry; 6676 Entry.Node = Arg; 6677 Entry.Ty = ArgTy; 6678 Entry.isSExt = false; 6679 Entry.isZExt = false; 6680 Args.push_back(Entry); 6681 6682 const char *LibcallName = 6683 (ArgVT == MVT::f64) ? "__sincos_stret" : "__sincosf_stret"; 6684 RTLIB::Libcall LC = 6685 (ArgVT == MVT::f64) ? RTLIB::SINCOS_F64 : RTLIB::SINCOS_F32; 6686 CallingConv::ID CC = getLibcallCallingConv(LC); 6687 SDValue Callee = DAG.getExternalSymbol(LibcallName, getPointerTy(DL)); 6688 6689 TargetLowering::CallLoweringInfo CLI(DAG); 6690 CLI.setDebugLoc(dl) 6691 .setChain(DAG.getEntryNode()) 6692 .setCallee(CC, RetTy, Callee, std::move(Args), 0) 6693 .setDiscardResult(ShouldUseSRet); 6694 std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI); 6695 6696 if (!ShouldUseSRet) 6697 return CallResult.first; 6698 6699 SDValue LoadSin = DAG.getLoad(ArgVT, dl, CallResult.second, SRet, 6700 MachinePointerInfo(), false, false, false, 0); 6701 6702 // Address of cos field. 6703 SDValue Add = DAG.getNode(ISD::ADD, dl, PtrVT, SRet, 6704 DAG.getIntPtrConstant(ArgVT.getStoreSize(), dl)); 6705 SDValue LoadCos = DAG.getLoad(ArgVT, dl, LoadSin.getValue(1), Add, 6706 MachinePointerInfo(), false, false, false, 0); 6707 6708 SDVTList Tys = DAG.getVTList(ArgVT, ArgVT); 6709 return DAG.getNode(ISD::MERGE_VALUES, dl, Tys, 6710 LoadSin.getValue(0), LoadCos.getValue(0)); 6711 } 6712 6713 SDValue ARMTargetLowering::LowerWindowsDIVLibCall(SDValue Op, SelectionDAG &DAG, 6714 bool Signed, 6715 SDValue &Chain) const { 6716 EVT VT = Op.getValueType(); 6717 assert((VT == MVT::i32 || VT == MVT::i64) && 6718 "unexpected type for custom lowering DIV"); 6719 SDLoc dl(Op); 6720 6721 const auto &DL = DAG.getDataLayout(); 6722 const auto &TLI = DAG.getTargetLoweringInfo(); 6723 6724 const char *Name = nullptr; 6725 if (Signed) 6726 Name = (VT == MVT::i32) ? "__rt_sdiv" : "__rt_sdiv64"; 6727 else 6728 Name = (VT == MVT::i32) ? "__rt_udiv" : "__rt_udiv64"; 6729 6730 SDValue ES = DAG.getExternalSymbol(Name, TLI.getPointerTy(DL)); 6731 6732 ARMTargetLowering::ArgListTy Args; 6733 6734 for (auto AI : {1, 0}) { 6735 ArgListEntry Arg; 6736 Arg.Node = Op.getOperand(AI); 6737 Arg.Ty = Arg.Node.getValueType().getTypeForEVT(*DAG.getContext()); 6738 Args.push_back(Arg); 6739 } 6740 6741 CallLoweringInfo CLI(DAG); 6742 CLI.setDebugLoc(dl) 6743 .setChain(Chain) 6744 .setCallee(CallingConv::ARM_AAPCS_VFP, VT.getTypeForEVT(*DAG.getContext()), 6745 ES, std::move(Args), 0); 6746 6747 return LowerCallTo(CLI).first; 6748 } 6749 6750 SDValue ARMTargetLowering::LowerDIV_Windows(SDValue Op, SelectionDAG &DAG, 6751 bool Signed) const { 6752 assert(Op.getValueType() == MVT::i32 && 6753 "unexpected type for custom lowering DIV"); 6754 SDLoc dl(Op); 6755 6756 SDValue DBZCHK = DAG.getNode(ARMISD::WIN__DBZCHK, dl, MVT::Other, 6757 DAG.getEntryNode(), Op.getOperand(1)); 6758 6759 return LowerWindowsDIVLibCall(Op, DAG, Signed, DBZCHK); 6760 } 6761 6762 void ARMTargetLowering::ExpandDIV_Windows( 6763 SDValue Op, SelectionDAG &DAG, bool Signed, 6764 SmallVectorImpl<SDValue> &Results) const { 6765 const auto &DL = DAG.getDataLayout(); 6766 const auto &TLI = DAG.getTargetLoweringInfo(); 6767 6768 assert(Op.getValueType() == MVT::i64 && 6769 "unexpected type for custom lowering DIV"); 6770 SDLoc dl(Op); 6771 6772 SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, Op.getOperand(1), 6773 DAG.getConstant(0, dl, MVT::i32)); 6774 SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, Op.getOperand(1), 6775 DAG.getConstant(1, dl, MVT::i32)); 6776 SDValue Or = DAG.getNode(ISD::OR, dl, MVT::i32, Lo, Hi); 6777 6778 SDValue DBZCHK = 6779 DAG.getNode(ARMISD::WIN__DBZCHK, dl, MVT::Other, DAG.getEntryNode(), Or); 6780 6781 SDValue Result = LowerWindowsDIVLibCall(Op, DAG, Signed, DBZCHK); 6782 6783 SDValue Lower = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, Result); 6784 SDValue Upper = DAG.getNode(ISD::SRL, dl, MVT::i64, Result, 6785 DAG.getConstant(32, dl, TLI.getPointerTy(DL))); 6786 Upper = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, Upper); 6787 6788 Results.push_back(Lower); 6789 Results.push_back(Upper); 6790 } 6791 6792 static SDValue LowerAtomicLoadStore(SDValue Op, SelectionDAG &DAG) { 6793 // Monotonic load/store is legal for all targets 6794 if (cast<AtomicSDNode>(Op)->getOrdering() <= Monotonic) 6795 return Op; 6796 6797 // Acquire/Release load/store is not legal for targets without a 6798 // dmb or equivalent available. 6799 return SDValue(); 6800 } 6801 6802 static void ReplaceREADCYCLECOUNTER(SDNode *N, 6803 SmallVectorImpl<SDValue> &Results, 6804 SelectionDAG &DAG, 6805 const ARMSubtarget *Subtarget) { 6806 SDLoc DL(N); 6807 // Under Power Management extensions, the cycle-count is: 6808 // mrc p15, #0, <Rt>, c9, c13, #0 6809 SDValue Ops[] = { N->getOperand(0), // Chain 6810 DAG.getConstant(Intrinsic::arm_mrc, DL, MVT::i32), 6811 DAG.getConstant(15, DL, MVT::i32), 6812 DAG.getConstant(0, DL, MVT::i32), 6813 DAG.getConstant(9, DL, MVT::i32), 6814 DAG.getConstant(13, DL, MVT::i32), 6815 DAG.getConstant(0, DL, MVT::i32) 6816 }; 6817 6818 SDValue Cycles32 = DAG.getNode(ISD::INTRINSIC_W_CHAIN, DL, 6819 DAG.getVTList(MVT::i32, MVT::Other), Ops); 6820 Results.push_back(DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, Cycles32, 6821 DAG.getConstant(0, DL, MVT::i32))); 6822 Results.push_back(Cycles32.getValue(1)); 6823 } 6824 6825 SDValue ARMTargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const { 6826 switch (Op.getOpcode()) { 6827 default: llvm_unreachable("Don't know how to custom lower this!"); 6828 case ISD::WRITE_REGISTER: return LowerWRITE_REGISTER(Op, DAG); 6829 case ISD::ConstantPool: return LowerConstantPool(Op, DAG); 6830 case ISD::BlockAddress: return LowerBlockAddress(Op, DAG); 6831 case ISD::GlobalAddress: 6832 switch (Subtarget->getTargetTriple().getObjectFormat()) { 6833 default: llvm_unreachable("unknown object format"); 6834 case Triple::COFF: 6835 return LowerGlobalAddressWindows(Op, DAG); 6836 case Triple::ELF: 6837 return LowerGlobalAddressELF(Op, DAG); 6838 case Triple::MachO: 6839 return LowerGlobalAddressDarwin(Op, DAG); 6840 } 6841 case ISD::GlobalTLSAddress: return LowerGlobalTLSAddress(Op, DAG); 6842 case ISD::SELECT: return LowerSELECT(Op, DAG); 6843 case ISD::SELECT_CC: return LowerSELECT_CC(Op, DAG); 6844 case ISD::BR_CC: return LowerBR_CC(Op, DAG); 6845 case ISD::BR_JT: return LowerBR_JT(Op, DAG); 6846 case ISD::VASTART: return LowerVASTART(Op, DAG); 6847 case ISD::ATOMIC_FENCE: return LowerATOMIC_FENCE(Op, DAG, Subtarget); 6848 case ISD::PREFETCH: return LowerPREFETCH(Op, DAG, Subtarget); 6849 case ISD::SINT_TO_FP: 6850 case ISD::UINT_TO_FP: return LowerINT_TO_FP(Op, DAG); 6851 case ISD::FP_TO_SINT: 6852 case ISD::FP_TO_UINT: return LowerFP_TO_INT(Op, DAG); 6853 case ISD::FCOPYSIGN: return LowerFCOPYSIGN(Op, DAG); 6854 case ISD::RETURNADDR: return LowerRETURNADDR(Op, DAG); 6855 case ISD::FRAMEADDR: return LowerFRAMEADDR(Op, DAG); 6856 case ISD::EH_SJLJ_SETJMP: return LowerEH_SJLJ_SETJMP(Op, DAG); 6857 case ISD::EH_SJLJ_LONGJMP: return LowerEH_SJLJ_LONGJMP(Op, DAG); 6858 case ISD::EH_SJLJ_SETUP_DISPATCH: return LowerEH_SJLJ_SETUP_DISPATCH(Op, DAG); 6859 case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG, 6860 Subtarget); 6861 case ISD::BITCAST: return ExpandBITCAST(Op.getNode(), DAG); 6862 case ISD::SHL: 6863 case ISD::SRL: 6864 case ISD::SRA: return LowerShift(Op.getNode(), DAG, Subtarget); 6865 case ISD::SREM: return LowerREM(Op.getNode(), DAG); 6866 case ISD::UREM: return LowerREM(Op.getNode(), DAG); 6867 case ISD::SHL_PARTS: return LowerShiftLeftParts(Op, DAG); 6868 case ISD::SRL_PARTS: 6869 case ISD::SRA_PARTS: return LowerShiftRightParts(Op, DAG); 6870 case ISD::CTTZ: 6871 case ISD::CTTZ_ZERO_UNDEF: return LowerCTTZ(Op.getNode(), DAG, Subtarget); 6872 case ISD::CTPOP: return LowerCTPOP(Op.getNode(), DAG, Subtarget); 6873 case ISD::SETCC: return LowerVSETCC(Op, DAG); 6874 case ISD::ConstantFP: return LowerConstantFP(Op, DAG, Subtarget); 6875 case ISD::BUILD_VECTOR: return LowerBUILD_VECTOR(Op, DAG, Subtarget); 6876 case ISD::VECTOR_SHUFFLE: return LowerVECTOR_SHUFFLE(Op, DAG); 6877 case ISD::INSERT_VECTOR_ELT: return LowerINSERT_VECTOR_ELT(Op, DAG); 6878 case ISD::EXTRACT_VECTOR_ELT: return LowerEXTRACT_VECTOR_ELT(Op, DAG); 6879 case ISD::CONCAT_VECTORS: return LowerCONCAT_VECTORS(Op, DAG); 6880 case ISD::FLT_ROUNDS_: return LowerFLT_ROUNDS_(Op, DAG); 6881 case ISD::MUL: return LowerMUL(Op, DAG); 6882 case ISD::SDIV: return LowerSDIV(Op, DAG); 6883 case ISD::UDIV: return LowerUDIV(Op, DAG); 6884 case ISD::ADDC: 6885 case ISD::ADDE: 6886 case ISD::SUBC: 6887 case ISD::SUBE: return LowerADDC_ADDE_SUBC_SUBE(Op, DAG); 6888 case ISD::SADDO: 6889 case ISD::UADDO: 6890 case ISD::SSUBO: 6891 case ISD::USUBO: 6892 return LowerXALUO(Op, DAG); 6893 case ISD::ATOMIC_LOAD: 6894 case ISD::ATOMIC_STORE: return LowerAtomicLoadStore(Op, DAG); 6895 case ISD::FSINCOS: return LowerFSINCOS(Op, DAG); 6896 case ISD::SDIVREM: 6897 case ISD::UDIVREM: return LowerDivRem(Op, DAG); 6898 case ISD::DYNAMIC_STACKALLOC: 6899 if (Subtarget->getTargetTriple().isWindowsItaniumEnvironment()) 6900 return LowerDYNAMIC_STACKALLOC(Op, DAG); 6901 llvm_unreachable("Don't know how to custom lower this!"); 6902 case ISD::FP_ROUND: return LowerFP_ROUND(Op, DAG); 6903 case ISD::FP_EXTEND: return LowerFP_EXTEND(Op, DAG); 6904 case ARMISD::WIN__DBZCHK: return SDValue(); 6905 } 6906 } 6907 6908 /// ReplaceNodeResults - Replace the results of node with an illegal result 6909 /// type with new values built out of custom code. 6910 void ARMTargetLowering::ReplaceNodeResults(SDNode *N, 6911 SmallVectorImpl<SDValue> &Results, 6912 SelectionDAG &DAG) const { 6913 SDValue Res; 6914 switch (N->getOpcode()) { 6915 default: 6916 llvm_unreachable("Don't know how to custom expand this!"); 6917 case ISD::READ_REGISTER: 6918 ExpandREAD_REGISTER(N, Results, DAG); 6919 break; 6920 case ISD::BITCAST: 6921 Res = ExpandBITCAST(N, DAG); 6922 break; 6923 case ISD::SRL: 6924 case ISD::SRA: 6925 Res = Expand64BitShift(N, DAG, Subtarget); 6926 break; 6927 case ISD::SREM: 6928 case ISD::UREM: 6929 Res = LowerREM(N, DAG); 6930 break; 6931 case ISD::READCYCLECOUNTER: 6932 ReplaceREADCYCLECOUNTER(N, Results, DAG, Subtarget); 6933 return; 6934 case ISD::UDIV: 6935 case ISD::SDIV: 6936 assert(Subtarget->isTargetWindows() && "can only expand DIV on Windows"); 6937 return ExpandDIV_Windows(SDValue(N, 0), DAG, N->getOpcode() == ISD::SDIV, 6938 Results); 6939 } 6940 if (Res.getNode()) 6941 Results.push_back(Res); 6942 } 6943 6944 //===----------------------------------------------------------------------===// 6945 // ARM Scheduler Hooks 6946 //===----------------------------------------------------------------------===// 6947 6948 /// SetupEntryBlockForSjLj - Insert code into the entry block that creates and 6949 /// registers the function context. 6950 void ARMTargetLowering:: 6951 SetupEntryBlockForSjLj(MachineInstr *MI, MachineBasicBlock *MBB, 6952 MachineBasicBlock *DispatchBB, int FI) const { 6953 const TargetInstrInfo *TII = Subtarget->getInstrInfo(); 6954 DebugLoc dl = MI->getDebugLoc(); 6955 MachineFunction *MF = MBB->getParent(); 6956 MachineRegisterInfo *MRI = &MF->getRegInfo(); 6957 MachineConstantPool *MCP = MF->getConstantPool(); 6958 ARMFunctionInfo *AFI = MF->getInfo<ARMFunctionInfo>(); 6959 const Function *F = MF->getFunction(); 6960 6961 bool isThumb = Subtarget->isThumb(); 6962 bool isThumb2 = Subtarget->isThumb2(); 6963 6964 unsigned PCLabelId = AFI->createPICLabelUId(); 6965 unsigned PCAdj = (isThumb || isThumb2) ? 4 : 8; 6966 ARMConstantPoolValue *CPV = 6967 ARMConstantPoolMBB::Create(F->getContext(), DispatchBB, PCLabelId, PCAdj); 6968 unsigned CPI = MCP->getConstantPoolIndex(CPV, 4); 6969 6970 const TargetRegisterClass *TRC = isThumb ? &ARM::tGPRRegClass 6971 : &ARM::GPRRegClass; 6972 6973 // Grab constant pool and fixed stack memory operands. 6974 MachineMemOperand *CPMMO = 6975 MF->getMachineMemOperand(MachinePointerInfo::getConstantPool(*MF), 6976 MachineMemOperand::MOLoad, 4, 4); 6977 6978 MachineMemOperand *FIMMOSt = 6979 MF->getMachineMemOperand(MachinePointerInfo::getFixedStack(*MF, FI), 6980 MachineMemOperand::MOStore, 4, 4); 6981 6982 // Load the address of the dispatch MBB into the jump buffer. 6983 if (isThumb2) { 6984 // Incoming value: jbuf 6985 // ldr.n r5, LCPI1_1 6986 // orr r5, r5, #1 6987 // add r5, pc 6988 // str r5, [$jbuf, #+4] ; &jbuf[1] 6989 unsigned NewVReg1 = MRI->createVirtualRegister(TRC); 6990 AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::t2LDRpci), NewVReg1) 6991 .addConstantPoolIndex(CPI) 6992 .addMemOperand(CPMMO)); 6993 // Set the low bit because of thumb mode. 6994 unsigned NewVReg2 = MRI->createVirtualRegister(TRC); 6995 AddDefaultCC( 6996 AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::t2ORRri), NewVReg2) 6997 .addReg(NewVReg1, RegState::Kill) 6998 .addImm(0x01))); 6999 unsigned NewVReg3 = MRI->createVirtualRegister(TRC); 7000 BuildMI(*MBB, MI, dl, TII->get(ARM::tPICADD), NewVReg3) 7001 .addReg(NewVReg2, RegState::Kill) 7002 .addImm(PCLabelId); 7003 AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::t2STRi12)) 7004 .addReg(NewVReg3, RegState::Kill) 7005 .addFrameIndex(FI) 7006 .addImm(36) // &jbuf[1] :: pc 7007 .addMemOperand(FIMMOSt)); 7008 } else if (isThumb) { 7009 // Incoming value: jbuf 7010 // ldr.n r1, LCPI1_4 7011 // add r1, pc 7012 // mov r2, #1 7013 // orrs r1, r2 7014 // add r2, $jbuf, #+4 ; &jbuf[1] 7015 // str r1, [r2] 7016 unsigned NewVReg1 = MRI->createVirtualRegister(TRC); 7017 AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::tLDRpci), NewVReg1) 7018 .addConstantPoolIndex(CPI) 7019 .addMemOperand(CPMMO)); 7020 unsigned NewVReg2 = MRI->createVirtualRegister(TRC); 7021 BuildMI(*MBB, MI, dl, TII->get(ARM::tPICADD), NewVReg2) 7022 .addReg(NewVReg1, RegState::Kill) 7023 .addImm(PCLabelId); 7024 // Set the low bit because of thumb mode. 7025 unsigned NewVReg3 = MRI->createVirtualRegister(TRC); 7026 AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::tMOVi8), NewVReg3) 7027 .addReg(ARM::CPSR, RegState::Define) 7028 .addImm(1)); 7029 unsigned NewVReg4 = MRI->createVirtualRegister(TRC); 7030 AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::tORR), NewVReg4) 7031 .addReg(ARM::CPSR, RegState::Define) 7032 .addReg(NewVReg2, RegState::Kill) 7033 .addReg(NewVReg3, RegState::Kill)); 7034 unsigned NewVReg5 = MRI->createVirtualRegister(TRC); 7035 BuildMI(*MBB, MI, dl, TII->get(ARM::tADDframe), NewVReg5) 7036 .addFrameIndex(FI) 7037 .addImm(36); // &jbuf[1] :: pc 7038 AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::tSTRi)) 7039 .addReg(NewVReg4, RegState::Kill) 7040 .addReg(NewVReg5, RegState::Kill) 7041 .addImm(0) 7042 .addMemOperand(FIMMOSt)); 7043 } else { 7044 // Incoming value: jbuf 7045 // ldr r1, LCPI1_1 7046 // add r1, pc, r1 7047 // str r1, [$jbuf, #+4] ; &jbuf[1] 7048 unsigned NewVReg1 = MRI->createVirtualRegister(TRC); 7049 AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::LDRi12), NewVReg1) 7050 .addConstantPoolIndex(CPI) 7051 .addImm(0) 7052 .addMemOperand(CPMMO)); 7053 unsigned NewVReg2 = MRI->createVirtualRegister(TRC); 7054 AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::PICADD), NewVReg2) 7055 .addReg(NewVReg1, RegState::Kill) 7056 .addImm(PCLabelId)); 7057 AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::STRi12)) 7058 .addReg(NewVReg2, RegState::Kill) 7059 .addFrameIndex(FI) 7060 .addImm(36) // &jbuf[1] :: pc 7061 .addMemOperand(FIMMOSt)); 7062 } 7063 } 7064 7065 void ARMTargetLowering::EmitSjLjDispatchBlock(MachineInstr *MI, 7066 MachineBasicBlock *MBB) const { 7067 const TargetInstrInfo *TII = Subtarget->getInstrInfo(); 7068 DebugLoc dl = MI->getDebugLoc(); 7069 MachineFunction *MF = MBB->getParent(); 7070 MachineRegisterInfo *MRI = &MF->getRegInfo(); 7071 MachineFrameInfo *MFI = MF->getFrameInfo(); 7072 int FI = MFI->getFunctionContextIndex(); 7073 7074 const TargetRegisterClass *TRC = Subtarget->isThumb() ? &ARM::tGPRRegClass 7075 : &ARM::GPRnopcRegClass; 7076 7077 // Get a mapping of the call site numbers to all of the landing pads they're 7078 // associated with. 7079 DenseMap<unsigned, SmallVector<MachineBasicBlock*, 2> > CallSiteNumToLPad; 7080 unsigned MaxCSNum = 0; 7081 MachineModuleInfo &MMI = MF->getMMI(); 7082 for (MachineFunction::iterator BB = MF->begin(), E = MF->end(); BB != E; 7083 ++BB) { 7084 if (!BB->isEHPad()) continue; 7085 7086 // FIXME: We should assert that the EH_LABEL is the first MI in the landing 7087 // pad. 7088 for (MachineBasicBlock::iterator 7089 II = BB->begin(), IE = BB->end(); II != IE; ++II) { 7090 if (!II->isEHLabel()) continue; 7091 7092 MCSymbol *Sym = II->getOperand(0).getMCSymbol(); 7093 if (!MMI.hasCallSiteLandingPad(Sym)) continue; 7094 7095 SmallVectorImpl<unsigned> &CallSiteIdxs = MMI.getCallSiteLandingPad(Sym); 7096 for (SmallVectorImpl<unsigned>::iterator 7097 CSI = CallSiteIdxs.begin(), CSE = CallSiteIdxs.end(); 7098 CSI != CSE; ++CSI) { 7099 CallSiteNumToLPad[*CSI].push_back(&*BB); 7100 MaxCSNum = std::max(MaxCSNum, *CSI); 7101 } 7102 break; 7103 } 7104 } 7105 7106 // Get an ordered list of the machine basic blocks for the jump table. 7107 std::vector<MachineBasicBlock*> LPadList; 7108 SmallPtrSet<MachineBasicBlock*, 64> InvokeBBs; 7109 LPadList.reserve(CallSiteNumToLPad.size()); 7110 for (unsigned I = 1; I <= MaxCSNum; ++I) { 7111 SmallVectorImpl<MachineBasicBlock*> &MBBList = CallSiteNumToLPad[I]; 7112 for (SmallVectorImpl<MachineBasicBlock*>::iterator 7113 II = MBBList.begin(), IE = MBBList.end(); II != IE; ++II) { 7114 LPadList.push_back(*II); 7115 InvokeBBs.insert((*II)->pred_begin(), (*II)->pred_end()); 7116 } 7117 } 7118 7119 assert(!LPadList.empty() && 7120 "No landing pad destinations for the dispatch jump table!"); 7121 7122 // Create the jump table and associated information. 7123 MachineJumpTableInfo *JTI = 7124 MF->getOrCreateJumpTableInfo(MachineJumpTableInfo::EK_Inline); 7125 unsigned MJTI = JTI->createJumpTableIndex(LPadList); 7126 Reloc::Model RelocM = getTargetMachine().getRelocationModel(); 7127 7128 // Create the MBBs for the dispatch code. 7129 7130 // Shove the dispatch's address into the return slot in the function context. 7131 MachineBasicBlock *DispatchBB = MF->CreateMachineBasicBlock(); 7132 DispatchBB->setIsEHPad(); 7133 7134 MachineBasicBlock *TrapBB = MF->CreateMachineBasicBlock(); 7135 unsigned trap_opcode; 7136 if (Subtarget->isThumb()) 7137 trap_opcode = ARM::tTRAP; 7138 else 7139 trap_opcode = Subtarget->useNaClTrap() ? ARM::TRAPNaCl : ARM::TRAP; 7140 7141 BuildMI(TrapBB, dl, TII->get(trap_opcode)); 7142 DispatchBB->addSuccessor(TrapBB); 7143 7144 MachineBasicBlock *DispContBB = MF->CreateMachineBasicBlock(); 7145 DispatchBB->addSuccessor(DispContBB); 7146 7147 // Insert and MBBs. 7148 MF->insert(MF->end(), DispatchBB); 7149 MF->insert(MF->end(), DispContBB); 7150 MF->insert(MF->end(), TrapBB); 7151 7152 // Insert code into the entry block that creates and registers the function 7153 // context. 7154 SetupEntryBlockForSjLj(MI, MBB, DispatchBB, FI); 7155 7156 MachineMemOperand *FIMMOLd = MF->getMachineMemOperand( 7157 MachinePointerInfo::getFixedStack(*MF, FI), 7158 MachineMemOperand::MOLoad | MachineMemOperand::MOVolatile, 4, 4); 7159 7160 MachineInstrBuilder MIB; 7161 MIB = BuildMI(DispatchBB, dl, TII->get(ARM::Int_eh_sjlj_dispatchsetup)); 7162 7163 const ARMBaseInstrInfo *AII = static_cast<const ARMBaseInstrInfo*>(TII); 7164 const ARMBaseRegisterInfo &RI = AII->getRegisterInfo(); 7165 7166 // Add a register mask with no preserved registers. This results in all 7167 // registers being marked as clobbered. 7168 MIB.addRegMask(RI.getNoPreservedMask()); 7169 7170 unsigned NumLPads = LPadList.size(); 7171 if (Subtarget->isThumb2()) { 7172 unsigned NewVReg1 = MRI->createVirtualRegister(TRC); 7173 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::t2LDRi12), NewVReg1) 7174 .addFrameIndex(FI) 7175 .addImm(4) 7176 .addMemOperand(FIMMOLd)); 7177 7178 if (NumLPads < 256) { 7179 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::t2CMPri)) 7180 .addReg(NewVReg1) 7181 .addImm(LPadList.size())); 7182 } else { 7183 unsigned VReg1 = MRI->createVirtualRegister(TRC); 7184 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::t2MOVi16), VReg1) 7185 .addImm(NumLPads & 0xFFFF)); 7186 7187 unsigned VReg2 = VReg1; 7188 if ((NumLPads & 0xFFFF0000) != 0) { 7189 VReg2 = MRI->createVirtualRegister(TRC); 7190 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::t2MOVTi16), VReg2) 7191 .addReg(VReg1) 7192 .addImm(NumLPads >> 16)); 7193 } 7194 7195 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::t2CMPrr)) 7196 .addReg(NewVReg1) 7197 .addReg(VReg2)); 7198 } 7199 7200 BuildMI(DispatchBB, dl, TII->get(ARM::t2Bcc)) 7201 .addMBB(TrapBB) 7202 .addImm(ARMCC::HI) 7203 .addReg(ARM::CPSR); 7204 7205 unsigned NewVReg3 = MRI->createVirtualRegister(TRC); 7206 AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::t2LEApcrelJT),NewVReg3) 7207 .addJumpTableIndex(MJTI)); 7208 7209 unsigned NewVReg4 = MRI->createVirtualRegister(TRC); 7210 AddDefaultCC( 7211 AddDefaultPred( 7212 BuildMI(DispContBB, dl, TII->get(ARM::t2ADDrs), NewVReg4) 7213 .addReg(NewVReg3, RegState::Kill) 7214 .addReg(NewVReg1) 7215 .addImm(ARM_AM::getSORegOpc(ARM_AM::lsl, 2)))); 7216 7217 BuildMI(DispContBB, dl, TII->get(ARM::t2BR_JT)) 7218 .addReg(NewVReg4, RegState::Kill) 7219 .addReg(NewVReg1) 7220 .addJumpTableIndex(MJTI); 7221 } else if (Subtarget->isThumb()) { 7222 unsigned NewVReg1 = MRI->createVirtualRegister(TRC); 7223 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::tLDRspi), NewVReg1) 7224 .addFrameIndex(FI) 7225 .addImm(1) 7226 .addMemOperand(FIMMOLd)); 7227 7228 if (NumLPads < 256) { 7229 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::tCMPi8)) 7230 .addReg(NewVReg1) 7231 .addImm(NumLPads)); 7232 } else { 7233 MachineConstantPool *ConstantPool = MF->getConstantPool(); 7234 Type *Int32Ty = Type::getInt32Ty(MF->getFunction()->getContext()); 7235 const Constant *C = ConstantInt::get(Int32Ty, NumLPads); 7236 7237 // MachineConstantPool wants an explicit alignment. 7238 unsigned Align = MF->getDataLayout().getPrefTypeAlignment(Int32Ty); 7239 if (Align == 0) 7240 Align = MF->getDataLayout().getTypeAllocSize(C->getType()); 7241 unsigned Idx = ConstantPool->getConstantPoolIndex(C, Align); 7242 7243 unsigned VReg1 = MRI->createVirtualRegister(TRC); 7244 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::tLDRpci)) 7245 .addReg(VReg1, RegState::Define) 7246 .addConstantPoolIndex(Idx)); 7247 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::tCMPr)) 7248 .addReg(NewVReg1) 7249 .addReg(VReg1)); 7250 } 7251 7252 BuildMI(DispatchBB, dl, TII->get(ARM::tBcc)) 7253 .addMBB(TrapBB) 7254 .addImm(ARMCC::HI) 7255 .addReg(ARM::CPSR); 7256 7257 unsigned NewVReg2 = MRI->createVirtualRegister(TRC); 7258 AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::tLSLri), NewVReg2) 7259 .addReg(ARM::CPSR, RegState::Define) 7260 .addReg(NewVReg1) 7261 .addImm(2)); 7262 7263 unsigned NewVReg3 = MRI->createVirtualRegister(TRC); 7264 AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::tLEApcrelJT), NewVReg3) 7265 .addJumpTableIndex(MJTI)); 7266 7267 unsigned NewVReg4 = MRI->createVirtualRegister(TRC); 7268 AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::tADDrr), NewVReg4) 7269 .addReg(ARM::CPSR, RegState::Define) 7270 .addReg(NewVReg2, RegState::Kill) 7271 .addReg(NewVReg3)); 7272 7273 MachineMemOperand *JTMMOLd = MF->getMachineMemOperand( 7274 MachinePointerInfo::getJumpTable(*MF), MachineMemOperand::MOLoad, 4, 4); 7275 7276 unsigned NewVReg5 = MRI->createVirtualRegister(TRC); 7277 AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::tLDRi), NewVReg5) 7278 .addReg(NewVReg4, RegState::Kill) 7279 .addImm(0) 7280 .addMemOperand(JTMMOLd)); 7281 7282 unsigned NewVReg6 = NewVReg5; 7283 if (RelocM == Reloc::PIC_) { 7284 NewVReg6 = MRI->createVirtualRegister(TRC); 7285 AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::tADDrr), NewVReg6) 7286 .addReg(ARM::CPSR, RegState::Define) 7287 .addReg(NewVReg5, RegState::Kill) 7288 .addReg(NewVReg3)); 7289 } 7290 7291 BuildMI(DispContBB, dl, TII->get(ARM::tBR_JTr)) 7292 .addReg(NewVReg6, RegState::Kill) 7293 .addJumpTableIndex(MJTI); 7294 } else { 7295 unsigned NewVReg1 = MRI->createVirtualRegister(TRC); 7296 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::LDRi12), NewVReg1) 7297 .addFrameIndex(FI) 7298 .addImm(4) 7299 .addMemOperand(FIMMOLd)); 7300 7301 if (NumLPads < 256) { 7302 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::CMPri)) 7303 .addReg(NewVReg1) 7304 .addImm(NumLPads)); 7305 } else if (Subtarget->hasV6T2Ops() && isUInt<16>(NumLPads)) { 7306 unsigned VReg1 = MRI->createVirtualRegister(TRC); 7307 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::MOVi16), VReg1) 7308 .addImm(NumLPads & 0xFFFF)); 7309 7310 unsigned VReg2 = VReg1; 7311 if ((NumLPads & 0xFFFF0000) != 0) { 7312 VReg2 = MRI->createVirtualRegister(TRC); 7313 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::MOVTi16), VReg2) 7314 .addReg(VReg1) 7315 .addImm(NumLPads >> 16)); 7316 } 7317 7318 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::CMPrr)) 7319 .addReg(NewVReg1) 7320 .addReg(VReg2)); 7321 } else { 7322 MachineConstantPool *ConstantPool = MF->getConstantPool(); 7323 Type *Int32Ty = Type::getInt32Ty(MF->getFunction()->getContext()); 7324 const Constant *C = ConstantInt::get(Int32Ty, NumLPads); 7325 7326 // MachineConstantPool wants an explicit alignment. 7327 unsigned Align = MF->getDataLayout().getPrefTypeAlignment(Int32Ty); 7328 if (Align == 0) 7329 Align = MF->getDataLayout().getTypeAllocSize(C->getType()); 7330 unsigned Idx = ConstantPool->getConstantPoolIndex(C, Align); 7331 7332 unsigned VReg1 = MRI->createVirtualRegister(TRC); 7333 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::LDRcp)) 7334 .addReg(VReg1, RegState::Define) 7335 .addConstantPoolIndex(Idx) 7336 .addImm(0)); 7337 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::CMPrr)) 7338 .addReg(NewVReg1) 7339 .addReg(VReg1, RegState::Kill)); 7340 } 7341 7342 BuildMI(DispatchBB, dl, TII->get(ARM::Bcc)) 7343 .addMBB(TrapBB) 7344 .addImm(ARMCC::HI) 7345 .addReg(ARM::CPSR); 7346 7347 unsigned NewVReg3 = MRI->createVirtualRegister(TRC); 7348 AddDefaultCC( 7349 AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::MOVsi), NewVReg3) 7350 .addReg(NewVReg1) 7351 .addImm(ARM_AM::getSORegOpc(ARM_AM::lsl, 2)))); 7352 unsigned NewVReg4 = MRI->createVirtualRegister(TRC); 7353 AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::LEApcrelJT), NewVReg4) 7354 .addJumpTableIndex(MJTI)); 7355 7356 MachineMemOperand *JTMMOLd = MF->getMachineMemOperand( 7357 MachinePointerInfo::getJumpTable(*MF), MachineMemOperand::MOLoad, 4, 4); 7358 unsigned NewVReg5 = MRI->createVirtualRegister(TRC); 7359 AddDefaultPred( 7360 BuildMI(DispContBB, dl, TII->get(ARM::LDRrs), NewVReg5) 7361 .addReg(NewVReg3, RegState::Kill) 7362 .addReg(NewVReg4) 7363 .addImm(0) 7364 .addMemOperand(JTMMOLd)); 7365 7366 if (RelocM == Reloc::PIC_) { 7367 BuildMI(DispContBB, dl, TII->get(ARM::BR_JTadd)) 7368 .addReg(NewVReg5, RegState::Kill) 7369 .addReg(NewVReg4) 7370 .addJumpTableIndex(MJTI); 7371 } else { 7372 BuildMI(DispContBB, dl, TII->get(ARM::BR_JTr)) 7373 .addReg(NewVReg5, RegState::Kill) 7374 .addJumpTableIndex(MJTI); 7375 } 7376 } 7377 7378 // Add the jump table entries as successors to the MBB. 7379 SmallPtrSet<MachineBasicBlock*, 8> SeenMBBs; 7380 for (std::vector<MachineBasicBlock*>::iterator 7381 I = LPadList.begin(), E = LPadList.end(); I != E; ++I) { 7382 MachineBasicBlock *CurMBB = *I; 7383 if (SeenMBBs.insert(CurMBB).second) 7384 DispContBB->addSuccessor(CurMBB); 7385 } 7386 7387 // N.B. the order the invoke BBs are processed in doesn't matter here. 7388 const MCPhysReg *SavedRegs = RI.getCalleeSavedRegs(MF); 7389 SmallVector<MachineBasicBlock*, 64> MBBLPads; 7390 for (MachineBasicBlock *BB : InvokeBBs) { 7391 7392 // Remove the landing pad successor from the invoke block and replace it 7393 // with the new dispatch block. 7394 SmallVector<MachineBasicBlock*, 4> Successors(BB->succ_begin(), 7395 BB->succ_end()); 7396 while (!Successors.empty()) { 7397 MachineBasicBlock *SMBB = Successors.pop_back_val(); 7398 if (SMBB->isEHPad()) { 7399 BB->removeSuccessor(SMBB); 7400 MBBLPads.push_back(SMBB); 7401 } 7402 } 7403 7404 BB->addSuccessor(DispatchBB, BranchProbability::getZero()); 7405 7406 // Find the invoke call and mark all of the callee-saved registers as 7407 // 'implicit defined' so that they're spilled. This prevents code from 7408 // moving instructions to before the EH block, where they will never be 7409 // executed. 7410 for (MachineBasicBlock::reverse_iterator 7411 II = BB->rbegin(), IE = BB->rend(); II != IE; ++II) { 7412 if (!II->isCall()) continue; 7413 7414 DenseMap<unsigned, bool> DefRegs; 7415 for (MachineInstr::mop_iterator 7416 OI = II->operands_begin(), OE = II->operands_end(); 7417 OI != OE; ++OI) { 7418 if (!OI->isReg()) continue; 7419 DefRegs[OI->getReg()] = true; 7420 } 7421 7422 MachineInstrBuilder MIB(*MF, &*II); 7423 7424 for (unsigned i = 0; SavedRegs[i] != 0; ++i) { 7425 unsigned Reg = SavedRegs[i]; 7426 if (Subtarget->isThumb2() && 7427 !ARM::tGPRRegClass.contains(Reg) && 7428 !ARM::hGPRRegClass.contains(Reg)) 7429 continue; 7430 if (Subtarget->isThumb1Only() && !ARM::tGPRRegClass.contains(Reg)) 7431 continue; 7432 if (!Subtarget->isThumb() && !ARM::GPRRegClass.contains(Reg)) 7433 continue; 7434 if (!DefRegs[Reg]) 7435 MIB.addReg(Reg, RegState::ImplicitDefine | RegState::Dead); 7436 } 7437 7438 break; 7439 } 7440 } 7441 7442 // Mark all former landing pads as non-landing pads. The dispatch is the only 7443 // landing pad now. 7444 for (SmallVectorImpl<MachineBasicBlock*>::iterator 7445 I = MBBLPads.begin(), E = MBBLPads.end(); I != E; ++I) 7446 (*I)->setIsEHPad(false); 7447 7448 // The instruction is gone now. 7449 MI->eraseFromParent(); 7450 } 7451 7452 static 7453 MachineBasicBlock *OtherSucc(MachineBasicBlock *MBB, MachineBasicBlock *Succ) { 7454 for (MachineBasicBlock::succ_iterator I = MBB->succ_begin(), 7455 E = MBB->succ_end(); I != E; ++I) 7456 if (*I != Succ) 7457 return *I; 7458 llvm_unreachable("Expecting a BB with two successors!"); 7459 } 7460 7461 /// Return the load opcode for a given load size. If load size >= 8, 7462 /// neon opcode will be returned. 7463 static unsigned getLdOpcode(unsigned LdSize, bool IsThumb1, bool IsThumb2) { 7464 if (LdSize >= 8) 7465 return LdSize == 16 ? ARM::VLD1q32wb_fixed 7466 : LdSize == 8 ? ARM::VLD1d32wb_fixed : 0; 7467 if (IsThumb1) 7468 return LdSize == 4 ? ARM::tLDRi 7469 : LdSize == 2 ? ARM::tLDRHi 7470 : LdSize == 1 ? ARM::tLDRBi : 0; 7471 if (IsThumb2) 7472 return LdSize == 4 ? ARM::t2LDR_POST 7473 : LdSize == 2 ? ARM::t2LDRH_POST 7474 : LdSize == 1 ? ARM::t2LDRB_POST : 0; 7475 return LdSize == 4 ? ARM::LDR_POST_IMM 7476 : LdSize == 2 ? ARM::LDRH_POST 7477 : LdSize == 1 ? ARM::LDRB_POST_IMM : 0; 7478 } 7479 7480 /// Return the store opcode for a given store size. If store size >= 8, 7481 /// neon opcode will be returned. 7482 static unsigned getStOpcode(unsigned StSize, bool IsThumb1, bool IsThumb2) { 7483 if (StSize >= 8) 7484 return StSize == 16 ? ARM::VST1q32wb_fixed 7485 : StSize == 8 ? ARM::VST1d32wb_fixed : 0; 7486 if (IsThumb1) 7487 return StSize == 4 ? ARM::tSTRi 7488 : StSize == 2 ? ARM::tSTRHi 7489 : StSize == 1 ? ARM::tSTRBi : 0; 7490 if (IsThumb2) 7491 return StSize == 4 ? ARM::t2STR_POST 7492 : StSize == 2 ? ARM::t2STRH_POST 7493 : StSize == 1 ? ARM::t2STRB_POST : 0; 7494 return StSize == 4 ? ARM::STR_POST_IMM 7495 : StSize == 2 ? ARM::STRH_POST 7496 : StSize == 1 ? ARM::STRB_POST_IMM : 0; 7497 } 7498 7499 /// Emit a post-increment load operation with given size. The instructions 7500 /// will be added to BB at Pos. 7501 static void emitPostLd(MachineBasicBlock *BB, MachineInstr *Pos, 7502 const TargetInstrInfo *TII, DebugLoc dl, 7503 unsigned LdSize, unsigned Data, unsigned AddrIn, 7504 unsigned AddrOut, bool IsThumb1, bool IsThumb2) { 7505 unsigned LdOpc = getLdOpcode(LdSize, IsThumb1, IsThumb2); 7506 assert(LdOpc != 0 && "Should have a load opcode"); 7507 if (LdSize >= 8) { 7508 AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(LdOpc), Data) 7509 .addReg(AddrOut, RegState::Define).addReg(AddrIn) 7510 .addImm(0)); 7511 } else if (IsThumb1) { 7512 // load + update AddrIn 7513 AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(LdOpc), Data) 7514 .addReg(AddrIn).addImm(0)); 7515 MachineInstrBuilder MIB = 7516 BuildMI(*BB, Pos, dl, TII->get(ARM::tADDi8), AddrOut); 7517 MIB = AddDefaultT1CC(MIB); 7518 MIB.addReg(AddrIn).addImm(LdSize); 7519 AddDefaultPred(MIB); 7520 } else if (IsThumb2) { 7521 AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(LdOpc), Data) 7522 .addReg(AddrOut, RegState::Define).addReg(AddrIn) 7523 .addImm(LdSize)); 7524 } else { // arm 7525 AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(LdOpc), Data) 7526 .addReg(AddrOut, RegState::Define).addReg(AddrIn) 7527 .addReg(0).addImm(LdSize)); 7528 } 7529 } 7530 7531 /// Emit a post-increment store operation with given size. The instructions 7532 /// will be added to BB at Pos. 7533 static void emitPostSt(MachineBasicBlock *BB, MachineInstr *Pos, 7534 const TargetInstrInfo *TII, DebugLoc dl, 7535 unsigned StSize, unsigned Data, unsigned AddrIn, 7536 unsigned AddrOut, bool IsThumb1, bool IsThumb2) { 7537 unsigned StOpc = getStOpcode(StSize, IsThumb1, IsThumb2); 7538 assert(StOpc != 0 && "Should have a store opcode"); 7539 if (StSize >= 8) { 7540 AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(StOpc), AddrOut) 7541 .addReg(AddrIn).addImm(0).addReg(Data)); 7542 } else if (IsThumb1) { 7543 // store + update AddrIn 7544 AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(StOpc)).addReg(Data) 7545 .addReg(AddrIn).addImm(0)); 7546 MachineInstrBuilder MIB = 7547 BuildMI(*BB, Pos, dl, TII->get(ARM::tADDi8), AddrOut); 7548 MIB = AddDefaultT1CC(MIB); 7549 MIB.addReg(AddrIn).addImm(StSize); 7550 AddDefaultPred(MIB); 7551 } else if (IsThumb2) { 7552 AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(StOpc), AddrOut) 7553 .addReg(Data).addReg(AddrIn).addImm(StSize)); 7554 } else { // arm 7555 AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(StOpc), AddrOut) 7556 .addReg(Data).addReg(AddrIn).addReg(0) 7557 .addImm(StSize)); 7558 } 7559 } 7560 7561 MachineBasicBlock * 7562 ARMTargetLowering::EmitStructByval(MachineInstr *MI, 7563 MachineBasicBlock *BB) const { 7564 // This pseudo instruction has 3 operands: dst, src, size 7565 // We expand it to a loop if size > Subtarget->getMaxInlineSizeThreshold(). 7566 // Otherwise, we will generate unrolled scalar copies. 7567 const TargetInstrInfo *TII = Subtarget->getInstrInfo(); 7568 const BasicBlock *LLVM_BB = BB->getBasicBlock(); 7569 MachineFunction::iterator It = ++BB->getIterator(); 7570 7571 unsigned dest = MI->getOperand(0).getReg(); 7572 unsigned src = MI->getOperand(1).getReg(); 7573 unsigned SizeVal = MI->getOperand(2).getImm(); 7574 unsigned Align = MI->getOperand(3).getImm(); 7575 DebugLoc dl = MI->getDebugLoc(); 7576 7577 MachineFunction *MF = BB->getParent(); 7578 MachineRegisterInfo &MRI = MF->getRegInfo(); 7579 unsigned UnitSize = 0; 7580 const TargetRegisterClass *TRC = nullptr; 7581 const TargetRegisterClass *VecTRC = nullptr; 7582 7583 bool IsThumb1 = Subtarget->isThumb1Only(); 7584 bool IsThumb2 = Subtarget->isThumb2(); 7585 7586 if (Align & 1) { 7587 UnitSize = 1; 7588 } else if (Align & 2) { 7589 UnitSize = 2; 7590 } else { 7591 // Check whether we can use NEON instructions. 7592 if (!MF->getFunction()->hasFnAttribute(Attribute::NoImplicitFloat) && 7593 Subtarget->hasNEON()) { 7594 if ((Align % 16 == 0) && SizeVal >= 16) 7595 UnitSize = 16; 7596 else if ((Align % 8 == 0) && SizeVal >= 8) 7597 UnitSize = 8; 7598 } 7599 // Can't use NEON instructions. 7600 if (UnitSize == 0) 7601 UnitSize = 4; 7602 } 7603 7604 // Select the correct opcode and register class for unit size load/store 7605 bool IsNeon = UnitSize >= 8; 7606 TRC = (IsThumb1 || IsThumb2) ? &ARM::tGPRRegClass : &ARM::GPRRegClass; 7607 if (IsNeon) 7608 VecTRC = UnitSize == 16 ? &ARM::DPairRegClass 7609 : UnitSize == 8 ? &ARM::DPRRegClass 7610 : nullptr; 7611 7612 unsigned BytesLeft = SizeVal % UnitSize; 7613 unsigned LoopSize = SizeVal - BytesLeft; 7614 7615 if (SizeVal <= Subtarget->getMaxInlineSizeThreshold()) { 7616 // Use LDR and STR to copy. 7617 // [scratch, srcOut] = LDR_POST(srcIn, UnitSize) 7618 // [destOut] = STR_POST(scratch, destIn, UnitSize) 7619 unsigned srcIn = src; 7620 unsigned destIn = dest; 7621 for (unsigned i = 0; i < LoopSize; i+=UnitSize) { 7622 unsigned srcOut = MRI.createVirtualRegister(TRC); 7623 unsigned destOut = MRI.createVirtualRegister(TRC); 7624 unsigned scratch = MRI.createVirtualRegister(IsNeon ? VecTRC : TRC); 7625 emitPostLd(BB, MI, TII, dl, UnitSize, scratch, srcIn, srcOut, 7626 IsThumb1, IsThumb2); 7627 emitPostSt(BB, MI, TII, dl, UnitSize, scratch, destIn, destOut, 7628 IsThumb1, IsThumb2); 7629 srcIn = srcOut; 7630 destIn = destOut; 7631 } 7632 7633 // Handle the leftover bytes with LDRB and STRB. 7634 // [scratch, srcOut] = LDRB_POST(srcIn, 1) 7635 // [destOut] = STRB_POST(scratch, destIn, 1) 7636 for (unsigned i = 0; i < BytesLeft; i++) { 7637 unsigned srcOut = MRI.createVirtualRegister(TRC); 7638 unsigned destOut = MRI.createVirtualRegister(TRC); 7639 unsigned scratch = MRI.createVirtualRegister(TRC); 7640 emitPostLd(BB, MI, TII, dl, 1, scratch, srcIn, srcOut, 7641 IsThumb1, IsThumb2); 7642 emitPostSt(BB, MI, TII, dl, 1, scratch, destIn, destOut, 7643 IsThumb1, IsThumb2); 7644 srcIn = srcOut; 7645 destIn = destOut; 7646 } 7647 MI->eraseFromParent(); // The instruction is gone now. 7648 return BB; 7649 } 7650 7651 // Expand the pseudo op to a loop. 7652 // thisMBB: 7653 // ... 7654 // movw varEnd, # --> with thumb2 7655 // movt varEnd, # 7656 // ldrcp varEnd, idx --> without thumb2 7657 // fallthrough --> loopMBB 7658 // loopMBB: 7659 // PHI varPhi, varEnd, varLoop 7660 // PHI srcPhi, src, srcLoop 7661 // PHI destPhi, dst, destLoop 7662 // [scratch, srcLoop] = LDR_POST(srcPhi, UnitSize) 7663 // [destLoop] = STR_POST(scratch, destPhi, UnitSize) 7664 // subs varLoop, varPhi, #UnitSize 7665 // bne loopMBB 7666 // fallthrough --> exitMBB 7667 // exitMBB: 7668 // epilogue to handle left-over bytes 7669 // [scratch, srcOut] = LDRB_POST(srcLoop, 1) 7670 // [destOut] = STRB_POST(scratch, destLoop, 1) 7671 MachineBasicBlock *loopMBB = MF->CreateMachineBasicBlock(LLVM_BB); 7672 MachineBasicBlock *exitMBB = MF->CreateMachineBasicBlock(LLVM_BB); 7673 MF->insert(It, loopMBB); 7674 MF->insert(It, exitMBB); 7675 7676 // Transfer the remainder of BB and its successor edges to exitMBB. 7677 exitMBB->splice(exitMBB->begin(), BB, 7678 std::next(MachineBasicBlock::iterator(MI)), BB->end()); 7679 exitMBB->transferSuccessorsAndUpdatePHIs(BB); 7680 7681 // Load an immediate to varEnd. 7682 unsigned varEnd = MRI.createVirtualRegister(TRC); 7683 if (Subtarget->useMovt(*MF)) { 7684 unsigned Vtmp = varEnd; 7685 if ((LoopSize & 0xFFFF0000) != 0) 7686 Vtmp = MRI.createVirtualRegister(TRC); 7687 AddDefaultPred(BuildMI(BB, dl, 7688 TII->get(IsThumb2 ? ARM::t2MOVi16 : ARM::MOVi16), 7689 Vtmp).addImm(LoopSize & 0xFFFF)); 7690 7691 if ((LoopSize & 0xFFFF0000) != 0) 7692 AddDefaultPred(BuildMI(BB, dl, 7693 TII->get(IsThumb2 ? ARM::t2MOVTi16 : ARM::MOVTi16), 7694 varEnd) 7695 .addReg(Vtmp) 7696 .addImm(LoopSize >> 16)); 7697 } else { 7698 MachineConstantPool *ConstantPool = MF->getConstantPool(); 7699 Type *Int32Ty = Type::getInt32Ty(MF->getFunction()->getContext()); 7700 const Constant *C = ConstantInt::get(Int32Ty, LoopSize); 7701 7702 // MachineConstantPool wants an explicit alignment. 7703 unsigned Align = MF->getDataLayout().getPrefTypeAlignment(Int32Ty); 7704 if (Align == 0) 7705 Align = MF->getDataLayout().getTypeAllocSize(C->getType()); 7706 unsigned Idx = ConstantPool->getConstantPoolIndex(C, Align); 7707 7708 if (IsThumb1) 7709 AddDefaultPred(BuildMI(*BB, MI, dl, TII->get(ARM::tLDRpci)).addReg( 7710 varEnd, RegState::Define).addConstantPoolIndex(Idx)); 7711 else 7712 AddDefaultPred(BuildMI(*BB, MI, dl, TII->get(ARM::LDRcp)).addReg( 7713 varEnd, RegState::Define).addConstantPoolIndex(Idx).addImm(0)); 7714 } 7715 BB->addSuccessor(loopMBB); 7716 7717 // Generate the loop body: 7718 // varPhi = PHI(varLoop, varEnd) 7719 // srcPhi = PHI(srcLoop, src) 7720 // destPhi = PHI(destLoop, dst) 7721 MachineBasicBlock *entryBB = BB; 7722 BB = loopMBB; 7723 unsigned varLoop = MRI.createVirtualRegister(TRC); 7724 unsigned varPhi = MRI.createVirtualRegister(TRC); 7725 unsigned srcLoop = MRI.createVirtualRegister(TRC); 7726 unsigned srcPhi = MRI.createVirtualRegister(TRC); 7727 unsigned destLoop = MRI.createVirtualRegister(TRC); 7728 unsigned destPhi = MRI.createVirtualRegister(TRC); 7729 7730 BuildMI(*BB, BB->begin(), dl, TII->get(ARM::PHI), varPhi) 7731 .addReg(varLoop).addMBB(loopMBB) 7732 .addReg(varEnd).addMBB(entryBB); 7733 BuildMI(BB, dl, TII->get(ARM::PHI), srcPhi) 7734 .addReg(srcLoop).addMBB(loopMBB) 7735 .addReg(src).addMBB(entryBB); 7736 BuildMI(BB, dl, TII->get(ARM::PHI), destPhi) 7737 .addReg(destLoop).addMBB(loopMBB) 7738 .addReg(dest).addMBB(entryBB); 7739 7740 // [scratch, srcLoop] = LDR_POST(srcPhi, UnitSize) 7741 // [destLoop] = STR_POST(scratch, destPhi, UnitSiz) 7742 unsigned scratch = MRI.createVirtualRegister(IsNeon ? VecTRC : TRC); 7743 emitPostLd(BB, BB->end(), TII, dl, UnitSize, scratch, srcPhi, srcLoop, 7744 IsThumb1, IsThumb2); 7745 emitPostSt(BB, BB->end(), TII, dl, UnitSize, scratch, destPhi, destLoop, 7746 IsThumb1, IsThumb2); 7747 7748 // Decrement loop variable by UnitSize. 7749 if (IsThumb1) { 7750 MachineInstrBuilder MIB = 7751 BuildMI(*BB, BB->end(), dl, TII->get(ARM::tSUBi8), varLoop); 7752 MIB = AddDefaultT1CC(MIB); 7753 MIB.addReg(varPhi).addImm(UnitSize); 7754 AddDefaultPred(MIB); 7755 } else { 7756 MachineInstrBuilder MIB = 7757 BuildMI(*BB, BB->end(), dl, 7758 TII->get(IsThumb2 ? ARM::t2SUBri : ARM::SUBri), varLoop); 7759 AddDefaultCC(AddDefaultPred(MIB.addReg(varPhi).addImm(UnitSize))); 7760 MIB->getOperand(5).setReg(ARM::CPSR); 7761 MIB->getOperand(5).setIsDef(true); 7762 } 7763 BuildMI(*BB, BB->end(), dl, 7764 TII->get(IsThumb1 ? ARM::tBcc : IsThumb2 ? ARM::t2Bcc : ARM::Bcc)) 7765 .addMBB(loopMBB).addImm(ARMCC::NE).addReg(ARM::CPSR); 7766 7767 // loopMBB can loop back to loopMBB or fall through to exitMBB. 7768 BB->addSuccessor(loopMBB); 7769 BB->addSuccessor(exitMBB); 7770 7771 // Add epilogue to handle BytesLeft. 7772 BB = exitMBB; 7773 MachineInstr *StartOfExit = exitMBB->begin(); 7774 7775 // [scratch, srcOut] = LDRB_POST(srcLoop, 1) 7776 // [destOut] = STRB_POST(scratch, destLoop, 1) 7777 unsigned srcIn = srcLoop; 7778 unsigned destIn = destLoop; 7779 for (unsigned i = 0; i < BytesLeft; i++) { 7780 unsigned srcOut = MRI.createVirtualRegister(TRC); 7781 unsigned destOut = MRI.createVirtualRegister(TRC); 7782 unsigned scratch = MRI.createVirtualRegister(TRC); 7783 emitPostLd(BB, StartOfExit, TII, dl, 1, scratch, srcIn, srcOut, 7784 IsThumb1, IsThumb2); 7785 emitPostSt(BB, StartOfExit, TII, dl, 1, scratch, destIn, destOut, 7786 IsThumb1, IsThumb2); 7787 srcIn = srcOut; 7788 destIn = destOut; 7789 } 7790 7791 MI->eraseFromParent(); // The instruction is gone now. 7792 return BB; 7793 } 7794 7795 MachineBasicBlock * 7796 ARMTargetLowering::EmitLowered__chkstk(MachineInstr *MI, 7797 MachineBasicBlock *MBB) const { 7798 const TargetMachine &TM = getTargetMachine(); 7799 const TargetInstrInfo &TII = *Subtarget->getInstrInfo(); 7800 DebugLoc DL = MI->getDebugLoc(); 7801 7802 assert(Subtarget->isTargetWindows() && 7803 "__chkstk is only supported on Windows"); 7804 assert(Subtarget->isThumb2() && "Windows on ARM requires Thumb-2 mode"); 7805 7806 // __chkstk takes the number of words to allocate on the stack in R4, and 7807 // returns the stack adjustment in number of bytes in R4. This will not 7808 // clober any other registers (other than the obvious lr). 7809 // 7810 // Although, technically, IP should be considered a register which may be 7811 // clobbered, the call itself will not touch it. Windows on ARM is a pure 7812 // thumb-2 environment, so there is no interworking required. As a result, we 7813 // do not expect a veneer to be emitted by the linker, clobbering IP. 7814 // 7815 // Each module receives its own copy of __chkstk, so no import thunk is 7816 // required, again, ensuring that IP is not clobbered. 7817 // 7818 // Finally, although some linkers may theoretically provide a trampoline for 7819 // out of range calls (which is quite common due to a 32M range limitation of 7820 // branches for Thumb), we can generate the long-call version via 7821 // -mcmodel=large, alleviating the need for the trampoline which may clobber 7822 // IP. 7823 7824 switch (TM.getCodeModel()) { 7825 case CodeModel::Small: 7826 case CodeModel::Medium: 7827 case CodeModel::Default: 7828 case CodeModel::Kernel: 7829 BuildMI(*MBB, MI, DL, TII.get(ARM::tBL)) 7830 .addImm((unsigned)ARMCC::AL).addReg(0) 7831 .addExternalSymbol("__chkstk") 7832 .addReg(ARM::R4, RegState::Implicit | RegState::Kill) 7833 .addReg(ARM::R4, RegState::Implicit | RegState::Define) 7834 .addReg(ARM::R12, RegState::Implicit | RegState::Define | RegState::Dead); 7835 break; 7836 case CodeModel::Large: 7837 case CodeModel::JITDefault: { 7838 MachineRegisterInfo &MRI = MBB->getParent()->getRegInfo(); 7839 unsigned Reg = MRI.createVirtualRegister(&ARM::rGPRRegClass); 7840 7841 BuildMI(*MBB, MI, DL, TII.get(ARM::t2MOVi32imm), Reg) 7842 .addExternalSymbol("__chkstk"); 7843 BuildMI(*MBB, MI, DL, TII.get(ARM::tBLXr)) 7844 .addImm((unsigned)ARMCC::AL).addReg(0) 7845 .addReg(Reg, RegState::Kill) 7846 .addReg(ARM::R4, RegState::Implicit | RegState::Kill) 7847 .addReg(ARM::R4, RegState::Implicit | RegState::Define) 7848 .addReg(ARM::R12, RegState::Implicit | RegState::Define | RegState::Dead); 7849 break; 7850 } 7851 } 7852 7853 AddDefaultCC(AddDefaultPred(BuildMI(*MBB, MI, DL, TII.get(ARM::t2SUBrr), 7854 ARM::SP) 7855 .addReg(ARM::SP).addReg(ARM::R4))); 7856 7857 MI->eraseFromParent(); 7858 return MBB; 7859 } 7860 7861 MachineBasicBlock * 7862 ARMTargetLowering::EmitLowered__dbzchk(MachineInstr *MI, 7863 MachineBasicBlock *MBB) const { 7864 DebugLoc DL = MI->getDebugLoc(); 7865 MachineFunction *MF = MBB->getParent(); 7866 const TargetInstrInfo *TII = Subtarget->getInstrInfo(); 7867 7868 MachineBasicBlock *ContBB = MF->CreateMachineBasicBlock(); 7869 MF->push_back(ContBB); 7870 ContBB->splice(ContBB->begin(), MBB, 7871 std::next(MachineBasicBlock::iterator(MI)), MBB->end()); 7872 MBB->addSuccessor(ContBB); 7873 7874 MachineBasicBlock *TrapBB = MF->CreateMachineBasicBlock(); 7875 MF->push_back(TrapBB); 7876 BuildMI(TrapBB, DL, TII->get(ARM::t2UDF)).addImm(249); 7877 MBB->addSuccessor(TrapBB); 7878 7879 BuildMI(*MBB, MI, DL, TII->get(ARM::tCBZ)) 7880 .addReg(MI->getOperand(0).getReg()) 7881 .addMBB(TrapBB); 7882 7883 MI->eraseFromParent(); 7884 return ContBB; 7885 } 7886 7887 MachineBasicBlock * 7888 ARMTargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI, 7889 MachineBasicBlock *BB) const { 7890 const TargetInstrInfo *TII = Subtarget->getInstrInfo(); 7891 DebugLoc dl = MI->getDebugLoc(); 7892 bool isThumb2 = Subtarget->isThumb2(); 7893 switch (MI->getOpcode()) { 7894 default: { 7895 MI->dump(); 7896 llvm_unreachable("Unexpected instr type to insert"); 7897 } 7898 // The Thumb2 pre-indexed stores have the same MI operands, they just 7899 // define them differently in the .td files from the isel patterns, so 7900 // they need pseudos. 7901 case ARM::t2STR_preidx: 7902 MI->setDesc(TII->get(ARM::t2STR_PRE)); 7903 return BB; 7904 case ARM::t2STRB_preidx: 7905 MI->setDesc(TII->get(ARM::t2STRB_PRE)); 7906 return BB; 7907 case ARM::t2STRH_preidx: 7908 MI->setDesc(TII->get(ARM::t2STRH_PRE)); 7909 return BB; 7910 7911 case ARM::STRi_preidx: 7912 case ARM::STRBi_preidx: { 7913 unsigned NewOpc = MI->getOpcode() == ARM::STRi_preidx ? 7914 ARM::STR_PRE_IMM : ARM::STRB_PRE_IMM; 7915 // Decode the offset. 7916 unsigned Offset = MI->getOperand(4).getImm(); 7917 bool isSub = ARM_AM::getAM2Op(Offset) == ARM_AM::sub; 7918 Offset = ARM_AM::getAM2Offset(Offset); 7919 if (isSub) 7920 Offset = -Offset; 7921 7922 MachineMemOperand *MMO = *MI->memoperands_begin(); 7923 BuildMI(*BB, MI, dl, TII->get(NewOpc)) 7924 .addOperand(MI->getOperand(0)) // Rn_wb 7925 .addOperand(MI->getOperand(1)) // Rt 7926 .addOperand(MI->getOperand(2)) // Rn 7927 .addImm(Offset) // offset (skip GPR==zero_reg) 7928 .addOperand(MI->getOperand(5)) // pred 7929 .addOperand(MI->getOperand(6)) 7930 .addMemOperand(MMO); 7931 MI->eraseFromParent(); 7932 return BB; 7933 } 7934 case ARM::STRr_preidx: 7935 case ARM::STRBr_preidx: 7936 case ARM::STRH_preidx: { 7937 unsigned NewOpc; 7938 switch (MI->getOpcode()) { 7939 default: llvm_unreachable("unexpected opcode!"); 7940 case ARM::STRr_preidx: NewOpc = ARM::STR_PRE_REG; break; 7941 case ARM::STRBr_preidx: NewOpc = ARM::STRB_PRE_REG; break; 7942 case ARM::STRH_preidx: NewOpc = ARM::STRH_PRE; break; 7943 } 7944 MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(NewOpc)); 7945 for (unsigned i = 0; i < MI->getNumOperands(); ++i) 7946 MIB.addOperand(MI->getOperand(i)); 7947 MI->eraseFromParent(); 7948 return BB; 7949 } 7950 7951 case ARM::tMOVCCr_pseudo: { 7952 // To "insert" a SELECT_CC instruction, we actually have to insert the 7953 // diamond control-flow pattern. The incoming instruction knows the 7954 // destination vreg to set, the condition code register to branch on, the 7955 // true/false values to select between, and a branch opcode to use. 7956 const BasicBlock *LLVM_BB = BB->getBasicBlock(); 7957 MachineFunction::iterator It = ++BB->getIterator(); 7958 7959 // thisMBB: 7960 // ... 7961 // TrueVal = ... 7962 // cmpTY ccX, r1, r2 7963 // bCC copy1MBB 7964 // fallthrough --> copy0MBB 7965 MachineBasicBlock *thisMBB = BB; 7966 MachineFunction *F = BB->getParent(); 7967 MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB); 7968 MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB); 7969 F->insert(It, copy0MBB); 7970 F->insert(It, sinkMBB); 7971 7972 // Transfer the remainder of BB and its successor edges to sinkMBB. 7973 sinkMBB->splice(sinkMBB->begin(), BB, 7974 std::next(MachineBasicBlock::iterator(MI)), BB->end()); 7975 sinkMBB->transferSuccessorsAndUpdatePHIs(BB); 7976 7977 BB->addSuccessor(copy0MBB); 7978 BB->addSuccessor(sinkMBB); 7979 7980 BuildMI(BB, dl, TII->get(ARM::tBcc)).addMBB(sinkMBB) 7981 .addImm(MI->getOperand(3).getImm()).addReg(MI->getOperand(4).getReg()); 7982 7983 // copy0MBB: 7984 // %FalseValue = ... 7985 // # fallthrough to sinkMBB 7986 BB = copy0MBB; 7987 7988 // Update machine-CFG edges 7989 BB->addSuccessor(sinkMBB); 7990 7991 // sinkMBB: 7992 // %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ] 7993 // ... 7994 BB = sinkMBB; 7995 BuildMI(*BB, BB->begin(), dl, 7996 TII->get(ARM::PHI), MI->getOperand(0).getReg()) 7997 .addReg(MI->getOperand(1).getReg()).addMBB(copy0MBB) 7998 .addReg(MI->getOperand(2).getReg()).addMBB(thisMBB); 7999 8000 MI->eraseFromParent(); // The pseudo instruction is gone now. 8001 return BB; 8002 } 8003 8004 case ARM::BCCi64: 8005 case ARM::BCCZi64: { 8006 // If there is an unconditional branch to the other successor, remove it. 8007 BB->erase(std::next(MachineBasicBlock::iterator(MI)), BB->end()); 8008 8009 // Compare both parts that make up the double comparison separately for 8010 // equality. 8011 bool RHSisZero = MI->getOpcode() == ARM::BCCZi64; 8012 8013 unsigned LHS1 = MI->getOperand(1).getReg(); 8014 unsigned LHS2 = MI->getOperand(2).getReg(); 8015 if (RHSisZero) { 8016 AddDefaultPred(BuildMI(BB, dl, 8017 TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri)) 8018 .addReg(LHS1).addImm(0)); 8019 BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri)) 8020 .addReg(LHS2).addImm(0) 8021 .addImm(ARMCC::EQ).addReg(ARM::CPSR); 8022 } else { 8023 unsigned RHS1 = MI->getOperand(3).getReg(); 8024 unsigned RHS2 = MI->getOperand(4).getReg(); 8025 AddDefaultPred(BuildMI(BB, dl, 8026 TII->get(isThumb2 ? ARM::t2CMPrr : ARM::CMPrr)) 8027 .addReg(LHS1).addReg(RHS1)); 8028 BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPrr : ARM::CMPrr)) 8029 .addReg(LHS2).addReg(RHS2) 8030 .addImm(ARMCC::EQ).addReg(ARM::CPSR); 8031 } 8032 8033 MachineBasicBlock *destMBB = MI->getOperand(RHSisZero ? 3 : 5).getMBB(); 8034 MachineBasicBlock *exitMBB = OtherSucc(BB, destMBB); 8035 if (MI->getOperand(0).getImm() == ARMCC::NE) 8036 std::swap(destMBB, exitMBB); 8037 8038 BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc)) 8039 .addMBB(destMBB).addImm(ARMCC::EQ).addReg(ARM::CPSR); 8040 if (isThumb2) 8041 AddDefaultPred(BuildMI(BB, dl, TII->get(ARM::t2B)).addMBB(exitMBB)); 8042 else 8043 BuildMI(BB, dl, TII->get(ARM::B)) .addMBB(exitMBB); 8044 8045 MI->eraseFromParent(); // The pseudo instruction is gone now. 8046 return BB; 8047 } 8048 8049 case ARM::Int_eh_sjlj_setjmp: 8050 case ARM::Int_eh_sjlj_setjmp_nofp: 8051 case ARM::tInt_eh_sjlj_setjmp: 8052 case ARM::t2Int_eh_sjlj_setjmp: 8053 case ARM::t2Int_eh_sjlj_setjmp_nofp: 8054 return BB; 8055 8056 case ARM::Int_eh_sjlj_setup_dispatch: 8057 EmitSjLjDispatchBlock(MI, BB); 8058 return BB; 8059 8060 case ARM::ABS: 8061 case ARM::t2ABS: { 8062 // To insert an ABS instruction, we have to insert the 8063 // diamond control-flow pattern. The incoming instruction knows the 8064 // source vreg to test against 0, the destination vreg to set, 8065 // the condition code register to branch on, the 8066 // true/false values to select between, and a branch opcode to use. 8067 // It transforms 8068 // V1 = ABS V0 8069 // into 8070 // V2 = MOVS V0 8071 // BCC (branch to SinkBB if V0 >= 0) 8072 // RSBBB: V3 = RSBri V2, 0 (compute ABS if V2 < 0) 8073 // SinkBB: V1 = PHI(V2, V3) 8074 const BasicBlock *LLVM_BB = BB->getBasicBlock(); 8075 MachineFunction::iterator BBI = ++BB->getIterator(); 8076 MachineFunction *Fn = BB->getParent(); 8077 MachineBasicBlock *RSBBB = Fn->CreateMachineBasicBlock(LLVM_BB); 8078 MachineBasicBlock *SinkBB = Fn->CreateMachineBasicBlock(LLVM_BB); 8079 Fn->insert(BBI, RSBBB); 8080 Fn->insert(BBI, SinkBB); 8081 8082 unsigned int ABSSrcReg = MI->getOperand(1).getReg(); 8083 unsigned int ABSDstReg = MI->getOperand(0).getReg(); 8084 bool ABSSrcKIll = MI->getOperand(1).isKill(); 8085 bool isThumb2 = Subtarget->isThumb2(); 8086 MachineRegisterInfo &MRI = Fn->getRegInfo(); 8087 // In Thumb mode S must not be specified if source register is the SP or 8088 // PC and if destination register is the SP, so restrict register class 8089 unsigned NewRsbDstReg = 8090 MRI.createVirtualRegister(isThumb2 ? &ARM::rGPRRegClass : &ARM::GPRRegClass); 8091 8092 // Transfer the remainder of BB and its successor edges to sinkMBB. 8093 SinkBB->splice(SinkBB->begin(), BB, 8094 std::next(MachineBasicBlock::iterator(MI)), BB->end()); 8095 SinkBB->transferSuccessorsAndUpdatePHIs(BB); 8096 8097 BB->addSuccessor(RSBBB); 8098 BB->addSuccessor(SinkBB); 8099 8100 // fall through to SinkMBB 8101 RSBBB->addSuccessor(SinkBB); 8102 8103 // insert a cmp at the end of BB 8104 AddDefaultPred(BuildMI(BB, dl, 8105 TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri)) 8106 .addReg(ABSSrcReg).addImm(0)); 8107 8108 // insert a bcc with opposite CC to ARMCC::MI at the end of BB 8109 BuildMI(BB, dl, 8110 TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc)).addMBB(SinkBB) 8111 .addImm(ARMCC::getOppositeCondition(ARMCC::MI)).addReg(ARM::CPSR); 8112 8113 // insert rsbri in RSBBB 8114 // Note: BCC and rsbri will be converted into predicated rsbmi 8115 // by if-conversion pass 8116 BuildMI(*RSBBB, RSBBB->begin(), dl, 8117 TII->get(isThumb2 ? ARM::t2RSBri : ARM::RSBri), NewRsbDstReg) 8118 .addReg(ABSSrcReg, ABSSrcKIll ? RegState::Kill : 0) 8119 .addImm(0).addImm((unsigned)ARMCC::AL).addReg(0).addReg(0); 8120 8121 // insert PHI in SinkBB, 8122 // reuse ABSDstReg to not change uses of ABS instruction 8123 BuildMI(*SinkBB, SinkBB->begin(), dl, 8124 TII->get(ARM::PHI), ABSDstReg) 8125 .addReg(NewRsbDstReg).addMBB(RSBBB) 8126 .addReg(ABSSrcReg).addMBB(BB); 8127 8128 // remove ABS instruction 8129 MI->eraseFromParent(); 8130 8131 // return last added BB 8132 return SinkBB; 8133 } 8134 case ARM::COPY_STRUCT_BYVAL_I32: 8135 ++NumLoopByVals; 8136 return EmitStructByval(MI, BB); 8137 case ARM::WIN__CHKSTK: 8138 return EmitLowered__chkstk(MI, BB); 8139 case ARM::WIN__DBZCHK: 8140 return EmitLowered__dbzchk(MI, BB); 8141 } 8142 } 8143 8144 /// \brief Attaches vregs to MEMCPY that it will use as scratch registers 8145 /// when it is expanded into LDM/STM. This is done as a post-isel lowering 8146 /// instead of as a custom inserter because we need the use list from the SDNode. 8147 static void attachMEMCPYScratchRegs(const ARMSubtarget *Subtarget, 8148 MachineInstr *MI, const SDNode *Node) { 8149 bool isThumb1 = Subtarget->isThumb1Only(); 8150 8151 DebugLoc DL = MI->getDebugLoc(); 8152 MachineFunction *MF = MI->getParent()->getParent(); 8153 MachineRegisterInfo &MRI = MF->getRegInfo(); 8154 MachineInstrBuilder MIB(*MF, MI); 8155 8156 // If the new dst/src is unused mark it as dead. 8157 if (!Node->hasAnyUseOfValue(0)) { 8158 MI->getOperand(0).setIsDead(true); 8159 } 8160 if (!Node->hasAnyUseOfValue(1)) { 8161 MI->getOperand(1).setIsDead(true); 8162 } 8163 8164 // The MEMCPY both defines and kills the scratch registers. 8165 for (unsigned I = 0; I != MI->getOperand(4).getImm(); ++I) { 8166 unsigned TmpReg = MRI.createVirtualRegister(isThumb1 ? &ARM::tGPRRegClass 8167 : &ARM::GPRRegClass); 8168 MIB.addReg(TmpReg, RegState::Define|RegState::Dead); 8169 } 8170 } 8171 8172 void ARMTargetLowering::AdjustInstrPostInstrSelection(MachineInstr *MI, 8173 SDNode *Node) const { 8174 if (MI->getOpcode() == ARM::MEMCPY) { 8175 attachMEMCPYScratchRegs(Subtarget, MI, Node); 8176 return; 8177 } 8178 8179 const MCInstrDesc *MCID = &MI->getDesc(); 8180 // Adjust potentially 's' setting instructions after isel, i.e. ADC, SBC, RSB, 8181 // RSC. Coming out of isel, they have an implicit CPSR def, but the optional 8182 // operand is still set to noreg. If needed, set the optional operand's 8183 // register to CPSR, and remove the redundant implicit def. 8184 // 8185 // e.g. ADCS (..., CPSR<imp-def>) -> ADC (... opt:CPSR<def>). 8186 8187 // Rename pseudo opcodes. 8188 unsigned NewOpc = convertAddSubFlagsOpcode(MI->getOpcode()); 8189 if (NewOpc) { 8190 const ARMBaseInstrInfo *TII = Subtarget->getInstrInfo(); 8191 MCID = &TII->get(NewOpc); 8192 8193 assert(MCID->getNumOperands() == MI->getDesc().getNumOperands() + 1 && 8194 "converted opcode should be the same except for cc_out"); 8195 8196 MI->setDesc(*MCID); 8197 8198 // Add the optional cc_out operand 8199 MI->addOperand(MachineOperand::CreateReg(0, /*isDef=*/true)); 8200 } 8201 unsigned ccOutIdx = MCID->getNumOperands() - 1; 8202 8203 // Any ARM instruction that sets the 's' bit should specify an optional 8204 // "cc_out" operand in the last operand position. 8205 if (!MI->hasOptionalDef() || !MCID->OpInfo[ccOutIdx].isOptionalDef()) { 8206 assert(!NewOpc && "Optional cc_out operand required"); 8207 return; 8208 } 8209 // Look for an implicit def of CPSR added by MachineInstr ctor. Remove it 8210 // since we already have an optional CPSR def. 8211 bool definesCPSR = false; 8212 bool deadCPSR = false; 8213 for (unsigned i = MCID->getNumOperands(), e = MI->getNumOperands(); 8214 i != e; ++i) { 8215 const MachineOperand &MO = MI->getOperand(i); 8216 if (MO.isReg() && MO.isDef() && MO.getReg() == ARM::CPSR) { 8217 definesCPSR = true; 8218 if (MO.isDead()) 8219 deadCPSR = true; 8220 MI->RemoveOperand(i); 8221 break; 8222 } 8223 } 8224 if (!definesCPSR) { 8225 assert(!NewOpc && "Optional cc_out operand required"); 8226 return; 8227 } 8228 assert(deadCPSR == !Node->hasAnyUseOfValue(1) && "inconsistent dead flag"); 8229 if (deadCPSR) { 8230 assert(!MI->getOperand(ccOutIdx).getReg() && 8231 "expect uninitialized optional cc_out operand"); 8232 return; 8233 } 8234 8235 // If this instruction was defined with an optional CPSR def and its dag node 8236 // had a live implicit CPSR def, then activate the optional CPSR def. 8237 MachineOperand &MO = MI->getOperand(ccOutIdx); 8238 MO.setReg(ARM::CPSR); 8239 MO.setIsDef(true); 8240 } 8241 8242 //===----------------------------------------------------------------------===// 8243 // ARM Optimization Hooks 8244 //===----------------------------------------------------------------------===// 8245 8246 // Helper function that checks if N is a null or all ones constant. 8247 static inline bool isZeroOrAllOnes(SDValue N, bool AllOnes) { 8248 return AllOnes ? isAllOnesConstant(N) : isNullConstant(N); 8249 } 8250 8251 // Return true if N is conditionally 0 or all ones. 8252 // Detects these expressions where cc is an i1 value: 8253 // 8254 // (select cc 0, y) [AllOnes=0] 8255 // (select cc y, 0) [AllOnes=0] 8256 // (zext cc) [AllOnes=0] 8257 // (sext cc) [AllOnes=0/1] 8258 // (select cc -1, y) [AllOnes=1] 8259 // (select cc y, -1) [AllOnes=1] 8260 // 8261 // Invert is set when N is the null/all ones constant when CC is false. 8262 // OtherOp is set to the alternative value of N. 8263 static bool isConditionalZeroOrAllOnes(SDNode *N, bool AllOnes, 8264 SDValue &CC, bool &Invert, 8265 SDValue &OtherOp, 8266 SelectionDAG &DAG) { 8267 switch (N->getOpcode()) { 8268 default: return false; 8269 case ISD::SELECT: { 8270 CC = N->getOperand(0); 8271 SDValue N1 = N->getOperand(1); 8272 SDValue N2 = N->getOperand(2); 8273 if (isZeroOrAllOnes(N1, AllOnes)) { 8274 Invert = false; 8275 OtherOp = N2; 8276 return true; 8277 } 8278 if (isZeroOrAllOnes(N2, AllOnes)) { 8279 Invert = true; 8280 OtherOp = N1; 8281 return true; 8282 } 8283 return false; 8284 } 8285 case ISD::ZERO_EXTEND: 8286 // (zext cc) can never be the all ones value. 8287 if (AllOnes) 8288 return false; 8289 // Fall through. 8290 case ISD::SIGN_EXTEND: { 8291 SDLoc dl(N); 8292 EVT VT = N->getValueType(0); 8293 CC = N->getOperand(0); 8294 if (CC.getValueType() != MVT::i1) 8295 return false; 8296 Invert = !AllOnes; 8297 if (AllOnes) 8298 // When looking for an AllOnes constant, N is an sext, and the 'other' 8299 // value is 0. 8300 OtherOp = DAG.getConstant(0, dl, VT); 8301 else if (N->getOpcode() == ISD::ZERO_EXTEND) 8302 // When looking for a 0 constant, N can be zext or sext. 8303 OtherOp = DAG.getConstant(1, dl, VT); 8304 else 8305 OtherOp = DAG.getConstant(APInt::getAllOnesValue(VT.getSizeInBits()), dl, 8306 VT); 8307 return true; 8308 } 8309 } 8310 } 8311 8312 // Combine a constant select operand into its use: 8313 // 8314 // (add (select cc, 0, c), x) -> (select cc, x, (add, x, c)) 8315 // (sub x, (select cc, 0, c)) -> (select cc, x, (sub, x, c)) 8316 // (and (select cc, -1, c), x) -> (select cc, x, (and, x, c)) [AllOnes=1] 8317 // (or (select cc, 0, c), x) -> (select cc, x, (or, x, c)) 8318 // (xor (select cc, 0, c), x) -> (select cc, x, (xor, x, c)) 8319 // 8320 // The transform is rejected if the select doesn't have a constant operand that 8321 // is null, or all ones when AllOnes is set. 8322 // 8323 // Also recognize sext/zext from i1: 8324 // 8325 // (add (zext cc), x) -> (select cc (add x, 1), x) 8326 // (add (sext cc), x) -> (select cc (add x, -1), x) 8327 // 8328 // These transformations eventually create predicated instructions. 8329 // 8330 // @param N The node to transform. 8331 // @param Slct The N operand that is a select. 8332 // @param OtherOp The other N operand (x above). 8333 // @param DCI Context. 8334 // @param AllOnes Require the select constant to be all ones instead of null. 8335 // @returns The new node, or SDValue() on failure. 8336 static 8337 SDValue combineSelectAndUse(SDNode *N, SDValue Slct, SDValue OtherOp, 8338 TargetLowering::DAGCombinerInfo &DCI, 8339 bool AllOnes = false) { 8340 SelectionDAG &DAG = DCI.DAG; 8341 EVT VT = N->getValueType(0); 8342 SDValue NonConstantVal; 8343 SDValue CCOp; 8344 bool SwapSelectOps; 8345 if (!isConditionalZeroOrAllOnes(Slct.getNode(), AllOnes, CCOp, SwapSelectOps, 8346 NonConstantVal, DAG)) 8347 return SDValue(); 8348 8349 // Slct is now know to be the desired identity constant when CC is true. 8350 SDValue TrueVal = OtherOp; 8351 SDValue FalseVal = DAG.getNode(N->getOpcode(), SDLoc(N), VT, 8352 OtherOp, NonConstantVal); 8353 // Unless SwapSelectOps says CC should be false. 8354 if (SwapSelectOps) 8355 std::swap(TrueVal, FalseVal); 8356 8357 return DAG.getNode(ISD::SELECT, SDLoc(N), VT, 8358 CCOp, TrueVal, FalseVal); 8359 } 8360 8361 // Attempt combineSelectAndUse on each operand of a commutative operator N. 8362 static 8363 SDValue combineSelectAndUseCommutative(SDNode *N, bool AllOnes, 8364 TargetLowering::DAGCombinerInfo &DCI) { 8365 SDValue N0 = N->getOperand(0); 8366 SDValue N1 = N->getOperand(1); 8367 if (N0.getNode()->hasOneUse()) { 8368 SDValue Result = combineSelectAndUse(N, N0, N1, DCI, AllOnes); 8369 if (Result.getNode()) 8370 return Result; 8371 } 8372 if (N1.getNode()->hasOneUse()) { 8373 SDValue Result = combineSelectAndUse(N, N1, N0, DCI, AllOnes); 8374 if (Result.getNode()) 8375 return Result; 8376 } 8377 return SDValue(); 8378 } 8379 8380 // AddCombineToVPADDL- For pair-wise add on neon, use the vpaddl instruction 8381 // (only after legalization). 8382 static SDValue AddCombineToVPADDL(SDNode *N, SDValue N0, SDValue N1, 8383 TargetLowering::DAGCombinerInfo &DCI, 8384 const ARMSubtarget *Subtarget) { 8385 8386 // Only perform optimization if after legalize, and if NEON is available. We 8387 // also expected both operands to be BUILD_VECTORs. 8388 if (DCI.isBeforeLegalize() || !Subtarget->hasNEON() 8389 || N0.getOpcode() != ISD::BUILD_VECTOR 8390 || N1.getOpcode() != ISD::BUILD_VECTOR) 8391 return SDValue(); 8392 8393 // Check output type since VPADDL operand elements can only be 8, 16, or 32. 8394 EVT VT = N->getValueType(0); 8395 if (!VT.isInteger() || VT.getVectorElementType() == MVT::i64) 8396 return SDValue(); 8397 8398 // Check that the vector operands are of the right form. 8399 // N0 and N1 are BUILD_VECTOR nodes with N number of EXTRACT_VECTOR 8400 // operands, where N is the size of the formed vector. 8401 // Each EXTRACT_VECTOR should have the same input vector and odd or even 8402 // index such that we have a pair wise add pattern. 8403 8404 // Grab the vector that all EXTRACT_VECTOR nodes should be referencing. 8405 if (N0->getOperand(0)->getOpcode() != ISD::EXTRACT_VECTOR_ELT) 8406 return SDValue(); 8407 SDValue Vec = N0->getOperand(0)->getOperand(0); 8408 SDNode *V = Vec.getNode(); 8409 unsigned nextIndex = 0; 8410 8411 // For each operands to the ADD which are BUILD_VECTORs, 8412 // check to see if each of their operands are an EXTRACT_VECTOR with 8413 // the same vector and appropriate index. 8414 for (unsigned i = 0, e = N0->getNumOperands(); i != e; ++i) { 8415 if (N0->getOperand(i)->getOpcode() == ISD::EXTRACT_VECTOR_ELT 8416 && N1->getOperand(i)->getOpcode() == ISD::EXTRACT_VECTOR_ELT) { 8417 8418 SDValue ExtVec0 = N0->getOperand(i); 8419 SDValue ExtVec1 = N1->getOperand(i); 8420 8421 // First operand is the vector, verify its the same. 8422 if (V != ExtVec0->getOperand(0).getNode() || 8423 V != ExtVec1->getOperand(0).getNode()) 8424 return SDValue(); 8425 8426 // Second is the constant, verify its correct. 8427 ConstantSDNode *C0 = dyn_cast<ConstantSDNode>(ExtVec0->getOperand(1)); 8428 ConstantSDNode *C1 = dyn_cast<ConstantSDNode>(ExtVec1->getOperand(1)); 8429 8430 // For the constant, we want to see all the even or all the odd. 8431 if (!C0 || !C1 || C0->getZExtValue() != nextIndex 8432 || C1->getZExtValue() != nextIndex+1) 8433 return SDValue(); 8434 8435 // Increment index. 8436 nextIndex+=2; 8437 } else 8438 return SDValue(); 8439 } 8440 8441 // Create VPADDL node. 8442 SelectionDAG &DAG = DCI.DAG; 8443 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 8444 8445 SDLoc dl(N); 8446 8447 // Build operand list. 8448 SmallVector<SDValue, 8> Ops; 8449 Ops.push_back(DAG.getConstant(Intrinsic::arm_neon_vpaddls, dl, 8450 TLI.getPointerTy(DAG.getDataLayout()))); 8451 8452 // Input is the vector. 8453 Ops.push_back(Vec); 8454 8455 // Get widened type and narrowed type. 8456 MVT widenType; 8457 unsigned numElem = VT.getVectorNumElements(); 8458 8459 EVT inputLaneType = Vec.getValueType().getVectorElementType(); 8460 switch (inputLaneType.getSimpleVT().SimpleTy) { 8461 case MVT::i8: widenType = MVT::getVectorVT(MVT::i16, numElem); break; 8462 case MVT::i16: widenType = MVT::getVectorVT(MVT::i32, numElem); break; 8463 case MVT::i32: widenType = MVT::getVectorVT(MVT::i64, numElem); break; 8464 default: 8465 llvm_unreachable("Invalid vector element type for padd optimization."); 8466 } 8467 8468 SDValue tmp = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, widenType, Ops); 8469 unsigned ExtOp = VT.bitsGT(tmp.getValueType()) ? ISD::ANY_EXTEND : ISD::TRUNCATE; 8470 return DAG.getNode(ExtOp, dl, VT, tmp); 8471 } 8472 8473 static SDValue findMUL_LOHI(SDValue V) { 8474 if (V->getOpcode() == ISD::UMUL_LOHI || 8475 V->getOpcode() == ISD::SMUL_LOHI) 8476 return V; 8477 return SDValue(); 8478 } 8479 8480 static SDValue AddCombineTo64bitMLAL(SDNode *AddcNode, 8481 TargetLowering::DAGCombinerInfo &DCI, 8482 const ARMSubtarget *Subtarget) { 8483 8484 if (Subtarget->isThumb1Only()) return SDValue(); 8485 8486 // Only perform the checks after legalize when the pattern is available. 8487 if (DCI.isBeforeLegalize()) return SDValue(); 8488 8489 // Look for multiply add opportunities. 8490 // The pattern is a ISD::UMUL_LOHI followed by two add nodes, where 8491 // each add nodes consumes a value from ISD::UMUL_LOHI and there is 8492 // a glue link from the first add to the second add. 8493 // If we find this pattern, we can replace the U/SMUL_LOHI, ADDC, and ADDE by 8494 // a S/UMLAL instruction. 8495 // UMUL_LOHI 8496 // / :lo \ :hi 8497 // / \ [no multiline comment] 8498 // loAdd -> ADDE | 8499 // \ :glue / 8500 // \ / 8501 // ADDC <- hiAdd 8502 // 8503 assert(AddcNode->getOpcode() == ISD::ADDC && "Expect an ADDC"); 8504 SDValue AddcOp0 = AddcNode->getOperand(0); 8505 SDValue AddcOp1 = AddcNode->getOperand(1); 8506 8507 // Check if the two operands are from the same mul_lohi node. 8508 if (AddcOp0.getNode() == AddcOp1.getNode()) 8509 return SDValue(); 8510 8511 assert(AddcNode->getNumValues() == 2 && 8512 AddcNode->getValueType(0) == MVT::i32 && 8513 "Expect ADDC with two result values. First: i32"); 8514 8515 // Check that we have a glued ADDC node. 8516 if (AddcNode->getValueType(1) != MVT::Glue) 8517 return SDValue(); 8518 8519 // Check that the ADDC adds the low result of the S/UMUL_LOHI. 8520 if (AddcOp0->getOpcode() != ISD::UMUL_LOHI && 8521 AddcOp0->getOpcode() != ISD::SMUL_LOHI && 8522 AddcOp1->getOpcode() != ISD::UMUL_LOHI && 8523 AddcOp1->getOpcode() != ISD::SMUL_LOHI) 8524 return SDValue(); 8525 8526 // Look for the glued ADDE. 8527 SDNode* AddeNode = AddcNode->getGluedUser(); 8528 if (!AddeNode) 8529 return SDValue(); 8530 8531 // Make sure it is really an ADDE. 8532 if (AddeNode->getOpcode() != ISD::ADDE) 8533 return SDValue(); 8534 8535 assert(AddeNode->getNumOperands() == 3 && 8536 AddeNode->getOperand(2).getValueType() == MVT::Glue && 8537 "ADDE node has the wrong inputs"); 8538 8539 // Check for the triangle shape. 8540 SDValue AddeOp0 = AddeNode->getOperand(0); 8541 SDValue AddeOp1 = AddeNode->getOperand(1); 8542 8543 // Make sure that the ADDE operands are not coming from the same node. 8544 if (AddeOp0.getNode() == AddeOp1.getNode()) 8545 return SDValue(); 8546 8547 // Find the MUL_LOHI node walking up ADDE's operands. 8548 bool IsLeftOperandMUL = false; 8549 SDValue MULOp = findMUL_LOHI(AddeOp0); 8550 if (MULOp == SDValue()) 8551 MULOp = findMUL_LOHI(AddeOp1); 8552 else 8553 IsLeftOperandMUL = true; 8554 if (MULOp == SDValue()) 8555 return SDValue(); 8556 8557 // Figure out the right opcode. 8558 unsigned Opc = MULOp->getOpcode(); 8559 unsigned FinalOpc = (Opc == ISD::SMUL_LOHI) ? ARMISD::SMLAL : ARMISD::UMLAL; 8560 8561 // Figure out the high and low input values to the MLAL node. 8562 SDValue* HiAdd = nullptr; 8563 SDValue* LoMul = nullptr; 8564 SDValue* LowAdd = nullptr; 8565 8566 // Ensure that ADDE is from high result of ISD::SMUL_LOHI. 8567 if ((AddeOp0 != MULOp.getValue(1)) && (AddeOp1 != MULOp.getValue(1))) 8568 return SDValue(); 8569 8570 if (IsLeftOperandMUL) 8571 HiAdd = &AddeOp1; 8572 else 8573 HiAdd = &AddeOp0; 8574 8575 8576 // Ensure that LoMul and LowAdd are taken from correct ISD::SMUL_LOHI node 8577 // whose low result is fed to the ADDC we are checking. 8578 8579 if (AddcOp0 == MULOp.getValue(0)) { 8580 LoMul = &AddcOp0; 8581 LowAdd = &AddcOp1; 8582 } 8583 if (AddcOp1 == MULOp.getValue(0)) { 8584 LoMul = &AddcOp1; 8585 LowAdd = &AddcOp0; 8586 } 8587 8588 if (!LoMul) 8589 return SDValue(); 8590 8591 // Create the merged node. 8592 SelectionDAG &DAG = DCI.DAG; 8593 8594 // Build operand list. 8595 SmallVector<SDValue, 8> Ops; 8596 Ops.push_back(LoMul->getOperand(0)); 8597 Ops.push_back(LoMul->getOperand(1)); 8598 Ops.push_back(*LowAdd); 8599 Ops.push_back(*HiAdd); 8600 8601 SDValue MLALNode = DAG.getNode(FinalOpc, SDLoc(AddcNode), 8602 DAG.getVTList(MVT::i32, MVT::i32), Ops); 8603 8604 // Replace the ADDs' nodes uses by the MLA node's values. 8605 SDValue HiMLALResult(MLALNode.getNode(), 1); 8606 DAG.ReplaceAllUsesOfValueWith(SDValue(AddeNode, 0), HiMLALResult); 8607 8608 SDValue LoMLALResult(MLALNode.getNode(), 0); 8609 DAG.ReplaceAllUsesOfValueWith(SDValue(AddcNode, 0), LoMLALResult); 8610 8611 // Return original node to notify the driver to stop replacing. 8612 SDValue resNode(AddcNode, 0); 8613 return resNode; 8614 } 8615 8616 /// PerformADDCCombine - Target-specific dag combine transform from 8617 /// ISD::ADDC, ISD::ADDE, and ISD::MUL_LOHI to MLAL. 8618 static SDValue PerformADDCCombine(SDNode *N, 8619 TargetLowering::DAGCombinerInfo &DCI, 8620 const ARMSubtarget *Subtarget) { 8621 8622 return AddCombineTo64bitMLAL(N, DCI, Subtarget); 8623 8624 } 8625 8626 /// PerformADDCombineWithOperands - Try DAG combinations for an ADD with 8627 /// operands N0 and N1. This is a helper for PerformADDCombine that is 8628 /// called with the default operands, and if that fails, with commuted 8629 /// operands. 8630 static SDValue PerformADDCombineWithOperands(SDNode *N, SDValue N0, SDValue N1, 8631 TargetLowering::DAGCombinerInfo &DCI, 8632 const ARMSubtarget *Subtarget){ 8633 8634 // Attempt to create vpaddl for this add. 8635 SDValue Result = AddCombineToVPADDL(N, N0, N1, DCI, Subtarget); 8636 if (Result.getNode()) 8637 return Result; 8638 8639 // fold (add (select cc, 0, c), x) -> (select cc, x, (add, x, c)) 8640 if (N0.getNode()->hasOneUse()) { 8641 SDValue Result = combineSelectAndUse(N, N0, N1, DCI); 8642 if (Result.getNode()) return Result; 8643 } 8644 return SDValue(); 8645 } 8646 8647 /// PerformADDCombine - Target-specific dag combine xforms for ISD::ADD. 8648 /// 8649 static SDValue PerformADDCombine(SDNode *N, 8650 TargetLowering::DAGCombinerInfo &DCI, 8651 const ARMSubtarget *Subtarget) { 8652 SDValue N0 = N->getOperand(0); 8653 SDValue N1 = N->getOperand(1); 8654 8655 // First try with the default operand order. 8656 SDValue Result = PerformADDCombineWithOperands(N, N0, N1, DCI, Subtarget); 8657 if (Result.getNode()) 8658 return Result; 8659 8660 // If that didn't work, try again with the operands commuted. 8661 return PerformADDCombineWithOperands(N, N1, N0, DCI, Subtarget); 8662 } 8663 8664 /// PerformSUBCombine - Target-specific dag combine xforms for ISD::SUB. 8665 /// 8666 static SDValue PerformSUBCombine(SDNode *N, 8667 TargetLowering::DAGCombinerInfo &DCI) { 8668 SDValue N0 = N->getOperand(0); 8669 SDValue N1 = N->getOperand(1); 8670 8671 // fold (sub x, (select cc, 0, c)) -> (select cc, x, (sub, x, c)) 8672 if (N1.getNode()->hasOneUse()) { 8673 SDValue Result = combineSelectAndUse(N, N1, N0, DCI); 8674 if (Result.getNode()) return Result; 8675 } 8676 8677 return SDValue(); 8678 } 8679 8680 /// PerformVMULCombine 8681 /// Distribute (A + B) * C to (A * C) + (B * C) to take advantage of the 8682 /// special multiplier accumulator forwarding. 8683 /// vmul d3, d0, d2 8684 /// vmla d3, d1, d2 8685 /// is faster than 8686 /// vadd d3, d0, d1 8687 /// vmul d3, d3, d2 8688 // However, for (A + B) * (A + B), 8689 // vadd d2, d0, d1 8690 // vmul d3, d0, d2 8691 // vmla d3, d1, d2 8692 // is slower than 8693 // vadd d2, d0, d1 8694 // vmul d3, d2, d2 8695 static SDValue PerformVMULCombine(SDNode *N, 8696 TargetLowering::DAGCombinerInfo &DCI, 8697 const ARMSubtarget *Subtarget) { 8698 if (!Subtarget->hasVMLxForwarding()) 8699 return SDValue(); 8700 8701 SelectionDAG &DAG = DCI.DAG; 8702 SDValue N0 = N->getOperand(0); 8703 SDValue N1 = N->getOperand(1); 8704 unsigned Opcode = N0.getOpcode(); 8705 if (Opcode != ISD::ADD && Opcode != ISD::SUB && 8706 Opcode != ISD::FADD && Opcode != ISD::FSUB) { 8707 Opcode = N1.getOpcode(); 8708 if (Opcode != ISD::ADD && Opcode != ISD::SUB && 8709 Opcode != ISD::FADD && Opcode != ISD::FSUB) 8710 return SDValue(); 8711 std::swap(N0, N1); 8712 } 8713 8714 if (N0 == N1) 8715 return SDValue(); 8716 8717 EVT VT = N->getValueType(0); 8718 SDLoc DL(N); 8719 SDValue N00 = N0->getOperand(0); 8720 SDValue N01 = N0->getOperand(1); 8721 return DAG.getNode(Opcode, DL, VT, 8722 DAG.getNode(ISD::MUL, DL, VT, N00, N1), 8723 DAG.getNode(ISD::MUL, DL, VT, N01, N1)); 8724 } 8725 8726 static SDValue PerformMULCombine(SDNode *N, 8727 TargetLowering::DAGCombinerInfo &DCI, 8728 const ARMSubtarget *Subtarget) { 8729 SelectionDAG &DAG = DCI.DAG; 8730 8731 if (Subtarget->isThumb1Only()) 8732 return SDValue(); 8733 8734 if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer()) 8735 return SDValue(); 8736 8737 EVT VT = N->getValueType(0); 8738 if (VT.is64BitVector() || VT.is128BitVector()) 8739 return PerformVMULCombine(N, DCI, Subtarget); 8740 if (VT != MVT::i32) 8741 return SDValue(); 8742 8743 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(1)); 8744 if (!C) 8745 return SDValue(); 8746 8747 int64_t MulAmt = C->getSExtValue(); 8748 unsigned ShiftAmt = countTrailingZeros<uint64_t>(MulAmt); 8749 8750 ShiftAmt = ShiftAmt & (32 - 1); 8751 SDValue V = N->getOperand(0); 8752 SDLoc DL(N); 8753 8754 SDValue Res; 8755 MulAmt >>= ShiftAmt; 8756 8757 if (MulAmt >= 0) { 8758 if (isPowerOf2_32(MulAmt - 1)) { 8759 // (mul x, 2^N + 1) => (add (shl x, N), x) 8760 Res = DAG.getNode(ISD::ADD, DL, VT, 8761 V, 8762 DAG.getNode(ISD::SHL, DL, VT, 8763 V, 8764 DAG.getConstant(Log2_32(MulAmt - 1), DL, 8765 MVT::i32))); 8766 } else if (isPowerOf2_32(MulAmt + 1)) { 8767 // (mul x, 2^N - 1) => (sub (shl x, N), x) 8768 Res = DAG.getNode(ISD::SUB, DL, VT, 8769 DAG.getNode(ISD::SHL, DL, VT, 8770 V, 8771 DAG.getConstant(Log2_32(MulAmt + 1), DL, 8772 MVT::i32)), 8773 V); 8774 } else 8775 return SDValue(); 8776 } else { 8777 uint64_t MulAmtAbs = -MulAmt; 8778 if (isPowerOf2_32(MulAmtAbs + 1)) { 8779 // (mul x, -(2^N - 1)) => (sub x, (shl x, N)) 8780 Res = DAG.getNode(ISD::SUB, DL, VT, 8781 V, 8782 DAG.getNode(ISD::SHL, DL, VT, 8783 V, 8784 DAG.getConstant(Log2_32(MulAmtAbs + 1), DL, 8785 MVT::i32))); 8786 } else if (isPowerOf2_32(MulAmtAbs - 1)) { 8787 // (mul x, -(2^N + 1)) => - (add (shl x, N), x) 8788 Res = DAG.getNode(ISD::ADD, DL, VT, 8789 V, 8790 DAG.getNode(ISD::SHL, DL, VT, 8791 V, 8792 DAG.getConstant(Log2_32(MulAmtAbs - 1), DL, 8793 MVT::i32))); 8794 Res = DAG.getNode(ISD::SUB, DL, VT, 8795 DAG.getConstant(0, DL, MVT::i32), Res); 8796 8797 } else 8798 return SDValue(); 8799 } 8800 8801 if (ShiftAmt != 0) 8802 Res = DAG.getNode(ISD::SHL, DL, VT, 8803 Res, DAG.getConstant(ShiftAmt, DL, MVT::i32)); 8804 8805 // Do not add new nodes to DAG combiner worklist. 8806 DCI.CombineTo(N, Res, false); 8807 return SDValue(); 8808 } 8809 8810 static SDValue PerformANDCombine(SDNode *N, 8811 TargetLowering::DAGCombinerInfo &DCI, 8812 const ARMSubtarget *Subtarget) { 8813 8814 // Attempt to use immediate-form VBIC 8815 BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(N->getOperand(1)); 8816 SDLoc dl(N); 8817 EVT VT = N->getValueType(0); 8818 SelectionDAG &DAG = DCI.DAG; 8819 8820 if(!DAG.getTargetLoweringInfo().isTypeLegal(VT)) 8821 return SDValue(); 8822 8823 APInt SplatBits, SplatUndef; 8824 unsigned SplatBitSize; 8825 bool HasAnyUndefs; 8826 if (BVN && 8827 BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs)) { 8828 if (SplatBitSize <= 64) { 8829 EVT VbicVT; 8830 SDValue Val = isNEONModifiedImm((~SplatBits).getZExtValue(), 8831 SplatUndef.getZExtValue(), SplatBitSize, 8832 DAG, dl, VbicVT, VT.is128BitVector(), 8833 OtherModImm); 8834 if (Val.getNode()) { 8835 SDValue Input = 8836 DAG.getNode(ISD::BITCAST, dl, VbicVT, N->getOperand(0)); 8837 SDValue Vbic = DAG.getNode(ARMISD::VBICIMM, dl, VbicVT, Input, Val); 8838 return DAG.getNode(ISD::BITCAST, dl, VT, Vbic); 8839 } 8840 } 8841 } 8842 8843 if (!Subtarget->isThumb1Only()) { 8844 // fold (and (select cc, -1, c), x) -> (select cc, x, (and, x, c)) 8845 SDValue Result = combineSelectAndUseCommutative(N, true, DCI); 8846 if (Result.getNode()) 8847 return Result; 8848 } 8849 8850 return SDValue(); 8851 } 8852 8853 /// PerformORCombine - Target-specific dag combine xforms for ISD::OR 8854 static SDValue PerformORCombine(SDNode *N, 8855 TargetLowering::DAGCombinerInfo &DCI, 8856 const ARMSubtarget *Subtarget) { 8857 // Attempt to use immediate-form VORR 8858 BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(N->getOperand(1)); 8859 SDLoc dl(N); 8860 EVT VT = N->getValueType(0); 8861 SelectionDAG &DAG = DCI.DAG; 8862 8863 if(!DAG.getTargetLoweringInfo().isTypeLegal(VT)) 8864 return SDValue(); 8865 8866 APInt SplatBits, SplatUndef; 8867 unsigned SplatBitSize; 8868 bool HasAnyUndefs; 8869 if (BVN && Subtarget->hasNEON() && 8870 BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs)) { 8871 if (SplatBitSize <= 64) { 8872 EVT VorrVT; 8873 SDValue Val = isNEONModifiedImm(SplatBits.getZExtValue(), 8874 SplatUndef.getZExtValue(), SplatBitSize, 8875 DAG, dl, VorrVT, VT.is128BitVector(), 8876 OtherModImm); 8877 if (Val.getNode()) { 8878 SDValue Input = 8879 DAG.getNode(ISD::BITCAST, dl, VorrVT, N->getOperand(0)); 8880 SDValue Vorr = DAG.getNode(ARMISD::VORRIMM, dl, VorrVT, Input, Val); 8881 return DAG.getNode(ISD::BITCAST, dl, VT, Vorr); 8882 } 8883 } 8884 } 8885 8886 if (!Subtarget->isThumb1Only()) { 8887 // fold (or (select cc, 0, c), x) -> (select cc, x, (or, x, c)) 8888 SDValue Result = combineSelectAndUseCommutative(N, false, DCI); 8889 if (Result.getNode()) 8890 return Result; 8891 } 8892 8893 // The code below optimizes (or (and X, Y), Z). 8894 // The AND operand needs to have a single user to make these optimizations 8895 // profitable. 8896 SDValue N0 = N->getOperand(0); 8897 if (N0.getOpcode() != ISD::AND || !N0.hasOneUse()) 8898 return SDValue(); 8899 SDValue N1 = N->getOperand(1); 8900 8901 // (or (and B, A), (and C, ~A)) => (VBSL A, B, C) when A is a constant. 8902 if (Subtarget->hasNEON() && N1.getOpcode() == ISD::AND && VT.isVector() && 8903 DAG.getTargetLoweringInfo().isTypeLegal(VT)) { 8904 APInt SplatUndef; 8905 unsigned SplatBitSize; 8906 bool HasAnyUndefs; 8907 8908 APInt SplatBits0, SplatBits1; 8909 BuildVectorSDNode *BVN0 = dyn_cast<BuildVectorSDNode>(N0->getOperand(1)); 8910 BuildVectorSDNode *BVN1 = dyn_cast<BuildVectorSDNode>(N1->getOperand(1)); 8911 // Ensure that the second operand of both ands are constants 8912 if (BVN0 && BVN0->isConstantSplat(SplatBits0, SplatUndef, SplatBitSize, 8913 HasAnyUndefs) && !HasAnyUndefs) { 8914 if (BVN1 && BVN1->isConstantSplat(SplatBits1, SplatUndef, SplatBitSize, 8915 HasAnyUndefs) && !HasAnyUndefs) { 8916 // Ensure that the bit width of the constants are the same and that 8917 // the splat arguments are logical inverses as per the pattern we 8918 // are trying to simplify. 8919 if (SplatBits0.getBitWidth() == SplatBits1.getBitWidth() && 8920 SplatBits0 == ~SplatBits1) { 8921 // Canonicalize the vector type to make instruction selection 8922 // simpler. 8923 EVT CanonicalVT = VT.is128BitVector() ? MVT::v4i32 : MVT::v2i32; 8924 SDValue Result = DAG.getNode(ARMISD::VBSL, dl, CanonicalVT, 8925 N0->getOperand(1), 8926 N0->getOperand(0), 8927 N1->getOperand(0)); 8928 return DAG.getNode(ISD::BITCAST, dl, VT, Result); 8929 } 8930 } 8931 } 8932 } 8933 8934 // Try to use the ARM/Thumb2 BFI (bitfield insert) instruction when 8935 // reasonable. 8936 8937 // BFI is only available on V6T2+ 8938 if (Subtarget->isThumb1Only() || !Subtarget->hasV6T2Ops()) 8939 return SDValue(); 8940 8941 SDLoc DL(N); 8942 // 1) or (and A, mask), val => ARMbfi A, val, mask 8943 // iff (val & mask) == val 8944 // 8945 // 2) or (and A, mask), (and B, mask2) => ARMbfi A, (lsr B, amt), mask 8946 // 2a) iff isBitFieldInvertedMask(mask) && isBitFieldInvertedMask(~mask2) 8947 // && mask == ~mask2 8948 // 2b) iff isBitFieldInvertedMask(~mask) && isBitFieldInvertedMask(mask2) 8949 // && ~mask == mask2 8950 // (i.e., copy a bitfield value into another bitfield of the same width) 8951 8952 if (VT != MVT::i32) 8953 return SDValue(); 8954 8955 SDValue N00 = N0.getOperand(0); 8956 8957 // The value and the mask need to be constants so we can verify this is 8958 // actually a bitfield set. If the mask is 0xffff, we can do better 8959 // via a movt instruction, so don't use BFI in that case. 8960 SDValue MaskOp = N0.getOperand(1); 8961 ConstantSDNode *MaskC = dyn_cast<ConstantSDNode>(MaskOp); 8962 if (!MaskC) 8963 return SDValue(); 8964 unsigned Mask = MaskC->getZExtValue(); 8965 if (Mask == 0xffff) 8966 return SDValue(); 8967 SDValue Res; 8968 // Case (1): or (and A, mask), val => ARMbfi A, val, mask 8969 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1); 8970 if (N1C) { 8971 unsigned Val = N1C->getZExtValue(); 8972 if ((Val & ~Mask) != Val) 8973 return SDValue(); 8974 8975 if (ARM::isBitFieldInvertedMask(Mask)) { 8976 Val >>= countTrailingZeros(~Mask); 8977 8978 Res = DAG.getNode(ARMISD::BFI, DL, VT, N00, 8979 DAG.getConstant(Val, DL, MVT::i32), 8980 DAG.getConstant(Mask, DL, MVT::i32)); 8981 8982 // Do not add new nodes to DAG combiner worklist. 8983 DCI.CombineTo(N, Res, false); 8984 return SDValue(); 8985 } 8986 } else if (N1.getOpcode() == ISD::AND) { 8987 // case (2) or (and A, mask), (and B, mask2) => ARMbfi A, (lsr B, amt), mask 8988 ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1)); 8989 if (!N11C) 8990 return SDValue(); 8991 unsigned Mask2 = N11C->getZExtValue(); 8992 8993 // Mask and ~Mask2 (or reverse) must be equivalent for the BFI pattern 8994 // as is to match. 8995 if (ARM::isBitFieldInvertedMask(Mask) && 8996 (Mask == ~Mask2)) { 8997 // The pack halfword instruction works better for masks that fit it, 8998 // so use that when it's available. 8999 if (Subtarget->hasT2ExtractPack() && 9000 (Mask == 0xffff || Mask == 0xffff0000)) 9001 return SDValue(); 9002 // 2a 9003 unsigned amt = countTrailingZeros(Mask2); 9004 Res = DAG.getNode(ISD::SRL, DL, VT, N1.getOperand(0), 9005 DAG.getConstant(amt, DL, MVT::i32)); 9006 Res = DAG.getNode(ARMISD::BFI, DL, VT, N00, Res, 9007 DAG.getConstant(Mask, DL, MVT::i32)); 9008 // Do not add new nodes to DAG combiner worklist. 9009 DCI.CombineTo(N, Res, false); 9010 return SDValue(); 9011 } else if (ARM::isBitFieldInvertedMask(~Mask) && 9012 (~Mask == Mask2)) { 9013 // The pack halfword instruction works better for masks that fit it, 9014 // so use that when it's available. 9015 if (Subtarget->hasT2ExtractPack() && 9016 (Mask2 == 0xffff || Mask2 == 0xffff0000)) 9017 return SDValue(); 9018 // 2b 9019 unsigned lsb = countTrailingZeros(Mask); 9020 Res = DAG.getNode(ISD::SRL, DL, VT, N00, 9021 DAG.getConstant(lsb, DL, MVT::i32)); 9022 Res = DAG.getNode(ARMISD::BFI, DL, VT, N1.getOperand(0), Res, 9023 DAG.getConstant(Mask2, DL, MVT::i32)); 9024 // Do not add new nodes to DAG combiner worklist. 9025 DCI.CombineTo(N, Res, false); 9026 return SDValue(); 9027 } 9028 } 9029 9030 if (DAG.MaskedValueIsZero(N1, MaskC->getAPIntValue()) && 9031 N00.getOpcode() == ISD::SHL && isa<ConstantSDNode>(N00.getOperand(1)) && 9032 ARM::isBitFieldInvertedMask(~Mask)) { 9033 // Case (3): or (and (shl A, #shamt), mask), B => ARMbfi B, A, ~mask 9034 // where lsb(mask) == #shamt and masked bits of B are known zero. 9035 SDValue ShAmt = N00.getOperand(1); 9036 unsigned ShAmtC = cast<ConstantSDNode>(ShAmt)->getZExtValue(); 9037 unsigned LSB = countTrailingZeros(Mask); 9038 if (ShAmtC != LSB) 9039 return SDValue(); 9040 9041 Res = DAG.getNode(ARMISD::BFI, DL, VT, N1, N00.getOperand(0), 9042 DAG.getConstant(~Mask, DL, MVT::i32)); 9043 9044 // Do not add new nodes to DAG combiner worklist. 9045 DCI.CombineTo(N, Res, false); 9046 } 9047 9048 return SDValue(); 9049 } 9050 9051 static SDValue PerformXORCombine(SDNode *N, 9052 TargetLowering::DAGCombinerInfo &DCI, 9053 const ARMSubtarget *Subtarget) { 9054 EVT VT = N->getValueType(0); 9055 SelectionDAG &DAG = DCI.DAG; 9056 9057 if(!DAG.getTargetLoweringInfo().isTypeLegal(VT)) 9058 return SDValue(); 9059 9060 if (!Subtarget->isThumb1Only()) { 9061 // fold (xor (select cc, 0, c), x) -> (select cc, x, (xor, x, c)) 9062 SDValue Result = combineSelectAndUseCommutative(N, false, DCI); 9063 if (Result.getNode()) 9064 return Result; 9065 } 9066 9067 return SDValue(); 9068 } 9069 9070 // ParseBFI - given a BFI instruction in N, extract the "from" value (Rn) and return it, 9071 // and fill in FromMask and ToMask with (consecutive) bits in "from" to be extracted and 9072 // their position in "to" (Rd). 9073 static SDValue ParseBFI(SDNode *N, APInt &ToMask, APInt &FromMask) { 9074 assert(N->getOpcode() == ARMISD::BFI); 9075 9076 SDValue From = N->getOperand(1); 9077 ToMask = ~cast<ConstantSDNode>(N->getOperand(2))->getAPIntValue(); 9078 FromMask = APInt::getLowBitsSet(ToMask.getBitWidth(), ToMask.countPopulation()); 9079 9080 // If the Base came from a SHR #C, we can deduce that it is really testing bit 9081 // #C in the base of the SHR. 9082 if (From->getOpcode() == ISD::SRL && 9083 isa<ConstantSDNode>(From->getOperand(1))) { 9084 APInt Shift = cast<ConstantSDNode>(From->getOperand(1))->getAPIntValue(); 9085 assert(Shift.getLimitedValue() < 32 && "Shift too large!"); 9086 FromMask <<= Shift.getLimitedValue(31); 9087 From = From->getOperand(0); 9088 } 9089 9090 return From; 9091 } 9092 9093 // If A and B contain one contiguous set of bits, does A | B == A . B? 9094 // 9095 // Neither A nor B must be zero. 9096 static bool BitsProperlyConcatenate(const APInt &A, const APInt &B) { 9097 unsigned LastActiveBitInA = A.countTrailingZeros(); 9098 unsigned FirstActiveBitInB = B.getBitWidth() - B.countLeadingZeros() - 1; 9099 return LastActiveBitInA - 1 == FirstActiveBitInB; 9100 } 9101 9102 static SDValue FindBFIToCombineWith(SDNode *N) { 9103 // We have a BFI in N. Follow a possible chain of BFIs and find a BFI it can combine with, 9104 // if one exists. 9105 APInt ToMask, FromMask; 9106 SDValue From = ParseBFI(N, ToMask, FromMask); 9107 SDValue To = N->getOperand(0); 9108 9109 // Now check for a compatible BFI to merge with. We can pass through BFIs that 9110 // aren't compatible, but not if they set the same bit in their destination as 9111 // we do (or that of any BFI we're going to combine with). 9112 SDValue V = To; 9113 APInt CombinedToMask = ToMask; 9114 while (V.getOpcode() == ARMISD::BFI) { 9115 APInt NewToMask, NewFromMask; 9116 SDValue NewFrom = ParseBFI(V.getNode(), NewToMask, NewFromMask); 9117 if (NewFrom != From) { 9118 // This BFI has a different base. Keep going. 9119 CombinedToMask |= NewToMask; 9120 V = V.getOperand(0); 9121 continue; 9122 } 9123 9124 // Do the written bits conflict with any we've seen so far? 9125 if ((NewToMask & CombinedToMask).getBoolValue()) 9126 // Conflicting bits - bail out because going further is unsafe. 9127 return SDValue(); 9128 9129 // Are the new bits contiguous when combined with the old bits? 9130 if (BitsProperlyConcatenate(ToMask, NewToMask) && 9131 BitsProperlyConcatenate(FromMask, NewFromMask)) 9132 return V; 9133 if (BitsProperlyConcatenate(NewToMask, ToMask) && 9134 BitsProperlyConcatenate(NewFromMask, FromMask)) 9135 return V; 9136 9137 // We've seen a write to some bits, so track it. 9138 CombinedToMask |= NewToMask; 9139 // Keep going... 9140 V = V.getOperand(0); 9141 } 9142 9143 return SDValue(); 9144 } 9145 9146 static SDValue PerformBFICombine(SDNode *N, 9147 TargetLowering::DAGCombinerInfo &DCI) { 9148 SDValue N1 = N->getOperand(1); 9149 if (N1.getOpcode() == ISD::AND) { 9150 // (bfi A, (and B, Mask1), Mask2) -> (bfi A, B, Mask2) iff 9151 // the bits being cleared by the AND are not demanded by the BFI. 9152 ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1)); 9153 if (!N11C) 9154 return SDValue(); 9155 unsigned InvMask = cast<ConstantSDNode>(N->getOperand(2))->getZExtValue(); 9156 unsigned LSB = countTrailingZeros(~InvMask); 9157 unsigned Width = (32 - countLeadingZeros(~InvMask)) - LSB; 9158 assert(Width < 9159 static_cast<unsigned>(std::numeric_limits<unsigned>::digits) && 9160 "undefined behavior"); 9161 unsigned Mask = (1u << Width) - 1; 9162 unsigned Mask2 = N11C->getZExtValue(); 9163 if ((Mask & (~Mask2)) == 0) 9164 return DCI.DAG.getNode(ARMISD::BFI, SDLoc(N), N->getValueType(0), 9165 N->getOperand(0), N1.getOperand(0), 9166 N->getOperand(2)); 9167 } else if (N->getOperand(0).getOpcode() == ARMISD::BFI) { 9168 // We have a BFI of a BFI. Walk up the BFI chain to see how long it goes. 9169 // Keep track of any consecutive bits set that all come from the same base 9170 // value. We can combine these together into a single BFI. 9171 SDValue CombineBFI = FindBFIToCombineWith(N); 9172 if (CombineBFI == SDValue()) 9173 return SDValue(); 9174 9175 // We've found a BFI. 9176 APInt ToMask1, FromMask1; 9177 SDValue From1 = ParseBFI(N, ToMask1, FromMask1); 9178 9179 APInt ToMask2, FromMask2; 9180 SDValue From2 = ParseBFI(CombineBFI.getNode(), ToMask2, FromMask2); 9181 assert(From1 == From2); 9182 (void)From2; 9183 9184 // First, unlink CombineBFI. 9185 DCI.DAG.ReplaceAllUsesWith(CombineBFI, CombineBFI.getOperand(0)); 9186 // Then create a new BFI, combining the two together. 9187 APInt NewFromMask = FromMask1 | FromMask2; 9188 APInt NewToMask = ToMask1 | ToMask2; 9189 9190 EVT VT = N->getValueType(0); 9191 SDLoc dl(N); 9192 9193 if (NewFromMask[0] == 0) 9194 From1 = DCI.DAG.getNode( 9195 ISD::SRL, dl, VT, From1, 9196 DCI.DAG.getConstant(NewFromMask.countTrailingZeros(), dl, VT)); 9197 return DCI.DAG.getNode(ARMISD::BFI, dl, VT, N->getOperand(0), From1, 9198 DCI.DAG.getConstant(~NewToMask, dl, VT)); 9199 } 9200 return SDValue(); 9201 } 9202 9203 /// PerformVMOVRRDCombine - Target-specific dag combine xforms for 9204 /// ARMISD::VMOVRRD. 9205 static SDValue PerformVMOVRRDCombine(SDNode *N, 9206 TargetLowering::DAGCombinerInfo &DCI, 9207 const ARMSubtarget *Subtarget) { 9208 // vmovrrd(vmovdrr x, y) -> x,y 9209 SDValue InDouble = N->getOperand(0); 9210 if (InDouble.getOpcode() == ARMISD::VMOVDRR && !Subtarget->isFPOnlySP()) 9211 return DCI.CombineTo(N, InDouble.getOperand(0), InDouble.getOperand(1)); 9212 9213 // vmovrrd(load f64) -> (load i32), (load i32) 9214 SDNode *InNode = InDouble.getNode(); 9215 if (ISD::isNormalLoad(InNode) && InNode->hasOneUse() && 9216 InNode->getValueType(0) == MVT::f64 && 9217 InNode->getOperand(1).getOpcode() == ISD::FrameIndex && 9218 !cast<LoadSDNode>(InNode)->isVolatile()) { 9219 // TODO: Should this be done for non-FrameIndex operands? 9220 LoadSDNode *LD = cast<LoadSDNode>(InNode); 9221 9222 SelectionDAG &DAG = DCI.DAG; 9223 SDLoc DL(LD); 9224 SDValue BasePtr = LD->getBasePtr(); 9225 SDValue NewLD1 = DAG.getLoad(MVT::i32, DL, LD->getChain(), BasePtr, 9226 LD->getPointerInfo(), LD->isVolatile(), 9227 LD->isNonTemporal(), LD->isInvariant(), 9228 LD->getAlignment()); 9229 9230 SDValue OffsetPtr = DAG.getNode(ISD::ADD, DL, MVT::i32, BasePtr, 9231 DAG.getConstant(4, DL, MVT::i32)); 9232 SDValue NewLD2 = DAG.getLoad(MVT::i32, DL, NewLD1.getValue(1), OffsetPtr, 9233 LD->getPointerInfo(), LD->isVolatile(), 9234 LD->isNonTemporal(), LD->isInvariant(), 9235 std::min(4U, LD->getAlignment() / 2)); 9236 9237 DAG.ReplaceAllUsesOfValueWith(SDValue(LD, 1), NewLD2.getValue(1)); 9238 if (DCI.DAG.getDataLayout().isBigEndian()) 9239 std::swap (NewLD1, NewLD2); 9240 SDValue Result = DCI.CombineTo(N, NewLD1, NewLD2); 9241 return Result; 9242 } 9243 9244 return SDValue(); 9245 } 9246 9247 /// PerformVMOVDRRCombine - Target-specific dag combine xforms for 9248 /// ARMISD::VMOVDRR. This is also used for BUILD_VECTORs with 2 operands. 9249 static SDValue PerformVMOVDRRCombine(SDNode *N, SelectionDAG &DAG) { 9250 // N=vmovrrd(X); vmovdrr(N:0, N:1) -> bit_convert(X) 9251 SDValue Op0 = N->getOperand(0); 9252 SDValue Op1 = N->getOperand(1); 9253 if (Op0.getOpcode() == ISD::BITCAST) 9254 Op0 = Op0.getOperand(0); 9255 if (Op1.getOpcode() == ISD::BITCAST) 9256 Op1 = Op1.getOperand(0); 9257 if (Op0.getOpcode() == ARMISD::VMOVRRD && 9258 Op0.getNode() == Op1.getNode() && 9259 Op0.getResNo() == 0 && Op1.getResNo() == 1) 9260 return DAG.getNode(ISD::BITCAST, SDLoc(N), 9261 N->getValueType(0), Op0.getOperand(0)); 9262 return SDValue(); 9263 } 9264 9265 /// hasNormalLoadOperand - Check if any of the operands of a BUILD_VECTOR node 9266 /// are normal, non-volatile loads. If so, it is profitable to bitcast an 9267 /// i64 vector to have f64 elements, since the value can then be loaded 9268 /// directly into a VFP register. 9269 static bool hasNormalLoadOperand(SDNode *N) { 9270 unsigned NumElts = N->getValueType(0).getVectorNumElements(); 9271 for (unsigned i = 0; i < NumElts; ++i) { 9272 SDNode *Elt = N->getOperand(i).getNode(); 9273 if (ISD::isNormalLoad(Elt) && !cast<LoadSDNode>(Elt)->isVolatile()) 9274 return true; 9275 } 9276 return false; 9277 } 9278 9279 /// PerformBUILD_VECTORCombine - Target-specific dag combine xforms for 9280 /// ISD::BUILD_VECTOR. 9281 static SDValue PerformBUILD_VECTORCombine(SDNode *N, 9282 TargetLowering::DAGCombinerInfo &DCI, 9283 const ARMSubtarget *Subtarget) { 9284 // build_vector(N=ARMISD::VMOVRRD(X), N:1) -> bit_convert(X): 9285 // VMOVRRD is introduced when legalizing i64 types. It forces the i64 value 9286 // into a pair of GPRs, which is fine when the value is used as a scalar, 9287 // but if the i64 value is converted to a vector, we need to undo the VMOVRRD. 9288 SelectionDAG &DAG = DCI.DAG; 9289 if (N->getNumOperands() == 2) { 9290 SDValue RV = PerformVMOVDRRCombine(N, DAG); 9291 if (RV.getNode()) 9292 return RV; 9293 } 9294 9295 // Load i64 elements as f64 values so that type legalization does not split 9296 // them up into i32 values. 9297 EVT VT = N->getValueType(0); 9298 if (VT.getVectorElementType() != MVT::i64 || !hasNormalLoadOperand(N)) 9299 return SDValue(); 9300 SDLoc dl(N); 9301 SmallVector<SDValue, 8> Ops; 9302 unsigned NumElts = VT.getVectorNumElements(); 9303 for (unsigned i = 0; i < NumElts; ++i) { 9304 SDValue V = DAG.getNode(ISD::BITCAST, dl, MVT::f64, N->getOperand(i)); 9305 Ops.push_back(V); 9306 // Make the DAGCombiner fold the bitcast. 9307 DCI.AddToWorklist(V.getNode()); 9308 } 9309 EVT FloatVT = EVT::getVectorVT(*DAG.getContext(), MVT::f64, NumElts); 9310 SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, FloatVT, Ops); 9311 return DAG.getNode(ISD::BITCAST, dl, VT, BV); 9312 } 9313 9314 /// \brief Target-specific dag combine xforms for ARMISD::BUILD_VECTOR. 9315 static SDValue 9316 PerformARMBUILD_VECTORCombine(SDNode *N, TargetLowering::DAGCombinerInfo &DCI) { 9317 // ARMISD::BUILD_VECTOR is introduced when legalizing ISD::BUILD_VECTOR. 9318 // At that time, we may have inserted bitcasts from integer to float. 9319 // If these bitcasts have survived DAGCombine, change the lowering of this 9320 // BUILD_VECTOR in something more vector friendly, i.e., that does not 9321 // force to use floating point types. 9322 9323 // Make sure we can change the type of the vector. 9324 // This is possible iff: 9325 // 1. The vector is only used in a bitcast to a integer type. I.e., 9326 // 1.1. Vector is used only once. 9327 // 1.2. Use is a bit convert to an integer type. 9328 // 2. The size of its operands are 32-bits (64-bits are not legal). 9329 EVT VT = N->getValueType(0); 9330 EVT EltVT = VT.getVectorElementType(); 9331 9332 // Check 1.1. and 2. 9333 if (EltVT.getSizeInBits() != 32 || !N->hasOneUse()) 9334 return SDValue(); 9335 9336 // By construction, the input type must be float. 9337 assert(EltVT == MVT::f32 && "Unexpected type!"); 9338 9339 // Check 1.2. 9340 SDNode *Use = *N->use_begin(); 9341 if (Use->getOpcode() != ISD::BITCAST || 9342 Use->getValueType(0).isFloatingPoint()) 9343 return SDValue(); 9344 9345 // Check profitability. 9346 // Model is, if more than half of the relevant operands are bitcast from 9347 // i32, turn the build_vector into a sequence of insert_vector_elt. 9348 // Relevant operands are everything that is not statically 9349 // (i.e., at compile time) bitcasted. 9350 unsigned NumOfBitCastedElts = 0; 9351 unsigned NumElts = VT.getVectorNumElements(); 9352 unsigned NumOfRelevantElts = NumElts; 9353 for (unsigned Idx = 0; Idx < NumElts; ++Idx) { 9354 SDValue Elt = N->getOperand(Idx); 9355 if (Elt->getOpcode() == ISD::BITCAST) { 9356 // Assume only bit cast to i32 will go away. 9357 if (Elt->getOperand(0).getValueType() == MVT::i32) 9358 ++NumOfBitCastedElts; 9359 } else if (Elt.getOpcode() == ISD::UNDEF || isa<ConstantSDNode>(Elt)) 9360 // Constants are statically casted, thus do not count them as 9361 // relevant operands. 9362 --NumOfRelevantElts; 9363 } 9364 9365 // Check if more than half of the elements require a non-free bitcast. 9366 if (NumOfBitCastedElts <= NumOfRelevantElts / 2) 9367 return SDValue(); 9368 9369 SelectionDAG &DAG = DCI.DAG; 9370 // Create the new vector type. 9371 EVT VecVT = EVT::getVectorVT(*DAG.getContext(), MVT::i32, NumElts); 9372 // Check if the type is legal. 9373 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 9374 if (!TLI.isTypeLegal(VecVT)) 9375 return SDValue(); 9376 9377 // Combine: 9378 // ARMISD::BUILD_VECTOR E1, E2, ..., EN. 9379 // => BITCAST INSERT_VECTOR_ELT 9380 // (INSERT_VECTOR_ELT (...), (BITCAST EN-1), N-1), 9381 // (BITCAST EN), N. 9382 SDValue Vec = DAG.getUNDEF(VecVT); 9383 SDLoc dl(N); 9384 for (unsigned Idx = 0 ; Idx < NumElts; ++Idx) { 9385 SDValue V = N->getOperand(Idx); 9386 if (V.getOpcode() == ISD::UNDEF) 9387 continue; 9388 if (V.getOpcode() == ISD::BITCAST && 9389 V->getOperand(0).getValueType() == MVT::i32) 9390 // Fold obvious case. 9391 V = V.getOperand(0); 9392 else { 9393 V = DAG.getNode(ISD::BITCAST, SDLoc(V), MVT::i32, V); 9394 // Make the DAGCombiner fold the bitcasts. 9395 DCI.AddToWorklist(V.getNode()); 9396 } 9397 SDValue LaneIdx = DAG.getConstant(Idx, dl, MVT::i32); 9398 Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VecVT, Vec, V, LaneIdx); 9399 } 9400 Vec = DAG.getNode(ISD::BITCAST, dl, VT, Vec); 9401 // Make the DAGCombiner fold the bitcasts. 9402 DCI.AddToWorklist(Vec.getNode()); 9403 return Vec; 9404 } 9405 9406 /// PerformInsertEltCombine - Target-specific dag combine xforms for 9407 /// ISD::INSERT_VECTOR_ELT. 9408 static SDValue PerformInsertEltCombine(SDNode *N, 9409 TargetLowering::DAGCombinerInfo &DCI) { 9410 // Bitcast an i64 load inserted into a vector to f64. 9411 // Otherwise, the i64 value will be legalized to a pair of i32 values. 9412 EVT VT = N->getValueType(0); 9413 SDNode *Elt = N->getOperand(1).getNode(); 9414 if (VT.getVectorElementType() != MVT::i64 || 9415 !ISD::isNormalLoad(Elt) || cast<LoadSDNode>(Elt)->isVolatile()) 9416 return SDValue(); 9417 9418 SelectionDAG &DAG = DCI.DAG; 9419 SDLoc dl(N); 9420 EVT FloatVT = EVT::getVectorVT(*DAG.getContext(), MVT::f64, 9421 VT.getVectorNumElements()); 9422 SDValue Vec = DAG.getNode(ISD::BITCAST, dl, FloatVT, N->getOperand(0)); 9423 SDValue V = DAG.getNode(ISD::BITCAST, dl, MVT::f64, N->getOperand(1)); 9424 // Make the DAGCombiner fold the bitcasts. 9425 DCI.AddToWorklist(Vec.getNode()); 9426 DCI.AddToWorklist(V.getNode()); 9427 SDValue InsElt = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, FloatVT, 9428 Vec, V, N->getOperand(2)); 9429 return DAG.getNode(ISD::BITCAST, dl, VT, InsElt); 9430 } 9431 9432 /// PerformVECTOR_SHUFFLECombine - Target-specific dag combine xforms for 9433 /// ISD::VECTOR_SHUFFLE. 9434 static SDValue PerformVECTOR_SHUFFLECombine(SDNode *N, SelectionDAG &DAG) { 9435 // The LLVM shufflevector instruction does not require the shuffle mask 9436 // length to match the operand vector length, but ISD::VECTOR_SHUFFLE does 9437 // have that requirement. When translating to ISD::VECTOR_SHUFFLE, if the 9438 // operands do not match the mask length, they are extended by concatenating 9439 // them with undef vectors. That is probably the right thing for other 9440 // targets, but for NEON it is better to concatenate two double-register 9441 // size vector operands into a single quad-register size vector. Do that 9442 // transformation here: 9443 // shuffle(concat(v1, undef), concat(v2, undef)) -> 9444 // shuffle(concat(v1, v2), undef) 9445 SDValue Op0 = N->getOperand(0); 9446 SDValue Op1 = N->getOperand(1); 9447 if (Op0.getOpcode() != ISD::CONCAT_VECTORS || 9448 Op1.getOpcode() != ISD::CONCAT_VECTORS || 9449 Op0.getNumOperands() != 2 || 9450 Op1.getNumOperands() != 2) 9451 return SDValue(); 9452 SDValue Concat0Op1 = Op0.getOperand(1); 9453 SDValue Concat1Op1 = Op1.getOperand(1); 9454 if (Concat0Op1.getOpcode() != ISD::UNDEF || 9455 Concat1Op1.getOpcode() != ISD::UNDEF) 9456 return SDValue(); 9457 // Skip the transformation if any of the types are illegal. 9458 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 9459 EVT VT = N->getValueType(0); 9460 if (!TLI.isTypeLegal(VT) || 9461 !TLI.isTypeLegal(Concat0Op1.getValueType()) || 9462 !TLI.isTypeLegal(Concat1Op1.getValueType())) 9463 return SDValue(); 9464 9465 SDValue NewConcat = DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT, 9466 Op0.getOperand(0), Op1.getOperand(0)); 9467 // Translate the shuffle mask. 9468 SmallVector<int, 16> NewMask; 9469 unsigned NumElts = VT.getVectorNumElements(); 9470 unsigned HalfElts = NumElts/2; 9471 ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N); 9472 for (unsigned n = 0; n < NumElts; ++n) { 9473 int MaskElt = SVN->getMaskElt(n); 9474 int NewElt = -1; 9475 if (MaskElt < (int)HalfElts) 9476 NewElt = MaskElt; 9477 else if (MaskElt >= (int)NumElts && MaskElt < (int)(NumElts + HalfElts)) 9478 NewElt = HalfElts + MaskElt - NumElts; 9479 NewMask.push_back(NewElt); 9480 } 9481 return DAG.getVectorShuffle(VT, SDLoc(N), NewConcat, 9482 DAG.getUNDEF(VT), NewMask.data()); 9483 } 9484 9485 /// CombineBaseUpdate - Target-specific DAG combine function for VLDDUP, 9486 /// NEON load/store intrinsics, and generic vector load/stores, to merge 9487 /// base address updates. 9488 /// For generic load/stores, the memory type is assumed to be a vector. 9489 /// The caller is assumed to have checked legality. 9490 static SDValue CombineBaseUpdate(SDNode *N, 9491 TargetLowering::DAGCombinerInfo &DCI) { 9492 SelectionDAG &DAG = DCI.DAG; 9493 const bool isIntrinsic = (N->getOpcode() == ISD::INTRINSIC_VOID || 9494 N->getOpcode() == ISD::INTRINSIC_W_CHAIN); 9495 const bool isStore = N->getOpcode() == ISD::STORE; 9496 const unsigned AddrOpIdx = ((isIntrinsic || isStore) ? 2 : 1); 9497 SDValue Addr = N->getOperand(AddrOpIdx); 9498 MemSDNode *MemN = cast<MemSDNode>(N); 9499 SDLoc dl(N); 9500 9501 // Search for a use of the address operand that is an increment. 9502 for (SDNode::use_iterator UI = Addr.getNode()->use_begin(), 9503 UE = Addr.getNode()->use_end(); UI != UE; ++UI) { 9504 SDNode *User = *UI; 9505 if (User->getOpcode() != ISD::ADD || 9506 UI.getUse().getResNo() != Addr.getResNo()) 9507 continue; 9508 9509 // Check that the add is independent of the load/store. Otherwise, folding 9510 // it would create a cycle. 9511 if (User->isPredecessorOf(N) || N->isPredecessorOf(User)) 9512 continue; 9513 9514 // Find the new opcode for the updating load/store. 9515 bool isLoadOp = true; 9516 bool isLaneOp = false; 9517 unsigned NewOpc = 0; 9518 unsigned NumVecs = 0; 9519 if (isIntrinsic) { 9520 unsigned IntNo = cast<ConstantSDNode>(N->getOperand(1))->getZExtValue(); 9521 switch (IntNo) { 9522 default: llvm_unreachable("unexpected intrinsic for Neon base update"); 9523 case Intrinsic::arm_neon_vld1: NewOpc = ARMISD::VLD1_UPD; 9524 NumVecs = 1; break; 9525 case Intrinsic::arm_neon_vld2: NewOpc = ARMISD::VLD2_UPD; 9526 NumVecs = 2; break; 9527 case Intrinsic::arm_neon_vld3: NewOpc = ARMISD::VLD3_UPD; 9528 NumVecs = 3; break; 9529 case Intrinsic::arm_neon_vld4: NewOpc = ARMISD::VLD4_UPD; 9530 NumVecs = 4; break; 9531 case Intrinsic::arm_neon_vld2lane: NewOpc = ARMISD::VLD2LN_UPD; 9532 NumVecs = 2; isLaneOp = true; break; 9533 case Intrinsic::arm_neon_vld3lane: NewOpc = ARMISD::VLD3LN_UPD; 9534 NumVecs = 3; isLaneOp = true; break; 9535 case Intrinsic::arm_neon_vld4lane: NewOpc = ARMISD::VLD4LN_UPD; 9536 NumVecs = 4; isLaneOp = true; break; 9537 case Intrinsic::arm_neon_vst1: NewOpc = ARMISD::VST1_UPD; 9538 NumVecs = 1; isLoadOp = false; break; 9539 case Intrinsic::arm_neon_vst2: NewOpc = ARMISD::VST2_UPD; 9540 NumVecs = 2; isLoadOp = false; break; 9541 case Intrinsic::arm_neon_vst3: NewOpc = ARMISD::VST3_UPD; 9542 NumVecs = 3; isLoadOp = false; break; 9543 case Intrinsic::arm_neon_vst4: NewOpc = ARMISD::VST4_UPD; 9544 NumVecs = 4; isLoadOp = false; break; 9545 case Intrinsic::arm_neon_vst2lane: NewOpc = ARMISD::VST2LN_UPD; 9546 NumVecs = 2; isLoadOp = false; isLaneOp = true; break; 9547 case Intrinsic::arm_neon_vst3lane: NewOpc = ARMISD::VST3LN_UPD; 9548 NumVecs = 3; isLoadOp = false; isLaneOp = true; break; 9549 case Intrinsic::arm_neon_vst4lane: NewOpc = ARMISD::VST4LN_UPD; 9550 NumVecs = 4; isLoadOp = false; isLaneOp = true; break; 9551 } 9552 } else { 9553 isLaneOp = true; 9554 switch (N->getOpcode()) { 9555 default: llvm_unreachable("unexpected opcode for Neon base update"); 9556 case ARMISD::VLD2DUP: NewOpc = ARMISD::VLD2DUP_UPD; NumVecs = 2; break; 9557 case ARMISD::VLD3DUP: NewOpc = ARMISD::VLD3DUP_UPD; NumVecs = 3; break; 9558 case ARMISD::VLD4DUP: NewOpc = ARMISD::VLD4DUP_UPD; NumVecs = 4; break; 9559 case ISD::LOAD: NewOpc = ARMISD::VLD1_UPD; 9560 NumVecs = 1; isLaneOp = false; break; 9561 case ISD::STORE: NewOpc = ARMISD::VST1_UPD; 9562 NumVecs = 1; isLaneOp = false; isLoadOp = false; break; 9563 } 9564 } 9565 9566 // Find the size of memory referenced by the load/store. 9567 EVT VecTy; 9568 if (isLoadOp) { 9569 VecTy = N->getValueType(0); 9570 } else if (isIntrinsic) { 9571 VecTy = N->getOperand(AddrOpIdx+1).getValueType(); 9572 } else { 9573 assert(isStore && "Node has to be a load, a store, or an intrinsic!"); 9574 VecTy = N->getOperand(1).getValueType(); 9575 } 9576 9577 unsigned NumBytes = NumVecs * VecTy.getSizeInBits() / 8; 9578 if (isLaneOp) 9579 NumBytes /= VecTy.getVectorNumElements(); 9580 9581 // If the increment is a constant, it must match the memory ref size. 9582 SDValue Inc = User->getOperand(User->getOperand(0) == Addr ? 1 : 0); 9583 if (ConstantSDNode *CInc = dyn_cast<ConstantSDNode>(Inc.getNode())) { 9584 uint64_t IncVal = CInc->getZExtValue(); 9585 if (IncVal != NumBytes) 9586 continue; 9587 } else if (NumBytes >= 3 * 16) { 9588 // VLD3/4 and VST3/4 for 128-bit vectors are implemented with two 9589 // separate instructions that make it harder to use a non-constant update. 9590 continue; 9591 } 9592 9593 // OK, we found an ADD we can fold into the base update. 9594 // Now, create a _UPD node, taking care of not breaking alignment. 9595 9596 EVT AlignedVecTy = VecTy; 9597 unsigned Alignment = MemN->getAlignment(); 9598 9599 // If this is a less-than-standard-aligned load/store, change the type to 9600 // match the standard alignment. 9601 // The alignment is overlooked when selecting _UPD variants; and it's 9602 // easier to introduce bitcasts here than fix that. 9603 // There are 3 ways to get to this base-update combine: 9604 // - intrinsics: they are assumed to be properly aligned (to the standard 9605 // alignment of the memory type), so we don't need to do anything. 9606 // - ARMISD::VLDx nodes: they are only generated from the aforementioned 9607 // intrinsics, so, likewise, there's nothing to do. 9608 // - generic load/store instructions: the alignment is specified as an 9609 // explicit operand, rather than implicitly as the standard alignment 9610 // of the memory type (like the intrisics). We need to change the 9611 // memory type to match the explicit alignment. That way, we don't 9612 // generate non-standard-aligned ARMISD::VLDx nodes. 9613 if (isa<LSBaseSDNode>(N)) { 9614 if (Alignment == 0) 9615 Alignment = 1; 9616 if (Alignment < VecTy.getScalarSizeInBits() / 8) { 9617 MVT EltTy = MVT::getIntegerVT(Alignment * 8); 9618 assert(NumVecs == 1 && "Unexpected multi-element generic load/store."); 9619 assert(!isLaneOp && "Unexpected generic load/store lane."); 9620 unsigned NumElts = NumBytes / (EltTy.getSizeInBits() / 8); 9621 AlignedVecTy = MVT::getVectorVT(EltTy, NumElts); 9622 } 9623 // Don't set an explicit alignment on regular load/stores that we want 9624 // to transform to VLD/VST 1_UPD nodes. 9625 // This matches the behavior of regular load/stores, which only get an 9626 // explicit alignment if the MMO alignment is larger than the standard 9627 // alignment of the memory type. 9628 // Intrinsics, however, always get an explicit alignment, set to the 9629 // alignment of the MMO. 9630 Alignment = 1; 9631 } 9632 9633 // Create the new updating load/store node. 9634 // First, create an SDVTList for the new updating node's results. 9635 EVT Tys[6]; 9636 unsigned NumResultVecs = (isLoadOp ? NumVecs : 0); 9637 unsigned n; 9638 for (n = 0; n < NumResultVecs; ++n) 9639 Tys[n] = AlignedVecTy; 9640 Tys[n++] = MVT::i32; 9641 Tys[n] = MVT::Other; 9642 SDVTList SDTys = DAG.getVTList(makeArrayRef(Tys, NumResultVecs+2)); 9643 9644 // Then, gather the new node's operands. 9645 SmallVector<SDValue, 8> Ops; 9646 Ops.push_back(N->getOperand(0)); // incoming chain 9647 Ops.push_back(N->getOperand(AddrOpIdx)); 9648 Ops.push_back(Inc); 9649 9650 if (StoreSDNode *StN = dyn_cast<StoreSDNode>(N)) { 9651 // Try to match the intrinsic's signature 9652 Ops.push_back(StN->getValue()); 9653 } else { 9654 // Loads (and of course intrinsics) match the intrinsics' signature, 9655 // so just add all but the alignment operand. 9656 for (unsigned i = AddrOpIdx + 1; i < N->getNumOperands() - 1; ++i) 9657 Ops.push_back(N->getOperand(i)); 9658 } 9659 9660 // For all node types, the alignment operand is always the last one. 9661 Ops.push_back(DAG.getConstant(Alignment, dl, MVT::i32)); 9662 9663 // If this is a non-standard-aligned STORE, the penultimate operand is the 9664 // stored value. Bitcast it to the aligned type. 9665 if (AlignedVecTy != VecTy && N->getOpcode() == ISD::STORE) { 9666 SDValue &StVal = Ops[Ops.size()-2]; 9667 StVal = DAG.getNode(ISD::BITCAST, dl, AlignedVecTy, StVal); 9668 } 9669 9670 SDValue UpdN = DAG.getMemIntrinsicNode(NewOpc, dl, SDTys, 9671 Ops, AlignedVecTy, 9672 MemN->getMemOperand()); 9673 9674 // Update the uses. 9675 SmallVector<SDValue, 5> NewResults; 9676 for (unsigned i = 0; i < NumResultVecs; ++i) 9677 NewResults.push_back(SDValue(UpdN.getNode(), i)); 9678 9679 // If this is an non-standard-aligned LOAD, the first result is the loaded 9680 // value. Bitcast it to the expected result type. 9681 if (AlignedVecTy != VecTy && N->getOpcode() == ISD::LOAD) { 9682 SDValue &LdVal = NewResults[0]; 9683 LdVal = DAG.getNode(ISD::BITCAST, dl, VecTy, LdVal); 9684 } 9685 9686 NewResults.push_back(SDValue(UpdN.getNode(), NumResultVecs+1)); // chain 9687 DCI.CombineTo(N, NewResults); 9688 DCI.CombineTo(User, SDValue(UpdN.getNode(), NumResultVecs)); 9689 9690 break; 9691 } 9692 return SDValue(); 9693 } 9694 9695 static SDValue PerformVLDCombine(SDNode *N, 9696 TargetLowering::DAGCombinerInfo &DCI) { 9697 if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer()) 9698 return SDValue(); 9699 9700 return CombineBaseUpdate(N, DCI); 9701 } 9702 9703 /// CombineVLDDUP - For a VDUPLANE node N, check if its source operand is a 9704 /// vldN-lane (N > 1) intrinsic, and if all the other uses of that intrinsic 9705 /// are also VDUPLANEs. If so, combine them to a vldN-dup operation and 9706 /// return true. 9707 static bool CombineVLDDUP(SDNode *N, TargetLowering::DAGCombinerInfo &DCI) { 9708 SelectionDAG &DAG = DCI.DAG; 9709 EVT VT = N->getValueType(0); 9710 // vldN-dup instructions only support 64-bit vectors for N > 1. 9711 if (!VT.is64BitVector()) 9712 return false; 9713 9714 // Check if the VDUPLANE operand is a vldN-dup intrinsic. 9715 SDNode *VLD = N->getOperand(0).getNode(); 9716 if (VLD->getOpcode() != ISD::INTRINSIC_W_CHAIN) 9717 return false; 9718 unsigned NumVecs = 0; 9719 unsigned NewOpc = 0; 9720 unsigned IntNo = cast<ConstantSDNode>(VLD->getOperand(1))->getZExtValue(); 9721 if (IntNo == Intrinsic::arm_neon_vld2lane) { 9722 NumVecs = 2; 9723 NewOpc = ARMISD::VLD2DUP; 9724 } else if (IntNo == Intrinsic::arm_neon_vld3lane) { 9725 NumVecs = 3; 9726 NewOpc = ARMISD::VLD3DUP; 9727 } else if (IntNo == Intrinsic::arm_neon_vld4lane) { 9728 NumVecs = 4; 9729 NewOpc = ARMISD::VLD4DUP; 9730 } else { 9731 return false; 9732 } 9733 9734 // First check that all the vldN-lane uses are VDUPLANEs and that the lane 9735 // numbers match the load. 9736 unsigned VLDLaneNo = 9737 cast<ConstantSDNode>(VLD->getOperand(NumVecs+3))->getZExtValue(); 9738 for (SDNode::use_iterator UI = VLD->use_begin(), UE = VLD->use_end(); 9739 UI != UE; ++UI) { 9740 // Ignore uses of the chain result. 9741 if (UI.getUse().getResNo() == NumVecs) 9742 continue; 9743 SDNode *User = *UI; 9744 if (User->getOpcode() != ARMISD::VDUPLANE || 9745 VLDLaneNo != cast<ConstantSDNode>(User->getOperand(1))->getZExtValue()) 9746 return false; 9747 } 9748 9749 // Create the vldN-dup node. 9750 EVT Tys[5]; 9751 unsigned n; 9752 for (n = 0; n < NumVecs; ++n) 9753 Tys[n] = VT; 9754 Tys[n] = MVT::Other; 9755 SDVTList SDTys = DAG.getVTList(makeArrayRef(Tys, NumVecs+1)); 9756 SDValue Ops[] = { VLD->getOperand(0), VLD->getOperand(2) }; 9757 MemIntrinsicSDNode *VLDMemInt = cast<MemIntrinsicSDNode>(VLD); 9758 SDValue VLDDup = DAG.getMemIntrinsicNode(NewOpc, SDLoc(VLD), SDTys, 9759 Ops, VLDMemInt->getMemoryVT(), 9760 VLDMemInt->getMemOperand()); 9761 9762 // Update the uses. 9763 for (SDNode::use_iterator UI = VLD->use_begin(), UE = VLD->use_end(); 9764 UI != UE; ++UI) { 9765 unsigned ResNo = UI.getUse().getResNo(); 9766 // Ignore uses of the chain result. 9767 if (ResNo == NumVecs) 9768 continue; 9769 SDNode *User = *UI; 9770 DCI.CombineTo(User, SDValue(VLDDup.getNode(), ResNo)); 9771 } 9772 9773 // Now the vldN-lane intrinsic is dead except for its chain result. 9774 // Update uses of the chain. 9775 std::vector<SDValue> VLDDupResults; 9776 for (unsigned n = 0; n < NumVecs; ++n) 9777 VLDDupResults.push_back(SDValue(VLDDup.getNode(), n)); 9778 VLDDupResults.push_back(SDValue(VLDDup.getNode(), NumVecs)); 9779 DCI.CombineTo(VLD, VLDDupResults); 9780 9781 return true; 9782 } 9783 9784 /// PerformVDUPLANECombine - Target-specific dag combine xforms for 9785 /// ARMISD::VDUPLANE. 9786 static SDValue PerformVDUPLANECombine(SDNode *N, 9787 TargetLowering::DAGCombinerInfo &DCI) { 9788 SDValue Op = N->getOperand(0); 9789 9790 // If the source is a vldN-lane (N > 1) intrinsic, and all the other uses 9791 // of that intrinsic are also VDUPLANEs, combine them to a vldN-dup operation. 9792 if (CombineVLDDUP(N, DCI)) 9793 return SDValue(N, 0); 9794 9795 // If the source is already a VMOVIMM or VMVNIMM splat, the VDUPLANE is 9796 // redundant. Ignore bit_converts for now; element sizes are checked below. 9797 while (Op.getOpcode() == ISD::BITCAST) 9798 Op = Op.getOperand(0); 9799 if (Op.getOpcode() != ARMISD::VMOVIMM && Op.getOpcode() != ARMISD::VMVNIMM) 9800 return SDValue(); 9801 9802 // Make sure the VMOV element size is not bigger than the VDUPLANE elements. 9803 unsigned EltSize = Op.getValueType().getVectorElementType().getSizeInBits(); 9804 // The canonical VMOV for a zero vector uses a 32-bit element size. 9805 unsigned Imm = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue(); 9806 unsigned EltBits; 9807 if (ARM_AM::decodeNEONModImm(Imm, EltBits) == 0) 9808 EltSize = 8; 9809 EVT VT = N->getValueType(0); 9810 if (EltSize > VT.getVectorElementType().getSizeInBits()) 9811 return SDValue(); 9812 9813 return DCI.DAG.getNode(ISD::BITCAST, SDLoc(N), VT, Op); 9814 } 9815 9816 static SDValue PerformLOADCombine(SDNode *N, 9817 TargetLowering::DAGCombinerInfo &DCI) { 9818 EVT VT = N->getValueType(0); 9819 9820 // If this is a legal vector load, try to combine it into a VLD1_UPD. 9821 if (ISD::isNormalLoad(N) && VT.isVector() && 9822 DCI.DAG.getTargetLoweringInfo().isTypeLegal(VT)) 9823 return CombineBaseUpdate(N, DCI); 9824 9825 return SDValue(); 9826 } 9827 9828 /// PerformSTORECombine - Target-specific dag combine xforms for 9829 /// ISD::STORE. 9830 static SDValue PerformSTORECombine(SDNode *N, 9831 TargetLowering::DAGCombinerInfo &DCI) { 9832 StoreSDNode *St = cast<StoreSDNode>(N); 9833 if (St->isVolatile()) 9834 return SDValue(); 9835 9836 // Optimize trunc store (of multiple scalars) to shuffle and store. First, 9837 // pack all of the elements in one place. Next, store to memory in fewer 9838 // chunks. 9839 SDValue StVal = St->getValue(); 9840 EVT VT = StVal.getValueType(); 9841 if (St->isTruncatingStore() && VT.isVector()) { 9842 SelectionDAG &DAG = DCI.DAG; 9843 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 9844 EVT StVT = St->getMemoryVT(); 9845 unsigned NumElems = VT.getVectorNumElements(); 9846 assert(StVT != VT && "Cannot truncate to the same type"); 9847 unsigned FromEltSz = VT.getVectorElementType().getSizeInBits(); 9848 unsigned ToEltSz = StVT.getVectorElementType().getSizeInBits(); 9849 9850 // From, To sizes and ElemCount must be pow of two 9851 if (!isPowerOf2_32(NumElems * FromEltSz * ToEltSz)) return SDValue(); 9852 9853 // We are going to use the original vector elt for storing. 9854 // Accumulated smaller vector elements must be a multiple of the store size. 9855 if (0 != (NumElems * FromEltSz) % ToEltSz) return SDValue(); 9856 9857 unsigned SizeRatio = FromEltSz / ToEltSz; 9858 assert(SizeRatio * NumElems * ToEltSz == VT.getSizeInBits()); 9859 9860 // Create a type on which we perform the shuffle. 9861 EVT WideVecVT = EVT::getVectorVT(*DAG.getContext(), StVT.getScalarType(), 9862 NumElems*SizeRatio); 9863 assert(WideVecVT.getSizeInBits() == VT.getSizeInBits()); 9864 9865 SDLoc DL(St); 9866 SDValue WideVec = DAG.getNode(ISD::BITCAST, DL, WideVecVT, StVal); 9867 SmallVector<int, 8> ShuffleVec(NumElems * SizeRatio, -1); 9868 for (unsigned i = 0; i < NumElems; ++i) 9869 ShuffleVec[i] = DAG.getDataLayout().isBigEndian() 9870 ? (i + 1) * SizeRatio - 1 9871 : i * SizeRatio; 9872 9873 // Can't shuffle using an illegal type. 9874 if (!TLI.isTypeLegal(WideVecVT)) return SDValue(); 9875 9876 SDValue Shuff = DAG.getVectorShuffle(WideVecVT, DL, WideVec, 9877 DAG.getUNDEF(WideVec.getValueType()), 9878 ShuffleVec.data()); 9879 // At this point all of the data is stored at the bottom of the 9880 // register. We now need to save it to mem. 9881 9882 // Find the largest store unit 9883 MVT StoreType = MVT::i8; 9884 for (MVT Tp : MVT::integer_valuetypes()) { 9885 if (TLI.isTypeLegal(Tp) && Tp.getSizeInBits() <= NumElems * ToEltSz) 9886 StoreType = Tp; 9887 } 9888 // Didn't find a legal store type. 9889 if (!TLI.isTypeLegal(StoreType)) 9890 return SDValue(); 9891 9892 // Bitcast the original vector into a vector of store-size units 9893 EVT StoreVecVT = EVT::getVectorVT(*DAG.getContext(), 9894 StoreType, VT.getSizeInBits()/EVT(StoreType).getSizeInBits()); 9895 assert(StoreVecVT.getSizeInBits() == VT.getSizeInBits()); 9896 SDValue ShuffWide = DAG.getNode(ISD::BITCAST, DL, StoreVecVT, Shuff); 9897 SmallVector<SDValue, 8> Chains; 9898 SDValue Increment = DAG.getConstant(StoreType.getSizeInBits() / 8, DL, 9899 TLI.getPointerTy(DAG.getDataLayout())); 9900 SDValue BasePtr = St->getBasePtr(); 9901 9902 // Perform one or more big stores into memory. 9903 unsigned E = (ToEltSz*NumElems)/StoreType.getSizeInBits(); 9904 for (unsigned I = 0; I < E; I++) { 9905 SDValue SubVec = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, 9906 StoreType, ShuffWide, 9907 DAG.getIntPtrConstant(I, DL)); 9908 SDValue Ch = DAG.getStore(St->getChain(), DL, SubVec, BasePtr, 9909 St->getPointerInfo(), St->isVolatile(), 9910 St->isNonTemporal(), St->getAlignment()); 9911 BasePtr = DAG.getNode(ISD::ADD, DL, BasePtr.getValueType(), BasePtr, 9912 Increment); 9913 Chains.push_back(Ch); 9914 } 9915 return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Chains); 9916 } 9917 9918 if (!ISD::isNormalStore(St)) 9919 return SDValue(); 9920 9921 // Split a store of a VMOVDRR into two integer stores to avoid mixing NEON and 9922 // ARM stores of arguments in the same cache line. 9923 if (StVal.getNode()->getOpcode() == ARMISD::VMOVDRR && 9924 StVal.getNode()->hasOneUse()) { 9925 SelectionDAG &DAG = DCI.DAG; 9926 bool isBigEndian = DAG.getDataLayout().isBigEndian(); 9927 SDLoc DL(St); 9928 SDValue BasePtr = St->getBasePtr(); 9929 SDValue NewST1 = DAG.getStore(St->getChain(), DL, 9930 StVal.getNode()->getOperand(isBigEndian ? 1 : 0 ), 9931 BasePtr, St->getPointerInfo(), St->isVolatile(), 9932 St->isNonTemporal(), St->getAlignment()); 9933 9934 SDValue OffsetPtr = DAG.getNode(ISD::ADD, DL, MVT::i32, BasePtr, 9935 DAG.getConstant(4, DL, MVT::i32)); 9936 return DAG.getStore(NewST1.getValue(0), DL, 9937 StVal.getNode()->getOperand(isBigEndian ? 0 : 1), 9938 OffsetPtr, St->getPointerInfo(), St->isVolatile(), 9939 St->isNonTemporal(), 9940 std::min(4U, St->getAlignment() / 2)); 9941 } 9942 9943 if (StVal.getValueType() == MVT::i64 && 9944 StVal.getNode()->getOpcode() == ISD::EXTRACT_VECTOR_ELT) { 9945 9946 // Bitcast an i64 store extracted from a vector to f64. 9947 // Otherwise, the i64 value will be legalized to a pair of i32 values. 9948 SelectionDAG &DAG = DCI.DAG; 9949 SDLoc dl(StVal); 9950 SDValue IntVec = StVal.getOperand(0); 9951 EVT FloatVT = EVT::getVectorVT(*DAG.getContext(), MVT::f64, 9952 IntVec.getValueType().getVectorNumElements()); 9953 SDValue Vec = DAG.getNode(ISD::BITCAST, dl, FloatVT, IntVec); 9954 SDValue ExtElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, 9955 Vec, StVal.getOperand(1)); 9956 dl = SDLoc(N); 9957 SDValue V = DAG.getNode(ISD::BITCAST, dl, MVT::i64, ExtElt); 9958 // Make the DAGCombiner fold the bitcasts. 9959 DCI.AddToWorklist(Vec.getNode()); 9960 DCI.AddToWorklist(ExtElt.getNode()); 9961 DCI.AddToWorklist(V.getNode()); 9962 return DAG.getStore(St->getChain(), dl, V, St->getBasePtr(), 9963 St->getPointerInfo(), St->isVolatile(), 9964 St->isNonTemporal(), St->getAlignment(), 9965 St->getAAInfo()); 9966 } 9967 9968 // If this is a legal vector store, try to combine it into a VST1_UPD. 9969 if (ISD::isNormalStore(N) && VT.isVector() && 9970 DCI.DAG.getTargetLoweringInfo().isTypeLegal(VT)) 9971 return CombineBaseUpdate(N, DCI); 9972 9973 return SDValue(); 9974 } 9975 9976 /// PerformVCVTCombine - VCVT (floating-point to fixed-point, Advanced SIMD) 9977 /// can replace combinations of VMUL and VCVT (floating-point to integer) 9978 /// when the VMUL has a constant operand that is a power of 2. 9979 /// 9980 /// Example (assume d17 = <float 8.000000e+00, float 8.000000e+00>): 9981 /// vmul.f32 d16, d17, d16 9982 /// vcvt.s32.f32 d16, d16 9983 /// becomes: 9984 /// vcvt.s32.f32 d16, d16, #3 9985 static SDValue PerformVCVTCombine(SDNode *N, SelectionDAG &DAG, 9986 const ARMSubtarget *Subtarget) { 9987 if (!Subtarget->hasNEON()) 9988 return SDValue(); 9989 9990 SDValue Op = N->getOperand(0); 9991 if (!Op.getValueType().isVector() || Op.getOpcode() != ISD::FMUL) 9992 return SDValue(); 9993 9994 SDValue ConstVec = Op->getOperand(1); 9995 if (!isa<BuildVectorSDNode>(ConstVec)) 9996 return SDValue(); 9997 9998 MVT FloatTy = Op.getSimpleValueType().getVectorElementType(); 9999 uint32_t FloatBits = FloatTy.getSizeInBits(); 10000 MVT IntTy = N->getSimpleValueType(0).getVectorElementType(); 10001 uint32_t IntBits = IntTy.getSizeInBits(); 10002 unsigned NumLanes = Op.getValueType().getVectorNumElements(); 10003 if (FloatBits != 32 || IntBits > 32 || NumLanes > 4) { 10004 // These instructions only exist converting from f32 to i32. We can handle 10005 // smaller integers by generating an extra truncate, but larger ones would 10006 // be lossy. We also can't handle more then 4 lanes, since these intructions 10007 // only support v2i32/v4i32 types. 10008 return SDValue(); 10009 } 10010 10011 BitVector UndefElements; 10012 BuildVectorSDNode *BV = cast<BuildVectorSDNode>(ConstVec); 10013 int32_t C = BV->getConstantFPSplatPow2ToLog2Int(&UndefElements, 33); 10014 if (C == -1 || C == 0 || C > 32) 10015 return SDValue(); 10016 10017 SDLoc dl(N); 10018 bool isSigned = N->getOpcode() == ISD::FP_TO_SINT; 10019 unsigned IntrinsicOpcode = isSigned ? Intrinsic::arm_neon_vcvtfp2fxs : 10020 Intrinsic::arm_neon_vcvtfp2fxu; 10021 SDValue FixConv = DAG.getNode( 10022 ISD::INTRINSIC_WO_CHAIN, dl, NumLanes == 2 ? MVT::v2i32 : MVT::v4i32, 10023 DAG.getConstant(IntrinsicOpcode, dl, MVT::i32), Op->getOperand(0), 10024 DAG.getConstant(C, dl, MVT::i32)); 10025 10026 if (IntBits < FloatBits) 10027 FixConv = DAG.getNode(ISD::TRUNCATE, dl, N->getValueType(0), FixConv); 10028 10029 return FixConv; 10030 } 10031 10032 /// PerformVDIVCombine - VCVT (fixed-point to floating-point, Advanced SIMD) 10033 /// can replace combinations of VCVT (integer to floating-point) and VDIV 10034 /// when the VDIV has a constant operand that is a power of 2. 10035 /// 10036 /// Example (assume d17 = <float 8.000000e+00, float 8.000000e+00>): 10037 /// vcvt.f32.s32 d16, d16 10038 /// vdiv.f32 d16, d17, d16 10039 /// becomes: 10040 /// vcvt.f32.s32 d16, d16, #3 10041 static SDValue PerformVDIVCombine(SDNode *N, SelectionDAG &DAG, 10042 const ARMSubtarget *Subtarget) { 10043 if (!Subtarget->hasNEON()) 10044 return SDValue(); 10045 10046 SDValue Op = N->getOperand(0); 10047 unsigned OpOpcode = Op.getNode()->getOpcode(); 10048 if (!N->getValueType(0).isVector() || 10049 (OpOpcode != ISD::SINT_TO_FP && OpOpcode != ISD::UINT_TO_FP)) 10050 return SDValue(); 10051 10052 SDValue ConstVec = N->getOperand(1); 10053 if (!isa<BuildVectorSDNode>(ConstVec)) 10054 return SDValue(); 10055 10056 MVT FloatTy = N->getSimpleValueType(0).getVectorElementType(); 10057 uint32_t FloatBits = FloatTy.getSizeInBits(); 10058 MVT IntTy = Op.getOperand(0).getSimpleValueType().getVectorElementType(); 10059 uint32_t IntBits = IntTy.getSizeInBits(); 10060 unsigned NumLanes = Op.getValueType().getVectorNumElements(); 10061 if (FloatBits != 32 || IntBits > 32 || NumLanes > 4) { 10062 // These instructions only exist converting from i32 to f32. We can handle 10063 // smaller integers by generating an extra extend, but larger ones would 10064 // be lossy. We also can't handle more then 4 lanes, since these intructions 10065 // only support v2i32/v4i32 types. 10066 return SDValue(); 10067 } 10068 10069 BitVector UndefElements; 10070 BuildVectorSDNode *BV = cast<BuildVectorSDNode>(ConstVec); 10071 int32_t C = BV->getConstantFPSplatPow2ToLog2Int(&UndefElements, 33); 10072 if (C == -1 || C == 0 || C > 32) 10073 return SDValue(); 10074 10075 SDLoc dl(N); 10076 bool isSigned = OpOpcode == ISD::SINT_TO_FP; 10077 SDValue ConvInput = Op.getOperand(0); 10078 if (IntBits < FloatBits) 10079 ConvInput = DAG.getNode(isSigned ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND, 10080 dl, NumLanes == 2 ? MVT::v2i32 : MVT::v4i32, 10081 ConvInput); 10082 10083 unsigned IntrinsicOpcode = isSigned ? Intrinsic::arm_neon_vcvtfxs2fp : 10084 Intrinsic::arm_neon_vcvtfxu2fp; 10085 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, 10086 Op.getValueType(), 10087 DAG.getConstant(IntrinsicOpcode, dl, MVT::i32), 10088 ConvInput, DAG.getConstant(C, dl, MVT::i32)); 10089 } 10090 10091 /// Getvshiftimm - Check if this is a valid build_vector for the immediate 10092 /// operand of a vector shift operation, where all the elements of the 10093 /// build_vector must have the same constant integer value. 10094 static bool getVShiftImm(SDValue Op, unsigned ElementBits, int64_t &Cnt) { 10095 // Ignore bit_converts. 10096 while (Op.getOpcode() == ISD::BITCAST) 10097 Op = Op.getOperand(0); 10098 BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(Op.getNode()); 10099 APInt SplatBits, SplatUndef; 10100 unsigned SplatBitSize; 10101 bool HasAnyUndefs; 10102 if (! BVN || ! BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, 10103 HasAnyUndefs, ElementBits) || 10104 SplatBitSize > ElementBits) 10105 return false; 10106 Cnt = SplatBits.getSExtValue(); 10107 return true; 10108 } 10109 10110 /// isVShiftLImm - Check if this is a valid build_vector for the immediate 10111 /// operand of a vector shift left operation. That value must be in the range: 10112 /// 0 <= Value < ElementBits for a left shift; or 10113 /// 0 <= Value <= ElementBits for a long left shift. 10114 static bool isVShiftLImm(SDValue Op, EVT VT, bool isLong, int64_t &Cnt) { 10115 assert(VT.isVector() && "vector shift count is not a vector type"); 10116 int64_t ElementBits = VT.getVectorElementType().getSizeInBits(); 10117 if (! getVShiftImm(Op, ElementBits, Cnt)) 10118 return false; 10119 return (Cnt >= 0 && (isLong ? Cnt-1 : Cnt) < ElementBits); 10120 } 10121 10122 /// isVShiftRImm - Check if this is a valid build_vector for the immediate 10123 /// operand of a vector shift right operation. For a shift opcode, the value 10124 /// is positive, but for an intrinsic the value count must be negative. The 10125 /// absolute value must be in the range: 10126 /// 1 <= |Value| <= ElementBits for a right shift; or 10127 /// 1 <= |Value| <= ElementBits/2 for a narrow right shift. 10128 static bool isVShiftRImm(SDValue Op, EVT VT, bool isNarrow, bool isIntrinsic, 10129 int64_t &Cnt) { 10130 assert(VT.isVector() && "vector shift count is not a vector type"); 10131 int64_t ElementBits = VT.getVectorElementType().getSizeInBits(); 10132 if (! getVShiftImm(Op, ElementBits, Cnt)) 10133 return false; 10134 if (!isIntrinsic) 10135 return (Cnt >= 1 && Cnt <= (isNarrow ? ElementBits/2 : ElementBits)); 10136 if (Cnt >= -(isNarrow ? ElementBits/2 : ElementBits) && Cnt <= -1) { 10137 Cnt = -Cnt; 10138 return true; 10139 } 10140 return false; 10141 } 10142 10143 /// PerformIntrinsicCombine - ARM-specific DAG combining for intrinsics. 10144 static SDValue PerformIntrinsicCombine(SDNode *N, SelectionDAG &DAG) { 10145 unsigned IntNo = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue(); 10146 switch (IntNo) { 10147 default: 10148 // Don't do anything for most intrinsics. 10149 break; 10150 10151 case Intrinsic::arm_neon_vabds: 10152 if (!N->getValueType(0).isInteger()) 10153 return SDValue(); 10154 return DAG.getNode(ISD::SABSDIFF, SDLoc(N), N->getValueType(0), 10155 N->getOperand(1), N->getOperand(2)); 10156 case Intrinsic::arm_neon_vabdu: 10157 return DAG.getNode(ISD::UABSDIFF, SDLoc(N), N->getValueType(0), 10158 N->getOperand(1), N->getOperand(2)); 10159 10160 // Vector shifts: check for immediate versions and lower them. 10161 // Note: This is done during DAG combining instead of DAG legalizing because 10162 // the build_vectors for 64-bit vector element shift counts are generally 10163 // not legal, and it is hard to see their values after they get legalized to 10164 // loads from a constant pool. 10165 case Intrinsic::arm_neon_vshifts: 10166 case Intrinsic::arm_neon_vshiftu: 10167 case Intrinsic::arm_neon_vrshifts: 10168 case Intrinsic::arm_neon_vrshiftu: 10169 case Intrinsic::arm_neon_vrshiftn: 10170 case Intrinsic::arm_neon_vqshifts: 10171 case Intrinsic::arm_neon_vqshiftu: 10172 case Intrinsic::arm_neon_vqshiftsu: 10173 case Intrinsic::arm_neon_vqshiftns: 10174 case Intrinsic::arm_neon_vqshiftnu: 10175 case Intrinsic::arm_neon_vqshiftnsu: 10176 case Intrinsic::arm_neon_vqrshiftns: 10177 case Intrinsic::arm_neon_vqrshiftnu: 10178 case Intrinsic::arm_neon_vqrshiftnsu: { 10179 EVT VT = N->getOperand(1).getValueType(); 10180 int64_t Cnt; 10181 unsigned VShiftOpc = 0; 10182 10183 switch (IntNo) { 10184 case Intrinsic::arm_neon_vshifts: 10185 case Intrinsic::arm_neon_vshiftu: 10186 if (isVShiftLImm(N->getOperand(2), VT, false, Cnt)) { 10187 VShiftOpc = ARMISD::VSHL; 10188 break; 10189 } 10190 if (isVShiftRImm(N->getOperand(2), VT, false, true, Cnt)) { 10191 VShiftOpc = (IntNo == Intrinsic::arm_neon_vshifts ? 10192 ARMISD::VSHRs : ARMISD::VSHRu); 10193 break; 10194 } 10195 return SDValue(); 10196 10197 case Intrinsic::arm_neon_vrshifts: 10198 case Intrinsic::arm_neon_vrshiftu: 10199 if (isVShiftRImm(N->getOperand(2), VT, false, true, Cnt)) 10200 break; 10201 return SDValue(); 10202 10203 case Intrinsic::arm_neon_vqshifts: 10204 case Intrinsic::arm_neon_vqshiftu: 10205 if (isVShiftLImm(N->getOperand(2), VT, false, Cnt)) 10206 break; 10207 return SDValue(); 10208 10209 case Intrinsic::arm_neon_vqshiftsu: 10210 if (isVShiftLImm(N->getOperand(2), VT, false, Cnt)) 10211 break; 10212 llvm_unreachable("invalid shift count for vqshlu intrinsic"); 10213 10214 case Intrinsic::arm_neon_vrshiftn: 10215 case Intrinsic::arm_neon_vqshiftns: 10216 case Intrinsic::arm_neon_vqshiftnu: 10217 case Intrinsic::arm_neon_vqshiftnsu: 10218 case Intrinsic::arm_neon_vqrshiftns: 10219 case Intrinsic::arm_neon_vqrshiftnu: 10220 case Intrinsic::arm_neon_vqrshiftnsu: 10221 // Narrowing shifts require an immediate right shift. 10222 if (isVShiftRImm(N->getOperand(2), VT, true, true, Cnt)) 10223 break; 10224 llvm_unreachable("invalid shift count for narrowing vector shift " 10225 "intrinsic"); 10226 10227 default: 10228 llvm_unreachable("unhandled vector shift"); 10229 } 10230 10231 switch (IntNo) { 10232 case Intrinsic::arm_neon_vshifts: 10233 case Intrinsic::arm_neon_vshiftu: 10234 // Opcode already set above. 10235 break; 10236 case Intrinsic::arm_neon_vrshifts: 10237 VShiftOpc = ARMISD::VRSHRs; break; 10238 case Intrinsic::arm_neon_vrshiftu: 10239 VShiftOpc = ARMISD::VRSHRu; break; 10240 case Intrinsic::arm_neon_vrshiftn: 10241 VShiftOpc = ARMISD::VRSHRN; break; 10242 case Intrinsic::arm_neon_vqshifts: 10243 VShiftOpc = ARMISD::VQSHLs; break; 10244 case Intrinsic::arm_neon_vqshiftu: 10245 VShiftOpc = ARMISD::VQSHLu; break; 10246 case Intrinsic::arm_neon_vqshiftsu: 10247 VShiftOpc = ARMISD::VQSHLsu; break; 10248 case Intrinsic::arm_neon_vqshiftns: 10249 VShiftOpc = ARMISD::VQSHRNs; break; 10250 case Intrinsic::arm_neon_vqshiftnu: 10251 VShiftOpc = ARMISD::VQSHRNu; break; 10252 case Intrinsic::arm_neon_vqshiftnsu: 10253 VShiftOpc = ARMISD::VQSHRNsu; break; 10254 case Intrinsic::arm_neon_vqrshiftns: 10255 VShiftOpc = ARMISD::VQRSHRNs; break; 10256 case Intrinsic::arm_neon_vqrshiftnu: 10257 VShiftOpc = ARMISD::VQRSHRNu; break; 10258 case Intrinsic::arm_neon_vqrshiftnsu: 10259 VShiftOpc = ARMISD::VQRSHRNsu; break; 10260 } 10261 10262 SDLoc dl(N); 10263 return DAG.getNode(VShiftOpc, dl, N->getValueType(0), 10264 N->getOperand(1), DAG.getConstant(Cnt, dl, MVT::i32)); 10265 } 10266 10267 case Intrinsic::arm_neon_vshiftins: { 10268 EVT VT = N->getOperand(1).getValueType(); 10269 int64_t Cnt; 10270 unsigned VShiftOpc = 0; 10271 10272 if (isVShiftLImm(N->getOperand(3), VT, false, Cnt)) 10273 VShiftOpc = ARMISD::VSLI; 10274 else if (isVShiftRImm(N->getOperand(3), VT, false, true, Cnt)) 10275 VShiftOpc = ARMISD::VSRI; 10276 else { 10277 llvm_unreachable("invalid shift count for vsli/vsri intrinsic"); 10278 } 10279 10280 SDLoc dl(N); 10281 return DAG.getNode(VShiftOpc, dl, N->getValueType(0), 10282 N->getOperand(1), N->getOperand(2), 10283 DAG.getConstant(Cnt, dl, MVT::i32)); 10284 } 10285 10286 case Intrinsic::arm_neon_vqrshifts: 10287 case Intrinsic::arm_neon_vqrshiftu: 10288 // No immediate versions of these to check for. 10289 break; 10290 } 10291 10292 return SDValue(); 10293 } 10294 10295 /// PerformShiftCombine - Checks for immediate versions of vector shifts and 10296 /// lowers them. As with the vector shift intrinsics, this is done during DAG 10297 /// combining instead of DAG legalizing because the build_vectors for 64-bit 10298 /// vector element shift counts are generally not legal, and it is hard to see 10299 /// their values after they get legalized to loads from a constant pool. 10300 static SDValue PerformShiftCombine(SDNode *N, SelectionDAG &DAG, 10301 const ARMSubtarget *ST) { 10302 EVT VT = N->getValueType(0); 10303 if (N->getOpcode() == ISD::SRL && VT == MVT::i32 && ST->hasV6Ops()) { 10304 // Canonicalize (srl (bswap x), 16) to (rotr (bswap x), 16) if the high 10305 // 16-bits of x is zero. This optimizes rev + lsr 16 to rev16. 10306 SDValue N1 = N->getOperand(1); 10307 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(N1)) { 10308 SDValue N0 = N->getOperand(0); 10309 if (C->getZExtValue() == 16 && N0.getOpcode() == ISD::BSWAP && 10310 DAG.MaskedValueIsZero(N0.getOperand(0), 10311 APInt::getHighBitsSet(32, 16))) 10312 return DAG.getNode(ISD::ROTR, SDLoc(N), VT, N0, N1); 10313 } 10314 } 10315 10316 // Nothing to be done for scalar shifts. 10317 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 10318 if (!VT.isVector() || !TLI.isTypeLegal(VT)) 10319 return SDValue(); 10320 10321 assert(ST->hasNEON() && "unexpected vector shift"); 10322 int64_t Cnt; 10323 10324 switch (N->getOpcode()) { 10325 default: llvm_unreachable("unexpected shift opcode"); 10326 10327 case ISD::SHL: 10328 if (isVShiftLImm(N->getOperand(1), VT, false, Cnt)) { 10329 SDLoc dl(N); 10330 return DAG.getNode(ARMISD::VSHL, dl, VT, N->getOperand(0), 10331 DAG.getConstant(Cnt, dl, MVT::i32)); 10332 } 10333 break; 10334 10335 case ISD::SRA: 10336 case ISD::SRL: 10337 if (isVShiftRImm(N->getOperand(1), VT, false, false, Cnt)) { 10338 unsigned VShiftOpc = (N->getOpcode() == ISD::SRA ? 10339 ARMISD::VSHRs : ARMISD::VSHRu); 10340 SDLoc dl(N); 10341 return DAG.getNode(VShiftOpc, dl, VT, N->getOperand(0), 10342 DAG.getConstant(Cnt, dl, MVT::i32)); 10343 } 10344 } 10345 return SDValue(); 10346 } 10347 10348 /// PerformExtendCombine - Target-specific DAG combining for ISD::SIGN_EXTEND, 10349 /// ISD::ZERO_EXTEND, and ISD::ANY_EXTEND. 10350 static SDValue PerformExtendCombine(SDNode *N, SelectionDAG &DAG, 10351 const ARMSubtarget *ST) { 10352 SDValue N0 = N->getOperand(0); 10353 10354 // Check for sign- and zero-extensions of vector extract operations of 8- 10355 // and 16-bit vector elements. NEON supports these directly. They are 10356 // handled during DAG combining because type legalization will promote them 10357 // to 32-bit types and it is messy to recognize the operations after that. 10358 if (ST->hasNEON() && N0.getOpcode() == ISD::EXTRACT_VECTOR_ELT) { 10359 SDValue Vec = N0.getOperand(0); 10360 SDValue Lane = N0.getOperand(1); 10361 EVT VT = N->getValueType(0); 10362 EVT EltVT = N0.getValueType(); 10363 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 10364 10365 if (VT == MVT::i32 && 10366 (EltVT == MVT::i8 || EltVT == MVT::i16) && 10367 TLI.isTypeLegal(Vec.getValueType()) && 10368 isa<ConstantSDNode>(Lane)) { 10369 10370 unsigned Opc = 0; 10371 switch (N->getOpcode()) { 10372 default: llvm_unreachable("unexpected opcode"); 10373 case ISD::SIGN_EXTEND: 10374 Opc = ARMISD::VGETLANEs; 10375 break; 10376 case ISD::ZERO_EXTEND: 10377 case ISD::ANY_EXTEND: 10378 Opc = ARMISD::VGETLANEu; 10379 break; 10380 } 10381 return DAG.getNode(Opc, SDLoc(N), VT, Vec, Lane); 10382 } 10383 } 10384 10385 return SDValue(); 10386 } 10387 10388 static void computeKnownBits(SelectionDAG &DAG, SDValue Op, APInt &KnownZero, 10389 APInt &KnownOne) { 10390 if (Op.getOpcode() == ARMISD::BFI) { 10391 // Conservatively, we can recurse down the first operand 10392 // and just mask out all affected bits. 10393 computeKnownBits(DAG, Op.getOperand(0), KnownZero, KnownOne); 10394 10395 // The operand to BFI is already a mask suitable for removing the bits it 10396 // sets. 10397 ConstantSDNode *CI = cast<ConstantSDNode>(Op.getOperand(2)); 10398 APInt Mask = CI->getAPIntValue(); 10399 KnownZero &= Mask; 10400 KnownOne &= Mask; 10401 return; 10402 } 10403 if (Op.getOpcode() == ARMISD::CMOV) { 10404 APInt KZ2(KnownZero.getBitWidth(), 0); 10405 APInt KO2(KnownOne.getBitWidth(), 0); 10406 computeKnownBits(DAG, Op.getOperand(1), KnownZero, KnownOne); 10407 computeKnownBits(DAG, Op.getOperand(2), KZ2, KO2); 10408 10409 KnownZero &= KZ2; 10410 KnownOne &= KO2; 10411 return; 10412 } 10413 return DAG.computeKnownBits(Op, KnownZero, KnownOne); 10414 } 10415 10416 SDValue ARMTargetLowering::PerformCMOVToBFICombine(SDNode *CMOV, SelectionDAG &DAG) const { 10417 // If we have a CMOV, OR and AND combination such as: 10418 // if (x & CN) 10419 // y |= CM; 10420 // 10421 // And: 10422 // * CN is a single bit; 10423 // * All bits covered by CM are known zero in y 10424 // 10425 // Then we can convert this into a sequence of BFI instructions. This will 10426 // always be a win if CM is a single bit, will always be no worse than the 10427 // TST&OR sequence if CM is two bits, and for thumb will be no worse if CM is 10428 // three bits (due to the extra IT instruction). 10429 10430 SDValue Op0 = CMOV->getOperand(0); 10431 SDValue Op1 = CMOV->getOperand(1); 10432 auto CCNode = cast<ConstantSDNode>(CMOV->getOperand(2)); 10433 auto CC = CCNode->getAPIntValue().getLimitedValue(); 10434 SDValue CmpZ = CMOV->getOperand(4); 10435 10436 // The compare must be against zero. 10437 if (!isNullConstant(CmpZ->getOperand(1))) 10438 return SDValue(); 10439 10440 assert(CmpZ->getOpcode() == ARMISD::CMPZ); 10441 SDValue And = CmpZ->getOperand(0); 10442 if (And->getOpcode() != ISD::AND) 10443 return SDValue(); 10444 ConstantSDNode *AndC = dyn_cast<ConstantSDNode>(And->getOperand(1)); 10445 if (!AndC || !AndC->getAPIntValue().isPowerOf2()) 10446 return SDValue(); 10447 SDValue X = And->getOperand(0); 10448 10449 if (CC == ARMCC::EQ) { 10450 // We're performing an "equal to zero" compare. Swap the operands so we 10451 // canonicalize on a "not equal to zero" compare. 10452 std::swap(Op0, Op1); 10453 } else { 10454 assert(CC == ARMCC::NE && "How can a CMPZ node not be EQ or NE?"); 10455 } 10456 10457 if (Op1->getOpcode() != ISD::OR) 10458 return SDValue(); 10459 10460 ConstantSDNode *OrC = dyn_cast<ConstantSDNode>(Op1->getOperand(1)); 10461 if (!OrC) 10462 return SDValue(); 10463 SDValue Y = Op1->getOperand(0); 10464 10465 if (Op0 != Y) 10466 return SDValue(); 10467 10468 // Now, is it profitable to continue? 10469 APInt OrCI = OrC->getAPIntValue(); 10470 unsigned Heuristic = Subtarget->isThumb() ? 3 : 2; 10471 if (OrCI.countPopulation() > Heuristic) 10472 return SDValue(); 10473 10474 // Lastly, can we determine that the bits defined by OrCI 10475 // are zero in Y? 10476 APInt KnownZero, KnownOne; 10477 computeKnownBits(DAG, Y, KnownZero, KnownOne); 10478 if ((OrCI & KnownZero) != OrCI) 10479 return SDValue(); 10480 10481 // OK, we can do the combine. 10482 SDValue V = Y; 10483 SDLoc dl(X); 10484 EVT VT = X.getValueType(); 10485 unsigned BitInX = AndC->getAPIntValue().logBase2(); 10486 10487 if (BitInX != 0) { 10488 // We must shift X first. 10489 X = DAG.getNode(ISD::SRL, dl, VT, X, 10490 DAG.getConstant(BitInX, dl, VT)); 10491 } 10492 10493 for (unsigned BitInY = 0, NumActiveBits = OrCI.getActiveBits(); 10494 BitInY < NumActiveBits; ++BitInY) { 10495 if (OrCI[BitInY] == 0) 10496 continue; 10497 APInt Mask(VT.getSizeInBits(), 0); 10498 Mask.setBit(BitInY); 10499 V = DAG.getNode(ARMISD::BFI, dl, VT, V, X, 10500 // Confusingly, the operand is an *inverted* mask. 10501 DAG.getConstant(~Mask, dl, VT)); 10502 } 10503 10504 return V; 10505 } 10506 10507 /// PerformCMOVCombine - Target-specific DAG combining for ARMISD::CMOV. 10508 SDValue 10509 ARMTargetLowering::PerformCMOVCombine(SDNode *N, SelectionDAG &DAG) const { 10510 SDValue Cmp = N->getOperand(4); 10511 if (Cmp.getOpcode() != ARMISD::CMPZ) 10512 // Only looking at EQ and NE cases. 10513 return SDValue(); 10514 10515 EVT VT = N->getValueType(0); 10516 SDLoc dl(N); 10517 SDValue LHS = Cmp.getOperand(0); 10518 SDValue RHS = Cmp.getOperand(1); 10519 SDValue FalseVal = N->getOperand(0); 10520 SDValue TrueVal = N->getOperand(1); 10521 SDValue ARMcc = N->getOperand(2); 10522 ARMCC::CondCodes CC = 10523 (ARMCC::CondCodes)cast<ConstantSDNode>(ARMcc)->getZExtValue(); 10524 10525 // BFI is only available on V6T2+. 10526 if (!Subtarget->isThumb1Only() && Subtarget->hasV6T2Ops()) { 10527 SDValue R = PerformCMOVToBFICombine(N, DAG); 10528 if (R) 10529 return R; 10530 } 10531 10532 // Simplify 10533 // mov r1, r0 10534 // cmp r1, x 10535 // mov r0, y 10536 // moveq r0, x 10537 // to 10538 // cmp r0, x 10539 // movne r0, y 10540 // 10541 // mov r1, r0 10542 // cmp r1, x 10543 // mov r0, x 10544 // movne r0, y 10545 // to 10546 // cmp r0, x 10547 // movne r0, y 10548 /// FIXME: Turn this into a target neutral optimization? 10549 SDValue Res; 10550 if (CC == ARMCC::NE && FalseVal == RHS && FalseVal != LHS) { 10551 Res = DAG.getNode(ARMISD::CMOV, dl, VT, LHS, TrueVal, ARMcc, 10552 N->getOperand(3), Cmp); 10553 } else if (CC == ARMCC::EQ && TrueVal == RHS) { 10554 SDValue ARMcc; 10555 SDValue NewCmp = getARMCmp(LHS, RHS, ISD::SETNE, ARMcc, DAG, dl); 10556 Res = DAG.getNode(ARMISD::CMOV, dl, VT, LHS, FalseVal, ARMcc, 10557 N->getOperand(3), NewCmp); 10558 } 10559 10560 if (Res.getNode()) { 10561 APInt KnownZero, KnownOne; 10562 DAG.computeKnownBits(SDValue(N,0), KnownZero, KnownOne); 10563 // Capture demanded bits information that would be otherwise lost. 10564 if (KnownZero == 0xfffffffe) 10565 Res = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Res, 10566 DAG.getValueType(MVT::i1)); 10567 else if (KnownZero == 0xffffff00) 10568 Res = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Res, 10569 DAG.getValueType(MVT::i8)); 10570 else if (KnownZero == 0xffff0000) 10571 Res = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Res, 10572 DAG.getValueType(MVT::i16)); 10573 } 10574 10575 return Res; 10576 } 10577 10578 SDValue ARMTargetLowering::PerformDAGCombine(SDNode *N, 10579 DAGCombinerInfo &DCI) const { 10580 switch (N->getOpcode()) { 10581 default: break; 10582 case ISD::ADDC: return PerformADDCCombine(N, DCI, Subtarget); 10583 case ISD::ADD: return PerformADDCombine(N, DCI, Subtarget); 10584 case ISD::SUB: return PerformSUBCombine(N, DCI); 10585 case ISD::MUL: return PerformMULCombine(N, DCI, Subtarget); 10586 case ISD::OR: return PerformORCombine(N, DCI, Subtarget); 10587 case ISD::XOR: return PerformXORCombine(N, DCI, Subtarget); 10588 case ISD::AND: return PerformANDCombine(N, DCI, Subtarget); 10589 case ARMISD::BFI: return PerformBFICombine(N, DCI); 10590 case ARMISD::VMOVRRD: return PerformVMOVRRDCombine(N, DCI, Subtarget); 10591 case ARMISD::VMOVDRR: return PerformVMOVDRRCombine(N, DCI.DAG); 10592 case ISD::STORE: return PerformSTORECombine(N, DCI); 10593 case ISD::BUILD_VECTOR: return PerformBUILD_VECTORCombine(N, DCI, Subtarget); 10594 case ISD::INSERT_VECTOR_ELT: return PerformInsertEltCombine(N, DCI); 10595 case ISD::VECTOR_SHUFFLE: return PerformVECTOR_SHUFFLECombine(N, DCI.DAG); 10596 case ARMISD::VDUPLANE: return PerformVDUPLANECombine(N, DCI); 10597 case ISD::FP_TO_SINT: 10598 case ISD::FP_TO_UINT: 10599 return PerformVCVTCombine(N, DCI.DAG, Subtarget); 10600 case ISD::FDIV: 10601 return PerformVDIVCombine(N, DCI.DAG, Subtarget); 10602 case ISD::INTRINSIC_WO_CHAIN: return PerformIntrinsicCombine(N, DCI.DAG); 10603 case ISD::SHL: 10604 case ISD::SRA: 10605 case ISD::SRL: return PerformShiftCombine(N, DCI.DAG, Subtarget); 10606 case ISD::SIGN_EXTEND: 10607 case ISD::ZERO_EXTEND: 10608 case ISD::ANY_EXTEND: return PerformExtendCombine(N, DCI.DAG, Subtarget); 10609 case ARMISD::CMOV: return PerformCMOVCombine(N, DCI.DAG); 10610 case ISD::LOAD: return PerformLOADCombine(N, DCI); 10611 case ARMISD::VLD2DUP: 10612 case ARMISD::VLD3DUP: 10613 case ARMISD::VLD4DUP: 10614 return PerformVLDCombine(N, DCI); 10615 case ARMISD::BUILD_VECTOR: 10616 return PerformARMBUILD_VECTORCombine(N, DCI); 10617 case ISD::INTRINSIC_VOID: 10618 case ISD::INTRINSIC_W_CHAIN: 10619 switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) { 10620 case Intrinsic::arm_neon_vld1: 10621 case Intrinsic::arm_neon_vld2: 10622 case Intrinsic::arm_neon_vld3: 10623 case Intrinsic::arm_neon_vld4: 10624 case Intrinsic::arm_neon_vld2lane: 10625 case Intrinsic::arm_neon_vld3lane: 10626 case Intrinsic::arm_neon_vld4lane: 10627 case Intrinsic::arm_neon_vst1: 10628 case Intrinsic::arm_neon_vst2: 10629 case Intrinsic::arm_neon_vst3: 10630 case Intrinsic::arm_neon_vst4: 10631 case Intrinsic::arm_neon_vst2lane: 10632 case Intrinsic::arm_neon_vst3lane: 10633 case Intrinsic::arm_neon_vst4lane: 10634 return PerformVLDCombine(N, DCI); 10635 default: break; 10636 } 10637 break; 10638 } 10639 return SDValue(); 10640 } 10641 10642 bool ARMTargetLowering::isDesirableToTransformToIntegerOp(unsigned Opc, 10643 EVT VT) const { 10644 return (VT == MVT::f32) && (Opc == ISD::LOAD || Opc == ISD::STORE); 10645 } 10646 10647 bool ARMTargetLowering::allowsMisalignedMemoryAccesses(EVT VT, 10648 unsigned, 10649 unsigned, 10650 bool *Fast) const { 10651 // The AllowsUnaliged flag models the SCTLR.A setting in ARM cpus 10652 bool AllowsUnaligned = Subtarget->allowsUnalignedMem(); 10653 10654 switch (VT.getSimpleVT().SimpleTy) { 10655 default: 10656 return false; 10657 case MVT::i8: 10658 case MVT::i16: 10659 case MVT::i32: { 10660 // Unaligned access can use (for example) LRDB, LRDH, LDR 10661 if (AllowsUnaligned) { 10662 if (Fast) 10663 *Fast = Subtarget->hasV7Ops(); 10664 return true; 10665 } 10666 return false; 10667 } 10668 case MVT::f64: 10669 case MVT::v2f64: { 10670 // For any little-endian targets with neon, we can support unaligned ld/st 10671 // of D and Q (e.g. {D0,D1}) registers by using vld1.i8/vst1.i8. 10672 // A big-endian target may also explicitly support unaligned accesses 10673 if (Subtarget->hasNEON() && (AllowsUnaligned || Subtarget->isLittle())) { 10674 if (Fast) 10675 *Fast = true; 10676 return true; 10677 } 10678 return false; 10679 } 10680 } 10681 } 10682 10683 static bool memOpAlign(unsigned DstAlign, unsigned SrcAlign, 10684 unsigned AlignCheck) { 10685 return ((SrcAlign == 0 || SrcAlign % AlignCheck == 0) && 10686 (DstAlign == 0 || DstAlign % AlignCheck == 0)); 10687 } 10688 10689 EVT ARMTargetLowering::getOptimalMemOpType(uint64_t Size, 10690 unsigned DstAlign, unsigned SrcAlign, 10691 bool IsMemset, bool ZeroMemset, 10692 bool MemcpyStrSrc, 10693 MachineFunction &MF) const { 10694 const Function *F = MF.getFunction(); 10695 10696 // See if we can use NEON instructions for this... 10697 if ((!IsMemset || ZeroMemset) && Subtarget->hasNEON() && 10698 !F->hasFnAttribute(Attribute::NoImplicitFloat)) { 10699 bool Fast; 10700 if (Size >= 16 && 10701 (memOpAlign(SrcAlign, DstAlign, 16) || 10702 (allowsMisalignedMemoryAccesses(MVT::v2f64, 0, 1, &Fast) && Fast))) { 10703 return MVT::v2f64; 10704 } else if (Size >= 8 && 10705 (memOpAlign(SrcAlign, DstAlign, 8) || 10706 (allowsMisalignedMemoryAccesses(MVT::f64, 0, 1, &Fast) && 10707 Fast))) { 10708 return MVT::f64; 10709 } 10710 } 10711 10712 // Lowering to i32/i16 if the size permits. 10713 if (Size >= 4) 10714 return MVT::i32; 10715 else if (Size >= 2) 10716 return MVT::i16; 10717 10718 // Let the target-independent logic figure it out. 10719 return MVT::Other; 10720 } 10721 10722 bool ARMTargetLowering::isZExtFree(SDValue Val, EVT VT2) const { 10723 if (Val.getOpcode() != ISD::LOAD) 10724 return false; 10725 10726 EVT VT1 = Val.getValueType(); 10727 if (!VT1.isSimple() || !VT1.isInteger() || 10728 !VT2.isSimple() || !VT2.isInteger()) 10729 return false; 10730 10731 switch (VT1.getSimpleVT().SimpleTy) { 10732 default: break; 10733 case MVT::i1: 10734 case MVT::i8: 10735 case MVT::i16: 10736 // 8-bit and 16-bit loads implicitly zero-extend to 32-bits. 10737 return true; 10738 } 10739 10740 return false; 10741 } 10742 10743 bool ARMTargetLowering::isVectorLoadExtDesirable(SDValue ExtVal) const { 10744 EVT VT = ExtVal.getValueType(); 10745 10746 if (!isTypeLegal(VT)) 10747 return false; 10748 10749 // Don't create a loadext if we can fold the extension into a wide/long 10750 // instruction. 10751 // If there's more than one user instruction, the loadext is desirable no 10752 // matter what. There can be two uses by the same instruction. 10753 if (ExtVal->use_empty() || 10754 !ExtVal->use_begin()->isOnlyUserOf(ExtVal.getNode())) 10755 return true; 10756 10757 SDNode *U = *ExtVal->use_begin(); 10758 if ((U->getOpcode() == ISD::ADD || U->getOpcode() == ISD::SUB || 10759 U->getOpcode() == ISD::SHL || U->getOpcode() == ARMISD::VSHL)) 10760 return false; 10761 10762 return true; 10763 } 10764 10765 bool ARMTargetLowering::allowTruncateForTailCall(Type *Ty1, Type *Ty2) const { 10766 if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy()) 10767 return false; 10768 10769 if (!isTypeLegal(EVT::getEVT(Ty1))) 10770 return false; 10771 10772 assert(Ty1->getPrimitiveSizeInBits() <= 64 && "i128 is probably not a noop"); 10773 10774 // Assuming the caller doesn't have a zeroext or signext return parameter, 10775 // truncation all the way down to i1 is valid. 10776 return true; 10777 } 10778 10779 10780 static bool isLegalT1AddressImmediate(int64_t V, EVT VT) { 10781 if (V < 0) 10782 return false; 10783 10784 unsigned Scale = 1; 10785 switch (VT.getSimpleVT().SimpleTy) { 10786 default: return false; 10787 case MVT::i1: 10788 case MVT::i8: 10789 // Scale == 1; 10790 break; 10791 case MVT::i16: 10792 // Scale == 2; 10793 Scale = 2; 10794 break; 10795 case MVT::i32: 10796 // Scale == 4; 10797 Scale = 4; 10798 break; 10799 } 10800 10801 if ((V & (Scale - 1)) != 0) 10802 return false; 10803 V /= Scale; 10804 return V == (V & ((1LL << 5) - 1)); 10805 } 10806 10807 static bool isLegalT2AddressImmediate(int64_t V, EVT VT, 10808 const ARMSubtarget *Subtarget) { 10809 bool isNeg = false; 10810 if (V < 0) { 10811 isNeg = true; 10812 V = - V; 10813 } 10814 10815 switch (VT.getSimpleVT().SimpleTy) { 10816 default: return false; 10817 case MVT::i1: 10818 case MVT::i8: 10819 case MVT::i16: 10820 case MVT::i32: 10821 // + imm12 or - imm8 10822 if (isNeg) 10823 return V == (V & ((1LL << 8) - 1)); 10824 return V == (V & ((1LL << 12) - 1)); 10825 case MVT::f32: 10826 case MVT::f64: 10827 // Same as ARM mode. FIXME: NEON? 10828 if (!Subtarget->hasVFP2()) 10829 return false; 10830 if ((V & 3) != 0) 10831 return false; 10832 V >>= 2; 10833 return V == (V & ((1LL << 8) - 1)); 10834 } 10835 } 10836 10837 /// isLegalAddressImmediate - Return true if the integer value can be used 10838 /// as the offset of the target addressing mode for load / store of the 10839 /// given type. 10840 static bool isLegalAddressImmediate(int64_t V, EVT VT, 10841 const ARMSubtarget *Subtarget) { 10842 if (V == 0) 10843 return true; 10844 10845 if (!VT.isSimple()) 10846 return false; 10847 10848 if (Subtarget->isThumb1Only()) 10849 return isLegalT1AddressImmediate(V, VT); 10850 else if (Subtarget->isThumb2()) 10851 return isLegalT2AddressImmediate(V, VT, Subtarget); 10852 10853 // ARM mode. 10854 if (V < 0) 10855 V = - V; 10856 switch (VT.getSimpleVT().SimpleTy) { 10857 default: return false; 10858 case MVT::i1: 10859 case MVT::i8: 10860 case MVT::i32: 10861 // +- imm12 10862 return V == (V & ((1LL << 12) - 1)); 10863 case MVT::i16: 10864 // +- imm8 10865 return V == (V & ((1LL << 8) - 1)); 10866 case MVT::f32: 10867 case MVT::f64: 10868 if (!Subtarget->hasVFP2()) // FIXME: NEON? 10869 return false; 10870 if ((V & 3) != 0) 10871 return false; 10872 V >>= 2; 10873 return V == (V & ((1LL << 8) - 1)); 10874 } 10875 } 10876 10877 bool ARMTargetLowering::isLegalT2ScaledAddressingMode(const AddrMode &AM, 10878 EVT VT) const { 10879 int Scale = AM.Scale; 10880 if (Scale < 0) 10881 return false; 10882 10883 switch (VT.getSimpleVT().SimpleTy) { 10884 default: return false; 10885 case MVT::i1: 10886 case MVT::i8: 10887 case MVT::i16: 10888 case MVT::i32: 10889 if (Scale == 1) 10890 return true; 10891 // r + r << imm 10892 Scale = Scale & ~1; 10893 return Scale == 2 || Scale == 4 || Scale == 8; 10894 case MVT::i64: 10895 // r + r 10896 if (((unsigned)AM.HasBaseReg + Scale) <= 2) 10897 return true; 10898 return false; 10899 case MVT::isVoid: 10900 // Note, we allow "void" uses (basically, uses that aren't loads or 10901 // stores), because arm allows folding a scale into many arithmetic 10902 // operations. This should be made more precise and revisited later. 10903 10904 // Allow r << imm, but the imm has to be a multiple of two. 10905 if (Scale & 1) return false; 10906 return isPowerOf2_32(Scale); 10907 } 10908 } 10909 10910 /// isLegalAddressingMode - Return true if the addressing mode represented 10911 /// by AM is legal for this target, for a load/store of the specified type. 10912 bool ARMTargetLowering::isLegalAddressingMode(const DataLayout &DL, 10913 const AddrMode &AM, Type *Ty, 10914 unsigned AS) const { 10915 EVT VT = getValueType(DL, Ty, true); 10916 if (!isLegalAddressImmediate(AM.BaseOffs, VT, Subtarget)) 10917 return false; 10918 10919 // Can never fold addr of global into load/store. 10920 if (AM.BaseGV) 10921 return false; 10922 10923 switch (AM.Scale) { 10924 case 0: // no scale reg, must be "r+i" or "r", or "i". 10925 break; 10926 case 1: 10927 if (Subtarget->isThumb1Only()) 10928 return false; 10929 // FALL THROUGH. 10930 default: 10931 // ARM doesn't support any R+R*scale+imm addr modes. 10932 if (AM.BaseOffs) 10933 return false; 10934 10935 if (!VT.isSimple()) 10936 return false; 10937 10938 if (Subtarget->isThumb2()) 10939 return isLegalT2ScaledAddressingMode(AM, VT); 10940 10941 int Scale = AM.Scale; 10942 switch (VT.getSimpleVT().SimpleTy) { 10943 default: return false; 10944 case MVT::i1: 10945 case MVT::i8: 10946 case MVT::i32: 10947 if (Scale < 0) Scale = -Scale; 10948 if (Scale == 1) 10949 return true; 10950 // r + r << imm 10951 return isPowerOf2_32(Scale & ~1); 10952 case MVT::i16: 10953 case MVT::i64: 10954 // r + r 10955 if (((unsigned)AM.HasBaseReg + Scale) <= 2) 10956 return true; 10957 return false; 10958 10959 case MVT::isVoid: 10960 // Note, we allow "void" uses (basically, uses that aren't loads or 10961 // stores), because arm allows folding a scale into many arithmetic 10962 // operations. This should be made more precise and revisited later. 10963 10964 // Allow r << imm, but the imm has to be a multiple of two. 10965 if (Scale & 1) return false; 10966 return isPowerOf2_32(Scale); 10967 } 10968 } 10969 return true; 10970 } 10971 10972 /// isLegalICmpImmediate - Return true if the specified immediate is legal 10973 /// icmp immediate, that is the target has icmp instructions which can compare 10974 /// a register against the immediate without having to materialize the 10975 /// immediate into a register. 10976 bool ARMTargetLowering::isLegalICmpImmediate(int64_t Imm) const { 10977 // Thumb2 and ARM modes can use cmn for negative immediates. 10978 if (!Subtarget->isThumb()) 10979 return ARM_AM::getSOImmVal(std::abs(Imm)) != -1; 10980 if (Subtarget->isThumb2()) 10981 return ARM_AM::getT2SOImmVal(std::abs(Imm)) != -1; 10982 // Thumb1 doesn't have cmn, and only 8-bit immediates. 10983 return Imm >= 0 && Imm <= 255; 10984 } 10985 10986 /// isLegalAddImmediate - Return true if the specified immediate is a legal add 10987 /// *or sub* immediate, that is the target has add or sub instructions which can 10988 /// add a register with the immediate without having to materialize the 10989 /// immediate into a register. 10990 bool ARMTargetLowering::isLegalAddImmediate(int64_t Imm) const { 10991 // Same encoding for add/sub, just flip the sign. 10992 int64_t AbsImm = std::abs(Imm); 10993 if (!Subtarget->isThumb()) 10994 return ARM_AM::getSOImmVal(AbsImm) != -1; 10995 if (Subtarget->isThumb2()) 10996 return ARM_AM::getT2SOImmVal(AbsImm) != -1; 10997 // Thumb1 only has 8-bit unsigned immediate. 10998 return AbsImm >= 0 && AbsImm <= 255; 10999 } 11000 11001 static bool getARMIndexedAddressParts(SDNode *Ptr, EVT VT, 11002 bool isSEXTLoad, SDValue &Base, 11003 SDValue &Offset, bool &isInc, 11004 SelectionDAG &DAG) { 11005 if (Ptr->getOpcode() != ISD::ADD && Ptr->getOpcode() != ISD::SUB) 11006 return false; 11007 11008 if (VT == MVT::i16 || ((VT == MVT::i8 || VT == MVT::i1) && isSEXTLoad)) { 11009 // AddressingMode 3 11010 Base = Ptr->getOperand(0); 11011 if (ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(Ptr->getOperand(1))) { 11012 int RHSC = (int)RHS->getZExtValue(); 11013 if (RHSC < 0 && RHSC > -256) { 11014 assert(Ptr->getOpcode() == ISD::ADD); 11015 isInc = false; 11016 Offset = DAG.getConstant(-RHSC, SDLoc(Ptr), RHS->getValueType(0)); 11017 return true; 11018 } 11019 } 11020 isInc = (Ptr->getOpcode() == ISD::ADD); 11021 Offset = Ptr->getOperand(1); 11022 return true; 11023 } else if (VT == MVT::i32 || VT == MVT::i8 || VT == MVT::i1) { 11024 // AddressingMode 2 11025 if (ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(Ptr->getOperand(1))) { 11026 int RHSC = (int)RHS->getZExtValue(); 11027 if (RHSC < 0 && RHSC > -0x1000) { 11028 assert(Ptr->getOpcode() == ISD::ADD); 11029 isInc = false; 11030 Offset = DAG.getConstant(-RHSC, SDLoc(Ptr), RHS->getValueType(0)); 11031 Base = Ptr->getOperand(0); 11032 return true; 11033 } 11034 } 11035 11036 if (Ptr->getOpcode() == ISD::ADD) { 11037 isInc = true; 11038 ARM_AM::ShiftOpc ShOpcVal= 11039 ARM_AM::getShiftOpcForNode(Ptr->getOperand(0).getOpcode()); 11040 if (ShOpcVal != ARM_AM::no_shift) { 11041 Base = Ptr->getOperand(1); 11042 Offset = Ptr->getOperand(0); 11043 } else { 11044 Base = Ptr->getOperand(0); 11045 Offset = Ptr->getOperand(1); 11046 } 11047 return true; 11048 } 11049 11050 isInc = (Ptr->getOpcode() == ISD::ADD); 11051 Base = Ptr->getOperand(0); 11052 Offset = Ptr->getOperand(1); 11053 return true; 11054 } 11055 11056 // FIXME: Use VLDM / VSTM to emulate indexed FP load / store. 11057 return false; 11058 } 11059 11060 static bool getT2IndexedAddressParts(SDNode *Ptr, EVT VT, 11061 bool isSEXTLoad, SDValue &Base, 11062 SDValue &Offset, bool &isInc, 11063 SelectionDAG &DAG) { 11064 if (Ptr->getOpcode() != ISD::ADD && Ptr->getOpcode() != ISD::SUB) 11065 return false; 11066 11067 Base = Ptr->getOperand(0); 11068 if (ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(Ptr->getOperand(1))) { 11069 int RHSC = (int)RHS->getZExtValue(); 11070 if (RHSC < 0 && RHSC > -0x100) { // 8 bits. 11071 assert(Ptr->getOpcode() == ISD::ADD); 11072 isInc = false; 11073 Offset = DAG.getConstant(-RHSC, SDLoc(Ptr), RHS->getValueType(0)); 11074 return true; 11075 } else if (RHSC > 0 && RHSC < 0x100) { // 8 bit, no zero. 11076 isInc = Ptr->getOpcode() == ISD::ADD; 11077 Offset = DAG.getConstant(RHSC, SDLoc(Ptr), RHS->getValueType(0)); 11078 return true; 11079 } 11080 } 11081 11082 return false; 11083 } 11084 11085 /// getPreIndexedAddressParts - returns true by value, base pointer and 11086 /// offset pointer and addressing mode by reference if the node's address 11087 /// can be legally represented as pre-indexed load / store address. 11088 bool 11089 ARMTargetLowering::getPreIndexedAddressParts(SDNode *N, SDValue &Base, 11090 SDValue &Offset, 11091 ISD::MemIndexedMode &AM, 11092 SelectionDAG &DAG) const { 11093 if (Subtarget->isThumb1Only()) 11094 return false; 11095 11096 EVT VT; 11097 SDValue Ptr; 11098 bool isSEXTLoad = false; 11099 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) { 11100 Ptr = LD->getBasePtr(); 11101 VT = LD->getMemoryVT(); 11102 isSEXTLoad = LD->getExtensionType() == ISD::SEXTLOAD; 11103 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) { 11104 Ptr = ST->getBasePtr(); 11105 VT = ST->getMemoryVT(); 11106 } else 11107 return false; 11108 11109 bool isInc; 11110 bool isLegal = false; 11111 if (Subtarget->isThumb2()) 11112 isLegal = getT2IndexedAddressParts(Ptr.getNode(), VT, isSEXTLoad, Base, 11113 Offset, isInc, DAG); 11114 else 11115 isLegal = getARMIndexedAddressParts(Ptr.getNode(), VT, isSEXTLoad, Base, 11116 Offset, isInc, DAG); 11117 if (!isLegal) 11118 return false; 11119 11120 AM = isInc ? ISD::PRE_INC : ISD::PRE_DEC; 11121 return true; 11122 } 11123 11124 /// getPostIndexedAddressParts - returns true by value, base pointer and 11125 /// offset pointer and addressing mode by reference if this node can be 11126 /// combined with a load / store to form a post-indexed load / store. 11127 bool ARMTargetLowering::getPostIndexedAddressParts(SDNode *N, SDNode *Op, 11128 SDValue &Base, 11129 SDValue &Offset, 11130 ISD::MemIndexedMode &AM, 11131 SelectionDAG &DAG) const { 11132 if (Subtarget->isThumb1Only()) 11133 return false; 11134 11135 EVT VT; 11136 SDValue Ptr; 11137 bool isSEXTLoad = false; 11138 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) { 11139 VT = LD->getMemoryVT(); 11140 Ptr = LD->getBasePtr(); 11141 isSEXTLoad = LD->getExtensionType() == ISD::SEXTLOAD; 11142 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) { 11143 VT = ST->getMemoryVT(); 11144 Ptr = ST->getBasePtr(); 11145 } else 11146 return false; 11147 11148 bool isInc; 11149 bool isLegal = false; 11150 if (Subtarget->isThumb2()) 11151 isLegal = getT2IndexedAddressParts(Op, VT, isSEXTLoad, Base, Offset, 11152 isInc, DAG); 11153 else 11154 isLegal = getARMIndexedAddressParts(Op, VT, isSEXTLoad, Base, Offset, 11155 isInc, DAG); 11156 if (!isLegal) 11157 return false; 11158 11159 if (Ptr != Base) { 11160 // Swap base ptr and offset to catch more post-index load / store when 11161 // it's legal. In Thumb2 mode, offset must be an immediate. 11162 if (Ptr == Offset && Op->getOpcode() == ISD::ADD && 11163 !Subtarget->isThumb2()) 11164 std::swap(Base, Offset); 11165 11166 // Post-indexed load / store update the base pointer. 11167 if (Ptr != Base) 11168 return false; 11169 } 11170 11171 AM = isInc ? ISD::POST_INC : ISD::POST_DEC; 11172 return true; 11173 } 11174 11175 void ARMTargetLowering::computeKnownBitsForTargetNode(const SDValue Op, 11176 APInt &KnownZero, 11177 APInt &KnownOne, 11178 const SelectionDAG &DAG, 11179 unsigned Depth) const { 11180 unsigned BitWidth = KnownOne.getBitWidth(); 11181 KnownZero = KnownOne = APInt(BitWidth, 0); 11182 switch (Op.getOpcode()) { 11183 default: break; 11184 case ARMISD::ADDC: 11185 case ARMISD::ADDE: 11186 case ARMISD::SUBC: 11187 case ARMISD::SUBE: 11188 // These nodes' second result is a boolean 11189 if (Op.getResNo() == 0) 11190 break; 11191 KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - 1); 11192 break; 11193 case ARMISD::CMOV: { 11194 // Bits are known zero/one if known on the LHS and RHS. 11195 DAG.computeKnownBits(Op.getOperand(0), KnownZero, KnownOne, Depth+1); 11196 if (KnownZero == 0 && KnownOne == 0) return; 11197 11198 APInt KnownZeroRHS, KnownOneRHS; 11199 DAG.computeKnownBits(Op.getOperand(1), KnownZeroRHS, KnownOneRHS, Depth+1); 11200 KnownZero &= KnownZeroRHS; 11201 KnownOne &= KnownOneRHS; 11202 return; 11203 } 11204 case ISD::INTRINSIC_W_CHAIN: { 11205 ConstantSDNode *CN = cast<ConstantSDNode>(Op->getOperand(1)); 11206 Intrinsic::ID IntID = static_cast<Intrinsic::ID>(CN->getZExtValue()); 11207 switch (IntID) { 11208 default: return; 11209 case Intrinsic::arm_ldaex: 11210 case Intrinsic::arm_ldrex: { 11211 EVT VT = cast<MemIntrinsicSDNode>(Op)->getMemoryVT(); 11212 unsigned MemBits = VT.getScalarType().getSizeInBits(); 11213 KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - MemBits); 11214 return; 11215 } 11216 } 11217 } 11218 } 11219 } 11220 11221 //===----------------------------------------------------------------------===// 11222 // ARM Inline Assembly Support 11223 //===----------------------------------------------------------------------===// 11224 11225 bool ARMTargetLowering::ExpandInlineAsm(CallInst *CI) const { 11226 // Looking for "rev" which is V6+. 11227 if (!Subtarget->hasV6Ops()) 11228 return false; 11229 11230 InlineAsm *IA = cast<InlineAsm>(CI->getCalledValue()); 11231 std::string AsmStr = IA->getAsmString(); 11232 SmallVector<StringRef, 4> AsmPieces; 11233 SplitString(AsmStr, AsmPieces, ";\n"); 11234 11235 switch (AsmPieces.size()) { 11236 default: return false; 11237 case 1: 11238 AsmStr = AsmPieces[0]; 11239 AsmPieces.clear(); 11240 SplitString(AsmStr, AsmPieces, " \t,"); 11241 11242 // rev $0, $1 11243 if (AsmPieces.size() == 3 && 11244 AsmPieces[0] == "rev" && AsmPieces[1] == "$0" && AsmPieces[2] == "$1" && 11245 IA->getConstraintString().compare(0, 4, "=l,l") == 0) { 11246 IntegerType *Ty = dyn_cast<IntegerType>(CI->getType()); 11247 if (Ty && Ty->getBitWidth() == 32) 11248 return IntrinsicLowering::LowerToByteSwap(CI); 11249 } 11250 break; 11251 } 11252 11253 return false; 11254 } 11255 11256 /// getConstraintType - Given a constraint letter, return the type of 11257 /// constraint it is for this target. 11258 ARMTargetLowering::ConstraintType 11259 ARMTargetLowering::getConstraintType(StringRef Constraint) const { 11260 if (Constraint.size() == 1) { 11261 switch (Constraint[0]) { 11262 default: break; 11263 case 'l': return C_RegisterClass; 11264 case 'w': return C_RegisterClass; 11265 case 'h': return C_RegisterClass; 11266 case 'x': return C_RegisterClass; 11267 case 't': return C_RegisterClass; 11268 case 'j': return C_Other; // Constant for movw. 11269 // An address with a single base register. Due to the way we 11270 // currently handle addresses it is the same as an 'r' memory constraint. 11271 case 'Q': return C_Memory; 11272 } 11273 } else if (Constraint.size() == 2) { 11274 switch (Constraint[0]) { 11275 default: break; 11276 // All 'U+' constraints are addresses. 11277 case 'U': return C_Memory; 11278 } 11279 } 11280 return TargetLowering::getConstraintType(Constraint); 11281 } 11282 11283 /// Examine constraint type and operand type and determine a weight value. 11284 /// This object must already have been set up with the operand type 11285 /// and the current alternative constraint selected. 11286 TargetLowering::ConstraintWeight 11287 ARMTargetLowering::getSingleConstraintMatchWeight( 11288 AsmOperandInfo &info, const char *constraint) const { 11289 ConstraintWeight weight = CW_Invalid; 11290 Value *CallOperandVal = info.CallOperandVal; 11291 // If we don't have a value, we can't do a match, 11292 // but allow it at the lowest weight. 11293 if (!CallOperandVal) 11294 return CW_Default; 11295 Type *type = CallOperandVal->getType(); 11296 // Look at the constraint type. 11297 switch (*constraint) { 11298 default: 11299 weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint); 11300 break; 11301 case 'l': 11302 if (type->isIntegerTy()) { 11303 if (Subtarget->isThumb()) 11304 weight = CW_SpecificReg; 11305 else 11306 weight = CW_Register; 11307 } 11308 break; 11309 case 'w': 11310 if (type->isFloatingPointTy()) 11311 weight = CW_Register; 11312 break; 11313 } 11314 return weight; 11315 } 11316 11317 typedef std::pair<unsigned, const TargetRegisterClass*> RCPair; 11318 RCPair ARMTargetLowering::getRegForInlineAsmConstraint( 11319 const TargetRegisterInfo *TRI, StringRef Constraint, MVT VT) const { 11320 if (Constraint.size() == 1) { 11321 // GCC ARM Constraint Letters 11322 switch (Constraint[0]) { 11323 case 'l': // Low regs or general regs. 11324 if (Subtarget->isThumb()) 11325 return RCPair(0U, &ARM::tGPRRegClass); 11326 return RCPair(0U, &ARM::GPRRegClass); 11327 case 'h': // High regs or no regs. 11328 if (Subtarget->isThumb()) 11329 return RCPair(0U, &ARM::hGPRRegClass); 11330 break; 11331 case 'r': 11332 if (Subtarget->isThumb1Only()) 11333 return RCPair(0U, &ARM::tGPRRegClass); 11334 return RCPair(0U, &ARM::GPRRegClass); 11335 case 'w': 11336 if (VT == MVT::Other) 11337 break; 11338 if (VT == MVT::f32) 11339 return RCPair(0U, &ARM::SPRRegClass); 11340 if (VT.getSizeInBits() == 64) 11341 return RCPair(0U, &ARM::DPRRegClass); 11342 if (VT.getSizeInBits() == 128) 11343 return RCPair(0U, &ARM::QPRRegClass); 11344 break; 11345 case 'x': 11346 if (VT == MVT::Other) 11347 break; 11348 if (VT == MVT::f32) 11349 return RCPair(0U, &ARM::SPR_8RegClass); 11350 if (VT.getSizeInBits() == 64) 11351 return RCPair(0U, &ARM::DPR_8RegClass); 11352 if (VT.getSizeInBits() == 128) 11353 return RCPair(0U, &ARM::QPR_8RegClass); 11354 break; 11355 case 't': 11356 if (VT == MVT::f32) 11357 return RCPair(0U, &ARM::SPRRegClass); 11358 break; 11359 } 11360 } 11361 if (StringRef("{cc}").equals_lower(Constraint)) 11362 return std::make_pair(unsigned(ARM::CPSR), &ARM::CCRRegClass); 11363 11364 return TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT); 11365 } 11366 11367 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops 11368 /// vector. If it is invalid, don't add anything to Ops. 11369 void ARMTargetLowering::LowerAsmOperandForConstraint(SDValue Op, 11370 std::string &Constraint, 11371 std::vector<SDValue>&Ops, 11372 SelectionDAG &DAG) const { 11373 SDValue Result; 11374 11375 // Currently only support length 1 constraints. 11376 if (Constraint.length() != 1) return; 11377 11378 char ConstraintLetter = Constraint[0]; 11379 switch (ConstraintLetter) { 11380 default: break; 11381 case 'j': 11382 case 'I': case 'J': case 'K': case 'L': 11383 case 'M': case 'N': case 'O': 11384 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op); 11385 if (!C) 11386 return; 11387 11388 int64_t CVal64 = C->getSExtValue(); 11389 int CVal = (int) CVal64; 11390 // None of these constraints allow values larger than 32 bits. Check 11391 // that the value fits in an int. 11392 if (CVal != CVal64) 11393 return; 11394 11395 switch (ConstraintLetter) { 11396 case 'j': 11397 // Constant suitable for movw, must be between 0 and 11398 // 65535. 11399 if (Subtarget->hasV6T2Ops()) 11400 if (CVal >= 0 && CVal <= 65535) 11401 break; 11402 return; 11403 case 'I': 11404 if (Subtarget->isThumb1Only()) { 11405 // This must be a constant between 0 and 255, for ADD 11406 // immediates. 11407 if (CVal >= 0 && CVal <= 255) 11408 break; 11409 } else if (Subtarget->isThumb2()) { 11410 // A constant that can be used as an immediate value in a 11411 // data-processing instruction. 11412 if (ARM_AM::getT2SOImmVal(CVal) != -1) 11413 break; 11414 } else { 11415 // A constant that can be used as an immediate value in a 11416 // data-processing instruction. 11417 if (ARM_AM::getSOImmVal(CVal) != -1) 11418 break; 11419 } 11420 return; 11421 11422 case 'J': 11423 if (Subtarget->isThumb()) { // FIXME thumb2 11424 // This must be a constant between -255 and -1, for negated ADD 11425 // immediates. This can be used in GCC with an "n" modifier that 11426 // prints the negated value, for use with SUB instructions. It is 11427 // not useful otherwise but is implemented for compatibility. 11428 if (CVal >= -255 && CVal <= -1) 11429 break; 11430 } else { 11431 // This must be a constant between -4095 and 4095. It is not clear 11432 // what this constraint is intended for. Implemented for 11433 // compatibility with GCC. 11434 if (CVal >= -4095 && CVal <= 4095) 11435 break; 11436 } 11437 return; 11438 11439 case 'K': 11440 if (Subtarget->isThumb1Only()) { 11441 // A 32-bit value where only one byte has a nonzero value. Exclude 11442 // zero to match GCC. This constraint is used by GCC internally for 11443 // constants that can be loaded with a move/shift combination. 11444 // It is not useful otherwise but is implemented for compatibility. 11445 if (CVal != 0 && ARM_AM::isThumbImmShiftedVal(CVal)) 11446 break; 11447 } else if (Subtarget->isThumb2()) { 11448 // A constant whose bitwise inverse can be used as an immediate 11449 // value in a data-processing instruction. This can be used in GCC 11450 // with a "B" modifier that prints the inverted value, for use with 11451 // BIC and MVN instructions. It is not useful otherwise but is 11452 // implemented for compatibility. 11453 if (ARM_AM::getT2SOImmVal(~CVal) != -1) 11454 break; 11455 } else { 11456 // A constant whose bitwise inverse can be used as an immediate 11457 // value in a data-processing instruction. This can be used in GCC 11458 // with a "B" modifier that prints the inverted value, for use with 11459 // BIC and MVN instructions. It is not useful otherwise but is 11460 // implemented for compatibility. 11461 if (ARM_AM::getSOImmVal(~CVal) != -1) 11462 break; 11463 } 11464 return; 11465 11466 case 'L': 11467 if (Subtarget->isThumb1Only()) { 11468 // This must be a constant between -7 and 7, 11469 // for 3-operand ADD/SUB immediate instructions. 11470 if (CVal >= -7 && CVal < 7) 11471 break; 11472 } else if (Subtarget->isThumb2()) { 11473 // A constant whose negation can be used as an immediate value in a 11474 // data-processing instruction. This can be used in GCC with an "n" 11475 // modifier that prints the negated value, for use with SUB 11476 // instructions. It is not useful otherwise but is implemented for 11477 // compatibility. 11478 if (ARM_AM::getT2SOImmVal(-CVal) != -1) 11479 break; 11480 } else { 11481 // A constant whose negation can be used as an immediate value in a 11482 // data-processing instruction. This can be used in GCC with an "n" 11483 // modifier that prints the negated value, for use with SUB 11484 // instructions. It is not useful otherwise but is implemented for 11485 // compatibility. 11486 if (ARM_AM::getSOImmVal(-CVal) != -1) 11487 break; 11488 } 11489 return; 11490 11491 case 'M': 11492 if (Subtarget->isThumb()) { // FIXME thumb2 11493 // This must be a multiple of 4 between 0 and 1020, for 11494 // ADD sp + immediate. 11495 if ((CVal >= 0 && CVal <= 1020) && ((CVal & 3) == 0)) 11496 break; 11497 } else { 11498 // A power of two or a constant between 0 and 32. This is used in 11499 // GCC for the shift amount on shifted register operands, but it is 11500 // useful in general for any shift amounts. 11501 if ((CVal >= 0 && CVal <= 32) || ((CVal & (CVal - 1)) == 0)) 11502 break; 11503 } 11504 return; 11505 11506 case 'N': 11507 if (Subtarget->isThumb()) { // FIXME thumb2 11508 // This must be a constant between 0 and 31, for shift amounts. 11509 if (CVal >= 0 && CVal <= 31) 11510 break; 11511 } 11512 return; 11513 11514 case 'O': 11515 if (Subtarget->isThumb()) { // FIXME thumb2 11516 // This must be a multiple of 4 between -508 and 508, for 11517 // ADD/SUB sp = sp + immediate. 11518 if ((CVal >= -508 && CVal <= 508) && ((CVal & 3) == 0)) 11519 break; 11520 } 11521 return; 11522 } 11523 Result = DAG.getTargetConstant(CVal, SDLoc(Op), Op.getValueType()); 11524 break; 11525 } 11526 11527 if (Result.getNode()) { 11528 Ops.push_back(Result); 11529 return; 11530 } 11531 return TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG); 11532 } 11533 11534 static RTLIB::Libcall getDivRemLibcall( 11535 const SDNode *N, MVT::SimpleValueType SVT) { 11536 assert((N->getOpcode() == ISD::SDIVREM || N->getOpcode() == ISD::UDIVREM || 11537 N->getOpcode() == ISD::SREM || N->getOpcode() == ISD::UREM) && 11538 "Unhandled Opcode in getDivRemLibcall"); 11539 bool isSigned = N->getOpcode() == ISD::SDIVREM || 11540 N->getOpcode() == ISD::SREM; 11541 RTLIB::Libcall LC; 11542 switch (SVT) { 11543 default: llvm_unreachable("Unexpected request for libcall!"); 11544 case MVT::i8: LC = isSigned ? RTLIB::SDIVREM_I8 : RTLIB::UDIVREM_I8; break; 11545 case MVT::i16: LC = isSigned ? RTLIB::SDIVREM_I16 : RTLIB::UDIVREM_I16; break; 11546 case MVT::i32: LC = isSigned ? RTLIB::SDIVREM_I32 : RTLIB::UDIVREM_I32; break; 11547 case MVT::i64: LC = isSigned ? RTLIB::SDIVREM_I64 : RTLIB::UDIVREM_I64; break; 11548 } 11549 return LC; 11550 } 11551 11552 static TargetLowering::ArgListTy getDivRemArgList( 11553 const SDNode *N, LLVMContext *Context) { 11554 assert((N->getOpcode() == ISD::SDIVREM || N->getOpcode() == ISD::UDIVREM || 11555 N->getOpcode() == ISD::SREM || N->getOpcode() == ISD::UREM) && 11556 "Unhandled Opcode in getDivRemArgList"); 11557 bool isSigned = N->getOpcode() == ISD::SDIVREM || 11558 N->getOpcode() == ISD::SREM; 11559 TargetLowering::ArgListTy Args; 11560 TargetLowering::ArgListEntry Entry; 11561 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) { 11562 EVT ArgVT = N->getOperand(i).getValueType(); 11563 Type *ArgTy = ArgVT.getTypeForEVT(*Context); 11564 Entry.Node = N->getOperand(i); 11565 Entry.Ty = ArgTy; 11566 Entry.isSExt = isSigned; 11567 Entry.isZExt = !isSigned; 11568 Args.push_back(Entry); 11569 } 11570 return Args; 11571 } 11572 11573 SDValue ARMTargetLowering::LowerDivRem(SDValue Op, SelectionDAG &DAG) const { 11574 assert((Subtarget->isTargetAEABI() || Subtarget->isTargetAndroid()) && 11575 "Register-based DivRem lowering only"); 11576 unsigned Opcode = Op->getOpcode(); 11577 assert((Opcode == ISD::SDIVREM || Opcode == ISD::UDIVREM) && 11578 "Invalid opcode for Div/Rem lowering"); 11579 bool isSigned = (Opcode == ISD::SDIVREM); 11580 EVT VT = Op->getValueType(0); 11581 Type *Ty = VT.getTypeForEVT(*DAG.getContext()); 11582 11583 RTLIB::Libcall LC = getDivRemLibcall(Op.getNode(), 11584 VT.getSimpleVT().SimpleTy); 11585 SDValue InChain = DAG.getEntryNode(); 11586 11587 TargetLowering::ArgListTy Args = getDivRemArgList(Op.getNode(), 11588 DAG.getContext()); 11589 11590 SDValue Callee = DAG.getExternalSymbol(getLibcallName(LC), 11591 getPointerTy(DAG.getDataLayout())); 11592 11593 Type *RetTy = (Type*)StructType::get(Ty, Ty, nullptr); 11594 11595 SDLoc dl(Op); 11596 TargetLowering::CallLoweringInfo CLI(DAG); 11597 CLI.setDebugLoc(dl).setChain(InChain) 11598 .setCallee(getLibcallCallingConv(LC), RetTy, Callee, std::move(Args), 0) 11599 .setInRegister().setSExtResult(isSigned).setZExtResult(!isSigned); 11600 11601 std::pair<SDValue, SDValue> CallInfo = LowerCallTo(CLI); 11602 return CallInfo.first; 11603 } 11604 11605 // Lowers REM using divmod helpers 11606 // see RTABI section 4.2/4.3 11607 SDValue ARMTargetLowering::LowerREM(SDNode *N, SelectionDAG &DAG) const { 11608 // Build return types (div and rem) 11609 std::vector<Type*> RetTyParams; 11610 Type *RetTyElement; 11611 11612 switch (N->getValueType(0).getSimpleVT().SimpleTy) { 11613 default: llvm_unreachable("Unexpected request for libcall!"); 11614 case MVT::i8: RetTyElement = Type::getInt8Ty(*DAG.getContext()); break; 11615 case MVT::i16: RetTyElement = Type::getInt16Ty(*DAG.getContext()); break; 11616 case MVT::i32: RetTyElement = Type::getInt32Ty(*DAG.getContext()); break; 11617 case MVT::i64: RetTyElement = Type::getInt64Ty(*DAG.getContext()); break; 11618 } 11619 11620 RetTyParams.push_back(RetTyElement); 11621 RetTyParams.push_back(RetTyElement); 11622 ArrayRef<Type*> ret = ArrayRef<Type*>(RetTyParams); 11623 Type *RetTy = StructType::get(*DAG.getContext(), ret); 11624 11625 RTLIB::Libcall LC = getDivRemLibcall(N, N->getValueType(0).getSimpleVT(). 11626 SimpleTy); 11627 SDValue InChain = DAG.getEntryNode(); 11628 TargetLowering::ArgListTy Args = getDivRemArgList(N, DAG.getContext()); 11629 bool isSigned = N->getOpcode() == ISD::SREM; 11630 SDValue Callee = DAG.getExternalSymbol(getLibcallName(LC), 11631 getPointerTy(DAG.getDataLayout())); 11632 11633 // Lower call 11634 CallLoweringInfo CLI(DAG); 11635 CLI.setChain(InChain) 11636 .setCallee(CallingConv::ARM_AAPCS, RetTy, Callee, std::move(Args), 0) 11637 .setSExtResult(isSigned).setZExtResult(!isSigned).setDebugLoc(SDLoc(N)); 11638 std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI); 11639 11640 // Return second (rem) result operand (first contains div) 11641 SDNode *ResNode = CallResult.first.getNode(); 11642 assert(ResNode->getNumOperands() == 2 && "divmod should return two operands"); 11643 return ResNode->getOperand(1); 11644 } 11645 11646 SDValue 11647 ARMTargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op, SelectionDAG &DAG) const { 11648 assert(Subtarget->isTargetWindows() && "unsupported target platform"); 11649 SDLoc DL(Op); 11650 11651 // Get the inputs. 11652 SDValue Chain = Op.getOperand(0); 11653 SDValue Size = Op.getOperand(1); 11654 11655 SDValue Words = DAG.getNode(ISD::SRL, DL, MVT::i32, Size, 11656 DAG.getConstant(2, DL, MVT::i32)); 11657 11658 SDValue Flag; 11659 Chain = DAG.getCopyToReg(Chain, DL, ARM::R4, Words, Flag); 11660 Flag = Chain.getValue(1); 11661 11662 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue); 11663 Chain = DAG.getNode(ARMISD::WIN__CHKSTK, DL, NodeTys, Chain, Flag); 11664 11665 SDValue NewSP = DAG.getCopyFromReg(Chain, DL, ARM::SP, MVT::i32); 11666 Chain = NewSP.getValue(1); 11667 11668 SDValue Ops[2] = { NewSP, Chain }; 11669 return DAG.getMergeValues(Ops, DL); 11670 } 11671 11672 SDValue ARMTargetLowering::LowerFP_EXTEND(SDValue Op, SelectionDAG &DAG) const { 11673 assert(Op.getValueType() == MVT::f64 && Subtarget->isFPOnlySP() && 11674 "Unexpected type for custom-lowering FP_EXTEND"); 11675 11676 RTLIB::Libcall LC; 11677 LC = RTLIB::getFPEXT(Op.getOperand(0).getValueType(), Op.getValueType()); 11678 11679 SDValue SrcVal = Op.getOperand(0); 11680 return makeLibCall(DAG, LC, Op.getValueType(), SrcVal, /*isSigned*/ false, 11681 SDLoc(Op)).first; 11682 } 11683 11684 SDValue ARMTargetLowering::LowerFP_ROUND(SDValue Op, SelectionDAG &DAG) const { 11685 assert(Op.getOperand(0).getValueType() == MVT::f64 && 11686 Subtarget->isFPOnlySP() && 11687 "Unexpected type for custom-lowering FP_ROUND"); 11688 11689 RTLIB::Libcall LC; 11690 LC = RTLIB::getFPROUND(Op.getOperand(0).getValueType(), Op.getValueType()); 11691 11692 SDValue SrcVal = Op.getOperand(0); 11693 return makeLibCall(DAG, LC, Op.getValueType(), SrcVal, /*isSigned*/ false, 11694 SDLoc(Op)).first; 11695 } 11696 11697 bool 11698 ARMTargetLowering::isOffsetFoldingLegal(const GlobalAddressSDNode *GA) const { 11699 // The ARM target isn't yet aware of offsets. 11700 return false; 11701 } 11702 11703 bool ARM::isBitFieldInvertedMask(unsigned v) { 11704 if (v == 0xffffffff) 11705 return false; 11706 11707 // there can be 1's on either or both "outsides", all the "inside" 11708 // bits must be 0's 11709 return isShiftedMask_32(~v); 11710 } 11711 11712 /// isFPImmLegal - Returns true if the target can instruction select the 11713 /// specified FP immediate natively. If false, the legalizer will 11714 /// materialize the FP immediate as a load from a constant pool. 11715 bool ARMTargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT) const { 11716 if (!Subtarget->hasVFP3()) 11717 return false; 11718 if (VT == MVT::f32) 11719 return ARM_AM::getFP32Imm(Imm) != -1; 11720 if (VT == MVT::f64 && !Subtarget->isFPOnlySP()) 11721 return ARM_AM::getFP64Imm(Imm) != -1; 11722 return false; 11723 } 11724 11725 /// getTgtMemIntrinsic - Represent NEON load and store intrinsics as 11726 /// MemIntrinsicNodes. The associated MachineMemOperands record the alignment 11727 /// specified in the intrinsic calls. 11728 bool ARMTargetLowering::getTgtMemIntrinsic(IntrinsicInfo &Info, 11729 const CallInst &I, 11730 unsigned Intrinsic) const { 11731 switch (Intrinsic) { 11732 case Intrinsic::arm_neon_vld1: 11733 case Intrinsic::arm_neon_vld2: 11734 case Intrinsic::arm_neon_vld3: 11735 case Intrinsic::arm_neon_vld4: 11736 case Intrinsic::arm_neon_vld2lane: 11737 case Intrinsic::arm_neon_vld3lane: 11738 case Intrinsic::arm_neon_vld4lane: { 11739 Info.opc = ISD::INTRINSIC_W_CHAIN; 11740 // Conservatively set memVT to the entire set of vectors loaded. 11741 auto &DL = I.getCalledFunction()->getParent()->getDataLayout(); 11742 uint64_t NumElts = DL.getTypeAllocSize(I.getType()) / 8; 11743 Info.memVT = EVT::getVectorVT(I.getType()->getContext(), MVT::i64, NumElts); 11744 Info.ptrVal = I.getArgOperand(0); 11745 Info.offset = 0; 11746 Value *AlignArg = I.getArgOperand(I.getNumArgOperands() - 1); 11747 Info.align = cast<ConstantInt>(AlignArg)->getZExtValue(); 11748 Info.vol = false; // volatile loads with NEON intrinsics not supported 11749 Info.readMem = true; 11750 Info.writeMem = false; 11751 return true; 11752 } 11753 case Intrinsic::arm_neon_vst1: 11754 case Intrinsic::arm_neon_vst2: 11755 case Intrinsic::arm_neon_vst3: 11756 case Intrinsic::arm_neon_vst4: 11757 case Intrinsic::arm_neon_vst2lane: 11758 case Intrinsic::arm_neon_vst3lane: 11759 case Intrinsic::arm_neon_vst4lane: { 11760 Info.opc = ISD::INTRINSIC_VOID; 11761 // Conservatively set memVT to the entire set of vectors stored. 11762 auto &DL = I.getCalledFunction()->getParent()->getDataLayout(); 11763 unsigned NumElts = 0; 11764 for (unsigned ArgI = 1, ArgE = I.getNumArgOperands(); ArgI < ArgE; ++ArgI) { 11765 Type *ArgTy = I.getArgOperand(ArgI)->getType(); 11766 if (!ArgTy->isVectorTy()) 11767 break; 11768 NumElts += DL.getTypeAllocSize(ArgTy) / 8; 11769 } 11770 Info.memVT = EVT::getVectorVT(I.getType()->getContext(), MVT::i64, NumElts); 11771 Info.ptrVal = I.getArgOperand(0); 11772 Info.offset = 0; 11773 Value *AlignArg = I.getArgOperand(I.getNumArgOperands() - 1); 11774 Info.align = cast<ConstantInt>(AlignArg)->getZExtValue(); 11775 Info.vol = false; // volatile stores with NEON intrinsics not supported 11776 Info.readMem = false; 11777 Info.writeMem = true; 11778 return true; 11779 } 11780 case Intrinsic::arm_ldaex: 11781 case Intrinsic::arm_ldrex: { 11782 auto &DL = I.getCalledFunction()->getParent()->getDataLayout(); 11783 PointerType *PtrTy = cast<PointerType>(I.getArgOperand(0)->getType()); 11784 Info.opc = ISD::INTRINSIC_W_CHAIN; 11785 Info.memVT = MVT::getVT(PtrTy->getElementType()); 11786 Info.ptrVal = I.getArgOperand(0); 11787 Info.offset = 0; 11788 Info.align = DL.getABITypeAlignment(PtrTy->getElementType()); 11789 Info.vol = true; 11790 Info.readMem = true; 11791 Info.writeMem = false; 11792 return true; 11793 } 11794 case Intrinsic::arm_stlex: 11795 case Intrinsic::arm_strex: { 11796 auto &DL = I.getCalledFunction()->getParent()->getDataLayout(); 11797 PointerType *PtrTy = cast<PointerType>(I.getArgOperand(1)->getType()); 11798 Info.opc = ISD::INTRINSIC_W_CHAIN; 11799 Info.memVT = MVT::getVT(PtrTy->getElementType()); 11800 Info.ptrVal = I.getArgOperand(1); 11801 Info.offset = 0; 11802 Info.align = DL.getABITypeAlignment(PtrTy->getElementType()); 11803 Info.vol = true; 11804 Info.readMem = false; 11805 Info.writeMem = true; 11806 return true; 11807 } 11808 case Intrinsic::arm_stlexd: 11809 case Intrinsic::arm_strexd: { 11810 Info.opc = ISD::INTRINSIC_W_CHAIN; 11811 Info.memVT = MVT::i64; 11812 Info.ptrVal = I.getArgOperand(2); 11813 Info.offset = 0; 11814 Info.align = 8; 11815 Info.vol = true; 11816 Info.readMem = false; 11817 Info.writeMem = true; 11818 return true; 11819 } 11820 case Intrinsic::arm_ldaexd: 11821 case Intrinsic::arm_ldrexd: { 11822 Info.opc = ISD::INTRINSIC_W_CHAIN; 11823 Info.memVT = MVT::i64; 11824 Info.ptrVal = I.getArgOperand(0); 11825 Info.offset = 0; 11826 Info.align = 8; 11827 Info.vol = true; 11828 Info.readMem = true; 11829 Info.writeMem = false; 11830 return true; 11831 } 11832 default: 11833 break; 11834 } 11835 11836 return false; 11837 } 11838 11839 /// \brief Returns true if it is beneficial to convert a load of a constant 11840 /// to just the constant itself. 11841 bool ARMTargetLowering::shouldConvertConstantLoadToIntImm(const APInt &Imm, 11842 Type *Ty) const { 11843 assert(Ty->isIntegerTy()); 11844 11845 unsigned Bits = Ty->getPrimitiveSizeInBits(); 11846 if (Bits == 0 || Bits > 32) 11847 return false; 11848 return true; 11849 } 11850 11851 Instruction* ARMTargetLowering::makeDMB(IRBuilder<> &Builder, 11852 ARM_MB::MemBOpt Domain) const { 11853 Module *M = Builder.GetInsertBlock()->getParent()->getParent(); 11854 11855 // First, if the target has no DMB, see what fallback we can use. 11856 if (!Subtarget->hasDataBarrier()) { 11857 // Some ARMv6 cpus can support data barriers with an mcr instruction. 11858 // Thumb1 and pre-v6 ARM mode use a libcall instead and should never get 11859 // here. 11860 if (Subtarget->hasV6Ops() && !Subtarget->isThumb()) { 11861 Function *MCR = llvm::Intrinsic::getDeclaration(M, Intrinsic::arm_mcr); 11862 Value* args[6] = {Builder.getInt32(15), Builder.getInt32(0), 11863 Builder.getInt32(0), Builder.getInt32(7), 11864 Builder.getInt32(10), Builder.getInt32(5)}; 11865 return Builder.CreateCall(MCR, args); 11866 } else { 11867 // Instead of using barriers, atomic accesses on these subtargets use 11868 // libcalls. 11869 llvm_unreachable("makeDMB on a target so old that it has no barriers"); 11870 } 11871 } else { 11872 Function *DMB = llvm::Intrinsic::getDeclaration(M, Intrinsic::arm_dmb); 11873 // Only a full system barrier exists in the M-class architectures. 11874 Domain = Subtarget->isMClass() ? ARM_MB::SY : Domain; 11875 Constant *CDomain = Builder.getInt32(Domain); 11876 return Builder.CreateCall(DMB, CDomain); 11877 } 11878 } 11879 11880 // Based on http://www.cl.cam.ac.uk/~pes20/cpp/cpp0xmappings.html 11881 Instruction* ARMTargetLowering::emitLeadingFence(IRBuilder<> &Builder, 11882 AtomicOrdering Ord, bool IsStore, 11883 bool IsLoad) const { 11884 if (!getInsertFencesForAtomic()) 11885 return nullptr; 11886 11887 switch (Ord) { 11888 case NotAtomic: 11889 case Unordered: 11890 llvm_unreachable("Invalid fence: unordered/non-atomic"); 11891 case Monotonic: 11892 case Acquire: 11893 return nullptr; // Nothing to do 11894 case SequentiallyConsistent: 11895 if (!IsStore) 11896 return nullptr; // Nothing to do 11897 /*FALLTHROUGH*/ 11898 case Release: 11899 case AcquireRelease: 11900 if (Subtarget->isSwift()) 11901 return makeDMB(Builder, ARM_MB::ISHST); 11902 // FIXME: add a comment with a link to documentation justifying this. 11903 else 11904 return makeDMB(Builder, ARM_MB::ISH); 11905 } 11906 llvm_unreachable("Unknown fence ordering in emitLeadingFence"); 11907 } 11908 11909 Instruction* ARMTargetLowering::emitTrailingFence(IRBuilder<> &Builder, 11910 AtomicOrdering Ord, bool IsStore, 11911 bool IsLoad) const { 11912 if (!getInsertFencesForAtomic()) 11913 return nullptr; 11914 11915 switch (Ord) { 11916 case NotAtomic: 11917 case Unordered: 11918 llvm_unreachable("Invalid fence: unordered/not-atomic"); 11919 case Monotonic: 11920 case Release: 11921 return nullptr; // Nothing to do 11922 case Acquire: 11923 case AcquireRelease: 11924 case SequentiallyConsistent: 11925 return makeDMB(Builder, ARM_MB::ISH); 11926 } 11927 llvm_unreachable("Unknown fence ordering in emitTrailingFence"); 11928 } 11929 11930 // Loads and stores less than 64-bits are already atomic; ones above that 11931 // are doomed anyway, so defer to the default libcall and blame the OS when 11932 // things go wrong. Cortex M doesn't have ldrexd/strexd though, so don't emit 11933 // anything for those. 11934 bool ARMTargetLowering::shouldExpandAtomicStoreInIR(StoreInst *SI) const { 11935 unsigned Size = SI->getValueOperand()->getType()->getPrimitiveSizeInBits(); 11936 return (Size == 64) && !Subtarget->isMClass(); 11937 } 11938 11939 // Loads and stores less than 64-bits are already atomic; ones above that 11940 // are doomed anyway, so defer to the default libcall and blame the OS when 11941 // things go wrong. Cortex M doesn't have ldrexd/strexd though, so don't emit 11942 // anything for those. 11943 // FIXME: ldrd and strd are atomic if the CPU has LPAE (e.g. A15 has that 11944 // guarantee, see DDI0406C ARM architecture reference manual, 11945 // sections A8.8.72-74 LDRD) 11946 TargetLowering::AtomicExpansionKind 11947 ARMTargetLowering::shouldExpandAtomicLoadInIR(LoadInst *LI) const { 11948 unsigned Size = LI->getType()->getPrimitiveSizeInBits(); 11949 return ((Size == 64) && !Subtarget->isMClass()) ? AtomicExpansionKind::LLOnly 11950 : AtomicExpansionKind::None; 11951 } 11952 11953 // For the real atomic operations, we have ldrex/strex up to 32 bits, 11954 // and up to 64 bits on the non-M profiles 11955 TargetLowering::AtomicExpansionKind 11956 ARMTargetLowering::shouldExpandAtomicRMWInIR(AtomicRMWInst *AI) const { 11957 unsigned Size = AI->getType()->getPrimitiveSizeInBits(); 11958 return (Size <= (Subtarget->isMClass() ? 32U : 64U)) 11959 ? AtomicExpansionKind::LLSC 11960 : AtomicExpansionKind::None; 11961 } 11962 11963 bool ARMTargetLowering::shouldExpandAtomicCmpXchgInIR( 11964 AtomicCmpXchgInst *AI) const { 11965 return true; 11966 } 11967 11968 // This has so far only been implemented for MachO. 11969 bool ARMTargetLowering::useLoadStackGuardNode() const { 11970 return Subtarget->isTargetMachO(); 11971 } 11972 11973 bool ARMTargetLowering::canCombineStoreAndExtract(Type *VectorTy, Value *Idx, 11974 unsigned &Cost) const { 11975 // If we do not have NEON, vector types are not natively supported. 11976 if (!Subtarget->hasNEON()) 11977 return false; 11978 11979 // Floating point values and vector values map to the same register file. 11980 // Therefore, although we could do a store extract of a vector type, this is 11981 // better to leave at float as we have more freedom in the addressing mode for 11982 // those. 11983 if (VectorTy->isFPOrFPVectorTy()) 11984 return false; 11985 11986 // If the index is unknown at compile time, this is very expensive to lower 11987 // and it is not possible to combine the store with the extract. 11988 if (!isa<ConstantInt>(Idx)) 11989 return false; 11990 11991 assert(VectorTy->isVectorTy() && "VectorTy is not a vector type"); 11992 unsigned BitWidth = cast<VectorType>(VectorTy)->getBitWidth(); 11993 // We can do a store + vector extract on any vector that fits perfectly in a D 11994 // or Q register. 11995 if (BitWidth == 64 || BitWidth == 128) { 11996 Cost = 0; 11997 return true; 11998 } 11999 return false; 12000 } 12001 12002 bool ARMTargetLowering::isCheapToSpeculateCttz() const { 12003 return Subtarget->hasV6T2Ops(); 12004 } 12005 12006 bool ARMTargetLowering::isCheapToSpeculateCtlz() const { 12007 return Subtarget->hasV6T2Ops(); 12008 } 12009 12010 Value *ARMTargetLowering::emitLoadLinked(IRBuilder<> &Builder, Value *Addr, 12011 AtomicOrdering Ord) const { 12012 Module *M = Builder.GetInsertBlock()->getParent()->getParent(); 12013 Type *ValTy = cast<PointerType>(Addr->getType())->getElementType(); 12014 bool IsAcquire = isAtLeastAcquire(Ord); 12015 12016 // Since i64 isn't legal and intrinsics don't get type-lowered, the ldrexd 12017 // intrinsic must return {i32, i32} and we have to recombine them into a 12018 // single i64 here. 12019 if (ValTy->getPrimitiveSizeInBits() == 64) { 12020 Intrinsic::ID Int = 12021 IsAcquire ? Intrinsic::arm_ldaexd : Intrinsic::arm_ldrexd; 12022 Function *Ldrex = llvm::Intrinsic::getDeclaration(M, Int); 12023 12024 Addr = Builder.CreateBitCast(Addr, Type::getInt8PtrTy(M->getContext())); 12025 Value *LoHi = Builder.CreateCall(Ldrex, Addr, "lohi"); 12026 12027 Value *Lo = Builder.CreateExtractValue(LoHi, 0, "lo"); 12028 Value *Hi = Builder.CreateExtractValue(LoHi, 1, "hi"); 12029 if (!Subtarget->isLittle()) 12030 std::swap (Lo, Hi); 12031 Lo = Builder.CreateZExt(Lo, ValTy, "lo64"); 12032 Hi = Builder.CreateZExt(Hi, ValTy, "hi64"); 12033 return Builder.CreateOr( 12034 Lo, Builder.CreateShl(Hi, ConstantInt::get(ValTy, 32)), "val64"); 12035 } 12036 12037 Type *Tys[] = { Addr->getType() }; 12038 Intrinsic::ID Int = IsAcquire ? Intrinsic::arm_ldaex : Intrinsic::arm_ldrex; 12039 Function *Ldrex = llvm::Intrinsic::getDeclaration(M, Int, Tys); 12040 12041 return Builder.CreateTruncOrBitCast( 12042 Builder.CreateCall(Ldrex, Addr), 12043 cast<PointerType>(Addr->getType())->getElementType()); 12044 } 12045 12046 void ARMTargetLowering::emitAtomicCmpXchgNoStoreLLBalance( 12047 IRBuilder<> &Builder) const { 12048 if (!Subtarget->hasV7Ops()) 12049 return; 12050 Module *M = Builder.GetInsertBlock()->getParent()->getParent(); 12051 Builder.CreateCall(llvm::Intrinsic::getDeclaration(M, Intrinsic::arm_clrex)); 12052 } 12053 12054 Value *ARMTargetLowering::emitStoreConditional(IRBuilder<> &Builder, Value *Val, 12055 Value *Addr, 12056 AtomicOrdering Ord) const { 12057 Module *M = Builder.GetInsertBlock()->getParent()->getParent(); 12058 bool IsRelease = isAtLeastRelease(Ord); 12059 12060 // Since the intrinsics must have legal type, the i64 intrinsics take two 12061 // parameters: "i32, i32". We must marshal Val into the appropriate form 12062 // before the call. 12063 if (Val->getType()->getPrimitiveSizeInBits() == 64) { 12064 Intrinsic::ID Int = 12065 IsRelease ? Intrinsic::arm_stlexd : Intrinsic::arm_strexd; 12066 Function *Strex = Intrinsic::getDeclaration(M, Int); 12067 Type *Int32Ty = Type::getInt32Ty(M->getContext()); 12068 12069 Value *Lo = Builder.CreateTrunc(Val, Int32Ty, "lo"); 12070 Value *Hi = Builder.CreateTrunc(Builder.CreateLShr(Val, 32), Int32Ty, "hi"); 12071 if (!Subtarget->isLittle()) 12072 std::swap (Lo, Hi); 12073 Addr = Builder.CreateBitCast(Addr, Type::getInt8PtrTy(M->getContext())); 12074 return Builder.CreateCall(Strex, {Lo, Hi, Addr}); 12075 } 12076 12077 Intrinsic::ID Int = IsRelease ? Intrinsic::arm_stlex : Intrinsic::arm_strex; 12078 Type *Tys[] = { Addr->getType() }; 12079 Function *Strex = Intrinsic::getDeclaration(M, Int, Tys); 12080 12081 return Builder.CreateCall( 12082 Strex, {Builder.CreateZExtOrBitCast( 12083 Val, Strex->getFunctionType()->getParamType(0)), 12084 Addr}); 12085 } 12086 12087 /// \brief Lower an interleaved load into a vldN intrinsic. 12088 /// 12089 /// E.g. Lower an interleaved load (Factor = 2): 12090 /// %wide.vec = load <8 x i32>, <8 x i32>* %ptr, align 4 12091 /// %v0 = shuffle %wide.vec, undef, <0, 2, 4, 6> ; Extract even elements 12092 /// %v1 = shuffle %wide.vec, undef, <1, 3, 5, 7> ; Extract odd elements 12093 /// 12094 /// Into: 12095 /// %vld2 = { <4 x i32>, <4 x i32> } call llvm.arm.neon.vld2(%ptr, 4) 12096 /// %vec0 = extractelement { <4 x i32>, <4 x i32> } %vld2, i32 0 12097 /// %vec1 = extractelement { <4 x i32>, <4 x i32> } %vld2, i32 1 12098 bool ARMTargetLowering::lowerInterleavedLoad( 12099 LoadInst *LI, ArrayRef<ShuffleVectorInst *> Shuffles, 12100 ArrayRef<unsigned> Indices, unsigned Factor) const { 12101 assert(Factor >= 2 && Factor <= getMaxSupportedInterleaveFactor() && 12102 "Invalid interleave factor"); 12103 assert(!Shuffles.empty() && "Empty shufflevector input"); 12104 assert(Shuffles.size() == Indices.size() && 12105 "Unmatched number of shufflevectors and indices"); 12106 12107 VectorType *VecTy = Shuffles[0]->getType(); 12108 Type *EltTy = VecTy->getVectorElementType(); 12109 12110 const DataLayout &DL = LI->getModule()->getDataLayout(); 12111 unsigned VecSize = DL.getTypeAllocSizeInBits(VecTy); 12112 bool EltIs64Bits = DL.getTypeAllocSizeInBits(EltTy) == 64; 12113 12114 // Skip if we do not have NEON and skip illegal vector types and vector types 12115 // with i64/f64 elements (vldN doesn't support i64/f64 elements). 12116 if (!Subtarget->hasNEON() || (VecSize != 64 && VecSize != 128) || EltIs64Bits) 12117 return false; 12118 12119 // A pointer vector can not be the return type of the ldN intrinsics. Need to 12120 // load integer vectors first and then convert to pointer vectors. 12121 if (EltTy->isPointerTy()) 12122 VecTy = 12123 VectorType::get(DL.getIntPtrType(EltTy), VecTy->getVectorNumElements()); 12124 12125 static const Intrinsic::ID LoadInts[3] = {Intrinsic::arm_neon_vld2, 12126 Intrinsic::arm_neon_vld3, 12127 Intrinsic::arm_neon_vld4}; 12128 12129 IRBuilder<> Builder(LI); 12130 SmallVector<Value *, 2> Ops; 12131 12132 Type *Int8Ptr = Builder.getInt8PtrTy(LI->getPointerAddressSpace()); 12133 Ops.push_back(Builder.CreateBitCast(LI->getPointerOperand(), Int8Ptr)); 12134 Ops.push_back(Builder.getInt32(LI->getAlignment())); 12135 12136 Type *Tys[] = { VecTy, Int8Ptr }; 12137 Function *VldnFunc = 12138 Intrinsic::getDeclaration(LI->getModule(), LoadInts[Factor - 2], Tys); 12139 CallInst *VldN = Builder.CreateCall(VldnFunc, Ops, "vldN"); 12140 12141 // Replace uses of each shufflevector with the corresponding vector loaded 12142 // by ldN. 12143 for (unsigned i = 0; i < Shuffles.size(); i++) { 12144 ShuffleVectorInst *SV = Shuffles[i]; 12145 unsigned Index = Indices[i]; 12146 12147 Value *SubVec = Builder.CreateExtractValue(VldN, Index); 12148 12149 // Convert the integer vector to pointer vector if the element is pointer. 12150 if (EltTy->isPointerTy()) 12151 SubVec = Builder.CreateIntToPtr(SubVec, SV->getType()); 12152 12153 SV->replaceAllUsesWith(SubVec); 12154 } 12155 12156 return true; 12157 } 12158 12159 /// \brief Get a mask consisting of sequential integers starting from \p Start. 12160 /// 12161 /// I.e. <Start, Start + 1, ..., Start + NumElts - 1> 12162 static Constant *getSequentialMask(IRBuilder<> &Builder, unsigned Start, 12163 unsigned NumElts) { 12164 SmallVector<Constant *, 16> Mask; 12165 for (unsigned i = 0; i < NumElts; i++) 12166 Mask.push_back(Builder.getInt32(Start + i)); 12167 12168 return ConstantVector::get(Mask); 12169 } 12170 12171 /// \brief Lower an interleaved store into a vstN intrinsic. 12172 /// 12173 /// E.g. Lower an interleaved store (Factor = 3): 12174 /// %i.vec = shuffle <8 x i32> %v0, <8 x i32> %v1, 12175 /// <0, 4, 8, 1, 5, 9, 2, 6, 10, 3, 7, 11> 12176 /// store <12 x i32> %i.vec, <12 x i32>* %ptr, align 4 12177 /// 12178 /// Into: 12179 /// %sub.v0 = shuffle <8 x i32> %v0, <8 x i32> v1, <0, 1, 2, 3> 12180 /// %sub.v1 = shuffle <8 x i32> %v0, <8 x i32> v1, <4, 5, 6, 7> 12181 /// %sub.v2 = shuffle <8 x i32> %v0, <8 x i32> v1, <8, 9, 10, 11> 12182 /// call void llvm.arm.neon.vst3(%ptr, %sub.v0, %sub.v1, %sub.v2, 4) 12183 /// 12184 /// Note that the new shufflevectors will be removed and we'll only generate one 12185 /// vst3 instruction in CodeGen. 12186 bool ARMTargetLowering::lowerInterleavedStore(StoreInst *SI, 12187 ShuffleVectorInst *SVI, 12188 unsigned Factor) const { 12189 assert(Factor >= 2 && Factor <= getMaxSupportedInterleaveFactor() && 12190 "Invalid interleave factor"); 12191 12192 VectorType *VecTy = SVI->getType(); 12193 assert(VecTy->getVectorNumElements() % Factor == 0 && 12194 "Invalid interleaved store"); 12195 12196 unsigned NumSubElts = VecTy->getVectorNumElements() / Factor; 12197 Type *EltTy = VecTy->getVectorElementType(); 12198 VectorType *SubVecTy = VectorType::get(EltTy, NumSubElts); 12199 12200 const DataLayout &DL = SI->getModule()->getDataLayout(); 12201 unsigned SubVecSize = DL.getTypeAllocSizeInBits(SubVecTy); 12202 bool EltIs64Bits = DL.getTypeAllocSizeInBits(EltTy) == 64; 12203 12204 // Skip if we do not have NEON and skip illegal vector types and vector types 12205 // with i64/f64 elements (vstN doesn't support i64/f64 elements). 12206 if (!Subtarget->hasNEON() || (SubVecSize != 64 && SubVecSize != 128) || 12207 EltIs64Bits) 12208 return false; 12209 12210 Value *Op0 = SVI->getOperand(0); 12211 Value *Op1 = SVI->getOperand(1); 12212 IRBuilder<> Builder(SI); 12213 12214 // StN intrinsics don't support pointer vectors as arguments. Convert pointer 12215 // vectors to integer vectors. 12216 if (EltTy->isPointerTy()) { 12217 Type *IntTy = DL.getIntPtrType(EltTy); 12218 12219 // Convert to the corresponding integer vector. 12220 Type *IntVecTy = 12221 VectorType::get(IntTy, Op0->getType()->getVectorNumElements()); 12222 Op0 = Builder.CreatePtrToInt(Op0, IntVecTy); 12223 Op1 = Builder.CreatePtrToInt(Op1, IntVecTy); 12224 12225 SubVecTy = VectorType::get(IntTy, NumSubElts); 12226 } 12227 12228 static const Intrinsic::ID StoreInts[3] = {Intrinsic::arm_neon_vst2, 12229 Intrinsic::arm_neon_vst3, 12230 Intrinsic::arm_neon_vst4}; 12231 SmallVector<Value *, 6> Ops; 12232 12233 Type *Int8Ptr = Builder.getInt8PtrTy(SI->getPointerAddressSpace()); 12234 Ops.push_back(Builder.CreateBitCast(SI->getPointerOperand(), Int8Ptr)); 12235 12236 Type *Tys[] = { Int8Ptr, SubVecTy }; 12237 Function *VstNFunc = Intrinsic::getDeclaration( 12238 SI->getModule(), StoreInts[Factor - 2], Tys); 12239 12240 // Split the shufflevector operands into sub vectors for the new vstN call. 12241 for (unsigned i = 0; i < Factor; i++) 12242 Ops.push_back(Builder.CreateShuffleVector( 12243 Op0, Op1, getSequentialMask(Builder, NumSubElts * i, NumSubElts))); 12244 12245 Ops.push_back(Builder.getInt32(SI->getAlignment())); 12246 Builder.CreateCall(VstNFunc, Ops); 12247 return true; 12248 } 12249 12250 enum HABaseType { 12251 HA_UNKNOWN = 0, 12252 HA_FLOAT, 12253 HA_DOUBLE, 12254 HA_VECT64, 12255 HA_VECT128 12256 }; 12257 12258 static bool isHomogeneousAggregate(Type *Ty, HABaseType &Base, 12259 uint64_t &Members) { 12260 if (auto *ST = dyn_cast<StructType>(Ty)) { 12261 for (unsigned i = 0; i < ST->getNumElements(); ++i) { 12262 uint64_t SubMembers = 0; 12263 if (!isHomogeneousAggregate(ST->getElementType(i), Base, SubMembers)) 12264 return false; 12265 Members += SubMembers; 12266 } 12267 } else if (auto *AT = dyn_cast<ArrayType>(Ty)) { 12268 uint64_t SubMembers = 0; 12269 if (!isHomogeneousAggregate(AT->getElementType(), Base, SubMembers)) 12270 return false; 12271 Members += SubMembers * AT->getNumElements(); 12272 } else if (Ty->isFloatTy()) { 12273 if (Base != HA_UNKNOWN && Base != HA_FLOAT) 12274 return false; 12275 Members = 1; 12276 Base = HA_FLOAT; 12277 } else if (Ty->isDoubleTy()) { 12278 if (Base != HA_UNKNOWN && Base != HA_DOUBLE) 12279 return false; 12280 Members = 1; 12281 Base = HA_DOUBLE; 12282 } else if (auto *VT = dyn_cast<VectorType>(Ty)) { 12283 Members = 1; 12284 switch (Base) { 12285 case HA_FLOAT: 12286 case HA_DOUBLE: 12287 return false; 12288 case HA_VECT64: 12289 return VT->getBitWidth() == 64; 12290 case HA_VECT128: 12291 return VT->getBitWidth() == 128; 12292 case HA_UNKNOWN: 12293 switch (VT->getBitWidth()) { 12294 case 64: 12295 Base = HA_VECT64; 12296 return true; 12297 case 128: 12298 Base = HA_VECT128; 12299 return true; 12300 default: 12301 return false; 12302 } 12303 } 12304 } 12305 12306 return (Members > 0 && Members <= 4); 12307 } 12308 12309 /// \brief Return true if a type is an AAPCS-VFP homogeneous aggregate or one of 12310 /// [N x i32] or [N x i64]. This allows front-ends to skip emitting padding when 12311 /// passing according to AAPCS rules. 12312 bool ARMTargetLowering::functionArgumentNeedsConsecutiveRegisters( 12313 Type *Ty, CallingConv::ID CallConv, bool isVarArg) const { 12314 if (getEffectiveCallingConv(CallConv, isVarArg) != 12315 CallingConv::ARM_AAPCS_VFP) 12316 return false; 12317 12318 HABaseType Base = HA_UNKNOWN; 12319 uint64_t Members = 0; 12320 bool IsHA = isHomogeneousAggregate(Ty, Base, Members); 12321 DEBUG(dbgs() << "isHA: " << IsHA << " "; Ty->dump()); 12322 12323 bool IsIntArray = Ty->isArrayTy() && Ty->getArrayElementType()->isIntegerTy(); 12324 return IsHA || IsIntArray; 12325 } 12326 12327 unsigned ARMTargetLowering::getExceptionPointerRegister( 12328 const Constant *PersonalityFn) const { 12329 // Platforms which do not use SjLj EH may return values in these registers 12330 // via the personality function. 12331 return Subtarget->useSjLjEH() ? ARM::NoRegister : ARM::R0; 12332 } 12333 12334 unsigned ARMTargetLowering::getExceptionSelectorRegister( 12335 const Constant *PersonalityFn) const { 12336 // Platforms which do not use SjLj EH may return values in these registers 12337 // via the personality function. 12338 return Subtarget->useSjLjEH() ? ARM::NoRegister : ARM::R1; 12339 } 12340