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 void ARMTargetLowering::InitLibcallCallingConvs() { 84 // The builtins on ARM always use AAPCS, irrespective of wheter C is AAPCS or 85 // AAPCS_VFP. 86 for (const auto LC : { 87 RTLIB::SHL_I16, 88 RTLIB::SHL_I32, 89 RTLIB::SHL_I64, 90 RTLIB::SHL_I128, 91 RTLIB::SRL_I16, 92 RTLIB::SRL_I32, 93 RTLIB::SRL_I64, 94 RTLIB::SRL_I128, 95 RTLIB::SRA_I16, 96 RTLIB::SRA_I32, 97 RTLIB::SRA_I64, 98 RTLIB::SRA_I128, 99 RTLIB::MUL_I8, 100 RTLIB::MUL_I16, 101 RTLIB::MUL_I32, 102 RTLIB::MUL_I64, 103 RTLIB::MUL_I128, 104 RTLIB::MULO_I32, 105 RTLIB::MULO_I64, 106 RTLIB::MULO_I128, 107 RTLIB::SDIV_I8, 108 RTLIB::SDIV_I16, 109 RTLIB::SDIV_I32, 110 RTLIB::SDIV_I64, 111 RTLIB::SDIV_I128, 112 RTLIB::UDIV_I8, 113 RTLIB::UDIV_I16, 114 RTLIB::UDIV_I32, 115 RTLIB::UDIV_I64, 116 RTLIB::UDIV_I128, 117 RTLIB::SREM_I8, 118 RTLIB::SREM_I16, 119 RTLIB::SREM_I32, 120 RTLIB::SREM_I64, 121 RTLIB::SREM_I128, 122 RTLIB::UREM_I8, 123 RTLIB::UREM_I16, 124 RTLIB::UREM_I32, 125 RTLIB::UREM_I64, 126 RTLIB::UREM_I128, 127 RTLIB::SDIVREM_I8, 128 RTLIB::SDIVREM_I16, 129 RTLIB::SDIVREM_I32, 130 RTLIB::SDIVREM_I64, 131 RTLIB::SDIVREM_I128, 132 RTLIB::UDIVREM_I8, 133 RTLIB::UDIVREM_I16, 134 RTLIB::UDIVREM_I32, 135 RTLIB::UDIVREM_I64, 136 RTLIB::UDIVREM_I128, 137 RTLIB::NEG_I32, 138 RTLIB::NEG_I64, 139 RTLIB::ADD_F32, 140 RTLIB::ADD_F64, 141 RTLIB::ADD_F80, 142 RTLIB::ADD_F128, 143 RTLIB::SUB_F32, 144 RTLIB::SUB_F64, 145 RTLIB::SUB_F80, 146 RTLIB::SUB_F128, 147 RTLIB::MUL_F32, 148 RTLIB::MUL_F64, 149 RTLIB::MUL_F80, 150 RTLIB::MUL_F128, 151 RTLIB::DIV_F32, 152 RTLIB::DIV_F64, 153 RTLIB::DIV_F80, 154 RTLIB::DIV_F128, 155 RTLIB::POWI_F32, 156 RTLIB::POWI_F64, 157 RTLIB::POWI_F80, 158 RTLIB::POWI_F128, 159 RTLIB::FPEXT_F64_F128, 160 RTLIB::FPEXT_F32_F128, 161 RTLIB::FPEXT_F32_F64, 162 RTLIB::FPEXT_F16_F32, 163 RTLIB::FPROUND_F32_F16, 164 RTLIB::FPROUND_F64_F16, 165 RTLIB::FPROUND_F80_F16, 166 RTLIB::FPROUND_F128_F16, 167 RTLIB::FPROUND_F64_F32, 168 RTLIB::FPROUND_F80_F32, 169 RTLIB::FPROUND_F128_F32, 170 RTLIB::FPROUND_F80_F64, 171 RTLIB::FPROUND_F128_F64, 172 RTLIB::FPTOSINT_F32_I32, 173 RTLIB::FPTOSINT_F32_I64, 174 RTLIB::FPTOSINT_F32_I128, 175 RTLIB::FPTOSINT_F64_I32, 176 RTLIB::FPTOSINT_F64_I64, 177 RTLIB::FPTOSINT_F64_I128, 178 RTLIB::FPTOSINT_F80_I32, 179 RTLIB::FPTOSINT_F80_I64, 180 RTLIB::FPTOSINT_F80_I128, 181 RTLIB::FPTOSINT_F128_I32, 182 RTLIB::FPTOSINT_F128_I64, 183 RTLIB::FPTOSINT_F128_I128, 184 RTLIB::FPTOUINT_F32_I32, 185 RTLIB::FPTOUINT_F32_I64, 186 RTLIB::FPTOUINT_F32_I128, 187 RTLIB::FPTOUINT_F64_I32, 188 RTLIB::FPTOUINT_F64_I64, 189 RTLIB::FPTOUINT_F64_I128, 190 RTLIB::FPTOUINT_F80_I32, 191 RTLIB::FPTOUINT_F80_I64, 192 RTLIB::FPTOUINT_F80_I128, 193 RTLIB::FPTOUINT_F128_I32, 194 RTLIB::FPTOUINT_F128_I64, 195 RTLIB::FPTOUINT_F128_I128, 196 RTLIB::SINTTOFP_I32_F32, 197 RTLIB::SINTTOFP_I32_F64, 198 RTLIB::SINTTOFP_I32_F80, 199 RTLIB::SINTTOFP_I32_F128, 200 RTLIB::SINTTOFP_I64_F32, 201 RTLIB::SINTTOFP_I64_F64, 202 RTLIB::SINTTOFP_I64_F80, 203 RTLIB::SINTTOFP_I64_F128, 204 RTLIB::SINTTOFP_I128_F32, 205 RTLIB::SINTTOFP_I128_F64, 206 RTLIB::SINTTOFP_I128_F80, 207 RTLIB::SINTTOFP_I128_F128, 208 RTLIB::UINTTOFP_I32_F32, 209 RTLIB::UINTTOFP_I32_F64, 210 RTLIB::UINTTOFP_I32_F80, 211 RTLIB::UINTTOFP_I32_F128, 212 RTLIB::UINTTOFP_I64_F32, 213 RTLIB::UINTTOFP_I64_F64, 214 RTLIB::UINTTOFP_I64_F80, 215 RTLIB::UINTTOFP_I64_F128, 216 RTLIB::UINTTOFP_I128_F32, 217 RTLIB::UINTTOFP_I128_F64, 218 RTLIB::UINTTOFP_I128_F80, 219 RTLIB::UINTTOFP_I128_F128, 220 RTLIB::OEQ_F32, 221 RTLIB::OEQ_F64, 222 RTLIB::OEQ_F128, 223 RTLIB::UNE_F32, 224 RTLIB::UNE_F64, 225 RTLIB::UNE_F128, 226 RTLIB::OGE_F32, 227 RTLIB::OGE_F64, 228 RTLIB::OGE_F128, 229 RTLIB::OLT_F32, 230 RTLIB::OLT_F64, 231 RTLIB::OLT_F128, 232 RTLIB::OLE_F32, 233 RTLIB::OLE_F64, 234 RTLIB::OLE_F128, 235 RTLIB::OGT_F32, 236 RTLIB::OGT_F64, 237 RTLIB::OGT_F128, 238 RTLIB::UO_F32, 239 RTLIB::UO_F64, 240 RTLIB::UO_F128, 241 RTLIB::O_F32, 242 RTLIB::O_F64, 243 RTLIB::O_F128, 244 }) 245 setLibcallCallingConv(LC, CallingConv::ARM_AAPCS); 246 } 247 248 // The APCS parameter registers. 249 static const MCPhysReg GPRArgRegs[] = { 250 ARM::R0, ARM::R1, ARM::R2, ARM::R3 251 }; 252 253 void ARMTargetLowering::addTypeForNEON(MVT VT, MVT PromotedLdStVT, 254 MVT PromotedBitwiseVT) { 255 if (VT != PromotedLdStVT) { 256 setOperationAction(ISD::LOAD, VT, Promote); 257 AddPromotedToType (ISD::LOAD, VT, PromotedLdStVT); 258 259 setOperationAction(ISD::STORE, VT, Promote); 260 AddPromotedToType (ISD::STORE, VT, PromotedLdStVT); 261 } 262 263 MVT ElemTy = VT.getVectorElementType(); 264 if (ElemTy != MVT::i64 && ElemTy != MVT::f64) 265 setOperationAction(ISD::SETCC, VT, Custom); 266 setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Custom); 267 setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom); 268 if (ElemTy == MVT::i32) { 269 setOperationAction(ISD::SINT_TO_FP, VT, Custom); 270 setOperationAction(ISD::UINT_TO_FP, VT, Custom); 271 setOperationAction(ISD::FP_TO_SINT, VT, Custom); 272 setOperationAction(ISD::FP_TO_UINT, VT, Custom); 273 } else { 274 setOperationAction(ISD::SINT_TO_FP, VT, Expand); 275 setOperationAction(ISD::UINT_TO_FP, VT, Expand); 276 setOperationAction(ISD::FP_TO_SINT, VT, Expand); 277 setOperationAction(ISD::FP_TO_UINT, VT, Expand); 278 } 279 setOperationAction(ISD::BUILD_VECTOR, VT, Custom); 280 setOperationAction(ISD::VECTOR_SHUFFLE, VT, Custom); 281 setOperationAction(ISD::CONCAT_VECTORS, VT, Legal); 282 setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Legal); 283 setOperationAction(ISD::SELECT, VT, Expand); 284 setOperationAction(ISD::SELECT_CC, VT, Expand); 285 setOperationAction(ISD::VSELECT, VT, Expand); 286 setOperationAction(ISD::SIGN_EXTEND_INREG, VT, Expand); 287 if (VT.isInteger()) { 288 setOperationAction(ISD::SHL, VT, Custom); 289 setOperationAction(ISD::SRA, VT, Custom); 290 setOperationAction(ISD::SRL, VT, Custom); 291 } 292 293 // Promote all bit-wise operations. 294 if (VT.isInteger() && VT != PromotedBitwiseVT) { 295 setOperationAction(ISD::AND, VT, Promote); 296 AddPromotedToType (ISD::AND, VT, PromotedBitwiseVT); 297 setOperationAction(ISD::OR, VT, Promote); 298 AddPromotedToType (ISD::OR, VT, PromotedBitwiseVT); 299 setOperationAction(ISD::XOR, VT, Promote); 300 AddPromotedToType (ISD::XOR, VT, PromotedBitwiseVT); 301 } 302 303 // Neon does not support vector divide/remainder operations. 304 setOperationAction(ISD::SDIV, VT, Expand); 305 setOperationAction(ISD::UDIV, VT, Expand); 306 setOperationAction(ISD::FDIV, VT, Expand); 307 setOperationAction(ISD::SREM, VT, Expand); 308 setOperationAction(ISD::UREM, VT, Expand); 309 setOperationAction(ISD::FREM, VT, Expand); 310 311 if (!VT.isFloatingPoint() && 312 VT != MVT::v2i64 && VT != MVT::v1i64) 313 for (unsigned Opcode : {ISD::SMIN, ISD::SMAX, ISD::UMIN, ISD::UMAX}) 314 setOperationAction(Opcode, VT, Legal); 315 } 316 317 void ARMTargetLowering::addDRTypeForNEON(MVT VT) { 318 addRegisterClass(VT, &ARM::DPRRegClass); 319 addTypeForNEON(VT, MVT::f64, MVT::v2i32); 320 } 321 322 void ARMTargetLowering::addQRTypeForNEON(MVT VT) { 323 addRegisterClass(VT, &ARM::DPairRegClass); 324 addTypeForNEON(VT, MVT::v2f64, MVT::v4i32); 325 } 326 327 ARMTargetLowering::ARMTargetLowering(const TargetMachine &TM, 328 const ARMSubtarget &STI) 329 : TargetLowering(TM), Subtarget(&STI) { 330 RegInfo = Subtarget->getRegisterInfo(); 331 Itins = Subtarget->getInstrItineraryData(); 332 333 setBooleanVectorContents(ZeroOrNegativeOneBooleanContent); 334 335 InitLibcallCallingConvs(); 336 337 if (Subtarget->isTargetMachO()) { 338 // Uses VFP for Thumb libfuncs if available. 339 if (Subtarget->isThumb() && Subtarget->hasVFP2() && 340 Subtarget->hasARMOps() && !Subtarget->useSoftFloat()) { 341 static const struct { 342 const RTLIB::Libcall Op; 343 const char * const Name; 344 const ISD::CondCode Cond; 345 } LibraryCalls[] = { 346 // Single-precision floating-point arithmetic. 347 { RTLIB::ADD_F32, "__addsf3vfp", ISD::SETCC_INVALID }, 348 { RTLIB::SUB_F32, "__subsf3vfp", ISD::SETCC_INVALID }, 349 { RTLIB::MUL_F32, "__mulsf3vfp", ISD::SETCC_INVALID }, 350 { RTLIB::DIV_F32, "__divsf3vfp", ISD::SETCC_INVALID }, 351 352 // Double-precision floating-point arithmetic. 353 { RTLIB::ADD_F64, "__adddf3vfp", ISD::SETCC_INVALID }, 354 { RTLIB::SUB_F64, "__subdf3vfp", ISD::SETCC_INVALID }, 355 { RTLIB::MUL_F64, "__muldf3vfp", ISD::SETCC_INVALID }, 356 { RTLIB::DIV_F64, "__divdf3vfp", ISD::SETCC_INVALID }, 357 358 // Single-precision comparisons. 359 { RTLIB::OEQ_F32, "__eqsf2vfp", ISD::SETNE }, 360 { RTLIB::UNE_F32, "__nesf2vfp", ISD::SETNE }, 361 { RTLIB::OLT_F32, "__ltsf2vfp", ISD::SETNE }, 362 { RTLIB::OLE_F32, "__lesf2vfp", ISD::SETNE }, 363 { RTLIB::OGE_F32, "__gesf2vfp", ISD::SETNE }, 364 { RTLIB::OGT_F32, "__gtsf2vfp", ISD::SETNE }, 365 { RTLIB::UO_F32, "__unordsf2vfp", ISD::SETNE }, 366 { RTLIB::O_F32, "__unordsf2vfp", ISD::SETEQ }, 367 368 // Double-precision comparisons. 369 { RTLIB::OEQ_F64, "__eqdf2vfp", ISD::SETNE }, 370 { RTLIB::UNE_F64, "__nedf2vfp", ISD::SETNE }, 371 { RTLIB::OLT_F64, "__ltdf2vfp", ISD::SETNE }, 372 { RTLIB::OLE_F64, "__ledf2vfp", ISD::SETNE }, 373 { RTLIB::OGE_F64, "__gedf2vfp", ISD::SETNE }, 374 { RTLIB::OGT_F64, "__gtdf2vfp", ISD::SETNE }, 375 { RTLIB::UO_F64, "__unorddf2vfp", ISD::SETNE }, 376 { RTLIB::O_F64, "__unorddf2vfp", ISD::SETEQ }, 377 378 // Floating-point to integer conversions. 379 // i64 conversions are done via library routines even when generating VFP 380 // instructions, so use the same ones. 381 { RTLIB::FPTOSINT_F64_I32, "__fixdfsivfp", ISD::SETCC_INVALID }, 382 { RTLIB::FPTOUINT_F64_I32, "__fixunsdfsivfp", ISD::SETCC_INVALID }, 383 { RTLIB::FPTOSINT_F32_I32, "__fixsfsivfp", ISD::SETCC_INVALID }, 384 { RTLIB::FPTOUINT_F32_I32, "__fixunssfsivfp", ISD::SETCC_INVALID }, 385 386 // Conversions between floating types. 387 { RTLIB::FPROUND_F64_F32, "__truncdfsf2vfp", ISD::SETCC_INVALID }, 388 { RTLIB::FPEXT_F32_F64, "__extendsfdf2vfp", ISD::SETCC_INVALID }, 389 390 // Integer to floating-point conversions. 391 // i64 conversions are done via library routines even when generating VFP 392 // instructions, so use the same ones. 393 // FIXME: There appears to be some naming inconsistency in ARM libgcc: 394 // e.g., __floatunsidf vs. __floatunssidfvfp. 395 { RTLIB::SINTTOFP_I32_F64, "__floatsidfvfp", ISD::SETCC_INVALID }, 396 { RTLIB::UINTTOFP_I32_F64, "__floatunssidfvfp", ISD::SETCC_INVALID }, 397 { RTLIB::SINTTOFP_I32_F32, "__floatsisfvfp", ISD::SETCC_INVALID }, 398 { RTLIB::UINTTOFP_I32_F32, "__floatunssisfvfp", ISD::SETCC_INVALID }, 399 }; 400 401 for (const auto &LC : LibraryCalls) { 402 setLibcallName(LC.Op, LC.Name); 403 if (LC.Cond != ISD::SETCC_INVALID) 404 setCmpLibcallCC(LC.Op, LC.Cond); 405 } 406 } 407 408 // Set the correct calling convention for ARMv7k WatchOS. It's just 409 // AAPCS_VFP for functions as simple as libcalls. 410 if (Subtarget->isTargetWatchABI()) { 411 for (int i = 0; i < RTLIB::UNKNOWN_LIBCALL; ++i) 412 setLibcallCallingConv((RTLIB::Libcall)i, CallingConv::ARM_AAPCS_VFP); 413 } 414 } 415 416 // These libcalls are not available in 32-bit. 417 setLibcallName(RTLIB::SHL_I128, nullptr); 418 setLibcallName(RTLIB::SRL_I128, nullptr); 419 setLibcallName(RTLIB::SRA_I128, nullptr); 420 421 // RTLIB 422 if (Subtarget->isAAPCS_ABI() && 423 (Subtarget->isTargetAEABI() || Subtarget->isTargetGNUAEABI() || 424 Subtarget->isTargetMuslAEABI() || Subtarget->isTargetAndroid())) { 425 static const struct { 426 const RTLIB::Libcall Op; 427 const char * const Name; 428 const CallingConv::ID CC; 429 const ISD::CondCode Cond; 430 } LibraryCalls[] = { 431 // Double-precision floating-point arithmetic helper functions 432 // RTABI chapter 4.1.2, Table 2 433 { RTLIB::ADD_F64, "__aeabi_dadd", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 434 { RTLIB::DIV_F64, "__aeabi_ddiv", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 435 { RTLIB::MUL_F64, "__aeabi_dmul", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 436 { RTLIB::SUB_F64, "__aeabi_dsub", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 437 438 // Double-precision floating-point comparison helper functions 439 // RTABI chapter 4.1.2, Table 3 440 { RTLIB::OEQ_F64, "__aeabi_dcmpeq", CallingConv::ARM_AAPCS, ISD::SETNE }, 441 { RTLIB::UNE_F64, "__aeabi_dcmpeq", CallingConv::ARM_AAPCS, ISD::SETEQ }, 442 { RTLIB::OLT_F64, "__aeabi_dcmplt", CallingConv::ARM_AAPCS, ISD::SETNE }, 443 { RTLIB::OLE_F64, "__aeabi_dcmple", CallingConv::ARM_AAPCS, ISD::SETNE }, 444 { RTLIB::OGE_F64, "__aeabi_dcmpge", CallingConv::ARM_AAPCS, ISD::SETNE }, 445 { RTLIB::OGT_F64, "__aeabi_dcmpgt", CallingConv::ARM_AAPCS, ISD::SETNE }, 446 { RTLIB::UO_F64, "__aeabi_dcmpun", CallingConv::ARM_AAPCS, ISD::SETNE }, 447 { RTLIB::O_F64, "__aeabi_dcmpun", CallingConv::ARM_AAPCS, ISD::SETEQ }, 448 449 // Single-precision floating-point arithmetic helper functions 450 // RTABI chapter 4.1.2, Table 4 451 { RTLIB::ADD_F32, "__aeabi_fadd", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 452 { RTLIB::DIV_F32, "__aeabi_fdiv", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 453 { RTLIB::MUL_F32, "__aeabi_fmul", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 454 { RTLIB::SUB_F32, "__aeabi_fsub", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 455 456 // Single-precision floating-point comparison helper functions 457 // RTABI chapter 4.1.2, Table 5 458 { RTLIB::OEQ_F32, "__aeabi_fcmpeq", CallingConv::ARM_AAPCS, ISD::SETNE }, 459 { RTLIB::UNE_F32, "__aeabi_fcmpeq", CallingConv::ARM_AAPCS, ISD::SETEQ }, 460 { RTLIB::OLT_F32, "__aeabi_fcmplt", CallingConv::ARM_AAPCS, ISD::SETNE }, 461 { RTLIB::OLE_F32, "__aeabi_fcmple", CallingConv::ARM_AAPCS, ISD::SETNE }, 462 { RTLIB::OGE_F32, "__aeabi_fcmpge", CallingConv::ARM_AAPCS, ISD::SETNE }, 463 { RTLIB::OGT_F32, "__aeabi_fcmpgt", CallingConv::ARM_AAPCS, ISD::SETNE }, 464 { RTLIB::UO_F32, "__aeabi_fcmpun", CallingConv::ARM_AAPCS, ISD::SETNE }, 465 { RTLIB::O_F32, "__aeabi_fcmpun", CallingConv::ARM_AAPCS, ISD::SETEQ }, 466 467 // Floating-point to integer conversions. 468 // RTABI chapter 4.1.2, Table 6 469 { RTLIB::FPTOSINT_F64_I32, "__aeabi_d2iz", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 470 { RTLIB::FPTOUINT_F64_I32, "__aeabi_d2uiz", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 471 { RTLIB::FPTOSINT_F64_I64, "__aeabi_d2lz", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 472 { RTLIB::FPTOUINT_F64_I64, "__aeabi_d2ulz", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 473 { RTLIB::FPTOSINT_F32_I32, "__aeabi_f2iz", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 474 { RTLIB::FPTOUINT_F32_I32, "__aeabi_f2uiz", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 475 { RTLIB::FPTOSINT_F32_I64, "__aeabi_f2lz", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 476 { RTLIB::FPTOUINT_F32_I64, "__aeabi_f2ulz", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 477 478 // Conversions between floating types. 479 // RTABI chapter 4.1.2, Table 7 480 { RTLIB::FPROUND_F64_F32, "__aeabi_d2f", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 481 { RTLIB::FPROUND_F64_F16, "__aeabi_d2h", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 482 { RTLIB::FPEXT_F32_F64, "__aeabi_f2d", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 483 484 // Integer to floating-point conversions. 485 // RTABI chapter 4.1.2, Table 8 486 { RTLIB::SINTTOFP_I32_F64, "__aeabi_i2d", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 487 { RTLIB::UINTTOFP_I32_F64, "__aeabi_ui2d", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 488 { RTLIB::SINTTOFP_I64_F64, "__aeabi_l2d", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 489 { RTLIB::UINTTOFP_I64_F64, "__aeabi_ul2d", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 490 { RTLIB::SINTTOFP_I32_F32, "__aeabi_i2f", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 491 { RTLIB::UINTTOFP_I32_F32, "__aeabi_ui2f", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 492 { RTLIB::SINTTOFP_I64_F32, "__aeabi_l2f", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 493 { RTLIB::UINTTOFP_I64_F32, "__aeabi_ul2f", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 494 495 // Long long helper functions 496 // RTABI chapter 4.2, Table 9 497 { RTLIB::MUL_I64, "__aeabi_lmul", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 498 { RTLIB::SHL_I64, "__aeabi_llsl", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 499 { RTLIB::SRL_I64, "__aeabi_llsr", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 500 { RTLIB::SRA_I64, "__aeabi_lasr", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 501 502 // Integer division functions 503 // RTABI chapter 4.3.1 504 { RTLIB::SDIV_I8, "__aeabi_idiv", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 505 { RTLIB::SDIV_I16, "__aeabi_idiv", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 506 { RTLIB::SDIV_I32, "__aeabi_idiv", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 507 { RTLIB::SDIV_I64, "__aeabi_ldivmod", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 508 { RTLIB::UDIV_I8, "__aeabi_uidiv", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 509 { RTLIB::UDIV_I16, "__aeabi_uidiv", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 510 { RTLIB::UDIV_I32, "__aeabi_uidiv", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 511 { RTLIB::UDIV_I64, "__aeabi_uldivmod", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 512 }; 513 514 for (const auto &LC : LibraryCalls) { 515 setLibcallName(LC.Op, LC.Name); 516 setLibcallCallingConv(LC.Op, LC.CC); 517 if (LC.Cond != ISD::SETCC_INVALID) 518 setCmpLibcallCC(LC.Op, LC.Cond); 519 } 520 521 // EABI dependent RTLIB 522 if (TM.Options.EABIVersion == EABI::EABI4 || 523 TM.Options.EABIVersion == EABI::EABI5) { 524 static const struct { 525 const RTLIB::Libcall Op; 526 const char *const Name; 527 const CallingConv::ID CC; 528 const ISD::CondCode Cond; 529 } MemOpsLibraryCalls[] = { 530 // Memory operations 531 // RTABI chapter 4.3.4 532 { RTLIB::MEMCPY, "__aeabi_memcpy", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 533 { RTLIB::MEMMOVE, "__aeabi_memmove", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 534 { RTLIB::MEMSET, "__aeabi_memset", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 535 }; 536 537 for (const auto &LC : MemOpsLibraryCalls) { 538 setLibcallName(LC.Op, LC.Name); 539 setLibcallCallingConv(LC.Op, LC.CC); 540 if (LC.Cond != ISD::SETCC_INVALID) 541 setCmpLibcallCC(LC.Op, LC.Cond); 542 } 543 } 544 } 545 546 if (Subtarget->isTargetWindows()) { 547 static const struct { 548 const RTLIB::Libcall Op; 549 const char * const Name; 550 const CallingConv::ID CC; 551 } LibraryCalls[] = { 552 { RTLIB::FPTOSINT_F32_I64, "__stoi64", CallingConv::ARM_AAPCS_VFP }, 553 { RTLIB::FPTOSINT_F64_I64, "__dtoi64", CallingConv::ARM_AAPCS_VFP }, 554 { RTLIB::FPTOUINT_F32_I64, "__stou64", CallingConv::ARM_AAPCS_VFP }, 555 { RTLIB::FPTOUINT_F64_I64, "__dtou64", CallingConv::ARM_AAPCS_VFP }, 556 { RTLIB::SINTTOFP_I64_F32, "__i64tos", CallingConv::ARM_AAPCS_VFP }, 557 { RTLIB::SINTTOFP_I64_F64, "__i64tod", CallingConv::ARM_AAPCS_VFP }, 558 { RTLIB::UINTTOFP_I64_F32, "__u64tos", CallingConv::ARM_AAPCS_VFP }, 559 { RTLIB::UINTTOFP_I64_F64, "__u64tod", CallingConv::ARM_AAPCS_VFP }, 560 }; 561 562 for (const auto &LC : LibraryCalls) { 563 setLibcallName(LC.Op, LC.Name); 564 setLibcallCallingConv(LC.Op, LC.CC); 565 } 566 } 567 568 // Use divmod compiler-rt calls for iOS 5.0 and later. 569 if (Subtarget->isTargetWatchOS() || 570 (Subtarget->isTargetIOS() && 571 !Subtarget->getTargetTriple().isOSVersionLT(5, 0))) { 572 setLibcallName(RTLIB::SDIVREM_I32, "__divmodsi4"); 573 setLibcallName(RTLIB::UDIVREM_I32, "__udivmodsi4"); 574 } 575 576 // The half <-> float conversion functions are always soft-float on 577 // non-watchos platforms, but are needed for some targets which use a 578 // hard-float calling convention by default. 579 if (!Subtarget->isTargetWatchABI()) { 580 if (Subtarget->isAAPCS_ABI()) { 581 setLibcallCallingConv(RTLIB::FPROUND_F32_F16, CallingConv::ARM_AAPCS); 582 setLibcallCallingConv(RTLIB::FPROUND_F64_F16, CallingConv::ARM_AAPCS); 583 setLibcallCallingConv(RTLIB::FPEXT_F16_F32, CallingConv::ARM_AAPCS); 584 } else { 585 setLibcallCallingConv(RTLIB::FPROUND_F32_F16, CallingConv::ARM_APCS); 586 setLibcallCallingConv(RTLIB::FPROUND_F64_F16, CallingConv::ARM_APCS); 587 setLibcallCallingConv(RTLIB::FPEXT_F16_F32, CallingConv::ARM_APCS); 588 } 589 } 590 591 // In EABI, these functions have an __aeabi_ prefix, but in GNUEABI they have 592 // a __gnu_ prefix (which is the default). 593 if (Subtarget->isTargetAEABI()) { 594 setLibcallName(RTLIB::FPROUND_F32_F16, "__aeabi_f2h"); 595 setLibcallName(RTLIB::FPROUND_F64_F16, "__aeabi_d2h"); 596 setLibcallName(RTLIB::FPEXT_F16_F32, "__aeabi_h2f"); 597 } 598 599 if (Subtarget->isThumb1Only()) 600 addRegisterClass(MVT::i32, &ARM::tGPRRegClass); 601 else 602 addRegisterClass(MVT::i32, &ARM::GPRRegClass); 603 if (!Subtarget->useSoftFloat() && Subtarget->hasVFP2() && 604 !Subtarget->isThumb1Only()) { 605 addRegisterClass(MVT::f32, &ARM::SPRRegClass); 606 addRegisterClass(MVT::f64, &ARM::DPRRegClass); 607 } 608 609 for (MVT VT : MVT::vector_valuetypes()) { 610 for (MVT InnerVT : MVT::vector_valuetypes()) { 611 setTruncStoreAction(VT, InnerVT, Expand); 612 setLoadExtAction(ISD::SEXTLOAD, VT, InnerVT, Expand); 613 setLoadExtAction(ISD::ZEXTLOAD, VT, InnerVT, Expand); 614 setLoadExtAction(ISD::EXTLOAD, VT, InnerVT, Expand); 615 } 616 617 setOperationAction(ISD::MULHS, VT, Expand); 618 setOperationAction(ISD::SMUL_LOHI, VT, Expand); 619 setOperationAction(ISD::MULHU, VT, Expand); 620 setOperationAction(ISD::UMUL_LOHI, VT, Expand); 621 622 setOperationAction(ISD::BSWAP, VT, Expand); 623 } 624 625 setOperationAction(ISD::ConstantFP, MVT::f32, Custom); 626 setOperationAction(ISD::ConstantFP, MVT::f64, Custom); 627 628 setOperationAction(ISD::READ_REGISTER, MVT::i64, Custom); 629 setOperationAction(ISD::WRITE_REGISTER, MVT::i64, Custom); 630 631 if (Subtarget->hasNEON()) { 632 addDRTypeForNEON(MVT::v2f32); 633 addDRTypeForNEON(MVT::v8i8); 634 addDRTypeForNEON(MVT::v4i16); 635 addDRTypeForNEON(MVT::v2i32); 636 addDRTypeForNEON(MVT::v1i64); 637 638 addQRTypeForNEON(MVT::v4f32); 639 addQRTypeForNEON(MVT::v2f64); 640 addQRTypeForNEON(MVT::v16i8); 641 addQRTypeForNEON(MVT::v8i16); 642 addQRTypeForNEON(MVT::v4i32); 643 addQRTypeForNEON(MVT::v2i64); 644 645 // v2f64 is legal so that QR subregs can be extracted as f64 elements, but 646 // neither Neon nor VFP support any arithmetic operations on it. 647 // The same with v4f32. But keep in mind that vadd, vsub, vmul are natively 648 // supported for v4f32. 649 setOperationAction(ISD::FADD, MVT::v2f64, Expand); 650 setOperationAction(ISD::FSUB, MVT::v2f64, Expand); 651 setOperationAction(ISD::FMUL, MVT::v2f64, Expand); 652 // FIXME: Code duplication: FDIV and FREM are expanded always, see 653 // ARMTargetLowering::addTypeForNEON method for details. 654 setOperationAction(ISD::FDIV, MVT::v2f64, Expand); 655 setOperationAction(ISD::FREM, MVT::v2f64, Expand); 656 // FIXME: Create unittest. 657 // In another words, find a way when "copysign" appears in DAG with vector 658 // operands. 659 setOperationAction(ISD::FCOPYSIGN, MVT::v2f64, Expand); 660 // FIXME: Code duplication: SETCC has custom operation action, see 661 // ARMTargetLowering::addTypeForNEON method for details. 662 setOperationAction(ISD::SETCC, MVT::v2f64, Expand); 663 // FIXME: Create unittest for FNEG and for FABS. 664 setOperationAction(ISD::FNEG, MVT::v2f64, Expand); 665 setOperationAction(ISD::FABS, MVT::v2f64, Expand); 666 setOperationAction(ISD::FSQRT, MVT::v2f64, Expand); 667 setOperationAction(ISD::FSIN, MVT::v2f64, Expand); 668 setOperationAction(ISD::FCOS, MVT::v2f64, Expand); 669 setOperationAction(ISD::FPOWI, MVT::v2f64, Expand); 670 setOperationAction(ISD::FPOW, MVT::v2f64, Expand); 671 setOperationAction(ISD::FLOG, MVT::v2f64, Expand); 672 setOperationAction(ISD::FLOG2, MVT::v2f64, Expand); 673 setOperationAction(ISD::FLOG10, MVT::v2f64, Expand); 674 setOperationAction(ISD::FEXP, MVT::v2f64, Expand); 675 setOperationAction(ISD::FEXP2, MVT::v2f64, Expand); 676 // FIXME: Create unittest for FCEIL, FTRUNC, FRINT, FNEARBYINT, FFLOOR. 677 setOperationAction(ISD::FCEIL, MVT::v2f64, Expand); 678 setOperationAction(ISD::FTRUNC, MVT::v2f64, Expand); 679 setOperationAction(ISD::FRINT, MVT::v2f64, Expand); 680 setOperationAction(ISD::FNEARBYINT, MVT::v2f64, Expand); 681 setOperationAction(ISD::FFLOOR, MVT::v2f64, Expand); 682 setOperationAction(ISD::FMA, MVT::v2f64, Expand); 683 684 setOperationAction(ISD::FSQRT, MVT::v4f32, Expand); 685 setOperationAction(ISD::FSIN, MVT::v4f32, Expand); 686 setOperationAction(ISD::FCOS, MVT::v4f32, Expand); 687 setOperationAction(ISD::FPOWI, MVT::v4f32, Expand); 688 setOperationAction(ISD::FPOW, MVT::v4f32, Expand); 689 setOperationAction(ISD::FLOG, MVT::v4f32, Expand); 690 setOperationAction(ISD::FLOG2, MVT::v4f32, Expand); 691 setOperationAction(ISD::FLOG10, MVT::v4f32, Expand); 692 setOperationAction(ISD::FEXP, MVT::v4f32, Expand); 693 setOperationAction(ISD::FEXP2, MVT::v4f32, Expand); 694 setOperationAction(ISD::FCEIL, MVT::v4f32, Expand); 695 setOperationAction(ISD::FTRUNC, MVT::v4f32, Expand); 696 setOperationAction(ISD::FRINT, MVT::v4f32, Expand); 697 setOperationAction(ISD::FNEARBYINT, MVT::v4f32, Expand); 698 setOperationAction(ISD::FFLOOR, MVT::v4f32, Expand); 699 700 // Mark v2f32 intrinsics. 701 setOperationAction(ISD::FSQRT, MVT::v2f32, Expand); 702 setOperationAction(ISD::FSIN, MVT::v2f32, Expand); 703 setOperationAction(ISD::FCOS, MVT::v2f32, Expand); 704 setOperationAction(ISD::FPOWI, MVT::v2f32, Expand); 705 setOperationAction(ISD::FPOW, MVT::v2f32, Expand); 706 setOperationAction(ISD::FLOG, MVT::v2f32, Expand); 707 setOperationAction(ISD::FLOG2, MVT::v2f32, Expand); 708 setOperationAction(ISD::FLOG10, MVT::v2f32, Expand); 709 setOperationAction(ISD::FEXP, MVT::v2f32, Expand); 710 setOperationAction(ISD::FEXP2, MVT::v2f32, Expand); 711 setOperationAction(ISD::FCEIL, MVT::v2f32, Expand); 712 setOperationAction(ISD::FTRUNC, MVT::v2f32, Expand); 713 setOperationAction(ISD::FRINT, MVT::v2f32, Expand); 714 setOperationAction(ISD::FNEARBYINT, MVT::v2f32, Expand); 715 setOperationAction(ISD::FFLOOR, MVT::v2f32, Expand); 716 717 // Neon does not support some operations on v1i64 and v2i64 types. 718 setOperationAction(ISD::MUL, MVT::v1i64, Expand); 719 // Custom handling for some quad-vector types to detect VMULL. 720 setOperationAction(ISD::MUL, MVT::v8i16, Custom); 721 setOperationAction(ISD::MUL, MVT::v4i32, Custom); 722 setOperationAction(ISD::MUL, MVT::v2i64, Custom); 723 // Custom handling for some vector types to avoid expensive expansions 724 setOperationAction(ISD::SDIV, MVT::v4i16, Custom); 725 setOperationAction(ISD::SDIV, MVT::v8i8, Custom); 726 setOperationAction(ISD::UDIV, MVT::v4i16, Custom); 727 setOperationAction(ISD::UDIV, MVT::v8i8, Custom); 728 setOperationAction(ISD::SETCC, MVT::v1i64, Expand); 729 setOperationAction(ISD::SETCC, MVT::v2i64, Expand); 730 // Neon does not have single instruction SINT_TO_FP and UINT_TO_FP with 731 // a destination type that is wider than the source, and nor does 732 // it have a FP_TO_[SU]INT instruction with a narrower destination than 733 // source. 734 setOperationAction(ISD::SINT_TO_FP, MVT::v4i16, Custom); 735 setOperationAction(ISD::UINT_TO_FP, MVT::v4i16, Custom); 736 setOperationAction(ISD::FP_TO_UINT, MVT::v4i16, Custom); 737 setOperationAction(ISD::FP_TO_SINT, MVT::v4i16, Custom); 738 739 setOperationAction(ISD::FP_ROUND, MVT::v2f32, Expand); 740 setOperationAction(ISD::FP_EXTEND, MVT::v2f64, Expand); 741 742 // NEON does not have single instruction CTPOP for vectors with element 743 // types wider than 8-bits. However, custom lowering can leverage the 744 // v8i8/v16i8 vcnt instruction. 745 setOperationAction(ISD::CTPOP, MVT::v2i32, Custom); 746 setOperationAction(ISD::CTPOP, MVT::v4i32, Custom); 747 setOperationAction(ISD::CTPOP, MVT::v4i16, Custom); 748 setOperationAction(ISD::CTPOP, MVT::v8i16, Custom); 749 setOperationAction(ISD::CTPOP, MVT::v1i64, Expand); 750 setOperationAction(ISD::CTPOP, MVT::v2i64, Expand); 751 752 setOperationAction(ISD::CTLZ, MVT::v1i64, Expand); 753 setOperationAction(ISD::CTLZ, MVT::v2i64, Expand); 754 755 // NEON does not have single instruction CTTZ for vectors. 756 setOperationAction(ISD::CTTZ, MVT::v8i8, Custom); 757 setOperationAction(ISD::CTTZ, MVT::v4i16, Custom); 758 setOperationAction(ISD::CTTZ, MVT::v2i32, Custom); 759 setOperationAction(ISD::CTTZ, MVT::v1i64, Custom); 760 761 setOperationAction(ISD::CTTZ, MVT::v16i8, Custom); 762 setOperationAction(ISD::CTTZ, MVT::v8i16, Custom); 763 setOperationAction(ISD::CTTZ, MVT::v4i32, Custom); 764 setOperationAction(ISD::CTTZ, MVT::v2i64, Custom); 765 766 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::v8i8, Custom); 767 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::v4i16, Custom); 768 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::v2i32, Custom); 769 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::v1i64, Custom); 770 771 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::v16i8, Custom); 772 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::v8i16, Custom); 773 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::v4i32, Custom); 774 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::v2i64, Custom); 775 776 // NEON only has FMA instructions as of VFP4. 777 if (!Subtarget->hasVFP4()) { 778 setOperationAction(ISD::FMA, MVT::v2f32, Expand); 779 setOperationAction(ISD::FMA, MVT::v4f32, Expand); 780 } 781 782 setTargetDAGCombine(ISD::INTRINSIC_VOID); 783 setTargetDAGCombine(ISD::INTRINSIC_W_CHAIN); 784 setTargetDAGCombine(ISD::INTRINSIC_WO_CHAIN); 785 setTargetDAGCombine(ISD::SHL); 786 setTargetDAGCombine(ISD::SRL); 787 setTargetDAGCombine(ISD::SRA); 788 setTargetDAGCombine(ISD::SIGN_EXTEND); 789 setTargetDAGCombine(ISD::ZERO_EXTEND); 790 setTargetDAGCombine(ISD::ANY_EXTEND); 791 setTargetDAGCombine(ISD::BUILD_VECTOR); 792 setTargetDAGCombine(ISD::VECTOR_SHUFFLE); 793 setTargetDAGCombine(ISD::INSERT_VECTOR_ELT); 794 setTargetDAGCombine(ISD::STORE); 795 setTargetDAGCombine(ISD::FP_TO_SINT); 796 setTargetDAGCombine(ISD::FP_TO_UINT); 797 setTargetDAGCombine(ISD::FDIV); 798 setTargetDAGCombine(ISD::LOAD); 799 800 // It is legal to extload from v4i8 to v4i16 or v4i32. 801 for (MVT Ty : {MVT::v8i8, MVT::v4i8, MVT::v2i8, MVT::v4i16, MVT::v2i16, 802 MVT::v2i32}) { 803 for (MVT VT : MVT::integer_vector_valuetypes()) { 804 setLoadExtAction(ISD::EXTLOAD, VT, Ty, Legal); 805 setLoadExtAction(ISD::ZEXTLOAD, VT, Ty, Legal); 806 setLoadExtAction(ISD::SEXTLOAD, VT, Ty, Legal); 807 } 808 } 809 } 810 811 // ARM and Thumb2 support UMLAL/SMLAL. 812 if (!Subtarget->isThumb1Only()) 813 setTargetDAGCombine(ISD::ADDC); 814 815 if (Subtarget->isFPOnlySP()) { 816 // When targeting a floating-point unit with only single-precision 817 // operations, f64 is legal for the few double-precision instructions which 818 // are present However, no double-precision operations other than moves, 819 // loads and stores are provided by the hardware. 820 setOperationAction(ISD::FADD, MVT::f64, Expand); 821 setOperationAction(ISD::FSUB, MVT::f64, Expand); 822 setOperationAction(ISD::FMUL, MVT::f64, Expand); 823 setOperationAction(ISD::FMA, MVT::f64, Expand); 824 setOperationAction(ISD::FDIV, MVT::f64, Expand); 825 setOperationAction(ISD::FREM, MVT::f64, Expand); 826 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand); 827 setOperationAction(ISD::FGETSIGN, MVT::f64, Expand); 828 setOperationAction(ISD::FNEG, MVT::f64, Expand); 829 setOperationAction(ISD::FABS, MVT::f64, Expand); 830 setOperationAction(ISD::FSQRT, MVT::f64, Expand); 831 setOperationAction(ISD::FSIN, MVT::f64, Expand); 832 setOperationAction(ISD::FCOS, MVT::f64, Expand); 833 setOperationAction(ISD::FPOWI, MVT::f64, Expand); 834 setOperationAction(ISD::FPOW, MVT::f64, Expand); 835 setOperationAction(ISD::FLOG, MVT::f64, Expand); 836 setOperationAction(ISD::FLOG2, MVT::f64, Expand); 837 setOperationAction(ISD::FLOG10, MVT::f64, Expand); 838 setOperationAction(ISD::FEXP, MVT::f64, Expand); 839 setOperationAction(ISD::FEXP2, MVT::f64, Expand); 840 setOperationAction(ISD::FCEIL, MVT::f64, Expand); 841 setOperationAction(ISD::FTRUNC, MVT::f64, Expand); 842 setOperationAction(ISD::FRINT, MVT::f64, Expand); 843 setOperationAction(ISD::FNEARBYINT, MVT::f64, Expand); 844 setOperationAction(ISD::FFLOOR, MVT::f64, Expand); 845 setOperationAction(ISD::SINT_TO_FP, MVT::i32, Custom); 846 setOperationAction(ISD::UINT_TO_FP, MVT::i32, Custom); 847 setOperationAction(ISD::FP_TO_SINT, MVT::i32, Custom); 848 setOperationAction(ISD::FP_TO_UINT, MVT::i32, Custom); 849 setOperationAction(ISD::FP_TO_SINT, MVT::f64, Custom); 850 setOperationAction(ISD::FP_TO_UINT, MVT::f64, Custom); 851 setOperationAction(ISD::FP_ROUND, MVT::f32, Custom); 852 setOperationAction(ISD::FP_EXTEND, MVT::f64, Custom); 853 } 854 855 computeRegisterProperties(Subtarget->getRegisterInfo()); 856 857 // ARM does not have floating-point extending loads. 858 for (MVT VT : MVT::fp_valuetypes()) { 859 setLoadExtAction(ISD::EXTLOAD, VT, MVT::f32, Expand); 860 setLoadExtAction(ISD::EXTLOAD, VT, MVT::f16, Expand); 861 } 862 863 // ... or truncating stores 864 setTruncStoreAction(MVT::f64, MVT::f32, Expand); 865 setTruncStoreAction(MVT::f32, MVT::f16, Expand); 866 setTruncStoreAction(MVT::f64, MVT::f16, Expand); 867 868 // ARM does not have i1 sign extending load. 869 for (MVT VT : MVT::integer_valuetypes()) 870 setLoadExtAction(ISD::SEXTLOAD, VT, MVT::i1, Promote); 871 872 // ARM supports all 4 flavors of integer indexed load / store. 873 if (!Subtarget->isThumb1Only()) { 874 for (unsigned im = (unsigned)ISD::PRE_INC; 875 im != (unsigned)ISD::LAST_INDEXED_MODE; ++im) { 876 setIndexedLoadAction(im, MVT::i1, Legal); 877 setIndexedLoadAction(im, MVT::i8, Legal); 878 setIndexedLoadAction(im, MVT::i16, Legal); 879 setIndexedLoadAction(im, MVT::i32, Legal); 880 setIndexedStoreAction(im, MVT::i1, Legal); 881 setIndexedStoreAction(im, MVT::i8, Legal); 882 setIndexedStoreAction(im, MVT::i16, Legal); 883 setIndexedStoreAction(im, MVT::i32, Legal); 884 } 885 } else { 886 // Thumb-1 has limited post-inc load/store support - LDM r0!, {r1}. 887 setIndexedLoadAction(ISD::POST_INC, MVT::i32, Legal); 888 setIndexedStoreAction(ISD::POST_INC, MVT::i32, Legal); 889 } 890 891 setOperationAction(ISD::SADDO, MVT::i32, Custom); 892 setOperationAction(ISD::UADDO, MVT::i32, Custom); 893 setOperationAction(ISD::SSUBO, MVT::i32, Custom); 894 setOperationAction(ISD::USUBO, MVT::i32, Custom); 895 896 // i64 operation support. 897 setOperationAction(ISD::MUL, MVT::i64, Expand); 898 setOperationAction(ISD::MULHU, MVT::i32, Expand); 899 if (Subtarget->isThumb1Only()) { 900 setOperationAction(ISD::UMUL_LOHI, MVT::i32, Expand); 901 setOperationAction(ISD::SMUL_LOHI, MVT::i32, Expand); 902 } 903 if (Subtarget->isThumb1Only() || !Subtarget->hasV6Ops() 904 || (Subtarget->isThumb2() && !Subtarget->hasDSP())) 905 setOperationAction(ISD::MULHS, MVT::i32, Expand); 906 907 setOperationAction(ISD::SHL_PARTS, MVT::i32, Custom); 908 setOperationAction(ISD::SRA_PARTS, MVT::i32, Custom); 909 setOperationAction(ISD::SRL_PARTS, MVT::i32, Custom); 910 setOperationAction(ISD::SRL, MVT::i64, Custom); 911 setOperationAction(ISD::SRA, MVT::i64, Custom); 912 913 if (!Subtarget->isThumb1Only()) { 914 // FIXME: We should do this for Thumb1 as well. 915 setOperationAction(ISD::ADDC, MVT::i32, Custom); 916 setOperationAction(ISD::ADDE, MVT::i32, Custom); 917 setOperationAction(ISD::SUBC, MVT::i32, Custom); 918 setOperationAction(ISD::SUBE, MVT::i32, Custom); 919 } 920 921 if (!Subtarget->isThumb1Only() && Subtarget->hasV6T2Ops()) 922 setOperationAction(ISD::BITREVERSE, MVT::i32, Legal); 923 924 // ARM does not have ROTL. 925 setOperationAction(ISD::ROTL, MVT::i32, Expand); 926 for (MVT VT : MVT::vector_valuetypes()) { 927 setOperationAction(ISD::ROTL, VT, Expand); 928 setOperationAction(ISD::ROTR, VT, Expand); 929 } 930 setOperationAction(ISD::CTTZ, MVT::i32, Custom); 931 setOperationAction(ISD::CTPOP, MVT::i32, Expand); 932 if (!Subtarget->hasV5TOps() || Subtarget->isThumb1Only()) 933 setOperationAction(ISD::CTLZ, MVT::i32, Expand); 934 935 // @llvm.readcyclecounter requires the Performance Monitors extension. 936 // Default to the 0 expansion on unsupported platforms. 937 // FIXME: Technically there are older ARM CPUs that have 938 // implementation-specific ways of obtaining this information. 939 if (Subtarget->hasPerfMon()) 940 setOperationAction(ISD::READCYCLECOUNTER, MVT::i64, Custom); 941 942 // Only ARMv6 has BSWAP. 943 if (!Subtarget->hasV6Ops()) 944 setOperationAction(ISD::BSWAP, MVT::i32, Expand); 945 946 bool hasDivide = Subtarget->isThumb() ? Subtarget->hasDivide() 947 : Subtarget->hasDivideInARMMode(); 948 if (!hasDivide) { 949 // These are expanded into libcalls if the cpu doesn't have HW divider. 950 setOperationAction(ISD::SDIV, MVT::i32, LibCall); 951 setOperationAction(ISD::UDIV, MVT::i32, LibCall); 952 } 953 954 if (Subtarget->isTargetWindows() && !Subtarget->hasDivide()) { 955 setOperationAction(ISD::SDIV, MVT::i32, Custom); 956 setOperationAction(ISD::UDIV, MVT::i32, Custom); 957 958 setOperationAction(ISD::SDIV, MVT::i64, Custom); 959 setOperationAction(ISD::UDIV, MVT::i64, Custom); 960 } 961 962 setOperationAction(ISD::SREM, MVT::i32, Expand); 963 setOperationAction(ISD::UREM, MVT::i32, Expand); 964 // Register based DivRem for AEABI (RTABI 4.2) 965 if (Subtarget->isTargetAEABI() || Subtarget->isTargetAndroid() || 966 Subtarget->isTargetGNUAEABI() || Subtarget->isTargetMuslAEABI()) { 967 setOperationAction(ISD::SREM, MVT::i64, Custom); 968 setOperationAction(ISD::UREM, MVT::i64, Custom); 969 HasStandaloneRem = false; 970 971 setLibcallName(RTLIB::SDIVREM_I8, "__aeabi_idivmod"); 972 setLibcallName(RTLIB::SDIVREM_I16, "__aeabi_idivmod"); 973 setLibcallName(RTLIB::SDIVREM_I32, "__aeabi_idivmod"); 974 setLibcallName(RTLIB::SDIVREM_I64, "__aeabi_ldivmod"); 975 setLibcallName(RTLIB::UDIVREM_I8, "__aeabi_uidivmod"); 976 setLibcallName(RTLIB::UDIVREM_I16, "__aeabi_uidivmod"); 977 setLibcallName(RTLIB::UDIVREM_I32, "__aeabi_uidivmod"); 978 setLibcallName(RTLIB::UDIVREM_I64, "__aeabi_uldivmod"); 979 980 setLibcallCallingConv(RTLIB::SDIVREM_I8, CallingConv::ARM_AAPCS); 981 setLibcallCallingConv(RTLIB::SDIVREM_I16, CallingConv::ARM_AAPCS); 982 setLibcallCallingConv(RTLIB::SDIVREM_I32, CallingConv::ARM_AAPCS); 983 setLibcallCallingConv(RTLIB::SDIVREM_I64, CallingConv::ARM_AAPCS); 984 setLibcallCallingConv(RTLIB::UDIVREM_I8, CallingConv::ARM_AAPCS); 985 setLibcallCallingConv(RTLIB::UDIVREM_I16, CallingConv::ARM_AAPCS); 986 setLibcallCallingConv(RTLIB::UDIVREM_I32, CallingConv::ARM_AAPCS); 987 setLibcallCallingConv(RTLIB::UDIVREM_I64, CallingConv::ARM_AAPCS); 988 989 setOperationAction(ISD::SDIVREM, MVT::i32, Custom); 990 setOperationAction(ISD::UDIVREM, MVT::i32, Custom); 991 setOperationAction(ISD::SDIVREM, MVT::i64, Custom); 992 setOperationAction(ISD::UDIVREM, MVT::i64, Custom); 993 } else { 994 setOperationAction(ISD::SDIVREM, MVT::i32, Expand); 995 setOperationAction(ISD::UDIVREM, MVT::i32, Expand); 996 } 997 998 setOperationAction(ISD::GlobalAddress, MVT::i32, Custom); 999 setOperationAction(ISD::ConstantPool, MVT::i32, Custom); 1000 setOperationAction(ISD::GlobalTLSAddress, MVT::i32, Custom); 1001 setOperationAction(ISD::BlockAddress, MVT::i32, Custom); 1002 1003 setOperationAction(ISD::TRAP, MVT::Other, Legal); 1004 1005 // Use the default implementation. 1006 setOperationAction(ISD::VASTART, MVT::Other, Custom); 1007 setOperationAction(ISD::VAARG, MVT::Other, Expand); 1008 setOperationAction(ISD::VACOPY, MVT::Other, Expand); 1009 setOperationAction(ISD::VAEND, MVT::Other, Expand); 1010 setOperationAction(ISD::STACKSAVE, MVT::Other, Expand); 1011 setOperationAction(ISD::STACKRESTORE, MVT::Other, Expand); 1012 1013 if (Subtarget->getTargetTriple().isWindowsItaniumEnvironment()) 1014 setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i32, Custom); 1015 else 1016 setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i32, Expand); 1017 1018 // ARMv6 Thumb1 (except for CPUs that support dmb / dsb) and earlier use 1019 // the default expansion. 1020 InsertFencesForAtomic = false; 1021 if (Subtarget->hasAnyDataBarrier() && 1022 (!Subtarget->isThumb() || Subtarget->hasV8MBaselineOps())) { 1023 // ATOMIC_FENCE needs custom lowering; the others should have been expanded 1024 // to ldrex/strex loops already. 1025 setOperationAction(ISD::ATOMIC_FENCE, MVT::Other, Custom); 1026 if (!Subtarget->isThumb() || !Subtarget->isMClass()) 1027 setOperationAction(ISD::ATOMIC_CMP_SWAP, MVT::i64, Custom); 1028 1029 // On v8, we have particularly efficient implementations of atomic fences 1030 // if they can be combined with nearby atomic loads and stores. 1031 if (!Subtarget->hasV8Ops() || getTargetMachine().getOptLevel() == 0) { 1032 // Automatically insert fences (dmb ish) around ATOMIC_SWAP etc. 1033 InsertFencesForAtomic = true; 1034 } 1035 } else { 1036 // If there's anything we can use as a barrier, go through custom lowering 1037 // for ATOMIC_FENCE. 1038 setOperationAction(ISD::ATOMIC_FENCE, MVT::Other, 1039 Subtarget->hasAnyDataBarrier() ? Custom : Expand); 1040 1041 // Set them all for expansion, which will force libcalls. 1042 setOperationAction(ISD::ATOMIC_CMP_SWAP, MVT::i32, Expand); 1043 setOperationAction(ISD::ATOMIC_SWAP, MVT::i32, Expand); 1044 setOperationAction(ISD::ATOMIC_LOAD_ADD, MVT::i32, Expand); 1045 setOperationAction(ISD::ATOMIC_LOAD_SUB, MVT::i32, Expand); 1046 setOperationAction(ISD::ATOMIC_LOAD_AND, MVT::i32, Expand); 1047 setOperationAction(ISD::ATOMIC_LOAD_OR, MVT::i32, Expand); 1048 setOperationAction(ISD::ATOMIC_LOAD_XOR, MVT::i32, Expand); 1049 setOperationAction(ISD::ATOMIC_LOAD_NAND, MVT::i32, Expand); 1050 setOperationAction(ISD::ATOMIC_LOAD_MIN, MVT::i32, Expand); 1051 setOperationAction(ISD::ATOMIC_LOAD_MAX, MVT::i32, Expand); 1052 setOperationAction(ISD::ATOMIC_LOAD_UMIN, MVT::i32, Expand); 1053 setOperationAction(ISD::ATOMIC_LOAD_UMAX, MVT::i32, Expand); 1054 // Mark ATOMIC_LOAD and ATOMIC_STORE custom so we can handle the 1055 // Unordered/Monotonic case. 1056 setOperationAction(ISD::ATOMIC_LOAD, MVT::i32, Custom); 1057 setOperationAction(ISD::ATOMIC_STORE, MVT::i32, Custom); 1058 } 1059 1060 setOperationAction(ISD::PREFETCH, MVT::Other, Custom); 1061 1062 // Requires SXTB/SXTH, available on v6 and up in both ARM and Thumb modes. 1063 if (!Subtarget->hasV6Ops()) { 1064 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i16, Expand); 1065 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i8, Expand); 1066 } 1067 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1, Expand); 1068 1069 if (!Subtarget->useSoftFloat() && Subtarget->hasVFP2() && 1070 !Subtarget->isThumb1Only()) { 1071 // Turn f64->i64 into VMOVRRD, i64 -> f64 to VMOVDRR 1072 // iff target supports vfp2. 1073 setOperationAction(ISD::BITCAST, MVT::i64, Custom); 1074 setOperationAction(ISD::FLT_ROUNDS_, MVT::i32, Custom); 1075 } 1076 1077 // We want to custom lower some of our intrinsics. 1078 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom); 1079 setOperationAction(ISD::EH_SJLJ_SETJMP, MVT::i32, Custom); 1080 setOperationAction(ISD::EH_SJLJ_LONGJMP, MVT::Other, Custom); 1081 setOperationAction(ISD::EH_SJLJ_SETUP_DISPATCH, MVT::Other, Custom); 1082 if (Subtarget->useSjLjEH()) 1083 setLibcallName(RTLIB::UNWIND_RESUME, "_Unwind_SjLj_Resume"); 1084 1085 setOperationAction(ISD::SETCC, MVT::i32, Expand); 1086 setOperationAction(ISD::SETCC, MVT::f32, Expand); 1087 setOperationAction(ISD::SETCC, MVT::f64, Expand); 1088 setOperationAction(ISD::SELECT, MVT::i32, Custom); 1089 setOperationAction(ISD::SELECT, MVT::f32, Custom); 1090 setOperationAction(ISD::SELECT, MVT::f64, Custom); 1091 setOperationAction(ISD::SELECT_CC, MVT::i32, Custom); 1092 setOperationAction(ISD::SELECT_CC, MVT::f32, Custom); 1093 setOperationAction(ISD::SELECT_CC, MVT::f64, Custom); 1094 1095 // Thumb-1 cannot currently select ARMISD::SUBE. 1096 if (!Subtarget->isThumb1Only()) 1097 setOperationAction(ISD::SETCCE, MVT::i32, Custom); 1098 1099 setOperationAction(ISD::BRCOND, MVT::Other, Expand); 1100 setOperationAction(ISD::BR_CC, MVT::i32, Custom); 1101 setOperationAction(ISD::BR_CC, MVT::f32, Custom); 1102 setOperationAction(ISD::BR_CC, MVT::f64, Custom); 1103 setOperationAction(ISD::BR_JT, MVT::Other, Custom); 1104 1105 // We don't support sin/cos/fmod/copysign/pow 1106 setOperationAction(ISD::FSIN, MVT::f64, Expand); 1107 setOperationAction(ISD::FSIN, MVT::f32, Expand); 1108 setOperationAction(ISD::FCOS, MVT::f32, Expand); 1109 setOperationAction(ISD::FCOS, MVT::f64, Expand); 1110 setOperationAction(ISD::FSINCOS, MVT::f64, Expand); 1111 setOperationAction(ISD::FSINCOS, MVT::f32, Expand); 1112 setOperationAction(ISD::FREM, MVT::f64, Expand); 1113 setOperationAction(ISD::FREM, MVT::f32, Expand); 1114 if (!Subtarget->useSoftFloat() && Subtarget->hasVFP2() && 1115 !Subtarget->isThumb1Only()) { 1116 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Custom); 1117 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom); 1118 } 1119 setOperationAction(ISD::FPOW, MVT::f64, Expand); 1120 setOperationAction(ISD::FPOW, MVT::f32, Expand); 1121 1122 if (!Subtarget->hasVFP4()) { 1123 setOperationAction(ISD::FMA, MVT::f64, Expand); 1124 setOperationAction(ISD::FMA, MVT::f32, Expand); 1125 } 1126 1127 // Various VFP goodness 1128 if (!Subtarget->useSoftFloat() && !Subtarget->isThumb1Only()) { 1129 // FP-ARMv8 adds f64 <-> f16 conversion. Before that it should be expanded. 1130 if (!Subtarget->hasFPARMv8() || Subtarget->isFPOnlySP()) { 1131 setOperationAction(ISD::FP16_TO_FP, MVT::f64, Expand); 1132 setOperationAction(ISD::FP_TO_FP16, MVT::f64, Expand); 1133 } 1134 1135 // fp16 is a special v7 extension that adds f16 <-> f32 conversions. 1136 if (!Subtarget->hasFP16()) { 1137 setOperationAction(ISD::FP16_TO_FP, MVT::f32, Expand); 1138 setOperationAction(ISD::FP_TO_FP16, MVT::f32, Expand); 1139 } 1140 } 1141 1142 // Combine sin / cos into one node or libcall if possible. 1143 if (Subtarget->hasSinCos()) { 1144 setLibcallName(RTLIB::SINCOS_F32, "sincosf"); 1145 setLibcallName(RTLIB::SINCOS_F64, "sincos"); 1146 if (Subtarget->isTargetWatchABI()) { 1147 setLibcallCallingConv(RTLIB::SINCOS_F32, CallingConv::ARM_AAPCS_VFP); 1148 setLibcallCallingConv(RTLIB::SINCOS_F64, CallingConv::ARM_AAPCS_VFP); 1149 } 1150 if (Subtarget->isTargetIOS() || Subtarget->isTargetWatchOS()) { 1151 // For iOS, we don't want to the normal expansion of a libcall to 1152 // sincos. We want to issue a libcall to __sincos_stret. 1153 setOperationAction(ISD::FSINCOS, MVT::f64, Custom); 1154 setOperationAction(ISD::FSINCOS, MVT::f32, Custom); 1155 } 1156 } 1157 1158 // FP-ARMv8 implements a lot of rounding-like FP operations. 1159 if (Subtarget->hasFPARMv8()) { 1160 setOperationAction(ISD::FFLOOR, MVT::f32, Legal); 1161 setOperationAction(ISD::FCEIL, MVT::f32, Legal); 1162 setOperationAction(ISD::FROUND, MVT::f32, Legal); 1163 setOperationAction(ISD::FTRUNC, MVT::f32, Legal); 1164 setOperationAction(ISD::FNEARBYINT, MVT::f32, Legal); 1165 setOperationAction(ISD::FRINT, MVT::f32, Legal); 1166 setOperationAction(ISD::FMINNUM, MVT::f32, Legal); 1167 setOperationAction(ISD::FMAXNUM, MVT::f32, Legal); 1168 setOperationAction(ISD::FMINNUM, MVT::v2f32, Legal); 1169 setOperationAction(ISD::FMAXNUM, MVT::v2f32, Legal); 1170 setOperationAction(ISD::FMINNUM, MVT::v4f32, Legal); 1171 setOperationAction(ISD::FMAXNUM, MVT::v4f32, Legal); 1172 1173 if (!Subtarget->isFPOnlySP()) { 1174 setOperationAction(ISD::FFLOOR, MVT::f64, Legal); 1175 setOperationAction(ISD::FCEIL, MVT::f64, Legal); 1176 setOperationAction(ISD::FROUND, MVT::f64, Legal); 1177 setOperationAction(ISD::FTRUNC, MVT::f64, Legal); 1178 setOperationAction(ISD::FNEARBYINT, MVT::f64, Legal); 1179 setOperationAction(ISD::FRINT, MVT::f64, Legal); 1180 setOperationAction(ISD::FMINNUM, MVT::f64, Legal); 1181 setOperationAction(ISD::FMAXNUM, MVT::f64, Legal); 1182 } 1183 } 1184 1185 if (Subtarget->hasNEON()) { 1186 // vmin and vmax aren't available in a scalar form, so we use 1187 // a NEON instruction with an undef lane instead. 1188 setOperationAction(ISD::FMINNAN, MVT::f32, Legal); 1189 setOperationAction(ISD::FMAXNAN, MVT::f32, Legal); 1190 setOperationAction(ISD::FMINNAN, MVT::v2f32, Legal); 1191 setOperationAction(ISD::FMAXNAN, MVT::v2f32, Legal); 1192 setOperationAction(ISD::FMINNAN, MVT::v4f32, Legal); 1193 setOperationAction(ISD::FMAXNAN, MVT::v4f32, Legal); 1194 } 1195 1196 // We have target-specific dag combine patterns for the following nodes: 1197 // ARMISD::VMOVRRD - No need to call setTargetDAGCombine 1198 setTargetDAGCombine(ISD::ADD); 1199 setTargetDAGCombine(ISD::SUB); 1200 setTargetDAGCombine(ISD::MUL); 1201 setTargetDAGCombine(ISD::AND); 1202 setTargetDAGCombine(ISD::OR); 1203 setTargetDAGCombine(ISD::XOR); 1204 1205 if (Subtarget->hasV6Ops()) 1206 setTargetDAGCombine(ISD::SRL); 1207 1208 setStackPointerRegisterToSaveRestore(ARM::SP); 1209 1210 if (Subtarget->useSoftFloat() || Subtarget->isThumb1Only() || 1211 !Subtarget->hasVFP2()) 1212 setSchedulingPreference(Sched::RegPressure); 1213 else 1214 setSchedulingPreference(Sched::Hybrid); 1215 1216 //// temporary - rewrite interface to use type 1217 MaxStoresPerMemset = 8; 1218 MaxStoresPerMemsetOptSize = 4; 1219 MaxStoresPerMemcpy = 4; // For @llvm.memcpy -> sequence of stores 1220 MaxStoresPerMemcpyOptSize = 2; 1221 MaxStoresPerMemmove = 4; // For @llvm.memmove -> sequence of stores 1222 MaxStoresPerMemmoveOptSize = 2; 1223 1224 // On ARM arguments smaller than 4 bytes are extended, so all arguments 1225 // are at least 4 bytes aligned. 1226 setMinStackArgumentAlignment(4); 1227 1228 // Prefer likely predicted branches to selects on out-of-order cores. 1229 PredictableSelectIsExpensive = Subtarget->getSchedModel().isOutOfOrder(); 1230 1231 setMinFunctionAlignment(Subtarget->isThumb() ? 1 : 2); 1232 } 1233 1234 bool ARMTargetLowering::useSoftFloat() const { 1235 return Subtarget->useSoftFloat(); 1236 } 1237 1238 // FIXME: It might make sense to define the representative register class as the 1239 // nearest super-register that has a non-null superset. For example, DPR_VFP2 is 1240 // a super-register of SPR, and DPR is a superset if DPR_VFP2. Consequently, 1241 // SPR's representative would be DPR_VFP2. This should work well if register 1242 // pressure tracking were modified such that a register use would increment the 1243 // pressure of the register class's representative and all of it's super 1244 // classes' representatives transitively. We have not implemented this because 1245 // of the difficulty prior to coalescing of modeling operand register classes 1246 // due to the common occurrence of cross class copies and subregister insertions 1247 // and extractions. 1248 std::pair<const TargetRegisterClass *, uint8_t> 1249 ARMTargetLowering::findRepresentativeClass(const TargetRegisterInfo *TRI, 1250 MVT VT) const { 1251 const TargetRegisterClass *RRC = nullptr; 1252 uint8_t Cost = 1; 1253 switch (VT.SimpleTy) { 1254 default: 1255 return TargetLowering::findRepresentativeClass(TRI, VT); 1256 // Use DPR as representative register class for all floating point 1257 // and vector types. Since there are 32 SPR registers and 32 DPR registers so 1258 // the cost is 1 for both f32 and f64. 1259 case MVT::f32: case MVT::f64: case MVT::v8i8: case MVT::v4i16: 1260 case MVT::v2i32: case MVT::v1i64: case MVT::v2f32: 1261 RRC = &ARM::DPRRegClass; 1262 // When NEON is used for SP, only half of the register file is available 1263 // because operations that define both SP and DP results will be constrained 1264 // to the VFP2 class (D0-D15). We currently model this constraint prior to 1265 // coalescing by double-counting the SP regs. See the FIXME above. 1266 if (Subtarget->useNEONForSinglePrecisionFP()) 1267 Cost = 2; 1268 break; 1269 case MVT::v16i8: case MVT::v8i16: case MVT::v4i32: case MVT::v2i64: 1270 case MVT::v4f32: case MVT::v2f64: 1271 RRC = &ARM::DPRRegClass; 1272 Cost = 2; 1273 break; 1274 case MVT::v4i64: 1275 RRC = &ARM::DPRRegClass; 1276 Cost = 4; 1277 break; 1278 case MVT::v8i64: 1279 RRC = &ARM::DPRRegClass; 1280 Cost = 8; 1281 break; 1282 } 1283 return std::make_pair(RRC, Cost); 1284 } 1285 1286 const char *ARMTargetLowering::getTargetNodeName(unsigned Opcode) const { 1287 switch ((ARMISD::NodeType)Opcode) { 1288 case ARMISD::FIRST_NUMBER: break; 1289 case ARMISD::Wrapper: return "ARMISD::Wrapper"; 1290 case ARMISD::WrapperPIC: return "ARMISD::WrapperPIC"; 1291 case ARMISD::WrapperJT: return "ARMISD::WrapperJT"; 1292 case ARMISD::COPY_STRUCT_BYVAL: return "ARMISD::COPY_STRUCT_BYVAL"; 1293 case ARMISD::CALL: return "ARMISD::CALL"; 1294 case ARMISD::CALL_PRED: return "ARMISD::CALL_PRED"; 1295 case ARMISD::CALL_NOLINK: return "ARMISD::CALL_NOLINK"; 1296 case ARMISD::BRCOND: return "ARMISD::BRCOND"; 1297 case ARMISD::BR_JT: return "ARMISD::BR_JT"; 1298 case ARMISD::BR2_JT: return "ARMISD::BR2_JT"; 1299 case ARMISD::RET_FLAG: return "ARMISD::RET_FLAG"; 1300 case ARMISD::INTRET_FLAG: return "ARMISD::INTRET_FLAG"; 1301 case ARMISD::PIC_ADD: return "ARMISD::PIC_ADD"; 1302 case ARMISD::CMP: return "ARMISD::CMP"; 1303 case ARMISD::CMN: return "ARMISD::CMN"; 1304 case ARMISD::CMPZ: return "ARMISD::CMPZ"; 1305 case ARMISD::CMPFP: return "ARMISD::CMPFP"; 1306 case ARMISD::CMPFPw0: return "ARMISD::CMPFPw0"; 1307 case ARMISD::BCC_i64: return "ARMISD::BCC_i64"; 1308 case ARMISD::FMSTAT: return "ARMISD::FMSTAT"; 1309 1310 case ARMISD::CMOV: return "ARMISD::CMOV"; 1311 1312 case ARMISD::SSAT: return "ARMISD::SSAT"; 1313 1314 case ARMISD::SRL_FLAG: return "ARMISD::SRL_FLAG"; 1315 case ARMISD::SRA_FLAG: return "ARMISD::SRA_FLAG"; 1316 case ARMISD::RRX: return "ARMISD::RRX"; 1317 1318 case ARMISD::ADDC: return "ARMISD::ADDC"; 1319 case ARMISD::ADDE: return "ARMISD::ADDE"; 1320 case ARMISD::SUBC: return "ARMISD::SUBC"; 1321 case ARMISD::SUBE: return "ARMISD::SUBE"; 1322 1323 case ARMISD::VMOVRRD: return "ARMISD::VMOVRRD"; 1324 case ARMISD::VMOVDRR: return "ARMISD::VMOVDRR"; 1325 1326 case ARMISD::EH_SJLJ_SETJMP: return "ARMISD::EH_SJLJ_SETJMP"; 1327 case ARMISD::EH_SJLJ_LONGJMP: return "ARMISD::EH_SJLJ_LONGJMP"; 1328 case ARMISD::EH_SJLJ_SETUP_DISPATCH: return "ARMISD::EH_SJLJ_SETUP_DISPATCH"; 1329 1330 case ARMISD::TC_RETURN: return "ARMISD::TC_RETURN"; 1331 1332 case ARMISD::THREAD_POINTER:return "ARMISD::THREAD_POINTER"; 1333 1334 case ARMISD::DYN_ALLOC: return "ARMISD::DYN_ALLOC"; 1335 1336 case ARMISD::MEMBARRIER_MCR: return "ARMISD::MEMBARRIER_MCR"; 1337 1338 case ARMISD::PRELOAD: return "ARMISD::PRELOAD"; 1339 1340 case ARMISD::WIN__CHKSTK: return "ARMISD:::WIN__CHKSTK"; 1341 case ARMISD::WIN__DBZCHK: return "ARMISD::WIN__DBZCHK"; 1342 1343 case ARMISD::VCEQ: return "ARMISD::VCEQ"; 1344 case ARMISD::VCEQZ: return "ARMISD::VCEQZ"; 1345 case ARMISD::VCGE: return "ARMISD::VCGE"; 1346 case ARMISD::VCGEZ: return "ARMISD::VCGEZ"; 1347 case ARMISD::VCLEZ: return "ARMISD::VCLEZ"; 1348 case ARMISD::VCGEU: return "ARMISD::VCGEU"; 1349 case ARMISD::VCGT: return "ARMISD::VCGT"; 1350 case ARMISD::VCGTZ: return "ARMISD::VCGTZ"; 1351 case ARMISD::VCLTZ: return "ARMISD::VCLTZ"; 1352 case ARMISD::VCGTU: return "ARMISD::VCGTU"; 1353 case ARMISD::VTST: return "ARMISD::VTST"; 1354 1355 case ARMISD::VSHL: return "ARMISD::VSHL"; 1356 case ARMISD::VSHRs: return "ARMISD::VSHRs"; 1357 case ARMISD::VSHRu: return "ARMISD::VSHRu"; 1358 case ARMISD::VRSHRs: return "ARMISD::VRSHRs"; 1359 case ARMISD::VRSHRu: return "ARMISD::VRSHRu"; 1360 case ARMISD::VRSHRN: return "ARMISD::VRSHRN"; 1361 case ARMISD::VQSHLs: return "ARMISD::VQSHLs"; 1362 case ARMISD::VQSHLu: return "ARMISD::VQSHLu"; 1363 case ARMISD::VQSHLsu: return "ARMISD::VQSHLsu"; 1364 case ARMISD::VQSHRNs: return "ARMISD::VQSHRNs"; 1365 case ARMISD::VQSHRNu: return "ARMISD::VQSHRNu"; 1366 case ARMISD::VQSHRNsu: return "ARMISD::VQSHRNsu"; 1367 case ARMISD::VQRSHRNs: return "ARMISD::VQRSHRNs"; 1368 case ARMISD::VQRSHRNu: return "ARMISD::VQRSHRNu"; 1369 case ARMISD::VQRSHRNsu: return "ARMISD::VQRSHRNsu"; 1370 case ARMISD::VSLI: return "ARMISD::VSLI"; 1371 case ARMISD::VSRI: return "ARMISD::VSRI"; 1372 case ARMISD::VGETLANEu: return "ARMISD::VGETLANEu"; 1373 case ARMISD::VGETLANEs: return "ARMISD::VGETLANEs"; 1374 case ARMISD::VMOVIMM: return "ARMISD::VMOVIMM"; 1375 case ARMISD::VMVNIMM: return "ARMISD::VMVNIMM"; 1376 case ARMISD::VMOVFPIMM: return "ARMISD::VMOVFPIMM"; 1377 case ARMISD::VDUP: return "ARMISD::VDUP"; 1378 case ARMISD::VDUPLANE: return "ARMISD::VDUPLANE"; 1379 case ARMISD::VEXT: return "ARMISD::VEXT"; 1380 case ARMISD::VREV64: return "ARMISD::VREV64"; 1381 case ARMISD::VREV32: return "ARMISD::VREV32"; 1382 case ARMISD::VREV16: return "ARMISD::VREV16"; 1383 case ARMISD::VZIP: return "ARMISD::VZIP"; 1384 case ARMISD::VUZP: return "ARMISD::VUZP"; 1385 case ARMISD::VTRN: return "ARMISD::VTRN"; 1386 case ARMISD::VTBL1: return "ARMISD::VTBL1"; 1387 case ARMISD::VTBL2: return "ARMISD::VTBL2"; 1388 case ARMISD::VMULLs: return "ARMISD::VMULLs"; 1389 case ARMISD::VMULLu: return "ARMISD::VMULLu"; 1390 case ARMISD::UMAAL: return "ARMISD::UMAAL"; 1391 case ARMISD::UMLAL: return "ARMISD::UMLAL"; 1392 case ARMISD::SMLAL: return "ARMISD::SMLAL"; 1393 case ARMISD::BUILD_VECTOR: return "ARMISD::BUILD_VECTOR"; 1394 case ARMISD::BFI: return "ARMISD::BFI"; 1395 case ARMISD::VORRIMM: return "ARMISD::VORRIMM"; 1396 case ARMISD::VBICIMM: return "ARMISD::VBICIMM"; 1397 case ARMISD::VBSL: return "ARMISD::VBSL"; 1398 case ARMISD::MEMCPY: return "ARMISD::MEMCPY"; 1399 case ARMISD::VLD2DUP: return "ARMISD::VLD2DUP"; 1400 case ARMISD::VLD3DUP: return "ARMISD::VLD3DUP"; 1401 case ARMISD::VLD4DUP: return "ARMISD::VLD4DUP"; 1402 case ARMISD::VLD1_UPD: return "ARMISD::VLD1_UPD"; 1403 case ARMISD::VLD2_UPD: return "ARMISD::VLD2_UPD"; 1404 case ARMISD::VLD3_UPD: return "ARMISD::VLD3_UPD"; 1405 case ARMISD::VLD4_UPD: return "ARMISD::VLD4_UPD"; 1406 case ARMISD::VLD2LN_UPD: return "ARMISD::VLD2LN_UPD"; 1407 case ARMISD::VLD3LN_UPD: return "ARMISD::VLD3LN_UPD"; 1408 case ARMISD::VLD4LN_UPD: return "ARMISD::VLD4LN_UPD"; 1409 case ARMISD::VLD2DUP_UPD: return "ARMISD::VLD2DUP_UPD"; 1410 case ARMISD::VLD3DUP_UPD: return "ARMISD::VLD3DUP_UPD"; 1411 case ARMISD::VLD4DUP_UPD: return "ARMISD::VLD4DUP_UPD"; 1412 case ARMISD::VST1_UPD: return "ARMISD::VST1_UPD"; 1413 case ARMISD::VST2_UPD: return "ARMISD::VST2_UPD"; 1414 case ARMISD::VST3_UPD: return "ARMISD::VST3_UPD"; 1415 case ARMISD::VST4_UPD: return "ARMISD::VST4_UPD"; 1416 case ARMISD::VST2LN_UPD: return "ARMISD::VST2LN_UPD"; 1417 case ARMISD::VST3LN_UPD: return "ARMISD::VST3LN_UPD"; 1418 case ARMISD::VST4LN_UPD: return "ARMISD::VST4LN_UPD"; 1419 } 1420 return nullptr; 1421 } 1422 1423 EVT ARMTargetLowering::getSetCCResultType(const DataLayout &DL, LLVMContext &, 1424 EVT VT) const { 1425 if (!VT.isVector()) 1426 return getPointerTy(DL); 1427 return VT.changeVectorElementTypeToInteger(); 1428 } 1429 1430 /// getRegClassFor - Return the register class that should be used for the 1431 /// specified value type. 1432 const TargetRegisterClass *ARMTargetLowering::getRegClassFor(MVT VT) const { 1433 // Map v4i64 to QQ registers but do not make the type legal. Similarly map 1434 // v8i64 to QQQQ registers. v4i64 and v8i64 are only used for REG_SEQUENCE to 1435 // load / store 4 to 8 consecutive D registers. 1436 if (Subtarget->hasNEON()) { 1437 if (VT == MVT::v4i64) 1438 return &ARM::QQPRRegClass; 1439 if (VT == MVT::v8i64) 1440 return &ARM::QQQQPRRegClass; 1441 } 1442 return TargetLowering::getRegClassFor(VT); 1443 } 1444 1445 // memcpy, and other memory intrinsics, typically tries to use LDM/STM if the 1446 // source/dest is aligned and the copy size is large enough. We therefore want 1447 // to align such objects passed to memory intrinsics. 1448 bool ARMTargetLowering::shouldAlignPointerArgs(CallInst *CI, unsigned &MinSize, 1449 unsigned &PrefAlign) const { 1450 if (!isa<MemIntrinsic>(CI)) 1451 return false; 1452 MinSize = 8; 1453 // On ARM11 onwards (excluding M class) 8-byte aligned LDM is typically 1 1454 // cycle faster than 4-byte aligned LDM. 1455 PrefAlign = (Subtarget->hasV6Ops() && !Subtarget->isMClass() ? 8 : 4); 1456 return true; 1457 } 1458 1459 // Create a fast isel object. 1460 FastISel * 1461 ARMTargetLowering::createFastISel(FunctionLoweringInfo &funcInfo, 1462 const TargetLibraryInfo *libInfo) const { 1463 return ARM::createFastISel(funcInfo, libInfo); 1464 } 1465 1466 Sched::Preference ARMTargetLowering::getSchedulingPreference(SDNode *N) const { 1467 unsigned NumVals = N->getNumValues(); 1468 if (!NumVals) 1469 return Sched::RegPressure; 1470 1471 for (unsigned i = 0; i != NumVals; ++i) { 1472 EVT VT = N->getValueType(i); 1473 if (VT == MVT::Glue || VT == MVT::Other) 1474 continue; 1475 if (VT.isFloatingPoint() || VT.isVector()) 1476 return Sched::ILP; 1477 } 1478 1479 if (!N->isMachineOpcode()) 1480 return Sched::RegPressure; 1481 1482 // Load are scheduled for latency even if there instruction itinerary 1483 // is not available. 1484 const TargetInstrInfo *TII = Subtarget->getInstrInfo(); 1485 const MCInstrDesc &MCID = TII->get(N->getMachineOpcode()); 1486 1487 if (MCID.getNumDefs() == 0) 1488 return Sched::RegPressure; 1489 if (!Itins->isEmpty() && 1490 Itins->getOperandCycle(MCID.getSchedClass(), 0) > 2) 1491 return Sched::ILP; 1492 1493 return Sched::RegPressure; 1494 } 1495 1496 //===----------------------------------------------------------------------===// 1497 // Lowering Code 1498 //===----------------------------------------------------------------------===// 1499 1500 /// IntCCToARMCC - Convert a DAG integer condition code to an ARM CC 1501 static ARMCC::CondCodes IntCCToARMCC(ISD::CondCode CC) { 1502 switch (CC) { 1503 default: llvm_unreachable("Unknown condition code!"); 1504 case ISD::SETNE: return ARMCC::NE; 1505 case ISD::SETEQ: return ARMCC::EQ; 1506 case ISD::SETGT: return ARMCC::GT; 1507 case ISD::SETGE: return ARMCC::GE; 1508 case ISD::SETLT: return ARMCC::LT; 1509 case ISD::SETLE: return ARMCC::LE; 1510 case ISD::SETUGT: return ARMCC::HI; 1511 case ISD::SETUGE: return ARMCC::HS; 1512 case ISD::SETULT: return ARMCC::LO; 1513 case ISD::SETULE: return ARMCC::LS; 1514 } 1515 } 1516 1517 /// FPCCToARMCC - Convert a DAG fp condition code to an ARM CC. 1518 static void FPCCToARMCC(ISD::CondCode CC, ARMCC::CondCodes &CondCode, 1519 ARMCC::CondCodes &CondCode2) { 1520 CondCode2 = ARMCC::AL; 1521 switch (CC) { 1522 default: llvm_unreachable("Unknown FP condition!"); 1523 case ISD::SETEQ: 1524 case ISD::SETOEQ: CondCode = ARMCC::EQ; break; 1525 case ISD::SETGT: 1526 case ISD::SETOGT: CondCode = ARMCC::GT; break; 1527 case ISD::SETGE: 1528 case ISD::SETOGE: CondCode = ARMCC::GE; break; 1529 case ISD::SETOLT: CondCode = ARMCC::MI; break; 1530 case ISD::SETOLE: CondCode = ARMCC::LS; break; 1531 case ISD::SETONE: CondCode = ARMCC::MI; CondCode2 = ARMCC::GT; break; 1532 case ISD::SETO: CondCode = ARMCC::VC; break; 1533 case ISD::SETUO: CondCode = ARMCC::VS; break; 1534 case ISD::SETUEQ: CondCode = ARMCC::EQ; CondCode2 = ARMCC::VS; break; 1535 case ISD::SETUGT: CondCode = ARMCC::HI; break; 1536 case ISD::SETUGE: CondCode = ARMCC::PL; break; 1537 case ISD::SETLT: 1538 case ISD::SETULT: CondCode = ARMCC::LT; break; 1539 case ISD::SETLE: 1540 case ISD::SETULE: CondCode = ARMCC::LE; break; 1541 case ISD::SETNE: 1542 case ISD::SETUNE: CondCode = ARMCC::NE; break; 1543 } 1544 } 1545 1546 //===----------------------------------------------------------------------===// 1547 // Calling Convention Implementation 1548 //===----------------------------------------------------------------------===// 1549 1550 #include "ARMGenCallingConv.inc" 1551 1552 /// getEffectiveCallingConv - Get the effective calling convention, taking into 1553 /// account presence of floating point hardware and calling convention 1554 /// limitations, such as support for variadic functions. 1555 CallingConv::ID 1556 ARMTargetLowering::getEffectiveCallingConv(CallingConv::ID CC, 1557 bool isVarArg) const { 1558 switch (CC) { 1559 default: 1560 llvm_unreachable("Unsupported calling convention"); 1561 case CallingConv::ARM_AAPCS: 1562 case CallingConv::ARM_APCS: 1563 case CallingConv::GHC: 1564 return CC; 1565 case CallingConv::PreserveMost: 1566 return CallingConv::PreserveMost; 1567 case CallingConv::ARM_AAPCS_VFP: 1568 case CallingConv::Swift: 1569 return isVarArg ? CallingConv::ARM_AAPCS : CallingConv::ARM_AAPCS_VFP; 1570 case CallingConv::C: 1571 if (!Subtarget->isAAPCS_ABI()) 1572 return CallingConv::ARM_APCS; 1573 else if (Subtarget->hasVFP2() && !Subtarget->isThumb1Only() && 1574 getTargetMachine().Options.FloatABIType == FloatABI::Hard && 1575 !isVarArg) 1576 return CallingConv::ARM_AAPCS_VFP; 1577 else 1578 return CallingConv::ARM_AAPCS; 1579 case CallingConv::Fast: 1580 case CallingConv::CXX_FAST_TLS: 1581 if (!Subtarget->isAAPCS_ABI()) { 1582 if (Subtarget->hasVFP2() && !Subtarget->isThumb1Only() && !isVarArg) 1583 return CallingConv::Fast; 1584 return CallingConv::ARM_APCS; 1585 } else if (Subtarget->hasVFP2() && !Subtarget->isThumb1Only() && !isVarArg) 1586 return CallingConv::ARM_AAPCS_VFP; 1587 else 1588 return CallingConv::ARM_AAPCS; 1589 } 1590 } 1591 1592 /// CCAssignFnForNode - Selects the correct CCAssignFn for the given 1593 /// CallingConvention. 1594 CCAssignFn *ARMTargetLowering::CCAssignFnForNode(CallingConv::ID CC, 1595 bool Return, 1596 bool isVarArg) const { 1597 switch (getEffectiveCallingConv(CC, isVarArg)) { 1598 default: 1599 llvm_unreachable("Unsupported calling convention"); 1600 case CallingConv::ARM_APCS: 1601 return (Return ? RetCC_ARM_APCS : CC_ARM_APCS); 1602 case CallingConv::ARM_AAPCS: 1603 return (Return ? RetCC_ARM_AAPCS : CC_ARM_AAPCS); 1604 case CallingConv::ARM_AAPCS_VFP: 1605 return (Return ? RetCC_ARM_AAPCS_VFP : CC_ARM_AAPCS_VFP); 1606 case CallingConv::Fast: 1607 return (Return ? RetFastCC_ARM_APCS : FastCC_ARM_APCS); 1608 case CallingConv::GHC: 1609 return (Return ? RetCC_ARM_APCS : CC_ARM_APCS_GHC); 1610 case CallingConv::PreserveMost: 1611 return (Return ? RetCC_ARM_AAPCS : CC_ARM_AAPCS); 1612 } 1613 } 1614 1615 /// LowerCallResult - Lower the result values of a call into the 1616 /// appropriate copies out of appropriate physical registers. 1617 SDValue ARMTargetLowering::LowerCallResult( 1618 SDValue Chain, SDValue InFlag, CallingConv::ID CallConv, bool isVarArg, 1619 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl, 1620 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals, bool isThisReturn, 1621 SDValue ThisVal) const { 1622 1623 // Assign locations to each value returned by this call. 1624 SmallVector<CCValAssign, 16> RVLocs; 1625 ARMCCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs, 1626 *DAG.getContext(), Call); 1627 CCInfo.AnalyzeCallResult(Ins, 1628 CCAssignFnForNode(CallConv, /* Return*/ true, 1629 isVarArg)); 1630 1631 // Copy all of the result registers out of their specified physreg. 1632 for (unsigned i = 0; i != RVLocs.size(); ++i) { 1633 CCValAssign VA = RVLocs[i]; 1634 1635 // Pass 'this' value directly from the argument to return value, to avoid 1636 // reg unit interference 1637 if (i == 0 && isThisReturn) { 1638 assert(!VA.needsCustom() && VA.getLocVT() == MVT::i32 && 1639 "unexpected return calling convention register assignment"); 1640 InVals.push_back(ThisVal); 1641 continue; 1642 } 1643 1644 SDValue Val; 1645 if (VA.needsCustom()) { 1646 // Handle f64 or half of a v2f64. 1647 SDValue Lo = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32, 1648 InFlag); 1649 Chain = Lo.getValue(1); 1650 InFlag = Lo.getValue(2); 1651 VA = RVLocs[++i]; // skip ahead to next loc 1652 SDValue Hi = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32, 1653 InFlag); 1654 Chain = Hi.getValue(1); 1655 InFlag = Hi.getValue(2); 1656 if (!Subtarget->isLittle()) 1657 std::swap (Lo, Hi); 1658 Val = DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi); 1659 1660 if (VA.getLocVT() == MVT::v2f64) { 1661 SDValue Vec = DAG.getNode(ISD::UNDEF, dl, MVT::v2f64); 1662 Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Vec, Val, 1663 DAG.getConstant(0, dl, MVT::i32)); 1664 1665 VA = RVLocs[++i]; // skip ahead to next loc 1666 Lo = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32, InFlag); 1667 Chain = Lo.getValue(1); 1668 InFlag = Lo.getValue(2); 1669 VA = RVLocs[++i]; // skip ahead to next loc 1670 Hi = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32, InFlag); 1671 Chain = Hi.getValue(1); 1672 InFlag = Hi.getValue(2); 1673 if (!Subtarget->isLittle()) 1674 std::swap (Lo, Hi); 1675 Val = DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi); 1676 Val = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Vec, Val, 1677 DAG.getConstant(1, dl, MVT::i32)); 1678 } 1679 } else { 1680 Val = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), VA.getLocVT(), 1681 InFlag); 1682 Chain = Val.getValue(1); 1683 InFlag = Val.getValue(2); 1684 } 1685 1686 switch (VA.getLocInfo()) { 1687 default: llvm_unreachable("Unknown loc info!"); 1688 case CCValAssign::Full: break; 1689 case CCValAssign::BCvt: 1690 Val = DAG.getNode(ISD::BITCAST, dl, VA.getValVT(), Val); 1691 break; 1692 } 1693 1694 InVals.push_back(Val); 1695 } 1696 1697 return Chain; 1698 } 1699 1700 /// LowerMemOpCallTo - Store the argument to the stack. 1701 SDValue ARMTargetLowering::LowerMemOpCallTo(SDValue Chain, SDValue StackPtr, 1702 SDValue Arg, const SDLoc &dl, 1703 SelectionDAG &DAG, 1704 const CCValAssign &VA, 1705 ISD::ArgFlagsTy Flags) const { 1706 unsigned LocMemOffset = VA.getLocMemOffset(); 1707 SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset, dl); 1708 PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(DAG.getDataLayout()), 1709 StackPtr, PtrOff); 1710 return DAG.getStore( 1711 Chain, dl, Arg, PtrOff, 1712 MachinePointerInfo::getStack(DAG.getMachineFunction(), LocMemOffset)); 1713 } 1714 1715 void ARMTargetLowering::PassF64ArgInRegs(const SDLoc &dl, SelectionDAG &DAG, 1716 SDValue Chain, SDValue &Arg, 1717 RegsToPassVector &RegsToPass, 1718 CCValAssign &VA, CCValAssign &NextVA, 1719 SDValue &StackPtr, 1720 SmallVectorImpl<SDValue> &MemOpChains, 1721 ISD::ArgFlagsTy Flags) const { 1722 1723 SDValue fmrrd = DAG.getNode(ARMISD::VMOVRRD, dl, 1724 DAG.getVTList(MVT::i32, MVT::i32), Arg); 1725 unsigned id = Subtarget->isLittle() ? 0 : 1; 1726 RegsToPass.push_back(std::make_pair(VA.getLocReg(), fmrrd.getValue(id))); 1727 1728 if (NextVA.isRegLoc()) 1729 RegsToPass.push_back(std::make_pair(NextVA.getLocReg(), fmrrd.getValue(1-id))); 1730 else { 1731 assert(NextVA.isMemLoc()); 1732 if (!StackPtr.getNode()) 1733 StackPtr = DAG.getCopyFromReg(Chain, dl, ARM::SP, 1734 getPointerTy(DAG.getDataLayout())); 1735 1736 MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, fmrrd.getValue(1-id), 1737 dl, DAG, NextVA, 1738 Flags)); 1739 } 1740 } 1741 1742 /// LowerCall - Lowering a call into a callseq_start <- 1743 /// ARMISD:CALL <- callseq_end chain. Also add input and output parameter 1744 /// nodes. 1745 SDValue 1746 ARMTargetLowering::LowerCall(TargetLowering::CallLoweringInfo &CLI, 1747 SmallVectorImpl<SDValue> &InVals) const { 1748 SelectionDAG &DAG = CLI.DAG; 1749 SDLoc &dl = CLI.DL; 1750 SmallVectorImpl<ISD::OutputArg> &Outs = CLI.Outs; 1751 SmallVectorImpl<SDValue> &OutVals = CLI.OutVals; 1752 SmallVectorImpl<ISD::InputArg> &Ins = CLI.Ins; 1753 SDValue Chain = CLI.Chain; 1754 SDValue Callee = CLI.Callee; 1755 bool &isTailCall = CLI.IsTailCall; 1756 CallingConv::ID CallConv = CLI.CallConv; 1757 bool doesNotRet = CLI.DoesNotReturn; 1758 bool isVarArg = CLI.IsVarArg; 1759 1760 MachineFunction &MF = DAG.getMachineFunction(); 1761 bool isStructRet = (Outs.empty()) ? false : Outs[0].Flags.isSRet(); 1762 bool isThisReturn = false; 1763 bool isSibCall = false; 1764 auto Attr = MF.getFunction()->getFnAttribute("disable-tail-calls"); 1765 1766 // Disable tail calls if they're not supported. 1767 if (!Subtarget->supportsTailCall() || Attr.getValueAsString() == "true") 1768 isTailCall = false; 1769 1770 if (isTailCall) { 1771 // Check if it's really possible to do a tail call. 1772 isTailCall = IsEligibleForTailCallOptimization(Callee, CallConv, 1773 isVarArg, isStructRet, MF.getFunction()->hasStructRetAttr(), 1774 Outs, OutVals, Ins, DAG); 1775 if (!isTailCall && CLI.CS && CLI.CS->isMustTailCall()) 1776 report_fatal_error("failed to perform tail call elimination on a call " 1777 "site marked musttail"); 1778 // We don't support GuaranteedTailCallOpt for ARM, only automatically 1779 // detected sibcalls. 1780 if (isTailCall) { 1781 ++NumTailCalls; 1782 isSibCall = true; 1783 } 1784 } 1785 1786 // Analyze operands of the call, assigning locations to each operand. 1787 SmallVector<CCValAssign, 16> ArgLocs; 1788 ARMCCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), ArgLocs, 1789 *DAG.getContext(), Call); 1790 CCInfo.AnalyzeCallOperands(Outs, 1791 CCAssignFnForNode(CallConv, /* Return*/ false, 1792 isVarArg)); 1793 1794 // Get a count of how many bytes are to be pushed on the stack. 1795 unsigned NumBytes = CCInfo.getNextStackOffset(); 1796 1797 // For tail calls, memory operands are available in our caller's stack. 1798 if (isSibCall) 1799 NumBytes = 0; 1800 1801 // Adjust the stack pointer for the new arguments... 1802 // These operations are automatically eliminated by the prolog/epilog pass 1803 if (!isSibCall) 1804 Chain = DAG.getCALLSEQ_START(Chain, 1805 DAG.getIntPtrConstant(NumBytes, dl, true), dl); 1806 1807 SDValue StackPtr = 1808 DAG.getCopyFromReg(Chain, dl, ARM::SP, getPointerTy(DAG.getDataLayout())); 1809 1810 RegsToPassVector RegsToPass; 1811 SmallVector<SDValue, 8> MemOpChains; 1812 1813 // Walk the register/memloc assignments, inserting copies/loads. In the case 1814 // of tail call optimization, arguments are handled later. 1815 for (unsigned i = 0, realArgIdx = 0, e = ArgLocs.size(); 1816 i != e; 1817 ++i, ++realArgIdx) { 1818 CCValAssign &VA = ArgLocs[i]; 1819 SDValue Arg = OutVals[realArgIdx]; 1820 ISD::ArgFlagsTy Flags = Outs[realArgIdx].Flags; 1821 bool isByVal = Flags.isByVal(); 1822 1823 // Promote the value if needed. 1824 switch (VA.getLocInfo()) { 1825 default: llvm_unreachable("Unknown loc info!"); 1826 case CCValAssign::Full: break; 1827 case CCValAssign::SExt: 1828 Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), Arg); 1829 break; 1830 case CCValAssign::ZExt: 1831 Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, VA.getLocVT(), Arg); 1832 break; 1833 case CCValAssign::AExt: 1834 Arg = DAG.getNode(ISD::ANY_EXTEND, dl, VA.getLocVT(), Arg); 1835 break; 1836 case CCValAssign::BCvt: 1837 Arg = DAG.getNode(ISD::BITCAST, dl, VA.getLocVT(), Arg); 1838 break; 1839 } 1840 1841 // f64 and v2f64 might be passed in i32 pairs and must be split into pieces 1842 if (VA.needsCustom()) { 1843 if (VA.getLocVT() == MVT::v2f64) { 1844 SDValue Op0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg, 1845 DAG.getConstant(0, dl, MVT::i32)); 1846 SDValue Op1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg, 1847 DAG.getConstant(1, dl, MVT::i32)); 1848 1849 PassF64ArgInRegs(dl, DAG, Chain, Op0, RegsToPass, 1850 VA, ArgLocs[++i], StackPtr, MemOpChains, Flags); 1851 1852 VA = ArgLocs[++i]; // skip ahead to next loc 1853 if (VA.isRegLoc()) { 1854 PassF64ArgInRegs(dl, DAG, Chain, Op1, RegsToPass, 1855 VA, ArgLocs[++i], StackPtr, MemOpChains, Flags); 1856 } else { 1857 assert(VA.isMemLoc()); 1858 1859 MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, Op1, 1860 dl, DAG, VA, Flags)); 1861 } 1862 } else { 1863 PassF64ArgInRegs(dl, DAG, Chain, Arg, RegsToPass, VA, ArgLocs[++i], 1864 StackPtr, MemOpChains, Flags); 1865 } 1866 } else if (VA.isRegLoc()) { 1867 if (realArgIdx == 0 && Flags.isReturned() && Outs[0].VT == MVT::i32) { 1868 assert(VA.getLocVT() == MVT::i32 && 1869 "unexpected calling convention register assignment"); 1870 assert(!Ins.empty() && Ins[0].VT == MVT::i32 && 1871 "unexpected use of 'returned'"); 1872 isThisReturn = true; 1873 } 1874 RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg)); 1875 } else if (isByVal) { 1876 assert(VA.isMemLoc()); 1877 unsigned offset = 0; 1878 1879 // True if this byval aggregate will be split between registers 1880 // and memory. 1881 unsigned ByValArgsCount = CCInfo.getInRegsParamsCount(); 1882 unsigned CurByValIdx = CCInfo.getInRegsParamsProcessed(); 1883 1884 if (CurByValIdx < ByValArgsCount) { 1885 1886 unsigned RegBegin, RegEnd; 1887 CCInfo.getInRegsParamInfo(CurByValIdx, RegBegin, RegEnd); 1888 1889 EVT PtrVT = 1890 DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout()); 1891 unsigned int i, j; 1892 for (i = 0, j = RegBegin; j < RegEnd; i++, j++) { 1893 SDValue Const = DAG.getConstant(4*i, dl, MVT::i32); 1894 SDValue AddArg = DAG.getNode(ISD::ADD, dl, PtrVT, Arg, Const); 1895 SDValue Load = DAG.getLoad(PtrVT, dl, Chain, AddArg, 1896 MachinePointerInfo(), 1897 DAG.InferPtrAlignment(AddArg)); 1898 MemOpChains.push_back(Load.getValue(1)); 1899 RegsToPass.push_back(std::make_pair(j, Load)); 1900 } 1901 1902 // If parameter size outsides register area, "offset" value 1903 // helps us to calculate stack slot for remained part properly. 1904 offset = RegEnd - RegBegin; 1905 1906 CCInfo.nextInRegsParam(); 1907 } 1908 1909 if (Flags.getByValSize() > 4*offset) { 1910 auto PtrVT = getPointerTy(DAG.getDataLayout()); 1911 unsigned LocMemOffset = VA.getLocMemOffset(); 1912 SDValue StkPtrOff = DAG.getIntPtrConstant(LocMemOffset, dl); 1913 SDValue Dst = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, StkPtrOff); 1914 SDValue SrcOffset = DAG.getIntPtrConstant(4*offset, dl); 1915 SDValue Src = DAG.getNode(ISD::ADD, dl, PtrVT, Arg, SrcOffset); 1916 SDValue SizeNode = DAG.getConstant(Flags.getByValSize() - 4*offset, dl, 1917 MVT::i32); 1918 SDValue AlignNode = DAG.getConstant(Flags.getByValAlign(), dl, 1919 MVT::i32); 1920 1921 SDVTList VTs = DAG.getVTList(MVT::Other, MVT::Glue); 1922 SDValue Ops[] = { Chain, Dst, Src, SizeNode, AlignNode}; 1923 MemOpChains.push_back(DAG.getNode(ARMISD::COPY_STRUCT_BYVAL, dl, VTs, 1924 Ops)); 1925 } 1926 } else if (!isSibCall) { 1927 assert(VA.isMemLoc()); 1928 1929 MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, Arg, 1930 dl, DAG, VA, Flags)); 1931 } 1932 } 1933 1934 if (!MemOpChains.empty()) 1935 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains); 1936 1937 // Build a sequence of copy-to-reg nodes chained together with token chain 1938 // and flag operands which copy the outgoing args into the appropriate regs. 1939 SDValue InFlag; 1940 // Tail call byval lowering might overwrite argument registers so in case of 1941 // tail call optimization the copies to registers are lowered later. 1942 if (!isTailCall) 1943 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) { 1944 Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first, 1945 RegsToPass[i].second, InFlag); 1946 InFlag = Chain.getValue(1); 1947 } 1948 1949 // For tail calls lower the arguments to the 'real' stack slot. 1950 if (isTailCall) { 1951 // Force all the incoming stack arguments to be loaded from the stack 1952 // before any new outgoing arguments are stored to the stack, because the 1953 // outgoing stack slots may alias the incoming argument stack slots, and 1954 // the alias isn't otherwise explicit. This is slightly more conservative 1955 // than necessary, because it means that each store effectively depends 1956 // on every argument instead of just those arguments it would clobber. 1957 1958 // Do not flag preceding copytoreg stuff together with the following stuff. 1959 InFlag = SDValue(); 1960 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) { 1961 Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first, 1962 RegsToPass[i].second, InFlag); 1963 InFlag = Chain.getValue(1); 1964 } 1965 InFlag = SDValue(); 1966 } 1967 1968 // If the callee is a GlobalAddress/ExternalSymbol node (quite common, every 1969 // direct call is) turn it into a TargetGlobalAddress/TargetExternalSymbol 1970 // node so that legalize doesn't hack it. 1971 bool isDirect = false; 1972 1973 const TargetMachine &TM = getTargetMachine(); 1974 const Module *Mod = MF.getFunction()->getParent(); 1975 const GlobalValue *GV = nullptr; 1976 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) 1977 GV = G->getGlobal(); 1978 bool isStub = 1979 !TM.shouldAssumeDSOLocal(*Mod, GV) && Subtarget->isTargetMachO(); 1980 1981 bool isARMFunc = !Subtarget->isThumb() || (isStub && !Subtarget->isMClass()); 1982 bool isLocalARMFunc = false; 1983 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>(); 1984 auto PtrVt = getPointerTy(DAG.getDataLayout()); 1985 1986 if (Subtarget->genLongCalls()) { 1987 assert((!isPositionIndependent() || Subtarget->isTargetWindows()) && 1988 "long-calls codegen is not position independent!"); 1989 // Handle a global address or an external symbol. If it's not one of 1990 // those, the target's already in a register, so we don't need to do 1991 // anything extra. 1992 if (isa<GlobalAddressSDNode>(Callee)) { 1993 // Create a constant pool entry for the callee address 1994 unsigned ARMPCLabelIndex = AFI->createPICLabelUId(); 1995 ARMConstantPoolValue *CPV = 1996 ARMConstantPoolConstant::Create(GV, ARMPCLabelIndex, ARMCP::CPValue, 0); 1997 1998 // Get the address of the callee into a register 1999 SDValue CPAddr = DAG.getTargetConstantPool(CPV, PtrVt, 4); 2000 CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr); 2001 Callee = DAG.getLoad( 2002 PtrVt, dl, DAG.getEntryNode(), CPAddr, 2003 MachinePointerInfo::getConstantPool(DAG.getMachineFunction())); 2004 } else if (ExternalSymbolSDNode *S=dyn_cast<ExternalSymbolSDNode>(Callee)) { 2005 const char *Sym = S->getSymbol(); 2006 2007 // Create a constant pool entry for the callee address 2008 unsigned ARMPCLabelIndex = AFI->createPICLabelUId(); 2009 ARMConstantPoolValue *CPV = 2010 ARMConstantPoolSymbol::Create(*DAG.getContext(), Sym, 2011 ARMPCLabelIndex, 0); 2012 // Get the address of the callee into a register 2013 SDValue CPAddr = DAG.getTargetConstantPool(CPV, PtrVt, 4); 2014 CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr); 2015 Callee = DAG.getLoad( 2016 PtrVt, dl, DAG.getEntryNode(), CPAddr, 2017 MachinePointerInfo::getConstantPool(DAG.getMachineFunction())); 2018 } 2019 } else if (isa<GlobalAddressSDNode>(Callee)) { 2020 // If we're optimizing for minimum size and the function is called three or 2021 // more times in this block, we can improve codesize by calling indirectly 2022 // as BLXr has a 16-bit encoding. 2023 auto *GV = cast<GlobalAddressSDNode>(Callee)->getGlobal(); 2024 auto *BB = CLI.CS->getParent(); 2025 bool PreferIndirect = 2026 Subtarget->isThumb() && MF.getFunction()->optForMinSize() && 2027 count_if(GV->users(), [&BB](const User *U) { 2028 return isa<Instruction>(U) && cast<Instruction>(U)->getParent() == BB; 2029 }) > 2; 2030 2031 if (!PreferIndirect) { 2032 isDirect = true; 2033 bool isDef = GV->isStrongDefinitionForLinker(); 2034 2035 // ARM call to a local ARM function is predicable. 2036 isLocalARMFunc = !Subtarget->isThumb() && (isDef || !ARMInterworking); 2037 // tBX takes a register source operand. 2038 if (isStub && Subtarget->isThumb1Only() && !Subtarget->hasV5TOps()) { 2039 assert(Subtarget->isTargetMachO() && "WrapperPIC use on non-MachO?"); 2040 Callee = DAG.getNode( 2041 ARMISD::WrapperPIC, dl, PtrVt, 2042 DAG.getTargetGlobalAddress(GV, dl, PtrVt, 0, ARMII::MO_NONLAZY)); 2043 Callee = DAG.getLoad( 2044 PtrVt, dl, DAG.getEntryNode(), Callee, 2045 MachinePointerInfo::getGOT(DAG.getMachineFunction()), 2046 /* Alignment = */ 0, MachineMemOperand::MODereferenceable | 2047 MachineMemOperand::MOInvariant); 2048 } else if (Subtarget->isTargetCOFF()) { 2049 assert(Subtarget->isTargetWindows() && 2050 "Windows is the only supported COFF target"); 2051 unsigned TargetFlags = GV->hasDLLImportStorageClass() 2052 ? ARMII::MO_DLLIMPORT 2053 : ARMII::MO_NO_FLAG; 2054 Callee = DAG.getTargetGlobalAddress(GV, dl, PtrVt, /*Offset=*/0, 2055 TargetFlags); 2056 if (GV->hasDLLImportStorageClass()) 2057 Callee = 2058 DAG.getLoad(PtrVt, dl, DAG.getEntryNode(), 2059 DAG.getNode(ARMISD::Wrapper, dl, PtrVt, Callee), 2060 MachinePointerInfo::getGOT(DAG.getMachineFunction())); 2061 } else { 2062 Callee = DAG.getTargetGlobalAddress(GV, dl, PtrVt, 0, 0); 2063 } 2064 } 2065 } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) { 2066 isDirect = true; 2067 // tBX takes a register source operand. 2068 const char *Sym = S->getSymbol(); 2069 if (isARMFunc && Subtarget->isThumb1Only() && !Subtarget->hasV5TOps()) { 2070 unsigned ARMPCLabelIndex = AFI->createPICLabelUId(); 2071 ARMConstantPoolValue *CPV = 2072 ARMConstantPoolSymbol::Create(*DAG.getContext(), Sym, 2073 ARMPCLabelIndex, 4); 2074 SDValue CPAddr = DAG.getTargetConstantPool(CPV, PtrVt, 4); 2075 CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr); 2076 Callee = DAG.getLoad( 2077 PtrVt, dl, DAG.getEntryNode(), CPAddr, 2078 MachinePointerInfo::getConstantPool(DAG.getMachineFunction())); 2079 SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, dl, MVT::i32); 2080 Callee = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVt, Callee, PICLabel); 2081 } else { 2082 Callee = DAG.getTargetExternalSymbol(Sym, PtrVt, 0); 2083 } 2084 } 2085 2086 // FIXME: handle tail calls differently. 2087 unsigned CallOpc; 2088 if (Subtarget->isThumb()) { 2089 if ((!isDirect || isARMFunc) && !Subtarget->hasV5TOps()) 2090 CallOpc = ARMISD::CALL_NOLINK; 2091 else 2092 CallOpc = ARMISD::CALL; 2093 } else { 2094 if (!isDirect && !Subtarget->hasV5TOps()) 2095 CallOpc = ARMISD::CALL_NOLINK; 2096 else if (doesNotRet && isDirect && Subtarget->hasRetAddrStack() && 2097 // Emit regular call when code size is the priority 2098 !MF.getFunction()->optForMinSize()) 2099 // "mov lr, pc; b _foo" to avoid confusing the RSP 2100 CallOpc = ARMISD::CALL_NOLINK; 2101 else 2102 CallOpc = isLocalARMFunc ? ARMISD::CALL_PRED : ARMISD::CALL; 2103 } 2104 2105 std::vector<SDValue> Ops; 2106 Ops.push_back(Chain); 2107 Ops.push_back(Callee); 2108 2109 // Add argument registers to the end of the list so that they are known live 2110 // into the call. 2111 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) 2112 Ops.push_back(DAG.getRegister(RegsToPass[i].first, 2113 RegsToPass[i].second.getValueType())); 2114 2115 // Add a register mask operand representing the call-preserved registers. 2116 if (!isTailCall) { 2117 const uint32_t *Mask; 2118 const ARMBaseRegisterInfo *ARI = Subtarget->getRegisterInfo(); 2119 if (isThisReturn) { 2120 // For 'this' returns, use the R0-preserving mask if applicable 2121 Mask = ARI->getThisReturnPreservedMask(MF, CallConv); 2122 if (!Mask) { 2123 // Set isThisReturn to false if the calling convention is not one that 2124 // allows 'returned' to be modeled in this way, so LowerCallResult does 2125 // not try to pass 'this' straight through 2126 isThisReturn = false; 2127 Mask = ARI->getCallPreservedMask(MF, CallConv); 2128 } 2129 } else 2130 Mask = ARI->getCallPreservedMask(MF, CallConv); 2131 2132 assert(Mask && "Missing call preserved mask for calling convention"); 2133 Ops.push_back(DAG.getRegisterMask(Mask)); 2134 } 2135 2136 if (InFlag.getNode()) 2137 Ops.push_back(InFlag); 2138 2139 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue); 2140 if (isTailCall) { 2141 MF.getFrameInfo().setHasTailCall(); 2142 return DAG.getNode(ARMISD::TC_RETURN, dl, NodeTys, Ops); 2143 } 2144 2145 // Returns a chain and a flag for retval copy to use. 2146 Chain = DAG.getNode(CallOpc, dl, NodeTys, Ops); 2147 InFlag = Chain.getValue(1); 2148 2149 Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, dl, true), 2150 DAG.getIntPtrConstant(0, dl, true), InFlag, dl); 2151 if (!Ins.empty()) 2152 InFlag = Chain.getValue(1); 2153 2154 // Handle result values, copying them out of physregs into vregs that we 2155 // return. 2156 return LowerCallResult(Chain, InFlag, CallConv, isVarArg, Ins, dl, DAG, 2157 InVals, isThisReturn, 2158 isThisReturn ? OutVals[0] : SDValue()); 2159 } 2160 2161 /// HandleByVal - Every parameter *after* a byval parameter is passed 2162 /// on the stack. Remember the next parameter register to allocate, 2163 /// and then confiscate the rest of the parameter registers to insure 2164 /// this. 2165 void ARMTargetLowering::HandleByVal(CCState *State, unsigned &Size, 2166 unsigned Align) const { 2167 assert((State->getCallOrPrologue() == Prologue || 2168 State->getCallOrPrologue() == Call) && 2169 "unhandled ParmContext"); 2170 2171 // Byval (as with any stack) slots are always at least 4 byte aligned. 2172 Align = std::max(Align, 4U); 2173 2174 unsigned Reg = State->AllocateReg(GPRArgRegs); 2175 if (!Reg) 2176 return; 2177 2178 unsigned AlignInRegs = Align / 4; 2179 unsigned Waste = (ARM::R4 - Reg) % AlignInRegs; 2180 for (unsigned i = 0; i < Waste; ++i) 2181 Reg = State->AllocateReg(GPRArgRegs); 2182 2183 if (!Reg) 2184 return; 2185 2186 unsigned Excess = 4 * (ARM::R4 - Reg); 2187 2188 // Special case when NSAA != SP and parameter size greater than size of 2189 // all remained GPR regs. In that case we can't split parameter, we must 2190 // send it to stack. We also must set NCRN to R4, so waste all 2191 // remained registers. 2192 const unsigned NSAAOffset = State->getNextStackOffset(); 2193 if (NSAAOffset != 0 && Size > Excess) { 2194 while (State->AllocateReg(GPRArgRegs)) 2195 ; 2196 return; 2197 } 2198 2199 // First register for byval parameter is the first register that wasn't 2200 // allocated before this method call, so it would be "reg". 2201 // If parameter is small enough to be saved in range [reg, r4), then 2202 // the end (first after last) register would be reg + param-size-in-regs, 2203 // else parameter would be splitted between registers and stack, 2204 // end register would be r4 in this case. 2205 unsigned ByValRegBegin = Reg; 2206 unsigned ByValRegEnd = std::min<unsigned>(Reg + Size / 4, ARM::R4); 2207 State->addInRegsParamInfo(ByValRegBegin, ByValRegEnd); 2208 // Note, first register is allocated in the beginning of function already, 2209 // allocate remained amount of registers we need. 2210 for (unsigned i = Reg + 1; i != ByValRegEnd; ++i) 2211 State->AllocateReg(GPRArgRegs); 2212 // A byval parameter that is split between registers and memory needs its 2213 // size truncated here. 2214 // In the case where the entire structure fits in registers, we set the 2215 // size in memory to zero. 2216 Size = std::max<int>(Size - Excess, 0); 2217 } 2218 2219 /// MatchingStackOffset - Return true if the given stack call argument is 2220 /// already available in the same position (relatively) of the caller's 2221 /// incoming argument stack. 2222 static 2223 bool MatchingStackOffset(SDValue Arg, unsigned Offset, ISD::ArgFlagsTy Flags, 2224 MachineFrameInfo &MFI, const MachineRegisterInfo *MRI, 2225 const TargetInstrInfo *TII) { 2226 unsigned Bytes = Arg.getValueType().getSizeInBits() / 8; 2227 int FI = INT_MAX; 2228 if (Arg.getOpcode() == ISD::CopyFromReg) { 2229 unsigned VR = cast<RegisterSDNode>(Arg.getOperand(1))->getReg(); 2230 if (!TargetRegisterInfo::isVirtualRegister(VR)) 2231 return false; 2232 MachineInstr *Def = MRI->getVRegDef(VR); 2233 if (!Def) 2234 return false; 2235 if (!Flags.isByVal()) { 2236 if (!TII->isLoadFromStackSlot(*Def, FI)) 2237 return false; 2238 } else { 2239 return false; 2240 } 2241 } else if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Arg)) { 2242 if (Flags.isByVal()) 2243 // ByVal argument is passed in as a pointer but it's now being 2244 // dereferenced. e.g. 2245 // define @foo(%struct.X* %A) { 2246 // tail call @bar(%struct.X* byval %A) 2247 // } 2248 return false; 2249 SDValue Ptr = Ld->getBasePtr(); 2250 FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr); 2251 if (!FINode) 2252 return false; 2253 FI = FINode->getIndex(); 2254 } else 2255 return false; 2256 2257 assert(FI != INT_MAX); 2258 if (!MFI.isFixedObjectIndex(FI)) 2259 return false; 2260 return Offset == MFI.getObjectOffset(FI) && Bytes == MFI.getObjectSize(FI); 2261 } 2262 2263 /// IsEligibleForTailCallOptimization - Check whether the call is eligible 2264 /// for tail call optimization. Targets which want to do tail call 2265 /// optimization should implement this function. 2266 bool 2267 ARMTargetLowering::IsEligibleForTailCallOptimization(SDValue Callee, 2268 CallingConv::ID CalleeCC, 2269 bool isVarArg, 2270 bool isCalleeStructRet, 2271 bool isCallerStructRet, 2272 const SmallVectorImpl<ISD::OutputArg> &Outs, 2273 const SmallVectorImpl<SDValue> &OutVals, 2274 const SmallVectorImpl<ISD::InputArg> &Ins, 2275 SelectionDAG& DAG) const { 2276 MachineFunction &MF = DAG.getMachineFunction(); 2277 const Function *CallerF = MF.getFunction(); 2278 CallingConv::ID CallerCC = CallerF->getCallingConv(); 2279 2280 assert(Subtarget->supportsTailCall()); 2281 2282 // Look for obvious safe cases to perform tail call optimization that do not 2283 // require ABI changes. This is what gcc calls sibcall. 2284 2285 // Do not sibcall optimize vararg calls unless the call site is not passing 2286 // any arguments. 2287 if (isVarArg && !Outs.empty()) 2288 return false; 2289 2290 // Exception-handling functions need a special set of instructions to indicate 2291 // a return to the hardware. Tail-calling another function would probably 2292 // break this. 2293 if (CallerF->hasFnAttribute("interrupt")) 2294 return false; 2295 2296 // Also avoid sibcall optimization if either caller or callee uses struct 2297 // return semantics. 2298 if (isCalleeStructRet || isCallerStructRet) 2299 return false; 2300 2301 // Externally-defined functions with weak linkage should not be 2302 // tail-called on ARM when the OS does not support dynamic 2303 // pre-emption of symbols, as the AAELF spec requires normal calls 2304 // to undefined weak functions to be replaced with a NOP or jump to the 2305 // next instruction. The behaviour of branch instructions in this 2306 // situation (as used for tail calls) is implementation-defined, so we 2307 // cannot rely on the linker replacing the tail call with a return. 2308 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) { 2309 const GlobalValue *GV = G->getGlobal(); 2310 const Triple &TT = getTargetMachine().getTargetTriple(); 2311 if (GV->hasExternalWeakLinkage() && 2312 (!TT.isOSWindows() || TT.isOSBinFormatELF() || TT.isOSBinFormatMachO())) 2313 return false; 2314 } 2315 2316 // Check that the call results are passed in the same way. 2317 LLVMContext &C = *DAG.getContext(); 2318 if (!CCState::resultsCompatible(CalleeCC, CallerCC, MF, C, Ins, 2319 CCAssignFnForNode(CalleeCC, true, isVarArg), 2320 CCAssignFnForNode(CallerCC, true, isVarArg))) 2321 return false; 2322 // The callee has to preserve all registers the caller needs to preserve. 2323 const ARMBaseRegisterInfo *TRI = Subtarget->getRegisterInfo(); 2324 const uint32_t *CallerPreserved = TRI->getCallPreservedMask(MF, CallerCC); 2325 if (CalleeCC != CallerCC) { 2326 const uint32_t *CalleePreserved = TRI->getCallPreservedMask(MF, CalleeCC); 2327 if (!TRI->regmaskSubsetEqual(CallerPreserved, CalleePreserved)) 2328 return false; 2329 } 2330 2331 // If Caller's vararg or byval argument has been split between registers and 2332 // stack, do not perform tail call, since part of the argument is in caller's 2333 // local frame. 2334 const ARMFunctionInfo *AFI_Caller = MF.getInfo<ARMFunctionInfo>(); 2335 if (AFI_Caller->getArgRegsSaveSize()) 2336 return false; 2337 2338 // If the callee takes no arguments then go on to check the results of the 2339 // call. 2340 if (!Outs.empty()) { 2341 // Check if stack adjustment is needed. For now, do not do this if any 2342 // argument is passed on the stack. 2343 SmallVector<CCValAssign, 16> ArgLocs; 2344 ARMCCState CCInfo(CalleeCC, isVarArg, MF, ArgLocs, C, Call); 2345 CCInfo.AnalyzeCallOperands(Outs, 2346 CCAssignFnForNode(CalleeCC, false, isVarArg)); 2347 if (CCInfo.getNextStackOffset()) { 2348 // Check if the arguments are already laid out in the right way as 2349 // the caller's fixed stack objects. 2350 MachineFrameInfo &MFI = MF.getFrameInfo(); 2351 const MachineRegisterInfo *MRI = &MF.getRegInfo(); 2352 const TargetInstrInfo *TII = Subtarget->getInstrInfo(); 2353 for (unsigned i = 0, realArgIdx = 0, e = ArgLocs.size(); 2354 i != e; 2355 ++i, ++realArgIdx) { 2356 CCValAssign &VA = ArgLocs[i]; 2357 EVT RegVT = VA.getLocVT(); 2358 SDValue Arg = OutVals[realArgIdx]; 2359 ISD::ArgFlagsTy Flags = Outs[realArgIdx].Flags; 2360 if (VA.getLocInfo() == CCValAssign::Indirect) 2361 return false; 2362 if (VA.needsCustom()) { 2363 // f64 and vector types are split into multiple registers or 2364 // register/stack-slot combinations. The types will not match 2365 // the registers; give up on memory f64 refs until we figure 2366 // out what to do about this. 2367 if (!VA.isRegLoc()) 2368 return false; 2369 if (!ArgLocs[++i].isRegLoc()) 2370 return false; 2371 if (RegVT == MVT::v2f64) { 2372 if (!ArgLocs[++i].isRegLoc()) 2373 return false; 2374 if (!ArgLocs[++i].isRegLoc()) 2375 return false; 2376 } 2377 } else if (!VA.isRegLoc()) { 2378 if (!MatchingStackOffset(Arg, VA.getLocMemOffset(), Flags, 2379 MFI, MRI, TII)) 2380 return false; 2381 } 2382 } 2383 } 2384 2385 const MachineRegisterInfo &MRI = MF.getRegInfo(); 2386 if (!parametersInCSRMatch(MRI, CallerPreserved, ArgLocs, OutVals)) 2387 return false; 2388 } 2389 2390 return true; 2391 } 2392 2393 bool 2394 ARMTargetLowering::CanLowerReturn(CallingConv::ID CallConv, 2395 MachineFunction &MF, bool isVarArg, 2396 const SmallVectorImpl<ISD::OutputArg> &Outs, 2397 LLVMContext &Context) const { 2398 SmallVector<CCValAssign, 16> RVLocs; 2399 CCState CCInfo(CallConv, isVarArg, MF, RVLocs, Context); 2400 return CCInfo.CheckReturn(Outs, CCAssignFnForNode(CallConv, /*Return=*/true, 2401 isVarArg)); 2402 } 2403 2404 static SDValue LowerInterruptReturn(SmallVectorImpl<SDValue> &RetOps, 2405 const SDLoc &DL, SelectionDAG &DAG) { 2406 const MachineFunction &MF = DAG.getMachineFunction(); 2407 const Function *F = MF.getFunction(); 2408 2409 StringRef IntKind = F->getFnAttribute("interrupt").getValueAsString(); 2410 2411 // See ARM ARM v7 B1.8.3. On exception entry LR is set to a possibly offset 2412 // version of the "preferred return address". These offsets affect the return 2413 // instruction if this is a return from PL1 without hypervisor extensions. 2414 // IRQ/FIQ: +4 "subs pc, lr, #4" 2415 // SWI: 0 "subs pc, lr, #0" 2416 // ABORT: +4 "subs pc, lr, #4" 2417 // UNDEF: +4/+2 "subs pc, lr, #0" 2418 // UNDEF varies depending on where the exception came from ARM or Thumb 2419 // mode. Alongside GCC, we throw our hands up in disgust and pretend it's 0. 2420 2421 int64_t LROffset; 2422 if (IntKind == "" || IntKind == "IRQ" || IntKind == "FIQ" || 2423 IntKind == "ABORT") 2424 LROffset = 4; 2425 else if (IntKind == "SWI" || IntKind == "UNDEF") 2426 LROffset = 0; 2427 else 2428 report_fatal_error("Unsupported interrupt attribute. If present, value " 2429 "must be one of: IRQ, FIQ, SWI, ABORT or UNDEF"); 2430 2431 RetOps.insert(RetOps.begin() + 1, 2432 DAG.getConstant(LROffset, DL, MVT::i32, false)); 2433 2434 return DAG.getNode(ARMISD::INTRET_FLAG, DL, MVT::Other, RetOps); 2435 } 2436 2437 SDValue 2438 ARMTargetLowering::LowerReturn(SDValue Chain, CallingConv::ID CallConv, 2439 bool isVarArg, 2440 const SmallVectorImpl<ISD::OutputArg> &Outs, 2441 const SmallVectorImpl<SDValue> &OutVals, 2442 const SDLoc &dl, SelectionDAG &DAG) const { 2443 2444 // CCValAssign - represent the assignment of the return value to a location. 2445 SmallVector<CCValAssign, 16> RVLocs; 2446 2447 // CCState - Info about the registers and stack slots. 2448 ARMCCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs, 2449 *DAG.getContext(), Call); 2450 2451 // Analyze outgoing return values. 2452 CCInfo.AnalyzeReturn(Outs, CCAssignFnForNode(CallConv, /* Return */ true, 2453 isVarArg)); 2454 2455 SDValue Flag; 2456 SmallVector<SDValue, 4> RetOps; 2457 RetOps.push_back(Chain); // Operand #0 = Chain (updated below) 2458 bool isLittleEndian = Subtarget->isLittle(); 2459 2460 MachineFunction &MF = DAG.getMachineFunction(); 2461 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>(); 2462 AFI->setReturnRegsCount(RVLocs.size()); 2463 2464 // Copy the result values into the output registers. 2465 for (unsigned i = 0, realRVLocIdx = 0; 2466 i != RVLocs.size(); 2467 ++i, ++realRVLocIdx) { 2468 CCValAssign &VA = RVLocs[i]; 2469 assert(VA.isRegLoc() && "Can only return in registers!"); 2470 2471 SDValue Arg = OutVals[realRVLocIdx]; 2472 2473 switch (VA.getLocInfo()) { 2474 default: llvm_unreachable("Unknown loc info!"); 2475 case CCValAssign::Full: break; 2476 case CCValAssign::BCvt: 2477 Arg = DAG.getNode(ISD::BITCAST, dl, VA.getLocVT(), Arg); 2478 break; 2479 } 2480 2481 if (VA.needsCustom()) { 2482 if (VA.getLocVT() == MVT::v2f64) { 2483 // Extract the first half and return it in two registers. 2484 SDValue Half = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg, 2485 DAG.getConstant(0, dl, MVT::i32)); 2486 SDValue HalfGPRs = DAG.getNode(ARMISD::VMOVRRD, dl, 2487 DAG.getVTList(MVT::i32, MVT::i32), Half); 2488 2489 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), 2490 HalfGPRs.getValue(isLittleEndian ? 0 : 1), 2491 Flag); 2492 Flag = Chain.getValue(1); 2493 RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT())); 2494 VA = RVLocs[++i]; // skip ahead to next loc 2495 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), 2496 HalfGPRs.getValue(isLittleEndian ? 1 : 0), 2497 Flag); 2498 Flag = Chain.getValue(1); 2499 RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT())); 2500 VA = RVLocs[++i]; // skip ahead to next loc 2501 2502 // Extract the 2nd half and fall through to handle it as an f64 value. 2503 Arg = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg, 2504 DAG.getConstant(1, dl, MVT::i32)); 2505 } 2506 // Legalize ret f64 -> ret 2 x i32. We always have fmrrd if f64 is 2507 // available. 2508 SDValue fmrrd = DAG.getNode(ARMISD::VMOVRRD, dl, 2509 DAG.getVTList(MVT::i32, MVT::i32), Arg); 2510 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), 2511 fmrrd.getValue(isLittleEndian ? 0 : 1), 2512 Flag); 2513 Flag = Chain.getValue(1); 2514 RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT())); 2515 VA = RVLocs[++i]; // skip ahead to next loc 2516 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), 2517 fmrrd.getValue(isLittleEndian ? 1 : 0), 2518 Flag); 2519 } else 2520 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), Arg, Flag); 2521 2522 // Guarantee that all emitted copies are 2523 // stuck together, avoiding something bad. 2524 Flag = Chain.getValue(1); 2525 RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT())); 2526 } 2527 const ARMBaseRegisterInfo *TRI = Subtarget->getRegisterInfo(); 2528 const MCPhysReg *I = 2529 TRI->getCalleeSavedRegsViaCopy(&DAG.getMachineFunction()); 2530 if (I) { 2531 for (; *I; ++I) { 2532 if (ARM::GPRRegClass.contains(*I)) 2533 RetOps.push_back(DAG.getRegister(*I, MVT::i32)); 2534 else if (ARM::DPRRegClass.contains(*I)) 2535 RetOps.push_back(DAG.getRegister(*I, MVT::getFloatingPointVT(64))); 2536 else 2537 llvm_unreachable("Unexpected register class in CSRsViaCopy!"); 2538 } 2539 } 2540 2541 // Update chain and glue. 2542 RetOps[0] = Chain; 2543 if (Flag.getNode()) 2544 RetOps.push_back(Flag); 2545 2546 // CPUs which aren't M-class use a special sequence to return from 2547 // exceptions (roughly, any instruction setting pc and cpsr simultaneously, 2548 // though we use "subs pc, lr, #N"). 2549 // 2550 // M-class CPUs actually use a normal return sequence with a special 2551 // (hardware-provided) value in LR, so the normal code path works. 2552 if (DAG.getMachineFunction().getFunction()->hasFnAttribute("interrupt") && 2553 !Subtarget->isMClass()) { 2554 if (Subtarget->isThumb1Only()) 2555 report_fatal_error("interrupt attribute is not supported in Thumb1"); 2556 return LowerInterruptReturn(RetOps, dl, DAG); 2557 } 2558 2559 return DAG.getNode(ARMISD::RET_FLAG, dl, MVT::Other, RetOps); 2560 } 2561 2562 bool ARMTargetLowering::isUsedByReturnOnly(SDNode *N, SDValue &Chain) const { 2563 if (N->getNumValues() != 1) 2564 return false; 2565 if (!N->hasNUsesOfValue(1, 0)) 2566 return false; 2567 2568 SDValue TCChain = Chain; 2569 SDNode *Copy = *N->use_begin(); 2570 if (Copy->getOpcode() == ISD::CopyToReg) { 2571 // If the copy has a glue operand, we conservatively assume it isn't safe to 2572 // perform a tail call. 2573 if (Copy->getOperand(Copy->getNumOperands()-1).getValueType() == MVT::Glue) 2574 return false; 2575 TCChain = Copy->getOperand(0); 2576 } else if (Copy->getOpcode() == ARMISD::VMOVRRD) { 2577 SDNode *VMov = Copy; 2578 // f64 returned in a pair of GPRs. 2579 SmallPtrSet<SDNode*, 2> Copies; 2580 for (SDNode::use_iterator UI = VMov->use_begin(), UE = VMov->use_end(); 2581 UI != UE; ++UI) { 2582 if (UI->getOpcode() != ISD::CopyToReg) 2583 return false; 2584 Copies.insert(*UI); 2585 } 2586 if (Copies.size() > 2) 2587 return false; 2588 2589 for (SDNode::use_iterator UI = VMov->use_begin(), UE = VMov->use_end(); 2590 UI != UE; ++UI) { 2591 SDValue UseChain = UI->getOperand(0); 2592 if (Copies.count(UseChain.getNode())) 2593 // Second CopyToReg 2594 Copy = *UI; 2595 else { 2596 // We are at the top of this chain. 2597 // If the copy has a glue operand, we conservatively assume it 2598 // isn't safe to perform a tail call. 2599 if (UI->getOperand(UI->getNumOperands()-1).getValueType() == MVT::Glue) 2600 return false; 2601 // First CopyToReg 2602 TCChain = UseChain; 2603 } 2604 } 2605 } else if (Copy->getOpcode() == ISD::BITCAST) { 2606 // f32 returned in a single GPR. 2607 if (!Copy->hasOneUse()) 2608 return false; 2609 Copy = *Copy->use_begin(); 2610 if (Copy->getOpcode() != ISD::CopyToReg || !Copy->hasNUsesOfValue(1, 0)) 2611 return false; 2612 // If the copy has a glue operand, we conservatively assume it isn't safe to 2613 // perform a tail call. 2614 if (Copy->getOperand(Copy->getNumOperands()-1).getValueType() == MVT::Glue) 2615 return false; 2616 TCChain = Copy->getOperand(0); 2617 } else { 2618 return false; 2619 } 2620 2621 bool HasRet = false; 2622 for (SDNode::use_iterator UI = Copy->use_begin(), UE = Copy->use_end(); 2623 UI != UE; ++UI) { 2624 if (UI->getOpcode() != ARMISD::RET_FLAG && 2625 UI->getOpcode() != ARMISD::INTRET_FLAG) 2626 return false; 2627 HasRet = true; 2628 } 2629 2630 if (!HasRet) 2631 return false; 2632 2633 Chain = TCChain; 2634 return true; 2635 } 2636 2637 bool ARMTargetLowering::mayBeEmittedAsTailCall(CallInst *CI) const { 2638 if (!Subtarget->supportsTailCall()) 2639 return false; 2640 2641 auto Attr = 2642 CI->getParent()->getParent()->getFnAttribute("disable-tail-calls"); 2643 if (!CI->isTailCall() || Attr.getValueAsString() == "true") 2644 return false; 2645 2646 return true; 2647 } 2648 2649 // Trying to write a 64 bit value so need to split into two 32 bit values first, 2650 // and pass the lower and high parts through. 2651 static SDValue LowerWRITE_REGISTER(SDValue Op, SelectionDAG &DAG) { 2652 SDLoc DL(Op); 2653 SDValue WriteValue = Op->getOperand(2); 2654 2655 // This function is only supposed to be called for i64 type argument. 2656 assert(WriteValue.getValueType() == MVT::i64 2657 && "LowerWRITE_REGISTER called for non-i64 type argument."); 2658 2659 SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, WriteValue, 2660 DAG.getConstant(0, DL, MVT::i32)); 2661 SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, WriteValue, 2662 DAG.getConstant(1, DL, MVT::i32)); 2663 SDValue Ops[] = { Op->getOperand(0), Op->getOperand(1), Lo, Hi }; 2664 return DAG.getNode(ISD::WRITE_REGISTER, DL, MVT::Other, Ops); 2665 } 2666 2667 // ConstantPool, JumpTable, GlobalAddress, and ExternalSymbol are lowered as 2668 // their target counterpart wrapped in the ARMISD::Wrapper node. Suppose N is 2669 // one of the above mentioned nodes. It has to be wrapped because otherwise 2670 // Select(N) returns N. So the raw TargetGlobalAddress nodes, etc. can only 2671 // be used to form addressing mode. These wrapped nodes will be selected 2672 // into MOVi. 2673 static SDValue LowerConstantPool(SDValue Op, SelectionDAG &DAG) { 2674 EVT PtrVT = Op.getValueType(); 2675 // FIXME there is no actual debug info here 2676 SDLoc dl(Op); 2677 ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op); 2678 SDValue Res; 2679 if (CP->isMachineConstantPoolEntry()) 2680 Res = DAG.getTargetConstantPool(CP->getMachineCPVal(), PtrVT, 2681 CP->getAlignment()); 2682 else 2683 Res = DAG.getTargetConstantPool(CP->getConstVal(), PtrVT, 2684 CP->getAlignment()); 2685 return DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Res); 2686 } 2687 2688 unsigned ARMTargetLowering::getJumpTableEncoding() const { 2689 return MachineJumpTableInfo::EK_Inline; 2690 } 2691 2692 SDValue ARMTargetLowering::LowerBlockAddress(SDValue Op, 2693 SelectionDAG &DAG) const { 2694 MachineFunction &MF = DAG.getMachineFunction(); 2695 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>(); 2696 unsigned ARMPCLabelIndex = 0; 2697 SDLoc DL(Op); 2698 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 2699 const BlockAddress *BA = cast<BlockAddressSDNode>(Op)->getBlockAddress(); 2700 SDValue CPAddr; 2701 bool IsPositionIndependent = isPositionIndependent() || Subtarget->isROPI(); 2702 if (!IsPositionIndependent) { 2703 CPAddr = DAG.getTargetConstantPool(BA, PtrVT, 4); 2704 } else { 2705 unsigned PCAdj = Subtarget->isThumb() ? 4 : 8; 2706 ARMPCLabelIndex = AFI->createPICLabelUId(); 2707 ARMConstantPoolValue *CPV = 2708 ARMConstantPoolConstant::Create(BA, ARMPCLabelIndex, 2709 ARMCP::CPBlockAddress, PCAdj); 2710 CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4); 2711 } 2712 CPAddr = DAG.getNode(ARMISD::Wrapper, DL, PtrVT, CPAddr); 2713 SDValue Result = DAG.getLoad( 2714 PtrVT, DL, DAG.getEntryNode(), CPAddr, 2715 MachinePointerInfo::getConstantPool(DAG.getMachineFunction())); 2716 if (!IsPositionIndependent) 2717 return Result; 2718 SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, DL, MVT::i32); 2719 return DAG.getNode(ARMISD::PIC_ADD, DL, PtrVT, Result, PICLabel); 2720 } 2721 2722 /// \brief Convert a TLS address reference into the correct sequence of loads 2723 /// and calls to compute the variable's address for Darwin, and return an 2724 /// SDValue containing the final node. 2725 2726 /// Darwin only has one TLS scheme which must be capable of dealing with the 2727 /// fully general situation, in the worst case. This means: 2728 /// + "extern __thread" declaration. 2729 /// + Defined in a possibly unknown dynamic library. 2730 /// 2731 /// The general system is that each __thread variable has a [3 x i32] descriptor 2732 /// which contains information used by the runtime to calculate the address. The 2733 /// only part of this the compiler needs to know about is the first word, which 2734 /// contains a function pointer that must be called with the address of the 2735 /// entire descriptor in "r0". 2736 /// 2737 /// Since this descriptor may be in a different unit, in general access must 2738 /// proceed along the usual ARM rules. A common sequence to produce is: 2739 /// 2740 /// movw rT1, :lower16:_var$non_lazy_ptr 2741 /// movt rT1, :upper16:_var$non_lazy_ptr 2742 /// ldr r0, [rT1] 2743 /// ldr rT2, [r0] 2744 /// blx rT2 2745 /// [...address now in r0...] 2746 SDValue 2747 ARMTargetLowering::LowerGlobalTLSAddressDarwin(SDValue Op, 2748 SelectionDAG &DAG) const { 2749 assert(Subtarget->isTargetDarwin() && "TLS only supported on Darwin"); 2750 SDLoc DL(Op); 2751 2752 // First step is to get the address of the actua global symbol. This is where 2753 // the TLS descriptor lives. 2754 SDValue DescAddr = LowerGlobalAddressDarwin(Op, DAG); 2755 2756 // The first entry in the descriptor is a function pointer that we must call 2757 // to obtain the address of the variable. 2758 SDValue Chain = DAG.getEntryNode(); 2759 SDValue FuncTLVGet = DAG.getLoad( 2760 MVT::i32, DL, Chain, DescAddr, 2761 MachinePointerInfo::getGOT(DAG.getMachineFunction()), 2762 /* Alignment = */ 4, 2763 MachineMemOperand::MONonTemporal | MachineMemOperand::MODereferenceable | 2764 MachineMemOperand::MOInvariant); 2765 Chain = FuncTLVGet.getValue(1); 2766 2767 MachineFunction &F = DAG.getMachineFunction(); 2768 MachineFrameInfo &MFI = F.getFrameInfo(); 2769 MFI.setAdjustsStack(true); 2770 2771 // TLS calls preserve all registers except those that absolutely must be 2772 // trashed: R0 (it takes an argument), LR (it's a call) and CPSR (let's not be 2773 // silly). 2774 auto TRI = 2775 getTargetMachine().getSubtargetImpl(*F.getFunction())->getRegisterInfo(); 2776 auto ARI = static_cast<const ARMRegisterInfo *>(TRI); 2777 const uint32_t *Mask = ARI->getTLSCallPreservedMask(DAG.getMachineFunction()); 2778 2779 // Finally, we can make the call. This is just a degenerate version of a 2780 // normal AArch64 call node: r0 takes the address of the descriptor, and 2781 // returns the address of the variable in this thread. 2782 Chain = DAG.getCopyToReg(Chain, DL, ARM::R0, DescAddr, SDValue()); 2783 Chain = 2784 DAG.getNode(ARMISD::CALL, DL, DAG.getVTList(MVT::Other, MVT::Glue), 2785 Chain, FuncTLVGet, DAG.getRegister(ARM::R0, MVT::i32), 2786 DAG.getRegisterMask(Mask), Chain.getValue(1)); 2787 return DAG.getCopyFromReg(Chain, DL, ARM::R0, MVT::i32, Chain.getValue(1)); 2788 } 2789 2790 SDValue 2791 ARMTargetLowering::LowerGlobalTLSAddressWindows(SDValue Op, 2792 SelectionDAG &DAG) const { 2793 assert(Subtarget->isTargetWindows() && "Windows specific TLS lowering"); 2794 2795 SDValue Chain = DAG.getEntryNode(); 2796 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 2797 SDLoc DL(Op); 2798 2799 // Load the current TEB (thread environment block) 2800 SDValue Ops[] = {Chain, 2801 DAG.getConstant(Intrinsic::arm_mrc, DL, MVT::i32), 2802 DAG.getConstant(15, DL, MVT::i32), 2803 DAG.getConstant(0, DL, MVT::i32), 2804 DAG.getConstant(13, DL, MVT::i32), 2805 DAG.getConstant(0, DL, MVT::i32), 2806 DAG.getConstant(2, DL, MVT::i32)}; 2807 SDValue CurrentTEB = DAG.getNode(ISD::INTRINSIC_W_CHAIN, DL, 2808 DAG.getVTList(MVT::i32, MVT::Other), Ops); 2809 2810 SDValue TEB = CurrentTEB.getValue(0); 2811 Chain = CurrentTEB.getValue(1); 2812 2813 // Load the ThreadLocalStoragePointer from the TEB 2814 // A pointer to the TLS array is located at offset 0x2c from the TEB. 2815 SDValue TLSArray = 2816 DAG.getNode(ISD::ADD, DL, PtrVT, TEB, DAG.getIntPtrConstant(0x2c, DL)); 2817 TLSArray = DAG.getLoad(PtrVT, DL, Chain, TLSArray, MachinePointerInfo()); 2818 2819 // The pointer to the thread's TLS data area is at the TLS Index scaled by 4 2820 // offset into the TLSArray. 2821 2822 // Load the TLS index from the C runtime 2823 SDValue TLSIndex = 2824 DAG.getTargetExternalSymbol("_tls_index", PtrVT, ARMII::MO_NO_FLAG); 2825 TLSIndex = DAG.getNode(ARMISD::Wrapper, DL, PtrVT, TLSIndex); 2826 TLSIndex = DAG.getLoad(PtrVT, DL, Chain, TLSIndex, MachinePointerInfo()); 2827 2828 SDValue Slot = DAG.getNode(ISD::SHL, DL, PtrVT, TLSIndex, 2829 DAG.getConstant(2, DL, MVT::i32)); 2830 SDValue TLS = DAG.getLoad(PtrVT, DL, Chain, 2831 DAG.getNode(ISD::ADD, DL, PtrVT, TLSArray, Slot), 2832 MachinePointerInfo()); 2833 2834 // Get the offset of the start of the .tls section (section base) 2835 const auto *GA = cast<GlobalAddressSDNode>(Op); 2836 auto *CPV = ARMConstantPoolConstant::Create(GA->getGlobal(), ARMCP::SECREL); 2837 SDValue Offset = DAG.getLoad( 2838 PtrVT, DL, Chain, DAG.getNode(ARMISD::Wrapper, DL, MVT::i32, 2839 DAG.getTargetConstantPool(CPV, PtrVT, 4)), 2840 MachinePointerInfo::getConstantPool(DAG.getMachineFunction())); 2841 2842 return DAG.getNode(ISD::ADD, DL, PtrVT, TLS, Offset); 2843 } 2844 2845 // Lower ISD::GlobalTLSAddress using the "general dynamic" model 2846 SDValue 2847 ARMTargetLowering::LowerToTLSGeneralDynamicModel(GlobalAddressSDNode *GA, 2848 SelectionDAG &DAG) const { 2849 SDLoc dl(GA); 2850 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 2851 unsigned char PCAdj = Subtarget->isThumb() ? 4 : 8; 2852 MachineFunction &MF = DAG.getMachineFunction(); 2853 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>(); 2854 unsigned ARMPCLabelIndex = AFI->createPICLabelUId(); 2855 ARMConstantPoolValue *CPV = 2856 ARMConstantPoolConstant::Create(GA->getGlobal(), ARMPCLabelIndex, 2857 ARMCP::CPValue, PCAdj, ARMCP::TLSGD, true); 2858 SDValue Argument = DAG.getTargetConstantPool(CPV, PtrVT, 4); 2859 Argument = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Argument); 2860 Argument = DAG.getLoad( 2861 PtrVT, dl, DAG.getEntryNode(), Argument, 2862 MachinePointerInfo::getConstantPool(DAG.getMachineFunction())); 2863 SDValue Chain = Argument.getValue(1); 2864 2865 SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, dl, MVT::i32); 2866 Argument = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Argument, PICLabel); 2867 2868 // call __tls_get_addr. 2869 ArgListTy Args; 2870 ArgListEntry Entry; 2871 Entry.Node = Argument; 2872 Entry.Ty = (Type *) Type::getInt32Ty(*DAG.getContext()); 2873 Args.push_back(Entry); 2874 2875 // FIXME: is there useful debug info available here? 2876 TargetLowering::CallLoweringInfo CLI(DAG); 2877 CLI.setDebugLoc(dl).setChain(Chain) 2878 .setCallee(CallingConv::C, Type::getInt32Ty(*DAG.getContext()), 2879 DAG.getExternalSymbol("__tls_get_addr", PtrVT), std::move(Args)); 2880 2881 std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI); 2882 return CallResult.first; 2883 } 2884 2885 // Lower ISD::GlobalTLSAddress using the "initial exec" or 2886 // "local exec" model. 2887 SDValue 2888 ARMTargetLowering::LowerToTLSExecModels(GlobalAddressSDNode *GA, 2889 SelectionDAG &DAG, 2890 TLSModel::Model model) const { 2891 const GlobalValue *GV = GA->getGlobal(); 2892 SDLoc dl(GA); 2893 SDValue Offset; 2894 SDValue Chain = DAG.getEntryNode(); 2895 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 2896 // Get the Thread Pointer 2897 SDValue ThreadPointer = DAG.getNode(ARMISD::THREAD_POINTER, dl, PtrVT); 2898 2899 if (model == TLSModel::InitialExec) { 2900 MachineFunction &MF = DAG.getMachineFunction(); 2901 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>(); 2902 unsigned ARMPCLabelIndex = AFI->createPICLabelUId(); 2903 // Initial exec model. 2904 unsigned char PCAdj = Subtarget->isThumb() ? 4 : 8; 2905 ARMConstantPoolValue *CPV = 2906 ARMConstantPoolConstant::Create(GA->getGlobal(), ARMPCLabelIndex, 2907 ARMCP::CPValue, PCAdj, ARMCP::GOTTPOFF, 2908 true); 2909 Offset = DAG.getTargetConstantPool(CPV, PtrVT, 4); 2910 Offset = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Offset); 2911 Offset = DAG.getLoad( 2912 PtrVT, dl, Chain, Offset, 2913 MachinePointerInfo::getConstantPool(DAG.getMachineFunction())); 2914 Chain = Offset.getValue(1); 2915 2916 SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, dl, MVT::i32); 2917 Offset = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Offset, PICLabel); 2918 2919 Offset = DAG.getLoad( 2920 PtrVT, dl, Chain, Offset, 2921 MachinePointerInfo::getConstantPool(DAG.getMachineFunction())); 2922 } else { 2923 // local exec model 2924 assert(model == TLSModel::LocalExec); 2925 ARMConstantPoolValue *CPV = 2926 ARMConstantPoolConstant::Create(GV, ARMCP::TPOFF); 2927 Offset = DAG.getTargetConstantPool(CPV, PtrVT, 4); 2928 Offset = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Offset); 2929 Offset = DAG.getLoad( 2930 PtrVT, dl, Chain, Offset, 2931 MachinePointerInfo::getConstantPool(DAG.getMachineFunction())); 2932 } 2933 2934 // The address of the thread local variable is the add of the thread 2935 // pointer with the offset of the variable. 2936 return DAG.getNode(ISD::ADD, dl, PtrVT, ThreadPointer, Offset); 2937 } 2938 2939 SDValue 2940 ARMTargetLowering::LowerGlobalTLSAddress(SDValue Op, SelectionDAG &DAG) const { 2941 if (Subtarget->isTargetDarwin()) 2942 return LowerGlobalTLSAddressDarwin(Op, DAG); 2943 2944 if (Subtarget->isTargetWindows()) 2945 return LowerGlobalTLSAddressWindows(Op, DAG); 2946 2947 // TODO: implement the "local dynamic" model 2948 assert(Subtarget->isTargetELF() && "Only ELF implemented here"); 2949 GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op); 2950 if (DAG.getTarget().Options.EmulatedTLS) 2951 return LowerToTLSEmulatedModel(GA, DAG); 2952 2953 TLSModel::Model model = getTargetMachine().getTLSModel(GA->getGlobal()); 2954 2955 switch (model) { 2956 case TLSModel::GeneralDynamic: 2957 case TLSModel::LocalDynamic: 2958 return LowerToTLSGeneralDynamicModel(GA, DAG); 2959 case TLSModel::InitialExec: 2960 case TLSModel::LocalExec: 2961 return LowerToTLSExecModels(GA, DAG, model); 2962 } 2963 llvm_unreachable("bogus TLS model"); 2964 } 2965 2966 SDValue ARMTargetLowering::LowerGlobalAddressELF(SDValue Op, 2967 SelectionDAG &DAG) const { 2968 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 2969 SDLoc dl(Op); 2970 const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal(); 2971 const TargetMachine &TM = getTargetMachine(); 2972 if (const GlobalAlias *GA = dyn_cast<GlobalAlias>(GV)) 2973 GV = GA->getBaseObject(); 2974 bool IsRO = 2975 (isa<GlobalVariable>(GV) && cast<GlobalVariable>(GV)->isConstant()) || 2976 isa<Function>(GV); 2977 if (isPositionIndependent()) { 2978 bool UseGOT_PREL = !TM.shouldAssumeDSOLocal(*GV->getParent(), GV); 2979 2980 MachineFunction &MF = DAG.getMachineFunction(); 2981 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>(); 2982 unsigned ARMPCLabelIndex = AFI->createPICLabelUId(); 2983 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 2984 SDLoc dl(Op); 2985 unsigned PCAdj = Subtarget->isThumb() ? 4 : 8; 2986 ARMConstantPoolValue *CPV = ARMConstantPoolConstant::Create( 2987 GV, ARMPCLabelIndex, ARMCP::CPValue, PCAdj, 2988 UseGOT_PREL ? ARMCP::GOT_PREL : ARMCP::no_modifier, 2989 /*AddCurrentAddress=*/UseGOT_PREL); 2990 SDValue CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4); 2991 CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr); 2992 SDValue Result = DAG.getLoad( 2993 PtrVT, dl, DAG.getEntryNode(), CPAddr, 2994 MachinePointerInfo::getConstantPool(DAG.getMachineFunction())); 2995 SDValue Chain = Result.getValue(1); 2996 SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, dl, MVT::i32); 2997 Result = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Result, PICLabel); 2998 if (UseGOT_PREL) 2999 Result = 3000 DAG.getLoad(PtrVT, dl, Chain, Result, 3001 MachinePointerInfo::getGOT(DAG.getMachineFunction())); 3002 return Result; 3003 } else if (Subtarget->isROPI() && IsRO) { 3004 // PC-relative. 3005 SDValue G = DAG.getTargetGlobalAddress(GV, dl, PtrVT); 3006 SDValue Result = DAG.getNode(ARMISD::WrapperPIC, dl, PtrVT, G); 3007 return Result; 3008 } else if (Subtarget->isRWPI() && !IsRO) { 3009 // SB-relative. 3010 ARMConstantPoolValue *CPV = 3011 ARMConstantPoolConstant::Create(GV, ARMCP::SBREL); 3012 SDValue CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4); 3013 CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr); 3014 SDValue G = DAG.getLoad( 3015 PtrVT, dl, DAG.getEntryNode(), CPAddr, 3016 MachinePointerInfo::getConstantPool(DAG.getMachineFunction())); 3017 SDValue SB = DAG.getCopyFromReg(DAG.getEntryNode(), dl, ARM::R9, PtrVT); 3018 SDValue Result = DAG.getNode(ISD::ADD, dl, PtrVT, SB, G); 3019 return Result; 3020 } 3021 3022 // If we have T2 ops, we can materialize the address directly via movt/movw 3023 // pair. This is always cheaper. 3024 if (Subtarget->useMovt(DAG.getMachineFunction())) { 3025 ++NumMovwMovt; 3026 // FIXME: Once remat is capable of dealing with instructions with register 3027 // operands, expand this into two nodes. 3028 return DAG.getNode(ARMISD::Wrapper, dl, PtrVT, 3029 DAG.getTargetGlobalAddress(GV, dl, PtrVT)); 3030 } else { 3031 SDValue CPAddr = DAG.getTargetConstantPool(GV, PtrVT, 4); 3032 CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr); 3033 return DAG.getLoad( 3034 PtrVT, dl, DAG.getEntryNode(), CPAddr, 3035 MachinePointerInfo::getConstantPool(DAG.getMachineFunction())); 3036 } 3037 } 3038 3039 SDValue ARMTargetLowering::LowerGlobalAddressDarwin(SDValue Op, 3040 SelectionDAG &DAG) const { 3041 assert(!Subtarget->isROPI() && !Subtarget->isRWPI() && 3042 "ROPI/RWPI not currently supported for Darwin"); 3043 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 3044 SDLoc dl(Op); 3045 const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal(); 3046 3047 if (Subtarget->useMovt(DAG.getMachineFunction())) 3048 ++NumMovwMovt; 3049 3050 // FIXME: Once remat is capable of dealing with instructions with register 3051 // operands, expand this into multiple nodes 3052 unsigned Wrapper = 3053 isPositionIndependent() ? ARMISD::WrapperPIC : ARMISD::Wrapper; 3054 3055 SDValue G = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, ARMII::MO_NONLAZY); 3056 SDValue Result = DAG.getNode(Wrapper, dl, PtrVT, G); 3057 3058 if (Subtarget->isGVIndirectSymbol(GV)) 3059 Result = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Result, 3060 MachinePointerInfo::getGOT(DAG.getMachineFunction())); 3061 return Result; 3062 } 3063 3064 SDValue ARMTargetLowering::LowerGlobalAddressWindows(SDValue Op, 3065 SelectionDAG &DAG) const { 3066 assert(Subtarget->isTargetWindows() && "non-Windows COFF is not supported"); 3067 assert(Subtarget->useMovt(DAG.getMachineFunction()) && 3068 "Windows on ARM expects to use movw/movt"); 3069 assert(!Subtarget->isROPI() && !Subtarget->isRWPI() && 3070 "ROPI/RWPI not currently supported for Windows"); 3071 3072 const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal(); 3073 const ARMII::TOF TargetFlags = 3074 (GV->hasDLLImportStorageClass() ? ARMII::MO_DLLIMPORT : ARMII::MO_NO_FLAG); 3075 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 3076 SDValue Result; 3077 SDLoc DL(Op); 3078 3079 ++NumMovwMovt; 3080 3081 // FIXME: Once remat is capable of dealing with instructions with register 3082 // operands, expand this into two nodes. 3083 Result = DAG.getNode(ARMISD::Wrapper, DL, PtrVT, 3084 DAG.getTargetGlobalAddress(GV, DL, PtrVT, /*Offset=*/0, 3085 TargetFlags)); 3086 if (GV->hasDLLImportStorageClass()) 3087 Result = DAG.getLoad(PtrVT, DL, DAG.getEntryNode(), Result, 3088 MachinePointerInfo::getGOT(DAG.getMachineFunction())); 3089 return Result; 3090 } 3091 3092 SDValue 3093 ARMTargetLowering::LowerEH_SJLJ_SETJMP(SDValue Op, SelectionDAG &DAG) const { 3094 SDLoc dl(Op); 3095 SDValue Val = DAG.getConstant(0, dl, MVT::i32); 3096 return DAG.getNode(ARMISD::EH_SJLJ_SETJMP, dl, 3097 DAG.getVTList(MVT::i32, MVT::Other), Op.getOperand(0), 3098 Op.getOperand(1), Val); 3099 } 3100 3101 SDValue 3102 ARMTargetLowering::LowerEH_SJLJ_LONGJMP(SDValue Op, SelectionDAG &DAG) const { 3103 SDLoc dl(Op); 3104 return DAG.getNode(ARMISD::EH_SJLJ_LONGJMP, dl, MVT::Other, Op.getOperand(0), 3105 Op.getOperand(1), DAG.getConstant(0, dl, MVT::i32)); 3106 } 3107 3108 SDValue ARMTargetLowering::LowerEH_SJLJ_SETUP_DISPATCH(SDValue Op, 3109 SelectionDAG &DAG) const { 3110 SDLoc dl(Op); 3111 return DAG.getNode(ARMISD::EH_SJLJ_SETUP_DISPATCH, dl, MVT::Other, 3112 Op.getOperand(0)); 3113 } 3114 3115 SDValue 3116 ARMTargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op, SelectionDAG &DAG, 3117 const ARMSubtarget *Subtarget) const { 3118 unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue(); 3119 SDLoc dl(Op); 3120 switch (IntNo) { 3121 default: return SDValue(); // Don't custom lower most intrinsics. 3122 case Intrinsic::arm_rbit: { 3123 assert(Op.getOperand(1).getValueType() == MVT::i32 && 3124 "RBIT intrinsic must have i32 type!"); 3125 return DAG.getNode(ISD::BITREVERSE, dl, MVT::i32, Op.getOperand(1)); 3126 } 3127 case Intrinsic::thread_pointer: { 3128 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 3129 return DAG.getNode(ARMISD::THREAD_POINTER, dl, PtrVT); 3130 } 3131 case Intrinsic::eh_sjlj_lsda: { 3132 MachineFunction &MF = DAG.getMachineFunction(); 3133 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>(); 3134 unsigned ARMPCLabelIndex = AFI->createPICLabelUId(); 3135 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 3136 SDValue CPAddr; 3137 bool IsPositionIndependent = isPositionIndependent(); 3138 unsigned PCAdj = IsPositionIndependent ? (Subtarget->isThumb() ? 4 : 8) : 0; 3139 ARMConstantPoolValue *CPV = 3140 ARMConstantPoolConstant::Create(MF.getFunction(), ARMPCLabelIndex, 3141 ARMCP::CPLSDA, PCAdj); 3142 CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4); 3143 CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr); 3144 SDValue Result = DAG.getLoad( 3145 PtrVT, dl, DAG.getEntryNode(), CPAddr, 3146 MachinePointerInfo::getConstantPool(DAG.getMachineFunction())); 3147 3148 if (IsPositionIndependent) { 3149 SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, dl, MVT::i32); 3150 Result = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Result, PICLabel); 3151 } 3152 return Result; 3153 } 3154 case Intrinsic::arm_neon_vmulls: 3155 case Intrinsic::arm_neon_vmullu: { 3156 unsigned NewOpc = (IntNo == Intrinsic::arm_neon_vmulls) 3157 ? ARMISD::VMULLs : ARMISD::VMULLu; 3158 return DAG.getNode(NewOpc, SDLoc(Op), Op.getValueType(), 3159 Op.getOperand(1), Op.getOperand(2)); 3160 } 3161 case Intrinsic::arm_neon_vminnm: 3162 case Intrinsic::arm_neon_vmaxnm: { 3163 unsigned NewOpc = (IntNo == Intrinsic::arm_neon_vminnm) 3164 ? ISD::FMINNUM : ISD::FMAXNUM; 3165 return DAG.getNode(NewOpc, SDLoc(Op), Op.getValueType(), 3166 Op.getOperand(1), Op.getOperand(2)); 3167 } 3168 case Intrinsic::arm_neon_vminu: 3169 case Intrinsic::arm_neon_vmaxu: { 3170 if (Op.getValueType().isFloatingPoint()) 3171 return SDValue(); 3172 unsigned NewOpc = (IntNo == Intrinsic::arm_neon_vminu) 3173 ? ISD::UMIN : ISD::UMAX; 3174 return DAG.getNode(NewOpc, SDLoc(Op), Op.getValueType(), 3175 Op.getOperand(1), Op.getOperand(2)); 3176 } 3177 case Intrinsic::arm_neon_vmins: 3178 case Intrinsic::arm_neon_vmaxs: { 3179 // v{min,max}s is overloaded between signed integers and floats. 3180 if (!Op.getValueType().isFloatingPoint()) { 3181 unsigned NewOpc = (IntNo == Intrinsic::arm_neon_vmins) 3182 ? ISD::SMIN : ISD::SMAX; 3183 return DAG.getNode(NewOpc, SDLoc(Op), Op.getValueType(), 3184 Op.getOperand(1), Op.getOperand(2)); 3185 } 3186 unsigned NewOpc = (IntNo == Intrinsic::arm_neon_vmins) 3187 ? ISD::FMINNAN : ISD::FMAXNAN; 3188 return DAG.getNode(NewOpc, SDLoc(Op), Op.getValueType(), 3189 Op.getOperand(1), Op.getOperand(2)); 3190 } 3191 } 3192 } 3193 3194 static SDValue LowerATOMIC_FENCE(SDValue Op, SelectionDAG &DAG, 3195 const ARMSubtarget *Subtarget) { 3196 // FIXME: handle "fence singlethread" more efficiently. 3197 SDLoc dl(Op); 3198 if (!Subtarget->hasDataBarrier()) { 3199 // Some ARMv6 cpus can support data barriers with an mcr instruction. 3200 // Thumb1 and pre-v6 ARM mode use a libcall instead and should never get 3201 // here. 3202 assert(Subtarget->hasV6Ops() && !Subtarget->isThumb() && 3203 "Unexpected ISD::ATOMIC_FENCE encountered. Should be libcall!"); 3204 return DAG.getNode(ARMISD::MEMBARRIER_MCR, dl, MVT::Other, Op.getOperand(0), 3205 DAG.getConstant(0, dl, MVT::i32)); 3206 } 3207 3208 ConstantSDNode *OrdN = cast<ConstantSDNode>(Op.getOperand(1)); 3209 AtomicOrdering Ord = static_cast<AtomicOrdering>(OrdN->getZExtValue()); 3210 ARM_MB::MemBOpt Domain = ARM_MB::ISH; 3211 if (Subtarget->isMClass()) { 3212 // Only a full system barrier exists in the M-class architectures. 3213 Domain = ARM_MB::SY; 3214 } else if (Subtarget->preferISHSTBarriers() && 3215 Ord == AtomicOrdering::Release) { 3216 // Swift happens to implement ISHST barriers in a way that's compatible with 3217 // Release semantics but weaker than ISH so we'd be fools not to use 3218 // it. Beware: other processors probably don't! 3219 Domain = ARM_MB::ISHST; 3220 } 3221 3222 return DAG.getNode(ISD::INTRINSIC_VOID, dl, MVT::Other, Op.getOperand(0), 3223 DAG.getConstant(Intrinsic::arm_dmb, dl, MVT::i32), 3224 DAG.getConstant(Domain, dl, MVT::i32)); 3225 } 3226 3227 static SDValue LowerPREFETCH(SDValue Op, SelectionDAG &DAG, 3228 const ARMSubtarget *Subtarget) { 3229 // ARM pre v5TE and Thumb1 does not have preload instructions. 3230 if (!(Subtarget->isThumb2() || 3231 (!Subtarget->isThumb1Only() && Subtarget->hasV5TEOps()))) 3232 // Just preserve the chain. 3233 return Op.getOperand(0); 3234 3235 SDLoc dl(Op); 3236 unsigned isRead = ~cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue() & 1; 3237 if (!isRead && 3238 (!Subtarget->hasV7Ops() || !Subtarget->hasMPExtension())) 3239 // ARMv7 with MP extension has PLDW. 3240 return Op.getOperand(0); 3241 3242 unsigned isData = cast<ConstantSDNode>(Op.getOperand(4))->getZExtValue(); 3243 if (Subtarget->isThumb()) { 3244 // Invert the bits. 3245 isRead = ~isRead & 1; 3246 isData = ~isData & 1; 3247 } 3248 3249 return DAG.getNode(ARMISD::PRELOAD, dl, MVT::Other, Op.getOperand(0), 3250 Op.getOperand(1), DAG.getConstant(isRead, dl, MVT::i32), 3251 DAG.getConstant(isData, dl, MVT::i32)); 3252 } 3253 3254 static SDValue LowerVASTART(SDValue Op, SelectionDAG &DAG) { 3255 MachineFunction &MF = DAG.getMachineFunction(); 3256 ARMFunctionInfo *FuncInfo = MF.getInfo<ARMFunctionInfo>(); 3257 3258 // vastart just stores the address of the VarArgsFrameIndex slot into the 3259 // memory location argument. 3260 SDLoc dl(Op); 3261 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout()); 3262 SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT); 3263 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue(); 3264 return DAG.getStore(Op.getOperand(0), dl, FR, Op.getOperand(1), 3265 MachinePointerInfo(SV)); 3266 } 3267 3268 SDValue ARMTargetLowering::GetF64FormalArgument(CCValAssign &VA, 3269 CCValAssign &NextVA, 3270 SDValue &Root, 3271 SelectionDAG &DAG, 3272 const SDLoc &dl) const { 3273 MachineFunction &MF = DAG.getMachineFunction(); 3274 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>(); 3275 3276 const TargetRegisterClass *RC; 3277 if (AFI->isThumb1OnlyFunction()) 3278 RC = &ARM::tGPRRegClass; 3279 else 3280 RC = &ARM::GPRRegClass; 3281 3282 // Transform the arguments stored in physical registers into virtual ones. 3283 unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC); 3284 SDValue ArgValue = DAG.getCopyFromReg(Root, dl, Reg, MVT::i32); 3285 3286 SDValue ArgValue2; 3287 if (NextVA.isMemLoc()) { 3288 MachineFrameInfo &MFI = MF.getFrameInfo(); 3289 int FI = MFI.CreateFixedObject(4, NextVA.getLocMemOffset(), true); 3290 3291 // Create load node to retrieve arguments from the stack. 3292 SDValue FIN = DAG.getFrameIndex(FI, getPointerTy(DAG.getDataLayout())); 3293 ArgValue2 = DAG.getLoad( 3294 MVT::i32, dl, Root, FIN, 3295 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI)); 3296 } else { 3297 Reg = MF.addLiveIn(NextVA.getLocReg(), RC); 3298 ArgValue2 = DAG.getCopyFromReg(Root, dl, Reg, MVT::i32); 3299 } 3300 if (!Subtarget->isLittle()) 3301 std::swap (ArgValue, ArgValue2); 3302 return DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, ArgValue, ArgValue2); 3303 } 3304 3305 // The remaining GPRs hold either the beginning of variable-argument 3306 // data, or the beginning of an aggregate passed by value (usually 3307 // byval). Either way, we allocate stack slots adjacent to the data 3308 // provided by our caller, and store the unallocated registers there. 3309 // If this is a variadic function, the va_list pointer will begin with 3310 // these values; otherwise, this reassembles a (byval) structure that 3311 // was split between registers and memory. 3312 // Return: The frame index registers were stored into. 3313 int ARMTargetLowering::StoreByValRegs(CCState &CCInfo, SelectionDAG &DAG, 3314 const SDLoc &dl, SDValue &Chain, 3315 const Value *OrigArg, 3316 unsigned InRegsParamRecordIdx, 3317 int ArgOffset, unsigned ArgSize) const { 3318 // Currently, two use-cases possible: 3319 // Case #1. Non-var-args function, and we meet first byval parameter. 3320 // Setup first unallocated register as first byval register; 3321 // eat all remained registers 3322 // (these two actions are performed by HandleByVal method). 3323 // Then, here, we initialize stack frame with 3324 // "store-reg" instructions. 3325 // Case #2. Var-args function, that doesn't contain byval parameters. 3326 // The same: eat all remained unallocated registers, 3327 // initialize stack frame. 3328 3329 MachineFunction &MF = DAG.getMachineFunction(); 3330 MachineFrameInfo &MFI = MF.getFrameInfo(); 3331 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>(); 3332 unsigned RBegin, REnd; 3333 if (InRegsParamRecordIdx < CCInfo.getInRegsParamsCount()) { 3334 CCInfo.getInRegsParamInfo(InRegsParamRecordIdx, RBegin, REnd); 3335 } else { 3336 unsigned RBeginIdx = CCInfo.getFirstUnallocated(GPRArgRegs); 3337 RBegin = RBeginIdx == 4 ? (unsigned)ARM::R4 : GPRArgRegs[RBeginIdx]; 3338 REnd = ARM::R4; 3339 } 3340 3341 if (REnd != RBegin) 3342 ArgOffset = -4 * (ARM::R4 - RBegin); 3343 3344 auto PtrVT = getPointerTy(DAG.getDataLayout()); 3345 int FrameIndex = MFI.CreateFixedObject(ArgSize, ArgOffset, false); 3346 SDValue FIN = DAG.getFrameIndex(FrameIndex, PtrVT); 3347 3348 SmallVector<SDValue, 4> MemOps; 3349 const TargetRegisterClass *RC = 3350 AFI->isThumb1OnlyFunction() ? &ARM::tGPRRegClass : &ARM::GPRRegClass; 3351 3352 for (unsigned Reg = RBegin, i = 0; Reg < REnd; ++Reg, ++i) { 3353 unsigned VReg = MF.addLiveIn(Reg, RC); 3354 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i32); 3355 SDValue Store = DAG.getStore(Val.getValue(1), dl, Val, FIN, 3356 MachinePointerInfo(OrigArg, 4 * i)); 3357 MemOps.push_back(Store); 3358 FIN = DAG.getNode(ISD::ADD, dl, PtrVT, FIN, DAG.getConstant(4, dl, PtrVT)); 3359 } 3360 3361 if (!MemOps.empty()) 3362 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOps); 3363 return FrameIndex; 3364 } 3365 3366 // Setup stack frame, the va_list pointer will start from. 3367 void ARMTargetLowering::VarArgStyleRegisters(CCState &CCInfo, SelectionDAG &DAG, 3368 const SDLoc &dl, SDValue &Chain, 3369 unsigned ArgOffset, 3370 unsigned TotalArgRegsSaveSize, 3371 bool ForceMutable) const { 3372 MachineFunction &MF = DAG.getMachineFunction(); 3373 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>(); 3374 3375 // Try to store any remaining integer argument regs 3376 // to their spots on the stack so that they may be loaded by dereferencing 3377 // the result of va_next. 3378 // If there is no regs to be stored, just point address after last 3379 // argument passed via stack. 3380 int FrameIndex = StoreByValRegs(CCInfo, DAG, dl, Chain, nullptr, 3381 CCInfo.getInRegsParamsCount(), 3382 CCInfo.getNextStackOffset(), 4); 3383 AFI->setVarArgsFrameIndex(FrameIndex); 3384 } 3385 3386 SDValue ARMTargetLowering::LowerFormalArguments( 3387 SDValue Chain, CallingConv::ID CallConv, bool isVarArg, 3388 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl, 3389 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const { 3390 MachineFunction &MF = DAG.getMachineFunction(); 3391 MachineFrameInfo &MFI = MF.getFrameInfo(); 3392 3393 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>(); 3394 3395 // Assign locations to all of the incoming arguments. 3396 SmallVector<CCValAssign, 16> ArgLocs; 3397 ARMCCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), ArgLocs, 3398 *DAG.getContext(), Prologue); 3399 CCInfo.AnalyzeFormalArguments(Ins, 3400 CCAssignFnForNode(CallConv, /* Return*/ false, 3401 isVarArg)); 3402 3403 SmallVector<SDValue, 16> ArgValues; 3404 SDValue ArgValue; 3405 Function::const_arg_iterator CurOrigArg = MF.getFunction()->arg_begin(); 3406 unsigned CurArgIdx = 0; 3407 3408 // Initially ArgRegsSaveSize is zero. 3409 // Then we increase this value each time we meet byval parameter. 3410 // We also increase this value in case of varargs function. 3411 AFI->setArgRegsSaveSize(0); 3412 3413 // Calculate the amount of stack space that we need to allocate to store 3414 // byval and variadic arguments that are passed in registers. 3415 // We need to know this before we allocate the first byval or variadic 3416 // argument, as they will be allocated a stack slot below the CFA (Canonical 3417 // Frame Address, the stack pointer at entry to the function). 3418 unsigned ArgRegBegin = ARM::R4; 3419 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) { 3420 if (CCInfo.getInRegsParamsProcessed() >= CCInfo.getInRegsParamsCount()) 3421 break; 3422 3423 CCValAssign &VA = ArgLocs[i]; 3424 unsigned Index = VA.getValNo(); 3425 ISD::ArgFlagsTy Flags = Ins[Index].Flags; 3426 if (!Flags.isByVal()) 3427 continue; 3428 3429 assert(VA.isMemLoc() && "unexpected byval pointer in reg"); 3430 unsigned RBegin, REnd; 3431 CCInfo.getInRegsParamInfo(CCInfo.getInRegsParamsProcessed(), RBegin, REnd); 3432 ArgRegBegin = std::min(ArgRegBegin, RBegin); 3433 3434 CCInfo.nextInRegsParam(); 3435 } 3436 CCInfo.rewindByValRegsInfo(); 3437 3438 int lastInsIndex = -1; 3439 if (isVarArg && MFI.hasVAStart()) { 3440 unsigned RegIdx = CCInfo.getFirstUnallocated(GPRArgRegs); 3441 if (RegIdx != array_lengthof(GPRArgRegs)) 3442 ArgRegBegin = std::min(ArgRegBegin, (unsigned)GPRArgRegs[RegIdx]); 3443 } 3444 3445 unsigned TotalArgRegsSaveSize = 4 * (ARM::R4 - ArgRegBegin); 3446 AFI->setArgRegsSaveSize(TotalArgRegsSaveSize); 3447 auto PtrVT = getPointerTy(DAG.getDataLayout()); 3448 3449 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) { 3450 CCValAssign &VA = ArgLocs[i]; 3451 if (Ins[VA.getValNo()].isOrigArg()) { 3452 std::advance(CurOrigArg, 3453 Ins[VA.getValNo()].getOrigArgIndex() - CurArgIdx); 3454 CurArgIdx = Ins[VA.getValNo()].getOrigArgIndex(); 3455 } 3456 // Arguments stored in registers. 3457 if (VA.isRegLoc()) { 3458 EVT RegVT = VA.getLocVT(); 3459 3460 if (VA.needsCustom()) { 3461 // f64 and vector types are split up into multiple registers or 3462 // combinations of registers and stack slots. 3463 if (VA.getLocVT() == MVT::v2f64) { 3464 SDValue ArgValue1 = GetF64FormalArgument(VA, ArgLocs[++i], 3465 Chain, DAG, dl); 3466 VA = ArgLocs[++i]; // skip ahead to next loc 3467 SDValue ArgValue2; 3468 if (VA.isMemLoc()) { 3469 int FI = MFI.CreateFixedObject(8, VA.getLocMemOffset(), true); 3470 SDValue FIN = DAG.getFrameIndex(FI, PtrVT); 3471 ArgValue2 = DAG.getLoad(MVT::f64, dl, Chain, FIN, 3472 MachinePointerInfo::getFixedStack( 3473 DAG.getMachineFunction(), FI)); 3474 } else { 3475 ArgValue2 = GetF64FormalArgument(VA, ArgLocs[++i], 3476 Chain, DAG, dl); 3477 } 3478 ArgValue = DAG.getNode(ISD::UNDEF, dl, MVT::v2f64); 3479 ArgValue = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, 3480 ArgValue, ArgValue1, 3481 DAG.getIntPtrConstant(0, dl)); 3482 ArgValue = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, 3483 ArgValue, ArgValue2, 3484 DAG.getIntPtrConstant(1, dl)); 3485 } else 3486 ArgValue = GetF64FormalArgument(VA, ArgLocs[++i], Chain, DAG, dl); 3487 3488 } else { 3489 const TargetRegisterClass *RC; 3490 3491 if (RegVT == MVT::f32) 3492 RC = &ARM::SPRRegClass; 3493 else if (RegVT == MVT::f64) 3494 RC = &ARM::DPRRegClass; 3495 else if (RegVT == MVT::v2f64) 3496 RC = &ARM::QPRRegClass; 3497 else if (RegVT == MVT::i32) 3498 RC = AFI->isThumb1OnlyFunction() ? &ARM::tGPRRegClass 3499 : &ARM::GPRRegClass; 3500 else 3501 llvm_unreachable("RegVT not supported by FORMAL_ARGUMENTS Lowering"); 3502 3503 // Transform the arguments in physical registers into virtual ones. 3504 unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC); 3505 ArgValue = DAG.getCopyFromReg(Chain, dl, Reg, RegVT); 3506 } 3507 3508 // If this is an 8 or 16-bit value, it is really passed promoted 3509 // to 32 bits. Insert an assert[sz]ext to capture this, then 3510 // truncate to the right size. 3511 switch (VA.getLocInfo()) { 3512 default: llvm_unreachable("Unknown loc info!"); 3513 case CCValAssign::Full: break; 3514 case CCValAssign::BCvt: 3515 ArgValue = DAG.getNode(ISD::BITCAST, dl, VA.getValVT(), ArgValue); 3516 break; 3517 case CCValAssign::SExt: 3518 ArgValue = DAG.getNode(ISD::AssertSext, dl, RegVT, ArgValue, 3519 DAG.getValueType(VA.getValVT())); 3520 ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue); 3521 break; 3522 case CCValAssign::ZExt: 3523 ArgValue = DAG.getNode(ISD::AssertZext, dl, RegVT, ArgValue, 3524 DAG.getValueType(VA.getValVT())); 3525 ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue); 3526 break; 3527 } 3528 3529 InVals.push_back(ArgValue); 3530 3531 } else { // VA.isRegLoc() 3532 3533 // sanity check 3534 assert(VA.isMemLoc()); 3535 assert(VA.getValVT() != MVT::i64 && "i64 should already be lowered"); 3536 3537 int index = VA.getValNo(); 3538 3539 // Some Ins[] entries become multiple ArgLoc[] entries. 3540 // Process them only once. 3541 if (index != lastInsIndex) 3542 { 3543 ISD::ArgFlagsTy Flags = Ins[index].Flags; 3544 // FIXME: For now, all byval parameter objects are marked mutable. 3545 // This can be changed with more analysis. 3546 // In case of tail call optimization mark all arguments mutable. 3547 // Since they could be overwritten by lowering of arguments in case of 3548 // a tail call. 3549 if (Flags.isByVal()) { 3550 assert(Ins[index].isOrigArg() && 3551 "Byval arguments cannot be implicit"); 3552 unsigned CurByValIndex = CCInfo.getInRegsParamsProcessed(); 3553 3554 int FrameIndex = StoreByValRegs( 3555 CCInfo, DAG, dl, Chain, &*CurOrigArg, CurByValIndex, 3556 VA.getLocMemOffset(), Flags.getByValSize()); 3557 InVals.push_back(DAG.getFrameIndex(FrameIndex, PtrVT)); 3558 CCInfo.nextInRegsParam(); 3559 } else { 3560 unsigned FIOffset = VA.getLocMemOffset(); 3561 int FI = MFI.CreateFixedObject(VA.getLocVT().getSizeInBits()/8, 3562 FIOffset, true); 3563 3564 // Create load nodes to retrieve arguments from the stack. 3565 SDValue FIN = DAG.getFrameIndex(FI, PtrVT); 3566 InVals.push_back(DAG.getLoad(VA.getValVT(), dl, Chain, FIN, 3567 MachinePointerInfo::getFixedStack( 3568 DAG.getMachineFunction(), FI))); 3569 } 3570 lastInsIndex = index; 3571 } 3572 } 3573 } 3574 3575 // varargs 3576 if (isVarArg && MFI.hasVAStart()) 3577 VarArgStyleRegisters(CCInfo, DAG, dl, Chain, 3578 CCInfo.getNextStackOffset(), 3579 TotalArgRegsSaveSize); 3580 3581 AFI->setArgumentStackSize(CCInfo.getNextStackOffset()); 3582 3583 return Chain; 3584 } 3585 3586 /// isFloatingPointZero - Return true if this is +0.0. 3587 static bool isFloatingPointZero(SDValue Op) { 3588 if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Op)) 3589 return CFP->getValueAPF().isPosZero(); 3590 else if (ISD::isEXTLoad(Op.getNode()) || ISD::isNON_EXTLoad(Op.getNode())) { 3591 // Maybe this has already been legalized into the constant pool? 3592 if (Op.getOperand(1).getOpcode() == ARMISD::Wrapper) { 3593 SDValue WrapperOp = Op.getOperand(1).getOperand(0); 3594 if (ConstantPoolSDNode *CP = dyn_cast<ConstantPoolSDNode>(WrapperOp)) 3595 if (const ConstantFP *CFP = dyn_cast<ConstantFP>(CP->getConstVal())) 3596 return CFP->getValueAPF().isPosZero(); 3597 } 3598 } else if (Op->getOpcode() == ISD::BITCAST && 3599 Op->getValueType(0) == MVT::f64) { 3600 // Handle (ISD::BITCAST (ARMISD::VMOVIMM (ISD::TargetConstant 0)) MVT::f64) 3601 // created by LowerConstantFP(). 3602 SDValue BitcastOp = Op->getOperand(0); 3603 if (BitcastOp->getOpcode() == ARMISD::VMOVIMM && 3604 isNullConstant(BitcastOp->getOperand(0))) 3605 return true; 3606 } 3607 return false; 3608 } 3609 3610 /// Returns appropriate ARM CMP (cmp) and corresponding condition code for 3611 /// the given operands. 3612 SDValue ARMTargetLowering::getARMCmp(SDValue LHS, SDValue RHS, ISD::CondCode CC, 3613 SDValue &ARMcc, SelectionDAG &DAG, 3614 const SDLoc &dl) const { 3615 if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS.getNode())) { 3616 unsigned C = RHSC->getZExtValue(); 3617 if (!isLegalICmpImmediate(C)) { 3618 // Constant does not fit, try adjusting it by one? 3619 switch (CC) { 3620 default: break; 3621 case ISD::SETLT: 3622 case ISD::SETGE: 3623 if (C != 0x80000000 && isLegalICmpImmediate(C-1)) { 3624 CC = (CC == ISD::SETLT) ? ISD::SETLE : ISD::SETGT; 3625 RHS = DAG.getConstant(C - 1, dl, MVT::i32); 3626 } 3627 break; 3628 case ISD::SETULT: 3629 case ISD::SETUGE: 3630 if (C != 0 && isLegalICmpImmediate(C-1)) { 3631 CC = (CC == ISD::SETULT) ? ISD::SETULE : ISD::SETUGT; 3632 RHS = DAG.getConstant(C - 1, dl, MVT::i32); 3633 } 3634 break; 3635 case ISD::SETLE: 3636 case ISD::SETGT: 3637 if (C != 0x7fffffff && isLegalICmpImmediate(C+1)) { 3638 CC = (CC == ISD::SETLE) ? ISD::SETLT : ISD::SETGE; 3639 RHS = DAG.getConstant(C + 1, dl, MVT::i32); 3640 } 3641 break; 3642 case ISD::SETULE: 3643 case ISD::SETUGT: 3644 if (C != 0xffffffff && isLegalICmpImmediate(C+1)) { 3645 CC = (CC == ISD::SETULE) ? ISD::SETULT : ISD::SETUGE; 3646 RHS = DAG.getConstant(C + 1, dl, MVT::i32); 3647 } 3648 break; 3649 } 3650 } 3651 } 3652 3653 ARMCC::CondCodes CondCode = IntCCToARMCC(CC); 3654 ARMISD::NodeType CompareType; 3655 switch (CondCode) { 3656 default: 3657 CompareType = ARMISD::CMP; 3658 break; 3659 case ARMCC::EQ: 3660 case ARMCC::NE: 3661 // Uses only Z Flag 3662 CompareType = ARMISD::CMPZ; 3663 break; 3664 } 3665 ARMcc = DAG.getConstant(CondCode, dl, MVT::i32); 3666 return DAG.getNode(CompareType, dl, MVT::Glue, LHS, RHS); 3667 } 3668 3669 /// Returns a appropriate VFP CMP (fcmp{s|d}+fmstat) for the given operands. 3670 SDValue ARMTargetLowering::getVFPCmp(SDValue LHS, SDValue RHS, 3671 SelectionDAG &DAG, const SDLoc &dl) const { 3672 assert(!Subtarget->isFPOnlySP() || RHS.getValueType() != MVT::f64); 3673 SDValue Cmp; 3674 if (!isFloatingPointZero(RHS)) 3675 Cmp = DAG.getNode(ARMISD::CMPFP, dl, MVT::Glue, LHS, RHS); 3676 else 3677 Cmp = DAG.getNode(ARMISD::CMPFPw0, dl, MVT::Glue, LHS); 3678 return DAG.getNode(ARMISD::FMSTAT, dl, MVT::Glue, Cmp); 3679 } 3680 3681 /// duplicateCmp - Glue values can have only one use, so this function 3682 /// duplicates a comparison node. 3683 SDValue 3684 ARMTargetLowering::duplicateCmp(SDValue Cmp, SelectionDAG &DAG) const { 3685 unsigned Opc = Cmp.getOpcode(); 3686 SDLoc DL(Cmp); 3687 if (Opc == ARMISD::CMP || Opc == ARMISD::CMPZ) 3688 return DAG.getNode(Opc, DL, MVT::Glue, Cmp.getOperand(0),Cmp.getOperand(1)); 3689 3690 assert(Opc == ARMISD::FMSTAT && "unexpected comparison operation"); 3691 Cmp = Cmp.getOperand(0); 3692 Opc = Cmp.getOpcode(); 3693 if (Opc == ARMISD::CMPFP) 3694 Cmp = DAG.getNode(Opc, DL, MVT::Glue, Cmp.getOperand(0),Cmp.getOperand(1)); 3695 else { 3696 assert(Opc == ARMISD::CMPFPw0 && "unexpected operand of FMSTAT"); 3697 Cmp = DAG.getNode(Opc, DL, MVT::Glue, Cmp.getOperand(0)); 3698 } 3699 return DAG.getNode(ARMISD::FMSTAT, DL, MVT::Glue, Cmp); 3700 } 3701 3702 std::pair<SDValue, SDValue> 3703 ARMTargetLowering::getARMXALUOOp(SDValue Op, SelectionDAG &DAG, 3704 SDValue &ARMcc) const { 3705 assert(Op.getValueType() == MVT::i32 && "Unsupported value type"); 3706 3707 SDValue Value, OverflowCmp; 3708 SDValue LHS = Op.getOperand(0); 3709 SDValue RHS = Op.getOperand(1); 3710 SDLoc dl(Op); 3711 3712 // FIXME: We are currently always generating CMPs because we don't support 3713 // generating CMN through the backend. This is not as good as the natural 3714 // CMP case because it causes a register dependency and cannot be folded 3715 // later. 3716 3717 switch (Op.getOpcode()) { 3718 default: 3719 llvm_unreachable("Unknown overflow instruction!"); 3720 case ISD::SADDO: 3721 ARMcc = DAG.getConstant(ARMCC::VC, dl, MVT::i32); 3722 Value = DAG.getNode(ISD::ADD, dl, Op.getValueType(), LHS, RHS); 3723 OverflowCmp = DAG.getNode(ARMISD::CMP, dl, MVT::Glue, Value, LHS); 3724 break; 3725 case ISD::UADDO: 3726 ARMcc = DAG.getConstant(ARMCC::HS, dl, MVT::i32); 3727 Value = DAG.getNode(ISD::ADD, dl, Op.getValueType(), LHS, RHS); 3728 OverflowCmp = DAG.getNode(ARMISD::CMP, dl, MVT::Glue, Value, LHS); 3729 break; 3730 case ISD::SSUBO: 3731 ARMcc = DAG.getConstant(ARMCC::VC, dl, MVT::i32); 3732 Value = DAG.getNode(ISD::SUB, dl, Op.getValueType(), LHS, RHS); 3733 OverflowCmp = DAG.getNode(ARMISD::CMP, dl, MVT::Glue, LHS, RHS); 3734 break; 3735 case ISD::USUBO: 3736 ARMcc = DAG.getConstant(ARMCC::HS, dl, MVT::i32); 3737 Value = DAG.getNode(ISD::SUB, dl, Op.getValueType(), LHS, RHS); 3738 OverflowCmp = DAG.getNode(ARMISD::CMP, dl, MVT::Glue, LHS, RHS); 3739 break; 3740 } // switch (...) 3741 3742 return std::make_pair(Value, OverflowCmp); 3743 } 3744 3745 3746 SDValue 3747 ARMTargetLowering::LowerXALUO(SDValue Op, SelectionDAG &DAG) const { 3748 // Let legalize expand this if it isn't a legal type yet. 3749 if (!DAG.getTargetLoweringInfo().isTypeLegal(Op.getValueType())) 3750 return SDValue(); 3751 3752 SDValue Value, OverflowCmp; 3753 SDValue ARMcc; 3754 std::tie(Value, OverflowCmp) = getARMXALUOOp(Op, DAG, ARMcc); 3755 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32); 3756 SDLoc dl(Op); 3757 // We use 0 and 1 as false and true values. 3758 SDValue TVal = DAG.getConstant(1, dl, MVT::i32); 3759 SDValue FVal = DAG.getConstant(0, dl, MVT::i32); 3760 EVT VT = Op.getValueType(); 3761 3762 SDValue Overflow = DAG.getNode(ARMISD::CMOV, dl, VT, TVal, FVal, 3763 ARMcc, CCR, OverflowCmp); 3764 3765 SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32); 3766 return DAG.getNode(ISD::MERGE_VALUES, dl, VTs, Value, Overflow); 3767 } 3768 3769 3770 SDValue ARMTargetLowering::LowerSELECT(SDValue Op, SelectionDAG &DAG) const { 3771 SDValue Cond = Op.getOperand(0); 3772 SDValue SelectTrue = Op.getOperand(1); 3773 SDValue SelectFalse = Op.getOperand(2); 3774 SDLoc dl(Op); 3775 unsigned Opc = Cond.getOpcode(); 3776 3777 if (Cond.getResNo() == 1 && 3778 (Opc == ISD::SADDO || Opc == ISD::UADDO || Opc == ISD::SSUBO || 3779 Opc == ISD::USUBO)) { 3780 if (!DAG.getTargetLoweringInfo().isTypeLegal(Cond->getValueType(0))) 3781 return SDValue(); 3782 3783 SDValue Value, OverflowCmp; 3784 SDValue ARMcc; 3785 std::tie(Value, OverflowCmp) = getARMXALUOOp(Cond, DAG, ARMcc); 3786 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32); 3787 EVT VT = Op.getValueType(); 3788 3789 return getCMOV(dl, VT, SelectTrue, SelectFalse, ARMcc, CCR, 3790 OverflowCmp, DAG); 3791 } 3792 3793 // Convert: 3794 // 3795 // (select (cmov 1, 0, cond), t, f) -> (cmov t, f, cond) 3796 // (select (cmov 0, 1, cond), t, f) -> (cmov f, t, cond) 3797 // 3798 if (Cond.getOpcode() == ARMISD::CMOV && Cond.hasOneUse()) { 3799 const ConstantSDNode *CMOVTrue = 3800 dyn_cast<ConstantSDNode>(Cond.getOperand(0)); 3801 const ConstantSDNode *CMOVFalse = 3802 dyn_cast<ConstantSDNode>(Cond.getOperand(1)); 3803 3804 if (CMOVTrue && CMOVFalse) { 3805 unsigned CMOVTrueVal = CMOVTrue->getZExtValue(); 3806 unsigned CMOVFalseVal = CMOVFalse->getZExtValue(); 3807 3808 SDValue True; 3809 SDValue False; 3810 if (CMOVTrueVal == 1 && CMOVFalseVal == 0) { 3811 True = SelectTrue; 3812 False = SelectFalse; 3813 } else if (CMOVTrueVal == 0 && CMOVFalseVal == 1) { 3814 True = SelectFalse; 3815 False = SelectTrue; 3816 } 3817 3818 if (True.getNode() && False.getNode()) { 3819 EVT VT = Op.getValueType(); 3820 SDValue ARMcc = Cond.getOperand(2); 3821 SDValue CCR = Cond.getOperand(3); 3822 SDValue Cmp = duplicateCmp(Cond.getOperand(4), DAG); 3823 assert(True.getValueType() == VT); 3824 return getCMOV(dl, VT, True, False, ARMcc, CCR, Cmp, DAG); 3825 } 3826 } 3827 } 3828 3829 // ARM's BooleanContents value is UndefinedBooleanContent. Mask out the 3830 // undefined bits before doing a full-word comparison with zero. 3831 Cond = DAG.getNode(ISD::AND, dl, Cond.getValueType(), Cond, 3832 DAG.getConstant(1, dl, Cond.getValueType())); 3833 3834 return DAG.getSelectCC(dl, Cond, 3835 DAG.getConstant(0, dl, Cond.getValueType()), 3836 SelectTrue, SelectFalse, ISD::SETNE); 3837 } 3838 3839 static void checkVSELConstraints(ISD::CondCode CC, ARMCC::CondCodes &CondCode, 3840 bool &swpCmpOps, bool &swpVselOps) { 3841 // Start by selecting the GE condition code for opcodes that return true for 3842 // 'equality' 3843 if (CC == ISD::SETUGE || CC == ISD::SETOGE || CC == ISD::SETOLE || 3844 CC == ISD::SETULE) 3845 CondCode = ARMCC::GE; 3846 3847 // and GT for opcodes that return false for 'equality'. 3848 else if (CC == ISD::SETUGT || CC == ISD::SETOGT || CC == ISD::SETOLT || 3849 CC == ISD::SETULT) 3850 CondCode = ARMCC::GT; 3851 3852 // Since we are constrained to GE/GT, if the opcode contains 'less', we need 3853 // to swap the compare operands. 3854 if (CC == ISD::SETOLE || CC == ISD::SETULE || CC == ISD::SETOLT || 3855 CC == ISD::SETULT) 3856 swpCmpOps = true; 3857 3858 // Both GT and GE are ordered comparisons, and return false for 'unordered'. 3859 // If we have an unordered opcode, we need to swap the operands to the VSEL 3860 // instruction (effectively negating the condition). 3861 // 3862 // This also has the effect of swapping which one of 'less' or 'greater' 3863 // returns true, so we also swap the compare operands. It also switches 3864 // whether we return true for 'equality', so we compensate by picking the 3865 // opposite condition code to our original choice. 3866 if (CC == ISD::SETULE || CC == ISD::SETULT || CC == ISD::SETUGE || 3867 CC == ISD::SETUGT) { 3868 swpCmpOps = !swpCmpOps; 3869 swpVselOps = !swpVselOps; 3870 CondCode = CondCode == ARMCC::GT ? ARMCC::GE : ARMCC::GT; 3871 } 3872 3873 // 'ordered' is 'anything but unordered', so use the VS condition code and 3874 // swap the VSEL operands. 3875 if (CC == ISD::SETO) { 3876 CondCode = ARMCC::VS; 3877 swpVselOps = true; 3878 } 3879 3880 // 'unordered or not equal' is 'anything but equal', so use the EQ condition 3881 // code and swap the VSEL operands. 3882 if (CC == ISD::SETUNE) { 3883 CondCode = ARMCC::EQ; 3884 swpVselOps = true; 3885 } 3886 } 3887 3888 SDValue ARMTargetLowering::getCMOV(const SDLoc &dl, EVT VT, SDValue FalseVal, 3889 SDValue TrueVal, SDValue ARMcc, SDValue CCR, 3890 SDValue Cmp, SelectionDAG &DAG) const { 3891 if (Subtarget->isFPOnlySP() && VT == MVT::f64) { 3892 FalseVal = DAG.getNode(ARMISD::VMOVRRD, dl, 3893 DAG.getVTList(MVT::i32, MVT::i32), FalseVal); 3894 TrueVal = DAG.getNode(ARMISD::VMOVRRD, dl, 3895 DAG.getVTList(MVT::i32, MVT::i32), TrueVal); 3896 3897 SDValue TrueLow = TrueVal.getValue(0); 3898 SDValue TrueHigh = TrueVal.getValue(1); 3899 SDValue FalseLow = FalseVal.getValue(0); 3900 SDValue FalseHigh = FalseVal.getValue(1); 3901 3902 SDValue Low = DAG.getNode(ARMISD::CMOV, dl, MVT::i32, FalseLow, TrueLow, 3903 ARMcc, CCR, Cmp); 3904 SDValue High = DAG.getNode(ARMISD::CMOV, dl, MVT::i32, FalseHigh, TrueHigh, 3905 ARMcc, CCR, duplicateCmp(Cmp, DAG)); 3906 3907 return DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Low, High); 3908 } else { 3909 return DAG.getNode(ARMISD::CMOV, dl, VT, FalseVal, TrueVal, ARMcc, CCR, 3910 Cmp); 3911 } 3912 } 3913 3914 static bool isGTorGE(ISD::CondCode CC) { 3915 return CC == ISD::SETGT || CC == ISD::SETGE; 3916 } 3917 3918 static bool isLTorLE(ISD::CondCode CC) { 3919 return CC == ISD::SETLT || CC == ISD::SETLE; 3920 } 3921 3922 // See if a conditional (LHS CC RHS ? TrueVal : FalseVal) is lower-saturating. 3923 // All of these conditions (and their <= and >= counterparts) will do: 3924 // x < k ? k : x 3925 // x > k ? x : k 3926 // k < x ? x : k 3927 // k > x ? k : x 3928 static bool isLowerSaturate(const SDValue LHS, const SDValue RHS, 3929 const SDValue TrueVal, const SDValue FalseVal, 3930 const ISD::CondCode CC, const SDValue K) { 3931 return (isGTorGE(CC) && 3932 ((K == LHS && K == TrueVal) || (K == RHS && K == FalseVal))) || 3933 (isLTorLE(CC) && 3934 ((K == RHS && K == TrueVal) || (K == LHS && K == FalseVal))); 3935 } 3936 3937 // Similar to isLowerSaturate(), but checks for upper-saturating conditions. 3938 static bool isUpperSaturate(const SDValue LHS, const SDValue RHS, 3939 const SDValue TrueVal, const SDValue FalseVal, 3940 const ISD::CondCode CC, const SDValue K) { 3941 return (isGTorGE(CC) && 3942 ((K == RHS && K == TrueVal) || (K == LHS && K == FalseVal))) || 3943 (isLTorLE(CC) && 3944 ((K == LHS && K == TrueVal) || (K == RHS && K == FalseVal))); 3945 } 3946 3947 // Check if two chained conditionals could be converted into SSAT. 3948 // 3949 // SSAT can replace a set of two conditional selectors that bound a number to an 3950 // interval of type [k, ~k] when k + 1 is a power of 2. Here are some examples: 3951 // 3952 // x < -k ? -k : (x > k ? k : x) 3953 // x < -k ? -k : (x < k ? x : k) 3954 // x > -k ? (x > k ? k : x) : -k 3955 // x < k ? (x < -k ? -k : x) : k 3956 // etc. 3957 // 3958 // It returns true if the conversion can be done, false otherwise. 3959 // Additionally, the variable is returned in parameter V and the constant in K. 3960 static bool isSaturatingConditional(const SDValue &Op, SDValue &V, 3961 uint64_t &K) { 3962 3963 SDValue LHS1 = Op.getOperand(0); 3964 SDValue RHS1 = Op.getOperand(1); 3965 SDValue TrueVal1 = Op.getOperand(2); 3966 SDValue FalseVal1 = Op.getOperand(3); 3967 ISD::CondCode CC1 = cast<CondCodeSDNode>(Op.getOperand(4))->get(); 3968 3969 const SDValue Op2 = isa<ConstantSDNode>(TrueVal1) ? FalseVal1 : TrueVal1; 3970 if (Op2.getOpcode() != ISD::SELECT_CC) 3971 return false; 3972 3973 SDValue LHS2 = Op2.getOperand(0); 3974 SDValue RHS2 = Op2.getOperand(1); 3975 SDValue TrueVal2 = Op2.getOperand(2); 3976 SDValue FalseVal2 = Op2.getOperand(3); 3977 ISD::CondCode CC2 = cast<CondCodeSDNode>(Op2.getOperand(4))->get(); 3978 3979 // Find out which are the constants and which are the variables 3980 // in each conditional 3981 SDValue *K1 = isa<ConstantSDNode>(LHS1) ? &LHS1 : isa<ConstantSDNode>(RHS1) 3982 ? &RHS1 3983 : NULL; 3984 SDValue *K2 = isa<ConstantSDNode>(LHS2) ? &LHS2 : isa<ConstantSDNode>(RHS2) 3985 ? &RHS2 3986 : NULL; 3987 SDValue K2Tmp = isa<ConstantSDNode>(TrueVal2) ? TrueVal2 : FalseVal2; 3988 SDValue V1Tmp = (K1 && *K1 == LHS1) ? RHS1 : LHS1; 3989 SDValue V2Tmp = (K2 && *K2 == LHS2) ? RHS2 : LHS2; 3990 SDValue V2 = (K2Tmp == TrueVal2) ? FalseVal2 : TrueVal2; 3991 3992 // We must detect cases where the original operations worked with 16- or 3993 // 8-bit values. In such case, V2Tmp != V2 because the comparison operations 3994 // must work with sign-extended values but the select operations return 3995 // the original non-extended value. 3996 SDValue V2TmpReg = V2Tmp; 3997 if (V2Tmp->getOpcode() == ISD::SIGN_EXTEND_INREG) 3998 V2TmpReg = V2Tmp->getOperand(0); 3999 4000 // Check that the registers and the constants have the correct values 4001 // in both conditionals 4002 if (!K1 || !K2 || *K1 == Op2 || *K2 != K2Tmp || V1Tmp != V2Tmp || 4003 V2TmpReg != V2) 4004 return false; 4005 4006 // Figure out which conditional is saturating the lower/upper bound. 4007 const SDValue *LowerCheckOp = 4008 isLowerSaturate(LHS1, RHS1, TrueVal1, FalseVal1, CC1, *K1) 4009 ? &Op 4010 : isLowerSaturate(LHS2, RHS2, TrueVal2, FalseVal2, CC2, *K2) ? &Op2 4011 : NULL; 4012 const SDValue *UpperCheckOp = 4013 isUpperSaturate(LHS1, RHS1, TrueVal1, FalseVal1, CC1, *K1) 4014 ? &Op 4015 : isUpperSaturate(LHS2, RHS2, TrueVal2, FalseVal2, CC2, *K2) ? &Op2 4016 : NULL; 4017 4018 if (!UpperCheckOp || !LowerCheckOp || LowerCheckOp == UpperCheckOp) 4019 return false; 4020 4021 // Check that the constant in the lower-bound check is 4022 // the opposite of the constant in the upper-bound check 4023 // in 1's complement. 4024 int64_t Val1 = cast<ConstantSDNode>(*K1)->getSExtValue(); 4025 int64_t Val2 = cast<ConstantSDNode>(*K2)->getSExtValue(); 4026 int64_t PosVal = std::max(Val1, Val2); 4027 4028 if (((Val1 > Val2 && UpperCheckOp == &Op) || 4029 (Val1 < Val2 && UpperCheckOp == &Op2)) && 4030 Val1 == ~Val2 && isPowerOf2_64(PosVal + 1)) { 4031 4032 V = V2; 4033 K = (uint64_t)PosVal; // At this point, PosVal is guaranteed to be positive 4034 return true; 4035 } 4036 4037 return false; 4038 } 4039 4040 SDValue ARMTargetLowering::LowerSELECT_CC(SDValue Op, SelectionDAG &DAG) const { 4041 4042 EVT VT = Op.getValueType(); 4043 SDLoc dl(Op); 4044 4045 // Try to convert two saturating conditional selects into a single SSAT 4046 SDValue SatValue; 4047 uint64_t SatConstant; 4048 if (((!Subtarget->isThumb() && Subtarget->hasV6Ops()) || Subtarget->isThumb2()) && 4049 isSaturatingConditional(Op, SatValue, SatConstant)) 4050 return DAG.getNode(ARMISD::SSAT, dl, VT, SatValue, 4051 DAG.getConstant(countTrailingOnes(SatConstant), dl, VT)); 4052 4053 SDValue LHS = Op.getOperand(0); 4054 SDValue RHS = Op.getOperand(1); 4055 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(4))->get(); 4056 SDValue TrueVal = Op.getOperand(2); 4057 SDValue FalseVal = Op.getOperand(3); 4058 4059 if (Subtarget->isFPOnlySP() && LHS.getValueType() == MVT::f64) { 4060 DAG.getTargetLoweringInfo().softenSetCCOperands(DAG, MVT::f64, LHS, RHS, CC, 4061 dl); 4062 4063 // If softenSetCCOperands only returned one value, we should compare it to 4064 // zero. 4065 if (!RHS.getNode()) { 4066 RHS = DAG.getConstant(0, dl, LHS.getValueType()); 4067 CC = ISD::SETNE; 4068 } 4069 } 4070 4071 if (LHS.getValueType() == MVT::i32) { 4072 // Try to generate VSEL on ARMv8. 4073 // The VSEL instruction can't use all the usual ARM condition 4074 // codes: it only has two bits to select the condition code, so it's 4075 // constrained to use only GE, GT, VS and EQ. 4076 // 4077 // To implement all the various ISD::SETXXX opcodes, we sometimes need to 4078 // swap the operands of the previous compare instruction (effectively 4079 // inverting the compare condition, swapping 'less' and 'greater') and 4080 // sometimes need to swap the operands to the VSEL (which inverts the 4081 // condition in the sense of firing whenever the previous condition didn't) 4082 if (Subtarget->hasFPARMv8() && (TrueVal.getValueType() == MVT::f32 || 4083 TrueVal.getValueType() == MVT::f64)) { 4084 ARMCC::CondCodes CondCode = IntCCToARMCC(CC); 4085 if (CondCode == ARMCC::LT || CondCode == ARMCC::LE || 4086 CondCode == ARMCC::VC || CondCode == ARMCC::NE) { 4087 CC = ISD::getSetCCInverse(CC, true); 4088 std::swap(TrueVal, FalseVal); 4089 } 4090 } 4091 4092 SDValue ARMcc; 4093 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32); 4094 SDValue Cmp = getARMCmp(LHS, RHS, CC, ARMcc, DAG, dl); 4095 return getCMOV(dl, VT, FalseVal, TrueVal, ARMcc, CCR, Cmp, DAG); 4096 } 4097 4098 ARMCC::CondCodes CondCode, CondCode2; 4099 FPCCToARMCC(CC, CondCode, CondCode2); 4100 4101 // Try to generate VMAXNM/VMINNM on ARMv8. 4102 if (Subtarget->hasFPARMv8() && (TrueVal.getValueType() == MVT::f32 || 4103 TrueVal.getValueType() == MVT::f64)) { 4104 bool swpCmpOps = false; 4105 bool swpVselOps = false; 4106 checkVSELConstraints(CC, CondCode, swpCmpOps, swpVselOps); 4107 4108 if (CondCode == ARMCC::GT || CondCode == ARMCC::GE || 4109 CondCode == ARMCC::VS || CondCode == ARMCC::EQ) { 4110 if (swpCmpOps) 4111 std::swap(LHS, RHS); 4112 if (swpVselOps) 4113 std::swap(TrueVal, FalseVal); 4114 } 4115 } 4116 4117 SDValue ARMcc = DAG.getConstant(CondCode, dl, MVT::i32); 4118 SDValue Cmp = getVFPCmp(LHS, RHS, DAG, dl); 4119 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32); 4120 SDValue Result = getCMOV(dl, VT, FalseVal, TrueVal, ARMcc, CCR, Cmp, DAG); 4121 if (CondCode2 != ARMCC::AL) { 4122 SDValue ARMcc2 = DAG.getConstant(CondCode2, dl, MVT::i32); 4123 // FIXME: Needs another CMP because flag can have but one use. 4124 SDValue Cmp2 = getVFPCmp(LHS, RHS, DAG, dl); 4125 Result = getCMOV(dl, VT, Result, TrueVal, ARMcc2, CCR, Cmp2, DAG); 4126 } 4127 return Result; 4128 } 4129 4130 /// canChangeToInt - Given the fp compare operand, return true if it is suitable 4131 /// to morph to an integer compare sequence. 4132 static bool canChangeToInt(SDValue Op, bool &SeenZero, 4133 const ARMSubtarget *Subtarget) { 4134 SDNode *N = Op.getNode(); 4135 if (!N->hasOneUse()) 4136 // Otherwise it requires moving the value from fp to integer registers. 4137 return false; 4138 if (!N->getNumValues()) 4139 return false; 4140 EVT VT = Op.getValueType(); 4141 if (VT != MVT::f32 && !Subtarget->isFPBrccSlow()) 4142 // f32 case is generally profitable. f64 case only makes sense when vcmpe + 4143 // vmrs are very slow, e.g. cortex-a8. 4144 return false; 4145 4146 if (isFloatingPointZero(Op)) { 4147 SeenZero = true; 4148 return true; 4149 } 4150 return ISD::isNormalLoad(N); 4151 } 4152 4153 static SDValue bitcastf32Toi32(SDValue Op, SelectionDAG &DAG) { 4154 if (isFloatingPointZero(Op)) 4155 return DAG.getConstant(0, SDLoc(Op), MVT::i32); 4156 4157 if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Op)) 4158 return DAG.getLoad(MVT::i32, SDLoc(Op), Ld->getChain(), Ld->getBasePtr(), 4159 Ld->getPointerInfo(), Ld->getAlignment(), 4160 Ld->getMemOperand()->getFlags()); 4161 4162 llvm_unreachable("Unknown VFP cmp argument!"); 4163 } 4164 4165 static void expandf64Toi32(SDValue Op, SelectionDAG &DAG, 4166 SDValue &RetVal1, SDValue &RetVal2) { 4167 SDLoc dl(Op); 4168 4169 if (isFloatingPointZero(Op)) { 4170 RetVal1 = DAG.getConstant(0, dl, MVT::i32); 4171 RetVal2 = DAG.getConstant(0, dl, MVT::i32); 4172 return; 4173 } 4174 4175 if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Op)) { 4176 SDValue Ptr = Ld->getBasePtr(); 4177 RetVal1 = 4178 DAG.getLoad(MVT::i32, dl, Ld->getChain(), Ptr, Ld->getPointerInfo(), 4179 Ld->getAlignment(), Ld->getMemOperand()->getFlags()); 4180 4181 EVT PtrType = Ptr.getValueType(); 4182 unsigned NewAlign = MinAlign(Ld->getAlignment(), 4); 4183 SDValue NewPtr = DAG.getNode(ISD::ADD, dl, 4184 PtrType, Ptr, DAG.getConstant(4, dl, PtrType)); 4185 RetVal2 = DAG.getLoad(MVT::i32, dl, Ld->getChain(), NewPtr, 4186 Ld->getPointerInfo().getWithOffset(4), NewAlign, 4187 Ld->getMemOperand()->getFlags()); 4188 return; 4189 } 4190 4191 llvm_unreachable("Unknown VFP cmp argument!"); 4192 } 4193 4194 /// OptimizeVFPBrcond - With -enable-unsafe-fp-math, it's legal to optimize some 4195 /// f32 and even f64 comparisons to integer ones. 4196 SDValue 4197 ARMTargetLowering::OptimizeVFPBrcond(SDValue Op, SelectionDAG &DAG) const { 4198 SDValue Chain = Op.getOperand(0); 4199 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(1))->get(); 4200 SDValue LHS = Op.getOperand(2); 4201 SDValue RHS = Op.getOperand(3); 4202 SDValue Dest = Op.getOperand(4); 4203 SDLoc dl(Op); 4204 4205 bool LHSSeenZero = false; 4206 bool LHSOk = canChangeToInt(LHS, LHSSeenZero, Subtarget); 4207 bool RHSSeenZero = false; 4208 bool RHSOk = canChangeToInt(RHS, RHSSeenZero, Subtarget); 4209 if (LHSOk && RHSOk && (LHSSeenZero || RHSSeenZero)) { 4210 // If unsafe fp math optimization is enabled and there are no other uses of 4211 // the CMP operands, and the condition code is EQ or NE, we can optimize it 4212 // to an integer comparison. 4213 if (CC == ISD::SETOEQ) 4214 CC = ISD::SETEQ; 4215 else if (CC == ISD::SETUNE) 4216 CC = ISD::SETNE; 4217 4218 SDValue Mask = DAG.getConstant(0x7fffffff, dl, MVT::i32); 4219 SDValue ARMcc; 4220 if (LHS.getValueType() == MVT::f32) { 4221 LHS = DAG.getNode(ISD::AND, dl, MVT::i32, 4222 bitcastf32Toi32(LHS, DAG), Mask); 4223 RHS = DAG.getNode(ISD::AND, dl, MVT::i32, 4224 bitcastf32Toi32(RHS, DAG), Mask); 4225 SDValue Cmp = getARMCmp(LHS, RHS, CC, ARMcc, DAG, dl); 4226 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32); 4227 return DAG.getNode(ARMISD::BRCOND, dl, MVT::Other, 4228 Chain, Dest, ARMcc, CCR, Cmp); 4229 } 4230 4231 SDValue LHS1, LHS2; 4232 SDValue RHS1, RHS2; 4233 expandf64Toi32(LHS, DAG, LHS1, LHS2); 4234 expandf64Toi32(RHS, DAG, RHS1, RHS2); 4235 LHS2 = DAG.getNode(ISD::AND, dl, MVT::i32, LHS2, Mask); 4236 RHS2 = DAG.getNode(ISD::AND, dl, MVT::i32, RHS2, Mask); 4237 ARMCC::CondCodes CondCode = IntCCToARMCC(CC); 4238 ARMcc = DAG.getConstant(CondCode, dl, MVT::i32); 4239 SDVTList VTList = DAG.getVTList(MVT::Other, MVT::Glue); 4240 SDValue Ops[] = { Chain, ARMcc, LHS1, LHS2, RHS1, RHS2, Dest }; 4241 return DAG.getNode(ARMISD::BCC_i64, dl, VTList, Ops); 4242 } 4243 4244 return SDValue(); 4245 } 4246 4247 SDValue ARMTargetLowering::LowerBR_CC(SDValue Op, SelectionDAG &DAG) const { 4248 SDValue Chain = Op.getOperand(0); 4249 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(1))->get(); 4250 SDValue LHS = Op.getOperand(2); 4251 SDValue RHS = Op.getOperand(3); 4252 SDValue Dest = Op.getOperand(4); 4253 SDLoc dl(Op); 4254 4255 if (Subtarget->isFPOnlySP() && LHS.getValueType() == MVT::f64) { 4256 DAG.getTargetLoweringInfo().softenSetCCOperands(DAG, MVT::f64, LHS, RHS, CC, 4257 dl); 4258 4259 // If softenSetCCOperands only returned one value, we should compare it to 4260 // zero. 4261 if (!RHS.getNode()) { 4262 RHS = DAG.getConstant(0, dl, LHS.getValueType()); 4263 CC = ISD::SETNE; 4264 } 4265 } 4266 4267 if (LHS.getValueType() == MVT::i32) { 4268 SDValue ARMcc; 4269 SDValue Cmp = getARMCmp(LHS, RHS, CC, ARMcc, DAG, dl); 4270 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32); 4271 return DAG.getNode(ARMISD::BRCOND, dl, MVT::Other, 4272 Chain, Dest, ARMcc, CCR, Cmp); 4273 } 4274 4275 assert(LHS.getValueType() == MVT::f32 || LHS.getValueType() == MVT::f64); 4276 4277 if (getTargetMachine().Options.UnsafeFPMath && 4278 (CC == ISD::SETEQ || CC == ISD::SETOEQ || 4279 CC == ISD::SETNE || CC == ISD::SETUNE)) { 4280 if (SDValue Result = OptimizeVFPBrcond(Op, DAG)) 4281 return Result; 4282 } 4283 4284 ARMCC::CondCodes CondCode, CondCode2; 4285 FPCCToARMCC(CC, CondCode, CondCode2); 4286 4287 SDValue ARMcc = DAG.getConstant(CondCode, dl, MVT::i32); 4288 SDValue Cmp = getVFPCmp(LHS, RHS, DAG, dl); 4289 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32); 4290 SDVTList VTList = DAG.getVTList(MVT::Other, MVT::Glue); 4291 SDValue Ops[] = { Chain, Dest, ARMcc, CCR, Cmp }; 4292 SDValue Res = DAG.getNode(ARMISD::BRCOND, dl, VTList, Ops); 4293 if (CondCode2 != ARMCC::AL) { 4294 ARMcc = DAG.getConstant(CondCode2, dl, MVT::i32); 4295 SDValue Ops[] = { Res, Dest, ARMcc, CCR, Res.getValue(1) }; 4296 Res = DAG.getNode(ARMISD::BRCOND, dl, VTList, Ops); 4297 } 4298 return Res; 4299 } 4300 4301 SDValue ARMTargetLowering::LowerBR_JT(SDValue Op, SelectionDAG &DAG) const { 4302 SDValue Chain = Op.getOperand(0); 4303 SDValue Table = Op.getOperand(1); 4304 SDValue Index = Op.getOperand(2); 4305 SDLoc dl(Op); 4306 4307 EVT PTy = getPointerTy(DAG.getDataLayout()); 4308 JumpTableSDNode *JT = cast<JumpTableSDNode>(Table); 4309 SDValue JTI = DAG.getTargetJumpTable(JT->getIndex(), PTy); 4310 Table = DAG.getNode(ARMISD::WrapperJT, dl, MVT::i32, JTI); 4311 Index = DAG.getNode(ISD::MUL, dl, PTy, Index, DAG.getConstant(4, dl, PTy)); 4312 SDValue Addr = DAG.getNode(ISD::ADD, dl, PTy, Index, Table); 4313 if (Subtarget->isThumb2()) { 4314 // Thumb2 uses a two-level jump. That is, it jumps into the jump table 4315 // which does another jump to the destination. This also makes it easier 4316 // to translate it to TBB / TBH later. 4317 // FIXME: This might not work if the function is extremely large. 4318 return DAG.getNode(ARMISD::BR2_JT, dl, MVT::Other, Chain, 4319 Addr, Op.getOperand(2), JTI); 4320 } 4321 if (isPositionIndependent() || Subtarget->isROPI()) { 4322 Addr = 4323 DAG.getLoad((EVT)MVT::i32, dl, Chain, Addr, 4324 MachinePointerInfo::getJumpTable(DAG.getMachineFunction())); 4325 Chain = Addr.getValue(1); 4326 Addr = DAG.getNode(ISD::ADD, dl, PTy, Addr, Table); 4327 return DAG.getNode(ARMISD::BR_JT, dl, MVT::Other, Chain, Addr, JTI); 4328 } else { 4329 Addr = 4330 DAG.getLoad(PTy, dl, Chain, Addr, 4331 MachinePointerInfo::getJumpTable(DAG.getMachineFunction())); 4332 Chain = Addr.getValue(1); 4333 return DAG.getNode(ARMISD::BR_JT, dl, MVT::Other, Chain, Addr, JTI); 4334 } 4335 } 4336 4337 static SDValue LowerVectorFP_TO_INT(SDValue Op, SelectionDAG &DAG) { 4338 EVT VT = Op.getValueType(); 4339 SDLoc dl(Op); 4340 4341 if (Op.getValueType().getVectorElementType() == MVT::i32) { 4342 if (Op.getOperand(0).getValueType().getVectorElementType() == MVT::f32) 4343 return Op; 4344 return DAG.UnrollVectorOp(Op.getNode()); 4345 } 4346 4347 assert(Op.getOperand(0).getValueType() == MVT::v4f32 && 4348 "Invalid type for custom lowering!"); 4349 if (VT != MVT::v4i16) 4350 return DAG.UnrollVectorOp(Op.getNode()); 4351 4352 Op = DAG.getNode(Op.getOpcode(), dl, MVT::v4i32, Op.getOperand(0)); 4353 return DAG.getNode(ISD::TRUNCATE, dl, VT, Op); 4354 } 4355 4356 SDValue ARMTargetLowering::LowerFP_TO_INT(SDValue Op, SelectionDAG &DAG) const { 4357 EVT VT = Op.getValueType(); 4358 if (VT.isVector()) 4359 return LowerVectorFP_TO_INT(Op, DAG); 4360 if (Subtarget->isFPOnlySP() && Op.getOperand(0).getValueType() == MVT::f64) { 4361 RTLIB::Libcall LC; 4362 if (Op.getOpcode() == ISD::FP_TO_SINT) 4363 LC = RTLIB::getFPTOSINT(Op.getOperand(0).getValueType(), 4364 Op.getValueType()); 4365 else 4366 LC = RTLIB::getFPTOUINT(Op.getOperand(0).getValueType(), 4367 Op.getValueType()); 4368 return makeLibCall(DAG, LC, Op.getValueType(), Op.getOperand(0), 4369 /*isSigned*/ false, SDLoc(Op)).first; 4370 } 4371 4372 return Op; 4373 } 4374 4375 static SDValue LowerVectorINT_TO_FP(SDValue Op, SelectionDAG &DAG) { 4376 EVT VT = Op.getValueType(); 4377 SDLoc dl(Op); 4378 4379 if (Op.getOperand(0).getValueType().getVectorElementType() == MVT::i32) { 4380 if (VT.getVectorElementType() == MVT::f32) 4381 return Op; 4382 return DAG.UnrollVectorOp(Op.getNode()); 4383 } 4384 4385 assert(Op.getOperand(0).getValueType() == MVT::v4i16 && 4386 "Invalid type for custom lowering!"); 4387 if (VT != MVT::v4f32) 4388 return DAG.UnrollVectorOp(Op.getNode()); 4389 4390 unsigned CastOpc; 4391 unsigned Opc; 4392 switch (Op.getOpcode()) { 4393 default: llvm_unreachable("Invalid opcode!"); 4394 case ISD::SINT_TO_FP: 4395 CastOpc = ISD::SIGN_EXTEND; 4396 Opc = ISD::SINT_TO_FP; 4397 break; 4398 case ISD::UINT_TO_FP: 4399 CastOpc = ISD::ZERO_EXTEND; 4400 Opc = ISD::UINT_TO_FP; 4401 break; 4402 } 4403 4404 Op = DAG.getNode(CastOpc, dl, MVT::v4i32, Op.getOperand(0)); 4405 return DAG.getNode(Opc, dl, VT, Op); 4406 } 4407 4408 SDValue ARMTargetLowering::LowerINT_TO_FP(SDValue Op, SelectionDAG &DAG) const { 4409 EVT VT = Op.getValueType(); 4410 if (VT.isVector()) 4411 return LowerVectorINT_TO_FP(Op, DAG); 4412 if (Subtarget->isFPOnlySP() && Op.getValueType() == MVT::f64) { 4413 RTLIB::Libcall LC; 4414 if (Op.getOpcode() == ISD::SINT_TO_FP) 4415 LC = RTLIB::getSINTTOFP(Op.getOperand(0).getValueType(), 4416 Op.getValueType()); 4417 else 4418 LC = RTLIB::getUINTTOFP(Op.getOperand(0).getValueType(), 4419 Op.getValueType()); 4420 return makeLibCall(DAG, LC, Op.getValueType(), Op.getOperand(0), 4421 /*isSigned*/ false, SDLoc(Op)).first; 4422 } 4423 4424 return Op; 4425 } 4426 4427 SDValue ARMTargetLowering::LowerFCOPYSIGN(SDValue Op, SelectionDAG &DAG) const { 4428 // Implement fcopysign with a fabs and a conditional fneg. 4429 SDValue Tmp0 = Op.getOperand(0); 4430 SDValue Tmp1 = Op.getOperand(1); 4431 SDLoc dl(Op); 4432 EVT VT = Op.getValueType(); 4433 EVT SrcVT = Tmp1.getValueType(); 4434 bool InGPR = Tmp0.getOpcode() == ISD::BITCAST || 4435 Tmp0.getOpcode() == ARMISD::VMOVDRR; 4436 bool UseNEON = !InGPR && Subtarget->hasNEON(); 4437 4438 if (UseNEON) { 4439 // Use VBSL to copy the sign bit. 4440 unsigned EncodedVal = ARM_AM::createNEONModImm(0x6, 0x80); 4441 SDValue Mask = DAG.getNode(ARMISD::VMOVIMM, dl, MVT::v2i32, 4442 DAG.getTargetConstant(EncodedVal, dl, MVT::i32)); 4443 EVT OpVT = (VT == MVT::f32) ? MVT::v2i32 : MVT::v1i64; 4444 if (VT == MVT::f64) 4445 Mask = DAG.getNode(ARMISD::VSHL, dl, OpVT, 4446 DAG.getNode(ISD::BITCAST, dl, OpVT, Mask), 4447 DAG.getConstant(32, dl, MVT::i32)); 4448 else /*if (VT == MVT::f32)*/ 4449 Tmp0 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f32, Tmp0); 4450 if (SrcVT == MVT::f32) { 4451 Tmp1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f32, Tmp1); 4452 if (VT == MVT::f64) 4453 Tmp1 = DAG.getNode(ARMISD::VSHL, dl, OpVT, 4454 DAG.getNode(ISD::BITCAST, dl, OpVT, Tmp1), 4455 DAG.getConstant(32, dl, MVT::i32)); 4456 } else if (VT == MVT::f32) 4457 Tmp1 = DAG.getNode(ARMISD::VSHRu, dl, MVT::v1i64, 4458 DAG.getNode(ISD::BITCAST, dl, MVT::v1i64, Tmp1), 4459 DAG.getConstant(32, dl, MVT::i32)); 4460 Tmp0 = DAG.getNode(ISD::BITCAST, dl, OpVT, Tmp0); 4461 Tmp1 = DAG.getNode(ISD::BITCAST, dl, OpVT, Tmp1); 4462 4463 SDValue AllOnes = DAG.getTargetConstant(ARM_AM::createNEONModImm(0xe, 0xff), 4464 dl, MVT::i32); 4465 AllOnes = DAG.getNode(ARMISD::VMOVIMM, dl, MVT::v8i8, AllOnes); 4466 SDValue MaskNot = DAG.getNode(ISD::XOR, dl, OpVT, Mask, 4467 DAG.getNode(ISD::BITCAST, dl, OpVT, AllOnes)); 4468 4469 SDValue Res = DAG.getNode(ISD::OR, dl, OpVT, 4470 DAG.getNode(ISD::AND, dl, OpVT, Tmp1, Mask), 4471 DAG.getNode(ISD::AND, dl, OpVT, Tmp0, MaskNot)); 4472 if (VT == MVT::f32) { 4473 Res = DAG.getNode(ISD::BITCAST, dl, MVT::v2f32, Res); 4474 Res = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f32, Res, 4475 DAG.getConstant(0, dl, MVT::i32)); 4476 } else { 4477 Res = DAG.getNode(ISD::BITCAST, dl, MVT::f64, Res); 4478 } 4479 4480 return Res; 4481 } 4482 4483 // Bitcast operand 1 to i32. 4484 if (SrcVT == MVT::f64) 4485 Tmp1 = DAG.getNode(ARMISD::VMOVRRD, dl, DAG.getVTList(MVT::i32, MVT::i32), 4486 Tmp1).getValue(1); 4487 Tmp1 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Tmp1); 4488 4489 // Or in the signbit with integer operations. 4490 SDValue Mask1 = DAG.getConstant(0x80000000, dl, MVT::i32); 4491 SDValue Mask2 = DAG.getConstant(0x7fffffff, dl, MVT::i32); 4492 Tmp1 = DAG.getNode(ISD::AND, dl, MVT::i32, Tmp1, Mask1); 4493 if (VT == MVT::f32) { 4494 Tmp0 = DAG.getNode(ISD::AND, dl, MVT::i32, 4495 DAG.getNode(ISD::BITCAST, dl, MVT::i32, Tmp0), Mask2); 4496 return DAG.getNode(ISD::BITCAST, dl, MVT::f32, 4497 DAG.getNode(ISD::OR, dl, MVT::i32, Tmp0, Tmp1)); 4498 } 4499 4500 // f64: Or the high part with signbit and then combine two parts. 4501 Tmp0 = DAG.getNode(ARMISD::VMOVRRD, dl, DAG.getVTList(MVT::i32, MVT::i32), 4502 Tmp0); 4503 SDValue Lo = Tmp0.getValue(0); 4504 SDValue Hi = DAG.getNode(ISD::AND, dl, MVT::i32, Tmp0.getValue(1), Mask2); 4505 Hi = DAG.getNode(ISD::OR, dl, MVT::i32, Hi, Tmp1); 4506 return DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi); 4507 } 4508 4509 SDValue ARMTargetLowering::LowerRETURNADDR(SDValue Op, SelectionDAG &DAG) const{ 4510 MachineFunction &MF = DAG.getMachineFunction(); 4511 MachineFrameInfo &MFI = MF.getFrameInfo(); 4512 MFI.setReturnAddressIsTaken(true); 4513 4514 if (verifyReturnAddressArgumentIsConstant(Op, DAG)) 4515 return SDValue(); 4516 4517 EVT VT = Op.getValueType(); 4518 SDLoc dl(Op); 4519 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue(); 4520 if (Depth) { 4521 SDValue FrameAddr = LowerFRAMEADDR(Op, DAG); 4522 SDValue Offset = DAG.getConstant(4, dl, MVT::i32); 4523 return DAG.getLoad(VT, dl, DAG.getEntryNode(), 4524 DAG.getNode(ISD::ADD, dl, VT, FrameAddr, Offset), 4525 MachinePointerInfo()); 4526 } 4527 4528 // Return LR, which contains the return address. Mark it an implicit live-in. 4529 unsigned Reg = MF.addLiveIn(ARM::LR, getRegClassFor(MVT::i32)); 4530 return DAG.getCopyFromReg(DAG.getEntryNode(), dl, Reg, VT); 4531 } 4532 4533 SDValue ARMTargetLowering::LowerFRAMEADDR(SDValue Op, SelectionDAG &DAG) const { 4534 const ARMBaseRegisterInfo &ARI = 4535 *static_cast<const ARMBaseRegisterInfo*>(RegInfo); 4536 MachineFunction &MF = DAG.getMachineFunction(); 4537 MachineFrameInfo &MFI = MF.getFrameInfo(); 4538 MFI.setFrameAddressIsTaken(true); 4539 4540 EVT VT = Op.getValueType(); 4541 SDLoc dl(Op); // FIXME probably not meaningful 4542 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue(); 4543 unsigned FrameReg = ARI.getFrameRegister(MF); 4544 SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, VT); 4545 while (Depth--) 4546 FrameAddr = DAG.getLoad(VT, dl, DAG.getEntryNode(), FrameAddr, 4547 MachinePointerInfo()); 4548 return FrameAddr; 4549 } 4550 4551 // FIXME? Maybe this could be a TableGen attribute on some registers and 4552 // this table could be generated automatically from RegInfo. 4553 unsigned ARMTargetLowering::getRegisterByName(const char* RegName, EVT VT, 4554 SelectionDAG &DAG) const { 4555 unsigned Reg = StringSwitch<unsigned>(RegName) 4556 .Case("sp", ARM::SP) 4557 .Default(0); 4558 if (Reg) 4559 return Reg; 4560 report_fatal_error(Twine("Invalid register name \"" 4561 + StringRef(RegName) + "\".")); 4562 } 4563 4564 // Result is 64 bit value so split into two 32 bit values and return as a 4565 // pair of values. 4566 static void ExpandREAD_REGISTER(SDNode *N, SmallVectorImpl<SDValue> &Results, 4567 SelectionDAG &DAG) { 4568 SDLoc DL(N); 4569 4570 // This function is only supposed to be called for i64 type destination. 4571 assert(N->getValueType(0) == MVT::i64 4572 && "ExpandREAD_REGISTER called for non-i64 type result."); 4573 4574 SDValue Read = DAG.getNode(ISD::READ_REGISTER, DL, 4575 DAG.getVTList(MVT::i32, MVT::i32, MVT::Other), 4576 N->getOperand(0), 4577 N->getOperand(1)); 4578 4579 Results.push_back(DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, Read.getValue(0), 4580 Read.getValue(1))); 4581 Results.push_back(Read.getOperand(0)); 4582 } 4583 4584 /// \p BC is a bitcast that is about to be turned into a VMOVDRR. 4585 /// When \p DstVT, the destination type of \p BC, is on the vector 4586 /// register bank and the source of bitcast, \p Op, operates on the same bank, 4587 /// it might be possible to combine them, such that everything stays on the 4588 /// vector register bank. 4589 /// \p return The node that would replace \p BT, if the combine 4590 /// is possible. 4591 static SDValue CombineVMOVDRRCandidateWithVecOp(const SDNode *BC, 4592 SelectionDAG &DAG) { 4593 SDValue Op = BC->getOperand(0); 4594 EVT DstVT = BC->getValueType(0); 4595 4596 // The only vector instruction that can produce a scalar (remember, 4597 // since the bitcast was about to be turned into VMOVDRR, the source 4598 // type is i64) from a vector is EXTRACT_VECTOR_ELT. 4599 // Moreover, we can do this combine only if there is one use. 4600 // Finally, if the destination type is not a vector, there is not 4601 // much point on forcing everything on the vector bank. 4602 if (!DstVT.isVector() || Op.getOpcode() != ISD::EXTRACT_VECTOR_ELT || 4603 !Op.hasOneUse()) 4604 return SDValue(); 4605 4606 // If the index is not constant, we will introduce an additional 4607 // multiply that will stick. 4608 // Give up in that case. 4609 ConstantSDNode *Index = dyn_cast<ConstantSDNode>(Op.getOperand(1)); 4610 if (!Index) 4611 return SDValue(); 4612 unsigned DstNumElt = DstVT.getVectorNumElements(); 4613 4614 // Compute the new index. 4615 const APInt &APIntIndex = Index->getAPIntValue(); 4616 APInt NewIndex(APIntIndex.getBitWidth(), DstNumElt); 4617 NewIndex *= APIntIndex; 4618 // Check if the new constant index fits into i32. 4619 if (NewIndex.getBitWidth() > 32) 4620 return SDValue(); 4621 4622 // vMTy bitcast(i64 extractelt vNi64 src, i32 index) -> 4623 // vMTy extractsubvector vNxMTy (bitcast vNi64 src), i32 index*M) 4624 SDLoc dl(Op); 4625 SDValue ExtractSrc = Op.getOperand(0); 4626 EVT VecVT = EVT::getVectorVT( 4627 *DAG.getContext(), DstVT.getScalarType(), 4628 ExtractSrc.getValueType().getVectorNumElements() * DstNumElt); 4629 SDValue BitCast = DAG.getNode(ISD::BITCAST, dl, VecVT, ExtractSrc); 4630 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DstVT, BitCast, 4631 DAG.getConstant(NewIndex.getZExtValue(), dl, MVT::i32)); 4632 } 4633 4634 /// ExpandBITCAST - If the target supports VFP, this function is called to 4635 /// expand a bit convert where either the source or destination type is i64 to 4636 /// use a VMOVDRR or VMOVRRD node. This should not be done when the non-i64 4637 /// operand type is illegal (e.g., v2f32 for a target that doesn't support 4638 /// vectors), since the legalizer won't know what to do with that. 4639 static SDValue ExpandBITCAST(SDNode *N, SelectionDAG &DAG) { 4640 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 4641 SDLoc dl(N); 4642 SDValue Op = N->getOperand(0); 4643 4644 // This function is only supposed to be called for i64 types, either as the 4645 // source or destination of the bit convert. 4646 EVT SrcVT = Op.getValueType(); 4647 EVT DstVT = N->getValueType(0); 4648 assert((SrcVT == MVT::i64 || DstVT == MVT::i64) && 4649 "ExpandBITCAST called for non-i64 type"); 4650 4651 // Turn i64->f64 into VMOVDRR. 4652 if (SrcVT == MVT::i64 && TLI.isTypeLegal(DstVT)) { 4653 // Do not force values to GPRs (this is what VMOVDRR does for the inputs) 4654 // if we can combine the bitcast with its source. 4655 if (SDValue Val = CombineVMOVDRRCandidateWithVecOp(N, DAG)) 4656 return Val; 4657 4658 SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, Op, 4659 DAG.getConstant(0, dl, MVT::i32)); 4660 SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, Op, 4661 DAG.getConstant(1, dl, MVT::i32)); 4662 return DAG.getNode(ISD::BITCAST, dl, DstVT, 4663 DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi)); 4664 } 4665 4666 // Turn f64->i64 into VMOVRRD. 4667 if (DstVT == MVT::i64 && TLI.isTypeLegal(SrcVT)) { 4668 SDValue Cvt; 4669 if (DAG.getDataLayout().isBigEndian() && SrcVT.isVector() && 4670 SrcVT.getVectorNumElements() > 1) 4671 Cvt = DAG.getNode(ARMISD::VMOVRRD, dl, 4672 DAG.getVTList(MVT::i32, MVT::i32), 4673 DAG.getNode(ARMISD::VREV64, dl, SrcVT, Op)); 4674 else 4675 Cvt = DAG.getNode(ARMISD::VMOVRRD, dl, 4676 DAG.getVTList(MVT::i32, MVT::i32), Op); 4677 // Merge the pieces into a single i64 value. 4678 return DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Cvt, Cvt.getValue(1)); 4679 } 4680 4681 return SDValue(); 4682 } 4683 4684 /// getZeroVector - Returns a vector of specified type with all zero elements. 4685 /// Zero vectors are used to represent vector negation and in those cases 4686 /// will be implemented with the NEON VNEG instruction. However, VNEG does 4687 /// not support i64 elements, so sometimes the zero vectors will need to be 4688 /// explicitly constructed. Regardless, use a canonical VMOV to create the 4689 /// zero vector. 4690 static SDValue getZeroVector(EVT VT, SelectionDAG &DAG, const SDLoc &dl) { 4691 assert(VT.isVector() && "Expected a vector type"); 4692 // The canonical modified immediate encoding of a zero vector is....0! 4693 SDValue EncodedVal = DAG.getTargetConstant(0, dl, MVT::i32); 4694 EVT VmovVT = VT.is128BitVector() ? MVT::v4i32 : MVT::v2i32; 4695 SDValue Vmov = DAG.getNode(ARMISD::VMOVIMM, dl, VmovVT, EncodedVal); 4696 return DAG.getNode(ISD::BITCAST, dl, VT, Vmov); 4697 } 4698 4699 /// LowerShiftRightParts - Lower SRA_PARTS, which returns two 4700 /// i32 values and take a 2 x i32 value to shift plus a shift amount. 4701 SDValue ARMTargetLowering::LowerShiftRightParts(SDValue Op, 4702 SelectionDAG &DAG) const { 4703 assert(Op.getNumOperands() == 3 && "Not a double-shift!"); 4704 EVT VT = Op.getValueType(); 4705 unsigned VTBits = VT.getSizeInBits(); 4706 SDLoc dl(Op); 4707 SDValue ShOpLo = Op.getOperand(0); 4708 SDValue ShOpHi = Op.getOperand(1); 4709 SDValue ShAmt = Op.getOperand(2); 4710 SDValue ARMcc; 4711 unsigned Opc = (Op.getOpcode() == ISD::SRA_PARTS) ? ISD::SRA : ISD::SRL; 4712 4713 assert(Op.getOpcode() == ISD::SRA_PARTS || Op.getOpcode() == ISD::SRL_PARTS); 4714 4715 SDValue RevShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32, 4716 DAG.getConstant(VTBits, dl, MVT::i32), ShAmt); 4717 SDValue Tmp1 = DAG.getNode(ISD::SRL, dl, VT, ShOpLo, ShAmt); 4718 SDValue ExtraShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32, ShAmt, 4719 DAG.getConstant(VTBits, dl, MVT::i32)); 4720 SDValue Tmp2 = DAG.getNode(ISD::SHL, dl, VT, ShOpHi, RevShAmt); 4721 SDValue FalseVal = DAG.getNode(ISD::OR, dl, VT, Tmp1, Tmp2); 4722 SDValue TrueVal = DAG.getNode(Opc, dl, VT, ShOpHi, ExtraShAmt); 4723 4724 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32); 4725 SDValue Cmp = getARMCmp(ExtraShAmt, DAG.getConstant(0, dl, MVT::i32), 4726 ISD::SETGE, ARMcc, DAG, dl); 4727 SDValue Hi = DAG.getNode(Opc, dl, VT, ShOpHi, ShAmt); 4728 SDValue Lo = DAG.getNode(ARMISD::CMOV, dl, VT, FalseVal, TrueVal, ARMcc, 4729 CCR, Cmp); 4730 4731 SDValue Ops[2] = { Lo, Hi }; 4732 return DAG.getMergeValues(Ops, dl); 4733 } 4734 4735 /// LowerShiftLeftParts - Lower SHL_PARTS, which returns two 4736 /// i32 values and take a 2 x i32 value to shift plus a shift amount. 4737 SDValue ARMTargetLowering::LowerShiftLeftParts(SDValue Op, 4738 SelectionDAG &DAG) const { 4739 assert(Op.getNumOperands() == 3 && "Not a double-shift!"); 4740 EVT VT = Op.getValueType(); 4741 unsigned VTBits = VT.getSizeInBits(); 4742 SDLoc dl(Op); 4743 SDValue ShOpLo = Op.getOperand(0); 4744 SDValue ShOpHi = Op.getOperand(1); 4745 SDValue ShAmt = Op.getOperand(2); 4746 SDValue ARMcc; 4747 4748 assert(Op.getOpcode() == ISD::SHL_PARTS); 4749 SDValue RevShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32, 4750 DAG.getConstant(VTBits, dl, MVT::i32), ShAmt); 4751 SDValue Tmp1 = DAG.getNode(ISD::SRL, dl, VT, ShOpLo, RevShAmt); 4752 SDValue ExtraShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32, ShAmt, 4753 DAG.getConstant(VTBits, dl, MVT::i32)); 4754 SDValue Tmp2 = DAG.getNode(ISD::SHL, dl, VT, ShOpHi, ShAmt); 4755 SDValue Tmp3 = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ExtraShAmt); 4756 4757 SDValue FalseVal = DAG.getNode(ISD::OR, dl, VT, Tmp1, Tmp2); 4758 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32); 4759 SDValue Cmp = getARMCmp(ExtraShAmt, DAG.getConstant(0, dl, MVT::i32), 4760 ISD::SETGE, ARMcc, DAG, dl); 4761 SDValue Lo = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ShAmt); 4762 SDValue Hi = DAG.getNode(ARMISD::CMOV, dl, VT, FalseVal, Tmp3, ARMcc, 4763 CCR, Cmp); 4764 4765 SDValue Ops[2] = { Lo, Hi }; 4766 return DAG.getMergeValues(Ops, dl); 4767 } 4768 4769 SDValue ARMTargetLowering::LowerFLT_ROUNDS_(SDValue Op, 4770 SelectionDAG &DAG) const { 4771 // The rounding mode is in bits 23:22 of the FPSCR. 4772 // The ARM rounding mode value to FLT_ROUNDS mapping is 0->1, 1->2, 2->3, 3->0 4773 // The formula we use to implement this is (((FPSCR + 1 << 22) >> 22) & 3) 4774 // so that the shift + and get folded into a bitfield extract. 4775 SDLoc dl(Op); 4776 SDValue FPSCR = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::i32, 4777 DAG.getConstant(Intrinsic::arm_get_fpscr, dl, 4778 MVT::i32)); 4779 SDValue FltRounds = DAG.getNode(ISD::ADD, dl, MVT::i32, FPSCR, 4780 DAG.getConstant(1U << 22, dl, MVT::i32)); 4781 SDValue RMODE = DAG.getNode(ISD::SRL, dl, MVT::i32, FltRounds, 4782 DAG.getConstant(22, dl, MVT::i32)); 4783 return DAG.getNode(ISD::AND, dl, MVT::i32, RMODE, 4784 DAG.getConstant(3, dl, MVT::i32)); 4785 } 4786 4787 static SDValue LowerCTTZ(SDNode *N, SelectionDAG &DAG, 4788 const ARMSubtarget *ST) { 4789 SDLoc dl(N); 4790 EVT VT = N->getValueType(0); 4791 if (VT.isVector()) { 4792 assert(ST->hasNEON()); 4793 4794 // Compute the least significant set bit: LSB = X & -X 4795 SDValue X = N->getOperand(0); 4796 SDValue NX = DAG.getNode(ISD::SUB, dl, VT, getZeroVector(VT, DAG, dl), X); 4797 SDValue LSB = DAG.getNode(ISD::AND, dl, VT, X, NX); 4798 4799 EVT ElemTy = VT.getVectorElementType(); 4800 4801 if (ElemTy == MVT::i8) { 4802 // Compute with: cttz(x) = ctpop(lsb - 1) 4803 SDValue One = DAG.getNode(ARMISD::VMOVIMM, dl, VT, 4804 DAG.getTargetConstant(1, dl, ElemTy)); 4805 SDValue Bits = DAG.getNode(ISD::SUB, dl, VT, LSB, One); 4806 return DAG.getNode(ISD::CTPOP, dl, VT, Bits); 4807 } 4808 4809 if ((ElemTy == MVT::i16 || ElemTy == MVT::i32) && 4810 (N->getOpcode() == ISD::CTTZ_ZERO_UNDEF)) { 4811 // Compute with: cttz(x) = (width - 1) - ctlz(lsb), if x != 0 4812 unsigned NumBits = ElemTy.getSizeInBits(); 4813 SDValue WidthMinus1 = 4814 DAG.getNode(ARMISD::VMOVIMM, dl, VT, 4815 DAG.getTargetConstant(NumBits - 1, dl, ElemTy)); 4816 SDValue CTLZ = DAG.getNode(ISD::CTLZ, dl, VT, LSB); 4817 return DAG.getNode(ISD::SUB, dl, VT, WidthMinus1, CTLZ); 4818 } 4819 4820 // Compute with: cttz(x) = ctpop(lsb - 1) 4821 4822 // Since we can only compute the number of bits in a byte with vcnt.8, we 4823 // have to gather the result with pairwise addition (vpaddl) for i16, i32, 4824 // and i64. 4825 4826 // Compute LSB - 1. 4827 SDValue Bits; 4828 if (ElemTy == MVT::i64) { 4829 // Load constant 0xffff'ffff'ffff'ffff to register. 4830 SDValue FF = DAG.getNode(ARMISD::VMOVIMM, dl, VT, 4831 DAG.getTargetConstant(0x1eff, dl, MVT::i32)); 4832 Bits = DAG.getNode(ISD::ADD, dl, VT, LSB, FF); 4833 } else { 4834 SDValue One = DAG.getNode(ARMISD::VMOVIMM, dl, VT, 4835 DAG.getTargetConstant(1, dl, ElemTy)); 4836 Bits = DAG.getNode(ISD::SUB, dl, VT, LSB, One); 4837 } 4838 4839 // Count #bits with vcnt.8. 4840 EVT VT8Bit = VT.is64BitVector() ? MVT::v8i8 : MVT::v16i8; 4841 SDValue BitsVT8 = DAG.getNode(ISD::BITCAST, dl, VT8Bit, Bits); 4842 SDValue Cnt8 = DAG.getNode(ISD::CTPOP, dl, VT8Bit, BitsVT8); 4843 4844 // Gather the #bits with vpaddl (pairwise add.) 4845 EVT VT16Bit = VT.is64BitVector() ? MVT::v4i16 : MVT::v8i16; 4846 SDValue Cnt16 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT16Bit, 4847 DAG.getTargetConstant(Intrinsic::arm_neon_vpaddlu, dl, MVT::i32), 4848 Cnt8); 4849 if (ElemTy == MVT::i16) 4850 return Cnt16; 4851 4852 EVT VT32Bit = VT.is64BitVector() ? MVT::v2i32 : MVT::v4i32; 4853 SDValue Cnt32 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT32Bit, 4854 DAG.getTargetConstant(Intrinsic::arm_neon_vpaddlu, dl, MVT::i32), 4855 Cnt16); 4856 if (ElemTy == MVT::i32) 4857 return Cnt32; 4858 4859 assert(ElemTy == MVT::i64); 4860 SDValue Cnt64 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT, 4861 DAG.getTargetConstant(Intrinsic::arm_neon_vpaddlu, dl, MVT::i32), 4862 Cnt32); 4863 return Cnt64; 4864 } 4865 4866 if (!ST->hasV6T2Ops()) 4867 return SDValue(); 4868 4869 SDValue rbit = DAG.getNode(ISD::BITREVERSE, dl, VT, N->getOperand(0)); 4870 return DAG.getNode(ISD::CTLZ, dl, VT, rbit); 4871 } 4872 4873 /// getCTPOP16BitCounts - Returns a v8i8/v16i8 vector containing the bit-count 4874 /// for each 16-bit element from operand, repeated. The basic idea is to 4875 /// leverage vcnt to get the 8-bit counts, gather and add the results. 4876 /// 4877 /// Trace for v4i16: 4878 /// input = [v0 v1 v2 v3 ] (vi 16-bit element) 4879 /// cast: N0 = [w0 w1 w2 w3 w4 w5 w6 w7] (v0 = [w0 w1], wi 8-bit element) 4880 /// vcnt: N1 = [b0 b1 b2 b3 b4 b5 b6 b7] (bi = bit-count of 8-bit element wi) 4881 /// vrev: N2 = [b1 b0 b3 b2 b5 b4 b7 b6] 4882 /// [b0 b1 b2 b3 b4 b5 b6 b7] 4883 /// +[b1 b0 b3 b2 b5 b4 b7 b6] 4884 /// N3=N1+N2 = [k0 k0 k1 k1 k2 k2 k3 k3] (k0 = b0+b1 = bit-count of 16-bit v0, 4885 /// vuzp: = [k0 k1 k2 k3 k0 k1 k2 k3] each ki is 8-bits) 4886 static SDValue getCTPOP16BitCounts(SDNode *N, SelectionDAG &DAG) { 4887 EVT VT = N->getValueType(0); 4888 SDLoc DL(N); 4889 4890 EVT VT8Bit = VT.is64BitVector() ? MVT::v8i8 : MVT::v16i8; 4891 SDValue N0 = DAG.getNode(ISD::BITCAST, DL, VT8Bit, N->getOperand(0)); 4892 SDValue N1 = DAG.getNode(ISD::CTPOP, DL, VT8Bit, N0); 4893 SDValue N2 = DAG.getNode(ARMISD::VREV16, DL, VT8Bit, N1); 4894 SDValue N3 = DAG.getNode(ISD::ADD, DL, VT8Bit, N1, N2); 4895 return DAG.getNode(ARMISD::VUZP, DL, VT8Bit, N3, N3); 4896 } 4897 4898 /// lowerCTPOP16BitElements - Returns a v4i16/v8i16 vector containing the 4899 /// bit-count for each 16-bit element from the operand. We need slightly 4900 /// different sequencing for v4i16 and v8i16 to stay within NEON's available 4901 /// 64/128-bit registers. 4902 /// 4903 /// Trace for v4i16: 4904 /// input = [v0 v1 v2 v3 ] (vi 16-bit element) 4905 /// v8i8: BitCounts = [k0 k1 k2 k3 k0 k1 k2 k3 ] (ki is the bit-count of vi) 4906 /// v8i16:Extended = [k0 k1 k2 k3 k0 k1 k2 k3 ] 4907 /// v4i16:Extracted = [k0 k1 k2 k3 ] 4908 static SDValue lowerCTPOP16BitElements(SDNode *N, SelectionDAG &DAG) { 4909 EVT VT = N->getValueType(0); 4910 SDLoc DL(N); 4911 4912 SDValue BitCounts = getCTPOP16BitCounts(N, DAG); 4913 if (VT.is64BitVector()) { 4914 SDValue Extended = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::v8i16, BitCounts); 4915 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v4i16, Extended, 4916 DAG.getIntPtrConstant(0, DL)); 4917 } else { 4918 SDValue Extracted = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v8i8, 4919 BitCounts, DAG.getIntPtrConstant(0, DL)); 4920 return DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::v8i16, Extracted); 4921 } 4922 } 4923 4924 /// lowerCTPOP32BitElements - Returns a v2i32/v4i32 vector containing the 4925 /// bit-count for each 32-bit element from the operand. The idea here is 4926 /// to split the vector into 16-bit elements, leverage the 16-bit count 4927 /// routine, and then combine the results. 4928 /// 4929 /// Trace for v2i32 (v4i32 similar with Extracted/Extended exchanged): 4930 /// input = [v0 v1 ] (vi: 32-bit elements) 4931 /// Bitcast = [w0 w1 w2 w3 ] (wi: 16-bit elements, v0 = [w0 w1]) 4932 /// Counts16 = [k0 k1 k2 k3 ] (ki: 16-bit elements, bit-count of wi) 4933 /// vrev: N0 = [k1 k0 k3 k2 ] 4934 /// [k0 k1 k2 k3 ] 4935 /// N1 =+[k1 k0 k3 k2 ] 4936 /// [k0 k2 k1 k3 ] 4937 /// N2 =+[k1 k3 k0 k2 ] 4938 /// [k0 k2 k1 k3 ] 4939 /// Extended =+[k1 k3 k0 k2 ] 4940 /// [k0 k2 ] 4941 /// Extracted=+[k1 k3 ] 4942 /// 4943 static SDValue lowerCTPOP32BitElements(SDNode *N, SelectionDAG &DAG) { 4944 EVT VT = N->getValueType(0); 4945 SDLoc DL(N); 4946 4947 EVT VT16Bit = VT.is64BitVector() ? MVT::v4i16 : MVT::v8i16; 4948 4949 SDValue Bitcast = DAG.getNode(ISD::BITCAST, DL, VT16Bit, N->getOperand(0)); 4950 SDValue Counts16 = lowerCTPOP16BitElements(Bitcast.getNode(), DAG); 4951 SDValue N0 = DAG.getNode(ARMISD::VREV32, DL, VT16Bit, Counts16); 4952 SDValue N1 = DAG.getNode(ISD::ADD, DL, VT16Bit, Counts16, N0); 4953 SDValue N2 = DAG.getNode(ARMISD::VUZP, DL, VT16Bit, N1, N1); 4954 4955 if (VT.is64BitVector()) { 4956 SDValue Extended = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::v4i32, N2); 4957 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2i32, Extended, 4958 DAG.getIntPtrConstant(0, DL)); 4959 } else { 4960 SDValue Extracted = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v4i16, N2, 4961 DAG.getIntPtrConstant(0, DL)); 4962 return DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::v4i32, Extracted); 4963 } 4964 } 4965 4966 static SDValue LowerCTPOP(SDNode *N, SelectionDAG &DAG, 4967 const ARMSubtarget *ST) { 4968 EVT VT = N->getValueType(0); 4969 4970 assert(ST->hasNEON() && "Custom ctpop lowering requires NEON."); 4971 assert((VT == MVT::v2i32 || VT == MVT::v4i32 || 4972 VT == MVT::v4i16 || VT == MVT::v8i16) && 4973 "Unexpected type for custom ctpop lowering"); 4974 4975 if (VT.getVectorElementType() == MVT::i32) 4976 return lowerCTPOP32BitElements(N, DAG); 4977 else 4978 return lowerCTPOP16BitElements(N, DAG); 4979 } 4980 4981 static SDValue LowerShift(SDNode *N, SelectionDAG &DAG, 4982 const ARMSubtarget *ST) { 4983 EVT VT = N->getValueType(0); 4984 SDLoc dl(N); 4985 4986 if (!VT.isVector()) 4987 return SDValue(); 4988 4989 // Lower vector shifts on NEON to use VSHL. 4990 assert(ST->hasNEON() && "unexpected vector shift"); 4991 4992 // Left shifts translate directly to the vshiftu intrinsic. 4993 if (N->getOpcode() == ISD::SHL) 4994 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT, 4995 DAG.getConstant(Intrinsic::arm_neon_vshiftu, dl, 4996 MVT::i32), 4997 N->getOperand(0), N->getOperand(1)); 4998 4999 assert((N->getOpcode() == ISD::SRA || 5000 N->getOpcode() == ISD::SRL) && "unexpected vector shift opcode"); 5001 5002 // NEON uses the same intrinsics for both left and right shifts. For 5003 // right shifts, the shift amounts are negative, so negate the vector of 5004 // shift amounts. 5005 EVT ShiftVT = N->getOperand(1).getValueType(); 5006 SDValue NegatedCount = DAG.getNode(ISD::SUB, dl, ShiftVT, 5007 getZeroVector(ShiftVT, DAG, dl), 5008 N->getOperand(1)); 5009 Intrinsic::ID vshiftInt = (N->getOpcode() == ISD::SRA ? 5010 Intrinsic::arm_neon_vshifts : 5011 Intrinsic::arm_neon_vshiftu); 5012 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT, 5013 DAG.getConstant(vshiftInt, dl, MVT::i32), 5014 N->getOperand(0), NegatedCount); 5015 } 5016 5017 static SDValue Expand64BitShift(SDNode *N, SelectionDAG &DAG, 5018 const ARMSubtarget *ST) { 5019 EVT VT = N->getValueType(0); 5020 SDLoc dl(N); 5021 5022 // We can get here for a node like i32 = ISD::SHL i32, i64 5023 if (VT != MVT::i64) 5024 return SDValue(); 5025 5026 assert((N->getOpcode() == ISD::SRL || N->getOpcode() == ISD::SRA) && 5027 "Unknown shift to lower!"); 5028 5029 // We only lower SRA, SRL of 1 here, all others use generic lowering. 5030 if (!isOneConstant(N->getOperand(1))) 5031 return SDValue(); 5032 5033 // If we are in thumb mode, we don't have RRX. 5034 if (ST->isThumb1Only()) return SDValue(); 5035 5036 // Okay, we have a 64-bit SRA or SRL of 1. Lower this to an RRX expr. 5037 SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(0), 5038 DAG.getConstant(0, dl, MVT::i32)); 5039 SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(0), 5040 DAG.getConstant(1, dl, MVT::i32)); 5041 5042 // First, build a SRA_FLAG/SRL_FLAG op, which shifts the top part by one and 5043 // captures the result into a carry flag. 5044 unsigned Opc = N->getOpcode() == ISD::SRL ? ARMISD::SRL_FLAG:ARMISD::SRA_FLAG; 5045 Hi = DAG.getNode(Opc, dl, DAG.getVTList(MVT::i32, MVT::Glue), Hi); 5046 5047 // The low part is an ARMISD::RRX operand, which shifts the carry in. 5048 Lo = DAG.getNode(ARMISD::RRX, dl, MVT::i32, Lo, Hi.getValue(1)); 5049 5050 // Merge the pieces into a single i64 value. 5051 return DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Lo, Hi); 5052 } 5053 5054 static SDValue LowerVSETCC(SDValue Op, SelectionDAG &DAG) { 5055 SDValue TmpOp0, TmpOp1; 5056 bool Invert = false; 5057 bool Swap = false; 5058 unsigned Opc = 0; 5059 5060 SDValue Op0 = Op.getOperand(0); 5061 SDValue Op1 = Op.getOperand(1); 5062 SDValue CC = Op.getOperand(2); 5063 EVT CmpVT = Op0.getValueType().changeVectorElementTypeToInteger(); 5064 EVT VT = Op.getValueType(); 5065 ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get(); 5066 SDLoc dl(Op); 5067 5068 if (CmpVT.getVectorElementType() == MVT::i64) 5069 // 64-bit comparisons are not legal. We've marked SETCC as non-Custom, 5070 // but it's possible that our operands are 64-bit but our result is 32-bit. 5071 // Bail in this case. 5072 return SDValue(); 5073 5074 if (Op1.getValueType().isFloatingPoint()) { 5075 switch (SetCCOpcode) { 5076 default: llvm_unreachable("Illegal FP comparison"); 5077 case ISD::SETUNE: 5078 case ISD::SETNE: Invert = true; LLVM_FALLTHROUGH; 5079 case ISD::SETOEQ: 5080 case ISD::SETEQ: Opc = ARMISD::VCEQ; break; 5081 case ISD::SETOLT: 5082 case ISD::SETLT: Swap = true; LLVM_FALLTHROUGH; 5083 case ISD::SETOGT: 5084 case ISD::SETGT: Opc = ARMISD::VCGT; break; 5085 case ISD::SETOLE: 5086 case ISD::SETLE: Swap = true; LLVM_FALLTHROUGH; 5087 case ISD::SETOGE: 5088 case ISD::SETGE: Opc = ARMISD::VCGE; break; 5089 case ISD::SETUGE: Swap = true; LLVM_FALLTHROUGH; 5090 case ISD::SETULE: Invert = true; Opc = ARMISD::VCGT; break; 5091 case ISD::SETUGT: Swap = true; LLVM_FALLTHROUGH; 5092 case ISD::SETULT: Invert = true; Opc = ARMISD::VCGE; break; 5093 case ISD::SETUEQ: Invert = true; LLVM_FALLTHROUGH; 5094 case ISD::SETONE: 5095 // Expand this to (OLT | OGT). 5096 TmpOp0 = Op0; 5097 TmpOp1 = Op1; 5098 Opc = ISD::OR; 5099 Op0 = DAG.getNode(ARMISD::VCGT, dl, CmpVT, TmpOp1, TmpOp0); 5100 Op1 = DAG.getNode(ARMISD::VCGT, dl, CmpVT, TmpOp0, TmpOp1); 5101 break; 5102 case ISD::SETUO: 5103 Invert = true; 5104 LLVM_FALLTHROUGH; 5105 case ISD::SETO: 5106 // Expand this to (OLT | OGE). 5107 TmpOp0 = Op0; 5108 TmpOp1 = Op1; 5109 Opc = ISD::OR; 5110 Op0 = DAG.getNode(ARMISD::VCGT, dl, CmpVT, TmpOp1, TmpOp0); 5111 Op1 = DAG.getNode(ARMISD::VCGE, dl, CmpVT, TmpOp0, TmpOp1); 5112 break; 5113 } 5114 } else { 5115 // Integer comparisons. 5116 switch (SetCCOpcode) { 5117 default: llvm_unreachable("Illegal integer comparison"); 5118 case ISD::SETNE: Invert = true; 5119 case ISD::SETEQ: Opc = ARMISD::VCEQ; break; 5120 case ISD::SETLT: Swap = true; 5121 case ISD::SETGT: Opc = ARMISD::VCGT; break; 5122 case ISD::SETLE: Swap = true; 5123 case ISD::SETGE: Opc = ARMISD::VCGE; break; 5124 case ISD::SETULT: Swap = true; 5125 case ISD::SETUGT: Opc = ARMISD::VCGTU; break; 5126 case ISD::SETULE: Swap = true; 5127 case ISD::SETUGE: Opc = ARMISD::VCGEU; break; 5128 } 5129 5130 // Detect VTST (Vector Test Bits) = icmp ne (and (op0, op1), zero). 5131 if (Opc == ARMISD::VCEQ) { 5132 5133 SDValue AndOp; 5134 if (ISD::isBuildVectorAllZeros(Op1.getNode())) 5135 AndOp = Op0; 5136 else if (ISD::isBuildVectorAllZeros(Op0.getNode())) 5137 AndOp = Op1; 5138 5139 // Ignore bitconvert. 5140 if (AndOp.getNode() && AndOp.getOpcode() == ISD::BITCAST) 5141 AndOp = AndOp.getOperand(0); 5142 5143 if (AndOp.getNode() && AndOp.getOpcode() == ISD::AND) { 5144 Opc = ARMISD::VTST; 5145 Op0 = DAG.getNode(ISD::BITCAST, dl, CmpVT, AndOp.getOperand(0)); 5146 Op1 = DAG.getNode(ISD::BITCAST, dl, CmpVT, AndOp.getOperand(1)); 5147 Invert = !Invert; 5148 } 5149 } 5150 } 5151 5152 if (Swap) 5153 std::swap(Op0, Op1); 5154 5155 // If one of the operands is a constant vector zero, attempt to fold the 5156 // comparison to a specialized compare-against-zero form. 5157 SDValue SingleOp; 5158 if (ISD::isBuildVectorAllZeros(Op1.getNode())) 5159 SingleOp = Op0; 5160 else if (ISD::isBuildVectorAllZeros(Op0.getNode())) { 5161 if (Opc == ARMISD::VCGE) 5162 Opc = ARMISD::VCLEZ; 5163 else if (Opc == ARMISD::VCGT) 5164 Opc = ARMISD::VCLTZ; 5165 SingleOp = Op1; 5166 } 5167 5168 SDValue Result; 5169 if (SingleOp.getNode()) { 5170 switch (Opc) { 5171 case ARMISD::VCEQ: 5172 Result = DAG.getNode(ARMISD::VCEQZ, dl, CmpVT, SingleOp); break; 5173 case ARMISD::VCGE: 5174 Result = DAG.getNode(ARMISD::VCGEZ, dl, CmpVT, SingleOp); break; 5175 case ARMISD::VCLEZ: 5176 Result = DAG.getNode(ARMISD::VCLEZ, dl, CmpVT, SingleOp); break; 5177 case ARMISD::VCGT: 5178 Result = DAG.getNode(ARMISD::VCGTZ, dl, CmpVT, SingleOp); break; 5179 case ARMISD::VCLTZ: 5180 Result = DAG.getNode(ARMISD::VCLTZ, dl, CmpVT, SingleOp); break; 5181 default: 5182 Result = DAG.getNode(Opc, dl, CmpVT, Op0, Op1); 5183 } 5184 } else { 5185 Result = DAG.getNode(Opc, dl, CmpVT, Op0, Op1); 5186 } 5187 5188 Result = DAG.getSExtOrTrunc(Result, dl, VT); 5189 5190 if (Invert) 5191 Result = DAG.getNOT(dl, Result, VT); 5192 5193 return Result; 5194 } 5195 5196 static SDValue LowerSETCCE(SDValue Op, SelectionDAG &DAG) { 5197 SDValue LHS = Op.getOperand(0); 5198 SDValue RHS = Op.getOperand(1); 5199 SDValue Carry = Op.getOperand(2); 5200 SDValue Cond = Op.getOperand(3); 5201 SDLoc DL(Op); 5202 5203 assert(LHS.getSimpleValueType().isInteger() && "SETCCE is integer only."); 5204 5205 assert(Carry.getOpcode() != ISD::CARRY_FALSE); 5206 SDVTList VTs = DAG.getVTList(LHS.getValueType(), MVT::i32); 5207 SDValue Cmp = DAG.getNode(ARMISD::SUBE, DL, VTs, LHS, RHS, Carry); 5208 5209 SDValue FVal = DAG.getConstant(0, DL, MVT::i32); 5210 SDValue TVal = DAG.getConstant(1, DL, MVT::i32); 5211 SDValue ARMcc = DAG.getConstant( 5212 IntCCToARMCC(cast<CondCodeSDNode>(Cond)->get()), DL, MVT::i32); 5213 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32); 5214 SDValue Chain = DAG.getCopyToReg(DAG.getEntryNode(), DL, ARM::CPSR, 5215 Cmp.getValue(1), SDValue()); 5216 return DAG.getNode(ARMISD::CMOV, DL, Op.getValueType(), FVal, TVal, ARMcc, 5217 CCR, Chain.getValue(1)); 5218 } 5219 5220 /// isNEONModifiedImm - Check if the specified splat value corresponds to a 5221 /// valid vector constant for a NEON instruction with a "modified immediate" 5222 /// operand (e.g., VMOV). If so, return the encoded value. 5223 static SDValue isNEONModifiedImm(uint64_t SplatBits, uint64_t SplatUndef, 5224 unsigned SplatBitSize, SelectionDAG &DAG, 5225 const SDLoc &dl, EVT &VT, bool is128Bits, 5226 NEONModImmType type) { 5227 unsigned OpCmode, Imm; 5228 5229 // SplatBitSize is set to the smallest size that splats the vector, so a 5230 // zero vector will always have SplatBitSize == 8. However, NEON modified 5231 // immediate instructions others than VMOV do not support the 8-bit encoding 5232 // of a zero vector, and the default encoding of zero is supposed to be the 5233 // 32-bit version. 5234 if (SplatBits == 0) 5235 SplatBitSize = 32; 5236 5237 switch (SplatBitSize) { 5238 case 8: 5239 if (type != VMOVModImm) 5240 return SDValue(); 5241 // Any 1-byte value is OK. Op=0, Cmode=1110. 5242 assert((SplatBits & ~0xff) == 0 && "one byte splat value is too big"); 5243 OpCmode = 0xe; 5244 Imm = SplatBits; 5245 VT = is128Bits ? MVT::v16i8 : MVT::v8i8; 5246 break; 5247 5248 case 16: 5249 // NEON's 16-bit VMOV supports splat values where only one byte is nonzero. 5250 VT = is128Bits ? MVT::v8i16 : MVT::v4i16; 5251 if ((SplatBits & ~0xff) == 0) { 5252 // Value = 0x00nn: Op=x, Cmode=100x. 5253 OpCmode = 0x8; 5254 Imm = SplatBits; 5255 break; 5256 } 5257 if ((SplatBits & ~0xff00) == 0) { 5258 // Value = 0xnn00: Op=x, Cmode=101x. 5259 OpCmode = 0xa; 5260 Imm = SplatBits >> 8; 5261 break; 5262 } 5263 return SDValue(); 5264 5265 case 32: 5266 // NEON's 32-bit VMOV supports splat values where: 5267 // * only one byte is nonzero, or 5268 // * the least significant byte is 0xff and the second byte is nonzero, or 5269 // * the least significant 2 bytes are 0xff and the third is nonzero. 5270 VT = is128Bits ? MVT::v4i32 : MVT::v2i32; 5271 if ((SplatBits & ~0xff) == 0) { 5272 // Value = 0x000000nn: Op=x, Cmode=000x. 5273 OpCmode = 0; 5274 Imm = SplatBits; 5275 break; 5276 } 5277 if ((SplatBits & ~0xff00) == 0) { 5278 // Value = 0x0000nn00: Op=x, Cmode=001x. 5279 OpCmode = 0x2; 5280 Imm = SplatBits >> 8; 5281 break; 5282 } 5283 if ((SplatBits & ~0xff0000) == 0) { 5284 // Value = 0x00nn0000: Op=x, Cmode=010x. 5285 OpCmode = 0x4; 5286 Imm = SplatBits >> 16; 5287 break; 5288 } 5289 if ((SplatBits & ~0xff000000) == 0) { 5290 // Value = 0xnn000000: Op=x, Cmode=011x. 5291 OpCmode = 0x6; 5292 Imm = SplatBits >> 24; 5293 break; 5294 } 5295 5296 // cmode == 0b1100 and cmode == 0b1101 are not supported for VORR or VBIC 5297 if (type == OtherModImm) return SDValue(); 5298 5299 if ((SplatBits & ~0xffff) == 0 && 5300 ((SplatBits | SplatUndef) & 0xff) == 0xff) { 5301 // Value = 0x0000nnff: Op=x, Cmode=1100. 5302 OpCmode = 0xc; 5303 Imm = SplatBits >> 8; 5304 break; 5305 } 5306 5307 if ((SplatBits & ~0xffffff) == 0 && 5308 ((SplatBits | SplatUndef) & 0xffff) == 0xffff) { 5309 // Value = 0x00nnffff: Op=x, Cmode=1101. 5310 OpCmode = 0xd; 5311 Imm = SplatBits >> 16; 5312 break; 5313 } 5314 5315 // Note: there are a few 32-bit splat values (specifically: 00ffff00, 5316 // ff000000, ff0000ff, and ffff00ff) that are valid for VMOV.I64 but not 5317 // VMOV.I32. A (very) minor optimization would be to replicate the value 5318 // and fall through here to test for a valid 64-bit splat. But, then the 5319 // caller would also need to check and handle the change in size. 5320 return SDValue(); 5321 5322 case 64: { 5323 if (type != VMOVModImm) 5324 return SDValue(); 5325 // NEON has a 64-bit VMOV splat where each byte is either 0 or 0xff. 5326 uint64_t BitMask = 0xff; 5327 uint64_t Val = 0; 5328 unsigned ImmMask = 1; 5329 Imm = 0; 5330 for (int ByteNum = 0; ByteNum < 8; ++ByteNum) { 5331 if (((SplatBits | SplatUndef) & BitMask) == BitMask) { 5332 Val |= BitMask; 5333 Imm |= ImmMask; 5334 } else if ((SplatBits & BitMask) != 0) { 5335 return SDValue(); 5336 } 5337 BitMask <<= 8; 5338 ImmMask <<= 1; 5339 } 5340 5341 if (DAG.getDataLayout().isBigEndian()) 5342 // swap higher and lower 32 bit word 5343 Imm = ((Imm & 0xf) << 4) | ((Imm & 0xf0) >> 4); 5344 5345 // Op=1, Cmode=1110. 5346 OpCmode = 0x1e; 5347 VT = is128Bits ? MVT::v2i64 : MVT::v1i64; 5348 break; 5349 } 5350 5351 default: 5352 llvm_unreachable("unexpected size for isNEONModifiedImm"); 5353 } 5354 5355 unsigned EncodedVal = ARM_AM::createNEONModImm(OpCmode, Imm); 5356 return DAG.getTargetConstant(EncodedVal, dl, MVT::i32); 5357 } 5358 5359 SDValue ARMTargetLowering::LowerConstantFP(SDValue Op, SelectionDAG &DAG, 5360 const ARMSubtarget *ST) const { 5361 if (!ST->hasVFP3()) 5362 return SDValue(); 5363 5364 bool IsDouble = Op.getValueType() == MVT::f64; 5365 ConstantFPSDNode *CFP = cast<ConstantFPSDNode>(Op); 5366 5367 // Use the default (constant pool) lowering for double constants when we have 5368 // an SP-only FPU 5369 if (IsDouble && Subtarget->isFPOnlySP()) 5370 return SDValue(); 5371 5372 // Try splatting with a VMOV.f32... 5373 const APFloat &FPVal = CFP->getValueAPF(); 5374 int ImmVal = IsDouble ? ARM_AM::getFP64Imm(FPVal) : ARM_AM::getFP32Imm(FPVal); 5375 5376 if (ImmVal != -1) { 5377 if (IsDouble || !ST->useNEONForSinglePrecisionFP()) { 5378 // We have code in place to select a valid ConstantFP already, no need to 5379 // do any mangling. 5380 return Op; 5381 } 5382 5383 // It's a float and we are trying to use NEON operations where 5384 // possible. Lower it to a splat followed by an extract. 5385 SDLoc DL(Op); 5386 SDValue NewVal = DAG.getTargetConstant(ImmVal, DL, MVT::i32); 5387 SDValue VecConstant = DAG.getNode(ARMISD::VMOVFPIMM, DL, MVT::v2f32, 5388 NewVal); 5389 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32, VecConstant, 5390 DAG.getConstant(0, DL, MVT::i32)); 5391 } 5392 5393 // The rest of our options are NEON only, make sure that's allowed before 5394 // proceeding.. 5395 if (!ST->hasNEON() || (!IsDouble && !ST->useNEONForSinglePrecisionFP())) 5396 return SDValue(); 5397 5398 EVT VMovVT; 5399 uint64_t iVal = FPVal.bitcastToAPInt().getZExtValue(); 5400 5401 // It wouldn't really be worth bothering for doubles except for one very 5402 // important value, which does happen to match: 0.0. So make sure we don't do 5403 // anything stupid. 5404 if (IsDouble && (iVal & 0xffffffff) != (iVal >> 32)) 5405 return SDValue(); 5406 5407 // Try a VMOV.i32 (FIXME: i8, i16, or i64 could work too). 5408 SDValue NewVal = isNEONModifiedImm(iVal & 0xffffffffU, 0, 32, DAG, SDLoc(Op), 5409 VMovVT, false, VMOVModImm); 5410 if (NewVal != SDValue()) { 5411 SDLoc DL(Op); 5412 SDValue VecConstant = DAG.getNode(ARMISD::VMOVIMM, DL, VMovVT, 5413 NewVal); 5414 if (IsDouble) 5415 return DAG.getNode(ISD::BITCAST, DL, MVT::f64, VecConstant); 5416 5417 // It's a float: cast and extract a vector element. 5418 SDValue VecFConstant = DAG.getNode(ISD::BITCAST, DL, MVT::v2f32, 5419 VecConstant); 5420 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32, VecFConstant, 5421 DAG.getConstant(0, DL, MVT::i32)); 5422 } 5423 5424 // Finally, try a VMVN.i32 5425 NewVal = isNEONModifiedImm(~iVal & 0xffffffffU, 0, 32, DAG, SDLoc(Op), VMovVT, 5426 false, VMVNModImm); 5427 if (NewVal != SDValue()) { 5428 SDLoc DL(Op); 5429 SDValue VecConstant = DAG.getNode(ARMISD::VMVNIMM, DL, VMovVT, NewVal); 5430 5431 if (IsDouble) 5432 return DAG.getNode(ISD::BITCAST, DL, MVT::f64, VecConstant); 5433 5434 // It's a float: cast and extract a vector element. 5435 SDValue VecFConstant = DAG.getNode(ISD::BITCAST, DL, MVT::v2f32, 5436 VecConstant); 5437 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32, VecFConstant, 5438 DAG.getConstant(0, DL, MVT::i32)); 5439 } 5440 5441 return SDValue(); 5442 } 5443 5444 // check if an VEXT instruction can handle the shuffle mask when the 5445 // vector sources of the shuffle are the same. 5446 static bool isSingletonVEXTMask(ArrayRef<int> M, EVT VT, unsigned &Imm) { 5447 unsigned NumElts = VT.getVectorNumElements(); 5448 5449 // Assume that the first shuffle index is not UNDEF. Fail if it is. 5450 if (M[0] < 0) 5451 return false; 5452 5453 Imm = M[0]; 5454 5455 // If this is a VEXT shuffle, the immediate value is the index of the first 5456 // element. The other shuffle indices must be the successive elements after 5457 // the first one. 5458 unsigned ExpectedElt = Imm; 5459 for (unsigned i = 1; i < NumElts; ++i) { 5460 // Increment the expected index. If it wraps around, just follow it 5461 // back to index zero and keep going. 5462 ++ExpectedElt; 5463 if (ExpectedElt == NumElts) 5464 ExpectedElt = 0; 5465 5466 if (M[i] < 0) continue; // ignore UNDEF indices 5467 if (ExpectedElt != static_cast<unsigned>(M[i])) 5468 return false; 5469 } 5470 5471 return true; 5472 } 5473 5474 5475 static bool isVEXTMask(ArrayRef<int> M, EVT VT, 5476 bool &ReverseVEXT, unsigned &Imm) { 5477 unsigned NumElts = VT.getVectorNumElements(); 5478 ReverseVEXT = false; 5479 5480 // Assume that the first shuffle index is not UNDEF. Fail if it is. 5481 if (M[0] < 0) 5482 return false; 5483 5484 Imm = M[0]; 5485 5486 // If this is a VEXT shuffle, the immediate value is the index of the first 5487 // element. The other shuffle indices must be the successive elements after 5488 // the first one. 5489 unsigned ExpectedElt = Imm; 5490 for (unsigned i = 1; i < NumElts; ++i) { 5491 // Increment the expected index. If it wraps around, it may still be 5492 // a VEXT but the source vectors must be swapped. 5493 ExpectedElt += 1; 5494 if (ExpectedElt == NumElts * 2) { 5495 ExpectedElt = 0; 5496 ReverseVEXT = true; 5497 } 5498 5499 if (M[i] < 0) continue; // ignore UNDEF indices 5500 if (ExpectedElt != static_cast<unsigned>(M[i])) 5501 return false; 5502 } 5503 5504 // Adjust the index value if the source operands will be swapped. 5505 if (ReverseVEXT) 5506 Imm -= NumElts; 5507 5508 return true; 5509 } 5510 5511 /// isVREVMask - Check if a vector shuffle corresponds to a VREV 5512 /// instruction with the specified blocksize. (The order of the elements 5513 /// within each block of the vector is reversed.) 5514 static bool isVREVMask(ArrayRef<int> M, EVT VT, unsigned BlockSize) { 5515 assert((BlockSize==16 || BlockSize==32 || BlockSize==64) && 5516 "Only possible block sizes for VREV are: 16, 32, 64"); 5517 5518 unsigned EltSz = VT.getVectorElementType().getSizeInBits(); 5519 if (EltSz == 64) 5520 return false; 5521 5522 unsigned NumElts = VT.getVectorNumElements(); 5523 unsigned BlockElts = M[0] + 1; 5524 // If the first shuffle index is UNDEF, be optimistic. 5525 if (M[0] < 0) 5526 BlockElts = BlockSize / EltSz; 5527 5528 if (BlockSize <= EltSz || BlockSize != BlockElts * EltSz) 5529 return false; 5530 5531 for (unsigned i = 0; i < NumElts; ++i) { 5532 if (M[i] < 0) continue; // ignore UNDEF indices 5533 if ((unsigned) M[i] != (i - i%BlockElts) + (BlockElts - 1 - i%BlockElts)) 5534 return false; 5535 } 5536 5537 return true; 5538 } 5539 5540 static bool isVTBLMask(ArrayRef<int> M, EVT VT) { 5541 // We can handle <8 x i8> vector shuffles. If the index in the mask is out of 5542 // range, then 0 is placed into the resulting vector. So pretty much any mask 5543 // of 8 elements can work here. 5544 return VT == MVT::v8i8 && M.size() == 8; 5545 } 5546 5547 // Checks whether the shuffle mask represents a vector transpose (VTRN) by 5548 // checking that pairs of elements in the shuffle mask represent the same index 5549 // in each vector, incrementing the expected index by 2 at each step. 5550 // e.g. For v1,v2 of type v4i32 a valid shuffle mask is: [0, 4, 2, 6] 5551 // v1={a,b,c,d} => x=shufflevector v1, v2 shufflemask => x={a,e,c,g} 5552 // v2={e,f,g,h} 5553 // WhichResult gives the offset for each element in the mask based on which 5554 // of the two results it belongs to. 5555 // 5556 // The transpose can be represented either as: 5557 // result1 = shufflevector v1, v2, result1_shuffle_mask 5558 // result2 = shufflevector v1, v2, result2_shuffle_mask 5559 // where v1/v2 and the shuffle masks have the same number of elements 5560 // (here WhichResult (see below) indicates which result is being checked) 5561 // 5562 // or as: 5563 // results = shufflevector v1, v2, shuffle_mask 5564 // where both results are returned in one vector and the shuffle mask has twice 5565 // as many elements as v1/v2 (here WhichResult will always be 0 if true) here we 5566 // want to check the low half and high half of the shuffle mask as if it were 5567 // the other case 5568 static bool isVTRNMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) { 5569 unsigned EltSz = VT.getVectorElementType().getSizeInBits(); 5570 if (EltSz == 64) 5571 return false; 5572 5573 unsigned NumElts = VT.getVectorNumElements(); 5574 if (M.size() != NumElts && M.size() != NumElts*2) 5575 return false; 5576 5577 // If the mask is twice as long as the input vector then we need to check the 5578 // upper and lower parts of the mask with a matching value for WhichResult 5579 // FIXME: A mask with only even values will be rejected in case the first 5580 // element is undefined, e.g. [-1, 4, 2, 6] will be rejected, because only 5581 // M[0] is used to determine WhichResult 5582 for (unsigned i = 0; i < M.size(); i += NumElts) { 5583 if (M.size() == NumElts * 2) 5584 WhichResult = i / NumElts; 5585 else 5586 WhichResult = M[i] == 0 ? 0 : 1; 5587 for (unsigned j = 0; j < NumElts; j += 2) { 5588 if ((M[i+j] >= 0 && (unsigned) M[i+j] != j + WhichResult) || 5589 (M[i+j+1] >= 0 && (unsigned) M[i+j+1] != j + NumElts + WhichResult)) 5590 return false; 5591 } 5592 } 5593 5594 if (M.size() == NumElts*2) 5595 WhichResult = 0; 5596 5597 return true; 5598 } 5599 5600 /// isVTRN_v_undef_Mask - Special case of isVTRNMask for canonical form of 5601 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef". 5602 /// Mask is e.g., <0, 0, 2, 2> instead of <0, 4, 2, 6>. 5603 static bool isVTRN_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult){ 5604 unsigned EltSz = VT.getVectorElementType().getSizeInBits(); 5605 if (EltSz == 64) 5606 return false; 5607 5608 unsigned NumElts = VT.getVectorNumElements(); 5609 if (M.size() != NumElts && M.size() != NumElts*2) 5610 return false; 5611 5612 for (unsigned i = 0; i < M.size(); i += NumElts) { 5613 if (M.size() == NumElts * 2) 5614 WhichResult = i / NumElts; 5615 else 5616 WhichResult = M[i] == 0 ? 0 : 1; 5617 for (unsigned j = 0; j < NumElts; j += 2) { 5618 if ((M[i+j] >= 0 && (unsigned) M[i+j] != j + WhichResult) || 5619 (M[i+j+1] >= 0 && (unsigned) M[i+j+1] != j + WhichResult)) 5620 return false; 5621 } 5622 } 5623 5624 if (M.size() == NumElts*2) 5625 WhichResult = 0; 5626 5627 return true; 5628 } 5629 5630 // Checks whether the shuffle mask represents a vector unzip (VUZP) by checking 5631 // that the mask elements are either all even and in steps of size 2 or all odd 5632 // and in steps of size 2. 5633 // e.g. For v1,v2 of type v4i32 a valid shuffle mask is: [0, 2, 4, 6] 5634 // v1={a,b,c,d} => x=shufflevector v1, v2 shufflemask => x={a,c,e,g} 5635 // v2={e,f,g,h} 5636 // Requires similar checks to that of isVTRNMask with 5637 // respect the how results are returned. 5638 static bool isVUZPMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) { 5639 unsigned EltSz = VT.getVectorElementType().getSizeInBits(); 5640 if (EltSz == 64) 5641 return false; 5642 5643 unsigned NumElts = VT.getVectorNumElements(); 5644 if (M.size() != NumElts && M.size() != NumElts*2) 5645 return false; 5646 5647 for (unsigned i = 0; i < M.size(); i += NumElts) { 5648 WhichResult = M[i] == 0 ? 0 : 1; 5649 for (unsigned j = 0; j < NumElts; ++j) { 5650 if (M[i+j] >= 0 && (unsigned) M[i+j] != 2 * j + WhichResult) 5651 return false; 5652 } 5653 } 5654 5655 if (M.size() == NumElts*2) 5656 WhichResult = 0; 5657 5658 // VUZP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32. 5659 if (VT.is64BitVector() && EltSz == 32) 5660 return false; 5661 5662 return true; 5663 } 5664 5665 /// isVUZP_v_undef_Mask - Special case of isVUZPMask for canonical form of 5666 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef". 5667 /// Mask is e.g., <0, 2, 0, 2> instead of <0, 2, 4, 6>, 5668 static bool isVUZP_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult){ 5669 unsigned EltSz = VT.getVectorElementType().getSizeInBits(); 5670 if (EltSz == 64) 5671 return false; 5672 5673 unsigned NumElts = VT.getVectorNumElements(); 5674 if (M.size() != NumElts && M.size() != NumElts*2) 5675 return false; 5676 5677 unsigned Half = NumElts / 2; 5678 for (unsigned i = 0; i < M.size(); i += NumElts) { 5679 WhichResult = M[i] == 0 ? 0 : 1; 5680 for (unsigned j = 0; j < NumElts; j += Half) { 5681 unsigned Idx = WhichResult; 5682 for (unsigned k = 0; k < Half; ++k) { 5683 int MIdx = M[i + j + k]; 5684 if (MIdx >= 0 && (unsigned) MIdx != Idx) 5685 return false; 5686 Idx += 2; 5687 } 5688 } 5689 } 5690 5691 if (M.size() == NumElts*2) 5692 WhichResult = 0; 5693 5694 // VUZP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32. 5695 if (VT.is64BitVector() && EltSz == 32) 5696 return false; 5697 5698 return true; 5699 } 5700 5701 // Checks whether the shuffle mask represents a vector zip (VZIP) by checking 5702 // that pairs of elements of the shufflemask represent the same index in each 5703 // vector incrementing sequentially through the vectors. 5704 // e.g. For v1,v2 of type v4i32 a valid shuffle mask is: [0, 4, 1, 5] 5705 // v1={a,b,c,d} => x=shufflevector v1, v2 shufflemask => x={a,e,b,f} 5706 // v2={e,f,g,h} 5707 // Requires similar checks to that of isVTRNMask with respect the how results 5708 // are returned. 5709 static bool isVZIPMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) { 5710 unsigned EltSz = VT.getVectorElementType().getSizeInBits(); 5711 if (EltSz == 64) 5712 return false; 5713 5714 unsigned NumElts = VT.getVectorNumElements(); 5715 if (M.size() != NumElts && M.size() != NumElts*2) 5716 return false; 5717 5718 for (unsigned i = 0; i < M.size(); i += NumElts) { 5719 WhichResult = M[i] == 0 ? 0 : 1; 5720 unsigned Idx = WhichResult * NumElts / 2; 5721 for (unsigned j = 0; j < NumElts; j += 2) { 5722 if ((M[i+j] >= 0 && (unsigned) M[i+j] != Idx) || 5723 (M[i+j+1] >= 0 && (unsigned) M[i+j+1] != Idx + NumElts)) 5724 return false; 5725 Idx += 1; 5726 } 5727 } 5728 5729 if (M.size() == NumElts*2) 5730 WhichResult = 0; 5731 5732 // VZIP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32. 5733 if (VT.is64BitVector() && EltSz == 32) 5734 return false; 5735 5736 return true; 5737 } 5738 5739 /// isVZIP_v_undef_Mask - Special case of isVZIPMask for canonical form of 5740 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef". 5741 /// Mask is e.g., <0, 0, 1, 1> instead of <0, 4, 1, 5>. 5742 static bool isVZIP_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult){ 5743 unsigned EltSz = VT.getVectorElementType().getSizeInBits(); 5744 if (EltSz == 64) 5745 return false; 5746 5747 unsigned NumElts = VT.getVectorNumElements(); 5748 if (M.size() != NumElts && M.size() != NumElts*2) 5749 return false; 5750 5751 for (unsigned i = 0; i < M.size(); i += NumElts) { 5752 WhichResult = M[i] == 0 ? 0 : 1; 5753 unsigned Idx = WhichResult * NumElts / 2; 5754 for (unsigned j = 0; j < NumElts; j += 2) { 5755 if ((M[i+j] >= 0 && (unsigned) M[i+j] != Idx) || 5756 (M[i+j+1] >= 0 && (unsigned) M[i+j+1] != Idx)) 5757 return false; 5758 Idx += 1; 5759 } 5760 } 5761 5762 if (M.size() == NumElts*2) 5763 WhichResult = 0; 5764 5765 // VZIP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32. 5766 if (VT.is64BitVector() && EltSz == 32) 5767 return false; 5768 5769 return true; 5770 } 5771 5772 /// Check if \p ShuffleMask is a NEON two-result shuffle (VZIP, VUZP, VTRN), 5773 /// and return the corresponding ARMISD opcode if it is, or 0 if it isn't. 5774 static unsigned isNEONTwoResultShuffleMask(ArrayRef<int> ShuffleMask, EVT VT, 5775 unsigned &WhichResult, 5776 bool &isV_UNDEF) { 5777 isV_UNDEF = false; 5778 if (isVTRNMask(ShuffleMask, VT, WhichResult)) 5779 return ARMISD::VTRN; 5780 if (isVUZPMask(ShuffleMask, VT, WhichResult)) 5781 return ARMISD::VUZP; 5782 if (isVZIPMask(ShuffleMask, VT, WhichResult)) 5783 return ARMISD::VZIP; 5784 5785 isV_UNDEF = true; 5786 if (isVTRN_v_undef_Mask(ShuffleMask, VT, WhichResult)) 5787 return ARMISD::VTRN; 5788 if (isVUZP_v_undef_Mask(ShuffleMask, VT, WhichResult)) 5789 return ARMISD::VUZP; 5790 if (isVZIP_v_undef_Mask(ShuffleMask, VT, WhichResult)) 5791 return ARMISD::VZIP; 5792 5793 return 0; 5794 } 5795 5796 /// \return true if this is a reverse operation on an vector. 5797 static bool isReverseMask(ArrayRef<int> M, EVT VT) { 5798 unsigned NumElts = VT.getVectorNumElements(); 5799 // Make sure the mask has the right size. 5800 if (NumElts != M.size()) 5801 return false; 5802 5803 // Look for <15, ..., 3, -1, 1, 0>. 5804 for (unsigned i = 0; i != NumElts; ++i) 5805 if (M[i] >= 0 && M[i] != (int) (NumElts - 1 - i)) 5806 return false; 5807 5808 return true; 5809 } 5810 5811 // If N is an integer constant that can be moved into a register in one 5812 // instruction, return an SDValue of such a constant (will become a MOV 5813 // instruction). Otherwise return null. 5814 static SDValue IsSingleInstrConstant(SDValue N, SelectionDAG &DAG, 5815 const ARMSubtarget *ST, const SDLoc &dl) { 5816 uint64_t Val; 5817 if (!isa<ConstantSDNode>(N)) 5818 return SDValue(); 5819 Val = cast<ConstantSDNode>(N)->getZExtValue(); 5820 5821 if (ST->isThumb1Only()) { 5822 if (Val <= 255 || ~Val <= 255) 5823 return DAG.getConstant(Val, dl, MVT::i32); 5824 } else { 5825 if (ARM_AM::getSOImmVal(Val) != -1 || ARM_AM::getSOImmVal(~Val) != -1) 5826 return DAG.getConstant(Val, dl, MVT::i32); 5827 } 5828 return SDValue(); 5829 } 5830 5831 // If this is a case we can't handle, return null and let the default 5832 // expansion code take care of it. 5833 SDValue ARMTargetLowering::LowerBUILD_VECTOR(SDValue Op, SelectionDAG &DAG, 5834 const ARMSubtarget *ST) const { 5835 BuildVectorSDNode *BVN = cast<BuildVectorSDNode>(Op.getNode()); 5836 SDLoc dl(Op); 5837 EVT VT = Op.getValueType(); 5838 5839 APInt SplatBits, SplatUndef; 5840 unsigned SplatBitSize; 5841 bool HasAnyUndefs; 5842 if (BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs)) { 5843 if (SplatBitSize <= 64) { 5844 // Check if an immediate VMOV works. 5845 EVT VmovVT; 5846 SDValue Val = isNEONModifiedImm(SplatBits.getZExtValue(), 5847 SplatUndef.getZExtValue(), SplatBitSize, 5848 DAG, dl, VmovVT, VT.is128BitVector(), 5849 VMOVModImm); 5850 if (Val.getNode()) { 5851 SDValue Vmov = DAG.getNode(ARMISD::VMOVIMM, dl, VmovVT, Val); 5852 return DAG.getNode(ISD::BITCAST, dl, VT, Vmov); 5853 } 5854 5855 // Try an immediate VMVN. 5856 uint64_t NegatedImm = (~SplatBits).getZExtValue(); 5857 Val = isNEONModifiedImm(NegatedImm, 5858 SplatUndef.getZExtValue(), SplatBitSize, 5859 DAG, dl, VmovVT, VT.is128BitVector(), 5860 VMVNModImm); 5861 if (Val.getNode()) { 5862 SDValue Vmov = DAG.getNode(ARMISD::VMVNIMM, dl, VmovVT, Val); 5863 return DAG.getNode(ISD::BITCAST, dl, VT, Vmov); 5864 } 5865 5866 // Use vmov.f32 to materialize other v2f32 and v4f32 splats. 5867 if ((VT == MVT::v2f32 || VT == MVT::v4f32) && SplatBitSize == 32) { 5868 int ImmVal = ARM_AM::getFP32Imm(SplatBits); 5869 if (ImmVal != -1) { 5870 SDValue Val = DAG.getTargetConstant(ImmVal, dl, MVT::i32); 5871 return DAG.getNode(ARMISD::VMOVFPIMM, dl, VT, Val); 5872 } 5873 } 5874 } 5875 } 5876 5877 // Scan through the operands to see if only one value is used. 5878 // 5879 // As an optimisation, even if more than one value is used it may be more 5880 // profitable to splat with one value then change some lanes. 5881 // 5882 // Heuristically we decide to do this if the vector has a "dominant" value, 5883 // defined as splatted to more than half of the lanes. 5884 unsigned NumElts = VT.getVectorNumElements(); 5885 bool isOnlyLowElement = true; 5886 bool usesOnlyOneValue = true; 5887 bool hasDominantValue = false; 5888 bool isConstant = true; 5889 5890 // Map of the number of times a particular SDValue appears in the 5891 // element list. 5892 DenseMap<SDValue, unsigned> ValueCounts; 5893 SDValue Value; 5894 for (unsigned i = 0; i < NumElts; ++i) { 5895 SDValue V = Op.getOperand(i); 5896 if (V.isUndef()) 5897 continue; 5898 if (i > 0) 5899 isOnlyLowElement = false; 5900 if (!isa<ConstantFPSDNode>(V) && !isa<ConstantSDNode>(V)) 5901 isConstant = false; 5902 5903 ValueCounts.insert(std::make_pair(V, 0)); 5904 unsigned &Count = ValueCounts[V]; 5905 5906 // Is this value dominant? (takes up more than half of the lanes) 5907 if (++Count > (NumElts / 2)) { 5908 hasDominantValue = true; 5909 Value = V; 5910 } 5911 } 5912 if (ValueCounts.size() != 1) 5913 usesOnlyOneValue = false; 5914 if (!Value.getNode() && ValueCounts.size() > 0) 5915 Value = ValueCounts.begin()->first; 5916 5917 if (ValueCounts.size() == 0) 5918 return DAG.getUNDEF(VT); 5919 5920 // Loads are better lowered with insert_vector_elt/ARMISD::BUILD_VECTOR. 5921 // Keep going if we are hitting this case. 5922 if (isOnlyLowElement && !ISD::isNormalLoad(Value.getNode())) 5923 return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Value); 5924 5925 unsigned EltSize = VT.getVectorElementType().getSizeInBits(); 5926 5927 // Use VDUP for non-constant splats. For f32 constant splats, reduce to 5928 // i32 and try again. 5929 if (hasDominantValue && EltSize <= 32) { 5930 if (!isConstant) { 5931 SDValue N; 5932 5933 // If we are VDUPing a value that comes directly from a vector, that will 5934 // cause an unnecessary move to and from a GPR, where instead we could 5935 // just use VDUPLANE. We can only do this if the lane being extracted 5936 // is at a constant index, as the VDUP from lane instructions only have 5937 // constant-index forms. 5938 ConstantSDNode *constIndex; 5939 if (Value->getOpcode() == ISD::EXTRACT_VECTOR_ELT && 5940 (constIndex = dyn_cast<ConstantSDNode>(Value->getOperand(1)))) { 5941 // We need to create a new undef vector to use for the VDUPLANE if the 5942 // size of the vector from which we get the value is different than the 5943 // size of the vector that we need to create. We will insert the element 5944 // such that the register coalescer will remove unnecessary copies. 5945 if (VT != Value->getOperand(0).getValueType()) { 5946 unsigned index = constIndex->getAPIntValue().getLimitedValue() % 5947 VT.getVectorNumElements(); 5948 N = DAG.getNode(ARMISD::VDUPLANE, dl, VT, 5949 DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, DAG.getUNDEF(VT), 5950 Value, DAG.getConstant(index, dl, MVT::i32)), 5951 DAG.getConstant(index, dl, MVT::i32)); 5952 } else 5953 N = DAG.getNode(ARMISD::VDUPLANE, dl, VT, 5954 Value->getOperand(0), Value->getOperand(1)); 5955 } else 5956 N = DAG.getNode(ARMISD::VDUP, dl, VT, Value); 5957 5958 if (!usesOnlyOneValue) { 5959 // The dominant value was splatted as 'N', but we now have to insert 5960 // all differing elements. 5961 for (unsigned I = 0; I < NumElts; ++I) { 5962 if (Op.getOperand(I) == Value) 5963 continue; 5964 SmallVector<SDValue, 3> Ops; 5965 Ops.push_back(N); 5966 Ops.push_back(Op.getOperand(I)); 5967 Ops.push_back(DAG.getConstant(I, dl, MVT::i32)); 5968 N = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Ops); 5969 } 5970 } 5971 return N; 5972 } 5973 if (VT.getVectorElementType().isFloatingPoint()) { 5974 SmallVector<SDValue, 8> Ops; 5975 for (unsigned i = 0; i < NumElts; ++i) 5976 Ops.push_back(DAG.getNode(ISD::BITCAST, dl, MVT::i32, 5977 Op.getOperand(i))); 5978 EVT VecVT = EVT::getVectorVT(*DAG.getContext(), MVT::i32, NumElts); 5979 SDValue Val = DAG.getBuildVector(VecVT, dl, Ops); 5980 Val = LowerBUILD_VECTOR(Val, DAG, ST); 5981 if (Val.getNode()) 5982 return DAG.getNode(ISD::BITCAST, dl, VT, Val); 5983 } 5984 if (usesOnlyOneValue) { 5985 SDValue Val = IsSingleInstrConstant(Value, DAG, ST, dl); 5986 if (isConstant && Val.getNode()) 5987 return DAG.getNode(ARMISD::VDUP, dl, VT, Val); 5988 } 5989 } 5990 5991 // If all elements are constants and the case above didn't get hit, fall back 5992 // to the default expansion, which will generate a load from the constant 5993 // pool. 5994 if (isConstant) 5995 return SDValue(); 5996 5997 // Empirical tests suggest this is rarely worth it for vectors of length <= 2. 5998 if (NumElts >= 4) { 5999 SDValue shuffle = ReconstructShuffle(Op, DAG); 6000 if (shuffle != SDValue()) 6001 return shuffle; 6002 } 6003 6004 // Vectors with 32- or 64-bit elements can be built by directly assigning 6005 // the subregisters. Lower it to an ARMISD::BUILD_VECTOR so the operands 6006 // will be legalized. 6007 if (EltSize >= 32) { 6008 // Do the expansion with floating-point types, since that is what the VFP 6009 // registers are defined to use, and since i64 is not legal. 6010 EVT EltVT = EVT::getFloatingPointVT(EltSize); 6011 EVT VecVT = EVT::getVectorVT(*DAG.getContext(), EltVT, NumElts); 6012 SmallVector<SDValue, 8> Ops; 6013 for (unsigned i = 0; i < NumElts; ++i) 6014 Ops.push_back(DAG.getNode(ISD::BITCAST, dl, EltVT, Op.getOperand(i))); 6015 SDValue Val = DAG.getNode(ARMISD::BUILD_VECTOR, dl, VecVT, Ops); 6016 return DAG.getNode(ISD::BITCAST, dl, VT, Val); 6017 } 6018 6019 // If all else fails, just use a sequence of INSERT_VECTOR_ELT when we 6020 // know the default expansion would otherwise fall back on something even 6021 // worse. For a vector with one or two non-undef values, that's 6022 // scalar_to_vector for the elements followed by a shuffle (provided the 6023 // shuffle is valid for the target) and materialization element by element 6024 // on the stack followed by a load for everything else. 6025 if (!isConstant && !usesOnlyOneValue) { 6026 SDValue Vec = DAG.getUNDEF(VT); 6027 for (unsigned i = 0 ; i < NumElts; ++i) { 6028 SDValue V = Op.getOperand(i); 6029 if (V.isUndef()) 6030 continue; 6031 SDValue LaneIdx = DAG.getConstant(i, dl, MVT::i32); 6032 Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Vec, V, LaneIdx); 6033 } 6034 return Vec; 6035 } 6036 6037 return SDValue(); 6038 } 6039 6040 // Gather data to see if the operation can be modelled as a 6041 // shuffle in combination with VEXTs. 6042 SDValue ARMTargetLowering::ReconstructShuffle(SDValue Op, 6043 SelectionDAG &DAG) const { 6044 assert(Op.getOpcode() == ISD::BUILD_VECTOR && "Unknown opcode!"); 6045 SDLoc dl(Op); 6046 EVT VT = Op.getValueType(); 6047 unsigned NumElts = VT.getVectorNumElements(); 6048 6049 struct ShuffleSourceInfo { 6050 SDValue Vec; 6051 unsigned MinElt; 6052 unsigned MaxElt; 6053 6054 // We may insert some combination of BITCASTs and VEXT nodes to force Vec to 6055 // be compatible with the shuffle we intend to construct. As a result 6056 // ShuffleVec will be some sliding window into the original Vec. 6057 SDValue ShuffleVec; 6058 6059 // Code should guarantee that element i in Vec starts at element "WindowBase 6060 // + i * WindowScale in ShuffleVec". 6061 int WindowBase; 6062 int WindowScale; 6063 6064 bool operator ==(SDValue OtherVec) { return Vec == OtherVec; } 6065 ShuffleSourceInfo(SDValue Vec) 6066 : Vec(Vec), MinElt(UINT_MAX), MaxElt(0), ShuffleVec(Vec), WindowBase(0), 6067 WindowScale(1) {} 6068 }; 6069 6070 // First gather all vectors used as an immediate source for this BUILD_VECTOR 6071 // node. 6072 SmallVector<ShuffleSourceInfo, 2> Sources; 6073 for (unsigned i = 0; i < NumElts; ++i) { 6074 SDValue V = Op.getOperand(i); 6075 if (V.isUndef()) 6076 continue; 6077 else if (V.getOpcode() != ISD::EXTRACT_VECTOR_ELT) { 6078 // A shuffle can only come from building a vector from various 6079 // elements of other vectors. 6080 return SDValue(); 6081 } else if (!isa<ConstantSDNode>(V.getOperand(1))) { 6082 // Furthermore, shuffles require a constant mask, whereas extractelts 6083 // accept variable indices. 6084 return SDValue(); 6085 } 6086 6087 // Add this element source to the list if it's not already there. 6088 SDValue SourceVec = V.getOperand(0); 6089 auto Source = find(Sources, SourceVec); 6090 if (Source == Sources.end()) 6091 Source = Sources.insert(Sources.end(), ShuffleSourceInfo(SourceVec)); 6092 6093 // Update the minimum and maximum lane number seen. 6094 unsigned EltNo = cast<ConstantSDNode>(V.getOperand(1))->getZExtValue(); 6095 Source->MinElt = std::min(Source->MinElt, EltNo); 6096 Source->MaxElt = std::max(Source->MaxElt, EltNo); 6097 } 6098 6099 // Currently only do something sane when at most two source vectors 6100 // are involved. 6101 if (Sources.size() > 2) 6102 return SDValue(); 6103 6104 // Find out the smallest element size among result and two sources, and use 6105 // it as element size to build the shuffle_vector. 6106 EVT SmallestEltTy = VT.getVectorElementType(); 6107 for (auto &Source : Sources) { 6108 EVT SrcEltTy = Source.Vec.getValueType().getVectorElementType(); 6109 if (SrcEltTy.bitsLT(SmallestEltTy)) 6110 SmallestEltTy = SrcEltTy; 6111 } 6112 unsigned ResMultiplier = 6113 VT.getVectorElementType().getSizeInBits() / SmallestEltTy.getSizeInBits(); 6114 NumElts = VT.getSizeInBits() / SmallestEltTy.getSizeInBits(); 6115 EVT ShuffleVT = EVT::getVectorVT(*DAG.getContext(), SmallestEltTy, NumElts); 6116 6117 // If the source vector is too wide or too narrow, we may nevertheless be able 6118 // to construct a compatible shuffle either by concatenating it with UNDEF or 6119 // extracting a suitable range of elements. 6120 for (auto &Src : Sources) { 6121 EVT SrcVT = Src.ShuffleVec.getValueType(); 6122 6123 if (SrcVT.getSizeInBits() == VT.getSizeInBits()) 6124 continue; 6125 6126 // This stage of the search produces a source with the same element type as 6127 // the original, but with a total width matching the BUILD_VECTOR output. 6128 EVT EltVT = SrcVT.getVectorElementType(); 6129 unsigned NumSrcElts = VT.getSizeInBits() / EltVT.getSizeInBits(); 6130 EVT DestVT = EVT::getVectorVT(*DAG.getContext(), EltVT, NumSrcElts); 6131 6132 if (SrcVT.getSizeInBits() < VT.getSizeInBits()) { 6133 if (2 * SrcVT.getSizeInBits() != VT.getSizeInBits()) 6134 return SDValue(); 6135 // We can pad out the smaller vector for free, so if it's part of a 6136 // shuffle... 6137 Src.ShuffleVec = 6138 DAG.getNode(ISD::CONCAT_VECTORS, dl, DestVT, Src.ShuffleVec, 6139 DAG.getUNDEF(Src.ShuffleVec.getValueType())); 6140 continue; 6141 } 6142 6143 if (SrcVT.getSizeInBits() != 2 * VT.getSizeInBits()) 6144 return SDValue(); 6145 6146 if (Src.MaxElt - Src.MinElt >= NumSrcElts) { 6147 // Span too large for a VEXT to cope 6148 return SDValue(); 6149 } 6150 6151 if (Src.MinElt >= NumSrcElts) { 6152 // The extraction can just take the second half 6153 Src.ShuffleVec = 6154 DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DestVT, Src.ShuffleVec, 6155 DAG.getConstant(NumSrcElts, dl, MVT::i32)); 6156 Src.WindowBase = -NumSrcElts; 6157 } else if (Src.MaxElt < NumSrcElts) { 6158 // The extraction can just take the first half 6159 Src.ShuffleVec = 6160 DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DestVT, Src.ShuffleVec, 6161 DAG.getConstant(0, dl, MVT::i32)); 6162 } else { 6163 // An actual VEXT is needed 6164 SDValue VEXTSrc1 = 6165 DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DestVT, Src.ShuffleVec, 6166 DAG.getConstant(0, dl, MVT::i32)); 6167 SDValue VEXTSrc2 = 6168 DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DestVT, Src.ShuffleVec, 6169 DAG.getConstant(NumSrcElts, dl, MVT::i32)); 6170 6171 Src.ShuffleVec = DAG.getNode(ARMISD::VEXT, dl, DestVT, VEXTSrc1, 6172 VEXTSrc2, 6173 DAG.getConstant(Src.MinElt, dl, MVT::i32)); 6174 Src.WindowBase = -Src.MinElt; 6175 } 6176 } 6177 6178 // Another possible incompatibility occurs from the vector element types. We 6179 // can fix this by bitcasting the source vectors to the same type we intend 6180 // for the shuffle. 6181 for (auto &Src : Sources) { 6182 EVT SrcEltTy = Src.ShuffleVec.getValueType().getVectorElementType(); 6183 if (SrcEltTy == SmallestEltTy) 6184 continue; 6185 assert(ShuffleVT.getVectorElementType() == SmallestEltTy); 6186 Src.ShuffleVec = DAG.getNode(ISD::BITCAST, dl, ShuffleVT, Src.ShuffleVec); 6187 Src.WindowScale = SrcEltTy.getSizeInBits() / SmallestEltTy.getSizeInBits(); 6188 Src.WindowBase *= Src.WindowScale; 6189 } 6190 6191 // Final sanity check before we try to actually produce a shuffle. 6192 DEBUG( 6193 for (auto Src : Sources) 6194 assert(Src.ShuffleVec.getValueType() == ShuffleVT); 6195 ); 6196 6197 // The stars all align, our next step is to produce the mask for the shuffle. 6198 SmallVector<int, 8> Mask(ShuffleVT.getVectorNumElements(), -1); 6199 int BitsPerShuffleLane = ShuffleVT.getVectorElementType().getSizeInBits(); 6200 for (unsigned i = 0; i < VT.getVectorNumElements(); ++i) { 6201 SDValue Entry = Op.getOperand(i); 6202 if (Entry.isUndef()) 6203 continue; 6204 6205 auto Src = find(Sources, Entry.getOperand(0)); 6206 int EltNo = cast<ConstantSDNode>(Entry.getOperand(1))->getSExtValue(); 6207 6208 // EXTRACT_VECTOR_ELT performs an implicit any_ext; BUILD_VECTOR an implicit 6209 // trunc. So only std::min(SrcBits, DestBits) actually get defined in this 6210 // segment. 6211 EVT OrigEltTy = Entry.getOperand(0).getValueType().getVectorElementType(); 6212 int BitsDefined = std::min(OrigEltTy.getSizeInBits(), 6213 VT.getVectorElementType().getSizeInBits()); 6214 int LanesDefined = BitsDefined / BitsPerShuffleLane; 6215 6216 // This source is expected to fill ResMultiplier lanes of the final shuffle, 6217 // starting at the appropriate offset. 6218 int *LaneMask = &Mask[i * ResMultiplier]; 6219 6220 int ExtractBase = EltNo * Src->WindowScale + Src->WindowBase; 6221 ExtractBase += NumElts * (Src - Sources.begin()); 6222 for (int j = 0; j < LanesDefined; ++j) 6223 LaneMask[j] = ExtractBase + j; 6224 } 6225 6226 // Final check before we try to produce nonsense... 6227 if (!isShuffleMaskLegal(Mask, ShuffleVT)) 6228 return SDValue(); 6229 6230 // We can't handle more than two sources. This should have already 6231 // been checked before this point. 6232 assert(Sources.size() <= 2 && "Too many sources!"); 6233 6234 SDValue ShuffleOps[] = { DAG.getUNDEF(ShuffleVT), DAG.getUNDEF(ShuffleVT) }; 6235 for (unsigned i = 0; i < Sources.size(); ++i) 6236 ShuffleOps[i] = Sources[i].ShuffleVec; 6237 6238 SDValue Shuffle = DAG.getVectorShuffle(ShuffleVT, dl, ShuffleOps[0], 6239 ShuffleOps[1], Mask); 6240 return DAG.getNode(ISD::BITCAST, dl, VT, Shuffle); 6241 } 6242 6243 /// isShuffleMaskLegal - Targets can use this to indicate that they only 6244 /// support *some* VECTOR_SHUFFLE operations, those with specific masks. 6245 /// By default, if a target supports the VECTOR_SHUFFLE node, all mask values 6246 /// are assumed to be legal. 6247 bool 6248 ARMTargetLowering::isShuffleMaskLegal(const SmallVectorImpl<int> &M, 6249 EVT VT) const { 6250 if (VT.getVectorNumElements() == 4 && 6251 (VT.is128BitVector() || VT.is64BitVector())) { 6252 unsigned PFIndexes[4]; 6253 for (unsigned i = 0; i != 4; ++i) { 6254 if (M[i] < 0) 6255 PFIndexes[i] = 8; 6256 else 6257 PFIndexes[i] = M[i]; 6258 } 6259 6260 // Compute the index in the perfect shuffle table. 6261 unsigned PFTableIndex = 6262 PFIndexes[0]*9*9*9+PFIndexes[1]*9*9+PFIndexes[2]*9+PFIndexes[3]; 6263 unsigned PFEntry = PerfectShuffleTable[PFTableIndex]; 6264 unsigned Cost = (PFEntry >> 30); 6265 6266 if (Cost <= 4) 6267 return true; 6268 } 6269 6270 bool ReverseVEXT, isV_UNDEF; 6271 unsigned Imm, WhichResult; 6272 6273 unsigned EltSize = VT.getVectorElementType().getSizeInBits(); 6274 return (EltSize >= 32 || 6275 ShuffleVectorSDNode::isSplatMask(&M[0], VT) || 6276 isVREVMask(M, VT, 64) || 6277 isVREVMask(M, VT, 32) || 6278 isVREVMask(M, VT, 16) || 6279 isVEXTMask(M, VT, ReverseVEXT, Imm) || 6280 isVTBLMask(M, VT) || 6281 isNEONTwoResultShuffleMask(M, VT, WhichResult, isV_UNDEF) || 6282 ((VT == MVT::v8i16 || VT == MVT::v16i8) && isReverseMask(M, VT))); 6283 } 6284 6285 /// GeneratePerfectShuffle - Given an entry in the perfect-shuffle table, emit 6286 /// the specified operations to build the shuffle. 6287 static SDValue GeneratePerfectShuffle(unsigned PFEntry, SDValue LHS, 6288 SDValue RHS, SelectionDAG &DAG, 6289 const SDLoc &dl) { 6290 unsigned OpNum = (PFEntry >> 26) & 0x0F; 6291 unsigned LHSID = (PFEntry >> 13) & ((1 << 13)-1); 6292 unsigned RHSID = (PFEntry >> 0) & ((1 << 13)-1); 6293 6294 enum { 6295 OP_COPY = 0, // Copy, used for things like <u,u,u,3> to say it is <0,1,2,3> 6296 OP_VREV, 6297 OP_VDUP0, 6298 OP_VDUP1, 6299 OP_VDUP2, 6300 OP_VDUP3, 6301 OP_VEXT1, 6302 OP_VEXT2, 6303 OP_VEXT3, 6304 OP_VUZPL, // VUZP, left result 6305 OP_VUZPR, // VUZP, right result 6306 OP_VZIPL, // VZIP, left result 6307 OP_VZIPR, // VZIP, right result 6308 OP_VTRNL, // VTRN, left result 6309 OP_VTRNR // VTRN, right result 6310 }; 6311 6312 if (OpNum == OP_COPY) { 6313 if (LHSID == (1*9+2)*9+3) return LHS; 6314 assert(LHSID == ((4*9+5)*9+6)*9+7 && "Illegal OP_COPY!"); 6315 return RHS; 6316 } 6317 6318 SDValue OpLHS, OpRHS; 6319 OpLHS = GeneratePerfectShuffle(PerfectShuffleTable[LHSID], LHS, RHS, DAG, dl); 6320 OpRHS = GeneratePerfectShuffle(PerfectShuffleTable[RHSID], LHS, RHS, DAG, dl); 6321 EVT VT = OpLHS.getValueType(); 6322 6323 switch (OpNum) { 6324 default: llvm_unreachable("Unknown shuffle opcode!"); 6325 case OP_VREV: 6326 // VREV divides the vector in half and swaps within the half. 6327 if (VT.getVectorElementType() == MVT::i32 || 6328 VT.getVectorElementType() == MVT::f32) 6329 return DAG.getNode(ARMISD::VREV64, dl, VT, OpLHS); 6330 // vrev <4 x i16> -> VREV32 6331 if (VT.getVectorElementType() == MVT::i16) 6332 return DAG.getNode(ARMISD::VREV32, dl, VT, OpLHS); 6333 // vrev <4 x i8> -> VREV16 6334 assert(VT.getVectorElementType() == MVT::i8); 6335 return DAG.getNode(ARMISD::VREV16, dl, VT, OpLHS); 6336 case OP_VDUP0: 6337 case OP_VDUP1: 6338 case OP_VDUP2: 6339 case OP_VDUP3: 6340 return DAG.getNode(ARMISD::VDUPLANE, dl, VT, 6341 OpLHS, DAG.getConstant(OpNum-OP_VDUP0, dl, MVT::i32)); 6342 case OP_VEXT1: 6343 case OP_VEXT2: 6344 case OP_VEXT3: 6345 return DAG.getNode(ARMISD::VEXT, dl, VT, 6346 OpLHS, OpRHS, 6347 DAG.getConstant(OpNum - OP_VEXT1 + 1, dl, MVT::i32)); 6348 case OP_VUZPL: 6349 case OP_VUZPR: 6350 return DAG.getNode(ARMISD::VUZP, dl, DAG.getVTList(VT, VT), 6351 OpLHS, OpRHS).getValue(OpNum-OP_VUZPL); 6352 case OP_VZIPL: 6353 case OP_VZIPR: 6354 return DAG.getNode(ARMISD::VZIP, dl, DAG.getVTList(VT, VT), 6355 OpLHS, OpRHS).getValue(OpNum-OP_VZIPL); 6356 case OP_VTRNL: 6357 case OP_VTRNR: 6358 return DAG.getNode(ARMISD::VTRN, dl, DAG.getVTList(VT, VT), 6359 OpLHS, OpRHS).getValue(OpNum-OP_VTRNL); 6360 } 6361 } 6362 6363 static SDValue LowerVECTOR_SHUFFLEv8i8(SDValue Op, 6364 ArrayRef<int> ShuffleMask, 6365 SelectionDAG &DAG) { 6366 // Check to see if we can use the VTBL instruction. 6367 SDValue V1 = Op.getOperand(0); 6368 SDValue V2 = Op.getOperand(1); 6369 SDLoc DL(Op); 6370 6371 SmallVector<SDValue, 8> VTBLMask; 6372 for (ArrayRef<int>::iterator 6373 I = ShuffleMask.begin(), E = ShuffleMask.end(); I != E; ++I) 6374 VTBLMask.push_back(DAG.getConstant(*I, DL, MVT::i32)); 6375 6376 if (V2.getNode()->isUndef()) 6377 return DAG.getNode(ARMISD::VTBL1, DL, MVT::v8i8, V1, 6378 DAG.getBuildVector(MVT::v8i8, DL, VTBLMask)); 6379 6380 return DAG.getNode(ARMISD::VTBL2, DL, MVT::v8i8, V1, V2, 6381 DAG.getBuildVector(MVT::v8i8, DL, VTBLMask)); 6382 } 6383 6384 static SDValue LowerReverse_VECTOR_SHUFFLEv16i8_v8i16(SDValue Op, 6385 SelectionDAG &DAG) { 6386 SDLoc DL(Op); 6387 SDValue OpLHS = Op.getOperand(0); 6388 EVT VT = OpLHS.getValueType(); 6389 6390 assert((VT == MVT::v8i16 || VT == MVT::v16i8) && 6391 "Expect an v8i16/v16i8 type"); 6392 OpLHS = DAG.getNode(ARMISD::VREV64, DL, VT, OpLHS); 6393 // For a v16i8 type: After the VREV, we have got <8, ...15, 8, ..., 0>. Now, 6394 // extract the first 8 bytes into the top double word and the last 8 bytes 6395 // into the bottom double word. The v8i16 case is similar. 6396 unsigned ExtractNum = (VT == MVT::v16i8) ? 8 : 4; 6397 return DAG.getNode(ARMISD::VEXT, DL, VT, OpLHS, OpLHS, 6398 DAG.getConstant(ExtractNum, DL, MVT::i32)); 6399 } 6400 6401 static SDValue LowerVECTOR_SHUFFLE(SDValue Op, SelectionDAG &DAG) { 6402 SDValue V1 = Op.getOperand(0); 6403 SDValue V2 = Op.getOperand(1); 6404 SDLoc dl(Op); 6405 EVT VT = Op.getValueType(); 6406 ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(Op.getNode()); 6407 6408 // Convert shuffles that are directly supported on NEON to target-specific 6409 // DAG nodes, instead of keeping them as shuffles and matching them again 6410 // during code selection. This is more efficient and avoids the possibility 6411 // of inconsistencies between legalization and selection. 6412 // FIXME: floating-point vectors should be canonicalized to integer vectors 6413 // of the same time so that they get CSEd properly. 6414 ArrayRef<int> ShuffleMask = SVN->getMask(); 6415 6416 unsigned EltSize = VT.getVectorElementType().getSizeInBits(); 6417 if (EltSize <= 32) { 6418 if (SVN->isSplat()) { 6419 int Lane = SVN->getSplatIndex(); 6420 // If this is undef splat, generate it via "just" vdup, if possible. 6421 if (Lane == -1) Lane = 0; 6422 6423 // Test if V1 is a SCALAR_TO_VECTOR. 6424 if (Lane == 0 && V1.getOpcode() == ISD::SCALAR_TO_VECTOR) { 6425 return DAG.getNode(ARMISD::VDUP, dl, VT, V1.getOperand(0)); 6426 } 6427 // Test if V1 is a BUILD_VECTOR which is equivalent to a SCALAR_TO_VECTOR 6428 // (and probably will turn into a SCALAR_TO_VECTOR once legalization 6429 // reaches it). 6430 if (Lane == 0 && V1.getOpcode() == ISD::BUILD_VECTOR && 6431 !isa<ConstantSDNode>(V1.getOperand(0))) { 6432 bool IsScalarToVector = true; 6433 for (unsigned i = 1, e = V1.getNumOperands(); i != e; ++i) 6434 if (!V1.getOperand(i).isUndef()) { 6435 IsScalarToVector = false; 6436 break; 6437 } 6438 if (IsScalarToVector) 6439 return DAG.getNode(ARMISD::VDUP, dl, VT, V1.getOperand(0)); 6440 } 6441 return DAG.getNode(ARMISD::VDUPLANE, dl, VT, V1, 6442 DAG.getConstant(Lane, dl, MVT::i32)); 6443 } 6444 6445 bool ReverseVEXT; 6446 unsigned Imm; 6447 if (isVEXTMask(ShuffleMask, VT, ReverseVEXT, Imm)) { 6448 if (ReverseVEXT) 6449 std::swap(V1, V2); 6450 return DAG.getNode(ARMISD::VEXT, dl, VT, V1, V2, 6451 DAG.getConstant(Imm, dl, MVT::i32)); 6452 } 6453 6454 if (isVREVMask(ShuffleMask, VT, 64)) 6455 return DAG.getNode(ARMISD::VREV64, dl, VT, V1); 6456 if (isVREVMask(ShuffleMask, VT, 32)) 6457 return DAG.getNode(ARMISD::VREV32, dl, VT, V1); 6458 if (isVREVMask(ShuffleMask, VT, 16)) 6459 return DAG.getNode(ARMISD::VREV16, dl, VT, V1); 6460 6461 if (V2->isUndef() && isSingletonVEXTMask(ShuffleMask, VT, Imm)) { 6462 return DAG.getNode(ARMISD::VEXT, dl, VT, V1, V1, 6463 DAG.getConstant(Imm, dl, MVT::i32)); 6464 } 6465 6466 // Check for Neon shuffles that modify both input vectors in place. 6467 // If both results are used, i.e., if there are two shuffles with the same 6468 // source operands and with masks corresponding to both results of one of 6469 // these operations, DAG memoization will ensure that a single node is 6470 // used for both shuffles. 6471 unsigned WhichResult; 6472 bool isV_UNDEF; 6473 if (unsigned ShuffleOpc = isNEONTwoResultShuffleMask( 6474 ShuffleMask, VT, WhichResult, isV_UNDEF)) { 6475 if (isV_UNDEF) 6476 V2 = V1; 6477 return DAG.getNode(ShuffleOpc, dl, DAG.getVTList(VT, VT), V1, V2) 6478 .getValue(WhichResult); 6479 } 6480 6481 // Also check for these shuffles through CONCAT_VECTORS: we canonicalize 6482 // shuffles that produce a result larger than their operands with: 6483 // shuffle(concat(v1, undef), concat(v2, undef)) 6484 // -> 6485 // shuffle(concat(v1, v2), undef) 6486 // because we can access quad vectors (see PerformVECTOR_SHUFFLECombine). 6487 // 6488 // This is useful in the general case, but there are special cases where 6489 // native shuffles produce larger results: the two-result ops. 6490 // 6491 // Look through the concat when lowering them: 6492 // shuffle(concat(v1, v2), undef) 6493 // -> 6494 // concat(VZIP(v1, v2):0, :1) 6495 // 6496 if (V1->getOpcode() == ISD::CONCAT_VECTORS && V2->isUndef()) { 6497 SDValue SubV1 = V1->getOperand(0); 6498 SDValue SubV2 = V1->getOperand(1); 6499 EVT SubVT = SubV1.getValueType(); 6500 6501 // We expect these to have been canonicalized to -1. 6502 assert(all_of(ShuffleMask, [&](int i) { 6503 return i < (int)VT.getVectorNumElements(); 6504 }) && "Unexpected shuffle index into UNDEF operand!"); 6505 6506 if (unsigned ShuffleOpc = isNEONTwoResultShuffleMask( 6507 ShuffleMask, SubVT, WhichResult, isV_UNDEF)) { 6508 if (isV_UNDEF) 6509 SubV2 = SubV1; 6510 assert((WhichResult == 0) && 6511 "In-place shuffle of concat can only have one result!"); 6512 SDValue Res = DAG.getNode(ShuffleOpc, dl, DAG.getVTList(SubVT, SubVT), 6513 SubV1, SubV2); 6514 return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, Res.getValue(0), 6515 Res.getValue(1)); 6516 } 6517 } 6518 } 6519 6520 // If the shuffle is not directly supported and it has 4 elements, use 6521 // the PerfectShuffle-generated table to synthesize it from other shuffles. 6522 unsigned NumElts = VT.getVectorNumElements(); 6523 if (NumElts == 4) { 6524 unsigned PFIndexes[4]; 6525 for (unsigned i = 0; i != 4; ++i) { 6526 if (ShuffleMask[i] < 0) 6527 PFIndexes[i] = 8; 6528 else 6529 PFIndexes[i] = ShuffleMask[i]; 6530 } 6531 6532 // Compute the index in the perfect shuffle table. 6533 unsigned PFTableIndex = 6534 PFIndexes[0]*9*9*9+PFIndexes[1]*9*9+PFIndexes[2]*9+PFIndexes[3]; 6535 unsigned PFEntry = PerfectShuffleTable[PFTableIndex]; 6536 unsigned Cost = (PFEntry >> 30); 6537 6538 if (Cost <= 4) 6539 return GeneratePerfectShuffle(PFEntry, V1, V2, DAG, dl); 6540 } 6541 6542 // Implement shuffles with 32- or 64-bit elements as ARMISD::BUILD_VECTORs. 6543 if (EltSize >= 32) { 6544 // Do the expansion with floating-point types, since that is what the VFP 6545 // registers are defined to use, and since i64 is not legal. 6546 EVT EltVT = EVT::getFloatingPointVT(EltSize); 6547 EVT VecVT = EVT::getVectorVT(*DAG.getContext(), EltVT, NumElts); 6548 V1 = DAG.getNode(ISD::BITCAST, dl, VecVT, V1); 6549 V2 = DAG.getNode(ISD::BITCAST, dl, VecVT, V2); 6550 SmallVector<SDValue, 8> Ops; 6551 for (unsigned i = 0; i < NumElts; ++i) { 6552 if (ShuffleMask[i] < 0) 6553 Ops.push_back(DAG.getUNDEF(EltVT)); 6554 else 6555 Ops.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, EltVT, 6556 ShuffleMask[i] < (int)NumElts ? V1 : V2, 6557 DAG.getConstant(ShuffleMask[i] & (NumElts-1), 6558 dl, MVT::i32))); 6559 } 6560 SDValue Val = DAG.getNode(ARMISD::BUILD_VECTOR, dl, VecVT, Ops); 6561 return DAG.getNode(ISD::BITCAST, dl, VT, Val); 6562 } 6563 6564 if ((VT == MVT::v8i16 || VT == MVT::v16i8) && isReverseMask(ShuffleMask, VT)) 6565 return LowerReverse_VECTOR_SHUFFLEv16i8_v8i16(Op, DAG); 6566 6567 if (VT == MVT::v8i8) 6568 if (SDValue NewOp = LowerVECTOR_SHUFFLEv8i8(Op, ShuffleMask, DAG)) 6569 return NewOp; 6570 6571 return SDValue(); 6572 } 6573 6574 static SDValue LowerINSERT_VECTOR_ELT(SDValue Op, SelectionDAG &DAG) { 6575 // INSERT_VECTOR_ELT is legal only for immediate indexes. 6576 SDValue Lane = Op.getOperand(2); 6577 if (!isa<ConstantSDNode>(Lane)) 6578 return SDValue(); 6579 6580 return Op; 6581 } 6582 6583 static SDValue LowerEXTRACT_VECTOR_ELT(SDValue Op, SelectionDAG &DAG) { 6584 // EXTRACT_VECTOR_ELT is legal only for immediate indexes. 6585 SDValue Lane = Op.getOperand(1); 6586 if (!isa<ConstantSDNode>(Lane)) 6587 return SDValue(); 6588 6589 SDValue Vec = Op.getOperand(0); 6590 if (Op.getValueType() == MVT::i32 && 6591 Vec.getValueType().getVectorElementType().getSizeInBits() < 32) { 6592 SDLoc dl(Op); 6593 return DAG.getNode(ARMISD::VGETLANEu, dl, MVT::i32, Vec, Lane); 6594 } 6595 6596 return Op; 6597 } 6598 6599 static SDValue LowerCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG) { 6600 // The only time a CONCAT_VECTORS operation can have legal types is when 6601 // two 64-bit vectors are concatenated to a 128-bit vector. 6602 assert(Op.getValueType().is128BitVector() && Op.getNumOperands() == 2 && 6603 "unexpected CONCAT_VECTORS"); 6604 SDLoc dl(Op); 6605 SDValue Val = DAG.getUNDEF(MVT::v2f64); 6606 SDValue Op0 = Op.getOperand(0); 6607 SDValue Op1 = Op.getOperand(1); 6608 if (!Op0.isUndef()) 6609 Val = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Val, 6610 DAG.getNode(ISD::BITCAST, dl, MVT::f64, Op0), 6611 DAG.getIntPtrConstant(0, dl)); 6612 if (!Op1.isUndef()) 6613 Val = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Val, 6614 DAG.getNode(ISD::BITCAST, dl, MVT::f64, Op1), 6615 DAG.getIntPtrConstant(1, dl)); 6616 return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Val); 6617 } 6618 6619 /// isExtendedBUILD_VECTOR - Check if N is a constant BUILD_VECTOR where each 6620 /// element has been zero/sign-extended, depending on the isSigned parameter, 6621 /// from an integer type half its size. 6622 static bool isExtendedBUILD_VECTOR(SDNode *N, SelectionDAG &DAG, 6623 bool isSigned) { 6624 // A v2i64 BUILD_VECTOR will have been legalized to a BITCAST from v4i32. 6625 EVT VT = N->getValueType(0); 6626 if (VT == MVT::v2i64 && N->getOpcode() == ISD::BITCAST) { 6627 SDNode *BVN = N->getOperand(0).getNode(); 6628 if (BVN->getValueType(0) != MVT::v4i32 || 6629 BVN->getOpcode() != ISD::BUILD_VECTOR) 6630 return false; 6631 unsigned LoElt = DAG.getDataLayout().isBigEndian() ? 1 : 0; 6632 unsigned HiElt = 1 - LoElt; 6633 ConstantSDNode *Lo0 = dyn_cast<ConstantSDNode>(BVN->getOperand(LoElt)); 6634 ConstantSDNode *Hi0 = dyn_cast<ConstantSDNode>(BVN->getOperand(HiElt)); 6635 ConstantSDNode *Lo1 = dyn_cast<ConstantSDNode>(BVN->getOperand(LoElt+2)); 6636 ConstantSDNode *Hi1 = dyn_cast<ConstantSDNode>(BVN->getOperand(HiElt+2)); 6637 if (!Lo0 || !Hi0 || !Lo1 || !Hi1) 6638 return false; 6639 if (isSigned) { 6640 if (Hi0->getSExtValue() == Lo0->getSExtValue() >> 32 && 6641 Hi1->getSExtValue() == Lo1->getSExtValue() >> 32) 6642 return true; 6643 } else { 6644 if (Hi0->isNullValue() && Hi1->isNullValue()) 6645 return true; 6646 } 6647 return false; 6648 } 6649 6650 if (N->getOpcode() != ISD::BUILD_VECTOR) 6651 return false; 6652 6653 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) { 6654 SDNode *Elt = N->getOperand(i).getNode(); 6655 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Elt)) { 6656 unsigned EltSize = VT.getVectorElementType().getSizeInBits(); 6657 unsigned HalfSize = EltSize / 2; 6658 if (isSigned) { 6659 if (!isIntN(HalfSize, C->getSExtValue())) 6660 return false; 6661 } else { 6662 if (!isUIntN(HalfSize, C->getZExtValue())) 6663 return false; 6664 } 6665 continue; 6666 } 6667 return false; 6668 } 6669 6670 return true; 6671 } 6672 6673 /// isSignExtended - Check if a node is a vector value that is sign-extended 6674 /// or a constant BUILD_VECTOR with sign-extended elements. 6675 static bool isSignExtended(SDNode *N, SelectionDAG &DAG) { 6676 if (N->getOpcode() == ISD::SIGN_EXTEND || ISD::isSEXTLoad(N)) 6677 return true; 6678 if (isExtendedBUILD_VECTOR(N, DAG, true)) 6679 return true; 6680 return false; 6681 } 6682 6683 /// isZeroExtended - Check if a node is a vector value that is zero-extended 6684 /// or a constant BUILD_VECTOR with zero-extended elements. 6685 static bool isZeroExtended(SDNode *N, SelectionDAG &DAG) { 6686 if (N->getOpcode() == ISD::ZERO_EXTEND || ISD::isZEXTLoad(N)) 6687 return true; 6688 if (isExtendedBUILD_VECTOR(N, DAG, false)) 6689 return true; 6690 return false; 6691 } 6692 6693 static EVT getExtensionTo64Bits(const EVT &OrigVT) { 6694 if (OrigVT.getSizeInBits() >= 64) 6695 return OrigVT; 6696 6697 assert(OrigVT.isSimple() && "Expecting a simple value type"); 6698 6699 MVT::SimpleValueType OrigSimpleTy = OrigVT.getSimpleVT().SimpleTy; 6700 switch (OrigSimpleTy) { 6701 default: llvm_unreachable("Unexpected Vector Type"); 6702 case MVT::v2i8: 6703 case MVT::v2i16: 6704 return MVT::v2i32; 6705 case MVT::v4i8: 6706 return MVT::v4i16; 6707 } 6708 } 6709 6710 /// AddRequiredExtensionForVMULL - Add a sign/zero extension to extend the total 6711 /// value size to 64 bits. We need a 64-bit D register as an operand to VMULL. 6712 /// We insert the required extension here to get the vector to fill a D register. 6713 static SDValue AddRequiredExtensionForVMULL(SDValue N, SelectionDAG &DAG, 6714 const EVT &OrigTy, 6715 const EVT &ExtTy, 6716 unsigned ExtOpcode) { 6717 // The vector originally had a size of OrigTy. It was then extended to ExtTy. 6718 // We expect the ExtTy to be 128-bits total. If the OrigTy is less than 6719 // 64-bits we need to insert a new extension so that it will be 64-bits. 6720 assert(ExtTy.is128BitVector() && "Unexpected extension size"); 6721 if (OrigTy.getSizeInBits() >= 64) 6722 return N; 6723 6724 // Must extend size to at least 64 bits to be used as an operand for VMULL. 6725 EVT NewVT = getExtensionTo64Bits(OrigTy); 6726 6727 return DAG.getNode(ExtOpcode, SDLoc(N), NewVT, N); 6728 } 6729 6730 /// SkipLoadExtensionForVMULL - return a load of the original vector size that 6731 /// does not do any sign/zero extension. If the original vector is less 6732 /// than 64 bits, an appropriate extension will be added after the load to 6733 /// reach a total size of 64 bits. We have to add the extension separately 6734 /// because ARM does not have a sign/zero extending load for vectors. 6735 static SDValue SkipLoadExtensionForVMULL(LoadSDNode *LD, SelectionDAG& DAG) { 6736 EVT ExtendedTy = getExtensionTo64Bits(LD->getMemoryVT()); 6737 6738 // The load already has the right type. 6739 if (ExtendedTy == LD->getMemoryVT()) 6740 return DAG.getLoad(LD->getMemoryVT(), SDLoc(LD), LD->getChain(), 6741 LD->getBasePtr(), LD->getPointerInfo(), 6742 LD->getAlignment(), LD->getMemOperand()->getFlags()); 6743 6744 // We need to create a zextload/sextload. We cannot just create a load 6745 // followed by a zext/zext node because LowerMUL is also run during normal 6746 // operation legalization where we can't create illegal types. 6747 return DAG.getExtLoad(LD->getExtensionType(), SDLoc(LD), ExtendedTy, 6748 LD->getChain(), LD->getBasePtr(), LD->getPointerInfo(), 6749 LD->getMemoryVT(), LD->getAlignment(), 6750 LD->getMemOperand()->getFlags()); 6751 } 6752 6753 /// SkipExtensionForVMULL - For a node that is a SIGN_EXTEND, ZERO_EXTEND, 6754 /// extending load, or BUILD_VECTOR with extended elements, return the 6755 /// unextended value. The unextended vector should be 64 bits so that it can 6756 /// be used as an operand to a VMULL instruction. If the original vector size 6757 /// before extension is less than 64 bits we add a an extension to resize 6758 /// the vector to 64 bits. 6759 static SDValue SkipExtensionForVMULL(SDNode *N, SelectionDAG &DAG) { 6760 if (N->getOpcode() == ISD::SIGN_EXTEND || N->getOpcode() == ISD::ZERO_EXTEND) 6761 return AddRequiredExtensionForVMULL(N->getOperand(0), DAG, 6762 N->getOperand(0)->getValueType(0), 6763 N->getValueType(0), 6764 N->getOpcode()); 6765 6766 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) 6767 return SkipLoadExtensionForVMULL(LD, DAG); 6768 6769 // Otherwise, the value must be a BUILD_VECTOR. For v2i64, it will 6770 // have been legalized as a BITCAST from v4i32. 6771 if (N->getOpcode() == ISD::BITCAST) { 6772 SDNode *BVN = N->getOperand(0).getNode(); 6773 assert(BVN->getOpcode() == ISD::BUILD_VECTOR && 6774 BVN->getValueType(0) == MVT::v4i32 && "expected v4i32 BUILD_VECTOR"); 6775 unsigned LowElt = DAG.getDataLayout().isBigEndian() ? 1 : 0; 6776 return DAG.getBuildVector( 6777 MVT::v2i32, SDLoc(N), 6778 {BVN->getOperand(LowElt), BVN->getOperand(LowElt + 2)}); 6779 } 6780 // Construct a new BUILD_VECTOR with elements truncated to half the size. 6781 assert(N->getOpcode() == ISD::BUILD_VECTOR && "expected BUILD_VECTOR"); 6782 EVT VT = N->getValueType(0); 6783 unsigned EltSize = VT.getVectorElementType().getSizeInBits() / 2; 6784 unsigned NumElts = VT.getVectorNumElements(); 6785 MVT TruncVT = MVT::getIntegerVT(EltSize); 6786 SmallVector<SDValue, 8> Ops; 6787 SDLoc dl(N); 6788 for (unsigned i = 0; i != NumElts; ++i) { 6789 ConstantSDNode *C = cast<ConstantSDNode>(N->getOperand(i)); 6790 const APInt &CInt = C->getAPIntValue(); 6791 // Element types smaller than 32 bits are not legal, so use i32 elements. 6792 // The values are implicitly truncated so sext vs. zext doesn't matter. 6793 Ops.push_back(DAG.getConstant(CInt.zextOrTrunc(32), dl, MVT::i32)); 6794 } 6795 return DAG.getBuildVector(MVT::getVectorVT(TruncVT, NumElts), dl, Ops); 6796 } 6797 6798 static bool isAddSubSExt(SDNode *N, SelectionDAG &DAG) { 6799 unsigned Opcode = N->getOpcode(); 6800 if (Opcode == ISD::ADD || Opcode == ISD::SUB) { 6801 SDNode *N0 = N->getOperand(0).getNode(); 6802 SDNode *N1 = N->getOperand(1).getNode(); 6803 return N0->hasOneUse() && N1->hasOneUse() && 6804 isSignExtended(N0, DAG) && isSignExtended(N1, DAG); 6805 } 6806 return false; 6807 } 6808 6809 static bool isAddSubZExt(SDNode *N, SelectionDAG &DAG) { 6810 unsigned Opcode = N->getOpcode(); 6811 if (Opcode == ISD::ADD || Opcode == ISD::SUB) { 6812 SDNode *N0 = N->getOperand(0).getNode(); 6813 SDNode *N1 = N->getOperand(1).getNode(); 6814 return N0->hasOneUse() && N1->hasOneUse() && 6815 isZeroExtended(N0, DAG) && isZeroExtended(N1, DAG); 6816 } 6817 return false; 6818 } 6819 6820 static SDValue LowerMUL(SDValue Op, SelectionDAG &DAG) { 6821 // Multiplications are only custom-lowered for 128-bit vectors so that 6822 // VMULL can be detected. Otherwise v2i64 multiplications are not legal. 6823 EVT VT = Op.getValueType(); 6824 assert(VT.is128BitVector() && VT.isInteger() && 6825 "unexpected type for custom-lowering ISD::MUL"); 6826 SDNode *N0 = Op.getOperand(0).getNode(); 6827 SDNode *N1 = Op.getOperand(1).getNode(); 6828 unsigned NewOpc = 0; 6829 bool isMLA = false; 6830 bool isN0SExt = isSignExtended(N0, DAG); 6831 bool isN1SExt = isSignExtended(N1, DAG); 6832 if (isN0SExt && isN1SExt) 6833 NewOpc = ARMISD::VMULLs; 6834 else { 6835 bool isN0ZExt = isZeroExtended(N0, DAG); 6836 bool isN1ZExt = isZeroExtended(N1, DAG); 6837 if (isN0ZExt && isN1ZExt) 6838 NewOpc = ARMISD::VMULLu; 6839 else if (isN1SExt || isN1ZExt) { 6840 // Look for (s/zext A + s/zext B) * (s/zext C). We want to turn these 6841 // into (s/zext A * s/zext C) + (s/zext B * s/zext C) 6842 if (isN1SExt && isAddSubSExt(N0, DAG)) { 6843 NewOpc = ARMISD::VMULLs; 6844 isMLA = true; 6845 } else if (isN1ZExt && isAddSubZExt(N0, DAG)) { 6846 NewOpc = ARMISD::VMULLu; 6847 isMLA = true; 6848 } else if (isN0ZExt && isAddSubZExt(N1, DAG)) { 6849 std::swap(N0, N1); 6850 NewOpc = ARMISD::VMULLu; 6851 isMLA = true; 6852 } 6853 } 6854 6855 if (!NewOpc) { 6856 if (VT == MVT::v2i64) 6857 // Fall through to expand this. It is not legal. 6858 return SDValue(); 6859 else 6860 // Other vector multiplications are legal. 6861 return Op; 6862 } 6863 } 6864 6865 // Legalize to a VMULL instruction. 6866 SDLoc DL(Op); 6867 SDValue Op0; 6868 SDValue Op1 = SkipExtensionForVMULL(N1, DAG); 6869 if (!isMLA) { 6870 Op0 = SkipExtensionForVMULL(N0, DAG); 6871 assert(Op0.getValueType().is64BitVector() && 6872 Op1.getValueType().is64BitVector() && 6873 "unexpected types for extended operands to VMULL"); 6874 return DAG.getNode(NewOpc, DL, VT, Op0, Op1); 6875 } 6876 6877 // Optimizing (zext A + zext B) * C, to (VMULL A, C) + (VMULL B, C) during 6878 // isel lowering to take advantage of no-stall back to back vmul + vmla. 6879 // vmull q0, d4, d6 6880 // vmlal q0, d5, d6 6881 // is faster than 6882 // vaddl q0, d4, d5 6883 // vmovl q1, d6 6884 // vmul q0, q0, q1 6885 SDValue N00 = SkipExtensionForVMULL(N0->getOperand(0).getNode(), DAG); 6886 SDValue N01 = SkipExtensionForVMULL(N0->getOperand(1).getNode(), DAG); 6887 EVT Op1VT = Op1.getValueType(); 6888 return DAG.getNode(N0->getOpcode(), DL, VT, 6889 DAG.getNode(NewOpc, DL, VT, 6890 DAG.getNode(ISD::BITCAST, DL, Op1VT, N00), Op1), 6891 DAG.getNode(NewOpc, DL, VT, 6892 DAG.getNode(ISD::BITCAST, DL, Op1VT, N01), Op1)); 6893 } 6894 6895 static SDValue LowerSDIV_v4i8(SDValue X, SDValue Y, const SDLoc &dl, 6896 SelectionDAG &DAG) { 6897 // TODO: Should this propagate fast-math-flags? 6898 6899 // Convert to float 6900 // float4 xf = vcvt_f32_s32(vmovl_s16(a.lo)); 6901 // float4 yf = vcvt_f32_s32(vmovl_s16(b.lo)); 6902 X = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, X); 6903 Y = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, Y); 6904 X = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, X); 6905 Y = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, Y); 6906 // Get reciprocal estimate. 6907 // float4 recip = vrecpeq_f32(yf); 6908 Y = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32, 6909 DAG.getConstant(Intrinsic::arm_neon_vrecpe, dl, MVT::i32), 6910 Y); 6911 // Because char has a smaller range than uchar, we can actually get away 6912 // without any newton steps. This requires that we use a weird bias 6913 // of 0xb000, however (again, this has been exhaustively tested). 6914 // float4 result = as_float4(as_int4(xf*recip) + 0xb000); 6915 X = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, X, Y); 6916 X = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, X); 6917 Y = DAG.getConstant(0xb000, dl, MVT::v4i32); 6918 X = DAG.getNode(ISD::ADD, dl, MVT::v4i32, X, Y); 6919 X = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, X); 6920 // Convert back to short. 6921 X = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::v4i32, X); 6922 X = DAG.getNode(ISD::TRUNCATE, dl, MVT::v4i16, X); 6923 return X; 6924 } 6925 6926 static SDValue LowerSDIV_v4i16(SDValue N0, SDValue N1, const SDLoc &dl, 6927 SelectionDAG &DAG) { 6928 // TODO: Should this propagate fast-math-flags? 6929 6930 SDValue N2; 6931 // Convert to float. 6932 // float4 yf = vcvt_f32_s32(vmovl_s16(y)); 6933 // float4 xf = vcvt_f32_s32(vmovl_s16(x)); 6934 N0 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, N0); 6935 N1 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, N1); 6936 N0 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N0); 6937 N1 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N1); 6938 6939 // Use reciprocal estimate and one refinement step. 6940 // float4 recip = vrecpeq_f32(yf); 6941 // recip *= vrecpsq_f32(yf, recip); 6942 N2 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32, 6943 DAG.getConstant(Intrinsic::arm_neon_vrecpe, dl, MVT::i32), 6944 N1); 6945 N1 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32, 6946 DAG.getConstant(Intrinsic::arm_neon_vrecps, dl, MVT::i32), 6947 N1, N2); 6948 N2 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N1, N2); 6949 // Because short has a smaller range than ushort, we can actually get away 6950 // with only a single newton step. This requires that we use a weird bias 6951 // of 89, however (again, this has been exhaustively tested). 6952 // float4 result = as_float4(as_int4(xf*recip) + 0x89); 6953 N0 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N0, N2); 6954 N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, N0); 6955 N1 = DAG.getConstant(0x89, dl, MVT::v4i32); 6956 N0 = DAG.getNode(ISD::ADD, dl, MVT::v4i32, N0, N1); 6957 N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, N0); 6958 // Convert back to integer and return. 6959 // return vmovn_s32(vcvt_s32_f32(result)); 6960 N0 = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::v4i32, N0); 6961 N0 = DAG.getNode(ISD::TRUNCATE, dl, MVT::v4i16, N0); 6962 return N0; 6963 } 6964 6965 static SDValue LowerSDIV(SDValue Op, SelectionDAG &DAG) { 6966 EVT VT = Op.getValueType(); 6967 assert((VT == MVT::v4i16 || VT == MVT::v8i8) && 6968 "unexpected type for custom-lowering ISD::SDIV"); 6969 6970 SDLoc dl(Op); 6971 SDValue N0 = Op.getOperand(0); 6972 SDValue N1 = Op.getOperand(1); 6973 SDValue N2, N3; 6974 6975 if (VT == MVT::v8i8) { 6976 N0 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v8i16, N0); 6977 N1 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v8i16, N1); 6978 6979 N2 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0, 6980 DAG.getIntPtrConstant(4, dl)); 6981 N3 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1, 6982 DAG.getIntPtrConstant(4, dl)); 6983 N0 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0, 6984 DAG.getIntPtrConstant(0, dl)); 6985 N1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1, 6986 DAG.getIntPtrConstant(0, dl)); 6987 6988 N0 = LowerSDIV_v4i8(N0, N1, dl, DAG); // v4i16 6989 N2 = LowerSDIV_v4i8(N2, N3, dl, DAG); // v4i16 6990 6991 N0 = DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v8i16, N0, N2); 6992 N0 = LowerCONCAT_VECTORS(N0, DAG); 6993 6994 N0 = DAG.getNode(ISD::TRUNCATE, dl, MVT::v8i8, N0); 6995 return N0; 6996 } 6997 return LowerSDIV_v4i16(N0, N1, dl, DAG); 6998 } 6999 7000 static SDValue LowerUDIV(SDValue Op, SelectionDAG &DAG) { 7001 // TODO: Should this propagate fast-math-flags? 7002 EVT VT = Op.getValueType(); 7003 assert((VT == MVT::v4i16 || VT == MVT::v8i8) && 7004 "unexpected type for custom-lowering ISD::UDIV"); 7005 7006 SDLoc dl(Op); 7007 SDValue N0 = Op.getOperand(0); 7008 SDValue N1 = Op.getOperand(1); 7009 SDValue N2, N3; 7010 7011 if (VT == MVT::v8i8) { 7012 N0 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v8i16, N0); 7013 N1 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v8i16, N1); 7014 7015 N2 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0, 7016 DAG.getIntPtrConstant(4, dl)); 7017 N3 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1, 7018 DAG.getIntPtrConstant(4, dl)); 7019 N0 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0, 7020 DAG.getIntPtrConstant(0, dl)); 7021 N1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1, 7022 DAG.getIntPtrConstant(0, dl)); 7023 7024 N0 = LowerSDIV_v4i16(N0, N1, dl, DAG); // v4i16 7025 N2 = LowerSDIV_v4i16(N2, N3, dl, DAG); // v4i16 7026 7027 N0 = DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v8i16, N0, N2); 7028 N0 = LowerCONCAT_VECTORS(N0, DAG); 7029 7030 N0 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v8i8, 7031 DAG.getConstant(Intrinsic::arm_neon_vqmovnsu, dl, 7032 MVT::i32), 7033 N0); 7034 return N0; 7035 } 7036 7037 // v4i16 sdiv ... Convert to float. 7038 // float4 yf = vcvt_f32_s32(vmovl_u16(y)); 7039 // float4 xf = vcvt_f32_s32(vmovl_u16(x)); 7040 N0 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v4i32, N0); 7041 N1 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v4i32, N1); 7042 N0 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N0); 7043 SDValue BN1 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N1); 7044 7045 // Use reciprocal estimate and two refinement steps. 7046 // float4 recip = vrecpeq_f32(yf); 7047 // recip *= vrecpsq_f32(yf, recip); 7048 // recip *= vrecpsq_f32(yf, recip); 7049 N2 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32, 7050 DAG.getConstant(Intrinsic::arm_neon_vrecpe, dl, MVT::i32), 7051 BN1); 7052 N1 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32, 7053 DAG.getConstant(Intrinsic::arm_neon_vrecps, dl, MVT::i32), 7054 BN1, N2); 7055 N2 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N1, N2); 7056 N1 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32, 7057 DAG.getConstant(Intrinsic::arm_neon_vrecps, dl, MVT::i32), 7058 BN1, N2); 7059 N2 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N1, N2); 7060 // Simply multiplying by the reciprocal estimate can leave us a few ulps 7061 // too low, so we add 2 ulps (exhaustive testing shows that this is enough, 7062 // and that it will never cause us to return an answer too large). 7063 // float4 result = as_float4(as_int4(xf*recip) + 2); 7064 N0 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N0, N2); 7065 N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, N0); 7066 N1 = DAG.getConstant(2, dl, MVT::v4i32); 7067 N0 = DAG.getNode(ISD::ADD, dl, MVT::v4i32, N0, N1); 7068 N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, N0); 7069 // Convert back to integer and return. 7070 // return vmovn_u32(vcvt_s32_f32(result)); 7071 N0 = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::v4i32, N0); 7072 N0 = DAG.getNode(ISD::TRUNCATE, dl, MVT::v4i16, N0); 7073 return N0; 7074 } 7075 7076 static SDValue LowerADDC_ADDE_SUBC_SUBE(SDValue Op, SelectionDAG &DAG) { 7077 EVT VT = Op.getNode()->getValueType(0); 7078 SDVTList VTs = DAG.getVTList(VT, MVT::i32); 7079 7080 unsigned Opc; 7081 bool ExtraOp = false; 7082 switch (Op.getOpcode()) { 7083 default: llvm_unreachable("Invalid code"); 7084 case ISD::ADDC: Opc = ARMISD::ADDC; break; 7085 case ISD::ADDE: Opc = ARMISD::ADDE; ExtraOp = true; break; 7086 case ISD::SUBC: Opc = ARMISD::SUBC; break; 7087 case ISD::SUBE: Opc = ARMISD::SUBE; ExtraOp = true; break; 7088 } 7089 7090 if (!ExtraOp) 7091 return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0), 7092 Op.getOperand(1)); 7093 return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0), 7094 Op.getOperand(1), Op.getOperand(2)); 7095 } 7096 7097 SDValue ARMTargetLowering::LowerFSINCOS(SDValue Op, SelectionDAG &DAG) const { 7098 assert(Subtarget->isTargetDarwin()); 7099 7100 // For iOS, we want to call an alternative entry point: __sincos_stret, 7101 // return values are passed via sret. 7102 SDLoc dl(Op); 7103 SDValue Arg = Op.getOperand(0); 7104 EVT ArgVT = Arg.getValueType(); 7105 Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext()); 7106 auto PtrVT = getPointerTy(DAG.getDataLayout()); 7107 7108 MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo(); 7109 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 7110 7111 // Pair of floats / doubles used to pass the result. 7112 Type *RetTy = StructType::get(ArgTy, ArgTy, nullptr); 7113 auto &DL = DAG.getDataLayout(); 7114 7115 ArgListTy Args; 7116 bool ShouldUseSRet = Subtarget->isAPCS_ABI(); 7117 SDValue SRet; 7118 if (ShouldUseSRet) { 7119 // Create stack object for sret. 7120 const uint64_t ByteSize = DL.getTypeAllocSize(RetTy); 7121 const unsigned StackAlign = DL.getPrefTypeAlignment(RetTy); 7122 int FrameIdx = MFI.CreateStackObject(ByteSize, StackAlign, false); 7123 SRet = DAG.getFrameIndex(FrameIdx, TLI.getPointerTy(DL)); 7124 7125 ArgListEntry Entry; 7126 Entry.Node = SRet; 7127 Entry.Ty = RetTy->getPointerTo(); 7128 Entry.isSExt = false; 7129 Entry.isZExt = false; 7130 Entry.isSRet = true; 7131 Args.push_back(Entry); 7132 RetTy = Type::getVoidTy(*DAG.getContext()); 7133 } 7134 7135 ArgListEntry Entry; 7136 Entry.Node = Arg; 7137 Entry.Ty = ArgTy; 7138 Entry.isSExt = false; 7139 Entry.isZExt = false; 7140 Args.push_back(Entry); 7141 7142 const char *LibcallName = 7143 (ArgVT == MVT::f64) ? "__sincos_stret" : "__sincosf_stret"; 7144 RTLIB::Libcall LC = 7145 (ArgVT == MVT::f64) ? RTLIB::SINCOS_F64 : RTLIB::SINCOS_F32; 7146 CallingConv::ID CC = getLibcallCallingConv(LC); 7147 SDValue Callee = DAG.getExternalSymbol(LibcallName, getPointerTy(DL)); 7148 7149 TargetLowering::CallLoweringInfo CLI(DAG); 7150 CLI.setDebugLoc(dl) 7151 .setChain(DAG.getEntryNode()) 7152 .setCallee(CC, RetTy, Callee, std::move(Args)) 7153 .setDiscardResult(ShouldUseSRet); 7154 std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI); 7155 7156 if (!ShouldUseSRet) 7157 return CallResult.first; 7158 7159 SDValue LoadSin = 7160 DAG.getLoad(ArgVT, dl, CallResult.second, SRet, MachinePointerInfo()); 7161 7162 // Address of cos field. 7163 SDValue Add = DAG.getNode(ISD::ADD, dl, PtrVT, SRet, 7164 DAG.getIntPtrConstant(ArgVT.getStoreSize(), dl)); 7165 SDValue LoadCos = 7166 DAG.getLoad(ArgVT, dl, LoadSin.getValue(1), Add, MachinePointerInfo()); 7167 7168 SDVTList Tys = DAG.getVTList(ArgVT, ArgVT); 7169 return DAG.getNode(ISD::MERGE_VALUES, dl, Tys, 7170 LoadSin.getValue(0), LoadCos.getValue(0)); 7171 } 7172 7173 SDValue ARMTargetLowering::LowerWindowsDIVLibCall(SDValue Op, SelectionDAG &DAG, 7174 bool Signed, 7175 SDValue &Chain) const { 7176 EVT VT = Op.getValueType(); 7177 assert((VT == MVT::i32 || VT == MVT::i64) && 7178 "unexpected type for custom lowering DIV"); 7179 SDLoc dl(Op); 7180 7181 const auto &DL = DAG.getDataLayout(); 7182 const auto &TLI = DAG.getTargetLoweringInfo(); 7183 7184 const char *Name = nullptr; 7185 if (Signed) 7186 Name = (VT == MVT::i32) ? "__rt_sdiv" : "__rt_sdiv64"; 7187 else 7188 Name = (VT == MVT::i32) ? "__rt_udiv" : "__rt_udiv64"; 7189 7190 SDValue ES = DAG.getExternalSymbol(Name, TLI.getPointerTy(DL)); 7191 7192 ARMTargetLowering::ArgListTy Args; 7193 7194 for (auto AI : {1, 0}) { 7195 ArgListEntry Arg; 7196 Arg.Node = Op.getOperand(AI); 7197 Arg.Ty = Arg.Node.getValueType().getTypeForEVT(*DAG.getContext()); 7198 Args.push_back(Arg); 7199 } 7200 7201 CallLoweringInfo CLI(DAG); 7202 CLI.setDebugLoc(dl) 7203 .setChain(Chain) 7204 .setCallee(CallingConv::ARM_AAPCS_VFP, VT.getTypeForEVT(*DAG.getContext()), 7205 ES, std::move(Args)); 7206 7207 return LowerCallTo(CLI).first; 7208 } 7209 7210 SDValue ARMTargetLowering::LowerDIV_Windows(SDValue Op, SelectionDAG &DAG, 7211 bool Signed) const { 7212 assert(Op.getValueType() == MVT::i32 && 7213 "unexpected type for custom lowering DIV"); 7214 SDLoc dl(Op); 7215 7216 SDValue DBZCHK = DAG.getNode(ARMISD::WIN__DBZCHK, dl, MVT::Other, 7217 DAG.getEntryNode(), Op.getOperand(1)); 7218 7219 return LowerWindowsDIVLibCall(Op, DAG, Signed, DBZCHK); 7220 } 7221 7222 void ARMTargetLowering::ExpandDIV_Windows( 7223 SDValue Op, SelectionDAG &DAG, bool Signed, 7224 SmallVectorImpl<SDValue> &Results) const { 7225 const auto &DL = DAG.getDataLayout(); 7226 const auto &TLI = DAG.getTargetLoweringInfo(); 7227 7228 assert(Op.getValueType() == MVT::i64 && 7229 "unexpected type for custom lowering DIV"); 7230 SDLoc dl(Op); 7231 7232 SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, Op.getOperand(1), 7233 DAG.getConstant(0, dl, MVT::i32)); 7234 SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, Op.getOperand(1), 7235 DAG.getConstant(1, dl, MVT::i32)); 7236 SDValue Or = DAG.getNode(ISD::OR, dl, MVT::i32, Lo, Hi); 7237 7238 SDValue DBZCHK = 7239 DAG.getNode(ARMISD::WIN__DBZCHK, dl, MVT::Other, DAG.getEntryNode(), Or); 7240 7241 SDValue Result = LowerWindowsDIVLibCall(Op, DAG, Signed, DBZCHK); 7242 7243 SDValue Lower = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, Result); 7244 SDValue Upper = DAG.getNode(ISD::SRL, dl, MVT::i64, Result, 7245 DAG.getConstant(32, dl, TLI.getPointerTy(DL))); 7246 Upper = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, Upper); 7247 7248 Results.push_back(Lower); 7249 Results.push_back(Upper); 7250 } 7251 7252 static SDValue LowerAtomicLoadStore(SDValue Op, SelectionDAG &DAG) { 7253 if (isStrongerThanMonotonic(cast<AtomicSDNode>(Op)->getOrdering())) 7254 // Acquire/Release load/store is not legal for targets without a dmb or 7255 // equivalent available. 7256 return SDValue(); 7257 7258 // Monotonic load/store is legal for all targets. 7259 return Op; 7260 } 7261 7262 static void ReplaceREADCYCLECOUNTER(SDNode *N, 7263 SmallVectorImpl<SDValue> &Results, 7264 SelectionDAG &DAG, 7265 const ARMSubtarget *Subtarget) { 7266 SDLoc DL(N); 7267 // Under Power Management extensions, the cycle-count is: 7268 // mrc p15, #0, <Rt>, c9, c13, #0 7269 SDValue Ops[] = { N->getOperand(0), // Chain 7270 DAG.getConstant(Intrinsic::arm_mrc, DL, MVT::i32), 7271 DAG.getConstant(15, DL, MVT::i32), 7272 DAG.getConstant(0, DL, MVT::i32), 7273 DAG.getConstant(9, DL, MVT::i32), 7274 DAG.getConstant(13, DL, MVT::i32), 7275 DAG.getConstant(0, DL, MVT::i32) 7276 }; 7277 7278 SDValue Cycles32 = DAG.getNode(ISD::INTRINSIC_W_CHAIN, DL, 7279 DAG.getVTList(MVT::i32, MVT::Other), Ops); 7280 Results.push_back(DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, Cycles32, 7281 DAG.getConstant(0, DL, MVT::i32))); 7282 Results.push_back(Cycles32.getValue(1)); 7283 } 7284 7285 static SDValue createGPRPairNode(SelectionDAG &DAG, SDValue V) { 7286 SDLoc dl(V.getNode()); 7287 SDValue VLo = DAG.getAnyExtOrTrunc(V, dl, MVT::i32); 7288 SDValue VHi = DAG.getAnyExtOrTrunc( 7289 DAG.getNode(ISD::SRL, dl, MVT::i64, V, DAG.getConstant(32, dl, MVT::i32)), 7290 dl, MVT::i32); 7291 SDValue RegClass = 7292 DAG.getTargetConstant(ARM::GPRPairRegClassID, dl, MVT::i32); 7293 SDValue SubReg0 = DAG.getTargetConstant(ARM::gsub_0, dl, MVT::i32); 7294 SDValue SubReg1 = DAG.getTargetConstant(ARM::gsub_1, dl, MVT::i32); 7295 const SDValue Ops[] = { RegClass, VLo, SubReg0, VHi, SubReg1 }; 7296 return SDValue( 7297 DAG.getMachineNode(TargetOpcode::REG_SEQUENCE, dl, MVT::Untyped, Ops), 0); 7298 } 7299 7300 static void ReplaceCMP_SWAP_64Results(SDNode *N, 7301 SmallVectorImpl<SDValue> & Results, 7302 SelectionDAG &DAG) { 7303 assert(N->getValueType(0) == MVT::i64 && 7304 "AtomicCmpSwap on types less than 64 should be legal"); 7305 SDValue Ops[] = {N->getOperand(1), 7306 createGPRPairNode(DAG, N->getOperand(2)), 7307 createGPRPairNode(DAG, N->getOperand(3)), 7308 N->getOperand(0)}; 7309 SDNode *CmpSwap = DAG.getMachineNode( 7310 ARM::CMP_SWAP_64, SDLoc(N), 7311 DAG.getVTList(MVT::Untyped, MVT::i32, MVT::Other), Ops); 7312 7313 MachineFunction &MF = DAG.getMachineFunction(); 7314 MachineSDNode::mmo_iterator MemOp = MF.allocateMemRefsArray(1); 7315 MemOp[0] = cast<MemSDNode>(N)->getMemOperand(); 7316 cast<MachineSDNode>(CmpSwap)->setMemRefs(MemOp, MemOp + 1); 7317 7318 Results.push_back(DAG.getTargetExtractSubreg(ARM::gsub_0, SDLoc(N), MVT::i32, 7319 SDValue(CmpSwap, 0))); 7320 Results.push_back(DAG.getTargetExtractSubreg(ARM::gsub_1, SDLoc(N), MVT::i32, 7321 SDValue(CmpSwap, 0))); 7322 Results.push_back(SDValue(CmpSwap, 2)); 7323 } 7324 7325 SDValue ARMTargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const { 7326 switch (Op.getOpcode()) { 7327 default: llvm_unreachable("Don't know how to custom lower this!"); 7328 case ISD::WRITE_REGISTER: return LowerWRITE_REGISTER(Op, DAG); 7329 case ISD::ConstantPool: return LowerConstantPool(Op, DAG); 7330 case ISD::BlockAddress: return LowerBlockAddress(Op, DAG); 7331 case ISD::GlobalAddress: 7332 switch (Subtarget->getTargetTriple().getObjectFormat()) { 7333 default: llvm_unreachable("unknown object format"); 7334 case Triple::COFF: 7335 return LowerGlobalAddressWindows(Op, DAG); 7336 case Triple::ELF: 7337 return LowerGlobalAddressELF(Op, DAG); 7338 case Triple::MachO: 7339 return LowerGlobalAddressDarwin(Op, DAG); 7340 } 7341 case ISD::GlobalTLSAddress: return LowerGlobalTLSAddress(Op, DAG); 7342 case ISD::SELECT: return LowerSELECT(Op, DAG); 7343 case ISD::SELECT_CC: return LowerSELECT_CC(Op, DAG); 7344 case ISD::BR_CC: return LowerBR_CC(Op, DAG); 7345 case ISD::BR_JT: return LowerBR_JT(Op, DAG); 7346 case ISD::VASTART: return LowerVASTART(Op, DAG); 7347 case ISD::ATOMIC_FENCE: return LowerATOMIC_FENCE(Op, DAG, Subtarget); 7348 case ISD::PREFETCH: return LowerPREFETCH(Op, DAG, Subtarget); 7349 case ISD::SINT_TO_FP: 7350 case ISD::UINT_TO_FP: return LowerINT_TO_FP(Op, DAG); 7351 case ISD::FP_TO_SINT: 7352 case ISD::FP_TO_UINT: return LowerFP_TO_INT(Op, DAG); 7353 case ISD::FCOPYSIGN: return LowerFCOPYSIGN(Op, DAG); 7354 case ISD::RETURNADDR: return LowerRETURNADDR(Op, DAG); 7355 case ISD::FRAMEADDR: return LowerFRAMEADDR(Op, DAG); 7356 case ISD::EH_SJLJ_SETJMP: return LowerEH_SJLJ_SETJMP(Op, DAG); 7357 case ISD::EH_SJLJ_LONGJMP: return LowerEH_SJLJ_LONGJMP(Op, DAG); 7358 case ISD::EH_SJLJ_SETUP_DISPATCH: return LowerEH_SJLJ_SETUP_DISPATCH(Op, DAG); 7359 case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG, 7360 Subtarget); 7361 case ISD::BITCAST: return ExpandBITCAST(Op.getNode(), DAG); 7362 case ISD::SHL: 7363 case ISD::SRL: 7364 case ISD::SRA: return LowerShift(Op.getNode(), DAG, Subtarget); 7365 case ISD::SREM: return LowerREM(Op.getNode(), DAG); 7366 case ISD::UREM: return LowerREM(Op.getNode(), DAG); 7367 case ISD::SHL_PARTS: return LowerShiftLeftParts(Op, DAG); 7368 case ISD::SRL_PARTS: 7369 case ISD::SRA_PARTS: return LowerShiftRightParts(Op, DAG); 7370 case ISD::CTTZ: 7371 case ISD::CTTZ_ZERO_UNDEF: return LowerCTTZ(Op.getNode(), DAG, Subtarget); 7372 case ISD::CTPOP: return LowerCTPOP(Op.getNode(), DAG, Subtarget); 7373 case ISD::SETCC: return LowerVSETCC(Op, DAG); 7374 case ISD::SETCCE: return LowerSETCCE(Op, DAG); 7375 case ISD::ConstantFP: return LowerConstantFP(Op, DAG, Subtarget); 7376 case ISD::BUILD_VECTOR: return LowerBUILD_VECTOR(Op, DAG, Subtarget); 7377 case ISD::VECTOR_SHUFFLE: return LowerVECTOR_SHUFFLE(Op, DAG); 7378 case ISD::INSERT_VECTOR_ELT: return LowerINSERT_VECTOR_ELT(Op, DAG); 7379 case ISD::EXTRACT_VECTOR_ELT: return LowerEXTRACT_VECTOR_ELT(Op, DAG); 7380 case ISD::CONCAT_VECTORS: return LowerCONCAT_VECTORS(Op, DAG); 7381 case ISD::FLT_ROUNDS_: return LowerFLT_ROUNDS_(Op, DAG); 7382 case ISD::MUL: return LowerMUL(Op, DAG); 7383 case ISD::SDIV: 7384 if (Subtarget->isTargetWindows()) 7385 return LowerDIV_Windows(Op, DAG, /* Signed */ true); 7386 return LowerSDIV(Op, DAG); 7387 case ISD::UDIV: 7388 if (Subtarget->isTargetWindows()) 7389 return LowerDIV_Windows(Op, DAG, /* Signed */ false); 7390 return LowerUDIV(Op, DAG); 7391 case ISD::ADDC: 7392 case ISD::ADDE: 7393 case ISD::SUBC: 7394 case ISD::SUBE: return LowerADDC_ADDE_SUBC_SUBE(Op, DAG); 7395 case ISD::SADDO: 7396 case ISD::UADDO: 7397 case ISD::SSUBO: 7398 case ISD::USUBO: 7399 return LowerXALUO(Op, DAG); 7400 case ISD::ATOMIC_LOAD: 7401 case ISD::ATOMIC_STORE: return LowerAtomicLoadStore(Op, DAG); 7402 case ISD::FSINCOS: return LowerFSINCOS(Op, DAG); 7403 case ISD::SDIVREM: 7404 case ISD::UDIVREM: return LowerDivRem(Op, DAG); 7405 case ISD::DYNAMIC_STACKALLOC: 7406 if (Subtarget->getTargetTriple().isWindowsItaniumEnvironment()) 7407 return LowerDYNAMIC_STACKALLOC(Op, DAG); 7408 llvm_unreachable("Don't know how to custom lower this!"); 7409 case ISD::FP_ROUND: return LowerFP_ROUND(Op, DAG); 7410 case ISD::FP_EXTEND: return LowerFP_EXTEND(Op, DAG); 7411 case ARMISD::WIN__DBZCHK: return SDValue(); 7412 } 7413 } 7414 7415 /// ReplaceNodeResults - Replace the results of node with an illegal result 7416 /// type with new values built out of custom code. 7417 void ARMTargetLowering::ReplaceNodeResults(SDNode *N, 7418 SmallVectorImpl<SDValue> &Results, 7419 SelectionDAG &DAG) const { 7420 SDValue Res; 7421 switch (N->getOpcode()) { 7422 default: 7423 llvm_unreachable("Don't know how to custom expand this!"); 7424 case ISD::READ_REGISTER: 7425 ExpandREAD_REGISTER(N, Results, DAG); 7426 break; 7427 case ISD::BITCAST: 7428 Res = ExpandBITCAST(N, DAG); 7429 break; 7430 case ISD::SRL: 7431 case ISD::SRA: 7432 Res = Expand64BitShift(N, DAG, Subtarget); 7433 break; 7434 case ISD::SREM: 7435 case ISD::UREM: 7436 Res = LowerREM(N, DAG); 7437 break; 7438 case ISD::SDIVREM: 7439 case ISD::UDIVREM: 7440 Res = LowerDivRem(SDValue(N, 0), DAG); 7441 assert(Res.getNumOperands() == 2 && "DivRem needs two values"); 7442 Results.push_back(Res.getValue(0)); 7443 Results.push_back(Res.getValue(1)); 7444 return; 7445 case ISD::READCYCLECOUNTER: 7446 ReplaceREADCYCLECOUNTER(N, Results, DAG, Subtarget); 7447 return; 7448 case ISD::UDIV: 7449 case ISD::SDIV: 7450 assert(Subtarget->isTargetWindows() && "can only expand DIV on Windows"); 7451 return ExpandDIV_Windows(SDValue(N, 0), DAG, N->getOpcode() == ISD::SDIV, 7452 Results); 7453 case ISD::ATOMIC_CMP_SWAP: 7454 ReplaceCMP_SWAP_64Results(N, Results, DAG); 7455 return; 7456 } 7457 if (Res.getNode()) 7458 Results.push_back(Res); 7459 } 7460 7461 //===----------------------------------------------------------------------===// 7462 // ARM Scheduler Hooks 7463 //===----------------------------------------------------------------------===// 7464 7465 /// SetupEntryBlockForSjLj - Insert code into the entry block that creates and 7466 /// registers the function context. 7467 void ARMTargetLowering::SetupEntryBlockForSjLj(MachineInstr &MI, 7468 MachineBasicBlock *MBB, 7469 MachineBasicBlock *DispatchBB, 7470 int FI) const { 7471 assert(!Subtarget->isROPI() && !Subtarget->isRWPI() && 7472 "ROPI/RWPI not currently supported with SjLj"); 7473 const TargetInstrInfo *TII = Subtarget->getInstrInfo(); 7474 DebugLoc dl = MI.getDebugLoc(); 7475 MachineFunction *MF = MBB->getParent(); 7476 MachineRegisterInfo *MRI = &MF->getRegInfo(); 7477 MachineConstantPool *MCP = MF->getConstantPool(); 7478 ARMFunctionInfo *AFI = MF->getInfo<ARMFunctionInfo>(); 7479 const Function *F = MF->getFunction(); 7480 7481 bool isThumb = Subtarget->isThumb(); 7482 bool isThumb2 = Subtarget->isThumb2(); 7483 7484 unsigned PCLabelId = AFI->createPICLabelUId(); 7485 unsigned PCAdj = (isThumb || isThumb2) ? 4 : 8; 7486 ARMConstantPoolValue *CPV = 7487 ARMConstantPoolMBB::Create(F->getContext(), DispatchBB, PCLabelId, PCAdj); 7488 unsigned CPI = MCP->getConstantPoolIndex(CPV, 4); 7489 7490 const TargetRegisterClass *TRC = isThumb ? &ARM::tGPRRegClass 7491 : &ARM::GPRRegClass; 7492 7493 // Grab constant pool and fixed stack memory operands. 7494 MachineMemOperand *CPMMO = 7495 MF->getMachineMemOperand(MachinePointerInfo::getConstantPool(*MF), 7496 MachineMemOperand::MOLoad, 4, 4); 7497 7498 MachineMemOperand *FIMMOSt = 7499 MF->getMachineMemOperand(MachinePointerInfo::getFixedStack(*MF, FI), 7500 MachineMemOperand::MOStore, 4, 4); 7501 7502 // Load the address of the dispatch MBB into the jump buffer. 7503 if (isThumb2) { 7504 // Incoming value: jbuf 7505 // ldr.n r5, LCPI1_1 7506 // orr r5, r5, #1 7507 // add r5, pc 7508 // str r5, [$jbuf, #+4] ; &jbuf[1] 7509 unsigned NewVReg1 = MRI->createVirtualRegister(TRC); 7510 AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::t2LDRpci), NewVReg1) 7511 .addConstantPoolIndex(CPI) 7512 .addMemOperand(CPMMO)); 7513 // Set the low bit because of thumb mode. 7514 unsigned NewVReg2 = MRI->createVirtualRegister(TRC); 7515 AddDefaultCC( 7516 AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::t2ORRri), NewVReg2) 7517 .addReg(NewVReg1, RegState::Kill) 7518 .addImm(0x01))); 7519 unsigned NewVReg3 = MRI->createVirtualRegister(TRC); 7520 BuildMI(*MBB, MI, dl, TII->get(ARM::tPICADD), NewVReg3) 7521 .addReg(NewVReg2, RegState::Kill) 7522 .addImm(PCLabelId); 7523 AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::t2STRi12)) 7524 .addReg(NewVReg3, RegState::Kill) 7525 .addFrameIndex(FI) 7526 .addImm(36) // &jbuf[1] :: pc 7527 .addMemOperand(FIMMOSt)); 7528 } else if (isThumb) { 7529 // Incoming value: jbuf 7530 // ldr.n r1, LCPI1_4 7531 // add r1, pc 7532 // mov r2, #1 7533 // orrs r1, r2 7534 // add r2, $jbuf, #+4 ; &jbuf[1] 7535 // str r1, [r2] 7536 unsigned NewVReg1 = MRI->createVirtualRegister(TRC); 7537 AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::tLDRpci), NewVReg1) 7538 .addConstantPoolIndex(CPI) 7539 .addMemOperand(CPMMO)); 7540 unsigned NewVReg2 = MRI->createVirtualRegister(TRC); 7541 BuildMI(*MBB, MI, dl, TII->get(ARM::tPICADD), NewVReg2) 7542 .addReg(NewVReg1, RegState::Kill) 7543 .addImm(PCLabelId); 7544 // Set the low bit because of thumb mode. 7545 unsigned NewVReg3 = MRI->createVirtualRegister(TRC); 7546 AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::tMOVi8), NewVReg3) 7547 .addReg(ARM::CPSR, RegState::Define) 7548 .addImm(1)); 7549 unsigned NewVReg4 = MRI->createVirtualRegister(TRC); 7550 AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::tORR), NewVReg4) 7551 .addReg(ARM::CPSR, RegState::Define) 7552 .addReg(NewVReg2, RegState::Kill) 7553 .addReg(NewVReg3, RegState::Kill)); 7554 unsigned NewVReg5 = MRI->createVirtualRegister(TRC); 7555 BuildMI(*MBB, MI, dl, TII->get(ARM::tADDframe), NewVReg5) 7556 .addFrameIndex(FI) 7557 .addImm(36); // &jbuf[1] :: pc 7558 AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::tSTRi)) 7559 .addReg(NewVReg4, RegState::Kill) 7560 .addReg(NewVReg5, RegState::Kill) 7561 .addImm(0) 7562 .addMemOperand(FIMMOSt)); 7563 } else { 7564 // Incoming value: jbuf 7565 // ldr r1, LCPI1_1 7566 // add r1, pc, r1 7567 // str r1, [$jbuf, #+4] ; &jbuf[1] 7568 unsigned NewVReg1 = MRI->createVirtualRegister(TRC); 7569 AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::LDRi12), NewVReg1) 7570 .addConstantPoolIndex(CPI) 7571 .addImm(0) 7572 .addMemOperand(CPMMO)); 7573 unsigned NewVReg2 = MRI->createVirtualRegister(TRC); 7574 AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::PICADD), NewVReg2) 7575 .addReg(NewVReg1, RegState::Kill) 7576 .addImm(PCLabelId)); 7577 AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::STRi12)) 7578 .addReg(NewVReg2, RegState::Kill) 7579 .addFrameIndex(FI) 7580 .addImm(36) // &jbuf[1] :: pc 7581 .addMemOperand(FIMMOSt)); 7582 } 7583 } 7584 7585 void ARMTargetLowering::EmitSjLjDispatchBlock(MachineInstr &MI, 7586 MachineBasicBlock *MBB) const { 7587 const TargetInstrInfo *TII = Subtarget->getInstrInfo(); 7588 DebugLoc dl = MI.getDebugLoc(); 7589 MachineFunction *MF = MBB->getParent(); 7590 MachineRegisterInfo *MRI = &MF->getRegInfo(); 7591 MachineFrameInfo &MFI = MF->getFrameInfo(); 7592 int FI = MFI.getFunctionContextIndex(); 7593 7594 const TargetRegisterClass *TRC = Subtarget->isThumb() ? &ARM::tGPRRegClass 7595 : &ARM::GPRnopcRegClass; 7596 7597 // Get a mapping of the call site numbers to all of the landing pads they're 7598 // associated with. 7599 DenseMap<unsigned, SmallVector<MachineBasicBlock*, 2> > CallSiteNumToLPad; 7600 unsigned MaxCSNum = 0; 7601 MachineModuleInfo &MMI = MF->getMMI(); 7602 for (MachineFunction::iterator BB = MF->begin(), E = MF->end(); BB != E; 7603 ++BB) { 7604 if (!BB->isEHPad()) continue; 7605 7606 // FIXME: We should assert that the EH_LABEL is the first MI in the landing 7607 // pad. 7608 for (MachineBasicBlock::iterator 7609 II = BB->begin(), IE = BB->end(); II != IE; ++II) { 7610 if (!II->isEHLabel()) continue; 7611 7612 MCSymbol *Sym = II->getOperand(0).getMCSymbol(); 7613 if (!MMI.hasCallSiteLandingPad(Sym)) continue; 7614 7615 SmallVectorImpl<unsigned> &CallSiteIdxs = MMI.getCallSiteLandingPad(Sym); 7616 for (SmallVectorImpl<unsigned>::iterator 7617 CSI = CallSiteIdxs.begin(), CSE = CallSiteIdxs.end(); 7618 CSI != CSE; ++CSI) { 7619 CallSiteNumToLPad[*CSI].push_back(&*BB); 7620 MaxCSNum = std::max(MaxCSNum, *CSI); 7621 } 7622 break; 7623 } 7624 } 7625 7626 // Get an ordered list of the machine basic blocks for the jump table. 7627 std::vector<MachineBasicBlock*> LPadList; 7628 SmallPtrSet<MachineBasicBlock*, 32> InvokeBBs; 7629 LPadList.reserve(CallSiteNumToLPad.size()); 7630 for (unsigned I = 1; I <= MaxCSNum; ++I) { 7631 SmallVectorImpl<MachineBasicBlock*> &MBBList = CallSiteNumToLPad[I]; 7632 for (SmallVectorImpl<MachineBasicBlock*>::iterator 7633 II = MBBList.begin(), IE = MBBList.end(); II != IE; ++II) { 7634 LPadList.push_back(*II); 7635 InvokeBBs.insert((*II)->pred_begin(), (*II)->pred_end()); 7636 } 7637 } 7638 7639 assert(!LPadList.empty() && 7640 "No landing pad destinations for the dispatch jump table!"); 7641 7642 // Create the jump table and associated information. 7643 MachineJumpTableInfo *JTI = 7644 MF->getOrCreateJumpTableInfo(MachineJumpTableInfo::EK_Inline); 7645 unsigned MJTI = JTI->createJumpTableIndex(LPadList); 7646 7647 // Create the MBBs for the dispatch code. 7648 7649 // Shove the dispatch's address into the return slot in the function context. 7650 MachineBasicBlock *DispatchBB = MF->CreateMachineBasicBlock(); 7651 DispatchBB->setIsEHPad(); 7652 7653 MachineBasicBlock *TrapBB = MF->CreateMachineBasicBlock(); 7654 unsigned trap_opcode; 7655 if (Subtarget->isThumb()) 7656 trap_opcode = ARM::tTRAP; 7657 else 7658 trap_opcode = Subtarget->useNaClTrap() ? ARM::TRAPNaCl : ARM::TRAP; 7659 7660 BuildMI(TrapBB, dl, TII->get(trap_opcode)); 7661 DispatchBB->addSuccessor(TrapBB); 7662 7663 MachineBasicBlock *DispContBB = MF->CreateMachineBasicBlock(); 7664 DispatchBB->addSuccessor(DispContBB); 7665 7666 // Insert and MBBs. 7667 MF->insert(MF->end(), DispatchBB); 7668 MF->insert(MF->end(), DispContBB); 7669 MF->insert(MF->end(), TrapBB); 7670 7671 // Insert code into the entry block that creates and registers the function 7672 // context. 7673 SetupEntryBlockForSjLj(MI, MBB, DispatchBB, FI); 7674 7675 MachineMemOperand *FIMMOLd = MF->getMachineMemOperand( 7676 MachinePointerInfo::getFixedStack(*MF, FI), 7677 MachineMemOperand::MOLoad | MachineMemOperand::MOVolatile, 4, 4); 7678 7679 MachineInstrBuilder MIB; 7680 MIB = BuildMI(DispatchBB, dl, TII->get(ARM::Int_eh_sjlj_dispatchsetup)); 7681 7682 const ARMBaseInstrInfo *AII = static_cast<const ARMBaseInstrInfo*>(TII); 7683 const ARMBaseRegisterInfo &RI = AII->getRegisterInfo(); 7684 7685 // Add a register mask with no preserved registers. This results in all 7686 // registers being marked as clobbered. 7687 MIB.addRegMask(RI.getNoPreservedMask()); 7688 7689 bool IsPositionIndependent = isPositionIndependent(); 7690 unsigned NumLPads = LPadList.size(); 7691 if (Subtarget->isThumb2()) { 7692 unsigned NewVReg1 = MRI->createVirtualRegister(TRC); 7693 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::t2LDRi12), NewVReg1) 7694 .addFrameIndex(FI) 7695 .addImm(4) 7696 .addMemOperand(FIMMOLd)); 7697 7698 if (NumLPads < 256) { 7699 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::t2CMPri)) 7700 .addReg(NewVReg1) 7701 .addImm(LPadList.size())); 7702 } else { 7703 unsigned VReg1 = MRI->createVirtualRegister(TRC); 7704 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::t2MOVi16), VReg1) 7705 .addImm(NumLPads & 0xFFFF)); 7706 7707 unsigned VReg2 = VReg1; 7708 if ((NumLPads & 0xFFFF0000) != 0) { 7709 VReg2 = MRI->createVirtualRegister(TRC); 7710 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::t2MOVTi16), VReg2) 7711 .addReg(VReg1) 7712 .addImm(NumLPads >> 16)); 7713 } 7714 7715 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::t2CMPrr)) 7716 .addReg(NewVReg1) 7717 .addReg(VReg2)); 7718 } 7719 7720 BuildMI(DispatchBB, dl, TII->get(ARM::t2Bcc)) 7721 .addMBB(TrapBB) 7722 .addImm(ARMCC::HI) 7723 .addReg(ARM::CPSR); 7724 7725 unsigned NewVReg3 = MRI->createVirtualRegister(TRC); 7726 AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::t2LEApcrelJT),NewVReg3) 7727 .addJumpTableIndex(MJTI)); 7728 7729 unsigned NewVReg4 = MRI->createVirtualRegister(TRC); 7730 AddDefaultCC( 7731 AddDefaultPred( 7732 BuildMI(DispContBB, dl, TII->get(ARM::t2ADDrs), NewVReg4) 7733 .addReg(NewVReg3, RegState::Kill) 7734 .addReg(NewVReg1) 7735 .addImm(ARM_AM::getSORegOpc(ARM_AM::lsl, 2)))); 7736 7737 BuildMI(DispContBB, dl, TII->get(ARM::t2BR_JT)) 7738 .addReg(NewVReg4, RegState::Kill) 7739 .addReg(NewVReg1) 7740 .addJumpTableIndex(MJTI); 7741 } else if (Subtarget->isThumb()) { 7742 unsigned NewVReg1 = MRI->createVirtualRegister(TRC); 7743 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::tLDRspi), NewVReg1) 7744 .addFrameIndex(FI) 7745 .addImm(1) 7746 .addMemOperand(FIMMOLd)); 7747 7748 if (NumLPads < 256) { 7749 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::tCMPi8)) 7750 .addReg(NewVReg1) 7751 .addImm(NumLPads)); 7752 } else { 7753 MachineConstantPool *ConstantPool = MF->getConstantPool(); 7754 Type *Int32Ty = Type::getInt32Ty(MF->getFunction()->getContext()); 7755 const Constant *C = ConstantInt::get(Int32Ty, NumLPads); 7756 7757 // MachineConstantPool wants an explicit alignment. 7758 unsigned Align = MF->getDataLayout().getPrefTypeAlignment(Int32Ty); 7759 if (Align == 0) 7760 Align = MF->getDataLayout().getTypeAllocSize(C->getType()); 7761 unsigned Idx = ConstantPool->getConstantPoolIndex(C, Align); 7762 7763 unsigned VReg1 = MRI->createVirtualRegister(TRC); 7764 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::tLDRpci)) 7765 .addReg(VReg1, RegState::Define) 7766 .addConstantPoolIndex(Idx)); 7767 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::tCMPr)) 7768 .addReg(NewVReg1) 7769 .addReg(VReg1)); 7770 } 7771 7772 BuildMI(DispatchBB, dl, TII->get(ARM::tBcc)) 7773 .addMBB(TrapBB) 7774 .addImm(ARMCC::HI) 7775 .addReg(ARM::CPSR); 7776 7777 unsigned NewVReg2 = MRI->createVirtualRegister(TRC); 7778 AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::tLSLri), NewVReg2) 7779 .addReg(ARM::CPSR, RegState::Define) 7780 .addReg(NewVReg1) 7781 .addImm(2)); 7782 7783 unsigned NewVReg3 = MRI->createVirtualRegister(TRC); 7784 AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::tLEApcrelJT), NewVReg3) 7785 .addJumpTableIndex(MJTI)); 7786 7787 unsigned NewVReg4 = MRI->createVirtualRegister(TRC); 7788 AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::tADDrr), NewVReg4) 7789 .addReg(ARM::CPSR, RegState::Define) 7790 .addReg(NewVReg2, RegState::Kill) 7791 .addReg(NewVReg3)); 7792 7793 MachineMemOperand *JTMMOLd = MF->getMachineMemOperand( 7794 MachinePointerInfo::getJumpTable(*MF), MachineMemOperand::MOLoad, 4, 4); 7795 7796 unsigned NewVReg5 = MRI->createVirtualRegister(TRC); 7797 AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::tLDRi), NewVReg5) 7798 .addReg(NewVReg4, RegState::Kill) 7799 .addImm(0) 7800 .addMemOperand(JTMMOLd)); 7801 7802 unsigned NewVReg6 = NewVReg5; 7803 if (IsPositionIndependent) { 7804 NewVReg6 = MRI->createVirtualRegister(TRC); 7805 AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::tADDrr), NewVReg6) 7806 .addReg(ARM::CPSR, RegState::Define) 7807 .addReg(NewVReg5, RegState::Kill) 7808 .addReg(NewVReg3)); 7809 } 7810 7811 BuildMI(DispContBB, dl, TII->get(ARM::tBR_JTr)) 7812 .addReg(NewVReg6, RegState::Kill) 7813 .addJumpTableIndex(MJTI); 7814 } else { 7815 unsigned NewVReg1 = MRI->createVirtualRegister(TRC); 7816 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::LDRi12), NewVReg1) 7817 .addFrameIndex(FI) 7818 .addImm(4) 7819 .addMemOperand(FIMMOLd)); 7820 7821 if (NumLPads < 256) { 7822 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::CMPri)) 7823 .addReg(NewVReg1) 7824 .addImm(NumLPads)); 7825 } else if (Subtarget->hasV6T2Ops() && isUInt<16>(NumLPads)) { 7826 unsigned VReg1 = MRI->createVirtualRegister(TRC); 7827 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::MOVi16), VReg1) 7828 .addImm(NumLPads & 0xFFFF)); 7829 7830 unsigned VReg2 = VReg1; 7831 if ((NumLPads & 0xFFFF0000) != 0) { 7832 VReg2 = MRI->createVirtualRegister(TRC); 7833 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::MOVTi16), VReg2) 7834 .addReg(VReg1) 7835 .addImm(NumLPads >> 16)); 7836 } 7837 7838 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::CMPrr)) 7839 .addReg(NewVReg1) 7840 .addReg(VReg2)); 7841 } else { 7842 MachineConstantPool *ConstantPool = MF->getConstantPool(); 7843 Type *Int32Ty = Type::getInt32Ty(MF->getFunction()->getContext()); 7844 const Constant *C = ConstantInt::get(Int32Ty, NumLPads); 7845 7846 // MachineConstantPool wants an explicit alignment. 7847 unsigned Align = MF->getDataLayout().getPrefTypeAlignment(Int32Ty); 7848 if (Align == 0) 7849 Align = MF->getDataLayout().getTypeAllocSize(C->getType()); 7850 unsigned Idx = ConstantPool->getConstantPoolIndex(C, Align); 7851 7852 unsigned VReg1 = MRI->createVirtualRegister(TRC); 7853 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::LDRcp)) 7854 .addReg(VReg1, RegState::Define) 7855 .addConstantPoolIndex(Idx) 7856 .addImm(0)); 7857 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::CMPrr)) 7858 .addReg(NewVReg1) 7859 .addReg(VReg1, RegState::Kill)); 7860 } 7861 7862 BuildMI(DispatchBB, dl, TII->get(ARM::Bcc)) 7863 .addMBB(TrapBB) 7864 .addImm(ARMCC::HI) 7865 .addReg(ARM::CPSR); 7866 7867 unsigned NewVReg3 = MRI->createVirtualRegister(TRC); 7868 AddDefaultCC( 7869 AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::MOVsi), NewVReg3) 7870 .addReg(NewVReg1) 7871 .addImm(ARM_AM::getSORegOpc(ARM_AM::lsl, 2)))); 7872 unsigned NewVReg4 = MRI->createVirtualRegister(TRC); 7873 AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::LEApcrelJT), NewVReg4) 7874 .addJumpTableIndex(MJTI)); 7875 7876 MachineMemOperand *JTMMOLd = MF->getMachineMemOperand( 7877 MachinePointerInfo::getJumpTable(*MF), MachineMemOperand::MOLoad, 4, 4); 7878 unsigned NewVReg5 = MRI->createVirtualRegister(TRC); 7879 AddDefaultPred( 7880 BuildMI(DispContBB, dl, TII->get(ARM::LDRrs), NewVReg5) 7881 .addReg(NewVReg3, RegState::Kill) 7882 .addReg(NewVReg4) 7883 .addImm(0) 7884 .addMemOperand(JTMMOLd)); 7885 7886 if (IsPositionIndependent) { 7887 BuildMI(DispContBB, dl, TII->get(ARM::BR_JTadd)) 7888 .addReg(NewVReg5, RegState::Kill) 7889 .addReg(NewVReg4) 7890 .addJumpTableIndex(MJTI); 7891 } else { 7892 BuildMI(DispContBB, dl, TII->get(ARM::BR_JTr)) 7893 .addReg(NewVReg5, RegState::Kill) 7894 .addJumpTableIndex(MJTI); 7895 } 7896 } 7897 7898 // Add the jump table entries as successors to the MBB. 7899 SmallPtrSet<MachineBasicBlock*, 8> SeenMBBs; 7900 for (std::vector<MachineBasicBlock*>::iterator 7901 I = LPadList.begin(), E = LPadList.end(); I != E; ++I) { 7902 MachineBasicBlock *CurMBB = *I; 7903 if (SeenMBBs.insert(CurMBB).second) 7904 DispContBB->addSuccessor(CurMBB); 7905 } 7906 7907 // N.B. the order the invoke BBs are processed in doesn't matter here. 7908 const MCPhysReg *SavedRegs = RI.getCalleeSavedRegs(MF); 7909 SmallVector<MachineBasicBlock*, 64> MBBLPads; 7910 for (MachineBasicBlock *BB : InvokeBBs) { 7911 7912 // Remove the landing pad successor from the invoke block and replace it 7913 // with the new dispatch block. 7914 SmallVector<MachineBasicBlock*, 4> Successors(BB->succ_begin(), 7915 BB->succ_end()); 7916 while (!Successors.empty()) { 7917 MachineBasicBlock *SMBB = Successors.pop_back_val(); 7918 if (SMBB->isEHPad()) { 7919 BB->removeSuccessor(SMBB); 7920 MBBLPads.push_back(SMBB); 7921 } 7922 } 7923 7924 BB->addSuccessor(DispatchBB, BranchProbability::getZero()); 7925 BB->normalizeSuccProbs(); 7926 7927 // Find the invoke call and mark all of the callee-saved registers as 7928 // 'implicit defined' so that they're spilled. This prevents code from 7929 // moving instructions to before the EH block, where they will never be 7930 // executed. 7931 for (MachineBasicBlock::reverse_iterator 7932 II = BB->rbegin(), IE = BB->rend(); II != IE; ++II) { 7933 if (!II->isCall()) continue; 7934 7935 DenseMap<unsigned, bool> DefRegs; 7936 for (MachineInstr::mop_iterator 7937 OI = II->operands_begin(), OE = II->operands_end(); 7938 OI != OE; ++OI) { 7939 if (!OI->isReg()) continue; 7940 DefRegs[OI->getReg()] = true; 7941 } 7942 7943 MachineInstrBuilder MIB(*MF, &*II); 7944 7945 for (unsigned i = 0; SavedRegs[i] != 0; ++i) { 7946 unsigned Reg = SavedRegs[i]; 7947 if (Subtarget->isThumb2() && 7948 !ARM::tGPRRegClass.contains(Reg) && 7949 !ARM::hGPRRegClass.contains(Reg)) 7950 continue; 7951 if (Subtarget->isThumb1Only() && !ARM::tGPRRegClass.contains(Reg)) 7952 continue; 7953 if (!Subtarget->isThumb() && !ARM::GPRRegClass.contains(Reg)) 7954 continue; 7955 if (!DefRegs[Reg]) 7956 MIB.addReg(Reg, RegState::ImplicitDefine | RegState::Dead); 7957 } 7958 7959 break; 7960 } 7961 } 7962 7963 // Mark all former landing pads as non-landing pads. The dispatch is the only 7964 // landing pad now. 7965 for (SmallVectorImpl<MachineBasicBlock*>::iterator 7966 I = MBBLPads.begin(), E = MBBLPads.end(); I != E; ++I) 7967 (*I)->setIsEHPad(false); 7968 7969 // The instruction is gone now. 7970 MI.eraseFromParent(); 7971 } 7972 7973 static 7974 MachineBasicBlock *OtherSucc(MachineBasicBlock *MBB, MachineBasicBlock *Succ) { 7975 for (MachineBasicBlock::succ_iterator I = MBB->succ_begin(), 7976 E = MBB->succ_end(); I != E; ++I) 7977 if (*I != Succ) 7978 return *I; 7979 llvm_unreachable("Expecting a BB with two successors!"); 7980 } 7981 7982 /// Return the load opcode for a given load size. If load size >= 8, 7983 /// neon opcode will be returned. 7984 static unsigned getLdOpcode(unsigned LdSize, bool IsThumb1, bool IsThumb2) { 7985 if (LdSize >= 8) 7986 return LdSize == 16 ? ARM::VLD1q32wb_fixed 7987 : LdSize == 8 ? ARM::VLD1d32wb_fixed : 0; 7988 if (IsThumb1) 7989 return LdSize == 4 ? ARM::tLDRi 7990 : LdSize == 2 ? ARM::tLDRHi 7991 : LdSize == 1 ? ARM::tLDRBi : 0; 7992 if (IsThumb2) 7993 return LdSize == 4 ? ARM::t2LDR_POST 7994 : LdSize == 2 ? ARM::t2LDRH_POST 7995 : LdSize == 1 ? ARM::t2LDRB_POST : 0; 7996 return LdSize == 4 ? ARM::LDR_POST_IMM 7997 : LdSize == 2 ? ARM::LDRH_POST 7998 : LdSize == 1 ? ARM::LDRB_POST_IMM : 0; 7999 } 8000 8001 /// Return the store opcode for a given store size. If store size >= 8, 8002 /// neon opcode will be returned. 8003 static unsigned getStOpcode(unsigned StSize, bool IsThumb1, bool IsThumb2) { 8004 if (StSize >= 8) 8005 return StSize == 16 ? ARM::VST1q32wb_fixed 8006 : StSize == 8 ? ARM::VST1d32wb_fixed : 0; 8007 if (IsThumb1) 8008 return StSize == 4 ? ARM::tSTRi 8009 : StSize == 2 ? ARM::tSTRHi 8010 : StSize == 1 ? ARM::tSTRBi : 0; 8011 if (IsThumb2) 8012 return StSize == 4 ? ARM::t2STR_POST 8013 : StSize == 2 ? ARM::t2STRH_POST 8014 : StSize == 1 ? ARM::t2STRB_POST : 0; 8015 return StSize == 4 ? ARM::STR_POST_IMM 8016 : StSize == 2 ? ARM::STRH_POST 8017 : StSize == 1 ? ARM::STRB_POST_IMM : 0; 8018 } 8019 8020 /// Emit a post-increment load operation with given size. The instructions 8021 /// will be added to BB at Pos. 8022 static void emitPostLd(MachineBasicBlock *BB, MachineBasicBlock::iterator Pos, 8023 const TargetInstrInfo *TII, const DebugLoc &dl, 8024 unsigned LdSize, unsigned Data, unsigned AddrIn, 8025 unsigned AddrOut, bool IsThumb1, bool IsThumb2) { 8026 unsigned LdOpc = getLdOpcode(LdSize, IsThumb1, IsThumb2); 8027 assert(LdOpc != 0 && "Should have a load opcode"); 8028 if (LdSize >= 8) { 8029 AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(LdOpc), Data) 8030 .addReg(AddrOut, RegState::Define).addReg(AddrIn) 8031 .addImm(0)); 8032 } else if (IsThumb1) { 8033 // load + update AddrIn 8034 AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(LdOpc), Data) 8035 .addReg(AddrIn).addImm(0)); 8036 MachineInstrBuilder MIB = 8037 BuildMI(*BB, Pos, dl, TII->get(ARM::tADDi8), AddrOut); 8038 MIB = AddDefaultT1CC(MIB); 8039 MIB.addReg(AddrIn).addImm(LdSize); 8040 AddDefaultPred(MIB); 8041 } else if (IsThumb2) { 8042 AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(LdOpc), Data) 8043 .addReg(AddrOut, RegState::Define).addReg(AddrIn) 8044 .addImm(LdSize)); 8045 } else { // arm 8046 AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(LdOpc), Data) 8047 .addReg(AddrOut, RegState::Define).addReg(AddrIn) 8048 .addReg(0).addImm(LdSize)); 8049 } 8050 } 8051 8052 /// Emit a post-increment store operation with given size. The instructions 8053 /// will be added to BB at Pos. 8054 static void emitPostSt(MachineBasicBlock *BB, MachineBasicBlock::iterator Pos, 8055 const TargetInstrInfo *TII, const DebugLoc &dl, 8056 unsigned StSize, unsigned Data, unsigned AddrIn, 8057 unsigned AddrOut, bool IsThumb1, bool IsThumb2) { 8058 unsigned StOpc = getStOpcode(StSize, IsThumb1, IsThumb2); 8059 assert(StOpc != 0 && "Should have a store opcode"); 8060 if (StSize >= 8) { 8061 AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(StOpc), AddrOut) 8062 .addReg(AddrIn).addImm(0).addReg(Data)); 8063 } else if (IsThumb1) { 8064 // store + update AddrIn 8065 AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(StOpc)).addReg(Data) 8066 .addReg(AddrIn).addImm(0)); 8067 MachineInstrBuilder MIB = 8068 BuildMI(*BB, Pos, dl, TII->get(ARM::tADDi8), AddrOut); 8069 MIB = AddDefaultT1CC(MIB); 8070 MIB.addReg(AddrIn).addImm(StSize); 8071 AddDefaultPred(MIB); 8072 } else if (IsThumb2) { 8073 AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(StOpc), AddrOut) 8074 .addReg(Data).addReg(AddrIn).addImm(StSize)); 8075 } else { // arm 8076 AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(StOpc), AddrOut) 8077 .addReg(Data).addReg(AddrIn).addReg(0) 8078 .addImm(StSize)); 8079 } 8080 } 8081 8082 MachineBasicBlock * 8083 ARMTargetLowering::EmitStructByval(MachineInstr &MI, 8084 MachineBasicBlock *BB) const { 8085 // This pseudo instruction has 3 operands: dst, src, size 8086 // We expand it to a loop if size > Subtarget->getMaxInlineSizeThreshold(). 8087 // Otherwise, we will generate unrolled scalar copies. 8088 const TargetInstrInfo *TII = Subtarget->getInstrInfo(); 8089 const BasicBlock *LLVM_BB = BB->getBasicBlock(); 8090 MachineFunction::iterator It = ++BB->getIterator(); 8091 8092 unsigned dest = MI.getOperand(0).getReg(); 8093 unsigned src = MI.getOperand(1).getReg(); 8094 unsigned SizeVal = MI.getOperand(2).getImm(); 8095 unsigned Align = MI.getOperand(3).getImm(); 8096 DebugLoc dl = MI.getDebugLoc(); 8097 8098 MachineFunction *MF = BB->getParent(); 8099 MachineRegisterInfo &MRI = MF->getRegInfo(); 8100 unsigned UnitSize = 0; 8101 const TargetRegisterClass *TRC = nullptr; 8102 const TargetRegisterClass *VecTRC = nullptr; 8103 8104 bool IsThumb1 = Subtarget->isThumb1Only(); 8105 bool IsThumb2 = Subtarget->isThumb2(); 8106 bool IsThumb = Subtarget->isThumb(); 8107 8108 if (Align & 1) { 8109 UnitSize = 1; 8110 } else if (Align & 2) { 8111 UnitSize = 2; 8112 } else { 8113 // Check whether we can use NEON instructions. 8114 if (!MF->getFunction()->hasFnAttribute(Attribute::NoImplicitFloat) && 8115 Subtarget->hasNEON()) { 8116 if ((Align % 16 == 0) && SizeVal >= 16) 8117 UnitSize = 16; 8118 else if ((Align % 8 == 0) && SizeVal >= 8) 8119 UnitSize = 8; 8120 } 8121 // Can't use NEON instructions. 8122 if (UnitSize == 0) 8123 UnitSize = 4; 8124 } 8125 8126 // Select the correct opcode and register class for unit size load/store 8127 bool IsNeon = UnitSize >= 8; 8128 TRC = IsThumb ? &ARM::tGPRRegClass : &ARM::GPRRegClass; 8129 if (IsNeon) 8130 VecTRC = UnitSize == 16 ? &ARM::DPairRegClass 8131 : UnitSize == 8 ? &ARM::DPRRegClass 8132 : nullptr; 8133 8134 unsigned BytesLeft = SizeVal % UnitSize; 8135 unsigned LoopSize = SizeVal - BytesLeft; 8136 8137 if (SizeVal <= Subtarget->getMaxInlineSizeThreshold()) { 8138 // Use LDR and STR to copy. 8139 // [scratch, srcOut] = LDR_POST(srcIn, UnitSize) 8140 // [destOut] = STR_POST(scratch, destIn, UnitSize) 8141 unsigned srcIn = src; 8142 unsigned destIn = dest; 8143 for (unsigned i = 0; i < LoopSize; i+=UnitSize) { 8144 unsigned srcOut = MRI.createVirtualRegister(TRC); 8145 unsigned destOut = MRI.createVirtualRegister(TRC); 8146 unsigned scratch = MRI.createVirtualRegister(IsNeon ? VecTRC : TRC); 8147 emitPostLd(BB, MI, TII, dl, UnitSize, scratch, srcIn, srcOut, 8148 IsThumb1, IsThumb2); 8149 emitPostSt(BB, MI, TII, dl, UnitSize, scratch, destIn, destOut, 8150 IsThumb1, IsThumb2); 8151 srcIn = srcOut; 8152 destIn = destOut; 8153 } 8154 8155 // Handle the leftover bytes with LDRB and STRB. 8156 // [scratch, srcOut] = LDRB_POST(srcIn, 1) 8157 // [destOut] = STRB_POST(scratch, destIn, 1) 8158 for (unsigned i = 0; i < BytesLeft; i++) { 8159 unsigned srcOut = MRI.createVirtualRegister(TRC); 8160 unsigned destOut = MRI.createVirtualRegister(TRC); 8161 unsigned scratch = MRI.createVirtualRegister(TRC); 8162 emitPostLd(BB, MI, TII, dl, 1, scratch, srcIn, srcOut, 8163 IsThumb1, IsThumb2); 8164 emitPostSt(BB, MI, TII, dl, 1, scratch, destIn, destOut, 8165 IsThumb1, IsThumb2); 8166 srcIn = srcOut; 8167 destIn = destOut; 8168 } 8169 MI.eraseFromParent(); // The instruction is gone now. 8170 return BB; 8171 } 8172 8173 // Expand the pseudo op to a loop. 8174 // thisMBB: 8175 // ... 8176 // movw varEnd, # --> with thumb2 8177 // movt varEnd, # 8178 // ldrcp varEnd, idx --> without thumb2 8179 // fallthrough --> loopMBB 8180 // loopMBB: 8181 // PHI varPhi, varEnd, varLoop 8182 // PHI srcPhi, src, srcLoop 8183 // PHI destPhi, dst, destLoop 8184 // [scratch, srcLoop] = LDR_POST(srcPhi, UnitSize) 8185 // [destLoop] = STR_POST(scratch, destPhi, UnitSize) 8186 // subs varLoop, varPhi, #UnitSize 8187 // bne loopMBB 8188 // fallthrough --> exitMBB 8189 // exitMBB: 8190 // epilogue to handle left-over bytes 8191 // [scratch, srcOut] = LDRB_POST(srcLoop, 1) 8192 // [destOut] = STRB_POST(scratch, destLoop, 1) 8193 MachineBasicBlock *loopMBB = MF->CreateMachineBasicBlock(LLVM_BB); 8194 MachineBasicBlock *exitMBB = MF->CreateMachineBasicBlock(LLVM_BB); 8195 MF->insert(It, loopMBB); 8196 MF->insert(It, exitMBB); 8197 8198 // Transfer the remainder of BB and its successor edges to exitMBB. 8199 exitMBB->splice(exitMBB->begin(), BB, 8200 std::next(MachineBasicBlock::iterator(MI)), BB->end()); 8201 exitMBB->transferSuccessorsAndUpdatePHIs(BB); 8202 8203 // Load an immediate to varEnd. 8204 unsigned varEnd = MRI.createVirtualRegister(TRC); 8205 if (Subtarget->useMovt(*MF)) { 8206 unsigned Vtmp = varEnd; 8207 if ((LoopSize & 0xFFFF0000) != 0) 8208 Vtmp = MRI.createVirtualRegister(TRC); 8209 AddDefaultPred(BuildMI(BB, dl, 8210 TII->get(IsThumb ? ARM::t2MOVi16 : ARM::MOVi16), 8211 Vtmp).addImm(LoopSize & 0xFFFF)); 8212 8213 if ((LoopSize & 0xFFFF0000) != 0) 8214 AddDefaultPred(BuildMI(BB, dl, 8215 TII->get(IsThumb ? ARM::t2MOVTi16 : ARM::MOVTi16), 8216 varEnd) 8217 .addReg(Vtmp) 8218 .addImm(LoopSize >> 16)); 8219 } else { 8220 MachineConstantPool *ConstantPool = MF->getConstantPool(); 8221 Type *Int32Ty = Type::getInt32Ty(MF->getFunction()->getContext()); 8222 const Constant *C = ConstantInt::get(Int32Ty, LoopSize); 8223 8224 // MachineConstantPool wants an explicit alignment. 8225 unsigned Align = MF->getDataLayout().getPrefTypeAlignment(Int32Ty); 8226 if (Align == 0) 8227 Align = MF->getDataLayout().getTypeAllocSize(C->getType()); 8228 unsigned Idx = ConstantPool->getConstantPoolIndex(C, Align); 8229 8230 if (IsThumb) 8231 AddDefaultPred(BuildMI(*BB, MI, dl, TII->get(ARM::tLDRpci)).addReg( 8232 varEnd, RegState::Define).addConstantPoolIndex(Idx)); 8233 else 8234 AddDefaultPred(BuildMI(*BB, MI, dl, TII->get(ARM::LDRcp)).addReg( 8235 varEnd, RegState::Define).addConstantPoolIndex(Idx).addImm(0)); 8236 } 8237 BB->addSuccessor(loopMBB); 8238 8239 // Generate the loop body: 8240 // varPhi = PHI(varLoop, varEnd) 8241 // srcPhi = PHI(srcLoop, src) 8242 // destPhi = PHI(destLoop, dst) 8243 MachineBasicBlock *entryBB = BB; 8244 BB = loopMBB; 8245 unsigned varLoop = MRI.createVirtualRegister(TRC); 8246 unsigned varPhi = MRI.createVirtualRegister(TRC); 8247 unsigned srcLoop = MRI.createVirtualRegister(TRC); 8248 unsigned srcPhi = MRI.createVirtualRegister(TRC); 8249 unsigned destLoop = MRI.createVirtualRegister(TRC); 8250 unsigned destPhi = MRI.createVirtualRegister(TRC); 8251 8252 BuildMI(*BB, BB->begin(), dl, TII->get(ARM::PHI), varPhi) 8253 .addReg(varLoop).addMBB(loopMBB) 8254 .addReg(varEnd).addMBB(entryBB); 8255 BuildMI(BB, dl, TII->get(ARM::PHI), srcPhi) 8256 .addReg(srcLoop).addMBB(loopMBB) 8257 .addReg(src).addMBB(entryBB); 8258 BuildMI(BB, dl, TII->get(ARM::PHI), destPhi) 8259 .addReg(destLoop).addMBB(loopMBB) 8260 .addReg(dest).addMBB(entryBB); 8261 8262 // [scratch, srcLoop] = LDR_POST(srcPhi, UnitSize) 8263 // [destLoop] = STR_POST(scratch, destPhi, UnitSiz) 8264 unsigned scratch = MRI.createVirtualRegister(IsNeon ? VecTRC : TRC); 8265 emitPostLd(BB, BB->end(), TII, dl, UnitSize, scratch, srcPhi, srcLoop, 8266 IsThumb1, IsThumb2); 8267 emitPostSt(BB, BB->end(), TII, dl, UnitSize, scratch, destPhi, destLoop, 8268 IsThumb1, IsThumb2); 8269 8270 // Decrement loop variable by UnitSize. 8271 if (IsThumb1) { 8272 MachineInstrBuilder MIB = 8273 BuildMI(*BB, BB->end(), dl, TII->get(ARM::tSUBi8), varLoop); 8274 MIB = AddDefaultT1CC(MIB); 8275 MIB.addReg(varPhi).addImm(UnitSize); 8276 AddDefaultPred(MIB); 8277 } else { 8278 MachineInstrBuilder MIB = 8279 BuildMI(*BB, BB->end(), dl, 8280 TII->get(IsThumb2 ? ARM::t2SUBri : ARM::SUBri), varLoop); 8281 AddDefaultCC(AddDefaultPred(MIB.addReg(varPhi).addImm(UnitSize))); 8282 MIB->getOperand(5).setReg(ARM::CPSR); 8283 MIB->getOperand(5).setIsDef(true); 8284 } 8285 BuildMI(*BB, BB->end(), dl, 8286 TII->get(IsThumb1 ? ARM::tBcc : IsThumb2 ? ARM::t2Bcc : ARM::Bcc)) 8287 .addMBB(loopMBB).addImm(ARMCC::NE).addReg(ARM::CPSR); 8288 8289 // loopMBB can loop back to loopMBB or fall through to exitMBB. 8290 BB->addSuccessor(loopMBB); 8291 BB->addSuccessor(exitMBB); 8292 8293 // Add epilogue to handle BytesLeft. 8294 BB = exitMBB; 8295 auto StartOfExit = exitMBB->begin(); 8296 8297 // [scratch, srcOut] = LDRB_POST(srcLoop, 1) 8298 // [destOut] = STRB_POST(scratch, destLoop, 1) 8299 unsigned srcIn = srcLoop; 8300 unsigned destIn = destLoop; 8301 for (unsigned i = 0; i < BytesLeft; i++) { 8302 unsigned srcOut = MRI.createVirtualRegister(TRC); 8303 unsigned destOut = MRI.createVirtualRegister(TRC); 8304 unsigned scratch = MRI.createVirtualRegister(TRC); 8305 emitPostLd(BB, StartOfExit, TII, dl, 1, scratch, srcIn, srcOut, 8306 IsThumb1, IsThumb2); 8307 emitPostSt(BB, StartOfExit, TII, dl, 1, scratch, destIn, destOut, 8308 IsThumb1, IsThumb2); 8309 srcIn = srcOut; 8310 destIn = destOut; 8311 } 8312 8313 MI.eraseFromParent(); // The instruction is gone now. 8314 return BB; 8315 } 8316 8317 MachineBasicBlock * 8318 ARMTargetLowering::EmitLowered__chkstk(MachineInstr &MI, 8319 MachineBasicBlock *MBB) const { 8320 const TargetMachine &TM = getTargetMachine(); 8321 const TargetInstrInfo &TII = *Subtarget->getInstrInfo(); 8322 DebugLoc DL = MI.getDebugLoc(); 8323 8324 assert(Subtarget->isTargetWindows() && 8325 "__chkstk is only supported on Windows"); 8326 assert(Subtarget->isThumb2() && "Windows on ARM requires Thumb-2 mode"); 8327 8328 // __chkstk takes the number of words to allocate on the stack in R4, and 8329 // returns the stack adjustment in number of bytes in R4. This will not 8330 // clober any other registers (other than the obvious lr). 8331 // 8332 // Although, technically, IP should be considered a register which may be 8333 // clobbered, the call itself will not touch it. Windows on ARM is a pure 8334 // thumb-2 environment, so there is no interworking required. As a result, we 8335 // do not expect a veneer to be emitted by the linker, clobbering IP. 8336 // 8337 // Each module receives its own copy of __chkstk, so no import thunk is 8338 // required, again, ensuring that IP is not clobbered. 8339 // 8340 // Finally, although some linkers may theoretically provide a trampoline for 8341 // out of range calls (which is quite common due to a 32M range limitation of 8342 // branches for Thumb), we can generate the long-call version via 8343 // -mcmodel=large, alleviating the need for the trampoline which may clobber 8344 // IP. 8345 8346 switch (TM.getCodeModel()) { 8347 case CodeModel::Small: 8348 case CodeModel::Medium: 8349 case CodeModel::Default: 8350 case CodeModel::Kernel: 8351 BuildMI(*MBB, MI, DL, TII.get(ARM::tBL)) 8352 .addImm((unsigned)ARMCC::AL).addReg(0) 8353 .addExternalSymbol("__chkstk") 8354 .addReg(ARM::R4, RegState::Implicit | RegState::Kill) 8355 .addReg(ARM::R4, RegState::Implicit | RegState::Define) 8356 .addReg(ARM::R12, RegState::Implicit | RegState::Define | RegState::Dead); 8357 break; 8358 case CodeModel::Large: 8359 case CodeModel::JITDefault: { 8360 MachineRegisterInfo &MRI = MBB->getParent()->getRegInfo(); 8361 unsigned Reg = MRI.createVirtualRegister(&ARM::rGPRRegClass); 8362 8363 BuildMI(*MBB, MI, DL, TII.get(ARM::t2MOVi32imm), Reg) 8364 .addExternalSymbol("__chkstk"); 8365 BuildMI(*MBB, MI, DL, TII.get(ARM::tBLXr)) 8366 .addImm((unsigned)ARMCC::AL).addReg(0) 8367 .addReg(Reg, RegState::Kill) 8368 .addReg(ARM::R4, RegState::Implicit | RegState::Kill) 8369 .addReg(ARM::R4, RegState::Implicit | RegState::Define) 8370 .addReg(ARM::R12, RegState::Implicit | RegState::Define | RegState::Dead); 8371 break; 8372 } 8373 } 8374 8375 AddDefaultCC(AddDefaultPred(BuildMI(*MBB, MI, DL, TII.get(ARM::t2SUBrr), 8376 ARM::SP) 8377 .addReg(ARM::SP, RegState::Kill) 8378 .addReg(ARM::R4, RegState::Kill) 8379 .setMIFlags(MachineInstr::FrameSetup))); 8380 8381 MI.eraseFromParent(); 8382 return MBB; 8383 } 8384 8385 MachineBasicBlock * 8386 ARMTargetLowering::EmitLowered__dbzchk(MachineInstr &MI, 8387 MachineBasicBlock *MBB) const { 8388 DebugLoc DL = MI.getDebugLoc(); 8389 MachineFunction *MF = MBB->getParent(); 8390 const TargetInstrInfo *TII = Subtarget->getInstrInfo(); 8391 8392 MachineBasicBlock *ContBB = MF->CreateMachineBasicBlock(); 8393 MF->insert(++MBB->getIterator(), ContBB); 8394 ContBB->splice(ContBB->begin(), MBB, 8395 std::next(MachineBasicBlock::iterator(MI)), MBB->end()); 8396 ContBB->transferSuccessorsAndUpdatePHIs(MBB); 8397 8398 MachineBasicBlock *TrapBB = MF->CreateMachineBasicBlock(); 8399 MF->push_back(TrapBB); 8400 BuildMI(TrapBB, DL, TII->get(ARM::t2UDF)).addImm(249); 8401 MBB->addSuccessor(TrapBB); 8402 8403 BuildMI(*MBB, MI, DL, TII->get(ARM::tCBZ)) 8404 .addReg(MI.getOperand(0).getReg()) 8405 .addMBB(TrapBB); 8406 AddDefaultPred(BuildMI(*MBB, MI, DL, TII->get(ARM::t2B)).addMBB(ContBB)); 8407 MBB->addSuccessor(ContBB); 8408 8409 MI.eraseFromParent(); 8410 return ContBB; 8411 } 8412 8413 MachineBasicBlock * 8414 ARMTargetLowering::EmitInstrWithCustomInserter(MachineInstr &MI, 8415 MachineBasicBlock *BB) const { 8416 const TargetInstrInfo *TII = Subtarget->getInstrInfo(); 8417 DebugLoc dl = MI.getDebugLoc(); 8418 bool isThumb2 = Subtarget->isThumb2(); 8419 switch (MI.getOpcode()) { 8420 default: { 8421 MI.dump(); 8422 llvm_unreachable("Unexpected instr type to insert"); 8423 } 8424 8425 // Thumb1 post-indexed loads are really just single-register LDMs. 8426 case ARM::tLDR_postidx: { 8427 BuildMI(*BB, MI, dl, TII->get(ARM::tLDMIA_UPD)) 8428 .addOperand(MI.getOperand(1)) // Rn_wb 8429 .addOperand(MI.getOperand(2)) // Rn 8430 .addOperand(MI.getOperand(3)) // PredImm 8431 .addOperand(MI.getOperand(4)) // PredReg 8432 .addOperand(MI.getOperand(0)); // Rt 8433 MI.eraseFromParent(); 8434 return BB; 8435 } 8436 8437 // The Thumb2 pre-indexed stores have the same MI operands, they just 8438 // define them differently in the .td files from the isel patterns, so 8439 // they need pseudos. 8440 case ARM::t2STR_preidx: 8441 MI.setDesc(TII->get(ARM::t2STR_PRE)); 8442 return BB; 8443 case ARM::t2STRB_preidx: 8444 MI.setDesc(TII->get(ARM::t2STRB_PRE)); 8445 return BB; 8446 case ARM::t2STRH_preidx: 8447 MI.setDesc(TII->get(ARM::t2STRH_PRE)); 8448 return BB; 8449 8450 case ARM::STRi_preidx: 8451 case ARM::STRBi_preidx: { 8452 unsigned NewOpc = MI.getOpcode() == ARM::STRi_preidx ? ARM::STR_PRE_IMM 8453 : ARM::STRB_PRE_IMM; 8454 // Decode the offset. 8455 unsigned Offset = MI.getOperand(4).getImm(); 8456 bool isSub = ARM_AM::getAM2Op(Offset) == ARM_AM::sub; 8457 Offset = ARM_AM::getAM2Offset(Offset); 8458 if (isSub) 8459 Offset = -Offset; 8460 8461 MachineMemOperand *MMO = *MI.memoperands_begin(); 8462 BuildMI(*BB, MI, dl, TII->get(NewOpc)) 8463 .addOperand(MI.getOperand(0)) // Rn_wb 8464 .addOperand(MI.getOperand(1)) // Rt 8465 .addOperand(MI.getOperand(2)) // Rn 8466 .addImm(Offset) // offset (skip GPR==zero_reg) 8467 .addOperand(MI.getOperand(5)) // pred 8468 .addOperand(MI.getOperand(6)) 8469 .addMemOperand(MMO); 8470 MI.eraseFromParent(); 8471 return BB; 8472 } 8473 case ARM::STRr_preidx: 8474 case ARM::STRBr_preidx: 8475 case ARM::STRH_preidx: { 8476 unsigned NewOpc; 8477 switch (MI.getOpcode()) { 8478 default: llvm_unreachable("unexpected opcode!"); 8479 case ARM::STRr_preidx: NewOpc = ARM::STR_PRE_REG; break; 8480 case ARM::STRBr_preidx: NewOpc = ARM::STRB_PRE_REG; break; 8481 case ARM::STRH_preidx: NewOpc = ARM::STRH_PRE; break; 8482 } 8483 MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(NewOpc)); 8484 for (unsigned i = 0; i < MI.getNumOperands(); ++i) 8485 MIB.addOperand(MI.getOperand(i)); 8486 MI.eraseFromParent(); 8487 return BB; 8488 } 8489 8490 case ARM::tMOVCCr_pseudo: { 8491 // To "insert" a SELECT_CC instruction, we actually have to insert the 8492 // diamond control-flow pattern. The incoming instruction knows the 8493 // destination vreg to set, the condition code register to branch on, the 8494 // true/false values to select between, and a branch opcode to use. 8495 const BasicBlock *LLVM_BB = BB->getBasicBlock(); 8496 MachineFunction::iterator It = ++BB->getIterator(); 8497 8498 // thisMBB: 8499 // ... 8500 // TrueVal = ... 8501 // cmpTY ccX, r1, r2 8502 // bCC copy1MBB 8503 // fallthrough --> copy0MBB 8504 MachineBasicBlock *thisMBB = BB; 8505 MachineFunction *F = BB->getParent(); 8506 MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB); 8507 MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB); 8508 F->insert(It, copy0MBB); 8509 F->insert(It, sinkMBB); 8510 8511 // Transfer the remainder of BB and its successor edges to sinkMBB. 8512 sinkMBB->splice(sinkMBB->begin(), BB, 8513 std::next(MachineBasicBlock::iterator(MI)), BB->end()); 8514 sinkMBB->transferSuccessorsAndUpdatePHIs(BB); 8515 8516 BB->addSuccessor(copy0MBB); 8517 BB->addSuccessor(sinkMBB); 8518 8519 BuildMI(BB, dl, TII->get(ARM::tBcc)) 8520 .addMBB(sinkMBB) 8521 .addImm(MI.getOperand(3).getImm()) 8522 .addReg(MI.getOperand(4).getReg()); 8523 8524 // copy0MBB: 8525 // %FalseValue = ... 8526 // # fallthrough to sinkMBB 8527 BB = copy0MBB; 8528 8529 // Update machine-CFG edges 8530 BB->addSuccessor(sinkMBB); 8531 8532 // sinkMBB: 8533 // %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ] 8534 // ... 8535 BB = sinkMBB; 8536 BuildMI(*BB, BB->begin(), dl, TII->get(ARM::PHI), MI.getOperand(0).getReg()) 8537 .addReg(MI.getOperand(1).getReg()) 8538 .addMBB(copy0MBB) 8539 .addReg(MI.getOperand(2).getReg()) 8540 .addMBB(thisMBB); 8541 8542 MI.eraseFromParent(); // The pseudo instruction is gone now. 8543 return BB; 8544 } 8545 8546 case ARM::BCCi64: 8547 case ARM::BCCZi64: { 8548 // If there is an unconditional branch to the other successor, remove it. 8549 BB->erase(std::next(MachineBasicBlock::iterator(MI)), BB->end()); 8550 8551 // Compare both parts that make up the double comparison separately for 8552 // equality. 8553 bool RHSisZero = MI.getOpcode() == ARM::BCCZi64; 8554 8555 unsigned LHS1 = MI.getOperand(1).getReg(); 8556 unsigned LHS2 = MI.getOperand(2).getReg(); 8557 if (RHSisZero) { 8558 AddDefaultPred(BuildMI(BB, dl, 8559 TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri)) 8560 .addReg(LHS1).addImm(0)); 8561 BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri)) 8562 .addReg(LHS2).addImm(0) 8563 .addImm(ARMCC::EQ).addReg(ARM::CPSR); 8564 } else { 8565 unsigned RHS1 = MI.getOperand(3).getReg(); 8566 unsigned RHS2 = MI.getOperand(4).getReg(); 8567 AddDefaultPred(BuildMI(BB, dl, 8568 TII->get(isThumb2 ? ARM::t2CMPrr : ARM::CMPrr)) 8569 .addReg(LHS1).addReg(RHS1)); 8570 BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPrr : ARM::CMPrr)) 8571 .addReg(LHS2).addReg(RHS2) 8572 .addImm(ARMCC::EQ).addReg(ARM::CPSR); 8573 } 8574 8575 MachineBasicBlock *destMBB = MI.getOperand(RHSisZero ? 3 : 5).getMBB(); 8576 MachineBasicBlock *exitMBB = OtherSucc(BB, destMBB); 8577 if (MI.getOperand(0).getImm() == ARMCC::NE) 8578 std::swap(destMBB, exitMBB); 8579 8580 BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc)) 8581 .addMBB(destMBB).addImm(ARMCC::EQ).addReg(ARM::CPSR); 8582 if (isThumb2) 8583 AddDefaultPred(BuildMI(BB, dl, TII->get(ARM::t2B)).addMBB(exitMBB)); 8584 else 8585 BuildMI(BB, dl, TII->get(ARM::B)) .addMBB(exitMBB); 8586 8587 MI.eraseFromParent(); // The pseudo instruction is gone now. 8588 return BB; 8589 } 8590 8591 case ARM::Int_eh_sjlj_setjmp: 8592 case ARM::Int_eh_sjlj_setjmp_nofp: 8593 case ARM::tInt_eh_sjlj_setjmp: 8594 case ARM::t2Int_eh_sjlj_setjmp: 8595 case ARM::t2Int_eh_sjlj_setjmp_nofp: 8596 return BB; 8597 8598 case ARM::Int_eh_sjlj_setup_dispatch: 8599 EmitSjLjDispatchBlock(MI, BB); 8600 return BB; 8601 8602 case ARM::ABS: 8603 case ARM::t2ABS: { 8604 // To insert an ABS instruction, we have to insert the 8605 // diamond control-flow pattern. The incoming instruction knows the 8606 // source vreg to test against 0, the destination vreg to set, 8607 // the condition code register to branch on, the 8608 // true/false values to select between, and a branch opcode to use. 8609 // It transforms 8610 // V1 = ABS V0 8611 // into 8612 // V2 = MOVS V0 8613 // BCC (branch to SinkBB if V0 >= 0) 8614 // RSBBB: V3 = RSBri V2, 0 (compute ABS if V2 < 0) 8615 // SinkBB: V1 = PHI(V2, V3) 8616 const BasicBlock *LLVM_BB = BB->getBasicBlock(); 8617 MachineFunction::iterator BBI = ++BB->getIterator(); 8618 MachineFunction *Fn = BB->getParent(); 8619 MachineBasicBlock *RSBBB = Fn->CreateMachineBasicBlock(LLVM_BB); 8620 MachineBasicBlock *SinkBB = Fn->CreateMachineBasicBlock(LLVM_BB); 8621 Fn->insert(BBI, RSBBB); 8622 Fn->insert(BBI, SinkBB); 8623 8624 unsigned int ABSSrcReg = MI.getOperand(1).getReg(); 8625 unsigned int ABSDstReg = MI.getOperand(0).getReg(); 8626 bool ABSSrcKIll = MI.getOperand(1).isKill(); 8627 bool isThumb2 = Subtarget->isThumb2(); 8628 MachineRegisterInfo &MRI = Fn->getRegInfo(); 8629 // In Thumb mode S must not be specified if source register is the SP or 8630 // PC and if destination register is the SP, so restrict register class 8631 unsigned NewRsbDstReg = 8632 MRI.createVirtualRegister(isThumb2 ? &ARM::rGPRRegClass : &ARM::GPRRegClass); 8633 8634 // Transfer the remainder of BB and its successor edges to sinkMBB. 8635 SinkBB->splice(SinkBB->begin(), BB, 8636 std::next(MachineBasicBlock::iterator(MI)), BB->end()); 8637 SinkBB->transferSuccessorsAndUpdatePHIs(BB); 8638 8639 BB->addSuccessor(RSBBB); 8640 BB->addSuccessor(SinkBB); 8641 8642 // fall through to SinkMBB 8643 RSBBB->addSuccessor(SinkBB); 8644 8645 // insert a cmp at the end of BB 8646 AddDefaultPred(BuildMI(BB, dl, 8647 TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri)) 8648 .addReg(ABSSrcReg).addImm(0)); 8649 8650 // insert a bcc with opposite CC to ARMCC::MI at the end of BB 8651 BuildMI(BB, dl, 8652 TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc)).addMBB(SinkBB) 8653 .addImm(ARMCC::getOppositeCondition(ARMCC::MI)).addReg(ARM::CPSR); 8654 8655 // insert rsbri in RSBBB 8656 // Note: BCC and rsbri will be converted into predicated rsbmi 8657 // by if-conversion pass 8658 BuildMI(*RSBBB, RSBBB->begin(), dl, 8659 TII->get(isThumb2 ? ARM::t2RSBri : ARM::RSBri), NewRsbDstReg) 8660 .addReg(ABSSrcReg, ABSSrcKIll ? RegState::Kill : 0) 8661 .addImm(0).addImm((unsigned)ARMCC::AL).addReg(0).addReg(0); 8662 8663 // insert PHI in SinkBB, 8664 // reuse ABSDstReg to not change uses of ABS instruction 8665 BuildMI(*SinkBB, SinkBB->begin(), dl, 8666 TII->get(ARM::PHI), ABSDstReg) 8667 .addReg(NewRsbDstReg).addMBB(RSBBB) 8668 .addReg(ABSSrcReg).addMBB(BB); 8669 8670 // remove ABS instruction 8671 MI.eraseFromParent(); 8672 8673 // return last added BB 8674 return SinkBB; 8675 } 8676 case ARM::COPY_STRUCT_BYVAL_I32: 8677 ++NumLoopByVals; 8678 return EmitStructByval(MI, BB); 8679 case ARM::WIN__CHKSTK: 8680 return EmitLowered__chkstk(MI, BB); 8681 case ARM::WIN__DBZCHK: 8682 return EmitLowered__dbzchk(MI, BB); 8683 } 8684 } 8685 8686 /// \brief Attaches vregs to MEMCPY that it will use as scratch registers 8687 /// when it is expanded into LDM/STM. This is done as a post-isel lowering 8688 /// instead of as a custom inserter because we need the use list from the SDNode. 8689 static void attachMEMCPYScratchRegs(const ARMSubtarget *Subtarget, 8690 MachineInstr &MI, const SDNode *Node) { 8691 bool isThumb1 = Subtarget->isThumb1Only(); 8692 8693 DebugLoc DL = MI.getDebugLoc(); 8694 MachineFunction *MF = MI.getParent()->getParent(); 8695 MachineRegisterInfo &MRI = MF->getRegInfo(); 8696 MachineInstrBuilder MIB(*MF, MI); 8697 8698 // If the new dst/src is unused mark it as dead. 8699 if (!Node->hasAnyUseOfValue(0)) { 8700 MI.getOperand(0).setIsDead(true); 8701 } 8702 if (!Node->hasAnyUseOfValue(1)) { 8703 MI.getOperand(1).setIsDead(true); 8704 } 8705 8706 // The MEMCPY both defines and kills the scratch registers. 8707 for (unsigned I = 0; I != MI.getOperand(4).getImm(); ++I) { 8708 unsigned TmpReg = MRI.createVirtualRegister(isThumb1 ? &ARM::tGPRRegClass 8709 : &ARM::GPRRegClass); 8710 MIB.addReg(TmpReg, RegState::Define|RegState::Dead); 8711 } 8712 } 8713 8714 void ARMTargetLowering::AdjustInstrPostInstrSelection(MachineInstr &MI, 8715 SDNode *Node) const { 8716 if (MI.getOpcode() == ARM::MEMCPY) { 8717 attachMEMCPYScratchRegs(Subtarget, MI, Node); 8718 return; 8719 } 8720 8721 const MCInstrDesc *MCID = &MI.getDesc(); 8722 // Adjust potentially 's' setting instructions after isel, i.e. ADC, SBC, RSB, 8723 // RSC. Coming out of isel, they have an implicit CPSR def, but the optional 8724 // operand is still set to noreg. If needed, set the optional operand's 8725 // register to CPSR, and remove the redundant implicit def. 8726 // 8727 // e.g. ADCS (..., CPSR<imp-def>) -> ADC (... opt:CPSR<def>). 8728 8729 // Rename pseudo opcodes. 8730 unsigned NewOpc = convertAddSubFlagsOpcode(MI.getOpcode()); 8731 if (NewOpc) { 8732 const ARMBaseInstrInfo *TII = Subtarget->getInstrInfo(); 8733 MCID = &TII->get(NewOpc); 8734 8735 assert(MCID->getNumOperands() == MI.getDesc().getNumOperands() + 1 && 8736 "converted opcode should be the same except for cc_out"); 8737 8738 MI.setDesc(*MCID); 8739 8740 // Add the optional cc_out operand 8741 MI.addOperand(MachineOperand::CreateReg(0, /*isDef=*/true)); 8742 } 8743 unsigned ccOutIdx = MCID->getNumOperands() - 1; 8744 8745 // Any ARM instruction that sets the 's' bit should specify an optional 8746 // "cc_out" operand in the last operand position. 8747 if (!MI.hasOptionalDef() || !MCID->OpInfo[ccOutIdx].isOptionalDef()) { 8748 assert(!NewOpc && "Optional cc_out operand required"); 8749 return; 8750 } 8751 // Look for an implicit def of CPSR added by MachineInstr ctor. Remove it 8752 // since we already have an optional CPSR def. 8753 bool definesCPSR = false; 8754 bool deadCPSR = false; 8755 for (unsigned i = MCID->getNumOperands(), e = MI.getNumOperands(); i != e; 8756 ++i) { 8757 const MachineOperand &MO = MI.getOperand(i); 8758 if (MO.isReg() && MO.isDef() && MO.getReg() == ARM::CPSR) { 8759 definesCPSR = true; 8760 if (MO.isDead()) 8761 deadCPSR = true; 8762 MI.RemoveOperand(i); 8763 break; 8764 } 8765 } 8766 if (!definesCPSR) { 8767 assert(!NewOpc && "Optional cc_out operand required"); 8768 return; 8769 } 8770 assert(deadCPSR == !Node->hasAnyUseOfValue(1) && "inconsistent dead flag"); 8771 if (deadCPSR) { 8772 assert(!MI.getOperand(ccOutIdx).getReg() && 8773 "expect uninitialized optional cc_out operand"); 8774 return; 8775 } 8776 8777 // If this instruction was defined with an optional CPSR def and its dag node 8778 // had a live implicit CPSR def, then activate the optional CPSR def. 8779 MachineOperand &MO = MI.getOperand(ccOutIdx); 8780 MO.setReg(ARM::CPSR); 8781 MO.setIsDef(true); 8782 } 8783 8784 //===----------------------------------------------------------------------===// 8785 // ARM Optimization Hooks 8786 //===----------------------------------------------------------------------===// 8787 8788 // Helper function that checks if N is a null or all ones constant. 8789 static inline bool isZeroOrAllOnes(SDValue N, bool AllOnes) { 8790 return AllOnes ? isAllOnesConstant(N) : isNullConstant(N); 8791 } 8792 8793 // Return true if N is conditionally 0 or all ones. 8794 // Detects these expressions where cc is an i1 value: 8795 // 8796 // (select cc 0, y) [AllOnes=0] 8797 // (select cc y, 0) [AllOnes=0] 8798 // (zext cc) [AllOnes=0] 8799 // (sext cc) [AllOnes=0/1] 8800 // (select cc -1, y) [AllOnes=1] 8801 // (select cc y, -1) [AllOnes=1] 8802 // 8803 // Invert is set when N is the null/all ones constant when CC is false. 8804 // OtherOp is set to the alternative value of N. 8805 static bool isConditionalZeroOrAllOnes(SDNode *N, bool AllOnes, 8806 SDValue &CC, bool &Invert, 8807 SDValue &OtherOp, 8808 SelectionDAG &DAG) { 8809 switch (N->getOpcode()) { 8810 default: return false; 8811 case ISD::SELECT: { 8812 CC = N->getOperand(0); 8813 SDValue N1 = N->getOperand(1); 8814 SDValue N2 = N->getOperand(2); 8815 if (isZeroOrAllOnes(N1, AllOnes)) { 8816 Invert = false; 8817 OtherOp = N2; 8818 return true; 8819 } 8820 if (isZeroOrAllOnes(N2, AllOnes)) { 8821 Invert = true; 8822 OtherOp = N1; 8823 return true; 8824 } 8825 return false; 8826 } 8827 case ISD::ZERO_EXTEND: 8828 // (zext cc) can never be the all ones value. 8829 if (AllOnes) 8830 return false; 8831 LLVM_FALLTHROUGH; 8832 case ISD::SIGN_EXTEND: { 8833 SDLoc dl(N); 8834 EVT VT = N->getValueType(0); 8835 CC = N->getOperand(0); 8836 if (CC.getValueType() != MVT::i1) 8837 return false; 8838 Invert = !AllOnes; 8839 if (AllOnes) 8840 // When looking for an AllOnes constant, N is an sext, and the 'other' 8841 // value is 0. 8842 OtherOp = DAG.getConstant(0, dl, VT); 8843 else if (N->getOpcode() == ISD::ZERO_EXTEND) 8844 // When looking for a 0 constant, N can be zext or sext. 8845 OtherOp = DAG.getConstant(1, dl, VT); 8846 else 8847 OtherOp = DAG.getConstant(APInt::getAllOnesValue(VT.getSizeInBits()), dl, 8848 VT); 8849 return true; 8850 } 8851 } 8852 } 8853 8854 // Combine a constant select operand into its use: 8855 // 8856 // (add (select cc, 0, c), x) -> (select cc, x, (add, x, c)) 8857 // (sub x, (select cc, 0, c)) -> (select cc, x, (sub, x, c)) 8858 // (and (select cc, -1, c), x) -> (select cc, x, (and, x, c)) [AllOnes=1] 8859 // (or (select cc, 0, c), x) -> (select cc, x, (or, x, c)) 8860 // (xor (select cc, 0, c), x) -> (select cc, x, (xor, x, c)) 8861 // 8862 // The transform is rejected if the select doesn't have a constant operand that 8863 // is null, or all ones when AllOnes is set. 8864 // 8865 // Also recognize sext/zext from i1: 8866 // 8867 // (add (zext cc), x) -> (select cc (add x, 1), x) 8868 // (add (sext cc), x) -> (select cc (add x, -1), x) 8869 // 8870 // These transformations eventually create predicated instructions. 8871 // 8872 // @param N The node to transform. 8873 // @param Slct The N operand that is a select. 8874 // @param OtherOp The other N operand (x above). 8875 // @param DCI Context. 8876 // @param AllOnes Require the select constant to be all ones instead of null. 8877 // @returns The new node, or SDValue() on failure. 8878 static 8879 SDValue combineSelectAndUse(SDNode *N, SDValue Slct, SDValue OtherOp, 8880 TargetLowering::DAGCombinerInfo &DCI, 8881 bool AllOnes = false) { 8882 SelectionDAG &DAG = DCI.DAG; 8883 EVT VT = N->getValueType(0); 8884 SDValue NonConstantVal; 8885 SDValue CCOp; 8886 bool SwapSelectOps; 8887 if (!isConditionalZeroOrAllOnes(Slct.getNode(), AllOnes, CCOp, SwapSelectOps, 8888 NonConstantVal, DAG)) 8889 return SDValue(); 8890 8891 // Slct is now know to be the desired identity constant when CC is true. 8892 SDValue TrueVal = OtherOp; 8893 SDValue FalseVal = DAG.getNode(N->getOpcode(), SDLoc(N), VT, 8894 OtherOp, NonConstantVal); 8895 // Unless SwapSelectOps says CC should be false. 8896 if (SwapSelectOps) 8897 std::swap(TrueVal, FalseVal); 8898 8899 return DAG.getNode(ISD::SELECT, SDLoc(N), VT, 8900 CCOp, TrueVal, FalseVal); 8901 } 8902 8903 // Attempt combineSelectAndUse on each operand of a commutative operator N. 8904 static 8905 SDValue combineSelectAndUseCommutative(SDNode *N, bool AllOnes, 8906 TargetLowering::DAGCombinerInfo &DCI) { 8907 SDValue N0 = N->getOperand(0); 8908 SDValue N1 = N->getOperand(1); 8909 if (N0.getNode()->hasOneUse()) 8910 if (SDValue Result = combineSelectAndUse(N, N0, N1, DCI, AllOnes)) 8911 return Result; 8912 if (N1.getNode()->hasOneUse()) 8913 if (SDValue Result = combineSelectAndUse(N, N1, N0, DCI, AllOnes)) 8914 return Result; 8915 return SDValue(); 8916 } 8917 8918 // AddCombineToVPADDL- For pair-wise add on neon, use the vpaddl instruction 8919 // (only after legalization). 8920 static SDValue AddCombineToVPADDL(SDNode *N, SDValue N0, SDValue N1, 8921 TargetLowering::DAGCombinerInfo &DCI, 8922 const ARMSubtarget *Subtarget) { 8923 8924 // Only perform optimization if after legalize, and if NEON is available. We 8925 // also expected both operands to be BUILD_VECTORs. 8926 if (DCI.isBeforeLegalize() || !Subtarget->hasNEON() 8927 || N0.getOpcode() != ISD::BUILD_VECTOR 8928 || N1.getOpcode() != ISD::BUILD_VECTOR) 8929 return SDValue(); 8930 8931 // Check output type since VPADDL operand elements can only be 8, 16, or 32. 8932 EVT VT = N->getValueType(0); 8933 if (!VT.isInteger() || VT.getVectorElementType() == MVT::i64) 8934 return SDValue(); 8935 8936 // Check that the vector operands are of the right form. 8937 // N0 and N1 are BUILD_VECTOR nodes with N number of EXTRACT_VECTOR 8938 // operands, where N is the size of the formed vector. 8939 // Each EXTRACT_VECTOR should have the same input vector and odd or even 8940 // index such that we have a pair wise add pattern. 8941 8942 // Grab the vector that all EXTRACT_VECTOR nodes should be referencing. 8943 if (N0->getOperand(0)->getOpcode() != ISD::EXTRACT_VECTOR_ELT) 8944 return SDValue(); 8945 SDValue Vec = N0->getOperand(0)->getOperand(0); 8946 SDNode *V = Vec.getNode(); 8947 unsigned nextIndex = 0; 8948 8949 // For each operands to the ADD which are BUILD_VECTORs, 8950 // check to see if each of their operands are an EXTRACT_VECTOR with 8951 // the same vector and appropriate index. 8952 for (unsigned i = 0, e = N0->getNumOperands(); i != e; ++i) { 8953 if (N0->getOperand(i)->getOpcode() == ISD::EXTRACT_VECTOR_ELT 8954 && N1->getOperand(i)->getOpcode() == ISD::EXTRACT_VECTOR_ELT) { 8955 8956 SDValue ExtVec0 = N0->getOperand(i); 8957 SDValue ExtVec1 = N1->getOperand(i); 8958 8959 // First operand is the vector, verify its the same. 8960 if (V != ExtVec0->getOperand(0).getNode() || 8961 V != ExtVec1->getOperand(0).getNode()) 8962 return SDValue(); 8963 8964 // Second is the constant, verify its correct. 8965 ConstantSDNode *C0 = dyn_cast<ConstantSDNode>(ExtVec0->getOperand(1)); 8966 ConstantSDNode *C1 = dyn_cast<ConstantSDNode>(ExtVec1->getOperand(1)); 8967 8968 // For the constant, we want to see all the even or all the odd. 8969 if (!C0 || !C1 || C0->getZExtValue() != nextIndex 8970 || C1->getZExtValue() != nextIndex+1) 8971 return SDValue(); 8972 8973 // Increment index. 8974 nextIndex+=2; 8975 } else 8976 return SDValue(); 8977 } 8978 8979 // Create VPADDL node. 8980 SelectionDAG &DAG = DCI.DAG; 8981 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 8982 8983 SDLoc dl(N); 8984 8985 // Build operand list. 8986 SmallVector<SDValue, 8> Ops; 8987 Ops.push_back(DAG.getConstant(Intrinsic::arm_neon_vpaddls, dl, 8988 TLI.getPointerTy(DAG.getDataLayout()))); 8989 8990 // Input is the vector. 8991 Ops.push_back(Vec); 8992 8993 // Get widened type and narrowed type. 8994 MVT widenType; 8995 unsigned numElem = VT.getVectorNumElements(); 8996 8997 EVT inputLaneType = Vec.getValueType().getVectorElementType(); 8998 switch (inputLaneType.getSimpleVT().SimpleTy) { 8999 case MVT::i8: widenType = MVT::getVectorVT(MVT::i16, numElem); break; 9000 case MVT::i16: widenType = MVT::getVectorVT(MVT::i32, numElem); break; 9001 case MVT::i32: widenType = MVT::getVectorVT(MVT::i64, numElem); break; 9002 default: 9003 llvm_unreachable("Invalid vector element type for padd optimization."); 9004 } 9005 9006 SDValue tmp = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, widenType, Ops); 9007 unsigned ExtOp = VT.bitsGT(tmp.getValueType()) ? ISD::ANY_EXTEND : ISD::TRUNCATE; 9008 return DAG.getNode(ExtOp, dl, VT, tmp); 9009 } 9010 9011 static SDValue findMUL_LOHI(SDValue V) { 9012 if (V->getOpcode() == ISD::UMUL_LOHI || 9013 V->getOpcode() == ISD::SMUL_LOHI) 9014 return V; 9015 return SDValue(); 9016 } 9017 9018 static SDValue AddCombineTo64bitMLAL(SDNode *AddcNode, 9019 TargetLowering::DAGCombinerInfo &DCI, 9020 const ARMSubtarget *Subtarget) { 9021 9022 // Look for multiply add opportunities. 9023 // The pattern is a ISD::UMUL_LOHI followed by two add nodes, where 9024 // each add nodes consumes a value from ISD::UMUL_LOHI and there is 9025 // a glue link from the first add to the second add. 9026 // If we find this pattern, we can replace the U/SMUL_LOHI, ADDC, and ADDE by 9027 // a S/UMLAL instruction. 9028 // UMUL_LOHI 9029 // / :lo \ :hi 9030 // / \ [no multiline comment] 9031 // loAdd -> ADDE | 9032 // \ :glue / 9033 // \ / 9034 // ADDC <- hiAdd 9035 // 9036 assert(AddcNode->getOpcode() == ISD::ADDC && "Expect an ADDC"); 9037 SDValue AddcOp0 = AddcNode->getOperand(0); 9038 SDValue AddcOp1 = AddcNode->getOperand(1); 9039 9040 // Check if the two operands are from the same mul_lohi node. 9041 if (AddcOp0.getNode() == AddcOp1.getNode()) 9042 return SDValue(); 9043 9044 assert(AddcNode->getNumValues() == 2 && 9045 AddcNode->getValueType(0) == MVT::i32 && 9046 "Expect ADDC with two result values. First: i32"); 9047 9048 // Check that we have a glued ADDC node. 9049 if (AddcNode->getValueType(1) != MVT::Glue) 9050 return SDValue(); 9051 9052 // Check that the ADDC adds the low result of the S/UMUL_LOHI. 9053 if (AddcOp0->getOpcode() != ISD::UMUL_LOHI && 9054 AddcOp0->getOpcode() != ISD::SMUL_LOHI && 9055 AddcOp1->getOpcode() != ISD::UMUL_LOHI && 9056 AddcOp1->getOpcode() != ISD::SMUL_LOHI) 9057 return SDValue(); 9058 9059 // Look for the glued ADDE. 9060 SDNode* AddeNode = AddcNode->getGluedUser(); 9061 if (!AddeNode) 9062 return SDValue(); 9063 9064 // Make sure it is really an ADDE. 9065 if (AddeNode->getOpcode() != ISD::ADDE) 9066 return SDValue(); 9067 9068 assert(AddeNode->getNumOperands() == 3 && 9069 AddeNode->getOperand(2).getValueType() == MVT::Glue && 9070 "ADDE node has the wrong inputs"); 9071 9072 // Check for the triangle shape. 9073 SDValue AddeOp0 = AddeNode->getOperand(0); 9074 SDValue AddeOp1 = AddeNode->getOperand(1); 9075 9076 // Make sure that the ADDE operands are not coming from the same node. 9077 if (AddeOp0.getNode() == AddeOp1.getNode()) 9078 return SDValue(); 9079 9080 // Find the MUL_LOHI node walking up ADDE's operands. 9081 bool IsLeftOperandMUL = false; 9082 SDValue MULOp = findMUL_LOHI(AddeOp0); 9083 if (MULOp == SDValue()) 9084 MULOp = findMUL_LOHI(AddeOp1); 9085 else 9086 IsLeftOperandMUL = true; 9087 if (MULOp == SDValue()) 9088 return SDValue(); 9089 9090 // Figure out the right opcode. 9091 unsigned Opc = MULOp->getOpcode(); 9092 unsigned FinalOpc = (Opc == ISD::SMUL_LOHI) ? ARMISD::SMLAL : ARMISD::UMLAL; 9093 9094 // Figure out the high and low input values to the MLAL node. 9095 SDValue* HiAdd = nullptr; 9096 SDValue* LoMul = nullptr; 9097 SDValue* LowAdd = nullptr; 9098 9099 // Ensure that ADDE is from high result of ISD::SMUL_LOHI. 9100 if ((AddeOp0 != MULOp.getValue(1)) && (AddeOp1 != MULOp.getValue(1))) 9101 return SDValue(); 9102 9103 if (IsLeftOperandMUL) 9104 HiAdd = &AddeOp1; 9105 else 9106 HiAdd = &AddeOp0; 9107 9108 9109 // Ensure that LoMul and LowAdd are taken from correct ISD::SMUL_LOHI node 9110 // whose low result is fed to the ADDC we are checking. 9111 9112 if (AddcOp0 == MULOp.getValue(0)) { 9113 LoMul = &AddcOp0; 9114 LowAdd = &AddcOp1; 9115 } 9116 if (AddcOp1 == MULOp.getValue(0)) { 9117 LoMul = &AddcOp1; 9118 LowAdd = &AddcOp0; 9119 } 9120 9121 if (!LoMul) 9122 return SDValue(); 9123 9124 // Create the merged node. 9125 SelectionDAG &DAG = DCI.DAG; 9126 9127 // Build operand list. 9128 SmallVector<SDValue, 8> Ops; 9129 Ops.push_back(LoMul->getOperand(0)); 9130 Ops.push_back(LoMul->getOperand(1)); 9131 Ops.push_back(*LowAdd); 9132 Ops.push_back(*HiAdd); 9133 9134 SDValue MLALNode = DAG.getNode(FinalOpc, SDLoc(AddcNode), 9135 DAG.getVTList(MVT::i32, MVT::i32), Ops); 9136 9137 // Replace the ADDs' nodes uses by the MLA node's values. 9138 SDValue HiMLALResult(MLALNode.getNode(), 1); 9139 DAG.ReplaceAllUsesOfValueWith(SDValue(AddeNode, 0), HiMLALResult); 9140 9141 SDValue LoMLALResult(MLALNode.getNode(), 0); 9142 DAG.ReplaceAllUsesOfValueWith(SDValue(AddcNode, 0), LoMLALResult); 9143 9144 // Return original node to notify the driver to stop replacing. 9145 SDValue resNode(AddcNode, 0); 9146 return resNode; 9147 } 9148 9149 static SDValue AddCombineTo64bitUMAAL(SDNode *AddcNode, 9150 TargetLowering::DAGCombinerInfo &DCI, 9151 const ARMSubtarget *Subtarget) { 9152 // UMAAL is similar to UMLAL except that it adds two unsigned values. 9153 // While trying to combine for the other MLAL nodes, first search for the 9154 // chance to use UMAAL. Check if Addc uses another addc node which can first 9155 // be combined into a UMLAL. The other pattern is AddcNode being combined 9156 // into an UMLAL and then using another addc is handled in ISelDAGToDAG. 9157 9158 if (!Subtarget->hasV6Ops() || 9159 (Subtarget->isThumb() && !Subtarget->hasThumb2())) 9160 return AddCombineTo64bitMLAL(AddcNode, DCI, Subtarget); 9161 9162 SDNode *PrevAddc = nullptr; 9163 if (AddcNode->getOperand(0).getOpcode() == ISD::ADDC) 9164 PrevAddc = AddcNode->getOperand(0).getNode(); 9165 else if (AddcNode->getOperand(1).getOpcode() == ISD::ADDC) 9166 PrevAddc = AddcNode->getOperand(1).getNode(); 9167 9168 // If there's no addc chains, just return a search for any MLAL. 9169 if (PrevAddc == nullptr) 9170 return AddCombineTo64bitMLAL(AddcNode, DCI, Subtarget); 9171 9172 // Try to convert the addc operand to an MLAL and if that fails try to 9173 // combine AddcNode. 9174 SDValue MLAL = AddCombineTo64bitMLAL(PrevAddc, DCI, Subtarget); 9175 if (MLAL != SDValue(PrevAddc, 0)) 9176 return AddCombineTo64bitMLAL(AddcNode, DCI, Subtarget); 9177 9178 // Find the converted UMAAL or quit if it doesn't exist. 9179 SDNode *UmlalNode = nullptr; 9180 SDValue AddHi; 9181 if (AddcNode->getOperand(0).getOpcode() == ARMISD::UMLAL) { 9182 UmlalNode = AddcNode->getOperand(0).getNode(); 9183 AddHi = AddcNode->getOperand(1); 9184 } else if (AddcNode->getOperand(1).getOpcode() == ARMISD::UMLAL) { 9185 UmlalNode = AddcNode->getOperand(1).getNode(); 9186 AddHi = AddcNode->getOperand(0); 9187 } else { 9188 return SDValue(); 9189 } 9190 9191 // The ADDC should be glued to an ADDE node, which uses the same UMLAL as 9192 // the ADDC as well as Zero. 9193 auto *Zero = dyn_cast<ConstantSDNode>(UmlalNode->getOperand(3)); 9194 9195 if (!Zero || Zero->getZExtValue() != 0) 9196 return SDValue(); 9197 9198 // Check that we have a glued ADDC node. 9199 if (AddcNode->getValueType(1) != MVT::Glue) 9200 return SDValue(); 9201 9202 // Look for the glued ADDE. 9203 SDNode* AddeNode = AddcNode->getGluedUser(); 9204 if (!AddeNode) 9205 return SDValue(); 9206 9207 if ((AddeNode->getOperand(0).getNode() == Zero && 9208 AddeNode->getOperand(1).getNode() == UmlalNode) || 9209 (AddeNode->getOperand(0).getNode() == UmlalNode && 9210 AddeNode->getOperand(1).getNode() == Zero)) { 9211 9212 SelectionDAG &DAG = DCI.DAG; 9213 SDValue Ops[] = { UmlalNode->getOperand(0), UmlalNode->getOperand(1), 9214 UmlalNode->getOperand(2), AddHi }; 9215 SDValue UMAAL = DAG.getNode(ARMISD::UMAAL, SDLoc(AddcNode), 9216 DAG.getVTList(MVT::i32, MVT::i32), Ops); 9217 9218 // Replace the ADDs' nodes uses by the UMAAL node's values. 9219 DAG.ReplaceAllUsesOfValueWith(SDValue(AddeNode, 0), SDValue(UMAAL.getNode(), 1)); 9220 DAG.ReplaceAllUsesOfValueWith(SDValue(AddcNode, 0), SDValue(UMAAL.getNode(), 0)); 9221 9222 // Return original node to notify the driver to stop replacing. 9223 return SDValue(AddcNode, 0); 9224 } 9225 return SDValue(); 9226 } 9227 9228 /// PerformADDCCombine - Target-specific dag combine transform from 9229 /// ISD::ADDC, ISD::ADDE, and ISD::MUL_LOHI to MLAL or 9230 /// ISD::ADDC, ISD::ADDE and ARMISD::UMLAL to ARMISD::UMAAL 9231 static SDValue PerformADDCCombine(SDNode *N, 9232 TargetLowering::DAGCombinerInfo &DCI, 9233 const ARMSubtarget *Subtarget) { 9234 9235 if (Subtarget->isThumb1Only()) return SDValue(); 9236 9237 // Only perform the checks after legalize when the pattern is available. 9238 if (DCI.isBeforeLegalize()) return SDValue(); 9239 9240 return AddCombineTo64bitUMAAL(N, DCI, Subtarget); 9241 } 9242 9243 /// PerformADDCombineWithOperands - Try DAG combinations for an ADD with 9244 /// operands N0 and N1. This is a helper for PerformADDCombine that is 9245 /// called with the default operands, and if that fails, with commuted 9246 /// operands. 9247 static SDValue PerformADDCombineWithOperands(SDNode *N, SDValue N0, SDValue N1, 9248 TargetLowering::DAGCombinerInfo &DCI, 9249 const ARMSubtarget *Subtarget){ 9250 9251 // Attempt to create vpaddl for this add. 9252 if (SDValue Result = AddCombineToVPADDL(N, N0, N1, DCI, Subtarget)) 9253 return Result; 9254 9255 // fold (add (select cc, 0, c), x) -> (select cc, x, (add, x, c)) 9256 if (N0.getNode()->hasOneUse()) 9257 if (SDValue Result = combineSelectAndUse(N, N0, N1, DCI)) 9258 return Result; 9259 return SDValue(); 9260 } 9261 9262 /// PerformADDCombine - Target-specific dag combine xforms for ISD::ADD. 9263 /// 9264 static SDValue PerformADDCombine(SDNode *N, 9265 TargetLowering::DAGCombinerInfo &DCI, 9266 const ARMSubtarget *Subtarget) { 9267 SDValue N0 = N->getOperand(0); 9268 SDValue N1 = N->getOperand(1); 9269 9270 // First try with the default operand order. 9271 if (SDValue Result = PerformADDCombineWithOperands(N, N0, N1, DCI, Subtarget)) 9272 return Result; 9273 9274 // If that didn't work, try again with the operands commuted. 9275 return PerformADDCombineWithOperands(N, N1, N0, DCI, Subtarget); 9276 } 9277 9278 /// PerformSUBCombine - Target-specific dag combine xforms for ISD::SUB. 9279 /// 9280 static SDValue PerformSUBCombine(SDNode *N, 9281 TargetLowering::DAGCombinerInfo &DCI) { 9282 SDValue N0 = N->getOperand(0); 9283 SDValue N1 = N->getOperand(1); 9284 9285 // fold (sub x, (select cc, 0, c)) -> (select cc, x, (sub, x, c)) 9286 if (N1.getNode()->hasOneUse()) 9287 if (SDValue Result = combineSelectAndUse(N, N1, N0, DCI)) 9288 return Result; 9289 9290 return SDValue(); 9291 } 9292 9293 /// PerformVMULCombine 9294 /// Distribute (A + B) * C to (A * C) + (B * C) to take advantage of the 9295 /// special multiplier accumulator forwarding. 9296 /// vmul d3, d0, d2 9297 /// vmla d3, d1, d2 9298 /// is faster than 9299 /// vadd d3, d0, d1 9300 /// vmul d3, d3, d2 9301 // However, for (A + B) * (A + B), 9302 // vadd d2, d0, d1 9303 // vmul d3, d0, d2 9304 // vmla d3, d1, d2 9305 // is slower than 9306 // vadd d2, d0, d1 9307 // vmul d3, d2, d2 9308 static SDValue PerformVMULCombine(SDNode *N, 9309 TargetLowering::DAGCombinerInfo &DCI, 9310 const ARMSubtarget *Subtarget) { 9311 if (!Subtarget->hasVMLxForwarding()) 9312 return SDValue(); 9313 9314 SelectionDAG &DAG = DCI.DAG; 9315 SDValue N0 = N->getOperand(0); 9316 SDValue N1 = N->getOperand(1); 9317 unsigned Opcode = N0.getOpcode(); 9318 if (Opcode != ISD::ADD && Opcode != ISD::SUB && 9319 Opcode != ISD::FADD && Opcode != ISD::FSUB) { 9320 Opcode = N1.getOpcode(); 9321 if (Opcode != ISD::ADD && Opcode != ISD::SUB && 9322 Opcode != ISD::FADD && Opcode != ISD::FSUB) 9323 return SDValue(); 9324 std::swap(N0, N1); 9325 } 9326 9327 if (N0 == N1) 9328 return SDValue(); 9329 9330 EVT VT = N->getValueType(0); 9331 SDLoc DL(N); 9332 SDValue N00 = N0->getOperand(0); 9333 SDValue N01 = N0->getOperand(1); 9334 return DAG.getNode(Opcode, DL, VT, 9335 DAG.getNode(ISD::MUL, DL, VT, N00, N1), 9336 DAG.getNode(ISD::MUL, DL, VT, N01, N1)); 9337 } 9338 9339 static SDValue PerformMULCombine(SDNode *N, 9340 TargetLowering::DAGCombinerInfo &DCI, 9341 const ARMSubtarget *Subtarget) { 9342 SelectionDAG &DAG = DCI.DAG; 9343 9344 if (Subtarget->isThumb1Only()) 9345 return SDValue(); 9346 9347 if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer()) 9348 return SDValue(); 9349 9350 EVT VT = N->getValueType(0); 9351 if (VT.is64BitVector() || VT.is128BitVector()) 9352 return PerformVMULCombine(N, DCI, Subtarget); 9353 if (VT != MVT::i32) 9354 return SDValue(); 9355 9356 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(1)); 9357 if (!C) 9358 return SDValue(); 9359 9360 int64_t MulAmt = C->getSExtValue(); 9361 unsigned ShiftAmt = countTrailingZeros<uint64_t>(MulAmt); 9362 9363 ShiftAmt = ShiftAmt & (32 - 1); 9364 SDValue V = N->getOperand(0); 9365 SDLoc DL(N); 9366 9367 SDValue Res; 9368 MulAmt >>= ShiftAmt; 9369 9370 if (MulAmt >= 0) { 9371 if (isPowerOf2_32(MulAmt - 1)) { 9372 // (mul x, 2^N + 1) => (add (shl x, N), x) 9373 Res = DAG.getNode(ISD::ADD, DL, VT, 9374 V, 9375 DAG.getNode(ISD::SHL, DL, VT, 9376 V, 9377 DAG.getConstant(Log2_32(MulAmt - 1), DL, 9378 MVT::i32))); 9379 } else if (isPowerOf2_32(MulAmt + 1)) { 9380 // (mul x, 2^N - 1) => (sub (shl x, N), x) 9381 Res = DAG.getNode(ISD::SUB, DL, VT, 9382 DAG.getNode(ISD::SHL, DL, VT, 9383 V, 9384 DAG.getConstant(Log2_32(MulAmt + 1), DL, 9385 MVT::i32)), 9386 V); 9387 } else 9388 return SDValue(); 9389 } else { 9390 uint64_t MulAmtAbs = -MulAmt; 9391 if (isPowerOf2_32(MulAmtAbs + 1)) { 9392 // (mul x, -(2^N - 1)) => (sub x, (shl x, N)) 9393 Res = DAG.getNode(ISD::SUB, DL, VT, 9394 V, 9395 DAG.getNode(ISD::SHL, DL, VT, 9396 V, 9397 DAG.getConstant(Log2_32(MulAmtAbs + 1), DL, 9398 MVT::i32))); 9399 } else if (isPowerOf2_32(MulAmtAbs - 1)) { 9400 // (mul x, -(2^N + 1)) => - (add (shl x, N), x) 9401 Res = DAG.getNode(ISD::ADD, DL, VT, 9402 V, 9403 DAG.getNode(ISD::SHL, DL, VT, 9404 V, 9405 DAG.getConstant(Log2_32(MulAmtAbs - 1), DL, 9406 MVT::i32))); 9407 Res = DAG.getNode(ISD::SUB, DL, VT, 9408 DAG.getConstant(0, DL, MVT::i32), Res); 9409 9410 } else 9411 return SDValue(); 9412 } 9413 9414 if (ShiftAmt != 0) 9415 Res = DAG.getNode(ISD::SHL, DL, VT, 9416 Res, DAG.getConstant(ShiftAmt, DL, MVT::i32)); 9417 9418 // Do not add new nodes to DAG combiner worklist. 9419 DCI.CombineTo(N, Res, false); 9420 return SDValue(); 9421 } 9422 9423 static SDValue PerformANDCombine(SDNode *N, 9424 TargetLowering::DAGCombinerInfo &DCI, 9425 const ARMSubtarget *Subtarget) { 9426 9427 // Attempt to use immediate-form VBIC 9428 BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(N->getOperand(1)); 9429 SDLoc dl(N); 9430 EVT VT = N->getValueType(0); 9431 SelectionDAG &DAG = DCI.DAG; 9432 9433 if(!DAG.getTargetLoweringInfo().isTypeLegal(VT)) 9434 return SDValue(); 9435 9436 APInt SplatBits, SplatUndef; 9437 unsigned SplatBitSize; 9438 bool HasAnyUndefs; 9439 if (BVN && 9440 BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs)) { 9441 if (SplatBitSize <= 64) { 9442 EVT VbicVT; 9443 SDValue Val = isNEONModifiedImm((~SplatBits).getZExtValue(), 9444 SplatUndef.getZExtValue(), SplatBitSize, 9445 DAG, dl, VbicVT, VT.is128BitVector(), 9446 OtherModImm); 9447 if (Val.getNode()) { 9448 SDValue Input = 9449 DAG.getNode(ISD::BITCAST, dl, VbicVT, N->getOperand(0)); 9450 SDValue Vbic = DAG.getNode(ARMISD::VBICIMM, dl, VbicVT, Input, Val); 9451 return DAG.getNode(ISD::BITCAST, dl, VT, Vbic); 9452 } 9453 } 9454 } 9455 9456 if (!Subtarget->isThumb1Only()) { 9457 // fold (and (select cc, -1, c), x) -> (select cc, x, (and, x, c)) 9458 if (SDValue Result = combineSelectAndUseCommutative(N, true, DCI)) 9459 return Result; 9460 } 9461 9462 return SDValue(); 9463 } 9464 9465 /// PerformORCombine - Target-specific dag combine xforms for ISD::OR 9466 static SDValue PerformORCombine(SDNode *N, 9467 TargetLowering::DAGCombinerInfo &DCI, 9468 const ARMSubtarget *Subtarget) { 9469 // Attempt to use immediate-form VORR 9470 BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(N->getOperand(1)); 9471 SDLoc dl(N); 9472 EVT VT = N->getValueType(0); 9473 SelectionDAG &DAG = DCI.DAG; 9474 9475 if(!DAG.getTargetLoweringInfo().isTypeLegal(VT)) 9476 return SDValue(); 9477 9478 APInt SplatBits, SplatUndef; 9479 unsigned SplatBitSize; 9480 bool HasAnyUndefs; 9481 if (BVN && Subtarget->hasNEON() && 9482 BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs)) { 9483 if (SplatBitSize <= 64) { 9484 EVT VorrVT; 9485 SDValue Val = isNEONModifiedImm(SplatBits.getZExtValue(), 9486 SplatUndef.getZExtValue(), SplatBitSize, 9487 DAG, dl, VorrVT, VT.is128BitVector(), 9488 OtherModImm); 9489 if (Val.getNode()) { 9490 SDValue Input = 9491 DAG.getNode(ISD::BITCAST, dl, VorrVT, N->getOperand(0)); 9492 SDValue Vorr = DAG.getNode(ARMISD::VORRIMM, dl, VorrVT, Input, Val); 9493 return DAG.getNode(ISD::BITCAST, dl, VT, Vorr); 9494 } 9495 } 9496 } 9497 9498 if (!Subtarget->isThumb1Only()) { 9499 // fold (or (select cc, 0, c), x) -> (select cc, x, (or, x, c)) 9500 if (SDValue Result = combineSelectAndUseCommutative(N, false, DCI)) 9501 return Result; 9502 } 9503 9504 // The code below optimizes (or (and X, Y), Z). 9505 // The AND operand needs to have a single user to make these optimizations 9506 // profitable. 9507 SDValue N0 = N->getOperand(0); 9508 if (N0.getOpcode() != ISD::AND || !N0.hasOneUse()) 9509 return SDValue(); 9510 SDValue N1 = N->getOperand(1); 9511 9512 // (or (and B, A), (and C, ~A)) => (VBSL A, B, C) when A is a constant. 9513 if (Subtarget->hasNEON() && N1.getOpcode() == ISD::AND && VT.isVector() && 9514 DAG.getTargetLoweringInfo().isTypeLegal(VT)) { 9515 APInt SplatUndef; 9516 unsigned SplatBitSize; 9517 bool HasAnyUndefs; 9518 9519 APInt SplatBits0, SplatBits1; 9520 BuildVectorSDNode *BVN0 = dyn_cast<BuildVectorSDNode>(N0->getOperand(1)); 9521 BuildVectorSDNode *BVN1 = dyn_cast<BuildVectorSDNode>(N1->getOperand(1)); 9522 // Ensure that the second operand of both ands are constants 9523 if (BVN0 && BVN0->isConstantSplat(SplatBits0, SplatUndef, SplatBitSize, 9524 HasAnyUndefs) && !HasAnyUndefs) { 9525 if (BVN1 && BVN1->isConstantSplat(SplatBits1, SplatUndef, SplatBitSize, 9526 HasAnyUndefs) && !HasAnyUndefs) { 9527 // Ensure that the bit width of the constants are the same and that 9528 // the splat arguments are logical inverses as per the pattern we 9529 // are trying to simplify. 9530 if (SplatBits0.getBitWidth() == SplatBits1.getBitWidth() && 9531 SplatBits0 == ~SplatBits1) { 9532 // Canonicalize the vector type to make instruction selection 9533 // simpler. 9534 EVT CanonicalVT = VT.is128BitVector() ? MVT::v4i32 : MVT::v2i32; 9535 SDValue Result = DAG.getNode(ARMISD::VBSL, dl, CanonicalVT, 9536 N0->getOperand(1), 9537 N0->getOperand(0), 9538 N1->getOperand(0)); 9539 return DAG.getNode(ISD::BITCAST, dl, VT, Result); 9540 } 9541 } 9542 } 9543 } 9544 9545 // Try to use the ARM/Thumb2 BFI (bitfield insert) instruction when 9546 // reasonable. 9547 9548 // BFI is only available on V6T2+ 9549 if (Subtarget->isThumb1Only() || !Subtarget->hasV6T2Ops()) 9550 return SDValue(); 9551 9552 SDLoc DL(N); 9553 // 1) or (and A, mask), val => ARMbfi A, val, mask 9554 // iff (val & mask) == val 9555 // 9556 // 2) or (and A, mask), (and B, mask2) => ARMbfi A, (lsr B, amt), mask 9557 // 2a) iff isBitFieldInvertedMask(mask) && isBitFieldInvertedMask(~mask2) 9558 // && mask == ~mask2 9559 // 2b) iff isBitFieldInvertedMask(~mask) && isBitFieldInvertedMask(mask2) 9560 // && ~mask == mask2 9561 // (i.e., copy a bitfield value into another bitfield of the same width) 9562 9563 if (VT != MVT::i32) 9564 return SDValue(); 9565 9566 SDValue N00 = N0.getOperand(0); 9567 9568 // The value and the mask need to be constants so we can verify this is 9569 // actually a bitfield set. If the mask is 0xffff, we can do better 9570 // via a movt instruction, so don't use BFI in that case. 9571 SDValue MaskOp = N0.getOperand(1); 9572 ConstantSDNode *MaskC = dyn_cast<ConstantSDNode>(MaskOp); 9573 if (!MaskC) 9574 return SDValue(); 9575 unsigned Mask = MaskC->getZExtValue(); 9576 if (Mask == 0xffff) 9577 return SDValue(); 9578 SDValue Res; 9579 // Case (1): or (and A, mask), val => ARMbfi A, val, mask 9580 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1); 9581 if (N1C) { 9582 unsigned Val = N1C->getZExtValue(); 9583 if ((Val & ~Mask) != Val) 9584 return SDValue(); 9585 9586 if (ARM::isBitFieldInvertedMask(Mask)) { 9587 Val >>= countTrailingZeros(~Mask); 9588 9589 Res = DAG.getNode(ARMISD::BFI, DL, VT, N00, 9590 DAG.getConstant(Val, DL, MVT::i32), 9591 DAG.getConstant(Mask, DL, MVT::i32)); 9592 9593 // Do not add new nodes to DAG combiner worklist. 9594 DCI.CombineTo(N, Res, false); 9595 return SDValue(); 9596 } 9597 } else if (N1.getOpcode() == ISD::AND) { 9598 // case (2) or (and A, mask), (and B, mask2) => ARMbfi A, (lsr B, amt), mask 9599 ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1)); 9600 if (!N11C) 9601 return SDValue(); 9602 unsigned Mask2 = N11C->getZExtValue(); 9603 9604 // Mask and ~Mask2 (or reverse) must be equivalent for the BFI pattern 9605 // as is to match. 9606 if (ARM::isBitFieldInvertedMask(Mask) && 9607 (Mask == ~Mask2)) { 9608 // The pack halfword instruction works better for masks that fit it, 9609 // so use that when it's available. 9610 if (Subtarget->hasT2ExtractPack() && 9611 (Mask == 0xffff || Mask == 0xffff0000)) 9612 return SDValue(); 9613 // 2a 9614 unsigned amt = countTrailingZeros(Mask2); 9615 Res = DAG.getNode(ISD::SRL, DL, VT, N1.getOperand(0), 9616 DAG.getConstant(amt, DL, MVT::i32)); 9617 Res = DAG.getNode(ARMISD::BFI, DL, VT, N00, Res, 9618 DAG.getConstant(Mask, DL, MVT::i32)); 9619 // Do not add new nodes to DAG combiner worklist. 9620 DCI.CombineTo(N, Res, false); 9621 return SDValue(); 9622 } else if (ARM::isBitFieldInvertedMask(~Mask) && 9623 (~Mask == Mask2)) { 9624 // The pack halfword instruction works better for masks that fit it, 9625 // so use that when it's available. 9626 if (Subtarget->hasT2ExtractPack() && 9627 (Mask2 == 0xffff || Mask2 == 0xffff0000)) 9628 return SDValue(); 9629 // 2b 9630 unsigned lsb = countTrailingZeros(Mask); 9631 Res = DAG.getNode(ISD::SRL, DL, VT, N00, 9632 DAG.getConstant(lsb, DL, MVT::i32)); 9633 Res = DAG.getNode(ARMISD::BFI, DL, VT, N1.getOperand(0), Res, 9634 DAG.getConstant(Mask2, DL, MVT::i32)); 9635 // Do not add new nodes to DAG combiner worklist. 9636 DCI.CombineTo(N, Res, false); 9637 return SDValue(); 9638 } 9639 } 9640 9641 if (DAG.MaskedValueIsZero(N1, MaskC->getAPIntValue()) && 9642 N00.getOpcode() == ISD::SHL && isa<ConstantSDNode>(N00.getOperand(1)) && 9643 ARM::isBitFieldInvertedMask(~Mask)) { 9644 // Case (3): or (and (shl A, #shamt), mask), B => ARMbfi B, A, ~mask 9645 // where lsb(mask) == #shamt and masked bits of B are known zero. 9646 SDValue ShAmt = N00.getOperand(1); 9647 unsigned ShAmtC = cast<ConstantSDNode>(ShAmt)->getZExtValue(); 9648 unsigned LSB = countTrailingZeros(Mask); 9649 if (ShAmtC != LSB) 9650 return SDValue(); 9651 9652 Res = DAG.getNode(ARMISD::BFI, DL, VT, N1, N00.getOperand(0), 9653 DAG.getConstant(~Mask, DL, MVT::i32)); 9654 9655 // Do not add new nodes to DAG combiner worklist. 9656 DCI.CombineTo(N, Res, false); 9657 } 9658 9659 return SDValue(); 9660 } 9661 9662 static SDValue PerformXORCombine(SDNode *N, 9663 TargetLowering::DAGCombinerInfo &DCI, 9664 const ARMSubtarget *Subtarget) { 9665 EVT VT = N->getValueType(0); 9666 SelectionDAG &DAG = DCI.DAG; 9667 9668 if(!DAG.getTargetLoweringInfo().isTypeLegal(VT)) 9669 return SDValue(); 9670 9671 if (!Subtarget->isThumb1Only()) { 9672 // fold (xor (select cc, 0, c), x) -> (select cc, x, (xor, x, c)) 9673 if (SDValue Result = combineSelectAndUseCommutative(N, false, DCI)) 9674 return Result; 9675 } 9676 9677 return SDValue(); 9678 } 9679 9680 // ParseBFI - given a BFI instruction in N, extract the "from" value (Rn) and return it, 9681 // and fill in FromMask and ToMask with (consecutive) bits in "from" to be extracted and 9682 // their position in "to" (Rd). 9683 static SDValue ParseBFI(SDNode *N, APInt &ToMask, APInt &FromMask) { 9684 assert(N->getOpcode() == ARMISD::BFI); 9685 9686 SDValue From = N->getOperand(1); 9687 ToMask = ~cast<ConstantSDNode>(N->getOperand(2))->getAPIntValue(); 9688 FromMask = APInt::getLowBitsSet(ToMask.getBitWidth(), ToMask.countPopulation()); 9689 9690 // If the Base came from a SHR #C, we can deduce that it is really testing bit 9691 // #C in the base of the SHR. 9692 if (From->getOpcode() == ISD::SRL && 9693 isa<ConstantSDNode>(From->getOperand(1))) { 9694 APInt Shift = cast<ConstantSDNode>(From->getOperand(1))->getAPIntValue(); 9695 assert(Shift.getLimitedValue() < 32 && "Shift too large!"); 9696 FromMask <<= Shift.getLimitedValue(31); 9697 From = From->getOperand(0); 9698 } 9699 9700 return From; 9701 } 9702 9703 // If A and B contain one contiguous set of bits, does A | B == A . B? 9704 // 9705 // Neither A nor B must be zero. 9706 static bool BitsProperlyConcatenate(const APInt &A, const APInt &B) { 9707 unsigned LastActiveBitInA = A.countTrailingZeros(); 9708 unsigned FirstActiveBitInB = B.getBitWidth() - B.countLeadingZeros() - 1; 9709 return LastActiveBitInA - 1 == FirstActiveBitInB; 9710 } 9711 9712 static SDValue FindBFIToCombineWith(SDNode *N) { 9713 // We have a BFI in N. Follow a possible chain of BFIs and find a BFI it can combine with, 9714 // if one exists. 9715 APInt ToMask, FromMask; 9716 SDValue From = ParseBFI(N, ToMask, FromMask); 9717 SDValue To = N->getOperand(0); 9718 9719 // Now check for a compatible BFI to merge with. We can pass through BFIs that 9720 // aren't compatible, but not if they set the same bit in their destination as 9721 // we do (or that of any BFI we're going to combine with). 9722 SDValue V = To; 9723 APInt CombinedToMask = ToMask; 9724 while (V.getOpcode() == ARMISD::BFI) { 9725 APInt NewToMask, NewFromMask; 9726 SDValue NewFrom = ParseBFI(V.getNode(), NewToMask, NewFromMask); 9727 if (NewFrom != From) { 9728 // This BFI has a different base. Keep going. 9729 CombinedToMask |= NewToMask; 9730 V = V.getOperand(0); 9731 continue; 9732 } 9733 9734 // Do the written bits conflict with any we've seen so far? 9735 if ((NewToMask & CombinedToMask).getBoolValue()) 9736 // Conflicting bits - bail out because going further is unsafe. 9737 return SDValue(); 9738 9739 // Are the new bits contiguous when combined with the old bits? 9740 if (BitsProperlyConcatenate(ToMask, NewToMask) && 9741 BitsProperlyConcatenate(FromMask, NewFromMask)) 9742 return V; 9743 if (BitsProperlyConcatenate(NewToMask, ToMask) && 9744 BitsProperlyConcatenate(NewFromMask, FromMask)) 9745 return V; 9746 9747 // We've seen a write to some bits, so track it. 9748 CombinedToMask |= NewToMask; 9749 // Keep going... 9750 V = V.getOperand(0); 9751 } 9752 9753 return SDValue(); 9754 } 9755 9756 static SDValue PerformBFICombine(SDNode *N, 9757 TargetLowering::DAGCombinerInfo &DCI) { 9758 SDValue N1 = N->getOperand(1); 9759 if (N1.getOpcode() == ISD::AND) { 9760 // (bfi A, (and B, Mask1), Mask2) -> (bfi A, B, Mask2) iff 9761 // the bits being cleared by the AND are not demanded by the BFI. 9762 ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1)); 9763 if (!N11C) 9764 return SDValue(); 9765 unsigned InvMask = cast<ConstantSDNode>(N->getOperand(2))->getZExtValue(); 9766 unsigned LSB = countTrailingZeros(~InvMask); 9767 unsigned Width = (32 - countLeadingZeros(~InvMask)) - LSB; 9768 assert(Width < 9769 static_cast<unsigned>(std::numeric_limits<unsigned>::digits) && 9770 "undefined behavior"); 9771 unsigned Mask = (1u << Width) - 1; 9772 unsigned Mask2 = N11C->getZExtValue(); 9773 if ((Mask & (~Mask2)) == 0) 9774 return DCI.DAG.getNode(ARMISD::BFI, SDLoc(N), N->getValueType(0), 9775 N->getOperand(0), N1.getOperand(0), 9776 N->getOperand(2)); 9777 } else if (N->getOperand(0).getOpcode() == ARMISD::BFI) { 9778 // We have a BFI of a BFI. Walk up the BFI chain to see how long it goes. 9779 // Keep track of any consecutive bits set that all come from the same base 9780 // value. We can combine these together into a single BFI. 9781 SDValue CombineBFI = FindBFIToCombineWith(N); 9782 if (CombineBFI == SDValue()) 9783 return SDValue(); 9784 9785 // We've found a BFI. 9786 APInt ToMask1, FromMask1; 9787 SDValue From1 = ParseBFI(N, ToMask1, FromMask1); 9788 9789 APInt ToMask2, FromMask2; 9790 SDValue From2 = ParseBFI(CombineBFI.getNode(), ToMask2, FromMask2); 9791 assert(From1 == From2); 9792 (void)From2; 9793 9794 // First, unlink CombineBFI. 9795 DCI.DAG.ReplaceAllUsesWith(CombineBFI, CombineBFI.getOperand(0)); 9796 // Then create a new BFI, combining the two together. 9797 APInt NewFromMask = FromMask1 | FromMask2; 9798 APInt NewToMask = ToMask1 | ToMask2; 9799 9800 EVT VT = N->getValueType(0); 9801 SDLoc dl(N); 9802 9803 if (NewFromMask[0] == 0) 9804 From1 = DCI.DAG.getNode( 9805 ISD::SRL, dl, VT, From1, 9806 DCI.DAG.getConstant(NewFromMask.countTrailingZeros(), dl, VT)); 9807 return DCI.DAG.getNode(ARMISD::BFI, dl, VT, N->getOperand(0), From1, 9808 DCI.DAG.getConstant(~NewToMask, dl, VT)); 9809 } 9810 return SDValue(); 9811 } 9812 9813 /// PerformVMOVRRDCombine - Target-specific dag combine xforms for 9814 /// ARMISD::VMOVRRD. 9815 static SDValue PerformVMOVRRDCombine(SDNode *N, 9816 TargetLowering::DAGCombinerInfo &DCI, 9817 const ARMSubtarget *Subtarget) { 9818 // vmovrrd(vmovdrr x, y) -> x,y 9819 SDValue InDouble = N->getOperand(0); 9820 if (InDouble.getOpcode() == ARMISD::VMOVDRR && !Subtarget->isFPOnlySP()) 9821 return DCI.CombineTo(N, InDouble.getOperand(0), InDouble.getOperand(1)); 9822 9823 // vmovrrd(load f64) -> (load i32), (load i32) 9824 SDNode *InNode = InDouble.getNode(); 9825 if (ISD::isNormalLoad(InNode) && InNode->hasOneUse() && 9826 InNode->getValueType(0) == MVT::f64 && 9827 InNode->getOperand(1).getOpcode() == ISD::FrameIndex && 9828 !cast<LoadSDNode>(InNode)->isVolatile()) { 9829 // TODO: Should this be done for non-FrameIndex operands? 9830 LoadSDNode *LD = cast<LoadSDNode>(InNode); 9831 9832 SelectionDAG &DAG = DCI.DAG; 9833 SDLoc DL(LD); 9834 SDValue BasePtr = LD->getBasePtr(); 9835 SDValue NewLD1 = 9836 DAG.getLoad(MVT::i32, DL, LD->getChain(), BasePtr, LD->getPointerInfo(), 9837 LD->getAlignment(), LD->getMemOperand()->getFlags()); 9838 9839 SDValue OffsetPtr = DAG.getNode(ISD::ADD, DL, MVT::i32, BasePtr, 9840 DAG.getConstant(4, DL, MVT::i32)); 9841 SDValue NewLD2 = DAG.getLoad( 9842 MVT::i32, DL, NewLD1.getValue(1), OffsetPtr, LD->getPointerInfo(), 9843 std::min(4U, LD->getAlignment() / 2), LD->getMemOperand()->getFlags()); 9844 9845 DAG.ReplaceAllUsesOfValueWith(SDValue(LD, 1), NewLD2.getValue(1)); 9846 if (DCI.DAG.getDataLayout().isBigEndian()) 9847 std::swap (NewLD1, NewLD2); 9848 SDValue Result = DCI.CombineTo(N, NewLD1, NewLD2); 9849 return Result; 9850 } 9851 9852 return SDValue(); 9853 } 9854 9855 /// PerformVMOVDRRCombine - Target-specific dag combine xforms for 9856 /// ARMISD::VMOVDRR. This is also used for BUILD_VECTORs with 2 operands. 9857 static SDValue PerformVMOVDRRCombine(SDNode *N, SelectionDAG &DAG) { 9858 // N=vmovrrd(X); vmovdrr(N:0, N:1) -> bit_convert(X) 9859 SDValue Op0 = N->getOperand(0); 9860 SDValue Op1 = N->getOperand(1); 9861 if (Op0.getOpcode() == ISD::BITCAST) 9862 Op0 = Op0.getOperand(0); 9863 if (Op1.getOpcode() == ISD::BITCAST) 9864 Op1 = Op1.getOperand(0); 9865 if (Op0.getOpcode() == ARMISD::VMOVRRD && 9866 Op0.getNode() == Op1.getNode() && 9867 Op0.getResNo() == 0 && Op1.getResNo() == 1) 9868 return DAG.getNode(ISD::BITCAST, SDLoc(N), 9869 N->getValueType(0), Op0.getOperand(0)); 9870 return SDValue(); 9871 } 9872 9873 /// hasNormalLoadOperand - Check if any of the operands of a BUILD_VECTOR node 9874 /// are normal, non-volatile loads. If so, it is profitable to bitcast an 9875 /// i64 vector to have f64 elements, since the value can then be loaded 9876 /// directly into a VFP register. 9877 static bool hasNormalLoadOperand(SDNode *N) { 9878 unsigned NumElts = N->getValueType(0).getVectorNumElements(); 9879 for (unsigned i = 0; i < NumElts; ++i) { 9880 SDNode *Elt = N->getOperand(i).getNode(); 9881 if (ISD::isNormalLoad(Elt) && !cast<LoadSDNode>(Elt)->isVolatile()) 9882 return true; 9883 } 9884 return false; 9885 } 9886 9887 /// PerformBUILD_VECTORCombine - Target-specific dag combine xforms for 9888 /// ISD::BUILD_VECTOR. 9889 static SDValue PerformBUILD_VECTORCombine(SDNode *N, 9890 TargetLowering::DAGCombinerInfo &DCI, 9891 const ARMSubtarget *Subtarget) { 9892 // build_vector(N=ARMISD::VMOVRRD(X), N:1) -> bit_convert(X): 9893 // VMOVRRD is introduced when legalizing i64 types. It forces the i64 value 9894 // into a pair of GPRs, which is fine when the value is used as a scalar, 9895 // but if the i64 value is converted to a vector, we need to undo the VMOVRRD. 9896 SelectionDAG &DAG = DCI.DAG; 9897 if (N->getNumOperands() == 2) 9898 if (SDValue RV = PerformVMOVDRRCombine(N, DAG)) 9899 return RV; 9900 9901 // Load i64 elements as f64 values so that type legalization does not split 9902 // them up into i32 values. 9903 EVT VT = N->getValueType(0); 9904 if (VT.getVectorElementType() != MVT::i64 || !hasNormalLoadOperand(N)) 9905 return SDValue(); 9906 SDLoc dl(N); 9907 SmallVector<SDValue, 8> Ops; 9908 unsigned NumElts = VT.getVectorNumElements(); 9909 for (unsigned i = 0; i < NumElts; ++i) { 9910 SDValue V = DAG.getNode(ISD::BITCAST, dl, MVT::f64, N->getOperand(i)); 9911 Ops.push_back(V); 9912 // Make the DAGCombiner fold the bitcast. 9913 DCI.AddToWorklist(V.getNode()); 9914 } 9915 EVT FloatVT = EVT::getVectorVT(*DAG.getContext(), MVT::f64, NumElts); 9916 SDValue BV = DAG.getBuildVector(FloatVT, dl, Ops); 9917 return DAG.getNode(ISD::BITCAST, dl, VT, BV); 9918 } 9919 9920 /// \brief Target-specific dag combine xforms for ARMISD::BUILD_VECTOR. 9921 static SDValue 9922 PerformARMBUILD_VECTORCombine(SDNode *N, TargetLowering::DAGCombinerInfo &DCI) { 9923 // ARMISD::BUILD_VECTOR is introduced when legalizing ISD::BUILD_VECTOR. 9924 // At that time, we may have inserted bitcasts from integer to float. 9925 // If these bitcasts have survived DAGCombine, change the lowering of this 9926 // BUILD_VECTOR in something more vector friendly, i.e., that does not 9927 // force to use floating point types. 9928 9929 // Make sure we can change the type of the vector. 9930 // This is possible iff: 9931 // 1. The vector is only used in a bitcast to a integer type. I.e., 9932 // 1.1. Vector is used only once. 9933 // 1.2. Use is a bit convert to an integer type. 9934 // 2. The size of its operands are 32-bits (64-bits are not legal). 9935 EVT VT = N->getValueType(0); 9936 EVT EltVT = VT.getVectorElementType(); 9937 9938 // Check 1.1. and 2. 9939 if (EltVT.getSizeInBits() != 32 || !N->hasOneUse()) 9940 return SDValue(); 9941 9942 // By construction, the input type must be float. 9943 assert(EltVT == MVT::f32 && "Unexpected type!"); 9944 9945 // Check 1.2. 9946 SDNode *Use = *N->use_begin(); 9947 if (Use->getOpcode() != ISD::BITCAST || 9948 Use->getValueType(0).isFloatingPoint()) 9949 return SDValue(); 9950 9951 // Check profitability. 9952 // Model is, if more than half of the relevant operands are bitcast from 9953 // i32, turn the build_vector into a sequence of insert_vector_elt. 9954 // Relevant operands are everything that is not statically 9955 // (i.e., at compile time) bitcasted. 9956 unsigned NumOfBitCastedElts = 0; 9957 unsigned NumElts = VT.getVectorNumElements(); 9958 unsigned NumOfRelevantElts = NumElts; 9959 for (unsigned Idx = 0; Idx < NumElts; ++Idx) { 9960 SDValue Elt = N->getOperand(Idx); 9961 if (Elt->getOpcode() == ISD::BITCAST) { 9962 // Assume only bit cast to i32 will go away. 9963 if (Elt->getOperand(0).getValueType() == MVT::i32) 9964 ++NumOfBitCastedElts; 9965 } else if (Elt.isUndef() || isa<ConstantSDNode>(Elt)) 9966 // Constants are statically casted, thus do not count them as 9967 // relevant operands. 9968 --NumOfRelevantElts; 9969 } 9970 9971 // Check if more than half of the elements require a non-free bitcast. 9972 if (NumOfBitCastedElts <= NumOfRelevantElts / 2) 9973 return SDValue(); 9974 9975 SelectionDAG &DAG = DCI.DAG; 9976 // Create the new vector type. 9977 EVT VecVT = EVT::getVectorVT(*DAG.getContext(), MVT::i32, NumElts); 9978 // Check if the type is legal. 9979 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 9980 if (!TLI.isTypeLegal(VecVT)) 9981 return SDValue(); 9982 9983 // Combine: 9984 // ARMISD::BUILD_VECTOR E1, E2, ..., EN. 9985 // => BITCAST INSERT_VECTOR_ELT 9986 // (INSERT_VECTOR_ELT (...), (BITCAST EN-1), N-1), 9987 // (BITCAST EN), N. 9988 SDValue Vec = DAG.getUNDEF(VecVT); 9989 SDLoc dl(N); 9990 for (unsigned Idx = 0 ; Idx < NumElts; ++Idx) { 9991 SDValue V = N->getOperand(Idx); 9992 if (V.isUndef()) 9993 continue; 9994 if (V.getOpcode() == ISD::BITCAST && 9995 V->getOperand(0).getValueType() == MVT::i32) 9996 // Fold obvious case. 9997 V = V.getOperand(0); 9998 else { 9999 V = DAG.getNode(ISD::BITCAST, SDLoc(V), MVT::i32, V); 10000 // Make the DAGCombiner fold the bitcasts. 10001 DCI.AddToWorklist(V.getNode()); 10002 } 10003 SDValue LaneIdx = DAG.getConstant(Idx, dl, MVT::i32); 10004 Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VecVT, Vec, V, LaneIdx); 10005 } 10006 Vec = DAG.getNode(ISD::BITCAST, dl, VT, Vec); 10007 // Make the DAGCombiner fold the bitcasts. 10008 DCI.AddToWorklist(Vec.getNode()); 10009 return Vec; 10010 } 10011 10012 /// PerformInsertEltCombine - Target-specific dag combine xforms for 10013 /// ISD::INSERT_VECTOR_ELT. 10014 static SDValue PerformInsertEltCombine(SDNode *N, 10015 TargetLowering::DAGCombinerInfo &DCI) { 10016 // Bitcast an i64 load inserted into a vector to f64. 10017 // Otherwise, the i64 value will be legalized to a pair of i32 values. 10018 EVT VT = N->getValueType(0); 10019 SDNode *Elt = N->getOperand(1).getNode(); 10020 if (VT.getVectorElementType() != MVT::i64 || 10021 !ISD::isNormalLoad(Elt) || cast<LoadSDNode>(Elt)->isVolatile()) 10022 return SDValue(); 10023 10024 SelectionDAG &DAG = DCI.DAG; 10025 SDLoc dl(N); 10026 EVT FloatVT = EVT::getVectorVT(*DAG.getContext(), MVT::f64, 10027 VT.getVectorNumElements()); 10028 SDValue Vec = DAG.getNode(ISD::BITCAST, dl, FloatVT, N->getOperand(0)); 10029 SDValue V = DAG.getNode(ISD::BITCAST, dl, MVT::f64, N->getOperand(1)); 10030 // Make the DAGCombiner fold the bitcasts. 10031 DCI.AddToWorklist(Vec.getNode()); 10032 DCI.AddToWorklist(V.getNode()); 10033 SDValue InsElt = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, FloatVT, 10034 Vec, V, N->getOperand(2)); 10035 return DAG.getNode(ISD::BITCAST, dl, VT, InsElt); 10036 } 10037 10038 /// PerformVECTOR_SHUFFLECombine - Target-specific dag combine xforms for 10039 /// ISD::VECTOR_SHUFFLE. 10040 static SDValue PerformVECTOR_SHUFFLECombine(SDNode *N, SelectionDAG &DAG) { 10041 // The LLVM shufflevector instruction does not require the shuffle mask 10042 // length to match the operand vector length, but ISD::VECTOR_SHUFFLE does 10043 // have that requirement. When translating to ISD::VECTOR_SHUFFLE, if the 10044 // operands do not match the mask length, they are extended by concatenating 10045 // them with undef vectors. That is probably the right thing for other 10046 // targets, but for NEON it is better to concatenate two double-register 10047 // size vector operands into a single quad-register size vector. Do that 10048 // transformation here: 10049 // shuffle(concat(v1, undef), concat(v2, undef)) -> 10050 // shuffle(concat(v1, v2), undef) 10051 SDValue Op0 = N->getOperand(0); 10052 SDValue Op1 = N->getOperand(1); 10053 if (Op0.getOpcode() != ISD::CONCAT_VECTORS || 10054 Op1.getOpcode() != ISD::CONCAT_VECTORS || 10055 Op0.getNumOperands() != 2 || 10056 Op1.getNumOperands() != 2) 10057 return SDValue(); 10058 SDValue Concat0Op1 = Op0.getOperand(1); 10059 SDValue Concat1Op1 = Op1.getOperand(1); 10060 if (!Concat0Op1.isUndef() || !Concat1Op1.isUndef()) 10061 return SDValue(); 10062 // Skip the transformation if any of the types are illegal. 10063 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 10064 EVT VT = N->getValueType(0); 10065 if (!TLI.isTypeLegal(VT) || 10066 !TLI.isTypeLegal(Concat0Op1.getValueType()) || 10067 !TLI.isTypeLegal(Concat1Op1.getValueType())) 10068 return SDValue(); 10069 10070 SDValue NewConcat = DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT, 10071 Op0.getOperand(0), Op1.getOperand(0)); 10072 // Translate the shuffle mask. 10073 SmallVector<int, 16> NewMask; 10074 unsigned NumElts = VT.getVectorNumElements(); 10075 unsigned HalfElts = NumElts/2; 10076 ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N); 10077 for (unsigned n = 0; n < NumElts; ++n) { 10078 int MaskElt = SVN->getMaskElt(n); 10079 int NewElt = -1; 10080 if (MaskElt < (int)HalfElts) 10081 NewElt = MaskElt; 10082 else if (MaskElt >= (int)NumElts && MaskElt < (int)(NumElts + HalfElts)) 10083 NewElt = HalfElts + MaskElt - NumElts; 10084 NewMask.push_back(NewElt); 10085 } 10086 return DAG.getVectorShuffle(VT, SDLoc(N), NewConcat, 10087 DAG.getUNDEF(VT), NewMask); 10088 } 10089 10090 /// CombineBaseUpdate - Target-specific DAG combine function for VLDDUP, 10091 /// NEON load/store intrinsics, and generic vector load/stores, to merge 10092 /// base address updates. 10093 /// For generic load/stores, the memory type is assumed to be a vector. 10094 /// The caller is assumed to have checked legality. 10095 static SDValue CombineBaseUpdate(SDNode *N, 10096 TargetLowering::DAGCombinerInfo &DCI) { 10097 SelectionDAG &DAG = DCI.DAG; 10098 const bool isIntrinsic = (N->getOpcode() == ISD::INTRINSIC_VOID || 10099 N->getOpcode() == ISD::INTRINSIC_W_CHAIN); 10100 const bool isStore = N->getOpcode() == ISD::STORE; 10101 const unsigned AddrOpIdx = ((isIntrinsic || isStore) ? 2 : 1); 10102 SDValue Addr = N->getOperand(AddrOpIdx); 10103 MemSDNode *MemN = cast<MemSDNode>(N); 10104 SDLoc dl(N); 10105 10106 // Search for a use of the address operand that is an increment. 10107 for (SDNode::use_iterator UI = Addr.getNode()->use_begin(), 10108 UE = Addr.getNode()->use_end(); UI != UE; ++UI) { 10109 SDNode *User = *UI; 10110 if (User->getOpcode() != ISD::ADD || 10111 UI.getUse().getResNo() != Addr.getResNo()) 10112 continue; 10113 10114 // Check that the add is independent of the load/store. Otherwise, folding 10115 // it would create a cycle. 10116 if (User->isPredecessorOf(N) || N->isPredecessorOf(User)) 10117 continue; 10118 10119 // Find the new opcode for the updating load/store. 10120 bool isLoadOp = true; 10121 bool isLaneOp = false; 10122 unsigned NewOpc = 0; 10123 unsigned NumVecs = 0; 10124 if (isIntrinsic) { 10125 unsigned IntNo = cast<ConstantSDNode>(N->getOperand(1))->getZExtValue(); 10126 switch (IntNo) { 10127 default: llvm_unreachable("unexpected intrinsic for Neon base update"); 10128 case Intrinsic::arm_neon_vld1: NewOpc = ARMISD::VLD1_UPD; 10129 NumVecs = 1; break; 10130 case Intrinsic::arm_neon_vld2: NewOpc = ARMISD::VLD2_UPD; 10131 NumVecs = 2; break; 10132 case Intrinsic::arm_neon_vld3: NewOpc = ARMISD::VLD3_UPD; 10133 NumVecs = 3; break; 10134 case Intrinsic::arm_neon_vld4: NewOpc = ARMISD::VLD4_UPD; 10135 NumVecs = 4; break; 10136 case Intrinsic::arm_neon_vld2lane: NewOpc = ARMISD::VLD2LN_UPD; 10137 NumVecs = 2; isLaneOp = true; break; 10138 case Intrinsic::arm_neon_vld3lane: NewOpc = ARMISD::VLD3LN_UPD; 10139 NumVecs = 3; isLaneOp = true; break; 10140 case Intrinsic::arm_neon_vld4lane: NewOpc = ARMISD::VLD4LN_UPD; 10141 NumVecs = 4; isLaneOp = true; break; 10142 case Intrinsic::arm_neon_vst1: NewOpc = ARMISD::VST1_UPD; 10143 NumVecs = 1; isLoadOp = false; break; 10144 case Intrinsic::arm_neon_vst2: NewOpc = ARMISD::VST2_UPD; 10145 NumVecs = 2; isLoadOp = false; break; 10146 case Intrinsic::arm_neon_vst3: NewOpc = ARMISD::VST3_UPD; 10147 NumVecs = 3; isLoadOp = false; break; 10148 case Intrinsic::arm_neon_vst4: NewOpc = ARMISD::VST4_UPD; 10149 NumVecs = 4; isLoadOp = false; break; 10150 case Intrinsic::arm_neon_vst2lane: NewOpc = ARMISD::VST2LN_UPD; 10151 NumVecs = 2; isLoadOp = false; isLaneOp = true; break; 10152 case Intrinsic::arm_neon_vst3lane: NewOpc = ARMISD::VST3LN_UPD; 10153 NumVecs = 3; isLoadOp = false; isLaneOp = true; break; 10154 case Intrinsic::arm_neon_vst4lane: NewOpc = ARMISD::VST4LN_UPD; 10155 NumVecs = 4; isLoadOp = false; isLaneOp = true; break; 10156 } 10157 } else { 10158 isLaneOp = true; 10159 switch (N->getOpcode()) { 10160 default: llvm_unreachable("unexpected opcode for Neon base update"); 10161 case ARMISD::VLD2DUP: NewOpc = ARMISD::VLD2DUP_UPD; NumVecs = 2; break; 10162 case ARMISD::VLD3DUP: NewOpc = ARMISD::VLD3DUP_UPD; NumVecs = 3; break; 10163 case ARMISD::VLD4DUP: NewOpc = ARMISD::VLD4DUP_UPD; NumVecs = 4; break; 10164 case ISD::LOAD: NewOpc = ARMISD::VLD1_UPD; 10165 NumVecs = 1; isLaneOp = false; break; 10166 case ISD::STORE: NewOpc = ARMISD::VST1_UPD; 10167 NumVecs = 1; isLaneOp = false; isLoadOp = false; break; 10168 } 10169 } 10170 10171 // Find the size of memory referenced by the load/store. 10172 EVT VecTy; 10173 if (isLoadOp) { 10174 VecTy = N->getValueType(0); 10175 } else if (isIntrinsic) { 10176 VecTy = N->getOperand(AddrOpIdx+1).getValueType(); 10177 } else { 10178 assert(isStore && "Node has to be a load, a store, or an intrinsic!"); 10179 VecTy = N->getOperand(1).getValueType(); 10180 } 10181 10182 unsigned NumBytes = NumVecs * VecTy.getSizeInBits() / 8; 10183 if (isLaneOp) 10184 NumBytes /= VecTy.getVectorNumElements(); 10185 10186 // If the increment is a constant, it must match the memory ref size. 10187 SDValue Inc = User->getOperand(User->getOperand(0) == Addr ? 1 : 0); 10188 if (ConstantSDNode *CInc = dyn_cast<ConstantSDNode>(Inc.getNode())) { 10189 uint64_t IncVal = CInc->getZExtValue(); 10190 if (IncVal != NumBytes) 10191 continue; 10192 } else if (NumBytes >= 3 * 16) { 10193 // VLD3/4 and VST3/4 for 128-bit vectors are implemented with two 10194 // separate instructions that make it harder to use a non-constant update. 10195 continue; 10196 } 10197 10198 // OK, we found an ADD we can fold into the base update. 10199 // Now, create a _UPD node, taking care of not breaking alignment. 10200 10201 EVT AlignedVecTy = VecTy; 10202 unsigned Alignment = MemN->getAlignment(); 10203 10204 // If this is a less-than-standard-aligned load/store, change the type to 10205 // match the standard alignment. 10206 // The alignment is overlooked when selecting _UPD variants; and it's 10207 // easier to introduce bitcasts here than fix that. 10208 // There are 3 ways to get to this base-update combine: 10209 // - intrinsics: they are assumed to be properly aligned (to the standard 10210 // alignment of the memory type), so we don't need to do anything. 10211 // - ARMISD::VLDx nodes: they are only generated from the aforementioned 10212 // intrinsics, so, likewise, there's nothing to do. 10213 // - generic load/store instructions: the alignment is specified as an 10214 // explicit operand, rather than implicitly as the standard alignment 10215 // of the memory type (like the intrisics). We need to change the 10216 // memory type to match the explicit alignment. That way, we don't 10217 // generate non-standard-aligned ARMISD::VLDx nodes. 10218 if (isa<LSBaseSDNode>(N)) { 10219 if (Alignment == 0) 10220 Alignment = 1; 10221 if (Alignment < VecTy.getScalarSizeInBits() / 8) { 10222 MVT EltTy = MVT::getIntegerVT(Alignment * 8); 10223 assert(NumVecs == 1 && "Unexpected multi-element generic load/store."); 10224 assert(!isLaneOp && "Unexpected generic load/store lane."); 10225 unsigned NumElts = NumBytes / (EltTy.getSizeInBits() / 8); 10226 AlignedVecTy = MVT::getVectorVT(EltTy, NumElts); 10227 } 10228 // Don't set an explicit alignment on regular load/stores that we want 10229 // to transform to VLD/VST 1_UPD nodes. 10230 // This matches the behavior of regular load/stores, which only get an 10231 // explicit alignment if the MMO alignment is larger than the standard 10232 // alignment of the memory type. 10233 // Intrinsics, however, always get an explicit alignment, set to the 10234 // alignment of the MMO. 10235 Alignment = 1; 10236 } 10237 10238 // Create the new updating load/store node. 10239 // First, create an SDVTList for the new updating node's results. 10240 EVT Tys[6]; 10241 unsigned NumResultVecs = (isLoadOp ? NumVecs : 0); 10242 unsigned n; 10243 for (n = 0; n < NumResultVecs; ++n) 10244 Tys[n] = AlignedVecTy; 10245 Tys[n++] = MVT::i32; 10246 Tys[n] = MVT::Other; 10247 SDVTList SDTys = DAG.getVTList(makeArrayRef(Tys, NumResultVecs+2)); 10248 10249 // Then, gather the new node's operands. 10250 SmallVector<SDValue, 8> Ops; 10251 Ops.push_back(N->getOperand(0)); // incoming chain 10252 Ops.push_back(N->getOperand(AddrOpIdx)); 10253 Ops.push_back(Inc); 10254 10255 if (StoreSDNode *StN = dyn_cast<StoreSDNode>(N)) { 10256 // Try to match the intrinsic's signature 10257 Ops.push_back(StN->getValue()); 10258 } else { 10259 // Loads (and of course intrinsics) match the intrinsics' signature, 10260 // so just add all but the alignment operand. 10261 for (unsigned i = AddrOpIdx + 1; i < N->getNumOperands() - 1; ++i) 10262 Ops.push_back(N->getOperand(i)); 10263 } 10264 10265 // For all node types, the alignment operand is always the last one. 10266 Ops.push_back(DAG.getConstant(Alignment, dl, MVT::i32)); 10267 10268 // If this is a non-standard-aligned STORE, the penultimate operand is the 10269 // stored value. Bitcast it to the aligned type. 10270 if (AlignedVecTy != VecTy && N->getOpcode() == ISD::STORE) { 10271 SDValue &StVal = Ops[Ops.size()-2]; 10272 StVal = DAG.getNode(ISD::BITCAST, dl, AlignedVecTy, StVal); 10273 } 10274 10275 SDValue UpdN = DAG.getMemIntrinsicNode(NewOpc, dl, SDTys, 10276 Ops, AlignedVecTy, 10277 MemN->getMemOperand()); 10278 10279 // Update the uses. 10280 SmallVector<SDValue, 5> NewResults; 10281 for (unsigned i = 0; i < NumResultVecs; ++i) 10282 NewResults.push_back(SDValue(UpdN.getNode(), i)); 10283 10284 // If this is an non-standard-aligned LOAD, the first result is the loaded 10285 // value. Bitcast it to the expected result type. 10286 if (AlignedVecTy != VecTy && N->getOpcode() == ISD::LOAD) { 10287 SDValue &LdVal = NewResults[0]; 10288 LdVal = DAG.getNode(ISD::BITCAST, dl, VecTy, LdVal); 10289 } 10290 10291 NewResults.push_back(SDValue(UpdN.getNode(), NumResultVecs+1)); // chain 10292 DCI.CombineTo(N, NewResults); 10293 DCI.CombineTo(User, SDValue(UpdN.getNode(), NumResultVecs)); 10294 10295 break; 10296 } 10297 return SDValue(); 10298 } 10299 10300 static SDValue PerformVLDCombine(SDNode *N, 10301 TargetLowering::DAGCombinerInfo &DCI) { 10302 if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer()) 10303 return SDValue(); 10304 10305 return CombineBaseUpdate(N, DCI); 10306 } 10307 10308 /// CombineVLDDUP - For a VDUPLANE node N, check if its source operand is a 10309 /// vldN-lane (N > 1) intrinsic, and if all the other uses of that intrinsic 10310 /// are also VDUPLANEs. If so, combine them to a vldN-dup operation and 10311 /// return true. 10312 static bool CombineVLDDUP(SDNode *N, TargetLowering::DAGCombinerInfo &DCI) { 10313 SelectionDAG &DAG = DCI.DAG; 10314 EVT VT = N->getValueType(0); 10315 // vldN-dup instructions only support 64-bit vectors for N > 1. 10316 if (!VT.is64BitVector()) 10317 return false; 10318 10319 // Check if the VDUPLANE operand is a vldN-dup intrinsic. 10320 SDNode *VLD = N->getOperand(0).getNode(); 10321 if (VLD->getOpcode() != ISD::INTRINSIC_W_CHAIN) 10322 return false; 10323 unsigned NumVecs = 0; 10324 unsigned NewOpc = 0; 10325 unsigned IntNo = cast<ConstantSDNode>(VLD->getOperand(1))->getZExtValue(); 10326 if (IntNo == Intrinsic::arm_neon_vld2lane) { 10327 NumVecs = 2; 10328 NewOpc = ARMISD::VLD2DUP; 10329 } else if (IntNo == Intrinsic::arm_neon_vld3lane) { 10330 NumVecs = 3; 10331 NewOpc = ARMISD::VLD3DUP; 10332 } else if (IntNo == Intrinsic::arm_neon_vld4lane) { 10333 NumVecs = 4; 10334 NewOpc = ARMISD::VLD4DUP; 10335 } else { 10336 return false; 10337 } 10338 10339 // First check that all the vldN-lane uses are VDUPLANEs and that the lane 10340 // numbers match the load. 10341 unsigned VLDLaneNo = 10342 cast<ConstantSDNode>(VLD->getOperand(NumVecs+3))->getZExtValue(); 10343 for (SDNode::use_iterator UI = VLD->use_begin(), UE = VLD->use_end(); 10344 UI != UE; ++UI) { 10345 // Ignore uses of the chain result. 10346 if (UI.getUse().getResNo() == NumVecs) 10347 continue; 10348 SDNode *User = *UI; 10349 if (User->getOpcode() != ARMISD::VDUPLANE || 10350 VLDLaneNo != cast<ConstantSDNode>(User->getOperand(1))->getZExtValue()) 10351 return false; 10352 } 10353 10354 // Create the vldN-dup node. 10355 EVT Tys[5]; 10356 unsigned n; 10357 for (n = 0; n < NumVecs; ++n) 10358 Tys[n] = VT; 10359 Tys[n] = MVT::Other; 10360 SDVTList SDTys = DAG.getVTList(makeArrayRef(Tys, NumVecs+1)); 10361 SDValue Ops[] = { VLD->getOperand(0), VLD->getOperand(2) }; 10362 MemIntrinsicSDNode *VLDMemInt = cast<MemIntrinsicSDNode>(VLD); 10363 SDValue VLDDup = DAG.getMemIntrinsicNode(NewOpc, SDLoc(VLD), SDTys, 10364 Ops, VLDMemInt->getMemoryVT(), 10365 VLDMemInt->getMemOperand()); 10366 10367 // Update the uses. 10368 for (SDNode::use_iterator UI = VLD->use_begin(), UE = VLD->use_end(); 10369 UI != UE; ++UI) { 10370 unsigned ResNo = UI.getUse().getResNo(); 10371 // Ignore uses of the chain result. 10372 if (ResNo == NumVecs) 10373 continue; 10374 SDNode *User = *UI; 10375 DCI.CombineTo(User, SDValue(VLDDup.getNode(), ResNo)); 10376 } 10377 10378 // Now the vldN-lane intrinsic is dead except for its chain result. 10379 // Update uses of the chain. 10380 std::vector<SDValue> VLDDupResults; 10381 for (unsigned n = 0; n < NumVecs; ++n) 10382 VLDDupResults.push_back(SDValue(VLDDup.getNode(), n)); 10383 VLDDupResults.push_back(SDValue(VLDDup.getNode(), NumVecs)); 10384 DCI.CombineTo(VLD, VLDDupResults); 10385 10386 return true; 10387 } 10388 10389 /// PerformVDUPLANECombine - Target-specific dag combine xforms for 10390 /// ARMISD::VDUPLANE. 10391 static SDValue PerformVDUPLANECombine(SDNode *N, 10392 TargetLowering::DAGCombinerInfo &DCI) { 10393 SDValue Op = N->getOperand(0); 10394 10395 // If the source is a vldN-lane (N > 1) intrinsic, and all the other uses 10396 // of that intrinsic are also VDUPLANEs, combine them to a vldN-dup operation. 10397 if (CombineVLDDUP(N, DCI)) 10398 return SDValue(N, 0); 10399 10400 // If the source is already a VMOVIMM or VMVNIMM splat, the VDUPLANE is 10401 // redundant. Ignore bit_converts for now; element sizes are checked below. 10402 while (Op.getOpcode() == ISD::BITCAST) 10403 Op = Op.getOperand(0); 10404 if (Op.getOpcode() != ARMISD::VMOVIMM && Op.getOpcode() != ARMISD::VMVNIMM) 10405 return SDValue(); 10406 10407 // Make sure the VMOV element size is not bigger than the VDUPLANE elements. 10408 unsigned EltSize = Op.getValueType().getVectorElementType().getSizeInBits(); 10409 // The canonical VMOV for a zero vector uses a 32-bit element size. 10410 unsigned Imm = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue(); 10411 unsigned EltBits; 10412 if (ARM_AM::decodeNEONModImm(Imm, EltBits) == 0) 10413 EltSize = 8; 10414 EVT VT = N->getValueType(0); 10415 if (EltSize > VT.getVectorElementType().getSizeInBits()) 10416 return SDValue(); 10417 10418 return DCI.DAG.getNode(ISD::BITCAST, SDLoc(N), VT, Op); 10419 } 10420 10421 static SDValue PerformLOADCombine(SDNode *N, 10422 TargetLowering::DAGCombinerInfo &DCI) { 10423 EVT VT = N->getValueType(0); 10424 10425 // If this is a legal vector load, try to combine it into a VLD1_UPD. 10426 if (ISD::isNormalLoad(N) && VT.isVector() && 10427 DCI.DAG.getTargetLoweringInfo().isTypeLegal(VT)) 10428 return CombineBaseUpdate(N, DCI); 10429 10430 return SDValue(); 10431 } 10432 10433 /// PerformSTORECombine - Target-specific dag combine xforms for 10434 /// ISD::STORE. 10435 static SDValue PerformSTORECombine(SDNode *N, 10436 TargetLowering::DAGCombinerInfo &DCI) { 10437 StoreSDNode *St = cast<StoreSDNode>(N); 10438 if (St->isVolatile()) 10439 return SDValue(); 10440 10441 // Optimize trunc store (of multiple scalars) to shuffle and store. First, 10442 // pack all of the elements in one place. Next, store to memory in fewer 10443 // chunks. 10444 SDValue StVal = St->getValue(); 10445 EVT VT = StVal.getValueType(); 10446 if (St->isTruncatingStore() && VT.isVector()) { 10447 SelectionDAG &DAG = DCI.DAG; 10448 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 10449 EVT StVT = St->getMemoryVT(); 10450 unsigned NumElems = VT.getVectorNumElements(); 10451 assert(StVT != VT && "Cannot truncate to the same type"); 10452 unsigned FromEltSz = VT.getVectorElementType().getSizeInBits(); 10453 unsigned ToEltSz = StVT.getVectorElementType().getSizeInBits(); 10454 10455 // From, To sizes and ElemCount must be pow of two 10456 if (!isPowerOf2_32(NumElems * FromEltSz * ToEltSz)) return SDValue(); 10457 10458 // We are going to use the original vector elt for storing. 10459 // Accumulated smaller vector elements must be a multiple of the store size. 10460 if (0 != (NumElems * FromEltSz) % ToEltSz) return SDValue(); 10461 10462 unsigned SizeRatio = FromEltSz / ToEltSz; 10463 assert(SizeRatio * NumElems * ToEltSz == VT.getSizeInBits()); 10464 10465 // Create a type on which we perform the shuffle. 10466 EVT WideVecVT = EVT::getVectorVT(*DAG.getContext(), StVT.getScalarType(), 10467 NumElems*SizeRatio); 10468 assert(WideVecVT.getSizeInBits() == VT.getSizeInBits()); 10469 10470 SDLoc DL(St); 10471 SDValue WideVec = DAG.getNode(ISD::BITCAST, DL, WideVecVT, StVal); 10472 SmallVector<int, 8> ShuffleVec(NumElems * SizeRatio, -1); 10473 for (unsigned i = 0; i < NumElems; ++i) 10474 ShuffleVec[i] = DAG.getDataLayout().isBigEndian() 10475 ? (i + 1) * SizeRatio - 1 10476 : i * SizeRatio; 10477 10478 // Can't shuffle using an illegal type. 10479 if (!TLI.isTypeLegal(WideVecVT)) return SDValue(); 10480 10481 SDValue Shuff = DAG.getVectorShuffle(WideVecVT, DL, WideVec, 10482 DAG.getUNDEF(WideVec.getValueType()), 10483 ShuffleVec); 10484 // At this point all of the data is stored at the bottom of the 10485 // register. We now need to save it to mem. 10486 10487 // Find the largest store unit 10488 MVT StoreType = MVT::i8; 10489 for (MVT Tp : MVT::integer_valuetypes()) { 10490 if (TLI.isTypeLegal(Tp) && Tp.getSizeInBits() <= NumElems * ToEltSz) 10491 StoreType = Tp; 10492 } 10493 // Didn't find a legal store type. 10494 if (!TLI.isTypeLegal(StoreType)) 10495 return SDValue(); 10496 10497 // Bitcast the original vector into a vector of store-size units 10498 EVT StoreVecVT = EVT::getVectorVT(*DAG.getContext(), 10499 StoreType, VT.getSizeInBits()/EVT(StoreType).getSizeInBits()); 10500 assert(StoreVecVT.getSizeInBits() == VT.getSizeInBits()); 10501 SDValue ShuffWide = DAG.getNode(ISD::BITCAST, DL, StoreVecVT, Shuff); 10502 SmallVector<SDValue, 8> Chains; 10503 SDValue Increment = DAG.getConstant(StoreType.getSizeInBits() / 8, DL, 10504 TLI.getPointerTy(DAG.getDataLayout())); 10505 SDValue BasePtr = St->getBasePtr(); 10506 10507 // Perform one or more big stores into memory. 10508 unsigned E = (ToEltSz*NumElems)/StoreType.getSizeInBits(); 10509 for (unsigned I = 0; I < E; I++) { 10510 SDValue SubVec = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, 10511 StoreType, ShuffWide, 10512 DAG.getIntPtrConstant(I, DL)); 10513 SDValue Ch = DAG.getStore(St->getChain(), DL, SubVec, BasePtr, 10514 St->getPointerInfo(), St->getAlignment(), 10515 St->getMemOperand()->getFlags()); 10516 BasePtr = DAG.getNode(ISD::ADD, DL, BasePtr.getValueType(), BasePtr, 10517 Increment); 10518 Chains.push_back(Ch); 10519 } 10520 return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Chains); 10521 } 10522 10523 if (!ISD::isNormalStore(St)) 10524 return SDValue(); 10525 10526 // Split a store of a VMOVDRR into two integer stores to avoid mixing NEON and 10527 // ARM stores of arguments in the same cache line. 10528 if (StVal.getNode()->getOpcode() == ARMISD::VMOVDRR && 10529 StVal.getNode()->hasOneUse()) { 10530 SelectionDAG &DAG = DCI.DAG; 10531 bool isBigEndian = DAG.getDataLayout().isBigEndian(); 10532 SDLoc DL(St); 10533 SDValue BasePtr = St->getBasePtr(); 10534 SDValue NewST1 = DAG.getStore( 10535 St->getChain(), DL, StVal.getNode()->getOperand(isBigEndian ? 1 : 0), 10536 BasePtr, St->getPointerInfo(), St->getAlignment(), 10537 St->getMemOperand()->getFlags()); 10538 10539 SDValue OffsetPtr = DAG.getNode(ISD::ADD, DL, MVT::i32, BasePtr, 10540 DAG.getConstant(4, DL, MVT::i32)); 10541 return DAG.getStore(NewST1.getValue(0), DL, 10542 StVal.getNode()->getOperand(isBigEndian ? 0 : 1), 10543 OffsetPtr, St->getPointerInfo(), 10544 std::min(4U, St->getAlignment() / 2), 10545 St->getMemOperand()->getFlags()); 10546 } 10547 10548 if (StVal.getValueType() == MVT::i64 && 10549 StVal.getNode()->getOpcode() == ISD::EXTRACT_VECTOR_ELT) { 10550 10551 // Bitcast an i64 store extracted from a vector to f64. 10552 // Otherwise, the i64 value will be legalized to a pair of i32 values. 10553 SelectionDAG &DAG = DCI.DAG; 10554 SDLoc dl(StVal); 10555 SDValue IntVec = StVal.getOperand(0); 10556 EVT FloatVT = EVT::getVectorVT(*DAG.getContext(), MVT::f64, 10557 IntVec.getValueType().getVectorNumElements()); 10558 SDValue Vec = DAG.getNode(ISD::BITCAST, dl, FloatVT, IntVec); 10559 SDValue ExtElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, 10560 Vec, StVal.getOperand(1)); 10561 dl = SDLoc(N); 10562 SDValue V = DAG.getNode(ISD::BITCAST, dl, MVT::i64, ExtElt); 10563 // Make the DAGCombiner fold the bitcasts. 10564 DCI.AddToWorklist(Vec.getNode()); 10565 DCI.AddToWorklist(ExtElt.getNode()); 10566 DCI.AddToWorklist(V.getNode()); 10567 return DAG.getStore(St->getChain(), dl, V, St->getBasePtr(), 10568 St->getPointerInfo(), St->getAlignment(), 10569 St->getMemOperand()->getFlags(), St->getAAInfo()); 10570 } 10571 10572 // If this is a legal vector store, try to combine it into a VST1_UPD. 10573 if (ISD::isNormalStore(N) && VT.isVector() && 10574 DCI.DAG.getTargetLoweringInfo().isTypeLegal(VT)) 10575 return CombineBaseUpdate(N, DCI); 10576 10577 return SDValue(); 10578 } 10579 10580 /// PerformVCVTCombine - VCVT (floating-point to fixed-point, Advanced SIMD) 10581 /// can replace combinations of VMUL and VCVT (floating-point to integer) 10582 /// when the VMUL has a constant operand that is a power of 2. 10583 /// 10584 /// Example (assume d17 = <float 8.000000e+00, float 8.000000e+00>): 10585 /// vmul.f32 d16, d17, d16 10586 /// vcvt.s32.f32 d16, d16 10587 /// becomes: 10588 /// vcvt.s32.f32 d16, d16, #3 10589 static SDValue PerformVCVTCombine(SDNode *N, SelectionDAG &DAG, 10590 const ARMSubtarget *Subtarget) { 10591 if (!Subtarget->hasNEON()) 10592 return SDValue(); 10593 10594 SDValue Op = N->getOperand(0); 10595 if (!Op.getValueType().isVector() || !Op.getValueType().isSimple() || 10596 Op.getOpcode() != ISD::FMUL) 10597 return SDValue(); 10598 10599 SDValue ConstVec = Op->getOperand(1); 10600 if (!isa<BuildVectorSDNode>(ConstVec)) 10601 return SDValue(); 10602 10603 MVT FloatTy = Op.getSimpleValueType().getVectorElementType(); 10604 uint32_t FloatBits = FloatTy.getSizeInBits(); 10605 MVT IntTy = N->getSimpleValueType(0).getVectorElementType(); 10606 uint32_t IntBits = IntTy.getSizeInBits(); 10607 unsigned NumLanes = Op.getValueType().getVectorNumElements(); 10608 if (FloatBits != 32 || IntBits > 32 || NumLanes > 4) { 10609 // These instructions only exist converting from f32 to i32. We can handle 10610 // smaller integers by generating an extra truncate, but larger ones would 10611 // be lossy. We also can't handle more then 4 lanes, since these intructions 10612 // only support v2i32/v4i32 types. 10613 return SDValue(); 10614 } 10615 10616 BitVector UndefElements; 10617 BuildVectorSDNode *BV = cast<BuildVectorSDNode>(ConstVec); 10618 int32_t C = BV->getConstantFPSplatPow2ToLog2Int(&UndefElements, 33); 10619 if (C == -1 || C == 0 || C > 32) 10620 return SDValue(); 10621 10622 SDLoc dl(N); 10623 bool isSigned = N->getOpcode() == ISD::FP_TO_SINT; 10624 unsigned IntrinsicOpcode = isSigned ? Intrinsic::arm_neon_vcvtfp2fxs : 10625 Intrinsic::arm_neon_vcvtfp2fxu; 10626 SDValue FixConv = DAG.getNode( 10627 ISD::INTRINSIC_WO_CHAIN, dl, NumLanes == 2 ? MVT::v2i32 : MVT::v4i32, 10628 DAG.getConstant(IntrinsicOpcode, dl, MVT::i32), Op->getOperand(0), 10629 DAG.getConstant(C, dl, MVT::i32)); 10630 10631 if (IntBits < FloatBits) 10632 FixConv = DAG.getNode(ISD::TRUNCATE, dl, N->getValueType(0), FixConv); 10633 10634 return FixConv; 10635 } 10636 10637 /// PerformVDIVCombine - VCVT (fixed-point to floating-point, Advanced SIMD) 10638 /// can replace combinations of VCVT (integer to floating-point) and VDIV 10639 /// when the VDIV has a constant operand that is a power of 2. 10640 /// 10641 /// Example (assume d17 = <float 8.000000e+00, float 8.000000e+00>): 10642 /// vcvt.f32.s32 d16, d16 10643 /// vdiv.f32 d16, d17, d16 10644 /// becomes: 10645 /// vcvt.f32.s32 d16, d16, #3 10646 static SDValue PerformVDIVCombine(SDNode *N, SelectionDAG &DAG, 10647 const ARMSubtarget *Subtarget) { 10648 if (!Subtarget->hasNEON()) 10649 return SDValue(); 10650 10651 SDValue Op = N->getOperand(0); 10652 unsigned OpOpcode = Op.getNode()->getOpcode(); 10653 if (!N->getValueType(0).isVector() || !N->getValueType(0).isSimple() || 10654 (OpOpcode != ISD::SINT_TO_FP && OpOpcode != ISD::UINT_TO_FP)) 10655 return SDValue(); 10656 10657 SDValue ConstVec = N->getOperand(1); 10658 if (!isa<BuildVectorSDNode>(ConstVec)) 10659 return SDValue(); 10660 10661 MVT FloatTy = N->getSimpleValueType(0).getVectorElementType(); 10662 uint32_t FloatBits = FloatTy.getSizeInBits(); 10663 MVT IntTy = Op.getOperand(0).getSimpleValueType().getVectorElementType(); 10664 uint32_t IntBits = IntTy.getSizeInBits(); 10665 unsigned NumLanes = Op.getValueType().getVectorNumElements(); 10666 if (FloatBits != 32 || IntBits > 32 || NumLanes > 4) { 10667 // These instructions only exist converting from i32 to f32. We can handle 10668 // smaller integers by generating an extra extend, but larger ones would 10669 // be lossy. We also can't handle more then 4 lanes, since these intructions 10670 // only support v2i32/v4i32 types. 10671 return SDValue(); 10672 } 10673 10674 BitVector UndefElements; 10675 BuildVectorSDNode *BV = cast<BuildVectorSDNode>(ConstVec); 10676 int32_t C = BV->getConstantFPSplatPow2ToLog2Int(&UndefElements, 33); 10677 if (C == -1 || C == 0 || C > 32) 10678 return SDValue(); 10679 10680 SDLoc dl(N); 10681 bool isSigned = OpOpcode == ISD::SINT_TO_FP; 10682 SDValue ConvInput = Op.getOperand(0); 10683 if (IntBits < FloatBits) 10684 ConvInput = DAG.getNode(isSigned ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND, 10685 dl, NumLanes == 2 ? MVT::v2i32 : MVT::v4i32, 10686 ConvInput); 10687 10688 unsigned IntrinsicOpcode = isSigned ? Intrinsic::arm_neon_vcvtfxs2fp : 10689 Intrinsic::arm_neon_vcvtfxu2fp; 10690 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, 10691 Op.getValueType(), 10692 DAG.getConstant(IntrinsicOpcode, dl, MVT::i32), 10693 ConvInput, DAG.getConstant(C, dl, MVT::i32)); 10694 } 10695 10696 /// Getvshiftimm - Check if this is a valid build_vector for the immediate 10697 /// operand of a vector shift operation, where all the elements of the 10698 /// build_vector must have the same constant integer value. 10699 static bool getVShiftImm(SDValue Op, unsigned ElementBits, int64_t &Cnt) { 10700 // Ignore bit_converts. 10701 while (Op.getOpcode() == ISD::BITCAST) 10702 Op = Op.getOperand(0); 10703 BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(Op.getNode()); 10704 APInt SplatBits, SplatUndef; 10705 unsigned SplatBitSize; 10706 bool HasAnyUndefs; 10707 if (! BVN || ! BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, 10708 HasAnyUndefs, ElementBits) || 10709 SplatBitSize > ElementBits) 10710 return false; 10711 Cnt = SplatBits.getSExtValue(); 10712 return true; 10713 } 10714 10715 /// isVShiftLImm - Check if this is a valid build_vector for the immediate 10716 /// operand of a vector shift left operation. That value must be in the range: 10717 /// 0 <= Value < ElementBits for a left shift; or 10718 /// 0 <= Value <= ElementBits for a long left shift. 10719 static bool isVShiftLImm(SDValue Op, EVT VT, bool isLong, int64_t &Cnt) { 10720 assert(VT.isVector() && "vector shift count is not a vector type"); 10721 int64_t ElementBits = VT.getVectorElementType().getSizeInBits(); 10722 if (! getVShiftImm(Op, ElementBits, Cnt)) 10723 return false; 10724 return (Cnt >= 0 && (isLong ? Cnt-1 : Cnt) < ElementBits); 10725 } 10726 10727 /// isVShiftRImm - Check if this is a valid build_vector for the immediate 10728 /// operand of a vector shift right operation. For a shift opcode, the value 10729 /// is positive, but for an intrinsic the value count must be negative. The 10730 /// absolute value must be in the range: 10731 /// 1 <= |Value| <= ElementBits for a right shift; or 10732 /// 1 <= |Value| <= ElementBits/2 for a narrow right shift. 10733 static bool isVShiftRImm(SDValue Op, EVT VT, bool isNarrow, bool isIntrinsic, 10734 int64_t &Cnt) { 10735 assert(VT.isVector() && "vector shift count is not a vector type"); 10736 int64_t ElementBits = VT.getVectorElementType().getSizeInBits(); 10737 if (! getVShiftImm(Op, ElementBits, Cnt)) 10738 return false; 10739 if (!isIntrinsic) 10740 return (Cnt >= 1 && Cnt <= (isNarrow ? ElementBits/2 : ElementBits)); 10741 if (Cnt >= -(isNarrow ? ElementBits/2 : ElementBits) && Cnt <= -1) { 10742 Cnt = -Cnt; 10743 return true; 10744 } 10745 return false; 10746 } 10747 10748 /// PerformIntrinsicCombine - ARM-specific DAG combining for intrinsics. 10749 static SDValue PerformIntrinsicCombine(SDNode *N, SelectionDAG &DAG) { 10750 unsigned IntNo = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue(); 10751 switch (IntNo) { 10752 default: 10753 // Don't do anything for most intrinsics. 10754 break; 10755 10756 // Vector shifts: check for immediate versions and lower them. 10757 // Note: This is done during DAG combining instead of DAG legalizing because 10758 // the build_vectors for 64-bit vector element shift counts are generally 10759 // not legal, and it is hard to see their values after they get legalized to 10760 // loads from a constant pool. 10761 case Intrinsic::arm_neon_vshifts: 10762 case Intrinsic::arm_neon_vshiftu: 10763 case Intrinsic::arm_neon_vrshifts: 10764 case Intrinsic::arm_neon_vrshiftu: 10765 case Intrinsic::arm_neon_vrshiftn: 10766 case Intrinsic::arm_neon_vqshifts: 10767 case Intrinsic::arm_neon_vqshiftu: 10768 case Intrinsic::arm_neon_vqshiftsu: 10769 case Intrinsic::arm_neon_vqshiftns: 10770 case Intrinsic::arm_neon_vqshiftnu: 10771 case Intrinsic::arm_neon_vqshiftnsu: 10772 case Intrinsic::arm_neon_vqrshiftns: 10773 case Intrinsic::arm_neon_vqrshiftnu: 10774 case Intrinsic::arm_neon_vqrshiftnsu: { 10775 EVT VT = N->getOperand(1).getValueType(); 10776 int64_t Cnt; 10777 unsigned VShiftOpc = 0; 10778 10779 switch (IntNo) { 10780 case Intrinsic::arm_neon_vshifts: 10781 case Intrinsic::arm_neon_vshiftu: 10782 if (isVShiftLImm(N->getOperand(2), VT, false, Cnt)) { 10783 VShiftOpc = ARMISD::VSHL; 10784 break; 10785 } 10786 if (isVShiftRImm(N->getOperand(2), VT, false, true, Cnt)) { 10787 VShiftOpc = (IntNo == Intrinsic::arm_neon_vshifts ? 10788 ARMISD::VSHRs : ARMISD::VSHRu); 10789 break; 10790 } 10791 return SDValue(); 10792 10793 case Intrinsic::arm_neon_vrshifts: 10794 case Intrinsic::arm_neon_vrshiftu: 10795 if (isVShiftRImm(N->getOperand(2), VT, false, true, Cnt)) 10796 break; 10797 return SDValue(); 10798 10799 case Intrinsic::arm_neon_vqshifts: 10800 case Intrinsic::arm_neon_vqshiftu: 10801 if (isVShiftLImm(N->getOperand(2), VT, false, Cnt)) 10802 break; 10803 return SDValue(); 10804 10805 case Intrinsic::arm_neon_vqshiftsu: 10806 if (isVShiftLImm(N->getOperand(2), VT, false, Cnt)) 10807 break; 10808 llvm_unreachable("invalid shift count for vqshlu intrinsic"); 10809 10810 case Intrinsic::arm_neon_vrshiftn: 10811 case Intrinsic::arm_neon_vqshiftns: 10812 case Intrinsic::arm_neon_vqshiftnu: 10813 case Intrinsic::arm_neon_vqshiftnsu: 10814 case Intrinsic::arm_neon_vqrshiftns: 10815 case Intrinsic::arm_neon_vqrshiftnu: 10816 case Intrinsic::arm_neon_vqrshiftnsu: 10817 // Narrowing shifts require an immediate right shift. 10818 if (isVShiftRImm(N->getOperand(2), VT, true, true, Cnt)) 10819 break; 10820 llvm_unreachable("invalid shift count for narrowing vector shift " 10821 "intrinsic"); 10822 10823 default: 10824 llvm_unreachable("unhandled vector shift"); 10825 } 10826 10827 switch (IntNo) { 10828 case Intrinsic::arm_neon_vshifts: 10829 case Intrinsic::arm_neon_vshiftu: 10830 // Opcode already set above. 10831 break; 10832 case Intrinsic::arm_neon_vrshifts: 10833 VShiftOpc = ARMISD::VRSHRs; break; 10834 case Intrinsic::arm_neon_vrshiftu: 10835 VShiftOpc = ARMISD::VRSHRu; break; 10836 case Intrinsic::arm_neon_vrshiftn: 10837 VShiftOpc = ARMISD::VRSHRN; break; 10838 case Intrinsic::arm_neon_vqshifts: 10839 VShiftOpc = ARMISD::VQSHLs; break; 10840 case Intrinsic::arm_neon_vqshiftu: 10841 VShiftOpc = ARMISD::VQSHLu; break; 10842 case Intrinsic::arm_neon_vqshiftsu: 10843 VShiftOpc = ARMISD::VQSHLsu; break; 10844 case Intrinsic::arm_neon_vqshiftns: 10845 VShiftOpc = ARMISD::VQSHRNs; break; 10846 case Intrinsic::arm_neon_vqshiftnu: 10847 VShiftOpc = ARMISD::VQSHRNu; break; 10848 case Intrinsic::arm_neon_vqshiftnsu: 10849 VShiftOpc = ARMISD::VQSHRNsu; break; 10850 case Intrinsic::arm_neon_vqrshiftns: 10851 VShiftOpc = ARMISD::VQRSHRNs; break; 10852 case Intrinsic::arm_neon_vqrshiftnu: 10853 VShiftOpc = ARMISD::VQRSHRNu; break; 10854 case Intrinsic::arm_neon_vqrshiftnsu: 10855 VShiftOpc = ARMISD::VQRSHRNsu; break; 10856 } 10857 10858 SDLoc dl(N); 10859 return DAG.getNode(VShiftOpc, dl, N->getValueType(0), 10860 N->getOperand(1), DAG.getConstant(Cnt, dl, MVT::i32)); 10861 } 10862 10863 case Intrinsic::arm_neon_vshiftins: { 10864 EVT VT = N->getOperand(1).getValueType(); 10865 int64_t Cnt; 10866 unsigned VShiftOpc = 0; 10867 10868 if (isVShiftLImm(N->getOperand(3), VT, false, Cnt)) 10869 VShiftOpc = ARMISD::VSLI; 10870 else if (isVShiftRImm(N->getOperand(3), VT, false, true, Cnt)) 10871 VShiftOpc = ARMISD::VSRI; 10872 else { 10873 llvm_unreachable("invalid shift count for vsli/vsri intrinsic"); 10874 } 10875 10876 SDLoc dl(N); 10877 return DAG.getNode(VShiftOpc, dl, N->getValueType(0), 10878 N->getOperand(1), N->getOperand(2), 10879 DAG.getConstant(Cnt, dl, MVT::i32)); 10880 } 10881 10882 case Intrinsic::arm_neon_vqrshifts: 10883 case Intrinsic::arm_neon_vqrshiftu: 10884 // No immediate versions of these to check for. 10885 break; 10886 } 10887 10888 return SDValue(); 10889 } 10890 10891 /// PerformShiftCombine - Checks for immediate versions of vector shifts and 10892 /// lowers them. As with the vector shift intrinsics, this is done during DAG 10893 /// combining instead of DAG legalizing because the build_vectors for 64-bit 10894 /// vector element shift counts are generally not legal, and it is hard to see 10895 /// their values after they get legalized to loads from a constant pool. 10896 static SDValue PerformShiftCombine(SDNode *N, SelectionDAG &DAG, 10897 const ARMSubtarget *ST) { 10898 EVT VT = N->getValueType(0); 10899 if (N->getOpcode() == ISD::SRL && VT == MVT::i32 && ST->hasV6Ops()) { 10900 // Canonicalize (srl (bswap x), 16) to (rotr (bswap x), 16) if the high 10901 // 16-bits of x is zero. This optimizes rev + lsr 16 to rev16. 10902 SDValue N1 = N->getOperand(1); 10903 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(N1)) { 10904 SDValue N0 = N->getOperand(0); 10905 if (C->getZExtValue() == 16 && N0.getOpcode() == ISD::BSWAP && 10906 DAG.MaskedValueIsZero(N0.getOperand(0), 10907 APInt::getHighBitsSet(32, 16))) 10908 return DAG.getNode(ISD::ROTR, SDLoc(N), VT, N0, N1); 10909 } 10910 } 10911 10912 // Nothing to be done for scalar shifts. 10913 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 10914 if (!VT.isVector() || !TLI.isTypeLegal(VT)) 10915 return SDValue(); 10916 10917 assert(ST->hasNEON() && "unexpected vector shift"); 10918 int64_t Cnt; 10919 10920 switch (N->getOpcode()) { 10921 default: llvm_unreachable("unexpected shift opcode"); 10922 10923 case ISD::SHL: 10924 if (isVShiftLImm(N->getOperand(1), VT, false, Cnt)) { 10925 SDLoc dl(N); 10926 return DAG.getNode(ARMISD::VSHL, dl, VT, N->getOperand(0), 10927 DAG.getConstant(Cnt, dl, MVT::i32)); 10928 } 10929 break; 10930 10931 case ISD::SRA: 10932 case ISD::SRL: 10933 if (isVShiftRImm(N->getOperand(1), VT, false, false, Cnt)) { 10934 unsigned VShiftOpc = (N->getOpcode() == ISD::SRA ? 10935 ARMISD::VSHRs : ARMISD::VSHRu); 10936 SDLoc dl(N); 10937 return DAG.getNode(VShiftOpc, dl, VT, N->getOperand(0), 10938 DAG.getConstant(Cnt, dl, MVT::i32)); 10939 } 10940 } 10941 return SDValue(); 10942 } 10943 10944 /// PerformExtendCombine - Target-specific DAG combining for ISD::SIGN_EXTEND, 10945 /// ISD::ZERO_EXTEND, and ISD::ANY_EXTEND. 10946 static SDValue PerformExtendCombine(SDNode *N, SelectionDAG &DAG, 10947 const ARMSubtarget *ST) { 10948 SDValue N0 = N->getOperand(0); 10949 10950 // Check for sign- and zero-extensions of vector extract operations of 8- 10951 // and 16-bit vector elements. NEON supports these directly. They are 10952 // handled during DAG combining because type legalization will promote them 10953 // to 32-bit types and it is messy to recognize the operations after that. 10954 if (ST->hasNEON() && N0.getOpcode() == ISD::EXTRACT_VECTOR_ELT) { 10955 SDValue Vec = N0.getOperand(0); 10956 SDValue Lane = N0.getOperand(1); 10957 EVT VT = N->getValueType(0); 10958 EVT EltVT = N0.getValueType(); 10959 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 10960 10961 if (VT == MVT::i32 && 10962 (EltVT == MVT::i8 || EltVT == MVT::i16) && 10963 TLI.isTypeLegal(Vec.getValueType()) && 10964 isa<ConstantSDNode>(Lane)) { 10965 10966 unsigned Opc = 0; 10967 switch (N->getOpcode()) { 10968 default: llvm_unreachable("unexpected opcode"); 10969 case ISD::SIGN_EXTEND: 10970 Opc = ARMISD::VGETLANEs; 10971 break; 10972 case ISD::ZERO_EXTEND: 10973 case ISD::ANY_EXTEND: 10974 Opc = ARMISD::VGETLANEu; 10975 break; 10976 } 10977 return DAG.getNode(Opc, SDLoc(N), VT, Vec, Lane); 10978 } 10979 } 10980 10981 return SDValue(); 10982 } 10983 10984 static void computeKnownBits(SelectionDAG &DAG, SDValue Op, APInt &KnownZero, 10985 APInt &KnownOne) { 10986 if (Op.getOpcode() == ARMISD::BFI) { 10987 // Conservatively, we can recurse down the first operand 10988 // and just mask out all affected bits. 10989 computeKnownBits(DAG, Op.getOperand(0), KnownZero, KnownOne); 10990 10991 // The operand to BFI is already a mask suitable for removing the bits it 10992 // sets. 10993 ConstantSDNode *CI = cast<ConstantSDNode>(Op.getOperand(2)); 10994 const APInt &Mask = CI->getAPIntValue(); 10995 KnownZero &= Mask; 10996 KnownOne &= Mask; 10997 return; 10998 } 10999 if (Op.getOpcode() == ARMISD::CMOV) { 11000 APInt KZ2(KnownZero.getBitWidth(), 0); 11001 APInt KO2(KnownOne.getBitWidth(), 0); 11002 computeKnownBits(DAG, Op.getOperand(1), KnownZero, KnownOne); 11003 computeKnownBits(DAG, Op.getOperand(2), KZ2, KO2); 11004 11005 KnownZero &= KZ2; 11006 KnownOne &= KO2; 11007 return; 11008 } 11009 return DAG.computeKnownBits(Op, KnownZero, KnownOne); 11010 } 11011 11012 SDValue ARMTargetLowering::PerformCMOVToBFICombine(SDNode *CMOV, SelectionDAG &DAG) const { 11013 // If we have a CMOV, OR and AND combination such as: 11014 // if (x & CN) 11015 // y |= CM; 11016 // 11017 // And: 11018 // * CN is a single bit; 11019 // * All bits covered by CM are known zero in y 11020 // 11021 // Then we can convert this into a sequence of BFI instructions. This will 11022 // always be a win if CM is a single bit, will always be no worse than the 11023 // TST&OR sequence if CM is two bits, and for thumb will be no worse if CM is 11024 // three bits (due to the extra IT instruction). 11025 11026 SDValue Op0 = CMOV->getOperand(0); 11027 SDValue Op1 = CMOV->getOperand(1); 11028 auto CCNode = cast<ConstantSDNode>(CMOV->getOperand(2)); 11029 auto CC = CCNode->getAPIntValue().getLimitedValue(); 11030 SDValue CmpZ = CMOV->getOperand(4); 11031 11032 // The compare must be against zero. 11033 if (!isNullConstant(CmpZ->getOperand(1))) 11034 return SDValue(); 11035 11036 assert(CmpZ->getOpcode() == ARMISD::CMPZ); 11037 SDValue And = CmpZ->getOperand(0); 11038 if (And->getOpcode() != ISD::AND) 11039 return SDValue(); 11040 ConstantSDNode *AndC = dyn_cast<ConstantSDNode>(And->getOperand(1)); 11041 if (!AndC || !AndC->getAPIntValue().isPowerOf2()) 11042 return SDValue(); 11043 SDValue X = And->getOperand(0); 11044 11045 if (CC == ARMCC::EQ) { 11046 // We're performing an "equal to zero" compare. Swap the operands so we 11047 // canonicalize on a "not equal to zero" compare. 11048 std::swap(Op0, Op1); 11049 } else { 11050 assert(CC == ARMCC::NE && "How can a CMPZ node not be EQ or NE?"); 11051 } 11052 11053 if (Op1->getOpcode() != ISD::OR) 11054 return SDValue(); 11055 11056 ConstantSDNode *OrC = dyn_cast<ConstantSDNode>(Op1->getOperand(1)); 11057 if (!OrC) 11058 return SDValue(); 11059 SDValue Y = Op1->getOperand(0); 11060 11061 if (Op0 != Y) 11062 return SDValue(); 11063 11064 // Now, is it profitable to continue? 11065 APInt OrCI = OrC->getAPIntValue(); 11066 unsigned Heuristic = Subtarget->isThumb() ? 3 : 2; 11067 if (OrCI.countPopulation() > Heuristic) 11068 return SDValue(); 11069 11070 // Lastly, can we determine that the bits defined by OrCI 11071 // are zero in Y? 11072 APInt KnownZero, KnownOne; 11073 computeKnownBits(DAG, Y, KnownZero, KnownOne); 11074 if ((OrCI & KnownZero) != OrCI) 11075 return SDValue(); 11076 11077 // OK, we can do the combine. 11078 SDValue V = Y; 11079 SDLoc dl(X); 11080 EVT VT = X.getValueType(); 11081 unsigned BitInX = AndC->getAPIntValue().logBase2(); 11082 11083 if (BitInX != 0) { 11084 // We must shift X first. 11085 X = DAG.getNode(ISD::SRL, dl, VT, X, 11086 DAG.getConstant(BitInX, dl, VT)); 11087 } 11088 11089 for (unsigned BitInY = 0, NumActiveBits = OrCI.getActiveBits(); 11090 BitInY < NumActiveBits; ++BitInY) { 11091 if (OrCI[BitInY] == 0) 11092 continue; 11093 APInt Mask(VT.getSizeInBits(), 0); 11094 Mask.setBit(BitInY); 11095 V = DAG.getNode(ARMISD::BFI, dl, VT, V, X, 11096 // Confusingly, the operand is an *inverted* mask. 11097 DAG.getConstant(~Mask, dl, VT)); 11098 } 11099 11100 return V; 11101 } 11102 11103 /// PerformBRCONDCombine - Target-specific DAG combining for ARMISD::BRCOND. 11104 SDValue 11105 ARMTargetLowering::PerformBRCONDCombine(SDNode *N, SelectionDAG &DAG) const { 11106 SDValue Cmp = N->getOperand(4); 11107 if (Cmp.getOpcode() != ARMISD::CMPZ) 11108 // Only looking at NE cases. 11109 return SDValue(); 11110 11111 EVT VT = N->getValueType(0); 11112 SDLoc dl(N); 11113 SDValue LHS = Cmp.getOperand(0); 11114 SDValue RHS = Cmp.getOperand(1); 11115 SDValue Chain = N->getOperand(0); 11116 SDValue BB = N->getOperand(1); 11117 SDValue ARMcc = N->getOperand(2); 11118 ARMCC::CondCodes CC = 11119 (ARMCC::CondCodes)cast<ConstantSDNode>(ARMcc)->getZExtValue(); 11120 11121 // (brcond Chain BB ne CPSR (cmpz (and (cmov 0 1 CC CPSR Cmp) 1) 0)) 11122 // -> (brcond Chain BB CC CPSR Cmp) 11123 if (CC == ARMCC::NE && LHS.getOpcode() == ISD::AND && LHS->hasOneUse() && 11124 LHS->getOperand(0)->getOpcode() == ARMISD::CMOV && 11125 LHS->getOperand(0)->hasOneUse()) { 11126 auto *LHS00C = dyn_cast<ConstantSDNode>(LHS->getOperand(0)->getOperand(0)); 11127 auto *LHS01C = dyn_cast<ConstantSDNode>(LHS->getOperand(0)->getOperand(1)); 11128 auto *LHS1C = dyn_cast<ConstantSDNode>(LHS->getOperand(1)); 11129 auto *RHSC = dyn_cast<ConstantSDNode>(RHS); 11130 if ((LHS00C && LHS00C->getZExtValue() == 0) && 11131 (LHS01C && LHS01C->getZExtValue() == 1) && 11132 (LHS1C && LHS1C->getZExtValue() == 1) && 11133 (RHSC && RHSC->getZExtValue() == 0)) { 11134 return DAG.getNode( 11135 ARMISD::BRCOND, dl, VT, Chain, BB, LHS->getOperand(0)->getOperand(2), 11136 LHS->getOperand(0)->getOperand(3), LHS->getOperand(0)->getOperand(4)); 11137 } 11138 } 11139 11140 return SDValue(); 11141 } 11142 11143 /// PerformCMOVCombine - Target-specific DAG combining for ARMISD::CMOV. 11144 SDValue 11145 ARMTargetLowering::PerformCMOVCombine(SDNode *N, SelectionDAG &DAG) const { 11146 SDValue Cmp = N->getOperand(4); 11147 if (Cmp.getOpcode() != ARMISD::CMPZ) 11148 // Only looking at EQ and NE cases. 11149 return SDValue(); 11150 11151 EVT VT = N->getValueType(0); 11152 SDLoc dl(N); 11153 SDValue LHS = Cmp.getOperand(0); 11154 SDValue RHS = Cmp.getOperand(1); 11155 SDValue FalseVal = N->getOperand(0); 11156 SDValue TrueVal = N->getOperand(1); 11157 SDValue ARMcc = N->getOperand(2); 11158 ARMCC::CondCodes CC = 11159 (ARMCC::CondCodes)cast<ConstantSDNode>(ARMcc)->getZExtValue(); 11160 11161 // BFI is only available on V6T2+. 11162 if (!Subtarget->isThumb1Only() && Subtarget->hasV6T2Ops()) { 11163 SDValue R = PerformCMOVToBFICombine(N, DAG); 11164 if (R) 11165 return R; 11166 } 11167 11168 // Simplify 11169 // mov r1, r0 11170 // cmp r1, x 11171 // mov r0, y 11172 // moveq r0, x 11173 // to 11174 // cmp r0, x 11175 // movne r0, y 11176 // 11177 // mov r1, r0 11178 // cmp r1, x 11179 // mov r0, x 11180 // movne r0, y 11181 // to 11182 // cmp r0, x 11183 // movne r0, y 11184 /// FIXME: Turn this into a target neutral optimization? 11185 SDValue Res; 11186 if (CC == ARMCC::NE && FalseVal == RHS && FalseVal != LHS) { 11187 Res = DAG.getNode(ARMISD::CMOV, dl, VT, LHS, TrueVal, ARMcc, 11188 N->getOperand(3), Cmp); 11189 } else if (CC == ARMCC::EQ && TrueVal == RHS) { 11190 SDValue ARMcc; 11191 SDValue NewCmp = getARMCmp(LHS, RHS, ISD::SETNE, ARMcc, DAG, dl); 11192 Res = DAG.getNode(ARMISD::CMOV, dl, VT, LHS, FalseVal, ARMcc, 11193 N->getOperand(3), NewCmp); 11194 } 11195 11196 // (cmov F T ne CPSR (cmpz (cmov 0 1 CC CPSR Cmp) 0)) 11197 // -> (cmov F T CC CPSR Cmp) 11198 if (CC == ARMCC::NE && LHS.getOpcode() == ARMISD::CMOV && LHS->hasOneUse()) { 11199 auto *LHS0C = dyn_cast<ConstantSDNode>(LHS->getOperand(0)); 11200 auto *LHS1C = dyn_cast<ConstantSDNode>(LHS->getOperand(1)); 11201 auto *RHSC = dyn_cast<ConstantSDNode>(RHS); 11202 if ((LHS0C && LHS0C->getZExtValue() == 0) && 11203 (LHS1C && LHS1C->getZExtValue() == 1) && 11204 (RHSC && RHSC->getZExtValue() == 0)) { 11205 return DAG.getNode(ARMISD::CMOV, dl, VT, FalseVal, TrueVal, 11206 LHS->getOperand(2), LHS->getOperand(3), 11207 LHS->getOperand(4)); 11208 } 11209 } 11210 11211 if (Res.getNode()) { 11212 APInt KnownZero, KnownOne; 11213 DAG.computeKnownBits(SDValue(N,0), KnownZero, KnownOne); 11214 // Capture demanded bits information that would be otherwise lost. 11215 if (KnownZero == 0xfffffffe) 11216 Res = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Res, 11217 DAG.getValueType(MVT::i1)); 11218 else if (KnownZero == 0xffffff00) 11219 Res = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Res, 11220 DAG.getValueType(MVT::i8)); 11221 else if (KnownZero == 0xffff0000) 11222 Res = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Res, 11223 DAG.getValueType(MVT::i16)); 11224 } 11225 11226 return Res; 11227 } 11228 11229 SDValue ARMTargetLowering::PerformDAGCombine(SDNode *N, 11230 DAGCombinerInfo &DCI) const { 11231 switch (N->getOpcode()) { 11232 default: break; 11233 case ISD::ADDC: return PerformADDCCombine(N, DCI, Subtarget); 11234 case ISD::ADD: return PerformADDCombine(N, DCI, Subtarget); 11235 case ISD::SUB: return PerformSUBCombine(N, DCI); 11236 case ISD::MUL: return PerformMULCombine(N, DCI, Subtarget); 11237 case ISD::OR: return PerformORCombine(N, DCI, Subtarget); 11238 case ISD::XOR: return PerformXORCombine(N, DCI, Subtarget); 11239 case ISD::AND: return PerformANDCombine(N, DCI, Subtarget); 11240 case ARMISD::BFI: return PerformBFICombine(N, DCI); 11241 case ARMISD::VMOVRRD: return PerformVMOVRRDCombine(N, DCI, Subtarget); 11242 case ARMISD::VMOVDRR: return PerformVMOVDRRCombine(N, DCI.DAG); 11243 case ISD::STORE: return PerformSTORECombine(N, DCI); 11244 case ISD::BUILD_VECTOR: return PerformBUILD_VECTORCombine(N, DCI, Subtarget); 11245 case ISD::INSERT_VECTOR_ELT: return PerformInsertEltCombine(N, DCI); 11246 case ISD::VECTOR_SHUFFLE: return PerformVECTOR_SHUFFLECombine(N, DCI.DAG); 11247 case ARMISD::VDUPLANE: return PerformVDUPLANECombine(N, DCI); 11248 case ISD::FP_TO_SINT: 11249 case ISD::FP_TO_UINT: 11250 return PerformVCVTCombine(N, DCI.DAG, Subtarget); 11251 case ISD::FDIV: 11252 return PerformVDIVCombine(N, DCI.DAG, Subtarget); 11253 case ISD::INTRINSIC_WO_CHAIN: return PerformIntrinsicCombine(N, DCI.DAG); 11254 case ISD::SHL: 11255 case ISD::SRA: 11256 case ISD::SRL: return PerformShiftCombine(N, DCI.DAG, Subtarget); 11257 case ISD::SIGN_EXTEND: 11258 case ISD::ZERO_EXTEND: 11259 case ISD::ANY_EXTEND: return PerformExtendCombine(N, DCI.DAG, Subtarget); 11260 case ARMISD::CMOV: return PerformCMOVCombine(N, DCI.DAG); 11261 case ARMISD::BRCOND: return PerformBRCONDCombine(N, DCI.DAG); 11262 case ISD::LOAD: return PerformLOADCombine(N, DCI); 11263 case ARMISD::VLD2DUP: 11264 case ARMISD::VLD3DUP: 11265 case ARMISD::VLD4DUP: 11266 return PerformVLDCombine(N, DCI); 11267 case ARMISD::BUILD_VECTOR: 11268 return PerformARMBUILD_VECTORCombine(N, DCI); 11269 case ISD::INTRINSIC_VOID: 11270 case ISD::INTRINSIC_W_CHAIN: 11271 switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) { 11272 case Intrinsic::arm_neon_vld1: 11273 case Intrinsic::arm_neon_vld2: 11274 case Intrinsic::arm_neon_vld3: 11275 case Intrinsic::arm_neon_vld4: 11276 case Intrinsic::arm_neon_vld2lane: 11277 case Intrinsic::arm_neon_vld3lane: 11278 case Intrinsic::arm_neon_vld4lane: 11279 case Intrinsic::arm_neon_vst1: 11280 case Intrinsic::arm_neon_vst2: 11281 case Intrinsic::arm_neon_vst3: 11282 case Intrinsic::arm_neon_vst4: 11283 case Intrinsic::arm_neon_vst2lane: 11284 case Intrinsic::arm_neon_vst3lane: 11285 case Intrinsic::arm_neon_vst4lane: 11286 return PerformVLDCombine(N, DCI); 11287 default: break; 11288 } 11289 break; 11290 } 11291 return SDValue(); 11292 } 11293 11294 bool ARMTargetLowering::isDesirableToTransformToIntegerOp(unsigned Opc, 11295 EVT VT) const { 11296 return (VT == MVT::f32) && (Opc == ISD::LOAD || Opc == ISD::STORE); 11297 } 11298 11299 bool ARMTargetLowering::allowsMisalignedMemoryAccesses(EVT VT, 11300 unsigned, 11301 unsigned, 11302 bool *Fast) const { 11303 // The AllowsUnaliged flag models the SCTLR.A setting in ARM cpus 11304 bool AllowsUnaligned = Subtarget->allowsUnalignedMem(); 11305 11306 switch (VT.getSimpleVT().SimpleTy) { 11307 default: 11308 return false; 11309 case MVT::i8: 11310 case MVT::i16: 11311 case MVT::i32: { 11312 // Unaligned access can use (for example) LRDB, LRDH, LDR 11313 if (AllowsUnaligned) { 11314 if (Fast) 11315 *Fast = Subtarget->hasV7Ops(); 11316 return true; 11317 } 11318 return false; 11319 } 11320 case MVT::f64: 11321 case MVT::v2f64: { 11322 // For any little-endian targets with neon, we can support unaligned ld/st 11323 // of D and Q (e.g. {D0,D1}) registers by using vld1.i8/vst1.i8. 11324 // A big-endian target may also explicitly support unaligned accesses 11325 if (Subtarget->hasNEON() && (AllowsUnaligned || Subtarget->isLittle())) { 11326 if (Fast) 11327 *Fast = true; 11328 return true; 11329 } 11330 return false; 11331 } 11332 } 11333 } 11334 11335 static bool memOpAlign(unsigned DstAlign, unsigned SrcAlign, 11336 unsigned AlignCheck) { 11337 return ((SrcAlign == 0 || SrcAlign % AlignCheck == 0) && 11338 (DstAlign == 0 || DstAlign % AlignCheck == 0)); 11339 } 11340 11341 EVT ARMTargetLowering::getOptimalMemOpType(uint64_t Size, 11342 unsigned DstAlign, unsigned SrcAlign, 11343 bool IsMemset, bool ZeroMemset, 11344 bool MemcpyStrSrc, 11345 MachineFunction &MF) const { 11346 const Function *F = MF.getFunction(); 11347 11348 // See if we can use NEON instructions for this... 11349 if ((!IsMemset || ZeroMemset) && Subtarget->hasNEON() && 11350 !F->hasFnAttribute(Attribute::NoImplicitFloat)) { 11351 bool Fast; 11352 if (Size >= 16 && 11353 (memOpAlign(SrcAlign, DstAlign, 16) || 11354 (allowsMisalignedMemoryAccesses(MVT::v2f64, 0, 1, &Fast) && Fast))) { 11355 return MVT::v2f64; 11356 } else if (Size >= 8 && 11357 (memOpAlign(SrcAlign, DstAlign, 8) || 11358 (allowsMisalignedMemoryAccesses(MVT::f64, 0, 1, &Fast) && 11359 Fast))) { 11360 return MVT::f64; 11361 } 11362 } 11363 11364 // Lowering to i32/i16 if the size permits. 11365 if (Size >= 4) 11366 return MVT::i32; 11367 else if (Size >= 2) 11368 return MVT::i16; 11369 11370 // Let the target-independent logic figure it out. 11371 return MVT::Other; 11372 } 11373 11374 bool ARMTargetLowering::isZExtFree(SDValue Val, EVT VT2) const { 11375 if (Val.getOpcode() != ISD::LOAD) 11376 return false; 11377 11378 EVT VT1 = Val.getValueType(); 11379 if (!VT1.isSimple() || !VT1.isInteger() || 11380 !VT2.isSimple() || !VT2.isInteger()) 11381 return false; 11382 11383 switch (VT1.getSimpleVT().SimpleTy) { 11384 default: break; 11385 case MVT::i1: 11386 case MVT::i8: 11387 case MVT::i16: 11388 // 8-bit and 16-bit loads implicitly zero-extend to 32-bits. 11389 return true; 11390 } 11391 11392 return false; 11393 } 11394 11395 bool ARMTargetLowering::isVectorLoadExtDesirable(SDValue ExtVal) const { 11396 EVT VT = ExtVal.getValueType(); 11397 11398 if (!isTypeLegal(VT)) 11399 return false; 11400 11401 // Don't create a loadext if we can fold the extension into a wide/long 11402 // instruction. 11403 // If there's more than one user instruction, the loadext is desirable no 11404 // matter what. There can be two uses by the same instruction. 11405 if (ExtVal->use_empty() || 11406 !ExtVal->use_begin()->isOnlyUserOf(ExtVal.getNode())) 11407 return true; 11408 11409 SDNode *U = *ExtVal->use_begin(); 11410 if ((U->getOpcode() == ISD::ADD || U->getOpcode() == ISD::SUB || 11411 U->getOpcode() == ISD::SHL || U->getOpcode() == ARMISD::VSHL)) 11412 return false; 11413 11414 return true; 11415 } 11416 11417 bool ARMTargetLowering::allowTruncateForTailCall(Type *Ty1, Type *Ty2) const { 11418 if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy()) 11419 return false; 11420 11421 if (!isTypeLegal(EVT::getEVT(Ty1))) 11422 return false; 11423 11424 assert(Ty1->getPrimitiveSizeInBits() <= 64 && "i128 is probably not a noop"); 11425 11426 // Assuming the caller doesn't have a zeroext or signext return parameter, 11427 // truncation all the way down to i1 is valid. 11428 return true; 11429 } 11430 11431 11432 static bool isLegalT1AddressImmediate(int64_t V, EVT VT) { 11433 if (V < 0) 11434 return false; 11435 11436 unsigned Scale = 1; 11437 switch (VT.getSimpleVT().SimpleTy) { 11438 default: return false; 11439 case MVT::i1: 11440 case MVT::i8: 11441 // Scale == 1; 11442 break; 11443 case MVT::i16: 11444 // Scale == 2; 11445 Scale = 2; 11446 break; 11447 case MVT::i32: 11448 // Scale == 4; 11449 Scale = 4; 11450 break; 11451 } 11452 11453 if ((V & (Scale - 1)) != 0) 11454 return false; 11455 V /= Scale; 11456 return V == (V & ((1LL << 5) - 1)); 11457 } 11458 11459 static bool isLegalT2AddressImmediate(int64_t V, EVT VT, 11460 const ARMSubtarget *Subtarget) { 11461 bool isNeg = false; 11462 if (V < 0) { 11463 isNeg = true; 11464 V = - V; 11465 } 11466 11467 switch (VT.getSimpleVT().SimpleTy) { 11468 default: return false; 11469 case MVT::i1: 11470 case MVT::i8: 11471 case MVT::i16: 11472 case MVT::i32: 11473 // + imm12 or - imm8 11474 if (isNeg) 11475 return V == (V & ((1LL << 8) - 1)); 11476 return V == (V & ((1LL << 12) - 1)); 11477 case MVT::f32: 11478 case MVT::f64: 11479 // Same as ARM mode. FIXME: NEON? 11480 if (!Subtarget->hasVFP2()) 11481 return false; 11482 if ((V & 3) != 0) 11483 return false; 11484 V >>= 2; 11485 return V == (V & ((1LL << 8) - 1)); 11486 } 11487 } 11488 11489 /// isLegalAddressImmediate - Return true if the integer value can be used 11490 /// as the offset of the target addressing mode for load / store of the 11491 /// given type. 11492 static bool isLegalAddressImmediate(int64_t V, EVT VT, 11493 const ARMSubtarget *Subtarget) { 11494 if (V == 0) 11495 return true; 11496 11497 if (!VT.isSimple()) 11498 return false; 11499 11500 if (Subtarget->isThumb1Only()) 11501 return isLegalT1AddressImmediate(V, VT); 11502 else if (Subtarget->isThumb2()) 11503 return isLegalT2AddressImmediate(V, VT, Subtarget); 11504 11505 // ARM mode. 11506 if (V < 0) 11507 V = - V; 11508 switch (VT.getSimpleVT().SimpleTy) { 11509 default: return false; 11510 case MVT::i1: 11511 case MVT::i8: 11512 case MVT::i32: 11513 // +- imm12 11514 return V == (V & ((1LL << 12) - 1)); 11515 case MVT::i16: 11516 // +- imm8 11517 return V == (V & ((1LL << 8) - 1)); 11518 case MVT::f32: 11519 case MVT::f64: 11520 if (!Subtarget->hasVFP2()) // FIXME: NEON? 11521 return false; 11522 if ((V & 3) != 0) 11523 return false; 11524 V >>= 2; 11525 return V == (V & ((1LL << 8) - 1)); 11526 } 11527 } 11528 11529 bool ARMTargetLowering::isLegalT2ScaledAddressingMode(const AddrMode &AM, 11530 EVT VT) const { 11531 int Scale = AM.Scale; 11532 if (Scale < 0) 11533 return false; 11534 11535 switch (VT.getSimpleVT().SimpleTy) { 11536 default: return false; 11537 case MVT::i1: 11538 case MVT::i8: 11539 case MVT::i16: 11540 case MVT::i32: 11541 if (Scale == 1) 11542 return true; 11543 // r + r << imm 11544 Scale = Scale & ~1; 11545 return Scale == 2 || Scale == 4 || Scale == 8; 11546 case MVT::i64: 11547 // r + r 11548 if (((unsigned)AM.HasBaseReg + Scale) <= 2) 11549 return true; 11550 return false; 11551 case MVT::isVoid: 11552 // Note, we allow "void" uses (basically, uses that aren't loads or 11553 // stores), because arm allows folding a scale into many arithmetic 11554 // operations. This should be made more precise and revisited later. 11555 11556 // Allow r << imm, but the imm has to be a multiple of two. 11557 if (Scale & 1) return false; 11558 return isPowerOf2_32(Scale); 11559 } 11560 } 11561 11562 /// isLegalAddressingMode - Return true if the addressing mode represented 11563 /// by AM is legal for this target, for a load/store of the specified type. 11564 bool ARMTargetLowering::isLegalAddressingMode(const DataLayout &DL, 11565 const AddrMode &AM, Type *Ty, 11566 unsigned AS) const { 11567 EVT VT = getValueType(DL, Ty, true); 11568 if (!isLegalAddressImmediate(AM.BaseOffs, VT, Subtarget)) 11569 return false; 11570 11571 // Can never fold addr of global into load/store. 11572 if (AM.BaseGV) 11573 return false; 11574 11575 switch (AM.Scale) { 11576 case 0: // no scale reg, must be "r+i" or "r", or "i". 11577 break; 11578 case 1: 11579 if (Subtarget->isThumb1Only()) 11580 return false; 11581 LLVM_FALLTHROUGH; 11582 default: 11583 // ARM doesn't support any R+R*scale+imm addr modes. 11584 if (AM.BaseOffs) 11585 return false; 11586 11587 if (!VT.isSimple()) 11588 return false; 11589 11590 if (Subtarget->isThumb2()) 11591 return isLegalT2ScaledAddressingMode(AM, VT); 11592 11593 int Scale = AM.Scale; 11594 switch (VT.getSimpleVT().SimpleTy) { 11595 default: return false; 11596 case MVT::i1: 11597 case MVT::i8: 11598 case MVT::i32: 11599 if (Scale < 0) Scale = -Scale; 11600 if (Scale == 1) 11601 return true; 11602 // r + r << imm 11603 return isPowerOf2_32(Scale & ~1); 11604 case MVT::i16: 11605 case MVT::i64: 11606 // r + r 11607 if (((unsigned)AM.HasBaseReg + Scale) <= 2) 11608 return true; 11609 return false; 11610 11611 case MVT::isVoid: 11612 // Note, we allow "void" uses (basically, uses that aren't loads or 11613 // stores), because arm allows folding a scale into many arithmetic 11614 // operations. This should be made more precise and revisited later. 11615 11616 // Allow r << imm, but the imm has to be a multiple of two. 11617 if (Scale & 1) return false; 11618 return isPowerOf2_32(Scale); 11619 } 11620 } 11621 return true; 11622 } 11623 11624 /// isLegalICmpImmediate - Return true if the specified immediate is legal 11625 /// icmp immediate, that is the target has icmp instructions which can compare 11626 /// a register against the immediate without having to materialize the 11627 /// immediate into a register. 11628 bool ARMTargetLowering::isLegalICmpImmediate(int64_t Imm) const { 11629 // Thumb2 and ARM modes can use cmn for negative immediates. 11630 if (!Subtarget->isThumb()) 11631 return ARM_AM::getSOImmVal(std::abs(Imm)) != -1; 11632 if (Subtarget->isThumb2()) 11633 return ARM_AM::getT2SOImmVal(std::abs(Imm)) != -1; 11634 // Thumb1 doesn't have cmn, and only 8-bit immediates. 11635 return Imm >= 0 && Imm <= 255; 11636 } 11637 11638 /// isLegalAddImmediate - Return true if the specified immediate is a legal add 11639 /// *or sub* immediate, that is the target has add or sub instructions which can 11640 /// add a register with the immediate without having to materialize the 11641 /// immediate into a register. 11642 bool ARMTargetLowering::isLegalAddImmediate(int64_t Imm) const { 11643 // Same encoding for add/sub, just flip the sign. 11644 int64_t AbsImm = std::abs(Imm); 11645 if (!Subtarget->isThumb()) 11646 return ARM_AM::getSOImmVal(AbsImm) != -1; 11647 if (Subtarget->isThumb2()) 11648 return ARM_AM::getT2SOImmVal(AbsImm) != -1; 11649 // Thumb1 only has 8-bit unsigned immediate. 11650 return AbsImm >= 0 && AbsImm <= 255; 11651 } 11652 11653 static bool getARMIndexedAddressParts(SDNode *Ptr, EVT VT, 11654 bool isSEXTLoad, SDValue &Base, 11655 SDValue &Offset, bool &isInc, 11656 SelectionDAG &DAG) { 11657 if (Ptr->getOpcode() != ISD::ADD && Ptr->getOpcode() != ISD::SUB) 11658 return false; 11659 11660 if (VT == MVT::i16 || ((VT == MVT::i8 || VT == MVT::i1) && isSEXTLoad)) { 11661 // AddressingMode 3 11662 Base = Ptr->getOperand(0); 11663 if (ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(Ptr->getOperand(1))) { 11664 int RHSC = (int)RHS->getZExtValue(); 11665 if (RHSC < 0 && RHSC > -256) { 11666 assert(Ptr->getOpcode() == ISD::ADD); 11667 isInc = false; 11668 Offset = DAG.getConstant(-RHSC, SDLoc(Ptr), RHS->getValueType(0)); 11669 return true; 11670 } 11671 } 11672 isInc = (Ptr->getOpcode() == ISD::ADD); 11673 Offset = Ptr->getOperand(1); 11674 return true; 11675 } else if (VT == MVT::i32 || VT == MVT::i8 || VT == MVT::i1) { 11676 // AddressingMode 2 11677 if (ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(Ptr->getOperand(1))) { 11678 int RHSC = (int)RHS->getZExtValue(); 11679 if (RHSC < 0 && RHSC > -0x1000) { 11680 assert(Ptr->getOpcode() == ISD::ADD); 11681 isInc = false; 11682 Offset = DAG.getConstant(-RHSC, SDLoc(Ptr), RHS->getValueType(0)); 11683 Base = Ptr->getOperand(0); 11684 return true; 11685 } 11686 } 11687 11688 if (Ptr->getOpcode() == ISD::ADD) { 11689 isInc = true; 11690 ARM_AM::ShiftOpc ShOpcVal= 11691 ARM_AM::getShiftOpcForNode(Ptr->getOperand(0).getOpcode()); 11692 if (ShOpcVal != ARM_AM::no_shift) { 11693 Base = Ptr->getOperand(1); 11694 Offset = Ptr->getOperand(0); 11695 } else { 11696 Base = Ptr->getOperand(0); 11697 Offset = Ptr->getOperand(1); 11698 } 11699 return true; 11700 } 11701 11702 isInc = (Ptr->getOpcode() == ISD::ADD); 11703 Base = Ptr->getOperand(0); 11704 Offset = Ptr->getOperand(1); 11705 return true; 11706 } 11707 11708 // FIXME: Use VLDM / VSTM to emulate indexed FP load / store. 11709 return false; 11710 } 11711 11712 static bool getT2IndexedAddressParts(SDNode *Ptr, EVT VT, 11713 bool isSEXTLoad, SDValue &Base, 11714 SDValue &Offset, bool &isInc, 11715 SelectionDAG &DAG) { 11716 if (Ptr->getOpcode() != ISD::ADD && Ptr->getOpcode() != ISD::SUB) 11717 return false; 11718 11719 Base = Ptr->getOperand(0); 11720 if (ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(Ptr->getOperand(1))) { 11721 int RHSC = (int)RHS->getZExtValue(); 11722 if (RHSC < 0 && RHSC > -0x100) { // 8 bits. 11723 assert(Ptr->getOpcode() == ISD::ADD); 11724 isInc = false; 11725 Offset = DAG.getConstant(-RHSC, SDLoc(Ptr), RHS->getValueType(0)); 11726 return true; 11727 } else if (RHSC > 0 && RHSC < 0x100) { // 8 bit, no zero. 11728 isInc = Ptr->getOpcode() == ISD::ADD; 11729 Offset = DAG.getConstant(RHSC, SDLoc(Ptr), RHS->getValueType(0)); 11730 return true; 11731 } 11732 } 11733 11734 return false; 11735 } 11736 11737 /// getPreIndexedAddressParts - returns true by value, base pointer and 11738 /// offset pointer and addressing mode by reference if the node's address 11739 /// can be legally represented as pre-indexed load / store address. 11740 bool 11741 ARMTargetLowering::getPreIndexedAddressParts(SDNode *N, SDValue &Base, 11742 SDValue &Offset, 11743 ISD::MemIndexedMode &AM, 11744 SelectionDAG &DAG) const { 11745 if (Subtarget->isThumb1Only()) 11746 return false; 11747 11748 EVT VT; 11749 SDValue Ptr; 11750 bool isSEXTLoad = false; 11751 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) { 11752 Ptr = LD->getBasePtr(); 11753 VT = LD->getMemoryVT(); 11754 isSEXTLoad = LD->getExtensionType() == ISD::SEXTLOAD; 11755 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) { 11756 Ptr = ST->getBasePtr(); 11757 VT = ST->getMemoryVT(); 11758 } else 11759 return false; 11760 11761 bool isInc; 11762 bool isLegal = false; 11763 if (Subtarget->isThumb2()) 11764 isLegal = getT2IndexedAddressParts(Ptr.getNode(), VT, isSEXTLoad, Base, 11765 Offset, isInc, DAG); 11766 else 11767 isLegal = getARMIndexedAddressParts(Ptr.getNode(), VT, isSEXTLoad, Base, 11768 Offset, isInc, DAG); 11769 if (!isLegal) 11770 return false; 11771 11772 AM = isInc ? ISD::PRE_INC : ISD::PRE_DEC; 11773 return true; 11774 } 11775 11776 /// getPostIndexedAddressParts - returns true by value, base pointer and 11777 /// offset pointer and addressing mode by reference if this node can be 11778 /// combined with a load / store to form a post-indexed load / store. 11779 bool ARMTargetLowering::getPostIndexedAddressParts(SDNode *N, SDNode *Op, 11780 SDValue &Base, 11781 SDValue &Offset, 11782 ISD::MemIndexedMode &AM, 11783 SelectionDAG &DAG) const { 11784 EVT VT; 11785 SDValue Ptr; 11786 bool isSEXTLoad = false, isNonExt; 11787 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) { 11788 VT = LD->getMemoryVT(); 11789 Ptr = LD->getBasePtr(); 11790 isSEXTLoad = LD->getExtensionType() == ISD::SEXTLOAD; 11791 isNonExt = LD->getExtensionType() == ISD::NON_EXTLOAD; 11792 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) { 11793 VT = ST->getMemoryVT(); 11794 Ptr = ST->getBasePtr(); 11795 isNonExt = !ST->isTruncatingStore(); 11796 } else 11797 return false; 11798 11799 if (Subtarget->isThumb1Only()) { 11800 // Thumb-1 can do a limited post-inc load or store as an updating LDM. It 11801 // must be non-extending/truncating, i32, with an offset of 4. 11802 assert(Op->getValueType(0) == MVT::i32 && "Non-i32 post-inc op?!"); 11803 if (Op->getOpcode() != ISD::ADD || !isNonExt) 11804 return false; 11805 auto *RHS = dyn_cast<ConstantSDNode>(Op->getOperand(1)); 11806 if (!RHS || RHS->getZExtValue() != 4) 11807 return false; 11808 11809 Offset = Op->getOperand(1); 11810 Base = Op->getOperand(0); 11811 AM = ISD::POST_INC; 11812 return true; 11813 } 11814 11815 bool isInc; 11816 bool isLegal = false; 11817 if (Subtarget->isThumb2()) 11818 isLegal = getT2IndexedAddressParts(Op, VT, isSEXTLoad, Base, Offset, 11819 isInc, DAG); 11820 else 11821 isLegal = getARMIndexedAddressParts(Op, VT, isSEXTLoad, Base, Offset, 11822 isInc, DAG); 11823 if (!isLegal) 11824 return false; 11825 11826 if (Ptr != Base) { 11827 // Swap base ptr and offset to catch more post-index load / store when 11828 // it's legal. In Thumb2 mode, offset must be an immediate. 11829 if (Ptr == Offset && Op->getOpcode() == ISD::ADD && 11830 !Subtarget->isThumb2()) 11831 std::swap(Base, Offset); 11832 11833 // Post-indexed load / store update the base pointer. 11834 if (Ptr != Base) 11835 return false; 11836 } 11837 11838 AM = isInc ? ISD::POST_INC : ISD::POST_DEC; 11839 return true; 11840 } 11841 11842 void ARMTargetLowering::computeKnownBitsForTargetNode(const SDValue Op, 11843 APInt &KnownZero, 11844 APInt &KnownOne, 11845 const SelectionDAG &DAG, 11846 unsigned Depth) const { 11847 unsigned BitWidth = KnownOne.getBitWidth(); 11848 KnownZero = KnownOne = APInt(BitWidth, 0); 11849 switch (Op.getOpcode()) { 11850 default: break; 11851 case ARMISD::ADDC: 11852 case ARMISD::ADDE: 11853 case ARMISD::SUBC: 11854 case ARMISD::SUBE: 11855 // These nodes' second result is a boolean 11856 if (Op.getResNo() == 0) 11857 break; 11858 KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - 1); 11859 break; 11860 case ARMISD::CMOV: { 11861 // Bits are known zero/one if known on the LHS and RHS. 11862 DAG.computeKnownBits(Op.getOperand(0), KnownZero, KnownOne, Depth+1); 11863 if (KnownZero == 0 && KnownOne == 0) return; 11864 11865 APInt KnownZeroRHS, KnownOneRHS; 11866 DAG.computeKnownBits(Op.getOperand(1), KnownZeroRHS, KnownOneRHS, Depth+1); 11867 KnownZero &= KnownZeroRHS; 11868 KnownOne &= KnownOneRHS; 11869 return; 11870 } 11871 case ISD::INTRINSIC_W_CHAIN: { 11872 ConstantSDNode *CN = cast<ConstantSDNode>(Op->getOperand(1)); 11873 Intrinsic::ID IntID = static_cast<Intrinsic::ID>(CN->getZExtValue()); 11874 switch (IntID) { 11875 default: return; 11876 case Intrinsic::arm_ldaex: 11877 case Intrinsic::arm_ldrex: { 11878 EVT VT = cast<MemIntrinsicSDNode>(Op)->getMemoryVT(); 11879 unsigned MemBits = VT.getScalarType().getSizeInBits(); 11880 KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - MemBits); 11881 return; 11882 } 11883 } 11884 } 11885 } 11886 } 11887 11888 //===----------------------------------------------------------------------===// 11889 // ARM Inline Assembly Support 11890 //===----------------------------------------------------------------------===// 11891 11892 bool ARMTargetLowering::ExpandInlineAsm(CallInst *CI) const { 11893 // Looking for "rev" which is V6+. 11894 if (!Subtarget->hasV6Ops()) 11895 return false; 11896 11897 InlineAsm *IA = cast<InlineAsm>(CI->getCalledValue()); 11898 std::string AsmStr = IA->getAsmString(); 11899 SmallVector<StringRef, 4> AsmPieces; 11900 SplitString(AsmStr, AsmPieces, ";\n"); 11901 11902 switch (AsmPieces.size()) { 11903 default: return false; 11904 case 1: 11905 AsmStr = AsmPieces[0]; 11906 AsmPieces.clear(); 11907 SplitString(AsmStr, AsmPieces, " \t,"); 11908 11909 // rev $0, $1 11910 if (AsmPieces.size() == 3 && 11911 AsmPieces[0] == "rev" && AsmPieces[1] == "$0" && AsmPieces[2] == "$1" && 11912 IA->getConstraintString().compare(0, 4, "=l,l") == 0) { 11913 IntegerType *Ty = dyn_cast<IntegerType>(CI->getType()); 11914 if (Ty && Ty->getBitWidth() == 32) 11915 return IntrinsicLowering::LowerToByteSwap(CI); 11916 } 11917 break; 11918 } 11919 11920 return false; 11921 } 11922 11923 const char *ARMTargetLowering::LowerXConstraint(EVT ConstraintVT) const { 11924 // At this point, we have to lower this constraint to something else, so we 11925 // lower it to an "r" or "w". However, by doing this we will force the result 11926 // to be in register, while the X constraint is much more permissive. 11927 // 11928 // Although we are correct (we are free to emit anything, without 11929 // constraints), we might break use cases that would expect us to be more 11930 // efficient and emit something else. 11931 if (!Subtarget->hasVFP2()) 11932 return "r"; 11933 if (ConstraintVT.isFloatingPoint()) 11934 return "w"; 11935 if (ConstraintVT.isVector() && Subtarget->hasNEON() && 11936 (ConstraintVT.getSizeInBits() == 64 || 11937 ConstraintVT.getSizeInBits() == 128)) 11938 return "w"; 11939 11940 return "r"; 11941 } 11942 11943 /// getConstraintType - Given a constraint letter, return the type of 11944 /// constraint it is for this target. 11945 ARMTargetLowering::ConstraintType 11946 ARMTargetLowering::getConstraintType(StringRef Constraint) const { 11947 if (Constraint.size() == 1) { 11948 switch (Constraint[0]) { 11949 default: break; 11950 case 'l': return C_RegisterClass; 11951 case 'w': return C_RegisterClass; 11952 case 'h': return C_RegisterClass; 11953 case 'x': return C_RegisterClass; 11954 case 't': return C_RegisterClass; 11955 case 'j': return C_Other; // Constant for movw. 11956 // An address with a single base register. Due to the way we 11957 // currently handle addresses it is the same as an 'r' memory constraint. 11958 case 'Q': return C_Memory; 11959 } 11960 } else if (Constraint.size() == 2) { 11961 switch (Constraint[0]) { 11962 default: break; 11963 // All 'U+' constraints are addresses. 11964 case 'U': return C_Memory; 11965 } 11966 } 11967 return TargetLowering::getConstraintType(Constraint); 11968 } 11969 11970 /// Examine constraint type and operand type and determine a weight value. 11971 /// This object must already have been set up with the operand type 11972 /// and the current alternative constraint selected. 11973 TargetLowering::ConstraintWeight 11974 ARMTargetLowering::getSingleConstraintMatchWeight( 11975 AsmOperandInfo &info, const char *constraint) const { 11976 ConstraintWeight weight = CW_Invalid; 11977 Value *CallOperandVal = info.CallOperandVal; 11978 // If we don't have a value, we can't do a match, 11979 // but allow it at the lowest weight. 11980 if (!CallOperandVal) 11981 return CW_Default; 11982 Type *type = CallOperandVal->getType(); 11983 // Look at the constraint type. 11984 switch (*constraint) { 11985 default: 11986 weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint); 11987 break; 11988 case 'l': 11989 if (type->isIntegerTy()) { 11990 if (Subtarget->isThumb()) 11991 weight = CW_SpecificReg; 11992 else 11993 weight = CW_Register; 11994 } 11995 break; 11996 case 'w': 11997 if (type->isFloatingPointTy()) 11998 weight = CW_Register; 11999 break; 12000 } 12001 return weight; 12002 } 12003 12004 typedef std::pair<unsigned, const TargetRegisterClass*> RCPair; 12005 RCPair ARMTargetLowering::getRegForInlineAsmConstraint( 12006 const TargetRegisterInfo *TRI, StringRef Constraint, MVT VT) const { 12007 if (Constraint.size() == 1) { 12008 // GCC ARM Constraint Letters 12009 switch (Constraint[0]) { 12010 case 'l': // Low regs or general regs. 12011 if (Subtarget->isThumb()) 12012 return RCPair(0U, &ARM::tGPRRegClass); 12013 return RCPair(0U, &ARM::GPRRegClass); 12014 case 'h': // High regs or no regs. 12015 if (Subtarget->isThumb()) 12016 return RCPair(0U, &ARM::hGPRRegClass); 12017 break; 12018 case 'r': 12019 if (Subtarget->isThumb1Only()) 12020 return RCPair(0U, &ARM::tGPRRegClass); 12021 return RCPair(0U, &ARM::GPRRegClass); 12022 case 'w': 12023 if (VT == MVT::Other) 12024 break; 12025 if (VT == MVT::f32) 12026 return RCPair(0U, &ARM::SPRRegClass); 12027 if (VT.getSizeInBits() == 64) 12028 return RCPair(0U, &ARM::DPRRegClass); 12029 if (VT.getSizeInBits() == 128) 12030 return RCPair(0U, &ARM::QPRRegClass); 12031 break; 12032 case 'x': 12033 if (VT == MVT::Other) 12034 break; 12035 if (VT == MVT::f32) 12036 return RCPair(0U, &ARM::SPR_8RegClass); 12037 if (VT.getSizeInBits() == 64) 12038 return RCPair(0U, &ARM::DPR_8RegClass); 12039 if (VT.getSizeInBits() == 128) 12040 return RCPair(0U, &ARM::QPR_8RegClass); 12041 break; 12042 case 't': 12043 if (VT == MVT::f32) 12044 return RCPair(0U, &ARM::SPRRegClass); 12045 break; 12046 } 12047 } 12048 if (StringRef("{cc}").equals_lower(Constraint)) 12049 return std::make_pair(unsigned(ARM::CPSR), &ARM::CCRRegClass); 12050 12051 return TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT); 12052 } 12053 12054 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops 12055 /// vector. If it is invalid, don't add anything to Ops. 12056 void ARMTargetLowering::LowerAsmOperandForConstraint(SDValue Op, 12057 std::string &Constraint, 12058 std::vector<SDValue>&Ops, 12059 SelectionDAG &DAG) const { 12060 SDValue Result; 12061 12062 // Currently only support length 1 constraints. 12063 if (Constraint.length() != 1) return; 12064 12065 char ConstraintLetter = Constraint[0]; 12066 switch (ConstraintLetter) { 12067 default: break; 12068 case 'j': 12069 case 'I': case 'J': case 'K': case 'L': 12070 case 'M': case 'N': case 'O': 12071 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op); 12072 if (!C) 12073 return; 12074 12075 int64_t CVal64 = C->getSExtValue(); 12076 int CVal = (int) CVal64; 12077 // None of these constraints allow values larger than 32 bits. Check 12078 // that the value fits in an int. 12079 if (CVal != CVal64) 12080 return; 12081 12082 switch (ConstraintLetter) { 12083 case 'j': 12084 // Constant suitable for movw, must be between 0 and 12085 // 65535. 12086 if (Subtarget->hasV6T2Ops()) 12087 if (CVal >= 0 && CVal <= 65535) 12088 break; 12089 return; 12090 case 'I': 12091 if (Subtarget->isThumb1Only()) { 12092 // This must be a constant between 0 and 255, for ADD 12093 // immediates. 12094 if (CVal >= 0 && CVal <= 255) 12095 break; 12096 } else if (Subtarget->isThumb2()) { 12097 // A constant that can be used as an immediate value in a 12098 // data-processing instruction. 12099 if (ARM_AM::getT2SOImmVal(CVal) != -1) 12100 break; 12101 } else { 12102 // A constant that can be used as an immediate value in a 12103 // data-processing instruction. 12104 if (ARM_AM::getSOImmVal(CVal) != -1) 12105 break; 12106 } 12107 return; 12108 12109 case 'J': 12110 if (Subtarget->isThumb1Only()) { 12111 // This must be a constant between -255 and -1, for negated ADD 12112 // immediates. This can be used in GCC with an "n" modifier that 12113 // prints the negated value, for use with SUB instructions. It is 12114 // not useful otherwise but is implemented for compatibility. 12115 if (CVal >= -255 && CVal <= -1) 12116 break; 12117 } else { 12118 // This must be a constant between -4095 and 4095. It is not clear 12119 // what this constraint is intended for. Implemented for 12120 // compatibility with GCC. 12121 if (CVal >= -4095 && CVal <= 4095) 12122 break; 12123 } 12124 return; 12125 12126 case 'K': 12127 if (Subtarget->isThumb1Only()) { 12128 // A 32-bit value where only one byte has a nonzero value. Exclude 12129 // zero to match GCC. This constraint is used by GCC internally for 12130 // constants that can be loaded with a move/shift combination. 12131 // It is not useful otherwise but is implemented for compatibility. 12132 if (CVal != 0 && ARM_AM::isThumbImmShiftedVal(CVal)) 12133 break; 12134 } else if (Subtarget->isThumb2()) { 12135 // A constant whose bitwise inverse can be used as an immediate 12136 // value in a data-processing instruction. This can be used in GCC 12137 // with a "B" modifier that prints the inverted value, for use with 12138 // BIC and MVN instructions. It is not useful otherwise but is 12139 // implemented for compatibility. 12140 if (ARM_AM::getT2SOImmVal(~CVal) != -1) 12141 break; 12142 } else { 12143 // A constant whose bitwise inverse can be used as an immediate 12144 // value in a data-processing instruction. This can be used in GCC 12145 // with a "B" modifier that prints the inverted value, for use with 12146 // BIC and MVN instructions. It is not useful otherwise but is 12147 // implemented for compatibility. 12148 if (ARM_AM::getSOImmVal(~CVal) != -1) 12149 break; 12150 } 12151 return; 12152 12153 case 'L': 12154 if (Subtarget->isThumb1Only()) { 12155 // This must be a constant between -7 and 7, 12156 // for 3-operand ADD/SUB immediate instructions. 12157 if (CVal >= -7 && CVal < 7) 12158 break; 12159 } else if (Subtarget->isThumb2()) { 12160 // A constant whose negation can be used as an immediate value in a 12161 // data-processing instruction. This can be used in GCC with an "n" 12162 // modifier that prints the negated value, for use with SUB 12163 // instructions. It is not useful otherwise but is implemented for 12164 // compatibility. 12165 if (ARM_AM::getT2SOImmVal(-CVal) != -1) 12166 break; 12167 } else { 12168 // A constant whose negation can be used as an immediate value in a 12169 // data-processing instruction. This can be used in GCC with an "n" 12170 // modifier that prints the negated value, for use with SUB 12171 // instructions. It is not useful otherwise but is implemented for 12172 // compatibility. 12173 if (ARM_AM::getSOImmVal(-CVal) != -1) 12174 break; 12175 } 12176 return; 12177 12178 case 'M': 12179 if (Subtarget->isThumb1Only()) { 12180 // This must be a multiple of 4 between 0 and 1020, for 12181 // ADD sp + immediate. 12182 if ((CVal >= 0 && CVal <= 1020) && ((CVal & 3) == 0)) 12183 break; 12184 } else { 12185 // A power of two or a constant between 0 and 32. This is used in 12186 // GCC for the shift amount on shifted register operands, but it is 12187 // useful in general for any shift amounts. 12188 if ((CVal >= 0 && CVal <= 32) || ((CVal & (CVal - 1)) == 0)) 12189 break; 12190 } 12191 return; 12192 12193 case 'N': 12194 if (Subtarget->isThumb()) { // FIXME thumb2 12195 // This must be a constant between 0 and 31, for shift amounts. 12196 if (CVal >= 0 && CVal <= 31) 12197 break; 12198 } 12199 return; 12200 12201 case 'O': 12202 if (Subtarget->isThumb()) { // FIXME thumb2 12203 // This must be a multiple of 4 between -508 and 508, for 12204 // ADD/SUB sp = sp + immediate. 12205 if ((CVal >= -508 && CVal <= 508) && ((CVal & 3) == 0)) 12206 break; 12207 } 12208 return; 12209 } 12210 Result = DAG.getTargetConstant(CVal, SDLoc(Op), Op.getValueType()); 12211 break; 12212 } 12213 12214 if (Result.getNode()) { 12215 Ops.push_back(Result); 12216 return; 12217 } 12218 return TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG); 12219 } 12220 12221 static RTLIB::Libcall getDivRemLibcall( 12222 const SDNode *N, MVT::SimpleValueType SVT) { 12223 assert((N->getOpcode() == ISD::SDIVREM || N->getOpcode() == ISD::UDIVREM || 12224 N->getOpcode() == ISD::SREM || N->getOpcode() == ISD::UREM) && 12225 "Unhandled Opcode in getDivRemLibcall"); 12226 bool isSigned = N->getOpcode() == ISD::SDIVREM || 12227 N->getOpcode() == ISD::SREM; 12228 RTLIB::Libcall LC; 12229 switch (SVT) { 12230 default: llvm_unreachable("Unexpected request for libcall!"); 12231 case MVT::i8: LC = isSigned ? RTLIB::SDIVREM_I8 : RTLIB::UDIVREM_I8; break; 12232 case MVT::i16: LC = isSigned ? RTLIB::SDIVREM_I16 : RTLIB::UDIVREM_I16; break; 12233 case MVT::i32: LC = isSigned ? RTLIB::SDIVREM_I32 : RTLIB::UDIVREM_I32; break; 12234 case MVT::i64: LC = isSigned ? RTLIB::SDIVREM_I64 : RTLIB::UDIVREM_I64; break; 12235 } 12236 return LC; 12237 } 12238 12239 static TargetLowering::ArgListTy getDivRemArgList( 12240 const SDNode *N, LLVMContext *Context) { 12241 assert((N->getOpcode() == ISD::SDIVREM || N->getOpcode() == ISD::UDIVREM || 12242 N->getOpcode() == ISD::SREM || N->getOpcode() == ISD::UREM) && 12243 "Unhandled Opcode in getDivRemArgList"); 12244 bool isSigned = N->getOpcode() == ISD::SDIVREM || 12245 N->getOpcode() == ISD::SREM; 12246 TargetLowering::ArgListTy Args; 12247 TargetLowering::ArgListEntry Entry; 12248 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) { 12249 EVT ArgVT = N->getOperand(i).getValueType(); 12250 Type *ArgTy = ArgVT.getTypeForEVT(*Context); 12251 Entry.Node = N->getOperand(i); 12252 Entry.Ty = ArgTy; 12253 Entry.isSExt = isSigned; 12254 Entry.isZExt = !isSigned; 12255 Args.push_back(Entry); 12256 } 12257 return Args; 12258 } 12259 12260 SDValue ARMTargetLowering::LowerDivRem(SDValue Op, SelectionDAG &DAG) const { 12261 assert((Subtarget->isTargetAEABI() || Subtarget->isTargetAndroid() || 12262 Subtarget->isTargetGNUAEABI() || Subtarget->isTargetMuslAEABI()) && 12263 "Register-based DivRem lowering only"); 12264 unsigned Opcode = Op->getOpcode(); 12265 assert((Opcode == ISD::SDIVREM || Opcode == ISD::UDIVREM) && 12266 "Invalid opcode for Div/Rem lowering"); 12267 bool isSigned = (Opcode == ISD::SDIVREM); 12268 EVT VT = Op->getValueType(0); 12269 Type *Ty = VT.getTypeForEVT(*DAG.getContext()); 12270 12271 RTLIB::Libcall LC = getDivRemLibcall(Op.getNode(), 12272 VT.getSimpleVT().SimpleTy); 12273 SDValue InChain = DAG.getEntryNode(); 12274 12275 TargetLowering::ArgListTy Args = getDivRemArgList(Op.getNode(), 12276 DAG.getContext()); 12277 12278 SDValue Callee = DAG.getExternalSymbol(getLibcallName(LC), 12279 getPointerTy(DAG.getDataLayout())); 12280 12281 Type *RetTy = (Type*)StructType::get(Ty, Ty, nullptr); 12282 12283 SDLoc dl(Op); 12284 TargetLowering::CallLoweringInfo CLI(DAG); 12285 CLI.setDebugLoc(dl).setChain(InChain) 12286 .setCallee(getLibcallCallingConv(LC), RetTy, Callee, std::move(Args)) 12287 .setInRegister().setSExtResult(isSigned).setZExtResult(!isSigned); 12288 12289 std::pair<SDValue, SDValue> CallInfo = LowerCallTo(CLI); 12290 return CallInfo.first; 12291 } 12292 12293 // Lowers REM using divmod helpers 12294 // see RTABI section 4.2/4.3 12295 SDValue ARMTargetLowering::LowerREM(SDNode *N, SelectionDAG &DAG) const { 12296 // Build return types (div and rem) 12297 std::vector<Type*> RetTyParams; 12298 Type *RetTyElement; 12299 12300 switch (N->getValueType(0).getSimpleVT().SimpleTy) { 12301 default: llvm_unreachable("Unexpected request for libcall!"); 12302 case MVT::i8: RetTyElement = Type::getInt8Ty(*DAG.getContext()); break; 12303 case MVT::i16: RetTyElement = Type::getInt16Ty(*DAG.getContext()); break; 12304 case MVT::i32: RetTyElement = Type::getInt32Ty(*DAG.getContext()); break; 12305 case MVT::i64: RetTyElement = Type::getInt64Ty(*DAG.getContext()); break; 12306 } 12307 12308 RetTyParams.push_back(RetTyElement); 12309 RetTyParams.push_back(RetTyElement); 12310 ArrayRef<Type*> ret = ArrayRef<Type*>(RetTyParams); 12311 Type *RetTy = StructType::get(*DAG.getContext(), ret); 12312 12313 RTLIB::Libcall LC = getDivRemLibcall(N, N->getValueType(0).getSimpleVT(). 12314 SimpleTy); 12315 SDValue InChain = DAG.getEntryNode(); 12316 TargetLowering::ArgListTy Args = getDivRemArgList(N, DAG.getContext()); 12317 bool isSigned = N->getOpcode() == ISD::SREM; 12318 SDValue Callee = DAG.getExternalSymbol(getLibcallName(LC), 12319 getPointerTy(DAG.getDataLayout())); 12320 12321 // Lower call 12322 CallLoweringInfo CLI(DAG); 12323 CLI.setChain(InChain) 12324 .setCallee(CallingConv::ARM_AAPCS, RetTy, Callee, std::move(Args)) 12325 .setSExtResult(isSigned).setZExtResult(!isSigned).setDebugLoc(SDLoc(N)); 12326 std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI); 12327 12328 // Return second (rem) result operand (first contains div) 12329 SDNode *ResNode = CallResult.first.getNode(); 12330 assert(ResNode->getNumOperands() == 2 && "divmod should return two operands"); 12331 return ResNode->getOperand(1); 12332 } 12333 12334 SDValue 12335 ARMTargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op, SelectionDAG &DAG) const { 12336 assert(Subtarget->isTargetWindows() && "unsupported target platform"); 12337 SDLoc DL(Op); 12338 12339 // Get the inputs. 12340 SDValue Chain = Op.getOperand(0); 12341 SDValue Size = Op.getOperand(1); 12342 12343 SDValue Words = DAG.getNode(ISD::SRL, DL, MVT::i32, Size, 12344 DAG.getConstant(2, DL, MVT::i32)); 12345 12346 SDValue Flag; 12347 Chain = DAG.getCopyToReg(Chain, DL, ARM::R4, Words, Flag); 12348 Flag = Chain.getValue(1); 12349 12350 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue); 12351 Chain = DAG.getNode(ARMISD::WIN__CHKSTK, DL, NodeTys, Chain, Flag); 12352 12353 SDValue NewSP = DAG.getCopyFromReg(Chain, DL, ARM::SP, MVT::i32); 12354 Chain = NewSP.getValue(1); 12355 12356 SDValue Ops[2] = { NewSP, Chain }; 12357 return DAG.getMergeValues(Ops, DL); 12358 } 12359 12360 SDValue ARMTargetLowering::LowerFP_EXTEND(SDValue Op, SelectionDAG &DAG) const { 12361 assert(Op.getValueType() == MVT::f64 && Subtarget->isFPOnlySP() && 12362 "Unexpected type for custom-lowering FP_EXTEND"); 12363 12364 RTLIB::Libcall LC; 12365 LC = RTLIB::getFPEXT(Op.getOperand(0).getValueType(), Op.getValueType()); 12366 12367 SDValue SrcVal = Op.getOperand(0); 12368 return makeLibCall(DAG, LC, Op.getValueType(), SrcVal, /*isSigned*/ false, 12369 SDLoc(Op)).first; 12370 } 12371 12372 SDValue ARMTargetLowering::LowerFP_ROUND(SDValue Op, SelectionDAG &DAG) const { 12373 assert(Op.getOperand(0).getValueType() == MVT::f64 && 12374 Subtarget->isFPOnlySP() && 12375 "Unexpected type for custom-lowering FP_ROUND"); 12376 12377 RTLIB::Libcall LC; 12378 LC = RTLIB::getFPROUND(Op.getOperand(0).getValueType(), Op.getValueType()); 12379 12380 SDValue SrcVal = Op.getOperand(0); 12381 return makeLibCall(DAG, LC, Op.getValueType(), SrcVal, /*isSigned*/ false, 12382 SDLoc(Op)).first; 12383 } 12384 12385 bool 12386 ARMTargetLowering::isOffsetFoldingLegal(const GlobalAddressSDNode *GA) const { 12387 // The ARM target isn't yet aware of offsets. 12388 return false; 12389 } 12390 12391 bool ARM::isBitFieldInvertedMask(unsigned v) { 12392 if (v == 0xffffffff) 12393 return false; 12394 12395 // there can be 1's on either or both "outsides", all the "inside" 12396 // bits must be 0's 12397 return isShiftedMask_32(~v); 12398 } 12399 12400 /// isFPImmLegal - Returns true if the target can instruction select the 12401 /// specified FP immediate natively. If false, the legalizer will 12402 /// materialize the FP immediate as a load from a constant pool. 12403 bool ARMTargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT) const { 12404 if (!Subtarget->hasVFP3()) 12405 return false; 12406 if (VT == MVT::f32) 12407 return ARM_AM::getFP32Imm(Imm) != -1; 12408 if (VT == MVT::f64 && !Subtarget->isFPOnlySP()) 12409 return ARM_AM::getFP64Imm(Imm) != -1; 12410 return false; 12411 } 12412 12413 /// getTgtMemIntrinsic - Represent NEON load and store intrinsics as 12414 /// MemIntrinsicNodes. The associated MachineMemOperands record the alignment 12415 /// specified in the intrinsic calls. 12416 bool ARMTargetLowering::getTgtMemIntrinsic(IntrinsicInfo &Info, 12417 const CallInst &I, 12418 unsigned Intrinsic) const { 12419 switch (Intrinsic) { 12420 case Intrinsic::arm_neon_vld1: 12421 case Intrinsic::arm_neon_vld2: 12422 case Intrinsic::arm_neon_vld3: 12423 case Intrinsic::arm_neon_vld4: 12424 case Intrinsic::arm_neon_vld2lane: 12425 case Intrinsic::arm_neon_vld3lane: 12426 case Intrinsic::arm_neon_vld4lane: { 12427 Info.opc = ISD::INTRINSIC_W_CHAIN; 12428 // Conservatively set memVT to the entire set of vectors loaded. 12429 auto &DL = I.getCalledFunction()->getParent()->getDataLayout(); 12430 uint64_t NumElts = DL.getTypeSizeInBits(I.getType()) / 64; 12431 Info.memVT = EVT::getVectorVT(I.getType()->getContext(), MVT::i64, NumElts); 12432 Info.ptrVal = I.getArgOperand(0); 12433 Info.offset = 0; 12434 Value *AlignArg = I.getArgOperand(I.getNumArgOperands() - 1); 12435 Info.align = cast<ConstantInt>(AlignArg)->getZExtValue(); 12436 Info.vol = false; // volatile loads with NEON intrinsics not supported 12437 Info.readMem = true; 12438 Info.writeMem = false; 12439 return true; 12440 } 12441 case Intrinsic::arm_neon_vst1: 12442 case Intrinsic::arm_neon_vst2: 12443 case Intrinsic::arm_neon_vst3: 12444 case Intrinsic::arm_neon_vst4: 12445 case Intrinsic::arm_neon_vst2lane: 12446 case Intrinsic::arm_neon_vst3lane: 12447 case Intrinsic::arm_neon_vst4lane: { 12448 Info.opc = ISD::INTRINSIC_VOID; 12449 // Conservatively set memVT to the entire set of vectors stored. 12450 auto &DL = I.getCalledFunction()->getParent()->getDataLayout(); 12451 unsigned NumElts = 0; 12452 for (unsigned ArgI = 1, ArgE = I.getNumArgOperands(); ArgI < ArgE; ++ArgI) { 12453 Type *ArgTy = I.getArgOperand(ArgI)->getType(); 12454 if (!ArgTy->isVectorTy()) 12455 break; 12456 NumElts += DL.getTypeSizeInBits(ArgTy) / 64; 12457 } 12458 Info.memVT = EVT::getVectorVT(I.getType()->getContext(), MVT::i64, NumElts); 12459 Info.ptrVal = I.getArgOperand(0); 12460 Info.offset = 0; 12461 Value *AlignArg = I.getArgOperand(I.getNumArgOperands() - 1); 12462 Info.align = cast<ConstantInt>(AlignArg)->getZExtValue(); 12463 Info.vol = false; // volatile stores with NEON intrinsics not supported 12464 Info.readMem = false; 12465 Info.writeMem = true; 12466 return true; 12467 } 12468 case Intrinsic::arm_ldaex: 12469 case Intrinsic::arm_ldrex: { 12470 auto &DL = I.getCalledFunction()->getParent()->getDataLayout(); 12471 PointerType *PtrTy = cast<PointerType>(I.getArgOperand(0)->getType()); 12472 Info.opc = ISD::INTRINSIC_W_CHAIN; 12473 Info.memVT = MVT::getVT(PtrTy->getElementType()); 12474 Info.ptrVal = I.getArgOperand(0); 12475 Info.offset = 0; 12476 Info.align = DL.getABITypeAlignment(PtrTy->getElementType()); 12477 Info.vol = true; 12478 Info.readMem = true; 12479 Info.writeMem = false; 12480 return true; 12481 } 12482 case Intrinsic::arm_stlex: 12483 case Intrinsic::arm_strex: { 12484 auto &DL = I.getCalledFunction()->getParent()->getDataLayout(); 12485 PointerType *PtrTy = cast<PointerType>(I.getArgOperand(1)->getType()); 12486 Info.opc = ISD::INTRINSIC_W_CHAIN; 12487 Info.memVT = MVT::getVT(PtrTy->getElementType()); 12488 Info.ptrVal = I.getArgOperand(1); 12489 Info.offset = 0; 12490 Info.align = DL.getABITypeAlignment(PtrTy->getElementType()); 12491 Info.vol = true; 12492 Info.readMem = false; 12493 Info.writeMem = true; 12494 return true; 12495 } 12496 case Intrinsic::arm_stlexd: 12497 case Intrinsic::arm_strexd: { 12498 Info.opc = ISD::INTRINSIC_W_CHAIN; 12499 Info.memVT = MVT::i64; 12500 Info.ptrVal = I.getArgOperand(2); 12501 Info.offset = 0; 12502 Info.align = 8; 12503 Info.vol = true; 12504 Info.readMem = false; 12505 Info.writeMem = true; 12506 return true; 12507 } 12508 case Intrinsic::arm_ldaexd: 12509 case Intrinsic::arm_ldrexd: { 12510 Info.opc = ISD::INTRINSIC_W_CHAIN; 12511 Info.memVT = MVT::i64; 12512 Info.ptrVal = I.getArgOperand(0); 12513 Info.offset = 0; 12514 Info.align = 8; 12515 Info.vol = true; 12516 Info.readMem = true; 12517 Info.writeMem = false; 12518 return true; 12519 } 12520 default: 12521 break; 12522 } 12523 12524 return false; 12525 } 12526 12527 /// \brief Returns true if it is beneficial to convert a load of a constant 12528 /// to just the constant itself. 12529 bool ARMTargetLowering::shouldConvertConstantLoadToIntImm(const APInt &Imm, 12530 Type *Ty) const { 12531 assert(Ty->isIntegerTy()); 12532 12533 unsigned Bits = Ty->getPrimitiveSizeInBits(); 12534 if (Bits == 0 || Bits > 32) 12535 return false; 12536 return true; 12537 } 12538 12539 Instruction* ARMTargetLowering::makeDMB(IRBuilder<> &Builder, 12540 ARM_MB::MemBOpt Domain) const { 12541 Module *M = Builder.GetInsertBlock()->getParent()->getParent(); 12542 12543 // First, if the target has no DMB, see what fallback we can use. 12544 if (!Subtarget->hasDataBarrier()) { 12545 // Some ARMv6 cpus can support data barriers with an mcr instruction. 12546 // Thumb1 and pre-v6 ARM mode use a libcall instead and should never get 12547 // here. 12548 if (Subtarget->hasV6Ops() && !Subtarget->isThumb()) { 12549 Function *MCR = llvm::Intrinsic::getDeclaration(M, Intrinsic::arm_mcr); 12550 Value* args[6] = {Builder.getInt32(15), Builder.getInt32(0), 12551 Builder.getInt32(0), Builder.getInt32(7), 12552 Builder.getInt32(10), Builder.getInt32(5)}; 12553 return Builder.CreateCall(MCR, args); 12554 } else { 12555 // Instead of using barriers, atomic accesses on these subtargets use 12556 // libcalls. 12557 llvm_unreachable("makeDMB on a target so old that it has no barriers"); 12558 } 12559 } else { 12560 Function *DMB = llvm::Intrinsic::getDeclaration(M, Intrinsic::arm_dmb); 12561 // Only a full system barrier exists in the M-class architectures. 12562 Domain = Subtarget->isMClass() ? ARM_MB::SY : Domain; 12563 Constant *CDomain = Builder.getInt32(Domain); 12564 return Builder.CreateCall(DMB, CDomain); 12565 } 12566 } 12567 12568 // Based on http://www.cl.cam.ac.uk/~pes20/cpp/cpp0xmappings.html 12569 Instruction* ARMTargetLowering::emitLeadingFence(IRBuilder<> &Builder, 12570 AtomicOrdering Ord, bool IsStore, 12571 bool IsLoad) const { 12572 switch (Ord) { 12573 case AtomicOrdering::NotAtomic: 12574 case AtomicOrdering::Unordered: 12575 llvm_unreachable("Invalid fence: unordered/non-atomic"); 12576 case AtomicOrdering::Monotonic: 12577 case AtomicOrdering::Acquire: 12578 return nullptr; // Nothing to do 12579 case AtomicOrdering::SequentiallyConsistent: 12580 if (!IsStore) 12581 return nullptr; // Nothing to do 12582 /*FALLTHROUGH*/ 12583 case AtomicOrdering::Release: 12584 case AtomicOrdering::AcquireRelease: 12585 if (Subtarget->preferISHSTBarriers()) 12586 return makeDMB(Builder, ARM_MB::ISHST); 12587 // FIXME: add a comment with a link to documentation justifying this. 12588 else 12589 return makeDMB(Builder, ARM_MB::ISH); 12590 } 12591 llvm_unreachable("Unknown fence ordering in emitLeadingFence"); 12592 } 12593 12594 Instruction* ARMTargetLowering::emitTrailingFence(IRBuilder<> &Builder, 12595 AtomicOrdering Ord, bool IsStore, 12596 bool IsLoad) const { 12597 switch (Ord) { 12598 case AtomicOrdering::NotAtomic: 12599 case AtomicOrdering::Unordered: 12600 llvm_unreachable("Invalid fence: unordered/not-atomic"); 12601 case AtomicOrdering::Monotonic: 12602 case AtomicOrdering::Release: 12603 return nullptr; // Nothing to do 12604 case AtomicOrdering::Acquire: 12605 case AtomicOrdering::AcquireRelease: 12606 case AtomicOrdering::SequentiallyConsistent: 12607 return makeDMB(Builder, ARM_MB::ISH); 12608 } 12609 llvm_unreachable("Unknown fence ordering in emitTrailingFence"); 12610 } 12611 12612 // Loads and stores less than 64-bits are already atomic; ones above that 12613 // are doomed anyway, so defer to the default libcall and blame the OS when 12614 // things go wrong. Cortex M doesn't have ldrexd/strexd though, so don't emit 12615 // anything for those. 12616 bool ARMTargetLowering::shouldExpandAtomicStoreInIR(StoreInst *SI) const { 12617 unsigned Size = SI->getValueOperand()->getType()->getPrimitiveSizeInBits(); 12618 return (Size == 64) && !Subtarget->isMClass(); 12619 } 12620 12621 // Loads and stores less than 64-bits are already atomic; ones above that 12622 // are doomed anyway, so defer to the default libcall and blame the OS when 12623 // things go wrong. Cortex M doesn't have ldrexd/strexd though, so don't emit 12624 // anything for those. 12625 // FIXME: ldrd and strd are atomic if the CPU has LPAE (e.g. A15 has that 12626 // guarantee, see DDI0406C ARM architecture reference manual, 12627 // sections A8.8.72-74 LDRD) 12628 TargetLowering::AtomicExpansionKind 12629 ARMTargetLowering::shouldExpandAtomicLoadInIR(LoadInst *LI) const { 12630 unsigned Size = LI->getType()->getPrimitiveSizeInBits(); 12631 return ((Size == 64) && !Subtarget->isMClass()) ? AtomicExpansionKind::LLOnly 12632 : AtomicExpansionKind::None; 12633 } 12634 12635 // For the real atomic operations, we have ldrex/strex up to 32 bits, 12636 // and up to 64 bits on the non-M profiles 12637 TargetLowering::AtomicExpansionKind 12638 ARMTargetLowering::shouldExpandAtomicRMWInIR(AtomicRMWInst *AI) const { 12639 unsigned Size = AI->getType()->getPrimitiveSizeInBits(); 12640 return (Size <= (Subtarget->isMClass() ? 32U : 64U)) 12641 ? AtomicExpansionKind::LLSC 12642 : AtomicExpansionKind::None; 12643 } 12644 12645 bool ARMTargetLowering::shouldExpandAtomicCmpXchgInIR( 12646 AtomicCmpXchgInst *AI) const { 12647 // At -O0, fast-regalloc cannot cope with the live vregs necessary to 12648 // implement cmpxchg without spilling. If the address being exchanged is also 12649 // on the stack and close enough to the spill slot, this can lead to a 12650 // situation where the monitor always gets cleared and the atomic operation 12651 // can never succeed. So at -O0 we need a late-expanded pseudo-inst instead. 12652 return getTargetMachine().getOptLevel() != 0; 12653 } 12654 12655 bool ARMTargetLowering::shouldInsertFencesForAtomic( 12656 const Instruction *I) const { 12657 return InsertFencesForAtomic; 12658 } 12659 12660 // This has so far only been implemented for MachO. 12661 bool ARMTargetLowering::useLoadStackGuardNode() const { 12662 return Subtarget->isTargetMachO(); 12663 } 12664 12665 bool ARMTargetLowering::canCombineStoreAndExtract(Type *VectorTy, Value *Idx, 12666 unsigned &Cost) const { 12667 // If we do not have NEON, vector types are not natively supported. 12668 if (!Subtarget->hasNEON()) 12669 return false; 12670 12671 // Floating point values and vector values map to the same register file. 12672 // Therefore, although we could do a store extract of a vector type, this is 12673 // better to leave at float as we have more freedom in the addressing mode for 12674 // those. 12675 if (VectorTy->isFPOrFPVectorTy()) 12676 return false; 12677 12678 // If the index is unknown at compile time, this is very expensive to lower 12679 // and it is not possible to combine the store with the extract. 12680 if (!isa<ConstantInt>(Idx)) 12681 return false; 12682 12683 assert(VectorTy->isVectorTy() && "VectorTy is not a vector type"); 12684 unsigned BitWidth = cast<VectorType>(VectorTy)->getBitWidth(); 12685 // We can do a store + vector extract on any vector that fits perfectly in a D 12686 // or Q register. 12687 if (BitWidth == 64 || BitWidth == 128) { 12688 Cost = 0; 12689 return true; 12690 } 12691 return false; 12692 } 12693 12694 bool ARMTargetLowering::isCheapToSpeculateCttz() const { 12695 return Subtarget->hasV6T2Ops(); 12696 } 12697 12698 bool ARMTargetLowering::isCheapToSpeculateCtlz() const { 12699 return Subtarget->hasV6T2Ops(); 12700 } 12701 12702 Value *ARMTargetLowering::emitLoadLinked(IRBuilder<> &Builder, Value *Addr, 12703 AtomicOrdering Ord) const { 12704 Module *M = Builder.GetInsertBlock()->getParent()->getParent(); 12705 Type *ValTy = cast<PointerType>(Addr->getType())->getElementType(); 12706 bool IsAcquire = isAcquireOrStronger(Ord); 12707 12708 // Since i64 isn't legal and intrinsics don't get type-lowered, the ldrexd 12709 // intrinsic must return {i32, i32} and we have to recombine them into a 12710 // single i64 here. 12711 if (ValTy->getPrimitiveSizeInBits() == 64) { 12712 Intrinsic::ID Int = 12713 IsAcquire ? Intrinsic::arm_ldaexd : Intrinsic::arm_ldrexd; 12714 Function *Ldrex = llvm::Intrinsic::getDeclaration(M, Int); 12715 12716 Addr = Builder.CreateBitCast(Addr, Type::getInt8PtrTy(M->getContext())); 12717 Value *LoHi = Builder.CreateCall(Ldrex, Addr, "lohi"); 12718 12719 Value *Lo = Builder.CreateExtractValue(LoHi, 0, "lo"); 12720 Value *Hi = Builder.CreateExtractValue(LoHi, 1, "hi"); 12721 if (!Subtarget->isLittle()) 12722 std::swap (Lo, Hi); 12723 Lo = Builder.CreateZExt(Lo, ValTy, "lo64"); 12724 Hi = Builder.CreateZExt(Hi, ValTy, "hi64"); 12725 return Builder.CreateOr( 12726 Lo, Builder.CreateShl(Hi, ConstantInt::get(ValTy, 32)), "val64"); 12727 } 12728 12729 Type *Tys[] = { Addr->getType() }; 12730 Intrinsic::ID Int = IsAcquire ? Intrinsic::arm_ldaex : Intrinsic::arm_ldrex; 12731 Function *Ldrex = llvm::Intrinsic::getDeclaration(M, Int, Tys); 12732 12733 return Builder.CreateTruncOrBitCast( 12734 Builder.CreateCall(Ldrex, Addr), 12735 cast<PointerType>(Addr->getType())->getElementType()); 12736 } 12737 12738 void ARMTargetLowering::emitAtomicCmpXchgNoStoreLLBalance( 12739 IRBuilder<> &Builder) const { 12740 if (!Subtarget->hasV7Ops()) 12741 return; 12742 Module *M = Builder.GetInsertBlock()->getParent()->getParent(); 12743 Builder.CreateCall(llvm::Intrinsic::getDeclaration(M, Intrinsic::arm_clrex)); 12744 } 12745 12746 Value *ARMTargetLowering::emitStoreConditional(IRBuilder<> &Builder, Value *Val, 12747 Value *Addr, 12748 AtomicOrdering Ord) const { 12749 Module *M = Builder.GetInsertBlock()->getParent()->getParent(); 12750 bool IsRelease = isReleaseOrStronger(Ord); 12751 12752 // Since the intrinsics must have legal type, the i64 intrinsics take two 12753 // parameters: "i32, i32". We must marshal Val into the appropriate form 12754 // before the call. 12755 if (Val->getType()->getPrimitiveSizeInBits() == 64) { 12756 Intrinsic::ID Int = 12757 IsRelease ? Intrinsic::arm_stlexd : Intrinsic::arm_strexd; 12758 Function *Strex = Intrinsic::getDeclaration(M, Int); 12759 Type *Int32Ty = Type::getInt32Ty(M->getContext()); 12760 12761 Value *Lo = Builder.CreateTrunc(Val, Int32Ty, "lo"); 12762 Value *Hi = Builder.CreateTrunc(Builder.CreateLShr(Val, 32), Int32Ty, "hi"); 12763 if (!Subtarget->isLittle()) 12764 std::swap (Lo, Hi); 12765 Addr = Builder.CreateBitCast(Addr, Type::getInt8PtrTy(M->getContext())); 12766 return Builder.CreateCall(Strex, {Lo, Hi, Addr}); 12767 } 12768 12769 Intrinsic::ID Int = IsRelease ? Intrinsic::arm_stlex : Intrinsic::arm_strex; 12770 Type *Tys[] = { Addr->getType() }; 12771 Function *Strex = Intrinsic::getDeclaration(M, Int, Tys); 12772 12773 return Builder.CreateCall( 12774 Strex, {Builder.CreateZExtOrBitCast( 12775 Val, Strex->getFunctionType()->getParamType(0)), 12776 Addr}); 12777 } 12778 12779 /// \brief Lower an interleaved load into a vldN intrinsic. 12780 /// 12781 /// E.g. Lower an interleaved load (Factor = 2): 12782 /// %wide.vec = load <8 x i32>, <8 x i32>* %ptr, align 4 12783 /// %v0 = shuffle %wide.vec, undef, <0, 2, 4, 6> ; Extract even elements 12784 /// %v1 = shuffle %wide.vec, undef, <1, 3, 5, 7> ; Extract odd elements 12785 /// 12786 /// Into: 12787 /// %vld2 = { <4 x i32>, <4 x i32> } call llvm.arm.neon.vld2(%ptr, 4) 12788 /// %vec0 = extractelement { <4 x i32>, <4 x i32> } %vld2, i32 0 12789 /// %vec1 = extractelement { <4 x i32>, <4 x i32> } %vld2, i32 1 12790 bool ARMTargetLowering::lowerInterleavedLoad( 12791 LoadInst *LI, ArrayRef<ShuffleVectorInst *> Shuffles, 12792 ArrayRef<unsigned> Indices, unsigned Factor) const { 12793 assert(Factor >= 2 && Factor <= getMaxSupportedInterleaveFactor() && 12794 "Invalid interleave factor"); 12795 assert(!Shuffles.empty() && "Empty shufflevector input"); 12796 assert(Shuffles.size() == Indices.size() && 12797 "Unmatched number of shufflevectors and indices"); 12798 12799 VectorType *VecTy = Shuffles[0]->getType(); 12800 Type *EltTy = VecTy->getVectorElementType(); 12801 12802 const DataLayout &DL = LI->getModule()->getDataLayout(); 12803 unsigned VecSize = DL.getTypeSizeInBits(VecTy); 12804 bool EltIs64Bits = DL.getTypeSizeInBits(EltTy) == 64; 12805 12806 // Skip if we do not have NEON and skip illegal vector types and vector types 12807 // with i64/f64 elements (vldN doesn't support i64/f64 elements). 12808 if (!Subtarget->hasNEON() || (VecSize != 64 && VecSize != 128) || EltIs64Bits) 12809 return false; 12810 12811 // A pointer vector can not be the return type of the ldN intrinsics. Need to 12812 // load integer vectors first and then convert to pointer vectors. 12813 if (EltTy->isPointerTy()) 12814 VecTy = 12815 VectorType::get(DL.getIntPtrType(EltTy), VecTy->getVectorNumElements()); 12816 12817 static const Intrinsic::ID LoadInts[3] = {Intrinsic::arm_neon_vld2, 12818 Intrinsic::arm_neon_vld3, 12819 Intrinsic::arm_neon_vld4}; 12820 12821 IRBuilder<> Builder(LI); 12822 SmallVector<Value *, 2> Ops; 12823 12824 Type *Int8Ptr = Builder.getInt8PtrTy(LI->getPointerAddressSpace()); 12825 Ops.push_back(Builder.CreateBitCast(LI->getPointerOperand(), Int8Ptr)); 12826 Ops.push_back(Builder.getInt32(LI->getAlignment())); 12827 12828 Type *Tys[] = { VecTy, Int8Ptr }; 12829 Function *VldnFunc = 12830 Intrinsic::getDeclaration(LI->getModule(), LoadInts[Factor - 2], Tys); 12831 CallInst *VldN = Builder.CreateCall(VldnFunc, Ops, "vldN"); 12832 12833 // Replace uses of each shufflevector with the corresponding vector loaded 12834 // by ldN. 12835 for (unsigned i = 0; i < Shuffles.size(); i++) { 12836 ShuffleVectorInst *SV = Shuffles[i]; 12837 unsigned Index = Indices[i]; 12838 12839 Value *SubVec = Builder.CreateExtractValue(VldN, Index); 12840 12841 // Convert the integer vector to pointer vector if the element is pointer. 12842 if (EltTy->isPointerTy()) 12843 SubVec = Builder.CreateIntToPtr(SubVec, SV->getType()); 12844 12845 SV->replaceAllUsesWith(SubVec); 12846 } 12847 12848 return true; 12849 } 12850 12851 /// \brief Get a mask consisting of sequential integers starting from \p Start. 12852 /// 12853 /// I.e. <Start, Start + 1, ..., Start + NumElts - 1> 12854 static Constant *getSequentialMask(IRBuilder<> &Builder, unsigned Start, 12855 unsigned NumElts) { 12856 SmallVector<Constant *, 16> Mask; 12857 for (unsigned i = 0; i < NumElts; i++) 12858 Mask.push_back(Builder.getInt32(Start + i)); 12859 12860 return ConstantVector::get(Mask); 12861 } 12862 12863 /// \brief Lower an interleaved store into a vstN intrinsic. 12864 /// 12865 /// E.g. Lower an interleaved store (Factor = 3): 12866 /// %i.vec = shuffle <8 x i32> %v0, <8 x i32> %v1, 12867 /// <0, 4, 8, 1, 5, 9, 2, 6, 10, 3, 7, 11> 12868 /// store <12 x i32> %i.vec, <12 x i32>* %ptr, align 4 12869 /// 12870 /// Into: 12871 /// %sub.v0 = shuffle <8 x i32> %v0, <8 x i32> v1, <0, 1, 2, 3> 12872 /// %sub.v1 = shuffle <8 x i32> %v0, <8 x i32> v1, <4, 5, 6, 7> 12873 /// %sub.v2 = shuffle <8 x i32> %v0, <8 x i32> v1, <8, 9, 10, 11> 12874 /// call void llvm.arm.neon.vst3(%ptr, %sub.v0, %sub.v1, %sub.v2, 4) 12875 /// 12876 /// Note that the new shufflevectors will be removed and we'll only generate one 12877 /// vst3 instruction in CodeGen. 12878 bool ARMTargetLowering::lowerInterleavedStore(StoreInst *SI, 12879 ShuffleVectorInst *SVI, 12880 unsigned Factor) const { 12881 assert(Factor >= 2 && Factor <= getMaxSupportedInterleaveFactor() && 12882 "Invalid interleave factor"); 12883 12884 VectorType *VecTy = SVI->getType(); 12885 assert(VecTy->getVectorNumElements() % Factor == 0 && 12886 "Invalid interleaved store"); 12887 12888 unsigned NumSubElts = VecTy->getVectorNumElements() / Factor; 12889 Type *EltTy = VecTy->getVectorElementType(); 12890 VectorType *SubVecTy = VectorType::get(EltTy, NumSubElts); 12891 12892 const DataLayout &DL = SI->getModule()->getDataLayout(); 12893 unsigned SubVecSize = DL.getTypeSizeInBits(SubVecTy); 12894 bool EltIs64Bits = DL.getTypeSizeInBits(EltTy) == 64; 12895 12896 // Skip if we do not have NEON and skip illegal vector types and vector types 12897 // with i64/f64 elements (vstN doesn't support i64/f64 elements). 12898 if (!Subtarget->hasNEON() || (SubVecSize != 64 && SubVecSize != 128) || 12899 EltIs64Bits) 12900 return false; 12901 12902 Value *Op0 = SVI->getOperand(0); 12903 Value *Op1 = SVI->getOperand(1); 12904 IRBuilder<> Builder(SI); 12905 12906 // StN intrinsics don't support pointer vectors as arguments. Convert pointer 12907 // vectors to integer vectors. 12908 if (EltTy->isPointerTy()) { 12909 Type *IntTy = DL.getIntPtrType(EltTy); 12910 12911 // Convert to the corresponding integer vector. 12912 Type *IntVecTy = 12913 VectorType::get(IntTy, Op0->getType()->getVectorNumElements()); 12914 Op0 = Builder.CreatePtrToInt(Op0, IntVecTy); 12915 Op1 = Builder.CreatePtrToInt(Op1, IntVecTy); 12916 12917 SubVecTy = VectorType::get(IntTy, NumSubElts); 12918 } 12919 12920 static const Intrinsic::ID StoreInts[3] = {Intrinsic::arm_neon_vst2, 12921 Intrinsic::arm_neon_vst3, 12922 Intrinsic::arm_neon_vst4}; 12923 SmallVector<Value *, 6> Ops; 12924 12925 Type *Int8Ptr = Builder.getInt8PtrTy(SI->getPointerAddressSpace()); 12926 Ops.push_back(Builder.CreateBitCast(SI->getPointerOperand(), Int8Ptr)); 12927 12928 Type *Tys[] = { Int8Ptr, SubVecTy }; 12929 Function *VstNFunc = Intrinsic::getDeclaration( 12930 SI->getModule(), StoreInts[Factor - 2], Tys); 12931 12932 // Split the shufflevector operands into sub vectors for the new vstN call. 12933 for (unsigned i = 0; i < Factor; i++) 12934 Ops.push_back(Builder.CreateShuffleVector( 12935 Op0, Op1, getSequentialMask(Builder, NumSubElts * i, NumSubElts))); 12936 12937 Ops.push_back(Builder.getInt32(SI->getAlignment())); 12938 Builder.CreateCall(VstNFunc, Ops); 12939 return true; 12940 } 12941 12942 enum HABaseType { 12943 HA_UNKNOWN = 0, 12944 HA_FLOAT, 12945 HA_DOUBLE, 12946 HA_VECT64, 12947 HA_VECT128 12948 }; 12949 12950 static bool isHomogeneousAggregate(Type *Ty, HABaseType &Base, 12951 uint64_t &Members) { 12952 if (auto *ST = dyn_cast<StructType>(Ty)) { 12953 for (unsigned i = 0; i < ST->getNumElements(); ++i) { 12954 uint64_t SubMembers = 0; 12955 if (!isHomogeneousAggregate(ST->getElementType(i), Base, SubMembers)) 12956 return false; 12957 Members += SubMembers; 12958 } 12959 } else if (auto *AT = dyn_cast<ArrayType>(Ty)) { 12960 uint64_t SubMembers = 0; 12961 if (!isHomogeneousAggregate(AT->getElementType(), Base, SubMembers)) 12962 return false; 12963 Members += SubMembers * AT->getNumElements(); 12964 } else if (Ty->isFloatTy()) { 12965 if (Base != HA_UNKNOWN && Base != HA_FLOAT) 12966 return false; 12967 Members = 1; 12968 Base = HA_FLOAT; 12969 } else if (Ty->isDoubleTy()) { 12970 if (Base != HA_UNKNOWN && Base != HA_DOUBLE) 12971 return false; 12972 Members = 1; 12973 Base = HA_DOUBLE; 12974 } else if (auto *VT = dyn_cast<VectorType>(Ty)) { 12975 Members = 1; 12976 switch (Base) { 12977 case HA_FLOAT: 12978 case HA_DOUBLE: 12979 return false; 12980 case HA_VECT64: 12981 return VT->getBitWidth() == 64; 12982 case HA_VECT128: 12983 return VT->getBitWidth() == 128; 12984 case HA_UNKNOWN: 12985 switch (VT->getBitWidth()) { 12986 case 64: 12987 Base = HA_VECT64; 12988 return true; 12989 case 128: 12990 Base = HA_VECT128; 12991 return true; 12992 default: 12993 return false; 12994 } 12995 } 12996 } 12997 12998 return (Members > 0 && Members <= 4); 12999 } 13000 13001 /// \brief Return true if a type is an AAPCS-VFP homogeneous aggregate or one of 13002 /// [N x i32] or [N x i64]. This allows front-ends to skip emitting padding when 13003 /// passing according to AAPCS rules. 13004 bool ARMTargetLowering::functionArgumentNeedsConsecutiveRegisters( 13005 Type *Ty, CallingConv::ID CallConv, bool isVarArg) const { 13006 if (getEffectiveCallingConv(CallConv, isVarArg) != 13007 CallingConv::ARM_AAPCS_VFP) 13008 return false; 13009 13010 HABaseType Base = HA_UNKNOWN; 13011 uint64_t Members = 0; 13012 bool IsHA = isHomogeneousAggregate(Ty, Base, Members); 13013 DEBUG(dbgs() << "isHA: " << IsHA << " "; Ty->dump()); 13014 13015 bool IsIntArray = Ty->isArrayTy() && Ty->getArrayElementType()->isIntegerTy(); 13016 return IsHA || IsIntArray; 13017 } 13018 13019 unsigned ARMTargetLowering::getExceptionPointerRegister( 13020 const Constant *PersonalityFn) const { 13021 // Platforms which do not use SjLj EH may return values in these registers 13022 // via the personality function. 13023 return Subtarget->useSjLjEH() ? ARM::NoRegister : ARM::R0; 13024 } 13025 13026 unsigned ARMTargetLowering::getExceptionSelectorRegister( 13027 const Constant *PersonalityFn) const { 13028 // Platforms which do not use SjLj EH may return values in these registers 13029 // via the personality function. 13030 return Subtarget->useSjLjEH() ? ARM::NoRegister : ARM::R1; 13031 } 13032 13033 void ARMTargetLowering::initializeSplitCSR(MachineBasicBlock *Entry) const { 13034 // Update IsSplitCSR in ARMFunctionInfo. 13035 ARMFunctionInfo *AFI = Entry->getParent()->getInfo<ARMFunctionInfo>(); 13036 AFI->setIsSplitCSR(true); 13037 } 13038 13039 void ARMTargetLowering::insertCopiesSplitCSR( 13040 MachineBasicBlock *Entry, 13041 const SmallVectorImpl<MachineBasicBlock *> &Exits) const { 13042 const ARMBaseRegisterInfo *TRI = Subtarget->getRegisterInfo(); 13043 const MCPhysReg *IStart = TRI->getCalleeSavedRegsViaCopy(Entry->getParent()); 13044 if (!IStart) 13045 return; 13046 13047 const TargetInstrInfo *TII = Subtarget->getInstrInfo(); 13048 MachineRegisterInfo *MRI = &Entry->getParent()->getRegInfo(); 13049 MachineBasicBlock::iterator MBBI = Entry->begin(); 13050 for (const MCPhysReg *I = IStart; *I; ++I) { 13051 const TargetRegisterClass *RC = nullptr; 13052 if (ARM::GPRRegClass.contains(*I)) 13053 RC = &ARM::GPRRegClass; 13054 else if (ARM::DPRRegClass.contains(*I)) 13055 RC = &ARM::DPRRegClass; 13056 else 13057 llvm_unreachable("Unexpected register class in CSRsViaCopy!"); 13058 13059 unsigned NewVR = MRI->createVirtualRegister(RC); 13060 // Create copy from CSR to a virtual register. 13061 // FIXME: this currently does not emit CFI pseudo-instructions, it works 13062 // fine for CXX_FAST_TLS since the C++-style TLS access functions should be 13063 // nounwind. If we want to generalize this later, we may need to emit 13064 // CFI pseudo-instructions. 13065 assert(Entry->getParent()->getFunction()->hasFnAttribute( 13066 Attribute::NoUnwind) && 13067 "Function should be nounwind in insertCopiesSplitCSR!"); 13068 Entry->addLiveIn(*I); 13069 BuildMI(*Entry, MBBI, DebugLoc(), TII->get(TargetOpcode::COPY), NewVR) 13070 .addReg(*I); 13071 13072 // Insert the copy-back instructions right before the terminator. 13073 for (auto *Exit : Exits) 13074 BuildMI(*Exit, Exit->getFirstTerminator(), DebugLoc(), 13075 TII->get(TargetOpcode::COPY), *I) 13076 .addReg(NewVR); 13077 } 13078 } 13079