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 { RTLIB::SDIV_I32, "__rt_sdiv", CallingConv::ARM_AAPCS_VFP }, 394 { RTLIB::UDIV_I32, "__rt_udiv", CallingConv::ARM_AAPCS_VFP }, 395 { RTLIB::SDIV_I64, "__rt_sdiv64", CallingConv::ARM_AAPCS_VFP }, 396 { RTLIB::UDIV_I64, "__rt_udiv64", CallingConv::ARM_AAPCS_VFP }, 397 }; 398 399 for (const auto &LC : LibraryCalls) { 400 setLibcallName(LC.Op, LC.Name); 401 setLibcallCallingConv(LC.Op, LC.CC); 402 } 403 } 404 405 // Use divmod compiler-rt calls for iOS 5.0 and later. 406 if (Subtarget->isTargetWatchOS() || 407 (Subtarget->isTargetIOS() && 408 !Subtarget->getTargetTriple().isOSVersionLT(5, 0))) { 409 setLibcallName(RTLIB::SDIVREM_I32, "__divmodsi4"); 410 setLibcallName(RTLIB::UDIVREM_I32, "__udivmodsi4"); 411 } 412 413 // The half <-> float conversion functions are always soft-float, but are 414 // needed for some targets which use a hard-float calling convention by 415 // default. 416 if (Subtarget->isAAPCS_ABI()) { 417 setLibcallCallingConv(RTLIB::FPROUND_F32_F16, CallingConv::ARM_AAPCS); 418 setLibcallCallingConv(RTLIB::FPROUND_F64_F16, CallingConv::ARM_AAPCS); 419 setLibcallCallingConv(RTLIB::FPEXT_F16_F32, CallingConv::ARM_AAPCS); 420 } else { 421 setLibcallCallingConv(RTLIB::FPROUND_F32_F16, CallingConv::ARM_APCS); 422 setLibcallCallingConv(RTLIB::FPROUND_F64_F16, CallingConv::ARM_APCS); 423 setLibcallCallingConv(RTLIB::FPEXT_F16_F32, CallingConv::ARM_APCS); 424 } 425 426 // In EABI, these functions have an __aeabi_ prefix, but in GNUEABI they have 427 // a __gnu_ prefix (which is the default). 428 if (Subtarget->isTargetAEABI()) { 429 setLibcallName(RTLIB::FPROUND_F32_F16, "__aeabi_f2h"); 430 setLibcallName(RTLIB::FPROUND_F64_F16, "__aeabi_d2h"); 431 setLibcallName(RTLIB::FPEXT_F16_F32, "__aeabi_h2f"); 432 } 433 434 if (Subtarget->isThumb1Only()) 435 addRegisterClass(MVT::i32, &ARM::tGPRRegClass); 436 else 437 addRegisterClass(MVT::i32, &ARM::GPRRegClass); 438 if (!Subtarget->useSoftFloat() && Subtarget->hasVFP2() && 439 !Subtarget->isThumb1Only()) { 440 addRegisterClass(MVT::f32, &ARM::SPRRegClass); 441 addRegisterClass(MVT::f64, &ARM::DPRRegClass); 442 } 443 444 for (MVT VT : MVT::vector_valuetypes()) { 445 for (MVT InnerVT : MVT::vector_valuetypes()) { 446 setTruncStoreAction(VT, InnerVT, Expand); 447 setLoadExtAction(ISD::SEXTLOAD, VT, InnerVT, Expand); 448 setLoadExtAction(ISD::ZEXTLOAD, VT, InnerVT, Expand); 449 setLoadExtAction(ISD::EXTLOAD, VT, InnerVT, Expand); 450 } 451 452 setOperationAction(ISD::MULHS, VT, Expand); 453 setOperationAction(ISD::SMUL_LOHI, VT, Expand); 454 setOperationAction(ISD::MULHU, VT, Expand); 455 setOperationAction(ISD::UMUL_LOHI, VT, Expand); 456 457 setOperationAction(ISD::BSWAP, VT, Expand); 458 } 459 460 setOperationAction(ISD::ConstantFP, MVT::f32, Custom); 461 setOperationAction(ISD::ConstantFP, MVT::f64, Custom); 462 463 setOperationAction(ISD::READ_REGISTER, MVT::i64, Custom); 464 setOperationAction(ISD::WRITE_REGISTER, MVT::i64, Custom); 465 466 if (Subtarget->hasNEON()) { 467 addDRTypeForNEON(MVT::v2f32); 468 addDRTypeForNEON(MVT::v8i8); 469 addDRTypeForNEON(MVT::v4i16); 470 addDRTypeForNEON(MVT::v2i32); 471 addDRTypeForNEON(MVT::v1i64); 472 473 addQRTypeForNEON(MVT::v4f32); 474 addQRTypeForNEON(MVT::v2f64); 475 addQRTypeForNEON(MVT::v16i8); 476 addQRTypeForNEON(MVT::v8i16); 477 addQRTypeForNEON(MVT::v4i32); 478 addQRTypeForNEON(MVT::v2i64); 479 480 // v2f64 is legal so that QR subregs can be extracted as f64 elements, but 481 // neither Neon nor VFP support any arithmetic operations on it. 482 // The same with v4f32. But keep in mind that vadd, vsub, vmul are natively 483 // supported for v4f32. 484 setOperationAction(ISD::FADD, MVT::v2f64, Expand); 485 setOperationAction(ISD::FSUB, MVT::v2f64, Expand); 486 setOperationAction(ISD::FMUL, MVT::v2f64, Expand); 487 // FIXME: Code duplication: FDIV and FREM are expanded always, see 488 // ARMTargetLowering::addTypeForNEON method for details. 489 setOperationAction(ISD::FDIV, MVT::v2f64, Expand); 490 setOperationAction(ISD::FREM, MVT::v2f64, Expand); 491 // FIXME: Create unittest. 492 // In another words, find a way when "copysign" appears in DAG with vector 493 // operands. 494 setOperationAction(ISD::FCOPYSIGN, MVT::v2f64, Expand); 495 // FIXME: Code duplication: SETCC has custom operation action, see 496 // ARMTargetLowering::addTypeForNEON method for details. 497 setOperationAction(ISD::SETCC, MVT::v2f64, Expand); 498 // FIXME: Create unittest for FNEG and for FABS. 499 setOperationAction(ISD::FNEG, MVT::v2f64, Expand); 500 setOperationAction(ISD::FABS, MVT::v2f64, Expand); 501 setOperationAction(ISD::FSQRT, MVT::v2f64, Expand); 502 setOperationAction(ISD::FSIN, MVT::v2f64, Expand); 503 setOperationAction(ISD::FCOS, MVT::v2f64, Expand); 504 setOperationAction(ISD::FPOWI, MVT::v2f64, Expand); 505 setOperationAction(ISD::FPOW, MVT::v2f64, Expand); 506 setOperationAction(ISD::FLOG, MVT::v2f64, Expand); 507 setOperationAction(ISD::FLOG2, MVT::v2f64, Expand); 508 setOperationAction(ISD::FLOG10, MVT::v2f64, Expand); 509 setOperationAction(ISD::FEXP, MVT::v2f64, Expand); 510 setOperationAction(ISD::FEXP2, MVT::v2f64, Expand); 511 // FIXME: Create unittest for FCEIL, FTRUNC, FRINT, FNEARBYINT, FFLOOR. 512 setOperationAction(ISD::FCEIL, MVT::v2f64, Expand); 513 setOperationAction(ISD::FTRUNC, MVT::v2f64, Expand); 514 setOperationAction(ISD::FRINT, MVT::v2f64, Expand); 515 setOperationAction(ISD::FNEARBYINT, MVT::v2f64, Expand); 516 setOperationAction(ISD::FFLOOR, MVT::v2f64, Expand); 517 setOperationAction(ISD::FMA, MVT::v2f64, Expand); 518 519 setOperationAction(ISD::FSQRT, MVT::v4f32, Expand); 520 setOperationAction(ISD::FSIN, MVT::v4f32, Expand); 521 setOperationAction(ISD::FCOS, MVT::v4f32, Expand); 522 setOperationAction(ISD::FPOWI, MVT::v4f32, Expand); 523 setOperationAction(ISD::FPOW, MVT::v4f32, Expand); 524 setOperationAction(ISD::FLOG, MVT::v4f32, Expand); 525 setOperationAction(ISD::FLOG2, MVT::v4f32, Expand); 526 setOperationAction(ISD::FLOG10, MVT::v4f32, Expand); 527 setOperationAction(ISD::FEXP, MVT::v4f32, Expand); 528 setOperationAction(ISD::FEXP2, MVT::v4f32, Expand); 529 setOperationAction(ISD::FCEIL, MVT::v4f32, Expand); 530 setOperationAction(ISD::FTRUNC, MVT::v4f32, Expand); 531 setOperationAction(ISD::FRINT, MVT::v4f32, Expand); 532 setOperationAction(ISD::FNEARBYINT, MVT::v4f32, Expand); 533 setOperationAction(ISD::FFLOOR, MVT::v4f32, Expand); 534 535 // Mark v2f32 intrinsics. 536 setOperationAction(ISD::FSQRT, MVT::v2f32, Expand); 537 setOperationAction(ISD::FSIN, MVT::v2f32, Expand); 538 setOperationAction(ISD::FCOS, MVT::v2f32, Expand); 539 setOperationAction(ISD::FPOWI, MVT::v2f32, Expand); 540 setOperationAction(ISD::FPOW, MVT::v2f32, Expand); 541 setOperationAction(ISD::FLOG, MVT::v2f32, Expand); 542 setOperationAction(ISD::FLOG2, MVT::v2f32, Expand); 543 setOperationAction(ISD::FLOG10, MVT::v2f32, Expand); 544 setOperationAction(ISD::FEXP, MVT::v2f32, Expand); 545 setOperationAction(ISD::FEXP2, MVT::v2f32, Expand); 546 setOperationAction(ISD::FCEIL, MVT::v2f32, Expand); 547 setOperationAction(ISD::FTRUNC, MVT::v2f32, Expand); 548 setOperationAction(ISD::FRINT, MVT::v2f32, Expand); 549 setOperationAction(ISD::FNEARBYINT, MVT::v2f32, Expand); 550 setOperationAction(ISD::FFLOOR, MVT::v2f32, Expand); 551 552 // Neon does not support some operations on v1i64 and v2i64 types. 553 setOperationAction(ISD::MUL, MVT::v1i64, Expand); 554 // Custom handling for some quad-vector types to detect VMULL. 555 setOperationAction(ISD::MUL, MVT::v8i16, Custom); 556 setOperationAction(ISD::MUL, MVT::v4i32, Custom); 557 setOperationAction(ISD::MUL, MVT::v2i64, Custom); 558 // Custom handling for some vector types to avoid expensive expansions 559 setOperationAction(ISD::SDIV, MVT::v4i16, Custom); 560 setOperationAction(ISD::SDIV, MVT::v8i8, Custom); 561 setOperationAction(ISD::UDIV, MVT::v4i16, Custom); 562 setOperationAction(ISD::UDIV, MVT::v8i8, Custom); 563 setOperationAction(ISD::SETCC, MVT::v1i64, Expand); 564 setOperationAction(ISD::SETCC, MVT::v2i64, Expand); 565 // Neon does not have single instruction SINT_TO_FP and UINT_TO_FP with 566 // a destination type that is wider than the source, and nor does 567 // it have a FP_TO_[SU]INT instruction with a narrower destination than 568 // source. 569 setOperationAction(ISD::SINT_TO_FP, MVT::v4i16, Custom); 570 setOperationAction(ISD::UINT_TO_FP, MVT::v4i16, Custom); 571 setOperationAction(ISD::FP_TO_UINT, MVT::v4i16, Custom); 572 setOperationAction(ISD::FP_TO_SINT, MVT::v4i16, Custom); 573 574 setOperationAction(ISD::FP_ROUND, MVT::v2f32, Expand); 575 setOperationAction(ISD::FP_EXTEND, MVT::v2f64, Expand); 576 577 // NEON does not have single instruction CTPOP for vectors with element 578 // types wider than 8-bits. However, custom lowering can leverage the 579 // v8i8/v16i8 vcnt instruction. 580 setOperationAction(ISD::CTPOP, MVT::v2i32, Custom); 581 setOperationAction(ISD::CTPOP, MVT::v4i32, Custom); 582 setOperationAction(ISD::CTPOP, MVT::v4i16, Custom); 583 setOperationAction(ISD::CTPOP, MVT::v8i16, Custom); 584 585 // NEON does not have single instruction CTTZ for vectors. 586 setOperationAction(ISD::CTTZ, MVT::v8i8, Custom); 587 setOperationAction(ISD::CTTZ, MVT::v4i16, Custom); 588 setOperationAction(ISD::CTTZ, MVT::v2i32, Custom); 589 setOperationAction(ISD::CTTZ, MVT::v1i64, Custom); 590 591 setOperationAction(ISD::CTTZ, MVT::v16i8, Custom); 592 setOperationAction(ISD::CTTZ, MVT::v8i16, Custom); 593 setOperationAction(ISD::CTTZ, MVT::v4i32, Custom); 594 setOperationAction(ISD::CTTZ, MVT::v2i64, Custom); 595 596 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::v8i8, Custom); 597 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::v4i16, Custom); 598 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::v2i32, Custom); 599 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::v1i64, Custom); 600 601 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::v16i8, Custom); 602 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::v8i16, Custom); 603 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::v4i32, Custom); 604 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::v2i64, Custom); 605 606 // NEON only has FMA instructions as of VFP4. 607 if (!Subtarget->hasVFP4()) { 608 setOperationAction(ISD::FMA, MVT::v2f32, Expand); 609 setOperationAction(ISD::FMA, MVT::v4f32, Expand); 610 } 611 612 setTargetDAGCombine(ISD::INTRINSIC_VOID); 613 setTargetDAGCombine(ISD::INTRINSIC_W_CHAIN); 614 setTargetDAGCombine(ISD::INTRINSIC_WO_CHAIN); 615 setTargetDAGCombine(ISD::SHL); 616 setTargetDAGCombine(ISD::SRL); 617 setTargetDAGCombine(ISD::SRA); 618 setTargetDAGCombine(ISD::SIGN_EXTEND); 619 setTargetDAGCombine(ISD::ZERO_EXTEND); 620 setTargetDAGCombine(ISD::ANY_EXTEND); 621 setTargetDAGCombine(ISD::BUILD_VECTOR); 622 setTargetDAGCombine(ISD::VECTOR_SHUFFLE); 623 setTargetDAGCombine(ISD::INSERT_VECTOR_ELT); 624 setTargetDAGCombine(ISD::STORE); 625 setTargetDAGCombine(ISD::FP_TO_SINT); 626 setTargetDAGCombine(ISD::FP_TO_UINT); 627 setTargetDAGCombine(ISD::FDIV); 628 setTargetDAGCombine(ISD::LOAD); 629 630 // It is legal to extload from v4i8 to v4i16 or v4i32. 631 for (MVT Ty : {MVT::v8i8, MVT::v4i8, MVT::v2i8, MVT::v4i16, MVT::v2i16, 632 MVT::v2i32}) { 633 for (MVT VT : MVT::integer_vector_valuetypes()) { 634 setLoadExtAction(ISD::EXTLOAD, VT, Ty, Legal); 635 setLoadExtAction(ISD::ZEXTLOAD, VT, Ty, Legal); 636 setLoadExtAction(ISD::SEXTLOAD, VT, Ty, Legal); 637 } 638 } 639 } 640 641 // ARM and Thumb2 support UMLAL/SMLAL. 642 if (!Subtarget->isThumb1Only()) 643 setTargetDAGCombine(ISD::ADDC); 644 645 if (Subtarget->isFPOnlySP()) { 646 // When targeting a floating-point unit with only single-precision 647 // operations, f64 is legal for the few double-precision instructions which 648 // are present However, no double-precision operations other than moves, 649 // loads and stores are provided by the hardware. 650 setOperationAction(ISD::FADD, MVT::f64, Expand); 651 setOperationAction(ISD::FSUB, MVT::f64, Expand); 652 setOperationAction(ISD::FMUL, MVT::f64, Expand); 653 setOperationAction(ISD::FMA, MVT::f64, Expand); 654 setOperationAction(ISD::FDIV, MVT::f64, Expand); 655 setOperationAction(ISD::FREM, MVT::f64, Expand); 656 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand); 657 setOperationAction(ISD::FGETSIGN, MVT::f64, Expand); 658 setOperationAction(ISD::FNEG, MVT::f64, Expand); 659 setOperationAction(ISD::FABS, MVT::f64, Expand); 660 setOperationAction(ISD::FSQRT, MVT::f64, Expand); 661 setOperationAction(ISD::FSIN, MVT::f64, Expand); 662 setOperationAction(ISD::FCOS, MVT::f64, Expand); 663 setOperationAction(ISD::FPOWI, MVT::f64, Expand); 664 setOperationAction(ISD::FPOW, MVT::f64, Expand); 665 setOperationAction(ISD::FLOG, MVT::f64, Expand); 666 setOperationAction(ISD::FLOG2, MVT::f64, Expand); 667 setOperationAction(ISD::FLOG10, MVT::f64, Expand); 668 setOperationAction(ISD::FEXP, MVT::f64, Expand); 669 setOperationAction(ISD::FEXP2, MVT::f64, Expand); 670 setOperationAction(ISD::FCEIL, MVT::f64, Expand); 671 setOperationAction(ISD::FTRUNC, MVT::f64, Expand); 672 setOperationAction(ISD::FRINT, MVT::f64, Expand); 673 setOperationAction(ISD::FNEARBYINT, MVT::f64, Expand); 674 setOperationAction(ISD::FFLOOR, MVT::f64, Expand); 675 setOperationAction(ISD::SINT_TO_FP, MVT::i32, Custom); 676 setOperationAction(ISD::UINT_TO_FP, MVT::i32, Custom); 677 setOperationAction(ISD::FP_TO_SINT, MVT::i32, Custom); 678 setOperationAction(ISD::FP_TO_UINT, MVT::i32, Custom); 679 setOperationAction(ISD::FP_TO_SINT, MVT::f64, Custom); 680 setOperationAction(ISD::FP_TO_UINT, MVT::f64, Custom); 681 setOperationAction(ISD::FP_ROUND, MVT::f32, Custom); 682 setOperationAction(ISD::FP_EXTEND, MVT::f64, Custom); 683 } 684 685 computeRegisterProperties(Subtarget->getRegisterInfo()); 686 687 // ARM does not have floating-point extending loads. 688 for (MVT VT : MVT::fp_valuetypes()) { 689 setLoadExtAction(ISD::EXTLOAD, VT, MVT::f32, Expand); 690 setLoadExtAction(ISD::EXTLOAD, VT, MVT::f16, Expand); 691 } 692 693 // ... or truncating stores 694 setTruncStoreAction(MVT::f64, MVT::f32, Expand); 695 setTruncStoreAction(MVT::f32, MVT::f16, Expand); 696 setTruncStoreAction(MVT::f64, MVT::f16, Expand); 697 698 // ARM does not have i1 sign extending load. 699 for (MVT VT : MVT::integer_valuetypes()) 700 setLoadExtAction(ISD::SEXTLOAD, VT, MVT::i1, Promote); 701 702 // ARM supports all 4 flavors of integer indexed load / store. 703 if (!Subtarget->isThumb1Only()) { 704 for (unsigned im = (unsigned)ISD::PRE_INC; 705 im != (unsigned)ISD::LAST_INDEXED_MODE; ++im) { 706 setIndexedLoadAction(im, MVT::i1, Legal); 707 setIndexedLoadAction(im, MVT::i8, Legal); 708 setIndexedLoadAction(im, MVT::i16, Legal); 709 setIndexedLoadAction(im, MVT::i32, Legal); 710 setIndexedStoreAction(im, MVT::i1, Legal); 711 setIndexedStoreAction(im, MVT::i8, Legal); 712 setIndexedStoreAction(im, MVT::i16, Legal); 713 setIndexedStoreAction(im, MVT::i32, Legal); 714 } 715 } 716 717 setOperationAction(ISD::SADDO, MVT::i32, Custom); 718 setOperationAction(ISD::UADDO, MVT::i32, Custom); 719 setOperationAction(ISD::SSUBO, MVT::i32, Custom); 720 setOperationAction(ISD::USUBO, MVT::i32, Custom); 721 722 // i64 operation support. 723 setOperationAction(ISD::MUL, MVT::i64, Expand); 724 setOperationAction(ISD::MULHU, MVT::i32, Expand); 725 if (Subtarget->isThumb1Only()) { 726 setOperationAction(ISD::UMUL_LOHI, MVT::i32, Expand); 727 setOperationAction(ISD::SMUL_LOHI, MVT::i32, Expand); 728 } 729 if (Subtarget->isThumb1Only() || !Subtarget->hasV6Ops() 730 || (Subtarget->isThumb2() && !Subtarget->hasDSP())) 731 setOperationAction(ISD::MULHS, MVT::i32, Expand); 732 733 setOperationAction(ISD::SHL_PARTS, MVT::i32, Custom); 734 setOperationAction(ISD::SRA_PARTS, MVT::i32, Custom); 735 setOperationAction(ISD::SRL_PARTS, MVT::i32, Custom); 736 setOperationAction(ISD::SRL, MVT::i64, Custom); 737 setOperationAction(ISD::SRA, MVT::i64, Custom); 738 739 if (!Subtarget->isThumb1Only()) { 740 // FIXME: We should do this for Thumb1 as well. 741 setOperationAction(ISD::ADDC, MVT::i32, Custom); 742 setOperationAction(ISD::ADDE, MVT::i32, Custom); 743 setOperationAction(ISD::SUBC, MVT::i32, Custom); 744 setOperationAction(ISD::SUBE, MVT::i32, Custom); 745 } 746 747 if (!Subtarget->isThumb1Only() && Subtarget->hasV6T2Ops()) 748 setOperationAction(ISD::BITREVERSE, MVT::i32, Legal); 749 750 // ARM does not have ROTL. 751 setOperationAction(ISD::ROTL, MVT::i32, Expand); 752 for (MVT VT : MVT::vector_valuetypes()) { 753 setOperationAction(ISD::ROTL, VT, Expand); 754 setOperationAction(ISD::ROTR, VT, Expand); 755 } 756 setOperationAction(ISD::CTTZ, MVT::i32, Custom); 757 setOperationAction(ISD::CTPOP, MVT::i32, Expand); 758 if (!Subtarget->hasV5TOps() || Subtarget->isThumb1Only()) 759 setOperationAction(ISD::CTLZ, MVT::i32, Expand); 760 761 // These just redirect to CTTZ and CTLZ on ARM. 762 setOperationAction(ISD::CTTZ_ZERO_UNDEF , MVT::i32 , Expand); 763 setOperationAction(ISD::CTLZ_ZERO_UNDEF , MVT::i32 , Expand); 764 765 // @llvm.readcyclecounter requires the Performance Monitors extension. 766 // Default to the 0 expansion on unsupported platforms. 767 // FIXME: Technically there are older ARM CPUs that have 768 // implementation-specific ways of obtaining this information. 769 if (Subtarget->hasPerfMon()) 770 setOperationAction(ISD::READCYCLECOUNTER, MVT::i64, Custom); 771 772 // Only ARMv6 has BSWAP. 773 if (!Subtarget->hasV6Ops()) 774 setOperationAction(ISD::BSWAP, MVT::i32, Expand); 775 776 bool hasDivide = Subtarget->isThumb() ? Subtarget->hasDivide() 777 : Subtarget->hasDivideInARMMode(); 778 if (!hasDivide) { 779 // These are expanded into libcalls if the cpu doesn't have HW divider. 780 setOperationAction(ISD::SDIV, MVT::i32, LibCall); 781 setOperationAction(ISD::UDIV, MVT::i32, LibCall); 782 } 783 784 setOperationAction(ISD::SREM, MVT::i32, Expand); 785 setOperationAction(ISD::UREM, MVT::i32, Expand); 786 // Register based DivRem for AEABI (RTABI 4.2) 787 if (Subtarget->isTargetAEABI() || Subtarget->isTargetAndroid()) { 788 setOperationAction(ISD::SREM, MVT::i64, Custom); 789 setOperationAction(ISD::UREM, MVT::i64, Custom); 790 791 setLibcallName(RTLIB::SDIVREM_I8, "__aeabi_idivmod"); 792 setLibcallName(RTLIB::SDIVREM_I16, "__aeabi_idivmod"); 793 setLibcallName(RTLIB::SDIVREM_I32, "__aeabi_idivmod"); 794 setLibcallName(RTLIB::SDIVREM_I64, "__aeabi_ldivmod"); 795 setLibcallName(RTLIB::UDIVREM_I8, "__aeabi_uidivmod"); 796 setLibcallName(RTLIB::UDIVREM_I16, "__aeabi_uidivmod"); 797 setLibcallName(RTLIB::UDIVREM_I32, "__aeabi_uidivmod"); 798 setLibcallName(RTLIB::UDIVREM_I64, "__aeabi_uldivmod"); 799 800 setLibcallCallingConv(RTLIB::SDIVREM_I8, CallingConv::ARM_AAPCS); 801 setLibcallCallingConv(RTLIB::SDIVREM_I16, CallingConv::ARM_AAPCS); 802 setLibcallCallingConv(RTLIB::SDIVREM_I32, CallingConv::ARM_AAPCS); 803 setLibcallCallingConv(RTLIB::SDIVREM_I64, CallingConv::ARM_AAPCS); 804 setLibcallCallingConv(RTLIB::UDIVREM_I8, CallingConv::ARM_AAPCS); 805 setLibcallCallingConv(RTLIB::UDIVREM_I16, CallingConv::ARM_AAPCS); 806 setLibcallCallingConv(RTLIB::UDIVREM_I32, CallingConv::ARM_AAPCS); 807 setLibcallCallingConv(RTLIB::UDIVREM_I64, CallingConv::ARM_AAPCS); 808 809 setOperationAction(ISD::SDIVREM, MVT::i32, Custom); 810 setOperationAction(ISD::UDIVREM, MVT::i32, Custom); 811 } else { 812 setOperationAction(ISD::SDIVREM, MVT::i32, Expand); 813 setOperationAction(ISD::UDIVREM, MVT::i32, Expand); 814 } 815 816 setOperationAction(ISD::GlobalAddress, MVT::i32, Custom); 817 setOperationAction(ISD::ConstantPool, MVT::i32, Custom); 818 setOperationAction(ISD::GlobalTLSAddress, MVT::i32, Custom); 819 setOperationAction(ISD::BlockAddress, MVT::i32, Custom); 820 821 setOperationAction(ISD::TRAP, MVT::Other, Legal); 822 823 // Use the default implementation. 824 setOperationAction(ISD::VASTART, MVT::Other, Custom); 825 setOperationAction(ISD::VAARG, MVT::Other, Expand); 826 setOperationAction(ISD::VACOPY, MVT::Other, Expand); 827 setOperationAction(ISD::VAEND, MVT::Other, Expand); 828 setOperationAction(ISD::STACKSAVE, MVT::Other, Expand); 829 setOperationAction(ISD::STACKRESTORE, MVT::Other, Expand); 830 831 if (Subtarget->getTargetTriple().isWindowsItaniumEnvironment()) 832 setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i32, Custom); 833 else 834 setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i32, Expand); 835 836 // ARMv6 Thumb1 (except for CPUs that support dmb / dsb) and earlier use 837 // the default expansion. If we are targeting a single threaded system, 838 // then set them all for expand so we can lower them later into their 839 // non-atomic form. 840 if (TM.Options.ThreadModel == ThreadModel::Single) 841 setOperationAction(ISD::ATOMIC_FENCE, MVT::Other, Expand); 842 else if (Subtarget->hasAnyDataBarrier() && (!Subtarget->isThumb() || 843 Subtarget->hasV8MBaselineOps())) { 844 // ATOMIC_FENCE needs custom lowering; the others should have been expanded 845 // to ldrex/strex loops already. 846 setOperationAction(ISD::ATOMIC_FENCE, MVT::Other, Custom); 847 848 // On v8, we have particularly efficient implementations of atomic fences 849 // if they can be combined with nearby atomic loads and stores. 850 if (!Subtarget->hasV8Ops()) { 851 // Automatically insert fences (dmb ish) around ATOMIC_SWAP etc. 852 setInsertFencesForAtomic(true); 853 } 854 } else { 855 // If there's anything we can use as a barrier, go through custom lowering 856 // for ATOMIC_FENCE. 857 setOperationAction(ISD::ATOMIC_FENCE, MVT::Other, 858 Subtarget->hasAnyDataBarrier() ? Custom : Expand); 859 860 // Set them all for expansion, which will force libcalls. 861 setOperationAction(ISD::ATOMIC_CMP_SWAP, MVT::i32, Expand); 862 setOperationAction(ISD::ATOMIC_SWAP, MVT::i32, Expand); 863 setOperationAction(ISD::ATOMIC_LOAD_ADD, MVT::i32, Expand); 864 setOperationAction(ISD::ATOMIC_LOAD_SUB, MVT::i32, Expand); 865 setOperationAction(ISD::ATOMIC_LOAD_AND, MVT::i32, Expand); 866 setOperationAction(ISD::ATOMIC_LOAD_OR, MVT::i32, Expand); 867 setOperationAction(ISD::ATOMIC_LOAD_XOR, MVT::i32, Expand); 868 setOperationAction(ISD::ATOMIC_LOAD_NAND, MVT::i32, Expand); 869 setOperationAction(ISD::ATOMIC_LOAD_MIN, MVT::i32, Expand); 870 setOperationAction(ISD::ATOMIC_LOAD_MAX, MVT::i32, Expand); 871 setOperationAction(ISD::ATOMIC_LOAD_UMIN, MVT::i32, Expand); 872 setOperationAction(ISD::ATOMIC_LOAD_UMAX, MVT::i32, Expand); 873 // Mark ATOMIC_LOAD and ATOMIC_STORE custom so we can handle the 874 // Unordered/Monotonic case. 875 setOperationAction(ISD::ATOMIC_LOAD, MVT::i32, Custom); 876 setOperationAction(ISD::ATOMIC_STORE, MVT::i32, Custom); 877 } 878 879 setOperationAction(ISD::PREFETCH, MVT::Other, Custom); 880 881 // Requires SXTB/SXTH, available on v6 and up in both ARM and Thumb modes. 882 if (!Subtarget->hasV6Ops()) { 883 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i16, Expand); 884 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i8, Expand); 885 } 886 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1, Expand); 887 888 if (!Subtarget->useSoftFloat() && Subtarget->hasVFP2() && 889 !Subtarget->isThumb1Only()) { 890 // Turn f64->i64 into VMOVRRD, i64 -> f64 to VMOVDRR 891 // iff target supports vfp2. 892 setOperationAction(ISD::BITCAST, MVT::i64, Custom); 893 setOperationAction(ISD::FLT_ROUNDS_, MVT::i32, Custom); 894 } 895 896 // We want to custom lower some of our intrinsics. 897 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom); 898 setOperationAction(ISD::EH_SJLJ_SETJMP, MVT::i32, Custom); 899 setOperationAction(ISD::EH_SJLJ_LONGJMP, MVT::Other, Custom); 900 setOperationAction(ISD::EH_SJLJ_SETUP_DISPATCH, MVT::Other, Custom); 901 if (Subtarget->useSjLjEH()) 902 setLibcallName(RTLIB::UNWIND_RESUME, "_Unwind_SjLj_Resume"); 903 904 setOperationAction(ISD::SETCC, MVT::i32, Expand); 905 setOperationAction(ISD::SETCC, MVT::f32, Expand); 906 setOperationAction(ISD::SETCC, MVT::f64, Expand); 907 setOperationAction(ISD::SELECT, MVT::i32, Custom); 908 setOperationAction(ISD::SELECT, MVT::f32, Custom); 909 setOperationAction(ISD::SELECT, MVT::f64, Custom); 910 setOperationAction(ISD::SELECT_CC, MVT::i32, Custom); 911 setOperationAction(ISD::SELECT_CC, MVT::f32, Custom); 912 setOperationAction(ISD::SELECT_CC, MVT::f64, Custom); 913 914 setOperationAction(ISD::BRCOND, MVT::Other, Expand); 915 setOperationAction(ISD::BR_CC, MVT::i32, Custom); 916 setOperationAction(ISD::BR_CC, MVT::f32, Custom); 917 setOperationAction(ISD::BR_CC, MVT::f64, Custom); 918 setOperationAction(ISD::BR_JT, MVT::Other, Custom); 919 920 // We don't support sin/cos/fmod/copysign/pow 921 setOperationAction(ISD::FSIN, MVT::f64, Expand); 922 setOperationAction(ISD::FSIN, MVT::f32, Expand); 923 setOperationAction(ISD::FCOS, MVT::f32, Expand); 924 setOperationAction(ISD::FCOS, MVT::f64, Expand); 925 setOperationAction(ISD::FSINCOS, MVT::f64, Expand); 926 setOperationAction(ISD::FSINCOS, MVT::f32, Expand); 927 setOperationAction(ISD::FREM, MVT::f64, Expand); 928 setOperationAction(ISD::FREM, MVT::f32, Expand); 929 if (!Subtarget->useSoftFloat() && Subtarget->hasVFP2() && 930 !Subtarget->isThumb1Only()) { 931 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Custom); 932 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom); 933 } 934 setOperationAction(ISD::FPOW, MVT::f64, Expand); 935 setOperationAction(ISD::FPOW, MVT::f32, Expand); 936 937 if (!Subtarget->hasVFP4()) { 938 setOperationAction(ISD::FMA, MVT::f64, Expand); 939 setOperationAction(ISD::FMA, MVT::f32, Expand); 940 } 941 942 // Various VFP goodness 943 if (!Subtarget->useSoftFloat() && !Subtarget->isThumb1Only()) { 944 // FP-ARMv8 adds f64 <-> f16 conversion. Before that it should be expanded. 945 if (!Subtarget->hasFPARMv8() || Subtarget->isFPOnlySP()) { 946 setOperationAction(ISD::FP16_TO_FP, MVT::f64, Expand); 947 setOperationAction(ISD::FP_TO_FP16, MVT::f64, Expand); 948 } 949 950 // fp16 is a special v7 extension that adds f16 <-> f32 conversions. 951 if (!Subtarget->hasFP16()) { 952 setOperationAction(ISD::FP16_TO_FP, MVT::f32, Expand); 953 setOperationAction(ISD::FP_TO_FP16, MVT::f32, Expand); 954 } 955 } 956 957 // Combine sin / cos into one node or libcall if possible. 958 if (Subtarget->hasSinCos()) { 959 setLibcallName(RTLIB::SINCOS_F32, "sincosf"); 960 setLibcallName(RTLIB::SINCOS_F64, "sincos"); 961 if (Subtarget->isTargetWatchABI()) { 962 setLibcallCallingConv(RTLIB::SINCOS_F32, CallingConv::ARM_AAPCS_VFP); 963 setLibcallCallingConv(RTLIB::SINCOS_F64, CallingConv::ARM_AAPCS_VFP); 964 } 965 if (Subtarget->isTargetIOS() || Subtarget->isTargetWatchOS()) { 966 // For iOS, we don't want to the normal expansion of a libcall to 967 // sincos. We want to issue a libcall to __sincos_stret. 968 setOperationAction(ISD::FSINCOS, MVT::f64, Custom); 969 setOperationAction(ISD::FSINCOS, MVT::f32, Custom); 970 } 971 } 972 973 // FP-ARMv8 implements a lot of rounding-like FP operations. 974 if (Subtarget->hasFPARMv8()) { 975 setOperationAction(ISD::FFLOOR, MVT::f32, Legal); 976 setOperationAction(ISD::FCEIL, MVT::f32, Legal); 977 setOperationAction(ISD::FROUND, MVT::f32, Legal); 978 setOperationAction(ISD::FTRUNC, MVT::f32, Legal); 979 setOperationAction(ISD::FNEARBYINT, MVT::f32, Legal); 980 setOperationAction(ISD::FRINT, MVT::f32, Legal); 981 setOperationAction(ISD::FMINNUM, MVT::f32, Legal); 982 setOperationAction(ISD::FMAXNUM, MVT::f32, Legal); 983 setOperationAction(ISD::FMINNUM, MVT::v2f32, Legal); 984 setOperationAction(ISD::FMAXNUM, MVT::v2f32, Legal); 985 setOperationAction(ISD::FMINNUM, MVT::v4f32, Legal); 986 setOperationAction(ISD::FMAXNUM, MVT::v4f32, Legal); 987 988 if (!Subtarget->isFPOnlySP()) { 989 setOperationAction(ISD::FFLOOR, MVT::f64, Legal); 990 setOperationAction(ISD::FCEIL, MVT::f64, Legal); 991 setOperationAction(ISD::FROUND, MVT::f64, Legal); 992 setOperationAction(ISD::FTRUNC, MVT::f64, Legal); 993 setOperationAction(ISD::FNEARBYINT, MVT::f64, Legal); 994 setOperationAction(ISD::FRINT, MVT::f64, Legal); 995 setOperationAction(ISD::FMINNUM, MVT::f64, Legal); 996 setOperationAction(ISD::FMAXNUM, MVT::f64, Legal); 997 } 998 } 999 1000 if (Subtarget->hasNEON()) { 1001 // vmin and vmax aren't available in a scalar form, so we use 1002 // a NEON instruction with an undef lane instead. 1003 setOperationAction(ISD::FMINNAN, MVT::f32, Legal); 1004 setOperationAction(ISD::FMAXNAN, MVT::f32, Legal); 1005 setOperationAction(ISD::FMINNAN, MVT::v2f32, Legal); 1006 setOperationAction(ISD::FMAXNAN, MVT::v2f32, Legal); 1007 setOperationAction(ISD::FMINNAN, MVT::v4f32, Legal); 1008 setOperationAction(ISD::FMAXNAN, MVT::v4f32, Legal); 1009 } 1010 1011 // We have target-specific dag combine patterns for the following nodes: 1012 // ARMISD::VMOVRRD - No need to call setTargetDAGCombine 1013 setTargetDAGCombine(ISD::ADD); 1014 setTargetDAGCombine(ISD::SUB); 1015 setTargetDAGCombine(ISD::MUL); 1016 setTargetDAGCombine(ISD::AND); 1017 setTargetDAGCombine(ISD::OR); 1018 setTargetDAGCombine(ISD::XOR); 1019 1020 if (Subtarget->hasV6Ops()) 1021 setTargetDAGCombine(ISD::SRL); 1022 1023 setStackPointerRegisterToSaveRestore(ARM::SP); 1024 1025 if (Subtarget->useSoftFloat() || Subtarget->isThumb1Only() || 1026 !Subtarget->hasVFP2()) 1027 setSchedulingPreference(Sched::RegPressure); 1028 else 1029 setSchedulingPreference(Sched::Hybrid); 1030 1031 //// temporary - rewrite interface to use type 1032 MaxStoresPerMemset = 8; 1033 MaxStoresPerMemsetOptSize = 4; 1034 MaxStoresPerMemcpy = 4; // For @llvm.memcpy -> sequence of stores 1035 MaxStoresPerMemcpyOptSize = 2; 1036 MaxStoresPerMemmove = 4; // For @llvm.memmove -> sequence of stores 1037 MaxStoresPerMemmoveOptSize = 2; 1038 1039 // On ARM arguments smaller than 4 bytes are extended, so all arguments 1040 // are at least 4 bytes aligned. 1041 setMinStackArgumentAlignment(4); 1042 1043 // Prefer likely predicted branches to selects on out-of-order cores. 1044 PredictableSelectIsExpensive = Subtarget->isLikeA9(); 1045 1046 setMinFunctionAlignment(Subtarget->isThumb() ? 1 : 2); 1047 } 1048 1049 bool ARMTargetLowering::useSoftFloat() const { 1050 return Subtarget->useSoftFloat(); 1051 } 1052 1053 // FIXME: It might make sense to define the representative register class as the 1054 // nearest super-register that has a non-null superset. For example, DPR_VFP2 is 1055 // a super-register of SPR, and DPR is a superset if DPR_VFP2. Consequently, 1056 // SPR's representative would be DPR_VFP2. This should work well if register 1057 // pressure tracking were modified such that a register use would increment the 1058 // pressure of the register class's representative and all of it's super 1059 // classes' representatives transitively. We have not implemented this because 1060 // of the difficulty prior to coalescing of modeling operand register classes 1061 // due to the common occurrence of cross class copies and subregister insertions 1062 // and extractions. 1063 std::pair<const TargetRegisterClass *, uint8_t> 1064 ARMTargetLowering::findRepresentativeClass(const TargetRegisterInfo *TRI, 1065 MVT VT) const { 1066 const TargetRegisterClass *RRC = nullptr; 1067 uint8_t Cost = 1; 1068 switch (VT.SimpleTy) { 1069 default: 1070 return TargetLowering::findRepresentativeClass(TRI, VT); 1071 // Use DPR as representative register class for all floating point 1072 // and vector types. Since there are 32 SPR registers and 32 DPR registers so 1073 // the cost is 1 for both f32 and f64. 1074 case MVT::f32: case MVT::f64: case MVT::v8i8: case MVT::v4i16: 1075 case MVT::v2i32: case MVT::v1i64: case MVT::v2f32: 1076 RRC = &ARM::DPRRegClass; 1077 // When NEON is used for SP, only half of the register file is available 1078 // because operations that define both SP and DP results will be constrained 1079 // to the VFP2 class (D0-D15). We currently model this constraint prior to 1080 // coalescing by double-counting the SP regs. See the FIXME above. 1081 if (Subtarget->useNEONForSinglePrecisionFP()) 1082 Cost = 2; 1083 break; 1084 case MVT::v16i8: case MVT::v8i16: case MVT::v4i32: case MVT::v2i64: 1085 case MVT::v4f32: case MVT::v2f64: 1086 RRC = &ARM::DPRRegClass; 1087 Cost = 2; 1088 break; 1089 case MVT::v4i64: 1090 RRC = &ARM::DPRRegClass; 1091 Cost = 4; 1092 break; 1093 case MVT::v8i64: 1094 RRC = &ARM::DPRRegClass; 1095 Cost = 8; 1096 break; 1097 } 1098 return std::make_pair(RRC, Cost); 1099 } 1100 1101 const char *ARMTargetLowering::getTargetNodeName(unsigned Opcode) const { 1102 switch ((ARMISD::NodeType)Opcode) { 1103 case ARMISD::FIRST_NUMBER: break; 1104 case ARMISD::Wrapper: return "ARMISD::Wrapper"; 1105 case ARMISD::WrapperPIC: return "ARMISD::WrapperPIC"; 1106 case ARMISD::WrapperJT: return "ARMISD::WrapperJT"; 1107 case ARMISD::COPY_STRUCT_BYVAL: return "ARMISD::COPY_STRUCT_BYVAL"; 1108 case ARMISD::CALL: return "ARMISD::CALL"; 1109 case ARMISD::CALL_PRED: return "ARMISD::CALL_PRED"; 1110 case ARMISD::CALL_NOLINK: return "ARMISD::CALL_NOLINK"; 1111 case ARMISD::tCALL: return "ARMISD::tCALL"; 1112 case ARMISD::BRCOND: return "ARMISD::BRCOND"; 1113 case ARMISD::BR_JT: return "ARMISD::BR_JT"; 1114 case ARMISD::BR2_JT: return "ARMISD::BR2_JT"; 1115 case ARMISD::RET_FLAG: return "ARMISD::RET_FLAG"; 1116 case ARMISD::INTRET_FLAG: return "ARMISD::INTRET_FLAG"; 1117 case ARMISD::PIC_ADD: return "ARMISD::PIC_ADD"; 1118 case ARMISD::CMP: return "ARMISD::CMP"; 1119 case ARMISD::CMN: return "ARMISD::CMN"; 1120 case ARMISD::CMPZ: return "ARMISD::CMPZ"; 1121 case ARMISD::CMPFP: return "ARMISD::CMPFP"; 1122 case ARMISD::CMPFPw0: return "ARMISD::CMPFPw0"; 1123 case ARMISD::BCC_i64: return "ARMISD::BCC_i64"; 1124 case ARMISD::FMSTAT: return "ARMISD::FMSTAT"; 1125 1126 case ARMISD::CMOV: return "ARMISD::CMOV"; 1127 1128 case ARMISD::SRL_FLAG: return "ARMISD::SRL_FLAG"; 1129 case ARMISD::SRA_FLAG: return "ARMISD::SRA_FLAG"; 1130 case ARMISD::RRX: return "ARMISD::RRX"; 1131 1132 case ARMISD::ADDC: return "ARMISD::ADDC"; 1133 case ARMISD::ADDE: return "ARMISD::ADDE"; 1134 case ARMISD::SUBC: return "ARMISD::SUBC"; 1135 case ARMISD::SUBE: return "ARMISD::SUBE"; 1136 1137 case ARMISD::VMOVRRD: return "ARMISD::VMOVRRD"; 1138 case ARMISD::VMOVDRR: return "ARMISD::VMOVDRR"; 1139 1140 case ARMISD::EH_SJLJ_SETJMP: return "ARMISD::EH_SJLJ_SETJMP"; 1141 case ARMISD::EH_SJLJ_LONGJMP: return "ARMISD::EH_SJLJ_LONGJMP"; 1142 case ARMISD::EH_SJLJ_SETUP_DISPATCH: return "ARMISD::EH_SJLJ_SETUP_DISPATCH"; 1143 1144 case ARMISD::TC_RETURN: return "ARMISD::TC_RETURN"; 1145 1146 case ARMISD::THREAD_POINTER:return "ARMISD::THREAD_POINTER"; 1147 1148 case ARMISD::DYN_ALLOC: return "ARMISD::DYN_ALLOC"; 1149 1150 case ARMISD::MEMBARRIER_MCR: return "ARMISD::MEMBARRIER_MCR"; 1151 1152 case ARMISD::PRELOAD: return "ARMISD::PRELOAD"; 1153 1154 case ARMISD::WIN__CHKSTK: return "ARMISD:::WIN__CHKSTK"; 1155 case ARMISD::WIN__DBZCHK: return "ARMISD::WIN__DBZCHK"; 1156 1157 case ARMISD::VCEQ: return "ARMISD::VCEQ"; 1158 case ARMISD::VCEQZ: return "ARMISD::VCEQZ"; 1159 case ARMISD::VCGE: return "ARMISD::VCGE"; 1160 case ARMISD::VCGEZ: return "ARMISD::VCGEZ"; 1161 case ARMISD::VCLEZ: return "ARMISD::VCLEZ"; 1162 case ARMISD::VCGEU: return "ARMISD::VCGEU"; 1163 case ARMISD::VCGT: return "ARMISD::VCGT"; 1164 case ARMISD::VCGTZ: return "ARMISD::VCGTZ"; 1165 case ARMISD::VCLTZ: return "ARMISD::VCLTZ"; 1166 case ARMISD::VCGTU: return "ARMISD::VCGTU"; 1167 case ARMISD::VTST: return "ARMISD::VTST"; 1168 1169 case ARMISD::VSHL: return "ARMISD::VSHL"; 1170 case ARMISD::VSHRs: return "ARMISD::VSHRs"; 1171 case ARMISD::VSHRu: return "ARMISD::VSHRu"; 1172 case ARMISD::VRSHRs: return "ARMISD::VRSHRs"; 1173 case ARMISD::VRSHRu: return "ARMISD::VRSHRu"; 1174 case ARMISD::VRSHRN: return "ARMISD::VRSHRN"; 1175 case ARMISD::VQSHLs: return "ARMISD::VQSHLs"; 1176 case ARMISD::VQSHLu: return "ARMISD::VQSHLu"; 1177 case ARMISD::VQSHLsu: return "ARMISD::VQSHLsu"; 1178 case ARMISD::VQSHRNs: return "ARMISD::VQSHRNs"; 1179 case ARMISD::VQSHRNu: return "ARMISD::VQSHRNu"; 1180 case ARMISD::VQSHRNsu: return "ARMISD::VQSHRNsu"; 1181 case ARMISD::VQRSHRNs: return "ARMISD::VQRSHRNs"; 1182 case ARMISD::VQRSHRNu: return "ARMISD::VQRSHRNu"; 1183 case ARMISD::VQRSHRNsu: return "ARMISD::VQRSHRNsu"; 1184 case ARMISD::VSLI: return "ARMISD::VSLI"; 1185 case ARMISD::VSRI: return "ARMISD::VSRI"; 1186 case ARMISD::VGETLANEu: return "ARMISD::VGETLANEu"; 1187 case ARMISD::VGETLANEs: return "ARMISD::VGETLANEs"; 1188 case ARMISD::VMOVIMM: return "ARMISD::VMOVIMM"; 1189 case ARMISD::VMVNIMM: return "ARMISD::VMVNIMM"; 1190 case ARMISD::VMOVFPIMM: return "ARMISD::VMOVFPIMM"; 1191 case ARMISD::VDUP: return "ARMISD::VDUP"; 1192 case ARMISD::VDUPLANE: return "ARMISD::VDUPLANE"; 1193 case ARMISD::VEXT: return "ARMISD::VEXT"; 1194 case ARMISD::VREV64: return "ARMISD::VREV64"; 1195 case ARMISD::VREV32: return "ARMISD::VREV32"; 1196 case ARMISD::VREV16: return "ARMISD::VREV16"; 1197 case ARMISD::VZIP: return "ARMISD::VZIP"; 1198 case ARMISD::VUZP: return "ARMISD::VUZP"; 1199 case ARMISD::VTRN: return "ARMISD::VTRN"; 1200 case ARMISD::VTBL1: return "ARMISD::VTBL1"; 1201 case ARMISD::VTBL2: return "ARMISD::VTBL2"; 1202 case ARMISD::VMULLs: return "ARMISD::VMULLs"; 1203 case ARMISD::VMULLu: return "ARMISD::VMULLu"; 1204 case ARMISD::UMLAL: return "ARMISD::UMLAL"; 1205 case ARMISD::SMLAL: return "ARMISD::SMLAL"; 1206 case ARMISD::BUILD_VECTOR: return "ARMISD::BUILD_VECTOR"; 1207 case ARMISD::BFI: return "ARMISD::BFI"; 1208 case ARMISD::VORRIMM: return "ARMISD::VORRIMM"; 1209 case ARMISD::VBICIMM: return "ARMISD::VBICIMM"; 1210 case ARMISD::VBSL: return "ARMISD::VBSL"; 1211 case ARMISD::MEMCPY: return "ARMISD::MEMCPY"; 1212 case ARMISD::VLD2DUP: return "ARMISD::VLD2DUP"; 1213 case ARMISD::VLD3DUP: return "ARMISD::VLD3DUP"; 1214 case ARMISD::VLD4DUP: return "ARMISD::VLD4DUP"; 1215 case ARMISD::VLD1_UPD: return "ARMISD::VLD1_UPD"; 1216 case ARMISD::VLD2_UPD: return "ARMISD::VLD2_UPD"; 1217 case ARMISD::VLD3_UPD: return "ARMISD::VLD3_UPD"; 1218 case ARMISD::VLD4_UPD: return "ARMISD::VLD4_UPD"; 1219 case ARMISD::VLD2LN_UPD: return "ARMISD::VLD2LN_UPD"; 1220 case ARMISD::VLD3LN_UPD: return "ARMISD::VLD3LN_UPD"; 1221 case ARMISD::VLD4LN_UPD: return "ARMISD::VLD4LN_UPD"; 1222 case ARMISD::VLD2DUP_UPD: return "ARMISD::VLD2DUP_UPD"; 1223 case ARMISD::VLD3DUP_UPD: return "ARMISD::VLD3DUP_UPD"; 1224 case ARMISD::VLD4DUP_UPD: return "ARMISD::VLD4DUP_UPD"; 1225 case ARMISD::VST1_UPD: return "ARMISD::VST1_UPD"; 1226 case ARMISD::VST2_UPD: return "ARMISD::VST2_UPD"; 1227 case ARMISD::VST3_UPD: return "ARMISD::VST3_UPD"; 1228 case ARMISD::VST4_UPD: return "ARMISD::VST4_UPD"; 1229 case ARMISD::VST2LN_UPD: return "ARMISD::VST2LN_UPD"; 1230 case ARMISD::VST3LN_UPD: return "ARMISD::VST3LN_UPD"; 1231 case ARMISD::VST4LN_UPD: return "ARMISD::VST4LN_UPD"; 1232 } 1233 return nullptr; 1234 } 1235 1236 EVT ARMTargetLowering::getSetCCResultType(const DataLayout &DL, LLVMContext &, 1237 EVT VT) const { 1238 if (!VT.isVector()) 1239 return getPointerTy(DL); 1240 return VT.changeVectorElementTypeToInteger(); 1241 } 1242 1243 /// getRegClassFor - Return the register class that should be used for the 1244 /// specified value type. 1245 const TargetRegisterClass *ARMTargetLowering::getRegClassFor(MVT VT) const { 1246 // Map v4i64 to QQ registers but do not make the type legal. Similarly map 1247 // v8i64 to QQQQ registers. v4i64 and v8i64 are only used for REG_SEQUENCE to 1248 // load / store 4 to 8 consecutive D registers. 1249 if (Subtarget->hasNEON()) { 1250 if (VT == MVT::v4i64) 1251 return &ARM::QQPRRegClass; 1252 if (VT == MVT::v8i64) 1253 return &ARM::QQQQPRRegClass; 1254 } 1255 return TargetLowering::getRegClassFor(VT); 1256 } 1257 1258 // memcpy, and other memory intrinsics, typically tries to use LDM/STM if the 1259 // source/dest is aligned and the copy size is large enough. We therefore want 1260 // to align such objects passed to memory intrinsics. 1261 bool ARMTargetLowering::shouldAlignPointerArgs(CallInst *CI, unsigned &MinSize, 1262 unsigned &PrefAlign) const { 1263 if (!isa<MemIntrinsic>(CI)) 1264 return false; 1265 MinSize = 8; 1266 // On ARM11 onwards (excluding M class) 8-byte aligned LDM is typically 1 1267 // cycle faster than 4-byte aligned LDM. 1268 PrefAlign = (Subtarget->hasV6Ops() && !Subtarget->isMClass() ? 8 : 4); 1269 return true; 1270 } 1271 1272 // Create a fast isel object. 1273 FastISel * 1274 ARMTargetLowering::createFastISel(FunctionLoweringInfo &funcInfo, 1275 const TargetLibraryInfo *libInfo) const { 1276 return ARM::createFastISel(funcInfo, libInfo); 1277 } 1278 1279 Sched::Preference ARMTargetLowering::getSchedulingPreference(SDNode *N) const { 1280 unsigned NumVals = N->getNumValues(); 1281 if (!NumVals) 1282 return Sched::RegPressure; 1283 1284 for (unsigned i = 0; i != NumVals; ++i) { 1285 EVT VT = N->getValueType(i); 1286 if (VT == MVT::Glue || VT == MVT::Other) 1287 continue; 1288 if (VT.isFloatingPoint() || VT.isVector()) 1289 return Sched::ILP; 1290 } 1291 1292 if (!N->isMachineOpcode()) 1293 return Sched::RegPressure; 1294 1295 // Load are scheduled for latency even if there instruction itinerary 1296 // is not available. 1297 const TargetInstrInfo *TII = Subtarget->getInstrInfo(); 1298 const MCInstrDesc &MCID = TII->get(N->getMachineOpcode()); 1299 1300 if (MCID.getNumDefs() == 0) 1301 return Sched::RegPressure; 1302 if (!Itins->isEmpty() && 1303 Itins->getOperandCycle(MCID.getSchedClass(), 0) > 2) 1304 return Sched::ILP; 1305 1306 return Sched::RegPressure; 1307 } 1308 1309 //===----------------------------------------------------------------------===// 1310 // Lowering Code 1311 //===----------------------------------------------------------------------===// 1312 1313 /// IntCCToARMCC - Convert a DAG integer condition code to an ARM CC 1314 static ARMCC::CondCodes IntCCToARMCC(ISD::CondCode CC) { 1315 switch (CC) { 1316 default: llvm_unreachable("Unknown condition code!"); 1317 case ISD::SETNE: return ARMCC::NE; 1318 case ISD::SETEQ: return ARMCC::EQ; 1319 case ISD::SETGT: return ARMCC::GT; 1320 case ISD::SETGE: return ARMCC::GE; 1321 case ISD::SETLT: return ARMCC::LT; 1322 case ISD::SETLE: return ARMCC::LE; 1323 case ISD::SETUGT: return ARMCC::HI; 1324 case ISD::SETUGE: return ARMCC::HS; 1325 case ISD::SETULT: return ARMCC::LO; 1326 case ISD::SETULE: return ARMCC::LS; 1327 } 1328 } 1329 1330 /// FPCCToARMCC - Convert a DAG fp condition code to an ARM CC. 1331 static void FPCCToARMCC(ISD::CondCode CC, ARMCC::CondCodes &CondCode, 1332 ARMCC::CondCodes &CondCode2) { 1333 CondCode2 = ARMCC::AL; 1334 switch (CC) { 1335 default: llvm_unreachable("Unknown FP condition!"); 1336 case ISD::SETEQ: 1337 case ISD::SETOEQ: CondCode = ARMCC::EQ; break; 1338 case ISD::SETGT: 1339 case ISD::SETOGT: CondCode = ARMCC::GT; break; 1340 case ISD::SETGE: 1341 case ISD::SETOGE: CondCode = ARMCC::GE; break; 1342 case ISD::SETOLT: CondCode = ARMCC::MI; break; 1343 case ISD::SETOLE: CondCode = ARMCC::LS; break; 1344 case ISD::SETONE: CondCode = ARMCC::MI; CondCode2 = ARMCC::GT; break; 1345 case ISD::SETO: CondCode = ARMCC::VC; break; 1346 case ISD::SETUO: CondCode = ARMCC::VS; break; 1347 case ISD::SETUEQ: CondCode = ARMCC::EQ; CondCode2 = ARMCC::VS; break; 1348 case ISD::SETUGT: CondCode = ARMCC::HI; break; 1349 case ISD::SETUGE: CondCode = ARMCC::PL; break; 1350 case ISD::SETLT: 1351 case ISD::SETULT: CondCode = ARMCC::LT; break; 1352 case ISD::SETLE: 1353 case ISD::SETULE: CondCode = ARMCC::LE; break; 1354 case ISD::SETNE: 1355 case ISD::SETUNE: CondCode = ARMCC::NE; break; 1356 } 1357 } 1358 1359 //===----------------------------------------------------------------------===// 1360 // Calling Convention Implementation 1361 //===----------------------------------------------------------------------===// 1362 1363 #include "ARMGenCallingConv.inc" 1364 1365 /// getEffectiveCallingConv - Get the effective calling convention, taking into 1366 /// account presence of floating point hardware and calling convention 1367 /// limitations, such as support for variadic functions. 1368 CallingConv::ID 1369 ARMTargetLowering::getEffectiveCallingConv(CallingConv::ID CC, 1370 bool isVarArg) const { 1371 switch (CC) { 1372 default: 1373 llvm_unreachable("Unsupported calling convention"); 1374 case CallingConv::ARM_AAPCS: 1375 case CallingConv::ARM_APCS: 1376 case CallingConv::GHC: 1377 return CC; 1378 case CallingConv::ARM_AAPCS_VFP: 1379 return isVarArg ? CallingConv::ARM_AAPCS : CallingConv::ARM_AAPCS_VFP; 1380 case CallingConv::C: 1381 if (!Subtarget->isAAPCS_ABI()) 1382 return CallingConv::ARM_APCS; 1383 else if (Subtarget->hasVFP2() && !Subtarget->isThumb1Only() && 1384 getTargetMachine().Options.FloatABIType == FloatABI::Hard && 1385 !isVarArg) 1386 return CallingConv::ARM_AAPCS_VFP; 1387 else 1388 return CallingConv::ARM_AAPCS; 1389 case CallingConv::Fast: 1390 case CallingConv::CXX_FAST_TLS: 1391 if (!Subtarget->isAAPCS_ABI()) { 1392 if (Subtarget->hasVFP2() && !Subtarget->isThumb1Only() && !isVarArg) 1393 return CallingConv::Fast; 1394 return CallingConv::ARM_APCS; 1395 } else if (Subtarget->hasVFP2() && !Subtarget->isThumb1Only() && !isVarArg) 1396 return CallingConv::ARM_AAPCS_VFP; 1397 else 1398 return CallingConv::ARM_AAPCS; 1399 } 1400 } 1401 1402 /// CCAssignFnForNode - Selects the correct CCAssignFn for the given 1403 /// CallingConvention. 1404 CCAssignFn *ARMTargetLowering::CCAssignFnForNode(CallingConv::ID CC, 1405 bool Return, 1406 bool isVarArg) const { 1407 switch (getEffectiveCallingConv(CC, isVarArg)) { 1408 default: 1409 llvm_unreachable("Unsupported calling convention"); 1410 case CallingConv::ARM_APCS: 1411 return (Return ? RetCC_ARM_APCS : CC_ARM_APCS); 1412 case CallingConv::ARM_AAPCS: 1413 return (Return ? RetCC_ARM_AAPCS : CC_ARM_AAPCS); 1414 case CallingConv::ARM_AAPCS_VFP: 1415 return (Return ? RetCC_ARM_AAPCS_VFP : CC_ARM_AAPCS_VFP); 1416 case CallingConv::Fast: 1417 return (Return ? RetFastCC_ARM_APCS : FastCC_ARM_APCS); 1418 case CallingConv::GHC: 1419 return (Return ? RetCC_ARM_APCS : CC_ARM_APCS_GHC); 1420 } 1421 } 1422 1423 /// LowerCallResult - Lower the result values of a call into the 1424 /// appropriate copies out of appropriate physical registers. 1425 SDValue 1426 ARMTargetLowering::LowerCallResult(SDValue Chain, SDValue InFlag, 1427 CallingConv::ID CallConv, bool isVarArg, 1428 const SmallVectorImpl<ISD::InputArg> &Ins, 1429 SDLoc dl, SelectionDAG &DAG, 1430 SmallVectorImpl<SDValue> &InVals, 1431 bool isThisReturn, SDValue ThisVal) const { 1432 1433 // Assign locations to each value returned by this call. 1434 SmallVector<CCValAssign, 16> RVLocs; 1435 ARMCCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs, 1436 *DAG.getContext(), Call); 1437 CCInfo.AnalyzeCallResult(Ins, 1438 CCAssignFnForNode(CallConv, /* Return*/ true, 1439 isVarArg)); 1440 1441 // Copy all of the result registers out of their specified physreg. 1442 for (unsigned i = 0; i != RVLocs.size(); ++i) { 1443 CCValAssign VA = RVLocs[i]; 1444 1445 // Pass 'this' value directly from the argument to return value, to avoid 1446 // reg unit interference 1447 if (i == 0 && isThisReturn) { 1448 assert(!VA.needsCustom() && VA.getLocVT() == MVT::i32 && 1449 "unexpected return calling convention register assignment"); 1450 InVals.push_back(ThisVal); 1451 continue; 1452 } 1453 1454 SDValue Val; 1455 if (VA.needsCustom()) { 1456 // Handle f64 or half of a v2f64. 1457 SDValue Lo = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32, 1458 InFlag); 1459 Chain = Lo.getValue(1); 1460 InFlag = Lo.getValue(2); 1461 VA = RVLocs[++i]; // skip ahead to next loc 1462 SDValue Hi = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32, 1463 InFlag); 1464 Chain = Hi.getValue(1); 1465 InFlag = Hi.getValue(2); 1466 if (!Subtarget->isLittle()) 1467 std::swap (Lo, Hi); 1468 Val = DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi); 1469 1470 if (VA.getLocVT() == MVT::v2f64) { 1471 SDValue Vec = DAG.getNode(ISD::UNDEF, dl, MVT::v2f64); 1472 Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Vec, Val, 1473 DAG.getConstant(0, dl, MVT::i32)); 1474 1475 VA = RVLocs[++i]; // skip ahead to next loc 1476 Lo = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32, InFlag); 1477 Chain = Lo.getValue(1); 1478 InFlag = Lo.getValue(2); 1479 VA = RVLocs[++i]; // skip ahead to next loc 1480 Hi = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32, InFlag); 1481 Chain = Hi.getValue(1); 1482 InFlag = Hi.getValue(2); 1483 if (!Subtarget->isLittle()) 1484 std::swap (Lo, Hi); 1485 Val = DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi); 1486 Val = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Vec, Val, 1487 DAG.getConstant(1, dl, MVT::i32)); 1488 } 1489 } else { 1490 Val = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), VA.getLocVT(), 1491 InFlag); 1492 Chain = Val.getValue(1); 1493 InFlag = Val.getValue(2); 1494 } 1495 1496 switch (VA.getLocInfo()) { 1497 default: llvm_unreachable("Unknown loc info!"); 1498 case CCValAssign::Full: break; 1499 case CCValAssign::BCvt: 1500 Val = DAG.getNode(ISD::BITCAST, dl, VA.getValVT(), Val); 1501 break; 1502 } 1503 1504 InVals.push_back(Val); 1505 } 1506 1507 return Chain; 1508 } 1509 1510 /// LowerMemOpCallTo - Store the argument to the stack. 1511 SDValue 1512 ARMTargetLowering::LowerMemOpCallTo(SDValue Chain, 1513 SDValue StackPtr, SDValue Arg, 1514 SDLoc dl, SelectionDAG &DAG, 1515 const CCValAssign &VA, 1516 ISD::ArgFlagsTy Flags) const { 1517 unsigned LocMemOffset = VA.getLocMemOffset(); 1518 SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset, dl); 1519 PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(DAG.getDataLayout()), 1520 StackPtr, PtrOff); 1521 return DAG.getStore( 1522 Chain, dl, Arg, PtrOff, 1523 MachinePointerInfo::getStack(DAG.getMachineFunction(), LocMemOffset), 1524 false, false, 0); 1525 } 1526 1527 void ARMTargetLowering::PassF64ArgInRegs(SDLoc dl, SelectionDAG &DAG, 1528 SDValue Chain, SDValue &Arg, 1529 RegsToPassVector &RegsToPass, 1530 CCValAssign &VA, CCValAssign &NextVA, 1531 SDValue &StackPtr, 1532 SmallVectorImpl<SDValue> &MemOpChains, 1533 ISD::ArgFlagsTy Flags) const { 1534 1535 SDValue fmrrd = DAG.getNode(ARMISD::VMOVRRD, dl, 1536 DAG.getVTList(MVT::i32, MVT::i32), Arg); 1537 unsigned id = Subtarget->isLittle() ? 0 : 1; 1538 RegsToPass.push_back(std::make_pair(VA.getLocReg(), fmrrd.getValue(id))); 1539 1540 if (NextVA.isRegLoc()) 1541 RegsToPass.push_back(std::make_pair(NextVA.getLocReg(), fmrrd.getValue(1-id))); 1542 else { 1543 assert(NextVA.isMemLoc()); 1544 if (!StackPtr.getNode()) 1545 StackPtr = DAG.getCopyFromReg(Chain, dl, ARM::SP, 1546 getPointerTy(DAG.getDataLayout())); 1547 1548 MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, fmrrd.getValue(1-id), 1549 dl, DAG, NextVA, 1550 Flags)); 1551 } 1552 } 1553 1554 /// LowerCall - Lowering a call into a callseq_start <- 1555 /// ARMISD:CALL <- callseq_end chain. Also add input and output parameter 1556 /// nodes. 1557 SDValue 1558 ARMTargetLowering::LowerCall(TargetLowering::CallLoweringInfo &CLI, 1559 SmallVectorImpl<SDValue> &InVals) const { 1560 SelectionDAG &DAG = CLI.DAG; 1561 SDLoc &dl = CLI.DL; 1562 SmallVectorImpl<ISD::OutputArg> &Outs = CLI.Outs; 1563 SmallVectorImpl<SDValue> &OutVals = CLI.OutVals; 1564 SmallVectorImpl<ISD::InputArg> &Ins = CLI.Ins; 1565 SDValue Chain = CLI.Chain; 1566 SDValue Callee = CLI.Callee; 1567 bool &isTailCall = CLI.IsTailCall; 1568 CallingConv::ID CallConv = CLI.CallConv; 1569 bool doesNotRet = CLI.DoesNotReturn; 1570 bool isVarArg = CLI.IsVarArg; 1571 1572 MachineFunction &MF = DAG.getMachineFunction(); 1573 bool isStructRet = (Outs.empty()) ? false : Outs[0].Flags.isSRet(); 1574 bool isThisReturn = false; 1575 bool isSibCall = false; 1576 auto Attr = MF.getFunction()->getFnAttribute("disable-tail-calls"); 1577 1578 // Disable tail calls if they're not supported. 1579 if (!Subtarget->supportsTailCall() || Attr.getValueAsString() == "true") 1580 isTailCall = false; 1581 1582 if (isTailCall) { 1583 // Check if it's really possible to do a tail call. 1584 isTailCall = IsEligibleForTailCallOptimization(Callee, CallConv, 1585 isVarArg, isStructRet, MF.getFunction()->hasStructRetAttr(), 1586 Outs, OutVals, Ins, DAG); 1587 if (!isTailCall && CLI.CS && CLI.CS->isMustTailCall()) 1588 report_fatal_error("failed to perform tail call elimination on a call " 1589 "site marked musttail"); 1590 // We don't support GuaranteedTailCallOpt for ARM, only automatically 1591 // detected sibcalls. 1592 if (isTailCall) { 1593 ++NumTailCalls; 1594 isSibCall = true; 1595 } 1596 } 1597 1598 // Analyze operands of the call, assigning locations to each operand. 1599 SmallVector<CCValAssign, 16> ArgLocs; 1600 ARMCCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), ArgLocs, 1601 *DAG.getContext(), Call); 1602 CCInfo.AnalyzeCallOperands(Outs, 1603 CCAssignFnForNode(CallConv, /* Return*/ false, 1604 isVarArg)); 1605 1606 // Get a count of how many bytes are to be pushed on the stack. 1607 unsigned NumBytes = CCInfo.getNextStackOffset(); 1608 1609 // For tail calls, memory operands are available in our caller's stack. 1610 if (isSibCall) 1611 NumBytes = 0; 1612 1613 // Adjust the stack pointer for the new arguments... 1614 // These operations are automatically eliminated by the prolog/epilog pass 1615 if (!isSibCall) 1616 Chain = DAG.getCALLSEQ_START(Chain, 1617 DAG.getIntPtrConstant(NumBytes, dl, true), dl); 1618 1619 SDValue StackPtr = 1620 DAG.getCopyFromReg(Chain, dl, ARM::SP, getPointerTy(DAG.getDataLayout())); 1621 1622 RegsToPassVector RegsToPass; 1623 SmallVector<SDValue, 8> MemOpChains; 1624 1625 // Walk the register/memloc assignments, inserting copies/loads. In the case 1626 // of tail call optimization, arguments are handled later. 1627 for (unsigned i = 0, realArgIdx = 0, e = ArgLocs.size(); 1628 i != e; 1629 ++i, ++realArgIdx) { 1630 CCValAssign &VA = ArgLocs[i]; 1631 SDValue Arg = OutVals[realArgIdx]; 1632 ISD::ArgFlagsTy Flags = Outs[realArgIdx].Flags; 1633 bool isByVal = Flags.isByVal(); 1634 1635 // Promote the value if needed. 1636 switch (VA.getLocInfo()) { 1637 default: llvm_unreachable("Unknown loc info!"); 1638 case CCValAssign::Full: break; 1639 case CCValAssign::SExt: 1640 Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), Arg); 1641 break; 1642 case CCValAssign::ZExt: 1643 Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, VA.getLocVT(), Arg); 1644 break; 1645 case CCValAssign::AExt: 1646 Arg = DAG.getNode(ISD::ANY_EXTEND, dl, VA.getLocVT(), Arg); 1647 break; 1648 case CCValAssign::BCvt: 1649 Arg = DAG.getNode(ISD::BITCAST, dl, VA.getLocVT(), Arg); 1650 break; 1651 } 1652 1653 // f64 and v2f64 might be passed in i32 pairs and must be split into pieces 1654 if (VA.needsCustom()) { 1655 if (VA.getLocVT() == MVT::v2f64) { 1656 SDValue Op0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg, 1657 DAG.getConstant(0, dl, MVT::i32)); 1658 SDValue Op1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg, 1659 DAG.getConstant(1, dl, MVT::i32)); 1660 1661 PassF64ArgInRegs(dl, DAG, Chain, Op0, RegsToPass, 1662 VA, ArgLocs[++i], StackPtr, MemOpChains, Flags); 1663 1664 VA = ArgLocs[++i]; // skip ahead to next loc 1665 if (VA.isRegLoc()) { 1666 PassF64ArgInRegs(dl, DAG, Chain, Op1, RegsToPass, 1667 VA, ArgLocs[++i], StackPtr, MemOpChains, Flags); 1668 } else { 1669 assert(VA.isMemLoc()); 1670 1671 MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, Op1, 1672 dl, DAG, VA, Flags)); 1673 } 1674 } else { 1675 PassF64ArgInRegs(dl, DAG, Chain, Arg, RegsToPass, VA, ArgLocs[++i], 1676 StackPtr, MemOpChains, Flags); 1677 } 1678 } else if (VA.isRegLoc()) { 1679 if (realArgIdx == 0 && Flags.isReturned() && Outs[0].VT == MVT::i32) { 1680 assert(VA.getLocVT() == MVT::i32 && 1681 "unexpected calling convention register assignment"); 1682 assert(!Ins.empty() && Ins[0].VT == MVT::i32 && 1683 "unexpected use of 'returned'"); 1684 isThisReturn = true; 1685 } 1686 RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg)); 1687 } else if (isByVal) { 1688 assert(VA.isMemLoc()); 1689 unsigned offset = 0; 1690 1691 // True if this byval aggregate will be split between registers 1692 // and memory. 1693 unsigned ByValArgsCount = CCInfo.getInRegsParamsCount(); 1694 unsigned CurByValIdx = CCInfo.getInRegsParamsProcessed(); 1695 1696 if (CurByValIdx < ByValArgsCount) { 1697 1698 unsigned RegBegin, RegEnd; 1699 CCInfo.getInRegsParamInfo(CurByValIdx, RegBegin, RegEnd); 1700 1701 EVT PtrVT = 1702 DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout()); 1703 unsigned int i, j; 1704 for (i = 0, j = RegBegin; j < RegEnd; i++, j++) { 1705 SDValue Const = DAG.getConstant(4*i, dl, MVT::i32); 1706 SDValue AddArg = DAG.getNode(ISD::ADD, dl, PtrVT, Arg, Const); 1707 SDValue Load = DAG.getLoad(PtrVT, dl, Chain, AddArg, 1708 MachinePointerInfo(), 1709 false, false, false, 1710 DAG.InferPtrAlignment(AddArg)); 1711 MemOpChains.push_back(Load.getValue(1)); 1712 RegsToPass.push_back(std::make_pair(j, Load)); 1713 } 1714 1715 // If parameter size outsides register area, "offset" value 1716 // helps us to calculate stack slot for remained part properly. 1717 offset = RegEnd - RegBegin; 1718 1719 CCInfo.nextInRegsParam(); 1720 } 1721 1722 if (Flags.getByValSize() > 4*offset) { 1723 auto PtrVT = getPointerTy(DAG.getDataLayout()); 1724 unsigned LocMemOffset = VA.getLocMemOffset(); 1725 SDValue StkPtrOff = DAG.getIntPtrConstant(LocMemOffset, dl); 1726 SDValue Dst = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, StkPtrOff); 1727 SDValue SrcOffset = DAG.getIntPtrConstant(4*offset, dl); 1728 SDValue Src = DAG.getNode(ISD::ADD, dl, PtrVT, Arg, SrcOffset); 1729 SDValue SizeNode = DAG.getConstant(Flags.getByValSize() - 4*offset, dl, 1730 MVT::i32); 1731 SDValue AlignNode = DAG.getConstant(Flags.getByValAlign(), dl, 1732 MVT::i32); 1733 1734 SDVTList VTs = DAG.getVTList(MVT::Other, MVT::Glue); 1735 SDValue Ops[] = { Chain, Dst, Src, SizeNode, AlignNode}; 1736 MemOpChains.push_back(DAG.getNode(ARMISD::COPY_STRUCT_BYVAL, dl, VTs, 1737 Ops)); 1738 } 1739 } else if (!isSibCall) { 1740 assert(VA.isMemLoc()); 1741 1742 MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, Arg, 1743 dl, DAG, VA, Flags)); 1744 } 1745 } 1746 1747 if (!MemOpChains.empty()) 1748 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains); 1749 1750 // Build a sequence of copy-to-reg nodes chained together with token chain 1751 // and flag operands which copy the outgoing args into the appropriate regs. 1752 SDValue InFlag; 1753 // Tail call byval lowering might overwrite argument registers so in case of 1754 // tail call optimization the copies to registers are lowered later. 1755 if (!isTailCall) 1756 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) { 1757 Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first, 1758 RegsToPass[i].second, InFlag); 1759 InFlag = Chain.getValue(1); 1760 } 1761 1762 // For tail calls lower the arguments to the 'real' stack slot. 1763 if (isTailCall) { 1764 // Force all the incoming stack arguments to be loaded from the stack 1765 // before any new outgoing arguments are stored to the stack, because the 1766 // outgoing stack slots may alias the incoming argument stack slots, and 1767 // the alias isn't otherwise explicit. This is slightly more conservative 1768 // than necessary, because it means that each store effectively depends 1769 // on every argument instead of just those arguments it would clobber. 1770 1771 // Do not flag preceding copytoreg stuff together with the following stuff. 1772 InFlag = SDValue(); 1773 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) { 1774 Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first, 1775 RegsToPass[i].second, InFlag); 1776 InFlag = Chain.getValue(1); 1777 } 1778 InFlag = SDValue(); 1779 } 1780 1781 // If the callee is a GlobalAddress/ExternalSymbol node (quite common, every 1782 // direct call is) turn it into a TargetGlobalAddress/TargetExternalSymbol 1783 // node so that legalize doesn't hack it. 1784 bool isDirect = false; 1785 bool isARMFunc = false; 1786 bool isLocalARMFunc = false; 1787 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>(); 1788 auto PtrVt = getPointerTy(DAG.getDataLayout()); 1789 1790 if (Subtarget->genLongCalls()) { 1791 assert((Subtarget->isTargetWindows() || 1792 getTargetMachine().getRelocationModel() == Reloc::Static) && 1793 "long-calls with non-static relocation model!"); 1794 // Handle a global address or an external symbol. If it's not one of 1795 // those, the target's already in a register, so we don't need to do 1796 // anything extra. 1797 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) { 1798 const GlobalValue *GV = G->getGlobal(); 1799 // Create a constant pool entry for the callee address 1800 unsigned ARMPCLabelIndex = AFI->createPICLabelUId(); 1801 ARMConstantPoolValue *CPV = 1802 ARMConstantPoolConstant::Create(GV, ARMPCLabelIndex, ARMCP::CPValue, 0); 1803 1804 // Get the address of the callee into a register 1805 SDValue CPAddr = DAG.getTargetConstantPool(CPV, PtrVt, 4); 1806 CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr); 1807 Callee = DAG.getLoad( 1808 PtrVt, dl, DAG.getEntryNode(), CPAddr, 1809 MachinePointerInfo::getConstantPool(DAG.getMachineFunction()), false, 1810 false, false, 0); 1811 } else if (ExternalSymbolSDNode *S=dyn_cast<ExternalSymbolSDNode>(Callee)) { 1812 const char *Sym = S->getSymbol(); 1813 1814 // Create a constant pool entry for the callee address 1815 unsigned ARMPCLabelIndex = AFI->createPICLabelUId(); 1816 ARMConstantPoolValue *CPV = 1817 ARMConstantPoolSymbol::Create(*DAG.getContext(), Sym, 1818 ARMPCLabelIndex, 0); 1819 // Get the address of the callee into a register 1820 SDValue CPAddr = DAG.getTargetConstantPool(CPV, PtrVt, 4); 1821 CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr); 1822 Callee = DAG.getLoad( 1823 PtrVt, dl, DAG.getEntryNode(), CPAddr, 1824 MachinePointerInfo::getConstantPool(DAG.getMachineFunction()), false, 1825 false, false, 0); 1826 } 1827 } else if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) { 1828 const GlobalValue *GV = G->getGlobal(); 1829 isDirect = true; 1830 bool isDef = GV->isStrongDefinitionForLinker(); 1831 bool isStub = (!isDef && Subtarget->isTargetMachO()) && 1832 getTargetMachine().getRelocationModel() != Reloc::Static; 1833 isARMFunc = !Subtarget->isThumb() || (isStub && !Subtarget->isMClass()); 1834 // ARM call to a local ARM function is predicable. 1835 isLocalARMFunc = !Subtarget->isThumb() && (isDef || !ARMInterworking); 1836 // tBX takes a register source operand. 1837 if (isStub && Subtarget->isThumb1Only() && !Subtarget->hasV5TOps()) { 1838 assert(Subtarget->isTargetMachO() && "WrapperPIC use on non-MachO?"); 1839 Callee = DAG.getNode( 1840 ARMISD::WrapperPIC, dl, PtrVt, 1841 DAG.getTargetGlobalAddress(GV, dl, PtrVt, 0, ARMII::MO_NONLAZY)); 1842 Callee = DAG.getLoad(PtrVt, dl, DAG.getEntryNode(), Callee, 1843 MachinePointerInfo::getGOT(DAG.getMachineFunction()), 1844 false, false, true, 0); 1845 } else if (Subtarget->isTargetCOFF()) { 1846 assert(Subtarget->isTargetWindows() && 1847 "Windows is the only supported COFF target"); 1848 unsigned TargetFlags = GV->hasDLLImportStorageClass() 1849 ? ARMII::MO_DLLIMPORT 1850 : ARMII::MO_NO_FLAG; 1851 Callee = 1852 DAG.getTargetGlobalAddress(GV, dl, PtrVt, /*Offset=*/0, TargetFlags); 1853 if (GV->hasDLLImportStorageClass()) 1854 Callee = 1855 DAG.getLoad(PtrVt, dl, DAG.getEntryNode(), 1856 DAG.getNode(ARMISD::Wrapper, dl, PtrVt, Callee), 1857 MachinePointerInfo::getGOT(DAG.getMachineFunction()), 1858 false, false, false, 0); 1859 } else { 1860 // On ELF targets for PIC code, direct calls should go through the PLT 1861 unsigned OpFlags = 0; 1862 if (Subtarget->isTargetELF() && 1863 getTargetMachine().getRelocationModel() == Reloc::PIC_) 1864 OpFlags = ARMII::MO_PLT; 1865 Callee = DAG.getTargetGlobalAddress(GV, dl, PtrVt, 0, OpFlags); 1866 } 1867 } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) { 1868 isDirect = true; 1869 bool isStub = Subtarget->isTargetMachO() && 1870 getTargetMachine().getRelocationModel() != Reloc::Static; 1871 isARMFunc = !Subtarget->isThumb() || (isStub && !Subtarget->isMClass()); 1872 // tBX takes a register source operand. 1873 const char *Sym = S->getSymbol(); 1874 if (isARMFunc && Subtarget->isThumb1Only() && !Subtarget->hasV5TOps()) { 1875 unsigned ARMPCLabelIndex = AFI->createPICLabelUId(); 1876 ARMConstantPoolValue *CPV = 1877 ARMConstantPoolSymbol::Create(*DAG.getContext(), Sym, 1878 ARMPCLabelIndex, 4); 1879 SDValue CPAddr = DAG.getTargetConstantPool(CPV, PtrVt, 4); 1880 CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr); 1881 Callee = DAG.getLoad( 1882 PtrVt, dl, DAG.getEntryNode(), CPAddr, 1883 MachinePointerInfo::getConstantPool(DAG.getMachineFunction()), false, 1884 false, false, 0); 1885 SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, dl, MVT::i32); 1886 Callee = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVt, Callee, PICLabel); 1887 } else { 1888 unsigned OpFlags = 0; 1889 // On ELF targets for PIC code, direct calls should go through the PLT 1890 if (Subtarget->isTargetELF() && 1891 getTargetMachine().getRelocationModel() == Reloc::PIC_) 1892 OpFlags = ARMII::MO_PLT; 1893 Callee = DAG.getTargetExternalSymbol(Sym, PtrVt, OpFlags); 1894 } 1895 } 1896 1897 // FIXME: handle tail calls differently. 1898 unsigned CallOpc; 1899 if (Subtarget->isThumb()) { 1900 if ((!isDirect || isARMFunc) && !Subtarget->hasV5TOps()) 1901 CallOpc = ARMISD::CALL_NOLINK; 1902 else 1903 CallOpc = isARMFunc ? ARMISD::CALL : ARMISD::tCALL; 1904 } else { 1905 if (!isDirect && !Subtarget->hasV5TOps()) 1906 CallOpc = ARMISD::CALL_NOLINK; 1907 else if (doesNotRet && isDirect && Subtarget->hasRAS() && 1908 // Emit regular call when code size is the priority 1909 !MF.getFunction()->optForMinSize()) 1910 // "mov lr, pc; b _foo" to avoid confusing the RSP 1911 CallOpc = ARMISD::CALL_NOLINK; 1912 else 1913 CallOpc = isLocalARMFunc ? ARMISD::CALL_PRED : ARMISD::CALL; 1914 } 1915 1916 std::vector<SDValue> Ops; 1917 Ops.push_back(Chain); 1918 Ops.push_back(Callee); 1919 1920 // Add argument registers to the end of the list so that they are known live 1921 // into the call. 1922 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) 1923 Ops.push_back(DAG.getRegister(RegsToPass[i].first, 1924 RegsToPass[i].second.getValueType())); 1925 1926 // Add a register mask operand representing the call-preserved registers. 1927 if (!isTailCall) { 1928 const uint32_t *Mask; 1929 const ARMBaseRegisterInfo *ARI = Subtarget->getRegisterInfo(); 1930 if (isThisReturn) { 1931 // For 'this' returns, use the R0-preserving mask if applicable 1932 Mask = ARI->getThisReturnPreservedMask(MF, CallConv); 1933 if (!Mask) { 1934 // Set isThisReturn to false if the calling convention is not one that 1935 // allows 'returned' to be modeled in this way, so LowerCallResult does 1936 // not try to pass 'this' straight through 1937 isThisReturn = false; 1938 Mask = ARI->getCallPreservedMask(MF, CallConv); 1939 } 1940 } else 1941 Mask = ARI->getCallPreservedMask(MF, CallConv); 1942 1943 assert(Mask && "Missing call preserved mask for calling convention"); 1944 Ops.push_back(DAG.getRegisterMask(Mask)); 1945 } 1946 1947 if (InFlag.getNode()) 1948 Ops.push_back(InFlag); 1949 1950 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue); 1951 if (isTailCall) { 1952 MF.getFrameInfo()->setHasTailCall(); 1953 return DAG.getNode(ARMISD::TC_RETURN, dl, NodeTys, Ops); 1954 } 1955 1956 // Returns a chain and a flag for retval copy to use. 1957 Chain = DAG.getNode(CallOpc, dl, NodeTys, Ops); 1958 InFlag = Chain.getValue(1); 1959 1960 Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, dl, true), 1961 DAG.getIntPtrConstant(0, dl, true), InFlag, dl); 1962 if (!Ins.empty()) 1963 InFlag = Chain.getValue(1); 1964 1965 // Handle result values, copying them out of physregs into vregs that we 1966 // return. 1967 return LowerCallResult(Chain, InFlag, CallConv, isVarArg, Ins, dl, DAG, 1968 InVals, isThisReturn, 1969 isThisReturn ? OutVals[0] : SDValue()); 1970 } 1971 1972 /// HandleByVal - Every parameter *after* a byval parameter is passed 1973 /// on the stack. Remember the next parameter register to allocate, 1974 /// and then confiscate the rest of the parameter registers to insure 1975 /// this. 1976 void ARMTargetLowering::HandleByVal(CCState *State, unsigned &Size, 1977 unsigned Align) const { 1978 assert((State->getCallOrPrologue() == Prologue || 1979 State->getCallOrPrologue() == Call) && 1980 "unhandled ParmContext"); 1981 1982 // Byval (as with any stack) slots are always at least 4 byte aligned. 1983 Align = std::max(Align, 4U); 1984 1985 unsigned Reg = State->AllocateReg(GPRArgRegs); 1986 if (!Reg) 1987 return; 1988 1989 unsigned AlignInRegs = Align / 4; 1990 unsigned Waste = (ARM::R4 - Reg) % AlignInRegs; 1991 for (unsigned i = 0; i < Waste; ++i) 1992 Reg = State->AllocateReg(GPRArgRegs); 1993 1994 if (!Reg) 1995 return; 1996 1997 unsigned Excess = 4 * (ARM::R4 - Reg); 1998 1999 // Special case when NSAA != SP and parameter size greater than size of 2000 // all remained GPR regs. In that case we can't split parameter, we must 2001 // send it to stack. We also must set NCRN to R4, so waste all 2002 // remained registers. 2003 const unsigned NSAAOffset = State->getNextStackOffset(); 2004 if (NSAAOffset != 0 && Size > Excess) { 2005 while (State->AllocateReg(GPRArgRegs)) 2006 ; 2007 return; 2008 } 2009 2010 // First register for byval parameter is the first register that wasn't 2011 // allocated before this method call, so it would be "reg". 2012 // If parameter is small enough to be saved in range [reg, r4), then 2013 // the end (first after last) register would be reg + param-size-in-regs, 2014 // else parameter would be splitted between registers and stack, 2015 // end register would be r4 in this case. 2016 unsigned ByValRegBegin = Reg; 2017 unsigned ByValRegEnd = std::min<unsigned>(Reg + Size / 4, ARM::R4); 2018 State->addInRegsParamInfo(ByValRegBegin, ByValRegEnd); 2019 // Note, first register is allocated in the beginning of function already, 2020 // allocate remained amount of registers we need. 2021 for (unsigned i = Reg + 1; i != ByValRegEnd; ++i) 2022 State->AllocateReg(GPRArgRegs); 2023 // A byval parameter that is split between registers and memory needs its 2024 // size truncated here. 2025 // In the case where the entire structure fits in registers, we set the 2026 // size in memory to zero. 2027 Size = std::max<int>(Size - Excess, 0); 2028 } 2029 2030 /// MatchingStackOffset - Return true if the given stack call argument is 2031 /// already available in the same position (relatively) of the caller's 2032 /// incoming argument stack. 2033 static 2034 bool MatchingStackOffset(SDValue Arg, unsigned Offset, ISD::ArgFlagsTy Flags, 2035 MachineFrameInfo *MFI, const MachineRegisterInfo *MRI, 2036 const TargetInstrInfo *TII) { 2037 unsigned Bytes = Arg.getValueType().getSizeInBits() / 8; 2038 int FI = INT_MAX; 2039 if (Arg.getOpcode() == ISD::CopyFromReg) { 2040 unsigned VR = cast<RegisterSDNode>(Arg.getOperand(1))->getReg(); 2041 if (!TargetRegisterInfo::isVirtualRegister(VR)) 2042 return false; 2043 MachineInstr *Def = MRI->getVRegDef(VR); 2044 if (!Def) 2045 return false; 2046 if (!Flags.isByVal()) { 2047 if (!TII->isLoadFromStackSlot(Def, FI)) 2048 return false; 2049 } else { 2050 return false; 2051 } 2052 } else if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Arg)) { 2053 if (Flags.isByVal()) 2054 // ByVal argument is passed in as a pointer but it's now being 2055 // dereferenced. e.g. 2056 // define @foo(%struct.X* %A) { 2057 // tail call @bar(%struct.X* byval %A) 2058 // } 2059 return false; 2060 SDValue Ptr = Ld->getBasePtr(); 2061 FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr); 2062 if (!FINode) 2063 return false; 2064 FI = FINode->getIndex(); 2065 } else 2066 return false; 2067 2068 assert(FI != INT_MAX); 2069 if (!MFI->isFixedObjectIndex(FI)) 2070 return false; 2071 return Offset == MFI->getObjectOffset(FI) && Bytes == MFI->getObjectSize(FI); 2072 } 2073 2074 /// IsEligibleForTailCallOptimization - Check whether the call is eligible 2075 /// for tail call optimization. Targets which want to do tail call 2076 /// optimization should implement this function. 2077 bool 2078 ARMTargetLowering::IsEligibleForTailCallOptimization(SDValue Callee, 2079 CallingConv::ID CalleeCC, 2080 bool isVarArg, 2081 bool isCalleeStructRet, 2082 bool isCallerStructRet, 2083 const SmallVectorImpl<ISD::OutputArg> &Outs, 2084 const SmallVectorImpl<SDValue> &OutVals, 2085 const SmallVectorImpl<ISD::InputArg> &Ins, 2086 SelectionDAG& DAG) const { 2087 const Function *CallerF = DAG.getMachineFunction().getFunction(); 2088 CallingConv::ID CallerCC = CallerF->getCallingConv(); 2089 bool CCMatch = CallerCC == CalleeCC; 2090 2091 assert(Subtarget->supportsTailCall()); 2092 2093 // Look for obvious safe cases to perform tail call optimization that do not 2094 // require ABI changes. This is what gcc calls sibcall. 2095 2096 // Do not sibcall optimize vararg calls unless the call site is not passing 2097 // any arguments. 2098 if (isVarArg && !Outs.empty()) 2099 return false; 2100 2101 // Exception-handling functions need a special set of instructions to indicate 2102 // a return to the hardware. Tail-calling another function would probably 2103 // break this. 2104 if (CallerF->hasFnAttribute("interrupt")) 2105 return false; 2106 2107 // Also avoid sibcall optimization if either caller or callee uses struct 2108 // return semantics. 2109 if (isCalleeStructRet || isCallerStructRet) 2110 return false; 2111 2112 // Externally-defined functions with weak linkage should not be 2113 // tail-called on ARM when the OS does not support dynamic 2114 // pre-emption of symbols, as the AAELF spec requires normal calls 2115 // to undefined weak functions to be replaced with a NOP or jump to the 2116 // next instruction. The behaviour of branch instructions in this 2117 // situation (as used for tail calls) is implementation-defined, so we 2118 // cannot rely on the linker replacing the tail call with a return. 2119 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) { 2120 const GlobalValue *GV = G->getGlobal(); 2121 const Triple &TT = getTargetMachine().getTargetTriple(); 2122 if (GV->hasExternalWeakLinkage() && 2123 (!TT.isOSWindows() || TT.isOSBinFormatELF() || TT.isOSBinFormatMachO())) 2124 return false; 2125 } 2126 2127 // If the calling conventions do not match, then we'd better make sure the 2128 // results are returned in the same way as what the caller expects. 2129 if (!CCMatch) { 2130 SmallVector<CCValAssign, 16> RVLocs1; 2131 ARMCCState CCInfo1(CalleeCC, false, DAG.getMachineFunction(), RVLocs1, 2132 *DAG.getContext(), Call); 2133 CCInfo1.AnalyzeCallResult(Ins, CCAssignFnForNode(CalleeCC, true, isVarArg)); 2134 2135 SmallVector<CCValAssign, 16> RVLocs2; 2136 ARMCCState CCInfo2(CallerCC, false, DAG.getMachineFunction(), RVLocs2, 2137 *DAG.getContext(), Call); 2138 CCInfo2.AnalyzeCallResult(Ins, CCAssignFnForNode(CallerCC, true, isVarArg)); 2139 2140 if (RVLocs1.size() != RVLocs2.size()) 2141 return false; 2142 for (unsigned i = 0, e = RVLocs1.size(); i != e; ++i) { 2143 if (RVLocs1[i].isRegLoc() != RVLocs2[i].isRegLoc()) 2144 return false; 2145 if (RVLocs1[i].getLocInfo() != RVLocs2[i].getLocInfo()) 2146 return false; 2147 if (RVLocs1[i].isRegLoc()) { 2148 if (RVLocs1[i].getLocReg() != RVLocs2[i].getLocReg()) 2149 return false; 2150 } else { 2151 if (RVLocs1[i].getLocMemOffset() != RVLocs2[i].getLocMemOffset()) 2152 return false; 2153 } 2154 } 2155 } 2156 2157 // If Caller's vararg or byval argument has been split between registers and 2158 // stack, do not perform tail call, since part of the argument is in caller's 2159 // local frame. 2160 const ARMFunctionInfo *AFI_Caller = DAG.getMachineFunction(). 2161 getInfo<ARMFunctionInfo>(); 2162 if (AFI_Caller->getArgRegsSaveSize()) 2163 return false; 2164 2165 // If the callee takes no arguments then go on to check the results of the 2166 // call. 2167 if (!Outs.empty()) { 2168 // Check if stack adjustment is needed. For now, do not do this if any 2169 // argument is passed on the stack. 2170 SmallVector<CCValAssign, 16> ArgLocs; 2171 ARMCCState CCInfo(CalleeCC, isVarArg, DAG.getMachineFunction(), ArgLocs, 2172 *DAG.getContext(), Call); 2173 CCInfo.AnalyzeCallOperands(Outs, 2174 CCAssignFnForNode(CalleeCC, false, isVarArg)); 2175 if (CCInfo.getNextStackOffset()) { 2176 MachineFunction &MF = DAG.getMachineFunction(); 2177 2178 // Check if the arguments are already laid out in the right way as 2179 // the caller's fixed stack objects. 2180 MachineFrameInfo *MFI = MF.getFrameInfo(); 2181 const MachineRegisterInfo *MRI = &MF.getRegInfo(); 2182 const TargetInstrInfo *TII = Subtarget->getInstrInfo(); 2183 for (unsigned i = 0, realArgIdx = 0, e = ArgLocs.size(); 2184 i != e; 2185 ++i, ++realArgIdx) { 2186 CCValAssign &VA = ArgLocs[i]; 2187 EVT RegVT = VA.getLocVT(); 2188 SDValue Arg = OutVals[realArgIdx]; 2189 ISD::ArgFlagsTy Flags = Outs[realArgIdx].Flags; 2190 if (VA.getLocInfo() == CCValAssign::Indirect) 2191 return false; 2192 if (VA.needsCustom()) { 2193 // f64 and vector types are split into multiple registers or 2194 // register/stack-slot combinations. The types will not match 2195 // the registers; give up on memory f64 refs until we figure 2196 // out what to do about this. 2197 if (!VA.isRegLoc()) 2198 return false; 2199 if (!ArgLocs[++i].isRegLoc()) 2200 return false; 2201 if (RegVT == MVT::v2f64) { 2202 if (!ArgLocs[++i].isRegLoc()) 2203 return false; 2204 if (!ArgLocs[++i].isRegLoc()) 2205 return false; 2206 } 2207 } else if (!VA.isRegLoc()) { 2208 if (!MatchingStackOffset(Arg, VA.getLocMemOffset(), Flags, 2209 MFI, MRI, TII)) 2210 return false; 2211 } 2212 } 2213 } 2214 } 2215 2216 return true; 2217 } 2218 2219 bool 2220 ARMTargetLowering::CanLowerReturn(CallingConv::ID CallConv, 2221 MachineFunction &MF, bool isVarArg, 2222 const SmallVectorImpl<ISD::OutputArg> &Outs, 2223 LLVMContext &Context) const { 2224 SmallVector<CCValAssign, 16> RVLocs; 2225 CCState CCInfo(CallConv, isVarArg, MF, RVLocs, Context); 2226 return CCInfo.CheckReturn(Outs, CCAssignFnForNode(CallConv, /*Return=*/true, 2227 isVarArg)); 2228 } 2229 2230 static SDValue LowerInterruptReturn(SmallVectorImpl<SDValue> &RetOps, 2231 SDLoc DL, SelectionDAG &DAG) { 2232 const MachineFunction &MF = DAG.getMachineFunction(); 2233 const Function *F = MF.getFunction(); 2234 2235 StringRef IntKind = F->getFnAttribute("interrupt").getValueAsString(); 2236 2237 // See ARM ARM v7 B1.8.3. On exception entry LR is set to a possibly offset 2238 // version of the "preferred return address". These offsets affect the return 2239 // instruction if this is a return from PL1 without hypervisor extensions. 2240 // IRQ/FIQ: +4 "subs pc, lr, #4" 2241 // SWI: 0 "subs pc, lr, #0" 2242 // ABORT: +4 "subs pc, lr, #4" 2243 // UNDEF: +4/+2 "subs pc, lr, #0" 2244 // UNDEF varies depending on where the exception came from ARM or Thumb 2245 // mode. Alongside GCC, we throw our hands up in disgust and pretend it's 0. 2246 2247 int64_t LROffset; 2248 if (IntKind == "" || IntKind == "IRQ" || IntKind == "FIQ" || 2249 IntKind == "ABORT") 2250 LROffset = 4; 2251 else if (IntKind == "SWI" || IntKind == "UNDEF") 2252 LROffset = 0; 2253 else 2254 report_fatal_error("Unsupported interrupt attribute. If present, value " 2255 "must be one of: IRQ, FIQ, SWI, ABORT or UNDEF"); 2256 2257 RetOps.insert(RetOps.begin() + 1, 2258 DAG.getConstant(LROffset, DL, MVT::i32, false)); 2259 2260 return DAG.getNode(ARMISD::INTRET_FLAG, DL, MVT::Other, RetOps); 2261 } 2262 2263 SDValue 2264 ARMTargetLowering::LowerReturn(SDValue Chain, 2265 CallingConv::ID CallConv, bool isVarArg, 2266 const SmallVectorImpl<ISD::OutputArg> &Outs, 2267 const SmallVectorImpl<SDValue> &OutVals, 2268 SDLoc dl, SelectionDAG &DAG) const { 2269 2270 // CCValAssign - represent the assignment of the return value to a location. 2271 SmallVector<CCValAssign, 16> RVLocs; 2272 2273 // CCState - Info about the registers and stack slots. 2274 ARMCCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs, 2275 *DAG.getContext(), Call); 2276 2277 // Analyze outgoing return values. 2278 CCInfo.AnalyzeReturn(Outs, CCAssignFnForNode(CallConv, /* Return */ true, 2279 isVarArg)); 2280 2281 SDValue Flag; 2282 SmallVector<SDValue, 4> RetOps; 2283 RetOps.push_back(Chain); // Operand #0 = Chain (updated below) 2284 bool isLittleEndian = Subtarget->isLittle(); 2285 2286 MachineFunction &MF = DAG.getMachineFunction(); 2287 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>(); 2288 AFI->setReturnRegsCount(RVLocs.size()); 2289 2290 // Copy the result values into the output registers. 2291 for (unsigned i = 0, realRVLocIdx = 0; 2292 i != RVLocs.size(); 2293 ++i, ++realRVLocIdx) { 2294 CCValAssign &VA = RVLocs[i]; 2295 assert(VA.isRegLoc() && "Can only return in registers!"); 2296 2297 SDValue Arg = OutVals[realRVLocIdx]; 2298 2299 switch (VA.getLocInfo()) { 2300 default: llvm_unreachable("Unknown loc info!"); 2301 case CCValAssign::Full: break; 2302 case CCValAssign::BCvt: 2303 Arg = DAG.getNode(ISD::BITCAST, dl, VA.getLocVT(), Arg); 2304 break; 2305 } 2306 2307 if (VA.needsCustom()) { 2308 if (VA.getLocVT() == MVT::v2f64) { 2309 // Extract the first half and return it in two registers. 2310 SDValue Half = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg, 2311 DAG.getConstant(0, dl, MVT::i32)); 2312 SDValue HalfGPRs = DAG.getNode(ARMISD::VMOVRRD, dl, 2313 DAG.getVTList(MVT::i32, MVT::i32), Half); 2314 2315 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), 2316 HalfGPRs.getValue(isLittleEndian ? 0 : 1), 2317 Flag); 2318 Flag = Chain.getValue(1); 2319 RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT())); 2320 VA = RVLocs[++i]; // skip ahead to next loc 2321 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), 2322 HalfGPRs.getValue(isLittleEndian ? 1 : 0), 2323 Flag); 2324 Flag = Chain.getValue(1); 2325 RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT())); 2326 VA = RVLocs[++i]; // skip ahead to next loc 2327 2328 // Extract the 2nd half and fall through to handle it as an f64 value. 2329 Arg = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg, 2330 DAG.getConstant(1, dl, MVT::i32)); 2331 } 2332 // Legalize ret f64 -> ret 2 x i32. We always have fmrrd if f64 is 2333 // available. 2334 SDValue fmrrd = DAG.getNode(ARMISD::VMOVRRD, dl, 2335 DAG.getVTList(MVT::i32, MVT::i32), Arg); 2336 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), 2337 fmrrd.getValue(isLittleEndian ? 0 : 1), 2338 Flag); 2339 Flag = Chain.getValue(1); 2340 RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT())); 2341 VA = RVLocs[++i]; // skip ahead to next loc 2342 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), 2343 fmrrd.getValue(isLittleEndian ? 1 : 0), 2344 Flag); 2345 } else 2346 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), Arg, Flag); 2347 2348 // Guarantee that all emitted copies are 2349 // stuck together, avoiding something bad. 2350 Flag = Chain.getValue(1); 2351 RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT())); 2352 } 2353 const ARMBaseRegisterInfo *TRI = Subtarget->getRegisterInfo(); 2354 const MCPhysReg *I = 2355 TRI->getCalleeSavedRegsViaCopy(&DAG.getMachineFunction()); 2356 if (I) { 2357 for (; *I; ++I) { 2358 if (ARM::GPRRegClass.contains(*I)) 2359 RetOps.push_back(DAG.getRegister(*I, MVT::i32)); 2360 else if (ARM::DPRRegClass.contains(*I)) 2361 RetOps.push_back(DAG.getRegister(*I, MVT::getFloatingPointVT(64))); 2362 else 2363 llvm_unreachable("Unexpected register class in CSRsViaCopy!"); 2364 } 2365 } 2366 2367 // Update chain and glue. 2368 RetOps[0] = Chain; 2369 if (Flag.getNode()) 2370 RetOps.push_back(Flag); 2371 2372 // CPUs which aren't M-class use a special sequence to return from 2373 // exceptions (roughly, any instruction setting pc and cpsr simultaneously, 2374 // though we use "subs pc, lr, #N"). 2375 // 2376 // M-class CPUs actually use a normal return sequence with a special 2377 // (hardware-provided) value in LR, so the normal code path works. 2378 if (DAG.getMachineFunction().getFunction()->hasFnAttribute("interrupt") && 2379 !Subtarget->isMClass()) { 2380 if (Subtarget->isThumb1Only()) 2381 report_fatal_error("interrupt attribute is not supported in Thumb1"); 2382 return LowerInterruptReturn(RetOps, dl, DAG); 2383 } 2384 2385 return DAG.getNode(ARMISD::RET_FLAG, dl, MVT::Other, RetOps); 2386 } 2387 2388 bool ARMTargetLowering::isUsedByReturnOnly(SDNode *N, SDValue &Chain) const { 2389 if (N->getNumValues() != 1) 2390 return false; 2391 if (!N->hasNUsesOfValue(1, 0)) 2392 return false; 2393 2394 SDValue TCChain = Chain; 2395 SDNode *Copy = *N->use_begin(); 2396 if (Copy->getOpcode() == ISD::CopyToReg) { 2397 // If the copy has a glue operand, we conservatively assume it isn't safe to 2398 // perform a tail call. 2399 if (Copy->getOperand(Copy->getNumOperands()-1).getValueType() == MVT::Glue) 2400 return false; 2401 TCChain = Copy->getOperand(0); 2402 } else if (Copy->getOpcode() == ARMISD::VMOVRRD) { 2403 SDNode *VMov = Copy; 2404 // f64 returned in a pair of GPRs. 2405 SmallPtrSet<SDNode*, 2> Copies; 2406 for (SDNode::use_iterator UI = VMov->use_begin(), UE = VMov->use_end(); 2407 UI != UE; ++UI) { 2408 if (UI->getOpcode() != ISD::CopyToReg) 2409 return false; 2410 Copies.insert(*UI); 2411 } 2412 if (Copies.size() > 2) 2413 return false; 2414 2415 for (SDNode::use_iterator UI = VMov->use_begin(), UE = VMov->use_end(); 2416 UI != UE; ++UI) { 2417 SDValue UseChain = UI->getOperand(0); 2418 if (Copies.count(UseChain.getNode())) 2419 // Second CopyToReg 2420 Copy = *UI; 2421 else { 2422 // We are at the top of this chain. 2423 // If the copy has a glue operand, we conservatively assume it 2424 // isn't safe to perform a tail call. 2425 if (UI->getOperand(UI->getNumOperands()-1).getValueType() == MVT::Glue) 2426 return false; 2427 // First CopyToReg 2428 TCChain = UseChain; 2429 } 2430 } 2431 } else if (Copy->getOpcode() == ISD::BITCAST) { 2432 // f32 returned in a single GPR. 2433 if (!Copy->hasOneUse()) 2434 return false; 2435 Copy = *Copy->use_begin(); 2436 if (Copy->getOpcode() != ISD::CopyToReg || !Copy->hasNUsesOfValue(1, 0)) 2437 return false; 2438 // If the copy has a glue operand, we conservatively assume it isn't safe to 2439 // perform a tail call. 2440 if (Copy->getOperand(Copy->getNumOperands()-1).getValueType() == MVT::Glue) 2441 return false; 2442 TCChain = Copy->getOperand(0); 2443 } else { 2444 return false; 2445 } 2446 2447 bool HasRet = false; 2448 for (SDNode::use_iterator UI = Copy->use_begin(), UE = Copy->use_end(); 2449 UI != UE; ++UI) { 2450 if (UI->getOpcode() != ARMISD::RET_FLAG && 2451 UI->getOpcode() != ARMISD::INTRET_FLAG) 2452 return false; 2453 HasRet = true; 2454 } 2455 2456 if (!HasRet) 2457 return false; 2458 2459 Chain = TCChain; 2460 return true; 2461 } 2462 2463 bool ARMTargetLowering::mayBeEmittedAsTailCall(CallInst *CI) const { 2464 if (!Subtarget->supportsTailCall()) 2465 return false; 2466 2467 auto Attr = 2468 CI->getParent()->getParent()->getFnAttribute("disable-tail-calls"); 2469 if (!CI->isTailCall() || Attr.getValueAsString() == "true") 2470 return false; 2471 2472 return true; 2473 } 2474 2475 // Trying to write a 64 bit value so need to split into two 32 bit values first, 2476 // and pass the lower and high parts through. 2477 static SDValue LowerWRITE_REGISTER(SDValue Op, SelectionDAG &DAG) { 2478 SDLoc DL(Op); 2479 SDValue WriteValue = Op->getOperand(2); 2480 2481 // This function is only supposed to be called for i64 type argument. 2482 assert(WriteValue.getValueType() == MVT::i64 2483 && "LowerWRITE_REGISTER called for non-i64 type argument."); 2484 2485 SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, WriteValue, 2486 DAG.getConstant(0, DL, MVT::i32)); 2487 SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, WriteValue, 2488 DAG.getConstant(1, DL, MVT::i32)); 2489 SDValue Ops[] = { Op->getOperand(0), Op->getOperand(1), Lo, Hi }; 2490 return DAG.getNode(ISD::WRITE_REGISTER, DL, MVT::Other, Ops); 2491 } 2492 2493 // ConstantPool, JumpTable, GlobalAddress, and ExternalSymbol are lowered as 2494 // their target counterpart wrapped in the ARMISD::Wrapper node. Suppose N is 2495 // one of the above mentioned nodes. It has to be wrapped because otherwise 2496 // Select(N) returns N. So the raw TargetGlobalAddress nodes, etc. can only 2497 // be used to form addressing mode. These wrapped nodes will be selected 2498 // into MOVi. 2499 static SDValue LowerConstantPool(SDValue Op, SelectionDAG &DAG) { 2500 EVT PtrVT = Op.getValueType(); 2501 // FIXME there is no actual debug info here 2502 SDLoc dl(Op); 2503 ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op); 2504 SDValue Res; 2505 if (CP->isMachineConstantPoolEntry()) 2506 Res = DAG.getTargetConstantPool(CP->getMachineCPVal(), PtrVT, 2507 CP->getAlignment()); 2508 else 2509 Res = DAG.getTargetConstantPool(CP->getConstVal(), PtrVT, 2510 CP->getAlignment()); 2511 return DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Res); 2512 } 2513 2514 unsigned ARMTargetLowering::getJumpTableEncoding() const { 2515 return MachineJumpTableInfo::EK_Inline; 2516 } 2517 2518 SDValue ARMTargetLowering::LowerBlockAddress(SDValue Op, 2519 SelectionDAG &DAG) const { 2520 MachineFunction &MF = DAG.getMachineFunction(); 2521 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>(); 2522 unsigned ARMPCLabelIndex = 0; 2523 SDLoc DL(Op); 2524 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 2525 const BlockAddress *BA = cast<BlockAddressSDNode>(Op)->getBlockAddress(); 2526 Reloc::Model RelocM = getTargetMachine().getRelocationModel(); 2527 SDValue CPAddr; 2528 if (RelocM == Reloc::Static) { 2529 CPAddr = DAG.getTargetConstantPool(BA, PtrVT, 4); 2530 } else { 2531 unsigned PCAdj = Subtarget->isThumb() ? 4 : 8; 2532 ARMPCLabelIndex = AFI->createPICLabelUId(); 2533 ARMConstantPoolValue *CPV = 2534 ARMConstantPoolConstant::Create(BA, ARMPCLabelIndex, 2535 ARMCP::CPBlockAddress, PCAdj); 2536 CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4); 2537 } 2538 CPAddr = DAG.getNode(ARMISD::Wrapper, DL, PtrVT, CPAddr); 2539 SDValue Result = 2540 DAG.getLoad(PtrVT, DL, DAG.getEntryNode(), CPAddr, 2541 MachinePointerInfo::getConstantPool(DAG.getMachineFunction()), 2542 false, false, false, 0); 2543 if (RelocM == Reloc::Static) 2544 return Result; 2545 SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, DL, MVT::i32); 2546 return DAG.getNode(ARMISD::PIC_ADD, DL, PtrVT, Result, PICLabel); 2547 } 2548 2549 /// \brief Convert a TLS address reference into the correct sequence of loads 2550 /// and calls to compute the variable's address for Darwin, and return an 2551 /// SDValue containing the final node. 2552 2553 /// Darwin only has one TLS scheme which must be capable of dealing with the 2554 /// fully general situation, in the worst case. This means: 2555 /// + "extern __thread" declaration. 2556 /// + Defined in a possibly unknown dynamic library. 2557 /// 2558 /// The general system is that each __thread variable has a [3 x i32] descriptor 2559 /// which contains information used by the runtime to calculate the address. The 2560 /// only part of this the compiler needs to know about is the first word, which 2561 /// contains a function pointer that must be called with the address of the 2562 /// entire descriptor in "r0". 2563 /// 2564 /// Since this descriptor may be in a different unit, in general access must 2565 /// proceed along the usual ARM rules. A common sequence to produce is: 2566 /// 2567 /// movw rT1, :lower16:_var$non_lazy_ptr 2568 /// movt rT1, :upper16:_var$non_lazy_ptr 2569 /// ldr r0, [rT1] 2570 /// ldr rT2, [r0] 2571 /// blx rT2 2572 /// [...address now in r0...] 2573 SDValue 2574 ARMTargetLowering::LowerGlobalTLSAddressDarwin(SDValue Op, 2575 SelectionDAG &DAG) const { 2576 assert(Subtarget->isTargetDarwin() && "TLS only supported on Darwin"); 2577 SDLoc DL(Op); 2578 2579 // First step is to get the address of the actua global symbol. This is where 2580 // the TLS descriptor lives. 2581 SDValue DescAddr = LowerGlobalAddressDarwin(Op, DAG); 2582 2583 // The first entry in the descriptor is a function pointer that we must call 2584 // to obtain the address of the variable. 2585 SDValue Chain = DAG.getEntryNode(); 2586 SDValue FuncTLVGet = 2587 DAG.getLoad(MVT::i32, DL, Chain, DescAddr, 2588 MachinePointerInfo::getGOT(DAG.getMachineFunction()), 2589 false, true, true, 4); 2590 Chain = FuncTLVGet.getValue(1); 2591 2592 MachineFunction &F = DAG.getMachineFunction(); 2593 MachineFrameInfo *MFI = F.getFrameInfo(); 2594 MFI->setAdjustsStack(true); 2595 2596 // TLS calls preserve all registers except those that absolutely must be 2597 // trashed: R0 (it takes an argument), LR (it's a call) and CPSR (let's not be 2598 // silly). 2599 auto TRI = 2600 getTargetMachine().getSubtargetImpl(*F.getFunction())->getRegisterInfo(); 2601 auto ARI = static_cast<const ARMRegisterInfo *>(TRI); 2602 const uint32_t *Mask = ARI->getTLSCallPreservedMask(DAG.getMachineFunction()); 2603 2604 // Finally, we can make the call. This is just a degenerate version of a 2605 // normal AArch64 call node: r0 takes the address of the descriptor, and 2606 // returns the address of the variable in this thread. 2607 Chain = DAG.getCopyToReg(Chain, DL, ARM::R0, DescAddr, SDValue()); 2608 Chain = 2609 DAG.getNode(ARMISD::CALL, DL, DAG.getVTList(MVT::Other, MVT::Glue), 2610 Chain, FuncTLVGet, DAG.getRegister(ARM::R0, MVT::i32), 2611 DAG.getRegisterMask(Mask), Chain.getValue(1)); 2612 return DAG.getCopyFromReg(Chain, DL, ARM::R0, MVT::i32, Chain.getValue(1)); 2613 } 2614 2615 // Lower ISD::GlobalTLSAddress using the "general dynamic" model 2616 SDValue 2617 ARMTargetLowering::LowerToTLSGeneralDynamicModel(GlobalAddressSDNode *GA, 2618 SelectionDAG &DAG) const { 2619 SDLoc dl(GA); 2620 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 2621 unsigned char PCAdj = Subtarget->isThumb() ? 4 : 8; 2622 MachineFunction &MF = DAG.getMachineFunction(); 2623 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>(); 2624 unsigned ARMPCLabelIndex = AFI->createPICLabelUId(); 2625 ARMConstantPoolValue *CPV = 2626 ARMConstantPoolConstant::Create(GA->getGlobal(), ARMPCLabelIndex, 2627 ARMCP::CPValue, PCAdj, ARMCP::TLSGD, true); 2628 SDValue Argument = DAG.getTargetConstantPool(CPV, PtrVT, 4); 2629 Argument = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Argument); 2630 Argument = 2631 DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Argument, 2632 MachinePointerInfo::getConstantPool(DAG.getMachineFunction()), 2633 false, false, false, 0); 2634 SDValue Chain = Argument.getValue(1); 2635 2636 SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, dl, MVT::i32); 2637 Argument = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Argument, PICLabel); 2638 2639 // call __tls_get_addr. 2640 ArgListTy Args; 2641 ArgListEntry Entry; 2642 Entry.Node = Argument; 2643 Entry.Ty = (Type *) Type::getInt32Ty(*DAG.getContext()); 2644 Args.push_back(Entry); 2645 2646 // FIXME: is there useful debug info available here? 2647 TargetLowering::CallLoweringInfo CLI(DAG); 2648 CLI.setDebugLoc(dl).setChain(Chain) 2649 .setCallee(CallingConv::C, Type::getInt32Ty(*DAG.getContext()), 2650 DAG.getExternalSymbol("__tls_get_addr", PtrVT), std::move(Args), 2651 0); 2652 2653 std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI); 2654 return CallResult.first; 2655 } 2656 2657 // Lower ISD::GlobalTLSAddress using the "initial exec" or 2658 // "local exec" model. 2659 SDValue 2660 ARMTargetLowering::LowerToTLSExecModels(GlobalAddressSDNode *GA, 2661 SelectionDAG &DAG, 2662 TLSModel::Model model) const { 2663 const GlobalValue *GV = GA->getGlobal(); 2664 SDLoc dl(GA); 2665 SDValue Offset; 2666 SDValue Chain = DAG.getEntryNode(); 2667 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 2668 // Get the Thread Pointer 2669 SDValue ThreadPointer = DAG.getNode(ARMISD::THREAD_POINTER, dl, PtrVT); 2670 2671 if (model == TLSModel::InitialExec) { 2672 MachineFunction &MF = DAG.getMachineFunction(); 2673 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>(); 2674 unsigned ARMPCLabelIndex = AFI->createPICLabelUId(); 2675 // Initial exec model. 2676 unsigned char PCAdj = Subtarget->isThumb() ? 4 : 8; 2677 ARMConstantPoolValue *CPV = 2678 ARMConstantPoolConstant::Create(GA->getGlobal(), ARMPCLabelIndex, 2679 ARMCP::CPValue, PCAdj, ARMCP::GOTTPOFF, 2680 true); 2681 Offset = DAG.getTargetConstantPool(CPV, PtrVT, 4); 2682 Offset = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Offset); 2683 Offset = DAG.getLoad( 2684 PtrVT, dl, Chain, Offset, 2685 MachinePointerInfo::getConstantPool(DAG.getMachineFunction()), false, 2686 false, false, 0); 2687 Chain = Offset.getValue(1); 2688 2689 SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, dl, MVT::i32); 2690 Offset = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Offset, PICLabel); 2691 2692 Offset = DAG.getLoad( 2693 PtrVT, dl, Chain, Offset, 2694 MachinePointerInfo::getConstantPool(DAG.getMachineFunction()), false, 2695 false, false, 0); 2696 } else { 2697 // local exec model 2698 assert(model == TLSModel::LocalExec); 2699 ARMConstantPoolValue *CPV = 2700 ARMConstantPoolConstant::Create(GV, ARMCP::TPOFF); 2701 Offset = DAG.getTargetConstantPool(CPV, PtrVT, 4); 2702 Offset = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Offset); 2703 Offset = DAG.getLoad( 2704 PtrVT, dl, Chain, Offset, 2705 MachinePointerInfo::getConstantPool(DAG.getMachineFunction()), false, 2706 false, false, 0); 2707 } 2708 2709 // The address of the thread local variable is the add of the thread 2710 // pointer with the offset of the variable. 2711 return DAG.getNode(ISD::ADD, dl, PtrVT, ThreadPointer, Offset); 2712 } 2713 2714 SDValue 2715 ARMTargetLowering::LowerGlobalTLSAddress(SDValue Op, SelectionDAG &DAG) const { 2716 if (Subtarget->isTargetDarwin()) 2717 return LowerGlobalTLSAddressDarwin(Op, DAG); 2718 2719 // TODO: implement the "local dynamic" model 2720 assert(Subtarget->isTargetELF() && "Only ELF implemented here"); 2721 GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op); 2722 if (DAG.getTarget().Options.EmulatedTLS) 2723 return LowerToTLSEmulatedModel(GA, DAG); 2724 2725 TLSModel::Model model = getTargetMachine().getTLSModel(GA->getGlobal()); 2726 2727 switch (model) { 2728 case TLSModel::GeneralDynamic: 2729 case TLSModel::LocalDynamic: 2730 return LowerToTLSGeneralDynamicModel(GA, DAG); 2731 case TLSModel::InitialExec: 2732 case TLSModel::LocalExec: 2733 return LowerToTLSExecModels(GA, DAG, model); 2734 } 2735 llvm_unreachable("bogus TLS model"); 2736 } 2737 2738 SDValue ARMTargetLowering::LowerGlobalAddressELF(SDValue Op, 2739 SelectionDAG &DAG) const { 2740 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 2741 SDLoc dl(Op); 2742 const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal(); 2743 if (getTargetMachine().getRelocationModel() == Reloc::PIC_) { 2744 bool UseGOT_PREL = 2745 !(GV->hasHiddenVisibility() || GV->hasLocalLinkage()); 2746 2747 MachineFunction &MF = DAG.getMachineFunction(); 2748 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>(); 2749 unsigned ARMPCLabelIndex = AFI->createPICLabelUId(); 2750 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 2751 SDLoc dl(Op); 2752 unsigned PCAdj = Subtarget->isThumb() ? 4 : 8; 2753 ARMConstantPoolValue *CPV = ARMConstantPoolConstant::Create( 2754 GV, ARMPCLabelIndex, ARMCP::CPValue, PCAdj, 2755 UseGOT_PREL ? ARMCP::GOT_PREL : ARMCP::no_modifier, 2756 /*AddCurrentAddress=*/UseGOT_PREL); 2757 SDValue CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4); 2758 CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr); 2759 SDValue Result = DAG.getLoad( 2760 PtrVT, dl, DAG.getEntryNode(), CPAddr, 2761 MachinePointerInfo::getConstantPool(DAG.getMachineFunction()), false, 2762 false, false, 0); 2763 SDValue Chain = Result.getValue(1); 2764 SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, dl, MVT::i32); 2765 Result = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Result, PICLabel); 2766 if (UseGOT_PREL) 2767 Result = DAG.getLoad(PtrVT, dl, Chain, Result, 2768 MachinePointerInfo::getGOT(DAG.getMachineFunction()), 2769 false, false, false, 0); 2770 return Result; 2771 } 2772 2773 // If we have T2 ops, we can materialize the address directly via movt/movw 2774 // pair. This is always cheaper. 2775 if (Subtarget->useMovt(DAG.getMachineFunction())) { 2776 ++NumMovwMovt; 2777 // FIXME: Once remat is capable of dealing with instructions with register 2778 // operands, expand this into two nodes. 2779 return DAG.getNode(ARMISD::Wrapper, dl, PtrVT, 2780 DAG.getTargetGlobalAddress(GV, dl, PtrVT)); 2781 } else { 2782 SDValue CPAddr = DAG.getTargetConstantPool(GV, PtrVT, 4); 2783 CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr); 2784 return DAG.getLoad( 2785 PtrVT, dl, DAG.getEntryNode(), CPAddr, 2786 MachinePointerInfo::getConstantPool(DAG.getMachineFunction()), false, 2787 false, false, 0); 2788 } 2789 } 2790 2791 SDValue ARMTargetLowering::LowerGlobalAddressDarwin(SDValue Op, 2792 SelectionDAG &DAG) const { 2793 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 2794 SDLoc dl(Op); 2795 const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal(); 2796 Reloc::Model RelocM = getTargetMachine().getRelocationModel(); 2797 2798 if (Subtarget->useMovt(DAG.getMachineFunction())) 2799 ++NumMovwMovt; 2800 2801 // FIXME: Once remat is capable of dealing with instructions with register 2802 // operands, expand this into multiple nodes 2803 unsigned Wrapper = 2804 RelocM == Reloc::PIC_ ? ARMISD::WrapperPIC : ARMISD::Wrapper; 2805 2806 SDValue G = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, ARMII::MO_NONLAZY); 2807 SDValue Result = DAG.getNode(Wrapper, dl, PtrVT, G); 2808 2809 if (Subtarget->GVIsIndirectSymbol(GV, RelocM)) 2810 Result = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Result, 2811 MachinePointerInfo::getGOT(DAG.getMachineFunction()), 2812 false, false, false, 0); 2813 return Result; 2814 } 2815 2816 SDValue ARMTargetLowering::LowerGlobalAddressWindows(SDValue Op, 2817 SelectionDAG &DAG) const { 2818 assert(Subtarget->isTargetWindows() && "non-Windows COFF is not supported"); 2819 assert(Subtarget->useMovt(DAG.getMachineFunction()) && 2820 "Windows on ARM expects to use movw/movt"); 2821 2822 const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal(); 2823 const ARMII::TOF TargetFlags = 2824 (GV->hasDLLImportStorageClass() ? ARMII::MO_DLLIMPORT : ARMII::MO_NO_FLAG); 2825 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 2826 SDValue Result; 2827 SDLoc DL(Op); 2828 2829 ++NumMovwMovt; 2830 2831 // FIXME: Once remat is capable of dealing with instructions with register 2832 // operands, expand this into two nodes. 2833 Result = DAG.getNode(ARMISD::Wrapper, DL, PtrVT, 2834 DAG.getTargetGlobalAddress(GV, DL, PtrVT, /*Offset=*/0, 2835 TargetFlags)); 2836 if (GV->hasDLLImportStorageClass()) 2837 Result = DAG.getLoad(PtrVT, DL, DAG.getEntryNode(), Result, 2838 MachinePointerInfo::getGOT(DAG.getMachineFunction()), 2839 false, false, false, 0); 2840 return Result; 2841 } 2842 2843 SDValue 2844 ARMTargetLowering::LowerEH_SJLJ_SETJMP(SDValue Op, SelectionDAG &DAG) const { 2845 SDLoc dl(Op); 2846 SDValue Val = DAG.getConstant(0, dl, MVT::i32); 2847 return DAG.getNode(ARMISD::EH_SJLJ_SETJMP, dl, 2848 DAG.getVTList(MVT::i32, MVT::Other), Op.getOperand(0), 2849 Op.getOperand(1), Val); 2850 } 2851 2852 SDValue 2853 ARMTargetLowering::LowerEH_SJLJ_LONGJMP(SDValue Op, SelectionDAG &DAG) const { 2854 SDLoc dl(Op); 2855 return DAG.getNode(ARMISD::EH_SJLJ_LONGJMP, dl, MVT::Other, Op.getOperand(0), 2856 Op.getOperand(1), DAG.getConstant(0, dl, MVT::i32)); 2857 } 2858 2859 SDValue ARMTargetLowering::LowerEH_SJLJ_SETUP_DISPATCH(SDValue Op, 2860 SelectionDAG &DAG) const { 2861 SDLoc dl(Op); 2862 return DAG.getNode(ARMISD::EH_SJLJ_SETUP_DISPATCH, dl, MVT::Other, 2863 Op.getOperand(0)); 2864 } 2865 2866 SDValue 2867 ARMTargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op, SelectionDAG &DAG, 2868 const ARMSubtarget *Subtarget) const { 2869 unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue(); 2870 SDLoc dl(Op); 2871 switch (IntNo) { 2872 default: return SDValue(); // Don't custom lower most intrinsics. 2873 case Intrinsic::arm_rbit: { 2874 assert(Op.getOperand(1).getValueType() == MVT::i32 && 2875 "RBIT intrinsic must have i32 type!"); 2876 return DAG.getNode(ISD::BITREVERSE, dl, MVT::i32, Op.getOperand(1)); 2877 } 2878 case Intrinsic::arm_thread_pointer: { 2879 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 2880 return DAG.getNode(ARMISD::THREAD_POINTER, dl, PtrVT); 2881 } 2882 case Intrinsic::eh_sjlj_lsda: { 2883 MachineFunction &MF = DAG.getMachineFunction(); 2884 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>(); 2885 unsigned ARMPCLabelIndex = AFI->createPICLabelUId(); 2886 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 2887 Reloc::Model RelocM = getTargetMachine().getRelocationModel(); 2888 SDValue CPAddr; 2889 unsigned PCAdj = (RelocM != Reloc::PIC_) 2890 ? 0 : (Subtarget->isThumb() ? 4 : 8); 2891 ARMConstantPoolValue *CPV = 2892 ARMConstantPoolConstant::Create(MF.getFunction(), ARMPCLabelIndex, 2893 ARMCP::CPLSDA, PCAdj); 2894 CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4); 2895 CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr); 2896 SDValue Result = DAG.getLoad( 2897 PtrVT, dl, DAG.getEntryNode(), CPAddr, 2898 MachinePointerInfo::getConstantPool(DAG.getMachineFunction()), false, 2899 false, false, 0); 2900 2901 if (RelocM == Reloc::PIC_) { 2902 SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, dl, MVT::i32); 2903 Result = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Result, PICLabel); 2904 } 2905 return Result; 2906 } 2907 case Intrinsic::arm_neon_vmulls: 2908 case Intrinsic::arm_neon_vmullu: { 2909 unsigned NewOpc = (IntNo == Intrinsic::arm_neon_vmulls) 2910 ? ARMISD::VMULLs : ARMISD::VMULLu; 2911 return DAG.getNode(NewOpc, SDLoc(Op), Op.getValueType(), 2912 Op.getOperand(1), Op.getOperand(2)); 2913 } 2914 case Intrinsic::arm_neon_vminnm: 2915 case Intrinsic::arm_neon_vmaxnm: { 2916 unsigned NewOpc = (IntNo == Intrinsic::arm_neon_vminnm) 2917 ? ISD::FMINNUM : ISD::FMAXNUM; 2918 return DAG.getNode(NewOpc, SDLoc(Op), Op.getValueType(), 2919 Op.getOperand(1), Op.getOperand(2)); 2920 } 2921 case Intrinsic::arm_neon_vminu: 2922 case Intrinsic::arm_neon_vmaxu: { 2923 if (Op.getValueType().isFloatingPoint()) 2924 return SDValue(); 2925 unsigned NewOpc = (IntNo == Intrinsic::arm_neon_vminu) 2926 ? ISD::UMIN : ISD::UMAX; 2927 return DAG.getNode(NewOpc, SDLoc(Op), Op.getValueType(), 2928 Op.getOperand(1), Op.getOperand(2)); 2929 } 2930 case Intrinsic::arm_neon_vmins: 2931 case Intrinsic::arm_neon_vmaxs: { 2932 // v{min,max}s is overloaded between signed integers and floats. 2933 if (!Op.getValueType().isFloatingPoint()) { 2934 unsigned NewOpc = (IntNo == Intrinsic::arm_neon_vmins) 2935 ? ISD::SMIN : ISD::SMAX; 2936 return DAG.getNode(NewOpc, SDLoc(Op), Op.getValueType(), 2937 Op.getOperand(1), Op.getOperand(2)); 2938 } 2939 unsigned NewOpc = (IntNo == Intrinsic::arm_neon_vmins) 2940 ? ISD::FMINNAN : ISD::FMAXNAN; 2941 return DAG.getNode(NewOpc, SDLoc(Op), Op.getValueType(), 2942 Op.getOperand(1), Op.getOperand(2)); 2943 } 2944 } 2945 } 2946 2947 static SDValue LowerATOMIC_FENCE(SDValue Op, SelectionDAG &DAG, 2948 const ARMSubtarget *Subtarget) { 2949 // FIXME: handle "fence singlethread" more efficiently. 2950 SDLoc dl(Op); 2951 if (!Subtarget->hasDataBarrier()) { 2952 // Some ARMv6 cpus can support data barriers with an mcr instruction. 2953 // Thumb1 and pre-v6 ARM mode use a libcall instead and should never get 2954 // here. 2955 assert(Subtarget->hasV6Ops() && !Subtarget->isThumb() && 2956 "Unexpected ISD::ATOMIC_FENCE encountered. Should be libcall!"); 2957 return DAG.getNode(ARMISD::MEMBARRIER_MCR, dl, MVT::Other, Op.getOperand(0), 2958 DAG.getConstant(0, dl, MVT::i32)); 2959 } 2960 2961 ConstantSDNode *OrdN = cast<ConstantSDNode>(Op.getOperand(1)); 2962 AtomicOrdering Ord = static_cast<AtomicOrdering>(OrdN->getZExtValue()); 2963 ARM_MB::MemBOpt Domain = ARM_MB::ISH; 2964 if (Subtarget->isMClass()) { 2965 // Only a full system barrier exists in the M-class architectures. 2966 Domain = ARM_MB::SY; 2967 } else if (Subtarget->isSwift() && Ord == Release) { 2968 // Swift happens to implement ISHST barriers in a way that's compatible with 2969 // Release semantics but weaker than ISH so we'd be fools not to use 2970 // it. Beware: other processors probably don't! 2971 Domain = ARM_MB::ISHST; 2972 } 2973 2974 return DAG.getNode(ISD::INTRINSIC_VOID, dl, MVT::Other, Op.getOperand(0), 2975 DAG.getConstant(Intrinsic::arm_dmb, dl, MVT::i32), 2976 DAG.getConstant(Domain, dl, MVT::i32)); 2977 } 2978 2979 static SDValue LowerPREFETCH(SDValue Op, SelectionDAG &DAG, 2980 const ARMSubtarget *Subtarget) { 2981 // ARM pre v5TE and Thumb1 does not have preload instructions. 2982 if (!(Subtarget->isThumb2() || 2983 (!Subtarget->isThumb1Only() && Subtarget->hasV5TEOps()))) 2984 // Just preserve the chain. 2985 return Op.getOperand(0); 2986 2987 SDLoc dl(Op); 2988 unsigned isRead = ~cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue() & 1; 2989 if (!isRead && 2990 (!Subtarget->hasV7Ops() || !Subtarget->hasMPExtension())) 2991 // ARMv7 with MP extension has PLDW. 2992 return Op.getOperand(0); 2993 2994 unsigned isData = cast<ConstantSDNode>(Op.getOperand(4))->getZExtValue(); 2995 if (Subtarget->isThumb()) { 2996 // Invert the bits. 2997 isRead = ~isRead & 1; 2998 isData = ~isData & 1; 2999 } 3000 3001 return DAG.getNode(ARMISD::PRELOAD, dl, MVT::Other, Op.getOperand(0), 3002 Op.getOperand(1), DAG.getConstant(isRead, dl, MVT::i32), 3003 DAG.getConstant(isData, dl, MVT::i32)); 3004 } 3005 3006 static SDValue LowerVASTART(SDValue Op, SelectionDAG &DAG) { 3007 MachineFunction &MF = DAG.getMachineFunction(); 3008 ARMFunctionInfo *FuncInfo = MF.getInfo<ARMFunctionInfo>(); 3009 3010 // vastart just stores the address of the VarArgsFrameIndex slot into the 3011 // memory location argument. 3012 SDLoc dl(Op); 3013 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout()); 3014 SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT); 3015 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue(); 3016 return DAG.getStore(Op.getOperand(0), dl, FR, Op.getOperand(1), 3017 MachinePointerInfo(SV), false, false, 0); 3018 } 3019 3020 SDValue 3021 ARMTargetLowering::GetF64FormalArgument(CCValAssign &VA, CCValAssign &NextVA, 3022 SDValue &Root, SelectionDAG &DAG, 3023 SDLoc dl) const { 3024 MachineFunction &MF = DAG.getMachineFunction(); 3025 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>(); 3026 3027 const TargetRegisterClass *RC; 3028 if (AFI->isThumb1OnlyFunction()) 3029 RC = &ARM::tGPRRegClass; 3030 else 3031 RC = &ARM::GPRRegClass; 3032 3033 // Transform the arguments stored in physical registers into virtual ones. 3034 unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC); 3035 SDValue ArgValue = DAG.getCopyFromReg(Root, dl, Reg, MVT::i32); 3036 3037 SDValue ArgValue2; 3038 if (NextVA.isMemLoc()) { 3039 MachineFrameInfo *MFI = MF.getFrameInfo(); 3040 int FI = MFI->CreateFixedObject(4, NextVA.getLocMemOffset(), true); 3041 3042 // Create load node to retrieve arguments from the stack. 3043 SDValue FIN = DAG.getFrameIndex(FI, getPointerTy(DAG.getDataLayout())); 3044 ArgValue2 = DAG.getLoad( 3045 MVT::i32, dl, Root, FIN, 3046 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI), false, 3047 false, false, 0); 3048 } else { 3049 Reg = MF.addLiveIn(NextVA.getLocReg(), RC); 3050 ArgValue2 = DAG.getCopyFromReg(Root, dl, Reg, MVT::i32); 3051 } 3052 if (!Subtarget->isLittle()) 3053 std::swap (ArgValue, ArgValue2); 3054 return DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, ArgValue, ArgValue2); 3055 } 3056 3057 // The remaining GPRs hold either the beginning of variable-argument 3058 // data, or the beginning of an aggregate passed by value (usually 3059 // byval). Either way, we allocate stack slots adjacent to the data 3060 // provided by our caller, and store the unallocated registers there. 3061 // If this is a variadic function, the va_list pointer will begin with 3062 // these values; otherwise, this reassembles a (byval) structure that 3063 // was split between registers and memory. 3064 // Return: The frame index registers were stored into. 3065 int 3066 ARMTargetLowering::StoreByValRegs(CCState &CCInfo, SelectionDAG &DAG, 3067 SDLoc dl, SDValue &Chain, 3068 const Value *OrigArg, 3069 unsigned InRegsParamRecordIdx, 3070 int ArgOffset, 3071 unsigned ArgSize) const { 3072 // Currently, two use-cases possible: 3073 // Case #1. Non-var-args function, and we meet first byval parameter. 3074 // Setup first unallocated register as first byval register; 3075 // eat all remained registers 3076 // (these two actions are performed by HandleByVal method). 3077 // Then, here, we initialize stack frame with 3078 // "store-reg" instructions. 3079 // Case #2. Var-args function, that doesn't contain byval parameters. 3080 // The same: eat all remained unallocated registers, 3081 // initialize stack frame. 3082 3083 MachineFunction &MF = DAG.getMachineFunction(); 3084 MachineFrameInfo *MFI = MF.getFrameInfo(); 3085 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>(); 3086 unsigned RBegin, REnd; 3087 if (InRegsParamRecordIdx < CCInfo.getInRegsParamsCount()) { 3088 CCInfo.getInRegsParamInfo(InRegsParamRecordIdx, RBegin, REnd); 3089 } else { 3090 unsigned RBeginIdx = CCInfo.getFirstUnallocated(GPRArgRegs); 3091 RBegin = RBeginIdx == 4 ? (unsigned)ARM::R4 : GPRArgRegs[RBeginIdx]; 3092 REnd = ARM::R4; 3093 } 3094 3095 if (REnd != RBegin) 3096 ArgOffset = -4 * (ARM::R4 - RBegin); 3097 3098 auto PtrVT = getPointerTy(DAG.getDataLayout()); 3099 int FrameIndex = MFI->CreateFixedObject(ArgSize, ArgOffset, false); 3100 SDValue FIN = DAG.getFrameIndex(FrameIndex, PtrVT); 3101 3102 SmallVector<SDValue, 4> MemOps; 3103 const TargetRegisterClass *RC = 3104 AFI->isThumb1OnlyFunction() ? &ARM::tGPRRegClass : &ARM::GPRRegClass; 3105 3106 for (unsigned Reg = RBegin, i = 0; Reg < REnd; ++Reg, ++i) { 3107 unsigned VReg = MF.addLiveIn(Reg, RC); 3108 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i32); 3109 SDValue Store = 3110 DAG.getStore(Val.getValue(1), dl, Val, FIN, 3111 MachinePointerInfo(OrigArg, 4 * i), false, false, 0); 3112 MemOps.push_back(Store); 3113 FIN = DAG.getNode(ISD::ADD, dl, PtrVT, FIN, DAG.getConstant(4, dl, PtrVT)); 3114 } 3115 3116 if (!MemOps.empty()) 3117 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOps); 3118 return FrameIndex; 3119 } 3120 3121 // Setup stack frame, the va_list pointer will start from. 3122 void 3123 ARMTargetLowering::VarArgStyleRegisters(CCState &CCInfo, SelectionDAG &DAG, 3124 SDLoc dl, SDValue &Chain, 3125 unsigned ArgOffset, 3126 unsigned TotalArgRegsSaveSize, 3127 bool ForceMutable) const { 3128 MachineFunction &MF = DAG.getMachineFunction(); 3129 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>(); 3130 3131 // Try to store any remaining integer argument regs 3132 // to their spots on the stack so that they may be loaded by deferencing 3133 // the result of va_next. 3134 // If there is no regs to be stored, just point address after last 3135 // argument passed via stack. 3136 int FrameIndex = StoreByValRegs(CCInfo, DAG, dl, Chain, nullptr, 3137 CCInfo.getInRegsParamsCount(), 3138 CCInfo.getNextStackOffset(), 4); 3139 AFI->setVarArgsFrameIndex(FrameIndex); 3140 } 3141 3142 SDValue 3143 ARMTargetLowering::LowerFormalArguments(SDValue Chain, 3144 CallingConv::ID CallConv, bool isVarArg, 3145 const SmallVectorImpl<ISD::InputArg> 3146 &Ins, 3147 SDLoc dl, SelectionDAG &DAG, 3148 SmallVectorImpl<SDValue> &InVals) 3149 const { 3150 MachineFunction &MF = DAG.getMachineFunction(); 3151 MachineFrameInfo *MFI = MF.getFrameInfo(); 3152 3153 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>(); 3154 3155 // Assign locations to all of the incoming arguments. 3156 SmallVector<CCValAssign, 16> ArgLocs; 3157 ARMCCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), ArgLocs, 3158 *DAG.getContext(), Prologue); 3159 CCInfo.AnalyzeFormalArguments(Ins, 3160 CCAssignFnForNode(CallConv, /* Return*/ false, 3161 isVarArg)); 3162 3163 SmallVector<SDValue, 16> ArgValues; 3164 SDValue ArgValue; 3165 Function::const_arg_iterator CurOrigArg = MF.getFunction()->arg_begin(); 3166 unsigned CurArgIdx = 0; 3167 3168 // Initially ArgRegsSaveSize is zero. 3169 // Then we increase this value each time we meet byval parameter. 3170 // We also increase this value in case of varargs function. 3171 AFI->setArgRegsSaveSize(0); 3172 3173 // Calculate the amount of stack space that we need to allocate to store 3174 // byval and variadic arguments that are passed in registers. 3175 // We need to know this before we allocate the first byval or variadic 3176 // argument, as they will be allocated a stack slot below the CFA (Canonical 3177 // Frame Address, the stack pointer at entry to the function). 3178 unsigned ArgRegBegin = ARM::R4; 3179 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) { 3180 if (CCInfo.getInRegsParamsProcessed() >= CCInfo.getInRegsParamsCount()) 3181 break; 3182 3183 CCValAssign &VA = ArgLocs[i]; 3184 unsigned Index = VA.getValNo(); 3185 ISD::ArgFlagsTy Flags = Ins[Index].Flags; 3186 if (!Flags.isByVal()) 3187 continue; 3188 3189 assert(VA.isMemLoc() && "unexpected byval pointer in reg"); 3190 unsigned RBegin, REnd; 3191 CCInfo.getInRegsParamInfo(CCInfo.getInRegsParamsProcessed(), RBegin, REnd); 3192 ArgRegBegin = std::min(ArgRegBegin, RBegin); 3193 3194 CCInfo.nextInRegsParam(); 3195 } 3196 CCInfo.rewindByValRegsInfo(); 3197 3198 int lastInsIndex = -1; 3199 if (isVarArg && MFI->hasVAStart()) { 3200 unsigned RegIdx = CCInfo.getFirstUnallocated(GPRArgRegs); 3201 if (RegIdx != array_lengthof(GPRArgRegs)) 3202 ArgRegBegin = std::min(ArgRegBegin, (unsigned)GPRArgRegs[RegIdx]); 3203 } 3204 3205 unsigned TotalArgRegsSaveSize = 4 * (ARM::R4 - ArgRegBegin); 3206 AFI->setArgRegsSaveSize(TotalArgRegsSaveSize); 3207 auto PtrVT = getPointerTy(DAG.getDataLayout()); 3208 3209 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) { 3210 CCValAssign &VA = ArgLocs[i]; 3211 if (Ins[VA.getValNo()].isOrigArg()) { 3212 std::advance(CurOrigArg, 3213 Ins[VA.getValNo()].getOrigArgIndex() - CurArgIdx); 3214 CurArgIdx = Ins[VA.getValNo()].getOrigArgIndex(); 3215 } 3216 // Arguments stored in registers. 3217 if (VA.isRegLoc()) { 3218 EVT RegVT = VA.getLocVT(); 3219 3220 if (VA.needsCustom()) { 3221 // f64 and vector types are split up into multiple registers or 3222 // combinations of registers and stack slots. 3223 if (VA.getLocVT() == MVT::v2f64) { 3224 SDValue ArgValue1 = GetF64FormalArgument(VA, ArgLocs[++i], 3225 Chain, DAG, dl); 3226 VA = ArgLocs[++i]; // skip ahead to next loc 3227 SDValue ArgValue2; 3228 if (VA.isMemLoc()) { 3229 int FI = MFI->CreateFixedObject(8, VA.getLocMemOffset(), true); 3230 SDValue FIN = DAG.getFrameIndex(FI, PtrVT); 3231 ArgValue2 = DAG.getLoad( 3232 MVT::f64, dl, Chain, FIN, 3233 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI), 3234 false, false, false, 0); 3235 } else { 3236 ArgValue2 = GetF64FormalArgument(VA, ArgLocs[++i], 3237 Chain, DAG, dl); 3238 } 3239 ArgValue = DAG.getNode(ISD::UNDEF, dl, MVT::v2f64); 3240 ArgValue = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, 3241 ArgValue, ArgValue1, 3242 DAG.getIntPtrConstant(0, dl)); 3243 ArgValue = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, 3244 ArgValue, ArgValue2, 3245 DAG.getIntPtrConstant(1, dl)); 3246 } else 3247 ArgValue = GetF64FormalArgument(VA, ArgLocs[++i], Chain, DAG, dl); 3248 3249 } else { 3250 const TargetRegisterClass *RC; 3251 3252 if (RegVT == MVT::f32) 3253 RC = &ARM::SPRRegClass; 3254 else if (RegVT == MVT::f64) 3255 RC = &ARM::DPRRegClass; 3256 else if (RegVT == MVT::v2f64) 3257 RC = &ARM::QPRRegClass; 3258 else if (RegVT == MVT::i32) 3259 RC = AFI->isThumb1OnlyFunction() ? &ARM::tGPRRegClass 3260 : &ARM::GPRRegClass; 3261 else 3262 llvm_unreachable("RegVT not supported by FORMAL_ARGUMENTS Lowering"); 3263 3264 // Transform the arguments in physical registers into virtual ones. 3265 unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC); 3266 ArgValue = DAG.getCopyFromReg(Chain, dl, Reg, RegVT); 3267 } 3268 3269 // If this is an 8 or 16-bit value, it is really passed promoted 3270 // to 32 bits. Insert an assert[sz]ext to capture this, then 3271 // truncate to the right size. 3272 switch (VA.getLocInfo()) { 3273 default: llvm_unreachable("Unknown loc info!"); 3274 case CCValAssign::Full: break; 3275 case CCValAssign::BCvt: 3276 ArgValue = DAG.getNode(ISD::BITCAST, dl, VA.getValVT(), ArgValue); 3277 break; 3278 case CCValAssign::SExt: 3279 ArgValue = DAG.getNode(ISD::AssertSext, dl, RegVT, ArgValue, 3280 DAG.getValueType(VA.getValVT())); 3281 ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue); 3282 break; 3283 case CCValAssign::ZExt: 3284 ArgValue = DAG.getNode(ISD::AssertZext, dl, RegVT, ArgValue, 3285 DAG.getValueType(VA.getValVT())); 3286 ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue); 3287 break; 3288 } 3289 3290 InVals.push_back(ArgValue); 3291 3292 } else { // VA.isRegLoc() 3293 3294 // sanity check 3295 assert(VA.isMemLoc()); 3296 assert(VA.getValVT() != MVT::i64 && "i64 should already be lowered"); 3297 3298 int index = VA.getValNo(); 3299 3300 // Some Ins[] entries become multiple ArgLoc[] entries. 3301 // Process them only once. 3302 if (index != lastInsIndex) 3303 { 3304 ISD::ArgFlagsTy Flags = Ins[index].Flags; 3305 // FIXME: For now, all byval parameter objects are marked mutable. 3306 // This can be changed with more analysis. 3307 // In case of tail call optimization mark all arguments mutable. 3308 // Since they could be overwritten by lowering of arguments in case of 3309 // a tail call. 3310 if (Flags.isByVal()) { 3311 assert(Ins[index].isOrigArg() && 3312 "Byval arguments cannot be implicit"); 3313 unsigned CurByValIndex = CCInfo.getInRegsParamsProcessed(); 3314 3315 int FrameIndex = StoreByValRegs( 3316 CCInfo, DAG, dl, Chain, &*CurOrigArg, CurByValIndex, 3317 VA.getLocMemOffset(), Flags.getByValSize()); 3318 InVals.push_back(DAG.getFrameIndex(FrameIndex, PtrVT)); 3319 CCInfo.nextInRegsParam(); 3320 } else { 3321 unsigned FIOffset = VA.getLocMemOffset(); 3322 int FI = MFI->CreateFixedObject(VA.getLocVT().getSizeInBits()/8, 3323 FIOffset, true); 3324 3325 // Create load nodes to retrieve arguments from the stack. 3326 SDValue FIN = DAG.getFrameIndex(FI, PtrVT); 3327 InVals.push_back(DAG.getLoad( 3328 VA.getValVT(), dl, Chain, FIN, 3329 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI), 3330 false, false, false, 0)); 3331 } 3332 lastInsIndex = index; 3333 } 3334 } 3335 } 3336 3337 // varargs 3338 if (isVarArg && MFI->hasVAStart()) 3339 VarArgStyleRegisters(CCInfo, DAG, dl, Chain, 3340 CCInfo.getNextStackOffset(), 3341 TotalArgRegsSaveSize); 3342 3343 AFI->setArgumentStackSize(CCInfo.getNextStackOffset()); 3344 3345 return Chain; 3346 } 3347 3348 /// isFloatingPointZero - Return true if this is +0.0. 3349 static bool isFloatingPointZero(SDValue Op) { 3350 if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Op)) 3351 return CFP->getValueAPF().isPosZero(); 3352 else if (ISD::isEXTLoad(Op.getNode()) || ISD::isNON_EXTLoad(Op.getNode())) { 3353 // Maybe this has already been legalized into the constant pool? 3354 if (Op.getOperand(1).getOpcode() == ARMISD::Wrapper) { 3355 SDValue WrapperOp = Op.getOperand(1).getOperand(0); 3356 if (ConstantPoolSDNode *CP = dyn_cast<ConstantPoolSDNode>(WrapperOp)) 3357 if (const ConstantFP *CFP = dyn_cast<ConstantFP>(CP->getConstVal())) 3358 return CFP->getValueAPF().isPosZero(); 3359 } 3360 } else if (Op->getOpcode() == ISD::BITCAST && 3361 Op->getValueType(0) == MVT::f64) { 3362 // Handle (ISD::BITCAST (ARMISD::VMOVIMM (ISD::TargetConstant 0)) MVT::f64) 3363 // created by LowerConstantFP(). 3364 SDValue BitcastOp = Op->getOperand(0); 3365 if (BitcastOp->getOpcode() == ARMISD::VMOVIMM && 3366 isNullConstant(BitcastOp->getOperand(0))) 3367 return true; 3368 } 3369 return false; 3370 } 3371 3372 /// Returns appropriate ARM CMP (cmp) and corresponding condition code for 3373 /// the given operands. 3374 SDValue 3375 ARMTargetLowering::getARMCmp(SDValue LHS, SDValue RHS, ISD::CondCode CC, 3376 SDValue &ARMcc, SelectionDAG &DAG, 3377 SDLoc dl) const { 3378 if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS.getNode())) { 3379 unsigned C = RHSC->getZExtValue(); 3380 if (!isLegalICmpImmediate(C)) { 3381 // Constant does not fit, try adjusting it by one? 3382 switch (CC) { 3383 default: break; 3384 case ISD::SETLT: 3385 case ISD::SETGE: 3386 if (C != 0x80000000 && isLegalICmpImmediate(C-1)) { 3387 CC = (CC == ISD::SETLT) ? ISD::SETLE : ISD::SETGT; 3388 RHS = DAG.getConstant(C - 1, dl, MVT::i32); 3389 } 3390 break; 3391 case ISD::SETULT: 3392 case ISD::SETUGE: 3393 if (C != 0 && isLegalICmpImmediate(C-1)) { 3394 CC = (CC == ISD::SETULT) ? ISD::SETULE : ISD::SETUGT; 3395 RHS = DAG.getConstant(C - 1, dl, MVT::i32); 3396 } 3397 break; 3398 case ISD::SETLE: 3399 case ISD::SETGT: 3400 if (C != 0x7fffffff && isLegalICmpImmediate(C+1)) { 3401 CC = (CC == ISD::SETLE) ? ISD::SETLT : ISD::SETGE; 3402 RHS = DAG.getConstant(C + 1, dl, MVT::i32); 3403 } 3404 break; 3405 case ISD::SETULE: 3406 case ISD::SETUGT: 3407 if (C != 0xffffffff && isLegalICmpImmediate(C+1)) { 3408 CC = (CC == ISD::SETULE) ? ISD::SETULT : ISD::SETUGE; 3409 RHS = DAG.getConstant(C + 1, dl, MVT::i32); 3410 } 3411 break; 3412 } 3413 } 3414 } 3415 3416 ARMCC::CondCodes CondCode = IntCCToARMCC(CC); 3417 ARMISD::NodeType CompareType; 3418 switch (CondCode) { 3419 default: 3420 CompareType = ARMISD::CMP; 3421 break; 3422 case ARMCC::EQ: 3423 case ARMCC::NE: 3424 // Uses only Z Flag 3425 CompareType = ARMISD::CMPZ; 3426 break; 3427 } 3428 ARMcc = DAG.getConstant(CondCode, dl, MVT::i32); 3429 return DAG.getNode(CompareType, dl, MVT::Glue, LHS, RHS); 3430 } 3431 3432 /// Returns a appropriate VFP CMP (fcmp{s|d}+fmstat) for the given operands. 3433 SDValue 3434 ARMTargetLowering::getVFPCmp(SDValue LHS, SDValue RHS, SelectionDAG &DAG, 3435 SDLoc dl) const { 3436 assert(!Subtarget->isFPOnlySP() || RHS.getValueType() != MVT::f64); 3437 SDValue Cmp; 3438 if (!isFloatingPointZero(RHS)) 3439 Cmp = DAG.getNode(ARMISD::CMPFP, dl, MVT::Glue, LHS, RHS); 3440 else 3441 Cmp = DAG.getNode(ARMISD::CMPFPw0, dl, MVT::Glue, LHS); 3442 return DAG.getNode(ARMISD::FMSTAT, dl, MVT::Glue, Cmp); 3443 } 3444 3445 /// duplicateCmp - Glue values can have only one use, so this function 3446 /// duplicates a comparison node. 3447 SDValue 3448 ARMTargetLowering::duplicateCmp(SDValue Cmp, SelectionDAG &DAG) const { 3449 unsigned Opc = Cmp.getOpcode(); 3450 SDLoc DL(Cmp); 3451 if (Opc == ARMISD::CMP || Opc == ARMISD::CMPZ) 3452 return DAG.getNode(Opc, DL, MVT::Glue, Cmp.getOperand(0),Cmp.getOperand(1)); 3453 3454 assert(Opc == ARMISD::FMSTAT && "unexpected comparison operation"); 3455 Cmp = Cmp.getOperand(0); 3456 Opc = Cmp.getOpcode(); 3457 if (Opc == ARMISD::CMPFP) 3458 Cmp = DAG.getNode(Opc, DL, MVT::Glue, Cmp.getOperand(0),Cmp.getOperand(1)); 3459 else { 3460 assert(Opc == ARMISD::CMPFPw0 && "unexpected operand of FMSTAT"); 3461 Cmp = DAG.getNode(Opc, DL, MVT::Glue, Cmp.getOperand(0)); 3462 } 3463 return DAG.getNode(ARMISD::FMSTAT, DL, MVT::Glue, Cmp); 3464 } 3465 3466 std::pair<SDValue, SDValue> 3467 ARMTargetLowering::getARMXALUOOp(SDValue Op, SelectionDAG &DAG, 3468 SDValue &ARMcc) const { 3469 assert(Op.getValueType() == MVT::i32 && "Unsupported value type"); 3470 3471 SDValue Value, OverflowCmp; 3472 SDValue LHS = Op.getOperand(0); 3473 SDValue RHS = Op.getOperand(1); 3474 SDLoc dl(Op); 3475 3476 // FIXME: We are currently always generating CMPs because we don't support 3477 // generating CMN through the backend. This is not as good as the natural 3478 // CMP case because it causes a register dependency and cannot be folded 3479 // later. 3480 3481 switch (Op.getOpcode()) { 3482 default: 3483 llvm_unreachable("Unknown overflow instruction!"); 3484 case ISD::SADDO: 3485 ARMcc = DAG.getConstant(ARMCC::VC, dl, MVT::i32); 3486 Value = DAG.getNode(ISD::ADD, dl, Op.getValueType(), LHS, RHS); 3487 OverflowCmp = DAG.getNode(ARMISD::CMP, dl, MVT::Glue, Value, LHS); 3488 break; 3489 case ISD::UADDO: 3490 ARMcc = DAG.getConstant(ARMCC::HS, dl, MVT::i32); 3491 Value = DAG.getNode(ISD::ADD, dl, Op.getValueType(), LHS, RHS); 3492 OverflowCmp = DAG.getNode(ARMISD::CMP, dl, MVT::Glue, Value, LHS); 3493 break; 3494 case ISD::SSUBO: 3495 ARMcc = DAG.getConstant(ARMCC::VC, dl, MVT::i32); 3496 Value = DAG.getNode(ISD::SUB, dl, Op.getValueType(), LHS, RHS); 3497 OverflowCmp = DAG.getNode(ARMISD::CMP, dl, MVT::Glue, LHS, RHS); 3498 break; 3499 case ISD::USUBO: 3500 ARMcc = DAG.getConstant(ARMCC::HS, dl, MVT::i32); 3501 Value = DAG.getNode(ISD::SUB, dl, Op.getValueType(), LHS, RHS); 3502 OverflowCmp = DAG.getNode(ARMISD::CMP, dl, MVT::Glue, LHS, RHS); 3503 break; 3504 } // switch (...) 3505 3506 return std::make_pair(Value, OverflowCmp); 3507 } 3508 3509 3510 SDValue 3511 ARMTargetLowering::LowerXALUO(SDValue Op, SelectionDAG &DAG) const { 3512 // Let legalize expand this if it isn't a legal type yet. 3513 if (!DAG.getTargetLoweringInfo().isTypeLegal(Op.getValueType())) 3514 return SDValue(); 3515 3516 SDValue Value, OverflowCmp; 3517 SDValue ARMcc; 3518 std::tie(Value, OverflowCmp) = getARMXALUOOp(Op, DAG, ARMcc); 3519 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32); 3520 SDLoc dl(Op); 3521 // We use 0 and 1 as false and true values. 3522 SDValue TVal = DAG.getConstant(1, dl, MVT::i32); 3523 SDValue FVal = DAG.getConstant(0, dl, MVT::i32); 3524 EVT VT = Op.getValueType(); 3525 3526 SDValue Overflow = DAG.getNode(ARMISD::CMOV, dl, VT, TVal, FVal, 3527 ARMcc, CCR, OverflowCmp); 3528 3529 SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32); 3530 return DAG.getNode(ISD::MERGE_VALUES, dl, VTs, Value, Overflow); 3531 } 3532 3533 3534 SDValue ARMTargetLowering::LowerSELECT(SDValue Op, SelectionDAG &DAG) const { 3535 SDValue Cond = Op.getOperand(0); 3536 SDValue SelectTrue = Op.getOperand(1); 3537 SDValue SelectFalse = Op.getOperand(2); 3538 SDLoc dl(Op); 3539 unsigned Opc = Cond.getOpcode(); 3540 3541 if (Cond.getResNo() == 1 && 3542 (Opc == ISD::SADDO || Opc == ISD::UADDO || Opc == ISD::SSUBO || 3543 Opc == ISD::USUBO)) { 3544 if (!DAG.getTargetLoweringInfo().isTypeLegal(Cond->getValueType(0))) 3545 return SDValue(); 3546 3547 SDValue Value, OverflowCmp; 3548 SDValue ARMcc; 3549 std::tie(Value, OverflowCmp) = getARMXALUOOp(Cond, DAG, ARMcc); 3550 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32); 3551 EVT VT = Op.getValueType(); 3552 3553 return getCMOV(dl, VT, SelectTrue, SelectFalse, ARMcc, CCR, 3554 OverflowCmp, DAG); 3555 } 3556 3557 // Convert: 3558 // 3559 // (select (cmov 1, 0, cond), t, f) -> (cmov t, f, cond) 3560 // (select (cmov 0, 1, cond), t, f) -> (cmov f, t, cond) 3561 // 3562 if (Cond.getOpcode() == ARMISD::CMOV && Cond.hasOneUse()) { 3563 const ConstantSDNode *CMOVTrue = 3564 dyn_cast<ConstantSDNode>(Cond.getOperand(0)); 3565 const ConstantSDNode *CMOVFalse = 3566 dyn_cast<ConstantSDNode>(Cond.getOperand(1)); 3567 3568 if (CMOVTrue && CMOVFalse) { 3569 unsigned CMOVTrueVal = CMOVTrue->getZExtValue(); 3570 unsigned CMOVFalseVal = CMOVFalse->getZExtValue(); 3571 3572 SDValue True; 3573 SDValue False; 3574 if (CMOVTrueVal == 1 && CMOVFalseVal == 0) { 3575 True = SelectTrue; 3576 False = SelectFalse; 3577 } else if (CMOVTrueVal == 0 && CMOVFalseVal == 1) { 3578 True = SelectFalse; 3579 False = SelectTrue; 3580 } 3581 3582 if (True.getNode() && False.getNode()) { 3583 EVT VT = Op.getValueType(); 3584 SDValue ARMcc = Cond.getOperand(2); 3585 SDValue CCR = Cond.getOperand(3); 3586 SDValue Cmp = duplicateCmp(Cond.getOperand(4), DAG); 3587 assert(True.getValueType() == VT); 3588 return getCMOV(dl, VT, True, False, ARMcc, CCR, Cmp, DAG); 3589 } 3590 } 3591 } 3592 3593 // ARM's BooleanContents value is UndefinedBooleanContent. Mask out the 3594 // undefined bits before doing a full-word comparison with zero. 3595 Cond = DAG.getNode(ISD::AND, dl, Cond.getValueType(), Cond, 3596 DAG.getConstant(1, dl, Cond.getValueType())); 3597 3598 return DAG.getSelectCC(dl, Cond, 3599 DAG.getConstant(0, dl, Cond.getValueType()), 3600 SelectTrue, SelectFalse, ISD::SETNE); 3601 } 3602 3603 static void checkVSELConstraints(ISD::CondCode CC, ARMCC::CondCodes &CondCode, 3604 bool &swpCmpOps, bool &swpVselOps) { 3605 // Start by selecting the GE condition code for opcodes that return true for 3606 // 'equality' 3607 if (CC == ISD::SETUGE || CC == ISD::SETOGE || CC == ISD::SETOLE || 3608 CC == ISD::SETULE) 3609 CondCode = ARMCC::GE; 3610 3611 // and GT for opcodes that return false for 'equality'. 3612 else if (CC == ISD::SETUGT || CC == ISD::SETOGT || CC == ISD::SETOLT || 3613 CC == ISD::SETULT) 3614 CondCode = ARMCC::GT; 3615 3616 // Since we are constrained to GE/GT, if the opcode contains 'less', we need 3617 // to swap the compare operands. 3618 if (CC == ISD::SETOLE || CC == ISD::SETULE || CC == ISD::SETOLT || 3619 CC == ISD::SETULT) 3620 swpCmpOps = true; 3621 3622 // Both GT and GE are ordered comparisons, and return false for 'unordered'. 3623 // If we have an unordered opcode, we need to swap the operands to the VSEL 3624 // instruction (effectively negating the condition). 3625 // 3626 // This also has the effect of swapping which one of 'less' or 'greater' 3627 // returns true, so we also swap the compare operands. It also switches 3628 // whether we return true for 'equality', so we compensate by picking the 3629 // opposite condition code to our original choice. 3630 if (CC == ISD::SETULE || CC == ISD::SETULT || CC == ISD::SETUGE || 3631 CC == ISD::SETUGT) { 3632 swpCmpOps = !swpCmpOps; 3633 swpVselOps = !swpVselOps; 3634 CondCode = CondCode == ARMCC::GT ? ARMCC::GE : ARMCC::GT; 3635 } 3636 3637 // 'ordered' is 'anything but unordered', so use the VS condition code and 3638 // swap the VSEL operands. 3639 if (CC == ISD::SETO) { 3640 CondCode = ARMCC::VS; 3641 swpVselOps = true; 3642 } 3643 3644 // 'unordered or not equal' is 'anything but equal', so use the EQ condition 3645 // code and swap the VSEL operands. 3646 if (CC == ISD::SETUNE) { 3647 CondCode = ARMCC::EQ; 3648 swpVselOps = true; 3649 } 3650 } 3651 3652 SDValue ARMTargetLowering::getCMOV(SDLoc dl, EVT VT, SDValue FalseVal, 3653 SDValue TrueVal, SDValue ARMcc, SDValue CCR, 3654 SDValue Cmp, SelectionDAG &DAG) const { 3655 if (Subtarget->isFPOnlySP() && VT == MVT::f64) { 3656 FalseVal = DAG.getNode(ARMISD::VMOVRRD, dl, 3657 DAG.getVTList(MVT::i32, MVT::i32), FalseVal); 3658 TrueVal = DAG.getNode(ARMISD::VMOVRRD, dl, 3659 DAG.getVTList(MVT::i32, MVT::i32), TrueVal); 3660 3661 SDValue TrueLow = TrueVal.getValue(0); 3662 SDValue TrueHigh = TrueVal.getValue(1); 3663 SDValue FalseLow = FalseVal.getValue(0); 3664 SDValue FalseHigh = FalseVal.getValue(1); 3665 3666 SDValue Low = DAG.getNode(ARMISD::CMOV, dl, MVT::i32, FalseLow, TrueLow, 3667 ARMcc, CCR, Cmp); 3668 SDValue High = DAG.getNode(ARMISD::CMOV, dl, MVT::i32, FalseHigh, TrueHigh, 3669 ARMcc, CCR, duplicateCmp(Cmp, DAG)); 3670 3671 return DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Low, High); 3672 } else { 3673 return DAG.getNode(ARMISD::CMOV, dl, VT, FalseVal, TrueVal, ARMcc, CCR, 3674 Cmp); 3675 } 3676 } 3677 3678 SDValue ARMTargetLowering::LowerSELECT_CC(SDValue Op, SelectionDAG &DAG) const { 3679 EVT VT = Op.getValueType(); 3680 SDValue LHS = Op.getOperand(0); 3681 SDValue RHS = Op.getOperand(1); 3682 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(4))->get(); 3683 SDValue TrueVal = Op.getOperand(2); 3684 SDValue FalseVal = Op.getOperand(3); 3685 SDLoc dl(Op); 3686 3687 if (Subtarget->isFPOnlySP() && LHS.getValueType() == MVT::f64) { 3688 DAG.getTargetLoweringInfo().softenSetCCOperands(DAG, MVT::f64, LHS, RHS, CC, 3689 dl); 3690 3691 // If softenSetCCOperands only returned one value, we should compare it to 3692 // zero. 3693 if (!RHS.getNode()) { 3694 RHS = DAG.getConstant(0, dl, LHS.getValueType()); 3695 CC = ISD::SETNE; 3696 } 3697 } 3698 3699 if (LHS.getValueType() == MVT::i32) { 3700 // Try to generate VSEL on ARMv8. 3701 // The VSEL instruction can't use all the usual ARM condition 3702 // codes: it only has two bits to select the condition code, so it's 3703 // constrained to use only GE, GT, VS and EQ. 3704 // 3705 // To implement all the various ISD::SETXXX opcodes, we sometimes need to 3706 // swap the operands of the previous compare instruction (effectively 3707 // inverting the compare condition, swapping 'less' and 'greater') and 3708 // sometimes need to swap the operands to the VSEL (which inverts the 3709 // condition in the sense of firing whenever the previous condition didn't) 3710 if (Subtarget->hasFPARMv8() && (TrueVal.getValueType() == MVT::f32 || 3711 TrueVal.getValueType() == MVT::f64)) { 3712 ARMCC::CondCodes CondCode = IntCCToARMCC(CC); 3713 if (CondCode == ARMCC::LT || CondCode == ARMCC::LE || 3714 CondCode == ARMCC::VC || CondCode == ARMCC::NE) { 3715 CC = ISD::getSetCCInverse(CC, true); 3716 std::swap(TrueVal, FalseVal); 3717 } 3718 } 3719 3720 SDValue ARMcc; 3721 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32); 3722 SDValue Cmp = getARMCmp(LHS, RHS, CC, ARMcc, DAG, dl); 3723 return getCMOV(dl, VT, FalseVal, TrueVal, ARMcc, CCR, Cmp, DAG); 3724 } 3725 3726 ARMCC::CondCodes CondCode, CondCode2; 3727 FPCCToARMCC(CC, CondCode, CondCode2); 3728 3729 // Try to generate VMAXNM/VMINNM on ARMv8. 3730 if (Subtarget->hasFPARMv8() && (TrueVal.getValueType() == MVT::f32 || 3731 TrueVal.getValueType() == MVT::f64)) { 3732 bool swpCmpOps = false; 3733 bool swpVselOps = false; 3734 checkVSELConstraints(CC, CondCode, swpCmpOps, swpVselOps); 3735 3736 if (CondCode == ARMCC::GT || CondCode == ARMCC::GE || 3737 CondCode == ARMCC::VS || CondCode == ARMCC::EQ) { 3738 if (swpCmpOps) 3739 std::swap(LHS, RHS); 3740 if (swpVselOps) 3741 std::swap(TrueVal, FalseVal); 3742 } 3743 } 3744 3745 SDValue ARMcc = DAG.getConstant(CondCode, dl, MVT::i32); 3746 SDValue Cmp = getVFPCmp(LHS, RHS, DAG, dl); 3747 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32); 3748 SDValue Result = getCMOV(dl, VT, FalseVal, TrueVal, ARMcc, CCR, Cmp, DAG); 3749 if (CondCode2 != ARMCC::AL) { 3750 SDValue ARMcc2 = DAG.getConstant(CondCode2, dl, MVT::i32); 3751 // FIXME: Needs another CMP because flag can have but one use. 3752 SDValue Cmp2 = getVFPCmp(LHS, RHS, DAG, dl); 3753 Result = getCMOV(dl, VT, Result, TrueVal, ARMcc2, CCR, Cmp2, DAG); 3754 } 3755 return Result; 3756 } 3757 3758 /// canChangeToInt - Given the fp compare operand, return true if it is suitable 3759 /// to morph to an integer compare sequence. 3760 static bool canChangeToInt(SDValue Op, bool &SeenZero, 3761 const ARMSubtarget *Subtarget) { 3762 SDNode *N = Op.getNode(); 3763 if (!N->hasOneUse()) 3764 // Otherwise it requires moving the value from fp to integer registers. 3765 return false; 3766 if (!N->getNumValues()) 3767 return false; 3768 EVT VT = Op.getValueType(); 3769 if (VT != MVT::f32 && !Subtarget->isFPBrccSlow()) 3770 // f32 case is generally profitable. f64 case only makes sense when vcmpe + 3771 // vmrs are very slow, e.g. cortex-a8. 3772 return false; 3773 3774 if (isFloatingPointZero(Op)) { 3775 SeenZero = true; 3776 return true; 3777 } 3778 return ISD::isNormalLoad(N); 3779 } 3780 3781 static SDValue bitcastf32Toi32(SDValue Op, SelectionDAG &DAG) { 3782 if (isFloatingPointZero(Op)) 3783 return DAG.getConstant(0, SDLoc(Op), MVT::i32); 3784 3785 if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Op)) 3786 return DAG.getLoad(MVT::i32, SDLoc(Op), 3787 Ld->getChain(), Ld->getBasePtr(), Ld->getPointerInfo(), 3788 Ld->isVolatile(), Ld->isNonTemporal(), 3789 Ld->isInvariant(), Ld->getAlignment()); 3790 3791 llvm_unreachable("Unknown VFP cmp argument!"); 3792 } 3793 3794 static void expandf64Toi32(SDValue Op, SelectionDAG &DAG, 3795 SDValue &RetVal1, SDValue &RetVal2) { 3796 SDLoc dl(Op); 3797 3798 if (isFloatingPointZero(Op)) { 3799 RetVal1 = DAG.getConstant(0, dl, MVT::i32); 3800 RetVal2 = DAG.getConstant(0, dl, MVT::i32); 3801 return; 3802 } 3803 3804 if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Op)) { 3805 SDValue Ptr = Ld->getBasePtr(); 3806 RetVal1 = DAG.getLoad(MVT::i32, dl, 3807 Ld->getChain(), Ptr, 3808 Ld->getPointerInfo(), 3809 Ld->isVolatile(), Ld->isNonTemporal(), 3810 Ld->isInvariant(), Ld->getAlignment()); 3811 3812 EVT PtrType = Ptr.getValueType(); 3813 unsigned NewAlign = MinAlign(Ld->getAlignment(), 4); 3814 SDValue NewPtr = DAG.getNode(ISD::ADD, dl, 3815 PtrType, Ptr, DAG.getConstant(4, dl, PtrType)); 3816 RetVal2 = DAG.getLoad(MVT::i32, dl, 3817 Ld->getChain(), NewPtr, 3818 Ld->getPointerInfo().getWithOffset(4), 3819 Ld->isVolatile(), Ld->isNonTemporal(), 3820 Ld->isInvariant(), NewAlign); 3821 return; 3822 } 3823 3824 llvm_unreachable("Unknown VFP cmp argument!"); 3825 } 3826 3827 /// OptimizeVFPBrcond - With -enable-unsafe-fp-math, it's legal to optimize some 3828 /// f32 and even f64 comparisons to integer ones. 3829 SDValue 3830 ARMTargetLowering::OptimizeVFPBrcond(SDValue Op, SelectionDAG &DAG) const { 3831 SDValue Chain = Op.getOperand(0); 3832 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(1))->get(); 3833 SDValue LHS = Op.getOperand(2); 3834 SDValue RHS = Op.getOperand(3); 3835 SDValue Dest = Op.getOperand(4); 3836 SDLoc dl(Op); 3837 3838 bool LHSSeenZero = false; 3839 bool LHSOk = canChangeToInt(LHS, LHSSeenZero, Subtarget); 3840 bool RHSSeenZero = false; 3841 bool RHSOk = canChangeToInt(RHS, RHSSeenZero, Subtarget); 3842 if (LHSOk && RHSOk && (LHSSeenZero || RHSSeenZero)) { 3843 // If unsafe fp math optimization is enabled and there are no other uses of 3844 // the CMP operands, and the condition code is EQ or NE, we can optimize it 3845 // to an integer comparison. 3846 if (CC == ISD::SETOEQ) 3847 CC = ISD::SETEQ; 3848 else if (CC == ISD::SETUNE) 3849 CC = ISD::SETNE; 3850 3851 SDValue Mask = DAG.getConstant(0x7fffffff, dl, MVT::i32); 3852 SDValue ARMcc; 3853 if (LHS.getValueType() == MVT::f32) { 3854 LHS = DAG.getNode(ISD::AND, dl, MVT::i32, 3855 bitcastf32Toi32(LHS, DAG), Mask); 3856 RHS = DAG.getNode(ISD::AND, dl, MVT::i32, 3857 bitcastf32Toi32(RHS, DAG), Mask); 3858 SDValue Cmp = getARMCmp(LHS, RHS, CC, ARMcc, DAG, dl); 3859 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32); 3860 return DAG.getNode(ARMISD::BRCOND, dl, MVT::Other, 3861 Chain, Dest, ARMcc, CCR, Cmp); 3862 } 3863 3864 SDValue LHS1, LHS2; 3865 SDValue RHS1, RHS2; 3866 expandf64Toi32(LHS, DAG, LHS1, LHS2); 3867 expandf64Toi32(RHS, DAG, RHS1, RHS2); 3868 LHS2 = DAG.getNode(ISD::AND, dl, MVT::i32, LHS2, Mask); 3869 RHS2 = DAG.getNode(ISD::AND, dl, MVT::i32, RHS2, Mask); 3870 ARMCC::CondCodes CondCode = IntCCToARMCC(CC); 3871 ARMcc = DAG.getConstant(CondCode, dl, MVT::i32); 3872 SDVTList VTList = DAG.getVTList(MVT::Other, MVT::Glue); 3873 SDValue Ops[] = { Chain, ARMcc, LHS1, LHS2, RHS1, RHS2, Dest }; 3874 return DAG.getNode(ARMISD::BCC_i64, dl, VTList, Ops); 3875 } 3876 3877 return SDValue(); 3878 } 3879 3880 SDValue ARMTargetLowering::LowerBR_CC(SDValue Op, SelectionDAG &DAG) const { 3881 SDValue Chain = Op.getOperand(0); 3882 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(1))->get(); 3883 SDValue LHS = Op.getOperand(2); 3884 SDValue RHS = Op.getOperand(3); 3885 SDValue Dest = Op.getOperand(4); 3886 SDLoc dl(Op); 3887 3888 if (Subtarget->isFPOnlySP() && LHS.getValueType() == MVT::f64) { 3889 DAG.getTargetLoweringInfo().softenSetCCOperands(DAG, MVT::f64, LHS, RHS, CC, 3890 dl); 3891 3892 // If softenSetCCOperands only returned one value, we should compare it to 3893 // zero. 3894 if (!RHS.getNode()) { 3895 RHS = DAG.getConstant(0, dl, LHS.getValueType()); 3896 CC = ISD::SETNE; 3897 } 3898 } 3899 3900 if (LHS.getValueType() == MVT::i32) { 3901 SDValue ARMcc; 3902 SDValue Cmp = getARMCmp(LHS, RHS, CC, ARMcc, DAG, dl); 3903 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32); 3904 return DAG.getNode(ARMISD::BRCOND, dl, MVT::Other, 3905 Chain, Dest, ARMcc, CCR, Cmp); 3906 } 3907 3908 assert(LHS.getValueType() == MVT::f32 || LHS.getValueType() == MVT::f64); 3909 3910 if (getTargetMachine().Options.UnsafeFPMath && 3911 (CC == ISD::SETEQ || CC == ISD::SETOEQ || 3912 CC == ISD::SETNE || CC == ISD::SETUNE)) { 3913 SDValue Result = OptimizeVFPBrcond(Op, DAG); 3914 if (Result.getNode()) 3915 return Result; 3916 } 3917 3918 ARMCC::CondCodes CondCode, CondCode2; 3919 FPCCToARMCC(CC, CondCode, CondCode2); 3920 3921 SDValue ARMcc = DAG.getConstant(CondCode, dl, MVT::i32); 3922 SDValue Cmp = getVFPCmp(LHS, RHS, DAG, dl); 3923 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32); 3924 SDVTList VTList = DAG.getVTList(MVT::Other, MVT::Glue); 3925 SDValue Ops[] = { Chain, Dest, ARMcc, CCR, Cmp }; 3926 SDValue Res = DAG.getNode(ARMISD::BRCOND, dl, VTList, Ops); 3927 if (CondCode2 != ARMCC::AL) { 3928 ARMcc = DAG.getConstant(CondCode2, dl, MVT::i32); 3929 SDValue Ops[] = { Res, Dest, ARMcc, CCR, Res.getValue(1) }; 3930 Res = DAG.getNode(ARMISD::BRCOND, dl, VTList, Ops); 3931 } 3932 return Res; 3933 } 3934 3935 SDValue ARMTargetLowering::LowerBR_JT(SDValue Op, SelectionDAG &DAG) const { 3936 SDValue Chain = Op.getOperand(0); 3937 SDValue Table = Op.getOperand(1); 3938 SDValue Index = Op.getOperand(2); 3939 SDLoc dl(Op); 3940 3941 EVT PTy = getPointerTy(DAG.getDataLayout()); 3942 JumpTableSDNode *JT = cast<JumpTableSDNode>(Table); 3943 SDValue JTI = DAG.getTargetJumpTable(JT->getIndex(), PTy); 3944 Table = DAG.getNode(ARMISD::WrapperJT, dl, MVT::i32, JTI); 3945 Index = DAG.getNode(ISD::MUL, dl, PTy, Index, DAG.getConstant(4, dl, PTy)); 3946 SDValue Addr = DAG.getNode(ISD::ADD, dl, PTy, Index, Table); 3947 if (Subtarget->isThumb2()) { 3948 // Thumb2 uses a two-level jump. That is, it jumps into the jump table 3949 // which does another jump to the destination. This also makes it easier 3950 // to translate it to TBB / TBH later. 3951 // FIXME: This might not work if the function is extremely large. 3952 return DAG.getNode(ARMISD::BR2_JT, dl, MVT::Other, Chain, 3953 Addr, Op.getOperand(2), JTI); 3954 } 3955 if (getTargetMachine().getRelocationModel() == Reloc::PIC_) { 3956 Addr = 3957 DAG.getLoad((EVT)MVT::i32, dl, Chain, Addr, 3958 MachinePointerInfo::getJumpTable(DAG.getMachineFunction()), 3959 false, false, false, 0); 3960 Chain = Addr.getValue(1); 3961 Addr = DAG.getNode(ISD::ADD, dl, PTy, Addr, Table); 3962 return DAG.getNode(ARMISD::BR_JT, dl, MVT::Other, Chain, Addr, JTI); 3963 } else { 3964 Addr = 3965 DAG.getLoad(PTy, dl, Chain, Addr, 3966 MachinePointerInfo::getJumpTable(DAG.getMachineFunction()), 3967 false, false, false, 0); 3968 Chain = Addr.getValue(1); 3969 return DAG.getNode(ARMISD::BR_JT, dl, MVT::Other, Chain, Addr, JTI); 3970 } 3971 } 3972 3973 static SDValue LowerVectorFP_TO_INT(SDValue Op, SelectionDAG &DAG) { 3974 EVT VT = Op.getValueType(); 3975 SDLoc dl(Op); 3976 3977 if (Op.getValueType().getVectorElementType() == MVT::i32) { 3978 if (Op.getOperand(0).getValueType().getVectorElementType() == MVT::f32) 3979 return Op; 3980 return DAG.UnrollVectorOp(Op.getNode()); 3981 } 3982 3983 assert(Op.getOperand(0).getValueType() == MVT::v4f32 && 3984 "Invalid type for custom lowering!"); 3985 if (VT != MVT::v4i16) 3986 return DAG.UnrollVectorOp(Op.getNode()); 3987 3988 Op = DAG.getNode(Op.getOpcode(), dl, MVT::v4i32, Op.getOperand(0)); 3989 return DAG.getNode(ISD::TRUNCATE, dl, VT, Op); 3990 } 3991 3992 SDValue ARMTargetLowering::LowerFP_TO_INT(SDValue Op, SelectionDAG &DAG) const { 3993 EVT VT = Op.getValueType(); 3994 if (VT.isVector()) 3995 return LowerVectorFP_TO_INT(Op, DAG); 3996 if (Subtarget->isFPOnlySP() && Op.getOperand(0).getValueType() == MVT::f64) { 3997 RTLIB::Libcall LC; 3998 if (Op.getOpcode() == ISD::FP_TO_SINT) 3999 LC = RTLIB::getFPTOSINT(Op.getOperand(0).getValueType(), 4000 Op.getValueType()); 4001 else 4002 LC = RTLIB::getFPTOUINT(Op.getOperand(0).getValueType(), 4003 Op.getValueType()); 4004 return makeLibCall(DAG, LC, Op.getValueType(), Op.getOperand(0), 4005 /*isSigned*/ false, SDLoc(Op)).first; 4006 } 4007 4008 return Op; 4009 } 4010 4011 static SDValue LowerVectorINT_TO_FP(SDValue Op, SelectionDAG &DAG) { 4012 EVT VT = Op.getValueType(); 4013 SDLoc dl(Op); 4014 4015 if (Op.getOperand(0).getValueType().getVectorElementType() == MVT::i32) { 4016 if (VT.getVectorElementType() == MVT::f32) 4017 return Op; 4018 return DAG.UnrollVectorOp(Op.getNode()); 4019 } 4020 4021 assert(Op.getOperand(0).getValueType() == MVT::v4i16 && 4022 "Invalid type for custom lowering!"); 4023 if (VT != MVT::v4f32) 4024 return DAG.UnrollVectorOp(Op.getNode()); 4025 4026 unsigned CastOpc; 4027 unsigned Opc; 4028 switch (Op.getOpcode()) { 4029 default: llvm_unreachable("Invalid opcode!"); 4030 case ISD::SINT_TO_FP: 4031 CastOpc = ISD::SIGN_EXTEND; 4032 Opc = ISD::SINT_TO_FP; 4033 break; 4034 case ISD::UINT_TO_FP: 4035 CastOpc = ISD::ZERO_EXTEND; 4036 Opc = ISD::UINT_TO_FP; 4037 break; 4038 } 4039 4040 Op = DAG.getNode(CastOpc, dl, MVT::v4i32, Op.getOperand(0)); 4041 return DAG.getNode(Opc, dl, VT, Op); 4042 } 4043 4044 SDValue ARMTargetLowering::LowerINT_TO_FP(SDValue Op, SelectionDAG &DAG) const { 4045 EVT VT = Op.getValueType(); 4046 if (VT.isVector()) 4047 return LowerVectorINT_TO_FP(Op, DAG); 4048 if (Subtarget->isFPOnlySP() && Op.getValueType() == MVT::f64) { 4049 RTLIB::Libcall LC; 4050 if (Op.getOpcode() == ISD::SINT_TO_FP) 4051 LC = RTLIB::getSINTTOFP(Op.getOperand(0).getValueType(), 4052 Op.getValueType()); 4053 else 4054 LC = RTLIB::getUINTTOFP(Op.getOperand(0).getValueType(), 4055 Op.getValueType()); 4056 return makeLibCall(DAG, LC, Op.getValueType(), Op.getOperand(0), 4057 /*isSigned*/ false, SDLoc(Op)).first; 4058 } 4059 4060 return Op; 4061 } 4062 4063 SDValue ARMTargetLowering::LowerFCOPYSIGN(SDValue Op, SelectionDAG &DAG) const { 4064 // Implement fcopysign with a fabs and a conditional fneg. 4065 SDValue Tmp0 = Op.getOperand(0); 4066 SDValue Tmp1 = Op.getOperand(1); 4067 SDLoc dl(Op); 4068 EVT VT = Op.getValueType(); 4069 EVT SrcVT = Tmp1.getValueType(); 4070 bool InGPR = Tmp0.getOpcode() == ISD::BITCAST || 4071 Tmp0.getOpcode() == ARMISD::VMOVDRR; 4072 bool UseNEON = !InGPR && Subtarget->hasNEON(); 4073 4074 if (UseNEON) { 4075 // Use VBSL to copy the sign bit. 4076 unsigned EncodedVal = ARM_AM::createNEONModImm(0x6, 0x80); 4077 SDValue Mask = DAG.getNode(ARMISD::VMOVIMM, dl, MVT::v2i32, 4078 DAG.getTargetConstant(EncodedVal, dl, MVT::i32)); 4079 EVT OpVT = (VT == MVT::f32) ? MVT::v2i32 : MVT::v1i64; 4080 if (VT == MVT::f64) 4081 Mask = DAG.getNode(ARMISD::VSHL, dl, OpVT, 4082 DAG.getNode(ISD::BITCAST, dl, OpVT, Mask), 4083 DAG.getConstant(32, dl, MVT::i32)); 4084 else /*if (VT == MVT::f32)*/ 4085 Tmp0 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f32, Tmp0); 4086 if (SrcVT == MVT::f32) { 4087 Tmp1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f32, Tmp1); 4088 if (VT == MVT::f64) 4089 Tmp1 = DAG.getNode(ARMISD::VSHL, dl, OpVT, 4090 DAG.getNode(ISD::BITCAST, dl, OpVT, Tmp1), 4091 DAG.getConstant(32, dl, MVT::i32)); 4092 } else if (VT == MVT::f32) 4093 Tmp1 = DAG.getNode(ARMISD::VSHRu, dl, MVT::v1i64, 4094 DAG.getNode(ISD::BITCAST, dl, MVT::v1i64, Tmp1), 4095 DAG.getConstant(32, dl, MVT::i32)); 4096 Tmp0 = DAG.getNode(ISD::BITCAST, dl, OpVT, Tmp0); 4097 Tmp1 = DAG.getNode(ISD::BITCAST, dl, OpVT, Tmp1); 4098 4099 SDValue AllOnes = DAG.getTargetConstant(ARM_AM::createNEONModImm(0xe, 0xff), 4100 dl, MVT::i32); 4101 AllOnes = DAG.getNode(ARMISD::VMOVIMM, dl, MVT::v8i8, AllOnes); 4102 SDValue MaskNot = DAG.getNode(ISD::XOR, dl, OpVT, Mask, 4103 DAG.getNode(ISD::BITCAST, dl, OpVT, AllOnes)); 4104 4105 SDValue Res = DAG.getNode(ISD::OR, dl, OpVT, 4106 DAG.getNode(ISD::AND, dl, OpVT, Tmp1, Mask), 4107 DAG.getNode(ISD::AND, dl, OpVT, Tmp0, MaskNot)); 4108 if (VT == MVT::f32) { 4109 Res = DAG.getNode(ISD::BITCAST, dl, MVT::v2f32, Res); 4110 Res = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f32, Res, 4111 DAG.getConstant(0, dl, MVT::i32)); 4112 } else { 4113 Res = DAG.getNode(ISD::BITCAST, dl, MVT::f64, Res); 4114 } 4115 4116 return Res; 4117 } 4118 4119 // Bitcast operand 1 to i32. 4120 if (SrcVT == MVT::f64) 4121 Tmp1 = DAG.getNode(ARMISD::VMOVRRD, dl, DAG.getVTList(MVT::i32, MVT::i32), 4122 Tmp1).getValue(1); 4123 Tmp1 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Tmp1); 4124 4125 // Or in the signbit with integer operations. 4126 SDValue Mask1 = DAG.getConstant(0x80000000, dl, MVT::i32); 4127 SDValue Mask2 = DAG.getConstant(0x7fffffff, dl, MVT::i32); 4128 Tmp1 = DAG.getNode(ISD::AND, dl, MVT::i32, Tmp1, Mask1); 4129 if (VT == MVT::f32) { 4130 Tmp0 = DAG.getNode(ISD::AND, dl, MVT::i32, 4131 DAG.getNode(ISD::BITCAST, dl, MVT::i32, Tmp0), Mask2); 4132 return DAG.getNode(ISD::BITCAST, dl, MVT::f32, 4133 DAG.getNode(ISD::OR, dl, MVT::i32, Tmp0, Tmp1)); 4134 } 4135 4136 // f64: Or the high part with signbit and then combine two parts. 4137 Tmp0 = DAG.getNode(ARMISD::VMOVRRD, dl, DAG.getVTList(MVT::i32, MVT::i32), 4138 Tmp0); 4139 SDValue Lo = Tmp0.getValue(0); 4140 SDValue Hi = DAG.getNode(ISD::AND, dl, MVT::i32, Tmp0.getValue(1), Mask2); 4141 Hi = DAG.getNode(ISD::OR, dl, MVT::i32, Hi, Tmp1); 4142 return DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi); 4143 } 4144 4145 SDValue ARMTargetLowering::LowerRETURNADDR(SDValue Op, SelectionDAG &DAG) const{ 4146 MachineFunction &MF = DAG.getMachineFunction(); 4147 MachineFrameInfo *MFI = MF.getFrameInfo(); 4148 MFI->setReturnAddressIsTaken(true); 4149 4150 if (verifyReturnAddressArgumentIsConstant(Op, DAG)) 4151 return SDValue(); 4152 4153 EVT VT = Op.getValueType(); 4154 SDLoc dl(Op); 4155 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue(); 4156 if (Depth) { 4157 SDValue FrameAddr = LowerFRAMEADDR(Op, DAG); 4158 SDValue Offset = DAG.getConstant(4, dl, MVT::i32); 4159 return DAG.getLoad(VT, dl, DAG.getEntryNode(), 4160 DAG.getNode(ISD::ADD, dl, VT, FrameAddr, Offset), 4161 MachinePointerInfo(), false, false, false, 0); 4162 } 4163 4164 // Return LR, which contains the return address. Mark it an implicit live-in. 4165 unsigned Reg = MF.addLiveIn(ARM::LR, getRegClassFor(MVT::i32)); 4166 return DAG.getCopyFromReg(DAG.getEntryNode(), dl, Reg, VT); 4167 } 4168 4169 SDValue ARMTargetLowering::LowerFRAMEADDR(SDValue Op, SelectionDAG &DAG) const { 4170 const ARMBaseRegisterInfo &ARI = 4171 *static_cast<const ARMBaseRegisterInfo*>(RegInfo); 4172 MachineFunction &MF = DAG.getMachineFunction(); 4173 MachineFrameInfo *MFI = MF.getFrameInfo(); 4174 MFI->setFrameAddressIsTaken(true); 4175 4176 EVT VT = Op.getValueType(); 4177 SDLoc dl(Op); // FIXME probably not meaningful 4178 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue(); 4179 unsigned FrameReg = ARI.getFrameRegister(MF); 4180 SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, VT); 4181 while (Depth--) 4182 FrameAddr = DAG.getLoad(VT, dl, DAG.getEntryNode(), FrameAddr, 4183 MachinePointerInfo(), 4184 false, false, false, 0); 4185 return FrameAddr; 4186 } 4187 4188 // FIXME? Maybe this could be a TableGen attribute on some registers and 4189 // this table could be generated automatically from RegInfo. 4190 unsigned ARMTargetLowering::getRegisterByName(const char* RegName, EVT VT, 4191 SelectionDAG &DAG) const { 4192 unsigned Reg = StringSwitch<unsigned>(RegName) 4193 .Case("sp", ARM::SP) 4194 .Default(0); 4195 if (Reg) 4196 return Reg; 4197 report_fatal_error(Twine("Invalid register name \"" 4198 + StringRef(RegName) + "\".")); 4199 } 4200 4201 // Result is 64 bit value so split into two 32 bit values and return as a 4202 // pair of values. 4203 static void ExpandREAD_REGISTER(SDNode *N, SmallVectorImpl<SDValue> &Results, 4204 SelectionDAG &DAG) { 4205 SDLoc DL(N); 4206 4207 // This function is only supposed to be called for i64 type destination. 4208 assert(N->getValueType(0) == MVT::i64 4209 && "ExpandREAD_REGISTER called for non-i64 type result."); 4210 4211 SDValue Read = DAG.getNode(ISD::READ_REGISTER, DL, 4212 DAG.getVTList(MVT::i32, MVT::i32, MVT::Other), 4213 N->getOperand(0), 4214 N->getOperand(1)); 4215 4216 Results.push_back(DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, Read.getValue(0), 4217 Read.getValue(1))); 4218 Results.push_back(Read.getOperand(0)); 4219 } 4220 4221 /// \p BC is a bitcast that is about to be turned into a VMOVDRR. 4222 /// When \p DstVT, the destination type of \p BC, is on the vector 4223 /// register bank and the source of bitcast, \p Op, operates on the same bank, 4224 /// it might be possible to combine them, such that everything stays on the 4225 /// vector register bank. 4226 /// \p return The node that would replace \p BT, if the combine 4227 /// is possible. 4228 static SDValue CombineVMOVDRRCandidateWithVecOp(const SDNode *BC, 4229 SelectionDAG &DAG) { 4230 SDValue Op = BC->getOperand(0); 4231 EVT DstVT = BC->getValueType(0); 4232 4233 // The only vector instruction that can produce a scalar (remember, 4234 // since the bitcast was about to be turned into VMOVDRR, the source 4235 // type is i64) from a vector is EXTRACT_VECTOR_ELT. 4236 // Moreover, we can do this combine only if there is one use. 4237 // Finally, if the destination type is not a vector, there is not 4238 // much point on forcing everything on the vector bank. 4239 if (!DstVT.isVector() || Op.getOpcode() != ISD::EXTRACT_VECTOR_ELT || 4240 !Op.hasOneUse()) 4241 return SDValue(); 4242 4243 // If the index is not constant, we will introduce an additional 4244 // multiply that will stick. 4245 // Give up in that case. 4246 ConstantSDNode *Index = dyn_cast<ConstantSDNode>(Op.getOperand(1)); 4247 if (!Index) 4248 return SDValue(); 4249 unsigned DstNumElt = DstVT.getVectorNumElements(); 4250 4251 // Compute the new index. 4252 const APInt &APIntIndex = Index->getAPIntValue(); 4253 APInt NewIndex(APIntIndex.getBitWidth(), DstNumElt); 4254 NewIndex *= APIntIndex; 4255 // Check if the new constant index fits into i32. 4256 if (NewIndex.getBitWidth() > 32) 4257 return SDValue(); 4258 4259 // vMTy bitcast(i64 extractelt vNi64 src, i32 index) -> 4260 // vMTy extractsubvector vNxMTy (bitcast vNi64 src), i32 index*M) 4261 SDLoc dl(Op); 4262 SDValue ExtractSrc = Op.getOperand(0); 4263 EVT VecVT = EVT::getVectorVT( 4264 *DAG.getContext(), DstVT.getScalarType(), 4265 ExtractSrc.getValueType().getVectorNumElements() * DstNumElt); 4266 SDValue BitCast = DAG.getNode(ISD::BITCAST, dl, VecVT, ExtractSrc); 4267 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DstVT, BitCast, 4268 DAG.getConstant(NewIndex.getZExtValue(), dl, MVT::i32)); 4269 } 4270 4271 /// ExpandBITCAST - If the target supports VFP, this function is called to 4272 /// expand a bit convert where either the source or destination type is i64 to 4273 /// use a VMOVDRR or VMOVRRD node. This should not be done when the non-i64 4274 /// operand type is illegal (e.g., v2f32 for a target that doesn't support 4275 /// vectors), since the legalizer won't know what to do with that. 4276 static SDValue ExpandBITCAST(SDNode *N, SelectionDAG &DAG) { 4277 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 4278 SDLoc dl(N); 4279 SDValue Op = N->getOperand(0); 4280 4281 // This function is only supposed to be called for i64 types, either as the 4282 // source or destination of the bit convert. 4283 EVT SrcVT = Op.getValueType(); 4284 EVT DstVT = N->getValueType(0); 4285 assert((SrcVT == MVT::i64 || DstVT == MVT::i64) && 4286 "ExpandBITCAST called for non-i64 type"); 4287 4288 // Turn i64->f64 into VMOVDRR. 4289 if (SrcVT == MVT::i64 && TLI.isTypeLegal(DstVT)) { 4290 // Do not force values to GPRs (this is what VMOVDRR does for the inputs) 4291 // if we can combine the bitcast with its source. 4292 if (SDValue Val = CombineVMOVDRRCandidateWithVecOp(N, DAG)) 4293 return Val; 4294 4295 SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, Op, 4296 DAG.getConstant(0, dl, MVT::i32)); 4297 SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, Op, 4298 DAG.getConstant(1, dl, MVT::i32)); 4299 return DAG.getNode(ISD::BITCAST, dl, DstVT, 4300 DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi)); 4301 } 4302 4303 // Turn f64->i64 into VMOVRRD. 4304 if (DstVT == MVT::i64 && TLI.isTypeLegal(SrcVT)) { 4305 SDValue Cvt; 4306 if (DAG.getDataLayout().isBigEndian() && SrcVT.isVector() && 4307 SrcVT.getVectorNumElements() > 1) 4308 Cvt = DAG.getNode(ARMISD::VMOVRRD, dl, 4309 DAG.getVTList(MVT::i32, MVT::i32), 4310 DAG.getNode(ARMISD::VREV64, dl, SrcVT, Op)); 4311 else 4312 Cvt = DAG.getNode(ARMISD::VMOVRRD, dl, 4313 DAG.getVTList(MVT::i32, MVT::i32), Op); 4314 // Merge the pieces into a single i64 value. 4315 return DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Cvt, Cvt.getValue(1)); 4316 } 4317 4318 return SDValue(); 4319 } 4320 4321 /// getZeroVector - Returns a vector of specified type with all zero elements. 4322 /// Zero vectors are used to represent vector negation and in those cases 4323 /// will be implemented with the NEON VNEG instruction. However, VNEG does 4324 /// not support i64 elements, so sometimes the zero vectors will need to be 4325 /// explicitly constructed. Regardless, use a canonical VMOV to create the 4326 /// zero vector. 4327 static SDValue getZeroVector(EVT VT, SelectionDAG &DAG, SDLoc dl) { 4328 assert(VT.isVector() && "Expected a vector type"); 4329 // The canonical modified immediate encoding of a zero vector is....0! 4330 SDValue EncodedVal = DAG.getTargetConstant(0, dl, MVT::i32); 4331 EVT VmovVT = VT.is128BitVector() ? MVT::v4i32 : MVT::v2i32; 4332 SDValue Vmov = DAG.getNode(ARMISD::VMOVIMM, dl, VmovVT, EncodedVal); 4333 return DAG.getNode(ISD::BITCAST, dl, VT, Vmov); 4334 } 4335 4336 /// LowerShiftRightParts - Lower SRA_PARTS, which returns two 4337 /// i32 values and take a 2 x i32 value to shift plus a shift amount. 4338 SDValue ARMTargetLowering::LowerShiftRightParts(SDValue Op, 4339 SelectionDAG &DAG) const { 4340 assert(Op.getNumOperands() == 3 && "Not a double-shift!"); 4341 EVT VT = Op.getValueType(); 4342 unsigned VTBits = VT.getSizeInBits(); 4343 SDLoc dl(Op); 4344 SDValue ShOpLo = Op.getOperand(0); 4345 SDValue ShOpHi = Op.getOperand(1); 4346 SDValue ShAmt = Op.getOperand(2); 4347 SDValue ARMcc; 4348 unsigned Opc = (Op.getOpcode() == ISD::SRA_PARTS) ? ISD::SRA : ISD::SRL; 4349 4350 assert(Op.getOpcode() == ISD::SRA_PARTS || Op.getOpcode() == ISD::SRL_PARTS); 4351 4352 SDValue RevShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32, 4353 DAG.getConstant(VTBits, dl, MVT::i32), ShAmt); 4354 SDValue Tmp1 = DAG.getNode(ISD::SRL, dl, VT, ShOpLo, ShAmt); 4355 SDValue ExtraShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32, ShAmt, 4356 DAG.getConstant(VTBits, dl, MVT::i32)); 4357 SDValue Tmp2 = DAG.getNode(ISD::SHL, dl, VT, ShOpHi, RevShAmt); 4358 SDValue FalseVal = DAG.getNode(ISD::OR, dl, VT, Tmp1, Tmp2); 4359 SDValue TrueVal = DAG.getNode(Opc, dl, VT, ShOpHi, ExtraShAmt); 4360 4361 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32); 4362 SDValue Cmp = getARMCmp(ExtraShAmt, DAG.getConstant(0, dl, MVT::i32), 4363 ISD::SETGE, ARMcc, DAG, dl); 4364 SDValue Hi = DAG.getNode(Opc, dl, VT, ShOpHi, ShAmt); 4365 SDValue Lo = DAG.getNode(ARMISD::CMOV, dl, VT, FalseVal, TrueVal, ARMcc, 4366 CCR, Cmp); 4367 4368 SDValue Ops[2] = { Lo, Hi }; 4369 return DAG.getMergeValues(Ops, dl); 4370 } 4371 4372 /// LowerShiftLeftParts - Lower SHL_PARTS, which returns two 4373 /// i32 values and take a 2 x i32 value to shift plus a shift amount. 4374 SDValue ARMTargetLowering::LowerShiftLeftParts(SDValue Op, 4375 SelectionDAG &DAG) const { 4376 assert(Op.getNumOperands() == 3 && "Not a double-shift!"); 4377 EVT VT = Op.getValueType(); 4378 unsigned VTBits = VT.getSizeInBits(); 4379 SDLoc dl(Op); 4380 SDValue ShOpLo = Op.getOperand(0); 4381 SDValue ShOpHi = Op.getOperand(1); 4382 SDValue ShAmt = Op.getOperand(2); 4383 SDValue ARMcc; 4384 4385 assert(Op.getOpcode() == ISD::SHL_PARTS); 4386 SDValue RevShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32, 4387 DAG.getConstant(VTBits, dl, MVT::i32), ShAmt); 4388 SDValue Tmp1 = DAG.getNode(ISD::SRL, dl, VT, ShOpLo, RevShAmt); 4389 SDValue ExtraShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32, ShAmt, 4390 DAG.getConstant(VTBits, dl, MVT::i32)); 4391 SDValue Tmp2 = DAG.getNode(ISD::SHL, dl, VT, ShOpHi, ShAmt); 4392 SDValue Tmp3 = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ExtraShAmt); 4393 4394 SDValue FalseVal = DAG.getNode(ISD::OR, dl, VT, Tmp1, Tmp2); 4395 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32); 4396 SDValue Cmp = getARMCmp(ExtraShAmt, DAG.getConstant(0, dl, MVT::i32), 4397 ISD::SETGE, ARMcc, DAG, dl); 4398 SDValue Lo = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ShAmt); 4399 SDValue Hi = DAG.getNode(ARMISD::CMOV, dl, VT, FalseVal, Tmp3, ARMcc, 4400 CCR, Cmp); 4401 4402 SDValue Ops[2] = { Lo, Hi }; 4403 return DAG.getMergeValues(Ops, dl); 4404 } 4405 4406 SDValue ARMTargetLowering::LowerFLT_ROUNDS_(SDValue Op, 4407 SelectionDAG &DAG) const { 4408 // The rounding mode is in bits 23:22 of the FPSCR. 4409 // The ARM rounding mode value to FLT_ROUNDS mapping is 0->1, 1->2, 2->3, 3->0 4410 // The formula we use to implement this is (((FPSCR + 1 << 22) >> 22) & 3) 4411 // so that the shift + and get folded into a bitfield extract. 4412 SDLoc dl(Op); 4413 SDValue FPSCR = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::i32, 4414 DAG.getConstant(Intrinsic::arm_get_fpscr, dl, 4415 MVT::i32)); 4416 SDValue FltRounds = DAG.getNode(ISD::ADD, dl, MVT::i32, FPSCR, 4417 DAG.getConstant(1U << 22, dl, MVT::i32)); 4418 SDValue RMODE = DAG.getNode(ISD::SRL, dl, MVT::i32, FltRounds, 4419 DAG.getConstant(22, dl, MVT::i32)); 4420 return DAG.getNode(ISD::AND, dl, MVT::i32, RMODE, 4421 DAG.getConstant(3, dl, MVT::i32)); 4422 } 4423 4424 static SDValue LowerCTTZ(SDNode *N, SelectionDAG &DAG, 4425 const ARMSubtarget *ST) { 4426 SDLoc dl(N); 4427 EVT VT = N->getValueType(0); 4428 if (VT.isVector()) { 4429 assert(ST->hasNEON()); 4430 4431 // Compute the least significant set bit: LSB = X & -X 4432 SDValue X = N->getOperand(0); 4433 SDValue NX = DAG.getNode(ISD::SUB, dl, VT, getZeroVector(VT, DAG, dl), X); 4434 SDValue LSB = DAG.getNode(ISD::AND, dl, VT, X, NX); 4435 4436 EVT ElemTy = VT.getVectorElementType(); 4437 4438 if (ElemTy == MVT::i8) { 4439 // Compute with: cttz(x) = ctpop(lsb - 1) 4440 SDValue One = DAG.getNode(ARMISD::VMOVIMM, dl, VT, 4441 DAG.getTargetConstant(1, dl, ElemTy)); 4442 SDValue Bits = DAG.getNode(ISD::SUB, dl, VT, LSB, One); 4443 return DAG.getNode(ISD::CTPOP, dl, VT, Bits); 4444 } 4445 4446 if ((ElemTy == MVT::i16 || ElemTy == MVT::i32) && 4447 (N->getOpcode() == ISD::CTTZ_ZERO_UNDEF)) { 4448 // Compute with: cttz(x) = (width - 1) - ctlz(lsb), if x != 0 4449 unsigned NumBits = ElemTy.getSizeInBits(); 4450 SDValue WidthMinus1 = 4451 DAG.getNode(ARMISD::VMOVIMM, dl, VT, 4452 DAG.getTargetConstant(NumBits - 1, dl, ElemTy)); 4453 SDValue CTLZ = DAG.getNode(ISD::CTLZ, dl, VT, LSB); 4454 return DAG.getNode(ISD::SUB, dl, VT, WidthMinus1, CTLZ); 4455 } 4456 4457 // Compute with: cttz(x) = ctpop(lsb - 1) 4458 4459 // Since we can only compute the number of bits in a byte with vcnt.8, we 4460 // have to gather the result with pairwise addition (vpaddl) for i16, i32, 4461 // and i64. 4462 4463 // Compute LSB - 1. 4464 SDValue Bits; 4465 if (ElemTy == MVT::i64) { 4466 // Load constant 0xffff'ffff'ffff'ffff to register. 4467 SDValue FF = DAG.getNode(ARMISD::VMOVIMM, dl, VT, 4468 DAG.getTargetConstant(0x1eff, dl, MVT::i32)); 4469 Bits = DAG.getNode(ISD::ADD, dl, VT, LSB, FF); 4470 } else { 4471 SDValue One = DAG.getNode(ARMISD::VMOVIMM, dl, VT, 4472 DAG.getTargetConstant(1, dl, ElemTy)); 4473 Bits = DAG.getNode(ISD::SUB, dl, VT, LSB, One); 4474 } 4475 4476 // Count #bits with vcnt.8. 4477 EVT VT8Bit = VT.is64BitVector() ? MVT::v8i8 : MVT::v16i8; 4478 SDValue BitsVT8 = DAG.getNode(ISD::BITCAST, dl, VT8Bit, Bits); 4479 SDValue Cnt8 = DAG.getNode(ISD::CTPOP, dl, VT8Bit, BitsVT8); 4480 4481 // Gather the #bits with vpaddl (pairwise add.) 4482 EVT VT16Bit = VT.is64BitVector() ? MVT::v4i16 : MVT::v8i16; 4483 SDValue Cnt16 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT16Bit, 4484 DAG.getTargetConstant(Intrinsic::arm_neon_vpaddlu, dl, MVT::i32), 4485 Cnt8); 4486 if (ElemTy == MVT::i16) 4487 return Cnt16; 4488 4489 EVT VT32Bit = VT.is64BitVector() ? MVT::v2i32 : MVT::v4i32; 4490 SDValue Cnt32 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT32Bit, 4491 DAG.getTargetConstant(Intrinsic::arm_neon_vpaddlu, dl, MVT::i32), 4492 Cnt16); 4493 if (ElemTy == MVT::i32) 4494 return Cnt32; 4495 4496 assert(ElemTy == MVT::i64); 4497 SDValue Cnt64 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT, 4498 DAG.getTargetConstant(Intrinsic::arm_neon_vpaddlu, dl, MVT::i32), 4499 Cnt32); 4500 return Cnt64; 4501 } 4502 4503 if (!ST->hasV6T2Ops()) 4504 return SDValue(); 4505 4506 SDValue rbit = DAG.getNode(ISD::BITREVERSE, dl, VT, N->getOperand(0)); 4507 return DAG.getNode(ISD::CTLZ, dl, VT, rbit); 4508 } 4509 4510 /// getCTPOP16BitCounts - Returns a v8i8/v16i8 vector containing the bit-count 4511 /// for each 16-bit element from operand, repeated. The basic idea is to 4512 /// leverage vcnt to get the 8-bit counts, gather and add the results. 4513 /// 4514 /// Trace for v4i16: 4515 /// input = [v0 v1 v2 v3 ] (vi 16-bit element) 4516 /// cast: N0 = [w0 w1 w2 w3 w4 w5 w6 w7] (v0 = [w0 w1], wi 8-bit element) 4517 /// vcnt: N1 = [b0 b1 b2 b3 b4 b5 b6 b7] (bi = bit-count of 8-bit element wi) 4518 /// vrev: N2 = [b1 b0 b3 b2 b5 b4 b7 b6] 4519 /// [b0 b1 b2 b3 b4 b5 b6 b7] 4520 /// +[b1 b0 b3 b2 b5 b4 b7 b6] 4521 /// N3=N1+N2 = [k0 k0 k1 k1 k2 k2 k3 k3] (k0 = b0+b1 = bit-count of 16-bit v0, 4522 /// vuzp: = [k0 k1 k2 k3 k0 k1 k2 k3] each ki is 8-bits) 4523 static SDValue getCTPOP16BitCounts(SDNode *N, SelectionDAG &DAG) { 4524 EVT VT = N->getValueType(0); 4525 SDLoc DL(N); 4526 4527 EVT VT8Bit = VT.is64BitVector() ? MVT::v8i8 : MVT::v16i8; 4528 SDValue N0 = DAG.getNode(ISD::BITCAST, DL, VT8Bit, N->getOperand(0)); 4529 SDValue N1 = DAG.getNode(ISD::CTPOP, DL, VT8Bit, N0); 4530 SDValue N2 = DAG.getNode(ARMISD::VREV16, DL, VT8Bit, N1); 4531 SDValue N3 = DAG.getNode(ISD::ADD, DL, VT8Bit, N1, N2); 4532 return DAG.getNode(ARMISD::VUZP, DL, VT8Bit, N3, N3); 4533 } 4534 4535 /// lowerCTPOP16BitElements - Returns a v4i16/v8i16 vector containing the 4536 /// bit-count for each 16-bit element from the operand. We need slightly 4537 /// different sequencing for v4i16 and v8i16 to stay within NEON's available 4538 /// 64/128-bit registers. 4539 /// 4540 /// Trace for v4i16: 4541 /// input = [v0 v1 v2 v3 ] (vi 16-bit element) 4542 /// v8i8: BitCounts = [k0 k1 k2 k3 k0 k1 k2 k3 ] (ki is the bit-count of vi) 4543 /// v8i16:Extended = [k0 k1 k2 k3 k0 k1 k2 k3 ] 4544 /// v4i16:Extracted = [k0 k1 k2 k3 ] 4545 static SDValue lowerCTPOP16BitElements(SDNode *N, SelectionDAG &DAG) { 4546 EVT VT = N->getValueType(0); 4547 SDLoc DL(N); 4548 4549 SDValue BitCounts = getCTPOP16BitCounts(N, DAG); 4550 if (VT.is64BitVector()) { 4551 SDValue Extended = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::v8i16, BitCounts); 4552 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v4i16, Extended, 4553 DAG.getIntPtrConstant(0, DL)); 4554 } else { 4555 SDValue Extracted = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v8i8, 4556 BitCounts, DAG.getIntPtrConstant(0, DL)); 4557 return DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::v8i16, Extracted); 4558 } 4559 } 4560 4561 /// lowerCTPOP32BitElements - Returns a v2i32/v4i32 vector containing the 4562 /// bit-count for each 32-bit element from the operand. The idea here is 4563 /// to split the vector into 16-bit elements, leverage the 16-bit count 4564 /// routine, and then combine the results. 4565 /// 4566 /// Trace for v2i32 (v4i32 similar with Extracted/Extended exchanged): 4567 /// input = [v0 v1 ] (vi: 32-bit elements) 4568 /// Bitcast = [w0 w1 w2 w3 ] (wi: 16-bit elements, v0 = [w0 w1]) 4569 /// Counts16 = [k0 k1 k2 k3 ] (ki: 16-bit elements, bit-count of wi) 4570 /// vrev: N0 = [k1 k0 k3 k2 ] 4571 /// [k0 k1 k2 k3 ] 4572 /// N1 =+[k1 k0 k3 k2 ] 4573 /// [k0 k2 k1 k3 ] 4574 /// N2 =+[k1 k3 k0 k2 ] 4575 /// [k0 k2 k1 k3 ] 4576 /// Extended =+[k1 k3 k0 k2 ] 4577 /// [k0 k2 ] 4578 /// Extracted=+[k1 k3 ] 4579 /// 4580 static SDValue lowerCTPOP32BitElements(SDNode *N, SelectionDAG &DAG) { 4581 EVT VT = N->getValueType(0); 4582 SDLoc DL(N); 4583 4584 EVT VT16Bit = VT.is64BitVector() ? MVT::v4i16 : MVT::v8i16; 4585 4586 SDValue Bitcast = DAG.getNode(ISD::BITCAST, DL, VT16Bit, N->getOperand(0)); 4587 SDValue Counts16 = lowerCTPOP16BitElements(Bitcast.getNode(), DAG); 4588 SDValue N0 = DAG.getNode(ARMISD::VREV32, DL, VT16Bit, Counts16); 4589 SDValue N1 = DAG.getNode(ISD::ADD, DL, VT16Bit, Counts16, N0); 4590 SDValue N2 = DAG.getNode(ARMISD::VUZP, DL, VT16Bit, N1, N1); 4591 4592 if (VT.is64BitVector()) { 4593 SDValue Extended = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::v4i32, N2); 4594 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2i32, Extended, 4595 DAG.getIntPtrConstant(0, DL)); 4596 } else { 4597 SDValue Extracted = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v4i16, N2, 4598 DAG.getIntPtrConstant(0, DL)); 4599 return DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::v4i32, Extracted); 4600 } 4601 } 4602 4603 static SDValue LowerCTPOP(SDNode *N, SelectionDAG &DAG, 4604 const ARMSubtarget *ST) { 4605 EVT VT = N->getValueType(0); 4606 4607 assert(ST->hasNEON() && "Custom ctpop lowering requires NEON."); 4608 assert((VT == MVT::v2i32 || VT == MVT::v4i32 || 4609 VT == MVT::v4i16 || VT == MVT::v8i16) && 4610 "Unexpected type for custom ctpop lowering"); 4611 4612 if (VT.getVectorElementType() == MVT::i32) 4613 return lowerCTPOP32BitElements(N, DAG); 4614 else 4615 return lowerCTPOP16BitElements(N, DAG); 4616 } 4617 4618 static SDValue LowerShift(SDNode *N, SelectionDAG &DAG, 4619 const ARMSubtarget *ST) { 4620 EVT VT = N->getValueType(0); 4621 SDLoc dl(N); 4622 4623 if (!VT.isVector()) 4624 return SDValue(); 4625 4626 // Lower vector shifts on NEON to use VSHL. 4627 assert(ST->hasNEON() && "unexpected vector shift"); 4628 4629 // Left shifts translate directly to the vshiftu intrinsic. 4630 if (N->getOpcode() == ISD::SHL) 4631 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT, 4632 DAG.getConstant(Intrinsic::arm_neon_vshiftu, dl, 4633 MVT::i32), 4634 N->getOperand(0), N->getOperand(1)); 4635 4636 assert((N->getOpcode() == ISD::SRA || 4637 N->getOpcode() == ISD::SRL) && "unexpected vector shift opcode"); 4638 4639 // NEON uses the same intrinsics for both left and right shifts. For 4640 // right shifts, the shift amounts are negative, so negate the vector of 4641 // shift amounts. 4642 EVT ShiftVT = N->getOperand(1).getValueType(); 4643 SDValue NegatedCount = DAG.getNode(ISD::SUB, dl, ShiftVT, 4644 getZeroVector(ShiftVT, DAG, dl), 4645 N->getOperand(1)); 4646 Intrinsic::ID vshiftInt = (N->getOpcode() == ISD::SRA ? 4647 Intrinsic::arm_neon_vshifts : 4648 Intrinsic::arm_neon_vshiftu); 4649 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT, 4650 DAG.getConstant(vshiftInt, dl, MVT::i32), 4651 N->getOperand(0), NegatedCount); 4652 } 4653 4654 static SDValue Expand64BitShift(SDNode *N, SelectionDAG &DAG, 4655 const ARMSubtarget *ST) { 4656 EVT VT = N->getValueType(0); 4657 SDLoc dl(N); 4658 4659 // We can get here for a node like i32 = ISD::SHL i32, i64 4660 if (VT != MVT::i64) 4661 return SDValue(); 4662 4663 assert((N->getOpcode() == ISD::SRL || N->getOpcode() == ISD::SRA) && 4664 "Unknown shift to lower!"); 4665 4666 // We only lower SRA, SRL of 1 here, all others use generic lowering. 4667 if (!isOneConstant(N->getOperand(1))) 4668 return SDValue(); 4669 4670 // If we are in thumb mode, we don't have RRX. 4671 if (ST->isThumb1Only()) return SDValue(); 4672 4673 // Okay, we have a 64-bit SRA or SRL of 1. Lower this to an RRX expr. 4674 SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(0), 4675 DAG.getConstant(0, dl, MVT::i32)); 4676 SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(0), 4677 DAG.getConstant(1, dl, MVT::i32)); 4678 4679 // First, build a SRA_FLAG/SRL_FLAG op, which shifts the top part by one and 4680 // captures the result into a carry flag. 4681 unsigned Opc = N->getOpcode() == ISD::SRL ? ARMISD::SRL_FLAG:ARMISD::SRA_FLAG; 4682 Hi = DAG.getNode(Opc, dl, DAG.getVTList(MVT::i32, MVT::Glue), Hi); 4683 4684 // The low part is an ARMISD::RRX operand, which shifts the carry in. 4685 Lo = DAG.getNode(ARMISD::RRX, dl, MVT::i32, Lo, Hi.getValue(1)); 4686 4687 // Merge the pieces into a single i64 value. 4688 return DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Lo, Hi); 4689 } 4690 4691 static SDValue LowerVSETCC(SDValue Op, SelectionDAG &DAG) { 4692 SDValue TmpOp0, TmpOp1; 4693 bool Invert = false; 4694 bool Swap = false; 4695 unsigned Opc = 0; 4696 4697 SDValue Op0 = Op.getOperand(0); 4698 SDValue Op1 = Op.getOperand(1); 4699 SDValue CC = Op.getOperand(2); 4700 EVT CmpVT = Op0.getValueType().changeVectorElementTypeToInteger(); 4701 EVT VT = Op.getValueType(); 4702 ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get(); 4703 SDLoc dl(Op); 4704 4705 if (CmpVT.getVectorElementType() == MVT::i64) 4706 // 64-bit comparisons are not legal. We've marked SETCC as non-Custom, 4707 // but it's possible that our operands are 64-bit but our result is 32-bit. 4708 // Bail in this case. 4709 return SDValue(); 4710 4711 if (Op1.getValueType().isFloatingPoint()) { 4712 switch (SetCCOpcode) { 4713 default: llvm_unreachable("Illegal FP comparison"); 4714 case ISD::SETUNE: 4715 case ISD::SETNE: Invert = true; // Fallthrough 4716 case ISD::SETOEQ: 4717 case ISD::SETEQ: Opc = ARMISD::VCEQ; break; 4718 case ISD::SETOLT: 4719 case ISD::SETLT: Swap = true; // Fallthrough 4720 case ISD::SETOGT: 4721 case ISD::SETGT: Opc = ARMISD::VCGT; break; 4722 case ISD::SETOLE: 4723 case ISD::SETLE: Swap = true; // Fallthrough 4724 case ISD::SETOGE: 4725 case ISD::SETGE: Opc = ARMISD::VCGE; break; 4726 case ISD::SETUGE: Swap = true; // Fallthrough 4727 case ISD::SETULE: Invert = true; Opc = ARMISD::VCGT; break; 4728 case ISD::SETUGT: Swap = true; // Fallthrough 4729 case ISD::SETULT: Invert = true; Opc = ARMISD::VCGE; break; 4730 case ISD::SETUEQ: Invert = true; // Fallthrough 4731 case ISD::SETONE: 4732 // Expand this to (OLT | OGT). 4733 TmpOp0 = Op0; 4734 TmpOp1 = Op1; 4735 Opc = ISD::OR; 4736 Op0 = DAG.getNode(ARMISD::VCGT, dl, CmpVT, TmpOp1, TmpOp0); 4737 Op1 = DAG.getNode(ARMISD::VCGT, dl, CmpVT, TmpOp0, TmpOp1); 4738 break; 4739 case ISD::SETUO: Invert = true; // Fallthrough 4740 case ISD::SETO: 4741 // Expand this to (OLT | OGE). 4742 TmpOp0 = Op0; 4743 TmpOp1 = Op1; 4744 Opc = ISD::OR; 4745 Op0 = DAG.getNode(ARMISD::VCGT, dl, CmpVT, TmpOp1, TmpOp0); 4746 Op1 = DAG.getNode(ARMISD::VCGE, dl, CmpVT, TmpOp0, TmpOp1); 4747 break; 4748 } 4749 } else { 4750 // Integer comparisons. 4751 switch (SetCCOpcode) { 4752 default: llvm_unreachable("Illegal integer comparison"); 4753 case ISD::SETNE: Invert = true; 4754 case ISD::SETEQ: Opc = ARMISD::VCEQ; break; 4755 case ISD::SETLT: Swap = true; 4756 case ISD::SETGT: Opc = ARMISD::VCGT; break; 4757 case ISD::SETLE: Swap = true; 4758 case ISD::SETGE: Opc = ARMISD::VCGE; break; 4759 case ISD::SETULT: Swap = true; 4760 case ISD::SETUGT: Opc = ARMISD::VCGTU; break; 4761 case ISD::SETULE: Swap = true; 4762 case ISD::SETUGE: Opc = ARMISD::VCGEU; break; 4763 } 4764 4765 // Detect VTST (Vector Test Bits) = icmp ne (and (op0, op1), zero). 4766 if (Opc == ARMISD::VCEQ) { 4767 4768 SDValue AndOp; 4769 if (ISD::isBuildVectorAllZeros(Op1.getNode())) 4770 AndOp = Op0; 4771 else if (ISD::isBuildVectorAllZeros(Op0.getNode())) 4772 AndOp = Op1; 4773 4774 // Ignore bitconvert. 4775 if (AndOp.getNode() && AndOp.getOpcode() == ISD::BITCAST) 4776 AndOp = AndOp.getOperand(0); 4777 4778 if (AndOp.getNode() && AndOp.getOpcode() == ISD::AND) { 4779 Opc = ARMISD::VTST; 4780 Op0 = DAG.getNode(ISD::BITCAST, dl, CmpVT, AndOp.getOperand(0)); 4781 Op1 = DAG.getNode(ISD::BITCAST, dl, CmpVT, AndOp.getOperand(1)); 4782 Invert = !Invert; 4783 } 4784 } 4785 } 4786 4787 if (Swap) 4788 std::swap(Op0, Op1); 4789 4790 // If one of the operands is a constant vector zero, attempt to fold the 4791 // comparison to a specialized compare-against-zero form. 4792 SDValue SingleOp; 4793 if (ISD::isBuildVectorAllZeros(Op1.getNode())) 4794 SingleOp = Op0; 4795 else if (ISD::isBuildVectorAllZeros(Op0.getNode())) { 4796 if (Opc == ARMISD::VCGE) 4797 Opc = ARMISD::VCLEZ; 4798 else if (Opc == ARMISD::VCGT) 4799 Opc = ARMISD::VCLTZ; 4800 SingleOp = Op1; 4801 } 4802 4803 SDValue Result; 4804 if (SingleOp.getNode()) { 4805 switch (Opc) { 4806 case ARMISD::VCEQ: 4807 Result = DAG.getNode(ARMISD::VCEQZ, dl, CmpVT, SingleOp); break; 4808 case ARMISD::VCGE: 4809 Result = DAG.getNode(ARMISD::VCGEZ, dl, CmpVT, SingleOp); break; 4810 case ARMISD::VCLEZ: 4811 Result = DAG.getNode(ARMISD::VCLEZ, dl, CmpVT, SingleOp); break; 4812 case ARMISD::VCGT: 4813 Result = DAG.getNode(ARMISD::VCGTZ, dl, CmpVT, SingleOp); break; 4814 case ARMISD::VCLTZ: 4815 Result = DAG.getNode(ARMISD::VCLTZ, dl, CmpVT, SingleOp); break; 4816 default: 4817 Result = DAG.getNode(Opc, dl, CmpVT, Op0, Op1); 4818 } 4819 } else { 4820 Result = DAG.getNode(Opc, dl, CmpVT, Op0, Op1); 4821 } 4822 4823 Result = DAG.getSExtOrTrunc(Result, dl, VT); 4824 4825 if (Invert) 4826 Result = DAG.getNOT(dl, Result, VT); 4827 4828 return Result; 4829 } 4830 4831 /// isNEONModifiedImm - Check if the specified splat value corresponds to a 4832 /// valid vector constant for a NEON instruction with a "modified immediate" 4833 /// operand (e.g., VMOV). If so, return the encoded value. 4834 static SDValue isNEONModifiedImm(uint64_t SplatBits, uint64_t SplatUndef, 4835 unsigned SplatBitSize, SelectionDAG &DAG, 4836 SDLoc dl, EVT &VT, bool is128Bits, 4837 NEONModImmType type) { 4838 unsigned OpCmode, Imm; 4839 4840 // SplatBitSize is set to the smallest size that splats the vector, so a 4841 // zero vector will always have SplatBitSize == 8. However, NEON modified 4842 // immediate instructions others than VMOV do not support the 8-bit encoding 4843 // of a zero vector, and the default encoding of zero is supposed to be the 4844 // 32-bit version. 4845 if (SplatBits == 0) 4846 SplatBitSize = 32; 4847 4848 switch (SplatBitSize) { 4849 case 8: 4850 if (type != VMOVModImm) 4851 return SDValue(); 4852 // Any 1-byte value is OK. Op=0, Cmode=1110. 4853 assert((SplatBits & ~0xff) == 0 && "one byte splat value is too big"); 4854 OpCmode = 0xe; 4855 Imm = SplatBits; 4856 VT = is128Bits ? MVT::v16i8 : MVT::v8i8; 4857 break; 4858 4859 case 16: 4860 // NEON's 16-bit VMOV supports splat values where only one byte is nonzero. 4861 VT = is128Bits ? MVT::v8i16 : MVT::v4i16; 4862 if ((SplatBits & ~0xff) == 0) { 4863 // Value = 0x00nn: Op=x, Cmode=100x. 4864 OpCmode = 0x8; 4865 Imm = SplatBits; 4866 break; 4867 } 4868 if ((SplatBits & ~0xff00) == 0) { 4869 // Value = 0xnn00: Op=x, Cmode=101x. 4870 OpCmode = 0xa; 4871 Imm = SplatBits >> 8; 4872 break; 4873 } 4874 return SDValue(); 4875 4876 case 32: 4877 // NEON's 32-bit VMOV supports splat values where: 4878 // * only one byte is nonzero, or 4879 // * the least significant byte is 0xff and the second byte is nonzero, or 4880 // * the least significant 2 bytes are 0xff and the third is nonzero. 4881 VT = is128Bits ? MVT::v4i32 : MVT::v2i32; 4882 if ((SplatBits & ~0xff) == 0) { 4883 // Value = 0x000000nn: Op=x, Cmode=000x. 4884 OpCmode = 0; 4885 Imm = SplatBits; 4886 break; 4887 } 4888 if ((SplatBits & ~0xff00) == 0) { 4889 // Value = 0x0000nn00: Op=x, Cmode=001x. 4890 OpCmode = 0x2; 4891 Imm = SplatBits >> 8; 4892 break; 4893 } 4894 if ((SplatBits & ~0xff0000) == 0) { 4895 // Value = 0x00nn0000: Op=x, Cmode=010x. 4896 OpCmode = 0x4; 4897 Imm = SplatBits >> 16; 4898 break; 4899 } 4900 if ((SplatBits & ~0xff000000) == 0) { 4901 // Value = 0xnn000000: Op=x, Cmode=011x. 4902 OpCmode = 0x6; 4903 Imm = SplatBits >> 24; 4904 break; 4905 } 4906 4907 // cmode == 0b1100 and cmode == 0b1101 are not supported for VORR or VBIC 4908 if (type == OtherModImm) return SDValue(); 4909 4910 if ((SplatBits & ~0xffff) == 0 && 4911 ((SplatBits | SplatUndef) & 0xff) == 0xff) { 4912 // Value = 0x0000nnff: Op=x, Cmode=1100. 4913 OpCmode = 0xc; 4914 Imm = SplatBits >> 8; 4915 break; 4916 } 4917 4918 if ((SplatBits & ~0xffffff) == 0 && 4919 ((SplatBits | SplatUndef) & 0xffff) == 0xffff) { 4920 // Value = 0x00nnffff: Op=x, Cmode=1101. 4921 OpCmode = 0xd; 4922 Imm = SplatBits >> 16; 4923 break; 4924 } 4925 4926 // Note: there are a few 32-bit splat values (specifically: 00ffff00, 4927 // ff000000, ff0000ff, and ffff00ff) that are valid for VMOV.I64 but not 4928 // VMOV.I32. A (very) minor optimization would be to replicate the value 4929 // and fall through here to test for a valid 64-bit splat. But, then the 4930 // caller would also need to check and handle the change in size. 4931 return SDValue(); 4932 4933 case 64: { 4934 if (type != VMOVModImm) 4935 return SDValue(); 4936 // NEON has a 64-bit VMOV splat where each byte is either 0 or 0xff. 4937 uint64_t BitMask = 0xff; 4938 uint64_t Val = 0; 4939 unsigned ImmMask = 1; 4940 Imm = 0; 4941 for (int ByteNum = 0; ByteNum < 8; ++ByteNum) { 4942 if (((SplatBits | SplatUndef) & BitMask) == BitMask) { 4943 Val |= BitMask; 4944 Imm |= ImmMask; 4945 } else if ((SplatBits & BitMask) != 0) { 4946 return SDValue(); 4947 } 4948 BitMask <<= 8; 4949 ImmMask <<= 1; 4950 } 4951 4952 if (DAG.getDataLayout().isBigEndian()) 4953 // swap higher and lower 32 bit word 4954 Imm = ((Imm & 0xf) << 4) | ((Imm & 0xf0) >> 4); 4955 4956 // Op=1, Cmode=1110. 4957 OpCmode = 0x1e; 4958 VT = is128Bits ? MVT::v2i64 : MVT::v1i64; 4959 break; 4960 } 4961 4962 default: 4963 llvm_unreachable("unexpected size for isNEONModifiedImm"); 4964 } 4965 4966 unsigned EncodedVal = ARM_AM::createNEONModImm(OpCmode, Imm); 4967 return DAG.getTargetConstant(EncodedVal, dl, MVT::i32); 4968 } 4969 4970 SDValue ARMTargetLowering::LowerConstantFP(SDValue Op, SelectionDAG &DAG, 4971 const ARMSubtarget *ST) const { 4972 if (!ST->hasVFP3()) 4973 return SDValue(); 4974 4975 bool IsDouble = Op.getValueType() == MVT::f64; 4976 ConstantFPSDNode *CFP = cast<ConstantFPSDNode>(Op); 4977 4978 // Use the default (constant pool) lowering for double constants when we have 4979 // an SP-only FPU 4980 if (IsDouble && Subtarget->isFPOnlySP()) 4981 return SDValue(); 4982 4983 // Try splatting with a VMOV.f32... 4984 APFloat FPVal = CFP->getValueAPF(); 4985 int ImmVal = IsDouble ? ARM_AM::getFP64Imm(FPVal) : ARM_AM::getFP32Imm(FPVal); 4986 4987 if (ImmVal != -1) { 4988 if (IsDouble || !ST->useNEONForSinglePrecisionFP()) { 4989 // We have code in place to select a valid ConstantFP already, no need to 4990 // do any mangling. 4991 return Op; 4992 } 4993 4994 // It's a float and we are trying to use NEON operations where 4995 // possible. Lower it to a splat followed by an extract. 4996 SDLoc DL(Op); 4997 SDValue NewVal = DAG.getTargetConstant(ImmVal, DL, MVT::i32); 4998 SDValue VecConstant = DAG.getNode(ARMISD::VMOVFPIMM, DL, MVT::v2f32, 4999 NewVal); 5000 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32, VecConstant, 5001 DAG.getConstant(0, DL, MVT::i32)); 5002 } 5003 5004 // The rest of our options are NEON only, make sure that's allowed before 5005 // proceeding.. 5006 if (!ST->hasNEON() || (!IsDouble && !ST->useNEONForSinglePrecisionFP())) 5007 return SDValue(); 5008 5009 EVT VMovVT; 5010 uint64_t iVal = FPVal.bitcastToAPInt().getZExtValue(); 5011 5012 // It wouldn't really be worth bothering for doubles except for one very 5013 // important value, which does happen to match: 0.0. So make sure we don't do 5014 // anything stupid. 5015 if (IsDouble && (iVal & 0xffffffff) != (iVal >> 32)) 5016 return SDValue(); 5017 5018 // Try a VMOV.i32 (FIXME: i8, i16, or i64 could work too). 5019 SDValue NewVal = isNEONModifiedImm(iVal & 0xffffffffU, 0, 32, DAG, SDLoc(Op), 5020 VMovVT, false, VMOVModImm); 5021 if (NewVal != SDValue()) { 5022 SDLoc DL(Op); 5023 SDValue VecConstant = DAG.getNode(ARMISD::VMOVIMM, DL, VMovVT, 5024 NewVal); 5025 if (IsDouble) 5026 return DAG.getNode(ISD::BITCAST, DL, MVT::f64, VecConstant); 5027 5028 // It's a float: cast and extract a vector element. 5029 SDValue VecFConstant = DAG.getNode(ISD::BITCAST, DL, MVT::v2f32, 5030 VecConstant); 5031 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32, VecFConstant, 5032 DAG.getConstant(0, DL, MVT::i32)); 5033 } 5034 5035 // Finally, try a VMVN.i32 5036 NewVal = isNEONModifiedImm(~iVal & 0xffffffffU, 0, 32, DAG, SDLoc(Op), VMovVT, 5037 false, VMVNModImm); 5038 if (NewVal != SDValue()) { 5039 SDLoc DL(Op); 5040 SDValue VecConstant = DAG.getNode(ARMISD::VMVNIMM, DL, VMovVT, NewVal); 5041 5042 if (IsDouble) 5043 return DAG.getNode(ISD::BITCAST, DL, MVT::f64, VecConstant); 5044 5045 // It's a float: cast and extract a vector element. 5046 SDValue VecFConstant = DAG.getNode(ISD::BITCAST, DL, MVT::v2f32, 5047 VecConstant); 5048 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32, VecFConstant, 5049 DAG.getConstant(0, DL, MVT::i32)); 5050 } 5051 5052 return SDValue(); 5053 } 5054 5055 // check if an VEXT instruction can handle the shuffle mask when the 5056 // vector sources of the shuffle are the same. 5057 static bool isSingletonVEXTMask(ArrayRef<int> M, EVT VT, unsigned &Imm) { 5058 unsigned NumElts = VT.getVectorNumElements(); 5059 5060 // Assume that the first shuffle index is not UNDEF. Fail if it is. 5061 if (M[0] < 0) 5062 return false; 5063 5064 Imm = M[0]; 5065 5066 // If this is a VEXT shuffle, the immediate value is the index of the first 5067 // element. The other shuffle indices must be the successive elements after 5068 // the first one. 5069 unsigned ExpectedElt = Imm; 5070 for (unsigned i = 1; i < NumElts; ++i) { 5071 // Increment the expected index. If it wraps around, just follow it 5072 // back to index zero and keep going. 5073 ++ExpectedElt; 5074 if (ExpectedElt == NumElts) 5075 ExpectedElt = 0; 5076 5077 if (M[i] < 0) continue; // ignore UNDEF indices 5078 if (ExpectedElt != static_cast<unsigned>(M[i])) 5079 return false; 5080 } 5081 5082 return true; 5083 } 5084 5085 5086 static bool isVEXTMask(ArrayRef<int> M, EVT VT, 5087 bool &ReverseVEXT, unsigned &Imm) { 5088 unsigned NumElts = VT.getVectorNumElements(); 5089 ReverseVEXT = false; 5090 5091 // Assume that the first shuffle index is not UNDEF. Fail if it is. 5092 if (M[0] < 0) 5093 return false; 5094 5095 Imm = M[0]; 5096 5097 // If this is a VEXT shuffle, the immediate value is the index of the first 5098 // element. The other shuffle indices must be the successive elements after 5099 // the first one. 5100 unsigned ExpectedElt = Imm; 5101 for (unsigned i = 1; i < NumElts; ++i) { 5102 // Increment the expected index. If it wraps around, it may still be 5103 // a VEXT but the source vectors must be swapped. 5104 ExpectedElt += 1; 5105 if (ExpectedElt == NumElts * 2) { 5106 ExpectedElt = 0; 5107 ReverseVEXT = true; 5108 } 5109 5110 if (M[i] < 0) continue; // ignore UNDEF indices 5111 if (ExpectedElt != static_cast<unsigned>(M[i])) 5112 return false; 5113 } 5114 5115 // Adjust the index value if the source operands will be swapped. 5116 if (ReverseVEXT) 5117 Imm -= NumElts; 5118 5119 return true; 5120 } 5121 5122 /// isVREVMask - Check if a vector shuffle corresponds to a VREV 5123 /// instruction with the specified blocksize. (The order of the elements 5124 /// within each block of the vector is reversed.) 5125 static bool isVREVMask(ArrayRef<int> M, EVT VT, unsigned BlockSize) { 5126 assert((BlockSize==16 || BlockSize==32 || BlockSize==64) && 5127 "Only possible block sizes for VREV are: 16, 32, 64"); 5128 5129 unsigned EltSz = VT.getVectorElementType().getSizeInBits(); 5130 if (EltSz == 64) 5131 return false; 5132 5133 unsigned NumElts = VT.getVectorNumElements(); 5134 unsigned BlockElts = M[0] + 1; 5135 // If the first shuffle index is UNDEF, be optimistic. 5136 if (M[0] < 0) 5137 BlockElts = BlockSize / EltSz; 5138 5139 if (BlockSize <= EltSz || BlockSize != BlockElts * EltSz) 5140 return false; 5141 5142 for (unsigned i = 0; i < NumElts; ++i) { 5143 if (M[i] < 0) continue; // ignore UNDEF indices 5144 if ((unsigned) M[i] != (i - i%BlockElts) + (BlockElts - 1 - i%BlockElts)) 5145 return false; 5146 } 5147 5148 return true; 5149 } 5150 5151 static bool isVTBLMask(ArrayRef<int> M, EVT VT) { 5152 // We can handle <8 x i8> vector shuffles. If the index in the mask is out of 5153 // range, then 0 is placed into the resulting vector. So pretty much any mask 5154 // of 8 elements can work here. 5155 return VT == MVT::v8i8 && M.size() == 8; 5156 } 5157 5158 // Checks whether the shuffle mask represents a vector transpose (VTRN) by 5159 // checking that pairs of elements in the shuffle mask represent the same index 5160 // in each vector, incrementing the expected index by 2 at each step. 5161 // e.g. For v1,v2 of type v4i32 a valid shuffle mask is: [0, 4, 2, 6] 5162 // v1={a,b,c,d} => x=shufflevector v1, v2 shufflemask => x={a,e,c,g} 5163 // v2={e,f,g,h} 5164 // WhichResult gives the offset for each element in the mask based on which 5165 // of the two results it belongs to. 5166 // 5167 // The transpose can be represented either as: 5168 // result1 = shufflevector v1, v2, result1_shuffle_mask 5169 // result2 = shufflevector v1, v2, result2_shuffle_mask 5170 // where v1/v2 and the shuffle masks have the same number of elements 5171 // (here WhichResult (see below) indicates which result is being checked) 5172 // 5173 // or as: 5174 // results = shufflevector v1, v2, shuffle_mask 5175 // where both results are returned in one vector and the shuffle mask has twice 5176 // as many elements as v1/v2 (here WhichResult will always be 0 if true) here we 5177 // want to check the low half and high half of the shuffle mask as if it were 5178 // the other case 5179 static bool isVTRNMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) { 5180 unsigned EltSz = VT.getVectorElementType().getSizeInBits(); 5181 if (EltSz == 64) 5182 return false; 5183 5184 unsigned NumElts = VT.getVectorNumElements(); 5185 if (M.size() != NumElts && M.size() != NumElts*2) 5186 return false; 5187 5188 // If the mask is twice as long as the input vector then we need to check the 5189 // upper and lower parts of the mask with a matching value for WhichResult 5190 // FIXME: A mask with only even values will be rejected in case the first 5191 // element is undefined, e.g. [-1, 4, 2, 6] will be rejected, because only 5192 // M[0] is used to determine WhichResult 5193 for (unsigned i = 0; i < M.size(); i += NumElts) { 5194 if (M.size() == NumElts * 2) 5195 WhichResult = i / NumElts; 5196 else 5197 WhichResult = M[i] == 0 ? 0 : 1; 5198 for (unsigned j = 0; j < NumElts; j += 2) { 5199 if ((M[i+j] >= 0 && (unsigned) M[i+j] != j + WhichResult) || 5200 (M[i+j+1] >= 0 && (unsigned) M[i+j+1] != j + NumElts + WhichResult)) 5201 return false; 5202 } 5203 } 5204 5205 if (M.size() == NumElts*2) 5206 WhichResult = 0; 5207 5208 return true; 5209 } 5210 5211 /// isVTRN_v_undef_Mask - Special case of isVTRNMask for canonical form of 5212 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef". 5213 /// Mask is e.g., <0, 0, 2, 2> instead of <0, 4, 2, 6>. 5214 static bool isVTRN_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult){ 5215 unsigned EltSz = VT.getVectorElementType().getSizeInBits(); 5216 if (EltSz == 64) 5217 return false; 5218 5219 unsigned NumElts = VT.getVectorNumElements(); 5220 if (M.size() != NumElts && M.size() != NumElts*2) 5221 return false; 5222 5223 for (unsigned i = 0; i < M.size(); i += NumElts) { 5224 if (M.size() == NumElts * 2) 5225 WhichResult = i / NumElts; 5226 else 5227 WhichResult = M[i] == 0 ? 0 : 1; 5228 for (unsigned j = 0; j < NumElts; j += 2) { 5229 if ((M[i+j] >= 0 && (unsigned) M[i+j] != j + WhichResult) || 5230 (M[i+j+1] >= 0 && (unsigned) M[i+j+1] != j + WhichResult)) 5231 return false; 5232 } 5233 } 5234 5235 if (M.size() == NumElts*2) 5236 WhichResult = 0; 5237 5238 return true; 5239 } 5240 5241 // Checks whether the shuffle mask represents a vector unzip (VUZP) by checking 5242 // that the mask elements are either all even and in steps of size 2 or all odd 5243 // and in steps of size 2. 5244 // e.g. For v1,v2 of type v4i32 a valid shuffle mask is: [0, 2, 4, 6] 5245 // v1={a,b,c,d} => x=shufflevector v1, v2 shufflemask => x={a,c,e,g} 5246 // v2={e,f,g,h} 5247 // Requires similar checks to that of isVTRNMask with 5248 // respect the how results are returned. 5249 static bool isVUZPMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) { 5250 unsigned EltSz = VT.getVectorElementType().getSizeInBits(); 5251 if (EltSz == 64) 5252 return false; 5253 5254 unsigned NumElts = VT.getVectorNumElements(); 5255 if (M.size() != NumElts && M.size() != NumElts*2) 5256 return false; 5257 5258 for (unsigned i = 0; i < M.size(); i += NumElts) { 5259 WhichResult = M[i] == 0 ? 0 : 1; 5260 for (unsigned j = 0; j < NumElts; ++j) { 5261 if (M[i+j] >= 0 && (unsigned) M[i+j] != 2 * j + WhichResult) 5262 return false; 5263 } 5264 } 5265 5266 if (M.size() == NumElts*2) 5267 WhichResult = 0; 5268 5269 // VUZP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32. 5270 if (VT.is64BitVector() && EltSz == 32) 5271 return false; 5272 5273 return true; 5274 } 5275 5276 /// isVUZP_v_undef_Mask - Special case of isVUZPMask for canonical form of 5277 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef". 5278 /// Mask is e.g., <0, 2, 0, 2> instead of <0, 2, 4, 6>, 5279 static bool isVUZP_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult){ 5280 unsigned EltSz = VT.getVectorElementType().getSizeInBits(); 5281 if (EltSz == 64) 5282 return false; 5283 5284 unsigned NumElts = VT.getVectorNumElements(); 5285 if (M.size() != NumElts && M.size() != NumElts*2) 5286 return false; 5287 5288 unsigned Half = NumElts / 2; 5289 for (unsigned i = 0; i < M.size(); i += NumElts) { 5290 WhichResult = M[i] == 0 ? 0 : 1; 5291 for (unsigned j = 0; j < NumElts; j += Half) { 5292 unsigned Idx = WhichResult; 5293 for (unsigned k = 0; k < Half; ++k) { 5294 int MIdx = M[i + j + k]; 5295 if (MIdx >= 0 && (unsigned) MIdx != Idx) 5296 return false; 5297 Idx += 2; 5298 } 5299 } 5300 } 5301 5302 if (M.size() == NumElts*2) 5303 WhichResult = 0; 5304 5305 // VUZP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32. 5306 if (VT.is64BitVector() && EltSz == 32) 5307 return false; 5308 5309 return true; 5310 } 5311 5312 // Checks whether the shuffle mask represents a vector zip (VZIP) by checking 5313 // that pairs of elements of the shufflemask represent the same index in each 5314 // vector incrementing sequentially through the vectors. 5315 // e.g. For v1,v2 of type v4i32 a valid shuffle mask is: [0, 4, 1, 5] 5316 // v1={a,b,c,d} => x=shufflevector v1, v2 shufflemask => x={a,e,b,f} 5317 // v2={e,f,g,h} 5318 // Requires similar checks to that of isVTRNMask with respect the how results 5319 // are returned. 5320 static bool isVZIPMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) { 5321 unsigned EltSz = VT.getVectorElementType().getSizeInBits(); 5322 if (EltSz == 64) 5323 return false; 5324 5325 unsigned NumElts = VT.getVectorNumElements(); 5326 if (M.size() != NumElts && M.size() != NumElts*2) 5327 return false; 5328 5329 for (unsigned i = 0; i < M.size(); i += NumElts) { 5330 WhichResult = M[i] == 0 ? 0 : 1; 5331 unsigned Idx = WhichResult * NumElts / 2; 5332 for (unsigned j = 0; j < NumElts; j += 2) { 5333 if ((M[i+j] >= 0 && (unsigned) M[i+j] != Idx) || 5334 (M[i+j+1] >= 0 && (unsigned) M[i+j+1] != Idx + NumElts)) 5335 return false; 5336 Idx += 1; 5337 } 5338 } 5339 5340 if (M.size() == NumElts*2) 5341 WhichResult = 0; 5342 5343 // VZIP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32. 5344 if (VT.is64BitVector() && EltSz == 32) 5345 return false; 5346 5347 return true; 5348 } 5349 5350 /// isVZIP_v_undef_Mask - Special case of isVZIPMask for canonical form of 5351 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef". 5352 /// Mask is e.g., <0, 0, 1, 1> instead of <0, 4, 1, 5>. 5353 static bool isVZIP_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult){ 5354 unsigned EltSz = VT.getVectorElementType().getSizeInBits(); 5355 if (EltSz == 64) 5356 return false; 5357 5358 unsigned NumElts = VT.getVectorNumElements(); 5359 if (M.size() != NumElts && M.size() != NumElts*2) 5360 return false; 5361 5362 for (unsigned i = 0; i < M.size(); i += NumElts) { 5363 WhichResult = M[i] == 0 ? 0 : 1; 5364 unsigned Idx = WhichResult * NumElts / 2; 5365 for (unsigned j = 0; j < NumElts; j += 2) { 5366 if ((M[i+j] >= 0 && (unsigned) M[i+j] != Idx) || 5367 (M[i+j+1] >= 0 && (unsigned) M[i+j+1] != Idx)) 5368 return false; 5369 Idx += 1; 5370 } 5371 } 5372 5373 if (M.size() == NumElts*2) 5374 WhichResult = 0; 5375 5376 // VZIP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32. 5377 if (VT.is64BitVector() && EltSz == 32) 5378 return false; 5379 5380 return true; 5381 } 5382 5383 /// Check if \p ShuffleMask is a NEON two-result shuffle (VZIP, VUZP, VTRN), 5384 /// and return the corresponding ARMISD opcode if it is, or 0 if it isn't. 5385 static unsigned isNEONTwoResultShuffleMask(ArrayRef<int> ShuffleMask, EVT VT, 5386 unsigned &WhichResult, 5387 bool &isV_UNDEF) { 5388 isV_UNDEF = false; 5389 if (isVTRNMask(ShuffleMask, VT, WhichResult)) 5390 return ARMISD::VTRN; 5391 if (isVUZPMask(ShuffleMask, VT, WhichResult)) 5392 return ARMISD::VUZP; 5393 if (isVZIPMask(ShuffleMask, VT, WhichResult)) 5394 return ARMISD::VZIP; 5395 5396 isV_UNDEF = true; 5397 if (isVTRN_v_undef_Mask(ShuffleMask, VT, WhichResult)) 5398 return ARMISD::VTRN; 5399 if (isVUZP_v_undef_Mask(ShuffleMask, VT, WhichResult)) 5400 return ARMISD::VUZP; 5401 if (isVZIP_v_undef_Mask(ShuffleMask, VT, WhichResult)) 5402 return ARMISD::VZIP; 5403 5404 return 0; 5405 } 5406 5407 /// \return true if this is a reverse operation on an vector. 5408 static bool isReverseMask(ArrayRef<int> M, EVT VT) { 5409 unsigned NumElts = VT.getVectorNumElements(); 5410 // Make sure the mask has the right size. 5411 if (NumElts != M.size()) 5412 return false; 5413 5414 // Look for <15, ..., 3, -1, 1, 0>. 5415 for (unsigned i = 0; i != NumElts; ++i) 5416 if (M[i] >= 0 && M[i] != (int) (NumElts - 1 - i)) 5417 return false; 5418 5419 return true; 5420 } 5421 5422 // If N is an integer constant that can be moved into a register in one 5423 // instruction, return an SDValue of such a constant (will become a MOV 5424 // instruction). Otherwise return null. 5425 static SDValue IsSingleInstrConstant(SDValue N, SelectionDAG &DAG, 5426 const ARMSubtarget *ST, SDLoc dl) { 5427 uint64_t Val; 5428 if (!isa<ConstantSDNode>(N)) 5429 return SDValue(); 5430 Val = cast<ConstantSDNode>(N)->getZExtValue(); 5431 5432 if (ST->isThumb1Only()) { 5433 if (Val <= 255 || ~Val <= 255) 5434 return DAG.getConstant(Val, dl, MVT::i32); 5435 } else { 5436 if (ARM_AM::getSOImmVal(Val) != -1 || ARM_AM::getSOImmVal(~Val) != -1) 5437 return DAG.getConstant(Val, dl, MVT::i32); 5438 } 5439 return SDValue(); 5440 } 5441 5442 // If this is a case we can't handle, return null and let the default 5443 // expansion code take care of it. 5444 SDValue ARMTargetLowering::LowerBUILD_VECTOR(SDValue Op, SelectionDAG &DAG, 5445 const ARMSubtarget *ST) const { 5446 BuildVectorSDNode *BVN = cast<BuildVectorSDNode>(Op.getNode()); 5447 SDLoc dl(Op); 5448 EVT VT = Op.getValueType(); 5449 5450 APInt SplatBits, SplatUndef; 5451 unsigned SplatBitSize; 5452 bool HasAnyUndefs; 5453 if (BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs)) { 5454 if (SplatBitSize <= 64) { 5455 // Check if an immediate VMOV works. 5456 EVT VmovVT; 5457 SDValue Val = isNEONModifiedImm(SplatBits.getZExtValue(), 5458 SplatUndef.getZExtValue(), SplatBitSize, 5459 DAG, dl, VmovVT, VT.is128BitVector(), 5460 VMOVModImm); 5461 if (Val.getNode()) { 5462 SDValue Vmov = DAG.getNode(ARMISD::VMOVIMM, dl, VmovVT, Val); 5463 return DAG.getNode(ISD::BITCAST, dl, VT, Vmov); 5464 } 5465 5466 // Try an immediate VMVN. 5467 uint64_t NegatedImm = (~SplatBits).getZExtValue(); 5468 Val = isNEONModifiedImm(NegatedImm, 5469 SplatUndef.getZExtValue(), SplatBitSize, 5470 DAG, dl, VmovVT, VT.is128BitVector(), 5471 VMVNModImm); 5472 if (Val.getNode()) { 5473 SDValue Vmov = DAG.getNode(ARMISD::VMVNIMM, dl, VmovVT, Val); 5474 return DAG.getNode(ISD::BITCAST, dl, VT, Vmov); 5475 } 5476 5477 // Use vmov.f32 to materialize other v2f32 and v4f32 splats. 5478 if ((VT == MVT::v2f32 || VT == MVT::v4f32) && SplatBitSize == 32) { 5479 int ImmVal = ARM_AM::getFP32Imm(SplatBits); 5480 if (ImmVal != -1) { 5481 SDValue Val = DAG.getTargetConstant(ImmVal, dl, MVT::i32); 5482 return DAG.getNode(ARMISD::VMOVFPIMM, dl, VT, Val); 5483 } 5484 } 5485 } 5486 } 5487 5488 // Scan through the operands to see if only one value is used. 5489 // 5490 // As an optimisation, even if more than one value is used it may be more 5491 // profitable to splat with one value then change some lanes. 5492 // 5493 // Heuristically we decide to do this if the vector has a "dominant" value, 5494 // defined as splatted to more than half of the lanes. 5495 unsigned NumElts = VT.getVectorNumElements(); 5496 bool isOnlyLowElement = true; 5497 bool usesOnlyOneValue = true; 5498 bool hasDominantValue = false; 5499 bool isConstant = true; 5500 5501 // Map of the number of times a particular SDValue appears in the 5502 // element list. 5503 DenseMap<SDValue, unsigned> ValueCounts; 5504 SDValue Value; 5505 for (unsigned i = 0; i < NumElts; ++i) { 5506 SDValue V = Op.getOperand(i); 5507 if (V.getOpcode() == ISD::UNDEF) 5508 continue; 5509 if (i > 0) 5510 isOnlyLowElement = false; 5511 if (!isa<ConstantFPSDNode>(V) && !isa<ConstantSDNode>(V)) 5512 isConstant = false; 5513 5514 ValueCounts.insert(std::make_pair(V, 0)); 5515 unsigned &Count = ValueCounts[V]; 5516 5517 // Is this value dominant? (takes up more than half of the lanes) 5518 if (++Count > (NumElts / 2)) { 5519 hasDominantValue = true; 5520 Value = V; 5521 } 5522 } 5523 if (ValueCounts.size() != 1) 5524 usesOnlyOneValue = false; 5525 if (!Value.getNode() && ValueCounts.size() > 0) 5526 Value = ValueCounts.begin()->first; 5527 5528 if (ValueCounts.size() == 0) 5529 return DAG.getUNDEF(VT); 5530 5531 // Loads are better lowered with insert_vector_elt/ARMISD::BUILD_VECTOR. 5532 // Keep going if we are hitting this case. 5533 if (isOnlyLowElement && !ISD::isNormalLoad(Value.getNode())) 5534 return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Value); 5535 5536 unsigned EltSize = VT.getVectorElementType().getSizeInBits(); 5537 5538 // Use VDUP for non-constant splats. For f32 constant splats, reduce to 5539 // i32 and try again. 5540 if (hasDominantValue && EltSize <= 32) { 5541 if (!isConstant) { 5542 SDValue N; 5543 5544 // If we are VDUPing a value that comes directly from a vector, that will 5545 // cause an unnecessary move to and from a GPR, where instead we could 5546 // just use VDUPLANE. We can only do this if the lane being extracted 5547 // is at a constant index, as the VDUP from lane instructions only have 5548 // constant-index forms. 5549 ConstantSDNode *constIndex; 5550 if (Value->getOpcode() == ISD::EXTRACT_VECTOR_ELT && 5551 (constIndex = dyn_cast<ConstantSDNode>(Value->getOperand(1)))) { 5552 // We need to create a new undef vector to use for the VDUPLANE if the 5553 // size of the vector from which we get the value is different than the 5554 // size of the vector that we need to create. We will insert the element 5555 // such that the register coalescer will remove unnecessary copies. 5556 if (VT != Value->getOperand(0).getValueType()) { 5557 unsigned index = constIndex->getAPIntValue().getLimitedValue() % 5558 VT.getVectorNumElements(); 5559 N = DAG.getNode(ARMISD::VDUPLANE, dl, VT, 5560 DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, DAG.getUNDEF(VT), 5561 Value, DAG.getConstant(index, dl, MVT::i32)), 5562 DAG.getConstant(index, dl, MVT::i32)); 5563 } else 5564 N = DAG.getNode(ARMISD::VDUPLANE, dl, VT, 5565 Value->getOperand(0), Value->getOperand(1)); 5566 } else 5567 N = DAG.getNode(ARMISD::VDUP, dl, VT, Value); 5568 5569 if (!usesOnlyOneValue) { 5570 // The dominant value was splatted as 'N', but we now have to insert 5571 // all differing elements. 5572 for (unsigned I = 0; I < NumElts; ++I) { 5573 if (Op.getOperand(I) == Value) 5574 continue; 5575 SmallVector<SDValue, 3> Ops; 5576 Ops.push_back(N); 5577 Ops.push_back(Op.getOperand(I)); 5578 Ops.push_back(DAG.getConstant(I, dl, MVT::i32)); 5579 N = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Ops); 5580 } 5581 } 5582 return N; 5583 } 5584 if (VT.getVectorElementType().isFloatingPoint()) { 5585 SmallVector<SDValue, 8> Ops; 5586 for (unsigned i = 0; i < NumElts; ++i) 5587 Ops.push_back(DAG.getNode(ISD::BITCAST, dl, MVT::i32, 5588 Op.getOperand(i))); 5589 EVT VecVT = EVT::getVectorVT(*DAG.getContext(), MVT::i32, NumElts); 5590 SDValue Val = DAG.getNode(ISD::BUILD_VECTOR, dl, VecVT, Ops); 5591 Val = LowerBUILD_VECTOR(Val, DAG, ST); 5592 if (Val.getNode()) 5593 return DAG.getNode(ISD::BITCAST, dl, VT, Val); 5594 } 5595 if (usesOnlyOneValue) { 5596 SDValue Val = IsSingleInstrConstant(Value, DAG, ST, dl); 5597 if (isConstant && Val.getNode()) 5598 return DAG.getNode(ARMISD::VDUP, dl, VT, Val); 5599 } 5600 } 5601 5602 // If all elements are constants and the case above didn't get hit, fall back 5603 // to the default expansion, which will generate a load from the constant 5604 // pool. 5605 if (isConstant) 5606 return SDValue(); 5607 5608 // Empirical tests suggest this is rarely worth it for vectors of length <= 2. 5609 if (NumElts >= 4) { 5610 SDValue shuffle = ReconstructShuffle(Op, DAG); 5611 if (shuffle != SDValue()) 5612 return shuffle; 5613 } 5614 5615 // Vectors with 32- or 64-bit elements can be built by directly assigning 5616 // the subregisters. Lower it to an ARMISD::BUILD_VECTOR so the operands 5617 // will be legalized. 5618 if (EltSize >= 32) { 5619 // Do the expansion with floating-point types, since that is what the VFP 5620 // registers are defined to use, and since i64 is not legal. 5621 EVT EltVT = EVT::getFloatingPointVT(EltSize); 5622 EVT VecVT = EVT::getVectorVT(*DAG.getContext(), EltVT, NumElts); 5623 SmallVector<SDValue, 8> Ops; 5624 for (unsigned i = 0; i < NumElts; ++i) 5625 Ops.push_back(DAG.getNode(ISD::BITCAST, dl, EltVT, Op.getOperand(i))); 5626 SDValue Val = DAG.getNode(ARMISD::BUILD_VECTOR, dl, VecVT, Ops); 5627 return DAG.getNode(ISD::BITCAST, dl, VT, Val); 5628 } 5629 5630 // If all else fails, just use a sequence of INSERT_VECTOR_ELT when we 5631 // know the default expansion would otherwise fall back on something even 5632 // worse. For a vector with one or two non-undef values, that's 5633 // scalar_to_vector for the elements followed by a shuffle (provided the 5634 // shuffle is valid for the target) and materialization element by element 5635 // on the stack followed by a load for everything else. 5636 if (!isConstant && !usesOnlyOneValue) { 5637 SDValue Vec = DAG.getUNDEF(VT); 5638 for (unsigned i = 0 ; i < NumElts; ++i) { 5639 SDValue V = Op.getOperand(i); 5640 if (V.getOpcode() == ISD::UNDEF) 5641 continue; 5642 SDValue LaneIdx = DAG.getConstant(i, dl, MVT::i32); 5643 Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Vec, V, LaneIdx); 5644 } 5645 return Vec; 5646 } 5647 5648 return SDValue(); 5649 } 5650 5651 // Gather data to see if the operation can be modelled as a 5652 // shuffle in combination with VEXTs. 5653 SDValue ARMTargetLowering::ReconstructShuffle(SDValue Op, 5654 SelectionDAG &DAG) const { 5655 assert(Op.getOpcode() == ISD::BUILD_VECTOR && "Unknown opcode!"); 5656 SDLoc dl(Op); 5657 EVT VT = Op.getValueType(); 5658 unsigned NumElts = VT.getVectorNumElements(); 5659 5660 struct ShuffleSourceInfo { 5661 SDValue Vec; 5662 unsigned MinElt; 5663 unsigned MaxElt; 5664 5665 // We may insert some combination of BITCASTs and VEXT nodes to force Vec to 5666 // be compatible with the shuffle we intend to construct. As a result 5667 // ShuffleVec will be some sliding window into the original Vec. 5668 SDValue ShuffleVec; 5669 5670 // Code should guarantee that element i in Vec starts at element "WindowBase 5671 // + i * WindowScale in ShuffleVec". 5672 int WindowBase; 5673 int WindowScale; 5674 5675 bool operator ==(SDValue OtherVec) { return Vec == OtherVec; } 5676 ShuffleSourceInfo(SDValue Vec) 5677 : Vec(Vec), MinElt(UINT_MAX), MaxElt(0), ShuffleVec(Vec), WindowBase(0), 5678 WindowScale(1) {} 5679 }; 5680 5681 // First gather all vectors used as an immediate source for this BUILD_VECTOR 5682 // node. 5683 SmallVector<ShuffleSourceInfo, 2> Sources; 5684 for (unsigned i = 0; i < NumElts; ++i) { 5685 SDValue V = Op.getOperand(i); 5686 if (V.getOpcode() == ISD::UNDEF) 5687 continue; 5688 else if (V.getOpcode() != ISD::EXTRACT_VECTOR_ELT) { 5689 // A shuffle can only come from building a vector from various 5690 // elements of other vectors. 5691 return SDValue(); 5692 } else if (!isa<ConstantSDNode>(V.getOperand(1))) { 5693 // Furthermore, shuffles require a constant mask, whereas extractelts 5694 // accept variable indices. 5695 return SDValue(); 5696 } 5697 5698 // Add this element source to the list if it's not already there. 5699 SDValue SourceVec = V.getOperand(0); 5700 auto Source = std::find(Sources.begin(), Sources.end(), SourceVec); 5701 if (Source == Sources.end()) 5702 Source = Sources.insert(Sources.end(), ShuffleSourceInfo(SourceVec)); 5703 5704 // Update the minimum and maximum lane number seen. 5705 unsigned EltNo = cast<ConstantSDNode>(V.getOperand(1))->getZExtValue(); 5706 Source->MinElt = std::min(Source->MinElt, EltNo); 5707 Source->MaxElt = std::max(Source->MaxElt, EltNo); 5708 } 5709 5710 // Currently only do something sane when at most two source vectors 5711 // are involved. 5712 if (Sources.size() > 2) 5713 return SDValue(); 5714 5715 // Find out the smallest element size among result and two sources, and use 5716 // it as element size to build the shuffle_vector. 5717 EVT SmallestEltTy = VT.getVectorElementType(); 5718 for (auto &Source : Sources) { 5719 EVT SrcEltTy = Source.Vec.getValueType().getVectorElementType(); 5720 if (SrcEltTy.bitsLT(SmallestEltTy)) 5721 SmallestEltTy = SrcEltTy; 5722 } 5723 unsigned ResMultiplier = 5724 VT.getVectorElementType().getSizeInBits() / SmallestEltTy.getSizeInBits(); 5725 NumElts = VT.getSizeInBits() / SmallestEltTy.getSizeInBits(); 5726 EVT ShuffleVT = EVT::getVectorVT(*DAG.getContext(), SmallestEltTy, NumElts); 5727 5728 // If the source vector is too wide or too narrow, we may nevertheless be able 5729 // to construct a compatible shuffle either by concatenating it with UNDEF or 5730 // extracting a suitable range of elements. 5731 for (auto &Src : Sources) { 5732 EVT SrcVT = Src.ShuffleVec.getValueType(); 5733 5734 if (SrcVT.getSizeInBits() == VT.getSizeInBits()) 5735 continue; 5736 5737 // This stage of the search produces a source with the same element type as 5738 // the original, but with a total width matching the BUILD_VECTOR output. 5739 EVT EltVT = SrcVT.getVectorElementType(); 5740 unsigned NumSrcElts = VT.getSizeInBits() / EltVT.getSizeInBits(); 5741 EVT DestVT = EVT::getVectorVT(*DAG.getContext(), EltVT, NumSrcElts); 5742 5743 if (SrcVT.getSizeInBits() < VT.getSizeInBits()) { 5744 if (2 * SrcVT.getSizeInBits() != VT.getSizeInBits()) 5745 return SDValue(); 5746 // We can pad out the smaller vector for free, so if it's part of a 5747 // shuffle... 5748 Src.ShuffleVec = 5749 DAG.getNode(ISD::CONCAT_VECTORS, dl, DestVT, Src.ShuffleVec, 5750 DAG.getUNDEF(Src.ShuffleVec.getValueType())); 5751 continue; 5752 } 5753 5754 if (SrcVT.getSizeInBits() != 2 * VT.getSizeInBits()) 5755 return SDValue(); 5756 5757 if (Src.MaxElt - Src.MinElt >= NumSrcElts) { 5758 // Span too large for a VEXT to cope 5759 return SDValue(); 5760 } 5761 5762 if (Src.MinElt >= NumSrcElts) { 5763 // The extraction can just take the second half 5764 Src.ShuffleVec = 5765 DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DestVT, Src.ShuffleVec, 5766 DAG.getConstant(NumSrcElts, dl, MVT::i32)); 5767 Src.WindowBase = -NumSrcElts; 5768 } else if (Src.MaxElt < NumSrcElts) { 5769 // The extraction can just take the first half 5770 Src.ShuffleVec = 5771 DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DestVT, Src.ShuffleVec, 5772 DAG.getConstant(0, dl, MVT::i32)); 5773 } else { 5774 // An actual VEXT is needed 5775 SDValue VEXTSrc1 = 5776 DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DestVT, Src.ShuffleVec, 5777 DAG.getConstant(0, dl, MVT::i32)); 5778 SDValue VEXTSrc2 = 5779 DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DestVT, Src.ShuffleVec, 5780 DAG.getConstant(NumSrcElts, dl, MVT::i32)); 5781 5782 Src.ShuffleVec = DAG.getNode(ARMISD::VEXT, dl, DestVT, VEXTSrc1, 5783 VEXTSrc2, 5784 DAG.getConstant(Src.MinElt, dl, MVT::i32)); 5785 Src.WindowBase = -Src.MinElt; 5786 } 5787 } 5788 5789 // Another possible incompatibility occurs from the vector element types. We 5790 // can fix this by bitcasting the source vectors to the same type we intend 5791 // for the shuffle. 5792 for (auto &Src : Sources) { 5793 EVT SrcEltTy = Src.ShuffleVec.getValueType().getVectorElementType(); 5794 if (SrcEltTy == SmallestEltTy) 5795 continue; 5796 assert(ShuffleVT.getVectorElementType() == SmallestEltTy); 5797 Src.ShuffleVec = DAG.getNode(ISD::BITCAST, dl, ShuffleVT, Src.ShuffleVec); 5798 Src.WindowScale = SrcEltTy.getSizeInBits() / SmallestEltTy.getSizeInBits(); 5799 Src.WindowBase *= Src.WindowScale; 5800 } 5801 5802 // Final sanity check before we try to actually produce a shuffle. 5803 DEBUG( 5804 for (auto Src : Sources) 5805 assert(Src.ShuffleVec.getValueType() == ShuffleVT); 5806 ); 5807 5808 // The stars all align, our next step is to produce the mask for the shuffle. 5809 SmallVector<int, 8> Mask(ShuffleVT.getVectorNumElements(), -1); 5810 int BitsPerShuffleLane = ShuffleVT.getVectorElementType().getSizeInBits(); 5811 for (unsigned i = 0; i < VT.getVectorNumElements(); ++i) { 5812 SDValue Entry = Op.getOperand(i); 5813 if (Entry.getOpcode() == ISD::UNDEF) 5814 continue; 5815 5816 auto Src = std::find(Sources.begin(), Sources.end(), Entry.getOperand(0)); 5817 int EltNo = cast<ConstantSDNode>(Entry.getOperand(1))->getSExtValue(); 5818 5819 // EXTRACT_VECTOR_ELT performs an implicit any_ext; BUILD_VECTOR an implicit 5820 // trunc. So only std::min(SrcBits, DestBits) actually get defined in this 5821 // segment. 5822 EVT OrigEltTy = Entry.getOperand(0).getValueType().getVectorElementType(); 5823 int BitsDefined = std::min(OrigEltTy.getSizeInBits(), 5824 VT.getVectorElementType().getSizeInBits()); 5825 int LanesDefined = BitsDefined / BitsPerShuffleLane; 5826 5827 // This source is expected to fill ResMultiplier lanes of the final shuffle, 5828 // starting at the appropriate offset. 5829 int *LaneMask = &Mask[i * ResMultiplier]; 5830 5831 int ExtractBase = EltNo * Src->WindowScale + Src->WindowBase; 5832 ExtractBase += NumElts * (Src - Sources.begin()); 5833 for (int j = 0; j < LanesDefined; ++j) 5834 LaneMask[j] = ExtractBase + j; 5835 } 5836 5837 // Final check before we try to produce nonsense... 5838 if (!isShuffleMaskLegal(Mask, ShuffleVT)) 5839 return SDValue(); 5840 5841 // We can't handle more than two sources. This should have already 5842 // been checked before this point. 5843 assert(Sources.size() <= 2 && "Too many sources!"); 5844 5845 SDValue ShuffleOps[] = { DAG.getUNDEF(ShuffleVT), DAG.getUNDEF(ShuffleVT) }; 5846 for (unsigned i = 0; i < Sources.size(); ++i) 5847 ShuffleOps[i] = Sources[i].ShuffleVec; 5848 5849 SDValue Shuffle = DAG.getVectorShuffle(ShuffleVT, dl, ShuffleOps[0], 5850 ShuffleOps[1], &Mask[0]); 5851 return DAG.getNode(ISD::BITCAST, dl, VT, Shuffle); 5852 } 5853 5854 /// isShuffleMaskLegal - Targets can use this to indicate that they only 5855 /// support *some* VECTOR_SHUFFLE operations, those with specific masks. 5856 /// By default, if a target supports the VECTOR_SHUFFLE node, all mask values 5857 /// are assumed to be legal. 5858 bool 5859 ARMTargetLowering::isShuffleMaskLegal(const SmallVectorImpl<int> &M, 5860 EVT VT) const { 5861 if (VT.getVectorNumElements() == 4 && 5862 (VT.is128BitVector() || VT.is64BitVector())) { 5863 unsigned PFIndexes[4]; 5864 for (unsigned i = 0; i != 4; ++i) { 5865 if (M[i] < 0) 5866 PFIndexes[i] = 8; 5867 else 5868 PFIndexes[i] = M[i]; 5869 } 5870 5871 // Compute the index in the perfect shuffle table. 5872 unsigned PFTableIndex = 5873 PFIndexes[0]*9*9*9+PFIndexes[1]*9*9+PFIndexes[2]*9+PFIndexes[3]; 5874 unsigned PFEntry = PerfectShuffleTable[PFTableIndex]; 5875 unsigned Cost = (PFEntry >> 30); 5876 5877 if (Cost <= 4) 5878 return true; 5879 } 5880 5881 bool ReverseVEXT, isV_UNDEF; 5882 unsigned Imm, WhichResult; 5883 5884 unsigned EltSize = VT.getVectorElementType().getSizeInBits(); 5885 return (EltSize >= 32 || 5886 ShuffleVectorSDNode::isSplatMask(&M[0], VT) || 5887 isVREVMask(M, VT, 64) || 5888 isVREVMask(M, VT, 32) || 5889 isVREVMask(M, VT, 16) || 5890 isVEXTMask(M, VT, ReverseVEXT, Imm) || 5891 isVTBLMask(M, VT) || 5892 isNEONTwoResultShuffleMask(M, VT, WhichResult, isV_UNDEF) || 5893 ((VT == MVT::v8i16 || VT == MVT::v16i8) && isReverseMask(M, VT))); 5894 } 5895 5896 /// GeneratePerfectShuffle - Given an entry in the perfect-shuffle table, emit 5897 /// the specified operations to build the shuffle. 5898 static SDValue GeneratePerfectShuffle(unsigned PFEntry, SDValue LHS, 5899 SDValue RHS, SelectionDAG &DAG, 5900 SDLoc dl) { 5901 unsigned OpNum = (PFEntry >> 26) & 0x0F; 5902 unsigned LHSID = (PFEntry >> 13) & ((1 << 13)-1); 5903 unsigned RHSID = (PFEntry >> 0) & ((1 << 13)-1); 5904 5905 enum { 5906 OP_COPY = 0, // Copy, used for things like <u,u,u,3> to say it is <0,1,2,3> 5907 OP_VREV, 5908 OP_VDUP0, 5909 OP_VDUP1, 5910 OP_VDUP2, 5911 OP_VDUP3, 5912 OP_VEXT1, 5913 OP_VEXT2, 5914 OP_VEXT3, 5915 OP_VUZPL, // VUZP, left result 5916 OP_VUZPR, // VUZP, right result 5917 OP_VZIPL, // VZIP, left result 5918 OP_VZIPR, // VZIP, right result 5919 OP_VTRNL, // VTRN, left result 5920 OP_VTRNR // VTRN, right result 5921 }; 5922 5923 if (OpNum == OP_COPY) { 5924 if (LHSID == (1*9+2)*9+3) return LHS; 5925 assert(LHSID == ((4*9+5)*9+6)*9+7 && "Illegal OP_COPY!"); 5926 return RHS; 5927 } 5928 5929 SDValue OpLHS, OpRHS; 5930 OpLHS = GeneratePerfectShuffle(PerfectShuffleTable[LHSID], LHS, RHS, DAG, dl); 5931 OpRHS = GeneratePerfectShuffle(PerfectShuffleTable[RHSID], LHS, RHS, DAG, dl); 5932 EVT VT = OpLHS.getValueType(); 5933 5934 switch (OpNum) { 5935 default: llvm_unreachable("Unknown shuffle opcode!"); 5936 case OP_VREV: 5937 // VREV divides the vector in half and swaps within the half. 5938 if (VT.getVectorElementType() == MVT::i32 || 5939 VT.getVectorElementType() == MVT::f32) 5940 return DAG.getNode(ARMISD::VREV64, dl, VT, OpLHS); 5941 // vrev <4 x i16> -> VREV32 5942 if (VT.getVectorElementType() == MVT::i16) 5943 return DAG.getNode(ARMISD::VREV32, dl, VT, OpLHS); 5944 // vrev <4 x i8> -> VREV16 5945 assert(VT.getVectorElementType() == MVT::i8); 5946 return DAG.getNode(ARMISD::VREV16, dl, VT, OpLHS); 5947 case OP_VDUP0: 5948 case OP_VDUP1: 5949 case OP_VDUP2: 5950 case OP_VDUP3: 5951 return DAG.getNode(ARMISD::VDUPLANE, dl, VT, 5952 OpLHS, DAG.getConstant(OpNum-OP_VDUP0, dl, MVT::i32)); 5953 case OP_VEXT1: 5954 case OP_VEXT2: 5955 case OP_VEXT3: 5956 return DAG.getNode(ARMISD::VEXT, dl, VT, 5957 OpLHS, OpRHS, 5958 DAG.getConstant(OpNum - OP_VEXT1 + 1, dl, MVT::i32)); 5959 case OP_VUZPL: 5960 case OP_VUZPR: 5961 return DAG.getNode(ARMISD::VUZP, dl, DAG.getVTList(VT, VT), 5962 OpLHS, OpRHS).getValue(OpNum-OP_VUZPL); 5963 case OP_VZIPL: 5964 case OP_VZIPR: 5965 return DAG.getNode(ARMISD::VZIP, dl, DAG.getVTList(VT, VT), 5966 OpLHS, OpRHS).getValue(OpNum-OP_VZIPL); 5967 case OP_VTRNL: 5968 case OP_VTRNR: 5969 return DAG.getNode(ARMISD::VTRN, dl, DAG.getVTList(VT, VT), 5970 OpLHS, OpRHS).getValue(OpNum-OP_VTRNL); 5971 } 5972 } 5973 5974 static SDValue LowerVECTOR_SHUFFLEv8i8(SDValue Op, 5975 ArrayRef<int> ShuffleMask, 5976 SelectionDAG &DAG) { 5977 // Check to see if we can use the VTBL instruction. 5978 SDValue V1 = Op.getOperand(0); 5979 SDValue V2 = Op.getOperand(1); 5980 SDLoc DL(Op); 5981 5982 SmallVector<SDValue, 8> VTBLMask; 5983 for (ArrayRef<int>::iterator 5984 I = ShuffleMask.begin(), E = ShuffleMask.end(); I != E; ++I) 5985 VTBLMask.push_back(DAG.getConstant(*I, DL, MVT::i32)); 5986 5987 if (V2.getNode()->getOpcode() == ISD::UNDEF) 5988 return DAG.getNode(ARMISD::VTBL1, DL, MVT::v8i8, V1, 5989 DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v8i8, VTBLMask)); 5990 5991 return DAG.getNode(ARMISD::VTBL2, DL, MVT::v8i8, V1, V2, 5992 DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v8i8, VTBLMask)); 5993 } 5994 5995 static SDValue LowerReverse_VECTOR_SHUFFLEv16i8_v8i16(SDValue Op, 5996 SelectionDAG &DAG) { 5997 SDLoc DL(Op); 5998 SDValue OpLHS = Op.getOperand(0); 5999 EVT VT = OpLHS.getValueType(); 6000 6001 assert((VT == MVT::v8i16 || VT == MVT::v16i8) && 6002 "Expect an v8i16/v16i8 type"); 6003 OpLHS = DAG.getNode(ARMISD::VREV64, DL, VT, OpLHS); 6004 // For a v16i8 type: After the VREV, we have got <8, ...15, 8, ..., 0>. Now, 6005 // extract the first 8 bytes into the top double word and the last 8 bytes 6006 // into the bottom double word. The v8i16 case is similar. 6007 unsigned ExtractNum = (VT == MVT::v16i8) ? 8 : 4; 6008 return DAG.getNode(ARMISD::VEXT, DL, VT, OpLHS, OpLHS, 6009 DAG.getConstant(ExtractNum, DL, MVT::i32)); 6010 } 6011 6012 static SDValue LowerVECTOR_SHUFFLE(SDValue Op, SelectionDAG &DAG) { 6013 SDValue V1 = Op.getOperand(0); 6014 SDValue V2 = Op.getOperand(1); 6015 SDLoc dl(Op); 6016 EVT VT = Op.getValueType(); 6017 ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(Op.getNode()); 6018 6019 // Convert shuffles that are directly supported on NEON to target-specific 6020 // DAG nodes, instead of keeping them as shuffles and matching them again 6021 // during code selection. This is more efficient and avoids the possibility 6022 // of inconsistencies between legalization and selection. 6023 // FIXME: floating-point vectors should be canonicalized to integer vectors 6024 // of the same time so that they get CSEd properly. 6025 ArrayRef<int> ShuffleMask = SVN->getMask(); 6026 6027 unsigned EltSize = VT.getVectorElementType().getSizeInBits(); 6028 if (EltSize <= 32) { 6029 if (ShuffleVectorSDNode::isSplatMask(&ShuffleMask[0], VT)) { 6030 int Lane = SVN->getSplatIndex(); 6031 // If this is undef splat, generate it via "just" vdup, if possible. 6032 if (Lane == -1) Lane = 0; 6033 6034 // Test if V1 is a SCALAR_TO_VECTOR. 6035 if (Lane == 0 && V1.getOpcode() == ISD::SCALAR_TO_VECTOR) { 6036 return DAG.getNode(ARMISD::VDUP, dl, VT, V1.getOperand(0)); 6037 } 6038 // Test if V1 is a BUILD_VECTOR which is equivalent to a SCALAR_TO_VECTOR 6039 // (and probably will turn into a SCALAR_TO_VECTOR once legalization 6040 // reaches it). 6041 if (Lane == 0 && V1.getOpcode() == ISD::BUILD_VECTOR && 6042 !isa<ConstantSDNode>(V1.getOperand(0))) { 6043 bool IsScalarToVector = true; 6044 for (unsigned i = 1, e = V1.getNumOperands(); i != e; ++i) 6045 if (V1.getOperand(i).getOpcode() != ISD::UNDEF) { 6046 IsScalarToVector = false; 6047 break; 6048 } 6049 if (IsScalarToVector) 6050 return DAG.getNode(ARMISD::VDUP, dl, VT, V1.getOperand(0)); 6051 } 6052 return DAG.getNode(ARMISD::VDUPLANE, dl, VT, V1, 6053 DAG.getConstant(Lane, dl, MVT::i32)); 6054 } 6055 6056 bool ReverseVEXT; 6057 unsigned Imm; 6058 if (isVEXTMask(ShuffleMask, VT, ReverseVEXT, Imm)) { 6059 if (ReverseVEXT) 6060 std::swap(V1, V2); 6061 return DAG.getNode(ARMISD::VEXT, dl, VT, V1, V2, 6062 DAG.getConstant(Imm, dl, MVT::i32)); 6063 } 6064 6065 if (isVREVMask(ShuffleMask, VT, 64)) 6066 return DAG.getNode(ARMISD::VREV64, dl, VT, V1); 6067 if (isVREVMask(ShuffleMask, VT, 32)) 6068 return DAG.getNode(ARMISD::VREV32, dl, VT, V1); 6069 if (isVREVMask(ShuffleMask, VT, 16)) 6070 return DAG.getNode(ARMISD::VREV16, dl, VT, V1); 6071 6072 if (V2->getOpcode() == ISD::UNDEF && 6073 isSingletonVEXTMask(ShuffleMask, VT, Imm)) { 6074 return DAG.getNode(ARMISD::VEXT, dl, VT, V1, V1, 6075 DAG.getConstant(Imm, dl, MVT::i32)); 6076 } 6077 6078 // Check for Neon shuffles that modify both input vectors in place. 6079 // If both results are used, i.e., if there are two shuffles with the same 6080 // source operands and with masks corresponding to both results of one of 6081 // these operations, DAG memoization will ensure that a single node is 6082 // used for both shuffles. 6083 unsigned WhichResult; 6084 bool isV_UNDEF; 6085 if (unsigned ShuffleOpc = isNEONTwoResultShuffleMask( 6086 ShuffleMask, VT, WhichResult, isV_UNDEF)) { 6087 if (isV_UNDEF) 6088 V2 = V1; 6089 return DAG.getNode(ShuffleOpc, dl, DAG.getVTList(VT, VT), V1, V2) 6090 .getValue(WhichResult); 6091 } 6092 6093 // Also check for these shuffles through CONCAT_VECTORS: we canonicalize 6094 // shuffles that produce a result larger than their operands with: 6095 // shuffle(concat(v1, undef), concat(v2, undef)) 6096 // -> 6097 // shuffle(concat(v1, v2), undef) 6098 // because we can access quad vectors (see PerformVECTOR_SHUFFLECombine). 6099 // 6100 // This is useful in the general case, but there are special cases where 6101 // native shuffles produce larger results: the two-result ops. 6102 // 6103 // Look through the concat when lowering them: 6104 // shuffle(concat(v1, v2), undef) 6105 // -> 6106 // concat(VZIP(v1, v2):0, :1) 6107 // 6108 if (V1->getOpcode() == ISD::CONCAT_VECTORS && 6109 V2->getOpcode() == ISD::UNDEF) { 6110 SDValue SubV1 = V1->getOperand(0); 6111 SDValue SubV2 = V1->getOperand(1); 6112 EVT SubVT = SubV1.getValueType(); 6113 6114 // We expect these to have been canonicalized to -1. 6115 assert(std::all_of(ShuffleMask.begin(), ShuffleMask.end(), [&](int i) { 6116 return i < (int)VT.getVectorNumElements(); 6117 }) && "Unexpected shuffle index into UNDEF operand!"); 6118 6119 if (unsigned ShuffleOpc = isNEONTwoResultShuffleMask( 6120 ShuffleMask, SubVT, WhichResult, isV_UNDEF)) { 6121 if (isV_UNDEF) 6122 SubV2 = SubV1; 6123 assert((WhichResult == 0) && 6124 "In-place shuffle of concat can only have one result!"); 6125 SDValue Res = DAG.getNode(ShuffleOpc, dl, DAG.getVTList(SubVT, SubVT), 6126 SubV1, SubV2); 6127 return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, Res.getValue(0), 6128 Res.getValue(1)); 6129 } 6130 } 6131 } 6132 6133 // If the shuffle is not directly supported and it has 4 elements, use 6134 // the PerfectShuffle-generated table to synthesize it from other shuffles. 6135 unsigned NumElts = VT.getVectorNumElements(); 6136 if (NumElts == 4) { 6137 unsigned PFIndexes[4]; 6138 for (unsigned i = 0; i != 4; ++i) { 6139 if (ShuffleMask[i] < 0) 6140 PFIndexes[i] = 8; 6141 else 6142 PFIndexes[i] = ShuffleMask[i]; 6143 } 6144 6145 // Compute the index in the perfect shuffle table. 6146 unsigned PFTableIndex = 6147 PFIndexes[0]*9*9*9+PFIndexes[1]*9*9+PFIndexes[2]*9+PFIndexes[3]; 6148 unsigned PFEntry = PerfectShuffleTable[PFTableIndex]; 6149 unsigned Cost = (PFEntry >> 30); 6150 6151 if (Cost <= 4) 6152 return GeneratePerfectShuffle(PFEntry, V1, V2, DAG, dl); 6153 } 6154 6155 // Implement shuffles with 32- or 64-bit elements as ARMISD::BUILD_VECTORs. 6156 if (EltSize >= 32) { 6157 // Do the expansion with floating-point types, since that is what the VFP 6158 // registers are defined to use, and since i64 is not legal. 6159 EVT EltVT = EVT::getFloatingPointVT(EltSize); 6160 EVT VecVT = EVT::getVectorVT(*DAG.getContext(), EltVT, NumElts); 6161 V1 = DAG.getNode(ISD::BITCAST, dl, VecVT, V1); 6162 V2 = DAG.getNode(ISD::BITCAST, dl, VecVT, V2); 6163 SmallVector<SDValue, 8> Ops; 6164 for (unsigned i = 0; i < NumElts; ++i) { 6165 if (ShuffleMask[i] < 0) 6166 Ops.push_back(DAG.getUNDEF(EltVT)); 6167 else 6168 Ops.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, EltVT, 6169 ShuffleMask[i] < (int)NumElts ? V1 : V2, 6170 DAG.getConstant(ShuffleMask[i] & (NumElts-1), 6171 dl, MVT::i32))); 6172 } 6173 SDValue Val = DAG.getNode(ARMISD::BUILD_VECTOR, dl, VecVT, Ops); 6174 return DAG.getNode(ISD::BITCAST, dl, VT, Val); 6175 } 6176 6177 if ((VT == MVT::v8i16 || VT == MVT::v16i8) && isReverseMask(ShuffleMask, VT)) 6178 return LowerReverse_VECTOR_SHUFFLEv16i8_v8i16(Op, DAG); 6179 6180 if (VT == MVT::v8i8) { 6181 SDValue NewOp = LowerVECTOR_SHUFFLEv8i8(Op, ShuffleMask, DAG); 6182 if (NewOp.getNode()) 6183 return NewOp; 6184 } 6185 6186 return SDValue(); 6187 } 6188 6189 static SDValue LowerINSERT_VECTOR_ELT(SDValue Op, SelectionDAG &DAG) { 6190 // INSERT_VECTOR_ELT is legal only for immediate indexes. 6191 SDValue Lane = Op.getOperand(2); 6192 if (!isa<ConstantSDNode>(Lane)) 6193 return SDValue(); 6194 6195 return Op; 6196 } 6197 6198 static SDValue LowerEXTRACT_VECTOR_ELT(SDValue Op, SelectionDAG &DAG) { 6199 // EXTRACT_VECTOR_ELT is legal only for immediate indexes. 6200 SDValue Lane = Op.getOperand(1); 6201 if (!isa<ConstantSDNode>(Lane)) 6202 return SDValue(); 6203 6204 SDValue Vec = Op.getOperand(0); 6205 if (Op.getValueType() == MVT::i32 && 6206 Vec.getValueType().getVectorElementType().getSizeInBits() < 32) { 6207 SDLoc dl(Op); 6208 return DAG.getNode(ARMISD::VGETLANEu, dl, MVT::i32, Vec, Lane); 6209 } 6210 6211 return Op; 6212 } 6213 6214 static SDValue LowerCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG) { 6215 // The only time a CONCAT_VECTORS operation can have legal types is when 6216 // two 64-bit vectors are concatenated to a 128-bit vector. 6217 assert(Op.getValueType().is128BitVector() && Op.getNumOperands() == 2 && 6218 "unexpected CONCAT_VECTORS"); 6219 SDLoc dl(Op); 6220 SDValue Val = DAG.getUNDEF(MVT::v2f64); 6221 SDValue Op0 = Op.getOperand(0); 6222 SDValue Op1 = Op.getOperand(1); 6223 if (Op0.getOpcode() != ISD::UNDEF) 6224 Val = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Val, 6225 DAG.getNode(ISD::BITCAST, dl, MVT::f64, Op0), 6226 DAG.getIntPtrConstant(0, dl)); 6227 if (Op1.getOpcode() != ISD::UNDEF) 6228 Val = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Val, 6229 DAG.getNode(ISD::BITCAST, dl, MVT::f64, Op1), 6230 DAG.getIntPtrConstant(1, dl)); 6231 return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Val); 6232 } 6233 6234 /// isExtendedBUILD_VECTOR - Check if N is a constant BUILD_VECTOR where each 6235 /// element has been zero/sign-extended, depending on the isSigned parameter, 6236 /// from an integer type half its size. 6237 static bool isExtendedBUILD_VECTOR(SDNode *N, SelectionDAG &DAG, 6238 bool isSigned) { 6239 // A v2i64 BUILD_VECTOR will have been legalized to a BITCAST from v4i32. 6240 EVT VT = N->getValueType(0); 6241 if (VT == MVT::v2i64 && N->getOpcode() == ISD::BITCAST) { 6242 SDNode *BVN = N->getOperand(0).getNode(); 6243 if (BVN->getValueType(0) != MVT::v4i32 || 6244 BVN->getOpcode() != ISD::BUILD_VECTOR) 6245 return false; 6246 unsigned LoElt = DAG.getDataLayout().isBigEndian() ? 1 : 0; 6247 unsigned HiElt = 1 - LoElt; 6248 ConstantSDNode *Lo0 = dyn_cast<ConstantSDNode>(BVN->getOperand(LoElt)); 6249 ConstantSDNode *Hi0 = dyn_cast<ConstantSDNode>(BVN->getOperand(HiElt)); 6250 ConstantSDNode *Lo1 = dyn_cast<ConstantSDNode>(BVN->getOperand(LoElt+2)); 6251 ConstantSDNode *Hi1 = dyn_cast<ConstantSDNode>(BVN->getOperand(HiElt+2)); 6252 if (!Lo0 || !Hi0 || !Lo1 || !Hi1) 6253 return false; 6254 if (isSigned) { 6255 if (Hi0->getSExtValue() == Lo0->getSExtValue() >> 32 && 6256 Hi1->getSExtValue() == Lo1->getSExtValue() >> 32) 6257 return true; 6258 } else { 6259 if (Hi0->isNullValue() && Hi1->isNullValue()) 6260 return true; 6261 } 6262 return false; 6263 } 6264 6265 if (N->getOpcode() != ISD::BUILD_VECTOR) 6266 return false; 6267 6268 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) { 6269 SDNode *Elt = N->getOperand(i).getNode(); 6270 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Elt)) { 6271 unsigned EltSize = VT.getVectorElementType().getSizeInBits(); 6272 unsigned HalfSize = EltSize / 2; 6273 if (isSigned) { 6274 if (!isIntN(HalfSize, C->getSExtValue())) 6275 return false; 6276 } else { 6277 if (!isUIntN(HalfSize, C->getZExtValue())) 6278 return false; 6279 } 6280 continue; 6281 } 6282 return false; 6283 } 6284 6285 return true; 6286 } 6287 6288 /// isSignExtended - Check if a node is a vector value that is sign-extended 6289 /// or a constant BUILD_VECTOR with sign-extended elements. 6290 static bool isSignExtended(SDNode *N, SelectionDAG &DAG) { 6291 if (N->getOpcode() == ISD::SIGN_EXTEND || ISD::isSEXTLoad(N)) 6292 return true; 6293 if (isExtendedBUILD_VECTOR(N, DAG, true)) 6294 return true; 6295 return false; 6296 } 6297 6298 /// isZeroExtended - Check if a node is a vector value that is zero-extended 6299 /// or a constant BUILD_VECTOR with zero-extended elements. 6300 static bool isZeroExtended(SDNode *N, SelectionDAG &DAG) { 6301 if (N->getOpcode() == ISD::ZERO_EXTEND || ISD::isZEXTLoad(N)) 6302 return true; 6303 if (isExtendedBUILD_VECTOR(N, DAG, false)) 6304 return true; 6305 return false; 6306 } 6307 6308 static EVT getExtensionTo64Bits(const EVT &OrigVT) { 6309 if (OrigVT.getSizeInBits() >= 64) 6310 return OrigVT; 6311 6312 assert(OrigVT.isSimple() && "Expecting a simple value type"); 6313 6314 MVT::SimpleValueType OrigSimpleTy = OrigVT.getSimpleVT().SimpleTy; 6315 switch (OrigSimpleTy) { 6316 default: llvm_unreachable("Unexpected Vector Type"); 6317 case MVT::v2i8: 6318 case MVT::v2i16: 6319 return MVT::v2i32; 6320 case MVT::v4i8: 6321 return MVT::v4i16; 6322 } 6323 } 6324 6325 /// AddRequiredExtensionForVMULL - Add a sign/zero extension to extend the total 6326 /// value size to 64 bits. We need a 64-bit D register as an operand to VMULL. 6327 /// We insert the required extension here to get the vector to fill a D register. 6328 static SDValue AddRequiredExtensionForVMULL(SDValue N, SelectionDAG &DAG, 6329 const EVT &OrigTy, 6330 const EVT &ExtTy, 6331 unsigned ExtOpcode) { 6332 // The vector originally had a size of OrigTy. It was then extended to ExtTy. 6333 // We expect the ExtTy to be 128-bits total. If the OrigTy is less than 6334 // 64-bits we need to insert a new extension so that it will be 64-bits. 6335 assert(ExtTy.is128BitVector() && "Unexpected extension size"); 6336 if (OrigTy.getSizeInBits() >= 64) 6337 return N; 6338 6339 // Must extend size to at least 64 bits to be used as an operand for VMULL. 6340 EVT NewVT = getExtensionTo64Bits(OrigTy); 6341 6342 return DAG.getNode(ExtOpcode, SDLoc(N), NewVT, N); 6343 } 6344 6345 /// SkipLoadExtensionForVMULL - return a load of the original vector size that 6346 /// does not do any sign/zero extension. If the original vector is less 6347 /// than 64 bits, an appropriate extension will be added after the load to 6348 /// reach a total size of 64 bits. We have to add the extension separately 6349 /// because ARM does not have a sign/zero extending load for vectors. 6350 static SDValue SkipLoadExtensionForVMULL(LoadSDNode *LD, SelectionDAG& DAG) { 6351 EVT ExtendedTy = getExtensionTo64Bits(LD->getMemoryVT()); 6352 6353 // The load already has the right type. 6354 if (ExtendedTy == LD->getMemoryVT()) 6355 return DAG.getLoad(LD->getMemoryVT(), SDLoc(LD), LD->getChain(), 6356 LD->getBasePtr(), LD->getPointerInfo(), LD->isVolatile(), 6357 LD->isNonTemporal(), LD->isInvariant(), 6358 LD->getAlignment()); 6359 6360 // We need to create a zextload/sextload. We cannot just create a load 6361 // followed by a zext/zext node because LowerMUL is also run during normal 6362 // operation legalization where we can't create illegal types. 6363 return DAG.getExtLoad(LD->getExtensionType(), SDLoc(LD), ExtendedTy, 6364 LD->getChain(), LD->getBasePtr(), LD->getPointerInfo(), 6365 LD->getMemoryVT(), LD->isVolatile(), LD->isInvariant(), 6366 LD->isNonTemporal(), LD->getAlignment()); 6367 } 6368 6369 /// SkipExtensionForVMULL - For a node that is a SIGN_EXTEND, ZERO_EXTEND, 6370 /// extending load, or BUILD_VECTOR with extended elements, return the 6371 /// unextended value. The unextended vector should be 64 bits so that it can 6372 /// be used as an operand to a VMULL instruction. If the original vector size 6373 /// before extension is less than 64 bits we add a an extension to resize 6374 /// the vector to 64 bits. 6375 static SDValue SkipExtensionForVMULL(SDNode *N, SelectionDAG &DAG) { 6376 if (N->getOpcode() == ISD::SIGN_EXTEND || N->getOpcode() == ISD::ZERO_EXTEND) 6377 return AddRequiredExtensionForVMULL(N->getOperand(0), DAG, 6378 N->getOperand(0)->getValueType(0), 6379 N->getValueType(0), 6380 N->getOpcode()); 6381 6382 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) 6383 return SkipLoadExtensionForVMULL(LD, DAG); 6384 6385 // Otherwise, the value must be a BUILD_VECTOR. For v2i64, it will 6386 // have been legalized as a BITCAST from v4i32. 6387 if (N->getOpcode() == ISD::BITCAST) { 6388 SDNode *BVN = N->getOperand(0).getNode(); 6389 assert(BVN->getOpcode() == ISD::BUILD_VECTOR && 6390 BVN->getValueType(0) == MVT::v4i32 && "expected v4i32 BUILD_VECTOR"); 6391 unsigned LowElt = DAG.getDataLayout().isBigEndian() ? 1 : 0; 6392 return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), MVT::v2i32, 6393 BVN->getOperand(LowElt), BVN->getOperand(LowElt+2)); 6394 } 6395 // Construct a new BUILD_VECTOR with elements truncated to half the size. 6396 assert(N->getOpcode() == ISD::BUILD_VECTOR && "expected BUILD_VECTOR"); 6397 EVT VT = N->getValueType(0); 6398 unsigned EltSize = VT.getVectorElementType().getSizeInBits() / 2; 6399 unsigned NumElts = VT.getVectorNumElements(); 6400 MVT TruncVT = MVT::getIntegerVT(EltSize); 6401 SmallVector<SDValue, 8> Ops; 6402 SDLoc dl(N); 6403 for (unsigned i = 0; i != NumElts; ++i) { 6404 ConstantSDNode *C = cast<ConstantSDNode>(N->getOperand(i)); 6405 const APInt &CInt = C->getAPIntValue(); 6406 // Element types smaller than 32 bits are not legal, so use i32 elements. 6407 // The values are implicitly truncated so sext vs. zext doesn't matter. 6408 Ops.push_back(DAG.getConstant(CInt.zextOrTrunc(32), dl, MVT::i32)); 6409 } 6410 return DAG.getNode(ISD::BUILD_VECTOR, dl, 6411 MVT::getVectorVT(TruncVT, NumElts), Ops); 6412 } 6413 6414 static bool isAddSubSExt(SDNode *N, SelectionDAG &DAG) { 6415 unsigned Opcode = N->getOpcode(); 6416 if (Opcode == ISD::ADD || Opcode == ISD::SUB) { 6417 SDNode *N0 = N->getOperand(0).getNode(); 6418 SDNode *N1 = N->getOperand(1).getNode(); 6419 return N0->hasOneUse() && N1->hasOneUse() && 6420 isSignExtended(N0, DAG) && isSignExtended(N1, DAG); 6421 } 6422 return false; 6423 } 6424 6425 static bool isAddSubZExt(SDNode *N, SelectionDAG &DAG) { 6426 unsigned Opcode = N->getOpcode(); 6427 if (Opcode == ISD::ADD || Opcode == ISD::SUB) { 6428 SDNode *N0 = N->getOperand(0).getNode(); 6429 SDNode *N1 = N->getOperand(1).getNode(); 6430 return N0->hasOneUse() && N1->hasOneUse() && 6431 isZeroExtended(N0, DAG) && isZeroExtended(N1, DAG); 6432 } 6433 return false; 6434 } 6435 6436 static SDValue LowerMUL(SDValue Op, SelectionDAG &DAG) { 6437 // Multiplications are only custom-lowered for 128-bit vectors so that 6438 // VMULL can be detected. Otherwise v2i64 multiplications are not legal. 6439 EVT VT = Op.getValueType(); 6440 assert(VT.is128BitVector() && VT.isInteger() && 6441 "unexpected type for custom-lowering ISD::MUL"); 6442 SDNode *N0 = Op.getOperand(0).getNode(); 6443 SDNode *N1 = Op.getOperand(1).getNode(); 6444 unsigned NewOpc = 0; 6445 bool isMLA = false; 6446 bool isN0SExt = isSignExtended(N0, DAG); 6447 bool isN1SExt = isSignExtended(N1, DAG); 6448 if (isN0SExt && isN1SExt) 6449 NewOpc = ARMISD::VMULLs; 6450 else { 6451 bool isN0ZExt = isZeroExtended(N0, DAG); 6452 bool isN1ZExt = isZeroExtended(N1, DAG); 6453 if (isN0ZExt && isN1ZExt) 6454 NewOpc = ARMISD::VMULLu; 6455 else if (isN1SExt || isN1ZExt) { 6456 // Look for (s/zext A + s/zext B) * (s/zext C). We want to turn these 6457 // into (s/zext A * s/zext C) + (s/zext B * s/zext C) 6458 if (isN1SExt && isAddSubSExt(N0, DAG)) { 6459 NewOpc = ARMISD::VMULLs; 6460 isMLA = true; 6461 } else if (isN1ZExt && isAddSubZExt(N0, DAG)) { 6462 NewOpc = ARMISD::VMULLu; 6463 isMLA = true; 6464 } else if (isN0ZExt && isAddSubZExt(N1, DAG)) { 6465 std::swap(N0, N1); 6466 NewOpc = ARMISD::VMULLu; 6467 isMLA = true; 6468 } 6469 } 6470 6471 if (!NewOpc) { 6472 if (VT == MVT::v2i64) 6473 // Fall through to expand this. It is not legal. 6474 return SDValue(); 6475 else 6476 // Other vector multiplications are legal. 6477 return Op; 6478 } 6479 } 6480 6481 // Legalize to a VMULL instruction. 6482 SDLoc DL(Op); 6483 SDValue Op0; 6484 SDValue Op1 = SkipExtensionForVMULL(N1, DAG); 6485 if (!isMLA) { 6486 Op0 = SkipExtensionForVMULL(N0, DAG); 6487 assert(Op0.getValueType().is64BitVector() && 6488 Op1.getValueType().is64BitVector() && 6489 "unexpected types for extended operands to VMULL"); 6490 return DAG.getNode(NewOpc, DL, VT, Op0, Op1); 6491 } 6492 6493 // Optimizing (zext A + zext B) * C, to (VMULL A, C) + (VMULL B, C) during 6494 // isel lowering to take advantage of no-stall back to back vmul + vmla. 6495 // vmull q0, d4, d6 6496 // vmlal q0, d5, d6 6497 // is faster than 6498 // vaddl q0, d4, d5 6499 // vmovl q1, d6 6500 // vmul q0, q0, q1 6501 SDValue N00 = SkipExtensionForVMULL(N0->getOperand(0).getNode(), DAG); 6502 SDValue N01 = SkipExtensionForVMULL(N0->getOperand(1).getNode(), DAG); 6503 EVT Op1VT = Op1.getValueType(); 6504 return DAG.getNode(N0->getOpcode(), DL, VT, 6505 DAG.getNode(NewOpc, DL, VT, 6506 DAG.getNode(ISD::BITCAST, DL, Op1VT, N00), Op1), 6507 DAG.getNode(NewOpc, DL, VT, 6508 DAG.getNode(ISD::BITCAST, DL, Op1VT, N01), Op1)); 6509 } 6510 6511 static SDValue 6512 LowerSDIV_v4i8(SDValue X, SDValue Y, SDLoc dl, SelectionDAG &DAG) { 6513 // TODO: Should this propagate fast-math-flags? 6514 6515 // Convert to float 6516 // float4 xf = vcvt_f32_s32(vmovl_s16(a.lo)); 6517 // float4 yf = vcvt_f32_s32(vmovl_s16(b.lo)); 6518 X = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, X); 6519 Y = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, Y); 6520 X = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, X); 6521 Y = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, Y); 6522 // Get reciprocal estimate. 6523 // float4 recip = vrecpeq_f32(yf); 6524 Y = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32, 6525 DAG.getConstant(Intrinsic::arm_neon_vrecpe, dl, MVT::i32), 6526 Y); 6527 // Because char has a smaller range than uchar, we can actually get away 6528 // without any newton steps. This requires that we use a weird bias 6529 // of 0xb000, however (again, this has been exhaustively tested). 6530 // float4 result = as_float4(as_int4(xf*recip) + 0xb000); 6531 X = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, X, Y); 6532 X = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, X); 6533 Y = DAG.getConstant(0xb000, dl, MVT::i32); 6534 Y = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Y, Y, Y, Y); 6535 X = DAG.getNode(ISD::ADD, dl, MVT::v4i32, X, Y); 6536 X = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, X); 6537 // Convert back to short. 6538 X = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::v4i32, X); 6539 X = DAG.getNode(ISD::TRUNCATE, dl, MVT::v4i16, X); 6540 return X; 6541 } 6542 6543 static SDValue 6544 LowerSDIV_v4i16(SDValue N0, SDValue N1, SDLoc dl, SelectionDAG &DAG) { 6545 // TODO: Should this propagate fast-math-flags? 6546 6547 SDValue N2; 6548 // Convert to float. 6549 // float4 yf = vcvt_f32_s32(vmovl_s16(y)); 6550 // float4 xf = vcvt_f32_s32(vmovl_s16(x)); 6551 N0 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, N0); 6552 N1 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, N1); 6553 N0 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N0); 6554 N1 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N1); 6555 6556 // Use reciprocal estimate and one refinement step. 6557 // float4 recip = vrecpeq_f32(yf); 6558 // recip *= vrecpsq_f32(yf, recip); 6559 N2 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32, 6560 DAG.getConstant(Intrinsic::arm_neon_vrecpe, dl, MVT::i32), 6561 N1); 6562 N1 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32, 6563 DAG.getConstant(Intrinsic::arm_neon_vrecps, dl, MVT::i32), 6564 N1, N2); 6565 N2 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N1, N2); 6566 // Because short has a smaller range than ushort, we can actually get away 6567 // with only a single newton step. This requires that we use a weird bias 6568 // of 89, however (again, this has been exhaustively tested). 6569 // float4 result = as_float4(as_int4(xf*recip) + 0x89); 6570 N0 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N0, N2); 6571 N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, N0); 6572 N1 = DAG.getConstant(0x89, dl, MVT::i32); 6573 N1 = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, N1, N1, N1, N1); 6574 N0 = DAG.getNode(ISD::ADD, dl, MVT::v4i32, N0, N1); 6575 N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, N0); 6576 // Convert back to integer and return. 6577 // return vmovn_s32(vcvt_s32_f32(result)); 6578 N0 = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::v4i32, N0); 6579 N0 = DAG.getNode(ISD::TRUNCATE, dl, MVT::v4i16, N0); 6580 return N0; 6581 } 6582 6583 static SDValue LowerSDIV(SDValue Op, SelectionDAG &DAG) { 6584 EVT VT = Op.getValueType(); 6585 assert((VT == MVT::v4i16 || VT == MVT::v8i8) && 6586 "unexpected type for custom-lowering ISD::SDIV"); 6587 6588 SDLoc dl(Op); 6589 SDValue N0 = Op.getOperand(0); 6590 SDValue N1 = Op.getOperand(1); 6591 SDValue N2, N3; 6592 6593 if (VT == MVT::v8i8) { 6594 N0 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v8i16, N0); 6595 N1 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v8i16, N1); 6596 6597 N2 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0, 6598 DAG.getIntPtrConstant(4, dl)); 6599 N3 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1, 6600 DAG.getIntPtrConstant(4, dl)); 6601 N0 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0, 6602 DAG.getIntPtrConstant(0, dl)); 6603 N1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1, 6604 DAG.getIntPtrConstant(0, dl)); 6605 6606 N0 = LowerSDIV_v4i8(N0, N1, dl, DAG); // v4i16 6607 N2 = LowerSDIV_v4i8(N2, N3, dl, DAG); // v4i16 6608 6609 N0 = DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v8i16, N0, N2); 6610 N0 = LowerCONCAT_VECTORS(N0, DAG); 6611 6612 N0 = DAG.getNode(ISD::TRUNCATE, dl, MVT::v8i8, N0); 6613 return N0; 6614 } 6615 return LowerSDIV_v4i16(N0, N1, dl, DAG); 6616 } 6617 6618 static SDValue LowerUDIV(SDValue Op, SelectionDAG &DAG) { 6619 // TODO: Should this propagate fast-math-flags? 6620 EVT VT = Op.getValueType(); 6621 assert((VT == MVT::v4i16 || VT == MVT::v8i8) && 6622 "unexpected type for custom-lowering ISD::UDIV"); 6623 6624 SDLoc dl(Op); 6625 SDValue N0 = Op.getOperand(0); 6626 SDValue N1 = Op.getOperand(1); 6627 SDValue N2, N3; 6628 6629 if (VT == MVT::v8i8) { 6630 N0 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v8i16, N0); 6631 N1 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v8i16, N1); 6632 6633 N2 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0, 6634 DAG.getIntPtrConstant(4, dl)); 6635 N3 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1, 6636 DAG.getIntPtrConstant(4, dl)); 6637 N0 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0, 6638 DAG.getIntPtrConstant(0, dl)); 6639 N1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1, 6640 DAG.getIntPtrConstant(0, dl)); 6641 6642 N0 = LowerSDIV_v4i16(N0, N1, dl, DAG); // v4i16 6643 N2 = LowerSDIV_v4i16(N2, N3, dl, DAG); // v4i16 6644 6645 N0 = DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v8i16, N0, N2); 6646 N0 = LowerCONCAT_VECTORS(N0, DAG); 6647 6648 N0 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v8i8, 6649 DAG.getConstant(Intrinsic::arm_neon_vqmovnsu, dl, 6650 MVT::i32), 6651 N0); 6652 return N0; 6653 } 6654 6655 // v4i16 sdiv ... Convert to float. 6656 // float4 yf = vcvt_f32_s32(vmovl_u16(y)); 6657 // float4 xf = vcvt_f32_s32(vmovl_u16(x)); 6658 N0 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v4i32, N0); 6659 N1 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v4i32, N1); 6660 N0 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N0); 6661 SDValue BN1 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N1); 6662 6663 // Use reciprocal estimate and two refinement steps. 6664 // float4 recip = vrecpeq_f32(yf); 6665 // recip *= vrecpsq_f32(yf, recip); 6666 // recip *= vrecpsq_f32(yf, recip); 6667 N2 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32, 6668 DAG.getConstant(Intrinsic::arm_neon_vrecpe, dl, MVT::i32), 6669 BN1); 6670 N1 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32, 6671 DAG.getConstant(Intrinsic::arm_neon_vrecps, dl, MVT::i32), 6672 BN1, N2); 6673 N2 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N1, N2); 6674 N1 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32, 6675 DAG.getConstant(Intrinsic::arm_neon_vrecps, dl, MVT::i32), 6676 BN1, N2); 6677 N2 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N1, N2); 6678 // Simply multiplying by the reciprocal estimate can leave us a few ulps 6679 // too low, so we add 2 ulps (exhaustive testing shows that this is enough, 6680 // and that it will never cause us to return an answer too large). 6681 // float4 result = as_float4(as_int4(xf*recip) + 2); 6682 N0 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N0, N2); 6683 N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, N0); 6684 N1 = DAG.getConstant(2, dl, MVT::i32); 6685 N1 = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, N1, N1, N1, N1); 6686 N0 = DAG.getNode(ISD::ADD, dl, MVT::v4i32, N0, N1); 6687 N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, N0); 6688 // Convert back to integer and return. 6689 // return vmovn_u32(vcvt_s32_f32(result)); 6690 N0 = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::v4i32, N0); 6691 N0 = DAG.getNode(ISD::TRUNCATE, dl, MVT::v4i16, N0); 6692 return N0; 6693 } 6694 6695 static SDValue LowerADDC_ADDE_SUBC_SUBE(SDValue Op, SelectionDAG &DAG) { 6696 EVT VT = Op.getNode()->getValueType(0); 6697 SDVTList VTs = DAG.getVTList(VT, MVT::i32); 6698 6699 unsigned Opc; 6700 bool ExtraOp = false; 6701 switch (Op.getOpcode()) { 6702 default: llvm_unreachable("Invalid code"); 6703 case ISD::ADDC: Opc = ARMISD::ADDC; break; 6704 case ISD::ADDE: Opc = ARMISD::ADDE; ExtraOp = true; break; 6705 case ISD::SUBC: Opc = ARMISD::SUBC; break; 6706 case ISD::SUBE: Opc = ARMISD::SUBE; ExtraOp = true; break; 6707 } 6708 6709 if (!ExtraOp) 6710 return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0), 6711 Op.getOperand(1)); 6712 return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0), 6713 Op.getOperand(1), Op.getOperand(2)); 6714 } 6715 6716 SDValue ARMTargetLowering::LowerFSINCOS(SDValue Op, SelectionDAG &DAG) const { 6717 assert(Subtarget->isTargetDarwin()); 6718 6719 // For iOS, we want to call an alternative entry point: __sincos_stret, 6720 // return values are passed via sret. 6721 SDLoc dl(Op); 6722 SDValue Arg = Op.getOperand(0); 6723 EVT ArgVT = Arg.getValueType(); 6724 Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext()); 6725 auto PtrVT = getPointerTy(DAG.getDataLayout()); 6726 6727 MachineFrameInfo *FrameInfo = DAG.getMachineFunction().getFrameInfo(); 6728 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 6729 6730 // Pair of floats / doubles used to pass the result. 6731 Type *RetTy = StructType::get(ArgTy, ArgTy, nullptr); 6732 auto &DL = DAG.getDataLayout(); 6733 6734 ArgListTy Args; 6735 bool ShouldUseSRet = Subtarget->isAPCS_ABI(); 6736 SDValue SRet; 6737 if (ShouldUseSRet) { 6738 // Create stack object for sret. 6739 const uint64_t ByteSize = DL.getTypeAllocSize(RetTy); 6740 const unsigned StackAlign = DL.getPrefTypeAlignment(RetTy); 6741 int FrameIdx = FrameInfo->CreateStackObject(ByteSize, StackAlign, false); 6742 SRet = DAG.getFrameIndex(FrameIdx, TLI.getPointerTy(DL)); 6743 6744 ArgListEntry Entry; 6745 Entry.Node = SRet; 6746 Entry.Ty = RetTy->getPointerTo(); 6747 Entry.isSExt = false; 6748 Entry.isZExt = false; 6749 Entry.isSRet = true; 6750 Args.push_back(Entry); 6751 RetTy = Type::getVoidTy(*DAG.getContext()); 6752 } 6753 6754 ArgListEntry Entry; 6755 Entry.Node = Arg; 6756 Entry.Ty = ArgTy; 6757 Entry.isSExt = false; 6758 Entry.isZExt = false; 6759 Args.push_back(Entry); 6760 6761 const char *LibcallName = 6762 (ArgVT == MVT::f64) ? "__sincos_stret" : "__sincosf_stret"; 6763 RTLIB::Libcall LC = 6764 (ArgVT == MVT::f64) ? RTLIB::SINCOS_F64 : RTLIB::SINCOS_F32; 6765 CallingConv::ID CC = getLibcallCallingConv(LC); 6766 SDValue Callee = DAG.getExternalSymbol(LibcallName, getPointerTy(DL)); 6767 6768 TargetLowering::CallLoweringInfo CLI(DAG); 6769 CLI.setDebugLoc(dl) 6770 .setChain(DAG.getEntryNode()) 6771 .setCallee(CC, RetTy, Callee, std::move(Args), 0) 6772 .setDiscardResult(ShouldUseSRet); 6773 std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI); 6774 6775 if (!ShouldUseSRet) 6776 return CallResult.first; 6777 6778 SDValue LoadSin = DAG.getLoad(ArgVT, dl, CallResult.second, SRet, 6779 MachinePointerInfo(), false, false, false, 0); 6780 6781 // Address of cos field. 6782 SDValue Add = DAG.getNode(ISD::ADD, dl, PtrVT, SRet, 6783 DAG.getIntPtrConstant(ArgVT.getStoreSize(), dl)); 6784 SDValue LoadCos = DAG.getLoad(ArgVT, dl, LoadSin.getValue(1), Add, 6785 MachinePointerInfo(), false, false, false, 0); 6786 6787 SDVTList Tys = DAG.getVTList(ArgVT, ArgVT); 6788 return DAG.getNode(ISD::MERGE_VALUES, dl, Tys, 6789 LoadSin.getValue(0), LoadCos.getValue(0)); 6790 } 6791 6792 SDValue ARMTargetLowering::LowerWindowsDIVLibCall(SDValue Op, SelectionDAG &DAG, 6793 bool Signed, 6794 SDValue &Chain) const { 6795 EVT VT = Op.getValueType(); 6796 assert((VT == MVT::i32 || VT == MVT::i64) && 6797 "unexpected type for custom lowering DIV"); 6798 SDLoc dl(Op); 6799 6800 const auto &DL = DAG.getDataLayout(); 6801 const auto &TLI = DAG.getTargetLoweringInfo(); 6802 6803 const char *Name = nullptr; 6804 if (Signed) 6805 Name = (VT == MVT::i32) ? "__rt_sdiv" : "__rt_sdiv64"; 6806 else 6807 Name = (VT == MVT::i32) ? "__rt_udiv" : "__rt_udiv64"; 6808 6809 SDValue ES = DAG.getExternalSymbol(Name, TLI.getPointerTy(DL)); 6810 6811 ARMTargetLowering::ArgListTy Args; 6812 6813 for (auto AI : {1, 0}) { 6814 ArgListEntry Arg; 6815 Arg.Node = Op.getOperand(AI); 6816 Arg.Ty = Arg.Node.getValueType().getTypeForEVT(*DAG.getContext()); 6817 Args.push_back(Arg); 6818 } 6819 6820 CallLoweringInfo CLI(DAG); 6821 CLI.setDebugLoc(dl) 6822 .setChain(Chain) 6823 .setCallee(CallingConv::ARM_AAPCS_VFP, VT.getTypeForEVT(*DAG.getContext()), 6824 ES, std::move(Args), 0); 6825 6826 return LowerCallTo(CLI).first; 6827 } 6828 6829 SDValue ARMTargetLowering::LowerDIV_Windows(SDValue Op, SelectionDAG &DAG, 6830 bool Signed) const { 6831 assert(Op.getValueType() == MVT::i32 && 6832 "unexpected type for custom lowering DIV"); 6833 SDLoc dl(Op); 6834 6835 SDValue DBZCHK = DAG.getNode(ARMISD::WIN__DBZCHK, dl, MVT::Other, 6836 DAG.getEntryNode(), Op.getOperand(1)); 6837 6838 return LowerWindowsDIVLibCall(Op, DAG, Signed, DBZCHK); 6839 } 6840 6841 void ARMTargetLowering::ExpandDIV_Windows( 6842 SDValue Op, SelectionDAG &DAG, bool Signed, 6843 SmallVectorImpl<SDValue> &Results) const { 6844 const auto &DL = DAG.getDataLayout(); 6845 const auto &TLI = DAG.getTargetLoweringInfo(); 6846 6847 assert(Op.getValueType() == MVT::i64 && 6848 "unexpected type for custom lowering DIV"); 6849 SDLoc dl(Op); 6850 6851 SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, Op.getOperand(1), 6852 DAG.getConstant(0, dl, MVT::i32)); 6853 SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, Op.getOperand(1), 6854 DAG.getConstant(1, dl, MVT::i32)); 6855 SDValue Or = DAG.getNode(ISD::OR, dl, MVT::i32, Lo, Hi); 6856 6857 SDValue DBZCHK = 6858 DAG.getNode(ARMISD::WIN__DBZCHK, dl, MVT::Other, DAG.getEntryNode(), Or); 6859 6860 SDValue Result = LowerWindowsDIVLibCall(Op, DAG, Signed, DBZCHK); 6861 6862 SDValue Lower = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, Result); 6863 SDValue Upper = DAG.getNode(ISD::SRL, dl, MVT::i64, Result, 6864 DAG.getConstant(32, dl, TLI.getPointerTy(DL))); 6865 Upper = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, Upper); 6866 6867 Results.push_back(Lower); 6868 Results.push_back(Upper); 6869 } 6870 6871 static SDValue LowerAtomicLoadStore(SDValue Op, SelectionDAG &DAG) { 6872 // Monotonic load/store is legal for all targets 6873 if (cast<AtomicSDNode>(Op)->getOrdering() <= Monotonic) 6874 return Op; 6875 6876 // Acquire/Release load/store is not legal for targets without a 6877 // dmb or equivalent available. 6878 return SDValue(); 6879 } 6880 6881 static void ReplaceREADCYCLECOUNTER(SDNode *N, 6882 SmallVectorImpl<SDValue> &Results, 6883 SelectionDAG &DAG, 6884 const ARMSubtarget *Subtarget) { 6885 SDLoc DL(N); 6886 // Under Power Management extensions, the cycle-count is: 6887 // mrc p15, #0, <Rt>, c9, c13, #0 6888 SDValue Ops[] = { N->getOperand(0), // Chain 6889 DAG.getConstant(Intrinsic::arm_mrc, DL, MVT::i32), 6890 DAG.getConstant(15, DL, MVT::i32), 6891 DAG.getConstant(0, DL, MVT::i32), 6892 DAG.getConstant(9, DL, MVT::i32), 6893 DAG.getConstant(13, DL, MVT::i32), 6894 DAG.getConstant(0, DL, MVT::i32) 6895 }; 6896 6897 SDValue Cycles32 = DAG.getNode(ISD::INTRINSIC_W_CHAIN, DL, 6898 DAG.getVTList(MVT::i32, MVT::Other), Ops); 6899 Results.push_back(DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, Cycles32, 6900 DAG.getConstant(0, DL, MVT::i32))); 6901 Results.push_back(Cycles32.getValue(1)); 6902 } 6903 6904 SDValue ARMTargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const { 6905 switch (Op.getOpcode()) { 6906 default: llvm_unreachable("Don't know how to custom lower this!"); 6907 case ISD::WRITE_REGISTER: return LowerWRITE_REGISTER(Op, DAG); 6908 case ISD::ConstantPool: return LowerConstantPool(Op, DAG); 6909 case ISD::BlockAddress: return LowerBlockAddress(Op, DAG); 6910 case ISD::GlobalAddress: 6911 switch (Subtarget->getTargetTriple().getObjectFormat()) { 6912 default: llvm_unreachable("unknown object format"); 6913 case Triple::COFF: 6914 return LowerGlobalAddressWindows(Op, DAG); 6915 case Triple::ELF: 6916 return LowerGlobalAddressELF(Op, DAG); 6917 case Triple::MachO: 6918 return LowerGlobalAddressDarwin(Op, DAG); 6919 } 6920 case ISD::GlobalTLSAddress: return LowerGlobalTLSAddress(Op, DAG); 6921 case ISD::SELECT: return LowerSELECT(Op, DAG); 6922 case ISD::SELECT_CC: return LowerSELECT_CC(Op, DAG); 6923 case ISD::BR_CC: return LowerBR_CC(Op, DAG); 6924 case ISD::BR_JT: return LowerBR_JT(Op, DAG); 6925 case ISD::VASTART: return LowerVASTART(Op, DAG); 6926 case ISD::ATOMIC_FENCE: return LowerATOMIC_FENCE(Op, DAG, Subtarget); 6927 case ISD::PREFETCH: return LowerPREFETCH(Op, DAG, Subtarget); 6928 case ISD::SINT_TO_FP: 6929 case ISD::UINT_TO_FP: return LowerINT_TO_FP(Op, DAG); 6930 case ISD::FP_TO_SINT: 6931 case ISD::FP_TO_UINT: return LowerFP_TO_INT(Op, DAG); 6932 case ISD::FCOPYSIGN: return LowerFCOPYSIGN(Op, DAG); 6933 case ISD::RETURNADDR: return LowerRETURNADDR(Op, DAG); 6934 case ISD::FRAMEADDR: return LowerFRAMEADDR(Op, DAG); 6935 case ISD::EH_SJLJ_SETJMP: return LowerEH_SJLJ_SETJMP(Op, DAG); 6936 case ISD::EH_SJLJ_LONGJMP: return LowerEH_SJLJ_LONGJMP(Op, DAG); 6937 case ISD::EH_SJLJ_SETUP_DISPATCH: return LowerEH_SJLJ_SETUP_DISPATCH(Op, DAG); 6938 case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG, 6939 Subtarget); 6940 case ISD::BITCAST: return ExpandBITCAST(Op.getNode(), DAG); 6941 case ISD::SHL: 6942 case ISD::SRL: 6943 case ISD::SRA: return LowerShift(Op.getNode(), DAG, Subtarget); 6944 case ISD::SREM: return LowerREM(Op.getNode(), DAG); 6945 case ISD::UREM: return LowerREM(Op.getNode(), DAG); 6946 case ISD::SHL_PARTS: return LowerShiftLeftParts(Op, DAG); 6947 case ISD::SRL_PARTS: 6948 case ISD::SRA_PARTS: return LowerShiftRightParts(Op, DAG); 6949 case ISD::CTTZ: 6950 case ISD::CTTZ_ZERO_UNDEF: return LowerCTTZ(Op.getNode(), DAG, Subtarget); 6951 case ISD::CTPOP: return LowerCTPOP(Op.getNode(), DAG, Subtarget); 6952 case ISD::SETCC: return LowerVSETCC(Op, DAG); 6953 case ISD::ConstantFP: return LowerConstantFP(Op, DAG, Subtarget); 6954 case ISD::BUILD_VECTOR: return LowerBUILD_VECTOR(Op, DAG, Subtarget); 6955 case ISD::VECTOR_SHUFFLE: return LowerVECTOR_SHUFFLE(Op, DAG); 6956 case ISD::INSERT_VECTOR_ELT: return LowerINSERT_VECTOR_ELT(Op, DAG); 6957 case ISD::EXTRACT_VECTOR_ELT: return LowerEXTRACT_VECTOR_ELT(Op, DAG); 6958 case ISD::CONCAT_VECTORS: return LowerCONCAT_VECTORS(Op, DAG); 6959 case ISD::FLT_ROUNDS_: return LowerFLT_ROUNDS_(Op, DAG); 6960 case ISD::MUL: return LowerMUL(Op, DAG); 6961 case ISD::SDIV: return LowerSDIV(Op, DAG); 6962 case ISD::UDIV: return LowerUDIV(Op, DAG); 6963 case ISD::ADDC: 6964 case ISD::ADDE: 6965 case ISD::SUBC: 6966 case ISD::SUBE: return LowerADDC_ADDE_SUBC_SUBE(Op, DAG); 6967 case ISD::SADDO: 6968 case ISD::UADDO: 6969 case ISD::SSUBO: 6970 case ISD::USUBO: 6971 return LowerXALUO(Op, DAG); 6972 case ISD::ATOMIC_LOAD: 6973 case ISD::ATOMIC_STORE: return LowerAtomicLoadStore(Op, DAG); 6974 case ISD::FSINCOS: return LowerFSINCOS(Op, DAG); 6975 case ISD::SDIVREM: 6976 case ISD::UDIVREM: return LowerDivRem(Op, DAG); 6977 case ISD::DYNAMIC_STACKALLOC: 6978 if (Subtarget->getTargetTriple().isWindowsItaniumEnvironment()) 6979 return LowerDYNAMIC_STACKALLOC(Op, DAG); 6980 llvm_unreachable("Don't know how to custom lower this!"); 6981 case ISD::FP_ROUND: return LowerFP_ROUND(Op, DAG); 6982 case ISD::FP_EXTEND: return LowerFP_EXTEND(Op, DAG); 6983 case ARMISD::WIN__DBZCHK: return SDValue(); 6984 } 6985 } 6986 6987 /// ReplaceNodeResults - Replace the results of node with an illegal result 6988 /// type with new values built out of custom code. 6989 void ARMTargetLowering::ReplaceNodeResults(SDNode *N, 6990 SmallVectorImpl<SDValue> &Results, 6991 SelectionDAG &DAG) const { 6992 SDValue Res; 6993 switch (N->getOpcode()) { 6994 default: 6995 llvm_unreachable("Don't know how to custom expand this!"); 6996 case ISD::READ_REGISTER: 6997 ExpandREAD_REGISTER(N, Results, DAG); 6998 break; 6999 case ISD::BITCAST: 7000 Res = ExpandBITCAST(N, DAG); 7001 break; 7002 case ISD::SRL: 7003 case ISD::SRA: 7004 Res = Expand64BitShift(N, DAG, Subtarget); 7005 break; 7006 case ISD::SREM: 7007 case ISD::UREM: 7008 Res = LowerREM(N, DAG); 7009 break; 7010 case ISD::READCYCLECOUNTER: 7011 ReplaceREADCYCLECOUNTER(N, Results, DAG, Subtarget); 7012 return; 7013 case ISD::UDIV: 7014 case ISD::SDIV: 7015 assert(Subtarget->isTargetWindows() && "can only expand DIV on Windows"); 7016 return ExpandDIV_Windows(SDValue(N, 0), DAG, N->getOpcode() == ISD::SDIV, 7017 Results); 7018 } 7019 if (Res.getNode()) 7020 Results.push_back(Res); 7021 } 7022 7023 //===----------------------------------------------------------------------===// 7024 // ARM Scheduler Hooks 7025 //===----------------------------------------------------------------------===// 7026 7027 /// SetupEntryBlockForSjLj - Insert code into the entry block that creates and 7028 /// registers the function context. 7029 void ARMTargetLowering:: 7030 SetupEntryBlockForSjLj(MachineInstr *MI, MachineBasicBlock *MBB, 7031 MachineBasicBlock *DispatchBB, int FI) const { 7032 const TargetInstrInfo *TII = Subtarget->getInstrInfo(); 7033 DebugLoc dl = MI->getDebugLoc(); 7034 MachineFunction *MF = MBB->getParent(); 7035 MachineRegisterInfo *MRI = &MF->getRegInfo(); 7036 MachineConstantPool *MCP = MF->getConstantPool(); 7037 ARMFunctionInfo *AFI = MF->getInfo<ARMFunctionInfo>(); 7038 const Function *F = MF->getFunction(); 7039 7040 bool isThumb = Subtarget->isThumb(); 7041 bool isThumb2 = Subtarget->isThumb2(); 7042 7043 unsigned PCLabelId = AFI->createPICLabelUId(); 7044 unsigned PCAdj = (isThumb || isThumb2) ? 4 : 8; 7045 ARMConstantPoolValue *CPV = 7046 ARMConstantPoolMBB::Create(F->getContext(), DispatchBB, PCLabelId, PCAdj); 7047 unsigned CPI = MCP->getConstantPoolIndex(CPV, 4); 7048 7049 const TargetRegisterClass *TRC = isThumb ? &ARM::tGPRRegClass 7050 : &ARM::GPRRegClass; 7051 7052 // Grab constant pool and fixed stack memory operands. 7053 MachineMemOperand *CPMMO = 7054 MF->getMachineMemOperand(MachinePointerInfo::getConstantPool(*MF), 7055 MachineMemOperand::MOLoad, 4, 4); 7056 7057 MachineMemOperand *FIMMOSt = 7058 MF->getMachineMemOperand(MachinePointerInfo::getFixedStack(*MF, FI), 7059 MachineMemOperand::MOStore, 4, 4); 7060 7061 // Load the address of the dispatch MBB into the jump buffer. 7062 if (isThumb2) { 7063 // Incoming value: jbuf 7064 // ldr.n r5, LCPI1_1 7065 // orr r5, r5, #1 7066 // add r5, pc 7067 // str r5, [$jbuf, #+4] ; &jbuf[1] 7068 unsigned NewVReg1 = MRI->createVirtualRegister(TRC); 7069 AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::t2LDRpci), NewVReg1) 7070 .addConstantPoolIndex(CPI) 7071 .addMemOperand(CPMMO)); 7072 // Set the low bit because of thumb mode. 7073 unsigned NewVReg2 = MRI->createVirtualRegister(TRC); 7074 AddDefaultCC( 7075 AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::t2ORRri), NewVReg2) 7076 .addReg(NewVReg1, RegState::Kill) 7077 .addImm(0x01))); 7078 unsigned NewVReg3 = MRI->createVirtualRegister(TRC); 7079 BuildMI(*MBB, MI, dl, TII->get(ARM::tPICADD), NewVReg3) 7080 .addReg(NewVReg2, RegState::Kill) 7081 .addImm(PCLabelId); 7082 AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::t2STRi12)) 7083 .addReg(NewVReg3, RegState::Kill) 7084 .addFrameIndex(FI) 7085 .addImm(36) // &jbuf[1] :: pc 7086 .addMemOperand(FIMMOSt)); 7087 } else if (isThumb) { 7088 // Incoming value: jbuf 7089 // ldr.n r1, LCPI1_4 7090 // add r1, pc 7091 // mov r2, #1 7092 // orrs r1, r2 7093 // add r2, $jbuf, #+4 ; &jbuf[1] 7094 // str r1, [r2] 7095 unsigned NewVReg1 = MRI->createVirtualRegister(TRC); 7096 AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::tLDRpci), NewVReg1) 7097 .addConstantPoolIndex(CPI) 7098 .addMemOperand(CPMMO)); 7099 unsigned NewVReg2 = MRI->createVirtualRegister(TRC); 7100 BuildMI(*MBB, MI, dl, TII->get(ARM::tPICADD), NewVReg2) 7101 .addReg(NewVReg1, RegState::Kill) 7102 .addImm(PCLabelId); 7103 // Set the low bit because of thumb mode. 7104 unsigned NewVReg3 = MRI->createVirtualRegister(TRC); 7105 AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::tMOVi8), NewVReg3) 7106 .addReg(ARM::CPSR, RegState::Define) 7107 .addImm(1)); 7108 unsigned NewVReg4 = MRI->createVirtualRegister(TRC); 7109 AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::tORR), NewVReg4) 7110 .addReg(ARM::CPSR, RegState::Define) 7111 .addReg(NewVReg2, RegState::Kill) 7112 .addReg(NewVReg3, RegState::Kill)); 7113 unsigned NewVReg5 = MRI->createVirtualRegister(TRC); 7114 BuildMI(*MBB, MI, dl, TII->get(ARM::tADDframe), NewVReg5) 7115 .addFrameIndex(FI) 7116 .addImm(36); // &jbuf[1] :: pc 7117 AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::tSTRi)) 7118 .addReg(NewVReg4, RegState::Kill) 7119 .addReg(NewVReg5, RegState::Kill) 7120 .addImm(0) 7121 .addMemOperand(FIMMOSt)); 7122 } else { 7123 // Incoming value: jbuf 7124 // ldr r1, LCPI1_1 7125 // add r1, pc, r1 7126 // str r1, [$jbuf, #+4] ; &jbuf[1] 7127 unsigned NewVReg1 = MRI->createVirtualRegister(TRC); 7128 AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::LDRi12), NewVReg1) 7129 .addConstantPoolIndex(CPI) 7130 .addImm(0) 7131 .addMemOperand(CPMMO)); 7132 unsigned NewVReg2 = MRI->createVirtualRegister(TRC); 7133 AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::PICADD), NewVReg2) 7134 .addReg(NewVReg1, RegState::Kill) 7135 .addImm(PCLabelId)); 7136 AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::STRi12)) 7137 .addReg(NewVReg2, RegState::Kill) 7138 .addFrameIndex(FI) 7139 .addImm(36) // &jbuf[1] :: pc 7140 .addMemOperand(FIMMOSt)); 7141 } 7142 } 7143 7144 void ARMTargetLowering::EmitSjLjDispatchBlock(MachineInstr *MI, 7145 MachineBasicBlock *MBB) const { 7146 const TargetInstrInfo *TII = Subtarget->getInstrInfo(); 7147 DebugLoc dl = MI->getDebugLoc(); 7148 MachineFunction *MF = MBB->getParent(); 7149 MachineRegisterInfo *MRI = &MF->getRegInfo(); 7150 MachineFrameInfo *MFI = MF->getFrameInfo(); 7151 int FI = MFI->getFunctionContextIndex(); 7152 7153 const TargetRegisterClass *TRC = Subtarget->isThumb() ? &ARM::tGPRRegClass 7154 : &ARM::GPRnopcRegClass; 7155 7156 // Get a mapping of the call site numbers to all of the landing pads they're 7157 // associated with. 7158 DenseMap<unsigned, SmallVector<MachineBasicBlock*, 2> > CallSiteNumToLPad; 7159 unsigned MaxCSNum = 0; 7160 MachineModuleInfo &MMI = MF->getMMI(); 7161 for (MachineFunction::iterator BB = MF->begin(), E = MF->end(); BB != E; 7162 ++BB) { 7163 if (!BB->isEHPad()) continue; 7164 7165 // FIXME: We should assert that the EH_LABEL is the first MI in the landing 7166 // pad. 7167 for (MachineBasicBlock::iterator 7168 II = BB->begin(), IE = BB->end(); II != IE; ++II) { 7169 if (!II->isEHLabel()) continue; 7170 7171 MCSymbol *Sym = II->getOperand(0).getMCSymbol(); 7172 if (!MMI.hasCallSiteLandingPad(Sym)) continue; 7173 7174 SmallVectorImpl<unsigned> &CallSiteIdxs = MMI.getCallSiteLandingPad(Sym); 7175 for (SmallVectorImpl<unsigned>::iterator 7176 CSI = CallSiteIdxs.begin(), CSE = CallSiteIdxs.end(); 7177 CSI != CSE; ++CSI) { 7178 CallSiteNumToLPad[*CSI].push_back(&*BB); 7179 MaxCSNum = std::max(MaxCSNum, *CSI); 7180 } 7181 break; 7182 } 7183 } 7184 7185 // Get an ordered list of the machine basic blocks for the jump table. 7186 std::vector<MachineBasicBlock*> LPadList; 7187 SmallPtrSet<MachineBasicBlock*, 64> InvokeBBs; 7188 LPadList.reserve(CallSiteNumToLPad.size()); 7189 for (unsigned I = 1; I <= MaxCSNum; ++I) { 7190 SmallVectorImpl<MachineBasicBlock*> &MBBList = CallSiteNumToLPad[I]; 7191 for (SmallVectorImpl<MachineBasicBlock*>::iterator 7192 II = MBBList.begin(), IE = MBBList.end(); II != IE; ++II) { 7193 LPadList.push_back(*II); 7194 InvokeBBs.insert((*II)->pred_begin(), (*II)->pred_end()); 7195 } 7196 } 7197 7198 assert(!LPadList.empty() && 7199 "No landing pad destinations for the dispatch jump table!"); 7200 7201 // Create the jump table and associated information. 7202 MachineJumpTableInfo *JTI = 7203 MF->getOrCreateJumpTableInfo(MachineJumpTableInfo::EK_Inline); 7204 unsigned MJTI = JTI->createJumpTableIndex(LPadList); 7205 Reloc::Model RelocM = getTargetMachine().getRelocationModel(); 7206 7207 // Create the MBBs for the dispatch code. 7208 7209 // Shove the dispatch's address into the return slot in the function context. 7210 MachineBasicBlock *DispatchBB = MF->CreateMachineBasicBlock(); 7211 DispatchBB->setIsEHPad(); 7212 7213 MachineBasicBlock *TrapBB = MF->CreateMachineBasicBlock(); 7214 unsigned trap_opcode; 7215 if (Subtarget->isThumb()) 7216 trap_opcode = ARM::tTRAP; 7217 else 7218 trap_opcode = Subtarget->useNaClTrap() ? ARM::TRAPNaCl : ARM::TRAP; 7219 7220 BuildMI(TrapBB, dl, TII->get(trap_opcode)); 7221 DispatchBB->addSuccessor(TrapBB); 7222 7223 MachineBasicBlock *DispContBB = MF->CreateMachineBasicBlock(); 7224 DispatchBB->addSuccessor(DispContBB); 7225 7226 // Insert and MBBs. 7227 MF->insert(MF->end(), DispatchBB); 7228 MF->insert(MF->end(), DispContBB); 7229 MF->insert(MF->end(), TrapBB); 7230 7231 // Insert code into the entry block that creates and registers the function 7232 // context. 7233 SetupEntryBlockForSjLj(MI, MBB, DispatchBB, FI); 7234 7235 MachineMemOperand *FIMMOLd = MF->getMachineMemOperand( 7236 MachinePointerInfo::getFixedStack(*MF, FI), 7237 MachineMemOperand::MOLoad | MachineMemOperand::MOVolatile, 4, 4); 7238 7239 MachineInstrBuilder MIB; 7240 MIB = BuildMI(DispatchBB, dl, TII->get(ARM::Int_eh_sjlj_dispatchsetup)); 7241 7242 const ARMBaseInstrInfo *AII = static_cast<const ARMBaseInstrInfo*>(TII); 7243 const ARMBaseRegisterInfo &RI = AII->getRegisterInfo(); 7244 7245 // Add a register mask with no preserved registers. This results in all 7246 // registers being marked as clobbered. 7247 MIB.addRegMask(RI.getNoPreservedMask()); 7248 7249 unsigned NumLPads = LPadList.size(); 7250 if (Subtarget->isThumb2()) { 7251 unsigned NewVReg1 = MRI->createVirtualRegister(TRC); 7252 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::t2LDRi12), NewVReg1) 7253 .addFrameIndex(FI) 7254 .addImm(4) 7255 .addMemOperand(FIMMOLd)); 7256 7257 if (NumLPads < 256) { 7258 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::t2CMPri)) 7259 .addReg(NewVReg1) 7260 .addImm(LPadList.size())); 7261 } else { 7262 unsigned VReg1 = MRI->createVirtualRegister(TRC); 7263 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::t2MOVi16), VReg1) 7264 .addImm(NumLPads & 0xFFFF)); 7265 7266 unsigned VReg2 = VReg1; 7267 if ((NumLPads & 0xFFFF0000) != 0) { 7268 VReg2 = MRI->createVirtualRegister(TRC); 7269 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::t2MOVTi16), VReg2) 7270 .addReg(VReg1) 7271 .addImm(NumLPads >> 16)); 7272 } 7273 7274 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::t2CMPrr)) 7275 .addReg(NewVReg1) 7276 .addReg(VReg2)); 7277 } 7278 7279 BuildMI(DispatchBB, dl, TII->get(ARM::t2Bcc)) 7280 .addMBB(TrapBB) 7281 .addImm(ARMCC::HI) 7282 .addReg(ARM::CPSR); 7283 7284 unsigned NewVReg3 = MRI->createVirtualRegister(TRC); 7285 AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::t2LEApcrelJT),NewVReg3) 7286 .addJumpTableIndex(MJTI)); 7287 7288 unsigned NewVReg4 = MRI->createVirtualRegister(TRC); 7289 AddDefaultCC( 7290 AddDefaultPred( 7291 BuildMI(DispContBB, dl, TII->get(ARM::t2ADDrs), NewVReg4) 7292 .addReg(NewVReg3, RegState::Kill) 7293 .addReg(NewVReg1) 7294 .addImm(ARM_AM::getSORegOpc(ARM_AM::lsl, 2)))); 7295 7296 BuildMI(DispContBB, dl, TII->get(ARM::t2BR_JT)) 7297 .addReg(NewVReg4, RegState::Kill) 7298 .addReg(NewVReg1) 7299 .addJumpTableIndex(MJTI); 7300 } else if (Subtarget->isThumb()) { 7301 unsigned NewVReg1 = MRI->createVirtualRegister(TRC); 7302 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::tLDRspi), NewVReg1) 7303 .addFrameIndex(FI) 7304 .addImm(1) 7305 .addMemOperand(FIMMOLd)); 7306 7307 if (NumLPads < 256) { 7308 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::tCMPi8)) 7309 .addReg(NewVReg1) 7310 .addImm(NumLPads)); 7311 } else { 7312 MachineConstantPool *ConstantPool = MF->getConstantPool(); 7313 Type *Int32Ty = Type::getInt32Ty(MF->getFunction()->getContext()); 7314 const Constant *C = ConstantInt::get(Int32Ty, NumLPads); 7315 7316 // MachineConstantPool wants an explicit alignment. 7317 unsigned Align = MF->getDataLayout().getPrefTypeAlignment(Int32Ty); 7318 if (Align == 0) 7319 Align = MF->getDataLayout().getTypeAllocSize(C->getType()); 7320 unsigned Idx = ConstantPool->getConstantPoolIndex(C, Align); 7321 7322 unsigned VReg1 = MRI->createVirtualRegister(TRC); 7323 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::tLDRpci)) 7324 .addReg(VReg1, RegState::Define) 7325 .addConstantPoolIndex(Idx)); 7326 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::tCMPr)) 7327 .addReg(NewVReg1) 7328 .addReg(VReg1)); 7329 } 7330 7331 BuildMI(DispatchBB, dl, TII->get(ARM::tBcc)) 7332 .addMBB(TrapBB) 7333 .addImm(ARMCC::HI) 7334 .addReg(ARM::CPSR); 7335 7336 unsigned NewVReg2 = MRI->createVirtualRegister(TRC); 7337 AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::tLSLri), NewVReg2) 7338 .addReg(ARM::CPSR, RegState::Define) 7339 .addReg(NewVReg1) 7340 .addImm(2)); 7341 7342 unsigned NewVReg3 = MRI->createVirtualRegister(TRC); 7343 AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::tLEApcrelJT), NewVReg3) 7344 .addJumpTableIndex(MJTI)); 7345 7346 unsigned NewVReg4 = MRI->createVirtualRegister(TRC); 7347 AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::tADDrr), NewVReg4) 7348 .addReg(ARM::CPSR, RegState::Define) 7349 .addReg(NewVReg2, RegState::Kill) 7350 .addReg(NewVReg3)); 7351 7352 MachineMemOperand *JTMMOLd = MF->getMachineMemOperand( 7353 MachinePointerInfo::getJumpTable(*MF), MachineMemOperand::MOLoad, 4, 4); 7354 7355 unsigned NewVReg5 = MRI->createVirtualRegister(TRC); 7356 AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::tLDRi), NewVReg5) 7357 .addReg(NewVReg4, RegState::Kill) 7358 .addImm(0) 7359 .addMemOperand(JTMMOLd)); 7360 7361 unsigned NewVReg6 = NewVReg5; 7362 if (RelocM == Reloc::PIC_) { 7363 NewVReg6 = MRI->createVirtualRegister(TRC); 7364 AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::tADDrr), NewVReg6) 7365 .addReg(ARM::CPSR, RegState::Define) 7366 .addReg(NewVReg5, RegState::Kill) 7367 .addReg(NewVReg3)); 7368 } 7369 7370 BuildMI(DispContBB, dl, TII->get(ARM::tBR_JTr)) 7371 .addReg(NewVReg6, RegState::Kill) 7372 .addJumpTableIndex(MJTI); 7373 } else { 7374 unsigned NewVReg1 = MRI->createVirtualRegister(TRC); 7375 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::LDRi12), NewVReg1) 7376 .addFrameIndex(FI) 7377 .addImm(4) 7378 .addMemOperand(FIMMOLd)); 7379 7380 if (NumLPads < 256) { 7381 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::CMPri)) 7382 .addReg(NewVReg1) 7383 .addImm(NumLPads)); 7384 } else if (Subtarget->hasV6T2Ops() && isUInt<16>(NumLPads)) { 7385 unsigned VReg1 = MRI->createVirtualRegister(TRC); 7386 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::MOVi16), VReg1) 7387 .addImm(NumLPads & 0xFFFF)); 7388 7389 unsigned VReg2 = VReg1; 7390 if ((NumLPads & 0xFFFF0000) != 0) { 7391 VReg2 = MRI->createVirtualRegister(TRC); 7392 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::MOVTi16), VReg2) 7393 .addReg(VReg1) 7394 .addImm(NumLPads >> 16)); 7395 } 7396 7397 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::CMPrr)) 7398 .addReg(NewVReg1) 7399 .addReg(VReg2)); 7400 } else { 7401 MachineConstantPool *ConstantPool = MF->getConstantPool(); 7402 Type *Int32Ty = Type::getInt32Ty(MF->getFunction()->getContext()); 7403 const Constant *C = ConstantInt::get(Int32Ty, NumLPads); 7404 7405 // MachineConstantPool wants an explicit alignment. 7406 unsigned Align = MF->getDataLayout().getPrefTypeAlignment(Int32Ty); 7407 if (Align == 0) 7408 Align = MF->getDataLayout().getTypeAllocSize(C->getType()); 7409 unsigned Idx = ConstantPool->getConstantPoolIndex(C, Align); 7410 7411 unsigned VReg1 = MRI->createVirtualRegister(TRC); 7412 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::LDRcp)) 7413 .addReg(VReg1, RegState::Define) 7414 .addConstantPoolIndex(Idx) 7415 .addImm(0)); 7416 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::CMPrr)) 7417 .addReg(NewVReg1) 7418 .addReg(VReg1, RegState::Kill)); 7419 } 7420 7421 BuildMI(DispatchBB, dl, TII->get(ARM::Bcc)) 7422 .addMBB(TrapBB) 7423 .addImm(ARMCC::HI) 7424 .addReg(ARM::CPSR); 7425 7426 unsigned NewVReg3 = MRI->createVirtualRegister(TRC); 7427 AddDefaultCC( 7428 AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::MOVsi), NewVReg3) 7429 .addReg(NewVReg1) 7430 .addImm(ARM_AM::getSORegOpc(ARM_AM::lsl, 2)))); 7431 unsigned NewVReg4 = MRI->createVirtualRegister(TRC); 7432 AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::LEApcrelJT), NewVReg4) 7433 .addJumpTableIndex(MJTI)); 7434 7435 MachineMemOperand *JTMMOLd = MF->getMachineMemOperand( 7436 MachinePointerInfo::getJumpTable(*MF), MachineMemOperand::MOLoad, 4, 4); 7437 unsigned NewVReg5 = MRI->createVirtualRegister(TRC); 7438 AddDefaultPred( 7439 BuildMI(DispContBB, dl, TII->get(ARM::LDRrs), NewVReg5) 7440 .addReg(NewVReg3, RegState::Kill) 7441 .addReg(NewVReg4) 7442 .addImm(0) 7443 .addMemOperand(JTMMOLd)); 7444 7445 if (RelocM == Reloc::PIC_) { 7446 BuildMI(DispContBB, dl, TII->get(ARM::BR_JTadd)) 7447 .addReg(NewVReg5, RegState::Kill) 7448 .addReg(NewVReg4) 7449 .addJumpTableIndex(MJTI); 7450 } else { 7451 BuildMI(DispContBB, dl, TII->get(ARM::BR_JTr)) 7452 .addReg(NewVReg5, RegState::Kill) 7453 .addJumpTableIndex(MJTI); 7454 } 7455 } 7456 7457 // Add the jump table entries as successors to the MBB. 7458 SmallPtrSet<MachineBasicBlock*, 8> SeenMBBs; 7459 for (std::vector<MachineBasicBlock*>::iterator 7460 I = LPadList.begin(), E = LPadList.end(); I != E; ++I) { 7461 MachineBasicBlock *CurMBB = *I; 7462 if (SeenMBBs.insert(CurMBB).second) 7463 DispContBB->addSuccessor(CurMBB); 7464 } 7465 7466 // N.B. the order the invoke BBs are processed in doesn't matter here. 7467 const MCPhysReg *SavedRegs = RI.getCalleeSavedRegs(MF); 7468 SmallVector<MachineBasicBlock*, 64> MBBLPads; 7469 for (MachineBasicBlock *BB : InvokeBBs) { 7470 7471 // Remove the landing pad successor from the invoke block and replace it 7472 // with the new dispatch block. 7473 SmallVector<MachineBasicBlock*, 4> Successors(BB->succ_begin(), 7474 BB->succ_end()); 7475 while (!Successors.empty()) { 7476 MachineBasicBlock *SMBB = Successors.pop_back_val(); 7477 if (SMBB->isEHPad()) { 7478 BB->removeSuccessor(SMBB); 7479 MBBLPads.push_back(SMBB); 7480 } 7481 } 7482 7483 BB->addSuccessor(DispatchBB, BranchProbability::getZero()); 7484 BB->normalizeSuccProbs(); 7485 7486 // Find the invoke call and mark all of the callee-saved registers as 7487 // 'implicit defined' so that they're spilled. This prevents code from 7488 // moving instructions to before the EH block, where they will never be 7489 // executed. 7490 for (MachineBasicBlock::reverse_iterator 7491 II = BB->rbegin(), IE = BB->rend(); II != IE; ++II) { 7492 if (!II->isCall()) continue; 7493 7494 DenseMap<unsigned, bool> DefRegs; 7495 for (MachineInstr::mop_iterator 7496 OI = II->operands_begin(), OE = II->operands_end(); 7497 OI != OE; ++OI) { 7498 if (!OI->isReg()) continue; 7499 DefRegs[OI->getReg()] = true; 7500 } 7501 7502 MachineInstrBuilder MIB(*MF, &*II); 7503 7504 for (unsigned i = 0; SavedRegs[i] != 0; ++i) { 7505 unsigned Reg = SavedRegs[i]; 7506 if (Subtarget->isThumb2() && 7507 !ARM::tGPRRegClass.contains(Reg) && 7508 !ARM::hGPRRegClass.contains(Reg)) 7509 continue; 7510 if (Subtarget->isThumb1Only() && !ARM::tGPRRegClass.contains(Reg)) 7511 continue; 7512 if (!Subtarget->isThumb() && !ARM::GPRRegClass.contains(Reg)) 7513 continue; 7514 if (!DefRegs[Reg]) 7515 MIB.addReg(Reg, RegState::ImplicitDefine | RegState::Dead); 7516 } 7517 7518 break; 7519 } 7520 } 7521 7522 // Mark all former landing pads as non-landing pads. The dispatch is the only 7523 // landing pad now. 7524 for (SmallVectorImpl<MachineBasicBlock*>::iterator 7525 I = MBBLPads.begin(), E = MBBLPads.end(); I != E; ++I) 7526 (*I)->setIsEHPad(false); 7527 7528 // The instruction is gone now. 7529 MI->eraseFromParent(); 7530 } 7531 7532 static 7533 MachineBasicBlock *OtherSucc(MachineBasicBlock *MBB, MachineBasicBlock *Succ) { 7534 for (MachineBasicBlock::succ_iterator I = MBB->succ_begin(), 7535 E = MBB->succ_end(); I != E; ++I) 7536 if (*I != Succ) 7537 return *I; 7538 llvm_unreachable("Expecting a BB with two successors!"); 7539 } 7540 7541 /// Return the load opcode for a given load size. If load size >= 8, 7542 /// neon opcode will be returned. 7543 static unsigned getLdOpcode(unsigned LdSize, bool IsThumb1, bool IsThumb2) { 7544 if (LdSize >= 8) 7545 return LdSize == 16 ? ARM::VLD1q32wb_fixed 7546 : LdSize == 8 ? ARM::VLD1d32wb_fixed : 0; 7547 if (IsThumb1) 7548 return LdSize == 4 ? ARM::tLDRi 7549 : LdSize == 2 ? ARM::tLDRHi 7550 : LdSize == 1 ? ARM::tLDRBi : 0; 7551 if (IsThumb2) 7552 return LdSize == 4 ? ARM::t2LDR_POST 7553 : LdSize == 2 ? ARM::t2LDRH_POST 7554 : LdSize == 1 ? ARM::t2LDRB_POST : 0; 7555 return LdSize == 4 ? ARM::LDR_POST_IMM 7556 : LdSize == 2 ? ARM::LDRH_POST 7557 : LdSize == 1 ? ARM::LDRB_POST_IMM : 0; 7558 } 7559 7560 /// Return the store opcode for a given store size. If store size >= 8, 7561 /// neon opcode will be returned. 7562 static unsigned getStOpcode(unsigned StSize, bool IsThumb1, bool IsThumb2) { 7563 if (StSize >= 8) 7564 return StSize == 16 ? ARM::VST1q32wb_fixed 7565 : StSize == 8 ? ARM::VST1d32wb_fixed : 0; 7566 if (IsThumb1) 7567 return StSize == 4 ? ARM::tSTRi 7568 : StSize == 2 ? ARM::tSTRHi 7569 : StSize == 1 ? ARM::tSTRBi : 0; 7570 if (IsThumb2) 7571 return StSize == 4 ? ARM::t2STR_POST 7572 : StSize == 2 ? ARM::t2STRH_POST 7573 : StSize == 1 ? ARM::t2STRB_POST : 0; 7574 return StSize == 4 ? ARM::STR_POST_IMM 7575 : StSize == 2 ? ARM::STRH_POST 7576 : StSize == 1 ? ARM::STRB_POST_IMM : 0; 7577 } 7578 7579 /// Emit a post-increment load operation with given size. The instructions 7580 /// will be added to BB at Pos. 7581 static void emitPostLd(MachineBasicBlock *BB, MachineInstr *Pos, 7582 const TargetInstrInfo *TII, DebugLoc dl, 7583 unsigned LdSize, unsigned Data, unsigned AddrIn, 7584 unsigned AddrOut, bool IsThumb1, bool IsThumb2) { 7585 unsigned LdOpc = getLdOpcode(LdSize, IsThumb1, IsThumb2); 7586 assert(LdOpc != 0 && "Should have a load opcode"); 7587 if (LdSize >= 8) { 7588 AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(LdOpc), Data) 7589 .addReg(AddrOut, RegState::Define).addReg(AddrIn) 7590 .addImm(0)); 7591 } else if (IsThumb1) { 7592 // load + update AddrIn 7593 AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(LdOpc), Data) 7594 .addReg(AddrIn).addImm(0)); 7595 MachineInstrBuilder MIB = 7596 BuildMI(*BB, Pos, dl, TII->get(ARM::tADDi8), AddrOut); 7597 MIB = AddDefaultT1CC(MIB); 7598 MIB.addReg(AddrIn).addImm(LdSize); 7599 AddDefaultPred(MIB); 7600 } else if (IsThumb2) { 7601 AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(LdOpc), Data) 7602 .addReg(AddrOut, RegState::Define).addReg(AddrIn) 7603 .addImm(LdSize)); 7604 } else { // arm 7605 AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(LdOpc), Data) 7606 .addReg(AddrOut, RegState::Define).addReg(AddrIn) 7607 .addReg(0).addImm(LdSize)); 7608 } 7609 } 7610 7611 /// Emit a post-increment store operation with given size. The instructions 7612 /// will be added to BB at Pos. 7613 static void emitPostSt(MachineBasicBlock *BB, MachineInstr *Pos, 7614 const TargetInstrInfo *TII, DebugLoc dl, 7615 unsigned StSize, unsigned Data, unsigned AddrIn, 7616 unsigned AddrOut, bool IsThumb1, bool IsThumb2) { 7617 unsigned StOpc = getStOpcode(StSize, IsThumb1, IsThumb2); 7618 assert(StOpc != 0 && "Should have a store opcode"); 7619 if (StSize >= 8) { 7620 AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(StOpc), AddrOut) 7621 .addReg(AddrIn).addImm(0).addReg(Data)); 7622 } else if (IsThumb1) { 7623 // store + update AddrIn 7624 AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(StOpc)).addReg(Data) 7625 .addReg(AddrIn).addImm(0)); 7626 MachineInstrBuilder MIB = 7627 BuildMI(*BB, Pos, dl, TII->get(ARM::tADDi8), AddrOut); 7628 MIB = AddDefaultT1CC(MIB); 7629 MIB.addReg(AddrIn).addImm(StSize); 7630 AddDefaultPred(MIB); 7631 } else if (IsThumb2) { 7632 AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(StOpc), AddrOut) 7633 .addReg(Data).addReg(AddrIn).addImm(StSize)); 7634 } else { // arm 7635 AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(StOpc), AddrOut) 7636 .addReg(Data).addReg(AddrIn).addReg(0) 7637 .addImm(StSize)); 7638 } 7639 } 7640 7641 MachineBasicBlock * 7642 ARMTargetLowering::EmitStructByval(MachineInstr *MI, 7643 MachineBasicBlock *BB) const { 7644 // This pseudo instruction has 3 operands: dst, src, size 7645 // We expand it to a loop if size > Subtarget->getMaxInlineSizeThreshold(). 7646 // Otherwise, we will generate unrolled scalar copies. 7647 const TargetInstrInfo *TII = Subtarget->getInstrInfo(); 7648 const BasicBlock *LLVM_BB = BB->getBasicBlock(); 7649 MachineFunction::iterator It = ++BB->getIterator(); 7650 7651 unsigned dest = MI->getOperand(0).getReg(); 7652 unsigned src = MI->getOperand(1).getReg(); 7653 unsigned SizeVal = MI->getOperand(2).getImm(); 7654 unsigned Align = MI->getOperand(3).getImm(); 7655 DebugLoc dl = MI->getDebugLoc(); 7656 7657 MachineFunction *MF = BB->getParent(); 7658 MachineRegisterInfo &MRI = MF->getRegInfo(); 7659 unsigned UnitSize = 0; 7660 const TargetRegisterClass *TRC = nullptr; 7661 const TargetRegisterClass *VecTRC = nullptr; 7662 7663 bool IsThumb1 = Subtarget->isThumb1Only(); 7664 bool IsThumb2 = Subtarget->isThumb2(); 7665 7666 if (Align & 1) { 7667 UnitSize = 1; 7668 } else if (Align & 2) { 7669 UnitSize = 2; 7670 } else { 7671 // Check whether we can use NEON instructions. 7672 if (!MF->getFunction()->hasFnAttribute(Attribute::NoImplicitFloat) && 7673 Subtarget->hasNEON()) { 7674 if ((Align % 16 == 0) && SizeVal >= 16) 7675 UnitSize = 16; 7676 else if ((Align % 8 == 0) && SizeVal >= 8) 7677 UnitSize = 8; 7678 } 7679 // Can't use NEON instructions. 7680 if (UnitSize == 0) 7681 UnitSize = 4; 7682 } 7683 7684 // Select the correct opcode and register class for unit size load/store 7685 bool IsNeon = UnitSize >= 8; 7686 TRC = (IsThumb1 || IsThumb2) ? &ARM::tGPRRegClass : &ARM::GPRRegClass; 7687 if (IsNeon) 7688 VecTRC = UnitSize == 16 ? &ARM::DPairRegClass 7689 : UnitSize == 8 ? &ARM::DPRRegClass 7690 : nullptr; 7691 7692 unsigned BytesLeft = SizeVal % UnitSize; 7693 unsigned LoopSize = SizeVal - BytesLeft; 7694 7695 if (SizeVal <= Subtarget->getMaxInlineSizeThreshold()) { 7696 // Use LDR and STR to copy. 7697 // [scratch, srcOut] = LDR_POST(srcIn, UnitSize) 7698 // [destOut] = STR_POST(scratch, destIn, UnitSize) 7699 unsigned srcIn = src; 7700 unsigned destIn = dest; 7701 for (unsigned i = 0; i < LoopSize; i+=UnitSize) { 7702 unsigned srcOut = MRI.createVirtualRegister(TRC); 7703 unsigned destOut = MRI.createVirtualRegister(TRC); 7704 unsigned scratch = MRI.createVirtualRegister(IsNeon ? VecTRC : TRC); 7705 emitPostLd(BB, MI, TII, dl, UnitSize, scratch, srcIn, srcOut, 7706 IsThumb1, IsThumb2); 7707 emitPostSt(BB, MI, TII, dl, UnitSize, scratch, destIn, destOut, 7708 IsThumb1, IsThumb2); 7709 srcIn = srcOut; 7710 destIn = destOut; 7711 } 7712 7713 // Handle the leftover bytes with LDRB and STRB. 7714 // [scratch, srcOut] = LDRB_POST(srcIn, 1) 7715 // [destOut] = STRB_POST(scratch, destIn, 1) 7716 for (unsigned i = 0; i < BytesLeft; i++) { 7717 unsigned srcOut = MRI.createVirtualRegister(TRC); 7718 unsigned destOut = MRI.createVirtualRegister(TRC); 7719 unsigned scratch = MRI.createVirtualRegister(TRC); 7720 emitPostLd(BB, MI, TII, dl, 1, scratch, srcIn, srcOut, 7721 IsThumb1, IsThumb2); 7722 emitPostSt(BB, MI, TII, dl, 1, scratch, destIn, destOut, 7723 IsThumb1, IsThumb2); 7724 srcIn = srcOut; 7725 destIn = destOut; 7726 } 7727 MI->eraseFromParent(); // The instruction is gone now. 7728 return BB; 7729 } 7730 7731 // Expand the pseudo op to a loop. 7732 // thisMBB: 7733 // ... 7734 // movw varEnd, # --> with thumb2 7735 // movt varEnd, # 7736 // ldrcp varEnd, idx --> without thumb2 7737 // fallthrough --> loopMBB 7738 // loopMBB: 7739 // PHI varPhi, varEnd, varLoop 7740 // PHI srcPhi, src, srcLoop 7741 // PHI destPhi, dst, destLoop 7742 // [scratch, srcLoop] = LDR_POST(srcPhi, UnitSize) 7743 // [destLoop] = STR_POST(scratch, destPhi, UnitSize) 7744 // subs varLoop, varPhi, #UnitSize 7745 // bne loopMBB 7746 // fallthrough --> exitMBB 7747 // exitMBB: 7748 // epilogue to handle left-over bytes 7749 // [scratch, srcOut] = LDRB_POST(srcLoop, 1) 7750 // [destOut] = STRB_POST(scratch, destLoop, 1) 7751 MachineBasicBlock *loopMBB = MF->CreateMachineBasicBlock(LLVM_BB); 7752 MachineBasicBlock *exitMBB = MF->CreateMachineBasicBlock(LLVM_BB); 7753 MF->insert(It, loopMBB); 7754 MF->insert(It, exitMBB); 7755 7756 // Transfer the remainder of BB and its successor edges to exitMBB. 7757 exitMBB->splice(exitMBB->begin(), BB, 7758 std::next(MachineBasicBlock::iterator(MI)), BB->end()); 7759 exitMBB->transferSuccessorsAndUpdatePHIs(BB); 7760 7761 // Load an immediate to varEnd. 7762 unsigned varEnd = MRI.createVirtualRegister(TRC); 7763 if (Subtarget->useMovt(*MF)) { 7764 unsigned Vtmp = varEnd; 7765 if ((LoopSize & 0xFFFF0000) != 0) 7766 Vtmp = MRI.createVirtualRegister(TRC); 7767 AddDefaultPred(BuildMI(BB, dl, 7768 TII->get(IsThumb2 ? ARM::t2MOVi16 : ARM::MOVi16), 7769 Vtmp).addImm(LoopSize & 0xFFFF)); 7770 7771 if ((LoopSize & 0xFFFF0000) != 0) 7772 AddDefaultPred(BuildMI(BB, dl, 7773 TII->get(IsThumb2 ? ARM::t2MOVTi16 : ARM::MOVTi16), 7774 varEnd) 7775 .addReg(Vtmp) 7776 .addImm(LoopSize >> 16)); 7777 } else { 7778 MachineConstantPool *ConstantPool = MF->getConstantPool(); 7779 Type *Int32Ty = Type::getInt32Ty(MF->getFunction()->getContext()); 7780 const Constant *C = ConstantInt::get(Int32Ty, LoopSize); 7781 7782 // MachineConstantPool wants an explicit alignment. 7783 unsigned Align = MF->getDataLayout().getPrefTypeAlignment(Int32Ty); 7784 if (Align == 0) 7785 Align = MF->getDataLayout().getTypeAllocSize(C->getType()); 7786 unsigned Idx = ConstantPool->getConstantPoolIndex(C, Align); 7787 7788 if (IsThumb1) 7789 AddDefaultPred(BuildMI(*BB, MI, dl, TII->get(ARM::tLDRpci)).addReg( 7790 varEnd, RegState::Define).addConstantPoolIndex(Idx)); 7791 else 7792 AddDefaultPred(BuildMI(*BB, MI, dl, TII->get(ARM::LDRcp)).addReg( 7793 varEnd, RegState::Define).addConstantPoolIndex(Idx).addImm(0)); 7794 } 7795 BB->addSuccessor(loopMBB); 7796 7797 // Generate the loop body: 7798 // varPhi = PHI(varLoop, varEnd) 7799 // srcPhi = PHI(srcLoop, src) 7800 // destPhi = PHI(destLoop, dst) 7801 MachineBasicBlock *entryBB = BB; 7802 BB = loopMBB; 7803 unsigned varLoop = MRI.createVirtualRegister(TRC); 7804 unsigned varPhi = MRI.createVirtualRegister(TRC); 7805 unsigned srcLoop = MRI.createVirtualRegister(TRC); 7806 unsigned srcPhi = MRI.createVirtualRegister(TRC); 7807 unsigned destLoop = MRI.createVirtualRegister(TRC); 7808 unsigned destPhi = MRI.createVirtualRegister(TRC); 7809 7810 BuildMI(*BB, BB->begin(), dl, TII->get(ARM::PHI), varPhi) 7811 .addReg(varLoop).addMBB(loopMBB) 7812 .addReg(varEnd).addMBB(entryBB); 7813 BuildMI(BB, dl, TII->get(ARM::PHI), srcPhi) 7814 .addReg(srcLoop).addMBB(loopMBB) 7815 .addReg(src).addMBB(entryBB); 7816 BuildMI(BB, dl, TII->get(ARM::PHI), destPhi) 7817 .addReg(destLoop).addMBB(loopMBB) 7818 .addReg(dest).addMBB(entryBB); 7819 7820 // [scratch, srcLoop] = LDR_POST(srcPhi, UnitSize) 7821 // [destLoop] = STR_POST(scratch, destPhi, UnitSiz) 7822 unsigned scratch = MRI.createVirtualRegister(IsNeon ? VecTRC : TRC); 7823 emitPostLd(BB, BB->end(), TII, dl, UnitSize, scratch, srcPhi, srcLoop, 7824 IsThumb1, IsThumb2); 7825 emitPostSt(BB, BB->end(), TII, dl, UnitSize, scratch, destPhi, destLoop, 7826 IsThumb1, IsThumb2); 7827 7828 // Decrement loop variable by UnitSize. 7829 if (IsThumb1) { 7830 MachineInstrBuilder MIB = 7831 BuildMI(*BB, BB->end(), dl, TII->get(ARM::tSUBi8), varLoop); 7832 MIB = AddDefaultT1CC(MIB); 7833 MIB.addReg(varPhi).addImm(UnitSize); 7834 AddDefaultPred(MIB); 7835 } else { 7836 MachineInstrBuilder MIB = 7837 BuildMI(*BB, BB->end(), dl, 7838 TII->get(IsThumb2 ? ARM::t2SUBri : ARM::SUBri), varLoop); 7839 AddDefaultCC(AddDefaultPred(MIB.addReg(varPhi).addImm(UnitSize))); 7840 MIB->getOperand(5).setReg(ARM::CPSR); 7841 MIB->getOperand(5).setIsDef(true); 7842 } 7843 BuildMI(*BB, BB->end(), dl, 7844 TII->get(IsThumb1 ? ARM::tBcc : IsThumb2 ? ARM::t2Bcc : ARM::Bcc)) 7845 .addMBB(loopMBB).addImm(ARMCC::NE).addReg(ARM::CPSR); 7846 7847 // loopMBB can loop back to loopMBB or fall through to exitMBB. 7848 BB->addSuccessor(loopMBB); 7849 BB->addSuccessor(exitMBB); 7850 7851 // Add epilogue to handle BytesLeft. 7852 BB = exitMBB; 7853 MachineInstr *StartOfExit = exitMBB->begin(); 7854 7855 // [scratch, srcOut] = LDRB_POST(srcLoop, 1) 7856 // [destOut] = STRB_POST(scratch, destLoop, 1) 7857 unsigned srcIn = srcLoop; 7858 unsigned destIn = destLoop; 7859 for (unsigned i = 0; i < BytesLeft; i++) { 7860 unsigned srcOut = MRI.createVirtualRegister(TRC); 7861 unsigned destOut = MRI.createVirtualRegister(TRC); 7862 unsigned scratch = MRI.createVirtualRegister(TRC); 7863 emitPostLd(BB, StartOfExit, TII, dl, 1, scratch, srcIn, srcOut, 7864 IsThumb1, IsThumb2); 7865 emitPostSt(BB, StartOfExit, TII, dl, 1, scratch, destIn, destOut, 7866 IsThumb1, IsThumb2); 7867 srcIn = srcOut; 7868 destIn = destOut; 7869 } 7870 7871 MI->eraseFromParent(); // The instruction is gone now. 7872 return BB; 7873 } 7874 7875 MachineBasicBlock * 7876 ARMTargetLowering::EmitLowered__chkstk(MachineInstr *MI, 7877 MachineBasicBlock *MBB) const { 7878 const TargetMachine &TM = getTargetMachine(); 7879 const TargetInstrInfo &TII = *Subtarget->getInstrInfo(); 7880 DebugLoc DL = MI->getDebugLoc(); 7881 7882 assert(Subtarget->isTargetWindows() && 7883 "__chkstk is only supported on Windows"); 7884 assert(Subtarget->isThumb2() && "Windows on ARM requires Thumb-2 mode"); 7885 7886 // __chkstk takes the number of words to allocate on the stack in R4, and 7887 // returns the stack adjustment in number of bytes in R4. This will not 7888 // clober any other registers (other than the obvious lr). 7889 // 7890 // Although, technically, IP should be considered a register which may be 7891 // clobbered, the call itself will not touch it. Windows on ARM is a pure 7892 // thumb-2 environment, so there is no interworking required. As a result, we 7893 // do not expect a veneer to be emitted by the linker, clobbering IP. 7894 // 7895 // Each module receives its own copy of __chkstk, so no import thunk is 7896 // required, again, ensuring that IP is not clobbered. 7897 // 7898 // Finally, although some linkers may theoretically provide a trampoline for 7899 // out of range calls (which is quite common due to a 32M range limitation of 7900 // branches for Thumb), we can generate the long-call version via 7901 // -mcmodel=large, alleviating the need for the trampoline which may clobber 7902 // IP. 7903 7904 switch (TM.getCodeModel()) { 7905 case CodeModel::Small: 7906 case CodeModel::Medium: 7907 case CodeModel::Default: 7908 case CodeModel::Kernel: 7909 BuildMI(*MBB, MI, DL, TII.get(ARM::tBL)) 7910 .addImm((unsigned)ARMCC::AL).addReg(0) 7911 .addExternalSymbol("__chkstk") 7912 .addReg(ARM::R4, RegState::Implicit | RegState::Kill) 7913 .addReg(ARM::R4, RegState::Implicit | RegState::Define) 7914 .addReg(ARM::R12, RegState::Implicit | RegState::Define | RegState::Dead); 7915 break; 7916 case CodeModel::Large: 7917 case CodeModel::JITDefault: { 7918 MachineRegisterInfo &MRI = MBB->getParent()->getRegInfo(); 7919 unsigned Reg = MRI.createVirtualRegister(&ARM::rGPRRegClass); 7920 7921 BuildMI(*MBB, MI, DL, TII.get(ARM::t2MOVi32imm), Reg) 7922 .addExternalSymbol("__chkstk"); 7923 BuildMI(*MBB, MI, DL, TII.get(ARM::tBLXr)) 7924 .addImm((unsigned)ARMCC::AL).addReg(0) 7925 .addReg(Reg, RegState::Kill) 7926 .addReg(ARM::R4, RegState::Implicit | RegState::Kill) 7927 .addReg(ARM::R4, RegState::Implicit | RegState::Define) 7928 .addReg(ARM::R12, RegState::Implicit | RegState::Define | RegState::Dead); 7929 break; 7930 } 7931 } 7932 7933 AddDefaultCC(AddDefaultPred(BuildMI(*MBB, MI, DL, TII.get(ARM::t2SUBrr), 7934 ARM::SP) 7935 .addReg(ARM::SP).addReg(ARM::R4))); 7936 7937 MI->eraseFromParent(); 7938 return MBB; 7939 } 7940 7941 MachineBasicBlock * 7942 ARMTargetLowering::EmitLowered__dbzchk(MachineInstr *MI, 7943 MachineBasicBlock *MBB) const { 7944 DebugLoc DL = MI->getDebugLoc(); 7945 MachineFunction *MF = MBB->getParent(); 7946 const TargetInstrInfo *TII = Subtarget->getInstrInfo(); 7947 7948 MachineBasicBlock *ContBB = MF->CreateMachineBasicBlock(); 7949 MF->push_back(ContBB); 7950 ContBB->splice(ContBB->begin(), MBB, 7951 std::next(MachineBasicBlock::iterator(MI)), MBB->end()); 7952 MBB->addSuccessor(ContBB); 7953 7954 MachineBasicBlock *TrapBB = MF->CreateMachineBasicBlock(); 7955 MF->push_back(TrapBB); 7956 BuildMI(TrapBB, DL, TII->get(ARM::t2UDF)).addImm(249); 7957 MBB->addSuccessor(TrapBB); 7958 7959 BuildMI(*MBB, MI, DL, TII->get(ARM::tCBZ)) 7960 .addReg(MI->getOperand(0).getReg()) 7961 .addMBB(TrapBB); 7962 7963 MI->eraseFromParent(); 7964 return ContBB; 7965 } 7966 7967 MachineBasicBlock * 7968 ARMTargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI, 7969 MachineBasicBlock *BB) const { 7970 const TargetInstrInfo *TII = Subtarget->getInstrInfo(); 7971 DebugLoc dl = MI->getDebugLoc(); 7972 bool isThumb2 = Subtarget->isThumb2(); 7973 switch (MI->getOpcode()) { 7974 default: { 7975 MI->dump(); 7976 llvm_unreachable("Unexpected instr type to insert"); 7977 } 7978 // The Thumb2 pre-indexed stores have the same MI operands, they just 7979 // define them differently in the .td files from the isel patterns, so 7980 // they need pseudos. 7981 case ARM::t2STR_preidx: 7982 MI->setDesc(TII->get(ARM::t2STR_PRE)); 7983 return BB; 7984 case ARM::t2STRB_preidx: 7985 MI->setDesc(TII->get(ARM::t2STRB_PRE)); 7986 return BB; 7987 case ARM::t2STRH_preidx: 7988 MI->setDesc(TII->get(ARM::t2STRH_PRE)); 7989 return BB; 7990 7991 case ARM::STRi_preidx: 7992 case ARM::STRBi_preidx: { 7993 unsigned NewOpc = MI->getOpcode() == ARM::STRi_preidx ? 7994 ARM::STR_PRE_IMM : ARM::STRB_PRE_IMM; 7995 // Decode the offset. 7996 unsigned Offset = MI->getOperand(4).getImm(); 7997 bool isSub = ARM_AM::getAM2Op(Offset) == ARM_AM::sub; 7998 Offset = ARM_AM::getAM2Offset(Offset); 7999 if (isSub) 8000 Offset = -Offset; 8001 8002 MachineMemOperand *MMO = *MI->memoperands_begin(); 8003 BuildMI(*BB, MI, dl, TII->get(NewOpc)) 8004 .addOperand(MI->getOperand(0)) // Rn_wb 8005 .addOperand(MI->getOperand(1)) // Rt 8006 .addOperand(MI->getOperand(2)) // Rn 8007 .addImm(Offset) // offset (skip GPR==zero_reg) 8008 .addOperand(MI->getOperand(5)) // pred 8009 .addOperand(MI->getOperand(6)) 8010 .addMemOperand(MMO); 8011 MI->eraseFromParent(); 8012 return BB; 8013 } 8014 case ARM::STRr_preidx: 8015 case ARM::STRBr_preidx: 8016 case ARM::STRH_preidx: { 8017 unsigned NewOpc; 8018 switch (MI->getOpcode()) { 8019 default: llvm_unreachable("unexpected opcode!"); 8020 case ARM::STRr_preidx: NewOpc = ARM::STR_PRE_REG; break; 8021 case ARM::STRBr_preidx: NewOpc = ARM::STRB_PRE_REG; break; 8022 case ARM::STRH_preidx: NewOpc = ARM::STRH_PRE; break; 8023 } 8024 MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(NewOpc)); 8025 for (unsigned i = 0; i < MI->getNumOperands(); ++i) 8026 MIB.addOperand(MI->getOperand(i)); 8027 MI->eraseFromParent(); 8028 return BB; 8029 } 8030 8031 case ARM::tMOVCCr_pseudo: { 8032 // To "insert" a SELECT_CC instruction, we actually have to insert the 8033 // diamond control-flow pattern. The incoming instruction knows the 8034 // destination vreg to set, the condition code register to branch on, the 8035 // true/false values to select between, and a branch opcode to use. 8036 const BasicBlock *LLVM_BB = BB->getBasicBlock(); 8037 MachineFunction::iterator It = ++BB->getIterator(); 8038 8039 // thisMBB: 8040 // ... 8041 // TrueVal = ... 8042 // cmpTY ccX, r1, r2 8043 // bCC copy1MBB 8044 // fallthrough --> copy0MBB 8045 MachineBasicBlock *thisMBB = BB; 8046 MachineFunction *F = BB->getParent(); 8047 MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB); 8048 MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB); 8049 F->insert(It, copy0MBB); 8050 F->insert(It, sinkMBB); 8051 8052 // Transfer the remainder of BB and its successor edges to sinkMBB. 8053 sinkMBB->splice(sinkMBB->begin(), BB, 8054 std::next(MachineBasicBlock::iterator(MI)), BB->end()); 8055 sinkMBB->transferSuccessorsAndUpdatePHIs(BB); 8056 8057 BB->addSuccessor(copy0MBB); 8058 BB->addSuccessor(sinkMBB); 8059 8060 BuildMI(BB, dl, TII->get(ARM::tBcc)).addMBB(sinkMBB) 8061 .addImm(MI->getOperand(3).getImm()).addReg(MI->getOperand(4).getReg()); 8062 8063 // copy0MBB: 8064 // %FalseValue = ... 8065 // # fallthrough to sinkMBB 8066 BB = copy0MBB; 8067 8068 // Update machine-CFG edges 8069 BB->addSuccessor(sinkMBB); 8070 8071 // sinkMBB: 8072 // %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ] 8073 // ... 8074 BB = sinkMBB; 8075 BuildMI(*BB, BB->begin(), dl, 8076 TII->get(ARM::PHI), MI->getOperand(0).getReg()) 8077 .addReg(MI->getOperand(1).getReg()).addMBB(copy0MBB) 8078 .addReg(MI->getOperand(2).getReg()).addMBB(thisMBB); 8079 8080 MI->eraseFromParent(); // The pseudo instruction is gone now. 8081 return BB; 8082 } 8083 8084 case ARM::BCCi64: 8085 case ARM::BCCZi64: { 8086 // If there is an unconditional branch to the other successor, remove it. 8087 BB->erase(std::next(MachineBasicBlock::iterator(MI)), BB->end()); 8088 8089 // Compare both parts that make up the double comparison separately for 8090 // equality. 8091 bool RHSisZero = MI->getOpcode() == ARM::BCCZi64; 8092 8093 unsigned LHS1 = MI->getOperand(1).getReg(); 8094 unsigned LHS2 = MI->getOperand(2).getReg(); 8095 if (RHSisZero) { 8096 AddDefaultPred(BuildMI(BB, dl, 8097 TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri)) 8098 .addReg(LHS1).addImm(0)); 8099 BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri)) 8100 .addReg(LHS2).addImm(0) 8101 .addImm(ARMCC::EQ).addReg(ARM::CPSR); 8102 } else { 8103 unsigned RHS1 = MI->getOperand(3).getReg(); 8104 unsigned RHS2 = MI->getOperand(4).getReg(); 8105 AddDefaultPred(BuildMI(BB, dl, 8106 TII->get(isThumb2 ? ARM::t2CMPrr : ARM::CMPrr)) 8107 .addReg(LHS1).addReg(RHS1)); 8108 BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPrr : ARM::CMPrr)) 8109 .addReg(LHS2).addReg(RHS2) 8110 .addImm(ARMCC::EQ).addReg(ARM::CPSR); 8111 } 8112 8113 MachineBasicBlock *destMBB = MI->getOperand(RHSisZero ? 3 : 5).getMBB(); 8114 MachineBasicBlock *exitMBB = OtherSucc(BB, destMBB); 8115 if (MI->getOperand(0).getImm() == ARMCC::NE) 8116 std::swap(destMBB, exitMBB); 8117 8118 BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc)) 8119 .addMBB(destMBB).addImm(ARMCC::EQ).addReg(ARM::CPSR); 8120 if (isThumb2) 8121 AddDefaultPred(BuildMI(BB, dl, TII->get(ARM::t2B)).addMBB(exitMBB)); 8122 else 8123 BuildMI(BB, dl, TII->get(ARM::B)) .addMBB(exitMBB); 8124 8125 MI->eraseFromParent(); // The pseudo instruction is gone now. 8126 return BB; 8127 } 8128 8129 case ARM::Int_eh_sjlj_setjmp: 8130 case ARM::Int_eh_sjlj_setjmp_nofp: 8131 case ARM::tInt_eh_sjlj_setjmp: 8132 case ARM::t2Int_eh_sjlj_setjmp: 8133 case ARM::t2Int_eh_sjlj_setjmp_nofp: 8134 return BB; 8135 8136 case ARM::Int_eh_sjlj_setup_dispatch: 8137 EmitSjLjDispatchBlock(MI, BB); 8138 return BB; 8139 8140 case ARM::ABS: 8141 case ARM::t2ABS: { 8142 // To insert an ABS instruction, we have to insert the 8143 // diamond control-flow pattern. The incoming instruction knows the 8144 // source vreg to test against 0, the destination vreg to set, 8145 // the condition code register to branch on, the 8146 // true/false values to select between, and a branch opcode to use. 8147 // It transforms 8148 // V1 = ABS V0 8149 // into 8150 // V2 = MOVS V0 8151 // BCC (branch to SinkBB if V0 >= 0) 8152 // RSBBB: V3 = RSBri V2, 0 (compute ABS if V2 < 0) 8153 // SinkBB: V1 = PHI(V2, V3) 8154 const BasicBlock *LLVM_BB = BB->getBasicBlock(); 8155 MachineFunction::iterator BBI = ++BB->getIterator(); 8156 MachineFunction *Fn = BB->getParent(); 8157 MachineBasicBlock *RSBBB = Fn->CreateMachineBasicBlock(LLVM_BB); 8158 MachineBasicBlock *SinkBB = Fn->CreateMachineBasicBlock(LLVM_BB); 8159 Fn->insert(BBI, RSBBB); 8160 Fn->insert(BBI, SinkBB); 8161 8162 unsigned int ABSSrcReg = MI->getOperand(1).getReg(); 8163 unsigned int ABSDstReg = MI->getOperand(0).getReg(); 8164 bool ABSSrcKIll = MI->getOperand(1).isKill(); 8165 bool isThumb2 = Subtarget->isThumb2(); 8166 MachineRegisterInfo &MRI = Fn->getRegInfo(); 8167 // In Thumb mode S must not be specified if source register is the SP or 8168 // PC and if destination register is the SP, so restrict register class 8169 unsigned NewRsbDstReg = 8170 MRI.createVirtualRegister(isThumb2 ? &ARM::rGPRRegClass : &ARM::GPRRegClass); 8171 8172 // Transfer the remainder of BB and its successor edges to sinkMBB. 8173 SinkBB->splice(SinkBB->begin(), BB, 8174 std::next(MachineBasicBlock::iterator(MI)), BB->end()); 8175 SinkBB->transferSuccessorsAndUpdatePHIs(BB); 8176 8177 BB->addSuccessor(RSBBB); 8178 BB->addSuccessor(SinkBB); 8179 8180 // fall through to SinkMBB 8181 RSBBB->addSuccessor(SinkBB); 8182 8183 // insert a cmp at the end of BB 8184 AddDefaultPred(BuildMI(BB, dl, 8185 TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri)) 8186 .addReg(ABSSrcReg).addImm(0)); 8187 8188 // insert a bcc with opposite CC to ARMCC::MI at the end of BB 8189 BuildMI(BB, dl, 8190 TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc)).addMBB(SinkBB) 8191 .addImm(ARMCC::getOppositeCondition(ARMCC::MI)).addReg(ARM::CPSR); 8192 8193 // insert rsbri in RSBBB 8194 // Note: BCC and rsbri will be converted into predicated rsbmi 8195 // by if-conversion pass 8196 BuildMI(*RSBBB, RSBBB->begin(), dl, 8197 TII->get(isThumb2 ? ARM::t2RSBri : ARM::RSBri), NewRsbDstReg) 8198 .addReg(ABSSrcReg, ABSSrcKIll ? RegState::Kill : 0) 8199 .addImm(0).addImm((unsigned)ARMCC::AL).addReg(0).addReg(0); 8200 8201 // insert PHI in SinkBB, 8202 // reuse ABSDstReg to not change uses of ABS instruction 8203 BuildMI(*SinkBB, SinkBB->begin(), dl, 8204 TII->get(ARM::PHI), ABSDstReg) 8205 .addReg(NewRsbDstReg).addMBB(RSBBB) 8206 .addReg(ABSSrcReg).addMBB(BB); 8207 8208 // remove ABS instruction 8209 MI->eraseFromParent(); 8210 8211 // return last added BB 8212 return SinkBB; 8213 } 8214 case ARM::COPY_STRUCT_BYVAL_I32: 8215 ++NumLoopByVals; 8216 return EmitStructByval(MI, BB); 8217 case ARM::WIN__CHKSTK: 8218 return EmitLowered__chkstk(MI, BB); 8219 case ARM::WIN__DBZCHK: 8220 return EmitLowered__dbzchk(MI, BB); 8221 } 8222 } 8223 8224 /// \brief Attaches vregs to MEMCPY that it will use as scratch registers 8225 /// when it is expanded into LDM/STM. This is done as a post-isel lowering 8226 /// instead of as a custom inserter because we need the use list from the SDNode. 8227 static void attachMEMCPYScratchRegs(const ARMSubtarget *Subtarget, 8228 MachineInstr *MI, const SDNode *Node) { 8229 bool isThumb1 = Subtarget->isThumb1Only(); 8230 8231 DebugLoc DL = MI->getDebugLoc(); 8232 MachineFunction *MF = MI->getParent()->getParent(); 8233 MachineRegisterInfo &MRI = MF->getRegInfo(); 8234 MachineInstrBuilder MIB(*MF, MI); 8235 8236 // If the new dst/src is unused mark it as dead. 8237 if (!Node->hasAnyUseOfValue(0)) { 8238 MI->getOperand(0).setIsDead(true); 8239 } 8240 if (!Node->hasAnyUseOfValue(1)) { 8241 MI->getOperand(1).setIsDead(true); 8242 } 8243 8244 // The MEMCPY both defines and kills the scratch registers. 8245 for (unsigned I = 0; I != MI->getOperand(4).getImm(); ++I) { 8246 unsigned TmpReg = MRI.createVirtualRegister(isThumb1 ? &ARM::tGPRRegClass 8247 : &ARM::GPRRegClass); 8248 MIB.addReg(TmpReg, RegState::Define|RegState::Dead); 8249 } 8250 } 8251 8252 void ARMTargetLowering::AdjustInstrPostInstrSelection(MachineInstr *MI, 8253 SDNode *Node) const { 8254 if (MI->getOpcode() == ARM::MEMCPY) { 8255 attachMEMCPYScratchRegs(Subtarget, MI, Node); 8256 return; 8257 } 8258 8259 const MCInstrDesc *MCID = &MI->getDesc(); 8260 // Adjust potentially 's' setting instructions after isel, i.e. ADC, SBC, RSB, 8261 // RSC. Coming out of isel, they have an implicit CPSR def, but the optional 8262 // operand is still set to noreg. If needed, set the optional operand's 8263 // register to CPSR, and remove the redundant implicit def. 8264 // 8265 // e.g. ADCS (..., CPSR<imp-def>) -> ADC (... opt:CPSR<def>). 8266 8267 // Rename pseudo opcodes. 8268 unsigned NewOpc = convertAddSubFlagsOpcode(MI->getOpcode()); 8269 if (NewOpc) { 8270 const ARMBaseInstrInfo *TII = Subtarget->getInstrInfo(); 8271 MCID = &TII->get(NewOpc); 8272 8273 assert(MCID->getNumOperands() == MI->getDesc().getNumOperands() + 1 && 8274 "converted opcode should be the same except for cc_out"); 8275 8276 MI->setDesc(*MCID); 8277 8278 // Add the optional cc_out operand 8279 MI->addOperand(MachineOperand::CreateReg(0, /*isDef=*/true)); 8280 } 8281 unsigned ccOutIdx = MCID->getNumOperands() - 1; 8282 8283 // Any ARM instruction that sets the 's' bit should specify an optional 8284 // "cc_out" operand in the last operand position. 8285 if (!MI->hasOptionalDef() || !MCID->OpInfo[ccOutIdx].isOptionalDef()) { 8286 assert(!NewOpc && "Optional cc_out operand required"); 8287 return; 8288 } 8289 // Look for an implicit def of CPSR added by MachineInstr ctor. Remove it 8290 // since we already have an optional CPSR def. 8291 bool definesCPSR = false; 8292 bool deadCPSR = false; 8293 for (unsigned i = MCID->getNumOperands(), e = MI->getNumOperands(); 8294 i != e; ++i) { 8295 const MachineOperand &MO = MI->getOperand(i); 8296 if (MO.isReg() && MO.isDef() && MO.getReg() == ARM::CPSR) { 8297 definesCPSR = true; 8298 if (MO.isDead()) 8299 deadCPSR = true; 8300 MI->RemoveOperand(i); 8301 break; 8302 } 8303 } 8304 if (!definesCPSR) { 8305 assert(!NewOpc && "Optional cc_out operand required"); 8306 return; 8307 } 8308 assert(deadCPSR == !Node->hasAnyUseOfValue(1) && "inconsistent dead flag"); 8309 if (deadCPSR) { 8310 assert(!MI->getOperand(ccOutIdx).getReg() && 8311 "expect uninitialized optional cc_out operand"); 8312 return; 8313 } 8314 8315 // If this instruction was defined with an optional CPSR def and its dag node 8316 // had a live implicit CPSR def, then activate the optional CPSR def. 8317 MachineOperand &MO = MI->getOperand(ccOutIdx); 8318 MO.setReg(ARM::CPSR); 8319 MO.setIsDef(true); 8320 } 8321 8322 //===----------------------------------------------------------------------===// 8323 // ARM Optimization Hooks 8324 //===----------------------------------------------------------------------===// 8325 8326 // Helper function that checks if N is a null or all ones constant. 8327 static inline bool isZeroOrAllOnes(SDValue N, bool AllOnes) { 8328 return AllOnes ? isAllOnesConstant(N) : isNullConstant(N); 8329 } 8330 8331 // Return true if N is conditionally 0 or all ones. 8332 // Detects these expressions where cc is an i1 value: 8333 // 8334 // (select cc 0, y) [AllOnes=0] 8335 // (select cc y, 0) [AllOnes=0] 8336 // (zext cc) [AllOnes=0] 8337 // (sext cc) [AllOnes=0/1] 8338 // (select cc -1, y) [AllOnes=1] 8339 // (select cc y, -1) [AllOnes=1] 8340 // 8341 // Invert is set when N is the null/all ones constant when CC is false. 8342 // OtherOp is set to the alternative value of N. 8343 static bool isConditionalZeroOrAllOnes(SDNode *N, bool AllOnes, 8344 SDValue &CC, bool &Invert, 8345 SDValue &OtherOp, 8346 SelectionDAG &DAG) { 8347 switch (N->getOpcode()) { 8348 default: return false; 8349 case ISD::SELECT: { 8350 CC = N->getOperand(0); 8351 SDValue N1 = N->getOperand(1); 8352 SDValue N2 = N->getOperand(2); 8353 if (isZeroOrAllOnes(N1, AllOnes)) { 8354 Invert = false; 8355 OtherOp = N2; 8356 return true; 8357 } 8358 if (isZeroOrAllOnes(N2, AllOnes)) { 8359 Invert = true; 8360 OtherOp = N1; 8361 return true; 8362 } 8363 return false; 8364 } 8365 case ISD::ZERO_EXTEND: 8366 // (zext cc) can never be the all ones value. 8367 if (AllOnes) 8368 return false; 8369 // Fall through. 8370 case ISD::SIGN_EXTEND: { 8371 SDLoc dl(N); 8372 EVT VT = N->getValueType(0); 8373 CC = N->getOperand(0); 8374 if (CC.getValueType() != MVT::i1) 8375 return false; 8376 Invert = !AllOnes; 8377 if (AllOnes) 8378 // When looking for an AllOnes constant, N is an sext, and the 'other' 8379 // value is 0. 8380 OtherOp = DAG.getConstant(0, dl, VT); 8381 else if (N->getOpcode() == ISD::ZERO_EXTEND) 8382 // When looking for a 0 constant, N can be zext or sext. 8383 OtherOp = DAG.getConstant(1, dl, VT); 8384 else 8385 OtherOp = DAG.getConstant(APInt::getAllOnesValue(VT.getSizeInBits()), dl, 8386 VT); 8387 return true; 8388 } 8389 } 8390 } 8391 8392 // Combine a constant select operand into its use: 8393 // 8394 // (add (select cc, 0, c), x) -> (select cc, x, (add, x, c)) 8395 // (sub x, (select cc, 0, c)) -> (select cc, x, (sub, x, c)) 8396 // (and (select cc, -1, c), x) -> (select cc, x, (and, x, c)) [AllOnes=1] 8397 // (or (select cc, 0, c), x) -> (select cc, x, (or, x, c)) 8398 // (xor (select cc, 0, c), x) -> (select cc, x, (xor, x, c)) 8399 // 8400 // The transform is rejected if the select doesn't have a constant operand that 8401 // is null, or all ones when AllOnes is set. 8402 // 8403 // Also recognize sext/zext from i1: 8404 // 8405 // (add (zext cc), x) -> (select cc (add x, 1), x) 8406 // (add (sext cc), x) -> (select cc (add x, -1), x) 8407 // 8408 // These transformations eventually create predicated instructions. 8409 // 8410 // @param N The node to transform. 8411 // @param Slct The N operand that is a select. 8412 // @param OtherOp The other N operand (x above). 8413 // @param DCI Context. 8414 // @param AllOnes Require the select constant to be all ones instead of null. 8415 // @returns The new node, or SDValue() on failure. 8416 static 8417 SDValue combineSelectAndUse(SDNode *N, SDValue Slct, SDValue OtherOp, 8418 TargetLowering::DAGCombinerInfo &DCI, 8419 bool AllOnes = false) { 8420 SelectionDAG &DAG = DCI.DAG; 8421 EVT VT = N->getValueType(0); 8422 SDValue NonConstantVal; 8423 SDValue CCOp; 8424 bool SwapSelectOps; 8425 if (!isConditionalZeroOrAllOnes(Slct.getNode(), AllOnes, CCOp, SwapSelectOps, 8426 NonConstantVal, DAG)) 8427 return SDValue(); 8428 8429 // Slct is now know to be the desired identity constant when CC is true. 8430 SDValue TrueVal = OtherOp; 8431 SDValue FalseVal = DAG.getNode(N->getOpcode(), SDLoc(N), VT, 8432 OtherOp, NonConstantVal); 8433 // Unless SwapSelectOps says CC should be false. 8434 if (SwapSelectOps) 8435 std::swap(TrueVal, FalseVal); 8436 8437 return DAG.getNode(ISD::SELECT, SDLoc(N), VT, 8438 CCOp, TrueVal, FalseVal); 8439 } 8440 8441 // Attempt combineSelectAndUse on each operand of a commutative operator N. 8442 static 8443 SDValue combineSelectAndUseCommutative(SDNode *N, bool AllOnes, 8444 TargetLowering::DAGCombinerInfo &DCI) { 8445 SDValue N0 = N->getOperand(0); 8446 SDValue N1 = N->getOperand(1); 8447 if (N0.getNode()->hasOneUse()) { 8448 SDValue Result = combineSelectAndUse(N, N0, N1, DCI, AllOnes); 8449 if (Result.getNode()) 8450 return Result; 8451 } 8452 if (N1.getNode()->hasOneUse()) { 8453 SDValue Result = combineSelectAndUse(N, N1, N0, DCI, AllOnes); 8454 if (Result.getNode()) 8455 return Result; 8456 } 8457 return SDValue(); 8458 } 8459 8460 // AddCombineToVPADDL- For pair-wise add on neon, use the vpaddl instruction 8461 // (only after legalization). 8462 static SDValue AddCombineToVPADDL(SDNode *N, SDValue N0, SDValue N1, 8463 TargetLowering::DAGCombinerInfo &DCI, 8464 const ARMSubtarget *Subtarget) { 8465 8466 // Only perform optimization if after legalize, and if NEON is available. We 8467 // also expected both operands to be BUILD_VECTORs. 8468 if (DCI.isBeforeLegalize() || !Subtarget->hasNEON() 8469 || N0.getOpcode() != ISD::BUILD_VECTOR 8470 || N1.getOpcode() != ISD::BUILD_VECTOR) 8471 return SDValue(); 8472 8473 // Check output type since VPADDL operand elements can only be 8, 16, or 32. 8474 EVT VT = N->getValueType(0); 8475 if (!VT.isInteger() || VT.getVectorElementType() == MVT::i64) 8476 return SDValue(); 8477 8478 // Check that the vector operands are of the right form. 8479 // N0 and N1 are BUILD_VECTOR nodes with N number of EXTRACT_VECTOR 8480 // operands, where N is the size of the formed vector. 8481 // Each EXTRACT_VECTOR should have the same input vector and odd or even 8482 // index such that we have a pair wise add pattern. 8483 8484 // Grab the vector that all EXTRACT_VECTOR nodes should be referencing. 8485 if (N0->getOperand(0)->getOpcode() != ISD::EXTRACT_VECTOR_ELT) 8486 return SDValue(); 8487 SDValue Vec = N0->getOperand(0)->getOperand(0); 8488 SDNode *V = Vec.getNode(); 8489 unsigned nextIndex = 0; 8490 8491 // For each operands to the ADD which are BUILD_VECTORs, 8492 // check to see if each of their operands are an EXTRACT_VECTOR with 8493 // the same vector and appropriate index. 8494 for (unsigned i = 0, e = N0->getNumOperands(); i != e; ++i) { 8495 if (N0->getOperand(i)->getOpcode() == ISD::EXTRACT_VECTOR_ELT 8496 && N1->getOperand(i)->getOpcode() == ISD::EXTRACT_VECTOR_ELT) { 8497 8498 SDValue ExtVec0 = N0->getOperand(i); 8499 SDValue ExtVec1 = N1->getOperand(i); 8500 8501 // First operand is the vector, verify its the same. 8502 if (V != ExtVec0->getOperand(0).getNode() || 8503 V != ExtVec1->getOperand(0).getNode()) 8504 return SDValue(); 8505 8506 // Second is the constant, verify its correct. 8507 ConstantSDNode *C0 = dyn_cast<ConstantSDNode>(ExtVec0->getOperand(1)); 8508 ConstantSDNode *C1 = dyn_cast<ConstantSDNode>(ExtVec1->getOperand(1)); 8509 8510 // For the constant, we want to see all the even or all the odd. 8511 if (!C0 || !C1 || C0->getZExtValue() != nextIndex 8512 || C1->getZExtValue() != nextIndex+1) 8513 return SDValue(); 8514 8515 // Increment index. 8516 nextIndex+=2; 8517 } else 8518 return SDValue(); 8519 } 8520 8521 // Create VPADDL node. 8522 SelectionDAG &DAG = DCI.DAG; 8523 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 8524 8525 SDLoc dl(N); 8526 8527 // Build operand list. 8528 SmallVector<SDValue, 8> Ops; 8529 Ops.push_back(DAG.getConstant(Intrinsic::arm_neon_vpaddls, dl, 8530 TLI.getPointerTy(DAG.getDataLayout()))); 8531 8532 // Input is the vector. 8533 Ops.push_back(Vec); 8534 8535 // Get widened type and narrowed type. 8536 MVT widenType; 8537 unsigned numElem = VT.getVectorNumElements(); 8538 8539 EVT inputLaneType = Vec.getValueType().getVectorElementType(); 8540 switch (inputLaneType.getSimpleVT().SimpleTy) { 8541 case MVT::i8: widenType = MVT::getVectorVT(MVT::i16, numElem); break; 8542 case MVT::i16: widenType = MVT::getVectorVT(MVT::i32, numElem); break; 8543 case MVT::i32: widenType = MVT::getVectorVT(MVT::i64, numElem); break; 8544 default: 8545 llvm_unreachable("Invalid vector element type for padd optimization."); 8546 } 8547 8548 SDValue tmp = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, widenType, Ops); 8549 unsigned ExtOp = VT.bitsGT(tmp.getValueType()) ? ISD::ANY_EXTEND : ISD::TRUNCATE; 8550 return DAG.getNode(ExtOp, dl, VT, tmp); 8551 } 8552 8553 static SDValue findMUL_LOHI(SDValue V) { 8554 if (V->getOpcode() == ISD::UMUL_LOHI || 8555 V->getOpcode() == ISD::SMUL_LOHI) 8556 return V; 8557 return SDValue(); 8558 } 8559 8560 static SDValue AddCombineTo64bitMLAL(SDNode *AddcNode, 8561 TargetLowering::DAGCombinerInfo &DCI, 8562 const ARMSubtarget *Subtarget) { 8563 8564 if (Subtarget->isThumb1Only()) return SDValue(); 8565 8566 // Only perform the checks after legalize when the pattern is available. 8567 if (DCI.isBeforeLegalize()) return SDValue(); 8568 8569 // Look for multiply add opportunities. 8570 // The pattern is a ISD::UMUL_LOHI followed by two add nodes, where 8571 // each add nodes consumes a value from ISD::UMUL_LOHI and there is 8572 // a glue link from the first add to the second add. 8573 // If we find this pattern, we can replace the U/SMUL_LOHI, ADDC, and ADDE by 8574 // a S/UMLAL instruction. 8575 // UMUL_LOHI 8576 // / :lo \ :hi 8577 // / \ [no multiline comment] 8578 // loAdd -> ADDE | 8579 // \ :glue / 8580 // \ / 8581 // ADDC <- hiAdd 8582 // 8583 assert(AddcNode->getOpcode() == ISD::ADDC && "Expect an ADDC"); 8584 SDValue AddcOp0 = AddcNode->getOperand(0); 8585 SDValue AddcOp1 = AddcNode->getOperand(1); 8586 8587 // Check if the two operands are from the same mul_lohi node. 8588 if (AddcOp0.getNode() == AddcOp1.getNode()) 8589 return SDValue(); 8590 8591 assert(AddcNode->getNumValues() == 2 && 8592 AddcNode->getValueType(0) == MVT::i32 && 8593 "Expect ADDC with two result values. First: i32"); 8594 8595 // Check that we have a glued ADDC node. 8596 if (AddcNode->getValueType(1) != MVT::Glue) 8597 return SDValue(); 8598 8599 // Check that the ADDC adds the low result of the S/UMUL_LOHI. 8600 if (AddcOp0->getOpcode() != ISD::UMUL_LOHI && 8601 AddcOp0->getOpcode() != ISD::SMUL_LOHI && 8602 AddcOp1->getOpcode() != ISD::UMUL_LOHI && 8603 AddcOp1->getOpcode() != ISD::SMUL_LOHI) 8604 return SDValue(); 8605 8606 // Look for the glued ADDE. 8607 SDNode* AddeNode = AddcNode->getGluedUser(); 8608 if (!AddeNode) 8609 return SDValue(); 8610 8611 // Make sure it is really an ADDE. 8612 if (AddeNode->getOpcode() != ISD::ADDE) 8613 return SDValue(); 8614 8615 assert(AddeNode->getNumOperands() == 3 && 8616 AddeNode->getOperand(2).getValueType() == MVT::Glue && 8617 "ADDE node has the wrong inputs"); 8618 8619 // Check for the triangle shape. 8620 SDValue AddeOp0 = AddeNode->getOperand(0); 8621 SDValue AddeOp1 = AddeNode->getOperand(1); 8622 8623 // Make sure that the ADDE operands are not coming from the same node. 8624 if (AddeOp0.getNode() == AddeOp1.getNode()) 8625 return SDValue(); 8626 8627 // Find the MUL_LOHI node walking up ADDE's operands. 8628 bool IsLeftOperandMUL = false; 8629 SDValue MULOp = findMUL_LOHI(AddeOp0); 8630 if (MULOp == SDValue()) 8631 MULOp = findMUL_LOHI(AddeOp1); 8632 else 8633 IsLeftOperandMUL = true; 8634 if (MULOp == SDValue()) 8635 return SDValue(); 8636 8637 // Figure out the right opcode. 8638 unsigned Opc = MULOp->getOpcode(); 8639 unsigned FinalOpc = (Opc == ISD::SMUL_LOHI) ? ARMISD::SMLAL : ARMISD::UMLAL; 8640 8641 // Figure out the high and low input values to the MLAL node. 8642 SDValue* HiAdd = nullptr; 8643 SDValue* LoMul = nullptr; 8644 SDValue* LowAdd = nullptr; 8645 8646 // Ensure that ADDE is from high result of ISD::SMUL_LOHI. 8647 if ((AddeOp0 != MULOp.getValue(1)) && (AddeOp1 != MULOp.getValue(1))) 8648 return SDValue(); 8649 8650 if (IsLeftOperandMUL) 8651 HiAdd = &AddeOp1; 8652 else 8653 HiAdd = &AddeOp0; 8654 8655 8656 // Ensure that LoMul and LowAdd are taken from correct ISD::SMUL_LOHI node 8657 // whose low result is fed to the ADDC we are checking. 8658 8659 if (AddcOp0 == MULOp.getValue(0)) { 8660 LoMul = &AddcOp0; 8661 LowAdd = &AddcOp1; 8662 } 8663 if (AddcOp1 == MULOp.getValue(0)) { 8664 LoMul = &AddcOp1; 8665 LowAdd = &AddcOp0; 8666 } 8667 8668 if (!LoMul) 8669 return SDValue(); 8670 8671 // Create the merged node. 8672 SelectionDAG &DAG = DCI.DAG; 8673 8674 // Build operand list. 8675 SmallVector<SDValue, 8> Ops; 8676 Ops.push_back(LoMul->getOperand(0)); 8677 Ops.push_back(LoMul->getOperand(1)); 8678 Ops.push_back(*LowAdd); 8679 Ops.push_back(*HiAdd); 8680 8681 SDValue MLALNode = DAG.getNode(FinalOpc, SDLoc(AddcNode), 8682 DAG.getVTList(MVT::i32, MVT::i32), Ops); 8683 8684 // Replace the ADDs' nodes uses by the MLA node's values. 8685 SDValue HiMLALResult(MLALNode.getNode(), 1); 8686 DAG.ReplaceAllUsesOfValueWith(SDValue(AddeNode, 0), HiMLALResult); 8687 8688 SDValue LoMLALResult(MLALNode.getNode(), 0); 8689 DAG.ReplaceAllUsesOfValueWith(SDValue(AddcNode, 0), LoMLALResult); 8690 8691 // Return original node to notify the driver to stop replacing. 8692 SDValue resNode(AddcNode, 0); 8693 return resNode; 8694 } 8695 8696 /// PerformADDCCombine - Target-specific dag combine transform from 8697 /// ISD::ADDC, ISD::ADDE, and ISD::MUL_LOHI to MLAL. 8698 static SDValue PerformADDCCombine(SDNode *N, 8699 TargetLowering::DAGCombinerInfo &DCI, 8700 const ARMSubtarget *Subtarget) { 8701 8702 return AddCombineTo64bitMLAL(N, DCI, Subtarget); 8703 8704 } 8705 8706 /// PerformADDCombineWithOperands - Try DAG combinations for an ADD with 8707 /// operands N0 and N1. This is a helper for PerformADDCombine that is 8708 /// called with the default operands, and if that fails, with commuted 8709 /// operands. 8710 static SDValue PerformADDCombineWithOperands(SDNode *N, SDValue N0, SDValue N1, 8711 TargetLowering::DAGCombinerInfo &DCI, 8712 const ARMSubtarget *Subtarget){ 8713 8714 // Attempt to create vpaddl for this add. 8715 SDValue Result = AddCombineToVPADDL(N, N0, N1, DCI, Subtarget); 8716 if (Result.getNode()) 8717 return Result; 8718 8719 // fold (add (select cc, 0, c), x) -> (select cc, x, (add, x, c)) 8720 if (N0.getNode()->hasOneUse()) { 8721 SDValue Result = combineSelectAndUse(N, N0, N1, DCI); 8722 if (Result.getNode()) return Result; 8723 } 8724 return SDValue(); 8725 } 8726 8727 /// PerformADDCombine - Target-specific dag combine xforms for ISD::ADD. 8728 /// 8729 static SDValue PerformADDCombine(SDNode *N, 8730 TargetLowering::DAGCombinerInfo &DCI, 8731 const ARMSubtarget *Subtarget) { 8732 SDValue N0 = N->getOperand(0); 8733 SDValue N1 = N->getOperand(1); 8734 8735 // First try with the default operand order. 8736 SDValue Result = PerformADDCombineWithOperands(N, N0, N1, DCI, Subtarget); 8737 if (Result.getNode()) 8738 return Result; 8739 8740 // If that didn't work, try again with the operands commuted. 8741 return PerformADDCombineWithOperands(N, N1, N0, DCI, Subtarget); 8742 } 8743 8744 /// PerformSUBCombine - Target-specific dag combine xforms for ISD::SUB. 8745 /// 8746 static SDValue PerformSUBCombine(SDNode *N, 8747 TargetLowering::DAGCombinerInfo &DCI) { 8748 SDValue N0 = N->getOperand(0); 8749 SDValue N1 = N->getOperand(1); 8750 8751 // fold (sub x, (select cc, 0, c)) -> (select cc, x, (sub, x, c)) 8752 if (N1.getNode()->hasOneUse()) { 8753 SDValue Result = combineSelectAndUse(N, N1, N0, DCI); 8754 if (Result.getNode()) return Result; 8755 } 8756 8757 return SDValue(); 8758 } 8759 8760 /// PerformVMULCombine 8761 /// Distribute (A + B) * C to (A * C) + (B * C) to take advantage of the 8762 /// special multiplier accumulator forwarding. 8763 /// vmul d3, d0, d2 8764 /// vmla d3, d1, d2 8765 /// is faster than 8766 /// vadd d3, d0, d1 8767 /// vmul d3, d3, d2 8768 // However, for (A + B) * (A + B), 8769 // vadd d2, d0, d1 8770 // vmul d3, d0, d2 8771 // vmla d3, d1, d2 8772 // is slower than 8773 // vadd d2, d0, d1 8774 // vmul d3, d2, d2 8775 static SDValue PerformVMULCombine(SDNode *N, 8776 TargetLowering::DAGCombinerInfo &DCI, 8777 const ARMSubtarget *Subtarget) { 8778 if (!Subtarget->hasVMLxForwarding()) 8779 return SDValue(); 8780 8781 SelectionDAG &DAG = DCI.DAG; 8782 SDValue N0 = N->getOperand(0); 8783 SDValue N1 = N->getOperand(1); 8784 unsigned Opcode = N0.getOpcode(); 8785 if (Opcode != ISD::ADD && Opcode != ISD::SUB && 8786 Opcode != ISD::FADD && Opcode != ISD::FSUB) { 8787 Opcode = N1.getOpcode(); 8788 if (Opcode != ISD::ADD && Opcode != ISD::SUB && 8789 Opcode != ISD::FADD && Opcode != ISD::FSUB) 8790 return SDValue(); 8791 std::swap(N0, N1); 8792 } 8793 8794 if (N0 == N1) 8795 return SDValue(); 8796 8797 EVT VT = N->getValueType(0); 8798 SDLoc DL(N); 8799 SDValue N00 = N0->getOperand(0); 8800 SDValue N01 = N0->getOperand(1); 8801 return DAG.getNode(Opcode, DL, VT, 8802 DAG.getNode(ISD::MUL, DL, VT, N00, N1), 8803 DAG.getNode(ISD::MUL, DL, VT, N01, N1)); 8804 } 8805 8806 static SDValue PerformMULCombine(SDNode *N, 8807 TargetLowering::DAGCombinerInfo &DCI, 8808 const ARMSubtarget *Subtarget) { 8809 SelectionDAG &DAG = DCI.DAG; 8810 8811 if (Subtarget->isThumb1Only()) 8812 return SDValue(); 8813 8814 if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer()) 8815 return SDValue(); 8816 8817 EVT VT = N->getValueType(0); 8818 if (VT.is64BitVector() || VT.is128BitVector()) 8819 return PerformVMULCombine(N, DCI, Subtarget); 8820 if (VT != MVT::i32) 8821 return SDValue(); 8822 8823 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(1)); 8824 if (!C) 8825 return SDValue(); 8826 8827 int64_t MulAmt = C->getSExtValue(); 8828 unsigned ShiftAmt = countTrailingZeros<uint64_t>(MulAmt); 8829 8830 ShiftAmt = ShiftAmt & (32 - 1); 8831 SDValue V = N->getOperand(0); 8832 SDLoc DL(N); 8833 8834 SDValue Res; 8835 MulAmt >>= ShiftAmt; 8836 8837 if (MulAmt >= 0) { 8838 if (isPowerOf2_32(MulAmt - 1)) { 8839 // (mul x, 2^N + 1) => (add (shl x, N), x) 8840 Res = DAG.getNode(ISD::ADD, DL, VT, 8841 V, 8842 DAG.getNode(ISD::SHL, DL, VT, 8843 V, 8844 DAG.getConstant(Log2_32(MulAmt - 1), DL, 8845 MVT::i32))); 8846 } else if (isPowerOf2_32(MulAmt + 1)) { 8847 // (mul x, 2^N - 1) => (sub (shl x, N), x) 8848 Res = DAG.getNode(ISD::SUB, DL, VT, 8849 DAG.getNode(ISD::SHL, DL, VT, 8850 V, 8851 DAG.getConstant(Log2_32(MulAmt + 1), DL, 8852 MVT::i32)), 8853 V); 8854 } else 8855 return SDValue(); 8856 } else { 8857 uint64_t MulAmtAbs = -MulAmt; 8858 if (isPowerOf2_32(MulAmtAbs + 1)) { 8859 // (mul x, -(2^N - 1)) => (sub x, (shl x, N)) 8860 Res = DAG.getNode(ISD::SUB, DL, VT, 8861 V, 8862 DAG.getNode(ISD::SHL, DL, VT, 8863 V, 8864 DAG.getConstant(Log2_32(MulAmtAbs + 1), DL, 8865 MVT::i32))); 8866 } else if (isPowerOf2_32(MulAmtAbs - 1)) { 8867 // (mul x, -(2^N + 1)) => - (add (shl x, N), x) 8868 Res = DAG.getNode(ISD::ADD, DL, VT, 8869 V, 8870 DAG.getNode(ISD::SHL, DL, VT, 8871 V, 8872 DAG.getConstant(Log2_32(MulAmtAbs - 1), DL, 8873 MVT::i32))); 8874 Res = DAG.getNode(ISD::SUB, DL, VT, 8875 DAG.getConstant(0, DL, MVT::i32), Res); 8876 8877 } else 8878 return SDValue(); 8879 } 8880 8881 if (ShiftAmt != 0) 8882 Res = DAG.getNode(ISD::SHL, DL, VT, 8883 Res, DAG.getConstant(ShiftAmt, DL, MVT::i32)); 8884 8885 // Do not add new nodes to DAG combiner worklist. 8886 DCI.CombineTo(N, Res, false); 8887 return SDValue(); 8888 } 8889 8890 static SDValue PerformANDCombine(SDNode *N, 8891 TargetLowering::DAGCombinerInfo &DCI, 8892 const ARMSubtarget *Subtarget) { 8893 8894 // Attempt to use immediate-form VBIC 8895 BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(N->getOperand(1)); 8896 SDLoc dl(N); 8897 EVT VT = N->getValueType(0); 8898 SelectionDAG &DAG = DCI.DAG; 8899 8900 if(!DAG.getTargetLoweringInfo().isTypeLegal(VT)) 8901 return SDValue(); 8902 8903 APInt SplatBits, SplatUndef; 8904 unsigned SplatBitSize; 8905 bool HasAnyUndefs; 8906 if (BVN && 8907 BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs)) { 8908 if (SplatBitSize <= 64) { 8909 EVT VbicVT; 8910 SDValue Val = isNEONModifiedImm((~SplatBits).getZExtValue(), 8911 SplatUndef.getZExtValue(), SplatBitSize, 8912 DAG, dl, VbicVT, VT.is128BitVector(), 8913 OtherModImm); 8914 if (Val.getNode()) { 8915 SDValue Input = 8916 DAG.getNode(ISD::BITCAST, dl, VbicVT, N->getOperand(0)); 8917 SDValue Vbic = DAG.getNode(ARMISD::VBICIMM, dl, VbicVT, Input, Val); 8918 return DAG.getNode(ISD::BITCAST, dl, VT, Vbic); 8919 } 8920 } 8921 } 8922 8923 if (!Subtarget->isThumb1Only()) { 8924 // fold (and (select cc, -1, c), x) -> (select cc, x, (and, x, c)) 8925 SDValue Result = combineSelectAndUseCommutative(N, true, DCI); 8926 if (Result.getNode()) 8927 return Result; 8928 } 8929 8930 return SDValue(); 8931 } 8932 8933 /// PerformORCombine - Target-specific dag combine xforms for ISD::OR 8934 static SDValue PerformORCombine(SDNode *N, 8935 TargetLowering::DAGCombinerInfo &DCI, 8936 const ARMSubtarget *Subtarget) { 8937 // Attempt to use immediate-form VORR 8938 BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(N->getOperand(1)); 8939 SDLoc dl(N); 8940 EVT VT = N->getValueType(0); 8941 SelectionDAG &DAG = DCI.DAG; 8942 8943 if(!DAG.getTargetLoweringInfo().isTypeLegal(VT)) 8944 return SDValue(); 8945 8946 APInt SplatBits, SplatUndef; 8947 unsigned SplatBitSize; 8948 bool HasAnyUndefs; 8949 if (BVN && Subtarget->hasNEON() && 8950 BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs)) { 8951 if (SplatBitSize <= 64) { 8952 EVT VorrVT; 8953 SDValue Val = isNEONModifiedImm(SplatBits.getZExtValue(), 8954 SplatUndef.getZExtValue(), SplatBitSize, 8955 DAG, dl, VorrVT, VT.is128BitVector(), 8956 OtherModImm); 8957 if (Val.getNode()) { 8958 SDValue Input = 8959 DAG.getNode(ISD::BITCAST, dl, VorrVT, N->getOperand(0)); 8960 SDValue Vorr = DAG.getNode(ARMISD::VORRIMM, dl, VorrVT, Input, Val); 8961 return DAG.getNode(ISD::BITCAST, dl, VT, Vorr); 8962 } 8963 } 8964 } 8965 8966 if (!Subtarget->isThumb1Only()) { 8967 // fold (or (select cc, 0, c), x) -> (select cc, x, (or, x, c)) 8968 SDValue Result = combineSelectAndUseCommutative(N, false, DCI); 8969 if (Result.getNode()) 8970 return Result; 8971 } 8972 8973 // The code below optimizes (or (and X, Y), Z). 8974 // The AND operand needs to have a single user to make these optimizations 8975 // profitable. 8976 SDValue N0 = N->getOperand(0); 8977 if (N0.getOpcode() != ISD::AND || !N0.hasOneUse()) 8978 return SDValue(); 8979 SDValue N1 = N->getOperand(1); 8980 8981 // (or (and B, A), (and C, ~A)) => (VBSL A, B, C) when A is a constant. 8982 if (Subtarget->hasNEON() && N1.getOpcode() == ISD::AND && VT.isVector() && 8983 DAG.getTargetLoweringInfo().isTypeLegal(VT)) { 8984 APInt SplatUndef; 8985 unsigned SplatBitSize; 8986 bool HasAnyUndefs; 8987 8988 APInt SplatBits0, SplatBits1; 8989 BuildVectorSDNode *BVN0 = dyn_cast<BuildVectorSDNode>(N0->getOperand(1)); 8990 BuildVectorSDNode *BVN1 = dyn_cast<BuildVectorSDNode>(N1->getOperand(1)); 8991 // Ensure that the second operand of both ands are constants 8992 if (BVN0 && BVN0->isConstantSplat(SplatBits0, SplatUndef, SplatBitSize, 8993 HasAnyUndefs) && !HasAnyUndefs) { 8994 if (BVN1 && BVN1->isConstantSplat(SplatBits1, SplatUndef, SplatBitSize, 8995 HasAnyUndefs) && !HasAnyUndefs) { 8996 // Ensure that the bit width of the constants are the same and that 8997 // the splat arguments are logical inverses as per the pattern we 8998 // are trying to simplify. 8999 if (SplatBits0.getBitWidth() == SplatBits1.getBitWidth() && 9000 SplatBits0 == ~SplatBits1) { 9001 // Canonicalize the vector type to make instruction selection 9002 // simpler. 9003 EVT CanonicalVT = VT.is128BitVector() ? MVT::v4i32 : MVT::v2i32; 9004 SDValue Result = DAG.getNode(ARMISD::VBSL, dl, CanonicalVT, 9005 N0->getOperand(1), 9006 N0->getOperand(0), 9007 N1->getOperand(0)); 9008 return DAG.getNode(ISD::BITCAST, dl, VT, Result); 9009 } 9010 } 9011 } 9012 } 9013 9014 // Try to use the ARM/Thumb2 BFI (bitfield insert) instruction when 9015 // reasonable. 9016 9017 // BFI is only available on V6T2+ 9018 if (Subtarget->isThumb1Only() || !Subtarget->hasV6T2Ops()) 9019 return SDValue(); 9020 9021 SDLoc DL(N); 9022 // 1) or (and A, mask), val => ARMbfi A, val, mask 9023 // iff (val & mask) == val 9024 // 9025 // 2) or (and A, mask), (and B, mask2) => ARMbfi A, (lsr B, amt), mask 9026 // 2a) iff isBitFieldInvertedMask(mask) && isBitFieldInvertedMask(~mask2) 9027 // && mask == ~mask2 9028 // 2b) iff isBitFieldInvertedMask(~mask) && isBitFieldInvertedMask(mask2) 9029 // && ~mask == mask2 9030 // (i.e., copy a bitfield value into another bitfield of the same width) 9031 9032 if (VT != MVT::i32) 9033 return SDValue(); 9034 9035 SDValue N00 = N0.getOperand(0); 9036 9037 // The value and the mask need to be constants so we can verify this is 9038 // actually a bitfield set. If the mask is 0xffff, we can do better 9039 // via a movt instruction, so don't use BFI in that case. 9040 SDValue MaskOp = N0.getOperand(1); 9041 ConstantSDNode *MaskC = dyn_cast<ConstantSDNode>(MaskOp); 9042 if (!MaskC) 9043 return SDValue(); 9044 unsigned Mask = MaskC->getZExtValue(); 9045 if (Mask == 0xffff) 9046 return SDValue(); 9047 SDValue Res; 9048 // Case (1): or (and A, mask), val => ARMbfi A, val, mask 9049 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1); 9050 if (N1C) { 9051 unsigned Val = N1C->getZExtValue(); 9052 if ((Val & ~Mask) != Val) 9053 return SDValue(); 9054 9055 if (ARM::isBitFieldInvertedMask(Mask)) { 9056 Val >>= countTrailingZeros(~Mask); 9057 9058 Res = DAG.getNode(ARMISD::BFI, DL, VT, N00, 9059 DAG.getConstant(Val, DL, MVT::i32), 9060 DAG.getConstant(Mask, DL, MVT::i32)); 9061 9062 // Do not add new nodes to DAG combiner worklist. 9063 DCI.CombineTo(N, Res, false); 9064 return SDValue(); 9065 } 9066 } else if (N1.getOpcode() == ISD::AND) { 9067 // case (2) or (and A, mask), (and B, mask2) => ARMbfi A, (lsr B, amt), mask 9068 ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1)); 9069 if (!N11C) 9070 return SDValue(); 9071 unsigned Mask2 = N11C->getZExtValue(); 9072 9073 // Mask and ~Mask2 (or reverse) must be equivalent for the BFI pattern 9074 // as is to match. 9075 if (ARM::isBitFieldInvertedMask(Mask) && 9076 (Mask == ~Mask2)) { 9077 // The pack halfword instruction works better for masks that fit it, 9078 // so use that when it's available. 9079 if (Subtarget->hasT2ExtractPack() && 9080 (Mask == 0xffff || Mask == 0xffff0000)) 9081 return SDValue(); 9082 // 2a 9083 unsigned amt = countTrailingZeros(Mask2); 9084 Res = DAG.getNode(ISD::SRL, DL, VT, N1.getOperand(0), 9085 DAG.getConstant(amt, DL, MVT::i32)); 9086 Res = DAG.getNode(ARMISD::BFI, DL, VT, N00, Res, 9087 DAG.getConstant(Mask, DL, MVT::i32)); 9088 // Do not add new nodes to DAG combiner worklist. 9089 DCI.CombineTo(N, Res, false); 9090 return SDValue(); 9091 } else if (ARM::isBitFieldInvertedMask(~Mask) && 9092 (~Mask == Mask2)) { 9093 // The pack halfword instruction works better for masks that fit it, 9094 // so use that when it's available. 9095 if (Subtarget->hasT2ExtractPack() && 9096 (Mask2 == 0xffff || Mask2 == 0xffff0000)) 9097 return SDValue(); 9098 // 2b 9099 unsigned lsb = countTrailingZeros(Mask); 9100 Res = DAG.getNode(ISD::SRL, DL, VT, N00, 9101 DAG.getConstant(lsb, DL, MVT::i32)); 9102 Res = DAG.getNode(ARMISD::BFI, DL, VT, N1.getOperand(0), Res, 9103 DAG.getConstant(Mask2, DL, MVT::i32)); 9104 // Do not add new nodes to DAG combiner worklist. 9105 DCI.CombineTo(N, Res, false); 9106 return SDValue(); 9107 } 9108 } 9109 9110 if (DAG.MaskedValueIsZero(N1, MaskC->getAPIntValue()) && 9111 N00.getOpcode() == ISD::SHL && isa<ConstantSDNode>(N00.getOperand(1)) && 9112 ARM::isBitFieldInvertedMask(~Mask)) { 9113 // Case (3): or (and (shl A, #shamt), mask), B => ARMbfi B, A, ~mask 9114 // where lsb(mask) == #shamt and masked bits of B are known zero. 9115 SDValue ShAmt = N00.getOperand(1); 9116 unsigned ShAmtC = cast<ConstantSDNode>(ShAmt)->getZExtValue(); 9117 unsigned LSB = countTrailingZeros(Mask); 9118 if (ShAmtC != LSB) 9119 return SDValue(); 9120 9121 Res = DAG.getNode(ARMISD::BFI, DL, VT, N1, N00.getOperand(0), 9122 DAG.getConstant(~Mask, DL, MVT::i32)); 9123 9124 // Do not add new nodes to DAG combiner worklist. 9125 DCI.CombineTo(N, Res, false); 9126 } 9127 9128 return SDValue(); 9129 } 9130 9131 static SDValue PerformXORCombine(SDNode *N, 9132 TargetLowering::DAGCombinerInfo &DCI, 9133 const ARMSubtarget *Subtarget) { 9134 EVT VT = N->getValueType(0); 9135 SelectionDAG &DAG = DCI.DAG; 9136 9137 if(!DAG.getTargetLoweringInfo().isTypeLegal(VT)) 9138 return SDValue(); 9139 9140 if (!Subtarget->isThumb1Only()) { 9141 // fold (xor (select cc, 0, c), x) -> (select cc, x, (xor, x, c)) 9142 SDValue Result = combineSelectAndUseCommutative(N, false, DCI); 9143 if (Result.getNode()) 9144 return Result; 9145 } 9146 9147 return SDValue(); 9148 } 9149 9150 // ParseBFI - given a BFI instruction in N, extract the "from" value (Rn) and return it, 9151 // and fill in FromMask and ToMask with (consecutive) bits in "from" to be extracted and 9152 // their position in "to" (Rd). 9153 static SDValue ParseBFI(SDNode *N, APInt &ToMask, APInt &FromMask) { 9154 assert(N->getOpcode() == ARMISD::BFI); 9155 9156 SDValue From = N->getOperand(1); 9157 ToMask = ~cast<ConstantSDNode>(N->getOperand(2))->getAPIntValue(); 9158 FromMask = APInt::getLowBitsSet(ToMask.getBitWidth(), ToMask.countPopulation()); 9159 9160 // If the Base came from a SHR #C, we can deduce that it is really testing bit 9161 // #C in the base of the SHR. 9162 if (From->getOpcode() == ISD::SRL && 9163 isa<ConstantSDNode>(From->getOperand(1))) { 9164 APInt Shift = cast<ConstantSDNode>(From->getOperand(1))->getAPIntValue(); 9165 assert(Shift.getLimitedValue() < 32 && "Shift too large!"); 9166 FromMask <<= Shift.getLimitedValue(31); 9167 From = From->getOperand(0); 9168 } 9169 9170 return From; 9171 } 9172 9173 // If A and B contain one contiguous set of bits, does A | B == A . B? 9174 // 9175 // Neither A nor B must be zero. 9176 static bool BitsProperlyConcatenate(const APInt &A, const APInt &B) { 9177 unsigned LastActiveBitInA = A.countTrailingZeros(); 9178 unsigned FirstActiveBitInB = B.getBitWidth() - B.countLeadingZeros() - 1; 9179 return LastActiveBitInA - 1 == FirstActiveBitInB; 9180 } 9181 9182 static SDValue FindBFIToCombineWith(SDNode *N) { 9183 // We have a BFI in N. Follow a possible chain of BFIs and find a BFI it can combine with, 9184 // if one exists. 9185 APInt ToMask, FromMask; 9186 SDValue From = ParseBFI(N, ToMask, FromMask); 9187 SDValue To = N->getOperand(0); 9188 9189 // Now check for a compatible BFI to merge with. We can pass through BFIs that 9190 // aren't compatible, but not if they set the same bit in their destination as 9191 // we do (or that of any BFI we're going to combine with). 9192 SDValue V = To; 9193 APInt CombinedToMask = ToMask; 9194 while (V.getOpcode() == ARMISD::BFI) { 9195 APInt NewToMask, NewFromMask; 9196 SDValue NewFrom = ParseBFI(V.getNode(), NewToMask, NewFromMask); 9197 if (NewFrom != From) { 9198 // This BFI has a different base. Keep going. 9199 CombinedToMask |= NewToMask; 9200 V = V.getOperand(0); 9201 continue; 9202 } 9203 9204 // Do the written bits conflict with any we've seen so far? 9205 if ((NewToMask & CombinedToMask).getBoolValue()) 9206 // Conflicting bits - bail out because going further is unsafe. 9207 return SDValue(); 9208 9209 // Are the new bits contiguous when combined with the old bits? 9210 if (BitsProperlyConcatenate(ToMask, NewToMask) && 9211 BitsProperlyConcatenate(FromMask, NewFromMask)) 9212 return V; 9213 if (BitsProperlyConcatenate(NewToMask, ToMask) && 9214 BitsProperlyConcatenate(NewFromMask, FromMask)) 9215 return V; 9216 9217 // We've seen a write to some bits, so track it. 9218 CombinedToMask |= NewToMask; 9219 // Keep going... 9220 V = V.getOperand(0); 9221 } 9222 9223 return SDValue(); 9224 } 9225 9226 static SDValue PerformBFICombine(SDNode *N, 9227 TargetLowering::DAGCombinerInfo &DCI) { 9228 SDValue N1 = N->getOperand(1); 9229 if (N1.getOpcode() == ISD::AND) { 9230 // (bfi A, (and B, Mask1), Mask2) -> (bfi A, B, Mask2) iff 9231 // the bits being cleared by the AND are not demanded by the BFI. 9232 ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1)); 9233 if (!N11C) 9234 return SDValue(); 9235 unsigned InvMask = cast<ConstantSDNode>(N->getOperand(2))->getZExtValue(); 9236 unsigned LSB = countTrailingZeros(~InvMask); 9237 unsigned Width = (32 - countLeadingZeros(~InvMask)) - LSB; 9238 assert(Width < 9239 static_cast<unsigned>(std::numeric_limits<unsigned>::digits) && 9240 "undefined behavior"); 9241 unsigned Mask = (1u << Width) - 1; 9242 unsigned Mask2 = N11C->getZExtValue(); 9243 if ((Mask & (~Mask2)) == 0) 9244 return DCI.DAG.getNode(ARMISD::BFI, SDLoc(N), N->getValueType(0), 9245 N->getOperand(0), N1.getOperand(0), 9246 N->getOperand(2)); 9247 } else if (N->getOperand(0).getOpcode() == ARMISD::BFI) { 9248 // We have a BFI of a BFI. Walk up the BFI chain to see how long it goes. 9249 // Keep track of any consecutive bits set that all come from the same base 9250 // value. We can combine these together into a single BFI. 9251 SDValue CombineBFI = FindBFIToCombineWith(N); 9252 if (CombineBFI == SDValue()) 9253 return SDValue(); 9254 9255 // We've found a BFI. 9256 APInt ToMask1, FromMask1; 9257 SDValue From1 = ParseBFI(N, ToMask1, FromMask1); 9258 9259 APInt ToMask2, FromMask2; 9260 SDValue From2 = ParseBFI(CombineBFI.getNode(), ToMask2, FromMask2); 9261 assert(From1 == From2); 9262 (void)From2; 9263 9264 // First, unlink CombineBFI. 9265 DCI.DAG.ReplaceAllUsesWith(CombineBFI, CombineBFI.getOperand(0)); 9266 // Then create a new BFI, combining the two together. 9267 APInt NewFromMask = FromMask1 | FromMask2; 9268 APInt NewToMask = ToMask1 | ToMask2; 9269 9270 EVT VT = N->getValueType(0); 9271 SDLoc dl(N); 9272 9273 if (NewFromMask[0] == 0) 9274 From1 = DCI.DAG.getNode( 9275 ISD::SRL, dl, VT, From1, 9276 DCI.DAG.getConstant(NewFromMask.countTrailingZeros(), dl, VT)); 9277 return DCI.DAG.getNode(ARMISD::BFI, dl, VT, N->getOperand(0), From1, 9278 DCI.DAG.getConstant(~NewToMask, dl, VT)); 9279 } 9280 return SDValue(); 9281 } 9282 9283 /// PerformVMOVRRDCombine - Target-specific dag combine xforms for 9284 /// ARMISD::VMOVRRD. 9285 static SDValue PerformVMOVRRDCombine(SDNode *N, 9286 TargetLowering::DAGCombinerInfo &DCI, 9287 const ARMSubtarget *Subtarget) { 9288 // vmovrrd(vmovdrr x, y) -> x,y 9289 SDValue InDouble = N->getOperand(0); 9290 if (InDouble.getOpcode() == ARMISD::VMOVDRR && !Subtarget->isFPOnlySP()) 9291 return DCI.CombineTo(N, InDouble.getOperand(0), InDouble.getOperand(1)); 9292 9293 // vmovrrd(load f64) -> (load i32), (load i32) 9294 SDNode *InNode = InDouble.getNode(); 9295 if (ISD::isNormalLoad(InNode) && InNode->hasOneUse() && 9296 InNode->getValueType(0) == MVT::f64 && 9297 InNode->getOperand(1).getOpcode() == ISD::FrameIndex && 9298 !cast<LoadSDNode>(InNode)->isVolatile()) { 9299 // TODO: Should this be done for non-FrameIndex operands? 9300 LoadSDNode *LD = cast<LoadSDNode>(InNode); 9301 9302 SelectionDAG &DAG = DCI.DAG; 9303 SDLoc DL(LD); 9304 SDValue BasePtr = LD->getBasePtr(); 9305 SDValue NewLD1 = DAG.getLoad(MVT::i32, DL, LD->getChain(), BasePtr, 9306 LD->getPointerInfo(), LD->isVolatile(), 9307 LD->isNonTemporal(), LD->isInvariant(), 9308 LD->getAlignment()); 9309 9310 SDValue OffsetPtr = DAG.getNode(ISD::ADD, DL, MVT::i32, BasePtr, 9311 DAG.getConstant(4, DL, MVT::i32)); 9312 SDValue NewLD2 = DAG.getLoad(MVT::i32, DL, NewLD1.getValue(1), OffsetPtr, 9313 LD->getPointerInfo(), LD->isVolatile(), 9314 LD->isNonTemporal(), LD->isInvariant(), 9315 std::min(4U, LD->getAlignment() / 2)); 9316 9317 DAG.ReplaceAllUsesOfValueWith(SDValue(LD, 1), NewLD2.getValue(1)); 9318 if (DCI.DAG.getDataLayout().isBigEndian()) 9319 std::swap (NewLD1, NewLD2); 9320 SDValue Result = DCI.CombineTo(N, NewLD1, NewLD2); 9321 return Result; 9322 } 9323 9324 return SDValue(); 9325 } 9326 9327 /// PerformVMOVDRRCombine - Target-specific dag combine xforms for 9328 /// ARMISD::VMOVDRR. This is also used for BUILD_VECTORs with 2 operands. 9329 static SDValue PerformVMOVDRRCombine(SDNode *N, SelectionDAG &DAG) { 9330 // N=vmovrrd(X); vmovdrr(N:0, N:1) -> bit_convert(X) 9331 SDValue Op0 = N->getOperand(0); 9332 SDValue Op1 = N->getOperand(1); 9333 if (Op0.getOpcode() == ISD::BITCAST) 9334 Op0 = Op0.getOperand(0); 9335 if (Op1.getOpcode() == ISD::BITCAST) 9336 Op1 = Op1.getOperand(0); 9337 if (Op0.getOpcode() == ARMISD::VMOVRRD && 9338 Op0.getNode() == Op1.getNode() && 9339 Op0.getResNo() == 0 && Op1.getResNo() == 1) 9340 return DAG.getNode(ISD::BITCAST, SDLoc(N), 9341 N->getValueType(0), Op0.getOperand(0)); 9342 return SDValue(); 9343 } 9344 9345 /// hasNormalLoadOperand - Check if any of the operands of a BUILD_VECTOR node 9346 /// are normal, non-volatile loads. If so, it is profitable to bitcast an 9347 /// i64 vector to have f64 elements, since the value can then be loaded 9348 /// directly into a VFP register. 9349 static bool hasNormalLoadOperand(SDNode *N) { 9350 unsigned NumElts = N->getValueType(0).getVectorNumElements(); 9351 for (unsigned i = 0; i < NumElts; ++i) { 9352 SDNode *Elt = N->getOperand(i).getNode(); 9353 if (ISD::isNormalLoad(Elt) && !cast<LoadSDNode>(Elt)->isVolatile()) 9354 return true; 9355 } 9356 return false; 9357 } 9358 9359 /// PerformBUILD_VECTORCombine - Target-specific dag combine xforms for 9360 /// ISD::BUILD_VECTOR. 9361 static SDValue PerformBUILD_VECTORCombine(SDNode *N, 9362 TargetLowering::DAGCombinerInfo &DCI, 9363 const ARMSubtarget *Subtarget) { 9364 // build_vector(N=ARMISD::VMOVRRD(X), N:1) -> bit_convert(X): 9365 // VMOVRRD is introduced when legalizing i64 types. It forces the i64 value 9366 // into a pair of GPRs, which is fine when the value is used as a scalar, 9367 // but if the i64 value is converted to a vector, we need to undo the VMOVRRD. 9368 SelectionDAG &DAG = DCI.DAG; 9369 if (N->getNumOperands() == 2) { 9370 SDValue RV = PerformVMOVDRRCombine(N, DAG); 9371 if (RV.getNode()) 9372 return RV; 9373 } 9374 9375 // Load i64 elements as f64 values so that type legalization does not split 9376 // them up into i32 values. 9377 EVT VT = N->getValueType(0); 9378 if (VT.getVectorElementType() != MVT::i64 || !hasNormalLoadOperand(N)) 9379 return SDValue(); 9380 SDLoc dl(N); 9381 SmallVector<SDValue, 8> Ops; 9382 unsigned NumElts = VT.getVectorNumElements(); 9383 for (unsigned i = 0; i < NumElts; ++i) { 9384 SDValue V = DAG.getNode(ISD::BITCAST, dl, MVT::f64, N->getOperand(i)); 9385 Ops.push_back(V); 9386 // Make the DAGCombiner fold the bitcast. 9387 DCI.AddToWorklist(V.getNode()); 9388 } 9389 EVT FloatVT = EVT::getVectorVT(*DAG.getContext(), MVT::f64, NumElts); 9390 SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, FloatVT, Ops); 9391 return DAG.getNode(ISD::BITCAST, dl, VT, BV); 9392 } 9393 9394 /// \brief Target-specific dag combine xforms for ARMISD::BUILD_VECTOR. 9395 static SDValue 9396 PerformARMBUILD_VECTORCombine(SDNode *N, TargetLowering::DAGCombinerInfo &DCI) { 9397 // ARMISD::BUILD_VECTOR is introduced when legalizing ISD::BUILD_VECTOR. 9398 // At that time, we may have inserted bitcasts from integer to float. 9399 // If these bitcasts have survived DAGCombine, change the lowering of this 9400 // BUILD_VECTOR in something more vector friendly, i.e., that does not 9401 // force to use floating point types. 9402 9403 // Make sure we can change the type of the vector. 9404 // This is possible iff: 9405 // 1. The vector is only used in a bitcast to a integer type. I.e., 9406 // 1.1. Vector is used only once. 9407 // 1.2. Use is a bit convert to an integer type. 9408 // 2. The size of its operands are 32-bits (64-bits are not legal). 9409 EVT VT = N->getValueType(0); 9410 EVT EltVT = VT.getVectorElementType(); 9411 9412 // Check 1.1. and 2. 9413 if (EltVT.getSizeInBits() != 32 || !N->hasOneUse()) 9414 return SDValue(); 9415 9416 // By construction, the input type must be float. 9417 assert(EltVT == MVT::f32 && "Unexpected type!"); 9418 9419 // Check 1.2. 9420 SDNode *Use = *N->use_begin(); 9421 if (Use->getOpcode() != ISD::BITCAST || 9422 Use->getValueType(0).isFloatingPoint()) 9423 return SDValue(); 9424 9425 // Check profitability. 9426 // Model is, if more than half of the relevant operands are bitcast from 9427 // i32, turn the build_vector into a sequence of insert_vector_elt. 9428 // Relevant operands are everything that is not statically 9429 // (i.e., at compile time) bitcasted. 9430 unsigned NumOfBitCastedElts = 0; 9431 unsigned NumElts = VT.getVectorNumElements(); 9432 unsigned NumOfRelevantElts = NumElts; 9433 for (unsigned Idx = 0; Idx < NumElts; ++Idx) { 9434 SDValue Elt = N->getOperand(Idx); 9435 if (Elt->getOpcode() == ISD::BITCAST) { 9436 // Assume only bit cast to i32 will go away. 9437 if (Elt->getOperand(0).getValueType() == MVT::i32) 9438 ++NumOfBitCastedElts; 9439 } else if (Elt.getOpcode() == ISD::UNDEF || isa<ConstantSDNode>(Elt)) 9440 // Constants are statically casted, thus do not count them as 9441 // relevant operands. 9442 --NumOfRelevantElts; 9443 } 9444 9445 // Check if more than half of the elements require a non-free bitcast. 9446 if (NumOfBitCastedElts <= NumOfRelevantElts / 2) 9447 return SDValue(); 9448 9449 SelectionDAG &DAG = DCI.DAG; 9450 // Create the new vector type. 9451 EVT VecVT = EVT::getVectorVT(*DAG.getContext(), MVT::i32, NumElts); 9452 // Check if the type is legal. 9453 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 9454 if (!TLI.isTypeLegal(VecVT)) 9455 return SDValue(); 9456 9457 // Combine: 9458 // ARMISD::BUILD_VECTOR E1, E2, ..., EN. 9459 // => BITCAST INSERT_VECTOR_ELT 9460 // (INSERT_VECTOR_ELT (...), (BITCAST EN-1), N-1), 9461 // (BITCAST EN), N. 9462 SDValue Vec = DAG.getUNDEF(VecVT); 9463 SDLoc dl(N); 9464 for (unsigned Idx = 0 ; Idx < NumElts; ++Idx) { 9465 SDValue V = N->getOperand(Idx); 9466 if (V.getOpcode() == ISD::UNDEF) 9467 continue; 9468 if (V.getOpcode() == ISD::BITCAST && 9469 V->getOperand(0).getValueType() == MVT::i32) 9470 // Fold obvious case. 9471 V = V.getOperand(0); 9472 else { 9473 V = DAG.getNode(ISD::BITCAST, SDLoc(V), MVT::i32, V); 9474 // Make the DAGCombiner fold the bitcasts. 9475 DCI.AddToWorklist(V.getNode()); 9476 } 9477 SDValue LaneIdx = DAG.getConstant(Idx, dl, MVT::i32); 9478 Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VecVT, Vec, V, LaneIdx); 9479 } 9480 Vec = DAG.getNode(ISD::BITCAST, dl, VT, Vec); 9481 // Make the DAGCombiner fold the bitcasts. 9482 DCI.AddToWorklist(Vec.getNode()); 9483 return Vec; 9484 } 9485 9486 /// PerformInsertEltCombine - Target-specific dag combine xforms for 9487 /// ISD::INSERT_VECTOR_ELT. 9488 static SDValue PerformInsertEltCombine(SDNode *N, 9489 TargetLowering::DAGCombinerInfo &DCI) { 9490 // Bitcast an i64 load inserted into a vector to f64. 9491 // Otherwise, the i64 value will be legalized to a pair of i32 values. 9492 EVT VT = N->getValueType(0); 9493 SDNode *Elt = N->getOperand(1).getNode(); 9494 if (VT.getVectorElementType() != MVT::i64 || 9495 !ISD::isNormalLoad(Elt) || cast<LoadSDNode>(Elt)->isVolatile()) 9496 return SDValue(); 9497 9498 SelectionDAG &DAG = DCI.DAG; 9499 SDLoc dl(N); 9500 EVT FloatVT = EVT::getVectorVT(*DAG.getContext(), MVT::f64, 9501 VT.getVectorNumElements()); 9502 SDValue Vec = DAG.getNode(ISD::BITCAST, dl, FloatVT, N->getOperand(0)); 9503 SDValue V = DAG.getNode(ISD::BITCAST, dl, MVT::f64, N->getOperand(1)); 9504 // Make the DAGCombiner fold the bitcasts. 9505 DCI.AddToWorklist(Vec.getNode()); 9506 DCI.AddToWorklist(V.getNode()); 9507 SDValue InsElt = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, FloatVT, 9508 Vec, V, N->getOperand(2)); 9509 return DAG.getNode(ISD::BITCAST, dl, VT, InsElt); 9510 } 9511 9512 /// PerformVECTOR_SHUFFLECombine - Target-specific dag combine xforms for 9513 /// ISD::VECTOR_SHUFFLE. 9514 static SDValue PerformVECTOR_SHUFFLECombine(SDNode *N, SelectionDAG &DAG) { 9515 // The LLVM shufflevector instruction does not require the shuffle mask 9516 // length to match the operand vector length, but ISD::VECTOR_SHUFFLE does 9517 // have that requirement. When translating to ISD::VECTOR_SHUFFLE, if the 9518 // operands do not match the mask length, they are extended by concatenating 9519 // them with undef vectors. That is probably the right thing for other 9520 // targets, but for NEON it is better to concatenate two double-register 9521 // size vector operands into a single quad-register size vector. Do that 9522 // transformation here: 9523 // shuffle(concat(v1, undef), concat(v2, undef)) -> 9524 // shuffle(concat(v1, v2), undef) 9525 SDValue Op0 = N->getOperand(0); 9526 SDValue Op1 = N->getOperand(1); 9527 if (Op0.getOpcode() != ISD::CONCAT_VECTORS || 9528 Op1.getOpcode() != ISD::CONCAT_VECTORS || 9529 Op0.getNumOperands() != 2 || 9530 Op1.getNumOperands() != 2) 9531 return SDValue(); 9532 SDValue Concat0Op1 = Op0.getOperand(1); 9533 SDValue Concat1Op1 = Op1.getOperand(1); 9534 if (Concat0Op1.getOpcode() != ISD::UNDEF || 9535 Concat1Op1.getOpcode() != ISD::UNDEF) 9536 return SDValue(); 9537 // Skip the transformation if any of the types are illegal. 9538 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 9539 EVT VT = N->getValueType(0); 9540 if (!TLI.isTypeLegal(VT) || 9541 !TLI.isTypeLegal(Concat0Op1.getValueType()) || 9542 !TLI.isTypeLegal(Concat1Op1.getValueType())) 9543 return SDValue(); 9544 9545 SDValue NewConcat = DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT, 9546 Op0.getOperand(0), Op1.getOperand(0)); 9547 // Translate the shuffle mask. 9548 SmallVector<int, 16> NewMask; 9549 unsigned NumElts = VT.getVectorNumElements(); 9550 unsigned HalfElts = NumElts/2; 9551 ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N); 9552 for (unsigned n = 0; n < NumElts; ++n) { 9553 int MaskElt = SVN->getMaskElt(n); 9554 int NewElt = -1; 9555 if (MaskElt < (int)HalfElts) 9556 NewElt = MaskElt; 9557 else if (MaskElt >= (int)NumElts && MaskElt < (int)(NumElts + HalfElts)) 9558 NewElt = HalfElts + MaskElt - NumElts; 9559 NewMask.push_back(NewElt); 9560 } 9561 return DAG.getVectorShuffle(VT, SDLoc(N), NewConcat, 9562 DAG.getUNDEF(VT), NewMask.data()); 9563 } 9564 9565 /// CombineBaseUpdate - Target-specific DAG combine function for VLDDUP, 9566 /// NEON load/store intrinsics, and generic vector load/stores, to merge 9567 /// base address updates. 9568 /// For generic load/stores, the memory type is assumed to be a vector. 9569 /// The caller is assumed to have checked legality. 9570 static SDValue CombineBaseUpdate(SDNode *N, 9571 TargetLowering::DAGCombinerInfo &DCI) { 9572 SelectionDAG &DAG = DCI.DAG; 9573 const bool isIntrinsic = (N->getOpcode() == ISD::INTRINSIC_VOID || 9574 N->getOpcode() == ISD::INTRINSIC_W_CHAIN); 9575 const bool isStore = N->getOpcode() == ISD::STORE; 9576 const unsigned AddrOpIdx = ((isIntrinsic || isStore) ? 2 : 1); 9577 SDValue Addr = N->getOperand(AddrOpIdx); 9578 MemSDNode *MemN = cast<MemSDNode>(N); 9579 SDLoc dl(N); 9580 9581 // Search for a use of the address operand that is an increment. 9582 for (SDNode::use_iterator UI = Addr.getNode()->use_begin(), 9583 UE = Addr.getNode()->use_end(); UI != UE; ++UI) { 9584 SDNode *User = *UI; 9585 if (User->getOpcode() != ISD::ADD || 9586 UI.getUse().getResNo() != Addr.getResNo()) 9587 continue; 9588 9589 // Check that the add is independent of the load/store. Otherwise, folding 9590 // it would create a cycle. 9591 if (User->isPredecessorOf(N) || N->isPredecessorOf(User)) 9592 continue; 9593 9594 // Find the new opcode for the updating load/store. 9595 bool isLoadOp = true; 9596 bool isLaneOp = false; 9597 unsigned NewOpc = 0; 9598 unsigned NumVecs = 0; 9599 if (isIntrinsic) { 9600 unsigned IntNo = cast<ConstantSDNode>(N->getOperand(1))->getZExtValue(); 9601 switch (IntNo) { 9602 default: llvm_unreachable("unexpected intrinsic for Neon base update"); 9603 case Intrinsic::arm_neon_vld1: NewOpc = ARMISD::VLD1_UPD; 9604 NumVecs = 1; break; 9605 case Intrinsic::arm_neon_vld2: NewOpc = ARMISD::VLD2_UPD; 9606 NumVecs = 2; break; 9607 case Intrinsic::arm_neon_vld3: NewOpc = ARMISD::VLD3_UPD; 9608 NumVecs = 3; break; 9609 case Intrinsic::arm_neon_vld4: NewOpc = ARMISD::VLD4_UPD; 9610 NumVecs = 4; break; 9611 case Intrinsic::arm_neon_vld2lane: NewOpc = ARMISD::VLD2LN_UPD; 9612 NumVecs = 2; isLaneOp = true; break; 9613 case Intrinsic::arm_neon_vld3lane: NewOpc = ARMISD::VLD3LN_UPD; 9614 NumVecs = 3; isLaneOp = true; break; 9615 case Intrinsic::arm_neon_vld4lane: NewOpc = ARMISD::VLD4LN_UPD; 9616 NumVecs = 4; isLaneOp = true; break; 9617 case Intrinsic::arm_neon_vst1: NewOpc = ARMISD::VST1_UPD; 9618 NumVecs = 1; isLoadOp = false; break; 9619 case Intrinsic::arm_neon_vst2: NewOpc = ARMISD::VST2_UPD; 9620 NumVecs = 2; isLoadOp = false; break; 9621 case Intrinsic::arm_neon_vst3: NewOpc = ARMISD::VST3_UPD; 9622 NumVecs = 3; isLoadOp = false; break; 9623 case Intrinsic::arm_neon_vst4: NewOpc = ARMISD::VST4_UPD; 9624 NumVecs = 4; isLoadOp = false; break; 9625 case Intrinsic::arm_neon_vst2lane: NewOpc = ARMISD::VST2LN_UPD; 9626 NumVecs = 2; isLoadOp = false; isLaneOp = true; break; 9627 case Intrinsic::arm_neon_vst3lane: NewOpc = ARMISD::VST3LN_UPD; 9628 NumVecs = 3; isLoadOp = false; isLaneOp = true; break; 9629 case Intrinsic::arm_neon_vst4lane: NewOpc = ARMISD::VST4LN_UPD; 9630 NumVecs = 4; isLoadOp = false; isLaneOp = true; break; 9631 } 9632 } else { 9633 isLaneOp = true; 9634 switch (N->getOpcode()) { 9635 default: llvm_unreachable("unexpected opcode for Neon base update"); 9636 case ARMISD::VLD2DUP: NewOpc = ARMISD::VLD2DUP_UPD; NumVecs = 2; break; 9637 case ARMISD::VLD3DUP: NewOpc = ARMISD::VLD3DUP_UPD; NumVecs = 3; break; 9638 case ARMISD::VLD4DUP: NewOpc = ARMISD::VLD4DUP_UPD; NumVecs = 4; break; 9639 case ISD::LOAD: NewOpc = ARMISD::VLD1_UPD; 9640 NumVecs = 1; isLaneOp = false; break; 9641 case ISD::STORE: NewOpc = ARMISD::VST1_UPD; 9642 NumVecs = 1; isLaneOp = false; isLoadOp = false; break; 9643 } 9644 } 9645 9646 // Find the size of memory referenced by the load/store. 9647 EVT VecTy; 9648 if (isLoadOp) { 9649 VecTy = N->getValueType(0); 9650 } else if (isIntrinsic) { 9651 VecTy = N->getOperand(AddrOpIdx+1).getValueType(); 9652 } else { 9653 assert(isStore && "Node has to be a load, a store, or an intrinsic!"); 9654 VecTy = N->getOperand(1).getValueType(); 9655 } 9656 9657 unsigned NumBytes = NumVecs * VecTy.getSizeInBits() / 8; 9658 if (isLaneOp) 9659 NumBytes /= VecTy.getVectorNumElements(); 9660 9661 // If the increment is a constant, it must match the memory ref size. 9662 SDValue Inc = User->getOperand(User->getOperand(0) == Addr ? 1 : 0); 9663 if (ConstantSDNode *CInc = dyn_cast<ConstantSDNode>(Inc.getNode())) { 9664 uint64_t IncVal = CInc->getZExtValue(); 9665 if (IncVal != NumBytes) 9666 continue; 9667 } else if (NumBytes >= 3 * 16) { 9668 // VLD3/4 and VST3/4 for 128-bit vectors are implemented with two 9669 // separate instructions that make it harder to use a non-constant update. 9670 continue; 9671 } 9672 9673 // OK, we found an ADD we can fold into the base update. 9674 // Now, create a _UPD node, taking care of not breaking alignment. 9675 9676 EVT AlignedVecTy = VecTy; 9677 unsigned Alignment = MemN->getAlignment(); 9678 9679 // If this is a less-than-standard-aligned load/store, change the type to 9680 // match the standard alignment. 9681 // The alignment is overlooked when selecting _UPD variants; and it's 9682 // easier to introduce bitcasts here than fix that. 9683 // There are 3 ways to get to this base-update combine: 9684 // - intrinsics: they are assumed to be properly aligned (to the standard 9685 // alignment of the memory type), so we don't need to do anything. 9686 // - ARMISD::VLDx nodes: they are only generated from the aforementioned 9687 // intrinsics, so, likewise, there's nothing to do. 9688 // - generic load/store instructions: the alignment is specified as an 9689 // explicit operand, rather than implicitly as the standard alignment 9690 // of the memory type (like the intrisics). We need to change the 9691 // memory type to match the explicit alignment. That way, we don't 9692 // generate non-standard-aligned ARMISD::VLDx nodes. 9693 if (isa<LSBaseSDNode>(N)) { 9694 if (Alignment == 0) 9695 Alignment = 1; 9696 if (Alignment < VecTy.getScalarSizeInBits() / 8) { 9697 MVT EltTy = MVT::getIntegerVT(Alignment * 8); 9698 assert(NumVecs == 1 && "Unexpected multi-element generic load/store."); 9699 assert(!isLaneOp && "Unexpected generic load/store lane."); 9700 unsigned NumElts = NumBytes / (EltTy.getSizeInBits() / 8); 9701 AlignedVecTy = MVT::getVectorVT(EltTy, NumElts); 9702 } 9703 // Don't set an explicit alignment on regular load/stores that we want 9704 // to transform to VLD/VST 1_UPD nodes. 9705 // This matches the behavior of regular load/stores, which only get an 9706 // explicit alignment if the MMO alignment is larger than the standard 9707 // alignment of the memory type. 9708 // Intrinsics, however, always get an explicit alignment, set to the 9709 // alignment of the MMO. 9710 Alignment = 1; 9711 } 9712 9713 // Create the new updating load/store node. 9714 // First, create an SDVTList for the new updating node's results. 9715 EVT Tys[6]; 9716 unsigned NumResultVecs = (isLoadOp ? NumVecs : 0); 9717 unsigned n; 9718 for (n = 0; n < NumResultVecs; ++n) 9719 Tys[n] = AlignedVecTy; 9720 Tys[n++] = MVT::i32; 9721 Tys[n] = MVT::Other; 9722 SDVTList SDTys = DAG.getVTList(makeArrayRef(Tys, NumResultVecs+2)); 9723 9724 // Then, gather the new node's operands. 9725 SmallVector<SDValue, 8> Ops; 9726 Ops.push_back(N->getOperand(0)); // incoming chain 9727 Ops.push_back(N->getOperand(AddrOpIdx)); 9728 Ops.push_back(Inc); 9729 9730 if (StoreSDNode *StN = dyn_cast<StoreSDNode>(N)) { 9731 // Try to match the intrinsic's signature 9732 Ops.push_back(StN->getValue()); 9733 } else { 9734 // Loads (and of course intrinsics) match the intrinsics' signature, 9735 // so just add all but the alignment operand. 9736 for (unsigned i = AddrOpIdx + 1; i < N->getNumOperands() - 1; ++i) 9737 Ops.push_back(N->getOperand(i)); 9738 } 9739 9740 // For all node types, the alignment operand is always the last one. 9741 Ops.push_back(DAG.getConstant(Alignment, dl, MVT::i32)); 9742 9743 // If this is a non-standard-aligned STORE, the penultimate operand is the 9744 // stored value. Bitcast it to the aligned type. 9745 if (AlignedVecTy != VecTy && N->getOpcode() == ISD::STORE) { 9746 SDValue &StVal = Ops[Ops.size()-2]; 9747 StVal = DAG.getNode(ISD::BITCAST, dl, AlignedVecTy, StVal); 9748 } 9749 9750 SDValue UpdN = DAG.getMemIntrinsicNode(NewOpc, dl, SDTys, 9751 Ops, AlignedVecTy, 9752 MemN->getMemOperand()); 9753 9754 // Update the uses. 9755 SmallVector<SDValue, 5> NewResults; 9756 for (unsigned i = 0; i < NumResultVecs; ++i) 9757 NewResults.push_back(SDValue(UpdN.getNode(), i)); 9758 9759 // If this is an non-standard-aligned LOAD, the first result is the loaded 9760 // value. Bitcast it to the expected result type. 9761 if (AlignedVecTy != VecTy && N->getOpcode() == ISD::LOAD) { 9762 SDValue &LdVal = NewResults[0]; 9763 LdVal = DAG.getNode(ISD::BITCAST, dl, VecTy, LdVal); 9764 } 9765 9766 NewResults.push_back(SDValue(UpdN.getNode(), NumResultVecs+1)); // chain 9767 DCI.CombineTo(N, NewResults); 9768 DCI.CombineTo(User, SDValue(UpdN.getNode(), NumResultVecs)); 9769 9770 break; 9771 } 9772 return SDValue(); 9773 } 9774 9775 static SDValue PerformVLDCombine(SDNode *N, 9776 TargetLowering::DAGCombinerInfo &DCI) { 9777 if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer()) 9778 return SDValue(); 9779 9780 return CombineBaseUpdate(N, DCI); 9781 } 9782 9783 /// CombineVLDDUP - For a VDUPLANE node N, check if its source operand is a 9784 /// vldN-lane (N > 1) intrinsic, and if all the other uses of that intrinsic 9785 /// are also VDUPLANEs. If so, combine them to a vldN-dup operation and 9786 /// return true. 9787 static bool CombineVLDDUP(SDNode *N, TargetLowering::DAGCombinerInfo &DCI) { 9788 SelectionDAG &DAG = DCI.DAG; 9789 EVT VT = N->getValueType(0); 9790 // vldN-dup instructions only support 64-bit vectors for N > 1. 9791 if (!VT.is64BitVector()) 9792 return false; 9793 9794 // Check if the VDUPLANE operand is a vldN-dup intrinsic. 9795 SDNode *VLD = N->getOperand(0).getNode(); 9796 if (VLD->getOpcode() != ISD::INTRINSIC_W_CHAIN) 9797 return false; 9798 unsigned NumVecs = 0; 9799 unsigned NewOpc = 0; 9800 unsigned IntNo = cast<ConstantSDNode>(VLD->getOperand(1))->getZExtValue(); 9801 if (IntNo == Intrinsic::arm_neon_vld2lane) { 9802 NumVecs = 2; 9803 NewOpc = ARMISD::VLD2DUP; 9804 } else if (IntNo == Intrinsic::arm_neon_vld3lane) { 9805 NumVecs = 3; 9806 NewOpc = ARMISD::VLD3DUP; 9807 } else if (IntNo == Intrinsic::arm_neon_vld4lane) { 9808 NumVecs = 4; 9809 NewOpc = ARMISD::VLD4DUP; 9810 } else { 9811 return false; 9812 } 9813 9814 // First check that all the vldN-lane uses are VDUPLANEs and that the lane 9815 // numbers match the load. 9816 unsigned VLDLaneNo = 9817 cast<ConstantSDNode>(VLD->getOperand(NumVecs+3))->getZExtValue(); 9818 for (SDNode::use_iterator UI = VLD->use_begin(), UE = VLD->use_end(); 9819 UI != UE; ++UI) { 9820 // Ignore uses of the chain result. 9821 if (UI.getUse().getResNo() == NumVecs) 9822 continue; 9823 SDNode *User = *UI; 9824 if (User->getOpcode() != ARMISD::VDUPLANE || 9825 VLDLaneNo != cast<ConstantSDNode>(User->getOperand(1))->getZExtValue()) 9826 return false; 9827 } 9828 9829 // Create the vldN-dup node. 9830 EVT Tys[5]; 9831 unsigned n; 9832 for (n = 0; n < NumVecs; ++n) 9833 Tys[n] = VT; 9834 Tys[n] = MVT::Other; 9835 SDVTList SDTys = DAG.getVTList(makeArrayRef(Tys, NumVecs+1)); 9836 SDValue Ops[] = { VLD->getOperand(0), VLD->getOperand(2) }; 9837 MemIntrinsicSDNode *VLDMemInt = cast<MemIntrinsicSDNode>(VLD); 9838 SDValue VLDDup = DAG.getMemIntrinsicNode(NewOpc, SDLoc(VLD), SDTys, 9839 Ops, VLDMemInt->getMemoryVT(), 9840 VLDMemInt->getMemOperand()); 9841 9842 // Update the uses. 9843 for (SDNode::use_iterator UI = VLD->use_begin(), UE = VLD->use_end(); 9844 UI != UE; ++UI) { 9845 unsigned ResNo = UI.getUse().getResNo(); 9846 // Ignore uses of the chain result. 9847 if (ResNo == NumVecs) 9848 continue; 9849 SDNode *User = *UI; 9850 DCI.CombineTo(User, SDValue(VLDDup.getNode(), ResNo)); 9851 } 9852 9853 // Now the vldN-lane intrinsic is dead except for its chain result. 9854 // Update uses of the chain. 9855 std::vector<SDValue> VLDDupResults; 9856 for (unsigned n = 0; n < NumVecs; ++n) 9857 VLDDupResults.push_back(SDValue(VLDDup.getNode(), n)); 9858 VLDDupResults.push_back(SDValue(VLDDup.getNode(), NumVecs)); 9859 DCI.CombineTo(VLD, VLDDupResults); 9860 9861 return true; 9862 } 9863 9864 /// PerformVDUPLANECombine - Target-specific dag combine xforms for 9865 /// ARMISD::VDUPLANE. 9866 static SDValue PerformVDUPLANECombine(SDNode *N, 9867 TargetLowering::DAGCombinerInfo &DCI) { 9868 SDValue Op = N->getOperand(0); 9869 9870 // If the source is a vldN-lane (N > 1) intrinsic, and all the other uses 9871 // of that intrinsic are also VDUPLANEs, combine them to a vldN-dup operation. 9872 if (CombineVLDDUP(N, DCI)) 9873 return SDValue(N, 0); 9874 9875 // If the source is already a VMOVIMM or VMVNIMM splat, the VDUPLANE is 9876 // redundant. Ignore bit_converts for now; element sizes are checked below. 9877 while (Op.getOpcode() == ISD::BITCAST) 9878 Op = Op.getOperand(0); 9879 if (Op.getOpcode() != ARMISD::VMOVIMM && Op.getOpcode() != ARMISD::VMVNIMM) 9880 return SDValue(); 9881 9882 // Make sure the VMOV element size is not bigger than the VDUPLANE elements. 9883 unsigned EltSize = Op.getValueType().getVectorElementType().getSizeInBits(); 9884 // The canonical VMOV for a zero vector uses a 32-bit element size. 9885 unsigned Imm = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue(); 9886 unsigned EltBits; 9887 if (ARM_AM::decodeNEONModImm(Imm, EltBits) == 0) 9888 EltSize = 8; 9889 EVT VT = N->getValueType(0); 9890 if (EltSize > VT.getVectorElementType().getSizeInBits()) 9891 return SDValue(); 9892 9893 return DCI.DAG.getNode(ISD::BITCAST, SDLoc(N), VT, Op); 9894 } 9895 9896 static SDValue PerformLOADCombine(SDNode *N, 9897 TargetLowering::DAGCombinerInfo &DCI) { 9898 EVT VT = N->getValueType(0); 9899 9900 // If this is a legal vector load, try to combine it into a VLD1_UPD. 9901 if (ISD::isNormalLoad(N) && VT.isVector() && 9902 DCI.DAG.getTargetLoweringInfo().isTypeLegal(VT)) 9903 return CombineBaseUpdate(N, DCI); 9904 9905 return SDValue(); 9906 } 9907 9908 /// PerformSTORECombine - Target-specific dag combine xforms for 9909 /// ISD::STORE. 9910 static SDValue PerformSTORECombine(SDNode *N, 9911 TargetLowering::DAGCombinerInfo &DCI) { 9912 StoreSDNode *St = cast<StoreSDNode>(N); 9913 if (St->isVolatile()) 9914 return SDValue(); 9915 9916 // Optimize trunc store (of multiple scalars) to shuffle and store. First, 9917 // pack all of the elements in one place. Next, store to memory in fewer 9918 // chunks. 9919 SDValue StVal = St->getValue(); 9920 EVT VT = StVal.getValueType(); 9921 if (St->isTruncatingStore() && VT.isVector()) { 9922 SelectionDAG &DAG = DCI.DAG; 9923 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 9924 EVT StVT = St->getMemoryVT(); 9925 unsigned NumElems = VT.getVectorNumElements(); 9926 assert(StVT != VT && "Cannot truncate to the same type"); 9927 unsigned FromEltSz = VT.getVectorElementType().getSizeInBits(); 9928 unsigned ToEltSz = StVT.getVectorElementType().getSizeInBits(); 9929 9930 // From, To sizes and ElemCount must be pow of two 9931 if (!isPowerOf2_32(NumElems * FromEltSz * ToEltSz)) return SDValue(); 9932 9933 // We are going to use the original vector elt for storing. 9934 // Accumulated smaller vector elements must be a multiple of the store size. 9935 if (0 != (NumElems * FromEltSz) % ToEltSz) return SDValue(); 9936 9937 unsigned SizeRatio = FromEltSz / ToEltSz; 9938 assert(SizeRatio * NumElems * ToEltSz == VT.getSizeInBits()); 9939 9940 // Create a type on which we perform the shuffle. 9941 EVT WideVecVT = EVT::getVectorVT(*DAG.getContext(), StVT.getScalarType(), 9942 NumElems*SizeRatio); 9943 assert(WideVecVT.getSizeInBits() == VT.getSizeInBits()); 9944 9945 SDLoc DL(St); 9946 SDValue WideVec = DAG.getNode(ISD::BITCAST, DL, WideVecVT, StVal); 9947 SmallVector<int, 8> ShuffleVec(NumElems * SizeRatio, -1); 9948 for (unsigned i = 0; i < NumElems; ++i) 9949 ShuffleVec[i] = DAG.getDataLayout().isBigEndian() 9950 ? (i + 1) * SizeRatio - 1 9951 : i * SizeRatio; 9952 9953 // Can't shuffle using an illegal type. 9954 if (!TLI.isTypeLegal(WideVecVT)) return SDValue(); 9955 9956 SDValue Shuff = DAG.getVectorShuffle(WideVecVT, DL, WideVec, 9957 DAG.getUNDEF(WideVec.getValueType()), 9958 ShuffleVec.data()); 9959 // At this point all of the data is stored at the bottom of the 9960 // register. We now need to save it to mem. 9961 9962 // Find the largest store unit 9963 MVT StoreType = MVT::i8; 9964 for (MVT Tp : MVT::integer_valuetypes()) { 9965 if (TLI.isTypeLegal(Tp) && Tp.getSizeInBits() <= NumElems * ToEltSz) 9966 StoreType = Tp; 9967 } 9968 // Didn't find a legal store type. 9969 if (!TLI.isTypeLegal(StoreType)) 9970 return SDValue(); 9971 9972 // Bitcast the original vector into a vector of store-size units 9973 EVT StoreVecVT = EVT::getVectorVT(*DAG.getContext(), 9974 StoreType, VT.getSizeInBits()/EVT(StoreType).getSizeInBits()); 9975 assert(StoreVecVT.getSizeInBits() == VT.getSizeInBits()); 9976 SDValue ShuffWide = DAG.getNode(ISD::BITCAST, DL, StoreVecVT, Shuff); 9977 SmallVector<SDValue, 8> Chains; 9978 SDValue Increment = DAG.getConstant(StoreType.getSizeInBits() / 8, DL, 9979 TLI.getPointerTy(DAG.getDataLayout())); 9980 SDValue BasePtr = St->getBasePtr(); 9981 9982 // Perform one or more big stores into memory. 9983 unsigned E = (ToEltSz*NumElems)/StoreType.getSizeInBits(); 9984 for (unsigned I = 0; I < E; I++) { 9985 SDValue SubVec = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, 9986 StoreType, ShuffWide, 9987 DAG.getIntPtrConstant(I, DL)); 9988 SDValue Ch = DAG.getStore(St->getChain(), DL, SubVec, BasePtr, 9989 St->getPointerInfo(), St->isVolatile(), 9990 St->isNonTemporal(), St->getAlignment()); 9991 BasePtr = DAG.getNode(ISD::ADD, DL, BasePtr.getValueType(), BasePtr, 9992 Increment); 9993 Chains.push_back(Ch); 9994 } 9995 return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Chains); 9996 } 9997 9998 if (!ISD::isNormalStore(St)) 9999 return SDValue(); 10000 10001 // Split a store of a VMOVDRR into two integer stores to avoid mixing NEON and 10002 // ARM stores of arguments in the same cache line. 10003 if (StVal.getNode()->getOpcode() == ARMISD::VMOVDRR && 10004 StVal.getNode()->hasOneUse()) { 10005 SelectionDAG &DAG = DCI.DAG; 10006 bool isBigEndian = DAG.getDataLayout().isBigEndian(); 10007 SDLoc DL(St); 10008 SDValue BasePtr = St->getBasePtr(); 10009 SDValue NewST1 = DAG.getStore(St->getChain(), DL, 10010 StVal.getNode()->getOperand(isBigEndian ? 1 : 0 ), 10011 BasePtr, St->getPointerInfo(), St->isVolatile(), 10012 St->isNonTemporal(), St->getAlignment()); 10013 10014 SDValue OffsetPtr = DAG.getNode(ISD::ADD, DL, MVT::i32, BasePtr, 10015 DAG.getConstant(4, DL, MVT::i32)); 10016 return DAG.getStore(NewST1.getValue(0), DL, 10017 StVal.getNode()->getOperand(isBigEndian ? 0 : 1), 10018 OffsetPtr, St->getPointerInfo(), St->isVolatile(), 10019 St->isNonTemporal(), 10020 std::min(4U, St->getAlignment() / 2)); 10021 } 10022 10023 if (StVal.getValueType() == MVT::i64 && 10024 StVal.getNode()->getOpcode() == ISD::EXTRACT_VECTOR_ELT) { 10025 10026 // Bitcast an i64 store extracted from a vector to f64. 10027 // Otherwise, the i64 value will be legalized to a pair of i32 values. 10028 SelectionDAG &DAG = DCI.DAG; 10029 SDLoc dl(StVal); 10030 SDValue IntVec = StVal.getOperand(0); 10031 EVT FloatVT = EVT::getVectorVT(*DAG.getContext(), MVT::f64, 10032 IntVec.getValueType().getVectorNumElements()); 10033 SDValue Vec = DAG.getNode(ISD::BITCAST, dl, FloatVT, IntVec); 10034 SDValue ExtElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, 10035 Vec, StVal.getOperand(1)); 10036 dl = SDLoc(N); 10037 SDValue V = DAG.getNode(ISD::BITCAST, dl, MVT::i64, ExtElt); 10038 // Make the DAGCombiner fold the bitcasts. 10039 DCI.AddToWorklist(Vec.getNode()); 10040 DCI.AddToWorklist(ExtElt.getNode()); 10041 DCI.AddToWorklist(V.getNode()); 10042 return DAG.getStore(St->getChain(), dl, V, St->getBasePtr(), 10043 St->getPointerInfo(), St->isVolatile(), 10044 St->isNonTemporal(), St->getAlignment(), 10045 St->getAAInfo()); 10046 } 10047 10048 // If this is a legal vector store, try to combine it into a VST1_UPD. 10049 if (ISD::isNormalStore(N) && VT.isVector() && 10050 DCI.DAG.getTargetLoweringInfo().isTypeLegal(VT)) 10051 return CombineBaseUpdate(N, DCI); 10052 10053 return SDValue(); 10054 } 10055 10056 /// PerformVCVTCombine - VCVT (floating-point to fixed-point, Advanced SIMD) 10057 /// can replace combinations of VMUL and VCVT (floating-point to integer) 10058 /// when the VMUL has a constant operand that is a power of 2. 10059 /// 10060 /// Example (assume d17 = <float 8.000000e+00, float 8.000000e+00>): 10061 /// vmul.f32 d16, d17, d16 10062 /// vcvt.s32.f32 d16, d16 10063 /// becomes: 10064 /// vcvt.s32.f32 d16, d16, #3 10065 static SDValue PerformVCVTCombine(SDNode *N, SelectionDAG &DAG, 10066 const ARMSubtarget *Subtarget) { 10067 if (!Subtarget->hasNEON()) 10068 return SDValue(); 10069 10070 SDValue Op = N->getOperand(0); 10071 if (!Op.getValueType().isVector() || Op.getOpcode() != ISD::FMUL) 10072 return SDValue(); 10073 10074 SDValue ConstVec = Op->getOperand(1); 10075 if (!isa<BuildVectorSDNode>(ConstVec)) 10076 return SDValue(); 10077 10078 MVT FloatTy = Op.getSimpleValueType().getVectorElementType(); 10079 uint32_t FloatBits = FloatTy.getSizeInBits(); 10080 MVT IntTy = N->getSimpleValueType(0).getVectorElementType(); 10081 uint32_t IntBits = IntTy.getSizeInBits(); 10082 unsigned NumLanes = Op.getValueType().getVectorNumElements(); 10083 if (FloatBits != 32 || IntBits > 32 || NumLanes > 4) { 10084 // These instructions only exist converting from f32 to i32. We can handle 10085 // smaller integers by generating an extra truncate, but larger ones would 10086 // be lossy. We also can't handle more then 4 lanes, since these intructions 10087 // only support v2i32/v4i32 types. 10088 return SDValue(); 10089 } 10090 10091 BitVector UndefElements; 10092 BuildVectorSDNode *BV = cast<BuildVectorSDNode>(ConstVec); 10093 int32_t C = BV->getConstantFPSplatPow2ToLog2Int(&UndefElements, 33); 10094 if (C == -1 || C == 0 || C > 32) 10095 return SDValue(); 10096 10097 SDLoc dl(N); 10098 bool isSigned = N->getOpcode() == ISD::FP_TO_SINT; 10099 unsigned IntrinsicOpcode = isSigned ? Intrinsic::arm_neon_vcvtfp2fxs : 10100 Intrinsic::arm_neon_vcvtfp2fxu; 10101 SDValue FixConv = DAG.getNode( 10102 ISD::INTRINSIC_WO_CHAIN, dl, NumLanes == 2 ? MVT::v2i32 : MVT::v4i32, 10103 DAG.getConstant(IntrinsicOpcode, dl, MVT::i32), Op->getOperand(0), 10104 DAG.getConstant(C, dl, MVT::i32)); 10105 10106 if (IntBits < FloatBits) 10107 FixConv = DAG.getNode(ISD::TRUNCATE, dl, N->getValueType(0), FixConv); 10108 10109 return FixConv; 10110 } 10111 10112 /// PerformVDIVCombine - VCVT (fixed-point to floating-point, Advanced SIMD) 10113 /// can replace combinations of VCVT (integer to floating-point) and VDIV 10114 /// when the VDIV has a constant operand that is a power of 2. 10115 /// 10116 /// Example (assume d17 = <float 8.000000e+00, float 8.000000e+00>): 10117 /// vcvt.f32.s32 d16, d16 10118 /// vdiv.f32 d16, d17, d16 10119 /// becomes: 10120 /// vcvt.f32.s32 d16, d16, #3 10121 static SDValue PerformVDIVCombine(SDNode *N, SelectionDAG &DAG, 10122 const ARMSubtarget *Subtarget) { 10123 if (!Subtarget->hasNEON()) 10124 return SDValue(); 10125 10126 SDValue Op = N->getOperand(0); 10127 unsigned OpOpcode = Op.getNode()->getOpcode(); 10128 if (!N->getValueType(0).isVector() || 10129 (OpOpcode != ISD::SINT_TO_FP && OpOpcode != ISD::UINT_TO_FP)) 10130 return SDValue(); 10131 10132 SDValue ConstVec = N->getOperand(1); 10133 if (!isa<BuildVectorSDNode>(ConstVec)) 10134 return SDValue(); 10135 10136 MVT FloatTy = N->getSimpleValueType(0).getVectorElementType(); 10137 uint32_t FloatBits = FloatTy.getSizeInBits(); 10138 MVT IntTy = Op.getOperand(0).getSimpleValueType().getVectorElementType(); 10139 uint32_t IntBits = IntTy.getSizeInBits(); 10140 unsigned NumLanes = Op.getValueType().getVectorNumElements(); 10141 if (FloatBits != 32 || IntBits > 32 || NumLanes > 4) { 10142 // These instructions only exist converting from i32 to f32. We can handle 10143 // smaller integers by generating an extra extend, but larger ones would 10144 // be lossy. We also can't handle more then 4 lanes, since these intructions 10145 // only support v2i32/v4i32 types. 10146 return SDValue(); 10147 } 10148 10149 BitVector UndefElements; 10150 BuildVectorSDNode *BV = cast<BuildVectorSDNode>(ConstVec); 10151 int32_t C = BV->getConstantFPSplatPow2ToLog2Int(&UndefElements, 33); 10152 if (C == -1 || C == 0 || C > 32) 10153 return SDValue(); 10154 10155 SDLoc dl(N); 10156 bool isSigned = OpOpcode == ISD::SINT_TO_FP; 10157 SDValue ConvInput = Op.getOperand(0); 10158 if (IntBits < FloatBits) 10159 ConvInput = DAG.getNode(isSigned ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND, 10160 dl, NumLanes == 2 ? MVT::v2i32 : MVT::v4i32, 10161 ConvInput); 10162 10163 unsigned IntrinsicOpcode = isSigned ? Intrinsic::arm_neon_vcvtfxs2fp : 10164 Intrinsic::arm_neon_vcvtfxu2fp; 10165 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, 10166 Op.getValueType(), 10167 DAG.getConstant(IntrinsicOpcode, dl, MVT::i32), 10168 ConvInput, DAG.getConstant(C, dl, MVT::i32)); 10169 } 10170 10171 /// Getvshiftimm - Check if this is a valid build_vector for the immediate 10172 /// operand of a vector shift operation, where all the elements of the 10173 /// build_vector must have the same constant integer value. 10174 static bool getVShiftImm(SDValue Op, unsigned ElementBits, int64_t &Cnt) { 10175 // Ignore bit_converts. 10176 while (Op.getOpcode() == ISD::BITCAST) 10177 Op = Op.getOperand(0); 10178 BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(Op.getNode()); 10179 APInt SplatBits, SplatUndef; 10180 unsigned SplatBitSize; 10181 bool HasAnyUndefs; 10182 if (! BVN || ! BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, 10183 HasAnyUndefs, ElementBits) || 10184 SplatBitSize > ElementBits) 10185 return false; 10186 Cnt = SplatBits.getSExtValue(); 10187 return true; 10188 } 10189 10190 /// isVShiftLImm - Check if this is a valid build_vector for the immediate 10191 /// operand of a vector shift left operation. That value must be in the range: 10192 /// 0 <= Value < ElementBits for a left shift; or 10193 /// 0 <= Value <= ElementBits for a long left shift. 10194 static bool isVShiftLImm(SDValue Op, EVT VT, bool isLong, int64_t &Cnt) { 10195 assert(VT.isVector() && "vector shift count is not a vector type"); 10196 int64_t ElementBits = VT.getVectorElementType().getSizeInBits(); 10197 if (! getVShiftImm(Op, ElementBits, Cnt)) 10198 return false; 10199 return (Cnt >= 0 && (isLong ? Cnt-1 : Cnt) < ElementBits); 10200 } 10201 10202 /// isVShiftRImm - Check if this is a valid build_vector for the immediate 10203 /// operand of a vector shift right operation. For a shift opcode, the value 10204 /// is positive, but for an intrinsic the value count must be negative. The 10205 /// absolute value must be in the range: 10206 /// 1 <= |Value| <= ElementBits for a right shift; or 10207 /// 1 <= |Value| <= ElementBits/2 for a narrow right shift. 10208 static bool isVShiftRImm(SDValue Op, EVT VT, bool isNarrow, bool isIntrinsic, 10209 int64_t &Cnt) { 10210 assert(VT.isVector() && "vector shift count is not a vector type"); 10211 int64_t ElementBits = VT.getVectorElementType().getSizeInBits(); 10212 if (! getVShiftImm(Op, ElementBits, Cnt)) 10213 return false; 10214 if (!isIntrinsic) 10215 return (Cnt >= 1 && Cnt <= (isNarrow ? ElementBits/2 : ElementBits)); 10216 if (Cnt >= -(isNarrow ? ElementBits/2 : ElementBits) && Cnt <= -1) { 10217 Cnt = -Cnt; 10218 return true; 10219 } 10220 return false; 10221 } 10222 10223 /// PerformIntrinsicCombine - ARM-specific DAG combining for intrinsics. 10224 static SDValue PerformIntrinsicCombine(SDNode *N, SelectionDAG &DAG) { 10225 unsigned IntNo = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue(); 10226 switch (IntNo) { 10227 default: 10228 // Don't do anything for most intrinsics. 10229 break; 10230 10231 // Vector shifts: check for immediate versions and lower them. 10232 // Note: This is done during DAG combining instead of DAG legalizing because 10233 // the build_vectors for 64-bit vector element shift counts are generally 10234 // not legal, and it is hard to see their values after they get legalized to 10235 // loads from a constant pool. 10236 case Intrinsic::arm_neon_vshifts: 10237 case Intrinsic::arm_neon_vshiftu: 10238 case Intrinsic::arm_neon_vrshifts: 10239 case Intrinsic::arm_neon_vrshiftu: 10240 case Intrinsic::arm_neon_vrshiftn: 10241 case Intrinsic::arm_neon_vqshifts: 10242 case Intrinsic::arm_neon_vqshiftu: 10243 case Intrinsic::arm_neon_vqshiftsu: 10244 case Intrinsic::arm_neon_vqshiftns: 10245 case Intrinsic::arm_neon_vqshiftnu: 10246 case Intrinsic::arm_neon_vqshiftnsu: 10247 case Intrinsic::arm_neon_vqrshiftns: 10248 case Intrinsic::arm_neon_vqrshiftnu: 10249 case Intrinsic::arm_neon_vqrshiftnsu: { 10250 EVT VT = N->getOperand(1).getValueType(); 10251 int64_t Cnt; 10252 unsigned VShiftOpc = 0; 10253 10254 switch (IntNo) { 10255 case Intrinsic::arm_neon_vshifts: 10256 case Intrinsic::arm_neon_vshiftu: 10257 if (isVShiftLImm(N->getOperand(2), VT, false, Cnt)) { 10258 VShiftOpc = ARMISD::VSHL; 10259 break; 10260 } 10261 if (isVShiftRImm(N->getOperand(2), VT, false, true, Cnt)) { 10262 VShiftOpc = (IntNo == Intrinsic::arm_neon_vshifts ? 10263 ARMISD::VSHRs : ARMISD::VSHRu); 10264 break; 10265 } 10266 return SDValue(); 10267 10268 case Intrinsic::arm_neon_vrshifts: 10269 case Intrinsic::arm_neon_vrshiftu: 10270 if (isVShiftRImm(N->getOperand(2), VT, false, true, Cnt)) 10271 break; 10272 return SDValue(); 10273 10274 case Intrinsic::arm_neon_vqshifts: 10275 case Intrinsic::arm_neon_vqshiftu: 10276 if (isVShiftLImm(N->getOperand(2), VT, false, Cnt)) 10277 break; 10278 return SDValue(); 10279 10280 case Intrinsic::arm_neon_vqshiftsu: 10281 if (isVShiftLImm(N->getOperand(2), VT, false, Cnt)) 10282 break; 10283 llvm_unreachable("invalid shift count for vqshlu intrinsic"); 10284 10285 case Intrinsic::arm_neon_vrshiftn: 10286 case Intrinsic::arm_neon_vqshiftns: 10287 case Intrinsic::arm_neon_vqshiftnu: 10288 case Intrinsic::arm_neon_vqshiftnsu: 10289 case Intrinsic::arm_neon_vqrshiftns: 10290 case Intrinsic::arm_neon_vqrshiftnu: 10291 case Intrinsic::arm_neon_vqrshiftnsu: 10292 // Narrowing shifts require an immediate right shift. 10293 if (isVShiftRImm(N->getOperand(2), VT, true, true, Cnt)) 10294 break; 10295 llvm_unreachable("invalid shift count for narrowing vector shift " 10296 "intrinsic"); 10297 10298 default: 10299 llvm_unreachable("unhandled vector shift"); 10300 } 10301 10302 switch (IntNo) { 10303 case Intrinsic::arm_neon_vshifts: 10304 case Intrinsic::arm_neon_vshiftu: 10305 // Opcode already set above. 10306 break; 10307 case Intrinsic::arm_neon_vrshifts: 10308 VShiftOpc = ARMISD::VRSHRs; break; 10309 case Intrinsic::arm_neon_vrshiftu: 10310 VShiftOpc = ARMISD::VRSHRu; break; 10311 case Intrinsic::arm_neon_vrshiftn: 10312 VShiftOpc = ARMISD::VRSHRN; break; 10313 case Intrinsic::arm_neon_vqshifts: 10314 VShiftOpc = ARMISD::VQSHLs; break; 10315 case Intrinsic::arm_neon_vqshiftu: 10316 VShiftOpc = ARMISD::VQSHLu; break; 10317 case Intrinsic::arm_neon_vqshiftsu: 10318 VShiftOpc = ARMISD::VQSHLsu; break; 10319 case Intrinsic::arm_neon_vqshiftns: 10320 VShiftOpc = ARMISD::VQSHRNs; break; 10321 case Intrinsic::arm_neon_vqshiftnu: 10322 VShiftOpc = ARMISD::VQSHRNu; break; 10323 case Intrinsic::arm_neon_vqshiftnsu: 10324 VShiftOpc = ARMISD::VQSHRNsu; break; 10325 case Intrinsic::arm_neon_vqrshiftns: 10326 VShiftOpc = ARMISD::VQRSHRNs; break; 10327 case Intrinsic::arm_neon_vqrshiftnu: 10328 VShiftOpc = ARMISD::VQRSHRNu; break; 10329 case Intrinsic::arm_neon_vqrshiftnsu: 10330 VShiftOpc = ARMISD::VQRSHRNsu; break; 10331 } 10332 10333 SDLoc dl(N); 10334 return DAG.getNode(VShiftOpc, dl, N->getValueType(0), 10335 N->getOperand(1), DAG.getConstant(Cnt, dl, MVT::i32)); 10336 } 10337 10338 case Intrinsic::arm_neon_vshiftins: { 10339 EVT VT = N->getOperand(1).getValueType(); 10340 int64_t Cnt; 10341 unsigned VShiftOpc = 0; 10342 10343 if (isVShiftLImm(N->getOperand(3), VT, false, Cnt)) 10344 VShiftOpc = ARMISD::VSLI; 10345 else if (isVShiftRImm(N->getOperand(3), VT, false, true, Cnt)) 10346 VShiftOpc = ARMISD::VSRI; 10347 else { 10348 llvm_unreachable("invalid shift count for vsli/vsri intrinsic"); 10349 } 10350 10351 SDLoc dl(N); 10352 return DAG.getNode(VShiftOpc, dl, N->getValueType(0), 10353 N->getOperand(1), N->getOperand(2), 10354 DAG.getConstant(Cnt, dl, MVT::i32)); 10355 } 10356 10357 case Intrinsic::arm_neon_vqrshifts: 10358 case Intrinsic::arm_neon_vqrshiftu: 10359 // No immediate versions of these to check for. 10360 break; 10361 } 10362 10363 return SDValue(); 10364 } 10365 10366 /// PerformShiftCombine - Checks for immediate versions of vector shifts and 10367 /// lowers them. As with the vector shift intrinsics, this is done during DAG 10368 /// combining instead of DAG legalizing because the build_vectors for 64-bit 10369 /// vector element shift counts are generally not legal, and it is hard to see 10370 /// their values after they get legalized to loads from a constant pool. 10371 static SDValue PerformShiftCombine(SDNode *N, SelectionDAG &DAG, 10372 const ARMSubtarget *ST) { 10373 EVT VT = N->getValueType(0); 10374 if (N->getOpcode() == ISD::SRL && VT == MVT::i32 && ST->hasV6Ops()) { 10375 // Canonicalize (srl (bswap x), 16) to (rotr (bswap x), 16) if the high 10376 // 16-bits of x is zero. This optimizes rev + lsr 16 to rev16. 10377 SDValue N1 = N->getOperand(1); 10378 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(N1)) { 10379 SDValue N0 = N->getOperand(0); 10380 if (C->getZExtValue() == 16 && N0.getOpcode() == ISD::BSWAP && 10381 DAG.MaskedValueIsZero(N0.getOperand(0), 10382 APInt::getHighBitsSet(32, 16))) 10383 return DAG.getNode(ISD::ROTR, SDLoc(N), VT, N0, N1); 10384 } 10385 } 10386 10387 // Nothing to be done for scalar shifts. 10388 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 10389 if (!VT.isVector() || !TLI.isTypeLegal(VT)) 10390 return SDValue(); 10391 10392 assert(ST->hasNEON() && "unexpected vector shift"); 10393 int64_t Cnt; 10394 10395 switch (N->getOpcode()) { 10396 default: llvm_unreachable("unexpected shift opcode"); 10397 10398 case ISD::SHL: 10399 if (isVShiftLImm(N->getOperand(1), VT, false, Cnt)) { 10400 SDLoc dl(N); 10401 return DAG.getNode(ARMISD::VSHL, dl, VT, N->getOperand(0), 10402 DAG.getConstant(Cnt, dl, MVT::i32)); 10403 } 10404 break; 10405 10406 case ISD::SRA: 10407 case ISD::SRL: 10408 if (isVShiftRImm(N->getOperand(1), VT, false, false, Cnt)) { 10409 unsigned VShiftOpc = (N->getOpcode() == ISD::SRA ? 10410 ARMISD::VSHRs : ARMISD::VSHRu); 10411 SDLoc dl(N); 10412 return DAG.getNode(VShiftOpc, dl, VT, N->getOperand(0), 10413 DAG.getConstant(Cnt, dl, MVT::i32)); 10414 } 10415 } 10416 return SDValue(); 10417 } 10418 10419 /// PerformExtendCombine - Target-specific DAG combining for ISD::SIGN_EXTEND, 10420 /// ISD::ZERO_EXTEND, and ISD::ANY_EXTEND. 10421 static SDValue PerformExtendCombine(SDNode *N, SelectionDAG &DAG, 10422 const ARMSubtarget *ST) { 10423 SDValue N0 = N->getOperand(0); 10424 10425 // Check for sign- and zero-extensions of vector extract operations of 8- 10426 // and 16-bit vector elements. NEON supports these directly. They are 10427 // handled during DAG combining because type legalization will promote them 10428 // to 32-bit types and it is messy to recognize the operations after that. 10429 if (ST->hasNEON() && N0.getOpcode() == ISD::EXTRACT_VECTOR_ELT) { 10430 SDValue Vec = N0.getOperand(0); 10431 SDValue Lane = N0.getOperand(1); 10432 EVT VT = N->getValueType(0); 10433 EVT EltVT = N0.getValueType(); 10434 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 10435 10436 if (VT == MVT::i32 && 10437 (EltVT == MVT::i8 || EltVT == MVT::i16) && 10438 TLI.isTypeLegal(Vec.getValueType()) && 10439 isa<ConstantSDNode>(Lane)) { 10440 10441 unsigned Opc = 0; 10442 switch (N->getOpcode()) { 10443 default: llvm_unreachable("unexpected opcode"); 10444 case ISD::SIGN_EXTEND: 10445 Opc = ARMISD::VGETLANEs; 10446 break; 10447 case ISD::ZERO_EXTEND: 10448 case ISD::ANY_EXTEND: 10449 Opc = ARMISD::VGETLANEu; 10450 break; 10451 } 10452 return DAG.getNode(Opc, SDLoc(N), VT, Vec, Lane); 10453 } 10454 } 10455 10456 return SDValue(); 10457 } 10458 10459 static void computeKnownBits(SelectionDAG &DAG, SDValue Op, APInt &KnownZero, 10460 APInt &KnownOne) { 10461 if (Op.getOpcode() == ARMISD::BFI) { 10462 // Conservatively, we can recurse down the first operand 10463 // and just mask out all affected bits. 10464 computeKnownBits(DAG, Op.getOperand(0), KnownZero, KnownOne); 10465 10466 // The operand to BFI is already a mask suitable for removing the bits it 10467 // sets. 10468 ConstantSDNode *CI = cast<ConstantSDNode>(Op.getOperand(2)); 10469 APInt Mask = CI->getAPIntValue(); 10470 KnownZero &= Mask; 10471 KnownOne &= Mask; 10472 return; 10473 } 10474 if (Op.getOpcode() == ARMISD::CMOV) { 10475 APInt KZ2(KnownZero.getBitWidth(), 0); 10476 APInt KO2(KnownOne.getBitWidth(), 0); 10477 computeKnownBits(DAG, Op.getOperand(1), KnownZero, KnownOne); 10478 computeKnownBits(DAG, Op.getOperand(2), KZ2, KO2); 10479 10480 KnownZero &= KZ2; 10481 KnownOne &= KO2; 10482 return; 10483 } 10484 return DAG.computeKnownBits(Op, KnownZero, KnownOne); 10485 } 10486 10487 SDValue ARMTargetLowering::PerformCMOVToBFICombine(SDNode *CMOV, SelectionDAG &DAG) const { 10488 // If we have a CMOV, OR and AND combination such as: 10489 // if (x & CN) 10490 // y |= CM; 10491 // 10492 // And: 10493 // * CN is a single bit; 10494 // * All bits covered by CM are known zero in y 10495 // 10496 // Then we can convert this into a sequence of BFI instructions. This will 10497 // always be a win if CM is a single bit, will always be no worse than the 10498 // TST&OR sequence if CM is two bits, and for thumb will be no worse if CM is 10499 // three bits (due to the extra IT instruction). 10500 10501 SDValue Op0 = CMOV->getOperand(0); 10502 SDValue Op1 = CMOV->getOperand(1); 10503 auto CCNode = cast<ConstantSDNode>(CMOV->getOperand(2)); 10504 auto CC = CCNode->getAPIntValue().getLimitedValue(); 10505 SDValue CmpZ = CMOV->getOperand(4); 10506 10507 // The compare must be against zero. 10508 if (!isNullConstant(CmpZ->getOperand(1))) 10509 return SDValue(); 10510 10511 assert(CmpZ->getOpcode() == ARMISD::CMPZ); 10512 SDValue And = CmpZ->getOperand(0); 10513 if (And->getOpcode() != ISD::AND) 10514 return SDValue(); 10515 ConstantSDNode *AndC = dyn_cast<ConstantSDNode>(And->getOperand(1)); 10516 if (!AndC || !AndC->getAPIntValue().isPowerOf2()) 10517 return SDValue(); 10518 SDValue X = And->getOperand(0); 10519 10520 if (CC == ARMCC::EQ) { 10521 // We're performing an "equal to zero" compare. Swap the operands so we 10522 // canonicalize on a "not equal to zero" compare. 10523 std::swap(Op0, Op1); 10524 } else { 10525 assert(CC == ARMCC::NE && "How can a CMPZ node not be EQ or NE?"); 10526 } 10527 10528 if (Op1->getOpcode() != ISD::OR) 10529 return SDValue(); 10530 10531 ConstantSDNode *OrC = dyn_cast<ConstantSDNode>(Op1->getOperand(1)); 10532 if (!OrC) 10533 return SDValue(); 10534 SDValue Y = Op1->getOperand(0); 10535 10536 if (Op0 != Y) 10537 return SDValue(); 10538 10539 // Now, is it profitable to continue? 10540 APInt OrCI = OrC->getAPIntValue(); 10541 unsigned Heuristic = Subtarget->isThumb() ? 3 : 2; 10542 if (OrCI.countPopulation() > Heuristic) 10543 return SDValue(); 10544 10545 // Lastly, can we determine that the bits defined by OrCI 10546 // are zero in Y? 10547 APInt KnownZero, KnownOne; 10548 computeKnownBits(DAG, Y, KnownZero, KnownOne); 10549 if ((OrCI & KnownZero) != OrCI) 10550 return SDValue(); 10551 10552 // OK, we can do the combine. 10553 SDValue V = Y; 10554 SDLoc dl(X); 10555 EVT VT = X.getValueType(); 10556 unsigned BitInX = AndC->getAPIntValue().logBase2(); 10557 10558 if (BitInX != 0) { 10559 // We must shift X first. 10560 X = DAG.getNode(ISD::SRL, dl, VT, X, 10561 DAG.getConstant(BitInX, dl, VT)); 10562 } 10563 10564 for (unsigned BitInY = 0, NumActiveBits = OrCI.getActiveBits(); 10565 BitInY < NumActiveBits; ++BitInY) { 10566 if (OrCI[BitInY] == 0) 10567 continue; 10568 APInt Mask(VT.getSizeInBits(), 0); 10569 Mask.setBit(BitInY); 10570 V = DAG.getNode(ARMISD::BFI, dl, VT, V, X, 10571 // Confusingly, the operand is an *inverted* mask. 10572 DAG.getConstant(~Mask, dl, VT)); 10573 } 10574 10575 return V; 10576 } 10577 10578 /// PerformCMOVCombine - Target-specific DAG combining for ARMISD::CMOV. 10579 SDValue 10580 ARMTargetLowering::PerformCMOVCombine(SDNode *N, SelectionDAG &DAG) const { 10581 SDValue Cmp = N->getOperand(4); 10582 if (Cmp.getOpcode() != ARMISD::CMPZ) 10583 // Only looking at EQ and NE cases. 10584 return SDValue(); 10585 10586 EVT VT = N->getValueType(0); 10587 SDLoc dl(N); 10588 SDValue LHS = Cmp.getOperand(0); 10589 SDValue RHS = Cmp.getOperand(1); 10590 SDValue FalseVal = N->getOperand(0); 10591 SDValue TrueVal = N->getOperand(1); 10592 SDValue ARMcc = N->getOperand(2); 10593 ARMCC::CondCodes CC = 10594 (ARMCC::CondCodes)cast<ConstantSDNode>(ARMcc)->getZExtValue(); 10595 10596 // BFI is only available on V6T2+. 10597 if (!Subtarget->isThumb1Only() && Subtarget->hasV6T2Ops()) { 10598 SDValue R = PerformCMOVToBFICombine(N, DAG); 10599 if (R) 10600 return R; 10601 } 10602 10603 // Simplify 10604 // mov r1, r0 10605 // cmp r1, x 10606 // mov r0, y 10607 // moveq r0, x 10608 // to 10609 // cmp r0, x 10610 // movne r0, y 10611 // 10612 // mov r1, r0 10613 // cmp r1, x 10614 // mov r0, x 10615 // movne r0, y 10616 // to 10617 // cmp r0, x 10618 // movne r0, y 10619 /// FIXME: Turn this into a target neutral optimization? 10620 SDValue Res; 10621 if (CC == ARMCC::NE && FalseVal == RHS && FalseVal != LHS) { 10622 Res = DAG.getNode(ARMISD::CMOV, dl, VT, LHS, TrueVal, ARMcc, 10623 N->getOperand(3), Cmp); 10624 } else if (CC == ARMCC::EQ && TrueVal == RHS) { 10625 SDValue ARMcc; 10626 SDValue NewCmp = getARMCmp(LHS, RHS, ISD::SETNE, ARMcc, DAG, dl); 10627 Res = DAG.getNode(ARMISD::CMOV, dl, VT, LHS, FalseVal, ARMcc, 10628 N->getOperand(3), NewCmp); 10629 } 10630 10631 if (Res.getNode()) { 10632 APInt KnownZero, KnownOne; 10633 DAG.computeKnownBits(SDValue(N,0), KnownZero, KnownOne); 10634 // Capture demanded bits information that would be otherwise lost. 10635 if (KnownZero == 0xfffffffe) 10636 Res = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Res, 10637 DAG.getValueType(MVT::i1)); 10638 else if (KnownZero == 0xffffff00) 10639 Res = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Res, 10640 DAG.getValueType(MVT::i8)); 10641 else if (KnownZero == 0xffff0000) 10642 Res = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Res, 10643 DAG.getValueType(MVT::i16)); 10644 } 10645 10646 return Res; 10647 } 10648 10649 SDValue ARMTargetLowering::PerformDAGCombine(SDNode *N, 10650 DAGCombinerInfo &DCI) const { 10651 switch (N->getOpcode()) { 10652 default: break; 10653 case ISD::ADDC: return PerformADDCCombine(N, DCI, Subtarget); 10654 case ISD::ADD: return PerformADDCombine(N, DCI, Subtarget); 10655 case ISD::SUB: return PerformSUBCombine(N, DCI); 10656 case ISD::MUL: return PerformMULCombine(N, DCI, Subtarget); 10657 case ISD::OR: return PerformORCombine(N, DCI, Subtarget); 10658 case ISD::XOR: return PerformXORCombine(N, DCI, Subtarget); 10659 case ISD::AND: return PerformANDCombine(N, DCI, Subtarget); 10660 case ARMISD::BFI: return PerformBFICombine(N, DCI); 10661 case ARMISD::VMOVRRD: return PerformVMOVRRDCombine(N, DCI, Subtarget); 10662 case ARMISD::VMOVDRR: return PerformVMOVDRRCombine(N, DCI.DAG); 10663 case ISD::STORE: return PerformSTORECombine(N, DCI); 10664 case ISD::BUILD_VECTOR: return PerformBUILD_VECTORCombine(N, DCI, Subtarget); 10665 case ISD::INSERT_VECTOR_ELT: return PerformInsertEltCombine(N, DCI); 10666 case ISD::VECTOR_SHUFFLE: return PerformVECTOR_SHUFFLECombine(N, DCI.DAG); 10667 case ARMISD::VDUPLANE: return PerformVDUPLANECombine(N, DCI); 10668 case ISD::FP_TO_SINT: 10669 case ISD::FP_TO_UINT: 10670 return PerformVCVTCombine(N, DCI.DAG, Subtarget); 10671 case ISD::FDIV: 10672 return PerformVDIVCombine(N, DCI.DAG, Subtarget); 10673 case ISD::INTRINSIC_WO_CHAIN: return PerformIntrinsicCombine(N, DCI.DAG); 10674 case ISD::SHL: 10675 case ISD::SRA: 10676 case ISD::SRL: return PerformShiftCombine(N, DCI.DAG, Subtarget); 10677 case ISD::SIGN_EXTEND: 10678 case ISD::ZERO_EXTEND: 10679 case ISD::ANY_EXTEND: return PerformExtendCombine(N, DCI.DAG, Subtarget); 10680 case ARMISD::CMOV: return PerformCMOVCombine(N, DCI.DAG); 10681 case ISD::LOAD: return PerformLOADCombine(N, DCI); 10682 case ARMISD::VLD2DUP: 10683 case ARMISD::VLD3DUP: 10684 case ARMISD::VLD4DUP: 10685 return PerformVLDCombine(N, DCI); 10686 case ARMISD::BUILD_VECTOR: 10687 return PerformARMBUILD_VECTORCombine(N, DCI); 10688 case ISD::INTRINSIC_VOID: 10689 case ISD::INTRINSIC_W_CHAIN: 10690 switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) { 10691 case Intrinsic::arm_neon_vld1: 10692 case Intrinsic::arm_neon_vld2: 10693 case Intrinsic::arm_neon_vld3: 10694 case Intrinsic::arm_neon_vld4: 10695 case Intrinsic::arm_neon_vld2lane: 10696 case Intrinsic::arm_neon_vld3lane: 10697 case Intrinsic::arm_neon_vld4lane: 10698 case Intrinsic::arm_neon_vst1: 10699 case Intrinsic::arm_neon_vst2: 10700 case Intrinsic::arm_neon_vst3: 10701 case Intrinsic::arm_neon_vst4: 10702 case Intrinsic::arm_neon_vst2lane: 10703 case Intrinsic::arm_neon_vst3lane: 10704 case Intrinsic::arm_neon_vst4lane: 10705 return PerformVLDCombine(N, DCI); 10706 default: break; 10707 } 10708 break; 10709 } 10710 return SDValue(); 10711 } 10712 10713 bool ARMTargetLowering::isDesirableToTransformToIntegerOp(unsigned Opc, 10714 EVT VT) const { 10715 return (VT == MVT::f32) && (Opc == ISD::LOAD || Opc == ISD::STORE); 10716 } 10717 10718 bool ARMTargetLowering::allowsMisalignedMemoryAccesses(EVT VT, 10719 unsigned, 10720 unsigned, 10721 bool *Fast) const { 10722 // The AllowsUnaliged flag models the SCTLR.A setting in ARM cpus 10723 bool AllowsUnaligned = Subtarget->allowsUnalignedMem(); 10724 10725 switch (VT.getSimpleVT().SimpleTy) { 10726 default: 10727 return false; 10728 case MVT::i8: 10729 case MVT::i16: 10730 case MVT::i32: { 10731 // Unaligned access can use (for example) LRDB, LRDH, LDR 10732 if (AllowsUnaligned) { 10733 if (Fast) 10734 *Fast = Subtarget->hasV7Ops(); 10735 return true; 10736 } 10737 return false; 10738 } 10739 case MVT::f64: 10740 case MVT::v2f64: { 10741 // For any little-endian targets with neon, we can support unaligned ld/st 10742 // of D and Q (e.g. {D0,D1}) registers by using vld1.i8/vst1.i8. 10743 // A big-endian target may also explicitly support unaligned accesses 10744 if (Subtarget->hasNEON() && (AllowsUnaligned || Subtarget->isLittle())) { 10745 if (Fast) 10746 *Fast = true; 10747 return true; 10748 } 10749 return false; 10750 } 10751 } 10752 } 10753 10754 static bool memOpAlign(unsigned DstAlign, unsigned SrcAlign, 10755 unsigned AlignCheck) { 10756 return ((SrcAlign == 0 || SrcAlign % AlignCheck == 0) && 10757 (DstAlign == 0 || DstAlign % AlignCheck == 0)); 10758 } 10759 10760 EVT ARMTargetLowering::getOptimalMemOpType(uint64_t Size, 10761 unsigned DstAlign, unsigned SrcAlign, 10762 bool IsMemset, bool ZeroMemset, 10763 bool MemcpyStrSrc, 10764 MachineFunction &MF) const { 10765 const Function *F = MF.getFunction(); 10766 10767 // See if we can use NEON instructions for this... 10768 if ((!IsMemset || ZeroMemset) && Subtarget->hasNEON() && 10769 !F->hasFnAttribute(Attribute::NoImplicitFloat)) { 10770 bool Fast; 10771 if (Size >= 16 && 10772 (memOpAlign(SrcAlign, DstAlign, 16) || 10773 (allowsMisalignedMemoryAccesses(MVT::v2f64, 0, 1, &Fast) && Fast))) { 10774 return MVT::v2f64; 10775 } else if (Size >= 8 && 10776 (memOpAlign(SrcAlign, DstAlign, 8) || 10777 (allowsMisalignedMemoryAccesses(MVT::f64, 0, 1, &Fast) && 10778 Fast))) { 10779 return MVT::f64; 10780 } 10781 } 10782 10783 // Lowering to i32/i16 if the size permits. 10784 if (Size >= 4) 10785 return MVT::i32; 10786 else if (Size >= 2) 10787 return MVT::i16; 10788 10789 // Let the target-independent logic figure it out. 10790 return MVT::Other; 10791 } 10792 10793 bool ARMTargetLowering::isZExtFree(SDValue Val, EVT VT2) const { 10794 if (Val.getOpcode() != ISD::LOAD) 10795 return false; 10796 10797 EVT VT1 = Val.getValueType(); 10798 if (!VT1.isSimple() || !VT1.isInteger() || 10799 !VT2.isSimple() || !VT2.isInteger()) 10800 return false; 10801 10802 switch (VT1.getSimpleVT().SimpleTy) { 10803 default: break; 10804 case MVT::i1: 10805 case MVT::i8: 10806 case MVT::i16: 10807 // 8-bit and 16-bit loads implicitly zero-extend to 32-bits. 10808 return true; 10809 } 10810 10811 return false; 10812 } 10813 10814 bool ARMTargetLowering::isVectorLoadExtDesirable(SDValue ExtVal) const { 10815 EVT VT = ExtVal.getValueType(); 10816 10817 if (!isTypeLegal(VT)) 10818 return false; 10819 10820 // Don't create a loadext if we can fold the extension into a wide/long 10821 // instruction. 10822 // If there's more than one user instruction, the loadext is desirable no 10823 // matter what. There can be two uses by the same instruction. 10824 if (ExtVal->use_empty() || 10825 !ExtVal->use_begin()->isOnlyUserOf(ExtVal.getNode())) 10826 return true; 10827 10828 SDNode *U = *ExtVal->use_begin(); 10829 if ((U->getOpcode() == ISD::ADD || U->getOpcode() == ISD::SUB || 10830 U->getOpcode() == ISD::SHL || U->getOpcode() == ARMISD::VSHL)) 10831 return false; 10832 10833 return true; 10834 } 10835 10836 bool ARMTargetLowering::allowTruncateForTailCall(Type *Ty1, Type *Ty2) const { 10837 if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy()) 10838 return false; 10839 10840 if (!isTypeLegal(EVT::getEVT(Ty1))) 10841 return false; 10842 10843 assert(Ty1->getPrimitiveSizeInBits() <= 64 && "i128 is probably not a noop"); 10844 10845 // Assuming the caller doesn't have a zeroext or signext return parameter, 10846 // truncation all the way down to i1 is valid. 10847 return true; 10848 } 10849 10850 10851 static bool isLegalT1AddressImmediate(int64_t V, EVT VT) { 10852 if (V < 0) 10853 return false; 10854 10855 unsigned Scale = 1; 10856 switch (VT.getSimpleVT().SimpleTy) { 10857 default: return false; 10858 case MVT::i1: 10859 case MVT::i8: 10860 // Scale == 1; 10861 break; 10862 case MVT::i16: 10863 // Scale == 2; 10864 Scale = 2; 10865 break; 10866 case MVT::i32: 10867 // Scale == 4; 10868 Scale = 4; 10869 break; 10870 } 10871 10872 if ((V & (Scale - 1)) != 0) 10873 return false; 10874 V /= Scale; 10875 return V == (V & ((1LL << 5) - 1)); 10876 } 10877 10878 static bool isLegalT2AddressImmediate(int64_t V, EVT VT, 10879 const ARMSubtarget *Subtarget) { 10880 bool isNeg = false; 10881 if (V < 0) { 10882 isNeg = true; 10883 V = - V; 10884 } 10885 10886 switch (VT.getSimpleVT().SimpleTy) { 10887 default: return false; 10888 case MVT::i1: 10889 case MVT::i8: 10890 case MVT::i16: 10891 case MVT::i32: 10892 // + imm12 or - imm8 10893 if (isNeg) 10894 return V == (V & ((1LL << 8) - 1)); 10895 return V == (V & ((1LL << 12) - 1)); 10896 case MVT::f32: 10897 case MVT::f64: 10898 // Same as ARM mode. FIXME: NEON? 10899 if (!Subtarget->hasVFP2()) 10900 return false; 10901 if ((V & 3) != 0) 10902 return false; 10903 V >>= 2; 10904 return V == (V & ((1LL << 8) - 1)); 10905 } 10906 } 10907 10908 /// isLegalAddressImmediate - Return true if the integer value can be used 10909 /// as the offset of the target addressing mode for load / store of the 10910 /// given type. 10911 static bool isLegalAddressImmediate(int64_t V, EVT VT, 10912 const ARMSubtarget *Subtarget) { 10913 if (V == 0) 10914 return true; 10915 10916 if (!VT.isSimple()) 10917 return false; 10918 10919 if (Subtarget->isThumb1Only()) 10920 return isLegalT1AddressImmediate(V, VT); 10921 else if (Subtarget->isThumb2()) 10922 return isLegalT2AddressImmediate(V, VT, Subtarget); 10923 10924 // ARM mode. 10925 if (V < 0) 10926 V = - V; 10927 switch (VT.getSimpleVT().SimpleTy) { 10928 default: return false; 10929 case MVT::i1: 10930 case MVT::i8: 10931 case MVT::i32: 10932 // +- imm12 10933 return V == (V & ((1LL << 12) - 1)); 10934 case MVT::i16: 10935 // +- imm8 10936 return V == (V & ((1LL << 8) - 1)); 10937 case MVT::f32: 10938 case MVT::f64: 10939 if (!Subtarget->hasVFP2()) // FIXME: NEON? 10940 return false; 10941 if ((V & 3) != 0) 10942 return false; 10943 V >>= 2; 10944 return V == (V & ((1LL << 8) - 1)); 10945 } 10946 } 10947 10948 bool ARMTargetLowering::isLegalT2ScaledAddressingMode(const AddrMode &AM, 10949 EVT VT) const { 10950 int Scale = AM.Scale; 10951 if (Scale < 0) 10952 return false; 10953 10954 switch (VT.getSimpleVT().SimpleTy) { 10955 default: return false; 10956 case MVT::i1: 10957 case MVT::i8: 10958 case MVT::i16: 10959 case MVT::i32: 10960 if (Scale == 1) 10961 return true; 10962 // r + r << imm 10963 Scale = Scale & ~1; 10964 return Scale == 2 || Scale == 4 || Scale == 8; 10965 case MVT::i64: 10966 // r + r 10967 if (((unsigned)AM.HasBaseReg + Scale) <= 2) 10968 return true; 10969 return false; 10970 case MVT::isVoid: 10971 // Note, we allow "void" uses (basically, uses that aren't loads or 10972 // stores), because arm allows folding a scale into many arithmetic 10973 // operations. This should be made more precise and revisited later. 10974 10975 // Allow r << imm, but the imm has to be a multiple of two. 10976 if (Scale & 1) return false; 10977 return isPowerOf2_32(Scale); 10978 } 10979 } 10980 10981 /// isLegalAddressingMode - Return true if the addressing mode represented 10982 /// by AM is legal for this target, for a load/store of the specified type. 10983 bool ARMTargetLowering::isLegalAddressingMode(const DataLayout &DL, 10984 const AddrMode &AM, Type *Ty, 10985 unsigned AS) const { 10986 EVT VT = getValueType(DL, Ty, true); 10987 if (!isLegalAddressImmediate(AM.BaseOffs, VT, Subtarget)) 10988 return false; 10989 10990 // Can never fold addr of global into load/store. 10991 if (AM.BaseGV) 10992 return false; 10993 10994 switch (AM.Scale) { 10995 case 0: // no scale reg, must be "r+i" or "r", or "i". 10996 break; 10997 case 1: 10998 if (Subtarget->isThumb1Only()) 10999 return false; 11000 // FALL THROUGH. 11001 default: 11002 // ARM doesn't support any R+R*scale+imm addr modes. 11003 if (AM.BaseOffs) 11004 return false; 11005 11006 if (!VT.isSimple()) 11007 return false; 11008 11009 if (Subtarget->isThumb2()) 11010 return isLegalT2ScaledAddressingMode(AM, VT); 11011 11012 int Scale = AM.Scale; 11013 switch (VT.getSimpleVT().SimpleTy) { 11014 default: return false; 11015 case MVT::i1: 11016 case MVT::i8: 11017 case MVT::i32: 11018 if (Scale < 0) Scale = -Scale; 11019 if (Scale == 1) 11020 return true; 11021 // r + r << imm 11022 return isPowerOf2_32(Scale & ~1); 11023 case MVT::i16: 11024 case MVT::i64: 11025 // r + r 11026 if (((unsigned)AM.HasBaseReg + Scale) <= 2) 11027 return true; 11028 return false; 11029 11030 case MVT::isVoid: 11031 // Note, we allow "void" uses (basically, uses that aren't loads or 11032 // stores), because arm allows folding a scale into many arithmetic 11033 // operations. This should be made more precise and revisited later. 11034 11035 // Allow r << imm, but the imm has to be a multiple of two. 11036 if (Scale & 1) return false; 11037 return isPowerOf2_32(Scale); 11038 } 11039 } 11040 return true; 11041 } 11042 11043 /// isLegalICmpImmediate - Return true if the specified immediate is legal 11044 /// icmp immediate, that is the target has icmp instructions which can compare 11045 /// a register against the immediate without having to materialize the 11046 /// immediate into a register. 11047 bool ARMTargetLowering::isLegalICmpImmediate(int64_t Imm) const { 11048 // Thumb2 and ARM modes can use cmn for negative immediates. 11049 if (!Subtarget->isThumb()) 11050 return ARM_AM::getSOImmVal(std::abs(Imm)) != -1; 11051 if (Subtarget->isThumb2()) 11052 return ARM_AM::getT2SOImmVal(std::abs(Imm)) != -1; 11053 // Thumb1 doesn't have cmn, and only 8-bit immediates. 11054 return Imm >= 0 && Imm <= 255; 11055 } 11056 11057 /// isLegalAddImmediate - Return true if the specified immediate is a legal add 11058 /// *or sub* immediate, that is the target has add or sub instructions which can 11059 /// add a register with the immediate without having to materialize the 11060 /// immediate into a register. 11061 bool ARMTargetLowering::isLegalAddImmediate(int64_t Imm) const { 11062 // Same encoding for add/sub, just flip the sign. 11063 int64_t AbsImm = std::abs(Imm); 11064 if (!Subtarget->isThumb()) 11065 return ARM_AM::getSOImmVal(AbsImm) != -1; 11066 if (Subtarget->isThumb2()) 11067 return ARM_AM::getT2SOImmVal(AbsImm) != -1; 11068 // Thumb1 only has 8-bit unsigned immediate. 11069 return AbsImm >= 0 && AbsImm <= 255; 11070 } 11071 11072 static bool getARMIndexedAddressParts(SDNode *Ptr, EVT VT, 11073 bool isSEXTLoad, SDValue &Base, 11074 SDValue &Offset, bool &isInc, 11075 SelectionDAG &DAG) { 11076 if (Ptr->getOpcode() != ISD::ADD && Ptr->getOpcode() != ISD::SUB) 11077 return false; 11078 11079 if (VT == MVT::i16 || ((VT == MVT::i8 || VT == MVT::i1) && isSEXTLoad)) { 11080 // AddressingMode 3 11081 Base = Ptr->getOperand(0); 11082 if (ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(Ptr->getOperand(1))) { 11083 int RHSC = (int)RHS->getZExtValue(); 11084 if (RHSC < 0 && RHSC > -256) { 11085 assert(Ptr->getOpcode() == ISD::ADD); 11086 isInc = false; 11087 Offset = DAG.getConstant(-RHSC, SDLoc(Ptr), RHS->getValueType(0)); 11088 return true; 11089 } 11090 } 11091 isInc = (Ptr->getOpcode() == ISD::ADD); 11092 Offset = Ptr->getOperand(1); 11093 return true; 11094 } else if (VT == MVT::i32 || VT == MVT::i8 || VT == MVT::i1) { 11095 // AddressingMode 2 11096 if (ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(Ptr->getOperand(1))) { 11097 int RHSC = (int)RHS->getZExtValue(); 11098 if (RHSC < 0 && RHSC > -0x1000) { 11099 assert(Ptr->getOpcode() == ISD::ADD); 11100 isInc = false; 11101 Offset = DAG.getConstant(-RHSC, SDLoc(Ptr), RHS->getValueType(0)); 11102 Base = Ptr->getOperand(0); 11103 return true; 11104 } 11105 } 11106 11107 if (Ptr->getOpcode() == ISD::ADD) { 11108 isInc = true; 11109 ARM_AM::ShiftOpc ShOpcVal= 11110 ARM_AM::getShiftOpcForNode(Ptr->getOperand(0).getOpcode()); 11111 if (ShOpcVal != ARM_AM::no_shift) { 11112 Base = Ptr->getOperand(1); 11113 Offset = Ptr->getOperand(0); 11114 } else { 11115 Base = Ptr->getOperand(0); 11116 Offset = Ptr->getOperand(1); 11117 } 11118 return true; 11119 } 11120 11121 isInc = (Ptr->getOpcode() == ISD::ADD); 11122 Base = Ptr->getOperand(0); 11123 Offset = Ptr->getOperand(1); 11124 return true; 11125 } 11126 11127 // FIXME: Use VLDM / VSTM to emulate indexed FP load / store. 11128 return false; 11129 } 11130 11131 static bool getT2IndexedAddressParts(SDNode *Ptr, EVT VT, 11132 bool isSEXTLoad, SDValue &Base, 11133 SDValue &Offset, bool &isInc, 11134 SelectionDAG &DAG) { 11135 if (Ptr->getOpcode() != ISD::ADD && Ptr->getOpcode() != ISD::SUB) 11136 return false; 11137 11138 Base = Ptr->getOperand(0); 11139 if (ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(Ptr->getOperand(1))) { 11140 int RHSC = (int)RHS->getZExtValue(); 11141 if (RHSC < 0 && RHSC > -0x100) { // 8 bits. 11142 assert(Ptr->getOpcode() == ISD::ADD); 11143 isInc = false; 11144 Offset = DAG.getConstant(-RHSC, SDLoc(Ptr), RHS->getValueType(0)); 11145 return true; 11146 } else if (RHSC > 0 && RHSC < 0x100) { // 8 bit, no zero. 11147 isInc = Ptr->getOpcode() == ISD::ADD; 11148 Offset = DAG.getConstant(RHSC, SDLoc(Ptr), RHS->getValueType(0)); 11149 return true; 11150 } 11151 } 11152 11153 return false; 11154 } 11155 11156 /// getPreIndexedAddressParts - returns true by value, base pointer and 11157 /// offset pointer and addressing mode by reference if the node's address 11158 /// can be legally represented as pre-indexed load / store address. 11159 bool 11160 ARMTargetLowering::getPreIndexedAddressParts(SDNode *N, SDValue &Base, 11161 SDValue &Offset, 11162 ISD::MemIndexedMode &AM, 11163 SelectionDAG &DAG) const { 11164 if (Subtarget->isThumb1Only()) 11165 return false; 11166 11167 EVT VT; 11168 SDValue Ptr; 11169 bool isSEXTLoad = false; 11170 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) { 11171 Ptr = LD->getBasePtr(); 11172 VT = LD->getMemoryVT(); 11173 isSEXTLoad = LD->getExtensionType() == ISD::SEXTLOAD; 11174 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) { 11175 Ptr = ST->getBasePtr(); 11176 VT = ST->getMemoryVT(); 11177 } else 11178 return false; 11179 11180 bool isInc; 11181 bool isLegal = false; 11182 if (Subtarget->isThumb2()) 11183 isLegal = getT2IndexedAddressParts(Ptr.getNode(), VT, isSEXTLoad, Base, 11184 Offset, isInc, DAG); 11185 else 11186 isLegal = getARMIndexedAddressParts(Ptr.getNode(), VT, isSEXTLoad, Base, 11187 Offset, isInc, DAG); 11188 if (!isLegal) 11189 return false; 11190 11191 AM = isInc ? ISD::PRE_INC : ISD::PRE_DEC; 11192 return true; 11193 } 11194 11195 /// getPostIndexedAddressParts - returns true by value, base pointer and 11196 /// offset pointer and addressing mode by reference if this node can be 11197 /// combined with a load / store to form a post-indexed load / store. 11198 bool ARMTargetLowering::getPostIndexedAddressParts(SDNode *N, SDNode *Op, 11199 SDValue &Base, 11200 SDValue &Offset, 11201 ISD::MemIndexedMode &AM, 11202 SelectionDAG &DAG) const { 11203 if (Subtarget->isThumb1Only()) 11204 return false; 11205 11206 EVT VT; 11207 SDValue Ptr; 11208 bool isSEXTLoad = false; 11209 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) { 11210 VT = LD->getMemoryVT(); 11211 Ptr = LD->getBasePtr(); 11212 isSEXTLoad = LD->getExtensionType() == ISD::SEXTLOAD; 11213 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) { 11214 VT = ST->getMemoryVT(); 11215 Ptr = ST->getBasePtr(); 11216 } else 11217 return false; 11218 11219 bool isInc; 11220 bool isLegal = false; 11221 if (Subtarget->isThumb2()) 11222 isLegal = getT2IndexedAddressParts(Op, VT, isSEXTLoad, Base, Offset, 11223 isInc, DAG); 11224 else 11225 isLegal = getARMIndexedAddressParts(Op, VT, isSEXTLoad, Base, Offset, 11226 isInc, DAG); 11227 if (!isLegal) 11228 return false; 11229 11230 if (Ptr != Base) { 11231 // Swap base ptr and offset to catch more post-index load / store when 11232 // it's legal. In Thumb2 mode, offset must be an immediate. 11233 if (Ptr == Offset && Op->getOpcode() == ISD::ADD && 11234 !Subtarget->isThumb2()) 11235 std::swap(Base, Offset); 11236 11237 // Post-indexed load / store update the base pointer. 11238 if (Ptr != Base) 11239 return false; 11240 } 11241 11242 AM = isInc ? ISD::POST_INC : ISD::POST_DEC; 11243 return true; 11244 } 11245 11246 void ARMTargetLowering::computeKnownBitsForTargetNode(const SDValue Op, 11247 APInt &KnownZero, 11248 APInt &KnownOne, 11249 const SelectionDAG &DAG, 11250 unsigned Depth) const { 11251 unsigned BitWidth = KnownOne.getBitWidth(); 11252 KnownZero = KnownOne = APInt(BitWidth, 0); 11253 switch (Op.getOpcode()) { 11254 default: break; 11255 case ARMISD::ADDC: 11256 case ARMISD::ADDE: 11257 case ARMISD::SUBC: 11258 case ARMISD::SUBE: 11259 // These nodes' second result is a boolean 11260 if (Op.getResNo() == 0) 11261 break; 11262 KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - 1); 11263 break; 11264 case ARMISD::CMOV: { 11265 // Bits are known zero/one if known on the LHS and RHS. 11266 DAG.computeKnownBits(Op.getOperand(0), KnownZero, KnownOne, Depth+1); 11267 if (KnownZero == 0 && KnownOne == 0) return; 11268 11269 APInt KnownZeroRHS, KnownOneRHS; 11270 DAG.computeKnownBits(Op.getOperand(1), KnownZeroRHS, KnownOneRHS, Depth+1); 11271 KnownZero &= KnownZeroRHS; 11272 KnownOne &= KnownOneRHS; 11273 return; 11274 } 11275 case ISD::INTRINSIC_W_CHAIN: { 11276 ConstantSDNode *CN = cast<ConstantSDNode>(Op->getOperand(1)); 11277 Intrinsic::ID IntID = static_cast<Intrinsic::ID>(CN->getZExtValue()); 11278 switch (IntID) { 11279 default: return; 11280 case Intrinsic::arm_ldaex: 11281 case Intrinsic::arm_ldrex: { 11282 EVT VT = cast<MemIntrinsicSDNode>(Op)->getMemoryVT(); 11283 unsigned MemBits = VT.getScalarType().getSizeInBits(); 11284 KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - MemBits); 11285 return; 11286 } 11287 } 11288 } 11289 } 11290 } 11291 11292 //===----------------------------------------------------------------------===// 11293 // ARM Inline Assembly Support 11294 //===----------------------------------------------------------------------===// 11295 11296 bool ARMTargetLowering::ExpandInlineAsm(CallInst *CI) const { 11297 // Looking for "rev" which is V6+. 11298 if (!Subtarget->hasV6Ops()) 11299 return false; 11300 11301 InlineAsm *IA = cast<InlineAsm>(CI->getCalledValue()); 11302 std::string AsmStr = IA->getAsmString(); 11303 SmallVector<StringRef, 4> AsmPieces; 11304 SplitString(AsmStr, AsmPieces, ";\n"); 11305 11306 switch (AsmPieces.size()) { 11307 default: return false; 11308 case 1: 11309 AsmStr = AsmPieces[0]; 11310 AsmPieces.clear(); 11311 SplitString(AsmStr, AsmPieces, " \t,"); 11312 11313 // rev $0, $1 11314 if (AsmPieces.size() == 3 && 11315 AsmPieces[0] == "rev" && AsmPieces[1] == "$0" && AsmPieces[2] == "$1" && 11316 IA->getConstraintString().compare(0, 4, "=l,l") == 0) { 11317 IntegerType *Ty = dyn_cast<IntegerType>(CI->getType()); 11318 if (Ty && Ty->getBitWidth() == 32) 11319 return IntrinsicLowering::LowerToByteSwap(CI); 11320 } 11321 break; 11322 } 11323 11324 return false; 11325 } 11326 11327 /// getConstraintType - Given a constraint letter, return the type of 11328 /// constraint it is for this target. 11329 ARMTargetLowering::ConstraintType 11330 ARMTargetLowering::getConstraintType(StringRef Constraint) const { 11331 if (Constraint.size() == 1) { 11332 switch (Constraint[0]) { 11333 default: break; 11334 case 'l': return C_RegisterClass; 11335 case 'w': return C_RegisterClass; 11336 case 'h': return C_RegisterClass; 11337 case 'x': return C_RegisterClass; 11338 case 't': return C_RegisterClass; 11339 case 'j': return C_Other; // Constant for movw. 11340 // An address with a single base register. Due to the way we 11341 // currently handle addresses it is the same as an 'r' memory constraint. 11342 case 'Q': return C_Memory; 11343 } 11344 } else if (Constraint.size() == 2) { 11345 switch (Constraint[0]) { 11346 default: break; 11347 // All 'U+' constraints are addresses. 11348 case 'U': return C_Memory; 11349 } 11350 } 11351 return TargetLowering::getConstraintType(Constraint); 11352 } 11353 11354 /// Examine constraint type and operand type and determine a weight value. 11355 /// This object must already have been set up with the operand type 11356 /// and the current alternative constraint selected. 11357 TargetLowering::ConstraintWeight 11358 ARMTargetLowering::getSingleConstraintMatchWeight( 11359 AsmOperandInfo &info, const char *constraint) const { 11360 ConstraintWeight weight = CW_Invalid; 11361 Value *CallOperandVal = info.CallOperandVal; 11362 // If we don't have a value, we can't do a match, 11363 // but allow it at the lowest weight. 11364 if (!CallOperandVal) 11365 return CW_Default; 11366 Type *type = CallOperandVal->getType(); 11367 // Look at the constraint type. 11368 switch (*constraint) { 11369 default: 11370 weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint); 11371 break; 11372 case 'l': 11373 if (type->isIntegerTy()) { 11374 if (Subtarget->isThumb()) 11375 weight = CW_SpecificReg; 11376 else 11377 weight = CW_Register; 11378 } 11379 break; 11380 case 'w': 11381 if (type->isFloatingPointTy()) 11382 weight = CW_Register; 11383 break; 11384 } 11385 return weight; 11386 } 11387 11388 typedef std::pair<unsigned, const TargetRegisterClass*> RCPair; 11389 RCPair ARMTargetLowering::getRegForInlineAsmConstraint( 11390 const TargetRegisterInfo *TRI, StringRef Constraint, MVT VT) const { 11391 if (Constraint.size() == 1) { 11392 // GCC ARM Constraint Letters 11393 switch (Constraint[0]) { 11394 case 'l': // Low regs or general regs. 11395 if (Subtarget->isThumb()) 11396 return RCPair(0U, &ARM::tGPRRegClass); 11397 return RCPair(0U, &ARM::GPRRegClass); 11398 case 'h': // High regs or no regs. 11399 if (Subtarget->isThumb()) 11400 return RCPair(0U, &ARM::hGPRRegClass); 11401 break; 11402 case 'r': 11403 if (Subtarget->isThumb1Only()) 11404 return RCPair(0U, &ARM::tGPRRegClass); 11405 return RCPair(0U, &ARM::GPRRegClass); 11406 case 'w': 11407 if (VT == MVT::Other) 11408 break; 11409 if (VT == MVT::f32) 11410 return RCPair(0U, &ARM::SPRRegClass); 11411 if (VT.getSizeInBits() == 64) 11412 return RCPair(0U, &ARM::DPRRegClass); 11413 if (VT.getSizeInBits() == 128) 11414 return RCPair(0U, &ARM::QPRRegClass); 11415 break; 11416 case 'x': 11417 if (VT == MVT::Other) 11418 break; 11419 if (VT == MVT::f32) 11420 return RCPair(0U, &ARM::SPR_8RegClass); 11421 if (VT.getSizeInBits() == 64) 11422 return RCPair(0U, &ARM::DPR_8RegClass); 11423 if (VT.getSizeInBits() == 128) 11424 return RCPair(0U, &ARM::QPR_8RegClass); 11425 break; 11426 case 't': 11427 if (VT == MVT::f32) 11428 return RCPair(0U, &ARM::SPRRegClass); 11429 break; 11430 } 11431 } 11432 if (StringRef("{cc}").equals_lower(Constraint)) 11433 return std::make_pair(unsigned(ARM::CPSR), &ARM::CCRRegClass); 11434 11435 return TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT); 11436 } 11437 11438 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops 11439 /// vector. If it is invalid, don't add anything to Ops. 11440 void ARMTargetLowering::LowerAsmOperandForConstraint(SDValue Op, 11441 std::string &Constraint, 11442 std::vector<SDValue>&Ops, 11443 SelectionDAG &DAG) const { 11444 SDValue Result; 11445 11446 // Currently only support length 1 constraints. 11447 if (Constraint.length() != 1) return; 11448 11449 char ConstraintLetter = Constraint[0]; 11450 switch (ConstraintLetter) { 11451 default: break; 11452 case 'j': 11453 case 'I': case 'J': case 'K': case 'L': 11454 case 'M': case 'N': case 'O': 11455 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op); 11456 if (!C) 11457 return; 11458 11459 int64_t CVal64 = C->getSExtValue(); 11460 int CVal = (int) CVal64; 11461 // None of these constraints allow values larger than 32 bits. Check 11462 // that the value fits in an int. 11463 if (CVal != CVal64) 11464 return; 11465 11466 switch (ConstraintLetter) { 11467 case 'j': 11468 // Constant suitable for movw, must be between 0 and 11469 // 65535. 11470 if (Subtarget->hasV6T2Ops()) 11471 if (CVal >= 0 && CVal <= 65535) 11472 break; 11473 return; 11474 case 'I': 11475 if (Subtarget->isThumb1Only()) { 11476 // This must be a constant between 0 and 255, for ADD 11477 // immediates. 11478 if (CVal >= 0 && CVal <= 255) 11479 break; 11480 } else if (Subtarget->isThumb2()) { 11481 // A constant that can be used as an immediate value in a 11482 // data-processing instruction. 11483 if (ARM_AM::getT2SOImmVal(CVal) != -1) 11484 break; 11485 } else { 11486 // A constant that can be used as an immediate value in a 11487 // data-processing instruction. 11488 if (ARM_AM::getSOImmVal(CVal) != -1) 11489 break; 11490 } 11491 return; 11492 11493 case 'J': 11494 if (Subtarget->isThumb1Only()) { 11495 // This must be a constant between -255 and -1, for negated ADD 11496 // immediates. This can be used in GCC with an "n" modifier that 11497 // prints the negated value, for use with SUB instructions. It is 11498 // not useful otherwise but is implemented for compatibility. 11499 if (CVal >= -255 && CVal <= -1) 11500 break; 11501 } else { 11502 // This must be a constant between -4095 and 4095. It is not clear 11503 // what this constraint is intended for. Implemented for 11504 // compatibility with GCC. 11505 if (CVal >= -4095 && CVal <= 4095) 11506 break; 11507 } 11508 return; 11509 11510 case 'K': 11511 if (Subtarget->isThumb1Only()) { 11512 // A 32-bit value where only one byte has a nonzero value. Exclude 11513 // zero to match GCC. This constraint is used by GCC internally for 11514 // constants that can be loaded with a move/shift combination. 11515 // It is not useful otherwise but is implemented for compatibility. 11516 if (CVal != 0 && ARM_AM::isThumbImmShiftedVal(CVal)) 11517 break; 11518 } else if (Subtarget->isThumb2()) { 11519 // A constant whose bitwise inverse can be used as an immediate 11520 // value in a data-processing instruction. This can be used in GCC 11521 // with a "B" modifier that prints the inverted value, for use with 11522 // BIC and MVN instructions. It is not useful otherwise but is 11523 // implemented for compatibility. 11524 if (ARM_AM::getT2SOImmVal(~CVal) != -1) 11525 break; 11526 } else { 11527 // A constant whose bitwise inverse can be used as an immediate 11528 // value in a data-processing instruction. This can be used in GCC 11529 // with a "B" modifier that prints the inverted value, for use with 11530 // BIC and MVN instructions. It is not useful otherwise but is 11531 // implemented for compatibility. 11532 if (ARM_AM::getSOImmVal(~CVal) != -1) 11533 break; 11534 } 11535 return; 11536 11537 case 'L': 11538 if (Subtarget->isThumb1Only()) { 11539 // This must be a constant between -7 and 7, 11540 // for 3-operand ADD/SUB immediate instructions. 11541 if (CVal >= -7 && CVal < 7) 11542 break; 11543 } else if (Subtarget->isThumb2()) { 11544 // A constant whose negation can be used as an immediate value in a 11545 // data-processing instruction. This can be used in GCC with an "n" 11546 // modifier that prints the negated value, for use with SUB 11547 // instructions. It is not useful otherwise but is implemented for 11548 // compatibility. 11549 if (ARM_AM::getT2SOImmVal(-CVal) != -1) 11550 break; 11551 } else { 11552 // A constant whose negation can be used as an immediate value in a 11553 // data-processing instruction. This can be used in GCC with an "n" 11554 // modifier that prints the negated value, for use with SUB 11555 // instructions. It is not useful otherwise but is implemented for 11556 // compatibility. 11557 if (ARM_AM::getSOImmVal(-CVal) != -1) 11558 break; 11559 } 11560 return; 11561 11562 case 'M': 11563 if (Subtarget->isThumb1Only()) { 11564 // This must be a multiple of 4 between 0 and 1020, for 11565 // ADD sp + immediate. 11566 if ((CVal >= 0 && CVal <= 1020) && ((CVal & 3) == 0)) 11567 break; 11568 } else { 11569 // A power of two or a constant between 0 and 32. This is used in 11570 // GCC for the shift amount on shifted register operands, but it is 11571 // useful in general for any shift amounts. 11572 if ((CVal >= 0 && CVal <= 32) || ((CVal & (CVal - 1)) == 0)) 11573 break; 11574 } 11575 return; 11576 11577 case 'N': 11578 if (Subtarget->isThumb()) { // FIXME thumb2 11579 // This must be a constant between 0 and 31, for shift amounts. 11580 if (CVal >= 0 && CVal <= 31) 11581 break; 11582 } 11583 return; 11584 11585 case 'O': 11586 if (Subtarget->isThumb()) { // FIXME thumb2 11587 // This must be a multiple of 4 between -508 and 508, for 11588 // ADD/SUB sp = sp + immediate. 11589 if ((CVal >= -508 && CVal <= 508) && ((CVal & 3) == 0)) 11590 break; 11591 } 11592 return; 11593 } 11594 Result = DAG.getTargetConstant(CVal, SDLoc(Op), Op.getValueType()); 11595 break; 11596 } 11597 11598 if (Result.getNode()) { 11599 Ops.push_back(Result); 11600 return; 11601 } 11602 return TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG); 11603 } 11604 11605 static RTLIB::Libcall getDivRemLibcall( 11606 const SDNode *N, MVT::SimpleValueType SVT) { 11607 assert((N->getOpcode() == ISD::SDIVREM || N->getOpcode() == ISD::UDIVREM || 11608 N->getOpcode() == ISD::SREM || N->getOpcode() == ISD::UREM) && 11609 "Unhandled Opcode in getDivRemLibcall"); 11610 bool isSigned = N->getOpcode() == ISD::SDIVREM || 11611 N->getOpcode() == ISD::SREM; 11612 RTLIB::Libcall LC; 11613 switch (SVT) { 11614 default: llvm_unreachable("Unexpected request for libcall!"); 11615 case MVT::i8: LC = isSigned ? RTLIB::SDIVREM_I8 : RTLIB::UDIVREM_I8; break; 11616 case MVT::i16: LC = isSigned ? RTLIB::SDIVREM_I16 : RTLIB::UDIVREM_I16; break; 11617 case MVT::i32: LC = isSigned ? RTLIB::SDIVREM_I32 : RTLIB::UDIVREM_I32; break; 11618 case MVT::i64: LC = isSigned ? RTLIB::SDIVREM_I64 : RTLIB::UDIVREM_I64; break; 11619 } 11620 return LC; 11621 } 11622 11623 static TargetLowering::ArgListTy getDivRemArgList( 11624 const SDNode *N, LLVMContext *Context) { 11625 assert((N->getOpcode() == ISD::SDIVREM || N->getOpcode() == ISD::UDIVREM || 11626 N->getOpcode() == ISD::SREM || N->getOpcode() == ISD::UREM) && 11627 "Unhandled Opcode in getDivRemArgList"); 11628 bool isSigned = N->getOpcode() == ISD::SDIVREM || 11629 N->getOpcode() == ISD::SREM; 11630 TargetLowering::ArgListTy Args; 11631 TargetLowering::ArgListEntry Entry; 11632 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) { 11633 EVT ArgVT = N->getOperand(i).getValueType(); 11634 Type *ArgTy = ArgVT.getTypeForEVT(*Context); 11635 Entry.Node = N->getOperand(i); 11636 Entry.Ty = ArgTy; 11637 Entry.isSExt = isSigned; 11638 Entry.isZExt = !isSigned; 11639 Args.push_back(Entry); 11640 } 11641 return Args; 11642 } 11643 11644 SDValue ARMTargetLowering::LowerDivRem(SDValue Op, SelectionDAG &DAG) const { 11645 assert((Subtarget->isTargetAEABI() || Subtarget->isTargetAndroid()) && 11646 "Register-based DivRem lowering only"); 11647 unsigned Opcode = Op->getOpcode(); 11648 assert((Opcode == ISD::SDIVREM || Opcode == ISD::UDIVREM) && 11649 "Invalid opcode for Div/Rem lowering"); 11650 bool isSigned = (Opcode == ISD::SDIVREM); 11651 EVT VT = Op->getValueType(0); 11652 Type *Ty = VT.getTypeForEVT(*DAG.getContext()); 11653 11654 RTLIB::Libcall LC = getDivRemLibcall(Op.getNode(), 11655 VT.getSimpleVT().SimpleTy); 11656 SDValue InChain = DAG.getEntryNode(); 11657 11658 TargetLowering::ArgListTy Args = getDivRemArgList(Op.getNode(), 11659 DAG.getContext()); 11660 11661 SDValue Callee = DAG.getExternalSymbol(getLibcallName(LC), 11662 getPointerTy(DAG.getDataLayout())); 11663 11664 Type *RetTy = (Type*)StructType::get(Ty, Ty, nullptr); 11665 11666 SDLoc dl(Op); 11667 TargetLowering::CallLoweringInfo CLI(DAG); 11668 CLI.setDebugLoc(dl).setChain(InChain) 11669 .setCallee(getLibcallCallingConv(LC), RetTy, Callee, std::move(Args), 0) 11670 .setInRegister().setSExtResult(isSigned).setZExtResult(!isSigned); 11671 11672 std::pair<SDValue, SDValue> CallInfo = LowerCallTo(CLI); 11673 return CallInfo.first; 11674 } 11675 11676 // Lowers REM using divmod helpers 11677 // see RTABI section 4.2/4.3 11678 SDValue ARMTargetLowering::LowerREM(SDNode *N, SelectionDAG &DAG) const { 11679 // Build return types (div and rem) 11680 std::vector<Type*> RetTyParams; 11681 Type *RetTyElement; 11682 11683 switch (N->getValueType(0).getSimpleVT().SimpleTy) { 11684 default: llvm_unreachable("Unexpected request for libcall!"); 11685 case MVT::i8: RetTyElement = Type::getInt8Ty(*DAG.getContext()); break; 11686 case MVT::i16: RetTyElement = Type::getInt16Ty(*DAG.getContext()); break; 11687 case MVT::i32: RetTyElement = Type::getInt32Ty(*DAG.getContext()); break; 11688 case MVT::i64: RetTyElement = Type::getInt64Ty(*DAG.getContext()); break; 11689 } 11690 11691 RetTyParams.push_back(RetTyElement); 11692 RetTyParams.push_back(RetTyElement); 11693 ArrayRef<Type*> ret = ArrayRef<Type*>(RetTyParams); 11694 Type *RetTy = StructType::get(*DAG.getContext(), ret); 11695 11696 RTLIB::Libcall LC = getDivRemLibcall(N, N->getValueType(0).getSimpleVT(). 11697 SimpleTy); 11698 SDValue InChain = DAG.getEntryNode(); 11699 TargetLowering::ArgListTy Args = getDivRemArgList(N, DAG.getContext()); 11700 bool isSigned = N->getOpcode() == ISD::SREM; 11701 SDValue Callee = DAG.getExternalSymbol(getLibcallName(LC), 11702 getPointerTy(DAG.getDataLayout())); 11703 11704 // Lower call 11705 CallLoweringInfo CLI(DAG); 11706 CLI.setChain(InChain) 11707 .setCallee(CallingConv::ARM_AAPCS, RetTy, Callee, std::move(Args), 0) 11708 .setSExtResult(isSigned).setZExtResult(!isSigned).setDebugLoc(SDLoc(N)); 11709 std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI); 11710 11711 // Return second (rem) result operand (first contains div) 11712 SDNode *ResNode = CallResult.first.getNode(); 11713 assert(ResNode->getNumOperands() == 2 && "divmod should return two operands"); 11714 return ResNode->getOperand(1); 11715 } 11716 11717 SDValue 11718 ARMTargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op, SelectionDAG &DAG) const { 11719 assert(Subtarget->isTargetWindows() && "unsupported target platform"); 11720 SDLoc DL(Op); 11721 11722 // Get the inputs. 11723 SDValue Chain = Op.getOperand(0); 11724 SDValue Size = Op.getOperand(1); 11725 11726 SDValue Words = DAG.getNode(ISD::SRL, DL, MVT::i32, Size, 11727 DAG.getConstant(2, DL, MVT::i32)); 11728 11729 SDValue Flag; 11730 Chain = DAG.getCopyToReg(Chain, DL, ARM::R4, Words, Flag); 11731 Flag = Chain.getValue(1); 11732 11733 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue); 11734 Chain = DAG.getNode(ARMISD::WIN__CHKSTK, DL, NodeTys, Chain, Flag); 11735 11736 SDValue NewSP = DAG.getCopyFromReg(Chain, DL, ARM::SP, MVT::i32); 11737 Chain = NewSP.getValue(1); 11738 11739 SDValue Ops[2] = { NewSP, Chain }; 11740 return DAG.getMergeValues(Ops, DL); 11741 } 11742 11743 SDValue ARMTargetLowering::LowerFP_EXTEND(SDValue Op, SelectionDAG &DAG) const { 11744 assert(Op.getValueType() == MVT::f64 && Subtarget->isFPOnlySP() && 11745 "Unexpected type for custom-lowering FP_EXTEND"); 11746 11747 RTLIB::Libcall LC; 11748 LC = RTLIB::getFPEXT(Op.getOperand(0).getValueType(), Op.getValueType()); 11749 11750 SDValue SrcVal = Op.getOperand(0); 11751 return makeLibCall(DAG, LC, Op.getValueType(), SrcVal, /*isSigned*/ false, 11752 SDLoc(Op)).first; 11753 } 11754 11755 SDValue ARMTargetLowering::LowerFP_ROUND(SDValue Op, SelectionDAG &DAG) const { 11756 assert(Op.getOperand(0).getValueType() == MVT::f64 && 11757 Subtarget->isFPOnlySP() && 11758 "Unexpected type for custom-lowering FP_ROUND"); 11759 11760 RTLIB::Libcall LC; 11761 LC = RTLIB::getFPROUND(Op.getOperand(0).getValueType(), Op.getValueType()); 11762 11763 SDValue SrcVal = Op.getOperand(0); 11764 return makeLibCall(DAG, LC, Op.getValueType(), SrcVal, /*isSigned*/ false, 11765 SDLoc(Op)).first; 11766 } 11767 11768 bool 11769 ARMTargetLowering::isOffsetFoldingLegal(const GlobalAddressSDNode *GA) const { 11770 // The ARM target isn't yet aware of offsets. 11771 return false; 11772 } 11773 11774 bool ARM::isBitFieldInvertedMask(unsigned v) { 11775 if (v == 0xffffffff) 11776 return false; 11777 11778 // there can be 1's on either or both "outsides", all the "inside" 11779 // bits must be 0's 11780 return isShiftedMask_32(~v); 11781 } 11782 11783 /// isFPImmLegal - Returns true if the target can instruction select the 11784 /// specified FP immediate natively. If false, the legalizer will 11785 /// materialize the FP immediate as a load from a constant pool. 11786 bool ARMTargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT) const { 11787 if (!Subtarget->hasVFP3()) 11788 return false; 11789 if (VT == MVT::f32) 11790 return ARM_AM::getFP32Imm(Imm) != -1; 11791 if (VT == MVT::f64 && !Subtarget->isFPOnlySP()) 11792 return ARM_AM::getFP64Imm(Imm) != -1; 11793 return false; 11794 } 11795 11796 /// getTgtMemIntrinsic - Represent NEON load and store intrinsics as 11797 /// MemIntrinsicNodes. The associated MachineMemOperands record the alignment 11798 /// specified in the intrinsic calls. 11799 bool ARMTargetLowering::getTgtMemIntrinsic(IntrinsicInfo &Info, 11800 const CallInst &I, 11801 unsigned Intrinsic) const { 11802 switch (Intrinsic) { 11803 case Intrinsic::arm_neon_vld1: 11804 case Intrinsic::arm_neon_vld2: 11805 case Intrinsic::arm_neon_vld3: 11806 case Intrinsic::arm_neon_vld4: 11807 case Intrinsic::arm_neon_vld2lane: 11808 case Intrinsic::arm_neon_vld3lane: 11809 case Intrinsic::arm_neon_vld4lane: { 11810 Info.opc = ISD::INTRINSIC_W_CHAIN; 11811 // Conservatively set memVT to the entire set of vectors loaded. 11812 auto &DL = I.getCalledFunction()->getParent()->getDataLayout(); 11813 uint64_t NumElts = DL.getTypeSizeInBits(I.getType()) / 64; 11814 Info.memVT = EVT::getVectorVT(I.getType()->getContext(), MVT::i64, NumElts); 11815 Info.ptrVal = I.getArgOperand(0); 11816 Info.offset = 0; 11817 Value *AlignArg = I.getArgOperand(I.getNumArgOperands() - 1); 11818 Info.align = cast<ConstantInt>(AlignArg)->getZExtValue(); 11819 Info.vol = false; // volatile loads with NEON intrinsics not supported 11820 Info.readMem = true; 11821 Info.writeMem = false; 11822 return true; 11823 } 11824 case Intrinsic::arm_neon_vst1: 11825 case Intrinsic::arm_neon_vst2: 11826 case Intrinsic::arm_neon_vst3: 11827 case Intrinsic::arm_neon_vst4: 11828 case Intrinsic::arm_neon_vst2lane: 11829 case Intrinsic::arm_neon_vst3lane: 11830 case Intrinsic::arm_neon_vst4lane: { 11831 Info.opc = ISD::INTRINSIC_VOID; 11832 // Conservatively set memVT to the entire set of vectors stored. 11833 auto &DL = I.getCalledFunction()->getParent()->getDataLayout(); 11834 unsigned NumElts = 0; 11835 for (unsigned ArgI = 1, ArgE = I.getNumArgOperands(); ArgI < ArgE; ++ArgI) { 11836 Type *ArgTy = I.getArgOperand(ArgI)->getType(); 11837 if (!ArgTy->isVectorTy()) 11838 break; 11839 NumElts += DL.getTypeSizeInBits(ArgTy) / 64; 11840 } 11841 Info.memVT = EVT::getVectorVT(I.getType()->getContext(), MVT::i64, NumElts); 11842 Info.ptrVal = I.getArgOperand(0); 11843 Info.offset = 0; 11844 Value *AlignArg = I.getArgOperand(I.getNumArgOperands() - 1); 11845 Info.align = cast<ConstantInt>(AlignArg)->getZExtValue(); 11846 Info.vol = false; // volatile stores with NEON intrinsics not supported 11847 Info.readMem = false; 11848 Info.writeMem = true; 11849 return true; 11850 } 11851 case Intrinsic::arm_ldaex: 11852 case Intrinsic::arm_ldrex: { 11853 auto &DL = I.getCalledFunction()->getParent()->getDataLayout(); 11854 PointerType *PtrTy = cast<PointerType>(I.getArgOperand(0)->getType()); 11855 Info.opc = ISD::INTRINSIC_W_CHAIN; 11856 Info.memVT = MVT::getVT(PtrTy->getElementType()); 11857 Info.ptrVal = I.getArgOperand(0); 11858 Info.offset = 0; 11859 Info.align = DL.getABITypeAlignment(PtrTy->getElementType()); 11860 Info.vol = true; 11861 Info.readMem = true; 11862 Info.writeMem = false; 11863 return true; 11864 } 11865 case Intrinsic::arm_stlex: 11866 case Intrinsic::arm_strex: { 11867 auto &DL = I.getCalledFunction()->getParent()->getDataLayout(); 11868 PointerType *PtrTy = cast<PointerType>(I.getArgOperand(1)->getType()); 11869 Info.opc = ISD::INTRINSIC_W_CHAIN; 11870 Info.memVT = MVT::getVT(PtrTy->getElementType()); 11871 Info.ptrVal = I.getArgOperand(1); 11872 Info.offset = 0; 11873 Info.align = DL.getABITypeAlignment(PtrTy->getElementType()); 11874 Info.vol = true; 11875 Info.readMem = false; 11876 Info.writeMem = true; 11877 return true; 11878 } 11879 case Intrinsic::arm_stlexd: 11880 case Intrinsic::arm_strexd: { 11881 Info.opc = ISD::INTRINSIC_W_CHAIN; 11882 Info.memVT = MVT::i64; 11883 Info.ptrVal = I.getArgOperand(2); 11884 Info.offset = 0; 11885 Info.align = 8; 11886 Info.vol = true; 11887 Info.readMem = false; 11888 Info.writeMem = true; 11889 return true; 11890 } 11891 case Intrinsic::arm_ldaexd: 11892 case Intrinsic::arm_ldrexd: { 11893 Info.opc = ISD::INTRINSIC_W_CHAIN; 11894 Info.memVT = MVT::i64; 11895 Info.ptrVal = I.getArgOperand(0); 11896 Info.offset = 0; 11897 Info.align = 8; 11898 Info.vol = true; 11899 Info.readMem = true; 11900 Info.writeMem = false; 11901 return true; 11902 } 11903 default: 11904 break; 11905 } 11906 11907 return false; 11908 } 11909 11910 /// \brief Returns true if it is beneficial to convert a load of a constant 11911 /// to just the constant itself. 11912 bool ARMTargetLowering::shouldConvertConstantLoadToIntImm(const APInt &Imm, 11913 Type *Ty) const { 11914 assert(Ty->isIntegerTy()); 11915 11916 unsigned Bits = Ty->getPrimitiveSizeInBits(); 11917 if (Bits == 0 || Bits > 32) 11918 return false; 11919 return true; 11920 } 11921 11922 Instruction* ARMTargetLowering::makeDMB(IRBuilder<> &Builder, 11923 ARM_MB::MemBOpt Domain) const { 11924 Module *M = Builder.GetInsertBlock()->getParent()->getParent(); 11925 11926 // First, if the target has no DMB, see what fallback we can use. 11927 if (!Subtarget->hasDataBarrier()) { 11928 // Some ARMv6 cpus can support data barriers with an mcr instruction. 11929 // Thumb1 and pre-v6 ARM mode use a libcall instead and should never get 11930 // here. 11931 if (Subtarget->hasV6Ops() && !Subtarget->isThumb()) { 11932 Function *MCR = llvm::Intrinsic::getDeclaration(M, Intrinsic::arm_mcr); 11933 Value* args[6] = {Builder.getInt32(15), Builder.getInt32(0), 11934 Builder.getInt32(0), Builder.getInt32(7), 11935 Builder.getInt32(10), Builder.getInt32(5)}; 11936 return Builder.CreateCall(MCR, args); 11937 } else { 11938 // Instead of using barriers, atomic accesses on these subtargets use 11939 // libcalls. 11940 llvm_unreachable("makeDMB on a target so old that it has no barriers"); 11941 } 11942 } else { 11943 Function *DMB = llvm::Intrinsic::getDeclaration(M, Intrinsic::arm_dmb); 11944 // Only a full system barrier exists in the M-class architectures. 11945 Domain = Subtarget->isMClass() ? ARM_MB::SY : Domain; 11946 Constant *CDomain = Builder.getInt32(Domain); 11947 return Builder.CreateCall(DMB, CDomain); 11948 } 11949 } 11950 11951 // Based on http://www.cl.cam.ac.uk/~pes20/cpp/cpp0xmappings.html 11952 Instruction* ARMTargetLowering::emitLeadingFence(IRBuilder<> &Builder, 11953 AtomicOrdering Ord, bool IsStore, 11954 bool IsLoad) const { 11955 if (!getInsertFencesForAtomic()) 11956 return nullptr; 11957 11958 switch (Ord) { 11959 case NotAtomic: 11960 case Unordered: 11961 llvm_unreachable("Invalid fence: unordered/non-atomic"); 11962 case Monotonic: 11963 case Acquire: 11964 return nullptr; // Nothing to do 11965 case SequentiallyConsistent: 11966 if (!IsStore) 11967 return nullptr; // Nothing to do 11968 /*FALLTHROUGH*/ 11969 case Release: 11970 case AcquireRelease: 11971 if (Subtarget->isSwift()) 11972 return makeDMB(Builder, ARM_MB::ISHST); 11973 // FIXME: add a comment with a link to documentation justifying this. 11974 else 11975 return makeDMB(Builder, ARM_MB::ISH); 11976 } 11977 llvm_unreachable("Unknown fence ordering in emitLeadingFence"); 11978 } 11979 11980 Instruction* ARMTargetLowering::emitTrailingFence(IRBuilder<> &Builder, 11981 AtomicOrdering Ord, bool IsStore, 11982 bool IsLoad) const { 11983 if (!getInsertFencesForAtomic()) 11984 return nullptr; 11985 11986 switch (Ord) { 11987 case NotAtomic: 11988 case Unordered: 11989 llvm_unreachable("Invalid fence: unordered/not-atomic"); 11990 case Monotonic: 11991 case Release: 11992 return nullptr; // Nothing to do 11993 case Acquire: 11994 case AcquireRelease: 11995 case SequentiallyConsistent: 11996 return makeDMB(Builder, ARM_MB::ISH); 11997 } 11998 llvm_unreachable("Unknown fence ordering in emitTrailingFence"); 11999 } 12000 12001 // Loads and stores less than 64-bits are already atomic; ones above that 12002 // are doomed anyway, so defer to the default libcall and blame the OS when 12003 // things go wrong. Cortex M doesn't have ldrexd/strexd though, so don't emit 12004 // anything for those. 12005 bool ARMTargetLowering::shouldExpandAtomicStoreInIR(StoreInst *SI) const { 12006 unsigned Size = SI->getValueOperand()->getType()->getPrimitiveSizeInBits(); 12007 return (Size == 64) && !Subtarget->isMClass(); 12008 } 12009 12010 // Loads and stores less than 64-bits are already atomic; ones above that 12011 // are doomed anyway, so defer to the default libcall and blame the OS when 12012 // things go wrong. Cortex M doesn't have ldrexd/strexd though, so don't emit 12013 // anything for those. 12014 // FIXME: ldrd and strd are atomic if the CPU has LPAE (e.g. A15 has that 12015 // guarantee, see DDI0406C ARM architecture reference manual, 12016 // sections A8.8.72-74 LDRD) 12017 TargetLowering::AtomicExpansionKind 12018 ARMTargetLowering::shouldExpandAtomicLoadInIR(LoadInst *LI) const { 12019 unsigned Size = LI->getType()->getPrimitiveSizeInBits(); 12020 return ((Size == 64) && !Subtarget->isMClass()) ? AtomicExpansionKind::LLOnly 12021 : AtomicExpansionKind::None; 12022 } 12023 12024 // For the real atomic operations, we have ldrex/strex up to 32 bits, 12025 // and up to 64 bits on the non-M profiles 12026 TargetLowering::AtomicExpansionKind 12027 ARMTargetLowering::shouldExpandAtomicRMWInIR(AtomicRMWInst *AI) const { 12028 unsigned Size = AI->getType()->getPrimitiveSizeInBits(); 12029 return (Size <= (Subtarget->isMClass() ? 32U : 64U)) 12030 ? AtomicExpansionKind::LLSC 12031 : AtomicExpansionKind::None; 12032 } 12033 12034 bool ARMTargetLowering::shouldExpandAtomicCmpXchgInIR( 12035 AtomicCmpXchgInst *AI) const { 12036 return true; 12037 } 12038 12039 // This has so far only been implemented for MachO. 12040 bool ARMTargetLowering::useLoadStackGuardNode() const { 12041 return Subtarget->isTargetMachO(); 12042 } 12043 12044 bool ARMTargetLowering::canCombineStoreAndExtract(Type *VectorTy, Value *Idx, 12045 unsigned &Cost) const { 12046 // If we do not have NEON, vector types are not natively supported. 12047 if (!Subtarget->hasNEON()) 12048 return false; 12049 12050 // Floating point values and vector values map to the same register file. 12051 // Therefore, although we could do a store extract of a vector type, this is 12052 // better to leave at float as we have more freedom in the addressing mode for 12053 // those. 12054 if (VectorTy->isFPOrFPVectorTy()) 12055 return false; 12056 12057 // If the index is unknown at compile time, this is very expensive to lower 12058 // and it is not possible to combine the store with the extract. 12059 if (!isa<ConstantInt>(Idx)) 12060 return false; 12061 12062 assert(VectorTy->isVectorTy() && "VectorTy is not a vector type"); 12063 unsigned BitWidth = cast<VectorType>(VectorTy)->getBitWidth(); 12064 // We can do a store + vector extract on any vector that fits perfectly in a D 12065 // or Q register. 12066 if (BitWidth == 64 || BitWidth == 128) { 12067 Cost = 0; 12068 return true; 12069 } 12070 return false; 12071 } 12072 12073 bool ARMTargetLowering::isCheapToSpeculateCttz() const { 12074 return Subtarget->hasV6T2Ops(); 12075 } 12076 12077 bool ARMTargetLowering::isCheapToSpeculateCtlz() const { 12078 return Subtarget->hasV6T2Ops(); 12079 } 12080 12081 Value *ARMTargetLowering::emitLoadLinked(IRBuilder<> &Builder, Value *Addr, 12082 AtomicOrdering Ord) const { 12083 Module *M = Builder.GetInsertBlock()->getParent()->getParent(); 12084 Type *ValTy = cast<PointerType>(Addr->getType())->getElementType(); 12085 bool IsAcquire = isAtLeastAcquire(Ord); 12086 12087 // Since i64 isn't legal and intrinsics don't get type-lowered, the ldrexd 12088 // intrinsic must return {i32, i32} and we have to recombine them into a 12089 // single i64 here. 12090 if (ValTy->getPrimitiveSizeInBits() == 64) { 12091 Intrinsic::ID Int = 12092 IsAcquire ? Intrinsic::arm_ldaexd : Intrinsic::arm_ldrexd; 12093 Function *Ldrex = llvm::Intrinsic::getDeclaration(M, Int); 12094 12095 Addr = Builder.CreateBitCast(Addr, Type::getInt8PtrTy(M->getContext())); 12096 Value *LoHi = Builder.CreateCall(Ldrex, Addr, "lohi"); 12097 12098 Value *Lo = Builder.CreateExtractValue(LoHi, 0, "lo"); 12099 Value *Hi = Builder.CreateExtractValue(LoHi, 1, "hi"); 12100 if (!Subtarget->isLittle()) 12101 std::swap (Lo, Hi); 12102 Lo = Builder.CreateZExt(Lo, ValTy, "lo64"); 12103 Hi = Builder.CreateZExt(Hi, ValTy, "hi64"); 12104 return Builder.CreateOr( 12105 Lo, Builder.CreateShl(Hi, ConstantInt::get(ValTy, 32)), "val64"); 12106 } 12107 12108 Type *Tys[] = { Addr->getType() }; 12109 Intrinsic::ID Int = IsAcquire ? Intrinsic::arm_ldaex : Intrinsic::arm_ldrex; 12110 Function *Ldrex = llvm::Intrinsic::getDeclaration(M, Int, Tys); 12111 12112 return Builder.CreateTruncOrBitCast( 12113 Builder.CreateCall(Ldrex, Addr), 12114 cast<PointerType>(Addr->getType())->getElementType()); 12115 } 12116 12117 void ARMTargetLowering::emitAtomicCmpXchgNoStoreLLBalance( 12118 IRBuilder<> &Builder) const { 12119 if (!Subtarget->hasV7Ops()) 12120 return; 12121 Module *M = Builder.GetInsertBlock()->getParent()->getParent(); 12122 Builder.CreateCall(llvm::Intrinsic::getDeclaration(M, Intrinsic::arm_clrex)); 12123 } 12124 12125 Value *ARMTargetLowering::emitStoreConditional(IRBuilder<> &Builder, Value *Val, 12126 Value *Addr, 12127 AtomicOrdering Ord) const { 12128 Module *M = Builder.GetInsertBlock()->getParent()->getParent(); 12129 bool IsRelease = isAtLeastRelease(Ord); 12130 12131 // Since the intrinsics must have legal type, the i64 intrinsics take two 12132 // parameters: "i32, i32". We must marshal Val into the appropriate form 12133 // before the call. 12134 if (Val->getType()->getPrimitiveSizeInBits() == 64) { 12135 Intrinsic::ID Int = 12136 IsRelease ? Intrinsic::arm_stlexd : Intrinsic::arm_strexd; 12137 Function *Strex = Intrinsic::getDeclaration(M, Int); 12138 Type *Int32Ty = Type::getInt32Ty(M->getContext()); 12139 12140 Value *Lo = Builder.CreateTrunc(Val, Int32Ty, "lo"); 12141 Value *Hi = Builder.CreateTrunc(Builder.CreateLShr(Val, 32), Int32Ty, "hi"); 12142 if (!Subtarget->isLittle()) 12143 std::swap (Lo, Hi); 12144 Addr = Builder.CreateBitCast(Addr, Type::getInt8PtrTy(M->getContext())); 12145 return Builder.CreateCall(Strex, {Lo, Hi, Addr}); 12146 } 12147 12148 Intrinsic::ID Int = IsRelease ? Intrinsic::arm_stlex : Intrinsic::arm_strex; 12149 Type *Tys[] = { Addr->getType() }; 12150 Function *Strex = Intrinsic::getDeclaration(M, Int, Tys); 12151 12152 return Builder.CreateCall( 12153 Strex, {Builder.CreateZExtOrBitCast( 12154 Val, Strex->getFunctionType()->getParamType(0)), 12155 Addr}); 12156 } 12157 12158 /// \brief Lower an interleaved load into a vldN intrinsic. 12159 /// 12160 /// E.g. Lower an interleaved load (Factor = 2): 12161 /// %wide.vec = load <8 x i32>, <8 x i32>* %ptr, align 4 12162 /// %v0 = shuffle %wide.vec, undef, <0, 2, 4, 6> ; Extract even elements 12163 /// %v1 = shuffle %wide.vec, undef, <1, 3, 5, 7> ; Extract odd elements 12164 /// 12165 /// Into: 12166 /// %vld2 = { <4 x i32>, <4 x i32> } call llvm.arm.neon.vld2(%ptr, 4) 12167 /// %vec0 = extractelement { <4 x i32>, <4 x i32> } %vld2, i32 0 12168 /// %vec1 = extractelement { <4 x i32>, <4 x i32> } %vld2, i32 1 12169 bool ARMTargetLowering::lowerInterleavedLoad( 12170 LoadInst *LI, ArrayRef<ShuffleVectorInst *> Shuffles, 12171 ArrayRef<unsigned> Indices, unsigned Factor) const { 12172 assert(Factor >= 2 && Factor <= getMaxSupportedInterleaveFactor() && 12173 "Invalid interleave factor"); 12174 assert(!Shuffles.empty() && "Empty shufflevector input"); 12175 assert(Shuffles.size() == Indices.size() && 12176 "Unmatched number of shufflevectors and indices"); 12177 12178 VectorType *VecTy = Shuffles[0]->getType(); 12179 Type *EltTy = VecTy->getVectorElementType(); 12180 12181 const DataLayout &DL = LI->getModule()->getDataLayout(); 12182 unsigned VecSize = DL.getTypeSizeInBits(VecTy); 12183 bool EltIs64Bits = DL.getTypeSizeInBits(EltTy) == 64; 12184 12185 // Skip if we do not have NEON and skip illegal vector types and vector types 12186 // with i64/f64 elements (vldN doesn't support i64/f64 elements). 12187 if (!Subtarget->hasNEON() || (VecSize != 64 && VecSize != 128) || EltIs64Bits) 12188 return false; 12189 12190 // A pointer vector can not be the return type of the ldN intrinsics. Need to 12191 // load integer vectors first and then convert to pointer vectors. 12192 if (EltTy->isPointerTy()) 12193 VecTy = 12194 VectorType::get(DL.getIntPtrType(EltTy), VecTy->getVectorNumElements()); 12195 12196 static const Intrinsic::ID LoadInts[3] = {Intrinsic::arm_neon_vld2, 12197 Intrinsic::arm_neon_vld3, 12198 Intrinsic::arm_neon_vld4}; 12199 12200 IRBuilder<> Builder(LI); 12201 SmallVector<Value *, 2> Ops; 12202 12203 Type *Int8Ptr = Builder.getInt8PtrTy(LI->getPointerAddressSpace()); 12204 Ops.push_back(Builder.CreateBitCast(LI->getPointerOperand(), Int8Ptr)); 12205 Ops.push_back(Builder.getInt32(LI->getAlignment())); 12206 12207 Type *Tys[] = { VecTy, Int8Ptr }; 12208 Function *VldnFunc = 12209 Intrinsic::getDeclaration(LI->getModule(), LoadInts[Factor - 2], Tys); 12210 CallInst *VldN = Builder.CreateCall(VldnFunc, Ops, "vldN"); 12211 12212 // Replace uses of each shufflevector with the corresponding vector loaded 12213 // by ldN. 12214 for (unsigned i = 0; i < Shuffles.size(); i++) { 12215 ShuffleVectorInst *SV = Shuffles[i]; 12216 unsigned Index = Indices[i]; 12217 12218 Value *SubVec = Builder.CreateExtractValue(VldN, Index); 12219 12220 // Convert the integer vector to pointer vector if the element is pointer. 12221 if (EltTy->isPointerTy()) 12222 SubVec = Builder.CreateIntToPtr(SubVec, SV->getType()); 12223 12224 SV->replaceAllUsesWith(SubVec); 12225 } 12226 12227 return true; 12228 } 12229 12230 /// \brief Get a mask consisting of sequential integers starting from \p Start. 12231 /// 12232 /// I.e. <Start, Start + 1, ..., Start + NumElts - 1> 12233 static Constant *getSequentialMask(IRBuilder<> &Builder, unsigned Start, 12234 unsigned NumElts) { 12235 SmallVector<Constant *, 16> Mask; 12236 for (unsigned i = 0; i < NumElts; i++) 12237 Mask.push_back(Builder.getInt32(Start + i)); 12238 12239 return ConstantVector::get(Mask); 12240 } 12241 12242 /// \brief Lower an interleaved store into a vstN intrinsic. 12243 /// 12244 /// E.g. Lower an interleaved store (Factor = 3): 12245 /// %i.vec = shuffle <8 x i32> %v0, <8 x i32> %v1, 12246 /// <0, 4, 8, 1, 5, 9, 2, 6, 10, 3, 7, 11> 12247 /// store <12 x i32> %i.vec, <12 x i32>* %ptr, align 4 12248 /// 12249 /// Into: 12250 /// %sub.v0 = shuffle <8 x i32> %v0, <8 x i32> v1, <0, 1, 2, 3> 12251 /// %sub.v1 = shuffle <8 x i32> %v0, <8 x i32> v1, <4, 5, 6, 7> 12252 /// %sub.v2 = shuffle <8 x i32> %v0, <8 x i32> v1, <8, 9, 10, 11> 12253 /// call void llvm.arm.neon.vst3(%ptr, %sub.v0, %sub.v1, %sub.v2, 4) 12254 /// 12255 /// Note that the new shufflevectors will be removed and we'll only generate one 12256 /// vst3 instruction in CodeGen. 12257 bool ARMTargetLowering::lowerInterleavedStore(StoreInst *SI, 12258 ShuffleVectorInst *SVI, 12259 unsigned Factor) const { 12260 assert(Factor >= 2 && Factor <= getMaxSupportedInterleaveFactor() && 12261 "Invalid interleave factor"); 12262 12263 VectorType *VecTy = SVI->getType(); 12264 assert(VecTy->getVectorNumElements() % Factor == 0 && 12265 "Invalid interleaved store"); 12266 12267 unsigned NumSubElts = VecTy->getVectorNumElements() / Factor; 12268 Type *EltTy = VecTy->getVectorElementType(); 12269 VectorType *SubVecTy = VectorType::get(EltTy, NumSubElts); 12270 12271 const DataLayout &DL = SI->getModule()->getDataLayout(); 12272 unsigned SubVecSize = DL.getTypeSizeInBits(SubVecTy); 12273 bool EltIs64Bits = DL.getTypeSizeInBits(EltTy) == 64; 12274 12275 // Skip if we do not have NEON and skip illegal vector types and vector types 12276 // with i64/f64 elements (vstN doesn't support i64/f64 elements). 12277 if (!Subtarget->hasNEON() || (SubVecSize != 64 && SubVecSize != 128) || 12278 EltIs64Bits) 12279 return false; 12280 12281 Value *Op0 = SVI->getOperand(0); 12282 Value *Op1 = SVI->getOperand(1); 12283 IRBuilder<> Builder(SI); 12284 12285 // StN intrinsics don't support pointer vectors as arguments. Convert pointer 12286 // vectors to integer vectors. 12287 if (EltTy->isPointerTy()) { 12288 Type *IntTy = DL.getIntPtrType(EltTy); 12289 12290 // Convert to the corresponding integer vector. 12291 Type *IntVecTy = 12292 VectorType::get(IntTy, Op0->getType()->getVectorNumElements()); 12293 Op0 = Builder.CreatePtrToInt(Op0, IntVecTy); 12294 Op1 = Builder.CreatePtrToInt(Op1, IntVecTy); 12295 12296 SubVecTy = VectorType::get(IntTy, NumSubElts); 12297 } 12298 12299 static const Intrinsic::ID StoreInts[3] = {Intrinsic::arm_neon_vst2, 12300 Intrinsic::arm_neon_vst3, 12301 Intrinsic::arm_neon_vst4}; 12302 SmallVector<Value *, 6> Ops; 12303 12304 Type *Int8Ptr = Builder.getInt8PtrTy(SI->getPointerAddressSpace()); 12305 Ops.push_back(Builder.CreateBitCast(SI->getPointerOperand(), Int8Ptr)); 12306 12307 Type *Tys[] = { Int8Ptr, SubVecTy }; 12308 Function *VstNFunc = Intrinsic::getDeclaration( 12309 SI->getModule(), StoreInts[Factor - 2], Tys); 12310 12311 // Split the shufflevector operands into sub vectors for the new vstN call. 12312 for (unsigned i = 0; i < Factor; i++) 12313 Ops.push_back(Builder.CreateShuffleVector( 12314 Op0, Op1, getSequentialMask(Builder, NumSubElts * i, NumSubElts))); 12315 12316 Ops.push_back(Builder.getInt32(SI->getAlignment())); 12317 Builder.CreateCall(VstNFunc, Ops); 12318 return true; 12319 } 12320 12321 enum HABaseType { 12322 HA_UNKNOWN = 0, 12323 HA_FLOAT, 12324 HA_DOUBLE, 12325 HA_VECT64, 12326 HA_VECT128 12327 }; 12328 12329 static bool isHomogeneousAggregate(Type *Ty, HABaseType &Base, 12330 uint64_t &Members) { 12331 if (auto *ST = dyn_cast<StructType>(Ty)) { 12332 for (unsigned i = 0; i < ST->getNumElements(); ++i) { 12333 uint64_t SubMembers = 0; 12334 if (!isHomogeneousAggregate(ST->getElementType(i), Base, SubMembers)) 12335 return false; 12336 Members += SubMembers; 12337 } 12338 } else if (auto *AT = dyn_cast<ArrayType>(Ty)) { 12339 uint64_t SubMembers = 0; 12340 if (!isHomogeneousAggregate(AT->getElementType(), Base, SubMembers)) 12341 return false; 12342 Members += SubMembers * AT->getNumElements(); 12343 } else if (Ty->isFloatTy()) { 12344 if (Base != HA_UNKNOWN && Base != HA_FLOAT) 12345 return false; 12346 Members = 1; 12347 Base = HA_FLOAT; 12348 } else if (Ty->isDoubleTy()) { 12349 if (Base != HA_UNKNOWN && Base != HA_DOUBLE) 12350 return false; 12351 Members = 1; 12352 Base = HA_DOUBLE; 12353 } else if (auto *VT = dyn_cast<VectorType>(Ty)) { 12354 Members = 1; 12355 switch (Base) { 12356 case HA_FLOAT: 12357 case HA_DOUBLE: 12358 return false; 12359 case HA_VECT64: 12360 return VT->getBitWidth() == 64; 12361 case HA_VECT128: 12362 return VT->getBitWidth() == 128; 12363 case HA_UNKNOWN: 12364 switch (VT->getBitWidth()) { 12365 case 64: 12366 Base = HA_VECT64; 12367 return true; 12368 case 128: 12369 Base = HA_VECT128; 12370 return true; 12371 default: 12372 return false; 12373 } 12374 } 12375 } 12376 12377 return (Members > 0 && Members <= 4); 12378 } 12379 12380 /// \brief Return true if a type is an AAPCS-VFP homogeneous aggregate or one of 12381 /// [N x i32] or [N x i64]. This allows front-ends to skip emitting padding when 12382 /// passing according to AAPCS rules. 12383 bool ARMTargetLowering::functionArgumentNeedsConsecutiveRegisters( 12384 Type *Ty, CallingConv::ID CallConv, bool isVarArg) const { 12385 if (getEffectiveCallingConv(CallConv, isVarArg) != 12386 CallingConv::ARM_AAPCS_VFP) 12387 return false; 12388 12389 HABaseType Base = HA_UNKNOWN; 12390 uint64_t Members = 0; 12391 bool IsHA = isHomogeneousAggregate(Ty, Base, Members); 12392 DEBUG(dbgs() << "isHA: " << IsHA << " "; Ty->dump()); 12393 12394 bool IsIntArray = Ty->isArrayTy() && Ty->getArrayElementType()->isIntegerTy(); 12395 return IsHA || IsIntArray; 12396 } 12397 12398 unsigned ARMTargetLowering::getExceptionPointerRegister( 12399 const Constant *PersonalityFn) const { 12400 // Platforms which do not use SjLj EH may return values in these registers 12401 // via the personality function. 12402 return Subtarget->useSjLjEH() ? ARM::NoRegister : ARM::R0; 12403 } 12404 12405 unsigned ARMTargetLowering::getExceptionSelectorRegister( 12406 const Constant *PersonalityFn) const { 12407 // Platforms which do not use SjLj EH may return values in these registers 12408 // via the personality function. 12409 return Subtarget->useSjLjEH() ? ARM::NoRegister : ARM::R1; 12410 } 12411 12412 void ARMTargetLowering::initializeSplitCSR(MachineBasicBlock *Entry) const { 12413 // Update IsSplitCSR in ARMFunctionInfo. 12414 ARMFunctionInfo *AFI = Entry->getParent()->getInfo<ARMFunctionInfo>(); 12415 AFI->setIsSplitCSR(true); 12416 } 12417 12418 void ARMTargetLowering::insertCopiesSplitCSR( 12419 MachineBasicBlock *Entry, 12420 const SmallVectorImpl<MachineBasicBlock *> &Exits) const { 12421 const ARMBaseRegisterInfo *TRI = Subtarget->getRegisterInfo(); 12422 const MCPhysReg *IStart = TRI->getCalleeSavedRegsViaCopy(Entry->getParent()); 12423 if (!IStart) 12424 return; 12425 12426 const TargetInstrInfo *TII = Subtarget->getInstrInfo(); 12427 MachineRegisterInfo *MRI = &Entry->getParent()->getRegInfo(); 12428 MachineBasicBlock::iterator MBBI = Entry->begin(); 12429 for (const MCPhysReg *I = IStart; *I; ++I) { 12430 const TargetRegisterClass *RC = nullptr; 12431 if (ARM::GPRRegClass.contains(*I)) 12432 RC = &ARM::GPRRegClass; 12433 else if (ARM::DPRRegClass.contains(*I)) 12434 RC = &ARM::DPRRegClass; 12435 else 12436 llvm_unreachable("Unexpected register class in CSRsViaCopy!"); 12437 12438 unsigned NewVR = MRI->createVirtualRegister(RC); 12439 // Create copy from CSR to a virtual register. 12440 // FIXME: this currently does not emit CFI pseudo-instructions, it works 12441 // fine for CXX_FAST_TLS since the C++-style TLS access functions should be 12442 // nounwind. If we want to generalize this later, we may need to emit 12443 // CFI pseudo-instructions. 12444 assert(Entry->getParent()->getFunction()->hasFnAttribute( 12445 Attribute::NoUnwind) && 12446 "Function should be nounwind in insertCopiesSplitCSR!"); 12447 Entry->addLiveIn(*I); 12448 BuildMI(*Entry, MBBI, DebugLoc(), TII->get(TargetOpcode::COPY), NewVR) 12449 .addReg(*I); 12450 12451 // Insert the copy-back instructions right before the terminator. 12452 for (auto *Exit : Exits) 12453 BuildMI(*Exit, Exit->getFirstTerminator(), DebugLoc(), 12454 TII->get(TargetOpcode::COPY), *I) 12455 .addReg(NewVR); 12456 } 12457 } 12458