1 //===-- ARMISelLowering.cpp - ARM DAG Lowering Implementation -------------===// 2 // 3 // The LLVM Compiler Infrastructure 4 // 5 // This file is distributed under the University of Illinois Open Source 6 // License. See LICENSE.TXT for details. 7 // 8 //===----------------------------------------------------------------------===// 9 // 10 // This file defines the interfaces that ARM uses to lower LLVM code into a 11 // selection DAG. 12 // 13 //===----------------------------------------------------------------------===// 14 15 #include "ARMISelLowering.h" 16 #include "ARMCallingConv.h" 17 #include "ARMConstantPoolValue.h" 18 #include "ARMMachineFunctionInfo.h" 19 #include "ARMPerfectShuffle.h" 20 #include "ARMSubtarget.h" 21 #include "ARMTargetMachine.h" 22 #include "ARMTargetObjectFile.h" 23 #include "MCTargetDesc/ARMAddressingModes.h" 24 #include "llvm/ADT/Statistic.h" 25 #include "llvm/ADT/StringExtras.h" 26 #include "llvm/ADT/StringSwitch.h" 27 #include "llvm/CodeGen/CallingConvLower.h" 28 #include "llvm/CodeGen/IntrinsicLowering.h" 29 #include "llvm/CodeGen/MachineBasicBlock.h" 30 #include "llvm/CodeGen/MachineFrameInfo.h" 31 #include "llvm/CodeGen/MachineFunction.h" 32 #include "llvm/CodeGen/MachineInstrBuilder.h" 33 #include "llvm/CodeGen/MachineJumpTableInfo.h" 34 #include "llvm/CodeGen/MachineModuleInfo.h" 35 #include "llvm/CodeGen/MachineRegisterInfo.h" 36 #include "llvm/CodeGen/SelectionDAG.h" 37 #include "llvm/IR/CallingConv.h" 38 #include "llvm/IR/Constants.h" 39 #include "llvm/IR/Function.h" 40 #include "llvm/IR/GlobalValue.h" 41 #include "llvm/IR/IRBuilder.h" 42 #include "llvm/IR/Instruction.h" 43 #include "llvm/IR/Instructions.h" 44 #include "llvm/IR/IntrinsicInst.h" 45 #include "llvm/IR/Intrinsics.h" 46 #include "llvm/IR/Type.h" 47 #include "llvm/MC/MCSectionMachO.h" 48 #include "llvm/Support/CommandLine.h" 49 #include "llvm/Support/Debug.h" 50 #include "llvm/Support/ErrorHandling.h" 51 #include "llvm/Support/MathExtras.h" 52 #include "llvm/Support/raw_ostream.h" 53 #include "llvm/Target/TargetOptions.h" 54 #include <utility> 55 using namespace llvm; 56 57 #define DEBUG_TYPE "arm-isel" 58 59 STATISTIC(NumTailCalls, "Number of tail calls"); 60 STATISTIC(NumMovwMovt, "Number of GAs materialized with movw + movt"); 61 STATISTIC(NumLoopByVals, "Number of loops generated for byval arguments"); 62 63 static cl::opt<bool> 64 ARMInterworking("arm-interworking", cl::Hidden, 65 cl::desc("Enable / disable ARM interworking (for debugging only)"), 66 cl::init(true)); 67 68 namespace { 69 class ARMCCState : public CCState { 70 public: 71 ARMCCState(CallingConv::ID CC, bool isVarArg, MachineFunction &MF, 72 SmallVectorImpl<CCValAssign> &locs, LLVMContext &C, 73 ParmContext PC) 74 : CCState(CC, isVarArg, MF, locs, C) { 75 assert(((PC == Call) || (PC == Prologue)) && 76 "ARMCCState users must specify whether their context is call" 77 "or prologue generation."); 78 CallOrPrologue = PC; 79 } 80 }; 81 } 82 83 // The APCS parameter registers. 84 static const MCPhysReg GPRArgRegs[] = { 85 ARM::R0, ARM::R1, ARM::R2, ARM::R3 86 }; 87 88 void ARMTargetLowering::addTypeForNEON(MVT VT, MVT PromotedLdStVT, 89 MVT PromotedBitwiseVT) { 90 if (VT != PromotedLdStVT) { 91 setOperationAction(ISD::LOAD, VT, Promote); 92 AddPromotedToType (ISD::LOAD, VT, PromotedLdStVT); 93 94 setOperationAction(ISD::STORE, VT, Promote); 95 AddPromotedToType (ISD::STORE, VT, PromotedLdStVT); 96 } 97 98 MVT ElemTy = VT.getVectorElementType(); 99 if (ElemTy != MVT::i64 && ElemTy != MVT::f64) 100 setOperationAction(ISD::SETCC, VT, Custom); 101 setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Custom); 102 setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom); 103 if (ElemTy == MVT::i32) { 104 setOperationAction(ISD::SINT_TO_FP, VT, Custom); 105 setOperationAction(ISD::UINT_TO_FP, VT, Custom); 106 setOperationAction(ISD::FP_TO_SINT, VT, Custom); 107 setOperationAction(ISD::FP_TO_UINT, VT, Custom); 108 } else { 109 setOperationAction(ISD::SINT_TO_FP, VT, Expand); 110 setOperationAction(ISD::UINT_TO_FP, VT, Expand); 111 setOperationAction(ISD::FP_TO_SINT, VT, Expand); 112 setOperationAction(ISD::FP_TO_UINT, VT, Expand); 113 } 114 setOperationAction(ISD::BUILD_VECTOR, VT, Custom); 115 setOperationAction(ISD::VECTOR_SHUFFLE, VT, Custom); 116 setOperationAction(ISD::CONCAT_VECTORS, VT, Legal); 117 setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Legal); 118 setOperationAction(ISD::SELECT, VT, Expand); 119 setOperationAction(ISD::SELECT_CC, VT, Expand); 120 setOperationAction(ISD::VSELECT, VT, Expand); 121 setOperationAction(ISD::SIGN_EXTEND_INREG, VT, Expand); 122 if (VT.isInteger()) { 123 setOperationAction(ISD::SHL, VT, Custom); 124 setOperationAction(ISD::SRA, VT, Custom); 125 setOperationAction(ISD::SRL, VT, Custom); 126 } 127 128 // Promote all bit-wise operations. 129 if (VT.isInteger() && VT != PromotedBitwiseVT) { 130 setOperationAction(ISD::AND, VT, Promote); 131 AddPromotedToType (ISD::AND, VT, PromotedBitwiseVT); 132 setOperationAction(ISD::OR, VT, Promote); 133 AddPromotedToType (ISD::OR, VT, PromotedBitwiseVT); 134 setOperationAction(ISD::XOR, VT, Promote); 135 AddPromotedToType (ISD::XOR, VT, PromotedBitwiseVT); 136 } 137 138 // Neon does not support vector divide/remainder operations. 139 setOperationAction(ISD::SDIV, VT, Expand); 140 setOperationAction(ISD::UDIV, VT, Expand); 141 setOperationAction(ISD::FDIV, VT, Expand); 142 setOperationAction(ISD::SREM, VT, Expand); 143 setOperationAction(ISD::UREM, VT, Expand); 144 setOperationAction(ISD::FREM, VT, Expand); 145 146 if (!VT.isFloatingPoint() && 147 VT != MVT::v2i64 && VT != MVT::v1i64) 148 for (unsigned Opcode : {ISD::SMIN, ISD::SMAX, ISD::UMIN, ISD::UMAX}) 149 setOperationAction(Opcode, VT, Legal); 150 } 151 152 void ARMTargetLowering::addDRTypeForNEON(MVT VT) { 153 addRegisterClass(VT, &ARM::DPRRegClass); 154 addTypeForNEON(VT, MVT::f64, MVT::v2i32); 155 } 156 157 void ARMTargetLowering::addQRTypeForNEON(MVT VT) { 158 addRegisterClass(VT, &ARM::DPairRegClass); 159 addTypeForNEON(VT, MVT::v2f64, MVT::v4i32); 160 } 161 162 ARMTargetLowering::ARMTargetLowering(const TargetMachine &TM, 163 const ARMSubtarget &STI) 164 : TargetLowering(TM), Subtarget(&STI) { 165 RegInfo = Subtarget->getRegisterInfo(); 166 Itins = Subtarget->getInstrItineraryData(); 167 168 setBooleanVectorContents(ZeroOrNegativeOneBooleanContent); 169 170 if (Subtarget->isTargetMachO()) { 171 // Uses VFP for Thumb libfuncs if available. 172 if (Subtarget->isThumb() && Subtarget->hasVFP2() && 173 Subtarget->hasARMOps() && !Subtarget->useSoftFloat()) { 174 static const struct { 175 const RTLIB::Libcall Op; 176 const char * const Name; 177 const ISD::CondCode Cond; 178 } LibraryCalls[] = { 179 // Single-precision floating-point arithmetic. 180 { RTLIB::ADD_F32, "__addsf3vfp", ISD::SETCC_INVALID }, 181 { RTLIB::SUB_F32, "__subsf3vfp", ISD::SETCC_INVALID }, 182 { RTLIB::MUL_F32, "__mulsf3vfp", ISD::SETCC_INVALID }, 183 { RTLIB::DIV_F32, "__divsf3vfp", ISD::SETCC_INVALID }, 184 185 // Double-precision floating-point arithmetic. 186 { RTLIB::ADD_F64, "__adddf3vfp", ISD::SETCC_INVALID }, 187 { RTLIB::SUB_F64, "__subdf3vfp", ISD::SETCC_INVALID }, 188 { RTLIB::MUL_F64, "__muldf3vfp", ISD::SETCC_INVALID }, 189 { RTLIB::DIV_F64, "__divdf3vfp", ISD::SETCC_INVALID }, 190 191 // Single-precision comparisons. 192 { RTLIB::OEQ_F32, "__eqsf2vfp", ISD::SETNE }, 193 { RTLIB::UNE_F32, "__nesf2vfp", ISD::SETNE }, 194 { RTLIB::OLT_F32, "__ltsf2vfp", ISD::SETNE }, 195 { RTLIB::OLE_F32, "__lesf2vfp", ISD::SETNE }, 196 { RTLIB::OGE_F32, "__gesf2vfp", ISD::SETNE }, 197 { RTLIB::OGT_F32, "__gtsf2vfp", ISD::SETNE }, 198 { RTLIB::UO_F32, "__unordsf2vfp", ISD::SETNE }, 199 { RTLIB::O_F32, "__unordsf2vfp", ISD::SETEQ }, 200 201 // Double-precision comparisons. 202 { RTLIB::OEQ_F64, "__eqdf2vfp", ISD::SETNE }, 203 { RTLIB::UNE_F64, "__nedf2vfp", ISD::SETNE }, 204 { RTLIB::OLT_F64, "__ltdf2vfp", ISD::SETNE }, 205 { RTLIB::OLE_F64, "__ledf2vfp", ISD::SETNE }, 206 { RTLIB::OGE_F64, "__gedf2vfp", ISD::SETNE }, 207 { RTLIB::OGT_F64, "__gtdf2vfp", ISD::SETNE }, 208 { RTLIB::UO_F64, "__unorddf2vfp", ISD::SETNE }, 209 { RTLIB::O_F64, "__unorddf2vfp", ISD::SETEQ }, 210 211 // Floating-point to integer conversions. 212 // i64 conversions are done via library routines even when generating VFP 213 // instructions, so use the same ones. 214 { RTLIB::FPTOSINT_F64_I32, "__fixdfsivfp", ISD::SETCC_INVALID }, 215 { RTLIB::FPTOUINT_F64_I32, "__fixunsdfsivfp", ISD::SETCC_INVALID }, 216 { RTLIB::FPTOSINT_F32_I32, "__fixsfsivfp", ISD::SETCC_INVALID }, 217 { RTLIB::FPTOUINT_F32_I32, "__fixunssfsivfp", ISD::SETCC_INVALID }, 218 219 // Conversions between floating types. 220 { RTLIB::FPROUND_F64_F32, "__truncdfsf2vfp", ISD::SETCC_INVALID }, 221 { RTLIB::FPEXT_F32_F64, "__extendsfdf2vfp", ISD::SETCC_INVALID }, 222 223 // Integer to floating-point conversions. 224 // i64 conversions are done via library routines even when generating VFP 225 // instructions, so use the same ones. 226 // FIXME: There appears to be some naming inconsistency in ARM libgcc: 227 // e.g., __floatunsidf vs. __floatunssidfvfp. 228 { RTLIB::SINTTOFP_I32_F64, "__floatsidfvfp", ISD::SETCC_INVALID }, 229 { RTLIB::UINTTOFP_I32_F64, "__floatunssidfvfp", ISD::SETCC_INVALID }, 230 { RTLIB::SINTTOFP_I32_F32, "__floatsisfvfp", ISD::SETCC_INVALID }, 231 { RTLIB::UINTTOFP_I32_F32, "__floatunssisfvfp", ISD::SETCC_INVALID }, 232 }; 233 234 for (const auto &LC : LibraryCalls) { 235 setLibcallName(LC.Op, LC.Name); 236 if (LC.Cond != ISD::SETCC_INVALID) 237 setCmpLibcallCC(LC.Op, LC.Cond); 238 } 239 } 240 241 // Set the correct calling convention for ARMv7k WatchOS. It's just 242 // AAPCS_VFP for functions as simple as libcalls. 243 if (Subtarget->isTargetWatchABI()) { 244 for (int i = 0; i < RTLIB::UNKNOWN_LIBCALL; ++i) 245 setLibcallCallingConv((RTLIB::Libcall)i, CallingConv::ARM_AAPCS_VFP); 246 } 247 } 248 249 // These libcalls are not available in 32-bit. 250 setLibcallName(RTLIB::SHL_I128, nullptr); 251 setLibcallName(RTLIB::SRL_I128, nullptr); 252 setLibcallName(RTLIB::SRA_I128, nullptr); 253 254 // RTLIB 255 if (Subtarget->isAAPCS_ABI() && 256 (Subtarget->isTargetAEABI() || Subtarget->isTargetGNUAEABI() || 257 Subtarget->isTargetAndroid())) { 258 static const struct { 259 const RTLIB::Libcall Op; 260 const char * const Name; 261 const CallingConv::ID CC; 262 const ISD::CondCode Cond; 263 } LibraryCalls[] = { 264 // Double-precision floating-point arithmetic helper functions 265 // RTABI chapter 4.1.2, Table 2 266 { RTLIB::ADD_F64, "__aeabi_dadd", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 267 { RTLIB::DIV_F64, "__aeabi_ddiv", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 268 { RTLIB::MUL_F64, "__aeabi_dmul", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 269 { RTLIB::SUB_F64, "__aeabi_dsub", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 270 271 // Double-precision floating-point comparison helper functions 272 // RTABI chapter 4.1.2, Table 3 273 { RTLIB::OEQ_F64, "__aeabi_dcmpeq", CallingConv::ARM_AAPCS, ISD::SETNE }, 274 { RTLIB::UNE_F64, "__aeabi_dcmpeq", CallingConv::ARM_AAPCS, ISD::SETEQ }, 275 { RTLIB::OLT_F64, "__aeabi_dcmplt", CallingConv::ARM_AAPCS, ISD::SETNE }, 276 { RTLIB::OLE_F64, "__aeabi_dcmple", CallingConv::ARM_AAPCS, ISD::SETNE }, 277 { RTLIB::OGE_F64, "__aeabi_dcmpge", CallingConv::ARM_AAPCS, ISD::SETNE }, 278 { RTLIB::OGT_F64, "__aeabi_dcmpgt", CallingConv::ARM_AAPCS, ISD::SETNE }, 279 { RTLIB::UO_F64, "__aeabi_dcmpun", CallingConv::ARM_AAPCS, ISD::SETNE }, 280 { RTLIB::O_F64, "__aeabi_dcmpun", CallingConv::ARM_AAPCS, ISD::SETEQ }, 281 282 // Single-precision floating-point arithmetic helper functions 283 // RTABI chapter 4.1.2, Table 4 284 { RTLIB::ADD_F32, "__aeabi_fadd", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 285 { RTLIB::DIV_F32, "__aeabi_fdiv", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 286 { RTLIB::MUL_F32, "__aeabi_fmul", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 287 { RTLIB::SUB_F32, "__aeabi_fsub", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 288 289 // Single-precision floating-point comparison helper functions 290 // RTABI chapter 4.1.2, Table 5 291 { RTLIB::OEQ_F32, "__aeabi_fcmpeq", CallingConv::ARM_AAPCS, ISD::SETNE }, 292 { RTLIB::UNE_F32, "__aeabi_fcmpeq", CallingConv::ARM_AAPCS, ISD::SETEQ }, 293 { RTLIB::OLT_F32, "__aeabi_fcmplt", CallingConv::ARM_AAPCS, ISD::SETNE }, 294 { RTLIB::OLE_F32, "__aeabi_fcmple", CallingConv::ARM_AAPCS, ISD::SETNE }, 295 { RTLIB::OGE_F32, "__aeabi_fcmpge", CallingConv::ARM_AAPCS, ISD::SETNE }, 296 { RTLIB::OGT_F32, "__aeabi_fcmpgt", CallingConv::ARM_AAPCS, ISD::SETNE }, 297 { RTLIB::UO_F32, "__aeabi_fcmpun", CallingConv::ARM_AAPCS, ISD::SETNE }, 298 { RTLIB::O_F32, "__aeabi_fcmpun", CallingConv::ARM_AAPCS, ISD::SETEQ }, 299 300 // Floating-point to integer conversions. 301 // RTABI chapter 4.1.2, Table 6 302 { RTLIB::FPTOSINT_F64_I32, "__aeabi_d2iz", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 303 { RTLIB::FPTOUINT_F64_I32, "__aeabi_d2uiz", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 304 { RTLIB::FPTOSINT_F64_I64, "__aeabi_d2lz", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 305 { RTLIB::FPTOUINT_F64_I64, "__aeabi_d2ulz", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 306 { RTLIB::FPTOSINT_F32_I32, "__aeabi_f2iz", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 307 { RTLIB::FPTOUINT_F32_I32, "__aeabi_f2uiz", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 308 { RTLIB::FPTOSINT_F32_I64, "__aeabi_f2lz", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 309 { RTLIB::FPTOUINT_F32_I64, "__aeabi_f2ulz", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 310 311 // Conversions between floating types. 312 // RTABI chapter 4.1.2, Table 7 313 { RTLIB::FPROUND_F64_F32, "__aeabi_d2f", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 314 { RTLIB::FPROUND_F64_F16, "__aeabi_d2h", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 315 { RTLIB::FPEXT_F32_F64, "__aeabi_f2d", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 316 317 // Integer to floating-point conversions. 318 // RTABI chapter 4.1.2, Table 8 319 { RTLIB::SINTTOFP_I32_F64, "__aeabi_i2d", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 320 { RTLIB::UINTTOFP_I32_F64, "__aeabi_ui2d", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 321 { RTLIB::SINTTOFP_I64_F64, "__aeabi_l2d", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 322 { RTLIB::UINTTOFP_I64_F64, "__aeabi_ul2d", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 323 { RTLIB::SINTTOFP_I32_F32, "__aeabi_i2f", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 324 { RTLIB::UINTTOFP_I32_F32, "__aeabi_ui2f", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 325 { RTLIB::SINTTOFP_I64_F32, "__aeabi_l2f", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 326 { RTLIB::UINTTOFP_I64_F32, "__aeabi_ul2f", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 327 328 // Long long helper functions 329 // RTABI chapter 4.2, Table 9 330 { RTLIB::MUL_I64, "__aeabi_lmul", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 331 { RTLIB::SHL_I64, "__aeabi_llsl", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 332 { RTLIB::SRL_I64, "__aeabi_llsr", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 333 { RTLIB::SRA_I64, "__aeabi_lasr", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 334 335 // Integer division functions 336 // RTABI chapter 4.3.1 337 { RTLIB::SDIV_I8, "__aeabi_idiv", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 338 { RTLIB::SDIV_I16, "__aeabi_idiv", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 339 { RTLIB::SDIV_I32, "__aeabi_idiv", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 340 { RTLIB::SDIV_I64, "__aeabi_ldivmod", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 341 { RTLIB::UDIV_I8, "__aeabi_uidiv", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 342 { RTLIB::UDIV_I16, "__aeabi_uidiv", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 343 { RTLIB::UDIV_I32, "__aeabi_uidiv", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 344 { RTLIB::UDIV_I64, "__aeabi_uldivmod", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 345 }; 346 347 for (const auto &LC : LibraryCalls) { 348 setLibcallName(LC.Op, LC.Name); 349 setLibcallCallingConv(LC.Op, LC.CC); 350 if (LC.Cond != ISD::SETCC_INVALID) 351 setCmpLibcallCC(LC.Op, LC.Cond); 352 } 353 354 // EABI dependent RTLIB 355 if (TM.Options.EABIVersion == EABI::EABI4 || 356 TM.Options.EABIVersion == EABI::EABI5) { 357 static const struct { 358 const RTLIB::Libcall Op; 359 const char *const Name; 360 const CallingConv::ID CC; 361 const ISD::CondCode Cond; 362 } MemOpsLibraryCalls[] = { 363 // Memory operations 364 // RTABI chapter 4.3.4 365 { RTLIB::MEMCPY, "__aeabi_memcpy", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 366 { RTLIB::MEMMOVE, "__aeabi_memmove", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 367 { RTLIB::MEMSET, "__aeabi_memset", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 368 }; 369 370 for (const auto &LC : MemOpsLibraryCalls) { 371 setLibcallName(LC.Op, LC.Name); 372 setLibcallCallingConv(LC.Op, LC.CC); 373 if (LC.Cond != ISD::SETCC_INVALID) 374 setCmpLibcallCC(LC.Op, LC.Cond); 375 } 376 } 377 } 378 379 if (Subtarget->isTargetWindows()) { 380 static const struct { 381 const RTLIB::Libcall Op; 382 const char * const Name; 383 const CallingConv::ID CC; 384 } LibraryCalls[] = { 385 { RTLIB::FPTOSINT_F32_I64, "__stoi64", CallingConv::ARM_AAPCS_VFP }, 386 { RTLIB::FPTOSINT_F64_I64, "__dtoi64", CallingConv::ARM_AAPCS_VFP }, 387 { RTLIB::FPTOUINT_F32_I64, "__stou64", CallingConv::ARM_AAPCS_VFP }, 388 { RTLIB::FPTOUINT_F64_I64, "__dtou64", CallingConv::ARM_AAPCS_VFP }, 389 { RTLIB::SINTTOFP_I64_F32, "__i64tos", CallingConv::ARM_AAPCS_VFP }, 390 { RTLIB::SINTTOFP_I64_F64, "__i64tod", CallingConv::ARM_AAPCS_VFP }, 391 { RTLIB::UINTTOFP_I64_F32, "__u64tos", CallingConv::ARM_AAPCS_VFP }, 392 { RTLIB::UINTTOFP_I64_F64, "__u64tod", CallingConv::ARM_AAPCS_VFP }, 393 }; 394 395 for (const auto &LC : LibraryCalls) { 396 setLibcallName(LC.Op, LC.Name); 397 setLibcallCallingConv(LC.Op, LC.CC); 398 } 399 } 400 401 // Use divmod compiler-rt calls for iOS 5.0 and later. 402 if (Subtarget->isTargetWatchOS() || 403 (Subtarget->isTargetIOS() && 404 !Subtarget->getTargetTriple().isOSVersionLT(5, 0))) { 405 setLibcallName(RTLIB::SDIVREM_I32, "__divmodsi4"); 406 setLibcallName(RTLIB::UDIVREM_I32, "__udivmodsi4"); 407 } 408 409 // The half <-> float conversion functions are always soft-float, but are 410 // needed for some targets which use a hard-float calling convention by 411 // default. 412 if (Subtarget->isAAPCS_ABI()) { 413 setLibcallCallingConv(RTLIB::FPROUND_F32_F16, CallingConv::ARM_AAPCS); 414 setLibcallCallingConv(RTLIB::FPROUND_F64_F16, CallingConv::ARM_AAPCS); 415 setLibcallCallingConv(RTLIB::FPEXT_F16_F32, CallingConv::ARM_AAPCS); 416 } else { 417 setLibcallCallingConv(RTLIB::FPROUND_F32_F16, CallingConv::ARM_APCS); 418 setLibcallCallingConv(RTLIB::FPROUND_F64_F16, CallingConv::ARM_APCS); 419 setLibcallCallingConv(RTLIB::FPEXT_F16_F32, CallingConv::ARM_APCS); 420 } 421 422 // In EABI, these functions have an __aeabi_ prefix, but in GNUEABI they have 423 // a __gnu_ prefix (which is the default). 424 if (Subtarget->isTargetAEABI()) { 425 setLibcallName(RTLIB::FPROUND_F32_F16, "__aeabi_f2h"); 426 setLibcallName(RTLIB::FPROUND_F64_F16, "__aeabi_d2h"); 427 setLibcallName(RTLIB::FPEXT_F16_F32, "__aeabi_h2f"); 428 } 429 430 if (Subtarget->isThumb1Only()) 431 addRegisterClass(MVT::i32, &ARM::tGPRRegClass); 432 else 433 addRegisterClass(MVT::i32, &ARM::GPRRegClass); 434 if (!Subtarget->useSoftFloat() && Subtarget->hasVFP2() && 435 !Subtarget->isThumb1Only()) { 436 addRegisterClass(MVT::f32, &ARM::SPRRegClass); 437 addRegisterClass(MVT::f64, &ARM::DPRRegClass); 438 } 439 440 for (MVT VT : MVT::vector_valuetypes()) { 441 for (MVT InnerVT : MVT::vector_valuetypes()) { 442 setTruncStoreAction(VT, InnerVT, Expand); 443 setLoadExtAction(ISD::SEXTLOAD, VT, InnerVT, Expand); 444 setLoadExtAction(ISD::ZEXTLOAD, VT, InnerVT, Expand); 445 setLoadExtAction(ISD::EXTLOAD, VT, InnerVT, Expand); 446 } 447 448 setOperationAction(ISD::MULHS, VT, Expand); 449 setOperationAction(ISD::SMUL_LOHI, VT, Expand); 450 setOperationAction(ISD::MULHU, VT, Expand); 451 setOperationAction(ISD::UMUL_LOHI, VT, Expand); 452 453 setOperationAction(ISD::BSWAP, VT, Expand); 454 } 455 456 setOperationAction(ISD::ConstantFP, MVT::f32, Custom); 457 setOperationAction(ISD::ConstantFP, MVT::f64, Custom); 458 459 setOperationAction(ISD::READ_REGISTER, MVT::i64, Custom); 460 setOperationAction(ISD::WRITE_REGISTER, MVT::i64, Custom); 461 462 if (Subtarget->hasNEON()) { 463 addDRTypeForNEON(MVT::v2f32); 464 addDRTypeForNEON(MVT::v8i8); 465 addDRTypeForNEON(MVT::v4i16); 466 addDRTypeForNEON(MVT::v2i32); 467 addDRTypeForNEON(MVT::v1i64); 468 469 addQRTypeForNEON(MVT::v4f32); 470 addQRTypeForNEON(MVT::v2f64); 471 addQRTypeForNEON(MVT::v16i8); 472 addQRTypeForNEON(MVT::v8i16); 473 addQRTypeForNEON(MVT::v4i32); 474 addQRTypeForNEON(MVT::v2i64); 475 476 // v2f64 is legal so that QR subregs can be extracted as f64 elements, but 477 // neither Neon nor VFP support any arithmetic operations on it. 478 // The same with v4f32. But keep in mind that vadd, vsub, vmul are natively 479 // supported for v4f32. 480 setOperationAction(ISD::FADD, MVT::v2f64, Expand); 481 setOperationAction(ISD::FSUB, MVT::v2f64, Expand); 482 setOperationAction(ISD::FMUL, MVT::v2f64, Expand); 483 // FIXME: Code duplication: FDIV and FREM are expanded always, see 484 // ARMTargetLowering::addTypeForNEON method for details. 485 setOperationAction(ISD::FDIV, MVT::v2f64, Expand); 486 setOperationAction(ISD::FREM, MVT::v2f64, Expand); 487 // FIXME: Create unittest. 488 // In another words, find a way when "copysign" appears in DAG with vector 489 // operands. 490 setOperationAction(ISD::FCOPYSIGN, MVT::v2f64, Expand); 491 // FIXME: Code duplication: SETCC has custom operation action, see 492 // ARMTargetLowering::addTypeForNEON method for details. 493 setOperationAction(ISD::SETCC, MVT::v2f64, Expand); 494 // FIXME: Create unittest for FNEG and for FABS. 495 setOperationAction(ISD::FNEG, MVT::v2f64, Expand); 496 setOperationAction(ISD::FABS, MVT::v2f64, Expand); 497 setOperationAction(ISD::FSQRT, MVT::v2f64, Expand); 498 setOperationAction(ISD::FSIN, MVT::v2f64, Expand); 499 setOperationAction(ISD::FCOS, MVT::v2f64, Expand); 500 setOperationAction(ISD::FPOWI, MVT::v2f64, Expand); 501 setOperationAction(ISD::FPOW, MVT::v2f64, Expand); 502 setOperationAction(ISD::FLOG, MVT::v2f64, Expand); 503 setOperationAction(ISD::FLOG2, MVT::v2f64, Expand); 504 setOperationAction(ISD::FLOG10, MVT::v2f64, Expand); 505 setOperationAction(ISD::FEXP, MVT::v2f64, Expand); 506 setOperationAction(ISD::FEXP2, MVT::v2f64, Expand); 507 // FIXME: Create unittest for FCEIL, FTRUNC, FRINT, FNEARBYINT, FFLOOR. 508 setOperationAction(ISD::FCEIL, MVT::v2f64, Expand); 509 setOperationAction(ISD::FTRUNC, MVT::v2f64, Expand); 510 setOperationAction(ISD::FRINT, MVT::v2f64, Expand); 511 setOperationAction(ISD::FNEARBYINT, MVT::v2f64, Expand); 512 setOperationAction(ISD::FFLOOR, MVT::v2f64, Expand); 513 setOperationAction(ISD::FMA, MVT::v2f64, Expand); 514 515 setOperationAction(ISD::FSQRT, MVT::v4f32, Expand); 516 setOperationAction(ISD::FSIN, MVT::v4f32, Expand); 517 setOperationAction(ISD::FCOS, MVT::v4f32, Expand); 518 setOperationAction(ISD::FPOWI, MVT::v4f32, Expand); 519 setOperationAction(ISD::FPOW, MVT::v4f32, Expand); 520 setOperationAction(ISD::FLOG, MVT::v4f32, Expand); 521 setOperationAction(ISD::FLOG2, MVT::v4f32, Expand); 522 setOperationAction(ISD::FLOG10, MVT::v4f32, Expand); 523 setOperationAction(ISD::FEXP, MVT::v4f32, Expand); 524 setOperationAction(ISD::FEXP2, MVT::v4f32, Expand); 525 setOperationAction(ISD::FCEIL, MVT::v4f32, Expand); 526 setOperationAction(ISD::FTRUNC, MVT::v4f32, Expand); 527 setOperationAction(ISD::FRINT, MVT::v4f32, Expand); 528 setOperationAction(ISD::FNEARBYINT, MVT::v4f32, Expand); 529 setOperationAction(ISD::FFLOOR, MVT::v4f32, Expand); 530 531 // Mark v2f32 intrinsics. 532 setOperationAction(ISD::FSQRT, MVT::v2f32, Expand); 533 setOperationAction(ISD::FSIN, MVT::v2f32, Expand); 534 setOperationAction(ISD::FCOS, MVT::v2f32, Expand); 535 setOperationAction(ISD::FPOWI, MVT::v2f32, Expand); 536 setOperationAction(ISD::FPOW, MVT::v2f32, Expand); 537 setOperationAction(ISD::FLOG, MVT::v2f32, Expand); 538 setOperationAction(ISD::FLOG2, MVT::v2f32, Expand); 539 setOperationAction(ISD::FLOG10, MVT::v2f32, Expand); 540 setOperationAction(ISD::FEXP, MVT::v2f32, Expand); 541 setOperationAction(ISD::FEXP2, MVT::v2f32, Expand); 542 setOperationAction(ISD::FCEIL, MVT::v2f32, Expand); 543 setOperationAction(ISD::FTRUNC, MVT::v2f32, Expand); 544 setOperationAction(ISD::FRINT, MVT::v2f32, Expand); 545 setOperationAction(ISD::FNEARBYINT, MVT::v2f32, Expand); 546 setOperationAction(ISD::FFLOOR, MVT::v2f32, Expand); 547 548 // Neon does not support some operations on v1i64 and v2i64 types. 549 setOperationAction(ISD::MUL, MVT::v1i64, Expand); 550 // Custom handling for some quad-vector types to detect VMULL. 551 setOperationAction(ISD::MUL, MVT::v8i16, Custom); 552 setOperationAction(ISD::MUL, MVT::v4i32, Custom); 553 setOperationAction(ISD::MUL, MVT::v2i64, Custom); 554 // Custom handling for some vector types to avoid expensive expansions 555 setOperationAction(ISD::SDIV, MVT::v4i16, Custom); 556 setOperationAction(ISD::SDIV, MVT::v8i8, Custom); 557 setOperationAction(ISD::UDIV, MVT::v4i16, Custom); 558 setOperationAction(ISD::UDIV, MVT::v8i8, Custom); 559 setOperationAction(ISD::SETCC, MVT::v1i64, Expand); 560 setOperationAction(ISD::SETCC, MVT::v2i64, Expand); 561 // Neon does not have single instruction SINT_TO_FP and UINT_TO_FP with 562 // a destination type that is wider than the source, and nor does 563 // it have a FP_TO_[SU]INT instruction with a narrower destination than 564 // source. 565 setOperationAction(ISD::SINT_TO_FP, MVT::v4i16, Custom); 566 setOperationAction(ISD::UINT_TO_FP, MVT::v4i16, Custom); 567 setOperationAction(ISD::FP_TO_UINT, MVT::v4i16, Custom); 568 setOperationAction(ISD::FP_TO_SINT, MVT::v4i16, Custom); 569 570 setOperationAction(ISD::FP_ROUND, MVT::v2f32, Expand); 571 setOperationAction(ISD::FP_EXTEND, MVT::v2f64, Expand); 572 573 // NEON does not have single instruction CTPOP for vectors with element 574 // types wider than 8-bits. However, custom lowering can leverage the 575 // v8i8/v16i8 vcnt instruction. 576 setOperationAction(ISD::CTPOP, MVT::v2i32, Custom); 577 setOperationAction(ISD::CTPOP, MVT::v4i32, Custom); 578 setOperationAction(ISD::CTPOP, MVT::v4i16, Custom); 579 setOperationAction(ISD::CTPOP, MVT::v8i16, Custom); 580 581 // NEON does not have single instruction CTTZ for vectors. 582 setOperationAction(ISD::CTTZ, MVT::v8i8, Custom); 583 setOperationAction(ISD::CTTZ, MVT::v4i16, Custom); 584 setOperationAction(ISD::CTTZ, MVT::v2i32, Custom); 585 setOperationAction(ISD::CTTZ, MVT::v1i64, Custom); 586 587 setOperationAction(ISD::CTTZ, MVT::v16i8, Custom); 588 setOperationAction(ISD::CTTZ, MVT::v8i16, Custom); 589 setOperationAction(ISD::CTTZ, MVT::v4i32, Custom); 590 setOperationAction(ISD::CTTZ, MVT::v2i64, Custom); 591 592 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::v8i8, Custom); 593 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::v4i16, Custom); 594 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::v2i32, Custom); 595 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::v1i64, Custom); 596 597 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::v16i8, Custom); 598 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::v8i16, Custom); 599 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::v4i32, Custom); 600 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::v2i64, Custom); 601 602 // NEON only has FMA instructions as of VFP4. 603 if (!Subtarget->hasVFP4()) { 604 setOperationAction(ISD::FMA, MVT::v2f32, Expand); 605 setOperationAction(ISD::FMA, MVT::v4f32, Expand); 606 } 607 608 setTargetDAGCombine(ISD::INTRINSIC_VOID); 609 setTargetDAGCombine(ISD::INTRINSIC_W_CHAIN); 610 setTargetDAGCombine(ISD::INTRINSIC_WO_CHAIN); 611 setTargetDAGCombine(ISD::SHL); 612 setTargetDAGCombine(ISD::SRL); 613 setTargetDAGCombine(ISD::SRA); 614 setTargetDAGCombine(ISD::SIGN_EXTEND); 615 setTargetDAGCombine(ISD::ZERO_EXTEND); 616 setTargetDAGCombine(ISD::ANY_EXTEND); 617 setTargetDAGCombine(ISD::BUILD_VECTOR); 618 setTargetDAGCombine(ISD::VECTOR_SHUFFLE); 619 setTargetDAGCombine(ISD::INSERT_VECTOR_ELT); 620 setTargetDAGCombine(ISD::STORE); 621 setTargetDAGCombine(ISD::FP_TO_SINT); 622 setTargetDAGCombine(ISD::FP_TO_UINT); 623 setTargetDAGCombine(ISD::FDIV); 624 setTargetDAGCombine(ISD::LOAD); 625 626 // It is legal to extload from v4i8 to v4i16 or v4i32. 627 for (MVT Ty : {MVT::v8i8, MVT::v4i8, MVT::v2i8, MVT::v4i16, MVT::v2i16, 628 MVT::v2i32}) { 629 for (MVT VT : MVT::integer_vector_valuetypes()) { 630 setLoadExtAction(ISD::EXTLOAD, VT, Ty, Legal); 631 setLoadExtAction(ISD::ZEXTLOAD, VT, Ty, Legal); 632 setLoadExtAction(ISD::SEXTLOAD, VT, Ty, Legal); 633 } 634 } 635 } 636 637 // ARM and Thumb2 support UMLAL/SMLAL. 638 if (!Subtarget->isThumb1Only()) 639 setTargetDAGCombine(ISD::ADDC); 640 641 if (Subtarget->isFPOnlySP()) { 642 // When targeting a floating-point unit with only single-precision 643 // operations, f64 is legal for the few double-precision instructions which 644 // are present However, no double-precision operations other than moves, 645 // loads and stores are provided by the hardware. 646 setOperationAction(ISD::FADD, MVT::f64, Expand); 647 setOperationAction(ISD::FSUB, MVT::f64, Expand); 648 setOperationAction(ISD::FMUL, MVT::f64, Expand); 649 setOperationAction(ISD::FMA, MVT::f64, Expand); 650 setOperationAction(ISD::FDIV, MVT::f64, Expand); 651 setOperationAction(ISD::FREM, MVT::f64, Expand); 652 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand); 653 setOperationAction(ISD::FGETSIGN, MVT::f64, Expand); 654 setOperationAction(ISD::FNEG, MVT::f64, Expand); 655 setOperationAction(ISD::FABS, MVT::f64, Expand); 656 setOperationAction(ISD::FSQRT, MVT::f64, Expand); 657 setOperationAction(ISD::FSIN, MVT::f64, Expand); 658 setOperationAction(ISD::FCOS, MVT::f64, Expand); 659 setOperationAction(ISD::FPOWI, MVT::f64, Expand); 660 setOperationAction(ISD::FPOW, MVT::f64, Expand); 661 setOperationAction(ISD::FLOG, MVT::f64, Expand); 662 setOperationAction(ISD::FLOG2, MVT::f64, Expand); 663 setOperationAction(ISD::FLOG10, MVT::f64, Expand); 664 setOperationAction(ISD::FEXP, MVT::f64, Expand); 665 setOperationAction(ISD::FEXP2, MVT::f64, Expand); 666 setOperationAction(ISD::FCEIL, MVT::f64, Expand); 667 setOperationAction(ISD::FTRUNC, MVT::f64, Expand); 668 setOperationAction(ISD::FRINT, MVT::f64, Expand); 669 setOperationAction(ISD::FNEARBYINT, MVT::f64, Expand); 670 setOperationAction(ISD::FFLOOR, MVT::f64, Expand); 671 setOperationAction(ISD::SINT_TO_FP, MVT::i32, Custom); 672 setOperationAction(ISD::UINT_TO_FP, MVT::i32, Custom); 673 setOperationAction(ISD::FP_TO_SINT, MVT::i32, Custom); 674 setOperationAction(ISD::FP_TO_UINT, MVT::i32, Custom); 675 setOperationAction(ISD::FP_TO_SINT, MVT::f64, Custom); 676 setOperationAction(ISD::FP_TO_UINT, MVT::f64, Custom); 677 setOperationAction(ISD::FP_ROUND, MVT::f32, Custom); 678 setOperationAction(ISD::FP_EXTEND, MVT::f64, Custom); 679 } 680 681 computeRegisterProperties(Subtarget->getRegisterInfo()); 682 683 // ARM does not have floating-point extending loads. 684 for (MVT VT : MVT::fp_valuetypes()) { 685 setLoadExtAction(ISD::EXTLOAD, VT, MVT::f32, Expand); 686 setLoadExtAction(ISD::EXTLOAD, VT, MVT::f16, Expand); 687 } 688 689 // ... or truncating stores 690 setTruncStoreAction(MVT::f64, MVT::f32, Expand); 691 setTruncStoreAction(MVT::f32, MVT::f16, Expand); 692 setTruncStoreAction(MVT::f64, MVT::f16, Expand); 693 694 // ARM does not have i1 sign extending load. 695 for (MVT VT : MVT::integer_valuetypes()) 696 setLoadExtAction(ISD::SEXTLOAD, VT, MVT::i1, Promote); 697 698 // ARM supports all 4 flavors of integer indexed load / store. 699 if (!Subtarget->isThumb1Only()) { 700 for (unsigned im = (unsigned)ISD::PRE_INC; 701 im != (unsigned)ISD::LAST_INDEXED_MODE; ++im) { 702 setIndexedLoadAction(im, MVT::i1, Legal); 703 setIndexedLoadAction(im, MVT::i8, Legal); 704 setIndexedLoadAction(im, MVT::i16, Legal); 705 setIndexedLoadAction(im, MVT::i32, Legal); 706 setIndexedStoreAction(im, MVT::i1, Legal); 707 setIndexedStoreAction(im, MVT::i8, Legal); 708 setIndexedStoreAction(im, MVT::i16, Legal); 709 setIndexedStoreAction(im, MVT::i32, Legal); 710 } 711 } 712 713 setOperationAction(ISD::SADDO, MVT::i32, Custom); 714 setOperationAction(ISD::UADDO, MVT::i32, Custom); 715 setOperationAction(ISD::SSUBO, MVT::i32, Custom); 716 setOperationAction(ISD::USUBO, MVT::i32, Custom); 717 718 // i64 operation support. 719 setOperationAction(ISD::MUL, MVT::i64, Expand); 720 setOperationAction(ISD::MULHU, MVT::i32, Expand); 721 if (Subtarget->isThumb1Only()) { 722 setOperationAction(ISD::UMUL_LOHI, MVT::i32, Expand); 723 setOperationAction(ISD::SMUL_LOHI, MVT::i32, Expand); 724 } 725 if (Subtarget->isThumb1Only() || !Subtarget->hasV6Ops() 726 || (Subtarget->isThumb2() && !Subtarget->hasDSP())) 727 setOperationAction(ISD::MULHS, MVT::i32, Expand); 728 729 setOperationAction(ISD::SHL_PARTS, MVT::i32, Custom); 730 setOperationAction(ISD::SRA_PARTS, MVT::i32, Custom); 731 setOperationAction(ISD::SRL_PARTS, MVT::i32, Custom); 732 setOperationAction(ISD::SRL, MVT::i64, Custom); 733 setOperationAction(ISD::SRA, MVT::i64, Custom); 734 735 if (!Subtarget->isThumb1Only()) { 736 // FIXME: We should do this for Thumb1 as well. 737 setOperationAction(ISD::ADDC, MVT::i32, Custom); 738 setOperationAction(ISD::ADDE, MVT::i32, Custom); 739 setOperationAction(ISD::SUBC, MVT::i32, Custom); 740 setOperationAction(ISD::SUBE, MVT::i32, Custom); 741 } 742 743 if (!Subtarget->isThumb1Only() && Subtarget->hasV6T2Ops()) 744 setOperationAction(ISD::BITREVERSE, MVT::i32, Legal); 745 746 // ARM does not have ROTL. 747 setOperationAction(ISD::ROTL, MVT::i32, Expand); 748 for (MVT VT : MVT::vector_valuetypes()) { 749 setOperationAction(ISD::ROTL, VT, Expand); 750 setOperationAction(ISD::ROTR, VT, Expand); 751 } 752 setOperationAction(ISD::CTTZ, MVT::i32, Custom); 753 setOperationAction(ISD::CTPOP, MVT::i32, Expand); 754 if (!Subtarget->hasV5TOps() || Subtarget->isThumb1Only()) 755 setOperationAction(ISD::CTLZ, MVT::i32, Expand); 756 757 // These just redirect to CTTZ and CTLZ on ARM. 758 setOperationAction(ISD::CTTZ_ZERO_UNDEF , MVT::i32 , Expand); 759 setOperationAction(ISD::CTLZ_ZERO_UNDEF , MVT::i32 , Expand); 760 761 // @llvm.readcyclecounter requires the Performance Monitors extension. 762 // Default to the 0 expansion on unsupported platforms. 763 // FIXME: Technically there are older ARM CPUs that have 764 // implementation-specific ways of obtaining this information. 765 if (Subtarget->hasPerfMon()) 766 setOperationAction(ISD::READCYCLECOUNTER, MVT::i64, Custom); 767 768 // Only ARMv6 has BSWAP. 769 if (!Subtarget->hasV6Ops()) 770 setOperationAction(ISD::BSWAP, MVT::i32, Expand); 771 772 bool hasDivide = Subtarget->isThumb() ? Subtarget->hasDivide() 773 : Subtarget->hasDivideInARMMode(); 774 if (!hasDivide) { 775 // These are expanded into libcalls if the cpu doesn't have HW divider. 776 setOperationAction(ISD::SDIV, MVT::i32, LibCall); 777 setOperationAction(ISD::UDIV, MVT::i32, LibCall); 778 } 779 780 if (Subtarget->isTargetWindows() && !Subtarget->hasDivide()) { 781 setOperationAction(ISD::SDIV, MVT::i32, Custom); 782 setOperationAction(ISD::UDIV, MVT::i32, Custom); 783 784 setOperationAction(ISD::SDIV, MVT::i64, Custom); 785 setOperationAction(ISD::UDIV, MVT::i64, Custom); 786 } 787 788 setOperationAction(ISD::SREM, MVT::i32, Expand); 789 setOperationAction(ISD::UREM, MVT::i32, Expand); 790 // Register based DivRem for AEABI (RTABI 4.2) 791 if (Subtarget->isTargetAEABI() || Subtarget->isTargetAndroid() || 792 Subtarget->isTargetGNUAEABI()) { 793 setOperationAction(ISD::SREM, MVT::i64, Custom); 794 setOperationAction(ISD::UREM, MVT::i64, Custom); 795 796 setLibcallName(RTLIB::SDIVREM_I8, "__aeabi_idivmod"); 797 setLibcallName(RTLIB::SDIVREM_I16, "__aeabi_idivmod"); 798 setLibcallName(RTLIB::SDIVREM_I32, "__aeabi_idivmod"); 799 setLibcallName(RTLIB::SDIVREM_I64, "__aeabi_ldivmod"); 800 setLibcallName(RTLIB::UDIVREM_I8, "__aeabi_uidivmod"); 801 setLibcallName(RTLIB::UDIVREM_I16, "__aeabi_uidivmod"); 802 setLibcallName(RTLIB::UDIVREM_I32, "__aeabi_uidivmod"); 803 setLibcallName(RTLIB::UDIVREM_I64, "__aeabi_uldivmod"); 804 805 setLibcallCallingConv(RTLIB::SDIVREM_I8, CallingConv::ARM_AAPCS); 806 setLibcallCallingConv(RTLIB::SDIVREM_I16, CallingConv::ARM_AAPCS); 807 setLibcallCallingConv(RTLIB::SDIVREM_I32, CallingConv::ARM_AAPCS); 808 setLibcallCallingConv(RTLIB::SDIVREM_I64, CallingConv::ARM_AAPCS); 809 setLibcallCallingConv(RTLIB::UDIVREM_I8, CallingConv::ARM_AAPCS); 810 setLibcallCallingConv(RTLIB::UDIVREM_I16, CallingConv::ARM_AAPCS); 811 setLibcallCallingConv(RTLIB::UDIVREM_I32, CallingConv::ARM_AAPCS); 812 setLibcallCallingConv(RTLIB::UDIVREM_I64, CallingConv::ARM_AAPCS); 813 814 setOperationAction(ISD::SDIVREM, MVT::i32, Custom); 815 setOperationAction(ISD::UDIVREM, MVT::i32, Custom); 816 setOperationAction(ISD::SDIVREM, MVT::i64, Custom); 817 setOperationAction(ISD::UDIVREM, MVT::i64, Custom); 818 } else { 819 setOperationAction(ISD::SDIVREM, MVT::i32, Expand); 820 setOperationAction(ISD::UDIVREM, MVT::i32, Expand); 821 } 822 823 setOperationAction(ISD::GlobalAddress, MVT::i32, Custom); 824 setOperationAction(ISD::ConstantPool, MVT::i32, Custom); 825 setOperationAction(ISD::GlobalTLSAddress, MVT::i32, Custom); 826 setOperationAction(ISD::BlockAddress, MVT::i32, Custom); 827 828 setOperationAction(ISD::TRAP, MVT::Other, Legal); 829 830 // Use the default implementation. 831 setOperationAction(ISD::VASTART, MVT::Other, Custom); 832 setOperationAction(ISD::VAARG, MVT::Other, Expand); 833 setOperationAction(ISD::VACOPY, MVT::Other, Expand); 834 setOperationAction(ISD::VAEND, MVT::Other, Expand); 835 setOperationAction(ISD::STACKSAVE, MVT::Other, Expand); 836 setOperationAction(ISD::STACKRESTORE, MVT::Other, Expand); 837 838 if (Subtarget->getTargetTriple().isWindowsItaniumEnvironment()) 839 setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i32, Custom); 840 else 841 setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i32, Expand); 842 843 // ARMv6 Thumb1 (except for CPUs that support dmb / dsb) and earlier use 844 // the default expansion. If we are targeting a single threaded system, 845 // then set them all for expand so we can lower them later into their 846 // non-atomic form. 847 InsertFencesForAtomic = false; 848 if (TM.Options.ThreadModel == ThreadModel::Single) 849 setOperationAction(ISD::ATOMIC_FENCE, MVT::Other, Expand); 850 else if (Subtarget->hasAnyDataBarrier() && (!Subtarget->isThumb() || 851 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 856 // On v8, we have particularly efficient implementations of atomic fences 857 // if they can be combined with nearby atomic loads and stores. 858 if (!Subtarget->hasV8Ops()) { 859 // Automatically insert fences (dmb ish) around ATOMIC_SWAP etc. 860 InsertFencesForAtomic = true; 861 } 862 } else { 863 // If there's anything we can use as a barrier, go through custom lowering 864 // for ATOMIC_FENCE. 865 setOperationAction(ISD::ATOMIC_FENCE, MVT::Other, 866 Subtarget->hasAnyDataBarrier() ? Custom : Expand); 867 868 // Set them all for expansion, which will force libcalls. 869 setOperationAction(ISD::ATOMIC_CMP_SWAP, MVT::i32, Expand); 870 setOperationAction(ISD::ATOMIC_SWAP, MVT::i32, Expand); 871 setOperationAction(ISD::ATOMIC_LOAD_ADD, MVT::i32, Expand); 872 setOperationAction(ISD::ATOMIC_LOAD_SUB, MVT::i32, Expand); 873 setOperationAction(ISD::ATOMIC_LOAD_AND, MVT::i32, Expand); 874 setOperationAction(ISD::ATOMIC_LOAD_OR, MVT::i32, Expand); 875 setOperationAction(ISD::ATOMIC_LOAD_XOR, MVT::i32, Expand); 876 setOperationAction(ISD::ATOMIC_LOAD_NAND, MVT::i32, Expand); 877 setOperationAction(ISD::ATOMIC_LOAD_MIN, MVT::i32, Expand); 878 setOperationAction(ISD::ATOMIC_LOAD_MAX, MVT::i32, Expand); 879 setOperationAction(ISD::ATOMIC_LOAD_UMIN, MVT::i32, Expand); 880 setOperationAction(ISD::ATOMIC_LOAD_UMAX, MVT::i32, Expand); 881 // Mark ATOMIC_LOAD and ATOMIC_STORE custom so we can handle the 882 // Unordered/Monotonic case. 883 setOperationAction(ISD::ATOMIC_LOAD, MVT::i32, Custom); 884 setOperationAction(ISD::ATOMIC_STORE, MVT::i32, Custom); 885 } 886 887 setOperationAction(ISD::PREFETCH, MVT::Other, Custom); 888 889 // Requires SXTB/SXTH, available on v6 and up in both ARM and Thumb modes. 890 if (!Subtarget->hasV6Ops()) { 891 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i16, Expand); 892 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i8, Expand); 893 } 894 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1, Expand); 895 896 if (!Subtarget->useSoftFloat() && Subtarget->hasVFP2() && 897 !Subtarget->isThumb1Only()) { 898 // Turn f64->i64 into VMOVRRD, i64 -> f64 to VMOVDRR 899 // iff target supports vfp2. 900 setOperationAction(ISD::BITCAST, MVT::i64, Custom); 901 setOperationAction(ISD::FLT_ROUNDS_, MVT::i32, Custom); 902 } 903 904 // We want to custom lower some of our intrinsics. 905 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom); 906 setOperationAction(ISD::EH_SJLJ_SETJMP, MVT::i32, Custom); 907 setOperationAction(ISD::EH_SJLJ_LONGJMP, MVT::Other, Custom); 908 setOperationAction(ISD::EH_SJLJ_SETUP_DISPATCH, MVT::Other, Custom); 909 if (Subtarget->useSjLjEH()) 910 setLibcallName(RTLIB::UNWIND_RESUME, "_Unwind_SjLj_Resume"); 911 912 setOperationAction(ISD::SETCC, MVT::i32, Expand); 913 setOperationAction(ISD::SETCC, MVT::f32, Expand); 914 setOperationAction(ISD::SETCC, MVT::f64, Expand); 915 setOperationAction(ISD::SELECT, MVT::i32, Custom); 916 setOperationAction(ISD::SELECT, MVT::f32, Custom); 917 setOperationAction(ISD::SELECT, MVT::f64, Custom); 918 setOperationAction(ISD::SELECT_CC, MVT::i32, Custom); 919 setOperationAction(ISD::SELECT_CC, MVT::f32, Custom); 920 setOperationAction(ISD::SELECT_CC, MVT::f64, Custom); 921 922 // Thumb-1 cannot currently select ARMISD::SUBE. 923 if (!Subtarget->isThumb1Only()) 924 setOperationAction(ISD::SETCCE, MVT::i32, Custom); 925 926 setOperationAction(ISD::BRCOND, MVT::Other, Expand); 927 setOperationAction(ISD::BR_CC, MVT::i32, Custom); 928 setOperationAction(ISD::BR_CC, MVT::f32, Custom); 929 setOperationAction(ISD::BR_CC, MVT::f64, Custom); 930 setOperationAction(ISD::BR_JT, MVT::Other, Custom); 931 932 // We don't support sin/cos/fmod/copysign/pow 933 setOperationAction(ISD::FSIN, MVT::f64, Expand); 934 setOperationAction(ISD::FSIN, MVT::f32, Expand); 935 setOperationAction(ISD::FCOS, MVT::f32, Expand); 936 setOperationAction(ISD::FCOS, MVT::f64, Expand); 937 setOperationAction(ISD::FSINCOS, MVT::f64, Expand); 938 setOperationAction(ISD::FSINCOS, MVT::f32, Expand); 939 setOperationAction(ISD::FREM, MVT::f64, Expand); 940 setOperationAction(ISD::FREM, MVT::f32, Expand); 941 if (!Subtarget->useSoftFloat() && Subtarget->hasVFP2() && 942 !Subtarget->isThumb1Only()) { 943 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Custom); 944 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom); 945 } 946 setOperationAction(ISD::FPOW, MVT::f64, Expand); 947 setOperationAction(ISD::FPOW, MVT::f32, Expand); 948 949 if (!Subtarget->hasVFP4()) { 950 setOperationAction(ISD::FMA, MVT::f64, Expand); 951 setOperationAction(ISD::FMA, MVT::f32, Expand); 952 } 953 954 // Various VFP goodness 955 if (!Subtarget->useSoftFloat() && !Subtarget->isThumb1Only()) { 956 // FP-ARMv8 adds f64 <-> f16 conversion. Before that it should be expanded. 957 if (!Subtarget->hasFPARMv8() || Subtarget->isFPOnlySP()) { 958 setOperationAction(ISD::FP16_TO_FP, MVT::f64, Expand); 959 setOperationAction(ISD::FP_TO_FP16, MVT::f64, Expand); 960 } 961 962 // fp16 is a special v7 extension that adds f16 <-> f32 conversions. 963 if (!Subtarget->hasFP16()) { 964 setOperationAction(ISD::FP16_TO_FP, MVT::f32, Expand); 965 setOperationAction(ISD::FP_TO_FP16, MVT::f32, Expand); 966 } 967 } 968 969 // Combine sin / cos into one node or libcall if possible. 970 if (Subtarget->hasSinCos()) { 971 setLibcallName(RTLIB::SINCOS_F32, "sincosf"); 972 setLibcallName(RTLIB::SINCOS_F64, "sincos"); 973 if (Subtarget->isTargetWatchABI()) { 974 setLibcallCallingConv(RTLIB::SINCOS_F32, CallingConv::ARM_AAPCS_VFP); 975 setLibcallCallingConv(RTLIB::SINCOS_F64, CallingConv::ARM_AAPCS_VFP); 976 } 977 if (Subtarget->isTargetIOS() || Subtarget->isTargetWatchOS()) { 978 // For iOS, we don't want to the normal expansion of a libcall to 979 // sincos. We want to issue a libcall to __sincos_stret. 980 setOperationAction(ISD::FSINCOS, MVT::f64, Custom); 981 setOperationAction(ISD::FSINCOS, MVT::f32, Custom); 982 } 983 } 984 985 // FP-ARMv8 implements a lot of rounding-like FP operations. 986 if (Subtarget->hasFPARMv8()) { 987 setOperationAction(ISD::FFLOOR, MVT::f32, Legal); 988 setOperationAction(ISD::FCEIL, MVT::f32, Legal); 989 setOperationAction(ISD::FROUND, MVT::f32, Legal); 990 setOperationAction(ISD::FTRUNC, MVT::f32, Legal); 991 setOperationAction(ISD::FNEARBYINT, MVT::f32, Legal); 992 setOperationAction(ISD::FRINT, MVT::f32, Legal); 993 setOperationAction(ISD::FMINNUM, MVT::f32, Legal); 994 setOperationAction(ISD::FMAXNUM, MVT::f32, Legal); 995 setOperationAction(ISD::FMINNUM, MVT::v2f32, Legal); 996 setOperationAction(ISD::FMAXNUM, MVT::v2f32, Legal); 997 setOperationAction(ISD::FMINNUM, MVT::v4f32, Legal); 998 setOperationAction(ISD::FMAXNUM, MVT::v4f32, Legal); 999 1000 if (!Subtarget->isFPOnlySP()) { 1001 setOperationAction(ISD::FFLOOR, MVT::f64, Legal); 1002 setOperationAction(ISD::FCEIL, MVT::f64, Legal); 1003 setOperationAction(ISD::FROUND, MVT::f64, Legal); 1004 setOperationAction(ISD::FTRUNC, MVT::f64, Legal); 1005 setOperationAction(ISD::FNEARBYINT, MVT::f64, Legal); 1006 setOperationAction(ISD::FRINT, MVT::f64, Legal); 1007 setOperationAction(ISD::FMINNUM, MVT::f64, Legal); 1008 setOperationAction(ISD::FMAXNUM, MVT::f64, Legal); 1009 } 1010 } 1011 1012 if (Subtarget->hasNEON()) { 1013 // vmin and vmax aren't available in a scalar form, so we use 1014 // a NEON instruction with an undef lane instead. 1015 setOperationAction(ISD::FMINNAN, MVT::f32, Legal); 1016 setOperationAction(ISD::FMAXNAN, MVT::f32, Legal); 1017 setOperationAction(ISD::FMINNAN, MVT::v2f32, Legal); 1018 setOperationAction(ISD::FMAXNAN, MVT::v2f32, Legal); 1019 setOperationAction(ISD::FMINNAN, MVT::v4f32, Legal); 1020 setOperationAction(ISD::FMAXNAN, MVT::v4f32, Legal); 1021 } 1022 1023 // We have target-specific dag combine patterns for the following nodes: 1024 // ARMISD::VMOVRRD - No need to call setTargetDAGCombine 1025 setTargetDAGCombine(ISD::ADD); 1026 setTargetDAGCombine(ISD::SUB); 1027 setTargetDAGCombine(ISD::MUL); 1028 setTargetDAGCombine(ISD::AND); 1029 setTargetDAGCombine(ISD::OR); 1030 setTargetDAGCombine(ISD::XOR); 1031 1032 if (Subtarget->hasV6Ops()) 1033 setTargetDAGCombine(ISD::SRL); 1034 1035 setStackPointerRegisterToSaveRestore(ARM::SP); 1036 1037 if (Subtarget->useSoftFloat() || Subtarget->isThumb1Only() || 1038 !Subtarget->hasVFP2()) 1039 setSchedulingPreference(Sched::RegPressure); 1040 else 1041 setSchedulingPreference(Sched::Hybrid); 1042 1043 //// temporary - rewrite interface to use type 1044 MaxStoresPerMemset = 8; 1045 MaxStoresPerMemsetOptSize = 4; 1046 MaxStoresPerMemcpy = 4; // For @llvm.memcpy -> sequence of stores 1047 MaxStoresPerMemcpyOptSize = 2; 1048 MaxStoresPerMemmove = 4; // For @llvm.memmove -> sequence of stores 1049 MaxStoresPerMemmoveOptSize = 2; 1050 1051 // On ARM arguments smaller than 4 bytes are extended, so all arguments 1052 // are at least 4 bytes aligned. 1053 setMinStackArgumentAlignment(4); 1054 1055 // Prefer likely predicted branches to selects on out-of-order cores. 1056 PredictableSelectIsExpensive = Subtarget->getSchedModel().isOutOfOrder(); 1057 1058 setMinFunctionAlignment(Subtarget->isThumb() ? 1 : 2); 1059 } 1060 1061 bool ARMTargetLowering::useSoftFloat() const { 1062 return Subtarget->useSoftFloat(); 1063 } 1064 1065 // FIXME: It might make sense to define the representative register class as the 1066 // nearest super-register that has a non-null superset. For example, DPR_VFP2 is 1067 // a super-register of SPR, and DPR is a superset if DPR_VFP2. Consequently, 1068 // SPR's representative would be DPR_VFP2. This should work well if register 1069 // pressure tracking were modified such that a register use would increment the 1070 // pressure of the register class's representative and all of it's super 1071 // classes' representatives transitively. We have not implemented this because 1072 // of the difficulty prior to coalescing of modeling operand register classes 1073 // due to the common occurrence of cross class copies and subregister insertions 1074 // and extractions. 1075 std::pair<const TargetRegisterClass *, uint8_t> 1076 ARMTargetLowering::findRepresentativeClass(const TargetRegisterInfo *TRI, 1077 MVT VT) const { 1078 const TargetRegisterClass *RRC = nullptr; 1079 uint8_t Cost = 1; 1080 switch (VT.SimpleTy) { 1081 default: 1082 return TargetLowering::findRepresentativeClass(TRI, VT); 1083 // Use DPR as representative register class for all floating point 1084 // and vector types. Since there are 32 SPR registers and 32 DPR registers so 1085 // the cost is 1 for both f32 and f64. 1086 case MVT::f32: case MVT::f64: case MVT::v8i8: case MVT::v4i16: 1087 case MVT::v2i32: case MVT::v1i64: case MVT::v2f32: 1088 RRC = &ARM::DPRRegClass; 1089 // When NEON is used for SP, only half of the register file is available 1090 // because operations that define both SP and DP results will be constrained 1091 // to the VFP2 class (D0-D15). We currently model this constraint prior to 1092 // coalescing by double-counting the SP regs. See the FIXME above. 1093 if (Subtarget->useNEONForSinglePrecisionFP()) 1094 Cost = 2; 1095 break; 1096 case MVT::v16i8: case MVT::v8i16: case MVT::v4i32: case MVT::v2i64: 1097 case MVT::v4f32: case MVT::v2f64: 1098 RRC = &ARM::DPRRegClass; 1099 Cost = 2; 1100 break; 1101 case MVT::v4i64: 1102 RRC = &ARM::DPRRegClass; 1103 Cost = 4; 1104 break; 1105 case MVT::v8i64: 1106 RRC = &ARM::DPRRegClass; 1107 Cost = 8; 1108 break; 1109 } 1110 return std::make_pair(RRC, Cost); 1111 } 1112 1113 const char *ARMTargetLowering::getTargetNodeName(unsigned Opcode) const { 1114 switch ((ARMISD::NodeType)Opcode) { 1115 case ARMISD::FIRST_NUMBER: break; 1116 case ARMISD::Wrapper: return "ARMISD::Wrapper"; 1117 case ARMISD::WrapperPIC: return "ARMISD::WrapperPIC"; 1118 case ARMISD::WrapperJT: return "ARMISD::WrapperJT"; 1119 case ARMISD::COPY_STRUCT_BYVAL: return "ARMISD::COPY_STRUCT_BYVAL"; 1120 case ARMISD::CALL: return "ARMISD::CALL"; 1121 case ARMISD::CALL_PRED: return "ARMISD::CALL_PRED"; 1122 case ARMISD::CALL_NOLINK: return "ARMISD::CALL_NOLINK"; 1123 case ARMISD::tCALL: return "ARMISD::tCALL"; 1124 case ARMISD::BRCOND: return "ARMISD::BRCOND"; 1125 case ARMISD::BR_JT: return "ARMISD::BR_JT"; 1126 case ARMISD::BR2_JT: return "ARMISD::BR2_JT"; 1127 case ARMISD::RET_FLAG: return "ARMISD::RET_FLAG"; 1128 case ARMISD::INTRET_FLAG: return "ARMISD::INTRET_FLAG"; 1129 case ARMISD::PIC_ADD: return "ARMISD::PIC_ADD"; 1130 case ARMISD::CMP: return "ARMISD::CMP"; 1131 case ARMISD::CMN: return "ARMISD::CMN"; 1132 case ARMISD::CMPZ: return "ARMISD::CMPZ"; 1133 case ARMISD::CMPFP: return "ARMISD::CMPFP"; 1134 case ARMISD::CMPFPw0: return "ARMISD::CMPFPw0"; 1135 case ARMISD::BCC_i64: return "ARMISD::BCC_i64"; 1136 case ARMISD::FMSTAT: return "ARMISD::FMSTAT"; 1137 1138 case ARMISD::CMOV: return "ARMISD::CMOV"; 1139 1140 case ARMISD::SRL_FLAG: return "ARMISD::SRL_FLAG"; 1141 case ARMISD::SRA_FLAG: return "ARMISD::SRA_FLAG"; 1142 case ARMISD::RRX: return "ARMISD::RRX"; 1143 1144 case ARMISD::ADDC: return "ARMISD::ADDC"; 1145 case ARMISD::ADDE: return "ARMISD::ADDE"; 1146 case ARMISD::SUBC: return "ARMISD::SUBC"; 1147 case ARMISD::SUBE: return "ARMISD::SUBE"; 1148 1149 case ARMISD::VMOVRRD: return "ARMISD::VMOVRRD"; 1150 case ARMISD::VMOVDRR: return "ARMISD::VMOVDRR"; 1151 1152 case ARMISD::EH_SJLJ_SETJMP: return "ARMISD::EH_SJLJ_SETJMP"; 1153 case ARMISD::EH_SJLJ_LONGJMP: return "ARMISD::EH_SJLJ_LONGJMP"; 1154 case ARMISD::EH_SJLJ_SETUP_DISPATCH: return "ARMISD::EH_SJLJ_SETUP_DISPATCH"; 1155 1156 case ARMISD::TC_RETURN: return "ARMISD::TC_RETURN"; 1157 1158 case ARMISD::THREAD_POINTER:return "ARMISD::THREAD_POINTER"; 1159 1160 case ARMISD::DYN_ALLOC: return "ARMISD::DYN_ALLOC"; 1161 1162 case ARMISD::MEMBARRIER_MCR: return "ARMISD::MEMBARRIER_MCR"; 1163 1164 case ARMISD::PRELOAD: return "ARMISD::PRELOAD"; 1165 1166 case ARMISD::WIN__CHKSTK: return "ARMISD:::WIN__CHKSTK"; 1167 case ARMISD::WIN__DBZCHK: return "ARMISD::WIN__DBZCHK"; 1168 1169 case ARMISD::VCEQ: return "ARMISD::VCEQ"; 1170 case ARMISD::VCEQZ: return "ARMISD::VCEQZ"; 1171 case ARMISD::VCGE: return "ARMISD::VCGE"; 1172 case ARMISD::VCGEZ: return "ARMISD::VCGEZ"; 1173 case ARMISD::VCLEZ: return "ARMISD::VCLEZ"; 1174 case ARMISD::VCGEU: return "ARMISD::VCGEU"; 1175 case ARMISD::VCGT: return "ARMISD::VCGT"; 1176 case ARMISD::VCGTZ: return "ARMISD::VCGTZ"; 1177 case ARMISD::VCLTZ: return "ARMISD::VCLTZ"; 1178 case ARMISD::VCGTU: return "ARMISD::VCGTU"; 1179 case ARMISD::VTST: return "ARMISD::VTST"; 1180 1181 case ARMISD::VSHL: return "ARMISD::VSHL"; 1182 case ARMISD::VSHRs: return "ARMISD::VSHRs"; 1183 case ARMISD::VSHRu: return "ARMISD::VSHRu"; 1184 case ARMISD::VRSHRs: return "ARMISD::VRSHRs"; 1185 case ARMISD::VRSHRu: return "ARMISD::VRSHRu"; 1186 case ARMISD::VRSHRN: return "ARMISD::VRSHRN"; 1187 case ARMISD::VQSHLs: return "ARMISD::VQSHLs"; 1188 case ARMISD::VQSHLu: return "ARMISD::VQSHLu"; 1189 case ARMISD::VQSHLsu: return "ARMISD::VQSHLsu"; 1190 case ARMISD::VQSHRNs: return "ARMISD::VQSHRNs"; 1191 case ARMISD::VQSHRNu: return "ARMISD::VQSHRNu"; 1192 case ARMISD::VQSHRNsu: return "ARMISD::VQSHRNsu"; 1193 case ARMISD::VQRSHRNs: return "ARMISD::VQRSHRNs"; 1194 case ARMISD::VQRSHRNu: return "ARMISD::VQRSHRNu"; 1195 case ARMISD::VQRSHRNsu: return "ARMISD::VQRSHRNsu"; 1196 case ARMISD::VSLI: return "ARMISD::VSLI"; 1197 case ARMISD::VSRI: return "ARMISD::VSRI"; 1198 case ARMISD::VGETLANEu: return "ARMISD::VGETLANEu"; 1199 case ARMISD::VGETLANEs: return "ARMISD::VGETLANEs"; 1200 case ARMISD::VMOVIMM: return "ARMISD::VMOVIMM"; 1201 case ARMISD::VMVNIMM: return "ARMISD::VMVNIMM"; 1202 case ARMISD::VMOVFPIMM: return "ARMISD::VMOVFPIMM"; 1203 case ARMISD::VDUP: return "ARMISD::VDUP"; 1204 case ARMISD::VDUPLANE: return "ARMISD::VDUPLANE"; 1205 case ARMISD::VEXT: return "ARMISD::VEXT"; 1206 case ARMISD::VREV64: return "ARMISD::VREV64"; 1207 case ARMISD::VREV32: return "ARMISD::VREV32"; 1208 case ARMISD::VREV16: return "ARMISD::VREV16"; 1209 case ARMISD::VZIP: return "ARMISD::VZIP"; 1210 case ARMISD::VUZP: return "ARMISD::VUZP"; 1211 case ARMISD::VTRN: return "ARMISD::VTRN"; 1212 case ARMISD::VTBL1: return "ARMISD::VTBL1"; 1213 case ARMISD::VTBL2: return "ARMISD::VTBL2"; 1214 case ARMISD::VMULLs: return "ARMISD::VMULLs"; 1215 case ARMISD::VMULLu: return "ARMISD::VMULLu"; 1216 case ARMISD::UMLAL: return "ARMISD::UMLAL"; 1217 case ARMISD::SMLAL: return "ARMISD::SMLAL"; 1218 case ARMISD::BUILD_VECTOR: return "ARMISD::BUILD_VECTOR"; 1219 case ARMISD::BFI: return "ARMISD::BFI"; 1220 case ARMISD::VORRIMM: return "ARMISD::VORRIMM"; 1221 case ARMISD::VBICIMM: return "ARMISD::VBICIMM"; 1222 case ARMISD::VBSL: return "ARMISD::VBSL"; 1223 case ARMISD::MEMCPY: return "ARMISD::MEMCPY"; 1224 case ARMISD::VLD2DUP: return "ARMISD::VLD2DUP"; 1225 case ARMISD::VLD3DUP: return "ARMISD::VLD3DUP"; 1226 case ARMISD::VLD4DUP: return "ARMISD::VLD4DUP"; 1227 case ARMISD::VLD1_UPD: return "ARMISD::VLD1_UPD"; 1228 case ARMISD::VLD2_UPD: return "ARMISD::VLD2_UPD"; 1229 case ARMISD::VLD3_UPD: return "ARMISD::VLD3_UPD"; 1230 case ARMISD::VLD4_UPD: return "ARMISD::VLD4_UPD"; 1231 case ARMISD::VLD2LN_UPD: return "ARMISD::VLD2LN_UPD"; 1232 case ARMISD::VLD3LN_UPD: return "ARMISD::VLD3LN_UPD"; 1233 case ARMISD::VLD4LN_UPD: return "ARMISD::VLD4LN_UPD"; 1234 case ARMISD::VLD2DUP_UPD: return "ARMISD::VLD2DUP_UPD"; 1235 case ARMISD::VLD3DUP_UPD: return "ARMISD::VLD3DUP_UPD"; 1236 case ARMISD::VLD4DUP_UPD: return "ARMISD::VLD4DUP_UPD"; 1237 case ARMISD::VST1_UPD: return "ARMISD::VST1_UPD"; 1238 case ARMISD::VST2_UPD: return "ARMISD::VST2_UPD"; 1239 case ARMISD::VST3_UPD: return "ARMISD::VST3_UPD"; 1240 case ARMISD::VST4_UPD: return "ARMISD::VST4_UPD"; 1241 case ARMISD::VST2LN_UPD: return "ARMISD::VST2LN_UPD"; 1242 case ARMISD::VST3LN_UPD: return "ARMISD::VST3LN_UPD"; 1243 case ARMISD::VST4LN_UPD: return "ARMISD::VST4LN_UPD"; 1244 } 1245 return nullptr; 1246 } 1247 1248 EVT ARMTargetLowering::getSetCCResultType(const DataLayout &DL, LLVMContext &, 1249 EVT VT) const { 1250 if (!VT.isVector()) 1251 return getPointerTy(DL); 1252 return VT.changeVectorElementTypeToInteger(); 1253 } 1254 1255 /// getRegClassFor - Return the register class that should be used for the 1256 /// specified value type. 1257 const TargetRegisterClass *ARMTargetLowering::getRegClassFor(MVT VT) const { 1258 // Map v4i64 to QQ registers but do not make the type legal. Similarly map 1259 // v8i64 to QQQQ registers. v4i64 and v8i64 are only used for REG_SEQUENCE to 1260 // load / store 4 to 8 consecutive D registers. 1261 if (Subtarget->hasNEON()) { 1262 if (VT == MVT::v4i64) 1263 return &ARM::QQPRRegClass; 1264 if (VT == MVT::v8i64) 1265 return &ARM::QQQQPRRegClass; 1266 } 1267 return TargetLowering::getRegClassFor(VT); 1268 } 1269 1270 // memcpy, and other memory intrinsics, typically tries to use LDM/STM if the 1271 // source/dest is aligned and the copy size is large enough. We therefore want 1272 // to align such objects passed to memory intrinsics. 1273 bool ARMTargetLowering::shouldAlignPointerArgs(CallInst *CI, unsigned &MinSize, 1274 unsigned &PrefAlign) const { 1275 if (!isa<MemIntrinsic>(CI)) 1276 return false; 1277 MinSize = 8; 1278 // On ARM11 onwards (excluding M class) 8-byte aligned LDM is typically 1 1279 // cycle faster than 4-byte aligned LDM. 1280 PrefAlign = (Subtarget->hasV6Ops() && !Subtarget->isMClass() ? 8 : 4); 1281 return true; 1282 } 1283 1284 // Create a fast isel object. 1285 FastISel * 1286 ARMTargetLowering::createFastISel(FunctionLoweringInfo &funcInfo, 1287 const TargetLibraryInfo *libInfo) const { 1288 return ARM::createFastISel(funcInfo, libInfo); 1289 } 1290 1291 Sched::Preference ARMTargetLowering::getSchedulingPreference(SDNode *N) const { 1292 unsigned NumVals = N->getNumValues(); 1293 if (!NumVals) 1294 return Sched::RegPressure; 1295 1296 for (unsigned i = 0; i != NumVals; ++i) { 1297 EVT VT = N->getValueType(i); 1298 if (VT == MVT::Glue || VT == MVT::Other) 1299 continue; 1300 if (VT.isFloatingPoint() || VT.isVector()) 1301 return Sched::ILP; 1302 } 1303 1304 if (!N->isMachineOpcode()) 1305 return Sched::RegPressure; 1306 1307 // Load are scheduled for latency even if there instruction itinerary 1308 // is not available. 1309 const TargetInstrInfo *TII = Subtarget->getInstrInfo(); 1310 const MCInstrDesc &MCID = TII->get(N->getMachineOpcode()); 1311 1312 if (MCID.getNumDefs() == 0) 1313 return Sched::RegPressure; 1314 if (!Itins->isEmpty() && 1315 Itins->getOperandCycle(MCID.getSchedClass(), 0) > 2) 1316 return Sched::ILP; 1317 1318 return Sched::RegPressure; 1319 } 1320 1321 //===----------------------------------------------------------------------===// 1322 // Lowering Code 1323 //===----------------------------------------------------------------------===// 1324 1325 /// IntCCToARMCC - Convert a DAG integer condition code to an ARM CC 1326 static ARMCC::CondCodes IntCCToARMCC(ISD::CondCode CC) { 1327 switch (CC) { 1328 default: llvm_unreachable("Unknown condition code!"); 1329 case ISD::SETNE: return ARMCC::NE; 1330 case ISD::SETEQ: return ARMCC::EQ; 1331 case ISD::SETGT: return ARMCC::GT; 1332 case ISD::SETGE: return ARMCC::GE; 1333 case ISD::SETLT: return ARMCC::LT; 1334 case ISD::SETLE: return ARMCC::LE; 1335 case ISD::SETUGT: return ARMCC::HI; 1336 case ISD::SETUGE: return ARMCC::HS; 1337 case ISD::SETULT: return ARMCC::LO; 1338 case ISD::SETULE: return ARMCC::LS; 1339 } 1340 } 1341 1342 /// FPCCToARMCC - Convert a DAG fp condition code to an ARM CC. 1343 static void FPCCToARMCC(ISD::CondCode CC, ARMCC::CondCodes &CondCode, 1344 ARMCC::CondCodes &CondCode2) { 1345 CondCode2 = ARMCC::AL; 1346 switch (CC) { 1347 default: llvm_unreachable("Unknown FP condition!"); 1348 case ISD::SETEQ: 1349 case ISD::SETOEQ: CondCode = ARMCC::EQ; break; 1350 case ISD::SETGT: 1351 case ISD::SETOGT: CondCode = ARMCC::GT; break; 1352 case ISD::SETGE: 1353 case ISD::SETOGE: CondCode = ARMCC::GE; break; 1354 case ISD::SETOLT: CondCode = ARMCC::MI; break; 1355 case ISD::SETOLE: CondCode = ARMCC::LS; break; 1356 case ISD::SETONE: CondCode = ARMCC::MI; CondCode2 = ARMCC::GT; break; 1357 case ISD::SETO: CondCode = ARMCC::VC; break; 1358 case ISD::SETUO: CondCode = ARMCC::VS; break; 1359 case ISD::SETUEQ: CondCode = ARMCC::EQ; CondCode2 = ARMCC::VS; break; 1360 case ISD::SETUGT: CondCode = ARMCC::HI; break; 1361 case ISD::SETUGE: CondCode = ARMCC::PL; break; 1362 case ISD::SETLT: 1363 case ISD::SETULT: CondCode = ARMCC::LT; break; 1364 case ISD::SETLE: 1365 case ISD::SETULE: CondCode = ARMCC::LE; break; 1366 case ISD::SETNE: 1367 case ISD::SETUNE: CondCode = ARMCC::NE; break; 1368 } 1369 } 1370 1371 //===----------------------------------------------------------------------===// 1372 // Calling Convention Implementation 1373 //===----------------------------------------------------------------------===// 1374 1375 #include "ARMGenCallingConv.inc" 1376 1377 /// getEffectiveCallingConv - Get the effective calling convention, taking into 1378 /// account presence of floating point hardware and calling convention 1379 /// limitations, such as support for variadic functions. 1380 CallingConv::ID 1381 ARMTargetLowering::getEffectiveCallingConv(CallingConv::ID CC, 1382 bool isVarArg) const { 1383 switch (CC) { 1384 default: 1385 llvm_unreachable("Unsupported calling convention"); 1386 case CallingConv::ARM_AAPCS: 1387 case CallingConv::ARM_APCS: 1388 case CallingConv::GHC: 1389 return CC; 1390 case CallingConv::PreserveMost: 1391 return CallingConv::PreserveMost; 1392 case CallingConv::ARM_AAPCS_VFP: 1393 return isVarArg ? CallingConv::ARM_AAPCS : CallingConv::ARM_AAPCS_VFP; 1394 case CallingConv::C: 1395 if (!Subtarget->isAAPCS_ABI()) 1396 return CallingConv::ARM_APCS; 1397 else if (Subtarget->hasVFP2() && !Subtarget->isThumb1Only() && 1398 getTargetMachine().Options.FloatABIType == FloatABI::Hard && 1399 !isVarArg) 1400 return CallingConv::ARM_AAPCS_VFP; 1401 else 1402 return CallingConv::ARM_AAPCS; 1403 case CallingConv::Fast: 1404 case CallingConv::CXX_FAST_TLS: 1405 if (!Subtarget->isAAPCS_ABI()) { 1406 if (Subtarget->hasVFP2() && !Subtarget->isThumb1Only() && !isVarArg) 1407 return CallingConv::Fast; 1408 return CallingConv::ARM_APCS; 1409 } else if (Subtarget->hasVFP2() && !Subtarget->isThumb1Only() && !isVarArg) 1410 return CallingConv::ARM_AAPCS_VFP; 1411 else 1412 return CallingConv::ARM_AAPCS; 1413 } 1414 } 1415 1416 /// CCAssignFnForNode - Selects the correct CCAssignFn for the given 1417 /// CallingConvention. 1418 CCAssignFn *ARMTargetLowering::CCAssignFnForNode(CallingConv::ID CC, 1419 bool Return, 1420 bool isVarArg) const { 1421 switch (getEffectiveCallingConv(CC, isVarArg)) { 1422 default: 1423 llvm_unreachable("Unsupported calling convention"); 1424 case CallingConv::ARM_APCS: 1425 return (Return ? RetCC_ARM_APCS : CC_ARM_APCS); 1426 case CallingConv::ARM_AAPCS: 1427 return (Return ? RetCC_ARM_AAPCS : CC_ARM_AAPCS); 1428 case CallingConv::ARM_AAPCS_VFP: 1429 return (Return ? RetCC_ARM_AAPCS_VFP : CC_ARM_AAPCS_VFP); 1430 case CallingConv::Fast: 1431 return (Return ? RetFastCC_ARM_APCS : FastCC_ARM_APCS); 1432 case CallingConv::GHC: 1433 return (Return ? RetCC_ARM_APCS : CC_ARM_APCS_GHC); 1434 case CallingConv::PreserveMost: 1435 return (Return ? RetCC_ARM_AAPCS : CC_ARM_AAPCS); 1436 } 1437 } 1438 1439 /// LowerCallResult - Lower the result values of a call into the 1440 /// appropriate copies out of appropriate physical registers. 1441 SDValue 1442 ARMTargetLowering::LowerCallResult(SDValue Chain, SDValue InFlag, 1443 CallingConv::ID CallConv, bool isVarArg, 1444 const SmallVectorImpl<ISD::InputArg> &Ins, 1445 SDLoc dl, SelectionDAG &DAG, 1446 SmallVectorImpl<SDValue> &InVals, 1447 bool isThisReturn, SDValue ThisVal) const { 1448 1449 // Assign locations to each value returned by this call. 1450 SmallVector<CCValAssign, 16> RVLocs; 1451 ARMCCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs, 1452 *DAG.getContext(), Call); 1453 CCInfo.AnalyzeCallResult(Ins, 1454 CCAssignFnForNode(CallConv, /* Return*/ true, 1455 isVarArg)); 1456 1457 // Copy all of the result registers out of their specified physreg. 1458 for (unsigned i = 0; i != RVLocs.size(); ++i) { 1459 CCValAssign VA = RVLocs[i]; 1460 1461 // Pass 'this' value directly from the argument to return value, to avoid 1462 // reg unit interference 1463 if (i == 0 && isThisReturn) { 1464 assert(!VA.needsCustom() && VA.getLocVT() == MVT::i32 && 1465 "unexpected return calling convention register assignment"); 1466 InVals.push_back(ThisVal); 1467 continue; 1468 } 1469 1470 SDValue Val; 1471 if (VA.needsCustom()) { 1472 // Handle f64 or half of a v2f64. 1473 SDValue Lo = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32, 1474 InFlag); 1475 Chain = Lo.getValue(1); 1476 InFlag = Lo.getValue(2); 1477 VA = RVLocs[++i]; // skip ahead to next loc 1478 SDValue Hi = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32, 1479 InFlag); 1480 Chain = Hi.getValue(1); 1481 InFlag = Hi.getValue(2); 1482 if (!Subtarget->isLittle()) 1483 std::swap (Lo, Hi); 1484 Val = DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi); 1485 1486 if (VA.getLocVT() == MVT::v2f64) { 1487 SDValue Vec = DAG.getNode(ISD::UNDEF, dl, MVT::v2f64); 1488 Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Vec, Val, 1489 DAG.getConstant(0, dl, MVT::i32)); 1490 1491 VA = RVLocs[++i]; // skip ahead to next loc 1492 Lo = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32, InFlag); 1493 Chain = Lo.getValue(1); 1494 InFlag = Lo.getValue(2); 1495 VA = RVLocs[++i]; // skip ahead to next loc 1496 Hi = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32, InFlag); 1497 Chain = Hi.getValue(1); 1498 InFlag = Hi.getValue(2); 1499 if (!Subtarget->isLittle()) 1500 std::swap (Lo, Hi); 1501 Val = DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi); 1502 Val = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Vec, Val, 1503 DAG.getConstant(1, dl, MVT::i32)); 1504 } 1505 } else { 1506 Val = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), VA.getLocVT(), 1507 InFlag); 1508 Chain = Val.getValue(1); 1509 InFlag = Val.getValue(2); 1510 } 1511 1512 switch (VA.getLocInfo()) { 1513 default: llvm_unreachable("Unknown loc info!"); 1514 case CCValAssign::Full: break; 1515 case CCValAssign::BCvt: 1516 Val = DAG.getNode(ISD::BITCAST, dl, VA.getValVT(), Val); 1517 break; 1518 } 1519 1520 InVals.push_back(Val); 1521 } 1522 1523 return Chain; 1524 } 1525 1526 /// LowerMemOpCallTo - Store the argument to the stack. 1527 SDValue 1528 ARMTargetLowering::LowerMemOpCallTo(SDValue Chain, 1529 SDValue StackPtr, SDValue Arg, 1530 SDLoc dl, SelectionDAG &DAG, 1531 const CCValAssign &VA, 1532 ISD::ArgFlagsTy Flags) const { 1533 unsigned LocMemOffset = VA.getLocMemOffset(); 1534 SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset, dl); 1535 PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(DAG.getDataLayout()), 1536 StackPtr, PtrOff); 1537 return DAG.getStore( 1538 Chain, dl, Arg, PtrOff, 1539 MachinePointerInfo::getStack(DAG.getMachineFunction(), LocMemOffset), 1540 false, false, 0); 1541 } 1542 1543 void ARMTargetLowering::PassF64ArgInRegs(SDLoc dl, SelectionDAG &DAG, 1544 SDValue Chain, SDValue &Arg, 1545 RegsToPassVector &RegsToPass, 1546 CCValAssign &VA, CCValAssign &NextVA, 1547 SDValue &StackPtr, 1548 SmallVectorImpl<SDValue> &MemOpChains, 1549 ISD::ArgFlagsTy Flags) const { 1550 1551 SDValue fmrrd = DAG.getNode(ARMISD::VMOVRRD, dl, 1552 DAG.getVTList(MVT::i32, MVT::i32), Arg); 1553 unsigned id = Subtarget->isLittle() ? 0 : 1; 1554 RegsToPass.push_back(std::make_pair(VA.getLocReg(), fmrrd.getValue(id))); 1555 1556 if (NextVA.isRegLoc()) 1557 RegsToPass.push_back(std::make_pair(NextVA.getLocReg(), fmrrd.getValue(1-id))); 1558 else { 1559 assert(NextVA.isMemLoc()); 1560 if (!StackPtr.getNode()) 1561 StackPtr = DAG.getCopyFromReg(Chain, dl, ARM::SP, 1562 getPointerTy(DAG.getDataLayout())); 1563 1564 MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, fmrrd.getValue(1-id), 1565 dl, DAG, NextVA, 1566 Flags)); 1567 } 1568 } 1569 1570 /// LowerCall - Lowering a call into a callseq_start <- 1571 /// ARMISD:CALL <- callseq_end chain. Also add input and output parameter 1572 /// nodes. 1573 SDValue 1574 ARMTargetLowering::LowerCall(TargetLowering::CallLoweringInfo &CLI, 1575 SmallVectorImpl<SDValue> &InVals) const { 1576 SelectionDAG &DAG = CLI.DAG; 1577 SDLoc &dl = CLI.DL; 1578 SmallVectorImpl<ISD::OutputArg> &Outs = CLI.Outs; 1579 SmallVectorImpl<SDValue> &OutVals = CLI.OutVals; 1580 SmallVectorImpl<ISD::InputArg> &Ins = CLI.Ins; 1581 SDValue Chain = CLI.Chain; 1582 SDValue Callee = CLI.Callee; 1583 bool &isTailCall = CLI.IsTailCall; 1584 CallingConv::ID CallConv = CLI.CallConv; 1585 bool doesNotRet = CLI.DoesNotReturn; 1586 bool isVarArg = CLI.IsVarArg; 1587 1588 MachineFunction &MF = DAG.getMachineFunction(); 1589 bool isStructRet = (Outs.empty()) ? false : Outs[0].Flags.isSRet(); 1590 bool isThisReturn = false; 1591 bool isSibCall = false; 1592 auto Attr = MF.getFunction()->getFnAttribute("disable-tail-calls"); 1593 1594 // Disable tail calls if they're not supported. 1595 if (!Subtarget->supportsTailCall() || Attr.getValueAsString() == "true") 1596 isTailCall = false; 1597 1598 if (isTailCall) { 1599 // Check if it's really possible to do a tail call. 1600 isTailCall = IsEligibleForTailCallOptimization(Callee, CallConv, 1601 isVarArg, isStructRet, MF.getFunction()->hasStructRetAttr(), 1602 Outs, OutVals, Ins, DAG); 1603 if (!isTailCall && CLI.CS && CLI.CS->isMustTailCall()) 1604 report_fatal_error("failed to perform tail call elimination on a call " 1605 "site marked musttail"); 1606 // We don't support GuaranteedTailCallOpt for ARM, only automatically 1607 // detected sibcalls. 1608 if (isTailCall) { 1609 ++NumTailCalls; 1610 isSibCall = true; 1611 } 1612 } 1613 1614 // Analyze operands of the call, assigning locations to each operand. 1615 SmallVector<CCValAssign, 16> ArgLocs; 1616 ARMCCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), ArgLocs, 1617 *DAG.getContext(), Call); 1618 CCInfo.AnalyzeCallOperands(Outs, 1619 CCAssignFnForNode(CallConv, /* Return*/ false, 1620 isVarArg)); 1621 1622 // Get a count of how many bytes are to be pushed on the stack. 1623 unsigned NumBytes = CCInfo.getNextStackOffset(); 1624 1625 // For tail calls, memory operands are available in our caller's stack. 1626 if (isSibCall) 1627 NumBytes = 0; 1628 1629 // Adjust the stack pointer for the new arguments... 1630 // These operations are automatically eliminated by the prolog/epilog pass 1631 if (!isSibCall) 1632 Chain = DAG.getCALLSEQ_START(Chain, 1633 DAG.getIntPtrConstant(NumBytes, dl, true), dl); 1634 1635 SDValue StackPtr = 1636 DAG.getCopyFromReg(Chain, dl, ARM::SP, getPointerTy(DAG.getDataLayout())); 1637 1638 RegsToPassVector RegsToPass; 1639 SmallVector<SDValue, 8> MemOpChains; 1640 1641 // Walk the register/memloc assignments, inserting copies/loads. In the case 1642 // of tail call optimization, arguments are handled later. 1643 for (unsigned i = 0, realArgIdx = 0, e = ArgLocs.size(); 1644 i != e; 1645 ++i, ++realArgIdx) { 1646 CCValAssign &VA = ArgLocs[i]; 1647 SDValue Arg = OutVals[realArgIdx]; 1648 ISD::ArgFlagsTy Flags = Outs[realArgIdx].Flags; 1649 bool isByVal = Flags.isByVal(); 1650 1651 // Promote the value if needed. 1652 switch (VA.getLocInfo()) { 1653 default: llvm_unreachable("Unknown loc info!"); 1654 case CCValAssign::Full: break; 1655 case CCValAssign::SExt: 1656 Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), Arg); 1657 break; 1658 case CCValAssign::ZExt: 1659 Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, VA.getLocVT(), Arg); 1660 break; 1661 case CCValAssign::AExt: 1662 Arg = DAG.getNode(ISD::ANY_EXTEND, dl, VA.getLocVT(), Arg); 1663 break; 1664 case CCValAssign::BCvt: 1665 Arg = DAG.getNode(ISD::BITCAST, dl, VA.getLocVT(), Arg); 1666 break; 1667 } 1668 1669 // f64 and v2f64 might be passed in i32 pairs and must be split into pieces 1670 if (VA.needsCustom()) { 1671 if (VA.getLocVT() == MVT::v2f64) { 1672 SDValue Op0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg, 1673 DAG.getConstant(0, dl, MVT::i32)); 1674 SDValue Op1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg, 1675 DAG.getConstant(1, dl, MVT::i32)); 1676 1677 PassF64ArgInRegs(dl, DAG, Chain, Op0, RegsToPass, 1678 VA, ArgLocs[++i], StackPtr, MemOpChains, Flags); 1679 1680 VA = ArgLocs[++i]; // skip ahead to next loc 1681 if (VA.isRegLoc()) { 1682 PassF64ArgInRegs(dl, DAG, Chain, Op1, RegsToPass, 1683 VA, ArgLocs[++i], StackPtr, MemOpChains, Flags); 1684 } else { 1685 assert(VA.isMemLoc()); 1686 1687 MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, Op1, 1688 dl, DAG, VA, Flags)); 1689 } 1690 } else { 1691 PassF64ArgInRegs(dl, DAG, Chain, Arg, RegsToPass, VA, ArgLocs[++i], 1692 StackPtr, MemOpChains, Flags); 1693 } 1694 } else if (VA.isRegLoc()) { 1695 if (realArgIdx == 0 && Flags.isReturned() && Outs[0].VT == MVT::i32) { 1696 assert(VA.getLocVT() == MVT::i32 && 1697 "unexpected calling convention register assignment"); 1698 assert(!Ins.empty() && Ins[0].VT == MVT::i32 && 1699 "unexpected use of 'returned'"); 1700 isThisReturn = true; 1701 } 1702 RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg)); 1703 } else if (isByVal) { 1704 assert(VA.isMemLoc()); 1705 unsigned offset = 0; 1706 1707 // True if this byval aggregate will be split between registers 1708 // and memory. 1709 unsigned ByValArgsCount = CCInfo.getInRegsParamsCount(); 1710 unsigned CurByValIdx = CCInfo.getInRegsParamsProcessed(); 1711 1712 if (CurByValIdx < ByValArgsCount) { 1713 1714 unsigned RegBegin, RegEnd; 1715 CCInfo.getInRegsParamInfo(CurByValIdx, RegBegin, RegEnd); 1716 1717 EVT PtrVT = 1718 DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout()); 1719 unsigned int i, j; 1720 for (i = 0, j = RegBegin; j < RegEnd; i++, j++) { 1721 SDValue Const = DAG.getConstant(4*i, dl, MVT::i32); 1722 SDValue AddArg = DAG.getNode(ISD::ADD, dl, PtrVT, Arg, Const); 1723 SDValue Load = DAG.getLoad(PtrVT, dl, Chain, AddArg, 1724 MachinePointerInfo(), 1725 false, false, false, 1726 DAG.InferPtrAlignment(AddArg)); 1727 MemOpChains.push_back(Load.getValue(1)); 1728 RegsToPass.push_back(std::make_pair(j, Load)); 1729 } 1730 1731 // If parameter size outsides register area, "offset" value 1732 // helps us to calculate stack slot for remained part properly. 1733 offset = RegEnd - RegBegin; 1734 1735 CCInfo.nextInRegsParam(); 1736 } 1737 1738 if (Flags.getByValSize() > 4*offset) { 1739 auto PtrVT = getPointerTy(DAG.getDataLayout()); 1740 unsigned LocMemOffset = VA.getLocMemOffset(); 1741 SDValue StkPtrOff = DAG.getIntPtrConstant(LocMemOffset, dl); 1742 SDValue Dst = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, StkPtrOff); 1743 SDValue SrcOffset = DAG.getIntPtrConstant(4*offset, dl); 1744 SDValue Src = DAG.getNode(ISD::ADD, dl, PtrVT, Arg, SrcOffset); 1745 SDValue SizeNode = DAG.getConstant(Flags.getByValSize() - 4*offset, dl, 1746 MVT::i32); 1747 SDValue AlignNode = DAG.getConstant(Flags.getByValAlign(), dl, 1748 MVT::i32); 1749 1750 SDVTList VTs = DAG.getVTList(MVT::Other, MVT::Glue); 1751 SDValue Ops[] = { Chain, Dst, Src, SizeNode, AlignNode}; 1752 MemOpChains.push_back(DAG.getNode(ARMISD::COPY_STRUCT_BYVAL, dl, VTs, 1753 Ops)); 1754 } 1755 } else if (!isSibCall) { 1756 assert(VA.isMemLoc()); 1757 1758 MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, Arg, 1759 dl, DAG, VA, Flags)); 1760 } 1761 } 1762 1763 if (!MemOpChains.empty()) 1764 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains); 1765 1766 // Build a sequence of copy-to-reg nodes chained together with token chain 1767 // and flag operands which copy the outgoing args into the appropriate regs. 1768 SDValue InFlag; 1769 // Tail call byval lowering might overwrite argument registers so in case of 1770 // tail call optimization the copies to registers are lowered later. 1771 if (!isTailCall) 1772 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) { 1773 Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first, 1774 RegsToPass[i].second, InFlag); 1775 InFlag = Chain.getValue(1); 1776 } 1777 1778 // For tail calls lower the arguments to the 'real' stack slot. 1779 if (isTailCall) { 1780 // Force all the incoming stack arguments to be loaded from the stack 1781 // before any new outgoing arguments are stored to the stack, because the 1782 // outgoing stack slots may alias the incoming argument stack slots, and 1783 // the alias isn't otherwise explicit. This is slightly more conservative 1784 // than necessary, because it means that each store effectively depends 1785 // on every argument instead of just those arguments it would clobber. 1786 1787 // Do not flag preceding copytoreg stuff together with the following stuff. 1788 InFlag = SDValue(); 1789 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) { 1790 Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first, 1791 RegsToPass[i].second, InFlag); 1792 InFlag = Chain.getValue(1); 1793 } 1794 InFlag = SDValue(); 1795 } 1796 1797 // If the callee is a GlobalAddress/ExternalSymbol node (quite common, every 1798 // direct call is) turn it into a TargetGlobalAddress/TargetExternalSymbol 1799 // node so that legalize doesn't hack it. 1800 bool isDirect = false; 1801 bool isARMFunc = false; 1802 bool isLocalARMFunc = false; 1803 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>(); 1804 auto PtrVt = getPointerTy(DAG.getDataLayout()); 1805 1806 if (Subtarget->genLongCalls()) { 1807 assert((Subtarget->isTargetWindows() || 1808 getTargetMachine().getRelocationModel() == Reloc::Static) && 1809 "long-calls with non-static relocation model!"); 1810 // Handle a global address or an external symbol. If it's not one of 1811 // those, the target's already in a register, so we don't need to do 1812 // anything extra. 1813 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) { 1814 const GlobalValue *GV = G->getGlobal(); 1815 // Create a constant pool entry for the callee address 1816 unsigned ARMPCLabelIndex = AFI->createPICLabelUId(); 1817 ARMConstantPoolValue *CPV = 1818 ARMConstantPoolConstant::Create(GV, ARMPCLabelIndex, ARMCP::CPValue, 0); 1819 1820 // Get the address of the callee into a register 1821 SDValue CPAddr = DAG.getTargetConstantPool(CPV, PtrVt, 4); 1822 CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr); 1823 Callee = DAG.getLoad( 1824 PtrVt, dl, DAG.getEntryNode(), CPAddr, 1825 MachinePointerInfo::getConstantPool(DAG.getMachineFunction()), false, 1826 false, false, 0); 1827 } else if (ExternalSymbolSDNode *S=dyn_cast<ExternalSymbolSDNode>(Callee)) { 1828 const char *Sym = S->getSymbol(); 1829 1830 // Create a constant pool entry for the callee address 1831 unsigned ARMPCLabelIndex = AFI->createPICLabelUId(); 1832 ARMConstantPoolValue *CPV = 1833 ARMConstantPoolSymbol::Create(*DAG.getContext(), Sym, 1834 ARMPCLabelIndex, 0); 1835 // Get the address of the callee into a register 1836 SDValue CPAddr = DAG.getTargetConstantPool(CPV, PtrVt, 4); 1837 CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr); 1838 Callee = DAG.getLoad( 1839 PtrVt, dl, DAG.getEntryNode(), CPAddr, 1840 MachinePointerInfo::getConstantPool(DAG.getMachineFunction()), false, 1841 false, false, 0); 1842 } 1843 } else if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) { 1844 const GlobalValue *GV = G->getGlobal(); 1845 isDirect = true; 1846 bool isDef = GV->isStrongDefinitionForLinker(); 1847 bool isStub = (!isDef && Subtarget->isTargetMachO()) && 1848 getTargetMachine().getRelocationModel() != Reloc::Static; 1849 isARMFunc = !Subtarget->isThumb() || (isStub && !Subtarget->isMClass()); 1850 // ARM call to a local ARM function is predicable. 1851 isLocalARMFunc = !Subtarget->isThumb() && (isDef || !ARMInterworking); 1852 // tBX takes a register source operand. 1853 if (isStub && Subtarget->isThumb1Only() && !Subtarget->hasV5TOps()) { 1854 assert(Subtarget->isTargetMachO() && "WrapperPIC use on non-MachO?"); 1855 Callee = DAG.getNode( 1856 ARMISD::WrapperPIC, dl, PtrVt, 1857 DAG.getTargetGlobalAddress(GV, dl, PtrVt, 0, ARMII::MO_NONLAZY)); 1858 Callee = DAG.getLoad(PtrVt, dl, DAG.getEntryNode(), Callee, 1859 MachinePointerInfo::getGOT(DAG.getMachineFunction()), 1860 false, false, true, 0); 1861 } else if (Subtarget->isTargetCOFF()) { 1862 assert(Subtarget->isTargetWindows() && 1863 "Windows is the only supported COFF target"); 1864 unsigned TargetFlags = GV->hasDLLImportStorageClass() 1865 ? ARMII::MO_DLLIMPORT 1866 : ARMII::MO_NO_FLAG; 1867 Callee = 1868 DAG.getTargetGlobalAddress(GV, dl, PtrVt, /*Offset=*/0, TargetFlags); 1869 if (GV->hasDLLImportStorageClass()) 1870 Callee = 1871 DAG.getLoad(PtrVt, dl, DAG.getEntryNode(), 1872 DAG.getNode(ARMISD::Wrapper, dl, PtrVt, Callee), 1873 MachinePointerInfo::getGOT(DAG.getMachineFunction()), 1874 false, false, false, 0); 1875 } else { 1876 // On ELF targets for PIC code, direct calls should go through the PLT 1877 unsigned OpFlags = 0; 1878 if (Subtarget->isTargetELF() && 1879 getTargetMachine().getRelocationModel() == Reloc::PIC_) 1880 OpFlags = ARMII::MO_PLT; 1881 Callee = DAG.getTargetGlobalAddress(GV, dl, PtrVt, 0, OpFlags); 1882 } 1883 } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) { 1884 isDirect = true; 1885 bool isStub = Subtarget->isTargetMachO() && 1886 getTargetMachine().getRelocationModel() != Reloc::Static; 1887 isARMFunc = !Subtarget->isThumb() || (isStub && !Subtarget->isMClass()); 1888 // tBX takes a register source operand. 1889 const char *Sym = S->getSymbol(); 1890 if (isARMFunc && Subtarget->isThumb1Only() && !Subtarget->hasV5TOps()) { 1891 unsigned ARMPCLabelIndex = AFI->createPICLabelUId(); 1892 ARMConstantPoolValue *CPV = 1893 ARMConstantPoolSymbol::Create(*DAG.getContext(), Sym, 1894 ARMPCLabelIndex, 4); 1895 SDValue CPAddr = DAG.getTargetConstantPool(CPV, PtrVt, 4); 1896 CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr); 1897 Callee = DAG.getLoad( 1898 PtrVt, dl, DAG.getEntryNode(), CPAddr, 1899 MachinePointerInfo::getConstantPool(DAG.getMachineFunction()), false, 1900 false, false, 0); 1901 SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, dl, MVT::i32); 1902 Callee = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVt, Callee, PICLabel); 1903 } else { 1904 unsigned OpFlags = 0; 1905 // On ELF targets for PIC code, direct calls should go through the PLT 1906 if (Subtarget->isTargetELF() && 1907 getTargetMachine().getRelocationModel() == Reloc::PIC_) 1908 OpFlags = ARMII::MO_PLT; 1909 Callee = DAG.getTargetExternalSymbol(Sym, PtrVt, OpFlags); 1910 } 1911 } 1912 1913 // FIXME: handle tail calls differently. 1914 unsigned CallOpc; 1915 if (Subtarget->isThumb()) { 1916 if ((!isDirect || isARMFunc) && !Subtarget->hasV5TOps()) 1917 CallOpc = ARMISD::CALL_NOLINK; 1918 else 1919 CallOpc = isARMFunc ? ARMISD::CALL : ARMISD::tCALL; 1920 } else { 1921 if (!isDirect && !Subtarget->hasV5TOps()) 1922 CallOpc = ARMISD::CALL_NOLINK; 1923 else if (doesNotRet && isDirect && Subtarget->hasRAS() && 1924 // Emit regular call when code size is the priority 1925 !MF.getFunction()->optForMinSize()) 1926 // "mov lr, pc; b _foo" to avoid confusing the RSP 1927 CallOpc = ARMISD::CALL_NOLINK; 1928 else 1929 CallOpc = isLocalARMFunc ? ARMISD::CALL_PRED : ARMISD::CALL; 1930 } 1931 1932 std::vector<SDValue> Ops; 1933 Ops.push_back(Chain); 1934 Ops.push_back(Callee); 1935 1936 // Add argument registers to the end of the list so that they are known live 1937 // into the call. 1938 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) 1939 Ops.push_back(DAG.getRegister(RegsToPass[i].first, 1940 RegsToPass[i].second.getValueType())); 1941 1942 // Add a register mask operand representing the call-preserved registers. 1943 if (!isTailCall) { 1944 const uint32_t *Mask; 1945 const ARMBaseRegisterInfo *ARI = Subtarget->getRegisterInfo(); 1946 if (isThisReturn) { 1947 // For 'this' returns, use the R0-preserving mask if applicable 1948 Mask = ARI->getThisReturnPreservedMask(MF, CallConv); 1949 if (!Mask) { 1950 // Set isThisReturn to false if the calling convention is not one that 1951 // allows 'returned' to be modeled in this way, so LowerCallResult does 1952 // not try to pass 'this' straight through 1953 isThisReturn = false; 1954 Mask = ARI->getCallPreservedMask(MF, CallConv); 1955 } 1956 } else 1957 Mask = ARI->getCallPreservedMask(MF, CallConv); 1958 1959 assert(Mask && "Missing call preserved mask for calling convention"); 1960 Ops.push_back(DAG.getRegisterMask(Mask)); 1961 } 1962 1963 if (InFlag.getNode()) 1964 Ops.push_back(InFlag); 1965 1966 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue); 1967 if (isTailCall) { 1968 MF.getFrameInfo()->setHasTailCall(); 1969 return DAG.getNode(ARMISD::TC_RETURN, dl, NodeTys, Ops); 1970 } 1971 1972 // Returns a chain and a flag for retval copy to use. 1973 Chain = DAG.getNode(CallOpc, dl, NodeTys, Ops); 1974 InFlag = Chain.getValue(1); 1975 1976 Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, dl, true), 1977 DAG.getIntPtrConstant(0, dl, true), InFlag, dl); 1978 if (!Ins.empty()) 1979 InFlag = Chain.getValue(1); 1980 1981 // Handle result values, copying them out of physregs into vregs that we 1982 // return. 1983 return LowerCallResult(Chain, InFlag, CallConv, isVarArg, Ins, dl, DAG, 1984 InVals, isThisReturn, 1985 isThisReturn ? OutVals[0] : SDValue()); 1986 } 1987 1988 /// HandleByVal - Every parameter *after* a byval parameter is passed 1989 /// on the stack. Remember the next parameter register to allocate, 1990 /// and then confiscate the rest of the parameter registers to insure 1991 /// this. 1992 void ARMTargetLowering::HandleByVal(CCState *State, unsigned &Size, 1993 unsigned Align) const { 1994 assert((State->getCallOrPrologue() == Prologue || 1995 State->getCallOrPrologue() == Call) && 1996 "unhandled ParmContext"); 1997 1998 // Byval (as with any stack) slots are always at least 4 byte aligned. 1999 Align = std::max(Align, 4U); 2000 2001 unsigned Reg = State->AllocateReg(GPRArgRegs); 2002 if (!Reg) 2003 return; 2004 2005 unsigned AlignInRegs = Align / 4; 2006 unsigned Waste = (ARM::R4 - Reg) % AlignInRegs; 2007 for (unsigned i = 0; i < Waste; ++i) 2008 Reg = State->AllocateReg(GPRArgRegs); 2009 2010 if (!Reg) 2011 return; 2012 2013 unsigned Excess = 4 * (ARM::R4 - Reg); 2014 2015 // Special case when NSAA != SP and parameter size greater than size of 2016 // all remained GPR regs. In that case we can't split parameter, we must 2017 // send it to stack. We also must set NCRN to R4, so waste all 2018 // remained registers. 2019 const unsigned NSAAOffset = State->getNextStackOffset(); 2020 if (NSAAOffset != 0 && Size > Excess) { 2021 while (State->AllocateReg(GPRArgRegs)) 2022 ; 2023 return; 2024 } 2025 2026 // First register for byval parameter is the first register that wasn't 2027 // allocated before this method call, so it would be "reg". 2028 // If parameter is small enough to be saved in range [reg, r4), then 2029 // the end (first after last) register would be reg + param-size-in-regs, 2030 // else parameter would be splitted between registers and stack, 2031 // end register would be r4 in this case. 2032 unsigned ByValRegBegin = Reg; 2033 unsigned ByValRegEnd = std::min<unsigned>(Reg + Size / 4, ARM::R4); 2034 State->addInRegsParamInfo(ByValRegBegin, ByValRegEnd); 2035 // Note, first register is allocated in the beginning of function already, 2036 // allocate remained amount of registers we need. 2037 for (unsigned i = Reg + 1; i != ByValRegEnd; ++i) 2038 State->AllocateReg(GPRArgRegs); 2039 // A byval parameter that is split between registers and memory needs its 2040 // size truncated here. 2041 // In the case where the entire structure fits in registers, we set the 2042 // size in memory to zero. 2043 Size = std::max<int>(Size - Excess, 0); 2044 } 2045 2046 /// MatchingStackOffset - Return true if the given stack call argument is 2047 /// already available in the same position (relatively) of the caller's 2048 /// incoming argument stack. 2049 static 2050 bool MatchingStackOffset(SDValue Arg, unsigned Offset, ISD::ArgFlagsTy Flags, 2051 MachineFrameInfo *MFI, const MachineRegisterInfo *MRI, 2052 const TargetInstrInfo *TII) { 2053 unsigned Bytes = Arg.getValueType().getSizeInBits() / 8; 2054 int FI = INT_MAX; 2055 if (Arg.getOpcode() == ISD::CopyFromReg) { 2056 unsigned VR = cast<RegisterSDNode>(Arg.getOperand(1))->getReg(); 2057 if (!TargetRegisterInfo::isVirtualRegister(VR)) 2058 return false; 2059 MachineInstr *Def = MRI->getVRegDef(VR); 2060 if (!Def) 2061 return false; 2062 if (!Flags.isByVal()) { 2063 if (!TII->isLoadFromStackSlot(Def, FI)) 2064 return false; 2065 } else { 2066 return false; 2067 } 2068 } else if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Arg)) { 2069 if (Flags.isByVal()) 2070 // ByVal argument is passed in as a pointer but it's now being 2071 // dereferenced. e.g. 2072 // define @foo(%struct.X* %A) { 2073 // tail call @bar(%struct.X* byval %A) 2074 // } 2075 return false; 2076 SDValue Ptr = Ld->getBasePtr(); 2077 FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr); 2078 if (!FINode) 2079 return false; 2080 FI = FINode->getIndex(); 2081 } else 2082 return false; 2083 2084 assert(FI != INT_MAX); 2085 if (!MFI->isFixedObjectIndex(FI)) 2086 return false; 2087 return Offset == MFI->getObjectOffset(FI) && Bytes == MFI->getObjectSize(FI); 2088 } 2089 2090 /// IsEligibleForTailCallOptimization - Check whether the call is eligible 2091 /// for tail call optimization. Targets which want to do tail call 2092 /// optimization should implement this function. 2093 bool 2094 ARMTargetLowering::IsEligibleForTailCallOptimization(SDValue Callee, 2095 CallingConv::ID CalleeCC, 2096 bool isVarArg, 2097 bool isCalleeStructRet, 2098 bool isCallerStructRet, 2099 const SmallVectorImpl<ISD::OutputArg> &Outs, 2100 const SmallVectorImpl<SDValue> &OutVals, 2101 const SmallVectorImpl<ISD::InputArg> &Ins, 2102 SelectionDAG& DAG) const { 2103 const Function *CallerF = DAG.getMachineFunction().getFunction(); 2104 CallingConv::ID CallerCC = CallerF->getCallingConv(); 2105 bool CCMatch = CallerCC == CalleeCC; 2106 2107 // Disable tailcall for CXX_FAST_TLS when callee and caller have different 2108 // calling conventions, given that CXX_FAST_TLS has a bigger CSR set. 2109 if (!CCMatch && 2110 (CallerCC == CallingConv::CXX_FAST_TLS || 2111 CalleeCC == CallingConv::CXX_FAST_TLS)) 2112 return false; 2113 2114 assert(Subtarget->supportsTailCall()); 2115 2116 // Look for obvious safe cases to perform tail call optimization that do not 2117 // require ABI changes. This is what gcc calls sibcall. 2118 2119 // Do not sibcall optimize vararg calls unless the call site is not passing 2120 // any arguments. 2121 if (isVarArg && !Outs.empty()) 2122 return false; 2123 2124 // Exception-handling functions need a special set of instructions to indicate 2125 // a return to the hardware. Tail-calling another function would probably 2126 // break this. 2127 if (CallerF->hasFnAttribute("interrupt")) 2128 return false; 2129 2130 // Also avoid sibcall optimization if either caller or callee uses struct 2131 // return semantics. 2132 if (isCalleeStructRet || isCallerStructRet) 2133 return false; 2134 2135 // Externally-defined functions with weak linkage should not be 2136 // tail-called on ARM when the OS does not support dynamic 2137 // pre-emption of symbols, as the AAELF spec requires normal calls 2138 // to undefined weak functions to be replaced with a NOP or jump to the 2139 // next instruction. The behaviour of branch instructions in this 2140 // situation (as used for tail calls) is implementation-defined, so we 2141 // cannot rely on the linker replacing the tail call with a return. 2142 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) { 2143 const GlobalValue *GV = G->getGlobal(); 2144 const Triple &TT = getTargetMachine().getTargetTriple(); 2145 if (GV->hasExternalWeakLinkage() && 2146 (!TT.isOSWindows() || TT.isOSBinFormatELF() || TT.isOSBinFormatMachO())) 2147 return false; 2148 } 2149 2150 // If the calling conventions do not match, then we'd better make sure the 2151 // results are returned in the same way as what the caller expects. 2152 if (!CCMatch) { 2153 SmallVector<CCValAssign, 16> RVLocs1; 2154 ARMCCState CCInfo1(CalleeCC, false, DAG.getMachineFunction(), RVLocs1, 2155 *DAG.getContext(), Call); 2156 CCInfo1.AnalyzeCallResult(Ins, CCAssignFnForNode(CalleeCC, true, isVarArg)); 2157 2158 SmallVector<CCValAssign, 16> RVLocs2; 2159 ARMCCState CCInfo2(CallerCC, false, DAG.getMachineFunction(), RVLocs2, 2160 *DAG.getContext(), Call); 2161 CCInfo2.AnalyzeCallResult(Ins, CCAssignFnForNode(CallerCC, true, isVarArg)); 2162 2163 if (RVLocs1.size() != RVLocs2.size()) 2164 return false; 2165 for (unsigned i = 0, e = RVLocs1.size(); i != e; ++i) { 2166 if (RVLocs1[i].isRegLoc() != RVLocs2[i].isRegLoc()) 2167 return false; 2168 if (RVLocs1[i].getLocInfo() != RVLocs2[i].getLocInfo()) 2169 return false; 2170 if (RVLocs1[i].isRegLoc()) { 2171 if (RVLocs1[i].getLocReg() != RVLocs2[i].getLocReg()) 2172 return false; 2173 } else { 2174 if (RVLocs1[i].getLocMemOffset() != RVLocs2[i].getLocMemOffset()) 2175 return false; 2176 } 2177 } 2178 } 2179 2180 // If Caller's vararg or byval argument has been split between registers and 2181 // stack, do not perform tail call, since part of the argument is in caller's 2182 // local frame. 2183 const ARMFunctionInfo *AFI_Caller = DAG.getMachineFunction(). 2184 getInfo<ARMFunctionInfo>(); 2185 if (AFI_Caller->getArgRegsSaveSize()) 2186 return false; 2187 2188 // If the callee takes no arguments then go on to check the results of the 2189 // call. 2190 if (!Outs.empty()) { 2191 // Check if stack adjustment is needed. For now, do not do this if any 2192 // argument is passed on the stack. 2193 SmallVector<CCValAssign, 16> ArgLocs; 2194 ARMCCState CCInfo(CalleeCC, isVarArg, DAG.getMachineFunction(), ArgLocs, 2195 *DAG.getContext(), Call); 2196 CCInfo.AnalyzeCallOperands(Outs, 2197 CCAssignFnForNode(CalleeCC, false, isVarArg)); 2198 if (CCInfo.getNextStackOffset()) { 2199 MachineFunction &MF = DAG.getMachineFunction(); 2200 2201 // Check if the arguments are already laid out in the right way as 2202 // the caller's fixed stack objects. 2203 MachineFrameInfo *MFI = MF.getFrameInfo(); 2204 const MachineRegisterInfo *MRI = &MF.getRegInfo(); 2205 const TargetInstrInfo *TII = Subtarget->getInstrInfo(); 2206 for (unsigned i = 0, realArgIdx = 0, e = ArgLocs.size(); 2207 i != e; 2208 ++i, ++realArgIdx) { 2209 CCValAssign &VA = ArgLocs[i]; 2210 EVT RegVT = VA.getLocVT(); 2211 SDValue Arg = OutVals[realArgIdx]; 2212 ISD::ArgFlagsTy Flags = Outs[realArgIdx].Flags; 2213 if (VA.getLocInfo() == CCValAssign::Indirect) 2214 return false; 2215 if (VA.needsCustom()) { 2216 // f64 and vector types are split into multiple registers or 2217 // register/stack-slot combinations. The types will not match 2218 // the registers; give up on memory f64 refs until we figure 2219 // out what to do about this. 2220 if (!VA.isRegLoc()) 2221 return false; 2222 if (!ArgLocs[++i].isRegLoc()) 2223 return false; 2224 if (RegVT == MVT::v2f64) { 2225 if (!ArgLocs[++i].isRegLoc()) 2226 return false; 2227 if (!ArgLocs[++i].isRegLoc()) 2228 return false; 2229 } 2230 } else if (!VA.isRegLoc()) { 2231 if (!MatchingStackOffset(Arg, VA.getLocMemOffset(), Flags, 2232 MFI, MRI, TII)) 2233 return false; 2234 } 2235 } 2236 } 2237 } 2238 2239 return true; 2240 } 2241 2242 bool 2243 ARMTargetLowering::CanLowerReturn(CallingConv::ID CallConv, 2244 MachineFunction &MF, bool isVarArg, 2245 const SmallVectorImpl<ISD::OutputArg> &Outs, 2246 LLVMContext &Context) const { 2247 SmallVector<CCValAssign, 16> RVLocs; 2248 CCState CCInfo(CallConv, isVarArg, MF, RVLocs, Context); 2249 return CCInfo.CheckReturn(Outs, CCAssignFnForNode(CallConv, /*Return=*/true, 2250 isVarArg)); 2251 } 2252 2253 static SDValue LowerInterruptReturn(SmallVectorImpl<SDValue> &RetOps, 2254 SDLoc DL, SelectionDAG &DAG) { 2255 const MachineFunction &MF = DAG.getMachineFunction(); 2256 const Function *F = MF.getFunction(); 2257 2258 StringRef IntKind = F->getFnAttribute("interrupt").getValueAsString(); 2259 2260 // See ARM ARM v7 B1.8.3. On exception entry LR is set to a possibly offset 2261 // version of the "preferred return address". These offsets affect the return 2262 // instruction if this is a return from PL1 without hypervisor extensions. 2263 // IRQ/FIQ: +4 "subs pc, lr, #4" 2264 // SWI: 0 "subs pc, lr, #0" 2265 // ABORT: +4 "subs pc, lr, #4" 2266 // UNDEF: +4/+2 "subs pc, lr, #0" 2267 // UNDEF varies depending on where the exception came from ARM or Thumb 2268 // mode. Alongside GCC, we throw our hands up in disgust and pretend it's 0. 2269 2270 int64_t LROffset; 2271 if (IntKind == "" || IntKind == "IRQ" || IntKind == "FIQ" || 2272 IntKind == "ABORT") 2273 LROffset = 4; 2274 else if (IntKind == "SWI" || IntKind == "UNDEF") 2275 LROffset = 0; 2276 else 2277 report_fatal_error("Unsupported interrupt attribute. If present, value " 2278 "must be one of: IRQ, FIQ, SWI, ABORT or UNDEF"); 2279 2280 RetOps.insert(RetOps.begin() + 1, 2281 DAG.getConstant(LROffset, DL, MVT::i32, false)); 2282 2283 return DAG.getNode(ARMISD::INTRET_FLAG, DL, MVT::Other, RetOps); 2284 } 2285 2286 SDValue 2287 ARMTargetLowering::LowerReturn(SDValue Chain, 2288 CallingConv::ID CallConv, bool isVarArg, 2289 const SmallVectorImpl<ISD::OutputArg> &Outs, 2290 const SmallVectorImpl<SDValue> &OutVals, 2291 SDLoc dl, SelectionDAG &DAG) const { 2292 2293 // CCValAssign - represent the assignment of the return value to a location. 2294 SmallVector<CCValAssign, 16> RVLocs; 2295 2296 // CCState - Info about the registers and stack slots. 2297 ARMCCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs, 2298 *DAG.getContext(), Call); 2299 2300 // Analyze outgoing return values. 2301 CCInfo.AnalyzeReturn(Outs, CCAssignFnForNode(CallConv, /* Return */ true, 2302 isVarArg)); 2303 2304 SDValue Flag; 2305 SmallVector<SDValue, 4> RetOps; 2306 RetOps.push_back(Chain); // Operand #0 = Chain (updated below) 2307 bool isLittleEndian = Subtarget->isLittle(); 2308 2309 MachineFunction &MF = DAG.getMachineFunction(); 2310 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>(); 2311 AFI->setReturnRegsCount(RVLocs.size()); 2312 2313 // Copy the result values into the output registers. 2314 for (unsigned i = 0, realRVLocIdx = 0; 2315 i != RVLocs.size(); 2316 ++i, ++realRVLocIdx) { 2317 CCValAssign &VA = RVLocs[i]; 2318 assert(VA.isRegLoc() && "Can only return in registers!"); 2319 2320 SDValue Arg = OutVals[realRVLocIdx]; 2321 2322 switch (VA.getLocInfo()) { 2323 default: llvm_unreachable("Unknown loc info!"); 2324 case CCValAssign::Full: break; 2325 case CCValAssign::BCvt: 2326 Arg = DAG.getNode(ISD::BITCAST, dl, VA.getLocVT(), Arg); 2327 break; 2328 } 2329 2330 if (VA.needsCustom()) { 2331 if (VA.getLocVT() == MVT::v2f64) { 2332 // Extract the first half and return it in two registers. 2333 SDValue Half = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg, 2334 DAG.getConstant(0, dl, MVT::i32)); 2335 SDValue HalfGPRs = DAG.getNode(ARMISD::VMOVRRD, dl, 2336 DAG.getVTList(MVT::i32, MVT::i32), Half); 2337 2338 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), 2339 HalfGPRs.getValue(isLittleEndian ? 0 : 1), 2340 Flag); 2341 Flag = Chain.getValue(1); 2342 RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT())); 2343 VA = RVLocs[++i]; // skip ahead to next loc 2344 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), 2345 HalfGPRs.getValue(isLittleEndian ? 1 : 0), 2346 Flag); 2347 Flag = Chain.getValue(1); 2348 RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT())); 2349 VA = RVLocs[++i]; // skip ahead to next loc 2350 2351 // Extract the 2nd half and fall through to handle it as an f64 value. 2352 Arg = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg, 2353 DAG.getConstant(1, dl, MVT::i32)); 2354 } 2355 // Legalize ret f64 -> ret 2 x i32. We always have fmrrd if f64 is 2356 // available. 2357 SDValue fmrrd = DAG.getNode(ARMISD::VMOVRRD, dl, 2358 DAG.getVTList(MVT::i32, MVT::i32), Arg); 2359 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), 2360 fmrrd.getValue(isLittleEndian ? 0 : 1), 2361 Flag); 2362 Flag = Chain.getValue(1); 2363 RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT())); 2364 VA = RVLocs[++i]; // skip ahead to next loc 2365 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), 2366 fmrrd.getValue(isLittleEndian ? 1 : 0), 2367 Flag); 2368 } else 2369 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), Arg, Flag); 2370 2371 // Guarantee that all emitted copies are 2372 // stuck together, avoiding something bad. 2373 Flag = Chain.getValue(1); 2374 RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT())); 2375 } 2376 const ARMBaseRegisterInfo *TRI = Subtarget->getRegisterInfo(); 2377 const MCPhysReg *I = 2378 TRI->getCalleeSavedRegsViaCopy(&DAG.getMachineFunction()); 2379 if (I) { 2380 for (; *I; ++I) { 2381 if (ARM::GPRRegClass.contains(*I)) 2382 RetOps.push_back(DAG.getRegister(*I, MVT::i32)); 2383 else if (ARM::DPRRegClass.contains(*I)) 2384 RetOps.push_back(DAG.getRegister(*I, MVT::getFloatingPointVT(64))); 2385 else 2386 llvm_unreachable("Unexpected register class in CSRsViaCopy!"); 2387 } 2388 } 2389 2390 // Update chain and glue. 2391 RetOps[0] = Chain; 2392 if (Flag.getNode()) 2393 RetOps.push_back(Flag); 2394 2395 // CPUs which aren't M-class use a special sequence to return from 2396 // exceptions (roughly, any instruction setting pc and cpsr simultaneously, 2397 // though we use "subs pc, lr, #N"). 2398 // 2399 // M-class CPUs actually use a normal return sequence with a special 2400 // (hardware-provided) value in LR, so the normal code path works. 2401 if (DAG.getMachineFunction().getFunction()->hasFnAttribute("interrupt") && 2402 !Subtarget->isMClass()) { 2403 if (Subtarget->isThumb1Only()) 2404 report_fatal_error("interrupt attribute is not supported in Thumb1"); 2405 return LowerInterruptReturn(RetOps, dl, DAG); 2406 } 2407 2408 return DAG.getNode(ARMISD::RET_FLAG, dl, MVT::Other, RetOps); 2409 } 2410 2411 bool ARMTargetLowering::isUsedByReturnOnly(SDNode *N, SDValue &Chain) const { 2412 if (N->getNumValues() != 1) 2413 return false; 2414 if (!N->hasNUsesOfValue(1, 0)) 2415 return false; 2416 2417 SDValue TCChain = Chain; 2418 SDNode *Copy = *N->use_begin(); 2419 if (Copy->getOpcode() == ISD::CopyToReg) { 2420 // If the copy has a glue operand, we conservatively assume it isn't safe to 2421 // perform a tail call. 2422 if (Copy->getOperand(Copy->getNumOperands()-1).getValueType() == MVT::Glue) 2423 return false; 2424 TCChain = Copy->getOperand(0); 2425 } else if (Copy->getOpcode() == ARMISD::VMOVRRD) { 2426 SDNode *VMov = Copy; 2427 // f64 returned in a pair of GPRs. 2428 SmallPtrSet<SDNode*, 2> Copies; 2429 for (SDNode::use_iterator UI = VMov->use_begin(), UE = VMov->use_end(); 2430 UI != UE; ++UI) { 2431 if (UI->getOpcode() != ISD::CopyToReg) 2432 return false; 2433 Copies.insert(*UI); 2434 } 2435 if (Copies.size() > 2) 2436 return false; 2437 2438 for (SDNode::use_iterator UI = VMov->use_begin(), UE = VMov->use_end(); 2439 UI != UE; ++UI) { 2440 SDValue UseChain = UI->getOperand(0); 2441 if (Copies.count(UseChain.getNode())) 2442 // Second CopyToReg 2443 Copy = *UI; 2444 else { 2445 // We are at the top of this chain. 2446 // If the copy has a glue operand, we conservatively assume it 2447 // isn't safe to perform a tail call. 2448 if (UI->getOperand(UI->getNumOperands()-1).getValueType() == MVT::Glue) 2449 return false; 2450 // First CopyToReg 2451 TCChain = UseChain; 2452 } 2453 } 2454 } else if (Copy->getOpcode() == ISD::BITCAST) { 2455 // f32 returned in a single GPR. 2456 if (!Copy->hasOneUse()) 2457 return false; 2458 Copy = *Copy->use_begin(); 2459 if (Copy->getOpcode() != ISD::CopyToReg || !Copy->hasNUsesOfValue(1, 0)) 2460 return false; 2461 // If the copy has a glue operand, we conservatively assume it isn't safe to 2462 // perform a tail call. 2463 if (Copy->getOperand(Copy->getNumOperands()-1).getValueType() == MVT::Glue) 2464 return false; 2465 TCChain = Copy->getOperand(0); 2466 } else { 2467 return false; 2468 } 2469 2470 bool HasRet = false; 2471 for (SDNode::use_iterator UI = Copy->use_begin(), UE = Copy->use_end(); 2472 UI != UE; ++UI) { 2473 if (UI->getOpcode() != ARMISD::RET_FLAG && 2474 UI->getOpcode() != ARMISD::INTRET_FLAG) 2475 return false; 2476 HasRet = true; 2477 } 2478 2479 if (!HasRet) 2480 return false; 2481 2482 Chain = TCChain; 2483 return true; 2484 } 2485 2486 bool ARMTargetLowering::mayBeEmittedAsTailCall(CallInst *CI) const { 2487 if (!Subtarget->supportsTailCall()) 2488 return false; 2489 2490 auto Attr = 2491 CI->getParent()->getParent()->getFnAttribute("disable-tail-calls"); 2492 if (!CI->isTailCall() || Attr.getValueAsString() == "true") 2493 return false; 2494 2495 return true; 2496 } 2497 2498 // Trying to write a 64 bit value so need to split into two 32 bit values first, 2499 // and pass the lower and high parts through. 2500 static SDValue LowerWRITE_REGISTER(SDValue Op, SelectionDAG &DAG) { 2501 SDLoc DL(Op); 2502 SDValue WriteValue = Op->getOperand(2); 2503 2504 // This function is only supposed to be called for i64 type argument. 2505 assert(WriteValue.getValueType() == MVT::i64 2506 && "LowerWRITE_REGISTER called for non-i64 type argument."); 2507 2508 SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, WriteValue, 2509 DAG.getConstant(0, DL, MVT::i32)); 2510 SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, WriteValue, 2511 DAG.getConstant(1, DL, MVT::i32)); 2512 SDValue Ops[] = { Op->getOperand(0), Op->getOperand(1), Lo, Hi }; 2513 return DAG.getNode(ISD::WRITE_REGISTER, DL, MVT::Other, Ops); 2514 } 2515 2516 // ConstantPool, JumpTable, GlobalAddress, and ExternalSymbol are lowered as 2517 // their target counterpart wrapped in the ARMISD::Wrapper node. Suppose N is 2518 // one of the above mentioned nodes. It has to be wrapped because otherwise 2519 // Select(N) returns N. So the raw TargetGlobalAddress nodes, etc. can only 2520 // be used to form addressing mode. These wrapped nodes will be selected 2521 // into MOVi. 2522 static SDValue LowerConstantPool(SDValue Op, SelectionDAG &DAG) { 2523 EVT PtrVT = Op.getValueType(); 2524 // FIXME there is no actual debug info here 2525 SDLoc dl(Op); 2526 ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op); 2527 SDValue Res; 2528 if (CP->isMachineConstantPoolEntry()) 2529 Res = DAG.getTargetConstantPool(CP->getMachineCPVal(), PtrVT, 2530 CP->getAlignment()); 2531 else 2532 Res = DAG.getTargetConstantPool(CP->getConstVal(), PtrVT, 2533 CP->getAlignment()); 2534 return DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Res); 2535 } 2536 2537 unsigned ARMTargetLowering::getJumpTableEncoding() const { 2538 return MachineJumpTableInfo::EK_Inline; 2539 } 2540 2541 SDValue ARMTargetLowering::LowerBlockAddress(SDValue Op, 2542 SelectionDAG &DAG) const { 2543 MachineFunction &MF = DAG.getMachineFunction(); 2544 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>(); 2545 unsigned ARMPCLabelIndex = 0; 2546 SDLoc DL(Op); 2547 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 2548 const BlockAddress *BA = cast<BlockAddressSDNode>(Op)->getBlockAddress(); 2549 Reloc::Model RelocM = getTargetMachine().getRelocationModel(); 2550 SDValue CPAddr; 2551 if (RelocM == Reloc::Static) { 2552 CPAddr = DAG.getTargetConstantPool(BA, PtrVT, 4); 2553 } else { 2554 unsigned PCAdj = Subtarget->isThumb() ? 4 : 8; 2555 ARMPCLabelIndex = AFI->createPICLabelUId(); 2556 ARMConstantPoolValue *CPV = 2557 ARMConstantPoolConstant::Create(BA, ARMPCLabelIndex, 2558 ARMCP::CPBlockAddress, PCAdj); 2559 CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4); 2560 } 2561 CPAddr = DAG.getNode(ARMISD::Wrapper, DL, PtrVT, CPAddr); 2562 SDValue Result = 2563 DAG.getLoad(PtrVT, DL, DAG.getEntryNode(), CPAddr, 2564 MachinePointerInfo::getConstantPool(DAG.getMachineFunction()), 2565 false, false, false, 0); 2566 if (RelocM == Reloc::Static) 2567 return Result; 2568 SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, DL, MVT::i32); 2569 return DAG.getNode(ARMISD::PIC_ADD, DL, PtrVT, Result, PICLabel); 2570 } 2571 2572 /// \brief Convert a TLS address reference into the correct sequence of loads 2573 /// and calls to compute the variable's address for Darwin, and return an 2574 /// SDValue containing the final node. 2575 2576 /// Darwin only has one TLS scheme which must be capable of dealing with the 2577 /// fully general situation, in the worst case. This means: 2578 /// + "extern __thread" declaration. 2579 /// + Defined in a possibly unknown dynamic library. 2580 /// 2581 /// The general system is that each __thread variable has a [3 x i32] descriptor 2582 /// which contains information used by the runtime to calculate the address. The 2583 /// only part of this the compiler needs to know about is the first word, which 2584 /// contains a function pointer that must be called with the address of the 2585 /// entire descriptor in "r0". 2586 /// 2587 /// Since this descriptor may be in a different unit, in general access must 2588 /// proceed along the usual ARM rules. A common sequence to produce is: 2589 /// 2590 /// movw rT1, :lower16:_var$non_lazy_ptr 2591 /// movt rT1, :upper16:_var$non_lazy_ptr 2592 /// ldr r0, [rT1] 2593 /// ldr rT2, [r0] 2594 /// blx rT2 2595 /// [...address now in r0...] 2596 SDValue 2597 ARMTargetLowering::LowerGlobalTLSAddressDarwin(SDValue Op, 2598 SelectionDAG &DAG) const { 2599 assert(Subtarget->isTargetDarwin() && "TLS only supported on Darwin"); 2600 SDLoc DL(Op); 2601 2602 // First step is to get the address of the actua global symbol. This is where 2603 // the TLS descriptor lives. 2604 SDValue DescAddr = LowerGlobalAddressDarwin(Op, DAG); 2605 2606 // The first entry in the descriptor is a function pointer that we must call 2607 // to obtain the address of the variable. 2608 SDValue Chain = DAG.getEntryNode(); 2609 SDValue FuncTLVGet = 2610 DAG.getLoad(MVT::i32, DL, Chain, DescAddr, 2611 MachinePointerInfo::getGOT(DAG.getMachineFunction()), 2612 false, true, true, 4); 2613 Chain = FuncTLVGet.getValue(1); 2614 2615 MachineFunction &F = DAG.getMachineFunction(); 2616 MachineFrameInfo *MFI = F.getFrameInfo(); 2617 MFI->setAdjustsStack(true); 2618 2619 // TLS calls preserve all registers except those that absolutely must be 2620 // trashed: R0 (it takes an argument), LR (it's a call) and CPSR (let's not be 2621 // silly). 2622 auto TRI = 2623 getTargetMachine().getSubtargetImpl(*F.getFunction())->getRegisterInfo(); 2624 auto ARI = static_cast<const ARMRegisterInfo *>(TRI); 2625 const uint32_t *Mask = ARI->getTLSCallPreservedMask(DAG.getMachineFunction()); 2626 2627 // Finally, we can make the call. This is just a degenerate version of a 2628 // normal AArch64 call node: r0 takes the address of the descriptor, and 2629 // returns the address of the variable in this thread. 2630 Chain = DAG.getCopyToReg(Chain, DL, ARM::R0, DescAddr, SDValue()); 2631 Chain = 2632 DAG.getNode(ARMISD::CALL, DL, DAG.getVTList(MVT::Other, MVT::Glue), 2633 Chain, FuncTLVGet, DAG.getRegister(ARM::R0, MVT::i32), 2634 DAG.getRegisterMask(Mask), Chain.getValue(1)); 2635 return DAG.getCopyFromReg(Chain, DL, ARM::R0, MVT::i32, Chain.getValue(1)); 2636 } 2637 2638 SDValue 2639 ARMTargetLowering::LowerGlobalTLSAddressWindows(SDValue Op, 2640 SelectionDAG &DAG) const { 2641 assert(Subtarget->isTargetWindows() && "Windows specific TLS lowering"); 2642 SDValue Chain = DAG.getEntryNode(); 2643 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 2644 SDLoc DL(Op); 2645 2646 // Load the current TEB (thread environment block) 2647 SDValue Ops[] = {Chain, 2648 DAG.getConstant(Intrinsic::arm_mrc, DL, MVT::i32), 2649 DAG.getConstant(15, DL, MVT::i32), 2650 DAG.getConstant(0, DL, MVT::i32), 2651 DAG.getConstant(13, DL, MVT::i32), 2652 DAG.getConstant(0, DL, MVT::i32), 2653 DAG.getConstant(2, DL, MVT::i32)}; 2654 SDValue CurrentTEB = DAG.getNode(ISD::INTRINSIC_W_CHAIN, DL, 2655 DAG.getVTList(MVT::i32, MVT::Other), Ops); 2656 2657 SDValue TEB = CurrentTEB.getValue(0); 2658 Chain = CurrentTEB.getValue(1); 2659 2660 // Load the ThreadLocalStoragePointer from the TEB 2661 // A pointer to the TLS array is located at offset 0x2c from the TEB. 2662 SDValue TLSArray = 2663 DAG.getNode(ISD::ADD, DL, PtrVT, TEB, DAG.getIntPtrConstant(0x2c, DL)); 2664 TLSArray = DAG.getLoad(PtrVT, DL, Chain, TLSArray, MachinePointerInfo(), 2665 false, false, false, 0); 2666 2667 // The pointer to the thread's TLS data area is at the TLS Index scaled by 4 2668 // offset into the TLSArray. 2669 2670 // Load the TLS index from the C runtime 2671 SDValue TLSIndex = 2672 DAG.getTargetExternalSymbol("_tls_index", PtrVT, ARMII::MO_NO_FLAG); 2673 TLSIndex = DAG.getNode(ARMISD::Wrapper, DL, PtrVT, TLSIndex); 2674 TLSIndex = DAG.getLoad(PtrVT, DL, Chain, TLSIndex, MachinePointerInfo(), 2675 false, false, false, 0); 2676 2677 SDValue Slot = DAG.getNode(ISD::SHL, DL, PtrVT, TLSIndex, 2678 DAG.getConstant(2, DL, MVT::i32)); 2679 SDValue TLS = DAG.getLoad(PtrVT, DL, Chain, 2680 DAG.getNode(ISD::ADD, DL, PtrVT, TLSArray, Slot), 2681 MachinePointerInfo(), false, false, false, 0); 2682 2683 return DAG.getNode(ISD::ADD, DL, PtrVT, TLS, 2684 LowerGlobalAddressWindows(Op, DAG)); 2685 } 2686 2687 // Lower ISD::GlobalTLSAddress using the "general dynamic" model 2688 SDValue 2689 ARMTargetLowering::LowerToTLSGeneralDynamicModel(GlobalAddressSDNode *GA, 2690 SelectionDAG &DAG) const { 2691 SDLoc dl(GA); 2692 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 2693 unsigned char PCAdj = Subtarget->isThumb() ? 4 : 8; 2694 MachineFunction &MF = DAG.getMachineFunction(); 2695 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>(); 2696 unsigned ARMPCLabelIndex = AFI->createPICLabelUId(); 2697 ARMConstantPoolValue *CPV = 2698 ARMConstantPoolConstant::Create(GA->getGlobal(), ARMPCLabelIndex, 2699 ARMCP::CPValue, PCAdj, ARMCP::TLSGD, true); 2700 SDValue Argument = DAG.getTargetConstantPool(CPV, PtrVT, 4); 2701 Argument = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Argument); 2702 Argument = 2703 DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Argument, 2704 MachinePointerInfo::getConstantPool(DAG.getMachineFunction()), 2705 false, false, false, 0); 2706 SDValue Chain = Argument.getValue(1); 2707 2708 SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, dl, MVT::i32); 2709 Argument = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Argument, PICLabel); 2710 2711 // call __tls_get_addr. 2712 ArgListTy Args; 2713 ArgListEntry Entry; 2714 Entry.Node = Argument; 2715 Entry.Ty = (Type *) Type::getInt32Ty(*DAG.getContext()); 2716 Args.push_back(Entry); 2717 2718 // FIXME: is there useful debug info available here? 2719 TargetLowering::CallLoweringInfo CLI(DAG); 2720 CLI.setDebugLoc(dl).setChain(Chain) 2721 .setCallee(CallingConv::C, Type::getInt32Ty(*DAG.getContext()), 2722 DAG.getExternalSymbol("__tls_get_addr", PtrVT), std::move(Args), 2723 0); 2724 2725 std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI); 2726 return CallResult.first; 2727 } 2728 2729 // Lower ISD::GlobalTLSAddress using the "initial exec" or 2730 // "local exec" model. 2731 SDValue 2732 ARMTargetLowering::LowerToTLSExecModels(GlobalAddressSDNode *GA, 2733 SelectionDAG &DAG, 2734 TLSModel::Model model) const { 2735 const GlobalValue *GV = GA->getGlobal(); 2736 SDLoc dl(GA); 2737 SDValue Offset; 2738 SDValue Chain = DAG.getEntryNode(); 2739 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 2740 // Get the Thread Pointer 2741 SDValue ThreadPointer = DAG.getNode(ARMISD::THREAD_POINTER, dl, PtrVT); 2742 2743 if (model == TLSModel::InitialExec) { 2744 MachineFunction &MF = DAG.getMachineFunction(); 2745 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>(); 2746 unsigned ARMPCLabelIndex = AFI->createPICLabelUId(); 2747 // Initial exec model. 2748 unsigned char PCAdj = Subtarget->isThumb() ? 4 : 8; 2749 ARMConstantPoolValue *CPV = 2750 ARMConstantPoolConstant::Create(GA->getGlobal(), ARMPCLabelIndex, 2751 ARMCP::CPValue, PCAdj, ARMCP::GOTTPOFF, 2752 true); 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 Chain = Offset.getValue(1); 2760 2761 SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, dl, MVT::i32); 2762 Offset = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Offset, PICLabel); 2763 2764 Offset = DAG.getLoad( 2765 PtrVT, dl, Chain, Offset, 2766 MachinePointerInfo::getConstantPool(DAG.getMachineFunction()), false, 2767 false, false, 0); 2768 } else { 2769 // local exec model 2770 assert(model == TLSModel::LocalExec); 2771 ARMConstantPoolValue *CPV = 2772 ARMConstantPoolConstant::Create(GV, ARMCP::TPOFF); 2773 Offset = DAG.getTargetConstantPool(CPV, PtrVT, 4); 2774 Offset = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Offset); 2775 Offset = DAG.getLoad( 2776 PtrVT, dl, Chain, Offset, 2777 MachinePointerInfo::getConstantPool(DAG.getMachineFunction()), false, 2778 false, false, 0); 2779 } 2780 2781 // The address of the thread local variable is the add of the thread 2782 // pointer with the offset of the variable. 2783 return DAG.getNode(ISD::ADD, dl, PtrVT, ThreadPointer, Offset); 2784 } 2785 2786 SDValue 2787 ARMTargetLowering::LowerGlobalTLSAddress(SDValue Op, SelectionDAG &DAG) const { 2788 if (Subtarget->isTargetDarwin()) 2789 return LowerGlobalTLSAddressDarwin(Op, DAG); 2790 2791 if (Subtarget->isTargetWindows()) 2792 return LowerGlobalTLSAddressWindows(Op, DAG); 2793 2794 // TODO: implement the "local dynamic" model 2795 assert(Subtarget->isTargetELF() && "Only ELF implemented here"); 2796 GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op); 2797 if (DAG.getTarget().Options.EmulatedTLS) 2798 return LowerToTLSEmulatedModel(GA, DAG); 2799 2800 TLSModel::Model model = getTargetMachine().getTLSModel(GA->getGlobal()); 2801 2802 switch (model) { 2803 case TLSModel::GeneralDynamic: 2804 case TLSModel::LocalDynamic: 2805 return LowerToTLSGeneralDynamicModel(GA, DAG); 2806 case TLSModel::InitialExec: 2807 case TLSModel::LocalExec: 2808 return LowerToTLSExecModels(GA, DAG, model); 2809 } 2810 llvm_unreachable("bogus TLS model"); 2811 } 2812 2813 SDValue ARMTargetLowering::LowerGlobalAddressELF(SDValue Op, 2814 SelectionDAG &DAG) const { 2815 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 2816 SDLoc dl(Op); 2817 const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal(); 2818 if (getTargetMachine().getRelocationModel() == Reloc::PIC_) { 2819 bool UseGOT_PREL = 2820 !(GV->hasHiddenVisibility() || GV->hasLocalLinkage()); 2821 2822 MachineFunction &MF = DAG.getMachineFunction(); 2823 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>(); 2824 unsigned ARMPCLabelIndex = AFI->createPICLabelUId(); 2825 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 2826 SDLoc dl(Op); 2827 unsigned PCAdj = Subtarget->isThumb() ? 4 : 8; 2828 ARMConstantPoolValue *CPV = ARMConstantPoolConstant::Create( 2829 GV, ARMPCLabelIndex, ARMCP::CPValue, PCAdj, 2830 UseGOT_PREL ? ARMCP::GOT_PREL : ARMCP::no_modifier, 2831 /*AddCurrentAddress=*/UseGOT_PREL); 2832 SDValue CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4); 2833 CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr); 2834 SDValue Result = DAG.getLoad( 2835 PtrVT, dl, DAG.getEntryNode(), CPAddr, 2836 MachinePointerInfo::getConstantPool(DAG.getMachineFunction()), false, 2837 false, false, 0); 2838 SDValue Chain = Result.getValue(1); 2839 SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, dl, MVT::i32); 2840 Result = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Result, PICLabel); 2841 if (UseGOT_PREL) 2842 Result = DAG.getLoad(PtrVT, dl, Chain, Result, 2843 MachinePointerInfo::getGOT(DAG.getMachineFunction()), 2844 false, false, false, 0); 2845 return Result; 2846 } 2847 2848 // If we have T2 ops, we can materialize the address directly via movt/movw 2849 // pair. This is always cheaper. 2850 if (Subtarget->useMovt(DAG.getMachineFunction())) { 2851 ++NumMovwMovt; 2852 // FIXME: Once remat is capable of dealing with instructions with register 2853 // operands, expand this into two nodes. 2854 return DAG.getNode(ARMISD::Wrapper, dl, PtrVT, 2855 DAG.getTargetGlobalAddress(GV, dl, PtrVT)); 2856 } else { 2857 SDValue CPAddr = DAG.getTargetConstantPool(GV, PtrVT, 4); 2858 CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr); 2859 return DAG.getLoad( 2860 PtrVT, dl, DAG.getEntryNode(), CPAddr, 2861 MachinePointerInfo::getConstantPool(DAG.getMachineFunction()), false, 2862 false, false, 0); 2863 } 2864 } 2865 2866 SDValue ARMTargetLowering::LowerGlobalAddressDarwin(SDValue Op, 2867 SelectionDAG &DAG) const { 2868 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 2869 SDLoc dl(Op); 2870 const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal(); 2871 Reloc::Model RelocM = getTargetMachine().getRelocationModel(); 2872 2873 if (Subtarget->useMovt(DAG.getMachineFunction())) 2874 ++NumMovwMovt; 2875 2876 // FIXME: Once remat is capable of dealing with instructions with register 2877 // operands, expand this into multiple nodes 2878 unsigned Wrapper = 2879 RelocM == Reloc::PIC_ ? ARMISD::WrapperPIC : ARMISD::Wrapper; 2880 2881 SDValue G = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, ARMII::MO_NONLAZY); 2882 SDValue Result = DAG.getNode(Wrapper, dl, PtrVT, G); 2883 2884 if (Subtarget->GVIsIndirectSymbol(GV, RelocM)) 2885 Result = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Result, 2886 MachinePointerInfo::getGOT(DAG.getMachineFunction()), 2887 false, false, false, 0); 2888 return Result; 2889 } 2890 2891 SDValue ARMTargetLowering::LowerGlobalAddressWindows(SDValue Op, 2892 SelectionDAG &DAG) const { 2893 assert(Subtarget->isTargetWindows() && "non-Windows COFF is not supported"); 2894 assert(Subtarget->useMovt(DAG.getMachineFunction()) && 2895 "Windows on ARM expects to use movw/movt"); 2896 2897 const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal(); 2898 const ARMII::TOF TargetFlags = 2899 (GV->hasDLLImportStorageClass() ? ARMII::MO_DLLIMPORT : ARMII::MO_NO_FLAG); 2900 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 2901 SDValue Result; 2902 SDLoc DL(Op); 2903 2904 ++NumMovwMovt; 2905 2906 // FIXME: Once remat is capable of dealing with instructions with register 2907 // operands, expand this into two nodes. 2908 Result = DAG.getNode(ARMISD::Wrapper, DL, PtrVT, 2909 DAG.getTargetGlobalAddress(GV, DL, PtrVT, /*Offset=*/0, 2910 TargetFlags)); 2911 if (GV->hasDLLImportStorageClass()) 2912 Result = DAG.getLoad(PtrVT, DL, DAG.getEntryNode(), Result, 2913 MachinePointerInfo::getGOT(DAG.getMachineFunction()), 2914 false, false, false, 0); 2915 return Result; 2916 } 2917 2918 SDValue 2919 ARMTargetLowering::LowerEH_SJLJ_SETJMP(SDValue Op, SelectionDAG &DAG) const { 2920 SDLoc dl(Op); 2921 SDValue Val = DAG.getConstant(0, dl, MVT::i32); 2922 return DAG.getNode(ARMISD::EH_SJLJ_SETJMP, dl, 2923 DAG.getVTList(MVT::i32, MVT::Other), Op.getOperand(0), 2924 Op.getOperand(1), Val); 2925 } 2926 2927 SDValue 2928 ARMTargetLowering::LowerEH_SJLJ_LONGJMP(SDValue Op, SelectionDAG &DAG) const { 2929 SDLoc dl(Op); 2930 return DAG.getNode(ARMISD::EH_SJLJ_LONGJMP, dl, MVT::Other, Op.getOperand(0), 2931 Op.getOperand(1), DAG.getConstant(0, dl, MVT::i32)); 2932 } 2933 2934 SDValue ARMTargetLowering::LowerEH_SJLJ_SETUP_DISPATCH(SDValue Op, 2935 SelectionDAG &DAG) const { 2936 SDLoc dl(Op); 2937 return DAG.getNode(ARMISD::EH_SJLJ_SETUP_DISPATCH, dl, MVT::Other, 2938 Op.getOperand(0)); 2939 } 2940 2941 SDValue 2942 ARMTargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op, SelectionDAG &DAG, 2943 const ARMSubtarget *Subtarget) const { 2944 unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue(); 2945 SDLoc dl(Op); 2946 switch (IntNo) { 2947 default: return SDValue(); // Don't custom lower most intrinsics. 2948 case Intrinsic::arm_rbit: { 2949 assert(Op.getOperand(1).getValueType() == MVT::i32 && 2950 "RBIT intrinsic must have i32 type!"); 2951 return DAG.getNode(ISD::BITREVERSE, dl, MVT::i32, Op.getOperand(1)); 2952 } 2953 case Intrinsic::arm_thread_pointer: { 2954 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 2955 return DAG.getNode(ARMISD::THREAD_POINTER, dl, PtrVT); 2956 } 2957 case Intrinsic::eh_sjlj_lsda: { 2958 MachineFunction &MF = DAG.getMachineFunction(); 2959 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>(); 2960 unsigned ARMPCLabelIndex = AFI->createPICLabelUId(); 2961 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 2962 Reloc::Model RelocM = getTargetMachine().getRelocationModel(); 2963 SDValue CPAddr; 2964 unsigned PCAdj = (RelocM != Reloc::PIC_) 2965 ? 0 : (Subtarget->isThumb() ? 4 : 8); 2966 ARMConstantPoolValue *CPV = 2967 ARMConstantPoolConstant::Create(MF.getFunction(), ARMPCLabelIndex, 2968 ARMCP::CPLSDA, PCAdj); 2969 CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4); 2970 CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr); 2971 SDValue Result = DAG.getLoad( 2972 PtrVT, dl, DAG.getEntryNode(), CPAddr, 2973 MachinePointerInfo::getConstantPool(DAG.getMachineFunction()), false, 2974 false, false, 0); 2975 2976 if (RelocM == Reloc::PIC_) { 2977 SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, dl, MVT::i32); 2978 Result = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Result, PICLabel); 2979 } 2980 return Result; 2981 } 2982 case Intrinsic::arm_neon_vmulls: 2983 case Intrinsic::arm_neon_vmullu: { 2984 unsigned NewOpc = (IntNo == Intrinsic::arm_neon_vmulls) 2985 ? ARMISD::VMULLs : ARMISD::VMULLu; 2986 return DAG.getNode(NewOpc, SDLoc(Op), Op.getValueType(), 2987 Op.getOperand(1), Op.getOperand(2)); 2988 } 2989 case Intrinsic::arm_neon_vminnm: 2990 case Intrinsic::arm_neon_vmaxnm: { 2991 unsigned NewOpc = (IntNo == Intrinsic::arm_neon_vminnm) 2992 ? ISD::FMINNUM : ISD::FMAXNUM; 2993 return DAG.getNode(NewOpc, SDLoc(Op), Op.getValueType(), 2994 Op.getOperand(1), Op.getOperand(2)); 2995 } 2996 case Intrinsic::arm_neon_vminu: 2997 case Intrinsic::arm_neon_vmaxu: { 2998 if (Op.getValueType().isFloatingPoint()) 2999 return SDValue(); 3000 unsigned NewOpc = (IntNo == Intrinsic::arm_neon_vminu) 3001 ? ISD::UMIN : ISD::UMAX; 3002 return DAG.getNode(NewOpc, SDLoc(Op), Op.getValueType(), 3003 Op.getOperand(1), Op.getOperand(2)); 3004 } 3005 case Intrinsic::arm_neon_vmins: 3006 case Intrinsic::arm_neon_vmaxs: { 3007 // v{min,max}s is overloaded between signed integers and floats. 3008 if (!Op.getValueType().isFloatingPoint()) { 3009 unsigned NewOpc = (IntNo == Intrinsic::arm_neon_vmins) 3010 ? ISD::SMIN : ISD::SMAX; 3011 return DAG.getNode(NewOpc, SDLoc(Op), Op.getValueType(), 3012 Op.getOperand(1), Op.getOperand(2)); 3013 } 3014 unsigned NewOpc = (IntNo == Intrinsic::arm_neon_vmins) 3015 ? ISD::FMINNAN : ISD::FMAXNAN; 3016 return DAG.getNode(NewOpc, SDLoc(Op), Op.getValueType(), 3017 Op.getOperand(1), Op.getOperand(2)); 3018 } 3019 } 3020 } 3021 3022 static SDValue LowerATOMIC_FENCE(SDValue Op, SelectionDAG &DAG, 3023 const ARMSubtarget *Subtarget) { 3024 // FIXME: handle "fence singlethread" more efficiently. 3025 SDLoc dl(Op); 3026 if (!Subtarget->hasDataBarrier()) { 3027 // Some ARMv6 cpus can support data barriers with an mcr instruction. 3028 // Thumb1 and pre-v6 ARM mode use a libcall instead and should never get 3029 // here. 3030 assert(Subtarget->hasV6Ops() && !Subtarget->isThumb() && 3031 "Unexpected ISD::ATOMIC_FENCE encountered. Should be libcall!"); 3032 return DAG.getNode(ARMISD::MEMBARRIER_MCR, dl, MVT::Other, Op.getOperand(0), 3033 DAG.getConstant(0, dl, MVT::i32)); 3034 } 3035 3036 ConstantSDNode *OrdN = cast<ConstantSDNode>(Op.getOperand(1)); 3037 AtomicOrdering Ord = static_cast<AtomicOrdering>(OrdN->getZExtValue()); 3038 ARM_MB::MemBOpt Domain = ARM_MB::ISH; 3039 if (Subtarget->isMClass()) { 3040 // Only a full system barrier exists in the M-class architectures. 3041 Domain = ARM_MB::SY; 3042 } else if (Subtarget->isSwift() && Ord == Release) { 3043 // Swift happens to implement ISHST barriers in a way that's compatible with 3044 // Release semantics but weaker than ISH so we'd be fools not to use 3045 // it. Beware: other processors probably don't! 3046 Domain = ARM_MB::ISHST; 3047 } 3048 3049 return DAG.getNode(ISD::INTRINSIC_VOID, dl, MVT::Other, Op.getOperand(0), 3050 DAG.getConstant(Intrinsic::arm_dmb, dl, MVT::i32), 3051 DAG.getConstant(Domain, dl, MVT::i32)); 3052 } 3053 3054 static SDValue LowerPREFETCH(SDValue Op, SelectionDAG &DAG, 3055 const ARMSubtarget *Subtarget) { 3056 // ARM pre v5TE and Thumb1 does not have preload instructions. 3057 if (!(Subtarget->isThumb2() || 3058 (!Subtarget->isThumb1Only() && Subtarget->hasV5TEOps()))) 3059 // Just preserve the chain. 3060 return Op.getOperand(0); 3061 3062 SDLoc dl(Op); 3063 unsigned isRead = ~cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue() & 1; 3064 if (!isRead && 3065 (!Subtarget->hasV7Ops() || !Subtarget->hasMPExtension())) 3066 // ARMv7 with MP extension has PLDW. 3067 return Op.getOperand(0); 3068 3069 unsigned isData = cast<ConstantSDNode>(Op.getOperand(4))->getZExtValue(); 3070 if (Subtarget->isThumb()) { 3071 // Invert the bits. 3072 isRead = ~isRead & 1; 3073 isData = ~isData & 1; 3074 } 3075 3076 return DAG.getNode(ARMISD::PRELOAD, dl, MVT::Other, Op.getOperand(0), 3077 Op.getOperand(1), DAG.getConstant(isRead, dl, MVT::i32), 3078 DAG.getConstant(isData, dl, MVT::i32)); 3079 } 3080 3081 static SDValue LowerVASTART(SDValue Op, SelectionDAG &DAG) { 3082 MachineFunction &MF = DAG.getMachineFunction(); 3083 ARMFunctionInfo *FuncInfo = MF.getInfo<ARMFunctionInfo>(); 3084 3085 // vastart just stores the address of the VarArgsFrameIndex slot into the 3086 // memory location argument. 3087 SDLoc dl(Op); 3088 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout()); 3089 SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT); 3090 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue(); 3091 return DAG.getStore(Op.getOperand(0), dl, FR, Op.getOperand(1), 3092 MachinePointerInfo(SV), false, false, 0); 3093 } 3094 3095 SDValue 3096 ARMTargetLowering::GetF64FormalArgument(CCValAssign &VA, CCValAssign &NextVA, 3097 SDValue &Root, SelectionDAG &DAG, 3098 SDLoc dl) const { 3099 MachineFunction &MF = DAG.getMachineFunction(); 3100 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>(); 3101 3102 const TargetRegisterClass *RC; 3103 if (AFI->isThumb1OnlyFunction()) 3104 RC = &ARM::tGPRRegClass; 3105 else 3106 RC = &ARM::GPRRegClass; 3107 3108 // Transform the arguments stored in physical registers into virtual ones. 3109 unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC); 3110 SDValue ArgValue = DAG.getCopyFromReg(Root, dl, Reg, MVT::i32); 3111 3112 SDValue ArgValue2; 3113 if (NextVA.isMemLoc()) { 3114 MachineFrameInfo *MFI = MF.getFrameInfo(); 3115 int FI = MFI->CreateFixedObject(4, NextVA.getLocMemOffset(), true); 3116 3117 // Create load node to retrieve arguments from the stack. 3118 SDValue FIN = DAG.getFrameIndex(FI, getPointerTy(DAG.getDataLayout())); 3119 ArgValue2 = DAG.getLoad( 3120 MVT::i32, dl, Root, FIN, 3121 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI), false, 3122 false, false, 0); 3123 } else { 3124 Reg = MF.addLiveIn(NextVA.getLocReg(), RC); 3125 ArgValue2 = DAG.getCopyFromReg(Root, dl, Reg, MVT::i32); 3126 } 3127 if (!Subtarget->isLittle()) 3128 std::swap (ArgValue, ArgValue2); 3129 return DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, ArgValue, ArgValue2); 3130 } 3131 3132 // The remaining GPRs hold either the beginning of variable-argument 3133 // data, or the beginning of an aggregate passed by value (usually 3134 // byval). Either way, we allocate stack slots adjacent to the data 3135 // provided by our caller, and store the unallocated registers there. 3136 // If this is a variadic function, the va_list pointer will begin with 3137 // these values; otherwise, this reassembles a (byval) structure that 3138 // was split between registers and memory. 3139 // Return: The frame index registers were stored into. 3140 int 3141 ARMTargetLowering::StoreByValRegs(CCState &CCInfo, SelectionDAG &DAG, 3142 SDLoc dl, SDValue &Chain, 3143 const Value *OrigArg, 3144 unsigned InRegsParamRecordIdx, 3145 int ArgOffset, 3146 unsigned ArgSize) const { 3147 // Currently, two use-cases possible: 3148 // Case #1. Non-var-args function, and we meet first byval parameter. 3149 // Setup first unallocated register as first byval register; 3150 // eat all remained registers 3151 // (these two actions are performed by HandleByVal method). 3152 // Then, here, we initialize stack frame with 3153 // "store-reg" instructions. 3154 // Case #2. Var-args function, that doesn't contain byval parameters. 3155 // The same: eat all remained unallocated registers, 3156 // initialize stack frame. 3157 3158 MachineFunction &MF = DAG.getMachineFunction(); 3159 MachineFrameInfo *MFI = MF.getFrameInfo(); 3160 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>(); 3161 unsigned RBegin, REnd; 3162 if (InRegsParamRecordIdx < CCInfo.getInRegsParamsCount()) { 3163 CCInfo.getInRegsParamInfo(InRegsParamRecordIdx, RBegin, REnd); 3164 } else { 3165 unsigned RBeginIdx = CCInfo.getFirstUnallocated(GPRArgRegs); 3166 RBegin = RBeginIdx == 4 ? (unsigned)ARM::R4 : GPRArgRegs[RBeginIdx]; 3167 REnd = ARM::R4; 3168 } 3169 3170 if (REnd != RBegin) 3171 ArgOffset = -4 * (ARM::R4 - RBegin); 3172 3173 auto PtrVT = getPointerTy(DAG.getDataLayout()); 3174 int FrameIndex = MFI->CreateFixedObject(ArgSize, ArgOffset, false); 3175 SDValue FIN = DAG.getFrameIndex(FrameIndex, PtrVT); 3176 3177 SmallVector<SDValue, 4> MemOps; 3178 const TargetRegisterClass *RC = 3179 AFI->isThumb1OnlyFunction() ? &ARM::tGPRRegClass : &ARM::GPRRegClass; 3180 3181 for (unsigned Reg = RBegin, i = 0; Reg < REnd; ++Reg, ++i) { 3182 unsigned VReg = MF.addLiveIn(Reg, RC); 3183 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i32); 3184 SDValue Store = 3185 DAG.getStore(Val.getValue(1), dl, Val, FIN, 3186 MachinePointerInfo(OrigArg, 4 * i), false, false, 0); 3187 MemOps.push_back(Store); 3188 FIN = DAG.getNode(ISD::ADD, dl, PtrVT, FIN, DAG.getConstant(4, dl, PtrVT)); 3189 } 3190 3191 if (!MemOps.empty()) 3192 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOps); 3193 return FrameIndex; 3194 } 3195 3196 // Setup stack frame, the va_list pointer will start from. 3197 void 3198 ARMTargetLowering::VarArgStyleRegisters(CCState &CCInfo, SelectionDAG &DAG, 3199 SDLoc dl, SDValue &Chain, 3200 unsigned ArgOffset, 3201 unsigned TotalArgRegsSaveSize, 3202 bool ForceMutable) const { 3203 MachineFunction &MF = DAG.getMachineFunction(); 3204 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>(); 3205 3206 // Try to store any remaining integer argument regs 3207 // to their spots on the stack so that they may be loaded by deferencing 3208 // the result of va_next. 3209 // If there is no regs to be stored, just point address after last 3210 // argument passed via stack. 3211 int FrameIndex = StoreByValRegs(CCInfo, DAG, dl, Chain, nullptr, 3212 CCInfo.getInRegsParamsCount(), 3213 CCInfo.getNextStackOffset(), 4); 3214 AFI->setVarArgsFrameIndex(FrameIndex); 3215 } 3216 3217 SDValue 3218 ARMTargetLowering::LowerFormalArguments(SDValue Chain, 3219 CallingConv::ID CallConv, bool isVarArg, 3220 const SmallVectorImpl<ISD::InputArg> 3221 &Ins, 3222 SDLoc dl, SelectionDAG &DAG, 3223 SmallVectorImpl<SDValue> &InVals) 3224 const { 3225 MachineFunction &MF = DAG.getMachineFunction(); 3226 MachineFrameInfo *MFI = MF.getFrameInfo(); 3227 3228 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>(); 3229 3230 // Assign locations to all of the incoming arguments. 3231 SmallVector<CCValAssign, 16> ArgLocs; 3232 ARMCCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), ArgLocs, 3233 *DAG.getContext(), Prologue); 3234 CCInfo.AnalyzeFormalArguments(Ins, 3235 CCAssignFnForNode(CallConv, /* Return*/ false, 3236 isVarArg)); 3237 3238 SmallVector<SDValue, 16> ArgValues; 3239 SDValue ArgValue; 3240 Function::const_arg_iterator CurOrigArg = MF.getFunction()->arg_begin(); 3241 unsigned CurArgIdx = 0; 3242 3243 // Initially ArgRegsSaveSize is zero. 3244 // Then we increase this value each time we meet byval parameter. 3245 // We also increase this value in case of varargs function. 3246 AFI->setArgRegsSaveSize(0); 3247 3248 // Calculate the amount of stack space that we need to allocate to store 3249 // byval and variadic arguments that are passed in registers. 3250 // We need to know this before we allocate the first byval or variadic 3251 // argument, as they will be allocated a stack slot below the CFA (Canonical 3252 // Frame Address, the stack pointer at entry to the function). 3253 unsigned ArgRegBegin = ARM::R4; 3254 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) { 3255 if (CCInfo.getInRegsParamsProcessed() >= CCInfo.getInRegsParamsCount()) 3256 break; 3257 3258 CCValAssign &VA = ArgLocs[i]; 3259 unsigned Index = VA.getValNo(); 3260 ISD::ArgFlagsTy Flags = Ins[Index].Flags; 3261 if (!Flags.isByVal()) 3262 continue; 3263 3264 assert(VA.isMemLoc() && "unexpected byval pointer in reg"); 3265 unsigned RBegin, REnd; 3266 CCInfo.getInRegsParamInfo(CCInfo.getInRegsParamsProcessed(), RBegin, REnd); 3267 ArgRegBegin = std::min(ArgRegBegin, RBegin); 3268 3269 CCInfo.nextInRegsParam(); 3270 } 3271 CCInfo.rewindByValRegsInfo(); 3272 3273 int lastInsIndex = -1; 3274 if (isVarArg && MFI->hasVAStart()) { 3275 unsigned RegIdx = CCInfo.getFirstUnallocated(GPRArgRegs); 3276 if (RegIdx != array_lengthof(GPRArgRegs)) 3277 ArgRegBegin = std::min(ArgRegBegin, (unsigned)GPRArgRegs[RegIdx]); 3278 } 3279 3280 unsigned TotalArgRegsSaveSize = 4 * (ARM::R4 - ArgRegBegin); 3281 AFI->setArgRegsSaveSize(TotalArgRegsSaveSize); 3282 auto PtrVT = getPointerTy(DAG.getDataLayout()); 3283 3284 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) { 3285 CCValAssign &VA = ArgLocs[i]; 3286 if (Ins[VA.getValNo()].isOrigArg()) { 3287 std::advance(CurOrigArg, 3288 Ins[VA.getValNo()].getOrigArgIndex() - CurArgIdx); 3289 CurArgIdx = Ins[VA.getValNo()].getOrigArgIndex(); 3290 } 3291 // Arguments stored in registers. 3292 if (VA.isRegLoc()) { 3293 EVT RegVT = VA.getLocVT(); 3294 3295 if (VA.needsCustom()) { 3296 // f64 and vector types are split up into multiple registers or 3297 // combinations of registers and stack slots. 3298 if (VA.getLocVT() == MVT::v2f64) { 3299 SDValue ArgValue1 = GetF64FormalArgument(VA, ArgLocs[++i], 3300 Chain, DAG, dl); 3301 VA = ArgLocs[++i]; // skip ahead to next loc 3302 SDValue ArgValue2; 3303 if (VA.isMemLoc()) { 3304 int FI = MFI->CreateFixedObject(8, VA.getLocMemOffset(), true); 3305 SDValue FIN = DAG.getFrameIndex(FI, PtrVT); 3306 ArgValue2 = DAG.getLoad( 3307 MVT::f64, dl, Chain, FIN, 3308 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI), 3309 false, false, false, 0); 3310 } else { 3311 ArgValue2 = GetF64FormalArgument(VA, ArgLocs[++i], 3312 Chain, DAG, dl); 3313 } 3314 ArgValue = DAG.getNode(ISD::UNDEF, dl, MVT::v2f64); 3315 ArgValue = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, 3316 ArgValue, ArgValue1, 3317 DAG.getIntPtrConstant(0, dl)); 3318 ArgValue = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, 3319 ArgValue, ArgValue2, 3320 DAG.getIntPtrConstant(1, dl)); 3321 } else 3322 ArgValue = GetF64FormalArgument(VA, ArgLocs[++i], Chain, DAG, dl); 3323 3324 } else { 3325 const TargetRegisterClass *RC; 3326 3327 if (RegVT == MVT::f32) 3328 RC = &ARM::SPRRegClass; 3329 else if (RegVT == MVT::f64) 3330 RC = &ARM::DPRRegClass; 3331 else if (RegVT == MVT::v2f64) 3332 RC = &ARM::QPRRegClass; 3333 else if (RegVT == MVT::i32) 3334 RC = AFI->isThumb1OnlyFunction() ? &ARM::tGPRRegClass 3335 : &ARM::GPRRegClass; 3336 else 3337 llvm_unreachable("RegVT not supported by FORMAL_ARGUMENTS Lowering"); 3338 3339 // Transform the arguments in physical registers into virtual ones. 3340 unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC); 3341 ArgValue = DAG.getCopyFromReg(Chain, dl, Reg, RegVT); 3342 } 3343 3344 // If this is an 8 or 16-bit value, it is really passed promoted 3345 // to 32 bits. Insert an assert[sz]ext to capture this, then 3346 // truncate to the right size. 3347 switch (VA.getLocInfo()) { 3348 default: llvm_unreachable("Unknown loc info!"); 3349 case CCValAssign::Full: break; 3350 case CCValAssign::BCvt: 3351 ArgValue = DAG.getNode(ISD::BITCAST, dl, VA.getValVT(), ArgValue); 3352 break; 3353 case CCValAssign::SExt: 3354 ArgValue = DAG.getNode(ISD::AssertSext, dl, RegVT, ArgValue, 3355 DAG.getValueType(VA.getValVT())); 3356 ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue); 3357 break; 3358 case CCValAssign::ZExt: 3359 ArgValue = DAG.getNode(ISD::AssertZext, dl, RegVT, ArgValue, 3360 DAG.getValueType(VA.getValVT())); 3361 ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue); 3362 break; 3363 } 3364 3365 InVals.push_back(ArgValue); 3366 3367 } else { // VA.isRegLoc() 3368 3369 // sanity check 3370 assert(VA.isMemLoc()); 3371 assert(VA.getValVT() != MVT::i64 && "i64 should already be lowered"); 3372 3373 int index = VA.getValNo(); 3374 3375 // Some Ins[] entries become multiple ArgLoc[] entries. 3376 // Process them only once. 3377 if (index != lastInsIndex) 3378 { 3379 ISD::ArgFlagsTy Flags = Ins[index].Flags; 3380 // FIXME: For now, all byval parameter objects are marked mutable. 3381 // This can be changed with more analysis. 3382 // In case of tail call optimization mark all arguments mutable. 3383 // Since they could be overwritten by lowering of arguments in case of 3384 // a tail call. 3385 if (Flags.isByVal()) { 3386 assert(Ins[index].isOrigArg() && 3387 "Byval arguments cannot be implicit"); 3388 unsigned CurByValIndex = CCInfo.getInRegsParamsProcessed(); 3389 3390 int FrameIndex = StoreByValRegs( 3391 CCInfo, DAG, dl, Chain, &*CurOrigArg, CurByValIndex, 3392 VA.getLocMemOffset(), Flags.getByValSize()); 3393 InVals.push_back(DAG.getFrameIndex(FrameIndex, PtrVT)); 3394 CCInfo.nextInRegsParam(); 3395 } else { 3396 unsigned FIOffset = VA.getLocMemOffset(); 3397 int FI = MFI->CreateFixedObject(VA.getLocVT().getSizeInBits()/8, 3398 FIOffset, true); 3399 3400 // Create load nodes to retrieve arguments from the stack. 3401 SDValue FIN = DAG.getFrameIndex(FI, PtrVT); 3402 InVals.push_back(DAG.getLoad( 3403 VA.getValVT(), dl, Chain, FIN, 3404 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI), 3405 false, false, false, 0)); 3406 } 3407 lastInsIndex = index; 3408 } 3409 } 3410 } 3411 3412 // varargs 3413 if (isVarArg && MFI->hasVAStart()) 3414 VarArgStyleRegisters(CCInfo, DAG, dl, Chain, 3415 CCInfo.getNextStackOffset(), 3416 TotalArgRegsSaveSize); 3417 3418 AFI->setArgumentStackSize(CCInfo.getNextStackOffset()); 3419 3420 return Chain; 3421 } 3422 3423 /// isFloatingPointZero - Return true if this is +0.0. 3424 static bool isFloatingPointZero(SDValue Op) { 3425 if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Op)) 3426 return CFP->getValueAPF().isPosZero(); 3427 else if (ISD::isEXTLoad(Op.getNode()) || ISD::isNON_EXTLoad(Op.getNode())) { 3428 // Maybe this has already been legalized into the constant pool? 3429 if (Op.getOperand(1).getOpcode() == ARMISD::Wrapper) { 3430 SDValue WrapperOp = Op.getOperand(1).getOperand(0); 3431 if (ConstantPoolSDNode *CP = dyn_cast<ConstantPoolSDNode>(WrapperOp)) 3432 if (const ConstantFP *CFP = dyn_cast<ConstantFP>(CP->getConstVal())) 3433 return CFP->getValueAPF().isPosZero(); 3434 } 3435 } else if (Op->getOpcode() == ISD::BITCAST && 3436 Op->getValueType(0) == MVT::f64) { 3437 // Handle (ISD::BITCAST (ARMISD::VMOVIMM (ISD::TargetConstant 0)) MVT::f64) 3438 // created by LowerConstantFP(). 3439 SDValue BitcastOp = Op->getOperand(0); 3440 if (BitcastOp->getOpcode() == ARMISD::VMOVIMM && 3441 isNullConstant(BitcastOp->getOperand(0))) 3442 return true; 3443 } 3444 return false; 3445 } 3446 3447 /// Returns appropriate ARM CMP (cmp) and corresponding condition code for 3448 /// the given operands. 3449 SDValue 3450 ARMTargetLowering::getARMCmp(SDValue LHS, SDValue RHS, ISD::CondCode CC, 3451 SDValue &ARMcc, SelectionDAG &DAG, 3452 SDLoc dl) const { 3453 if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS.getNode())) { 3454 unsigned C = RHSC->getZExtValue(); 3455 if (!isLegalICmpImmediate(C)) { 3456 // Constant does not fit, try adjusting it by one? 3457 switch (CC) { 3458 default: break; 3459 case ISD::SETLT: 3460 case ISD::SETGE: 3461 if (C != 0x80000000 && isLegalICmpImmediate(C-1)) { 3462 CC = (CC == ISD::SETLT) ? ISD::SETLE : ISD::SETGT; 3463 RHS = DAG.getConstant(C - 1, dl, MVT::i32); 3464 } 3465 break; 3466 case ISD::SETULT: 3467 case ISD::SETUGE: 3468 if (C != 0 && isLegalICmpImmediate(C-1)) { 3469 CC = (CC == ISD::SETULT) ? ISD::SETULE : ISD::SETUGT; 3470 RHS = DAG.getConstant(C - 1, dl, MVT::i32); 3471 } 3472 break; 3473 case ISD::SETLE: 3474 case ISD::SETGT: 3475 if (C != 0x7fffffff && isLegalICmpImmediate(C+1)) { 3476 CC = (CC == ISD::SETLE) ? ISD::SETLT : ISD::SETGE; 3477 RHS = DAG.getConstant(C + 1, dl, MVT::i32); 3478 } 3479 break; 3480 case ISD::SETULE: 3481 case ISD::SETUGT: 3482 if (C != 0xffffffff && isLegalICmpImmediate(C+1)) { 3483 CC = (CC == ISD::SETULE) ? ISD::SETULT : ISD::SETUGE; 3484 RHS = DAG.getConstant(C + 1, dl, MVT::i32); 3485 } 3486 break; 3487 } 3488 } 3489 } 3490 3491 ARMCC::CondCodes CondCode = IntCCToARMCC(CC); 3492 ARMISD::NodeType CompareType; 3493 switch (CondCode) { 3494 default: 3495 CompareType = ARMISD::CMP; 3496 break; 3497 case ARMCC::EQ: 3498 case ARMCC::NE: 3499 // Uses only Z Flag 3500 CompareType = ARMISD::CMPZ; 3501 break; 3502 } 3503 ARMcc = DAG.getConstant(CondCode, dl, MVT::i32); 3504 return DAG.getNode(CompareType, dl, MVT::Glue, LHS, RHS); 3505 } 3506 3507 /// Returns a appropriate VFP CMP (fcmp{s|d}+fmstat) for the given operands. 3508 SDValue 3509 ARMTargetLowering::getVFPCmp(SDValue LHS, SDValue RHS, SelectionDAG &DAG, 3510 SDLoc dl) const { 3511 assert(!Subtarget->isFPOnlySP() || RHS.getValueType() != MVT::f64); 3512 SDValue Cmp; 3513 if (!isFloatingPointZero(RHS)) 3514 Cmp = DAG.getNode(ARMISD::CMPFP, dl, MVT::Glue, LHS, RHS); 3515 else 3516 Cmp = DAG.getNode(ARMISD::CMPFPw0, dl, MVT::Glue, LHS); 3517 return DAG.getNode(ARMISD::FMSTAT, dl, MVT::Glue, Cmp); 3518 } 3519 3520 /// duplicateCmp - Glue values can have only one use, so this function 3521 /// duplicates a comparison node. 3522 SDValue 3523 ARMTargetLowering::duplicateCmp(SDValue Cmp, SelectionDAG &DAG) const { 3524 unsigned Opc = Cmp.getOpcode(); 3525 SDLoc DL(Cmp); 3526 if (Opc == ARMISD::CMP || Opc == ARMISD::CMPZ) 3527 return DAG.getNode(Opc, DL, MVT::Glue, Cmp.getOperand(0),Cmp.getOperand(1)); 3528 3529 assert(Opc == ARMISD::FMSTAT && "unexpected comparison operation"); 3530 Cmp = Cmp.getOperand(0); 3531 Opc = Cmp.getOpcode(); 3532 if (Opc == ARMISD::CMPFP) 3533 Cmp = DAG.getNode(Opc, DL, MVT::Glue, Cmp.getOperand(0),Cmp.getOperand(1)); 3534 else { 3535 assert(Opc == ARMISD::CMPFPw0 && "unexpected operand of FMSTAT"); 3536 Cmp = DAG.getNode(Opc, DL, MVT::Glue, Cmp.getOperand(0)); 3537 } 3538 return DAG.getNode(ARMISD::FMSTAT, DL, MVT::Glue, Cmp); 3539 } 3540 3541 std::pair<SDValue, SDValue> 3542 ARMTargetLowering::getARMXALUOOp(SDValue Op, SelectionDAG &DAG, 3543 SDValue &ARMcc) const { 3544 assert(Op.getValueType() == MVT::i32 && "Unsupported value type"); 3545 3546 SDValue Value, OverflowCmp; 3547 SDValue LHS = Op.getOperand(0); 3548 SDValue RHS = Op.getOperand(1); 3549 SDLoc dl(Op); 3550 3551 // FIXME: We are currently always generating CMPs because we don't support 3552 // generating CMN through the backend. This is not as good as the natural 3553 // CMP case because it causes a register dependency and cannot be folded 3554 // later. 3555 3556 switch (Op.getOpcode()) { 3557 default: 3558 llvm_unreachable("Unknown overflow instruction!"); 3559 case ISD::SADDO: 3560 ARMcc = DAG.getConstant(ARMCC::VC, dl, MVT::i32); 3561 Value = DAG.getNode(ISD::ADD, dl, Op.getValueType(), LHS, RHS); 3562 OverflowCmp = DAG.getNode(ARMISD::CMP, dl, MVT::Glue, Value, LHS); 3563 break; 3564 case ISD::UADDO: 3565 ARMcc = DAG.getConstant(ARMCC::HS, dl, MVT::i32); 3566 Value = DAG.getNode(ISD::ADD, dl, Op.getValueType(), LHS, RHS); 3567 OverflowCmp = DAG.getNode(ARMISD::CMP, dl, MVT::Glue, Value, LHS); 3568 break; 3569 case ISD::SSUBO: 3570 ARMcc = DAG.getConstant(ARMCC::VC, dl, MVT::i32); 3571 Value = DAG.getNode(ISD::SUB, dl, Op.getValueType(), LHS, RHS); 3572 OverflowCmp = DAG.getNode(ARMISD::CMP, dl, MVT::Glue, LHS, RHS); 3573 break; 3574 case ISD::USUBO: 3575 ARMcc = DAG.getConstant(ARMCC::HS, dl, MVT::i32); 3576 Value = DAG.getNode(ISD::SUB, dl, Op.getValueType(), LHS, RHS); 3577 OverflowCmp = DAG.getNode(ARMISD::CMP, dl, MVT::Glue, LHS, RHS); 3578 break; 3579 } // switch (...) 3580 3581 return std::make_pair(Value, OverflowCmp); 3582 } 3583 3584 3585 SDValue 3586 ARMTargetLowering::LowerXALUO(SDValue Op, SelectionDAG &DAG) const { 3587 // Let legalize expand this if it isn't a legal type yet. 3588 if (!DAG.getTargetLoweringInfo().isTypeLegal(Op.getValueType())) 3589 return SDValue(); 3590 3591 SDValue Value, OverflowCmp; 3592 SDValue ARMcc; 3593 std::tie(Value, OverflowCmp) = getARMXALUOOp(Op, DAG, ARMcc); 3594 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32); 3595 SDLoc dl(Op); 3596 // We use 0 and 1 as false and true values. 3597 SDValue TVal = DAG.getConstant(1, dl, MVT::i32); 3598 SDValue FVal = DAG.getConstant(0, dl, MVT::i32); 3599 EVT VT = Op.getValueType(); 3600 3601 SDValue Overflow = DAG.getNode(ARMISD::CMOV, dl, VT, TVal, FVal, 3602 ARMcc, CCR, OverflowCmp); 3603 3604 SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32); 3605 return DAG.getNode(ISD::MERGE_VALUES, dl, VTs, Value, Overflow); 3606 } 3607 3608 3609 SDValue ARMTargetLowering::LowerSELECT(SDValue Op, SelectionDAG &DAG) const { 3610 SDValue Cond = Op.getOperand(0); 3611 SDValue SelectTrue = Op.getOperand(1); 3612 SDValue SelectFalse = Op.getOperand(2); 3613 SDLoc dl(Op); 3614 unsigned Opc = Cond.getOpcode(); 3615 3616 if (Cond.getResNo() == 1 && 3617 (Opc == ISD::SADDO || Opc == ISD::UADDO || Opc == ISD::SSUBO || 3618 Opc == ISD::USUBO)) { 3619 if (!DAG.getTargetLoweringInfo().isTypeLegal(Cond->getValueType(0))) 3620 return SDValue(); 3621 3622 SDValue Value, OverflowCmp; 3623 SDValue ARMcc; 3624 std::tie(Value, OverflowCmp) = getARMXALUOOp(Cond, DAG, ARMcc); 3625 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32); 3626 EVT VT = Op.getValueType(); 3627 3628 return getCMOV(dl, VT, SelectTrue, SelectFalse, ARMcc, CCR, 3629 OverflowCmp, DAG); 3630 } 3631 3632 // Convert: 3633 // 3634 // (select (cmov 1, 0, cond), t, f) -> (cmov t, f, cond) 3635 // (select (cmov 0, 1, cond), t, f) -> (cmov f, t, cond) 3636 // 3637 if (Cond.getOpcode() == ARMISD::CMOV && Cond.hasOneUse()) { 3638 const ConstantSDNode *CMOVTrue = 3639 dyn_cast<ConstantSDNode>(Cond.getOperand(0)); 3640 const ConstantSDNode *CMOVFalse = 3641 dyn_cast<ConstantSDNode>(Cond.getOperand(1)); 3642 3643 if (CMOVTrue && CMOVFalse) { 3644 unsigned CMOVTrueVal = CMOVTrue->getZExtValue(); 3645 unsigned CMOVFalseVal = CMOVFalse->getZExtValue(); 3646 3647 SDValue True; 3648 SDValue False; 3649 if (CMOVTrueVal == 1 && CMOVFalseVal == 0) { 3650 True = SelectTrue; 3651 False = SelectFalse; 3652 } else if (CMOVTrueVal == 0 && CMOVFalseVal == 1) { 3653 True = SelectFalse; 3654 False = SelectTrue; 3655 } 3656 3657 if (True.getNode() && False.getNode()) { 3658 EVT VT = Op.getValueType(); 3659 SDValue ARMcc = Cond.getOperand(2); 3660 SDValue CCR = Cond.getOperand(3); 3661 SDValue Cmp = duplicateCmp(Cond.getOperand(4), DAG); 3662 assert(True.getValueType() == VT); 3663 return getCMOV(dl, VT, True, False, ARMcc, CCR, Cmp, DAG); 3664 } 3665 } 3666 } 3667 3668 // ARM's BooleanContents value is UndefinedBooleanContent. Mask out the 3669 // undefined bits before doing a full-word comparison with zero. 3670 Cond = DAG.getNode(ISD::AND, dl, Cond.getValueType(), Cond, 3671 DAG.getConstant(1, dl, Cond.getValueType())); 3672 3673 return DAG.getSelectCC(dl, Cond, 3674 DAG.getConstant(0, dl, Cond.getValueType()), 3675 SelectTrue, SelectFalse, ISD::SETNE); 3676 } 3677 3678 static void checkVSELConstraints(ISD::CondCode CC, ARMCC::CondCodes &CondCode, 3679 bool &swpCmpOps, bool &swpVselOps) { 3680 // Start by selecting the GE condition code for opcodes that return true for 3681 // 'equality' 3682 if (CC == ISD::SETUGE || CC == ISD::SETOGE || CC == ISD::SETOLE || 3683 CC == ISD::SETULE) 3684 CondCode = ARMCC::GE; 3685 3686 // and GT for opcodes that return false for 'equality'. 3687 else if (CC == ISD::SETUGT || CC == ISD::SETOGT || CC == ISD::SETOLT || 3688 CC == ISD::SETULT) 3689 CondCode = ARMCC::GT; 3690 3691 // Since we are constrained to GE/GT, if the opcode contains 'less', we need 3692 // to swap the compare operands. 3693 if (CC == ISD::SETOLE || CC == ISD::SETULE || CC == ISD::SETOLT || 3694 CC == ISD::SETULT) 3695 swpCmpOps = true; 3696 3697 // Both GT and GE are ordered comparisons, and return false for 'unordered'. 3698 // If we have an unordered opcode, we need to swap the operands to the VSEL 3699 // instruction (effectively negating the condition). 3700 // 3701 // This also has the effect of swapping which one of 'less' or 'greater' 3702 // returns true, so we also swap the compare operands. It also switches 3703 // whether we return true for 'equality', so we compensate by picking the 3704 // opposite condition code to our original choice. 3705 if (CC == ISD::SETULE || CC == ISD::SETULT || CC == ISD::SETUGE || 3706 CC == ISD::SETUGT) { 3707 swpCmpOps = !swpCmpOps; 3708 swpVselOps = !swpVselOps; 3709 CondCode = CondCode == ARMCC::GT ? ARMCC::GE : ARMCC::GT; 3710 } 3711 3712 // 'ordered' is 'anything but unordered', so use the VS condition code and 3713 // swap the VSEL operands. 3714 if (CC == ISD::SETO) { 3715 CondCode = ARMCC::VS; 3716 swpVselOps = true; 3717 } 3718 3719 // 'unordered or not equal' is 'anything but equal', so use the EQ condition 3720 // code and swap the VSEL operands. 3721 if (CC == ISD::SETUNE) { 3722 CondCode = ARMCC::EQ; 3723 swpVselOps = true; 3724 } 3725 } 3726 3727 SDValue ARMTargetLowering::getCMOV(SDLoc dl, EVT VT, SDValue FalseVal, 3728 SDValue TrueVal, SDValue ARMcc, SDValue CCR, 3729 SDValue Cmp, SelectionDAG &DAG) const { 3730 if (Subtarget->isFPOnlySP() && VT == MVT::f64) { 3731 FalseVal = DAG.getNode(ARMISD::VMOVRRD, dl, 3732 DAG.getVTList(MVT::i32, MVT::i32), FalseVal); 3733 TrueVal = DAG.getNode(ARMISD::VMOVRRD, dl, 3734 DAG.getVTList(MVT::i32, MVT::i32), TrueVal); 3735 3736 SDValue TrueLow = TrueVal.getValue(0); 3737 SDValue TrueHigh = TrueVal.getValue(1); 3738 SDValue FalseLow = FalseVal.getValue(0); 3739 SDValue FalseHigh = FalseVal.getValue(1); 3740 3741 SDValue Low = DAG.getNode(ARMISD::CMOV, dl, MVT::i32, FalseLow, TrueLow, 3742 ARMcc, CCR, Cmp); 3743 SDValue High = DAG.getNode(ARMISD::CMOV, dl, MVT::i32, FalseHigh, TrueHigh, 3744 ARMcc, CCR, duplicateCmp(Cmp, DAG)); 3745 3746 return DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Low, High); 3747 } else { 3748 return DAG.getNode(ARMISD::CMOV, dl, VT, FalseVal, TrueVal, ARMcc, CCR, 3749 Cmp); 3750 } 3751 } 3752 3753 SDValue ARMTargetLowering::LowerSELECT_CC(SDValue Op, SelectionDAG &DAG) const { 3754 EVT VT = Op.getValueType(); 3755 SDValue LHS = Op.getOperand(0); 3756 SDValue RHS = Op.getOperand(1); 3757 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(4))->get(); 3758 SDValue TrueVal = Op.getOperand(2); 3759 SDValue FalseVal = Op.getOperand(3); 3760 SDLoc dl(Op); 3761 3762 if (Subtarget->isFPOnlySP() && LHS.getValueType() == MVT::f64) { 3763 DAG.getTargetLoweringInfo().softenSetCCOperands(DAG, MVT::f64, LHS, RHS, CC, 3764 dl); 3765 3766 // If softenSetCCOperands only returned one value, we should compare it to 3767 // zero. 3768 if (!RHS.getNode()) { 3769 RHS = DAG.getConstant(0, dl, LHS.getValueType()); 3770 CC = ISD::SETNE; 3771 } 3772 } 3773 3774 if (LHS.getValueType() == MVT::i32) { 3775 // Try to generate VSEL on ARMv8. 3776 // The VSEL instruction can't use all the usual ARM condition 3777 // codes: it only has two bits to select the condition code, so it's 3778 // constrained to use only GE, GT, VS and EQ. 3779 // 3780 // To implement all the various ISD::SETXXX opcodes, we sometimes need to 3781 // swap the operands of the previous compare instruction (effectively 3782 // inverting the compare condition, swapping 'less' and 'greater') and 3783 // sometimes need to swap the operands to the VSEL (which inverts the 3784 // condition in the sense of firing whenever the previous condition didn't) 3785 if (Subtarget->hasFPARMv8() && (TrueVal.getValueType() == MVT::f32 || 3786 TrueVal.getValueType() == MVT::f64)) { 3787 ARMCC::CondCodes CondCode = IntCCToARMCC(CC); 3788 if (CondCode == ARMCC::LT || CondCode == ARMCC::LE || 3789 CondCode == ARMCC::VC || CondCode == ARMCC::NE) { 3790 CC = ISD::getSetCCInverse(CC, true); 3791 std::swap(TrueVal, FalseVal); 3792 } 3793 } 3794 3795 SDValue ARMcc; 3796 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32); 3797 SDValue Cmp = getARMCmp(LHS, RHS, CC, ARMcc, DAG, dl); 3798 return getCMOV(dl, VT, FalseVal, TrueVal, ARMcc, CCR, Cmp, DAG); 3799 } 3800 3801 ARMCC::CondCodes CondCode, CondCode2; 3802 FPCCToARMCC(CC, CondCode, CondCode2); 3803 3804 // Try to generate VMAXNM/VMINNM on ARMv8. 3805 if (Subtarget->hasFPARMv8() && (TrueVal.getValueType() == MVT::f32 || 3806 TrueVal.getValueType() == MVT::f64)) { 3807 bool swpCmpOps = false; 3808 bool swpVselOps = false; 3809 checkVSELConstraints(CC, CondCode, swpCmpOps, swpVselOps); 3810 3811 if (CondCode == ARMCC::GT || CondCode == ARMCC::GE || 3812 CondCode == ARMCC::VS || CondCode == ARMCC::EQ) { 3813 if (swpCmpOps) 3814 std::swap(LHS, RHS); 3815 if (swpVselOps) 3816 std::swap(TrueVal, FalseVal); 3817 } 3818 } 3819 3820 SDValue ARMcc = DAG.getConstant(CondCode, dl, MVT::i32); 3821 SDValue Cmp = getVFPCmp(LHS, RHS, DAG, dl); 3822 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32); 3823 SDValue Result = getCMOV(dl, VT, FalseVal, TrueVal, ARMcc, CCR, Cmp, DAG); 3824 if (CondCode2 != ARMCC::AL) { 3825 SDValue ARMcc2 = DAG.getConstant(CondCode2, dl, MVT::i32); 3826 // FIXME: Needs another CMP because flag can have but one use. 3827 SDValue Cmp2 = getVFPCmp(LHS, RHS, DAG, dl); 3828 Result = getCMOV(dl, VT, Result, TrueVal, ARMcc2, CCR, Cmp2, DAG); 3829 } 3830 return Result; 3831 } 3832 3833 /// canChangeToInt - Given the fp compare operand, return true if it is suitable 3834 /// to morph to an integer compare sequence. 3835 static bool canChangeToInt(SDValue Op, bool &SeenZero, 3836 const ARMSubtarget *Subtarget) { 3837 SDNode *N = Op.getNode(); 3838 if (!N->hasOneUse()) 3839 // Otherwise it requires moving the value from fp to integer registers. 3840 return false; 3841 if (!N->getNumValues()) 3842 return false; 3843 EVT VT = Op.getValueType(); 3844 if (VT != MVT::f32 && !Subtarget->isFPBrccSlow()) 3845 // f32 case is generally profitable. f64 case only makes sense when vcmpe + 3846 // vmrs are very slow, e.g. cortex-a8. 3847 return false; 3848 3849 if (isFloatingPointZero(Op)) { 3850 SeenZero = true; 3851 return true; 3852 } 3853 return ISD::isNormalLoad(N); 3854 } 3855 3856 static SDValue bitcastf32Toi32(SDValue Op, SelectionDAG &DAG) { 3857 if (isFloatingPointZero(Op)) 3858 return DAG.getConstant(0, SDLoc(Op), MVT::i32); 3859 3860 if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Op)) 3861 return DAG.getLoad(MVT::i32, SDLoc(Op), 3862 Ld->getChain(), Ld->getBasePtr(), Ld->getPointerInfo(), 3863 Ld->isVolatile(), Ld->isNonTemporal(), 3864 Ld->isInvariant(), Ld->getAlignment()); 3865 3866 llvm_unreachable("Unknown VFP cmp argument!"); 3867 } 3868 3869 static void expandf64Toi32(SDValue Op, SelectionDAG &DAG, 3870 SDValue &RetVal1, SDValue &RetVal2) { 3871 SDLoc dl(Op); 3872 3873 if (isFloatingPointZero(Op)) { 3874 RetVal1 = DAG.getConstant(0, dl, MVT::i32); 3875 RetVal2 = DAG.getConstant(0, dl, MVT::i32); 3876 return; 3877 } 3878 3879 if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Op)) { 3880 SDValue Ptr = Ld->getBasePtr(); 3881 RetVal1 = DAG.getLoad(MVT::i32, dl, 3882 Ld->getChain(), Ptr, 3883 Ld->getPointerInfo(), 3884 Ld->isVolatile(), Ld->isNonTemporal(), 3885 Ld->isInvariant(), Ld->getAlignment()); 3886 3887 EVT PtrType = Ptr.getValueType(); 3888 unsigned NewAlign = MinAlign(Ld->getAlignment(), 4); 3889 SDValue NewPtr = DAG.getNode(ISD::ADD, dl, 3890 PtrType, Ptr, DAG.getConstant(4, dl, PtrType)); 3891 RetVal2 = DAG.getLoad(MVT::i32, dl, 3892 Ld->getChain(), NewPtr, 3893 Ld->getPointerInfo().getWithOffset(4), 3894 Ld->isVolatile(), Ld->isNonTemporal(), 3895 Ld->isInvariant(), NewAlign); 3896 return; 3897 } 3898 3899 llvm_unreachable("Unknown VFP cmp argument!"); 3900 } 3901 3902 /// OptimizeVFPBrcond - With -enable-unsafe-fp-math, it's legal to optimize some 3903 /// f32 and even f64 comparisons to integer ones. 3904 SDValue 3905 ARMTargetLowering::OptimizeVFPBrcond(SDValue Op, SelectionDAG &DAG) const { 3906 SDValue Chain = Op.getOperand(0); 3907 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(1))->get(); 3908 SDValue LHS = Op.getOperand(2); 3909 SDValue RHS = Op.getOperand(3); 3910 SDValue Dest = Op.getOperand(4); 3911 SDLoc dl(Op); 3912 3913 bool LHSSeenZero = false; 3914 bool LHSOk = canChangeToInt(LHS, LHSSeenZero, Subtarget); 3915 bool RHSSeenZero = false; 3916 bool RHSOk = canChangeToInt(RHS, RHSSeenZero, Subtarget); 3917 if (LHSOk && RHSOk && (LHSSeenZero || RHSSeenZero)) { 3918 // If unsafe fp math optimization is enabled and there are no other uses of 3919 // the CMP operands, and the condition code is EQ or NE, we can optimize it 3920 // to an integer comparison. 3921 if (CC == ISD::SETOEQ) 3922 CC = ISD::SETEQ; 3923 else if (CC == ISD::SETUNE) 3924 CC = ISD::SETNE; 3925 3926 SDValue Mask = DAG.getConstant(0x7fffffff, dl, MVT::i32); 3927 SDValue ARMcc; 3928 if (LHS.getValueType() == MVT::f32) { 3929 LHS = DAG.getNode(ISD::AND, dl, MVT::i32, 3930 bitcastf32Toi32(LHS, DAG), Mask); 3931 RHS = DAG.getNode(ISD::AND, dl, MVT::i32, 3932 bitcastf32Toi32(RHS, DAG), Mask); 3933 SDValue Cmp = getARMCmp(LHS, RHS, CC, ARMcc, DAG, dl); 3934 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32); 3935 return DAG.getNode(ARMISD::BRCOND, dl, MVT::Other, 3936 Chain, Dest, ARMcc, CCR, Cmp); 3937 } 3938 3939 SDValue LHS1, LHS2; 3940 SDValue RHS1, RHS2; 3941 expandf64Toi32(LHS, DAG, LHS1, LHS2); 3942 expandf64Toi32(RHS, DAG, RHS1, RHS2); 3943 LHS2 = DAG.getNode(ISD::AND, dl, MVT::i32, LHS2, Mask); 3944 RHS2 = DAG.getNode(ISD::AND, dl, MVT::i32, RHS2, Mask); 3945 ARMCC::CondCodes CondCode = IntCCToARMCC(CC); 3946 ARMcc = DAG.getConstant(CondCode, dl, MVT::i32); 3947 SDVTList VTList = DAG.getVTList(MVT::Other, MVT::Glue); 3948 SDValue Ops[] = { Chain, ARMcc, LHS1, LHS2, RHS1, RHS2, Dest }; 3949 return DAG.getNode(ARMISD::BCC_i64, dl, VTList, Ops); 3950 } 3951 3952 return SDValue(); 3953 } 3954 3955 SDValue ARMTargetLowering::LowerBR_CC(SDValue Op, SelectionDAG &DAG) const { 3956 SDValue Chain = Op.getOperand(0); 3957 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(1))->get(); 3958 SDValue LHS = Op.getOperand(2); 3959 SDValue RHS = Op.getOperand(3); 3960 SDValue Dest = Op.getOperand(4); 3961 SDLoc dl(Op); 3962 3963 if (Subtarget->isFPOnlySP() && LHS.getValueType() == MVT::f64) { 3964 DAG.getTargetLoweringInfo().softenSetCCOperands(DAG, MVT::f64, LHS, RHS, CC, 3965 dl); 3966 3967 // If softenSetCCOperands only returned one value, we should compare it to 3968 // zero. 3969 if (!RHS.getNode()) { 3970 RHS = DAG.getConstant(0, dl, LHS.getValueType()); 3971 CC = ISD::SETNE; 3972 } 3973 } 3974 3975 if (LHS.getValueType() == MVT::i32) { 3976 SDValue ARMcc; 3977 SDValue Cmp = getARMCmp(LHS, RHS, CC, ARMcc, DAG, dl); 3978 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32); 3979 return DAG.getNode(ARMISD::BRCOND, dl, MVT::Other, 3980 Chain, Dest, ARMcc, CCR, Cmp); 3981 } 3982 3983 assert(LHS.getValueType() == MVT::f32 || LHS.getValueType() == MVT::f64); 3984 3985 if (getTargetMachine().Options.UnsafeFPMath && 3986 (CC == ISD::SETEQ || CC == ISD::SETOEQ || 3987 CC == ISD::SETNE || CC == ISD::SETUNE)) { 3988 if (SDValue Result = OptimizeVFPBrcond(Op, DAG)) 3989 return Result; 3990 } 3991 3992 ARMCC::CondCodes CondCode, CondCode2; 3993 FPCCToARMCC(CC, CondCode, CondCode2); 3994 3995 SDValue ARMcc = DAG.getConstant(CondCode, dl, MVT::i32); 3996 SDValue Cmp = getVFPCmp(LHS, RHS, DAG, dl); 3997 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32); 3998 SDVTList VTList = DAG.getVTList(MVT::Other, MVT::Glue); 3999 SDValue Ops[] = { Chain, Dest, ARMcc, CCR, Cmp }; 4000 SDValue Res = DAG.getNode(ARMISD::BRCOND, dl, VTList, Ops); 4001 if (CondCode2 != ARMCC::AL) { 4002 ARMcc = DAG.getConstant(CondCode2, dl, MVT::i32); 4003 SDValue Ops[] = { Res, Dest, ARMcc, CCR, Res.getValue(1) }; 4004 Res = DAG.getNode(ARMISD::BRCOND, dl, VTList, Ops); 4005 } 4006 return Res; 4007 } 4008 4009 SDValue ARMTargetLowering::LowerBR_JT(SDValue Op, SelectionDAG &DAG) const { 4010 SDValue Chain = Op.getOperand(0); 4011 SDValue Table = Op.getOperand(1); 4012 SDValue Index = Op.getOperand(2); 4013 SDLoc dl(Op); 4014 4015 EVT PTy = getPointerTy(DAG.getDataLayout()); 4016 JumpTableSDNode *JT = cast<JumpTableSDNode>(Table); 4017 SDValue JTI = DAG.getTargetJumpTable(JT->getIndex(), PTy); 4018 Table = DAG.getNode(ARMISD::WrapperJT, dl, MVT::i32, JTI); 4019 Index = DAG.getNode(ISD::MUL, dl, PTy, Index, DAG.getConstant(4, dl, PTy)); 4020 SDValue Addr = DAG.getNode(ISD::ADD, dl, PTy, Index, Table); 4021 if (Subtarget->isThumb2()) { 4022 // Thumb2 uses a two-level jump. That is, it jumps into the jump table 4023 // which does another jump to the destination. This also makes it easier 4024 // to translate it to TBB / TBH later. 4025 // FIXME: This might not work if the function is extremely large. 4026 return DAG.getNode(ARMISD::BR2_JT, dl, MVT::Other, Chain, 4027 Addr, Op.getOperand(2), JTI); 4028 } 4029 if (getTargetMachine().getRelocationModel() == Reloc::PIC_) { 4030 Addr = 4031 DAG.getLoad((EVT)MVT::i32, dl, Chain, Addr, 4032 MachinePointerInfo::getJumpTable(DAG.getMachineFunction()), 4033 false, false, false, 0); 4034 Chain = Addr.getValue(1); 4035 Addr = DAG.getNode(ISD::ADD, dl, PTy, Addr, Table); 4036 return DAG.getNode(ARMISD::BR_JT, dl, MVT::Other, Chain, Addr, JTI); 4037 } else { 4038 Addr = 4039 DAG.getLoad(PTy, dl, Chain, Addr, 4040 MachinePointerInfo::getJumpTable(DAG.getMachineFunction()), 4041 false, false, false, 0); 4042 Chain = Addr.getValue(1); 4043 return DAG.getNode(ARMISD::BR_JT, dl, MVT::Other, Chain, Addr, JTI); 4044 } 4045 } 4046 4047 static SDValue LowerVectorFP_TO_INT(SDValue Op, SelectionDAG &DAG) { 4048 EVT VT = Op.getValueType(); 4049 SDLoc dl(Op); 4050 4051 if (Op.getValueType().getVectorElementType() == MVT::i32) { 4052 if (Op.getOperand(0).getValueType().getVectorElementType() == MVT::f32) 4053 return Op; 4054 return DAG.UnrollVectorOp(Op.getNode()); 4055 } 4056 4057 assert(Op.getOperand(0).getValueType() == MVT::v4f32 && 4058 "Invalid type for custom lowering!"); 4059 if (VT != MVT::v4i16) 4060 return DAG.UnrollVectorOp(Op.getNode()); 4061 4062 Op = DAG.getNode(Op.getOpcode(), dl, MVT::v4i32, Op.getOperand(0)); 4063 return DAG.getNode(ISD::TRUNCATE, dl, VT, Op); 4064 } 4065 4066 SDValue ARMTargetLowering::LowerFP_TO_INT(SDValue Op, SelectionDAG &DAG) const { 4067 EVT VT = Op.getValueType(); 4068 if (VT.isVector()) 4069 return LowerVectorFP_TO_INT(Op, DAG); 4070 if (Subtarget->isFPOnlySP() && Op.getOperand(0).getValueType() == MVT::f64) { 4071 RTLIB::Libcall LC; 4072 if (Op.getOpcode() == ISD::FP_TO_SINT) 4073 LC = RTLIB::getFPTOSINT(Op.getOperand(0).getValueType(), 4074 Op.getValueType()); 4075 else 4076 LC = RTLIB::getFPTOUINT(Op.getOperand(0).getValueType(), 4077 Op.getValueType()); 4078 return makeLibCall(DAG, LC, Op.getValueType(), Op.getOperand(0), 4079 /*isSigned*/ false, SDLoc(Op)).first; 4080 } 4081 4082 return Op; 4083 } 4084 4085 static SDValue LowerVectorINT_TO_FP(SDValue Op, SelectionDAG &DAG) { 4086 EVT VT = Op.getValueType(); 4087 SDLoc dl(Op); 4088 4089 if (Op.getOperand(0).getValueType().getVectorElementType() == MVT::i32) { 4090 if (VT.getVectorElementType() == MVT::f32) 4091 return Op; 4092 return DAG.UnrollVectorOp(Op.getNode()); 4093 } 4094 4095 assert(Op.getOperand(0).getValueType() == MVT::v4i16 && 4096 "Invalid type for custom lowering!"); 4097 if (VT != MVT::v4f32) 4098 return DAG.UnrollVectorOp(Op.getNode()); 4099 4100 unsigned CastOpc; 4101 unsigned Opc; 4102 switch (Op.getOpcode()) { 4103 default: llvm_unreachable("Invalid opcode!"); 4104 case ISD::SINT_TO_FP: 4105 CastOpc = ISD::SIGN_EXTEND; 4106 Opc = ISD::SINT_TO_FP; 4107 break; 4108 case ISD::UINT_TO_FP: 4109 CastOpc = ISD::ZERO_EXTEND; 4110 Opc = ISD::UINT_TO_FP; 4111 break; 4112 } 4113 4114 Op = DAG.getNode(CastOpc, dl, MVT::v4i32, Op.getOperand(0)); 4115 return DAG.getNode(Opc, dl, VT, Op); 4116 } 4117 4118 SDValue ARMTargetLowering::LowerINT_TO_FP(SDValue Op, SelectionDAG &DAG) const { 4119 EVT VT = Op.getValueType(); 4120 if (VT.isVector()) 4121 return LowerVectorINT_TO_FP(Op, DAG); 4122 if (Subtarget->isFPOnlySP() && Op.getValueType() == MVT::f64) { 4123 RTLIB::Libcall LC; 4124 if (Op.getOpcode() == ISD::SINT_TO_FP) 4125 LC = RTLIB::getSINTTOFP(Op.getOperand(0).getValueType(), 4126 Op.getValueType()); 4127 else 4128 LC = RTLIB::getUINTTOFP(Op.getOperand(0).getValueType(), 4129 Op.getValueType()); 4130 return makeLibCall(DAG, LC, Op.getValueType(), Op.getOperand(0), 4131 /*isSigned*/ false, SDLoc(Op)).first; 4132 } 4133 4134 return Op; 4135 } 4136 4137 SDValue ARMTargetLowering::LowerFCOPYSIGN(SDValue Op, SelectionDAG &DAG) const { 4138 // Implement fcopysign with a fabs and a conditional fneg. 4139 SDValue Tmp0 = Op.getOperand(0); 4140 SDValue Tmp1 = Op.getOperand(1); 4141 SDLoc dl(Op); 4142 EVT VT = Op.getValueType(); 4143 EVT SrcVT = Tmp1.getValueType(); 4144 bool InGPR = Tmp0.getOpcode() == ISD::BITCAST || 4145 Tmp0.getOpcode() == ARMISD::VMOVDRR; 4146 bool UseNEON = !InGPR && Subtarget->hasNEON(); 4147 4148 if (UseNEON) { 4149 // Use VBSL to copy the sign bit. 4150 unsigned EncodedVal = ARM_AM::createNEONModImm(0x6, 0x80); 4151 SDValue Mask = DAG.getNode(ARMISD::VMOVIMM, dl, MVT::v2i32, 4152 DAG.getTargetConstant(EncodedVal, dl, MVT::i32)); 4153 EVT OpVT = (VT == MVT::f32) ? MVT::v2i32 : MVT::v1i64; 4154 if (VT == MVT::f64) 4155 Mask = DAG.getNode(ARMISD::VSHL, dl, OpVT, 4156 DAG.getNode(ISD::BITCAST, dl, OpVT, Mask), 4157 DAG.getConstant(32, dl, MVT::i32)); 4158 else /*if (VT == MVT::f32)*/ 4159 Tmp0 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f32, Tmp0); 4160 if (SrcVT == MVT::f32) { 4161 Tmp1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f32, Tmp1); 4162 if (VT == MVT::f64) 4163 Tmp1 = DAG.getNode(ARMISD::VSHL, dl, OpVT, 4164 DAG.getNode(ISD::BITCAST, dl, OpVT, Tmp1), 4165 DAG.getConstant(32, dl, MVT::i32)); 4166 } else if (VT == MVT::f32) 4167 Tmp1 = DAG.getNode(ARMISD::VSHRu, dl, MVT::v1i64, 4168 DAG.getNode(ISD::BITCAST, dl, MVT::v1i64, Tmp1), 4169 DAG.getConstant(32, dl, MVT::i32)); 4170 Tmp0 = DAG.getNode(ISD::BITCAST, dl, OpVT, Tmp0); 4171 Tmp1 = DAG.getNode(ISD::BITCAST, dl, OpVT, Tmp1); 4172 4173 SDValue AllOnes = DAG.getTargetConstant(ARM_AM::createNEONModImm(0xe, 0xff), 4174 dl, MVT::i32); 4175 AllOnes = DAG.getNode(ARMISD::VMOVIMM, dl, MVT::v8i8, AllOnes); 4176 SDValue MaskNot = DAG.getNode(ISD::XOR, dl, OpVT, Mask, 4177 DAG.getNode(ISD::BITCAST, dl, OpVT, AllOnes)); 4178 4179 SDValue Res = DAG.getNode(ISD::OR, dl, OpVT, 4180 DAG.getNode(ISD::AND, dl, OpVT, Tmp1, Mask), 4181 DAG.getNode(ISD::AND, dl, OpVT, Tmp0, MaskNot)); 4182 if (VT == MVT::f32) { 4183 Res = DAG.getNode(ISD::BITCAST, dl, MVT::v2f32, Res); 4184 Res = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f32, Res, 4185 DAG.getConstant(0, dl, MVT::i32)); 4186 } else { 4187 Res = DAG.getNode(ISD::BITCAST, dl, MVT::f64, Res); 4188 } 4189 4190 return Res; 4191 } 4192 4193 // Bitcast operand 1 to i32. 4194 if (SrcVT == MVT::f64) 4195 Tmp1 = DAG.getNode(ARMISD::VMOVRRD, dl, DAG.getVTList(MVT::i32, MVT::i32), 4196 Tmp1).getValue(1); 4197 Tmp1 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Tmp1); 4198 4199 // Or in the signbit with integer operations. 4200 SDValue Mask1 = DAG.getConstant(0x80000000, dl, MVT::i32); 4201 SDValue Mask2 = DAG.getConstant(0x7fffffff, dl, MVT::i32); 4202 Tmp1 = DAG.getNode(ISD::AND, dl, MVT::i32, Tmp1, Mask1); 4203 if (VT == MVT::f32) { 4204 Tmp0 = DAG.getNode(ISD::AND, dl, MVT::i32, 4205 DAG.getNode(ISD::BITCAST, dl, MVT::i32, Tmp0), Mask2); 4206 return DAG.getNode(ISD::BITCAST, dl, MVT::f32, 4207 DAG.getNode(ISD::OR, dl, MVT::i32, Tmp0, Tmp1)); 4208 } 4209 4210 // f64: Or the high part with signbit and then combine two parts. 4211 Tmp0 = DAG.getNode(ARMISD::VMOVRRD, dl, DAG.getVTList(MVT::i32, MVT::i32), 4212 Tmp0); 4213 SDValue Lo = Tmp0.getValue(0); 4214 SDValue Hi = DAG.getNode(ISD::AND, dl, MVT::i32, Tmp0.getValue(1), Mask2); 4215 Hi = DAG.getNode(ISD::OR, dl, MVT::i32, Hi, Tmp1); 4216 return DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi); 4217 } 4218 4219 SDValue ARMTargetLowering::LowerRETURNADDR(SDValue Op, SelectionDAG &DAG) const{ 4220 MachineFunction &MF = DAG.getMachineFunction(); 4221 MachineFrameInfo *MFI = MF.getFrameInfo(); 4222 MFI->setReturnAddressIsTaken(true); 4223 4224 if (verifyReturnAddressArgumentIsConstant(Op, DAG)) 4225 return SDValue(); 4226 4227 EVT VT = Op.getValueType(); 4228 SDLoc dl(Op); 4229 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue(); 4230 if (Depth) { 4231 SDValue FrameAddr = LowerFRAMEADDR(Op, DAG); 4232 SDValue Offset = DAG.getConstant(4, dl, MVT::i32); 4233 return DAG.getLoad(VT, dl, DAG.getEntryNode(), 4234 DAG.getNode(ISD::ADD, dl, VT, FrameAddr, Offset), 4235 MachinePointerInfo(), false, false, false, 0); 4236 } 4237 4238 // Return LR, which contains the return address. Mark it an implicit live-in. 4239 unsigned Reg = MF.addLiveIn(ARM::LR, getRegClassFor(MVT::i32)); 4240 return DAG.getCopyFromReg(DAG.getEntryNode(), dl, Reg, VT); 4241 } 4242 4243 SDValue ARMTargetLowering::LowerFRAMEADDR(SDValue Op, SelectionDAG &DAG) const { 4244 const ARMBaseRegisterInfo &ARI = 4245 *static_cast<const ARMBaseRegisterInfo*>(RegInfo); 4246 MachineFunction &MF = DAG.getMachineFunction(); 4247 MachineFrameInfo *MFI = MF.getFrameInfo(); 4248 MFI->setFrameAddressIsTaken(true); 4249 4250 EVT VT = Op.getValueType(); 4251 SDLoc dl(Op); // FIXME probably not meaningful 4252 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue(); 4253 unsigned FrameReg = ARI.getFrameRegister(MF); 4254 SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, VT); 4255 while (Depth--) 4256 FrameAddr = DAG.getLoad(VT, dl, DAG.getEntryNode(), FrameAddr, 4257 MachinePointerInfo(), 4258 false, false, false, 0); 4259 return FrameAddr; 4260 } 4261 4262 // FIXME? Maybe this could be a TableGen attribute on some registers and 4263 // this table could be generated automatically from RegInfo. 4264 unsigned ARMTargetLowering::getRegisterByName(const char* RegName, EVT VT, 4265 SelectionDAG &DAG) const { 4266 unsigned Reg = StringSwitch<unsigned>(RegName) 4267 .Case("sp", ARM::SP) 4268 .Default(0); 4269 if (Reg) 4270 return Reg; 4271 report_fatal_error(Twine("Invalid register name \"" 4272 + StringRef(RegName) + "\".")); 4273 } 4274 4275 // Result is 64 bit value so split into two 32 bit values and return as a 4276 // pair of values. 4277 static void ExpandREAD_REGISTER(SDNode *N, SmallVectorImpl<SDValue> &Results, 4278 SelectionDAG &DAG) { 4279 SDLoc DL(N); 4280 4281 // This function is only supposed to be called for i64 type destination. 4282 assert(N->getValueType(0) == MVT::i64 4283 && "ExpandREAD_REGISTER called for non-i64 type result."); 4284 4285 SDValue Read = DAG.getNode(ISD::READ_REGISTER, DL, 4286 DAG.getVTList(MVT::i32, MVT::i32, MVT::Other), 4287 N->getOperand(0), 4288 N->getOperand(1)); 4289 4290 Results.push_back(DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, Read.getValue(0), 4291 Read.getValue(1))); 4292 Results.push_back(Read.getOperand(0)); 4293 } 4294 4295 /// \p BC is a bitcast that is about to be turned into a VMOVDRR. 4296 /// When \p DstVT, the destination type of \p BC, is on the vector 4297 /// register bank and the source of bitcast, \p Op, operates on the same bank, 4298 /// it might be possible to combine them, such that everything stays on the 4299 /// vector register bank. 4300 /// \p return The node that would replace \p BT, if the combine 4301 /// is possible. 4302 static SDValue CombineVMOVDRRCandidateWithVecOp(const SDNode *BC, 4303 SelectionDAG &DAG) { 4304 SDValue Op = BC->getOperand(0); 4305 EVT DstVT = BC->getValueType(0); 4306 4307 // The only vector instruction that can produce a scalar (remember, 4308 // since the bitcast was about to be turned into VMOVDRR, the source 4309 // type is i64) from a vector is EXTRACT_VECTOR_ELT. 4310 // Moreover, we can do this combine only if there is one use. 4311 // Finally, if the destination type is not a vector, there is not 4312 // much point on forcing everything on the vector bank. 4313 if (!DstVT.isVector() || Op.getOpcode() != ISD::EXTRACT_VECTOR_ELT || 4314 !Op.hasOneUse()) 4315 return SDValue(); 4316 4317 // If the index is not constant, we will introduce an additional 4318 // multiply that will stick. 4319 // Give up in that case. 4320 ConstantSDNode *Index = dyn_cast<ConstantSDNode>(Op.getOperand(1)); 4321 if (!Index) 4322 return SDValue(); 4323 unsigned DstNumElt = DstVT.getVectorNumElements(); 4324 4325 // Compute the new index. 4326 const APInt &APIntIndex = Index->getAPIntValue(); 4327 APInt NewIndex(APIntIndex.getBitWidth(), DstNumElt); 4328 NewIndex *= APIntIndex; 4329 // Check if the new constant index fits into i32. 4330 if (NewIndex.getBitWidth() > 32) 4331 return SDValue(); 4332 4333 // vMTy bitcast(i64 extractelt vNi64 src, i32 index) -> 4334 // vMTy extractsubvector vNxMTy (bitcast vNi64 src), i32 index*M) 4335 SDLoc dl(Op); 4336 SDValue ExtractSrc = Op.getOperand(0); 4337 EVT VecVT = EVT::getVectorVT( 4338 *DAG.getContext(), DstVT.getScalarType(), 4339 ExtractSrc.getValueType().getVectorNumElements() * DstNumElt); 4340 SDValue BitCast = DAG.getNode(ISD::BITCAST, dl, VecVT, ExtractSrc); 4341 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DstVT, BitCast, 4342 DAG.getConstant(NewIndex.getZExtValue(), dl, MVT::i32)); 4343 } 4344 4345 /// ExpandBITCAST - If the target supports VFP, this function is called to 4346 /// expand a bit convert where either the source or destination type is i64 to 4347 /// use a VMOVDRR or VMOVRRD node. This should not be done when the non-i64 4348 /// operand type is illegal (e.g., v2f32 for a target that doesn't support 4349 /// vectors), since the legalizer won't know what to do with that. 4350 static SDValue ExpandBITCAST(SDNode *N, SelectionDAG &DAG) { 4351 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 4352 SDLoc dl(N); 4353 SDValue Op = N->getOperand(0); 4354 4355 // This function is only supposed to be called for i64 types, either as the 4356 // source or destination of the bit convert. 4357 EVT SrcVT = Op.getValueType(); 4358 EVT DstVT = N->getValueType(0); 4359 assert((SrcVT == MVT::i64 || DstVT == MVT::i64) && 4360 "ExpandBITCAST called for non-i64 type"); 4361 4362 // Turn i64->f64 into VMOVDRR. 4363 if (SrcVT == MVT::i64 && TLI.isTypeLegal(DstVT)) { 4364 // Do not force values to GPRs (this is what VMOVDRR does for the inputs) 4365 // if we can combine the bitcast with its source. 4366 if (SDValue Val = CombineVMOVDRRCandidateWithVecOp(N, DAG)) 4367 return Val; 4368 4369 SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, Op, 4370 DAG.getConstant(0, dl, MVT::i32)); 4371 SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, Op, 4372 DAG.getConstant(1, dl, MVT::i32)); 4373 return DAG.getNode(ISD::BITCAST, dl, DstVT, 4374 DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi)); 4375 } 4376 4377 // Turn f64->i64 into VMOVRRD. 4378 if (DstVT == MVT::i64 && TLI.isTypeLegal(SrcVT)) { 4379 SDValue Cvt; 4380 if (DAG.getDataLayout().isBigEndian() && SrcVT.isVector() && 4381 SrcVT.getVectorNumElements() > 1) 4382 Cvt = DAG.getNode(ARMISD::VMOVRRD, dl, 4383 DAG.getVTList(MVT::i32, MVT::i32), 4384 DAG.getNode(ARMISD::VREV64, dl, SrcVT, Op)); 4385 else 4386 Cvt = DAG.getNode(ARMISD::VMOVRRD, dl, 4387 DAG.getVTList(MVT::i32, MVT::i32), Op); 4388 // Merge the pieces into a single i64 value. 4389 return DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Cvt, Cvt.getValue(1)); 4390 } 4391 4392 return SDValue(); 4393 } 4394 4395 /// getZeroVector - Returns a vector of specified type with all zero elements. 4396 /// Zero vectors are used to represent vector negation and in those cases 4397 /// will be implemented with the NEON VNEG instruction. However, VNEG does 4398 /// not support i64 elements, so sometimes the zero vectors will need to be 4399 /// explicitly constructed. Regardless, use a canonical VMOV to create the 4400 /// zero vector. 4401 static SDValue getZeroVector(EVT VT, SelectionDAG &DAG, SDLoc dl) { 4402 assert(VT.isVector() && "Expected a vector type"); 4403 // The canonical modified immediate encoding of a zero vector is....0! 4404 SDValue EncodedVal = DAG.getTargetConstant(0, dl, MVT::i32); 4405 EVT VmovVT = VT.is128BitVector() ? MVT::v4i32 : MVT::v2i32; 4406 SDValue Vmov = DAG.getNode(ARMISD::VMOVIMM, dl, VmovVT, EncodedVal); 4407 return DAG.getNode(ISD::BITCAST, dl, VT, Vmov); 4408 } 4409 4410 /// LowerShiftRightParts - Lower SRA_PARTS, which returns two 4411 /// i32 values and take a 2 x i32 value to shift plus a shift amount. 4412 SDValue ARMTargetLowering::LowerShiftRightParts(SDValue Op, 4413 SelectionDAG &DAG) const { 4414 assert(Op.getNumOperands() == 3 && "Not a double-shift!"); 4415 EVT VT = Op.getValueType(); 4416 unsigned VTBits = VT.getSizeInBits(); 4417 SDLoc dl(Op); 4418 SDValue ShOpLo = Op.getOperand(0); 4419 SDValue ShOpHi = Op.getOperand(1); 4420 SDValue ShAmt = Op.getOperand(2); 4421 SDValue ARMcc; 4422 unsigned Opc = (Op.getOpcode() == ISD::SRA_PARTS) ? ISD::SRA : ISD::SRL; 4423 4424 assert(Op.getOpcode() == ISD::SRA_PARTS || Op.getOpcode() == ISD::SRL_PARTS); 4425 4426 SDValue RevShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32, 4427 DAG.getConstant(VTBits, dl, MVT::i32), ShAmt); 4428 SDValue Tmp1 = DAG.getNode(ISD::SRL, dl, VT, ShOpLo, ShAmt); 4429 SDValue ExtraShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32, ShAmt, 4430 DAG.getConstant(VTBits, dl, MVT::i32)); 4431 SDValue Tmp2 = DAG.getNode(ISD::SHL, dl, VT, ShOpHi, RevShAmt); 4432 SDValue FalseVal = DAG.getNode(ISD::OR, dl, VT, Tmp1, Tmp2); 4433 SDValue TrueVal = DAG.getNode(Opc, dl, VT, ShOpHi, ExtraShAmt); 4434 4435 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32); 4436 SDValue Cmp = getARMCmp(ExtraShAmt, DAG.getConstant(0, dl, MVT::i32), 4437 ISD::SETGE, ARMcc, DAG, dl); 4438 SDValue Hi = DAG.getNode(Opc, dl, VT, ShOpHi, ShAmt); 4439 SDValue Lo = DAG.getNode(ARMISD::CMOV, dl, VT, FalseVal, TrueVal, ARMcc, 4440 CCR, Cmp); 4441 4442 SDValue Ops[2] = { Lo, Hi }; 4443 return DAG.getMergeValues(Ops, dl); 4444 } 4445 4446 /// LowerShiftLeftParts - Lower SHL_PARTS, which returns two 4447 /// i32 values and take a 2 x i32 value to shift plus a shift amount. 4448 SDValue ARMTargetLowering::LowerShiftLeftParts(SDValue Op, 4449 SelectionDAG &DAG) const { 4450 assert(Op.getNumOperands() == 3 && "Not a double-shift!"); 4451 EVT VT = Op.getValueType(); 4452 unsigned VTBits = VT.getSizeInBits(); 4453 SDLoc dl(Op); 4454 SDValue ShOpLo = Op.getOperand(0); 4455 SDValue ShOpHi = Op.getOperand(1); 4456 SDValue ShAmt = Op.getOperand(2); 4457 SDValue ARMcc; 4458 4459 assert(Op.getOpcode() == ISD::SHL_PARTS); 4460 SDValue RevShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32, 4461 DAG.getConstant(VTBits, dl, MVT::i32), ShAmt); 4462 SDValue Tmp1 = DAG.getNode(ISD::SRL, dl, VT, ShOpLo, RevShAmt); 4463 SDValue ExtraShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32, ShAmt, 4464 DAG.getConstant(VTBits, dl, MVT::i32)); 4465 SDValue Tmp2 = DAG.getNode(ISD::SHL, dl, VT, ShOpHi, ShAmt); 4466 SDValue Tmp3 = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ExtraShAmt); 4467 4468 SDValue FalseVal = DAG.getNode(ISD::OR, dl, VT, Tmp1, Tmp2); 4469 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32); 4470 SDValue Cmp = getARMCmp(ExtraShAmt, DAG.getConstant(0, dl, MVT::i32), 4471 ISD::SETGE, ARMcc, DAG, dl); 4472 SDValue Lo = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ShAmt); 4473 SDValue Hi = DAG.getNode(ARMISD::CMOV, dl, VT, FalseVal, Tmp3, ARMcc, 4474 CCR, Cmp); 4475 4476 SDValue Ops[2] = { Lo, Hi }; 4477 return DAG.getMergeValues(Ops, dl); 4478 } 4479 4480 SDValue ARMTargetLowering::LowerFLT_ROUNDS_(SDValue Op, 4481 SelectionDAG &DAG) const { 4482 // The rounding mode is in bits 23:22 of the FPSCR. 4483 // The ARM rounding mode value to FLT_ROUNDS mapping is 0->1, 1->2, 2->3, 3->0 4484 // The formula we use to implement this is (((FPSCR + 1 << 22) >> 22) & 3) 4485 // so that the shift + and get folded into a bitfield extract. 4486 SDLoc dl(Op); 4487 SDValue FPSCR = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::i32, 4488 DAG.getConstant(Intrinsic::arm_get_fpscr, dl, 4489 MVT::i32)); 4490 SDValue FltRounds = DAG.getNode(ISD::ADD, dl, MVT::i32, FPSCR, 4491 DAG.getConstant(1U << 22, dl, MVT::i32)); 4492 SDValue RMODE = DAG.getNode(ISD::SRL, dl, MVT::i32, FltRounds, 4493 DAG.getConstant(22, dl, MVT::i32)); 4494 return DAG.getNode(ISD::AND, dl, MVT::i32, RMODE, 4495 DAG.getConstant(3, dl, MVT::i32)); 4496 } 4497 4498 static SDValue LowerCTTZ(SDNode *N, SelectionDAG &DAG, 4499 const ARMSubtarget *ST) { 4500 SDLoc dl(N); 4501 EVT VT = N->getValueType(0); 4502 if (VT.isVector()) { 4503 assert(ST->hasNEON()); 4504 4505 // Compute the least significant set bit: LSB = X & -X 4506 SDValue X = N->getOperand(0); 4507 SDValue NX = DAG.getNode(ISD::SUB, dl, VT, getZeroVector(VT, DAG, dl), X); 4508 SDValue LSB = DAG.getNode(ISD::AND, dl, VT, X, NX); 4509 4510 EVT ElemTy = VT.getVectorElementType(); 4511 4512 if (ElemTy == MVT::i8) { 4513 // Compute with: cttz(x) = ctpop(lsb - 1) 4514 SDValue One = DAG.getNode(ARMISD::VMOVIMM, dl, VT, 4515 DAG.getTargetConstant(1, dl, ElemTy)); 4516 SDValue Bits = DAG.getNode(ISD::SUB, dl, VT, LSB, One); 4517 return DAG.getNode(ISD::CTPOP, dl, VT, Bits); 4518 } 4519 4520 if ((ElemTy == MVT::i16 || ElemTy == MVT::i32) && 4521 (N->getOpcode() == ISD::CTTZ_ZERO_UNDEF)) { 4522 // Compute with: cttz(x) = (width - 1) - ctlz(lsb), if x != 0 4523 unsigned NumBits = ElemTy.getSizeInBits(); 4524 SDValue WidthMinus1 = 4525 DAG.getNode(ARMISD::VMOVIMM, dl, VT, 4526 DAG.getTargetConstant(NumBits - 1, dl, ElemTy)); 4527 SDValue CTLZ = DAG.getNode(ISD::CTLZ, dl, VT, LSB); 4528 return DAG.getNode(ISD::SUB, dl, VT, WidthMinus1, CTLZ); 4529 } 4530 4531 // Compute with: cttz(x) = ctpop(lsb - 1) 4532 4533 // Since we can only compute the number of bits in a byte with vcnt.8, we 4534 // have to gather the result with pairwise addition (vpaddl) for i16, i32, 4535 // and i64. 4536 4537 // Compute LSB - 1. 4538 SDValue Bits; 4539 if (ElemTy == MVT::i64) { 4540 // Load constant 0xffff'ffff'ffff'ffff to register. 4541 SDValue FF = DAG.getNode(ARMISD::VMOVIMM, dl, VT, 4542 DAG.getTargetConstant(0x1eff, dl, MVT::i32)); 4543 Bits = DAG.getNode(ISD::ADD, dl, VT, LSB, FF); 4544 } else { 4545 SDValue One = DAG.getNode(ARMISD::VMOVIMM, dl, VT, 4546 DAG.getTargetConstant(1, dl, ElemTy)); 4547 Bits = DAG.getNode(ISD::SUB, dl, VT, LSB, One); 4548 } 4549 4550 // Count #bits with vcnt.8. 4551 EVT VT8Bit = VT.is64BitVector() ? MVT::v8i8 : MVT::v16i8; 4552 SDValue BitsVT8 = DAG.getNode(ISD::BITCAST, dl, VT8Bit, Bits); 4553 SDValue Cnt8 = DAG.getNode(ISD::CTPOP, dl, VT8Bit, BitsVT8); 4554 4555 // Gather the #bits with vpaddl (pairwise add.) 4556 EVT VT16Bit = VT.is64BitVector() ? MVT::v4i16 : MVT::v8i16; 4557 SDValue Cnt16 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT16Bit, 4558 DAG.getTargetConstant(Intrinsic::arm_neon_vpaddlu, dl, MVT::i32), 4559 Cnt8); 4560 if (ElemTy == MVT::i16) 4561 return Cnt16; 4562 4563 EVT VT32Bit = VT.is64BitVector() ? MVT::v2i32 : MVT::v4i32; 4564 SDValue Cnt32 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT32Bit, 4565 DAG.getTargetConstant(Intrinsic::arm_neon_vpaddlu, dl, MVT::i32), 4566 Cnt16); 4567 if (ElemTy == MVT::i32) 4568 return Cnt32; 4569 4570 assert(ElemTy == MVT::i64); 4571 SDValue Cnt64 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT, 4572 DAG.getTargetConstant(Intrinsic::arm_neon_vpaddlu, dl, MVT::i32), 4573 Cnt32); 4574 return Cnt64; 4575 } 4576 4577 if (!ST->hasV6T2Ops()) 4578 return SDValue(); 4579 4580 SDValue rbit = DAG.getNode(ISD::BITREVERSE, dl, VT, N->getOperand(0)); 4581 return DAG.getNode(ISD::CTLZ, dl, VT, rbit); 4582 } 4583 4584 /// getCTPOP16BitCounts - Returns a v8i8/v16i8 vector containing the bit-count 4585 /// for each 16-bit element from operand, repeated. The basic idea is to 4586 /// leverage vcnt to get the 8-bit counts, gather and add the results. 4587 /// 4588 /// Trace for v4i16: 4589 /// input = [v0 v1 v2 v3 ] (vi 16-bit element) 4590 /// cast: N0 = [w0 w1 w2 w3 w4 w5 w6 w7] (v0 = [w0 w1], wi 8-bit element) 4591 /// vcnt: N1 = [b0 b1 b2 b3 b4 b5 b6 b7] (bi = bit-count of 8-bit element wi) 4592 /// vrev: N2 = [b1 b0 b3 b2 b5 b4 b7 b6] 4593 /// [b0 b1 b2 b3 b4 b5 b6 b7] 4594 /// +[b1 b0 b3 b2 b5 b4 b7 b6] 4595 /// N3=N1+N2 = [k0 k0 k1 k1 k2 k2 k3 k3] (k0 = b0+b1 = bit-count of 16-bit v0, 4596 /// vuzp: = [k0 k1 k2 k3 k0 k1 k2 k3] each ki is 8-bits) 4597 static SDValue getCTPOP16BitCounts(SDNode *N, SelectionDAG &DAG) { 4598 EVT VT = N->getValueType(0); 4599 SDLoc DL(N); 4600 4601 EVT VT8Bit = VT.is64BitVector() ? MVT::v8i8 : MVT::v16i8; 4602 SDValue N0 = DAG.getNode(ISD::BITCAST, DL, VT8Bit, N->getOperand(0)); 4603 SDValue N1 = DAG.getNode(ISD::CTPOP, DL, VT8Bit, N0); 4604 SDValue N2 = DAG.getNode(ARMISD::VREV16, DL, VT8Bit, N1); 4605 SDValue N3 = DAG.getNode(ISD::ADD, DL, VT8Bit, N1, N2); 4606 return DAG.getNode(ARMISD::VUZP, DL, VT8Bit, N3, N3); 4607 } 4608 4609 /// lowerCTPOP16BitElements - Returns a v4i16/v8i16 vector containing the 4610 /// bit-count for each 16-bit element from the operand. We need slightly 4611 /// different sequencing for v4i16 and v8i16 to stay within NEON's available 4612 /// 64/128-bit registers. 4613 /// 4614 /// Trace for v4i16: 4615 /// input = [v0 v1 v2 v3 ] (vi 16-bit element) 4616 /// v8i8: BitCounts = [k0 k1 k2 k3 k0 k1 k2 k3 ] (ki is the bit-count of vi) 4617 /// v8i16:Extended = [k0 k1 k2 k3 k0 k1 k2 k3 ] 4618 /// v4i16:Extracted = [k0 k1 k2 k3 ] 4619 static SDValue lowerCTPOP16BitElements(SDNode *N, SelectionDAG &DAG) { 4620 EVT VT = N->getValueType(0); 4621 SDLoc DL(N); 4622 4623 SDValue BitCounts = getCTPOP16BitCounts(N, DAG); 4624 if (VT.is64BitVector()) { 4625 SDValue Extended = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::v8i16, BitCounts); 4626 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v4i16, Extended, 4627 DAG.getIntPtrConstant(0, DL)); 4628 } else { 4629 SDValue Extracted = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v8i8, 4630 BitCounts, DAG.getIntPtrConstant(0, DL)); 4631 return DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::v8i16, Extracted); 4632 } 4633 } 4634 4635 /// lowerCTPOP32BitElements - Returns a v2i32/v4i32 vector containing the 4636 /// bit-count for each 32-bit element from the operand. The idea here is 4637 /// to split the vector into 16-bit elements, leverage the 16-bit count 4638 /// routine, and then combine the results. 4639 /// 4640 /// Trace for v2i32 (v4i32 similar with Extracted/Extended exchanged): 4641 /// input = [v0 v1 ] (vi: 32-bit elements) 4642 /// Bitcast = [w0 w1 w2 w3 ] (wi: 16-bit elements, v0 = [w0 w1]) 4643 /// Counts16 = [k0 k1 k2 k3 ] (ki: 16-bit elements, bit-count of wi) 4644 /// vrev: N0 = [k1 k0 k3 k2 ] 4645 /// [k0 k1 k2 k3 ] 4646 /// N1 =+[k1 k0 k3 k2 ] 4647 /// [k0 k2 k1 k3 ] 4648 /// N2 =+[k1 k3 k0 k2 ] 4649 /// [k0 k2 k1 k3 ] 4650 /// Extended =+[k1 k3 k0 k2 ] 4651 /// [k0 k2 ] 4652 /// Extracted=+[k1 k3 ] 4653 /// 4654 static SDValue lowerCTPOP32BitElements(SDNode *N, SelectionDAG &DAG) { 4655 EVT VT = N->getValueType(0); 4656 SDLoc DL(N); 4657 4658 EVT VT16Bit = VT.is64BitVector() ? MVT::v4i16 : MVT::v8i16; 4659 4660 SDValue Bitcast = DAG.getNode(ISD::BITCAST, DL, VT16Bit, N->getOperand(0)); 4661 SDValue Counts16 = lowerCTPOP16BitElements(Bitcast.getNode(), DAG); 4662 SDValue N0 = DAG.getNode(ARMISD::VREV32, DL, VT16Bit, Counts16); 4663 SDValue N1 = DAG.getNode(ISD::ADD, DL, VT16Bit, Counts16, N0); 4664 SDValue N2 = DAG.getNode(ARMISD::VUZP, DL, VT16Bit, N1, N1); 4665 4666 if (VT.is64BitVector()) { 4667 SDValue Extended = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::v4i32, N2); 4668 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2i32, Extended, 4669 DAG.getIntPtrConstant(0, DL)); 4670 } else { 4671 SDValue Extracted = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v4i16, N2, 4672 DAG.getIntPtrConstant(0, DL)); 4673 return DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::v4i32, Extracted); 4674 } 4675 } 4676 4677 static SDValue LowerCTPOP(SDNode *N, SelectionDAG &DAG, 4678 const ARMSubtarget *ST) { 4679 EVT VT = N->getValueType(0); 4680 4681 assert(ST->hasNEON() && "Custom ctpop lowering requires NEON."); 4682 assert((VT == MVT::v2i32 || VT == MVT::v4i32 || 4683 VT == MVT::v4i16 || VT == MVT::v8i16) && 4684 "Unexpected type for custom ctpop lowering"); 4685 4686 if (VT.getVectorElementType() == MVT::i32) 4687 return lowerCTPOP32BitElements(N, DAG); 4688 else 4689 return lowerCTPOP16BitElements(N, DAG); 4690 } 4691 4692 static SDValue LowerShift(SDNode *N, SelectionDAG &DAG, 4693 const ARMSubtarget *ST) { 4694 EVT VT = N->getValueType(0); 4695 SDLoc dl(N); 4696 4697 if (!VT.isVector()) 4698 return SDValue(); 4699 4700 // Lower vector shifts on NEON to use VSHL. 4701 assert(ST->hasNEON() && "unexpected vector shift"); 4702 4703 // Left shifts translate directly to the vshiftu intrinsic. 4704 if (N->getOpcode() == ISD::SHL) 4705 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT, 4706 DAG.getConstant(Intrinsic::arm_neon_vshiftu, dl, 4707 MVT::i32), 4708 N->getOperand(0), N->getOperand(1)); 4709 4710 assert((N->getOpcode() == ISD::SRA || 4711 N->getOpcode() == ISD::SRL) && "unexpected vector shift opcode"); 4712 4713 // NEON uses the same intrinsics for both left and right shifts. For 4714 // right shifts, the shift amounts are negative, so negate the vector of 4715 // shift amounts. 4716 EVT ShiftVT = N->getOperand(1).getValueType(); 4717 SDValue NegatedCount = DAG.getNode(ISD::SUB, dl, ShiftVT, 4718 getZeroVector(ShiftVT, DAG, dl), 4719 N->getOperand(1)); 4720 Intrinsic::ID vshiftInt = (N->getOpcode() == ISD::SRA ? 4721 Intrinsic::arm_neon_vshifts : 4722 Intrinsic::arm_neon_vshiftu); 4723 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT, 4724 DAG.getConstant(vshiftInt, dl, MVT::i32), 4725 N->getOperand(0), NegatedCount); 4726 } 4727 4728 static SDValue Expand64BitShift(SDNode *N, SelectionDAG &DAG, 4729 const ARMSubtarget *ST) { 4730 EVT VT = N->getValueType(0); 4731 SDLoc dl(N); 4732 4733 // We can get here for a node like i32 = ISD::SHL i32, i64 4734 if (VT != MVT::i64) 4735 return SDValue(); 4736 4737 assert((N->getOpcode() == ISD::SRL || N->getOpcode() == ISD::SRA) && 4738 "Unknown shift to lower!"); 4739 4740 // We only lower SRA, SRL of 1 here, all others use generic lowering. 4741 if (!isOneConstant(N->getOperand(1))) 4742 return SDValue(); 4743 4744 // If we are in thumb mode, we don't have RRX. 4745 if (ST->isThumb1Only()) return SDValue(); 4746 4747 // Okay, we have a 64-bit SRA or SRL of 1. Lower this to an RRX expr. 4748 SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(0), 4749 DAG.getConstant(0, dl, MVT::i32)); 4750 SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(0), 4751 DAG.getConstant(1, dl, MVT::i32)); 4752 4753 // First, build a SRA_FLAG/SRL_FLAG op, which shifts the top part by one and 4754 // captures the result into a carry flag. 4755 unsigned Opc = N->getOpcode() == ISD::SRL ? ARMISD::SRL_FLAG:ARMISD::SRA_FLAG; 4756 Hi = DAG.getNode(Opc, dl, DAG.getVTList(MVT::i32, MVT::Glue), Hi); 4757 4758 // The low part is an ARMISD::RRX operand, which shifts the carry in. 4759 Lo = DAG.getNode(ARMISD::RRX, dl, MVT::i32, Lo, Hi.getValue(1)); 4760 4761 // Merge the pieces into a single i64 value. 4762 return DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Lo, Hi); 4763 } 4764 4765 static SDValue LowerVSETCC(SDValue Op, SelectionDAG &DAG) { 4766 SDValue TmpOp0, TmpOp1; 4767 bool Invert = false; 4768 bool Swap = false; 4769 unsigned Opc = 0; 4770 4771 SDValue Op0 = Op.getOperand(0); 4772 SDValue Op1 = Op.getOperand(1); 4773 SDValue CC = Op.getOperand(2); 4774 EVT CmpVT = Op0.getValueType().changeVectorElementTypeToInteger(); 4775 EVT VT = Op.getValueType(); 4776 ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get(); 4777 SDLoc dl(Op); 4778 4779 if (CmpVT.getVectorElementType() == MVT::i64) 4780 // 64-bit comparisons are not legal. We've marked SETCC as non-Custom, 4781 // but it's possible that our operands are 64-bit but our result is 32-bit. 4782 // Bail in this case. 4783 return SDValue(); 4784 4785 if (Op1.getValueType().isFloatingPoint()) { 4786 switch (SetCCOpcode) { 4787 default: llvm_unreachable("Illegal FP comparison"); 4788 case ISD::SETUNE: 4789 case ISD::SETNE: Invert = true; // Fallthrough 4790 case ISD::SETOEQ: 4791 case ISD::SETEQ: Opc = ARMISD::VCEQ; break; 4792 case ISD::SETOLT: 4793 case ISD::SETLT: Swap = true; // Fallthrough 4794 case ISD::SETOGT: 4795 case ISD::SETGT: Opc = ARMISD::VCGT; break; 4796 case ISD::SETOLE: 4797 case ISD::SETLE: Swap = true; // Fallthrough 4798 case ISD::SETOGE: 4799 case ISD::SETGE: Opc = ARMISD::VCGE; break; 4800 case ISD::SETUGE: Swap = true; // Fallthrough 4801 case ISD::SETULE: Invert = true; Opc = ARMISD::VCGT; break; 4802 case ISD::SETUGT: Swap = true; // Fallthrough 4803 case ISD::SETULT: Invert = true; Opc = ARMISD::VCGE; break; 4804 case ISD::SETUEQ: Invert = true; // Fallthrough 4805 case ISD::SETONE: 4806 // Expand this to (OLT | OGT). 4807 TmpOp0 = Op0; 4808 TmpOp1 = Op1; 4809 Opc = ISD::OR; 4810 Op0 = DAG.getNode(ARMISD::VCGT, dl, CmpVT, TmpOp1, TmpOp0); 4811 Op1 = DAG.getNode(ARMISD::VCGT, dl, CmpVT, TmpOp0, TmpOp1); 4812 break; 4813 case ISD::SETUO: Invert = true; // Fallthrough 4814 case ISD::SETO: 4815 // Expand this to (OLT | OGE). 4816 TmpOp0 = Op0; 4817 TmpOp1 = Op1; 4818 Opc = ISD::OR; 4819 Op0 = DAG.getNode(ARMISD::VCGT, dl, CmpVT, TmpOp1, TmpOp0); 4820 Op1 = DAG.getNode(ARMISD::VCGE, dl, CmpVT, TmpOp0, TmpOp1); 4821 break; 4822 } 4823 } else { 4824 // Integer comparisons. 4825 switch (SetCCOpcode) { 4826 default: llvm_unreachable("Illegal integer comparison"); 4827 case ISD::SETNE: Invert = true; 4828 case ISD::SETEQ: Opc = ARMISD::VCEQ; break; 4829 case ISD::SETLT: Swap = true; 4830 case ISD::SETGT: Opc = ARMISD::VCGT; break; 4831 case ISD::SETLE: Swap = true; 4832 case ISD::SETGE: Opc = ARMISD::VCGE; break; 4833 case ISD::SETULT: Swap = true; 4834 case ISD::SETUGT: Opc = ARMISD::VCGTU; break; 4835 case ISD::SETULE: Swap = true; 4836 case ISD::SETUGE: Opc = ARMISD::VCGEU; break; 4837 } 4838 4839 // Detect VTST (Vector Test Bits) = icmp ne (and (op0, op1), zero). 4840 if (Opc == ARMISD::VCEQ) { 4841 4842 SDValue AndOp; 4843 if (ISD::isBuildVectorAllZeros(Op1.getNode())) 4844 AndOp = Op0; 4845 else if (ISD::isBuildVectorAllZeros(Op0.getNode())) 4846 AndOp = Op1; 4847 4848 // Ignore bitconvert. 4849 if (AndOp.getNode() && AndOp.getOpcode() == ISD::BITCAST) 4850 AndOp = AndOp.getOperand(0); 4851 4852 if (AndOp.getNode() && AndOp.getOpcode() == ISD::AND) { 4853 Opc = ARMISD::VTST; 4854 Op0 = DAG.getNode(ISD::BITCAST, dl, CmpVT, AndOp.getOperand(0)); 4855 Op1 = DAG.getNode(ISD::BITCAST, dl, CmpVT, AndOp.getOperand(1)); 4856 Invert = !Invert; 4857 } 4858 } 4859 } 4860 4861 if (Swap) 4862 std::swap(Op0, Op1); 4863 4864 // If one of the operands is a constant vector zero, attempt to fold the 4865 // comparison to a specialized compare-against-zero form. 4866 SDValue SingleOp; 4867 if (ISD::isBuildVectorAllZeros(Op1.getNode())) 4868 SingleOp = Op0; 4869 else if (ISD::isBuildVectorAllZeros(Op0.getNode())) { 4870 if (Opc == ARMISD::VCGE) 4871 Opc = ARMISD::VCLEZ; 4872 else if (Opc == ARMISD::VCGT) 4873 Opc = ARMISD::VCLTZ; 4874 SingleOp = Op1; 4875 } 4876 4877 SDValue Result; 4878 if (SingleOp.getNode()) { 4879 switch (Opc) { 4880 case ARMISD::VCEQ: 4881 Result = DAG.getNode(ARMISD::VCEQZ, dl, CmpVT, SingleOp); break; 4882 case ARMISD::VCGE: 4883 Result = DAG.getNode(ARMISD::VCGEZ, dl, CmpVT, SingleOp); break; 4884 case ARMISD::VCLEZ: 4885 Result = DAG.getNode(ARMISD::VCLEZ, dl, CmpVT, SingleOp); break; 4886 case ARMISD::VCGT: 4887 Result = DAG.getNode(ARMISD::VCGTZ, dl, CmpVT, SingleOp); break; 4888 case ARMISD::VCLTZ: 4889 Result = DAG.getNode(ARMISD::VCLTZ, dl, CmpVT, SingleOp); break; 4890 default: 4891 Result = DAG.getNode(Opc, dl, CmpVT, Op0, Op1); 4892 } 4893 } else { 4894 Result = DAG.getNode(Opc, dl, CmpVT, Op0, Op1); 4895 } 4896 4897 Result = DAG.getSExtOrTrunc(Result, dl, VT); 4898 4899 if (Invert) 4900 Result = DAG.getNOT(dl, Result, VT); 4901 4902 return Result; 4903 } 4904 4905 static SDValue LowerSETCCE(SDValue Op, SelectionDAG &DAG) { 4906 SDValue LHS = Op.getOperand(0); 4907 SDValue RHS = Op.getOperand(1); 4908 SDValue Carry = Op.getOperand(2); 4909 SDValue Cond = Op.getOperand(3); 4910 SDLoc DL(Op); 4911 4912 assert(LHS.getSimpleValueType().isInteger() && "SETCCE is integer only."); 4913 4914 assert(Carry.getOpcode() != ISD::CARRY_FALSE); 4915 SDVTList VTs = DAG.getVTList(LHS.getValueType(), MVT::i32); 4916 SDValue Cmp = DAG.getNode(ARMISD::SUBE, DL, VTs, LHS, RHS, Carry); 4917 4918 SDValue FVal = DAG.getConstant(0, DL, MVT::i32); 4919 SDValue TVal = DAG.getConstant(1, DL, MVT::i32); 4920 SDValue ARMcc = DAG.getConstant( 4921 IntCCToARMCC(cast<CondCodeSDNode>(Cond)->get()), DL, MVT::i32); 4922 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32); 4923 SDValue Chain = DAG.getCopyToReg(DAG.getEntryNode(), DL, ARM::CPSR, 4924 Cmp.getValue(1), SDValue()); 4925 return DAG.getNode(ARMISD::CMOV, DL, Op.getValueType(), FVal, TVal, ARMcc, 4926 CCR, Chain.getValue(1)); 4927 } 4928 4929 /// isNEONModifiedImm - Check if the specified splat value corresponds to a 4930 /// valid vector constant for a NEON instruction with a "modified immediate" 4931 /// operand (e.g., VMOV). If so, return the encoded value. 4932 static SDValue isNEONModifiedImm(uint64_t SplatBits, uint64_t SplatUndef, 4933 unsigned SplatBitSize, SelectionDAG &DAG, 4934 SDLoc dl, EVT &VT, bool is128Bits, 4935 NEONModImmType type) { 4936 unsigned OpCmode, Imm; 4937 4938 // SplatBitSize is set to the smallest size that splats the vector, so a 4939 // zero vector will always have SplatBitSize == 8. However, NEON modified 4940 // immediate instructions others than VMOV do not support the 8-bit encoding 4941 // of a zero vector, and the default encoding of zero is supposed to be the 4942 // 32-bit version. 4943 if (SplatBits == 0) 4944 SplatBitSize = 32; 4945 4946 switch (SplatBitSize) { 4947 case 8: 4948 if (type != VMOVModImm) 4949 return SDValue(); 4950 // Any 1-byte value is OK. Op=0, Cmode=1110. 4951 assert((SplatBits & ~0xff) == 0 && "one byte splat value is too big"); 4952 OpCmode = 0xe; 4953 Imm = SplatBits; 4954 VT = is128Bits ? MVT::v16i8 : MVT::v8i8; 4955 break; 4956 4957 case 16: 4958 // NEON's 16-bit VMOV supports splat values where only one byte is nonzero. 4959 VT = is128Bits ? MVT::v8i16 : MVT::v4i16; 4960 if ((SplatBits & ~0xff) == 0) { 4961 // Value = 0x00nn: Op=x, Cmode=100x. 4962 OpCmode = 0x8; 4963 Imm = SplatBits; 4964 break; 4965 } 4966 if ((SplatBits & ~0xff00) == 0) { 4967 // Value = 0xnn00: Op=x, Cmode=101x. 4968 OpCmode = 0xa; 4969 Imm = SplatBits >> 8; 4970 break; 4971 } 4972 return SDValue(); 4973 4974 case 32: 4975 // NEON's 32-bit VMOV supports splat values where: 4976 // * only one byte is nonzero, or 4977 // * the least significant byte is 0xff and the second byte is nonzero, or 4978 // * the least significant 2 bytes are 0xff and the third is nonzero. 4979 VT = is128Bits ? MVT::v4i32 : MVT::v2i32; 4980 if ((SplatBits & ~0xff) == 0) { 4981 // Value = 0x000000nn: Op=x, Cmode=000x. 4982 OpCmode = 0; 4983 Imm = SplatBits; 4984 break; 4985 } 4986 if ((SplatBits & ~0xff00) == 0) { 4987 // Value = 0x0000nn00: Op=x, Cmode=001x. 4988 OpCmode = 0x2; 4989 Imm = SplatBits >> 8; 4990 break; 4991 } 4992 if ((SplatBits & ~0xff0000) == 0) { 4993 // Value = 0x00nn0000: Op=x, Cmode=010x. 4994 OpCmode = 0x4; 4995 Imm = SplatBits >> 16; 4996 break; 4997 } 4998 if ((SplatBits & ~0xff000000) == 0) { 4999 // Value = 0xnn000000: Op=x, Cmode=011x. 5000 OpCmode = 0x6; 5001 Imm = SplatBits >> 24; 5002 break; 5003 } 5004 5005 // cmode == 0b1100 and cmode == 0b1101 are not supported for VORR or VBIC 5006 if (type == OtherModImm) return SDValue(); 5007 5008 if ((SplatBits & ~0xffff) == 0 && 5009 ((SplatBits | SplatUndef) & 0xff) == 0xff) { 5010 // Value = 0x0000nnff: Op=x, Cmode=1100. 5011 OpCmode = 0xc; 5012 Imm = SplatBits >> 8; 5013 break; 5014 } 5015 5016 if ((SplatBits & ~0xffffff) == 0 && 5017 ((SplatBits | SplatUndef) & 0xffff) == 0xffff) { 5018 // Value = 0x00nnffff: Op=x, Cmode=1101. 5019 OpCmode = 0xd; 5020 Imm = SplatBits >> 16; 5021 break; 5022 } 5023 5024 // Note: there are a few 32-bit splat values (specifically: 00ffff00, 5025 // ff000000, ff0000ff, and ffff00ff) that are valid for VMOV.I64 but not 5026 // VMOV.I32. A (very) minor optimization would be to replicate the value 5027 // and fall through here to test for a valid 64-bit splat. But, then the 5028 // caller would also need to check and handle the change in size. 5029 return SDValue(); 5030 5031 case 64: { 5032 if (type != VMOVModImm) 5033 return SDValue(); 5034 // NEON has a 64-bit VMOV splat where each byte is either 0 or 0xff. 5035 uint64_t BitMask = 0xff; 5036 uint64_t Val = 0; 5037 unsigned ImmMask = 1; 5038 Imm = 0; 5039 for (int ByteNum = 0; ByteNum < 8; ++ByteNum) { 5040 if (((SplatBits | SplatUndef) & BitMask) == BitMask) { 5041 Val |= BitMask; 5042 Imm |= ImmMask; 5043 } else if ((SplatBits & BitMask) != 0) { 5044 return SDValue(); 5045 } 5046 BitMask <<= 8; 5047 ImmMask <<= 1; 5048 } 5049 5050 if (DAG.getDataLayout().isBigEndian()) 5051 // swap higher and lower 32 bit word 5052 Imm = ((Imm & 0xf) << 4) | ((Imm & 0xf0) >> 4); 5053 5054 // Op=1, Cmode=1110. 5055 OpCmode = 0x1e; 5056 VT = is128Bits ? MVT::v2i64 : MVT::v1i64; 5057 break; 5058 } 5059 5060 default: 5061 llvm_unreachable("unexpected size for isNEONModifiedImm"); 5062 } 5063 5064 unsigned EncodedVal = ARM_AM::createNEONModImm(OpCmode, Imm); 5065 return DAG.getTargetConstant(EncodedVal, dl, MVT::i32); 5066 } 5067 5068 SDValue ARMTargetLowering::LowerConstantFP(SDValue Op, SelectionDAG &DAG, 5069 const ARMSubtarget *ST) const { 5070 if (!ST->hasVFP3()) 5071 return SDValue(); 5072 5073 bool IsDouble = Op.getValueType() == MVT::f64; 5074 ConstantFPSDNode *CFP = cast<ConstantFPSDNode>(Op); 5075 5076 // Use the default (constant pool) lowering for double constants when we have 5077 // an SP-only FPU 5078 if (IsDouble && Subtarget->isFPOnlySP()) 5079 return SDValue(); 5080 5081 // Try splatting with a VMOV.f32... 5082 APFloat FPVal = CFP->getValueAPF(); 5083 int ImmVal = IsDouble ? ARM_AM::getFP64Imm(FPVal) : ARM_AM::getFP32Imm(FPVal); 5084 5085 if (ImmVal != -1) { 5086 if (IsDouble || !ST->useNEONForSinglePrecisionFP()) { 5087 // We have code in place to select a valid ConstantFP already, no need to 5088 // do any mangling. 5089 return Op; 5090 } 5091 5092 // It's a float and we are trying to use NEON operations where 5093 // possible. Lower it to a splat followed by an extract. 5094 SDLoc DL(Op); 5095 SDValue NewVal = DAG.getTargetConstant(ImmVal, DL, MVT::i32); 5096 SDValue VecConstant = DAG.getNode(ARMISD::VMOVFPIMM, DL, MVT::v2f32, 5097 NewVal); 5098 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32, VecConstant, 5099 DAG.getConstant(0, DL, MVT::i32)); 5100 } 5101 5102 // The rest of our options are NEON only, make sure that's allowed before 5103 // proceeding.. 5104 if (!ST->hasNEON() || (!IsDouble && !ST->useNEONForSinglePrecisionFP())) 5105 return SDValue(); 5106 5107 EVT VMovVT; 5108 uint64_t iVal = FPVal.bitcastToAPInt().getZExtValue(); 5109 5110 // It wouldn't really be worth bothering for doubles except for one very 5111 // important value, which does happen to match: 0.0. So make sure we don't do 5112 // anything stupid. 5113 if (IsDouble && (iVal & 0xffffffff) != (iVal >> 32)) 5114 return SDValue(); 5115 5116 // Try a VMOV.i32 (FIXME: i8, i16, or i64 could work too). 5117 SDValue NewVal = isNEONModifiedImm(iVal & 0xffffffffU, 0, 32, DAG, SDLoc(Op), 5118 VMovVT, false, VMOVModImm); 5119 if (NewVal != SDValue()) { 5120 SDLoc DL(Op); 5121 SDValue VecConstant = DAG.getNode(ARMISD::VMOVIMM, DL, VMovVT, 5122 NewVal); 5123 if (IsDouble) 5124 return DAG.getNode(ISD::BITCAST, DL, MVT::f64, VecConstant); 5125 5126 // It's a float: cast and extract a vector element. 5127 SDValue VecFConstant = DAG.getNode(ISD::BITCAST, DL, MVT::v2f32, 5128 VecConstant); 5129 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32, VecFConstant, 5130 DAG.getConstant(0, DL, MVT::i32)); 5131 } 5132 5133 // Finally, try a VMVN.i32 5134 NewVal = isNEONModifiedImm(~iVal & 0xffffffffU, 0, 32, DAG, SDLoc(Op), VMovVT, 5135 false, VMVNModImm); 5136 if (NewVal != SDValue()) { 5137 SDLoc DL(Op); 5138 SDValue VecConstant = DAG.getNode(ARMISD::VMVNIMM, DL, VMovVT, NewVal); 5139 5140 if (IsDouble) 5141 return DAG.getNode(ISD::BITCAST, DL, MVT::f64, VecConstant); 5142 5143 // It's a float: cast and extract a vector element. 5144 SDValue VecFConstant = DAG.getNode(ISD::BITCAST, DL, MVT::v2f32, 5145 VecConstant); 5146 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32, VecFConstant, 5147 DAG.getConstant(0, DL, MVT::i32)); 5148 } 5149 5150 return SDValue(); 5151 } 5152 5153 // check if an VEXT instruction can handle the shuffle mask when the 5154 // vector sources of the shuffle are the same. 5155 static bool isSingletonVEXTMask(ArrayRef<int> M, EVT VT, unsigned &Imm) { 5156 unsigned NumElts = VT.getVectorNumElements(); 5157 5158 // Assume that the first shuffle index is not UNDEF. Fail if it is. 5159 if (M[0] < 0) 5160 return false; 5161 5162 Imm = M[0]; 5163 5164 // If this is a VEXT shuffle, the immediate value is the index of the first 5165 // element. The other shuffle indices must be the successive elements after 5166 // the first one. 5167 unsigned ExpectedElt = Imm; 5168 for (unsigned i = 1; i < NumElts; ++i) { 5169 // Increment the expected index. If it wraps around, just follow it 5170 // back to index zero and keep going. 5171 ++ExpectedElt; 5172 if (ExpectedElt == NumElts) 5173 ExpectedElt = 0; 5174 5175 if (M[i] < 0) continue; // ignore UNDEF indices 5176 if (ExpectedElt != static_cast<unsigned>(M[i])) 5177 return false; 5178 } 5179 5180 return true; 5181 } 5182 5183 5184 static bool isVEXTMask(ArrayRef<int> M, EVT VT, 5185 bool &ReverseVEXT, unsigned &Imm) { 5186 unsigned NumElts = VT.getVectorNumElements(); 5187 ReverseVEXT = false; 5188 5189 // Assume that the first shuffle index is not UNDEF. Fail if it is. 5190 if (M[0] < 0) 5191 return false; 5192 5193 Imm = M[0]; 5194 5195 // If this is a VEXT shuffle, the immediate value is the index of the first 5196 // element. The other shuffle indices must be the successive elements after 5197 // the first one. 5198 unsigned ExpectedElt = Imm; 5199 for (unsigned i = 1; i < NumElts; ++i) { 5200 // Increment the expected index. If it wraps around, it may still be 5201 // a VEXT but the source vectors must be swapped. 5202 ExpectedElt += 1; 5203 if (ExpectedElt == NumElts * 2) { 5204 ExpectedElt = 0; 5205 ReverseVEXT = true; 5206 } 5207 5208 if (M[i] < 0) continue; // ignore UNDEF indices 5209 if (ExpectedElt != static_cast<unsigned>(M[i])) 5210 return false; 5211 } 5212 5213 // Adjust the index value if the source operands will be swapped. 5214 if (ReverseVEXT) 5215 Imm -= NumElts; 5216 5217 return true; 5218 } 5219 5220 /// isVREVMask - Check if a vector shuffle corresponds to a VREV 5221 /// instruction with the specified blocksize. (The order of the elements 5222 /// within each block of the vector is reversed.) 5223 static bool isVREVMask(ArrayRef<int> M, EVT VT, unsigned BlockSize) { 5224 assert((BlockSize==16 || BlockSize==32 || BlockSize==64) && 5225 "Only possible block sizes for VREV are: 16, 32, 64"); 5226 5227 unsigned EltSz = VT.getVectorElementType().getSizeInBits(); 5228 if (EltSz == 64) 5229 return false; 5230 5231 unsigned NumElts = VT.getVectorNumElements(); 5232 unsigned BlockElts = M[0] + 1; 5233 // If the first shuffle index is UNDEF, be optimistic. 5234 if (M[0] < 0) 5235 BlockElts = BlockSize / EltSz; 5236 5237 if (BlockSize <= EltSz || BlockSize != BlockElts * EltSz) 5238 return false; 5239 5240 for (unsigned i = 0; i < NumElts; ++i) { 5241 if (M[i] < 0) continue; // ignore UNDEF indices 5242 if ((unsigned) M[i] != (i - i%BlockElts) + (BlockElts - 1 - i%BlockElts)) 5243 return false; 5244 } 5245 5246 return true; 5247 } 5248 5249 static bool isVTBLMask(ArrayRef<int> M, EVT VT) { 5250 // We can handle <8 x i8> vector shuffles. If the index in the mask is out of 5251 // range, then 0 is placed into the resulting vector. So pretty much any mask 5252 // of 8 elements can work here. 5253 return VT == MVT::v8i8 && M.size() == 8; 5254 } 5255 5256 // Checks whether the shuffle mask represents a vector transpose (VTRN) by 5257 // checking that pairs of elements in the shuffle mask represent the same index 5258 // in each vector, incrementing the expected index by 2 at each step. 5259 // e.g. For v1,v2 of type v4i32 a valid shuffle mask is: [0, 4, 2, 6] 5260 // v1={a,b,c,d} => x=shufflevector v1, v2 shufflemask => x={a,e,c,g} 5261 // v2={e,f,g,h} 5262 // WhichResult gives the offset for each element in the mask based on which 5263 // of the two results it belongs to. 5264 // 5265 // The transpose can be represented either as: 5266 // result1 = shufflevector v1, v2, result1_shuffle_mask 5267 // result2 = shufflevector v1, v2, result2_shuffle_mask 5268 // where v1/v2 and the shuffle masks have the same number of elements 5269 // (here WhichResult (see below) indicates which result is being checked) 5270 // 5271 // or as: 5272 // results = shufflevector v1, v2, shuffle_mask 5273 // where both results are returned in one vector and the shuffle mask has twice 5274 // as many elements as v1/v2 (here WhichResult will always be 0 if true) here we 5275 // want to check the low half and high half of the shuffle mask as if it were 5276 // the other case 5277 static bool isVTRNMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) { 5278 unsigned EltSz = VT.getVectorElementType().getSizeInBits(); 5279 if (EltSz == 64) 5280 return false; 5281 5282 unsigned NumElts = VT.getVectorNumElements(); 5283 if (M.size() != NumElts && M.size() != NumElts*2) 5284 return false; 5285 5286 // If the mask is twice as long as the input vector then we need to check the 5287 // upper and lower parts of the mask with a matching value for WhichResult 5288 // FIXME: A mask with only even values will be rejected in case the first 5289 // element is undefined, e.g. [-1, 4, 2, 6] will be rejected, because only 5290 // M[0] is used to determine WhichResult 5291 for (unsigned i = 0; i < M.size(); i += NumElts) { 5292 if (M.size() == NumElts * 2) 5293 WhichResult = i / NumElts; 5294 else 5295 WhichResult = M[i] == 0 ? 0 : 1; 5296 for (unsigned j = 0; j < NumElts; j += 2) { 5297 if ((M[i+j] >= 0 && (unsigned) M[i+j] != j + WhichResult) || 5298 (M[i+j+1] >= 0 && (unsigned) M[i+j+1] != j + NumElts + WhichResult)) 5299 return false; 5300 } 5301 } 5302 5303 if (M.size() == NumElts*2) 5304 WhichResult = 0; 5305 5306 return true; 5307 } 5308 5309 /// isVTRN_v_undef_Mask - Special case of isVTRNMask for canonical form of 5310 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef". 5311 /// Mask is e.g., <0, 0, 2, 2> instead of <0, 4, 2, 6>. 5312 static bool isVTRN_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult){ 5313 unsigned EltSz = VT.getVectorElementType().getSizeInBits(); 5314 if (EltSz == 64) 5315 return false; 5316 5317 unsigned NumElts = VT.getVectorNumElements(); 5318 if (M.size() != NumElts && M.size() != NumElts*2) 5319 return false; 5320 5321 for (unsigned i = 0; i < M.size(); i += NumElts) { 5322 if (M.size() == NumElts * 2) 5323 WhichResult = i / NumElts; 5324 else 5325 WhichResult = M[i] == 0 ? 0 : 1; 5326 for (unsigned j = 0; j < NumElts; j += 2) { 5327 if ((M[i+j] >= 0 && (unsigned) M[i+j] != j + WhichResult) || 5328 (M[i+j+1] >= 0 && (unsigned) M[i+j+1] != j + WhichResult)) 5329 return false; 5330 } 5331 } 5332 5333 if (M.size() == NumElts*2) 5334 WhichResult = 0; 5335 5336 return true; 5337 } 5338 5339 // Checks whether the shuffle mask represents a vector unzip (VUZP) by checking 5340 // that the mask elements are either all even and in steps of size 2 or all odd 5341 // and in steps of size 2. 5342 // e.g. For v1,v2 of type v4i32 a valid shuffle mask is: [0, 2, 4, 6] 5343 // v1={a,b,c,d} => x=shufflevector v1, v2 shufflemask => x={a,c,e,g} 5344 // v2={e,f,g,h} 5345 // Requires similar checks to that of isVTRNMask with 5346 // respect the how results are returned. 5347 static bool isVUZPMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) { 5348 unsigned EltSz = VT.getVectorElementType().getSizeInBits(); 5349 if (EltSz == 64) 5350 return false; 5351 5352 unsigned NumElts = VT.getVectorNumElements(); 5353 if (M.size() != NumElts && M.size() != NumElts*2) 5354 return false; 5355 5356 for (unsigned i = 0; i < M.size(); i += NumElts) { 5357 WhichResult = M[i] == 0 ? 0 : 1; 5358 for (unsigned j = 0; j < NumElts; ++j) { 5359 if (M[i+j] >= 0 && (unsigned) M[i+j] != 2 * j + WhichResult) 5360 return false; 5361 } 5362 } 5363 5364 if (M.size() == NumElts*2) 5365 WhichResult = 0; 5366 5367 // VUZP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32. 5368 if (VT.is64BitVector() && EltSz == 32) 5369 return false; 5370 5371 return true; 5372 } 5373 5374 /// isVUZP_v_undef_Mask - Special case of isVUZPMask for canonical form of 5375 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef". 5376 /// Mask is e.g., <0, 2, 0, 2> instead of <0, 2, 4, 6>, 5377 static bool isVUZP_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult){ 5378 unsigned EltSz = VT.getVectorElementType().getSizeInBits(); 5379 if (EltSz == 64) 5380 return false; 5381 5382 unsigned NumElts = VT.getVectorNumElements(); 5383 if (M.size() != NumElts && M.size() != NumElts*2) 5384 return false; 5385 5386 unsigned Half = NumElts / 2; 5387 for (unsigned i = 0; i < M.size(); i += NumElts) { 5388 WhichResult = M[i] == 0 ? 0 : 1; 5389 for (unsigned j = 0; j < NumElts; j += Half) { 5390 unsigned Idx = WhichResult; 5391 for (unsigned k = 0; k < Half; ++k) { 5392 int MIdx = M[i + j + k]; 5393 if (MIdx >= 0 && (unsigned) MIdx != Idx) 5394 return false; 5395 Idx += 2; 5396 } 5397 } 5398 } 5399 5400 if (M.size() == NumElts*2) 5401 WhichResult = 0; 5402 5403 // VUZP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32. 5404 if (VT.is64BitVector() && EltSz == 32) 5405 return false; 5406 5407 return true; 5408 } 5409 5410 // Checks whether the shuffle mask represents a vector zip (VZIP) by checking 5411 // that pairs of elements of the shufflemask represent the same index in each 5412 // vector incrementing sequentially through the vectors. 5413 // e.g. For v1,v2 of type v4i32 a valid shuffle mask is: [0, 4, 1, 5] 5414 // v1={a,b,c,d} => x=shufflevector v1, v2 shufflemask => x={a,e,b,f} 5415 // v2={e,f,g,h} 5416 // Requires similar checks to that of isVTRNMask with respect the how results 5417 // are returned. 5418 static bool isVZIPMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) { 5419 unsigned EltSz = VT.getVectorElementType().getSizeInBits(); 5420 if (EltSz == 64) 5421 return false; 5422 5423 unsigned NumElts = VT.getVectorNumElements(); 5424 if (M.size() != NumElts && M.size() != NumElts*2) 5425 return false; 5426 5427 for (unsigned i = 0; i < M.size(); i += NumElts) { 5428 WhichResult = M[i] == 0 ? 0 : 1; 5429 unsigned Idx = WhichResult * NumElts / 2; 5430 for (unsigned j = 0; j < NumElts; j += 2) { 5431 if ((M[i+j] >= 0 && (unsigned) M[i+j] != Idx) || 5432 (M[i+j+1] >= 0 && (unsigned) M[i+j+1] != Idx + NumElts)) 5433 return false; 5434 Idx += 1; 5435 } 5436 } 5437 5438 if (M.size() == NumElts*2) 5439 WhichResult = 0; 5440 5441 // VZIP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32. 5442 if (VT.is64BitVector() && EltSz == 32) 5443 return false; 5444 5445 return true; 5446 } 5447 5448 /// isVZIP_v_undef_Mask - Special case of isVZIPMask for canonical form of 5449 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef". 5450 /// Mask is e.g., <0, 0, 1, 1> instead of <0, 4, 1, 5>. 5451 static bool isVZIP_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult){ 5452 unsigned EltSz = VT.getVectorElementType().getSizeInBits(); 5453 if (EltSz == 64) 5454 return false; 5455 5456 unsigned NumElts = VT.getVectorNumElements(); 5457 if (M.size() != NumElts && M.size() != NumElts*2) 5458 return false; 5459 5460 for (unsigned i = 0; i < M.size(); i += NumElts) { 5461 WhichResult = M[i] == 0 ? 0 : 1; 5462 unsigned Idx = WhichResult * NumElts / 2; 5463 for (unsigned j = 0; j < NumElts; j += 2) { 5464 if ((M[i+j] >= 0 && (unsigned) M[i+j] != Idx) || 5465 (M[i+j+1] >= 0 && (unsigned) M[i+j+1] != Idx)) 5466 return false; 5467 Idx += 1; 5468 } 5469 } 5470 5471 if (M.size() == NumElts*2) 5472 WhichResult = 0; 5473 5474 // VZIP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32. 5475 if (VT.is64BitVector() && EltSz == 32) 5476 return false; 5477 5478 return true; 5479 } 5480 5481 /// Check if \p ShuffleMask is a NEON two-result shuffle (VZIP, VUZP, VTRN), 5482 /// and return the corresponding ARMISD opcode if it is, or 0 if it isn't. 5483 static unsigned isNEONTwoResultShuffleMask(ArrayRef<int> ShuffleMask, EVT VT, 5484 unsigned &WhichResult, 5485 bool &isV_UNDEF) { 5486 isV_UNDEF = false; 5487 if (isVTRNMask(ShuffleMask, VT, WhichResult)) 5488 return ARMISD::VTRN; 5489 if (isVUZPMask(ShuffleMask, VT, WhichResult)) 5490 return ARMISD::VUZP; 5491 if (isVZIPMask(ShuffleMask, VT, WhichResult)) 5492 return ARMISD::VZIP; 5493 5494 isV_UNDEF = true; 5495 if (isVTRN_v_undef_Mask(ShuffleMask, VT, WhichResult)) 5496 return ARMISD::VTRN; 5497 if (isVUZP_v_undef_Mask(ShuffleMask, VT, WhichResult)) 5498 return ARMISD::VUZP; 5499 if (isVZIP_v_undef_Mask(ShuffleMask, VT, WhichResult)) 5500 return ARMISD::VZIP; 5501 5502 return 0; 5503 } 5504 5505 /// \return true if this is a reverse operation on an vector. 5506 static bool isReverseMask(ArrayRef<int> M, EVT VT) { 5507 unsigned NumElts = VT.getVectorNumElements(); 5508 // Make sure the mask has the right size. 5509 if (NumElts != M.size()) 5510 return false; 5511 5512 // Look for <15, ..., 3, -1, 1, 0>. 5513 for (unsigned i = 0; i != NumElts; ++i) 5514 if (M[i] >= 0 && M[i] != (int) (NumElts - 1 - i)) 5515 return false; 5516 5517 return true; 5518 } 5519 5520 // If N is an integer constant that can be moved into a register in one 5521 // instruction, return an SDValue of such a constant (will become a MOV 5522 // instruction). Otherwise return null. 5523 static SDValue IsSingleInstrConstant(SDValue N, SelectionDAG &DAG, 5524 const ARMSubtarget *ST, SDLoc dl) { 5525 uint64_t Val; 5526 if (!isa<ConstantSDNode>(N)) 5527 return SDValue(); 5528 Val = cast<ConstantSDNode>(N)->getZExtValue(); 5529 5530 if (ST->isThumb1Only()) { 5531 if (Val <= 255 || ~Val <= 255) 5532 return DAG.getConstant(Val, dl, MVT::i32); 5533 } else { 5534 if (ARM_AM::getSOImmVal(Val) != -1 || ARM_AM::getSOImmVal(~Val) != -1) 5535 return DAG.getConstant(Val, dl, MVT::i32); 5536 } 5537 return SDValue(); 5538 } 5539 5540 // If this is a case we can't handle, return null and let the default 5541 // expansion code take care of it. 5542 SDValue ARMTargetLowering::LowerBUILD_VECTOR(SDValue Op, SelectionDAG &DAG, 5543 const ARMSubtarget *ST) const { 5544 BuildVectorSDNode *BVN = cast<BuildVectorSDNode>(Op.getNode()); 5545 SDLoc dl(Op); 5546 EVT VT = Op.getValueType(); 5547 5548 APInt SplatBits, SplatUndef; 5549 unsigned SplatBitSize; 5550 bool HasAnyUndefs; 5551 if (BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs)) { 5552 if (SplatBitSize <= 64) { 5553 // Check if an immediate VMOV works. 5554 EVT VmovVT; 5555 SDValue Val = isNEONModifiedImm(SplatBits.getZExtValue(), 5556 SplatUndef.getZExtValue(), SplatBitSize, 5557 DAG, dl, VmovVT, VT.is128BitVector(), 5558 VMOVModImm); 5559 if (Val.getNode()) { 5560 SDValue Vmov = DAG.getNode(ARMISD::VMOVIMM, dl, VmovVT, Val); 5561 return DAG.getNode(ISD::BITCAST, dl, VT, Vmov); 5562 } 5563 5564 // Try an immediate VMVN. 5565 uint64_t NegatedImm = (~SplatBits).getZExtValue(); 5566 Val = isNEONModifiedImm(NegatedImm, 5567 SplatUndef.getZExtValue(), SplatBitSize, 5568 DAG, dl, VmovVT, VT.is128BitVector(), 5569 VMVNModImm); 5570 if (Val.getNode()) { 5571 SDValue Vmov = DAG.getNode(ARMISD::VMVNIMM, dl, VmovVT, Val); 5572 return DAG.getNode(ISD::BITCAST, dl, VT, Vmov); 5573 } 5574 5575 // Use vmov.f32 to materialize other v2f32 and v4f32 splats. 5576 if ((VT == MVT::v2f32 || VT == MVT::v4f32) && SplatBitSize == 32) { 5577 int ImmVal = ARM_AM::getFP32Imm(SplatBits); 5578 if (ImmVal != -1) { 5579 SDValue Val = DAG.getTargetConstant(ImmVal, dl, MVT::i32); 5580 return DAG.getNode(ARMISD::VMOVFPIMM, dl, VT, Val); 5581 } 5582 } 5583 } 5584 } 5585 5586 // Scan through the operands to see if only one value is used. 5587 // 5588 // As an optimisation, even if more than one value is used it may be more 5589 // profitable to splat with one value then change some lanes. 5590 // 5591 // Heuristically we decide to do this if the vector has a "dominant" value, 5592 // defined as splatted to more than half of the lanes. 5593 unsigned NumElts = VT.getVectorNumElements(); 5594 bool isOnlyLowElement = true; 5595 bool usesOnlyOneValue = true; 5596 bool hasDominantValue = false; 5597 bool isConstant = true; 5598 5599 // Map of the number of times a particular SDValue appears in the 5600 // element list. 5601 DenseMap<SDValue, unsigned> ValueCounts; 5602 SDValue Value; 5603 for (unsigned i = 0; i < NumElts; ++i) { 5604 SDValue V = Op.getOperand(i); 5605 if (V.isUndef()) 5606 continue; 5607 if (i > 0) 5608 isOnlyLowElement = false; 5609 if (!isa<ConstantFPSDNode>(V) && !isa<ConstantSDNode>(V)) 5610 isConstant = false; 5611 5612 ValueCounts.insert(std::make_pair(V, 0)); 5613 unsigned &Count = ValueCounts[V]; 5614 5615 // Is this value dominant? (takes up more than half of the lanes) 5616 if (++Count > (NumElts / 2)) { 5617 hasDominantValue = true; 5618 Value = V; 5619 } 5620 } 5621 if (ValueCounts.size() != 1) 5622 usesOnlyOneValue = false; 5623 if (!Value.getNode() && ValueCounts.size() > 0) 5624 Value = ValueCounts.begin()->first; 5625 5626 if (ValueCounts.size() == 0) 5627 return DAG.getUNDEF(VT); 5628 5629 // Loads are better lowered with insert_vector_elt/ARMISD::BUILD_VECTOR. 5630 // Keep going if we are hitting this case. 5631 if (isOnlyLowElement && !ISD::isNormalLoad(Value.getNode())) 5632 return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Value); 5633 5634 unsigned EltSize = VT.getVectorElementType().getSizeInBits(); 5635 5636 // Use VDUP for non-constant splats. For f32 constant splats, reduce to 5637 // i32 and try again. 5638 if (hasDominantValue && EltSize <= 32) { 5639 if (!isConstant) { 5640 SDValue N; 5641 5642 // If we are VDUPing a value that comes directly from a vector, that will 5643 // cause an unnecessary move to and from a GPR, where instead we could 5644 // just use VDUPLANE. We can only do this if the lane being extracted 5645 // is at a constant index, as the VDUP from lane instructions only have 5646 // constant-index forms. 5647 ConstantSDNode *constIndex; 5648 if (Value->getOpcode() == ISD::EXTRACT_VECTOR_ELT && 5649 (constIndex = dyn_cast<ConstantSDNode>(Value->getOperand(1)))) { 5650 // We need to create a new undef vector to use for the VDUPLANE if the 5651 // size of the vector from which we get the value is different than the 5652 // size of the vector that we need to create. We will insert the element 5653 // such that the register coalescer will remove unnecessary copies. 5654 if (VT != Value->getOperand(0).getValueType()) { 5655 unsigned index = constIndex->getAPIntValue().getLimitedValue() % 5656 VT.getVectorNumElements(); 5657 N = DAG.getNode(ARMISD::VDUPLANE, dl, VT, 5658 DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, DAG.getUNDEF(VT), 5659 Value, DAG.getConstant(index, dl, MVT::i32)), 5660 DAG.getConstant(index, dl, MVT::i32)); 5661 } else 5662 N = DAG.getNode(ARMISD::VDUPLANE, dl, VT, 5663 Value->getOperand(0), Value->getOperand(1)); 5664 } else 5665 N = DAG.getNode(ARMISD::VDUP, dl, VT, Value); 5666 5667 if (!usesOnlyOneValue) { 5668 // The dominant value was splatted as 'N', but we now have to insert 5669 // all differing elements. 5670 for (unsigned I = 0; I < NumElts; ++I) { 5671 if (Op.getOperand(I) == Value) 5672 continue; 5673 SmallVector<SDValue, 3> Ops; 5674 Ops.push_back(N); 5675 Ops.push_back(Op.getOperand(I)); 5676 Ops.push_back(DAG.getConstant(I, dl, MVT::i32)); 5677 N = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Ops); 5678 } 5679 } 5680 return N; 5681 } 5682 if (VT.getVectorElementType().isFloatingPoint()) { 5683 SmallVector<SDValue, 8> Ops; 5684 for (unsigned i = 0; i < NumElts; ++i) 5685 Ops.push_back(DAG.getNode(ISD::BITCAST, dl, MVT::i32, 5686 Op.getOperand(i))); 5687 EVT VecVT = EVT::getVectorVT(*DAG.getContext(), MVT::i32, NumElts); 5688 SDValue Val = DAG.getNode(ISD::BUILD_VECTOR, dl, VecVT, Ops); 5689 Val = LowerBUILD_VECTOR(Val, DAG, ST); 5690 if (Val.getNode()) 5691 return DAG.getNode(ISD::BITCAST, dl, VT, Val); 5692 } 5693 if (usesOnlyOneValue) { 5694 SDValue Val = IsSingleInstrConstant(Value, DAG, ST, dl); 5695 if (isConstant && Val.getNode()) 5696 return DAG.getNode(ARMISD::VDUP, dl, VT, Val); 5697 } 5698 } 5699 5700 // If all elements are constants and the case above didn't get hit, fall back 5701 // to the default expansion, which will generate a load from the constant 5702 // pool. 5703 if (isConstant) 5704 return SDValue(); 5705 5706 // Empirical tests suggest this is rarely worth it for vectors of length <= 2. 5707 if (NumElts >= 4) { 5708 SDValue shuffle = ReconstructShuffle(Op, DAG); 5709 if (shuffle != SDValue()) 5710 return shuffle; 5711 } 5712 5713 // Vectors with 32- or 64-bit elements can be built by directly assigning 5714 // the subregisters. Lower it to an ARMISD::BUILD_VECTOR so the operands 5715 // will be legalized. 5716 if (EltSize >= 32) { 5717 // Do the expansion with floating-point types, since that is what the VFP 5718 // registers are defined to use, and since i64 is not legal. 5719 EVT EltVT = EVT::getFloatingPointVT(EltSize); 5720 EVT VecVT = EVT::getVectorVT(*DAG.getContext(), EltVT, NumElts); 5721 SmallVector<SDValue, 8> Ops; 5722 for (unsigned i = 0; i < NumElts; ++i) 5723 Ops.push_back(DAG.getNode(ISD::BITCAST, dl, EltVT, Op.getOperand(i))); 5724 SDValue Val = DAG.getNode(ARMISD::BUILD_VECTOR, dl, VecVT, Ops); 5725 return DAG.getNode(ISD::BITCAST, dl, VT, Val); 5726 } 5727 5728 // If all else fails, just use a sequence of INSERT_VECTOR_ELT when we 5729 // know the default expansion would otherwise fall back on something even 5730 // worse. For a vector with one or two non-undef values, that's 5731 // scalar_to_vector for the elements followed by a shuffle (provided the 5732 // shuffle is valid for the target) and materialization element by element 5733 // on the stack followed by a load for everything else. 5734 if (!isConstant && !usesOnlyOneValue) { 5735 SDValue Vec = DAG.getUNDEF(VT); 5736 for (unsigned i = 0 ; i < NumElts; ++i) { 5737 SDValue V = Op.getOperand(i); 5738 if (V.isUndef()) 5739 continue; 5740 SDValue LaneIdx = DAG.getConstant(i, dl, MVT::i32); 5741 Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Vec, V, LaneIdx); 5742 } 5743 return Vec; 5744 } 5745 5746 return SDValue(); 5747 } 5748 5749 // Gather data to see if the operation can be modelled as a 5750 // shuffle in combination with VEXTs. 5751 SDValue ARMTargetLowering::ReconstructShuffle(SDValue Op, 5752 SelectionDAG &DAG) const { 5753 assert(Op.getOpcode() == ISD::BUILD_VECTOR && "Unknown opcode!"); 5754 SDLoc dl(Op); 5755 EVT VT = Op.getValueType(); 5756 unsigned NumElts = VT.getVectorNumElements(); 5757 5758 struct ShuffleSourceInfo { 5759 SDValue Vec; 5760 unsigned MinElt; 5761 unsigned MaxElt; 5762 5763 // We may insert some combination of BITCASTs and VEXT nodes to force Vec to 5764 // be compatible with the shuffle we intend to construct. As a result 5765 // ShuffleVec will be some sliding window into the original Vec. 5766 SDValue ShuffleVec; 5767 5768 // Code should guarantee that element i in Vec starts at element "WindowBase 5769 // + i * WindowScale in ShuffleVec". 5770 int WindowBase; 5771 int WindowScale; 5772 5773 bool operator ==(SDValue OtherVec) { return Vec == OtherVec; } 5774 ShuffleSourceInfo(SDValue Vec) 5775 : Vec(Vec), MinElt(UINT_MAX), MaxElt(0), ShuffleVec(Vec), WindowBase(0), 5776 WindowScale(1) {} 5777 }; 5778 5779 // First gather all vectors used as an immediate source for this BUILD_VECTOR 5780 // node. 5781 SmallVector<ShuffleSourceInfo, 2> Sources; 5782 for (unsigned i = 0; i < NumElts; ++i) { 5783 SDValue V = Op.getOperand(i); 5784 if (V.isUndef()) 5785 continue; 5786 else if (V.getOpcode() != ISD::EXTRACT_VECTOR_ELT) { 5787 // A shuffle can only come from building a vector from various 5788 // elements of other vectors. 5789 return SDValue(); 5790 } else if (!isa<ConstantSDNode>(V.getOperand(1))) { 5791 // Furthermore, shuffles require a constant mask, whereas extractelts 5792 // accept variable indices. 5793 return SDValue(); 5794 } 5795 5796 // Add this element source to the list if it's not already there. 5797 SDValue SourceVec = V.getOperand(0); 5798 auto Source = std::find(Sources.begin(), Sources.end(), SourceVec); 5799 if (Source == Sources.end()) 5800 Source = Sources.insert(Sources.end(), ShuffleSourceInfo(SourceVec)); 5801 5802 // Update the minimum and maximum lane number seen. 5803 unsigned EltNo = cast<ConstantSDNode>(V.getOperand(1))->getZExtValue(); 5804 Source->MinElt = std::min(Source->MinElt, EltNo); 5805 Source->MaxElt = std::max(Source->MaxElt, EltNo); 5806 } 5807 5808 // Currently only do something sane when at most two source vectors 5809 // are involved. 5810 if (Sources.size() > 2) 5811 return SDValue(); 5812 5813 // Find out the smallest element size among result and two sources, and use 5814 // it as element size to build the shuffle_vector. 5815 EVT SmallestEltTy = VT.getVectorElementType(); 5816 for (auto &Source : Sources) { 5817 EVT SrcEltTy = Source.Vec.getValueType().getVectorElementType(); 5818 if (SrcEltTy.bitsLT(SmallestEltTy)) 5819 SmallestEltTy = SrcEltTy; 5820 } 5821 unsigned ResMultiplier = 5822 VT.getVectorElementType().getSizeInBits() / SmallestEltTy.getSizeInBits(); 5823 NumElts = VT.getSizeInBits() / SmallestEltTy.getSizeInBits(); 5824 EVT ShuffleVT = EVT::getVectorVT(*DAG.getContext(), SmallestEltTy, NumElts); 5825 5826 // If the source vector is too wide or too narrow, we may nevertheless be able 5827 // to construct a compatible shuffle either by concatenating it with UNDEF or 5828 // extracting a suitable range of elements. 5829 for (auto &Src : Sources) { 5830 EVT SrcVT = Src.ShuffleVec.getValueType(); 5831 5832 if (SrcVT.getSizeInBits() == VT.getSizeInBits()) 5833 continue; 5834 5835 // This stage of the search produces a source with the same element type as 5836 // the original, but with a total width matching the BUILD_VECTOR output. 5837 EVT EltVT = SrcVT.getVectorElementType(); 5838 unsigned NumSrcElts = VT.getSizeInBits() / EltVT.getSizeInBits(); 5839 EVT DestVT = EVT::getVectorVT(*DAG.getContext(), EltVT, NumSrcElts); 5840 5841 if (SrcVT.getSizeInBits() < VT.getSizeInBits()) { 5842 if (2 * SrcVT.getSizeInBits() != VT.getSizeInBits()) 5843 return SDValue(); 5844 // We can pad out the smaller vector for free, so if it's part of a 5845 // shuffle... 5846 Src.ShuffleVec = 5847 DAG.getNode(ISD::CONCAT_VECTORS, dl, DestVT, Src.ShuffleVec, 5848 DAG.getUNDEF(Src.ShuffleVec.getValueType())); 5849 continue; 5850 } 5851 5852 if (SrcVT.getSizeInBits() != 2 * VT.getSizeInBits()) 5853 return SDValue(); 5854 5855 if (Src.MaxElt - Src.MinElt >= NumSrcElts) { 5856 // Span too large for a VEXT to cope 5857 return SDValue(); 5858 } 5859 5860 if (Src.MinElt >= NumSrcElts) { 5861 // The extraction can just take the second half 5862 Src.ShuffleVec = 5863 DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DestVT, Src.ShuffleVec, 5864 DAG.getConstant(NumSrcElts, dl, MVT::i32)); 5865 Src.WindowBase = -NumSrcElts; 5866 } else if (Src.MaxElt < NumSrcElts) { 5867 // The extraction can just take the first half 5868 Src.ShuffleVec = 5869 DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DestVT, Src.ShuffleVec, 5870 DAG.getConstant(0, dl, MVT::i32)); 5871 } else { 5872 // An actual VEXT is needed 5873 SDValue VEXTSrc1 = 5874 DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DestVT, Src.ShuffleVec, 5875 DAG.getConstant(0, dl, MVT::i32)); 5876 SDValue VEXTSrc2 = 5877 DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DestVT, Src.ShuffleVec, 5878 DAG.getConstant(NumSrcElts, dl, MVT::i32)); 5879 5880 Src.ShuffleVec = DAG.getNode(ARMISD::VEXT, dl, DestVT, VEXTSrc1, 5881 VEXTSrc2, 5882 DAG.getConstant(Src.MinElt, dl, MVT::i32)); 5883 Src.WindowBase = -Src.MinElt; 5884 } 5885 } 5886 5887 // Another possible incompatibility occurs from the vector element types. We 5888 // can fix this by bitcasting the source vectors to the same type we intend 5889 // for the shuffle. 5890 for (auto &Src : Sources) { 5891 EVT SrcEltTy = Src.ShuffleVec.getValueType().getVectorElementType(); 5892 if (SrcEltTy == SmallestEltTy) 5893 continue; 5894 assert(ShuffleVT.getVectorElementType() == SmallestEltTy); 5895 Src.ShuffleVec = DAG.getNode(ISD::BITCAST, dl, ShuffleVT, Src.ShuffleVec); 5896 Src.WindowScale = SrcEltTy.getSizeInBits() / SmallestEltTy.getSizeInBits(); 5897 Src.WindowBase *= Src.WindowScale; 5898 } 5899 5900 // Final sanity check before we try to actually produce a shuffle. 5901 DEBUG( 5902 for (auto Src : Sources) 5903 assert(Src.ShuffleVec.getValueType() == ShuffleVT); 5904 ); 5905 5906 // The stars all align, our next step is to produce the mask for the shuffle. 5907 SmallVector<int, 8> Mask(ShuffleVT.getVectorNumElements(), -1); 5908 int BitsPerShuffleLane = ShuffleVT.getVectorElementType().getSizeInBits(); 5909 for (unsigned i = 0; i < VT.getVectorNumElements(); ++i) { 5910 SDValue Entry = Op.getOperand(i); 5911 if (Entry.isUndef()) 5912 continue; 5913 5914 auto Src = std::find(Sources.begin(), Sources.end(), Entry.getOperand(0)); 5915 int EltNo = cast<ConstantSDNode>(Entry.getOperand(1))->getSExtValue(); 5916 5917 // EXTRACT_VECTOR_ELT performs an implicit any_ext; BUILD_VECTOR an implicit 5918 // trunc. So only std::min(SrcBits, DestBits) actually get defined in this 5919 // segment. 5920 EVT OrigEltTy = Entry.getOperand(0).getValueType().getVectorElementType(); 5921 int BitsDefined = std::min(OrigEltTy.getSizeInBits(), 5922 VT.getVectorElementType().getSizeInBits()); 5923 int LanesDefined = BitsDefined / BitsPerShuffleLane; 5924 5925 // This source is expected to fill ResMultiplier lanes of the final shuffle, 5926 // starting at the appropriate offset. 5927 int *LaneMask = &Mask[i * ResMultiplier]; 5928 5929 int ExtractBase = EltNo * Src->WindowScale + Src->WindowBase; 5930 ExtractBase += NumElts * (Src - Sources.begin()); 5931 for (int j = 0; j < LanesDefined; ++j) 5932 LaneMask[j] = ExtractBase + j; 5933 } 5934 5935 // Final check before we try to produce nonsense... 5936 if (!isShuffleMaskLegal(Mask, ShuffleVT)) 5937 return SDValue(); 5938 5939 // We can't handle more than two sources. This should have already 5940 // been checked before this point. 5941 assert(Sources.size() <= 2 && "Too many sources!"); 5942 5943 SDValue ShuffleOps[] = { DAG.getUNDEF(ShuffleVT), DAG.getUNDEF(ShuffleVT) }; 5944 for (unsigned i = 0; i < Sources.size(); ++i) 5945 ShuffleOps[i] = Sources[i].ShuffleVec; 5946 5947 SDValue Shuffle = DAG.getVectorShuffle(ShuffleVT, dl, ShuffleOps[0], 5948 ShuffleOps[1], &Mask[0]); 5949 return DAG.getNode(ISD::BITCAST, dl, VT, Shuffle); 5950 } 5951 5952 /// isShuffleMaskLegal - Targets can use this to indicate that they only 5953 /// support *some* VECTOR_SHUFFLE operations, those with specific masks. 5954 /// By default, if a target supports the VECTOR_SHUFFLE node, all mask values 5955 /// are assumed to be legal. 5956 bool 5957 ARMTargetLowering::isShuffleMaskLegal(const SmallVectorImpl<int> &M, 5958 EVT VT) const { 5959 if (VT.getVectorNumElements() == 4 && 5960 (VT.is128BitVector() || VT.is64BitVector())) { 5961 unsigned PFIndexes[4]; 5962 for (unsigned i = 0; i != 4; ++i) { 5963 if (M[i] < 0) 5964 PFIndexes[i] = 8; 5965 else 5966 PFIndexes[i] = M[i]; 5967 } 5968 5969 // Compute the index in the perfect shuffle table. 5970 unsigned PFTableIndex = 5971 PFIndexes[0]*9*9*9+PFIndexes[1]*9*9+PFIndexes[2]*9+PFIndexes[3]; 5972 unsigned PFEntry = PerfectShuffleTable[PFTableIndex]; 5973 unsigned Cost = (PFEntry >> 30); 5974 5975 if (Cost <= 4) 5976 return true; 5977 } 5978 5979 bool ReverseVEXT, isV_UNDEF; 5980 unsigned Imm, WhichResult; 5981 5982 unsigned EltSize = VT.getVectorElementType().getSizeInBits(); 5983 return (EltSize >= 32 || 5984 ShuffleVectorSDNode::isSplatMask(&M[0], VT) || 5985 isVREVMask(M, VT, 64) || 5986 isVREVMask(M, VT, 32) || 5987 isVREVMask(M, VT, 16) || 5988 isVEXTMask(M, VT, ReverseVEXT, Imm) || 5989 isVTBLMask(M, VT) || 5990 isNEONTwoResultShuffleMask(M, VT, WhichResult, isV_UNDEF) || 5991 ((VT == MVT::v8i16 || VT == MVT::v16i8) && isReverseMask(M, VT))); 5992 } 5993 5994 /// GeneratePerfectShuffle - Given an entry in the perfect-shuffle table, emit 5995 /// the specified operations to build the shuffle. 5996 static SDValue GeneratePerfectShuffle(unsigned PFEntry, SDValue LHS, 5997 SDValue RHS, SelectionDAG &DAG, 5998 SDLoc dl) { 5999 unsigned OpNum = (PFEntry >> 26) & 0x0F; 6000 unsigned LHSID = (PFEntry >> 13) & ((1 << 13)-1); 6001 unsigned RHSID = (PFEntry >> 0) & ((1 << 13)-1); 6002 6003 enum { 6004 OP_COPY = 0, // Copy, used for things like <u,u,u,3> to say it is <0,1,2,3> 6005 OP_VREV, 6006 OP_VDUP0, 6007 OP_VDUP1, 6008 OP_VDUP2, 6009 OP_VDUP3, 6010 OP_VEXT1, 6011 OP_VEXT2, 6012 OP_VEXT3, 6013 OP_VUZPL, // VUZP, left result 6014 OP_VUZPR, // VUZP, right result 6015 OP_VZIPL, // VZIP, left result 6016 OP_VZIPR, // VZIP, right result 6017 OP_VTRNL, // VTRN, left result 6018 OP_VTRNR // VTRN, right result 6019 }; 6020 6021 if (OpNum == OP_COPY) { 6022 if (LHSID == (1*9+2)*9+3) return LHS; 6023 assert(LHSID == ((4*9+5)*9+6)*9+7 && "Illegal OP_COPY!"); 6024 return RHS; 6025 } 6026 6027 SDValue OpLHS, OpRHS; 6028 OpLHS = GeneratePerfectShuffle(PerfectShuffleTable[LHSID], LHS, RHS, DAG, dl); 6029 OpRHS = GeneratePerfectShuffle(PerfectShuffleTable[RHSID], LHS, RHS, DAG, dl); 6030 EVT VT = OpLHS.getValueType(); 6031 6032 switch (OpNum) { 6033 default: llvm_unreachable("Unknown shuffle opcode!"); 6034 case OP_VREV: 6035 // VREV divides the vector in half and swaps within the half. 6036 if (VT.getVectorElementType() == MVT::i32 || 6037 VT.getVectorElementType() == MVT::f32) 6038 return DAG.getNode(ARMISD::VREV64, dl, VT, OpLHS); 6039 // vrev <4 x i16> -> VREV32 6040 if (VT.getVectorElementType() == MVT::i16) 6041 return DAG.getNode(ARMISD::VREV32, dl, VT, OpLHS); 6042 // vrev <4 x i8> -> VREV16 6043 assert(VT.getVectorElementType() == MVT::i8); 6044 return DAG.getNode(ARMISD::VREV16, dl, VT, OpLHS); 6045 case OP_VDUP0: 6046 case OP_VDUP1: 6047 case OP_VDUP2: 6048 case OP_VDUP3: 6049 return DAG.getNode(ARMISD::VDUPLANE, dl, VT, 6050 OpLHS, DAG.getConstant(OpNum-OP_VDUP0, dl, MVT::i32)); 6051 case OP_VEXT1: 6052 case OP_VEXT2: 6053 case OP_VEXT3: 6054 return DAG.getNode(ARMISD::VEXT, dl, VT, 6055 OpLHS, OpRHS, 6056 DAG.getConstant(OpNum - OP_VEXT1 + 1, dl, MVT::i32)); 6057 case OP_VUZPL: 6058 case OP_VUZPR: 6059 return DAG.getNode(ARMISD::VUZP, dl, DAG.getVTList(VT, VT), 6060 OpLHS, OpRHS).getValue(OpNum-OP_VUZPL); 6061 case OP_VZIPL: 6062 case OP_VZIPR: 6063 return DAG.getNode(ARMISD::VZIP, dl, DAG.getVTList(VT, VT), 6064 OpLHS, OpRHS).getValue(OpNum-OP_VZIPL); 6065 case OP_VTRNL: 6066 case OP_VTRNR: 6067 return DAG.getNode(ARMISD::VTRN, dl, DAG.getVTList(VT, VT), 6068 OpLHS, OpRHS).getValue(OpNum-OP_VTRNL); 6069 } 6070 } 6071 6072 static SDValue LowerVECTOR_SHUFFLEv8i8(SDValue Op, 6073 ArrayRef<int> ShuffleMask, 6074 SelectionDAG &DAG) { 6075 // Check to see if we can use the VTBL instruction. 6076 SDValue V1 = Op.getOperand(0); 6077 SDValue V2 = Op.getOperand(1); 6078 SDLoc DL(Op); 6079 6080 SmallVector<SDValue, 8> VTBLMask; 6081 for (ArrayRef<int>::iterator 6082 I = ShuffleMask.begin(), E = ShuffleMask.end(); I != E; ++I) 6083 VTBLMask.push_back(DAG.getConstant(*I, DL, MVT::i32)); 6084 6085 if (V2.getNode()->isUndef()) 6086 return DAG.getNode(ARMISD::VTBL1, DL, MVT::v8i8, V1, 6087 DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v8i8, VTBLMask)); 6088 6089 return DAG.getNode(ARMISD::VTBL2, DL, MVT::v8i8, V1, V2, 6090 DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v8i8, VTBLMask)); 6091 } 6092 6093 static SDValue LowerReverse_VECTOR_SHUFFLEv16i8_v8i16(SDValue Op, 6094 SelectionDAG &DAG) { 6095 SDLoc DL(Op); 6096 SDValue OpLHS = Op.getOperand(0); 6097 EVT VT = OpLHS.getValueType(); 6098 6099 assert((VT == MVT::v8i16 || VT == MVT::v16i8) && 6100 "Expect an v8i16/v16i8 type"); 6101 OpLHS = DAG.getNode(ARMISD::VREV64, DL, VT, OpLHS); 6102 // For a v16i8 type: After the VREV, we have got <8, ...15, 8, ..., 0>. Now, 6103 // extract the first 8 bytes into the top double word and the last 8 bytes 6104 // into the bottom double word. The v8i16 case is similar. 6105 unsigned ExtractNum = (VT == MVT::v16i8) ? 8 : 4; 6106 return DAG.getNode(ARMISD::VEXT, DL, VT, OpLHS, OpLHS, 6107 DAG.getConstant(ExtractNum, DL, MVT::i32)); 6108 } 6109 6110 static SDValue LowerVECTOR_SHUFFLE(SDValue Op, SelectionDAG &DAG) { 6111 SDValue V1 = Op.getOperand(0); 6112 SDValue V2 = Op.getOperand(1); 6113 SDLoc dl(Op); 6114 EVT VT = Op.getValueType(); 6115 ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(Op.getNode()); 6116 6117 // Convert shuffles that are directly supported on NEON to target-specific 6118 // DAG nodes, instead of keeping them as shuffles and matching them again 6119 // during code selection. This is more efficient and avoids the possibility 6120 // of inconsistencies between legalization and selection. 6121 // FIXME: floating-point vectors should be canonicalized to integer vectors 6122 // of the same time so that they get CSEd properly. 6123 ArrayRef<int> ShuffleMask = SVN->getMask(); 6124 6125 unsigned EltSize = VT.getVectorElementType().getSizeInBits(); 6126 if (EltSize <= 32) { 6127 if (ShuffleVectorSDNode::isSplatMask(&ShuffleMask[0], VT)) { 6128 int Lane = SVN->getSplatIndex(); 6129 // If this is undef splat, generate it via "just" vdup, if possible. 6130 if (Lane == -1) Lane = 0; 6131 6132 // Test if V1 is a SCALAR_TO_VECTOR. 6133 if (Lane == 0 && V1.getOpcode() == ISD::SCALAR_TO_VECTOR) { 6134 return DAG.getNode(ARMISD::VDUP, dl, VT, V1.getOperand(0)); 6135 } 6136 // Test if V1 is a BUILD_VECTOR which is equivalent to a SCALAR_TO_VECTOR 6137 // (and probably will turn into a SCALAR_TO_VECTOR once legalization 6138 // reaches it). 6139 if (Lane == 0 && V1.getOpcode() == ISD::BUILD_VECTOR && 6140 !isa<ConstantSDNode>(V1.getOperand(0))) { 6141 bool IsScalarToVector = true; 6142 for (unsigned i = 1, e = V1.getNumOperands(); i != e; ++i) 6143 if (!V1.getOperand(i).isUndef()) { 6144 IsScalarToVector = false; 6145 break; 6146 } 6147 if (IsScalarToVector) 6148 return DAG.getNode(ARMISD::VDUP, dl, VT, V1.getOperand(0)); 6149 } 6150 return DAG.getNode(ARMISD::VDUPLANE, dl, VT, V1, 6151 DAG.getConstant(Lane, dl, MVT::i32)); 6152 } 6153 6154 bool ReverseVEXT; 6155 unsigned Imm; 6156 if (isVEXTMask(ShuffleMask, VT, ReverseVEXT, Imm)) { 6157 if (ReverseVEXT) 6158 std::swap(V1, V2); 6159 return DAG.getNode(ARMISD::VEXT, dl, VT, V1, V2, 6160 DAG.getConstant(Imm, dl, MVT::i32)); 6161 } 6162 6163 if (isVREVMask(ShuffleMask, VT, 64)) 6164 return DAG.getNode(ARMISD::VREV64, dl, VT, V1); 6165 if (isVREVMask(ShuffleMask, VT, 32)) 6166 return DAG.getNode(ARMISD::VREV32, dl, VT, V1); 6167 if (isVREVMask(ShuffleMask, VT, 16)) 6168 return DAG.getNode(ARMISD::VREV16, dl, VT, V1); 6169 6170 if (V2->isUndef() && isSingletonVEXTMask(ShuffleMask, VT, Imm)) { 6171 return DAG.getNode(ARMISD::VEXT, dl, VT, V1, V1, 6172 DAG.getConstant(Imm, dl, MVT::i32)); 6173 } 6174 6175 // Check for Neon shuffles that modify both input vectors in place. 6176 // If both results are used, i.e., if there are two shuffles with the same 6177 // source operands and with masks corresponding to both results of one of 6178 // these operations, DAG memoization will ensure that a single node is 6179 // used for both shuffles. 6180 unsigned WhichResult; 6181 bool isV_UNDEF; 6182 if (unsigned ShuffleOpc = isNEONTwoResultShuffleMask( 6183 ShuffleMask, VT, WhichResult, isV_UNDEF)) { 6184 if (isV_UNDEF) 6185 V2 = V1; 6186 return DAG.getNode(ShuffleOpc, dl, DAG.getVTList(VT, VT), V1, V2) 6187 .getValue(WhichResult); 6188 } 6189 6190 // Also check for these shuffles through CONCAT_VECTORS: we canonicalize 6191 // shuffles that produce a result larger than their operands with: 6192 // shuffle(concat(v1, undef), concat(v2, undef)) 6193 // -> 6194 // shuffle(concat(v1, v2), undef) 6195 // because we can access quad vectors (see PerformVECTOR_SHUFFLECombine). 6196 // 6197 // This is useful in the general case, but there are special cases where 6198 // native shuffles produce larger results: the two-result ops. 6199 // 6200 // Look through the concat when lowering them: 6201 // shuffle(concat(v1, v2), undef) 6202 // -> 6203 // concat(VZIP(v1, v2):0, :1) 6204 // 6205 if (V1->getOpcode() == ISD::CONCAT_VECTORS && V2->isUndef()) { 6206 SDValue SubV1 = V1->getOperand(0); 6207 SDValue SubV2 = V1->getOperand(1); 6208 EVT SubVT = SubV1.getValueType(); 6209 6210 // We expect these to have been canonicalized to -1. 6211 assert(std::all_of(ShuffleMask.begin(), ShuffleMask.end(), [&](int i) { 6212 return i < (int)VT.getVectorNumElements(); 6213 }) && "Unexpected shuffle index into UNDEF operand!"); 6214 6215 if (unsigned ShuffleOpc = isNEONTwoResultShuffleMask( 6216 ShuffleMask, SubVT, WhichResult, isV_UNDEF)) { 6217 if (isV_UNDEF) 6218 SubV2 = SubV1; 6219 assert((WhichResult == 0) && 6220 "In-place shuffle of concat can only have one result!"); 6221 SDValue Res = DAG.getNode(ShuffleOpc, dl, DAG.getVTList(SubVT, SubVT), 6222 SubV1, SubV2); 6223 return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, Res.getValue(0), 6224 Res.getValue(1)); 6225 } 6226 } 6227 } 6228 6229 // If the shuffle is not directly supported and it has 4 elements, use 6230 // the PerfectShuffle-generated table to synthesize it from other shuffles. 6231 unsigned NumElts = VT.getVectorNumElements(); 6232 if (NumElts == 4) { 6233 unsigned PFIndexes[4]; 6234 for (unsigned i = 0; i != 4; ++i) { 6235 if (ShuffleMask[i] < 0) 6236 PFIndexes[i] = 8; 6237 else 6238 PFIndexes[i] = ShuffleMask[i]; 6239 } 6240 6241 // Compute the index in the perfect shuffle table. 6242 unsigned PFTableIndex = 6243 PFIndexes[0]*9*9*9+PFIndexes[1]*9*9+PFIndexes[2]*9+PFIndexes[3]; 6244 unsigned PFEntry = PerfectShuffleTable[PFTableIndex]; 6245 unsigned Cost = (PFEntry >> 30); 6246 6247 if (Cost <= 4) 6248 return GeneratePerfectShuffle(PFEntry, V1, V2, DAG, dl); 6249 } 6250 6251 // Implement shuffles with 32- or 64-bit elements as ARMISD::BUILD_VECTORs. 6252 if (EltSize >= 32) { 6253 // Do the expansion with floating-point types, since that is what the VFP 6254 // registers are defined to use, and since i64 is not legal. 6255 EVT EltVT = EVT::getFloatingPointVT(EltSize); 6256 EVT VecVT = EVT::getVectorVT(*DAG.getContext(), EltVT, NumElts); 6257 V1 = DAG.getNode(ISD::BITCAST, dl, VecVT, V1); 6258 V2 = DAG.getNode(ISD::BITCAST, dl, VecVT, V2); 6259 SmallVector<SDValue, 8> Ops; 6260 for (unsigned i = 0; i < NumElts; ++i) { 6261 if (ShuffleMask[i] < 0) 6262 Ops.push_back(DAG.getUNDEF(EltVT)); 6263 else 6264 Ops.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, EltVT, 6265 ShuffleMask[i] < (int)NumElts ? V1 : V2, 6266 DAG.getConstant(ShuffleMask[i] & (NumElts-1), 6267 dl, MVT::i32))); 6268 } 6269 SDValue Val = DAG.getNode(ARMISD::BUILD_VECTOR, dl, VecVT, Ops); 6270 return DAG.getNode(ISD::BITCAST, dl, VT, Val); 6271 } 6272 6273 if ((VT == MVT::v8i16 || VT == MVT::v16i8) && isReverseMask(ShuffleMask, VT)) 6274 return LowerReverse_VECTOR_SHUFFLEv16i8_v8i16(Op, DAG); 6275 6276 if (VT == MVT::v8i8) 6277 if (SDValue NewOp = LowerVECTOR_SHUFFLEv8i8(Op, ShuffleMask, DAG)) 6278 return NewOp; 6279 6280 return SDValue(); 6281 } 6282 6283 static SDValue LowerINSERT_VECTOR_ELT(SDValue Op, SelectionDAG &DAG) { 6284 // INSERT_VECTOR_ELT is legal only for immediate indexes. 6285 SDValue Lane = Op.getOperand(2); 6286 if (!isa<ConstantSDNode>(Lane)) 6287 return SDValue(); 6288 6289 return Op; 6290 } 6291 6292 static SDValue LowerEXTRACT_VECTOR_ELT(SDValue Op, SelectionDAG &DAG) { 6293 // EXTRACT_VECTOR_ELT is legal only for immediate indexes. 6294 SDValue Lane = Op.getOperand(1); 6295 if (!isa<ConstantSDNode>(Lane)) 6296 return SDValue(); 6297 6298 SDValue Vec = Op.getOperand(0); 6299 if (Op.getValueType() == MVT::i32 && 6300 Vec.getValueType().getVectorElementType().getSizeInBits() < 32) { 6301 SDLoc dl(Op); 6302 return DAG.getNode(ARMISD::VGETLANEu, dl, MVT::i32, Vec, Lane); 6303 } 6304 6305 return Op; 6306 } 6307 6308 static SDValue LowerCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG) { 6309 // The only time a CONCAT_VECTORS operation can have legal types is when 6310 // two 64-bit vectors are concatenated to a 128-bit vector. 6311 assert(Op.getValueType().is128BitVector() && Op.getNumOperands() == 2 && 6312 "unexpected CONCAT_VECTORS"); 6313 SDLoc dl(Op); 6314 SDValue Val = DAG.getUNDEF(MVT::v2f64); 6315 SDValue Op0 = Op.getOperand(0); 6316 SDValue Op1 = Op.getOperand(1); 6317 if (!Op0.isUndef()) 6318 Val = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Val, 6319 DAG.getNode(ISD::BITCAST, dl, MVT::f64, Op0), 6320 DAG.getIntPtrConstant(0, dl)); 6321 if (!Op1.isUndef()) 6322 Val = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Val, 6323 DAG.getNode(ISD::BITCAST, dl, MVT::f64, Op1), 6324 DAG.getIntPtrConstant(1, dl)); 6325 return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Val); 6326 } 6327 6328 /// isExtendedBUILD_VECTOR - Check if N is a constant BUILD_VECTOR where each 6329 /// element has been zero/sign-extended, depending on the isSigned parameter, 6330 /// from an integer type half its size. 6331 static bool isExtendedBUILD_VECTOR(SDNode *N, SelectionDAG &DAG, 6332 bool isSigned) { 6333 // A v2i64 BUILD_VECTOR will have been legalized to a BITCAST from v4i32. 6334 EVT VT = N->getValueType(0); 6335 if (VT == MVT::v2i64 && N->getOpcode() == ISD::BITCAST) { 6336 SDNode *BVN = N->getOperand(0).getNode(); 6337 if (BVN->getValueType(0) != MVT::v4i32 || 6338 BVN->getOpcode() != ISD::BUILD_VECTOR) 6339 return false; 6340 unsigned LoElt = DAG.getDataLayout().isBigEndian() ? 1 : 0; 6341 unsigned HiElt = 1 - LoElt; 6342 ConstantSDNode *Lo0 = dyn_cast<ConstantSDNode>(BVN->getOperand(LoElt)); 6343 ConstantSDNode *Hi0 = dyn_cast<ConstantSDNode>(BVN->getOperand(HiElt)); 6344 ConstantSDNode *Lo1 = dyn_cast<ConstantSDNode>(BVN->getOperand(LoElt+2)); 6345 ConstantSDNode *Hi1 = dyn_cast<ConstantSDNode>(BVN->getOperand(HiElt+2)); 6346 if (!Lo0 || !Hi0 || !Lo1 || !Hi1) 6347 return false; 6348 if (isSigned) { 6349 if (Hi0->getSExtValue() == Lo0->getSExtValue() >> 32 && 6350 Hi1->getSExtValue() == Lo1->getSExtValue() >> 32) 6351 return true; 6352 } else { 6353 if (Hi0->isNullValue() && Hi1->isNullValue()) 6354 return true; 6355 } 6356 return false; 6357 } 6358 6359 if (N->getOpcode() != ISD::BUILD_VECTOR) 6360 return false; 6361 6362 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) { 6363 SDNode *Elt = N->getOperand(i).getNode(); 6364 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Elt)) { 6365 unsigned EltSize = VT.getVectorElementType().getSizeInBits(); 6366 unsigned HalfSize = EltSize / 2; 6367 if (isSigned) { 6368 if (!isIntN(HalfSize, C->getSExtValue())) 6369 return false; 6370 } else { 6371 if (!isUIntN(HalfSize, C->getZExtValue())) 6372 return false; 6373 } 6374 continue; 6375 } 6376 return false; 6377 } 6378 6379 return true; 6380 } 6381 6382 /// isSignExtended - Check if a node is a vector value that is sign-extended 6383 /// or a constant BUILD_VECTOR with sign-extended elements. 6384 static bool isSignExtended(SDNode *N, SelectionDAG &DAG) { 6385 if (N->getOpcode() == ISD::SIGN_EXTEND || ISD::isSEXTLoad(N)) 6386 return true; 6387 if (isExtendedBUILD_VECTOR(N, DAG, true)) 6388 return true; 6389 return false; 6390 } 6391 6392 /// isZeroExtended - Check if a node is a vector value that is zero-extended 6393 /// or a constant BUILD_VECTOR with zero-extended elements. 6394 static bool isZeroExtended(SDNode *N, SelectionDAG &DAG) { 6395 if (N->getOpcode() == ISD::ZERO_EXTEND || ISD::isZEXTLoad(N)) 6396 return true; 6397 if (isExtendedBUILD_VECTOR(N, DAG, false)) 6398 return true; 6399 return false; 6400 } 6401 6402 static EVT getExtensionTo64Bits(const EVT &OrigVT) { 6403 if (OrigVT.getSizeInBits() >= 64) 6404 return OrigVT; 6405 6406 assert(OrigVT.isSimple() && "Expecting a simple value type"); 6407 6408 MVT::SimpleValueType OrigSimpleTy = OrigVT.getSimpleVT().SimpleTy; 6409 switch (OrigSimpleTy) { 6410 default: llvm_unreachable("Unexpected Vector Type"); 6411 case MVT::v2i8: 6412 case MVT::v2i16: 6413 return MVT::v2i32; 6414 case MVT::v4i8: 6415 return MVT::v4i16; 6416 } 6417 } 6418 6419 /// AddRequiredExtensionForVMULL - Add a sign/zero extension to extend the total 6420 /// value size to 64 bits. We need a 64-bit D register as an operand to VMULL. 6421 /// We insert the required extension here to get the vector to fill a D register. 6422 static SDValue AddRequiredExtensionForVMULL(SDValue N, SelectionDAG &DAG, 6423 const EVT &OrigTy, 6424 const EVT &ExtTy, 6425 unsigned ExtOpcode) { 6426 // The vector originally had a size of OrigTy. It was then extended to ExtTy. 6427 // We expect the ExtTy to be 128-bits total. If the OrigTy is less than 6428 // 64-bits we need to insert a new extension so that it will be 64-bits. 6429 assert(ExtTy.is128BitVector() && "Unexpected extension size"); 6430 if (OrigTy.getSizeInBits() >= 64) 6431 return N; 6432 6433 // Must extend size to at least 64 bits to be used as an operand for VMULL. 6434 EVT NewVT = getExtensionTo64Bits(OrigTy); 6435 6436 return DAG.getNode(ExtOpcode, SDLoc(N), NewVT, N); 6437 } 6438 6439 /// SkipLoadExtensionForVMULL - return a load of the original vector size that 6440 /// does not do any sign/zero extension. If the original vector is less 6441 /// than 64 bits, an appropriate extension will be added after the load to 6442 /// reach a total size of 64 bits. We have to add the extension separately 6443 /// because ARM does not have a sign/zero extending load for vectors. 6444 static SDValue SkipLoadExtensionForVMULL(LoadSDNode *LD, SelectionDAG& DAG) { 6445 EVT ExtendedTy = getExtensionTo64Bits(LD->getMemoryVT()); 6446 6447 // The load already has the right type. 6448 if (ExtendedTy == LD->getMemoryVT()) 6449 return DAG.getLoad(LD->getMemoryVT(), SDLoc(LD), LD->getChain(), 6450 LD->getBasePtr(), LD->getPointerInfo(), LD->isVolatile(), 6451 LD->isNonTemporal(), LD->isInvariant(), 6452 LD->getAlignment()); 6453 6454 // We need to create a zextload/sextload. We cannot just create a load 6455 // followed by a zext/zext node because LowerMUL is also run during normal 6456 // operation legalization where we can't create illegal types. 6457 return DAG.getExtLoad(LD->getExtensionType(), SDLoc(LD), ExtendedTy, 6458 LD->getChain(), LD->getBasePtr(), LD->getPointerInfo(), 6459 LD->getMemoryVT(), LD->isVolatile(), LD->isInvariant(), 6460 LD->isNonTemporal(), LD->getAlignment()); 6461 } 6462 6463 /// SkipExtensionForVMULL - For a node that is a SIGN_EXTEND, ZERO_EXTEND, 6464 /// extending load, or BUILD_VECTOR with extended elements, return the 6465 /// unextended value. The unextended vector should be 64 bits so that it can 6466 /// be used as an operand to a VMULL instruction. If the original vector size 6467 /// before extension is less than 64 bits we add a an extension to resize 6468 /// the vector to 64 bits. 6469 static SDValue SkipExtensionForVMULL(SDNode *N, SelectionDAG &DAG) { 6470 if (N->getOpcode() == ISD::SIGN_EXTEND || N->getOpcode() == ISD::ZERO_EXTEND) 6471 return AddRequiredExtensionForVMULL(N->getOperand(0), DAG, 6472 N->getOperand(0)->getValueType(0), 6473 N->getValueType(0), 6474 N->getOpcode()); 6475 6476 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) 6477 return SkipLoadExtensionForVMULL(LD, DAG); 6478 6479 // Otherwise, the value must be a BUILD_VECTOR. For v2i64, it will 6480 // have been legalized as a BITCAST from v4i32. 6481 if (N->getOpcode() == ISD::BITCAST) { 6482 SDNode *BVN = N->getOperand(0).getNode(); 6483 assert(BVN->getOpcode() == ISD::BUILD_VECTOR && 6484 BVN->getValueType(0) == MVT::v4i32 && "expected v4i32 BUILD_VECTOR"); 6485 unsigned LowElt = DAG.getDataLayout().isBigEndian() ? 1 : 0; 6486 return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), MVT::v2i32, 6487 BVN->getOperand(LowElt), BVN->getOperand(LowElt+2)); 6488 } 6489 // Construct a new BUILD_VECTOR with elements truncated to half the size. 6490 assert(N->getOpcode() == ISD::BUILD_VECTOR && "expected BUILD_VECTOR"); 6491 EVT VT = N->getValueType(0); 6492 unsigned EltSize = VT.getVectorElementType().getSizeInBits() / 2; 6493 unsigned NumElts = VT.getVectorNumElements(); 6494 MVT TruncVT = MVT::getIntegerVT(EltSize); 6495 SmallVector<SDValue, 8> Ops; 6496 SDLoc dl(N); 6497 for (unsigned i = 0; i != NumElts; ++i) { 6498 ConstantSDNode *C = cast<ConstantSDNode>(N->getOperand(i)); 6499 const APInt &CInt = C->getAPIntValue(); 6500 // Element types smaller than 32 bits are not legal, so use i32 elements. 6501 // The values are implicitly truncated so sext vs. zext doesn't matter. 6502 Ops.push_back(DAG.getConstant(CInt.zextOrTrunc(32), dl, MVT::i32)); 6503 } 6504 return DAG.getNode(ISD::BUILD_VECTOR, dl, 6505 MVT::getVectorVT(TruncVT, NumElts), Ops); 6506 } 6507 6508 static bool isAddSubSExt(SDNode *N, SelectionDAG &DAG) { 6509 unsigned Opcode = N->getOpcode(); 6510 if (Opcode == ISD::ADD || Opcode == ISD::SUB) { 6511 SDNode *N0 = N->getOperand(0).getNode(); 6512 SDNode *N1 = N->getOperand(1).getNode(); 6513 return N0->hasOneUse() && N1->hasOneUse() && 6514 isSignExtended(N0, DAG) && isSignExtended(N1, DAG); 6515 } 6516 return false; 6517 } 6518 6519 static bool isAddSubZExt(SDNode *N, SelectionDAG &DAG) { 6520 unsigned Opcode = N->getOpcode(); 6521 if (Opcode == ISD::ADD || Opcode == ISD::SUB) { 6522 SDNode *N0 = N->getOperand(0).getNode(); 6523 SDNode *N1 = N->getOperand(1).getNode(); 6524 return N0->hasOneUse() && N1->hasOneUse() && 6525 isZeroExtended(N0, DAG) && isZeroExtended(N1, DAG); 6526 } 6527 return false; 6528 } 6529 6530 static SDValue LowerMUL(SDValue Op, SelectionDAG &DAG) { 6531 // Multiplications are only custom-lowered for 128-bit vectors so that 6532 // VMULL can be detected. Otherwise v2i64 multiplications are not legal. 6533 EVT VT = Op.getValueType(); 6534 assert(VT.is128BitVector() && VT.isInteger() && 6535 "unexpected type for custom-lowering ISD::MUL"); 6536 SDNode *N0 = Op.getOperand(0).getNode(); 6537 SDNode *N1 = Op.getOperand(1).getNode(); 6538 unsigned NewOpc = 0; 6539 bool isMLA = false; 6540 bool isN0SExt = isSignExtended(N0, DAG); 6541 bool isN1SExt = isSignExtended(N1, DAG); 6542 if (isN0SExt && isN1SExt) 6543 NewOpc = ARMISD::VMULLs; 6544 else { 6545 bool isN0ZExt = isZeroExtended(N0, DAG); 6546 bool isN1ZExt = isZeroExtended(N1, DAG); 6547 if (isN0ZExt && isN1ZExt) 6548 NewOpc = ARMISD::VMULLu; 6549 else if (isN1SExt || isN1ZExt) { 6550 // Look for (s/zext A + s/zext B) * (s/zext C). We want to turn these 6551 // into (s/zext A * s/zext C) + (s/zext B * s/zext C) 6552 if (isN1SExt && isAddSubSExt(N0, DAG)) { 6553 NewOpc = ARMISD::VMULLs; 6554 isMLA = true; 6555 } else if (isN1ZExt && isAddSubZExt(N0, DAG)) { 6556 NewOpc = ARMISD::VMULLu; 6557 isMLA = true; 6558 } else if (isN0ZExt && isAddSubZExt(N1, DAG)) { 6559 std::swap(N0, N1); 6560 NewOpc = ARMISD::VMULLu; 6561 isMLA = true; 6562 } 6563 } 6564 6565 if (!NewOpc) { 6566 if (VT == MVT::v2i64) 6567 // Fall through to expand this. It is not legal. 6568 return SDValue(); 6569 else 6570 // Other vector multiplications are legal. 6571 return Op; 6572 } 6573 } 6574 6575 // Legalize to a VMULL instruction. 6576 SDLoc DL(Op); 6577 SDValue Op0; 6578 SDValue Op1 = SkipExtensionForVMULL(N1, DAG); 6579 if (!isMLA) { 6580 Op0 = SkipExtensionForVMULL(N0, DAG); 6581 assert(Op0.getValueType().is64BitVector() && 6582 Op1.getValueType().is64BitVector() && 6583 "unexpected types for extended operands to VMULL"); 6584 return DAG.getNode(NewOpc, DL, VT, Op0, Op1); 6585 } 6586 6587 // Optimizing (zext A + zext B) * C, to (VMULL A, C) + (VMULL B, C) during 6588 // isel lowering to take advantage of no-stall back to back vmul + vmla. 6589 // vmull q0, d4, d6 6590 // vmlal q0, d5, d6 6591 // is faster than 6592 // vaddl q0, d4, d5 6593 // vmovl q1, d6 6594 // vmul q0, q0, q1 6595 SDValue N00 = SkipExtensionForVMULL(N0->getOperand(0).getNode(), DAG); 6596 SDValue N01 = SkipExtensionForVMULL(N0->getOperand(1).getNode(), DAG); 6597 EVT Op1VT = Op1.getValueType(); 6598 return DAG.getNode(N0->getOpcode(), DL, VT, 6599 DAG.getNode(NewOpc, DL, VT, 6600 DAG.getNode(ISD::BITCAST, DL, Op1VT, N00), Op1), 6601 DAG.getNode(NewOpc, DL, VT, 6602 DAG.getNode(ISD::BITCAST, DL, Op1VT, N01), Op1)); 6603 } 6604 6605 static SDValue 6606 LowerSDIV_v4i8(SDValue X, SDValue Y, SDLoc dl, SelectionDAG &DAG) { 6607 // TODO: Should this propagate fast-math-flags? 6608 6609 // Convert to float 6610 // float4 xf = vcvt_f32_s32(vmovl_s16(a.lo)); 6611 // float4 yf = vcvt_f32_s32(vmovl_s16(b.lo)); 6612 X = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, X); 6613 Y = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, Y); 6614 X = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, X); 6615 Y = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, Y); 6616 // Get reciprocal estimate. 6617 // float4 recip = vrecpeq_f32(yf); 6618 Y = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32, 6619 DAG.getConstant(Intrinsic::arm_neon_vrecpe, dl, MVT::i32), 6620 Y); 6621 // Because char has a smaller range than uchar, we can actually get away 6622 // without any newton steps. This requires that we use a weird bias 6623 // of 0xb000, however (again, this has been exhaustively tested). 6624 // float4 result = as_float4(as_int4(xf*recip) + 0xb000); 6625 X = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, X, Y); 6626 X = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, X); 6627 Y = DAG.getConstant(0xb000, dl, MVT::v4i32); 6628 X = DAG.getNode(ISD::ADD, dl, MVT::v4i32, X, Y); 6629 X = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, X); 6630 // Convert back to short. 6631 X = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::v4i32, X); 6632 X = DAG.getNode(ISD::TRUNCATE, dl, MVT::v4i16, X); 6633 return X; 6634 } 6635 6636 static SDValue 6637 LowerSDIV_v4i16(SDValue N0, SDValue N1, SDLoc dl, SelectionDAG &DAG) { 6638 // TODO: Should this propagate fast-math-flags? 6639 6640 SDValue N2; 6641 // Convert to float. 6642 // float4 yf = vcvt_f32_s32(vmovl_s16(y)); 6643 // float4 xf = vcvt_f32_s32(vmovl_s16(x)); 6644 N0 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, N0); 6645 N1 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, N1); 6646 N0 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N0); 6647 N1 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N1); 6648 6649 // Use reciprocal estimate and one refinement step. 6650 // float4 recip = vrecpeq_f32(yf); 6651 // recip *= vrecpsq_f32(yf, recip); 6652 N2 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32, 6653 DAG.getConstant(Intrinsic::arm_neon_vrecpe, dl, MVT::i32), 6654 N1); 6655 N1 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32, 6656 DAG.getConstant(Intrinsic::arm_neon_vrecps, dl, MVT::i32), 6657 N1, N2); 6658 N2 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N1, N2); 6659 // Because short has a smaller range than ushort, we can actually get away 6660 // with only a single newton step. This requires that we use a weird bias 6661 // of 89, however (again, this has been exhaustively tested). 6662 // float4 result = as_float4(as_int4(xf*recip) + 0x89); 6663 N0 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N0, N2); 6664 N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, N0); 6665 N1 = DAG.getConstant(0x89, dl, MVT::v4i32); 6666 N0 = DAG.getNode(ISD::ADD, dl, MVT::v4i32, N0, N1); 6667 N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, N0); 6668 // Convert back to integer and return. 6669 // return vmovn_s32(vcvt_s32_f32(result)); 6670 N0 = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::v4i32, N0); 6671 N0 = DAG.getNode(ISD::TRUNCATE, dl, MVT::v4i16, N0); 6672 return N0; 6673 } 6674 6675 static SDValue LowerSDIV(SDValue Op, SelectionDAG &DAG) { 6676 EVT VT = Op.getValueType(); 6677 assert((VT == MVT::v4i16 || VT == MVT::v8i8) && 6678 "unexpected type for custom-lowering ISD::SDIV"); 6679 6680 SDLoc dl(Op); 6681 SDValue N0 = Op.getOperand(0); 6682 SDValue N1 = Op.getOperand(1); 6683 SDValue N2, N3; 6684 6685 if (VT == MVT::v8i8) { 6686 N0 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v8i16, N0); 6687 N1 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v8i16, N1); 6688 6689 N2 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0, 6690 DAG.getIntPtrConstant(4, dl)); 6691 N3 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1, 6692 DAG.getIntPtrConstant(4, dl)); 6693 N0 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0, 6694 DAG.getIntPtrConstant(0, dl)); 6695 N1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1, 6696 DAG.getIntPtrConstant(0, dl)); 6697 6698 N0 = LowerSDIV_v4i8(N0, N1, dl, DAG); // v4i16 6699 N2 = LowerSDIV_v4i8(N2, N3, dl, DAG); // v4i16 6700 6701 N0 = DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v8i16, N0, N2); 6702 N0 = LowerCONCAT_VECTORS(N0, DAG); 6703 6704 N0 = DAG.getNode(ISD::TRUNCATE, dl, MVT::v8i8, N0); 6705 return N0; 6706 } 6707 return LowerSDIV_v4i16(N0, N1, dl, DAG); 6708 } 6709 6710 static SDValue LowerUDIV(SDValue Op, SelectionDAG &DAG) { 6711 // TODO: Should this propagate fast-math-flags? 6712 EVT VT = Op.getValueType(); 6713 assert((VT == MVT::v4i16 || VT == MVT::v8i8) && 6714 "unexpected type for custom-lowering ISD::UDIV"); 6715 6716 SDLoc dl(Op); 6717 SDValue N0 = Op.getOperand(0); 6718 SDValue N1 = Op.getOperand(1); 6719 SDValue N2, N3; 6720 6721 if (VT == MVT::v8i8) { 6722 N0 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v8i16, N0); 6723 N1 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v8i16, N1); 6724 6725 N2 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0, 6726 DAG.getIntPtrConstant(4, dl)); 6727 N3 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1, 6728 DAG.getIntPtrConstant(4, dl)); 6729 N0 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0, 6730 DAG.getIntPtrConstant(0, dl)); 6731 N1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1, 6732 DAG.getIntPtrConstant(0, dl)); 6733 6734 N0 = LowerSDIV_v4i16(N0, N1, dl, DAG); // v4i16 6735 N2 = LowerSDIV_v4i16(N2, N3, dl, DAG); // v4i16 6736 6737 N0 = DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v8i16, N0, N2); 6738 N0 = LowerCONCAT_VECTORS(N0, DAG); 6739 6740 N0 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v8i8, 6741 DAG.getConstant(Intrinsic::arm_neon_vqmovnsu, dl, 6742 MVT::i32), 6743 N0); 6744 return N0; 6745 } 6746 6747 // v4i16 sdiv ... Convert to float. 6748 // float4 yf = vcvt_f32_s32(vmovl_u16(y)); 6749 // float4 xf = vcvt_f32_s32(vmovl_u16(x)); 6750 N0 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v4i32, N0); 6751 N1 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v4i32, N1); 6752 N0 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N0); 6753 SDValue BN1 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N1); 6754 6755 // Use reciprocal estimate and two refinement steps. 6756 // float4 recip = vrecpeq_f32(yf); 6757 // recip *= vrecpsq_f32(yf, recip); 6758 // recip *= vrecpsq_f32(yf, recip); 6759 N2 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32, 6760 DAG.getConstant(Intrinsic::arm_neon_vrecpe, dl, MVT::i32), 6761 BN1); 6762 N1 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32, 6763 DAG.getConstant(Intrinsic::arm_neon_vrecps, dl, MVT::i32), 6764 BN1, N2); 6765 N2 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N1, N2); 6766 N1 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32, 6767 DAG.getConstant(Intrinsic::arm_neon_vrecps, dl, MVT::i32), 6768 BN1, N2); 6769 N2 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N1, N2); 6770 // Simply multiplying by the reciprocal estimate can leave us a few ulps 6771 // too low, so we add 2 ulps (exhaustive testing shows that this is enough, 6772 // and that it will never cause us to return an answer too large). 6773 // float4 result = as_float4(as_int4(xf*recip) + 2); 6774 N0 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N0, N2); 6775 N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, N0); 6776 N1 = DAG.getConstant(2, dl, MVT::v4i32); 6777 N0 = DAG.getNode(ISD::ADD, dl, MVT::v4i32, N0, N1); 6778 N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, N0); 6779 // Convert back to integer and return. 6780 // return vmovn_u32(vcvt_s32_f32(result)); 6781 N0 = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::v4i32, N0); 6782 N0 = DAG.getNode(ISD::TRUNCATE, dl, MVT::v4i16, N0); 6783 return N0; 6784 } 6785 6786 static SDValue LowerADDC_ADDE_SUBC_SUBE(SDValue Op, SelectionDAG &DAG) { 6787 EVT VT = Op.getNode()->getValueType(0); 6788 SDVTList VTs = DAG.getVTList(VT, MVT::i32); 6789 6790 unsigned Opc; 6791 bool ExtraOp = false; 6792 switch (Op.getOpcode()) { 6793 default: llvm_unreachable("Invalid code"); 6794 case ISD::ADDC: Opc = ARMISD::ADDC; break; 6795 case ISD::ADDE: Opc = ARMISD::ADDE; ExtraOp = true; break; 6796 case ISD::SUBC: Opc = ARMISD::SUBC; break; 6797 case ISD::SUBE: Opc = ARMISD::SUBE; ExtraOp = true; break; 6798 } 6799 6800 if (!ExtraOp) 6801 return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0), 6802 Op.getOperand(1)); 6803 return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0), 6804 Op.getOperand(1), Op.getOperand(2)); 6805 } 6806 6807 SDValue ARMTargetLowering::LowerFSINCOS(SDValue Op, SelectionDAG &DAG) const { 6808 assert(Subtarget->isTargetDarwin()); 6809 6810 // For iOS, we want to call an alternative entry point: __sincos_stret, 6811 // return values are passed via sret. 6812 SDLoc dl(Op); 6813 SDValue Arg = Op.getOperand(0); 6814 EVT ArgVT = Arg.getValueType(); 6815 Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext()); 6816 auto PtrVT = getPointerTy(DAG.getDataLayout()); 6817 6818 MachineFrameInfo *FrameInfo = DAG.getMachineFunction().getFrameInfo(); 6819 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 6820 6821 // Pair of floats / doubles used to pass the result. 6822 Type *RetTy = StructType::get(ArgTy, ArgTy, nullptr); 6823 auto &DL = DAG.getDataLayout(); 6824 6825 ArgListTy Args; 6826 bool ShouldUseSRet = Subtarget->isAPCS_ABI(); 6827 SDValue SRet; 6828 if (ShouldUseSRet) { 6829 // Create stack object for sret. 6830 const uint64_t ByteSize = DL.getTypeAllocSize(RetTy); 6831 const unsigned StackAlign = DL.getPrefTypeAlignment(RetTy); 6832 int FrameIdx = FrameInfo->CreateStackObject(ByteSize, StackAlign, false); 6833 SRet = DAG.getFrameIndex(FrameIdx, TLI.getPointerTy(DL)); 6834 6835 ArgListEntry Entry; 6836 Entry.Node = SRet; 6837 Entry.Ty = RetTy->getPointerTo(); 6838 Entry.isSExt = false; 6839 Entry.isZExt = false; 6840 Entry.isSRet = true; 6841 Args.push_back(Entry); 6842 RetTy = Type::getVoidTy(*DAG.getContext()); 6843 } 6844 6845 ArgListEntry Entry; 6846 Entry.Node = Arg; 6847 Entry.Ty = ArgTy; 6848 Entry.isSExt = false; 6849 Entry.isZExt = false; 6850 Args.push_back(Entry); 6851 6852 const char *LibcallName = 6853 (ArgVT == MVT::f64) ? "__sincos_stret" : "__sincosf_stret"; 6854 RTLIB::Libcall LC = 6855 (ArgVT == MVT::f64) ? RTLIB::SINCOS_F64 : RTLIB::SINCOS_F32; 6856 CallingConv::ID CC = getLibcallCallingConv(LC); 6857 SDValue Callee = DAG.getExternalSymbol(LibcallName, getPointerTy(DL)); 6858 6859 TargetLowering::CallLoweringInfo CLI(DAG); 6860 CLI.setDebugLoc(dl) 6861 .setChain(DAG.getEntryNode()) 6862 .setCallee(CC, RetTy, Callee, std::move(Args), 0) 6863 .setDiscardResult(ShouldUseSRet); 6864 std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI); 6865 6866 if (!ShouldUseSRet) 6867 return CallResult.first; 6868 6869 SDValue LoadSin = DAG.getLoad(ArgVT, dl, CallResult.second, SRet, 6870 MachinePointerInfo(), false, false, false, 0); 6871 6872 // Address of cos field. 6873 SDValue Add = DAG.getNode(ISD::ADD, dl, PtrVT, SRet, 6874 DAG.getIntPtrConstant(ArgVT.getStoreSize(), dl)); 6875 SDValue LoadCos = DAG.getLoad(ArgVT, dl, LoadSin.getValue(1), Add, 6876 MachinePointerInfo(), false, false, false, 0); 6877 6878 SDVTList Tys = DAG.getVTList(ArgVT, ArgVT); 6879 return DAG.getNode(ISD::MERGE_VALUES, dl, Tys, 6880 LoadSin.getValue(0), LoadCos.getValue(0)); 6881 } 6882 6883 SDValue ARMTargetLowering::LowerWindowsDIVLibCall(SDValue Op, SelectionDAG &DAG, 6884 bool Signed, 6885 SDValue &Chain) const { 6886 EVT VT = Op.getValueType(); 6887 assert((VT == MVT::i32 || VT == MVT::i64) && 6888 "unexpected type for custom lowering DIV"); 6889 SDLoc dl(Op); 6890 6891 const auto &DL = DAG.getDataLayout(); 6892 const auto &TLI = DAG.getTargetLoweringInfo(); 6893 6894 const char *Name = nullptr; 6895 if (Signed) 6896 Name = (VT == MVT::i32) ? "__rt_sdiv" : "__rt_sdiv64"; 6897 else 6898 Name = (VT == MVT::i32) ? "__rt_udiv" : "__rt_udiv64"; 6899 6900 SDValue ES = DAG.getExternalSymbol(Name, TLI.getPointerTy(DL)); 6901 6902 ARMTargetLowering::ArgListTy Args; 6903 6904 for (auto AI : {1, 0}) { 6905 ArgListEntry Arg; 6906 Arg.Node = Op.getOperand(AI); 6907 Arg.Ty = Arg.Node.getValueType().getTypeForEVT(*DAG.getContext()); 6908 Args.push_back(Arg); 6909 } 6910 6911 CallLoweringInfo CLI(DAG); 6912 CLI.setDebugLoc(dl) 6913 .setChain(Chain) 6914 .setCallee(CallingConv::ARM_AAPCS_VFP, VT.getTypeForEVT(*DAG.getContext()), 6915 ES, std::move(Args), 0); 6916 6917 return LowerCallTo(CLI).first; 6918 } 6919 6920 SDValue ARMTargetLowering::LowerDIV_Windows(SDValue Op, SelectionDAG &DAG, 6921 bool Signed) const { 6922 assert(Op.getValueType() == MVT::i32 && 6923 "unexpected type for custom lowering DIV"); 6924 SDLoc dl(Op); 6925 6926 SDValue DBZCHK = DAG.getNode(ARMISD::WIN__DBZCHK, dl, MVT::Other, 6927 DAG.getEntryNode(), Op.getOperand(1)); 6928 6929 return LowerWindowsDIVLibCall(Op, DAG, Signed, DBZCHK); 6930 } 6931 6932 void ARMTargetLowering::ExpandDIV_Windows( 6933 SDValue Op, SelectionDAG &DAG, bool Signed, 6934 SmallVectorImpl<SDValue> &Results) const { 6935 const auto &DL = DAG.getDataLayout(); 6936 const auto &TLI = DAG.getTargetLoweringInfo(); 6937 6938 assert(Op.getValueType() == MVT::i64 && 6939 "unexpected type for custom lowering DIV"); 6940 SDLoc dl(Op); 6941 6942 SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, Op.getOperand(1), 6943 DAG.getConstant(0, dl, MVT::i32)); 6944 SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, Op.getOperand(1), 6945 DAG.getConstant(1, dl, MVT::i32)); 6946 SDValue Or = DAG.getNode(ISD::OR, dl, MVT::i32, Lo, Hi); 6947 6948 SDValue DBZCHK = 6949 DAG.getNode(ARMISD::WIN__DBZCHK, dl, MVT::Other, DAG.getEntryNode(), Or); 6950 6951 SDValue Result = LowerWindowsDIVLibCall(Op, DAG, Signed, DBZCHK); 6952 6953 SDValue Lower = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, Result); 6954 SDValue Upper = DAG.getNode(ISD::SRL, dl, MVT::i64, Result, 6955 DAG.getConstant(32, dl, TLI.getPointerTy(DL))); 6956 Upper = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, Upper); 6957 6958 Results.push_back(Lower); 6959 Results.push_back(Upper); 6960 } 6961 6962 static SDValue LowerAtomicLoadStore(SDValue Op, SelectionDAG &DAG) { 6963 // Monotonic load/store is legal for all targets 6964 if (cast<AtomicSDNode>(Op)->getOrdering() <= Monotonic) 6965 return Op; 6966 6967 // Acquire/Release load/store is not legal for targets without a 6968 // dmb or equivalent available. 6969 return SDValue(); 6970 } 6971 6972 static void ReplaceREADCYCLECOUNTER(SDNode *N, 6973 SmallVectorImpl<SDValue> &Results, 6974 SelectionDAG &DAG, 6975 const ARMSubtarget *Subtarget) { 6976 SDLoc DL(N); 6977 // Under Power Management extensions, the cycle-count is: 6978 // mrc p15, #0, <Rt>, c9, c13, #0 6979 SDValue Ops[] = { N->getOperand(0), // Chain 6980 DAG.getConstant(Intrinsic::arm_mrc, DL, MVT::i32), 6981 DAG.getConstant(15, DL, MVT::i32), 6982 DAG.getConstant(0, DL, MVT::i32), 6983 DAG.getConstant(9, DL, MVT::i32), 6984 DAG.getConstant(13, DL, MVT::i32), 6985 DAG.getConstant(0, DL, MVT::i32) 6986 }; 6987 6988 SDValue Cycles32 = DAG.getNode(ISD::INTRINSIC_W_CHAIN, DL, 6989 DAG.getVTList(MVT::i32, MVT::Other), Ops); 6990 Results.push_back(DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, Cycles32, 6991 DAG.getConstant(0, DL, MVT::i32))); 6992 Results.push_back(Cycles32.getValue(1)); 6993 } 6994 6995 SDValue ARMTargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const { 6996 switch (Op.getOpcode()) { 6997 default: llvm_unreachable("Don't know how to custom lower this!"); 6998 case ISD::WRITE_REGISTER: return LowerWRITE_REGISTER(Op, DAG); 6999 case ISD::ConstantPool: return LowerConstantPool(Op, DAG); 7000 case ISD::BlockAddress: return LowerBlockAddress(Op, DAG); 7001 case ISD::GlobalAddress: 7002 switch (Subtarget->getTargetTriple().getObjectFormat()) { 7003 default: llvm_unreachable("unknown object format"); 7004 case Triple::COFF: 7005 return LowerGlobalAddressWindows(Op, DAG); 7006 case Triple::ELF: 7007 return LowerGlobalAddressELF(Op, DAG); 7008 case Triple::MachO: 7009 return LowerGlobalAddressDarwin(Op, DAG); 7010 } 7011 case ISD::GlobalTLSAddress: return LowerGlobalTLSAddress(Op, DAG); 7012 case ISD::SELECT: return LowerSELECT(Op, DAG); 7013 case ISD::SELECT_CC: return LowerSELECT_CC(Op, DAG); 7014 case ISD::BR_CC: return LowerBR_CC(Op, DAG); 7015 case ISD::BR_JT: return LowerBR_JT(Op, DAG); 7016 case ISD::VASTART: return LowerVASTART(Op, DAG); 7017 case ISD::ATOMIC_FENCE: return LowerATOMIC_FENCE(Op, DAG, Subtarget); 7018 case ISD::PREFETCH: return LowerPREFETCH(Op, DAG, Subtarget); 7019 case ISD::SINT_TO_FP: 7020 case ISD::UINT_TO_FP: return LowerINT_TO_FP(Op, DAG); 7021 case ISD::FP_TO_SINT: 7022 case ISD::FP_TO_UINT: return LowerFP_TO_INT(Op, DAG); 7023 case ISD::FCOPYSIGN: return LowerFCOPYSIGN(Op, DAG); 7024 case ISD::RETURNADDR: return LowerRETURNADDR(Op, DAG); 7025 case ISD::FRAMEADDR: return LowerFRAMEADDR(Op, DAG); 7026 case ISD::EH_SJLJ_SETJMP: return LowerEH_SJLJ_SETJMP(Op, DAG); 7027 case ISD::EH_SJLJ_LONGJMP: return LowerEH_SJLJ_LONGJMP(Op, DAG); 7028 case ISD::EH_SJLJ_SETUP_DISPATCH: return LowerEH_SJLJ_SETUP_DISPATCH(Op, DAG); 7029 case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG, 7030 Subtarget); 7031 case ISD::BITCAST: return ExpandBITCAST(Op.getNode(), DAG); 7032 case ISD::SHL: 7033 case ISD::SRL: 7034 case ISD::SRA: return LowerShift(Op.getNode(), DAG, Subtarget); 7035 case ISD::SREM: return LowerREM(Op.getNode(), DAG); 7036 case ISD::UREM: return LowerREM(Op.getNode(), DAG); 7037 case ISD::SHL_PARTS: return LowerShiftLeftParts(Op, DAG); 7038 case ISD::SRL_PARTS: 7039 case ISD::SRA_PARTS: return LowerShiftRightParts(Op, DAG); 7040 case ISD::CTTZ: 7041 case ISD::CTTZ_ZERO_UNDEF: return LowerCTTZ(Op.getNode(), DAG, Subtarget); 7042 case ISD::CTPOP: return LowerCTPOP(Op.getNode(), DAG, Subtarget); 7043 case ISD::SETCC: return LowerVSETCC(Op, DAG); 7044 case ISD::SETCCE: return LowerSETCCE(Op, DAG); 7045 case ISD::ConstantFP: return LowerConstantFP(Op, DAG, Subtarget); 7046 case ISD::BUILD_VECTOR: return LowerBUILD_VECTOR(Op, DAG, Subtarget); 7047 case ISD::VECTOR_SHUFFLE: return LowerVECTOR_SHUFFLE(Op, DAG); 7048 case ISD::INSERT_VECTOR_ELT: return LowerINSERT_VECTOR_ELT(Op, DAG); 7049 case ISD::EXTRACT_VECTOR_ELT: return LowerEXTRACT_VECTOR_ELT(Op, DAG); 7050 case ISD::CONCAT_VECTORS: return LowerCONCAT_VECTORS(Op, DAG); 7051 case ISD::FLT_ROUNDS_: return LowerFLT_ROUNDS_(Op, DAG); 7052 case ISD::MUL: return LowerMUL(Op, DAG); 7053 case ISD::SDIV: 7054 if (Subtarget->isTargetWindows()) 7055 return LowerDIV_Windows(Op, DAG, /* Signed */ true); 7056 return LowerSDIV(Op, DAG); 7057 case ISD::UDIV: 7058 if (Subtarget->isTargetWindows()) 7059 return LowerDIV_Windows(Op, DAG, /* Signed */ false); 7060 return LowerUDIV(Op, DAG); 7061 case ISD::ADDC: 7062 case ISD::ADDE: 7063 case ISD::SUBC: 7064 case ISD::SUBE: return LowerADDC_ADDE_SUBC_SUBE(Op, DAG); 7065 case ISD::SADDO: 7066 case ISD::UADDO: 7067 case ISD::SSUBO: 7068 case ISD::USUBO: 7069 return LowerXALUO(Op, DAG); 7070 case ISD::ATOMIC_LOAD: 7071 case ISD::ATOMIC_STORE: return LowerAtomicLoadStore(Op, DAG); 7072 case ISD::FSINCOS: return LowerFSINCOS(Op, DAG); 7073 case ISD::SDIVREM: 7074 case ISD::UDIVREM: return LowerDivRem(Op, DAG); 7075 case ISD::DYNAMIC_STACKALLOC: 7076 if (Subtarget->getTargetTriple().isWindowsItaniumEnvironment()) 7077 return LowerDYNAMIC_STACKALLOC(Op, DAG); 7078 llvm_unreachable("Don't know how to custom lower this!"); 7079 case ISD::FP_ROUND: return LowerFP_ROUND(Op, DAG); 7080 case ISD::FP_EXTEND: return LowerFP_EXTEND(Op, DAG); 7081 case ARMISD::WIN__DBZCHK: return SDValue(); 7082 } 7083 } 7084 7085 /// ReplaceNodeResults - Replace the results of node with an illegal result 7086 /// type with new values built out of custom code. 7087 void ARMTargetLowering::ReplaceNodeResults(SDNode *N, 7088 SmallVectorImpl<SDValue> &Results, 7089 SelectionDAG &DAG) const { 7090 SDValue Res; 7091 switch (N->getOpcode()) { 7092 default: 7093 llvm_unreachable("Don't know how to custom expand this!"); 7094 case ISD::READ_REGISTER: 7095 ExpandREAD_REGISTER(N, Results, DAG); 7096 break; 7097 case ISD::BITCAST: 7098 Res = ExpandBITCAST(N, DAG); 7099 break; 7100 case ISD::SRL: 7101 case ISD::SRA: 7102 Res = Expand64BitShift(N, DAG, Subtarget); 7103 break; 7104 case ISD::SREM: 7105 case ISD::UREM: 7106 Res = LowerREM(N, DAG); 7107 break; 7108 case ISD::SDIVREM: 7109 case ISD::UDIVREM: 7110 Res = LowerDivRem(SDValue(N, 0), DAG); 7111 assert(Res.getNumOperands() == 2 && "DivRem needs two values"); 7112 Results.push_back(Res.getValue(0)); 7113 Results.push_back(Res.getValue(1)); 7114 return; 7115 case ISD::READCYCLECOUNTER: 7116 ReplaceREADCYCLECOUNTER(N, Results, DAG, Subtarget); 7117 return; 7118 case ISD::UDIV: 7119 case ISD::SDIV: 7120 assert(Subtarget->isTargetWindows() && "can only expand DIV on Windows"); 7121 return ExpandDIV_Windows(SDValue(N, 0), DAG, N->getOpcode() == ISD::SDIV, 7122 Results); 7123 } 7124 if (Res.getNode()) 7125 Results.push_back(Res); 7126 } 7127 7128 //===----------------------------------------------------------------------===// 7129 // ARM Scheduler Hooks 7130 //===----------------------------------------------------------------------===// 7131 7132 /// SetupEntryBlockForSjLj - Insert code into the entry block that creates and 7133 /// registers the function context. 7134 void ARMTargetLowering:: 7135 SetupEntryBlockForSjLj(MachineInstr *MI, MachineBasicBlock *MBB, 7136 MachineBasicBlock *DispatchBB, int FI) const { 7137 const TargetInstrInfo *TII = Subtarget->getInstrInfo(); 7138 DebugLoc dl = MI->getDebugLoc(); 7139 MachineFunction *MF = MBB->getParent(); 7140 MachineRegisterInfo *MRI = &MF->getRegInfo(); 7141 MachineConstantPool *MCP = MF->getConstantPool(); 7142 ARMFunctionInfo *AFI = MF->getInfo<ARMFunctionInfo>(); 7143 const Function *F = MF->getFunction(); 7144 7145 bool isThumb = Subtarget->isThumb(); 7146 bool isThumb2 = Subtarget->isThumb2(); 7147 7148 unsigned PCLabelId = AFI->createPICLabelUId(); 7149 unsigned PCAdj = (isThumb || isThumb2) ? 4 : 8; 7150 ARMConstantPoolValue *CPV = 7151 ARMConstantPoolMBB::Create(F->getContext(), DispatchBB, PCLabelId, PCAdj); 7152 unsigned CPI = MCP->getConstantPoolIndex(CPV, 4); 7153 7154 const TargetRegisterClass *TRC = isThumb ? &ARM::tGPRRegClass 7155 : &ARM::GPRRegClass; 7156 7157 // Grab constant pool and fixed stack memory operands. 7158 MachineMemOperand *CPMMO = 7159 MF->getMachineMemOperand(MachinePointerInfo::getConstantPool(*MF), 7160 MachineMemOperand::MOLoad, 4, 4); 7161 7162 MachineMemOperand *FIMMOSt = 7163 MF->getMachineMemOperand(MachinePointerInfo::getFixedStack(*MF, FI), 7164 MachineMemOperand::MOStore, 4, 4); 7165 7166 // Load the address of the dispatch MBB into the jump buffer. 7167 if (isThumb2) { 7168 // Incoming value: jbuf 7169 // ldr.n r5, LCPI1_1 7170 // orr r5, r5, #1 7171 // add r5, pc 7172 // str r5, [$jbuf, #+4] ; &jbuf[1] 7173 unsigned NewVReg1 = MRI->createVirtualRegister(TRC); 7174 AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::t2LDRpci), NewVReg1) 7175 .addConstantPoolIndex(CPI) 7176 .addMemOperand(CPMMO)); 7177 // Set the low bit because of thumb mode. 7178 unsigned NewVReg2 = MRI->createVirtualRegister(TRC); 7179 AddDefaultCC( 7180 AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::t2ORRri), NewVReg2) 7181 .addReg(NewVReg1, RegState::Kill) 7182 .addImm(0x01))); 7183 unsigned NewVReg3 = MRI->createVirtualRegister(TRC); 7184 BuildMI(*MBB, MI, dl, TII->get(ARM::tPICADD), NewVReg3) 7185 .addReg(NewVReg2, RegState::Kill) 7186 .addImm(PCLabelId); 7187 AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::t2STRi12)) 7188 .addReg(NewVReg3, RegState::Kill) 7189 .addFrameIndex(FI) 7190 .addImm(36) // &jbuf[1] :: pc 7191 .addMemOperand(FIMMOSt)); 7192 } else if (isThumb) { 7193 // Incoming value: jbuf 7194 // ldr.n r1, LCPI1_4 7195 // add r1, pc 7196 // mov r2, #1 7197 // orrs r1, r2 7198 // add r2, $jbuf, #+4 ; &jbuf[1] 7199 // str r1, [r2] 7200 unsigned NewVReg1 = MRI->createVirtualRegister(TRC); 7201 AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::tLDRpci), NewVReg1) 7202 .addConstantPoolIndex(CPI) 7203 .addMemOperand(CPMMO)); 7204 unsigned NewVReg2 = MRI->createVirtualRegister(TRC); 7205 BuildMI(*MBB, MI, dl, TII->get(ARM::tPICADD), NewVReg2) 7206 .addReg(NewVReg1, RegState::Kill) 7207 .addImm(PCLabelId); 7208 // Set the low bit because of thumb mode. 7209 unsigned NewVReg3 = MRI->createVirtualRegister(TRC); 7210 AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::tMOVi8), NewVReg3) 7211 .addReg(ARM::CPSR, RegState::Define) 7212 .addImm(1)); 7213 unsigned NewVReg4 = MRI->createVirtualRegister(TRC); 7214 AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::tORR), NewVReg4) 7215 .addReg(ARM::CPSR, RegState::Define) 7216 .addReg(NewVReg2, RegState::Kill) 7217 .addReg(NewVReg3, RegState::Kill)); 7218 unsigned NewVReg5 = MRI->createVirtualRegister(TRC); 7219 BuildMI(*MBB, MI, dl, TII->get(ARM::tADDframe), NewVReg5) 7220 .addFrameIndex(FI) 7221 .addImm(36); // &jbuf[1] :: pc 7222 AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::tSTRi)) 7223 .addReg(NewVReg4, RegState::Kill) 7224 .addReg(NewVReg5, RegState::Kill) 7225 .addImm(0) 7226 .addMemOperand(FIMMOSt)); 7227 } else { 7228 // Incoming value: jbuf 7229 // ldr r1, LCPI1_1 7230 // add r1, pc, r1 7231 // str r1, [$jbuf, #+4] ; &jbuf[1] 7232 unsigned NewVReg1 = MRI->createVirtualRegister(TRC); 7233 AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::LDRi12), NewVReg1) 7234 .addConstantPoolIndex(CPI) 7235 .addImm(0) 7236 .addMemOperand(CPMMO)); 7237 unsigned NewVReg2 = MRI->createVirtualRegister(TRC); 7238 AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::PICADD), NewVReg2) 7239 .addReg(NewVReg1, RegState::Kill) 7240 .addImm(PCLabelId)); 7241 AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::STRi12)) 7242 .addReg(NewVReg2, RegState::Kill) 7243 .addFrameIndex(FI) 7244 .addImm(36) // &jbuf[1] :: pc 7245 .addMemOperand(FIMMOSt)); 7246 } 7247 } 7248 7249 void ARMTargetLowering::EmitSjLjDispatchBlock(MachineInstr *MI, 7250 MachineBasicBlock *MBB) const { 7251 const TargetInstrInfo *TII = Subtarget->getInstrInfo(); 7252 DebugLoc dl = MI->getDebugLoc(); 7253 MachineFunction *MF = MBB->getParent(); 7254 MachineRegisterInfo *MRI = &MF->getRegInfo(); 7255 MachineFrameInfo *MFI = MF->getFrameInfo(); 7256 int FI = MFI->getFunctionContextIndex(); 7257 7258 const TargetRegisterClass *TRC = Subtarget->isThumb() ? &ARM::tGPRRegClass 7259 : &ARM::GPRnopcRegClass; 7260 7261 // Get a mapping of the call site numbers to all of the landing pads they're 7262 // associated with. 7263 DenseMap<unsigned, SmallVector<MachineBasicBlock*, 2> > CallSiteNumToLPad; 7264 unsigned MaxCSNum = 0; 7265 MachineModuleInfo &MMI = MF->getMMI(); 7266 for (MachineFunction::iterator BB = MF->begin(), E = MF->end(); BB != E; 7267 ++BB) { 7268 if (!BB->isEHPad()) continue; 7269 7270 // FIXME: We should assert that the EH_LABEL is the first MI in the landing 7271 // pad. 7272 for (MachineBasicBlock::iterator 7273 II = BB->begin(), IE = BB->end(); II != IE; ++II) { 7274 if (!II->isEHLabel()) continue; 7275 7276 MCSymbol *Sym = II->getOperand(0).getMCSymbol(); 7277 if (!MMI.hasCallSiteLandingPad(Sym)) continue; 7278 7279 SmallVectorImpl<unsigned> &CallSiteIdxs = MMI.getCallSiteLandingPad(Sym); 7280 for (SmallVectorImpl<unsigned>::iterator 7281 CSI = CallSiteIdxs.begin(), CSE = CallSiteIdxs.end(); 7282 CSI != CSE; ++CSI) { 7283 CallSiteNumToLPad[*CSI].push_back(&*BB); 7284 MaxCSNum = std::max(MaxCSNum, *CSI); 7285 } 7286 break; 7287 } 7288 } 7289 7290 // Get an ordered list of the machine basic blocks for the jump table. 7291 std::vector<MachineBasicBlock*> LPadList; 7292 SmallPtrSet<MachineBasicBlock*, 32> InvokeBBs; 7293 LPadList.reserve(CallSiteNumToLPad.size()); 7294 for (unsigned I = 1; I <= MaxCSNum; ++I) { 7295 SmallVectorImpl<MachineBasicBlock*> &MBBList = CallSiteNumToLPad[I]; 7296 for (SmallVectorImpl<MachineBasicBlock*>::iterator 7297 II = MBBList.begin(), IE = MBBList.end(); II != IE; ++II) { 7298 LPadList.push_back(*II); 7299 InvokeBBs.insert((*II)->pred_begin(), (*II)->pred_end()); 7300 } 7301 } 7302 7303 assert(!LPadList.empty() && 7304 "No landing pad destinations for the dispatch jump table!"); 7305 7306 // Create the jump table and associated information. 7307 MachineJumpTableInfo *JTI = 7308 MF->getOrCreateJumpTableInfo(MachineJumpTableInfo::EK_Inline); 7309 unsigned MJTI = JTI->createJumpTableIndex(LPadList); 7310 Reloc::Model RelocM = getTargetMachine().getRelocationModel(); 7311 7312 // Create the MBBs for the dispatch code. 7313 7314 // Shove the dispatch's address into the return slot in the function context. 7315 MachineBasicBlock *DispatchBB = MF->CreateMachineBasicBlock(); 7316 DispatchBB->setIsEHPad(); 7317 7318 MachineBasicBlock *TrapBB = MF->CreateMachineBasicBlock(); 7319 unsigned trap_opcode; 7320 if (Subtarget->isThumb()) 7321 trap_opcode = ARM::tTRAP; 7322 else 7323 trap_opcode = Subtarget->useNaClTrap() ? ARM::TRAPNaCl : ARM::TRAP; 7324 7325 BuildMI(TrapBB, dl, TII->get(trap_opcode)); 7326 DispatchBB->addSuccessor(TrapBB); 7327 7328 MachineBasicBlock *DispContBB = MF->CreateMachineBasicBlock(); 7329 DispatchBB->addSuccessor(DispContBB); 7330 7331 // Insert and MBBs. 7332 MF->insert(MF->end(), DispatchBB); 7333 MF->insert(MF->end(), DispContBB); 7334 MF->insert(MF->end(), TrapBB); 7335 7336 // Insert code into the entry block that creates and registers the function 7337 // context. 7338 SetupEntryBlockForSjLj(MI, MBB, DispatchBB, FI); 7339 7340 MachineMemOperand *FIMMOLd = MF->getMachineMemOperand( 7341 MachinePointerInfo::getFixedStack(*MF, FI), 7342 MachineMemOperand::MOLoad | MachineMemOperand::MOVolatile, 4, 4); 7343 7344 MachineInstrBuilder MIB; 7345 MIB = BuildMI(DispatchBB, dl, TII->get(ARM::Int_eh_sjlj_dispatchsetup)); 7346 7347 const ARMBaseInstrInfo *AII = static_cast<const ARMBaseInstrInfo*>(TII); 7348 const ARMBaseRegisterInfo &RI = AII->getRegisterInfo(); 7349 7350 // Add a register mask with no preserved registers. This results in all 7351 // registers being marked as clobbered. 7352 MIB.addRegMask(RI.getNoPreservedMask()); 7353 7354 unsigned NumLPads = LPadList.size(); 7355 if (Subtarget->isThumb2()) { 7356 unsigned NewVReg1 = MRI->createVirtualRegister(TRC); 7357 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::t2LDRi12), NewVReg1) 7358 .addFrameIndex(FI) 7359 .addImm(4) 7360 .addMemOperand(FIMMOLd)); 7361 7362 if (NumLPads < 256) { 7363 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::t2CMPri)) 7364 .addReg(NewVReg1) 7365 .addImm(LPadList.size())); 7366 } else { 7367 unsigned VReg1 = MRI->createVirtualRegister(TRC); 7368 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::t2MOVi16), VReg1) 7369 .addImm(NumLPads & 0xFFFF)); 7370 7371 unsigned VReg2 = VReg1; 7372 if ((NumLPads & 0xFFFF0000) != 0) { 7373 VReg2 = MRI->createVirtualRegister(TRC); 7374 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::t2MOVTi16), VReg2) 7375 .addReg(VReg1) 7376 .addImm(NumLPads >> 16)); 7377 } 7378 7379 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::t2CMPrr)) 7380 .addReg(NewVReg1) 7381 .addReg(VReg2)); 7382 } 7383 7384 BuildMI(DispatchBB, dl, TII->get(ARM::t2Bcc)) 7385 .addMBB(TrapBB) 7386 .addImm(ARMCC::HI) 7387 .addReg(ARM::CPSR); 7388 7389 unsigned NewVReg3 = MRI->createVirtualRegister(TRC); 7390 AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::t2LEApcrelJT),NewVReg3) 7391 .addJumpTableIndex(MJTI)); 7392 7393 unsigned NewVReg4 = MRI->createVirtualRegister(TRC); 7394 AddDefaultCC( 7395 AddDefaultPred( 7396 BuildMI(DispContBB, dl, TII->get(ARM::t2ADDrs), NewVReg4) 7397 .addReg(NewVReg3, RegState::Kill) 7398 .addReg(NewVReg1) 7399 .addImm(ARM_AM::getSORegOpc(ARM_AM::lsl, 2)))); 7400 7401 BuildMI(DispContBB, dl, TII->get(ARM::t2BR_JT)) 7402 .addReg(NewVReg4, RegState::Kill) 7403 .addReg(NewVReg1) 7404 .addJumpTableIndex(MJTI); 7405 } else if (Subtarget->isThumb()) { 7406 unsigned NewVReg1 = MRI->createVirtualRegister(TRC); 7407 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::tLDRspi), NewVReg1) 7408 .addFrameIndex(FI) 7409 .addImm(1) 7410 .addMemOperand(FIMMOLd)); 7411 7412 if (NumLPads < 256) { 7413 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::tCMPi8)) 7414 .addReg(NewVReg1) 7415 .addImm(NumLPads)); 7416 } else { 7417 MachineConstantPool *ConstantPool = MF->getConstantPool(); 7418 Type *Int32Ty = Type::getInt32Ty(MF->getFunction()->getContext()); 7419 const Constant *C = ConstantInt::get(Int32Ty, NumLPads); 7420 7421 // MachineConstantPool wants an explicit alignment. 7422 unsigned Align = MF->getDataLayout().getPrefTypeAlignment(Int32Ty); 7423 if (Align == 0) 7424 Align = MF->getDataLayout().getTypeAllocSize(C->getType()); 7425 unsigned Idx = ConstantPool->getConstantPoolIndex(C, Align); 7426 7427 unsigned VReg1 = MRI->createVirtualRegister(TRC); 7428 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::tLDRpci)) 7429 .addReg(VReg1, RegState::Define) 7430 .addConstantPoolIndex(Idx)); 7431 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::tCMPr)) 7432 .addReg(NewVReg1) 7433 .addReg(VReg1)); 7434 } 7435 7436 BuildMI(DispatchBB, dl, TII->get(ARM::tBcc)) 7437 .addMBB(TrapBB) 7438 .addImm(ARMCC::HI) 7439 .addReg(ARM::CPSR); 7440 7441 unsigned NewVReg2 = MRI->createVirtualRegister(TRC); 7442 AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::tLSLri), NewVReg2) 7443 .addReg(ARM::CPSR, RegState::Define) 7444 .addReg(NewVReg1) 7445 .addImm(2)); 7446 7447 unsigned NewVReg3 = MRI->createVirtualRegister(TRC); 7448 AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::tLEApcrelJT), NewVReg3) 7449 .addJumpTableIndex(MJTI)); 7450 7451 unsigned NewVReg4 = MRI->createVirtualRegister(TRC); 7452 AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::tADDrr), NewVReg4) 7453 .addReg(ARM::CPSR, RegState::Define) 7454 .addReg(NewVReg2, RegState::Kill) 7455 .addReg(NewVReg3)); 7456 7457 MachineMemOperand *JTMMOLd = MF->getMachineMemOperand( 7458 MachinePointerInfo::getJumpTable(*MF), MachineMemOperand::MOLoad, 4, 4); 7459 7460 unsigned NewVReg5 = MRI->createVirtualRegister(TRC); 7461 AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::tLDRi), NewVReg5) 7462 .addReg(NewVReg4, RegState::Kill) 7463 .addImm(0) 7464 .addMemOperand(JTMMOLd)); 7465 7466 unsigned NewVReg6 = NewVReg5; 7467 if (RelocM == Reloc::PIC_) { 7468 NewVReg6 = MRI->createVirtualRegister(TRC); 7469 AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::tADDrr), NewVReg6) 7470 .addReg(ARM::CPSR, RegState::Define) 7471 .addReg(NewVReg5, RegState::Kill) 7472 .addReg(NewVReg3)); 7473 } 7474 7475 BuildMI(DispContBB, dl, TII->get(ARM::tBR_JTr)) 7476 .addReg(NewVReg6, RegState::Kill) 7477 .addJumpTableIndex(MJTI); 7478 } else { 7479 unsigned NewVReg1 = MRI->createVirtualRegister(TRC); 7480 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::LDRi12), NewVReg1) 7481 .addFrameIndex(FI) 7482 .addImm(4) 7483 .addMemOperand(FIMMOLd)); 7484 7485 if (NumLPads < 256) { 7486 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::CMPri)) 7487 .addReg(NewVReg1) 7488 .addImm(NumLPads)); 7489 } else if (Subtarget->hasV6T2Ops() && isUInt<16>(NumLPads)) { 7490 unsigned VReg1 = MRI->createVirtualRegister(TRC); 7491 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::MOVi16), VReg1) 7492 .addImm(NumLPads & 0xFFFF)); 7493 7494 unsigned VReg2 = VReg1; 7495 if ((NumLPads & 0xFFFF0000) != 0) { 7496 VReg2 = MRI->createVirtualRegister(TRC); 7497 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::MOVTi16), VReg2) 7498 .addReg(VReg1) 7499 .addImm(NumLPads >> 16)); 7500 } 7501 7502 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::CMPrr)) 7503 .addReg(NewVReg1) 7504 .addReg(VReg2)); 7505 } else { 7506 MachineConstantPool *ConstantPool = MF->getConstantPool(); 7507 Type *Int32Ty = Type::getInt32Ty(MF->getFunction()->getContext()); 7508 const Constant *C = ConstantInt::get(Int32Ty, NumLPads); 7509 7510 // MachineConstantPool wants an explicit alignment. 7511 unsigned Align = MF->getDataLayout().getPrefTypeAlignment(Int32Ty); 7512 if (Align == 0) 7513 Align = MF->getDataLayout().getTypeAllocSize(C->getType()); 7514 unsigned Idx = ConstantPool->getConstantPoolIndex(C, Align); 7515 7516 unsigned VReg1 = MRI->createVirtualRegister(TRC); 7517 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::LDRcp)) 7518 .addReg(VReg1, RegState::Define) 7519 .addConstantPoolIndex(Idx) 7520 .addImm(0)); 7521 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::CMPrr)) 7522 .addReg(NewVReg1) 7523 .addReg(VReg1, RegState::Kill)); 7524 } 7525 7526 BuildMI(DispatchBB, dl, TII->get(ARM::Bcc)) 7527 .addMBB(TrapBB) 7528 .addImm(ARMCC::HI) 7529 .addReg(ARM::CPSR); 7530 7531 unsigned NewVReg3 = MRI->createVirtualRegister(TRC); 7532 AddDefaultCC( 7533 AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::MOVsi), NewVReg3) 7534 .addReg(NewVReg1) 7535 .addImm(ARM_AM::getSORegOpc(ARM_AM::lsl, 2)))); 7536 unsigned NewVReg4 = MRI->createVirtualRegister(TRC); 7537 AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::LEApcrelJT), NewVReg4) 7538 .addJumpTableIndex(MJTI)); 7539 7540 MachineMemOperand *JTMMOLd = MF->getMachineMemOperand( 7541 MachinePointerInfo::getJumpTable(*MF), MachineMemOperand::MOLoad, 4, 4); 7542 unsigned NewVReg5 = MRI->createVirtualRegister(TRC); 7543 AddDefaultPred( 7544 BuildMI(DispContBB, dl, TII->get(ARM::LDRrs), NewVReg5) 7545 .addReg(NewVReg3, RegState::Kill) 7546 .addReg(NewVReg4) 7547 .addImm(0) 7548 .addMemOperand(JTMMOLd)); 7549 7550 if (RelocM == Reloc::PIC_) { 7551 BuildMI(DispContBB, dl, TII->get(ARM::BR_JTadd)) 7552 .addReg(NewVReg5, RegState::Kill) 7553 .addReg(NewVReg4) 7554 .addJumpTableIndex(MJTI); 7555 } else { 7556 BuildMI(DispContBB, dl, TII->get(ARM::BR_JTr)) 7557 .addReg(NewVReg5, RegState::Kill) 7558 .addJumpTableIndex(MJTI); 7559 } 7560 } 7561 7562 // Add the jump table entries as successors to the MBB. 7563 SmallPtrSet<MachineBasicBlock*, 8> SeenMBBs; 7564 for (std::vector<MachineBasicBlock*>::iterator 7565 I = LPadList.begin(), E = LPadList.end(); I != E; ++I) { 7566 MachineBasicBlock *CurMBB = *I; 7567 if (SeenMBBs.insert(CurMBB).second) 7568 DispContBB->addSuccessor(CurMBB); 7569 } 7570 7571 // N.B. the order the invoke BBs are processed in doesn't matter here. 7572 const MCPhysReg *SavedRegs = RI.getCalleeSavedRegs(MF); 7573 SmallVector<MachineBasicBlock*, 64> MBBLPads; 7574 for (MachineBasicBlock *BB : InvokeBBs) { 7575 7576 // Remove the landing pad successor from the invoke block and replace it 7577 // with the new dispatch block. 7578 SmallVector<MachineBasicBlock*, 4> Successors(BB->succ_begin(), 7579 BB->succ_end()); 7580 while (!Successors.empty()) { 7581 MachineBasicBlock *SMBB = Successors.pop_back_val(); 7582 if (SMBB->isEHPad()) { 7583 BB->removeSuccessor(SMBB); 7584 MBBLPads.push_back(SMBB); 7585 } 7586 } 7587 7588 BB->addSuccessor(DispatchBB, BranchProbability::getZero()); 7589 BB->normalizeSuccProbs(); 7590 7591 // Find the invoke call and mark all of the callee-saved registers as 7592 // 'implicit defined' so that they're spilled. This prevents code from 7593 // moving instructions to before the EH block, where they will never be 7594 // executed. 7595 for (MachineBasicBlock::reverse_iterator 7596 II = BB->rbegin(), IE = BB->rend(); II != IE; ++II) { 7597 if (!II->isCall()) continue; 7598 7599 DenseMap<unsigned, bool> DefRegs; 7600 for (MachineInstr::mop_iterator 7601 OI = II->operands_begin(), OE = II->operands_end(); 7602 OI != OE; ++OI) { 7603 if (!OI->isReg()) continue; 7604 DefRegs[OI->getReg()] = true; 7605 } 7606 7607 MachineInstrBuilder MIB(*MF, &*II); 7608 7609 for (unsigned i = 0; SavedRegs[i] != 0; ++i) { 7610 unsigned Reg = SavedRegs[i]; 7611 if (Subtarget->isThumb2() && 7612 !ARM::tGPRRegClass.contains(Reg) && 7613 !ARM::hGPRRegClass.contains(Reg)) 7614 continue; 7615 if (Subtarget->isThumb1Only() && !ARM::tGPRRegClass.contains(Reg)) 7616 continue; 7617 if (!Subtarget->isThumb() && !ARM::GPRRegClass.contains(Reg)) 7618 continue; 7619 if (!DefRegs[Reg]) 7620 MIB.addReg(Reg, RegState::ImplicitDefine | RegState::Dead); 7621 } 7622 7623 break; 7624 } 7625 } 7626 7627 // Mark all former landing pads as non-landing pads. The dispatch is the only 7628 // landing pad now. 7629 for (SmallVectorImpl<MachineBasicBlock*>::iterator 7630 I = MBBLPads.begin(), E = MBBLPads.end(); I != E; ++I) 7631 (*I)->setIsEHPad(false); 7632 7633 // The instruction is gone now. 7634 MI->eraseFromParent(); 7635 } 7636 7637 static 7638 MachineBasicBlock *OtherSucc(MachineBasicBlock *MBB, MachineBasicBlock *Succ) { 7639 for (MachineBasicBlock::succ_iterator I = MBB->succ_begin(), 7640 E = MBB->succ_end(); I != E; ++I) 7641 if (*I != Succ) 7642 return *I; 7643 llvm_unreachable("Expecting a BB with two successors!"); 7644 } 7645 7646 /// Return the load opcode for a given load size. If load size >= 8, 7647 /// neon opcode will be returned. 7648 static unsigned getLdOpcode(unsigned LdSize, bool IsThumb1, bool IsThumb2) { 7649 if (LdSize >= 8) 7650 return LdSize == 16 ? ARM::VLD1q32wb_fixed 7651 : LdSize == 8 ? ARM::VLD1d32wb_fixed : 0; 7652 if (IsThumb1) 7653 return LdSize == 4 ? ARM::tLDRi 7654 : LdSize == 2 ? ARM::tLDRHi 7655 : LdSize == 1 ? ARM::tLDRBi : 0; 7656 if (IsThumb2) 7657 return LdSize == 4 ? ARM::t2LDR_POST 7658 : LdSize == 2 ? ARM::t2LDRH_POST 7659 : LdSize == 1 ? ARM::t2LDRB_POST : 0; 7660 return LdSize == 4 ? ARM::LDR_POST_IMM 7661 : LdSize == 2 ? ARM::LDRH_POST 7662 : LdSize == 1 ? ARM::LDRB_POST_IMM : 0; 7663 } 7664 7665 /// Return the store opcode for a given store size. If store size >= 8, 7666 /// neon opcode will be returned. 7667 static unsigned getStOpcode(unsigned StSize, bool IsThumb1, bool IsThumb2) { 7668 if (StSize >= 8) 7669 return StSize == 16 ? ARM::VST1q32wb_fixed 7670 : StSize == 8 ? ARM::VST1d32wb_fixed : 0; 7671 if (IsThumb1) 7672 return StSize == 4 ? ARM::tSTRi 7673 : StSize == 2 ? ARM::tSTRHi 7674 : StSize == 1 ? ARM::tSTRBi : 0; 7675 if (IsThumb2) 7676 return StSize == 4 ? ARM::t2STR_POST 7677 : StSize == 2 ? ARM::t2STRH_POST 7678 : StSize == 1 ? ARM::t2STRB_POST : 0; 7679 return StSize == 4 ? ARM::STR_POST_IMM 7680 : StSize == 2 ? ARM::STRH_POST 7681 : StSize == 1 ? ARM::STRB_POST_IMM : 0; 7682 } 7683 7684 /// Emit a post-increment load operation with given size. The instructions 7685 /// will be added to BB at Pos. 7686 static void emitPostLd(MachineBasicBlock *BB, MachineInstr *Pos, 7687 const TargetInstrInfo *TII, DebugLoc dl, 7688 unsigned LdSize, unsigned Data, unsigned AddrIn, 7689 unsigned AddrOut, bool IsThumb1, bool IsThumb2) { 7690 unsigned LdOpc = getLdOpcode(LdSize, IsThumb1, IsThumb2); 7691 assert(LdOpc != 0 && "Should have a load opcode"); 7692 if (LdSize >= 8) { 7693 AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(LdOpc), Data) 7694 .addReg(AddrOut, RegState::Define).addReg(AddrIn) 7695 .addImm(0)); 7696 } else if (IsThumb1) { 7697 // load + update AddrIn 7698 AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(LdOpc), Data) 7699 .addReg(AddrIn).addImm(0)); 7700 MachineInstrBuilder MIB = 7701 BuildMI(*BB, Pos, dl, TII->get(ARM::tADDi8), AddrOut); 7702 MIB = AddDefaultT1CC(MIB); 7703 MIB.addReg(AddrIn).addImm(LdSize); 7704 AddDefaultPred(MIB); 7705 } else if (IsThumb2) { 7706 AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(LdOpc), Data) 7707 .addReg(AddrOut, RegState::Define).addReg(AddrIn) 7708 .addImm(LdSize)); 7709 } else { // arm 7710 AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(LdOpc), Data) 7711 .addReg(AddrOut, RegState::Define).addReg(AddrIn) 7712 .addReg(0).addImm(LdSize)); 7713 } 7714 } 7715 7716 /// Emit a post-increment store operation with given size. The instructions 7717 /// will be added to BB at Pos. 7718 static void emitPostSt(MachineBasicBlock *BB, MachineInstr *Pos, 7719 const TargetInstrInfo *TII, DebugLoc dl, 7720 unsigned StSize, unsigned Data, unsigned AddrIn, 7721 unsigned AddrOut, bool IsThumb1, bool IsThumb2) { 7722 unsigned StOpc = getStOpcode(StSize, IsThumb1, IsThumb2); 7723 assert(StOpc != 0 && "Should have a store opcode"); 7724 if (StSize >= 8) { 7725 AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(StOpc), AddrOut) 7726 .addReg(AddrIn).addImm(0).addReg(Data)); 7727 } else if (IsThumb1) { 7728 // store + update AddrIn 7729 AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(StOpc)).addReg(Data) 7730 .addReg(AddrIn).addImm(0)); 7731 MachineInstrBuilder MIB = 7732 BuildMI(*BB, Pos, dl, TII->get(ARM::tADDi8), AddrOut); 7733 MIB = AddDefaultT1CC(MIB); 7734 MIB.addReg(AddrIn).addImm(StSize); 7735 AddDefaultPred(MIB); 7736 } else if (IsThumb2) { 7737 AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(StOpc), AddrOut) 7738 .addReg(Data).addReg(AddrIn).addImm(StSize)); 7739 } else { // arm 7740 AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(StOpc), AddrOut) 7741 .addReg(Data).addReg(AddrIn).addReg(0) 7742 .addImm(StSize)); 7743 } 7744 } 7745 7746 MachineBasicBlock * 7747 ARMTargetLowering::EmitStructByval(MachineInstr *MI, 7748 MachineBasicBlock *BB) const { 7749 // This pseudo instruction has 3 operands: dst, src, size 7750 // We expand it to a loop if size > Subtarget->getMaxInlineSizeThreshold(). 7751 // Otherwise, we will generate unrolled scalar copies. 7752 const TargetInstrInfo *TII = Subtarget->getInstrInfo(); 7753 const BasicBlock *LLVM_BB = BB->getBasicBlock(); 7754 MachineFunction::iterator It = ++BB->getIterator(); 7755 7756 unsigned dest = MI->getOperand(0).getReg(); 7757 unsigned src = MI->getOperand(1).getReg(); 7758 unsigned SizeVal = MI->getOperand(2).getImm(); 7759 unsigned Align = MI->getOperand(3).getImm(); 7760 DebugLoc dl = MI->getDebugLoc(); 7761 7762 MachineFunction *MF = BB->getParent(); 7763 MachineRegisterInfo &MRI = MF->getRegInfo(); 7764 unsigned UnitSize = 0; 7765 const TargetRegisterClass *TRC = nullptr; 7766 const TargetRegisterClass *VecTRC = nullptr; 7767 7768 bool IsThumb1 = Subtarget->isThumb1Only(); 7769 bool IsThumb2 = Subtarget->isThumb2(); 7770 7771 if (Align & 1) { 7772 UnitSize = 1; 7773 } else if (Align & 2) { 7774 UnitSize = 2; 7775 } else { 7776 // Check whether we can use NEON instructions. 7777 if (!MF->getFunction()->hasFnAttribute(Attribute::NoImplicitFloat) && 7778 Subtarget->hasNEON()) { 7779 if ((Align % 16 == 0) && SizeVal >= 16) 7780 UnitSize = 16; 7781 else if ((Align % 8 == 0) && SizeVal >= 8) 7782 UnitSize = 8; 7783 } 7784 // Can't use NEON instructions. 7785 if (UnitSize == 0) 7786 UnitSize = 4; 7787 } 7788 7789 // Select the correct opcode and register class for unit size load/store 7790 bool IsNeon = UnitSize >= 8; 7791 TRC = (IsThumb1 || IsThumb2) ? &ARM::tGPRRegClass : &ARM::GPRRegClass; 7792 if (IsNeon) 7793 VecTRC = UnitSize == 16 ? &ARM::DPairRegClass 7794 : UnitSize == 8 ? &ARM::DPRRegClass 7795 : nullptr; 7796 7797 unsigned BytesLeft = SizeVal % UnitSize; 7798 unsigned LoopSize = SizeVal - BytesLeft; 7799 7800 if (SizeVal <= Subtarget->getMaxInlineSizeThreshold()) { 7801 // Use LDR and STR to copy. 7802 // [scratch, srcOut] = LDR_POST(srcIn, UnitSize) 7803 // [destOut] = STR_POST(scratch, destIn, UnitSize) 7804 unsigned srcIn = src; 7805 unsigned destIn = dest; 7806 for (unsigned i = 0; i < LoopSize; i+=UnitSize) { 7807 unsigned srcOut = MRI.createVirtualRegister(TRC); 7808 unsigned destOut = MRI.createVirtualRegister(TRC); 7809 unsigned scratch = MRI.createVirtualRegister(IsNeon ? VecTRC : TRC); 7810 emitPostLd(BB, MI, TII, dl, UnitSize, scratch, srcIn, srcOut, 7811 IsThumb1, IsThumb2); 7812 emitPostSt(BB, MI, TII, dl, UnitSize, scratch, destIn, destOut, 7813 IsThumb1, IsThumb2); 7814 srcIn = srcOut; 7815 destIn = destOut; 7816 } 7817 7818 // Handle the leftover bytes with LDRB and STRB. 7819 // [scratch, srcOut] = LDRB_POST(srcIn, 1) 7820 // [destOut] = STRB_POST(scratch, destIn, 1) 7821 for (unsigned i = 0; i < BytesLeft; i++) { 7822 unsigned srcOut = MRI.createVirtualRegister(TRC); 7823 unsigned destOut = MRI.createVirtualRegister(TRC); 7824 unsigned scratch = MRI.createVirtualRegister(TRC); 7825 emitPostLd(BB, MI, TII, dl, 1, scratch, srcIn, srcOut, 7826 IsThumb1, IsThumb2); 7827 emitPostSt(BB, MI, TII, dl, 1, scratch, destIn, destOut, 7828 IsThumb1, IsThumb2); 7829 srcIn = srcOut; 7830 destIn = destOut; 7831 } 7832 MI->eraseFromParent(); // The instruction is gone now. 7833 return BB; 7834 } 7835 7836 // Expand the pseudo op to a loop. 7837 // thisMBB: 7838 // ... 7839 // movw varEnd, # --> with thumb2 7840 // movt varEnd, # 7841 // ldrcp varEnd, idx --> without thumb2 7842 // fallthrough --> loopMBB 7843 // loopMBB: 7844 // PHI varPhi, varEnd, varLoop 7845 // PHI srcPhi, src, srcLoop 7846 // PHI destPhi, dst, destLoop 7847 // [scratch, srcLoop] = LDR_POST(srcPhi, UnitSize) 7848 // [destLoop] = STR_POST(scratch, destPhi, UnitSize) 7849 // subs varLoop, varPhi, #UnitSize 7850 // bne loopMBB 7851 // fallthrough --> exitMBB 7852 // exitMBB: 7853 // epilogue to handle left-over bytes 7854 // [scratch, srcOut] = LDRB_POST(srcLoop, 1) 7855 // [destOut] = STRB_POST(scratch, destLoop, 1) 7856 MachineBasicBlock *loopMBB = MF->CreateMachineBasicBlock(LLVM_BB); 7857 MachineBasicBlock *exitMBB = MF->CreateMachineBasicBlock(LLVM_BB); 7858 MF->insert(It, loopMBB); 7859 MF->insert(It, exitMBB); 7860 7861 // Transfer the remainder of BB and its successor edges to exitMBB. 7862 exitMBB->splice(exitMBB->begin(), BB, 7863 std::next(MachineBasicBlock::iterator(MI)), BB->end()); 7864 exitMBB->transferSuccessorsAndUpdatePHIs(BB); 7865 7866 // Load an immediate to varEnd. 7867 unsigned varEnd = MRI.createVirtualRegister(TRC); 7868 if (Subtarget->useMovt(*MF)) { 7869 unsigned Vtmp = varEnd; 7870 if ((LoopSize & 0xFFFF0000) != 0) 7871 Vtmp = MRI.createVirtualRegister(TRC); 7872 AddDefaultPred(BuildMI(BB, dl, 7873 TII->get(IsThumb2 ? ARM::t2MOVi16 : ARM::MOVi16), 7874 Vtmp).addImm(LoopSize & 0xFFFF)); 7875 7876 if ((LoopSize & 0xFFFF0000) != 0) 7877 AddDefaultPred(BuildMI(BB, dl, 7878 TII->get(IsThumb2 ? ARM::t2MOVTi16 : ARM::MOVTi16), 7879 varEnd) 7880 .addReg(Vtmp) 7881 .addImm(LoopSize >> 16)); 7882 } else { 7883 MachineConstantPool *ConstantPool = MF->getConstantPool(); 7884 Type *Int32Ty = Type::getInt32Ty(MF->getFunction()->getContext()); 7885 const Constant *C = ConstantInt::get(Int32Ty, LoopSize); 7886 7887 // MachineConstantPool wants an explicit alignment. 7888 unsigned Align = MF->getDataLayout().getPrefTypeAlignment(Int32Ty); 7889 if (Align == 0) 7890 Align = MF->getDataLayout().getTypeAllocSize(C->getType()); 7891 unsigned Idx = ConstantPool->getConstantPoolIndex(C, Align); 7892 7893 if (IsThumb1) 7894 AddDefaultPred(BuildMI(*BB, MI, dl, TII->get(ARM::tLDRpci)).addReg( 7895 varEnd, RegState::Define).addConstantPoolIndex(Idx)); 7896 else 7897 AddDefaultPred(BuildMI(*BB, MI, dl, TII->get(ARM::LDRcp)).addReg( 7898 varEnd, RegState::Define).addConstantPoolIndex(Idx).addImm(0)); 7899 } 7900 BB->addSuccessor(loopMBB); 7901 7902 // Generate the loop body: 7903 // varPhi = PHI(varLoop, varEnd) 7904 // srcPhi = PHI(srcLoop, src) 7905 // destPhi = PHI(destLoop, dst) 7906 MachineBasicBlock *entryBB = BB; 7907 BB = loopMBB; 7908 unsigned varLoop = MRI.createVirtualRegister(TRC); 7909 unsigned varPhi = MRI.createVirtualRegister(TRC); 7910 unsigned srcLoop = MRI.createVirtualRegister(TRC); 7911 unsigned srcPhi = MRI.createVirtualRegister(TRC); 7912 unsigned destLoop = MRI.createVirtualRegister(TRC); 7913 unsigned destPhi = MRI.createVirtualRegister(TRC); 7914 7915 BuildMI(*BB, BB->begin(), dl, TII->get(ARM::PHI), varPhi) 7916 .addReg(varLoop).addMBB(loopMBB) 7917 .addReg(varEnd).addMBB(entryBB); 7918 BuildMI(BB, dl, TII->get(ARM::PHI), srcPhi) 7919 .addReg(srcLoop).addMBB(loopMBB) 7920 .addReg(src).addMBB(entryBB); 7921 BuildMI(BB, dl, TII->get(ARM::PHI), destPhi) 7922 .addReg(destLoop).addMBB(loopMBB) 7923 .addReg(dest).addMBB(entryBB); 7924 7925 // [scratch, srcLoop] = LDR_POST(srcPhi, UnitSize) 7926 // [destLoop] = STR_POST(scratch, destPhi, UnitSiz) 7927 unsigned scratch = MRI.createVirtualRegister(IsNeon ? VecTRC : TRC); 7928 emitPostLd(BB, BB->end(), TII, dl, UnitSize, scratch, srcPhi, srcLoop, 7929 IsThumb1, IsThumb2); 7930 emitPostSt(BB, BB->end(), TII, dl, UnitSize, scratch, destPhi, destLoop, 7931 IsThumb1, IsThumb2); 7932 7933 // Decrement loop variable by UnitSize. 7934 if (IsThumb1) { 7935 MachineInstrBuilder MIB = 7936 BuildMI(*BB, BB->end(), dl, TII->get(ARM::tSUBi8), varLoop); 7937 MIB = AddDefaultT1CC(MIB); 7938 MIB.addReg(varPhi).addImm(UnitSize); 7939 AddDefaultPred(MIB); 7940 } else { 7941 MachineInstrBuilder MIB = 7942 BuildMI(*BB, BB->end(), dl, 7943 TII->get(IsThumb2 ? ARM::t2SUBri : ARM::SUBri), varLoop); 7944 AddDefaultCC(AddDefaultPred(MIB.addReg(varPhi).addImm(UnitSize))); 7945 MIB->getOperand(5).setReg(ARM::CPSR); 7946 MIB->getOperand(5).setIsDef(true); 7947 } 7948 BuildMI(*BB, BB->end(), dl, 7949 TII->get(IsThumb1 ? ARM::tBcc : IsThumb2 ? ARM::t2Bcc : ARM::Bcc)) 7950 .addMBB(loopMBB).addImm(ARMCC::NE).addReg(ARM::CPSR); 7951 7952 // loopMBB can loop back to loopMBB or fall through to exitMBB. 7953 BB->addSuccessor(loopMBB); 7954 BB->addSuccessor(exitMBB); 7955 7956 // Add epilogue to handle BytesLeft. 7957 BB = exitMBB; 7958 MachineInstr *StartOfExit = exitMBB->begin(); 7959 7960 // [scratch, srcOut] = LDRB_POST(srcLoop, 1) 7961 // [destOut] = STRB_POST(scratch, destLoop, 1) 7962 unsigned srcIn = srcLoop; 7963 unsigned destIn = destLoop; 7964 for (unsigned i = 0; i < BytesLeft; i++) { 7965 unsigned srcOut = MRI.createVirtualRegister(TRC); 7966 unsigned destOut = MRI.createVirtualRegister(TRC); 7967 unsigned scratch = MRI.createVirtualRegister(TRC); 7968 emitPostLd(BB, StartOfExit, TII, dl, 1, scratch, srcIn, srcOut, 7969 IsThumb1, IsThumb2); 7970 emitPostSt(BB, StartOfExit, TII, dl, 1, scratch, destIn, destOut, 7971 IsThumb1, IsThumb2); 7972 srcIn = srcOut; 7973 destIn = destOut; 7974 } 7975 7976 MI->eraseFromParent(); // The instruction is gone now. 7977 return BB; 7978 } 7979 7980 MachineBasicBlock * 7981 ARMTargetLowering::EmitLowered__chkstk(MachineInstr *MI, 7982 MachineBasicBlock *MBB) const { 7983 const TargetMachine &TM = getTargetMachine(); 7984 const TargetInstrInfo &TII = *Subtarget->getInstrInfo(); 7985 DebugLoc DL = MI->getDebugLoc(); 7986 7987 assert(Subtarget->isTargetWindows() && 7988 "__chkstk is only supported on Windows"); 7989 assert(Subtarget->isThumb2() && "Windows on ARM requires Thumb-2 mode"); 7990 7991 // __chkstk takes the number of words to allocate on the stack in R4, and 7992 // returns the stack adjustment in number of bytes in R4. This will not 7993 // clober any other registers (other than the obvious lr). 7994 // 7995 // Although, technically, IP should be considered a register which may be 7996 // clobbered, the call itself will not touch it. Windows on ARM is a pure 7997 // thumb-2 environment, so there is no interworking required. As a result, we 7998 // do not expect a veneer to be emitted by the linker, clobbering IP. 7999 // 8000 // Each module receives its own copy of __chkstk, so no import thunk is 8001 // required, again, ensuring that IP is not clobbered. 8002 // 8003 // Finally, although some linkers may theoretically provide a trampoline for 8004 // out of range calls (which is quite common due to a 32M range limitation of 8005 // branches for Thumb), we can generate the long-call version via 8006 // -mcmodel=large, alleviating the need for the trampoline which may clobber 8007 // IP. 8008 8009 switch (TM.getCodeModel()) { 8010 case CodeModel::Small: 8011 case CodeModel::Medium: 8012 case CodeModel::Default: 8013 case CodeModel::Kernel: 8014 BuildMI(*MBB, MI, DL, TII.get(ARM::tBL)) 8015 .addImm((unsigned)ARMCC::AL).addReg(0) 8016 .addExternalSymbol("__chkstk") 8017 .addReg(ARM::R4, RegState::Implicit | RegState::Kill) 8018 .addReg(ARM::R4, RegState::Implicit | RegState::Define) 8019 .addReg(ARM::R12, RegState::Implicit | RegState::Define | RegState::Dead); 8020 break; 8021 case CodeModel::Large: 8022 case CodeModel::JITDefault: { 8023 MachineRegisterInfo &MRI = MBB->getParent()->getRegInfo(); 8024 unsigned Reg = MRI.createVirtualRegister(&ARM::rGPRRegClass); 8025 8026 BuildMI(*MBB, MI, DL, TII.get(ARM::t2MOVi32imm), Reg) 8027 .addExternalSymbol("__chkstk"); 8028 BuildMI(*MBB, MI, DL, TII.get(ARM::tBLXr)) 8029 .addImm((unsigned)ARMCC::AL).addReg(0) 8030 .addReg(Reg, RegState::Kill) 8031 .addReg(ARM::R4, RegState::Implicit | RegState::Kill) 8032 .addReg(ARM::R4, RegState::Implicit | RegState::Define) 8033 .addReg(ARM::R12, RegState::Implicit | RegState::Define | RegState::Dead); 8034 break; 8035 } 8036 } 8037 8038 AddDefaultCC(AddDefaultPred(BuildMI(*MBB, MI, DL, TII.get(ARM::t2SUBrr), 8039 ARM::SP) 8040 .addReg(ARM::SP).addReg(ARM::R4))); 8041 8042 MI->eraseFromParent(); 8043 return MBB; 8044 } 8045 8046 MachineBasicBlock * 8047 ARMTargetLowering::EmitLowered__dbzchk(MachineInstr *MI, 8048 MachineBasicBlock *MBB) const { 8049 DebugLoc DL = MI->getDebugLoc(); 8050 MachineFunction *MF = MBB->getParent(); 8051 const TargetInstrInfo *TII = Subtarget->getInstrInfo(); 8052 8053 MachineBasicBlock *ContBB = MF->CreateMachineBasicBlock(); 8054 MF->insert(++MBB->getIterator(), ContBB); 8055 ContBB->splice(ContBB->begin(), MBB, 8056 std::next(MachineBasicBlock::iterator(MI)), MBB->end()); 8057 ContBB->transferSuccessorsAndUpdatePHIs(MBB); 8058 8059 MachineBasicBlock *TrapBB = MF->CreateMachineBasicBlock(); 8060 MF->push_back(TrapBB); 8061 BuildMI(TrapBB, DL, TII->get(ARM::t2UDF)).addImm(249); 8062 MBB->addSuccessor(TrapBB); 8063 8064 BuildMI(*MBB, MI, DL, TII->get(ARM::tCBZ)) 8065 .addReg(MI->getOperand(0).getReg()) 8066 .addMBB(TrapBB); 8067 AddDefaultPred(BuildMI(*MBB, MI, DL, TII->get(ARM::t2B)).addMBB(ContBB)); 8068 MBB->addSuccessor(ContBB); 8069 8070 MI->eraseFromParent(); 8071 return ContBB; 8072 } 8073 8074 MachineBasicBlock * 8075 ARMTargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI, 8076 MachineBasicBlock *BB) const { 8077 const TargetInstrInfo *TII = Subtarget->getInstrInfo(); 8078 DebugLoc dl = MI->getDebugLoc(); 8079 bool isThumb2 = Subtarget->isThumb2(); 8080 switch (MI->getOpcode()) { 8081 default: { 8082 MI->dump(); 8083 llvm_unreachable("Unexpected instr type to insert"); 8084 } 8085 // The Thumb2 pre-indexed stores have the same MI operands, they just 8086 // define them differently in the .td files from the isel patterns, so 8087 // they need pseudos. 8088 case ARM::t2STR_preidx: 8089 MI->setDesc(TII->get(ARM::t2STR_PRE)); 8090 return BB; 8091 case ARM::t2STRB_preidx: 8092 MI->setDesc(TII->get(ARM::t2STRB_PRE)); 8093 return BB; 8094 case ARM::t2STRH_preidx: 8095 MI->setDesc(TII->get(ARM::t2STRH_PRE)); 8096 return BB; 8097 8098 case ARM::STRi_preidx: 8099 case ARM::STRBi_preidx: { 8100 unsigned NewOpc = MI->getOpcode() == ARM::STRi_preidx ? 8101 ARM::STR_PRE_IMM : ARM::STRB_PRE_IMM; 8102 // Decode the offset. 8103 unsigned Offset = MI->getOperand(4).getImm(); 8104 bool isSub = ARM_AM::getAM2Op(Offset) == ARM_AM::sub; 8105 Offset = ARM_AM::getAM2Offset(Offset); 8106 if (isSub) 8107 Offset = -Offset; 8108 8109 MachineMemOperand *MMO = *MI->memoperands_begin(); 8110 BuildMI(*BB, MI, dl, TII->get(NewOpc)) 8111 .addOperand(MI->getOperand(0)) // Rn_wb 8112 .addOperand(MI->getOperand(1)) // Rt 8113 .addOperand(MI->getOperand(2)) // Rn 8114 .addImm(Offset) // offset (skip GPR==zero_reg) 8115 .addOperand(MI->getOperand(5)) // pred 8116 .addOperand(MI->getOperand(6)) 8117 .addMemOperand(MMO); 8118 MI->eraseFromParent(); 8119 return BB; 8120 } 8121 case ARM::STRr_preidx: 8122 case ARM::STRBr_preidx: 8123 case ARM::STRH_preidx: { 8124 unsigned NewOpc; 8125 switch (MI->getOpcode()) { 8126 default: llvm_unreachable("unexpected opcode!"); 8127 case ARM::STRr_preidx: NewOpc = ARM::STR_PRE_REG; break; 8128 case ARM::STRBr_preidx: NewOpc = ARM::STRB_PRE_REG; break; 8129 case ARM::STRH_preidx: NewOpc = ARM::STRH_PRE; break; 8130 } 8131 MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(NewOpc)); 8132 for (unsigned i = 0; i < MI->getNumOperands(); ++i) 8133 MIB.addOperand(MI->getOperand(i)); 8134 MI->eraseFromParent(); 8135 return BB; 8136 } 8137 8138 case ARM::tMOVCCr_pseudo: { 8139 // To "insert" a SELECT_CC instruction, we actually have to insert the 8140 // diamond control-flow pattern. The incoming instruction knows the 8141 // destination vreg to set, the condition code register to branch on, the 8142 // true/false values to select between, and a branch opcode to use. 8143 const BasicBlock *LLVM_BB = BB->getBasicBlock(); 8144 MachineFunction::iterator It = ++BB->getIterator(); 8145 8146 // thisMBB: 8147 // ... 8148 // TrueVal = ... 8149 // cmpTY ccX, r1, r2 8150 // bCC copy1MBB 8151 // fallthrough --> copy0MBB 8152 MachineBasicBlock *thisMBB = BB; 8153 MachineFunction *F = BB->getParent(); 8154 MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB); 8155 MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB); 8156 F->insert(It, copy0MBB); 8157 F->insert(It, sinkMBB); 8158 8159 // Transfer the remainder of BB and its successor edges to sinkMBB. 8160 sinkMBB->splice(sinkMBB->begin(), BB, 8161 std::next(MachineBasicBlock::iterator(MI)), BB->end()); 8162 sinkMBB->transferSuccessorsAndUpdatePHIs(BB); 8163 8164 BB->addSuccessor(copy0MBB); 8165 BB->addSuccessor(sinkMBB); 8166 8167 BuildMI(BB, dl, TII->get(ARM::tBcc)).addMBB(sinkMBB) 8168 .addImm(MI->getOperand(3).getImm()).addReg(MI->getOperand(4).getReg()); 8169 8170 // copy0MBB: 8171 // %FalseValue = ... 8172 // # fallthrough to sinkMBB 8173 BB = copy0MBB; 8174 8175 // Update machine-CFG edges 8176 BB->addSuccessor(sinkMBB); 8177 8178 // sinkMBB: 8179 // %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ] 8180 // ... 8181 BB = sinkMBB; 8182 BuildMI(*BB, BB->begin(), dl, 8183 TII->get(ARM::PHI), MI->getOperand(0).getReg()) 8184 .addReg(MI->getOperand(1).getReg()).addMBB(copy0MBB) 8185 .addReg(MI->getOperand(2).getReg()).addMBB(thisMBB); 8186 8187 MI->eraseFromParent(); // The pseudo instruction is gone now. 8188 return BB; 8189 } 8190 8191 case ARM::BCCi64: 8192 case ARM::BCCZi64: { 8193 // If there is an unconditional branch to the other successor, remove it. 8194 BB->erase(std::next(MachineBasicBlock::iterator(MI)), BB->end()); 8195 8196 // Compare both parts that make up the double comparison separately for 8197 // equality. 8198 bool RHSisZero = MI->getOpcode() == ARM::BCCZi64; 8199 8200 unsigned LHS1 = MI->getOperand(1).getReg(); 8201 unsigned LHS2 = MI->getOperand(2).getReg(); 8202 if (RHSisZero) { 8203 AddDefaultPred(BuildMI(BB, dl, 8204 TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri)) 8205 .addReg(LHS1).addImm(0)); 8206 BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri)) 8207 .addReg(LHS2).addImm(0) 8208 .addImm(ARMCC::EQ).addReg(ARM::CPSR); 8209 } else { 8210 unsigned RHS1 = MI->getOperand(3).getReg(); 8211 unsigned RHS2 = MI->getOperand(4).getReg(); 8212 AddDefaultPred(BuildMI(BB, dl, 8213 TII->get(isThumb2 ? ARM::t2CMPrr : ARM::CMPrr)) 8214 .addReg(LHS1).addReg(RHS1)); 8215 BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPrr : ARM::CMPrr)) 8216 .addReg(LHS2).addReg(RHS2) 8217 .addImm(ARMCC::EQ).addReg(ARM::CPSR); 8218 } 8219 8220 MachineBasicBlock *destMBB = MI->getOperand(RHSisZero ? 3 : 5).getMBB(); 8221 MachineBasicBlock *exitMBB = OtherSucc(BB, destMBB); 8222 if (MI->getOperand(0).getImm() == ARMCC::NE) 8223 std::swap(destMBB, exitMBB); 8224 8225 BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc)) 8226 .addMBB(destMBB).addImm(ARMCC::EQ).addReg(ARM::CPSR); 8227 if (isThumb2) 8228 AddDefaultPred(BuildMI(BB, dl, TII->get(ARM::t2B)).addMBB(exitMBB)); 8229 else 8230 BuildMI(BB, dl, TII->get(ARM::B)) .addMBB(exitMBB); 8231 8232 MI->eraseFromParent(); // The pseudo instruction is gone now. 8233 return BB; 8234 } 8235 8236 case ARM::Int_eh_sjlj_setjmp: 8237 case ARM::Int_eh_sjlj_setjmp_nofp: 8238 case ARM::tInt_eh_sjlj_setjmp: 8239 case ARM::t2Int_eh_sjlj_setjmp: 8240 case ARM::t2Int_eh_sjlj_setjmp_nofp: 8241 return BB; 8242 8243 case ARM::Int_eh_sjlj_setup_dispatch: 8244 EmitSjLjDispatchBlock(MI, BB); 8245 return BB; 8246 8247 case ARM::ABS: 8248 case ARM::t2ABS: { 8249 // To insert an ABS instruction, we have to insert the 8250 // diamond control-flow pattern. The incoming instruction knows the 8251 // source vreg to test against 0, the destination vreg to set, 8252 // the condition code register to branch on, the 8253 // true/false values to select between, and a branch opcode to use. 8254 // It transforms 8255 // V1 = ABS V0 8256 // into 8257 // V2 = MOVS V0 8258 // BCC (branch to SinkBB if V0 >= 0) 8259 // RSBBB: V3 = RSBri V2, 0 (compute ABS if V2 < 0) 8260 // SinkBB: V1 = PHI(V2, V3) 8261 const BasicBlock *LLVM_BB = BB->getBasicBlock(); 8262 MachineFunction::iterator BBI = ++BB->getIterator(); 8263 MachineFunction *Fn = BB->getParent(); 8264 MachineBasicBlock *RSBBB = Fn->CreateMachineBasicBlock(LLVM_BB); 8265 MachineBasicBlock *SinkBB = Fn->CreateMachineBasicBlock(LLVM_BB); 8266 Fn->insert(BBI, RSBBB); 8267 Fn->insert(BBI, SinkBB); 8268 8269 unsigned int ABSSrcReg = MI->getOperand(1).getReg(); 8270 unsigned int ABSDstReg = MI->getOperand(0).getReg(); 8271 bool ABSSrcKIll = MI->getOperand(1).isKill(); 8272 bool isThumb2 = Subtarget->isThumb2(); 8273 MachineRegisterInfo &MRI = Fn->getRegInfo(); 8274 // In Thumb mode S must not be specified if source register is the SP or 8275 // PC and if destination register is the SP, so restrict register class 8276 unsigned NewRsbDstReg = 8277 MRI.createVirtualRegister(isThumb2 ? &ARM::rGPRRegClass : &ARM::GPRRegClass); 8278 8279 // Transfer the remainder of BB and its successor edges to sinkMBB. 8280 SinkBB->splice(SinkBB->begin(), BB, 8281 std::next(MachineBasicBlock::iterator(MI)), BB->end()); 8282 SinkBB->transferSuccessorsAndUpdatePHIs(BB); 8283 8284 BB->addSuccessor(RSBBB); 8285 BB->addSuccessor(SinkBB); 8286 8287 // fall through to SinkMBB 8288 RSBBB->addSuccessor(SinkBB); 8289 8290 // insert a cmp at the end of BB 8291 AddDefaultPred(BuildMI(BB, dl, 8292 TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri)) 8293 .addReg(ABSSrcReg).addImm(0)); 8294 8295 // insert a bcc with opposite CC to ARMCC::MI at the end of BB 8296 BuildMI(BB, dl, 8297 TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc)).addMBB(SinkBB) 8298 .addImm(ARMCC::getOppositeCondition(ARMCC::MI)).addReg(ARM::CPSR); 8299 8300 // insert rsbri in RSBBB 8301 // Note: BCC and rsbri will be converted into predicated rsbmi 8302 // by if-conversion pass 8303 BuildMI(*RSBBB, RSBBB->begin(), dl, 8304 TII->get(isThumb2 ? ARM::t2RSBri : ARM::RSBri), NewRsbDstReg) 8305 .addReg(ABSSrcReg, ABSSrcKIll ? RegState::Kill : 0) 8306 .addImm(0).addImm((unsigned)ARMCC::AL).addReg(0).addReg(0); 8307 8308 // insert PHI in SinkBB, 8309 // reuse ABSDstReg to not change uses of ABS instruction 8310 BuildMI(*SinkBB, SinkBB->begin(), dl, 8311 TII->get(ARM::PHI), ABSDstReg) 8312 .addReg(NewRsbDstReg).addMBB(RSBBB) 8313 .addReg(ABSSrcReg).addMBB(BB); 8314 8315 // remove ABS instruction 8316 MI->eraseFromParent(); 8317 8318 // return last added BB 8319 return SinkBB; 8320 } 8321 case ARM::COPY_STRUCT_BYVAL_I32: 8322 ++NumLoopByVals; 8323 return EmitStructByval(MI, BB); 8324 case ARM::WIN__CHKSTK: 8325 return EmitLowered__chkstk(MI, BB); 8326 case ARM::WIN__DBZCHK: 8327 return EmitLowered__dbzchk(MI, BB); 8328 } 8329 } 8330 8331 /// \brief Attaches vregs to MEMCPY that it will use as scratch registers 8332 /// when it is expanded into LDM/STM. This is done as a post-isel lowering 8333 /// instead of as a custom inserter because we need the use list from the SDNode. 8334 static void attachMEMCPYScratchRegs(const ARMSubtarget *Subtarget, 8335 MachineInstr *MI, const SDNode *Node) { 8336 bool isThumb1 = Subtarget->isThumb1Only(); 8337 8338 DebugLoc DL = MI->getDebugLoc(); 8339 MachineFunction *MF = MI->getParent()->getParent(); 8340 MachineRegisterInfo &MRI = MF->getRegInfo(); 8341 MachineInstrBuilder MIB(*MF, MI); 8342 8343 // If the new dst/src is unused mark it as dead. 8344 if (!Node->hasAnyUseOfValue(0)) { 8345 MI->getOperand(0).setIsDead(true); 8346 } 8347 if (!Node->hasAnyUseOfValue(1)) { 8348 MI->getOperand(1).setIsDead(true); 8349 } 8350 8351 // The MEMCPY both defines and kills the scratch registers. 8352 for (unsigned I = 0; I != MI->getOperand(4).getImm(); ++I) { 8353 unsigned TmpReg = MRI.createVirtualRegister(isThumb1 ? &ARM::tGPRRegClass 8354 : &ARM::GPRRegClass); 8355 MIB.addReg(TmpReg, RegState::Define|RegState::Dead); 8356 } 8357 } 8358 8359 void ARMTargetLowering::AdjustInstrPostInstrSelection(MachineInstr *MI, 8360 SDNode *Node) const { 8361 if (MI->getOpcode() == ARM::MEMCPY) { 8362 attachMEMCPYScratchRegs(Subtarget, MI, Node); 8363 return; 8364 } 8365 8366 const MCInstrDesc *MCID = &MI->getDesc(); 8367 // Adjust potentially 's' setting instructions after isel, i.e. ADC, SBC, RSB, 8368 // RSC. Coming out of isel, they have an implicit CPSR def, but the optional 8369 // operand is still set to noreg. If needed, set the optional operand's 8370 // register to CPSR, and remove the redundant implicit def. 8371 // 8372 // e.g. ADCS (..., CPSR<imp-def>) -> ADC (... opt:CPSR<def>). 8373 8374 // Rename pseudo opcodes. 8375 unsigned NewOpc = convertAddSubFlagsOpcode(MI->getOpcode()); 8376 if (NewOpc) { 8377 const ARMBaseInstrInfo *TII = Subtarget->getInstrInfo(); 8378 MCID = &TII->get(NewOpc); 8379 8380 assert(MCID->getNumOperands() == MI->getDesc().getNumOperands() + 1 && 8381 "converted opcode should be the same except for cc_out"); 8382 8383 MI->setDesc(*MCID); 8384 8385 // Add the optional cc_out operand 8386 MI->addOperand(MachineOperand::CreateReg(0, /*isDef=*/true)); 8387 } 8388 unsigned ccOutIdx = MCID->getNumOperands() - 1; 8389 8390 // Any ARM instruction that sets the 's' bit should specify an optional 8391 // "cc_out" operand in the last operand position. 8392 if (!MI->hasOptionalDef() || !MCID->OpInfo[ccOutIdx].isOptionalDef()) { 8393 assert(!NewOpc && "Optional cc_out operand required"); 8394 return; 8395 } 8396 // Look for an implicit def of CPSR added by MachineInstr ctor. Remove it 8397 // since we already have an optional CPSR def. 8398 bool definesCPSR = false; 8399 bool deadCPSR = false; 8400 for (unsigned i = MCID->getNumOperands(), e = MI->getNumOperands(); 8401 i != e; ++i) { 8402 const MachineOperand &MO = MI->getOperand(i); 8403 if (MO.isReg() && MO.isDef() && MO.getReg() == ARM::CPSR) { 8404 definesCPSR = true; 8405 if (MO.isDead()) 8406 deadCPSR = true; 8407 MI->RemoveOperand(i); 8408 break; 8409 } 8410 } 8411 if (!definesCPSR) { 8412 assert(!NewOpc && "Optional cc_out operand required"); 8413 return; 8414 } 8415 assert(deadCPSR == !Node->hasAnyUseOfValue(1) && "inconsistent dead flag"); 8416 if (deadCPSR) { 8417 assert(!MI->getOperand(ccOutIdx).getReg() && 8418 "expect uninitialized optional cc_out operand"); 8419 return; 8420 } 8421 8422 // If this instruction was defined with an optional CPSR def and its dag node 8423 // had a live implicit CPSR def, then activate the optional CPSR def. 8424 MachineOperand &MO = MI->getOperand(ccOutIdx); 8425 MO.setReg(ARM::CPSR); 8426 MO.setIsDef(true); 8427 } 8428 8429 //===----------------------------------------------------------------------===// 8430 // ARM Optimization Hooks 8431 //===----------------------------------------------------------------------===// 8432 8433 // Helper function that checks if N is a null or all ones constant. 8434 static inline bool isZeroOrAllOnes(SDValue N, bool AllOnes) { 8435 return AllOnes ? isAllOnesConstant(N) : isNullConstant(N); 8436 } 8437 8438 // Return true if N is conditionally 0 or all ones. 8439 // Detects these expressions where cc is an i1 value: 8440 // 8441 // (select cc 0, y) [AllOnes=0] 8442 // (select cc y, 0) [AllOnes=0] 8443 // (zext cc) [AllOnes=0] 8444 // (sext cc) [AllOnes=0/1] 8445 // (select cc -1, y) [AllOnes=1] 8446 // (select cc y, -1) [AllOnes=1] 8447 // 8448 // Invert is set when N is the null/all ones constant when CC is false. 8449 // OtherOp is set to the alternative value of N. 8450 static bool isConditionalZeroOrAllOnes(SDNode *N, bool AllOnes, 8451 SDValue &CC, bool &Invert, 8452 SDValue &OtherOp, 8453 SelectionDAG &DAG) { 8454 switch (N->getOpcode()) { 8455 default: return false; 8456 case ISD::SELECT: { 8457 CC = N->getOperand(0); 8458 SDValue N1 = N->getOperand(1); 8459 SDValue N2 = N->getOperand(2); 8460 if (isZeroOrAllOnes(N1, AllOnes)) { 8461 Invert = false; 8462 OtherOp = N2; 8463 return true; 8464 } 8465 if (isZeroOrAllOnes(N2, AllOnes)) { 8466 Invert = true; 8467 OtherOp = N1; 8468 return true; 8469 } 8470 return false; 8471 } 8472 case ISD::ZERO_EXTEND: 8473 // (zext cc) can never be the all ones value. 8474 if (AllOnes) 8475 return false; 8476 // Fall through. 8477 case ISD::SIGN_EXTEND: { 8478 SDLoc dl(N); 8479 EVT VT = N->getValueType(0); 8480 CC = N->getOperand(0); 8481 if (CC.getValueType() != MVT::i1) 8482 return false; 8483 Invert = !AllOnes; 8484 if (AllOnes) 8485 // When looking for an AllOnes constant, N is an sext, and the 'other' 8486 // value is 0. 8487 OtherOp = DAG.getConstant(0, dl, VT); 8488 else if (N->getOpcode() == ISD::ZERO_EXTEND) 8489 // When looking for a 0 constant, N can be zext or sext. 8490 OtherOp = DAG.getConstant(1, dl, VT); 8491 else 8492 OtherOp = DAG.getConstant(APInt::getAllOnesValue(VT.getSizeInBits()), dl, 8493 VT); 8494 return true; 8495 } 8496 } 8497 } 8498 8499 // Combine a constant select operand into its use: 8500 // 8501 // (add (select cc, 0, c), x) -> (select cc, x, (add, x, c)) 8502 // (sub x, (select cc, 0, c)) -> (select cc, x, (sub, x, c)) 8503 // (and (select cc, -1, c), x) -> (select cc, x, (and, x, c)) [AllOnes=1] 8504 // (or (select cc, 0, c), x) -> (select cc, x, (or, x, c)) 8505 // (xor (select cc, 0, c), x) -> (select cc, x, (xor, x, c)) 8506 // 8507 // The transform is rejected if the select doesn't have a constant operand that 8508 // is null, or all ones when AllOnes is set. 8509 // 8510 // Also recognize sext/zext from i1: 8511 // 8512 // (add (zext cc), x) -> (select cc (add x, 1), x) 8513 // (add (sext cc), x) -> (select cc (add x, -1), x) 8514 // 8515 // These transformations eventually create predicated instructions. 8516 // 8517 // @param N The node to transform. 8518 // @param Slct The N operand that is a select. 8519 // @param OtherOp The other N operand (x above). 8520 // @param DCI Context. 8521 // @param AllOnes Require the select constant to be all ones instead of null. 8522 // @returns The new node, or SDValue() on failure. 8523 static 8524 SDValue combineSelectAndUse(SDNode *N, SDValue Slct, SDValue OtherOp, 8525 TargetLowering::DAGCombinerInfo &DCI, 8526 bool AllOnes = false) { 8527 SelectionDAG &DAG = DCI.DAG; 8528 EVT VT = N->getValueType(0); 8529 SDValue NonConstantVal; 8530 SDValue CCOp; 8531 bool SwapSelectOps; 8532 if (!isConditionalZeroOrAllOnes(Slct.getNode(), AllOnes, CCOp, SwapSelectOps, 8533 NonConstantVal, DAG)) 8534 return SDValue(); 8535 8536 // Slct is now know to be the desired identity constant when CC is true. 8537 SDValue TrueVal = OtherOp; 8538 SDValue FalseVal = DAG.getNode(N->getOpcode(), SDLoc(N), VT, 8539 OtherOp, NonConstantVal); 8540 // Unless SwapSelectOps says CC should be false. 8541 if (SwapSelectOps) 8542 std::swap(TrueVal, FalseVal); 8543 8544 return DAG.getNode(ISD::SELECT, SDLoc(N), VT, 8545 CCOp, TrueVal, FalseVal); 8546 } 8547 8548 // Attempt combineSelectAndUse on each operand of a commutative operator N. 8549 static 8550 SDValue combineSelectAndUseCommutative(SDNode *N, bool AllOnes, 8551 TargetLowering::DAGCombinerInfo &DCI) { 8552 SDValue N0 = N->getOperand(0); 8553 SDValue N1 = N->getOperand(1); 8554 if (N0.getNode()->hasOneUse()) 8555 if (SDValue Result = combineSelectAndUse(N, N0, N1, DCI, AllOnes)) 8556 return Result; 8557 if (N1.getNode()->hasOneUse()) 8558 if (SDValue Result = combineSelectAndUse(N, N1, N0, DCI, AllOnes)) 8559 return Result; 8560 return SDValue(); 8561 } 8562 8563 // AddCombineToVPADDL- For pair-wise add on neon, use the vpaddl instruction 8564 // (only after legalization). 8565 static SDValue AddCombineToVPADDL(SDNode *N, SDValue N0, SDValue N1, 8566 TargetLowering::DAGCombinerInfo &DCI, 8567 const ARMSubtarget *Subtarget) { 8568 8569 // Only perform optimization if after legalize, and if NEON is available. We 8570 // also expected both operands to be BUILD_VECTORs. 8571 if (DCI.isBeforeLegalize() || !Subtarget->hasNEON() 8572 || N0.getOpcode() != ISD::BUILD_VECTOR 8573 || N1.getOpcode() != ISD::BUILD_VECTOR) 8574 return SDValue(); 8575 8576 // Check output type since VPADDL operand elements can only be 8, 16, or 32. 8577 EVT VT = N->getValueType(0); 8578 if (!VT.isInteger() || VT.getVectorElementType() == MVT::i64) 8579 return SDValue(); 8580 8581 // Check that the vector operands are of the right form. 8582 // N0 and N1 are BUILD_VECTOR nodes with N number of EXTRACT_VECTOR 8583 // operands, where N is the size of the formed vector. 8584 // Each EXTRACT_VECTOR should have the same input vector and odd or even 8585 // index such that we have a pair wise add pattern. 8586 8587 // Grab the vector that all EXTRACT_VECTOR nodes should be referencing. 8588 if (N0->getOperand(0)->getOpcode() != ISD::EXTRACT_VECTOR_ELT) 8589 return SDValue(); 8590 SDValue Vec = N0->getOperand(0)->getOperand(0); 8591 SDNode *V = Vec.getNode(); 8592 unsigned nextIndex = 0; 8593 8594 // For each operands to the ADD which are BUILD_VECTORs, 8595 // check to see if each of their operands are an EXTRACT_VECTOR with 8596 // the same vector and appropriate index. 8597 for (unsigned i = 0, e = N0->getNumOperands(); i != e; ++i) { 8598 if (N0->getOperand(i)->getOpcode() == ISD::EXTRACT_VECTOR_ELT 8599 && N1->getOperand(i)->getOpcode() == ISD::EXTRACT_VECTOR_ELT) { 8600 8601 SDValue ExtVec0 = N0->getOperand(i); 8602 SDValue ExtVec1 = N1->getOperand(i); 8603 8604 // First operand is the vector, verify its the same. 8605 if (V != ExtVec0->getOperand(0).getNode() || 8606 V != ExtVec1->getOperand(0).getNode()) 8607 return SDValue(); 8608 8609 // Second is the constant, verify its correct. 8610 ConstantSDNode *C0 = dyn_cast<ConstantSDNode>(ExtVec0->getOperand(1)); 8611 ConstantSDNode *C1 = dyn_cast<ConstantSDNode>(ExtVec1->getOperand(1)); 8612 8613 // For the constant, we want to see all the even or all the odd. 8614 if (!C0 || !C1 || C0->getZExtValue() != nextIndex 8615 || C1->getZExtValue() != nextIndex+1) 8616 return SDValue(); 8617 8618 // Increment index. 8619 nextIndex+=2; 8620 } else 8621 return SDValue(); 8622 } 8623 8624 // Create VPADDL node. 8625 SelectionDAG &DAG = DCI.DAG; 8626 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 8627 8628 SDLoc dl(N); 8629 8630 // Build operand list. 8631 SmallVector<SDValue, 8> Ops; 8632 Ops.push_back(DAG.getConstant(Intrinsic::arm_neon_vpaddls, dl, 8633 TLI.getPointerTy(DAG.getDataLayout()))); 8634 8635 // Input is the vector. 8636 Ops.push_back(Vec); 8637 8638 // Get widened type and narrowed type. 8639 MVT widenType; 8640 unsigned numElem = VT.getVectorNumElements(); 8641 8642 EVT inputLaneType = Vec.getValueType().getVectorElementType(); 8643 switch (inputLaneType.getSimpleVT().SimpleTy) { 8644 case MVT::i8: widenType = MVT::getVectorVT(MVT::i16, numElem); break; 8645 case MVT::i16: widenType = MVT::getVectorVT(MVT::i32, numElem); break; 8646 case MVT::i32: widenType = MVT::getVectorVT(MVT::i64, numElem); break; 8647 default: 8648 llvm_unreachable("Invalid vector element type for padd optimization."); 8649 } 8650 8651 SDValue tmp = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, widenType, Ops); 8652 unsigned ExtOp = VT.bitsGT(tmp.getValueType()) ? ISD::ANY_EXTEND : ISD::TRUNCATE; 8653 return DAG.getNode(ExtOp, dl, VT, tmp); 8654 } 8655 8656 static SDValue findMUL_LOHI(SDValue V) { 8657 if (V->getOpcode() == ISD::UMUL_LOHI || 8658 V->getOpcode() == ISD::SMUL_LOHI) 8659 return V; 8660 return SDValue(); 8661 } 8662 8663 static SDValue AddCombineTo64bitMLAL(SDNode *AddcNode, 8664 TargetLowering::DAGCombinerInfo &DCI, 8665 const ARMSubtarget *Subtarget) { 8666 8667 if (Subtarget->isThumb1Only()) return SDValue(); 8668 8669 // Only perform the checks after legalize when the pattern is available. 8670 if (DCI.isBeforeLegalize()) return SDValue(); 8671 8672 // Look for multiply add opportunities. 8673 // The pattern is a ISD::UMUL_LOHI followed by two add nodes, where 8674 // each add nodes consumes a value from ISD::UMUL_LOHI and there is 8675 // a glue link from the first add to the second add. 8676 // If we find this pattern, we can replace the U/SMUL_LOHI, ADDC, and ADDE by 8677 // a S/UMLAL instruction. 8678 // UMUL_LOHI 8679 // / :lo \ :hi 8680 // / \ [no multiline comment] 8681 // loAdd -> ADDE | 8682 // \ :glue / 8683 // \ / 8684 // ADDC <- hiAdd 8685 // 8686 assert(AddcNode->getOpcode() == ISD::ADDC && "Expect an ADDC"); 8687 SDValue AddcOp0 = AddcNode->getOperand(0); 8688 SDValue AddcOp1 = AddcNode->getOperand(1); 8689 8690 // Check if the two operands are from the same mul_lohi node. 8691 if (AddcOp0.getNode() == AddcOp1.getNode()) 8692 return SDValue(); 8693 8694 assert(AddcNode->getNumValues() == 2 && 8695 AddcNode->getValueType(0) == MVT::i32 && 8696 "Expect ADDC with two result values. First: i32"); 8697 8698 // Check that we have a glued ADDC node. 8699 if (AddcNode->getValueType(1) != MVT::Glue) 8700 return SDValue(); 8701 8702 // Check that the ADDC adds the low result of the S/UMUL_LOHI. 8703 if (AddcOp0->getOpcode() != ISD::UMUL_LOHI && 8704 AddcOp0->getOpcode() != ISD::SMUL_LOHI && 8705 AddcOp1->getOpcode() != ISD::UMUL_LOHI && 8706 AddcOp1->getOpcode() != ISD::SMUL_LOHI) 8707 return SDValue(); 8708 8709 // Look for the glued ADDE. 8710 SDNode* AddeNode = AddcNode->getGluedUser(); 8711 if (!AddeNode) 8712 return SDValue(); 8713 8714 // Make sure it is really an ADDE. 8715 if (AddeNode->getOpcode() != ISD::ADDE) 8716 return SDValue(); 8717 8718 assert(AddeNode->getNumOperands() == 3 && 8719 AddeNode->getOperand(2).getValueType() == MVT::Glue && 8720 "ADDE node has the wrong inputs"); 8721 8722 // Check for the triangle shape. 8723 SDValue AddeOp0 = AddeNode->getOperand(0); 8724 SDValue AddeOp1 = AddeNode->getOperand(1); 8725 8726 // Make sure that the ADDE operands are not coming from the same node. 8727 if (AddeOp0.getNode() == AddeOp1.getNode()) 8728 return SDValue(); 8729 8730 // Find the MUL_LOHI node walking up ADDE's operands. 8731 bool IsLeftOperandMUL = false; 8732 SDValue MULOp = findMUL_LOHI(AddeOp0); 8733 if (MULOp == SDValue()) 8734 MULOp = findMUL_LOHI(AddeOp1); 8735 else 8736 IsLeftOperandMUL = true; 8737 if (MULOp == SDValue()) 8738 return SDValue(); 8739 8740 // Figure out the right opcode. 8741 unsigned Opc = MULOp->getOpcode(); 8742 unsigned FinalOpc = (Opc == ISD::SMUL_LOHI) ? ARMISD::SMLAL : ARMISD::UMLAL; 8743 8744 // Figure out the high and low input values to the MLAL node. 8745 SDValue* HiAdd = nullptr; 8746 SDValue* LoMul = nullptr; 8747 SDValue* LowAdd = nullptr; 8748 8749 // Ensure that ADDE is from high result of ISD::SMUL_LOHI. 8750 if ((AddeOp0 != MULOp.getValue(1)) && (AddeOp1 != MULOp.getValue(1))) 8751 return SDValue(); 8752 8753 if (IsLeftOperandMUL) 8754 HiAdd = &AddeOp1; 8755 else 8756 HiAdd = &AddeOp0; 8757 8758 8759 // Ensure that LoMul and LowAdd are taken from correct ISD::SMUL_LOHI node 8760 // whose low result is fed to the ADDC we are checking. 8761 8762 if (AddcOp0 == MULOp.getValue(0)) { 8763 LoMul = &AddcOp0; 8764 LowAdd = &AddcOp1; 8765 } 8766 if (AddcOp1 == MULOp.getValue(0)) { 8767 LoMul = &AddcOp1; 8768 LowAdd = &AddcOp0; 8769 } 8770 8771 if (!LoMul) 8772 return SDValue(); 8773 8774 // Create the merged node. 8775 SelectionDAG &DAG = DCI.DAG; 8776 8777 // Build operand list. 8778 SmallVector<SDValue, 8> Ops; 8779 Ops.push_back(LoMul->getOperand(0)); 8780 Ops.push_back(LoMul->getOperand(1)); 8781 Ops.push_back(*LowAdd); 8782 Ops.push_back(*HiAdd); 8783 8784 SDValue MLALNode = DAG.getNode(FinalOpc, SDLoc(AddcNode), 8785 DAG.getVTList(MVT::i32, MVT::i32), Ops); 8786 8787 // Replace the ADDs' nodes uses by the MLA node's values. 8788 SDValue HiMLALResult(MLALNode.getNode(), 1); 8789 DAG.ReplaceAllUsesOfValueWith(SDValue(AddeNode, 0), HiMLALResult); 8790 8791 SDValue LoMLALResult(MLALNode.getNode(), 0); 8792 DAG.ReplaceAllUsesOfValueWith(SDValue(AddcNode, 0), LoMLALResult); 8793 8794 // Return original node to notify the driver to stop replacing. 8795 SDValue resNode(AddcNode, 0); 8796 return resNode; 8797 } 8798 8799 /// PerformADDCCombine - Target-specific dag combine transform from 8800 /// ISD::ADDC, ISD::ADDE, and ISD::MUL_LOHI to MLAL. 8801 static SDValue PerformADDCCombine(SDNode *N, 8802 TargetLowering::DAGCombinerInfo &DCI, 8803 const ARMSubtarget *Subtarget) { 8804 8805 return AddCombineTo64bitMLAL(N, DCI, Subtarget); 8806 8807 } 8808 8809 /// PerformADDCombineWithOperands - Try DAG combinations for an ADD with 8810 /// operands N0 and N1. This is a helper for PerformADDCombine that is 8811 /// called with the default operands, and if that fails, with commuted 8812 /// operands. 8813 static SDValue PerformADDCombineWithOperands(SDNode *N, SDValue N0, SDValue N1, 8814 TargetLowering::DAGCombinerInfo &DCI, 8815 const ARMSubtarget *Subtarget){ 8816 8817 // Attempt to create vpaddl for this add. 8818 if (SDValue Result = AddCombineToVPADDL(N, N0, N1, DCI, Subtarget)) 8819 return Result; 8820 8821 // fold (add (select cc, 0, c), x) -> (select cc, x, (add, x, c)) 8822 if (N0.getNode()->hasOneUse()) 8823 if (SDValue Result = combineSelectAndUse(N, N0, N1, DCI)) 8824 return Result; 8825 return SDValue(); 8826 } 8827 8828 /// PerformADDCombine - Target-specific dag combine xforms for ISD::ADD. 8829 /// 8830 static SDValue PerformADDCombine(SDNode *N, 8831 TargetLowering::DAGCombinerInfo &DCI, 8832 const ARMSubtarget *Subtarget) { 8833 SDValue N0 = N->getOperand(0); 8834 SDValue N1 = N->getOperand(1); 8835 8836 // First try with the default operand order. 8837 if (SDValue Result = PerformADDCombineWithOperands(N, N0, N1, DCI, Subtarget)) 8838 return Result; 8839 8840 // If that didn't work, try again with the operands commuted. 8841 return PerformADDCombineWithOperands(N, N1, N0, DCI, Subtarget); 8842 } 8843 8844 /// PerformSUBCombine - Target-specific dag combine xforms for ISD::SUB. 8845 /// 8846 static SDValue PerformSUBCombine(SDNode *N, 8847 TargetLowering::DAGCombinerInfo &DCI) { 8848 SDValue N0 = N->getOperand(0); 8849 SDValue N1 = N->getOperand(1); 8850 8851 // fold (sub x, (select cc, 0, c)) -> (select cc, x, (sub, x, c)) 8852 if (N1.getNode()->hasOneUse()) 8853 if (SDValue Result = combineSelectAndUse(N, N1, N0, DCI)) 8854 return Result; 8855 8856 return SDValue(); 8857 } 8858 8859 /// PerformVMULCombine 8860 /// Distribute (A + B) * C to (A * C) + (B * C) to take advantage of the 8861 /// special multiplier accumulator forwarding. 8862 /// vmul d3, d0, d2 8863 /// vmla d3, d1, d2 8864 /// is faster than 8865 /// vadd d3, d0, d1 8866 /// vmul d3, d3, d2 8867 // However, for (A + B) * (A + B), 8868 // vadd d2, d0, d1 8869 // vmul d3, d0, d2 8870 // vmla d3, d1, d2 8871 // is slower than 8872 // vadd d2, d0, d1 8873 // vmul d3, d2, d2 8874 static SDValue PerformVMULCombine(SDNode *N, 8875 TargetLowering::DAGCombinerInfo &DCI, 8876 const ARMSubtarget *Subtarget) { 8877 if (!Subtarget->hasVMLxForwarding()) 8878 return SDValue(); 8879 8880 SelectionDAG &DAG = DCI.DAG; 8881 SDValue N0 = N->getOperand(0); 8882 SDValue N1 = N->getOperand(1); 8883 unsigned Opcode = N0.getOpcode(); 8884 if (Opcode != ISD::ADD && Opcode != ISD::SUB && 8885 Opcode != ISD::FADD && Opcode != ISD::FSUB) { 8886 Opcode = N1.getOpcode(); 8887 if (Opcode != ISD::ADD && Opcode != ISD::SUB && 8888 Opcode != ISD::FADD && Opcode != ISD::FSUB) 8889 return SDValue(); 8890 std::swap(N0, N1); 8891 } 8892 8893 if (N0 == N1) 8894 return SDValue(); 8895 8896 EVT VT = N->getValueType(0); 8897 SDLoc DL(N); 8898 SDValue N00 = N0->getOperand(0); 8899 SDValue N01 = N0->getOperand(1); 8900 return DAG.getNode(Opcode, DL, VT, 8901 DAG.getNode(ISD::MUL, DL, VT, N00, N1), 8902 DAG.getNode(ISD::MUL, DL, VT, N01, N1)); 8903 } 8904 8905 static SDValue PerformMULCombine(SDNode *N, 8906 TargetLowering::DAGCombinerInfo &DCI, 8907 const ARMSubtarget *Subtarget) { 8908 SelectionDAG &DAG = DCI.DAG; 8909 8910 if (Subtarget->isThumb1Only()) 8911 return SDValue(); 8912 8913 if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer()) 8914 return SDValue(); 8915 8916 EVT VT = N->getValueType(0); 8917 if (VT.is64BitVector() || VT.is128BitVector()) 8918 return PerformVMULCombine(N, DCI, Subtarget); 8919 if (VT != MVT::i32) 8920 return SDValue(); 8921 8922 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(1)); 8923 if (!C) 8924 return SDValue(); 8925 8926 int64_t MulAmt = C->getSExtValue(); 8927 unsigned ShiftAmt = countTrailingZeros<uint64_t>(MulAmt); 8928 8929 ShiftAmt = ShiftAmt & (32 - 1); 8930 SDValue V = N->getOperand(0); 8931 SDLoc DL(N); 8932 8933 SDValue Res; 8934 MulAmt >>= ShiftAmt; 8935 8936 if (MulAmt >= 0) { 8937 if (isPowerOf2_32(MulAmt - 1)) { 8938 // (mul x, 2^N + 1) => (add (shl x, N), x) 8939 Res = DAG.getNode(ISD::ADD, DL, VT, 8940 V, 8941 DAG.getNode(ISD::SHL, DL, VT, 8942 V, 8943 DAG.getConstant(Log2_32(MulAmt - 1), DL, 8944 MVT::i32))); 8945 } else if (isPowerOf2_32(MulAmt + 1)) { 8946 // (mul x, 2^N - 1) => (sub (shl x, N), x) 8947 Res = DAG.getNode(ISD::SUB, DL, VT, 8948 DAG.getNode(ISD::SHL, DL, VT, 8949 V, 8950 DAG.getConstant(Log2_32(MulAmt + 1), DL, 8951 MVT::i32)), 8952 V); 8953 } else 8954 return SDValue(); 8955 } else { 8956 uint64_t MulAmtAbs = -MulAmt; 8957 if (isPowerOf2_32(MulAmtAbs + 1)) { 8958 // (mul x, -(2^N - 1)) => (sub x, (shl x, N)) 8959 Res = DAG.getNode(ISD::SUB, DL, VT, 8960 V, 8961 DAG.getNode(ISD::SHL, DL, VT, 8962 V, 8963 DAG.getConstant(Log2_32(MulAmtAbs + 1), DL, 8964 MVT::i32))); 8965 } else if (isPowerOf2_32(MulAmtAbs - 1)) { 8966 // (mul x, -(2^N + 1)) => - (add (shl x, N), x) 8967 Res = DAG.getNode(ISD::ADD, DL, VT, 8968 V, 8969 DAG.getNode(ISD::SHL, DL, VT, 8970 V, 8971 DAG.getConstant(Log2_32(MulAmtAbs - 1), DL, 8972 MVT::i32))); 8973 Res = DAG.getNode(ISD::SUB, DL, VT, 8974 DAG.getConstant(0, DL, MVT::i32), Res); 8975 8976 } else 8977 return SDValue(); 8978 } 8979 8980 if (ShiftAmt != 0) 8981 Res = DAG.getNode(ISD::SHL, DL, VT, 8982 Res, DAG.getConstant(ShiftAmt, DL, MVT::i32)); 8983 8984 // Do not add new nodes to DAG combiner worklist. 8985 DCI.CombineTo(N, Res, false); 8986 return SDValue(); 8987 } 8988 8989 static SDValue PerformANDCombine(SDNode *N, 8990 TargetLowering::DAGCombinerInfo &DCI, 8991 const ARMSubtarget *Subtarget) { 8992 8993 // Attempt to use immediate-form VBIC 8994 BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(N->getOperand(1)); 8995 SDLoc dl(N); 8996 EVT VT = N->getValueType(0); 8997 SelectionDAG &DAG = DCI.DAG; 8998 8999 if(!DAG.getTargetLoweringInfo().isTypeLegal(VT)) 9000 return SDValue(); 9001 9002 APInt SplatBits, SplatUndef; 9003 unsigned SplatBitSize; 9004 bool HasAnyUndefs; 9005 if (BVN && 9006 BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs)) { 9007 if (SplatBitSize <= 64) { 9008 EVT VbicVT; 9009 SDValue Val = isNEONModifiedImm((~SplatBits).getZExtValue(), 9010 SplatUndef.getZExtValue(), SplatBitSize, 9011 DAG, dl, VbicVT, VT.is128BitVector(), 9012 OtherModImm); 9013 if (Val.getNode()) { 9014 SDValue Input = 9015 DAG.getNode(ISD::BITCAST, dl, VbicVT, N->getOperand(0)); 9016 SDValue Vbic = DAG.getNode(ARMISD::VBICIMM, dl, VbicVT, Input, Val); 9017 return DAG.getNode(ISD::BITCAST, dl, VT, Vbic); 9018 } 9019 } 9020 } 9021 9022 if (!Subtarget->isThumb1Only()) { 9023 // fold (and (select cc, -1, c), x) -> (select cc, x, (and, x, c)) 9024 if (SDValue Result = combineSelectAndUseCommutative(N, true, DCI)) 9025 return Result; 9026 } 9027 9028 return SDValue(); 9029 } 9030 9031 /// PerformORCombine - Target-specific dag combine xforms for ISD::OR 9032 static SDValue PerformORCombine(SDNode *N, 9033 TargetLowering::DAGCombinerInfo &DCI, 9034 const ARMSubtarget *Subtarget) { 9035 // Attempt to use immediate-form VORR 9036 BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(N->getOperand(1)); 9037 SDLoc dl(N); 9038 EVT VT = N->getValueType(0); 9039 SelectionDAG &DAG = DCI.DAG; 9040 9041 if(!DAG.getTargetLoweringInfo().isTypeLegal(VT)) 9042 return SDValue(); 9043 9044 APInt SplatBits, SplatUndef; 9045 unsigned SplatBitSize; 9046 bool HasAnyUndefs; 9047 if (BVN && Subtarget->hasNEON() && 9048 BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs)) { 9049 if (SplatBitSize <= 64) { 9050 EVT VorrVT; 9051 SDValue Val = isNEONModifiedImm(SplatBits.getZExtValue(), 9052 SplatUndef.getZExtValue(), SplatBitSize, 9053 DAG, dl, VorrVT, VT.is128BitVector(), 9054 OtherModImm); 9055 if (Val.getNode()) { 9056 SDValue Input = 9057 DAG.getNode(ISD::BITCAST, dl, VorrVT, N->getOperand(0)); 9058 SDValue Vorr = DAG.getNode(ARMISD::VORRIMM, dl, VorrVT, Input, Val); 9059 return DAG.getNode(ISD::BITCAST, dl, VT, Vorr); 9060 } 9061 } 9062 } 9063 9064 if (!Subtarget->isThumb1Only()) { 9065 // fold (or (select cc, 0, c), x) -> (select cc, x, (or, x, c)) 9066 if (SDValue Result = combineSelectAndUseCommutative(N, false, DCI)) 9067 return Result; 9068 } 9069 9070 // The code below optimizes (or (and X, Y), Z). 9071 // The AND operand needs to have a single user to make these optimizations 9072 // profitable. 9073 SDValue N0 = N->getOperand(0); 9074 if (N0.getOpcode() != ISD::AND || !N0.hasOneUse()) 9075 return SDValue(); 9076 SDValue N1 = N->getOperand(1); 9077 9078 // (or (and B, A), (and C, ~A)) => (VBSL A, B, C) when A is a constant. 9079 if (Subtarget->hasNEON() && N1.getOpcode() == ISD::AND && VT.isVector() && 9080 DAG.getTargetLoweringInfo().isTypeLegal(VT)) { 9081 APInt SplatUndef; 9082 unsigned SplatBitSize; 9083 bool HasAnyUndefs; 9084 9085 APInt SplatBits0, SplatBits1; 9086 BuildVectorSDNode *BVN0 = dyn_cast<BuildVectorSDNode>(N0->getOperand(1)); 9087 BuildVectorSDNode *BVN1 = dyn_cast<BuildVectorSDNode>(N1->getOperand(1)); 9088 // Ensure that the second operand of both ands are constants 9089 if (BVN0 && BVN0->isConstantSplat(SplatBits0, SplatUndef, SplatBitSize, 9090 HasAnyUndefs) && !HasAnyUndefs) { 9091 if (BVN1 && BVN1->isConstantSplat(SplatBits1, SplatUndef, SplatBitSize, 9092 HasAnyUndefs) && !HasAnyUndefs) { 9093 // Ensure that the bit width of the constants are the same and that 9094 // the splat arguments are logical inverses as per the pattern we 9095 // are trying to simplify. 9096 if (SplatBits0.getBitWidth() == SplatBits1.getBitWidth() && 9097 SplatBits0 == ~SplatBits1) { 9098 // Canonicalize the vector type to make instruction selection 9099 // simpler. 9100 EVT CanonicalVT = VT.is128BitVector() ? MVT::v4i32 : MVT::v2i32; 9101 SDValue Result = DAG.getNode(ARMISD::VBSL, dl, CanonicalVT, 9102 N0->getOperand(1), 9103 N0->getOperand(0), 9104 N1->getOperand(0)); 9105 return DAG.getNode(ISD::BITCAST, dl, VT, Result); 9106 } 9107 } 9108 } 9109 } 9110 9111 // Try to use the ARM/Thumb2 BFI (bitfield insert) instruction when 9112 // reasonable. 9113 9114 // BFI is only available on V6T2+ 9115 if (Subtarget->isThumb1Only() || !Subtarget->hasV6T2Ops()) 9116 return SDValue(); 9117 9118 SDLoc DL(N); 9119 // 1) or (and A, mask), val => ARMbfi A, val, mask 9120 // iff (val & mask) == val 9121 // 9122 // 2) or (and A, mask), (and B, mask2) => ARMbfi A, (lsr B, amt), mask 9123 // 2a) iff isBitFieldInvertedMask(mask) && isBitFieldInvertedMask(~mask2) 9124 // && mask == ~mask2 9125 // 2b) iff isBitFieldInvertedMask(~mask) && isBitFieldInvertedMask(mask2) 9126 // && ~mask == mask2 9127 // (i.e., copy a bitfield value into another bitfield of the same width) 9128 9129 if (VT != MVT::i32) 9130 return SDValue(); 9131 9132 SDValue N00 = N0.getOperand(0); 9133 9134 // The value and the mask need to be constants so we can verify this is 9135 // actually a bitfield set. If the mask is 0xffff, we can do better 9136 // via a movt instruction, so don't use BFI in that case. 9137 SDValue MaskOp = N0.getOperand(1); 9138 ConstantSDNode *MaskC = dyn_cast<ConstantSDNode>(MaskOp); 9139 if (!MaskC) 9140 return SDValue(); 9141 unsigned Mask = MaskC->getZExtValue(); 9142 if (Mask == 0xffff) 9143 return SDValue(); 9144 SDValue Res; 9145 // Case (1): or (and A, mask), val => ARMbfi A, val, mask 9146 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1); 9147 if (N1C) { 9148 unsigned Val = N1C->getZExtValue(); 9149 if ((Val & ~Mask) != Val) 9150 return SDValue(); 9151 9152 if (ARM::isBitFieldInvertedMask(Mask)) { 9153 Val >>= countTrailingZeros(~Mask); 9154 9155 Res = DAG.getNode(ARMISD::BFI, DL, VT, N00, 9156 DAG.getConstant(Val, DL, MVT::i32), 9157 DAG.getConstant(Mask, DL, MVT::i32)); 9158 9159 // Do not add new nodes to DAG combiner worklist. 9160 DCI.CombineTo(N, Res, false); 9161 return SDValue(); 9162 } 9163 } else if (N1.getOpcode() == ISD::AND) { 9164 // case (2) or (and A, mask), (and B, mask2) => ARMbfi A, (lsr B, amt), mask 9165 ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1)); 9166 if (!N11C) 9167 return SDValue(); 9168 unsigned Mask2 = N11C->getZExtValue(); 9169 9170 // Mask and ~Mask2 (or reverse) must be equivalent for the BFI pattern 9171 // as is to match. 9172 if (ARM::isBitFieldInvertedMask(Mask) && 9173 (Mask == ~Mask2)) { 9174 // The pack halfword instruction works better for masks that fit it, 9175 // so use that when it's available. 9176 if (Subtarget->hasT2ExtractPack() && 9177 (Mask == 0xffff || Mask == 0xffff0000)) 9178 return SDValue(); 9179 // 2a 9180 unsigned amt = countTrailingZeros(Mask2); 9181 Res = DAG.getNode(ISD::SRL, DL, VT, N1.getOperand(0), 9182 DAG.getConstant(amt, DL, MVT::i32)); 9183 Res = DAG.getNode(ARMISD::BFI, DL, VT, N00, Res, 9184 DAG.getConstant(Mask, DL, MVT::i32)); 9185 // Do not add new nodes to DAG combiner worklist. 9186 DCI.CombineTo(N, Res, false); 9187 return SDValue(); 9188 } else if (ARM::isBitFieldInvertedMask(~Mask) && 9189 (~Mask == Mask2)) { 9190 // The pack halfword instruction works better for masks that fit it, 9191 // so use that when it's available. 9192 if (Subtarget->hasT2ExtractPack() && 9193 (Mask2 == 0xffff || Mask2 == 0xffff0000)) 9194 return SDValue(); 9195 // 2b 9196 unsigned lsb = countTrailingZeros(Mask); 9197 Res = DAG.getNode(ISD::SRL, DL, VT, N00, 9198 DAG.getConstant(lsb, DL, MVT::i32)); 9199 Res = DAG.getNode(ARMISD::BFI, DL, VT, N1.getOperand(0), Res, 9200 DAG.getConstant(Mask2, DL, MVT::i32)); 9201 // Do not add new nodes to DAG combiner worklist. 9202 DCI.CombineTo(N, Res, false); 9203 return SDValue(); 9204 } 9205 } 9206 9207 if (DAG.MaskedValueIsZero(N1, MaskC->getAPIntValue()) && 9208 N00.getOpcode() == ISD::SHL && isa<ConstantSDNode>(N00.getOperand(1)) && 9209 ARM::isBitFieldInvertedMask(~Mask)) { 9210 // Case (3): or (and (shl A, #shamt), mask), B => ARMbfi B, A, ~mask 9211 // where lsb(mask) == #shamt and masked bits of B are known zero. 9212 SDValue ShAmt = N00.getOperand(1); 9213 unsigned ShAmtC = cast<ConstantSDNode>(ShAmt)->getZExtValue(); 9214 unsigned LSB = countTrailingZeros(Mask); 9215 if (ShAmtC != LSB) 9216 return SDValue(); 9217 9218 Res = DAG.getNode(ARMISD::BFI, DL, VT, N1, N00.getOperand(0), 9219 DAG.getConstant(~Mask, DL, MVT::i32)); 9220 9221 // Do not add new nodes to DAG combiner worklist. 9222 DCI.CombineTo(N, Res, false); 9223 } 9224 9225 return SDValue(); 9226 } 9227 9228 static SDValue PerformXORCombine(SDNode *N, 9229 TargetLowering::DAGCombinerInfo &DCI, 9230 const ARMSubtarget *Subtarget) { 9231 EVT VT = N->getValueType(0); 9232 SelectionDAG &DAG = DCI.DAG; 9233 9234 if(!DAG.getTargetLoweringInfo().isTypeLegal(VT)) 9235 return SDValue(); 9236 9237 if (!Subtarget->isThumb1Only()) { 9238 // fold (xor (select cc, 0, c), x) -> (select cc, x, (xor, x, c)) 9239 if (SDValue Result = combineSelectAndUseCommutative(N, false, DCI)) 9240 return Result; 9241 } 9242 9243 return SDValue(); 9244 } 9245 9246 // ParseBFI - given a BFI instruction in N, extract the "from" value (Rn) and return it, 9247 // and fill in FromMask and ToMask with (consecutive) bits in "from" to be extracted and 9248 // their position in "to" (Rd). 9249 static SDValue ParseBFI(SDNode *N, APInt &ToMask, APInt &FromMask) { 9250 assert(N->getOpcode() == ARMISD::BFI); 9251 9252 SDValue From = N->getOperand(1); 9253 ToMask = ~cast<ConstantSDNode>(N->getOperand(2))->getAPIntValue(); 9254 FromMask = APInt::getLowBitsSet(ToMask.getBitWidth(), ToMask.countPopulation()); 9255 9256 // If the Base came from a SHR #C, we can deduce that it is really testing bit 9257 // #C in the base of the SHR. 9258 if (From->getOpcode() == ISD::SRL && 9259 isa<ConstantSDNode>(From->getOperand(1))) { 9260 APInt Shift = cast<ConstantSDNode>(From->getOperand(1))->getAPIntValue(); 9261 assert(Shift.getLimitedValue() < 32 && "Shift too large!"); 9262 FromMask <<= Shift.getLimitedValue(31); 9263 From = From->getOperand(0); 9264 } 9265 9266 return From; 9267 } 9268 9269 // If A and B contain one contiguous set of bits, does A | B == A . B? 9270 // 9271 // Neither A nor B must be zero. 9272 static bool BitsProperlyConcatenate(const APInt &A, const APInt &B) { 9273 unsigned LastActiveBitInA = A.countTrailingZeros(); 9274 unsigned FirstActiveBitInB = B.getBitWidth() - B.countLeadingZeros() - 1; 9275 return LastActiveBitInA - 1 == FirstActiveBitInB; 9276 } 9277 9278 static SDValue FindBFIToCombineWith(SDNode *N) { 9279 // We have a BFI in N. Follow a possible chain of BFIs and find a BFI it can combine with, 9280 // if one exists. 9281 APInt ToMask, FromMask; 9282 SDValue From = ParseBFI(N, ToMask, FromMask); 9283 SDValue To = N->getOperand(0); 9284 9285 // Now check for a compatible BFI to merge with. We can pass through BFIs that 9286 // aren't compatible, but not if they set the same bit in their destination as 9287 // we do (or that of any BFI we're going to combine with). 9288 SDValue V = To; 9289 APInt CombinedToMask = ToMask; 9290 while (V.getOpcode() == ARMISD::BFI) { 9291 APInt NewToMask, NewFromMask; 9292 SDValue NewFrom = ParseBFI(V.getNode(), NewToMask, NewFromMask); 9293 if (NewFrom != From) { 9294 // This BFI has a different base. Keep going. 9295 CombinedToMask |= NewToMask; 9296 V = V.getOperand(0); 9297 continue; 9298 } 9299 9300 // Do the written bits conflict with any we've seen so far? 9301 if ((NewToMask & CombinedToMask).getBoolValue()) 9302 // Conflicting bits - bail out because going further is unsafe. 9303 return SDValue(); 9304 9305 // Are the new bits contiguous when combined with the old bits? 9306 if (BitsProperlyConcatenate(ToMask, NewToMask) && 9307 BitsProperlyConcatenate(FromMask, NewFromMask)) 9308 return V; 9309 if (BitsProperlyConcatenate(NewToMask, ToMask) && 9310 BitsProperlyConcatenate(NewFromMask, FromMask)) 9311 return V; 9312 9313 // We've seen a write to some bits, so track it. 9314 CombinedToMask |= NewToMask; 9315 // Keep going... 9316 V = V.getOperand(0); 9317 } 9318 9319 return SDValue(); 9320 } 9321 9322 static SDValue PerformBFICombine(SDNode *N, 9323 TargetLowering::DAGCombinerInfo &DCI) { 9324 SDValue N1 = N->getOperand(1); 9325 if (N1.getOpcode() == ISD::AND) { 9326 // (bfi A, (and B, Mask1), Mask2) -> (bfi A, B, Mask2) iff 9327 // the bits being cleared by the AND are not demanded by the BFI. 9328 ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1)); 9329 if (!N11C) 9330 return SDValue(); 9331 unsigned InvMask = cast<ConstantSDNode>(N->getOperand(2))->getZExtValue(); 9332 unsigned LSB = countTrailingZeros(~InvMask); 9333 unsigned Width = (32 - countLeadingZeros(~InvMask)) - LSB; 9334 assert(Width < 9335 static_cast<unsigned>(std::numeric_limits<unsigned>::digits) && 9336 "undefined behavior"); 9337 unsigned Mask = (1u << Width) - 1; 9338 unsigned Mask2 = N11C->getZExtValue(); 9339 if ((Mask & (~Mask2)) == 0) 9340 return DCI.DAG.getNode(ARMISD::BFI, SDLoc(N), N->getValueType(0), 9341 N->getOperand(0), N1.getOperand(0), 9342 N->getOperand(2)); 9343 } else if (N->getOperand(0).getOpcode() == ARMISD::BFI) { 9344 // We have a BFI of a BFI. Walk up the BFI chain to see how long it goes. 9345 // Keep track of any consecutive bits set that all come from the same base 9346 // value. We can combine these together into a single BFI. 9347 SDValue CombineBFI = FindBFIToCombineWith(N); 9348 if (CombineBFI == SDValue()) 9349 return SDValue(); 9350 9351 // We've found a BFI. 9352 APInt ToMask1, FromMask1; 9353 SDValue From1 = ParseBFI(N, ToMask1, FromMask1); 9354 9355 APInt ToMask2, FromMask2; 9356 SDValue From2 = ParseBFI(CombineBFI.getNode(), ToMask2, FromMask2); 9357 assert(From1 == From2); 9358 (void)From2; 9359 9360 // First, unlink CombineBFI. 9361 DCI.DAG.ReplaceAllUsesWith(CombineBFI, CombineBFI.getOperand(0)); 9362 // Then create a new BFI, combining the two together. 9363 APInt NewFromMask = FromMask1 | FromMask2; 9364 APInt NewToMask = ToMask1 | ToMask2; 9365 9366 EVT VT = N->getValueType(0); 9367 SDLoc dl(N); 9368 9369 if (NewFromMask[0] == 0) 9370 From1 = DCI.DAG.getNode( 9371 ISD::SRL, dl, VT, From1, 9372 DCI.DAG.getConstant(NewFromMask.countTrailingZeros(), dl, VT)); 9373 return DCI.DAG.getNode(ARMISD::BFI, dl, VT, N->getOperand(0), From1, 9374 DCI.DAG.getConstant(~NewToMask, dl, VT)); 9375 } 9376 return SDValue(); 9377 } 9378 9379 /// PerformVMOVRRDCombine - Target-specific dag combine xforms for 9380 /// ARMISD::VMOVRRD. 9381 static SDValue PerformVMOVRRDCombine(SDNode *N, 9382 TargetLowering::DAGCombinerInfo &DCI, 9383 const ARMSubtarget *Subtarget) { 9384 // vmovrrd(vmovdrr x, y) -> x,y 9385 SDValue InDouble = N->getOperand(0); 9386 if (InDouble.getOpcode() == ARMISD::VMOVDRR && !Subtarget->isFPOnlySP()) 9387 return DCI.CombineTo(N, InDouble.getOperand(0), InDouble.getOperand(1)); 9388 9389 // vmovrrd(load f64) -> (load i32), (load i32) 9390 SDNode *InNode = InDouble.getNode(); 9391 if (ISD::isNormalLoad(InNode) && InNode->hasOneUse() && 9392 InNode->getValueType(0) == MVT::f64 && 9393 InNode->getOperand(1).getOpcode() == ISD::FrameIndex && 9394 !cast<LoadSDNode>(InNode)->isVolatile()) { 9395 // TODO: Should this be done for non-FrameIndex operands? 9396 LoadSDNode *LD = cast<LoadSDNode>(InNode); 9397 9398 SelectionDAG &DAG = DCI.DAG; 9399 SDLoc DL(LD); 9400 SDValue BasePtr = LD->getBasePtr(); 9401 SDValue NewLD1 = DAG.getLoad(MVT::i32, DL, LD->getChain(), BasePtr, 9402 LD->getPointerInfo(), LD->isVolatile(), 9403 LD->isNonTemporal(), LD->isInvariant(), 9404 LD->getAlignment()); 9405 9406 SDValue OffsetPtr = DAG.getNode(ISD::ADD, DL, MVT::i32, BasePtr, 9407 DAG.getConstant(4, DL, MVT::i32)); 9408 SDValue NewLD2 = DAG.getLoad(MVT::i32, DL, NewLD1.getValue(1), OffsetPtr, 9409 LD->getPointerInfo(), LD->isVolatile(), 9410 LD->isNonTemporal(), LD->isInvariant(), 9411 std::min(4U, LD->getAlignment() / 2)); 9412 9413 DAG.ReplaceAllUsesOfValueWith(SDValue(LD, 1), NewLD2.getValue(1)); 9414 if (DCI.DAG.getDataLayout().isBigEndian()) 9415 std::swap (NewLD1, NewLD2); 9416 SDValue Result = DCI.CombineTo(N, NewLD1, NewLD2); 9417 return Result; 9418 } 9419 9420 return SDValue(); 9421 } 9422 9423 /// PerformVMOVDRRCombine - Target-specific dag combine xforms for 9424 /// ARMISD::VMOVDRR. This is also used for BUILD_VECTORs with 2 operands. 9425 static SDValue PerformVMOVDRRCombine(SDNode *N, SelectionDAG &DAG) { 9426 // N=vmovrrd(X); vmovdrr(N:0, N:1) -> bit_convert(X) 9427 SDValue Op0 = N->getOperand(0); 9428 SDValue Op1 = N->getOperand(1); 9429 if (Op0.getOpcode() == ISD::BITCAST) 9430 Op0 = Op0.getOperand(0); 9431 if (Op1.getOpcode() == ISD::BITCAST) 9432 Op1 = Op1.getOperand(0); 9433 if (Op0.getOpcode() == ARMISD::VMOVRRD && 9434 Op0.getNode() == Op1.getNode() && 9435 Op0.getResNo() == 0 && Op1.getResNo() == 1) 9436 return DAG.getNode(ISD::BITCAST, SDLoc(N), 9437 N->getValueType(0), Op0.getOperand(0)); 9438 return SDValue(); 9439 } 9440 9441 /// hasNormalLoadOperand - Check if any of the operands of a BUILD_VECTOR node 9442 /// are normal, non-volatile loads. If so, it is profitable to bitcast an 9443 /// i64 vector to have f64 elements, since the value can then be loaded 9444 /// directly into a VFP register. 9445 static bool hasNormalLoadOperand(SDNode *N) { 9446 unsigned NumElts = N->getValueType(0).getVectorNumElements(); 9447 for (unsigned i = 0; i < NumElts; ++i) { 9448 SDNode *Elt = N->getOperand(i).getNode(); 9449 if (ISD::isNormalLoad(Elt) && !cast<LoadSDNode>(Elt)->isVolatile()) 9450 return true; 9451 } 9452 return false; 9453 } 9454 9455 /// PerformBUILD_VECTORCombine - Target-specific dag combine xforms for 9456 /// ISD::BUILD_VECTOR. 9457 static SDValue PerformBUILD_VECTORCombine(SDNode *N, 9458 TargetLowering::DAGCombinerInfo &DCI, 9459 const ARMSubtarget *Subtarget) { 9460 // build_vector(N=ARMISD::VMOVRRD(X), N:1) -> bit_convert(X): 9461 // VMOVRRD is introduced when legalizing i64 types. It forces the i64 value 9462 // into a pair of GPRs, which is fine when the value is used as a scalar, 9463 // but if the i64 value is converted to a vector, we need to undo the VMOVRRD. 9464 SelectionDAG &DAG = DCI.DAG; 9465 if (N->getNumOperands() == 2) 9466 if (SDValue RV = PerformVMOVDRRCombine(N, DAG)) 9467 return RV; 9468 9469 // Load i64 elements as f64 values so that type legalization does not split 9470 // them up into i32 values. 9471 EVT VT = N->getValueType(0); 9472 if (VT.getVectorElementType() != MVT::i64 || !hasNormalLoadOperand(N)) 9473 return SDValue(); 9474 SDLoc dl(N); 9475 SmallVector<SDValue, 8> Ops; 9476 unsigned NumElts = VT.getVectorNumElements(); 9477 for (unsigned i = 0; i < NumElts; ++i) { 9478 SDValue V = DAG.getNode(ISD::BITCAST, dl, MVT::f64, N->getOperand(i)); 9479 Ops.push_back(V); 9480 // Make the DAGCombiner fold the bitcast. 9481 DCI.AddToWorklist(V.getNode()); 9482 } 9483 EVT FloatVT = EVT::getVectorVT(*DAG.getContext(), MVT::f64, NumElts); 9484 SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, FloatVT, Ops); 9485 return DAG.getNode(ISD::BITCAST, dl, VT, BV); 9486 } 9487 9488 /// \brief Target-specific dag combine xforms for ARMISD::BUILD_VECTOR. 9489 static SDValue 9490 PerformARMBUILD_VECTORCombine(SDNode *N, TargetLowering::DAGCombinerInfo &DCI) { 9491 // ARMISD::BUILD_VECTOR is introduced when legalizing ISD::BUILD_VECTOR. 9492 // At that time, we may have inserted bitcasts from integer to float. 9493 // If these bitcasts have survived DAGCombine, change the lowering of this 9494 // BUILD_VECTOR in something more vector friendly, i.e., that does not 9495 // force to use floating point types. 9496 9497 // Make sure we can change the type of the vector. 9498 // This is possible iff: 9499 // 1. The vector is only used in a bitcast to a integer type. I.e., 9500 // 1.1. Vector is used only once. 9501 // 1.2. Use is a bit convert to an integer type. 9502 // 2. The size of its operands are 32-bits (64-bits are not legal). 9503 EVT VT = N->getValueType(0); 9504 EVT EltVT = VT.getVectorElementType(); 9505 9506 // Check 1.1. and 2. 9507 if (EltVT.getSizeInBits() != 32 || !N->hasOneUse()) 9508 return SDValue(); 9509 9510 // By construction, the input type must be float. 9511 assert(EltVT == MVT::f32 && "Unexpected type!"); 9512 9513 // Check 1.2. 9514 SDNode *Use = *N->use_begin(); 9515 if (Use->getOpcode() != ISD::BITCAST || 9516 Use->getValueType(0).isFloatingPoint()) 9517 return SDValue(); 9518 9519 // Check profitability. 9520 // Model is, if more than half of the relevant operands are bitcast from 9521 // i32, turn the build_vector into a sequence of insert_vector_elt. 9522 // Relevant operands are everything that is not statically 9523 // (i.e., at compile time) bitcasted. 9524 unsigned NumOfBitCastedElts = 0; 9525 unsigned NumElts = VT.getVectorNumElements(); 9526 unsigned NumOfRelevantElts = NumElts; 9527 for (unsigned Idx = 0; Idx < NumElts; ++Idx) { 9528 SDValue Elt = N->getOperand(Idx); 9529 if (Elt->getOpcode() == ISD::BITCAST) { 9530 // Assume only bit cast to i32 will go away. 9531 if (Elt->getOperand(0).getValueType() == MVT::i32) 9532 ++NumOfBitCastedElts; 9533 } else if (Elt.isUndef() || isa<ConstantSDNode>(Elt)) 9534 // Constants are statically casted, thus do not count them as 9535 // relevant operands. 9536 --NumOfRelevantElts; 9537 } 9538 9539 // Check if more than half of the elements require a non-free bitcast. 9540 if (NumOfBitCastedElts <= NumOfRelevantElts / 2) 9541 return SDValue(); 9542 9543 SelectionDAG &DAG = DCI.DAG; 9544 // Create the new vector type. 9545 EVT VecVT = EVT::getVectorVT(*DAG.getContext(), MVT::i32, NumElts); 9546 // Check if the type is legal. 9547 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 9548 if (!TLI.isTypeLegal(VecVT)) 9549 return SDValue(); 9550 9551 // Combine: 9552 // ARMISD::BUILD_VECTOR E1, E2, ..., EN. 9553 // => BITCAST INSERT_VECTOR_ELT 9554 // (INSERT_VECTOR_ELT (...), (BITCAST EN-1), N-1), 9555 // (BITCAST EN), N. 9556 SDValue Vec = DAG.getUNDEF(VecVT); 9557 SDLoc dl(N); 9558 for (unsigned Idx = 0 ; Idx < NumElts; ++Idx) { 9559 SDValue V = N->getOperand(Idx); 9560 if (V.isUndef()) 9561 continue; 9562 if (V.getOpcode() == ISD::BITCAST && 9563 V->getOperand(0).getValueType() == MVT::i32) 9564 // Fold obvious case. 9565 V = V.getOperand(0); 9566 else { 9567 V = DAG.getNode(ISD::BITCAST, SDLoc(V), MVT::i32, V); 9568 // Make the DAGCombiner fold the bitcasts. 9569 DCI.AddToWorklist(V.getNode()); 9570 } 9571 SDValue LaneIdx = DAG.getConstant(Idx, dl, MVT::i32); 9572 Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VecVT, Vec, V, LaneIdx); 9573 } 9574 Vec = DAG.getNode(ISD::BITCAST, dl, VT, Vec); 9575 // Make the DAGCombiner fold the bitcasts. 9576 DCI.AddToWorklist(Vec.getNode()); 9577 return Vec; 9578 } 9579 9580 /// PerformInsertEltCombine - Target-specific dag combine xforms for 9581 /// ISD::INSERT_VECTOR_ELT. 9582 static SDValue PerformInsertEltCombine(SDNode *N, 9583 TargetLowering::DAGCombinerInfo &DCI) { 9584 // Bitcast an i64 load inserted into a vector to f64. 9585 // Otherwise, the i64 value will be legalized to a pair of i32 values. 9586 EVT VT = N->getValueType(0); 9587 SDNode *Elt = N->getOperand(1).getNode(); 9588 if (VT.getVectorElementType() != MVT::i64 || 9589 !ISD::isNormalLoad(Elt) || cast<LoadSDNode>(Elt)->isVolatile()) 9590 return SDValue(); 9591 9592 SelectionDAG &DAG = DCI.DAG; 9593 SDLoc dl(N); 9594 EVT FloatVT = EVT::getVectorVT(*DAG.getContext(), MVT::f64, 9595 VT.getVectorNumElements()); 9596 SDValue Vec = DAG.getNode(ISD::BITCAST, dl, FloatVT, N->getOperand(0)); 9597 SDValue V = DAG.getNode(ISD::BITCAST, dl, MVT::f64, N->getOperand(1)); 9598 // Make the DAGCombiner fold the bitcasts. 9599 DCI.AddToWorklist(Vec.getNode()); 9600 DCI.AddToWorklist(V.getNode()); 9601 SDValue InsElt = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, FloatVT, 9602 Vec, V, N->getOperand(2)); 9603 return DAG.getNode(ISD::BITCAST, dl, VT, InsElt); 9604 } 9605 9606 /// PerformVECTOR_SHUFFLECombine - Target-specific dag combine xforms for 9607 /// ISD::VECTOR_SHUFFLE. 9608 static SDValue PerformVECTOR_SHUFFLECombine(SDNode *N, SelectionDAG &DAG) { 9609 // The LLVM shufflevector instruction does not require the shuffle mask 9610 // length to match the operand vector length, but ISD::VECTOR_SHUFFLE does 9611 // have that requirement. When translating to ISD::VECTOR_SHUFFLE, if the 9612 // operands do not match the mask length, they are extended by concatenating 9613 // them with undef vectors. That is probably the right thing for other 9614 // targets, but for NEON it is better to concatenate two double-register 9615 // size vector operands into a single quad-register size vector. Do that 9616 // transformation here: 9617 // shuffle(concat(v1, undef), concat(v2, undef)) -> 9618 // shuffle(concat(v1, v2), undef) 9619 SDValue Op0 = N->getOperand(0); 9620 SDValue Op1 = N->getOperand(1); 9621 if (Op0.getOpcode() != ISD::CONCAT_VECTORS || 9622 Op1.getOpcode() != ISD::CONCAT_VECTORS || 9623 Op0.getNumOperands() != 2 || 9624 Op1.getNumOperands() != 2) 9625 return SDValue(); 9626 SDValue Concat0Op1 = Op0.getOperand(1); 9627 SDValue Concat1Op1 = Op1.getOperand(1); 9628 if (!Concat0Op1.isUndef() || !Concat1Op1.isUndef()) 9629 return SDValue(); 9630 // Skip the transformation if any of the types are illegal. 9631 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 9632 EVT VT = N->getValueType(0); 9633 if (!TLI.isTypeLegal(VT) || 9634 !TLI.isTypeLegal(Concat0Op1.getValueType()) || 9635 !TLI.isTypeLegal(Concat1Op1.getValueType())) 9636 return SDValue(); 9637 9638 SDValue NewConcat = DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT, 9639 Op0.getOperand(0), Op1.getOperand(0)); 9640 // Translate the shuffle mask. 9641 SmallVector<int, 16> NewMask; 9642 unsigned NumElts = VT.getVectorNumElements(); 9643 unsigned HalfElts = NumElts/2; 9644 ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N); 9645 for (unsigned n = 0; n < NumElts; ++n) { 9646 int MaskElt = SVN->getMaskElt(n); 9647 int NewElt = -1; 9648 if (MaskElt < (int)HalfElts) 9649 NewElt = MaskElt; 9650 else if (MaskElt >= (int)NumElts && MaskElt < (int)(NumElts + HalfElts)) 9651 NewElt = HalfElts + MaskElt - NumElts; 9652 NewMask.push_back(NewElt); 9653 } 9654 return DAG.getVectorShuffle(VT, SDLoc(N), NewConcat, 9655 DAG.getUNDEF(VT), NewMask.data()); 9656 } 9657 9658 /// CombineBaseUpdate - Target-specific DAG combine function for VLDDUP, 9659 /// NEON load/store intrinsics, and generic vector load/stores, to merge 9660 /// base address updates. 9661 /// For generic load/stores, the memory type is assumed to be a vector. 9662 /// The caller is assumed to have checked legality. 9663 static SDValue CombineBaseUpdate(SDNode *N, 9664 TargetLowering::DAGCombinerInfo &DCI) { 9665 SelectionDAG &DAG = DCI.DAG; 9666 const bool isIntrinsic = (N->getOpcode() == ISD::INTRINSIC_VOID || 9667 N->getOpcode() == ISD::INTRINSIC_W_CHAIN); 9668 const bool isStore = N->getOpcode() == ISD::STORE; 9669 const unsigned AddrOpIdx = ((isIntrinsic || isStore) ? 2 : 1); 9670 SDValue Addr = N->getOperand(AddrOpIdx); 9671 MemSDNode *MemN = cast<MemSDNode>(N); 9672 SDLoc dl(N); 9673 9674 // Search for a use of the address operand that is an increment. 9675 for (SDNode::use_iterator UI = Addr.getNode()->use_begin(), 9676 UE = Addr.getNode()->use_end(); UI != UE; ++UI) { 9677 SDNode *User = *UI; 9678 if (User->getOpcode() != ISD::ADD || 9679 UI.getUse().getResNo() != Addr.getResNo()) 9680 continue; 9681 9682 // Check that the add is independent of the load/store. Otherwise, folding 9683 // it would create a cycle. 9684 if (User->isPredecessorOf(N) || N->isPredecessorOf(User)) 9685 continue; 9686 9687 // Find the new opcode for the updating load/store. 9688 bool isLoadOp = true; 9689 bool isLaneOp = false; 9690 unsigned NewOpc = 0; 9691 unsigned NumVecs = 0; 9692 if (isIntrinsic) { 9693 unsigned IntNo = cast<ConstantSDNode>(N->getOperand(1))->getZExtValue(); 9694 switch (IntNo) { 9695 default: llvm_unreachable("unexpected intrinsic for Neon base update"); 9696 case Intrinsic::arm_neon_vld1: NewOpc = ARMISD::VLD1_UPD; 9697 NumVecs = 1; break; 9698 case Intrinsic::arm_neon_vld2: NewOpc = ARMISD::VLD2_UPD; 9699 NumVecs = 2; break; 9700 case Intrinsic::arm_neon_vld3: NewOpc = ARMISD::VLD3_UPD; 9701 NumVecs = 3; break; 9702 case Intrinsic::arm_neon_vld4: NewOpc = ARMISD::VLD4_UPD; 9703 NumVecs = 4; break; 9704 case Intrinsic::arm_neon_vld2lane: NewOpc = ARMISD::VLD2LN_UPD; 9705 NumVecs = 2; isLaneOp = true; break; 9706 case Intrinsic::arm_neon_vld3lane: NewOpc = ARMISD::VLD3LN_UPD; 9707 NumVecs = 3; isLaneOp = true; break; 9708 case Intrinsic::arm_neon_vld4lane: NewOpc = ARMISD::VLD4LN_UPD; 9709 NumVecs = 4; isLaneOp = true; break; 9710 case Intrinsic::arm_neon_vst1: NewOpc = ARMISD::VST1_UPD; 9711 NumVecs = 1; isLoadOp = false; break; 9712 case Intrinsic::arm_neon_vst2: NewOpc = ARMISD::VST2_UPD; 9713 NumVecs = 2; isLoadOp = false; break; 9714 case Intrinsic::arm_neon_vst3: NewOpc = ARMISD::VST3_UPD; 9715 NumVecs = 3; isLoadOp = false; break; 9716 case Intrinsic::arm_neon_vst4: NewOpc = ARMISD::VST4_UPD; 9717 NumVecs = 4; isLoadOp = false; break; 9718 case Intrinsic::arm_neon_vst2lane: NewOpc = ARMISD::VST2LN_UPD; 9719 NumVecs = 2; isLoadOp = false; isLaneOp = true; break; 9720 case Intrinsic::arm_neon_vst3lane: NewOpc = ARMISD::VST3LN_UPD; 9721 NumVecs = 3; isLoadOp = false; isLaneOp = true; break; 9722 case Intrinsic::arm_neon_vst4lane: NewOpc = ARMISD::VST4LN_UPD; 9723 NumVecs = 4; isLoadOp = false; isLaneOp = true; break; 9724 } 9725 } else { 9726 isLaneOp = true; 9727 switch (N->getOpcode()) { 9728 default: llvm_unreachable("unexpected opcode for Neon base update"); 9729 case ARMISD::VLD2DUP: NewOpc = ARMISD::VLD2DUP_UPD; NumVecs = 2; break; 9730 case ARMISD::VLD3DUP: NewOpc = ARMISD::VLD3DUP_UPD; NumVecs = 3; break; 9731 case ARMISD::VLD4DUP: NewOpc = ARMISD::VLD4DUP_UPD; NumVecs = 4; break; 9732 case ISD::LOAD: NewOpc = ARMISD::VLD1_UPD; 9733 NumVecs = 1; isLaneOp = false; break; 9734 case ISD::STORE: NewOpc = ARMISD::VST1_UPD; 9735 NumVecs = 1; isLaneOp = false; isLoadOp = false; break; 9736 } 9737 } 9738 9739 // Find the size of memory referenced by the load/store. 9740 EVT VecTy; 9741 if (isLoadOp) { 9742 VecTy = N->getValueType(0); 9743 } else if (isIntrinsic) { 9744 VecTy = N->getOperand(AddrOpIdx+1).getValueType(); 9745 } else { 9746 assert(isStore && "Node has to be a load, a store, or an intrinsic!"); 9747 VecTy = N->getOperand(1).getValueType(); 9748 } 9749 9750 unsigned NumBytes = NumVecs * VecTy.getSizeInBits() / 8; 9751 if (isLaneOp) 9752 NumBytes /= VecTy.getVectorNumElements(); 9753 9754 // If the increment is a constant, it must match the memory ref size. 9755 SDValue Inc = User->getOperand(User->getOperand(0) == Addr ? 1 : 0); 9756 if (ConstantSDNode *CInc = dyn_cast<ConstantSDNode>(Inc.getNode())) { 9757 uint64_t IncVal = CInc->getZExtValue(); 9758 if (IncVal != NumBytes) 9759 continue; 9760 } else if (NumBytes >= 3 * 16) { 9761 // VLD3/4 and VST3/4 for 128-bit vectors are implemented with two 9762 // separate instructions that make it harder to use a non-constant update. 9763 continue; 9764 } 9765 9766 // OK, we found an ADD we can fold into the base update. 9767 // Now, create a _UPD node, taking care of not breaking alignment. 9768 9769 EVT AlignedVecTy = VecTy; 9770 unsigned Alignment = MemN->getAlignment(); 9771 9772 // If this is a less-than-standard-aligned load/store, change the type to 9773 // match the standard alignment. 9774 // The alignment is overlooked when selecting _UPD variants; and it's 9775 // easier to introduce bitcasts here than fix that. 9776 // There are 3 ways to get to this base-update combine: 9777 // - intrinsics: they are assumed to be properly aligned (to the standard 9778 // alignment of the memory type), so we don't need to do anything. 9779 // - ARMISD::VLDx nodes: they are only generated from the aforementioned 9780 // intrinsics, so, likewise, there's nothing to do. 9781 // - generic load/store instructions: the alignment is specified as an 9782 // explicit operand, rather than implicitly as the standard alignment 9783 // of the memory type (like the intrisics). We need to change the 9784 // memory type to match the explicit alignment. That way, we don't 9785 // generate non-standard-aligned ARMISD::VLDx nodes. 9786 if (isa<LSBaseSDNode>(N)) { 9787 if (Alignment == 0) 9788 Alignment = 1; 9789 if (Alignment < VecTy.getScalarSizeInBits() / 8) { 9790 MVT EltTy = MVT::getIntegerVT(Alignment * 8); 9791 assert(NumVecs == 1 && "Unexpected multi-element generic load/store."); 9792 assert(!isLaneOp && "Unexpected generic load/store lane."); 9793 unsigned NumElts = NumBytes / (EltTy.getSizeInBits() / 8); 9794 AlignedVecTy = MVT::getVectorVT(EltTy, NumElts); 9795 } 9796 // Don't set an explicit alignment on regular load/stores that we want 9797 // to transform to VLD/VST 1_UPD nodes. 9798 // This matches the behavior of regular load/stores, which only get an 9799 // explicit alignment if the MMO alignment is larger than the standard 9800 // alignment of the memory type. 9801 // Intrinsics, however, always get an explicit alignment, set to the 9802 // alignment of the MMO. 9803 Alignment = 1; 9804 } 9805 9806 // Create the new updating load/store node. 9807 // First, create an SDVTList for the new updating node's results. 9808 EVT Tys[6]; 9809 unsigned NumResultVecs = (isLoadOp ? NumVecs : 0); 9810 unsigned n; 9811 for (n = 0; n < NumResultVecs; ++n) 9812 Tys[n] = AlignedVecTy; 9813 Tys[n++] = MVT::i32; 9814 Tys[n] = MVT::Other; 9815 SDVTList SDTys = DAG.getVTList(makeArrayRef(Tys, NumResultVecs+2)); 9816 9817 // Then, gather the new node's operands. 9818 SmallVector<SDValue, 8> Ops; 9819 Ops.push_back(N->getOperand(0)); // incoming chain 9820 Ops.push_back(N->getOperand(AddrOpIdx)); 9821 Ops.push_back(Inc); 9822 9823 if (StoreSDNode *StN = dyn_cast<StoreSDNode>(N)) { 9824 // Try to match the intrinsic's signature 9825 Ops.push_back(StN->getValue()); 9826 } else { 9827 // Loads (and of course intrinsics) match the intrinsics' signature, 9828 // so just add all but the alignment operand. 9829 for (unsigned i = AddrOpIdx + 1; i < N->getNumOperands() - 1; ++i) 9830 Ops.push_back(N->getOperand(i)); 9831 } 9832 9833 // For all node types, the alignment operand is always the last one. 9834 Ops.push_back(DAG.getConstant(Alignment, dl, MVT::i32)); 9835 9836 // If this is a non-standard-aligned STORE, the penultimate operand is the 9837 // stored value. Bitcast it to the aligned type. 9838 if (AlignedVecTy != VecTy && N->getOpcode() == ISD::STORE) { 9839 SDValue &StVal = Ops[Ops.size()-2]; 9840 StVal = DAG.getNode(ISD::BITCAST, dl, AlignedVecTy, StVal); 9841 } 9842 9843 SDValue UpdN = DAG.getMemIntrinsicNode(NewOpc, dl, SDTys, 9844 Ops, AlignedVecTy, 9845 MemN->getMemOperand()); 9846 9847 // Update the uses. 9848 SmallVector<SDValue, 5> NewResults; 9849 for (unsigned i = 0; i < NumResultVecs; ++i) 9850 NewResults.push_back(SDValue(UpdN.getNode(), i)); 9851 9852 // If this is an non-standard-aligned LOAD, the first result is the loaded 9853 // value. Bitcast it to the expected result type. 9854 if (AlignedVecTy != VecTy && N->getOpcode() == ISD::LOAD) { 9855 SDValue &LdVal = NewResults[0]; 9856 LdVal = DAG.getNode(ISD::BITCAST, dl, VecTy, LdVal); 9857 } 9858 9859 NewResults.push_back(SDValue(UpdN.getNode(), NumResultVecs+1)); // chain 9860 DCI.CombineTo(N, NewResults); 9861 DCI.CombineTo(User, SDValue(UpdN.getNode(), NumResultVecs)); 9862 9863 break; 9864 } 9865 return SDValue(); 9866 } 9867 9868 static SDValue PerformVLDCombine(SDNode *N, 9869 TargetLowering::DAGCombinerInfo &DCI) { 9870 if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer()) 9871 return SDValue(); 9872 9873 return CombineBaseUpdate(N, DCI); 9874 } 9875 9876 /// CombineVLDDUP - For a VDUPLANE node N, check if its source operand is a 9877 /// vldN-lane (N > 1) intrinsic, and if all the other uses of that intrinsic 9878 /// are also VDUPLANEs. If so, combine them to a vldN-dup operation and 9879 /// return true. 9880 static bool CombineVLDDUP(SDNode *N, TargetLowering::DAGCombinerInfo &DCI) { 9881 SelectionDAG &DAG = DCI.DAG; 9882 EVT VT = N->getValueType(0); 9883 // vldN-dup instructions only support 64-bit vectors for N > 1. 9884 if (!VT.is64BitVector()) 9885 return false; 9886 9887 // Check if the VDUPLANE operand is a vldN-dup intrinsic. 9888 SDNode *VLD = N->getOperand(0).getNode(); 9889 if (VLD->getOpcode() != ISD::INTRINSIC_W_CHAIN) 9890 return false; 9891 unsigned NumVecs = 0; 9892 unsigned NewOpc = 0; 9893 unsigned IntNo = cast<ConstantSDNode>(VLD->getOperand(1))->getZExtValue(); 9894 if (IntNo == Intrinsic::arm_neon_vld2lane) { 9895 NumVecs = 2; 9896 NewOpc = ARMISD::VLD2DUP; 9897 } else if (IntNo == Intrinsic::arm_neon_vld3lane) { 9898 NumVecs = 3; 9899 NewOpc = ARMISD::VLD3DUP; 9900 } else if (IntNo == Intrinsic::arm_neon_vld4lane) { 9901 NumVecs = 4; 9902 NewOpc = ARMISD::VLD4DUP; 9903 } else { 9904 return false; 9905 } 9906 9907 // First check that all the vldN-lane uses are VDUPLANEs and that the lane 9908 // numbers match the load. 9909 unsigned VLDLaneNo = 9910 cast<ConstantSDNode>(VLD->getOperand(NumVecs+3))->getZExtValue(); 9911 for (SDNode::use_iterator UI = VLD->use_begin(), UE = VLD->use_end(); 9912 UI != UE; ++UI) { 9913 // Ignore uses of the chain result. 9914 if (UI.getUse().getResNo() == NumVecs) 9915 continue; 9916 SDNode *User = *UI; 9917 if (User->getOpcode() != ARMISD::VDUPLANE || 9918 VLDLaneNo != cast<ConstantSDNode>(User->getOperand(1))->getZExtValue()) 9919 return false; 9920 } 9921 9922 // Create the vldN-dup node. 9923 EVT Tys[5]; 9924 unsigned n; 9925 for (n = 0; n < NumVecs; ++n) 9926 Tys[n] = VT; 9927 Tys[n] = MVT::Other; 9928 SDVTList SDTys = DAG.getVTList(makeArrayRef(Tys, NumVecs+1)); 9929 SDValue Ops[] = { VLD->getOperand(0), VLD->getOperand(2) }; 9930 MemIntrinsicSDNode *VLDMemInt = cast<MemIntrinsicSDNode>(VLD); 9931 SDValue VLDDup = DAG.getMemIntrinsicNode(NewOpc, SDLoc(VLD), SDTys, 9932 Ops, VLDMemInt->getMemoryVT(), 9933 VLDMemInt->getMemOperand()); 9934 9935 // Update the uses. 9936 for (SDNode::use_iterator UI = VLD->use_begin(), UE = VLD->use_end(); 9937 UI != UE; ++UI) { 9938 unsigned ResNo = UI.getUse().getResNo(); 9939 // Ignore uses of the chain result. 9940 if (ResNo == NumVecs) 9941 continue; 9942 SDNode *User = *UI; 9943 DCI.CombineTo(User, SDValue(VLDDup.getNode(), ResNo)); 9944 } 9945 9946 // Now the vldN-lane intrinsic is dead except for its chain result. 9947 // Update uses of the chain. 9948 std::vector<SDValue> VLDDupResults; 9949 for (unsigned n = 0; n < NumVecs; ++n) 9950 VLDDupResults.push_back(SDValue(VLDDup.getNode(), n)); 9951 VLDDupResults.push_back(SDValue(VLDDup.getNode(), NumVecs)); 9952 DCI.CombineTo(VLD, VLDDupResults); 9953 9954 return true; 9955 } 9956 9957 /// PerformVDUPLANECombine - Target-specific dag combine xforms for 9958 /// ARMISD::VDUPLANE. 9959 static SDValue PerformVDUPLANECombine(SDNode *N, 9960 TargetLowering::DAGCombinerInfo &DCI) { 9961 SDValue Op = N->getOperand(0); 9962 9963 // If the source is a vldN-lane (N > 1) intrinsic, and all the other uses 9964 // of that intrinsic are also VDUPLANEs, combine them to a vldN-dup operation. 9965 if (CombineVLDDUP(N, DCI)) 9966 return SDValue(N, 0); 9967 9968 // If the source is already a VMOVIMM or VMVNIMM splat, the VDUPLANE is 9969 // redundant. Ignore bit_converts for now; element sizes are checked below. 9970 while (Op.getOpcode() == ISD::BITCAST) 9971 Op = Op.getOperand(0); 9972 if (Op.getOpcode() != ARMISD::VMOVIMM && Op.getOpcode() != ARMISD::VMVNIMM) 9973 return SDValue(); 9974 9975 // Make sure the VMOV element size is not bigger than the VDUPLANE elements. 9976 unsigned EltSize = Op.getValueType().getVectorElementType().getSizeInBits(); 9977 // The canonical VMOV for a zero vector uses a 32-bit element size. 9978 unsigned Imm = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue(); 9979 unsigned EltBits; 9980 if (ARM_AM::decodeNEONModImm(Imm, EltBits) == 0) 9981 EltSize = 8; 9982 EVT VT = N->getValueType(0); 9983 if (EltSize > VT.getVectorElementType().getSizeInBits()) 9984 return SDValue(); 9985 9986 return DCI.DAG.getNode(ISD::BITCAST, SDLoc(N), VT, Op); 9987 } 9988 9989 static SDValue PerformLOADCombine(SDNode *N, 9990 TargetLowering::DAGCombinerInfo &DCI) { 9991 EVT VT = N->getValueType(0); 9992 9993 // If this is a legal vector load, try to combine it into a VLD1_UPD. 9994 if (ISD::isNormalLoad(N) && VT.isVector() && 9995 DCI.DAG.getTargetLoweringInfo().isTypeLegal(VT)) 9996 return CombineBaseUpdate(N, DCI); 9997 9998 return SDValue(); 9999 } 10000 10001 /// PerformSTORECombine - Target-specific dag combine xforms for 10002 /// ISD::STORE. 10003 static SDValue PerformSTORECombine(SDNode *N, 10004 TargetLowering::DAGCombinerInfo &DCI) { 10005 StoreSDNode *St = cast<StoreSDNode>(N); 10006 if (St->isVolatile()) 10007 return SDValue(); 10008 10009 // Optimize trunc store (of multiple scalars) to shuffle and store. First, 10010 // pack all of the elements in one place. Next, store to memory in fewer 10011 // chunks. 10012 SDValue StVal = St->getValue(); 10013 EVT VT = StVal.getValueType(); 10014 if (St->isTruncatingStore() && VT.isVector()) { 10015 SelectionDAG &DAG = DCI.DAG; 10016 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 10017 EVT StVT = St->getMemoryVT(); 10018 unsigned NumElems = VT.getVectorNumElements(); 10019 assert(StVT != VT && "Cannot truncate to the same type"); 10020 unsigned FromEltSz = VT.getVectorElementType().getSizeInBits(); 10021 unsigned ToEltSz = StVT.getVectorElementType().getSizeInBits(); 10022 10023 // From, To sizes and ElemCount must be pow of two 10024 if (!isPowerOf2_32(NumElems * FromEltSz * ToEltSz)) return SDValue(); 10025 10026 // We are going to use the original vector elt for storing. 10027 // Accumulated smaller vector elements must be a multiple of the store size. 10028 if (0 != (NumElems * FromEltSz) % ToEltSz) return SDValue(); 10029 10030 unsigned SizeRatio = FromEltSz / ToEltSz; 10031 assert(SizeRatio * NumElems * ToEltSz == VT.getSizeInBits()); 10032 10033 // Create a type on which we perform the shuffle. 10034 EVT WideVecVT = EVT::getVectorVT(*DAG.getContext(), StVT.getScalarType(), 10035 NumElems*SizeRatio); 10036 assert(WideVecVT.getSizeInBits() == VT.getSizeInBits()); 10037 10038 SDLoc DL(St); 10039 SDValue WideVec = DAG.getNode(ISD::BITCAST, DL, WideVecVT, StVal); 10040 SmallVector<int, 8> ShuffleVec(NumElems * SizeRatio, -1); 10041 for (unsigned i = 0; i < NumElems; ++i) 10042 ShuffleVec[i] = DAG.getDataLayout().isBigEndian() 10043 ? (i + 1) * SizeRatio - 1 10044 : i * SizeRatio; 10045 10046 // Can't shuffle using an illegal type. 10047 if (!TLI.isTypeLegal(WideVecVT)) return SDValue(); 10048 10049 SDValue Shuff = DAG.getVectorShuffle(WideVecVT, DL, WideVec, 10050 DAG.getUNDEF(WideVec.getValueType()), 10051 ShuffleVec.data()); 10052 // At this point all of the data is stored at the bottom of the 10053 // register. We now need to save it to mem. 10054 10055 // Find the largest store unit 10056 MVT StoreType = MVT::i8; 10057 for (MVT Tp : MVT::integer_valuetypes()) { 10058 if (TLI.isTypeLegal(Tp) && Tp.getSizeInBits() <= NumElems * ToEltSz) 10059 StoreType = Tp; 10060 } 10061 // Didn't find a legal store type. 10062 if (!TLI.isTypeLegal(StoreType)) 10063 return SDValue(); 10064 10065 // Bitcast the original vector into a vector of store-size units 10066 EVT StoreVecVT = EVT::getVectorVT(*DAG.getContext(), 10067 StoreType, VT.getSizeInBits()/EVT(StoreType).getSizeInBits()); 10068 assert(StoreVecVT.getSizeInBits() == VT.getSizeInBits()); 10069 SDValue ShuffWide = DAG.getNode(ISD::BITCAST, DL, StoreVecVT, Shuff); 10070 SmallVector<SDValue, 8> Chains; 10071 SDValue Increment = DAG.getConstant(StoreType.getSizeInBits() / 8, DL, 10072 TLI.getPointerTy(DAG.getDataLayout())); 10073 SDValue BasePtr = St->getBasePtr(); 10074 10075 // Perform one or more big stores into memory. 10076 unsigned E = (ToEltSz*NumElems)/StoreType.getSizeInBits(); 10077 for (unsigned I = 0; I < E; I++) { 10078 SDValue SubVec = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, 10079 StoreType, ShuffWide, 10080 DAG.getIntPtrConstant(I, DL)); 10081 SDValue Ch = DAG.getStore(St->getChain(), DL, SubVec, BasePtr, 10082 St->getPointerInfo(), St->isVolatile(), 10083 St->isNonTemporal(), St->getAlignment()); 10084 BasePtr = DAG.getNode(ISD::ADD, DL, BasePtr.getValueType(), BasePtr, 10085 Increment); 10086 Chains.push_back(Ch); 10087 } 10088 return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Chains); 10089 } 10090 10091 if (!ISD::isNormalStore(St)) 10092 return SDValue(); 10093 10094 // Split a store of a VMOVDRR into two integer stores to avoid mixing NEON and 10095 // ARM stores of arguments in the same cache line. 10096 if (StVal.getNode()->getOpcode() == ARMISD::VMOVDRR && 10097 StVal.getNode()->hasOneUse()) { 10098 SelectionDAG &DAG = DCI.DAG; 10099 bool isBigEndian = DAG.getDataLayout().isBigEndian(); 10100 SDLoc DL(St); 10101 SDValue BasePtr = St->getBasePtr(); 10102 SDValue NewST1 = DAG.getStore(St->getChain(), DL, 10103 StVal.getNode()->getOperand(isBigEndian ? 1 : 0 ), 10104 BasePtr, St->getPointerInfo(), St->isVolatile(), 10105 St->isNonTemporal(), St->getAlignment()); 10106 10107 SDValue OffsetPtr = DAG.getNode(ISD::ADD, DL, MVT::i32, BasePtr, 10108 DAG.getConstant(4, DL, MVT::i32)); 10109 return DAG.getStore(NewST1.getValue(0), DL, 10110 StVal.getNode()->getOperand(isBigEndian ? 0 : 1), 10111 OffsetPtr, St->getPointerInfo(), St->isVolatile(), 10112 St->isNonTemporal(), 10113 std::min(4U, St->getAlignment() / 2)); 10114 } 10115 10116 if (StVal.getValueType() == MVT::i64 && 10117 StVal.getNode()->getOpcode() == ISD::EXTRACT_VECTOR_ELT) { 10118 10119 // Bitcast an i64 store extracted from a vector to f64. 10120 // Otherwise, the i64 value will be legalized to a pair of i32 values. 10121 SelectionDAG &DAG = DCI.DAG; 10122 SDLoc dl(StVal); 10123 SDValue IntVec = StVal.getOperand(0); 10124 EVT FloatVT = EVT::getVectorVT(*DAG.getContext(), MVT::f64, 10125 IntVec.getValueType().getVectorNumElements()); 10126 SDValue Vec = DAG.getNode(ISD::BITCAST, dl, FloatVT, IntVec); 10127 SDValue ExtElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, 10128 Vec, StVal.getOperand(1)); 10129 dl = SDLoc(N); 10130 SDValue V = DAG.getNode(ISD::BITCAST, dl, MVT::i64, ExtElt); 10131 // Make the DAGCombiner fold the bitcasts. 10132 DCI.AddToWorklist(Vec.getNode()); 10133 DCI.AddToWorklist(ExtElt.getNode()); 10134 DCI.AddToWorklist(V.getNode()); 10135 return DAG.getStore(St->getChain(), dl, V, St->getBasePtr(), 10136 St->getPointerInfo(), St->isVolatile(), 10137 St->isNonTemporal(), St->getAlignment(), 10138 St->getAAInfo()); 10139 } 10140 10141 // If this is a legal vector store, try to combine it into a VST1_UPD. 10142 if (ISD::isNormalStore(N) && VT.isVector() && 10143 DCI.DAG.getTargetLoweringInfo().isTypeLegal(VT)) 10144 return CombineBaseUpdate(N, DCI); 10145 10146 return SDValue(); 10147 } 10148 10149 /// PerformVCVTCombine - VCVT (floating-point to fixed-point, Advanced SIMD) 10150 /// can replace combinations of VMUL and VCVT (floating-point to integer) 10151 /// when the VMUL has a constant operand that is a power of 2. 10152 /// 10153 /// Example (assume d17 = <float 8.000000e+00, float 8.000000e+00>): 10154 /// vmul.f32 d16, d17, d16 10155 /// vcvt.s32.f32 d16, d16 10156 /// becomes: 10157 /// vcvt.s32.f32 d16, d16, #3 10158 static SDValue PerformVCVTCombine(SDNode *N, SelectionDAG &DAG, 10159 const ARMSubtarget *Subtarget) { 10160 if (!Subtarget->hasNEON()) 10161 return SDValue(); 10162 10163 SDValue Op = N->getOperand(0); 10164 if (!Op.getValueType().isVector() || !Op.getValueType().isSimple() || 10165 Op.getOpcode() != ISD::FMUL) 10166 return SDValue(); 10167 10168 SDValue ConstVec = Op->getOperand(1); 10169 if (!isa<BuildVectorSDNode>(ConstVec)) 10170 return SDValue(); 10171 10172 MVT FloatTy = Op.getSimpleValueType().getVectorElementType(); 10173 uint32_t FloatBits = FloatTy.getSizeInBits(); 10174 MVT IntTy = N->getSimpleValueType(0).getVectorElementType(); 10175 uint32_t IntBits = IntTy.getSizeInBits(); 10176 unsigned NumLanes = Op.getValueType().getVectorNumElements(); 10177 if (FloatBits != 32 || IntBits > 32 || NumLanes > 4) { 10178 // These instructions only exist converting from f32 to i32. We can handle 10179 // smaller integers by generating an extra truncate, but larger ones would 10180 // be lossy. We also can't handle more then 4 lanes, since these intructions 10181 // only support v2i32/v4i32 types. 10182 return SDValue(); 10183 } 10184 10185 BitVector UndefElements; 10186 BuildVectorSDNode *BV = cast<BuildVectorSDNode>(ConstVec); 10187 int32_t C = BV->getConstantFPSplatPow2ToLog2Int(&UndefElements, 33); 10188 if (C == -1 || C == 0 || C > 32) 10189 return SDValue(); 10190 10191 SDLoc dl(N); 10192 bool isSigned = N->getOpcode() == ISD::FP_TO_SINT; 10193 unsigned IntrinsicOpcode = isSigned ? Intrinsic::arm_neon_vcvtfp2fxs : 10194 Intrinsic::arm_neon_vcvtfp2fxu; 10195 SDValue FixConv = DAG.getNode( 10196 ISD::INTRINSIC_WO_CHAIN, dl, NumLanes == 2 ? MVT::v2i32 : MVT::v4i32, 10197 DAG.getConstant(IntrinsicOpcode, dl, MVT::i32), Op->getOperand(0), 10198 DAG.getConstant(C, dl, MVT::i32)); 10199 10200 if (IntBits < FloatBits) 10201 FixConv = DAG.getNode(ISD::TRUNCATE, dl, N->getValueType(0), FixConv); 10202 10203 return FixConv; 10204 } 10205 10206 /// PerformVDIVCombine - VCVT (fixed-point to floating-point, Advanced SIMD) 10207 /// can replace combinations of VCVT (integer to floating-point) and VDIV 10208 /// when the VDIV has a constant operand that is a power of 2. 10209 /// 10210 /// Example (assume d17 = <float 8.000000e+00, float 8.000000e+00>): 10211 /// vcvt.f32.s32 d16, d16 10212 /// vdiv.f32 d16, d17, d16 10213 /// becomes: 10214 /// vcvt.f32.s32 d16, d16, #3 10215 static SDValue PerformVDIVCombine(SDNode *N, SelectionDAG &DAG, 10216 const ARMSubtarget *Subtarget) { 10217 if (!Subtarget->hasNEON()) 10218 return SDValue(); 10219 10220 SDValue Op = N->getOperand(0); 10221 unsigned OpOpcode = Op.getNode()->getOpcode(); 10222 if (!N->getValueType(0).isVector() || !N->getValueType(0).isSimple() || 10223 (OpOpcode != ISD::SINT_TO_FP && OpOpcode != ISD::UINT_TO_FP)) 10224 return SDValue(); 10225 10226 SDValue ConstVec = N->getOperand(1); 10227 if (!isa<BuildVectorSDNode>(ConstVec)) 10228 return SDValue(); 10229 10230 MVT FloatTy = N->getSimpleValueType(0).getVectorElementType(); 10231 uint32_t FloatBits = FloatTy.getSizeInBits(); 10232 MVT IntTy = Op.getOperand(0).getSimpleValueType().getVectorElementType(); 10233 uint32_t IntBits = IntTy.getSizeInBits(); 10234 unsigned NumLanes = Op.getValueType().getVectorNumElements(); 10235 if (FloatBits != 32 || IntBits > 32 || NumLanes > 4) { 10236 // These instructions only exist converting from i32 to f32. We can handle 10237 // smaller integers by generating an extra extend, but larger ones would 10238 // be lossy. We also can't handle more then 4 lanes, since these intructions 10239 // only support v2i32/v4i32 types. 10240 return SDValue(); 10241 } 10242 10243 BitVector UndefElements; 10244 BuildVectorSDNode *BV = cast<BuildVectorSDNode>(ConstVec); 10245 int32_t C = BV->getConstantFPSplatPow2ToLog2Int(&UndefElements, 33); 10246 if (C == -1 || C == 0 || C > 32) 10247 return SDValue(); 10248 10249 SDLoc dl(N); 10250 bool isSigned = OpOpcode == ISD::SINT_TO_FP; 10251 SDValue ConvInput = Op.getOperand(0); 10252 if (IntBits < FloatBits) 10253 ConvInput = DAG.getNode(isSigned ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND, 10254 dl, NumLanes == 2 ? MVT::v2i32 : MVT::v4i32, 10255 ConvInput); 10256 10257 unsigned IntrinsicOpcode = isSigned ? Intrinsic::arm_neon_vcvtfxs2fp : 10258 Intrinsic::arm_neon_vcvtfxu2fp; 10259 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, 10260 Op.getValueType(), 10261 DAG.getConstant(IntrinsicOpcode, dl, MVT::i32), 10262 ConvInput, DAG.getConstant(C, dl, MVT::i32)); 10263 } 10264 10265 /// Getvshiftimm - Check if this is a valid build_vector for the immediate 10266 /// operand of a vector shift operation, where all the elements of the 10267 /// build_vector must have the same constant integer value. 10268 static bool getVShiftImm(SDValue Op, unsigned ElementBits, int64_t &Cnt) { 10269 // Ignore bit_converts. 10270 while (Op.getOpcode() == ISD::BITCAST) 10271 Op = Op.getOperand(0); 10272 BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(Op.getNode()); 10273 APInt SplatBits, SplatUndef; 10274 unsigned SplatBitSize; 10275 bool HasAnyUndefs; 10276 if (! BVN || ! BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, 10277 HasAnyUndefs, ElementBits) || 10278 SplatBitSize > ElementBits) 10279 return false; 10280 Cnt = SplatBits.getSExtValue(); 10281 return true; 10282 } 10283 10284 /// isVShiftLImm - Check if this is a valid build_vector for the immediate 10285 /// operand of a vector shift left operation. That value must be in the range: 10286 /// 0 <= Value < ElementBits for a left shift; or 10287 /// 0 <= Value <= ElementBits for a long left shift. 10288 static bool isVShiftLImm(SDValue Op, EVT VT, bool isLong, int64_t &Cnt) { 10289 assert(VT.isVector() && "vector shift count is not a vector type"); 10290 int64_t ElementBits = VT.getVectorElementType().getSizeInBits(); 10291 if (! getVShiftImm(Op, ElementBits, Cnt)) 10292 return false; 10293 return (Cnt >= 0 && (isLong ? Cnt-1 : Cnt) < ElementBits); 10294 } 10295 10296 /// isVShiftRImm - Check if this is a valid build_vector for the immediate 10297 /// operand of a vector shift right operation. For a shift opcode, the value 10298 /// is positive, but for an intrinsic the value count must be negative. The 10299 /// absolute value must be in the range: 10300 /// 1 <= |Value| <= ElementBits for a right shift; or 10301 /// 1 <= |Value| <= ElementBits/2 for a narrow right shift. 10302 static bool isVShiftRImm(SDValue Op, EVT VT, bool isNarrow, bool isIntrinsic, 10303 int64_t &Cnt) { 10304 assert(VT.isVector() && "vector shift count is not a vector type"); 10305 int64_t ElementBits = VT.getVectorElementType().getSizeInBits(); 10306 if (! getVShiftImm(Op, ElementBits, Cnt)) 10307 return false; 10308 if (!isIntrinsic) 10309 return (Cnt >= 1 && Cnt <= (isNarrow ? ElementBits/2 : ElementBits)); 10310 if (Cnt >= -(isNarrow ? ElementBits/2 : ElementBits) && Cnt <= -1) { 10311 Cnt = -Cnt; 10312 return true; 10313 } 10314 return false; 10315 } 10316 10317 /// PerformIntrinsicCombine - ARM-specific DAG combining for intrinsics. 10318 static SDValue PerformIntrinsicCombine(SDNode *N, SelectionDAG &DAG) { 10319 unsigned IntNo = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue(); 10320 switch (IntNo) { 10321 default: 10322 // Don't do anything for most intrinsics. 10323 break; 10324 10325 // Vector shifts: check for immediate versions and lower them. 10326 // Note: This is done during DAG combining instead of DAG legalizing because 10327 // the build_vectors for 64-bit vector element shift counts are generally 10328 // not legal, and it is hard to see their values after they get legalized to 10329 // loads from a constant pool. 10330 case Intrinsic::arm_neon_vshifts: 10331 case Intrinsic::arm_neon_vshiftu: 10332 case Intrinsic::arm_neon_vrshifts: 10333 case Intrinsic::arm_neon_vrshiftu: 10334 case Intrinsic::arm_neon_vrshiftn: 10335 case Intrinsic::arm_neon_vqshifts: 10336 case Intrinsic::arm_neon_vqshiftu: 10337 case Intrinsic::arm_neon_vqshiftsu: 10338 case Intrinsic::arm_neon_vqshiftns: 10339 case Intrinsic::arm_neon_vqshiftnu: 10340 case Intrinsic::arm_neon_vqshiftnsu: 10341 case Intrinsic::arm_neon_vqrshiftns: 10342 case Intrinsic::arm_neon_vqrshiftnu: 10343 case Intrinsic::arm_neon_vqrshiftnsu: { 10344 EVT VT = N->getOperand(1).getValueType(); 10345 int64_t Cnt; 10346 unsigned VShiftOpc = 0; 10347 10348 switch (IntNo) { 10349 case Intrinsic::arm_neon_vshifts: 10350 case Intrinsic::arm_neon_vshiftu: 10351 if (isVShiftLImm(N->getOperand(2), VT, false, Cnt)) { 10352 VShiftOpc = ARMISD::VSHL; 10353 break; 10354 } 10355 if (isVShiftRImm(N->getOperand(2), VT, false, true, Cnt)) { 10356 VShiftOpc = (IntNo == Intrinsic::arm_neon_vshifts ? 10357 ARMISD::VSHRs : ARMISD::VSHRu); 10358 break; 10359 } 10360 return SDValue(); 10361 10362 case Intrinsic::arm_neon_vrshifts: 10363 case Intrinsic::arm_neon_vrshiftu: 10364 if (isVShiftRImm(N->getOperand(2), VT, false, true, Cnt)) 10365 break; 10366 return SDValue(); 10367 10368 case Intrinsic::arm_neon_vqshifts: 10369 case Intrinsic::arm_neon_vqshiftu: 10370 if (isVShiftLImm(N->getOperand(2), VT, false, Cnt)) 10371 break; 10372 return SDValue(); 10373 10374 case Intrinsic::arm_neon_vqshiftsu: 10375 if (isVShiftLImm(N->getOperand(2), VT, false, Cnt)) 10376 break; 10377 llvm_unreachable("invalid shift count for vqshlu intrinsic"); 10378 10379 case Intrinsic::arm_neon_vrshiftn: 10380 case Intrinsic::arm_neon_vqshiftns: 10381 case Intrinsic::arm_neon_vqshiftnu: 10382 case Intrinsic::arm_neon_vqshiftnsu: 10383 case Intrinsic::arm_neon_vqrshiftns: 10384 case Intrinsic::arm_neon_vqrshiftnu: 10385 case Intrinsic::arm_neon_vqrshiftnsu: 10386 // Narrowing shifts require an immediate right shift. 10387 if (isVShiftRImm(N->getOperand(2), VT, true, true, Cnt)) 10388 break; 10389 llvm_unreachable("invalid shift count for narrowing vector shift " 10390 "intrinsic"); 10391 10392 default: 10393 llvm_unreachable("unhandled vector shift"); 10394 } 10395 10396 switch (IntNo) { 10397 case Intrinsic::arm_neon_vshifts: 10398 case Intrinsic::arm_neon_vshiftu: 10399 // Opcode already set above. 10400 break; 10401 case Intrinsic::arm_neon_vrshifts: 10402 VShiftOpc = ARMISD::VRSHRs; break; 10403 case Intrinsic::arm_neon_vrshiftu: 10404 VShiftOpc = ARMISD::VRSHRu; break; 10405 case Intrinsic::arm_neon_vrshiftn: 10406 VShiftOpc = ARMISD::VRSHRN; break; 10407 case Intrinsic::arm_neon_vqshifts: 10408 VShiftOpc = ARMISD::VQSHLs; break; 10409 case Intrinsic::arm_neon_vqshiftu: 10410 VShiftOpc = ARMISD::VQSHLu; break; 10411 case Intrinsic::arm_neon_vqshiftsu: 10412 VShiftOpc = ARMISD::VQSHLsu; break; 10413 case Intrinsic::arm_neon_vqshiftns: 10414 VShiftOpc = ARMISD::VQSHRNs; break; 10415 case Intrinsic::arm_neon_vqshiftnu: 10416 VShiftOpc = ARMISD::VQSHRNu; break; 10417 case Intrinsic::arm_neon_vqshiftnsu: 10418 VShiftOpc = ARMISD::VQSHRNsu; break; 10419 case Intrinsic::arm_neon_vqrshiftns: 10420 VShiftOpc = ARMISD::VQRSHRNs; break; 10421 case Intrinsic::arm_neon_vqrshiftnu: 10422 VShiftOpc = ARMISD::VQRSHRNu; break; 10423 case Intrinsic::arm_neon_vqrshiftnsu: 10424 VShiftOpc = ARMISD::VQRSHRNsu; break; 10425 } 10426 10427 SDLoc dl(N); 10428 return DAG.getNode(VShiftOpc, dl, N->getValueType(0), 10429 N->getOperand(1), DAG.getConstant(Cnt, dl, MVT::i32)); 10430 } 10431 10432 case Intrinsic::arm_neon_vshiftins: { 10433 EVT VT = N->getOperand(1).getValueType(); 10434 int64_t Cnt; 10435 unsigned VShiftOpc = 0; 10436 10437 if (isVShiftLImm(N->getOperand(3), VT, false, Cnt)) 10438 VShiftOpc = ARMISD::VSLI; 10439 else if (isVShiftRImm(N->getOperand(3), VT, false, true, Cnt)) 10440 VShiftOpc = ARMISD::VSRI; 10441 else { 10442 llvm_unreachable("invalid shift count for vsli/vsri intrinsic"); 10443 } 10444 10445 SDLoc dl(N); 10446 return DAG.getNode(VShiftOpc, dl, N->getValueType(0), 10447 N->getOperand(1), N->getOperand(2), 10448 DAG.getConstant(Cnt, dl, MVT::i32)); 10449 } 10450 10451 case Intrinsic::arm_neon_vqrshifts: 10452 case Intrinsic::arm_neon_vqrshiftu: 10453 // No immediate versions of these to check for. 10454 break; 10455 } 10456 10457 return SDValue(); 10458 } 10459 10460 /// PerformShiftCombine - Checks for immediate versions of vector shifts and 10461 /// lowers them. As with the vector shift intrinsics, this is done during DAG 10462 /// combining instead of DAG legalizing because the build_vectors for 64-bit 10463 /// vector element shift counts are generally not legal, and it is hard to see 10464 /// their values after they get legalized to loads from a constant pool. 10465 static SDValue PerformShiftCombine(SDNode *N, SelectionDAG &DAG, 10466 const ARMSubtarget *ST) { 10467 EVT VT = N->getValueType(0); 10468 if (N->getOpcode() == ISD::SRL && VT == MVT::i32 && ST->hasV6Ops()) { 10469 // Canonicalize (srl (bswap x), 16) to (rotr (bswap x), 16) if the high 10470 // 16-bits of x is zero. This optimizes rev + lsr 16 to rev16. 10471 SDValue N1 = N->getOperand(1); 10472 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(N1)) { 10473 SDValue N0 = N->getOperand(0); 10474 if (C->getZExtValue() == 16 && N0.getOpcode() == ISD::BSWAP && 10475 DAG.MaskedValueIsZero(N0.getOperand(0), 10476 APInt::getHighBitsSet(32, 16))) 10477 return DAG.getNode(ISD::ROTR, SDLoc(N), VT, N0, N1); 10478 } 10479 } 10480 10481 // Nothing to be done for scalar shifts. 10482 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 10483 if (!VT.isVector() || !TLI.isTypeLegal(VT)) 10484 return SDValue(); 10485 10486 assert(ST->hasNEON() && "unexpected vector shift"); 10487 int64_t Cnt; 10488 10489 switch (N->getOpcode()) { 10490 default: llvm_unreachable("unexpected shift opcode"); 10491 10492 case ISD::SHL: 10493 if (isVShiftLImm(N->getOperand(1), VT, false, Cnt)) { 10494 SDLoc dl(N); 10495 return DAG.getNode(ARMISD::VSHL, dl, VT, N->getOperand(0), 10496 DAG.getConstant(Cnt, dl, MVT::i32)); 10497 } 10498 break; 10499 10500 case ISD::SRA: 10501 case ISD::SRL: 10502 if (isVShiftRImm(N->getOperand(1), VT, false, false, Cnt)) { 10503 unsigned VShiftOpc = (N->getOpcode() == ISD::SRA ? 10504 ARMISD::VSHRs : ARMISD::VSHRu); 10505 SDLoc dl(N); 10506 return DAG.getNode(VShiftOpc, dl, VT, N->getOperand(0), 10507 DAG.getConstant(Cnt, dl, MVT::i32)); 10508 } 10509 } 10510 return SDValue(); 10511 } 10512 10513 /// PerformExtendCombine - Target-specific DAG combining for ISD::SIGN_EXTEND, 10514 /// ISD::ZERO_EXTEND, and ISD::ANY_EXTEND. 10515 static SDValue PerformExtendCombine(SDNode *N, SelectionDAG &DAG, 10516 const ARMSubtarget *ST) { 10517 SDValue N0 = N->getOperand(0); 10518 10519 // Check for sign- and zero-extensions of vector extract operations of 8- 10520 // and 16-bit vector elements. NEON supports these directly. They are 10521 // handled during DAG combining because type legalization will promote them 10522 // to 32-bit types and it is messy to recognize the operations after that. 10523 if (ST->hasNEON() && N0.getOpcode() == ISD::EXTRACT_VECTOR_ELT) { 10524 SDValue Vec = N0.getOperand(0); 10525 SDValue Lane = N0.getOperand(1); 10526 EVT VT = N->getValueType(0); 10527 EVT EltVT = N0.getValueType(); 10528 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 10529 10530 if (VT == MVT::i32 && 10531 (EltVT == MVT::i8 || EltVT == MVT::i16) && 10532 TLI.isTypeLegal(Vec.getValueType()) && 10533 isa<ConstantSDNode>(Lane)) { 10534 10535 unsigned Opc = 0; 10536 switch (N->getOpcode()) { 10537 default: llvm_unreachable("unexpected opcode"); 10538 case ISD::SIGN_EXTEND: 10539 Opc = ARMISD::VGETLANEs; 10540 break; 10541 case ISD::ZERO_EXTEND: 10542 case ISD::ANY_EXTEND: 10543 Opc = ARMISD::VGETLANEu; 10544 break; 10545 } 10546 return DAG.getNode(Opc, SDLoc(N), VT, Vec, Lane); 10547 } 10548 } 10549 10550 return SDValue(); 10551 } 10552 10553 static void computeKnownBits(SelectionDAG &DAG, SDValue Op, APInt &KnownZero, 10554 APInt &KnownOne) { 10555 if (Op.getOpcode() == ARMISD::BFI) { 10556 // Conservatively, we can recurse down the first operand 10557 // and just mask out all affected bits. 10558 computeKnownBits(DAG, Op.getOperand(0), KnownZero, KnownOne); 10559 10560 // The operand to BFI is already a mask suitable for removing the bits it 10561 // sets. 10562 ConstantSDNode *CI = cast<ConstantSDNode>(Op.getOperand(2)); 10563 APInt Mask = CI->getAPIntValue(); 10564 KnownZero &= Mask; 10565 KnownOne &= Mask; 10566 return; 10567 } 10568 if (Op.getOpcode() == ARMISD::CMOV) { 10569 APInt KZ2(KnownZero.getBitWidth(), 0); 10570 APInt KO2(KnownOne.getBitWidth(), 0); 10571 computeKnownBits(DAG, Op.getOperand(1), KnownZero, KnownOne); 10572 computeKnownBits(DAG, Op.getOperand(2), KZ2, KO2); 10573 10574 KnownZero &= KZ2; 10575 KnownOne &= KO2; 10576 return; 10577 } 10578 return DAG.computeKnownBits(Op, KnownZero, KnownOne); 10579 } 10580 10581 SDValue ARMTargetLowering::PerformCMOVToBFICombine(SDNode *CMOV, SelectionDAG &DAG) const { 10582 // If we have a CMOV, OR and AND combination such as: 10583 // if (x & CN) 10584 // y |= CM; 10585 // 10586 // And: 10587 // * CN is a single bit; 10588 // * All bits covered by CM are known zero in y 10589 // 10590 // Then we can convert this into a sequence of BFI instructions. This will 10591 // always be a win if CM is a single bit, will always be no worse than the 10592 // TST&OR sequence if CM is two bits, and for thumb will be no worse if CM is 10593 // three bits (due to the extra IT instruction). 10594 10595 SDValue Op0 = CMOV->getOperand(0); 10596 SDValue Op1 = CMOV->getOperand(1); 10597 auto CCNode = cast<ConstantSDNode>(CMOV->getOperand(2)); 10598 auto CC = CCNode->getAPIntValue().getLimitedValue(); 10599 SDValue CmpZ = CMOV->getOperand(4); 10600 10601 // The compare must be against zero. 10602 if (!isNullConstant(CmpZ->getOperand(1))) 10603 return SDValue(); 10604 10605 assert(CmpZ->getOpcode() == ARMISD::CMPZ); 10606 SDValue And = CmpZ->getOperand(0); 10607 if (And->getOpcode() != ISD::AND) 10608 return SDValue(); 10609 ConstantSDNode *AndC = dyn_cast<ConstantSDNode>(And->getOperand(1)); 10610 if (!AndC || !AndC->getAPIntValue().isPowerOf2()) 10611 return SDValue(); 10612 SDValue X = And->getOperand(0); 10613 10614 if (CC == ARMCC::EQ) { 10615 // We're performing an "equal to zero" compare. Swap the operands so we 10616 // canonicalize on a "not equal to zero" compare. 10617 std::swap(Op0, Op1); 10618 } else { 10619 assert(CC == ARMCC::NE && "How can a CMPZ node not be EQ or NE?"); 10620 } 10621 10622 if (Op1->getOpcode() != ISD::OR) 10623 return SDValue(); 10624 10625 ConstantSDNode *OrC = dyn_cast<ConstantSDNode>(Op1->getOperand(1)); 10626 if (!OrC) 10627 return SDValue(); 10628 SDValue Y = Op1->getOperand(0); 10629 10630 if (Op0 != Y) 10631 return SDValue(); 10632 10633 // Now, is it profitable to continue? 10634 APInt OrCI = OrC->getAPIntValue(); 10635 unsigned Heuristic = Subtarget->isThumb() ? 3 : 2; 10636 if (OrCI.countPopulation() > Heuristic) 10637 return SDValue(); 10638 10639 // Lastly, can we determine that the bits defined by OrCI 10640 // are zero in Y? 10641 APInt KnownZero, KnownOne; 10642 computeKnownBits(DAG, Y, KnownZero, KnownOne); 10643 if ((OrCI & KnownZero) != OrCI) 10644 return SDValue(); 10645 10646 // OK, we can do the combine. 10647 SDValue V = Y; 10648 SDLoc dl(X); 10649 EVT VT = X.getValueType(); 10650 unsigned BitInX = AndC->getAPIntValue().logBase2(); 10651 10652 if (BitInX != 0) { 10653 // We must shift X first. 10654 X = DAG.getNode(ISD::SRL, dl, VT, X, 10655 DAG.getConstant(BitInX, dl, VT)); 10656 } 10657 10658 for (unsigned BitInY = 0, NumActiveBits = OrCI.getActiveBits(); 10659 BitInY < NumActiveBits; ++BitInY) { 10660 if (OrCI[BitInY] == 0) 10661 continue; 10662 APInt Mask(VT.getSizeInBits(), 0); 10663 Mask.setBit(BitInY); 10664 V = DAG.getNode(ARMISD::BFI, dl, VT, V, X, 10665 // Confusingly, the operand is an *inverted* mask. 10666 DAG.getConstant(~Mask, dl, VT)); 10667 } 10668 10669 return V; 10670 } 10671 10672 /// PerformBRCONDCombine - Target-specific DAG combining for ARMISD::BRCOND. 10673 SDValue 10674 ARMTargetLowering::PerformBRCONDCombine(SDNode *N, SelectionDAG &DAG) const { 10675 SDValue Cmp = N->getOperand(4); 10676 if (Cmp.getOpcode() != ARMISD::CMPZ) 10677 // Only looking at NE cases. 10678 return SDValue(); 10679 10680 EVT VT = N->getValueType(0); 10681 SDLoc dl(N); 10682 SDValue LHS = Cmp.getOperand(0); 10683 SDValue RHS = Cmp.getOperand(1); 10684 SDValue Chain = N->getOperand(0); 10685 SDValue BB = N->getOperand(1); 10686 SDValue ARMcc = N->getOperand(2); 10687 ARMCC::CondCodes CC = 10688 (ARMCC::CondCodes)cast<ConstantSDNode>(ARMcc)->getZExtValue(); 10689 10690 // (brcond Chain BB ne CPSR (cmpz (and (cmov 0 1 CC CPSR Cmp) 1) 0)) 10691 // -> (brcond Chain BB CC CPSR Cmp) 10692 if (CC == ARMCC::NE && LHS.getOpcode() == ISD::AND && LHS->hasOneUse() && 10693 LHS->getOperand(0)->getOpcode() == ARMISD::CMOV && 10694 LHS->getOperand(0)->hasOneUse()) { 10695 auto *LHS00C = dyn_cast<ConstantSDNode>(LHS->getOperand(0)->getOperand(0)); 10696 auto *LHS01C = dyn_cast<ConstantSDNode>(LHS->getOperand(0)->getOperand(1)); 10697 auto *LHS1C = dyn_cast<ConstantSDNode>(LHS->getOperand(1)); 10698 auto *RHSC = dyn_cast<ConstantSDNode>(RHS); 10699 if ((LHS00C && LHS00C->getZExtValue() == 0) && 10700 (LHS01C && LHS01C->getZExtValue() == 1) && 10701 (LHS1C && LHS1C->getZExtValue() == 1) && 10702 (RHSC && RHSC->getZExtValue() == 0)) { 10703 return DAG.getNode( 10704 ARMISD::BRCOND, dl, VT, Chain, BB, LHS->getOperand(0)->getOperand(2), 10705 LHS->getOperand(0)->getOperand(3), LHS->getOperand(0)->getOperand(4)); 10706 } 10707 } 10708 10709 return SDValue(); 10710 } 10711 10712 /// PerformCMOVCombine - Target-specific DAG combining for ARMISD::CMOV. 10713 SDValue 10714 ARMTargetLowering::PerformCMOVCombine(SDNode *N, SelectionDAG &DAG) const { 10715 SDValue Cmp = N->getOperand(4); 10716 if (Cmp.getOpcode() != ARMISD::CMPZ) 10717 // Only looking at EQ and NE cases. 10718 return SDValue(); 10719 10720 EVT VT = N->getValueType(0); 10721 SDLoc dl(N); 10722 SDValue LHS = Cmp.getOperand(0); 10723 SDValue RHS = Cmp.getOperand(1); 10724 SDValue FalseVal = N->getOperand(0); 10725 SDValue TrueVal = N->getOperand(1); 10726 SDValue ARMcc = N->getOperand(2); 10727 ARMCC::CondCodes CC = 10728 (ARMCC::CondCodes)cast<ConstantSDNode>(ARMcc)->getZExtValue(); 10729 10730 // BFI is only available on V6T2+. 10731 if (!Subtarget->isThumb1Only() && Subtarget->hasV6T2Ops()) { 10732 SDValue R = PerformCMOVToBFICombine(N, DAG); 10733 if (R) 10734 return R; 10735 } 10736 10737 // Simplify 10738 // mov r1, r0 10739 // cmp r1, x 10740 // mov r0, y 10741 // moveq r0, x 10742 // to 10743 // cmp r0, x 10744 // movne r0, y 10745 // 10746 // mov r1, r0 10747 // cmp r1, x 10748 // mov r0, x 10749 // movne r0, y 10750 // to 10751 // cmp r0, x 10752 // movne r0, y 10753 /// FIXME: Turn this into a target neutral optimization? 10754 SDValue Res; 10755 if (CC == ARMCC::NE && FalseVal == RHS && FalseVal != LHS) { 10756 Res = DAG.getNode(ARMISD::CMOV, dl, VT, LHS, TrueVal, ARMcc, 10757 N->getOperand(3), Cmp); 10758 } else if (CC == ARMCC::EQ && TrueVal == RHS) { 10759 SDValue ARMcc; 10760 SDValue NewCmp = getARMCmp(LHS, RHS, ISD::SETNE, ARMcc, DAG, dl); 10761 Res = DAG.getNode(ARMISD::CMOV, dl, VT, LHS, FalseVal, ARMcc, 10762 N->getOperand(3), NewCmp); 10763 } 10764 10765 // (cmov F T ne CPSR (cmpz (cmov 0 1 CC CPSR Cmp) 0)) 10766 // -> (cmov F T CC CPSR Cmp) 10767 if (CC == ARMCC::NE && LHS.getOpcode() == ARMISD::CMOV && LHS->hasOneUse()) { 10768 auto *LHS0C = dyn_cast<ConstantSDNode>(LHS->getOperand(0)); 10769 auto *LHS1C = dyn_cast<ConstantSDNode>(LHS->getOperand(1)); 10770 auto *RHSC = dyn_cast<ConstantSDNode>(RHS); 10771 if ((LHS0C && LHS0C->getZExtValue() == 0) && 10772 (LHS1C && LHS1C->getZExtValue() == 1) && 10773 (RHSC && RHSC->getZExtValue() == 0)) { 10774 return DAG.getNode(ARMISD::CMOV, dl, VT, FalseVal, TrueVal, 10775 LHS->getOperand(2), LHS->getOperand(3), 10776 LHS->getOperand(4)); 10777 } 10778 } 10779 10780 if (Res.getNode()) { 10781 APInt KnownZero, KnownOne; 10782 DAG.computeKnownBits(SDValue(N,0), KnownZero, KnownOne); 10783 // Capture demanded bits information that would be otherwise lost. 10784 if (KnownZero == 0xfffffffe) 10785 Res = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Res, 10786 DAG.getValueType(MVT::i1)); 10787 else if (KnownZero == 0xffffff00) 10788 Res = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Res, 10789 DAG.getValueType(MVT::i8)); 10790 else if (KnownZero == 0xffff0000) 10791 Res = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Res, 10792 DAG.getValueType(MVT::i16)); 10793 } 10794 10795 return Res; 10796 } 10797 10798 SDValue ARMTargetLowering::PerformDAGCombine(SDNode *N, 10799 DAGCombinerInfo &DCI) const { 10800 switch (N->getOpcode()) { 10801 default: break; 10802 case ISD::ADDC: return PerformADDCCombine(N, DCI, Subtarget); 10803 case ISD::ADD: return PerformADDCombine(N, DCI, Subtarget); 10804 case ISD::SUB: return PerformSUBCombine(N, DCI); 10805 case ISD::MUL: return PerformMULCombine(N, DCI, Subtarget); 10806 case ISD::OR: return PerformORCombine(N, DCI, Subtarget); 10807 case ISD::XOR: return PerformXORCombine(N, DCI, Subtarget); 10808 case ISD::AND: return PerformANDCombine(N, DCI, Subtarget); 10809 case ARMISD::BFI: return PerformBFICombine(N, DCI); 10810 case ARMISD::VMOVRRD: return PerformVMOVRRDCombine(N, DCI, Subtarget); 10811 case ARMISD::VMOVDRR: return PerformVMOVDRRCombine(N, DCI.DAG); 10812 case ISD::STORE: return PerformSTORECombine(N, DCI); 10813 case ISD::BUILD_VECTOR: return PerformBUILD_VECTORCombine(N, DCI, Subtarget); 10814 case ISD::INSERT_VECTOR_ELT: return PerformInsertEltCombine(N, DCI); 10815 case ISD::VECTOR_SHUFFLE: return PerformVECTOR_SHUFFLECombine(N, DCI.DAG); 10816 case ARMISD::VDUPLANE: return PerformVDUPLANECombine(N, DCI); 10817 case ISD::FP_TO_SINT: 10818 case ISD::FP_TO_UINT: 10819 return PerformVCVTCombine(N, DCI.DAG, Subtarget); 10820 case ISD::FDIV: 10821 return PerformVDIVCombine(N, DCI.DAG, Subtarget); 10822 case ISD::INTRINSIC_WO_CHAIN: return PerformIntrinsicCombine(N, DCI.DAG); 10823 case ISD::SHL: 10824 case ISD::SRA: 10825 case ISD::SRL: return PerformShiftCombine(N, DCI.DAG, Subtarget); 10826 case ISD::SIGN_EXTEND: 10827 case ISD::ZERO_EXTEND: 10828 case ISD::ANY_EXTEND: return PerformExtendCombine(N, DCI.DAG, Subtarget); 10829 case ARMISD::CMOV: return PerformCMOVCombine(N, DCI.DAG); 10830 case ARMISD::BRCOND: return PerformBRCONDCombine(N, DCI.DAG); 10831 case ISD::LOAD: return PerformLOADCombine(N, DCI); 10832 case ARMISD::VLD2DUP: 10833 case ARMISD::VLD3DUP: 10834 case ARMISD::VLD4DUP: 10835 return PerformVLDCombine(N, DCI); 10836 case ARMISD::BUILD_VECTOR: 10837 return PerformARMBUILD_VECTORCombine(N, DCI); 10838 case ISD::INTRINSIC_VOID: 10839 case ISD::INTRINSIC_W_CHAIN: 10840 switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) { 10841 case Intrinsic::arm_neon_vld1: 10842 case Intrinsic::arm_neon_vld2: 10843 case Intrinsic::arm_neon_vld3: 10844 case Intrinsic::arm_neon_vld4: 10845 case Intrinsic::arm_neon_vld2lane: 10846 case Intrinsic::arm_neon_vld3lane: 10847 case Intrinsic::arm_neon_vld4lane: 10848 case Intrinsic::arm_neon_vst1: 10849 case Intrinsic::arm_neon_vst2: 10850 case Intrinsic::arm_neon_vst3: 10851 case Intrinsic::arm_neon_vst4: 10852 case Intrinsic::arm_neon_vst2lane: 10853 case Intrinsic::arm_neon_vst3lane: 10854 case Intrinsic::arm_neon_vst4lane: 10855 return PerformVLDCombine(N, DCI); 10856 default: break; 10857 } 10858 break; 10859 } 10860 return SDValue(); 10861 } 10862 10863 bool ARMTargetLowering::isDesirableToTransformToIntegerOp(unsigned Opc, 10864 EVT VT) const { 10865 return (VT == MVT::f32) && (Opc == ISD::LOAD || Opc == ISD::STORE); 10866 } 10867 10868 bool ARMTargetLowering::allowsMisalignedMemoryAccesses(EVT VT, 10869 unsigned, 10870 unsigned, 10871 bool *Fast) const { 10872 // The AllowsUnaliged flag models the SCTLR.A setting in ARM cpus 10873 bool AllowsUnaligned = Subtarget->allowsUnalignedMem(); 10874 10875 switch (VT.getSimpleVT().SimpleTy) { 10876 default: 10877 return false; 10878 case MVT::i8: 10879 case MVT::i16: 10880 case MVT::i32: { 10881 // Unaligned access can use (for example) LRDB, LRDH, LDR 10882 if (AllowsUnaligned) { 10883 if (Fast) 10884 *Fast = Subtarget->hasV7Ops(); 10885 return true; 10886 } 10887 return false; 10888 } 10889 case MVT::f64: 10890 case MVT::v2f64: { 10891 // For any little-endian targets with neon, we can support unaligned ld/st 10892 // of D and Q (e.g. {D0,D1}) registers by using vld1.i8/vst1.i8. 10893 // A big-endian target may also explicitly support unaligned accesses 10894 if (Subtarget->hasNEON() && (AllowsUnaligned || Subtarget->isLittle())) { 10895 if (Fast) 10896 *Fast = true; 10897 return true; 10898 } 10899 return false; 10900 } 10901 } 10902 } 10903 10904 static bool memOpAlign(unsigned DstAlign, unsigned SrcAlign, 10905 unsigned AlignCheck) { 10906 return ((SrcAlign == 0 || SrcAlign % AlignCheck == 0) && 10907 (DstAlign == 0 || DstAlign % AlignCheck == 0)); 10908 } 10909 10910 EVT ARMTargetLowering::getOptimalMemOpType(uint64_t Size, 10911 unsigned DstAlign, unsigned SrcAlign, 10912 bool IsMemset, bool ZeroMemset, 10913 bool MemcpyStrSrc, 10914 MachineFunction &MF) const { 10915 const Function *F = MF.getFunction(); 10916 10917 // See if we can use NEON instructions for this... 10918 if ((!IsMemset || ZeroMemset) && Subtarget->hasNEON() && 10919 !F->hasFnAttribute(Attribute::NoImplicitFloat)) { 10920 bool Fast; 10921 if (Size >= 16 && 10922 (memOpAlign(SrcAlign, DstAlign, 16) || 10923 (allowsMisalignedMemoryAccesses(MVT::v2f64, 0, 1, &Fast) && Fast))) { 10924 return MVT::v2f64; 10925 } else if (Size >= 8 && 10926 (memOpAlign(SrcAlign, DstAlign, 8) || 10927 (allowsMisalignedMemoryAccesses(MVT::f64, 0, 1, &Fast) && 10928 Fast))) { 10929 return MVT::f64; 10930 } 10931 } 10932 10933 // Lowering to i32/i16 if the size permits. 10934 if (Size >= 4) 10935 return MVT::i32; 10936 else if (Size >= 2) 10937 return MVT::i16; 10938 10939 // Let the target-independent logic figure it out. 10940 return MVT::Other; 10941 } 10942 10943 bool ARMTargetLowering::isZExtFree(SDValue Val, EVT VT2) const { 10944 if (Val.getOpcode() != ISD::LOAD) 10945 return false; 10946 10947 EVT VT1 = Val.getValueType(); 10948 if (!VT1.isSimple() || !VT1.isInteger() || 10949 !VT2.isSimple() || !VT2.isInteger()) 10950 return false; 10951 10952 switch (VT1.getSimpleVT().SimpleTy) { 10953 default: break; 10954 case MVT::i1: 10955 case MVT::i8: 10956 case MVT::i16: 10957 // 8-bit and 16-bit loads implicitly zero-extend to 32-bits. 10958 return true; 10959 } 10960 10961 return false; 10962 } 10963 10964 bool ARMTargetLowering::isVectorLoadExtDesirable(SDValue ExtVal) const { 10965 EVT VT = ExtVal.getValueType(); 10966 10967 if (!isTypeLegal(VT)) 10968 return false; 10969 10970 // Don't create a loadext if we can fold the extension into a wide/long 10971 // instruction. 10972 // If there's more than one user instruction, the loadext is desirable no 10973 // matter what. There can be two uses by the same instruction. 10974 if (ExtVal->use_empty() || 10975 !ExtVal->use_begin()->isOnlyUserOf(ExtVal.getNode())) 10976 return true; 10977 10978 SDNode *U = *ExtVal->use_begin(); 10979 if ((U->getOpcode() == ISD::ADD || U->getOpcode() == ISD::SUB || 10980 U->getOpcode() == ISD::SHL || U->getOpcode() == ARMISD::VSHL)) 10981 return false; 10982 10983 return true; 10984 } 10985 10986 bool ARMTargetLowering::allowTruncateForTailCall(Type *Ty1, Type *Ty2) const { 10987 if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy()) 10988 return false; 10989 10990 if (!isTypeLegal(EVT::getEVT(Ty1))) 10991 return false; 10992 10993 assert(Ty1->getPrimitiveSizeInBits() <= 64 && "i128 is probably not a noop"); 10994 10995 // Assuming the caller doesn't have a zeroext or signext return parameter, 10996 // truncation all the way down to i1 is valid. 10997 return true; 10998 } 10999 11000 11001 static bool isLegalT1AddressImmediate(int64_t V, EVT VT) { 11002 if (V < 0) 11003 return false; 11004 11005 unsigned Scale = 1; 11006 switch (VT.getSimpleVT().SimpleTy) { 11007 default: return false; 11008 case MVT::i1: 11009 case MVT::i8: 11010 // Scale == 1; 11011 break; 11012 case MVT::i16: 11013 // Scale == 2; 11014 Scale = 2; 11015 break; 11016 case MVT::i32: 11017 // Scale == 4; 11018 Scale = 4; 11019 break; 11020 } 11021 11022 if ((V & (Scale - 1)) != 0) 11023 return false; 11024 V /= Scale; 11025 return V == (V & ((1LL << 5) - 1)); 11026 } 11027 11028 static bool isLegalT2AddressImmediate(int64_t V, EVT VT, 11029 const ARMSubtarget *Subtarget) { 11030 bool isNeg = false; 11031 if (V < 0) { 11032 isNeg = true; 11033 V = - V; 11034 } 11035 11036 switch (VT.getSimpleVT().SimpleTy) { 11037 default: return false; 11038 case MVT::i1: 11039 case MVT::i8: 11040 case MVT::i16: 11041 case MVT::i32: 11042 // + imm12 or - imm8 11043 if (isNeg) 11044 return V == (V & ((1LL << 8) - 1)); 11045 return V == (V & ((1LL << 12) - 1)); 11046 case MVT::f32: 11047 case MVT::f64: 11048 // Same as ARM mode. FIXME: NEON? 11049 if (!Subtarget->hasVFP2()) 11050 return false; 11051 if ((V & 3) != 0) 11052 return false; 11053 V >>= 2; 11054 return V == (V & ((1LL << 8) - 1)); 11055 } 11056 } 11057 11058 /// isLegalAddressImmediate - Return true if the integer value can be used 11059 /// as the offset of the target addressing mode for load / store of the 11060 /// given type. 11061 static bool isLegalAddressImmediate(int64_t V, EVT VT, 11062 const ARMSubtarget *Subtarget) { 11063 if (V == 0) 11064 return true; 11065 11066 if (!VT.isSimple()) 11067 return false; 11068 11069 if (Subtarget->isThumb1Only()) 11070 return isLegalT1AddressImmediate(V, VT); 11071 else if (Subtarget->isThumb2()) 11072 return isLegalT2AddressImmediate(V, VT, Subtarget); 11073 11074 // ARM mode. 11075 if (V < 0) 11076 V = - V; 11077 switch (VT.getSimpleVT().SimpleTy) { 11078 default: return false; 11079 case MVT::i1: 11080 case MVT::i8: 11081 case MVT::i32: 11082 // +- imm12 11083 return V == (V & ((1LL << 12) - 1)); 11084 case MVT::i16: 11085 // +- imm8 11086 return V == (V & ((1LL << 8) - 1)); 11087 case MVT::f32: 11088 case MVT::f64: 11089 if (!Subtarget->hasVFP2()) // FIXME: NEON? 11090 return false; 11091 if ((V & 3) != 0) 11092 return false; 11093 V >>= 2; 11094 return V == (V & ((1LL << 8) - 1)); 11095 } 11096 } 11097 11098 bool ARMTargetLowering::isLegalT2ScaledAddressingMode(const AddrMode &AM, 11099 EVT VT) const { 11100 int Scale = AM.Scale; 11101 if (Scale < 0) 11102 return false; 11103 11104 switch (VT.getSimpleVT().SimpleTy) { 11105 default: return false; 11106 case MVT::i1: 11107 case MVT::i8: 11108 case MVT::i16: 11109 case MVT::i32: 11110 if (Scale == 1) 11111 return true; 11112 // r + r << imm 11113 Scale = Scale & ~1; 11114 return Scale == 2 || Scale == 4 || Scale == 8; 11115 case MVT::i64: 11116 // r + r 11117 if (((unsigned)AM.HasBaseReg + Scale) <= 2) 11118 return true; 11119 return false; 11120 case MVT::isVoid: 11121 // Note, we allow "void" uses (basically, uses that aren't loads or 11122 // stores), because arm allows folding a scale into many arithmetic 11123 // operations. This should be made more precise and revisited later. 11124 11125 // Allow r << imm, but the imm has to be a multiple of two. 11126 if (Scale & 1) return false; 11127 return isPowerOf2_32(Scale); 11128 } 11129 } 11130 11131 /// isLegalAddressingMode - Return true if the addressing mode represented 11132 /// by AM is legal for this target, for a load/store of the specified type. 11133 bool ARMTargetLowering::isLegalAddressingMode(const DataLayout &DL, 11134 const AddrMode &AM, Type *Ty, 11135 unsigned AS) const { 11136 EVT VT = getValueType(DL, Ty, true); 11137 if (!isLegalAddressImmediate(AM.BaseOffs, VT, Subtarget)) 11138 return false; 11139 11140 // Can never fold addr of global into load/store. 11141 if (AM.BaseGV) 11142 return false; 11143 11144 switch (AM.Scale) { 11145 case 0: // no scale reg, must be "r+i" or "r", or "i". 11146 break; 11147 case 1: 11148 if (Subtarget->isThumb1Only()) 11149 return false; 11150 // FALL THROUGH. 11151 default: 11152 // ARM doesn't support any R+R*scale+imm addr modes. 11153 if (AM.BaseOffs) 11154 return false; 11155 11156 if (!VT.isSimple()) 11157 return false; 11158 11159 if (Subtarget->isThumb2()) 11160 return isLegalT2ScaledAddressingMode(AM, VT); 11161 11162 int Scale = AM.Scale; 11163 switch (VT.getSimpleVT().SimpleTy) { 11164 default: return false; 11165 case MVT::i1: 11166 case MVT::i8: 11167 case MVT::i32: 11168 if (Scale < 0) Scale = -Scale; 11169 if (Scale == 1) 11170 return true; 11171 // r + r << imm 11172 return isPowerOf2_32(Scale & ~1); 11173 case MVT::i16: 11174 case MVT::i64: 11175 // r + r 11176 if (((unsigned)AM.HasBaseReg + Scale) <= 2) 11177 return true; 11178 return false; 11179 11180 case MVT::isVoid: 11181 // Note, we allow "void" uses (basically, uses that aren't loads or 11182 // stores), because arm allows folding a scale into many arithmetic 11183 // operations. This should be made more precise and revisited later. 11184 11185 // Allow r << imm, but the imm has to be a multiple of two. 11186 if (Scale & 1) return false; 11187 return isPowerOf2_32(Scale); 11188 } 11189 } 11190 return true; 11191 } 11192 11193 /// isLegalICmpImmediate - Return true if the specified immediate is legal 11194 /// icmp immediate, that is the target has icmp instructions which can compare 11195 /// a register against the immediate without having to materialize the 11196 /// immediate into a register. 11197 bool ARMTargetLowering::isLegalICmpImmediate(int64_t Imm) const { 11198 // Thumb2 and ARM modes can use cmn for negative immediates. 11199 if (!Subtarget->isThumb()) 11200 return ARM_AM::getSOImmVal(std::abs(Imm)) != -1; 11201 if (Subtarget->isThumb2()) 11202 return ARM_AM::getT2SOImmVal(std::abs(Imm)) != -1; 11203 // Thumb1 doesn't have cmn, and only 8-bit immediates. 11204 return Imm >= 0 && Imm <= 255; 11205 } 11206 11207 /// isLegalAddImmediate - Return true if the specified immediate is a legal add 11208 /// *or sub* immediate, that is the target has add or sub instructions which can 11209 /// add a register with the immediate without having to materialize the 11210 /// immediate into a register. 11211 bool ARMTargetLowering::isLegalAddImmediate(int64_t Imm) const { 11212 // Same encoding for add/sub, just flip the sign. 11213 int64_t AbsImm = std::abs(Imm); 11214 if (!Subtarget->isThumb()) 11215 return ARM_AM::getSOImmVal(AbsImm) != -1; 11216 if (Subtarget->isThumb2()) 11217 return ARM_AM::getT2SOImmVal(AbsImm) != -1; 11218 // Thumb1 only has 8-bit unsigned immediate. 11219 return AbsImm >= 0 && AbsImm <= 255; 11220 } 11221 11222 static bool getARMIndexedAddressParts(SDNode *Ptr, EVT VT, 11223 bool isSEXTLoad, SDValue &Base, 11224 SDValue &Offset, bool &isInc, 11225 SelectionDAG &DAG) { 11226 if (Ptr->getOpcode() != ISD::ADD && Ptr->getOpcode() != ISD::SUB) 11227 return false; 11228 11229 if (VT == MVT::i16 || ((VT == MVT::i8 || VT == MVT::i1) && isSEXTLoad)) { 11230 // AddressingMode 3 11231 Base = Ptr->getOperand(0); 11232 if (ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(Ptr->getOperand(1))) { 11233 int RHSC = (int)RHS->getZExtValue(); 11234 if (RHSC < 0 && RHSC > -256) { 11235 assert(Ptr->getOpcode() == ISD::ADD); 11236 isInc = false; 11237 Offset = DAG.getConstant(-RHSC, SDLoc(Ptr), RHS->getValueType(0)); 11238 return true; 11239 } 11240 } 11241 isInc = (Ptr->getOpcode() == ISD::ADD); 11242 Offset = Ptr->getOperand(1); 11243 return true; 11244 } else if (VT == MVT::i32 || VT == MVT::i8 || VT == MVT::i1) { 11245 // AddressingMode 2 11246 if (ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(Ptr->getOperand(1))) { 11247 int RHSC = (int)RHS->getZExtValue(); 11248 if (RHSC < 0 && RHSC > -0x1000) { 11249 assert(Ptr->getOpcode() == ISD::ADD); 11250 isInc = false; 11251 Offset = DAG.getConstant(-RHSC, SDLoc(Ptr), RHS->getValueType(0)); 11252 Base = Ptr->getOperand(0); 11253 return true; 11254 } 11255 } 11256 11257 if (Ptr->getOpcode() == ISD::ADD) { 11258 isInc = true; 11259 ARM_AM::ShiftOpc ShOpcVal= 11260 ARM_AM::getShiftOpcForNode(Ptr->getOperand(0).getOpcode()); 11261 if (ShOpcVal != ARM_AM::no_shift) { 11262 Base = Ptr->getOperand(1); 11263 Offset = Ptr->getOperand(0); 11264 } else { 11265 Base = Ptr->getOperand(0); 11266 Offset = Ptr->getOperand(1); 11267 } 11268 return true; 11269 } 11270 11271 isInc = (Ptr->getOpcode() == ISD::ADD); 11272 Base = Ptr->getOperand(0); 11273 Offset = Ptr->getOperand(1); 11274 return true; 11275 } 11276 11277 // FIXME: Use VLDM / VSTM to emulate indexed FP load / store. 11278 return false; 11279 } 11280 11281 static bool getT2IndexedAddressParts(SDNode *Ptr, EVT VT, 11282 bool isSEXTLoad, SDValue &Base, 11283 SDValue &Offset, bool &isInc, 11284 SelectionDAG &DAG) { 11285 if (Ptr->getOpcode() != ISD::ADD && Ptr->getOpcode() != ISD::SUB) 11286 return false; 11287 11288 Base = Ptr->getOperand(0); 11289 if (ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(Ptr->getOperand(1))) { 11290 int RHSC = (int)RHS->getZExtValue(); 11291 if (RHSC < 0 && RHSC > -0x100) { // 8 bits. 11292 assert(Ptr->getOpcode() == ISD::ADD); 11293 isInc = false; 11294 Offset = DAG.getConstant(-RHSC, SDLoc(Ptr), RHS->getValueType(0)); 11295 return true; 11296 } else if (RHSC > 0 && RHSC < 0x100) { // 8 bit, no zero. 11297 isInc = Ptr->getOpcode() == ISD::ADD; 11298 Offset = DAG.getConstant(RHSC, SDLoc(Ptr), RHS->getValueType(0)); 11299 return true; 11300 } 11301 } 11302 11303 return false; 11304 } 11305 11306 /// getPreIndexedAddressParts - returns true by value, base pointer and 11307 /// offset pointer and addressing mode by reference if the node's address 11308 /// can be legally represented as pre-indexed load / store address. 11309 bool 11310 ARMTargetLowering::getPreIndexedAddressParts(SDNode *N, SDValue &Base, 11311 SDValue &Offset, 11312 ISD::MemIndexedMode &AM, 11313 SelectionDAG &DAG) const { 11314 if (Subtarget->isThumb1Only()) 11315 return false; 11316 11317 EVT VT; 11318 SDValue Ptr; 11319 bool isSEXTLoad = false; 11320 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) { 11321 Ptr = LD->getBasePtr(); 11322 VT = LD->getMemoryVT(); 11323 isSEXTLoad = LD->getExtensionType() == ISD::SEXTLOAD; 11324 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) { 11325 Ptr = ST->getBasePtr(); 11326 VT = ST->getMemoryVT(); 11327 } else 11328 return false; 11329 11330 bool isInc; 11331 bool isLegal = false; 11332 if (Subtarget->isThumb2()) 11333 isLegal = getT2IndexedAddressParts(Ptr.getNode(), VT, isSEXTLoad, Base, 11334 Offset, isInc, DAG); 11335 else 11336 isLegal = getARMIndexedAddressParts(Ptr.getNode(), VT, isSEXTLoad, Base, 11337 Offset, isInc, DAG); 11338 if (!isLegal) 11339 return false; 11340 11341 AM = isInc ? ISD::PRE_INC : ISD::PRE_DEC; 11342 return true; 11343 } 11344 11345 /// getPostIndexedAddressParts - returns true by value, base pointer and 11346 /// offset pointer and addressing mode by reference if this node can be 11347 /// combined with a load / store to form a post-indexed load / store. 11348 bool ARMTargetLowering::getPostIndexedAddressParts(SDNode *N, SDNode *Op, 11349 SDValue &Base, 11350 SDValue &Offset, 11351 ISD::MemIndexedMode &AM, 11352 SelectionDAG &DAG) const { 11353 if (Subtarget->isThumb1Only()) 11354 return false; 11355 11356 EVT VT; 11357 SDValue Ptr; 11358 bool isSEXTLoad = false; 11359 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) { 11360 VT = LD->getMemoryVT(); 11361 Ptr = LD->getBasePtr(); 11362 isSEXTLoad = LD->getExtensionType() == ISD::SEXTLOAD; 11363 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) { 11364 VT = ST->getMemoryVT(); 11365 Ptr = ST->getBasePtr(); 11366 } else 11367 return false; 11368 11369 bool isInc; 11370 bool isLegal = false; 11371 if (Subtarget->isThumb2()) 11372 isLegal = getT2IndexedAddressParts(Op, VT, isSEXTLoad, Base, Offset, 11373 isInc, DAG); 11374 else 11375 isLegal = getARMIndexedAddressParts(Op, VT, isSEXTLoad, Base, Offset, 11376 isInc, DAG); 11377 if (!isLegal) 11378 return false; 11379 11380 if (Ptr != Base) { 11381 // Swap base ptr and offset to catch more post-index load / store when 11382 // it's legal. In Thumb2 mode, offset must be an immediate. 11383 if (Ptr == Offset && Op->getOpcode() == ISD::ADD && 11384 !Subtarget->isThumb2()) 11385 std::swap(Base, Offset); 11386 11387 // Post-indexed load / store update the base pointer. 11388 if (Ptr != Base) 11389 return false; 11390 } 11391 11392 AM = isInc ? ISD::POST_INC : ISD::POST_DEC; 11393 return true; 11394 } 11395 11396 void ARMTargetLowering::computeKnownBitsForTargetNode(const SDValue Op, 11397 APInt &KnownZero, 11398 APInt &KnownOne, 11399 const SelectionDAG &DAG, 11400 unsigned Depth) const { 11401 unsigned BitWidth = KnownOne.getBitWidth(); 11402 KnownZero = KnownOne = APInt(BitWidth, 0); 11403 switch (Op.getOpcode()) { 11404 default: break; 11405 case ARMISD::ADDC: 11406 case ARMISD::ADDE: 11407 case ARMISD::SUBC: 11408 case ARMISD::SUBE: 11409 // These nodes' second result is a boolean 11410 if (Op.getResNo() == 0) 11411 break; 11412 KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - 1); 11413 break; 11414 case ARMISD::CMOV: { 11415 // Bits are known zero/one if known on the LHS and RHS. 11416 DAG.computeKnownBits(Op.getOperand(0), KnownZero, KnownOne, Depth+1); 11417 if (KnownZero == 0 && KnownOne == 0) return; 11418 11419 APInt KnownZeroRHS, KnownOneRHS; 11420 DAG.computeKnownBits(Op.getOperand(1), KnownZeroRHS, KnownOneRHS, Depth+1); 11421 KnownZero &= KnownZeroRHS; 11422 KnownOne &= KnownOneRHS; 11423 return; 11424 } 11425 case ISD::INTRINSIC_W_CHAIN: { 11426 ConstantSDNode *CN = cast<ConstantSDNode>(Op->getOperand(1)); 11427 Intrinsic::ID IntID = static_cast<Intrinsic::ID>(CN->getZExtValue()); 11428 switch (IntID) { 11429 default: return; 11430 case Intrinsic::arm_ldaex: 11431 case Intrinsic::arm_ldrex: { 11432 EVT VT = cast<MemIntrinsicSDNode>(Op)->getMemoryVT(); 11433 unsigned MemBits = VT.getScalarType().getSizeInBits(); 11434 KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - MemBits); 11435 return; 11436 } 11437 } 11438 } 11439 } 11440 } 11441 11442 //===----------------------------------------------------------------------===// 11443 // ARM Inline Assembly Support 11444 //===----------------------------------------------------------------------===// 11445 11446 bool ARMTargetLowering::ExpandInlineAsm(CallInst *CI) const { 11447 // Looking for "rev" which is V6+. 11448 if (!Subtarget->hasV6Ops()) 11449 return false; 11450 11451 InlineAsm *IA = cast<InlineAsm>(CI->getCalledValue()); 11452 std::string AsmStr = IA->getAsmString(); 11453 SmallVector<StringRef, 4> AsmPieces; 11454 SplitString(AsmStr, AsmPieces, ";\n"); 11455 11456 switch (AsmPieces.size()) { 11457 default: return false; 11458 case 1: 11459 AsmStr = AsmPieces[0]; 11460 AsmPieces.clear(); 11461 SplitString(AsmStr, AsmPieces, " \t,"); 11462 11463 // rev $0, $1 11464 if (AsmPieces.size() == 3 && 11465 AsmPieces[0] == "rev" && AsmPieces[1] == "$0" && AsmPieces[2] == "$1" && 11466 IA->getConstraintString().compare(0, 4, "=l,l") == 0) { 11467 IntegerType *Ty = dyn_cast<IntegerType>(CI->getType()); 11468 if (Ty && Ty->getBitWidth() == 32) 11469 return IntrinsicLowering::LowerToByteSwap(CI); 11470 } 11471 break; 11472 } 11473 11474 return false; 11475 } 11476 11477 /// getConstraintType - Given a constraint letter, return the type of 11478 /// constraint it is for this target. 11479 ARMTargetLowering::ConstraintType 11480 ARMTargetLowering::getConstraintType(StringRef Constraint) const { 11481 if (Constraint.size() == 1) { 11482 switch (Constraint[0]) { 11483 default: break; 11484 case 'l': return C_RegisterClass; 11485 case 'w': return C_RegisterClass; 11486 case 'h': return C_RegisterClass; 11487 case 'x': return C_RegisterClass; 11488 case 't': return C_RegisterClass; 11489 case 'j': return C_Other; // Constant for movw. 11490 // An address with a single base register. Due to the way we 11491 // currently handle addresses it is the same as an 'r' memory constraint. 11492 case 'Q': return C_Memory; 11493 } 11494 } else if (Constraint.size() == 2) { 11495 switch (Constraint[0]) { 11496 default: break; 11497 // All 'U+' constraints are addresses. 11498 case 'U': return C_Memory; 11499 } 11500 } 11501 return TargetLowering::getConstraintType(Constraint); 11502 } 11503 11504 /// Examine constraint type and operand type and determine a weight value. 11505 /// This object must already have been set up with the operand type 11506 /// and the current alternative constraint selected. 11507 TargetLowering::ConstraintWeight 11508 ARMTargetLowering::getSingleConstraintMatchWeight( 11509 AsmOperandInfo &info, const char *constraint) const { 11510 ConstraintWeight weight = CW_Invalid; 11511 Value *CallOperandVal = info.CallOperandVal; 11512 // If we don't have a value, we can't do a match, 11513 // but allow it at the lowest weight. 11514 if (!CallOperandVal) 11515 return CW_Default; 11516 Type *type = CallOperandVal->getType(); 11517 // Look at the constraint type. 11518 switch (*constraint) { 11519 default: 11520 weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint); 11521 break; 11522 case 'l': 11523 if (type->isIntegerTy()) { 11524 if (Subtarget->isThumb()) 11525 weight = CW_SpecificReg; 11526 else 11527 weight = CW_Register; 11528 } 11529 break; 11530 case 'w': 11531 if (type->isFloatingPointTy()) 11532 weight = CW_Register; 11533 break; 11534 } 11535 return weight; 11536 } 11537 11538 typedef std::pair<unsigned, const TargetRegisterClass*> RCPair; 11539 RCPair ARMTargetLowering::getRegForInlineAsmConstraint( 11540 const TargetRegisterInfo *TRI, StringRef Constraint, MVT VT) const { 11541 if (Constraint.size() == 1) { 11542 // GCC ARM Constraint Letters 11543 switch (Constraint[0]) { 11544 case 'l': // Low regs or general regs. 11545 if (Subtarget->isThumb()) 11546 return RCPair(0U, &ARM::tGPRRegClass); 11547 return RCPair(0U, &ARM::GPRRegClass); 11548 case 'h': // High regs or no regs. 11549 if (Subtarget->isThumb()) 11550 return RCPair(0U, &ARM::hGPRRegClass); 11551 break; 11552 case 'r': 11553 if (Subtarget->isThumb1Only()) 11554 return RCPair(0U, &ARM::tGPRRegClass); 11555 return RCPair(0U, &ARM::GPRRegClass); 11556 case 'w': 11557 if (VT == MVT::Other) 11558 break; 11559 if (VT == MVT::f32) 11560 return RCPair(0U, &ARM::SPRRegClass); 11561 if (VT.getSizeInBits() == 64) 11562 return RCPair(0U, &ARM::DPRRegClass); 11563 if (VT.getSizeInBits() == 128) 11564 return RCPair(0U, &ARM::QPRRegClass); 11565 break; 11566 case 'x': 11567 if (VT == MVT::Other) 11568 break; 11569 if (VT == MVT::f32) 11570 return RCPair(0U, &ARM::SPR_8RegClass); 11571 if (VT.getSizeInBits() == 64) 11572 return RCPair(0U, &ARM::DPR_8RegClass); 11573 if (VT.getSizeInBits() == 128) 11574 return RCPair(0U, &ARM::QPR_8RegClass); 11575 break; 11576 case 't': 11577 if (VT == MVT::f32) 11578 return RCPair(0U, &ARM::SPRRegClass); 11579 break; 11580 } 11581 } 11582 if (StringRef("{cc}").equals_lower(Constraint)) 11583 return std::make_pair(unsigned(ARM::CPSR), &ARM::CCRRegClass); 11584 11585 return TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT); 11586 } 11587 11588 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops 11589 /// vector. If it is invalid, don't add anything to Ops. 11590 void ARMTargetLowering::LowerAsmOperandForConstraint(SDValue Op, 11591 std::string &Constraint, 11592 std::vector<SDValue>&Ops, 11593 SelectionDAG &DAG) const { 11594 SDValue Result; 11595 11596 // Currently only support length 1 constraints. 11597 if (Constraint.length() != 1) return; 11598 11599 char ConstraintLetter = Constraint[0]; 11600 switch (ConstraintLetter) { 11601 default: break; 11602 case 'j': 11603 case 'I': case 'J': case 'K': case 'L': 11604 case 'M': case 'N': case 'O': 11605 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op); 11606 if (!C) 11607 return; 11608 11609 int64_t CVal64 = C->getSExtValue(); 11610 int CVal = (int) CVal64; 11611 // None of these constraints allow values larger than 32 bits. Check 11612 // that the value fits in an int. 11613 if (CVal != CVal64) 11614 return; 11615 11616 switch (ConstraintLetter) { 11617 case 'j': 11618 // Constant suitable for movw, must be between 0 and 11619 // 65535. 11620 if (Subtarget->hasV6T2Ops()) 11621 if (CVal >= 0 && CVal <= 65535) 11622 break; 11623 return; 11624 case 'I': 11625 if (Subtarget->isThumb1Only()) { 11626 // This must be a constant between 0 and 255, for ADD 11627 // immediates. 11628 if (CVal >= 0 && CVal <= 255) 11629 break; 11630 } else if (Subtarget->isThumb2()) { 11631 // A constant that can be used as an immediate value in a 11632 // data-processing instruction. 11633 if (ARM_AM::getT2SOImmVal(CVal) != -1) 11634 break; 11635 } else { 11636 // A constant that can be used as an immediate value in a 11637 // data-processing instruction. 11638 if (ARM_AM::getSOImmVal(CVal) != -1) 11639 break; 11640 } 11641 return; 11642 11643 case 'J': 11644 if (Subtarget->isThumb1Only()) { 11645 // This must be a constant between -255 and -1, for negated ADD 11646 // immediates. This can be used in GCC with an "n" modifier that 11647 // prints the negated value, for use with SUB instructions. It is 11648 // not useful otherwise but is implemented for compatibility. 11649 if (CVal >= -255 && CVal <= -1) 11650 break; 11651 } else { 11652 // This must be a constant between -4095 and 4095. It is not clear 11653 // what this constraint is intended for. Implemented for 11654 // compatibility with GCC. 11655 if (CVal >= -4095 && CVal <= 4095) 11656 break; 11657 } 11658 return; 11659 11660 case 'K': 11661 if (Subtarget->isThumb1Only()) { 11662 // A 32-bit value where only one byte has a nonzero value. Exclude 11663 // zero to match GCC. This constraint is used by GCC internally for 11664 // constants that can be loaded with a move/shift combination. 11665 // It is not useful otherwise but is implemented for compatibility. 11666 if (CVal != 0 && ARM_AM::isThumbImmShiftedVal(CVal)) 11667 break; 11668 } else if (Subtarget->isThumb2()) { 11669 // A constant whose bitwise inverse can be used as an immediate 11670 // value in a data-processing instruction. This can be used in GCC 11671 // with a "B" modifier that prints the inverted value, for use with 11672 // BIC and MVN instructions. It is not useful otherwise but is 11673 // implemented for compatibility. 11674 if (ARM_AM::getT2SOImmVal(~CVal) != -1) 11675 break; 11676 } else { 11677 // A constant whose bitwise inverse can be used as an immediate 11678 // value in a data-processing instruction. This can be used in GCC 11679 // with a "B" modifier that prints the inverted value, for use with 11680 // BIC and MVN instructions. It is not useful otherwise but is 11681 // implemented for compatibility. 11682 if (ARM_AM::getSOImmVal(~CVal) != -1) 11683 break; 11684 } 11685 return; 11686 11687 case 'L': 11688 if (Subtarget->isThumb1Only()) { 11689 // This must be a constant between -7 and 7, 11690 // for 3-operand ADD/SUB immediate instructions. 11691 if (CVal >= -7 && CVal < 7) 11692 break; 11693 } else if (Subtarget->isThumb2()) { 11694 // A constant whose negation can be used as an immediate value in a 11695 // data-processing instruction. This can be used in GCC with an "n" 11696 // modifier that prints the negated value, for use with SUB 11697 // instructions. It is not useful otherwise but is implemented for 11698 // compatibility. 11699 if (ARM_AM::getT2SOImmVal(-CVal) != -1) 11700 break; 11701 } else { 11702 // A constant whose negation can be used as an immediate value in a 11703 // data-processing instruction. This can be used in GCC with an "n" 11704 // modifier that prints the negated value, for use with SUB 11705 // instructions. It is not useful otherwise but is implemented for 11706 // compatibility. 11707 if (ARM_AM::getSOImmVal(-CVal) != -1) 11708 break; 11709 } 11710 return; 11711 11712 case 'M': 11713 if (Subtarget->isThumb1Only()) { 11714 // This must be a multiple of 4 between 0 and 1020, for 11715 // ADD sp + immediate. 11716 if ((CVal >= 0 && CVal <= 1020) && ((CVal & 3) == 0)) 11717 break; 11718 } else { 11719 // A power of two or a constant between 0 and 32. This is used in 11720 // GCC for the shift amount on shifted register operands, but it is 11721 // useful in general for any shift amounts. 11722 if ((CVal >= 0 && CVal <= 32) || ((CVal & (CVal - 1)) == 0)) 11723 break; 11724 } 11725 return; 11726 11727 case 'N': 11728 if (Subtarget->isThumb()) { // FIXME thumb2 11729 // This must be a constant between 0 and 31, for shift amounts. 11730 if (CVal >= 0 && CVal <= 31) 11731 break; 11732 } 11733 return; 11734 11735 case 'O': 11736 if (Subtarget->isThumb()) { // FIXME thumb2 11737 // This must be a multiple of 4 between -508 and 508, for 11738 // ADD/SUB sp = sp + immediate. 11739 if ((CVal >= -508 && CVal <= 508) && ((CVal & 3) == 0)) 11740 break; 11741 } 11742 return; 11743 } 11744 Result = DAG.getTargetConstant(CVal, SDLoc(Op), Op.getValueType()); 11745 break; 11746 } 11747 11748 if (Result.getNode()) { 11749 Ops.push_back(Result); 11750 return; 11751 } 11752 return TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG); 11753 } 11754 11755 static RTLIB::Libcall getDivRemLibcall( 11756 const SDNode *N, MVT::SimpleValueType SVT) { 11757 assert((N->getOpcode() == ISD::SDIVREM || N->getOpcode() == ISD::UDIVREM || 11758 N->getOpcode() == ISD::SREM || N->getOpcode() == ISD::UREM) && 11759 "Unhandled Opcode in getDivRemLibcall"); 11760 bool isSigned = N->getOpcode() == ISD::SDIVREM || 11761 N->getOpcode() == ISD::SREM; 11762 RTLIB::Libcall LC; 11763 switch (SVT) { 11764 default: llvm_unreachable("Unexpected request for libcall!"); 11765 case MVT::i8: LC = isSigned ? RTLIB::SDIVREM_I8 : RTLIB::UDIVREM_I8; break; 11766 case MVT::i16: LC = isSigned ? RTLIB::SDIVREM_I16 : RTLIB::UDIVREM_I16; break; 11767 case MVT::i32: LC = isSigned ? RTLIB::SDIVREM_I32 : RTLIB::UDIVREM_I32; break; 11768 case MVT::i64: LC = isSigned ? RTLIB::SDIVREM_I64 : RTLIB::UDIVREM_I64; break; 11769 } 11770 return LC; 11771 } 11772 11773 static TargetLowering::ArgListTy getDivRemArgList( 11774 const SDNode *N, LLVMContext *Context) { 11775 assert((N->getOpcode() == ISD::SDIVREM || N->getOpcode() == ISD::UDIVREM || 11776 N->getOpcode() == ISD::SREM || N->getOpcode() == ISD::UREM) && 11777 "Unhandled Opcode in getDivRemArgList"); 11778 bool isSigned = N->getOpcode() == ISD::SDIVREM || 11779 N->getOpcode() == ISD::SREM; 11780 TargetLowering::ArgListTy Args; 11781 TargetLowering::ArgListEntry Entry; 11782 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) { 11783 EVT ArgVT = N->getOperand(i).getValueType(); 11784 Type *ArgTy = ArgVT.getTypeForEVT(*Context); 11785 Entry.Node = N->getOperand(i); 11786 Entry.Ty = ArgTy; 11787 Entry.isSExt = isSigned; 11788 Entry.isZExt = !isSigned; 11789 Args.push_back(Entry); 11790 } 11791 return Args; 11792 } 11793 11794 SDValue ARMTargetLowering::LowerDivRem(SDValue Op, SelectionDAG &DAG) const { 11795 assert((Subtarget->isTargetAEABI() || Subtarget->isTargetAndroid() || 11796 Subtarget->isTargetGNUAEABI()) && 11797 "Register-based DivRem lowering only"); 11798 unsigned Opcode = Op->getOpcode(); 11799 assert((Opcode == ISD::SDIVREM || Opcode == ISD::UDIVREM) && 11800 "Invalid opcode for Div/Rem lowering"); 11801 bool isSigned = (Opcode == ISD::SDIVREM); 11802 EVT VT = Op->getValueType(0); 11803 Type *Ty = VT.getTypeForEVT(*DAG.getContext()); 11804 11805 RTLIB::Libcall LC = getDivRemLibcall(Op.getNode(), 11806 VT.getSimpleVT().SimpleTy); 11807 SDValue InChain = DAG.getEntryNode(); 11808 11809 TargetLowering::ArgListTy Args = getDivRemArgList(Op.getNode(), 11810 DAG.getContext()); 11811 11812 SDValue Callee = DAG.getExternalSymbol(getLibcallName(LC), 11813 getPointerTy(DAG.getDataLayout())); 11814 11815 Type *RetTy = (Type*)StructType::get(Ty, Ty, nullptr); 11816 11817 SDLoc dl(Op); 11818 TargetLowering::CallLoweringInfo CLI(DAG); 11819 CLI.setDebugLoc(dl).setChain(InChain) 11820 .setCallee(getLibcallCallingConv(LC), RetTy, Callee, std::move(Args), 0) 11821 .setInRegister().setSExtResult(isSigned).setZExtResult(!isSigned); 11822 11823 std::pair<SDValue, SDValue> CallInfo = LowerCallTo(CLI); 11824 return CallInfo.first; 11825 } 11826 11827 // Lowers REM using divmod helpers 11828 // see RTABI section 4.2/4.3 11829 SDValue ARMTargetLowering::LowerREM(SDNode *N, SelectionDAG &DAG) const { 11830 // Build return types (div and rem) 11831 std::vector<Type*> RetTyParams; 11832 Type *RetTyElement; 11833 11834 switch (N->getValueType(0).getSimpleVT().SimpleTy) { 11835 default: llvm_unreachable("Unexpected request for libcall!"); 11836 case MVT::i8: RetTyElement = Type::getInt8Ty(*DAG.getContext()); break; 11837 case MVT::i16: RetTyElement = Type::getInt16Ty(*DAG.getContext()); break; 11838 case MVT::i32: RetTyElement = Type::getInt32Ty(*DAG.getContext()); break; 11839 case MVT::i64: RetTyElement = Type::getInt64Ty(*DAG.getContext()); break; 11840 } 11841 11842 RetTyParams.push_back(RetTyElement); 11843 RetTyParams.push_back(RetTyElement); 11844 ArrayRef<Type*> ret = ArrayRef<Type*>(RetTyParams); 11845 Type *RetTy = StructType::get(*DAG.getContext(), ret); 11846 11847 RTLIB::Libcall LC = getDivRemLibcall(N, N->getValueType(0).getSimpleVT(). 11848 SimpleTy); 11849 SDValue InChain = DAG.getEntryNode(); 11850 TargetLowering::ArgListTy Args = getDivRemArgList(N, DAG.getContext()); 11851 bool isSigned = N->getOpcode() == ISD::SREM; 11852 SDValue Callee = DAG.getExternalSymbol(getLibcallName(LC), 11853 getPointerTy(DAG.getDataLayout())); 11854 11855 // Lower call 11856 CallLoweringInfo CLI(DAG); 11857 CLI.setChain(InChain) 11858 .setCallee(CallingConv::ARM_AAPCS, RetTy, Callee, std::move(Args), 0) 11859 .setSExtResult(isSigned).setZExtResult(!isSigned).setDebugLoc(SDLoc(N)); 11860 std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI); 11861 11862 // Return second (rem) result operand (first contains div) 11863 SDNode *ResNode = CallResult.first.getNode(); 11864 assert(ResNode->getNumOperands() == 2 && "divmod should return two operands"); 11865 return ResNode->getOperand(1); 11866 } 11867 11868 SDValue 11869 ARMTargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op, SelectionDAG &DAG) const { 11870 assert(Subtarget->isTargetWindows() && "unsupported target platform"); 11871 SDLoc DL(Op); 11872 11873 // Get the inputs. 11874 SDValue Chain = Op.getOperand(0); 11875 SDValue Size = Op.getOperand(1); 11876 11877 SDValue Words = DAG.getNode(ISD::SRL, DL, MVT::i32, Size, 11878 DAG.getConstant(2, DL, MVT::i32)); 11879 11880 SDValue Flag; 11881 Chain = DAG.getCopyToReg(Chain, DL, ARM::R4, Words, Flag); 11882 Flag = Chain.getValue(1); 11883 11884 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue); 11885 Chain = DAG.getNode(ARMISD::WIN__CHKSTK, DL, NodeTys, Chain, Flag); 11886 11887 SDValue NewSP = DAG.getCopyFromReg(Chain, DL, ARM::SP, MVT::i32); 11888 Chain = NewSP.getValue(1); 11889 11890 SDValue Ops[2] = { NewSP, Chain }; 11891 return DAG.getMergeValues(Ops, DL); 11892 } 11893 11894 SDValue ARMTargetLowering::LowerFP_EXTEND(SDValue Op, SelectionDAG &DAG) const { 11895 assert(Op.getValueType() == MVT::f64 && Subtarget->isFPOnlySP() && 11896 "Unexpected type for custom-lowering FP_EXTEND"); 11897 11898 RTLIB::Libcall LC; 11899 LC = RTLIB::getFPEXT(Op.getOperand(0).getValueType(), Op.getValueType()); 11900 11901 SDValue SrcVal = Op.getOperand(0); 11902 return makeLibCall(DAG, LC, Op.getValueType(), SrcVal, /*isSigned*/ false, 11903 SDLoc(Op)).first; 11904 } 11905 11906 SDValue ARMTargetLowering::LowerFP_ROUND(SDValue Op, SelectionDAG &DAG) const { 11907 assert(Op.getOperand(0).getValueType() == MVT::f64 && 11908 Subtarget->isFPOnlySP() && 11909 "Unexpected type for custom-lowering FP_ROUND"); 11910 11911 RTLIB::Libcall LC; 11912 LC = RTLIB::getFPROUND(Op.getOperand(0).getValueType(), Op.getValueType()); 11913 11914 SDValue SrcVal = Op.getOperand(0); 11915 return makeLibCall(DAG, LC, Op.getValueType(), SrcVal, /*isSigned*/ false, 11916 SDLoc(Op)).first; 11917 } 11918 11919 bool 11920 ARMTargetLowering::isOffsetFoldingLegal(const GlobalAddressSDNode *GA) const { 11921 // The ARM target isn't yet aware of offsets. 11922 return false; 11923 } 11924 11925 bool ARM::isBitFieldInvertedMask(unsigned v) { 11926 if (v == 0xffffffff) 11927 return false; 11928 11929 // there can be 1's on either or both "outsides", all the "inside" 11930 // bits must be 0's 11931 return isShiftedMask_32(~v); 11932 } 11933 11934 /// isFPImmLegal - Returns true if the target can instruction select the 11935 /// specified FP immediate natively. If false, the legalizer will 11936 /// materialize the FP immediate as a load from a constant pool. 11937 bool ARMTargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT) const { 11938 if (!Subtarget->hasVFP3()) 11939 return false; 11940 if (VT == MVT::f32) 11941 return ARM_AM::getFP32Imm(Imm) != -1; 11942 if (VT == MVT::f64 && !Subtarget->isFPOnlySP()) 11943 return ARM_AM::getFP64Imm(Imm) != -1; 11944 return false; 11945 } 11946 11947 /// getTgtMemIntrinsic - Represent NEON load and store intrinsics as 11948 /// MemIntrinsicNodes. The associated MachineMemOperands record the alignment 11949 /// specified in the intrinsic calls. 11950 bool ARMTargetLowering::getTgtMemIntrinsic(IntrinsicInfo &Info, 11951 const CallInst &I, 11952 unsigned Intrinsic) const { 11953 switch (Intrinsic) { 11954 case Intrinsic::arm_neon_vld1: 11955 case Intrinsic::arm_neon_vld2: 11956 case Intrinsic::arm_neon_vld3: 11957 case Intrinsic::arm_neon_vld4: 11958 case Intrinsic::arm_neon_vld2lane: 11959 case Intrinsic::arm_neon_vld3lane: 11960 case Intrinsic::arm_neon_vld4lane: { 11961 Info.opc = ISD::INTRINSIC_W_CHAIN; 11962 // Conservatively set memVT to the entire set of vectors loaded. 11963 auto &DL = I.getCalledFunction()->getParent()->getDataLayout(); 11964 uint64_t NumElts = DL.getTypeSizeInBits(I.getType()) / 64; 11965 Info.memVT = EVT::getVectorVT(I.getType()->getContext(), MVT::i64, NumElts); 11966 Info.ptrVal = I.getArgOperand(0); 11967 Info.offset = 0; 11968 Value *AlignArg = I.getArgOperand(I.getNumArgOperands() - 1); 11969 Info.align = cast<ConstantInt>(AlignArg)->getZExtValue(); 11970 Info.vol = false; // volatile loads with NEON intrinsics not supported 11971 Info.readMem = true; 11972 Info.writeMem = false; 11973 return true; 11974 } 11975 case Intrinsic::arm_neon_vst1: 11976 case Intrinsic::arm_neon_vst2: 11977 case Intrinsic::arm_neon_vst3: 11978 case Intrinsic::arm_neon_vst4: 11979 case Intrinsic::arm_neon_vst2lane: 11980 case Intrinsic::arm_neon_vst3lane: 11981 case Intrinsic::arm_neon_vst4lane: { 11982 Info.opc = ISD::INTRINSIC_VOID; 11983 // Conservatively set memVT to the entire set of vectors stored. 11984 auto &DL = I.getCalledFunction()->getParent()->getDataLayout(); 11985 unsigned NumElts = 0; 11986 for (unsigned ArgI = 1, ArgE = I.getNumArgOperands(); ArgI < ArgE; ++ArgI) { 11987 Type *ArgTy = I.getArgOperand(ArgI)->getType(); 11988 if (!ArgTy->isVectorTy()) 11989 break; 11990 NumElts += DL.getTypeSizeInBits(ArgTy) / 64; 11991 } 11992 Info.memVT = EVT::getVectorVT(I.getType()->getContext(), MVT::i64, NumElts); 11993 Info.ptrVal = I.getArgOperand(0); 11994 Info.offset = 0; 11995 Value *AlignArg = I.getArgOperand(I.getNumArgOperands() - 1); 11996 Info.align = cast<ConstantInt>(AlignArg)->getZExtValue(); 11997 Info.vol = false; // volatile stores with NEON intrinsics not supported 11998 Info.readMem = false; 11999 Info.writeMem = true; 12000 return true; 12001 } 12002 case Intrinsic::arm_ldaex: 12003 case Intrinsic::arm_ldrex: { 12004 auto &DL = I.getCalledFunction()->getParent()->getDataLayout(); 12005 PointerType *PtrTy = cast<PointerType>(I.getArgOperand(0)->getType()); 12006 Info.opc = ISD::INTRINSIC_W_CHAIN; 12007 Info.memVT = MVT::getVT(PtrTy->getElementType()); 12008 Info.ptrVal = I.getArgOperand(0); 12009 Info.offset = 0; 12010 Info.align = DL.getABITypeAlignment(PtrTy->getElementType()); 12011 Info.vol = true; 12012 Info.readMem = true; 12013 Info.writeMem = false; 12014 return true; 12015 } 12016 case Intrinsic::arm_stlex: 12017 case Intrinsic::arm_strex: { 12018 auto &DL = I.getCalledFunction()->getParent()->getDataLayout(); 12019 PointerType *PtrTy = cast<PointerType>(I.getArgOperand(1)->getType()); 12020 Info.opc = ISD::INTRINSIC_W_CHAIN; 12021 Info.memVT = MVT::getVT(PtrTy->getElementType()); 12022 Info.ptrVal = I.getArgOperand(1); 12023 Info.offset = 0; 12024 Info.align = DL.getABITypeAlignment(PtrTy->getElementType()); 12025 Info.vol = true; 12026 Info.readMem = false; 12027 Info.writeMem = true; 12028 return true; 12029 } 12030 case Intrinsic::arm_stlexd: 12031 case Intrinsic::arm_strexd: { 12032 Info.opc = ISD::INTRINSIC_W_CHAIN; 12033 Info.memVT = MVT::i64; 12034 Info.ptrVal = I.getArgOperand(2); 12035 Info.offset = 0; 12036 Info.align = 8; 12037 Info.vol = true; 12038 Info.readMem = false; 12039 Info.writeMem = true; 12040 return true; 12041 } 12042 case Intrinsic::arm_ldaexd: 12043 case Intrinsic::arm_ldrexd: { 12044 Info.opc = ISD::INTRINSIC_W_CHAIN; 12045 Info.memVT = MVT::i64; 12046 Info.ptrVal = I.getArgOperand(0); 12047 Info.offset = 0; 12048 Info.align = 8; 12049 Info.vol = true; 12050 Info.readMem = true; 12051 Info.writeMem = false; 12052 return true; 12053 } 12054 default: 12055 break; 12056 } 12057 12058 return false; 12059 } 12060 12061 /// \brief Returns true if it is beneficial to convert a load of a constant 12062 /// to just the constant itself. 12063 bool ARMTargetLowering::shouldConvertConstantLoadToIntImm(const APInt &Imm, 12064 Type *Ty) const { 12065 assert(Ty->isIntegerTy()); 12066 12067 unsigned Bits = Ty->getPrimitiveSizeInBits(); 12068 if (Bits == 0 || Bits > 32) 12069 return false; 12070 return true; 12071 } 12072 12073 Instruction* ARMTargetLowering::makeDMB(IRBuilder<> &Builder, 12074 ARM_MB::MemBOpt Domain) const { 12075 Module *M = Builder.GetInsertBlock()->getParent()->getParent(); 12076 12077 // First, if the target has no DMB, see what fallback we can use. 12078 if (!Subtarget->hasDataBarrier()) { 12079 // Some ARMv6 cpus can support data barriers with an mcr instruction. 12080 // Thumb1 and pre-v6 ARM mode use a libcall instead and should never get 12081 // here. 12082 if (Subtarget->hasV6Ops() && !Subtarget->isThumb()) { 12083 Function *MCR = llvm::Intrinsic::getDeclaration(M, Intrinsic::arm_mcr); 12084 Value* args[6] = {Builder.getInt32(15), Builder.getInt32(0), 12085 Builder.getInt32(0), Builder.getInt32(7), 12086 Builder.getInt32(10), Builder.getInt32(5)}; 12087 return Builder.CreateCall(MCR, args); 12088 } else { 12089 // Instead of using barriers, atomic accesses on these subtargets use 12090 // libcalls. 12091 llvm_unreachable("makeDMB on a target so old that it has no barriers"); 12092 } 12093 } else { 12094 Function *DMB = llvm::Intrinsic::getDeclaration(M, Intrinsic::arm_dmb); 12095 // Only a full system barrier exists in the M-class architectures. 12096 Domain = Subtarget->isMClass() ? ARM_MB::SY : Domain; 12097 Constant *CDomain = Builder.getInt32(Domain); 12098 return Builder.CreateCall(DMB, CDomain); 12099 } 12100 } 12101 12102 // Based on http://www.cl.cam.ac.uk/~pes20/cpp/cpp0xmappings.html 12103 Instruction* ARMTargetLowering::emitLeadingFence(IRBuilder<> &Builder, 12104 AtomicOrdering Ord, bool IsStore, 12105 bool IsLoad) const { 12106 switch (Ord) { 12107 case NotAtomic: 12108 case Unordered: 12109 llvm_unreachable("Invalid fence: unordered/non-atomic"); 12110 case Monotonic: 12111 case Acquire: 12112 return nullptr; // Nothing to do 12113 case SequentiallyConsistent: 12114 if (!IsStore) 12115 return nullptr; // Nothing to do 12116 /*FALLTHROUGH*/ 12117 case Release: 12118 case AcquireRelease: 12119 if (Subtarget->isSwift()) 12120 return makeDMB(Builder, ARM_MB::ISHST); 12121 // FIXME: add a comment with a link to documentation justifying this. 12122 else 12123 return makeDMB(Builder, ARM_MB::ISH); 12124 } 12125 llvm_unreachable("Unknown fence ordering in emitLeadingFence"); 12126 } 12127 12128 Instruction* ARMTargetLowering::emitTrailingFence(IRBuilder<> &Builder, 12129 AtomicOrdering Ord, bool IsStore, 12130 bool IsLoad) const { 12131 switch (Ord) { 12132 case NotAtomic: 12133 case Unordered: 12134 llvm_unreachable("Invalid fence: unordered/not-atomic"); 12135 case Monotonic: 12136 case Release: 12137 return nullptr; // Nothing to do 12138 case Acquire: 12139 case AcquireRelease: 12140 case SequentiallyConsistent: 12141 return makeDMB(Builder, ARM_MB::ISH); 12142 } 12143 llvm_unreachable("Unknown fence ordering in emitTrailingFence"); 12144 } 12145 12146 // Loads and stores less than 64-bits are already atomic; ones above that 12147 // are doomed anyway, so defer to the default libcall and blame the OS when 12148 // things go wrong. Cortex M doesn't have ldrexd/strexd though, so don't emit 12149 // anything for those. 12150 bool ARMTargetLowering::shouldExpandAtomicStoreInIR(StoreInst *SI) const { 12151 unsigned Size = SI->getValueOperand()->getType()->getPrimitiveSizeInBits(); 12152 return (Size == 64) && !Subtarget->isMClass(); 12153 } 12154 12155 // Loads and stores less than 64-bits are already atomic; ones above that 12156 // are doomed anyway, so defer to the default libcall and blame the OS when 12157 // things go wrong. Cortex M doesn't have ldrexd/strexd though, so don't emit 12158 // anything for those. 12159 // FIXME: ldrd and strd are atomic if the CPU has LPAE (e.g. A15 has that 12160 // guarantee, see DDI0406C ARM architecture reference manual, 12161 // sections A8.8.72-74 LDRD) 12162 TargetLowering::AtomicExpansionKind 12163 ARMTargetLowering::shouldExpandAtomicLoadInIR(LoadInst *LI) const { 12164 unsigned Size = LI->getType()->getPrimitiveSizeInBits(); 12165 return ((Size == 64) && !Subtarget->isMClass()) ? AtomicExpansionKind::LLOnly 12166 : AtomicExpansionKind::None; 12167 } 12168 12169 // For the real atomic operations, we have ldrex/strex up to 32 bits, 12170 // and up to 64 bits on the non-M profiles 12171 TargetLowering::AtomicExpansionKind 12172 ARMTargetLowering::shouldExpandAtomicRMWInIR(AtomicRMWInst *AI) const { 12173 unsigned Size = AI->getType()->getPrimitiveSizeInBits(); 12174 return (Size <= (Subtarget->isMClass() ? 32U : 64U)) 12175 ? AtomicExpansionKind::LLSC 12176 : AtomicExpansionKind::None; 12177 } 12178 12179 bool ARMTargetLowering::shouldExpandAtomicCmpXchgInIR( 12180 AtomicCmpXchgInst *AI) const { 12181 return true; 12182 } 12183 12184 bool ARMTargetLowering::shouldInsertFencesForAtomic( 12185 const Instruction *I) const { 12186 return InsertFencesForAtomic; 12187 } 12188 12189 // This has so far only been implemented for MachO. 12190 bool ARMTargetLowering::useLoadStackGuardNode() const { 12191 return Subtarget->isTargetMachO(); 12192 } 12193 12194 bool ARMTargetLowering::canCombineStoreAndExtract(Type *VectorTy, Value *Idx, 12195 unsigned &Cost) const { 12196 // If we do not have NEON, vector types are not natively supported. 12197 if (!Subtarget->hasNEON()) 12198 return false; 12199 12200 // Floating point values and vector values map to the same register file. 12201 // Therefore, although we could do a store extract of a vector type, this is 12202 // better to leave at float as we have more freedom in the addressing mode for 12203 // those. 12204 if (VectorTy->isFPOrFPVectorTy()) 12205 return false; 12206 12207 // If the index is unknown at compile time, this is very expensive to lower 12208 // and it is not possible to combine the store with the extract. 12209 if (!isa<ConstantInt>(Idx)) 12210 return false; 12211 12212 assert(VectorTy->isVectorTy() && "VectorTy is not a vector type"); 12213 unsigned BitWidth = cast<VectorType>(VectorTy)->getBitWidth(); 12214 // We can do a store + vector extract on any vector that fits perfectly in a D 12215 // or Q register. 12216 if (BitWidth == 64 || BitWidth == 128) { 12217 Cost = 0; 12218 return true; 12219 } 12220 return false; 12221 } 12222 12223 bool ARMTargetLowering::isCheapToSpeculateCttz() const { 12224 return Subtarget->hasV6T2Ops(); 12225 } 12226 12227 bool ARMTargetLowering::isCheapToSpeculateCtlz() const { 12228 return Subtarget->hasV6T2Ops(); 12229 } 12230 12231 Value *ARMTargetLowering::emitLoadLinked(IRBuilder<> &Builder, Value *Addr, 12232 AtomicOrdering Ord) const { 12233 Module *M = Builder.GetInsertBlock()->getParent()->getParent(); 12234 Type *ValTy = cast<PointerType>(Addr->getType())->getElementType(); 12235 bool IsAcquire = isAtLeastAcquire(Ord); 12236 12237 // Since i64 isn't legal and intrinsics don't get type-lowered, the ldrexd 12238 // intrinsic must return {i32, i32} and we have to recombine them into a 12239 // single i64 here. 12240 if (ValTy->getPrimitiveSizeInBits() == 64) { 12241 Intrinsic::ID Int = 12242 IsAcquire ? Intrinsic::arm_ldaexd : Intrinsic::arm_ldrexd; 12243 Function *Ldrex = llvm::Intrinsic::getDeclaration(M, Int); 12244 12245 Addr = Builder.CreateBitCast(Addr, Type::getInt8PtrTy(M->getContext())); 12246 Value *LoHi = Builder.CreateCall(Ldrex, Addr, "lohi"); 12247 12248 Value *Lo = Builder.CreateExtractValue(LoHi, 0, "lo"); 12249 Value *Hi = Builder.CreateExtractValue(LoHi, 1, "hi"); 12250 if (!Subtarget->isLittle()) 12251 std::swap (Lo, Hi); 12252 Lo = Builder.CreateZExt(Lo, ValTy, "lo64"); 12253 Hi = Builder.CreateZExt(Hi, ValTy, "hi64"); 12254 return Builder.CreateOr( 12255 Lo, Builder.CreateShl(Hi, ConstantInt::get(ValTy, 32)), "val64"); 12256 } 12257 12258 Type *Tys[] = { Addr->getType() }; 12259 Intrinsic::ID Int = IsAcquire ? Intrinsic::arm_ldaex : Intrinsic::arm_ldrex; 12260 Function *Ldrex = llvm::Intrinsic::getDeclaration(M, Int, Tys); 12261 12262 return Builder.CreateTruncOrBitCast( 12263 Builder.CreateCall(Ldrex, Addr), 12264 cast<PointerType>(Addr->getType())->getElementType()); 12265 } 12266 12267 void ARMTargetLowering::emitAtomicCmpXchgNoStoreLLBalance( 12268 IRBuilder<> &Builder) const { 12269 if (!Subtarget->hasV7Ops()) 12270 return; 12271 Module *M = Builder.GetInsertBlock()->getParent()->getParent(); 12272 Builder.CreateCall(llvm::Intrinsic::getDeclaration(M, Intrinsic::arm_clrex)); 12273 } 12274 12275 Value *ARMTargetLowering::emitStoreConditional(IRBuilder<> &Builder, Value *Val, 12276 Value *Addr, 12277 AtomicOrdering Ord) const { 12278 Module *M = Builder.GetInsertBlock()->getParent()->getParent(); 12279 bool IsRelease = isAtLeastRelease(Ord); 12280 12281 // Since the intrinsics must have legal type, the i64 intrinsics take two 12282 // parameters: "i32, i32". We must marshal Val into the appropriate form 12283 // before the call. 12284 if (Val->getType()->getPrimitiveSizeInBits() == 64) { 12285 Intrinsic::ID Int = 12286 IsRelease ? Intrinsic::arm_stlexd : Intrinsic::arm_strexd; 12287 Function *Strex = Intrinsic::getDeclaration(M, Int); 12288 Type *Int32Ty = Type::getInt32Ty(M->getContext()); 12289 12290 Value *Lo = Builder.CreateTrunc(Val, Int32Ty, "lo"); 12291 Value *Hi = Builder.CreateTrunc(Builder.CreateLShr(Val, 32), Int32Ty, "hi"); 12292 if (!Subtarget->isLittle()) 12293 std::swap (Lo, Hi); 12294 Addr = Builder.CreateBitCast(Addr, Type::getInt8PtrTy(M->getContext())); 12295 return Builder.CreateCall(Strex, {Lo, Hi, Addr}); 12296 } 12297 12298 Intrinsic::ID Int = IsRelease ? Intrinsic::arm_stlex : Intrinsic::arm_strex; 12299 Type *Tys[] = { Addr->getType() }; 12300 Function *Strex = Intrinsic::getDeclaration(M, Int, Tys); 12301 12302 return Builder.CreateCall( 12303 Strex, {Builder.CreateZExtOrBitCast( 12304 Val, Strex->getFunctionType()->getParamType(0)), 12305 Addr}); 12306 } 12307 12308 /// \brief Lower an interleaved load into a vldN intrinsic. 12309 /// 12310 /// E.g. Lower an interleaved load (Factor = 2): 12311 /// %wide.vec = load <8 x i32>, <8 x i32>* %ptr, align 4 12312 /// %v0 = shuffle %wide.vec, undef, <0, 2, 4, 6> ; Extract even elements 12313 /// %v1 = shuffle %wide.vec, undef, <1, 3, 5, 7> ; Extract odd elements 12314 /// 12315 /// Into: 12316 /// %vld2 = { <4 x i32>, <4 x i32> } call llvm.arm.neon.vld2(%ptr, 4) 12317 /// %vec0 = extractelement { <4 x i32>, <4 x i32> } %vld2, i32 0 12318 /// %vec1 = extractelement { <4 x i32>, <4 x i32> } %vld2, i32 1 12319 bool ARMTargetLowering::lowerInterleavedLoad( 12320 LoadInst *LI, ArrayRef<ShuffleVectorInst *> Shuffles, 12321 ArrayRef<unsigned> Indices, unsigned Factor) const { 12322 assert(Factor >= 2 && Factor <= getMaxSupportedInterleaveFactor() && 12323 "Invalid interleave factor"); 12324 assert(!Shuffles.empty() && "Empty shufflevector input"); 12325 assert(Shuffles.size() == Indices.size() && 12326 "Unmatched number of shufflevectors and indices"); 12327 12328 VectorType *VecTy = Shuffles[0]->getType(); 12329 Type *EltTy = VecTy->getVectorElementType(); 12330 12331 const DataLayout &DL = LI->getModule()->getDataLayout(); 12332 unsigned VecSize = DL.getTypeSizeInBits(VecTy); 12333 bool EltIs64Bits = DL.getTypeSizeInBits(EltTy) == 64; 12334 12335 // Skip if we do not have NEON and skip illegal vector types and vector types 12336 // with i64/f64 elements (vldN doesn't support i64/f64 elements). 12337 if (!Subtarget->hasNEON() || (VecSize != 64 && VecSize != 128) || EltIs64Bits) 12338 return false; 12339 12340 // A pointer vector can not be the return type of the ldN intrinsics. Need to 12341 // load integer vectors first and then convert to pointer vectors. 12342 if (EltTy->isPointerTy()) 12343 VecTy = 12344 VectorType::get(DL.getIntPtrType(EltTy), VecTy->getVectorNumElements()); 12345 12346 static const Intrinsic::ID LoadInts[3] = {Intrinsic::arm_neon_vld2, 12347 Intrinsic::arm_neon_vld3, 12348 Intrinsic::arm_neon_vld4}; 12349 12350 IRBuilder<> Builder(LI); 12351 SmallVector<Value *, 2> Ops; 12352 12353 Type *Int8Ptr = Builder.getInt8PtrTy(LI->getPointerAddressSpace()); 12354 Ops.push_back(Builder.CreateBitCast(LI->getPointerOperand(), Int8Ptr)); 12355 Ops.push_back(Builder.getInt32(LI->getAlignment())); 12356 12357 Type *Tys[] = { VecTy, Int8Ptr }; 12358 Function *VldnFunc = 12359 Intrinsic::getDeclaration(LI->getModule(), LoadInts[Factor - 2], Tys); 12360 CallInst *VldN = Builder.CreateCall(VldnFunc, Ops, "vldN"); 12361 12362 // Replace uses of each shufflevector with the corresponding vector loaded 12363 // by ldN. 12364 for (unsigned i = 0; i < Shuffles.size(); i++) { 12365 ShuffleVectorInst *SV = Shuffles[i]; 12366 unsigned Index = Indices[i]; 12367 12368 Value *SubVec = Builder.CreateExtractValue(VldN, Index); 12369 12370 // Convert the integer vector to pointer vector if the element is pointer. 12371 if (EltTy->isPointerTy()) 12372 SubVec = Builder.CreateIntToPtr(SubVec, SV->getType()); 12373 12374 SV->replaceAllUsesWith(SubVec); 12375 } 12376 12377 return true; 12378 } 12379 12380 /// \brief Get a mask consisting of sequential integers starting from \p Start. 12381 /// 12382 /// I.e. <Start, Start + 1, ..., Start + NumElts - 1> 12383 static Constant *getSequentialMask(IRBuilder<> &Builder, unsigned Start, 12384 unsigned NumElts) { 12385 SmallVector<Constant *, 16> Mask; 12386 for (unsigned i = 0; i < NumElts; i++) 12387 Mask.push_back(Builder.getInt32(Start + i)); 12388 12389 return ConstantVector::get(Mask); 12390 } 12391 12392 /// \brief Lower an interleaved store into a vstN intrinsic. 12393 /// 12394 /// E.g. Lower an interleaved store (Factor = 3): 12395 /// %i.vec = shuffle <8 x i32> %v0, <8 x i32> %v1, 12396 /// <0, 4, 8, 1, 5, 9, 2, 6, 10, 3, 7, 11> 12397 /// store <12 x i32> %i.vec, <12 x i32>* %ptr, align 4 12398 /// 12399 /// Into: 12400 /// %sub.v0 = shuffle <8 x i32> %v0, <8 x i32> v1, <0, 1, 2, 3> 12401 /// %sub.v1 = shuffle <8 x i32> %v0, <8 x i32> v1, <4, 5, 6, 7> 12402 /// %sub.v2 = shuffle <8 x i32> %v0, <8 x i32> v1, <8, 9, 10, 11> 12403 /// call void llvm.arm.neon.vst3(%ptr, %sub.v0, %sub.v1, %sub.v2, 4) 12404 /// 12405 /// Note that the new shufflevectors will be removed and we'll only generate one 12406 /// vst3 instruction in CodeGen. 12407 bool ARMTargetLowering::lowerInterleavedStore(StoreInst *SI, 12408 ShuffleVectorInst *SVI, 12409 unsigned Factor) const { 12410 assert(Factor >= 2 && Factor <= getMaxSupportedInterleaveFactor() && 12411 "Invalid interleave factor"); 12412 12413 VectorType *VecTy = SVI->getType(); 12414 assert(VecTy->getVectorNumElements() % Factor == 0 && 12415 "Invalid interleaved store"); 12416 12417 unsigned NumSubElts = VecTy->getVectorNumElements() / Factor; 12418 Type *EltTy = VecTy->getVectorElementType(); 12419 VectorType *SubVecTy = VectorType::get(EltTy, NumSubElts); 12420 12421 const DataLayout &DL = SI->getModule()->getDataLayout(); 12422 unsigned SubVecSize = DL.getTypeSizeInBits(SubVecTy); 12423 bool EltIs64Bits = DL.getTypeSizeInBits(EltTy) == 64; 12424 12425 // Skip if we do not have NEON and skip illegal vector types and vector types 12426 // with i64/f64 elements (vstN doesn't support i64/f64 elements). 12427 if (!Subtarget->hasNEON() || (SubVecSize != 64 && SubVecSize != 128) || 12428 EltIs64Bits) 12429 return false; 12430 12431 Value *Op0 = SVI->getOperand(0); 12432 Value *Op1 = SVI->getOperand(1); 12433 IRBuilder<> Builder(SI); 12434 12435 // StN intrinsics don't support pointer vectors as arguments. Convert pointer 12436 // vectors to integer vectors. 12437 if (EltTy->isPointerTy()) { 12438 Type *IntTy = DL.getIntPtrType(EltTy); 12439 12440 // Convert to the corresponding integer vector. 12441 Type *IntVecTy = 12442 VectorType::get(IntTy, Op0->getType()->getVectorNumElements()); 12443 Op0 = Builder.CreatePtrToInt(Op0, IntVecTy); 12444 Op1 = Builder.CreatePtrToInt(Op1, IntVecTy); 12445 12446 SubVecTy = VectorType::get(IntTy, NumSubElts); 12447 } 12448 12449 static const Intrinsic::ID StoreInts[3] = {Intrinsic::arm_neon_vst2, 12450 Intrinsic::arm_neon_vst3, 12451 Intrinsic::arm_neon_vst4}; 12452 SmallVector<Value *, 6> Ops; 12453 12454 Type *Int8Ptr = Builder.getInt8PtrTy(SI->getPointerAddressSpace()); 12455 Ops.push_back(Builder.CreateBitCast(SI->getPointerOperand(), Int8Ptr)); 12456 12457 Type *Tys[] = { Int8Ptr, SubVecTy }; 12458 Function *VstNFunc = Intrinsic::getDeclaration( 12459 SI->getModule(), StoreInts[Factor - 2], Tys); 12460 12461 // Split the shufflevector operands into sub vectors for the new vstN call. 12462 for (unsigned i = 0; i < Factor; i++) 12463 Ops.push_back(Builder.CreateShuffleVector( 12464 Op0, Op1, getSequentialMask(Builder, NumSubElts * i, NumSubElts))); 12465 12466 Ops.push_back(Builder.getInt32(SI->getAlignment())); 12467 Builder.CreateCall(VstNFunc, Ops); 12468 return true; 12469 } 12470 12471 enum HABaseType { 12472 HA_UNKNOWN = 0, 12473 HA_FLOAT, 12474 HA_DOUBLE, 12475 HA_VECT64, 12476 HA_VECT128 12477 }; 12478 12479 static bool isHomogeneousAggregate(Type *Ty, HABaseType &Base, 12480 uint64_t &Members) { 12481 if (auto *ST = dyn_cast<StructType>(Ty)) { 12482 for (unsigned i = 0; i < ST->getNumElements(); ++i) { 12483 uint64_t SubMembers = 0; 12484 if (!isHomogeneousAggregate(ST->getElementType(i), Base, SubMembers)) 12485 return false; 12486 Members += SubMembers; 12487 } 12488 } else if (auto *AT = dyn_cast<ArrayType>(Ty)) { 12489 uint64_t SubMembers = 0; 12490 if (!isHomogeneousAggregate(AT->getElementType(), Base, SubMembers)) 12491 return false; 12492 Members += SubMembers * AT->getNumElements(); 12493 } else if (Ty->isFloatTy()) { 12494 if (Base != HA_UNKNOWN && Base != HA_FLOAT) 12495 return false; 12496 Members = 1; 12497 Base = HA_FLOAT; 12498 } else if (Ty->isDoubleTy()) { 12499 if (Base != HA_UNKNOWN && Base != HA_DOUBLE) 12500 return false; 12501 Members = 1; 12502 Base = HA_DOUBLE; 12503 } else if (auto *VT = dyn_cast<VectorType>(Ty)) { 12504 Members = 1; 12505 switch (Base) { 12506 case HA_FLOAT: 12507 case HA_DOUBLE: 12508 return false; 12509 case HA_VECT64: 12510 return VT->getBitWidth() == 64; 12511 case HA_VECT128: 12512 return VT->getBitWidth() == 128; 12513 case HA_UNKNOWN: 12514 switch (VT->getBitWidth()) { 12515 case 64: 12516 Base = HA_VECT64; 12517 return true; 12518 case 128: 12519 Base = HA_VECT128; 12520 return true; 12521 default: 12522 return false; 12523 } 12524 } 12525 } 12526 12527 return (Members > 0 && Members <= 4); 12528 } 12529 12530 /// \brief Return true if a type is an AAPCS-VFP homogeneous aggregate or one of 12531 /// [N x i32] or [N x i64]. This allows front-ends to skip emitting padding when 12532 /// passing according to AAPCS rules. 12533 bool ARMTargetLowering::functionArgumentNeedsConsecutiveRegisters( 12534 Type *Ty, CallingConv::ID CallConv, bool isVarArg) const { 12535 if (getEffectiveCallingConv(CallConv, isVarArg) != 12536 CallingConv::ARM_AAPCS_VFP) 12537 return false; 12538 12539 HABaseType Base = HA_UNKNOWN; 12540 uint64_t Members = 0; 12541 bool IsHA = isHomogeneousAggregate(Ty, Base, Members); 12542 DEBUG(dbgs() << "isHA: " << IsHA << " "; Ty->dump()); 12543 12544 bool IsIntArray = Ty->isArrayTy() && Ty->getArrayElementType()->isIntegerTy(); 12545 return IsHA || IsIntArray; 12546 } 12547 12548 unsigned ARMTargetLowering::getExceptionPointerRegister( 12549 const Constant *PersonalityFn) const { 12550 // Platforms which do not use SjLj EH may return values in these registers 12551 // via the personality function. 12552 return Subtarget->useSjLjEH() ? ARM::NoRegister : ARM::R0; 12553 } 12554 12555 unsigned ARMTargetLowering::getExceptionSelectorRegister( 12556 const Constant *PersonalityFn) const { 12557 // Platforms which do not use SjLj EH may return values in these registers 12558 // via the personality function. 12559 return Subtarget->useSjLjEH() ? ARM::NoRegister : ARM::R1; 12560 } 12561 12562 void ARMTargetLowering::initializeSplitCSR(MachineBasicBlock *Entry) const { 12563 // Update IsSplitCSR in ARMFunctionInfo. 12564 ARMFunctionInfo *AFI = Entry->getParent()->getInfo<ARMFunctionInfo>(); 12565 AFI->setIsSplitCSR(true); 12566 } 12567 12568 void ARMTargetLowering::insertCopiesSplitCSR( 12569 MachineBasicBlock *Entry, 12570 const SmallVectorImpl<MachineBasicBlock *> &Exits) const { 12571 const ARMBaseRegisterInfo *TRI = Subtarget->getRegisterInfo(); 12572 const MCPhysReg *IStart = TRI->getCalleeSavedRegsViaCopy(Entry->getParent()); 12573 if (!IStart) 12574 return; 12575 12576 const TargetInstrInfo *TII = Subtarget->getInstrInfo(); 12577 MachineRegisterInfo *MRI = &Entry->getParent()->getRegInfo(); 12578 MachineBasicBlock::iterator MBBI = Entry->begin(); 12579 for (const MCPhysReg *I = IStart; *I; ++I) { 12580 const TargetRegisterClass *RC = nullptr; 12581 if (ARM::GPRRegClass.contains(*I)) 12582 RC = &ARM::GPRRegClass; 12583 else if (ARM::DPRRegClass.contains(*I)) 12584 RC = &ARM::DPRRegClass; 12585 else 12586 llvm_unreachable("Unexpected register class in CSRsViaCopy!"); 12587 12588 unsigned NewVR = MRI->createVirtualRegister(RC); 12589 // Create copy from CSR to a virtual register. 12590 // FIXME: this currently does not emit CFI pseudo-instructions, it works 12591 // fine for CXX_FAST_TLS since the C++-style TLS access functions should be 12592 // nounwind. If we want to generalize this later, we may need to emit 12593 // CFI pseudo-instructions. 12594 assert(Entry->getParent()->getFunction()->hasFnAttribute( 12595 Attribute::NoUnwind) && 12596 "Function should be nounwind in insertCopiesSplitCSR!"); 12597 Entry->addLiveIn(*I); 12598 BuildMI(*Entry, MBBI, DebugLoc(), TII->get(TargetOpcode::COPY), NewVR) 12599 .addReg(*I); 12600 12601 // Insert the copy-back instructions right before the terminator. 12602 for (auto *Exit : Exits) 12603 BuildMI(*Exit, Exit->getFirstTerminator(), DebugLoc(), 12604 TII->get(TargetOpcode::COPY), *I) 12605 .addReg(NewVR); 12606 } 12607 } 12608