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/Analysis.h" 28 #include "llvm/CodeGen/CallingConvLower.h" 29 #include "llvm/CodeGen/IntrinsicLowering.h" 30 #include "llvm/CodeGen/MachineBasicBlock.h" 31 #include "llvm/CodeGen/MachineFrameInfo.h" 32 #include "llvm/CodeGen/MachineFunction.h" 33 #include "llvm/CodeGen/MachineInstrBuilder.h" 34 #include "llvm/CodeGen/MachineJumpTableInfo.h" 35 #include "llvm/CodeGen/MachineModuleInfo.h" 36 #include "llvm/CodeGen/MachineRegisterInfo.h" 37 #include "llvm/CodeGen/SelectionDAG.h" 38 #include "llvm/IR/CallingConv.h" 39 #include "llvm/IR/Constants.h" 40 #include "llvm/IR/Function.h" 41 #include "llvm/IR/GlobalValue.h" 42 #include "llvm/IR/IRBuilder.h" 43 #include "llvm/IR/Instruction.h" 44 #include "llvm/IR/Instructions.h" 45 #include "llvm/IR/IntrinsicInst.h" 46 #include "llvm/IR/Intrinsics.h" 47 #include "llvm/IR/Type.h" 48 #include "llvm/MC/MCSectionMachO.h" 49 #include "llvm/Support/CommandLine.h" 50 #include "llvm/Support/Debug.h" 51 #include "llvm/Support/ErrorHandling.h" 52 #include "llvm/Support/MathExtras.h" 53 #include "llvm/Support/raw_ostream.h" 54 #include "llvm/Target/TargetOptions.h" 55 #include <utility> 56 using namespace llvm; 57 58 #define DEBUG_TYPE "arm-isel" 59 60 STATISTIC(NumTailCalls, "Number of tail calls"); 61 STATISTIC(NumMovwMovt, "Number of GAs materialized with movw + movt"); 62 STATISTIC(NumLoopByVals, "Number of loops generated for byval arguments"); 63 64 static cl::opt<bool> 65 ARMInterworking("arm-interworking", cl::Hidden, 66 cl::desc("Enable / disable ARM interworking (for debugging only)"), 67 cl::init(true)); 68 69 namespace { 70 class ARMCCState : public CCState { 71 public: 72 ARMCCState(CallingConv::ID CC, bool isVarArg, MachineFunction &MF, 73 SmallVectorImpl<CCValAssign> &locs, LLVMContext &C, 74 ParmContext PC) 75 : CCState(CC, isVarArg, MF, locs, C) { 76 assert(((PC == Call) || (PC == Prologue)) && 77 "ARMCCState users must specify whether their context is call" 78 "or prologue generation."); 79 CallOrPrologue = PC; 80 } 81 }; 82 } 83 84 // The APCS parameter registers. 85 static const MCPhysReg GPRArgRegs[] = { 86 ARM::R0, ARM::R1, ARM::R2, ARM::R3 87 }; 88 89 void ARMTargetLowering::addTypeForNEON(MVT VT, MVT PromotedLdStVT, 90 MVT PromotedBitwiseVT) { 91 if (VT != PromotedLdStVT) { 92 setOperationAction(ISD::LOAD, VT, Promote); 93 AddPromotedToType (ISD::LOAD, VT, PromotedLdStVT); 94 95 setOperationAction(ISD::STORE, VT, Promote); 96 AddPromotedToType (ISD::STORE, VT, PromotedLdStVT); 97 } 98 99 MVT ElemTy = VT.getVectorElementType(); 100 if (ElemTy != MVT::i64 && ElemTy != MVT::f64) 101 setOperationAction(ISD::SETCC, VT, Custom); 102 setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Custom); 103 setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom); 104 if (ElemTy == MVT::i32) { 105 setOperationAction(ISD::SINT_TO_FP, VT, Custom); 106 setOperationAction(ISD::UINT_TO_FP, VT, Custom); 107 setOperationAction(ISD::FP_TO_SINT, VT, Custom); 108 setOperationAction(ISD::FP_TO_UINT, VT, Custom); 109 } else { 110 setOperationAction(ISD::SINT_TO_FP, VT, Expand); 111 setOperationAction(ISD::UINT_TO_FP, VT, Expand); 112 setOperationAction(ISD::FP_TO_SINT, VT, Expand); 113 setOperationAction(ISD::FP_TO_UINT, VT, Expand); 114 } 115 setOperationAction(ISD::BUILD_VECTOR, VT, Custom); 116 setOperationAction(ISD::VECTOR_SHUFFLE, VT, Custom); 117 setOperationAction(ISD::CONCAT_VECTORS, VT, Legal); 118 setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Legal); 119 setOperationAction(ISD::SELECT, VT, Expand); 120 setOperationAction(ISD::SELECT_CC, VT, Expand); 121 setOperationAction(ISD::VSELECT, VT, Expand); 122 setOperationAction(ISD::SIGN_EXTEND_INREG, VT, Expand); 123 if (VT.isInteger()) { 124 setOperationAction(ISD::SHL, VT, Custom); 125 setOperationAction(ISD::SRA, VT, Custom); 126 setOperationAction(ISD::SRL, VT, Custom); 127 } 128 129 // Promote all bit-wise operations. 130 if (VT.isInteger() && VT != PromotedBitwiseVT) { 131 setOperationAction(ISD::AND, VT, Promote); 132 AddPromotedToType (ISD::AND, VT, PromotedBitwiseVT); 133 setOperationAction(ISD::OR, VT, Promote); 134 AddPromotedToType (ISD::OR, VT, PromotedBitwiseVT); 135 setOperationAction(ISD::XOR, VT, Promote); 136 AddPromotedToType (ISD::XOR, VT, PromotedBitwiseVT); 137 } 138 139 // Neon does not support vector divide/remainder operations. 140 setOperationAction(ISD::SDIV, VT, Expand); 141 setOperationAction(ISD::UDIV, VT, Expand); 142 setOperationAction(ISD::FDIV, VT, Expand); 143 setOperationAction(ISD::SREM, VT, Expand); 144 setOperationAction(ISD::UREM, VT, Expand); 145 setOperationAction(ISD::FREM, VT, Expand); 146 147 if (!VT.isFloatingPoint() && 148 VT != MVT::v2i64 && VT != MVT::v1i64) 149 for (unsigned Opcode : {ISD::SMIN, ISD::SMAX, ISD::UMIN, ISD::UMAX}) 150 setOperationAction(Opcode, VT, Legal); 151 } 152 153 void ARMTargetLowering::addDRTypeForNEON(MVT VT) { 154 addRegisterClass(VT, &ARM::DPRRegClass); 155 addTypeForNEON(VT, MVT::f64, MVT::v2i32); 156 } 157 158 void ARMTargetLowering::addQRTypeForNEON(MVT VT) { 159 addRegisterClass(VT, &ARM::DPairRegClass); 160 addTypeForNEON(VT, MVT::v2f64, MVT::v4i32); 161 } 162 163 ARMTargetLowering::ARMTargetLowering(const TargetMachine &TM, 164 const ARMSubtarget &STI) 165 : TargetLowering(TM), Subtarget(&STI) { 166 RegInfo = Subtarget->getRegisterInfo(); 167 Itins = Subtarget->getInstrItineraryData(); 168 169 setBooleanVectorContents(ZeroOrNegativeOneBooleanContent); 170 171 if (Subtarget->isTargetMachO()) { 172 // Uses VFP for Thumb libfuncs if available. 173 if (Subtarget->isThumb() && Subtarget->hasVFP2() && 174 Subtarget->hasARMOps() && !Subtarget->useSoftFloat()) { 175 static const struct { 176 const RTLIB::Libcall Op; 177 const char * const Name; 178 const ISD::CondCode Cond; 179 } LibraryCalls[] = { 180 // Single-precision floating-point arithmetic. 181 { RTLIB::ADD_F32, "__addsf3vfp", ISD::SETCC_INVALID }, 182 { RTLIB::SUB_F32, "__subsf3vfp", ISD::SETCC_INVALID }, 183 { RTLIB::MUL_F32, "__mulsf3vfp", ISD::SETCC_INVALID }, 184 { RTLIB::DIV_F32, "__divsf3vfp", ISD::SETCC_INVALID }, 185 186 // Double-precision floating-point arithmetic. 187 { RTLIB::ADD_F64, "__adddf3vfp", ISD::SETCC_INVALID }, 188 { RTLIB::SUB_F64, "__subdf3vfp", ISD::SETCC_INVALID }, 189 { RTLIB::MUL_F64, "__muldf3vfp", ISD::SETCC_INVALID }, 190 { RTLIB::DIV_F64, "__divdf3vfp", ISD::SETCC_INVALID }, 191 192 // Single-precision comparisons. 193 { RTLIB::OEQ_F32, "__eqsf2vfp", ISD::SETNE }, 194 { RTLIB::UNE_F32, "__nesf2vfp", ISD::SETNE }, 195 { RTLIB::OLT_F32, "__ltsf2vfp", ISD::SETNE }, 196 { RTLIB::OLE_F32, "__lesf2vfp", ISD::SETNE }, 197 { RTLIB::OGE_F32, "__gesf2vfp", ISD::SETNE }, 198 { RTLIB::OGT_F32, "__gtsf2vfp", ISD::SETNE }, 199 { RTLIB::UO_F32, "__unordsf2vfp", ISD::SETNE }, 200 { RTLIB::O_F32, "__unordsf2vfp", ISD::SETEQ }, 201 202 // Double-precision comparisons. 203 { RTLIB::OEQ_F64, "__eqdf2vfp", ISD::SETNE }, 204 { RTLIB::UNE_F64, "__nedf2vfp", ISD::SETNE }, 205 { RTLIB::OLT_F64, "__ltdf2vfp", ISD::SETNE }, 206 { RTLIB::OLE_F64, "__ledf2vfp", ISD::SETNE }, 207 { RTLIB::OGE_F64, "__gedf2vfp", ISD::SETNE }, 208 { RTLIB::OGT_F64, "__gtdf2vfp", ISD::SETNE }, 209 { RTLIB::UO_F64, "__unorddf2vfp", ISD::SETNE }, 210 { RTLIB::O_F64, "__unorddf2vfp", ISD::SETEQ }, 211 212 // Floating-point to integer conversions. 213 // i64 conversions are done via library routines even when generating VFP 214 // instructions, so use the same ones. 215 { RTLIB::FPTOSINT_F64_I32, "__fixdfsivfp", ISD::SETCC_INVALID }, 216 { RTLIB::FPTOUINT_F64_I32, "__fixunsdfsivfp", ISD::SETCC_INVALID }, 217 { RTLIB::FPTOSINT_F32_I32, "__fixsfsivfp", ISD::SETCC_INVALID }, 218 { RTLIB::FPTOUINT_F32_I32, "__fixunssfsivfp", ISD::SETCC_INVALID }, 219 220 // Conversions between floating types. 221 { RTLIB::FPROUND_F64_F32, "__truncdfsf2vfp", ISD::SETCC_INVALID }, 222 { RTLIB::FPEXT_F32_F64, "__extendsfdf2vfp", ISD::SETCC_INVALID }, 223 224 // Integer to floating-point conversions. 225 // i64 conversions are done via library routines even when generating VFP 226 // instructions, so use the same ones. 227 // FIXME: There appears to be some naming inconsistency in ARM libgcc: 228 // e.g., __floatunsidf vs. __floatunssidfvfp. 229 { RTLIB::SINTTOFP_I32_F64, "__floatsidfvfp", ISD::SETCC_INVALID }, 230 { RTLIB::UINTTOFP_I32_F64, "__floatunssidfvfp", ISD::SETCC_INVALID }, 231 { RTLIB::SINTTOFP_I32_F32, "__floatsisfvfp", ISD::SETCC_INVALID }, 232 { RTLIB::UINTTOFP_I32_F32, "__floatunssisfvfp", ISD::SETCC_INVALID }, 233 }; 234 235 for (const auto &LC : LibraryCalls) { 236 setLibcallName(LC.Op, LC.Name); 237 if (LC.Cond != ISD::SETCC_INVALID) 238 setCmpLibcallCC(LC.Op, LC.Cond); 239 } 240 } 241 242 // Set the correct calling convention for ARMv7k WatchOS. It's just 243 // AAPCS_VFP for functions as simple as libcalls. 244 if (Subtarget->isTargetWatchABI()) { 245 for (int i = 0; i < RTLIB::UNKNOWN_LIBCALL; ++i) 246 setLibcallCallingConv((RTLIB::Libcall)i, CallingConv::ARM_AAPCS_VFP); 247 } 248 } 249 250 // These libcalls are not available in 32-bit. 251 setLibcallName(RTLIB::SHL_I128, nullptr); 252 setLibcallName(RTLIB::SRL_I128, nullptr); 253 setLibcallName(RTLIB::SRA_I128, nullptr); 254 255 // RTLIB 256 if (Subtarget->isAAPCS_ABI() && 257 (Subtarget->isTargetAEABI() || Subtarget->isTargetGNUAEABI() || 258 Subtarget->isTargetMuslAEABI() || Subtarget->isTargetAndroid())) { 259 static const struct { 260 const RTLIB::Libcall Op; 261 const char * const Name; 262 const CallingConv::ID CC; 263 const ISD::CondCode Cond; 264 } LibraryCalls[] = { 265 // Double-precision floating-point arithmetic helper functions 266 // RTABI chapter 4.1.2, Table 2 267 { RTLIB::ADD_F64, "__aeabi_dadd", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 268 { RTLIB::DIV_F64, "__aeabi_ddiv", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 269 { RTLIB::MUL_F64, "__aeabi_dmul", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 270 { RTLIB::SUB_F64, "__aeabi_dsub", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 271 272 // Double-precision floating-point comparison helper functions 273 // RTABI chapter 4.1.2, Table 3 274 { RTLIB::OEQ_F64, "__aeabi_dcmpeq", CallingConv::ARM_AAPCS, ISD::SETNE }, 275 { RTLIB::UNE_F64, "__aeabi_dcmpeq", CallingConv::ARM_AAPCS, ISD::SETEQ }, 276 { RTLIB::OLT_F64, "__aeabi_dcmplt", CallingConv::ARM_AAPCS, ISD::SETNE }, 277 { RTLIB::OLE_F64, "__aeabi_dcmple", CallingConv::ARM_AAPCS, ISD::SETNE }, 278 { RTLIB::OGE_F64, "__aeabi_dcmpge", CallingConv::ARM_AAPCS, ISD::SETNE }, 279 { RTLIB::OGT_F64, "__aeabi_dcmpgt", CallingConv::ARM_AAPCS, ISD::SETNE }, 280 { RTLIB::UO_F64, "__aeabi_dcmpun", CallingConv::ARM_AAPCS, ISD::SETNE }, 281 { RTLIB::O_F64, "__aeabi_dcmpun", CallingConv::ARM_AAPCS, ISD::SETEQ }, 282 283 // Single-precision floating-point arithmetic helper functions 284 // RTABI chapter 4.1.2, Table 4 285 { RTLIB::ADD_F32, "__aeabi_fadd", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 286 { RTLIB::DIV_F32, "__aeabi_fdiv", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 287 { RTLIB::MUL_F32, "__aeabi_fmul", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 288 { RTLIB::SUB_F32, "__aeabi_fsub", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 289 290 // Single-precision floating-point comparison helper functions 291 // RTABI chapter 4.1.2, Table 5 292 { RTLIB::OEQ_F32, "__aeabi_fcmpeq", CallingConv::ARM_AAPCS, ISD::SETNE }, 293 { RTLIB::UNE_F32, "__aeabi_fcmpeq", CallingConv::ARM_AAPCS, ISD::SETEQ }, 294 { RTLIB::OLT_F32, "__aeabi_fcmplt", CallingConv::ARM_AAPCS, ISD::SETNE }, 295 { RTLIB::OLE_F32, "__aeabi_fcmple", CallingConv::ARM_AAPCS, ISD::SETNE }, 296 { RTLIB::OGE_F32, "__aeabi_fcmpge", CallingConv::ARM_AAPCS, ISD::SETNE }, 297 { RTLIB::OGT_F32, "__aeabi_fcmpgt", CallingConv::ARM_AAPCS, ISD::SETNE }, 298 { RTLIB::UO_F32, "__aeabi_fcmpun", CallingConv::ARM_AAPCS, ISD::SETNE }, 299 { RTLIB::O_F32, "__aeabi_fcmpun", CallingConv::ARM_AAPCS, ISD::SETEQ }, 300 301 // Floating-point to integer conversions. 302 // RTABI chapter 4.1.2, Table 6 303 { RTLIB::FPTOSINT_F64_I32, "__aeabi_d2iz", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 304 { RTLIB::FPTOUINT_F64_I32, "__aeabi_d2uiz", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 305 { RTLIB::FPTOSINT_F64_I64, "__aeabi_d2lz", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 306 { RTLIB::FPTOUINT_F64_I64, "__aeabi_d2ulz", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 307 { RTLIB::FPTOSINT_F32_I32, "__aeabi_f2iz", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 308 { RTLIB::FPTOUINT_F32_I32, "__aeabi_f2uiz", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 309 { RTLIB::FPTOSINT_F32_I64, "__aeabi_f2lz", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 310 { RTLIB::FPTOUINT_F32_I64, "__aeabi_f2ulz", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 311 312 // Conversions between floating types. 313 // RTABI chapter 4.1.2, Table 7 314 { RTLIB::FPROUND_F64_F32, "__aeabi_d2f", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 315 { RTLIB::FPROUND_F64_F16, "__aeabi_d2h", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 316 { RTLIB::FPEXT_F32_F64, "__aeabi_f2d", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 317 318 // Integer to floating-point conversions. 319 // RTABI chapter 4.1.2, Table 8 320 { RTLIB::SINTTOFP_I32_F64, "__aeabi_i2d", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 321 { RTLIB::UINTTOFP_I32_F64, "__aeabi_ui2d", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 322 { RTLIB::SINTTOFP_I64_F64, "__aeabi_l2d", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 323 { RTLIB::UINTTOFP_I64_F64, "__aeabi_ul2d", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 324 { RTLIB::SINTTOFP_I32_F32, "__aeabi_i2f", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 325 { RTLIB::UINTTOFP_I32_F32, "__aeabi_ui2f", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 326 { RTLIB::SINTTOFP_I64_F32, "__aeabi_l2f", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 327 { RTLIB::UINTTOFP_I64_F32, "__aeabi_ul2f", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 328 329 // Long long helper functions 330 // RTABI chapter 4.2, Table 9 331 { RTLIB::MUL_I64, "__aeabi_lmul", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 332 { RTLIB::SHL_I64, "__aeabi_llsl", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 333 { RTLIB::SRL_I64, "__aeabi_llsr", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 334 { RTLIB::SRA_I64, "__aeabi_lasr", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 335 336 // Integer division functions 337 // RTABI chapter 4.3.1 338 { RTLIB::SDIV_I8, "__aeabi_idiv", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 339 { RTLIB::SDIV_I16, "__aeabi_idiv", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 340 { RTLIB::SDIV_I32, "__aeabi_idiv", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 341 { RTLIB::SDIV_I64, "__aeabi_ldivmod", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 342 { RTLIB::UDIV_I8, "__aeabi_uidiv", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 343 { RTLIB::UDIV_I16, "__aeabi_uidiv", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 344 { RTLIB::UDIV_I32, "__aeabi_uidiv", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 345 { RTLIB::UDIV_I64, "__aeabi_uldivmod", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 346 }; 347 348 for (const auto &LC : LibraryCalls) { 349 setLibcallName(LC.Op, LC.Name); 350 setLibcallCallingConv(LC.Op, LC.CC); 351 if (LC.Cond != ISD::SETCC_INVALID) 352 setCmpLibcallCC(LC.Op, LC.Cond); 353 } 354 355 // EABI dependent RTLIB 356 if (TM.Options.EABIVersion == EABI::EABI4 || 357 TM.Options.EABIVersion == EABI::EABI5) { 358 static const struct { 359 const RTLIB::Libcall Op; 360 const char *const Name; 361 const CallingConv::ID CC; 362 const ISD::CondCode Cond; 363 } MemOpsLibraryCalls[] = { 364 // Memory operations 365 // RTABI chapter 4.3.4 366 { RTLIB::MEMCPY, "__aeabi_memcpy", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 367 { RTLIB::MEMMOVE, "__aeabi_memmove", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 368 { RTLIB::MEMSET, "__aeabi_memset", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 369 }; 370 371 for (const auto &LC : MemOpsLibraryCalls) { 372 setLibcallName(LC.Op, LC.Name); 373 setLibcallCallingConv(LC.Op, LC.CC); 374 if (LC.Cond != ISD::SETCC_INVALID) 375 setCmpLibcallCC(LC.Op, LC.Cond); 376 } 377 } 378 } 379 380 if (Subtarget->isTargetWindows()) { 381 static const struct { 382 const RTLIB::Libcall Op; 383 const char * const Name; 384 const CallingConv::ID CC; 385 } LibraryCalls[] = { 386 { RTLIB::FPTOSINT_F32_I64, "__stoi64", CallingConv::ARM_AAPCS_VFP }, 387 { RTLIB::FPTOSINT_F64_I64, "__dtoi64", CallingConv::ARM_AAPCS_VFP }, 388 { RTLIB::FPTOUINT_F32_I64, "__stou64", CallingConv::ARM_AAPCS_VFP }, 389 { RTLIB::FPTOUINT_F64_I64, "__dtou64", CallingConv::ARM_AAPCS_VFP }, 390 { RTLIB::SINTTOFP_I64_F32, "__i64tos", CallingConv::ARM_AAPCS_VFP }, 391 { RTLIB::SINTTOFP_I64_F64, "__i64tod", CallingConv::ARM_AAPCS_VFP }, 392 { RTLIB::UINTTOFP_I64_F32, "__u64tos", CallingConv::ARM_AAPCS_VFP }, 393 { RTLIB::UINTTOFP_I64_F64, "__u64tod", CallingConv::ARM_AAPCS_VFP }, 394 }; 395 396 for (const auto &LC : LibraryCalls) { 397 setLibcallName(LC.Op, LC.Name); 398 setLibcallCallingConv(LC.Op, LC.CC); 399 } 400 } 401 402 // Use divmod compiler-rt calls for iOS 5.0 and later. 403 if (Subtarget->isTargetWatchOS() || 404 (Subtarget->isTargetIOS() && 405 !Subtarget->getTargetTriple().isOSVersionLT(5, 0))) { 406 setLibcallName(RTLIB::SDIVREM_I32, "__divmodsi4"); 407 setLibcallName(RTLIB::UDIVREM_I32, "__udivmodsi4"); 408 } 409 410 // The half <-> float conversion functions are always soft-float on 411 // non-watchos platforms, but are needed for some targets which use a 412 // hard-float calling convention by default. 413 if (!Subtarget->isTargetWatchABI()) { 414 if (Subtarget->isAAPCS_ABI()) { 415 setLibcallCallingConv(RTLIB::FPROUND_F32_F16, CallingConv::ARM_AAPCS); 416 setLibcallCallingConv(RTLIB::FPROUND_F64_F16, CallingConv::ARM_AAPCS); 417 setLibcallCallingConv(RTLIB::FPEXT_F16_F32, CallingConv::ARM_AAPCS); 418 } else { 419 setLibcallCallingConv(RTLIB::FPROUND_F32_F16, CallingConv::ARM_APCS); 420 setLibcallCallingConv(RTLIB::FPROUND_F64_F16, CallingConv::ARM_APCS); 421 setLibcallCallingConv(RTLIB::FPEXT_F16_F32, CallingConv::ARM_APCS); 422 } 423 } 424 425 // In EABI, these functions have an __aeabi_ prefix, but in GNUEABI they have 426 // a __gnu_ prefix (which is the default). 427 if (Subtarget->isTargetAEABI()) { 428 setLibcallName(RTLIB::FPROUND_F32_F16, "__aeabi_f2h"); 429 setLibcallName(RTLIB::FPROUND_F64_F16, "__aeabi_d2h"); 430 setLibcallName(RTLIB::FPEXT_F16_F32, "__aeabi_h2f"); 431 } 432 433 if (Subtarget->isThumb1Only()) 434 addRegisterClass(MVT::i32, &ARM::tGPRRegClass); 435 else 436 addRegisterClass(MVT::i32, &ARM::GPRRegClass); 437 if (!Subtarget->useSoftFloat() && Subtarget->hasVFP2() && 438 !Subtarget->isThumb1Only()) { 439 addRegisterClass(MVT::f32, &ARM::SPRRegClass); 440 addRegisterClass(MVT::f64, &ARM::DPRRegClass); 441 } 442 443 for (MVT VT : MVT::vector_valuetypes()) { 444 for (MVT InnerVT : MVT::vector_valuetypes()) { 445 setTruncStoreAction(VT, InnerVT, Expand); 446 setLoadExtAction(ISD::SEXTLOAD, VT, InnerVT, Expand); 447 setLoadExtAction(ISD::ZEXTLOAD, VT, InnerVT, Expand); 448 setLoadExtAction(ISD::EXTLOAD, VT, InnerVT, Expand); 449 } 450 451 setOperationAction(ISD::MULHS, VT, Expand); 452 setOperationAction(ISD::SMUL_LOHI, VT, Expand); 453 setOperationAction(ISD::MULHU, VT, Expand); 454 setOperationAction(ISD::UMUL_LOHI, VT, Expand); 455 456 setOperationAction(ISD::BSWAP, VT, Expand); 457 } 458 459 setOperationAction(ISD::ConstantFP, MVT::f32, Custom); 460 setOperationAction(ISD::ConstantFP, MVT::f64, Custom); 461 462 setOperationAction(ISD::READ_REGISTER, MVT::i64, Custom); 463 setOperationAction(ISD::WRITE_REGISTER, MVT::i64, Custom); 464 465 if (Subtarget->hasNEON()) { 466 addDRTypeForNEON(MVT::v2f32); 467 addDRTypeForNEON(MVT::v8i8); 468 addDRTypeForNEON(MVT::v4i16); 469 addDRTypeForNEON(MVT::v2i32); 470 addDRTypeForNEON(MVT::v1i64); 471 472 addQRTypeForNEON(MVT::v4f32); 473 addQRTypeForNEON(MVT::v2f64); 474 addQRTypeForNEON(MVT::v16i8); 475 addQRTypeForNEON(MVT::v8i16); 476 addQRTypeForNEON(MVT::v4i32); 477 addQRTypeForNEON(MVT::v2i64); 478 479 // v2f64 is legal so that QR subregs can be extracted as f64 elements, but 480 // neither Neon nor VFP support any arithmetic operations on it. 481 // The same with v4f32. But keep in mind that vadd, vsub, vmul are natively 482 // supported for v4f32. 483 setOperationAction(ISD::FADD, MVT::v2f64, Expand); 484 setOperationAction(ISD::FSUB, MVT::v2f64, Expand); 485 setOperationAction(ISD::FMUL, MVT::v2f64, Expand); 486 // FIXME: Code duplication: FDIV and FREM are expanded always, see 487 // ARMTargetLowering::addTypeForNEON method for details. 488 setOperationAction(ISD::FDIV, MVT::v2f64, Expand); 489 setOperationAction(ISD::FREM, MVT::v2f64, Expand); 490 // FIXME: Create unittest. 491 // In another words, find a way when "copysign" appears in DAG with vector 492 // operands. 493 setOperationAction(ISD::FCOPYSIGN, MVT::v2f64, Expand); 494 // FIXME: Code duplication: SETCC has custom operation action, see 495 // ARMTargetLowering::addTypeForNEON method for details. 496 setOperationAction(ISD::SETCC, MVT::v2f64, Expand); 497 // FIXME: Create unittest for FNEG and for FABS. 498 setOperationAction(ISD::FNEG, MVT::v2f64, Expand); 499 setOperationAction(ISD::FABS, MVT::v2f64, Expand); 500 setOperationAction(ISD::FSQRT, MVT::v2f64, Expand); 501 setOperationAction(ISD::FSIN, MVT::v2f64, Expand); 502 setOperationAction(ISD::FCOS, MVT::v2f64, Expand); 503 setOperationAction(ISD::FPOWI, MVT::v2f64, Expand); 504 setOperationAction(ISD::FPOW, MVT::v2f64, Expand); 505 setOperationAction(ISD::FLOG, MVT::v2f64, Expand); 506 setOperationAction(ISD::FLOG2, MVT::v2f64, Expand); 507 setOperationAction(ISD::FLOG10, MVT::v2f64, Expand); 508 setOperationAction(ISD::FEXP, MVT::v2f64, Expand); 509 setOperationAction(ISD::FEXP2, MVT::v2f64, Expand); 510 // FIXME: Create unittest for FCEIL, FTRUNC, FRINT, FNEARBYINT, FFLOOR. 511 setOperationAction(ISD::FCEIL, MVT::v2f64, Expand); 512 setOperationAction(ISD::FTRUNC, MVT::v2f64, Expand); 513 setOperationAction(ISD::FRINT, MVT::v2f64, Expand); 514 setOperationAction(ISD::FNEARBYINT, MVT::v2f64, Expand); 515 setOperationAction(ISD::FFLOOR, MVT::v2f64, Expand); 516 setOperationAction(ISD::FMA, MVT::v2f64, Expand); 517 518 setOperationAction(ISD::FSQRT, MVT::v4f32, Expand); 519 setOperationAction(ISD::FSIN, MVT::v4f32, Expand); 520 setOperationAction(ISD::FCOS, MVT::v4f32, Expand); 521 setOperationAction(ISD::FPOWI, MVT::v4f32, Expand); 522 setOperationAction(ISD::FPOW, MVT::v4f32, Expand); 523 setOperationAction(ISD::FLOG, MVT::v4f32, Expand); 524 setOperationAction(ISD::FLOG2, MVT::v4f32, Expand); 525 setOperationAction(ISD::FLOG10, MVT::v4f32, Expand); 526 setOperationAction(ISD::FEXP, MVT::v4f32, Expand); 527 setOperationAction(ISD::FEXP2, MVT::v4f32, Expand); 528 setOperationAction(ISD::FCEIL, MVT::v4f32, Expand); 529 setOperationAction(ISD::FTRUNC, MVT::v4f32, Expand); 530 setOperationAction(ISD::FRINT, MVT::v4f32, Expand); 531 setOperationAction(ISD::FNEARBYINT, MVT::v4f32, Expand); 532 setOperationAction(ISD::FFLOOR, MVT::v4f32, Expand); 533 534 // Mark v2f32 intrinsics. 535 setOperationAction(ISD::FSQRT, MVT::v2f32, Expand); 536 setOperationAction(ISD::FSIN, MVT::v2f32, Expand); 537 setOperationAction(ISD::FCOS, MVT::v2f32, Expand); 538 setOperationAction(ISD::FPOWI, MVT::v2f32, Expand); 539 setOperationAction(ISD::FPOW, MVT::v2f32, Expand); 540 setOperationAction(ISD::FLOG, MVT::v2f32, Expand); 541 setOperationAction(ISD::FLOG2, MVT::v2f32, Expand); 542 setOperationAction(ISD::FLOG10, MVT::v2f32, Expand); 543 setOperationAction(ISD::FEXP, MVT::v2f32, Expand); 544 setOperationAction(ISD::FEXP2, MVT::v2f32, Expand); 545 setOperationAction(ISD::FCEIL, MVT::v2f32, Expand); 546 setOperationAction(ISD::FTRUNC, MVT::v2f32, Expand); 547 setOperationAction(ISD::FRINT, MVT::v2f32, Expand); 548 setOperationAction(ISD::FNEARBYINT, MVT::v2f32, Expand); 549 setOperationAction(ISD::FFLOOR, MVT::v2f32, Expand); 550 551 // Neon does not support some operations on v1i64 and v2i64 types. 552 setOperationAction(ISD::MUL, MVT::v1i64, Expand); 553 // Custom handling for some quad-vector types to detect VMULL. 554 setOperationAction(ISD::MUL, MVT::v8i16, Custom); 555 setOperationAction(ISD::MUL, MVT::v4i32, Custom); 556 setOperationAction(ISD::MUL, MVT::v2i64, Custom); 557 // Custom handling for some vector types to avoid expensive expansions 558 setOperationAction(ISD::SDIV, MVT::v4i16, Custom); 559 setOperationAction(ISD::SDIV, MVT::v8i8, Custom); 560 setOperationAction(ISD::UDIV, MVT::v4i16, Custom); 561 setOperationAction(ISD::UDIV, MVT::v8i8, Custom); 562 setOperationAction(ISD::SETCC, MVT::v1i64, Expand); 563 setOperationAction(ISD::SETCC, MVT::v2i64, Expand); 564 // Neon does not have single instruction SINT_TO_FP and UINT_TO_FP with 565 // a destination type that is wider than the source, and nor does 566 // it have a FP_TO_[SU]INT instruction with a narrower destination than 567 // source. 568 setOperationAction(ISD::SINT_TO_FP, MVT::v4i16, Custom); 569 setOperationAction(ISD::UINT_TO_FP, MVT::v4i16, Custom); 570 setOperationAction(ISD::FP_TO_UINT, MVT::v4i16, Custom); 571 setOperationAction(ISD::FP_TO_SINT, MVT::v4i16, Custom); 572 573 setOperationAction(ISD::FP_ROUND, MVT::v2f32, Expand); 574 setOperationAction(ISD::FP_EXTEND, MVT::v2f64, Expand); 575 576 // NEON does not have single instruction CTPOP for vectors with element 577 // types wider than 8-bits. However, custom lowering can leverage the 578 // v8i8/v16i8 vcnt instruction. 579 setOperationAction(ISD::CTPOP, MVT::v2i32, Custom); 580 setOperationAction(ISD::CTPOP, MVT::v4i32, Custom); 581 setOperationAction(ISD::CTPOP, MVT::v4i16, Custom); 582 setOperationAction(ISD::CTPOP, MVT::v8i16, Custom); 583 setOperationAction(ISD::CTPOP, MVT::v1i64, Expand); 584 setOperationAction(ISD::CTPOP, MVT::v2i64, Expand); 585 586 setOperationAction(ISD::CTLZ, MVT::v1i64, Expand); 587 setOperationAction(ISD::CTLZ, MVT::v2i64, Expand); 588 589 // NEON does not have single instruction CTTZ for vectors. 590 setOperationAction(ISD::CTTZ, MVT::v8i8, Custom); 591 setOperationAction(ISD::CTTZ, MVT::v4i16, Custom); 592 setOperationAction(ISD::CTTZ, MVT::v2i32, Custom); 593 setOperationAction(ISD::CTTZ, MVT::v1i64, Custom); 594 595 setOperationAction(ISD::CTTZ, MVT::v16i8, Custom); 596 setOperationAction(ISD::CTTZ, MVT::v8i16, Custom); 597 setOperationAction(ISD::CTTZ, MVT::v4i32, Custom); 598 setOperationAction(ISD::CTTZ, MVT::v2i64, Custom); 599 600 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::v8i8, Custom); 601 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::v4i16, Custom); 602 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::v2i32, Custom); 603 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::v1i64, Custom); 604 605 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::v16i8, Custom); 606 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::v8i16, Custom); 607 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::v4i32, Custom); 608 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::v2i64, Custom); 609 610 // NEON only has FMA instructions as of VFP4. 611 if (!Subtarget->hasVFP4()) { 612 setOperationAction(ISD::FMA, MVT::v2f32, Expand); 613 setOperationAction(ISD::FMA, MVT::v4f32, Expand); 614 } 615 616 setTargetDAGCombine(ISD::INTRINSIC_VOID); 617 setTargetDAGCombine(ISD::INTRINSIC_W_CHAIN); 618 setTargetDAGCombine(ISD::INTRINSIC_WO_CHAIN); 619 setTargetDAGCombine(ISD::SHL); 620 setTargetDAGCombine(ISD::SRL); 621 setTargetDAGCombine(ISD::SRA); 622 setTargetDAGCombine(ISD::SIGN_EXTEND); 623 setTargetDAGCombine(ISD::ZERO_EXTEND); 624 setTargetDAGCombine(ISD::ANY_EXTEND); 625 setTargetDAGCombine(ISD::BUILD_VECTOR); 626 setTargetDAGCombine(ISD::VECTOR_SHUFFLE); 627 setTargetDAGCombine(ISD::INSERT_VECTOR_ELT); 628 setTargetDAGCombine(ISD::STORE); 629 setTargetDAGCombine(ISD::FP_TO_SINT); 630 setTargetDAGCombine(ISD::FP_TO_UINT); 631 setTargetDAGCombine(ISD::FDIV); 632 setTargetDAGCombine(ISD::LOAD); 633 634 // It is legal to extload from v4i8 to v4i16 or v4i32. 635 for (MVT Ty : {MVT::v8i8, MVT::v4i8, MVT::v2i8, MVT::v4i16, MVT::v2i16, 636 MVT::v2i32}) { 637 for (MVT VT : MVT::integer_vector_valuetypes()) { 638 setLoadExtAction(ISD::EXTLOAD, VT, Ty, Legal); 639 setLoadExtAction(ISD::ZEXTLOAD, VT, Ty, Legal); 640 setLoadExtAction(ISD::SEXTLOAD, VT, Ty, Legal); 641 } 642 } 643 } 644 645 // ARM and Thumb2 support UMLAL/SMLAL. 646 if (!Subtarget->isThumb1Only()) 647 setTargetDAGCombine(ISD::ADDC); 648 649 if (Subtarget->isFPOnlySP()) { 650 // When targeting a floating-point unit with only single-precision 651 // operations, f64 is legal for the few double-precision instructions which 652 // are present However, no double-precision operations other than moves, 653 // loads and stores are provided by the hardware. 654 setOperationAction(ISD::FADD, MVT::f64, Expand); 655 setOperationAction(ISD::FSUB, MVT::f64, Expand); 656 setOperationAction(ISD::FMUL, MVT::f64, Expand); 657 setOperationAction(ISD::FMA, MVT::f64, Expand); 658 setOperationAction(ISD::FDIV, MVT::f64, Expand); 659 setOperationAction(ISD::FREM, MVT::f64, Expand); 660 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand); 661 setOperationAction(ISD::FGETSIGN, MVT::f64, Expand); 662 setOperationAction(ISD::FNEG, MVT::f64, Expand); 663 setOperationAction(ISD::FABS, MVT::f64, Expand); 664 setOperationAction(ISD::FSQRT, MVT::f64, Expand); 665 setOperationAction(ISD::FSIN, MVT::f64, Expand); 666 setOperationAction(ISD::FCOS, MVT::f64, Expand); 667 setOperationAction(ISD::FPOWI, MVT::f64, Expand); 668 setOperationAction(ISD::FPOW, MVT::f64, Expand); 669 setOperationAction(ISD::FLOG, MVT::f64, Expand); 670 setOperationAction(ISD::FLOG2, MVT::f64, Expand); 671 setOperationAction(ISD::FLOG10, MVT::f64, Expand); 672 setOperationAction(ISD::FEXP, MVT::f64, Expand); 673 setOperationAction(ISD::FEXP2, MVT::f64, Expand); 674 setOperationAction(ISD::FCEIL, MVT::f64, Expand); 675 setOperationAction(ISD::FTRUNC, MVT::f64, Expand); 676 setOperationAction(ISD::FRINT, MVT::f64, Expand); 677 setOperationAction(ISD::FNEARBYINT, MVT::f64, Expand); 678 setOperationAction(ISD::FFLOOR, MVT::f64, Expand); 679 setOperationAction(ISD::SINT_TO_FP, MVT::i32, Custom); 680 setOperationAction(ISD::UINT_TO_FP, MVT::i32, Custom); 681 setOperationAction(ISD::FP_TO_SINT, MVT::i32, Custom); 682 setOperationAction(ISD::FP_TO_UINT, MVT::i32, Custom); 683 setOperationAction(ISD::FP_TO_SINT, MVT::f64, Custom); 684 setOperationAction(ISD::FP_TO_UINT, MVT::f64, Custom); 685 setOperationAction(ISD::FP_ROUND, MVT::f32, Custom); 686 setOperationAction(ISD::FP_EXTEND, MVT::f64, Custom); 687 } 688 689 computeRegisterProperties(Subtarget->getRegisterInfo()); 690 691 // ARM does not have floating-point extending loads. 692 for (MVT VT : MVT::fp_valuetypes()) { 693 setLoadExtAction(ISD::EXTLOAD, VT, MVT::f32, Expand); 694 setLoadExtAction(ISD::EXTLOAD, VT, MVT::f16, Expand); 695 } 696 697 // ... or truncating stores 698 setTruncStoreAction(MVT::f64, MVT::f32, Expand); 699 setTruncStoreAction(MVT::f32, MVT::f16, Expand); 700 setTruncStoreAction(MVT::f64, MVT::f16, Expand); 701 702 // ARM does not have i1 sign extending load. 703 for (MVT VT : MVT::integer_valuetypes()) 704 setLoadExtAction(ISD::SEXTLOAD, VT, MVT::i1, Promote); 705 706 // ARM supports all 4 flavors of integer indexed load / store. 707 if (!Subtarget->isThumb1Only()) { 708 for (unsigned im = (unsigned)ISD::PRE_INC; 709 im != (unsigned)ISD::LAST_INDEXED_MODE; ++im) { 710 setIndexedLoadAction(im, MVT::i1, Legal); 711 setIndexedLoadAction(im, MVT::i8, Legal); 712 setIndexedLoadAction(im, MVT::i16, Legal); 713 setIndexedLoadAction(im, MVT::i32, Legal); 714 setIndexedStoreAction(im, MVT::i1, Legal); 715 setIndexedStoreAction(im, MVT::i8, Legal); 716 setIndexedStoreAction(im, MVT::i16, Legal); 717 setIndexedStoreAction(im, MVT::i32, Legal); 718 } 719 } 720 721 setOperationAction(ISD::SADDO, MVT::i32, Custom); 722 setOperationAction(ISD::UADDO, MVT::i32, Custom); 723 setOperationAction(ISD::SSUBO, MVT::i32, Custom); 724 setOperationAction(ISD::USUBO, MVT::i32, Custom); 725 726 // i64 operation support. 727 setOperationAction(ISD::MUL, MVT::i64, Expand); 728 setOperationAction(ISD::MULHU, MVT::i32, Expand); 729 if (Subtarget->isThumb1Only()) { 730 setOperationAction(ISD::UMUL_LOHI, MVT::i32, Expand); 731 setOperationAction(ISD::SMUL_LOHI, MVT::i32, Expand); 732 } 733 if (Subtarget->isThumb1Only() || !Subtarget->hasV6Ops() 734 || (Subtarget->isThumb2() && !Subtarget->hasDSP())) 735 setOperationAction(ISD::MULHS, MVT::i32, Expand); 736 737 setOperationAction(ISD::SHL_PARTS, MVT::i32, Custom); 738 setOperationAction(ISD::SRA_PARTS, MVT::i32, Custom); 739 setOperationAction(ISD::SRL_PARTS, MVT::i32, Custom); 740 setOperationAction(ISD::SRL, MVT::i64, Custom); 741 setOperationAction(ISD::SRA, MVT::i64, Custom); 742 743 if (!Subtarget->isThumb1Only()) { 744 // FIXME: We should do this for Thumb1 as well. 745 setOperationAction(ISD::ADDC, MVT::i32, Custom); 746 setOperationAction(ISD::ADDE, MVT::i32, Custom); 747 setOperationAction(ISD::SUBC, MVT::i32, Custom); 748 setOperationAction(ISD::SUBE, MVT::i32, Custom); 749 } 750 751 if (!Subtarget->isThumb1Only() && Subtarget->hasV6T2Ops()) 752 setOperationAction(ISD::BITREVERSE, MVT::i32, Legal); 753 754 // ARM does not have ROTL. 755 setOperationAction(ISD::ROTL, MVT::i32, Expand); 756 for (MVT VT : MVT::vector_valuetypes()) { 757 setOperationAction(ISD::ROTL, VT, Expand); 758 setOperationAction(ISD::ROTR, VT, Expand); 759 } 760 setOperationAction(ISD::CTTZ, MVT::i32, Custom); 761 setOperationAction(ISD::CTPOP, MVT::i32, Expand); 762 if (!Subtarget->hasV5TOps() || Subtarget->isThumb1Only()) 763 setOperationAction(ISD::CTLZ, MVT::i32, Expand); 764 765 // @llvm.readcyclecounter requires the Performance Monitors extension. 766 // Default to the 0 expansion on unsupported platforms. 767 // FIXME: Technically there are older ARM CPUs that have 768 // implementation-specific ways of obtaining this information. 769 if (Subtarget->hasPerfMon()) 770 setOperationAction(ISD::READCYCLECOUNTER, MVT::i64, Custom); 771 772 // Only ARMv6 has BSWAP. 773 if (!Subtarget->hasV6Ops()) 774 setOperationAction(ISD::BSWAP, MVT::i32, Expand); 775 776 bool hasDivide = Subtarget->isThumb() ? Subtarget->hasDivide() 777 : Subtarget->hasDivideInARMMode(); 778 if (!hasDivide) { 779 // These are expanded into libcalls if the cpu doesn't have HW divider. 780 setOperationAction(ISD::SDIV, MVT::i32, LibCall); 781 setOperationAction(ISD::UDIV, MVT::i32, LibCall); 782 } 783 784 if (Subtarget->isTargetWindows() && !Subtarget->hasDivide()) { 785 setOperationAction(ISD::SDIV, MVT::i32, Custom); 786 setOperationAction(ISD::UDIV, MVT::i32, Custom); 787 788 setOperationAction(ISD::SDIV, MVT::i64, Custom); 789 setOperationAction(ISD::UDIV, MVT::i64, Custom); 790 } 791 792 setOperationAction(ISD::SREM, MVT::i32, Expand); 793 setOperationAction(ISD::UREM, MVT::i32, Expand); 794 // Register based DivRem for AEABI (RTABI 4.2) 795 if (Subtarget->isTargetAEABI() || Subtarget->isTargetAndroid() || 796 Subtarget->isTargetGNUAEABI() || Subtarget->isTargetMuslAEABI()) { 797 setOperationAction(ISD::SREM, MVT::i64, Custom); 798 setOperationAction(ISD::UREM, MVT::i64, Custom); 799 800 setLibcallName(RTLIB::SDIVREM_I8, "__aeabi_idivmod"); 801 setLibcallName(RTLIB::SDIVREM_I16, "__aeabi_idivmod"); 802 setLibcallName(RTLIB::SDIVREM_I32, "__aeabi_idivmod"); 803 setLibcallName(RTLIB::SDIVREM_I64, "__aeabi_ldivmod"); 804 setLibcallName(RTLIB::UDIVREM_I8, "__aeabi_uidivmod"); 805 setLibcallName(RTLIB::UDIVREM_I16, "__aeabi_uidivmod"); 806 setLibcallName(RTLIB::UDIVREM_I32, "__aeabi_uidivmod"); 807 setLibcallName(RTLIB::UDIVREM_I64, "__aeabi_uldivmod"); 808 809 setLibcallCallingConv(RTLIB::SDIVREM_I8, CallingConv::ARM_AAPCS); 810 setLibcallCallingConv(RTLIB::SDIVREM_I16, CallingConv::ARM_AAPCS); 811 setLibcallCallingConv(RTLIB::SDIVREM_I32, CallingConv::ARM_AAPCS); 812 setLibcallCallingConv(RTLIB::SDIVREM_I64, CallingConv::ARM_AAPCS); 813 setLibcallCallingConv(RTLIB::UDIVREM_I8, CallingConv::ARM_AAPCS); 814 setLibcallCallingConv(RTLIB::UDIVREM_I16, CallingConv::ARM_AAPCS); 815 setLibcallCallingConv(RTLIB::UDIVREM_I32, CallingConv::ARM_AAPCS); 816 setLibcallCallingConv(RTLIB::UDIVREM_I64, CallingConv::ARM_AAPCS); 817 818 setOperationAction(ISD::SDIVREM, MVT::i32, Custom); 819 setOperationAction(ISD::UDIVREM, MVT::i32, Custom); 820 setOperationAction(ISD::SDIVREM, MVT::i64, Custom); 821 setOperationAction(ISD::UDIVREM, MVT::i64, Custom); 822 } else { 823 setOperationAction(ISD::SDIVREM, MVT::i32, Expand); 824 setOperationAction(ISD::UDIVREM, MVT::i32, Expand); 825 } 826 827 setOperationAction(ISD::GlobalAddress, MVT::i32, Custom); 828 setOperationAction(ISD::ConstantPool, MVT::i32, Custom); 829 setOperationAction(ISD::GlobalTLSAddress, MVT::i32, Custom); 830 setOperationAction(ISD::BlockAddress, MVT::i32, Custom); 831 832 setOperationAction(ISD::TRAP, MVT::Other, Legal); 833 834 // Use the default implementation. 835 setOperationAction(ISD::VASTART, MVT::Other, Custom); 836 setOperationAction(ISD::VAARG, MVT::Other, Expand); 837 setOperationAction(ISD::VACOPY, MVT::Other, Expand); 838 setOperationAction(ISD::VAEND, MVT::Other, Expand); 839 setOperationAction(ISD::STACKSAVE, MVT::Other, Expand); 840 setOperationAction(ISD::STACKRESTORE, MVT::Other, Expand); 841 842 if (Subtarget->getTargetTriple().isWindowsItaniumEnvironment()) 843 setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i32, Custom); 844 else 845 setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i32, Expand); 846 847 // ARMv6 Thumb1 (except for CPUs that support dmb / dsb) and earlier use 848 // the default expansion. 849 InsertFencesForAtomic = false; 850 if (Subtarget->hasAnyDataBarrier() && 851 (!Subtarget->isThumb() || Subtarget->hasV8MBaselineOps())) { 852 // ATOMIC_FENCE needs custom lowering; the others should have been expanded 853 // to ldrex/strex loops already. 854 setOperationAction(ISD::ATOMIC_FENCE, MVT::Other, Custom); 855 if (!Subtarget->isThumb() || !Subtarget->isMClass()) 856 setOperationAction(ISD::ATOMIC_CMP_SWAP, MVT::i64, Custom); 857 858 // On v8, we have particularly efficient implementations of atomic fences 859 // if they can be combined with nearby atomic loads and stores. 860 if (!Subtarget->hasV8Ops() || getTargetMachine().getOptLevel() == 0) { 861 // Automatically insert fences (dmb ish) around ATOMIC_SWAP etc. 862 InsertFencesForAtomic = true; 863 } 864 } else { 865 // If there's anything we can use as a barrier, go through custom lowering 866 // for ATOMIC_FENCE. 867 setOperationAction(ISD::ATOMIC_FENCE, MVT::Other, 868 Subtarget->hasAnyDataBarrier() ? Custom : Expand); 869 870 // Set them all for expansion, which will force libcalls. 871 setOperationAction(ISD::ATOMIC_CMP_SWAP, MVT::i32, Expand); 872 setOperationAction(ISD::ATOMIC_SWAP, MVT::i32, Expand); 873 setOperationAction(ISD::ATOMIC_LOAD_ADD, MVT::i32, Expand); 874 setOperationAction(ISD::ATOMIC_LOAD_SUB, MVT::i32, Expand); 875 setOperationAction(ISD::ATOMIC_LOAD_AND, MVT::i32, Expand); 876 setOperationAction(ISD::ATOMIC_LOAD_OR, MVT::i32, Expand); 877 setOperationAction(ISD::ATOMIC_LOAD_XOR, MVT::i32, Expand); 878 setOperationAction(ISD::ATOMIC_LOAD_NAND, MVT::i32, Expand); 879 setOperationAction(ISD::ATOMIC_LOAD_MIN, MVT::i32, Expand); 880 setOperationAction(ISD::ATOMIC_LOAD_MAX, MVT::i32, Expand); 881 setOperationAction(ISD::ATOMIC_LOAD_UMIN, MVT::i32, Expand); 882 setOperationAction(ISD::ATOMIC_LOAD_UMAX, MVT::i32, Expand); 883 // Mark ATOMIC_LOAD and ATOMIC_STORE custom so we can handle the 884 // Unordered/Monotonic case. 885 setOperationAction(ISD::ATOMIC_LOAD, MVT::i32, Custom); 886 setOperationAction(ISD::ATOMIC_STORE, MVT::i32, Custom); 887 } 888 889 setOperationAction(ISD::PREFETCH, MVT::Other, Custom); 890 891 // Requires SXTB/SXTH, available on v6 and up in both ARM and Thumb modes. 892 if (!Subtarget->hasV6Ops()) { 893 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i16, Expand); 894 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i8, Expand); 895 } 896 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1, Expand); 897 898 if (!Subtarget->useSoftFloat() && Subtarget->hasVFP2() && 899 !Subtarget->isThumb1Only()) { 900 // Turn f64->i64 into VMOVRRD, i64 -> f64 to VMOVDRR 901 // iff target supports vfp2. 902 setOperationAction(ISD::BITCAST, MVT::i64, Custom); 903 setOperationAction(ISD::FLT_ROUNDS_, MVT::i32, Custom); 904 } 905 906 // We want to custom lower some of our intrinsics. 907 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom); 908 setOperationAction(ISD::EH_SJLJ_SETJMP, MVT::i32, Custom); 909 setOperationAction(ISD::EH_SJLJ_LONGJMP, MVT::Other, Custom); 910 setOperationAction(ISD::EH_SJLJ_SETUP_DISPATCH, MVT::Other, Custom); 911 if (Subtarget->useSjLjEH()) 912 setLibcallName(RTLIB::UNWIND_RESUME, "_Unwind_SjLj_Resume"); 913 914 setOperationAction(ISD::SETCC, MVT::i32, Expand); 915 setOperationAction(ISD::SETCC, MVT::f32, Expand); 916 setOperationAction(ISD::SETCC, MVT::f64, Expand); 917 setOperationAction(ISD::SELECT, MVT::i32, Custom); 918 setOperationAction(ISD::SELECT, MVT::f32, Custom); 919 setOperationAction(ISD::SELECT, MVT::f64, Custom); 920 setOperationAction(ISD::SELECT_CC, MVT::i32, Custom); 921 setOperationAction(ISD::SELECT_CC, MVT::f32, Custom); 922 setOperationAction(ISD::SELECT_CC, MVT::f64, Custom); 923 924 // Thumb-1 cannot currently select ARMISD::SUBE. 925 if (!Subtarget->isThumb1Only()) 926 setOperationAction(ISD::SETCCE, MVT::i32, Custom); 927 928 setOperationAction(ISD::BRCOND, MVT::Other, Expand); 929 setOperationAction(ISD::BR_CC, MVT::i32, Custom); 930 setOperationAction(ISD::BR_CC, MVT::f32, Custom); 931 setOperationAction(ISD::BR_CC, MVT::f64, Custom); 932 setOperationAction(ISD::BR_JT, MVT::Other, Custom); 933 934 // We don't support sin/cos/fmod/copysign/pow 935 setOperationAction(ISD::FSIN, MVT::f64, Expand); 936 setOperationAction(ISD::FSIN, MVT::f32, Expand); 937 setOperationAction(ISD::FCOS, MVT::f32, Expand); 938 setOperationAction(ISD::FCOS, MVT::f64, Expand); 939 setOperationAction(ISD::FSINCOS, MVT::f64, Expand); 940 setOperationAction(ISD::FSINCOS, MVT::f32, Expand); 941 setOperationAction(ISD::FREM, MVT::f64, Expand); 942 setOperationAction(ISD::FREM, MVT::f32, Expand); 943 if (!Subtarget->useSoftFloat() && Subtarget->hasVFP2() && 944 !Subtarget->isThumb1Only()) { 945 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Custom); 946 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom); 947 } 948 setOperationAction(ISD::FPOW, MVT::f64, Expand); 949 setOperationAction(ISD::FPOW, MVT::f32, Expand); 950 951 if (!Subtarget->hasVFP4()) { 952 setOperationAction(ISD::FMA, MVT::f64, Expand); 953 setOperationAction(ISD::FMA, MVT::f32, Expand); 954 } 955 956 // Various VFP goodness 957 if (!Subtarget->useSoftFloat() && !Subtarget->isThumb1Only()) { 958 // FP-ARMv8 adds f64 <-> f16 conversion. Before that it should be expanded. 959 if (!Subtarget->hasFPARMv8() || Subtarget->isFPOnlySP()) { 960 setOperationAction(ISD::FP16_TO_FP, MVT::f64, Expand); 961 setOperationAction(ISD::FP_TO_FP16, MVT::f64, Expand); 962 } 963 964 // fp16 is a special v7 extension that adds f16 <-> f32 conversions. 965 if (!Subtarget->hasFP16()) { 966 setOperationAction(ISD::FP16_TO_FP, MVT::f32, Expand); 967 setOperationAction(ISD::FP_TO_FP16, MVT::f32, Expand); 968 } 969 } 970 971 // Combine sin / cos into one node or libcall if possible. 972 if (Subtarget->hasSinCos()) { 973 setLibcallName(RTLIB::SINCOS_F32, "sincosf"); 974 setLibcallName(RTLIB::SINCOS_F64, "sincos"); 975 if (Subtarget->isTargetWatchABI()) { 976 setLibcallCallingConv(RTLIB::SINCOS_F32, CallingConv::ARM_AAPCS_VFP); 977 setLibcallCallingConv(RTLIB::SINCOS_F64, CallingConv::ARM_AAPCS_VFP); 978 } 979 if (Subtarget->isTargetIOS() || Subtarget->isTargetWatchOS()) { 980 // For iOS, we don't want to the normal expansion of a libcall to 981 // sincos. We want to issue a libcall to __sincos_stret. 982 setOperationAction(ISD::FSINCOS, MVT::f64, Custom); 983 setOperationAction(ISD::FSINCOS, MVT::f32, Custom); 984 } 985 } 986 987 // FP-ARMv8 implements a lot of rounding-like FP operations. 988 if (Subtarget->hasFPARMv8()) { 989 setOperationAction(ISD::FFLOOR, MVT::f32, Legal); 990 setOperationAction(ISD::FCEIL, MVT::f32, Legal); 991 setOperationAction(ISD::FROUND, MVT::f32, Legal); 992 setOperationAction(ISD::FTRUNC, MVT::f32, Legal); 993 setOperationAction(ISD::FNEARBYINT, MVT::f32, Legal); 994 setOperationAction(ISD::FRINT, MVT::f32, Legal); 995 setOperationAction(ISD::FMINNUM, MVT::f32, Legal); 996 setOperationAction(ISD::FMAXNUM, MVT::f32, Legal); 997 setOperationAction(ISD::FMINNUM, MVT::v2f32, Legal); 998 setOperationAction(ISD::FMAXNUM, MVT::v2f32, Legal); 999 setOperationAction(ISD::FMINNUM, MVT::v4f32, Legal); 1000 setOperationAction(ISD::FMAXNUM, MVT::v4f32, Legal); 1001 1002 if (!Subtarget->isFPOnlySP()) { 1003 setOperationAction(ISD::FFLOOR, MVT::f64, Legal); 1004 setOperationAction(ISD::FCEIL, MVT::f64, Legal); 1005 setOperationAction(ISD::FROUND, MVT::f64, Legal); 1006 setOperationAction(ISD::FTRUNC, MVT::f64, Legal); 1007 setOperationAction(ISD::FNEARBYINT, MVT::f64, Legal); 1008 setOperationAction(ISD::FRINT, MVT::f64, Legal); 1009 setOperationAction(ISD::FMINNUM, MVT::f64, Legal); 1010 setOperationAction(ISD::FMAXNUM, MVT::f64, Legal); 1011 } 1012 } 1013 1014 if (Subtarget->hasNEON()) { 1015 // vmin and vmax aren't available in a scalar form, so we use 1016 // a NEON instruction with an undef lane instead. 1017 setOperationAction(ISD::FMINNAN, MVT::f32, Legal); 1018 setOperationAction(ISD::FMAXNAN, MVT::f32, Legal); 1019 setOperationAction(ISD::FMINNAN, MVT::v2f32, Legal); 1020 setOperationAction(ISD::FMAXNAN, MVT::v2f32, Legal); 1021 setOperationAction(ISD::FMINNAN, MVT::v4f32, Legal); 1022 setOperationAction(ISD::FMAXNAN, MVT::v4f32, Legal); 1023 } 1024 1025 // We have target-specific dag combine patterns for the following nodes: 1026 // ARMISD::VMOVRRD - No need to call setTargetDAGCombine 1027 setTargetDAGCombine(ISD::ADD); 1028 setTargetDAGCombine(ISD::SUB); 1029 setTargetDAGCombine(ISD::MUL); 1030 setTargetDAGCombine(ISD::AND); 1031 setTargetDAGCombine(ISD::OR); 1032 setTargetDAGCombine(ISD::XOR); 1033 1034 if (Subtarget->hasV6Ops()) 1035 setTargetDAGCombine(ISD::SRL); 1036 1037 setStackPointerRegisterToSaveRestore(ARM::SP); 1038 1039 if (Subtarget->useSoftFloat() || Subtarget->isThumb1Only() || 1040 !Subtarget->hasVFP2()) 1041 setSchedulingPreference(Sched::RegPressure); 1042 else 1043 setSchedulingPreference(Sched::Hybrid); 1044 1045 //// temporary - rewrite interface to use type 1046 MaxStoresPerMemset = 8; 1047 MaxStoresPerMemsetOptSize = 4; 1048 MaxStoresPerMemcpy = 4; // For @llvm.memcpy -> sequence of stores 1049 MaxStoresPerMemcpyOptSize = 2; 1050 MaxStoresPerMemmove = 4; // For @llvm.memmove -> sequence of stores 1051 MaxStoresPerMemmoveOptSize = 2; 1052 1053 // On ARM arguments smaller than 4 bytes are extended, so all arguments 1054 // are at least 4 bytes aligned. 1055 setMinStackArgumentAlignment(4); 1056 1057 // Prefer likely predicted branches to selects on out-of-order cores. 1058 PredictableSelectIsExpensive = Subtarget->getSchedModel().isOutOfOrder(); 1059 1060 setMinFunctionAlignment(Subtarget->isThumb() ? 1 : 2); 1061 } 1062 1063 bool ARMTargetLowering::useSoftFloat() const { 1064 return Subtarget->useSoftFloat(); 1065 } 1066 1067 // FIXME: It might make sense to define the representative register class as the 1068 // nearest super-register that has a non-null superset. For example, DPR_VFP2 is 1069 // a super-register of SPR, and DPR is a superset if DPR_VFP2. Consequently, 1070 // SPR's representative would be DPR_VFP2. This should work well if register 1071 // pressure tracking were modified such that a register use would increment the 1072 // pressure of the register class's representative and all of it's super 1073 // classes' representatives transitively. We have not implemented this because 1074 // of the difficulty prior to coalescing of modeling operand register classes 1075 // due to the common occurrence of cross class copies and subregister insertions 1076 // and extractions. 1077 std::pair<const TargetRegisterClass *, uint8_t> 1078 ARMTargetLowering::findRepresentativeClass(const TargetRegisterInfo *TRI, 1079 MVT VT) const { 1080 const TargetRegisterClass *RRC = nullptr; 1081 uint8_t Cost = 1; 1082 switch (VT.SimpleTy) { 1083 default: 1084 return TargetLowering::findRepresentativeClass(TRI, VT); 1085 // Use DPR as representative register class for all floating point 1086 // and vector types. Since there are 32 SPR registers and 32 DPR registers so 1087 // the cost is 1 for both f32 and f64. 1088 case MVT::f32: case MVT::f64: case MVT::v8i8: case MVT::v4i16: 1089 case MVT::v2i32: case MVT::v1i64: case MVT::v2f32: 1090 RRC = &ARM::DPRRegClass; 1091 // When NEON is used for SP, only half of the register file is available 1092 // because operations that define both SP and DP results will be constrained 1093 // to the VFP2 class (D0-D15). We currently model this constraint prior to 1094 // coalescing by double-counting the SP regs. See the FIXME above. 1095 if (Subtarget->useNEONForSinglePrecisionFP()) 1096 Cost = 2; 1097 break; 1098 case MVT::v16i8: case MVT::v8i16: case MVT::v4i32: case MVT::v2i64: 1099 case MVT::v4f32: case MVT::v2f64: 1100 RRC = &ARM::DPRRegClass; 1101 Cost = 2; 1102 break; 1103 case MVT::v4i64: 1104 RRC = &ARM::DPRRegClass; 1105 Cost = 4; 1106 break; 1107 case MVT::v8i64: 1108 RRC = &ARM::DPRRegClass; 1109 Cost = 8; 1110 break; 1111 } 1112 return std::make_pair(RRC, Cost); 1113 } 1114 1115 const char *ARMTargetLowering::getTargetNodeName(unsigned Opcode) const { 1116 switch ((ARMISD::NodeType)Opcode) { 1117 case ARMISD::FIRST_NUMBER: break; 1118 case ARMISD::Wrapper: return "ARMISD::Wrapper"; 1119 case ARMISD::WrapperPIC: return "ARMISD::WrapperPIC"; 1120 case ARMISD::WrapperJT: return "ARMISD::WrapperJT"; 1121 case ARMISD::COPY_STRUCT_BYVAL: return "ARMISD::COPY_STRUCT_BYVAL"; 1122 case ARMISD::CALL: return "ARMISD::CALL"; 1123 case ARMISD::CALL_PRED: return "ARMISD::CALL_PRED"; 1124 case ARMISD::CALL_NOLINK: return "ARMISD::CALL_NOLINK"; 1125 case ARMISD::BRCOND: return "ARMISD::BRCOND"; 1126 case ARMISD::BR_JT: return "ARMISD::BR_JT"; 1127 case ARMISD::BR2_JT: return "ARMISD::BR2_JT"; 1128 case ARMISD::RET_FLAG: return "ARMISD::RET_FLAG"; 1129 case ARMISD::INTRET_FLAG: return "ARMISD::INTRET_FLAG"; 1130 case ARMISD::PIC_ADD: return "ARMISD::PIC_ADD"; 1131 case ARMISD::CMP: return "ARMISD::CMP"; 1132 case ARMISD::CMN: return "ARMISD::CMN"; 1133 case ARMISD::CMPZ: return "ARMISD::CMPZ"; 1134 case ARMISD::CMPFP: return "ARMISD::CMPFP"; 1135 case ARMISD::CMPFPw0: return "ARMISD::CMPFPw0"; 1136 case ARMISD::BCC_i64: return "ARMISD::BCC_i64"; 1137 case ARMISD::FMSTAT: return "ARMISD::FMSTAT"; 1138 1139 case ARMISD::CMOV: return "ARMISD::CMOV"; 1140 1141 case ARMISD::SSAT: return "ARMISD::SSAT"; 1142 1143 case ARMISD::SRL_FLAG: return "ARMISD::SRL_FLAG"; 1144 case ARMISD::SRA_FLAG: return "ARMISD::SRA_FLAG"; 1145 case ARMISD::RRX: return "ARMISD::RRX"; 1146 1147 case ARMISD::ADDC: return "ARMISD::ADDC"; 1148 case ARMISD::ADDE: return "ARMISD::ADDE"; 1149 case ARMISD::SUBC: return "ARMISD::SUBC"; 1150 case ARMISD::SUBE: return "ARMISD::SUBE"; 1151 1152 case ARMISD::VMOVRRD: return "ARMISD::VMOVRRD"; 1153 case ARMISD::VMOVDRR: return "ARMISD::VMOVDRR"; 1154 1155 case ARMISD::EH_SJLJ_SETJMP: return "ARMISD::EH_SJLJ_SETJMP"; 1156 case ARMISD::EH_SJLJ_LONGJMP: return "ARMISD::EH_SJLJ_LONGJMP"; 1157 case ARMISD::EH_SJLJ_SETUP_DISPATCH: return "ARMISD::EH_SJLJ_SETUP_DISPATCH"; 1158 1159 case ARMISD::TC_RETURN: return "ARMISD::TC_RETURN"; 1160 1161 case ARMISD::THREAD_POINTER:return "ARMISD::THREAD_POINTER"; 1162 1163 case ARMISD::DYN_ALLOC: return "ARMISD::DYN_ALLOC"; 1164 1165 case ARMISD::MEMBARRIER_MCR: return "ARMISD::MEMBARRIER_MCR"; 1166 1167 case ARMISD::PRELOAD: return "ARMISD::PRELOAD"; 1168 1169 case ARMISD::WIN__CHKSTK: return "ARMISD:::WIN__CHKSTK"; 1170 case ARMISD::WIN__DBZCHK: return "ARMISD::WIN__DBZCHK"; 1171 1172 case ARMISD::VCEQ: return "ARMISD::VCEQ"; 1173 case ARMISD::VCEQZ: return "ARMISD::VCEQZ"; 1174 case ARMISD::VCGE: return "ARMISD::VCGE"; 1175 case ARMISD::VCGEZ: return "ARMISD::VCGEZ"; 1176 case ARMISD::VCLEZ: return "ARMISD::VCLEZ"; 1177 case ARMISD::VCGEU: return "ARMISD::VCGEU"; 1178 case ARMISD::VCGT: return "ARMISD::VCGT"; 1179 case ARMISD::VCGTZ: return "ARMISD::VCGTZ"; 1180 case ARMISD::VCLTZ: return "ARMISD::VCLTZ"; 1181 case ARMISD::VCGTU: return "ARMISD::VCGTU"; 1182 case ARMISD::VTST: return "ARMISD::VTST"; 1183 1184 case ARMISD::VSHL: return "ARMISD::VSHL"; 1185 case ARMISD::VSHRs: return "ARMISD::VSHRs"; 1186 case ARMISD::VSHRu: return "ARMISD::VSHRu"; 1187 case ARMISD::VRSHRs: return "ARMISD::VRSHRs"; 1188 case ARMISD::VRSHRu: return "ARMISD::VRSHRu"; 1189 case ARMISD::VRSHRN: return "ARMISD::VRSHRN"; 1190 case ARMISD::VQSHLs: return "ARMISD::VQSHLs"; 1191 case ARMISD::VQSHLu: return "ARMISD::VQSHLu"; 1192 case ARMISD::VQSHLsu: return "ARMISD::VQSHLsu"; 1193 case ARMISD::VQSHRNs: return "ARMISD::VQSHRNs"; 1194 case ARMISD::VQSHRNu: return "ARMISD::VQSHRNu"; 1195 case ARMISD::VQSHRNsu: return "ARMISD::VQSHRNsu"; 1196 case ARMISD::VQRSHRNs: return "ARMISD::VQRSHRNs"; 1197 case ARMISD::VQRSHRNu: return "ARMISD::VQRSHRNu"; 1198 case ARMISD::VQRSHRNsu: return "ARMISD::VQRSHRNsu"; 1199 case ARMISD::VSLI: return "ARMISD::VSLI"; 1200 case ARMISD::VSRI: return "ARMISD::VSRI"; 1201 case ARMISD::VGETLANEu: return "ARMISD::VGETLANEu"; 1202 case ARMISD::VGETLANEs: return "ARMISD::VGETLANEs"; 1203 case ARMISD::VMOVIMM: return "ARMISD::VMOVIMM"; 1204 case ARMISD::VMVNIMM: return "ARMISD::VMVNIMM"; 1205 case ARMISD::VMOVFPIMM: return "ARMISD::VMOVFPIMM"; 1206 case ARMISD::VDUP: return "ARMISD::VDUP"; 1207 case ARMISD::VDUPLANE: return "ARMISD::VDUPLANE"; 1208 case ARMISD::VEXT: return "ARMISD::VEXT"; 1209 case ARMISD::VREV64: return "ARMISD::VREV64"; 1210 case ARMISD::VREV32: return "ARMISD::VREV32"; 1211 case ARMISD::VREV16: return "ARMISD::VREV16"; 1212 case ARMISD::VZIP: return "ARMISD::VZIP"; 1213 case ARMISD::VUZP: return "ARMISD::VUZP"; 1214 case ARMISD::VTRN: return "ARMISD::VTRN"; 1215 case ARMISD::VTBL1: return "ARMISD::VTBL1"; 1216 case ARMISD::VTBL2: return "ARMISD::VTBL2"; 1217 case ARMISD::VMULLs: return "ARMISD::VMULLs"; 1218 case ARMISD::VMULLu: return "ARMISD::VMULLu"; 1219 case ARMISD::UMAAL: return "ARMISD::UMAAL"; 1220 case ARMISD::UMLAL: return "ARMISD::UMLAL"; 1221 case ARMISD::SMLAL: return "ARMISD::SMLAL"; 1222 case ARMISD::BUILD_VECTOR: return "ARMISD::BUILD_VECTOR"; 1223 case ARMISD::BFI: return "ARMISD::BFI"; 1224 case ARMISD::VORRIMM: return "ARMISD::VORRIMM"; 1225 case ARMISD::VBICIMM: return "ARMISD::VBICIMM"; 1226 case ARMISD::VBSL: return "ARMISD::VBSL"; 1227 case ARMISD::MEMCPY: return "ARMISD::MEMCPY"; 1228 case ARMISD::VLD2DUP: return "ARMISD::VLD2DUP"; 1229 case ARMISD::VLD3DUP: return "ARMISD::VLD3DUP"; 1230 case ARMISD::VLD4DUP: return "ARMISD::VLD4DUP"; 1231 case ARMISD::VLD1_UPD: return "ARMISD::VLD1_UPD"; 1232 case ARMISD::VLD2_UPD: return "ARMISD::VLD2_UPD"; 1233 case ARMISD::VLD3_UPD: return "ARMISD::VLD3_UPD"; 1234 case ARMISD::VLD4_UPD: return "ARMISD::VLD4_UPD"; 1235 case ARMISD::VLD2LN_UPD: return "ARMISD::VLD2LN_UPD"; 1236 case ARMISD::VLD3LN_UPD: return "ARMISD::VLD3LN_UPD"; 1237 case ARMISD::VLD4LN_UPD: return "ARMISD::VLD4LN_UPD"; 1238 case ARMISD::VLD2DUP_UPD: return "ARMISD::VLD2DUP_UPD"; 1239 case ARMISD::VLD3DUP_UPD: return "ARMISD::VLD3DUP_UPD"; 1240 case ARMISD::VLD4DUP_UPD: return "ARMISD::VLD4DUP_UPD"; 1241 case ARMISD::VST1_UPD: return "ARMISD::VST1_UPD"; 1242 case ARMISD::VST2_UPD: return "ARMISD::VST2_UPD"; 1243 case ARMISD::VST3_UPD: return "ARMISD::VST3_UPD"; 1244 case ARMISD::VST4_UPD: return "ARMISD::VST4_UPD"; 1245 case ARMISD::VST2LN_UPD: return "ARMISD::VST2LN_UPD"; 1246 case ARMISD::VST3LN_UPD: return "ARMISD::VST3LN_UPD"; 1247 case ARMISD::VST4LN_UPD: return "ARMISD::VST4LN_UPD"; 1248 } 1249 return nullptr; 1250 } 1251 1252 EVT ARMTargetLowering::getSetCCResultType(const DataLayout &DL, LLVMContext &, 1253 EVT VT) const { 1254 if (!VT.isVector()) 1255 return getPointerTy(DL); 1256 return VT.changeVectorElementTypeToInteger(); 1257 } 1258 1259 /// getRegClassFor - Return the register class that should be used for the 1260 /// specified value type. 1261 const TargetRegisterClass *ARMTargetLowering::getRegClassFor(MVT VT) const { 1262 // Map v4i64 to QQ registers but do not make the type legal. Similarly map 1263 // v8i64 to QQQQ registers. v4i64 and v8i64 are only used for REG_SEQUENCE to 1264 // load / store 4 to 8 consecutive D registers. 1265 if (Subtarget->hasNEON()) { 1266 if (VT == MVT::v4i64) 1267 return &ARM::QQPRRegClass; 1268 if (VT == MVT::v8i64) 1269 return &ARM::QQQQPRRegClass; 1270 } 1271 return TargetLowering::getRegClassFor(VT); 1272 } 1273 1274 // memcpy, and other memory intrinsics, typically tries to use LDM/STM if the 1275 // source/dest is aligned and the copy size is large enough. We therefore want 1276 // to align such objects passed to memory intrinsics. 1277 bool ARMTargetLowering::shouldAlignPointerArgs(CallInst *CI, unsigned &MinSize, 1278 unsigned &PrefAlign) const { 1279 if (!isa<MemIntrinsic>(CI)) 1280 return false; 1281 MinSize = 8; 1282 // On ARM11 onwards (excluding M class) 8-byte aligned LDM is typically 1 1283 // cycle faster than 4-byte aligned LDM. 1284 PrefAlign = (Subtarget->hasV6Ops() && !Subtarget->isMClass() ? 8 : 4); 1285 return true; 1286 } 1287 1288 // Create a fast isel object. 1289 FastISel * 1290 ARMTargetLowering::createFastISel(FunctionLoweringInfo &funcInfo, 1291 const TargetLibraryInfo *libInfo) const { 1292 return ARM::createFastISel(funcInfo, libInfo); 1293 } 1294 1295 Sched::Preference ARMTargetLowering::getSchedulingPreference(SDNode *N) const { 1296 unsigned NumVals = N->getNumValues(); 1297 if (!NumVals) 1298 return Sched::RegPressure; 1299 1300 for (unsigned i = 0; i != NumVals; ++i) { 1301 EVT VT = N->getValueType(i); 1302 if (VT == MVT::Glue || VT == MVT::Other) 1303 continue; 1304 if (VT.isFloatingPoint() || VT.isVector()) 1305 return Sched::ILP; 1306 } 1307 1308 if (!N->isMachineOpcode()) 1309 return Sched::RegPressure; 1310 1311 // Load are scheduled for latency even if there instruction itinerary 1312 // is not available. 1313 const TargetInstrInfo *TII = Subtarget->getInstrInfo(); 1314 const MCInstrDesc &MCID = TII->get(N->getMachineOpcode()); 1315 1316 if (MCID.getNumDefs() == 0) 1317 return Sched::RegPressure; 1318 if (!Itins->isEmpty() && 1319 Itins->getOperandCycle(MCID.getSchedClass(), 0) > 2) 1320 return Sched::ILP; 1321 1322 return Sched::RegPressure; 1323 } 1324 1325 //===----------------------------------------------------------------------===// 1326 // Lowering Code 1327 //===----------------------------------------------------------------------===// 1328 1329 /// IntCCToARMCC - Convert a DAG integer condition code to an ARM CC 1330 static ARMCC::CondCodes IntCCToARMCC(ISD::CondCode CC) { 1331 switch (CC) { 1332 default: llvm_unreachable("Unknown condition code!"); 1333 case ISD::SETNE: return ARMCC::NE; 1334 case ISD::SETEQ: return ARMCC::EQ; 1335 case ISD::SETGT: return ARMCC::GT; 1336 case ISD::SETGE: return ARMCC::GE; 1337 case ISD::SETLT: return ARMCC::LT; 1338 case ISD::SETLE: return ARMCC::LE; 1339 case ISD::SETUGT: return ARMCC::HI; 1340 case ISD::SETUGE: return ARMCC::HS; 1341 case ISD::SETULT: return ARMCC::LO; 1342 case ISD::SETULE: return ARMCC::LS; 1343 } 1344 } 1345 1346 /// FPCCToARMCC - Convert a DAG fp condition code to an ARM CC. 1347 static void FPCCToARMCC(ISD::CondCode CC, ARMCC::CondCodes &CondCode, 1348 ARMCC::CondCodes &CondCode2) { 1349 CondCode2 = ARMCC::AL; 1350 switch (CC) { 1351 default: llvm_unreachable("Unknown FP condition!"); 1352 case ISD::SETEQ: 1353 case ISD::SETOEQ: CondCode = ARMCC::EQ; break; 1354 case ISD::SETGT: 1355 case ISD::SETOGT: CondCode = ARMCC::GT; break; 1356 case ISD::SETGE: 1357 case ISD::SETOGE: CondCode = ARMCC::GE; break; 1358 case ISD::SETOLT: CondCode = ARMCC::MI; break; 1359 case ISD::SETOLE: CondCode = ARMCC::LS; break; 1360 case ISD::SETONE: CondCode = ARMCC::MI; CondCode2 = ARMCC::GT; break; 1361 case ISD::SETO: CondCode = ARMCC::VC; break; 1362 case ISD::SETUO: CondCode = ARMCC::VS; break; 1363 case ISD::SETUEQ: CondCode = ARMCC::EQ; CondCode2 = ARMCC::VS; break; 1364 case ISD::SETUGT: CondCode = ARMCC::HI; break; 1365 case ISD::SETUGE: CondCode = ARMCC::PL; break; 1366 case ISD::SETLT: 1367 case ISD::SETULT: CondCode = ARMCC::LT; break; 1368 case ISD::SETLE: 1369 case ISD::SETULE: CondCode = ARMCC::LE; break; 1370 case ISD::SETNE: 1371 case ISD::SETUNE: CondCode = ARMCC::NE; break; 1372 } 1373 } 1374 1375 //===----------------------------------------------------------------------===// 1376 // Calling Convention Implementation 1377 //===----------------------------------------------------------------------===// 1378 1379 #include "ARMGenCallingConv.inc" 1380 1381 /// getEffectiveCallingConv - Get the effective calling convention, taking into 1382 /// account presence of floating point hardware and calling convention 1383 /// limitations, such as support for variadic functions. 1384 CallingConv::ID 1385 ARMTargetLowering::getEffectiveCallingConv(CallingConv::ID CC, 1386 bool isVarArg) const { 1387 switch (CC) { 1388 default: 1389 llvm_unreachable("Unsupported calling convention"); 1390 case CallingConv::ARM_AAPCS: 1391 case CallingConv::ARM_APCS: 1392 case CallingConv::GHC: 1393 return CC; 1394 case CallingConv::PreserveMost: 1395 return CallingConv::PreserveMost; 1396 case CallingConv::ARM_AAPCS_VFP: 1397 case CallingConv::Swift: 1398 return isVarArg ? CallingConv::ARM_AAPCS : CallingConv::ARM_AAPCS_VFP; 1399 case CallingConv::C: 1400 if (!Subtarget->isAAPCS_ABI()) 1401 return CallingConv::ARM_APCS; 1402 else if (Subtarget->hasVFP2() && !Subtarget->isThumb1Only() && 1403 getTargetMachine().Options.FloatABIType == FloatABI::Hard && 1404 !isVarArg) 1405 return CallingConv::ARM_AAPCS_VFP; 1406 else 1407 return CallingConv::ARM_AAPCS; 1408 case CallingConv::Fast: 1409 case CallingConv::CXX_FAST_TLS: 1410 if (!Subtarget->isAAPCS_ABI()) { 1411 if (Subtarget->hasVFP2() && !Subtarget->isThumb1Only() && !isVarArg) 1412 return CallingConv::Fast; 1413 return CallingConv::ARM_APCS; 1414 } else if (Subtarget->hasVFP2() && !Subtarget->isThumb1Only() && !isVarArg) 1415 return CallingConv::ARM_AAPCS_VFP; 1416 else 1417 return CallingConv::ARM_AAPCS; 1418 } 1419 } 1420 1421 /// CCAssignFnForNode - Selects the correct CCAssignFn for the given 1422 /// CallingConvention. 1423 CCAssignFn *ARMTargetLowering::CCAssignFnForNode(CallingConv::ID CC, 1424 bool Return, 1425 bool isVarArg) const { 1426 switch (getEffectiveCallingConv(CC, isVarArg)) { 1427 default: 1428 llvm_unreachable("Unsupported calling convention"); 1429 case CallingConv::ARM_APCS: 1430 return (Return ? RetCC_ARM_APCS : CC_ARM_APCS); 1431 case CallingConv::ARM_AAPCS: 1432 return (Return ? RetCC_ARM_AAPCS : CC_ARM_AAPCS); 1433 case CallingConv::ARM_AAPCS_VFP: 1434 return (Return ? RetCC_ARM_AAPCS_VFP : CC_ARM_AAPCS_VFP); 1435 case CallingConv::Fast: 1436 return (Return ? RetFastCC_ARM_APCS : FastCC_ARM_APCS); 1437 case CallingConv::GHC: 1438 return (Return ? RetCC_ARM_APCS : CC_ARM_APCS_GHC); 1439 case CallingConv::PreserveMost: 1440 return (Return ? RetCC_ARM_AAPCS : CC_ARM_AAPCS); 1441 } 1442 } 1443 1444 /// LowerCallResult - Lower the result values of a call into the 1445 /// appropriate copies out of appropriate physical registers. 1446 SDValue ARMTargetLowering::LowerCallResult( 1447 SDValue Chain, SDValue InFlag, CallingConv::ID CallConv, bool isVarArg, 1448 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl, 1449 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals, bool isThisReturn, 1450 SDValue ThisVal) const { 1451 1452 // Assign locations to each value returned by this call. 1453 SmallVector<CCValAssign, 16> RVLocs; 1454 ARMCCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs, 1455 *DAG.getContext(), Call); 1456 CCInfo.AnalyzeCallResult(Ins, 1457 CCAssignFnForNode(CallConv, /* Return*/ true, 1458 isVarArg)); 1459 1460 // Copy all of the result registers out of their specified physreg. 1461 for (unsigned i = 0; i != RVLocs.size(); ++i) { 1462 CCValAssign VA = RVLocs[i]; 1463 1464 // Pass 'this' value directly from the argument to return value, to avoid 1465 // reg unit interference 1466 if (i == 0 && isThisReturn) { 1467 assert(!VA.needsCustom() && VA.getLocVT() == MVT::i32 && 1468 "unexpected return calling convention register assignment"); 1469 InVals.push_back(ThisVal); 1470 continue; 1471 } 1472 1473 SDValue Val; 1474 if (VA.needsCustom()) { 1475 // Handle f64 or half of a v2f64. 1476 SDValue Lo = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32, 1477 InFlag); 1478 Chain = Lo.getValue(1); 1479 InFlag = Lo.getValue(2); 1480 VA = RVLocs[++i]; // skip ahead to next loc 1481 SDValue Hi = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32, 1482 InFlag); 1483 Chain = Hi.getValue(1); 1484 InFlag = Hi.getValue(2); 1485 if (!Subtarget->isLittle()) 1486 std::swap (Lo, Hi); 1487 Val = DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi); 1488 1489 if (VA.getLocVT() == MVT::v2f64) { 1490 SDValue Vec = DAG.getNode(ISD::UNDEF, dl, MVT::v2f64); 1491 Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Vec, Val, 1492 DAG.getConstant(0, dl, MVT::i32)); 1493 1494 VA = RVLocs[++i]; // skip ahead to next loc 1495 Lo = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32, InFlag); 1496 Chain = Lo.getValue(1); 1497 InFlag = Lo.getValue(2); 1498 VA = RVLocs[++i]; // skip ahead to next loc 1499 Hi = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32, InFlag); 1500 Chain = Hi.getValue(1); 1501 InFlag = Hi.getValue(2); 1502 if (!Subtarget->isLittle()) 1503 std::swap (Lo, Hi); 1504 Val = DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi); 1505 Val = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Vec, Val, 1506 DAG.getConstant(1, dl, MVT::i32)); 1507 } 1508 } else { 1509 Val = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), VA.getLocVT(), 1510 InFlag); 1511 Chain = Val.getValue(1); 1512 InFlag = Val.getValue(2); 1513 } 1514 1515 switch (VA.getLocInfo()) { 1516 default: llvm_unreachable("Unknown loc info!"); 1517 case CCValAssign::Full: break; 1518 case CCValAssign::BCvt: 1519 Val = DAG.getNode(ISD::BITCAST, dl, VA.getValVT(), Val); 1520 break; 1521 } 1522 1523 InVals.push_back(Val); 1524 } 1525 1526 return Chain; 1527 } 1528 1529 /// LowerMemOpCallTo - Store the argument to the stack. 1530 SDValue ARMTargetLowering::LowerMemOpCallTo(SDValue Chain, SDValue StackPtr, 1531 SDValue Arg, const SDLoc &dl, 1532 SelectionDAG &DAG, 1533 const CCValAssign &VA, 1534 ISD::ArgFlagsTy Flags) const { 1535 unsigned LocMemOffset = VA.getLocMemOffset(); 1536 SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset, dl); 1537 PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(DAG.getDataLayout()), 1538 StackPtr, PtrOff); 1539 return DAG.getStore( 1540 Chain, dl, Arg, PtrOff, 1541 MachinePointerInfo::getStack(DAG.getMachineFunction(), LocMemOffset), 1542 false, false, 0); 1543 } 1544 1545 void ARMTargetLowering::PassF64ArgInRegs(const SDLoc &dl, SelectionDAG &DAG, 1546 SDValue Chain, SDValue &Arg, 1547 RegsToPassVector &RegsToPass, 1548 CCValAssign &VA, CCValAssign &NextVA, 1549 SDValue &StackPtr, 1550 SmallVectorImpl<SDValue> &MemOpChains, 1551 ISD::ArgFlagsTy Flags) const { 1552 1553 SDValue fmrrd = DAG.getNode(ARMISD::VMOVRRD, dl, 1554 DAG.getVTList(MVT::i32, MVT::i32), Arg); 1555 unsigned id = Subtarget->isLittle() ? 0 : 1; 1556 RegsToPass.push_back(std::make_pair(VA.getLocReg(), fmrrd.getValue(id))); 1557 1558 if (NextVA.isRegLoc()) 1559 RegsToPass.push_back(std::make_pair(NextVA.getLocReg(), fmrrd.getValue(1-id))); 1560 else { 1561 assert(NextVA.isMemLoc()); 1562 if (!StackPtr.getNode()) 1563 StackPtr = DAG.getCopyFromReg(Chain, dl, ARM::SP, 1564 getPointerTy(DAG.getDataLayout())); 1565 1566 MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, fmrrd.getValue(1-id), 1567 dl, DAG, NextVA, 1568 Flags)); 1569 } 1570 } 1571 1572 /// LowerCall - Lowering a call into a callseq_start <- 1573 /// ARMISD:CALL <- callseq_end chain. Also add input and output parameter 1574 /// nodes. 1575 SDValue 1576 ARMTargetLowering::LowerCall(TargetLowering::CallLoweringInfo &CLI, 1577 SmallVectorImpl<SDValue> &InVals) const { 1578 SelectionDAG &DAG = CLI.DAG; 1579 SDLoc &dl = CLI.DL; 1580 SmallVectorImpl<ISD::OutputArg> &Outs = CLI.Outs; 1581 SmallVectorImpl<SDValue> &OutVals = CLI.OutVals; 1582 SmallVectorImpl<ISD::InputArg> &Ins = CLI.Ins; 1583 SDValue Chain = CLI.Chain; 1584 SDValue Callee = CLI.Callee; 1585 bool &isTailCall = CLI.IsTailCall; 1586 CallingConv::ID CallConv = CLI.CallConv; 1587 bool doesNotRet = CLI.DoesNotReturn; 1588 bool isVarArg = CLI.IsVarArg; 1589 1590 MachineFunction &MF = DAG.getMachineFunction(); 1591 bool isStructRet = (Outs.empty()) ? false : Outs[0].Flags.isSRet(); 1592 bool isThisReturn = false; 1593 bool isSibCall = false; 1594 auto Attr = MF.getFunction()->getFnAttribute("disable-tail-calls"); 1595 1596 // Disable tail calls if they're not supported. 1597 if (!Subtarget->supportsTailCall() || Attr.getValueAsString() == "true") 1598 isTailCall = false; 1599 1600 if (isTailCall) { 1601 // Check if it's really possible to do a tail call. 1602 isTailCall = IsEligibleForTailCallOptimization(Callee, CallConv, 1603 isVarArg, isStructRet, MF.getFunction()->hasStructRetAttr(), 1604 Outs, OutVals, Ins, DAG); 1605 if (!isTailCall && CLI.CS && CLI.CS->isMustTailCall()) 1606 report_fatal_error("failed to perform tail call elimination on a call " 1607 "site marked musttail"); 1608 // We don't support GuaranteedTailCallOpt for ARM, only automatically 1609 // detected sibcalls. 1610 if (isTailCall) { 1611 ++NumTailCalls; 1612 isSibCall = true; 1613 } 1614 } 1615 1616 // Analyze operands of the call, assigning locations to each operand. 1617 SmallVector<CCValAssign, 16> ArgLocs; 1618 ARMCCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), ArgLocs, 1619 *DAG.getContext(), Call); 1620 CCInfo.AnalyzeCallOperands(Outs, 1621 CCAssignFnForNode(CallConv, /* Return*/ false, 1622 isVarArg)); 1623 1624 // Get a count of how many bytes are to be pushed on the stack. 1625 unsigned NumBytes = CCInfo.getNextStackOffset(); 1626 1627 // For tail calls, memory operands are available in our caller's stack. 1628 if (isSibCall) 1629 NumBytes = 0; 1630 1631 // Adjust the stack pointer for the new arguments... 1632 // These operations are automatically eliminated by the prolog/epilog pass 1633 if (!isSibCall) 1634 Chain = DAG.getCALLSEQ_START(Chain, 1635 DAG.getIntPtrConstant(NumBytes, dl, true), dl); 1636 1637 SDValue StackPtr = 1638 DAG.getCopyFromReg(Chain, dl, ARM::SP, getPointerTy(DAG.getDataLayout())); 1639 1640 RegsToPassVector RegsToPass; 1641 SmallVector<SDValue, 8> MemOpChains; 1642 1643 // Walk the register/memloc assignments, inserting copies/loads. In the case 1644 // of tail call optimization, arguments are handled later. 1645 for (unsigned i = 0, realArgIdx = 0, e = ArgLocs.size(); 1646 i != e; 1647 ++i, ++realArgIdx) { 1648 CCValAssign &VA = ArgLocs[i]; 1649 SDValue Arg = OutVals[realArgIdx]; 1650 ISD::ArgFlagsTy Flags = Outs[realArgIdx].Flags; 1651 bool isByVal = Flags.isByVal(); 1652 1653 // Promote the value if needed. 1654 switch (VA.getLocInfo()) { 1655 default: llvm_unreachable("Unknown loc info!"); 1656 case CCValAssign::Full: break; 1657 case CCValAssign::SExt: 1658 Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), Arg); 1659 break; 1660 case CCValAssign::ZExt: 1661 Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, VA.getLocVT(), Arg); 1662 break; 1663 case CCValAssign::AExt: 1664 Arg = DAG.getNode(ISD::ANY_EXTEND, dl, VA.getLocVT(), Arg); 1665 break; 1666 case CCValAssign::BCvt: 1667 Arg = DAG.getNode(ISD::BITCAST, dl, VA.getLocVT(), Arg); 1668 break; 1669 } 1670 1671 // f64 and v2f64 might be passed in i32 pairs and must be split into pieces 1672 if (VA.needsCustom()) { 1673 if (VA.getLocVT() == MVT::v2f64) { 1674 SDValue Op0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg, 1675 DAG.getConstant(0, dl, MVT::i32)); 1676 SDValue Op1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg, 1677 DAG.getConstant(1, dl, MVT::i32)); 1678 1679 PassF64ArgInRegs(dl, DAG, Chain, Op0, RegsToPass, 1680 VA, ArgLocs[++i], StackPtr, MemOpChains, Flags); 1681 1682 VA = ArgLocs[++i]; // skip ahead to next loc 1683 if (VA.isRegLoc()) { 1684 PassF64ArgInRegs(dl, DAG, Chain, Op1, RegsToPass, 1685 VA, ArgLocs[++i], StackPtr, MemOpChains, Flags); 1686 } else { 1687 assert(VA.isMemLoc()); 1688 1689 MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, Op1, 1690 dl, DAG, VA, Flags)); 1691 } 1692 } else { 1693 PassF64ArgInRegs(dl, DAG, Chain, Arg, RegsToPass, VA, ArgLocs[++i], 1694 StackPtr, MemOpChains, Flags); 1695 } 1696 } else if (VA.isRegLoc()) { 1697 if (realArgIdx == 0 && Flags.isReturned() && Outs[0].VT == MVT::i32) { 1698 assert(VA.getLocVT() == MVT::i32 && 1699 "unexpected calling convention register assignment"); 1700 assert(!Ins.empty() && Ins[0].VT == MVT::i32 && 1701 "unexpected use of 'returned'"); 1702 isThisReturn = true; 1703 } 1704 RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg)); 1705 } else if (isByVal) { 1706 assert(VA.isMemLoc()); 1707 unsigned offset = 0; 1708 1709 // True if this byval aggregate will be split between registers 1710 // and memory. 1711 unsigned ByValArgsCount = CCInfo.getInRegsParamsCount(); 1712 unsigned CurByValIdx = CCInfo.getInRegsParamsProcessed(); 1713 1714 if (CurByValIdx < ByValArgsCount) { 1715 1716 unsigned RegBegin, RegEnd; 1717 CCInfo.getInRegsParamInfo(CurByValIdx, RegBegin, RegEnd); 1718 1719 EVT PtrVT = 1720 DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout()); 1721 unsigned int i, j; 1722 for (i = 0, j = RegBegin; j < RegEnd; i++, j++) { 1723 SDValue Const = DAG.getConstant(4*i, dl, MVT::i32); 1724 SDValue AddArg = DAG.getNode(ISD::ADD, dl, PtrVT, Arg, Const); 1725 SDValue Load = DAG.getLoad(PtrVT, dl, Chain, AddArg, 1726 MachinePointerInfo(), 1727 false, false, false, 1728 DAG.InferPtrAlignment(AddArg)); 1729 MemOpChains.push_back(Load.getValue(1)); 1730 RegsToPass.push_back(std::make_pair(j, Load)); 1731 } 1732 1733 // If parameter size outsides register area, "offset" value 1734 // helps us to calculate stack slot for remained part properly. 1735 offset = RegEnd - RegBegin; 1736 1737 CCInfo.nextInRegsParam(); 1738 } 1739 1740 if (Flags.getByValSize() > 4*offset) { 1741 auto PtrVT = getPointerTy(DAG.getDataLayout()); 1742 unsigned LocMemOffset = VA.getLocMemOffset(); 1743 SDValue StkPtrOff = DAG.getIntPtrConstant(LocMemOffset, dl); 1744 SDValue Dst = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, StkPtrOff); 1745 SDValue SrcOffset = DAG.getIntPtrConstant(4*offset, dl); 1746 SDValue Src = DAG.getNode(ISD::ADD, dl, PtrVT, Arg, SrcOffset); 1747 SDValue SizeNode = DAG.getConstant(Flags.getByValSize() - 4*offset, dl, 1748 MVT::i32); 1749 SDValue AlignNode = DAG.getConstant(Flags.getByValAlign(), dl, 1750 MVT::i32); 1751 1752 SDVTList VTs = DAG.getVTList(MVT::Other, MVT::Glue); 1753 SDValue Ops[] = { Chain, Dst, Src, SizeNode, AlignNode}; 1754 MemOpChains.push_back(DAG.getNode(ARMISD::COPY_STRUCT_BYVAL, dl, VTs, 1755 Ops)); 1756 } 1757 } else if (!isSibCall) { 1758 assert(VA.isMemLoc()); 1759 1760 MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, Arg, 1761 dl, DAG, VA, Flags)); 1762 } 1763 } 1764 1765 if (!MemOpChains.empty()) 1766 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains); 1767 1768 // Build a sequence of copy-to-reg nodes chained together with token chain 1769 // and flag operands which copy the outgoing args into the appropriate regs. 1770 SDValue InFlag; 1771 // Tail call byval lowering might overwrite argument registers so in case of 1772 // tail call optimization the copies to registers are lowered later. 1773 if (!isTailCall) 1774 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) { 1775 Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first, 1776 RegsToPass[i].second, InFlag); 1777 InFlag = Chain.getValue(1); 1778 } 1779 1780 // For tail calls lower the arguments to the 'real' stack slot. 1781 if (isTailCall) { 1782 // Force all the incoming stack arguments to be loaded from the stack 1783 // before any new outgoing arguments are stored to the stack, because the 1784 // outgoing stack slots may alias the incoming argument stack slots, and 1785 // the alias isn't otherwise explicit. This is slightly more conservative 1786 // than necessary, because it means that each store effectively depends 1787 // on every argument instead of just those arguments it would clobber. 1788 1789 // Do not flag preceding copytoreg stuff together with the following stuff. 1790 InFlag = SDValue(); 1791 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) { 1792 Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first, 1793 RegsToPass[i].second, InFlag); 1794 InFlag = Chain.getValue(1); 1795 } 1796 InFlag = SDValue(); 1797 } 1798 1799 // If the callee is a GlobalAddress/ExternalSymbol node (quite common, every 1800 // direct call is) turn it into a TargetGlobalAddress/TargetExternalSymbol 1801 // node so that legalize doesn't hack it. 1802 bool isDirect = false; 1803 1804 const TargetMachine &TM = getTargetMachine(); 1805 const Module *Mod = MF.getFunction()->getParent(); 1806 const GlobalValue *GV = nullptr; 1807 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) 1808 GV = G->getGlobal(); 1809 bool isStub = 1810 !TM.shouldAssumeDSOLocal(*Mod, GV) && Subtarget->isTargetMachO(); 1811 1812 bool isARMFunc = !Subtarget->isThumb() || (isStub && !Subtarget->isMClass()); 1813 bool isLocalARMFunc = false; 1814 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>(); 1815 auto PtrVt = getPointerTy(DAG.getDataLayout()); 1816 1817 if (Subtarget->genLongCalls()) { 1818 assert(!isPositionIndependent() && 1819 "long-calls codegen is not position independent!"); 1820 // Handle a global address or an external symbol. If it's not one of 1821 // those, the target's already in a register, so we don't need to do 1822 // anything extra. 1823 if (isa<GlobalAddressSDNode>(Callee)) { 1824 // Create a constant pool entry for the callee address 1825 unsigned ARMPCLabelIndex = AFI->createPICLabelUId(); 1826 ARMConstantPoolValue *CPV = 1827 ARMConstantPoolConstant::Create(GV, ARMPCLabelIndex, ARMCP::CPValue, 0); 1828 1829 // Get the address of the callee into a register 1830 SDValue CPAddr = DAG.getTargetConstantPool(CPV, PtrVt, 4); 1831 CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr); 1832 Callee = DAG.getLoad( 1833 PtrVt, dl, DAG.getEntryNode(), CPAddr, 1834 MachinePointerInfo::getConstantPool(DAG.getMachineFunction()), false, 1835 false, false, 0); 1836 } else if (ExternalSymbolSDNode *S=dyn_cast<ExternalSymbolSDNode>(Callee)) { 1837 const char *Sym = S->getSymbol(); 1838 1839 // Create a constant pool entry for the callee address 1840 unsigned ARMPCLabelIndex = AFI->createPICLabelUId(); 1841 ARMConstantPoolValue *CPV = 1842 ARMConstantPoolSymbol::Create(*DAG.getContext(), Sym, 1843 ARMPCLabelIndex, 0); 1844 // Get the address of the callee into a register 1845 SDValue CPAddr = DAG.getTargetConstantPool(CPV, PtrVt, 4); 1846 CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr); 1847 Callee = DAG.getLoad( 1848 PtrVt, dl, DAG.getEntryNode(), CPAddr, 1849 MachinePointerInfo::getConstantPool(DAG.getMachineFunction()), false, 1850 false, false, 0); 1851 } 1852 } else if (isa<GlobalAddressSDNode>(Callee)) { 1853 isDirect = true; 1854 bool isDef = GV->isStrongDefinitionForLinker(); 1855 1856 // ARM call to a local ARM function is predicable. 1857 isLocalARMFunc = !Subtarget->isThumb() && (isDef || !ARMInterworking); 1858 // tBX takes a register source operand. 1859 if (isStub && Subtarget->isThumb1Only() && !Subtarget->hasV5TOps()) { 1860 assert(Subtarget->isTargetMachO() && "WrapperPIC use on non-MachO?"); 1861 Callee = DAG.getNode( 1862 ARMISD::WrapperPIC, dl, PtrVt, 1863 DAG.getTargetGlobalAddress(GV, dl, PtrVt, 0, ARMII::MO_NONLAZY)); 1864 Callee = DAG.getLoad(PtrVt, dl, DAG.getEntryNode(), Callee, 1865 MachinePointerInfo::getGOT(DAG.getMachineFunction()), 1866 false, false, true, 0); 1867 } else if (Subtarget->isTargetCOFF()) { 1868 assert(Subtarget->isTargetWindows() && 1869 "Windows is the only supported COFF target"); 1870 unsigned TargetFlags = GV->hasDLLImportStorageClass() 1871 ? ARMII::MO_DLLIMPORT 1872 : ARMII::MO_NO_FLAG; 1873 Callee = 1874 DAG.getTargetGlobalAddress(GV, dl, PtrVt, /*Offset=*/0, TargetFlags); 1875 if (GV->hasDLLImportStorageClass()) 1876 Callee = 1877 DAG.getLoad(PtrVt, dl, DAG.getEntryNode(), 1878 DAG.getNode(ARMISD::Wrapper, dl, PtrVt, Callee), 1879 MachinePointerInfo::getGOT(DAG.getMachineFunction()), 1880 false, false, false, 0); 1881 } else { 1882 Callee = DAG.getTargetGlobalAddress(GV, dl, PtrVt, 0, 0); 1883 } 1884 } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) { 1885 isDirect = true; 1886 // tBX takes a register source operand. 1887 const char *Sym = S->getSymbol(); 1888 if (isARMFunc && Subtarget->isThumb1Only() && !Subtarget->hasV5TOps()) { 1889 unsigned ARMPCLabelIndex = AFI->createPICLabelUId(); 1890 ARMConstantPoolValue *CPV = 1891 ARMConstantPoolSymbol::Create(*DAG.getContext(), Sym, 1892 ARMPCLabelIndex, 4); 1893 SDValue CPAddr = DAG.getTargetConstantPool(CPV, PtrVt, 4); 1894 CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr); 1895 Callee = DAG.getLoad( 1896 PtrVt, dl, DAG.getEntryNode(), CPAddr, 1897 MachinePointerInfo::getConstantPool(DAG.getMachineFunction()), false, 1898 false, false, 0); 1899 SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, dl, MVT::i32); 1900 Callee = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVt, Callee, PICLabel); 1901 } else { 1902 Callee = DAG.getTargetExternalSymbol(Sym, PtrVt, 0); 1903 } 1904 } 1905 1906 // FIXME: handle tail calls differently. 1907 unsigned CallOpc; 1908 if (Subtarget->isThumb()) { 1909 if ((!isDirect || isARMFunc) && !Subtarget->hasV5TOps()) 1910 CallOpc = ARMISD::CALL_NOLINK; 1911 else 1912 CallOpc = ARMISD::CALL; 1913 } else { 1914 if (!isDirect && !Subtarget->hasV5TOps()) 1915 CallOpc = ARMISD::CALL_NOLINK; 1916 else if (doesNotRet && isDirect && Subtarget->hasRetAddrStack() && 1917 // Emit regular call when code size is the priority 1918 !MF.getFunction()->optForMinSize()) 1919 // "mov lr, pc; b _foo" to avoid confusing the RSP 1920 CallOpc = ARMISD::CALL_NOLINK; 1921 else 1922 CallOpc = isLocalARMFunc ? ARMISD::CALL_PRED : ARMISD::CALL; 1923 } 1924 1925 std::vector<SDValue> Ops; 1926 Ops.push_back(Chain); 1927 Ops.push_back(Callee); 1928 1929 // Add argument registers to the end of the list so that they are known live 1930 // into the call. 1931 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) 1932 Ops.push_back(DAG.getRegister(RegsToPass[i].first, 1933 RegsToPass[i].second.getValueType())); 1934 1935 // Add a register mask operand representing the call-preserved registers. 1936 if (!isTailCall) { 1937 const uint32_t *Mask; 1938 const ARMBaseRegisterInfo *ARI = Subtarget->getRegisterInfo(); 1939 if (isThisReturn) { 1940 // For 'this' returns, use the R0-preserving mask if applicable 1941 Mask = ARI->getThisReturnPreservedMask(MF, CallConv); 1942 if (!Mask) { 1943 // Set isThisReturn to false if the calling convention is not one that 1944 // allows 'returned' to be modeled in this way, so LowerCallResult does 1945 // not try to pass 'this' straight through 1946 isThisReturn = false; 1947 Mask = ARI->getCallPreservedMask(MF, CallConv); 1948 } 1949 } else 1950 Mask = ARI->getCallPreservedMask(MF, CallConv); 1951 1952 assert(Mask && "Missing call preserved mask for calling convention"); 1953 Ops.push_back(DAG.getRegisterMask(Mask)); 1954 } 1955 1956 if (InFlag.getNode()) 1957 Ops.push_back(InFlag); 1958 1959 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue); 1960 if (isTailCall) { 1961 MF.getFrameInfo()->setHasTailCall(); 1962 return DAG.getNode(ARMISD::TC_RETURN, dl, NodeTys, Ops); 1963 } 1964 1965 // Returns a chain and a flag for retval copy to use. 1966 Chain = DAG.getNode(CallOpc, dl, NodeTys, Ops); 1967 InFlag = Chain.getValue(1); 1968 1969 Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, dl, true), 1970 DAG.getIntPtrConstant(0, dl, true), InFlag, dl); 1971 if (!Ins.empty()) 1972 InFlag = Chain.getValue(1); 1973 1974 // Handle result values, copying them out of physregs into vregs that we 1975 // return. 1976 return LowerCallResult(Chain, InFlag, CallConv, isVarArg, Ins, dl, DAG, 1977 InVals, isThisReturn, 1978 isThisReturn ? OutVals[0] : SDValue()); 1979 } 1980 1981 /// HandleByVal - Every parameter *after* a byval parameter is passed 1982 /// on the stack. Remember the next parameter register to allocate, 1983 /// and then confiscate the rest of the parameter registers to insure 1984 /// this. 1985 void ARMTargetLowering::HandleByVal(CCState *State, unsigned &Size, 1986 unsigned Align) const { 1987 assert((State->getCallOrPrologue() == Prologue || 1988 State->getCallOrPrologue() == Call) && 1989 "unhandled ParmContext"); 1990 1991 // Byval (as with any stack) slots are always at least 4 byte aligned. 1992 Align = std::max(Align, 4U); 1993 1994 unsigned Reg = State->AllocateReg(GPRArgRegs); 1995 if (!Reg) 1996 return; 1997 1998 unsigned AlignInRegs = Align / 4; 1999 unsigned Waste = (ARM::R4 - Reg) % AlignInRegs; 2000 for (unsigned i = 0; i < Waste; ++i) 2001 Reg = State->AllocateReg(GPRArgRegs); 2002 2003 if (!Reg) 2004 return; 2005 2006 unsigned Excess = 4 * (ARM::R4 - Reg); 2007 2008 // Special case when NSAA != SP and parameter size greater than size of 2009 // all remained GPR regs. In that case we can't split parameter, we must 2010 // send it to stack. We also must set NCRN to R4, so waste all 2011 // remained registers. 2012 const unsigned NSAAOffset = State->getNextStackOffset(); 2013 if (NSAAOffset != 0 && Size > Excess) { 2014 while (State->AllocateReg(GPRArgRegs)) 2015 ; 2016 return; 2017 } 2018 2019 // First register for byval parameter is the first register that wasn't 2020 // allocated before this method call, so it would be "reg". 2021 // If parameter is small enough to be saved in range [reg, r4), then 2022 // the end (first after last) register would be reg + param-size-in-regs, 2023 // else parameter would be splitted between registers and stack, 2024 // end register would be r4 in this case. 2025 unsigned ByValRegBegin = Reg; 2026 unsigned ByValRegEnd = std::min<unsigned>(Reg + Size / 4, ARM::R4); 2027 State->addInRegsParamInfo(ByValRegBegin, ByValRegEnd); 2028 // Note, first register is allocated in the beginning of function already, 2029 // allocate remained amount of registers we need. 2030 for (unsigned i = Reg + 1; i != ByValRegEnd; ++i) 2031 State->AllocateReg(GPRArgRegs); 2032 // A byval parameter that is split between registers and memory needs its 2033 // size truncated here. 2034 // In the case where the entire structure fits in registers, we set the 2035 // size in memory to zero. 2036 Size = std::max<int>(Size - Excess, 0); 2037 } 2038 2039 /// MatchingStackOffset - Return true if the given stack call argument is 2040 /// already available in the same position (relatively) of the caller's 2041 /// incoming argument stack. 2042 static 2043 bool MatchingStackOffset(SDValue Arg, unsigned Offset, ISD::ArgFlagsTy Flags, 2044 MachineFrameInfo *MFI, const MachineRegisterInfo *MRI, 2045 const TargetInstrInfo *TII) { 2046 unsigned Bytes = Arg.getValueType().getSizeInBits() / 8; 2047 int FI = INT_MAX; 2048 if (Arg.getOpcode() == ISD::CopyFromReg) { 2049 unsigned VR = cast<RegisterSDNode>(Arg.getOperand(1))->getReg(); 2050 if (!TargetRegisterInfo::isVirtualRegister(VR)) 2051 return false; 2052 MachineInstr *Def = MRI->getVRegDef(VR); 2053 if (!Def) 2054 return false; 2055 if (!Flags.isByVal()) { 2056 if (!TII->isLoadFromStackSlot(*Def, FI)) 2057 return false; 2058 } else { 2059 return false; 2060 } 2061 } else if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Arg)) { 2062 if (Flags.isByVal()) 2063 // ByVal argument is passed in as a pointer but it's now being 2064 // dereferenced. e.g. 2065 // define @foo(%struct.X* %A) { 2066 // tail call @bar(%struct.X* byval %A) 2067 // } 2068 return false; 2069 SDValue Ptr = Ld->getBasePtr(); 2070 FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr); 2071 if (!FINode) 2072 return false; 2073 FI = FINode->getIndex(); 2074 } else 2075 return false; 2076 2077 assert(FI != INT_MAX); 2078 if (!MFI->isFixedObjectIndex(FI)) 2079 return false; 2080 return Offset == MFI->getObjectOffset(FI) && Bytes == MFI->getObjectSize(FI); 2081 } 2082 2083 /// IsEligibleForTailCallOptimization - Check whether the call is eligible 2084 /// for tail call optimization. Targets which want to do tail call 2085 /// optimization should implement this function. 2086 bool 2087 ARMTargetLowering::IsEligibleForTailCallOptimization(SDValue Callee, 2088 CallingConv::ID CalleeCC, 2089 bool isVarArg, 2090 bool isCalleeStructRet, 2091 bool isCallerStructRet, 2092 const SmallVectorImpl<ISD::OutputArg> &Outs, 2093 const SmallVectorImpl<SDValue> &OutVals, 2094 const SmallVectorImpl<ISD::InputArg> &Ins, 2095 SelectionDAG& DAG) const { 2096 MachineFunction &MF = DAG.getMachineFunction(); 2097 const Function *CallerF = MF.getFunction(); 2098 CallingConv::ID CallerCC = CallerF->getCallingConv(); 2099 2100 assert(Subtarget->supportsTailCall()); 2101 2102 // Look for obvious safe cases to perform tail call optimization that do not 2103 // require ABI changes. This is what gcc calls sibcall. 2104 2105 // Do not sibcall optimize vararg calls unless the call site is not passing 2106 // any arguments. 2107 if (isVarArg && !Outs.empty()) 2108 return false; 2109 2110 // Exception-handling functions need a special set of instructions to indicate 2111 // a return to the hardware. Tail-calling another function would probably 2112 // break this. 2113 if (CallerF->hasFnAttribute("interrupt")) 2114 return false; 2115 2116 // Also avoid sibcall optimization if either caller or callee uses struct 2117 // return semantics. 2118 if (isCalleeStructRet || isCallerStructRet) 2119 return false; 2120 2121 // Externally-defined functions with weak linkage should not be 2122 // tail-called on ARM when the OS does not support dynamic 2123 // pre-emption of symbols, as the AAELF spec requires normal calls 2124 // to undefined weak functions to be replaced with a NOP or jump to the 2125 // next instruction. The behaviour of branch instructions in this 2126 // situation (as used for tail calls) is implementation-defined, so we 2127 // cannot rely on the linker replacing the tail call with a return. 2128 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) { 2129 const GlobalValue *GV = G->getGlobal(); 2130 const Triple &TT = getTargetMachine().getTargetTriple(); 2131 if (GV->hasExternalWeakLinkage() && 2132 (!TT.isOSWindows() || TT.isOSBinFormatELF() || TT.isOSBinFormatMachO())) 2133 return false; 2134 } 2135 2136 // Check that the call results are passed in the same way. 2137 LLVMContext &C = *DAG.getContext(); 2138 if (!CCState::resultsCompatible(CalleeCC, CallerCC, MF, C, Ins, 2139 CCAssignFnForNode(CalleeCC, true, isVarArg), 2140 CCAssignFnForNode(CallerCC, true, isVarArg))) 2141 return false; 2142 // The callee has to preserve all registers the caller needs to preserve. 2143 const ARMBaseRegisterInfo *TRI = Subtarget->getRegisterInfo(); 2144 const uint32_t *CallerPreserved = TRI->getCallPreservedMask(MF, CallerCC); 2145 if (CalleeCC != CallerCC) { 2146 const uint32_t *CalleePreserved = TRI->getCallPreservedMask(MF, CalleeCC); 2147 if (!TRI->regmaskSubsetEqual(CallerPreserved, CalleePreserved)) 2148 return false; 2149 } 2150 2151 // If Caller's vararg or byval argument has been split between registers and 2152 // stack, do not perform tail call, since part of the argument is in caller's 2153 // local frame. 2154 const ARMFunctionInfo *AFI_Caller = MF.getInfo<ARMFunctionInfo>(); 2155 if (AFI_Caller->getArgRegsSaveSize()) 2156 return false; 2157 2158 // If the callee takes no arguments then go on to check the results of the 2159 // call. 2160 if (!Outs.empty()) { 2161 // Check if stack adjustment is needed. For now, do not do this if any 2162 // argument is passed on the stack. 2163 SmallVector<CCValAssign, 16> ArgLocs; 2164 ARMCCState CCInfo(CalleeCC, isVarArg, MF, ArgLocs, C, Call); 2165 CCInfo.AnalyzeCallOperands(Outs, 2166 CCAssignFnForNode(CalleeCC, false, isVarArg)); 2167 if (CCInfo.getNextStackOffset()) { 2168 // Check if the arguments are already laid out in the right way as 2169 // the caller's fixed stack objects. 2170 MachineFrameInfo *MFI = MF.getFrameInfo(); 2171 const MachineRegisterInfo *MRI = &MF.getRegInfo(); 2172 const TargetInstrInfo *TII = Subtarget->getInstrInfo(); 2173 for (unsigned i = 0, realArgIdx = 0, e = ArgLocs.size(); 2174 i != e; 2175 ++i, ++realArgIdx) { 2176 CCValAssign &VA = ArgLocs[i]; 2177 EVT RegVT = VA.getLocVT(); 2178 SDValue Arg = OutVals[realArgIdx]; 2179 ISD::ArgFlagsTy Flags = Outs[realArgIdx].Flags; 2180 if (VA.getLocInfo() == CCValAssign::Indirect) 2181 return false; 2182 if (VA.needsCustom()) { 2183 // f64 and vector types are split into multiple registers or 2184 // register/stack-slot combinations. The types will not match 2185 // the registers; give up on memory f64 refs until we figure 2186 // out what to do about this. 2187 if (!VA.isRegLoc()) 2188 return false; 2189 if (!ArgLocs[++i].isRegLoc()) 2190 return false; 2191 if (RegVT == MVT::v2f64) { 2192 if (!ArgLocs[++i].isRegLoc()) 2193 return false; 2194 if (!ArgLocs[++i].isRegLoc()) 2195 return false; 2196 } 2197 } else if (!VA.isRegLoc()) { 2198 if (!MatchingStackOffset(Arg, VA.getLocMemOffset(), Flags, 2199 MFI, MRI, TII)) 2200 return false; 2201 } 2202 } 2203 } 2204 2205 const MachineRegisterInfo &MRI = MF.getRegInfo(); 2206 if (!parametersInCSRMatch(MRI, CallerPreserved, ArgLocs, OutVals)) 2207 return false; 2208 } 2209 2210 return true; 2211 } 2212 2213 bool 2214 ARMTargetLowering::CanLowerReturn(CallingConv::ID CallConv, 2215 MachineFunction &MF, bool isVarArg, 2216 const SmallVectorImpl<ISD::OutputArg> &Outs, 2217 LLVMContext &Context) const { 2218 SmallVector<CCValAssign, 16> RVLocs; 2219 CCState CCInfo(CallConv, isVarArg, MF, RVLocs, Context); 2220 return CCInfo.CheckReturn(Outs, CCAssignFnForNode(CallConv, /*Return=*/true, 2221 isVarArg)); 2222 } 2223 2224 static SDValue LowerInterruptReturn(SmallVectorImpl<SDValue> &RetOps, 2225 const SDLoc &DL, SelectionDAG &DAG) { 2226 const MachineFunction &MF = DAG.getMachineFunction(); 2227 const Function *F = MF.getFunction(); 2228 2229 StringRef IntKind = F->getFnAttribute("interrupt").getValueAsString(); 2230 2231 // See ARM ARM v7 B1.8.3. On exception entry LR is set to a possibly offset 2232 // version of the "preferred return address". These offsets affect the return 2233 // instruction if this is a return from PL1 without hypervisor extensions. 2234 // IRQ/FIQ: +4 "subs pc, lr, #4" 2235 // SWI: 0 "subs pc, lr, #0" 2236 // ABORT: +4 "subs pc, lr, #4" 2237 // UNDEF: +4/+2 "subs pc, lr, #0" 2238 // UNDEF varies depending on where the exception came from ARM or Thumb 2239 // mode. Alongside GCC, we throw our hands up in disgust and pretend it's 0. 2240 2241 int64_t LROffset; 2242 if (IntKind == "" || IntKind == "IRQ" || IntKind == "FIQ" || 2243 IntKind == "ABORT") 2244 LROffset = 4; 2245 else if (IntKind == "SWI" || IntKind == "UNDEF") 2246 LROffset = 0; 2247 else 2248 report_fatal_error("Unsupported interrupt attribute. If present, value " 2249 "must be one of: IRQ, FIQ, SWI, ABORT or UNDEF"); 2250 2251 RetOps.insert(RetOps.begin() + 1, 2252 DAG.getConstant(LROffset, DL, MVT::i32, false)); 2253 2254 return DAG.getNode(ARMISD::INTRET_FLAG, DL, MVT::Other, RetOps); 2255 } 2256 2257 SDValue 2258 ARMTargetLowering::LowerReturn(SDValue Chain, CallingConv::ID CallConv, 2259 bool isVarArg, 2260 const SmallVectorImpl<ISD::OutputArg> &Outs, 2261 const SmallVectorImpl<SDValue> &OutVals, 2262 const SDLoc &dl, SelectionDAG &DAG) const { 2263 2264 // CCValAssign - represent the assignment of the return value to a location. 2265 SmallVector<CCValAssign, 16> RVLocs; 2266 2267 // CCState - Info about the registers and stack slots. 2268 ARMCCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs, 2269 *DAG.getContext(), Call); 2270 2271 // Analyze outgoing return values. 2272 CCInfo.AnalyzeReturn(Outs, CCAssignFnForNode(CallConv, /* Return */ true, 2273 isVarArg)); 2274 2275 SDValue Flag; 2276 SmallVector<SDValue, 4> RetOps; 2277 RetOps.push_back(Chain); // Operand #0 = Chain (updated below) 2278 bool isLittleEndian = Subtarget->isLittle(); 2279 2280 MachineFunction &MF = DAG.getMachineFunction(); 2281 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>(); 2282 AFI->setReturnRegsCount(RVLocs.size()); 2283 2284 // Copy the result values into the output registers. 2285 for (unsigned i = 0, realRVLocIdx = 0; 2286 i != RVLocs.size(); 2287 ++i, ++realRVLocIdx) { 2288 CCValAssign &VA = RVLocs[i]; 2289 assert(VA.isRegLoc() && "Can only return in registers!"); 2290 2291 SDValue Arg = OutVals[realRVLocIdx]; 2292 2293 switch (VA.getLocInfo()) { 2294 default: llvm_unreachable("Unknown loc info!"); 2295 case CCValAssign::Full: break; 2296 case CCValAssign::BCvt: 2297 Arg = DAG.getNode(ISD::BITCAST, dl, VA.getLocVT(), Arg); 2298 break; 2299 } 2300 2301 if (VA.needsCustom()) { 2302 if (VA.getLocVT() == MVT::v2f64) { 2303 // Extract the first half and return it in two registers. 2304 SDValue Half = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg, 2305 DAG.getConstant(0, dl, MVT::i32)); 2306 SDValue HalfGPRs = DAG.getNode(ARMISD::VMOVRRD, dl, 2307 DAG.getVTList(MVT::i32, MVT::i32), Half); 2308 2309 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), 2310 HalfGPRs.getValue(isLittleEndian ? 0 : 1), 2311 Flag); 2312 Flag = Chain.getValue(1); 2313 RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT())); 2314 VA = RVLocs[++i]; // skip ahead to next loc 2315 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), 2316 HalfGPRs.getValue(isLittleEndian ? 1 : 0), 2317 Flag); 2318 Flag = Chain.getValue(1); 2319 RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT())); 2320 VA = RVLocs[++i]; // skip ahead to next loc 2321 2322 // Extract the 2nd half and fall through to handle it as an f64 value. 2323 Arg = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg, 2324 DAG.getConstant(1, dl, MVT::i32)); 2325 } 2326 // Legalize ret f64 -> ret 2 x i32. We always have fmrrd if f64 is 2327 // available. 2328 SDValue fmrrd = DAG.getNode(ARMISD::VMOVRRD, dl, 2329 DAG.getVTList(MVT::i32, MVT::i32), Arg); 2330 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), 2331 fmrrd.getValue(isLittleEndian ? 0 : 1), 2332 Flag); 2333 Flag = Chain.getValue(1); 2334 RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT())); 2335 VA = RVLocs[++i]; // skip ahead to next loc 2336 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), 2337 fmrrd.getValue(isLittleEndian ? 1 : 0), 2338 Flag); 2339 } else 2340 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), Arg, Flag); 2341 2342 // Guarantee that all emitted copies are 2343 // stuck together, avoiding something bad. 2344 Flag = Chain.getValue(1); 2345 RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT())); 2346 } 2347 const ARMBaseRegisterInfo *TRI = Subtarget->getRegisterInfo(); 2348 const MCPhysReg *I = 2349 TRI->getCalleeSavedRegsViaCopy(&DAG.getMachineFunction()); 2350 if (I) { 2351 for (; *I; ++I) { 2352 if (ARM::GPRRegClass.contains(*I)) 2353 RetOps.push_back(DAG.getRegister(*I, MVT::i32)); 2354 else if (ARM::DPRRegClass.contains(*I)) 2355 RetOps.push_back(DAG.getRegister(*I, MVT::getFloatingPointVT(64))); 2356 else 2357 llvm_unreachable("Unexpected register class in CSRsViaCopy!"); 2358 } 2359 } 2360 2361 // Update chain and glue. 2362 RetOps[0] = Chain; 2363 if (Flag.getNode()) 2364 RetOps.push_back(Flag); 2365 2366 // CPUs which aren't M-class use a special sequence to return from 2367 // exceptions (roughly, any instruction setting pc and cpsr simultaneously, 2368 // though we use "subs pc, lr, #N"). 2369 // 2370 // M-class CPUs actually use a normal return sequence with a special 2371 // (hardware-provided) value in LR, so the normal code path works. 2372 if (DAG.getMachineFunction().getFunction()->hasFnAttribute("interrupt") && 2373 !Subtarget->isMClass()) { 2374 if (Subtarget->isThumb1Only()) 2375 report_fatal_error("interrupt attribute is not supported in Thumb1"); 2376 return LowerInterruptReturn(RetOps, dl, DAG); 2377 } 2378 2379 return DAG.getNode(ARMISD::RET_FLAG, dl, MVT::Other, RetOps); 2380 } 2381 2382 bool ARMTargetLowering::isUsedByReturnOnly(SDNode *N, SDValue &Chain) const { 2383 if (N->getNumValues() != 1) 2384 return false; 2385 if (!N->hasNUsesOfValue(1, 0)) 2386 return false; 2387 2388 SDValue TCChain = Chain; 2389 SDNode *Copy = *N->use_begin(); 2390 if (Copy->getOpcode() == ISD::CopyToReg) { 2391 // If the copy has a glue operand, we conservatively assume it isn't safe to 2392 // perform a tail call. 2393 if (Copy->getOperand(Copy->getNumOperands()-1).getValueType() == MVT::Glue) 2394 return false; 2395 TCChain = Copy->getOperand(0); 2396 } else if (Copy->getOpcode() == ARMISD::VMOVRRD) { 2397 SDNode *VMov = Copy; 2398 // f64 returned in a pair of GPRs. 2399 SmallPtrSet<SDNode*, 2> Copies; 2400 for (SDNode::use_iterator UI = VMov->use_begin(), UE = VMov->use_end(); 2401 UI != UE; ++UI) { 2402 if (UI->getOpcode() != ISD::CopyToReg) 2403 return false; 2404 Copies.insert(*UI); 2405 } 2406 if (Copies.size() > 2) 2407 return false; 2408 2409 for (SDNode::use_iterator UI = VMov->use_begin(), UE = VMov->use_end(); 2410 UI != UE; ++UI) { 2411 SDValue UseChain = UI->getOperand(0); 2412 if (Copies.count(UseChain.getNode())) 2413 // Second CopyToReg 2414 Copy = *UI; 2415 else { 2416 // We are at the top of this chain. 2417 // If the copy has a glue operand, we conservatively assume it 2418 // isn't safe to perform a tail call. 2419 if (UI->getOperand(UI->getNumOperands()-1).getValueType() == MVT::Glue) 2420 return false; 2421 // First CopyToReg 2422 TCChain = UseChain; 2423 } 2424 } 2425 } else if (Copy->getOpcode() == ISD::BITCAST) { 2426 // f32 returned in a single GPR. 2427 if (!Copy->hasOneUse()) 2428 return false; 2429 Copy = *Copy->use_begin(); 2430 if (Copy->getOpcode() != ISD::CopyToReg || !Copy->hasNUsesOfValue(1, 0)) 2431 return false; 2432 // If the copy has a glue operand, we conservatively assume it isn't safe to 2433 // perform a tail call. 2434 if (Copy->getOperand(Copy->getNumOperands()-1).getValueType() == MVT::Glue) 2435 return false; 2436 TCChain = Copy->getOperand(0); 2437 } else { 2438 return false; 2439 } 2440 2441 bool HasRet = false; 2442 for (SDNode::use_iterator UI = Copy->use_begin(), UE = Copy->use_end(); 2443 UI != UE; ++UI) { 2444 if (UI->getOpcode() != ARMISD::RET_FLAG && 2445 UI->getOpcode() != ARMISD::INTRET_FLAG) 2446 return false; 2447 HasRet = true; 2448 } 2449 2450 if (!HasRet) 2451 return false; 2452 2453 Chain = TCChain; 2454 return true; 2455 } 2456 2457 bool ARMTargetLowering::mayBeEmittedAsTailCall(CallInst *CI) const { 2458 if (!Subtarget->supportsTailCall()) 2459 return false; 2460 2461 auto Attr = 2462 CI->getParent()->getParent()->getFnAttribute("disable-tail-calls"); 2463 if (!CI->isTailCall() || Attr.getValueAsString() == "true") 2464 return false; 2465 2466 return true; 2467 } 2468 2469 // Trying to write a 64 bit value so need to split into two 32 bit values first, 2470 // and pass the lower and high parts through. 2471 static SDValue LowerWRITE_REGISTER(SDValue Op, SelectionDAG &DAG) { 2472 SDLoc DL(Op); 2473 SDValue WriteValue = Op->getOperand(2); 2474 2475 // This function is only supposed to be called for i64 type argument. 2476 assert(WriteValue.getValueType() == MVT::i64 2477 && "LowerWRITE_REGISTER called for non-i64 type argument."); 2478 2479 SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, WriteValue, 2480 DAG.getConstant(0, DL, MVT::i32)); 2481 SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, WriteValue, 2482 DAG.getConstant(1, DL, MVT::i32)); 2483 SDValue Ops[] = { Op->getOperand(0), Op->getOperand(1), Lo, Hi }; 2484 return DAG.getNode(ISD::WRITE_REGISTER, DL, MVT::Other, Ops); 2485 } 2486 2487 // ConstantPool, JumpTable, GlobalAddress, and ExternalSymbol are lowered as 2488 // their target counterpart wrapped in the ARMISD::Wrapper node. Suppose N is 2489 // one of the above mentioned nodes. It has to be wrapped because otherwise 2490 // Select(N) returns N. So the raw TargetGlobalAddress nodes, etc. can only 2491 // be used to form addressing mode. These wrapped nodes will be selected 2492 // into MOVi. 2493 static SDValue LowerConstantPool(SDValue Op, SelectionDAG &DAG) { 2494 EVT PtrVT = Op.getValueType(); 2495 // FIXME there is no actual debug info here 2496 SDLoc dl(Op); 2497 ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op); 2498 SDValue Res; 2499 if (CP->isMachineConstantPoolEntry()) 2500 Res = DAG.getTargetConstantPool(CP->getMachineCPVal(), PtrVT, 2501 CP->getAlignment()); 2502 else 2503 Res = DAG.getTargetConstantPool(CP->getConstVal(), PtrVT, 2504 CP->getAlignment()); 2505 return DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Res); 2506 } 2507 2508 unsigned ARMTargetLowering::getJumpTableEncoding() const { 2509 return MachineJumpTableInfo::EK_Inline; 2510 } 2511 2512 SDValue ARMTargetLowering::LowerBlockAddress(SDValue Op, 2513 SelectionDAG &DAG) const { 2514 MachineFunction &MF = DAG.getMachineFunction(); 2515 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>(); 2516 unsigned ARMPCLabelIndex = 0; 2517 SDLoc DL(Op); 2518 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 2519 const BlockAddress *BA = cast<BlockAddressSDNode>(Op)->getBlockAddress(); 2520 SDValue CPAddr; 2521 bool IsPositionIndependent = isPositionIndependent(); 2522 if (!IsPositionIndependent) { 2523 CPAddr = DAG.getTargetConstantPool(BA, PtrVT, 4); 2524 } else { 2525 unsigned PCAdj = Subtarget->isThumb() ? 4 : 8; 2526 ARMPCLabelIndex = AFI->createPICLabelUId(); 2527 ARMConstantPoolValue *CPV = 2528 ARMConstantPoolConstant::Create(BA, ARMPCLabelIndex, 2529 ARMCP::CPBlockAddress, PCAdj); 2530 CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4); 2531 } 2532 CPAddr = DAG.getNode(ARMISD::Wrapper, DL, PtrVT, CPAddr); 2533 SDValue Result = 2534 DAG.getLoad(PtrVT, DL, DAG.getEntryNode(), CPAddr, 2535 MachinePointerInfo::getConstantPool(DAG.getMachineFunction()), 2536 false, false, false, 0); 2537 if (!IsPositionIndependent) 2538 return Result; 2539 SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, DL, MVT::i32); 2540 return DAG.getNode(ARMISD::PIC_ADD, DL, PtrVT, Result, PICLabel); 2541 } 2542 2543 /// \brief Convert a TLS address reference into the correct sequence of loads 2544 /// and calls to compute the variable's address for Darwin, and return an 2545 /// SDValue containing the final node. 2546 2547 /// Darwin only has one TLS scheme which must be capable of dealing with the 2548 /// fully general situation, in the worst case. This means: 2549 /// + "extern __thread" declaration. 2550 /// + Defined in a possibly unknown dynamic library. 2551 /// 2552 /// The general system is that each __thread variable has a [3 x i32] descriptor 2553 /// which contains information used by the runtime to calculate the address. The 2554 /// only part of this the compiler needs to know about is the first word, which 2555 /// contains a function pointer that must be called with the address of the 2556 /// entire descriptor in "r0". 2557 /// 2558 /// Since this descriptor may be in a different unit, in general access must 2559 /// proceed along the usual ARM rules. A common sequence to produce is: 2560 /// 2561 /// movw rT1, :lower16:_var$non_lazy_ptr 2562 /// movt rT1, :upper16:_var$non_lazy_ptr 2563 /// ldr r0, [rT1] 2564 /// ldr rT2, [r0] 2565 /// blx rT2 2566 /// [...address now in r0...] 2567 SDValue 2568 ARMTargetLowering::LowerGlobalTLSAddressDarwin(SDValue Op, 2569 SelectionDAG &DAG) const { 2570 assert(Subtarget->isTargetDarwin() && "TLS only supported on Darwin"); 2571 SDLoc DL(Op); 2572 2573 // First step is to get the address of the actua global symbol. This is where 2574 // the TLS descriptor lives. 2575 SDValue DescAddr = LowerGlobalAddressDarwin(Op, DAG); 2576 2577 // The first entry in the descriptor is a function pointer that we must call 2578 // to obtain the address of the variable. 2579 SDValue Chain = DAG.getEntryNode(); 2580 SDValue FuncTLVGet = 2581 DAG.getLoad(MVT::i32, DL, Chain, DescAddr, 2582 MachinePointerInfo::getGOT(DAG.getMachineFunction()), 2583 false, true, true, 4); 2584 Chain = FuncTLVGet.getValue(1); 2585 2586 MachineFunction &F = DAG.getMachineFunction(); 2587 MachineFrameInfo *MFI = F.getFrameInfo(); 2588 MFI->setAdjustsStack(true); 2589 2590 // TLS calls preserve all registers except those that absolutely must be 2591 // trashed: R0 (it takes an argument), LR (it's a call) and CPSR (let's not be 2592 // silly). 2593 auto TRI = 2594 getTargetMachine().getSubtargetImpl(*F.getFunction())->getRegisterInfo(); 2595 auto ARI = static_cast<const ARMRegisterInfo *>(TRI); 2596 const uint32_t *Mask = ARI->getTLSCallPreservedMask(DAG.getMachineFunction()); 2597 2598 // Finally, we can make the call. This is just a degenerate version of a 2599 // normal AArch64 call node: r0 takes the address of the descriptor, and 2600 // returns the address of the variable in this thread. 2601 Chain = DAG.getCopyToReg(Chain, DL, ARM::R0, DescAddr, SDValue()); 2602 Chain = 2603 DAG.getNode(ARMISD::CALL, DL, DAG.getVTList(MVT::Other, MVT::Glue), 2604 Chain, FuncTLVGet, DAG.getRegister(ARM::R0, MVT::i32), 2605 DAG.getRegisterMask(Mask), Chain.getValue(1)); 2606 return DAG.getCopyFromReg(Chain, DL, ARM::R0, MVT::i32, Chain.getValue(1)); 2607 } 2608 2609 SDValue 2610 ARMTargetLowering::LowerGlobalTLSAddressWindows(SDValue Op, 2611 SelectionDAG &DAG) const { 2612 assert(Subtarget->isTargetWindows() && "Windows specific TLS lowering"); 2613 2614 SDValue Chain = DAG.getEntryNode(); 2615 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 2616 SDLoc DL(Op); 2617 2618 // Load the current TEB (thread environment block) 2619 SDValue Ops[] = {Chain, 2620 DAG.getConstant(Intrinsic::arm_mrc, DL, MVT::i32), 2621 DAG.getConstant(15, DL, MVT::i32), 2622 DAG.getConstant(0, DL, MVT::i32), 2623 DAG.getConstant(13, DL, MVT::i32), 2624 DAG.getConstant(0, DL, MVT::i32), 2625 DAG.getConstant(2, DL, MVT::i32)}; 2626 SDValue CurrentTEB = DAG.getNode(ISD::INTRINSIC_W_CHAIN, DL, 2627 DAG.getVTList(MVT::i32, MVT::Other), Ops); 2628 2629 SDValue TEB = CurrentTEB.getValue(0); 2630 Chain = CurrentTEB.getValue(1); 2631 2632 // Load the ThreadLocalStoragePointer from the TEB 2633 // A pointer to the TLS array is located at offset 0x2c from the TEB. 2634 SDValue TLSArray = 2635 DAG.getNode(ISD::ADD, DL, PtrVT, TEB, DAG.getIntPtrConstant(0x2c, DL)); 2636 TLSArray = DAG.getLoad(PtrVT, DL, Chain, TLSArray, MachinePointerInfo(), 2637 false, false, false, 0); 2638 2639 // The pointer to the thread's TLS data area is at the TLS Index scaled by 4 2640 // offset into the TLSArray. 2641 2642 // Load the TLS index from the C runtime 2643 SDValue TLSIndex = 2644 DAG.getTargetExternalSymbol("_tls_index", PtrVT, ARMII::MO_NO_FLAG); 2645 TLSIndex = DAG.getNode(ARMISD::Wrapper, DL, PtrVT, TLSIndex); 2646 TLSIndex = DAG.getLoad(PtrVT, DL, Chain, TLSIndex, MachinePointerInfo(), 2647 false, false, false, 0); 2648 2649 SDValue Slot = DAG.getNode(ISD::SHL, DL, PtrVT, TLSIndex, 2650 DAG.getConstant(2, DL, MVT::i32)); 2651 SDValue TLS = DAG.getLoad(PtrVT, DL, Chain, 2652 DAG.getNode(ISD::ADD, DL, PtrVT, TLSArray, Slot), 2653 MachinePointerInfo(), false, false, false, 0); 2654 2655 // Get the offset of the start of the .tls section (section base) 2656 const auto *GA = cast<GlobalAddressSDNode>(Op); 2657 auto *CPV = ARMConstantPoolConstant::Create(GA->getGlobal(), ARMCP::SECREL); 2658 SDValue Offset = 2659 DAG.getLoad(PtrVT, DL, Chain, 2660 DAG.getNode(ARMISD::Wrapper, DL, MVT::i32, 2661 DAG.getTargetConstantPool(CPV, PtrVT, 4)), 2662 MachinePointerInfo::getConstantPool(DAG.getMachineFunction()), 2663 false, false, false, 0); 2664 2665 return DAG.getNode(ISD::ADD, DL, PtrVT, TLS, Offset); 2666 } 2667 2668 // Lower ISD::GlobalTLSAddress using the "general dynamic" model 2669 SDValue 2670 ARMTargetLowering::LowerToTLSGeneralDynamicModel(GlobalAddressSDNode *GA, 2671 SelectionDAG &DAG) const { 2672 SDLoc dl(GA); 2673 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 2674 unsigned char PCAdj = Subtarget->isThumb() ? 4 : 8; 2675 MachineFunction &MF = DAG.getMachineFunction(); 2676 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>(); 2677 unsigned ARMPCLabelIndex = AFI->createPICLabelUId(); 2678 ARMConstantPoolValue *CPV = 2679 ARMConstantPoolConstant::Create(GA->getGlobal(), ARMPCLabelIndex, 2680 ARMCP::CPValue, PCAdj, ARMCP::TLSGD, true); 2681 SDValue Argument = DAG.getTargetConstantPool(CPV, PtrVT, 4); 2682 Argument = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Argument); 2683 Argument = 2684 DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Argument, 2685 MachinePointerInfo::getConstantPool(DAG.getMachineFunction()), 2686 false, false, false, 0); 2687 SDValue Chain = Argument.getValue(1); 2688 2689 SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, dl, MVT::i32); 2690 Argument = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Argument, PICLabel); 2691 2692 // call __tls_get_addr. 2693 ArgListTy Args; 2694 ArgListEntry Entry; 2695 Entry.Node = Argument; 2696 Entry.Ty = (Type *) Type::getInt32Ty(*DAG.getContext()); 2697 Args.push_back(Entry); 2698 2699 // FIXME: is there useful debug info available here? 2700 TargetLowering::CallLoweringInfo CLI(DAG); 2701 CLI.setDebugLoc(dl).setChain(Chain) 2702 .setCallee(CallingConv::C, Type::getInt32Ty(*DAG.getContext()), 2703 DAG.getExternalSymbol("__tls_get_addr", PtrVT), std::move(Args)); 2704 2705 std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI); 2706 return CallResult.first; 2707 } 2708 2709 // Lower ISD::GlobalTLSAddress using the "initial exec" or 2710 // "local exec" model. 2711 SDValue 2712 ARMTargetLowering::LowerToTLSExecModels(GlobalAddressSDNode *GA, 2713 SelectionDAG &DAG, 2714 TLSModel::Model model) const { 2715 const GlobalValue *GV = GA->getGlobal(); 2716 SDLoc dl(GA); 2717 SDValue Offset; 2718 SDValue Chain = DAG.getEntryNode(); 2719 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 2720 // Get the Thread Pointer 2721 SDValue ThreadPointer = DAG.getNode(ARMISD::THREAD_POINTER, dl, PtrVT); 2722 2723 if (model == TLSModel::InitialExec) { 2724 MachineFunction &MF = DAG.getMachineFunction(); 2725 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>(); 2726 unsigned ARMPCLabelIndex = AFI->createPICLabelUId(); 2727 // Initial exec model. 2728 unsigned char PCAdj = Subtarget->isThumb() ? 4 : 8; 2729 ARMConstantPoolValue *CPV = 2730 ARMConstantPoolConstant::Create(GA->getGlobal(), ARMPCLabelIndex, 2731 ARMCP::CPValue, PCAdj, ARMCP::GOTTPOFF, 2732 true); 2733 Offset = DAG.getTargetConstantPool(CPV, PtrVT, 4); 2734 Offset = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Offset); 2735 Offset = DAG.getLoad( 2736 PtrVT, dl, Chain, Offset, 2737 MachinePointerInfo::getConstantPool(DAG.getMachineFunction()), false, 2738 false, false, 0); 2739 Chain = Offset.getValue(1); 2740 2741 SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, dl, MVT::i32); 2742 Offset = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Offset, PICLabel); 2743 2744 Offset = DAG.getLoad( 2745 PtrVT, dl, Chain, Offset, 2746 MachinePointerInfo::getConstantPool(DAG.getMachineFunction()), false, 2747 false, false, 0); 2748 } else { 2749 // local exec model 2750 assert(model == TLSModel::LocalExec); 2751 ARMConstantPoolValue *CPV = 2752 ARMConstantPoolConstant::Create(GV, ARMCP::TPOFF); 2753 Offset = DAG.getTargetConstantPool(CPV, PtrVT, 4); 2754 Offset = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Offset); 2755 Offset = DAG.getLoad( 2756 PtrVT, dl, Chain, Offset, 2757 MachinePointerInfo::getConstantPool(DAG.getMachineFunction()), false, 2758 false, false, 0); 2759 } 2760 2761 // The address of the thread local variable is the add of the thread 2762 // pointer with the offset of the variable. 2763 return DAG.getNode(ISD::ADD, dl, PtrVT, ThreadPointer, Offset); 2764 } 2765 2766 SDValue 2767 ARMTargetLowering::LowerGlobalTLSAddress(SDValue Op, SelectionDAG &DAG) const { 2768 if (Subtarget->isTargetDarwin()) 2769 return LowerGlobalTLSAddressDarwin(Op, DAG); 2770 2771 if (Subtarget->isTargetWindows()) 2772 return LowerGlobalTLSAddressWindows(Op, DAG); 2773 2774 // TODO: implement the "local dynamic" model 2775 assert(Subtarget->isTargetELF() && "Only ELF implemented here"); 2776 GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op); 2777 if (DAG.getTarget().Options.EmulatedTLS) 2778 return LowerToTLSEmulatedModel(GA, DAG); 2779 2780 TLSModel::Model model = getTargetMachine().getTLSModel(GA->getGlobal()); 2781 2782 switch (model) { 2783 case TLSModel::GeneralDynamic: 2784 case TLSModel::LocalDynamic: 2785 return LowerToTLSGeneralDynamicModel(GA, DAG); 2786 case TLSModel::InitialExec: 2787 case TLSModel::LocalExec: 2788 return LowerToTLSExecModels(GA, DAG, model); 2789 } 2790 llvm_unreachable("bogus TLS model"); 2791 } 2792 2793 SDValue ARMTargetLowering::LowerGlobalAddressELF(SDValue Op, 2794 SelectionDAG &DAG) const { 2795 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 2796 SDLoc dl(Op); 2797 const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal(); 2798 const TargetMachine &TM = getTargetMachine(); 2799 if (isPositionIndependent()) { 2800 bool UseGOT_PREL = !TM.shouldAssumeDSOLocal(*GV->getParent(), GV); 2801 2802 MachineFunction &MF = DAG.getMachineFunction(); 2803 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>(); 2804 unsigned ARMPCLabelIndex = AFI->createPICLabelUId(); 2805 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 2806 SDLoc dl(Op); 2807 unsigned PCAdj = Subtarget->isThumb() ? 4 : 8; 2808 ARMConstantPoolValue *CPV = ARMConstantPoolConstant::Create( 2809 GV, ARMPCLabelIndex, ARMCP::CPValue, PCAdj, 2810 UseGOT_PREL ? ARMCP::GOT_PREL : ARMCP::no_modifier, 2811 /*AddCurrentAddress=*/UseGOT_PREL); 2812 SDValue CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4); 2813 CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr); 2814 SDValue Result = DAG.getLoad( 2815 PtrVT, dl, DAG.getEntryNode(), CPAddr, 2816 MachinePointerInfo::getConstantPool(DAG.getMachineFunction()), false, 2817 false, false, 0); 2818 SDValue Chain = Result.getValue(1); 2819 SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, dl, MVT::i32); 2820 Result = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Result, PICLabel); 2821 if (UseGOT_PREL) 2822 Result = DAG.getLoad(PtrVT, dl, Chain, Result, 2823 MachinePointerInfo::getGOT(DAG.getMachineFunction()), 2824 false, false, false, 0); 2825 return Result; 2826 } 2827 2828 // If we have T2 ops, we can materialize the address directly via movt/movw 2829 // pair. This is always cheaper. 2830 if (Subtarget->useMovt(DAG.getMachineFunction())) { 2831 ++NumMovwMovt; 2832 // FIXME: Once remat is capable of dealing with instructions with register 2833 // operands, expand this into two nodes. 2834 return DAG.getNode(ARMISD::Wrapper, dl, PtrVT, 2835 DAG.getTargetGlobalAddress(GV, dl, PtrVT)); 2836 } else { 2837 SDValue CPAddr = DAG.getTargetConstantPool(GV, PtrVT, 4); 2838 CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr); 2839 return DAG.getLoad( 2840 PtrVT, dl, DAG.getEntryNode(), CPAddr, 2841 MachinePointerInfo::getConstantPool(DAG.getMachineFunction()), false, 2842 false, false, 0); 2843 } 2844 } 2845 2846 SDValue ARMTargetLowering::LowerGlobalAddressDarwin(SDValue Op, 2847 SelectionDAG &DAG) const { 2848 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 2849 SDLoc dl(Op); 2850 const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal(); 2851 2852 if (Subtarget->useMovt(DAG.getMachineFunction())) 2853 ++NumMovwMovt; 2854 2855 // FIXME: Once remat is capable of dealing with instructions with register 2856 // operands, expand this into multiple nodes 2857 unsigned Wrapper = 2858 isPositionIndependent() ? ARMISD::WrapperPIC : ARMISD::Wrapper; 2859 2860 SDValue G = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, ARMII::MO_NONLAZY); 2861 SDValue Result = DAG.getNode(Wrapper, dl, PtrVT, G); 2862 2863 if (Subtarget->isGVIndirectSymbol(GV)) 2864 Result = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Result, 2865 MachinePointerInfo::getGOT(DAG.getMachineFunction()), 2866 false, false, false, 0); 2867 return Result; 2868 } 2869 2870 SDValue ARMTargetLowering::LowerGlobalAddressWindows(SDValue Op, 2871 SelectionDAG &DAG) const { 2872 assert(Subtarget->isTargetWindows() && "non-Windows COFF is not supported"); 2873 assert(Subtarget->useMovt(DAG.getMachineFunction()) && 2874 "Windows on ARM expects to use movw/movt"); 2875 2876 const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal(); 2877 const ARMII::TOF TargetFlags = 2878 (GV->hasDLLImportStorageClass() ? ARMII::MO_DLLIMPORT : ARMII::MO_NO_FLAG); 2879 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 2880 SDValue Result; 2881 SDLoc DL(Op); 2882 2883 ++NumMovwMovt; 2884 2885 // FIXME: Once remat is capable of dealing with instructions with register 2886 // operands, expand this into two nodes. 2887 Result = DAG.getNode(ARMISD::Wrapper, DL, PtrVT, 2888 DAG.getTargetGlobalAddress(GV, DL, PtrVT, /*Offset=*/0, 2889 TargetFlags)); 2890 if (GV->hasDLLImportStorageClass()) 2891 Result = DAG.getLoad(PtrVT, DL, DAG.getEntryNode(), Result, 2892 MachinePointerInfo::getGOT(DAG.getMachineFunction()), 2893 false, false, false, 0); 2894 return Result; 2895 } 2896 2897 SDValue 2898 ARMTargetLowering::LowerEH_SJLJ_SETJMP(SDValue Op, SelectionDAG &DAG) const { 2899 SDLoc dl(Op); 2900 SDValue Val = DAG.getConstant(0, dl, MVT::i32); 2901 return DAG.getNode(ARMISD::EH_SJLJ_SETJMP, dl, 2902 DAG.getVTList(MVT::i32, MVT::Other), Op.getOperand(0), 2903 Op.getOperand(1), Val); 2904 } 2905 2906 SDValue 2907 ARMTargetLowering::LowerEH_SJLJ_LONGJMP(SDValue Op, SelectionDAG &DAG) const { 2908 SDLoc dl(Op); 2909 return DAG.getNode(ARMISD::EH_SJLJ_LONGJMP, dl, MVT::Other, Op.getOperand(0), 2910 Op.getOperand(1), DAG.getConstant(0, dl, MVT::i32)); 2911 } 2912 2913 SDValue ARMTargetLowering::LowerEH_SJLJ_SETUP_DISPATCH(SDValue Op, 2914 SelectionDAG &DAG) const { 2915 SDLoc dl(Op); 2916 return DAG.getNode(ARMISD::EH_SJLJ_SETUP_DISPATCH, dl, MVT::Other, 2917 Op.getOperand(0)); 2918 } 2919 2920 SDValue 2921 ARMTargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op, SelectionDAG &DAG, 2922 const ARMSubtarget *Subtarget) const { 2923 unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue(); 2924 SDLoc dl(Op); 2925 switch (IntNo) { 2926 default: return SDValue(); // Don't custom lower most intrinsics. 2927 case Intrinsic::arm_rbit: { 2928 assert(Op.getOperand(1).getValueType() == MVT::i32 && 2929 "RBIT intrinsic must have i32 type!"); 2930 return DAG.getNode(ISD::BITREVERSE, dl, MVT::i32, Op.getOperand(1)); 2931 } 2932 case Intrinsic::thread_pointer: { 2933 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 2934 return DAG.getNode(ARMISD::THREAD_POINTER, dl, PtrVT); 2935 } 2936 case Intrinsic::eh_sjlj_lsda: { 2937 MachineFunction &MF = DAG.getMachineFunction(); 2938 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>(); 2939 unsigned ARMPCLabelIndex = AFI->createPICLabelUId(); 2940 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 2941 SDValue CPAddr; 2942 bool IsPositionIndependent = isPositionIndependent(); 2943 unsigned PCAdj = IsPositionIndependent ? (Subtarget->isThumb() ? 4 : 8) : 0; 2944 ARMConstantPoolValue *CPV = 2945 ARMConstantPoolConstant::Create(MF.getFunction(), ARMPCLabelIndex, 2946 ARMCP::CPLSDA, PCAdj); 2947 CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4); 2948 CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr); 2949 SDValue Result = DAG.getLoad( 2950 PtrVT, dl, DAG.getEntryNode(), CPAddr, 2951 MachinePointerInfo::getConstantPool(DAG.getMachineFunction()), false, 2952 false, false, 0); 2953 2954 if (IsPositionIndependent) { 2955 SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, dl, MVT::i32); 2956 Result = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Result, PICLabel); 2957 } 2958 return Result; 2959 } 2960 case Intrinsic::arm_neon_vmulls: 2961 case Intrinsic::arm_neon_vmullu: { 2962 unsigned NewOpc = (IntNo == Intrinsic::arm_neon_vmulls) 2963 ? ARMISD::VMULLs : ARMISD::VMULLu; 2964 return DAG.getNode(NewOpc, SDLoc(Op), Op.getValueType(), 2965 Op.getOperand(1), Op.getOperand(2)); 2966 } 2967 case Intrinsic::arm_neon_vminnm: 2968 case Intrinsic::arm_neon_vmaxnm: { 2969 unsigned NewOpc = (IntNo == Intrinsic::arm_neon_vminnm) 2970 ? ISD::FMINNUM : ISD::FMAXNUM; 2971 return DAG.getNode(NewOpc, SDLoc(Op), Op.getValueType(), 2972 Op.getOperand(1), Op.getOperand(2)); 2973 } 2974 case Intrinsic::arm_neon_vminu: 2975 case Intrinsic::arm_neon_vmaxu: { 2976 if (Op.getValueType().isFloatingPoint()) 2977 return SDValue(); 2978 unsigned NewOpc = (IntNo == Intrinsic::arm_neon_vminu) 2979 ? ISD::UMIN : ISD::UMAX; 2980 return DAG.getNode(NewOpc, SDLoc(Op), Op.getValueType(), 2981 Op.getOperand(1), Op.getOperand(2)); 2982 } 2983 case Intrinsic::arm_neon_vmins: 2984 case Intrinsic::arm_neon_vmaxs: { 2985 // v{min,max}s is overloaded between signed integers and floats. 2986 if (!Op.getValueType().isFloatingPoint()) { 2987 unsigned NewOpc = (IntNo == Intrinsic::arm_neon_vmins) 2988 ? ISD::SMIN : ISD::SMAX; 2989 return DAG.getNode(NewOpc, SDLoc(Op), Op.getValueType(), 2990 Op.getOperand(1), Op.getOperand(2)); 2991 } 2992 unsigned NewOpc = (IntNo == Intrinsic::arm_neon_vmins) 2993 ? ISD::FMINNAN : ISD::FMAXNAN; 2994 return DAG.getNode(NewOpc, SDLoc(Op), Op.getValueType(), 2995 Op.getOperand(1), Op.getOperand(2)); 2996 } 2997 } 2998 } 2999 3000 static SDValue LowerATOMIC_FENCE(SDValue Op, SelectionDAG &DAG, 3001 const ARMSubtarget *Subtarget) { 3002 // FIXME: handle "fence singlethread" more efficiently. 3003 SDLoc dl(Op); 3004 if (!Subtarget->hasDataBarrier()) { 3005 // Some ARMv6 cpus can support data barriers with an mcr instruction. 3006 // Thumb1 and pre-v6 ARM mode use a libcall instead and should never get 3007 // here. 3008 assert(Subtarget->hasV6Ops() && !Subtarget->isThumb() && 3009 "Unexpected ISD::ATOMIC_FENCE encountered. Should be libcall!"); 3010 return DAG.getNode(ARMISD::MEMBARRIER_MCR, dl, MVT::Other, Op.getOperand(0), 3011 DAG.getConstant(0, dl, MVT::i32)); 3012 } 3013 3014 ConstantSDNode *OrdN = cast<ConstantSDNode>(Op.getOperand(1)); 3015 AtomicOrdering Ord = static_cast<AtomicOrdering>(OrdN->getZExtValue()); 3016 ARM_MB::MemBOpt Domain = ARM_MB::ISH; 3017 if (Subtarget->isMClass()) { 3018 // Only a full system barrier exists in the M-class architectures. 3019 Domain = ARM_MB::SY; 3020 } else if (Subtarget->preferISHSTBarriers() && 3021 Ord == AtomicOrdering::Release) { 3022 // Swift happens to implement ISHST barriers in a way that's compatible with 3023 // Release semantics but weaker than ISH so we'd be fools not to use 3024 // it. Beware: other processors probably don't! 3025 Domain = ARM_MB::ISHST; 3026 } 3027 3028 return DAG.getNode(ISD::INTRINSIC_VOID, dl, MVT::Other, Op.getOperand(0), 3029 DAG.getConstant(Intrinsic::arm_dmb, dl, MVT::i32), 3030 DAG.getConstant(Domain, dl, MVT::i32)); 3031 } 3032 3033 static SDValue LowerPREFETCH(SDValue Op, SelectionDAG &DAG, 3034 const ARMSubtarget *Subtarget) { 3035 // ARM pre v5TE and Thumb1 does not have preload instructions. 3036 if (!(Subtarget->isThumb2() || 3037 (!Subtarget->isThumb1Only() && Subtarget->hasV5TEOps()))) 3038 // Just preserve the chain. 3039 return Op.getOperand(0); 3040 3041 SDLoc dl(Op); 3042 unsigned isRead = ~cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue() & 1; 3043 if (!isRead && 3044 (!Subtarget->hasV7Ops() || !Subtarget->hasMPExtension())) 3045 // ARMv7 with MP extension has PLDW. 3046 return Op.getOperand(0); 3047 3048 unsigned isData = cast<ConstantSDNode>(Op.getOperand(4))->getZExtValue(); 3049 if (Subtarget->isThumb()) { 3050 // Invert the bits. 3051 isRead = ~isRead & 1; 3052 isData = ~isData & 1; 3053 } 3054 3055 return DAG.getNode(ARMISD::PRELOAD, dl, MVT::Other, Op.getOperand(0), 3056 Op.getOperand(1), DAG.getConstant(isRead, dl, MVT::i32), 3057 DAG.getConstant(isData, dl, MVT::i32)); 3058 } 3059 3060 static SDValue LowerVASTART(SDValue Op, SelectionDAG &DAG) { 3061 MachineFunction &MF = DAG.getMachineFunction(); 3062 ARMFunctionInfo *FuncInfo = MF.getInfo<ARMFunctionInfo>(); 3063 3064 // vastart just stores the address of the VarArgsFrameIndex slot into the 3065 // memory location argument. 3066 SDLoc dl(Op); 3067 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout()); 3068 SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT); 3069 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue(); 3070 return DAG.getStore(Op.getOperand(0), dl, FR, Op.getOperand(1), 3071 MachinePointerInfo(SV), false, false, 0); 3072 } 3073 3074 SDValue ARMTargetLowering::GetF64FormalArgument(CCValAssign &VA, 3075 CCValAssign &NextVA, 3076 SDValue &Root, 3077 SelectionDAG &DAG, 3078 const SDLoc &dl) const { 3079 MachineFunction &MF = DAG.getMachineFunction(); 3080 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>(); 3081 3082 const TargetRegisterClass *RC; 3083 if (AFI->isThumb1OnlyFunction()) 3084 RC = &ARM::tGPRRegClass; 3085 else 3086 RC = &ARM::GPRRegClass; 3087 3088 // Transform the arguments stored in physical registers into virtual ones. 3089 unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC); 3090 SDValue ArgValue = DAG.getCopyFromReg(Root, dl, Reg, MVT::i32); 3091 3092 SDValue ArgValue2; 3093 if (NextVA.isMemLoc()) { 3094 MachineFrameInfo *MFI = MF.getFrameInfo(); 3095 int FI = MFI->CreateFixedObject(4, NextVA.getLocMemOffset(), true); 3096 3097 // Create load node to retrieve arguments from the stack. 3098 SDValue FIN = DAG.getFrameIndex(FI, getPointerTy(DAG.getDataLayout())); 3099 ArgValue2 = DAG.getLoad( 3100 MVT::i32, dl, Root, FIN, 3101 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI), false, 3102 false, false, 0); 3103 } else { 3104 Reg = MF.addLiveIn(NextVA.getLocReg(), RC); 3105 ArgValue2 = DAG.getCopyFromReg(Root, dl, Reg, MVT::i32); 3106 } 3107 if (!Subtarget->isLittle()) 3108 std::swap (ArgValue, ArgValue2); 3109 return DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, ArgValue, ArgValue2); 3110 } 3111 3112 // The remaining GPRs hold either the beginning of variable-argument 3113 // data, or the beginning of an aggregate passed by value (usually 3114 // byval). Either way, we allocate stack slots adjacent to the data 3115 // provided by our caller, and store the unallocated registers there. 3116 // If this is a variadic function, the va_list pointer will begin with 3117 // these values; otherwise, this reassembles a (byval) structure that 3118 // was split between registers and memory. 3119 // Return: The frame index registers were stored into. 3120 int ARMTargetLowering::StoreByValRegs(CCState &CCInfo, SelectionDAG &DAG, 3121 const SDLoc &dl, SDValue &Chain, 3122 const Value *OrigArg, 3123 unsigned InRegsParamRecordIdx, 3124 int ArgOffset, unsigned ArgSize) const { 3125 // Currently, two use-cases possible: 3126 // Case #1. Non-var-args function, and we meet first byval parameter. 3127 // Setup first unallocated register as first byval register; 3128 // eat all remained registers 3129 // (these two actions are performed by HandleByVal method). 3130 // Then, here, we initialize stack frame with 3131 // "store-reg" instructions. 3132 // Case #2. Var-args function, that doesn't contain byval parameters. 3133 // The same: eat all remained unallocated registers, 3134 // initialize stack frame. 3135 3136 MachineFunction &MF = DAG.getMachineFunction(); 3137 MachineFrameInfo *MFI = MF.getFrameInfo(); 3138 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>(); 3139 unsigned RBegin, REnd; 3140 if (InRegsParamRecordIdx < CCInfo.getInRegsParamsCount()) { 3141 CCInfo.getInRegsParamInfo(InRegsParamRecordIdx, RBegin, REnd); 3142 } else { 3143 unsigned RBeginIdx = CCInfo.getFirstUnallocated(GPRArgRegs); 3144 RBegin = RBeginIdx == 4 ? (unsigned)ARM::R4 : GPRArgRegs[RBeginIdx]; 3145 REnd = ARM::R4; 3146 } 3147 3148 if (REnd != RBegin) 3149 ArgOffset = -4 * (ARM::R4 - RBegin); 3150 3151 auto PtrVT = getPointerTy(DAG.getDataLayout()); 3152 int FrameIndex = MFI->CreateFixedObject(ArgSize, ArgOffset, false); 3153 SDValue FIN = DAG.getFrameIndex(FrameIndex, PtrVT); 3154 3155 SmallVector<SDValue, 4> MemOps; 3156 const TargetRegisterClass *RC = 3157 AFI->isThumb1OnlyFunction() ? &ARM::tGPRRegClass : &ARM::GPRRegClass; 3158 3159 for (unsigned Reg = RBegin, i = 0; Reg < REnd; ++Reg, ++i) { 3160 unsigned VReg = MF.addLiveIn(Reg, RC); 3161 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i32); 3162 SDValue Store = 3163 DAG.getStore(Val.getValue(1), dl, Val, FIN, 3164 MachinePointerInfo(OrigArg, 4 * i), false, false, 0); 3165 MemOps.push_back(Store); 3166 FIN = DAG.getNode(ISD::ADD, dl, PtrVT, FIN, DAG.getConstant(4, dl, PtrVT)); 3167 } 3168 3169 if (!MemOps.empty()) 3170 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOps); 3171 return FrameIndex; 3172 } 3173 3174 // Setup stack frame, the va_list pointer will start from. 3175 void ARMTargetLowering::VarArgStyleRegisters(CCState &CCInfo, SelectionDAG &DAG, 3176 const SDLoc &dl, SDValue &Chain, 3177 unsigned ArgOffset, 3178 unsigned TotalArgRegsSaveSize, 3179 bool ForceMutable) const { 3180 MachineFunction &MF = DAG.getMachineFunction(); 3181 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>(); 3182 3183 // Try to store any remaining integer argument regs 3184 // to their spots on the stack so that they may be loaded by dereferencing 3185 // the result of va_next. 3186 // If there is no regs to be stored, just point address after last 3187 // argument passed via stack. 3188 int FrameIndex = StoreByValRegs(CCInfo, DAG, dl, Chain, nullptr, 3189 CCInfo.getInRegsParamsCount(), 3190 CCInfo.getNextStackOffset(), 4); 3191 AFI->setVarArgsFrameIndex(FrameIndex); 3192 } 3193 3194 SDValue ARMTargetLowering::LowerFormalArguments( 3195 SDValue Chain, CallingConv::ID CallConv, bool isVarArg, 3196 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl, 3197 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const { 3198 MachineFunction &MF = DAG.getMachineFunction(); 3199 MachineFrameInfo *MFI = MF.getFrameInfo(); 3200 3201 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>(); 3202 3203 // Assign locations to all of the incoming arguments. 3204 SmallVector<CCValAssign, 16> ArgLocs; 3205 ARMCCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), ArgLocs, 3206 *DAG.getContext(), Prologue); 3207 CCInfo.AnalyzeFormalArguments(Ins, 3208 CCAssignFnForNode(CallConv, /* Return*/ false, 3209 isVarArg)); 3210 3211 SmallVector<SDValue, 16> ArgValues; 3212 SDValue ArgValue; 3213 Function::const_arg_iterator CurOrigArg = MF.getFunction()->arg_begin(); 3214 unsigned CurArgIdx = 0; 3215 3216 // Initially ArgRegsSaveSize is zero. 3217 // Then we increase this value each time we meet byval parameter. 3218 // We also increase this value in case of varargs function. 3219 AFI->setArgRegsSaveSize(0); 3220 3221 // Calculate the amount of stack space that we need to allocate to store 3222 // byval and variadic arguments that are passed in registers. 3223 // We need to know this before we allocate the first byval or variadic 3224 // argument, as they will be allocated a stack slot below the CFA (Canonical 3225 // Frame Address, the stack pointer at entry to the function). 3226 unsigned ArgRegBegin = ARM::R4; 3227 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) { 3228 if (CCInfo.getInRegsParamsProcessed() >= CCInfo.getInRegsParamsCount()) 3229 break; 3230 3231 CCValAssign &VA = ArgLocs[i]; 3232 unsigned Index = VA.getValNo(); 3233 ISD::ArgFlagsTy Flags = Ins[Index].Flags; 3234 if (!Flags.isByVal()) 3235 continue; 3236 3237 assert(VA.isMemLoc() && "unexpected byval pointer in reg"); 3238 unsigned RBegin, REnd; 3239 CCInfo.getInRegsParamInfo(CCInfo.getInRegsParamsProcessed(), RBegin, REnd); 3240 ArgRegBegin = std::min(ArgRegBegin, RBegin); 3241 3242 CCInfo.nextInRegsParam(); 3243 } 3244 CCInfo.rewindByValRegsInfo(); 3245 3246 int lastInsIndex = -1; 3247 if (isVarArg && MFI->hasVAStart()) { 3248 unsigned RegIdx = CCInfo.getFirstUnallocated(GPRArgRegs); 3249 if (RegIdx != array_lengthof(GPRArgRegs)) 3250 ArgRegBegin = std::min(ArgRegBegin, (unsigned)GPRArgRegs[RegIdx]); 3251 } 3252 3253 unsigned TotalArgRegsSaveSize = 4 * (ARM::R4 - ArgRegBegin); 3254 AFI->setArgRegsSaveSize(TotalArgRegsSaveSize); 3255 auto PtrVT = getPointerTy(DAG.getDataLayout()); 3256 3257 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) { 3258 CCValAssign &VA = ArgLocs[i]; 3259 if (Ins[VA.getValNo()].isOrigArg()) { 3260 std::advance(CurOrigArg, 3261 Ins[VA.getValNo()].getOrigArgIndex() - CurArgIdx); 3262 CurArgIdx = Ins[VA.getValNo()].getOrigArgIndex(); 3263 } 3264 // Arguments stored in registers. 3265 if (VA.isRegLoc()) { 3266 EVT RegVT = VA.getLocVT(); 3267 3268 if (VA.needsCustom()) { 3269 // f64 and vector types are split up into multiple registers or 3270 // combinations of registers and stack slots. 3271 if (VA.getLocVT() == MVT::v2f64) { 3272 SDValue ArgValue1 = GetF64FormalArgument(VA, ArgLocs[++i], 3273 Chain, DAG, dl); 3274 VA = ArgLocs[++i]; // skip ahead to next loc 3275 SDValue ArgValue2; 3276 if (VA.isMemLoc()) { 3277 int FI = MFI->CreateFixedObject(8, VA.getLocMemOffset(), true); 3278 SDValue FIN = DAG.getFrameIndex(FI, PtrVT); 3279 ArgValue2 = DAG.getLoad( 3280 MVT::f64, dl, Chain, FIN, 3281 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI), 3282 false, false, false, 0); 3283 } else { 3284 ArgValue2 = GetF64FormalArgument(VA, ArgLocs[++i], 3285 Chain, DAG, dl); 3286 } 3287 ArgValue = DAG.getNode(ISD::UNDEF, dl, MVT::v2f64); 3288 ArgValue = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, 3289 ArgValue, ArgValue1, 3290 DAG.getIntPtrConstant(0, dl)); 3291 ArgValue = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, 3292 ArgValue, ArgValue2, 3293 DAG.getIntPtrConstant(1, dl)); 3294 } else 3295 ArgValue = GetF64FormalArgument(VA, ArgLocs[++i], Chain, DAG, dl); 3296 3297 } else { 3298 const TargetRegisterClass *RC; 3299 3300 if (RegVT == MVT::f32) 3301 RC = &ARM::SPRRegClass; 3302 else if (RegVT == MVT::f64) 3303 RC = &ARM::DPRRegClass; 3304 else if (RegVT == MVT::v2f64) 3305 RC = &ARM::QPRRegClass; 3306 else if (RegVT == MVT::i32) 3307 RC = AFI->isThumb1OnlyFunction() ? &ARM::tGPRRegClass 3308 : &ARM::GPRRegClass; 3309 else 3310 llvm_unreachable("RegVT not supported by FORMAL_ARGUMENTS Lowering"); 3311 3312 // Transform the arguments in physical registers into virtual ones. 3313 unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC); 3314 ArgValue = DAG.getCopyFromReg(Chain, dl, Reg, RegVT); 3315 } 3316 3317 // If this is an 8 or 16-bit value, it is really passed promoted 3318 // to 32 bits. Insert an assert[sz]ext to capture this, then 3319 // truncate to the right size. 3320 switch (VA.getLocInfo()) { 3321 default: llvm_unreachable("Unknown loc info!"); 3322 case CCValAssign::Full: break; 3323 case CCValAssign::BCvt: 3324 ArgValue = DAG.getNode(ISD::BITCAST, dl, VA.getValVT(), ArgValue); 3325 break; 3326 case CCValAssign::SExt: 3327 ArgValue = DAG.getNode(ISD::AssertSext, dl, RegVT, ArgValue, 3328 DAG.getValueType(VA.getValVT())); 3329 ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue); 3330 break; 3331 case CCValAssign::ZExt: 3332 ArgValue = DAG.getNode(ISD::AssertZext, dl, RegVT, ArgValue, 3333 DAG.getValueType(VA.getValVT())); 3334 ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue); 3335 break; 3336 } 3337 3338 InVals.push_back(ArgValue); 3339 3340 } else { // VA.isRegLoc() 3341 3342 // sanity check 3343 assert(VA.isMemLoc()); 3344 assert(VA.getValVT() != MVT::i64 && "i64 should already be lowered"); 3345 3346 int index = VA.getValNo(); 3347 3348 // Some Ins[] entries become multiple ArgLoc[] entries. 3349 // Process them only once. 3350 if (index != lastInsIndex) 3351 { 3352 ISD::ArgFlagsTy Flags = Ins[index].Flags; 3353 // FIXME: For now, all byval parameter objects are marked mutable. 3354 // This can be changed with more analysis. 3355 // In case of tail call optimization mark all arguments mutable. 3356 // Since they could be overwritten by lowering of arguments in case of 3357 // a tail call. 3358 if (Flags.isByVal()) { 3359 assert(Ins[index].isOrigArg() && 3360 "Byval arguments cannot be implicit"); 3361 unsigned CurByValIndex = CCInfo.getInRegsParamsProcessed(); 3362 3363 int FrameIndex = StoreByValRegs( 3364 CCInfo, DAG, dl, Chain, &*CurOrigArg, CurByValIndex, 3365 VA.getLocMemOffset(), Flags.getByValSize()); 3366 InVals.push_back(DAG.getFrameIndex(FrameIndex, PtrVT)); 3367 CCInfo.nextInRegsParam(); 3368 } else { 3369 unsigned FIOffset = VA.getLocMemOffset(); 3370 int FI = MFI->CreateFixedObject(VA.getLocVT().getSizeInBits()/8, 3371 FIOffset, true); 3372 3373 // Create load nodes to retrieve arguments from the stack. 3374 SDValue FIN = DAG.getFrameIndex(FI, PtrVT); 3375 InVals.push_back(DAG.getLoad( 3376 VA.getValVT(), dl, Chain, FIN, 3377 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI), 3378 false, false, false, 0)); 3379 } 3380 lastInsIndex = index; 3381 } 3382 } 3383 } 3384 3385 // varargs 3386 if (isVarArg && MFI->hasVAStart()) 3387 VarArgStyleRegisters(CCInfo, DAG, dl, Chain, 3388 CCInfo.getNextStackOffset(), 3389 TotalArgRegsSaveSize); 3390 3391 AFI->setArgumentStackSize(CCInfo.getNextStackOffset()); 3392 3393 return Chain; 3394 } 3395 3396 /// isFloatingPointZero - Return true if this is +0.0. 3397 static bool isFloatingPointZero(SDValue Op) { 3398 if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Op)) 3399 return CFP->getValueAPF().isPosZero(); 3400 else if (ISD::isEXTLoad(Op.getNode()) || ISD::isNON_EXTLoad(Op.getNode())) { 3401 // Maybe this has already been legalized into the constant pool? 3402 if (Op.getOperand(1).getOpcode() == ARMISD::Wrapper) { 3403 SDValue WrapperOp = Op.getOperand(1).getOperand(0); 3404 if (ConstantPoolSDNode *CP = dyn_cast<ConstantPoolSDNode>(WrapperOp)) 3405 if (const ConstantFP *CFP = dyn_cast<ConstantFP>(CP->getConstVal())) 3406 return CFP->getValueAPF().isPosZero(); 3407 } 3408 } else if (Op->getOpcode() == ISD::BITCAST && 3409 Op->getValueType(0) == MVT::f64) { 3410 // Handle (ISD::BITCAST (ARMISD::VMOVIMM (ISD::TargetConstant 0)) MVT::f64) 3411 // created by LowerConstantFP(). 3412 SDValue BitcastOp = Op->getOperand(0); 3413 if (BitcastOp->getOpcode() == ARMISD::VMOVIMM && 3414 isNullConstant(BitcastOp->getOperand(0))) 3415 return true; 3416 } 3417 return false; 3418 } 3419 3420 /// Returns appropriate ARM CMP (cmp) and corresponding condition code for 3421 /// the given operands. 3422 SDValue ARMTargetLowering::getARMCmp(SDValue LHS, SDValue RHS, ISD::CondCode CC, 3423 SDValue &ARMcc, SelectionDAG &DAG, 3424 const SDLoc &dl) const { 3425 if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS.getNode())) { 3426 unsigned C = RHSC->getZExtValue(); 3427 if (!isLegalICmpImmediate(C)) { 3428 // Constant does not fit, try adjusting it by one? 3429 switch (CC) { 3430 default: break; 3431 case ISD::SETLT: 3432 case ISD::SETGE: 3433 if (C != 0x80000000 && isLegalICmpImmediate(C-1)) { 3434 CC = (CC == ISD::SETLT) ? ISD::SETLE : ISD::SETGT; 3435 RHS = DAG.getConstant(C - 1, dl, MVT::i32); 3436 } 3437 break; 3438 case ISD::SETULT: 3439 case ISD::SETUGE: 3440 if (C != 0 && isLegalICmpImmediate(C-1)) { 3441 CC = (CC == ISD::SETULT) ? ISD::SETULE : ISD::SETUGT; 3442 RHS = DAG.getConstant(C - 1, dl, MVT::i32); 3443 } 3444 break; 3445 case ISD::SETLE: 3446 case ISD::SETGT: 3447 if (C != 0x7fffffff && isLegalICmpImmediate(C+1)) { 3448 CC = (CC == ISD::SETLE) ? ISD::SETLT : ISD::SETGE; 3449 RHS = DAG.getConstant(C + 1, dl, MVT::i32); 3450 } 3451 break; 3452 case ISD::SETULE: 3453 case ISD::SETUGT: 3454 if (C != 0xffffffff && isLegalICmpImmediate(C+1)) { 3455 CC = (CC == ISD::SETULE) ? ISD::SETULT : ISD::SETUGE; 3456 RHS = DAG.getConstant(C + 1, dl, MVT::i32); 3457 } 3458 break; 3459 } 3460 } 3461 } 3462 3463 ARMCC::CondCodes CondCode = IntCCToARMCC(CC); 3464 ARMISD::NodeType CompareType; 3465 switch (CondCode) { 3466 default: 3467 CompareType = ARMISD::CMP; 3468 break; 3469 case ARMCC::EQ: 3470 case ARMCC::NE: 3471 // Uses only Z Flag 3472 CompareType = ARMISD::CMPZ; 3473 break; 3474 } 3475 ARMcc = DAG.getConstant(CondCode, dl, MVT::i32); 3476 return DAG.getNode(CompareType, dl, MVT::Glue, LHS, RHS); 3477 } 3478 3479 /// Returns a appropriate VFP CMP (fcmp{s|d}+fmstat) for the given operands. 3480 SDValue ARMTargetLowering::getVFPCmp(SDValue LHS, SDValue RHS, 3481 SelectionDAG &DAG, const SDLoc &dl) const { 3482 assert(!Subtarget->isFPOnlySP() || RHS.getValueType() != MVT::f64); 3483 SDValue Cmp; 3484 if (!isFloatingPointZero(RHS)) 3485 Cmp = DAG.getNode(ARMISD::CMPFP, dl, MVT::Glue, LHS, RHS); 3486 else 3487 Cmp = DAG.getNode(ARMISD::CMPFPw0, dl, MVT::Glue, LHS); 3488 return DAG.getNode(ARMISD::FMSTAT, dl, MVT::Glue, Cmp); 3489 } 3490 3491 /// duplicateCmp - Glue values can have only one use, so this function 3492 /// duplicates a comparison node. 3493 SDValue 3494 ARMTargetLowering::duplicateCmp(SDValue Cmp, SelectionDAG &DAG) const { 3495 unsigned Opc = Cmp.getOpcode(); 3496 SDLoc DL(Cmp); 3497 if (Opc == ARMISD::CMP || Opc == ARMISD::CMPZ) 3498 return DAG.getNode(Opc, DL, MVT::Glue, Cmp.getOperand(0),Cmp.getOperand(1)); 3499 3500 assert(Opc == ARMISD::FMSTAT && "unexpected comparison operation"); 3501 Cmp = Cmp.getOperand(0); 3502 Opc = Cmp.getOpcode(); 3503 if (Opc == ARMISD::CMPFP) 3504 Cmp = DAG.getNode(Opc, DL, MVT::Glue, Cmp.getOperand(0),Cmp.getOperand(1)); 3505 else { 3506 assert(Opc == ARMISD::CMPFPw0 && "unexpected operand of FMSTAT"); 3507 Cmp = DAG.getNode(Opc, DL, MVT::Glue, Cmp.getOperand(0)); 3508 } 3509 return DAG.getNode(ARMISD::FMSTAT, DL, MVT::Glue, Cmp); 3510 } 3511 3512 std::pair<SDValue, SDValue> 3513 ARMTargetLowering::getARMXALUOOp(SDValue Op, SelectionDAG &DAG, 3514 SDValue &ARMcc) const { 3515 assert(Op.getValueType() == MVT::i32 && "Unsupported value type"); 3516 3517 SDValue Value, OverflowCmp; 3518 SDValue LHS = Op.getOperand(0); 3519 SDValue RHS = Op.getOperand(1); 3520 SDLoc dl(Op); 3521 3522 // FIXME: We are currently always generating CMPs because we don't support 3523 // generating CMN through the backend. This is not as good as the natural 3524 // CMP case because it causes a register dependency and cannot be folded 3525 // later. 3526 3527 switch (Op.getOpcode()) { 3528 default: 3529 llvm_unreachable("Unknown overflow instruction!"); 3530 case ISD::SADDO: 3531 ARMcc = DAG.getConstant(ARMCC::VC, dl, MVT::i32); 3532 Value = DAG.getNode(ISD::ADD, dl, Op.getValueType(), LHS, RHS); 3533 OverflowCmp = DAG.getNode(ARMISD::CMP, dl, MVT::Glue, Value, LHS); 3534 break; 3535 case ISD::UADDO: 3536 ARMcc = DAG.getConstant(ARMCC::HS, dl, MVT::i32); 3537 Value = DAG.getNode(ISD::ADD, dl, Op.getValueType(), LHS, RHS); 3538 OverflowCmp = DAG.getNode(ARMISD::CMP, dl, MVT::Glue, Value, LHS); 3539 break; 3540 case ISD::SSUBO: 3541 ARMcc = DAG.getConstant(ARMCC::VC, dl, MVT::i32); 3542 Value = DAG.getNode(ISD::SUB, dl, Op.getValueType(), LHS, RHS); 3543 OverflowCmp = DAG.getNode(ARMISD::CMP, dl, MVT::Glue, LHS, RHS); 3544 break; 3545 case ISD::USUBO: 3546 ARMcc = DAG.getConstant(ARMCC::HS, dl, MVT::i32); 3547 Value = DAG.getNode(ISD::SUB, dl, Op.getValueType(), LHS, RHS); 3548 OverflowCmp = DAG.getNode(ARMISD::CMP, dl, MVT::Glue, LHS, RHS); 3549 break; 3550 } // switch (...) 3551 3552 return std::make_pair(Value, OverflowCmp); 3553 } 3554 3555 3556 SDValue 3557 ARMTargetLowering::LowerXALUO(SDValue Op, SelectionDAG &DAG) const { 3558 // Let legalize expand this if it isn't a legal type yet. 3559 if (!DAG.getTargetLoweringInfo().isTypeLegal(Op.getValueType())) 3560 return SDValue(); 3561 3562 SDValue Value, OverflowCmp; 3563 SDValue ARMcc; 3564 std::tie(Value, OverflowCmp) = getARMXALUOOp(Op, DAG, ARMcc); 3565 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32); 3566 SDLoc dl(Op); 3567 // We use 0 and 1 as false and true values. 3568 SDValue TVal = DAG.getConstant(1, dl, MVT::i32); 3569 SDValue FVal = DAG.getConstant(0, dl, MVT::i32); 3570 EVT VT = Op.getValueType(); 3571 3572 SDValue Overflow = DAG.getNode(ARMISD::CMOV, dl, VT, TVal, FVal, 3573 ARMcc, CCR, OverflowCmp); 3574 3575 SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32); 3576 return DAG.getNode(ISD::MERGE_VALUES, dl, VTs, Value, Overflow); 3577 } 3578 3579 3580 SDValue ARMTargetLowering::LowerSELECT(SDValue Op, SelectionDAG &DAG) const { 3581 SDValue Cond = Op.getOperand(0); 3582 SDValue SelectTrue = Op.getOperand(1); 3583 SDValue SelectFalse = Op.getOperand(2); 3584 SDLoc dl(Op); 3585 unsigned Opc = Cond.getOpcode(); 3586 3587 if (Cond.getResNo() == 1 && 3588 (Opc == ISD::SADDO || Opc == ISD::UADDO || Opc == ISD::SSUBO || 3589 Opc == ISD::USUBO)) { 3590 if (!DAG.getTargetLoweringInfo().isTypeLegal(Cond->getValueType(0))) 3591 return SDValue(); 3592 3593 SDValue Value, OverflowCmp; 3594 SDValue ARMcc; 3595 std::tie(Value, OverflowCmp) = getARMXALUOOp(Cond, DAG, ARMcc); 3596 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32); 3597 EVT VT = Op.getValueType(); 3598 3599 return getCMOV(dl, VT, SelectTrue, SelectFalse, ARMcc, CCR, 3600 OverflowCmp, DAG); 3601 } 3602 3603 // Convert: 3604 // 3605 // (select (cmov 1, 0, cond), t, f) -> (cmov t, f, cond) 3606 // (select (cmov 0, 1, cond), t, f) -> (cmov f, t, cond) 3607 // 3608 if (Cond.getOpcode() == ARMISD::CMOV && Cond.hasOneUse()) { 3609 const ConstantSDNode *CMOVTrue = 3610 dyn_cast<ConstantSDNode>(Cond.getOperand(0)); 3611 const ConstantSDNode *CMOVFalse = 3612 dyn_cast<ConstantSDNode>(Cond.getOperand(1)); 3613 3614 if (CMOVTrue && CMOVFalse) { 3615 unsigned CMOVTrueVal = CMOVTrue->getZExtValue(); 3616 unsigned CMOVFalseVal = CMOVFalse->getZExtValue(); 3617 3618 SDValue True; 3619 SDValue False; 3620 if (CMOVTrueVal == 1 && CMOVFalseVal == 0) { 3621 True = SelectTrue; 3622 False = SelectFalse; 3623 } else if (CMOVTrueVal == 0 && CMOVFalseVal == 1) { 3624 True = SelectFalse; 3625 False = SelectTrue; 3626 } 3627 3628 if (True.getNode() && False.getNode()) { 3629 EVT VT = Op.getValueType(); 3630 SDValue ARMcc = Cond.getOperand(2); 3631 SDValue CCR = Cond.getOperand(3); 3632 SDValue Cmp = duplicateCmp(Cond.getOperand(4), DAG); 3633 assert(True.getValueType() == VT); 3634 return getCMOV(dl, VT, True, False, ARMcc, CCR, Cmp, DAG); 3635 } 3636 } 3637 } 3638 3639 // ARM's BooleanContents value is UndefinedBooleanContent. Mask out the 3640 // undefined bits before doing a full-word comparison with zero. 3641 Cond = DAG.getNode(ISD::AND, dl, Cond.getValueType(), Cond, 3642 DAG.getConstant(1, dl, Cond.getValueType())); 3643 3644 return DAG.getSelectCC(dl, Cond, 3645 DAG.getConstant(0, dl, Cond.getValueType()), 3646 SelectTrue, SelectFalse, ISD::SETNE); 3647 } 3648 3649 static void checkVSELConstraints(ISD::CondCode CC, ARMCC::CondCodes &CondCode, 3650 bool &swpCmpOps, bool &swpVselOps) { 3651 // Start by selecting the GE condition code for opcodes that return true for 3652 // 'equality' 3653 if (CC == ISD::SETUGE || CC == ISD::SETOGE || CC == ISD::SETOLE || 3654 CC == ISD::SETULE) 3655 CondCode = ARMCC::GE; 3656 3657 // and GT for opcodes that return false for 'equality'. 3658 else if (CC == ISD::SETUGT || CC == ISD::SETOGT || CC == ISD::SETOLT || 3659 CC == ISD::SETULT) 3660 CondCode = ARMCC::GT; 3661 3662 // Since we are constrained to GE/GT, if the opcode contains 'less', we need 3663 // to swap the compare operands. 3664 if (CC == ISD::SETOLE || CC == ISD::SETULE || CC == ISD::SETOLT || 3665 CC == ISD::SETULT) 3666 swpCmpOps = true; 3667 3668 // Both GT and GE are ordered comparisons, and return false for 'unordered'. 3669 // If we have an unordered opcode, we need to swap the operands to the VSEL 3670 // instruction (effectively negating the condition). 3671 // 3672 // This also has the effect of swapping which one of 'less' or 'greater' 3673 // returns true, so we also swap the compare operands. It also switches 3674 // whether we return true for 'equality', so we compensate by picking the 3675 // opposite condition code to our original choice. 3676 if (CC == ISD::SETULE || CC == ISD::SETULT || CC == ISD::SETUGE || 3677 CC == ISD::SETUGT) { 3678 swpCmpOps = !swpCmpOps; 3679 swpVselOps = !swpVselOps; 3680 CondCode = CondCode == ARMCC::GT ? ARMCC::GE : ARMCC::GT; 3681 } 3682 3683 // 'ordered' is 'anything but unordered', so use the VS condition code and 3684 // swap the VSEL operands. 3685 if (CC == ISD::SETO) { 3686 CondCode = ARMCC::VS; 3687 swpVselOps = true; 3688 } 3689 3690 // 'unordered or not equal' is 'anything but equal', so use the EQ condition 3691 // code and swap the VSEL operands. 3692 if (CC == ISD::SETUNE) { 3693 CondCode = ARMCC::EQ; 3694 swpVselOps = true; 3695 } 3696 } 3697 3698 SDValue ARMTargetLowering::getCMOV(const SDLoc &dl, EVT VT, SDValue FalseVal, 3699 SDValue TrueVal, SDValue ARMcc, SDValue CCR, 3700 SDValue Cmp, SelectionDAG &DAG) const { 3701 if (Subtarget->isFPOnlySP() && VT == MVT::f64) { 3702 FalseVal = DAG.getNode(ARMISD::VMOVRRD, dl, 3703 DAG.getVTList(MVT::i32, MVT::i32), FalseVal); 3704 TrueVal = DAG.getNode(ARMISD::VMOVRRD, dl, 3705 DAG.getVTList(MVT::i32, MVT::i32), TrueVal); 3706 3707 SDValue TrueLow = TrueVal.getValue(0); 3708 SDValue TrueHigh = TrueVal.getValue(1); 3709 SDValue FalseLow = FalseVal.getValue(0); 3710 SDValue FalseHigh = FalseVal.getValue(1); 3711 3712 SDValue Low = DAG.getNode(ARMISD::CMOV, dl, MVT::i32, FalseLow, TrueLow, 3713 ARMcc, CCR, Cmp); 3714 SDValue High = DAG.getNode(ARMISD::CMOV, dl, MVT::i32, FalseHigh, TrueHigh, 3715 ARMcc, CCR, duplicateCmp(Cmp, DAG)); 3716 3717 return DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Low, High); 3718 } else { 3719 return DAG.getNode(ARMISD::CMOV, dl, VT, FalseVal, TrueVal, ARMcc, CCR, 3720 Cmp); 3721 } 3722 } 3723 3724 bool isGTorGE(ISD::CondCode CC) { return CC == ISD::SETGT || CC == ISD::SETGE; } 3725 3726 bool isLTorLE(ISD::CondCode CC) { return CC == ISD::SETLT || CC == ISD::SETLE; } 3727 3728 // See if a conditional (LHS CC RHS ? TrueVal : FalseVal) is lower-saturating. 3729 // All of these conditions (and their <= and >= counterparts) will do: 3730 // x < k ? k : x 3731 // x > k ? x : k 3732 // k < x ? x : k 3733 // k > x ? k : x 3734 bool isLowerSaturate(const SDValue LHS, const SDValue RHS, 3735 const SDValue TrueVal, const SDValue FalseVal, 3736 const ISD::CondCode CC, const SDValue K) { 3737 return (isGTorGE(CC) && 3738 ((K == LHS && K == TrueVal) || (K == RHS && K == FalseVal))) || 3739 (isLTorLE(CC) && 3740 ((K == RHS && K == TrueVal) || (K == LHS && K == FalseVal))); 3741 } 3742 3743 // Similar to isLowerSaturate(), but checks for upper-saturating conditions. 3744 bool isUpperSaturate(const SDValue LHS, const SDValue RHS, 3745 const SDValue TrueVal, const SDValue FalseVal, 3746 const ISD::CondCode CC, const SDValue K) { 3747 return (isGTorGE(CC) && 3748 ((K == RHS && K == TrueVal) || (K == LHS && K == FalseVal))) || 3749 (isLTorLE(CC) && 3750 ((K == LHS && K == TrueVal) || (K == RHS && K == FalseVal))); 3751 } 3752 3753 // Check if two chained conditionals could be converted into SSAT. 3754 // 3755 // SSAT can replace a set of two conditional selectors that bound a number to an 3756 // interval of type [k, ~k] when k + 1 is a power of 2. Here are some examples: 3757 // 3758 // x < -k ? -k : (x > k ? k : x) 3759 // x < -k ? -k : (x < k ? x : k) 3760 // x > -k ? (x > k ? k : x) : -k 3761 // x < k ? (x < -k ? -k : x) : k 3762 // etc. 3763 // 3764 // It returns true if the conversion can be done, false otherwise. 3765 // Additionally, the variable is returned in parameter V and the constant in K. 3766 bool isSaturatingConditional(const SDValue &Op, SDValue &V, uint64_t &K) { 3767 3768 SDValue LHS1 = Op.getOperand(0); 3769 SDValue RHS1 = Op.getOperand(1); 3770 SDValue TrueVal1 = Op.getOperand(2); 3771 SDValue FalseVal1 = Op.getOperand(3); 3772 ISD::CondCode CC1 = cast<CondCodeSDNode>(Op.getOperand(4))->get(); 3773 3774 const SDValue Op2 = isa<ConstantSDNode>(TrueVal1) ? FalseVal1 : TrueVal1; 3775 if (Op2.getOpcode() != ISD::SELECT_CC) 3776 return false; 3777 3778 SDValue LHS2 = Op2.getOperand(0); 3779 SDValue RHS2 = Op2.getOperand(1); 3780 SDValue TrueVal2 = Op2.getOperand(2); 3781 SDValue FalseVal2 = Op2.getOperand(3); 3782 ISD::CondCode CC2 = cast<CondCodeSDNode>(Op2.getOperand(4))->get(); 3783 3784 // Find out which are the constants and which are the variables 3785 // in each conditional 3786 SDValue *K1 = isa<ConstantSDNode>(LHS1) ? &LHS1 : isa<ConstantSDNode>(RHS1) 3787 ? &RHS1 3788 : NULL; 3789 SDValue *K2 = isa<ConstantSDNode>(LHS2) ? &LHS2 : isa<ConstantSDNode>(RHS2) 3790 ? &RHS2 3791 : NULL; 3792 SDValue K2Tmp = isa<ConstantSDNode>(TrueVal2) ? TrueVal2 : FalseVal2; 3793 SDValue V1Tmp = (K1 && *K1 == LHS1) ? RHS1 : LHS1; 3794 SDValue V2Tmp = (K2 && *K2 == LHS2) ? RHS2 : LHS2; 3795 SDValue V2 = (K2Tmp == TrueVal2) ? FalseVal2 : TrueVal2; 3796 3797 // We must detect cases where the original operations worked with 16- or 3798 // 8-bit values. In such case, V2Tmp != V2 because the comparison operations 3799 // must work with sign-extended values but the select operations return 3800 // the original non-extended value. 3801 SDValue V2TmpReg = V2Tmp; 3802 if (V2Tmp->getOpcode() == ISD::SIGN_EXTEND_INREG) 3803 V2TmpReg = V2Tmp->getOperand(0); 3804 3805 // Check that the registers and the constants have the correct values 3806 // in both conditionals 3807 if (!K1 || !K2 || *K1 == Op2 || *K2 != K2Tmp || V1Tmp != V2Tmp || 3808 V2TmpReg != V2) 3809 return false; 3810 3811 // Figure out which conditional is saturating the lower/upper bound. 3812 const SDValue *LowerCheckOp = 3813 isLowerSaturate(LHS1, RHS1, TrueVal1, FalseVal1, CC1, *K1) 3814 ? &Op 3815 : isLowerSaturate(LHS2, RHS2, TrueVal2, FalseVal2, CC2, *K2) ? &Op2 3816 : NULL; 3817 const SDValue *UpperCheckOp = 3818 isUpperSaturate(LHS1, RHS1, TrueVal1, FalseVal1, CC1, *K1) 3819 ? &Op 3820 : isUpperSaturate(LHS2, RHS2, TrueVal2, FalseVal2, CC2, *K2) ? &Op2 3821 : NULL; 3822 3823 if (!UpperCheckOp || !LowerCheckOp || LowerCheckOp == UpperCheckOp) 3824 return false; 3825 3826 // Check that the constant in the lower-bound check is 3827 // the opposite of the constant in the upper-bound check 3828 // in 1's complement. 3829 int64_t Val1 = cast<ConstantSDNode>(*K1)->getSExtValue(); 3830 int64_t Val2 = cast<ConstantSDNode>(*K2)->getSExtValue(); 3831 int64_t PosVal = std::max(Val1, Val2); 3832 3833 if (((Val1 > Val2 && UpperCheckOp == &Op) || 3834 (Val1 < Val2 && UpperCheckOp == &Op2)) && 3835 Val1 == ~Val2 && isPowerOf2_64(PosVal + 1)) { 3836 3837 V = V2; 3838 K = (uint64_t)PosVal; // At this point, PosVal is guaranteed to be positive 3839 return true; 3840 } 3841 3842 return false; 3843 } 3844 3845 SDValue ARMTargetLowering::LowerSELECT_CC(SDValue Op, SelectionDAG &DAG) const { 3846 3847 EVT VT = Op.getValueType(); 3848 SDLoc dl(Op); 3849 3850 // Try to convert two saturating conditional selects into a single SSAT 3851 SDValue SatValue; 3852 uint64_t SatConstant; 3853 if (isSaturatingConditional(Op, SatValue, SatConstant)) 3854 return DAG.getNode(ARMISD::SSAT, dl, VT, SatValue, 3855 DAG.getConstant(countTrailingOnes(SatConstant), dl, VT)); 3856 3857 SDValue LHS = Op.getOperand(0); 3858 SDValue RHS = Op.getOperand(1); 3859 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(4))->get(); 3860 SDValue TrueVal = Op.getOperand(2); 3861 SDValue FalseVal = Op.getOperand(3); 3862 3863 if (Subtarget->isFPOnlySP() && LHS.getValueType() == MVT::f64) { 3864 DAG.getTargetLoweringInfo().softenSetCCOperands(DAG, MVT::f64, LHS, RHS, CC, 3865 dl); 3866 3867 // If softenSetCCOperands only returned one value, we should compare it to 3868 // zero. 3869 if (!RHS.getNode()) { 3870 RHS = DAG.getConstant(0, dl, LHS.getValueType()); 3871 CC = ISD::SETNE; 3872 } 3873 } 3874 3875 if (LHS.getValueType() == MVT::i32) { 3876 // Try to generate VSEL on ARMv8. 3877 // The VSEL instruction can't use all the usual ARM condition 3878 // codes: it only has two bits to select the condition code, so it's 3879 // constrained to use only GE, GT, VS and EQ. 3880 // 3881 // To implement all the various ISD::SETXXX opcodes, we sometimes need to 3882 // swap the operands of the previous compare instruction (effectively 3883 // inverting the compare condition, swapping 'less' and 'greater') and 3884 // sometimes need to swap the operands to the VSEL (which inverts the 3885 // condition in the sense of firing whenever the previous condition didn't) 3886 if (Subtarget->hasFPARMv8() && (TrueVal.getValueType() == MVT::f32 || 3887 TrueVal.getValueType() == MVT::f64)) { 3888 ARMCC::CondCodes CondCode = IntCCToARMCC(CC); 3889 if (CondCode == ARMCC::LT || CondCode == ARMCC::LE || 3890 CondCode == ARMCC::VC || CondCode == ARMCC::NE) { 3891 CC = ISD::getSetCCInverse(CC, true); 3892 std::swap(TrueVal, FalseVal); 3893 } 3894 } 3895 3896 SDValue ARMcc; 3897 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32); 3898 SDValue Cmp = getARMCmp(LHS, RHS, CC, ARMcc, DAG, dl); 3899 return getCMOV(dl, VT, FalseVal, TrueVal, ARMcc, CCR, Cmp, DAG); 3900 } 3901 3902 ARMCC::CondCodes CondCode, CondCode2; 3903 FPCCToARMCC(CC, CondCode, CondCode2); 3904 3905 // Try to generate VMAXNM/VMINNM on ARMv8. 3906 if (Subtarget->hasFPARMv8() && (TrueVal.getValueType() == MVT::f32 || 3907 TrueVal.getValueType() == MVT::f64)) { 3908 bool swpCmpOps = false; 3909 bool swpVselOps = false; 3910 checkVSELConstraints(CC, CondCode, swpCmpOps, swpVselOps); 3911 3912 if (CondCode == ARMCC::GT || CondCode == ARMCC::GE || 3913 CondCode == ARMCC::VS || CondCode == ARMCC::EQ) { 3914 if (swpCmpOps) 3915 std::swap(LHS, RHS); 3916 if (swpVselOps) 3917 std::swap(TrueVal, FalseVal); 3918 } 3919 } 3920 3921 SDValue ARMcc = DAG.getConstant(CondCode, dl, MVT::i32); 3922 SDValue Cmp = getVFPCmp(LHS, RHS, DAG, dl); 3923 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32); 3924 SDValue Result = getCMOV(dl, VT, FalseVal, TrueVal, ARMcc, CCR, Cmp, DAG); 3925 if (CondCode2 != ARMCC::AL) { 3926 SDValue ARMcc2 = DAG.getConstant(CondCode2, dl, MVT::i32); 3927 // FIXME: Needs another CMP because flag can have but one use. 3928 SDValue Cmp2 = getVFPCmp(LHS, RHS, DAG, dl); 3929 Result = getCMOV(dl, VT, Result, TrueVal, ARMcc2, CCR, Cmp2, DAG); 3930 } 3931 return Result; 3932 } 3933 3934 /// canChangeToInt - Given the fp compare operand, return true if it is suitable 3935 /// to morph to an integer compare sequence. 3936 static bool canChangeToInt(SDValue Op, bool &SeenZero, 3937 const ARMSubtarget *Subtarget) { 3938 SDNode *N = Op.getNode(); 3939 if (!N->hasOneUse()) 3940 // Otherwise it requires moving the value from fp to integer registers. 3941 return false; 3942 if (!N->getNumValues()) 3943 return false; 3944 EVT VT = Op.getValueType(); 3945 if (VT != MVT::f32 && !Subtarget->isFPBrccSlow()) 3946 // f32 case is generally profitable. f64 case only makes sense when vcmpe + 3947 // vmrs are very slow, e.g. cortex-a8. 3948 return false; 3949 3950 if (isFloatingPointZero(Op)) { 3951 SeenZero = true; 3952 return true; 3953 } 3954 return ISD::isNormalLoad(N); 3955 } 3956 3957 static SDValue bitcastf32Toi32(SDValue Op, SelectionDAG &DAG) { 3958 if (isFloatingPointZero(Op)) 3959 return DAG.getConstant(0, SDLoc(Op), MVT::i32); 3960 3961 if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Op)) 3962 return DAG.getLoad(MVT::i32, SDLoc(Op), 3963 Ld->getChain(), Ld->getBasePtr(), Ld->getPointerInfo(), 3964 Ld->isVolatile(), Ld->isNonTemporal(), 3965 Ld->isInvariant(), Ld->getAlignment()); 3966 3967 llvm_unreachable("Unknown VFP cmp argument!"); 3968 } 3969 3970 static void expandf64Toi32(SDValue Op, SelectionDAG &DAG, 3971 SDValue &RetVal1, SDValue &RetVal2) { 3972 SDLoc dl(Op); 3973 3974 if (isFloatingPointZero(Op)) { 3975 RetVal1 = DAG.getConstant(0, dl, MVT::i32); 3976 RetVal2 = DAG.getConstant(0, dl, MVT::i32); 3977 return; 3978 } 3979 3980 if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Op)) { 3981 SDValue Ptr = Ld->getBasePtr(); 3982 RetVal1 = DAG.getLoad(MVT::i32, dl, 3983 Ld->getChain(), Ptr, 3984 Ld->getPointerInfo(), 3985 Ld->isVolatile(), Ld->isNonTemporal(), 3986 Ld->isInvariant(), Ld->getAlignment()); 3987 3988 EVT PtrType = Ptr.getValueType(); 3989 unsigned NewAlign = MinAlign(Ld->getAlignment(), 4); 3990 SDValue NewPtr = DAG.getNode(ISD::ADD, dl, 3991 PtrType, Ptr, DAG.getConstant(4, dl, PtrType)); 3992 RetVal2 = DAG.getLoad(MVT::i32, dl, 3993 Ld->getChain(), NewPtr, 3994 Ld->getPointerInfo().getWithOffset(4), 3995 Ld->isVolatile(), Ld->isNonTemporal(), 3996 Ld->isInvariant(), NewAlign); 3997 return; 3998 } 3999 4000 llvm_unreachable("Unknown VFP cmp argument!"); 4001 } 4002 4003 /// OptimizeVFPBrcond - With -enable-unsafe-fp-math, it's legal to optimize some 4004 /// f32 and even f64 comparisons to integer ones. 4005 SDValue 4006 ARMTargetLowering::OptimizeVFPBrcond(SDValue Op, SelectionDAG &DAG) const { 4007 SDValue Chain = Op.getOperand(0); 4008 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(1))->get(); 4009 SDValue LHS = Op.getOperand(2); 4010 SDValue RHS = Op.getOperand(3); 4011 SDValue Dest = Op.getOperand(4); 4012 SDLoc dl(Op); 4013 4014 bool LHSSeenZero = false; 4015 bool LHSOk = canChangeToInt(LHS, LHSSeenZero, Subtarget); 4016 bool RHSSeenZero = false; 4017 bool RHSOk = canChangeToInt(RHS, RHSSeenZero, Subtarget); 4018 if (LHSOk && RHSOk && (LHSSeenZero || RHSSeenZero)) { 4019 // If unsafe fp math optimization is enabled and there are no other uses of 4020 // the CMP operands, and the condition code is EQ or NE, we can optimize it 4021 // to an integer comparison. 4022 if (CC == ISD::SETOEQ) 4023 CC = ISD::SETEQ; 4024 else if (CC == ISD::SETUNE) 4025 CC = ISD::SETNE; 4026 4027 SDValue Mask = DAG.getConstant(0x7fffffff, dl, MVT::i32); 4028 SDValue ARMcc; 4029 if (LHS.getValueType() == MVT::f32) { 4030 LHS = DAG.getNode(ISD::AND, dl, MVT::i32, 4031 bitcastf32Toi32(LHS, DAG), Mask); 4032 RHS = DAG.getNode(ISD::AND, dl, MVT::i32, 4033 bitcastf32Toi32(RHS, DAG), Mask); 4034 SDValue Cmp = getARMCmp(LHS, RHS, CC, ARMcc, DAG, dl); 4035 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32); 4036 return DAG.getNode(ARMISD::BRCOND, dl, MVT::Other, 4037 Chain, Dest, ARMcc, CCR, Cmp); 4038 } 4039 4040 SDValue LHS1, LHS2; 4041 SDValue RHS1, RHS2; 4042 expandf64Toi32(LHS, DAG, LHS1, LHS2); 4043 expandf64Toi32(RHS, DAG, RHS1, RHS2); 4044 LHS2 = DAG.getNode(ISD::AND, dl, MVT::i32, LHS2, Mask); 4045 RHS2 = DAG.getNode(ISD::AND, dl, MVT::i32, RHS2, Mask); 4046 ARMCC::CondCodes CondCode = IntCCToARMCC(CC); 4047 ARMcc = DAG.getConstant(CondCode, dl, MVT::i32); 4048 SDVTList VTList = DAG.getVTList(MVT::Other, MVT::Glue); 4049 SDValue Ops[] = { Chain, ARMcc, LHS1, LHS2, RHS1, RHS2, Dest }; 4050 return DAG.getNode(ARMISD::BCC_i64, dl, VTList, Ops); 4051 } 4052 4053 return SDValue(); 4054 } 4055 4056 SDValue ARMTargetLowering::LowerBR_CC(SDValue Op, SelectionDAG &DAG) const { 4057 SDValue Chain = Op.getOperand(0); 4058 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(1))->get(); 4059 SDValue LHS = Op.getOperand(2); 4060 SDValue RHS = Op.getOperand(3); 4061 SDValue Dest = Op.getOperand(4); 4062 SDLoc dl(Op); 4063 4064 if (Subtarget->isFPOnlySP() && LHS.getValueType() == MVT::f64) { 4065 DAG.getTargetLoweringInfo().softenSetCCOperands(DAG, MVT::f64, LHS, RHS, CC, 4066 dl); 4067 4068 // If softenSetCCOperands only returned one value, we should compare it to 4069 // zero. 4070 if (!RHS.getNode()) { 4071 RHS = DAG.getConstant(0, dl, LHS.getValueType()); 4072 CC = ISD::SETNE; 4073 } 4074 } 4075 4076 if (LHS.getValueType() == MVT::i32) { 4077 SDValue ARMcc; 4078 SDValue Cmp = getARMCmp(LHS, RHS, CC, ARMcc, DAG, dl); 4079 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32); 4080 return DAG.getNode(ARMISD::BRCOND, dl, MVT::Other, 4081 Chain, Dest, ARMcc, CCR, Cmp); 4082 } 4083 4084 assert(LHS.getValueType() == MVT::f32 || LHS.getValueType() == MVT::f64); 4085 4086 if (getTargetMachine().Options.UnsafeFPMath && 4087 (CC == ISD::SETEQ || CC == ISD::SETOEQ || 4088 CC == ISD::SETNE || CC == ISD::SETUNE)) { 4089 if (SDValue Result = OptimizeVFPBrcond(Op, DAG)) 4090 return Result; 4091 } 4092 4093 ARMCC::CondCodes CondCode, CondCode2; 4094 FPCCToARMCC(CC, CondCode, CondCode2); 4095 4096 SDValue ARMcc = DAG.getConstant(CondCode, dl, MVT::i32); 4097 SDValue Cmp = getVFPCmp(LHS, RHS, DAG, dl); 4098 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32); 4099 SDVTList VTList = DAG.getVTList(MVT::Other, MVT::Glue); 4100 SDValue Ops[] = { Chain, Dest, ARMcc, CCR, Cmp }; 4101 SDValue Res = DAG.getNode(ARMISD::BRCOND, dl, VTList, Ops); 4102 if (CondCode2 != ARMCC::AL) { 4103 ARMcc = DAG.getConstant(CondCode2, dl, MVT::i32); 4104 SDValue Ops[] = { Res, Dest, ARMcc, CCR, Res.getValue(1) }; 4105 Res = DAG.getNode(ARMISD::BRCOND, dl, VTList, Ops); 4106 } 4107 return Res; 4108 } 4109 4110 SDValue ARMTargetLowering::LowerBR_JT(SDValue Op, SelectionDAG &DAG) const { 4111 SDValue Chain = Op.getOperand(0); 4112 SDValue Table = Op.getOperand(1); 4113 SDValue Index = Op.getOperand(2); 4114 SDLoc dl(Op); 4115 4116 EVT PTy = getPointerTy(DAG.getDataLayout()); 4117 JumpTableSDNode *JT = cast<JumpTableSDNode>(Table); 4118 SDValue JTI = DAG.getTargetJumpTable(JT->getIndex(), PTy); 4119 Table = DAG.getNode(ARMISD::WrapperJT, dl, MVT::i32, JTI); 4120 Index = DAG.getNode(ISD::MUL, dl, PTy, Index, DAG.getConstant(4, dl, PTy)); 4121 SDValue Addr = DAG.getNode(ISD::ADD, dl, PTy, Index, Table); 4122 if (Subtarget->isThumb2()) { 4123 // Thumb2 uses a two-level jump. That is, it jumps into the jump table 4124 // which does another jump to the destination. This also makes it easier 4125 // to translate it to TBB / TBH later. 4126 // FIXME: This might not work if the function is extremely large. 4127 return DAG.getNode(ARMISD::BR2_JT, dl, MVT::Other, Chain, 4128 Addr, Op.getOperand(2), JTI); 4129 } 4130 if (isPositionIndependent()) { 4131 Addr = 4132 DAG.getLoad((EVT)MVT::i32, dl, Chain, Addr, 4133 MachinePointerInfo::getJumpTable(DAG.getMachineFunction()), 4134 false, false, false, 0); 4135 Chain = Addr.getValue(1); 4136 Addr = DAG.getNode(ISD::ADD, dl, PTy, Addr, Table); 4137 return DAG.getNode(ARMISD::BR_JT, dl, MVT::Other, Chain, Addr, JTI); 4138 } else { 4139 Addr = 4140 DAG.getLoad(PTy, dl, Chain, Addr, 4141 MachinePointerInfo::getJumpTable(DAG.getMachineFunction()), 4142 false, false, false, 0); 4143 Chain = Addr.getValue(1); 4144 return DAG.getNode(ARMISD::BR_JT, dl, MVT::Other, Chain, Addr, JTI); 4145 } 4146 } 4147 4148 static SDValue LowerVectorFP_TO_INT(SDValue Op, SelectionDAG &DAG) { 4149 EVT VT = Op.getValueType(); 4150 SDLoc dl(Op); 4151 4152 if (Op.getValueType().getVectorElementType() == MVT::i32) { 4153 if (Op.getOperand(0).getValueType().getVectorElementType() == MVT::f32) 4154 return Op; 4155 return DAG.UnrollVectorOp(Op.getNode()); 4156 } 4157 4158 assert(Op.getOperand(0).getValueType() == MVT::v4f32 && 4159 "Invalid type for custom lowering!"); 4160 if (VT != MVT::v4i16) 4161 return DAG.UnrollVectorOp(Op.getNode()); 4162 4163 Op = DAG.getNode(Op.getOpcode(), dl, MVT::v4i32, Op.getOperand(0)); 4164 return DAG.getNode(ISD::TRUNCATE, dl, VT, Op); 4165 } 4166 4167 SDValue ARMTargetLowering::LowerFP_TO_INT(SDValue Op, SelectionDAG &DAG) const { 4168 EVT VT = Op.getValueType(); 4169 if (VT.isVector()) 4170 return LowerVectorFP_TO_INT(Op, DAG); 4171 if (Subtarget->isFPOnlySP() && Op.getOperand(0).getValueType() == MVT::f64) { 4172 RTLIB::Libcall LC; 4173 if (Op.getOpcode() == ISD::FP_TO_SINT) 4174 LC = RTLIB::getFPTOSINT(Op.getOperand(0).getValueType(), 4175 Op.getValueType()); 4176 else 4177 LC = RTLIB::getFPTOUINT(Op.getOperand(0).getValueType(), 4178 Op.getValueType()); 4179 return makeLibCall(DAG, LC, Op.getValueType(), Op.getOperand(0), 4180 /*isSigned*/ false, SDLoc(Op)).first; 4181 } 4182 4183 return Op; 4184 } 4185 4186 static SDValue LowerVectorINT_TO_FP(SDValue Op, SelectionDAG &DAG) { 4187 EVT VT = Op.getValueType(); 4188 SDLoc dl(Op); 4189 4190 if (Op.getOperand(0).getValueType().getVectorElementType() == MVT::i32) { 4191 if (VT.getVectorElementType() == MVT::f32) 4192 return Op; 4193 return DAG.UnrollVectorOp(Op.getNode()); 4194 } 4195 4196 assert(Op.getOperand(0).getValueType() == MVT::v4i16 && 4197 "Invalid type for custom lowering!"); 4198 if (VT != MVT::v4f32) 4199 return DAG.UnrollVectorOp(Op.getNode()); 4200 4201 unsigned CastOpc; 4202 unsigned Opc; 4203 switch (Op.getOpcode()) { 4204 default: llvm_unreachable("Invalid opcode!"); 4205 case ISD::SINT_TO_FP: 4206 CastOpc = ISD::SIGN_EXTEND; 4207 Opc = ISD::SINT_TO_FP; 4208 break; 4209 case ISD::UINT_TO_FP: 4210 CastOpc = ISD::ZERO_EXTEND; 4211 Opc = ISD::UINT_TO_FP; 4212 break; 4213 } 4214 4215 Op = DAG.getNode(CastOpc, dl, MVT::v4i32, Op.getOperand(0)); 4216 return DAG.getNode(Opc, dl, VT, Op); 4217 } 4218 4219 SDValue ARMTargetLowering::LowerINT_TO_FP(SDValue Op, SelectionDAG &DAG) const { 4220 EVT VT = Op.getValueType(); 4221 if (VT.isVector()) 4222 return LowerVectorINT_TO_FP(Op, DAG); 4223 if (Subtarget->isFPOnlySP() && Op.getValueType() == MVT::f64) { 4224 RTLIB::Libcall LC; 4225 if (Op.getOpcode() == ISD::SINT_TO_FP) 4226 LC = RTLIB::getSINTTOFP(Op.getOperand(0).getValueType(), 4227 Op.getValueType()); 4228 else 4229 LC = RTLIB::getUINTTOFP(Op.getOperand(0).getValueType(), 4230 Op.getValueType()); 4231 return makeLibCall(DAG, LC, Op.getValueType(), Op.getOperand(0), 4232 /*isSigned*/ false, SDLoc(Op)).first; 4233 } 4234 4235 return Op; 4236 } 4237 4238 SDValue ARMTargetLowering::LowerFCOPYSIGN(SDValue Op, SelectionDAG &DAG) const { 4239 // Implement fcopysign with a fabs and a conditional fneg. 4240 SDValue Tmp0 = Op.getOperand(0); 4241 SDValue Tmp1 = Op.getOperand(1); 4242 SDLoc dl(Op); 4243 EVT VT = Op.getValueType(); 4244 EVT SrcVT = Tmp1.getValueType(); 4245 bool InGPR = Tmp0.getOpcode() == ISD::BITCAST || 4246 Tmp0.getOpcode() == ARMISD::VMOVDRR; 4247 bool UseNEON = !InGPR && Subtarget->hasNEON(); 4248 4249 if (UseNEON) { 4250 // Use VBSL to copy the sign bit. 4251 unsigned EncodedVal = ARM_AM::createNEONModImm(0x6, 0x80); 4252 SDValue Mask = DAG.getNode(ARMISD::VMOVIMM, dl, MVT::v2i32, 4253 DAG.getTargetConstant(EncodedVal, dl, MVT::i32)); 4254 EVT OpVT = (VT == MVT::f32) ? MVT::v2i32 : MVT::v1i64; 4255 if (VT == MVT::f64) 4256 Mask = DAG.getNode(ARMISD::VSHL, dl, OpVT, 4257 DAG.getNode(ISD::BITCAST, dl, OpVT, Mask), 4258 DAG.getConstant(32, dl, MVT::i32)); 4259 else /*if (VT == MVT::f32)*/ 4260 Tmp0 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f32, Tmp0); 4261 if (SrcVT == MVT::f32) { 4262 Tmp1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f32, Tmp1); 4263 if (VT == MVT::f64) 4264 Tmp1 = DAG.getNode(ARMISD::VSHL, dl, OpVT, 4265 DAG.getNode(ISD::BITCAST, dl, OpVT, Tmp1), 4266 DAG.getConstant(32, dl, MVT::i32)); 4267 } else if (VT == MVT::f32) 4268 Tmp1 = DAG.getNode(ARMISD::VSHRu, dl, MVT::v1i64, 4269 DAG.getNode(ISD::BITCAST, dl, MVT::v1i64, Tmp1), 4270 DAG.getConstant(32, dl, MVT::i32)); 4271 Tmp0 = DAG.getNode(ISD::BITCAST, dl, OpVT, Tmp0); 4272 Tmp1 = DAG.getNode(ISD::BITCAST, dl, OpVT, Tmp1); 4273 4274 SDValue AllOnes = DAG.getTargetConstant(ARM_AM::createNEONModImm(0xe, 0xff), 4275 dl, MVT::i32); 4276 AllOnes = DAG.getNode(ARMISD::VMOVIMM, dl, MVT::v8i8, AllOnes); 4277 SDValue MaskNot = DAG.getNode(ISD::XOR, dl, OpVT, Mask, 4278 DAG.getNode(ISD::BITCAST, dl, OpVT, AllOnes)); 4279 4280 SDValue Res = DAG.getNode(ISD::OR, dl, OpVT, 4281 DAG.getNode(ISD::AND, dl, OpVT, Tmp1, Mask), 4282 DAG.getNode(ISD::AND, dl, OpVT, Tmp0, MaskNot)); 4283 if (VT == MVT::f32) { 4284 Res = DAG.getNode(ISD::BITCAST, dl, MVT::v2f32, Res); 4285 Res = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f32, Res, 4286 DAG.getConstant(0, dl, MVT::i32)); 4287 } else { 4288 Res = DAG.getNode(ISD::BITCAST, dl, MVT::f64, Res); 4289 } 4290 4291 return Res; 4292 } 4293 4294 // Bitcast operand 1 to i32. 4295 if (SrcVT == MVT::f64) 4296 Tmp1 = DAG.getNode(ARMISD::VMOVRRD, dl, DAG.getVTList(MVT::i32, MVT::i32), 4297 Tmp1).getValue(1); 4298 Tmp1 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Tmp1); 4299 4300 // Or in the signbit with integer operations. 4301 SDValue Mask1 = DAG.getConstant(0x80000000, dl, MVT::i32); 4302 SDValue Mask2 = DAG.getConstant(0x7fffffff, dl, MVT::i32); 4303 Tmp1 = DAG.getNode(ISD::AND, dl, MVT::i32, Tmp1, Mask1); 4304 if (VT == MVT::f32) { 4305 Tmp0 = DAG.getNode(ISD::AND, dl, MVT::i32, 4306 DAG.getNode(ISD::BITCAST, dl, MVT::i32, Tmp0), Mask2); 4307 return DAG.getNode(ISD::BITCAST, dl, MVT::f32, 4308 DAG.getNode(ISD::OR, dl, MVT::i32, Tmp0, Tmp1)); 4309 } 4310 4311 // f64: Or the high part with signbit and then combine two parts. 4312 Tmp0 = DAG.getNode(ARMISD::VMOVRRD, dl, DAG.getVTList(MVT::i32, MVT::i32), 4313 Tmp0); 4314 SDValue Lo = Tmp0.getValue(0); 4315 SDValue Hi = DAG.getNode(ISD::AND, dl, MVT::i32, Tmp0.getValue(1), Mask2); 4316 Hi = DAG.getNode(ISD::OR, dl, MVT::i32, Hi, Tmp1); 4317 return DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi); 4318 } 4319 4320 SDValue ARMTargetLowering::LowerRETURNADDR(SDValue Op, SelectionDAG &DAG) const{ 4321 MachineFunction &MF = DAG.getMachineFunction(); 4322 MachineFrameInfo *MFI = MF.getFrameInfo(); 4323 MFI->setReturnAddressIsTaken(true); 4324 4325 if (verifyReturnAddressArgumentIsConstant(Op, DAG)) 4326 return SDValue(); 4327 4328 EVT VT = Op.getValueType(); 4329 SDLoc dl(Op); 4330 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue(); 4331 if (Depth) { 4332 SDValue FrameAddr = LowerFRAMEADDR(Op, DAG); 4333 SDValue Offset = DAG.getConstant(4, dl, MVT::i32); 4334 return DAG.getLoad(VT, dl, DAG.getEntryNode(), 4335 DAG.getNode(ISD::ADD, dl, VT, FrameAddr, Offset), 4336 MachinePointerInfo(), false, false, false, 0); 4337 } 4338 4339 // Return LR, which contains the return address. Mark it an implicit live-in. 4340 unsigned Reg = MF.addLiveIn(ARM::LR, getRegClassFor(MVT::i32)); 4341 return DAG.getCopyFromReg(DAG.getEntryNode(), dl, Reg, VT); 4342 } 4343 4344 SDValue ARMTargetLowering::LowerFRAMEADDR(SDValue Op, SelectionDAG &DAG) const { 4345 const ARMBaseRegisterInfo &ARI = 4346 *static_cast<const ARMBaseRegisterInfo*>(RegInfo); 4347 MachineFunction &MF = DAG.getMachineFunction(); 4348 MachineFrameInfo *MFI = MF.getFrameInfo(); 4349 MFI->setFrameAddressIsTaken(true); 4350 4351 EVT VT = Op.getValueType(); 4352 SDLoc dl(Op); // FIXME probably not meaningful 4353 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue(); 4354 unsigned FrameReg = ARI.getFrameRegister(MF); 4355 SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, VT); 4356 while (Depth--) 4357 FrameAddr = DAG.getLoad(VT, dl, DAG.getEntryNode(), FrameAddr, 4358 MachinePointerInfo(), 4359 false, false, false, 0); 4360 return FrameAddr; 4361 } 4362 4363 // FIXME? Maybe this could be a TableGen attribute on some registers and 4364 // this table could be generated automatically from RegInfo. 4365 unsigned ARMTargetLowering::getRegisterByName(const char* RegName, EVT VT, 4366 SelectionDAG &DAG) const { 4367 unsigned Reg = StringSwitch<unsigned>(RegName) 4368 .Case("sp", ARM::SP) 4369 .Default(0); 4370 if (Reg) 4371 return Reg; 4372 report_fatal_error(Twine("Invalid register name \"" 4373 + StringRef(RegName) + "\".")); 4374 } 4375 4376 // Result is 64 bit value so split into two 32 bit values and return as a 4377 // pair of values. 4378 static void ExpandREAD_REGISTER(SDNode *N, SmallVectorImpl<SDValue> &Results, 4379 SelectionDAG &DAG) { 4380 SDLoc DL(N); 4381 4382 // This function is only supposed to be called for i64 type destination. 4383 assert(N->getValueType(0) == MVT::i64 4384 && "ExpandREAD_REGISTER called for non-i64 type result."); 4385 4386 SDValue Read = DAG.getNode(ISD::READ_REGISTER, DL, 4387 DAG.getVTList(MVT::i32, MVT::i32, MVT::Other), 4388 N->getOperand(0), 4389 N->getOperand(1)); 4390 4391 Results.push_back(DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, Read.getValue(0), 4392 Read.getValue(1))); 4393 Results.push_back(Read.getOperand(0)); 4394 } 4395 4396 /// \p BC is a bitcast that is about to be turned into a VMOVDRR. 4397 /// When \p DstVT, the destination type of \p BC, is on the vector 4398 /// register bank and the source of bitcast, \p Op, operates on the same bank, 4399 /// it might be possible to combine them, such that everything stays on the 4400 /// vector register bank. 4401 /// \p return The node that would replace \p BT, if the combine 4402 /// is possible. 4403 static SDValue CombineVMOVDRRCandidateWithVecOp(const SDNode *BC, 4404 SelectionDAG &DAG) { 4405 SDValue Op = BC->getOperand(0); 4406 EVT DstVT = BC->getValueType(0); 4407 4408 // The only vector instruction that can produce a scalar (remember, 4409 // since the bitcast was about to be turned into VMOVDRR, the source 4410 // type is i64) from a vector is EXTRACT_VECTOR_ELT. 4411 // Moreover, we can do this combine only if there is one use. 4412 // Finally, if the destination type is not a vector, there is not 4413 // much point on forcing everything on the vector bank. 4414 if (!DstVT.isVector() || Op.getOpcode() != ISD::EXTRACT_VECTOR_ELT || 4415 !Op.hasOneUse()) 4416 return SDValue(); 4417 4418 // If the index is not constant, we will introduce an additional 4419 // multiply that will stick. 4420 // Give up in that case. 4421 ConstantSDNode *Index = dyn_cast<ConstantSDNode>(Op.getOperand(1)); 4422 if (!Index) 4423 return SDValue(); 4424 unsigned DstNumElt = DstVT.getVectorNumElements(); 4425 4426 // Compute the new index. 4427 const APInt &APIntIndex = Index->getAPIntValue(); 4428 APInt NewIndex(APIntIndex.getBitWidth(), DstNumElt); 4429 NewIndex *= APIntIndex; 4430 // Check if the new constant index fits into i32. 4431 if (NewIndex.getBitWidth() > 32) 4432 return SDValue(); 4433 4434 // vMTy bitcast(i64 extractelt vNi64 src, i32 index) -> 4435 // vMTy extractsubvector vNxMTy (bitcast vNi64 src), i32 index*M) 4436 SDLoc dl(Op); 4437 SDValue ExtractSrc = Op.getOperand(0); 4438 EVT VecVT = EVT::getVectorVT( 4439 *DAG.getContext(), DstVT.getScalarType(), 4440 ExtractSrc.getValueType().getVectorNumElements() * DstNumElt); 4441 SDValue BitCast = DAG.getNode(ISD::BITCAST, dl, VecVT, ExtractSrc); 4442 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DstVT, BitCast, 4443 DAG.getConstant(NewIndex.getZExtValue(), dl, MVT::i32)); 4444 } 4445 4446 /// ExpandBITCAST - If the target supports VFP, this function is called to 4447 /// expand a bit convert where either the source or destination type is i64 to 4448 /// use a VMOVDRR or VMOVRRD node. This should not be done when the non-i64 4449 /// operand type is illegal (e.g., v2f32 for a target that doesn't support 4450 /// vectors), since the legalizer won't know what to do with that. 4451 static SDValue ExpandBITCAST(SDNode *N, SelectionDAG &DAG) { 4452 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 4453 SDLoc dl(N); 4454 SDValue Op = N->getOperand(0); 4455 4456 // This function is only supposed to be called for i64 types, either as the 4457 // source or destination of the bit convert. 4458 EVT SrcVT = Op.getValueType(); 4459 EVT DstVT = N->getValueType(0); 4460 assert((SrcVT == MVT::i64 || DstVT == MVT::i64) && 4461 "ExpandBITCAST called for non-i64 type"); 4462 4463 // Turn i64->f64 into VMOVDRR. 4464 if (SrcVT == MVT::i64 && TLI.isTypeLegal(DstVT)) { 4465 // Do not force values to GPRs (this is what VMOVDRR does for the inputs) 4466 // if we can combine the bitcast with its source. 4467 if (SDValue Val = CombineVMOVDRRCandidateWithVecOp(N, DAG)) 4468 return Val; 4469 4470 SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, Op, 4471 DAG.getConstant(0, dl, MVT::i32)); 4472 SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, Op, 4473 DAG.getConstant(1, dl, MVT::i32)); 4474 return DAG.getNode(ISD::BITCAST, dl, DstVT, 4475 DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi)); 4476 } 4477 4478 // Turn f64->i64 into VMOVRRD. 4479 if (DstVT == MVT::i64 && TLI.isTypeLegal(SrcVT)) { 4480 SDValue Cvt; 4481 if (DAG.getDataLayout().isBigEndian() && SrcVT.isVector() && 4482 SrcVT.getVectorNumElements() > 1) 4483 Cvt = DAG.getNode(ARMISD::VMOVRRD, dl, 4484 DAG.getVTList(MVT::i32, MVT::i32), 4485 DAG.getNode(ARMISD::VREV64, dl, SrcVT, Op)); 4486 else 4487 Cvt = DAG.getNode(ARMISD::VMOVRRD, dl, 4488 DAG.getVTList(MVT::i32, MVT::i32), Op); 4489 // Merge the pieces into a single i64 value. 4490 return DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Cvt, Cvt.getValue(1)); 4491 } 4492 4493 return SDValue(); 4494 } 4495 4496 /// getZeroVector - Returns a vector of specified type with all zero elements. 4497 /// Zero vectors are used to represent vector negation and in those cases 4498 /// will be implemented with the NEON VNEG instruction. However, VNEG does 4499 /// not support i64 elements, so sometimes the zero vectors will need to be 4500 /// explicitly constructed. Regardless, use a canonical VMOV to create the 4501 /// zero vector. 4502 static SDValue getZeroVector(EVT VT, SelectionDAG &DAG, const SDLoc &dl) { 4503 assert(VT.isVector() && "Expected a vector type"); 4504 // The canonical modified immediate encoding of a zero vector is....0! 4505 SDValue EncodedVal = DAG.getTargetConstant(0, dl, MVT::i32); 4506 EVT VmovVT = VT.is128BitVector() ? MVT::v4i32 : MVT::v2i32; 4507 SDValue Vmov = DAG.getNode(ARMISD::VMOVIMM, dl, VmovVT, EncodedVal); 4508 return DAG.getNode(ISD::BITCAST, dl, VT, Vmov); 4509 } 4510 4511 /// LowerShiftRightParts - Lower SRA_PARTS, which returns two 4512 /// i32 values and take a 2 x i32 value to shift plus a shift amount. 4513 SDValue ARMTargetLowering::LowerShiftRightParts(SDValue Op, 4514 SelectionDAG &DAG) const { 4515 assert(Op.getNumOperands() == 3 && "Not a double-shift!"); 4516 EVT VT = Op.getValueType(); 4517 unsigned VTBits = VT.getSizeInBits(); 4518 SDLoc dl(Op); 4519 SDValue ShOpLo = Op.getOperand(0); 4520 SDValue ShOpHi = Op.getOperand(1); 4521 SDValue ShAmt = Op.getOperand(2); 4522 SDValue ARMcc; 4523 unsigned Opc = (Op.getOpcode() == ISD::SRA_PARTS) ? ISD::SRA : ISD::SRL; 4524 4525 assert(Op.getOpcode() == ISD::SRA_PARTS || Op.getOpcode() == ISD::SRL_PARTS); 4526 4527 SDValue RevShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32, 4528 DAG.getConstant(VTBits, dl, MVT::i32), ShAmt); 4529 SDValue Tmp1 = DAG.getNode(ISD::SRL, dl, VT, ShOpLo, ShAmt); 4530 SDValue ExtraShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32, ShAmt, 4531 DAG.getConstant(VTBits, dl, MVT::i32)); 4532 SDValue Tmp2 = DAG.getNode(ISD::SHL, dl, VT, ShOpHi, RevShAmt); 4533 SDValue FalseVal = DAG.getNode(ISD::OR, dl, VT, Tmp1, Tmp2); 4534 SDValue TrueVal = DAG.getNode(Opc, dl, VT, ShOpHi, ExtraShAmt); 4535 4536 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32); 4537 SDValue Cmp = getARMCmp(ExtraShAmt, DAG.getConstant(0, dl, MVT::i32), 4538 ISD::SETGE, ARMcc, DAG, dl); 4539 SDValue Hi = DAG.getNode(Opc, dl, VT, ShOpHi, ShAmt); 4540 SDValue Lo = DAG.getNode(ARMISD::CMOV, dl, VT, FalseVal, TrueVal, ARMcc, 4541 CCR, Cmp); 4542 4543 SDValue Ops[2] = { Lo, Hi }; 4544 return DAG.getMergeValues(Ops, dl); 4545 } 4546 4547 /// LowerShiftLeftParts - Lower SHL_PARTS, which returns two 4548 /// i32 values and take a 2 x i32 value to shift plus a shift amount. 4549 SDValue ARMTargetLowering::LowerShiftLeftParts(SDValue Op, 4550 SelectionDAG &DAG) const { 4551 assert(Op.getNumOperands() == 3 && "Not a double-shift!"); 4552 EVT VT = Op.getValueType(); 4553 unsigned VTBits = VT.getSizeInBits(); 4554 SDLoc dl(Op); 4555 SDValue ShOpLo = Op.getOperand(0); 4556 SDValue ShOpHi = Op.getOperand(1); 4557 SDValue ShAmt = Op.getOperand(2); 4558 SDValue ARMcc; 4559 4560 assert(Op.getOpcode() == ISD::SHL_PARTS); 4561 SDValue RevShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32, 4562 DAG.getConstant(VTBits, dl, MVT::i32), ShAmt); 4563 SDValue Tmp1 = DAG.getNode(ISD::SRL, dl, VT, ShOpLo, RevShAmt); 4564 SDValue ExtraShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32, ShAmt, 4565 DAG.getConstant(VTBits, dl, MVT::i32)); 4566 SDValue Tmp2 = DAG.getNode(ISD::SHL, dl, VT, ShOpHi, ShAmt); 4567 SDValue Tmp3 = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ExtraShAmt); 4568 4569 SDValue FalseVal = DAG.getNode(ISD::OR, dl, VT, Tmp1, Tmp2); 4570 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32); 4571 SDValue Cmp = getARMCmp(ExtraShAmt, DAG.getConstant(0, dl, MVT::i32), 4572 ISD::SETGE, ARMcc, DAG, dl); 4573 SDValue Lo = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ShAmt); 4574 SDValue Hi = DAG.getNode(ARMISD::CMOV, dl, VT, FalseVal, Tmp3, ARMcc, 4575 CCR, Cmp); 4576 4577 SDValue Ops[2] = { Lo, Hi }; 4578 return DAG.getMergeValues(Ops, dl); 4579 } 4580 4581 SDValue ARMTargetLowering::LowerFLT_ROUNDS_(SDValue Op, 4582 SelectionDAG &DAG) const { 4583 // The rounding mode is in bits 23:22 of the FPSCR. 4584 // The ARM rounding mode value to FLT_ROUNDS mapping is 0->1, 1->2, 2->3, 3->0 4585 // The formula we use to implement this is (((FPSCR + 1 << 22) >> 22) & 3) 4586 // so that the shift + and get folded into a bitfield extract. 4587 SDLoc dl(Op); 4588 SDValue FPSCR = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::i32, 4589 DAG.getConstant(Intrinsic::arm_get_fpscr, dl, 4590 MVT::i32)); 4591 SDValue FltRounds = DAG.getNode(ISD::ADD, dl, MVT::i32, FPSCR, 4592 DAG.getConstant(1U << 22, dl, MVT::i32)); 4593 SDValue RMODE = DAG.getNode(ISD::SRL, dl, MVT::i32, FltRounds, 4594 DAG.getConstant(22, dl, MVT::i32)); 4595 return DAG.getNode(ISD::AND, dl, MVT::i32, RMODE, 4596 DAG.getConstant(3, dl, MVT::i32)); 4597 } 4598 4599 static SDValue LowerCTTZ(SDNode *N, SelectionDAG &DAG, 4600 const ARMSubtarget *ST) { 4601 SDLoc dl(N); 4602 EVT VT = N->getValueType(0); 4603 if (VT.isVector()) { 4604 assert(ST->hasNEON()); 4605 4606 // Compute the least significant set bit: LSB = X & -X 4607 SDValue X = N->getOperand(0); 4608 SDValue NX = DAG.getNode(ISD::SUB, dl, VT, getZeroVector(VT, DAG, dl), X); 4609 SDValue LSB = DAG.getNode(ISD::AND, dl, VT, X, NX); 4610 4611 EVT ElemTy = VT.getVectorElementType(); 4612 4613 if (ElemTy == MVT::i8) { 4614 // Compute with: cttz(x) = ctpop(lsb - 1) 4615 SDValue One = DAG.getNode(ARMISD::VMOVIMM, dl, VT, 4616 DAG.getTargetConstant(1, dl, ElemTy)); 4617 SDValue Bits = DAG.getNode(ISD::SUB, dl, VT, LSB, One); 4618 return DAG.getNode(ISD::CTPOP, dl, VT, Bits); 4619 } 4620 4621 if ((ElemTy == MVT::i16 || ElemTy == MVT::i32) && 4622 (N->getOpcode() == ISD::CTTZ_ZERO_UNDEF)) { 4623 // Compute with: cttz(x) = (width - 1) - ctlz(lsb), if x != 0 4624 unsigned NumBits = ElemTy.getSizeInBits(); 4625 SDValue WidthMinus1 = 4626 DAG.getNode(ARMISD::VMOVIMM, dl, VT, 4627 DAG.getTargetConstant(NumBits - 1, dl, ElemTy)); 4628 SDValue CTLZ = DAG.getNode(ISD::CTLZ, dl, VT, LSB); 4629 return DAG.getNode(ISD::SUB, dl, VT, WidthMinus1, CTLZ); 4630 } 4631 4632 // Compute with: cttz(x) = ctpop(lsb - 1) 4633 4634 // Since we can only compute the number of bits in a byte with vcnt.8, we 4635 // have to gather the result with pairwise addition (vpaddl) for i16, i32, 4636 // and i64. 4637 4638 // Compute LSB - 1. 4639 SDValue Bits; 4640 if (ElemTy == MVT::i64) { 4641 // Load constant 0xffff'ffff'ffff'ffff to register. 4642 SDValue FF = DAG.getNode(ARMISD::VMOVIMM, dl, VT, 4643 DAG.getTargetConstant(0x1eff, dl, MVT::i32)); 4644 Bits = DAG.getNode(ISD::ADD, dl, VT, LSB, FF); 4645 } else { 4646 SDValue One = DAG.getNode(ARMISD::VMOVIMM, dl, VT, 4647 DAG.getTargetConstant(1, dl, ElemTy)); 4648 Bits = DAG.getNode(ISD::SUB, dl, VT, LSB, One); 4649 } 4650 4651 // Count #bits with vcnt.8. 4652 EVT VT8Bit = VT.is64BitVector() ? MVT::v8i8 : MVT::v16i8; 4653 SDValue BitsVT8 = DAG.getNode(ISD::BITCAST, dl, VT8Bit, Bits); 4654 SDValue Cnt8 = DAG.getNode(ISD::CTPOP, dl, VT8Bit, BitsVT8); 4655 4656 // Gather the #bits with vpaddl (pairwise add.) 4657 EVT VT16Bit = VT.is64BitVector() ? MVT::v4i16 : MVT::v8i16; 4658 SDValue Cnt16 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT16Bit, 4659 DAG.getTargetConstant(Intrinsic::arm_neon_vpaddlu, dl, MVT::i32), 4660 Cnt8); 4661 if (ElemTy == MVT::i16) 4662 return Cnt16; 4663 4664 EVT VT32Bit = VT.is64BitVector() ? MVT::v2i32 : MVT::v4i32; 4665 SDValue Cnt32 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT32Bit, 4666 DAG.getTargetConstant(Intrinsic::arm_neon_vpaddlu, dl, MVT::i32), 4667 Cnt16); 4668 if (ElemTy == MVT::i32) 4669 return Cnt32; 4670 4671 assert(ElemTy == MVT::i64); 4672 SDValue Cnt64 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT, 4673 DAG.getTargetConstant(Intrinsic::arm_neon_vpaddlu, dl, MVT::i32), 4674 Cnt32); 4675 return Cnt64; 4676 } 4677 4678 if (!ST->hasV6T2Ops()) 4679 return SDValue(); 4680 4681 SDValue rbit = DAG.getNode(ISD::BITREVERSE, dl, VT, N->getOperand(0)); 4682 return DAG.getNode(ISD::CTLZ, dl, VT, rbit); 4683 } 4684 4685 /// getCTPOP16BitCounts - Returns a v8i8/v16i8 vector containing the bit-count 4686 /// for each 16-bit element from operand, repeated. The basic idea is to 4687 /// leverage vcnt to get the 8-bit counts, gather and add the results. 4688 /// 4689 /// Trace for v4i16: 4690 /// input = [v0 v1 v2 v3 ] (vi 16-bit element) 4691 /// cast: N0 = [w0 w1 w2 w3 w4 w5 w6 w7] (v0 = [w0 w1], wi 8-bit element) 4692 /// vcnt: N1 = [b0 b1 b2 b3 b4 b5 b6 b7] (bi = bit-count of 8-bit element wi) 4693 /// vrev: N2 = [b1 b0 b3 b2 b5 b4 b7 b6] 4694 /// [b0 b1 b2 b3 b4 b5 b6 b7] 4695 /// +[b1 b0 b3 b2 b5 b4 b7 b6] 4696 /// N3=N1+N2 = [k0 k0 k1 k1 k2 k2 k3 k3] (k0 = b0+b1 = bit-count of 16-bit v0, 4697 /// vuzp: = [k0 k1 k2 k3 k0 k1 k2 k3] each ki is 8-bits) 4698 static SDValue getCTPOP16BitCounts(SDNode *N, SelectionDAG &DAG) { 4699 EVT VT = N->getValueType(0); 4700 SDLoc DL(N); 4701 4702 EVT VT8Bit = VT.is64BitVector() ? MVT::v8i8 : MVT::v16i8; 4703 SDValue N0 = DAG.getNode(ISD::BITCAST, DL, VT8Bit, N->getOperand(0)); 4704 SDValue N1 = DAG.getNode(ISD::CTPOP, DL, VT8Bit, N0); 4705 SDValue N2 = DAG.getNode(ARMISD::VREV16, DL, VT8Bit, N1); 4706 SDValue N3 = DAG.getNode(ISD::ADD, DL, VT8Bit, N1, N2); 4707 return DAG.getNode(ARMISD::VUZP, DL, VT8Bit, N3, N3); 4708 } 4709 4710 /// lowerCTPOP16BitElements - Returns a v4i16/v8i16 vector containing the 4711 /// bit-count for each 16-bit element from the operand. We need slightly 4712 /// different sequencing for v4i16 and v8i16 to stay within NEON's available 4713 /// 64/128-bit registers. 4714 /// 4715 /// Trace for v4i16: 4716 /// input = [v0 v1 v2 v3 ] (vi 16-bit element) 4717 /// v8i8: BitCounts = [k0 k1 k2 k3 k0 k1 k2 k3 ] (ki is the bit-count of vi) 4718 /// v8i16:Extended = [k0 k1 k2 k3 k0 k1 k2 k3 ] 4719 /// v4i16:Extracted = [k0 k1 k2 k3 ] 4720 static SDValue lowerCTPOP16BitElements(SDNode *N, SelectionDAG &DAG) { 4721 EVT VT = N->getValueType(0); 4722 SDLoc DL(N); 4723 4724 SDValue BitCounts = getCTPOP16BitCounts(N, DAG); 4725 if (VT.is64BitVector()) { 4726 SDValue Extended = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::v8i16, BitCounts); 4727 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v4i16, Extended, 4728 DAG.getIntPtrConstant(0, DL)); 4729 } else { 4730 SDValue Extracted = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v8i8, 4731 BitCounts, DAG.getIntPtrConstant(0, DL)); 4732 return DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::v8i16, Extracted); 4733 } 4734 } 4735 4736 /// lowerCTPOP32BitElements - Returns a v2i32/v4i32 vector containing the 4737 /// bit-count for each 32-bit element from the operand. The idea here is 4738 /// to split the vector into 16-bit elements, leverage the 16-bit count 4739 /// routine, and then combine the results. 4740 /// 4741 /// Trace for v2i32 (v4i32 similar with Extracted/Extended exchanged): 4742 /// input = [v0 v1 ] (vi: 32-bit elements) 4743 /// Bitcast = [w0 w1 w2 w3 ] (wi: 16-bit elements, v0 = [w0 w1]) 4744 /// Counts16 = [k0 k1 k2 k3 ] (ki: 16-bit elements, bit-count of wi) 4745 /// vrev: N0 = [k1 k0 k3 k2 ] 4746 /// [k0 k1 k2 k3 ] 4747 /// N1 =+[k1 k0 k3 k2 ] 4748 /// [k0 k2 k1 k3 ] 4749 /// N2 =+[k1 k3 k0 k2 ] 4750 /// [k0 k2 k1 k3 ] 4751 /// Extended =+[k1 k3 k0 k2 ] 4752 /// [k0 k2 ] 4753 /// Extracted=+[k1 k3 ] 4754 /// 4755 static SDValue lowerCTPOP32BitElements(SDNode *N, SelectionDAG &DAG) { 4756 EVT VT = N->getValueType(0); 4757 SDLoc DL(N); 4758 4759 EVT VT16Bit = VT.is64BitVector() ? MVT::v4i16 : MVT::v8i16; 4760 4761 SDValue Bitcast = DAG.getNode(ISD::BITCAST, DL, VT16Bit, N->getOperand(0)); 4762 SDValue Counts16 = lowerCTPOP16BitElements(Bitcast.getNode(), DAG); 4763 SDValue N0 = DAG.getNode(ARMISD::VREV32, DL, VT16Bit, Counts16); 4764 SDValue N1 = DAG.getNode(ISD::ADD, DL, VT16Bit, Counts16, N0); 4765 SDValue N2 = DAG.getNode(ARMISD::VUZP, DL, VT16Bit, N1, N1); 4766 4767 if (VT.is64BitVector()) { 4768 SDValue Extended = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::v4i32, N2); 4769 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2i32, Extended, 4770 DAG.getIntPtrConstant(0, DL)); 4771 } else { 4772 SDValue Extracted = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v4i16, N2, 4773 DAG.getIntPtrConstant(0, DL)); 4774 return DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::v4i32, Extracted); 4775 } 4776 } 4777 4778 static SDValue LowerCTPOP(SDNode *N, SelectionDAG &DAG, 4779 const ARMSubtarget *ST) { 4780 EVT VT = N->getValueType(0); 4781 4782 assert(ST->hasNEON() && "Custom ctpop lowering requires NEON."); 4783 assert((VT == MVT::v2i32 || VT == MVT::v4i32 || 4784 VT == MVT::v4i16 || VT == MVT::v8i16) && 4785 "Unexpected type for custom ctpop lowering"); 4786 4787 if (VT.getVectorElementType() == MVT::i32) 4788 return lowerCTPOP32BitElements(N, DAG); 4789 else 4790 return lowerCTPOP16BitElements(N, DAG); 4791 } 4792 4793 static SDValue LowerShift(SDNode *N, SelectionDAG &DAG, 4794 const ARMSubtarget *ST) { 4795 EVT VT = N->getValueType(0); 4796 SDLoc dl(N); 4797 4798 if (!VT.isVector()) 4799 return SDValue(); 4800 4801 // Lower vector shifts on NEON to use VSHL. 4802 assert(ST->hasNEON() && "unexpected vector shift"); 4803 4804 // Left shifts translate directly to the vshiftu intrinsic. 4805 if (N->getOpcode() == ISD::SHL) 4806 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT, 4807 DAG.getConstant(Intrinsic::arm_neon_vshiftu, dl, 4808 MVT::i32), 4809 N->getOperand(0), N->getOperand(1)); 4810 4811 assert((N->getOpcode() == ISD::SRA || 4812 N->getOpcode() == ISD::SRL) && "unexpected vector shift opcode"); 4813 4814 // NEON uses the same intrinsics for both left and right shifts. For 4815 // right shifts, the shift amounts are negative, so negate the vector of 4816 // shift amounts. 4817 EVT ShiftVT = N->getOperand(1).getValueType(); 4818 SDValue NegatedCount = DAG.getNode(ISD::SUB, dl, ShiftVT, 4819 getZeroVector(ShiftVT, DAG, dl), 4820 N->getOperand(1)); 4821 Intrinsic::ID vshiftInt = (N->getOpcode() == ISD::SRA ? 4822 Intrinsic::arm_neon_vshifts : 4823 Intrinsic::arm_neon_vshiftu); 4824 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT, 4825 DAG.getConstant(vshiftInt, dl, MVT::i32), 4826 N->getOperand(0), NegatedCount); 4827 } 4828 4829 static SDValue Expand64BitShift(SDNode *N, SelectionDAG &DAG, 4830 const ARMSubtarget *ST) { 4831 EVT VT = N->getValueType(0); 4832 SDLoc dl(N); 4833 4834 // We can get here for a node like i32 = ISD::SHL i32, i64 4835 if (VT != MVT::i64) 4836 return SDValue(); 4837 4838 assert((N->getOpcode() == ISD::SRL || N->getOpcode() == ISD::SRA) && 4839 "Unknown shift to lower!"); 4840 4841 // We only lower SRA, SRL of 1 here, all others use generic lowering. 4842 if (!isOneConstant(N->getOperand(1))) 4843 return SDValue(); 4844 4845 // If we are in thumb mode, we don't have RRX. 4846 if (ST->isThumb1Only()) return SDValue(); 4847 4848 // Okay, we have a 64-bit SRA or SRL of 1. Lower this to an RRX expr. 4849 SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(0), 4850 DAG.getConstant(0, dl, MVT::i32)); 4851 SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(0), 4852 DAG.getConstant(1, dl, MVT::i32)); 4853 4854 // First, build a SRA_FLAG/SRL_FLAG op, which shifts the top part by one and 4855 // captures the result into a carry flag. 4856 unsigned Opc = N->getOpcode() == ISD::SRL ? ARMISD::SRL_FLAG:ARMISD::SRA_FLAG; 4857 Hi = DAG.getNode(Opc, dl, DAG.getVTList(MVT::i32, MVT::Glue), Hi); 4858 4859 // The low part is an ARMISD::RRX operand, which shifts the carry in. 4860 Lo = DAG.getNode(ARMISD::RRX, dl, MVT::i32, Lo, Hi.getValue(1)); 4861 4862 // Merge the pieces into a single i64 value. 4863 return DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Lo, Hi); 4864 } 4865 4866 static SDValue LowerVSETCC(SDValue Op, SelectionDAG &DAG) { 4867 SDValue TmpOp0, TmpOp1; 4868 bool Invert = false; 4869 bool Swap = false; 4870 unsigned Opc = 0; 4871 4872 SDValue Op0 = Op.getOperand(0); 4873 SDValue Op1 = Op.getOperand(1); 4874 SDValue CC = Op.getOperand(2); 4875 EVT CmpVT = Op0.getValueType().changeVectorElementTypeToInteger(); 4876 EVT VT = Op.getValueType(); 4877 ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get(); 4878 SDLoc dl(Op); 4879 4880 if (CmpVT.getVectorElementType() == MVT::i64) 4881 // 64-bit comparisons are not legal. We've marked SETCC as non-Custom, 4882 // but it's possible that our operands are 64-bit but our result is 32-bit. 4883 // Bail in this case. 4884 return SDValue(); 4885 4886 if (Op1.getValueType().isFloatingPoint()) { 4887 switch (SetCCOpcode) { 4888 default: llvm_unreachable("Illegal FP comparison"); 4889 case ISD::SETUNE: 4890 case ISD::SETNE: Invert = true; // Fallthrough 4891 case ISD::SETOEQ: 4892 case ISD::SETEQ: Opc = ARMISD::VCEQ; break; 4893 case ISD::SETOLT: 4894 case ISD::SETLT: Swap = true; // Fallthrough 4895 case ISD::SETOGT: 4896 case ISD::SETGT: Opc = ARMISD::VCGT; break; 4897 case ISD::SETOLE: 4898 case ISD::SETLE: Swap = true; // Fallthrough 4899 case ISD::SETOGE: 4900 case ISD::SETGE: Opc = ARMISD::VCGE; break; 4901 case ISD::SETUGE: Swap = true; // Fallthrough 4902 case ISD::SETULE: Invert = true; Opc = ARMISD::VCGT; break; 4903 case ISD::SETUGT: Swap = true; // Fallthrough 4904 case ISD::SETULT: Invert = true; Opc = ARMISD::VCGE; break; 4905 case ISD::SETUEQ: Invert = true; // Fallthrough 4906 case ISD::SETONE: 4907 // Expand this to (OLT | OGT). 4908 TmpOp0 = Op0; 4909 TmpOp1 = Op1; 4910 Opc = ISD::OR; 4911 Op0 = DAG.getNode(ARMISD::VCGT, dl, CmpVT, TmpOp1, TmpOp0); 4912 Op1 = DAG.getNode(ARMISD::VCGT, dl, CmpVT, TmpOp0, TmpOp1); 4913 break; 4914 case ISD::SETUO: Invert = true; // Fallthrough 4915 case ISD::SETO: 4916 // Expand this to (OLT | OGE). 4917 TmpOp0 = Op0; 4918 TmpOp1 = Op1; 4919 Opc = ISD::OR; 4920 Op0 = DAG.getNode(ARMISD::VCGT, dl, CmpVT, TmpOp1, TmpOp0); 4921 Op1 = DAG.getNode(ARMISD::VCGE, dl, CmpVT, TmpOp0, TmpOp1); 4922 break; 4923 } 4924 } else { 4925 // Integer comparisons. 4926 switch (SetCCOpcode) { 4927 default: llvm_unreachable("Illegal integer comparison"); 4928 case ISD::SETNE: Invert = true; 4929 case ISD::SETEQ: Opc = ARMISD::VCEQ; break; 4930 case ISD::SETLT: Swap = true; 4931 case ISD::SETGT: Opc = ARMISD::VCGT; break; 4932 case ISD::SETLE: Swap = true; 4933 case ISD::SETGE: Opc = ARMISD::VCGE; break; 4934 case ISD::SETULT: Swap = true; 4935 case ISD::SETUGT: Opc = ARMISD::VCGTU; break; 4936 case ISD::SETULE: Swap = true; 4937 case ISD::SETUGE: Opc = ARMISD::VCGEU; break; 4938 } 4939 4940 // Detect VTST (Vector Test Bits) = icmp ne (and (op0, op1), zero). 4941 if (Opc == ARMISD::VCEQ) { 4942 4943 SDValue AndOp; 4944 if (ISD::isBuildVectorAllZeros(Op1.getNode())) 4945 AndOp = Op0; 4946 else if (ISD::isBuildVectorAllZeros(Op0.getNode())) 4947 AndOp = Op1; 4948 4949 // Ignore bitconvert. 4950 if (AndOp.getNode() && AndOp.getOpcode() == ISD::BITCAST) 4951 AndOp = AndOp.getOperand(0); 4952 4953 if (AndOp.getNode() && AndOp.getOpcode() == ISD::AND) { 4954 Opc = ARMISD::VTST; 4955 Op0 = DAG.getNode(ISD::BITCAST, dl, CmpVT, AndOp.getOperand(0)); 4956 Op1 = DAG.getNode(ISD::BITCAST, dl, CmpVT, AndOp.getOperand(1)); 4957 Invert = !Invert; 4958 } 4959 } 4960 } 4961 4962 if (Swap) 4963 std::swap(Op0, Op1); 4964 4965 // If one of the operands is a constant vector zero, attempt to fold the 4966 // comparison to a specialized compare-against-zero form. 4967 SDValue SingleOp; 4968 if (ISD::isBuildVectorAllZeros(Op1.getNode())) 4969 SingleOp = Op0; 4970 else if (ISD::isBuildVectorAllZeros(Op0.getNode())) { 4971 if (Opc == ARMISD::VCGE) 4972 Opc = ARMISD::VCLEZ; 4973 else if (Opc == ARMISD::VCGT) 4974 Opc = ARMISD::VCLTZ; 4975 SingleOp = Op1; 4976 } 4977 4978 SDValue Result; 4979 if (SingleOp.getNode()) { 4980 switch (Opc) { 4981 case ARMISD::VCEQ: 4982 Result = DAG.getNode(ARMISD::VCEQZ, dl, CmpVT, SingleOp); break; 4983 case ARMISD::VCGE: 4984 Result = DAG.getNode(ARMISD::VCGEZ, dl, CmpVT, SingleOp); break; 4985 case ARMISD::VCLEZ: 4986 Result = DAG.getNode(ARMISD::VCLEZ, dl, CmpVT, SingleOp); break; 4987 case ARMISD::VCGT: 4988 Result = DAG.getNode(ARMISD::VCGTZ, dl, CmpVT, SingleOp); break; 4989 case ARMISD::VCLTZ: 4990 Result = DAG.getNode(ARMISD::VCLTZ, dl, CmpVT, SingleOp); break; 4991 default: 4992 Result = DAG.getNode(Opc, dl, CmpVT, Op0, Op1); 4993 } 4994 } else { 4995 Result = DAG.getNode(Opc, dl, CmpVT, Op0, Op1); 4996 } 4997 4998 Result = DAG.getSExtOrTrunc(Result, dl, VT); 4999 5000 if (Invert) 5001 Result = DAG.getNOT(dl, Result, VT); 5002 5003 return Result; 5004 } 5005 5006 static SDValue LowerSETCCE(SDValue Op, SelectionDAG &DAG) { 5007 SDValue LHS = Op.getOperand(0); 5008 SDValue RHS = Op.getOperand(1); 5009 SDValue Carry = Op.getOperand(2); 5010 SDValue Cond = Op.getOperand(3); 5011 SDLoc DL(Op); 5012 5013 assert(LHS.getSimpleValueType().isInteger() && "SETCCE is integer only."); 5014 5015 assert(Carry.getOpcode() != ISD::CARRY_FALSE); 5016 SDVTList VTs = DAG.getVTList(LHS.getValueType(), MVT::i32); 5017 SDValue Cmp = DAG.getNode(ARMISD::SUBE, DL, VTs, LHS, RHS, Carry); 5018 5019 SDValue FVal = DAG.getConstant(0, DL, MVT::i32); 5020 SDValue TVal = DAG.getConstant(1, DL, MVT::i32); 5021 SDValue ARMcc = DAG.getConstant( 5022 IntCCToARMCC(cast<CondCodeSDNode>(Cond)->get()), DL, MVT::i32); 5023 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32); 5024 SDValue Chain = DAG.getCopyToReg(DAG.getEntryNode(), DL, ARM::CPSR, 5025 Cmp.getValue(1), SDValue()); 5026 return DAG.getNode(ARMISD::CMOV, DL, Op.getValueType(), FVal, TVal, ARMcc, 5027 CCR, Chain.getValue(1)); 5028 } 5029 5030 /// isNEONModifiedImm - Check if the specified splat value corresponds to a 5031 /// valid vector constant for a NEON instruction with a "modified immediate" 5032 /// operand (e.g., VMOV). If so, return the encoded value. 5033 static SDValue isNEONModifiedImm(uint64_t SplatBits, uint64_t SplatUndef, 5034 unsigned SplatBitSize, SelectionDAG &DAG, 5035 const SDLoc &dl, EVT &VT, bool is128Bits, 5036 NEONModImmType type) { 5037 unsigned OpCmode, Imm; 5038 5039 // SplatBitSize is set to the smallest size that splats the vector, so a 5040 // zero vector will always have SplatBitSize == 8. However, NEON modified 5041 // immediate instructions others than VMOV do not support the 8-bit encoding 5042 // of a zero vector, and the default encoding of zero is supposed to be the 5043 // 32-bit version. 5044 if (SplatBits == 0) 5045 SplatBitSize = 32; 5046 5047 switch (SplatBitSize) { 5048 case 8: 5049 if (type != VMOVModImm) 5050 return SDValue(); 5051 // Any 1-byte value is OK. Op=0, Cmode=1110. 5052 assert((SplatBits & ~0xff) == 0 && "one byte splat value is too big"); 5053 OpCmode = 0xe; 5054 Imm = SplatBits; 5055 VT = is128Bits ? MVT::v16i8 : MVT::v8i8; 5056 break; 5057 5058 case 16: 5059 // NEON's 16-bit VMOV supports splat values where only one byte is nonzero. 5060 VT = is128Bits ? MVT::v8i16 : MVT::v4i16; 5061 if ((SplatBits & ~0xff) == 0) { 5062 // Value = 0x00nn: Op=x, Cmode=100x. 5063 OpCmode = 0x8; 5064 Imm = SplatBits; 5065 break; 5066 } 5067 if ((SplatBits & ~0xff00) == 0) { 5068 // Value = 0xnn00: Op=x, Cmode=101x. 5069 OpCmode = 0xa; 5070 Imm = SplatBits >> 8; 5071 break; 5072 } 5073 return SDValue(); 5074 5075 case 32: 5076 // NEON's 32-bit VMOV supports splat values where: 5077 // * only one byte is nonzero, or 5078 // * the least significant byte is 0xff and the second byte is nonzero, or 5079 // * the least significant 2 bytes are 0xff and the third is nonzero. 5080 VT = is128Bits ? MVT::v4i32 : MVT::v2i32; 5081 if ((SplatBits & ~0xff) == 0) { 5082 // Value = 0x000000nn: Op=x, Cmode=000x. 5083 OpCmode = 0; 5084 Imm = SplatBits; 5085 break; 5086 } 5087 if ((SplatBits & ~0xff00) == 0) { 5088 // Value = 0x0000nn00: Op=x, Cmode=001x. 5089 OpCmode = 0x2; 5090 Imm = SplatBits >> 8; 5091 break; 5092 } 5093 if ((SplatBits & ~0xff0000) == 0) { 5094 // Value = 0x00nn0000: Op=x, Cmode=010x. 5095 OpCmode = 0x4; 5096 Imm = SplatBits >> 16; 5097 break; 5098 } 5099 if ((SplatBits & ~0xff000000) == 0) { 5100 // Value = 0xnn000000: Op=x, Cmode=011x. 5101 OpCmode = 0x6; 5102 Imm = SplatBits >> 24; 5103 break; 5104 } 5105 5106 // cmode == 0b1100 and cmode == 0b1101 are not supported for VORR or VBIC 5107 if (type == OtherModImm) return SDValue(); 5108 5109 if ((SplatBits & ~0xffff) == 0 && 5110 ((SplatBits | SplatUndef) & 0xff) == 0xff) { 5111 // Value = 0x0000nnff: Op=x, Cmode=1100. 5112 OpCmode = 0xc; 5113 Imm = SplatBits >> 8; 5114 break; 5115 } 5116 5117 if ((SplatBits & ~0xffffff) == 0 && 5118 ((SplatBits | SplatUndef) & 0xffff) == 0xffff) { 5119 // Value = 0x00nnffff: Op=x, Cmode=1101. 5120 OpCmode = 0xd; 5121 Imm = SplatBits >> 16; 5122 break; 5123 } 5124 5125 // Note: there are a few 32-bit splat values (specifically: 00ffff00, 5126 // ff000000, ff0000ff, and ffff00ff) that are valid for VMOV.I64 but not 5127 // VMOV.I32. A (very) minor optimization would be to replicate the value 5128 // and fall through here to test for a valid 64-bit splat. But, then the 5129 // caller would also need to check and handle the change in size. 5130 return SDValue(); 5131 5132 case 64: { 5133 if (type != VMOVModImm) 5134 return SDValue(); 5135 // NEON has a 64-bit VMOV splat where each byte is either 0 or 0xff. 5136 uint64_t BitMask = 0xff; 5137 uint64_t Val = 0; 5138 unsigned ImmMask = 1; 5139 Imm = 0; 5140 for (int ByteNum = 0; ByteNum < 8; ++ByteNum) { 5141 if (((SplatBits | SplatUndef) & BitMask) == BitMask) { 5142 Val |= BitMask; 5143 Imm |= ImmMask; 5144 } else if ((SplatBits & BitMask) != 0) { 5145 return SDValue(); 5146 } 5147 BitMask <<= 8; 5148 ImmMask <<= 1; 5149 } 5150 5151 if (DAG.getDataLayout().isBigEndian()) 5152 // swap higher and lower 32 bit word 5153 Imm = ((Imm & 0xf) << 4) | ((Imm & 0xf0) >> 4); 5154 5155 // Op=1, Cmode=1110. 5156 OpCmode = 0x1e; 5157 VT = is128Bits ? MVT::v2i64 : MVT::v1i64; 5158 break; 5159 } 5160 5161 default: 5162 llvm_unreachable("unexpected size for isNEONModifiedImm"); 5163 } 5164 5165 unsigned EncodedVal = ARM_AM::createNEONModImm(OpCmode, Imm); 5166 return DAG.getTargetConstant(EncodedVal, dl, MVT::i32); 5167 } 5168 5169 SDValue ARMTargetLowering::LowerConstantFP(SDValue Op, SelectionDAG &DAG, 5170 const ARMSubtarget *ST) const { 5171 if (!ST->hasVFP3()) 5172 return SDValue(); 5173 5174 bool IsDouble = Op.getValueType() == MVT::f64; 5175 ConstantFPSDNode *CFP = cast<ConstantFPSDNode>(Op); 5176 5177 // Use the default (constant pool) lowering for double constants when we have 5178 // an SP-only FPU 5179 if (IsDouble && Subtarget->isFPOnlySP()) 5180 return SDValue(); 5181 5182 // Try splatting with a VMOV.f32... 5183 const APFloat &FPVal = CFP->getValueAPF(); 5184 int ImmVal = IsDouble ? ARM_AM::getFP64Imm(FPVal) : ARM_AM::getFP32Imm(FPVal); 5185 5186 if (ImmVal != -1) { 5187 if (IsDouble || !ST->useNEONForSinglePrecisionFP()) { 5188 // We have code in place to select a valid ConstantFP already, no need to 5189 // do any mangling. 5190 return Op; 5191 } 5192 5193 // It's a float and we are trying to use NEON operations where 5194 // possible. Lower it to a splat followed by an extract. 5195 SDLoc DL(Op); 5196 SDValue NewVal = DAG.getTargetConstant(ImmVal, DL, MVT::i32); 5197 SDValue VecConstant = DAG.getNode(ARMISD::VMOVFPIMM, DL, MVT::v2f32, 5198 NewVal); 5199 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32, VecConstant, 5200 DAG.getConstant(0, DL, MVT::i32)); 5201 } 5202 5203 // The rest of our options are NEON only, make sure that's allowed before 5204 // proceeding.. 5205 if (!ST->hasNEON() || (!IsDouble && !ST->useNEONForSinglePrecisionFP())) 5206 return SDValue(); 5207 5208 EVT VMovVT; 5209 uint64_t iVal = FPVal.bitcastToAPInt().getZExtValue(); 5210 5211 // It wouldn't really be worth bothering for doubles except for one very 5212 // important value, which does happen to match: 0.0. So make sure we don't do 5213 // anything stupid. 5214 if (IsDouble && (iVal & 0xffffffff) != (iVal >> 32)) 5215 return SDValue(); 5216 5217 // Try a VMOV.i32 (FIXME: i8, i16, or i64 could work too). 5218 SDValue NewVal = isNEONModifiedImm(iVal & 0xffffffffU, 0, 32, DAG, SDLoc(Op), 5219 VMovVT, false, VMOVModImm); 5220 if (NewVal != SDValue()) { 5221 SDLoc DL(Op); 5222 SDValue VecConstant = DAG.getNode(ARMISD::VMOVIMM, DL, VMovVT, 5223 NewVal); 5224 if (IsDouble) 5225 return DAG.getNode(ISD::BITCAST, DL, MVT::f64, VecConstant); 5226 5227 // It's a float: cast and extract a vector element. 5228 SDValue VecFConstant = DAG.getNode(ISD::BITCAST, DL, MVT::v2f32, 5229 VecConstant); 5230 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32, VecFConstant, 5231 DAG.getConstant(0, DL, MVT::i32)); 5232 } 5233 5234 // Finally, try a VMVN.i32 5235 NewVal = isNEONModifiedImm(~iVal & 0xffffffffU, 0, 32, DAG, SDLoc(Op), VMovVT, 5236 false, VMVNModImm); 5237 if (NewVal != SDValue()) { 5238 SDLoc DL(Op); 5239 SDValue VecConstant = DAG.getNode(ARMISD::VMVNIMM, DL, VMovVT, NewVal); 5240 5241 if (IsDouble) 5242 return DAG.getNode(ISD::BITCAST, DL, MVT::f64, VecConstant); 5243 5244 // It's a float: cast and extract a vector element. 5245 SDValue VecFConstant = DAG.getNode(ISD::BITCAST, DL, MVT::v2f32, 5246 VecConstant); 5247 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32, VecFConstant, 5248 DAG.getConstant(0, DL, MVT::i32)); 5249 } 5250 5251 return SDValue(); 5252 } 5253 5254 // check if an VEXT instruction can handle the shuffle mask when the 5255 // vector sources of the shuffle are the same. 5256 static bool isSingletonVEXTMask(ArrayRef<int> M, EVT VT, unsigned &Imm) { 5257 unsigned NumElts = VT.getVectorNumElements(); 5258 5259 // Assume that the first shuffle index is not UNDEF. Fail if it is. 5260 if (M[0] < 0) 5261 return false; 5262 5263 Imm = M[0]; 5264 5265 // If this is a VEXT shuffle, the immediate value is the index of the first 5266 // element. The other shuffle indices must be the successive elements after 5267 // the first one. 5268 unsigned ExpectedElt = Imm; 5269 for (unsigned i = 1; i < NumElts; ++i) { 5270 // Increment the expected index. If it wraps around, just follow it 5271 // back to index zero and keep going. 5272 ++ExpectedElt; 5273 if (ExpectedElt == NumElts) 5274 ExpectedElt = 0; 5275 5276 if (M[i] < 0) continue; // ignore UNDEF indices 5277 if (ExpectedElt != static_cast<unsigned>(M[i])) 5278 return false; 5279 } 5280 5281 return true; 5282 } 5283 5284 5285 static bool isVEXTMask(ArrayRef<int> M, EVT VT, 5286 bool &ReverseVEXT, unsigned &Imm) { 5287 unsigned NumElts = VT.getVectorNumElements(); 5288 ReverseVEXT = false; 5289 5290 // Assume that the first shuffle index is not UNDEF. Fail if it is. 5291 if (M[0] < 0) 5292 return false; 5293 5294 Imm = M[0]; 5295 5296 // If this is a VEXT shuffle, the immediate value is the index of the first 5297 // element. The other shuffle indices must be the successive elements after 5298 // the first one. 5299 unsigned ExpectedElt = Imm; 5300 for (unsigned i = 1; i < NumElts; ++i) { 5301 // Increment the expected index. If it wraps around, it may still be 5302 // a VEXT but the source vectors must be swapped. 5303 ExpectedElt += 1; 5304 if (ExpectedElt == NumElts * 2) { 5305 ExpectedElt = 0; 5306 ReverseVEXT = true; 5307 } 5308 5309 if (M[i] < 0) continue; // ignore UNDEF indices 5310 if (ExpectedElt != static_cast<unsigned>(M[i])) 5311 return false; 5312 } 5313 5314 // Adjust the index value if the source operands will be swapped. 5315 if (ReverseVEXT) 5316 Imm -= NumElts; 5317 5318 return true; 5319 } 5320 5321 /// isVREVMask - Check if a vector shuffle corresponds to a VREV 5322 /// instruction with the specified blocksize. (The order of the elements 5323 /// within each block of the vector is reversed.) 5324 static bool isVREVMask(ArrayRef<int> M, EVT VT, unsigned BlockSize) { 5325 assert((BlockSize==16 || BlockSize==32 || BlockSize==64) && 5326 "Only possible block sizes for VREV are: 16, 32, 64"); 5327 5328 unsigned EltSz = VT.getVectorElementType().getSizeInBits(); 5329 if (EltSz == 64) 5330 return false; 5331 5332 unsigned NumElts = VT.getVectorNumElements(); 5333 unsigned BlockElts = M[0] + 1; 5334 // If the first shuffle index is UNDEF, be optimistic. 5335 if (M[0] < 0) 5336 BlockElts = BlockSize / EltSz; 5337 5338 if (BlockSize <= EltSz || BlockSize != BlockElts * EltSz) 5339 return false; 5340 5341 for (unsigned i = 0; i < NumElts; ++i) { 5342 if (M[i] < 0) continue; // ignore UNDEF indices 5343 if ((unsigned) M[i] != (i - i%BlockElts) + (BlockElts - 1 - i%BlockElts)) 5344 return false; 5345 } 5346 5347 return true; 5348 } 5349 5350 static bool isVTBLMask(ArrayRef<int> M, EVT VT) { 5351 // We can handle <8 x i8> vector shuffles. If the index in the mask is out of 5352 // range, then 0 is placed into the resulting vector. So pretty much any mask 5353 // of 8 elements can work here. 5354 return VT == MVT::v8i8 && M.size() == 8; 5355 } 5356 5357 // Checks whether the shuffle mask represents a vector transpose (VTRN) by 5358 // checking that pairs of elements in the shuffle mask represent the same index 5359 // in each vector, incrementing the expected index by 2 at each step. 5360 // e.g. For v1,v2 of type v4i32 a valid shuffle mask is: [0, 4, 2, 6] 5361 // v1={a,b,c,d} => x=shufflevector v1, v2 shufflemask => x={a,e,c,g} 5362 // v2={e,f,g,h} 5363 // WhichResult gives the offset for each element in the mask based on which 5364 // of the two results it belongs to. 5365 // 5366 // The transpose can be represented either as: 5367 // result1 = shufflevector v1, v2, result1_shuffle_mask 5368 // result2 = shufflevector v1, v2, result2_shuffle_mask 5369 // where v1/v2 and the shuffle masks have the same number of elements 5370 // (here WhichResult (see below) indicates which result is being checked) 5371 // 5372 // or as: 5373 // results = shufflevector v1, v2, shuffle_mask 5374 // where both results are returned in one vector and the shuffle mask has twice 5375 // as many elements as v1/v2 (here WhichResult will always be 0 if true) here we 5376 // want to check the low half and high half of the shuffle mask as if it were 5377 // the other case 5378 static bool isVTRNMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) { 5379 unsigned EltSz = VT.getVectorElementType().getSizeInBits(); 5380 if (EltSz == 64) 5381 return false; 5382 5383 unsigned NumElts = VT.getVectorNumElements(); 5384 if (M.size() != NumElts && M.size() != NumElts*2) 5385 return false; 5386 5387 // If the mask is twice as long as the input vector then we need to check the 5388 // upper and lower parts of the mask with a matching value for WhichResult 5389 // FIXME: A mask with only even values will be rejected in case the first 5390 // element is undefined, e.g. [-1, 4, 2, 6] will be rejected, because only 5391 // M[0] is used to determine WhichResult 5392 for (unsigned i = 0; i < M.size(); i += NumElts) { 5393 if (M.size() == NumElts * 2) 5394 WhichResult = i / NumElts; 5395 else 5396 WhichResult = M[i] == 0 ? 0 : 1; 5397 for (unsigned j = 0; j < NumElts; j += 2) { 5398 if ((M[i+j] >= 0 && (unsigned) M[i+j] != j + WhichResult) || 5399 (M[i+j+1] >= 0 && (unsigned) M[i+j+1] != j + NumElts + WhichResult)) 5400 return false; 5401 } 5402 } 5403 5404 if (M.size() == NumElts*2) 5405 WhichResult = 0; 5406 5407 return true; 5408 } 5409 5410 /// isVTRN_v_undef_Mask - Special case of isVTRNMask for canonical form of 5411 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef". 5412 /// Mask is e.g., <0, 0, 2, 2> instead of <0, 4, 2, 6>. 5413 static bool isVTRN_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult){ 5414 unsigned EltSz = VT.getVectorElementType().getSizeInBits(); 5415 if (EltSz == 64) 5416 return false; 5417 5418 unsigned NumElts = VT.getVectorNumElements(); 5419 if (M.size() != NumElts && M.size() != NumElts*2) 5420 return false; 5421 5422 for (unsigned i = 0; i < M.size(); i += NumElts) { 5423 if (M.size() == NumElts * 2) 5424 WhichResult = i / NumElts; 5425 else 5426 WhichResult = M[i] == 0 ? 0 : 1; 5427 for (unsigned j = 0; j < NumElts; j += 2) { 5428 if ((M[i+j] >= 0 && (unsigned) M[i+j] != j + WhichResult) || 5429 (M[i+j+1] >= 0 && (unsigned) M[i+j+1] != j + WhichResult)) 5430 return false; 5431 } 5432 } 5433 5434 if (M.size() == NumElts*2) 5435 WhichResult = 0; 5436 5437 return true; 5438 } 5439 5440 // Checks whether the shuffle mask represents a vector unzip (VUZP) by checking 5441 // that the mask elements are either all even and in steps of size 2 or all odd 5442 // and in steps of size 2. 5443 // e.g. For v1,v2 of type v4i32 a valid shuffle mask is: [0, 2, 4, 6] 5444 // v1={a,b,c,d} => x=shufflevector v1, v2 shufflemask => x={a,c,e,g} 5445 // v2={e,f,g,h} 5446 // Requires similar checks to that of isVTRNMask with 5447 // respect the how results are returned. 5448 static bool isVUZPMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) { 5449 unsigned EltSz = VT.getVectorElementType().getSizeInBits(); 5450 if (EltSz == 64) 5451 return false; 5452 5453 unsigned NumElts = VT.getVectorNumElements(); 5454 if (M.size() != NumElts && M.size() != NumElts*2) 5455 return false; 5456 5457 for (unsigned i = 0; i < M.size(); i += NumElts) { 5458 WhichResult = M[i] == 0 ? 0 : 1; 5459 for (unsigned j = 0; j < NumElts; ++j) { 5460 if (M[i+j] >= 0 && (unsigned) M[i+j] != 2 * j + WhichResult) 5461 return false; 5462 } 5463 } 5464 5465 if (M.size() == NumElts*2) 5466 WhichResult = 0; 5467 5468 // VUZP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32. 5469 if (VT.is64BitVector() && EltSz == 32) 5470 return false; 5471 5472 return true; 5473 } 5474 5475 /// isVUZP_v_undef_Mask - Special case of isVUZPMask for canonical form of 5476 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef". 5477 /// Mask is e.g., <0, 2, 0, 2> instead of <0, 2, 4, 6>, 5478 static bool isVUZP_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult){ 5479 unsigned EltSz = VT.getVectorElementType().getSizeInBits(); 5480 if (EltSz == 64) 5481 return false; 5482 5483 unsigned NumElts = VT.getVectorNumElements(); 5484 if (M.size() != NumElts && M.size() != NumElts*2) 5485 return false; 5486 5487 unsigned Half = NumElts / 2; 5488 for (unsigned i = 0; i < M.size(); i += NumElts) { 5489 WhichResult = M[i] == 0 ? 0 : 1; 5490 for (unsigned j = 0; j < NumElts; j += Half) { 5491 unsigned Idx = WhichResult; 5492 for (unsigned k = 0; k < Half; ++k) { 5493 int MIdx = M[i + j + k]; 5494 if (MIdx >= 0 && (unsigned) MIdx != Idx) 5495 return false; 5496 Idx += 2; 5497 } 5498 } 5499 } 5500 5501 if (M.size() == NumElts*2) 5502 WhichResult = 0; 5503 5504 // VUZP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32. 5505 if (VT.is64BitVector() && EltSz == 32) 5506 return false; 5507 5508 return true; 5509 } 5510 5511 // Checks whether the shuffle mask represents a vector zip (VZIP) by checking 5512 // that pairs of elements of the shufflemask represent the same index in each 5513 // vector incrementing sequentially through the vectors. 5514 // e.g. For v1,v2 of type v4i32 a valid shuffle mask is: [0, 4, 1, 5] 5515 // v1={a,b,c,d} => x=shufflevector v1, v2 shufflemask => x={a,e,b,f} 5516 // v2={e,f,g,h} 5517 // Requires similar checks to that of isVTRNMask with respect the how results 5518 // are returned. 5519 static bool isVZIPMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) { 5520 unsigned EltSz = VT.getVectorElementType().getSizeInBits(); 5521 if (EltSz == 64) 5522 return false; 5523 5524 unsigned NumElts = VT.getVectorNumElements(); 5525 if (M.size() != NumElts && M.size() != NumElts*2) 5526 return false; 5527 5528 for (unsigned i = 0; i < M.size(); i += NumElts) { 5529 WhichResult = M[i] == 0 ? 0 : 1; 5530 unsigned Idx = WhichResult * NumElts / 2; 5531 for (unsigned j = 0; j < NumElts; j += 2) { 5532 if ((M[i+j] >= 0 && (unsigned) M[i+j] != Idx) || 5533 (M[i+j+1] >= 0 && (unsigned) M[i+j+1] != Idx + NumElts)) 5534 return false; 5535 Idx += 1; 5536 } 5537 } 5538 5539 if (M.size() == NumElts*2) 5540 WhichResult = 0; 5541 5542 // VZIP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32. 5543 if (VT.is64BitVector() && EltSz == 32) 5544 return false; 5545 5546 return true; 5547 } 5548 5549 /// isVZIP_v_undef_Mask - Special case of isVZIPMask for canonical form of 5550 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef". 5551 /// Mask is e.g., <0, 0, 1, 1> instead of <0, 4, 1, 5>. 5552 static bool isVZIP_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult){ 5553 unsigned EltSz = VT.getVectorElementType().getSizeInBits(); 5554 if (EltSz == 64) 5555 return false; 5556 5557 unsigned NumElts = VT.getVectorNumElements(); 5558 if (M.size() != NumElts && M.size() != NumElts*2) 5559 return false; 5560 5561 for (unsigned i = 0; i < M.size(); i += NumElts) { 5562 WhichResult = M[i] == 0 ? 0 : 1; 5563 unsigned Idx = WhichResult * NumElts / 2; 5564 for (unsigned j = 0; j < NumElts; j += 2) { 5565 if ((M[i+j] >= 0 && (unsigned) M[i+j] != Idx) || 5566 (M[i+j+1] >= 0 && (unsigned) M[i+j+1] != Idx)) 5567 return false; 5568 Idx += 1; 5569 } 5570 } 5571 5572 if (M.size() == NumElts*2) 5573 WhichResult = 0; 5574 5575 // VZIP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32. 5576 if (VT.is64BitVector() && EltSz == 32) 5577 return false; 5578 5579 return true; 5580 } 5581 5582 /// Check if \p ShuffleMask is a NEON two-result shuffle (VZIP, VUZP, VTRN), 5583 /// and return the corresponding ARMISD opcode if it is, or 0 if it isn't. 5584 static unsigned isNEONTwoResultShuffleMask(ArrayRef<int> ShuffleMask, EVT VT, 5585 unsigned &WhichResult, 5586 bool &isV_UNDEF) { 5587 isV_UNDEF = false; 5588 if (isVTRNMask(ShuffleMask, VT, WhichResult)) 5589 return ARMISD::VTRN; 5590 if (isVUZPMask(ShuffleMask, VT, WhichResult)) 5591 return ARMISD::VUZP; 5592 if (isVZIPMask(ShuffleMask, VT, WhichResult)) 5593 return ARMISD::VZIP; 5594 5595 isV_UNDEF = true; 5596 if (isVTRN_v_undef_Mask(ShuffleMask, VT, WhichResult)) 5597 return ARMISD::VTRN; 5598 if (isVUZP_v_undef_Mask(ShuffleMask, VT, WhichResult)) 5599 return ARMISD::VUZP; 5600 if (isVZIP_v_undef_Mask(ShuffleMask, VT, WhichResult)) 5601 return ARMISD::VZIP; 5602 5603 return 0; 5604 } 5605 5606 /// \return true if this is a reverse operation on an vector. 5607 static bool isReverseMask(ArrayRef<int> M, EVT VT) { 5608 unsigned NumElts = VT.getVectorNumElements(); 5609 // Make sure the mask has the right size. 5610 if (NumElts != M.size()) 5611 return false; 5612 5613 // Look for <15, ..., 3, -1, 1, 0>. 5614 for (unsigned i = 0; i != NumElts; ++i) 5615 if (M[i] >= 0 && M[i] != (int) (NumElts - 1 - i)) 5616 return false; 5617 5618 return true; 5619 } 5620 5621 // If N is an integer constant that can be moved into a register in one 5622 // instruction, return an SDValue of such a constant (will become a MOV 5623 // instruction). Otherwise return null. 5624 static SDValue IsSingleInstrConstant(SDValue N, SelectionDAG &DAG, 5625 const ARMSubtarget *ST, const SDLoc &dl) { 5626 uint64_t Val; 5627 if (!isa<ConstantSDNode>(N)) 5628 return SDValue(); 5629 Val = cast<ConstantSDNode>(N)->getZExtValue(); 5630 5631 if (ST->isThumb1Only()) { 5632 if (Val <= 255 || ~Val <= 255) 5633 return DAG.getConstant(Val, dl, MVT::i32); 5634 } else { 5635 if (ARM_AM::getSOImmVal(Val) != -1 || ARM_AM::getSOImmVal(~Val) != -1) 5636 return DAG.getConstant(Val, dl, MVT::i32); 5637 } 5638 return SDValue(); 5639 } 5640 5641 // If this is a case we can't handle, return null and let the default 5642 // expansion code take care of it. 5643 SDValue ARMTargetLowering::LowerBUILD_VECTOR(SDValue Op, SelectionDAG &DAG, 5644 const ARMSubtarget *ST) const { 5645 BuildVectorSDNode *BVN = cast<BuildVectorSDNode>(Op.getNode()); 5646 SDLoc dl(Op); 5647 EVT VT = Op.getValueType(); 5648 5649 APInt SplatBits, SplatUndef; 5650 unsigned SplatBitSize; 5651 bool HasAnyUndefs; 5652 if (BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs)) { 5653 if (SplatBitSize <= 64) { 5654 // Check if an immediate VMOV works. 5655 EVT VmovVT; 5656 SDValue Val = isNEONModifiedImm(SplatBits.getZExtValue(), 5657 SplatUndef.getZExtValue(), SplatBitSize, 5658 DAG, dl, VmovVT, VT.is128BitVector(), 5659 VMOVModImm); 5660 if (Val.getNode()) { 5661 SDValue Vmov = DAG.getNode(ARMISD::VMOVIMM, dl, VmovVT, Val); 5662 return DAG.getNode(ISD::BITCAST, dl, VT, Vmov); 5663 } 5664 5665 // Try an immediate VMVN. 5666 uint64_t NegatedImm = (~SplatBits).getZExtValue(); 5667 Val = isNEONModifiedImm(NegatedImm, 5668 SplatUndef.getZExtValue(), SplatBitSize, 5669 DAG, dl, VmovVT, VT.is128BitVector(), 5670 VMVNModImm); 5671 if (Val.getNode()) { 5672 SDValue Vmov = DAG.getNode(ARMISD::VMVNIMM, dl, VmovVT, Val); 5673 return DAG.getNode(ISD::BITCAST, dl, VT, Vmov); 5674 } 5675 5676 // Use vmov.f32 to materialize other v2f32 and v4f32 splats. 5677 if ((VT == MVT::v2f32 || VT == MVT::v4f32) && SplatBitSize == 32) { 5678 int ImmVal = ARM_AM::getFP32Imm(SplatBits); 5679 if (ImmVal != -1) { 5680 SDValue Val = DAG.getTargetConstant(ImmVal, dl, MVT::i32); 5681 return DAG.getNode(ARMISD::VMOVFPIMM, dl, VT, Val); 5682 } 5683 } 5684 } 5685 } 5686 5687 // Scan through the operands to see if only one value is used. 5688 // 5689 // As an optimisation, even if more than one value is used it may be more 5690 // profitable to splat with one value then change some lanes. 5691 // 5692 // Heuristically we decide to do this if the vector has a "dominant" value, 5693 // defined as splatted to more than half of the lanes. 5694 unsigned NumElts = VT.getVectorNumElements(); 5695 bool isOnlyLowElement = true; 5696 bool usesOnlyOneValue = true; 5697 bool hasDominantValue = false; 5698 bool isConstant = true; 5699 5700 // Map of the number of times a particular SDValue appears in the 5701 // element list. 5702 DenseMap<SDValue, unsigned> ValueCounts; 5703 SDValue Value; 5704 for (unsigned i = 0; i < NumElts; ++i) { 5705 SDValue V = Op.getOperand(i); 5706 if (V.isUndef()) 5707 continue; 5708 if (i > 0) 5709 isOnlyLowElement = false; 5710 if (!isa<ConstantFPSDNode>(V) && !isa<ConstantSDNode>(V)) 5711 isConstant = false; 5712 5713 ValueCounts.insert(std::make_pair(V, 0)); 5714 unsigned &Count = ValueCounts[V]; 5715 5716 // Is this value dominant? (takes up more than half of the lanes) 5717 if (++Count > (NumElts / 2)) { 5718 hasDominantValue = true; 5719 Value = V; 5720 } 5721 } 5722 if (ValueCounts.size() != 1) 5723 usesOnlyOneValue = false; 5724 if (!Value.getNode() && ValueCounts.size() > 0) 5725 Value = ValueCounts.begin()->first; 5726 5727 if (ValueCounts.size() == 0) 5728 return DAG.getUNDEF(VT); 5729 5730 // Loads are better lowered with insert_vector_elt/ARMISD::BUILD_VECTOR. 5731 // Keep going if we are hitting this case. 5732 if (isOnlyLowElement && !ISD::isNormalLoad(Value.getNode())) 5733 return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Value); 5734 5735 unsigned EltSize = VT.getVectorElementType().getSizeInBits(); 5736 5737 // Use VDUP for non-constant splats. For f32 constant splats, reduce to 5738 // i32 and try again. 5739 if (hasDominantValue && EltSize <= 32) { 5740 if (!isConstant) { 5741 SDValue N; 5742 5743 // If we are VDUPing a value that comes directly from a vector, that will 5744 // cause an unnecessary move to and from a GPR, where instead we could 5745 // just use VDUPLANE. We can only do this if the lane being extracted 5746 // is at a constant index, as the VDUP from lane instructions only have 5747 // constant-index forms. 5748 ConstantSDNode *constIndex; 5749 if (Value->getOpcode() == ISD::EXTRACT_VECTOR_ELT && 5750 (constIndex = dyn_cast<ConstantSDNode>(Value->getOperand(1)))) { 5751 // We need to create a new undef vector to use for the VDUPLANE if the 5752 // size of the vector from which we get the value is different than the 5753 // size of the vector that we need to create. We will insert the element 5754 // such that the register coalescer will remove unnecessary copies. 5755 if (VT != Value->getOperand(0).getValueType()) { 5756 unsigned index = constIndex->getAPIntValue().getLimitedValue() % 5757 VT.getVectorNumElements(); 5758 N = DAG.getNode(ARMISD::VDUPLANE, dl, VT, 5759 DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, DAG.getUNDEF(VT), 5760 Value, DAG.getConstant(index, dl, MVT::i32)), 5761 DAG.getConstant(index, dl, MVT::i32)); 5762 } else 5763 N = DAG.getNode(ARMISD::VDUPLANE, dl, VT, 5764 Value->getOperand(0), Value->getOperand(1)); 5765 } else 5766 N = DAG.getNode(ARMISD::VDUP, dl, VT, Value); 5767 5768 if (!usesOnlyOneValue) { 5769 // The dominant value was splatted as 'N', but we now have to insert 5770 // all differing elements. 5771 for (unsigned I = 0; I < NumElts; ++I) { 5772 if (Op.getOperand(I) == Value) 5773 continue; 5774 SmallVector<SDValue, 3> Ops; 5775 Ops.push_back(N); 5776 Ops.push_back(Op.getOperand(I)); 5777 Ops.push_back(DAG.getConstant(I, dl, MVT::i32)); 5778 N = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Ops); 5779 } 5780 } 5781 return N; 5782 } 5783 if (VT.getVectorElementType().isFloatingPoint()) { 5784 SmallVector<SDValue, 8> Ops; 5785 for (unsigned i = 0; i < NumElts; ++i) 5786 Ops.push_back(DAG.getNode(ISD::BITCAST, dl, MVT::i32, 5787 Op.getOperand(i))); 5788 EVT VecVT = EVT::getVectorVT(*DAG.getContext(), MVT::i32, NumElts); 5789 SDValue Val = DAG.getBuildVector(VecVT, dl, Ops); 5790 Val = LowerBUILD_VECTOR(Val, DAG, ST); 5791 if (Val.getNode()) 5792 return DAG.getNode(ISD::BITCAST, dl, VT, Val); 5793 } 5794 if (usesOnlyOneValue) { 5795 SDValue Val = IsSingleInstrConstant(Value, DAG, ST, dl); 5796 if (isConstant && Val.getNode()) 5797 return DAG.getNode(ARMISD::VDUP, dl, VT, Val); 5798 } 5799 } 5800 5801 // If all elements are constants and the case above didn't get hit, fall back 5802 // to the default expansion, which will generate a load from the constant 5803 // pool. 5804 if (isConstant) 5805 return SDValue(); 5806 5807 // Empirical tests suggest this is rarely worth it for vectors of length <= 2. 5808 if (NumElts >= 4) { 5809 SDValue shuffle = ReconstructShuffle(Op, DAG); 5810 if (shuffle != SDValue()) 5811 return shuffle; 5812 } 5813 5814 // Vectors with 32- or 64-bit elements can be built by directly assigning 5815 // the subregisters. Lower it to an ARMISD::BUILD_VECTOR so the operands 5816 // will be legalized. 5817 if (EltSize >= 32) { 5818 // Do the expansion with floating-point types, since that is what the VFP 5819 // registers are defined to use, and since i64 is not legal. 5820 EVT EltVT = EVT::getFloatingPointVT(EltSize); 5821 EVT VecVT = EVT::getVectorVT(*DAG.getContext(), EltVT, NumElts); 5822 SmallVector<SDValue, 8> Ops; 5823 for (unsigned i = 0; i < NumElts; ++i) 5824 Ops.push_back(DAG.getNode(ISD::BITCAST, dl, EltVT, Op.getOperand(i))); 5825 SDValue Val = DAG.getNode(ARMISD::BUILD_VECTOR, dl, VecVT, Ops); 5826 return DAG.getNode(ISD::BITCAST, dl, VT, Val); 5827 } 5828 5829 // If all else fails, just use a sequence of INSERT_VECTOR_ELT when we 5830 // know the default expansion would otherwise fall back on something even 5831 // worse. For a vector with one or two non-undef values, that's 5832 // scalar_to_vector for the elements followed by a shuffle (provided the 5833 // shuffle is valid for the target) and materialization element by element 5834 // on the stack followed by a load for everything else. 5835 if (!isConstant && !usesOnlyOneValue) { 5836 SDValue Vec = DAG.getUNDEF(VT); 5837 for (unsigned i = 0 ; i < NumElts; ++i) { 5838 SDValue V = Op.getOperand(i); 5839 if (V.isUndef()) 5840 continue; 5841 SDValue LaneIdx = DAG.getConstant(i, dl, MVT::i32); 5842 Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Vec, V, LaneIdx); 5843 } 5844 return Vec; 5845 } 5846 5847 return SDValue(); 5848 } 5849 5850 // Gather data to see if the operation can be modelled as a 5851 // shuffle in combination with VEXTs. 5852 SDValue ARMTargetLowering::ReconstructShuffle(SDValue Op, 5853 SelectionDAG &DAG) const { 5854 assert(Op.getOpcode() == ISD::BUILD_VECTOR && "Unknown opcode!"); 5855 SDLoc dl(Op); 5856 EVT VT = Op.getValueType(); 5857 unsigned NumElts = VT.getVectorNumElements(); 5858 5859 struct ShuffleSourceInfo { 5860 SDValue Vec; 5861 unsigned MinElt; 5862 unsigned MaxElt; 5863 5864 // We may insert some combination of BITCASTs and VEXT nodes to force Vec to 5865 // be compatible with the shuffle we intend to construct. As a result 5866 // ShuffleVec will be some sliding window into the original Vec. 5867 SDValue ShuffleVec; 5868 5869 // Code should guarantee that element i in Vec starts at element "WindowBase 5870 // + i * WindowScale in ShuffleVec". 5871 int WindowBase; 5872 int WindowScale; 5873 5874 bool operator ==(SDValue OtherVec) { return Vec == OtherVec; } 5875 ShuffleSourceInfo(SDValue Vec) 5876 : Vec(Vec), MinElt(UINT_MAX), MaxElt(0), ShuffleVec(Vec), WindowBase(0), 5877 WindowScale(1) {} 5878 }; 5879 5880 // First gather all vectors used as an immediate source for this BUILD_VECTOR 5881 // node. 5882 SmallVector<ShuffleSourceInfo, 2> Sources; 5883 for (unsigned i = 0; i < NumElts; ++i) { 5884 SDValue V = Op.getOperand(i); 5885 if (V.isUndef()) 5886 continue; 5887 else if (V.getOpcode() != ISD::EXTRACT_VECTOR_ELT) { 5888 // A shuffle can only come from building a vector from various 5889 // elements of other vectors. 5890 return SDValue(); 5891 } else if (!isa<ConstantSDNode>(V.getOperand(1))) { 5892 // Furthermore, shuffles require a constant mask, whereas extractelts 5893 // accept variable indices. 5894 return SDValue(); 5895 } 5896 5897 // Add this element source to the list if it's not already there. 5898 SDValue SourceVec = V.getOperand(0); 5899 auto Source = std::find(Sources.begin(), Sources.end(), SourceVec); 5900 if (Source == Sources.end()) 5901 Source = Sources.insert(Sources.end(), ShuffleSourceInfo(SourceVec)); 5902 5903 // Update the minimum and maximum lane number seen. 5904 unsigned EltNo = cast<ConstantSDNode>(V.getOperand(1))->getZExtValue(); 5905 Source->MinElt = std::min(Source->MinElt, EltNo); 5906 Source->MaxElt = std::max(Source->MaxElt, EltNo); 5907 } 5908 5909 // Currently only do something sane when at most two source vectors 5910 // are involved. 5911 if (Sources.size() > 2) 5912 return SDValue(); 5913 5914 // Find out the smallest element size among result and two sources, and use 5915 // it as element size to build the shuffle_vector. 5916 EVT SmallestEltTy = VT.getVectorElementType(); 5917 for (auto &Source : Sources) { 5918 EVT SrcEltTy = Source.Vec.getValueType().getVectorElementType(); 5919 if (SrcEltTy.bitsLT(SmallestEltTy)) 5920 SmallestEltTy = SrcEltTy; 5921 } 5922 unsigned ResMultiplier = 5923 VT.getVectorElementType().getSizeInBits() / SmallestEltTy.getSizeInBits(); 5924 NumElts = VT.getSizeInBits() / SmallestEltTy.getSizeInBits(); 5925 EVT ShuffleVT = EVT::getVectorVT(*DAG.getContext(), SmallestEltTy, NumElts); 5926 5927 // If the source vector is too wide or too narrow, we may nevertheless be able 5928 // to construct a compatible shuffle either by concatenating it with UNDEF or 5929 // extracting a suitable range of elements. 5930 for (auto &Src : Sources) { 5931 EVT SrcVT = Src.ShuffleVec.getValueType(); 5932 5933 if (SrcVT.getSizeInBits() == VT.getSizeInBits()) 5934 continue; 5935 5936 // This stage of the search produces a source with the same element type as 5937 // the original, but with a total width matching the BUILD_VECTOR output. 5938 EVT EltVT = SrcVT.getVectorElementType(); 5939 unsigned NumSrcElts = VT.getSizeInBits() / EltVT.getSizeInBits(); 5940 EVT DestVT = EVT::getVectorVT(*DAG.getContext(), EltVT, NumSrcElts); 5941 5942 if (SrcVT.getSizeInBits() < VT.getSizeInBits()) { 5943 if (2 * SrcVT.getSizeInBits() != VT.getSizeInBits()) 5944 return SDValue(); 5945 // We can pad out the smaller vector for free, so if it's part of a 5946 // shuffle... 5947 Src.ShuffleVec = 5948 DAG.getNode(ISD::CONCAT_VECTORS, dl, DestVT, Src.ShuffleVec, 5949 DAG.getUNDEF(Src.ShuffleVec.getValueType())); 5950 continue; 5951 } 5952 5953 if (SrcVT.getSizeInBits() != 2 * VT.getSizeInBits()) 5954 return SDValue(); 5955 5956 if (Src.MaxElt - Src.MinElt >= NumSrcElts) { 5957 // Span too large for a VEXT to cope 5958 return SDValue(); 5959 } 5960 5961 if (Src.MinElt >= NumSrcElts) { 5962 // The extraction can just take the second half 5963 Src.ShuffleVec = 5964 DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DestVT, Src.ShuffleVec, 5965 DAG.getConstant(NumSrcElts, dl, MVT::i32)); 5966 Src.WindowBase = -NumSrcElts; 5967 } else if (Src.MaxElt < NumSrcElts) { 5968 // The extraction can just take the first half 5969 Src.ShuffleVec = 5970 DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DestVT, Src.ShuffleVec, 5971 DAG.getConstant(0, dl, MVT::i32)); 5972 } else { 5973 // An actual VEXT is needed 5974 SDValue VEXTSrc1 = 5975 DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DestVT, Src.ShuffleVec, 5976 DAG.getConstant(0, dl, MVT::i32)); 5977 SDValue VEXTSrc2 = 5978 DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DestVT, Src.ShuffleVec, 5979 DAG.getConstant(NumSrcElts, dl, MVT::i32)); 5980 5981 Src.ShuffleVec = DAG.getNode(ARMISD::VEXT, dl, DestVT, VEXTSrc1, 5982 VEXTSrc2, 5983 DAG.getConstant(Src.MinElt, dl, MVT::i32)); 5984 Src.WindowBase = -Src.MinElt; 5985 } 5986 } 5987 5988 // Another possible incompatibility occurs from the vector element types. We 5989 // can fix this by bitcasting the source vectors to the same type we intend 5990 // for the shuffle. 5991 for (auto &Src : Sources) { 5992 EVT SrcEltTy = Src.ShuffleVec.getValueType().getVectorElementType(); 5993 if (SrcEltTy == SmallestEltTy) 5994 continue; 5995 assert(ShuffleVT.getVectorElementType() == SmallestEltTy); 5996 Src.ShuffleVec = DAG.getNode(ISD::BITCAST, dl, ShuffleVT, Src.ShuffleVec); 5997 Src.WindowScale = SrcEltTy.getSizeInBits() / SmallestEltTy.getSizeInBits(); 5998 Src.WindowBase *= Src.WindowScale; 5999 } 6000 6001 // Final sanity check before we try to actually produce a shuffle. 6002 DEBUG( 6003 for (auto Src : Sources) 6004 assert(Src.ShuffleVec.getValueType() == ShuffleVT); 6005 ); 6006 6007 // The stars all align, our next step is to produce the mask for the shuffle. 6008 SmallVector<int, 8> Mask(ShuffleVT.getVectorNumElements(), -1); 6009 int BitsPerShuffleLane = ShuffleVT.getVectorElementType().getSizeInBits(); 6010 for (unsigned i = 0; i < VT.getVectorNumElements(); ++i) { 6011 SDValue Entry = Op.getOperand(i); 6012 if (Entry.isUndef()) 6013 continue; 6014 6015 auto Src = std::find(Sources.begin(), Sources.end(), Entry.getOperand(0)); 6016 int EltNo = cast<ConstantSDNode>(Entry.getOperand(1))->getSExtValue(); 6017 6018 // EXTRACT_VECTOR_ELT performs an implicit any_ext; BUILD_VECTOR an implicit 6019 // trunc. So only std::min(SrcBits, DestBits) actually get defined in this 6020 // segment. 6021 EVT OrigEltTy = Entry.getOperand(0).getValueType().getVectorElementType(); 6022 int BitsDefined = std::min(OrigEltTy.getSizeInBits(), 6023 VT.getVectorElementType().getSizeInBits()); 6024 int LanesDefined = BitsDefined / BitsPerShuffleLane; 6025 6026 // This source is expected to fill ResMultiplier lanes of the final shuffle, 6027 // starting at the appropriate offset. 6028 int *LaneMask = &Mask[i * ResMultiplier]; 6029 6030 int ExtractBase = EltNo * Src->WindowScale + Src->WindowBase; 6031 ExtractBase += NumElts * (Src - Sources.begin()); 6032 for (int j = 0; j < LanesDefined; ++j) 6033 LaneMask[j] = ExtractBase + j; 6034 } 6035 6036 // Final check before we try to produce nonsense... 6037 if (!isShuffleMaskLegal(Mask, ShuffleVT)) 6038 return SDValue(); 6039 6040 // We can't handle more than two sources. This should have already 6041 // been checked before this point. 6042 assert(Sources.size() <= 2 && "Too many sources!"); 6043 6044 SDValue ShuffleOps[] = { DAG.getUNDEF(ShuffleVT), DAG.getUNDEF(ShuffleVT) }; 6045 for (unsigned i = 0; i < Sources.size(); ++i) 6046 ShuffleOps[i] = Sources[i].ShuffleVec; 6047 6048 SDValue Shuffle = DAG.getVectorShuffle(ShuffleVT, dl, ShuffleOps[0], 6049 ShuffleOps[1], &Mask[0]); 6050 return DAG.getNode(ISD::BITCAST, dl, VT, Shuffle); 6051 } 6052 6053 /// isShuffleMaskLegal - Targets can use this to indicate that they only 6054 /// support *some* VECTOR_SHUFFLE operations, those with specific masks. 6055 /// By default, if a target supports the VECTOR_SHUFFLE node, all mask values 6056 /// are assumed to be legal. 6057 bool 6058 ARMTargetLowering::isShuffleMaskLegal(const SmallVectorImpl<int> &M, 6059 EVT VT) const { 6060 if (VT.getVectorNumElements() == 4 && 6061 (VT.is128BitVector() || VT.is64BitVector())) { 6062 unsigned PFIndexes[4]; 6063 for (unsigned i = 0; i != 4; ++i) { 6064 if (M[i] < 0) 6065 PFIndexes[i] = 8; 6066 else 6067 PFIndexes[i] = M[i]; 6068 } 6069 6070 // Compute the index in the perfect shuffle table. 6071 unsigned PFTableIndex = 6072 PFIndexes[0]*9*9*9+PFIndexes[1]*9*9+PFIndexes[2]*9+PFIndexes[3]; 6073 unsigned PFEntry = PerfectShuffleTable[PFTableIndex]; 6074 unsigned Cost = (PFEntry >> 30); 6075 6076 if (Cost <= 4) 6077 return true; 6078 } 6079 6080 bool ReverseVEXT, isV_UNDEF; 6081 unsigned Imm, WhichResult; 6082 6083 unsigned EltSize = VT.getVectorElementType().getSizeInBits(); 6084 return (EltSize >= 32 || 6085 ShuffleVectorSDNode::isSplatMask(&M[0], VT) || 6086 isVREVMask(M, VT, 64) || 6087 isVREVMask(M, VT, 32) || 6088 isVREVMask(M, VT, 16) || 6089 isVEXTMask(M, VT, ReverseVEXT, Imm) || 6090 isVTBLMask(M, VT) || 6091 isNEONTwoResultShuffleMask(M, VT, WhichResult, isV_UNDEF) || 6092 ((VT == MVT::v8i16 || VT == MVT::v16i8) && isReverseMask(M, VT))); 6093 } 6094 6095 /// GeneratePerfectShuffle - Given an entry in the perfect-shuffle table, emit 6096 /// the specified operations to build the shuffle. 6097 static SDValue GeneratePerfectShuffle(unsigned PFEntry, SDValue LHS, 6098 SDValue RHS, SelectionDAG &DAG, 6099 const SDLoc &dl) { 6100 unsigned OpNum = (PFEntry >> 26) & 0x0F; 6101 unsigned LHSID = (PFEntry >> 13) & ((1 << 13)-1); 6102 unsigned RHSID = (PFEntry >> 0) & ((1 << 13)-1); 6103 6104 enum { 6105 OP_COPY = 0, // Copy, used for things like <u,u,u,3> to say it is <0,1,2,3> 6106 OP_VREV, 6107 OP_VDUP0, 6108 OP_VDUP1, 6109 OP_VDUP2, 6110 OP_VDUP3, 6111 OP_VEXT1, 6112 OP_VEXT2, 6113 OP_VEXT3, 6114 OP_VUZPL, // VUZP, left result 6115 OP_VUZPR, // VUZP, right result 6116 OP_VZIPL, // VZIP, left result 6117 OP_VZIPR, // VZIP, right result 6118 OP_VTRNL, // VTRN, left result 6119 OP_VTRNR // VTRN, right result 6120 }; 6121 6122 if (OpNum == OP_COPY) { 6123 if (LHSID == (1*9+2)*9+3) return LHS; 6124 assert(LHSID == ((4*9+5)*9+6)*9+7 && "Illegal OP_COPY!"); 6125 return RHS; 6126 } 6127 6128 SDValue OpLHS, OpRHS; 6129 OpLHS = GeneratePerfectShuffle(PerfectShuffleTable[LHSID], LHS, RHS, DAG, dl); 6130 OpRHS = GeneratePerfectShuffle(PerfectShuffleTable[RHSID], LHS, RHS, DAG, dl); 6131 EVT VT = OpLHS.getValueType(); 6132 6133 switch (OpNum) { 6134 default: llvm_unreachable("Unknown shuffle opcode!"); 6135 case OP_VREV: 6136 // VREV divides the vector in half and swaps within the half. 6137 if (VT.getVectorElementType() == MVT::i32 || 6138 VT.getVectorElementType() == MVT::f32) 6139 return DAG.getNode(ARMISD::VREV64, dl, VT, OpLHS); 6140 // vrev <4 x i16> -> VREV32 6141 if (VT.getVectorElementType() == MVT::i16) 6142 return DAG.getNode(ARMISD::VREV32, dl, VT, OpLHS); 6143 // vrev <4 x i8> -> VREV16 6144 assert(VT.getVectorElementType() == MVT::i8); 6145 return DAG.getNode(ARMISD::VREV16, dl, VT, OpLHS); 6146 case OP_VDUP0: 6147 case OP_VDUP1: 6148 case OP_VDUP2: 6149 case OP_VDUP3: 6150 return DAG.getNode(ARMISD::VDUPLANE, dl, VT, 6151 OpLHS, DAG.getConstant(OpNum-OP_VDUP0, dl, MVT::i32)); 6152 case OP_VEXT1: 6153 case OP_VEXT2: 6154 case OP_VEXT3: 6155 return DAG.getNode(ARMISD::VEXT, dl, VT, 6156 OpLHS, OpRHS, 6157 DAG.getConstant(OpNum - OP_VEXT1 + 1, dl, MVT::i32)); 6158 case OP_VUZPL: 6159 case OP_VUZPR: 6160 return DAG.getNode(ARMISD::VUZP, dl, DAG.getVTList(VT, VT), 6161 OpLHS, OpRHS).getValue(OpNum-OP_VUZPL); 6162 case OP_VZIPL: 6163 case OP_VZIPR: 6164 return DAG.getNode(ARMISD::VZIP, dl, DAG.getVTList(VT, VT), 6165 OpLHS, OpRHS).getValue(OpNum-OP_VZIPL); 6166 case OP_VTRNL: 6167 case OP_VTRNR: 6168 return DAG.getNode(ARMISD::VTRN, dl, DAG.getVTList(VT, VT), 6169 OpLHS, OpRHS).getValue(OpNum-OP_VTRNL); 6170 } 6171 } 6172 6173 static SDValue LowerVECTOR_SHUFFLEv8i8(SDValue Op, 6174 ArrayRef<int> ShuffleMask, 6175 SelectionDAG &DAG) { 6176 // Check to see if we can use the VTBL instruction. 6177 SDValue V1 = Op.getOperand(0); 6178 SDValue V2 = Op.getOperand(1); 6179 SDLoc DL(Op); 6180 6181 SmallVector<SDValue, 8> VTBLMask; 6182 for (ArrayRef<int>::iterator 6183 I = ShuffleMask.begin(), E = ShuffleMask.end(); I != E; ++I) 6184 VTBLMask.push_back(DAG.getConstant(*I, DL, MVT::i32)); 6185 6186 if (V2.getNode()->isUndef()) 6187 return DAG.getNode(ARMISD::VTBL1, DL, MVT::v8i8, V1, 6188 DAG.getBuildVector(MVT::v8i8, DL, VTBLMask)); 6189 6190 return DAG.getNode(ARMISD::VTBL2, DL, MVT::v8i8, V1, V2, 6191 DAG.getBuildVector(MVT::v8i8, DL, VTBLMask)); 6192 } 6193 6194 static SDValue LowerReverse_VECTOR_SHUFFLEv16i8_v8i16(SDValue Op, 6195 SelectionDAG &DAG) { 6196 SDLoc DL(Op); 6197 SDValue OpLHS = Op.getOperand(0); 6198 EVT VT = OpLHS.getValueType(); 6199 6200 assert((VT == MVT::v8i16 || VT == MVT::v16i8) && 6201 "Expect an v8i16/v16i8 type"); 6202 OpLHS = DAG.getNode(ARMISD::VREV64, DL, VT, OpLHS); 6203 // For a v16i8 type: After the VREV, we have got <8, ...15, 8, ..., 0>. Now, 6204 // extract the first 8 bytes into the top double word and the last 8 bytes 6205 // into the bottom double word. The v8i16 case is similar. 6206 unsigned ExtractNum = (VT == MVT::v16i8) ? 8 : 4; 6207 return DAG.getNode(ARMISD::VEXT, DL, VT, OpLHS, OpLHS, 6208 DAG.getConstant(ExtractNum, DL, MVT::i32)); 6209 } 6210 6211 static SDValue LowerVECTOR_SHUFFLE(SDValue Op, SelectionDAG &DAG) { 6212 SDValue V1 = Op.getOperand(0); 6213 SDValue V2 = Op.getOperand(1); 6214 SDLoc dl(Op); 6215 EVT VT = Op.getValueType(); 6216 ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(Op.getNode()); 6217 6218 // Convert shuffles that are directly supported on NEON to target-specific 6219 // DAG nodes, instead of keeping them as shuffles and matching them again 6220 // during code selection. This is more efficient and avoids the possibility 6221 // of inconsistencies between legalization and selection. 6222 // FIXME: floating-point vectors should be canonicalized to integer vectors 6223 // of the same time so that they get CSEd properly. 6224 ArrayRef<int> ShuffleMask = SVN->getMask(); 6225 6226 unsigned EltSize = VT.getVectorElementType().getSizeInBits(); 6227 if (EltSize <= 32) { 6228 if (SVN->isSplat()) { 6229 int Lane = SVN->getSplatIndex(); 6230 // If this is undef splat, generate it via "just" vdup, if possible. 6231 if (Lane == -1) Lane = 0; 6232 6233 // Test if V1 is a SCALAR_TO_VECTOR. 6234 if (Lane == 0 && V1.getOpcode() == ISD::SCALAR_TO_VECTOR) { 6235 return DAG.getNode(ARMISD::VDUP, dl, VT, V1.getOperand(0)); 6236 } 6237 // Test if V1 is a BUILD_VECTOR which is equivalent to a SCALAR_TO_VECTOR 6238 // (and probably will turn into a SCALAR_TO_VECTOR once legalization 6239 // reaches it). 6240 if (Lane == 0 && V1.getOpcode() == ISD::BUILD_VECTOR && 6241 !isa<ConstantSDNode>(V1.getOperand(0))) { 6242 bool IsScalarToVector = true; 6243 for (unsigned i = 1, e = V1.getNumOperands(); i != e; ++i) 6244 if (!V1.getOperand(i).isUndef()) { 6245 IsScalarToVector = false; 6246 break; 6247 } 6248 if (IsScalarToVector) 6249 return DAG.getNode(ARMISD::VDUP, dl, VT, V1.getOperand(0)); 6250 } 6251 return DAG.getNode(ARMISD::VDUPLANE, dl, VT, V1, 6252 DAG.getConstant(Lane, dl, MVT::i32)); 6253 } 6254 6255 bool ReverseVEXT; 6256 unsigned Imm; 6257 if (isVEXTMask(ShuffleMask, VT, ReverseVEXT, Imm)) { 6258 if (ReverseVEXT) 6259 std::swap(V1, V2); 6260 return DAG.getNode(ARMISD::VEXT, dl, VT, V1, V2, 6261 DAG.getConstant(Imm, dl, MVT::i32)); 6262 } 6263 6264 if (isVREVMask(ShuffleMask, VT, 64)) 6265 return DAG.getNode(ARMISD::VREV64, dl, VT, V1); 6266 if (isVREVMask(ShuffleMask, VT, 32)) 6267 return DAG.getNode(ARMISD::VREV32, dl, VT, V1); 6268 if (isVREVMask(ShuffleMask, VT, 16)) 6269 return DAG.getNode(ARMISD::VREV16, dl, VT, V1); 6270 6271 if (V2->isUndef() && isSingletonVEXTMask(ShuffleMask, VT, Imm)) { 6272 return DAG.getNode(ARMISD::VEXT, dl, VT, V1, V1, 6273 DAG.getConstant(Imm, dl, MVT::i32)); 6274 } 6275 6276 // Check for Neon shuffles that modify both input vectors in place. 6277 // If both results are used, i.e., if there are two shuffles with the same 6278 // source operands and with masks corresponding to both results of one of 6279 // these operations, DAG memoization will ensure that a single node is 6280 // used for both shuffles. 6281 unsigned WhichResult; 6282 bool isV_UNDEF; 6283 if (unsigned ShuffleOpc = isNEONTwoResultShuffleMask( 6284 ShuffleMask, VT, WhichResult, isV_UNDEF)) { 6285 if (isV_UNDEF) 6286 V2 = V1; 6287 return DAG.getNode(ShuffleOpc, dl, DAG.getVTList(VT, VT), V1, V2) 6288 .getValue(WhichResult); 6289 } 6290 6291 // Also check for these shuffles through CONCAT_VECTORS: we canonicalize 6292 // shuffles that produce a result larger than their operands with: 6293 // shuffle(concat(v1, undef), concat(v2, undef)) 6294 // -> 6295 // shuffle(concat(v1, v2), undef) 6296 // because we can access quad vectors (see PerformVECTOR_SHUFFLECombine). 6297 // 6298 // This is useful in the general case, but there are special cases where 6299 // native shuffles produce larger results: the two-result ops. 6300 // 6301 // Look through the concat when lowering them: 6302 // shuffle(concat(v1, v2), undef) 6303 // -> 6304 // concat(VZIP(v1, v2):0, :1) 6305 // 6306 if (V1->getOpcode() == ISD::CONCAT_VECTORS && V2->isUndef()) { 6307 SDValue SubV1 = V1->getOperand(0); 6308 SDValue SubV2 = V1->getOperand(1); 6309 EVT SubVT = SubV1.getValueType(); 6310 6311 // We expect these to have been canonicalized to -1. 6312 assert(std::all_of(ShuffleMask.begin(), ShuffleMask.end(), [&](int i) { 6313 return i < (int)VT.getVectorNumElements(); 6314 }) && "Unexpected shuffle index into UNDEF operand!"); 6315 6316 if (unsigned ShuffleOpc = isNEONTwoResultShuffleMask( 6317 ShuffleMask, SubVT, WhichResult, isV_UNDEF)) { 6318 if (isV_UNDEF) 6319 SubV2 = SubV1; 6320 assert((WhichResult == 0) && 6321 "In-place shuffle of concat can only have one result!"); 6322 SDValue Res = DAG.getNode(ShuffleOpc, dl, DAG.getVTList(SubVT, SubVT), 6323 SubV1, SubV2); 6324 return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, Res.getValue(0), 6325 Res.getValue(1)); 6326 } 6327 } 6328 } 6329 6330 // If the shuffle is not directly supported and it has 4 elements, use 6331 // the PerfectShuffle-generated table to synthesize it from other shuffles. 6332 unsigned NumElts = VT.getVectorNumElements(); 6333 if (NumElts == 4) { 6334 unsigned PFIndexes[4]; 6335 for (unsigned i = 0; i != 4; ++i) { 6336 if (ShuffleMask[i] < 0) 6337 PFIndexes[i] = 8; 6338 else 6339 PFIndexes[i] = ShuffleMask[i]; 6340 } 6341 6342 // Compute the index in the perfect shuffle table. 6343 unsigned PFTableIndex = 6344 PFIndexes[0]*9*9*9+PFIndexes[1]*9*9+PFIndexes[2]*9+PFIndexes[3]; 6345 unsigned PFEntry = PerfectShuffleTable[PFTableIndex]; 6346 unsigned Cost = (PFEntry >> 30); 6347 6348 if (Cost <= 4) 6349 return GeneratePerfectShuffle(PFEntry, V1, V2, DAG, dl); 6350 } 6351 6352 // Implement shuffles with 32- or 64-bit elements as ARMISD::BUILD_VECTORs. 6353 if (EltSize >= 32) { 6354 // Do the expansion with floating-point types, since that is what the VFP 6355 // registers are defined to use, and since i64 is not legal. 6356 EVT EltVT = EVT::getFloatingPointVT(EltSize); 6357 EVT VecVT = EVT::getVectorVT(*DAG.getContext(), EltVT, NumElts); 6358 V1 = DAG.getNode(ISD::BITCAST, dl, VecVT, V1); 6359 V2 = DAG.getNode(ISD::BITCAST, dl, VecVT, V2); 6360 SmallVector<SDValue, 8> Ops; 6361 for (unsigned i = 0; i < NumElts; ++i) { 6362 if (ShuffleMask[i] < 0) 6363 Ops.push_back(DAG.getUNDEF(EltVT)); 6364 else 6365 Ops.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, EltVT, 6366 ShuffleMask[i] < (int)NumElts ? V1 : V2, 6367 DAG.getConstant(ShuffleMask[i] & (NumElts-1), 6368 dl, MVT::i32))); 6369 } 6370 SDValue Val = DAG.getNode(ARMISD::BUILD_VECTOR, dl, VecVT, Ops); 6371 return DAG.getNode(ISD::BITCAST, dl, VT, Val); 6372 } 6373 6374 if ((VT == MVT::v8i16 || VT == MVT::v16i8) && isReverseMask(ShuffleMask, VT)) 6375 return LowerReverse_VECTOR_SHUFFLEv16i8_v8i16(Op, DAG); 6376 6377 if (VT == MVT::v8i8) 6378 if (SDValue NewOp = LowerVECTOR_SHUFFLEv8i8(Op, ShuffleMask, DAG)) 6379 return NewOp; 6380 6381 return SDValue(); 6382 } 6383 6384 static SDValue LowerINSERT_VECTOR_ELT(SDValue Op, SelectionDAG &DAG) { 6385 // INSERT_VECTOR_ELT is legal only for immediate indexes. 6386 SDValue Lane = Op.getOperand(2); 6387 if (!isa<ConstantSDNode>(Lane)) 6388 return SDValue(); 6389 6390 return Op; 6391 } 6392 6393 static SDValue LowerEXTRACT_VECTOR_ELT(SDValue Op, SelectionDAG &DAG) { 6394 // EXTRACT_VECTOR_ELT is legal only for immediate indexes. 6395 SDValue Lane = Op.getOperand(1); 6396 if (!isa<ConstantSDNode>(Lane)) 6397 return SDValue(); 6398 6399 SDValue Vec = Op.getOperand(0); 6400 if (Op.getValueType() == MVT::i32 && 6401 Vec.getValueType().getVectorElementType().getSizeInBits() < 32) { 6402 SDLoc dl(Op); 6403 return DAG.getNode(ARMISD::VGETLANEu, dl, MVT::i32, Vec, Lane); 6404 } 6405 6406 return Op; 6407 } 6408 6409 static SDValue LowerCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG) { 6410 // The only time a CONCAT_VECTORS operation can have legal types is when 6411 // two 64-bit vectors are concatenated to a 128-bit vector. 6412 assert(Op.getValueType().is128BitVector() && Op.getNumOperands() == 2 && 6413 "unexpected CONCAT_VECTORS"); 6414 SDLoc dl(Op); 6415 SDValue Val = DAG.getUNDEF(MVT::v2f64); 6416 SDValue Op0 = Op.getOperand(0); 6417 SDValue Op1 = Op.getOperand(1); 6418 if (!Op0.isUndef()) 6419 Val = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Val, 6420 DAG.getNode(ISD::BITCAST, dl, MVT::f64, Op0), 6421 DAG.getIntPtrConstant(0, dl)); 6422 if (!Op1.isUndef()) 6423 Val = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Val, 6424 DAG.getNode(ISD::BITCAST, dl, MVT::f64, Op1), 6425 DAG.getIntPtrConstant(1, dl)); 6426 return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Val); 6427 } 6428 6429 /// isExtendedBUILD_VECTOR - Check if N is a constant BUILD_VECTOR where each 6430 /// element has been zero/sign-extended, depending on the isSigned parameter, 6431 /// from an integer type half its size. 6432 static bool isExtendedBUILD_VECTOR(SDNode *N, SelectionDAG &DAG, 6433 bool isSigned) { 6434 // A v2i64 BUILD_VECTOR will have been legalized to a BITCAST from v4i32. 6435 EVT VT = N->getValueType(0); 6436 if (VT == MVT::v2i64 && N->getOpcode() == ISD::BITCAST) { 6437 SDNode *BVN = N->getOperand(0).getNode(); 6438 if (BVN->getValueType(0) != MVT::v4i32 || 6439 BVN->getOpcode() != ISD::BUILD_VECTOR) 6440 return false; 6441 unsigned LoElt = DAG.getDataLayout().isBigEndian() ? 1 : 0; 6442 unsigned HiElt = 1 - LoElt; 6443 ConstantSDNode *Lo0 = dyn_cast<ConstantSDNode>(BVN->getOperand(LoElt)); 6444 ConstantSDNode *Hi0 = dyn_cast<ConstantSDNode>(BVN->getOperand(HiElt)); 6445 ConstantSDNode *Lo1 = dyn_cast<ConstantSDNode>(BVN->getOperand(LoElt+2)); 6446 ConstantSDNode *Hi1 = dyn_cast<ConstantSDNode>(BVN->getOperand(HiElt+2)); 6447 if (!Lo0 || !Hi0 || !Lo1 || !Hi1) 6448 return false; 6449 if (isSigned) { 6450 if (Hi0->getSExtValue() == Lo0->getSExtValue() >> 32 && 6451 Hi1->getSExtValue() == Lo1->getSExtValue() >> 32) 6452 return true; 6453 } else { 6454 if (Hi0->isNullValue() && Hi1->isNullValue()) 6455 return true; 6456 } 6457 return false; 6458 } 6459 6460 if (N->getOpcode() != ISD::BUILD_VECTOR) 6461 return false; 6462 6463 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) { 6464 SDNode *Elt = N->getOperand(i).getNode(); 6465 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Elt)) { 6466 unsigned EltSize = VT.getVectorElementType().getSizeInBits(); 6467 unsigned HalfSize = EltSize / 2; 6468 if (isSigned) { 6469 if (!isIntN(HalfSize, C->getSExtValue())) 6470 return false; 6471 } else { 6472 if (!isUIntN(HalfSize, C->getZExtValue())) 6473 return false; 6474 } 6475 continue; 6476 } 6477 return false; 6478 } 6479 6480 return true; 6481 } 6482 6483 /// isSignExtended - Check if a node is a vector value that is sign-extended 6484 /// or a constant BUILD_VECTOR with sign-extended elements. 6485 static bool isSignExtended(SDNode *N, SelectionDAG &DAG) { 6486 if (N->getOpcode() == ISD::SIGN_EXTEND || ISD::isSEXTLoad(N)) 6487 return true; 6488 if (isExtendedBUILD_VECTOR(N, DAG, true)) 6489 return true; 6490 return false; 6491 } 6492 6493 /// isZeroExtended - Check if a node is a vector value that is zero-extended 6494 /// or a constant BUILD_VECTOR with zero-extended elements. 6495 static bool isZeroExtended(SDNode *N, SelectionDAG &DAG) { 6496 if (N->getOpcode() == ISD::ZERO_EXTEND || ISD::isZEXTLoad(N)) 6497 return true; 6498 if (isExtendedBUILD_VECTOR(N, DAG, false)) 6499 return true; 6500 return false; 6501 } 6502 6503 static EVT getExtensionTo64Bits(const EVT &OrigVT) { 6504 if (OrigVT.getSizeInBits() >= 64) 6505 return OrigVT; 6506 6507 assert(OrigVT.isSimple() && "Expecting a simple value type"); 6508 6509 MVT::SimpleValueType OrigSimpleTy = OrigVT.getSimpleVT().SimpleTy; 6510 switch (OrigSimpleTy) { 6511 default: llvm_unreachable("Unexpected Vector Type"); 6512 case MVT::v2i8: 6513 case MVT::v2i16: 6514 return MVT::v2i32; 6515 case MVT::v4i8: 6516 return MVT::v4i16; 6517 } 6518 } 6519 6520 /// AddRequiredExtensionForVMULL - Add a sign/zero extension to extend the total 6521 /// value size to 64 bits. We need a 64-bit D register as an operand to VMULL. 6522 /// We insert the required extension here to get the vector to fill a D register. 6523 static SDValue AddRequiredExtensionForVMULL(SDValue N, SelectionDAG &DAG, 6524 const EVT &OrigTy, 6525 const EVT &ExtTy, 6526 unsigned ExtOpcode) { 6527 // The vector originally had a size of OrigTy. It was then extended to ExtTy. 6528 // We expect the ExtTy to be 128-bits total. If the OrigTy is less than 6529 // 64-bits we need to insert a new extension so that it will be 64-bits. 6530 assert(ExtTy.is128BitVector() && "Unexpected extension size"); 6531 if (OrigTy.getSizeInBits() >= 64) 6532 return N; 6533 6534 // Must extend size to at least 64 bits to be used as an operand for VMULL. 6535 EVT NewVT = getExtensionTo64Bits(OrigTy); 6536 6537 return DAG.getNode(ExtOpcode, SDLoc(N), NewVT, N); 6538 } 6539 6540 /// SkipLoadExtensionForVMULL - return a load of the original vector size that 6541 /// does not do any sign/zero extension. If the original vector is less 6542 /// than 64 bits, an appropriate extension will be added after the load to 6543 /// reach a total size of 64 bits. We have to add the extension separately 6544 /// because ARM does not have a sign/zero extending load for vectors. 6545 static SDValue SkipLoadExtensionForVMULL(LoadSDNode *LD, SelectionDAG& DAG) { 6546 EVT ExtendedTy = getExtensionTo64Bits(LD->getMemoryVT()); 6547 6548 // The load already has the right type. 6549 if (ExtendedTy == LD->getMemoryVT()) 6550 return DAG.getLoad(LD->getMemoryVT(), SDLoc(LD), LD->getChain(), 6551 LD->getBasePtr(), LD->getPointerInfo(), LD->isVolatile(), 6552 LD->isNonTemporal(), LD->isInvariant(), 6553 LD->getAlignment()); 6554 6555 // We need to create a zextload/sextload. We cannot just create a load 6556 // followed by a zext/zext node because LowerMUL is also run during normal 6557 // operation legalization where we can't create illegal types. 6558 return DAG.getExtLoad(LD->getExtensionType(), SDLoc(LD), ExtendedTy, 6559 LD->getChain(), LD->getBasePtr(), LD->getPointerInfo(), 6560 LD->getMemoryVT(), LD->isVolatile(), LD->isInvariant(), 6561 LD->isNonTemporal(), LD->getAlignment()); 6562 } 6563 6564 /// SkipExtensionForVMULL - For a node that is a SIGN_EXTEND, ZERO_EXTEND, 6565 /// extending load, or BUILD_VECTOR with extended elements, return the 6566 /// unextended value. The unextended vector should be 64 bits so that it can 6567 /// be used as an operand to a VMULL instruction. If the original vector size 6568 /// before extension is less than 64 bits we add a an extension to resize 6569 /// the vector to 64 bits. 6570 static SDValue SkipExtensionForVMULL(SDNode *N, SelectionDAG &DAG) { 6571 if (N->getOpcode() == ISD::SIGN_EXTEND || N->getOpcode() == ISD::ZERO_EXTEND) 6572 return AddRequiredExtensionForVMULL(N->getOperand(0), DAG, 6573 N->getOperand(0)->getValueType(0), 6574 N->getValueType(0), 6575 N->getOpcode()); 6576 6577 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) 6578 return SkipLoadExtensionForVMULL(LD, DAG); 6579 6580 // Otherwise, the value must be a BUILD_VECTOR. For v2i64, it will 6581 // have been legalized as a BITCAST from v4i32. 6582 if (N->getOpcode() == ISD::BITCAST) { 6583 SDNode *BVN = N->getOperand(0).getNode(); 6584 assert(BVN->getOpcode() == ISD::BUILD_VECTOR && 6585 BVN->getValueType(0) == MVT::v4i32 && "expected v4i32 BUILD_VECTOR"); 6586 unsigned LowElt = DAG.getDataLayout().isBigEndian() ? 1 : 0; 6587 return DAG.getBuildVector( 6588 MVT::v2i32, SDLoc(N), 6589 {BVN->getOperand(LowElt), BVN->getOperand(LowElt + 2)}); 6590 } 6591 // Construct a new BUILD_VECTOR with elements truncated to half the size. 6592 assert(N->getOpcode() == ISD::BUILD_VECTOR && "expected BUILD_VECTOR"); 6593 EVT VT = N->getValueType(0); 6594 unsigned EltSize = VT.getVectorElementType().getSizeInBits() / 2; 6595 unsigned NumElts = VT.getVectorNumElements(); 6596 MVT TruncVT = MVT::getIntegerVT(EltSize); 6597 SmallVector<SDValue, 8> Ops; 6598 SDLoc dl(N); 6599 for (unsigned i = 0; i != NumElts; ++i) { 6600 ConstantSDNode *C = cast<ConstantSDNode>(N->getOperand(i)); 6601 const APInt &CInt = C->getAPIntValue(); 6602 // Element types smaller than 32 bits are not legal, so use i32 elements. 6603 // The values are implicitly truncated so sext vs. zext doesn't matter. 6604 Ops.push_back(DAG.getConstant(CInt.zextOrTrunc(32), dl, MVT::i32)); 6605 } 6606 return DAG.getBuildVector(MVT::getVectorVT(TruncVT, NumElts), dl, Ops); 6607 } 6608 6609 static bool isAddSubSExt(SDNode *N, SelectionDAG &DAG) { 6610 unsigned Opcode = N->getOpcode(); 6611 if (Opcode == ISD::ADD || Opcode == ISD::SUB) { 6612 SDNode *N0 = N->getOperand(0).getNode(); 6613 SDNode *N1 = N->getOperand(1).getNode(); 6614 return N0->hasOneUse() && N1->hasOneUse() && 6615 isSignExtended(N0, DAG) && isSignExtended(N1, DAG); 6616 } 6617 return false; 6618 } 6619 6620 static bool isAddSubZExt(SDNode *N, SelectionDAG &DAG) { 6621 unsigned Opcode = N->getOpcode(); 6622 if (Opcode == ISD::ADD || Opcode == ISD::SUB) { 6623 SDNode *N0 = N->getOperand(0).getNode(); 6624 SDNode *N1 = N->getOperand(1).getNode(); 6625 return N0->hasOneUse() && N1->hasOneUse() && 6626 isZeroExtended(N0, DAG) && isZeroExtended(N1, DAG); 6627 } 6628 return false; 6629 } 6630 6631 static SDValue LowerMUL(SDValue Op, SelectionDAG &DAG) { 6632 // Multiplications are only custom-lowered for 128-bit vectors so that 6633 // VMULL can be detected. Otherwise v2i64 multiplications are not legal. 6634 EVT VT = Op.getValueType(); 6635 assert(VT.is128BitVector() && VT.isInteger() && 6636 "unexpected type for custom-lowering ISD::MUL"); 6637 SDNode *N0 = Op.getOperand(0).getNode(); 6638 SDNode *N1 = Op.getOperand(1).getNode(); 6639 unsigned NewOpc = 0; 6640 bool isMLA = false; 6641 bool isN0SExt = isSignExtended(N0, DAG); 6642 bool isN1SExt = isSignExtended(N1, DAG); 6643 if (isN0SExt && isN1SExt) 6644 NewOpc = ARMISD::VMULLs; 6645 else { 6646 bool isN0ZExt = isZeroExtended(N0, DAG); 6647 bool isN1ZExt = isZeroExtended(N1, DAG); 6648 if (isN0ZExt && isN1ZExt) 6649 NewOpc = ARMISD::VMULLu; 6650 else if (isN1SExt || isN1ZExt) { 6651 // Look for (s/zext A + s/zext B) * (s/zext C). We want to turn these 6652 // into (s/zext A * s/zext C) + (s/zext B * s/zext C) 6653 if (isN1SExt && isAddSubSExt(N0, DAG)) { 6654 NewOpc = ARMISD::VMULLs; 6655 isMLA = true; 6656 } else if (isN1ZExt && isAddSubZExt(N0, DAG)) { 6657 NewOpc = ARMISD::VMULLu; 6658 isMLA = true; 6659 } else if (isN0ZExt && isAddSubZExt(N1, DAG)) { 6660 std::swap(N0, N1); 6661 NewOpc = ARMISD::VMULLu; 6662 isMLA = true; 6663 } 6664 } 6665 6666 if (!NewOpc) { 6667 if (VT == MVT::v2i64) 6668 // Fall through to expand this. It is not legal. 6669 return SDValue(); 6670 else 6671 // Other vector multiplications are legal. 6672 return Op; 6673 } 6674 } 6675 6676 // Legalize to a VMULL instruction. 6677 SDLoc DL(Op); 6678 SDValue Op0; 6679 SDValue Op1 = SkipExtensionForVMULL(N1, DAG); 6680 if (!isMLA) { 6681 Op0 = SkipExtensionForVMULL(N0, DAG); 6682 assert(Op0.getValueType().is64BitVector() && 6683 Op1.getValueType().is64BitVector() && 6684 "unexpected types for extended operands to VMULL"); 6685 return DAG.getNode(NewOpc, DL, VT, Op0, Op1); 6686 } 6687 6688 // Optimizing (zext A + zext B) * C, to (VMULL A, C) + (VMULL B, C) during 6689 // isel lowering to take advantage of no-stall back to back vmul + vmla. 6690 // vmull q0, d4, d6 6691 // vmlal q0, d5, d6 6692 // is faster than 6693 // vaddl q0, d4, d5 6694 // vmovl q1, d6 6695 // vmul q0, q0, q1 6696 SDValue N00 = SkipExtensionForVMULL(N0->getOperand(0).getNode(), DAG); 6697 SDValue N01 = SkipExtensionForVMULL(N0->getOperand(1).getNode(), DAG); 6698 EVT Op1VT = Op1.getValueType(); 6699 return DAG.getNode(N0->getOpcode(), DL, VT, 6700 DAG.getNode(NewOpc, DL, VT, 6701 DAG.getNode(ISD::BITCAST, DL, Op1VT, N00), Op1), 6702 DAG.getNode(NewOpc, DL, VT, 6703 DAG.getNode(ISD::BITCAST, DL, Op1VT, N01), Op1)); 6704 } 6705 6706 static SDValue LowerSDIV_v4i8(SDValue X, SDValue Y, const SDLoc &dl, 6707 SelectionDAG &DAG) { 6708 // TODO: Should this propagate fast-math-flags? 6709 6710 // Convert to float 6711 // float4 xf = vcvt_f32_s32(vmovl_s16(a.lo)); 6712 // float4 yf = vcvt_f32_s32(vmovl_s16(b.lo)); 6713 X = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, X); 6714 Y = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, Y); 6715 X = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, X); 6716 Y = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, Y); 6717 // Get reciprocal estimate. 6718 // float4 recip = vrecpeq_f32(yf); 6719 Y = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32, 6720 DAG.getConstant(Intrinsic::arm_neon_vrecpe, dl, MVT::i32), 6721 Y); 6722 // Because char has a smaller range than uchar, we can actually get away 6723 // without any newton steps. This requires that we use a weird bias 6724 // of 0xb000, however (again, this has been exhaustively tested). 6725 // float4 result = as_float4(as_int4(xf*recip) + 0xb000); 6726 X = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, X, Y); 6727 X = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, X); 6728 Y = DAG.getConstant(0xb000, dl, MVT::v4i32); 6729 X = DAG.getNode(ISD::ADD, dl, MVT::v4i32, X, Y); 6730 X = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, X); 6731 // Convert back to short. 6732 X = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::v4i32, X); 6733 X = DAG.getNode(ISD::TRUNCATE, dl, MVT::v4i16, X); 6734 return X; 6735 } 6736 6737 static SDValue LowerSDIV_v4i16(SDValue N0, SDValue N1, const SDLoc &dl, 6738 SelectionDAG &DAG) { 6739 // TODO: Should this propagate fast-math-flags? 6740 6741 SDValue N2; 6742 // Convert to float. 6743 // float4 yf = vcvt_f32_s32(vmovl_s16(y)); 6744 // float4 xf = vcvt_f32_s32(vmovl_s16(x)); 6745 N0 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, N0); 6746 N1 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, N1); 6747 N0 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N0); 6748 N1 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N1); 6749 6750 // Use reciprocal estimate and one refinement step. 6751 // float4 recip = vrecpeq_f32(yf); 6752 // recip *= vrecpsq_f32(yf, recip); 6753 N2 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32, 6754 DAG.getConstant(Intrinsic::arm_neon_vrecpe, dl, MVT::i32), 6755 N1); 6756 N1 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32, 6757 DAG.getConstant(Intrinsic::arm_neon_vrecps, dl, MVT::i32), 6758 N1, N2); 6759 N2 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N1, N2); 6760 // Because short has a smaller range than ushort, we can actually get away 6761 // with only a single newton step. This requires that we use a weird bias 6762 // of 89, however (again, this has been exhaustively tested). 6763 // float4 result = as_float4(as_int4(xf*recip) + 0x89); 6764 N0 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N0, N2); 6765 N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, N0); 6766 N1 = DAG.getConstant(0x89, dl, MVT::v4i32); 6767 N0 = DAG.getNode(ISD::ADD, dl, MVT::v4i32, N0, N1); 6768 N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, N0); 6769 // Convert back to integer and return. 6770 // return vmovn_s32(vcvt_s32_f32(result)); 6771 N0 = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::v4i32, N0); 6772 N0 = DAG.getNode(ISD::TRUNCATE, dl, MVT::v4i16, N0); 6773 return N0; 6774 } 6775 6776 static SDValue LowerSDIV(SDValue Op, SelectionDAG &DAG) { 6777 EVT VT = Op.getValueType(); 6778 assert((VT == MVT::v4i16 || VT == MVT::v8i8) && 6779 "unexpected type for custom-lowering ISD::SDIV"); 6780 6781 SDLoc dl(Op); 6782 SDValue N0 = Op.getOperand(0); 6783 SDValue N1 = Op.getOperand(1); 6784 SDValue N2, N3; 6785 6786 if (VT == MVT::v8i8) { 6787 N0 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v8i16, N0); 6788 N1 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v8i16, N1); 6789 6790 N2 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0, 6791 DAG.getIntPtrConstant(4, dl)); 6792 N3 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1, 6793 DAG.getIntPtrConstant(4, dl)); 6794 N0 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0, 6795 DAG.getIntPtrConstant(0, dl)); 6796 N1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1, 6797 DAG.getIntPtrConstant(0, dl)); 6798 6799 N0 = LowerSDIV_v4i8(N0, N1, dl, DAG); // v4i16 6800 N2 = LowerSDIV_v4i8(N2, N3, dl, DAG); // v4i16 6801 6802 N0 = DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v8i16, N0, N2); 6803 N0 = LowerCONCAT_VECTORS(N0, DAG); 6804 6805 N0 = DAG.getNode(ISD::TRUNCATE, dl, MVT::v8i8, N0); 6806 return N0; 6807 } 6808 return LowerSDIV_v4i16(N0, N1, dl, DAG); 6809 } 6810 6811 static SDValue LowerUDIV(SDValue Op, SelectionDAG &DAG) { 6812 // TODO: Should this propagate fast-math-flags? 6813 EVT VT = Op.getValueType(); 6814 assert((VT == MVT::v4i16 || VT == MVT::v8i8) && 6815 "unexpected type for custom-lowering ISD::UDIV"); 6816 6817 SDLoc dl(Op); 6818 SDValue N0 = Op.getOperand(0); 6819 SDValue N1 = Op.getOperand(1); 6820 SDValue N2, N3; 6821 6822 if (VT == MVT::v8i8) { 6823 N0 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v8i16, N0); 6824 N1 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v8i16, N1); 6825 6826 N2 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0, 6827 DAG.getIntPtrConstant(4, dl)); 6828 N3 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1, 6829 DAG.getIntPtrConstant(4, dl)); 6830 N0 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0, 6831 DAG.getIntPtrConstant(0, dl)); 6832 N1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1, 6833 DAG.getIntPtrConstant(0, dl)); 6834 6835 N0 = LowerSDIV_v4i16(N0, N1, dl, DAG); // v4i16 6836 N2 = LowerSDIV_v4i16(N2, N3, dl, DAG); // v4i16 6837 6838 N0 = DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v8i16, N0, N2); 6839 N0 = LowerCONCAT_VECTORS(N0, DAG); 6840 6841 N0 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v8i8, 6842 DAG.getConstant(Intrinsic::arm_neon_vqmovnsu, dl, 6843 MVT::i32), 6844 N0); 6845 return N0; 6846 } 6847 6848 // v4i16 sdiv ... Convert to float. 6849 // float4 yf = vcvt_f32_s32(vmovl_u16(y)); 6850 // float4 xf = vcvt_f32_s32(vmovl_u16(x)); 6851 N0 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v4i32, N0); 6852 N1 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v4i32, N1); 6853 N0 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N0); 6854 SDValue BN1 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N1); 6855 6856 // Use reciprocal estimate and two refinement steps. 6857 // float4 recip = vrecpeq_f32(yf); 6858 // recip *= vrecpsq_f32(yf, recip); 6859 // recip *= vrecpsq_f32(yf, recip); 6860 N2 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32, 6861 DAG.getConstant(Intrinsic::arm_neon_vrecpe, dl, MVT::i32), 6862 BN1); 6863 N1 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32, 6864 DAG.getConstant(Intrinsic::arm_neon_vrecps, dl, MVT::i32), 6865 BN1, N2); 6866 N2 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N1, N2); 6867 N1 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32, 6868 DAG.getConstant(Intrinsic::arm_neon_vrecps, dl, MVT::i32), 6869 BN1, N2); 6870 N2 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N1, N2); 6871 // Simply multiplying by the reciprocal estimate can leave us a few ulps 6872 // too low, so we add 2 ulps (exhaustive testing shows that this is enough, 6873 // and that it will never cause us to return an answer too large). 6874 // float4 result = as_float4(as_int4(xf*recip) + 2); 6875 N0 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N0, N2); 6876 N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, N0); 6877 N1 = DAG.getConstant(2, dl, MVT::v4i32); 6878 N0 = DAG.getNode(ISD::ADD, dl, MVT::v4i32, N0, N1); 6879 N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, N0); 6880 // Convert back to integer and return. 6881 // return vmovn_u32(vcvt_s32_f32(result)); 6882 N0 = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::v4i32, N0); 6883 N0 = DAG.getNode(ISD::TRUNCATE, dl, MVT::v4i16, N0); 6884 return N0; 6885 } 6886 6887 static SDValue LowerADDC_ADDE_SUBC_SUBE(SDValue Op, SelectionDAG &DAG) { 6888 EVT VT = Op.getNode()->getValueType(0); 6889 SDVTList VTs = DAG.getVTList(VT, MVT::i32); 6890 6891 unsigned Opc; 6892 bool ExtraOp = false; 6893 switch (Op.getOpcode()) { 6894 default: llvm_unreachable("Invalid code"); 6895 case ISD::ADDC: Opc = ARMISD::ADDC; break; 6896 case ISD::ADDE: Opc = ARMISD::ADDE; ExtraOp = true; break; 6897 case ISD::SUBC: Opc = ARMISD::SUBC; break; 6898 case ISD::SUBE: Opc = ARMISD::SUBE; ExtraOp = true; break; 6899 } 6900 6901 if (!ExtraOp) 6902 return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0), 6903 Op.getOperand(1)); 6904 return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0), 6905 Op.getOperand(1), Op.getOperand(2)); 6906 } 6907 6908 SDValue ARMTargetLowering::LowerFSINCOS(SDValue Op, SelectionDAG &DAG) const { 6909 assert(Subtarget->isTargetDarwin()); 6910 6911 // For iOS, we want to call an alternative entry point: __sincos_stret, 6912 // return values are passed via sret. 6913 SDLoc dl(Op); 6914 SDValue Arg = Op.getOperand(0); 6915 EVT ArgVT = Arg.getValueType(); 6916 Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext()); 6917 auto PtrVT = getPointerTy(DAG.getDataLayout()); 6918 6919 MachineFrameInfo *FrameInfo = DAG.getMachineFunction().getFrameInfo(); 6920 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 6921 6922 // Pair of floats / doubles used to pass the result. 6923 Type *RetTy = StructType::get(ArgTy, ArgTy, nullptr); 6924 auto &DL = DAG.getDataLayout(); 6925 6926 ArgListTy Args; 6927 bool ShouldUseSRet = Subtarget->isAPCS_ABI(); 6928 SDValue SRet; 6929 if (ShouldUseSRet) { 6930 // Create stack object for sret. 6931 const uint64_t ByteSize = DL.getTypeAllocSize(RetTy); 6932 const unsigned StackAlign = DL.getPrefTypeAlignment(RetTy); 6933 int FrameIdx = FrameInfo->CreateStackObject(ByteSize, StackAlign, false); 6934 SRet = DAG.getFrameIndex(FrameIdx, TLI.getPointerTy(DL)); 6935 6936 ArgListEntry Entry; 6937 Entry.Node = SRet; 6938 Entry.Ty = RetTy->getPointerTo(); 6939 Entry.isSExt = false; 6940 Entry.isZExt = false; 6941 Entry.isSRet = true; 6942 Args.push_back(Entry); 6943 RetTy = Type::getVoidTy(*DAG.getContext()); 6944 } 6945 6946 ArgListEntry Entry; 6947 Entry.Node = Arg; 6948 Entry.Ty = ArgTy; 6949 Entry.isSExt = false; 6950 Entry.isZExt = false; 6951 Args.push_back(Entry); 6952 6953 const char *LibcallName = 6954 (ArgVT == MVT::f64) ? "__sincos_stret" : "__sincosf_stret"; 6955 RTLIB::Libcall LC = 6956 (ArgVT == MVT::f64) ? RTLIB::SINCOS_F64 : RTLIB::SINCOS_F32; 6957 CallingConv::ID CC = getLibcallCallingConv(LC); 6958 SDValue Callee = DAG.getExternalSymbol(LibcallName, getPointerTy(DL)); 6959 6960 TargetLowering::CallLoweringInfo CLI(DAG); 6961 CLI.setDebugLoc(dl) 6962 .setChain(DAG.getEntryNode()) 6963 .setCallee(CC, RetTy, Callee, std::move(Args)) 6964 .setDiscardResult(ShouldUseSRet); 6965 std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI); 6966 6967 if (!ShouldUseSRet) 6968 return CallResult.first; 6969 6970 SDValue LoadSin = DAG.getLoad(ArgVT, dl, CallResult.second, SRet, 6971 MachinePointerInfo(), false, false, false, 0); 6972 6973 // Address of cos field. 6974 SDValue Add = DAG.getNode(ISD::ADD, dl, PtrVT, SRet, 6975 DAG.getIntPtrConstant(ArgVT.getStoreSize(), dl)); 6976 SDValue LoadCos = DAG.getLoad(ArgVT, dl, LoadSin.getValue(1), Add, 6977 MachinePointerInfo(), false, false, false, 0); 6978 6979 SDVTList Tys = DAG.getVTList(ArgVT, ArgVT); 6980 return DAG.getNode(ISD::MERGE_VALUES, dl, Tys, 6981 LoadSin.getValue(0), LoadCos.getValue(0)); 6982 } 6983 6984 SDValue ARMTargetLowering::LowerWindowsDIVLibCall(SDValue Op, SelectionDAG &DAG, 6985 bool Signed, 6986 SDValue &Chain) const { 6987 EVT VT = Op.getValueType(); 6988 assert((VT == MVT::i32 || VT == MVT::i64) && 6989 "unexpected type for custom lowering DIV"); 6990 SDLoc dl(Op); 6991 6992 const auto &DL = DAG.getDataLayout(); 6993 const auto &TLI = DAG.getTargetLoweringInfo(); 6994 6995 const char *Name = nullptr; 6996 if (Signed) 6997 Name = (VT == MVT::i32) ? "__rt_sdiv" : "__rt_sdiv64"; 6998 else 6999 Name = (VT == MVT::i32) ? "__rt_udiv" : "__rt_udiv64"; 7000 7001 SDValue ES = DAG.getExternalSymbol(Name, TLI.getPointerTy(DL)); 7002 7003 ARMTargetLowering::ArgListTy Args; 7004 7005 for (auto AI : {1, 0}) { 7006 ArgListEntry Arg; 7007 Arg.Node = Op.getOperand(AI); 7008 Arg.Ty = Arg.Node.getValueType().getTypeForEVT(*DAG.getContext()); 7009 Args.push_back(Arg); 7010 } 7011 7012 CallLoweringInfo CLI(DAG); 7013 CLI.setDebugLoc(dl) 7014 .setChain(Chain) 7015 .setCallee(CallingConv::ARM_AAPCS_VFP, VT.getTypeForEVT(*DAG.getContext()), 7016 ES, std::move(Args)); 7017 7018 return LowerCallTo(CLI).first; 7019 } 7020 7021 SDValue ARMTargetLowering::LowerDIV_Windows(SDValue Op, SelectionDAG &DAG, 7022 bool Signed) const { 7023 assert(Op.getValueType() == MVT::i32 && 7024 "unexpected type for custom lowering DIV"); 7025 SDLoc dl(Op); 7026 7027 SDValue DBZCHK = DAG.getNode(ARMISD::WIN__DBZCHK, dl, MVT::Other, 7028 DAG.getEntryNode(), Op.getOperand(1)); 7029 7030 return LowerWindowsDIVLibCall(Op, DAG, Signed, DBZCHK); 7031 } 7032 7033 void ARMTargetLowering::ExpandDIV_Windows( 7034 SDValue Op, SelectionDAG &DAG, bool Signed, 7035 SmallVectorImpl<SDValue> &Results) const { 7036 const auto &DL = DAG.getDataLayout(); 7037 const auto &TLI = DAG.getTargetLoweringInfo(); 7038 7039 assert(Op.getValueType() == MVT::i64 && 7040 "unexpected type for custom lowering DIV"); 7041 SDLoc dl(Op); 7042 7043 SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, Op.getOperand(1), 7044 DAG.getConstant(0, dl, MVT::i32)); 7045 SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, Op.getOperand(1), 7046 DAG.getConstant(1, dl, MVT::i32)); 7047 SDValue Or = DAG.getNode(ISD::OR, dl, MVT::i32, Lo, Hi); 7048 7049 SDValue DBZCHK = 7050 DAG.getNode(ARMISD::WIN__DBZCHK, dl, MVT::Other, DAG.getEntryNode(), Or); 7051 7052 SDValue Result = LowerWindowsDIVLibCall(Op, DAG, Signed, DBZCHK); 7053 7054 SDValue Lower = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, Result); 7055 SDValue Upper = DAG.getNode(ISD::SRL, dl, MVT::i64, Result, 7056 DAG.getConstant(32, dl, TLI.getPointerTy(DL))); 7057 Upper = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, Upper); 7058 7059 Results.push_back(Lower); 7060 Results.push_back(Upper); 7061 } 7062 7063 static SDValue LowerAtomicLoadStore(SDValue Op, SelectionDAG &DAG) { 7064 if (isStrongerThanMonotonic(cast<AtomicSDNode>(Op)->getOrdering())) 7065 // Acquire/Release load/store is not legal for targets without a dmb or 7066 // equivalent available. 7067 return SDValue(); 7068 7069 // Monotonic load/store is legal for all targets. 7070 return Op; 7071 } 7072 7073 static void ReplaceREADCYCLECOUNTER(SDNode *N, 7074 SmallVectorImpl<SDValue> &Results, 7075 SelectionDAG &DAG, 7076 const ARMSubtarget *Subtarget) { 7077 SDLoc DL(N); 7078 // Under Power Management extensions, the cycle-count is: 7079 // mrc p15, #0, <Rt>, c9, c13, #0 7080 SDValue Ops[] = { N->getOperand(0), // Chain 7081 DAG.getConstant(Intrinsic::arm_mrc, DL, MVT::i32), 7082 DAG.getConstant(15, DL, MVT::i32), 7083 DAG.getConstant(0, DL, MVT::i32), 7084 DAG.getConstant(9, DL, MVT::i32), 7085 DAG.getConstant(13, DL, MVT::i32), 7086 DAG.getConstant(0, DL, MVT::i32) 7087 }; 7088 7089 SDValue Cycles32 = DAG.getNode(ISD::INTRINSIC_W_CHAIN, DL, 7090 DAG.getVTList(MVT::i32, MVT::Other), Ops); 7091 Results.push_back(DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, Cycles32, 7092 DAG.getConstant(0, DL, MVT::i32))); 7093 Results.push_back(Cycles32.getValue(1)); 7094 } 7095 7096 static SDValue createGPRPairNode(SelectionDAG &DAG, SDValue V) { 7097 SDLoc dl(V.getNode()); 7098 SDValue VLo = DAG.getAnyExtOrTrunc(V, dl, MVT::i32); 7099 SDValue VHi = DAG.getAnyExtOrTrunc( 7100 DAG.getNode(ISD::SRL, dl, MVT::i64, V, DAG.getConstant(32, dl, MVT::i32)), 7101 dl, MVT::i32); 7102 SDValue RegClass = 7103 DAG.getTargetConstant(ARM::GPRPairRegClassID, dl, MVT::i32); 7104 SDValue SubReg0 = DAG.getTargetConstant(ARM::gsub_0, dl, MVT::i32); 7105 SDValue SubReg1 = DAG.getTargetConstant(ARM::gsub_1, dl, MVT::i32); 7106 const SDValue Ops[] = { RegClass, VLo, SubReg0, VHi, SubReg1 }; 7107 return SDValue( 7108 DAG.getMachineNode(TargetOpcode::REG_SEQUENCE, dl, MVT::Untyped, Ops), 0); 7109 } 7110 7111 static void ReplaceCMP_SWAP_64Results(SDNode *N, 7112 SmallVectorImpl<SDValue> & Results, 7113 SelectionDAG &DAG) { 7114 assert(N->getValueType(0) == MVT::i64 && 7115 "AtomicCmpSwap on types less than 64 should be legal"); 7116 SDValue Ops[] = {N->getOperand(1), 7117 createGPRPairNode(DAG, N->getOperand(2)), 7118 createGPRPairNode(DAG, N->getOperand(3)), 7119 N->getOperand(0)}; 7120 SDNode *CmpSwap = DAG.getMachineNode( 7121 ARM::CMP_SWAP_64, SDLoc(N), 7122 DAG.getVTList(MVT::Untyped, MVT::i32, MVT::Other), Ops); 7123 7124 MachineFunction &MF = DAG.getMachineFunction(); 7125 MachineSDNode::mmo_iterator MemOp = MF.allocateMemRefsArray(1); 7126 MemOp[0] = cast<MemSDNode>(N)->getMemOperand(); 7127 cast<MachineSDNode>(CmpSwap)->setMemRefs(MemOp, MemOp + 1); 7128 7129 Results.push_back(DAG.getTargetExtractSubreg(ARM::gsub_0, SDLoc(N), MVT::i32, 7130 SDValue(CmpSwap, 0))); 7131 Results.push_back(DAG.getTargetExtractSubreg(ARM::gsub_1, SDLoc(N), MVT::i32, 7132 SDValue(CmpSwap, 0))); 7133 Results.push_back(SDValue(CmpSwap, 2)); 7134 } 7135 7136 SDValue ARMTargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const { 7137 switch (Op.getOpcode()) { 7138 default: llvm_unreachable("Don't know how to custom lower this!"); 7139 case ISD::WRITE_REGISTER: return LowerWRITE_REGISTER(Op, DAG); 7140 case ISD::ConstantPool: return LowerConstantPool(Op, DAG); 7141 case ISD::BlockAddress: return LowerBlockAddress(Op, DAG); 7142 case ISD::GlobalAddress: 7143 switch (Subtarget->getTargetTriple().getObjectFormat()) { 7144 default: llvm_unreachable("unknown object format"); 7145 case Triple::COFF: 7146 return LowerGlobalAddressWindows(Op, DAG); 7147 case Triple::ELF: 7148 return LowerGlobalAddressELF(Op, DAG); 7149 case Triple::MachO: 7150 return LowerGlobalAddressDarwin(Op, DAG); 7151 } 7152 case ISD::GlobalTLSAddress: return LowerGlobalTLSAddress(Op, DAG); 7153 case ISD::SELECT: return LowerSELECT(Op, DAG); 7154 case ISD::SELECT_CC: return LowerSELECT_CC(Op, DAG); 7155 case ISD::BR_CC: return LowerBR_CC(Op, DAG); 7156 case ISD::BR_JT: return LowerBR_JT(Op, DAG); 7157 case ISD::VASTART: return LowerVASTART(Op, DAG); 7158 case ISD::ATOMIC_FENCE: return LowerATOMIC_FENCE(Op, DAG, Subtarget); 7159 case ISD::PREFETCH: return LowerPREFETCH(Op, DAG, Subtarget); 7160 case ISD::SINT_TO_FP: 7161 case ISD::UINT_TO_FP: return LowerINT_TO_FP(Op, DAG); 7162 case ISD::FP_TO_SINT: 7163 case ISD::FP_TO_UINT: return LowerFP_TO_INT(Op, DAG); 7164 case ISD::FCOPYSIGN: return LowerFCOPYSIGN(Op, DAG); 7165 case ISD::RETURNADDR: return LowerRETURNADDR(Op, DAG); 7166 case ISD::FRAMEADDR: return LowerFRAMEADDR(Op, DAG); 7167 case ISD::EH_SJLJ_SETJMP: return LowerEH_SJLJ_SETJMP(Op, DAG); 7168 case ISD::EH_SJLJ_LONGJMP: return LowerEH_SJLJ_LONGJMP(Op, DAG); 7169 case ISD::EH_SJLJ_SETUP_DISPATCH: return LowerEH_SJLJ_SETUP_DISPATCH(Op, DAG); 7170 case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG, 7171 Subtarget); 7172 case ISD::BITCAST: return ExpandBITCAST(Op.getNode(), DAG); 7173 case ISD::SHL: 7174 case ISD::SRL: 7175 case ISD::SRA: return LowerShift(Op.getNode(), DAG, Subtarget); 7176 case ISD::SREM: return LowerREM(Op.getNode(), DAG); 7177 case ISD::UREM: return LowerREM(Op.getNode(), DAG); 7178 case ISD::SHL_PARTS: return LowerShiftLeftParts(Op, DAG); 7179 case ISD::SRL_PARTS: 7180 case ISD::SRA_PARTS: return LowerShiftRightParts(Op, DAG); 7181 case ISD::CTTZ: 7182 case ISD::CTTZ_ZERO_UNDEF: return LowerCTTZ(Op.getNode(), DAG, Subtarget); 7183 case ISD::CTPOP: return LowerCTPOP(Op.getNode(), DAG, Subtarget); 7184 case ISD::SETCC: return LowerVSETCC(Op, DAG); 7185 case ISD::SETCCE: return LowerSETCCE(Op, DAG); 7186 case ISD::ConstantFP: return LowerConstantFP(Op, DAG, Subtarget); 7187 case ISD::BUILD_VECTOR: return LowerBUILD_VECTOR(Op, DAG, Subtarget); 7188 case ISD::VECTOR_SHUFFLE: return LowerVECTOR_SHUFFLE(Op, DAG); 7189 case ISD::INSERT_VECTOR_ELT: return LowerINSERT_VECTOR_ELT(Op, DAG); 7190 case ISD::EXTRACT_VECTOR_ELT: return LowerEXTRACT_VECTOR_ELT(Op, DAG); 7191 case ISD::CONCAT_VECTORS: return LowerCONCAT_VECTORS(Op, DAG); 7192 case ISD::FLT_ROUNDS_: return LowerFLT_ROUNDS_(Op, DAG); 7193 case ISD::MUL: return LowerMUL(Op, DAG); 7194 case ISD::SDIV: 7195 if (Subtarget->isTargetWindows()) 7196 return LowerDIV_Windows(Op, DAG, /* Signed */ true); 7197 return LowerSDIV(Op, DAG); 7198 case ISD::UDIV: 7199 if (Subtarget->isTargetWindows()) 7200 return LowerDIV_Windows(Op, DAG, /* Signed */ false); 7201 return LowerUDIV(Op, DAG); 7202 case ISD::ADDC: 7203 case ISD::ADDE: 7204 case ISD::SUBC: 7205 case ISD::SUBE: return LowerADDC_ADDE_SUBC_SUBE(Op, DAG); 7206 case ISD::SADDO: 7207 case ISD::UADDO: 7208 case ISD::SSUBO: 7209 case ISD::USUBO: 7210 return LowerXALUO(Op, DAG); 7211 case ISD::ATOMIC_LOAD: 7212 case ISD::ATOMIC_STORE: return LowerAtomicLoadStore(Op, DAG); 7213 case ISD::FSINCOS: return LowerFSINCOS(Op, DAG); 7214 case ISD::SDIVREM: 7215 case ISD::UDIVREM: return LowerDivRem(Op, DAG); 7216 case ISD::DYNAMIC_STACKALLOC: 7217 if (Subtarget->getTargetTriple().isWindowsItaniumEnvironment()) 7218 return LowerDYNAMIC_STACKALLOC(Op, DAG); 7219 llvm_unreachable("Don't know how to custom lower this!"); 7220 case ISD::FP_ROUND: return LowerFP_ROUND(Op, DAG); 7221 case ISD::FP_EXTEND: return LowerFP_EXTEND(Op, DAG); 7222 case ARMISD::WIN__DBZCHK: return SDValue(); 7223 } 7224 } 7225 7226 /// ReplaceNodeResults - Replace the results of node with an illegal result 7227 /// type with new values built out of custom code. 7228 void ARMTargetLowering::ReplaceNodeResults(SDNode *N, 7229 SmallVectorImpl<SDValue> &Results, 7230 SelectionDAG &DAG) const { 7231 SDValue Res; 7232 switch (N->getOpcode()) { 7233 default: 7234 llvm_unreachable("Don't know how to custom expand this!"); 7235 case ISD::READ_REGISTER: 7236 ExpandREAD_REGISTER(N, Results, DAG); 7237 break; 7238 case ISD::BITCAST: 7239 Res = ExpandBITCAST(N, DAG); 7240 break; 7241 case ISD::SRL: 7242 case ISD::SRA: 7243 Res = Expand64BitShift(N, DAG, Subtarget); 7244 break; 7245 case ISD::SREM: 7246 case ISD::UREM: 7247 Res = LowerREM(N, DAG); 7248 break; 7249 case ISD::SDIVREM: 7250 case ISD::UDIVREM: 7251 Res = LowerDivRem(SDValue(N, 0), DAG); 7252 assert(Res.getNumOperands() == 2 && "DivRem needs two values"); 7253 Results.push_back(Res.getValue(0)); 7254 Results.push_back(Res.getValue(1)); 7255 return; 7256 case ISD::READCYCLECOUNTER: 7257 ReplaceREADCYCLECOUNTER(N, Results, DAG, Subtarget); 7258 return; 7259 case ISD::UDIV: 7260 case ISD::SDIV: 7261 assert(Subtarget->isTargetWindows() && "can only expand DIV on Windows"); 7262 return ExpandDIV_Windows(SDValue(N, 0), DAG, N->getOpcode() == ISD::SDIV, 7263 Results); 7264 case ISD::ATOMIC_CMP_SWAP: 7265 ReplaceCMP_SWAP_64Results(N, Results, DAG); 7266 return; 7267 } 7268 if (Res.getNode()) 7269 Results.push_back(Res); 7270 } 7271 7272 //===----------------------------------------------------------------------===// 7273 // ARM Scheduler Hooks 7274 //===----------------------------------------------------------------------===// 7275 7276 /// SetupEntryBlockForSjLj - Insert code into the entry block that creates and 7277 /// registers the function context. 7278 void ARMTargetLowering:: 7279 SetupEntryBlockForSjLj(MachineInstr *MI, MachineBasicBlock *MBB, 7280 MachineBasicBlock *DispatchBB, int FI) const { 7281 const TargetInstrInfo *TII = Subtarget->getInstrInfo(); 7282 DebugLoc dl = MI->getDebugLoc(); 7283 MachineFunction *MF = MBB->getParent(); 7284 MachineRegisterInfo *MRI = &MF->getRegInfo(); 7285 MachineConstantPool *MCP = MF->getConstantPool(); 7286 ARMFunctionInfo *AFI = MF->getInfo<ARMFunctionInfo>(); 7287 const Function *F = MF->getFunction(); 7288 7289 bool isThumb = Subtarget->isThumb(); 7290 bool isThumb2 = Subtarget->isThumb2(); 7291 7292 unsigned PCLabelId = AFI->createPICLabelUId(); 7293 unsigned PCAdj = (isThumb || isThumb2) ? 4 : 8; 7294 ARMConstantPoolValue *CPV = 7295 ARMConstantPoolMBB::Create(F->getContext(), DispatchBB, PCLabelId, PCAdj); 7296 unsigned CPI = MCP->getConstantPoolIndex(CPV, 4); 7297 7298 const TargetRegisterClass *TRC = isThumb ? &ARM::tGPRRegClass 7299 : &ARM::GPRRegClass; 7300 7301 // Grab constant pool and fixed stack memory operands. 7302 MachineMemOperand *CPMMO = 7303 MF->getMachineMemOperand(MachinePointerInfo::getConstantPool(*MF), 7304 MachineMemOperand::MOLoad, 4, 4); 7305 7306 MachineMemOperand *FIMMOSt = 7307 MF->getMachineMemOperand(MachinePointerInfo::getFixedStack(*MF, FI), 7308 MachineMemOperand::MOStore, 4, 4); 7309 7310 // Load the address of the dispatch MBB into the jump buffer. 7311 if (isThumb2) { 7312 // Incoming value: jbuf 7313 // ldr.n r5, LCPI1_1 7314 // orr r5, r5, #1 7315 // add r5, pc 7316 // str r5, [$jbuf, #+4] ; &jbuf[1] 7317 unsigned NewVReg1 = MRI->createVirtualRegister(TRC); 7318 AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::t2LDRpci), NewVReg1) 7319 .addConstantPoolIndex(CPI) 7320 .addMemOperand(CPMMO)); 7321 // Set the low bit because of thumb mode. 7322 unsigned NewVReg2 = MRI->createVirtualRegister(TRC); 7323 AddDefaultCC( 7324 AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::t2ORRri), NewVReg2) 7325 .addReg(NewVReg1, RegState::Kill) 7326 .addImm(0x01))); 7327 unsigned NewVReg3 = MRI->createVirtualRegister(TRC); 7328 BuildMI(*MBB, MI, dl, TII->get(ARM::tPICADD), NewVReg3) 7329 .addReg(NewVReg2, RegState::Kill) 7330 .addImm(PCLabelId); 7331 AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::t2STRi12)) 7332 .addReg(NewVReg3, RegState::Kill) 7333 .addFrameIndex(FI) 7334 .addImm(36) // &jbuf[1] :: pc 7335 .addMemOperand(FIMMOSt)); 7336 } else if (isThumb) { 7337 // Incoming value: jbuf 7338 // ldr.n r1, LCPI1_4 7339 // add r1, pc 7340 // mov r2, #1 7341 // orrs r1, r2 7342 // add r2, $jbuf, #+4 ; &jbuf[1] 7343 // str r1, [r2] 7344 unsigned NewVReg1 = MRI->createVirtualRegister(TRC); 7345 AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::tLDRpci), NewVReg1) 7346 .addConstantPoolIndex(CPI) 7347 .addMemOperand(CPMMO)); 7348 unsigned NewVReg2 = MRI->createVirtualRegister(TRC); 7349 BuildMI(*MBB, MI, dl, TII->get(ARM::tPICADD), NewVReg2) 7350 .addReg(NewVReg1, RegState::Kill) 7351 .addImm(PCLabelId); 7352 // Set the low bit because of thumb mode. 7353 unsigned NewVReg3 = MRI->createVirtualRegister(TRC); 7354 AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::tMOVi8), NewVReg3) 7355 .addReg(ARM::CPSR, RegState::Define) 7356 .addImm(1)); 7357 unsigned NewVReg4 = MRI->createVirtualRegister(TRC); 7358 AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::tORR), NewVReg4) 7359 .addReg(ARM::CPSR, RegState::Define) 7360 .addReg(NewVReg2, RegState::Kill) 7361 .addReg(NewVReg3, RegState::Kill)); 7362 unsigned NewVReg5 = MRI->createVirtualRegister(TRC); 7363 BuildMI(*MBB, MI, dl, TII->get(ARM::tADDframe), NewVReg5) 7364 .addFrameIndex(FI) 7365 .addImm(36); // &jbuf[1] :: pc 7366 AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::tSTRi)) 7367 .addReg(NewVReg4, RegState::Kill) 7368 .addReg(NewVReg5, RegState::Kill) 7369 .addImm(0) 7370 .addMemOperand(FIMMOSt)); 7371 } else { 7372 // Incoming value: jbuf 7373 // ldr r1, LCPI1_1 7374 // add r1, pc, r1 7375 // str r1, [$jbuf, #+4] ; &jbuf[1] 7376 unsigned NewVReg1 = MRI->createVirtualRegister(TRC); 7377 AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::LDRi12), NewVReg1) 7378 .addConstantPoolIndex(CPI) 7379 .addImm(0) 7380 .addMemOperand(CPMMO)); 7381 unsigned NewVReg2 = MRI->createVirtualRegister(TRC); 7382 AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::PICADD), NewVReg2) 7383 .addReg(NewVReg1, RegState::Kill) 7384 .addImm(PCLabelId)); 7385 AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::STRi12)) 7386 .addReg(NewVReg2, RegState::Kill) 7387 .addFrameIndex(FI) 7388 .addImm(36) // &jbuf[1] :: pc 7389 .addMemOperand(FIMMOSt)); 7390 } 7391 } 7392 7393 void ARMTargetLowering::EmitSjLjDispatchBlock(MachineInstr *MI, 7394 MachineBasicBlock *MBB) const { 7395 const TargetInstrInfo *TII = Subtarget->getInstrInfo(); 7396 DebugLoc dl = MI->getDebugLoc(); 7397 MachineFunction *MF = MBB->getParent(); 7398 MachineRegisterInfo *MRI = &MF->getRegInfo(); 7399 MachineFrameInfo *MFI = MF->getFrameInfo(); 7400 int FI = MFI->getFunctionContextIndex(); 7401 7402 const TargetRegisterClass *TRC = Subtarget->isThumb() ? &ARM::tGPRRegClass 7403 : &ARM::GPRnopcRegClass; 7404 7405 // Get a mapping of the call site numbers to all of the landing pads they're 7406 // associated with. 7407 DenseMap<unsigned, SmallVector<MachineBasicBlock*, 2> > CallSiteNumToLPad; 7408 unsigned MaxCSNum = 0; 7409 MachineModuleInfo &MMI = MF->getMMI(); 7410 for (MachineFunction::iterator BB = MF->begin(), E = MF->end(); BB != E; 7411 ++BB) { 7412 if (!BB->isEHPad()) continue; 7413 7414 // FIXME: We should assert that the EH_LABEL is the first MI in the landing 7415 // pad. 7416 for (MachineBasicBlock::iterator 7417 II = BB->begin(), IE = BB->end(); II != IE; ++II) { 7418 if (!II->isEHLabel()) continue; 7419 7420 MCSymbol *Sym = II->getOperand(0).getMCSymbol(); 7421 if (!MMI.hasCallSiteLandingPad(Sym)) continue; 7422 7423 SmallVectorImpl<unsigned> &CallSiteIdxs = MMI.getCallSiteLandingPad(Sym); 7424 for (SmallVectorImpl<unsigned>::iterator 7425 CSI = CallSiteIdxs.begin(), CSE = CallSiteIdxs.end(); 7426 CSI != CSE; ++CSI) { 7427 CallSiteNumToLPad[*CSI].push_back(&*BB); 7428 MaxCSNum = std::max(MaxCSNum, *CSI); 7429 } 7430 break; 7431 } 7432 } 7433 7434 // Get an ordered list of the machine basic blocks for the jump table. 7435 std::vector<MachineBasicBlock*> LPadList; 7436 SmallPtrSet<MachineBasicBlock*, 32> InvokeBBs; 7437 LPadList.reserve(CallSiteNumToLPad.size()); 7438 for (unsigned I = 1; I <= MaxCSNum; ++I) { 7439 SmallVectorImpl<MachineBasicBlock*> &MBBList = CallSiteNumToLPad[I]; 7440 for (SmallVectorImpl<MachineBasicBlock*>::iterator 7441 II = MBBList.begin(), IE = MBBList.end(); II != IE; ++II) { 7442 LPadList.push_back(*II); 7443 InvokeBBs.insert((*II)->pred_begin(), (*II)->pred_end()); 7444 } 7445 } 7446 7447 assert(!LPadList.empty() && 7448 "No landing pad destinations for the dispatch jump table!"); 7449 7450 // Create the jump table and associated information. 7451 MachineJumpTableInfo *JTI = 7452 MF->getOrCreateJumpTableInfo(MachineJumpTableInfo::EK_Inline); 7453 unsigned MJTI = JTI->createJumpTableIndex(LPadList); 7454 7455 // Create the MBBs for the dispatch code. 7456 7457 // Shove the dispatch's address into the return slot in the function context. 7458 MachineBasicBlock *DispatchBB = MF->CreateMachineBasicBlock(); 7459 DispatchBB->setIsEHPad(); 7460 7461 MachineBasicBlock *TrapBB = MF->CreateMachineBasicBlock(); 7462 unsigned trap_opcode; 7463 if (Subtarget->isThumb()) 7464 trap_opcode = ARM::tTRAP; 7465 else 7466 trap_opcode = Subtarget->useNaClTrap() ? ARM::TRAPNaCl : ARM::TRAP; 7467 7468 BuildMI(TrapBB, dl, TII->get(trap_opcode)); 7469 DispatchBB->addSuccessor(TrapBB); 7470 7471 MachineBasicBlock *DispContBB = MF->CreateMachineBasicBlock(); 7472 DispatchBB->addSuccessor(DispContBB); 7473 7474 // Insert and MBBs. 7475 MF->insert(MF->end(), DispatchBB); 7476 MF->insert(MF->end(), DispContBB); 7477 MF->insert(MF->end(), TrapBB); 7478 7479 // Insert code into the entry block that creates and registers the function 7480 // context. 7481 SetupEntryBlockForSjLj(MI, MBB, DispatchBB, FI); 7482 7483 MachineMemOperand *FIMMOLd = MF->getMachineMemOperand( 7484 MachinePointerInfo::getFixedStack(*MF, FI), 7485 MachineMemOperand::MOLoad | MachineMemOperand::MOVolatile, 4, 4); 7486 7487 MachineInstrBuilder MIB; 7488 MIB = BuildMI(DispatchBB, dl, TII->get(ARM::Int_eh_sjlj_dispatchsetup)); 7489 7490 const ARMBaseInstrInfo *AII = static_cast<const ARMBaseInstrInfo*>(TII); 7491 const ARMBaseRegisterInfo &RI = AII->getRegisterInfo(); 7492 7493 // Add a register mask with no preserved registers. This results in all 7494 // registers being marked as clobbered. 7495 MIB.addRegMask(RI.getNoPreservedMask()); 7496 7497 bool IsPositionIndependent = isPositionIndependent(); 7498 unsigned NumLPads = LPadList.size(); 7499 if (Subtarget->isThumb2()) { 7500 unsigned NewVReg1 = MRI->createVirtualRegister(TRC); 7501 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::t2LDRi12), NewVReg1) 7502 .addFrameIndex(FI) 7503 .addImm(4) 7504 .addMemOperand(FIMMOLd)); 7505 7506 if (NumLPads < 256) { 7507 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::t2CMPri)) 7508 .addReg(NewVReg1) 7509 .addImm(LPadList.size())); 7510 } else { 7511 unsigned VReg1 = MRI->createVirtualRegister(TRC); 7512 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::t2MOVi16), VReg1) 7513 .addImm(NumLPads & 0xFFFF)); 7514 7515 unsigned VReg2 = VReg1; 7516 if ((NumLPads & 0xFFFF0000) != 0) { 7517 VReg2 = MRI->createVirtualRegister(TRC); 7518 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::t2MOVTi16), VReg2) 7519 .addReg(VReg1) 7520 .addImm(NumLPads >> 16)); 7521 } 7522 7523 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::t2CMPrr)) 7524 .addReg(NewVReg1) 7525 .addReg(VReg2)); 7526 } 7527 7528 BuildMI(DispatchBB, dl, TII->get(ARM::t2Bcc)) 7529 .addMBB(TrapBB) 7530 .addImm(ARMCC::HI) 7531 .addReg(ARM::CPSR); 7532 7533 unsigned NewVReg3 = MRI->createVirtualRegister(TRC); 7534 AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::t2LEApcrelJT),NewVReg3) 7535 .addJumpTableIndex(MJTI)); 7536 7537 unsigned NewVReg4 = MRI->createVirtualRegister(TRC); 7538 AddDefaultCC( 7539 AddDefaultPred( 7540 BuildMI(DispContBB, dl, TII->get(ARM::t2ADDrs), NewVReg4) 7541 .addReg(NewVReg3, RegState::Kill) 7542 .addReg(NewVReg1) 7543 .addImm(ARM_AM::getSORegOpc(ARM_AM::lsl, 2)))); 7544 7545 BuildMI(DispContBB, dl, TII->get(ARM::t2BR_JT)) 7546 .addReg(NewVReg4, RegState::Kill) 7547 .addReg(NewVReg1) 7548 .addJumpTableIndex(MJTI); 7549 } else if (Subtarget->isThumb()) { 7550 unsigned NewVReg1 = MRI->createVirtualRegister(TRC); 7551 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::tLDRspi), NewVReg1) 7552 .addFrameIndex(FI) 7553 .addImm(1) 7554 .addMemOperand(FIMMOLd)); 7555 7556 if (NumLPads < 256) { 7557 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::tCMPi8)) 7558 .addReg(NewVReg1) 7559 .addImm(NumLPads)); 7560 } else { 7561 MachineConstantPool *ConstantPool = MF->getConstantPool(); 7562 Type *Int32Ty = Type::getInt32Ty(MF->getFunction()->getContext()); 7563 const Constant *C = ConstantInt::get(Int32Ty, NumLPads); 7564 7565 // MachineConstantPool wants an explicit alignment. 7566 unsigned Align = MF->getDataLayout().getPrefTypeAlignment(Int32Ty); 7567 if (Align == 0) 7568 Align = MF->getDataLayout().getTypeAllocSize(C->getType()); 7569 unsigned Idx = ConstantPool->getConstantPoolIndex(C, Align); 7570 7571 unsigned VReg1 = MRI->createVirtualRegister(TRC); 7572 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::tLDRpci)) 7573 .addReg(VReg1, RegState::Define) 7574 .addConstantPoolIndex(Idx)); 7575 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::tCMPr)) 7576 .addReg(NewVReg1) 7577 .addReg(VReg1)); 7578 } 7579 7580 BuildMI(DispatchBB, dl, TII->get(ARM::tBcc)) 7581 .addMBB(TrapBB) 7582 .addImm(ARMCC::HI) 7583 .addReg(ARM::CPSR); 7584 7585 unsigned NewVReg2 = MRI->createVirtualRegister(TRC); 7586 AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::tLSLri), NewVReg2) 7587 .addReg(ARM::CPSR, RegState::Define) 7588 .addReg(NewVReg1) 7589 .addImm(2)); 7590 7591 unsigned NewVReg3 = MRI->createVirtualRegister(TRC); 7592 AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::tLEApcrelJT), NewVReg3) 7593 .addJumpTableIndex(MJTI)); 7594 7595 unsigned NewVReg4 = MRI->createVirtualRegister(TRC); 7596 AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::tADDrr), NewVReg4) 7597 .addReg(ARM::CPSR, RegState::Define) 7598 .addReg(NewVReg2, RegState::Kill) 7599 .addReg(NewVReg3)); 7600 7601 MachineMemOperand *JTMMOLd = MF->getMachineMemOperand( 7602 MachinePointerInfo::getJumpTable(*MF), MachineMemOperand::MOLoad, 4, 4); 7603 7604 unsigned NewVReg5 = MRI->createVirtualRegister(TRC); 7605 AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::tLDRi), NewVReg5) 7606 .addReg(NewVReg4, RegState::Kill) 7607 .addImm(0) 7608 .addMemOperand(JTMMOLd)); 7609 7610 unsigned NewVReg6 = NewVReg5; 7611 if (IsPositionIndependent) { 7612 NewVReg6 = MRI->createVirtualRegister(TRC); 7613 AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::tADDrr), NewVReg6) 7614 .addReg(ARM::CPSR, RegState::Define) 7615 .addReg(NewVReg5, RegState::Kill) 7616 .addReg(NewVReg3)); 7617 } 7618 7619 BuildMI(DispContBB, dl, TII->get(ARM::tBR_JTr)) 7620 .addReg(NewVReg6, RegState::Kill) 7621 .addJumpTableIndex(MJTI); 7622 } else { 7623 unsigned NewVReg1 = MRI->createVirtualRegister(TRC); 7624 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::LDRi12), NewVReg1) 7625 .addFrameIndex(FI) 7626 .addImm(4) 7627 .addMemOperand(FIMMOLd)); 7628 7629 if (NumLPads < 256) { 7630 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::CMPri)) 7631 .addReg(NewVReg1) 7632 .addImm(NumLPads)); 7633 } else if (Subtarget->hasV6T2Ops() && isUInt<16>(NumLPads)) { 7634 unsigned VReg1 = MRI->createVirtualRegister(TRC); 7635 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::MOVi16), VReg1) 7636 .addImm(NumLPads & 0xFFFF)); 7637 7638 unsigned VReg2 = VReg1; 7639 if ((NumLPads & 0xFFFF0000) != 0) { 7640 VReg2 = MRI->createVirtualRegister(TRC); 7641 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::MOVTi16), VReg2) 7642 .addReg(VReg1) 7643 .addImm(NumLPads >> 16)); 7644 } 7645 7646 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::CMPrr)) 7647 .addReg(NewVReg1) 7648 .addReg(VReg2)); 7649 } else { 7650 MachineConstantPool *ConstantPool = MF->getConstantPool(); 7651 Type *Int32Ty = Type::getInt32Ty(MF->getFunction()->getContext()); 7652 const Constant *C = ConstantInt::get(Int32Ty, NumLPads); 7653 7654 // MachineConstantPool wants an explicit alignment. 7655 unsigned Align = MF->getDataLayout().getPrefTypeAlignment(Int32Ty); 7656 if (Align == 0) 7657 Align = MF->getDataLayout().getTypeAllocSize(C->getType()); 7658 unsigned Idx = ConstantPool->getConstantPoolIndex(C, Align); 7659 7660 unsigned VReg1 = MRI->createVirtualRegister(TRC); 7661 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::LDRcp)) 7662 .addReg(VReg1, RegState::Define) 7663 .addConstantPoolIndex(Idx) 7664 .addImm(0)); 7665 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::CMPrr)) 7666 .addReg(NewVReg1) 7667 .addReg(VReg1, RegState::Kill)); 7668 } 7669 7670 BuildMI(DispatchBB, dl, TII->get(ARM::Bcc)) 7671 .addMBB(TrapBB) 7672 .addImm(ARMCC::HI) 7673 .addReg(ARM::CPSR); 7674 7675 unsigned NewVReg3 = MRI->createVirtualRegister(TRC); 7676 AddDefaultCC( 7677 AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::MOVsi), NewVReg3) 7678 .addReg(NewVReg1) 7679 .addImm(ARM_AM::getSORegOpc(ARM_AM::lsl, 2)))); 7680 unsigned NewVReg4 = MRI->createVirtualRegister(TRC); 7681 AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::LEApcrelJT), NewVReg4) 7682 .addJumpTableIndex(MJTI)); 7683 7684 MachineMemOperand *JTMMOLd = MF->getMachineMemOperand( 7685 MachinePointerInfo::getJumpTable(*MF), MachineMemOperand::MOLoad, 4, 4); 7686 unsigned NewVReg5 = MRI->createVirtualRegister(TRC); 7687 AddDefaultPred( 7688 BuildMI(DispContBB, dl, TII->get(ARM::LDRrs), NewVReg5) 7689 .addReg(NewVReg3, RegState::Kill) 7690 .addReg(NewVReg4) 7691 .addImm(0) 7692 .addMemOperand(JTMMOLd)); 7693 7694 if (IsPositionIndependent) { 7695 BuildMI(DispContBB, dl, TII->get(ARM::BR_JTadd)) 7696 .addReg(NewVReg5, RegState::Kill) 7697 .addReg(NewVReg4) 7698 .addJumpTableIndex(MJTI); 7699 } else { 7700 BuildMI(DispContBB, dl, TII->get(ARM::BR_JTr)) 7701 .addReg(NewVReg5, RegState::Kill) 7702 .addJumpTableIndex(MJTI); 7703 } 7704 } 7705 7706 // Add the jump table entries as successors to the MBB. 7707 SmallPtrSet<MachineBasicBlock*, 8> SeenMBBs; 7708 for (std::vector<MachineBasicBlock*>::iterator 7709 I = LPadList.begin(), E = LPadList.end(); I != E; ++I) { 7710 MachineBasicBlock *CurMBB = *I; 7711 if (SeenMBBs.insert(CurMBB).second) 7712 DispContBB->addSuccessor(CurMBB); 7713 } 7714 7715 // N.B. the order the invoke BBs are processed in doesn't matter here. 7716 const MCPhysReg *SavedRegs = RI.getCalleeSavedRegs(MF); 7717 SmallVector<MachineBasicBlock*, 64> MBBLPads; 7718 for (MachineBasicBlock *BB : InvokeBBs) { 7719 7720 // Remove the landing pad successor from the invoke block and replace it 7721 // with the new dispatch block. 7722 SmallVector<MachineBasicBlock*, 4> Successors(BB->succ_begin(), 7723 BB->succ_end()); 7724 while (!Successors.empty()) { 7725 MachineBasicBlock *SMBB = Successors.pop_back_val(); 7726 if (SMBB->isEHPad()) { 7727 BB->removeSuccessor(SMBB); 7728 MBBLPads.push_back(SMBB); 7729 } 7730 } 7731 7732 BB->addSuccessor(DispatchBB, BranchProbability::getZero()); 7733 BB->normalizeSuccProbs(); 7734 7735 // Find the invoke call and mark all of the callee-saved registers as 7736 // 'implicit defined' so that they're spilled. This prevents code from 7737 // moving instructions to before the EH block, where they will never be 7738 // executed. 7739 for (MachineBasicBlock::reverse_iterator 7740 II = BB->rbegin(), IE = BB->rend(); II != IE; ++II) { 7741 if (!II->isCall()) continue; 7742 7743 DenseMap<unsigned, bool> DefRegs; 7744 for (MachineInstr::mop_iterator 7745 OI = II->operands_begin(), OE = II->operands_end(); 7746 OI != OE; ++OI) { 7747 if (!OI->isReg()) continue; 7748 DefRegs[OI->getReg()] = true; 7749 } 7750 7751 MachineInstrBuilder MIB(*MF, &*II); 7752 7753 for (unsigned i = 0; SavedRegs[i] != 0; ++i) { 7754 unsigned Reg = SavedRegs[i]; 7755 if (Subtarget->isThumb2() && 7756 !ARM::tGPRRegClass.contains(Reg) && 7757 !ARM::hGPRRegClass.contains(Reg)) 7758 continue; 7759 if (Subtarget->isThumb1Only() && !ARM::tGPRRegClass.contains(Reg)) 7760 continue; 7761 if (!Subtarget->isThumb() && !ARM::GPRRegClass.contains(Reg)) 7762 continue; 7763 if (!DefRegs[Reg]) 7764 MIB.addReg(Reg, RegState::ImplicitDefine | RegState::Dead); 7765 } 7766 7767 break; 7768 } 7769 } 7770 7771 // Mark all former landing pads as non-landing pads. The dispatch is the only 7772 // landing pad now. 7773 for (SmallVectorImpl<MachineBasicBlock*>::iterator 7774 I = MBBLPads.begin(), E = MBBLPads.end(); I != E; ++I) 7775 (*I)->setIsEHPad(false); 7776 7777 // The instruction is gone now. 7778 MI->eraseFromParent(); 7779 } 7780 7781 static 7782 MachineBasicBlock *OtherSucc(MachineBasicBlock *MBB, MachineBasicBlock *Succ) { 7783 for (MachineBasicBlock::succ_iterator I = MBB->succ_begin(), 7784 E = MBB->succ_end(); I != E; ++I) 7785 if (*I != Succ) 7786 return *I; 7787 llvm_unreachable("Expecting a BB with two successors!"); 7788 } 7789 7790 /// Return the load opcode for a given load size. If load size >= 8, 7791 /// neon opcode will be returned. 7792 static unsigned getLdOpcode(unsigned LdSize, bool IsThumb1, bool IsThumb2) { 7793 if (LdSize >= 8) 7794 return LdSize == 16 ? ARM::VLD1q32wb_fixed 7795 : LdSize == 8 ? ARM::VLD1d32wb_fixed : 0; 7796 if (IsThumb1) 7797 return LdSize == 4 ? ARM::tLDRi 7798 : LdSize == 2 ? ARM::tLDRHi 7799 : LdSize == 1 ? ARM::tLDRBi : 0; 7800 if (IsThumb2) 7801 return LdSize == 4 ? ARM::t2LDR_POST 7802 : LdSize == 2 ? ARM::t2LDRH_POST 7803 : LdSize == 1 ? ARM::t2LDRB_POST : 0; 7804 return LdSize == 4 ? ARM::LDR_POST_IMM 7805 : LdSize == 2 ? ARM::LDRH_POST 7806 : LdSize == 1 ? ARM::LDRB_POST_IMM : 0; 7807 } 7808 7809 /// Return the store opcode for a given store size. If store size >= 8, 7810 /// neon opcode will be returned. 7811 static unsigned getStOpcode(unsigned StSize, bool IsThumb1, bool IsThumb2) { 7812 if (StSize >= 8) 7813 return StSize == 16 ? ARM::VST1q32wb_fixed 7814 : StSize == 8 ? ARM::VST1d32wb_fixed : 0; 7815 if (IsThumb1) 7816 return StSize == 4 ? ARM::tSTRi 7817 : StSize == 2 ? ARM::tSTRHi 7818 : StSize == 1 ? ARM::tSTRBi : 0; 7819 if (IsThumb2) 7820 return StSize == 4 ? ARM::t2STR_POST 7821 : StSize == 2 ? ARM::t2STRH_POST 7822 : StSize == 1 ? ARM::t2STRB_POST : 0; 7823 return StSize == 4 ? ARM::STR_POST_IMM 7824 : StSize == 2 ? ARM::STRH_POST 7825 : StSize == 1 ? ARM::STRB_POST_IMM : 0; 7826 } 7827 7828 /// Emit a post-increment load operation with given size. The instructions 7829 /// will be added to BB at Pos. 7830 static void emitPostLd(MachineBasicBlock *BB, MachineInstr *Pos, 7831 const TargetInstrInfo *TII, const DebugLoc &dl, 7832 unsigned LdSize, unsigned Data, unsigned AddrIn, 7833 unsigned AddrOut, bool IsThumb1, bool IsThumb2) { 7834 unsigned LdOpc = getLdOpcode(LdSize, IsThumb1, IsThumb2); 7835 assert(LdOpc != 0 && "Should have a load opcode"); 7836 if (LdSize >= 8) { 7837 AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(LdOpc), Data) 7838 .addReg(AddrOut, RegState::Define).addReg(AddrIn) 7839 .addImm(0)); 7840 } else if (IsThumb1) { 7841 // load + update AddrIn 7842 AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(LdOpc), Data) 7843 .addReg(AddrIn).addImm(0)); 7844 MachineInstrBuilder MIB = 7845 BuildMI(*BB, Pos, dl, TII->get(ARM::tADDi8), AddrOut); 7846 MIB = AddDefaultT1CC(MIB); 7847 MIB.addReg(AddrIn).addImm(LdSize); 7848 AddDefaultPred(MIB); 7849 } else if (IsThumb2) { 7850 AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(LdOpc), Data) 7851 .addReg(AddrOut, RegState::Define).addReg(AddrIn) 7852 .addImm(LdSize)); 7853 } else { // arm 7854 AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(LdOpc), Data) 7855 .addReg(AddrOut, RegState::Define).addReg(AddrIn) 7856 .addReg(0).addImm(LdSize)); 7857 } 7858 } 7859 7860 /// Emit a post-increment store operation with given size. The instructions 7861 /// will be added to BB at Pos. 7862 static void emitPostSt(MachineBasicBlock *BB, MachineInstr *Pos, 7863 const TargetInstrInfo *TII, const DebugLoc &dl, 7864 unsigned StSize, unsigned Data, unsigned AddrIn, 7865 unsigned AddrOut, bool IsThumb1, bool IsThumb2) { 7866 unsigned StOpc = getStOpcode(StSize, IsThumb1, IsThumb2); 7867 assert(StOpc != 0 && "Should have a store opcode"); 7868 if (StSize >= 8) { 7869 AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(StOpc), AddrOut) 7870 .addReg(AddrIn).addImm(0).addReg(Data)); 7871 } else if (IsThumb1) { 7872 // store + update AddrIn 7873 AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(StOpc)).addReg(Data) 7874 .addReg(AddrIn).addImm(0)); 7875 MachineInstrBuilder MIB = 7876 BuildMI(*BB, Pos, dl, TII->get(ARM::tADDi8), AddrOut); 7877 MIB = AddDefaultT1CC(MIB); 7878 MIB.addReg(AddrIn).addImm(StSize); 7879 AddDefaultPred(MIB); 7880 } else if (IsThumb2) { 7881 AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(StOpc), AddrOut) 7882 .addReg(Data).addReg(AddrIn).addImm(StSize)); 7883 } else { // arm 7884 AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(StOpc), AddrOut) 7885 .addReg(Data).addReg(AddrIn).addReg(0) 7886 .addImm(StSize)); 7887 } 7888 } 7889 7890 MachineBasicBlock * 7891 ARMTargetLowering::EmitStructByval(MachineInstr *MI, 7892 MachineBasicBlock *BB) const { 7893 // This pseudo instruction has 3 operands: dst, src, size 7894 // We expand it to a loop if size > Subtarget->getMaxInlineSizeThreshold(). 7895 // Otherwise, we will generate unrolled scalar copies. 7896 const TargetInstrInfo *TII = Subtarget->getInstrInfo(); 7897 const BasicBlock *LLVM_BB = BB->getBasicBlock(); 7898 MachineFunction::iterator It = ++BB->getIterator(); 7899 7900 unsigned dest = MI->getOperand(0).getReg(); 7901 unsigned src = MI->getOperand(1).getReg(); 7902 unsigned SizeVal = MI->getOperand(2).getImm(); 7903 unsigned Align = MI->getOperand(3).getImm(); 7904 DebugLoc dl = MI->getDebugLoc(); 7905 7906 MachineFunction *MF = BB->getParent(); 7907 MachineRegisterInfo &MRI = MF->getRegInfo(); 7908 unsigned UnitSize = 0; 7909 const TargetRegisterClass *TRC = nullptr; 7910 const TargetRegisterClass *VecTRC = nullptr; 7911 7912 bool IsThumb1 = Subtarget->isThumb1Only(); 7913 bool IsThumb2 = Subtarget->isThumb2(); 7914 7915 if (Align & 1) { 7916 UnitSize = 1; 7917 } else if (Align & 2) { 7918 UnitSize = 2; 7919 } else { 7920 // Check whether we can use NEON instructions. 7921 if (!MF->getFunction()->hasFnAttribute(Attribute::NoImplicitFloat) && 7922 Subtarget->hasNEON()) { 7923 if ((Align % 16 == 0) && SizeVal >= 16) 7924 UnitSize = 16; 7925 else if ((Align % 8 == 0) && SizeVal >= 8) 7926 UnitSize = 8; 7927 } 7928 // Can't use NEON instructions. 7929 if (UnitSize == 0) 7930 UnitSize = 4; 7931 } 7932 7933 // Select the correct opcode and register class for unit size load/store 7934 bool IsNeon = UnitSize >= 8; 7935 TRC = (IsThumb1 || IsThumb2) ? &ARM::tGPRRegClass : &ARM::GPRRegClass; 7936 if (IsNeon) 7937 VecTRC = UnitSize == 16 ? &ARM::DPairRegClass 7938 : UnitSize == 8 ? &ARM::DPRRegClass 7939 : nullptr; 7940 7941 unsigned BytesLeft = SizeVal % UnitSize; 7942 unsigned LoopSize = SizeVal - BytesLeft; 7943 7944 if (SizeVal <= Subtarget->getMaxInlineSizeThreshold()) { 7945 // Use LDR and STR to copy. 7946 // [scratch, srcOut] = LDR_POST(srcIn, UnitSize) 7947 // [destOut] = STR_POST(scratch, destIn, UnitSize) 7948 unsigned srcIn = src; 7949 unsigned destIn = dest; 7950 for (unsigned i = 0; i < LoopSize; i+=UnitSize) { 7951 unsigned srcOut = MRI.createVirtualRegister(TRC); 7952 unsigned destOut = MRI.createVirtualRegister(TRC); 7953 unsigned scratch = MRI.createVirtualRegister(IsNeon ? VecTRC : TRC); 7954 emitPostLd(BB, MI, TII, dl, UnitSize, scratch, srcIn, srcOut, 7955 IsThumb1, IsThumb2); 7956 emitPostSt(BB, MI, TII, dl, UnitSize, scratch, destIn, destOut, 7957 IsThumb1, IsThumb2); 7958 srcIn = srcOut; 7959 destIn = destOut; 7960 } 7961 7962 // Handle the leftover bytes with LDRB and STRB. 7963 // [scratch, srcOut] = LDRB_POST(srcIn, 1) 7964 // [destOut] = STRB_POST(scratch, destIn, 1) 7965 for (unsigned i = 0; i < BytesLeft; i++) { 7966 unsigned srcOut = MRI.createVirtualRegister(TRC); 7967 unsigned destOut = MRI.createVirtualRegister(TRC); 7968 unsigned scratch = MRI.createVirtualRegister(TRC); 7969 emitPostLd(BB, MI, TII, dl, 1, scratch, srcIn, srcOut, 7970 IsThumb1, IsThumb2); 7971 emitPostSt(BB, MI, TII, dl, 1, scratch, destIn, destOut, 7972 IsThumb1, IsThumb2); 7973 srcIn = srcOut; 7974 destIn = destOut; 7975 } 7976 MI->eraseFromParent(); // The instruction is gone now. 7977 return BB; 7978 } 7979 7980 // Expand the pseudo op to a loop. 7981 // thisMBB: 7982 // ... 7983 // movw varEnd, # --> with thumb2 7984 // movt varEnd, # 7985 // ldrcp varEnd, idx --> without thumb2 7986 // fallthrough --> loopMBB 7987 // loopMBB: 7988 // PHI varPhi, varEnd, varLoop 7989 // PHI srcPhi, src, srcLoop 7990 // PHI destPhi, dst, destLoop 7991 // [scratch, srcLoop] = LDR_POST(srcPhi, UnitSize) 7992 // [destLoop] = STR_POST(scratch, destPhi, UnitSize) 7993 // subs varLoop, varPhi, #UnitSize 7994 // bne loopMBB 7995 // fallthrough --> exitMBB 7996 // exitMBB: 7997 // epilogue to handle left-over bytes 7998 // [scratch, srcOut] = LDRB_POST(srcLoop, 1) 7999 // [destOut] = STRB_POST(scratch, destLoop, 1) 8000 MachineBasicBlock *loopMBB = MF->CreateMachineBasicBlock(LLVM_BB); 8001 MachineBasicBlock *exitMBB = MF->CreateMachineBasicBlock(LLVM_BB); 8002 MF->insert(It, loopMBB); 8003 MF->insert(It, exitMBB); 8004 8005 // Transfer the remainder of BB and its successor edges to exitMBB. 8006 exitMBB->splice(exitMBB->begin(), BB, 8007 std::next(MachineBasicBlock::iterator(MI)), BB->end()); 8008 exitMBB->transferSuccessorsAndUpdatePHIs(BB); 8009 8010 // Load an immediate to varEnd. 8011 unsigned varEnd = MRI.createVirtualRegister(TRC); 8012 if (Subtarget->useMovt(*MF)) { 8013 unsigned Vtmp = varEnd; 8014 if ((LoopSize & 0xFFFF0000) != 0) 8015 Vtmp = MRI.createVirtualRegister(TRC); 8016 AddDefaultPred(BuildMI(BB, dl, 8017 TII->get(IsThumb2 ? ARM::t2MOVi16 : ARM::MOVi16), 8018 Vtmp).addImm(LoopSize & 0xFFFF)); 8019 8020 if ((LoopSize & 0xFFFF0000) != 0) 8021 AddDefaultPred(BuildMI(BB, dl, 8022 TII->get(IsThumb2 ? ARM::t2MOVTi16 : ARM::MOVTi16), 8023 varEnd) 8024 .addReg(Vtmp) 8025 .addImm(LoopSize >> 16)); 8026 } else { 8027 MachineConstantPool *ConstantPool = MF->getConstantPool(); 8028 Type *Int32Ty = Type::getInt32Ty(MF->getFunction()->getContext()); 8029 const Constant *C = ConstantInt::get(Int32Ty, LoopSize); 8030 8031 // MachineConstantPool wants an explicit alignment. 8032 unsigned Align = MF->getDataLayout().getPrefTypeAlignment(Int32Ty); 8033 if (Align == 0) 8034 Align = MF->getDataLayout().getTypeAllocSize(C->getType()); 8035 unsigned Idx = ConstantPool->getConstantPoolIndex(C, Align); 8036 8037 if (IsThumb1) 8038 AddDefaultPred(BuildMI(*BB, MI, dl, TII->get(ARM::tLDRpci)).addReg( 8039 varEnd, RegState::Define).addConstantPoolIndex(Idx)); 8040 else 8041 AddDefaultPred(BuildMI(*BB, MI, dl, TII->get(ARM::LDRcp)).addReg( 8042 varEnd, RegState::Define).addConstantPoolIndex(Idx).addImm(0)); 8043 } 8044 BB->addSuccessor(loopMBB); 8045 8046 // Generate the loop body: 8047 // varPhi = PHI(varLoop, varEnd) 8048 // srcPhi = PHI(srcLoop, src) 8049 // destPhi = PHI(destLoop, dst) 8050 MachineBasicBlock *entryBB = BB; 8051 BB = loopMBB; 8052 unsigned varLoop = MRI.createVirtualRegister(TRC); 8053 unsigned varPhi = MRI.createVirtualRegister(TRC); 8054 unsigned srcLoop = MRI.createVirtualRegister(TRC); 8055 unsigned srcPhi = MRI.createVirtualRegister(TRC); 8056 unsigned destLoop = MRI.createVirtualRegister(TRC); 8057 unsigned destPhi = MRI.createVirtualRegister(TRC); 8058 8059 BuildMI(*BB, BB->begin(), dl, TII->get(ARM::PHI), varPhi) 8060 .addReg(varLoop).addMBB(loopMBB) 8061 .addReg(varEnd).addMBB(entryBB); 8062 BuildMI(BB, dl, TII->get(ARM::PHI), srcPhi) 8063 .addReg(srcLoop).addMBB(loopMBB) 8064 .addReg(src).addMBB(entryBB); 8065 BuildMI(BB, dl, TII->get(ARM::PHI), destPhi) 8066 .addReg(destLoop).addMBB(loopMBB) 8067 .addReg(dest).addMBB(entryBB); 8068 8069 // [scratch, srcLoop] = LDR_POST(srcPhi, UnitSize) 8070 // [destLoop] = STR_POST(scratch, destPhi, UnitSiz) 8071 unsigned scratch = MRI.createVirtualRegister(IsNeon ? VecTRC : TRC); 8072 emitPostLd(BB, BB->end(), TII, dl, UnitSize, scratch, srcPhi, srcLoop, 8073 IsThumb1, IsThumb2); 8074 emitPostSt(BB, BB->end(), TII, dl, UnitSize, scratch, destPhi, destLoop, 8075 IsThumb1, IsThumb2); 8076 8077 // Decrement loop variable by UnitSize. 8078 if (IsThumb1) { 8079 MachineInstrBuilder MIB = 8080 BuildMI(*BB, BB->end(), dl, TII->get(ARM::tSUBi8), varLoop); 8081 MIB = AddDefaultT1CC(MIB); 8082 MIB.addReg(varPhi).addImm(UnitSize); 8083 AddDefaultPred(MIB); 8084 } else { 8085 MachineInstrBuilder MIB = 8086 BuildMI(*BB, BB->end(), dl, 8087 TII->get(IsThumb2 ? ARM::t2SUBri : ARM::SUBri), varLoop); 8088 AddDefaultCC(AddDefaultPred(MIB.addReg(varPhi).addImm(UnitSize))); 8089 MIB->getOperand(5).setReg(ARM::CPSR); 8090 MIB->getOperand(5).setIsDef(true); 8091 } 8092 BuildMI(*BB, BB->end(), dl, 8093 TII->get(IsThumb1 ? ARM::tBcc : IsThumb2 ? ARM::t2Bcc : ARM::Bcc)) 8094 .addMBB(loopMBB).addImm(ARMCC::NE).addReg(ARM::CPSR); 8095 8096 // loopMBB can loop back to loopMBB or fall through to exitMBB. 8097 BB->addSuccessor(loopMBB); 8098 BB->addSuccessor(exitMBB); 8099 8100 // Add epilogue to handle BytesLeft. 8101 BB = exitMBB; 8102 MachineInstr *StartOfExit = exitMBB->begin(); 8103 8104 // [scratch, srcOut] = LDRB_POST(srcLoop, 1) 8105 // [destOut] = STRB_POST(scratch, destLoop, 1) 8106 unsigned srcIn = srcLoop; 8107 unsigned destIn = destLoop; 8108 for (unsigned i = 0; i < BytesLeft; i++) { 8109 unsigned srcOut = MRI.createVirtualRegister(TRC); 8110 unsigned destOut = MRI.createVirtualRegister(TRC); 8111 unsigned scratch = MRI.createVirtualRegister(TRC); 8112 emitPostLd(BB, StartOfExit, TII, dl, 1, scratch, srcIn, srcOut, 8113 IsThumb1, IsThumb2); 8114 emitPostSt(BB, StartOfExit, TII, dl, 1, scratch, destIn, destOut, 8115 IsThumb1, IsThumb2); 8116 srcIn = srcOut; 8117 destIn = destOut; 8118 } 8119 8120 MI->eraseFromParent(); // The instruction is gone now. 8121 return BB; 8122 } 8123 8124 MachineBasicBlock * 8125 ARMTargetLowering::EmitLowered__chkstk(MachineInstr *MI, 8126 MachineBasicBlock *MBB) const { 8127 const TargetMachine &TM = getTargetMachine(); 8128 const TargetInstrInfo &TII = *Subtarget->getInstrInfo(); 8129 DebugLoc DL = MI->getDebugLoc(); 8130 8131 assert(Subtarget->isTargetWindows() && 8132 "__chkstk is only supported on Windows"); 8133 assert(Subtarget->isThumb2() && "Windows on ARM requires Thumb-2 mode"); 8134 8135 // __chkstk takes the number of words to allocate on the stack in R4, and 8136 // returns the stack adjustment in number of bytes in R4. This will not 8137 // clober any other registers (other than the obvious lr). 8138 // 8139 // Although, technically, IP should be considered a register which may be 8140 // clobbered, the call itself will not touch it. Windows on ARM is a pure 8141 // thumb-2 environment, so there is no interworking required. As a result, we 8142 // do not expect a veneer to be emitted by the linker, clobbering IP. 8143 // 8144 // Each module receives its own copy of __chkstk, so no import thunk is 8145 // required, again, ensuring that IP is not clobbered. 8146 // 8147 // Finally, although some linkers may theoretically provide a trampoline for 8148 // out of range calls (which is quite common due to a 32M range limitation of 8149 // branches for Thumb), we can generate the long-call version via 8150 // -mcmodel=large, alleviating the need for the trampoline which may clobber 8151 // IP. 8152 8153 switch (TM.getCodeModel()) { 8154 case CodeModel::Small: 8155 case CodeModel::Medium: 8156 case CodeModel::Default: 8157 case CodeModel::Kernel: 8158 BuildMI(*MBB, MI, DL, TII.get(ARM::tBL)) 8159 .addImm((unsigned)ARMCC::AL).addReg(0) 8160 .addExternalSymbol("__chkstk") 8161 .addReg(ARM::R4, RegState::Implicit | RegState::Kill) 8162 .addReg(ARM::R4, RegState::Implicit | RegState::Define) 8163 .addReg(ARM::R12, RegState::Implicit | RegState::Define | RegState::Dead); 8164 break; 8165 case CodeModel::Large: 8166 case CodeModel::JITDefault: { 8167 MachineRegisterInfo &MRI = MBB->getParent()->getRegInfo(); 8168 unsigned Reg = MRI.createVirtualRegister(&ARM::rGPRRegClass); 8169 8170 BuildMI(*MBB, MI, DL, TII.get(ARM::t2MOVi32imm), Reg) 8171 .addExternalSymbol("__chkstk"); 8172 BuildMI(*MBB, MI, DL, TII.get(ARM::tBLXr)) 8173 .addImm((unsigned)ARMCC::AL).addReg(0) 8174 .addReg(Reg, RegState::Kill) 8175 .addReg(ARM::R4, RegState::Implicit | RegState::Kill) 8176 .addReg(ARM::R4, RegState::Implicit | RegState::Define) 8177 .addReg(ARM::R12, RegState::Implicit | RegState::Define | RegState::Dead); 8178 break; 8179 } 8180 } 8181 8182 AddDefaultCC(AddDefaultPred(BuildMI(*MBB, MI, DL, TII.get(ARM::t2SUBrr), 8183 ARM::SP) 8184 .addReg(ARM::SP, RegState::Kill) 8185 .addReg(ARM::R4, RegState::Kill) 8186 .setMIFlags(MachineInstr::FrameSetup))); 8187 8188 MI->eraseFromParent(); 8189 return MBB; 8190 } 8191 8192 MachineBasicBlock * 8193 ARMTargetLowering::EmitLowered__dbzchk(MachineInstr *MI, 8194 MachineBasicBlock *MBB) const { 8195 DebugLoc DL = MI->getDebugLoc(); 8196 MachineFunction *MF = MBB->getParent(); 8197 const TargetInstrInfo *TII = Subtarget->getInstrInfo(); 8198 8199 MachineBasicBlock *ContBB = MF->CreateMachineBasicBlock(); 8200 MF->insert(++MBB->getIterator(), ContBB); 8201 ContBB->splice(ContBB->begin(), MBB, 8202 std::next(MachineBasicBlock::iterator(MI)), MBB->end()); 8203 ContBB->transferSuccessorsAndUpdatePHIs(MBB); 8204 8205 MachineBasicBlock *TrapBB = MF->CreateMachineBasicBlock(); 8206 MF->push_back(TrapBB); 8207 BuildMI(TrapBB, DL, TII->get(ARM::t2UDF)).addImm(249); 8208 MBB->addSuccessor(TrapBB); 8209 8210 BuildMI(*MBB, MI, DL, TII->get(ARM::tCBZ)) 8211 .addReg(MI->getOperand(0).getReg()) 8212 .addMBB(TrapBB); 8213 AddDefaultPred(BuildMI(*MBB, MI, DL, TII->get(ARM::t2B)).addMBB(ContBB)); 8214 MBB->addSuccessor(ContBB); 8215 8216 MI->eraseFromParent(); 8217 return ContBB; 8218 } 8219 8220 MachineBasicBlock * 8221 ARMTargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI, 8222 MachineBasicBlock *BB) const { 8223 const TargetInstrInfo *TII = Subtarget->getInstrInfo(); 8224 DebugLoc dl = MI->getDebugLoc(); 8225 bool isThumb2 = Subtarget->isThumb2(); 8226 switch (MI->getOpcode()) { 8227 default: { 8228 MI->dump(); 8229 llvm_unreachable("Unexpected instr type to insert"); 8230 } 8231 // The Thumb2 pre-indexed stores have the same MI operands, they just 8232 // define them differently in the .td files from the isel patterns, so 8233 // they need pseudos. 8234 case ARM::t2STR_preidx: 8235 MI->setDesc(TII->get(ARM::t2STR_PRE)); 8236 return BB; 8237 case ARM::t2STRB_preidx: 8238 MI->setDesc(TII->get(ARM::t2STRB_PRE)); 8239 return BB; 8240 case ARM::t2STRH_preidx: 8241 MI->setDesc(TII->get(ARM::t2STRH_PRE)); 8242 return BB; 8243 8244 case ARM::STRi_preidx: 8245 case ARM::STRBi_preidx: { 8246 unsigned NewOpc = MI->getOpcode() == ARM::STRi_preidx ? 8247 ARM::STR_PRE_IMM : ARM::STRB_PRE_IMM; 8248 // Decode the offset. 8249 unsigned Offset = MI->getOperand(4).getImm(); 8250 bool isSub = ARM_AM::getAM2Op(Offset) == ARM_AM::sub; 8251 Offset = ARM_AM::getAM2Offset(Offset); 8252 if (isSub) 8253 Offset = -Offset; 8254 8255 MachineMemOperand *MMO = *MI->memoperands_begin(); 8256 BuildMI(*BB, MI, dl, TII->get(NewOpc)) 8257 .addOperand(MI->getOperand(0)) // Rn_wb 8258 .addOperand(MI->getOperand(1)) // Rt 8259 .addOperand(MI->getOperand(2)) // Rn 8260 .addImm(Offset) // offset (skip GPR==zero_reg) 8261 .addOperand(MI->getOperand(5)) // pred 8262 .addOperand(MI->getOperand(6)) 8263 .addMemOperand(MMO); 8264 MI->eraseFromParent(); 8265 return BB; 8266 } 8267 case ARM::STRr_preidx: 8268 case ARM::STRBr_preidx: 8269 case ARM::STRH_preidx: { 8270 unsigned NewOpc; 8271 switch (MI->getOpcode()) { 8272 default: llvm_unreachable("unexpected opcode!"); 8273 case ARM::STRr_preidx: NewOpc = ARM::STR_PRE_REG; break; 8274 case ARM::STRBr_preidx: NewOpc = ARM::STRB_PRE_REG; break; 8275 case ARM::STRH_preidx: NewOpc = ARM::STRH_PRE; break; 8276 } 8277 MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(NewOpc)); 8278 for (unsigned i = 0; i < MI->getNumOperands(); ++i) 8279 MIB.addOperand(MI->getOperand(i)); 8280 MI->eraseFromParent(); 8281 return BB; 8282 } 8283 8284 case ARM::tMOVCCr_pseudo: { 8285 // To "insert" a SELECT_CC instruction, we actually have to insert the 8286 // diamond control-flow pattern. The incoming instruction knows the 8287 // destination vreg to set, the condition code register to branch on, the 8288 // true/false values to select between, and a branch opcode to use. 8289 const BasicBlock *LLVM_BB = BB->getBasicBlock(); 8290 MachineFunction::iterator It = ++BB->getIterator(); 8291 8292 // thisMBB: 8293 // ... 8294 // TrueVal = ... 8295 // cmpTY ccX, r1, r2 8296 // bCC copy1MBB 8297 // fallthrough --> copy0MBB 8298 MachineBasicBlock *thisMBB = BB; 8299 MachineFunction *F = BB->getParent(); 8300 MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB); 8301 MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB); 8302 F->insert(It, copy0MBB); 8303 F->insert(It, sinkMBB); 8304 8305 // Transfer the remainder of BB and its successor edges to sinkMBB. 8306 sinkMBB->splice(sinkMBB->begin(), BB, 8307 std::next(MachineBasicBlock::iterator(MI)), BB->end()); 8308 sinkMBB->transferSuccessorsAndUpdatePHIs(BB); 8309 8310 BB->addSuccessor(copy0MBB); 8311 BB->addSuccessor(sinkMBB); 8312 8313 BuildMI(BB, dl, TII->get(ARM::tBcc)).addMBB(sinkMBB) 8314 .addImm(MI->getOperand(3).getImm()).addReg(MI->getOperand(4).getReg()); 8315 8316 // copy0MBB: 8317 // %FalseValue = ... 8318 // # fallthrough to sinkMBB 8319 BB = copy0MBB; 8320 8321 // Update machine-CFG edges 8322 BB->addSuccessor(sinkMBB); 8323 8324 // sinkMBB: 8325 // %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ] 8326 // ... 8327 BB = sinkMBB; 8328 BuildMI(*BB, BB->begin(), dl, 8329 TII->get(ARM::PHI), MI->getOperand(0).getReg()) 8330 .addReg(MI->getOperand(1).getReg()).addMBB(copy0MBB) 8331 .addReg(MI->getOperand(2).getReg()).addMBB(thisMBB); 8332 8333 MI->eraseFromParent(); // The pseudo instruction is gone now. 8334 return BB; 8335 } 8336 8337 case ARM::BCCi64: 8338 case ARM::BCCZi64: { 8339 // If there is an unconditional branch to the other successor, remove it. 8340 BB->erase(std::next(MachineBasicBlock::iterator(MI)), BB->end()); 8341 8342 // Compare both parts that make up the double comparison separately for 8343 // equality. 8344 bool RHSisZero = MI->getOpcode() == ARM::BCCZi64; 8345 8346 unsigned LHS1 = MI->getOperand(1).getReg(); 8347 unsigned LHS2 = MI->getOperand(2).getReg(); 8348 if (RHSisZero) { 8349 AddDefaultPred(BuildMI(BB, dl, 8350 TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri)) 8351 .addReg(LHS1).addImm(0)); 8352 BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri)) 8353 .addReg(LHS2).addImm(0) 8354 .addImm(ARMCC::EQ).addReg(ARM::CPSR); 8355 } else { 8356 unsigned RHS1 = MI->getOperand(3).getReg(); 8357 unsigned RHS2 = MI->getOperand(4).getReg(); 8358 AddDefaultPred(BuildMI(BB, dl, 8359 TII->get(isThumb2 ? ARM::t2CMPrr : ARM::CMPrr)) 8360 .addReg(LHS1).addReg(RHS1)); 8361 BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPrr : ARM::CMPrr)) 8362 .addReg(LHS2).addReg(RHS2) 8363 .addImm(ARMCC::EQ).addReg(ARM::CPSR); 8364 } 8365 8366 MachineBasicBlock *destMBB = MI->getOperand(RHSisZero ? 3 : 5).getMBB(); 8367 MachineBasicBlock *exitMBB = OtherSucc(BB, destMBB); 8368 if (MI->getOperand(0).getImm() == ARMCC::NE) 8369 std::swap(destMBB, exitMBB); 8370 8371 BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc)) 8372 .addMBB(destMBB).addImm(ARMCC::EQ).addReg(ARM::CPSR); 8373 if (isThumb2) 8374 AddDefaultPred(BuildMI(BB, dl, TII->get(ARM::t2B)).addMBB(exitMBB)); 8375 else 8376 BuildMI(BB, dl, TII->get(ARM::B)) .addMBB(exitMBB); 8377 8378 MI->eraseFromParent(); // The pseudo instruction is gone now. 8379 return BB; 8380 } 8381 8382 case ARM::Int_eh_sjlj_setjmp: 8383 case ARM::Int_eh_sjlj_setjmp_nofp: 8384 case ARM::tInt_eh_sjlj_setjmp: 8385 case ARM::t2Int_eh_sjlj_setjmp: 8386 case ARM::t2Int_eh_sjlj_setjmp_nofp: 8387 return BB; 8388 8389 case ARM::Int_eh_sjlj_setup_dispatch: 8390 EmitSjLjDispatchBlock(MI, BB); 8391 return BB; 8392 8393 case ARM::ABS: 8394 case ARM::t2ABS: { 8395 // To insert an ABS instruction, we have to insert the 8396 // diamond control-flow pattern. The incoming instruction knows the 8397 // source vreg to test against 0, the destination vreg to set, 8398 // the condition code register to branch on, the 8399 // true/false values to select between, and a branch opcode to use. 8400 // It transforms 8401 // V1 = ABS V0 8402 // into 8403 // V2 = MOVS V0 8404 // BCC (branch to SinkBB if V0 >= 0) 8405 // RSBBB: V3 = RSBri V2, 0 (compute ABS if V2 < 0) 8406 // SinkBB: V1 = PHI(V2, V3) 8407 const BasicBlock *LLVM_BB = BB->getBasicBlock(); 8408 MachineFunction::iterator BBI = ++BB->getIterator(); 8409 MachineFunction *Fn = BB->getParent(); 8410 MachineBasicBlock *RSBBB = Fn->CreateMachineBasicBlock(LLVM_BB); 8411 MachineBasicBlock *SinkBB = Fn->CreateMachineBasicBlock(LLVM_BB); 8412 Fn->insert(BBI, RSBBB); 8413 Fn->insert(BBI, SinkBB); 8414 8415 unsigned int ABSSrcReg = MI->getOperand(1).getReg(); 8416 unsigned int ABSDstReg = MI->getOperand(0).getReg(); 8417 bool ABSSrcKIll = MI->getOperand(1).isKill(); 8418 bool isThumb2 = Subtarget->isThumb2(); 8419 MachineRegisterInfo &MRI = Fn->getRegInfo(); 8420 // In Thumb mode S must not be specified if source register is the SP or 8421 // PC and if destination register is the SP, so restrict register class 8422 unsigned NewRsbDstReg = 8423 MRI.createVirtualRegister(isThumb2 ? &ARM::rGPRRegClass : &ARM::GPRRegClass); 8424 8425 // Transfer the remainder of BB and its successor edges to sinkMBB. 8426 SinkBB->splice(SinkBB->begin(), BB, 8427 std::next(MachineBasicBlock::iterator(MI)), BB->end()); 8428 SinkBB->transferSuccessorsAndUpdatePHIs(BB); 8429 8430 BB->addSuccessor(RSBBB); 8431 BB->addSuccessor(SinkBB); 8432 8433 // fall through to SinkMBB 8434 RSBBB->addSuccessor(SinkBB); 8435 8436 // insert a cmp at the end of BB 8437 AddDefaultPred(BuildMI(BB, dl, 8438 TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri)) 8439 .addReg(ABSSrcReg).addImm(0)); 8440 8441 // insert a bcc with opposite CC to ARMCC::MI at the end of BB 8442 BuildMI(BB, dl, 8443 TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc)).addMBB(SinkBB) 8444 .addImm(ARMCC::getOppositeCondition(ARMCC::MI)).addReg(ARM::CPSR); 8445 8446 // insert rsbri in RSBBB 8447 // Note: BCC and rsbri will be converted into predicated rsbmi 8448 // by if-conversion pass 8449 BuildMI(*RSBBB, RSBBB->begin(), dl, 8450 TII->get(isThumb2 ? ARM::t2RSBri : ARM::RSBri), NewRsbDstReg) 8451 .addReg(ABSSrcReg, ABSSrcKIll ? RegState::Kill : 0) 8452 .addImm(0).addImm((unsigned)ARMCC::AL).addReg(0).addReg(0); 8453 8454 // insert PHI in SinkBB, 8455 // reuse ABSDstReg to not change uses of ABS instruction 8456 BuildMI(*SinkBB, SinkBB->begin(), dl, 8457 TII->get(ARM::PHI), ABSDstReg) 8458 .addReg(NewRsbDstReg).addMBB(RSBBB) 8459 .addReg(ABSSrcReg).addMBB(BB); 8460 8461 // remove ABS instruction 8462 MI->eraseFromParent(); 8463 8464 // return last added BB 8465 return SinkBB; 8466 } 8467 case ARM::COPY_STRUCT_BYVAL_I32: 8468 ++NumLoopByVals; 8469 return EmitStructByval(MI, BB); 8470 case ARM::WIN__CHKSTK: 8471 return EmitLowered__chkstk(MI, BB); 8472 case ARM::WIN__DBZCHK: 8473 return EmitLowered__dbzchk(MI, BB); 8474 } 8475 } 8476 8477 /// \brief Attaches vregs to MEMCPY that it will use as scratch registers 8478 /// when it is expanded into LDM/STM. This is done as a post-isel lowering 8479 /// instead of as a custom inserter because we need the use list from the SDNode. 8480 static void attachMEMCPYScratchRegs(const ARMSubtarget *Subtarget, 8481 MachineInstr *MI, const SDNode *Node) { 8482 bool isThumb1 = Subtarget->isThumb1Only(); 8483 8484 DebugLoc DL = MI->getDebugLoc(); 8485 MachineFunction *MF = MI->getParent()->getParent(); 8486 MachineRegisterInfo &MRI = MF->getRegInfo(); 8487 MachineInstrBuilder MIB(*MF, MI); 8488 8489 // If the new dst/src is unused mark it as dead. 8490 if (!Node->hasAnyUseOfValue(0)) { 8491 MI->getOperand(0).setIsDead(true); 8492 } 8493 if (!Node->hasAnyUseOfValue(1)) { 8494 MI->getOperand(1).setIsDead(true); 8495 } 8496 8497 // The MEMCPY both defines and kills the scratch registers. 8498 for (unsigned I = 0; I != MI->getOperand(4).getImm(); ++I) { 8499 unsigned TmpReg = MRI.createVirtualRegister(isThumb1 ? &ARM::tGPRRegClass 8500 : &ARM::GPRRegClass); 8501 MIB.addReg(TmpReg, RegState::Define|RegState::Dead); 8502 } 8503 } 8504 8505 void ARMTargetLowering::AdjustInstrPostInstrSelection(MachineInstr *MI, 8506 SDNode *Node) const { 8507 if (MI->getOpcode() == ARM::MEMCPY) { 8508 attachMEMCPYScratchRegs(Subtarget, MI, Node); 8509 return; 8510 } 8511 8512 const MCInstrDesc *MCID = &MI->getDesc(); 8513 // Adjust potentially 's' setting instructions after isel, i.e. ADC, SBC, RSB, 8514 // RSC. Coming out of isel, they have an implicit CPSR def, but the optional 8515 // operand is still set to noreg. If needed, set the optional operand's 8516 // register to CPSR, and remove the redundant implicit def. 8517 // 8518 // e.g. ADCS (..., CPSR<imp-def>) -> ADC (... opt:CPSR<def>). 8519 8520 // Rename pseudo opcodes. 8521 unsigned NewOpc = convertAddSubFlagsOpcode(MI->getOpcode()); 8522 if (NewOpc) { 8523 const ARMBaseInstrInfo *TII = Subtarget->getInstrInfo(); 8524 MCID = &TII->get(NewOpc); 8525 8526 assert(MCID->getNumOperands() == MI->getDesc().getNumOperands() + 1 && 8527 "converted opcode should be the same except for cc_out"); 8528 8529 MI->setDesc(*MCID); 8530 8531 // Add the optional cc_out operand 8532 MI->addOperand(MachineOperand::CreateReg(0, /*isDef=*/true)); 8533 } 8534 unsigned ccOutIdx = MCID->getNumOperands() - 1; 8535 8536 // Any ARM instruction that sets the 's' bit should specify an optional 8537 // "cc_out" operand in the last operand position. 8538 if (!MI->hasOptionalDef() || !MCID->OpInfo[ccOutIdx].isOptionalDef()) { 8539 assert(!NewOpc && "Optional cc_out operand required"); 8540 return; 8541 } 8542 // Look for an implicit def of CPSR added by MachineInstr ctor. Remove it 8543 // since we already have an optional CPSR def. 8544 bool definesCPSR = false; 8545 bool deadCPSR = false; 8546 for (unsigned i = MCID->getNumOperands(), e = MI->getNumOperands(); 8547 i != e; ++i) { 8548 const MachineOperand &MO = MI->getOperand(i); 8549 if (MO.isReg() && MO.isDef() && MO.getReg() == ARM::CPSR) { 8550 definesCPSR = true; 8551 if (MO.isDead()) 8552 deadCPSR = true; 8553 MI->RemoveOperand(i); 8554 break; 8555 } 8556 } 8557 if (!definesCPSR) { 8558 assert(!NewOpc && "Optional cc_out operand required"); 8559 return; 8560 } 8561 assert(deadCPSR == !Node->hasAnyUseOfValue(1) && "inconsistent dead flag"); 8562 if (deadCPSR) { 8563 assert(!MI->getOperand(ccOutIdx).getReg() && 8564 "expect uninitialized optional cc_out operand"); 8565 return; 8566 } 8567 8568 // If this instruction was defined with an optional CPSR def and its dag node 8569 // had a live implicit CPSR def, then activate the optional CPSR def. 8570 MachineOperand &MO = MI->getOperand(ccOutIdx); 8571 MO.setReg(ARM::CPSR); 8572 MO.setIsDef(true); 8573 } 8574 8575 //===----------------------------------------------------------------------===// 8576 // ARM Optimization Hooks 8577 //===----------------------------------------------------------------------===// 8578 8579 // Helper function that checks if N is a null or all ones constant. 8580 static inline bool isZeroOrAllOnes(SDValue N, bool AllOnes) { 8581 return AllOnes ? isAllOnesConstant(N) : isNullConstant(N); 8582 } 8583 8584 // Return true if N is conditionally 0 or all ones. 8585 // Detects these expressions where cc is an i1 value: 8586 // 8587 // (select cc 0, y) [AllOnes=0] 8588 // (select cc y, 0) [AllOnes=0] 8589 // (zext cc) [AllOnes=0] 8590 // (sext cc) [AllOnes=0/1] 8591 // (select cc -1, y) [AllOnes=1] 8592 // (select cc y, -1) [AllOnes=1] 8593 // 8594 // Invert is set when N is the null/all ones constant when CC is false. 8595 // OtherOp is set to the alternative value of N. 8596 static bool isConditionalZeroOrAllOnes(SDNode *N, bool AllOnes, 8597 SDValue &CC, bool &Invert, 8598 SDValue &OtherOp, 8599 SelectionDAG &DAG) { 8600 switch (N->getOpcode()) { 8601 default: return false; 8602 case ISD::SELECT: { 8603 CC = N->getOperand(0); 8604 SDValue N1 = N->getOperand(1); 8605 SDValue N2 = N->getOperand(2); 8606 if (isZeroOrAllOnes(N1, AllOnes)) { 8607 Invert = false; 8608 OtherOp = N2; 8609 return true; 8610 } 8611 if (isZeroOrAllOnes(N2, AllOnes)) { 8612 Invert = true; 8613 OtherOp = N1; 8614 return true; 8615 } 8616 return false; 8617 } 8618 case ISD::ZERO_EXTEND: 8619 // (zext cc) can never be the all ones value. 8620 if (AllOnes) 8621 return false; 8622 // Fall through. 8623 case ISD::SIGN_EXTEND: { 8624 SDLoc dl(N); 8625 EVT VT = N->getValueType(0); 8626 CC = N->getOperand(0); 8627 if (CC.getValueType() != MVT::i1) 8628 return false; 8629 Invert = !AllOnes; 8630 if (AllOnes) 8631 // When looking for an AllOnes constant, N is an sext, and the 'other' 8632 // value is 0. 8633 OtherOp = DAG.getConstant(0, dl, VT); 8634 else if (N->getOpcode() == ISD::ZERO_EXTEND) 8635 // When looking for a 0 constant, N can be zext or sext. 8636 OtherOp = DAG.getConstant(1, dl, VT); 8637 else 8638 OtherOp = DAG.getConstant(APInt::getAllOnesValue(VT.getSizeInBits()), dl, 8639 VT); 8640 return true; 8641 } 8642 } 8643 } 8644 8645 // Combine a constant select operand into its use: 8646 // 8647 // (add (select cc, 0, c), x) -> (select cc, x, (add, x, c)) 8648 // (sub x, (select cc, 0, c)) -> (select cc, x, (sub, x, c)) 8649 // (and (select cc, -1, c), x) -> (select cc, x, (and, x, c)) [AllOnes=1] 8650 // (or (select cc, 0, c), x) -> (select cc, x, (or, x, c)) 8651 // (xor (select cc, 0, c), x) -> (select cc, x, (xor, x, c)) 8652 // 8653 // The transform is rejected if the select doesn't have a constant operand that 8654 // is null, or all ones when AllOnes is set. 8655 // 8656 // Also recognize sext/zext from i1: 8657 // 8658 // (add (zext cc), x) -> (select cc (add x, 1), x) 8659 // (add (sext cc), x) -> (select cc (add x, -1), x) 8660 // 8661 // These transformations eventually create predicated instructions. 8662 // 8663 // @param N The node to transform. 8664 // @param Slct The N operand that is a select. 8665 // @param OtherOp The other N operand (x above). 8666 // @param DCI Context. 8667 // @param AllOnes Require the select constant to be all ones instead of null. 8668 // @returns The new node, or SDValue() on failure. 8669 static 8670 SDValue combineSelectAndUse(SDNode *N, SDValue Slct, SDValue OtherOp, 8671 TargetLowering::DAGCombinerInfo &DCI, 8672 bool AllOnes = false) { 8673 SelectionDAG &DAG = DCI.DAG; 8674 EVT VT = N->getValueType(0); 8675 SDValue NonConstantVal; 8676 SDValue CCOp; 8677 bool SwapSelectOps; 8678 if (!isConditionalZeroOrAllOnes(Slct.getNode(), AllOnes, CCOp, SwapSelectOps, 8679 NonConstantVal, DAG)) 8680 return SDValue(); 8681 8682 // Slct is now know to be the desired identity constant when CC is true. 8683 SDValue TrueVal = OtherOp; 8684 SDValue FalseVal = DAG.getNode(N->getOpcode(), SDLoc(N), VT, 8685 OtherOp, NonConstantVal); 8686 // Unless SwapSelectOps says CC should be false. 8687 if (SwapSelectOps) 8688 std::swap(TrueVal, FalseVal); 8689 8690 return DAG.getNode(ISD::SELECT, SDLoc(N), VT, 8691 CCOp, TrueVal, FalseVal); 8692 } 8693 8694 // Attempt combineSelectAndUse on each operand of a commutative operator N. 8695 static 8696 SDValue combineSelectAndUseCommutative(SDNode *N, bool AllOnes, 8697 TargetLowering::DAGCombinerInfo &DCI) { 8698 SDValue N0 = N->getOperand(0); 8699 SDValue N1 = N->getOperand(1); 8700 if (N0.getNode()->hasOneUse()) 8701 if (SDValue Result = combineSelectAndUse(N, N0, N1, DCI, AllOnes)) 8702 return Result; 8703 if (N1.getNode()->hasOneUse()) 8704 if (SDValue Result = combineSelectAndUse(N, N1, N0, DCI, AllOnes)) 8705 return Result; 8706 return SDValue(); 8707 } 8708 8709 // AddCombineToVPADDL- For pair-wise add on neon, use the vpaddl instruction 8710 // (only after legalization). 8711 static SDValue AddCombineToVPADDL(SDNode *N, SDValue N0, SDValue N1, 8712 TargetLowering::DAGCombinerInfo &DCI, 8713 const ARMSubtarget *Subtarget) { 8714 8715 // Only perform optimization if after legalize, and if NEON is available. We 8716 // also expected both operands to be BUILD_VECTORs. 8717 if (DCI.isBeforeLegalize() || !Subtarget->hasNEON() 8718 || N0.getOpcode() != ISD::BUILD_VECTOR 8719 || N1.getOpcode() != ISD::BUILD_VECTOR) 8720 return SDValue(); 8721 8722 // Check output type since VPADDL operand elements can only be 8, 16, or 32. 8723 EVT VT = N->getValueType(0); 8724 if (!VT.isInteger() || VT.getVectorElementType() == MVT::i64) 8725 return SDValue(); 8726 8727 // Check that the vector operands are of the right form. 8728 // N0 and N1 are BUILD_VECTOR nodes with N number of EXTRACT_VECTOR 8729 // operands, where N is the size of the formed vector. 8730 // Each EXTRACT_VECTOR should have the same input vector and odd or even 8731 // index such that we have a pair wise add pattern. 8732 8733 // Grab the vector that all EXTRACT_VECTOR nodes should be referencing. 8734 if (N0->getOperand(0)->getOpcode() != ISD::EXTRACT_VECTOR_ELT) 8735 return SDValue(); 8736 SDValue Vec = N0->getOperand(0)->getOperand(0); 8737 SDNode *V = Vec.getNode(); 8738 unsigned nextIndex = 0; 8739 8740 // For each operands to the ADD which are BUILD_VECTORs, 8741 // check to see if each of their operands are an EXTRACT_VECTOR with 8742 // the same vector and appropriate index. 8743 for (unsigned i = 0, e = N0->getNumOperands(); i != e; ++i) { 8744 if (N0->getOperand(i)->getOpcode() == ISD::EXTRACT_VECTOR_ELT 8745 && N1->getOperand(i)->getOpcode() == ISD::EXTRACT_VECTOR_ELT) { 8746 8747 SDValue ExtVec0 = N0->getOperand(i); 8748 SDValue ExtVec1 = N1->getOperand(i); 8749 8750 // First operand is the vector, verify its the same. 8751 if (V != ExtVec0->getOperand(0).getNode() || 8752 V != ExtVec1->getOperand(0).getNode()) 8753 return SDValue(); 8754 8755 // Second is the constant, verify its correct. 8756 ConstantSDNode *C0 = dyn_cast<ConstantSDNode>(ExtVec0->getOperand(1)); 8757 ConstantSDNode *C1 = dyn_cast<ConstantSDNode>(ExtVec1->getOperand(1)); 8758 8759 // For the constant, we want to see all the even or all the odd. 8760 if (!C0 || !C1 || C0->getZExtValue() != nextIndex 8761 || C1->getZExtValue() != nextIndex+1) 8762 return SDValue(); 8763 8764 // Increment index. 8765 nextIndex+=2; 8766 } else 8767 return SDValue(); 8768 } 8769 8770 // Create VPADDL node. 8771 SelectionDAG &DAG = DCI.DAG; 8772 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 8773 8774 SDLoc dl(N); 8775 8776 // Build operand list. 8777 SmallVector<SDValue, 8> Ops; 8778 Ops.push_back(DAG.getConstant(Intrinsic::arm_neon_vpaddls, dl, 8779 TLI.getPointerTy(DAG.getDataLayout()))); 8780 8781 // Input is the vector. 8782 Ops.push_back(Vec); 8783 8784 // Get widened type and narrowed type. 8785 MVT widenType; 8786 unsigned numElem = VT.getVectorNumElements(); 8787 8788 EVT inputLaneType = Vec.getValueType().getVectorElementType(); 8789 switch (inputLaneType.getSimpleVT().SimpleTy) { 8790 case MVT::i8: widenType = MVT::getVectorVT(MVT::i16, numElem); break; 8791 case MVT::i16: widenType = MVT::getVectorVT(MVT::i32, numElem); break; 8792 case MVT::i32: widenType = MVT::getVectorVT(MVT::i64, numElem); break; 8793 default: 8794 llvm_unreachable("Invalid vector element type for padd optimization."); 8795 } 8796 8797 SDValue tmp = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, widenType, Ops); 8798 unsigned ExtOp = VT.bitsGT(tmp.getValueType()) ? ISD::ANY_EXTEND : ISD::TRUNCATE; 8799 return DAG.getNode(ExtOp, dl, VT, tmp); 8800 } 8801 8802 static SDValue findMUL_LOHI(SDValue V) { 8803 if (V->getOpcode() == ISD::UMUL_LOHI || 8804 V->getOpcode() == ISD::SMUL_LOHI) 8805 return V; 8806 return SDValue(); 8807 } 8808 8809 static SDValue AddCombineTo64bitMLAL(SDNode *AddcNode, 8810 TargetLowering::DAGCombinerInfo &DCI, 8811 const ARMSubtarget *Subtarget) { 8812 8813 // Look for multiply add opportunities. 8814 // The pattern is a ISD::UMUL_LOHI followed by two add nodes, where 8815 // each add nodes consumes a value from ISD::UMUL_LOHI and there is 8816 // a glue link from the first add to the second add. 8817 // If we find this pattern, we can replace the U/SMUL_LOHI, ADDC, and ADDE by 8818 // a S/UMLAL instruction. 8819 // UMUL_LOHI 8820 // / :lo \ :hi 8821 // / \ [no multiline comment] 8822 // loAdd -> ADDE | 8823 // \ :glue / 8824 // \ / 8825 // ADDC <- hiAdd 8826 // 8827 assert(AddcNode->getOpcode() == ISD::ADDC && "Expect an ADDC"); 8828 SDValue AddcOp0 = AddcNode->getOperand(0); 8829 SDValue AddcOp1 = AddcNode->getOperand(1); 8830 8831 // Check if the two operands are from the same mul_lohi node. 8832 if (AddcOp0.getNode() == AddcOp1.getNode()) 8833 return SDValue(); 8834 8835 assert(AddcNode->getNumValues() == 2 && 8836 AddcNode->getValueType(0) == MVT::i32 && 8837 "Expect ADDC with two result values. First: i32"); 8838 8839 // Check that we have a glued ADDC node. 8840 if (AddcNode->getValueType(1) != MVT::Glue) 8841 return SDValue(); 8842 8843 // Check that the ADDC adds the low result of the S/UMUL_LOHI. 8844 if (AddcOp0->getOpcode() != ISD::UMUL_LOHI && 8845 AddcOp0->getOpcode() != ISD::SMUL_LOHI && 8846 AddcOp1->getOpcode() != ISD::UMUL_LOHI && 8847 AddcOp1->getOpcode() != ISD::SMUL_LOHI) 8848 return SDValue(); 8849 8850 // Look for the glued ADDE. 8851 SDNode* AddeNode = AddcNode->getGluedUser(); 8852 if (!AddeNode) 8853 return SDValue(); 8854 8855 // Make sure it is really an ADDE. 8856 if (AddeNode->getOpcode() != ISD::ADDE) 8857 return SDValue(); 8858 8859 assert(AddeNode->getNumOperands() == 3 && 8860 AddeNode->getOperand(2).getValueType() == MVT::Glue && 8861 "ADDE node has the wrong inputs"); 8862 8863 // Check for the triangle shape. 8864 SDValue AddeOp0 = AddeNode->getOperand(0); 8865 SDValue AddeOp1 = AddeNode->getOperand(1); 8866 8867 // Make sure that the ADDE operands are not coming from the same node. 8868 if (AddeOp0.getNode() == AddeOp1.getNode()) 8869 return SDValue(); 8870 8871 // Find the MUL_LOHI node walking up ADDE's operands. 8872 bool IsLeftOperandMUL = false; 8873 SDValue MULOp = findMUL_LOHI(AddeOp0); 8874 if (MULOp == SDValue()) 8875 MULOp = findMUL_LOHI(AddeOp1); 8876 else 8877 IsLeftOperandMUL = true; 8878 if (MULOp == SDValue()) 8879 return SDValue(); 8880 8881 // Figure out the right opcode. 8882 unsigned Opc = MULOp->getOpcode(); 8883 unsigned FinalOpc = (Opc == ISD::SMUL_LOHI) ? ARMISD::SMLAL : ARMISD::UMLAL; 8884 8885 // Figure out the high and low input values to the MLAL node. 8886 SDValue* HiAdd = nullptr; 8887 SDValue* LoMul = nullptr; 8888 SDValue* LowAdd = nullptr; 8889 8890 // Ensure that ADDE is from high result of ISD::SMUL_LOHI. 8891 if ((AddeOp0 != MULOp.getValue(1)) && (AddeOp1 != MULOp.getValue(1))) 8892 return SDValue(); 8893 8894 if (IsLeftOperandMUL) 8895 HiAdd = &AddeOp1; 8896 else 8897 HiAdd = &AddeOp0; 8898 8899 8900 // Ensure that LoMul and LowAdd are taken from correct ISD::SMUL_LOHI node 8901 // whose low result is fed to the ADDC we are checking. 8902 8903 if (AddcOp0 == MULOp.getValue(0)) { 8904 LoMul = &AddcOp0; 8905 LowAdd = &AddcOp1; 8906 } 8907 if (AddcOp1 == MULOp.getValue(0)) { 8908 LoMul = &AddcOp1; 8909 LowAdd = &AddcOp0; 8910 } 8911 8912 if (!LoMul) 8913 return SDValue(); 8914 8915 // Create the merged node. 8916 SelectionDAG &DAG = DCI.DAG; 8917 8918 // Build operand list. 8919 SmallVector<SDValue, 8> Ops; 8920 Ops.push_back(LoMul->getOperand(0)); 8921 Ops.push_back(LoMul->getOperand(1)); 8922 Ops.push_back(*LowAdd); 8923 Ops.push_back(*HiAdd); 8924 8925 SDValue MLALNode = DAG.getNode(FinalOpc, SDLoc(AddcNode), 8926 DAG.getVTList(MVT::i32, MVT::i32), Ops); 8927 8928 // Replace the ADDs' nodes uses by the MLA node's values. 8929 SDValue HiMLALResult(MLALNode.getNode(), 1); 8930 DAG.ReplaceAllUsesOfValueWith(SDValue(AddeNode, 0), HiMLALResult); 8931 8932 SDValue LoMLALResult(MLALNode.getNode(), 0); 8933 DAG.ReplaceAllUsesOfValueWith(SDValue(AddcNode, 0), LoMLALResult); 8934 8935 // Return original node to notify the driver to stop replacing. 8936 SDValue resNode(AddcNode, 0); 8937 return resNode; 8938 } 8939 8940 static SDValue AddCombineTo64bitUMAAL(SDNode *AddcNode, 8941 TargetLowering::DAGCombinerInfo &DCI, 8942 const ARMSubtarget *Subtarget) { 8943 // UMAAL is similar to UMLAL except that it adds two unsigned values. 8944 // While trying to combine for the other MLAL nodes, first search for the 8945 // chance to use UMAAL. Check if Addc uses another addc node which can first 8946 // be combined into a UMLAL. The other pattern is AddcNode being combined 8947 // into an UMLAL and then using another addc is handled in ISelDAGToDAG. 8948 8949 if (!Subtarget->hasV6Ops()) 8950 return AddCombineTo64bitMLAL(AddcNode, DCI, Subtarget); 8951 8952 SDNode *PrevAddc = nullptr; 8953 if (AddcNode->getOperand(0).getOpcode() == ISD::ADDC) 8954 PrevAddc = AddcNode->getOperand(0).getNode(); 8955 else if (AddcNode->getOperand(1).getOpcode() == ISD::ADDC) 8956 PrevAddc = AddcNode->getOperand(1).getNode(); 8957 8958 // If there's no addc chains, just return a search for any MLAL. 8959 if (PrevAddc == nullptr) 8960 return AddCombineTo64bitMLAL(AddcNode, DCI, Subtarget); 8961 8962 // Try to convert the addc operand to an MLAL and if that fails try to 8963 // combine AddcNode. 8964 SDValue MLAL = AddCombineTo64bitMLAL(PrevAddc, DCI, Subtarget); 8965 if (MLAL != SDValue(PrevAddc, 0)) 8966 return AddCombineTo64bitMLAL(AddcNode, DCI, Subtarget); 8967 8968 // Find the converted UMAAL or quit if it doesn't exist. 8969 SDNode *UmlalNode = nullptr; 8970 SDValue AddHi; 8971 if (AddcNode->getOperand(0).getOpcode() == ARMISD::UMLAL) { 8972 UmlalNode = AddcNode->getOperand(0).getNode(); 8973 AddHi = AddcNode->getOperand(1); 8974 } else if (AddcNode->getOperand(1).getOpcode() == ARMISD::UMLAL) { 8975 UmlalNode = AddcNode->getOperand(1).getNode(); 8976 AddHi = AddcNode->getOperand(0); 8977 } else { 8978 return SDValue(); 8979 } 8980 8981 // The ADDC should be glued to an ADDE node, which uses the same UMLAL as 8982 // the ADDC as well as Zero. 8983 auto *Zero = dyn_cast<ConstantSDNode>(UmlalNode->getOperand(3)); 8984 8985 if (!Zero || Zero->getZExtValue() != 0) 8986 return SDValue(); 8987 8988 // Check that we have a glued ADDC node. 8989 if (AddcNode->getValueType(1) != MVT::Glue) 8990 return SDValue(); 8991 8992 // Look for the glued ADDE. 8993 SDNode* AddeNode = AddcNode->getGluedUser(); 8994 if (!AddeNode) 8995 return SDValue(); 8996 8997 if ((AddeNode->getOperand(0).getNode() == Zero && 8998 AddeNode->getOperand(1).getNode() == UmlalNode) || 8999 (AddeNode->getOperand(0).getNode() == UmlalNode && 9000 AddeNode->getOperand(1).getNode() == Zero)) { 9001 9002 SelectionDAG &DAG = DCI.DAG; 9003 SDValue Ops[] = { UmlalNode->getOperand(0), UmlalNode->getOperand(1), 9004 UmlalNode->getOperand(2), AddHi }; 9005 SDValue UMAAL = DAG.getNode(ARMISD::UMAAL, SDLoc(AddcNode), 9006 DAG.getVTList(MVT::i32, MVT::i32), Ops); 9007 9008 // Replace the ADDs' nodes uses by the UMAAL node's values. 9009 DAG.ReplaceAllUsesOfValueWith(SDValue(AddeNode, 0), SDValue(UMAAL.getNode(), 1)); 9010 DAG.ReplaceAllUsesOfValueWith(SDValue(AddcNode, 0), SDValue(UMAAL.getNode(), 0)); 9011 9012 // Return original node to notify the driver to stop replacing. 9013 return SDValue(AddcNode, 0); 9014 } 9015 return SDValue(); 9016 } 9017 9018 /// PerformADDCCombine - Target-specific dag combine transform from 9019 /// ISD::ADDC, ISD::ADDE, and ISD::MUL_LOHI to MLAL or 9020 /// ISD::ADDC, ISD::ADDE and ARMISD::UMLAL to ARMISD::UMAAL 9021 static SDValue PerformADDCCombine(SDNode *N, 9022 TargetLowering::DAGCombinerInfo &DCI, 9023 const ARMSubtarget *Subtarget) { 9024 9025 if (Subtarget->isThumb1Only()) return SDValue(); 9026 9027 // Only perform the checks after legalize when the pattern is available. 9028 if (DCI.isBeforeLegalize()) return SDValue(); 9029 9030 return AddCombineTo64bitUMAAL(N, DCI, Subtarget); 9031 } 9032 9033 /// PerformADDCombineWithOperands - Try DAG combinations for an ADD with 9034 /// operands N0 and N1. This is a helper for PerformADDCombine that is 9035 /// called with the default operands, and if that fails, with commuted 9036 /// operands. 9037 static SDValue PerformADDCombineWithOperands(SDNode *N, SDValue N0, SDValue N1, 9038 TargetLowering::DAGCombinerInfo &DCI, 9039 const ARMSubtarget *Subtarget){ 9040 9041 // Attempt to create vpaddl for this add. 9042 if (SDValue Result = AddCombineToVPADDL(N, N0, N1, DCI, Subtarget)) 9043 return Result; 9044 9045 // fold (add (select cc, 0, c), x) -> (select cc, x, (add, x, c)) 9046 if (N0.getNode()->hasOneUse()) 9047 if (SDValue Result = combineSelectAndUse(N, N0, N1, DCI)) 9048 return Result; 9049 return SDValue(); 9050 } 9051 9052 /// PerformADDCombine - Target-specific dag combine xforms for ISD::ADD. 9053 /// 9054 static SDValue PerformADDCombine(SDNode *N, 9055 TargetLowering::DAGCombinerInfo &DCI, 9056 const ARMSubtarget *Subtarget) { 9057 SDValue N0 = N->getOperand(0); 9058 SDValue N1 = N->getOperand(1); 9059 9060 // First try with the default operand order. 9061 if (SDValue Result = PerformADDCombineWithOperands(N, N0, N1, DCI, Subtarget)) 9062 return Result; 9063 9064 // If that didn't work, try again with the operands commuted. 9065 return PerformADDCombineWithOperands(N, N1, N0, DCI, Subtarget); 9066 } 9067 9068 /// PerformSUBCombine - Target-specific dag combine xforms for ISD::SUB. 9069 /// 9070 static SDValue PerformSUBCombine(SDNode *N, 9071 TargetLowering::DAGCombinerInfo &DCI) { 9072 SDValue N0 = N->getOperand(0); 9073 SDValue N1 = N->getOperand(1); 9074 9075 // fold (sub x, (select cc, 0, c)) -> (select cc, x, (sub, x, c)) 9076 if (N1.getNode()->hasOneUse()) 9077 if (SDValue Result = combineSelectAndUse(N, N1, N0, DCI)) 9078 return Result; 9079 9080 return SDValue(); 9081 } 9082 9083 /// PerformVMULCombine 9084 /// Distribute (A + B) * C to (A * C) + (B * C) to take advantage of the 9085 /// special multiplier accumulator forwarding. 9086 /// vmul d3, d0, d2 9087 /// vmla d3, d1, d2 9088 /// is faster than 9089 /// vadd d3, d0, d1 9090 /// vmul d3, d3, d2 9091 // However, for (A + B) * (A + B), 9092 // vadd d2, d0, d1 9093 // vmul d3, d0, d2 9094 // vmla d3, d1, d2 9095 // is slower than 9096 // vadd d2, d0, d1 9097 // vmul d3, d2, d2 9098 static SDValue PerformVMULCombine(SDNode *N, 9099 TargetLowering::DAGCombinerInfo &DCI, 9100 const ARMSubtarget *Subtarget) { 9101 if (!Subtarget->hasVMLxForwarding()) 9102 return SDValue(); 9103 9104 SelectionDAG &DAG = DCI.DAG; 9105 SDValue N0 = N->getOperand(0); 9106 SDValue N1 = N->getOperand(1); 9107 unsigned Opcode = N0.getOpcode(); 9108 if (Opcode != ISD::ADD && Opcode != ISD::SUB && 9109 Opcode != ISD::FADD && Opcode != ISD::FSUB) { 9110 Opcode = N1.getOpcode(); 9111 if (Opcode != ISD::ADD && Opcode != ISD::SUB && 9112 Opcode != ISD::FADD && Opcode != ISD::FSUB) 9113 return SDValue(); 9114 std::swap(N0, N1); 9115 } 9116 9117 if (N0 == N1) 9118 return SDValue(); 9119 9120 EVT VT = N->getValueType(0); 9121 SDLoc DL(N); 9122 SDValue N00 = N0->getOperand(0); 9123 SDValue N01 = N0->getOperand(1); 9124 return DAG.getNode(Opcode, DL, VT, 9125 DAG.getNode(ISD::MUL, DL, VT, N00, N1), 9126 DAG.getNode(ISD::MUL, DL, VT, N01, N1)); 9127 } 9128 9129 static SDValue PerformMULCombine(SDNode *N, 9130 TargetLowering::DAGCombinerInfo &DCI, 9131 const ARMSubtarget *Subtarget) { 9132 SelectionDAG &DAG = DCI.DAG; 9133 9134 if (Subtarget->isThumb1Only()) 9135 return SDValue(); 9136 9137 if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer()) 9138 return SDValue(); 9139 9140 EVT VT = N->getValueType(0); 9141 if (VT.is64BitVector() || VT.is128BitVector()) 9142 return PerformVMULCombine(N, DCI, Subtarget); 9143 if (VT != MVT::i32) 9144 return SDValue(); 9145 9146 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(1)); 9147 if (!C) 9148 return SDValue(); 9149 9150 int64_t MulAmt = C->getSExtValue(); 9151 unsigned ShiftAmt = countTrailingZeros<uint64_t>(MulAmt); 9152 9153 ShiftAmt = ShiftAmt & (32 - 1); 9154 SDValue V = N->getOperand(0); 9155 SDLoc DL(N); 9156 9157 SDValue Res; 9158 MulAmt >>= ShiftAmt; 9159 9160 if (MulAmt >= 0) { 9161 if (isPowerOf2_32(MulAmt - 1)) { 9162 // (mul x, 2^N + 1) => (add (shl x, N), x) 9163 Res = DAG.getNode(ISD::ADD, DL, VT, 9164 V, 9165 DAG.getNode(ISD::SHL, DL, VT, 9166 V, 9167 DAG.getConstant(Log2_32(MulAmt - 1), DL, 9168 MVT::i32))); 9169 } else if (isPowerOf2_32(MulAmt + 1)) { 9170 // (mul x, 2^N - 1) => (sub (shl x, N), x) 9171 Res = DAG.getNode(ISD::SUB, DL, VT, 9172 DAG.getNode(ISD::SHL, DL, VT, 9173 V, 9174 DAG.getConstant(Log2_32(MulAmt + 1), DL, 9175 MVT::i32)), 9176 V); 9177 } else 9178 return SDValue(); 9179 } else { 9180 uint64_t MulAmtAbs = -MulAmt; 9181 if (isPowerOf2_32(MulAmtAbs + 1)) { 9182 // (mul x, -(2^N - 1)) => (sub x, (shl x, N)) 9183 Res = DAG.getNode(ISD::SUB, DL, VT, 9184 V, 9185 DAG.getNode(ISD::SHL, DL, VT, 9186 V, 9187 DAG.getConstant(Log2_32(MulAmtAbs + 1), DL, 9188 MVT::i32))); 9189 } else if (isPowerOf2_32(MulAmtAbs - 1)) { 9190 // (mul x, -(2^N + 1)) => - (add (shl x, N), x) 9191 Res = DAG.getNode(ISD::ADD, DL, VT, 9192 V, 9193 DAG.getNode(ISD::SHL, DL, VT, 9194 V, 9195 DAG.getConstant(Log2_32(MulAmtAbs - 1), DL, 9196 MVT::i32))); 9197 Res = DAG.getNode(ISD::SUB, DL, VT, 9198 DAG.getConstant(0, DL, MVT::i32), Res); 9199 9200 } else 9201 return SDValue(); 9202 } 9203 9204 if (ShiftAmt != 0) 9205 Res = DAG.getNode(ISD::SHL, DL, VT, 9206 Res, DAG.getConstant(ShiftAmt, DL, MVT::i32)); 9207 9208 // Do not add new nodes to DAG combiner worklist. 9209 DCI.CombineTo(N, Res, false); 9210 return SDValue(); 9211 } 9212 9213 static SDValue PerformANDCombine(SDNode *N, 9214 TargetLowering::DAGCombinerInfo &DCI, 9215 const ARMSubtarget *Subtarget) { 9216 9217 // Attempt to use immediate-form VBIC 9218 BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(N->getOperand(1)); 9219 SDLoc dl(N); 9220 EVT VT = N->getValueType(0); 9221 SelectionDAG &DAG = DCI.DAG; 9222 9223 if(!DAG.getTargetLoweringInfo().isTypeLegal(VT)) 9224 return SDValue(); 9225 9226 APInt SplatBits, SplatUndef; 9227 unsigned SplatBitSize; 9228 bool HasAnyUndefs; 9229 if (BVN && 9230 BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs)) { 9231 if (SplatBitSize <= 64) { 9232 EVT VbicVT; 9233 SDValue Val = isNEONModifiedImm((~SplatBits).getZExtValue(), 9234 SplatUndef.getZExtValue(), SplatBitSize, 9235 DAG, dl, VbicVT, VT.is128BitVector(), 9236 OtherModImm); 9237 if (Val.getNode()) { 9238 SDValue Input = 9239 DAG.getNode(ISD::BITCAST, dl, VbicVT, N->getOperand(0)); 9240 SDValue Vbic = DAG.getNode(ARMISD::VBICIMM, dl, VbicVT, Input, Val); 9241 return DAG.getNode(ISD::BITCAST, dl, VT, Vbic); 9242 } 9243 } 9244 } 9245 9246 if (!Subtarget->isThumb1Only()) { 9247 // fold (and (select cc, -1, c), x) -> (select cc, x, (and, x, c)) 9248 if (SDValue Result = combineSelectAndUseCommutative(N, true, DCI)) 9249 return Result; 9250 } 9251 9252 return SDValue(); 9253 } 9254 9255 /// PerformORCombine - Target-specific dag combine xforms for ISD::OR 9256 static SDValue PerformORCombine(SDNode *N, 9257 TargetLowering::DAGCombinerInfo &DCI, 9258 const ARMSubtarget *Subtarget) { 9259 // Attempt to use immediate-form VORR 9260 BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(N->getOperand(1)); 9261 SDLoc dl(N); 9262 EVT VT = N->getValueType(0); 9263 SelectionDAG &DAG = DCI.DAG; 9264 9265 if(!DAG.getTargetLoweringInfo().isTypeLegal(VT)) 9266 return SDValue(); 9267 9268 APInt SplatBits, SplatUndef; 9269 unsigned SplatBitSize; 9270 bool HasAnyUndefs; 9271 if (BVN && Subtarget->hasNEON() && 9272 BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs)) { 9273 if (SplatBitSize <= 64) { 9274 EVT VorrVT; 9275 SDValue Val = isNEONModifiedImm(SplatBits.getZExtValue(), 9276 SplatUndef.getZExtValue(), SplatBitSize, 9277 DAG, dl, VorrVT, VT.is128BitVector(), 9278 OtherModImm); 9279 if (Val.getNode()) { 9280 SDValue Input = 9281 DAG.getNode(ISD::BITCAST, dl, VorrVT, N->getOperand(0)); 9282 SDValue Vorr = DAG.getNode(ARMISD::VORRIMM, dl, VorrVT, Input, Val); 9283 return DAG.getNode(ISD::BITCAST, dl, VT, Vorr); 9284 } 9285 } 9286 } 9287 9288 if (!Subtarget->isThumb1Only()) { 9289 // fold (or (select cc, 0, c), x) -> (select cc, x, (or, x, c)) 9290 if (SDValue Result = combineSelectAndUseCommutative(N, false, DCI)) 9291 return Result; 9292 } 9293 9294 // The code below optimizes (or (and X, Y), Z). 9295 // The AND operand needs to have a single user to make these optimizations 9296 // profitable. 9297 SDValue N0 = N->getOperand(0); 9298 if (N0.getOpcode() != ISD::AND || !N0.hasOneUse()) 9299 return SDValue(); 9300 SDValue N1 = N->getOperand(1); 9301 9302 // (or (and B, A), (and C, ~A)) => (VBSL A, B, C) when A is a constant. 9303 if (Subtarget->hasNEON() && N1.getOpcode() == ISD::AND && VT.isVector() && 9304 DAG.getTargetLoweringInfo().isTypeLegal(VT)) { 9305 APInt SplatUndef; 9306 unsigned SplatBitSize; 9307 bool HasAnyUndefs; 9308 9309 APInt SplatBits0, SplatBits1; 9310 BuildVectorSDNode *BVN0 = dyn_cast<BuildVectorSDNode>(N0->getOperand(1)); 9311 BuildVectorSDNode *BVN1 = dyn_cast<BuildVectorSDNode>(N1->getOperand(1)); 9312 // Ensure that the second operand of both ands are constants 9313 if (BVN0 && BVN0->isConstantSplat(SplatBits0, SplatUndef, SplatBitSize, 9314 HasAnyUndefs) && !HasAnyUndefs) { 9315 if (BVN1 && BVN1->isConstantSplat(SplatBits1, SplatUndef, SplatBitSize, 9316 HasAnyUndefs) && !HasAnyUndefs) { 9317 // Ensure that the bit width of the constants are the same and that 9318 // the splat arguments are logical inverses as per the pattern we 9319 // are trying to simplify. 9320 if (SplatBits0.getBitWidth() == SplatBits1.getBitWidth() && 9321 SplatBits0 == ~SplatBits1) { 9322 // Canonicalize the vector type to make instruction selection 9323 // simpler. 9324 EVT CanonicalVT = VT.is128BitVector() ? MVT::v4i32 : MVT::v2i32; 9325 SDValue Result = DAG.getNode(ARMISD::VBSL, dl, CanonicalVT, 9326 N0->getOperand(1), 9327 N0->getOperand(0), 9328 N1->getOperand(0)); 9329 return DAG.getNode(ISD::BITCAST, dl, VT, Result); 9330 } 9331 } 9332 } 9333 } 9334 9335 // Try to use the ARM/Thumb2 BFI (bitfield insert) instruction when 9336 // reasonable. 9337 9338 // BFI is only available on V6T2+ 9339 if (Subtarget->isThumb1Only() || !Subtarget->hasV6T2Ops()) 9340 return SDValue(); 9341 9342 SDLoc DL(N); 9343 // 1) or (and A, mask), val => ARMbfi A, val, mask 9344 // iff (val & mask) == val 9345 // 9346 // 2) or (and A, mask), (and B, mask2) => ARMbfi A, (lsr B, amt), mask 9347 // 2a) iff isBitFieldInvertedMask(mask) && isBitFieldInvertedMask(~mask2) 9348 // && mask == ~mask2 9349 // 2b) iff isBitFieldInvertedMask(~mask) && isBitFieldInvertedMask(mask2) 9350 // && ~mask == mask2 9351 // (i.e., copy a bitfield value into another bitfield of the same width) 9352 9353 if (VT != MVT::i32) 9354 return SDValue(); 9355 9356 SDValue N00 = N0.getOperand(0); 9357 9358 // The value and the mask need to be constants so we can verify this is 9359 // actually a bitfield set. If the mask is 0xffff, we can do better 9360 // via a movt instruction, so don't use BFI in that case. 9361 SDValue MaskOp = N0.getOperand(1); 9362 ConstantSDNode *MaskC = dyn_cast<ConstantSDNode>(MaskOp); 9363 if (!MaskC) 9364 return SDValue(); 9365 unsigned Mask = MaskC->getZExtValue(); 9366 if (Mask == 0xffff) 9367 return SDValue(); 9368 SDValue Res; 9369 // Case (1): or (and A, mask), val => ARMbfi A, val, mask 9370 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1); 9371 if (N1C) { 9372 unsigned Val = N1C->getZExtValue(); 9373 if ((Val & ~Mask) != Val) 9374 return SDValue(); 9375 9376 if (ARM::isBitFieldInvertedMask(Mask)) { 9377 Val >>= countTrailingZeros(~Mask); 9378 9379 Res = DAG.getNode(ARMISD::BFI, DL, VT, N00, 9380 DAG.getConstant(Val, DL, MVT::i32), 9381 DAG.getConstant(Mask, DL, MVT::i32)); 9382 9383 // Do not add new nodes to DAG combiner worklist. 9384 DCI.CombineTo(N, Res, false); 9385 return SDValue(); 9386 } 9387 } else if (N1.getOpcode() == ISD::AND) { 9388 // case (2) or (and A, mask), (and B, mask2) => ARMbfi A, (lsr B, amt), mask 9389 ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1)); 9390 if (!N11C) 9391 return SDValue(); 9392 unsigned Mask2 = N11C->getZExtValue(); 9393 9394 // Mask and ~Mask2 (or reverse) must be equivalent for the BFI pattern 9395 // as is to match. 9396 if (ARM::isBitFieldInvertedMask(Mask) && 9397 (Mask == ~Mask2)) { 9398 // The pack halfword instruction works better for masks that fit it, 9399 // so use that when it's available. 9400 if (Subtarget->hasT2ExtractPack() && 9401 (Mask == 0xffff || Mask == 0xffff0000)) 9402 return SDValue(); 9403 // 2a 9404 unsigned amt = countTrailingZeros(Mask2); 9405 Res = DAG.getNode(ISD::SRL, DL, VT, N1.getOperand(0), 9406 DAG.getConstant(amt, DL, MVT::i32)); 9407 Res = DAG.getNode(ARMISD::BFI, DL, VT, N00, Res, 9408 DAG.getConstant(Mask, DL, MVT::i32)); 9409 // Do not add new nodes to DAG combiner worklist. 9410 DCI.CombineTo(N, Res, false); 9411 return SDValue(); 9412 } else if (ARM::isBitFieldInvertedMask(~Mask) && 9413 (~Mask == Mask2)) { 9414 // The pack halfword instruction works better for masks that fit it, 9415 // so use that when it's available. 9416 if (Subtarget->hasT2ExtractPack() && 9417 (Mask2 == 0xffff || Mask2 == 0xffff0000)) 9418 return SDValue(); 9419 // 2b 9420 unsigned lsb = countTrailingZeros(Mask); 9421 Res = DAG.getNode(ISD::SRL, DL, VT, N00, 9422 DAG.getConstant(lsb, DL, MVT::i32)); 9423 Res = DAG.getNode(ARMISD::BFI, DL, VT, N1.getOperand(0), Res, 9424 DAG.getConstant(Mask2, DL, MVT::i32)); 9425 // Do not add new nodes to DAG combiner worklist. 9426 DCI.CombineTo(N, Res, false); 9427 return SDValue(); 9428 } 9429 } 9430 9431 if (DAG.MaskedValueIsZero(N1, MaskC->getAPIntValue()) && 9432 N00.getOpcode() == ISD::SHL && isa<ConstantSDNode>(N00.getOperand(1)) && 9433 ARM::isBitFieldInvertedMask(~Mask)) { 9434 // Case (3): or (and (shl A, #shamt), mask), B => ARMbfi B, A, ~mask 9435 // where lsb(mask) == #shamt and masked bits of B are known zero. 9436 SDValue ShAmt = N00.getOperand(1); 9437 unsigned ShAmtC = cast<ConstantSDNode>(ShAmt)->getZExtValue(); 9438 unsigned LSB = countTrailingZeros(Mask); 9439 if (ShAmtC != LSB) 9440 return SDValue(); 9441 9442 Res = DAG.getNode(ARMISD::BFI, DL, VT, N1, N00.getOperand(0), 9443 DAG.getConstant(~Mask, DL, MVT::i32)); 9444 9445 // Do not add new nodes to DAG combiner worklist. 9446 DCI.CombineTo(N, Res, false); 9447 } 9448 9449 return SDValue(); 9450 } 9451 9452 static SDValue PerformXORCombine(SDNode *N, 9453 TargetLowering::DAGCombinerInfo &DCI, 9454 const ARMSubtarget *Subtarget) { 9455 EVT VT = N->getValueType(0); 9456 SelectionDAG &DAG = DCI.DAG; 9457 9458 if(!DAG.getTargetLoweringInfo().isTypeLegal(VT)) 9459 return SDValue(); 9460 9461 if (!Subtarget->isThumb1Only()) { 9462 // fold (xor (select cc, 0, c), x) -> (select cc, x, (xor, x, c)) 9463 if (SDValue Result = combineSelectAndUseCommutative(N, false, DCI)) 9464 return Result; 9465 } 9466 9467 return SDValue(); 9468 } 9469 9470 // ParseBFI - given a BFI instruction in N, extract the "from" value (Rn) and return it, 9471 // and fill in FromMask and ToMask with (consecutive) bits in "from" to be extracted and 9472 // their position in "to" (Rd). 9473 static SDValue ParseBFI(SDNode *N, APInt &ToMask, APInt &FromMask) { 9474 assert(N->getOpcode() == ARMISD::BFI); 9475 9476 SDValue From = N->getOperand(1); 9477 ToMask = ~cast<ConstantSDNode>(N->getOperand(2))->getAPIntValue(); 9478 FromMask = APInt::getLowBitsSet(ToMask.getBitWidth(), ToMask.countPopulation()); 9479 9480 // If the Base came from a SHR #C, we can deduce that it is really testing bit 9481 // #C in the base of the SHR. 9482 if (From->getOpcode() == ISD::SRL && 9483 isa<ConstantSDNode>(From->getOperand(1))) { 9484 APInt Shift = cast<ConstantSDNode>(From->getOperand(1))->getAPIntValue(); 9485 assert(Shift.getLimitedValue() < 32 && "Shift too large!"); 9486 FromMask <<= Shift.getLimitedValue(31); 9487 From = From->getOperand(0); 9488 } 9489 9490 return From; 9491 } 9492 9493 // If A and B contain one contiguous set of bits, does A | B == A . B? 9494 // 9495 // Neither A nor B must be zero. 9496 static bool BitsProperlyConcatenate(const APInt &A, const APInt &B) { 9497 unsigned LastActiveBitInA = A.countTrailingZeros(); 9498 unsigned FirstActiveBitInB = B.getBitWidth() - B.countLeadingZeros() - 1; 9499 return LastActiveBitInA - 1 == FirstActiveBitInB; 9500 } 9501 9502 static SDValue FindBFIToCombineWith(SDNode *N) { 9503 // We have a BFI in N. Follow a possible chain of BFIs and find a BFI it can combine with, 9504 // if one exists. 9505 APInt ToMask, FromMask; 9506 SDValue From = ParseBFI(N, ToMask, FromMask); 9507 SDValue To = N->getOperand(0); 9508 9509 // Now check for a compatible BFI to merge with. We can pass through BFIs that 9510 // aren't compatible, but not if they set the same bit in their destination as 9511 // we do (or that of any BFI we're going to combine with). 9512 SDValue V = To; 9513 APInt CombinedToMask = ToMask; 9514 while (V.getOpcode() == ARMISD::BFI) { 9515 APInt NewToMask, NewFromMask; 9516 SDValue NewFrom = ParseBFI(V.getNode(), NewToMask, NewFromMask); 9517 if (NewFrom != From) { 9518 // This BFI has a different base. Keep going. 9519 CombinedToMask |= NewToMask; 9520 V = V.getOperand(0); 9521 continue; 9522 } 9523 9524 // Do the written bits conflict with any we've seen so far? 9525 if ((NewToMask & CombinedToMask).getBoolValue()) 9526 // Conflicting bits - bail out because going further is unsafe. 9527 return SDValue(); 9528 9529 // Are the new bits contiguous when combined with the old bits? 9530 if (BitsProperlyConcatenate(ToMask, NewToMask) && 9531 BitsProperlyConcatenate(FromMask, NewFromMask)) 9532 return V; 9533 if (BitsProperlyConcatenate(NewToMask, ToMask) && 9534 BitsProperlyConcatenate(NewFromMask, FromMask)) 9535 return V; 9536 9537 // We've seen a write to some bits, so track it. 9538 CombinedToMask |= NewToMask; 9539 // Keep going... 9540 V = V.getOperand(0); 9541 } 9542 9543 return SDValue(); 9544 } 9545 9546 static SDValue PerformBFICombine(SDNode *N, 9547 TargetLowering::DAGCombinerInfo &DCI) { 9548 SDValue N1 = N->getOperand(1); 9549 if (N1.getOpcode() == ISD::AND) { 9550 // (bfi A, (and B, Mask1), Mask2) -> (bfi A, B, Mask2) iff 9551 // the bits being cleared by the AND are not demanded by the BFI. 9552 ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1)); 9553 if (!N11C) 9554 return SDValue(); 9555 unsigned InvMask = cast<ConstantSDNode>(N->getOperand(2))->getZExtValue(); 9556 unsigned LSB = countTrailingZeros(~InvMask); 9557 unsigned Width = (32 - countLeadingZeros(~InvMask)) - LSB; 9558 assert(Width < 9559 static_cast<unsigned>(std::numeric_limits<unsigned>::digits) && 9560 "undefined behavior"); 9561 unsigned Mask = (1u << Width) - 1; 9562 unsigned Mask2 = N11C->getZExtValue(); 9563 if ((Mask & (~Mask2)) == 0) 9564 return DCI.DAG.getNode(ARMISD::BFI, SDLoc(N), N->getValueType(0), 9565 N->getOperand(0), N1.getOperand(0), 9566 N->getOperand(2)); 9567 } else if (N->getOperand(0).getOpcode() == ARMISD::BFI) { 9568 // We have a BFI of a BFI. Walk up the BFI chain to see how long it goes. 9569 // Keep track of any consecutive bits set that all come from the same base 9570 // value. We can combine these together into a single BFI. 9571 SDValue CombineBFI = FindBFIToCombineWith(N); 9572 if (CombineBFI == SDValue()) 9573 return SDValue(); 9574 9575 // We've found a BFI. 9576 APInt ToMask1, FromMask1; 9577 SDValue From1 = ParseBFI(N, ToMask1, FromMask1); 9578 9579 APInt ToMask2, FromMask2; 9580 SDValue From2 = ParseBFI(CombineBFI.getNode(), ToMask2, FromMask2); 9581 assert(From1 == From2); 9582 (void)From2; 9583 9584 // First, unlink CombineBFI. 9585 DCI.DAG.ReplaceAllUsesWith(CombineBFI, CombineBFI.getOperand(0)); 9586 // Then create a new BFI, combining the two together. 9587 APInt NewFromMask = FromMask1 | FromMask2; 9588 APInt NewToMask = ToMask1 | ToMask2; 9589 9590 EVT VT = N->getValueType(0); 9591 SDLoc dl(N); 9592 9593 if (NewFromMask[0] == 0) 9594 From1 = DCI.DAG.getNode( 9595 ISD::SRL, dl, VT, From1, 9596 DCI.DAG.getConstant(NewFromMask.countTrailingZeros(), dl, VT)); 9597 return DCI.DAG.getNode(ARMISD::BFI, dl, VT, N->getOperand(0), From1, 9598 DCI.DAG.getConstant(~NewToMask, dl, VT)); 9599 } 9600 return SDValue(); 9601 } 9602 9603 /// PerformVMOVRRDCombine - Target-specific dag combine xforms for 9604 /// ARMISD::VMOVRRD. 9605 static SDValue PerformVMOVRRDCombine(SDNode *N, 9606 TargetLowering::DAGCombinerInfo &DCI, 9607 const ARMSubtarget *Subtarget) { 9608 // vmovrrd(vmovdrr x, y) -> x,y 9609 SDValue InDouble = N->getOperand(0); 9610 if (InDouble.getOpcode() == ARMISD::VMOVDRR && !Subtarget->isFPOnlySP()) 9611 return DCI.CombineTo(N, InDouble.getOperand(0), InDouble.getOperand(1)); 9612 9613 // vmovrrd(load f64) -> (load i32), (load i32) 9614 SDNode *InNode = InDouble.getNode(); 9615 if (ISD::isNormalLoad(InNode) && InNode->hasOneUse() && 9616 InNode->getValueType(0) == MVT::f64 && 9617 InNode->getOperand(1).getOpcode() == ISD::FrameIndex && 9618 !cast<LoadSDNode>(InNode)->isVolatile()) { 9619 // TODO: Should this be done for non-FrameIndex operands? 9620 LoadSDNode *LD = cast<LoadSDNode>(InNode); 9621 9622 SelectionDAG &DAG = DCI.DAG; 9623 SDLoc DL(LD); 9624 SDValue BasePtr = LD->getBasePtr(); 9625 SDValue NewLD1 = DAG.getLoad(MVT::i32, DL, LD->getChain(), BasePtr, 9626 LD->getPointerInfo(), LD->isVolatile(), 9627 LD->isNonTemporal(), LD->isInvariant(), 9628 LD->getAlignment()); 9629 9630 SDValue OffsetPtr = DAG.getNode(ISD::ADD, DL, MVT::i32, BasePtr, 9631 DAG.getConstant(4, DL, MVT::i32)); 9632 SDValue NewLD2 = DAG.getLoad(MVT::i32, DL, NewLD1.getValue(1), OffsetPtr, 9633 LD->getPointerInfo(), LD->isVolatile(), 9634 LD->isNonTemporal(), LD->isInvariant(), 9635 std::min(4U, LD->getAlignment() / 2)); 9636 9637 DAG.ReplaceAllUsesOfValueWith(SDValue(LD, 1), NewLD2.getValue(1)); 9638 if (DCI.DAG.getDataLayout().isBigEndian()) 9639 std::swap (NewLD1, NewLD2); 9640 SDValue Result = DCI.CombineTo(N, NewLD1, NewLD2); 9641 return Result; 9642 } 9643 9644 return SDValue(); 9645 } 9646 9647 /// PerformVMOVDRRCombine - Target-specific dag combine xforms for 9648 /// ARMISD::VMOVDRR. This is also used for BUILD_VECTORs with 2 operands. 9649 static SDValue PerformVMOVDRRCombine(SDNode *N, SelectionDAG &DAG) { 9650 // N=vmovrrd(X); vmovdrr(N:0, N:1) -> bit_convert(X) 9651 SDValue Op0 = N->getOperand(0); 9652 SDValue Op1 = N->getOperand(1); 9653 if (Op0.getOpcode() == ISD::BITCAST) 9654 Op0 = Op0.getOperand(0); 9655 if (Op1.getOpcode() == ISD::BITCAST) 9656 Op1 = Op1.getOperand(0); 9657 if (Op0.getOpcode() == ARMISD::VMOVRRD && 9658 Op0.getNode() == Op1.getNode() && 9659 Op0.getResNo() == 0 && Op1.getResNo() == 1) 9660 return DAG.getNode(ISD::BITCAST, SDLoc(N), 9661 N->getValueType(0), Op0.getOperand(0)); 9662 return SDValue(); 9663 } 9664 9665 /// hasNormalLoadOperand - Check if any of the operands of a BUILD_VECTOR node 9666 /// are normal, non-volatile loads. If so, it is profitable to bitcast an 9667 /// i64 vector to have f64 elements, since the value can then be loaded 9668 /// directly into a VFP register. 9669 static bool hasNormalLoadOperand(SDNode *N) { 9670 unsigned NumElts = N->getValueType(0).getVectorNumElements(); 9671 for (unsigned i = 0; i < NumElts; ++i) { 9672 SDNode *Elt = N->getOperand(i).getNode(); 9673 if (ISD::isNormalLoad(Elt) && !cast<LoadSDNode>(Elt)->isVolatile()) 9674 return true; 9675 } 9676 return false; 9677 } 9678 9679 /// PerformBUILD_VECTORCombine - Target-specific dag combine xforms for 9680 /// ISD::BUILD_VECTOR. 9681 static SDValue PerformBUILD_VECTORCombine(SDNode *N, 9682 TargetLowering::DAGCombinerInfo &DCI, 9683 const ARMSubtarget *Subtarget) { 9684 // build_vector(N=ARMISD::VMOVRRD(X), N:1) -> bit_convert(X): 9685 // VMOVRRD is introduced when legalizing i64 types. It forces the i64 value 9686 // into a pair of GPRs, which is fine when the value is used as a scalar, 9687 // but if the i64 value is converted to a vector, we need to undo the VMOVRRD. 9688 SelectionDAG &DAG = DCI.DAG; 9689 if (N->getNumOperands() == 2) 9690 if (SDValue RV = PerformVMOVDRRCombine(N, DAG)) 9691 return RV; 9692 9693 // Load i64 elements as f64 values so that type legalization does not split 9694 // them up into i32 values. 9695 EVT VT = N->getValueType(0); 9696 if (VT.getVectorElementType() != MVT::i64 || !hasNormalLoadOperand(N)) 9697 return SDValue(); 9698 SDLoc dl(N); 9699 SmallVector<SDValue, 8> Ops; 9700 unsigned NumElts = VT.getVectorNumElements(); 9701 for (unsigned i = 0; i < NumElts; ++i) { 9702 SDValue V = DAG.getNode(ISD::BITCAST, dl, MVT::f64, N->getOperand(i)); 9703 Ops.push_back(V); 9704 // Make the DAGCombiner fold the bitcast. 9705 DCI.AddToWorklist(V.getNode()); 9706 } 9707 EVT FloatVT = EVT::getVectorVT(*DAG.getContext(), MVT::f64, NumElts); 9708 SDValue BV = DAG.getBuildVector(FloatVT, dl, Ops); 9709 return DAG.getNode(ISD::BITCAST, dl, VT, BV); 9710 } 9711 9712 /// \brief Target-specific dag combine xforms for ARMISD::BUILD_VECTOR. 9713 static SDValue 9714 PerformARMBUILD_VECTORCombine(SDNode *N, TargetLowering::DAGCombinerInfo &DCI) { 9715 // ARMISD::BUILD_VECTOR is introduced when legalizing ISD::BUILD_VECTOR. 9716 // At that time, we may have inserted bitcasts from integer to float. 9717 // If these bitcasts have survived DAGCombine, change the lowering of this 9718 // BUILD_VECTOR in something more vector friendly, i.e., that does not 9719 // force to use floating point types. 9720 9721 // Make sure we can change the type of the vector. 9722 // This is possible iff: 9723 // 1. The vector is only used in a bitcast to a integer type. I.e., 9724 // 1.1. Vector is used only once. 9725 // 1.2. Use is a bit convert to an integer type. 9726 // 2. The size of its operands are 32-bits (64-bits are not legal). 9727 EVT VT = N->getValueType(0); 9728 EVT EltVT = VT.getVectorElementType(); 9729 9730 // Check 1.1. and 2. 9731 if (EltVT.getSizeInBits() != 32 || !N->hasOneUse()) 9732 return SDValue(); 9733 9734 // By construction, the input type must be float. 9735 assert(EltVT == MVT::f32 && "Unexpected type!"); 9736 9737 // Check 1.2. 9738 SDNode *Use = *N->use_begin(); 9739 if (Use->getOpcode() != ISD::BITCAST || 9740 Use->getValueType(0).isFloatingPoint()) 9741 return SDValue(); 9742 9743 // Check profitability. 9744 // Model is, if more than half of the relevant operands are bitcast from 9745 // i32, turn the build_vector into a sequence of insert_vector_elt. 9746 // Relevant operands are everything that is not statically 9747 // (i.e., at compile time) bitcasted. 9748 unsigned NumOfBitCastedElts = 0; 9749 unsigned NumElts = VT.getVectorNumElements(); 9750 unsigned NumOfRelevantElts = NumElts; 9751 for (unsigned Idx = 0; Idx < NumElts; ++Idx) { 9752 SDValue Elt = N->getOperand(Idx); 9753 if (Elt->getOpcode() == ISD::BITCAST) { 9754 // Assume only bit cast to i32 will go away. 9755 if (Elt->getOperand(0).getValueType() == MVT::i32) 9756 ++NumOfBitCastedElts; 9757 } else if (Elt.isUndef() || isa<ConstantSDNode>(Elt)) 9758 // Constants are statically casted, thus do not count them as 9759 // relevant operands. 9760 --NumOfRelevantElts; 9761 } 9762 9763 // Check if more than half of the elements require a non-free bitcast. 9764 if (NumOfBitCastedElts <= NumOfRelevantElts / 2) 9765 return SDValue(); 9766 9767 SelectionDAG &DAG = DCI.DAG; 9768 // Create the new vector type. 9769 EVT VecVT = EVT::getVectorVT(*DAG.getContext(), MVT::i32, NumElts); 9770 // Check if the type is legal. 9771 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 9772 if (!TLI.isTypeLegal(VecVT)) 9773 return SDValue(); 9774 9775 // Combine: 9776 // ARMISD::BUILD_VECTOR E1, E2, ..., EN. 9777 // => BITCAST INSERT_VECTOR_ELT 9778 // (INSERT_VECTOR_ELT (...), (BITCAST EN-1), N-1), 9779 // (BITCAST EN), N. 9780 SDValue Vec = DAG.getUNDEF(VecVT); 9781 SDLoc dl(N); 9782 for (unsigned Idx = 0 ; Idx < NumElts; ++Idx) { 9783 SDValue V = N->getOperand(Idx); 9784 if (V.isUndef()) 9785 continue; 9786 if (V.getOpcode() == ISD::BITCAST && 9787 V->getOperand(0).getValueType() == MVT::i32) 9788 // Fold obvious case. 9789 V = V.getOperand(0); 9790 else { 9791 V = DAG.getNode(ISD::BITCAST, SDLoc(V), MVT::i32, V); 9792 // Make the DAGCombiner fold the bitcasts. 9793 DCI.AddToWorklist(V.getNode()); 9794 } 9795 SDValue LaneIdx = DAG.getConstant(Idx, dl, MVT::i32); 9796 Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VecVT, Vec, V, LaneIdx); 9797 } 9798 Vec = DAG.getNode(ISD::BITCAST, dl, VT, Vec); 9799 // Make the DAGCombiner fold the bitcasts. 9800 DCI.AddToWorklist(Vec.getNode()); 9801 return Vec; 9802 } 9803 9804 /// PerformInsertEltCombine - Target-specific dag combine xforms for 9805 /// ISD::INSERT_VECTOR_ELT. 9806 static SDValue PerformInsertEltCombine(SDNode *N, 9807 TargetLowering::DAGCombinerInfo &DCI) { 9808 // Bitcast an i64 load inserted into a vector to f64. 9809 // Otherwise, the i64 value will be legalized to a pair of i32 values. 9810 EVT VT = N->getValueType(0); 9811 SDNode *Elt = N->getOperand(1).getNode(); 9812 if (VT.getVectorElementType() != MVT::i64 || 9813 !ISD::isNormalLoad(Elt) || cast<LoadSDNode>(Elt)->isVolatile()) 9814 return SDValue(); 9815 9816 SelectionDAG &DAG = DCI.DAG; 9817 SDLoc dl(N); 9818 EVT FloatVT = EVT::getVectorVT(*DAG.getContext(), MVT::f64, 9819 VT.getVectorNumElements()); 9820 SDValue Vec = DAG.getNode(ISD::BITCAST, dl, FloatVT, N->getOperand(0)); 9821 SDValue V = DAG.getNode(ISD::BITCAST, dl, MVT::f64, N->getOperand(1)); 9822 // Make the DAGCombiner fold the bitcasts. 9823 DCI.AddToWorklist(Vec.getNode()); 9824 DCI.AddToWorklist(V.getNode()); 9825 SDValue InsElt = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, FloatVT, 9826 Vec, V, N->getOperand(2)); 9827 return DAG.getNode(ISD::BITCAST, dl, VT, InsElt); 9828 } 9829 9830 /// PerformVECTOR_SHUFFLECombine - Target-specific dag combine xforms for 9831 /// ISD::VECTOR_SHUFFLE. 9832 static SDValue PerformVECTOR_SHUFFLECombine(SDNode *N, SelectionDAG &DAG) { 9833 // The LLVM shufflevector instruction does not require the shuffle mask 9834 // length to match the operand vector length, but ISD::VECTOR_SHUFFLE does 9835 // have that requirement. When translating to ISD::VECTOR_SHUFFLE, if the 9836 // operands do not match the mask length, they are extended by concatenating 9837 // them with undef vectors. That is probably the right thing for other 9838 // targets, but for NEON it is better to concatenate two double-register 9839 // size vector operands into a single quad-register size vector. Do that 9840 // transformation here: 9841 // shuffle(concat(v1, undef), concat(v2, undef)) -> 9842 // shuffle(concat(v1, v2), undef) 9843 SDValue Op0 = N->getOperand(0); 9844 SDValue Op1 = N->getOperand(1); 9845 if (Op0.getOpcode() != ISD::CONCAT_VECTORS || 9846 Op1.getOpcode() != ISD::CONCAT_VECTORS || 9847 Op0.getNumOperands() != 2 || 9848 Op1.getNumOperands() != 2) 9849 return SDValue(); 9850 SDValue Concat0Op1 = Op0.getOperand(1); 9851 SDValue Concat1Op1 = Op1.getOperand(1); 9852 if (!Concat0Op1.isUndef() || !Concat1Op1.isUndef()) 9853 return SDValue(); 9854 // Skip the transformation if any of the types are illegal. 9855 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 9856 EVT VT = N->getValueType(0); 9857 if (!TLI.isTypeLegal(VT) || 9858 !TLI.isTypeLegal(Concat0Op1.getValueType()) || 9859 !TLI.isTypeLegal(Concat1Op1.getValueType())) 9860 return SDValue(); 9861 9862 SDValue NewConcat = DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT, 9863 Op0.getOperand(0), Op1.getOperand(0)); 9864 // Translate the shuffle mask. 9865 SmallVector<int, 16> NewMask; 9866 unsigned NumElts = VT.getVectorNumElements(); 9867 unsigned HalfElts = NumElts/2; 9868 ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N); 9869 for (unsigned n = 0; n < NumElts; ++n) { 9870 int MaskElt = SVN->getMaskElt(n); 9871 int NewElt = -1; 9872 if (MaskElt < (int)HalfElts) 9873 NewElt = MaskElt; 9874 else if (MaskElt >= (int)NumElts && MaskElt < (int)(NumElts + HalfElts)) 9875 NewElt = HalfElts + MaskElt - NumElts; 9876 NewMask.push_back(NewElt); 9877 } 9878 return DAG.getVectorShuffle(VT, SDLoc(N), NewConcat, 9879 DAG.getUNDEF(VT), NewMask.data()); 9880 } 9881 9882 /// CombineBaseUpdate - Target-specific DAG combine function for VLDDUP, 9883 /// NEON load/store intrinsics, and generic vector load/stores, to merge 9884 /// base address updates. 9885 /// For generic load/stores, the memory type is assumed to be a vector. 9886 /// The caller is assumed to have checked legality. 9887 static SDValue CombineBaseUpdate(SDNode *N, 9888 TargetLowering::DAGCombinerInfo &DCI) { 9889 SelectionDAG &DAG = DCI.DAG; 9890 const bool isIntrinsic = (N->getOpcode() == ISD::INTRINSIC_VOID || 9891 N->getOpcode() == ISD::INTRINSIC_W_CHAIN); 9892 const bool isStore = N->getOpcode() == ISD::STORE; 9893 const unsigned AddrOpIdx = ((isIntrinsic || isStore) ? 2 : 1); 9894 SDValue Addr = N->getOperand(AddrOpIdx); 9895 MemSDNode *MemN = cast<MemSDNode>(N); 9896 SDLoc dl(N); 9897 9898 // Search for a use of the address operand that is an increment. 9899 for (SDNode::use_iterator UI = Addr.getNode()->use_begin(), 9900 UE = Addr.getNode()->use_end(); UI != UE; ++UI) { 9901 SDNode *User = *UI; 9902 if (User->getOpcode() != ISD::ADD || 9903 UI.getUse().getResNo() != Addr.getResNo()) 9904 continue; 9905 9906 // Check that the add is independent of the load/store. Otherwise, folding 9907 // it would create a cycle. 9908 if (User->isPredecessorOf(N) || N->isPredecessorOf(User)) 9909 continue; 9910 9911 // Find the new opcode for the updating load/store. 9912 bool isLoadOp = true; 9913 bool isLaneOp = false; 9914 unsigned NewOpc = 0; 9915 unsigned NumVecs = 0; 9916 if (isIntrinsic) { 9917 unsigned IntNo = cast<ConstantSDNode>(N->getOperand(1))->getZExtValue(); 9918 switch (IntNo) { 9919 default: llvm_unreachable("unexpected intrinsic for Neon base update"); 9920 case Intrinsic::arm_neon_vld1: NewOpc = ARMISD::VLD1_UPD; 9921 NumVecs = 1; break; 9922 case Intrinsic::arm_neon_vld2: NewOpc = ARMISD::VLD2_UPD; 9923 NumVecs = 2; break; 9924 case Intrinsic::arm_neon_vld3: NewOpc = ARMISD::VLD3_UPD; 9925 NumVecs = 3; break; 9926 case Intrinsic::arm_neon_vld4: NewOpc = ARMISD::VLD4_UPD; 9927 NumVecs = 4; break; 9928 case Intrinsic::arm_neon_vld2lane: NewOpc = ARMISD::VLD2LN_UPD; 9929 NumVecs = 2; isLaneOp = true; break; 9930 case Intrinsic::arm_neon_vld3lane: NewOpc = ARMISD::VLD3LN_UPD; 9931 NumVecs = 3; isLaneOp = true; break; 9932 case Intrinsic::arm_neon_vld4lane: NewOpc = ARMISD::VLD4LN_UPD; 9933 NumVecs = 4; isLaneOp = true; break; 9934 case Intrinsic::arm_neon_vst1: NewOpc = ARMISD::VST1_UPD; 9935 NumVecs = 1; isLoadOp = false; break; 9936 case Intrinsic::arm_neon_vst2: NewOpc = ARMISD::VST2_UPD; 9937 NumVecs = 2; isLoadOp = false; break; 9938 case Intrinsic::arm_neon_vst3: NewOpc = ARMISD::VST3_UPD; 9939 NumVecs = 3; isLoadOp = false; break; 9940 case Intrinsic::arm_neon_vst4: NewOpc = ARMISD::VST4_UPD; 9941 NumVecs = 4; isLoadOp = false; break; 9942 case Intrinsic::arm_neon_vst2lane: NewOpc = ARMISD::VST2LN_UPD; 9943 NumVecs = 2; isLoadOp = false; isLaneOp = true; break; 9944 case Intrinsic::arm_neon_vst3lane: NewOpc = ARMISD::VST3LN_UPD; 9945 NumVecs = 3; isLoadOp = false; isLaneOp = true; break; 9946 case Intrinsic::arm_neon_vst4lane: NewOpc = ARMISD::VST4LN_UPD; 9947 NumVecs = 4; isLoadOp = false; isLaneOp = true; break; 9948 } 9949 } else { 9950 isLaneOp = true; 9951 switch (N->getOpcode()) { 9952 default: llvm_unreachable("unexpected opcode for Neon base update"); 9953 case ARMISD::VLD2DUP: NewOpc = ARMISD::VLD2DUP_UPD; NumVecs = 2; break; 9954 case ARMISD::VLD3DUP: NewOpc = ARMISD::VLD3DUP_UPD; NumVecs = 3; break; 9955 case ARMISD::VLD4DUP: NewOpc = ARMISD::VLD4DUP_UPD; NumVecs = 4; break; 9956 case ISD::LOAD: NewOpc = ARMISD::VLD1_UPD; 9957 NumVecs = 1; isLaneOp = false; break; 9958 case ISD::STORE: NewOpc = ARMISD::VST1_UPD; 9959 NumVecs = 1; isLaneOp = false; isLoadOp = false; break; 9960 } 9961 } 9962 9963 // Find the size of memory referenced by the load/store. 9964 EVT VecTy; 9965 if (isLoadOp) { 9966 VecTy = N->getValueType(0); 9967 } else if (isIntrinsic) { 9968 VecTy = N->getOperand(AddrOpIdx+1).getValueType(); 9969 } else { 9970 assert(isStore && "Node has to be a load, a store, or an intrinsic!"); 9971 VecTy = N->getOperand(1).getValueType(); 9972 } 9973 9974 unsigned NumBytes = NumVecs * VecTy.getSizeInBits() / 8; 9975 if (isLaneOp) 9976 NumBytes /= VecTy.getVectorNumElements(); 9977 9978 // If the increment is a constant, it must match the memory ref size. 9979 SDValue Inc = User->getOperand(User->getOperand(0) == Addr ? 1 : 0); 9980 if (ConstantSDNode *CInc = dyn_cast<ConstantSDNode>(Inc.getNode())) { 9981 uint64_t IncVal = CInc->getZExtValue(); 9982 if (IncVal != NumBytes) 9983 continue; 9984 } else if (NumBytes >= 3 * 16) { 9985 // VLD3/4 and VST3/4 for 128-bit vectors are implemented with two 9986 // separate instructions that make it harder to use a non-constant update. 9987 continue; 9988 } 9989 9990 // OK, we found an ADD we can fold into the base update. 9991 // Now, create a _UPD node, taking care of not breaking alignment. 9992 9993 EVT AlignedVecTy = VecTy; 9994 unsigned Alignment = MemN->getAlignment(); 9995 9996 // If this is a less-than-standard-aligned load/store, change the type to 9997 // match the standard alignment. 9998 // The alignment is overlooked when selecting _UPD variants; and it's 9999 // easier to introduce bitcasts here than fix that. 10000 // There are 3 ways to get to this base-update combine: 10001 // - intrinsics: they are assumed to be properly aligned (to the standard 10002 // alignment of the memory type), so we don't need to do anything. 10003 // - ARMISD::VLDx nodes: they are only generated from the aforementioned 10004 // intrinsics, so, likewise, there's nothing to do. 10005 // - generic load/store instructions: the alignment is specified as an 10006 // explicit operand, rather than implicitly as the standard alignment 10007 // of the memory type (like the intrisics). We need to change the 10008 // memory type to match the explicit alignment. That way, we don't 10009 // generate non-standard-aligned ARMISD::VLDx nodes. 10010 if (isa<LSBaseSDNode>(N)) { 10011 if (Alignment == 0) 10012 Alignment = 1; 10013 if (Alignment < VecTy.getScalarSizeInBits() / 8) { 10014 MVT EltTy = MVT::getIntegerVT(Alignment * 8); 10015 assert(NumVecs == 1 && "Unexpected multi-element generic load/store."); 10016 assert(!isLaneOp && "Unexpected generic load/store lane."); 10017 unsigned NumElts = NumBytes / (EltTy.getSizeInBits() / 8); 10018 AlignedVecTy = MVT::getVectorVT(EltTy, NumElts); 10019 } 10020 // Don't set an explicit alignment on regular load/stores that we want 10021 // to transform to VLD/VST 1_UPD nodes. 10022 // This matches the behavior of regular load/stores, which only get an 10023 // explicit alignment if the MMO alignment is larger than the standard 10024 // alignment of the memory type. 10025 // Intrinsics, however, always get an explicit alignment, set to the 10026 // alignment of the MMO. 10027 Alignment = 1; 10028 } 10029 10030 // Create the new updating load/store node. 10031 // First, create an SDVTList for the new updating node's results. 10032 EVT Tys[6]; 10033 unsigned NumResultVecs = (isLoadOp ? NumVecs : 0); 10034 unsigned n; 10035 for (n = 0; n < NumResultVecs; ++n) 10036 Tys[n] = AlignedVecTy; 10037 Tys[n++] = MVT::i32; 10038 Tys[n] = MVT::Other; 10039 SDVTList SDTys = DAG.getVTList(makeArrayRef(Tys, NumResultVecs+2)); 10040 10041 // Then, gather the new node's operands. 10042 SmallVector<SDValue, 8> Ops; 10043 Ops.push_back(N->getOperand(0)); // incoming chain 10044 Ops.push_back(N->getOperand(AddrOpIdx)); 10045 Ops.push_back(Inc); 10046 10047 if (StoreSDNode *StN = dyn_cast<StoreSDNode>(N)) { 10048 // Try to match the intrinsic's signature 10049 Ops.push_back(StN->getValue()); 10050 } else { 10051 // Loads (and of course intrinsics) match the intrinsics' signature, 10052 // so just add all but the alignment operand. 10053 for (unsigned i = AddrOpIdx + 1; i < N->getNumOperands() - 1; ++i) 10054 Ops.push_back(N->getOperand(i)); 10055 } 10056 10057 // For all node types, the alignment operand is always the last one. 10058 Ops.push_back(DAG.getConstant(Alignment, dl, MVT::i32)); 10059 10060 // If this is a non-standard-aligned STORE, the penultimate operand is the 10061 // stored value. Bitcast it to the aligned type. 10062 if (AlignedVecTy != VecTy && N->getOpcode() == ISD::STORE) { 10063 SDValue &StVal = Ops[Ops.size()-2]; 10064 StVal = DAG.getNode(ISD::BITCAST, dl, AlignedVecTy, StVal); 10065 } 10066 10067 SDValue UpdN = DAG.getMemIntrinsicNode(NewOpc, dl, SDTys, 10068 Ops, AlignedVecTy, 10069 MemN->getMemOperand()); 10070 10071 // Update the uses. 10072 SmallVector<SDValue, 5> NewResults; 10073 for (unsigned i = 0; i < NumResultVecs; ++i) 10074 NewResults.push_back(SDValue(UpdN.getNode(), i)); 10075 10076 // If this is an non-standard-aligned LOAD, the first result is the loaded 10077 // value. Bitcast it to the expected result type. 10078 if (AlignedVecTy != VecTy && N->getOpcode() == ISD::LOAD) { 10079 SDValue &LdVal = NewResults[0]; 10080 LdVal = DAG.getNode(ISD::BITCAST, dl, VecTy, LdVal); 10081 } 10082 10083 NewResults.push_back(SDValue(UpdN.getNode(), NumResultVecs+1)); // chain 10084 DCI.CombineTo(N, NewResults); 10085 DCI.CombineTo(User, SDValue(UpdN.getNode(), NumResultVecs)); 10086 10087 break; 10088 } 10089 return SDValue(); 10090 } 10091 10092 static SDValue PerformVLDCombine(SDNode *N, 10093 TargetLowering::DAGCombinerInfo &DCI) { 10094 if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer()) 10095 return SDValue(); 10096 10097 return CombineBaseUpdate(N, DCI); 10098 } 10099 10100 /// CombineVLDDUP - For a VDUPLANE node N, check if its source operand is a 10101 /// vldN-lane (N > 1) intrinsic, and if all the other uses of that intrinsic 10102 /// are also VDUPLANEs. If so, combine them to a vldN-dup operation and 10103 /// return true. 10104 static bool CombineVLDDUP(SDNode *N, TargetLowering::DAGCombinerInfo &DCI) { 10105 SelectionDAG &DAG = DCI.DAG; 10106 EVT VT = N->getValueType(0); 10107 // vldN-dup instructions only support 64-bit vectors for N > 1. 10108 if (!VT.is64BitVector()) 10109 return false; 10110 10111 // Check if the VDUPLANE operand is a vldN-dup intrinsic. 10112 SDNode *VLD = N->getOperand(0).getNode(); 10113 if (VLD->getOpcode() != ISD::INTRINSIC_W_CHAIN) 10114 return false; 10115 unsigned NumVecs = 0; 10116 unsigned NewOpc = 0; 10117 unsigned IntNo = cast<ConstantSDNode>(VLD->getOperand(1))->getZExtValue(); 10118 if (IntNo == Intrinsic::arm_neon_vld2lane) { 10119 NumVecs = 2; 10120 NewOpc = ARMISD::VLD2DUP; 10121 } else if (IntNo == Intrinsic::arm_neon_vld3lane) { 10122 NumVecs = 3; 10123 NewOpc = ARMISD::VLD3DUP; 10124 } else if (IntNo == Intrinsic::arm_neon_vld4lane) { 10125 NumVecs = 4; 10126 NewOpc = ARMISD::VLD4DUP; 10127 } else { 10128 return false; 10129 } 10130 10131 // First check that all the vldN-lane uses are VDUPLANEs and that the lane 10132 // numbers match the load. 10133 unsigned VLDLaneNo = 10134 cast<ConstantSDNode>(VLD->getOperand(NumVecs+3))->getZExtValue(); 10135 for (SDNode::use_iterator UI = VLD->use_begin(), UE = VLD->use_end(); 10136 UI != UE; ++UI) { 10137 // Ignore uses of the chain result. 10138 if (UI.getUse().getResNo() == NumVecs) 10139 continue; 10140 SDNode *User = *UI; 10141 if (User->getOpcode() != ARMISD::VDUPLANE || 10142 VLDLaneNo != cast<ConstantSDNode>(User->getOperand(1))->getZExtValue()) 10143 return false; 10144 } 10145 10146 // Create the vldN-dup node. 10147 EVT Tys[5]; 10148 unsigned n; 10149 for (n = 0; n < NumVecs; ++n) 10150 Tys[n] = VT; 10151 Tys[n] = MVT::Other; 10152 SDVTList SDTys = DAG.getVTList(makeArrayRef(Tys, NumVecs+1)); 10153 SDValue Ops[] = { VLD->getOperand(0), VLD->getOperand(2) }; 10154 MemIntrinsicSDNode *VLDMemInt = cast<MemIntrinsicSDNode>(VLD); 10155 SDValue VLDDup = DAG.getMemIntrinsicNode(NewOpc, SDLoc(VLD), SDTys, 10156 Ops, VLDMemInt->getMemoryVT(), 10157 VLDMemInt->getMemOperand()); 10158 10159 // Update the uses. 10160 for (SDNode::use_iterator UI = VLD->use_begin(), UE = VLD->use_end(); 10161 UI != UE; ++UI) { 10162 unsigned ResNo = UI.getUse().getResNo(); 10163 // Ignore uses of the chain result. 10164 if (ResNo == NumVecs) 10165 continue; 10166 SDNode *User = *UI; 10167 DCI.CombineTo(User, SDValue(VLDDup.getNode(), ResNo)); 10168 } 10169 10170 // Now the vldN-lane intrinsic is dead except for its chain result. 10171 // Update uses of the chain. 10172 std::vector<SDValue> VLDDupResults; 10173 for (unsigned n = 0; n < NumVecs; ++n) 10174 VLDDupResults.push_back(SDValue(VLDDup.getNode(), n)); 10175 VLDDupResults.push_back(SDValue(VLDDup.getNode(), NumVecs)); 10176 DCI.CombineTo(VLD, VLDDupResults); 10177 10178 return true; 10179 } 10180 10181 /// PerformVDUPLANECombine - Target-specific dag combine xforms for 10182 /// ARMISD::VDUPLANE. 10183 static SDValue PerformVDUPLANECombine(SDNode *N, 10184 TargetLowering::DAGCombinerInfo &DCI) { 10185 SDValue Op = N->getOperand(0); 10186 10187 // If the source is a vldN-lane (N > 1) intrinsic, and all the other uses 10188 // of that intrinsic are also VDUPLANEs, combine them to a vldN-dup operation. 10189 if (CombineVLDDUP(N, DCI)) 10190 return SDValue(N, 0); 10191 10192 // If the source is already a VMOVIMM or VMVNIMM splat, the VDUPLANE is 10193 // redundant. Ignore bit_converts for now; element sizes are checked below. 10194 while (Op.getOpcode() == ISD::BITCAST) 10195 Op = Op.getOperand(0); 10196 if (Op.getOpcode() != ARMISD::VMOVIMM && Op.getOpcode() != ARMISD::VMVNIMM) 10197 return SDValue(); 10198 10199 // Make sure the VMOV element size is not bigger than the VDUPLANE elements. 10200 unsigned EltSize = Op.getValueType().getVectorElementType().getSizeInBits(); 10201 // The canonical VMOV for a zero vector uses a 32-bit element size. 10202 unsigned Imm = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue(); 10203 unsigned EltBits; 10204 if (ARM_AM::decodeNEONModImm(Imm, EltBits) == 0) 10205 EltSize = 8; 10206 EVT VT = N->getValueType(0); 10207 if (EltSize > VT.getVectorElementType().getSizeInBits()) 10208 return SDValue(); 10209 10210 return DCI.DAG.getNode(ISD::BITCAST, SDLoc(N), VT, Op); 10211 } 10212 10213 static SDValue PerformLOADCombine(SDNode *N, 10214 TargetLowering::DAGCombinerInfo &DCI) { 10215 EVT VT = N->getValueType(0); 10216 10217 // If this is a legal vector load, try to combine it into a VLD1_UPD. 10218 if (ISD::isNormalLoad(N) && VT.isVector() && 10219 DCI.DAG.getTargetLoweringInfo().isTypeLegal(VT)) 10220 return CombineBaseUpdate(N, DCI); 10221 10222 return SDValue(); 10223 } 10224 10225 /// PerformSTORECombine - Target-specific dag combine xforms for 10226 /// ISD::STORE. 10227 static SDValue PerformSTORECombine(SDNode *N, 10228 TargetLowering::DAGCombinerInfo &DCI) { 10229 StoreSDNode *St = cast<StoreSDNode>(N); 10230 if (St->isVolatile()) 10231 return SDValue(); 10232 10233 // Optimize trunc store (of multiple scalars) to shuffle and store. First, 10234 // pack all of the elements in one place. Next, store to memory in fewer 10235 // chunks. 10236 SDValue StVal = St->getValue(); 10237 EVT VT = StVal.getValueType(); 10238 if (St->isTruncatingStore() && VT.isVector()) { 10239 SelectionDAG &DAG = DCI.DAG; 10240 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 10241 EVT StVT = St->getMemoryVT(); 10242 unsigned NumElems = VT.getVectorNumElements(); 10243 assert(StVT != VT && "Cannot truncate to the same type"); 10244 unsigned FromEltSz = VT.getVectorElementType().getSizeInBits(); 10245 unsigned ToEltSz = StVT.getVectorElementType().getSizeInBits(); 10246 10247 // From, To sizes and ElemCount must be pow of two 10248 if (!isPowerOf2_32(NumElems * FromEltSz * ToEltSz)) return SDValue(); 10249 10250 // We are going to use the original vector elt for storing. 10251 // Accumulated smaller vector elements must be a multiple of the store size. 10252 if (0 != (NumElems * FromEltSz) % ToEltSz) return SDValue(); 10253 10254 unsigned SizeRatio = FromEltSz / ToEltSz; 10255 assert(SizeRatio * NumElems * ToEltSz == VT.getSizeInBits()); 10256 10257 // Create a type on which we perform the shuffle. 10258 EVT WideVecVT = EVT::getVectorVT(*DAG.getContext(), StVT.getScalarType(), 10259 NumElems*SizeRatio); 10260 assert(WideVecVT.getSizeInBits() == VT.getSizeInBits()); 10261 10262 SDLoc DL(St); 10263 SDValue WideVec = DAG.getNode(ISD::BITCAST, DL, WideVecVT, StVal); 10264 SmallVector<int, 8> ShuffleVec(NumElems * SizeRatio, -1); 10265 for (unsigned i = 0; i < NumElems; ++i) 10266 ShuffleVec[i] = DAG.getDataLayout().isBigEndian() 10267 ? (i + 1) * SizeRatio - 1 10268 : i * SizeRatio; 10269 10270 // Can't shuffle using an illegal type. 10271 if (!TLI.isTypeLegal(WideVecVT)) return SDValue(); 10272 10273 SDValue Shuff = DAG.getVectorShuffle(WideVecVT, DL, WideVec, 10274 DAG.getUNDEF(WideVec.getValueType()), 10275 ShuffleVec.data()); 10276 // At this point all of the data is stored at the bottom of the 10277 // register. We now need to save it to mem. 10278 10279 // Find the largest store unit 10280 MVT StoreType = MVT::i8; 10281 for (MVT Tp : MVT::integer_valuetypes()) { 10282 if (TLI.isTypeLegal(Tp) && Tp.getSizeInBits() <= NumElems * ToEltSz) 10283 StoreType = Tp; 10284 } 10285 // Didn't find a legal store type. 10286 if (!TLI.isTypeLegal(StoreType)) 10287 return SDValue(); 10288 10289 // Bitcast the original vector into a vector of store-size units 10290 EVT StoreVecVT = EVT::getVectorVT(*DAG.getContext(), 10291 StoreType, VT.getSizeInBits()/EVT(StoreType).getSizeInBits()); 10292 assert(StoreVecVT.getSizeInBits() == VT.getSizeInBits()); 10293 SDValue ShuffWide = DAG.getNode(ISD::BITCAST, DL, StoreVecVT, Shuff); 10294 SmallVector<SDValue, 8> Chains; 10295 SDValue Increment = DAG.getConstant(StoreType.getSizeInBits() / 8, DL, 10296 TLI.getPointerTy(DAG.getDataLayout())); 10297 SDValue BasePtr = St->getBasePtr(); 10298 10299 // Perform one or more big stores into memory. 10300 unsigned E = (ToEltSz*NumElems)/StoreType.getSizeInBits(); 10301 for (unsigned I = 0; I < E; I++) { 10302 SDValue SubVec = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, 10303 StoreType, ShuffWide, 10304 DAG.getIntPtrConstant(I, DL)); 10305 SDValue Ch = DAG.getStore(St->getChain(), DL, SubVec, BasePtr, 10306 St->getPointerInfo(), St->isVolatile(), 10307 St->isNonTemporal(), St->getAlignment()); 10308 BasePtr = DAG.getNode(ISD::ADD, DL, BasePtr.getValueType(), BasePtr, 10309 Increment); 10310 Chains.push_back(Ch); 10311 } 10312 return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Chains); 10313 } 10314 10315 if (!ISD::isNormalStore(St)) 10316 return SDValue(); 10317 10318 // Split a store of a VMOVDRR into two integer stores to avoid mixing NEON and 10319 // ARM stores of arguments in the same cache line. 10320 if (StVal.getNode()->getOpcode() == ARMISD::VMOVDRR && 10321 StVal.getNode()->hasOneUse()) { 10322 SelectionDAG &DAG = DCI.DAG; 10323 bool isBigEndian = DAG.getDataLayout().isBigEndian(); 10324 SDLoc DL(St); 10325 SDValue BasePtr = St->getBasePtr(); 10326 SDValue NewST1 = DAG.getStore(St->getChain(), DL, 10327 StVal.getNode()->getOperand(isBigEndian ? 1 : 0 ), 10328 BasePtr, St->getPointerInfo(), St->isVolatile(), 10329 St->isNonTemporal(), St->getAlignment()); 10330 10331 SDValue OffsetPtr = DAG.getNode(ISD::ADD, DL, MVT::i32, BasePtr, 10332 DAG.getConstant(4, DL, MVT::i32)); 10333 return DAG.getStore(NewST1.getValue(0), DL, 10334 StVal.getNode()->getOperand(isBigEndian ? 0 : 1), 10335 OffsetPtr, St->getPointerInfo(), St->isVolatile(), 10336 St->isNonTemporal(), 10337 std::min(4U, St->getAlignment() / 2)); 10338 } 10339 10340 if (StVal.getValueType() == MVT::i64 && 10341 StVal.getNode()->getOpcode() == ISD::EXTRACT_VECTOR_ELT) { 10342 10343 // Bitcast an i64 store extracted from a vector to f64. 10344 // Otherwise, the i64 value will be legalized to a pair of i32 values. 10345 SelectionDAG &DAG = DCI.DAG; 10346 SDLoc dl(StVal); 10347 SDValue IntVec = StVal.getOperand(0); 10348 EVT FloatVT = EVT::getVectorVT(*DAG.getContext(), MVT::f64, 10349 IntVec.getValueType().getVectorNumElements()); 10350 SDValue Vec = DAG.getNode(ISD::BITCAST, dl, FloatVT, IntVec); 10351 SDValue ExtElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, 10352 Vec, StVal.getOperand(1)); 10353 dl = SDLoc(N); 10354 SDValue V = DAG.getNode(ISD::BITCAST, dl, MVT::i64, ExtElt); 10355 // Make the DAGCombiner fold the bitcasts. 10356 DCI.AddToWorklist(Vec.getNode()); 10357 DCI.AddToWorklist(ExtElt.getNode()); 10358 DCI.AddToWorklist(V.getNode()); 10359 return DAG.getStore(St->getChain(), dl, V, St->getBasePtr(), 10360 St->getPointerInfo(), St->isVolatile(), 10361 St->isNonTemporal(), St->getAlignment(), 10362 St->getAAInfo()); 10363 } 10364 10365 // If this is a legal vector store, try to combine it into a VST1_UPD. 10366 if (ISD::isNormalStore(N) && VT.isVector() && 10367 DCI.DAG.getTargetLoweringInfo().isTypeLegal(VT)) 10368 return CombineBaseUpdate(N, DCI); 10369 10370 return SDValue(); 10371 } 10372 10373 /// PerformVCVTCombine - VCVT (floating-point to fixed-point, Advanced SIMD) 10374 /// can replace combinations of VMUL and VCVT (floating-point to integer) 10375 /// when the VMUL has a constant operand that is a power of 2. 10376 /// 10377 /// Example (assume d17 = <float 8.000000e+00, float 8.000000e+00>): 10378 /// vmul.f32 d16, d17, d16 10379 /// vcvt.s32.f32 d16, d16 10380 /// becomes: 10381 /// vcvt.s32.f32 d16, d16, #3 10382 static SDValue PerformVCVTCombine(SDNode *N, SelectionDAG &DAG, 10383 const ARMSubtarget *Subtarget) { 10384 if (!Subtarget->hasNEON()) 10385 return SDValue(); 10386 10387 SDValue Op = N->getOperand(0); 10388 if (!Op.getValueType().isVector() || !Op.getValueType().isSimple() || 10389 Op.getOpcode() != ISD::FMUL) 10390 return SDValue(); 10391 10392 SDValue ConstVec = Op->getOperand(1); 10393 if (!isa<BuildVectorSDNode>(ConstVec)) 10394 return SDValue(); 10395 10396 MVT FloatTy = Op.getSimpleValueType().getVectorElementType(); 10397 uint32_t FloatBits = FloatTy.getSizeInBits(); 10398 MVT IntTy = N->getSimpleValueType(0).getVectorElementType(); 10399 uint32_t IntBits = IntTy.getSizeInBits(); 10400 unsigned NumLanes = Op.getValueType().getVectorNumElements(); 10401 if (FloatBits != 32 || IntBits > 32 || NumLanes > 4) { 10402 // These instructions only exist converting from f32 to i32. We can handle 10403 // smaller integers by generating an extra truncate, but larger ones would 10404 // be lossy. We also can't handle more then 4 lanes, since these intructions 10405 // only support v2i32/v4i32 types. 10406 return SDValue(); 10407 } 10408 10409 BitVector UndefElements; 10410 BuildVectorSDNode *BV = cast<BuildVectorSDNode>(ConstVec); 10411 int32_t C = BV->getConstantFPSplatPow2ToLog2Int(&UndefElements, 33); 10412 if (C == -1 || C == 0 || C > 32) 10413 return SDValue(); 10414 10415 SDLoc dl(N); 10416 bool isSigned = N->getOpcode() == ISD::FP_TO_SINT; 10417 unsigned IntrinsicOpcode = isSigned ? Intrinsic::arm_neon_vcvtfp2fxs : 10418 Intrinsic::arm_neon_vcvtfp2fxu; 10419 SDValue FixConv = DAG.getNode( 10420 ISD::INTRINSIC_WO_CHAIN, dl, NumLanes == 2 ? MVT::v2i32 : MVT::v4i32, 10421 DAG.getConstant(IntrinsicOpcode, dl, MVT::i32), Op->getOperand(0), 10422 DAG.getConstant(C, dl, MVT::i32)); 10423 10424 if (IntBits < FloatBits) 10425 FixConv = DAG.getNode(ISD::TRUNCATE, dl, N->getValueType(0), FixConv); 10426 10427 return FixConv; 10428 } 10429 10430 /// PerformVDIVCombine - VCVT (fixed-point to floating-point, Advanced SIMD) 10431 /// can replace combinations of VCVT (integer to floating-point) and VDIV 10432 /// when the VDIV has a constant operand that is a power of 2. 10433 /// 10434 /// Example (assume d17 = <float 8.000000e+00, float 8.000000e+00>): 10435 /// vcvt.f32.s32 d16, d16 10436 /// vdiv.f32 d16, d17, d16 10437 /// becomes: 10438 /// vcvt.f32.s32 d16, d16, #3 10439 static SDValue PerformVDIVCombine(SDNode *N, SelectionDAG &DAG, 10440 const ARMSubtarget *Subtarget) { 10441 if (!Subtarget->hasNEON()) 10442 return SDValue(); 10443 10444 SDValue Op = N->getOperand(0); 10445 unsigned OpOpcode = Op.getNode()->getOpcode(); 10446 if (!N->getValueType(0).isVector() || !N->getValueType(0).isSimple() || 10447 (OpOpcode != ISD::SINT_TO_FP && OpOpcode != ISD::UINT_TO_FP)) 10448 return SDValue(); 10449 10450 SDValue ConstVec = N->getOperand(1); 10451 if (!isa<BuildVectorSDNode>(ConstVec)) 10452 return SDValue(); 10453 10454 MVT FloatTy = N->getSimpleValueType(0).getVectorElementType(); 10455 uint32_t FloatBits = FloatTy.getSizeInBits(); 10456 MVT IntTy = Op.getOperand(0).getSimpleValueType().getVectorElementType(); 10457 uint32_t IntBits = IntTy.getSizeInBits(); 10458 unsigned NumLanes = Op.getValueType().getVectorNumElements(); 10459 if (FloatBits != 32 || IntBits > 32 || NumLanes > 4) { 10460 // These instructions only exist converting from i32 to f32. We can handle 10461 // smaller integers by generating an extra extend, but larger ones would 10462 // be lossy. We also can't handle more then 4 lanes, since these intructions 10463 // only support v2i32/v4i32 types. 10464 return SDValue(); 10465 } 10466 10467 BitVector UndefElements; 10468 BuildVectorSDNode *BV = cast<BuildVectorSDNode>(ConstVec); 10469 int32_t C = BV->getConstantFPSplatPow2ToLog2Int(&UndefElements, 33); 10470 if (C == -1 || C == 0 || C > 32) 10471 return SDValue(); 10472 10473 SDLoc dl(N); 10474 bool isSigned = OpOpcode == ISD::SINT_TO_FP; 10475 SDValue ConvInput = Op.getOperand(0); 10476 if (IntBits < FloatBits) 10477 ConvInput = DAG.getNode(isSigned ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND, 10478 dl, NumLanes == 2 ? MVT::v2i32 : MVT::v4i32, 10479 ConvInput); 10480 10481 unsigned IntrinsicOpcode = isSigned ? Intrinsic::arm_neon_vcvtfxs2fp : 10482 Intrinsic::arm_neon_vcvtfxu2fp; 10483 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, 10484 Op.getValueType(), 10485 DAG.getConstant(IntrinsicOpcode, dl, MVT::i32), 10486 ConvInput, DAG.getConstant(C, dl, MVT::i32)); 10487 } 10488 10489 /// Getvshiftimm - Check if this is a valid build_vector for the immediate 10490 /// operand of a vector shift operation, where all the elements of the 10491 /// build_vector must have the same constant integer value. 10492 static bool getVShiftImm(SDValue Op, unsigned ElementBits, int64_t &Cnt) { 10493 // Ignore bit_converts. 10494 while (Op.getOpcode() == ISD::BITCAST) 10495 Op = Op.getOperand(0); 10496 BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(Op.getNode()); 10497 APInt SplatBits, SplatUndef; 10498 unsigned SplatBitSize; 10499 bool HasAnyUndefs; 10500 if (! BVN || ! BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, 10501 HasAnyUndefs, ElementBits) || 10502 SplatBitSize > ElementBits) 10503 return false; 10504 Cnt = SplatBits.getSExtValue(); 10505 return true; 10506 } 10507 10508 /// isVShiftLImm - Check if this is a valid build_vector for the immediate 10509 /// operand of a vector shift left operation. That value must be in the range: 10510 /// 0 <= Value < ElementBits for a left shift; or 10511 /// 0 <= Value <= ElementBits for a long left shift. 10512 static bool isVShiftLImm(SDValue Op, EVT VT, bool isLong, int64_t &Cnt) { 10513 assert(VT.isVector() && "vector shift count is not a vector type"); 10514 int64_t ElementBits = VT.getVectorElementType().getSizeInBits(); 10515 if (! getVShiftImm(Op, ElementBits, Cnt)) 10516 return false; 10517 return (Cnt >= 0 && (isLong ? Cnt-1 : Cnt) < ElementBits); 10518 } 10519 10520 /// isVShiftRImm - Check if this is a valid build_vector for the immediate 10521 /// operand of a vector shift right operation. For a shift opcode, the value 10522 /// is positive, but for an intrinsic the value count must be negative. The 10523 /// absolute value must be in the range: 10524 /// 1 <= |Value| <= ElementBits for a right shift; or 10525 /// 1 <= |Value| <= ElementBits/2 for a narrow right shift. 10526 static bool isVShiftRImm(SDValue Op, EVT VT, bool isNarrow, bool isIntrinsic, 10527 int64_t &Cnt) { 10528 assert(VT.isVector() && "vector shift count is not a vector type"); 10529 int64_t ElementBits = VT.getVectorElementType().getSizeInBits(); 10530 if (! getVShiftImm(Op, ElementBits, Cnt)) 10531 return false; 10532 if (!isIntrinsic) 10533 return (Cnt >= 1 && Cnt <= (isNarrow ? ElementBits/2 : ElementBits)); 10534 if (Cnt >= -(isNarrow ? ElementBits/2 : ElementBits) && Cnt <= -1) { 10535 Cnt = -Cnt; 10536 return true; 10537 } 10538 return false; 10539 } 10540 10541 /// PerformIntrinsicCombine - ARM-specific DAG combining for intrinsics. 10542 static SDValue PerformIntrinsicCombine(SDNode *N, SelectionDAG &DAG) { 10543 unsigned IntNo = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue(); 10544 switch (IntNo) { 10545 default: 10546 // Don't do anything for most intrinsics. 10547 break; 10548 10549 // Vector shifts: check for immediate versions and lower them. 10550 // Note: This is done during DAG combining instead of DAG legalizing because 10551 // the build_vectors for 64-bit vector element shift counts are generally 10552 // not legal, and it is hard to see their values after they get legalized to 10553 // loads from a constant pool. 10554 case Intrinsic::arm_neon_vshifts: 10555 case Intrinsic::arm_neon_vshiftu: 10556 case Intrinsic::arm_neon_vrshifts: 10557 case Intrinsic::arm_neon_vrshiftu: 10558 case Intrinsic::arm_neon_vrshiftn: 10559 case Intrinsic::arm_neon_vqshifts: 10560 case Intrinsic::arm_neon_vqshiftu: 10561 case Intrinsic::arm_neon_vqshiftsu: 10562 case Intrinsic::arm_neon_vqshiftns: 10563 case Intrinsic::arm_neon_vqshiftnu: 10564 case Intrinsic::arm_neon_vqshiftnsu: 10565 case Intrinsic::arm_neon_vqrshiftns: 10566 case Intrinsic::arm_neon_vqrshiftnu: 10567 case Intrinsic::arm_neon_vqrshiftnsu: { 10568 EVT VT = N->getOperand(1).getValueType(); 10569 int64_t Cnt; 10570 unsigned VShiftOpc = 0; 10571 10572 switch (IntNo) { 10573 case Intrinsic::arm_neon_vshifts: 10574 case Intrinsic::arm_neon_vshiftu: 10575 if (isVShiftLImm(N->getOperand(2), VT, false, Cnt)) { 10576 VShiftOpc = ARMISD::VSHL; 10577 break; 10578 } 10579 if (isVShiftRImm(N->getOperand(2), VT, false, true, Cnt)) { 10580 VShiftOpc = (IntNo == Intrinsic::arm_neon_vshifts ? 10581 ARMISD::VSHRs : ARMISD::VSHRu); 10582 break; 10583 } 10584 return SDValue(); 10585 10586 case Intrinsic::arm_neon_vrshifts: 10587 case Intrinsic::arm_neon_vrshiftu: 10588 if (isVShiftRImm(N->getOperand(2), VT, false, true, Cnt)) 10589 break; 10590 return SDValue(); 10591 10592 case Intrinsic::arm_neon_vqshifts: 10593 case Intrinsic::arm_neon_vqshiftu: 10594 if (isVShiftLImm(N->getOperand(2), VT, false, Cnt)) 10595 break; 10596 return SDValue(); 10597 10598 case Intrinsic::arm_neon_vqshiftsu: 10599 if (isVShiftLImm(N->getOperand(2), VT, false, Cnt)) 10600 break; 10601 llvm_unreachable("invalid shift count for vqshlu intrinsic"); 10602 10603 case Intrinsic::arm_neon_vrshiftn: 10604 case Intrinsic::arm_neon_vqshiftns: 10605 case Intrinsic::arm_neon_vqshiftnu: 10606 case Intrinsic::arm_neon_vqshiftnsu: 10607 case Intrinsic::arm_neon_vqrshiftns: 10608 case Intrinsic::arm_neon_vqrshiftnu: 10609 case Intrinsic::arm_neon_vqrshiftnsu: 10610 // Narrowing shifts require an immediate right shift. 10611 if (isVShiftRImm(N->getOperand(2), VT, true, true, Cnt)) 10612 break; 10613 llvm_unreachable("invalid shift count for narrowing vector shift " 10614 "intrinsic"); 10615 10616 default: 10617 llvm_unreachable("unhandled vector shift"); 10618 } 10619 10620 switch (IntNo) { 10621 case Intrinsic::arm_neon_vshifts: 10622 case Intrinsic::arm_neon_vshiftu: 10623 // Opcode already set above. 10624 break; 10625 case Intrinsic::arm_neon_vrshifts: 10626 VShiftOpc = ARMISD::VRSHRs; break; 10627 case Intrinsic::arm_neon_vrshiftu: 10628 VShiftOpc = ARMISD::VRSHRu; break; 10629 case Intrinsic::arm_neon_vrshiftn: 10630 VShiftOpc = ARMISD::VRSHRN; break; 10631 case Intrinsic::arm_neon_vqshifts: 10632 VShiftOpc = ARMISD::VQSHLs; break; 10633 case Intrinsic::arm_neon_vqshiftu: 10634 VShiftOpc = ARMISD::VQSHLu; break; 10635 case Intrinsic::arm_neon_vqshiftsu: 10636 VShiftOpc = ARMISD::VQSHLsu; break; 10637 case Intrinsic::arm_neon_vqshiftns: 10638 VShiftOpc = ARMISD::VQSHRNs; break; 10639 case Intrinsic::arm_neon_vqshiftnu: 10640 VShiftOpc = ARMISD::VQSHRNu; break; 10641 case Intrinsic::arm_neon_vqshiftnsu: 10642 VShiftOpc = ARMISD::VQSHRNsu; break; 10643 case Intrinsic::arm_neon_vqrshiftns: 10644 VShiftOpc = ARMISD::VQRSHRNs; break; 10645 case Intrinsic::arm_neon_vqrshiftnu: 10646 VShiftOpc = ARMISD::VQRSHRNu; break; 10647 case Intrinsic::arm_neon_vqrshiftnsu: 10648 VShiftOpc = ARMISD::VQRSHRNsu; break; 10649 } 10650 10651 SDLoc dl(N); 10652 return DAG.getNode(VShiftOpc, dl, N->getValueType(0), 10653 N->getOperand(1), DAG.getConstant(Cnt, dl, MVT::i32)); 10654 } 10655 10656 case Intrinsic::arm_neon_vshiftins: { 10657 EVT VT = N->getOperand(1).getValueType(); 10658 int64_t Cnt; 10659 unsigned VShiftOpc = 0; 10660 10661 if (isVShiftLImm(N->getOperand(3), VT, false, Cnt)) 10662 VShiftOpc = ARMISD::VSLI; 10663 else if (isVShiftRImm(N->getOperand(3), VT, false, true, Cnt)) 10664 VShiftOpc = ARMISD::VSRI; 10665 else { 10666 llvm_unreachable("invalid shift count for vsli/vsri intrinsic"); 10667 } 10668 10669 SDLoc dl(N); 10670 return DAG.getNode(VShiftOpc, dl, N->getValueType(0), 10671 N->getOperand(1), N->getOperand(2), 10672 DAG.getConstant(Cnt, dl, MVT::i32)); 10673 } 10674 10675 case Intrinsic::arm_neon_vqrshifts: 10676 case Intrinsic::arm_neon_vqrshiftu: 10677 // No immediate versions of these to check for. 10678 break; 10679 } 10680 10681 return SDValue(); 10682 } 10683 10684 /// PerformShiftCombine - Checks for immediate versions of vector shifts and 10685 /// lowers them. As with the vector shift intrinsics, this is done during DAG 10686 /// combining instead of DAG legalizing because the build_vectors for 64-bit 10687 /// vector element shift counts are generally not legal, and it is hard to see 10688 /// their values after they get legalized to loads from a constant pool. 10689 static SDValue PerformShiftCombine(SDNode *N, SelectionDAG &DAG, 10690 const ARMSubtarget *ST) { 10691 EVT VT = N->getValueType(0); 10692 if (N->getOpcode() == ISD::SRL && VT == MVT::i32 && ST->hasV6Ops()) { 10693 // Canonicalize (srl (bswap x), 16) to (rotr (bswap x), 16) if the high 10694 // 16-bits of x is zero. This optimizes rev + lsr 16 to rev16. 10695 SDValue N1 = N->getOperand(1); 10696 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(N1)) { 10697 SDValue N0 = N->getOperand(0); 10698 if (C->getZExtValue() == 16 && N0.getOpcode() == ISD::BSWAP && 10699 DAG.MaskedValueIsZero(N0.getOperand(0), 10700 APInt::getHighBitsSet(32, 16))) 10701 return DAG.getNode(ISD::ROTR, SDLoc(N), VT, N0, N1); 10702 } 10703 } 10704 10705 // Nothing to be done for scalar shifts. 10706 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 10707 if (!VT.isVector() || !TLI.isTypeLegal(VT)) 10708 return SDValue(); 10709 10710 assert(ST->hasNEON() && "unexpected vector shift"); 10711 int64_t Cnt; 10712 10713 switch (N->getOpcode()) { 10714 default: llvm_unreachable("unexpected shift opcode"); 10715 10716 case ISD::SHL: 10717 if (isVShiftLImm(N->getOperand(1), VT, false, Cnt)) { 10718 SDLoc dl(N); 10719 return DAG.getNode(ARMISD::VSHL, dl, VT, N->getOperand(0), 10720 DAG.getConstant(Cnt, dl, MVT::i32)); 10721 } 10722 break; 10723 10724 case ISD::SRA: 10725 case ISD::SRL: 10726 if (isVShiftRImm(N->getOperand(1), VT, false, false, Cnt)) { 10727 unsigned VShiftOpc = (N->getOpcode() == ISD::SRA ? 10728 ARMISD::VSHRs : ARMISD::VSHRu); 10729 SDLoc dl(N); 10730 return DAG.getNode(VShiftOpc, dl, VT, N->getOperand(0), 10731 DAG.getConstant(Cnt, dl, MVT::i32)); 10732 } 10733 } 10734 return SDValue(); 10735 } 10736 10737 /// PerformExtendCombine - Target-specific DAG combining for ISD::SIGN_EXTEND, 10738 /// ISD::ZERO_EXTEND, and ISD::ANY_EXTEND. 10739 static SDValue PerformExtendCombine(SDNode *N, SelectionDAG &DAG, 10740 const ARMSubtarget *ST) { 10741 SDValue N0 = N->getOperand(0); 10742 10743 // Check for sign- and zero-extensions of vector extract operations of 8- 10744 // and 16-bit vector elements. NEON supports these directly. They are 10745 // handled during DAG combining because type legalization will promote them 10746 // to 32-bit types and it is messy to recognize the operations after that. 10747 if (ST->hasNEON() && N0.getOpcode() == ISD::EXTRACT_VECTOR_ELT) { 10748 SDValue Vec = N0.getOperand(0); 10749 SDValue Lane = N0.getOperand(1); 10750 EVT VT = N->getValueType(0); 10751 EVT EltVT = N0.getValueType(); 10752 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 10753 10754 if (VT == MVT::i32 && 10755 (EltVT == MVT::i8 || EltVT == MVT::i16) && 10756 TLI.isTypeLegal(Vec.getValueType()) && 10757 isa<ConstantSDNode>(Lane)) { 10758 10759 unsigned Opc = 0; 10760 switch (N->getOpcode()) { 10761 default: llvm_unreachable("unexpected opcode"); 10762 case ISD::SIGN_EXTEND: 10763 Opc = ARMISD::VGETLANEs; 10764 break; 10765 case ISD::ZERO_EXTEND: 10766 case ISD::ANY_EXTEND: 10767 Opc = ARMISD::VGETLANEu; 10768 break; 10769 } 10770 return DAG.getNode(Opc, SDLoc(N), VT, Vec, Lane); 10771 } 10772 } 10773 10774 return SDValue(); 10775 } 10776 10777 static void computeKnownBits(SelectionDAG &DAG, SDValue Op, APInt &KnownZero, 10778 APInt &KnownOne) { 10779 if (Op.getOpcode() == ARMISD::BFI) { 10780 // Conservatively, we can recurse down the first operand 10781 // and just mask out all affected bits. 10782 computeKnownBits(DAG, Op.getOperand(0), KnownZero, KnownOne); 10783 10784 // The operand to BFI is already a mask suitable for removing the bits it 10785 // sets. 10786 ConstantSDNode *CI = cast<ConstantSDNode>(Op.getOperand(2)); 10787 const APInt &Mask = CI->getAPIntValue(); 10788 KnownZero &= Mask; 10789 KnownOne &= Mask; 10790 return; 10791 } 10792 if (Op.getOpcode() == ARMISD::CMOV) { 10793 APInt KZ2(KnownZero.getBitWidth(), 0); 10794 APInt KO2(KnownOne.getBitWidth(), 0); 10795 computeKnownBits(DAG, Op.getOperand(1), KnownZero, KnownOne); 10796 computeKnownBits(DAG, Op.getOperand(2), KZ2, KO2); 10797 10798 KnownZero &= KZ2; 10799 KnownOne &= KO2; 10800 return; 10801 } 10802 return DAG.computeKnownBits(Op, KnownZero, KnownOne); 10803 } 10804 10805 SDValue ARMTargetLowering::PerformCMOVToBFICombine(SDNode *CMOV, SelectionDAG &DAG) const { 10806 // If we have a CMOV, OR and AND combination such as: 10807 // if (x & CN) 10808 // y |= CM; 10809 // 10810 // And: 10811 // * CN is a single bit; 10812 // * All bits covered by CM are known zero in y 10813 // 10814 // Then we can convert this into a sequence of BFI instructions. This will 10815 // always be a win if CM is a single bit, will always be no worse than the 10816 // TST&OR sequence if CM is two bits, and for thumb will be no worse if CM is 10817 // three bits (due to the extra IT instruction). 10818 10819 SDValue Op0 = CMOV->getOperand(0); 10820 SDValue Op1 = CMOV->getOperand(1); 10821 auto CCNode = cast<ConstantSDNode>(CMOV->getOperand(2)); 10822 auto CC = CCNode->getAPIntValue().getLimitedValue(); 10823 SDValue CmpZ = CMOV->getOperand(4); 10824 10825 // The compare must be against zero. 10826 if (!isNullConstant(CmpZ->getOperand(1))) 10827 return SDValue(); 10828 10829 assert(CmpZ->getOpcode() == ARMISD::CMPZ); 10830 SDValue And = CmpZ->getOperand(0); 10831 if (And->getOpcode() != ISD::AND) 10832 return SDValue(); 10833 ConstantSDNode *AndC = dyn_cast<ConstantSDNode>(And->getOperand(1)); 10834 if (!AndC || !AndC->getAPIntValue().isPowerOf2()) 10835 return SDValue(); 10836 SDValue X = And->getOperand(0); 10837 10838 if (CC == ARMCC::EQ) { 10839 // We're performing an "equal to zero" compare. Swap the operands so we 10840 // canonicalize on a "not equal to zero" compare. 10841 std::swap(Op0, Op1); 10842 } else { 10843 assert(CC == ARMCC::NE && "How can a CMPZ node not be EQ or NE?"); 10844 } 10845 10846 if (Op1->getOpcode() != ISD::OR) 10847 return SDValue(); 10848 10849 ConstantSDNode *OrC = dyn_cast<ConstantSDNode>(Op1->getOperand(1)); 10850 if (!OrC) 10851 return SDValue(); 10852 SDValue Y = Op1->getOperand(0); 10853 10854 if (Op0 != Y) 10855 return SDValue(); 10856 10857 // Now, is it profitable to continue? 10858 APInt OrCI = OrC->getAPIntValue(); 10859 unsigned Heuristic = Subtarget->isThumb() ? 3 : 2; 10860 if (OrCI.countPopulation() > Heuristic) 10861 return SDValue(); 10862 10863 // Lastly, can we determine that the bits defined by OrCI 10864 // are zero in Y? 10865 APInt KnownZero, KnownOne; 10866 computeKnownBits(DAG, Y, KnownZero, KnownOne); 10867 if ((OrCI & KnownZero) != OrCI) 10868 return SDValue(); 10869 10870 // OK, we can do the combine. 10871 SDValue V = Y; 10872 SDLoc dl(X); 10873 EVT VT = X.getValueType(); 10874 unsigned BitInX = AndC->getAPIntValue().logBase2(); 10875 10876 if (BitInX != 0) { 10877 // We must shift X first. 10878 X = DAG.getNode(ISD::SRL, dl, VT, X, 10879 DAG.getConstant(BitInX, dl, VT)); 10880 } 10881 10882 for (unsigned BitInY = 0, NumActiveBits = OrCI.getActiveBits(); 10883 BitInY < NumActiveBits; ++BitInY) { 10884 if (OrCI[BitInY] == 0) 10885 continue; 10886 APInt Mask(VT.getSizeInBits(), 0); 10887 Mask.setBit(BitInY); 10888 V = DAG.getNode(ARMISD::BFI, dl, VT, V, X, 10889 // Confusingly, the operand is an *inverted* mask. 10890 DAG.getConstant(~Mask, dl, VT)); 10891 } 10892 10893 return V; 10894 } 10895 10896 /// PerformBRCONDCombine - Target-specific DAG combining for ARMISD::BRCOND. 10897 SDValue 10898 ARMTargetLowering::PerformBRCONDCombine(SDNode *N, SelectionDAG &DAG) const { 10899 SDValue Cmp = N->getOperand(4); 10900 if (Cmp.getOpcode() != ARMISD::CMPZ) 10901 // Only looking at NE cases. 10902 return SDValue(); 10903 10904 EVT VT = N->getValueType(0); 10905 SDLoc dl(N); 10906 SDValue LHS = Cmp.getOperand(0); 10907 SDValue RHS = Cmp.getOperand(1); 10908 SDValue Chain = N->getOperand(0); 10909 SDValue BB = N->getOperand(1); 10910 SDValue ARMcc = N->getOperand(2); 10911 ARMCC::CondCodes CC = 10912 (ARMCC::CondCodes)cast<ConstantSDNode>(ARMcc)->getZExtValue(); 10913 10914 // (brcond Chain BB ne CPSR (cmpz (and (cmov 0 1 CC CPSR Cmp) 1) 0)) 10915 // -> (brcond Chain BB CC CPSR Cmp) 10916 if (CC == ARMCC::NE && LHS.getOpcode() == ISD::AND && LHS->hasOneUse() && 10917 LHS->getOperand(0)->getOpcode() == ARMISD::CMOV && 10918 LHS->getOperand(0)->hasOneUse()) { 10919 auto *LHS00C = dyn_cast<ConstantSDNode>(LHS->getOperand(0)->getOperand(0)); 10920 auto *LHS01C = dyn_cast<ConstantSDNode>(LHS->getOperand(0)->getOperand(1)); 10921 auto *LHS1C = dyn_cast<ConstantSDNode>(LHS->getOperand(1)); 10922 auto *RHSC = dyn_cast<ConstantSDNode>(RHS); 10923 if ((LHS00C && LHS00C->getZExtValue() == 0) && 10924 (LHS01C && LHS01C->getZExtValue() == 1) && 10925 (LHS1C && LHS1C->getZExtValue() == 1) && 10926 (RHSC && RHSC->getZExtValue() == 0)) { 10927 return DAG.getNode( 10928 ARMISD::BRCOND, dl, VT, Chain, BB, LHS->getOperand(0)->getOperand(2), 10929 LHS->getOperand(0)->getOperand(3), LHS->getOperand(0)->getOperand(4)); 10930 } 10931 } 10932 10933 return SDValue(); 10934 } 10935 10936 /// PerformCMOVCombine - Target-specific DAG combining for ARMISD::CMOV. 10937 SDValue 10938 ARMTargetLowering::PerformCMOVCombine(SDNode *N, SelectionDAG &DAG) const { 10939 SDValue Cmp = N->getOperand(4); 10940 if (Cmp.getOpcode() != ARMISD::CMPZ) 10941 // Only looking at EQ and NE cases. 10942 return SDValue(); 10943 10944 EVT VT = N->getValueType(0); 10945 SDLoc dl(N); 10946 SDValue LHS = Cmp.getOperand(0); 10947 SDValue RHS = Cmp.getOperand(1); 10948 SDValue FalseVal = N->getOperand(0); 10949 SDValue TrueVal = N->getOperand(1); 10950 SDValue ARMcc = N->getOperand(2); 10951 ARMCC::CondCodes CC = 10952 (ARMCC::CondCodes)cast<ConstantSDNode>(ARMcc)->getZExtValue(); 10953 10954 // BFI is only available on V6T2+. 10955 if (!Subtarget->isThumb1Only() && Subtarget->hasV6T2Ops()) { 10956 SDValue R = PerformCMOVToBFICombine(N, DAG); 10957 if (R) 10958 return R; 10959 } 10960 10961 // Simplify 10962 // mov r1, r0 10963 // cmp r1, x 10964 // mov r0, y 10965 // moveq r0, x 10966 // to 10967 // cmp r0, x 10968 // movne r0, y 10969 // 10970 // mov r1, r0 10971 // cmp r1, x 10972 // mov r0, x 10973 // movne r0, y 10974 // to 10975 // cmp r0, x 10976 // movne r0, y 10977 /// FIXME: Turn this into a target neutral optimization? 10978 SDValue Res; 10979 if (CC == ARMCC::NE && FalseVal == RHS && FalseVal != LHS) { 10980 Res = DAG.getNode(ARMISD::CMOV, dl, VT, LHS, TrueVal, ARMcc, 10981 N->getOperand(3), Cmp); 10982 } else if (CC == ARMCC::EQ && TrueVal == RHS) { 10983 SDValue ARMcc; 10984 SDValue NewCmp = getARMCmp(LHS, RHS, ISD::SETNE, ARMcc, DAG, dl); 10985 Res = DAG.getNode(ARMISD::CMOV, dl, VT, LHS, FalseVal, ARMcc, 10986 N->getOperand(3), NewCmp); 10987 } 10988 10989 // (cmov F T ne CPSR (cmpz (cmov 0 1 CC CPSR Cmp) 0)) 10990 // -> (cmov F T CC CPSR Cmp) 10991 if (CC == ARMCC::NE && LHS.getOpcode() == ARMISD::CMOV && LHS->hasOneUse()) { 10992 auto *LHS0C = dyn_cast<ConstantSDNode>(LHS->getOperand(0)); 10993 auto *LHS1C = dyn_cast<ConstantSDNode>(LHS->getOperand(1)); 10994 auto *RHSC = dyn_cast<ConstantSDNode>(RHS); 10995 if ((LHS0C && LHS0C->getZExtValue() == 0) && 10996 (LHS1C && LHS1C->getZExtValue() == 1) && 10997 (RHSC && RHSC->getZExtValue() == 0)) { 10998 return DAG.getNode(ARMISD::CMOV, dl, VT, FalseVal, TrueVal, 10999 LHS->getOperand(2), LHS->getOperand(3), 11000 LHS->getOperand(4)); 11001 } 11002 } 11003 11004 if (Res.getNode()) { 11005 APInt KnownZero, KnownOne; 11006 DAG.computeKnownBits(SDValue(N,0), KnownZero, KnownOne); 11007 // Capture demanded bits information that would be otherwise lost. 11008 if (KnownZero == 0xfffffffe) 11009 Res = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Res, 11010 DAG.getValueType(MVT::i1)); 11011 else if (KnownZero == 0xffffff00) 11012 Res = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Res, 11013 DAG.getValueType(MVT::i8)); 11014 else if (KnownZero == 0xffff0000) 11015 Res = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Res, 11016 DAG.getValueType(MVT::i16)); 11017 } 11018 11019 return Res; 11020 } 11021 11022 SDValue ARMTargetLowering::PerformDAGCombine(SDNode *N, 11023 DAGCombinerInfo &DCI) const { 11024 switch (N->getOpcode()) { 11025 default: break; 11026 case ISD::ADDC: return PerformADDCCombine(N, DCI, Subtarget); 11027 case ISD::ADD: return PerformADDCombine(N, DCI, Subtarget); 11028 case ISD::SUB: return PerformSUBCombine(N, DCI); 11029 case ISD::MUL: return PerformMULCombine(N, DCI, Subtarget); 11030 case ISD::OR: return PerformORCombine(N, DCI, Subtarget); 11031 case ISD::XOR: return PerformXORCombine(N, DCI, Subtarget); 11032 case ISD::AND: return PerformANDCombine(N, DCI, Subtarget); 11033 case ARMISD::BFI: return PerformBFICombine(N, DCI); 11034 case ARMISD::VMOVRRD: return PerformVMOVRRDCombine(N, DCI, Subtarget); 11035 case ARMISD::VMOVDRR: return PerformVMOVDRRCombine(N, DCI.DAG); 11036 case ISD::STORE: return PerformSTORECombine(N, DCI); 11037 case ISD::BUILD_VECTOR: return PerformBUILD_VECTORCombine(N, DCI, Subtarget); 11038 case ISD::INSERT_VECTOR_ELT: return PerformInsertEltCombine(N, DCI); 11039 case ISD::VECTOR_SHUFFLE: return PerformVECTOR_SHUFFLECombine(N, DCI.DAG); 11040 case ARMISD::VDUPLANE: return PerformVDUPLANECombine(N, DCI); 11041 case ISD::FP_TO_SINT: 11042 case ISD::FP_TO_UINT: 11043 return PerformVCVTCombine(N, DCI.DAG, Subtarget); 11044 case ISD::FDIV: 11045 return PerformVDIVCombine(N, DCI.DAG, Subtarget); 11046 case ISD::INTRINSIC_WO_CHAIN: return PerformIntrinsicCombine(N, DCI.DAG); 11047 case ISD::SHL: 11048 case ISD::SRA: 11049 case ISD::SRL: return PerformShiftCombine(N, DCI.DAG, Subtarget); 11050 case ISD::SIGN_EXTEND: 11051 case ISD::ZERO_EXTEND: 11052 case ISD::ANY_EXTEND: return PerformExtendCombine(N, DCI.DAG, Subtarget); 11053 case ARMISD::CMOV: return PerformCMOVCombine(N, DCI.DAG); 11054 case ARMISD::BRCOND: return PerformBRCONDCombine(N, DCI.DAG); 11055 case ISD::LOAD: return PerformLOADCombine(N, DCI); 11056 case ARMISD::VLD2DUP: 11057 case ARMISD::VLD3DUP: 11058 case ARMISD::VLD4DUP: 11059 return PerformVLDCombine(N, DCI); 11060 case ARMISD::BUILD_VECTOR: 11061 return PerformARMBUILD_VECTORCombine(N, DCI); 11062 case ISD::INTRINSIC_VOID: 11063 case ISD::INTRINSIC_W_CHAIN: 11064 switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) { 11065 case Intrinsic::arm_neon_vld1: 11066 case Intrinsic::arm_neon_vld2: 11067 case Intrinsic::arm_neon_vld3: 11068 case Intrinsic::arm_neon_vld4: 11069 case Intrinsic::arm_neon_vld2lane: 11070 case Intrinsic::arm_neon_vld3lane: 11071 case Intrinsic::arm_neon_vld4lane: 11072 case Intrinsic::arm_neon_vst1: 11073 case Intrinsic::arm_neon_vst2: 11074 case Intrinsic::arm_neon_vst3: 11075 case Intrinsic::arm_neon_vst4: 11076 case Intrinsic::arm_neon_vst2lane: 11077 case Intrinsic::arm_neon_vst3lane: 11078 case Intrinsic::arm_neon_vst4lane: 11079 return PerformVLDCombine(N, DCI); 11080 default: break; 11081 } 11082 break; 11083 } 11084 return SDValue(); 11085 } 11086 11087 bool ARMTargetLowering::isDesirableToTransformToIntegerOp(unsigned Opc, 11088 EVT VT) const { 11089 return (VT == MVT::f32) && (Opc == ISD::LOAD || Opc == ISD::STORE); 11090 } 11091 11092 bool ARMTargetLowering::allowsMisalignedMemoryAccesses(EVT VT, 11093 unsigned, 11094 unsigned, 11095 bool *Fast) const { 11096 // The AllowsUnaliged flag models the SCTLR.A setting in ARM cpus 11097 bool AllowsUnaligned = Subtarget->allowsUnalignedMem(); 11098 11099 switch (VT.getSimpleVT().SimpleTy) { 11100 default: 11101 return false; 11102 case MVT::i8: 11103 case MVT::i16: 11104 case MVT::i32: { 11105 // Unaligned access can use (for example) LRDB, LRDH, LDR 11106 if (AllowsUnaligned) { 11107 if (Fast) 11108 *Fast = Subtarget->hasV7Ops(); 11109 return true; 11110 } 11111 return false; 11112 } 11113 case MVT::f64: 11114 case MVT::v2f64: { 11115 // For any little-endian targets with neon, we can support unaligned ld/st 11116 // of D and Q (e.g. {D0,D1}) registers by using vld1.i8/vst1.i8. 11117 // A big-endian target may also explicitly support unaligned accesses 11118 if (Subtarget->hasNEON() && (AllowsUnaligned || Subtarget->isLittle())) { 11119 if (Fast) 11120 *Fast = true; 11121 return true; 11122 } 11123 return false; 11124 } 11125 } 11126 } 11127 11128 static bool memOpAlign(unsigned DstAlign, unsigned SrcAlign, 11129 unsigned AlignCheck) { 11130 return ((SrcAlign == 0 || SrcAlign % AlignCheck == 0) && 11131 (DstAlign == 0 || DstAlign % AlignCheck == 0)); 11132 } 11133 11134 EVT ARMTargetLowering::getOptimalMemOpType(uint64_t Size, 11135 unsigned DstAlign, unsigned SrcAlign, 11136 bool IsMemset, bool ZeroMemset, 11137 bool MemcpyStrSrc, 11138 MachineFunction &MF) const { 11139 const Function *F = MF.getFunction(); 11140 11141 // See if we can use NEON instructions for this... 11142 if ((!IsMemset || ZeroMemset) && Subtarget->hasNEON() && 11143 !F->hasFnAttribute(Attribute::NoImplicitFloat)) { 11144 bool Fast; 11145 if (Size >= 16 && 11146 (memOpAlign(SrcAlign, DstAlign, 16) || 11147 (allowsMisalignedMemoryAccesses(MVT::v2f64, 0, 1, &Fast) && Fast))) { 11148 return MVT::v2f64; 11149 } else if (Size >= 8 && 11150 (memOpAlign(SrcAlign, DstAlign, 8) || 11151 (allowsMisalignedMemoryAccesses(MVT::f64, 0, 1, &Fast) && 11152 Fast))) { 11153 return MVT::f64; 11154 } 11155 } 11156 11157 // Lowering to i32/i16 if the size permits. 11158 if (Size >= 4) 11159 return MVT::i32; 11160 else if (Size >= 2) 11161 return MVT::i16; 11162 11163 // Let the target-independent logic figure it out. 11164 return MVT::Other; 11165 } 11166 11167 bool ARMTargetLowering::isZExtFree(SDValue Val, EVT VT2) const { 11168 if (Val.getOpcode() != ISD::LOAD) 11169 return false; 11170 11171 EVT VT1 = Val.getValueType(); 11172 if (!VT1.isSimple() || !VT1.isInteger() || 11173 !VT2.isSimple() || !VT2.isInteger()) 11174 return false; 11175 11176 switch (VT1.getSimpleVT().SimpleTy) { 11177 default: break; 11178 case MVT::i1: 11179 case MVT::i8: 11180 case MVT::i16: 11181 // 8-bit and 16-bit loads implicitly zero-extend to 32-bits. 11182 return true; 11183 } 11184 11185 return false; 11186 } 11187 11188 bool ARMTargetLowering::isVectorLoadExtDesirable(SDValue ExtVal) const { 11189 EVT VT = ExtVal.getValueType(); 11190 11191 if (!isTypeLegal(VT)) 11192 return false; 11193 11194 // Don't create a loadext if we can fold the extension into a wide/long 11195 // instruction. 11196 // If there's more than one user instruction, the loadext is desirable no 11197 // matter what. There can be two uses by the same instruction. 11198 if (ExtVal->use_empty() || 11199 !ExtVal->use_begin()->isOnlyUserOf(ExtVal.getNode())) 11200 return true; 11201 11202 SDNode *U = *ExtVal->use_begin(); 11203 if ((U->getOpcode() == ISD::ADD || U->getOpcode() == ISD::SUB || 11204 U->getOpcode() == ISD::SHL || U->getOpcode() == ARMISD::VSHL)) 11205 return false; 11206 11207 return true; 11208 } 11209 11210 bool ARMTargetLowering::allowTruncateForTailCall(Type *Ty1, Type *Ty2) const { 11211 if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy()) 11212 return false; 11213 11214 if (!isTypeLegal(EVT::getEVT(Ty1))) 11215 return false; 11216 11217 assert(Ty1->getPrimitiveSizeInBits() <= 64 && "i128 is probably not a noop"); 11218 11219 // Assuming the caller doesn't have a zeroext or signext return parameter, 11220 // truncation all the way down to i1 is valid. 11221 return true; 11222 } 11223 11224 11225 static bool isLegalT1AddressImmediate(int64_t V, EVT VT) { 11226 if (V < 0) 11227 return false; 11228 11229 unsigned Scale = 1; 11230 switch (VT.getSimpleVT().SimpleTy) { 11231 default: return false; 11232 case MVT::i1: 11233 case MVT::i8: 11234 // Scale == 1; 11235 break; 11236 case MVT::i16: 11237 // Scale == 2; 11238 Scale = 2; 11239 break; 11240 case MVT::i32: 11241 // Scale == 4; 11242 Scale = 4; 11243 break; 11244 } 11245 11246 if ((V & (Scale - 1)) != 0) 11247 return false; 11248 V /= Scale; 11249 return V == (V & ((1LL << 5) - 1)); 11250 } 11251 11252 static bool isLegalT2AddressImmediate(int64_t V, EVT VT, 11253 const ARMSubtarget *Subtarget) { 11254 bool isNeg = false; 11255 if (V < 0) { 11256 isNeg = true; 11257 V = - V; 11258 } 11259 11260 switch (VT.getSimpleVT().SimpleTy) { 11261 default: return false; 11262 case MVT::i1: 11263 case MVT::i8: 11264 case MVT::i16: 11265 case MVT::i32: 11266 // + imm12 or - imm8 11267 if (isNeg) 11268 return V == (V & ((1LL << 8) - 1)); 11269 return V == (V & ((1LL << 12) - 1)); 11270 case MVT::f32: 11271 case MVT::f64: 11272 // Same as ARM mode. FIXME: NEON? 11273 if (!Subtarget->hasVFP2()) 11274 return false; 11275 if ((V & 3) != 0) 11276 return false; 11277 V >>= 2; 11278 return V == (V & ((1LL << 8) - 1)); 11279 } 11280 } 11281 11282 /// isLegalAddressImmediate - Return true if the integer value can be used 11283 /// as the offset of the target addressing mode for load / store of the 11284 /// given type. 11285 static bool isLegalAddressImmediate(int64_t V, EVT VT, 11286 const ARMSubtarget *Subtarget) { 11287 if (V == 0) 11288 return true; 11289 11290 if (!VT.isSimple()) 11291 return false; 11292 11293 if (Subtarget->isThumb1Only()) 11294 return isLegalT1AddressImmediate(V, VT); 11295 else if (Subtarget->isThumb2()) 11296 return isLegalT2AddressImmediate(V, VT, Subtarget); 11297 11298 // ARM mode. 11299 if (V < 0) 11300 V = - V; 11301 switch (VT.getSimpleVT().SimpleTy) { 11302 default: return false; 11303 case MVT::i1: 11304 case MVT::i8: 11305 case MVT::i32: 11306 // +- imm12 11307 return V == (V & ((1LL << 12) - 1)); 11308 case MVT::i16: 11309 // +- imm8 11310 return V == (V & ((1LL << 8) - 1)); 11311 case MVT::f32: 11312 case MVT::f64: 11313 if (!Subtarget->hasVFP2()) // FIXME: NEON? 11314 return false; 11315 if ((V & 3) != 0) 11316 return false; 11317 V >>= 2; 11318 return V == (V & ((1LL << 8) - 1)); 11319 } 11320 } 11321 11322 bool ARMTargetLowering::isLegalT2ScaledAddressingMode(const AddrMode &AM, 11323 EVT VT) const { 11324 int Scale = AM.Scale; 11325 if (Scale < 0) 11326 return false; 11327 11328 switch (VT.getSimpleVT().SimpleTy) { 11329 default: return false; 11330 case MVT::i1: 11331 case MVT::i8: 11332 case MVT::i16: 11333 case MVT::i32: 11334 if (Scale == 1) 11335 return true; 11336 // r + r << imm 11337 Scale = Scale & ~1; 11338 return Scale == 2 || Scale == 4 || Scale == 8; 11339 case MVT::i64: 11340 // r + r 11341 if (((unsigned)AM.HasBaseReg + Scale) <= 2) 11342 return true; 11343 return false; 11344 case MVT::isVoid: 11345 // Note, we allow "void" uses (basically, uses that aren't loads or 11346 // stores), because arm allows folding a scale into many arithmetic 11347 // operations. This should be made more precise and revisited later. 11348 11349 // Allow r << imm, but the imm has to be a multiple of two. 11350 if (Scale & 1) return false; 11351 return isPowerOf2_32(Scale); 11352 } 11353 } 11354 11355 /// isLegalAddressingMode - Return true if the addressing mode represented 11356 /// by AM is legal for this target, for a load/store of the specified type. 11357 bool ARMTargetLowering::isLegalAddressingMode(const DataLayout &DL, 11358 const AddrMode &AM, Type *Ty, 11359 unsigned AS) const { 11360 EVT VT = getValueType(DL, Ty, true); 11361 if (!isLegalAddressImmediate(AM.BaseOffs, VT, Subtarget)) 11362 return false; 11363 11364 // Can never fold addr of global into load/store. 11365 if (AM.BaseGV) 11366 return false; 11367 11368 switch (AM.Scale) { 11369 case 0: // no scale reg, must be "r+i" or "r", or "i". 11370 break; 11371 case 1: 11372 if (Subtarget->isThumb1Only()) 11373 return false; 11374 // FALL THROUGH. 11375 default: 11376 // ARM doesn't support any R+R*scale+imm addr modes. 11377 if (AM.BaseOffs) 11378 return false; 11379 11380 if (!VT.isSimple()) 11381 return false; 11382 11383 if (Subtarget->isThumb2()) 11384 return isLegalT2ScaledAddressingMode(AM, VT); 11385 11386 int Scale = AM.Scale; 11387 switch (VT.getSimpleVT().SimpleTy) { 11388 default: return false; 11389 case MVT::i1: 11390 case MVT::i8: 11391 case MVT::i32: 11392 if (Scale < 0) Scale = -Scale; 11393 if (Scale == 1) 11394 return true; 11395 // r + r << imm 11396 return isPowerOf2_32(Scale & ~1); 11397 case MVT::i16: 11398 case MVT::i64: 11399 // r + r 11400 if (((unsigned)AM.HasBaseReg + Scale) <= 2) 11401 return true; 11402 return false; 11403 11404 case MVT::isVoid: 11405 // Note, we allow "void" uses (basically, uses that aren't loads or 11406 // stores), because arm allows folding a scale into many arithmetic 11407 // operations. This should be made more precise and revisited later. 11408 11409 // Allow r << imm, but the imm has to be a multiple of two. 11410 if (Scale & 1) return false; 11411 return isPowerOf2_32(Scale); 11412 } 11413 } 11414 return true; 11415 } 11416 11417 /// isLegalICmpImmediate - Return true if the specified immediate is legal 11418 /// icmp immediate, that is the target has icmp instructions which can compare 11419 /// a register against the immediate without having to materialize the 11420 /// immediate into a register. 11421 bool ARMTargetLowering::isLegalICmpImmediate(int64_t Imm) const { 11422 // Thumb2 and ARM modes can use cmn for negative immediates. 11423 if (!Subtarget->isThumb()) 11424 return ARM_AM::getSOImmVal(std::abs(Imm)) != -1; 11425 if (Subtarget->isThumb2()) 11426 return ARM_AM::getT2SOImmVal(std::abs(Imm)) != -1; 11427 // Thumb1 doesn't have cmn, and only 8-bit immediates. 11428 return Imm >= 0 && Imm <= 255; 11429 } 11430 11431 /// isLegalAddImmediate - Return true if the specified immediate is a legal add 11432 /// *or sub* immediate, that is the target has add or sub instructions which can 11433 /// add a register with the immediate without having to materialize the 11434 /// immediate into a register. 11435 bool ARMTargetLowering::isLegalAddImmediate(int64_t Imm) const { 11436 // Same encoding for add/sub, just flip the sign. 11437 int64_t AbsImm = std::abs(Imm); 11438 if (!Subtarget->isThumb()) 11439 return ARM_AM::getSOImmVal(AbsImm) != -1; 11440 if (Subtarget->isThumb2()) 11441 return ARM_AM::getT2SOImmVal(AbsImm) != -1; 11442 // Thumb1 only has 8-bit unsigned immediate. 11443 return AbsImm >= 0 && AbsImm <= 255; 11444 } 11445 11446 static bool getARMIndexedAddressParts(SDNode *Ptr, EVT VT, 11447 bool isSEXTLoad, SDValue &Base, 11448 SDValue &Offset, bool &isInc, 11449 SelectionDAG &DAG) { 11450 if (Ptr->getOpcode() != ISD::ADD && Ptr->getOpcode() != ISD::SUB) 11451 return false; 11452 11453 if (VT == MVT::i16 || ((VT == MVT::i8 || VT == MVT::i1) && isSEXTLoad)) { 11454 // AddressingMode 3 11455 Base = Ptr->getOperand(0); 11456 if (ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(Ptr->getOperand(1))) { 11457 int RHSC = (int)RHS->getZExtValue(); 11458 if (RHSC < 0 && RHSC > -256) { 11459 assert(Ptr->getOpcode() == ISD::ADD); 11460 isInc = false; 11461 Offset = DAG.getConstant(-RHSC, SDLoc(Ptr), RHS->getValueType(0)); 11462 return true; 11463 } 11464 } 11465 isInc = (Ptr->getOpcode() == ISD::ADD); 11466 Offset = Ptr->getOperand(1); 11467 return true; 11468 } else if (VT == MVT::i32 || VT == MVT::i8 || VT == MVT::i1) { 11469 // AddressingMode 2 11470 if (ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(Ptr->getOperand(1))) { 11471 int RHSC = (int)RHS->getZExtValue(); 11472 if (RHSC < 0 && RHSC > -0x1000) { 11473 assert(Ptr->getOpcode() == ISD::ADD); 11474 isInc = false; 11475 Offset = DAG.getConstant(-RHSC, SDLoc(Ptr), RHS->getValueType(0)); 11476 Base = Ptr->getOperand(0); 11477 return true; 11478 } 11479 } 11480 11481 if (Ptr->getOpcode() == ISD::ADD) { 11482 isInc = true; 11483 ARM_AM::ShiftOpc ShOpcVal= 11484 ARM_AM::getShiftOpcForNode(Ptr->getOperand(0).getOpcode()); 11485 if (ShOpcVal != ARM_AM::no_shift) { 11486 Base = Ptr->getOperand(1); 11487 Offset = Ptr->getOperand(0); 11488 } else { 11489 Base = Ptr->getOperand(0); 11490 Offset = Ptr->getOperand(1); 11491 } 11492 return true; 11493 } 11494 11495 isInc = (Ptr->getOpcode() == ISD::ADD); 11496 Base = Ptr->getOperand(0); 11497 Offset = Ptr->getOperand(1); 11498 return true; 11499 } 11500 11501 // FIXME: Use VLDM / VSTM to emulate indexed FP load / store. 11502 return false; 11503 } 11504 11505 static bool getT2IndexedAddressParts(SDNode *Ptr, EVT VT, 11506 bool isSEXTLoad, SDValue &Base, 11507 SDValue &Offset, bool &isInc, 11508 SelectionDAG &DAG) { 11509 if (Ptr->getOpcode() != ISD::ADD && Ptr->getOpcode() != ISD::SUB) 11510 return false; 11511 11512 Base = Ptr->getOperand(0); 11513 if (ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(Ptr->getOperand(1))) { 11514 int RHSC = (int)RHS->getZExtValue(); 11515 if (RHSC < 0 && RHSC > -0x100) { // 8 bits. 11516 assert(Ptr->getOpcode() == ISD::ADD); 11517 isInc = false; 11518 Offset = DAG.getConstant(-RHSC, SDLoc(Ptr), RHS->getValueType(0)); 11519 return true; 11520 } else if (RHSC > 0 && RHSC < 0x100) { // 8 bit, no zero. 11521 isInc = Ptr->getOpcode() == ISD::ADD; 11522 Offset = DAG.getConstant(RHSC, SDLoc(Ptr), RHS->getValueType(0)); 11523 return true; 11524 } 11525 } 11526 11527 return false; 11528 } 11529 11530 /// getPreIndexedAddressParts - returns true by value, base pointer and 11531 /// offset pointer and addressing mode by reference if the node's address 11532 /// can be legally represented as pre-indexed load / store address. 11533 bool 11534 ARMTargetLowering::getPreIndexedAddressParts(SDNode *N, SDValue &Base, 11535 SDValue &Offset, 11536 ISD::MemIndexedMode &AM, 11537 SelectionDAG &DAG) const { 11538 if (Subtarget->isThumb1Only()) 11539 return false; 11540 11541 EVT VT; 11542 SDValue Ptr; 11543 bool isSEXTLoad = false; 11544 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) { 11545 Ptr = LD->getBasePtr(); 11546 VT = LD->getMemoryVT(); 11547 isSEXTLoad = LD->getExtensionType() == ISD::SEXTLOAD; 11548 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) { 11549 Ptr = ST->getBasePtr(); 11550 VT = ST->getMemoryVT(); 11551 } else 11552 return false; 11553 11554 bool isInc; 11555 bool isLegal = false; 11556 if (Subtarget->isThumb2()) 11557 isLegal = getT2IndexedAddressParts(Ptr.getNode(), VT, isSEXTLoad, Base, 11558 Offset, isInc, DAG); 11559 else 11560 isLegal = getARMIndexedAddressParts(Ptr.getNode(), VT, isSEXTLoad, Base, 11561 Offset, isInc, DAG); 11562 if (!isLegal) 11563 return false; 11564 11565 AM = isInc ? ISD::PRE_INC : ISD::PRE_DEC; 11566 return true; 11567 } 11568 11569 /// getPostIndexedAddressParts - returns true by value, base pointer and 11570 /// offset pointer and addressing mode by reference if this node can be 11571 /// combined with a load / store to form a post-indexed load / store. 11572 bool ARMTargetLowering::getPostIndexedAddressParts(SDNode *N, SDNode *Op, 11573 SDValue &Base, 11574 SDValue &Offset, 11575 ISD::MemIndexedMode &AM, 11576 SelectionDAG &DAG) const { 11577 if (Subtarget->isThumb1Only()) 11578 return false; 11579 11580 EVT VT; 11581 SDValue Ptr; 11582 bool isSEXTLoad = false; 11583 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) { 11584 VT = LD->getMemoryVT(); 11585 Ptr = LD->getBasePtr(); 11586 isSEXTLoad = LD->getExtensionType() == ISD::SEXTLOAD; 11587 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) { 11588 VT = ST->getMemoryVT(); 11589 Ptr = ST->getBasePtr(); 11590 } else 11591 return false; 11592 11593 bool isInc; 11594 bool isLegal = false; 11595 if (Subtarget->isThumb2()) 11596 isLegal = getT2IndexedAddressParts(Op, VT, isSEXTLoad, Base, Offset, 11597 isInc, DAG); 11598 else 11599 isLegal = getARMIndexedAddressParts(Op, VT, isSEXTLoad, Base, Offset, 11600 isInc, DAG); 11601 if (!isLegal) 11602 return false; 11603 11604 if (Ptr != Base) { 11605 // Swap base ptr and offset to catch more post-index load / store when 11606 // it's legal. In Thumb2 mode, offset must be an immediate. 11607 if (Ptr == Offset && Op->getOpcode() == ISD::ADD && 11608 !Subtarget->isThumb2()) 11609 std::swap(Base, Offset); 11610 11611 // Post-indexed load / store update the base pointer. 11612 if (Ptr != Base) 11613 return false; 11614 } 11615 11616 AM = isInc ? ISD::POST_INC : ISD::POST_DEC; 11617 return true; 11618 } 11619 11620 void ARMTargetLowering::computeKnownBitsForTargetNode(const SDValue Op, 11621 APInt &KnownZero, 11622 APInt &KnownOne, 11623 const SelectionDAG &DAG, 11624 unsigned Depth) const { 11625 unsigned BitWidth = KnownOne.getBitWidth(); 11626 KnownZero = KnownOne = APInt(BitWidth, 0); 11627 switch (Op.getOpcode()) { 11628 default: break; 11629 case ARMISD::ADDC: 11630 case ARMISD::ADDE: 11631 case ARMISD::SUBC: 11632 case ARMISD::SUBE: 11633 // These nodes' second result is a boolean 11634 if (Op.getResNo() == 0) 11635 break; 11636 KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - 1); 11637 break; 11638 case ARMISD::CMOV: { 11639 // Bits are known zero/one if known on the LHS and RHS. 11640 DAG.computeKnownBits(Op.getOperand(0), KnownZero, KnownOne, Depth+1); 11641 if (KnownZero == 0 && KnownOne == 0) return; 11642 11643 APInt KnownZeroRHS, KnownOneRHS; 11644 DAG.computeKnownBits(Op.getOperand(1), KnownZeroRHS, KnownOneRHS, Depth+1); 11645 KnownZero &= KnownZeroRHS; 11646 KnownOne &= KnownOneRHS; 11647 return; 11648 } 11649 case ISD::INTRINSIC_W_CHAIN: { 11650 ConstantSDNode *CN = cast<ConstantSDNode>(Op->getOperand(1)); 11651 Intrinsic::ID IntID = static_cast<Intrinsic::ID>(CN->getZExtValue()); 11652 switch (IntID) { 11653 default: return; 11654 case Intrinsic::arm_ldaex: 11655 case Intrinsic::arm_ldrex: { 11656 EVT VT = cast<MemIntrinsicSDNode>(Op)->getMemoryVT(); 11657 unsigned MemBits = VT.getScalarType().getSizeInBits(); 11658 KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - MemBits); 11659 return; 11660 } 11661 } 11662 } 11663 } 11664 } 11665 11666 //===----------------------------------------------------------------------===// 11667 // ARM Inline Assembly Support 11668 //===----------------------------------------------------------------------===// 11669 11670 bool ARMTargetLowering::ExpandInlineAsm(CallInst *CI) const { 11671 // Looking for "rev" which is V6+. 11672 if (!Subtarget->hasV6Ops()) 11673 return false; 11674 11675 InlineAsm *IA = cast<InlineAsm>(CI->getCalledValue()); 11676 std::string AsmStr = IA->getAsmString(); 11677 SmallVector<StringRef, 4> AsmPieces; 11678 SplitString(AsmStr, AsmPieces, ";\n"); 11679 11680 switch (AsmPieces.size()) { 11681 default: return false; 11682 case 1: 11683 AsmStr = AsmPieces[0]; 11684 AsmPieces.clear(); 11685 SplitString(AsmStr, AsmPieces, " \t,"); 11686 11687 // rev $0, $1 11688 if (AsmPieces.size() == 3 && 11689 AsmPieces[0] == "rev" && AsmPieces[1] == "$0" && AsmPieces[2] == "$1" && 11690 IA->getConstraintString().compare(0, 4, "=l,l") == 0) { 11691 IntegerType *Ty = dyn_cast<IntegerType>(CI->getType()); 11692 if (Ty && Ty->getBitWidth() == 32) 11693 return IntrinsicLowering::LowerToByteSwap(CI); 11694 } 11695 break; 11696 } 11697 11698 return false; 11699 } 11700 11701 const char *ARMTargetLowering::LowerXConstraint(EVT ConstraintVT) const { 11702 // At this point, we have to lower this constraint to something else, so we 11703 // lower it to an "r" or "w". However, by doing this we will force the result 11704 // to be in register, while the X constraint is much more permissive. 11705 // 11706 // Although we are correct (we are free to emit anything, without 11707 // constraints), we might break use cases that would expect us to be more 11708 // efficient and emit something else. 11709 if (!Subtarget->hasVFP2()) 11710 return "r"; 11711 if (ConstraintVT.isFloatingPoint()) 11712 return "w"; 11713 if (ConstraintVT.isVector() && Subtarget->hasNEON() && 11714 (ConstraintVT.getSizeInBits() == 64 || 11715 ConstraintVT.getSizeInBits() == 128)) 11716 return "w"; 11717 11718 return "r"; 11719 } 11720 11721 /// getConstraintType - Given a constraint letter, return the type of 11722 /// constraint it is for this target. 11723 ARMTargetLowering::ConstraintType 11724 ARMTargetLowering::getConstraintType(StringRef Constraint) const { 11725 if (Constraint.size() == 1) { 11726 switch (Constraint[0]) { 11727 default: break; 11728 case 'l': return C_RegisterClass; 11729 case 'w': return C_RegisterClass; 11730 case 'h': return C_RegisterClass; 11731 case 'x': return C_RegisterClass; 11732 case 't': return C_RegisterClass; 11733 case 'j': return C_Other; // Constant for movw. 11734 // An address with a single base register. Due to the way we 11735 // currently handle addresses it is the same as an 'r' memory constraint. 11736 case 'Q': return C_Memory; 11737 } 11738 } else if (Constraint.size() == 2) { 11739 switch (Constraint[0]) { 11740 default: break; 11741 // All 'U+' constraints are addresses. 11742 case 'U': return C_Memory; 11743 } 11744 } 11745 return TargetLowering::getConstraintType(Constraint); 11746 } 11747 11748 /// Examine constraint type and operand type and determine a weight value. 11749 /// This object must already have been set up with the operand type 11750 /// and the current alternative constraint selected. 11751 TargetLowering::ConstraintWeight 11752 ARMTargetLowering::getSingleConstraintMatchWeight( 11753 AsmOperandInfo &info, const char *constraint) const { 11754 ConstraintWeight weight = CW_Invalid; 11755 Value *CallOperandVal = info.CallOperandVal; 11756 // If we don't have a value, we can't do a match, 11757 // but allow it at the lowest weight. 11758 if (!CallOperandVal) 11759 return CW_Default; 11760 Type *type = CallOperandVal->getType(); 11761 // Look at the constraint type. 11762 switch (*constraint) { 11763 default: 11764 weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint); 11765 break; 11766 case 'l': 11767 if (type->isIntegerTy()) { 11768 if (Subtarget->isThumb()) 11769 weight = CW_SpecificReg; 11770 else 11771 weight = CW_Register; 11772 } 11773 break; 11774 case 'w': 11775 if (type->isFloatingPointTy()) 11776 weight = CW_Register; 11777 break; 11778 } 11779 return weight; 11780 } 11781 11782 typedef std::pair<unsigned, const TargetRegisterClass*> RCPair; 11783 RCPair ARMTargetLowering::getRegForInlineAsmConstraint( 11784 const TargetRegisterInfo *TRI, StringRef Constraint, MVT VT) const { 11785 if (Constraint.size() == 1) { 11786 // GCC ARM Constraint Letters 11787 switch (Constraint[0]) { 11788 case 'l': // Low regs or general regs. 11789 if (Subtarget->isThumb()) 11790 return RCPair(0U, &ARM::tGPRRegClass); 11791 return RCPair(0U, &ARM::GPRRegClass); 11792 case 'h': // High regs or no regs. 11793 if (Subtarget->isThumb()) 11794 return RCPair(0U, &ARM::hGPRRegClass); 11795 break; 11796 case 'r': 11797 if (Subtarget->isThumb1Only()) 11798 return RCPair(0U, &ARM::tGPRRegClass); 11799 return RCPair(0U, &ARM::GPRRegClass); 11800 case 'w': 11801 if (VT == MVT::Other) 11802 break; 11803 if (VT == MVT::f32) 11804 return RCPair(0U, &ARM::SPRRegClass); 11805 if (VT.getSizeInBits() == 64) 11806 return RCPair(0U, &ARM::DPRRegClass); 11807 if (VT.getSizeInBits() == 128) 11808 return RCPair(0U, &ARM::QPRRegClass); 11809 break; 11810 case 'x': 11811 if (VT == MVT::Other) 11812 break; 11813 if (VT == MVT::f32) 11814 return RCPair(0U, &ARM::SPR_8RegClass); 11815 if (VT.getSizeInBits() == 64) 11816 return RCPair(0U, &ARM::DPR_8RegClass); 11817 if (VT.getSizeInBits() == 128) 11818 return RCPair(0U, &ARM::QPR_8RegClass); 11819 break; 11820 case 't': 11821 if (VT == MVT::f32) 11822 return RCPair(0U, &ARM::SPRRegClass); 11823 break; 11824 } 11825 } 11826 if (StringRef("{cc}").equals_lower(Constraint)) 11827 return std::make_pair(unsigned(ARM::CPSR), &ARM::CCRRegClass); 11828 11829 return TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT); 11830 } 11831 11832 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops 11833 /// vector. If it is invalid, don't add anything to Ops. 11834 void ARMTargetLowering::LowerAsmOperandForConstraint(SDValue Op, 11835 std::string &Constraint, 11836 std::vector<SDValue>&Ops, 11837 SelectionDAG &DAG) const { 11838 SDValue Result; 11839 11840 // Currently only support length 1 constraints. 11841 if (Constraint.length() != 1) return; 11842 11843 char ConstraintLetter = Constraint[0]; 11844 switch (ConstraintLetter) { 11845 default: break; 11846 case 'j': 11847 case 'I': case 'J': case 'K': case 'L': 11848 case 'M': case 'N': case 'O': 11849 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op); 11850 if (!C) 11851 return; 11852 11853 int64_t CVal64 = C->getSExtValue(); 11854 int CVal = (int) CVal64; 11855 // None of these constraints allow values larger than 32 bits. Check 11856 // that the value fits in an int. 11857 if (CVal != CVal64) 11858 return; 11859 11860 switch (ConstraintLetter) { 11861 case 'j': 11862 // Constant suitable for movw, must be between 0 and 11863 // 65535. 11864 if (Subtarget->hasV6T2Ops()) 11865 if (CVal >= 0 && CVal <= 65535) 11866 break; 11867 return; 11868 case 'I': 11869 if (Subtarget->isThumb1Only()) { 11870 // This must be a constant between 0 and 255, for ADD 11871 // immediates. 11872 if (CVal >= 0 && CVal <= 255) 11873 break; 11874 } else if (Subtarget->isThumb2()) { 11875 // A constant that can be used as an immediate value in a 11876 // data-processing instruction. 11877 if (ARM_AM::getT2SOImmVal(CVal) != -1) 11878 break; 11879 } else { 11880 // A constant that can be used as an immediate value in a 11881 // data-processing instruction. 11882 if (ARM_AM::getSOImmVal(CVal) != -1) 11883 break; 11884 } 11885 return; 11886 11887 case 'J': 11888 if (Subtarget->isThumb1Only()) { 11889 // This must be a constant between -255 and -1, for negated ADD 11890 // immediates. This can be used in GCC with an "n" modifier that 11891 // prints the negated value, for use with SUB instructions. It is 11892 // not useful otherwise but is implemented for compatibility. 11893 if (CVal >= -255 && CVal <= -1) 11894 break; 11895 } else { 11896 // This must be a constant between -4095 and 4095. It is not clear 11897 // what this constraint is intended for. Implemented for 11898 // compatibility with GCC. 11899 if (CVal >= -4095 && CVal <= 4095) 11900 break; 11901 } 11902 return; 11903 11904 case 'K': 11905 if (Subtarget->isThumb1Only()) { 11906 // A 32-bit value where only one byte has a nonzero value. Exclude 11907 // zero to match GCC. This constraint is used by GCC internally for 11908 // constants that can be loaded with a move/shift combination. 11909 // It is not useful otherwise but is implemented for compatibility. 11910 if (CVal != 0 && ARM_AM::isThumbImmShiftedVal(CVal)) 11911 break; 11912 } else if (Subtarget->isThumb2()) { 11913 // A constant whose bitwise inverse can be used as an immediate 11914 // value in a data-processing instruction. This can be used in GCC 11915 // with a "B" modifier that prints the inverted value, for use with 11916 // BIC and MVN instructions. It is not useful otherwise but is 11917 // implemented for compatibility. 11918 if (ARM_AM::getT2SOImmVal(~CVal) != -1) 11919 break; 11920 } else { 11921 // A constant whose bitwise inverse can be used as an immediate 11922 // value in a data-processing instruction. This can be used in GCC 11923 // with a "B" modifier that prints the inverted value, for use with 11924 // BIC and MVN instructions. It is not useful otherwise but is 11925 // implemented for compatibility. 11926 if (ARM_AM::getSOImmVal(~CVal) != -1) 11927 break; 11928 } 11929 return; 11930 11931 case 'L': 11932 if (Subtarget->isThumb1Only()) { 11933 // This must be a constant between -7 and 7, 11934 // for 3-operand ADD/SUB immediate instructions. 11935 if (CVal >= -7 && CVal < 7) 11936 break; 11937 } else if (Subtarget->isThumb2()) { 11938 // A constant whose negation can be used as an immediate value in a 11939 // data-processing instruction. This can be used in GCC with an "n" 11940 // modifier that prints the negated value, for use with SUB 11941 // instructions. It is not useful otherwise but is implemented for 11942 // compatibility. 11943 if (ARM_AM::getT2SOImmVal(-CVal) != -1) 11944 break; 11945 } else { 11946 // A constant whose negation can be used as an immediate value in a 11947 // data-processing instruction. This can be used in GCC with an "n" 11948 // modifier that prints the negated value, for use with SUB 11949 // instructions. It is not useful otherwise but is implemented for 11950 // compatibility. 11951 if (ARM_AM::getSOImmVal(-CVal) != -1) 11952 break; 11953 } 11954 return; 11955 11956 case 'M': 11957 if (Subtarget->isThumb1Only()) { 11958 // This must be a multiple of 4 between 0 and 1020, for 11959 // ADD sp + immediate. 11960 if ((CVal >= 0 && CVal <= 1020) && ((CVal & 3) == 0)) 11961 break; 11962 } else { 11963 // A power of two or a constant between 0 and 32. This is used in 11964 // GCC for the shift amount on shifted register operands, but it is 11965 // useful in general for any shift amounts. 11966 if ((CVal >= 0 && CVal <= 32) || ((CVal & (CVal - 1)) == 0)) 11967 break; 11968 } 11969 return; 11970 11971 case 'N': 11972 if (Subtarget->isThumb()) { // FIXME thumb2 11973 // This must be a constant between 0 and 31, for shift amounts. 11974 if (CVal >= 0 && CVal <= 31) 11975 break; 11976 } 11977 return; 11978 11979 case 'O': 11980 if (Subtarget->isThumb()) { // FIXME thumb2 11981 // This must be a multiple of 4 between -508 and 508, for 11982 // ADD/SUB sp = sp + immediate. 11983 if ((CVal >= -508 && CVal <= 508) && ((CVal & 3) == 0)) 11984 break; 11985 } 11986 return; 11987 } 11988 Result = DAG.getTargetConstant(CVal, SDLoc(Op), Op.getValueType()); 11989 break; 11990 } 11991 11992 if (Result.getNode()) { 11993 Ops.push_back(Result); 11994 return; 11995 } 11996 return TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG); 11997 } 11998 11999 static RTLIB::Libcall getDivRemLibcall( 12000 const SDNode *N, MVT::SimpleValueType SVT) { 12001 assert((N->getOpcode() == ISD::SDIVREM || N->getOpcode() == ISD::UDIVREM || 12002 N->getOpcode() == ISD::SREM || N->getOpcode() == ISD::UREM) && 12003 "Unhandled Opcode in getDivRemLibcall"); 12004 bool isSigned = N->getOpcode() == ISD::SDIVREM || 12005 N->getOpcode() == ISD::SREM; 12006 RTLIB::Libcall LC; 12007 switch (SVT) { 12008 default: llvm_unreachable("Unexpected request for libcall!"); 12009 case MVT::i8: LC = isSigned ? RTLIB::SDIVREM_I8 : RTLIB::UDIVREM_I8; break; 12010 case MVT::i16: LC = isSigned ? RTLIB::SDIVREM_I16 : RTLIB::UDIVREM_I16; break; 12011 case MVT::i32: LC = isSigned ? RTLIB::SDIVREM_I32 : RTLIB::UDIVREM_I32; break; 12012 case MVT::i64: LC = isSigned ? RTLIB::SDIVREM_I64 : RTLIB::UDIVREM_I64; break; 12013 } 12014 return LC; 12015 } 12016 12017 static TargetLowering::ArgListTy getDivRemArgList( 12018 const SDNode *N, LLVMContext *Context) { 12019 assert((N->getOpcode() == ISD::SDIVREM || N->getOpcode() == ISD::UDIVREM || 12020 N->getOpcode() == ISD::SREM || N->getOpcode() == ISD::UREM) && 12021 "Unhandled Opcode in getDivRemArgList"); 12022 bool isSigned = N->getOpcode() == ISD::SDIVREM || 12023 N->getOpcode() == ISD::SREM; 12024 TargetLowering::ArgListTy Args; 12025 TargetLowering::ArgListEntry Entry; 12026 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) { 12027 EVT ArgVT = N->getOperand(i).getValueType(); 12028 Type *ArgTy = ArgVT.getTypeForEVT(*Context); 12029 Entry.Node = N->getOperand(i); 12030 Entry.Ty = ArgTy; 12031 Entry.isSExt = isSigned; 12032 Entry.isZExt = !isSigned; 12033 Args.push_back(Entry); 12034 } 12035 return Args; 12036 } 12037 12038 SDValue ARMTargetLowering::LowerDivRem(SDValue Op, SelectionDAG &DAG) const { 12039 assert((Subtarget->isTargetAEABI() || Subtarget->isTargetAndroid() || 12040 Subtarget->isTargetGNUAEABI() || Subtarget->isTargetMuslAEABI()) && 12041 "Register-based DivRem lowering only"); 12042 unsigned Opcode = Op->getOpcode(); 12043 assert((Opcode == ISD::SDIVREM || Opcode == ISD::UDIVREM) && 12044 "Invalid opcode for Div/Rem lowering"); 12045 bool isSigned = (Opcode == ISD::SDIVREM); 12046 EVT VT = Op->getValueType(0); 12047 Type *Ty = VT.getTypeForEVT(*DAG.getContext()); 12048 12049 RTLIB::Libcall LC = getDivRemLibcall(Op.getNode(), 12050 VT.getSimpleVT().SimpleTy); 12051 SDValue InChain = DAG.getEntryNode(); 12052 12053 TargetLowering::ArgListTy Args = getDivRemArgList(Op.getNode(), 12054 DAG.getContext()); 12055 12056 SDValue Callee = DAG.getExternalSymbol(getLibcallName(LC), 12057 getPointerTy(DAG.getDataLayout())); 12058 12059 Type *RetTy = (Type*)StructType::get(Ty, Ty, nullptr); 12060 12061 SDLoc dl(Op); 12062 TargetLowering::CallLoweringInfo CLI(DAG); 12063 CLI.setDebugLoc(dl).setChain(InChain) 12064 .setCallee(getLibcallCallingConv(LC), RetTy, Callee, std::move(Args)) 12065 .setInRegister().setSExtResult(isSigned).setZExtResult(!isSigned); 12066 12067 std::pair<SDValue, SDValue> CallInfo = LowerCallTo(CLI); 12068 return CallInfo.first; 12069 } 12070 12071 // Lowers REM using divmod helpers 12072 // see RTABI section 4.2/4.3 12073 SDValue ARMTargetLowering::LowerREM(SDNode *N, SelectionDAG &DAG) const { 12074 // Build return types (div and rem) 12075 std::vector<Type*> RetTyParams; 12076 Type *RetTyElement; 12077 12078 switch (N->getValueType(0).getSimpleVT().SimpleTy) { 12079 default: llvm_unreachable("Unexpected request for libcall!"); 12080 case MVT::i8: RetTyElement = Type::getInt8Ty(*DAG.getContext()); break; 12081 case MVT::i16: RetTyElement = Type::getInt16Ty(*DAG.getContext()); break; 12082 case MVT::i32: RetTyElement = Type::getInt32Ty(*DAG.getContext()); break; 12083 case MVT::i64: RetTyElement = Type::getInt64Ty(*DAG.getContext()); break; 12084 } 12085 12086 RetTyParams.push_back(RetTyElement); 12087 RetTyParams.push_back(RetTyElement); 12088 ArrayRef<Type*> ret = ArrayRef<Type*>(RetTyParams); 12089 Type *RetTy = StructType::get(*DAG.getContext(), ret); 12090 12091 RTLIB::Libcall LC = getDivRemLibcall(N, N->getValueType(0).getSimpleVT(). 12092 SimpleTy); 12093 SDValue InChain = DAG.getEntryNode(); 12094 TargetLowering::ArgListTy Args = getDivRemArgList(N, DAG.getContext()); 12095 bool isSigned = N->getOpcode() == ISD::SREM; 12096 SDValue Callee = DAG.getExternalSymbol(getLibcallName(LC), 12097 getPointerTy(DAG.getDataLayout())); 12098 12099 // Lower call 12100 CallLoweringInfo CLI(DAG); 12101 CLI.setChain(InChain) 12102 .setCallee(CallingConv::ARM_AAPCS, RetTy, Callee, std::move(Args)) 12103 .setSExtResult(isSigned).setZExtResult(!isSigned).setDebugLoc(SDLoc(N)); 12104 std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI); 12105 12106 // Return second (rem) result operand (first contains div) 12107 SDNode *ResNode = CallResult.first.getNode(); 12108 assert(ResNode->getNumOperands() == 2 && "divmod should return two operands"); 12109 return ResNode->getOperand(1); 12110 } 12111 12112 SDValue 12113 ARMTargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op, SelectionDAG &DAG) const { 12114 assert(Subtarget->isTargetWindows() && "unsupported target platform"); 12115 SDLoc DL(Op); 12116 12117 // Get the inputs. 12118 SDValue Chain = Op.getOperand(0); 12119 SDValue Size = Op.getOperand(1); 12120 12121 SDValue Words = DAG.getNode(ISD::SRL, DL, MVT::i32, Size, 12122 DAG.getConstant(2, DL, MVT::i32)); 12123 12124 SDValue Flag; 12125 Chain = DAG.getCopyToReg(Chain, DL, ARM::R4, Words, Flag); 12126 Flag = Chain.getValue(1); 12127 12128 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue); 12129 Chain = DAG.getNode(ARMISD::WIN__CHKSTK, DL, NodeTys, Chain, Flag); 12130 12131 SDValue NewSP = DAG.getCopyFromReg(Chain, DL, ARM::SP, MVT::i32); 12132 Chain = NewSP.getValue(1); 12133 12134 SDValue Ops[2] = { NewSP, Chain }; 12135 return DAG.getMergeValues(Ops, DL); 12136 } 12137 12138 SDValue ARMTargetLowering::LowerFP_EXTEND(SDValue Op, SelectionDAG &DAG) const { 12139 assert(Op.getValueType() == MVT::f64 && Subtarget->isFPOnlySP() && 12140 "Unexpected type for custom-lowering FP_EXTEND"); 12141 12142 RTLIB::Libcall LC; 12143 LC = RTLIB::getFPEXT(Op.getOperand(0).getValueType(), Op.getValueType()); 12144 12145 SDValue SrcVal = Op.getOperand(0); 12146 return makeLibCall(DAG, LC, Op.getValueType(), SrcVal, /*isSigned*/ false, 12147 SDLoc(Op)).first; 12148 } 12149 12150 SDValue ARMTargetLowering::LowerFP_ROUND(SDValue Op, SelectionDAG &DAG) const { 12151 assert(Op.getOperand(0).getValueType() == MVT::f64 && 12152 Subtarget->isFPOnlySP() && 12153 "Unexpected type for custom-lowering FP_ROUND"); 12154 12155 RTLIB::Libcall LC; 12156 LC = RTLIB::getFPROUND(Op.getOperand(0).getValueType(), Op.getValueType()); 12157 12158 SDValue SrcVal = Op.getOperand(0); 12159 return makeLibCall(DAG, LC, Op.getValueType(), SrcVal, /*isSigned*/ false, 12160 SDLoc(Op)).first; 12161 } 12162 12163 bool 12164 ARMTargetLowering::isOffsetFoldingLegal(const GlobalAddressSDNode *GA) const { 12165 // The ARM target isn't yet aware of offsets. 12166 return false; 12167 } 12168 12169 bool ARM::isBitFieldInvertedMask(unsigned v) { 12170 if (v == 0xffffffff) 12171 return false; 12172 12173 // there can be 1's on either or both "outsides", all the "inside" 12174 // bits must be 0's 12175 return isShiftedMask_32(~v); 12176 } 12177 12178 /// isFPImmLegal - Returns true if the target can instruction select the 12179 /// specified FP immediate natively. If false, the legalizer will 12180 /// materialize the FP immediate as a load from a constant pool. 12181 bool ARMTargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT) const { 12182 if (!Subtarget->hasVFP3()) 12183 return false; 12184 if (VT == MVT::f32) 12185 return ARM_AM::getFP32Imm(Imm) != -1; 12186 if (VT == MVT::f64 && !Subtarget->isFPOnlySP()) 12187 return ARM_AM::getFP64Imm(Imm) != -1; 12188 return false; 12189 } 12190 12191 /// getTgtMemIntrinsic - Represent NEON load and store intrinsics as 12192 /// MemIntrinsicNodes. The associated MachineMemOperands record the alignment 12193 /// specified in the intrinsic calls. 12194 bool ARMTargetLowering::getTgtMemIntrinsic(IntrinsicInfo &Info, 12195 const CallInst &I, 12196 unsigned Intrinsic) const { 12197 switch (Intrinsic) { 12198 case Intrinsic::arm_neon_vld1: 12199 case Intrinsic::arm_neon_vld2: 12200 case Intrinsic::arm_neon_vld3: 12201 case Intrinsic::arm_neon_vld4: 12202 case Intrinsic::arm_neon_vld2lane: 12203 case Intrinsic::arm_neon_vld3lane: 12204 case Intrinsic::arm_neon_vld4lane: { 12205 Info.opc = ISD::INTRINSIC_W_CHAIN; 12206 // Conservatively set memVT to the entire set of vectors loaded. 12207 auto &DL = I.getCalledFunction()->getParent()->getDataLayout(); 12208 uint64_t NumElts = DL.getTypeSizeInBits(I.getType()) / 64; 12209 Info.memVT = EVT::getVectorVT(I.getType()->getContext(), MVT::i64, NumElts); 12210 Info.ptrVal = I.getArgOperand(0); 12211 Info.offset = 0; 12212 Value *AlignArg = I.getArgOperand(I.getNumArgOperands() - 1); 12213 Info.align = cast<ConstantInt>(AlignArg)->getZExtValue(); 12214 Info.vol = false; // volatile loads with NEON intrinsics not supported 12215 Info.readMem = true; 12216 Info.writeMem = false; 12217 return true; 12218 } 12219 case Intrinsic::arm_neon_vst1: 12220 case Intrinsic::arm_neon_vst2: 12221 case Intrinsic::arm_neon_vst3: 12222 case Intrinsic::arm_neon_vst4: 12223 case Intrinsic::arm_neon_vst2lane: 12224 case Intrinsic::arm_neon_vst3lane: 12225 case Intrinsic::arm_neon_vst4lane: { 12226 Info.opc = ISD::INTRINSIC_VOID; 12227 // Conservatively set memVT to the entire set of vectors stored. 12228 auto &DL = I.getCalledFunction()->getParent()->getDataLayout(); 12229 unsigned NumElts = 0; 12230 for (unsigned ArgI = 1, ArgE = I.getNumArgOperands(); ArgI < ArgE; ++ArgI) { 12231 Type *ArgTy = I.getArgOperand(ArgI)->getType(); 12232 if (!ArgTy->isVectorTy()) 12233 break; 12234 NumElts += DL.getTypeSizeInBits(ArgTy) / 64; 12235 } 12236 Info.memVT = EVT::getVectorVT(I.getType()->getContext(), MVT::i64, NumElts); 12237 Info.ptrVal = I.getArgOperand(0); 12238 Info.offset = 0; 12239 Value *AlignArg = I.getArgOperand(I.getNumArgOperands() - 1); 12240 Info.align = cast<ConstantInt>(AlignArg)->getZExtValue(); 12241 Info.vol = false; // volatile stores with NEON intrinsics not supported 12242 Info.readMem = false; 12243 Info.writeMem = true; 12244 return true; 12245 } 12246 case Intrinsic::arm_ldaex: 12247 case Intrinsic::arm_ldrex: { 12248 auto &DL = I.getCalledFunction()->getParent()->getDataLayout(); 12249 PointerType *PtrTy = cast<PointerType>(I.getArgOperand(0)->getType()); 12250 Info.opc = ISD::INTRINSIC_W_CHAIN; 12251 Info.memVT = MVT::getVT(PtrTy->getElementType()); 12252 Info.ptrVal = I.getArgOperand(0); 12253 Info.offset = 0; 12254 Info.align = DL.getABITypeAlignment(PtrTy->getElementType()); 12255 Info.vol = true; 12256 Info.readMem = true; 12257 Info.writeMem = false; 12258 return true; 12259 } 12260 case Intrinsic::arm_stlex: 12261 case Intrinsic::arm_strex: { 12262 auto &DL = I.getCalledFunction()->getParent()->getDataLayout(); 12263 PointerType *PtrTy = cast<PointerType>(I.getArgOperand(1)->getType()); 12264 Info.opc = ISD::INTRINSIC_W_CHAIN; 12265 Info.memVT = MVT::getVT(PtrTy->getElementType()); 12266 Info.ptrVal = I.getArgOperand(1); 12267 Info.offset = 0; 12268 Info.align = DL.getABITypeAlignment(PtrTy->getElementType()); 12269 Info.vol = true; 12270 Info.readMem = false; 12271 Info.writeMem = true; 12272 return true; 12273 } 12274 case Intrinsic::arm_stlexd: 12275 case Intrinsic::arm_strexd: { 12276 Info.opc = ISD::INTRINSIC_W_CHAIN; 12277 Info.memVT = MVT::i64; 12278 Info.ptrVal = I.getArgOperand(2); 12279 Info.offset = 0; 12280 Info.align = 8; 12281 Info.vol = true; 12282 Info.readMem = false; 12283 Info.writeMem = true; 12284 return true; 12285 } 12286 case Intrinsic::arm_ldaexd: 12287 case Intrinsic::arm_ldrexd: { 12288 Info.opc = ISD::INTRINSIC_W_CHAIN; 12289 Info.memVT = MVT::i64; 12290 Info.ptrVal = I.getArgOperand(0); 12291 Info.offset = 0; 12292 Info.align = 8; 12293 Info.vol = true; 12294 Info.readMem = true; 12295 Info.writeMem = false; 12296 return true; 12297 } 12298 default: 12299 break; 12300 } 12301 12302 return false; 12303 } 12304 12305 /// \brief Returns true if it is beneficial to convert a load of a constant 12306 /// to just the constant itself. 12307 bool ARMTargetLowering::shouldConvertConstantLoadToIntImm(const APInt &Imm, 12308 Type *Ty) const { 12309 assert(Ty->isIntegerTy()); 12310 12311 unsigned Bits = Ty->getPrimitiveSizeInBits(); 12312 if (Bits == 0 || Bits > 32) 12313 return false; 12314 return true; 12315 } 12316 12317 Instruction* ARMTargetLowering::makeDMB(IRBuilder<> &Builder, 12318 ARM_MB::MemBOpt Domain) const { 12319 Module *M = Builder.GetInsertBlock()->getParent()->getParent(); 12320 12321 // First, if the target has no DMB, see what fallback we can use. 12322 if (!Subtarget->hasDataBarrier()) { 12323 // Some ARMv6 cpus can support data barriers with an mcr instruction. 12324 // Thumb1 and pre-v6 ARM mode use a libcall instead and should never get 12325 // here. 12326 if (Subtarget->hasV6Ops() && !Subtarget->isThumb()) { 12327 Function *MCR = llvm::Intrinsic::getDeclaration(M, Intrinsic::arm_mcr); 12328 Value* args[6] = {Builder.getInt32(15), Builder.getInt32(0), 12329 Builder.getInt32(0), Builder.getInt32(7), 12330 Builder.getInt32(10), Builder.getInt32(5)}; 12331 return Builder.CreateCall(MCR, args); 12332 } else { 12333 // Instead of using barriers, atomic accesses on these subtargets use 12334 // libcalls. 12335 llvm_unreachable("makeDMB on a target so old that it has no barriers"); 12336 } 12337 } else { 12338 Function *DMB = llvm::Intrinsic::getDeclaration(M, Intrinsic::arm_dmb); 12339 // Only a full system barrier exists in the M-class architectures. 12340 Domain = Subtarget->isMClass() ? ARM_MB::SY : Domain; 12341 Constant *CDomain = Builder.getInt32(Domain); 12342 return Builder.CreateCall(DMB, CDomain); 12343 } 12344 } 12345 12346 // Based on http://www.cl.cam.ac.uk/~pes20/cpp/cpp0xmappings.html 12347 Instruction* ARMTargetLowering::emitLeadingFence(IRBuilder<> &Builder, 12348 AtomicOrdering Ord, bool IsStore, 12349 bool IsLoad) const { 12350 switch (Ord) { 12351 case AtomicOrdering::NotAtomic: 12352 case AtomicOrdering::Unordered: 12353 llvm_unreachable("Invalid fence: unordered/non-atomic"); 12354 case AtomicOrdering::Monotonic: 12355 case AtomicOrdering::Acquire: 12356 return nullptr; // Nothing to do 12357 case AtomicOrdering::SequentiallyConsistent: 12358 if (!IsStore) 12359 return nullptr; // Nothing to do 12360 /*FALLTHROUGH*/ 12361 case AtomicOrdering::Release: 12362 case AtomicOrdering::AcquireRelease: 12363 if (Subtarget->preferISHSTBarriers()) 12364 return makeDMB(Builder, ARM_MB::ISHST); 12365 // FIXME: add a comment with a link to documentation justifying this. 12366 else 12367 return makeDMB(Builder, ARM_MB::ISH); 12368 } 12369 llvm_unreachable("Unknown fence ordering in emitLeadingFence"); 12370 } 12371 12372 Instruction* ARMTargetLowering::emitTrailingFence(IRBuilder<> &Builder, 12373 AtomicOrdering Ord, bool IsStore, 12374 bool IsLoad) const { 12375 switch (Ord) { 12376 case AtomicOrdering::NotAtomic: 12377 case AtomicOrdering::Unordered: 12378 llvm_unreachable("Invalid fence: unordered/not-atomic"); 12379 case AtomicOrdering::Monotonic: 12380 case AtomicOrdering::Release: 12381 return nullptr; // Nothing to do 12382 case AtomicOrdering::Acquire: 12383 case AtomicOrdering::AcquireRelease: 12384 case AtomicOrdering::SequentiallyConsistent: 12385 return makeDMB(Builder, ARM_MB::ISH); 12386 } 12387 llvm_unreachable("Unknown fence ordering in emitTrailingFence"); 12388 } 12389 12390 // Loads and stores less than 64-bits are already atomic; ones above that 12391 // are doomed anyway, so defer to the default libcall and blame the OS when 12392 // things go wrong. Cortex M doesn't have ldrexd/strexd though, so don't emit 12393 // anything for those. 12394 bool ARMTargetLowering::shouldExpandAtomicStoreInIR(StoreInst *SI) const { 12395 unsigned Size = SI->getValueOperand()->getType()->getPrimitiveSizeInBits(); 12396 return (Size == 64) && !Subtarget->isMClass(); 12397 } 12398 12399 // Loads and stores less than 64-bits are already atomic; ones above that 12400 // are doomed anyway, so defer to the default libcall and blame the OS when 12401 // things go wrong. Cortex M doesn't have ldrexd/strexd though, so don't emit 12402 // anything for those. 12403 // FIXME: ldrd and strd are atomic if the CPU has LPAE (e.g. A15 has that 12404 // guarantee, see DDI0406C ARM architecture reference manual, 12405 // sections A8.8.72-74 LDRD) 12406 TargetLowering::AtomicExpansionKind 12407 ARMTargetLowering::shouldExpandAtomicLoadInIR(LoadInst *LI) const { 12408 unsigned Size = LI->getType()->getPrimitiveSizeInBits(); 12409 return ((Size == 64) && !Subtarget->isMClass()) ? AtomicExpansionKind::LLOnly 12410 : AtomicExpansionKind::None; 12411 } 12412 12413 // For the real atomic operations, we have ldrex/strex up to 32 bits, 12414 // and up to 64 bits on the non-M profiles 12415 TargetLowering::AtomicExpansionKind 12416 ARMTargetLowering::shouldExpandAtomicRMWInIR(AtomicRMWInst *AI) const { 12417 unsigned Size = AI->getType()->getPrimitiveSizeInBits(); 12418 return (Size <= (Subtarget->isMClass() ? 32U : 64U)) 12419 ? AtomicExpansionKind::LLSC 12420 : AtomicExpansionKind::None; 12421 } 12422 12423 bool ARMTargetLowering::shouldExpandAtomicCmpXchgInIR( 12424 AtomicCmpXchgInst *AI) const { 12425 // At -O0, fast-regalloc cannot cope with the live vregs necessary to 12426 // implement cmpxchg without spilling. If the address being exchanged is also 12427 // on the stack and close enough to the spill slot, this can lead to a 12428 // situation where the monitor always gets cleared and the atomic operation 12429 // can never succeed. So at -O0 we need a late-expanded pseudo-inst instead. 12430 return getTargetMachine().getOptLevel() != 0; 12431 } 12432 12433 bool ARMTargetLowering::shouldInsertFencesForAtomic( 12434 const Instruction *I) const { 12435 return InsertFencesForAtomic; 12436 } 12437 12438 // This has so far only been implemented for MachO. 12439 bool ARMTargetLowering::useLoadStackGuardNode() const { 12440 return Subtarget->isTargetMachO(); 12441 } 12442 12443 bool ARMTargetLowering::canCombineStoreAndExtract(Type *VectorTy, Value *Idx, 12444 unsigned &Cost) const { 12445 // If we do not have NEON, vector types are not natively supported. 12446 if (!Subtarget->hasNEON()) 12447 return false; 12448 12449 // Floating point values and vector values map to the same register file. 12450 // Therefore, although we could do a store extract of a vector type, this is 12451 // better to leave at float as we have more freedom in the addressing mode for 12452 // those. 12453 if (VectorTy->isFPOrFPVectorTy()) 12454 return false; 12455 12456 // If the index is unknown at compile time, this is very expensive to lower 12457 // and it is not possible to combine the store with the extract. 12458 if (!isa<ConstantInt>(Idx)) 12459 return false; 12460 12461 assert(VectorTy->isVectorTy() && "VectorTy is not a vector type"); 12462 unsigned BitWidth = cast<VectorType>(VectorTy)->getBitWidth(); 12463 // We can do a store + vector extract on any vector that fits perfectly in a D 12464 // or Q register. 12465 if (BitWidth == 64 || BitWidth == 128) { 12466 Cost = 0; 12467 return true; 12468 } 12469 return false; 12470 } 12471 12472 bool ARMTargetLowering::isCheapToSpeculateCttz() const { 12473 return Subtarget->hasV6T2Ops(); 12474 } 12475 12476 bool ARMTargetLowering::isCheapToSpeculateCtlz() const { 12477 return Subtarget->hasV6T2Ops(); 12478 } 12479 12480 Value *ARMTargetLowering::emitLoadLinked(IRBuilder<> &Builder, Value *Addr, 12481 AtomicOrdering Ord) const { 12482 Module *M = Builder.GetInsertBlock()->getParent()->getParent(); 12483 Type *ValTy = cast<PointerType>(Addr->getType())->getElementType(); 12484 bool IsAcquire = isAcquireOrStronger(Ord); 12485 12486 // Since i64 isn't legal and intrinsics don't get type-lowered, the ldrexd 12487 // intrinsic must return {i32, i32} and we have to recombine them into a 12488 // single i64 here. 12489 if (ValTy->getPrimitiveSizeInBits() == 64) { 12490 Intrinsic::ID Int = 12491 IsAcquire ? Intrinsic::arm_ldaexd : Intrinsic::arm_ldrexd; 12492 Function *Ldrex = llvm::Intrinsic::getDeclaration(M, Int); 12493 12494 Addr = Builder.CreateBitCast(Addr, Type::getInt8PtrTy(M->getContext())); 12495 Value *LoHi = Builder.CreateCall(Ldrex, Addr, "lohi"); 12496 12497 Value *Lo = Builder.CreateExtractValue(LoHi, 0, "lo"); 12498 Value *Hi = Builder.CreateExtractValue(LoHi, 1, "hi"); 12499 if (!Subtarget->isLittle()) 12500 std::swap (Lo, Hi); 12501 Lo = Builder.CreateZExt(Lo, ValTy, "lo64"); 12502 Hi = Builder.CreateZExt(Hi, ValTy, "hi64"); 12503 return Builder.CreateOr( 12504 Lo, Builder.CreateShl(Hi, ConstantInt::get(ValTy, 32)), "val64"); 12505 } 12506 12507 Type *Tys[] = { Addr->getType() }; 12508 Intrinsic::ID Int = IsAcquire ? Intrinsic::arm_ldaex : Intrinsic::arm_ldrex; 12509 Function *Ldrex = llvm::Intrinsic::getDeclaration(M, Int, Tys); 12510 12511 return Builder.CreateTruncOrBitCast( 12512 Builder.CreateCall(Ldrex, Addr), 12513 cast<PointerType>(Addr->getType())->getElementType()); 12514 } 12515 12516 void ARMTargetLowering::emitAtomicCmpXchgNoStoreLLBalance( 12517 IRBuilder<> &Builder) const { 12518 if (!Subtarget->hasV7Ops()) 12519 return; 12520 Module *M = Builder.GetInsertBlock()->getParent()->getParent(); 12521 Builder.CreateCall(llvm::Intrinsic::getDeclaration(M, Intrinsic::arm_clrex)); 12522 } 12523 12524 Value *ARMTargetLowering::emitStoreConditional(IRBuilder<> &Builder, Value *Val, 12525 Value *Addr, 12526 AtomicOrdering Ord) const { 12527 Module *M = Builder.GetInsertBlock()->getParent()->getParent(); 12528 bool IsRelease = isReleaseOrStronger(Ord); 12529 12530 // Since the intrinsics must have legal type, the i64 intrinsics take two 12531 // parameters: "i32, i32". We must marshal Val into the appropriate form 12532 // before the call. 12533 if (Val->getType()->getPrimitiveSizeInBits() == 64) { 12534 Intrinsic::ID Int = 12535 IsRelease ? Intrinsic::arm_stlexd : Intrinsic::arm_strexd; 12536 Function *Strex = Intrinsic::getDeclaration(M, Int); 12537 Type *Int32Ty = Type::getInt32Ty(M->getContext()); 12538 12539 Value *Lo = Builder.CreateTrunc(Val, Int32Ty, "lo"); 12540 Value *Hi = Builder.CreateTrunc(Builder.CreateLShr(Val, 32), Int32Ty, "hi"); 12541 if (!Subtarget->isLittle()) 12542 std::swap (Lo, Hi); 12543 Addr = Builder.CreateBitCast(Addr, Type::getInt8PtrTy(M->getContext())); 12544 return Builder.CreateCall(Strex, {Lo, Hi, Addr}); 12545 } 12546 12547 Intrinsic::ID Int = IsRelease ? Intrinsic::arm_stlex : Intrinsic::arm_strex; 12548 Type *Tys[] = { Addr->getType() }; 12549 Function *Strex = Intrinsic::getDeclaration(M, Int, Tys); 12550 12551 return Builder.CreateCall( 12552 Strex, {Builder.CreateZExtOrBitCast( 12553 Val, Strex->getFunctionType()->getParamType(0)), 12554 Addr}); 12555 } 12556 12557 /// \brief Lower an interleaved load into a vldN intrinsic. 12558 /// 12559 /// E.g. Lower an interleaved load (Factor = 2): 12560 /// %wide.vec = load <8 x i32>, <8 x i32>* %ptr, align 4 12561 /// %v0 = shuffle %wide.vec, undef, <0, 2, 4, 6> ; Extract even elements 12562 /// %v1 = shuffle %wide.vec, undef, <1, 3, 5, 7> ; Extract odd elements 12563 /// 12564 /// Into: 12565 /// %vld2 = { <4 x i32>, <4 x i32> } call llvm.arm.neon.vld2(%ptr, 4) 12566 /// %vec0 = extractelement { <4 x i32>, <4 x i32> } %vld2, i32 0 12567 /// %vec1 = extractelement { <4 x i32>, <4 x i32> } %vld2, i32 1 12568 bool ARMTargetLowering::lowerInterleavedLoad( 12569 LoadInst *LI, ArrayRef<ShuffleVectorInst *> Shuffles, 12570 ArrayRef<unsigned> Indices, unsigned Factor) const { 12571 assert(Factor >= 2 && Factor <= getMaxSupportedInterleaveFactor() && 12572 "Invalid interleave factor"); 12573 assert(!Shuffles.empty() && "Empty shufflevector input"); 12574 assert(Shuffles.size() == Indices.size() && 12575 "Unmatched number of shufflevectors and indices"); 12576 12577 VectorType *VecTy = Shuffles[0]->getType(); 12578 Type *EltTy = VecTy->getVectorElementType(); 12579 12580 const DataLayout &DL = LI->getModule()->getDataLayout(); 12581 unsigned VecSize = DL.getTypeSizeInBits(VecTy); 12582 bool EltIs64Bits = DL.getTypeSizeInBits(EltTy) == 64; 12583 12584 // Skip if we do not have NEON and skip illegal vector types and vector types 12585 // with i64/f64 elements (vldN doesn't support i64/f64 elements). 12586 if (!Subtarget->hasNEON() || (VecSize != 64 && VecSize != 128) || EltIs64Bits) 12587 return false; 12588 12589 // A pointer vector can not be the return type of the ldN intrinsics. Need to 12590 // load integer vectors first and then convert to pointer vectors. 12591 if (EltTy->isPointerTy()) 12592 VecTy = 12593 VectorType::get(DL.getIntPtrType(EltTy), VecTy->getVectorNumElements()); 12594 12595 static const Intrinsic::ID LoadInts[3] = {Intrinsic::arm_neon_vld2, 12596 Intrinsic::arm_neon_vld3, 12597 Intrinsic::arm_neon_vld4}; 12598 12599 IRBuilder<> Builder(LI); 12600 SmallVector<Value *, 2> Ops; 12601 12602 Type *Int8Ptr = Builder.getInt8PtrTy(LI->getPointerAddressSpace()); 12603 Ops.push_back(Builder.CreateBitCast(LI->getPointerOperand(), Int8Ptr)); 12604 Ops.push_back(Builder.getInt32(LI->getAlignment())); 12605 12606 Type *Tys[] = { VecTy, Int8Ptr }; 12607 Function *VldnFunc = 12608 Intrinsic::getDeclaration(LI->getModule(), LoadInts[Factor - 2], Tys); 12609 CallInst *VldN = Builder.CreateCall(VldnFunc, Ops, "vldN"); 12610 12611 // Replace uses of each shufflevector with the corresponding vector loaded 12612 // by ldN. 12613 for (unsigned i = 0; i < Shuffles.size(); i++) { 12614 ShuffleVectorInst *SV = Shuffles[i]; 12615 unsigned Index = Indices[i]; 12616 12617 Value *SubVec = Builder.CreateExtractValue(VldN, Index); 12618 12619 // Convert the integer vector to pointer vector if the element is pointer. 12620 if (EltTy->isPointerTy()) 12621 SubVec = Builder.CreateIntToPtr(SubVec, SV->getType()); 12622 12623 SV->replaceAllUsesWith(SubVec); 12624 } 12625 12626 return true; 12627 } 12628 12629 /// \brief Get a mask consisting of sequential integers starting from \p Start. 12630 /// 12631 /// I.e. <Start, Start + 1, ..., Start + NumElts - 1> 12632 static Constant *getSequentialMask(IRBuilder<> &Builder, unsigned Start, 12633 unsigned NumElts) { 12634 SmallVector<Constant *, 16> Mask; 12635 for (unsigned i = 0; i < NumElts; i++) 12636 Mask.push_back(Builder.getInt32(Start + i)); 12637 12638 return ConstantVector::get(Mask); 12639 } 12640 12641 /// \brief Lower an interleaved store into a vstN intrinsic. 12642 /// 12643 /// E.g. Lower an interleaved store (Factor = 3): 12644 /// %i.vec = shuffle <8 x i32> %v0, <8 x i32> %v1, 12645 /// <0, 4, 8, 1, 5, 9, 2, 6, 10, 3, 7, 11> 12646 /// store <12 x i32> %i.vec, <12 x i32>* %ptr, align 4 12647 /// 12648 /// Into: 12649 /// %sub.v0 = shuffle <8 x i32> %v0, <8 x i32> v1, <0, 1, 2, 3> 12650 /// %sub.v1 = shuffle <8 x i32> %v0, <8 x i32> v1, <4, 5, 6, 7> 12651 /// %sub.v2 = shuffle <8 x i32> %v0, <8 x i32> v1, <8, 9, 10, 11> 12652 /// call void llvm.arm.neon.vst3(%ptr, %sub.v0, %sub.v1, %sub.v2, 4) 12653 /// 12654 /// Note that the new shufflevectors will be removed and we'll only generate one 12655 /// vst3 instruction in CodeGen. 12656 bool ARMTargetLowering::lowerInterleavedStore(StoreInst *SI, 12657 ShuffleVectorInst *SVI, 12658 unsigned Factor) const { 12659 assert(Factor >= 2 && Factor <= getMaxSupportedInterleaveFactor() && 12660 "Invalid interleave factor"); 12661 12662 VectorType *VecTy = SVI->getType(); 12663 assert(VecTy->getVectorNumElements() % Factor == 0 && 12664 "Invalid interleaved store"); 12665 12666 unsigned NumSubElts = VecTy->getVectorNumElements() / Factor; 12667 Type *EltTy = VecTy->getVectorElementType(); 12668 VectorType *SubVecTy = VectorType::get(EltTy, NumSubElts); 12669 12670 const DataLayout &DL = SI->getModule()->getDataLayout(); 12671 unsigned SubVecSize = DL.getTypeSizeInBits(SubVecTy); 12672 bool EltIs64Bits = DL.getTypeSizeInBits(EltTy) == 64; 12673 12674 // Skip if we do not have NEON and skip illegal vector types and vector types 12675 // with i64/f64 elements (vstN doesn't support i64/f64 elements). 12676 if (!Subtarget->hasNEON() || (SubVecSize != 64 && SubVecSize != 128) || 12677 EltIs64Bits) 12678 return false; 12679 12680 Value *Op0 = SVI->getOperand(0); 12681 Value *Op1 = SVI->getOperand(1); 12682 IRBuilder<> Builder(SI); 12683 12684 // StN intrinsics don't support pointer vectors as arguments. Convert pointer 12685 // vectors to integer vectors. 12686 if (EltTy->isPointerTy()) { 12687 Type *IntTy = DL.getIntPtrType(EltTy); 12688 12689 // Convert to the corresponding integer vector. 12690 Type *IntVecTy = 12691 VectorType::get(IntTy, Op0->getType()->getVectorNumElements()); 12692 Op0 = Builder.CreatePtrToInt(Op0, IntVecTy); 12693 Op1 = Builder.CreatePtrToInt(Op1, IntVecTy); 12694 12695 SubVecTy = VectorType::get(IntTy, NumSubElts); 12696 } 12697 12698 static const Intrinsic::ID StoreInts[3] = {Intrinsic::arm_neon_vst2, 12699 Intrinsic::arm_neon_vst3, 12700 Intrinsic::arm_neon_vst4}; 12701 SmallVector<Value *, 6> Ops; 12702 12703 Type *Int8Ptr = Builder.getInt8PtrTy(SI->getPointerAddressSpace()); 12704 Ops.push_back(Builder.CreateBitCast(SI->getPointerOperand(), Int8Ptr)); 12705 12706 Type *Tys[] = { Int8Ptr, SubVecTy }; 12707 Function *VstNFunc = Intrinsic::getDeclaration( 12708 SI->getModule(), StoreInts[Factor - 2], Tys); 12709 12710 // Split the shufflevector operands into sub vectors for the new vstN call. 12711 for (unsigned i = 0; i < Factor; i++) 12712 Ops.push_back(Builder.CreateShuffleVector( 12713 Op0, Op1, getSequentialMask(Builder, NumSubElts * i, NumSubElts))); 12714 12715 Ops.push_back(Builder.getInt32(SI->getAlignment())); 12716 Builder.CreateCall(VstNFunc, Ops); 12717 return true; 12718 } 12719 12720 enum HABaseType { 12721 HA_UNKNOWN = 0, 12722 HA_FLOAT, 12723 HA_DOUBLE, 12724 HA_VECT64, 12725 HA_VECT128 12726 }; 12727 12728 static bool isHomogeneousAggregate(Type *Ty, HABaseType &Base, 12729 uint64_t &Members) { 12730 if (auto *ST = dyn_cast<StructType>(Ty)) { 12731 for (unsigned i = 0; i < ST->getNumElements(); ++i) { 12732 uint64_t SubMembers = 0; 12733 if (!isHomogeneousAggregate(ST->getElementType(i), Base, SubMembers)) 12734 return false; 12735 Members += SubMembers; 12736 } 12737 } else if (auto *AT = dyn_cast<ArrayType>(Ty)) { 12738 uint64_t SubMembers = 0; 12739 if (!isHomogeneousAggregate(AT->getElementType(), Base, SubMembers)) 12740 return false; 12741 Members += SubMembers * AT->getNumElements(); 12742 } else if (Ty->isFloatTy()) { 12743 if (Base != HA_UNKNOWN && Base != HA_FLOAT) 12744 return false; 12745 Members = 1; 12746 Base = HA_FLOAT; 12747 } else if (Ty->isDoubleTy()) { 12748 if (Base != HA_UNKNOWN && Base != HA_DOUBLE) 12749 return false; 12750 Members = 1; 12751 Base = HA_DOUBLE; 12752 } else if (auto *VT = dyn_cast<VectorType>(Ty)) { 12753 Members = 1; 12754 switch (Base) { 12755 case HA_FLOAT: 12756 case HA_DOUBLE: 12757 return false; 12758 case HA_VECT64: 12759 return VT->getBitWidth() == 64; 12760 case HA_VECT128: 12761 return VT->getBitWidth() == 128; 12762 case HA_UNKNOWN: 12763 switch (VT->getBitWidth()) { 12764 case 64: 12765 Base = HA_VECT64; 12766 return true; 12767 case 128: 12768 Base = HA_VECT128; 12769 return true; 12770 default: 12771 return false; 12772 } 12773 } 12774 } 12775 12776 return (Members > 0 && Members <= 4); 12777 } 12778 12779 /// \brief Return true if a type is an AAPCS-VFP homogeneous aggregate or one of 12780 /// [N x i32] or [N x i64]. This allows front-ends to skip emitting padding when 12781 /// passing according to AAPCS rules. 12782 bool ARMTargetLowering::functionArgumentNeedsConsecutiveRegisters( 12783 Type *Ty, CallingConv::ID CallConv, bool isVarArg) const { 12784 if (getEffectiveCallingConv(CallConv, isVarArg) != 12785 CallingConv::ARM_AAPCS_VFP) 12786 return false; 12787 12788 HABaseType Base = HA_UNKNOWN; 12789 uint64_t Members = 0; 12790 bool IsHA = isHomogeneousAggregate(Ty, Base, Members); 12791 DEBUG(dbgs() << "isHA: " << IsHA << " "; Ty->dump()); 12792 12793 bool IsIntArray = Ty->isArrayTy() && Ty->getArrayElementType()->isIntegerTy(); 12794 return IsHA || IsIntArray; 12795 } 12796 12797 unsigned ARMTargetLowering::getExceptionPointerRegister( 12798 const Constant *PersonalityFn) const { 12799 // Platforms which do not use SjLj EH may return values in these registers 12800 // via the personality function. 12801 return Subtarget->useSjLjEH() ? ARM::NoRegister : ARM::R0; 12802 } 12803 12804 unsigned ARMTargetLowering::getExceptionSelectorRegister( 12805 const Constant *PersonalityFn) const { 12806 // Platforms which do not use SjLj EH may return values in these registers 12807 // via the personality function. 12808 return Subtarget->useSjLjEH() ? ARM::NoRegister : ARM::R1; 12809 } 12810 12811 void ARMTargetLowering::initializeSplitCSR(MachineBasicBlock *Entry) const { 12812 // Update IsSplitCSR in ARMFunctionInfo. 12813 ARMFunctionInfo *AFI = Entry->getParent()->getInfo<ARMFunctionInfo>(); 12814 AFI->setIsSplitCSR(true); 12815 } 12816 12817 void ARMTargetLowering::insertCopiesSplitCSR( 12818 MachineBasicBlock *Entry, 12819 const SmallVectorImpl<MachineBasicBlock *> &Exits) const { 12820 const ARMBaseRegisterInfo *TRI = Subtarget->getRegisterInfo(); 12821 const MCPhysReg *IStart = TRI->getCalleeSavedRegsViaCopy(Entry->getParent()); 12822 if (!IStart) 12823 return; 12824 12825 const TargetInstrInfo *TII = Subtarget->getInstrInfo(); 12826 MachineRegisterInfo *MRI = &Entry->getParent()->getRegInfo(); 12827 MachineBasicBlock::iterator MBBI = Entry->begin(); 12828 for (const MCPhysReg *I = IStart; *I; ++I) { 12829 const TargetRegisterClass *RC = nullptr; 12830 if (ARM::GPRRegClass.contains(*I)) 12831 RC = &ARM::GPRRegClass; 12832 else if (ARM::DPRRegClass.contains(*I)) 12833 RC = &ARM::DPRRegClass; 12834 else 12835 llvm_unreachable("Unexpected register class in CSRsViaCopy!"); 12836 12837 unsigned NewVR = MRI->createVirtualRegister(RC); 12838 // Create copy from CSR to a virtual register. 12839 // FIXME: this currently does not emit CFI pseudo-instructions, it works 12840 // fine for CXX_FAST_TLS since the C++-style TLS access functions should be 12841 // nounwind. If we want to generalize this later, we may need to emit 12842 // CFI pseudo-instructions. 12843 assert(Entry->getParent()->getFunction()->hasFnAttribute( 12844 Attribute::NoUnwind) && 12845 "Function should be nounwind in insertCopiesSplitCSR!"); 12846 Entry->addLiveIn(*I); 12847 BuildMI(*Entry, MBBI, DebugLoc(), TII->get(TargetOpcode::COPY), NewVR) 12848 .addReg(*I); 12849 12850 // Insert the copy-back instructions right before the terminator. 12851 for (auto *Exit : Exits) 12852 BuildMI(*Exit, Exit->getFirstTerminator(), DebugLoc(), 12853 TII->get(TargetOpcode::COPY), *I) 12854 .addReg(NewVR); 12855 } 12856 } 12857