1 //===-- ARMISelLowering.cpp - ARM DAG Lowering Implementation -------------===// 2 // 3 // The LLVM Compiler Infrastructure 4 // 5 // This file is distributed under the University of Illinois Open Source 6 // License. See LICENSE.TXT for details. 7 // 8 //===----------------------------------------------------------------------===// 9 // 10 // This file defines the interfaces that ARM uses to lower LLVM code into a 11 // selection DAG. 12 // 13 //===----------------------------------------------------------------------===// 14 15 #include "ARMISelLowering.h" 16 #include "ARMCallingConv.h" 17 #include "ARMConstantPoolValue.h" 18 #include "ARMMachineFunctionInfo.h" 19 #include "ARMPerfectShuffle.h" 20 #include "ARMSubtarget.h" 21 #include "ARMTargetMachine.h" 22 #include "ARMTargetObjectFile.h" 23 #include "MCTargetDesc/ARMAddressingModes.h" 24 #include "llvm/ADT/Statistic.h" 25 #include "llvm/ADT/StringExtras.h" 26 #include "llvm/ADT/StringSwitch.h" 27 #include "llvm/CodeGen/CallingConvLower.h" 28 #include "llvm/CodeGen/IntrinsicLowering.h" 29 #include "llvm/CodeGen/MachineBasicBlock.h" 30 #include "llvm/CodeGen/MachineFrameInfo.h" 31 #include "llvm/CodeGen/MachineFunction.h" 32 #include "llvm/CodeGen/MachineInstrBuilder.h" 33 #include "llvm/CodeGen/MachineJumpTableInfo.h" 34 #include "llvm/CodeGen/MachineModuleInfo.h" 35 #include "llvm/CodeGen/MachineRegisterInfo.h" 36 #include "llvm/CodeGen/SelectionDAG.h" 37 #include "llvm/IR/CallingConv.h" 38 #include "llvm/IR/Constants.h" 39 #include "llvm/IR/Function.h" 40 #include "llvm/IR/GlobalValue.h" 41 #include "llvm/IR/IRBuilder.h" 42 #include "llvm/IR/Instruction.h" 43 #include "llvm/IR/Instructions.h" 44 #include "llvm/IR/IntrinsicInst.h" 45 #include "llvm/IR/Intrinsics.h" 46 #include "llvm/IR/Type.h" 47 #include "llvm/MC/MCSectionMachO.h" 48 #include "llvm/Support/CommandLine.h" 49 #include "llvm/Support/Debug.h" 50 #include "llvm/Support/ErrorHandling.h" 51 #include "llvm/Support/MathExtras.h" 52 #include "llvm/Support/raw_ostream.h" 53 #include "llvm/Target/TargetOptions.h" 54 #include <utility> 55 using namespace llvm; 56 57 #define DEBUG_TYPE "arm-isel" 58 59 STATISTIC(NumTailCalls, "Number of tail calls"); 60 STATISTIC(NumMovwMovt, "Number of GAs materialized with movw + movt"); 61 STATISTIC(NumLoopByVals, "Number of loops generated for byval arguments"); 62 63 static cl::opt<bool> 64 ARMInterworking("arm-interworking", cl::Hidden, 65 cl::desc("Enable / disable ARM interworking (for debugging only)"), 66 cl::init(true)); 67 68 namespace { 69 class ARMCCState : public CCState { 70 public: 71 ARMCCState(CallingConv::ID CC, bool isVarArg, MachineFunction &MF, 72 SmallVectorImpl<CCValAssign> &locs, LLVMContext &C, 73 ParmContext PC) 74 : CCState(CC, isVarArg, MF, locs, C) { 75 assert(((PC == Call) || (PC == Prologue)) && 76 "ARMCCState users must specify whether their context is call" 77 "or prologue generation."); 78 CallOrPrologue = PC; 79 } 80 }; 81 } 82 83 // The APCS parameter registers. 84 static const MCPhysReg GPRArgRegs[] = { 85 ARM::R0, ARM::R1, ARM::R2, ARM::R3 86 }; 87 88 void ARMTargetLowering::addTypeForNEON(MVT VT, MVT PromotedLdStVT, 89 MVT PromotedBitwiseVT) { 90 if (VT != PromotedLdStVT) { 91 setOperationAction(ISD::LOAD, VT, Promote); 92 AddPromotedToType (ISD::LOAD, VT, PromotedLdStVT); 93 94 setOperationAction(ISD::STORE, VT, Promote); 95 AddPromotedToType (ISD::STORE, VT, PromotedLdStVT); 96 } 97 98 MVT ElemTy = VT.getVectorElementType(); 99 if (ElemTy != MVT::i64 && ElemTy != MVT::f64) 100 setOperationAction(ISD::SETCC, VT, Custom); 101 setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Custom); 102 setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom); 103 if (ElemTy == MVT::i32) { 104 setOperationAction(ISD::SINT_TO_FP, VT, Custom); 105 setOperationAction(ISD::UINT_TO_FP, VT, Custom); 106 setOperationAction(ISD::FP_TO_SINT, VT, Custom); 107 setOperationAction(ISD::FP_TO_UINT, VT, Custom); 108 } else { 109 setOperationAction(ISD::SINT_TO_FP, VT, Expand); 110 setOperationAction(ISD::UINT_TO_FP, VT, Expand); 111 setOperationAction(ISD::FP_TO_SINT, VT, Expand); 112 setOperationAction(ISD::FP_TO_UINT, VT, Expand); 113 } 114 setOperationAction(ISD::BUILD_VECTOR, VT, Custom); 115 setOperationAction(ISD::VECTOR_SHUFFLE, VT, Custom); 116 setOperationAction(ISD::CONCAT_VECTORS, VT, Legal); 117 setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Legal); 118 setOperationAction(ISD::SELECT, VT, Expand); 119 setOperationAction(ISD::SELECT_CC, VT, Expand); 120 setOperationAction(ISD::VSELECT, VT, Expand); 121 setOperationAction(ISD::SIGN_EXTEND_INREG, VT, Expand); 122 if (VT.isInteger()) { 123 setOperationAction(ISD::SHL, VT, Custom); 124 setOperationAction(ISD::SRA, VT, Custom); 125 setOperationAction(ISD::SRL, VT, Custom); 126 } 127 128 // Promote all bit-wise operations. 129 if (VT.isInteger() && VT != PromotedBitwiseVT) { 130 setOperationAction(ISD::AND, VT, Promote); 131 AddPromotedToType (ISD::AND, VT, PromotedBitwiseVT); 132 setOperationAction(ISD::OR, VT, Promote); 133 AddPromotedToType (ISD::OR, VT, PromotedBitwiseVT); 134 setOperationAction(ISD::XOR, VT, Promote); 135 AddPromotedToType (ISD::XOR, VT, PromotedBitwiseVT); 136 } 137 138 // Neon does not support vector divide/remainder operations. 139 setOperationAction(ISD::SDIV, VT, Expand); 140 setOperationAction(ISD::UDIV, VT, Expand); 141 setOperationAction(ISD::FDIV, VT, Expand); 142 setOperationAction(ISD::SREM, VT, Expand); 143 setOperationAction(ISD::UREM, VT, Expand); 144 setOperationAction(ISD::FREM, VT, Expand); 145 146 if (!VT.isFloatingPoint() && 147 VT != MVT::v2i64 && VT != MVT::v1i64) 148 for (unsigned Opcode : {ISD::SMIN, ISD::SMAX, ISD::UMIN, ISD::UMAX}) 149 setOperationAction(Opcode, VT, Legal); 150 } 151 152 void ARMTargetLowering::addDRTypeForNEON(MVT VT) { 153 addRegisterClass(VT, &ARM::DPRRegClass); 154 addTypeForNEON(VT, MVT::f64, MVT::v2i32); 155 } 156 157 void ARMTargetLowering::addQRTypeForNEON(MVT VT) { 158 addRegisterClass(VT, &ARM::DPairRegClass); 159 addTypeForNEON(VT, MVT::v2f64, MVT::v4i32); 160 } 161 162 ARMTargetLowering::ARMTargetLowering(const TargetMachine &TM, 163 const ARMSubtarget &STI) 164 : TargetLowering(TM), Subtarget(&STI) { 165 RegInfo = Subtarget->getRegisterInfo(); 166 Itins = Subtarget->getInstrItineraryData(); 167 168 setBooleanVectorContents(ZeroOrNegativeOneBooleanContent); 169 170 if (Subtarget->isTargetMachO()) { 171 // Uses VFP for Thumb libfuncs if available. 172 if (Subtarget->isThumb() && Subtarget->hasVFP2() && 173 Subtarget->hasARMOps() && !Subtarget->useSoftFloat()) { 174 static const struct { 175 const RTLIB::Libcall Op; 176 const char * const Name; 177 const ISD::CondCode Cond; 178 } LibraryCalls[] = { 179 // Single-precision floating-point arithmetic. 180 { RTLIB::ADD_F32, "__addsf3vfp", ISD::SETCC_INVALID }, 181 { RTLIB::SUB_F32, "__subsf3vfp", ISD::SETCC_INVALID }, 182 { RTLIB::MUL_F32, "__mulsf3vfp", ISD::SETCC_INVALID }, 183 { RTLIB::DIV_F32, "__divsf3vfp", ISD::SETCC_INVALID }, 184 185 // Double-precision floating-point arithmetic. 186 { RTLIB::ADD_F64, "__adddf3vfp", ISD::SETCC_INVALID }, 187 { RTLIB::SUB_F64, "__subdf3vfp", ISD::SETCC_INVALID }, 188 { RTLIB::MUL_F64, "__muldf3vfp", ISD::SETCC_INVALID }, 189 { RTLIB::DIV_F64, "__divdf3vfp", ISD::SETCC_INVALID }, 190 191 // Single-precision comparisons. 192 { RTLIB::OEQ_F32, "__eqsf2vfp", ISD::SETNE }, 193 { RTLIB::UNE_F32, "__nesf2vfp", ISD::SETNE }, 194 { RTLIB::OLT_F32, "__ltsf2vfp", ISD::SETNE }, 195 { RTLIB::OLE_F32, "__lesf2vfp", ISD::SETNE }, 196 { RTLIB::OGE_F32, "__gesf2vfp", ISD::SETNE }, 197 { RTLIB::OGT_F32, "__gtsf2vfp", ISD::SETNE }, 198 { RTLIB::UO_F32, "__unordsf2vfp", ISD::SETNE }, 199 { RTLIB::O_F32, "__unordsf2vfp", ISD::SETEQ }, 200 201 // Double-precision comparisons. 202 { RTLIB::OEQ_F64, "__eqdf2vfp", ISD::SETNE }, 203 { RTLIB::UNE_F64, "__nedf2vfp", ISD::SETNE }, 204 { RTLIB::OLT_F64, "__ltdf2vfp", ISD::SETNE }, 205 { RTLIB::OLE_F64, "__ledf2vfp", ISD::SETNE }, 206 { RTLIB::OGE_F64, "__gedf2vfp", ISD::SETNE }, 207 { RTLIB::OGT_F64, "__gtdf2vfp", ISD::SETNE }, 208 { RTLIB::UO_F64, "__unorddf2vfp", ISD::SETNE }, 209 { RTLIB::O_F64, "__unorddf2vfp", ISD::SETEQ }, 210 211 // Floating-point to integer conversions. 212 // i64 conversions are done via library routines even when generating VFP 213 // instructions, so use the same ones. 214 { RTLIB::FPTOSINT_F64_I32, "__fixdfsivfp", ISD::SETCC_INVALID }, 215 { RTLIB::FPTOUINT_F64_I32, "__fixunsdfsivfp", ISD::SETCC_INVALID }, 216 { RTLIB::FPTOSINT_F32_I32, "__fixsfsivfp", ISD::SETCC_INVALID }, 217 { RTLIB::FPTOUINT_F32_I32, "__fixunssfsivfp", ISD::SETCC_INVALID }, 218 219 // Conversions between floating types. 220 { RTLIB::FPROUND_F64_F32, "__truncdfsf2vfp", ISD::SETCC_INVALID }, 221 { RTLIB::FPEXT_F32_F64, "__extendsfdf2vfp", ISD::SETCC_INVALID }, 222 223 // Integer to floating-point conversions. 224 // i64 conversions are done via library routines even when generating VFP 225 // instructions, so use the same ones. 226 // FIXME: There appears to be some naming inconsistency in ARM libgcc: 227 // e.g., __floatunsidf vs. __floatunssidfvfp. 228 { RTLIB::SINTTOFP_I32_F64, "__floatsidfvfp", ISD::SETCC_INVALID }, 229 { RTLIB::UINTTOFP_I32_F64, "__floatunssidfvfp", ISD::SETCC_INVALID }, 230 { RTLIB::SINTTOFP_I32_F32, "__floatsisfvfp", ISD::SETCC_INVALID }, 231 { RTLIB::UINTTOFP_I32_F32, "__floatunssisfvfp", ISD::SETCC_INVALID }, 232 }; 233 234 for (const auto &LC : LibraryCalls) { 235 setLibcallName(LC.Op, LC.Name); 236 if (LC.Cond != ISD::SETCC_INVALID) 237 setCmpLibcallCC(LC.Op, LC.Cond); 238 } 239 } 240 241 // Set the correct calling convention for ARMv7k WatchOS. It's just 242 // AAPCS_VFP for functions as simple as libcalls. 243 if (Subtarget->isTargetWatchABI()) { 244 for (int i = 0; i < RTLIB::UNKNOWN_LIBCALL; ++i) 245 setLibcallCallingConv((RTLIB::Libcall)i, CallingConv::ARM_AAPCS_VFP); 246 } 247 } 248 249 // These libcalls are not available in 32-bit. 250 setLibcallName(RTLIB::SHL_I128, nullptr); 251 setLibcallName(RTLIB::SRL_I128, nullptr); 252 setLibcallName(RTLIB::SRA_I128, nullptr); 253 254 // RTLIB 255 if (Subtarget->isAAPCS_ABI() && 256 (Subtarget->isTargetAEABI() || Subtarget->isTargetGNUAEABI() || 257 Subtarget->isTargetAndroid())) { 258 static const struct { 259 const RTLIB::Libcall Op; 260 const char * const Name; 261 const CallingConv::ID CC; 262 const ISD::CondCode Cond; 263 } LibraryCalls[] = { 264 // Double-precision floating-point arithmetic helper functions 265 // RTABI chapter 4.1.2, Table 2 266 { RTLIB::ADD_F64, "__aeabi_dadd", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 267 { RTLIB::DIV_F64, "__aeabi_ddiv", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 268 { RTLIB::MUL_F64, "__aeabi_dmul", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 269 { RTLIB::SUB_F64, "__aeabi_dsub", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 270 271 // Double-precision floating-point comparison helper functions 272 // RTABI chapter 4.1.2, Table 3 273 { RTLIB::OEQ_F64, "__aeabi_dcmpeq", CallingConv::ARM_AAPCS, ISD::SETNE }, 274 { RTLIB::UNE_F64, "__aeabi_dcmpeq", CallingConv::ARM_AAPCS, ISD::SETEQ }, 275 { RTLIB::OLT_F64, "__aeabi_dcmplt", CallingConv::ARM_AAPCS, ISD::SETNE }, 276 { RTLIB::OLE_F64, "__aeabi_dcmple", CallingConv::ARM_AAPCS, ISD::SETNE }, 277 { RTLIB::OGE_F64, "__aeabi_dcmpge", CallingConv::ARM_AAPCS, ISD::SETNE }, 278 { RTLIB::OGT_F64, "__aeabi_dcmpgt", CallingConv::ARM_AAPCS, ISD::SETNE }, 279 { RTLIB::UO_F64, "__aeabi_dcmpun", CallingConv::ARM_AAPCS, ISD::SETNE }, 280 { RTLIB::O_F64, "__aeabi_dcmpun", CallingConv::ARM_AAPCS, ISD::SETEQ }, 281 282 // Single-precision floating-point arithmetic helper functions 283 // RTABI chapter 4.1.2, Table 4 284 { RTLIB::ADD_F32, "__aeabi_fadd", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 285 { RTLIB::DIV_F32, "__aeabi_fdiv", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 286 { RTLIB::MUL_F32, "__aeabi_fmul", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 287 { RTLIB::SUB_F32, "__aeabi_fsub", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 288 289 // Single-precision floating-point comparison helper functions 290 // RTABI chapter 4.1.2, Table 5 291 { RTLIB::OEQ_F32, "__aeabi_fcmpeq", CallingConv::ARM_AAPCS, ISD::SETNE }, 292 { RTLIB::UNE_F32, "__aeabi_fcmpeq", CallingConv::ARM_AAPCS, ISD::SETEQ }, 293 { RTLIB::OLT_F32, "__aeabi_fcmplt", CallingConv::ARM_AAPCS, ISD::SETNE }, 294 { RTLIB::OLE_F32, "__aeabi_fcmple", CallingConv::ARM_AAPCS, ISD::SETNE }, 295 { RTLIB::OGE_F32, "__aeabi_fcmpge", CallingConv::ARM_AAPCS, ISD::SETNE }, 296 { RTLIB::OGT_F32, "__aeabi_fcmpgt", CallingConv::ARM_AAPCS, ISD::SETNE }, 297 { RTLIB::UO_F32, "__aeabi_fcmpun", CallingConv::ARM_AAPCS, ISD::SETNE }, 298 { RTLIB::O_F32, "__aeabi_fcmpun", CallingConv::ARM_AAPCS, ISD::SETEQ }, 299 300 // Floating-point to integer conversions. 301 // RTABI chapter 4.1.2, Table 6 302 { RTLIB::FPTOSINT_F64_I32, "__aeabi_d2iz", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 303 { RTLIB::FPTOUINT_F64_I32, "__aeabi_d2uiz", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 304 { RTLIB::FPTOSINT_F64_I64, "__aeabi_d2lz", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 305 { RTLIB::FPTOUINT_F64_I64, "__aeabi_d2ulz", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 306 { RTLIB::FPTOSINT_F32_I32, "__aeabi_f2iz", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 307 { RTLIB::FPTOUINT_F32_I32, "__aeabi_f2uiz", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 308 { RTLIB::FPTOSINT_F32_I64, "__aeabi_f2lz", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 309 { RTLIB::FPTOUINT_F32_I64, "__aeabi_f2ulz", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 310 311 // Conversions between floating types. 312 // RTABI chapter 4.1.2, Table 7 313 { RTLIB::FPROUND_F64_F32, "__aeabi_d2f", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 314 { RTLIB::FPROUND_F64_F16, "__aeabi_d2h", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 315 { RTLIB::FPEXT_F32_F64, "__aeabi_f2d", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 316 317 // Integer to floating-point conversions. 318 // RTABI chapter 4.1.2, Table 8 319 { RTLIB::SINTTOFP_I32_F64, "__aeabi_i2d", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 320 { RTLIB::UINTTOFP_I32_F64, "__aeabi_ui2d", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 321 { RTLIB::SINTTOFP_I64_F64, "__aeabi_l2d", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 322 { RTLIB::UINTTOFP_I64_F64, "__aeabi_ul2d", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 323 { RTLIB::SINTTOFP_I32_F32, "__aeabi_i2f", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 324 { RTLIB::UINTTOFP_I32_F32, "__aeabi_ui2f", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 325 { RTLIB::SINTTOFP_I64_F32, "__aeabi_l2f", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 326 { RTLIB::UINTTOFP_I64_F32, "__aeabi_ul2f", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 327 328 // Long long helper functions 329 // RTABI chapter 4.2, Table 9 330 { RTLIB::MUL_I64, "__aeabi_lmul", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 331 { RTLIB::SHL_I64, "__aeabi_llsl", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 332 { RTLIB::SRL_I64, "__aeabi_llsr", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 333 { RTLIB::SRA_I64, "__aeabi_lasr", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 334 335 // Integer division functions 336 // RTABI chapter 4.3.1 337 { RTLIB::SDIV_I8, "__aeabi_idiv", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 338 { RTLIB::SDIV_I16, "__aeabi_idiv", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 339 { RTLIB::SDIV_I32, "__aeabi_idiv", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 340 { RTLIB::SDIV_I64, "__aeabi_ldivmod", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 341 { RTLIB::UDIV_I8, "__aeabi_uidiv", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 342 { RTLIB::UDIV_I16, "__aeabi_uidiv", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 343 { RTLIB::UDIV_I32, "__aeabi_uidiv", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 344 { RTLIB::UDIV_I64, "__aeabi_uldivmod", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 345 }; 346 347 for (const auto &LC : LibraryCalls) { 348 setLibcallName(LC.Op, LC.Name); 349 setLibcallCallingConv(LC.Op, LC.CC); 350 if (LC.Cond != ISD::SETCC_INVALID) 351 setCmpLibcallCC(LC.Op, LC.Cond); 352 } 353 354 // EABI dependent RTLIB 355 if (TM.Options.EABIVersion == EABI::EABI4 || 356 TM.Options.EABIVersion == EABI::EABI5) { 357 static const struct { 358 const RTLIB::Libcall Op; 359 const char *const Name; 360 const CallingConv::ID CC; 361 const ISD::CondCode Cond; 362 } MemOpsLibraryCalls[] = { 363 // Memory operations 364 // RTABI chapter 4.3.4 365 { RTLIB::MEMCPY, "__aeabi_memcpy", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 366 { RTLIB::MEMMOVE, "__aeabi_memmove", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 367 { RTLIB::MEMSET, "__aeabi_memset", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 368 }; 369 370 for (const auto &LC : MemOpsLibraryCalls) { 371 setLibcallName(LC.Op, LC.Name); 372 setLibcallCallingConv(LC.Op, LC.CC); 373 if (LC.Cond != ISD::SETCC_INVALID) 374 setCmpLibcallCC(LC.Op, LC.Cond); 375 } 376 } 377 } 378 379 if (Subtarget->isTargetWindows()) { 380 static const struct { 381 const RTLIB::Libcall Op; 382 const char * const Name; 383 const CallingConv::ID CC; 384 } LibraryCalls[] = { 385 { RTLIB::FPTOSINT_F32_I64, "__stoi64", CallingConv::ARM_AAPCS_VFP }, 386 { RTLIB::FPTOSINT_F64_I64, "__dtoi64", CallingConv::ARM_AAPCS_VFP }, 387 { RTLIB::FPTOUINT_F32_I64, "__stou64", CallingConv::ARM_AAPCS_VFP }, 388 { RTLIB::FPTOUINT_F64_I64, "__dtou64", CallingConv::ARM_AAPCS_VFP }, 389 { RTLIB::SINTTOFP_I64_F32, "__i64tos", CallingConv::ARM_AAPCS_VFP }, 390 { RTLIB::SINTTOFP_I64_F64, "__i64tod", CallingConv::ARM_AAPCS_VFP }, 391 { RTLIB::UINTTOFP_I64_F32, "__u64tos", CallingConv::ARM_AAPCS_VFP }, 392 { RTLIB::UINTTOFP_I64_F64, "__u64tod", CallingConv::ARM_AAPCS_VFP }, 393 }; 394 395 for (const auto &LC : LibraryCalls) { 396 setLibcallName(LC.Op, LC.Name); 397 setLibcallCallingConv(LC.Op, LC.CC); 398 } 399 } 400 401 // Use divmod compiler-rt calls for iOS 5.0 and later. 402 if (Subtarget->isTargetWatchOS() || 403 (Subtarget->isTargetIOS() && 404 !Subtarget->getTargetTriple().isOSVersionLT(5, 0))) { 405 setLibcallName(RTLIB::SDIVREM_I32, "__divmodsi4"); 406 setLibcallName(RTLIB::UDIVREM_I32, "__udivmodsi4"); 407 } 408 409 // The half <-> float conversion functions are always soft-float, but are 410 // needed for some targets which use a hard-float calling convention by 411 // default. 412 if (Subtarget->isAAPCS_ABI()) { 413 setLibcallCallingConv(RTLIB::FPROUND_F32_F16, CallingConv::ARM_AAPCS); 414 setLibcallCallingConv(RTLIB::FPROUND_F64_F16, CallingConv::ARM_AAPCS); 415 setLibcallCallingConv(RTLIB::FPEXT_F16_F32, CallingConv::ARM_AAPCS); 416 } else { 417 setLibcallCallingConv(RTLIB::FPROUND_F32_F16, CallingConv::ARM_APCS); 418 setLibcallCallingConv(RTLIB::FPROUND_F64_F16, CallingConv::ARM_APCS); 419 setLibcallCallingConv(RTLIB::FPEXT_F16_F32, CallingConv::ARM_APCS); 420 } 421 422 // In EABI, these functions have an __aeabi_ prefix, but in GNUEABI they have 423 // a __gnu_ prefix (which is the default). 424 if (Subtarget->isTargetAEABI()) { 425 setLibcallName(RTLIB::FPROUND_F32_F16, "__aeabi_f2h"); 426 setLibcallName(RTLIB::FPROUND_F64_F16, "__aeabi_d2h"); 427 setLibcallName(RTLIB::FPEXT_F16_F32, "__aeabi_h2f"); 428 } 429 430 if (Subtarget->isThumb1Only()) 431 addRegisterClass(MVT::i32, &ARM::tGPRRegClass); 432 else 433 addRegisterClass(MVT::i32, &ARM::GPRRegClass); 434 if (!Subtarget->useSoftFloat() && Subtarget->hasVFP2() && 435 !Subtarget->isThumb1Only()) { 436 addRegisterClass(MVT::f32, &ARM::SPRRegClass); 437 addRegisterClass(MVT::f64, &ARM::DPRRegClass); 438 } 439 440 for (MVT VT : MVT::vector_valuetypes()) { 441 for (MVT InnerVT : MVT::vector_valuetypes()) { 442 setTruncStoreAction(VT, InnerVT, Expand); 443 setLoadExtAction(ISD::SEXTLOAD, VT, InnerVT, Expand); 444 setLoadExtAction(ISD::ZEXTLOAD, VT, InnerVT, Expand); 445 setLoadExtAction(ISD::EXTLOAD, VT, InnerVT, Expand); 446 } 447 448 setOperationAction(ISD::MULHS, VT, Expand); 449 setOperationAction(ISD::SMUL_LOHI, VT, Expand); 450 setOperationAction(ISD::MULHU, VT, Expand); 451 setOperationAction(ISD::UMUL_LOHI, VT, Expand); 452 453 setOperationAction(ISD::BSWAP, VT, Expand); 454 } 455 456 setOperationAction(ISD::ConstantFP, MVT::f32, Custom); 457 setOperationAction(ISD::ConstantFP, MVT::f64, Custom); 458 459 setOperationAction(ISD::READ_REGISTER, MVT::i64, Custom); 460 setOperationAction(ISD::WRITE_REGISTER, MVT::i64, Custom); 461 462 if (Subtarget->hasNEON()) { 463 addDRTypeForNEON(MVT::v2f32); 464 addDRTypeForNEON(MVT::v8i8); 465 addDRTypeForNEON(MVT::v4i16); 466 addDRTypeForNEON(MVT::v2i32); 467 addDRTypeForNEON(MVT::v1i64); 468 469 addQRTypeForNEON(MVT::v4f32); 470 addQRTypeForNEON(MVT::v2f64); 471 addQRTypeForNEON(MVT::v16i8); 472 addQRTypeForNEON(MVT::v8i16); 473 addQRTypeForNEON(MVT::v4i32); 474 addQRTypeForNEON(MVT::v2i64); 475 476 // v2f64 is legal so that QR subregs can be extracted as f64 elements, but 477 // neither Neon nor VFP support any arithmetic operations on it. 478 // The same with v4f32. But keep in mind that vadd, vsub, vmul are natively 479 // supported for v4f32. 480 setOperationAction(ISD::FADD, MVT::v2f64, Expand); 481 setOperationAction(ISD::FSUB, MVT::v2f64, Expand); 482 setOperationAction(ISD::FMUL, MVT::v2f64, Expand); 483 // FIXME: Code duplication: FDIV and FREM are expanded always, see 484 // ARMTargetLowering::addTypeForNEON method for details. 485 setOperationAction(ISD::FDIV, MVT::v2f64, Expand); 486 setOperationAction(ISD::FREM, MVT::v2f64, Expand); 487 // FIXME: Create unittest. 488 // In another words, find a way when "copysign" appears in DAG with vector 489 // operands. 490 setOperationAction(ISD::FCOPYSIGN, MVT::v2f64, Expand); 491 // FIXME: Code duplication: SETCC has custom operation action, see 492 // ARMTargetLowering::addTypeForNEON method for details. 493 setOperationAction(ISD::SETCC, MVT::v2f64, Expand); 494 // FIXME: Create unittest for FNEG and for FABS. 495 setOperationAction(ISD::FNEG, MVT::v2f64, Expand); 496 setOperationAction(ISD::FABS, MVT::v2f64, Expand); 497 setOperationAction(ISD::FSQRT, MVT::v2f64, Expand); 498 setOperationAction(ISD::FSIN, MVT::v2f64, Expand); 499 setOperationAction(ISD::FCOS, MVT::v2f64, Expand); 500 setOperationAction(ISD::FPOWI, MVT::v2f64, Expand); 501 setOperationAction(ISD::FPOW, MVT::v2f64, Expand); 502 setOperationAction(ISD::FLOG, MVT::v2f64, Expand); 503 setOperationAction(ISD::FLOG2, MVT::v2f64, Expand); 504 setOperationAction(ISD::FLOG10, MVT::v2f64, Expand); 505 setOperationAction(ISD::FEXP, MVT::v2f64, Expand); 506 setOperationAction(ISD::FEXP2, MVT::v2f64, Expand); 507 // FIXME: Create unittest for FCEIL, FTRUNC, FRINT, FNEARBYINT, FFLOOR. 508 setOperationAction(ISD::FCEIL, MVT::v2f64, Expand); 509 setOperationAction(ISD::FTRUNC, MVT::v2f64, Expand); 510 setOperationAction(ISD::FRINT, MVT::v2f64, Expand); 511 setOperationAction(ISD::FNEARBYINT, MVT::v2f64, Expand); 512 setOperationAction(ISD::FFLOOR, MVT::v2f64, Expand); 513 setOperationAction(ISD::FMA, MVT::v2f64, Expand); 514 515 setOperationAction(ISD::FSQRT, MVT::v4f32, Expand); 516 setOperationAction(ISD::FSIN, MVT::v4f32, Expand); 517 setOperationAction(ISD::FCOS, MVT::v4f32, Expand); 518 setOperationAction(ISD::FPOWI, MVT::v4f32, Expand); 519 setOperationAction(ISD::FPOW, MVT::v4f32, Expand); 520 setOperationAction(ISD::FLOG, MVT::v4f32, Expand); 521 setOperationAction(ISD::FLOG2, MVT::v4f32, Expand); 522 setOperationAction(ISD::FLOG10, MVT::v4f32, Expand); 523 setOperationAction(ISD::FEXP, MVT::v4f32, Expand); 524 setOperationAction(ISD::FEXP2, MVT::v4f32, Expand); 525 setOperationAction(ISD::FCEIL, MVT::v4f32, Expand); 526 setOperationAction(ISD::FTRUNC, MVT::v4f32, Expand); 527 setOperationAction(ISD::FRINT, MVT::v4f32, Expand); 528 setOperationAction(ISD::FNEARBYINT, MVT::v4f32, Expand); 529 setOperationAction(ISD::FFLOOR, MVT::v4f32, Expand); 530 531 // Mark v2f32 intrinsics. 532 setOperationAction(ISD::FSQRT, MVT::v2f32, Expand); 533 setOperationAction(ISD::FSIN, MVT::v2f32, Expand); 534 setOperationAction(ISD::FCOS, MVT::v2f32, Expand); 535 setOperationAction(ISD::FPOWI, MVT::v2f32, Expand); 536 setOperationAction(ISD::FPOW, MVT::v2f32, Expand); 537 setOperationAction(ISD::FLOG, MVT::v2f32, Expand); 538 setOperationAction(ISD::FLOG2, MVT::v2f32, Expand); 539 setOperationAction(ISD::FLOG10, MVT::v2f32, Expand); 540 setOperationAction(ISD::FEXP, MVT::v2f32, Expand); 541 setOperationAction(ISD::FEXP2, MVT::v2f32, Expand); 542 setOperationAction(ISD::FCEIL, MVT::v2f32, Expand); 543 setOperationAction(ISD::FTRUNC, MVT::v2f32, Expand); 544 setOperationAction(ISD::FRINT, MVT::v2f32, Expand); 545 setOperationAction(ISD::FNEARBYINT, MVT::v2f32, Expand); 546 setOperationAction(ISD::FFLOOR, MVT::v2f32, Expand); 547 548 // Neon does not support some operations on v1i64 and v2i64 types. 549 setOperationAction(ISD::MUL, MVT::v1i64, Expand); 550 // Custom handling for some quad-vector types to detect VMULL. 551 setOperationAction(ISD::MUL, MVT::v8i16, Custom); 552 setOperationAction(ISD::MUL, MVT::v4i32, Custom); 553 setOperationAction(ISD::MUL, MVT::v2i64, Custom); 554 // Custom handling for some vector types to avoid expensive expansions 555 setOperationAction(ISD::SDIV, MVT::v4i16, Custom); 556 setOperationAction(ISD::SDIV, MVT::v8i8, Custom); 557 setOperationAction(ISD::UDIV, MVT::v4i16, Custom); 558 setOperationAction(ISD::UDIV, MVT::v8i8, Custom); 559 setOperationAction(ISD::SETCC, MVT::v1i64, Expand); 560 setOperationAction(ISD::SETCC, MVT::v2i64, Expand); 561 // Neon does not have single instruction SINT_TO_FP and UINT_TO_FP with 562 // a destination type that is wider than the source, and nor does 563 // it have a FP_TO_[SU]INT instruction with a narrower destination than 564 // source. 565 setOperationAction(ISD::SINT_TO_FP, MVT::v4i16, Custom); 566 setOperationAction(ISD::UINT_TO_FP, MVT::v4i16, Custom); 567 setOperationAction(ISD::FP_TO_UINT, MVT::v4i16, Custom); 568 setOperationAction(ISD::FP_TO_SINT, MVT::v4i16, Custom); 569 570 setOperationAction(ISD::FP_ROUND, MVT::v2f32, Expand); 571 setOperationAction(ISD::FP_EXTEND, MVT::v2f64, Expand); 572 573 // NEON does not have single instruction CTPOP for vectors with element 574 // types wider than 8-bits. However, custom lowering can leverage the 575 // v8i8/v16i8 vcnt instruction. 576 setOperationAction(ISD::CTPOP, MVT::v2i32, Custom); 577 setOperationAction(ISD::CTPOP, MVT::v4i32, Custom); 578 setOperationAction(ISD::CTPOP, MVT::v4i16, Custom); 579 setOperationAction(ISD::CTPOP, MVT::v8i16, Custom); 580 setOperationAction(ISD::CTPOP, MVT::v1i64, Expand); 581 setOperationAction(ISD::CTPOP, MVT::v2i64, Expand); 582 583 setOperationAction(ISD::CTLZ, MVT::v1i64, Expand); 584 setOperationAction(ISD::CTLZ, MVT::v2i64, Expand); 585 586 // NEON does not have single instruction CTTZ for vectors. 587 setOperationAction(ISD::CTTZ, MVT::v8i8, Custom); 588 setOperationAction(ISD::CTTZ, MVT::v4i16, Custom); 589 setOperationAction(ISD::CTTZ, MVT::v2i32, Custom); 590 setOperationAction(ISD::CTTZ, MVT::v1i64, Custom); 591 592 setOperationAction(ISD::CTTZ, MVT::v16i8, Custom); 593 setOperationAction(ISD::CTTZ, MVT::v8i16, Custom); 594 setOperationAction(ISD::CTTZ, MVT::v4i32, Custom); 595 setOperationAction(ISD::CTTZ, MVT::v2i64, Custom); 596 597 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::v8i8, Custom); 598 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::v4i16, Custom); 599 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::v2i32, Custom); 600 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::v1i64, Custom); 601 602 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::v16i8, Custom); 603 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::v8i16, Custom); 604 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::v4i32, Custom); 605 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::v2i64, Custom); 606 607 // NEON only has FMA instructions as of VFP4. 608 if (!Subtarget->hasVFP4()) { 609 setOperationAction(ISD::FMA, MVT::v2f32, Expand); 610 setOperationAction(ISD::FMA, MVT::v4f32, Expand); 611 } 612 613 setTargetDAGCombine(ISD::INTRINSIC_VOID); 614 setTargetDAGCombine(ISD::INTRINSIC_W_CHAIN); 615 setTargetDAGCombine(ISD::INTRINSIC_WO_CHAIN); 616 setTargetDAGCombine(ISD::SHL); 617 setTargetDAGCombine(ISD::SRL); 618 setTargetDAGCombine(ISD::SRA); 619 setTargetDAGCombine(ISD::SIGN_EXTEND); 620 setTargetDAGCombine(ISD::ZERO_EXTEND); 621 setTargetDAGCombine(ISD::ANY_EXTEND); 622 setTargetDAGCombine(ISD::BUILD_VECTOR); 623 setTargetDAGCombine(ISD::VECTOR_SHUFFLE); 624 setTargetDAGCombine(ISD::INSERT_VECTOR_ELT); 625 setTargetDAGCombine(ISD::STORE); 626 setTargetDAGCombine(ISD::FP_TO_SINT); 627 setTargetDAGCombine(ISD::FP_TO_UINT); 628 setTargetDAGCombine(ISD::FDIV); 629 setTargetDAGCombine(ISD::LOAD); 630 631 // It is legal to extload from v4i8 to v4i16 or v4i32. 632 for (MVT Ty : {MVT::v8i8, MVT::v4i8, MVT::v2i8, MVT::v4i16, MVT::v2i16, 633 MVT::v2i32}) { 634 for (MVT VT : MVT::integer_vector_valuetypes()) { 635 setLoadExtAction(ISD::EXTLOAD, VT, Ty, Legal); 636 setLoadExtAction(ISD::ZEXTLOAD, VT, Ty, Legal); 637 setLoadExtAction(ISD::SEXTLOAD, VT, Ty, Legal); 638 } 639 } 640 } 641 642 // ARM and Thumb2 support UMLAL/SMLAL. 643 if (!Subtarget->isThumb1Only()) 644 setTargetDAGCombine(ISD::ADDC); 645 646 if (Subtarget->isFPOnlySP()) { 647 // When targeting a floating-point unit with only single-precision 648 // operations, f64 is legal for the few double-precision instructions which 649 // are present However, no double-precision operations other than moves, 650 // loads and stores are provided by the hardware. 651 setOperationAction(ISD::FADD, MVT::f64, Expand); 652 setOperationAction(ISD::FSUB, MVT::f64, Expand); 653 setOperationAction(ISD::FMUL, MVT::f64, Expand); 654 setOperationAction(ISD::FMA, MVT::f64, Expand); 655 setOperationAction(ISD::FDIV, MVT::f64, Expand); 656 setOperationAction(ISD::FREM, MVT::f64, Expand); 657 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand); 658 setOperationAction(ISD::FGETSIGN, MVT::f64, Expand); 659 setOperationAction(ISD::FNEG, MVT::f64, Expand); 660 setOperationAction(ISD::FABS, MVT::f64, Expand); 661 setOperationAction(ISD::FSQRT, MVT::f64, Expand); 662 setOperationAction(ISD::FSIN, MVT::f64, Expand); 663 setOperationAction(ISD::FCOS, MVT::f64, Expand); 664 setOperationAction(ISD::FPOWI, MVT::f64, Expand); 665 setOperationAction(ISD::FPOW, MVT::f64, Expand); 666 setOperationAction(ISD::FLOG, MVT::f64, Expand); 667 setOperationAction(ISD::FLOG2, MVT::f64, Expand); 668 setOperationAction(ISD::FLOG10, MVT::f64, Expand); 669 setOperationAction(ISD::FEXP, MVT::f64, Expand); 670 setOperationAction(ISD::FEXP2, MVT::f64, Expand); 671 setOperationAction(ISD::FCEIL, MVT::f64, Expand); 672 setOperationAction(ISD::FTRUNC, MVT::f64, Expand); 673 setOperationAction(ISD::FRINT, MVT::f64, Expand); 674 setOperationAction(ISD::FNEARBYINT, MVT::f64, Expand); 675 setOperationAction(ISD::FFLOOR, MVT::f64, Expand); 676 setOperationAction(ISD::SINT_TO_FP, MVT::i32, Custom); 677 setOperationAction(ISD::UINT_TO_FP, MVT::i32, Custom); 678 setOperationAction(ISD::FP_TO_SINT, MVT::i32, Custom); 679 setOperationAction(ISD::FP_TO_UINT, MVT::i32, Custom); 680 setOperationAction(ISD::FP_TO_SINT, MVT::f64, Custom); 681 setOperationAction(ISD::FP_TO_UINT, MVT::f64, Custom); 682 setOperationAction(ISD::FP_ROUND, MVT::f32, Custom); 683 setOperationAction(ISD::FP_EXTEND, MVT::f64, Custom); 684 } 685 686 computeRegisterProperties(Subtarget->getRegisterInfo()); 687 688 // ARM does not have floating-point extending loads. 689 for (MVT VT : MVT::fp_valuetypes()) { 690 setLoadExtAction(ISD::EXTLOAD, VT, MVT::f32, Expand); 691 setLoadExtAction(ISD::EXTLOAD, VT, MVT::f16, Expand); 692 } 693 694 // ... or truncating stores 695 setTruncStoreAction(MVT::f64, MVT::f32, Expand); 696 setTruncStoreAction(MVT::f32, MVT::f16, Expand); 697 setTruncStoreAction(MVT::f64, MVT::f16, Expand); 698 699 // ARM does not have i1 sign extending load. 700 for (MVT VT : MVT::integer_valuetypes()) 701 setLoadExtAction(ISD::SEXTLOAD, VT, MVT::i1, Promote); 702 703 // ARM supports all 4 flavors of integer indexed load / store. 704 if (!Subtarget->isThumb1Only()) { 705 for (unsigned im = (unsigned)ISD::PRE_INC; 706 im != (unsigned)ISD::LAST_INDEXED_MODE; ++im) { 707 setIndexedLoadAction(im, MVT::i1, Legal); 708 setIndexedLoadAction(im, MVT::i8, Legal); 709 setIndexedLoadAction(im, MVT::i16, Legal); 710 setIndexedLoadAction(im, MVT::i32, Legal); 711 setIndexedStoreAction(im, MVT::i1, Legal); 712 setIndexedStoreAction(im, MVT::i8, Legal); 713 setIndexedStoreAction(im, MVT::i16, Legal); 714 setIndexedStoreAction(im, MVT::i32, Legal); 715 } 716 } 717 718 setOperationAction(ISD::SADDO, MVT::i32, Custom); 719 setOperationAction(ISD::UADDO, MVT::i32, Custom); 720 setOperationAction(ISD::SSUBO, MVT::i32, Custom); 721 setOperationAction(ISD::USUBO, MVT::i32, Custom); 722 723 // i64 operation support. 724 setOperationAction(ISD::MUL, MVT::i64, Expand); 725 setOperationAction(ISD::MULHU, MVT::i32, Expand); 726 if (Subtarget->isThumb1Only()) { 727 setOperationAction(ISD::UMUL_LOHI, MVT::i32, Expand); 728 setOperationAction(ISD::SMUL_LOHI, MVT::i32, Expand); 729 } 730 if (Subtarget->isThumb1Only() || !Subtarget->hasV6Ops() 731 || (Subtarget->isThumb2() && !Subtarget->hasDSP())) 732 setOperationAction(ISD::MULHS, MVT::i32, Expand); 733 734 setOperationAction(ISD::SHL_PARTS, MVT::i32, Custom); 735 setOperationAction(ISD::SRA_PARTS, MVT::i32, Custom); 736 setOperationAction(ISD::SRL_PARTS, MVT::i32, Custom); 737 setOperationAction(ISD::SRL, MVT::i64, Custom); 738 setOperationAction(ISD::SRA, MVT::i64, Custom); 739 740 if (!Subtarget->isThumb1Only()) { 741 // FIXME: We should do this for Thumb1 as well. 742 setOperationAction(ISD::ADDC, MVT::i32, Custom); 743 setOperationAction(ISD::ADDE, MVT::i32, Custom); 744 setOperationAction(ISD::SUBC, MVT::i32, Custom); 745 setOperationAction(ISD::SUBE, MVT::i32, Custom); 746 } 747 748 if (!Subtarget->isThumb1Only() && Subtarget->hasV6T2Ops()) 749 setOperationAction(ISD::BITREVERSE, MVT::i32, Legal); 750 751 // ARM does not have ROTL. 752 setOperationAction(ISD::ROTL, MVT::i32, Expand); 753 for (MVT VT : MVT::vector_valuetypes()) { 754 setOperationAction(ISD::ROTL, VT, Expand); 755 setOperationAction(ISD::ROTR, VT, Expand); 756 } 757 setOperationAction(ISD::CTTZ, MVT::i32, Custom); 758 setOperationAction(ISD::CTPOP, MVT::i32, Expand); 759 if (!Subtarget->hasV5TOps() || Subtarget->isThumb1Only()) 760 setOperationAction(ISD::CTLZ, MVT::i32, Expand); 761 762 // @llvm.readcyclecounter requires the Performance Monitors extension. 763 // Default to the 0 expansion on unsupported platforms. 764 // FIXME: Technically there are older ARM CPUs that have 765 // implementation-specific ways of obtaining this information. 766 if (Subtarget->hasPerfMon()) 767 setOperationAction(ISD::READCYCLECOUNTER, MVT::i64, Custom); 768 769 // Only ARMv6 has BSWAP. 770 if (!Subtarget->hasV6Ops()) 771 setOperationAction(ISD::BSWAP, MVT::i32, Expand); 772 773 bool hasDivide = Subtarget->isThumb() ? Subtarget->hasDivide() 774 : Subtarget->hasDivideInARMMode(); 775 if (!hasDivide) { 776 // These are expanded into libcalls if the cpu doesn't have HW divider. 777 setOperationAction(ISD::SDIV, MVT::i32, LibCall); 778 setOperationAction(ISD::UDIV, MVT::i32, LibCall); 779 } 780 781 if (Subtarget->isTargetWindows() && !Subtarget->hasDivide()) { 782 setOperationAction(ISD::SDIV, MVT::i32, Custom); 783 setOperationAction(ISD::UDIV, MVT::i32, Custom); 784 785 setOperationAction(ISD::SDIV, MVT::i64, Custom); 786 setOperationAction(ISD::UDIV, MVT::i64, Custom); 787 } 788 789 setOperationAction(ISD::SREM, MVT::i32, Expand); 790 setOperationAction(ISD::UREM, MVT::i32, Expand); 791 // Register based DivRem for AEABI (RTABI 4.2) 792 if (Subtarget->isTargetAEABI() || Subtarget->isTargetAndroid() || 793 Subtarget->isTargetGNUAEABI()) { 794 setOperationAction(ISD::SREM, MVT::i64, Custom); 795 setOperationAction(ISD::UREM, MVT::i64, Custom); 796 797 setLibcallName(RTLIB::SDIVREM_I8, "__aeabi_idivmod"); 798 setLibcallName(RTLIB::SDIVREM_I16, "__aeabi_idivmod"); 799 setLibcallName(RTLIB::SDIVREM_I32, "__aeabi_idivmod"); 800 setLibcallName(RTLIB::SDIVREM_I64, "__aeabi_ldivmod"); 801 setLibcallName(RTLIB::UDIVREM_I8, "__aeabi_uidivmod"); 802 setLibcallName(RTLIB::UDIVREM_I16, "__aeabi_uidivmod"); 803 setLibcallName(RTLIB::UDIVREM_I32, "__aeabi_uidivmod"); 804 setLibcallName(RTLIB::UDIVREM_I64, "__aeabi_uldivmod"); 805 806 setLibcallCallingConv(RTLIB::SDIVREM_I8, CallingConv::ARM_AAPCS); 807 setLibcallCallingConv(RTLIB::SDIVREM_I16, CallingConv::ARM_AAPCS); 808 setLibcallCallingConv(RTLIB::SDIVREM_I32, CallingConv::ARM_AAPCS); 809 setLibcallCallingConv(RTLIB::SDIVREM_I64, CallingConv::ARM_AAPCS); 810 setLibcallCallingConv(RTLIB::UDIVREM_I8, CallingConv::ARM_AAPCS); 811 setLibcallCallingConv(RTLIB::UDIVREM_I16, CallingConv::ARM_AAPCS); 812 setLibcallCallingConv(RTLIB::UDIVREM_I32, CallingConv::ARM_AAPCS); 813 setLibcallCallingConv(RTLIB::UDIVREM_I64, CallingConv::ARM_AAPCS); 814 815 setOperationAction(ISD::SDIVREM, MVT::i32, Custom); 816 setOperationAction(ISD::UDIVREM, MVT::i32, Custom); 817 setOperationAction(ISD::SDIVREM, MVT::i64, Custom); 818 setOperationAction(ISD::UDIVREM, MVT::i64, Custom); 819 } else { 820 setOperationAction(ISD::SDIVREM, MVT::i32, Expand); 821 setOperationAction(ISD::UDIVREM, MVT::i32, Expand); 822 } 823 824 setOperationAction(ISD::GlobalAddress, MVT::i32, Custom); 825 setOperationAction(ISD::ConstantPool, MVT::i32, Custom); 826 setOperationAction(ISD::GlobalTLSAddress, MVT::i32, Custom); 827 setOperationAction(ISD::BlockAddress, MVT::i32, Custom); 828 829 setOperationAction(ISD::TRAP, MVT::Other, Legal); 830 831 // Use the default implementation. 832 setOperationAction(ISD::VASTART, MVT::Other, Custom); 833 setOperationAction(ISD::VAARG, MVT::Other, Expand); 834 setOperationAction(ISD::VACOPY, MVT::Other, Expand); 835 setOperationAction(ISD::VAEND, MVT::Other, Expand); 836 setOperationAction(ISD::STACKSAVE, MVT::Other, Expand); 837 setOperationAction(ISD::STACKRESTORE, MVT::Other, Expand); 838 839 if (Subtarget->getTargetTriple().isWindowsItaniumEnvironment()) 840 setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i32, Custom); 841 else 842 setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i32, Expand); 843 844 // ARMv6 Thumb1 (except for CPUs that support dmb / dsb) and earlier use 845 // the default expansion. 846 InsertFencesForAtomic = false; 847 if (Subtarget->hasAnyDataBarrier() && 848 (!Subtarget->isThumb() || Subtarget->hasV8MBaselineOps())) { 849 // ATOMIC_FENCE needs custom lowering; the others should have been expanded 850 // to ldrex/strex loops already. 851 setOperationAction(ISD::ATOMIC_FENCE, MVT::Other, Custom); 852 if (!Subtarget->isThumb() || !Subtarget->isMClass()) 853 setOperationAction(ISD::ATOMIC_CMP_SWAP, MVT::i64, Custom); 854 855 // On v8, we have particularly efficient implementations of atomic fences 856 // if they can be combined with nearby atomic loads and stores. 857 if (!Subtarget->hasV8Ops() || getTargetMachine().getOptLevel() == 0) { 858 // Automatically insert fences (dmb ish) around ATOMIC_SWAP etc. 859 InsertFencesForAtomic = true; 860 } 861 } else { 862 // If there's anything we can use as a barrier, go through custom lowering 863 // for ATOMIC_FENCE. 864 setOperationAction(ISD::ATOMIC_FENCE, MVT::Other, 865 Subtarget->hasAnyDataBarrier() ? Custom : Expand); 866 867 // Set them all for expansion, which will force libcalls. 868 setOperationAction(ISD::ATOMIC_CMP_SWAP, MVT::i32, Expand); 869 setOperationAction(ISD::ATOMIC_SWAP, MVT::i32, Expand); 870 setOperationAction(ISD::ATOMIC_LOAD_ADD, MVT::i32, Expand); 871 setOperationAction(ISD::ATOMIC_LOAD_SUB, MVT::i32, Expand); 872 setOperationAction(ISD::ATOMIC_LOAD_AND, MVT::i32, Expand); 873 setOperationAction(ISD::ATOMIC_LOAD_OR, MVT::i32, Expand); 874 setOperationAction(ISD::ATOMIC_LOAD_XOR, MVT::i32, Expand); 875 setOperationAction(ISD::ATOMIC_LOAD_NAND, MVT::i32, Expand); 876 setOperationAction(ISD::ATOMIC_LOAD_MIN, MVT::i32, Expand); 877 setOperationAction(ISD::ATOMIC_LOAD_MAX, MVT::i32, Expand); 878 setOperationAction(ISD::ATOMIC_LOAD_UMIN, MVT::i32, Expand); 879 setOperationAction(ISD::ATOMIC_LOAD_UMAX, MVT::i32, Expand); 880 // Mark ATOMIC_LOAD and ATOMIC_STORE custom so we can handle the 881 // Unordered/Monotonic case. 882 setOperationAction(ISD::ATOMIC_LOAD, MVT::i32, Custom); 883 setOperationAction(ISD::ATOMIC_STORE, MVT::i32, Custom); 884 } 885 886 setOperationAction(ISD::PREFETCH, MVT::Other, Custom); 887 888 // Requires SXTB/SXTH, available on v6 and up in both ARM and Thumb modes. 889 if (!Subtarget->hasV6Ops()) { 890 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i16, Expand); 891 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i8, Expand); 892 } 893 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1, Expand); 894 895 if (!Subtarget->useSoftFloat() && Subtarget->hasVFP2() && 896 !Subtarget->isThumb1Only()) { 897 // Turn f64->i64 into VMOVRRD, i64 -> f64 to VMOVDRR 898 // iff target supports vfp2. 899 setOperationAction(ISD::BITCAST, MVT::i64, Custom); 900 setOperationAction(ISD::FLT_ROUNDS_, MVT::i32, Custom); 901 } 902 903 // We want to custom lower some of our intrinsics. 904 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom); 905 setOperationAction(ISD::EH_SJLJ_SETJMP, MVT::i32, Custom); 906 setOperationAction(ISD::EH_SJLJ_LONGJMP, MVT::Other, Custom); 907 setOperationAction(ISD::EH_SJLJ_SETUP_DISPATCH, MVT::Other, Custom); 908 if (Subtarget->useSjLjEH()) 909 setLibcallName(RTLIB::UNWIND_RESUME, "_Unwind_SjLj_Resume"); 910 911 setOperationAction(ISD::SETCC, MVT::i32, Expand); 912 setOperationAction(ISD::SETCC, MVT::f32, Expand); 913 setOperationAction(ISD::SETCC, MVT::f64, Expand); 914 setOperationAction(ISD::SELECT, MVT::i32, Custom); 915 setOperationAction(ISD::SELECT, MVT::f32, Custom); 916 setOperationAction(ISD::SELECT, MVT::f64, Custom); 917 setOperationAction(ISD::SELECT_CC, MVT::i32, Custom); 918 setOperationAction(ISD::SELECT_CC, MVT::f32, Custom); 919 setOperationAction(ISD::SELECT_CC, MVT::f64, Custom); 920 921 // Thumb-1 cannot currently select ARMISD::SUBE. 922 if (!Subtarget->isThumb1Only()) 923 setOperationAction(ISD::SETCCE, MVT::i32, Custom); 924 925 setOperationAction(ISD::BRCOND, MVT::Other, Expand); 926 setOperationAction(ISD::BR_CC, MVT::i32, Custom); 927 setOperationAction(ISD::BR_CC, MVT::f32, Custom); 928 setOperationAction(ISD::BR_CC, MVT::f64, Custom); 929 setOperationAction(ISD::BR_JT, MVT::Other, Custom); 930 931 // We don't support sin/cos/fmod/copysign/pow 932 setOperationAction(ISD::FSIN, MVT::f64, Expand); 933 setOperationAction(ISD::FSIN, MVT::f32, Expand); 934 setOperationAction(ISD::FCOS, MVT::f32, Expand); 935 setOperationAction(ISD::FCOS, MVT::f64, Expand); 936 setOperationAction(ISD::FSINCOS, MVT::f64, Expand); 937 setOperationAction(ISD::FSINCOS, MVT::f32, Expand); 938 setOperationAction(ISD::FREM, MVT::f64, Expand); 939 setOperationAction(ISD::FREM, MVT::f32, Expand); 940 if (!Subtarget->useSoftFloat() && Subtarget->hasVFP2() && 941 !Subtarget->isThumb1Only()) { 942 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Custom); 943 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom); 944 } 945 setOperationAction(ISD::FPOW, MVT::f64, Expand); 946 setOperationAction(ISD::FPOW, MVT::f32, Expand); 947 948 if (!Subtarget->hasVFP4()) { 949 setOperationAction(ISD::FMA, MVT::f64, Expand); 950 setOperationAction(ISD::FMA, MVT::f32, Expand); 951 } 952 953 // Various VFP goodness 954 if (!Subtarget->useSoftFloat() && !Subtarget->isThumb1Only()) { 955 // FP-ARMv8 adds f64 <-> f16 conversion. Before that it should be expanded. 956 if (!Subtarget->hasFPARMv8() || Subtarget->isFPOnlySP()) { 957 setOperationAction(ISD::FP16_TO_FP, MVT::f64, Expand); 958 setOperationAction(ISD::FP_TO_FP16, MVT::f64, Expand); 959 } 960 961 // fp16 is a special v7 extension that adds f16 <-> f32 conversions. 962 if (!Subtarget->hasFP16()) { 963 setOperationAction(ISD::FP16_TO_FP, MVT::f32, Expand); 964 setOperationAction(ISD::FP_TO_FP16, MVT::f32, Expand); 965 } 966 } 967 968 // Combine sin / cos into one node or libcall if possible. 969 if (Subtarget->hasSinCos()) { 970 setLibcallName(RTLIB::SINCOS_F32, "sincosf"); 971 setLibcallName(RTLIB::SINCOS_F64, "sincos"); 972 if (Subtarget->isTargetWatchABI()) { 973 setLibcallCallingConv(RTLIB::SINCOS_F32, CallingConv::ARM_AAPCS_VFP); 974 setLibcallCallingConv(RTLIB::SINCOS_F64, CallingConv::ARM_AAPCS_VFP); 975 } 976 if (Subtarget->isTargetIOS() || Subtarget->isTargetWatchOS()) { 977 // For iOS, we don't want to the normal expansion of a libcall to 978 // sincos. We want to issue a libcall to __sincos_stret. 979 setOperationAction(ISD::FSINCOS, MVT::f64, Custom); 980 setOperationAction(ISD::FSINCOS, MVT::f32, Custom); 981 } 982 } 983 984 // FP-ARMv8 implements a lot of rounding-like FP operations. 985 if (Subtarget->hasFPARMv8()) { 986 setOperationAction(ISD::FFLOOR, MVT::f32, Legal); 987 setOperationAction(ISD::FCEIL, MVT::f32, Legal); 988 setOperationAction(ISD::FROUND, MVT::f32, Legal); 989 setOperationAction(ISD::FTRUNC, MVT::f32, Legal); 990 setOperationAction(ISD::FNEARBYINT, MVT::f32, Legal); 991 setOperationAction(ISD::FRINT, MVT::f32, Legal); 992 setOperationAction(ISD::FMINNUM, MVT::f32, Legal); 993 setOperationAction(ISD::FMAXNUM, MVT::f32, Legal); 994 setOperationAction(ISD::FMINNUM, MVT::v2f32, Legal); 995 setOperationAction(ISD::FMAXNUM, MVT::v2f32, Legal); 996 setOperationAction(ISD::FMINNUM, MVT::v4f32, Legal); 997 setOperationAction(ISD::FMAXNUM, MVT::v4f32, Legal); 998 999 if (!Subtarget->isFPOnlySP()) { 1000 setOperationAction(ISD::FFLOOR, MVT::f64, Legal); 1001 setOperationAction(ISD::FCEIL, MVT::f64, Legal); 1002 setOperationAction(ISD::FROUND, MVT::f64, Legal); 1003 setOperationAction(ISD::FTRUNC, MVT::f64, Legal); 1004 setOperationAction(ISD::FNEARBYINT, MVT::f64, Legal); 1005 setOperationAction(ISD::FRINT, MVT::f64, Legal); 1006 setOperationAction(ISD::FMINNUM, MVT::f64, Legal); 1007 setOperationAction(ISD::FMAXNUM, MVT::f64, Legal); 1008 } 1009 } 1010 1011 if (Subtarget->hasNEON()) { 1012 // vmin and vmax aren't available in a scalar form, so we use 1013 // a NEON instruction with an undef lane instead. 1014 setOperationAction(ISD::FMINNAN, MVT::f32, Legal); 1015 setOperationAction(ISD::FMAXNAN, MVT::f32, Legal); 1016 setOperationAction(ISD::FMINNAN, MVT::v2f32, Legal); 1017 setOperationAction(ISD::FMAXNAN, MVT::v2f32, Legal); 1018 setOperationAction(ISD::FMINNAN, MVT::v4f32, Legal); 1019 setOperationAction(ISD::FMAXNAN, MVT::v4f32, Legal); 1020 } 1021 1022 // We have target-specific dag combine patterns for the following nodes: 1023 // ARMISD::VMOVRRD - No need to call setTargetDAGCombine 1024 setTargetDAGCombine(ISD::ADD); 1025 setTargetDAGCombine(ISD::SUB); 1026 setTargetDAGCombine(ISD::MUL); 1027 setTargetDAGCombine(ISD::AND); 1028 setTargetDAGCombine(ISD::OR); 1029 setTargetDAGCombine(ISD::XOR); 1030 1031 if (Subtarget->hasV6Ops()) 1032 setTargetDAGCombine(ISD::SRL); 1033 1034 setStackPointerRegisterToSaveRestore(ARM::SP); 1035 1036 if (Subtarget->useSoftFloat() || Subtarget->isThumb1Only() || 1037 !Subtarget->hasVFP2()) 1038 setSchedulingPreference(Sched::RegPressure); 1039 else 1040 setSchedulingPreference(Sched::Hybrid); 1041 1042 //// temporary - rewrite interface to use type 1043 MaxStoresPerMemset = 8; 1044 MaxStoresPerMemsetOptSize = 4; 1045 MaxStoresPerMemcpy = 4; // For @llvm.memcpy -> sequence of stores 1046 MaxStoresPerMemcpyOptSize = 2; 1047 MaxStoresPerMemmove = 4; // For @llvm.memmove -> sequence of stores 1048 MaxStoresPerMemmoveOptSize = 2; 1049 1050 // On ARM arguments smaller than 4 bytes are extended, so all arguments 1051 // are at least 4 bytes aligned. 1052 setMinStackArgumentAlignment(4); 1053 1054 // Prefer likely predicted branches to selects on out-of-order cores. 1055 PredictableSelectIsExpensive = Subtarget->getSchedModel().isOutOfOrder(); 1056 1057 setMinFunctionAlignment(Subtarget->isThumb() ? 1 : 2); 1058 } 1059 1060 bool ARMTargetLowering::useSoftFloat() const { 1061 return Subtarget->useSoftFloat(); 1062 } 1063 1064 // FIXME: It might make sense to define the representative register class as the 1065 // nearest super-register that has a non-null superset. For example, DPR_VFP2 is 1066 // a super-register of SPR, and DPR is a superset if DPR_VFP2. Consequently, 1067 // SPR's representative would be DPR_VFP2. This should work well if register 1068 // pressure tracking were modified such that a register use would increment the 1069 // pressure of the register class's representative and all of it's super 1070 // classes' representatives transitively. We have not implemented this because 1071 // of the difficulty prior to coalescing of modeling operand register classes 1072 // due to the common occurrence of cross class copies and subregister insertions 1073 // and extractions. 1074 std::pair<const TargetRegisterClass *, uint8_t> 1075 ARMTargetLowering::findRepresentativeClass(const TargetRegisterInfo *TRI, 1076 MVT VT) const { 1077 const TargetRegisterClass *RRC = nullptr; 1078 uint8_t Cost = 1; 1079 switch (VT.SimpleTy) { 1080 default: 1081 return TargetLowering::findRepresentativeClass(TRI, VT); 1082 // Use DPR as representative register class for all floating point 1083 // and vector types. Since there are 32 SPR registers and 32 DPR registers so 1084 // the cost is 1 for both f32 and f64. 1085 case MVT::f32: case MVT::f64: case MVT::v8i8: case MVT::v4i16: 1086 case MVT::v2i32: case MVT::v1i64: case MVT::v2f32: 1087 RRC = &ARM::DPRRegClass; 1088 // When NEON is used for SP, only half of the register file is available 1089 // because operations that define both SP and DP results will be constrained 1090 // to the VFP2 class (D0-D15). We currently model this constraint prior to 1091 // coalescing by double-counting the SP regs. See the FIXME above. 1092 if (Subtarget->useNEONForSinglePrecisionFP()) 1093 Cost = 2; 1094 break; 1095 case MVT::v16i8: case MVT::v8i16: case MVT::v4i32: case MVT::v2i64: 1096 case MVT::v4f32: case MVT::v2f64: 1097 RRC = &ARM::DPRRegClass; 1098 Cost = 2; 1099 break; 1100 case MVT::v4i64: 1101 RRC = &ARM::DPRRegClass; 1102 Cost = 4; 1103 break; 1104 case MVT::v8i64: 1105 RRC = &ARM::DPRRegClass; 1106 Cost = 8; 1107 break; 1108 } 1109 return std::make_pair(RRC, Cost); 1110 } 1111 1112 const char *ARMTargetLowering::getTargetNodeName(unsigned Opcode) const { 1113 switch ((ARMISD::NodeType)Opcode) { 1114 case ARMISD::FIRST_NUMBER: break; 1115 case ARMISD::Wrapper: return "ARMISD::Wrapper"; 1116 case ARMISD::WrapperPIC: return "ARMISD::WrapperPIC"; 1117 case ARMISD::WrapperJT: return "ARMISD::WrapperJT"; 1118 case ARMISD::COPY_STRUCT_BYVAL: return "ARMISD::COPY_STRUCT_BYVAL"; 1119 case ARMISD::CALL: return "ARMISD::CALL"; 1120 case ARMISD::CALL_PRED: return "ARMISD::CALL_PRED"; 1121 case ARMISD::CALL_NOLINK: return "ARMISD::CALL_NOLINK"; 1122 case ARMISD::tCALL: return "ARMISD::tCALL"; 1123 case ARMISD::BRCOND: return "ARMISD::BRCOND"; 1124 case ARMISD::BR_JT: return "ARMISD::BR_JT"; 1125 case ARMISD::BR2_JT: return "ARMISD::BR2_JT"; 1126 case ARMISD::RET_FLAG: return "ARMISD::RET_FLAG"; 1127 case ARMISD::INTRET_FLAG: return "ARMISD::INTRET_FLAG"; 1128 case ARMISD::PIC_ADD: return "ARMISD::PIC_ADD"; 1129 case ARMISD::CMP: return "ARMISD::CMP"; 1130 case ARMISD::CMN: return "ARMISD::CMN"; 1131 case ARMISD::CMPZ: return "ARMISD::CMPZ"; 1132 case ARMISD::CMPFP: return "ARMISD::CMPFP"; 1133 case ARMISD::CMPFPw0: return "ARMISD::CMPFPw0"; 1134 case ARMISD::BCC_i64: return "ARMISD::BCC_i64"; 1135 case ARMISD::FMSTAT: return "ARMISD::FMSTAT"; 1136 1137 case ARMISD::CMOV: return "ARMISD::CMOV"; 1138 1139 case ARMISD::SRL_FLAG: return "ARMISD::SRL_FLAG"; 1140 case ARMISD::SRA_FLAG: return "ARMISD::SRA_FLAG"; 1141 case ARMISD::RRX: return "ARMISD::RRX"; 1142 1143 case ARMISD::ADDC: return "ARMISD::ADDC"; 1144 case ARMISD::ADDE: return "ARMISD::ADDE"; 1145 case ARMISD::SUBC: return "ARMISD::SUBC"; 1146 case ARMISD::SUBE: return "ARMISD::SUBE"; 1147 1148 case ARMISD::VMOVRRD: return "ARMISD::VMOVRRD"; 1149 case ARMISD::VMOVDRR: return "ARMISD::VMOVDRR"; 1150 1151 case ARMISD::EH_SJLJ_SETJMP: return "ARMISD::EH_SJLJ_SETJMP"; 1152 case ARMISD::EH_SJLJ_LONGJMP: return "ARMISD::EH_SJLJ_LONGJMP"; 1153 case ARMISD::EH_SJLJ_SETUP_DISPATCH: return "ARMISD::EH_SJLJ_SETUP_DISPATCH"; 1154 1155 case ARMISD::TC_RETURN: return "ARMISD::TC_RETURN"; 1156 1157 case ARMISD::THREAD_POINTER:return "ARMISD::THREAD_POINTER"; 1158 1159 case ARMISD::DYN_ALLOC: return "ARMISD::DYN_ALLOC"; 1160 1161 case ARMISD::MEMBARRIER_MCR: return "ARMISD::MEMBARRIER_MCR"; 1162 1163 case ARMISD::PRELOAD: return "ARMISD::PRELOAD"; 1164 1165 case ARMISD::WIN__CHKSTK: return "ARMISD:::WIN__CHKSTK"; 1166 case ARMISD::WIN__DBZCHK: return "ARMISD::WIN__DBZCHK"; 1167 1168 case ARMISD::VCEQ: return "ARMISD::VCEQ"; 1169 case ARMISD::VCEQZ: return "ARMISD::VCEQZ"; 1170 case ARMISD::VCGE: return "ARMISD::VCGE"; 1171 case ARMISD::VCGEZ: return "ARMISD::VCGEZ"; 1172 case ARMISD::VCLEZ: return "ARMISD::VCLEZ"; 1173 case ARMISD::VCGEU: return "ARMISD::VCGEU"; 1174 case ARMISD::VCGT: return "ARMISD::VCGT"; 1175 case ARMISD::VCGTZ: return "ARMISD::VCGTZ"; 1176 case ARMISD::VCLTZ: return "ARMISD::VCLTZ"; 1177 case ARMISD::VCGTU: return "ARMISD::VCGTU"; 1178 case ARMISD::VTST: return "ARMISD::VTST"; 1179 1180 case ARMISD::VSHL: return "ARMISD::VSHL"; 1181 case ARMISD::VSHRs: return "ARMISD::VSHRs"; 1182 case ARMISD::VSHRu: return "ARMISD::VSHRu"; 1183 case ARMISD::VRSHRs: return "ARMISD::VRSHRs"; 1184 case ARMISD::VRSHRu: return "ARMISD::VRSHRu"; 1185 case ARMISD::VRSHRN: return "ARMISD::VRSHRN"; 1186 case ARMISD::VQSHLs: return "ARMISD::VQSHLs"; 1187 case ARMISD::VQSHLu: return "ARMISD::VQSHLu"; 1188 case ARMISD::VQSHLsu: return "ARMISD::VQSHLsu"; 1189 case ARMISD::VQSHRNs: return "ARMISD::VQSHRNs"; 1190 case ARMISD::VQSHRNu: return "ARMISD::VQSHRNu"; 1191 case ARMISD::VQSHRNsu: return "ARMISD::VQSHRNsu"; 1192 case ARMISD::VQRSHRNs: return "ARMISD::VQRSHRNs"; 1193 case ARMISD::VQRSHRNu: return "ARMISD::VQRSHRNu"; 1194 case ARMISD::VQRSHRNsu: return "ARMISD::VQRSHRNsu"; 1195 case ARMISD::VSLI: return "ARMISD::VSLI"; 1196 case ARMISD::VSRI: return "ARMISD::VSRI"; 1197 case ARMISD::VGETLANEu: return "ARMISD::VGETLANEu"; 1198 case ARMISD::VGETLANEs: return "ARMISD::VGETLANEs"; 1199 case ARMISD::VMOVIMM: return "ARMISD::VMOVIMM"; 1200 case ARMISD::VMVNIMM: return "ARMISD::VMVNIMM"; 1201 case ARMISD::VMOVFPIMM: return "ARMISD::VMOVFPIMM"; 1202 case ARMISD::VDUP: return "ARMISD::VDUP"; 1203 case ARMISD::VDUPLANE: return "ARMISD::VDUPLANE"; 1204 case ARMISD::VEXT: return "ARMISD::VEXT"; 1205 case ARMISD::VREV64: return "ARMISD::VREV64"; 1206 case ARMISD::VREV32: return "ARMISD::VREV32"; 1207 case ARMISD::VREV16: return "ARMISD::VREV16"; 1208 case ARMISD::VZIP: return "ARMISD::VZIP"; 1209 case ARMISD::VUZP: return "ARMISD::VUZP"; 1210 case ARMISD::VTRN: return "ARMISD::VTRN"; 1211 case ARMISD::VTBL1: return "ARMISD::VTBL1"; 1212 case ARMISD::VTBL2: return "ARMISD::VTBL2"; 1213 case ARMISD::VMULLs: return "ARMISD::VMULLs"; 1214 case ARMISD::VMULLu: return "ARMISD::VMULLu"; 1215 case ARMISD::UMLAL: return "ARMISD::UMLAL"; 1216 case ARMISD::SMLAL: return "ARMISD::SMLAL"; 1217 case ARMISD::BUILD_VECTOR: return "ARMISD::BUILD_VECTOR"; 1218 case ARMISD::BFI: return "ARMISD::BFI"; 1219 case ARMISD::VORRIMM: return "ARMISD::VORRIMM"; 1220 case ARMISD::VBICIMM: return "ARMISD::VBICIMM"; 1221 case ARMISD::VBSL: return "ARMISD::VBSL"; 1222 case ARMISD::MEMCPY: return "ARMISD::MEMCPY"; 1223 case ARMISD::VLD2DUP: return "ARMISD::VLD2DUP"; 1224 case ARMISD::VLD3DUP: return "ARMISD::VLD3DUP"; 1225 case ARMISD::VLD4DUP: return "ARMISD::VLD4DUP"; 1226 case ARMISD::VLD1_UPD: return "ARMISD::VLD1_UPD"; 1227 case ARMISD::VLD2_UPD: return "ARMISD::VLD2_UPD"; 1228 case ARMISD::VLD3_UPD: return "ARMISD::VLD3_UPD"; 1229 case ARMISD::VLD4_UPD: return "ARMISD::VLD4_UPD"; 1230 case ARMISD::VLD2LN_UPD: return "ARMISD::VLD2LN_UPD"; 1231 case ARMISD::VLD3LN_UPD: return "ARMISD::VLD3LN_UPD"; 1232 case ARMISD::VLD4LN_UPD: return "ARMISD::VLD4LN_UPD"; 1233 case ARMISD::VLD2DUP_UPD: return "ARMISD::VLD2DUP_UPD"; 1234 case ARMISD::VLD3DUP_UPD: return "ARMISD::VLD3DUP_UPD"; 1235 case ARMISD::VLD4DUP_UPD: return "ARMISD::VLD4DUP_UPD"; 1236 case ARMISD::VST1_UPD: return "ARMISD::VST1_UPD"; 1237 case ARMISD::VST2_UPD: return "ARMISD::VST2_UPD"; 1238 case ARMISD::VST3_UPD: return "ARMISD::VST3_UPD"; 1239 case ARMISD::VST4_UPD: return "ARMISD::VST4_UPD"; 1240 case ARMISD::VST2LN_UPD: return "ARMISD::VST2LN_UPD"; 1241 case ARMISD::VST3LN_UPD: return "ARMISD::VST3LN_UPD"; 1242 case ARMISD::VST4LN_UPD: return "ARMISD::VST4LN_UPD"; 1243 } 1244 return nullptr; 1245 } 1246 1247 EVT ARMTargetLowering::getSetCCResultType(const DataLayout &DL, LLVMContext &, 1248 EVT VT) const { 1249 if (!VT.isVector()) 1250 return getPointerTy(DL); 1251 return VT.changeVectorElementTypeToInteger(); 1252 } 1253 1254 /// getRegClassFor - Return the register class that should be used for the 1255 /// specified value type. 1256 const TargetRegisterClass *ARMTargetLowering::getRegClassFor(MVT VT) const { 1257 // Map v4i64 to QQ registers but do not make the type legal. Similarly map 1258 // v8i64 to QQQQ registers. v4i64 and v8i64 are only used for REG_SEQUENCE to 1259 // load / store 4 to 8 consecutive D registers. 1260 if (Subtarget->hasNEON()) { 1261 if (VT == MVT::v4i64) 1262 return &ARM::QQPRRegClass; 1263 if (VT == MVT::v8i64) 1264 return &ARM::QQQQPRRegClass; 1265 } 1266 return TargetLowering::getRegClassFor(VT); 1267 } 1268 1269 // memcpy, and other memory intrinsics, typically tries to use LDM/STM if the 1270 // source/dest is aligned and the copy size is large enough. We therefore want 1271 // to align such objects passed to memory intrinsics. 1272 bool ARMTargetLowering::shouldAlignPointerArgs(CallInst *CI, unsigned &MinSize, 1273 unsigned &PrefAlign) const { 1274 if (!isa<MemIntrinsic>(CI)) 1275 return false; 1276 MinSize = 8; 1277 // On ARM11 onwards (excluding M class) 8-byte aligned LDM is typically 1 1278 // cycle faster than 4-byte aligned LDM. 1279 PrefAlign = (Subtarget->hasV6Ops() && !Subtarget->isMClass() ? 8 : 4); 1280 return true; 1281 } 1282 1283 // Create a fast isel object. 1284 FastISel * 1285 ARMTargetLowering::createFastISel(FunctionLoweringInfo &funcInfo, 1286 const TargetLibraryInfo *libInfo) const { 1287 return ARM::createFastISel(funcInfo, libInfo); 1288 } 1289 1290 Sched::Preference ARMTargetLowering::getSchedulingPreference(SDNode *N) const { 1291 unsigned NumVals = N->getNumValues(); 1292 if (!NumVals) 1293 return Sched::RegPressure; 1294 1295 for (unsigned i = 0; i != NumVals; ++i) { 1296 EVT VT = N->getValueType(i); 1297 if (VT == MVT::Glue || VT == MVT::Other) 1298 continue; 1299 if (VT.isFloatingPoint() || VT.isVector()) 1300 return Sched::ILP; 1301 } 1302 1303 if (!N->isMachineOpcode()) 1304 return Sched::RegPressure; 1305 1306 // Load are scheduled for latency even if there instruction itinerary 1307 // is not available. 1308 const TargetInstrInfo *TII = Subtarget->getInstrInfo(); 1309 const MCInstrDesc &MCID = TII->get(N->getMachineOpcode()); 1310 1311 if (MCID.getNumDefs() == 0) 1312 return Sched::RegPressure; 1313 if (!Itins->isEmpty() && 1314 Itins->getOperandCycle(MCID.getSchedClass(), 0) > 2) 1315 return Sched::ILP; 1316 1317 return Sched::RegPressure; 1318 } 1319 1320 //===----------------------------------------------------------------------===// 1321 // Lowering Code 1322 //===----------------------------------------------------------------------===// 1323 1324 /// IntCCToARMCC - Convert a DAG integer condition code to an ARM CC 1325 static ARMCC::CondCodes IntCCToARMCC(ISD::CondCode CC) { 1326 switch (CC) { 1327 default: llvm_unreachable("Unknown condition code!"); 1328 case ISD::SETNE: return ARMCC::NE; 1329 case ISD::SETEQ: return ARMCC::EQ; 1330 case ISD::SETGT: return ARMCC::GT; 1331 case ISD::SETGE: return ARMCC::GE; 1332 case ISD::SETLT: return ARMCC::LT; 1333 case ISD::SETLE: return ARMCC::LE; 1334 case ISD::SETUGT: return ARMCC::HI; 1335 case ISD::SETUGE: return ARMCC::HS; 1336 case ISD::SETULT: return ARMCC::LO; 1337 case ISD::SETULE: return ARMCC::LS; 1338 } 1339 } 1340 1341 /// FPCCToARMCC - Convert a DAG fp condition code to an ARM CC. 1342 static void FPCCToARMCC(ISD::CondCode CC, ARMCC::CondCodes &CondCode, 1343 ARMCC::CondCodes &CondCode2) { 1344 CondCode2 = ARMCC::AL; 1345 switch (CC) { 1346 default: llvm_unreachable("Unknown FP condition!"); 1347 case ISD::SETEQ: 1348 case ISD::SETOEQ: CondCode = ARMCC::EQ; break; 1349 case ISD::SETGT: 1350 case ISD::SETOGT: CondCode = ARMCC::GT; break; 1351 case ISD::SETGE: 1352 case ISD::SETOGE: CondCode = ARMCC::GE; break; 1353 case ISD::SETOLT: CondCode = ARMCC::MI; break; 1354 case ISD::SETOLE: CondCode = ARMCC::LS; break; 1355 case ISD::SETONE: CondCode = ARMCC::MI; CondCode2 = ARMCC::GT; break; 1356 case ISD::SETO: CondCode = ARMCC::VC; break; 1357 case ISD::SETUO: CondCode = ARMCC::VS; break; 1358 case ISD::SETUEQ: CondCode = ARMCC::EQ; CondCode2 = ARMCC::VS; break; 1359 case ISD::SETUGT: CondCode = ARMCC::HI; break; 1360 case ISD::SETUGE: CondCode = ARMCC::PL; break; 1361 case ISD::SETLT: 1362 case ISD::SETULT: CondCode = ARMCC::LT; break; 1363 case ISD::SETLE: 1364 case ISD::SETULE: CondCode = ARMCC::LE; break; 1365 case ISD::SETNE: 1366 case ISD::SETUNE: CondCode = ARMCC::NE; break; 1367 } 1368 } 1369 1370 //===----------------------------------------------------------------------===// 1371 // Calling Convention Implementation 1372 //===----------------------------------------------------------------------===// 1373 1374 #include "ARMGenCallingConv.inc" 1375 1376 /// getEffectiveCallingConv - Get the effective calling convention, taking into 1377 /// account presence of floating point hardware and calling convention 1378 /// limitations, such as support for variadic functions. 1379 CallingConv::ID 1380 ARMTargetLowering::getEffectiveCallingConv(CallingConv::ID CC, 1381 bool isVarArg) const { 1382 switch (CC) { 1383 default: 1384 llvm_unreachable("Unsupported calling convention"); 1385 case CallingConv::ARM_AAPCS: 1386 case CallingConv::ARM_APCS: 1387 case CallingConv::GHC: 1388 return CC; 1389 case CallingConv::PreserveMost: 1390 return CallingConv::PreserveMost; 1391 case CallingConv::ARM_AAPCS_VFP: 1392 case CallingConv::Swift: 1393 return isVarArg ? CallingConv::ARM_AAPCS : CallingConv::ARM_AAPCS_VFP; 1394 case CallingConv::C: 1395 if (!Subtarget->isAAPCS_ABI()) 1396 return CallingConv::ARM_APCS; 1397 else if (Subtarget->hasVFP2() && !Subtarget->isThumb1Only() && 1398 getTargetMachine().Options.FloatABIType == FloatABI::Hard && 1399 !isVarArg) 1400 return CallingConv::ARM_AAPCS_VFP; 1401 else 1402 return CallingConv::ARM_AAPCS; 1403 case CallingConv::Fast: 1404 case CallingConv::CXX_FAST_TLS: 1405 if (!Subtarget->isAAPCS_ABI()) { 1406 if (Subtarget->hasVFP2() && !Subtarget->isThumb1Only() && !isVarArg) 1407 return CallingConv::Fast; 1408 return CallingConv::ARM_APCS; 1409 } else if (Subtarget->hasVFP2() && !Subtarget->isThumb1Only() && !isVarArg) 1410 return CallingConv::ARM_AAPCS_VFP; 1411 else 1412 return CallingConv::ARM_AAPCS; 1413 } 1414 } 1415 1416 /// CCAssignFnForNode - Selects the correct CCAssignFn for the given 1417 /// CallingConvention. 1418 CCAssignFn *ARMTargetLowering::CCAssignFnForNode(CallingConv::ID CC, 1419 bool Return, 1420 bool isVarArg) const { 1421 switch (getEffectiveCallingConv(CC, isVarArg)) { 1422 default: 1423 llvm_unreachable("Unsupported calling convention"); 1424 case CallingConv::ARM_APCS: 1425 return (Return ? RetCC_ARM_APCS : CC_ARM_APCS); 1426 case CallingConv::ARM_AAPCS: 1427 return (Return ? RetCC_ARM_AAPCS : CC_ARM_AAPCS); 1428 case CallingConv::ARM_AAPCS_VFP: 1429 return (Return ? RetCC_ARM_AAPCS_VFP : CC_ARM_AAPCS_VFP); 1430 case CallingConv::Fast: 1431 return (Return ? RetFastCC_ARM_APCS : FastCC_ARM_APCS); 1432 case CallingConv::GHC: 1433 return (Return ? RetCC_ARM_APCS : CC_ARM_APCS_GHC); 1434 case CallingConv::PreserveMost: 1435 return (Return ? RetCC_ARM_AAPCS : CC_ARM_AAPCS); 1436 } 1437 } 1438 1439 /// LowerCallResult - Lower the result values of a call into the 1440 /// appropriate copies out of appropriate physical registers. 1441 SDValue 1442 ARMTargetLowering::LowerCallResult(SDValue Chain, SDValue InFlag, 1443 CallingConv::ID CallConv, bool isVarArg, 1444 const SmallVectorImpl<ISD::InputArg> &Ins, 1445 SDLoc dl, SelectionDAG &DAG, 1446 SmallVectorImpl<SDValue> &InVals, 1447 bool isThisReturn, SDValue ThisVal) const { 1448 1449 // Assign locations to each value returned by this call. 1450 SmallVector<CCValAssign, 16> RVLocs; 1451 ARMCCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs, 1452 *DAG.getContext(), Call); 1453 CCInfo.AnalyzeCallResult(Ins, 1454 CCAssignFnForNode(CallConv, /* Return*/ true, 1455 isVarArg)); 1456 1457 // Copy all of the result registers out of their specified physreg. 1458 for (unsigned i = 0; i != RVLocs.size(); ++i) { 1459 CCValAssign VA = RVLocs[i]; 1460 1461 // Pass 'this' value directly from the argument to return value, to avoid 1462 // reg unit interference 1463 if (i == 0 && isThisReturn) { 1464 assert(!VA.needsCustom() && VA.getLocVT() == MVT::i32 && 1465 "unexpected return calling convention register assignment"); 1466 InVals.push_back(ThisVal); 1467 continue; 1468 } 1469 1470 SDValue Val; 1471 if (VA.needsCustom()) { 1472 // Handle f64 or half of a v2f64. 1473 SDValue Lo = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32, 1474 InFlag); 1475 Chain = Lo.getValue(1); 1476 InFlag = Lo.getValue(2); 1477 VA = RVLocs[++i]; // skip ahead to next loc 1478 SDValue Hi = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32, 1479 InFlag); 1480 Chain = Hi.getValue(1); 1481 InFlag = Hi.getValue(2); 1482 if (!Subtarget->isLittle()) 1483 std::swap (Lo, Hi); 1484 Val = DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi); 1485 1486 if (VA.getLocVT() == MVT::v2f64) { 1487 SDValue Vec = DAG.getNode(ISD::UNDEF, dl, MVT::v2f64); 1488 Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Vec, Val, 1489 DAG.getConstant(0, dl, MVT::i32)); 1490 1491 VA = RVLocs[++i]; // skip ahead to next loc 1492 Lo = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32, InFlag); 1493 Chain = Lo.getValue(1); 1494 InFlag = Lo.getValue(2); 1495 VA = RVLocs[++i]; // skip ahead to next loc 1496 Hi = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32, InFlag); 1497 Chain = Hi.getValue(1); 1498 InFlag = Hi.getValue(2); 1499 if (!Subtarget->isLittle()) 1500 std::swap (Lo, Hi); 1501 Val = DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi); 1502 Val = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Vec, Val, 1503 DAG.getConstant(1, dl, MVT::i32)); 1504 } 1505 } else { 1506 Val = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), VA.getLocVT(), 1507 InFlag); 1508 Chain = Val.getValue(1); 1509 InFlag = Val.getValue(2); 1510 } 1511 1512 switch (VA.getLocInfo()) { 1513 default: llvm_unreachable("Unknown loc info!"); 1514 case CCValAssign::Full: break; 1515 case CCValAssign::BCvt: 1516 Val = DAG.getNode(ISD::BITCAST, dl, VA.getValVT(), Val); 1517 break; 1518 } 1519 1520 InVals.push_back(Val); 1521 } 1522 1523 return Chain; 1524 } 1525 1526 /// LowerMemOpCallTo - Store the argument to the stack. 1527 SDValue 1528 ARMTargetLowering::LowerMemOpCallTo(SDValue Chain, 1529 SDValue StackPtr, SDValue Arg, 1530 SDLoc dl, SelectionDAG &DAG, 1531 const CCValAssign &VA, 1532 ISD::ArgFlagsTy Flags) const { 1533 unsigned LocMemOffset = VA.getLocMemOffset(); 1534 SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset, dl); 1535 PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(DAG.getDataLayout()), 1536 StackPtr, PtrOff); 1537 return DAG.getStore( 1538 Chain, dl, Arg, PtrOff, 1539 MachinePointerInfo::getStack(DAG.getMachineFunction(), LocMemOffset), 1540 false, false, 0); 1541 } 1542 1543 void ARMTargetLowering::PassF64ArgInRegs(SDLoc dl, SelectionDAG &DAG, 1544 SDValue Chain, SDValue &Arg, 1545 RegsToPassVector &RegsToPass, 1546 CCValAssign &VA, CCValAssign &NextVA, 1547 SDValue &StackPtr, 1548 SmallVectorImpl<SDValue> &MemOpChains, 1549 ISD::ArgFlagsTy Flags) const { 1550 1551 SDValue fmrrd = DAG.getNode(ARMISD::VMOVRRD, dl, 1552 DAG.getVTList(MVT::i32, MVT::i32), Arg); 1553 unsigned id = Subtarget->isLittle() ? 0 : 1; 1554 RegsToPass.push_back(std::make_pair(VA.getLocReg(), fmrrd.getValue(id))); 1555 1556 if (NextVA.isRegLoc()) 1557 RegsToPass.push_back(std::make_pair(NextVA.getLocReg(), fmrrd.getValue(1-id))); 1558 else { 1559 assert(NextVA.isMemLoc()); 1560 if (!StackPtr.getNode()) 1561 StackPtr = DAG.getCopyFromReg(Chain, dl, ARM::SP, 1562 getPointerTy(DAG.getDataLayout())); 1563 1564 MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, fmrrd.getValue(1-id), 1565 dl, DAG, NextVA, 1566 Flags)); 1567 } 1568 } 1569 1570 /// LowerCall - Lowering a call into a callseq_start <- 1571 /// ARMISD:CALL <- callseq_end chain. Also add input and output parameter 1572 /// nodes. 1573 SDValue 1574 ARMTargetLowering::LowerCall(TargetLowering::CallLoweringInfo &CLI, 1575 SmallVectorImpl<SDValue> &InVals) const { 1576 SelectionDAG &DAG = CLI.DAG; 1577 SDLoc &dl = CLI.DL; 1578 SmallVectorImpl<ISD::OutputArg> &Outs = CLI.Outs; 1579 SmallVectorImpl<SDValue> &OutVals = CLI.OutVals; 1580 SmallVectorImpl<ISD::InputArg> &Ins = CLI.Ins; 1581 SDValue Chain = CLI.Chain; 1582 SDValue Callee = CLI.Callee; 1583 bool &isTailCall = CLI.IsTailCall; 1584 CallingConv::ID CallConv = CLI.CallConv; 1585 bool doesNotRet = CLI.DoesNotReturn; 1586 bool isVarArg = CLI.IsVarArg; 1587 1588 MachineFunction &MF = DAG.getMachineFunction(); 1589 bool isStructRet = (Outs.empty()) ? false : Outs[0].Flags.isSRet(); 1590 bool isThisReturn = false; 1591 bool isSibCall = false; 1592 auto Attr = MF.getFunction()->getFnAttribute("disable-tail-calls"); 1593 1594 // Disable tail calls if they're not supported. 1595 if (!Subtarget->supportsTailCall() || Attr.getValueAsString() == "true") 1596 isTailCall = false; 1597 1598 if (isTailCall) { 1599 // Check if it's really possible to do a tail call. 1600 isTailCall = IsEligibleForTailCallOptimization(Callee, CallConv, 1601 isVarArg, isStructRet, MF.getFunction()->hasStructRetAttr(), 1602 Outs, OutVals, Ins, DAG); 1603 if (!isTailCall && CLI.CS && CLI.CS->isMustTailCall()) 1604 report_fatal_error("failed to perform tail call elimination on a call " 1605 "site marked musttail"); 1606 // We don't support GuaranteedTailCallOpt for ARM, only automatically 1607 // detected sibcalls. 1608 if (isTailCall) { 1609 ++NumTailCalls; 1610 isSibCall = true; 1611 } 1612 } 1613 1614 // Analyze operands of the call, assigning locations to each operand. 1615 SmallVector<CCValAssign, 16> ArgLocs; 1616 ARMCCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), ArgLocs, 1617 *DAG.getContext(), Call); 1618 CCInfo.AnalyzeCallOperands(Outs, 1619 CCAssignFnForNode(CallConv, /* Return*/ false, 1620 isVarArg)); 1621 1622 // Get a count of how many bytes are to be pushed on the stack. 1623 unsigned NumBytes = CCInfo.getNextStackOffset(); 1624 1625 // For tail calls, memory operands are available in our caller's stack. 1626 if (isSibCall) 1627 NumBytes = 0; 1628 1629 // Adjust the stack pointer for the new arguments... 1630 // These operations are automatically eliminated by the prolog/epilog pass 1631 if (!isSibCall) 1632 Chain = DAG.getCALLSEQ_START(Chain, 1633 DAG.getIntPtrConstant(NumBytes, dl, true), dl); 1634 1635 SDValue StackPtr = 1636 DAG.getCopyFromReg(Chain, dl, ARM::SP, getPointerTy(DAG.getDataLayout())); 1637 1638 RegsToPassVector RegsToPass; 1639 SmallVector<SDValue, 8> MemOpChains; 1640 1641 // Walk the register/memloc assignments, inserting copies/loads. In the case 1642 // of tail call optimization, arguments are handled later. 1643 for (unsigned i = 0, realArgIdx = 0, e = ArgLocs.size(); 1644 i != e; 1645 ++i, ++realArgIdx) { 1646 CCValAssign &VA = ArgLocs[i]; 1647 SDValue Arg = OutVals[realArgIdx]; 1648 ISD::ArgFlagsTy Flags = Outs[realArgIdx].Flags; 1649 bool isByVal = Flags.isByVal(); 1650 1651 // Promote the value if needed. 1652 switch (VA.getLocInfo()) { 1653 default: llvm_unreachable("Unknown loc info!"); 1654 case CCValAssign::Full: break; 1655 case CCValAssign::SExt: 1656 Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), Arg); 1657 break; 1658 case CCValAssign::ZExt: 1659 Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, VA.getLocVT(), Arg); 1660 break; 1661 case CCValAssign::AExt: 1662 Arg = DAG.getNode(ISD::ANY_EXTEND, dl, VA.getLocVT(), Arg); 1663 break; 1664 case CCValAssign::BCvt: 1665 Arg = DAG.getNode(ISD::BITCAST, dl, VA.getLocVT(), Arg); 1666 break; 1667 } 1668 1669 // f64 and v2f64 might be passed in i32 pairs and must be split into pieces 1670 if (VA.needsCustom()) { 1671 if (VA.getLocVT() == MVT::v2f64) { 1672 SDValue Op0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg, 1673 DAG.getConstant(0, dl, MVT::i32)); 1674 SDValue Op1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg, 1675 DAG.getConstant(1, dl, MVT::i32)); 1676 1677 PassF64ArgInRegs(dl, DAG, Chain, Op0, RegsToPass, 1678 VA, ArgLocs[++i], StackPtr, MemOpChains, Flags); 1679 1680 VA = ArgLocs[++i]; // skip ahead to next loc 1681 if (VA.isRegLoc()) { 1682 PassF64ArgInRegs(dl, DAG, Chain, Op1, RegsToPass, 1683 VA, ArgLocs[++i], StackPtr, MemOpChains, Flags); 1684 } else { 1685 assert(VA.isMemLoc()); 1686 1687 MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, Op1, 1688 dl, DAG, VA, Flags)); 1689 } 1690 } else { 1691 PassF64ArgInRegs(dl, DAG, Chain, Arg, RegsToPass, VA, ArgLocs[++i], 1692 StackPtr, MemOpChains, Flags); 1693 } 1694 } else if (VA.isRegLoc()) { 1695 if (realArgIdx == 0 && Flags.isReturned() && Outs[0].VT == MVT::i32) { 1696 assert(VA.getLocVT() == MVT::i32 && 1697 "unexpected calling convention register assignment"); 1698 assert(!Ins.empty() && Ins[0].VT == MVT::i32 && 1699 "unexpected use of 'returned'"); 1700 isThisReturn = true; 1701 } 1702 RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg)); 1703 } else if (isByVal) { 1704 assert(VA.isMemLoc()); 1705 unsigned offset = 0; 1706 1707 // True if this byval aggregate will be split between registers 1708 // and memory. 1709 unsigned ByValArgsCount = CCInfo.getInRegsParamsCount(); 1710 unsigned CurByValIdx = CCInfo.getInRegsParamsProcessed(); 1711 1712 if (CurByValIdx < ByValArgsCount) { 1713 1714 unsigned RegBegin, RegEnd; 1715 CCInfo.getInRegsParamInfo(CurByValIdx, RegBegin, RegEnd); 1716 1717 EVT PtrVT = 1718 DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout()); 1719 unsigned int i, j; 1720 for (i = 0, j = RegBegin; j < RegEnd; i++, j++) { 1721 SDValue Const = DAG.getConstant(4*i, dl, MVT::i32); 1722 SDValue AddArg = DAG.getNode(ISD::ADD, dl, PtrVT, Arg, Const); 1723 SDValue Load = DAG.getLoad(PtrVT, dl, Chain, AddArg, 1724 MachinePointerInfo(), 1725 false, false, false, 1726 DAG.InferPtrAlignment(AddArg)); 1727 MemOpChains.push_back(Load.getValue(1)); 1728 RegsToPass.push_back(std::make_pair(j, Load)); 1729 } 1730 1731 // If parameter size outsides register area, "offset" value 1732 // helps us to calculate stack slot for remained part properly. 1733 offset = RegEnd - RegBegin; 1734 1735 CCInfo.nextInRegsParam(); 1736 } 1737 1738 if (Flags.getByValSize() > 4*offset) { 1739 auto PtrVT = getPointerTy(DAG.getDataLayout()); 1740 unsigned LocMemOffset = VA.getLocMemOffset(); 1741 SDValue StkPtrOff = DAG.getIntPtrConstant(LocMemOffset, dl); 1742 SDValue Dst = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, StkPtrOff); 1743 SDValue SrcOffset = DAG.getIntPtrConstant(4*offset, dl); 1744 SDValue Src = DAG.getNode(ISD::ADD, dl, PtrVT, Arg, SrcOffset); 1745 SDValue SizeNode = DAG.getConstant(Flags.getByValSize() - 4*offset, dl, 1746 MVT::i32); 1747 SDValue AlignNode = DAG.getConstant(Flags.getByValAlign(), dl, 1748 MVT::i32); 1749 1750 SDVTList VTs = DAG.getVTList(MVT::Other, MVT::Glue); 1751 SDValue Ops[] = { Chain, Dst, Src, SizeNode, AlignNode}; 1752 MemOpChains.push_back(DAG.getNode(ARMISD::COPY_STRUCT_BYVAL, dl, VTs, 1753 Ops)); 1754 } 1755 } else if (!isSibCall) { 1756 assert(VA.isMemLoc()); 1757 1758 MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, Arg, 1759 dl, DAG, VA, Flags)); 1760 } 1761 } 1762 1763 if (!MemOpChains.empty()) 1764 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains); 1765 1766 // Build a sequence of copy-to-reg nodes chained together with token chain 1767 // and flag operands which copy the outgoing args into the appropriate regs. 1768 SDValue InFlag; 1769 // Tail call byval lowering might overwrite argument registers so in case of 1770 // tail call optimization the copies to registers are lowered later. 1771 if (!isTailCall) 1772 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) { 1773 Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first, 1774 RegsToPass[i].second, InFlag); 1775 InFlag = Chain.getValue(1); 1776 } 1777 1778 // For tail calls lower the arguments to the 'real' stack slot. 1779 if (isTailCall) { 1780 // Force all the incoming stack arguments to be loaded from the stack 1781 // before any new outgoing arguments are stored to the stack, because the 1782 // outgoing stack slots may alias the incoming argument stack slots, and 1783 // the alias isn't otherwise explicit. This is slightly more conservative 1784 // than necessary, because it means that each store effectively depends 1785 // on every argument instead of just those arguments it would clobber. 1786 1787 // Do not flag preceding copytoreg stuff together with the following stuff. 1788 InFlag = SDValue(); 1789 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) { 1790 Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first, 1791 RegsToPass[i].second, InFlag); 1792 InFlag = Chain.getValue(1); 1793 } 1794 InFlag = SDValue(); 1795 } 1796 1797 // If the callee is a GlobalAddress/ExternalSymbol node (quite common, every 1798 // direct call is) turn it into a TargetGlobalAddress/TargetExternalSymbol 1799 // node so that legalize doesn't hack it. 1800 bool isDirect = false; 1801 bool isARMFunc = false; 1802 bool isLocalARMFunc = false; 1803 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>(); 1804 auto PtrVt = getPointerTy(DAG.getDataLayout()); 1805 1806 if (Subtarget->genLongCalls()) { 1807 assert((Subtarget->isTargetWindows() || 1808 getTargetMachine().getRelocationModel() == Reloc::Static) && 1809 "long-calls with non-static relocation model!"); 1810 // Handle a global address or an external symbol. If it's not one of 1811 // those, the target's already in a register, so we don't need to do 1812 // anything extra. 1813 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) { 1814 const GlobalValue *GV = G->getGlobal(); 1815 // Create a constant pool entry for the callee address 1816 unsigned ARMPCLabelIndex = AFI->createPICLabelUId(); 1817 ARMConstantPoolValue *CPV = 1818 ARMConstantPoolConstant::Create(GV, ARMPCLabelIndex, ARMCP::CPValue, 0); 1819 1820 // Get the address of the callee into a register 1821 SDValue CPAddr = DAG.getTargetConstantPool(CPV, PtrVt, 4); 1822 CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr); 1823 Callee = DAG.getLoad( 1824 PtrVt, dl, DAG.getEntryNode(), CPAddr, 1825 MachinePointerInfo::getConstantPool(DAG.getMachineFunction()), false, 1826 false, false, 0); 1827 } else if (ExternalSymbolSDNode *S=dyn_cast<ExternalSymbolSDNode>(Callee)) { 1828 const char *Sym = S->getSymbol(); 1829 1830 // Create a constant pool entry for the callee address 1831 unsigned ARMPCLabelIndex = AFI->createPICLabelUId(); 1832 ARMConstantPoolValue *CPV = 1833 ARMConstantPoolSymbol::Create(*DAG.getContext(), Sym, 1834 ARMPCLabelIndex, 0); 1835 // Get the address of the callee into a register 1836 SDValue CPAddr = DAG.getTargetConstantPool(CPV, PtrVt, 4); 1837 CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr); 1838 Callee = DAG.getLoad( 1839 PtrVt, dl, DAG.getEntryNode(), CPAddr, 1840 MachinePointerInfo::getConstantPool(DAG.getMachineFunction()), false, 1841 false, false, 0); 1842 } 1843 } else if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) { 1844 const GlobalValue *GV = G->getGlobal(); 1845 isDirect = true; 1846 bool isDef = GV->isStrongDefinitionForLinker(); 1847 bool isStub = (!isDef && Subtarget->isTargetMachO()) && 1848 getTargetMachine().getRelocationModel() != Reloc::Static; 1849 isARMFunc = !Subtarget->isThumb() || (isStub && !Subtarget->isMClass()); 1850 // ARM call to a local ARM function is predicable. 1851 isLocalARMFunc = !Subtarget->isThumb() && (isDef || !ARMInterworking); 1852 // tBX takes a register source operand. 1853 if (isStub && Subtarget->isThumb1Only() && !Subtarget->hasV5TOps()) { 1854 assert(Subtarget->isTargetMachO() && "WrapperPIC use on non-MachO?"); 1855 Callee = DAG.getNode( 1856 ARMISD::WrapperPIC, dl, PtrVt, 1857 DAG.getTargetGlobalAddress(GV, dl, PtrVt, 0, ARMII::MO_NONLAZY)); 1858 Callee = DAG.getLoad(PtrVt, dl, DAG.getEntryNode(), Callee, 1859 MachinePointerInfo::getGOT(DAG.getMachineFunction()), 1860 false, false, true, 0); 1861 } else if (Subtarget->isTargetCOFF()) { 1862 assert(Subtarget->isTargetWindows() && 1863 "Windows is the only supported COFF target"); 1864 unsigned TargetFlags = GV->hasDLLImportStorageClass() 1865 ? ARMII::MO_DLLIMPORT 1866 : ARMII::MO_NO_FLAG; 1867 Callee = 1868 DAG.getTargetGlobalAddress(GV, dl, PtrVt, /*Offset=*/0, TargetFlags); 1869 if (GV->hasDLLImportStorageClass()) 1870 Callee = 1871 DAG.getLoad(PtrVt, dl, DAG.getEntryNode(), 1872 DAG.getNode(ARMISD::Wrapper, dl, PtrVt, Callee), 1873 MachinePointerInfo::getGOT(DAG.getMachineFunction()), 1874 false, false, false, 0); 1875 } else { 1876 // On ELF targets for PIC code, direct calls should go through the PLT 1877 unsigned OpFlags = 0; 1878 if (Subtarget->isTargetELF() && 1879 getTargetMachine().getRelocationModel() == Reloc::PIC_) 1880 OpFlags = ARMII::MO_PLT; 1881 Callee = DAG.getTargetGlobalAddress(GV, dl, PtrVt, 0, OpFlags); 1882 } 1883 } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) { 1884 isDirect = true; 1885 bool isStub = Subtarget->isTargetMachO() && 1886 getTargetMachine().getRelocationModel() != Reloc::Static; 1887 isARMFunc = !Subtarget->isThumb() || (isStub && !Subtarget->isMClass()); 1888 // tBX takes a register source operand. 1889 const char *Sym = S->getSymbol(); 1890 if (isARMFunc && Subtarget->isThumb1Only() && !Subtarget->hasV5TOps()) { 1891 unsigned ARMPCLabelIndex = AFI->createPICLabelUId(); 1892 ARMConstantPoolValue *CPV = 1893 ARMConstantPoolSymbol::Create(*DAG.getContext(), Sym, 1894 ARMPCLabelIndex, 4); 1895 SDValue CPAddr = DAG.getTargetConstantPool(CPV, PtrVt, 4); 1896 CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr); 1897 Callee = DAG.getLoad( 1898 PtrVt, dl, DAG.getEntryNode(), CPAddr, 1899 MachinePointerInfo::getConstantPool(DAG.getMachineFunction()), false, 1900 false, false, 0); 1901 SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, dl, MVT::i32); 1902 Callee = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVt, Callee, PICLabel); 1903 } else { 1904 unsigned OpFlags = 0; 1905 // On ELF targets for PIC code, direct calls should go through the PLT 1906 if (Subtarget->isTargetELF() && 1907 getTargetMachine().getRelocationModel() == Reloc::PIC_) 1908 OpFlags = ARMII::MO_PLT; 1909 Callee = DAG.getTargetExternalSymbol(Sym, PtrVt, OpFlags); 1910 } 1911 } 1912 1913 // FIXME: handle tail calls differently. 1914 unsigned CallOpc; 1915 if (Subtarget->isThumb()) { 1916 if ((!isDirect || isARMFunc) && !Subtarget->hasV5TOps()) 1917 CallOpc = ARMISD::CALL_NOLINK; 1918 else 1919 CallOpc = isARMFunc ? ARMISD::CALL : ARMISD::tCALL; 1920 } else { 1921 if (!isDirect && !Subtarget->hasV5TOps()) 1922 CallOpc = ARMISD::CALL_NOLINK; 1923 else if (doesNotRet && isDirect && Subtarget->hasRAS() && 1924 // Emit regular call when code size is the priority 1925 !MF.getFunction()->optForMinSize()) 1926 // "mov lr, pc; b _foo" to avoid confusing the RSP 1927 CallOpc = ARMISD::CALL_NOLINK; 1928 else 1929 CallOpc = isLocalARMFunc ? ARMISD::CALL_PRED : ARMISD::CALL; 1930 } 1931 1932 std::vector<SDValue> Ops; 1933 Ops.push_back(Chain); 1934 Ops.push_back(Callee); 1935 1936 // Add argument registers to the end of the list so that they are known live 1937 // into the call. 1938 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) 1939 Ops.push_back(DAG.getRegister(RegsToPass[i].first, 1940 RegsToPass[i].second.getValueType())); 1941 1942 // Add a register mask operand representing the call-preserved registers. 1943 if (!isTailCall) { 1944 const uint32_t *Mask; 1945 const ARMBaseRegisterInfo *ARI = Subtarget->getRegisterInfo(); 1946 if (isThisReturn) { 1947 // For 'this' returns, use the R0-preserving mask if applicable 1948 Mask = ARI->getThisReturnPreservedMask(MF, CallConv); 1949 if (!Mask) { 1950 // Set isThisReturn to false if the calling convention is not one that 1951 // allows 'returned' to be modeled in this way, so LowerCallResult does 1952 // not try to pass 'this' straight through 1953 isThisReturn = false; 1954 Mask = ARI->getCallPreservedMask(MF, CallConv); 1955 } 1956 } else 1957 Mask = ARI->getCallPreservedMask(MF, CallConv); 1958 1959 assert(Mask && "Missing call preserved mask for calling convention"); 1960 Ops.push_back(DAG.getRegisterMask(Mask)); 1961 } 1962 1963 if (InFlag.getNode()) 1964 Ops.push_back(InFlag); 1965 1966 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue); 1967 if (isTailCall) { 1968 MF.getFrameInfo()->setHasTailCall(); 1969 return DAG.getNode(ARMISD::TC_RETURN, dl, NodeTys, Ops); 1970 } 1971 1972 // Returns a chain and a flag for retval copy to use. 1973 Chain = DAG.getNode(CallOpc, dl, NodeTys, Ops); 1974 InFlag = Chain.getValue(1); 1975 1976 Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, dl, true), 1977 DAG.getIntPtrConstant(0, dl, true), InFlag, dl); 1978 if (!Ins.empty()) 1979 InFlag = Chain.getValue(1); 1980 1981 // Handle result values, copying them out of physregs into vregs that we 1982 // return. 1983 return LowerCallResult(Chain, InFlag, CallConv, isVarArg, Ins, dl, DAG, 1984 InVals, isThisReturn, 1985 isThisReturn ? OutVals[0] : SDValue()); 1986 } 1987 1988 /// HandleByVal - Every parameter *after* a byval parameter is passed 1989 /// on the stack. Remember the next parameter register to allocate, 1990 /// and then confiscate the rest of the parameter registers to insure 1991 /// this. 1992 void ARMTargetLowering::HandleByVal(CCState *State, unsigned &Size, 1993 unsigned Align) const { 1994 assert((State->getCallOrPrologue() == Prologue || 1995 State->getCallOrPrologue() == Call) && 1996 "unhandled ParmContext"); 1997 1998 // Byval (as with any stack) slots are always at least 4 byte aligned. 1999 Align = std::max(Align, 4U); 2000 2001 unsigned Reg = State->AllocateReg(GPRArgRegs); 2002 if (!Reg) 2003 return; 2004 2005 unsigned AlignInRegs = Align / 4; 2006 unsigned Waste = (ARM::R4 - Reg) % AlignInRegs; 2007 for (unsigned i = 0; i < Waste; ++i) 2008 Reg = State->AllocateReg(GPRArgRegs); 2009 2010 if (!Reg) 2011 return; 2012 2013 unsigned Excess = 4 * (ARM::R4 - Reg); 2014 2015 // Special case when NSAA != SP and parameter size greater than size of 2016 // all remained GPR regs. In that case we can't split parameter, we must 2017 // send it to stack. We also must set NCRN to R4, so waste all 2018 // remained registers. 2019 const unsigned NSAAOffset = State->getNextStackOffset(); 2020 if (NSAAOffset != 0 && Size > Excess) { 2021 while (State->AllocateReg(GPRArgRegs)) 2022 ; 2023 return; 2024 } 2025 2026 // First register for byval parameter is the first register that wasn't 2027 // allocated before this method call, so it would be "reg". 2028 // If parameter is small enough to be saved in range [reg, r4), then 2029 // the end (first after last) register would be reg + param-size-in-regs, 2030 // else parameter would be splitted between registers and stack, 2031 // end register would be r4 in this case. 2032 unsigned ByValRegBegin = Reg; 2033 unsigned ByValRegEnd = std::min<unsigned>(Reg + Size / 4, ARM::R4); 2034 State->addInRegsParamInfo(ByValRegBegin, ByValRegEnd); 2035 // Note, first register is allocated in the beginning of function already, 2036 // allocate remained amount of registers we need. 2037 for (unsigned i = Reg + 1; i != ByValRegEnd; ++i) 2038 State->AllocateReg(GPRArgRegs); 2039 // A byval parameter that is split between registers and memory needs its 2040 // size truncated here. 2041 // In the case where the entire structure fits in registers, we set the 2042 // size in memory to zero. 2043 Size = std::max<int>(Size - Excess, 0); 2044 } 2045 2046 /// MatchingStackOffset - Return true if the given stack call argument is 2047 /// already available in the same position (relatively) of the caller's 2048 /// incoming argument stack. 2049 static 2050 bool MatchingStackOffset(SDValue Arg, unsigned Offset, ISD::ArgFlagsTy Flags, 2051 MachineFrameInfo *MFI, const MachineRegisterInfo *MRI, 2052 const TargetInstrInfo *TII) { 2053 unsigned Bytes = Arg.getValueType().getSizeInBits() / 8; 2054 int FI = INT_MAX; 2055 if (Arg.getOpcode() == ISD::CopyFromReg) { 2056 unsigned VR = cast<RegisterSDNode>(Arg.getOperand(1))->getReg(); 2057 if (!TargetRegisterInfo::isVirtualRegister(VR)) 2058 return false; 2059 MachineInstr *Def = MRI->getVRegDef(VR); 2060 if (!Def) 2061 return false; 2062 if (!Flags.isByVal()) { 2063 if (!TII->isLoadFromStackSlot(Def, FI)) 2064 return false; 2065 } else { 2066 return false; 2067 } 2068 } else if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Arg)) { 2069 if (Flags.isByVal()) 2070 // ByVal argument is passed in as a pointer but it's now being 2071 // dereferenced. e.g. 2072 // define @foo(%struct.X* %A) { 2073 // tail call @bar(%struct.X* byval %A) 2074 // } 2075 return false; 2076 SDValue Ptr = Ld->getBasePtr(); 2077 FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr); 2078 if (!FINode) 2079 return false; 2080 FI = FINode->getIndex(); 2081 } else 2082 return false; 2083 2084 assert(FI != INT_MAX); 2085 if (!MFI->isFixedObjectIndex(FI)) 2086 return false; 2087 return Offset == MFI->getObjectOffset(FI) && Bytes == MFI->getObjectSize(FI); 2088 } 2089 2090 /// IsEligibleForTailCallOptimization - Check whether the call is eligible 2091 /// for tail call optimization. Targets which want to do tail call 2092 /// optimization should implement this function. 2093 bool 2094 ARMTargetLowering::IsEligibleForTailCallOptimization(SDValue Callee, 2095 CallingConv::ID CalleeCC, 2096 bool isVarArg, 2097 bool isCalleeStructRet, 2098 bool isCallerStructRet, 2099 const SmallVectorImpl<ISD::OutputArg> &Outs, 2100 const SmallVectorImpl<SDValue> &OutVals, 2101 const SmallVectorImpl<ISD::InputArg> &Ins, 2102 SelectionDAG& DAG) const { 2103 MachineFunction &MF = DAG.getMachineFunction(); 2104 const Function *CallerF = MF.getFunction(); 2105 CallingConv::ID CallerCC = CallerF->getCallingConv(); 2106 2107 assert(Subtarget->supportsTailCall()); 2108 2109 // Look for obvious safe cases to perform tail call optimization that do not 2110 // require ABI changes. This is what gcc calls sibcall. 2111 2112 // Do not sibcall optimize vararg calls unless the call site is not passing 2113 // any arguments. 2114 if (isVarArg && !Outs.empty()) 2115 return false; 2116 2117 // Exception-handling functions need a special set of instructions to indicate 2118 // a return to the hardware. Tail-calling another function would probably 2119 // break this. 2120 if (CallerF->hasFnAttribute("interrupt")) 2121 return false; 2122 2123 // Also avoid sibcall optimization if either caller or callee uses struct 2124 // return semantics. 2125 if (isCalleeStructRet || isCallerStructRet) 2126 return false; 2127 2128 // Externally-defined functions with weak linkage should not be 2129 // tail-called on ARM when the OS does not support dynamic 2130 // pre-emption of symbols, as the AAELF spec requires normal calls 2131 // to undefined weak functions to be replaced with a NOP or jump to the 2132 // next instruction. The behaviour of branch instructions in this 2133 // situation (as used for tail calls) is implementation-defined, so we 2134 // cannot rely on the linker replacing the tail call with a return. 2135 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) { 2136 const GlobalValue *GV = G->getGlobal(); 2137 const Triple &TT = getTargetMachine().getTargetTriple(); 2138 if (GV->hasExternalWeakLinkage() && 2139 (!TT.isOSWindows() || TT.isOSBinFormatELF() || TT.isOSBinFormatMachO())) 2140 return false; 2141 } 2142 2143 // Check that the call results are passed in the same way. 2144 LLVMContext &C = *DAG.getContext(); 2145 if (!CCState::resultsCompatible(CalleeCC, CallerCC, MF, C, Ins, 2146 CCAssignFnForNode(CalleeCC, true, isVarArg), 2147 CCAssignFnForNode(CallerCC, true, isVarArg))) 2148 return false; 2149 // The callee has to preserve all registers the caller needs to preserve. 2150 const ARMBaseRegisterInfo *TRI = Subtarget->getRegisterInfo(); 2151 const uint32_t *CallerPreserved = TRI->getCallPreservedMask(MF, CallerCC); 2152 if (CalleeCC != CallerCC) { 2153 const uint32_t *CalleePreserved = TRI->getCallPreservedMask(MF, CalleeCC); 2154 if (!TRI->regmaskSubsetEqual(CallerPreserved, CalleePreserved)) 2155 return false; 2156 } 2157 2158 // If Caller's vararg or byval argument has been split between registers and 2159 // stack, do not perform tail call, since part of the argument is in caller's 2160 // local frame. 2161 const ARMFunctionInfo *AFI_Caller = MF.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, MF, ArgLocs, C, Call); 2172 CCInfo.AnalyzeCallOperands(Outs, 2173 CCAssignFnForNode(CalleeCC, false, isVarArg)); 2174 if (CCInfo.getNextStackOffset()) { 2175 // Check if the arguments are already laid out in the right way as 2176 // the caller's fixed stack objects. 2177 MachineFrameInfo *MFI = MF.getFrameInfo(); 2178 const MachineRegisterInfo *MRI = &MF.getRegInfo(); 2179 const TargetInstrInfo *TII = Subtarget->getInstrInfo(); 2180 for (unsigned i = 0, realArgIdx = 0, e = ArgLocs.size(); 2181 i != e; 2182 ++i, ++realArgIdx) { 2183 CCValAssign &VA = ArgLocs[i]; 2184 EVT RegVT = VA.getLocVT(); 2185 SDValue Arg = OutVals[realArgIdx]; 2186 ISD::ArgFlagsTy Flags = Outs[realArgIdx].Flags; 2187 if (VA.getLocInfo() == CCValAssign::Indirect) 2188 return false; 2189 if (VA.needsCustom()) { 2190 // f64 and vector types are split into multiple registers or 2191 // register/stack-slot combinations. The types will not match 2192 // the registers; give up on memory f64 refs until we figure 2193 // out what to do about this. 2194 if (!VA.isRegLoc()) 2195 return false; 2196 if (!ArgLocs[++i].isRegLoc()) 2197 return false; 2198 if (RegVT == MVT::v2f64) { 2199 if (!ArgLocs[++i].isRegLoc()) 2200 return false; 2201 if (!ArgLocs[++i].isRegLoc()) 2202 return false; 2203 } 2204 } else if (!VA.isRegLoc()) { 2205 if (!MatchingStackOffset(Arg, VA.getLocMemOffset(), Flags, 2206 MFI, MRI, TII)) 2207 return false; 2208 } 2209 } 2210 } 2211 2212 const MachineRegisterInfo &MRI = MF.getRegInfo(); 2213 if (!parametersInCSRMatch(MRI, CallerPreserved, ArgLocs, OutVals)) 2214 return false; 2215 } 2216 2217 return true; 2218 } 2219 2220 bool 2221 ARMTargetLowering::CanLowerReturn(CallingConv::ID CallConv, 2222 MachineFunction &MF, bool isVarArg, 2223 const SmallVectorImpl<ISD::OutputArg> &Outs, 2224 LLVMContext &Context) const { 2225 SmallVector<CCValAssign, 16> RVLocs; 2226 CCState CCInfo(CallConv, isVarArg, MF, RVLocs, Context); 2227 return CCInfo.CheckReturn(Outs, CCAssignFnForNode(CallConv, /*Return=*/true, 2228 isVarArg)); 2229 } 2230 2231 static SDValue LowerInterruptReturn(SmallVectorImpl<SDValue> &RetOps, 2232 SDLoc DL, SelectionDAG &DAG) { 2233 const MachineFunction &MF = DAG.getMachineFunction(); 2234 const Function *F = MF.getFunction(); 2235 2236 StringRef IntKind = F->getFnAttribute("interrupt").getValueAsString(); 2237 2238 // See ARM ARM v7 B1.8.3. On exception entry LR is set to a possibly offset 2239 // version of the "preferred return address". These offsets affect the return 2240 // instruction if this is a return from PL1 without hypervisor extensions. 2241 // IRQ/FIQ: +4 "subs pc, lr, #4" 2242 // SWI: 0 "subs pc, lr, #0" 2243 // ABORT: +4 "subs pc, lr, #4" 2244 // UNDEF: +4/+2 "subs pc, lr, #0" 2245 // UNDEF varies depending on where the exception came from ARM or Thumb 2246 // mode. Alongside GCC, we throw our hands up in disgust and pretend it's 0. 2247 2248 int64_t LROffset; 2249 if (IntKind == "" || IntKind == "IRQ" || IntKind == "FIQ" || 2250 IntKind == "ABORT") 2251 LROffset = 4; 2252 else if (IntKind == "SWI" || IntKind == "UNDEF") 2253 LROffset = 0; 2254 else 2255 report_fatal_error("Unsupported interrupt attribute. If present, value " 2256 "must be one of: IRQ, FIQ, SWI, ABORT or UNDEF"); 2257 2258 RetOps.insert(RetOps.begin() + 1, 2259 DAG.getConstant(LROffset, DL, MVT::i32, false)); 2260 2261 return DAG.getNode(ARMISD::INTRET_FLAG, DL, MVT::Other, RetOps); 2262 } 2263 2264 SDValue 2265 ARMTargetLowering::LowerReturn(SDValue Chain, 2266 CallingConv::ID CallConv, bool isVarArg, 2267 const SmallVectorImpl<ISD::OutputArg> &Outs, 2268 const SmallVectorImpl<SDValue> &OutVals, 2269 SDLoc dl, SelectionDAG &DAG) const { 2270 2271 // CCValAssign - represent the assignment of the return value to a location. 2272 SmallVector<CCValAssign, 16> RVLocs; 2273 2274 // CCState - Info about the registers and stack slots. 2275 ARMCCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs, 2276 *DAG.getContext(), Call); 2277 2278 // Analyze outgoing return values. 2279 CCInfo.AnalyzeReturn(Outs, CCAssignFnForNode(CallConv, /* Return */ true, 2280 isVarArg)); 2281 2282 SDValue Flag; 2283 SmallVector<SDValue, 4> RetOps; 2284 RetOps.push_back(Chain); // Operand #0 = Chain (updated below) 2285 bool isLittleEndian = Subtarget->isLittle(); 2286 2287 MachineFunction &MF = DAG.getMachineFunction(); 2288 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>(); 2289 AFI->setReturnRegsCount(RVLocs.size()); 2290 2291 // Copy the result values into the output registers. 2292 for (unsigned i = 0, realRVLocIdx = 0; 2293 i != RVLocs.size(); 2294 ++i, ++realRVLocIdx) { 2295 CCValAssign &VA = RVLocs[i]; 2296 assert(VA.isRegLoc() && "Can only return in registers!"); 2297 2298 SDValue Arg = OutVals[realRVLocIdx]; 2299 2300 switch (VA.getLocInfo()) { 2301 default: llvm_unreachable("Unknown loc info!"); 2302 case CCValAssign::Full: break; 2303 case CCValAssign::BCvt: 2304 Arg = DAG.getNode(ISD::BITCAST, dl, VA.getLocVT(), Arg); 2305 break; 2306 } 2307 2308 if (VA.needsCustom()) { 2309 if (VA.getLocVT() == MVT::v2f64) { 2310 // Extract the first half and return it in two registers. 2311 SDValue Half = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg, 2312 DAG.getConstant(0, dl, MVT::i32)); 2313 SDValue HalfGPRs = DAG.getNode(ARMISD::VMOVRRD, dl, 2314 DAG.getVTList(MVT::i32, MVT::i32), Half); 2315 2316 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), 2317 HalfGPRs.getValue(isLittleEndian ? 0 : 1), 2318 Flag); 2319 Flag = Chain.getValue(1); 2320 RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT())); 2321 VA = RVLocs[++i]; // skip ahead to next loc 2322 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), 2323 HalfGPRs.getValue(isLittleEndian ? 1 : 0), 2324 Flag); 2325 Flag = Chain.getValue(1); 2326 RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT())); 2327 VA = RVLocs[++i]; // skip ahead to next loc 2328 2329 // Extract the 2nd half and fall through to handle it as an f64 value. 2330 Arg = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg, 2331 DAG.getConstant(1, dl, MVT::i32)); 2332 } 2333 // Legalize ret f64 -> ret 2 x i32. We always have fmrrd if f64 is 2334 // available. 2335 SDValue fmrrd = DAG.getNode(ARMISD::VMOVRRD, dl, 2336 DAG.getVTList(MVT::i32, MVT::i32), Arg); 2337 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), 2338 fmrrd.getValue(isLittleEndian ? 0 : 1), 2339 Flag); 2340 Flag = Chain.getValue(1); 2341 RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT())); 2342 VA = RVLocs[++i]; // skip ahead to next loc 2343 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), 2344 fmrrd.getValue(isLittleEndian ? 1 : 0), 2345 Flag); 2346 } else 2347 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), Arg, Flag); 2348 2349 // Guarantee that all emitted copies are 2350 // stuck together, avoiding something bad. 2351 Flag = Chain.getValue(1); 2352 RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT())); 2353 } 2354 const ARMBaseRegisterInfo *TRI = Subtarget->getRegisterInfo(); 2355 const MCPhysReg *I = 2356 TRI->getCalleeSavedRegsViaCopy(&DAG.getMachineFunction()); 2357 if (I) { 2358 for (; *I; ++I) { 2359 if (ARM::GPRRegClass.contains(*I)) 2360 RetOps.push_back(DAG.getRegister(*I, MVT::i32)); 2361 else if (ARM::DPRRegClass.contains(*I)) 2362 RetOps.push_back(DAG.getRegister(*I, MVT::getFloatingPointVT(64))); 2363 else 2364 llvm_unreachable("Unexpected register class in CSRsViaCopy!"); 2365 } 2366 } 2367 2368 // Update chain and glue. 2369 RetOps[0] = Chain; 2370 if (Flag.getNode()) 2371 RetOps.push_back(Flag); 2372 2373 // CPUs which aren't M-class use a special sequence to return from 2374 // exceptions (roughly, any instruction setting pc and cpsr simultaneously, 2375 // though we use "subs pc, lr, #N"). 2376 // 2377 // M-class CPUs actually use a normal return sequence with a special 2378 // (hardware-provided) value in LR, so the normal code path works. 2379 if (DAG.getMachineFunction().getFunction()->hasFnAttribute("interrupt") && 2380 !Subtarget->isMClass()) { 2381 if (Subtarget->isThumb1Only()) 2382 report_fatal_error("interrupt attribute is not supported in Thumb1"); 2383 return LowerInterruptReturn(RetOps, dl, DAG); 2384 } 2385 2386 return DAG.getNode(ARMISD::RET_FLAG, dl, MVT::Other, RetOps); 2387 } 2388 2389 bool ARMTargetLowering::isUsedByReturnOnly(SDNode *N, SDValue &Chain) const { 2390 if (N->getNumValues() != 1) 2391 return false; 2392 if (!N->hasNUsesOfValue(1, 0)) 2393 return false; 2394 2395 SDValue TCChain = Chain; 2396 SDNode *Copy = *N->use_begin(); 2397 if (Copy->getOpcode() == ISD::CopyToReg) { 2398 // If the copy has a glue operand, we conservatively assume it isn't safe to 2399 // perform a tail call. 2400 if (Copy->getOperand(Copy->getNumOperands()-1).getValueType() == MVT::Glue) 2401 return false; 2402 TCChain = Copy->getOperand(0); 2403 } else if (Copy->getOpcode() == ARMISD::VMOVRRD) { 2404 SDNode *VMov = Copy; 2405 // f64 returned in a pair of GPRs. 2406 SmallPtrSet<SDNode*, 2> Copies; 2407 for (SDNode::use_iterator UI = VMov->use_begin(), UE = VMov->use_end(); 2408 UI != UE; ++UI) { 2409 if (UI->getOpcode() != ISD::CopyToReg) 2410 return false; 2411 Copies.insert(*UI); 2412 } 2413 if (Copies.size() > 2) 2414 return false; 2415 2416 for (SDNode::use_iterator UI = VMov->use_begin(), UE = VMov->use_end(); 2417 UI != UE; ++UI) { 2418 SDValue UseChain = UI->getOperand(0); 2419 if (Copies.count(UseChain.getNode())) 2420 // Second CopyToReg 2421 Copy = *UI; 2422 else { 2423 // We are at the top of this chain. 2424 // If the copy has a glue operand, we conservatively assume it 2425 // isn't safe to perform a tail call. 2426 if (UI->getOperand(UI->getNumOperands()-1).getValueType() == MVT::Glue) 2427 return false; 2428 // First CopyToReg 2429 TCChain = UseChain; 2430 } 2431 } 2432 } else if (Copy->getOpcode() == ISD::BITCAST) { 2433 // f32 returned in a single GPR. 2434 if (!Copy->hasOneUse()) 2435 return false; 2436 Copy = *Copy->use_begin(); 2437 if (Copy->getOpcode() != ISD::CopyToReg || !Copy->hasNUsesOfValue(1, 0)) 2438 return false; 2439 // If the copy has a glue operand, we conservatively assume it isn't safe to 2440 // perform a tail call. 2441 if (Copy->getOperand(Copy->getNumOperands()-1).getValueType() == MVT::Glue) 2442 return false; 2443 TCChain = Copy->getOperand(0); 2444 } else { 2445 return false; 2446 } 2447 2448 bool HasRet = false; 2449 for (SDNode::use_iterator UI = Copy->use_begin(), UE = Copy->use_end(); 2450 UI != UE; ++UI) { 2451 if (UI->getOpcode() != ARMISD::RET_FLAG && 2452 UI->getOpcode() != ARMISD::INTRET_FLAG) 2453 return false; 2454 HasRet = true; 2455 } 2456 2457 if (!HasRet) 2458 return false; 2459 2460 Chain = TCChain; 2461 return true; 2462 } 2463 2464 bool ARMTargetLowering::mayBeEmittedAsTailCall(CallInst *CI) const { 2465 if (!Subtarget->supportsTailCall()) 2466 return false; 2467 2468 auto Attr = 2469 CI->getParent()->getParent()->getFnAttribute("disable-tail-calls"); 2470 if (!CI->isTailCall() || Attr.getValueAsString() == "true") 2471 return false; 2472 2473 return true; 2474 } 2475 2476 // Trying to write a 64 bit value so need to split into two 32 bit values first, 2477 // and pass the lower and high parts through. 2478 static SDValue LowerWRITE_REGISTER(SDValue Op, SelectionDAG &DAG) { 2479 SDLoc DL(Op); 2480 SDValue WriteValue = Op->getOperand(2); 2481 2482 // This function is only supposed to be called for i64 type argument. 2483 assert(WriteValue.getValueType() == MVT::i64 2484 && "LowerWRITE_REGISTER called for non-i64 type argument."); 2485 2486 SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, WriteValue, 2487 DAG.getConstant(0, DL, MVT::i32)); 2488 SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, WriteValue, 2489 DAG.getConstant(1, DL, MVT::i32)); 2490 SDValue Ops[] = { Op->getOperand(0), Op->getOperand(1), Lo, Hi }; 2491 return DAG.getNode(ISD::WRITE_REGISTER, DL, MVT::Other, Ops); 2492 } 2493 2494 // ConstantPool, JumpTable, GlobalAddress, and ExternalSymbol are lowered as 2495 // their target counterpart wrapped in the ARMISD::Wrapper node. Suppose N is 2496 // one of the above mentioned nodes. It has to be wrapped because otherwise 2497 // Select(N) returns N. So the raw TargetGlobalAddress nodes, etc. can only 2498 // be used to form addressing mode. These wrapped nodes will be selected 2499 // into MOVi. 2500 static SDValue LowerConstantPool(SDValue Op, SelectionDAG &DAG) { 2501 EVT PtrVT = Op.getValueType(); 2502 // FIXME there is no actual debug info here 2503 SDLoc dl(Op); 2504 ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op); 2505 SDValue Res; 2506 if (CP->isMachineConstantPoolEntry()) 2507 Res = DAG.getTargetConstantPool(CP->getMachineCPVal(), PtrVT, 2508 CP->getAlignment()); 2509 else 2510 Res = DAG.getTargetConstantPool(CP->getConstVal(), PtrVT, 2511 CP->getAlignment()); 2512 return DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Res); 2513 } 2514 2515 unsigned ARMTargetLowering::getJumpTableEncoding() const { 2516 return MachineJumpTableInfo::EK_Inline; 2517 } 2518 2519 SDValue ARMTargetLowering::LowerBlockAddress(SDValue Op, 2520 SelectionDAG &DAG) const { 2521 MachineFunction &MF = DAG.getMachineFunction(); 2522 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>(); 2523 unsigned ARMPCLabelIndex = 0; 2524 SDLoc DL(Op); 2525 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 2526 const BlockAddress *BA = cast<BlockAddressSDNode>(Op)->getBlockAddress(); 2527 Reloc::Model RelocM = getTargetMachine().getRelocationModel(); 2528 SDValue CPAddr; 2529 if (RelocM == Reloc::Static) { 2530 CPAddr = DAG.getTargetConstantPool(BA, PtrVT, 4); 2531 } else { 2532 unsigned PCAdj = Subtarget->isThumb() ? 4 : 8; 2533 ARMPCLabelIndex = AFI->createPICLabelUId(); 2534 ARMConstantPoolValue *CPV = 2535 ARMConstantPoolConstant::Create(BA, ARMPCLabelIndex, 2536 ARMCP::CPBlockAddress, PCAdj); 2537 CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4); 2538 } 2539 CPAddr = DAG.getNode(ARMISD::Wrapper, DL, PtrVT, CPAddr); 2540 SDValue Result = 2541 DAG.getLoad(PtrVT, DL, DAG.getEntryNode(), CPAddr, 2542 MachinePointerInfo::getConstantPool(DAG.getMachineFunction()), 2543 false, false, false, 0); 2544 if (RelocM == Reloc::Static) 2545 return Result; 2546 SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, DL, MVT::i32); 2547 return DAG.getNode(ARMISD::PIC_ADD, DL, PtrVT, Result, PICLabel); 2548 } 2549 2550 /// \brief Convert a TLS address reference into the correct sequence of loads 2551 /// and calls to compute the variable's address for Darwin, and return an 2552 /// SDValue containing the final node. 2553 2554 /// Darwin only has one TLS scheme which must be capable of dealing with the 2555 /// fully general situation, in the worst case. This means: 2556 /// + "extern __thread" declaration. 2557 /// + Defined in a possibly unknown dynamic library. 2558 /// 2559 /// The general system is that each __thread variable has a [3 x i32] descriptor 2560 /// which contains information used by the runtime to calculate the address. The 2561 /// only part of this the compiler needs to know about is the first word, which 2562 /// contains a function pointer that must be called with the address of the 2563 /// entire descriptor in "r0". 2564 /// 2565 /// Since this descriptor may be in a different unit, in general access must 2566 /// proceed along the usual ARM rules. A common sequence to produce is: 2567 /// 2568 /// movw rT1, :lower16:_var$non_lazy_ptr 2569 /// movt rT1, :upper16:_var$non_lazy_ptr 2570 /// ldr r0, [rT1] 2571 /// ldr rT2, [r0] 2572 /// blx rT2 2573 /// [...address now in r0...] 2574 SDValue 2575 ARMTargetLowering::LowerGlobalTLSAddressDarwin(SDValue Op, 2576 SelectionDAG &DAG) const { 2577 assert(Subtarget->isTargetDarwin() && "TLS only supported on Darwin"); 2578 SDLoc DL(Op); 2579 2580 // First step is to get the address of the actua global symbol. This is where 2581 // the TLS descriptor lives. 2582 SDValue DescAddr = LowerGlobalAddressDarwin(Op, DAG); 2583 2584 // The first entry in the descriptor is a function pointer that we must call 2585 // to obtain the address of the variable. 2586 SDValue Chain = DAG.getEntryNode(); 2587 SDValue FuncTLVGet = 2588 DAG.getLoad(MVT::i32, DL, Chain, DescAddr, 2589 MachinePointerInfo::getGOT(DAG.getMachineFunction()), 2590 false, true, true, 4); 2591 Chain = FuncTLVGet.getValue(1); 2592 2593 MachineFunction &F = DAG.getMachineFunction(); 2594 MachineFrameInfo *MFI = F.getFrameInfo(); 2595 MFI->setAdjustsStack(true); 2596 2597 // TLS calls preserve all registers except those that absolutely must be 2598 // trashed: R0 (it takes an argument), LR (it's a call) and CPSR (let's not be 2599 // silly). 2600 auto TRI = 2601 getTargetMachine().getSubtargetImpl(*F.getFunction())->getRegisterInfo(); 2602 auto ARI = static_cast<const ARMRegisterInfo *>(TRI); 2603 const uint32_t *Mask = ARI->getTLSCallPreservedMask(DAG.getMachineFunction()); 2604 2605 // Finally, we can make the call. This is just a degenerate version of a 2606 // normal AArch64 call node: r0 takes the address of the descriptor, and 2607 // returns the address of the variable in this thread. 2608 Chain = DAG.getCopyToReg(Chain, DL, ARM::R0, DescAddr, SDValue()); 2609 Chain = 2610 DAG.getNode(ARMISD::CALL, DL, DAG.getVTList(MVT::Other, MVT::Glue), 2611 Chain, FuncTLVGet, DAG.getRegister(ARM::R0, MVT::i32), 2612 DAG.getRegisterMask(Mask), Chain.getValue(1)); 2613 return DAG.getCopyFromReg(Chain, DL, ARM::R0, MVT::i32, Chain.getValue(1)); 2614 } 2615 2616 SDValue 2617 ARMTargetLowering::LowerGlobalTLSAddressWindows(SDValue Op, 2618 SelectionDAG &DAG) const { 2619 assert(Subtarget->isTargetWindows() && "Windows specific TLS lowering"); 2620 SDValue Chain = DAG.getEntryNode(); 2621 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 2622 SDLoc DL(Op); 2623 2624 // Load the current TEB (thread environment block) 2625 SDValue Ops[] = {Chain, 2626 DAG.getConstant(Intrinsic::arm_mrc, DL, MVT::i32), 2627 DAG.getConstant(15, DL, MVT::i32), 2628 DAG.getConstant(0, DL, MVT::i32), 2629 DAG.getConstant(13, DL, MVT::i32), 2630 DAG.getConstant(0, DL, MVT::i32), 2631 DAG.getConstant(2, DL, MVT::i32)}; 2632 SDValue CurrentTEB = DAG.getNode(ISD::INTRINSIC_W_CHAIN, DL, 2633 DAG.getVTList(MVT::i32, MVT::Other), Ops); 2634 2635 SDValue TEB = CurrentTEB.getValue(0); 2636 Chain = CurrentTEB.getValue(1); 2637 2638 // Load the ThreadLocalStoragePointer from the TEB 2639 // A pointer to the TLS array is located at offset 0x2c from the TEB. 2640 SDValue TLSArray = 2641 DAG.getNode(ISD::ADD, DL, PtrVT, TEB, DAG.getIntPtrConstant(0x2c, DL)); 2642 TLSArray = DAG.getLoad(PtrVT, DL, Chain, TLSArray, MachinePointerInfo(), 2643 false, false, false, 0); 2644 2645 // The pointer to the thread's TLS data area is at the TLS Index scaled by 4 2646 // offset into the TLSArray. 2647 2648 // Load the TLS index from the C runtime 2649 SDValue TLSIndex = 2650 DAG.getTargetExternalSymbol("_tls_index", PtrVT, ARMII::MO_NO_FLAG); 2651 TLSIndex = DAG.getNode(ARMISD::Wrapper, DL, PtrVT, TLSIndex); 2652 TLSIndex = DAG.getLoad(PtrVT, DL, Chain, TLSIndex, MachinePointerInfo(), 2653 false, false, false, 0); 2654 2655 SDValue Slot = DAG.getNode(ISD::SHL, DL, PtrVT, TLSIndex, 2656 DAG.getConstant(2, DL, MVT::i32)); 2657 SDValue TLS = DAG.getLoad(PtrVT, DL, Chain, 2658 DAG.getNode(ISD::ADD, DL, PtrVT, TLSArray, Slot), 2659 MachinePointerInfo(), false, false, false, 0); 2660 2661 return DAG.getNode(ISD::ADD, DL, PtrVT, TLS, 2662 LowerGlobalAddressWindows(Op, DAG)); 2663 } 2664 2665 // Lower ISD::GlobalTLSAddress using the "general dynamic" model 2666 SDValue 2667 ARMTargetLowering::LowerToTLSGeneralDynamicModel(GlobalAddressSDNode *GA, 2668 SelectionDAG &DAG) const { 2669 SDLoc dl(GA); 2670 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 2671 unsigned char PCAdj = Subtarget->isThumb() ? 4 : 8; 2672 MachineFunction &MF = DAG.getMachineFunction(); 2673 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>(); 2674 unsigned ARMPCLabelIndex = AFI->createPICLabelUId(); 2675 ARMConstantPoolValue *CPV = 2676 ARMConstantPoolConstant::Create(GA->getGlobal(), ARMPCLabelIndex, 2677 ARMCP::CPValue, PCAdj, ARMCP::TLSGD, true); 2678 SDValue Argument = DAG.getTargetConstantPool(CPV, PtrVT, 4); 2679 Argument = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Argument); 2680 Argument = 2681 DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Argument, 2682 MachinePointerInfo::getConstantPool(DAG.getMachineFunction()), 2683 false, false, false, 0); 2684 SDValue Chain = Argument.getValue(1); 2685 2686 SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, dl, MVT::i32); 2687 Argument = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Argument, PICLabel); 2688 2689 // call __tls_get_addr. 2690 ArgListTy Args; 2691 ArgListEntry Entry; 2692 Entry.Node = Argument; 2693 Entry.Ty = (Type *) Type::getInt32Ty(*DAG.getContext()); 2694 Args.push_back(Entry); 2695 2696 // FIXME: is there useful debug info available here? 2697 TargetLowering::CallLoweringInfo CLI(DAG); 2698 CLI.setDebugLoc(dl).setChain(Chain) 2699 .setCallee(CallingConv::C, Type::getInt32Ty(*DAG.getContext()), 2700 DAG.getExternalSymbol("__tls_get_addr", PtrVT), std::move(Args), 2701 0); 2702 2703 std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI); 2704 return CallResult.first; 2705 } 2706 2707 // Lower ISD::GlobalTLSAddress using the "initial exec" or 2708 // "local exec" model. 2709 SDValue 2710 ARMTargetLowering::LowerToTLSExecModels(GlobalAddressSDNode *GA, 2711 SelectionDAG &DAG, 2712 TLSModel::Model model) const { 2713 const GlobalValue *GV = GA->getGlobal(); 2714 SDLoc dl(GA); 2715 SDValue Offset; 2716 SDValue Chain = DAG.getEntryNode(); 2717 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 2718 // Get the Thread Pointer 2719 SDValue ThreadPointer = DAG.getNode(ARMISD::THREAD_POINTER, dl, PtrVT); 2720 2721 if (model == TLSModel::InitialExec) { 2722 MachineFunction &MF = DAG.getMachineFunction(); 2723 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>(); 2724 unsigned ARMPCLabelIndex = AFI->createPICLabelUId(); 2725 // Initial exec model. 2726 unsigned char PCAdj = Subtarget->isThumb() ? 4 : 8; 2727 ARMConstantPoolValue *CPV = 2728 ARMConstantPoolConstant::Create(GA->getGlobal(), ARMPCLabelIndex, 2729 ARMCP::CPValue, PCAdj, ARMCP::GOTTPOFF, 2730 true); 2731 Offset = DAG.getTargetConstantPool(CPV, PtrVT, 4); 2732 Offset = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Offset); 2733 Offset = DAG.getLoad( 2734 PtrVT, dl, Chain, Offset, 2735 MachinePointerInfo::getConstantPool(DAG.getMachineFunction()), false, 2736 false, false, 0); 2737 Chain = Offset.getValue(1); 2738 2739 SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, dl, MVT::i32); 2740 Offset = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Offset, PICLabel); 2741 2742 Offset = DAG.getLoad( 2743 PtrVT, dl, Chain, Offset, 2744 MachinePointerInfo::getConstantPool(DAG.getMachineFunction()), false, 2745 false, false, 0); 2746 } else { 2747 // local exec model 2748 assert(model == TLSModel::LocalExec); 2749 ARMConstantPoolValue *CPV = 2750 ARMConstantPoolConstant::Create(GV, ARMCP::TPOFF); 2751 Offset = DAG.getTargetConstantPool(CPV, PtrVT, 4); 2752 Offset = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Offset); 2753 Offset = DAG.getLoad( 2754 PtrVT, dl, Chain, Offset, 2755 MachinePointerInfo::getConstantPool(DAG.getMachineFunction()), false, 2756 false, false, 0); 2757 } 2758 2759 // The address of the thread local variable is the add of the thread 2760 // pointer with the offset of the variable. 2761 return DAG.getNode(ISD::ADD, dl, PtrVT, ThreadPointer, Offset); 2762 } 2763 2764 SDValue 2765 ARMTargetLowering::LowerGlobalTLSAddress(SDValue Op, SelectionDAG &DAG) const { 2766 if (Subtarget->isTargetDarwin()) 2767 return LowerGlobalTLSAddressDarwin(Op, DAG); 2768 2769 if (Subtarget->isTargetWindows()) 2770 return LowerGlobalTLSAddressWindows(Op, DAG); 2771 2772 // TODO: implement the "local dynamic" model 2773 assert(Subtarget->isTargetELF() && "Only ELF implemented here"); 2774 GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op); 2775 if (DAG.getTarget().Options.EmulatedTLS) 2776 return LowerToTLSEmulatedModel(GA, DAG); 2777 2778 TLSModel::Model model = getTargetMachine().getTLSModel(GA->getGlobal()); 2779 2780 switch (model) { 2781 case TLSModel::GeneralDynamic: 2782 case TLSModel::LocalDynamic: 2783 return LowerToTLSGeneralDynamicModel(GA, DAG); 2784 case TLSModel::InitialExec: 2785 case TLSModel::LocalExec: 2786 return LowerToTLSExecModels(GA, DAG, model); 2787 } 2788 llvm_unreachable("bogus TLS model"); 2789 } 2790 2791 SDValue ARMTargetLowering::LowerGlobalAddressELF(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 if (getTargetMachine().getRelocationModel() == Reloc::PIC_) { 2797 bool UseGOT_PREL = 2798 !(GV->hasHiddenVisibility() || GV->hasLocalLinkage()); 2799 2800 MachineFunction &MF = DAG.getMachineFunction(); 2801 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>(); 2802 unsigned ARMPCLabelIndex = AFI->createPICLabelUId(); 2803 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 2804 SDLoc dl(Op); 2805 unsigned PCAdj = Subtarget->isThumb() ? 4 : 8; 2806 ARMConstantPoolValue *CPV = ARMConstantPoolConstant::Create( 2807 GV, ARMPCLabelIndex, ARMCP::CPValue, PCAdj, 2808 UseGOT_PREL ? ARMCP::GOT_PREL : ARMCP::no_modifier, 2809 /*AddCurrentAddress=*/UseGOT_PREL); 2810 SDValue CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4); 2811 CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr); 2812 SDValue Result = DAG.getLoad( 2813 PtrVT, dl, DAG.getEntryNode(), CPAddr, 2814 MachinePointerInfo::getConstantPool(DAG.getMachineFunction()), false, 2815 false, false, 0); 2816 SDValue Chain = Result.getValue(1); 2817 SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, dl, MVT::i32); 2818 Result = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Result, PICLabel); 2819 if (UseGOT_PREL) 2820 Result = DAG.getLoad(PtrVT, dl, Chain, Result, 2821 MachinePointerInfo::getGOT(DAG.getMachineFunction()), 2822 false, false, false, 0); 2823 return Result; 2824 } 2825 2826 // If we have T2 ops, we can materialize the address directly via movt/movw 2827 // pair. This is always cheaper. 2828 if (Subtarget->useMovt(DAG.getMachineFunction())) { 2829 ++NumMovwMovt; 2830 // FIXME: Once remat is capable of dealing with instructions with register 2831 // operands, expand this into two nodes. 2832 return DAG.getNode(ARMISD::Wrapper, dl, PtrVT, 2833 DAG.getTargetGlobalAddress(GV, dl, PtrVT)); 2834 } else { 2835 SDValue CPAddr = DAG.getTargetConstantPool(GV, PtrVT, 4); 2836 CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr); 2837 return DAG.getLoad( 2838 PtrVT, dl, DAG.getEntryNode(), CPAddr, 2839 MachinePointerInfo::getConstantPool(DAG.getMachineFunction()), false, 2840 false, false, 0); 2841 } 2842 } 2843 2844 SDValue ARMTargetLowering::LowerGlobalAddressDarwin(SDValue Op, 2845 SelectionDAG &DAG) const { 2846 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 2847 SDLoc dl(Op); 2848 const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal(); 2849 Reloc::Model RelocM = getTargetMachine().getRelocationModel(); 2850 2851 if (Subtarget->useMovt(DAG.getMachineFunction())) 2852 ++NumMovwMovt; 2853 2854 // FIXME: Once remat is capable of dealing with instructions with register 2855 // operands, expand this into multiple nodes 2856 unsigned Wrapper = 2857 RelocM == Reloc::PIC_ ? ARMISD::WrapperPIC : ARMISD::Wrapper; 2858 2859 SDValue G = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, ARMII::MO_NONLAZY); 2860 SDValue Result = DAG.getNode(Wrapper, dl, PtrVT, G); 2861 2862 if (Subtarget->GVIsIndirectSymbol(GV, RelocM)) 2863 Result = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Result, 2864 MachinePointerInfo::getGOT(DAG.getMachineFunction()), 2865 false, false, false, 0); 2866 return Result; 2867 } 2868 2869 SDValue ARMTargetLowering::LowerGlobalAddressWindows(SDValue Op, 2870 SelectionDAG &DAG) const { 2871 assert(Subtarget->isTargetWindows() && "non-Windows COFF is not supported"); 2872 assert(Subtarget->useMovt(DAG.getMachineFunction()) && 2873 "Windows on ARM expects to use movw/movt"); 2874 2875 const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal(); 2876 const ARMII::TOF TargetFlags = 2877 (GV->hasDLLImportStorageClass() ? ARMII::MO_DLLIMPORT : ARMII::MO_NO_FLAG); 2878 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 2879 SDValue Result; 2880 SDLoc DL(Op); 2881 2882 ++NumMovwMovt; 2883 2884 // FIXME: Once remat is capable of dealing with instructions with register 2885 // operands, expand this into two nodes. 2886 Result = DAG.getNode(ARMISD::Wrapper, DL, PtrVT, 2887 DAG.getTargetGlobalAddress(GV, DL, PtrVT, /*Offset=*/0, 2888 TargetFlags)); 2889 if (GV->hasDLLImportStorageClass()) 2890 Result = DAG.getLoad(PtrVT, DL, DAG.getEntryNode(), Result, 2891 MachinePointerInfo::getGOT(DAG.getMachineFunction()), 2892 false, false, false, 0); 2893 return Result; 2894 } 2895 2896 SDValue 2897 ARMTargetLowering::LowerEH_SJLJ_SETJMP(SDValue Op, SelectionDAG &DAG) const { 2898 SDLoc dl(Op); 2899 SDValue Val = DAG.getConstant(0, dl, MVT::i32); 2900 return DAG.getNode(ARMISD::EH_SJLJ_SETJMP, dl, 2901 DAG.getVTList(MVT::i32, MVT::Other), Op.getOperand(0), 2902 Op.getOperand(1), Val); 2903 } 2904 2905 SDValue 2906 ARMTargetLowering::LowerEH_SJLJ_LONGJMP(SDValue Op, SelectionDAG &DAG) const { 2907 SDLoc dl(Op); 2908 return DAG.getNode(ARMISD::EH_SJLJ_LONGJMP, dl, MVT::Other, Op.getOperand(0), 2909 Op.getOperand(1), DAG.getConstant(0, dl, MVT::i32)); 2910 } 2911 2912 SDValue ARMTargetLowering::LowerEH_SJLJ_SETUP_DISPATCH(SDValue Op, 2913 SelectionDAG &DAG) const { 2914 SDLoc dl(Op); 2915 return DAG.getNode(ARMISD::EH_SJLJ_SETUP_DISPATCH, dl, MVT::Other, 2916 Op.getOperand(0)); 2917 } 2918 2919 SDValue 2920 ARMTargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op, SelectionDAG &DAG, 2921 const ARMSubtarget *Subtarget) const { 2922 unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue(); 2923 SDLoc dl(Op); 2924 switch (IntNo) { 2925 default: return SDValue(); // Don't custom lower most intrinsics. 2926 case Intrinsic::arm_rbit: { 2927 assert(Op.getOperand(1).getValueType() == MVT::i32 && 2928 "RBIT intrinsic must have i32 type!"); 2929 return DAG.getNode(ISD::BITREVERSE, dl, MVT::i32, Op.getOperand(1)); 2930 } 2931 case Intrinsic::thread_pointer: { 2932 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 2933 return DAG.getNode(ARMISD::THREAD_POINTER, dl, PtrVT); 2934 } 2935 case Intrinsic::eh_sjlj_lsda: { 2936 MachineFunction &MF = DAG.getMachineFunction(); 2937 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>(); 2938 unsigned ARMPCLabelIndex = AFI->createPICLabelUId(); 2939 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 2940 Reloc::Model RelocM = getTargetMachine().getRelocationModel(); 2941 SDValue CPAddr; 2942 unsigned PCAdj = (RelocM != Reloc::PIC_) 2943 ? 0 : (Subtarget->isThumb() ? 4 : 8); 2944 ARMConstantPoolValue *CPV = 2945 ARMConstantPoolConstant::Create(MF.getFunction(), ARMPCLabelIndex, 2946 ARMCP::CPLSDA, PCAdj); 2947 CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4); 2948 CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr); 2949 SDValue Result = DAG.getLoad( 2950 PtrVT, dl, DAG.getEntryNode(), CPAddr, 2951 MachinePointerInfo::getConstantPool(DAG.getMachineFunction()), false, 2952 false, false, 0); 2953 2954 if (RelocM == Reloc::PIC_) { 2955 SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, dl, MVT::i32); 2956 Result = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Result, PICLabel); 2957 } 2958 return Result; 2959 } 2960 case Intrinsic::arm_neon_vmulls: 2961 case Intrinsic::arm_neon_vmullu: { 2962 unsigned NewOpc = (IntNo == Intrinsic::arm_neon_vmulls) 2963 ? ARMISD::VMULLs : ARMISD::VMULLu; 2964 return DAG.getNode(NewOpc, SDLoc(Op), Op.getValueType(), 2965 Op.getOperand(1), Op.getOperand(2)); 2966 } 2967 case Intrinsic::arm_neon_vminnm: 2968 case Intrinsic::arm_neon_vmaxnm: { 2969 unsigned NewOpc = (IntNo == Intrinsic::arm_neon_vminnm) 2970 ? ISD::FMINNUM : ISD::FMAXNUM; 2971 return DAG.getNode(NewOpc, SDLoc(Op), Op.getValueType(), 2972 Op.getOperand(1), Op.getOperand(2)); 2973 } 2974 case Intrinsic::arm_neon_vminu: 2975 case Intrinsic::arm_neon_vmaxu: { 2976 if (Op.getValueType().isFloatingPoint()) 2977 return SDValue(); 2978 unsigned NewOpc = (IntNo == Intrinsic::arm_neon_vminu) 2979 ? ISD::UMIN : ISD::UMAX; 2980 return DAG.getNode(NewOpc, SDLoc(Op), Op.getValueType(), 2981 Op.getOperand(1), Op.getOperand(2)); 2982 } 2983 case Intrinsic::arm_neon_vmins: 2984 case Intrinsic::arm_neon_vmaxs: { 2985 // v{min,max}s is overloaded between signed integers and floats. 2986 if (!Op.getValueType().isFloatingPoint()) { 2987 unsigned NewOpc = (IntNo == Intrinsic::arm_neon_vmins) 2988 ? ISD::SMIN : ISD::SMAX; 2989 return DAG.getNode(NewOpc, SDLoc(Op), Op.getValueType(), 2990 Op.getOperand(1), Op.getOperand(2)); 2991 } 2992 unsigned NewOpc = (IntNo == Intrinsic::arm_neon_vmins) 2993 ? ISD::FMINNAN : ISD::FMAXNAN; 2994 return DAG.getNode(NewOpc, SDLoc(Op), Op.getValueType(), 2995 Op.getOperand(1), Op.getOperand(2)); 2996 } 2997 } 2998 } 2999 3000 static SDValue LowerATOMIC_FENCE(SDValue Op, SelectionDAG &DAG, 3001 const ARMSubtarget *Subtarget) { 3002 // FIXME: handle "fence singlethread" more efficiently. 3003 SDLoc dl(Op); 3004 if (!Subtarget->hasDataBarrier()) { 3005 // Some ARMv6 cpus can support data barriers with an mcr instruction. 3006 // Thumb1 and pre-v6 ARM mode use a libcall instead and should never get 3007 // here. 3008 assert(Subtarget->hasV6Ops() && !Subtarget->isThumb() && 3009 "Unexpected ISD::ATOMIC_FENCE encountered. Should be libcall!"); 3010 return DAG.getNode(ARMISD::MEMBARRIER_MCR, dl, MVT::Other, Op.getOperand(0), 3011 DAG.getConstant(0, dl, MVT::i32)); 3012 } 3013 3014 ConstantSDNode *OrdN = cast<ConstantSDNode>(Op.getOperand(1)); 3015 AtomicOrdering Ord = static_cast<AtomicOrdering>(OrdN->getZExtValue()); 3016 ARM_MB::MemBOpt Domain = ARM_MB::ISH; 3017 if (Subtarget->isMClass()) { 3018 // Only a full system barrier exists in the M-class architectures. 3019 Domain = ARM_MB::SY; 3020 } else if (Subtarget->isSwift() && Ord == AtomicOrdering::Release) { 3021 // Swift happens to implement ISHST barriers in a way that's compatible with 3022 // Release semantics but weaker than ISH so we'd be fools not to use 3023 // it. Beware: other processors probably don't! 3024 Domain = ARM_MB::ISHST; 3025 } 3026 3027 return DAG.getNode(ISD::INTRINSIC_VOID, dl, MVT::Other, Op.getOperand(0), 3028 DAG.getConstant(Intrinsic::arm_dmb, dl, MVT::i32), 3029 DAG.getConstant(Domain, dl, MVT::i32)); 3030 } 3031 3032 static SDValue LowerPREFETCH(SDValue Op, SelectionDAG &DAG, 3033 const ARMSubtarget *Subtarget) { 3034 // ARM pre v5TE and Thumb1 does not have preload instructions. 3035 if (!(Subtarget->isThumb2() || 3036 (!Subtarget->isThumb1Only() && Subtarget->hasV5TEOps()))) 3037 // Just preserve the chain. 3038 return Op.getOperand(0); 3039 3040 SDLoc dl(Op); 3041 unsigned isRead = ~cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue() & 1; 3042 if (!isRead && 3043 (!Subtarget->hasV7Ops() || !Subtarget->hasMPExtension())) 3044 // ARMv7 with MP extension has PLDW. 3045 return Op.getOperand(0); 3046 3047 unsigned isData = cast<ConstantSDNode>(Op.getOperand(4))->getZExtValue(); 3048 if (Subtarget->isThumb()) { 3049 // Invert the bits. 3050 isRead = ~isRead & 1; 3051 isData = ~isData & 1; 3052 } 3053 3054 return DAG.getNode(ARMISD::PRELOAD, dl, MVT::Other, Op.getOperand(0), 3055 Op.getOperand(1), DAG.getConstant(isRead, dl, MVT::i32), 3056 DAG.getConstant(isData, dl, MVT::i32)); 3057 } 3058 3059 static SDValue LowerVASTART(SDValue Op, SelectionDAG &DAG) { 3060 MachineFunction &MF = DAG.getMachineFunction(); 3061 ARMFunctionInfo *FuncInfo = MF.getInfo<ARMFunctionInfo>(); 3062 3063 // vastart just stores the address of the VarArgsFrameIndex slot into the 3064 // memory location argument. 3065 SDLoc dl(Op); 3066 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout()); 3067 SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT); 3068 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue(); 3069 return DAG.getStore(Op.getOperand(0), dl, FR, Op.getOperand(1), 3070 MachinePointerInfo(SV), false, false, 0); 3071 } 3072 3073 SDValue 3074 ARMTargetLowering::GetF64FormalArgument(CCValAssign &VA, CCValAssign &NextVA, 3075 SDValue &Root, SelectionDAG &DAG, 3076 SDLoc dl) const { 3077 MachineFunction &MF = DAG.getMachineFunction(); 3078 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>(); 3079 3080 const TargetRegisterClass *RC; 3081 if (AFI->isThumb1OnlyFunction()) 3082 RC = &ARM::tGPRRegClass; 3083 else 3084 RC = &ARM::GPRRegClass; 3085 3086 // Transform the arguments stored in physical registers into virtual ones. 3087 unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC); 3088 SDValue ArgValue = DAG.getCopyFromReg(Root, dl, Reg, MVT::i32); 3089 3090 SDValue ArgValue2; 3091 if (NextVA.isMemLoc()) { 3092 MachineFrameInfo *MFI = MF.getFrameInfo(); 3093 int FI = MFI->CreateFixedObject(4, NextVA.getLocMemOffset(), true); 3094 3095 // Create load node to retrieve arguments from the stack. 3096 SDValue FIN = DAG.getFrameIndex(FI, getPointerTy(DAG.getDataLayout())); 3097 ArgValue2 = DAG.getLoad( 3098 MVT::i32, dl, Root, FIN, 3099 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI), false, 3100 false, false, 0); 3101 } else { 3102 Reg = MF.addLiveIn(NextVA.getLocReg(), RC); 3103 ArgValue2 = DAG.getCopyFromReg(Root, dl, Reg, MVT::i32); 3104 } 3105 if (!Subtarget->isLittle()) 3106 std::swap (ArgValue, ArgValue2); 3107 return DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, ArgValue, ArgValue2); 3108 } 3109 3110 // The remaining GPRs hold either the beginning of variable-argument 3111 // data, or the beginning of an aggregate passed by value (usually 3112 // byval). Either way, we allocate stack slots adjacent to the data 3113 // provided by our caller, and store the unallocated registers there. 3114 // If this is a variadic function, the va_list pointer will begin with 3115 // these values; otherwise, this reassembles a (byval) structure that 3116 // was split between registers and memory. 3117 // Return: The frame index registers were stored into. 3118 int 3119 ARMTargetLowering::StoreByValRegs(CCState &CCInfo, SelectionDAG &DAG, 3120 SDLoc dl, SDValue &Chain, 3121 const Value *OrigArg, 3122 unsigned InRegsParamRecordIdx, 3123 int ArgOffset, 3124 unsigned ArgSize) const { 3125 // Currently, two use-cases possible: 3126 // Case #1. Non-var-args function, and we meet first byval parameter. 3127 // Setup first unallocated register as first byval register; 3128 // eat all remained registers 3129 // (these two actions are performed by HandleByVal method). 3130 // Then, here, we initialize stack frame with 3131 // "store-reg" instructions. 3132 // Case #2. Var-args function, that doesn't contain byval parameters. 3133 // The same: eat all remained unallocated registers, 3134 // initialize stack frame. 3135 3136 MachineFunction &MF = DAG.getMachineFunction(); 3137 MachineFrameInfo *MFI = MF.getFrameInfo(); 3138 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>(); 3139 unsigned RBegin, REnd; 3140 if (InRegsParamRecordIdx < CCInfo.getInRegsParamsCount()) { 3141 CCInfo.getInRegsParamInfo(InRegsParamRecordIdx, RBegin, REnd); 3142 } else { 3143 unsigned RBeginIdx = CCInfo.getFirstUnallocated(GPRArgRegs); 3144 RBegin = RBeginIdx == 4 ? (unsigned)ARM::R4 : GPRArgRegs[RBeginIdx]; 3145 REnd = ARM::R4; 3146 } 3147 3148 if (REnd != RBegin) 3149 ArgOffset = -4 * (ARM::R4 - RBegin); 3150 3151 auto PtrVT = getPointerTy(DAG.getDataLayout()); 3152 int FrameIndex = MFI->CreateFixedObject(ArgSize, ArgOffset, false); 3153 SDValue FIN = DAG.getFrameIndex(FrameIndex, PtrVT); 3154 3155 SmallVector<SDValue, 4> MemOps; 3156 const TargetRegisterClass *RC = 3157 AFI->isThumb1OnlyFunction() ? &ARM::tGPRRegClass : &ARM::GPRRegClass; 3158 3159 for (unsigned Reg = RBegin, i = 0; Reg < REnd; ++Reg, ++i) { 3160 unsigned VReg = MF.addLiveIn(Reg, RC); 3161 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i32); 3162 SDValue Store = 3163 DAG.getStore(Val.getValue(1), dl, Val, FIN, 3164 MachinePointerInfo(OrigArg, 4 * i), false, false, 0); 3165 MemOps.push_back(Store); 3166 FIN = DAG.getNode(ISD::ADD, dl, PtrVT, FIN, DAG.getConstant(4, dl, PtrVT)); 3167 } 3168 3169 if (!MemOps.empty()) 3170 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOps); 3171 return FrameIndex; 3172 } 3173 3174 // Setup stack frame, the va_list pointer will start from. 3175 void 3176 ARMTargetLowering::VarArgStyleRegisters(CCState &CCInfo, SelectionDAG &DAG, 3177 SDLoc dl, SDValue &Chain, 3178 unsigned ArgOffset, 3179 unsigned TotalArgRegsSaveSize, 3180 bool ForceMutable) const { 3181 MachineFunction &MF = DAG.getMachineFunction(); 3182 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>(); 3183 3184 // Try to store any remaining integer argument regs 3185 // to their spots on the stack so that they may be loaded by deferencing 3186 // the result of va_next. 3187 // If there is no regs to be stored, just point address after last 3188 // argument passed via stack. 3189 int FrameIndex = StoreByValRegs(CCInfo, DAG, dl, Chain, nullptr, 3190 CCInfo.getInRegsParamsCount(), 3191 CCInfo.getNextStackOffset(), 4); 3192 AFI->setVarArgsFrameIndex(FrameIndex); 3193 } 3194 3195 SDValue 3196 ARMTargetLowering::LowerFormalArguments(SDValue Chain, 3197 CallingConv::ID CallConv, bool isVarArg, 3198 const SmallVectorImpl<ISD::InputArg> 3199 &Ins, 3200 SDLoc dl, SelectionDAG &DAG, 3201 SmallVectorImpl<SDValue> &InVals) 3202 const { 3203 MachineFunction &MF = DAG.getMachineFunction(); 3204 MachineFrameInfo *MFI = MF.getFrameInfo(); 3205 3206 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>(); 3207 3208 // Assign locations to all of the incoming arguments. 3209 SmallVector<CCValAssign, 16> ArgLocs; 3210 ARMCCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), ArgLocs, 3211 *DAG.getContext(), Prologue); 3212 CCInfo.AnalyzeFormalArguments(Ins, 3213 CCAssignFnForNode(CallConv, /* Return*/ false, 3214 isVarArg)); 3215 3216 SmallVector<SDValue, 16> ArgValues; 3217 SDValue ArgValue; 3218 Function::const_arg_iterator CurOrigArg = MF.getFunction()->arg_begin(); 3219 unsigned CurArgIdx = 0; 3220 3221 // Initially ArgRegsSaveSize is zero. 3222 // Then we increase this value each time we meet byval parameter. 3223 // We also increase this value in case of varargs function. 3224 AFI->setArgRegsSaveSize(0); 3225 3226 // Calculate the amount of stack space that we need to allocate to store 3227 // byval and variadic arguments that are passed in registers. 3228 // We need to know this before we allocate the first byval or variadic 3229 // argument, as they will be allocated a stack slot below the CFA (Canonical 3230 // Frame Address, the stack pointer at entry to the function). 3231 unsigned ArgRegBegin = ARM::R4; 3232 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) { 3233 if (CCInfo.getInRegsParamsProcessed() >= CCInfo.getInRegsParamsCount()) 3234 break; 3235 3236 CCValAssign &VA = ArgLocs[i]; 3237 unsigned Index = VA.getValNo(); 3238 ISD::ArgFlagsTy Flags = Ins[Index].Flags; 3239 if (!Flags.isByVal()) 3240 continue; 3241 3242 assert(VA.isMemLoc() && "unexpected byval pointer in reg"); 3243 unsigned RBegin, REnd; 3244 CCInfo.getInRegsParamInfo(CCInfo.getInRegsParamsProcessed(), RBegin, REnd); 3245 ArgRegBegin = std::min(ArgRegBegin, RBegin); 3246 3247 CCInfo.nextInRegsParam(); 3248 } 3249 CCInfo.rewindByValRegsInfo(); 3250 3251 int lastInsIndex = -1; 3252 if (isVarArg && MFI->hasVAStart()) { 3253 unsigned RegIdx = CCInfo.getFirstUnallocated(GPRArgRegs); 3254 if (RegIdx != array_lengthof(GPRArgRegs)) 3255 ArgRegBegin = std::min(ArgRegBegin, (unsigned)GPRArgRegs[RegIdx]); 3256 } 3257 3258 unsigned TotalArgRegsSaveSize = 4 * (ARM::R4 - ArgRegBegin); 3259 AFI->setArgRegsSaveSize(TotalArgRegsSaveSize); 3260 auto PtrVT = getPointerTy(DAG.getDataLayout()); 3261 3262 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) { 3263 CCValAssign &VA = ArgLocs[i]; 3264 if (Ins[VA.getValNo()].isOrigArg()) { 3265 std::advance(CurOrigArg, 3266 Ins[VA.getValNo()].getOrigArgIndex() - CurArgIdx); 3267 CurArgIdx = Ins[VA.getValNo()].getOrigArgIndex(); 3268 } 3269 // Arguments stored in registers. 3270 if (VA.isRegLoc()) { 3271 EVT RegVT = VA.getLocVT(); 3272 3273 if (VA.needsCustom()) { 3274 // f64 and vector types are split up into multiple registers or 3275 // combinations of registers and stack slots. 3276 if (VA.getLocVT() == MVT::v2f64) { 3277 SDValue ArgValue1 = GetF64FormalArgument(VA, ArgLocs[++i], 3278 Chain, DAG, dl); 3279 VA = ArgLocs[++i]; // skip ahead to next loc 3280 SDValue ArgValue2; 3281 if (VA.isMemLoc()) { 3282 int FI = MFI->CreateFixedObject(8, VA.getLocMemOffset(), true); 3283 SDValue FIN = DAG.getFrameIndex(FI, PtrVT); 3284 ArgValue2 = DAG.getLoad( 3285 MVT::f64, dl, Chain, FIN, 3286 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI), 3287 false, false, false, 0); 3288 } else { 3289 ArgValue2 = GetF64FormalArgument(VA, ArgLocs[++i], 3290 Chain, DAG, dl); 3291 } 3292 ArgValue = DAG.getNode(ISD::UNDEF, dl, MVT::v2f64); 3293 ArgValue = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, 3294 ArgValue, ArgValue1, 3295 DAG.getIntPtrConstant(0, dl)); 3296 ArgValue = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, 3297 ArgValue, ArgValue2, 3298 DAG.getIntPtrConstant(1, dl)); 3299 } else 3300 ArgValue = GetF64FormalArgument(VA, ArgLocs[++i], Chain, DAG, dl); 3301 3302 } else { 3303 const TargetRegisterClass *RC; 3304 3305 if (RegVT == MVT::f32) 3306 RC = &ARM::SPRRegClass; 3307 else if (RegVT == MVT::f64) 3308 RC = &ARM::DPRRegClass; 3309 else if (RegVT == MVT::v2f64) 3310 RC = &ARM::QPRRegClass; 3311 else if (RegVT == MVT::i32) 3312 RC = AFI->isThumb1OnlyFunction() ? &ARM::tGPRRegClass 3313 : &ARM::GPRRegClass; 3314 else 3315 llvm_unreachable("RegVT not supported by FORMAL_ARGUMENTS Lowering"); 3316 3317 // Transform the arguments in physical registers into virtual ones. 3318 unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC); 3319 ArgValue = DAG.getCopyFromReg(Chain, dl, Reg, RegVT); 3320 } 3321 3322 // If this is an 8 or 16-bit value, it is really passed promoted 3323 // to 32 bits. Insert an assert[sz]ext to capture this, then 3324 // truncate to the right size. 3325 switch (VA.getLocInfo()) { 3326 default: llvm_unreachable("Unknown loc info!"); 3327 case CCValAssign::Full: break; 3328 case CCValAssign::BCvt: 3329 ArgValue = DAG.getNode(ISD::BITCAST, dl, VA.getValVT(), ArgValue); 3330 break; 3331 case CCValAssign::SExt: 3332 ArgValue = DAG.getNode(ISD::AssertSext, dl, RegVT, ArgValue, 3333 DAG.getValueType(VA.getValVT())); 3334 ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue); 3335 break; 3336 case CCValAssign::ZExt: 3337 ArgValue = DAG.getNode(ISD::AssertZext, dl, RegVT, ArgValue, 3338 DAG.getValueType(VA.getValVT())); 3339 ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue); 3340 break; 3341 } 3342 3343 InVals.push_back(ArgValue); 3344 3345 } else { // VA.isRegLoc() 3346 3347 // sanity check 3348 assert(VA.isMemLoc()); 3349 assert(VA.getValVT() != MVT::i64 && "i64 should already be lowered"); 3350 3351 int index = VA.getValNo(); 3352 3353 // Some Ins[] entries become multiple ArgLoc[] entries. 3354 // Process them only once. 3355 if (index != lastInsIndex) 3356 { 3357 ISD::ArgFlagsTy Flags = Ins[index].Flags; 3358 // FIXME: For now, all byval parameter objects are marked mutable. 3359 // This can be changed with more analysis. 3360 // In case of tail call optimization mark all arguments mutable. 3361 // Since they could be overwritten by lowering of arguments in case of 3362 // a tail call. 3363 if (Flags.isByVal()) { 3364 assert(Ins[index].isOrigArg() && 3365 "Byval arguments cannot be implicit"); 3366 unsigned CurByValIndex = CCInfo.getInRegsParamsProcessed(); 3367 3368 int FrameIndex = StoreByValRegs( 3369 CCInfo, DAG, dl, Chain, &*CurOrigArg, CurByValIndex, 3370 VA.getLocMemOffset(), Flags.getByValSize()); 3371 InVals.push_back(DAG.getFrameIndex(FrameIndex, PtrVT)); 3372 CCInfo.nextInRegsParam(); 3373 } else { 3374 unsigned FIOffset = VA.getLocMemOffset(); 3375 int FI = MFI->CreateFixedObject(VA.getLocVT().getSizeInBits()/8, 3376 FIOffset, true); 3377 3378 // Create load nodes to retrieve arguments from the stack. 3379 SDValue FIN = DAG.getFrameIndex(FI, PtrVT); 3380 InVals.push_back(DAG.getLoad( 3381 VA.getValVT(), dl, Chain, FIN, 3382 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI), 3383 false, false, false, 0)); 3384 } 3385 lastInsIndex = index; 3386 } 3387 } 3388 } 3389 3390 // varargs 3391 if (isVarArg && MFI->hasVAStart()) 3392 VarArgStyleRegisters(CCInfo, DAG, dl, Chain, 3393 CCInfo.getNextStackOffset(), 3394 TotalArgRegsSaveSize); 3395 3396 AFI->setArgumentStackSize(CCInfo.getNextStackOffset()); 3397 3398 return Chain; 3399 } 3400 3401 /// isFloatingPointZero - Return true if this is +0.0. 3402 static bool isFloatingPointZero(SDValue Op) { 3403 if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Op)) 3404 return CFP->getValueAPF().isPosZero(); 3405 else if (ISD::isEXTLoad(Op.getNode()) || ISD::isNON_EXTLoad(Op.getNode())) { 3406 // Maybe this has already been legalized into the constant pool? 3407 if (Op.getOperand(1).getOpcode() == ARMISD::Wrapper) { 3408 SDValue WrapperOp = Op.getOperand(1).getOperand(0); 3409 if (ConstantPoolSDNode *CP = dyn_cast<ConstantPoolSDNode>(WrapperOp)) 3410 if (const ConstantFP *CFP = dyn_cast<ConstantFP>(CP->getConstVal())) 3411 return CFP->getValueAPF().isPosZero(); 3412 } 3413 } else if (Op->getOpcode() == ISD::BITCAST && 3414 Op->getValueType(0) == MVT::f64) { 3415 // Handle (ISD::BITCAST (ARMISD::VMOVIMM (ISD::TargetConstant 0)) MVT::f64) 3416 // created by LowerConstantFP(). 3417 SDValue BitcastOp = Op->getOperand(0); 3418 if (BitcastOp->getOpcode() == ARMISD::VMOVIMM && 3419 isNullConstant(BitcastOp->getOperand(0))) 3420 return true; 3421 } 3422 return false; 3423 } 3424 3425 /// Returns appropriate ARM CMP (cmp) and corresponding condition code for 3426 /// the given operands. 3427 SDValue 3428 ARMTargetLowering::getARMCmp(SDValue LHS, SDValue RHS, ISD::CondCode CC, 3429 SDValue &ARMcc, SelectionDAG &DAG, 3430 SDLoc dl) const { 3431 if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS.getNode())) { 3432 unsigned C = RHSC->getZExtValue(); 3433 if (!isLegalICmpImmediate(C)) { 3434 // Constant does not fit, try adjusting it by one? 3435 switch (CC) { 3436 default: break; 3437 case ISD::SETLT: 3438 case ISD::SETGE: 3439 if (C != 0x80000000 && isLegalICmpImmediate(C-1)) { 3440 CC = (CC == ISD::SETLT) ? ISD::SETLE : ISD::SETGT; 3441 RHS = DAG.getConstant(C - 1, dl, MVT::i32); 3442 } 3443 break; 3444 case ISD::SETULT: 3445 case ISD::SETUGE: 3446 if (C != 0 && isLegalICmpImmediate(C-1)) { 3447 CC = (CC == ISD::SETULT) ? ISD::SETULE : ISD::SETUGT; 3448 RHS = DAG.getConstant(C - 1, dl, MVT::i32); 3449 } 3450 break; 3451 case ISD::SETLE: 3452 case ISD::SETGT: 3453 if (C != 0x7fffffff && isLegalICmpImmediate(C+1)) { 3454 CC = (CC == ISD::SETLE) ? ISD::SETLT : ISD::SETGE; 3455 RHS = DAG.getConstant(C + 1, dl, MVT::i32); 3456 } 3457 break; 3458 case ISD::SETULE: 3459 case ISD::SETUGT: 3460 if (C != 0xffffffff && isLegalICmpImmediate(C+1)) { 3461 CC = (CC == ISD::SETULE) ? ISD::SETULT : ISD::SETUGE; 3462 RHS = DAG.getConstant(C + 1, dl, MVT::i32); 3463 } 3464 break; 3465 } 3466 } 3467 } 3468 3469 ARMCC::CondCodes CondCode = IntCCToARMCC(CC); 3470 ARMISD::NodeType CompareType; 3471 switch (CondCode) { 3472 default: 3473 CompareType = ARMISD::CMP; 3474 break; 3475 case ARMCC::EQ: 3476 case ARMCC::NE: 3477 // Uses only Z Flag 3478 CompareType = ARMISD::CMPZ; 3479 break; 3480 } 3481 ARMcc = DAG.getConstant(CondCode, dl, MVT::i32); 3482 return DAG.getNode(CompareType, dl, MVT::Glue, LHS, RHS); 3483 } 3484 3485 /// Returns a appropriate VFP CMP (fcmp{s|d}+fmstat) for the given operands. 3486 SDValue 3487 ARMTargetLowering::getVFPCmp(SDValue LHS, SDValue RHS, SelectionDAG &DAG, 3488 SDLoc dl) const { 3489 assert(!Subtarget->isFPOnlySP() || RHS.getValueType() != MVT::f64); 3490 SDValue Cmp; 3491 if (!isFloatingPointZero(RHS)) 3492 Cmp = DAG.getNode(ARMISD::CMPFP, dl, MVT::Glue, LHS, RHS); 3493 else 3494 Cmp = DAG.getNode(ARMISD::CMPFPw0, dl, MVT::Glue, LHS); 3495 return DAG.getNode(ARMISD::FMSTAT, dl, MVT::Glue, Cmp); 3496 } 3497 3498 /// duplicateCmp - Glue values can have only one use, so this function 3499 /// duplicates a comparison node. 3500 SDValue 3501 ARMTargetLowering::duplicateCmp(SDValue Cmp, SelectionDAG &DAG) const { 3502 unsigned Opc = Cmp.getOpcode(); 3503 SDLoc DL(Cmp); 3504 if (Opc == ARMISD::CMP || Opc == ARMISD::CMPZ) 3505 return DAG.getNode(Opc, DL, MVT::Glue, Cmp.getOperand(0),Cmp.getOperand(1)); 3506 3507 assert(Opc == ARMISD::FMSTAT && "unexpected comparison operation"); 3508 Cmp = Cmp.getOperand(0); 3509 Opc = Cmp.getOpcode(); 3510 if (Opc == ARMISD::CMPFP) 3511 Cmp = DAG.getNode(Opc, DL, MVT::Glue, Cmp.getOperand(0),Cmp.getOperand(1)); 3512 else { 3513 assert(Opc == ARMISD::CMPFPw0 && "unexpected operand of FMSTAT"); 3514 Cmp = DAG.getNode(Opc, DL, MVT::Glue, Cmp.getOperand(0)); 3515 } 3516 return DAG.getNode(ARMISD::FMSTAT, DL, MVT::Glue, Cmp); 3517 } 3518 3519 std::pair<SDValue, SDValue> 3520 ARMTargetLowering::getARMXALUOOp(SDValue Op, SelectionDAG &DAG, 3521 SDValue &ARMcc) const { 3522 assert(Op.getValueType() == MVT::i32 && "Unsupported value type"); 3523 3524 SDValue Value, OverflowCmp; 3525 SDValue LHS = Op.getOperand(0); 3526 SDValue RHS = Op.getOperand(1); 3527 SDLoc dl(Op); 3528 3529 // FIXME: We are currently always generating CMPs because we don't support 3530 // generating CMN through the backend. This is not as good as the natural 3531 // CMP case because it causes a register dependency and cannot be folded 3532 // later. 3533 3534 switch (Op.getOpcode()) { 3535 default: 3536 llvm_unreachable("Unknown overflow instruction!"); 3537 case ISD::SADDO: 3538 ARMcc = DAG.getConstant(ARMCC::VC, dl, MVT::i32); 3539 Value = DAG.getNode(ISD::ADD, dl, Op.getValueType(), LHS, RHS); 3540 OverflowCmp = DAG.getNode(ARMISD::CMP, dl, MVT::Glue, Value, LHS); 3541 break; 3542 case ISD::UADDO: 3543 ARMcc = DAG.getConstant(ARMCC::HS, dl, MVT::i32); 3544 Value = DAG.getNode(ISD::ADD, dl, Op.getValueType(), LHS, RHS); 3545 OverflowCmp = DAG.getNode(ARMISD::CMP, dl, MVT::Glue, Value, LHS); 3546 break; 3547 case ISD::SSUBO: 3548 ARMcc = DAG.getConstant(ARMCC::VC, dl, MVT::i32); 3549 Value = DAG.getNode(ISD::SUB, dl, Op.getValueType(), LHS, RHS); 3550 OverflowCmp = DAG.getNode(ARMISD::CMP, dl, MVT::Glue, LHS, RHS); 3551 break; 3552 case ISD::USUBO: 3553 ARMcc = DAG.getConstant(ARMCC::HS, dl, MVT::i32); 3554 Value = DAG.getNode(ISD::SUB, dl, Op.getValueType(), LHS, RHS); 3555 OverflowCmp = DAG.getNode(ARMISD::CMP, dl, MVT::Glue, LHS, RHS); 3556 break; 3557 } // switch (...) 3558 3559 return std::make_pair(Value, OverflowCmp); 3560 } 3561 3562 3563 SDValue 3564 ARMTargetLowering::LowerXALUO(SDValue Op, SelectionDAG &DAG) const { 3565 // Let legalize expand this if it isn't a legal type yet. 3566 if (!DAG.getTargetLoweringInfo().isTypeLegal(Op.getValueType())) 3567 return SDValue(); 3568 3569 SDValue Value, OverflowCmp; 3570 SDValue ARMcc; 3571 std::tie(Value, OverflowCmp) = getARMXALUOOp(Op, DAG, ARMcc); 3572 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32); 3573 SDLoc dl(Op); 3574 // We use 0 and 1 as false and true values. 3575 SDValue TVal = DAG.getConstant(1, dl, MVT::i32); 3576 SDValue FVal = DAG.getConstant(0, dl, MVT::i32); 3577 EVT VT = Op.getValueType(); 3578 3579 SDValue Overflow = DAG.getNode(ARMISD::CMOV, dl, VT, TVal, FVal, 3580 ARMcc, CCR, OverflowCmp); 3581 3582 SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32); 3583 return DAG.getNode(ISD::MERGE_VALUES, dl, VTs, Value, Overflow); 3584 } 3585 3586 3587 SDValue ARMTargetLowering::LowerSELECT(SDValue Op, SelectionDAG &DAG) const { 3588 SDValue Cond = Op.getOperand(0); 3589 SDValue SelectTrue = Op.getOperand(1); 3590 SDValue SelectFalse = Op.getOperand(2); 3591 SDLoc dl(Op); 3592 unsigned Opc = Cond.getOpcode(); 3593 3594 if (Cond.getResNo() == 1 && 3595 (Opc == ISD::SADDO || Opc == ISD::UADDO || Opc == ISD::SSUBO || 3596 Opc == ISD::USUBO)) { 3597 if (!DAG.getTargetLoweringInfo().isTypeLegal(Cond->getValueType(0))) 3598 return SDValue(); 3599 3600 SDValue Value, OverflowCmp; 3601 SDValue ARMcc; 3602 std::tie(Value, OverflowCmp) = getARMXALUOOp(Cond, DAG, ARMcc); 3603 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32); 3604 EVT VT = Op.getValueType(); 3605 3606 return getCMOV(dl, VT, SelectTrue, SelectFalse, ARMcc, CCR, 3607 OverflowCmp, DAG); 3608 } 3609 3610 // Convert: 3611 // 3612 // (select (cmov 1, 0, cond), t, f) -> (cmov t, f, cond) 3613 // (select (cmov 0, 1, cond), t, f) -> (cmov f, t, cond) 3614 // 3615 if (Cond.getOpcode() == ARMISD::CMOV && Cond.hasOneUse()) { 3616 const ConstantSDNode *CMOVTrue = 3617 dyn_cast<ConstantSDNode>(Cond.getOperand(0)); 3618 const ConstantSDNode *CMOVFalse = 3619 dyn_cast<ConstantSDNode>(Cond.getOperand(1)); 3620 3621 if (CMOVTrue && CMOVFalse) { 3622 unsigned CMOVTrueVal = CMOVTrue->getZExtValue(); 3623 unsigned CMOVFalseVal = CMOVFalse->getZExtValue(); 3624 3625 SDValue True; 3626 SDValue False; 3627 if (CMOVTrueVal == 1 && CMOVFalseVal == 0) { 3628 True = SelectTrue; 3629 False = SelectFalse; 3630 } else if (CMOVTrueVal == 0 && CMOVFalseVal == 1) { 3631 True = SelectFalse; 3632 False = SelectTrue; 3633 } 3634 3635 if (True.getNode() && False.getNode()) { 3636 EVT VT = Op.getValueType(); 3637 SDValue ARMcc = Cond.getOperand(2); 3638 SDValue CCR = Cond.getOperand(3); 3639 SDValue Cmp = duplicateCmp(Cond.getOperand(4), DAG); 3640 assert(True.getValueType() == VT); 3641 return getCMOV(dl, VT, True, False, ARMcc, CCR, Cmp, DAG); 3642 } 3643 } 3644 } 3645 3646 // ARM's BooleanContents value is UndefinedBooleanContent. Mask out the 3647 // undefined bits before doing a full-word comparison with zero. 3648 Cond = DAG.getNode(ISD::AND, dl, Cond.getValueType(), Cond, 3649 DAG.getConstant(1, dl, Cond.getValueType())); 3650 3651 return DAG.getSelectCC(dl, Cond, 3652 DAG.getConstant(0, dl, Cond.getValueType()), 3653 SelectTrue, SelectFalse, ISD::SETNE); 3654 } 3655 3656 static void checkVSELConstraints(ISD::CondCode CC, ARMCC::CondCodes &CondCode, 3657 bool &swpCmpOps, bool &swpVselOps) { 3658 // Start by selecting the GE condition code for opcodes that return true for 3659 // 'equality' 3660 if (CC == ISD::SETUGE || CC == ISD::SETOGE || CC == ISD::SETOLE || 3661 CC == ISD::SETULE) 3662 CondCode = ARMCC::GE; 3663 3664 // and GT for opcodes that return false for 'equality'. 3665 else if (CC == ISD::SETUGT || CC == ISD::SETOGT || CC == ISD::SETOLT || 3666 CC == ISD::SETULT) 3667 CondCode = ARMCC::GT; 3668 3669 // Since we are constrained to GE/GT, if the opcode contains 'less', we need 3670 // to swap the compare operands. 3671 if (CC == ISD::SETOLE || CC == ISD::SETULE || CC == ISD::SETOLT || 3672 CC == ISD::SETULT) 3673 swpCmpOps = true; 3674 3675 // Both GT and GE are ordered comparisons, and return false for 'unordered'. 3676 // If we have an unordered opcode, we need to swap the operands to the VSEL 3677 // instruction (effectively negating the condition). 3678 // 3679 // This also has the effect of swapping which one of 'less' or 'greater' 3680 // returns true, so we also swap the compare operands. It also switches 3681 // whether we return true for 'equality', so we compensate by picking the 3682 // opposite condition code to our original choice. 3683 if (CC == ISD::SETULE || CC == ISD::SETULT || CC == ISD::SETUGE || 3684 CC == ISD::SETUGT) { 3685 swpCmpOps = !swpCmpOps; 3686 swpVselOps = !swpVselOps; 3687 CondCode = CondCode == ARMCC::GT ? ARMCC::GE : ARMCC::GT; 3688 } 3689 3690 // 'ordered' is 'anything but unordered', so use the VS condition code and 3691 // swap the VSEL operands. 3692 if (CC == ISD::SETO) { 3693 CondCode = ARMCC::VS; 3694 swpVselOps = true; 3695 } 3696 3697 // 'unordered or not equal' is 'anything but equal', so use the EQ condition 3698 // code and swap the VSEL operands. 3699 if (CC == ISD::SETUNE) { 3700 CondCode = ARMCC::EQ; 3701 swpVselOps = true; 3702 } 3703 } 3704 3705 SDValue ARMTargetLowering::getCMOV(SDLoc dl, EVT VT, SDValue FalseVal, 3706 SDValue TrueVal, SDValue ARMcc, SDValue CCR, 3707 SDValue Cmp, SelectionDAG &DAG) const { 3708 if (Subtarget->isFPOnlySP() && VT == MVT::f64) { 3709 FalseVal = DAG.getNode(ARMISD::VMOVRRD, dl, 3710 DAG.getVTList(MVT::i32, MVT::i32), FalseVal); 3711 TrueVal = DAG.getNode(ARMISD::VMOVRRD, dl, 3712 DAG.getVTList(MVT::i32, MVT::i32), TrueVal); 3713 3714 SDValue TrueLow = TrueVal.getValue(0); 3715 SDValue TrueHigh = TrueVal.getValue(1); 3716 SDValue FalseLow = FalseVal.getValue(0); 3717 SDValue FalseHigh = FalseVal.getValue(1); 3718 3719 SDValue Low = DAG.getNode(ARMISD::CMOV, dl, MVT::i32, FalseLow, TrueLow, 3720 ARMcc, CCR, Cmp); 3721 SDValue High = DAG.getNode(ARMISD::CMOV, dl, MVT::i32, FalseHigh, TrueHigh, 3722 ARMcc, CCR, duplicateCmp(Cmp, DAG)); 3723 3724 return DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Low, High); 3725 } else { 3726 return DAG.getNode(ARMISD::CMOV, dl, VT, FalseVal, TrueVal, ARMcc, CCR, 3727 Cmp); 3728 } 3729 } 3730 3731 SDValue ARMTargetLowering::LowerSELECT_CC(SDValue Op, SelectionDAG &DAG) const { 3732 EVT VT = Op.getValueType(); 3733 SDValue LHS = Op.getOperand(0); 3734 SDValue RHS = Op.getOperand(1); 3735 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(4))->get(); 3736 SDValue TrueVal = Op.getOperand(2); 3737 SDValue FalseVal = Op.getOperand(3); 3738 SDLoc dl(Op); 3739 3740 if (Subtarget->isFPOnlySP() && LHS.getValueType() == MVT::f64) { 3741 DAG.getTargetLoweringInfo().softenSetCCOperands(DAG, MVT::f64, LHS, RHS, CC, 3742 dl); 3743 3744 // If softenSetCCOperands only returned one value, we should compare it to 3745 // zero. 3746 if (!RHS.getNode()) { 3747 RHS = DAG.getConstant(0, dl, LHS.getValueType()); 3748 CC = ISD::SETNE; 3749 } 3750 } 3751 3752 if (LHS.getValueType() == MVT::i32) { 3753 // Try to generate VSEL on ARMv8. 3754 // The VSEL instruction can't use all the usual ARM condition 3755 // codes: it only has two bits to select the condition code, so it's 3756 // constrained to use only GE, GT, VS and EQ. 3757 // 3758 // To implement all the various ISD::SETXXX opcodes, we sometimes need to 3759 // swap the operands of the previous compare instruction (effectively 3760 // inverting the compare condition, swapping 'less' and 'greater') and 3761 // sometimes need to swap the operands to the VSEL (which inverts the 3762 // condition in the sense of firing whenever the previous condition didn't) 3763 if (Subtarget->hasFPARMv8() && (TrueVal.getValueType() == MVT::f32 || 3764 TrueVal.getValueType() == MVT::f64)) { 3765 ARMCC::CondCodes CondCode = IntCCToARMCC(CC); 3766 if (CondCode == ARMCC::LT || CondCode == ARMCC::LE || 3767 CondCode == ARMCC::VC || CondCode == ARMCC::NE) { 3768 CC = ISD::getSetCCInverse(CC, true); 3769 std::swap(TrueVal, FalseVal); 3770 } 3771 } 3772 3773 SDValue ARMcc; 3774 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32); 3775 SDValue Cmp = getARMCmp(LHS, RHS, CC, ARMcc, DAG, dl); 3776 return getCMOV(dl, VT, FalseVal, TrueVal, ARMcc, CCR, Cmp, DAG); 3777 } 3778 3779 ARMCC::CondCodes CondCode, CondCode2; 3780 FPCCToARMCC(CC, CondCode, CondCode2); 3781 3782 // Try to generate VMAXNM/VMINNM on ARMv8. 3783 if (Subtarget->hasFPARMv8() && (TrueVal.getValueType() == MVT::f32 || 3784 TrueVal.getValueType() == MVT::f64)) { 3785 bool swpCmpOps = false; 3786 bool swpVselOps = false; 3787 checkVSELConstraints(CC, CondCode, swpCmpOps, swpVselOps); 3788 3789 if (CondCode == ARMCC::GT || CondCode == ARMCC::GE || 3790 CondCode == ARMCC::VS || CondCode == ARMCC::EQ) { 3791 if (swpCmpOps) 3792 std::swap(LHS, RHS); 3793 if (swpVselOps) 3794 std::swap(TrueVal, FalseVal); 3795 } 3796 } 3797 3798 SDValue ARMcc = DAG.getConstant(CondCode, dl, MVT::i32); 3799 SDValue Cmp = getVFPCmp(LHS, RHS, DAG, dl); 3800 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32); 3801 SDValue Result = getCMOV(dl, VT, FalseVal, TrueVal, ARMcc, CCR, Cmp, DAG); 3802 if (CondCode2 != ARMCC::AL) { 3803 SDValue ARMcc2 = DAG.getConstant(CondCode2, dl, MVT::i32); 3804 // FIXME: Needs another CMP because flag can have but one use. 3805 SDValue Cmp2 = getVFPCmp(LHS, RHS, DAG, dl); 3806 Result = getCMOV(dl, VT, Result, TrueVal, ARMcc2, CCR, Cmp2, DAG); 3807 } 3808 return Result; 3809 } 3810 3811 /// canChangeToInt - Given the fp compare operand, return true if it is suitable 3812 /// to morph to an integer compare sequence. 3813 static bool canChangeToInt(SDValue Op, bool &SeenZero, 3814 const ARMSubtarget *Subtarget) { 3815 SDNode *N = Op.getNode(); 3816 if (!N->hasOneUse()) 3817 // Otherwise it requires moving the value from fp to integer registers. 3818 return false; 3819 if (!N->getNumValues()) 3820 return false; 3821 EVT VT = Op.getValueType(); 3822 if (VT != MVT::f32 && !Subtarget->isFPBrccSlow()) 3823 // f32 case is generally profitable. f64 case only makes sense when vcmpe + 3824 // vmrs are very slow, e.g. cortex-a8. 3825 return false; 3826 3827 if (isFloatingPointZero(Op)) { 3828 SeenZero = true; 3829 return true; 3830 } 3831 return ISD::isNormalLoad(N); 3832 } 3833 3834 static SDValue bitcastf32Toi32(SDValue Op, SelectionDAG &DAG) { 3835 if (isFloatingPointZero(Op)) 3836 return DAG.getConstant(0, SDLoc(Op), MVT::i32); 3837 3838 if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Op)) 3839 return DAG.getLoad(MVT::i32, SDLoc(Op), 3840 Ld->getChain(), Ld->getBasePtr(), Ld->getPointerInfo(), 3841 Ld->isVolatile(), Ld->isNonTemporal(), 3842 Ld->isInvariant(), Ld->getAlignment()); 3843 3844 llvm_unreachable("Unknown VFP cmp argument!"); 3845 } 3846 3847 static void expandf64Toi32(SDValue Op, SelectionDAG &DAG, 3848 SDValue &RetVal1, SDValue &RetVal2) { 3849 SDLoc dl(Op); 3850 3851 if (isFloatingPointZero(Op)) { 3852 RetVal1 = DAG.getConstant(0, dl, MVT::i32); 3853 RetVal2 = DAG.getConstant(0, dl, MVT::i32); 3854 return; 3855 } 3856 3857 if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Op)) { 3858 SDValue Ptr = Ld->getBasePtr(); 3859 RetVal1 = DAG.getLoad(MVT::i32, dl, 3860 Ld->getChain(), Ptr, 3861 Ld->getPointerInfo(), 3862 Ld->isVolatile(), Ld->isNonTemporal(), 3863 Ld->isInvariant(), Ld->getAlignment()); 3864 3865 EVT PtrType = Ptr.getValueType(); 3866 unsigned NewAlign = MinAlign(Ld->getAlignment(), 4); 3867 SDValue NewPtr = DAG.getNode(ISD::ADD, dl, 3868 PtrType, Ptr, DAG.getConstant(4, dl, PtrType)); 3869 RetVal2 = DAG.getLoad(MVT::i32, dl, 3870 Ld->getChain(), NewPtr, 3871 Ld->getPointerInfo().getWithOffset(4), 3872 Ld->isVolatile(), Ld->isNonTemporal(), 3873 Ld->isInvariant(), NewAlign); 3874 return; 3875 } 3876 3877 llvm_unreachable("Unknown VFP cmp argument!"); 3878 } 3879 3880 /// OptimizeVFPBrcond - With -enable-unsafe-fp-math, it's legal to optimize some 3881 /// f32 and even f64 comparisons to integer ones. 3882 SDValue 3883 ARMTargetLowering::OptimizeVFPBrcond(SDValue Op, SelectionDAG &DAG) const { 3884 SDValue Chain = Op.getOperand(0); 3885 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(1))->get(); 3886 SDValue LHS = Op.getOperand(2); 3887 SDValue RHS = Op.getOperand(3); 3888 SDValue Dest = Op.getOperand(4); 3889 SDLoc dl(Op); 3890 3891 bool LHSSeenZero = false; 3892 bool LHSOk = canChangeToInt(LHS, LHSSeenZero, Subtarget); 3893 bool RHSSeenZero = false; 3894 bool RHSOk = canChangeToInt(RHS, RHSSeenZero, Subtarget); 3895 if (LHSOk && RHSOk && (LHSSeenZero || RHSSeenZero)) { 3896 // If unsafe fp math optimization is enabled and there are no other uses of 3897 // the CMP operands, and the condition code is EQ or NE, we can optimize it 3898 // to an integer comparison. 3899 if (CC == ISD::SETOEQ) 3900 CC = ISD::SETEQ; 3901 else if (CC == ISD::SETUNE) 3902 CC = ISD::SETNE; 3903 3904 SDValue Mask = DAG.getConstant(0x7fffffff, dl, MVT::i32); 3905 SDValue ARMcc; 3906 if (LHS.getValueType() == MVT::f32) { 3907 LHS = DAG.getNode(ISD::AND, dl, MVT::i32, 3908 bitcastf32Toi32(LHS, DAG), Mask); 3909 RHS = DAG.getNode(ISD::AND, dl, MVT::i32, 3910 bitcastf32Toi32(RHS, DAG), Mask); 3911 SDValue Cmp = getARMCmp(LHS, RHS, CC, ARMcc, DAG, dl); 3912 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32); 3913 return DAG.getNode(ARMISD::BRCOND, dl, MVT::Other, 3914 Chain, Dest, ARMcc, CCR, Cmp); 3915 } 3916 3917 SDValue LHS1, LHS2; 3918 SDValue RHS1, RHS2; 3919 expandf64Toi32(LHS, DAG, LHS1, LHS2); 3920 expandf64Toi32(RHS, DAG, RHS1, RHS2); 3921 LHS2 = DAG.getNode(ISD::AND, dl, MVT::i32, LHS2, Mask); 3922 RHS2 = DAG.getNode(ISD::AND, dl, MVT::i32, RHS2, Mask); 3923 ARMCC::CondCodes CondCode = IntCCToARMCC(CC); 3924 ARMcc = DAG.getConstant(CondCode, dl, MVT::i32); 3925 SDVTList VTList = DAG.getVTList(MVT::Other, MVT::Glue); 3926 SDValue Ops[] = { Chain, ARMcc, LHS1, LHS2, RHS1, RHS2, Dest }; 3927 return DAG.getNode(ARMISD::BCC_i64, dl, VTList, Ops); 3928 } 3929 3930 return SDValue(); 3931 } 3932 3933 SDValue ARMTargetLowering::LowerBR_CC(SDValue Op, SelectionDAG &DAG) const { 3934 SDValue Chain = Op.getOperand(0); 3935 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(1))->get(); 3936 SDValue LHS = Op.getOperand(2); 3937 SDValue RHS = Op.getOperand(3); 3938 SDValue Dest = Op.getOperand(4); 3939 SDLoc dl(Op); 3940 3941 if (Subtarget->isFPOnlySP() && LHS.getValueType() == MVT::f64) { 3942 DAG.getTargetLoweringInfo().softenSetCCOperands(DAG, MVT::f64, LHS, RHS, CC, 3943 dl); 3944 3945 // If softenSetCCOperands only returned one value, we should compare it to 3946 // zero. 3947 if (!RHS.getNode()) { 3948 RHS = DAG.getConstant(0, dl, LHS.getValueType()); 3949 CC = ISD::SETNE; 3950 } 3951 } 3952 3953 if (LHS.getValueType() == MVT::i32) { 3954 SDValue ARMcc; 3955 SDValue Cmp = getARMCmp(LHS, RHS, CC, ARMcc, DAG, dl); 3956 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32); 3957 return DAG.getNode(ARMISD::BRCOND, dl, MVT::Other, 3958 Chain, Dest, ARMcc, CCR, Cmp); 3959 } 3960 3961 assert(LHS.getValueType() == MVT::f32 || LHS.getValueType() == MVT::f64); 3962 3963 if (getTargetMachine().Options.UnsafeFPMath && 3964 (CC == ISD::SETEQ || CC == ISD::SETOEQ || 3965 CC == ISD::SETNE || CC == ISD::SETUNE)) { 3966 if (SDValue Result = OptimizeVFPBrcond(Op, DAG)) 3967 return Result; 3968 } 3969 3970 ARMCC::CondCodes CondCode, CondCode2; 3971 FPCCToARMCC(CC, CondCode, CondCode2); 3972 3973 SDValue ARMcc = DAG.getConstant(CondCode, dl, MVT::i32); 3974 SDValue Cmp = getVFPCmp(LHS, RHS, DAG, dl); 3975 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32); 3976 SDVTList VTList = DAG.getVTList(MVT::Other, MVT::Glue); 3977 SDValue Ops[] = { Chain, Dest, ARMcc, CCR, Cmp }; 3978 SDValue Res = DAG.getNode(ARMISD::BRCOND, dl, VTList, Ops); 3979 if (CondCode2 != ARMCC::AL) { 3980 ARMcc = DAG.getConstant(CondCode2, dl, MVT::i32); 3981 SDValue Ops[] = { Res, Dest, ARMcc, CCR, Res.getValue(1) }; 3982 Res = DAG.getNode(ARMISD::BRCOND, dl, VTList, Ops); 3983 } 3984 return Res; 3985 } 3986 3987 SDValue ARMTargetLowering::LowerBR_JT(SDValue Op, SelectionDAG &DAG) const { 3988 SDValue Chain = Op.getOperand(0); 3989 SDValue Table = Op.getOperand(1); 3990 SDValue Index = Op.getOperand(2); 3991 SDLoc dl(Op); 3992 3993 EVT PTy = getPointerTy(DAG.getDataLayout()); 3994 JumpTableSDNode *JT = cast<JumpTableSDNode>(Table); 3995 SDValue JTI = DAG.getTargetJumpTable(JT->getIndex(), PTy); 3996 Table = DAG.getNode(ARMISD::WrapperJT, dl, MVT::i32, JTI); 3997 Index = DAG.getNode(ISD::MUL, dl, PTy, Index, DAG.getConstant(4, dl, PTy)); 3998 SDValue Addr = DAG.getNode(ISD::ADD, dl, PTy, Index, Table); 3999 if (Subtarget->isThumb2()) { 4000 // Thumb2 uses a two-level jump. That is, it jumps into the jump table 4001 // which does another jump to the destination. This also makes it easier 4002 // to translate it to TBB / TBH later. 4003 // FIXME: This might not work if the function is extremely large. 4004 return DAG.getNode(ARMISD::BR2_JT, dl, MVT::Other, Chain, 4005 Addr, Op.getOperand(2), JTI); 4006 } 4007 if (getTargetMachine().getRelocationModel() == Reloc::PIC_) { 4008 Addr = 4009 DAG.getLoad((EVT)MVT::i32, dl, Chain, Addr, 4010 MachinePointerInfo::getJumpTable(DAG.getMachineFunction()), 4011 false, false, false, 0); 4012 Chain = Addr.getValue(1); 4013 Addr = DAG.getNode(ISD::ADD, dl, PTy, Addr, Table); 4014 return DAG.getNode(ARMISD::BR_JT, dl, MVT::Other, Chain, Addr, JTI); 4015 } else { 4016 Addr = 4017 DAG.getLoad(PTy, dl, Chain, Addr, 4018 MachinePointerInfo::getJumpTable(DAG.getMachineFunction()), 4019 false, false, false, 0); 4020 Chain = Addr.getValue(1); 4021 return DAG.getNode(ARMISD::BR_JT, dl, MVT::Other, Chain, Addr, JTI); 4022 } 4023 } 4024 4025 static SDValue LowerVectorFP_TO_INT(SDValue Op, SelectionDAG &DAG) { 4026 EVT VT = Op.getValueType(); 4027 SDLoc dl(Op); 4028 4029 if (Op.getValueType().getVectorElementType() == MVT::i32) { 4030 if (Op.getOperand(0).getValueType().getVectorElementType() == MVT::f32) 4031 return Op; 4032 return DAG.UnrollVectorOp(Op.getNode()); 4033 } 4034 4035 assert(Op.getOperand(0).getValueType() == MVT::v4f32 && 4036 "Invalid type for custom lowering!"); 4037 if (VT != MVT::v4i16) 4038 return DAG.UnrollVectorOp(Op.getNode()); 4039 4040 Op = DAG.getNode(Op.getOpcode(), dl, MVT::v4i32, Op.getOperand(0)); 4041 return DAG.getNode(ISD::TRUNCATE, dl, VT, Op); 4042 } 4043 4044 SDValue ARMTargetLowering::LowerFP_TO_INT(SDValue Op, SelectionDAG &DAG) const { 4045 EVT VT = Op.getValueType(); 4046 if (VT.isVector()) 4047 return LowerVectorFP_TO_INT(Op, DAG); 4048 if (Subtarget->isFPOnlySP() && Op.getOperand(0).getValueType() == MVT::f64) { 4049 RTLIB::Libcall LC; 4050 if (Op.getOpcode() == ISD::FP_TO_SINT) 4051 LC = RTLIB::getFPTOSINT(Op.getOperand(0).getValueType(), 4052 Op.getValueType()); 4053 else 4054 LC = RTLIB::getFPTOUINT(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 static SDValue LowerVectorINT_TO_FP(SDValue Op, SelectionDAG &DAG) { 4064 EVT VT = Op.getValueType(); 4065 SDLoc dl(Op); 4066 4067 if (Op.getOperand(0).getValueType().getVectorElementType() == MVT::i32) { 4068 if (VT.getVectorElementType() == MVT::f32) 4069 return Op; 4070 return DAG.UnrollVectorOp(Op.getNode()); 4071 } 4072 4073 assert(Op.getOperand(0).getValueType() == MVT::v4i16 && 4074 "Invalid type for custom lowering!"); 4075 if (VT != MVT::v4f32) 4076 return DAG.UnrollVectorOp(Op.getNode()); 4077 4078 unsigned CastOpc; 4079 unsigned Opc; 4080 switch (Op.getOpcode()) { 4081 default: llvm_unreachable("Invalid opcode!"); 4082 case ISD::SINT_TO_FP: 4083 CastOpc = ISD::SIGN_EXTEND; 4084 Opc = ISD::SINT_TO_FP; 4085 break; 4086 case ISD::UINT_TO_FP: 4087 CastOpc = ISD::ZERO_EXTEND; 4088 Opc = ISD::UINT_TO_FP; 4089 break; 4090 } 4091 4092 Op = DAG.getNode(CastOpc, dl, MVT::v4i32, Op.getOperand(0)); 4093 return DAG.getNode(Opc, dl, VT, Op); 4094 } 4095 4096 SDValue ARMTargetLowering::LowerINT_TO_FP(SDValue Op, SelectionDAG &DAG) const { 4097 EVT VT = Op.getValueType(); 4098 if (VT.isVector()) 4099 return LowerVectorINT_TO_FP(Op, DAG); 4100 if (Subtarget->isFPOnlySP() && Op.getValueType() == MVT::f64) { 4101 RTLIB::Libcall LC; 4102 if (Op.getOpcode() == ISD::SINT_TO_FP) 4103 LC = RTLIB::getSINTTOFP(Op.getOperand(0).getValueType(), 4104 Op.getValueType()); 4105 else 4106 LC = RTLIB::getUINTTOFP(Op.getOperand(0).getValueType(), 4107 Op.getValueType()); 4108 return makeLibCall(DAG, LC, Op.getValueType(), Op.getOperand(0), 4109 /*isSigned*/ false, SDLoc(Op)).first; 4110 } 4111 4112 return Op; 4113 } 4114 4115 SDValue ARMTargetLowering::LowerFCOPYSIGN(SDValue Op, SelectionDAG &DAG) const { 4116 // Implement fcopysign with a fabs and a conditional fneg. 4117 SDValue Tmp0 = Op.getOperand(0); 4118 SDValue Tmp1 = Op.getOperand(1); 4119 SDLoc dl(Op); 4120 EVT VT = Op.getValueType(); 4121 EVT SrcVT = Tmp1.getValueType(); 4122 bool InGPR = Tmp0.getOpcode() == ISD::BITCAST || 4123 Tmp0.getOpcode() == ARMISD::VMOVDRR; 4124 bool UseNEON = !InGPR && Subtarget->hasNEON(); 4125 4126 if (UseNEON) { 4127 // Use VBSL to copy the sign bit. 4128 unsigned EncodedVal = ARM_AM::createNEONModImm(0x6, 0x80); 4129 SDValue Mask = DAG.getNode(ARMISD::VMOVIMM, dl, MVT::v2i32, 4130 DAG.getTargetConstant(EncodedVal, dl, MVT::i32)); 4131 EVT OpVT = (VT == MVT::f32) ? MVT::v2i32 : MVT::v1i64; 4132 if (VT == MVT::f64) 4133 Mask = DAG.getNode(ARMISD::VSHL, dl, OpVT, 4134 DAG.getNode(ISD::BITCAST, dl, OpVT, Mask), 4135 DAG.getConstant(32, dl, MVT::i32)); 4136 else /*if (VT == MVT::f32)*/ 4137 Tmp0 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f32, Tmp0); 4138 if (SrcVT == MVT::f32) { 4139 Tmp1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f32, Tmp1); 4140 if (VT == MVT::f64) 4141 Tmp1 = DAG.getNode(ARMISD::VSHL, dl, OpVT, 4142 DAG.getNode(ISD::BITCAST, dl, OpVT, Tmp1), 4143 DAG.getConstant(32, dl, MVT::i32)); 4144 } else if (VT == MVT::f32) 4145 Tmp1 = DAG.getNode(ARMISD::VSHRu, dl, MVT::v1i64, 4146 DAG.getNode(ISD::BITCAST, dl, MVT::v1i64, Tmp1), 4147 DAG.getConstant(32, dl, MVT::i32)); 4148 Tmp0 = DAG.getNode(ISD::BITCAST, dl, OpVT, Tmp0); 4149 Tmp1 = DAG.getNode(ISD::BITCAST, dl, OpVT, Tmp1); 4150 4151 SDValue AllOnes = DAG.getTargetConstant(ARM_AM::createNEONModImm(0xe, 0xff), 4152 dl, MVT::i32); 4153 AllOnes = DAG.getNode(ARMISD::VMOVIMM, dl, MVT::v8i8, AllOnes); 4154 SDValue MaskNot = DAG.getNode(ISD::XOR, dl, OpVT, Mask, 4155 DAG.getNode(ISD::BITCAST, dl, OpVT, AllOnes)); 4156 4157 SDValue Res = DAG.getNode(ISD::OR, dl, OpVT, 4158 DAG.getNode(ISD::AND, dl, OpVT, Tmp1, Mask), 4159 DAG.getNode(ISD::AND, dl, OpVT, Tmp0, MaskNot)); 4160 if (VT == MVT::f32) { 4161 Res = DAG.getNode(ISD::BITCAST, dl, MVT::v2f32, Res); 4162 Res = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f32, Res, 4163 DAG.getConstant(0, dl, MVT::i32)); 4164 } else { 4165 Res = DAG.getNode(ISD::BITCAST, dl, MVT::f64, Res); 4166 } 4167 4168 return Res; 4169 } 4170 4171 // Bitcast operand 1 to i32. 4172 if (SrcVT == MVT::f64) 4173 Tmp1 = DAG.getNode(ARMISD::VMOVRRD, dl, DAG.getVTList(MVT::i32, MVT::i32), 4174 Tmp1).getValue(1); 4175 Tmp1 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Tmp1); 4176 4177 // Or in the signbit with integer operations. 4178 SDValue Mask1 = DAG.getConstant(0x80000000, dl, MVT::i32); 4179 SDValue Mask2 = DAG.getConstant(0x7fffffff, dl, MVT::i32); 4180 Tmp1 = DAG.getNode(ISD::AND, dl, MVT::i32, Tmp1, Mask1); 4181 if (VT == MVT::f32) { 4182 Tmp0 = DAG.getNode(ISD::AND, dl, MVT::i32, 4183 DAG.getNode(ISD::BITCAST, dl, MVT::i32, Tmp0), Mask2); 4184 return DAG.getNode(ISD::BITCAST, dl, MVT::f32, 4185 DAG.getNode(ISD::OR, dl, MVT::i32, Tmp0, Tmp1)); 4186 } 4187 4188 // f64: Or the high part with signbit and then combine two parts. 4189 Tmp0 = DAG.getNode(ARMISD::VMOVRRD, dl, DAG.getVTList(MVT::i32, MVT::i32), 4190 Tmp0); 4191 SDValue Lo = Tmp0.getValue(0); 4192 SDValue Hi = DAG.getNode(ISD::AND, dl, MVT::i32, Tmp0.getValue(1), Mask2); 4193 Hi = DAG.getNode(ISD::OR, dl, MVT::i32, Hi, Tmp1); 4194 return DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi); 4195 } 4196 4197 SDValue ARMTargetLowering::LowerRETURNADDR(SDValue Op, SelectionDAG &DAG) const{ 4198 MachineFunction &MF = DAG.getMachineFunction(); 4199 MachineFrameInfo *MFI = MF.getFrameInfo(); 4200 MFI->setReturnAddressIsTaken(true); 4201 4202 if (verifyReturnAddressArgumentIsConstant(Op, DAG)) 4203 return SDValue(); 4204 4205 EVT VT = Op.getValueType(); 4206 SDLoc dl(Op); 4207 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue(); 4208 if (Depth) { 4209 SDValue FrameAddr = LowerFRAMEADDR(Op, DAG); 4210 SDValue Offset = DAG.getConstant(4, dl, MVT::i32); 4211 return DAG.getLoad(VT, dl, DAG.getEntryNode(), 4212 DAG.getNode(ISD::ADD, dl, VT, FrameAddr, Offset), 4213 MachinePointerInfo(), false, false, false, 0); 4214 } 4215 4216 // Return LR, which contains the return address. Mark it an implicit live-in. 4217 unsigned Reg = MF.addLiveIn(ARM::LR, getRegClassFor(MVT::i32)); 4218 return DAG.getCopyFromReg(DAG.getEntryNode(), dl, Reg, VT); 4219 } 4220 4221 SDValue ARMTargetLowering::LowerFRAMEADDR(SDValue Op, SelectionDAG &DAG) const { 4222 const ARMBaseRegisterInfo &ARI = 4223 *static_cast<const ARMBaseRegisterInfo*>(RegInfo); 4224 MachineFunction &MF = DAG.getMachineFunction(); 4225 MachineFrameInfo *MFI = MF.getFrameInfo(); 4226 MFI->setFrameAddressIsTaken(true); 4227 4228 EVT VT = Op.getValueType(); 4229 SDLoc dl(Op); // FIXME probably not meaningful 4230 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue(); 4231 unsigned FrameReg = ARI.getFrameRegister(MF); 4232 SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, VT); 4233 while (Depth--) 4234 FrameAddr = DAG.getLoad(VT, dl, DAG.getEntryNode(), FrameAddr, 4235 MachinePointerInfo(), 4236 false, false, false, 0); 4237 return FrameAddr; 4238 } 4239 4240 // FIXME? Maybe this could be a TableGen attribute on some registers and 4241 // this table could be generated automatically from RegInfo. 4242 unsigned ARMTargetLowering::getRegisterByName(const char* RegName, EVT VT, 4243 SelectionDAG &DAG) const { 4244 unsigned Reg = StringSwitch<unsigned>(RegName) 4245 .Case("sp", ARM::SP) 4246 .Default(0); 4247 if (Reg) 4248 return Reg; 4249 report_fatal_error(Twine("Invalid register name \"" 4250 + StringRef(RegName) + "\".")); 4251 } 4252 4253 // Result is 64 bit value so split into two 32 bit values and return as a 4254 // pair of values. 4255 static void ExpandREAD_REGISTER(SDNode *N, SmallVectorImpl<SDValue> &Results, 4256 SelectionDAG &DAG) { 4257 SDLoc DL(N); 4258 4259 // This function is only supposed to be called for i64 type destination. 4260 assert(N->getValueType(0) == MVT::i64 4261 && "ExpandREAD_REGISTER called for non-i64 type result."); 4262 4263 SDValue Read = DAG.getNode(ISD::READ_REGISTER, DL, 4264 DAG.getVTList(MVT::i32, MVT::i32, MVT::Other), 4265 N->getOperand(0), 4266 N->getOperand(1)); 4267 4268 Results.push_back(DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, Read.getValue(0), 4269 Read.getValue(1))); 4270 Results.push_back(Read.getOperand(0)); 4271 } 4272 4273 /// \p BC is a bitcast that is about to be turned into a VMOVDRR. 4274 /// When \p DstVT, the destination type of \p BC, is on the vector 4275 /// register bank and the source of bitcast, \p Op, operates on the same bank, 4276 /// it might be possible to combine them, such that everything stays on the 4277 /// vector register bank. 4278 /// \p return The node that would replace \p BT, if the combine 4279 /// is possible. 4280 static SDValue CombineVMOVDRRCandidateWithVecOp(const SDNode *BC, 4281 SelectionDAG &DAG) { 4282 SDValue Op = BC->getOperand(0); 4283 EVT DstVT = BC->getValueType(0); 4284 4285 // The only vector instruction that can produce a scalar (remember, 4286 // since the bitcast was about to be turned into VMOVDRR, the source 4287 // type is i64) from a vector is EXTRACT_VECTOR_ELT. 4288 // Moreover, we can do this combine only if there is one use. 4289 // Finally, if the destination type is not a vector, there is not 4290 // much point on forcing everything on the vector bank. 4291 if (!DstVT.isVector() || Op.getOpcode() != ISD::EXTRACT_VECTOR_ELT || 4292 !Op.hasOneUse()) 4293 return SDValue(); 4294 4295 // If the index is not constant, we will introduce an additional 4296 // multiply that will stick. 4297 // Give up in that case. 4298 ConstantSDNode *Index = dyn_cast<ConstantSDNode>(Op.getOperand(1)); 4299 if (!Index) 4300 return SDValue(); 4301 unsigned DstNumElt = DstVT.getVectorNumElements(); 4302 4303 // Compute the new index. 4304 const APInt &APIntIndex = Index->getAPIntValue(); 4305 APInt NewIndex(APIntIndex.getBitWidth(), DstNumElt); 4306 NewIndex *= APIntIndex; 4307 // Check if the new constant index fits into i32. 4308 if (NewIndex.getBitWidth() > 32) 4309 return SDValue(); 4310 4311 // vMTy bitcast(i64 extractelt vNi64 src, i32 index) -> 4312 // vMTy extractsubvector vNxMTy (bitcast vNi64 src), i32 index*M) 4313 SDLoc dl(Op); 4314 SDValue ExtractSrc = Op.getOperand(0); 4315 EVT VecVT = EVT::getVectorVT( 4316 *DAG.getContext(), DstVT.getScalarType(), 4317 ExtractSrc.getValueType().getVectorNumElements() * DstNumElt); 4318 SDValue BitCast = DAG.getNode(ISD::BITCAST, dl, VecVT, ExtractSrc); 4319 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DstVT, BitCast, 4320 DAG.getConstant(NewIndex.getZExtValue(), dl, MVT::i32)); 4321 } 4322 4323 /// ExpandBITCAST - If the target supports VFP, this function is called to 4324 /// expand a bit convert where either the source or destination type is i64 to 4325 /// use a VMOVDRR or VMOVRRD node. This should not be done when the non-i64 4326 /// operand type is illegal (e.g., v2f32 for a target that doesn't support 4327 /// vectors), since the legalizer won't know what to do with that. 4328 static SDValue ExpandBITCAST(SDNode *N, SelectionDAG &DAG) { 4329 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 4330 SDLoc dl(N); 4331 SDValue Op = N->getOperand(0); 4332 4333 // This function is only supposed to be called for i64 types, either as the 4334 // source or destination of the bit convert. 4335 EVT SrcVT = Op.getValueType(); 4336 EVT DstVT = N->getValueType(0); 4337 assert((SrcVT == MVT::i64 || DstVT == MVT::i64) && 4338 "ExpandBITCAST called for non-i64 type"); 4339 4340 // Turn i64->f64 into VMOVDRR. 4341 if (SrcVT == MVT::i64 && TLI.isTypeLegal(DstVT)) { 4342 // Do not force values to GPRs (this is what VMOVDRR does for the inputs) 4343 // if we can combine the bitcast with its source. 4344 if (SDValue Val = CombineVMOVDRRCandidateWithVecOp(N, DAG)) 4345 return Val; 4346 4347 SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, Op, 4348 DAG.getConstant(0, dl, MVT::i32)); 4349 SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, Op, 4350 DAG.getConstant(1, dl, MVT::i32)); 4351 return DAG.getNode(ISD::BITCAST, dl, DstVT, 4352 DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi)); 4353 } 4354 4355 // Turn f64->i64 into VMOVRRD. 4356 if (DstVT == MVT::i64 && TLI.isTypeLegal(SrcVT)) { 4357 SDValue Cvt; 4358 if (DAG.getDataLayout().isBigEndian() && SrcVT.isVector() && 4359 SrcVT.getVectorNumElements() > 1) 4360 Cvt = DAG.getNode(ARMISD::VMOVRRD, dl, 4361 DAG.getVTList(MVT::i32, MVT::i32), 4362 DAG.getNode(ARMISD::VREV64, dl, SrcVT, Op)); 4363 else 4364 Cvt = DAG.getNode(ARMISD::VMOVRRD, dl, 4365 DAG.getVTList(MVT::i32, MVT::i32), Op); 4366 // Merge the pieces into a single i64 value. 4367 return DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Cvt, Cvt.getValue(1)); 4368 } 4369 4370 return SDValue(); 4371 } 4372 4373 /// getZeroVector - Returns a vector of specified type with all zero elements. 4374 /// Zero vectors are used to represent vector negation and in those cases 4375 /// will be implemented with the NEON VNEG instruction. However, VNEG does 4376 /// not support i64 elements, so sometimes the zero vectors will need to be 4377 /// explicitly constructed. Regardless, use a canonical VMOV to create the 4378 /// zero vector. 4379 static SDValue getZeroVector(EVT VT, SelectionDAG &DAG, SDLoc dl) { 4380 assert(VT.isVector() && "Expected a vector type"); 4381 // The canonical modified immediate encoding of a zero vector is....0! 4382 SDValue EncodedVal = DAG.getTargetConstant(0, dl, MVT::i32); 4383 EVT VmovVT = VT.is128BitVector() ? MVT::v4i32 : MVT::v2i32; 4384 SDValue Vmov = DAG.getNode(ARMISD::VMOVIMM, dl, VmovVT, EncodedVal); 4385 return DAG.getNode(ISD::BITCAST, dl, VT, Vmov); 4386 } 4387 4388 /// LowerShiftRightParts - Lower SRA_PARTS, which returns two 4389 /// i32 values and take a 2 x i32 value to shift plus a shift amount. 4390 SDValue ARMTargetLowering::LowerShiftRightParts(SDValue Op, 4391 SelectionDAG &DAG) const { 4392 assert(Op.getNumOperands() == 3 && "Not a double-shift!"); 4393 EVT VT = Op.getValueType(); 4394 unsigned VTBits = VT.getSizeInBits(); 4395 SDLoc dl(Op); 4396 SDValue ShOpLo = Op.getOperand(0); 4397 SDValue ShOpHi = Op.getOperand(1); 4398 SDValue ShAmt = Op.getOperand(2); 4399 SDValue ARMcc; 4400 unsigned Opc = (Op.getOpcode() == ISD::SRA_PARTS) ? ISD::SRA : ISD::SRL; 4401 4402 assert(Op.getOpcode() == ISD::SRA_PARTS || Op.getOpcode() == ISD::SRL_PARTS); 4403 4404 SDValue RevShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32, 4405 DAG.getConstant(VTBits, dl, MVT::i32), ShAmt); 4406 SDValue Tmp1 = DAG.getNode(ISD::SRL, dl, VT, ShOpLo, ShAmt); 4407 SDValue ExtraShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32, ShAmt, 4408 DAG.getConstant(VTBits, dl, MVT::i32)); 4409 SDValue Tmp2 = DAG.getNode(ISD::SHL, dl, VT, ShOpHi, RevShAmt); 4410 SDValue FalseVal = DAG.getNode(ISD::OR, dl, VT, Tmp1, Tmp2); 4411 SDValue TrueVal = DAG.getNode(Opc, dl, VT, ShOpHi, ExtraShAmt); 4412 4413 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32); 4414 SDValue Cmp = getARMCmp(ExtraShAmt, DAG.getConstant(0, dl, MVT::i32), 4415 ISD::SETGE, ARMcc, DAG, dl); 4416 SDValue Hi = DAG.getNode(Opc, dl, VT, ShOpHi, ShAmt); 4417 SDValue Lo = DAG.getNode(ARMISD::CMOV, dl, VT, FalseVal, TrueVal, ARMcc, 4418 CCR, Cmp); 4419 4420 SDValue Ops[2] = { Lo, Hi }; 4421 return DAG.getMergeValues(Ops, dl); 4422 } 4423 4424 /// LowerShiftLeftParts - Lower SHL_PARTS, which returns two 4425 /// i32 values and take a 2 x i32 value to shift plus a shift amount. 4426 SDValue ARMTargetLowering::LowerShiftLeftParts(SDValue Op, 4427 SelectionDAG &DAG) const { 4428 assert(Op.getNumOperands() == 3 && "Not a double-shift!"); 4429 EVT VT = Op.getValueType(); 4430 unsigned VTBits = VT.getSizeInBits(); 4431 SDLoc dl(Op); 4432 SDValue ShOpLo = Op.getOperand(0); 4433 SDValue ShOpHi = Op.getOperand(1); 4434 SDValue ShAmt = Op.getOperand(2); 4435 SDValue ARMcc; 4436 4437 assert(Op.getOpcode() == ISD::SHL_PARTS); 4438 SDValue RevShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32, 4439 DAG.getConstant(VTBits, dl, MVT::i32), ShAmt); 4440 SDValue Tmp1 = DAG.getNode(ISD::SRL, dl, VT, ShOpLo, RevShAmt); 4441 SDValue ExtraShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32, ShAmt, 4442 DAG.getConstant(VTBits, dl, MVT::i32)); 4443 SDValue Tmp2 = DAG.getNode(ISD::SHL, dl, VT, ShOpHi, ShAmt); 4444 SDValue Tmp3 = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ExtraShAmt); 4445 4446 SDValue FalseVal = DAG.getNode(ISD::OR, dl, VT, Tmp1, Tmp2); 4447 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32); 4448 SDValue Cmp = getARMCmp(ExtraShAmt, DAG.getConstant(0, dl, MVT::i32), 4449 ISD::SETGE, ARMcc, DAG, dl); 4450 SDValue Lo = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ShAmt); 4451 SDValue Hi = DAG.getNode(ARMISD::CMOV, dl, VT, FalseVal, Tmp3, ARMcc, 4452 CCR, Cmp); 4453 4454 SDValue Ops[2] = { Lo, Hi }; 4455 return DAG.getMergeValues(Ops, dl); 4456 } 4457 4458 SDValue ARMTargetLowering::LowerFLT_ROUNDS_(SDValue Op, 4459 SelectionDAG &DAG) const { 4460 // The rounding mode is in bits 23:22 of the FPSCR. 4461 // The ARM rounding mode value to FLT_ROUNDS mapping is 0->1, 1->2, 2->3, 3->0 4462 // The formula we use to implement this is (((FPSCR + 1 << 22) >> 22) & 3) 4463 // so that the shift + and get folded into a bitfield extract. 4464 SDLoc dl(Op); 4465 SDValue FPSCR = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::i32, 4466 DAG.getConstant(Intrinsic::arm_get_fpscr, dl, 4467 MVT::i32)); 4468 SDValue FltRounds = DAG.getNode(ISD::ADD, dl, MVT::i32, FPSCR, 4469 DAG.getConstant(1U << 22, dl, MVT::i32)); 4470 SDValue RMODE = DAG.getNode(ISD::SRL, dl, MVT::i32, FltRounds, 4471 DAG.getConstant(22, dl, MVT::i32)); 4472 return DAG.getNode(ISD::AND, dl, MVT::i32, RMODE, 4473 DAG.getConstant(3, dl, MVT::i32)); 4474 } 4475 4476 static SDValue LowerCTTZ(SDNode *N, SelectionDAG &DAG, 4477 const ARMSubtarget *ST) { 4478 SDLoc dl(N); 4479 EVT VT = N->getValueType(0); 4480 if (VT.isVector()) { 4481 assert(ST->hasNEON()); 4482 4483 // Compute the least significant set bit: LSB = X & -X 4484 SDValue X = N->getOperand(0); 4485 SDValue NX = DAG.getNode(ISD::SUB, dl, VT, getZeroVector(VT, DAG, dl), X); 4486 SDValue LSB = DAG.getNode(ISD::AND, dl, VT, X, NX); 4487 4488 EVT ElemTy = VT.getVectorElementType(); 4489 4490 if (ElemTy == MVT::i8) { 4491 // Compute with: cttz(x) = ctpop(lsb - 1) 4492 SDValue One = DAG.getNode(ARMISD::VMOVIMM, dl, VT, 4493 DAG.getTargetConstant(1, dl, ElemTy)); 4494 SDValue Bits = DAG.getNode(ISD::SUB, dl, VT, LSB, One); 4495 return DAG.getNode(ISD::CTPOP, dl, VT, Bits); 4496 } 4497 4498 if ((ElemTy == MVT::i16 || ElemTy == MVT::i32) && 4499 (N->getOpcode() == ISD::CTTZ_ZERO_UNDEF)) { 4500 // Compute with: cttz(x) = (width - 1) - ctlz(lsb), if x != 0 4501 unsigned NumBits = ElemTy.getSizeInBits(); 4502 SDValue WidthMinus1 = 4503 DAG.getNode(ARMISD::VMOVIMM, dl, VT, 4504 DAG.getTargetConstant(NumBits - 1, dl, ElemTy)); 4505 SDValue CTLZ = DAG.getNode(ISD::CTLZ, dl, VT, LSB); 4506 return DAG.getNode(ISD::SUB, dl, VT, WidthMinus1, CTLZ); 4507 } 4508 4509 // Compute with: cttz(x) = ctpop(lsb - 1) 4510 4511 // Since we can only compute the number of bits in a byte with vcnt.8, we 4512 // have to gather the result with pairwise addition (vpaddl) for i16, i32, 4513 // and i64. 4514 4515 // Compute LSB - 1. 4516 SDValue Bits; 4517 if (ElemTy == MVT::i64) { 4518 // Load constant 0xffff'ffff'ffff'ffff to register. 4519 SDValue FF = DAG.getNode(ARMISD::VMOVIMM, dl, VT, 4520 DAG.getTargetConstant(0x1eff, dl, MVT::i32)); 4521 Bits = DAG.getNode(ISD::ADD, dl, VT, LSB, FF); 4522 } else { 4523 SDValue One = DAG.getNode(ARMISD::VMOVIMM, dl, VT, 4524 DAG.getTargetConstant(1, dl, ElemTy)); 4525 Bits = DAG.getNode(ISD::SUB, dl, VT, LSB, One); 4526 } 4527 4528 // Count #bits with vcnt.8. 4529 EVT VT8Bit = VT.is64BitVector() ? MVT::v8i8 : MVT::v16i8; 4530 SDValue BitsVT8 = DAG.getNode(ISD::BITCAST, dl, VT8Bit, Bits); 4531 SDValue Cnt8 = DAG.getNode(ISD::CTPOP, dl, VT8Bit, BitsVT8); 4532 4533 // Gather the #bits with vpaddl (pairwise add.) 4534 EVT VT16Bit = VT.is64BitVector() ? MVT::v4i16 : MVT::v8i16; 4535 SDValue Cnt16 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT16Bit, 4536 DAG.getTargetConstant(Intrinsic::arm_neon_vpaddlu, dl, MVT::i32), 4537 Cnt8); 4538 if (ElemTy == MVT::i16) 4539 return Cnt16; 4540 4541 EVT VT32Bit = VT.is64BitVector() ? MVT::v2i32 : MVT::v4i32; 4542 SDValue Cnt32 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT32Bit, 4543 DAG.getTargetConstant(Intrinsic::arm_neon_vpaddlu, dl, MVT::i32), 4544 Cnt16); 4545 if (ElemTy == MVT::i32) 4546 return Cnt32; 4547 4548 assert(ElemTy == MVT::i64); 4549 SDValue Cnt64 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT, 4550 DAG.getTargetConstant(Intrinsic::arm_neon_vpaddlu, dl, MVT::i32), 4551 Cnt32); 4552 return Cnt64; 4553 } 4554 4555 if (!ST->hasV6T2Ops()) 4556 return SDValue(); 4557 4558 SDValue rbit = DAG.getNode(ISD::BITREVERSE, dl, VT, N->getOperand(0)); 4559 return DAG.getNode(ISD::CTLZ, dl, VT, rbit); 4560 } 4561 4562 /// getCTPOP16BitCounts - Returns a v8i8/v16i8 vector containing the bit-count 4563 /// for each 16-bit element from operand, repeated. The basic idea is to 4564 /// leverage vcnt to get the 8-bit counts, gather and add the results. 4565 /// 4566 /// Trace for v4i16: 4567 /// input = [v0 v1 v2 v3 ] (vi 16-bit element) 4568 /// cast: N0 = [w0 w1 w2 w3 w4 w5 w6 w7] (v0 = [w0 w1], wi 8-bit element) 4569 /// vcnt: N1 = [b0 b1 b2 b3 b4 b5 b6 b7] (bi = bit-count of 8-bit element wi) 4570 /// vrev: N2 = [b1 b0 b3 b2 b5 b4 b7 b6] 4571 /// [b0 b1 b2 b3 b4 b5 b6 b7] 4572 /// +[b1 b0 b3 b2 b5 b4 b7 b6] 4573 /// N3=N1+N2 = [k0 k0 k1 k1 k2 k2 k3 k3] (k0 = b0+b1 = bit-count of 16-bit v0, 4574 /// vuzp: = [k0 k1 k2 k3 k0 k1 k2 k3] each ki is 8-bits) 4575 static SDValue getCTPOP16BitCounts(SDNode *N, SelectionDAG &DAG) { 4576 EVT VT = N->getValueType(0); 4577 SDLoc DL(N); 4578 4579 EVT VT8Bit = VT.is64BitVector() ? MVT::v8i8 : MVT::v16i8; 4580 SDValue N0 = DAG.getNode(ISD::BITCAST, DL, VT8Bit, N->getOperand(0)); 4581 SDValue N1 = DAG.getNode(ISD::CTPOP, DL, VT8Bit, N0); 4582 SDValue N2 = DAG.getNode(ARMISD::VREV16, DL, VT8Bit, N1); 4583 SDValue N3 = DAG.getNode(ISD::ADD, DL, VT8Bit, N1, N2); 4584 return DAG.getNode(ARMISD::VUZP, DL, VT8Bit, N3, N3); 4585 } 4586 4587 /// lowerCTPOP16BitElements - Returns a v4i16/v8i16 vector containing the 4588 /// bit-count for each 16-bit element from the operand. We need slightly 4589 /// different sequencing for v4i16 and v8i16 to stay within NEON's available 4590 /// 64/128-bit registers. 4591 /// 4592 /// Trace for v4i16: 4593 /// input = [v0 v1 v2 v3 ] (vi 16-bit element) 4594 /// v8i8: BitCounts = [k0 k1 k2 k3 k0 k1 k2 k3 ] (ki is the bit-count of vi) 4595 /// v8i16:Extended = [k0 k1 k2 k3 k0 k1 k2 k3 ] 4596 /// v4i16:Extracted = [k0 k1 k2 k3 ] 4597 static SDValue lowerCTPOP16BitElements(SDNode *N, SelectionDAG &DAG) { 4598 EVT VT = N->getValueType(0); 4599 SDLoc DL(N); 4600 4601 SDValue BitCounts = getCTPOP16BitCounts(N, DAG); 4602 if (VT.is64BitVector()) { 4603 SDValue Extended = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::v8i16, BitCounts); 4604 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v4i16, Extended, 4605 DAG.getIntPtrConstant(0, DL)); 4606 } else { 4607 SDValue Extracted = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v8i8, 4608 BitCounts, DAG.getIntPtrConstant(0, DL)); 4609 return DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::v8i16, Extracted); 4610 } 4611 } 4612 4613 /// lowerCTPOP32BitElements - Returns a v2i32/v4i32 vector containing the 4614 /// bit-count for each 32-bit element from the operand. The idea here is 4615 /// to split the vector into 16-bit elements, leverage the 16-bit count 4616 /// routine, and then combine the results. 4617 /// 4618 /// Trace for v2i32 (v4i32 similar with Extracted/Extended exchanged): 4619 /// input = [v0 v1 ] (vi: 32-bit elements) 4620 /// Bitcast = [w0 w1 w2 w3 ] (wi: 16-bit elements, v0 = [w0 w1]) 4621 /// Counts16 = [k0 k1 k2 k3 ] (ki: 16-bit elements, bit-count of wi) 4622 /// vrev: N0 = [k1 k0 k3 k2 ] 4623 /// [k0 k1 k2 k3 ] 4624 /// N1 =+[k1 k0 k3 k2 ] 4625 /// [k0 k2 k1 k3 ] 4626 /// N2 =+[k1 k3 k0 k2 ] 4627 /// [k0 k2 k1 k3 ] 4628 /// Extended =+[k1 k3 k0 k2 ] 4629 /// [k0 k2 ] 4630 /// Extracted=+[k1 k3 ] 4631 /// 4632 static SDValue lowerCTPOP32BitElements(SDNode *N, SelectionDAG &DAG) { 4633 EVT VT = N->getValueType(0); 4634 SDLoc DL(N); 4635 4636 EVT VT16Bit = VT.is64BitVector() ? MVT::v4i16 : MVT::v8i16; 4637 4638 SDValue Bitcast = DAG.getNode(ISD::BITCAST, DL, VT16Bit, N->getOperand(0)); 4639 SDValue Counts16 = lowerCTPOP16BitElements(Bitcast.getNode(), DAG); 4640 SDValue N0 = DAG.getNode(ARMISD::VREV32, DL, VT16Bit, Counts16); 4641 SDValue N1 = DAG.getNode(ISD::ADD, DL, VT16Bit, Counts16, N0); 4642 SDValue N2 = DAG.getNode(ARMISD::VUZP, DL, VT16Bit, N1, N1); 4643 4644 if (VT.is64BitVector()) { 4645 SDValue Extended = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::v4i32, N2); 4646 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2i32, Extended, 4647 DAG.getIntPtrConstant(0, DL)); 4648 } else { 4649 SDValue Extracted = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v4i16, N2, 4650 DAG.getIntPtrConstant(0, DL)); 4651 return DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::v4i32, Extracted); 4652 } 4653 } 4654 4655 static SDValue LowerCTPOP(SDNode *N, SelectionDAG &DAG, 4656 const ARMSubtarget *ST) { 4657 EVT VT = N->getValueType(0); 4658 4659 assert(ST->hasNEON() && "Custom ctpop lowering requires NEON."); 4660 assert((VT == MVT::v2i32 || VT == MVT::v4i32 || 4661 VT == MVT::v4i16 || VT == MVT::v8i16) && 4662 "Unexpected type for custom ctpop lowering"); 4663 4664 if (VT.getVectorElementType() == MVT::i32) 4665 return lowerCTPOP32BitElements(N, DAG); 4666 else 4667 return lowerCTPOP16BitElements(N, DAG); 4668 } 4669 4670 static SDValue LowerShift(SDNode *N, SelectionDAG &DAG, 4671 const ARMSubtarget *ST) { 4672 EVT VT = N->getValueType(0); 4673 SDLoc dl(N); 4674 4675 if (!VT.isVector()) 4676 return SDValue(); 4677 4678 // Lower vector shifts on NEON to use VSHL. 4679 assert(ST->hasNEON() && "unexpected vector shift"); 4680 4681 // Left shifts translate directly to the vshiftu intrinsic. 4682 if (N->getOpcode() == ISD::SHL) 4683 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT, 4684 DAG.getConstant(Intrinsic::arm_neon_vshiftu, dl, 4685 MVT::i32), 4686 N->getOperand(0), N->getOperand(1)); 4687 4688 assert((N->getOpcode() == ISD::SRA || 4689 N->getOpcode() == ISD::SRL) && "unexpected vector shift opcode"); 4690 4691 // NEON uses the same intrinsics for both left and right shifts. For 4692 // right shifts, the shift amounts are negative, so negate the vector of 4693 // shift amounts. 4694 EVT ShiftVT = N->getOperand(1).getValueType(); 4695 SDValue NegatedCount = DAG.getNode(ISD::SUB, dl, ShiftVT, 4696 getZeroVector(ShiftVT, DAG, dl), 4697 N->getOperand(1)); 4698 Intrinsic::ID vshiftInt = (N->getOpcode() == ISD::SRA ? 4699 Intrinsic::arm_neon_vshifts : 4700 Intrinsic::arm_neon_vshiftu); 4701 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT, 4702 DAG.getConstant(vshiftInt, dl, MVT::i32), 4703 N->getOperand(0), NegatedCount); 4704 } 4705 4706 static SDValue Expand64BitShift(SDNode *N, SelectionDAG &DAG, 4707 const ARMSubtarget *ST) { 4708 EVT VT = N->getValueType(0); 4709 SDLoc dl(N); 4710 4711 // We can get here for a node like i32 = ISD::SHL i32, i64 4712 if (VT != MVT::i64) 4713 return SDValue(); 4714 4715 assert((N->getOpcode() == ISD::SRL || N->getOpcode() == ISD::SRA) && 4716 "Unknown shift to lower!"); 4717 4718 // We only lower SRA, SRL of 1 here, all others use generic lowering. 4719 if (!isOneConstant(N->getOperand(1))) 4720 return SDValue(); 4721 4722 // If we are in thumb mode, we don't have RRX. 4723 if (ST->isThumb1Only()) return SDValue(); 4724 4725 // Okay, we have a 64-bit SRA or SRL of 1. Lower this to an RRX expr. 4726 SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(0), 4727 DAG.getConstant(0, dl, MVT::i32)); 4728 SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(0), 4729 DAG.getConstant(1, dl, MVT::i32)); 4730 4731 // First, build a SRA_FLAG/SRL_FLAG op, which shifts the top part by one and 4732 // captures the result into a carry flag. 4733 unsigned Opc = N->getOpcode() == ISD::SRL ? ARMISD::SRL_FLAG:ARMISD::SRA_FLAG; 4734 Hi = DAG.getNode(Opc, dl, DAG.getVTList(MVT::i32, MVT::Glue), Hi); 4735 4736 // The low part is an ARMISD::RRX operand, which shifts the carry in. 4737 Lo = DAG.getNode(ARMISD::RRX, dl, MVT::i32, Lo, Hi.getValue(1)); 4738 4739 // Merge the pieces into a single i64 value. 4740 return DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Lo, Hi); 4741 } 4742 4743 static SDValue LowerVSETCC(SDValue Op, SelectionDAG &DAG) { 4744 SDValue TmpOp0, TmpOp1; 4745 bool Invert = false; 4746 bool Swap = false; 4747 unsigned Opc = 0; 4748 4749 SDValue Op0 = Op.getOperand(0); 4750 SDValue Op1 = Op.getOperand(1); 4751 SDValue CC = Op.getOperand(2); 4752 EVT CmpVT = Op0.getValueType().changeVectorElementTypeToInteger(); 4753 EVT VT = Op.getValueType(); 4754 ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get(); 4755 SDLoc dl(Op); 4756 4757 if (CmpVT.getVectorElementType() == MVT::i64) 4758 // 64-bit comparisons are not legal. We've marked SETCC as non-Custom, 4759 // but it's possible that our operands are 64-bit but our result is 32-bit. 4760 // Bail in this case. 4761 return SDValue(); 4762 4763 if (Op1.getValueType().isFloatingPoint()) { 4764 switch (SetCCOpcode) { 4765 default: llvm_unreachable("Illegal FP comparison"); 4766 case ISD::SETUNE: 4767 case ISD::SETNE: Invert = true; // Fallthrough 4768 case ISD::SETOEQ: 4769 case ISD::SETEQ: Opc = ARMISD::VCEQ; break; 4770 case ISD::SETOLT: 4771 case ISD::SETLT: Swap = true; // Fallthrough 4772 case ISD::SETOGT: 4773 case ISD::SETGT: Opc = ARMISD::VCGT; break; 4774 case ISD::SETOLE: 4775 case ISD::SETLE: Swap = true; // Fallthrough 4776 case ISD::SETOGE: 4777 case ISD::SETGE: Opc = ARMISD::VCGE; break; 4778 case ISD::SETUGE: Swap = true; // Fallthrough 4779 case ISD::SETULE: Invert = true; Opc = ARMISD::VCGT; break; 4780 case ISD::SETUGT: Swap = true; // Fallthrough 4781 case ISD::SETULT: Invert = true; Opc = ARMISD::VCGE; break; 4782 case ISD::SETUEQ: Invert = true; // Fallthrough 4783 case ISD::SETONE: 4784 // Expand this to (OLT | OGT). 4785 TmpOp0 = Op0; 4786 TmpOp1 = Op1; 4787 Opc = ISD::OR; 4788 Op0 = DAG.getNode(ARMISD::VCGT, dl, CmpVT, TmpOp1, TmpOp0); 4789 Op1 = DAG.getNode(ARMISD::VCGT, dl, CmpVT, TmpOp0, TmpOp1); 4790 break; 4791 case ISD::SETUO: Invert = true; // Fallthrough 4792 case ISD::SETO: 4793 // Expand this to (OLT | OGE). 4794 TmpOp0 = Op0; 4795 TmpOp1 = Op1; 4796 Opc = ISD::OR; 4797 Op0 = DAG.getNode(ARMISD::VCGT, dl, CmpVT, TmpOp1, TmpOp0); 4798 Op1 = DAG.getNode(ARMISD::VCGE, dl, CmpVT, TmpOp0, TmpOp1); 4799 break; 4800 } 4801 } else { 4802 // Integer comparisons. 4803 switch (SetCCOpcode) { 4804 default: llvm_unreachable("Illegal integer comparison"); 4805 case ISD::SETNE: Invert = true; 4806 case ISD::SETEQ: Opc = ARMISD::VCEQ; break; 4807 case ISD::SETLT: Swap = true; 4808 case ISD::SETGT: Opc = ARMISD::VCGT; break; 4809 case ISD::SETLE: Swap = true; 4810 case ISD::SETGE: Opc = ARMISD::VCGE; break; 4811 case ISD::SETULT: Swap = true; 4812 case ISD::SETUGT: Opc = ARMISD::VCGTU; break; 4813 case ISD::SETULE: Swap = true; 4814 case ISD::SETUGE: Opc = ARMISD::VCGEU; break; 4815 } 4816 4817 // Detect VTST (Vector Test Bits) = icmp ne (and (op0, op1), zero). 4818 if (Opc == ARMISD::VCEQ) { 4819 4820 SDValue AndOp; 4821 if (ISD::isBuildVectorAllZeros(Op1.getNode())) 4822 AndOp = Op0; 4823 else if (ISD::isBuildVectorAllZeros(Op0.getNode())) 4824 AndOp = Op1; 4825 4826 // Ignore bitconvert. 4827 if (AndOp.getNode() && AndOp.getOpcode() == ISD::BITCAST) 4828 AndOp = AndOp.getOperand(0); 4829 4830 if (AndOp.getNode() && AndOp.getOpcode() == ISD::AND) { 4831 Opc = ARMISD::VTST; 4832 Op0 = DAG.getNode(ISD::BITCAST, dl, CmpVT, AndOp.getOperand(0)); 4833 Op1 = DAG.getNode(ISD::BITCAST, dl, CmpVT, AndOp.getOperand(1)); 4834 Invert = !Invert; 4835 } 4836 } 4837 } 4838 4839 if (Swap) 4840 std::swap(Op0, Op1); 4841 4842 // If one of the operands is a constant vector zero, attempt to fold the 4843 // comparison to a specialized compare-against-zero form. 4844 SDValue SingleOp; 4845 if (ISD::isBuildVectorAllZeros(Op1.getNode())) 4846 SingleOp = Op0; 4847 else if (ISD::isBuildVectorAllZeros(Op0.getNode())) { 4848 if (Opc == ARMISD::VCGE) 4849 Opc = ARMISD::VCLEZ; 4850 else if (Opc == ARMISD::VCGT) 4851 Opc = ARMISD::VCLTZ; 4852 SingleOp = Op1; 4853 } 4854 4855 SDValue Result; 4856 if (SingleOp.getNode()) { 4857 switch (Opc) { 4858 case ARMISD::VCEQ: 4859 Result = DAG.getNode(ARMISD::VCEQZ, dl, CmpVT, SingleOp); break; 4860 case ARMISD::VCGE: 4861 Result = DAG.getNode(ARMISD::VCGEZ, dl, CmpVT, SingleOp); break; 4862 case ARMISD::VCLEZ: 4863 Result = DAG.getNode(ARMISD::VCLEZ, dl, CmpVT, SingleOp); break; 4864 case ARMISD::VCGT: 4865 Result = DAG.getNode(ARMISD::VCGTZ, dl, CmpVT, SingleOp); break; 4866 case ARMISD::VCLTZ: 4867 Result = DAG.getNode(ARMISD::VCLTZ, dl, CmpVT, SingleOp); break; 4868 default: 4869 Result = DAG.getNode(Opc, dl, CmpVT, Op0, Op1); 4870 } 4871 } else { 4872 Result = DAG.getNode(Opc, dl, CmpVT, Op0, Op1); 4873 } 4874 4875 Result = DAG.getSExtOrTrunc(Result, dl, VT); 4876 4877 if (Invert) 4878 Result = DAG.getNOT(dl, Result, VT); 4879 4880 return Result; 4881 } 4882 4883 static SDValue LowerSETCCE(SDValue Op, SelectionDAG &DAG) { 4884 SDValue LHS = Op.getOperand(0); 4885 SDValue RHS = Op.getOperand(1); 4886 SDValue Carry = Op.getOperand(2); 4887 SDValue Cond = Op.getOperand(3); 4888 SDLoc DL(Op); 4889 4890 assert(LHS.getSimpleValueType().isInteger() && "SETCCE is integer only."); 4891 4892 assert(Carry.getOpcode() != ISD::CARRY_FALSE); 4893 SDVTList VTs = DAG.getVTList(LHS.getValueType(), MVT::i32); 4894 SDValue Cmp = DAG.getNode(ARMISD::SUBE, DL, VTs, LHS, RHS, Carry); 4895 4896 SDValue FVal = DAG.getConstant(0, DL, MVT::i32); 4897 SDValue TVal = DAG.getConstant(1, DL, MVT::i32); 4898 SDValue ARMcc = DAG.getConstant( 4899 IntCCToARMCC(cast<CondCodeSDNode>(Cond)->get()), DL, MVT::i32); 4900 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32); 4901 SDValue Chain = DAG.getCopyToReg(DAG.getEntryNode(), DL, ARM::CPSR, 4902 Cmp.getValue(1), SDValue()); 4903 return DAG.getNode(ARMISD::CMOV, DL, Op.getValueType(), FVal, TVal, ARMcc, 4904 CCR, Chain.getValue(1)); 4905 } 4906 4907 /// isNEONModifiedImm - Check if the specified splat value corresponds to a 4908 /// valid vector constant for a NEON instruction with a "modified immediate" 4909 /// operand (e.g., VMOV). If so, return the encoded value. 4910 static SDValue isNEONModifiedImm(uint64_t SplatBits, uint64_t SplatUndef, 4911 unsigned SplatBitSize, SelectionDAG &DAG, 4912 SDLoc dl, EVT &VT, bool is128Bits, 4913 NEONModImmType type) { 4914 unsigned OpCmode, Imm; 4915 4916 // SplatBitSize is set to the smallest size that splats the vector, so a 4917 // zero vector will always have SplatBitSize == 8. However, NEON modified 4918 // immediate instructions others than VMOV do not support the 8-bit encoding 4919 // of a zero vector, and the default encoding of zero is supposed to be the 4920 // 32-bit version. 4921 if (SplatBits == 0) 4922 SplatBitSize = 32; 4923 4924 switch (SplatBitSize) { 4925 case 8: 4926 if (type != VMOVModImm) 4927 return SDValue(); 4928 // Any 1-byte value is OK. Op=0, Cmode=1110. 4929 assert((SplatBits & ~0xff) == 0 && "one byte splat value is too big"); 4930 OpCmode = 0xe; 4931 Imm = SplatBits; 4932 VT = is128Bits ? MVT::v16i8 : MVT::v8i8; 4933 break; 4934 4935 case 16: 4936 // NEON's 16-bit VMOV supports splat values where only one byte is nonzero. 4937 VT = is128Bits ? MVT::v8i16 : MVT::v4i16; 4938 if ((SplatBits & ~0xff) == 0) { 4939 // Value = 0x00nn: Op=x, Cmode=100x. 4940 OpCmode = 0x8; 4941 Imm = SplatBits; 4942 break; 4943 } 4944 if ((SplatBits & ~0xff00) == 0) { 4945 // Value = 0xnn00: Op=x, Cmode=101x. 4946 OpCmode = 0xa; 4947 Imm = SplatBits >> 8; 4948 break; 4949 } 4950 return SDValue(); 4951 4952 case 32: 4953 // NEON's 32-bit VMOV supports splat values where: 4954 // * only one byte is nonzero, or 4955 // * the least significant byte is 0xff and the second byte is nonzero, or 4956 // * the least significant 2 bytes are 0xff and the third is nonzero. 4957 VT = is128Bits ? MVT::v4i32 : MVT::v2i32; 4958 if ((SplatBits & ~0xff) == 0) { 4959 // Value = 0x000000nn: Op=x, Cmode=000x. 4960 OpCmode = 0; 4961 Imm = SplatBits; 4962 break; 4963 } 4964 if ((SplatBits & ~0xff00) == 0) { 4965 // Value = 0x0000nn00: Op=x, Cmode=001x. 4966 OpCmode = 0x2; 4967 Imm = SplatBits >> 8; 4968 break; 4969 } 4970 if ((SplatBits & ~0xff0000) == 0) { 4971 // Value = 0x00nn0000: Op=x, Cmode=010x. 4972 OpCmode = 0x4; 4973 Imm = SplatBits >> 16; 4974 break; 4975 } 4976 if ((SplatBits & ~0xff000000) == 0) { 4977 // Value = 0xnn000000: Op=x, Cmode=011x. 4978 OpCmode = 0x6; 4979 Imm = SplatBits >> 24; 4980 break; 4981 } 4982 4983 // cmode == 0b1100 and cmode == 0b1101 are not supported for VORR or VBIC 4984 if (type == OtherModImm) return SDValue(); 4985 4986 if ((SplatBits & ~0xffff) == 0 && 4987 ((SplatBits | SplatUndef) & 0xff) == 0xff) { 4988 // Value = 0x0000nnff: Op=x, Cmode=1100. 4989 OpCmode = 0xc; 4990 Imm = SplatBits >> 8; 4991 break; 4992 } 4993 4994 if ((SplatBits & ~0xffffff) == 0 && 4995 ((SplatBits | SplatUndef) & 0xffff) == 0xffff) { 4996 // Value = 0x00nnffff: Op=x, Cmode=1101. 4997 OpCmode = 0xd; 4998 Imm = SplatBits >> 16; 4999 break; 5000 } 5001 5002 // Note: there are a few 32-bit splat values (specifically: 00ffff00, 5003 // ff000000, ff0000ff, and ffff00ff) that are valid for VMOV.I64 but not 5004 // VMOV.I32. A (very) minor optimization would be to replicate the value 5005 // and fall through here to test for a valid 64-bit splat. But, then the 5006 // caller would also need to check and handle the change in size. 5007 return SDValue(); 5008 5009 case 64: { 5010 if (type != VMOVModImm) 5011 return SDValue(); 5012 // NEON has a 64-bit VMOV splat where each byte is either 0 or 0xff. 5013 uint64_t BitMask = 0xff; 5014 uint64_t Val = 0; 5015 unsigned ImmMask = 1; 5016 Imm = 0; 5017 for (int ByteNum = 0; ByteNum < 8; ++ByteNum) { 5018 if (((SplatBits | SplatUndef) & BitMask) == BitMask) { 5019 Val |= BitMask; 5020 Imm |= ImmMask; 5021 } else if ((SplatBits & BitMask) != 0) { 5022 return SDValue(); 5023 } 5024 BitMask <<= 8; 5025 ImmMask <<= 1; 5026 } 5027 5028 if (DAG.getDataLayout().isBigEndian()) 5029 // swap higher and lower 32 bit word 5030 Imm = ((Imm & 0xf) << 4) | ((Imm & 0xf0) >> 4); 5031 5032 // Op=1, Cmode=1110. 5033 OpCmode = 0x1e; 5034 VT = is128Bits ? MVT::v2i64 : MVT::v1i64; 5035 break; 5036 } 5037 5038 default: 5039 llvm_unreachable("unexpected size for isNEONModifiedImm"); 5040 } 5041 5042 unsigned EncodedVal = ARM_AM::createNEONModImm(OpCmode, Imm); 5043 return DAG.getTargetConstant(EncodedVal, dl, MVT::i32); 5044 } 5045 5046 SDValue ARMTargetLowering::LowerConstantFP(SDValue Op, SelectionDAG &DAG, 5047 const ARMSubtarget *ST) const { 5048 if (!ST->hasVFP3()) 5049 return SDValue(); 5050 5051 bool IsDouble = Op.getValueType() == MVT::f64; 5052 ConstantFPSDNode *CFP = cast<ConstantFPSDNode>(Op); 5053 5054 // Use the default (constant pool) lowering for double constants when we have 5055 // an SP-only FPU 5056 if (IsDouble && Subtarget->isFPOnlySP()) 5057 return SDValue(); 5058 5059 // Try splatting with a VMOV.f32... 5060 APFloat FPVal = CFP->getValueAPF(); 5061 int ImmVal = IsDouble ? ARM_AM::getFP64Imm(FPVal) : ARM_AM::getFP32Imm(FPVal); 5062 5063 if (ImmVal != -1) { 5064 if (IsDouble || !ST->useNEONForSinglePrecisionFP()) { 5065 // We have code in place to select a valid ConstantFP already, no need to 5066 // do any mangling. 5067 return Op; 5068 } 5069 5070 // It's a float and we are trying to use NEON operations where 5071 // possible. Lower it to a splat followed by an extract. 5072 SDLoc DL(Op); 5073 SDValue NewVal = DAG.getTargetConstant(ImmVal, DL, MVT::i32); 5074 SDValue VecConstant = DAG.getNode(ARMISD::VMOVFPIMM, DL, MVT::v2f32, 5075 NewVal); 5076 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32, VecConstant, 5077 DAG.getConstant(0, DL, MVT::i32)); 5078 } 5079 5080 // The rest of our options are NEON only, make sure that's allowed before 5081 // proceeding.. 5082 if (!ST->hasNEON() || (!IsDouble && !ST->useNEONForSinglePrecisionFP())) 5083 return SDValue(); 5084 5085 EVT VMovVT; 5086 uint64_t iVal = FPVal.bitcastToAPInt().getZExtValue(); 5087 5088 // It wouldn't really be worth bothering for doubles except for one very 5089 // important value, which does happen to match: 0.0. So make sure we don't do 5090 // anything stupid. 5091 if (IsDouble && (iVal & 0xffffffff) != (iVal >> 32)) 5092 return SDValue(); 5093 5094 // Try a VMOV.i32 (FIXME: i8, i16, or i64 could work too). 5095 SDValue NewVal = isNEONModifiedImm(iVal & 0xffffffffU, 0, 32, DAG, SDLoc(Op), 5096 VMovVT, false, VMOVModImm); 5097 if (NewVal != SDValue()) { 5098 SDLoc DL(Op); 5099 SDValue VecConstant = DAG.getNode(ARMISD::VMOVIMM, DL, VMovVT, 5100 NewVal); 5101 if (IsDouble) 5102 return DAG.getNode(ISD::BITCAST, DL, MVT::f64, VecConstant); 5103 5104 // It's a float: cast and extract a vector element. 5105 SDValue VecFConstant = DAG.getNode(ISD::BITCAST, DL, MVT::v2f32, 5106 VecConstant); 5107 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32, VecFConstant, 5108 DAG.getConstant(0, DL, MVT::i32)); 5109 } 5110 5111 // Finally, try a VMVN.i32 5112 NewVal = isNEONModifiedImm(~iVal & 0xffffffffU, 0, 32, DAG, SDLoc(Op), VMovVT, 5113 false, VMVNModImm); 5114 if (NewVal != SDValue()) { 5115 SDLoc DL(Op); 5116 SDValue VecConstant = DAG.getNode(ARMISD::VMVNIMM, DL, VMovVT, NewVal); 5117 5118 if (IsDouble) 5119 return DAG.getNode(ISD::BITCAST, DL, MVT::f64, VecConstant); 5120 5121 // It's a float: cast and extract a vector element. 5122 SDValue VecFConstant = DAG.getNode(ISD::BITCAST, DL, MVT::v2f32, 5123 VecConstant); 5124 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32, VecFConstant, 5125 DAG.getConstant(0, DL, MVT::i32)); 5126 } 5127 5128 return SDValue(); 5129 } 5130 5131 // check if an VEXT instruction can handle the shuffle mask when the 5132 // vector sources of the shuffle are the same. 5133 static bool isSingletonVEXTMask(ArrayRef<int> M, EVT VT, unsigned &Imm) { 5134 unsigned NumElts = VT.getVectorNumElements(); 5135 5136 // Assume that the first shuffle index is not UNDEF. Fail if it is. 5137 if (M[0] < 0) 5138 return false; 5139 5140 Imm = M[0]; 5141 5142 // If this is a VEXT shuffle, the immediate value is the index of the first 5143 // element. The other shuffle indices must be the successive elements after 5144 // the first one. 5145 unsigned ExpectedElt = Imm; 5146 for (unsigned i = 1; i < NumElts; ++i) { 5147 // Increment the expected index. If it wraps around, just follow it 5148 // back to index zero and keep going. 5149 ++ExpectedElt; 5150 if (ExpectedElt == NumElts) 5151 ExpectedElt = 0; 5152 5153 if (M[i] < 0) continue; // ignore UNDEF indices 5154 if (ExpectedElt != static_cast<unsigned>(M[i])) 5155 return false; 5156 } 5157 5158 return true; 5159 } 5160 5161 5162 static bool isVEXTMask(ArrayRef<int> M, EVT VT, 5163 bool &ReverseVEXT, unsigned &Imm) { 5164 unsigned NumElts = VT.getVectorNumElements(); 5165 ReverseVEXT = false; 5166 5167 // Assume that the first shuffle index is not UNDEF. Fail if it is. 5168 if (M[0] < 0) 5169 return false; 5170 5171 Imm = M[0]; 5172 5173 // If this is a VEXT shuffle, the immediate value is the index of the first 5174 // element. The other shuffle indices must be the successive elements after 5175 // the first one. 5176 unsigned ExpectedElt = Imm; 5177 for (unsigned i = 1; i < NumElts; ++i) { 5178 // Increment the expected index. If it wraps around, it may still be 5179 // a VEXT but the source vectors must be swapped. 5180 ExpectedElt += 1; 5181 if (ExpectedElt == NumElts * 2) { 5182 ExpectedElt = 0; 5183 ReverseVEXT = true; 5184 } 5185 5186 if (M[i] < 0) continue; // ignore UNDEF indices 5187 if (ExpectedElt != static_cast<unsigned>(M[i])) 5188 return false; 5189 } 5190 5191 // Adjust the index value if the source operands will be swapped. 5192 if (ReverseVEXT) 5193 Imm -= NumElts; 5194 5195 return true; 5196 } 5197 5198 /// isVREVMask - Check if a vector shuffle corresponds to a VREV 5199 /// instruction with the specified blocksize. (The order of the elements 5200 /// within each block of the vector is reversed.) 5201 static bool isVREVMask(ArrayRef<int> M, EVT VT, unsigned BlockSize) { 5202 assert((BlockSize==16 || BlockSize==32 || BlockSize==64) && 5203 "Only possible block sizes for VREV are: 16, 32, 64"); 5204 5205 unsigned EltSz = VT.getVectorElementType().getSizeInBits(); 5206 if (EltSz == 64) 5207 return false; 5208 5209 unsigned NumElts = VT.getVectorNumElements(); 5210 unsigned BlockElts = M[0] + 1; 5211 // If the first shuffle index is UNDEF, be optimistic. 5212 if (M[0] < 0) 5213 BlockElts = BlockSize / EltSz; 5214 5215 if (BlockSize <= EltSz || BlockSize != BlockElts * EltSz) 5216 return false; 5217 5218 for (unsigned i = 0; i < NumElts; ++i) { 5219 if (M[i] < 0) continue; // ignore UNDEF indices 5220 if ((unsigned) M[i] != (i - i%BlockElts) + (BlockElts - 1 - i%BlockElts)) 5221 return false; 5222 } 5223 5224 return true; 5225 } 5226 5227 static bool isVTBLMask(ArrayRef<int> M, EVT VT) { 5228 // We can handle <8 x i8> vector shuffles. If the index in the mask is out of 5229 // range, then 0 is placed into the resulting vector. So pretty much any mask 5230 // of 8 elements can work here. 5231 return VT == MVT::v8i8 && M.size() == 8; 5232 } 5233 5234 // Checks whether the shuffle mask represents a vector transpose (VTRN) by 5235 // checking that pairs of elements in the shuffle mask represent the same index 5236 // in each vector, incrementing the expected index by 2 at each step. 5237 // e.g. For v1,v2 of type v4i32 a valid shuffle mask is: [0, 4, 2, 6] 5238 // v1={a,b,c,d} => x=shufflevector v1, v2 shufflemask => x={a,e,c,g} 5239 // v2={e,f,g,h} 5240 // WhichResult gives the offset for each element in the mask based on which 5241 // of the two results it belongs to. 5242 // 5243 // The transpose can be represented either as: 5244 // result1 = shufflevector v1, v2, result1_shuffle_mask 5245 // result2 = shufflevector v1, v2, result2_shuffle_mask 5246 // where v1/v2 and the shuffle masks have the same number of elements 5247 // (here WhichResult (see below) indicates which result is being checked) 5248 // 5249 // or as: 5250 // results = shufflevector v1, v2, shuffle_mask 5251 // where both results are returned in one vector and the shuffle mask has twice 5252 // as many elements as v1/v2 (here WhichResult will always be 0 if true) here we 5253 // want to check the low half and high half of the shuffle mask as if it were 5254 // the other case 5255 static bool isVTRNMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) { 5256 unsigned EltSz = VT.getVectorElementType().getSizeInBits(); 5257 if (EltSz == 64) 5258 return false; 5259 5260 unsigned NumElts = VT.getVectorNumElements(); 5261 if (M.size() != NumElts && M.size() != NumElts*2) 5262 return false; 5263 5264 // If the mask is twice as long as the input vector then we need to check the 5265 // upper and lower parts of the mask with a matching value for WhichResult 5266 // FIXME: A mask with only even values will be rejected in case the first 5267 // element is undefined, e.g. [-1, 4, 2, 6] will be rejected, because only 5268 // M[0] is used to determine WhichResult 5269 for (unsigned i = 0; i < M.size(); i += NumElts) { 5270 if (M.size() == NumElts * 2) 5271 WhichResult = i / NumElts; 5272 else 5273 WhichResult = M[i] == 0 ? 0 : 1; 5274 for (unsigned j = 0; j < NumElts; j += 2) { 5275 if ((M[i+j] >= 0 && (unsigned) M[i+j] != j + WhichResult) || 5276 (M[i+j+1] >= 0 && (unsigned) M[i+j+1] != j + NumElts + WhichResult)) 5277 return false; 5278 } 5279 } 5280 5281 if (M.size() == NumElts*2) 5282 WhichResult = 0; 5283 5284 return true; 5285 } 5286 5287 /// isVTRN_v_undef_Mask - Special case of isVTRNMask for canonical form of 5288 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef". 5289 /// Mask is e.g., <0, 0, 2, 2> instead of <0, 4, 2, 6>. 5290 static bool isVTRN_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult){ 5291 unsigned EltSz = VT.getVectorElementType().getSizeInBits(); 5292 if (EltSz == 64) 5293 return false; 5294 5295 unsigned NumElts = VT.getVectorNumElements(); 5296 if (M.size() != NumElts && M.size() != NumElts*2) 5297 return false; 5298 5299 for (unsigned i = 0; i < M.size(); i += NumElts) { 5300 if (M.size() == NumElts * 2) 5301 WhichResult = i / NumElts; 5302 else 5303 WhichResult = M[i] == 0 ? 0 : 1; 5304 for (unsigned j = 0; j < NumElts; j += 2) { 5305 if ((M[i+j] >= 0 && (unsigned) M[i+j] != j + WhichResult) || 5306 (M[i+j+1] >= 0 && (unsigned) M[i+j+1] != j + WhichResult)) 5307 return false; 5308 } 5309 } 5310 5311 if (M.size() == NumElts*2) 5312 WhichResult = 0; 5313 5314 return true; 5315 } 5316 5317 // Checks whether the shuffle mask represents a vector unzip (VUZP) by checking 5318 // that the mask elements are either all even and in steps of size 2 or all odd 5319 // and in steps of size 2. 5320 // e.g. For v1,v2 of type v4i32 a valid shuffle mask is: [0, 2, 4, 6] 5321 // v1={a,b,c,d} => x=shufflevector v1, v2 shufflemask => x={a,c,e,g} 5322 // v2={e,f,g,h} 5323 // Requires similar checks to that of isVTRNMask with 5324 // respect the how results are returned. 5325 static bool isVUZPMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) { 5326 unsigned EltSz = VT.getVectorElementType().getSizeInBits(); 5327 if (EltSz == 64) 5328 return false; 5329 5330 unsigned NumElts = VT.getVectorNumElements(); 5331 if (M.size() != NumElts && M.size() != NumElts*2) 5332 return false; 5333 5334 for (unsigned i = 0; i < M.size(); i += NumElts) { 5335 WhichResult = M[i] == 0 ? 0 : 1; 5336 for (unsigned j = 0; j < NumElts; ++j) { 5337 if (M[i+j] >= 0 && (unsigned) M[i+j] != 2 * j + WhichResult) 5338 return false; 5339 } 5340 } 5341 5342 if (M.size() == NumElts*2) 5343 WhichResult = 0; 5344 5345 // VUZP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32. 5346 if (VT.is64BitVector() && EltSz == 32) 5347 return false; 5348 5349 return true; 5350 } 5351 5352 /// isVUZP_v_undef_Mask - Special case of isVUZPMask for canonical form of 5353 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef". 5354 /// Mask is e.g., <0, 2, 0, 2> instead of <0, 2, 4, 6>, 5355 static bool isVUZP_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult){ 5356 unsigned EltSz = VT.getVectorElementType().getSizeInBits(); 5357 if (EltSz == 64) 5358 return false; 5359 5360 unsigned NumElts = VT.getVectorNumElements(); 5361 if (M.size() != NumElts && M.size() != NumElts*2) 5362 return false; 5363 5364 unsigned Half = NumElts / 2; 5365 for (unsigned i = 0; i < M.size(); i += NumElts) { 5366 WhichResult = M[i] == 0 ? 0 : 1; 5367 for (unsigned j = 0; j < NumElts; j += Half) { 5368 unsigned Idx = WhichResult; 5369 for (unsigned k = 0; k < Half; ++k) { 5370 int MIdx = M[i + j + k]; 5371 if (MIdx >= 0 && (unsigned) MIdx != Idx) 5372 return false; 5373 Idx += 2; 5374 } 5375 } 5376 } 5377 5378 if (M.size() == NumElts*2) 5379 WhichResult = 0; 5380 5381 // VUZP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32. 5382 if (VT.is64BitVector() && EltSz == 32) 5383 return false; 5384 5385 return true; 5386 } 5387 5388 // Checks whether the shuffle mask represents a vector zip (VZIP) by checking 5389 // that pairs of elements of the shufflemask represent the same index in each 5390 // vector incrementing sequentially through the vectors. 5391 // e.g. For v1,v2 of type v4i32 a valid shuffle mask is: [0, 4, 1, 5] 5392 // v1={a,b,c,d} => x=shufflevector v1, v2 shufflemask => x={a,e,b,f} 5393 // v2={e,f,g,h} 5394 // Requires similar checks to that of isVTRNMask with respect the how results 5395 // are returned. 5396 static bool isVZIPMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) { 5397 unsigned EltSz = VT.getVectorElementType().getSizeInBits(); 5398 if (EltSz == 64) 5399 return false; 5400 5401 unsigned NumElts = VT.getVectorNumElements(); 5402 if (M.size() != NumElts && M.size() != NumElts*2) 5403 return false; 5404 5405 for (unsigned i = 0; i < M.size(); i += NumElts) { 5406 WhichResult = M[i] == 0 ? 0 : 1; 5407 unsigned Idx = WhichResult * NumElts / 2; 5408 for (unsigned j = 0; j < NumElts; j += 2) { 5409 if ((M[i+j] >= 0 && (unsigned) M[i+j] != Idx) || 5410 (M[i+j+1] >= 0 && (unsigned) M[i+j+1] != Idx + NumElts)) 5411 return false; 5412 Idx += 1; 5413 } 5414 } 5415 5416 if (M.size() == NumElts*2) 5417 WhichResult = 0; 5418 5419 // VZIP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32. 5420 if (VT.is64BitVector() && EltSz == 32) 5421 return false; 5422 5423 return true; 5424 } 5425 5426 /// isVZIP_v_undef_Mask - Special case of isVZIPMask for canonical form of 5427 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef". 5428 /// Mask is e.g., <0, 0, 1, 1> instead of <0, 4, 1, 5>. 5429 static bool isVZIP_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult){ 5430 unsigned EltSz = VT.getVectorElementType().getSizeInBits(); 5431 if (EltSz == 64) 5432 return false; 5433 5434 unsigned NumElts = VT.getVectorNumElements(); 5435 if (M.size() != NumElts && M.size() != NumElts*2) 5436 return false; 5437 5438 for (unsigned i = 0; i < M.size(); i += NumElts) { 5439 WhichResult = M[i] == 0 ? 0 : 1; 5440 unsigned Idx = WhichResult * NumElts / 2; 5441 for (unsigned j = 0; j < NumElts; j += 2) { 5442 if ((M[i+j] >= 0 && (unsigned) M[i+j] != Idx) || 5443 (M[i+j+1] >= 0 && (unsigned) M[i+j+1] != Idx)) 5444 return false; 5445 Idx += 1; 5446 } 5447 } 5448 5449 if (M.size() == NumElts*2) 5450 WhichResult = 0; 5451 5452 // VZIP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32. 5453 if (VT.is64BitVector() && EltSz == 32) 5454 return false; 5455 5456 return true; 5457 } 5458 5459 /// Check if \p ShuffleMask is a NEON two-result shuffle (VZIP, VUZP, VTRN), 5460 /// and return the corresponding ARMISD opcode if it is, or 0 if it isn't. 5461 static unsigned isNEONTwoResultShuffleMask(ArrayRef<int> ShuffleMask, EVT VT, 5462 unsigned &WhichResult, 5463 bool &isV_UNDEF) { 5464 isV_UNDEF = false; 5465 if (isVTRNMask(ShuffleMask, VT, WhichResult)) 5466 return ARMISD::VTRN; 5467 if (isVUZPMask(ShuffleMask, VT, WhichResult)) 5468 return ARMISD::VUZP; 5469 if (isVZIPMask(ShuffleMask, VT, WhichResult)) 5470 return ARMISD::VZIP; 5471 5472 isV_UNDEF = true; 5473 if (isVTRN_v_undef_Mask(ShuffleMask, VT, WhichResult)) 5474 return ARMISD::VTRN; 5475 if (isVUZP_v_undef_Mask(ShuffleMask, VT, WhichResult)) 5476 return ARMISD::VUZP; 5477 if (isVZIP_v_undef_Mask(ShuffleMask, VT, WhichResult)) 5478 return ARMISD::VZIP; 5479 5480 return 0; 5481 } 5482 5483 /// \return true if this is a reverse operation on an vector. 5484 static bool isReverseMask(ArrayRef<int> M, EVT VT) { 5485 unsigned NumElts = VT.getVectorNumElements(); 5486 // Make sure the mask has the right size. 5487 if (NumElts != M.size()) 5488 return false; 5489 5490 // Look for <15, ..., 3, -1, 1, 0>. 5491 for (unsigned i = 0; i != NumElts; ++i) 5492 if (M[i] >= 0 && M[i] != (int) (NumElts - 1 - i)) 5493 return false; 5494 5495 return true; 5496 } 5497 5498 // If N is an integer constant that can be moved into a register in one 5499 // instruction, return an SDValue of such a constant (will become a MOV 5500 // instruction). Otherwise return null. 5501 static SDValue IsSingleInstrConstant(SDValue N, SelectionDAG &DAG, 5502 const ARMSubtarget *ST, SDLoc dl) { 5503 uint64_t Val; 5504 if (!isa<ConstantSDNode>(N)) 5505 return SDValue(); 5506 Val = cast<ConstantSDNode>(N)->getZExtValue(); 5507 5508 if (ST->isThumb1Only()) { 5509 if (Val <= 255 || ~Val <= 255) 5510 return DAG.getConstant(Val, dl, MVT::i32); 5511 } else { 5512 if (ARM_AM::getSOImmVal(Val) != -1 || ARM_AM::getSOImmVal(~Val) != -1) 5513 return DAG.getConstant(Val, dl, MVT::i32); 5514 } 5515 return SDValue(); 5516 } 5517 5518 // If this is a case we can't handle, return null and let the default 5519 // expansion code take care of it. 5520 SDValue ARMTargetLowering::LowerBUILD_VECTOR(SDValue Op, SelectionDAG &DAG, 5521 const ARMSubtarget *ST) const { 5522 BuildVectorSDNode *BVN = cast<BuildVectorSDNode>(Op.getNode()); 5523 SDLoc dl(Op); 5524 EVT VT = Op.getValueType(); 5525 5526 APInt SplatBits, SplatUndef; 5527 unsigned SplatBitSize; 5528 bool HasAnyUndefs; 5529 if (BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs)) { 5530 if (SplatBitSize <= 64) { 5531 // Check if an immediate VMOV works. 5532 EVT VmovVT; 5533 SDValue Val = isNEONModifiedImm(SplatBits.getZExtValue(), 5534 SplatUndef.getZExtValue(), SplatBitSize, 5535 DAG, dl, VmovVT, VT.is128BitVector(), 5536 VMOVModImm); 5537 if (Val.getNode()) { 5538 SDValue Vmov = DAG.getNode(ARMISD::VMOVIMM, dl, VmovVT, Val); 5539 return DAG.getNode(ISD::BITCAST, dl, VT, Vmov); 5540 } 5541 5542 // Try an immediate VMVN. 5543 uint64_t NegatedImm = (~SplatBits).getZExtValue(); 5544 Val = isNEONModifiedImm(NegatedImm, 5545 SplatUndef.getZExtValue(), SplatBitSize, 5546 DAG, dl, VmovVT, VT.is128BitVector(), 5547 VMVNModImm); 5548 if (Val.getNode()) { 5549 SDValue Vmov = DAG.getNode(ARMISD::VMVNIMM, dl, VmovVT, Val); 5550 return DAG.getNode(ISD::BITCAST, dl, VT, Vmov); 5551 } 5552 5553 // Use vmov.f32 to materialize other v2f32 and v4f32 splats. 5554 if ((VT == MVT::v2f32 || VT == MVT::v4f32) && SplatBitSize == 32) { 5555 int ImmVal = ARM_AM::getFP32Imm(SplatBits); 5556 if (ImmVal != -1) { 5557 SDValue Val = DAG.getTargetConstant(ImmVal, dl, MVT::i32); 5558 return DAG.getNode(ARMISD::VMOVFPIMM, dl, VT, Val); 5559 } 5560 } 5561 } 5562 } 5563 5564 // Scan through the operands to see if only one value is used. 5565 // 5566 // As an optimisation, even if more than one value is used it may be more 5567 // profitable to splat with one value then change some lanes. 5568 // 5569 // Heuristically we decide to do this if the vector has a "dominant" value, 5570 // defined as splatted to more than half of the lanes. 5571 unsigned NumElts = VT.getVectorNumElements(); 5572 bool isOnlyLowElement = true; 5573 bool usesOnlyOneValue = true; 5574 bool hasDominantValue = false; 5575 bool isConstant = true; 5576 5577 // Map of the number of times a particular SDValue appears in the 5578 // element list. 5579 DenseMap<SDValue, unsigned> ValueCounts; 5580 SDValue Value; 5581 for (unsigned i = 0; i < NumElts; ++i) { 5582 SDValue V = Op.getOperand(i); 5583 if (V.isUndef()) 5584 continue; 5585 if (i > 0) 5586 isOnlyLowElement = false; 5587 if (!isa<ConstantFPSDNode>(V) && !isa<ConstantSDNode>(V)) 5588 isConstant = false; 5589 5590 ValueCounts.insert(std::make_pair(V, 0)); 5591 unsigned &Count = ValueCounts[V]; 5592 5593 // Is this value dominant? (takes up more than half of the lanes) 5594 if (++Count > (NumElts / 2)) { 5595 hasDominantValue = true; 5596 Value = V; 5597 } 5598 } 5599 if (ValueCounts.size() != 1) 5600 usesOnlyOneValue = false; 5601 if (!Value.getNode() && ValueCounts.size() > 0) 5602 Value = ValueCounts.begin()->first; 5603 5604 if (ValueCounts.size() == 0) 5605 return DAG.getUNDEF(VT); 5606 5607 // Loads are better lowered with insert_vector_elt/ARMISD::BUILD_VECTOR. 5608 // Keep going if we are hitting this case. 5609 if (isOnlyLowElement && !ISD::isNormalLoad(Value.getNode())) 5610 return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Value); 5611 5612 unsigned EltSize = VT.getVectorElementType().getSizeInBits(); 5613 5614 // Use VDUP for non-constant splats. For f32 constant splats, reduce to 5615 // i32 and try again. 5616 if (hasDominantValue && EltSize <= 32) { 5617 if (!isConstant) { 5618 SDValue N; 5619 5620 // If we are VDUPing a value that comes directly from a vector, that will 5621 // cause an unnecessary move to and from a GPR, where instead we could 5622 // just use VDUPLANE. We can only do this if the lane being extracted 5623 // is at a constant index, as the VDUP from lane instructions only have 5624 // constant-index forms. 5625 ConstantSDNode *constIndex; 5626 if (Value->getOpcode() == ISD::EXTRACT_VECTOR_ELT && 5627 (constIndex = dyn_cast<ConstantSDNode>(Value->getOperand(1)))) { 5628 // We need to create a new undef vector to use for the VDUPLANE if the 5629 // size of the vector from which we get the value is different than the 5630 // size of the vector that we need to create. We will insert the element 5631 // such that the register coalescer will remove unnecessary copies. 5632 if (VT != Value->getOperand(0).getValueType()) { 5633 unsigned index = constIndex->getAPIntValue().getLimitedValue() % 5634 VT.getVectorNumElements(); 5635 N = DAG.getNode(ARMISD::VDUPLANE, dl, VT, 5636 DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, DAG.getUNDEF(VT), 5637 Value, DAG.getConstant(index, dl, MVT::i32)), 5638 DAG.getConstant(index, dl, MVT::i32)); 5639 } else 5640 N = DAG.getNode(ARMISD::VDUPLANE, dl, VT, 5641 Value->getOperand(0), Value->getOperand(1)); 5642 } else 5643 N = DAG.getNode(ARMISD::VDUP, dl, VT, Value); 5644 5645 if (!usesOnlyOneValue) { 5646 // The dominant value was splatted as 'N', but we now have to insert 5647 // all differing elements. 5648 for (unsigned I = 0; I < NumElts; ++I) { 5649 if (Op.getOperand(I) == Value) 5650 continue; 5651 SmallVector<SDValue, 3> Ops; 5652 Ops.push_back(N); 5653 Ops.push_back(Op.getOperand(I)); 5654 Ops.push_back(DAG.getConstant(I, dl, MVT::i32)); 5655 N = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Ops); 5656 } 5657 } 5658 return N; 5659 } 5660 if (VT.getVectorElementType().isFloatingPoint()) { 5661 SmallVector<SDValue, 8> Ops; 5662 for (unsigned i = 0; i < NumElts; ++i) 5663 Ops.push_back(DAG.getNode(ISD::BITCAST, dl, MVT::i32, 5664 Op.getOperand(i))); 5665 EVT VecVT = EVT::getVectorVT(*DAG.getContext(), MVT::i32, NumElts); 5666 SDValue Val = DAG.getBuildVector(VecVT, dl, Ops); 5667 Val = LowerBUILD_VECTOR(Val, DAG, ST); 5668 if (Val.getNode()) 5669 return DAG.getNode(ISD::BITCAST, dl, VT, Val); 5670 } 5671 if (usesOnlyOneValue) { 5672 SDValue Val = IsSingleInstrConstant(Value, DAG, ST, dl); 5673 if (isConstant && Val.getNode()) 5674 return DAG.getNode(ARMISD::VDUP, dl, VT, Val); 5675 } 5676 } 5677 5678 // If all elements are constants and the case above didn't get hit, fall back 5679 // to the default expansion, which will generate a load from the constant 5680 // pool. 5681 if (isConstant) 5682 return SDValue(); 5683 5684 // Empirical tests suggest this is rarely worth it for vectors of length <= 2. 5685 if (NumElts >= 4) { 5686 SDValue shuffle = ReconstructShuffle(Op, DAG); 5687 if (shuffle != SDValue()) 5688 return shuffle; 5689 } 5690 5691 // Vectors with 32- or 64-bit elements can be built by directly assigning 5692 // the subregisters. Lower it to an ARMISD::BUILD_VECTOR so the operands 5693 // will be legalized. 5694 if (EltSize >= 32) { 5695 // Do the expansion with floating-point types, since that is what the VFP 5696 // registers are defined to use, and since i64 is not legal. 5697 EVT EltVT = EVT::getFloatingPointVT(EltSize); 5698 EVT VecVT = EVT::getVectorVT(*DAG.getContext(), EltVT, NumElts); 5699 SmallVector<SDValue, 8> Ops; 5700 for (unsigned i = 0; i < NumElts; ++i) 5701 Ops.push_back(DAG.getNode(ISD::BITCAST, dl, EltVT, Op.getOperand(i))); 5702 SDValue Val = DAG.getNode(ARMISD::BUILD_VECTOR, dl, VecVT, Ops); 5703 return DAG.getNode(ISD::BITCAST, dl, VT, Val); 5704 } 5705 5706 // If all else fails, just use a sequence of INSERT_VECTOR_ELT when we 5707 // know the default expansion would otherwise fall back on something even 5708 // worse. For a vector with one or two non-undef values, that's 5709 // scalar_to_vector for the elements followed by a shuffle (provided the 5710 // shuffle is valid for the target) and materialization element by element 5711 // on the stack followed by a load for everything else. 5712 if (!isConstant && !usesOnlyOneValue) { 5713 SDValue Vec = DAG.getUNDEF(VT); 5714 for (unsigned i = 0 ; i < NumElts; ++i) { 5715 SDValue V = Op.getOperand(i); 5716 if (V.isUndef()) 5717 continue; 5718 SDValue LaneIdx = DAG.getConstant(i, dl, MVT::i32); 5719 Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Vec, V, LaneIdx); 5720 } 5721 return Vec; 5722 } 5723 5724 return SDValue(); 5725 } 5726 5727 // Gather data to see if the operation can be modelled as a 5728 // shuffle in combination with VEXTs. 5729 SDValue ARMTargetLowering::ReconstructShuffle(SDValue Op, 5730 SelectionDAG &DAG) const { 5731 assert(Op.getOpcode() == ISD::BUILD_VECTOR && "Unknown opcode!"); 5732 SDLoc dl(Op); 5733 EVT VT = Op.getValueType(); 5734 unsigned NumElts = VT.getVectorNumElements(); 5735 5736 struct ShuffleSourceInfo { 5737 SDValue Vec; 5738 unsigned MinElt; 5739 unsigned MaxElt; 5740 5741 // We may insert some combination of BITCASTs and VEXT nodes to force Vec to 5742 // be compatible with the shuffle we intend to construct. As a result 5743 // ShuffleVec will be some sliding window into the original Vec. 5744 SDValue ShuffleVec; 5745 5746 // Code should guarantee that element i in Vec starts at element "WindowBase 5747 // + i * WindowScale in ShuffleVec". 5748 int WindowBase; 5749 int WindowScale; 5750 5751 bool operator ==(SDValue OtherVec) { return Vec == OtherVec; } 5752 ShuffleSourceInfo(SDValue Vec) 5753 : Vec(Vec), MinElt(UINT_MAX), MaxElt(0), ShuffleVec(Vec), WindowBase(0), 5754 WindowScale(1) {} 5755 }; 5756 5757 // First gather all vectors used as an immediate source for this BUILD_VECTOR 5758 // node. 5759 SmallVector<ShuffleSourceInfo, 2> Sources; 5760 for (unsigned i = 0; i < NumElts; ++i) { 5761 SDValue V = Op.getOperand(i); 5762 if (V.isUndef()) 5763 continue; 5764 else if (V.getOpcode() != ISD::EXTRACT_VECTOR_ELT) { 5765 // A shuffle can only come from building a vector from various 5766 // elements of other vectors. 5767 return SDValue(); 5768 } else if (!isa<ConstantSDNode>(V.getOperand(1))) { 5769 // Furthermore, shuffles require a constant mask, whereas extractelts 5770 // accept variable indices. 5771 return SDValue(); 5772 } 5773 5774 // Add this element source to the list if it's not already there. 5775 SDValue SourceVec = V.getOperand(0); 5776 auto Source = std::find(Sources.begin(), Sources.end(), SourceVec); 5777 if (Source == Sources.end()) 5778 Source = Sources.insert(Sources.end(), ShuffleSourceInfo(SourceVec)); 5779 5780 // Update the minimum and maximum lane number seen. 5781 unsigned EltNo = cast<ConstantSDNode>(V.getOperand(1))->getZExtValue(); 5782 Source->MinElt = std::min(Source->MinElt, EltNo); 5783 Source->MaxElt = std::max(Source->MaxElt, EltNo); 5784 } 5785 5786 // Currently only do something sane when at most two source vectors 5787 // are involved. 5788 if (Sources.size() > 2) 5789 return SDValue(); 5790 5791 // Find out the smallest element size among result and two sources, and use 5792 // it as element size to build the shuffle_vector. 5793 EVT SmallestEltTy = VT.getVectorElementType(); 5794 for (auto &Source : Sources) { 5795 EVT SrcEltTy = Source.Vec.getValueType().getVectorElementType(); 5796 if (SrcEltTy.bitsLT(SmallestEltTy)) 5797 SmallestEltTy = SrcEltTy; 5798 } 5799 unsigned ResMultiplier = 5800 VT.getVectorElementType().getSizeInBits() / SmallestEltTy.getSizeInBits(); 5801 NumElts = VT.getSizeInBits() / SmallestEltTy.getSizeInBits(); 5802 EVT ShuffleVT = EVT::getVectorVT(*DAG.getContext(), SmallestEltTy, NumElts); 5803 5804 // If the source vector is too wide or too narrow, we may nevertheless be able 5805 // to construct a compatible shuffle either by concatenating it with UNDEF or 5806 // extracting a suitable range of elements. 5807 for (auto &Src : Sources) { 5808 EVT SrcVT = Src.ShuffleVec.getValueType(); 5809 5810 if (SrcVT.getSizeInBits() == VT.getSizeInBits()) 5811 continue; 5812 5813 // This stage of the search produces a source with the same element type as 5814 // the original, but with a total width matching the BUILD_VECTOR output. 5815 EVT EltVT = SrcVT.getVectorElementType(); 5816 unsigned NumSrcElts = VT.getSizeInBits() / EltVT.getSizeInBits(); 5817 EVT DestVT = EVT::getVectorVT(*DAG.getContext(), EltVT, NumSrcElts); 5818 5819 if (SrcVT.getSizeInBits() < VT.getSizeInBits()) { 5820 if (2 * SrcVT.getSizeInBits() != VT.getSizeInBits()) 5821 return SDValue(); 5822 // We can pad out the smaller vector for free, so if it's part of a 5823 // shuffle... 5824 Src.ShuffleVec = 5825 DAG.getNode(ISD::CONCAT_VECTORS, dl, DestVT, Src.ShuffleVec, 5826 DAG.getUNDEF(Src.ShuffleVec.getValueType())); 5827 continue; 5828 } 5829 5830 if (SrcVT.getSizeInBits() != 2 * VT.getSizeInBits()) 5831 return SDValue(); 5832 5833 if (Src.MaxElt - Src.MinElt >= NumSrcElts) { 5834 // Span too large for a VEXT to cope 5835 return SDValue(); 5836 } 5837 5838 if (Src.MinElt >= NumSrcElts) { 5839 // The extraction can just take the second half 5840 Src.ShuffleVec = 5841 DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DestVT, Src.ShuffleVec, 5842 DAG.getConstant(NumSrcElts, dl, MVT::i32)); 5843 Src.WindowBase = -NumSrcElts; 5844 } else if (Src.MaxElt < NumSrcElts) { 5845 // The extraction can just take the first half 5846 Src.ShuffleVec = 5847 DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DestVT, Src.ShuffleVec, 5848 DAG.getConstant(0, dl, MVT::i32)); 5849 } else { 5850 // An actual VEXT is needed 5851 SDValue VEXTSrc1 = 5852 DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DestVT, Src.ShuffleVec, 5853 DAG.getConstant(0, dl, MVT::i32)); 5854 SDValue VEXTSrc2 = 5855 DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DestVT, Src.ShuffleVec, 5856 DAG.getConstant(NumSrcElts, dl, MVT::i32)); 5857 5858 Src.ShuffleVec = DAG.getNode(ARMISD::VEXT, dl, DestVT, VEXTSrc1, 5859 VEXTSrc2, 5860 DAG.getConstant(Src.MinElt, dl, MVT::i32)); 5861 Src.WindowBase = -Src.MinElt; 5862 } 5863 } 5864 5865 // Another possible incompatibility occurs from the vector element types. We 5866 // can fix this by bitcasting the source vectors to the same type we intend 5867 // for the shuffle. 5868 for (auto &Src : Sources) { 5869 EVT SrcEltTy = Src.ShuffleVec.getValueType().getVectorElementType(); 5870 if (SrcEltTy == SmallestEltTy) 5871 continue; 5872 assert(ShuffleVT.getVectorElementType() == SmallestEltTy); 5873 Src.ShuffleVec = DAG.getNode(ISD::BITCAST, dl, ShuffleVT, Src.ShuffleVec); 5874 Src.WindowScale = SrcEltTy.getSizeInBits() / SmallestEltTy.getSizeInBits(); 5875 Src.WindowBase *= Src.WindowScale; 5876 } 5877 5878 // Final sanity check before we try to actually produce a shuffle. 5879 DEBUG( 5880 for (auto Src : Sources) 5881 assert(Src.ShuffleVec.getValueType() == ShuffleVT); 5882 ); 5883 5884 // The stars all align, our next step is to produce the mask for the shuffle. 5885 SmallVector<int, 8> Mask(ShuffleVT.getVectorNumElements(), -1); 5886 int BitsPerShuffleLane = ShuffleVT.getVectorElementType().getSizeInBits(); 5887 for (unsigned i = 0; i < VT.getVectorNumElements(); ++i) { 5888 SDValue Entry = Op.getOperand(i); 5889 if (Entry.isUndef()) 5890 continue; 5891 5892 auto Src = std::find(Sources.begin(), Sources.end(), Entry.getOperand(0)); 5893 int EltNo = cast<ConstantSDNode>(Entry.getOperand(1))->getSExtValue(); 5894 5895 // EXTRACT_VECTOR_ELT performs an implicit any_ext; BUILD_VECTOR an implicit 5896 // trunc. So only std::min(SrcBits, DestBits) actually get defined in this 5897 // segment. 5898 EVT OrigEltTy = Entry.getOperand(0).getValueType().getVectorElementType(); 5899 int BitsDefined = std::min(OrigEltTy.getSizeInBits(), 5900 VT.getVectorElementType().getSizeInBits()); 5901 int LanesDefined = BitsDefined / BitsPerShuffleLane; 5902 5903 // This source is expected to fill ResMultiplier lanes of the final shuffle, 5904 // starting at the appropriate offset. 5905 int *LaneMask = &Mask[i * ResMultiplier]; 5906 5907 int ExtractBase = EltNo * Src->WindowScale + Src->WindowBase; 5908 ExtractBase += NumElts * (Src - Sources.begin()); 5909 for (int j = 0; j < LanesDefined; ++j) 5910 LaneMask[j] = ExtractBase + j; 5911 } 5912 5913 // Final check before we try to produce nonsense... 5914 if (!isShuffleMaskLegal(Mask, ShuffleVT)) 5915 return SDValue(); 5916 5917 // We can't handle more than two sources. This should have already 5918 // been checked before this point. 5919 assert(Sources.size() <= 2 && "Too many sources!"); 5920 5921 SDValue ShuffleOps[] = { DAG.getUNDEF(ShuffleVT), DAG.getUNDEF(ShuffleVT) }; 5922 for (unsigned i = 0; i < Sources.size(); ++i) 5923 ShuffleOps[i] = Sources[i].ShuffleVec; 5924 5925 SDValue Shuffle = DAG.getVectorShuffle(ShuffleVT, dl, ShuffleOps[0], 5926 ShuffleOps[1], &Mask[0]); 5927 return DAG.getNode(ISD::BITCAST, dl, VT, Shuffle); 5928 } 5929 5930 /// isShuffleMaskLegal - Targets can use this to indicate that they only 5931 /// support *some* VECTOR_SHUFFLE operations, those with specific masks. 5932 /// By default, if a target supports the VECTOR_SHUFFLE node, all mask values 5933 /// are assumed to be legal. 5934 bool 5935 ARMTargetLowering::isShuffleMaskLegal(const SmallVectorImpl<int> &M, 5936 EVT VT) const { 5937 if (VT.getVectorNumElements() == 4 && 5938 (VT.is128BitVector() || VT.is64BitVector())) { 5939 unsigned PFIndexes[4]; 5940 for (unsigned i = 0; i != 4; ++i) { 5941 if (M[i] < 0) 5942 PFIndexes[i] = 8; 5943 else 5944 PFIndexes[i] = M[i]; 5945 } 5946 5947 // Compute the index in the perfect shuffle table. 5948 unsigned PFTableIndex = 5949 PFIndexes[0]*9*9*9+PFIndexes[1]*9*9+PFIndexes[2]*9+PFIndexes[3]; 5950 unsigned PFEntry = PerfectShuffleTable[PFTableIndex]; 5951 unsigned Cost = (PFEntry >> 30); 5952 5953 if (Cost <= 4) 5954 return true; 5955 } 5956 5957 bool ReverseVEXT, isV_UNDEF; 5958 unsigned Imm, WhichResult; 5959 5960 unsigned EltSize = VT.getVectorElementType().getSizeInBits(); 5961 return (EltSize >= 32 || 5962 ShuffleVectorSDNode::isSplatMask(&M[0], VT) || 5963 isVREVMask(M, VT, 64) || 5964 isVREVMask(M, VT, 32) || 5965 isVREVMask(M, VT, 16) || 5966 isVEXTMask(M, VT, ReverseVEXT, Imm) || 5967 isVTBLMask(M, VT) || 5968 isNEONTwoResultShuffleMask(M, VT, WhichResult, isV_UNDEF) || 5969 ((VT == MVT::v8i16 || VT == MVT::v16i8) && isReverseMask(M, VT))); 5970 } 5971 5972 /// GeneratePerfectShuffle - Given an entry in the perfect-shuffle table, emit 5973 /// the specified operations to build the shuffle. 5974 static SDValue GeneratePerfectShuffle(unsigned PFEntry, SDValue LHS, 5975 SDValue RHS, SelectionDAG &DAG, 5976 SDLoc dl) { 5977 unsigned OpNum = (PFEntry >> 26) & 0x0F; 5978 unsigned LHSID = (PFEntry >> 13) & ((1 << 13)-1); 5979 unsigned RHSID = (PFEntry >> 0) & ((1 << 13)-1); 5980 5981 enum { 5982 OP_COPY = 0, // Copy, used for things like <u,u,u,3> to say it is <0,1,2,3> 5983 OP_VREV, 5984 OP_VDUP0, 5985 OP_VDUP1, 5986 OP_VDUP2, 5987 OP_VDUP3, 5988 OP_VEXT1, 5989 OP_VEXT2, 5990 OP_VEXT3, 5991 OP_VUZPL, // VUZP, left result 5992 OP_VUZPR, // VUZP, right result 5993 OP_VZIPL, // VZIP, left result 5994 OP_VZIPR, // VZIP, right result 5995 OP_VTRNL, // VTRN, left result 5996 OP_VTRNR // VTRN, right result 5997 }; 5998 5999 if (OpNum == OP_COPY) { 6000 if (LHSID == (1*9+2)*9+3) return LHS; 6001 assert(LHSID == ((4*9+5)*9+6)*9+7 && "Illegal OP_COPY!"); 6002 return RHS; 6003 } 6004 6005 SDValue OpLHS, OpRHS; 6006 OpLHS = GeneratePerfectShuffle(PerfectShuffleTable[LHSID], LHS, RHS, DAG, dl); 6007 OpRHS = GeneratePerfectShuffle(PerfectShuffleTable[RHSID], LHS, RHS, DAG, dl); 6008 EVT VT = OpLHS.getValueType(); 6009 6010 switch (OpNum) { 6011 default: llvm_unreachable("Unknown shuffle opcode!"); 6012 case OP_VREV: 6013 // VREV divides the vector in half and swaps within the half. 6014 if (VT.getVectorElementType() == MVT::i32 || 6015 VT.getVectorElementType() == MVT::f32) 6016 return DAG.getNode(ARMISD::VREV64, dl, VT, OpLHS); 6017 // vrev <4 x i16> -> VREV32 6018 if (VT.getVectorElementType() == MVT::i16) 6019 return DAG.getNode(ARMISD::VREV32, dl, VT, OpLHS); 6020 // vrev <4 x i8> -> VREV16 6021 assert(VT.getVectorElementType() == MVT::i8); 6022 return DAG.getNode(ARMISD::VREV16, dl, VT, OpLHS); 6023 case OP_VDUP0: 6024 case OP_VDUP1: 6025 case OP_VDUP2: 6026 case OP_VDUP3: 6027 return DAG.getNode(ARMISD::VDUPLANE, dl, VT, 6028 OpLHS, DAG.getConstant(OpNum-OP_VDUP0, dl, MVT::i32)); 6029 case OP_VEXT1: 6030 case OP_VEXT2: 6031 case OP_VEXT3: 6032 return DAG.getNode(ARMISD::VEXT, dl, VT, 6033 OpLHS, OpRHS, 6034 DAG.getConstant(OpNum - OP_VEXT1 + 1, dl, MVT::i32)); 6035 case OP_VUZPL: 6036 case OP_VUZPR: 6037 return DAG.getNode(ARMISD::VUZP, dl, DAG.getVTList(VT, VT), 6038 OpLHS, OpRHS).getValue(OpNum-OP_VUZPL); 6039 case OP_VZIPL: 6040 case OP_VZIPR: 6041 return DAG.getNode(ARMISD::VZIP, dl, DAG.getVTList(VT, VT), 6042 OpLHS, OpRHS).getValue(OpNum-OP_VZIPL); 6043 case OP_VTRNL: 6044 case OP_VTRNR: 6045 return DAG.getNode(ARMISD::VTRN, dl, DAG.getVTList(VT, VT), 6046 OpLHS, OpRHS).getValue(OpNum-OP_VTRNL); 6047 } 6048 } 6049 6050 static SDValue LowerVECTOR_SHUFFLEv8i8(SDValue Op, 6051 ArrayRef<int> ShuffleMask, 6052 SelectionDAG &DAG) { 6053 // Check to see if we can use the VTBL instruction. 6054 SDValue V1 = Op.getOperand(0); 6055 SDValue V2 = Op.getOperand(1); 6056 SDLoc DL(Op); 6057 6058 SmallVector<SDValue, 8> VTBLMask; 6059 for (ArrayRef<int>::iterator 6060 I = ShuffleMask.begin(), E = ShuffleMask.end(); I != E; ++I) 6061 VTBLMask.push_back(DAG.getConstant(*I, DL, MVT::i32)); 6062 6063 if (V2.getNode()->isUndef()) 6064 return DAG.getNode(ARMISD::VTBL1, DL, MVT::v8i8, V1, 6065 DAG.getBuildVector(MVT::v8i8, DL, VTBLMask)); 6066 6067 return DAG.getNode(ARMISD::VTBL2, DL, MVT::v8i8, V1, V2, 6068 DAG.getBuildVector(MVT::v8i8, DL, VTBLMask)); 6069 } 6070 6071 static SDValue LowerReverse_VECTOR_SHUFFLEv16i8_v8i16(SDValue Op, 6072 SelectionDAG &DAG) { 6073 SDLoc DL(Op); 6074 SDValue OpLHS = Op.getOperand(0); 6075 EVT VT = OpLHS.getValueType(); 6076 6077 assert((VT == MVT::v8i16 || VT == MVT::v16i8) && 6078 "Expect an v8i16/v16i8 type"); 6079 OpLHS = DAG.getNode(ARMISD::VREV64, DL, VT, OpLHS); 6080 // For a v16i8 type: After the VREV, we have got <8, ...15, 8, ..., 0>. Now, 6081 // extract the first 8 bytes into the top double word and the last 8 bytes 6082 // into the bottom double word. The v8i16 case is similar. 6083 unsigned ExtractNum = (VT == MVT::v16i8) ? 8 : 4; 6084 return DAG.getNode(ARMISD::VEXT, DL, VT, OpLHS, OpLHS, 6085 DAG.getConstant(ExtractNum, DL, MVT::i32)); 6086 } 6087 6088 static SDValue LowerVECTOR_SHUFFLE(SDValue Op, SelectionDAG &DAG) { 6089 SDValue V1 = Op.getOperand(0); 6090 SDValue V2 = Op.getOperand(1); 6091 SDLoc dl(Op); 6092 EVT VT = Op.getValueType(); 6093 ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(Op.getNode()); 6094 6095 // Convert shuffles that are directly supported on NEON to target-specific 6096 // DAG nodes, instead of keeping them as shuffles and matching them again 6097 // during code selection. This is more efficient and avoids the possibility 6098 // of inconsistencies between legalization and selection. 6099 // FIXME: floating-point vectors should be canonicalized to integer vectors 6100 // of the same time so that they get CSEd properly. 6101 ArrayRef<int> ShuffleMask = SVN->getMask(); 6102 6103 unsigned EltSize = VT.getVectorElementType().getSizeInBits(); 6104 if (EltSize <= 32) { 6105 if (ShuffleVectorSDNode::isSplatMask(&ShuffleMask[0], VT)) { 6106 int Lane = SVN->getSplatIndex(); 6107 // If this is undef splat, generate it via "just" vdup, if possible. 6108 if (Lane == -1) Lane = 0; 6109 6110 // Test if V1 is a SCALAR_TO_VECTOR. 6111 if (Lane == 0 && V1.getOpcode() == ISD::SCALAR_TO_VECTOR) { 6112 return DAG.getNode(ARMISD::VDUP, dl, VT, V1.getOperand(0)); 6113 } 6114 // Test if V1 is a BUILD_VECTOR which is equivalent to a SCALAR_TO_VECTOR 6115 // (and probably will turn into a SCALAR_TO_VECTOR once legalization 6116 // reaches it). 6117 if (Lane == 0 && V1.getOpcode() == ISD::BUILD_VECTOR && 6118 !isa<ConstantSDNode>(V1.getOperand(0))) { 6119 bool IsScalarToVector = true; 6120 for (unsigned i = 1, e = V1.getNumOperands(); i != e; ++i) 6121 if (!V1.getOperand(i).isUndef()) { 6122 IsScalarToVector = false; 6123 break; 6124 } 6125 if (IsScalarToVector) 6126 return DAG.getNode(ARMISD::VDUP, dl, VT, V1.getOperand(0)); 6127 } 6128 return DAG.getNode(ARMISD::VDUPLANE, dl, VT, V1, 6129 DAG.getConstant(Lane, dl, MVT::i32)); 6130 } 6131 6132 bool ReverseVEXT; 6133 unsigned Imm; 6134 if (isVEXTMask(ShuffleMask, VT, ReverseVEXT, Imm)) { 6135 if (ReverseVEXT) 6136 std::swap(V1, V2); 6137 return DAG.getNode(ARMISD::VEXT, dl, VT, V1, V2, 6138 DAG.getConstant(Imm, dl, MVT::i32)); 6139 } 6140 6141 if (isVREVMask(ShuffleMask, VT, 64)) 6142 return DAG.getNode(ARMISD::VREV64, dl, VT, V1); 6143 if (isVREVMask(ShuffleMask, VT, 32)) 6144 return DAG.getNode(ARMISD::VREV32, dl, VT, V1); 6145 if (isVREVMask(ShuffleMask, VT, 16)) 6146 return DAG.getNode(ARMISD::VREV16, dl, VT, V1); 6147 6148 if (V2->isUndef() && isSingletonVEXTMask(ShuffleMask, VT, Imm)) { 6149 return DAG.getNode(ARMISD::VEXT, dl, VT, V1, V1, 6150 DAG.getConstant(Imm, dl, MVT::i32)); 6151 } 6152 6153 // Check for Neon shuffles that modify both input vectors in place. 6154 // If both results are used, i.e., if there are two shuffles with the same 6155 // source operands and with masks corresponding to both results of one of 6156 // these operations, DAG memoization will ensure that a single node is 6157 // used for both shuffles. 6158 unsigned WhichResult; 6159 bool isV_UNDEF; 6160 if (unsigned ShuffleOpc = isNEONTwoResultShuffleMask( 6161 ShuffleMask, VT, WhichResult, isV_UNDEF)) { 6162 if (isV_UNDEF) 6163 V2 = V1; 6164 return DAG.getNode(ShuffleOpc, dl, DAG.getVTList(VT, VT), V1, V2) 6165 .getValue(WhichResult); 6166 } 6167 6168 // Also check for these shuffles through CONCAT_VECTORS: we canonicalize 6169 // shuffles that produce a result larger than their operands with: 6170 // shuffle(concat(v1, undef), concat(v2, undef)) 6171 // -> 6172 // shuffle(concat(v1, v2), undef) 6173 // because we can access quad vectors (see PerformVECTOR_SHUFFLECombine). 6174 // 6175 // This is useful in the general case, but there are special cases where 6176 // native shuffles produce larger results: the two-result ops. 6177 // 6178 // Look through the concat when lowering them: 6179 // shuffle(concat(v1, v2), undef) 6180 // -> 6181 // concat(VZIP(v1, v2):0, :1) 6182 // 6183 if (V1->getOpcode() == ISD::CONCAT_VECTORS && V2->isUndef()) { 6184 SDValue SubV1 = V1->getOperand(0); 6185 SDValue SubV2 = V1->getOperand(1); 6186 EVT SubVT = SubV1.getValueType(); 6187 6188 // We expect these to have been canonicalized to -1. 6189 assert(std::all_of(ShuffleMask.begin(), ShuffleMask.end(), [&](int i) { 6190 return i < (int)VT.getVectorNumElements(); 6191 }) && "Unexpected shuffle index into UNDEF operand!"); 6192 6193 if (unsigned ShuffleOpc = isNEONTwoResultShuffleMask( 6194 ShuffleMask, SubVT, WhichResult, isV_UNDEF)) { 6195 if (isV_UNDEF) 6196 SubV2 = SubV1; 6197 assert((WhichResult == 0) && 6198 "In-place shuffle of concat can only have one result!"); 6199 SDValue Res = DAG.getNode(ShuffleOpc, dl, DAG.getVTList(SubVT, SubVT), 6200 SubV1, SubV2); 6201 return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, Res.getValue(0), 6202 Res.getValue(1)); 6203 } 6204 } 6205 } 6206 6207 // If the shuffle is not directly supported and it has 4 elements, use 6208 // the PerfectShuffle-generated table to synthesize it from other shuffles. 6209 unsigned NumElts = VT.getVectorNumElements(); 6210 if (NumElts == 4) { 6211 unsigned PFIndexes[4]; 6212 for (unsigned i = 0; i != 4; ++i) { 6213 if (ShuffleMask[i] < 0) 6214 PFIndexes[i] = 8; 6215 else 6216 PFIndexes[i] = ShuffleMask[i]; 6217 } 6218 6219 // Compute the index in the perfect shuffle table. 6220 unsigned PFTableIndex = 6221 PFIndexes[0]*9*9*9+PFIndexes[1]*9*9+PFIndexes[2]*9+PFIndexes[3]; 6222 unsigned PFEntry = PerfectShuffleTable[PFTableIndex]; 6223 unsigned Cost = (PFEntry >> 30); 6224 6225 if (Cost <= 4) 6226 return GeneratePerfectShuffle(PFEntry, V1, V2, DAG, dl); 6227 } 6228 6229 // Implement shuffles with 32- or 64-bit elements as ARMISD::BUILD_VECTORs. 6230 if (EltSize >= 32) { 6231 // Do the expansion with floating-point types, since that is what the VFP 6232 // registers are defined to use, and since i64 is not legal. 6233 EVT EltVT = EVT::getFloatingPointVT(EltSize); 6234 EVT VecVT = EVT::getVectorVT(*DAG.getContext(), EltVT, NumElts); 6235 V1 = DAG.getNode(ISD::BITCAST, dl, VecVT, V1); 6236 V2 = DAG.getNode(ISD::BITCAST, dl, VecVT, V2); 6237 SmallVector<SDValue, 8> Ops; 6238 for (unsigned i = 0; i < NumElts; ++i) { 6239 if (ShuffleMask[i] < 0) 6240 Ops.push_back(DAG.getUNDEF(EltVT)); 6241 else 6242 Ops.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, EltVT, 6243 ShuffleMask[i] < (int)NumElts ? V1 : V2, 6244 DAG.getConstant(ShuffleMask[i] & (NumElts-1), 6245 dl, MVT::i32))); 6246 } 6247 SDValue Val = DAG.getNode(ARMISD::BUILD_VECTOR, dl, VecVT, Ops); 6248 return DAG.getNode(ISD::BITCAST, dl, VT, Val); 6249 } 6250 6251 if ((VT == MVT::v8i16 || VT == MVT::v16i8) && isReverseMask(ShuffleMask, VT)) 6252 return LowerReverse_VECTOR_SHUFFLEv16i8_v8i16(Op, DAG); 6253 6254 if (VT == MVT::v8i8) 6255 if (SDValue NewOp = LowerVECTOR_SHUFFLEv8i8(Op, ShuffleMask, DAG)) 6256 return NewOp; 6257 6258 return SDValue(); 6259 } 6260 6261 static SDValue LowerINSERT_VECTOR_ELT(SDValue Op, SelectionDAG &DAG) { 6262 // INSERT_VECTOR_ELT is legal only for immediate indexes. 6263 SDValue Lane = Op.getOperand(2); 6264 if (!isa<ConstantSDNode>(Lane)) 6265 return SDValue(); 6266 6267 return Op; 6268 } 6269 6270 static SDValue LowerEXTRACT_VECTOR_ELT(SDValue Op, SelectionDAG &DAG) { 6271 // EXTRACT_VECTOR_ELT is legal only for immediate indexes. 6272 SDValue Lane = Op.getOperand(1); 6273 if (!isa<ConstantSDNode>(Lane)) 6274 return SDValue(); 6275 6276 SDValue Vec = Op.getOperand(0); 6277 if (Op.getValueType() == MVT::i32 && 6278 Vec.getValueType().getVectorElementType().getSizeInBits() < 32) { 6279 SDLoc dl(Op); 6280 return DAG.getNode(ARMISD::VGETLANEu, dl, MVT::i32, Vec, Lane); 6281 } 6282 6283 return Op; 6284 } 6285 6286 static SDValue LowerCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG) { 6287 // The only time a CONCAT_VECTORS operation can have legal types is when 6288 // two 64-bit vectors are concatenated to a 128-bit vector. 6289 assert(Op.getValueType().is128BitVector() && Op.getNumOperands() == 2 && 6290 "unexpected CONCAT_VECTORS"); 6291 SDLoc dl(Op); 6292 SDValue Val = DAG.getUNDEF(MVT::v2f64); 6293 SDValue Op0 = Op.getOperand(0); 6294 SDValue Op1 = Op.getOperand(1); 6295 if (!Op0.isUndef()) 6296 Val = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Val, 6297 DAG.getNode(ISD::BITCAST, dl, MVT::f64, Op0), 6298 DAG.getIntPtrConstant(0, dl)); 6299 if (!Op1.isUndef()) 6300 Val = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Val, 6301 DAG.getNode(ISD::BITCAST, dl, MVT::f64, Op1), 6302 DAG.getIntPtrConstant(1, dl)); 6303 return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Val); 6304 } 6305 6306 /// isExtendedBUILD_VECTOR - Check if N is a constant BUILD_VECTOR where each 6307 /// element has been zero/sign-extended, depending on the isSigned parameter, 6308 /// from an integer type half its size. 6309 static bool isExtendedBUILD_VECTOR(SDNode *N, SelectionDAG &DAG, 6310 bool isSigned) { 6311 // A v2i64 BUILD_VECTOR will have been legalized to a BITCAST from v4i32. 6312 EVT VT = N->getValueType(0); 6313 if (VT == MVT::v2i64 && N->getOpcode() == ISD::BITCAST) { 6314 SDNode *BVN = N->getOperand(0).getNode(); 6315 if (BVN->getValueType(0) != MVT::v4i32 || 6316 BVN->getOpcode() != ISD::BUILD_VECTOR) 6317 return false; 6318 unsigned LoElt = DAG.getDataLayout().isBigEndian() ? 1 : 0; 6319 unsigned HiElt = 1 - LoElt; 6320 ConstantSDNode *Lo0 = dyn_cast<ConstantSDNode>(BVN->getOperand(LoElt)); 6321 ConstantSDNode *Hi0 = dyn_cast<ConstantSDNode>(BVN->getOperand(HiElt)); 6322 ConstantSDNode *Lo1 = dyn_cast<ConstantSDNode>(BVN->getOperand(LoElt+2)); 6323 ConstantSDNode *Hi1 = dyn_cast<ConstantSDNode>(BVN->getOperand(HiElt+2)); 6324 if (!Lo0 || !Hi0 || !Lo1 || !Hi1) 6325 return false; 6326 if (isSigned) { 6327 if (Hi0->getSExtValue() == Lo0->getSExtValue() >> 32 && 6328 Hi1->getSExtValue() == Lo1->getSExtValue() >> 32) 6329 return true; 6330 } else { 6331 if (Hi0->isNullValue() && Hi1->isNullValue()) 6332 return true; 6333 } 6334 return false; 6335 } 6336 6337 if (N->getOpcode() != ISD::BUILD_VECTOR) 6338 return false; 6339 6340 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) { 6341 SDNode *Elt = N->getOperand(i).getNode(); 6342 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Elt)) { 6343 unsigned EltSize = VT.getVectorElementType().getSizeInBits(); 6344 unsigned HalfSize = EltSize / 2; 6345 if (isSigned) { 6346 if (!isIntN(HalfSize, C->getSExtValue())) 6347 return false; 6348 } else { 6349 if (!isUIntN(HalfSize, C->getZExtValue())) 6350 return false; 6351 } 6352 continue; 6353 } 6354 return false; 6355 } 6356 6357 return true; 6358 } 6359 6360 /// isSignExtended - Check if a node is a vector value that is sign-extended 6361 /// or a constant BUILD_VECTOR with sign-extended elements. 6362 static bool isSignExtended(SDNode *N, SelectionDAG &DAG) { 6363 if (N->getOpcode() == ISD::SIGN_EXTEND || ISD::isSEXTLoad(N)) 6364 return true; 6365 if (isExtendedBUILD_VECTOR(N, DAG, true)) 6366 return true; 6367 return false; 6368 } 6369 6370 /// isZeroExtended - Check if a node is a vector value that is zero-extended 6371 /// or a constant BUILD_VECTOR with zero-extended elements. 6372 static bool isZeroExtended(SDNode *N, SelectionDAG &DAG) { 6373 if (N->getOpcode() == ISD::ZERO_EXTEND || ISD::isZEXTLoad(N)) 6374 return true; 6375 if (isExtendedBUILD_VECTOR(N, DAG, false)) 6376 return true; 6377 return false; 6378 } 6379 6380 static EVT getExtensionTo64Bits(const EVT &OrigVT) { 6381 if (OrigVT.getSizeInBits() >= 64) 6382 return OrigVT; 6383 6384 assert(OrigVT.isSimple() && "Expecting a simple value type"); 6385 6386 MVT::SimpleValueType OrigSimpleTy = OrigVT.getSimpleVT().SimpleTy; 6387 switch (OrigSimpleTy) { 6388 default: llvm_unreachable("Unexpected Vector Type"); 6389 case MVT::v2i8: 6390 case MVT::v2i16: 6391 return MVT::v2i32; 6392 case MVT::v4i8: 6393 return MVT::v4i16; 6394 } 6395 } 6396 6397 /// AddRequiredExtensionForVMULL - Add a sign/zero extension to extend the total 6398 /// value size to 64 bits. We need a 64-bit D register as an operand to VMULL. 6399 /// We insert the required extension here to get the vector to fill a D register. 6400 static SDValue AddRequiredExtensionForVMULL(SDValue N, SelectionDAG &DAG, 6401 const EVT &OrigTy, 6402 const EVT &ExtTy, 6403 unsigned ExtOpcode) { 6404 // The vector originally had a size of OrigTy. It was then extended to ExtTy. 6405 // We expect the ExtTy to be 128-bits total. If the OrigTy is less than 6406 // 64-bits we need to insert a new extension so that it will be 64-bits. 6407 assert(ExtTy.is128BitVector() && "Unexpected extension size"); 6408 if (OrigTy.getSizeInBits() >= 64) 6409 return N; 6410 6411 // Must extend size to at least 64 bits to be used as an operand for VMULL. 6412 EVT NewVT = getExtensionTo64Bits(OrigTy); 6413 6414 return DAG.getNode(ExtOpcode, SDLoc(N), NewVT, N); 6415 } 6416 6417 /// SkipLoadExtensionForVMULL - return a load of the original vector size that 6418 /// does not do any sign/zero extension. If the original vector is less 6419 /// than 64 bits, an appropriate extension will be added after the load to 6420 /// reach a total size of 64 bits. We have to add the extension separately 6421 /// because ARM does not have a sign/zero extending load for vectors. 6422 static SDValue SkipLoadExtensionForVMULL(LoadSDNode *LD, SelectionDAG& DAG) { 6423 EVT ExtendedTy = getExtensionTo64Bits(LD->getMemoryVT()); 6424 6425 // The load already has the right type. 6426 if (ExtendedTy == LD->getMemoryVT()) 6427 return DAG.getLoad(LD->getMemoryVT(), SDLoc(LD), LD->getChain(), 6428 LD->getBasePtr(), LD->getPointerInfo(), LD->isVolatile(), 6429 LD->isNonTemporal(), LD->isInvariant(), 6430 LD->getAlignment()); 6431 6432 // We need to create a zextload/sextload. We cannot just create a load 6433 // followed by a zext/zext node because LowerMUL is also run during normal 6434 // operation legalization where we can't create illegal types. 6435 return DAG.getExtLoad(LD->getExtensionType(), SDLoc(LD), ExtendedTy, 6436 LD->getChain(), LD->getBasePtr(), LD->getPointerInfo(), 6437 LD->getMemoryVT(), LD->isVolatile(), LD->isInvariant(), 6438 LD->isNonTemporal(), LD->getAlignment()); 6439 } 6440 6441 /// SkipExtensionForVMULL - For a node that is a SIGN_EXTEND, ZERO_EXTEND, 6442 /// extending load, or BUILD_VECTOR with extended elements, return the 6443 /// unextended value. The unextended vector should be 64 bits so that it can 6444 /// be used as an operand to a VMULL instruction. If the original vector size 6445 /// before extension is less than 64 bits we add a an extension to resize 6446 /// the vector to 64 bits. 6447 static SDValue SkipExtensionForVMULL(SDNode *N, SelectionDAG &DAG) { 6448 if (N->getOpcode() == ISD::SIGN_EXTEND || N->getOpcode() == ISD::ZERO_EXTEND) 6449 return AddRequiredExtensionForVMULL(N->getOperand(0), DAG, 6450 N->getOperand(0)->getValueType(0), 6451 N->getValueType(0), 6452 N->getOpcode()); 6453 6454 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) 6455 return SkipLoadExtensionForVMULL(LD, DAG); 6456 6457 // Otherwise, the value must be a BUILD_VECTOR. For v2i64, it will 6458 // have been legalized as a BITCAST from v4i32. 6459 if (N->getOpcode() == ISD::BITCAST) { 6460 SDNode *BVN = N->getOperand(0).getNode(); 6461 assert(BVN->getOpcode() == ISD::BUILD_VECTOR && 6462 BVN->getValueType(0) == MVT::v4i32 && "expected v4i32 BUILD_VECTOR"); 6463 unsigned LowElt = DAG.getDataLayout().isBigEndian() ? 1 : 0; 6464 return DAG.getBuildVector( 6465 MVT::v2i32, SDLoc(N), 6466 {BVN->getOperand(LowElt), BVN->getOperand(LowElt + 2)}); 6467 } 6468 // Construct a new BUILD_VECTOR with elements truncated to half the size. 6469 assert(N->getOpcode() == ISD::BUILD_VECTOR && "expected BUILD_VECTOR"); 6470 EVT VT = N->getValueType(0); 6471 unsigned EltSize = VT.getVectorElementType().getSizeInBits() / 2; 6472 unsigned NumElts = VT.getVectorNumElements(); 6473 MVT TruncVT = MVT::getIntegerVT(EltSize); 6474 SmallVector<SDValue, 8> Ops; 6475 SDLoc dl(N); 6476 for (unsigned i = 0; i != NumElts; ++i) { 6477 ConstantSDNode *C = cast<ConstantSDNode>(N->getOperand(i)); 6478 const APInt &CInt = C->getAPIntValue(); 6479 // Element types smaller than 32 bits are not legal, so use i32 elements. 6480 // The values are implicitly truncated so sext vs. zext doesn't matter. 6481 Ops.push_back(DAG.getConstant(CInt.zextOrTrunc(32), dl, MVT::i32)); 6482 } 6483 return DAG.getBuildVector(MVT::getVectorVT(TruncVT, NumElts), dl, Ops); 6484 } 6485 6486 static bool isAddSubSExt(SDNode *N, SelectionDAG &DAG) { 6487 unsigned Opcode = N->getOpcode(); 6488 if (Opcode == ISD::ADD || Opcode == ISD::SUB) { 6489 SDNode *N0 = N->getOperand(0).getNode(); 6490 SDNode *N1 = N->getOperand(1).getNode(); 6491 return N0->hasOneUse() && N1->hasOneUse() && 6492 isSignExtended(N0, DAG) && isSignExtended(N1, DAG); 6493 } 6494 return false; 6495 } 6496 6497 static bool isAddSubZExt(SDNode *N, SelectionDAG &DAG) { 6498 unsigned Opcode = N->getOpcode(); 6499 if (Opcode == ISD::ADD || Opcode == ISD::SUB) { 6500 SDNode *N0 = N->getOperand(0).getNode(); 6501 SDNode *N1 = N->getOperand(1).getNode(); 6502 return N0->hasOneUse() && N1->hasOneUse() && 6503 isZeroExtended(N0, DAG) && isZeroExtended(N1, DAG); 6504 } 6505 return false; 6506 } 6507 6508 static SDValue LowerMUL(SDValue Op, SelectionDAG &DAG) { 6509 // Multiplications are only custom-lowered for 128-bit vectors so that 6510 // VMULL can be detected. Otherwise v2i64 multiplications are not legal. 6511 EVT VT = Op.getValueType(); 6512 assert(VT.is128BitVector() && VT.isInteger() && 6513 "unexpected type for custom-lowering ISD::MUL"); 6514 SDNode *N0 = Op.getOperand(0).getNode(); 6515 SDNode *N1 = Op.getOperand(1).getNode(); 6516 unsigned NewOpc = 0; 6517 bool isMLA = false; 6518 bool isN0SExt = isSignExtended(N0, DAG); 6519 bool isN1SExt = isSignExtended(N1, DAG); 6520 if (isN0SExt && isN1SExt) 6521 NewOpc = ARMISD::VMULLs; 6522 else { 6523 bool isN0ZExt = isZeroExtended(N0, DAG); 6524 bool isN1ZExt = isZeroExtended(N1, DAG); 6525 if (isN0ZExt && isN1ZExt) 6526 NewOpc = ARMISD::VMULLu; 6527 else if (isN1SExt || isN1ZExt) { 6528 // Look for (s/zext A + s/zext B) * (s/zext C). We want to turn these 6529 // into (s/zext A * s/zext C) + (s/zext B * s/zext C) 6530 if (isN1SExt && isAddSubSExt(N0, DAG)) { 6531 NewOpc = ARMISD::VMULLs; 6532 isMLA = true; 6533 } else if (isN1ZExt && isAddSubZExt(N0, DAG)) { 6534 NewOpc = ARMISD::VMULLu; 6535 isMLA = true; 6536 } else if (isN0ZExt && isAddSubZExt(N1, DAG)) { 6537 std::swap(N0, N1); 6538 NewOpc = ARMISD::VMULLu; 6539 isMLA = true; 6540 } 6541 } 6542 6543 if (!NewOpc) { 6544 if (VT == MVT::v2i64) 6545 // Fall through to expand this. It is not legal. 6546 return SDValue(); 6547 else 6548 // Other vector multiplications are legal. 6549 return Op; 6550 } 6551 } 6552 6553 // Legalize to a VMULL instruction. 6554 SDLoc DL(Op); 6555 SDValue Op0; 6556 SDValue Op1 = SkipExtensionForVMULL(N1, DAG); 6557 if (!isMLA) { 6558 Op0 = SkipExtensionForVMULL(N0, DAG); 6559 assert(Op0.getValueType().is64BitVector() && 6560 Op1.getValueType().is64BitVector() && 6561 "unexpected types for extended operands to VMULL"); 6562 return DAG.getNode(NewOpc, DL, VT, Op0, Op1); 6563 } 6564 6565 // Optimizing (zext A + zext B) * C, to (VMULL A, C) + (VMULL B, C) during 6566 // isel lowering to take advantage of no-stall back to back vmul + vmla. 6567 // vmull q0, d4, d6 6568 // vmlal q0, d5, d6 6569 // is faster than 6570 // vaddl q0, d4, d5 6571 // vmovl q1, d6 6572 // vmul q0, q0, q1 6573 SDValue N00 = SkipExtensionForVMULL(N0->getOperand(0).getNode(), DAG); 6574 SDValue N01 = SkipExtensionForVMULL(N0->getOperand(1).getNode(), DAG); 6575 EVT Op1VT = Op1.getValueType(); 6576 return DAG.getNode(N0->getOpcode(), DL, VT, 6577 DAG.getNode(NewOpc, DL, VT, 6578 DAG.getNode(ISD::BITCAST, DL, Op1VT, N00), Op1), 6579 DAG.getNode(NewOpc, DL, VT, 6580 DAG.getNode(ISD::BITCAST, DL, Op1VT, N01), Op1)); 6581 } 6582 6583 static SDValue 6584 LowerSDIV_v4i8(SDValue X, SDValue Y, SDLoc dl, SelectionDAG &DAG) { 6585 // TODO: Should this propagate fast-math-flags? 6586 6587 // Convert to float 6588 // float4 xf = vcvt_f32_s32(vmovl_s16(a.lo)); 6589 // float4 yf = vcvt_f32_s32(vmovl_s16(b.lo)); 6590 X = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, X); 6591 Y = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, Y); 6592 X = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, X); 6593 Y = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, Y); 6594 // Get reciprocal estimate. 6595 // float4 recip = vrecpeq_f32(yf); 6596 Y = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32, 6597 DAG.getConstant(Intrinsic::arm_neon_vrecpe, dl, MVT::i32), 6598 Y); 6599 // Because char has a smaller range than uchar, we can actually get away 6600 // without any newton steps. This requires that we use a weird bias 6601 // of 0xb000, however (again, this has been exhaustively tested). 6602 // float4 result = as_float4(as_int4(xf*recip) + 0xb000); 6603 X = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, X, Y); 6604 X = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, X); 6605 Y = DAG.getConstant(0xb000, dl, MVT::v4i32); 6606 X = DAG.getNode(ISD::ADD, dl, MVT::v4i32, X, Y); 6607 X = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, X); 6608 // Convert back to short. 6609 X = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::v4i32, X); 6610 X = DAG.getNode(ISD::TRUNCATE, dl, MVT::v4i16, X); 6611 return X; 6612 } 6613 6614 static SDValue 6615 LowerSDIV_v4i16(SDValue N0, SDValue N1, SDLoc dl, SelectionDAG &DAG) { 6616 // TODO: Should this propagate fast-math-flags? 6617 6618 SDValue N2; 6619 // Convert to float. 6620 // float4 yf = vcvt_f32_s32(vmovl_s16(y)); 6621 // float4 xf = vcvt_f32_s32(vmovl_s16(x)); 6622 N0 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, N0); 6623 N1 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, N1); 6624 N0 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N0); 6625 N1 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N1); 6626 6627 // Use reciprocal estimate and one refinement step. 6628 // float4 recip = vrecpeq_f32(yf); 6629 // recip *= vrecpsq_f32(yf, recip); 6630 N2 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32, 6631 DAG.getConstant(Intrinsic::arm_neon_vrecpe, dl, MVT::i32), 6632 N1); 6633 N1 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32, 6634 DAG.getConstant(Intrinsic::arm_neon_vrecps, dl, MVT::i32), 6635 N1, N2); 6636 N2 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N1, N2); 6637 // Because short has a smaller range than ushort, we can actually get away 6638 // with only a single newton step. This requires that we use a weird bias 6639 // of 89, however (again, this has been exhaustively tested). 6640 // float4 result = as_float4(as_int4(xf*recip) + 0x89); 6641 N0 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N0, N2); 6642 N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, N0); 6643 N1 = DAG.getConstant(0x89, dl, MVT::v4i32); 6644 N0 = DAG.getNode(ISD::ADD, dl, MVT::v4i32, N0, N1); 6645 N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, N0); 6646 // Convert back to integer and return. 6647 // return vmovn_s32(vcvt_s32_f32(result)); 6648 N0 = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::v4i32, N0); 6649 N0 = DAG.getNode(ISD::TRUNCATE, dl, MVT::v4i16, N0); 6650 return N0; 6651 } 6652 6653 static SDValue LowerSDIV(SDValue Op, SelectionDAG &DAG) { 6654 EVT VT = Op.getValueType(); 6655 assert((VT == MVT::v4i16 || VT == MVT::v8i8) && 6656 "unexpected type for custom-lowering ISD::SDIV"); 6657 6658 SDLoc dl(Op); 6659 SDValue N0 = Op.getOperand(0); 6660 SDValue N1 = Op.getOperand(1); 6661 SDValue N2, N3; 6662 6663 if (VT == MVT::v8i8) { 6664 N0 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v8i16, N0); 6665 N1 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v8i16, N1); 6666 6667 N2 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0, 6668 DAG.getIntPtrConstant(4, dl)); 6669 N3 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1, 6670 DAG.getIntPtrConstant(4, dl)); 6671 N0 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0, 6672 DAG.getIntPtrConstant(0, dl)); 6673 N1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1, 6674 DAG.getIntPtrConstant(0, dl)); 6675 6676 N0 = LowerSDIV_v4i8(N0, N1, dl, DAG); // v4i16 6677 N2 = LowerSDIV_v4i8(N2, N3, dl, DAG); // v4i16 6678 6679 N0 = DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v8i16, N0, N2); 6680 N0 = LowerCONCAT_VECTORS(N0, DAG); 6681 6682 N0 = DAG.getNode(ISD::TRUNCATE, dl, MVT::v8i8, N0); 6683 return N0; 6684 } 6685 return LowerSDIV_v4i16(N0, N1, dl, DAG); 6686 } 6687 6688 static SDValue LowerUDIV(SDValue Op, SelectionDAG &DAG) { 6689 // TODO: Should this propagate fast-math-flags? 6690 EVT VT = Op.getValueType(); 6691 assert((VT == MVT::v4i16 || VT == MVT::v8i8) && 6692 "unexpected type for custom-lowering ISD::UDIV"); 6693 6694 SDLoc dl(Op); 6695 SDValue N0 = Op.getOperand(0); 6696 SDValue N1 = Op.getOperand(1); 6697 SDValue N2, N3; 6698 6699 if (VT == MVT::v8i8) { 6700 N0 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v8i16, N0); 6701 N1 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v8i16, N1); 6702 6703 N2 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0, 6704 DAG.getIntPtrConstant(4, dl)); 6705 N3 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1, 6706 DAG.getIntPtrConstant(4, dl)); 6707 N0 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0, 6708 DAG.getIntPtrConstant(0, dl)); 6709 N1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1, 6710 DAG.getIntPtrConstant(0, dl)); 6711 6712 N0 = LowerSDIV_v4i16(N0, N1, dl, DAG); // v4i16 6713 N2 = LowerSDIV_v4i16(N2, N3, dl, DAG); // v4i16 6714 6715 N0 = DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v8i16, N0, N2); 6716 N0 = LowerCONCAT_VECTORS(N0, DAG); 6717 6718 N0 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v8i8, 6719 DAG.getConstant(Intrinsic::arm_neon_vqmovnsu, dl, 6720 MVT::i32), 6721 N0); 6722 return N0; 6723 } 6724 6725 // v4i16 sdiv ... Convert to float. 6726 // float4 yf = vcvt_f32_s32(vmovl_u16(y)); 6727 // float4 xf = vcvt_f32_s32(vmovl_u16(x)); 6728 N0 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v4i32, N0); 6729 N1 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v4i32, N1); 6730 N0 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N0); 6731 SDValue BN1 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N1); 6732 6733 // Use reciprocal estimate and two refinement steps. 6734 // float4 recip = vrecpeq_f32(yf); 6735 // recip *= vrecpsq_f32(yf, recip); 6736 // recip *= vrecpsq_f32(yf, recip); 6737 N2 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32, 6738 DAG.getConstant(Intrinsic::arm_neon_vrecpe, dl, MVT::i32), 6739 BN1); 6740 N1 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32, 6741 DAG.getConstant(Intrinsic::arm_neon_vrecps, dl, MVT::i32), 6742 BN1, N2); 6743 N2 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N1, N2); 6744 N1 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32, 6745 DAG.getConstant(Intrinsic::arm_neon_vrecps, dl, MVT::i32), 6746 BN1, N2); 6747 N2 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N1, N2); 6748 // Simply multiplying by the reciprocal estimate can leave us a few ulps 6749 // too low, so we add 2 ulps (exhaustive testing shows that this is enough, 6750 // and that it will never cause us to return an answer too large). 6751 // float4 result = as_float4(as_int4(xf*recip) + 2); 6752 N0 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N0, N2); 6753 N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, N0); 6754 N1 = DAG.getConstant(2, dl, MVT::v4i32); 6755 N0 = DAG.getNode(ISD::ADD, dl, MVT::v4i32, N0, N1); 6756 N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, N0); 6757 // Convert back to integer and return. 6758 // return vmovn_u32(vcvt_s32_f32(result)); 6759 N0 = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::v4i32, N0); 6760 N0 = DAG.getNode(ISD::TRUNCATE, dl, MVT::v4i16, N0); 6761 return N0; 6762 } 6763 6764 static SDValue LowerADDC_ADDE_SUBC_SUBE(SDValue Op, SelectionDAG &DAG) { 6765 EVT VT = Op.getNode()->getValueType(0); 6766 SDVTList VTs = DAG.getVTList(VT, MVT::i32); 6767 6768 unsigned Opc; 6769 bool ExtraOp = false; 6770 switch (Op.getOpcode()) { 6771 default: llvm_unreachable("Invalid code"); 6772 case ISD::ADDC: Opc = ARMISD::ADDC; break; 6773 case ISD::ADDE: Opc = ARMISD::ADDE; ExtraOp = true; break; 6774 case ISD::SUBC: Opc = ARMISD::SUBC; break; 6775 case ISD::SUBE: Opc = ARMISD::SUBE; ExtraOp = true; break; 6776 } 6777 6778 if (!ExtraOp) 6779 return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0), 6780 Op.getOperand(1)); 6781 return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0), 6782 Op.getOperand(1), Op.getOperand(2)); 6783 } 6784 6785 SDValue ARMTargetLowering::LowerFSINCOS(SDValue Op, SelectionDAG &DAG) const { 6786 assert(Subtarget->isTargetDarwin()); 6787 6788 // For iOS, we want to call an alternative entry point: __sincos_stret, 6789 // return values are passed via sret. 6790 SDLoc dl(Op); 6791 SDValue Arg = Op.getOperand(0); 6792 EVT ArgVT = Arg.getValueType(); 6793 Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext()); 6794 auto PtrVT = getPointerTy(DAG.getDataLayout()); 6795 6796 MachineFrameInfo *FrameInfo = DAG.getMachineFunction().getFrameInfo(); 6797 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 6798 6799 // Pair of floats / doubles used to pass the result. 6800 Type *RetTy = StructType::get(ArgTy, ArgTy, nullptr); 6801 auto &DL = DAG.getDataLayout(); 6802 6803 ArgListTy Args; 6804 bool ShouldUseSRet = Subtarget->isAPCS_ABI(); 6805 SDValue SRet; 6806 if (ShouldUseSRet) { 6807 // Create stack object for sret. 6808 const uint64_t ByteSize = DL.getTypeAllocSize(RetTy); 6809 const unsigned StackAlign = DL.getPrefTypeAlignment(RetTy); 6810 int FrameIdx = FrameInfo->CreateStackObject(ByteSize, StackAlign, false); 6811 SRet = DAG.getFrameIndex(FrameIdx, TLI.getPointerTy(DL)); 6812 6813 ArgListEntry Entry; 6814 Entry.Node = SRet; 6815 Entry.Ty = RetTy->getPointerTo(); 6816 Entry.isSExt = false; 6817 Entry.isZExt = false; 6818 Entry.isSRet = true; 6819 Args.push_back(Entry); 6820 RetTy = Type::getVoidTy(*DAG.getContext()); 6821 } 6822 6823 ArgListEntry Entry; 6824 Entry.Node = Arg; 6825 Entry.Ty = ArgTy; 6826 Entry.isSExt = false; 6827 Entry.isZExt = false; 6828 Args.push_back(Entry); 6829 6830 const char *LibcallName = 6831 (ArgVT == MVT::f64) ? "__sincos_stret" : "__sincosf_stret"; 6832 RTLIB::Libcall LC = 6833 (ArgVT == MVT::f64) ? RTLIB::SINCOS_F64 : RTLIB::SINCOS_F32; 6834 CallingConv::ID CC = getLibcallCallingConv(LC); 6835 SDValue Callee = DAG.getExternalSymbol(LibcallName, getPointerTy(DL)); 6836 6837 TargetLowering::CallLoweringInfo CLI(DAG); 6838 CLI.setDebugLoc(dl) 6839 .setChain(DAG.getEntryNode()) 6840 .setCallee(CC, RetTy, Callee, std::move(Args), 0) 6841 .setDiscardResult(ShouldUseSRet); 6842 std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI); 6843 6844 if (!ShouldUseSRet) 6845 return CallResult.first; 6846 6847 SDValue LoadSin = DAG.getLoad(ArgVT, dl, CallResult.second, SRet, 6848 MachinePointerInfo(), false, false, false, 0); 6849 6850 // Address of cos field. 6851 SDValue Add = DAG.getNode(ISD::ADD, dl, PtrVT, SRet, 6852 DAG.getIntPtrConstant(ArgVT.getStoreSize(), dl)); 6853 SDValue LoadCos = DAG.getLoad(ArgVT, dl, LoadSin.getValue(1), Add, 6854 MachinePointerInfo(), false, false, false, 0); 6855 6856 SDVTList Tys = DAG.getVTList(ArgVT, ArgVT); 6857 return DAG.getNode(ISD::MERGE_VALUES, dl, Tys, 6858 LoadSin.getValue(0), LoadCos.getValue(0)); 6859 } 6860 6861 SDValue ARMTargetLowering::LowerWindowsDIVLibCall(SDValue Op, SelectionDAG &DAG, 6862 bool Signed, 6863 SDValue &Chain) const { 6864 EVT VT = Op.getValueType(); 6865 assert((VT == MVT::i32 || VT == MVT::i64) && 6866 "unexpected type for custom lowering DIV"); 6867 SDLoc dl(Op); 6868 6869 const auto &DL = DAG.getDataLayout(); 6870 const auto &TLI = DAG.getTargetLoweringInfo(); 6871 6872 const char *Name = nullptr; 6873 if (Signed) 6874 Name = (VT == MVT::i32) ? "__rt_sdiv" : "__rt_sdiv64"; 6875 else 6876 Name = (VT == MVT::i32) ? "__rt_udiv" : "__rt_udiv64"; 6877 6878 SDValue ES = DAG.getExternalSymbol(Name, TLI.getPointerTy(DL)); 6879 6880 ARMTargetLowering::ArgListTy Args; 6881 6882 for (auto AI : {1, 0}) { 6883 ArgListEntry Arg; 6884 Arg.Node = Op.getOperand(AI); 6885 Arg.Ty = Arg.Node.getValueType().getTypeForEVT(*DAG.getContext()); 6886 Args.push_back(Arg); 6887 } 6888 6889 CallLoweringInfo CLI(DAG); 6890 CLI.setDebugLoc(dl) 6891 .setChain(Chain) 6892 .setCallee(CallingConv::ARM_AAPCS_VFP, VT.getTypeForEVT(*DAG.getContext()), 6893 ES, std::move(Args), 0); 6894 6895 return LowerCallTo(CLI).first; 6896 } 6897 6898 SDValue ARMTargetLowering::LowerDIV_Windows(SDValue Op, SelectionDAG &DAG, 6899 bool Signed) const { 6900 assert(Op.getValueType() == MVT::i32 && 6901 "unexpected type for custom lowering DIV"); 6902 SDLoc dl(Op); 6903 6904 SDValue DBZCHK = DAG.getNode(ARMISD::WIN__DBZCHK, dl, MVT::Other, 6905 DAG.getEntryNode(), Op.getOperand(1)); 6906 6907 return LowerWindowsDIVLibCall(Op, DAG, Signed, DBZCHK); 6908 } 6909 6910 void ARMTargetLowering::ExpandDIV_Windows( 6911 SDValue Op, SelectionDAG &DAG, bool Signed, 6912 SmallVectorImpl<SDValue> &Results) const { 6913 const auto &DL = DAG.getDataLayout(); 6914 const auto &TLI = DAG.getTargetLoweringInfo(); 6915 6916 assert(Op.getValueType() == MVT::i64 && 6917 "unexpected type for custom lowering DIV"); 6918 SDLoc dl(Op); 6919 6920 SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, Op.getOperand(1), 6921 DAG.getConstant(0, dl, MVT::i32)); 6922 SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, Op.getOperand(1), 6923 DAG.getConstant(1, dl, MVT::i32)); 6924 SDValue Or = DAG.getNode(ISD::OR, dl, MVT::i32, Lo, Hi); 6925 6926 SDValue DBZCHK = 6927 DAG.getNode(ARMISD::WIN__DBZCHK, dl, MVT::Other, DAG.getEntryNode(), Or); 6928 6929 SDValue Result = LowerWindowsDIVLibCall(Op, DAG, Signed, DBZCHK); 6930 6931 SDValue Lower = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, Result); 6932 SDValue Upper = DAG.getNode(ISD::SRL, dl, MVT::i64, Result, 6933 DAG.getConstant(32, dl, TLI.getPointerTy(DL))); 6934 Upper = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, Upper); 6935 6936 Results.push_back(Lower); 6937 Results.push_back(Upper); 6938 } 6939 6940 static SDValue LowerAtomicLoadStore(SDValue Op, SelectionDAG &DAG) { 6941 if (isStrongerThanMonotonic(cast<AtomicSDNode>(Op)->getOrdering())) 6942 // Acquire/Release load/store is not legal for targets without a dmb or 6943 // equivalent available. 6944 return SDValue(); 6945 6946 // Monotonic load/store is legal for all targets. 6947 return Op; 6948 } 6949 6950 static void ReplaceREADCYCLECOUNTER(SDNode *N, 6951 SmallVectorImpl<SDValue> &Results, 6952 SelectionDAG &DAG, 6953 const ARMSubtarget *Subtarget) { 6954 SDLoc DL(N); 6955 // Under Power Management extensions, the cycle-count is: 6956 // mrc p15, #0, <Rt>, c9, c13, #0 6957 SDValue Ops[] = { N->getOperand(0), // Chain 6958 DAG.getConstant(Intrinsic::arm_mrc, DL, MVT::i32), 6959 DAG.getConstant(15, DL, MVT::i32), 6960 DAG.getConstant(0, DL, MVT::i32), 6961 DAG.getConstant(9, DL, MVT::i32), 6962 DAG.getConstant(13, DL, MVT::i32), 6963 DAG.getConstant(0, DL, MVT::i32) 6964 }; 6965 6966 SDValue Cycles32 = DAG.getNode(ISD::INTRINSIC_W_CHAIN, DL, 6967 DAG.getVTList(MVT::i32, MVT::Other), Ops); 6968 Results.push_back(DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, Cycles32, 6969 DAG.getConstant(0, DL, MVT::i32))); 6970 Results.push_back(Cycles32.getValue(1)); 6971 } 6972 6973 static SDValue createGPRPairNode(SelectionDAG &DAG, SDValue V) { 6974 SDLoc dl(V.getNode()); 6975 SDValue VLo = DAG.getAnyExtOrTrunc(V, dl, MVT::i32); 6976 SDValue VHi = DAG.getAnyExtOrTrunc( 6977 DAG.getNode(ISD::SRL, dl, MVT::i64, V, DAG.getConstant(32, dl, MVT::i32)), 6978 dl, MVT::i32); 6979 SDValue RegClass = 6980 DAG.getTargetConstant(ARM::GPRPairRegClassID, dl, MVT::i32); 6981 SDValue SubReg0 = DAG.getTargetConstant(ARM::gsub_0, dl, MVT::i32); 6982 SDValue SubReg1 = DAG.getTargetConstant(ARM::gsub_1, dl, MVT::i32); 6983 const SDValue Ops[] = { RegClass, VLo, SubReg0, VHi, SubReg1 }; 6984 return SDValue( 6985 DAG.getMachineNode(TargetOpcode::REG_SEQUENCE, dl, MVT::Untyped, Ops), 0); 6986 } 6987 6988 static void ReplaceCMP_SWAP_64Results(SDNode *N, 6989 SmallVectorImpl<SDValue> & Results, 6990 SelectionDAG &DAG) { 6991 assert(N->getValueType(0) == MVT::i64 && 6992 "AtomicCmpSwap on types less than 64 should be legal"); 6993 SDValue Ops[] = {N->getOperand(1), 6994 createGPRPairNode(DAG, N->getOperand(2)), 6995 createGPRPairNode(DAG, N->getOperand(3)), 6996 N->getOperand(0)}; 6997 SDNode *CmpSwap = DAG.getMachineNode( 6998 ARM::CMP_SWAP_64, SDLoc(N), 6999 DAG.getVTList(MVT::Untyped, MVT::i32, MVT::Other), Ops); 7000 7001 MachineFunction &MF = DAG.getMachineFunction(); 7002 MachineSDNode::mmo_iterator MemOp = MF.allocateMemRefsArray(1); 7003 MemOp[0] = cast<MemSDNode>(N)->getMemOperand(); 7004 cast<MachineSDNode>(CmpSwap)->setMemRefs(MemOp, MemOp + 1); 7005 7006 Results.push_back(DAG.getTargetExtractSubreg(ARM::gsub_0, SDLoc(N), MVT::i32, 7007 SDValue(CmpSwap, 0))); 7008 Results.push_back(DAG.getTargetExtractSubreg(ARM::gsub_1, SDLoc(N), MVT::i32, 7009 SDValue(CmpSwap, 0))); 7010 Results.push_back(SDValue(CmpSwap, 2)); 7011 } 7012 7013 SDValue ARMTargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const { 7014 switch (Op.getOpcode()) { 7015 default: llvm_unreachable("Don't know how to custom lower this!"); 7016 case ISD::WRITE_REGISTER: return LowerWRITE_REGISTER(Op, DAG); 7017 case ISD::ConstantPool: return LowerConstantPool(Op, DAG); 7018 case ISD::BlockAddress: return LowerBlockAddress(Op, DAG); 7019 case ISD::GlobalAddress: 7020 switch (Subtarget->getTargetTriple().getObjectFormat()) { 7021 default: llvm_unreachable("unknown object format"); 7022 case Triple::COFF: 7023 return LowerGlobalAddressWindows(Op, DAG); 7024 case Triple::ELF: 7025 return LowerGlobalAddressELF(Op, DAG); 7026 case Triple::MachO: 7027 return LowerGlobalAddressDarwin(Op, DAG); 7028 } 7029 case ISD::GlobalTLSAddress: return LowerGlobalTLSAddress(Op, DAG); 7030 case ISD::SELECT: return LowerSELECT(Op, DAG); 7031 case ISD::SELECT_CC: return LowerSELECT_CC(Op, DAG); 7032 case ISD::BR_CC: return LowerBR_CC(Op, DAG); 7033 case ISD::BR_JT: return LowerBR_JT(Op, DAG); 7034 case ISD::VASTART: return LowerVASTART(Op, DAG); 7035 case ISD::ATOMIC_FENCE: return LowerATOMIC_FENCE(Op, DAG, Subtarget); 7036 case ISD::PREFETCH: return LowerPREFETCH(Op, DAG, Subtarget); 7037 case ISD::SINT_TO_FP: 7038 case ISD::UINT_TO_FP: return LowerINT_TO_FP(Op, DAG); 7039 case ISD::FP_TO_SINT: 7040 case ISD::FP_TO_UINT: return LowerFP_TO_INT(Op, DAG); 7041 case ISD::FCOPYSIGN: return LowerFCOPYSIGN(Op, DAG); 7042 case ISD::RETURNADDR: return LowerRETURNADDR(Op, DAG); 7043 case ISD::FRAMEADDR: return LowerFRAMEADDR(Op, DAG); 7044 case ISD::EH_SJLJ_SETJMP: return LowerEH_SJLJ_SETJMP(Op, DAG); 7045 case ISD::EH_SJLJ_LONGJMP: return LowerEH_SJLJ_LONGJMP(Op, DAG); 7046 case ISD::EH_SJLJ_SETUP_DISPATCH: return LowerEH_SJLJ_SETUP_DISPATCH(Op, DAG); 7047 case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG, 7048 Subtarget); 7049 case ISD::BITCAST: return ExpandBITCAST(Op.getNode(), DAG); 7050 case ISD::SHL: 7051 case ISD::SRL: 7052 case ISD::SRA: return LowerShift(Op.getNode(), DAG, Subtarget); 7053 case ISD::SREM: return LowerREM(Op.getNode(), DAG); 7054 case ISD::UREM: return LowerREM(Op.getNode(), DAG); 7055 case ISD::SHL_PARTS: return LowerShiftLeftParts(Op, DAG); 7056 case ISD::SRL_PARTS: 7057 case ISD::SRA_PARTS: return LowerShiftRightParts(Op, DAG); 7058 case ISD::CTTZ: 7059 case ISD::CTTZ_ZERO_UNDEF: return LowerCTTZ(Op.getNode(), DAG, Subtarget); 7060 case ISD::CTPOP: return LowerCTPOP(Op.getNode(), DAG, Subtarget); 7061 case ISD::SETCC: return LowerVSETCC(Op, DAG); 7062 case ISD::SETCCE: return LowerSETCCE(Op, DAG); 7063 case ISD::ConstantFP: return LowerConstantFP(Op, DAG, Subtarget); 7064 case ISD::BUILD_VECTOR: return LowerBUILD_VECTOR(Op, DAG, Subtarget); 7065 case ISD::VECTOR_SHUFFLE: return LowerVECTOR_SHUFFLE(Op, DAG); 7066 case ISD::INSERT_VECTOR_ELT: return LowerINSERT_VECTOR_ELT(Op, DAG); 7067 case ISD::EXTRACT_VECTOR_ELT: return LowerEXTRACT_VECTOR_ELT(Op, DAG); 7068 case ISD::CONCAT_VECTORS: return LowerCONCAT_VECTORS(Op, DAG); 7069 case ISD::FLT_ROUNDS_: return LowerFLT_ROUNDS_(Op, DAG); 7070 case ISD::MUL: return LowerMUL(Op, DAG); 7071 case ISD::SDIV: 7072 if (Subtarget->isTargetWindows()) 7073 return LowerDIV_Windows(Op, DAG, /* Signed */ true); 7074 return LowerSDIV(Op, DAG); 7075 case ISD::UDIV: 7076 if (Subtarget->isTargetWindows()) 7077 return LowerDIV_Windows(Op, DAG, /* Signed */ false); 7078 return LowerUDIV(Op, DAG); 7079 case ISD::ADDC: 7080 case ISD::ADDE: 7081 case ISD::SUBC: 7082 case ISD::SUBE: return LowerADDC_ADDE_SUBC_SUBE(Op, DAG); 7083 case ISD::SADDO: 7084 case ISD::UADDO: 7085 case ISD::SSUBO: 7086 case ISD::USUBO: 7087 return LowerXALUO(Op, DAG); 7088 case ISD::ATOMIC_LOAD: 7089 case ISD::ATOMIC_STORE: return LowerAtomicLoadStore(Op, DAG); 7090 case ISD::FSINCOS: return LowerFSINCOS(Op, DAG); 7091 case ISD::SDIVREM: 7092 case ISD::UDIVREM: return LowerDivRem(Op, DAG); 7093 case ISD::DYNAMIC_STACKALLOC: 7094 if (Subtarget->getTargetTriple().isWindowsItaniumEnvironment()) 7095 return LowerDYNAMIC_STACKALLOC(Op, DAG); 7096 llvm_unreachable("Don't know how to custom lower this!"); 7097 case ISD::FP_ROUND: return LowerFP_ROUND(Op, DAG); 7098 case ISD::FP_EXTEND: return LowerFP_EXTEND(Op, DAG); 7099 case ARMISD::WIN__DBZCHK: return SDValue(); 7100 } 7101 } 7102 7103 /// ReplaceNodeResults - Replace the results of node with an illegal result 7104 /// type with new values built out of custom code. 7105 void ARMTargetLowering::ReplaceNodeResults(SDNode *N, 7106 SmallVectorImpl<SDValue> &Results, 7107 SelectionDAG &DAG) const { 7108 SDValue Res; 7109 switch (N->getOpcode()) { 7110 default: 7111 llvm_unreachable("Don't know how to custom expand this!"); 7112 case ISD::READ_REGISTER: 7113 ExpandREAD_REGISTER(N, Results, DAG); 7114 break; 7115 case ISD::BITCAST: 7116 Res = ExpandBITCAST(N, DAG); 7117 break; 7118 case ISD::SRL: 7119 case ISD::SRA: 7120 Res = Expand64BitShift(N, DAG, Subtarget); 7121 break; 7122 case ISD::SREM: 7123 case ISD::UREM: 7124 Res = LowerREM(N, DAG); 7125 break; 7126 case ISD::SDIVREM: 7127 case ISD::UDIVREM: 7128 Res = LowerDivRem(SDValue(N, 0), DAG); 7129 assert(Res.getNumOperands() == 2 && "DivRem needs two values"); 7130 Results.push_back(Res.getValue(0)); 7131 Results.push_back(Res.getValue(1)); 7132 return; 7133 case ISD::READCYCLECOUNTER: 7134 ReplaceREADCYCLECOUNTER(N, Results, DAG, Subtarget); 7135 return; 7136 case ISD::UDIV: 7137 case ISD::SDIV: 7138 assert(Subtarget->isTargetWindows() && "can only expand DIV on Windows"); 7139 return ExpandDIV_Windows(SDValue(N, 0), DAG, N->getOpcode() == ISD::SDIV, 7140 Results); 7141 case ISD::ATOMIC_CMP_SWAP: 7142 ReplaceCMP_SWAP_64Results(N, Results, DAG); 7143 return; 7144 } 7145 if (Res.getNode()) 7146 Results.push_back(Res); 7147 } 7148 7149 //===----------------------------------------------------------------------===// 7150 // ARM Scheduler Hooks 7151 //===----------------------------------------------------------------------===// 7152 7153 /// SetupEntryBlockForSjLj - Insert code into the entry block that creates and 7154 /// registers the function context. 7155 void ARMTargetLowering:: 7156 SetupEntryBlockForSjLj(MachineInstr *MI, MachineBasicBlock *MBB, 7157 MachineBasicBlock *DispatchBB, int FI) const { 7158 const TargetInstrInfo *TII = Subtarget->getInstrInfo(); 7159 DebugLoc dl = MI->getDebugLoc(); 7160 MachineFunction *MF = MBB->getParent(); 7161 MachineRegisterInfo *MRI = &MF->getRegInfo(); 7162 MachineConstantPool *MCP = MF->getConstantPool(); 7163 ARMFunctionInfo *AFI = MF->getInfo<ARMFunctionInfo>(); 7164 const Function *F = MF->getFunction(); 7165 7166 bool isThumb = Subtarget->isThumb(); 7167 bool isThumb2 = Subtarget->isThumb2(); 7168 7169 unsigned PCLabelId = AFI->createPICLabelUId(); 7170 unsigned PCAdj = (isThumb || isThumb2) ? 4 : 8; 7171 ARMConstantPoolValue *CPV = 7172 ARMConstantPoolMBB::Create(F->getContext(), DispatchBB, PCLabelId, PCAdj); 7173 unsigned CPI = MCP->getConstantPoolIndex(CPV, 4); 7174 7175 const TargetRegisterClass *TRC = isThumb ? &ARM::tGPRRegClass 7176 : &ARM::GPRRegClass; 7177 7178 // Grab constant pool and fixed stack memory operands. 7179 MachineMemOperand *CPMMO = 7180 MF->getMachineMemOperand(MachinePointerInfo::getConstantPool(*MF), 7181 MachineMemOperand::MOLoad, 4, 4); 7182 7183 MachineMemOperand *FIMMOSt = 7184 MF->getMachineMemOperand(MachinePointerInfo::getFixedStack(*MF, FI), 7185 MachineMemOperand::MOStore, 4, 4); 7186 7187 // Load the address of the dispatch MBB into the jump buffer. 7188 if (isThumb2) { 7189 // Incoming value: jbuf 7190 // ldr.n r5, LCPI1_1 7191 // orr r5, r5, #1 7192 // add r5, pc 7193 // str r5, [$jbuf, #+4] ; &jbuf[1] 7194 unsigned NewVReg1 = MRI->createVirtualRegister(TRC); 7195 AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::t2LDRpci), NewVReg1) 7196 .addConstantPoolIndex(CPI) 7197 .addMemOperand(CPMMO)); 7198 // Set the low bit because of thumb mode. 7199 unsigned NewVReg2 = MRI->createVirtualRegister(TRC); 7200 AddDefaultCC( 7201 AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::t2ORRri), NewVReg2) 7202 .addReg(NewVReg1, RegState::Kill) 7203 .addImm(0x01))); 7204 unsigned NewVReg3 = MRI->createVirtualRegister(TRC); 7205 BuildMI(*MBB, MI, dl, TII->get(ARM::tPICADD), NewVReg3) 7206 .addReg(NewVReg2, RegState::Kill) 7207 .addImm(PCLabelId); 7208 AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::t2STRi12)) 7209 .addReg(NewVReg3, RegState::Kill) 7210 .addFrameIndex(FI) 7211 .addImm(36) // &jbuf[1] :: pc 7212 .addMemOperand(FIMMOSt)); 7213 } else if (isThumb) { 7214 // Incoming value: jbuf 7215 // ldr.n r1, LCPI1_4 7216 // add r1, pc 7217 // mov r2, #1 7218 // orrs r1, r2 7219 // add r2, $jbuf, #+4 ; &jbuf[1] 7220 // str r1, [r2] 7221 unsigned NewVReg1 = MRI->createVirtualRegister(TRC); 7222 AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::tLDRpci), NewVReg1) 7223 .addConstantPoolIndex(CPI) 7224 .addMemOperand(CPMMO)); 7225 unsigned NewVReg2 = MRI->createVirtualRegister(TRC); 7226 BuildMI(*MBB, MI, dl, TII->get(ARM::tPICADD), NewVReg2) 7227 .addReg(NewVReg1, RegState::Kill) 7228 .addImm(PCLabelId); 7229 // Set the low bit because of thumb mode. 7230 unsigned NewVReg3 = MRI->createVirtualRegister(TRC); 7231 AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::tMOVi8), NewVReg3) 7232 .addReg(ARM::CPSR, RegState::Define) 7233 .addImm(1)); 7234 unsigned NewVReg4 = MRI->createVirtualRegister(TRC); 7235 AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::tORR), NewVReg4) 7236 .addReg(ARM::CPSR, RegState::Define) 7237 .addReg(NewVReg2, RegState::Kill) 7238 .addReg(NewVReg3, RegState::Kill)); 7239 unsigned NewVReg5 = MRI->createVirtualRegister(TRC); 7240 BuildMI(*MBB, MI, dl, TII->get(ARM::tADDframe), NewVReg5) 7241 .addFrameIndex(FI) 7242 .addImm(36); // &jbuf[1] :: pc 7243 AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::tSTRi)) 7244 .addReg(NewVReg4, RegState::Kill) 7245 .addReg(NewVReg5, RegState::Kill) 7246 .addImm(0) 7247 .addMemOperand(FIMMOSt)); 7248 } else { 7249 // Incoming value: jbuf 7250 // ldr r1, LCPI1_1 7251 // add r1, pc, r1 7252 // str r1, [$jbuf, #+4] ; &jbuf[1] 7253 unsigned NewVReg1 = MRI->createVirtualRegister(TRC); 7254 AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::LDRi12), NewVReg1) 7255 .addConstantPoolIndex(CPI) 7256 .addImm(0) 7257 .addMemOperand(CPMMO)); 7258 unsigned NewVReg2 = MRI->createVirtualRegister(TRC); 7259 AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::PICADD), NewVReg2) 7260 .addReg(NewVReg1, RegState::Kill) 7261 .addImm(PCLabelId)); 7262 AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::STRi12)) 7263 .addReg(NewVReg2, RegState::Kill) 7264 .addFrameIndex(FI) 7265 .addImm(36) // &jbuf[1] :: pc 7266 .addMemOperand(FIMMOSt)); 7267 } 7268 } 7269 7270 void ARMTargetLowering::EmitSjLjDispatchBlock(MachineInstr *MI, 7271 MachineBasicBlock *MBB) const { 7272 const TargetInstrInfo *TII = Subtarget->getInstrInfo(); 7273 DebugLoc dl = MI->getDebugLoc(); 7274 MachineFunction *MF = MBB->getParent(); 7275 MachineRegisterInfo *MRI = &MF->getRegInfo(); 7276 MachineFrameInfo *MFI = MF->getFrameInfo(); 7277 int FI = MFI->getFunctionContextIndex(); 7278 7279 const TargetRegisterClass *TRC = Subtarget->isThumb() ? &ARM::tGPRRegClass 7280 : &ARM::GPRnopcRegClass; 7281 7282 // Get a mapping of the call site numbers to all of the landing pads they're 7283 // associated with. 7284 DenseMap<unsigned, SmallVector<MachineBasicBlock*, 2> > CallSiteNumToLPad; 7285 unsigned MaxCSNum = 0; 7286 MachineModuleInfo &MMI = MF->getMMI(); 7287 for (MachineFunction::iterator BB = MF->begin(), E = MF->end(); BB != E; 7288 ++BB) { 7289 if (!BB->isEHPad()) continue; 7290 7291 // FIXME: We should assert that the EH_LABEL is the first MI in the landing 7292 // pad. 7293 for (MachineBasicBlock::iterator 7294 II = BB->begin(), IE = BB->end(); II != IE; ++II) { 7295 if (!II->isEHLabel()) continue; 7296 7297 MCSymbol *Sym = II->getOperand(0).getMCSymbol(); 7298 if (!MMI.hasCallSiteLandingPad(Sym)) continue; 7299 7300 SmallVectorImpl<unsigned> &CallSiteIdxs = MMI.getCallSiteLandingPad(Sym); 7301 for (SmallVectorImpl<unsigned>::iterator 7302 CSI = CallSiteIdxs.begin(), CSE = CallSiteIdxs.end(); 7303 CSI != CSE; ++CSI) { 7304 CallSiteNumToLPad[*CSI].push_back(&*BB); 7305 MaxCSNum = std::max(MaxCSNum, *CSI); 7306 } 7307 break; 7308 } 7309 } 7310 7311 // Get an ordered list of the machine basic blocks for the jump table. 7312 std::vector<MachineBasicBlock*> LPadList; 7313 SmallPtrSet<MachineBasicBlock*, 32> InvokeBBs; 7314 LPadList.reserve(CallSiteNumToLPad.size()); 7315 for (unsigned I = 1; I <= MaxCSNum; ++I) { 7316 SmallVectorImpl<MachineBasicBlock*> &MBBList = CallSiteNumToLPad[I]; 7317 for (SmallVectorImpl<MachineBasicBlock*>::iterator 7318 II = MBBList.begin(), IE = MBBList.end(); II != IE; ++II) { 7319 LPadList.push_back(*II); 7320 InvokeBBs.insert((*II)->pred_begin(), (*II)->pred_end()); 7321 } 7322 } 7323 7324 assert(!LPadList.empty() && 7325 "No landing pad destinations for the dispatch jump table!"); 7326 7327 // Create the jump table and associated information. 7328 MachineJumpTableInfo *JTI = 7329 MF->getOrCreateJumpTableInfo(MachineJumpTableInfo::EK_Inline); 7330 unsigned MJTI = JTI->createJumpTableIndex(LPadList); 7331 Reloc::Model RelocM = getTargetMachine().getRelocationModel(); 7332 7333 // Create the MBBs for the dispatch code. 7334 7335 // Shove the dispatch's address into the return slot in the function context. 7336 MachineBasicBlock *DispatchBB = MF->CreateMachineBasicBlock(); 7337 DispatchBB->setIsEHPad(); 7338 7339 MachineBasicBlock *TrapBB = MF->CreateMachineBasicBlock(); 7340 unsigned trap_opcode; 7341 if (Subtarget->isThumb()) 7342 trap_opcode = ARM::tTRAP; 7343 else 7344 trap_opcode = Subtarget->useNaClTrap() ? ARM::TRAPNaCl : ARM::TRAP; 7345 7346 BuildMI(TrapBB, dl, TII->get(trap_opcode)); 7347 DispatchBB->addSuccessor(TrapBB); 7348 7349 MachineBasicBlock *DispContBB = MF->CreateMachineBasicBlock(); 7350 DispatchBB->addSuccessor(DispContBB); 7351 7352 // Insert and MBBs. 7353 MF->insert(MF->end(), DispatchBB); 7354 MF->insert(MF->end(), DispContBB); 7355 MF->insert(MF->end(), TrapBB); 7356 7357 // Insert code into the entry block that creates and registers the function 7358 // context. 7359 SetupEntryBlockForSjLj(MI, MBB, DispatchBB, FI); 7360 7361 MachineMemOperand *FIMMOLd = MF->getMachineMemOperand( 7362 MachinePointerInfo::getFixedStack(*MF, FI), 7363 MachineMemOperand::MOLoad | MachineMemOperand::MOVolatile, 4, 4); 7364 7365 MachineInstrBuilder MIB; 7366 MIB = BuildMI(DispatchBB, dl, TII->get(ARM::Int_eh_sjlj_dispatchsetup)); 7367 7368 const ARMBaseInstrInfo *AII = static_cast<const ARMBaseInstrInfo*>(TII); 7369 const ARMBaseRegisterInfo &RI = AII->getRegisterInfo(); 7370 7371 // Add a register mask with no preserved registers. This results in all 7372 // registers being marked as clobbered. 7373 MIB.addRegMask(RI.getNoPreservedMask()); 7374 7375 unsigned NumLPads = LPadList.size(); 7376 if (Subtarget->isThumb2()) { 7377 unsigned NewVReg1 = MRI->createVirtualRegister(TRC); 7378 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::t2LDRi12), NewVReg1) 7379 .addFrameIndex(FI) 7380 .addImm(4) 7381 .addMemOperand(FIMMOLd)); 7382 7383 if (NumLPads < 256) { 7384 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::t2CMPri)) 7385 .addReg(NewVReg1) 7386 .addImm(LPadList.size())); 7387 } else { 7388 unsigned VReg1 = MRI->createVirtualRegister(TRC); 7389 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::t2MOVi16), VReg1) 7390 .addImm(NumLPads & 0xFFFF)); 7391 7392 unsigned VReg2 = VReg1; 7393 if ((NumLPads & 0xFFFF0000) != 0) { 7394 VReg2 = MRI->createVirtualRegister(TRC); 7395 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::t2MOVTi16), VReg2) 7396 .addReg(VReg1) 7397 .addImm(NumLPads >> 16)); 7398 } 7399 7400 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::t2CMPrr)) 7401 .addReg(NewVReg1) 7402 .addReg(VReg2)); 7403 } 7404 7405 BuildMI(DispatchBB, dl, TII->get(ARM::t2Bcc)) 7406 .addMBB(TrapBB) 7407 .addImm(ARMCC::HI) 7408 .addReg(ARM::CPSR); 7409 7410 unsigned NewVReg3 = MRI->createVirtualRegister(TRC); 7411 AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::t2LEApcrelJT),NewVReg3) 7412 .addJumpTableIndex(MJTI)); 7413 7414 unsigned NewVReg4 = MRI->createVirtualRegister(TRC); 7415 AddDefaultCC( 7416 AddDefaultPred( 7417 BuildMI(DispContBB, dl, TII->get(ARM::t2ADDrs), NewVReg4) 7418 .addReg(NewVReg3, RegState::Kill) 7419 .addReg(NewVReg1) 7420 .addImm(ARM_AM::getSORegOpc(ARM_AM::lsl, 2)))); 7421 7422 BuildMI(DispContBB, dl, TII->get(ARM::t2BR_JT)) 7423 .addReg(NewVReg4, RegState::Kill) 7424 .addReg(NewVReg1) 7425 .addJumpTableIndex(MJTI); 7426 } else if (Subtarget->isThumb()) { 7427 unsigned NewVReg1 = MRI->createVirtualRegister(TRC); 7428 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::tLDRspi), NewVReg1) 7429 .addFrameIndex(FI) 7430 .addImm(1) 7431 .addMemOperand(FIMMOLd)); 7432 7433 if (NumLPads < 256) { 7434 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::tCMPi8)) 7435 .addReg(NewVReg1) 7436 .addImm(NumLPads)); 7437 } else { 7438 MachineConstantPool *ConstantPool = MF->getConstantPool(); 7439 Type *Int32Ty = Type::getInt32Ty(MF->getFunction()->getContext()); 7440 const Constant *C = ConstantInt::get(Int32Ty, NumLPads); 7441 7442 // MachineConstantPool wants an explicit alignment. 7443 unsigned Align = MF->getDataLayout().getPrefTypeAlignment(Int32Ty); 7444 if (Align == 0) 7445 Align = MF->getDataLayout().getTypeAllocSize(C->getType()); 7446 unsigned Idx = ConstantPool->getConstantPoolIndex(C, Align); 7447 7448 unsigned VReg1 = MRI->createVirtualRegister(TRC); 7449 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::tLDRpci)) 7450 .addReg(VReg1, RegState::Define) 7451 .addConstantPoolIndex(Idx)); 7452 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::tCMPr)) 7453 .addReg(NewVReg1) 7454 .addReg(VReg1)); 7455 } 7456 7457 BuildMI(DispatchBB, dl, TII->get(ARM::tBcc)) 7458 .addMBB(TrapBB) 7459 .addImm(ARMCC::HI) 7460 .addReg(ARM::CPSR); 7461 7462 unsigned NewVReg2 = MRI->createVirtualRegister(TRC); 7463 AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::tLSLri), NewVReg2) 7464 .addReg(ARM::CPSR, RegState::Define) 7465 .addReg(NewVReg1) 7466 .addImm(2)); 7467 7468 unsigned NewVReg3 = MRI->createVirtualRegister(TRC); 7469 AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::tLEApcrelJT), NewVReg3) 7470 .addJumpTableIndex(MJTI)); 7471 7472 unsigned NewVReg4 = MRI->createVirtualRegister(TRC); 7473 AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::tADDrr), NewVReg4) 7474 .addReg(ARM::CPSR, RegState::Define) 7475 .addReg(NewVReg2, RegState::Kill) 7476 .addReg(NewVReg3)); 7477 7478 MachineMemOperand *JTMMOLd = MF->getMachineMemOperand( 7479 MachinePointerInfo::getJumpTable(*MF), MachineMemOperand::MOLoad, 4, 4); 7480 7481 unsigned NewVReg5 = MRI->createVirtualRegister(TRC); 7482 AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::tLDRi), NewVReg5) 7483 .addReg(NewVReg4, RegState::Kill) 7484 .addImm(0) 7485 .addMemOperand(JTMMOLd)); 7486 7487 unsigned NewVReg6 = NewVReg5; 7488 if (RelocM == Reloc::PIC_) { 7489 NewVReg6 = MRI->createVirtualRegister(TRC); 7490 AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::tADDrr), NewVReg6) 7491 .addReg(ARM::CPSR, RegState::Define) 7492 .addReg(NewVReg5, RegState::Kill) 7493 .addReg(NewVReg3)); 7494 } 7495 7496 BuildMI(DispContBB, dl, TII->get(ARM::tBR_JTr)) 7497 .addReg(NewVReg6, RegState::Kill) 7498 .addJumpTableIndex(MJTI); 7499 } else { 7500 unsigned NewVReg1 = MRI->createVirtualRegister(TRC); 7501 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::LDRi12), NewVReg1) 7502 .addFrameIndex(FI) 7503 .addImm(4) 7504 .addMemOperand(FIMMOLd)); 7505 7506 if (NumLPads < 256) { 7507 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::CMPri)) 7508 .addReg(NewVReg1) 7509 .addImm(NumLPads)); 7510 } else if (Subtarget->hasV6T2Ops() && isUInt<16>(NumLPads)) { 7511 unsigned VReg1 = MRI->createVirtualRegister(TRC); 7512 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::MOVi16), VReg1) 7513 .addImm(NumLPads & 0xFFFF)); 7514 7515 unsigned VReg2 = VReg1; 7516 if ((NumLPads & 0xFFFF0000) != 0) { 7517 VReg2 = MRI->createVirtualRegister(TRC); 7518 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::MOVTi16), VReg2) 7519 .addReg(VReg1) 7520 .addImm(NumLPads >> 16)); 7521 } 7522 7523 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::CMPrr)) 7524 .addReg(NewVReg1) 7525 .addReg(VReg2)); 7526 } else { 7527 MachineConstantPool *ConstantPool = MF->getConstantPool(); 7528 Type *Int32Ty = Type::getInt32Ty(MF->getFunction()->getContext()); 7529 const Constant *C = ConstantInt::get(Int32Ty, NumLPads); 7530 7531 // MachineConstantPool wants an explicit alignment. 7532 unsigned Align = MF->getDataLayout().getPrefTypeAlignment(Int32Ty); 7533 if (Align == 0) 7534 Align = MF->getDataLayout().getTypeAllocSize(C->getType()); 7535 unsigned Idx = ConstantPool->getConstantPoolIndex(C, Align); 7536 7537 unsigned VReg1 = MRI->createVirtualRegister(TRC); 7538 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::LDRcp)) 7539 .addReg(VReg1, RegState::Define) 7540 .addConstantPoolIndex(Idx) 7541 .addImm(0)); 7542 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::CMPrr)) 7543 .addReg(NewVReg1) 7544 .addReg(VReg1, RegState::Kill)); 7545 } 7546 7547 BuildMI(DispatchBB, dl, TII->get(ARM::Bcc)) 7548 .addMBB(TrapBB) 7549 .addImm(ARMCC::HI) 7550 .addReg(ARM::CPSR); 7551 7552 unsigned NewVReg3 = MRI->createVirtualRegister(TRC); 7553 AddDefaultCC( 7554 AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::MOVsi), NewVReg3) 7555 .addReg(NewVReg1) 7556 .addImm(ARM_AM::getSORegOpc(ARM_AM::lsl, 2)))); 7557 unsigned NewVReg4 = MRI->createVirtualRegister(TRC); 7558 AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::LEApcrelJT), NewVReg4) 7559 .addJumpTableIndex(MJTI)); 7560 7561 MachineMemOperand *JTMMOLd = MF->getMachineMemOperand( 7562 MachinePointerInfo::getJumpTable(*MF), MachineMemOperand::MOLoad, 4, 4); 7563 unsigned NewVReg5 = MRI->createVirtualRegister(TRC); 7564 AddDefaultPred( 7565 BuildMI(DispContBB, dl, TII->get(ARM::LDRrs), NewVReg5) 7566 .addReg(NewVReg3, RegState::Kill) 7567 .addReg(NewVReg4) 7568 .addImm(0) 7569 .addMemOperand(JTMMOLd)); 7570 7571 if (RelocM == Reloc::PIC_) { 7572 BuildMI(DispContBB, dl, TII->get(ARM::BR_JTadd)) 7573 .addReg(NewVReg5, RegState::Kill) 7574 .addReg(NewVReg4) 7575 .addJumpTableIndex(MJTI); 7576 } else { 7577 BuildMI(DispContBB, dl, TII->get(ARM::BR_JTr)) 7578 .addReg(NewVReg5, RegState::Kill) 7579 .addJumpTableIndex(MJTI); 7580 } 7581 } 7582 7583 // Add the jump table entries as successors to the MBB. 7584 SmallPtrSet<MachineBasicBlock*, 8> SeenMBBs; 7585 for (std::vector<MachineBasicBlock*>::iterator 7586 I = LPadList.begin(), E = LPadList.end(); I != E; ++I) { 7587 MachineBasicBlock *CurMBB = *I; 7588 if (SeenMBBs.insert(CurMBB).second) 7589 DispContBB->addSuccessor(CurMBB); 7590 } 7591 7592 // N.B. the order the invoke BBs are processed in doesn't matter here. 7593 const MCPhysReg *SavedRegs = RI.getCalleeSavedRegs(MF); 7594 SmallVector<MachineBasicBlock*, 64> MBBLPads; 7595 for (MachineBasicBlock *BB : InvokeBBs) { 7596 7597 // Remove the landing pad successor from the invoke block and replace it 7598 // with the new dispatch block. 7599 SmallVector<MachineBasicBlock*, 4> Successors(BB->succ_begin(), 7600 BB->succ_end()); 7601 while (!Successors.empty()) { 7602 MachineBasicBlock *SMBB = Successors.pop_back_val(); 7603 if (SMBB->isEHPad()) { 7604 BB->removeSuccessor(SMBB); 7605 MBBLPads.push_back(SMBB); 7606 } 7607 } 7608 7609 BB->addSuccessor(DispatchBB, BranchProbability::getZero()); 7610 BB->normalizeSuccProbs(); 7611 7612 // Find the invoke call and mark all of the callee-saved registers as 7613 // 'implicit defined' so that they're spilled. This prevents code from 7614 // moving instructions to before the EH block, where they will never be 7615 // executed. 7616 for (MachineBasicBlock::reverse_iterator 7617 II = BB->rbegin(), IE = BB->rend(); II != IE; ++II) { 7618 if (!II->isCall()) continue; 7619 7620 DenseMap<unsigned, bool> DefRegs; 7621 for (MachineInstr::mop_iterator 7622 OI = II->operands_begin(), OE = II->operands_end(); 7623 OI != OE; ++OI) { 7624 if (!OI->isReg()) continue; 7625 DefRegs[OI->getReg()] = true; 7626 } 7627 7628 MachineInstrBuilder MIB(*MF, &*II); 7629 7630 for (unsigned i = 0; SavedRegs[i] != 0; ++i) { 7631 unsigned Reg = SavedRegs[i]; 7632 if (Subtarget->isThumb2() && 7633 !ARM::tGPRRegClass.contains(Reg) && 7634 !ARM::hGPRRegClass.contains(Reg)) 7635 continue; 7636 if (Subtarget->isThumb1Only() && !ARM::tGPRRegClass.contains(Reg)) 7637 continue; 7638 if (!Subtarget->isThumb() && !ARM::GPRRegClass.contains(Reg)) 7639 continue; 7640 if (!DefRegs[Reg]) 7641 MIB.addReg(Reg, RegState::ImplicitDefine | RegState::Dead); 7642 } 7643 7644 break; 7645 } 7646 } 7647 7648 // Mark all former landing pads as non-landing pads. The dispatch is the only 7649 // landing pad now. 7650 for (SmallVectorImpl<MachineBasicBlock*>::iterator 7651 I = MBBLPads.begin(), E = MBBLPads.end(); I != E; ++I) 7652 (*I)->setIsEHPad(false); 7653 7654 // The instruction is gone now. 7655 MI->eraseFromParent(); 7656 } 7657 7658 static 7659 MachineBasicBlock *OtherSucc(MachineBasicBlock *MBB, MachineBasicBlock *Succ) { 7660 for (MachineBasicBlock::succ_iterator I = MBB->succ_begin(), 7661 E = MBB->succ_end(); I != E; ++I) 7662 if (*I != Succ) 7663 return *I; 7664 llvm_unreachable("Expecting a BB with two successors!"); 7665 } 7666 7667 /// Return the load opcode for a given load size. If load size >= 8, 7668 /// neon opcode will be returned. 7669 static unsigned getLdOpcode(unsigned LdSize, bool IsThumb1, bool IsThumb2) { 7670 if (LdSize >= 8) 7671 return LdSize == 16 ? ARM::VLD1q32wb_fixed 7672 : LdSize == 8 ? ARM::VLD1d32wb_fixed : 0; 7673 if (IsThumb1) 7674 return LdSize == 4 ? ARM::tLDRi 7675 : LdSize == 2 ? ARM::tLDRHi 7676 : LdSize == 1 ? ARM::tLDRBi : 0; 7677 if (IsThumb2) 7678 return LdSize == 4 ? ARM::t2LDR_POST 7679 : LdSize == 2 ? ARM::t2LDRH_POST 7680 : LdSize == 1 ? ARM::t2LDRB_POST : 0; 7681 return LdSize == 4 ? ARM::LDR_POST_IMM 7682 : LdSize == 2 ? ARM::LDRH_POST 7683 : LdSize == 1 ? ARM::LDRB_POST_IMM : 0; 7684 } 7685 7686 /// Return the store opcode for a given store size. If store size >= 8, 7687 /// neon opcode will be returned. 7688 static unsigned getStOpcode(unsigned StSize, bool IsThumb1, bool IsThumb2) { 7689 if (StSize >= 8) 7690 return StSize == 16 ? ARM::VST1q32wb_fixed 7691 : StSize == 8 ? ARM::VST1d32wb_fixed : 0; 7692 if (IsThumb1) 7693 return StSize == 4 ? ARM::tSTRi 7694 : StSize == 2 ? ARM::tSTRHi 7695 : StSize == 1 ? ARM::tSTRBi : 0; 7696 if (IsThumb2) 7697 return StSize == 4 ? ARM::t2STR_POST 7698 : StSize == 2 ? ARM::t2STRH_POST 7699 : StSize == 1 ? ARM::t2STRB_POST : 0; 7700 return StSize == 4 ? ARM::STR_POST_IMM 7701 : StSize == 2 ? ARM::STRH_POST 7702 : StSize == 1 ? ARM::STRB_POST_IMM : 0; 7703 } 7704 7705 /// Emit a post-increment load operation with given size. The instructions 7706 /// will be added to BB at Pos. 7707 static void emitPostLd(MachineBasicBlock *BB, MachineInstr *Pos, 7708 const TargetInstrInfo *TII, DebugLoc dl, 7709 unsigned LdSize, unsigned Data, unsigned AddrIn, 7710 unsigned AddrOut, bool IsThumb1, bool IsThumb2) { 7711 unsigned LdOpc = getLdOpcode(LdSize, IsThumb1, IsThumb2); 7712 assert(LdOpc != 0 && "Should have a load opcode"); 7713 if (LdSize >= 8) { 7714 AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(LdOpc), Data) 7715 .addReg(AddrOut, RegState::Define).addReg(AddrIn) 7716 .addImm(0)); 7717 } else if (IsThumb1) { 7718 // load + update AddrIn 7719 AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(LdOpc), Data) 7720 .addReg(AddrIn).addImm(0)); 7721 MachineInstrBuilder MIB = 7722 BuildMI(*BB, Pos, dl, TII->get(ARM::tADDi8), AddrOut); 7723 MIB = AddDefaultT1CC(MIB); 7724 MIB.addReg(AddrIn).addImm(LdSize); 7725 AddDefaultPred(MIB); 7726 } else if (IsThumb2) { 7727 AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(LdOpc), Data) 7728 .addReg(AddrOut, RegState::Define).addReg(AddrIn) 7729 .addImm(LdSize)); 7730 } else { // arm 7731 AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(LdOpc), Data) 7732 .addReg(AddrOut, RegState::Define).addReg(AddrIn) 7733 .addReg(0).addImm(LdSize)); 7734 } 7735 } 7736 7737 /// Emit a post-increment store operation with given size. The instructions 7738 /// will be added to BB at Pos. 7739 static void emitPostSt(MachineBasicBlock *BB, MachineInstr *Pos, 7740 const TargetInstrInfo *TII, DebugLoc dl, 7741 unsigned StSize, unsigned Data, unsigned AddrIn, 7742 unsigned AddrOut, bool IsThumb1, bool IsThumb2) { 7743 unsigned StOpc = getStOpcode(StSize, IsThumb1, IsThumb2); 7744 assert(StOpc != 0 && "Should have a store opcode"); 7745 if (StSize >= 8) { 7746 AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(StOpc), AddrOut) 7747 .addReg(AddrIn).addImm(0).addReg(Data)); 7748 } else if (IsThumb1) { 7749 // store + update AddrIn 7750 AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(StOpc)).addReg(Data) 7751 .addReg(AddrIn).addImm(0)); 7752 MachineInstrBuilder MIB = 7753 BuildMI(*BB, Pos, dl, TII->get(ARM::tADDi8), AddrOut); 7754 MIB = AddDefaultT1CC(MIB); 7755 MIB.addReg(AddrIn).addImm(StSize); 7756 AddDefaultPred(MIB); 7757 } else if (IsThumb2) { 7758 AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(StOpc), AddrOut) 7759 .addReg(Data).addReg(AddrIn).addImm(StSize)); 7760 } else { // arm 7761 AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(StOpc), AddrOut) 7762 .addReg(Data).addReg(AddrIn).addReg(0) 7763 .addImm(StSize)); 7764 } 7765 } 7766 7767 MachineBasicBlock * 7768 ARMTargetLowering::EmitStructByval(MachineInstr *MI, 7769 MachineBasicBlock *BB) const { 7770 // This pseudo instruction has 3 operands: dst, src, size 7771 // We expand it to a loop if size > Subtarget->getMaxInlineSizeThreshold(). 7772 // Otherwise, we will generate unrolled scalar copies. 7773 const TargetInstrInfo *TII = Subtarget->getInstrInfo(); 7774 const BasicBlock *LLVM_BB = BB->getBasicBlock(); 7775 MachineFunction::iterator It = ++BB->getIterator(); 7776 7777 unsigned dest = MI->getOperand(0).getReg(); 7778 unsigned src = MI->getOperand(1).getReg(); 7779 unsigned SizeVal = MI->getOperand(2).getImm(); 7780 unsigned Align = MI->getOperand(3).getImm(); 7781 DebugLoc dl = MI->getDebugLoc(); 7782 7783 MachineFunction *MF = BB->getParent(); 7784 MachineRegisterInfo &MRI = MF->getRegInfo(); 7785 unsigned UnitSize = 0; 7786 const TargetRegisterClass *TRC = nullptr; 7787 const TargetRegisterClass *VecTRC = nullptr; 7788 7789 bool IsThumb1 = Subtarget->isThumb1Only(); 7790 bool IsThumb2 = Subtarget->isThumb2(); 7791 7792 if (Align & 1) { 7793 UnitSize = 1; 7794 } else if (Align & 2) { 7795 UnitSize = 2; 7796 } else { 7797 // Check whether we can use NEON instructions. 7798 if (!MF->getFunction()->hasFnAttribute(Attribute::NoImplicitFloat) && 7799 Subtarget->hasNEON()) { 7800 if ((Align % 16 == 0) && SizeVal >= 16) 7801 UnitSize = 16; 7802 else if ((Align % 8 == 0) && SizeVal >= 8) 7803 UnitSize = 8; 7804 } 7805 // Can't use NEON instructions. 7806 if (UnitSize == 0) 7807 UnitSize = 4; 7808 } 7809 7810 // Select the correct opcode and register class for unit size load/store 7811 bool IsNeon = UnitSize >= 8; 7812 TRC = (IsThumb1 || IsThumb2) ? &ARM::tGPRRegClass : &ARM::GPRRegClass; 7813 if (IsNeon) 7814 VecTRC = UnitSize == 16 ? &ARM::DPairRegClass 7815 : UnitSize == 8 ? &ARM::DPRRegClass 7816 : nullptr; 7817 7818 unsigned BytesLeft = SizeVal % UnitSize; 7819 unsigned LoopSize = SizeVal - BytesLeft; 7820 7821 if (SizeVal <= Subtarget->getMaxInlineSizeThreshold()) { 7822 // Use LDR and STR to copy. 7823 // [scratch, srcOut] = LDR_POST(srcIn, UnitSize) 7824 // [destOut] = STR_POST(scratch, destIn, UnitSize) 7825 unsigned srcIn = src; 7826 unsigned destIn = dest; 7827 for (unsigned i = 0; i < LoopSize; i+=UnitSize) { 7828 unsigned srcOut = MRI.createVirtualRegister(TRC); 7829 unsigned destOut = MRI.createVirtualRegister(TRC); 7830 unsigned scratch = MRI.createVirtualRegister(IsNeon ? VecTRC : TRC); 7831 emitPostLd(BB, MI, TII, dl, UnitSize, scratch, srcIn, srcOut, 7832 IsThumb1, IsThumb2); 7833 emitPostSt(BB, MI, TII, dl, UnitSize, scratch, destIn, destOut, 7834 IsThumb1, IsThumb2); 7835 srcIn = srcOut; 7836 destIn = destOut; 7837 } 7838 7839 // Handle the leftover bytes with LDRB and STRB. 7840 // [scratch, srcOut] = LDRB_POST(srcIn, 1) 7841 // [destOut] = STRB_POST(scratch, destIn, 1) 7842 for (unsigned i = 0; i < BytesLeft; i++) { 7843 unsigned srcOut = MRI.createVirtualRegister(TRC); 7844 unsigned destOut = MRI.createVirtualRegister(TRC); 7845 unsigned scratch = MRI.createVirtualRegister(TRC); 7846 emitPostLd(BB, MI, TII, dl, 1, scratch, srcIn, srcOut, 7847 IsThumb1, IsThumb2); 7848 emitPostSt(BB, MI, TII, dl, 1, scratch, destIn, destOut, 7849 IsThumb1, IsThumb2); 7850 srcIn = srcOut; 7851 destIn = destOut; 7852 } 7853 MI->eraseFromParent(); // The instruction is gone now. 7854 return BB; 7855 } 7856 7857 // Expand the pseudo op to a loop. 7858 // thisMBB: 7859 // ... 7860 // movw varEnd, # --> with thumb2 7861 // movt varEnd, # 7862 // ldrcp varEnd, idx --> without thumb2 7863 // fallthrough --> loopMBB 7864 // loopMBB: 7865 // PHI varPhi, varEnd, varLoop 7866 // PHI srcPhi, src, srcLoop 7867 // PHI destPhi, dst, destLoop 7868 // [scratch, srcLoop] = LDR_POST(srcPhi, UnitSize) 7869 // [destLoop] = STR_POST(scratch, destPhi, UnitSize) 7870 // subs varLoop, varPhi, #UnitSize 7871 // bne loopMBB 7872 // fallthrough --> exitMBB 7873 // exitMBB: 7874 // epilogue to handle left-over bytes 7875 // [scratch, srcOut] = LDRB_POST(srcLoop, 1) 7876 // [destOut] = STRB_POST(scratch, destLoop, 1) 7877 MachineBasicBlock *loopMBB = MF->CreateMachineBasicBlock(LLVM_BB); 7878 MachineBasicBlock *exitMBB = MF->CreateMachineBasicBlock(LLVM_BB); 7879 MF->insert(It, loopMBB); 7880 MF->insert(It, exitMBB); 7881 7882 // Transfer the remainder of BB and its successor edges to exitMBB. 7883 exitMBB->splice(exitMBB->begin(), BB, 7884 std::next(MachineBasicBlock::iterator(MI)), BB->end()); 7885 exitMBB->transferSuccessorsAndUpdatePHIs(BB); 7886 7887 // Load an immediate to varEnd. 7888 unsigned varEnd = MRI.createVirtualRegister(TRC); 7889 if (Subtarget->useMovt(*MF)) { 7890 unsigned Vtmp = varEnd; 7891 if ((LoopSize & 0xFFFF0000) != 0) 7892 Vtmp = MRI.createVirtualRegister(TRC); 7893 AddDefaultPred(BuildMI(BB, dl, 7894 TII->get(IsThumb2 ? ARM::t2MOVi16 : ARM::MOVi16), 7895 Vtmp).addImm(LoopSize & 0xFFFF)); 7896 7897 if ((LoopSize & 0xFFFF0000) != 0) 7898 AddDefaultPred(BuildMI(BB, dl, 7899 TII->get(IsThumb2 ? ARM::t2MOVTi16 : ARM::MOVTi16), 7900 varEnd) 7901 .addReg(Vtmp) 7902 .addImm(LoopSize >> 16)); 7903 } else { 7904 MachineConstantPool *ConstantPool = MF->getConstantPool(); 7905 Type *Int32Ty = Type::getInt32Ty(MF->getFunction()->getContext()); 7906 const Constant *C = ConstantInt::get(Int32Ty, LoopSize); 7907 7908 // MachineConstantPool wants an explicit alignment. 7909 unsigned Align = MF->getDataLayout().getPrefTypeAlignment(Int32Ty); 7910 if (Align == 0) 7911 Align = MF->getDataLayout().getTypeAllocSize(C->getType()); 7912 unsigned Idx = ConstantPool->getConstantPoolIndex(C, Align); 7913 7914 if (IsThumb1) 7915 AddDefaultPred(BuildMI(*BB, MI, dl, TII->get(ARM::tLDRpci)).addReg( 7916 varEnd, RegState::Define).addConstantPoolIndex(Idx)); 7917 else 7918 AddDefaultPred(BuildMI(*BB, MI, dl, TII->get(ARM::LDRcp)).addReg( 7919 varEnd, RegState::Define).addConstantPoolIndex(Idx).addImm(0)); 7920 } 7921 BB->addSuccessor(loopMBB); 7922 7923 // Generate the loop body: 7924 // varPhi = PHI(varLoop, varEnd) 7925 // srcPhi = PHI(srcLoop, src) 7926 // destPhi = PHI(destLoop, dst) 7927 MachineBasicBlock *entryBB = BB; 7928 BB = loopMBB; 7929 unsigned varLoop = MRI.createVirtualRegister(TRC); 7930 unsigned varPhi = MRI.createVirtualRegister(TRC); 7931 unsigned srcLoop = MRI.createVirtualRegister(TRC); 7932 unsigned srcPhi = MRI.createVirtualRegister(TRC); 7933 unsigned destLoop = MRI.createVirtualRegister(TRC); 7934 unsigned destPhi = MRI.createVirtualRegister(TRC); 7935 7936 BuildMI(*BB, BB->begin(), dl, TII->get(ARM::PHI), varPhi) 7937 .addReg(varLoop).addMBB(loopMBB) 7938 .addReg(varEnd).addMBB(entryBB); 7939 BuildMI(BB, dl, TII->get(ARM::PHI), srcPhi) 7940 .addReg(srcLoop).addMBB(loopMBB) 7941 .addReg(src).addMBB(entryBB); 7942 BuildMI(BB, dl, TII->get(ARM::PHI), destPhi) 7943 .addReg(destLoop).addMBB(loopMBB) 7944 .addReg(dest).addMBB(entryBB); 7945 7946 // [scratch, srcLoop] = LDR_POST(srcPhi, UnitSize) 7947 // [destLoop] = STR_POST(scratch, destPhi, UnitSiz) 7948 unsigned scratch = MRI.createVirtualRegister(IsNeon ? VecTRC : TRC); 7949 emitPostLd(BB, BB->end(), TII, dl, UnitSize, scratch, srcPhi, srcLoop, 7950 IsThumb1, IsThumb2); 7951 emitPostSt(BB, BB->end(), TII, dl, UnitSize, scratch, destPhi, destLoop, 7952 IsThumb1, IsThumb2); 7953 7954 // Decrement loop variable by UnitSize. 7955 if (IsThumb1) { 7956 MachineInstrBuilder MIB = 7957 BuildMI(*BB, BB->end(), dl, TII->get(ARM::tSUBi8), varLoop); 7958 MIB = AddDefaultT1CC(MIB); 7959 MIB.addReg(varPhi).addImm(UnitSize); 7960 AddDefaultPred(MIB); 7961 } else { 7962 MachineInstrBuilder MIB = 7963 BuildMI(*BB, BB->end(), dl, 7964 TII->get(IsThumb2 ? ARM::t2SUBri : ARM::SUBri), varLoop); 7965 AddDefaultCC(AddDefaultPred(MIB.addReg(varPhi).addImm(UnitSize))); 7966 MIB->getOperand(5).setReg(ARM::CPSR); 7967 MIB->getOperand(5).setIsDef(true); 7968 } 7969 BuildMI(*BB, BB->end(), dl, 7970 TII->get(IsThumb1 ? ARM::tBcc : IsThumb2 ? ARM::t2Bcc : ARM::Bcc)) 7971 .addMBB(loopMBB).addImm(ARMCC::NE).addReg(ARM::CPSR); 7972 7973 // loopMBB can loop back to loopMBB or fall through to exitMBB. 7974 BB->addSuccessor(loopMBB); 7975 BB->addSuccessor(exitMBB); 7976 7977 // Add epilogue to handle BytesLeft. 7978 BB = exitMBB; 7979 MachineInstr *StartOfExit = exitMBB->begin(); 7980 7981 // [scratch, srcOut] = LDRB_POST(srcLoop, 1) 7982 // [destOut] = STRB_POST(scratch, destLoop, 1) 7983 unsigned srcIn = srcLoop; 7984 unsigned destIn = destLoop; 7985 for (unsigned i = 0; i < BytesLeft; i++) { 7986 unsigned srcOut = MRI.createVirtualRegister(TRC); 7987 unsigned destOut = MRI.createVirtualRegister(TRC); 7988 unsigned scratch = MRI.createVirtualRegister(TRC); 7989 emitPostLd(BB, StartOfExit, TII, dl, 1, scratch, srcIn, srcOut, 7990 IsThumb1, IsThumb2); 7991 emitPostSt(BB, StartOfExit, TII, dl, 1, scratch, destIn, destOut, 7992 IsThumb1, IsThumb2); 7993 srcIn = srcOut; 7994 destIn = destOut; 7995 } 7996 7997 MI->eraseFromParent(); // The instruction is gone now. 7998 return BB; 7999 } 8000 8001 MachineBasicBlock * 8002 ARMTargetLowering::EmitLowered__chkstk(MachineInstr *MI, 8003 MachineBasicBlock *MBB) const { 8004 const TargetMachine &TM = getTargetMachine(); 8005 const TargetInstrInfo &TII = *Subtarget->getInstrInfo(); 8006 DebugLoc DL = MI->getDebugLoc(); 8007 8008 assert(Subtarget->isTargetWindows() && 8009 "__chkstk is only supported on Windows"); 8010 assert(Subtarget->isThumb2() && "Windows on ARM requires Thumb-2 mode"); 8011 8012 // __chkstk takes the number of words to allocate on the stack in R4, and 8013 // returns the stack adjustment in number of bytes in R4. This will not 8014 // clober any other registers (other than the obvious lr). 8015 // 8016 // Although, technically, IP should be considered a register which may be 8017 // clobbered, the call itself will not touch it. Windows on ARM is a pure 8018 // thumb-2 environment, so there is no interworking required. As a result, we 8019 // do not expect a veneer to be emitted by the linker, clobbering IP. 8020 // 8021 // Each module receives its own copy of __chkstk, so no import thunk is 8022 // required, again, ensuring that IP is not clobbered. 8023 // 8024 // Finally, although some linkers may theoretically provide a trampoline for 8025 // out of range calls (which is quite common due to a 32M range limitation of 8026 // branches for Thumb), we can generate the long-call version via 8027 // -mcmodel=large, alleviating the need for the trampoline which may clobber 8028 // IP. 8029 8030 switch (TM.getCodeModel()) { 8031 case CodeModel::Small: 8032 case CodeModel::Medium: 8033 case CodeModel::Default: 8034 case CodeModel::Kernel: 8035 BuildMI(*MBB, MI, DL, TII.get(ARM::tBL)) 8036 .addImm((unsigned)ARMCC::AL).addReg(0) 8037 .addExternalSymbol("__chkstk") 8038 .addReg(ARM::R4, RegState::Implicit | RegState::Kill) 8039 .addReg(ARM::R4, RegState::Implicit | RegState::Define) 8040 .addReg(ARM::R12, RegState::Implicit | RegState::Define | RegState::Dead); 8041 break; 8042 case CodeModel::Large: 8043 case CodeModel::JITDefault: { 8044 MachineRegisterInfo &MRI = MBB->getParent()->getRegInfo(); 8045 unsigned Reg = MRI.createVirtualRegister(&ARM::rGPRRegClass); 8046 8047 BuildMI(*MBB, MI, DL, TII.get(ARM::t2MOVi32imm), Reg) 8048 .addExternalSymbol("__chkstk"); 8049 BuildMI(*MBB, MI, DL, TII.get(ARM::tBLXr)) 8050 .addImm((unsigned)ARMCC::AL).addReg(0) 8051 .addReg(Reg, RegState::Kill) 8052 .addReg(ARM::R4, RegState::Implicit | RegState::Kill) 8053 .addReg(ARM::R4, RegState::Implicit | RegState::Define) 8054 .addReg(ARM::R12, RegState::Implicit | RegState::Define | RegState::Dead); 8055 break; 8056 } 8057 } 8058 8059 AddDefaultCC(AddDefaultPred(BuildMI(*MBB, MI, DL, TII.get(ARM::t2SUBrr), 8060 ARM::SP) 8061 .addReg(ARM::SP, RegState::Kill) 8062 .addReg(ARM::R4, RegState::Kill) 8063 .setMIFlags(MachineInstr::FrameSetup))); 8064 8065 MI->eraseFromParent(); 8066 return MBB; 8067 } 8068 8069 MachineBasicBlock * 8070 ARMTargetLowering::EmitLowered__dbzchk(MachineInstr *MI, 8071 MachineBasicBlock *MBB) const { 8072 DebugLoc DL = MI->getDebugLoc(); 8073 MachineFunction *MF = MBB->getParent(); 8074 const TargetInstrInfo *TII = Subtarget->getInstrInfo(); 8075 8076 MachineBasicBlock *ContBB = MF->CreateMachineBasicBlock(); 8077 MF->insert(++MBB->getIterator(), ContBB); 8078 ContBB->splice(ContBB->begin(), MBB, 8079 std::next(MachineBasicBlock::iterator(MI)), MBB->end()); 8080 ContBB->transferSuccessorsAndUpdatePHIs(MBB); 8081 8082 MachineBasicBlock *TrapBB = MF->CreateMachineBasicBlock(); 8083 MF->push_back(TrapBB); 8084 BuildMI(TrapBB, DL, TII->get(ARM::t2UDF)).addImm(249); 8085 MBB->addSuccessor(TrapBB); 8086 8087 BuildMI(*MBB, MI, DL, TII->get(ARM::tCBZ)) 8088 .addReg(MI->getOperand(0).getReg()) 8089 .addMBB(TrapBB); 8090 AddDefaultPred(BuildMI(*MBB, MI, DL, TII->get(ARM::t2B)).addMBB(ContBB)); 8091 MBB->addSuccessor(ContBB); 8092 8093 MI->eraseFromParent(); 8094 return ContBB; 8095 } 8096 8097 MachineBasicBlock * 8098 ARMTargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI, 8099 MachineBasicBlock *BB) const { 8100 const TargetInstrInfo *TII = Subtarget->getInstrInfo(); 8101 DebugLoc dl = MI->getDebugLoc(); 8102 bool isThumb2 = Subtarget->isThumb2(); 8103 switch (MI->getOpcode()) { 8104 default: { 8105 MI->dump(); 8106 llvm_unreachable("Unexpected instr type to insert"); 8107 } 8108 // The Thumb2 pre-indexed stores have the same MI operands, they just 8109 // define them differently in the .td files from the isel patterns, so 8110 // they need pseudos. 8111 case ARM::t2STR_preidx: 8112 MI->setDesc(TII->get(ARM::t2STR_PRE)); 8113 return BB; 8114 case ARM::t2STRB_preidx: 8115 MI->setDesc(TII->get(ARM::t2STRB_PRE)); 8116 return BB; 8117 case ARM::t2STRH_preidx: 8118 MI->setDesc(TII->get(ARM::t2STRH_PRE)); 8119 return BB; 8120 8121 case ARM::STRi_preidx: 8122 case ARM::STRBi_preidx: { 8123 unsigned NewOpc = MI->getOpcode() == ARM::STRi_preidx ? 8124 ARM::STR_PRE_IMM : ARM::STRB_PRE_IMM; 8125 // Decode the offset. 8126 unsigned Offset = MI->getOperand(4).getImm(); 8127 bool isSub = ARM_AM::getAM2Op(Offset) == ARM_AM::sub; 8128 Offset = ARM_AM::getAM2Offset(Offset); 8129 if (isSub) 8130 Offset = -Offset; 8131 8132 MachineMemOperand *MMO = *MI->memoperands_begin(); 8133 BuildMI(*BB, MI, dl, TII->get(NewOpc)) 8134 .addOperand(MI->getOperand(0)) // Rn_wb 8135 .addOperand(MI->getOperand(1)) // Rt 8136 .addOperand(MI->getOperand(2)) // Rn 8137 .addImm(Offset) // offset (skip GPR==zero_reg) 8138 .addOperand(MI->getOperand(5)) // pred 8139 .addOperand(MI->getOperand(6)) 8140 .addMemOperand(MMO); 8141 MI->eraseFromParent(); 8142 return BB; 8143 } 8144 case ARM::STRr_preidx: 8145 case ARM::STRBr_preidx: 8146 case ARM::STRH_preidx: { 8147 unsigned NewOpc; 8148 switch (MI->getOpcode()) { 8149 default: llvm_unreachable("unexpected opcode!"); 8150 case ARM::STRr_preidx: NewOpc = ARM::STR_PRE_REG; break; 8151 case ARM::STRBr_preidx: NewOpc = ARM::STRB_PRE_REG; break; 8152 case ARM::STRH_preidx: NewOpc = ARM::STRH_PRE; break; 8153 } 8154 MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(NewOpc)); 8155 for (unsigned i = 0; i < MI->getNumOperands(); ++i) 8156 MIB.addOperand(MI->getOperand(i)); 8157 MI->eraseFromParent(); 8158 return BB; 8159 } 8160 8161 case ARM::tMOVCCr_pseudo: { 8162 // To "insert" a SELECT_CC instruction, we actually have to insert the 8163 // diamond control-flow pattern. The incoming instruction knows the 8164 // destination vreg to set, the condition code register to branch on, the 8165 // true/false values to select between, and a branch opcode to use. 8166 const BasicBlock *LLVM_BB = BB->getBasicBlock(); 8167 MachineFunction::iterator It = ++BB->getIterator(); 8168 8169 // thisMBB: 8170 // ... 8171 // TrueVal = ... 8172 // cmpTY ccX, r1, r2 8173 // bCC copy1MBB 8174 // fallthrough --> copy0MBB 8175 MachineBasicBlock *thisMBB = BB; 8176 MachineFunction *F = BB->getParent(); 8177 MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB); 8178 MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB); 8179 F->insert(It, copy0MBB); 8180 F->insert(It, sinkMBB); 8181 8182 // Transfer the remainder of BB and its successor edges to sinkMBB. 8183 sinkMBB->splice(sinkMBB->begin(), BB, 8184 std::next(MachineBasicBlock::iterator(MI)), BB->end()); 8185 sinkMBB->transferSuccessorsAndUpdatePHIs(BB); 8186 8187 BB->addSuccessor(copy0MBB); 8188 BB->addSuccessor(sinkMBB); 8189 8190 BuildMI(BB, dl, TII->get(ARM::tBcc)).addMBB(sinkMBB) 8191 .addImm(MI->getOperand(3).getImm()).addReg(MI->getOperand(4).getReg()); 8192 8193 // copy0MBB: 8194 // %FalseValue = ... 8195 // # fallthrough to sinkMBB 8196 BB = copy0MBB; 8197 8198 // Update machine-CFG edges 8199 BB->addSuccessor(sinkMBB); 8200 8201 // sinkMBB: 8202 // %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ] 8203 // ... 8204 BB = sinkMBB; 8205 BuildMI(*BB, BB->begin(), dl, 8206 TII->get(ARM::PHI), MI->getOperand(0).getReg()) 8207 .addReg(MI->getOperand(1).getReg()).addMBB(copy0MBB) 8208 .addReg(MI->getOperand(2).getReg()).addMBB(thisMBB); 8209 8210 MI->eraseFromParent(); // The pseudo instruction is gone now. 8211 return BB; 8212 } 8213 8214 case ARM::BCCi64: 8215 case ARM::BCCZi64: { 8216 // If there is an unconditional branch to the other successor, remove it. 8217 BB->erase(std::next(MachineBasicBlock::iterator(MI)), BB->end()); 8218 8219 // Compare both parts that make up the double comparison separately for 8220 // equality. 8221 bool RHSisZero = MI->getOpcode() == ARM::BCCZi64; 8222 8223 unsigned LHS1 = MI->getOperand(1).getReg(); 8224 unsigned LHS2 = MI->getOperand(2).getReg(); 8225 if (RHSisZero) { 8226 AddDefaultPred(BuildMI(BB, dl, 8227 TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri)) 8228 .addReg(LHS1).addImm(0)); 8229 BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri)) 8230 .addReg(LHS2).addImm(0) 8231 .addImm(ARMCC::EQ).addReg(ARM::CPSR); 8232 } else { 8233 unsigned RHS1 = MI->getOperand(3).getReg(); 8234 unsigned RHS2 = MI->getOperand(4).getReg(); 8235 AddDefaultPred(BuildMI(BB, dl, 8236 TII->get(isThumb2 ? ARM::t2CMPrr : ARM::CMPrr)) 8237 .addReg(LHS1).addReg(RHS1)); 8238 BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPrr : ARM::CMPrr)) 8239 .addReg(LHS2).addReg(RHS2) 8240 .addImm(ARMCC::EQ).addReg(ARM::CPSR); 8241 } 8242 8243 MachineBasicBlock *destMBB = MI->getOperand(RHSisZero ? 3 : 5).getMBB(); 8244 MachineBasicBlock *exitMBB = OtherSucc(BB, destMBB); 8245 if (MI->getOperand(0).getImm() == ARMCC::NE) 8246 std::swap(destMBB, exitMBB); 8247 8248 BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc)) 8249 .addMBB(destMBB).addImm(ARMCC::EQ).addReg(ARM::CPSR); 8250 if (isThumb2) 8251 AddDefaultPred(BuildMI(BB, dl, TII->get(ARM::t2B)).addMBB(exitMBB)); 8252 else 8253 BuildMI(BB, dl, TII->get(ARM::B)) .addMBB(exitMBB); 8254 8255 MI->eraseFromParent(); // The pseudo instruction is gone now. 8256 return BB; 8257 } 8258 8259 case ARM::Int_eh_sjlj_setjmp: 8260 case ARM::Int_eh_sjlj_setjmp_nofp: 8261 case ARM::tInt_eh_sjlj_setjmp: 8262 case ARM::t2Int_eh_sjlj_setjmp: 8263 case ARM::t2Int_eh_sjlj_setjmp_nofp: 8264 return BB; 8265 8266 case ARM::Int_eh_sjlj_setup_dispatch: 8267 EmitSjLjDispatchBlock(MI, BB); 8268 return BB; 8269 8270 case ARM::ABS: 8271 case ARM::t2ABS: { 8272 // To insert an ABS instruction, we have to insert the 8273 // diamond control-flow pattern. The incoming instruction knows the 8274 // source vreg to test against 0, the destination vreg to set, 8275 // the condition code register to branch on, the 8276 // true/false values to select between, and a branch opcode to use. 8277 // It transforms 8278 // V1 = ABS V0 8279 // into 8280 // V2 = MOVS V0 8281 // BCC (branch to SinkBB if V0 >= 0) 8282 // RSBBB: V3 = RSBri V2, 0 (compute ABS if V2 < 0) 8283 // SinkBB: V1 = PHI(V2, V3) 8284 const BasicBlock *LLVM_BB = BB->getBasicBlock(); 8285 MachineFunction::iterator BBI = ++BB->getIterator(); 8286 MachineFunction *Fn = BB->getParent(); 8287 MachineBasicBlock *RSBBB = Fn->CreateMachineBasicBlock(LLVM_BB); 8288 MachineBasicBlock *SinkBB = Fn->CreateMachineBasicBlock(LLVM_BB); 8289 Fn->insert(BBI, RSBBB); 8290 Fn->insert(BBI, SinkBB); 8291 8292 unsigned int ABSSrcReg = MI->getOperand(1).getReg(); 8293 unsigned int ABSDstReg = MI->getOperand(0).getReg(); 8294 bool ABSSrcKIll = MI->getOperand(1).isKill(); 8295 bool isThumb2 = Subtarget->isThumb2(); 8296 MachineRegisterInfo &MRI = Fn->getRegInfo(); 8297 // In Thumb mode S must not be specified if source register is the SP or 8298 // PC and if destination register is the SP, so restrict register class 8299 unsigned NewRsbDstReg = 8300 MRI.createVirtualRegister(isThumb2 ? &ARM::rGPRRegClass : &ARM::GPRRegClass); 8301 8302 // Transfer the remainder of BB and its successor edges to sinkMBB. 8303 SinkBB->splice(SinkBB->begin(), BB, 8304 std::next(MachineBasicBlock::iterator(MI)), BB->end()); 8305 SinkBB->transferSuccessorsAndUpdatePHIs(BB); 8306 8307 BB->addSuccessor(RSBBB); 8308 BB->addSuccessor(SinkBB); 8309 8310 // fall through to SinkMBB 8311 RSBBB->addSuccessor(SinkBB); 8312 8313 // insert a cmp at the end of BB 8314 AddDefaultPred(BuildMI(BB, dl, 8315 TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri)) 8316 .addReg(ABSSrcReg).addImm(0)); 8317 8318 // insert a bcc with opposite CC to ARMCC::MI at the end of BB 8319 BuildMI(BB, dl, 8320 TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc)).addMBB(SinkBB) 8321 .addImm(ARMCC::getOppositeCondition(ARMCC::MI)).addReg(ARM::CPSR); 8322 8323 // insert rsbri in RSBBB 8324 // Note: BCC and rsbri will be converted into predicated rsbmi 8325 // by if-conversion pass 8326 BuildMI(*RSBBB, RSBBB->begin(), dl, 8327 TII->get(isThumb2 ? ARM::t2RSBri : ARM::RSBri), NewRsbDstReg) 8328 .addReg(ABSSrcReg, ABSSrcKIll ? RegState::Kill : 0) 8329 .addImm(0).addImm((unsigned)ARMCC::AL).addReg(0).addReg(0); 8330 8331 // insert PHI in SinkBB, 8332 // reuse ABSDstReg to not change uses of ABS instruction 8333 BuildMI(*SinkBB, SinkBB->begin(), dl, 8334 TII->get(ARM::PHI), ABSDstReg) 8335 .addReg(NewRsbDstReg).addMBB(RSBBB) 8336 .addReg(ABSSrcReg).addMBB(BB); 8337 8338 // remove ABS instruction 8339 MI->eraseFromParent(); 8340 8341 // return last added BB 8342 return SinkBB; 8343 } 8344 case ARM::COPY_STRUCT_BYVAL_I32: 8345 ++NumLoopByVals; 8346 return EmitStructByval(MI, BB); 8347 case ARM::WIN__CHKSTK: 8348 return EmitLowered__chkstk(MI, BB); 8349 case ARM::WIN__DBZCHK: 8350 return EmitLowered__dbzchk(MI, BB); 8351 } 8352 } 8353 8354 /// \brief Attaches vregs to MEMCPY that it will use as scratch registers 8355 /// when it is expanded into LDM/STM. This is done as a post-isel lowering 8356 /// instead of as a custom inserter because we need the use list from the SDNode. 8357 static void attachMEMCPYScratchRegs(const ARMSubtarget *Subtarget, 8358 MachineInstr *MI, const SDNode *Node) { 8359 bool isThumb1 = Subtarget->isThumb1Only(); 8360 8361 DebugLoc DL = MI->getDebugLoc(); 8362 MachineFunction *MF = MI->getParent()->getParent(); 8363 MachineRegisterInfo &MRI = MF->getRegInfo(); 8364 MachineInstrBuilder MIB(*MF, MI); 8365 8366 // If the new dst/src is unused mark it as dead. 8367 if (!Node->hasAnyUseOfValue(0)) { 8368 MI->getOperand(0).setIsDead(true); 8369 } 8370 if (!Node->hasAnyUseOfValue(1)) { 8371 MI->getOperand(1).setIsDead(true); 8372 } 8373 8374 // The MEMCPY both defines and kills the scratch registers. 8375 for (unsigned I = 0; I != MI->getOperand(4).getImm(); ++I) { 8376 unsigned TmpReg = MRI.createVirtualRegister(isThumb1 ? &ARM::tGPRRegClass 8377 : &ARM::GPRRegClass); 8378 MIB.addReg(TmpReg, RegState::Define|RegState::Dead); 8379 } 8380 } 8381 8382 void ARMTargetLowering::AdjustInstrPostInstrSelection(MachineInstr *MI, 8383 SDNode *Node) const { 8384 if (MI->getOpcode() == ARM::MEMCPY) { 8385 attachMEMCPYScratchRegs(Subtarget, MI, Node); 8386 return; 8387 } 8388 8389 const MCInstrDesc *MCID = &MI->getDesc(); 8390 // Adjust potentially 's' setting instructions after isel, i.e. ADC, SBC, RSB, 8391 // RSC. Coming out of isel, they have an implicit CPSR def, but the optional 8392 // operand is still set to noreg. If needed, set the optional operand's 8393 // register to CPSR, and remove the redundant implicit def. 8394 // 8395 // e.g. ADCS (..., CPSR<imp-def>) -> ADC (... opt:CPSR<def>). 8396 8397 // Rename pseudo opcodes. 8398 unsigned NewOpc = convertAddSubFlagsOpcode(MI->getOpcode()); 8399 if (NewOpc) { 8400 const ARMBaseInstrInfo *TII = Subtarget->getInstrInfo(); 8401 MCID = &TII->get(NewOpc); 8402 8403 assert(MCID->getNumOperands() == MI->getDesc().getNumOperands() + 1 && 8404 "converted opcode should be the same except for cc_out"); 8405 8406 MI->setDesc(*MCID); 8407 8408 // Add the optional cc_out operand 8409 MI->addOperand(MachineOperand::CreateReg(0, /*isDef=*/true)); 8410 } 8411 unsigned ccOutIdx = MCID->getNumOperands() - 1; 8412 8413 // Any ARM instruction that sets the 's' bit should specify an optional 8414 // "cc_out" operand in the last operand position. 8415 if (!MI->hasOptionalDef() || !MCID->OpInfo[ccOutIdx].isOptionalDef()) { 8416 assert(!NewOpc && "Optional cc_out operand required"); 8417 return; 8418 } 8419 // Look for an implicit def of CPSR added by MachineInstr ctor. Remove it 8420 // since we already have an optional CPSR def. 8421 bool definesCPSR = false; 8422 bool deadCPSR = false; 8423 for (unsigned i = MCID->getNumOperands(), e = MI->getNumOperands(); 8424 i != e; ++i) { 8425 const MachineOperand &MO = MI->getOperand(i); 8426 if (MO.isReg() && MO.isDef() && MO.getReg() == ARM::CPSR) { 8427 definesCPSR = true; 8428 if (MO.isDead()) 8429 deadCPSR = true; 8430 MI->RemoveOperand(i); 8431 break; 8432 } 8433 } 8434 if (!definesCPSR) { 8435 assert(!NewOpc && "Optional cc_out operand required"); 8436 return; 8437 } 8438 assert(deadCPSR == !Node->hasAnyUseOfValue(1) && "inconsistent dead flag"); 8439 if (deadCPSR) { 8440 assert(!MI->getOperand(ccOutIdx).getReg() && 8441 "expect uninitialized optional cc_out operand"); 8442 return; 8443 } 8444 8445 // If this instruction was defined with an optional CPSR def and its dag node 8446 // had a live implicit CPSR def, then activate the optional CPSR def. 8447 MachineOperand &MO = MI->getOperand(ccOutIdx); 8448 MO.setReg(ARM::CPSR); 8449 MO.setIsDef(true); 8450 } 8451 8452 //===----------------------------------------------------------------------===// 8453 // ARM Optimization Hooks 8454 //===----------------------------------------------------------------------===// 8455 8456 // Helper function that checks if N is a null or all ones constant. 8457 static inline bool isZeroOrAllOnes(SDValue N, bool AllOnes) { 8458 return AllOnes ? isAllOnesConstant(N) : isNullConstant(N); 8459 } 8460 8461 // Return true if N is conditionally 0 or all ones. 8462 // Detects these expressions where cc is an i1 value: 8463 // 8464 // (select cc 0, y) [AllOnes=0] 8465 // (select cc y, 0) [AllOnes=0] 8466 // (zext cc) [AllOnes=0] 8467 // (sext cc) [AllOnes=0/1] 8468 // (select cc -1, y) [AllOnes=1] 8469 // (select cc y, -1) [AllOnes=1] 8470 // 8471 // Invert is set when N is the null/all ones constant when CC is false. 8472 // OtherOp is set to the alternative value of N. 8473 static bool isConditionalZeroOrAllOnes(SDNode *N, bool AllOnes, 8474 SDValue &CC, bool &Invert, 8475 SDValue &OtherOp, 8476 SelectionDAG &DAG) { 8477 switch (N->getOpcode()) { 8478 default: return false; 8479 case ISD::SELECT: { 8480 CC = N->getOperand(0); 8481 SDValue N1 = N->getOperand(1); 8482 SDValue N2 = N->getOperand(2); 8483 if (isZeroOrAllOnes(N1, AllOnes)) { 8484 Invert = false; 8485 OtherOp = N2; 8486 return true; 8487 } 8488 if (isZeroOrAllOnes(N2, AllOnes)) { 8489 Invert = true; 8490 OtherOp = N1; 8491 return true; 8492 } 8493 return false; 8494 } 8495 case ISD::ZERO_EXTEND: 8496 // (zext cc) can never be the all ones value. 8497 if (AllOnes) 8498 return false; 8499 // Fall through. 8500 case ISD::SIGN_EXTEND: { 8501 SDLoc dl(N); 8502 EVT VT = N->getValueType(0); 8503 CC = N->getOperand(0); 8504 if (CC.getValueType() != MVT::i1) 8505 return false; 8506 Invert = !AllOnes; 8507 if (AllOnes) 8508 // When looking for an AllOnes constant, N is an sext, and the 'other' 8509 // value is 0. 8510 OtherOp = DAG.getConstant(0, dl, VT); 8511 else if (N->getOpcode() == ISD::ZERO_EXTEND) 8512 // When looking for a 0 constant, N can be zext or sext. 8513 OtherOp = DAG.getConstant(1, dl, VT); 8514 else 8515 OtherOp = DAG.getConstant(APInt::getAllOnesValue(VT.getSizeInBits()), dl, 8516 VT); 8517 return true; 8518 } 8519 } 8520 } 8521 8522 // Combine a constant select operand into its use: 8523 // 8524 // (add (select cc, 0, c), x) -> (select cc, x, (add, x, c)) 8525 // (sub x, (select cc, 0, c)) -> (select cc, x, (sub, x, c)) 8526 // (and (select cc, -1, c), x) -> (select cc, x, (and, x, c)) [AllOnes=1] 8527 // (or (select cc, 0, c), x) -> (select cc, x, (or, x, c)) 8528 // (xor (select cc, 0, c), x) -> (select cc, x, (xor, x, c)) 8529 // 8530 // The transform is rejected if the select doesn't have a constant operand that 8531 // is null, or all ones when AllOnes is set. 8532 // 8533 // Also recognize sext/zext from i1: 8534 // 8535 // (add (zext cc), x) -> (select cc (add x, 1), x) 8536 // (add (sext cc), x) -> (select cc (add x, -1), x) 8537 // 8538 // These transformations eventually create predicated instructions. 8539 // 8540 // @param N The node to transform. 8541 // @param Slct The N operand that is a select. 8542 // @param OtherOp The other N operand (x above). 8543 // @param DCI Context. 8544 // @param AllOnes Require the select constant to be all ones instead of null. 8545 // @returns The new node, or SDValue() on failure. 8546 static 8547 SDValue combineSelectAndUse(SDNode *N, SDValue Slct, SDValue OtherOp, 8548 TargetLowering::DAGCombinerInfo &DCI, 8549 bool AllOnes = false) { 8550 SelectionDAG &DAG = DCI.DAG; 8551 EVT VT = N->getValueType(0); 8552 SDValue NonConstantVal; 8553 SDValue CCOp; 8554 bool SwapSelectOps; 8555 if (!isConditionalZeroOrAllOnes(Slct.getNode(), AllOnes, CCOp, SwapSelectOps, 8556 NonConstantVal, DAG)) 8557 return SDValue(); 8558 8559 // Slct is now know to be the desired identity constant when CC is true. 8560 SDValue TrueVal = OtherOp; 8561 SDValue FalseVal = DAG.getNode(N->getOpcode(), SDLoc(N), VT, 8562 OtherOp, NonConstantVal); 8563 // Unless SwapSelectOps says CC should be false. 8564 if (SwapSelectOps) 8565 std::swap(TrueVal, FalseVal); 8566 8567 return DAG.getNode(ISD::SELECT, SDLoc(N), VT, 8568 CCOp, TrueVal, FalseVal); 8569 } 8570 8571 // Attempt combineSelectAndUse on each operand of a commutative operator N. 8572 static 8573 SDValue combineSelectAndUseCommutative(SDNode *N, bool AllOnes, 8574 TargetLowering::DAGCombinerInfo &DCI) { 8575 SDValue N0 = N->getOperand(0); 8576 SDValue N1 = N->getOperand(1); 8577 if (N0.getNode()->hasOneUse()) 8578 if (SDValue Result = combineSelectAndUse(N, N0, N1, DCI, AllOnes)) 8579 return Result; 8580 if (N1.getNode()->hasOneUse()) 8581 if (SDValue Result = combineSelectAndUse(N, N1, N0, DCI, AllOnes)) 8582 return Result; 8583 return SDValue(); 8584 } 8585 8586 // AddCombineToVPADDL- For pair-wise add on neon, use the vpaddl instruction 8587 // (only after legalization). 8588 static SDValue AddCombineToVPADDL(SDNode *N, SDValue N0, SDValue N1, 8589 TargetLowering::DAGCombinerInfo &DCI, 8590 const ARMSubtarget *Subtarget) { 8591 8592 // Only perform optimization if after legalize, and if NEON is available. We 8593 // also expected both operands to be BUILD_VECTORs. 8594 if (DCI.isBeforeLegalize() || !Subtarget->hasNEON() 8595 || N0.getOpcode() != ISD::BUILD_VECTOR 8596 || N1.getOpcode() != ISD::BUILD_VECTOR) 8597 return SDValue(); 8598 8599 // Check output type since VPADDL operand elements can only be 8, 16, or 32. 8600 EVT VT = N->getValueType(0); 8601 if (!VT.isInteger() || VT.getVectorElementType() == MVT::i64) 8602 return SDValue(); 8603 8604 // Check that the vector operands are of the right form. 8605 // N0 and N1 are BUILD_VECTOR nodes with N number of EXTRACT_VECTOR 8606 // operands, where N is the size of the formed vector. 8607 // Each EXTRACT_VECTOR should have the same input vector and odd or even 8608 // index such that we have a pair wise add pattern. 8609 8610 // Grab the vector that all EXTRACT_VECTOR nodes should be referencing. 8611 if (N0->getOperand(0)->getOpcode() != ISD::EXTRACT_VECTOR_ELT) 8612 return SDValue(); 8613 SDValue Vec = N0->getOperand(0)->getOperand(0); 8614 SDNode *V = Vec.getNode(); 8615 unsigned nextIndex = 0; 8616 8617 // For each operands to the ADD which are BUILD_VECTORs, 8618 // check to see if each of their operands are an EXTRACT_VECTOR with 8619 // the same vector and appropriate index. 8620 for (unsigned i = 0, e = N0->getNumOperands(); i != e; ++i) { 8621 if (N0->getOperand(i)->getOpcode() == ISD::EXTRACT_VECTOR_ELT 8622 && N1->getOperand(i)->getOpcode() == ISD::EXTRACT_VECTOR_ELT) { 8623 8624 SDValue ExtVec0 = N0->getOperand(i); 8625 SDValue ExtVec1 = N1->getOperand(i); 8626 8627 // First operand is the vector, verify its the same. 8628 if (V != ExtVec0->getOperand(0).getNode() || 8629 V != ExtVec1->getOperand(0).getNode()) 8630 return SDValue(); 8631 8632 // Second is the constant, verify its correct. 8633 ConstantSDNode *C0 = dyn_cast<ConstantSDNode>(ExtVec0->getOperand(1)); 8634 ConstantSDNode *C1 = dyn_cast<ConstantSDNode>(ExtVec1->getOperand(1)); 8635 8636 // For the constant, we want to see all the even or all the odd. 8637 if (!C0 || !C1 || C0->getZExtValue() != nextIndex 8638 || C1->getZExtValue() != nextIndex+1) 8639 return SDValue(); 8640 8641 // Increment index. 8642 nextIndex+=2; 8643 } else 8644 return SDValue(); 8645 } 8646 8647 // Create VPADDL node. 8648 SelectionDAG &DAG = DCI.DAG; 8649 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 8650 8651 SDLoc dl(N); 8652 8653 // Build operand list. 8654 SmallVector<SDValue, 8> Ops; 8655 Ops.push_back(DAG.getConstant(Intrinsic::arm_neon_vpaddls, dl, 8656 TLI.getPointerTy(DAG.getDataLayout()))); 8657 8658 // Input is the vector. 8659 Ops.push_back(Vec); 8660 8661 // Get widened type and narrowed type. 8662 MVT widenType; 8663 unsigned numElem = VT.getVectorNumElements(); 8664 8665 EVT inputLaneType = Vec.getValueType().getVectorElementType(); 8666 switch (inputLaneType.getSimpleVT().SimpleTy) { 8667 case MVT::i8: widenType = MVT::getVectorVT(MVT::i16, numElem); break; 8668 case MVT::i16: widenType = MVT::getVectorVT(MVT::i32, numElem); break; 8669 case MVT::i32: widenType = MVT::getVectorVT(MVT::i64, numElem); break; 8670 default: 8671 llvm_unreachable("Invalid vector element type for padd optimization."); 8672 } 8673 8674 SDValue tmp = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, widenType, Ops); 8675 unsigned ExtOp = VT.bitsGT(tmp.getValueType()) ? ISD::ANY_EXTEND : ISD::TRUNCATE; 8676 return DAG.getNode(ExtOp, dl, VT, tmp); 8677 } 8678 8679 static SDValue findMUL_LOHI(SDValue V) { 8680 if (V->getOpcode() == ISD::UMUL_LOHI || 8681 V->getOpcode() == ISD::SMUL_LOHI) 8682 return V; 8683 return SDValue(); 8684 } 8685 8686 static SDValue AddCombineTo64bitMLAL(SDNode *AddcNode, 8687 TargetLowering::DAGCombinerInfo &DCI, 8688 const ARMSubtarget *Subtarget) { 8689 8690 if (Subtarget->isThumb1Only()) return SDValue(); 8691 8692 // Only perform the checks after legalize when the pattern is available. 8693 if (DCI.isBeforeLegalize()) return SDValue(); 8694 8695 // Look for multiply add opportunities. 8696 // The pattern is a ISD::UMUL_LOHI followed by two add nodes, where 8697 // each add nodes consumes a value from ISD::UMUL_LOHI and there is 8698 // a glue link from the first add to the second add. 8699 // If we find this pattern, we can replace the U/SMUL_LOHI, ADDC, and ADDE by 8700 // a S/UMLAL instruction. 8701 // UMUL_LOHI 8702 // / :lo \ :hi 8703 // / \ [no multiline comment] 8704 // loAdd -> ADDE | 8705 // \ :glue / 8706 // \ / 8707 // ADDC <- hiAdd 8708 // 8709 assert(AddcNode->getOpcode() == ISD::ADDC && "Expect an ADDC"); 8710 SDValue AddcOp0 = AddcNode->getOperand(0); 8711 SDValue AddcOp1 = AddcNode->getOperand(1); 8712 8713 // Check if the two operands are from the same mul_lohi node. 8714 if (AddcOp0.getNode() == AddcOp1.getNode()) 8715 return SDValue(); 8716 8717 assert(AddcNode->getNumValues() == 2 && 8718 AddcNode->getValueType(0) == MVT::i32 && 8719 "Expect ADDC with two result values. First: i32"); 8720 8721 // Check that we have a glued ADDC node. 8722 if (AddcNode->getValueType(1) != MVT::Glue) 8723 return SDValue(); 8724 8725 // Check that the ADDC adds the low result of the S/UMUL_LOHI. 8726 if (AddcOp0->getOpcode() != ISD::UMUL_LOHI && 8727 AddcOp0->getOpcode() != ISD::SMUL_LOHI && 8728 AddcOp1->getOpcode() != ISD::UMUL_LOHI && 8729 AddcOp1->getOpcode() != ISD::SMUL_LOHI) 8730 return SDValue(); 8731 8732 // Look for the glued ADDE. 8733 SDNode* AddeNode = AddcNode->getGluedUser(); 8734 if (!AddeNode) 8735 return SDValue(); 8736 8737 // Make sure it is really an ADDE. 8738 if (AddeNode->getOpcode() != ISD::ADDE) 8739 return SDValue(); 8740 8741 assert(AddeNode->getNumOperands() == 3 && 8742 AddeNode->getOperand(2).getValueType() == MVT::Glue && 8743 "ADDE node has the wrong inputs"); 8744 8745 // Check for the triangle shape. 8746 SDValue AddeOp0 = AddeNode->getOperand(0); 8747 SDValue AddeOp1 = AddeNode->getOperand(1); 8748 8749 // Make sure that the ADDE operands are not coming from the same node. 8750 if (AddeOp0.getNode() == AddeOp1.getNode()) 8751 return SDValue(); 8752 8753 // Find the MUL_LOHI node walking up ADDE's operands. 8754 bool IsLeftOperandMUL = false; 8755 SDValue MULOp = findMUL_LOHI(AddeOp0); 8756 if (MULOp == SDValue()) 8757 MULOp = findMUL_LOHI(AddeOp1); 8758 else 8759 IsLeftOperandMUL = true; 8760 if (MULOp == SDValue()) 8761 return SDValue(); 8762 8763 // Figure out the right opcode. 8764 unsigned Opc = MULOp->getOpcode(); 8765 unsigned FinalOpc = (Opc == ISD::SMUL_LOHI) ? ARMISD::SMLAL : ARMISD::UMLAL; 8766 8767 // Figure out the high and low input values to the MLAL node. 8768 SDValue* HiAdd = nullptr; 8769 SDValue* LoMul = nullptr; 8770 SDValue* LowAdd = nullptr; 8771 8772 // Ensure that ADDE is from high result of ISD::SMUL_LOHI. 8773 if ((AddeOp0 != MULOp.getValue(1)) && (AddeOp1 != MULOp.getValue(1))) 8774 return SDValue(); 8775 8776 if (IsLeftOperandMUL) 8777 HiAdd = &AddeOp1; 8778 else 8779 HiAdd = &AddeOp0; 8780 8781 8782 // Ensure that LoMul and LowAdd are taken from correct ISD::SMUL_LOHI node 8783 // whose low result is fed to the ADDC we are checking. 8784 8785 if (AddcOp0 == MULOp.getValue(0)) { 8786 LoMul = &AddcOp0; 8787 LowAdd = &AddcOp1; 8788 } 8789 if (AddcOp1 == MULOp.getValue(0)) { 8790 LoMul = &AddcOp1; 8791 LowAdd = &AddcOp0; 8792 } 8793 8794 if (!LoMul) 8795 return SDValue(); 8796 8797 // Create the merged node. 8798 SelectionDAG &DAG = DCI.DAG; 8799 8800 // Build operand list. 8801 SmallVector<SDValue, 8> Ops; 8802 Ops.push_back(LoMul->getOperand(0)); 8803 Ops.push_back(LoMul->getOperand(1)); 8804 Ops.push_back(*LowAdd); 8805 Ops.push_back(*HiAdd); 8806 8807 SDValue MLALNode = DAG.getNode(FinalOpc, SDLoc(AddcNode), 8808 DAG.getVTList(MVT::i32, MVT::i32), Ops); 8809 8810 // Replace the ADDs' nodes uses by the MLA node's values. 8811 SDValue HiMLALResult(MLALNode.getNode(), 1); 8812 DAG.ReplaceAllUsesOfValueWith(SDValue(AddeNode, 0), HiMLALResult); 8813 8814 SDValue LoMLALResult(MLALNode.getNode(), 0); 8815 DAG.ReplaceAllUsesOfValueWith(SDValue(AddcNode, 0), LoMLALResult); 8816 8817 // Return original node to notify the driver to stop replacing. 8818 SDValue resNode(AddcNode, 0); 8819 return resNode; 8820 } 8821 8822 /// PerformADDCCombine - Target-specific dag combine transform from 8823 /// ISD::ADDC, ISD::ADDE, and ISD::MUL_LOHI to MLAL. 8824 static SDValue PerformADDCCombine(SDNode *N, 8825 TargetLowering::DAGCombinerInfo &DCI, 8826 const ARMSubtarget *Subtarget) { 8827 8828 return AddCombineTo64bitMLAL(N, DCI, Subtarget); 8829 8830 } 8831 8832 /// PerformADDCombineWithOperands - Try DAG combinations for an ADD with 8833 /// operands N0 and N1. This is a helper for PerformADDCombine that is 8834 /// called with the default operands, and if that fails, with commuted 8835 /// operands. 8836 static SDValue PerformADDCombineWithOperands(SDNode *N, SDValue N0, SDValue N1, 8837 TargetLowering::DAGCombinerInfo &DCI, 8838 const ARMSubtarget *Subtarget){ 8839 8840 // Attempt to create vpaddl for this add. 8841 if (SDValue Result = AddCombineToVPADDL(N, N0, N1, DCI, Subtarget)) 8842 return Result; 8843 8844 // fold (add (select cc, 0, c), x) -> (select cc, x, (add, x, c)) 8845 if (N0.getNode()->hasOneUse()) 8846 if (SDValue Result = combineSelectAndUse(N, N0, N1, DCI)) 8847 return Result; 8848 return SDValue(); 8849 } 8850 8851 /// PerformADDCombine - Target-specific dag combine xforms for ISD::ADD. 8852 /// 8853 static SDValue PerformADDCombine(SDNode *N, 8854 TargetLowering::DAGCombinerInfo &DCI, 8855 const ARMSubtarget *Subtarget) { 8856 SDValue N0 = N->getOperand(0); 8857 SDValue N1 = N->getOperand(1); 8858 8859 // First try with the default operand order. 8860 if (SDValue Result = PerformADDCombineWithOperands(N, N0, N1, DCI, Subtarget)) 8861 return Result; 8862 8863 // If that didn't work, try again with the operands commuted. 8864 return PerformADDCombineWithOperands(N, N1, N0, DCI, Subtarget); 8865 } 8866 8867 /// PerformSUBCombine - Target-specific dag combine xforms for ISD::SUB. 8868 /// 8869 static SDValue PerformSUBCombine(SDNode *N, 8870 TargetLowering::DAGCombinerInfo &DCI) { 8871 SDValue N0 = N->getOperand(0); 8872 SDValue N1 = N->getOperand(1); 8873 8874 // fold (sub x, (select cc, 0, c)) -> (select cc, x, (sub, x, c)) 8875 if (N1.getNode()->hasOneUse()) 8876 if (SDValue Result = combineSelectAndUse(N, N1, N0, DCI)) 8877 return Result; 8878 8879 return SDValue(); 8880 } 8881 8882 /// PerformVMULCombine 8883 /// Distribute (A + B) * C to (A * C) + (B * C) to take advantage of the 8884 /// special multiplier accumulator forwarding. 8885 /// vmul d3, d0, d2 8886 /// vmla d3, d1, d2 8887 /// is faster than 8888 /// vadd d3, d0, d1 8889 /// vmul d3, d3, d2 8890 // However, for (A + B) * (A + B), 8891 // vadd d2, d0, d1 8892 // vmul d3, d0, d2 8893 // vmla d3, d1, d2 8894 // is slower than 8895 // vadd d2, d0, d1 8896 // vmul d3, d2, d2 8897 static SDValue PerformVMULCombine(SDNode *N, 8898 TargetLowering::DAGCombinerInfo &DCI, 8899 const ARMSubtarget *Subtarget) { 8900 if (!Subtarget->hasVMLxForwarding()) 8901 return SDValue(); 8902 8903 SelectionDAG &DAG = DCI.DAG; 8904 SDValue N0 = N->getOperand(0); 8905 SDValue N1 = N->getOperand(1); 8906 unsigned Opcode = N0.getOpcode(); 8907 if (Opcode != ISD::ADD && Opcode != ISD::SUB && 8908 Opcode != ISD::FADD && Opcode != ISD::FSUB) { 8909 Opcode = N1.getOpcode(); 8910 if (Opcode != ISD::ADD && Opcode != ISD::SUB && 8911 Opcode != ISD::FADD && Opcode != ISD::FSUB) 8912 return SDValue(); 8913 std::swap(N0, N1); 8914 } 8915 8916 if (N0 == N1) 8917 return SDValue(); 8918 8919 EVT VT = N->getValueType(0); 8920 SDLoc DL(N); 8921 SDValue N00 = N0->getOperand(0); 8922 SDValue N01 = N0->getOperand(1); 8923 return DAG.getNode(Opcode, DL, VT, 8924 DAG.getNode(ISD::MUL, DL, VT, N00, N1), 8925 DAG.getNode(ISD::MUL, DL, VT, N01, N1)); 8926 } 8927 8928 static SDValue PerformMULCombine(SDNode *N, 8929 TargetLowering::DAGCombinerInfo &DCI, 8930 const ARMSubtarget *Subtarget) { 8931 SelectionDAG &DAG = DCI.DAG; 8932 8933 if (Subtarget->isThumb1Only()) 8934 return SDValue(); 8935 8936 if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer()) 8937 return SDValue(); 8938 8939 EVT VT = N->getValueType(0); 8940 if (VT.is64BitVector() || VT.is128BitVector()) 8941 return PerformVMULCombine(N, DCI, Subtarget); 8942 if (VT != MVT::i32) 8943 return SDValue(); 8944 8945 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(1)); 8946 if (!C) 8947 return SDValue(); 8948 8949 int64_t MulAmt = C->getSExtValue(); 8950 unsigned ShiftAmt = countTrailingZeros<uint64_t>(MulAmt); 8951 8952 ShiftAmt = ShiftAmt & (32 - 1); 8953 SDValue V = N->getOperand(0); 8954 SDLoc DL(N); 8955 8956 SDValue Res; 8957 MulAmt >>= ShiftAmt; 8958 8959 if (MulAmt >= 0) { 8960 if (isPowerOf2_32(MulAmt - 1)) { 8961 // (mul x, 2^N + 1) => (add (shl x, N), x) 8962 Res = DAG.getNode(ISD::ADD, DL, VT, 8963 V, 8964 DAG.getNode(ISD::SHL, DL, VT, 8965 V, 8966 DAG.getConstant(Log2_32(MulAmt - 1), DL, 8967 MVT::i32))); 8968 } else if (isPowerOf2_32(MulAmt + 1)) { 8969 // (mul x, 2^N - 1) => (sub (shl x, N), x) 8970 Res = DAG.getNode(ISD::SUB, DL, VT, 8971 DAG.getNode(ISD::SHL, DL, VT, 8972 V, 8973 DAG.getConstant(Log2_32(MulAmt + 1), DL, 8974 MVT::i32)), 8975 V); 8976 } else 8977 return SDValue(); 8978 } else { 8979 uint64_t MulAmtAbs = -MulAmt; 8980 if (isPowerOf2_32(MulAmtAbs + 1)) { 8981 // (mul x, -(2^N - 1)) => (sub x, (shl x, N)) 8982 Res = DAG.getNode(ISD::SUB, DL, VT, 8983 V, 8984 DAG.getNode(ISD::SHL, DL, VT, 8985 V, 8986 DAG.getConstant(Log2_32(MulAmtAbs + 1), DL, 8987 MVT::i32))); 8988 } else if (isPowerOf2_32(MulAmtAbs - 1)) { 8989 // (mul x, -(2^N + 1)) => - (add (shl x, N), x) 8990 Res = DAG.getNode(ISD::ADD, DL, VT, 8991 V, 8992 DAG.getNode(ISD::SHL, DL, VT, 8993 V, 8994 DAG.getConstant(Log2_32(MulAmtAbs - 1), DL, 8995 MVT::i32))); 8996 Res = DAG.getNode(ISD::SUB, DL, VT, 8997 DAG.getConstant(0, DL, MVT::i32), Res); 8998 8999 } else 9000 return SDValue(); 9001 } 9002 9003 if (ShiftAmt != 0) 9004 Res = DAG.getNode(ISD::SHL, DL, VT, 9005 Res, DAG.getConstant(ShiftAmt, DL, MVT::i32)); 9006 9007 // Do not add new nodes to DAG combiner worklist. 9008 DCI.CombineTo(N, Res, false); 9009 return SDValue(); 9010 } 9011 9012 static SDValue PerformANDCombine(SDNode *N, 9013 TargetLowering::DAGCombinerInfo &DCI, 9014 const ARMSubtarget *Subtarget) { 9015 9016 // Attempt to use immediate-form VBIC 9017 BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(N->getOperand(1)); 9018 SDLoc dl(N); 9019 EVT VT = N->getValueType(0); 9020 SelectionDAG &DAG = DCI.DAG; 9021 9022 if(!DAG.getTargetLoweringInfo().isTypeLegal(VT)) 9023 return SDValue(); 9024 9025 APInt SplatBits, SplatUndef; 9026 unsigned SplatBitSize; 9027 bool HasAnyUndefs; 9028 if (BVN && 9029 BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs)) { 9030 if (SplatBitSize <= 64) { 9031 EVT VbicVT; 9032 SDValue Val = isNEONModifiedImm((~SplatBits).getZExtValue(), 9033 SplatUndef.getZExtValue(), SplatBitSize, 9034 DAG, dl, VbicVT, VT.is128BitVector(), 9035 OtherModImm); 9036 if (Val.getNode()) { 9037 SDValue Input = 9038 DAG.getNode(ISD::BITCAST, dl, VbicVT, N->getOperand(0)); 9039 SDValue Vbic = DAG.getNode(ARMISD::VBICIMM, dl, VbicVT, Input, Val); 9040 return DAG.getNode(ISD::BITCAST, dl, VT, Vbic); 9041 } 9042 } 9043 } 9044 9045 if (!Subtarget->isThumb1Only()) { 9046 // fold (and (select cc, -1, c), x) -> (select cc, x, (and, x, c)) 9047 if (SDValue Result = combineSelectAndUseCommutative(N, true, DCI)) 9048 return Result; 9049 } 9050 9051 return SDValue(); 9052 } 9053 9054 /// PerformORCombine - Target-specific dag combine xforms for ISD::OR 9055 static SDValue PerformORCombine(SDNode *N, 9056 TargetLowering::DAGCombinerInfo &DCI, 9057 const ARMSubtarget *Subtarget) { 9058 // Attempt to use immediate-form VORR 9059 BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(N->getOperand(1)); 9060 SDLoc dl(N); 9061 EVT VT = N->getValueType(0); 9062 SelectionDAG &DAG = DCI.DAG; 9063 9064 if(!DAG.getTargetLoweringInfo().isTypeLegal(VT)) 9065 return SDValue(); 9066 9067 APInt SplatBits, SplatUndef; 9068 unsigned SplatBitSize; 9069 bool HasAnyUndefs; 9070 if (BVN && Subtarget->hasNEON() && 9071 BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs)) { 9072 if (SplatBitSize <= 64) { 9073 EVT VorrVT; 9074 SDValue Val = isNEONModifiedImm(SplatBits.getZExtValue(), 9075 SplatUndef.getZExtValue(), SplatBitSize, 9076 DAG, dl, VorrVT, VT.is128BitVector(), 9077 OtherModImm); 9078 if (Val.getNode()) { 9079 SDValue Input = 9080 DAG.getNode(ISD::BITCAST, dl, VorrVT, N->getOperand(0)); 9081 SDValue Vorr = DAG.getNode(ARMISD::VORRIMM, dl, VorrVT, Input, Val); 9082 return DAG.getNode(ISD::BITCAST, dl, VT, Vorr); 9083 } 9084 } 9085 } 9086 9087 if (!Subtarget->isThumb1Only()) { 9088 // fold (or (select cc, 0, c), x) -> (select cc, x, (or, x, c)) 9089 if (SDValue Result = combineSelectAndUseCommutative(N, false, DCI)) 9090 return Result; 9091 } 9092 9093 // The code below optimizes (or (and X, Y), Z). 9094 // The AND operand needs to have a single user to make these optimizations 9095 // profitable. 9096 SDValue N0 = N->getOperand(0); 9097 if (N0.getOpcode() != ISD::AND || !N0.hasOneUse()) 9098 return SDValue(); 9099 SDValue N1 = N->getOperand(1); 9100 9101 // (or (and B, A), (and C, ~A)) => (VBSL A, B, C) when A is a constant. 9102 if (Subtarget->hasNEON() && N1.getOpcode() == ISD::AND && VT.isVector() && 9103 DAG.getTargetLoweringInfo().isTypeLegal(VT)) { 9104 APInt SplatUndef; 9105 unsigned SplatBitSize; 9106 bool HasAnyUndefs; 9107 9108 APInt SplatBits0, SplatBits1; 9109 BuildVectorSDNode *BVN0 = dyn_cast<BuildVectorSDNode>(N0->getOperand(1)); 9110 BuildVectorSDNode *BVN1 = dyn_cast<BuildVectorSDNode>(N1->getOperand(1)); 9111 // Ensure that the second operand of both ands are constants 9112 if (BVN0 && BVN0->isConstantSplat(SplatBits0, SplatUndef, SplatBitSize, 9113 HasAnyUndefs) && !HasAnyUndefs) { 9114 if (BVN1 && BVN1->isConstantSplat(SplatBits1, SplatUndef, SplatBitSize, 9115 HasAnyUndefs) && !HasAnyUndefs) { 9116 // Ensure that the bit width of the constants are the same and that 9117 // the splat arguments are logical inverses as per the pattern we 9118 // are trying to simplify. 9119 if (SplatBits0.getBitWidth() == SplatBits1.getBitWidth() && 9120 SplatBits0 == ~SplatBits1) { 9121 // Canonicalize the vector type to make instruction selection 9122 // simpler. 9123 EVT CanonicalVT = VT.is128BitVector() ? MVT::v4i32 : MVT::v2i32; 9124 SDValue Result = DAG.getNode(ARMISD::VBSL, dl, CanonicalVT, 9125 N0->getOperand(1), 9126 N0->getOperand(0), 9127 N1->getOperand(0)); 9128 return DAG.getNode(ISD::BITCAST, dl, VT, Result); 9129 } 9130 } 9131 } 9132 } 9133 9134 // Try to use the ARM/Thumb2 BFI (bitfield insert) instruction when 9135 // reasonable. 9136 9137 // BFI is only available on V6T2+ 9138 if (Subtarget->isThumb1Only() || !Subtarget->hasV6T2Ops()) 9139 return SDValue(); 9140 9141 SDLoc DL(N); 9142 // 1) or (and A, mask), val => ARMbfi A, val, mask 9143 // iff (val & mask) == val 9144 // 9145 // 2) or (and A, mask), (and B, mask2) => ARMbfi A, (lsr B, amt), mask 9146 // 2a) iff isBitFieldInvertedMask(mask) && isBitFieldInvertedMask(~mask2) 9147 // && mask == ~mask2 9148 // 2b) iff isBitFieldInvertedMask(~mask) && isBitFieldInvertedMask(mask2) 9149 // && ~mask == mask2 9150 // (i.e., copy a bitfield value into another bitfield of the same width) 9151 9152 if (VT != MVT::i32) 9153 return SDValue(); 9154 9155 SDValue N00 = N0.getOperand(0); 9156 9157 // The value and the mask need to be constants so we can verify this is 9158 // actually a bitfield set. If the mask is 0xffff, we can do better 9159 // via a movt instruction, so don't use BFI in that case. 9160 SDValue MaskOp = N0.getOperand(1); 9161 ConstantSDNode *MaskC = dyn_cast<ConstantSDNode>(MaskOp); 9162 if (!MaskC) 9163 return SDValue(); 9164 unsigned Mask = MaskC->getZExtValue(); 9165 if (Mask == 0xffff) 9166 return SDValue(); 9167 SDValue Res; 9168 // Case (1): or (and A, mask), val => ARMbfi A, val, mask 9169 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1); 9170 if (N1C) { 9171 unsigned Val = N1C->getZExtValue(); 9172 if ((Val & ~Mask) != Val) 9173 return SDValue(); 9174 9175 if (ARM::isBitFieldInvertedMask(Mask)) { 9176 Val >>= countTrailingZeros(~Mask); 9177 9178 Res = DAG.getNode(ARMISD::BFI, DL, VT, N00, 9179 DAG.getConstant(Val, DL, MVT::i32), 9180 DAG.getConstant(Mask, DL, MVT::i32)); 9181 9182 // Do not add new nodes to DAG combiner worklist. 9183 DCI.CombineTo(N, Res, false); 9184 return SDValue(); 9185 } 9186 } else if (N1.getOpcode() == ISD::AND) { 9187 // case (2) or (and A, mask), (and B, mask2) => ARMbfi A, (lsr B, amt), mask 9188 ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1)); 9189 if (!N11C) 9190 return SDValue(); 9191 unsigned Mask2 = N11C->getZExtValue(); 9192 9193 // Mask and ~Mask2 (or reverse) must be equivalent for the BFI pattern 9194 // as is to match. 9195 if (ARM::isBitFieldInvertedMask(Mask) && 9196 (Mask == ~Mask2)) { 9197 // The pack halfword instruction works better for masks that fit it, 9198 // so use that when it's available. 9199 if (Subtarget->hasT2ExtractPack() && 9200 (Mask == 0xffff || Mask == 0xffff0000)) 9201 return SDValue(); 9202 // 2a 9203 unsigned amt = countTrailingZeros(Mask2); 9204 Res = DAG.getNode(ISD::SRL, DL, VT, N1.getOperand(0), 9205 DAG.getConstant(amt, DL, MVT::i32)); 9206 Res = DAG.getNode(ARMISD::BFI, DL, VT, N00, Res, 9207 DAG.getConstant(Mask, DL, MVT::i32)); 9208 // Do not add new nodes to DAG combiner worklist. 9209 DCI.CombineTo(N, Res, false); 9210 return SDValue(); 9211 } else if (ARM::isBitFieldInvertedMask(~Mask) && 9212 (~Mask == Mask2)) { 9213 // The pack halfword instruction works better for masks that fit it, 9214 // so use that when it's available. 9215 if (Subtarget->hasT2ExtractPack() && 9216 (Mask2 == 0xffff || Mask2 == 0xffff0000)) 9217 return SDValue(); 9218 // 2b 9219 unsigned lsb = countTrailingZeros(Mask); 9220 Res = DAG.getNode(ISD::SRL, DL, VT, N00, 9221 DAG.getConstant(lsb, DL, MVT::i32)); 9222 Res = DAG.getNode(ARMISD::BFI, DL, VT, N1.getOperand(0), Res, 9223 DAG.getConstant(Mask2, DL, MVT::i32)); 9224 // Do not add new nodes to DAG combiner worklist. 9225 DCI.CombineTo(N, Res, false); 9226 return SDValue(); 9227 } 9228 } 9229 9230 if (DAG.MaskedValueIsZero(N1, MaskC->getAPIntValue()) && 9231 N00.getOpcode() == ISD::SHL && isa<ConstantSDNode>(N00.getOperand(1)) && 9232 ARM::isBitFieldInvertedMask(~Mask)) { 9233 // Case (3): or (and (shl A, #shamt), mask), B => ARMbfi B, A, ~mask 9234 // where lsb(mask) == #shamt and masked bits of B are known zero. 9235 SDValue ShAmt = N00.getOperand(1); 9236 unsigned ShAmtC = cast<ConstantSDNode>(ShAmt)->getZExtValue(); 9237 unsigned LSB = countTrailingZeros(Mask); 9238 if (ShAmtC != LSB) 9239 return SDValue(); 9240 9241 Res = DAG.getNode(ARMISD::BFI, DL, VT, N1, N00.getOperand(0), 9242 DAG.getConstant(~Mask, DL, MVT::i32)); 9243 9244 // Do not add new nodes to DAG combiner worklist. 9245 DCI.CombineTo(N, Res, false); 9246 } 9247 9248 return SDValue(); 9249 } 9250 9251 static SDValue PerformXORCombine(SDNode *N, 9252 TargetLowering::DAGCombinerInfo &DCI, 9253 const ARMSubtarget *Subtarget) { 9254 EVT VT = N->getValueType(0); 9255 SelectionDAG &DAG = DCI.DAG; 9256 9257 if(!DAG.getTargetLoweringInfo().isTypeLegal(VT)) 9258 return SDValue(); 9259 9260 if (!Subtarget->isThumb1Only()) { 9261 // fold (xor (select cc, 0, c), x) -> (select cc, x, (xor, x, c)) 9262 if (SDValue Result = combineSelectAndUseCommutative(N, false, DCI)) 9263 return Result; 9264 } 9265 9266 return SDValue(); 9267 } 9268 9269 // ParseBFI - given a BFI instruction in N, extract the "from" value (Rn) and return it, 9270 // and fill in FromMask and ToMask with (consecutive) bits in "from" to be extracted and 9271 // their position in "to" (Rd). 9272 static SDValue ParseBFI(SDNode *N, APInt &ToMask, APInt &FromMask) { 9273 assert(N->getOpcode() == ARMISD::BFI); 9274 9275 SDValue From = N->getOperand(1); 9276 ToMask = ~cast<ConstantSDNode>(N->getOperand(2))->getAPIntValue(); 9277 FromMask = APInt::getLowBitsSet(ToMask.getBitWidth(), ToMask.countPopulation()); 9278 9279 // If the Base came from a SHR #C, we can deduce that it is really testing bit 9280 // #C in the base of the SHR. 9281 if (From->getOpcode() == ISD::SRL && 9282 isa<ConstantSDNode>(From->getOperand(1))) { 9283 APInt Shift = cast<ConstantSDNode>(From->getOperand(1))->getAPIntValue(); 9284 assert(Shift.getLimitedValue() < 32 && "Shift too large!"); 9285 FromMask <<= Shift.getLimitedValue(31); 9286 From = From->getOperand(0); 9287 } 9288 9289 return From; 9290 } 9291 9292 // If A and B contain one contiguous set of bits, does A | B == A . B? 9293 // 9294 // Neither A nor B must be zero. 9295 static bool BitsProperlyConcatenate(const APInt &A, const APInt &B) { 9296 unsigned LastActiveBitInA = A.countTrailingZeros(); 9297 unsigned FirstActiveBitInB = B.getBitWidth() - B.countLeadingZeros() - 1; 9298 return LastActiveBitInA - 1 == FirstActiveBitInB; 9299 } 9300 9301 static SDValue FindBFIToCombineWith(SDNode *N) { 9302 // We have a BFI in N. Follow a possible chain of BFIs and find a BFI it can combine with, 9303 // if one exists. 9304 APInt ToMask, FromMask; 9305 SDValue From = ParseBFI(N, ToMask, FromMask); 9306 SDValue To = N->getOperand(0); 9307 9308 // Now check for a compatible BFI to merge with. We can pass through BFIs that 9309 // aren't compatible, but not if they set the same bit in their destination as 9310 // we do (or that of any BFI we're going to combine with). 9311 SDValue V = To; 9312 APInt CombinedToMask = ToMask; 9313 while (V.getOpcode() == ARMISD::BFI) { 9314 APInt NewToMask, NewFromMask; 9315 SDValue NewFrom = ParseBFI(V.getNode(), NewToMask, NewFromMask); 9316 if (NewFrom != From) { 9317 // This BFI has a different base. Keep going. 9318 CombinedToMask |= NewToMask; 9319 V = V.getOperand(0); 9320 continue; 9321 } 9322 9323 // Do the written bits conflict with any we've seen so far? 9324 if ((NewToMask & CombinedToMask).getBoolValue()) 9325 // Conflicting bits - bail out because going further is unsafe. 9326 return SDValue(); 9327 9328 // Are the new bits contiguous when combined with the old bits? 9329 if (BitsProperlyConcatenate(ToMask, NewToMask) && 9330 BitsProperlyConcatenate(FromMask, NewFromMask)) 9331 return V; 9332 if (BitsProperlyConcatenate(NewToMask, ToMask) && 9333 BitsProperlyConcatenate(NewFromMask, FromMask)) 9334 return V; 9335 9336 // We've seen a write to some bits, so track it. 9337 CombinedToMask |= NewToMask; 9338 // Keep going... 9339 V = V.getOperand(0); 9340 } 9341 9342 return SDValue(); 9343 } 9344 9345 static SDValue PerformBFICombine(SDNode *N, 9346 TargetLowering::DAGCombinerInfo &DCI) { 9347 SDValue N1 = N->getOperand(1); 9348 if (N1.getOpcode() == ISD::AND) { 9349 // (bfi A, (and B, Mask1), Mask2) -> (bfi A, B, Mask2) iff 9350 // the bits being cleared by the AND are not demanded by the BFI. 9351 ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1)); 9352 if (!N11C) 9353 return SDValue(); 9354 unsigned InvMask = cast<ConstantSDNode>(N->getOperand(2))->getZExtValue(); 9355 unsigned LSB = countTrailingZeros(~InvMask); 9356 unsigned Width = (32 - countLeadingZeros(~InvMask)) - LSB; 9357 assert(Width < 9358 static_cast<unsigned>(std::numeric_limits<unsigned>::digits) && 9359 "undefined behavior"); 9360 unsigned Mask = (1u << Width) - 1; 9361 unsigned Mask2 = N11C->getZExtValue(); 9362 if ((Mask & (~Mask2)) == 0) 9363 return DCI.DAG.getNode(ARMISD::BFI, SDLoc(N), N->getValueType(0), 9364 N->getOperand(0), N1.getOperand(0), 9365 N->getOperand(2)); 9366 } else if (N->getOperand(0).getOpcode() == ARMISD::BFI) { 9367 // We have a BFI of a BFI. Walk up the BFI chain to see how long it goes. 9368 // Keep track of any consecutive bits set that all come from the same base 9369 // value. We can combine these together into a single BFI. 9370 SDValue CombineBFI = FindBFIToCombineWith(N); 9371 if (CombineBFI == SDValue()) 9372 return SDValue(); 9373 9374 // We've found a BFI. 9375 APInt ToMask1, FromMask1; 9376 SDValue From1 = ParseBFI(N, ToMask1, FromMask1); 9377 9378 APInt ToMask2, FromMask2; 9379 SDValue From2 = ParseBFI(CombineBFI.getNode(), ToMask2, FromMask2); 9380 assert(From1 == From2); 9381 (void)From2; 9382 9383 // First, unlink CombineBFI. 9384 DCI.DAG.ReplaceAllUsesWith(CombineBFI, CombineBFI.getOperand(0)); 9385 // Then create a new BFI, combining the two together. 9386 APInt NewFromMask = FromMask1 | FromMask2; 9387 APInt NewToMask = ToMask1 | ToMask2; 9388 9389 EVT VT = N->getValueType(0); 9390 SDLoc dl(N); 9391 9392 if (NewFromMask[0] == 0) 9393 From1 = DCI.DAG.getNode( 9394 ISD::SRL, dl, VT, From1, 9395 DCI.DAG.getConstant(NewFromMask.countTrailingZeros(), dl, VT)); 9396 return DCI.DAG.getNode(ARMISD::BFI, dl, VT, N->getOperand(0), From1, 9397 DCI.DAG.getConstant(~NewToMask, dl, VT)); 9398 } 9399 return SDValue(); 9400 } 9401 9402 /// PerformVMOVRRDCombine - Target-specific dag combine xforms for 9403 /// ARMISD::VMOVRRD. 9404 static SDValue PerformVMOVRRDCombine(SDNode *N, 9405 TargetLowering::DAGCombinerInfo &DCI, 9406 const ARMSubtarget *Subtarget) { 9407 // vmovrrd(vmovdrr x, y) -> x,y 9408 SDValue InDouble = N->getOperand(0); 9409 if (InDouble.getOpcode() == ARMISD::VMOVDRR && !Subtarget->isFPOnlySP()) 9410 return DCI.CombineTo(N, InDouble.getOperand(0), InDouble.getOperand(1)); 9411 9412 // vmovrrd(load f64) -> (load i32), (load i32) 9413 SDNode *InNode = InDouble.getNode(); 9414 if (ISD::isNormalLoad(InNode) && InNode->hasOneUse() && 9415 InNode->getValueType(0) == MVT::f64 && 9416 InNode->getOperand(1).getOpcode() == ISD::FrameIndex && 9417 !cast<LoadSDNode>(InNode)->isVolatile()) { 9418 // TODO: Should this be done for non-FrameIndex operands? 9419 LoadSDNode *LD = cast<LoadSDNode>(InNode); 9420 9421 SelectionDAG &DAG = DCI.DAG; 9422 SDLoc DL(LD); 9423 SDValue BasePtr = LD->getBasePtr(); 9424 SDValue NewLD1 = DAG.getLoad(MVT::i32, DL, LD->getChain(), BasePtr, 9425 LD->getPointerInfo(), LD->isVolatile(), 9426 LD->isNonTemporal(), LD->isInvariant(), 9427 LD->getAlignment()); 9428 9429 SDValue OffsetPtr = DAG.getNode(ISD::ADD, DL, MVT::i32, BasePtr, 9430 DAG.getConstant(4, DL, MVT::i32)); 9431 SDValue NewLD2 = DAG.getLoad(MVT::i32, DL, NewLD1.getValue(1), OffsetPtr, 9432 LD->getPointerInfo(), LD->isVolatile(), 9433 LD->isNonTemporal(), LD->isInvariant(), 9434 std::min(4U, LD->getAlignment() / 2)); 9435 9436 DAG.ReplaceAllUsesOfValueWith(SDValue(LD, 1), NewLD2.getValue(1)); 9437 if (DCI.DAG.getDataLayout().isBigEndian()) 9438 std::swap (NewLD1, NewLD2); 9439 SDValue Result = DCI.CombineTo(N, NewLD1, NewLD2); 9440 return Result; 9441 } 9442 9443 return SDValue(); 9444 } 9445 9446 /// PerformVMOVDRRCombine - Target-specific dag combine xforms for 9447 /// ARMISD::VMOVDRR. This is also used for BUILD_VECTORs with 2 operands. 9448 static SDValue PerformVMOVDRRCombine(SDNode *N, SelectionDAG &DAG) { 9449 // N=vmovrrd(X); vmovdrr(N:0, N:1) -> bit_convert(X) 9450 SDValue Op0 = N->getOperand(0); 9451 SDValue Op1 = N->getOperand(1); 9452 if (Op0.getOpcode() == ISD::BITCAST) 9453 Op0 = Op0.getOperand(0); 9454 if (Op1.getOpcode() == ISD::BITCAST) 9455 Op1 = Op1.getOperand(0); 9456 if (Op0.getOpcode() == ARMISD::VMOVRRD && 9457 Op0.getNode() == Op1.getNode() && 9458 Op0.getResNo() == 0 && Op1.getResNo() == 1) 9459 return DAG.getNode(ISD::BITCAST, SDLoc(N), 9460 N->getValueType(0), Op0.getOperand(0)); 9461 return SDValue(); 9462 } 9463 9464 /// hasNormalLoadOperand - Check if any of the operands of a BUILD_VECTOR node 9465 /// are normal, non-volatile loads. If so, it is profitable to bitcast an 9466 /// i64 vector to have f64 elements, since the value can then be loaded 9467 /// directly into a VFP register. 9468 static bool hasNormalLoadOperand(SDNode *N) { 9469 unsigned NumElts = N->getValueType(0).getVectorNumElements(); 9470 for (unsigned i = 0; i < NumElts; ++i) { 9471 SDNode *Elt = N->getOperand(i).getNode(); 9472 if (ISD::isNormalLoad(Elt) && !cast<LoadSDNode>(Elt)->isVolatile()) 9473 return true; 9474 } 9475 return false; 9476 } 9477 9478 /// PerformBUILD_VECTORCombine - Target-specific dag combine xforms for 9479 /// ISD::BUILD_VECTOR. 9480 static SDValue PerformBUILD_VECTORCombine(SDNode *N, 9481 TargetLowering::DAGCombinerInfo &DCI, 9482 const ARMSubtarget *Subtarget) { 9483 // build_vector(N=ARMISD::VMOVRRD(X), N:1) -> bit_convert(X): 9484 // VMOVRRD is introduced when legalizing i64 types. It forces the i64 value 9485 // into a pair of GPRs, which is fine when the value is used as a scalar, 9486 // but if the i64 value is converted to a vector, we need to undo the VMOVRRD. 9487 SelectionDAG &DAG = DCI.DAG; 9488 if (N->getNumOperands() == 2) 9489 if (SDValue RV = PerformVMOVDRRCombine(N, DAG)) 9490 return RV; 9491 9492 // Load i64 elements as f64 values so that type legalization does not split 9493 // them up into i32 values. 9494 EVT VT = N->getValueType(0); 9495 if (VT.getVectorElementType() != MVT::i64 || !hasNormalLoadOperand(N)) 9496 return SDValue(); 9497 SDLoc dl(N); 9498 SmallVector<SDValue, 8> Ops; 9499 unsigned NumElts = VT.getVectorNumElements(); 9500 for (unsigned i = 0; i < NumElts; ++i) { 9501 SDValue V = DAG.getNode(ISD::BITCAST, dl, MVT::f64, N->getOperand(i)); 9502 Ops.push_back(V); 9503 // Make the DAGCombiner fold the bitcast. 9504 DCI.AddToWorklist(V.getNode()); 9505 } 9506 EVT FloatVT = EVT::getVectorVT(*DAG.getContext(), MVT::f64, NumElts); 9507 SDValue BV = DAG.getBuildVector(FloatVT, dl, Ops); 9508 return DAG.getNode(ISD::BITCAST, dl, VT, BV); 9509 } 9510 9511 /// \brief Target-specific dag combine xforms for ARMISD::BUILD_VECTOR. 9512 static SDValue 9513 PerformARMBUILD_VECTORCombine(SDNode *N, TargetLowering::DAGCombinerInfo &DCI) { 9514 // ARMISD::BUILD_VECTOR is introduced when legalizing ISD::BUILD_VECTOR. 9515 // At that time, we may have inserted bitcasts from integer to float. 9516 // If these bitcasts have survived DAGCombine, change the lowering of this 9517 // BUILD_VECTOR in something more vector friendly, i.e., that does not 9518 // force to use floating point types. 9519 9520 // Make sure we can change the type of the vector. 9521 // This is possible iff: 9522 // 1. The vector is only used in a bitcast to a integer type. I.e., 9523 // 1.1. Vector is used only once. 9524 // 1.2. Use is a bit convert to an integer type. 9525 // 2. The size of its operands are 32-bits (64-bits are not legal). 9526 EVT VT = N->getValueType(0); 9527 EVT EltVT = VT.getVectorElementType(); 9528 9529 // Check 1.1. and 2. 9530 if (EltVT.getSizeInBits() != 32 || !N->hasOneUse()) 9531 return SDValue(); 9532 9533 // By construction, the input type must be float. 9534 assert(EltVT == MVT::f32 && "Unexpected type!"); 9535 9536 // Check 1.2. 9537 SDNode *Use = *N->use_begin(); 9538 if (Use->getOpcode() != ISD::BITCAST || 9539 Use->getValueType(0).isFloatingPoint()) 9540 return SDValue(); 9541 9542 // Check profitability. 9543 // Model is, if more than half of the relevant operands are bitcast from 9544 // i32, turn the build_vector into a sequence of insert_vector_elt. 9545 // Relevant operands are everything that is not statically 9546 // (i.e., at compile time) bitcasted. 9547 unsigned NumOfBitCastedElts = 0; 9548 unsigned NumElts = VT.getVectorNumElements(); 9549 unsigned NumOfRelevantElts = NumElts; 9550 for (unsigned Idx = 0; Idx < NumElts; ++Idx) { 9551 SDValue Elt = N->getOperand(Idx); 9552 if (Elt->getOpcode() == ISD::BITCAST) { 9553 // Assume only bit cast to i32 will go away. 9554 if (Elt->getOperand(0).getValueType() == MVT::i32) 9555 ++NumOfBitCastedElts; 9556 } else if (Elt.isUndef() || isa<ConstantSDNode>(Elt)) 9557 // Constants are statically casted, thus do not count them as 9558 // relevant operands. 9559 --NumOfRelevantElts; 9560 } 9561 9562 // Check if more than half of the elements require a non-free bitcast. 9563 if (NumOfBitCastedElts <= NumOfRelevantElts / 2) 9564 return SDValue(); 9565 9566 SelectionDAG &DAG = DCI.DAG; 9567 // Create the new vector type. 9568 EVT VecVT = EVT::getVectorVT(*DAG.getContext(), MVT::i32, NumElts); 9569 // Check if the type is legal. 9570 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 9571 if (!TLI.isTypeLegal(VecVT)) 9572 return SDValue(); 9573 9574 // Combine: 9575 // ARMISD::BUILD_VECTOR E1, E2, ..., EN. 9576 // => BITCAST INSERT_VECTOR_ELT 9577 // (INSERT_VECTOR_ELT (...), (BITCAST EN-1), N-1), 9578 // (BITCAST EN), N. 9579 SDValue Vec = DAG.getUNDEF(VecVT); 9580 SDLoc dl(N); 9581 for (unsigned Idx = 0 ; Idx < NumElts; ++Idx) { 9582 SDValue V = N->getOperand(Idx); 9583 if (V.isUndef()) 9584 continue; 9585 if (V.getOpcode() == ISD::BITCAST && 9586 V->getOperand(0).getValueType() == MVT::i32) 9587 // Fold obvious case. 9588 V = V.getOperand(0); 9589 else { 9590 V = DAG.getNode(ISD::BITCAST, SDLoc(V), MVT::i32, V); 9591 // Make the DAGCombiner fold the bitcasts. 9592 DCI.AddToWorklist(V.getNode()); 9593 } 9594 SDValue LaneIdx = DAG.getConstant(Idx, dl, MVT::i32); 9595 Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VecVT, Vec, V, LaneIdx); 9596 } 9597 Vec = DAG.getNode(ISD::BITCAST, dl, VT, Vec); 9598 // Make the DAGCombiner fold the bitcasts. 9599 DCI.AddToWorklist(Vec.getNode()); 9600 return Vec; 9601 } 9602 9603 /// PerformInsertEltCombine - Target-specific dag combine xforms for 9604 /// ISD::INSERT_VECTOR_ELT. 9605 static SDValue PerformInsertEltCombine(SDNode *N, 9606 TargetLowering::DAGCombinerInfo &DCI) { 9607 // Bitcast an i64 load inserted into a vector to f64. 9608 // Otherwise, the i64 value will be legalized to a pair of i32 values. 9609 EVT VT = N->getValueType(0); 9610 SDNode *Elt = N->getOperand(1).getNode(); 9611 if (VT.getVectorElementType() != MVT::i64 || 9612 !ISD::isNormalLoad(Elt) || cast<LoadSDNode>(Elt)->isVolatile()) 9613 return SDValue(); 9614 9615 SelectionDAG &DAG = DCI.DAG; 9616 SDLoc dl(N); 9617 EVT FloatVT = EVT::getVectorVT(*DAG.getContext(), MVT::f64, 9618 VT.getVectorNumElements()); 9619 SDValue Vec = DAG.getNode(ISD::BITCAST, dl, FloatVT, N->getOperand(0)); 9620 SDValue V = DAG.getNode(ISD::BITCAST, dl, MVT::f64, N->getOperand(1)); 9621 // Make the DAGCombiner fold the bitcasts. 9622 DCI.AddToWorklist(Vec.getNode()); 9623 DCI.AddToWorklist(V.getNode()); 9624 SDValue InsElt = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, FloatVT, 9625 Vec, V, N->getOperand(2)); 9626 return DAG.getNode(ISD::BITCAST, dl, VT, InsElt); 9627 } 9628 9629 /// PerformVECTOR_SHUFFLECombine - Target-specific dag combine xforms for 9630 /// ISD::VECTOR_SHUFFLE. 9631 static SDValue PerformVECTOR_SHUFFLECombine(SDNode *N, SelectionDAG &DAG) { 9632 // The LLVM shufflevector instruction does not require the shuffle mask 9633 // length to match the operand vector length, but ISD::VECTOR_SHUFFLE does 9634 // have that requirement. When translating to ISD::VECTOR_SHUFFLE, if the 9635 // operands do not match the mask length, they are extended by concatenating 9636 // them with undef vectors. That is probably the right thing for other 9637 // targets, but for NEON it is better to concatenate two double-register 9638 // size vector operands into a single quad-register size vector. Do that 9639 // transformation here: 9640 // shuffle(concat(v1, undef), concat(v2, undef)) -> 9641 // shuffle(concat(v1, v2), undef) 9642 SDValue Op0 = N->getOperand(0); 9643 SDValue Op1 = N->getOperand(1); 9644 if (Op0.getOpcode() != ISD::CONCAT_VECTORS || 9645 Op1.getOpcode() != ISD::CONCAT_VECTORS || 9646 Op0.getNumOperands() != 2 || 9647 Op1.getNumOperands() != 2) 9648 return SDValue(); 9649 SDValue Concat0Op1 = Op0.getOperand(1); 9650 SDValue Concat1Op1 = Op1.getOperand(1); 9651 if (!Concat0Op1.isUndef() || !Concat1Op1.isUndef()) 9652 return SDValue(); 9653 // Skip the transformation if any of the types are illegal. 9654 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 9655 EVT VT = N->getValueType(0); 9656 if (!TLI.isTypeLegal(VT) || 9657 !TLI.isTypeLegal(Concat0Op1.getValueType()) || 9658 !TLI.isTypeLegal(Concat1Op1.getValueType())) 9659 return SDValue(); 9660 9661 SDValue NewConcat = DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT, 9662 Op0.getOperand(0), Op1.getOperand(0)); 9663 // Translate the shuffle mask. 9664 SmallVector<int, 16> NewMask; 9665 unsigned NumElts = VT.getVectorNumElements(); 9666 unsigned HalfElts = NumElts/2; 9667 ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N); 9668 for (unsigned n = 0; n < NumElts; ++n) { 9669 int MaskElt = SVN->getMaskElt(n); 9670 int NewElt = -1; 9671 if (MaskElt < (int)HalfElts) 9672 NewElt = MaskElt; 9673 else if (MaskElt >= (int)NumElts && MaskElt < (int)(NumElts + HalfElts)) 9674 NewElt = HalfElts + MaskElt - NumElts; 9675 NewMask.push_back(NewElt); 9676 } 9677 return DAG.getVectorShuffle(VT, SDLoc(N), NewConcat, 9678 DAG.getUNDEF(VT), NewMask.data()); 9679 } 9680 9681 /// CombineBaseUpdate - Target-specific DAG combine function for VLDDUP, 9682 /// NEON load/store intrinsics, and generic vector load/stores, to merge 9683 /// base address updates. 9684 /// For generic load/stores, the memory type is assumed to be a vector. 9685 /// The caller is assumed to have checked legality. 9686 static SDValue CombineBaseUpdate(SDNode *N, 9687 TargetLowering::DAGCombinerInfo &DCI) { 9688 SelectionDAG &DAG = DCI.DAG; 9689 const bool isIntrinsic = (N->getOpcode() == ISD::INTRINSIC_VOID || 9690 N->getOpcode() == ISD::INTRINSIC_W_CHAIN); 9691 const bool isStore = N->getOpcode() == ISD::STORE; 9692 const unsigned AddrOpIdx = ((isIntrinsic || isStore) ? 2 : 1); 9693 SDValue Addr = N->getOperand(AddrOpIdx); 9694 MemSDNode *MemN = cast<MemSDNode>(N); 9695 SDLoc dl(N); 9696 9697 // Search for a use of the address operand that is an increment. 9698 for (SDNode::use_iterator UI = Addr.getNode()->use_begin(), 9699 UE = Addr.getNode()->use_end(); UI != UE; ++UI) { 9700 SDNode *User = *UI; 9701 if (User->getOpcode() != ISD::ADD || 9702 UI.getUse().getResNo() != Addr.getResNo()) 9703 continue; 9704 9705 // Check that the add is independent of the load/store. Otherwise, folding 9706 // it would create a cycle. 9707 if (User->isPredecessorOf(N) || N->isPredecessorOf(User)) 9708 continue; 9709 9710 // Find the new opcode for the updating load/store. 9711 bool isLoadOp = true; 9712 bool isLaneOp = false; 9713 unsigned NewOpc = 0; 9714 unsigned NumVecs = 0; 9715 if (isIntrinsic) { 9716 unsigned IntNo = cast<ConstantSDNode>(N->getOperand(1))->getZExtValue(); 9717 switch (IntNo) { 9718 default: llvm_unreachable("unexpected intrinsic for Neon base update"); 9719 case Intrinsic::arm_neon_vld1: NewOpc = ARMISD::VLD1_UPD; 9720 NumVecs = 1; break; 9721 case Intrinsic::arm_neon_vld2: NewOpc = ARMISD::VLD2_UPD; 9722 NumVecs = 2; break; 9723 case Intrinsic::arm_neon_vld3: NewOpc = ARMISD::VLD3_UPD; 9724 NumVecs = 3; break; 9725 case Intrinsic::arm_neon_vld4: NewOpc = ARMISD::VLD4_UPD; 9726 NumVecs = 4; break; 9727 case Intrinsic::arm_neon_vld2lane: NewOpc = ARMISD::VLD2LN_UPD; 9728 NumVecs = 2; isLaneOp = true; break; 9729 case Intrinsic::arm_neon_vld3lane: NewOpc = ARMISD::VLD3LN_UPD; 9730 NumVecs = 3; isLaneOp = true; break; 9731 case Intrinsic::arm_neon_vld4lane: NewOpc = ARMISD::VLD4LN_UPD; 9732 NumVecs = 4; isLaneOp = true; break; 9733 case Intrinsic::arm_neon_vst1: NewOpc = ARMISD::VST1_UPD; 9734 NumVecs = 1; isLoadOp = false; break; 9735 case Intrinsic::arm_neon_vst2: NewOpc = ARMISD::VST2_UPD; 9736 NumVecs = 2; isLoadOp = false; break; 9737 case Intrinsic::arm_neon_vst3: NewOpc = ARMISD::VST3_UPD; 9738 NumVecs = 3; isLoadOp = false; break; 9739 case Intrinsic::arm_neon_vst4: NewOpc = ARMISD::VST4_UPD; 9740 NumVecs = 4; isLoadOp = false; break; 9741 case Intrinsic::arm_neon_vst2lane: NewOpc = ARMISD::VST2LN_UPD; 9742 NumVecs = 2; isLoadOp = false; isLaneOp = true; break; 9743 case Intrinsic::arm_neon_vst3lane: NewOpc = ARMISD::VST3LN_UPD; 9744 NumVecs = 3; isLoadOp = false; isLaneOp = true; break; 9745 case Intrinsic::arm_neon_vst4lane: NewOpc = ARMISD::VST4LN_UPD; 9746 NumVecs = 4; isLoadOp = false; isLaneOp = true; break; 9747 } 9748 } else { 9749 isLaneOp = true; 9750 switch (N->getOpcode()) { 9751 default: llvm_unreachable("unexpected opcode for Neon base update"); 9752 case ARMISD::VLD2DUP: NewOpc = ARMISD::VLD2DUP_UPD; NumVecs = 2; break; 9753 case ARMISD::VLD3DUP: NewOpc = ARMISD::VLD3DUP_UPD; NumVecs = 3; break; 9754 case ARMISD::VLD4DUP: NewOpc = ARMISD::VLD4DUP_UPD; NumVecs = 4; break; 9755 case ISD::LOAD: NewOpc = ARMISD::VLD1_UPD; 9756 NumVecs = 1; isLaneOp = false; break; 9757 case ISD::STORE: NewOpc = ARMISD::VST1_UPD; 9758 NumVecs = 1; isLaneOp = false; isLoadOp = false; break; 9759 } 9760 } 9761 9762 // Find the size of memory referenced by the load/store. 9763 EVT VecTy; 9764 if (isLoadOp) { 9765 VecTy = N->getValueType(0); 9766 } else if (isIntrinsic) { 9767 VecTy = N->getOperand(AddrOpIdx+1).getValueType(); 9768 } else { 9769 assert(isStore && "Node has to be a load, a store, or an intrinsic!"); 9770 VecTy = N->getOperand(1).getValueType(); 9771 } 9772 9773 unsigned NumBytes = NumVecs * VecTy.getSizeInBits() / 8; 9774 if (isLaneOp) 9775 NumBytes /= VecTy.getVectorNumElements(); 9776 9777 // If the increment is a constant, it must match the memory ref size. 9778 SDValue Inc = User->getOperand(User->getOperand(0) == Addr ? 1 : 0); 9779 if (ConstantSDNode *CInc = dyn_cast<ConstantSDNode>(Inc.getNode())) { 9780 uint64_t IncVal = CInc->getZExtValue(); 9781 if (IncVal != NumBytes) 9782 continue; 9783 } else if (NumBytes >= 3 * 16) { 9784 // VLD3/4 and VST3/4 for 128-bit vectors are implemented with two 9785 // separate instructions that make it harder to use a non-constant update. 9786 continue; 9787 } 9788 9789 // OK, we found an ADD we can fold into the base update. 9790 // Now, create a _UPD node, taking care of not breaking alignment. 9791 9792 EVT AlignedVecTy = VecTy; 9793 unsigned Alignment = MemN->getAlignment(); 9794 9795 // If this is a less-than-standard-aligned load/store, change the type to 9796 // match the standard alignment. 9797 // The alignment is overlooked when selecting _UPD variants; and it's 9798 // easier to introduce bitcasts here than fix that. 9799 // There are 3 ways to get to this base-update combine: 9800 // - intrinsics: they are assumed to be properly aligned (to the standard 9801 // alignment of the memory type), so we don't need to do anything. 9802 // - ARMISD::VLDx nodes: they are only generated from the aforementioned 9803 // intrinsics, so, likewise, there's nothing to do. 9804 // - generic load/store instructions: the alignment is specified as an 9805 // explicit operand, rather than implicitly as the standard alignment 9806 // of the memory type (like the intrisics). We need to change the 9807 // memory type to match the explicit alignment. That way, we don't 9808 // generate non-standard-aligned ARMISD::VLDx nodes. 9809 if (isa<LSBaseSDNode>(N)) { 9810 if (Alignment == 0) 9811 Alignment = 1; 9812 if (Alignment < VecTy.getScalarSizeInBits() / 8) { 9813 MVT EltTy = MVT::getIntegerVT(Alignment * 8); 9814 assert(NumVecs == 1 && "Unexpected multi-element generic load/store."); 9815 assert(!isLaneOp && "Unexpected generic load/store lane."); 9816 unsigned NumElts = NumBytes / (EltTy.getSizeInBits() / 8); 9817 AlignedVecTy = MVT::getVectorVT(EltTy, NumElts); 9818 } 9819 // Don't set an explicit alignment on regular load/stores that we want 9820 // to transform to VLD/VST 1_UPD nodes. 9821 // This matches the behavior of regular load/stores, which only get an 9822 // explicit alignment if the MMO alignment is larger than the standard 9823 // alignment of the memory type. 9824 // Intrinsics, however, always get an explicit alignment, set to the 9825 // alignment of the MMO. 9826 Alignment = 1; 9827 } 9828 9829 // Create the new updating load/store node. 9830 // First, create an SDVTList for the new updating node's results. 9831 EVT Tys[6]; 9832 unsigned NumResultVecs = (isLoadOp ? NumVecs : 0); 9833 unsigned n; 9834 for (n = 0; n < NumResultVecs; ++n) 9835 Tys[n] = AlignedVecTy; 9836 Tys[n++] = MVT::i32; 9837 Tys[n] = MVT::Other; 9838 SDVTList SDTys = DAG.getVTList(makeArrayRef(Tys, NumResultVecs+2)); 9839 9840 // Then, gather the new node's operands. 9841 SmallVector<SDValue, 8> Ops; 9842 Ops.push_back(N->getOperand(0)); // incoming chain 9843 Ops.push_back(N->getOperand(AddrOpIdx)); 9844 Ops.push_back(Inc); 9845 9846 if (StoreSDNode *StN = dyn_cast<StoreSDNode>(N)) { 9847 // Try to match the intrinsic's signature 9848 Ops.push_back(StN->getValue()); 9849 } else { 9850 // Loads (and of course intrinsics) match the intrinsics' signature, 9851 // so just add all but the alignment operand. 9852 for (unsigned i = AddrOpIdx + 1; i < N->getNumOperands() - 1; ++i) 9853 Ops.push_back(N->getOperand(i)); 9854 } 9855 9856 // For all node types, the alignment operand is always the last one. 9857 Ops.push_back(DAG.getConstant(Alignment, dl, MVT::i32)); 9858 9859 // If this is a non-standard-aligned STORE, the penultimate operand is the 9860 // stored value. Bitcast it to the aligned type. 9861 if (AlignedVecTy != VecTy && N->getOpcode() == ISD::STORE) { 9862 SDValue &StVal = Ops[Ops.size()-2]; 9863 StVal = DAG.getNode(ISD::BITCAST, dl, AlignedVecTy, StVal); 9864 } 9865 9866 SDValue UpdN = DAG.getMemIntrinsicNode(NewOpc, dl, SDTys, 9867 Ops, AlignedVecTy, 9868 MemN->getMemOperand()); 9869 9870 // Update the uses. 9871 SmallVector<SDValue, 5> NewResults; 9872 for (unsigned i = 0; i < NumResultVecs; ++i) 9873 NewResults.push_back(SDValue(UpdN.getNode(), i)); 9874 9875 // If this is an non-standard-aligned LOAD, the first result is the loaded 9876 // value. Bitcast it to the expected result type. 9877 if (AlignedVecTy != VecTy && N->getOpcode() == ISD::LOAD) { 9878 SDValue &LdVal = NewResults[0]; 9879 LdVal = DAG.getNode(ISD::BITCAST, dl, VecTy, LdVal); 9880 } 9881 9882 NewResults.push_back(SDValue(UpdN.getNode(), NumResultVecs+1)); // chain 9883 DCI.CombineTo(N, NewResults); 9884 DCI.CombineTo(User, SDValue(UpdN.getNode(), NumResultVecs)); 9885 9886 break; 9887 } 9888 return SDValue(); 9889 } 9890 9891 static SDValue PerformVLDCombine(SDNode *N, 9892 TargetLowering::DAGCombinerInfo &DCI) { 9893 if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer()) 9894 return SDValue(); 9895 9896 return CombineBaseUpdate(N, DCI); 9897 } 9898 9899 /// CombineVLDDUP - For a VDUPLANE node N, check if its source operand is a 9900 /// vldN-lane (N > 1) intrinsic, and if all the other uses of that intrinsic 9901 /// are also VDUPLANEs. If so, combine them to a vldN-dup operation and 9902 /// return true. 9903 static bool CombineVLDDUP(SDNode *N, TargetLowering::DAGCombinerInfo &DCI) { 9904 SelectionDAG &DAG = DCI.DAG; 9905 EVT VT = N->getValueType(0); 9906 // vldN-dup instructions only support 64-bit vectors for N > 1. 9907 if (!VT.is64BitVector()) 9908 return false; 9909 9910 // Check if the VDUPLANE operand is a vldN-dup intrinsic. 9911 SDNode *VLD = N->getOperand(0).getNode(); 9912 if (VLD->getOpcode() != ISD::INTRINSIC_W_CHAIN) 9913 return false; 9914 unsigned NumVecs = 0; 9915 unsigned NewOpc = 0; 9916 unsigned IntNo = cast<ConstantSDNode>(VLD->getOperand(1))->getZExtValue(); 9917 if (IntNo == Intrinsic::arm_neon_vld2lane) { 9918 NumVecs = 2; 9919 NewOpc = ARMISD::VLD2DUP; 9920 } else if (IntNo == Intrinsic::arm_neon_vld3lane) { 9921 NumVecs = 3; 9922 NewOpc = ARMISD::VLD3DUP; 9923 } else if (IntNo == Intrinsic::arm_neon_vld4lane) { 9924 NumVecs = 4; 9925 NewOpc = ARMISD::VLD4DUP; 9926 } else { 9927 return false; 9928 } 9929 9930 // First check that all the vldN-lane uses are VDUPLANEs and that the lane 9931 // numbers match the load. 9932 unsigned VLDLaneNo = 9933 cast<ConstantSDNode>(VLD->getOperand(NumVecs+3))->getZExtValue(); 9934 for (SDNode::use_iterator UI = VLD->use_begin(), UE = VLD->use_end(); 9935 UI != UE; ++UI) { 9936 // Ignore uses of the chain result. 9937 if (UI.getUse().getResNo() == NumVecs) 9938 continue; 9939 SDNode *User = *UI; 9940 if (User->getOpcode() != ARMISD::VDUPLANE || 9941 VLDLaneNo != cast<ConstantSDNode>(User->getOperand(1))->getZExtValue()) 9942 return false; 9943 } 9944 9945 // Create the vldN-dup node. 9946 EVT Tys[5]; 9947 unsigned n; 9948 for (n = 0; n < NumVecs; ++n) 9949 Tys[n] = VT; 9950 Tys[n] = MVT::Other; 9951 SDVTList SDTys = DAG.getVTList(makeArrayRef(Tys, NumVecs+1)); 9952 SDValue Ops[] = { VLD->getOperand(0), VLD->getOperand(2) }; 9953 MemIntrinsicSDNode *VLDMemInt = cast<MemIntrinsicSDNode>(VLD); 9954 SDValue VLDDup = DAG.getMemIntrinsicNode(NewOpc, SDLoc(VLD), SDTys, 9955 Ops, VLDMemInt->getMemoryVT(), 9956 VLDMemInt->getMemOperand()); 9957 9958 // Update the uses. 9959 for (SDNode::use_iterator UI = VLD->use_begin(), UE = VLD->use_end(); 9960 UI != UE; ++UI) { 9961 unsigned ResNo = UI.getUse().getResNo(); 9962 // Ignore uses of the chain result. 9963 if (ResNo == NumVecs) 9964 continue; 9965 SDNode *User = *UI; 9966 DCI.CombineTo(User, SDValue(VLDDup.getNode(), ResNo)); 9967 } 9968 9969 // Now the vldN-lane intrinsic is dead except for its chain result. 9970 // Update uses of the chain. 9971 std::vector<SDValue> VLDDupResults; 9972 for (unsigned n = 0; n < NumVecs; ++n) 9973 VLDDupResults.push_back(SDValue(VLDDup.getNode(), n)); 9974 VLDDupResults.push_back(SDValue(VLDDup.getNode(), NumVecs)); 9975 DCI.CombineTo(VLD, VLDDupResults); 9976 9977 return true; 9978 } 9979 9980 /// PerformVDUPLANECombine - Target-specific dag combine xforms for 9981 /// ARMISD::VDUPLANE. 9982 static SDValue PerformVDUPLANECombine(SDNode *N, 9983 TargetLowering::DAGCombinerInfo &DCI) { 9984 SDValue Op = N->getOperand(0); 9985 9986 // If the source is a vldN-lane (N > 1) intrinsic, and all the other uses 9987 // of that intrinsic are also VDUPLANEs, combine them to a vldN-dup operation. 9988 if (CombineVLDDUP(N, DCI)) 9989 return SDValue(N, 0); 9990 9991 // If the source is already a VMOVIMM or VMVNIMM splat, the VDUPLANE is 9992 // redundant. Ignore bit_converts for now; element sizes are checked below. 9993 while (Op.getOpcode() == ISD::BITCAST) 9994 Op = Op.getOperand(0); 9995 if (Op.getOpcode() != ARMISD::VMOVIMM && Op.getOpcode() != ARMISD::VMVNIMM) 9996 return SDValue(); 9997 9998 // Make sure the VMOV element size is not bigger than the VDUPLANE elements. 9999 unsigned EltSize = Op.getValueType().getVectorElementType().getSizeInBits(); 10000 // The canonical VMOV for a zero vector uses a 32-bit element size. 10001 unsigned Imm = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue(); 10002 unsigned EltBits; 10003 if (ARM_AM::decodeNEONModImm(Imm, EltBits) == 0) 10004 EltSize = 8; 10005 EVT VT = N->getValueType(0); 10006 if (EltSize > VT.getVectorElementType().getSizeInBits()) 10007 return SDValue(); 10008 10009 return DCI.DAG.getNode(ISD::BITCAST, SDLoc(N), VT, Op); 10010 } 10011 10012 static SDValue PerformLOADCombine(SDNode *N, 10013 TargetLowering::DAGCombinerInfo &DCI) { 10014 EVT VT = N->getValueType(0); 10015 10016 // If this is a legal vector load, try to combine it into a VLD1_UPD. 10017 if (ISD::isNormalLoad(N) && VT.isVector() && 10018 DCI.DAG.getTargetLoweringInfo().isTypeLegal(VT)) 10019 return CombineBaseUpdate(N, DCI); 10020 10021 return SDValue(); 10022 } 10023 10024 /// PerformSTORECombine - Target-specific dag combine xforms for 10025 /// ISD::STORE. 10026 static SDValue PerformSTORECombine(SDNode *N, 10027 TargetLowering::DAGCombinerInfo &DCI) { 10028 StoreSDNode *St = cast<StoreSDNode>(N); 10029 if (St->isVolatile()) 10030 return SDValue(); 10031 10032 // Optimize trunc store (of multiple scalars) to shuffle and store. First, 10033 // pack all of the elements in one place. Next, store to memory in fewer 10034 // chunks. 10035 SDValue StVal = St->getValue(); 10036 EVT VT = StVal.getValueType(); 10037 if (St->isTruncatingStore() && VT.isVector()) { 10038 SelectionDAG &DAG = DCI.DAG; 10039 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 10040 EVT StVT = St->getMemoryVT(); 10041 unsigned NumElems = VT.getVectorNumElements(); 10042 assert(StVT != VT && "Cannot truncate to the same type"); 10043 unsigned FromEltSz = VT.getVectorElementType().getSizeInBits(); 10044 unsigned ToEltSz = StVT.getVectorElementType().getSizeInBits(); 10045 10046 // From, To sizes and ElemCount must be pow of two 10047 if (!isPowerOf2_32(NumElems * FromEltSz * ToEltSz)) return SDValue(); 10048 10049 // We are going to use the original vector elt for storing. 10050 // Accumulated smaller vector elements must be a multiple of the store size. 10051 if (0 != (NumElems * FromEltSz) % ToEltSz) return SDValue(); 10052 10053 unsigned SizeRatio = FromEltSz / ToEltSz; 10054 assert(SizeRatio * NumElems * ToEltSz == VT.getSizeInBits()); 10055 10056 // Create a type on which we perform the shuffle. 10057 EVT WideVecVT = EVT::getVectorVT(*DAG.getContext(), StVT.getScalarType(), 10058 NumElems*SizeRatio); 10059 assert(WideVecVT.getSizeInBits() == VT.getSizeInBits()); 10060 10061 SDLoc DL(St); 10062 SDValue WideVec = DAG.getNode(ISD::BITCAST, DL, WideVecVT, StVal); 10063 SmallVector<int, 8> ShuffleVec(NumElems * SizeRatio, -1); 10064 for (unsigned i = 0; i < NumElems; ++i) 10065 ShuffleVec[i] = DAG.getDataLayout().isBigEndian() 10066 ? (i + 1) * SizeRatio - 1 10067 : i * SizeRatio; 10068 10069 // Can't shuffle using an illegal type. 10070 if (!TLI.isTypeLegal(WideVecVT)) return SDValue(); 10071 10072 SDValue Shuff = DAG.getVectorShuffle(WideVecVT, DL, WideVec, 10073 DAG.getUNDEF(WideVec.getValueType()), 10074 ShuffleVec.data()); 10075 // At this point all of the data is stored at the bottom of the 10076 // register. We now need to save it to mem. 10077 10078 // Find the largest store unit 10079 MVT StoreType = MVT::i8; 10080 for (MVT Tp : MVT::integer_valuetypes()) { 10081 if (TLI.isTypeLegal(Tp) && Tp.getSizeInBits() <= NumElems * ToEltSz) 10082 StoreType = Tp; 10083 } 10084 // Didn't find a legal store type. 10085 if (!TLI.isTypeLegal(StoreType)) 10086 return SDValue(); 10087 10088 // Bitcast the original vector into a vector of store-size units 10089 EVT StoreVecVT = EVT::getVectorVT(*DAG.getContext(), 10090 StoreType, VT.getSizeInBits()/EVT(StoreType).getSizeInBits()); 10091 assert(StoreVecVT.getSizeInBits() == VT.getSizeInBits()); 10092 SDValue ShuffWide = DAG.getNode(ISD::BITCAST, DL, StoreVecVT, Shuff); 10093 SmallVector<SDValue, 8> Chains; 10094 SDValue Increment = DAG.getConstant(StoreType.getSizeInBits() / 8, DL, 10095 TLI.getPointerTy(DAG.getDataLayout())); 10096 SDValue BasePtr = St->getBasePtr(); 10097 10098 // Perform one or more big stores into memory. 10099 unsigned E = (ToEltSz*NumElems)/StoreType.getSizeInBits(); 10100 for (unsigned I = 0; I < E; I++) { 10101 SDValue SubVec = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, 10102 StoreType, ShuffWide, 10103 DAG.getIntPtrConstant(I, DL)); 10104 SDValue Ch = DAG.getStore(St->getChain(), DL, SubVec, BasePtr, 10105 St->getPointerInfo(), St->isVolatile(), 10106 St->isNonTemporal(), St->getAlignment()); 10107 BasePtr = DAG.getNode(ISD::ADD, DL, BasePtr.getValueType(), BasePtr, 10108 Increment); 10109 Chains.push_back(Ch); 10110 } 10111 return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Chains); 10112 } 10113 10114 if (!ISD::isNormalStore(St)) 10115 return SDValue(); 10116 10117 // Split a store of a VMOVDRR into two integer stores to avoid mixing NEON and 10118 // ARM stores of arguments in the same cache line. 10119 if (StVal.getNode()->getOpcode() == ARMISD::VMOVDRR && 10120 StVal.getNode()->hasOneUse()) { 10121 SelectionDAG &DAG = DCI.DAG; 10122 bool isBigEndian = DAG.getDataLayout().isBigEndian(); 10123 SDLoc DL(St); 10124 SDValue BasePtr = St->getBasePtr(); 10125 SDValue NewST1 = DAG.getStore(St->getChain(), DL, 10126 StVal.getNode()->getOperand(isBigEndian ? 1 : 0 ), 10127 BasePtr, St->getPointerInfo(), St->isVolatile(), 10128 St->isNonTemporal(), St->getAlignment()); 10129 10130 SDValue OffsetPtr = DAG.getNode(ISD::ADD, DL, MVT::i32, BasePtr, 10131 DAG.getConstant(4, DL, MVT::i32)); 10132 return DAG.getStore(NewST1.getValue(0), DL, 10133 StVal.getNode()->getOperand(isBigEndian ? 0 : 1), 10134 OffsetPtr, St->getPointerInfo(), St->isVolatile(), 10135 St->isNonTemporal(), 10136 std::min(4U, St->getAlignment() / 2)); 10137 } 10138 10139 if (StVal.getValueType() == MVT::i64 && 10140 StVal.getNode()->getOpcode() == ISD::EXTRACT_VECTOR_ELT) { 10141 10142 // Bitcast an i64 store extracted from a vector to f64. 10143 // Otherwise, the i64 value will be legalized to a pair of i32 values. 10144 SelectionDAG &DAG = DCI.DAG; 10145 SDLoc dl(StVal); 10146 SDValue IntVec = StVal.getOperand(0); 10147 EVT FloatVT = EVT::getVectorVT(*DAG.getContext(), MVT::f64, 10148 IntVec.getValueType().getVectorNumElements()); 10149 SDValue Vec = DAG.getNode(ISD::BITCAST, dl, FloatVT, IntVec); 10150 SDValue ExtElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, 10151 Vec, StVal.getOperand(1)); 10152 dl = SDLoc(N); 10153 SDValue V = DAG.getNode(ISD::BITCAST, dl, MVT::i64, ExtElt); 10154 // Make the DAGCombiner fold the bitcasts. 10155 DCI.AddToWorklist(Vec.getNode()); 10156 DCI.AddToWorklist(ExtElt.getNode()); 10157 DCI.AddToWorklist(V.getNode()); 10158 return DAG.getStore(St->getChain(), dl, V, St->getBasePtr(), 10159 St->getPointerInfo(), St->isVolatile(), 10160 St->isNonTemporal(), St->getAlignment(), 10161 St->getAAInfo()); 10162 } 10163 10164 // If this is a legal vector store, try to combine it into a VST1_UPD. 10165 if (ISD::isNormalStore(N) && VT.isVector() && 10166 DCI.DAG.getTargetLoweringInfo().isTypeLegal(VT)) 10167 return CombineBaseUpdate(N, DCI); 10168 10169 return SDValue(); 10170 } 10171 10172 /// PerformVCVTCombine - VCVT (floating-point to fixed-point, Advanced SIMD) 10173 /// can replace combinations of VMUL and VCVT (floating-point to integer) 10174 /// when the VMUL has a constant operand that is a power of 2. 10175 /// 10176 /// Example (assume d17 = <float 8.000000e+00, float 8.000000e+00>): 10177 /// vmul.f32 d16, d17, d16 10178 /// vcvt.s32.f32 d16, d16 10179 /// becomes: 10180 /// vcvt.s32.f32 d16, d16, #3 10181 static SDValue PerformVCVTCombine(SDNode *N, SelectionDAG &DAG, 10182 const ARMSubtarget *Subtarget) { 10183 if (!Subtarget->hasNEON()) 10184 return SDValue(); 10185 10186 SDValue Op = N->getOperand(0); 10187 if (!Op.getValueType().isVector() || !Op.getValueType().isSimple() || 10188 Op.getOpcode() != ISD::FMUL) 10189 return SDValue(); 10190 10191 SDValue ConstVec = Op->getOperand(1); 10192 if (!isa<BuildVectorSDNode>(ConstVec)) 10193 return SDValue(); 10194 10195 MVT FloatTy = Op.getSimpleValueType().getVectorElementType(); 10196 uint32_t FloatBits = FloatTy.getSizeInBits(); 10197 MVT IntTy = N->getSimpleValueType(0).getVectorElementType(); 10198 uint32_t IntBits = IntTy.getSizeInBits(); 10199 unsigned NumLanes = Op.getValueType().getVectorNumElements(); 10200 if (FloatBits != 32 || IntBits > 32 || NumLanes > 4) { 10201 // These instructions only exist converting from f32 to i32. We can handle 10202 // smaller integers by generating an extra truncate, but larger ones would 10203 // be lossy. We also can't handle more then 4 lanes, since these intructions 10204 // only support v2i32/v4i32 types. 10205 return SDValue(); 10206 } 10207 10208 BitVector UndefElements; 10209 BuildVectorSDNode *BV = cast<BuildVectorSDNode>(ConstVec); 10210 int32_t C = BV->getConstantFPSplatPow2ToLog2Int(&UndefElements, 33); 10211 if (C == -1 || C == 0 || C > 32) 10212 return SDValue(); 10213 10214 SDLoc dl(N); 10215 bool isSigned = N->getOpcode() == ISD::FP_TO_SINT; 10216 unsigned IntrinsicOpcode = isSigned ? Intrinsic::arm_neon_vcvtfp2fxs : 10217 Intrinsic::arm_neon_vcvtfp2fxu; 10218 SDValue FixConv = DAG.getNode( 10219 ISD::INTRINSIC_WO_CHAIN, dl, NumLanes == 2 ? MVT::v2i32 : MVT::v4i32, 10220 DAG.getConstant(IntrinsicOpcode, dl, MVT::i32), Op->getOperand(0), 10221 DAG.getConstant(C, dl, MVT::i32)); 10222 10223 if (IntBits < FloatBits) 10224 FixConv = DAG.getNode(ISD::TRUNCATE, dl, N->getValueType(0), FixConv); 10225 10226 return FixConv; 10227 } 10228 10229 /// PerformVDIVCombine - VCVT (fixed-point to floating-point, Advanced SIMD) 10230 /// can replace combinations of VCVT (integer to floating-point) and VDIV 10231 /// when the VDIV has a constant operand that is a power of 2. 10232 /// 10233 /// Example (assume d17 = <float 8.000000e+00, float 8.000000e+00>): 10234 /// vcvt.f32.s32 d16, d16 10235 /// vdiv.f32 d16, d17, d16 10236 /// becomes: 10237 /// vcvt.f32.s32 d16, d16, #3 10238 static SDValue PerformVDIVCombine(SDNode *N, SelectionDAG &DAG, 10239 const ARMSubtarget *Subtarget) { 10240 if (!Subtarget->hasNEON()) 10241 return SDValue(); 10242 10243 SDValue Op = N->getOperand(0); 10244 unsigned OpOpcode = Op.getNode()->getOpcode(); 10245 if (!N->getValueType(0).isVector() || !N->getValueType(0).isSimple() || 10246 (OpOpcode != ISD::SINT_TO_FP && OpOpcode != ISD::UINT_TO_FP)) 10247 return SDValue(); 10248 10249 SDValue ConstVec = N->getOperand(1); 10250 if (!isa<BuildVectorSDNode>(ConstVec)) 10251 return SDValue(); 10252 10253 MVT FloatTy = N->getSimpleValueType(0).getVectorElementType(); 10254 uint32_t FloatBits = FloatTy.getSizeInBits(); 10255 MVT IntTy = Op.getOperand(0).getSimpleValueType().getVectorElementType(); 10256 uint32_t IntBits = IntTy.getSizeInBits(); 10257 unsigned NumLanes = Op.getValueType().getVectorNumElements(); 10258 if (FloatBits != 32 || IntBits > 32 || NumLanes > 4) { 10259 // These instructions only exist converting from i32 to f32. We can handle 10260 // smaller integers by generating an extra extend, but larger ones would 10261 // be lossy. We also can't handle more then 4 lanes, since these intructions 10262 // only support v2i32/v4i32 types. 10263 return SDValue(); 10264 } 10265 10266 BitVector UndefElements; 10267 BuildVectorSDNode *BV = cast<BuildVectorSDNode>(ConstVec); 10268 int32_t C = BV->getConstantFPSplatPow2ToLog2Int(&UndefElements, 33); 10269 if (C == -1 || C == 0 || C > 32) 10270 return SDValue(); 10271 10272 SDLoc dl(N); 10273 bool isSigned = OpOpcode == ISD::SINT_TO_FP; 10274 SDValue ConvInput = Op.getOperand(0); 10275 if (IntBits < FloatBits) 10276 ConvInput = DAG.getNode(isSigned ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND, 10277 dl, NumLanes == 2 ? MVT::v2i32 : MVT::v4i32, 10278 ConvInput); 10279 10280 unsigned IntrinsicOpcode = isSigned ? Intrinsic::arm_neon_vcvtfxs2fp : 10281 Intrinsic::arm_neon_vcvtfxu2fp; 10282 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, 10283 Op.getValueType(), 10284 DAG.getConstant(IntrinsicOpcode, dl, MVT::i32), 10285 ConvInput, DAG.getConstant(C, dl, MVT::i32)); 10286 } 10287 10288 /// Getvshiftimm - Check if this is a valid build_vector for the immediate 10289 /// operand of a vector shift operation, where all the elements of the 10290 /// build_vector must have the same constant integer value. 10291 static bool getVShiftImm(SDValue Op, unsigned ElementBits, int64_t &Cnt) { 10292 // Ignore bit_converts. 10293 while (Op.getOpcode() == ISD::BITCAST) 10294 Op = Op.getOperand(0); 10295 BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(Op.getNode()); 10296 APInt SplatBits, SplatUndef; 10297 unsigned SplatBitSize; 10298 bool HasAnyUndefs; 10299 if (! BVN || ! BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, 10300 HasAnyUndefs, ElementBits) || 10301 SplatBitSize > ElementBits) 10302 return false; 10303 Cnt = SplatBits.getSExtValue(); 10304 return true; 10305 } 10306 10307 /// isVShiftLImm - Check if this is a valid build_vector for the immediate 10308 /// operand of a vector shift left operation. That value must be in the range: 10309 /// 0 <= Value < ElementBits for a left shift; or 10310 /// 0 <= Value <= ElementBits for a long left shift. 10311 static bool isVShiftLImm(SDValue Op, EVT VT, bool isLong, int64_t &Cnt) { 10312 assert(VT.isVector() && "vector shift count is not a vector type"); 10313 int64_t ElementBits = VT.getVectorElementType().getSizeInBits(); 10314 if (! getVShiftImm(Op, ElementBits, Cnt)) 10315 return false; 10316 return (Cnt >= 0 && (isLong ? Cnt-1 : Cnt) < ElementBits); 10317 } 10318 10319 /// isVShiftRImm - Check if this is a valid build_vector for the immediate 10320 /// operand of a vector shift right operation. For a shift opcode, the value 10321 /// is positive, but for an intrinsic the value count must be negative. The 10322 /// absolute value must be in the range: 10323 /// 1 <= |Value| <= ElementBits for a right shift; or 10324 /// 1 <= |Value| <= ElementBits/2 for a narrow right shift. 10325 static bool isVShiftRImm(SDValue Op, EVT VT, bool isNarrow, bool isIntrinsic, 10326 int64_t &Cnt) { 10327 assert(VT.isVector() && "vector shift count is not a vector type"); 10328 int64_t ElementBits = VT.getVectorElementType().getSizeInBits(); 10329 if (! getVShiftImm(Op, ElementBits, Cnt)) 10330 return false; 10331 if (!isIntrinsic) 10332 return (Cnt >= 1 && Cnt <= (isNarrow ? ElementBits/2 : ElementBits)); 10333 if (Cnt >= -(isNarrow ? ElementBits/2 : ElementBits) && Cnt <= -1) { 10334 Cnt = -Cnt; 10335 return true; 10336 } 10337 return false; 10338 } 10339 10340 /// PerformIntrinsicCombine - ARM-specific DAG combining for intrinsics. 10341 static SDValue PerformIntrinsicCombine(SDNode *N, SelectionDAG &DAG) { 10342 unsigned IntNo = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue(); 10343 switch (IntNo) { 10344 default: 10345 // Don't do anything for most intrinsics. 10346 break; 10347 10348 // Vector shifts: check for immediate versions and lower them. 10349 // Note: This is done during DAG combining instead of DAG legalizing because 10350 // the build_vectors for 64-bit vector element shift counts are generally 10351 // not legal, and it is hard to see their values after they get legalized to 10352 // loads from a constant pool. 10353 case Intrinsic::arm_neon_vshifts: 10354 case Intrinsic::arm_neon_vshiftu: 10355 case Intrinsic::arm_neon_vrshifts: 10356 case Intrinsic::arm_neon_vrshiftu: 10357 case Intrinsic::arm_neon_vrshiftn: 10358 case Intrinsic::arm_neon_vqshifts: 10359 case Intrinsic::arm_neon_vqshiftu: 10360 case Intrinsic::arm_neon_vqshiftsu: 10361 case Intrinsic::arm_neon_vqshiftns: 10362 case Intrinsic::arm_neon_vqshiftnu: 10363 case Intrinsic::arm_neon_vqshiftnsu: 10364 case Intrinsic::arm_neon_vqrshiftns: 10365 case Intrinsic::arm_neon_vqrshiftnu: 10366 case Intrinsic::arm_neon_vqrshiftnsu: { 10367 EVT VT = N->getOperand(1).getValueType(); 10368 int64_t Cnt; 10369 unsigned VShiftOpc = 0; 10370 10371 switch (IntNo) { 10372 case Intrinsic::arm_neon_vshifts: 10373 case Intrinsic::arm_neon_vshiftu: 10374 if (isVShiftLImm(N->getOperand(2), VT, false, Cnt)) { 10375 VShiftOpc = ARMISD::VSHL; 10376 break; 10377 } 10378 if (isVShiftRImm(N->getOperand(2), VT, false, true, Cnt)) { 10379 VShiftOpc = (IntNo == Intrinsic::arm_neon_vshifts ? 10380 ARMISD::VSHRs : ARMISD::VSHRu); 10381 break; 10382 } 10383 return SDValue(); 10384 10385 case Intrinsic::arm_neon_vrshifts: 10386 case Intrinsic::arm_neon_vrshiftu: 10387 if (isVShiftRImm(N->getOperand(2), VT, false, true, Cnt)) 10388 break; 10389 return SDValue(); 10390 10391 case Intrinsic::arm_neon_vqshifts: 10392 case Intrinsic::arm_neon_vqshiftu: 10393 if (isVShiftLImm(N->getOperand(2), VT, false, Cnt)) 10394 break; 10395 return SDValue(); 10396 10397 case Intrinsic::arm_neon_vqshiftsu: 10398 if (isVShiftLImm(N->getOperand(2), VT, false, Cnt)) 10399 break; 10400 llvm_unreachable("invalid shift count for vqshlu intrinsic"); 10401 10402 case Intrinsic::arm_neon_vrshiftn: 10403 case Intrinsic::arm_neon_vqshiftns: 10404 case Intrinsic::arm_neon_vqshiftnu: 10405 case Intrinsic::arm_neon_vqshiftnsu: 10406 case Intrinsic::arm_neon_vqrshiftns: 10407 case Intrinsic::arm_neon_vqrshiftnu: 10408 case Intrinsic::arm_neon_vqrshiftnsu: 10409 // Narrowing shifts require an immediate right shift. 10410 if (isVShiftRImm(N->getOperand(2), VT, true, true, Cnt)) 10411 break; 10412 llvm_unreachable("invalid shift count for narrowing vector shift " 10413 "intrinsic"); 10414 10415 default: 10416 llvm_unreachable("unhandled vector shift"); 10417 } 10418 10419 switch (IntNo) { 10420 case Intrinsic::arm_neon_vshifts: 10421 case Intrinsic::arm_neon_vshiftu: 10422 // Opcode already set above. 10423 break; 10424 case Intrinsic::arm_neon_vrshifts: 10425 VShiftOpc = ARMISD::VRSHRs; break; 10426 case Intrinsic::arm_neon_vrshiftu: 10427 VShiftOpc = ARMISD::VRSHRu; break; 10428 case Intrinsic::arm_neon_vrshiftn: 10429 VShiftOpc = ARMISD::VRSHRN; break; 10430 case Intrinsic::arm_neon_vqshifts: 10431 VShiftOpc = ARMISD::VQSHLs; break; 10432 case Intrinsic::arm_neon_vqshiftu: 10433 VShiftOpc = ARMISD::VQSHLu; break; 10434 case Intrinsic::arm_neon_vqshiftsu: 10435 VShiftOpc = ARMISD::VQSHLsu; break; 10436 case Intrinsic::arm_neon_vqshiftns: 10437 VShiftOpc = ARMISD::VQSHRNs; break; 10438 case Intrinsic::arm_neon_vqshiftnu: 10439 VShiftOpc = ARMISD::VQSHRNu; break; 10440 case Intrinsic::arm_neon_vqshiftnsu: 10441 VShiftOpc = ARMISD::VQSHRNsu; break; 10442 case Intrinsic::arm_neon_vqrshiftns: 10443 VShiftOpc = ARMISD::VQRSHRNs; break; 10444 case Intrinsic::arm_neon_vqrshiftnu: 10445 VShiftOpc = ARMISD::VQRSHRNu; break; 10446 case Intrinsic::arm_neon_vqrshiftnsu: 10447 VShiftOpc = ARMISD::VQRSHRNsu; break; 10448 } 10449 10450 SDLoc dl(N); 10451 return DAG.getNode(VShiftOpc, dl, N->getValueType(0), 10452 N->getOperand(1), DAG.getConstant(Cnt, dl, MVT::i32)); 10453 } 10454 10455 case Intrinsic::arm_neon_vshiftins: { 10456 EVT VT = N->getOperand(1).getValueType(); 10457 int64_t Cnt; 10458 unsigned VShiftOpc = 0; 10459 10460 if (isVShiftLImm(N->getOperand(3), VT, false, Cnt)) 10461 VShiftOpc = ARMISD::VSLI; 10462 else if (isVShiftRImm(N->getOperand(3), VT, false, true, Cnt)) 10463 VShiftOpc = ARMISD::VSRI; 10464 else { 10465 llvm_unreachable("invalid shift count for vsli/vsri intrinsic"); 10466 } 10467 10468 SDLoc dl(N); 10469 return DAG.getNode(VShiftOpc, dl, N->getValueType(0), 10470 N->getOperand(1), N->getOperand(2), 10471 DAG.getConstant(Cnt, dl, MVT::i32)); 10472 } 10473 10474 case Intrinsic::arm_neon_vqrshifts: 10475 case Intrinsic::arm_neon_vqrshiftu: 10476 // No immediate versions of these to check for. 10477 break; 10478 } 10479 10480 return SDValue(); 10481 } 10482 10483 /// PerformShiftCombine - Checks for immediate versions of vector shifts and 10484 /// lowers them. As with the vector shift intrinsics, this is done during DAG 10485 /// combining instead of DAG legalizing because the build_vectors for 64-bit 10486 /// vector element shift counts are generally not legal, and it is hard to see 10487 /// their values after they get legalized to loads from a constant pool. 10488 static SDValue PerformShiftCombine(SDNode *N, SelectionDAG &DAG, 10489 const ARMSubtarget *ST) { 10490 EVT VT = N->getValueType(0); 10491 if (N->getOpcode() == ISD::SRL && VT == MVT::i32 && ST->hasV6Ops()) { 10492 // Canonicalize (srl (bswap x), 16) to (rotr (bswap x), 16) if the high 10493 // 16-bits of x is zero. This optimizes rev + lsr 16 to rev16. 10494 SDValue N1 = N->getOperand(1); 10495 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(N1)) { 10496 SDValue N0 = N->getOperand(0); 10497 if (C->getZExtValue() == 16 && N0.getOpcode() == ISD::BSWAP && 10498 DAG.MaskedValueIsZero(N0.getOperand(0), 10499 APInt::getHighBitsSet(32, 16))) 10500 return DAG.getNode(ISD::ROTR, SDLoc(N), VT, N0, N1); 10501 } 10502 } 10503 10504 // Nothing to be done for scalar shifts. 10505 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 10506 if (!VT.isVector() || !TLI.isTypeLegal(VT)) 10507 return SDValue(); 10508 10509 assert(ST->hasNEON() && "unexpected vector shift"); 10510 int64_t Cnt; 10511 10512 switch (N->getOpcode()) { 10513 default: llvm_unreachable("unexpected shift opcode"); 10514 10515 case ISD::SHL: 10516 if (isVShiftLImm(N->getOperand(1), VT, false, Cnt)) { 10517 SDLoc dl(N); 10518 return DAG.getNode(ARMISD::VSHL, dl, VT, N->getOperand(0), 10519 DAG.getConstant(Cnt, dl, MVT::i32)); 10520 } 10521 break; 10522 10523 case ISD::SRA: 10524 case ISD::SRL: 10525 if (isVShiftRImm(N->getOperand(1), VT, false, false, Cnt)) { 10526 unsigned VShiftOpc = (N->getOpcode() == ISD::SRA ? 10527 ARMISD::VSHRs : ARMISD::VSHRu); 10528 SDLoc dl(N); 10529 return DAG.getNode(VShiftOpc, dl, VT, N->getOperand(0), 10530 DAG.getConstant(Cnt, dl, MVT::i32)); 10531 } 10532 } 10533 return SDValue(); 10534 } 10535 10536 /// PerformExtendCombine - Target-specific DAG combining for ISD::SIGN_EXTEND, 10537 /// ISD::ZERO_EXTEND, and ISD::ANY_EXTEND. 10538 static SDValue PerformExtendCombine(SDNode *N, SelectionDAG &DAG, 10539 const ARMSubtarget *ST) { 10540 SDValue N0 = N->getOperand(0); 10541 10542 // Check for sign- and zero-extensions of vector extract operations of 8- 10543 // and 16-bit vector elements. NEON supports these directly. They are 10544 // handled during DAG combining because type legalization will promote them 10545 // to 32-bit types and it is messy to recognize the operations after that. 10546 if (ST->hasNEON() && N0.getOpcode() == ISD::EXTRACT_VECTOR_ELT) { 10547 SDValue Vec = N0.getOperand(0); 10548 SDValue Lane = N0.getOperand(1); 10549 EVT VT = N->getValueType(0); 10550 EVT EltVT = N0.getValueType(); 10551 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 10552 10553 if (VT == MVT::i32 && 10554 (EltVT == MVT::i8 || EltVT == MVT::i16) && 10555 TLI.isTypeLegal(Vec.getValueType()) && 10556 isa<ConstantSDNode>(Lane)) { 10557 10558 unsigned Opc = 0; 10559 switch (N->getOpcode()) { 10560 default: llvm_unreachable("unexpected opcode"); 10561 case ISD::SIGN_EXTEND: 10562 Opc = ARMISD::VGETLANEs; 10563 break; 10564 case ISD::ZERO_EXTEND: 10565 case ISD::ANY_EXTEND: 10566 Opc = ARMISD::VGETLANEu; 10567 break; 10568 } 10569 return DAG.getNode(Opc, SDLoc(N), VT, Vec, Lane); 10570 } 10571 } 10572 10573 return SDValue(); 10574 } 10575 10576 static void computeKnownBits(SelectionDAG &DAG, SDValue Op, APInt &KnownZero, 10577 APInt &KnownOne) { 10578 if (Op.getOpcode() == ARMISD::BFI) { 10579 // Conservatively, we can recurse down the first operand 10580 // and just mask out all affected bits. 10581 computeKnownBits(DAG, Op.getOperand(0), KnownZero, KnownOne); 10582 10583 // The operand to BFI is already a mask suitable for removing the bits it 10584 // sets. 10585 ConstantSDNode *CI = cast<ConstantSDNode>(Op.getOperand(2)); 10586 APInt Mask = CI->getAPIntValue(); 10587 KnownZero &= Mask; 10588 KnownOne &= Mask; 10589 return; 10590 } 10591 if (Op.getOpcode() == ARMISD::CMOV) { 10592 APInt KZ2(KnownZero.getBitWidth(), 0); 10593 APInt KO2(KnownOne.getBitWidth(), 0); 10594 computeKnownBits(DAG, Op.getOperand(1), KnownZero, KnownOne); 10595 computeKnownBits(DAG, Op.getOperand(2), KZ2, KO2); 10596 10597 KnownZero &= KZ2; 10598 KnownOne &= KO2; 10599 return; 10600 } 10601 return DAG.computeKnownBits(Op, KnownZero, KnownOne); 10602 } 10603 10604 SDValue ARMTargetLowering::PerformCMOVToBFICombine(SDNode *CMOV, SelectionDAG &DAG) const { 10605 // If we have a CMOV, OR and AND combination such as: 10606 // if (x & CN) 10607 // y |= CM; 10608 // 10609 // And: 10610 // * CN is a single bit; 10611 // * All bits covered by CM are known zero in y 10612 // 10613 // Then we can convert this into a sequence of BFI instructions. This will 10614 // always be a win if CM is a single bit, will always be no worse than the 10615 // TST&OR sequence if CM is two bits, and for thumb will be no worse if CM is 10616 // three bits (due to the extra IT instruction). 10617 10618 SDValue Op0 = CMOV->getOperand(0); 10619 SDValue Op1 = CMOV->getOperand(1); 10620 auto CCNode = cast<ConstantSDNode>(CMOV->getOperand(2)); 10621 auto CC = CCNode->getAPIntValue().getLimitedValue(); 10622 SDValue CmpZ = CMOV->getOperand(4); 10623 10624 // The compare must be against zero. 10625 if (!isNullConstant(CmpZ->getOperand(1))) 10626 return SDValue(); 10627 10628 assert(CmpZ->getOpcode() == ARMISD::CMPZ); 10629 SDValue And = CmpZ->getOperand(0); 10630 if (And->getOpcode() != ISD::AND) 10631 return SDValue(); 10632 ConstantSDNode *AndC = dyn_cast<ConstantSDNode>(And->getOperand(1)); 10633 if (!AndC || !AndC->getAPIntValue().isPowerOf2()) 10634 return SDValue(); 10635 SDValue X = And->getOperand(0); 10636 10637 if (CC == ARMCC::EQ) { 10638 // We're performing an "equal to zero" compare. Swap the operands so we 10639 // canonicalize on a "not equal to zero" compare. 10640 std::swap(Op0, Op1); 10641 } else { 10642 assert(CC == ARMCC::NE && "How can a CMPZ node not be EQ or NE?"); 10643 } 10644 10645 if (Op1->getOpcode() != ISD::OR) 10646 return SDValue(); 10647 10648 ConstantSDNode *OrC = dyn_cast<ConstantSDNode>(Op1->getOperand(1)); 10649 if (!OrC) 10650 return SDValue(); 10651 SDValue Y = Op1->getOperand(0); 10652 10653 if (Op0 != Y) 10654 return SDValue(); 10655 10656 // Now, is it profitable to continue? 10657 APInt OrCI = OrC->getAPIntValue(); 10658 unsigned Heuristic = Subtarget->isThumb() ? 3 : 2; 10659 if (OrCI.countPopulation() > Heuristic) 10660 return SDValue(); 10661 10662 // Lastly, can we determine that the bits defined by OrCI 10663 // are zero in Y? 10664 APInt KnownZero, KnownOne; 10665 computeKnownBits(DAG, Y, KnownZero, KnownOne); 10666 if ((OrCI & KnownZero) != OrCI) 10667 return SDValue(); 10668 10669 // OK, we can do the combine. 10670 SDValue V = Y; 10671 SDLoc dl(X); 10672 EVT VT = X.getValueType(); 10673 unsigned BitInX = AndC->getAPIntValue().logBase2(); 10674 10675 if (BitInX != 0) { 10676 // We must shift X first. 10677 X = DAG.getNode(ISD::SRL, dl, VT, X, 10678 DAG.getConstant(BitInX, dl, VT)); 10679 } 10680 10681 for (unsigned BitInY = 0, NumActiveBits = OrCI.getActiveBits(); 10682 BitInY < NumActiveBits; ++BitInY) { 10683 if (OrCI[BitInY] == 0) 10684 continue; 10685 APInt Mask(VT.getSizeInBits(), 0); 10686 Mask.setBit(BitInY); 10687 V = DAG.getNode(ARMISD::BFI, dl, VT, V, X, 10688 // Confusingly, the operand is an *inverted* mask. 10689 DAG.getConstant(~Mask, dl, VT)); 10690 } 10691 10692 return V; 10693 } 10694 10695 /// PerformBRCONDCombine - Target-specific DAG combining for ARMISD::BRCOND. 10696 SDValue 10697 ARMTargetLowering::PerformBRCONDCombine(SDNode *N, SelectionDAG &DAG) const { 10698 SDValue Cmp = N->getOperand(4); 10699 if (Cmp.getOpcode() != ARMISD::CMPZ) 10700 // Only looking at NE cases. 10701 return SDValue(); 10702 10703 EVT VT = N->getValueType(0); 10704 SDLoc dl(N); 10705 SDValue LHS = Cmp.getOperand(0); 10706 SDValue RHS = Cmp.getOperand(1); 10707 SDValue Chain = N->getOperand(0); 10708 SDValue BB = N->getOperand(1); 10709 SDValue ARMcc = N->getOperand(2); 10710 ARMCC::CondCodes CC = 10711 (ARMCC::CondCodes)cast<ConstantSDNode>(ARMcc)->getZExtValue(); 10712 10713 // (brcond Chain BB ne CPSR (cmpz (and (cmov 0 1 CC CPSR Cmp) 1) 0)) 10714 // -> (brcond Chain BB CC CPSR Cmp) 10715 if (CC == ARMCC::NE && LHS.getOpcode() == ISD::AND && LHS->hasOneUse() && 10716 LHS->getOperand(0)->getOpcode() == ARMISD::CMOV && 10717 LHS->getOperand(0)->hasOneUse()) { 10718 auto *LHS00C = dyn_cast<ConstantSDNode>(LHS->getOperand(0)->getOperand(0)); 10719 auto *LHS01C = dyn_cast<ConstantSDNode>(LHS->getOperand(0)->getOperand(1)); 10720 auto *LHS1C = dyn_cast<ConstantSDNode>(LHS->getOperand(1)); 10721 auto *RHSC = dyn_cast<ConstantSDNode>(RHS); 10722 if ((LHS00C && LHS00C->getZExtValue() == 0) && 10723 (LHS01C && LHS01C->getZExtValue() == 1) && 10724 (LHS1C && LHS1C->getZExtValue() == 1) && 10725 (RHSC && RHSC->getZExtValue() == 0)) { 10726 return DAG.getNode( 10727 ARMISD::BRCOND, dl, VT, Chain, BB, LHS->getOperand(0)->getOperand(2), 10728 LHS->getOperand(0)->getOperand(3), LHS->getOperand(0)->getOperand(4)); 10729 } 10730 } 10731 10732 return SDValue(); 10733 } 10734 10735 /// PerformCMOVCombine - Target-specific DAG combining for ARMISD::CMOV. 10736 SDValue 10737 ARMTargetLowering::PerformCMOVCombine(SDNode *N, SelectionDAG &DAG) const { 10738 SDValue Cmp = N->getOperand(4); 10739 if (Cmp.getOpcode() != ARMISD::CMPZ) 10740 // Only looking at EQ and NE cases. 10741 return SDValue(); 10742 10743 EVT VT = N->getValueType(0); 10744 SDLoc dl(N); 10745 SDValue LHS = Cmp.getOperand(0); 10746 SDValue RHS = Cmp.getOperand(1); 10747 SDValue FalseVal = N->getOperand(0); 10748 SDValue TrueVal = N->getOperand(1); 10749 SDValue ARMcc = N->getOperand(2); 10750 ARMCC::CondCodes CC = 10751 (ARMCC::CondCodes)cast<ConstantSDNode>(ARMcc)->getZExtValue(); 10752 10753 // BFI is only available on V6T2+. 10754 if (!Subtarget->isThumb1Only() && Subtarget->hasV6T2Ops()) { 10755 SDValue R = PerformCMOVToBFICombine(N, DAG); 10756 if (R) 10757 return R; 10758 } 10759 10760 // Simplify 10761 // mov r1, r0 10762 // cmp r1, x 10763 // mov r0, y 10764 // moveq r0, x 10765 // to 10766 // cmp r0, x 10767 // movne r0, y 10768 // 10769 // mov r1, r0 10770 // cmp r1, x 10771 // mov r0, x 10772 // movne r0, y 10773 // to 10774 // cmp r0, x 10775 // movne r0, y 10776 /// FIXME: Turn this into a target neutral optimization? 10777 SDValue Res; 10778 if (CC == ARMCC::NE && FalseVal == RHS && FalseVal != LHS) { 10779 Res = DAG.getNode(ARMISD::CMOV, dl, VT, LHS, TrueVal, ARMcc, 10780 N->getOperand(3), Cmp); 10781 } else if (CC == ARMCC::EQ && TrueVal == RHS) { 10782 SDValue ARMcc; 10783 SDValue NewCmp = getARMCmp(LHS, RHS, ISD::SETNE, ARMcc, DAG, dl); 10784 Res = DAG.getNode(ARMISD::CMOV, dl, VT, LHS, FalseVal, ARMcc, 10785 N->getOperand(3), NewCmp); 10786 } 10787 10788 // (cmov F T ne CPSR (cmpz (cmov 0 1 CC CPSR Cmp) 0)) 10789 // -> (cmov F T CC CPSR Cmp) 10790 if (CC == ARMCC::NE && LHS.getOpcode() == ARMISD::CMOV && LHS->hasOneUse()) { 10791 auto *LHS0C = dyn_cast<ConstantSDNode>(LHS->getOperand(0)); 10792 auto *LHS1C = dyn_cast<ConstantSDNode>(LHS->getOperand(1)); 10793 auto *RHSC = dyn_cast<ConstantSDNode>(RHS); 10794 if ((LHS0C && LHS0C->getZExtValue() == 0) && 10795 (LHS1C && LHS1C->getZExtValue() == 1) && 10796 (RHSC && RHSC->getZExtValue() == 0)) { 10797 return DAG.getNode(ARMISD::CMOV, dl, VT, FalseVal, TrueVal, 10798 LHS->getOperand(2), LHS->getOperand(3), 10799 LHS->getOperand(4)); 10800 } 10801 } 10802 10803 if (Res.getNode()) { 10804 APInt KnownZero, KnownOne; 10805 DAG.computeKnownBits(SDValue(N,0), KnownZero, KnownOne); 10806 // Capture demanded bits information that would be otherwise lost. 10807 if (KnownZero == 0xfffffffe) 10808 Res = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Res, 10809 DAG.getValueType(MVT::i1)); 10810 else if (KnownZero == 0xffffff00) 10811 Res = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Res, 10812 DAG.getValueType(MVT::i8)); 10813 else if (KnownZero == 0xffff0000) 10814 Res = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Res, 10815 DAG.getValueType(MVT::i16)); 10816 } 10817 10818 return Res; 10819 } 10820 10821 SDValue ARMTargetLowering::PerformDAGCombine(SDNode *N, 10822 DAGCombinerInfo &DCI) const { 10823 switch (N->getOpcode()) { 10824 default: break; 10825 case ISD::ADDC: return PerformADDCCombine(N, DCI, Subtarget); 10826 case ISD::ADD: return PerformADDCombine(N, DCI, Subtarget); 10827 case ISD::SUB: return PerformSUBCombine(N, DCI); 10828 case ISD::MUL: return PerformMULCombine(N, DCI, Subtarget); 10829 case ISD::OR: return PerformORCombine(N, DCI, Subtarget); 10830 case ISD::XOR: return PerformXORCombine(N, DCI, Subtarget); 10831 case ISD::AND: return PerformANDCombine(N, DCI, Subtarget); 10832 case ARMISD::BFI: return PerformBFICombine(N, DCI); 10833 case ARMISD::VMOVRRD: return PerformVMOVRRDCombine(N, DCI, Subtarget); 10834 case ARMISD::VMOVDRR: return PerformVMOVDRRCombine(N, DCI.DAG); 10835 case ISD::STORE: return PerformSTORECombine(N, DCI); 10836 case ISD::BUILD_VECTOR: return PerformBUILD_VECTORCombine(N, DCI, Subtarget); 10837 case ISD::INSERT_VECTOR_ELT: return PerformInsertEltCombine(N, DCI); 10838 case ISD::VECTOR_SHUFFLE: return PerformVECTOR_SHUFFLECombine(N, DCI.DAG); 10839 case ARMISD::VDUPLANE: return PerformVDUPLANECombine(N, DCI); 10840 case ISD::FP_TO_SINT: 10841 case ISD::FP_TO_UINT: 10842 return PerformVCVTCombine(N, DCI.DAG, Subtarget); 10843 case ISD::FDIV: 10844 return PerformVDIVCombine(N, DCI.DAG, Subtarget); 10845 case ISD::INTRINSIC_WO_CHAIN: return PerformIntrinsicCombine(N, DCI.DAG); 10846 case ISD::SHL: 10847 case ISD::SRA: 10848 case ISD::SRL: return PerformShiftCombine(N, DCI.DAG, Subtarget); 10849 case ISD::SIGN_EXTEND: 10850 case ISD::ZERO_EXTEND: 10851 case ISD::ANY_EXTEND: return PerformExtendCombine(N, DCI.DAG, Subtarget); 10852 case ARMISD::CMOV: return PerformCMOVCombine(N, DCI.DAG); 10853 case ARMISD::BRCOND: return PerformBRCONDCombine(N, DCI.DAG); 10854 case ISD::LOAD: return PerformLOADCombine(N, DCI); 10855 case ARMISD::VLD2DUP: 10856 case ARMISD::VLD3DUP: 10857 case ARMISD::VLD4DUP: 10858 return PerformVLDCombine(N, DCI); 10859 case ARMISD::BUILD_VECTOR: 10860 return PerformARMBUILD_VECTORCombine(N, DCI); 10861 case ISD::INTRINSIC_VOID: 10862 case ISD::INTRINSIC_W_CHAIN: 10863 switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) { 10864 case Intrinsic::arm_neon_vld1: 10865 case Intrinsic::arm_neon_vld2: 10866 case Intrinsic::arm_neon_vld3: 10867 case Intrinsic::arm_neon_vld4: 10868 case Intrinsic::arm_neon_vld2lane: 10869 case Intrinsic::arm_neon_vld3lane: 10870 case Intrinsic::arm_neon_vld4lane: 10871 case Intrinsic::arm_neon_vst1: 10872 case Intrinsic::arm_neon_vst2: 10873 case Intrinsic::arm_neon_vst3: 10874 case Intrinsic::arm_neon_vst4: 10875 case Intrinsic::arm_neon_vst2lane: 10876 case Intrinsic::arm_neon_vst3lane: 10877 case Intrinsic::arm_neon_vst4lane: 10878 return PerformVLDCombine(N, DCI); 10879 default: break; 10880 } 10881 break; 10882 } 10883 return SDValue(); 10884 } 10885 10886 bool ARMTargetLowering::isDesirableToTransformToIntegerOp(unsigned Opc, 10887 EVT VT) const { 10888 return (VT == MVT::f32) && (Opc == ISD::LOAD || Opc == ISD::STORE); 10889 } 10890 10891 bool ARMTargetLowering::allowsMisalignedMemoryAccesses(EVT VT, 10892 unsigned, 10893 unsigned, 10894 bool *Fast) const { 10895 // The AllowsUnaliged flag models the SCTLR.A setting in ARM cpus 10896 bool AllowsUnaligned = Subtarget->allowsUnalignedMem(); 10897 10898 switch (VT.getSimpleVT().SimpleTy) { 10899 default: 10900 return false; 10901 case MVT::i8: 10902 case MVT::i16: 10903 case MVT::i32: { 10904 // Unaligned access can use (for example) LRDB, LRDH, LDR 10905 if (AllowsUnaligned) { 10906 if (Fast) 10907 *Fast = Subtarget->hasV7Ops(); 10908 return true; 10909 } 10910 return false; 10911 } 10912 case MVT::f64: 10913 case MVT::v2f64: { 10914 // For any little-endian targets with neon, we can support unaligned ld/st 10915 // of D and Q (e.g. {D0,D1}) registers by using vld1.i8/vst1.i8. 10916 // A big-endian target may also explicitly support unaligned accesses 10917 if (Subtarget->hasNEON() && (AllowsUnaligned || Subtarget->isLittle())) { 10918 if (Fast) 10919 *Fast = true; 10920 return true; 10921 } 10922 return false; 10923 } 10924 } 10925 } 10926 10927 static bool memOpAlign(unsigned DstAlign, unsigned SrcAlign, 10928 unsigned AlignCheck) { 10929 return ((SrcAlign == 0 || SrcAlign % AlignCheck == 0) && 10930 (DstAlign == 0 || DstAlign % AlignCheck == 0)); 10931 } 10932 10933 EVT ARMTargetLowering::getOptimalMemOpType(uint64_t Size, 10934 unsigned DstAlign, unsigned SrcAlign, 10935 bool IsMemset, bool ZeroMemset, 10936 bool MemcpyStrSrc, 10937 MachineFunction &MF) const { 10938 const Function *F = MF.getFunction(); 10939 10940 // See if we can use NEON instructions for this... 10941 if ((!IsMemset || ZeroMemset) && Subtarget->hasNEON() && 10942 !F->hasFnAttribute(Attribute::NoImplicitFloat)) { 10943 bool Fast; 10944 if (Size >= 16 && 10945 (memOpAlign(SrcAlign, DstAlign, 16) || 10946 (allowsMisalignedMemoryAccesses(MVT::v2f64, 0, 1, &Fast) && Fast))) { 10947 return MVT::v2f64; 10948 } else if (Size >= 8 && 10949 (memOpAlign(SrcAlign, DstAlign, 8) || 10950 (allowsMisalignedMemoryAccesses(MVT::f64, 0, 1, &Fast) && 10951 Fast))) { 10952 return MVT::f64; 10953 } 10954 } 10955 10956 // Lowering to i32/i16 if the size permits. 10957 if (Size >= 4) 10958 return MVT::i32; 10959 else if (Size >= 2) 10960 return MVT::i16; 10961 10962 // Let the target-independent logic figure it out. 10963 return MVT::Other; 10964 } 10965 10966 bool ARMTargetLowering::isZExtFree(SDValue Val, EVT VT2) const { 10967 if (Val.getOpcode() != ISD::LOAD) 10968 return false; 10969 10970 EVT VT1 = Val.getValueType(); 10971 if (!VT1.isSimple() || !VT1.isInteger() || 10972 !VT2.isSimple() || !VT2.isInteger()) 10973 return false; 10974 10975 switch (VT1.getSimpleVT().SimpleTy) { 10976 default: break; 10977 case MVT::i1: 10978 case MVT::i8: 10979 case MVT::i16: 10980 // 8-bit and 16-bit loads implicitly zero-extend to 32-bits. 10981 return true; 10982 } 10983 10984 return false; 10985 } 10986 10987 bool ARMTargetLowering::isVectorLoadExtDesirable(SDValue ExtVal) const { 10988 EVT VT = ExtVal.getValueType(); 10989 10990 if (!isTypeLegal(VT)) 10991 return false; 10992 10993 // Don't create a loadext if we can fold the extension into a wide/long 10994 // instruction. 10995 // If there's more than one user instruction, the loadext is desirable no 10996 // matter what. There can be two uses by the same instruction. 10997 if (ExtVal->use_empty() || 10998 !ExtVal->use_begin()->isOnlyUserOf(ExtVal.getNode())) 10999 return true; 11000 11001 SDNode *U = *ExtVal->use_begin(); 11002 if ((U->getOpcode() == ISD::ADD || U->getOpcode() == ISD::SUB || 11003 U->getOpcode() == ISD::SHL || U->getOpcode() == ARMISD::VSHL)) 11004 return false; 11005 11006 return true; 11007 } 11008 11009 bool ARMTargetLowering::allowTruncateForTailCall(Type *Ty1, Type *Ty2) const { 11010 if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy()) 11011 return false; 11012 11013 if (!isTypeLegal(EVT::getEVT(Ty1))) 11014 return false; 11015 11016 assert(Ty1->getPrimitiveSizeInBits() <= 64 && "i128 is probably not a noop"); 11017 11018 // Assuming the caller doesn't have a zeroext or signext return parameter, 11019 // truncation all the way down to i1 is valid. 11020 return true; 11021 } 11022 11023 11024 static bool isLegalT1AddressImmediate(int64_t V, EVT VT) { 11025 if (V < 0) 11026 return false; 11027 11028 unsigned Scale = 1; 11029 switch (VT.getSimpleVT().SimpleTy) { 11030 default: return false; 11031 case MVT::i1: 11032 case MVT::i8: 11033 // Scale == 1; 11034 break; 11035 case MVT::i16: 11036 // Scale == 2; 11037 Scale = 2; 11038 break; 11039 case MVT::i32: 11040 // Scale == 4; 11041 Scale = 4; 11042 break; 11043 } 11044 11045 if ((V & (Scale - 1)) != 0) 11046 return false; 11047 V /= Scale; 11048 return V == (V & ((1LL << 5) - 1)); 11049 } 11050 11051 static bool isLegalT2AddressImmediate(int64_t V, EVT VT, 11052 const ARMSubtarget *Subtarget) { 11053 bool isNeg = false; 11054 if (V < 0) { 11055 isNeg = true; 11056 V = - V; 11057 } 11058 11059 switch (VT.getSimpleVT().SimpleTy) { 11060 default: return false; 11061 case MVT::i1: 11062 case MVT::i8: 11063 case MVT::i16: 11064 case MVT::i32: 11065 // + imm12 or - imm8 11066 if (isNeg) 11067 return V == (V & ((1LL << 8) - 1)); 11068 return V == (V & ((1LL << 12) - 1)); 11069 case MVT::f32: 11070 case MVT::f64: 11071 // Same as ARM mode. FIXME: NEON? 11072 if (!Subtarget->hasVFP2()) 11073 return false; 11074 if ((V & 3) != 0) 11075 return false; 11076 V >>= 2; 11077 return V == (V & ((1LL << 8) - 1)); 11078 } 11079 } 11080 11081 /// isLegalAddressImmediate - Return true if the integer value can be used 11082 /// as the offset of the target addressing mode for load / store of the 11083 /// given type. 11084 static bool isLegalAddressImmediate(int64_t V, EVT VT, 11085 const ARMSubtarget *Subtarget) { 11086 if (V == 0) 11087 return true; 11088 11089 if (!VT.isSimple()) 11090 return false; 11091 11092 if (Subtarget->isThumb1Only()) 11093 return isLegalT1AddressImmediate(V, VT); 11094 else if (Subtarget->isThumb2()) 11095 return isLegalT2AddressImmediate(V, VT, Subtarget); 11096 11097 // ARM mode. 11098 if (V < 0) 11099 V = - V; 11100 switch (VT.getSimpleVT().SimpleTy) { 11101 default: return false; 11102 case MVT::i1: 11103 case MVT::i8: 11104 case MVT::i32: 11105 // +- imm12 11106 return V == (V & ((1LL << 12) - 1)); 11107 case MVT::i16: 11108 // +- imm8 11109 return V == (V & ((1LL << 8) - 1)); 11110 case MVT::f32: 11111 case MVT::f64: 11112 if (!Subtarget->hasVFP2()) // FIXME: NEON? 11113 return false; 11114 if ((V & 3) != 0) 11115 return false; 11116 V >>= 2; 11117 return V == (V & ((1LL << 8) - 1)); 11118 } 11119 } 11120 11121 bool ARMTargetLowering::isLegalT2ScaledAddressingMode(const AddrMode &AM, 11122 EVT VT) const { 11123 int Scale = AM.Scale; 11124 if (Scale < 0) 11125 return false; 11126 11127 switch (VT.getSimpleVT().SimpleTy) { 11128 default: return false; 11129 case MVT::i1: 11130 case MVT::i8: 11131 case MVT::i16: 11132 case MVT::i32: 11133 if (Scale == 1) 11134 return true; 11135 // r + r << imm 11136 Scale = Scale & ~1; 11137 return Scale == 2 || Scale == 4 || Scale == 8; 11138 case MVT::i64: 11139 // r + r 11140 if (((unsigned)AM.HasBaseReg + Scale) <= 2) 11141 return true; 11142 return false; 11143 case MVT::isVoid: 11144 // Note, we allow "void" uses (basically, uses that aren't loads or 11145 // stores), because arm allows folding a scale into many arithmetic 11146 // operations. This should be made more precise and revisited later. 11147 11148 // Allow r << imm, but the imm has to be a multiple of two. 11149 if (Scale & 1) return false; 11150 return isPowerOf2_32(Scale); 11151 } 11152 } 11153 11154 /// isLegalAddressingMode - Return true if the addressing mode represented 11155 /// by AM is legal for this target, for a load/store of the specified type. 11156 bool ARMTargetLowering::isLegalAddressingMode(const DataLayout &DL, 11157 const AddrMode &AM, Type *Ty, 11158 unsigned AS) const { 11159 EVT VT = getValueType(DL, Ty, true); 11160 if (!isLegalAddressImmediate(AM.BaseOffs, VT, Subtarget)) 11161 return false; 11162 11163 // Can never fold addr of global into load/store. 11164 if (AM.BaseGV) 11165 return false; 11166 11167 switch (AM.Scale) { 11168 case 0: // no scale reg, must be "r+i" or "r", or "i". 11169 break; 11170 case 1: 11171 if (Subtarget->isThumb1Only()) 11172 return false; 11173 // FALL THROUGH. 11174 default: 11175 // ARM doesn't support any R+R*scale+imm addr modes. 11176 if (AM.BaseOffs) 11177 return false; 11178 11179 if (!VT.isSimple()) 11180 return false; 11181 11182 if (Subtarget->isThumb2()) 11183 return isLegalT2ScaledAddressingMode(AM, VT); 11184 11185 int Scale = AM.Scale; 11186 switch (VT.getSimpleVT().SimpleTy) { 11187 default: return false; 11188 case MVT::i1: 11189 case MVT::i8: 11190 case MVT::i32: 11191 if (Scale < 0) Scale = -Scale; 11192 if (Scale == 1) 11193 return true; 11194 // r + r << imm 11195 return isPowerOf2_32(Scale & ~1); 11196 case MVT::i16: 11197 case MVT::i64: 11198 // r + r 11199 if (((unsigned)AM.HasBaseReg + Scale) <= 2) 11200 return true; 11201 return false; 11202 11203 case MVT::isVoid: 11204 // Note, we allow "void" uses (basically, uses that aren't loads or 11205 // stores), because arm allows folding a scale into many arithmetic 11206 // operations. This should be made more precise and revisited later. 11207 11208 // Allow r << imm, but the imm has to be a multiple of two. 11209 if (Scale & 1) return false; 11210 return isPowerOf2_32(Scale); 11211 } 11212 } 11213 return true; 11214 } 11215 11216 /// isLegalICmpImmediate - Return true if the specified immediate is legal 11217 /// icmp immediate, that is the target has icmp instructions which can compare 11218 /// a register against the immediate without having to materialize the 11219 /// immediate into a register. 11220 bool ARMTargetLowering::isLegalICmpImmediate(int64_t Imm) const { 11221 // Thumb2 and ARM modes can use cmn for negative immediates. 11222 if (!Subtarget->isThumb()) 11223 return ARM_AM::getSOImmVal(std::abs(Imm)) != -1; 11224 if (Subtarget->isThumb2()) 11225 return ARM_AM::getT2SOImmVal(std::abs(Imm)) != -1; 11226 // Thumb1 doesn't have cmn, and only 8-bit immediates. 11227 return Imm >= 0 && Imm <= 255; 11228 } 11229 11230 /// isLegalAddImmediate - Return true if the specified immediate is a legal add 11231 /// *or sub* immediate, that is the target has add or sub instructions which can 11232 /// add a register with the immediate without having to materialize the 11233 /// immediate into a register. 11234 bool ARMTargetLowering::isLegalAddImmediate(int64_t Imm) const { 11235 // Same encoding for add/sub, just flip the sign. 11236 int64_t AbsImm = std::abs(Imm); 11237 if (!Subtarget->isThumb()) 11238 return ARM_AM::getSOImmVal(AbsImm) != -1; 11239 if (Subtarget->isThumb2()) 11240 return ARM_AM::getT2SOImmVal(AbsImm) != -1; 11241 // Thumb1 only has 8-bit unsigned immediate. 11242 return AbsImm >= 0 && AbsImm <= 255; 11243 } 11244 11245 static bool getARMIndexedAddressParts(SDNode *Ptr, EVT VT, 11246 bool isSEXTLoad, SDValue &Base, 11247 SDValue &Offset, bool &isInc, 11248 SelectionDAG &DAG) { 11249 if (Ptr->getOpcode() != ISD::ADD && Ptr->getOpcode() != ISD::SUB) 11250 return false; 11251 11252 if (VT == MVT::i16 || ((VT == MVT::i8 || VT == MVT::i1) && isSEXTLoad)) { 11253 // AddressingMode 3 11254 Base = Ptr->getOperand(0); 11255 if (ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(Ptr->getOperand(1))) { 11256 int RHSC = (int)RHS->getZExtValue(); 11257 if (RHSC < 0 && RHSC > -256) { 11258 assert(Ptr->getOpcode() == ISD::ADD); 11259 isInc = false; 11260 Offset = DAG.getConstant(-RHSC, SDLoc(Ptr), RHS->getValueType(0)); 11261 return true; 11262 } 11263 } 11264 isInc = (Ptr->getOpcode() == ISD::ADD); 11265 Offset = Ptr->getOperand(1); 11266 return true; 11267 } else if (VT == MVT::i32 || VT == MVT::i8 || VT == MVT::i1) { 11268 // AddressingMode 2 11269 if (ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(Ptr->getOperand(1))) { 11270 int RHSC = (int)RHS->getZExtValue(); 11271 if (RHSC < 0 && RHSC > -0x1000) { 11272 assert(Ptr->getOpcode() == ISD::ADD); 11273 isInc = false; 11274 Offset = DAG.getConstant(-RHSC, SDLoc(Ptr), RHS->getValueType(0)); 11275 Base = Ptr->getOperand(0); 11276 return true; 11277 } 11278 } 11279 11280 if (Ptr->getOpcode() == ISD::ADD) { 11281 isInc = true; 11282 ARM_AM::ShiftOpc ShOpcVal= 11283 ARM_AM::getShiftOpcForNode(Ptr->getOperand(0).getOpcode()); 11284 if (ShOpcVal != ARM_AM::no_shift) { 11285 Base = Ptr->getOperand(1); 11286 Offset = Ptr->getOperand(0); 11287 } else { 11288 Base = Ptr->getOperand(0); 11289 Offset = Ptr->getOperand(1); 11290 } 11291 return true; 11292 } 11293 11294 isInc = (Ptr->getOpcode() == ISD::ADD); 11295 Base = Ptr->getOperand(0); 11296 Offset = Ptr->getOperand(1); 11297 return true; 11298 } 11299 11300 // FIXME: Use VLDM / VSTM to emulate indexed FP load / store. 11301 return false; 11302 } 11303 11304 static bool getT2IndexedAddressParts(SDNode *Ptr, EVT VT, 11305 bool isSEXTLoad, SDValue &Base, 11306 SDValue &Offset, bool &isInc, 11307 SelectionDAG &DAG) { 11308 if (Ptr->getOpcode() != ISD::ADD && Ptr->getOpcode() != ISD::SUB) 11309 return false; 11310 11311 Base = Ptr->getOperand(0); 11312 if (ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(Ptr->getOperand(1))) { 11313 int RHSC = (int)RHS->getZExtValue(); 11314 if (RHSC < 0 && RHSC > -0x100) { // 8 bits. 11315 assert(Ptr->getOpcode() == ISD::ADD); 11316 isInc = false; 11317 Offset = DAG.getConstant(-RHSC, SDLoc(Ptr), RHS->getValueType(0)); 11318 return true; 11319 } else if (RHSC > 0 && RHSC < 0x100) { // 8 bit, no zero. 11320 isInc = Ptr->getOpcode() == ISD::ADD; 11321 Offset = DAG.getConstant(RHSC, SDLoc(Ptr), RHS->getValueType(0)); 11322 return true; 11323 } 11324 } 11325 11326 return false; 11327 } 11328 11329 /// getPreIndexedAddressParts - returns true by value, base pointer and 11330 /// offset pointer and addressing mode by reference if the node's address 11331 /// can be legally represented as pre-indexed load / store address. 11332 bool 11333 ARMTargetLowering::getPreIndexedAddressParts(SDNode *N, SDValue &Base, 11334 SDValue &Offset, 11335 ISD::MemIndexedMode &AM, 11336 SelectionDAG &DAG) const { 11337 if (Subtarget->isThumb1Only()) 11338 return false; 11339 11340 EVT VT; 11341 SDValue Ptr; 11342 bool isSEXTLoad = false; 11343 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) { 11344 Ptr = LD->getBasePtr(); 11345 VT = LD->getMemoryVT(); 11346 isSEXTLoad = LD->getExtensionType() == ISD::SEXTLOAD; 11347 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) { 11348 Ptr = ST->getBasePtr(); 11349 VT = ST->getMemoryVT(); 11350 } else 11351 return false; 11352 11353 bool isInc; 11354 bool isLegal = false; 11355 if (Subtarget->isThumb2()) 11356 isLegal = getT2IndexedAddressParts(Ptr.getNode(), VT, isSEXTLoad, Base, 11357 Offset, isInc, DAG); 11358 else 11359 isLegal = getARMIndexedAddressParts(Ptr.getNode(), VT, isSEXTLoad, Base, 11360 Offset, isInc, DAG); 11361 if (!isLegal) 11362 return false; 11363 11364 AM = isInc ? ISD::PRE_INC : ISD::PRE_DEC; 11365 return true; 11366 } 11367 11368 /// getPostIndexedAddressParts - returns true by value, base pointer and 11369 /// offset pointer and addressing mode by reference if this node can be 11370 /// combined with a load / store to form a post-indexed load / store. 11371 bool ARMTargetLowering::getPostIndexedAddressParts(SDNode *N, SDNode *Op, 11372 SDValue &Base, 11373 SDValue &Offset, 11374 ISD::MemIndexedMode &AM, 11375 SelectionDAG &DAG) const { 11376 if (Subtarget->isThumb1Only()) 11377 return false; 11378 11379 EVT VT; 11380 SDValue Ptr; 11381 bool isSEXTLoad = false; 11382 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) { 11383 VT = LD->getMemoryVT(); 11384 Ptr = LD->getBasePtr(); 11385 isSEXTLoad = LD->getExtensionType() == ISD::SEXTLOAD; 11386 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) { 11387 VT = ST->getMemoryVT(); 11388 Ptr = ST->getBasePtr(); 11389 } else 11390 return false; 11391 11392 bool isInc; 11393 bool isLegal = false; 11394 if (Subtarget->isThumb2()) 11395 isLegal = getT2IndexedAddressParts(Op, VT, isSEXTLoad, Base, Offset, 11396 isInc, DAG); 11397 else 11398 isLegal = getARMIndexedAddressParts(Op, VT, isSEXTLoad, Base, Offset, 11399 isInc, DAG); 11400 if (!isLegal) 11401 return false; 11402 11403 if (Ptr != Base) { 11404 // Swap base ptr and offset to catch more post-index load / store when 11405 // it's legal. In Thumb2 mode, offset must be an immediate. 11406 if (Ptr == Offset && Op->getOpcode() == ISD::ADD && 11407 !Subtarget->isThumb2()) 11408 std::swap(Base, Offset); 11409 11410 // Post-indexed load / store update the base pointer. 11411 if (Ptr != Base) 11412 return false; 11413 } 11414 11415 AM = isInc ? ISD::POST_INC : ISD::POST_DEC; 11416 return true; 11417 } 11418 11419 void ARMTargetLowering::computeKnownBitsForTargetNode(const SDValue Op, 11420 APInt &KnownZero, 11421 APInt &KnownOne, 11422 const SelectionDAG &DAG, 11423 unsigned Depth) const { 11424 unsigned BitWidth = KnownOne.getBitWidth(); 11425 KnownZero = KnownOne = APInt(BitWidth, 0); 11426 switch (Op.getOpcode()) { 11427 default: break; 11428 case ARMISD::ADDC: 11429 case ARMISD::ADDE: 11430 case ARMISD::SUBC: 11431 case ARMISD::SUBE: 11432 // These nodes' second result is a boolean 11433 if (Op.getResNo() == 0) 11434 break; 11435 KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - 1); 11436 break; 11437 case ARMISD::CMOV: { 11438 // Bits are known zero/one if known on the LHS and RHS. 11439 DAG.computeKnownBits(Op.getOperand(0), KnownZero, KnownOne, Depth+1); 11440 if (KnownZero == 0 && KnownOne == 0) return; 11441 11442 APInt KnownZeroRHS, KnownOneRHS; 11443 DAG.computeKnownBits(Op.getOperand(1), KnownZeroRHS, KnownOneRHS, Depth+1); 11444 KnownZero &= KnownZeroRHS; 11445 KnownOne &= KnownOneRHS; 11446 return; 11447 } 11448 case ISD::INTRINSIC_W_CHAIN: { 11449 ConstantSDNode *CN = cast<ConstantSDNode>(Op->getOperand(1)); 11450 Intrinsic::ID IntID = static_cast<Intrinsic::ID>(CN->getZExtValue()); 11451 switch (IntID) { 11452 default: return; 11453 case Intrinsic::arm_ldaex: 11454 case Intrinsic::arm_ldrex: { 11455 EVT VT = cast<MemIntrinsicSDNode>(Op)->getMemoryVT(); 11456 unsigned MemBits = VT.getScalarType().getSizeInBits(); 11457 KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - MemBits); 11458 return; 11459 } 11460 } 11461 } 11462 } 11463 } 11464 11465 //===----------------------------------------------------------------------===// 11466 // ARM Inline Assembly Support 11467 //===----------------------------------------------------------------------===// 11468 11469 bool ARMTargetLowering::ExpandInlineAsm(CallInst *CI) const { 11470 // Looking for "rev" which is V6+. 11471 if (!Subtarget->hasV6Ops()) 11472 return false; 11473 11474 InlineAsm *IA = cast<InlineAsm>(CI->getCalledValue()); 11475 std::string AsmStr = IA->getAsmString(); 11476 SmallVector<StringRef, 4> AsmPieces; 11477 SplitString(AsmStr, AsmPieces, ";\n"); 11478 11479 switch (AsmPieces.size()) { 11480 default: return false; 11481 case 1: 11482 AsmStr = AsmPieces[0]; 11483 AsmPieces.clear(); 11484 SplitString(AsmStr, AsmPieces, " \t,"); 11485 11486 // rev $0, $1 11487 if (AsmPieces.size() == 3 && 11488 AsmPieces[0] == "rev" && AsmPieces[1] == "$0" && AsmPieces[2] == "$1" && 11489 IA->getConstraintString().compare(0, 4, "=l,l") == 0) { 11490 IntegerType *Ty = dyn_cast<IntegerType>(CI->getType()); 11491 if (Ty && Ty->getBitWidth() == 32) 11492 return IntrinsicLowering::LowerToByteSwap(CI); 11493 } 11494 break; 11495 } 11496 11497 return false; 11498 } 11499 11500 const char *ARMTargetLowering::LowerXConstraint(EVT ConstraintVT) const { 11501 // At this point, we have to lower this constraint to something else, so we 11502 // lower it to an "r" or "w". However, by doing this we will force the result 11503 // to be in register, while the X constraint is much more permissive. 11504 // 11505 // Although we are correct (we are free to emit anything, without 11506 // constraints), we might break use cases that would expect us to be more 11507 // efficient and emit something else. 11508 if (!Subtarget->hasVFP2()) 11509 return "r"; 11510 if (ConstraintVT.isFloatingPoint()) 11511 return "w"; 11512 if (ConstraintVT.isVector() && Subtarget->hasNEON() && 11513 (ConstraintVT.getSizeInBits() == 64 || 11514 ConstraintVT.getSizeInBits() == 128)) 11515 return "w"; 11516 11517 return "r"; 11518 } 11519 11520 /// getConstraintType - Given a constraint letter, return the type of 11521 /// constraint it is for this target. 11522 ARMTargetLowering::ConstraintType 11523 ARMTargetLowering::getConstraintType(StringRef Constraint) const { 11524 if (Constraint.size() == 1) { 11525 switch (Constraint[0]) { 11526 default: break; 11527 case 'l': return C_RegisterClass; 11528 case 'w': return C_RegisterClass; 11529 case 'h': return C_RegisterClass; 11530 case 'x': return C_RegisterClass; 11531 case 't': return C_RegisterClass; 11532 case 'j': return C_Other; // Constant for movw. 11533 // An address with a single base register. Due to the way we 11534 // currently handle addresses it is the same as an 'r' memory constraint. 11535 case 'Q': return C_Memory; 11536 } 11537 } else if (Constraint.size() == 2) { 11538 switch (Constraint[0]) { 11539 default: break; 11540 // All 'U+' constraints are addresses. 11541 case 'U': return C_Memory; 11542 } 11543 } 11544 return TargetLowering::getConstraintType(Constraint); 11545 } 11546 11547 /// Examine constraint type and operand type and determine a weight value. 11548 /// This object must already have been set up with the operand type 11549 /// and the current alternative constraint selected. 11550 TargetLowering::ConstraintWeight 11551 ARMTargetLowering::getSingleConstraintMatchWeight( 11552 AsmOperandInfo &info, const char *constraint) const { 11553 ConstraintWeight weight = CW_Invalid; 11554 Value *CallOperandVal = info.CallOperandVal; 11555 // If we don't have a value, we can't do a match, 11556 // but allow it at the lowest weight. 11557 if (!CallOperandVal) 11558 return CW_Default; 11559 Type *type = CallOperandVal->getType(); 11560 // Look at the constraint type. 11561 switch (*constraint) { 11562 default: 11563 weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint); 11564 break; 11565 case 'l': 11566 if (type->isIntegerTy()) { 11567 if (Subtarget->isThumb()) 11568 weight = CW_SpecificReg; 11569 else 11570 weight = CW_Register; 11571 } 11572 break; 11573 case 'w': 11574 if (type->isFloatingPointTy()) 11575 weight = CW_Register; 11576 break; 11577 } 11578 return weight; 11579 } 11580 11581 typedef std::pair<unsigned, const TargetRegisterClass*> RCPair; 11582 RCPair ARMTargetLowering::getRegForInlineAsmConstraint( 11583 const TargetRegisterInfo *TRI, StringRef Constraint, MVT VT) const { 11584 if (Constraint.size() == 1) { 11585 // GCC ARM Constraint Letters 11586 switch (Constraint[0]) { 11587 case 'l': // Low regs or general regs. 11588 if (Subtarget->isThumb()) 11589 return RCPair(0U, &ARM::tGPRRegClass); 11590 return RCPair(0U, &ARM::GPRRegClass); 11591 case 'h': // High regs or no regs. 11592 if (Subtarget->isThumb()) 11593 return RCPair(0U, &ARM::hGPRRegClass); 11594 break; 11595 case 'r': 11596 if (Subtarget->isThumb1Only()) 11597 return RCPair(0U, &ARM::tGPRRegClass); 11598 return RCPair(0U, &ARM::GPRRegClass); 11599 case 'w': 11600 if (VT == MVT::Other) 11601 break; 11602 if (VT == MVT::f32) 11603 return RCPair(0U, &ARM::SPRRegClass); 11604 if (VT.getSizeInBits() == 64) 11605 return RCPair(0U, &ARM::DPRRegClass); 11606 if (VT.getSizeInBits() == 128) 11607 return RCPair(0U, &ARM::QPRRegClass); 11608 break; 11609 case 'x': 11610 if (VT == MVT::Other) 11611 break; 11612 if (VT == MVT::f32) 11613 return RCPair(0U, &ARM::SPR_8RegClass); 11614 if (VT.getSizeInBits() == 64) 11615 return RCPair(0U, &ARM::DPR_8RegClass); 11616 if (VT.getSizeInBits() == 128) 11617 return RCPair(0U, &ARM::QPR_8RegClass); 11618 break; 11619 case 't': 11620 if (VT == MVT::f32) 11621 return RCPair(0U, &ARM::SPRRegClass); 11622 break; 11623 } 11624 } 11625 if (StringRef("{cc}").equals_lower(Constraint)) 11626 return std::make_pair(unsigned(ARM::CPSR), &ARM::CCRRegClass); 11627 11628 return TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT); 11629 } 11630 11631 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops 11632 /// vector. If it is invalid, don't add anything to Ops. 11633 void ARMTargetLowering::LowerAsmOperandForConstraint(SDValue Op, 11634 std::string &Constraint, 11635 std::vector<SDValue>&Ops, 11636 SelectionDAG &DAG) const { 11637 SDValue Result; 11638 11639 // Currently only support length 1 constraints. 11640 if (Constraint.length() != 1) return; 11641 11642 char ConstraintLetter = Constraint[0]; 11643 switch (ConstraintLetter) { 11644 default: break; 11645 case 'j': 11646 case 'I': case 'J': case 'K': case 'L': 11647 case 'M': case 'N': case 'O': 11648 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op); 11649 if (!C) 11650 return; 11651 11652 int64_t CVal64 = C->getSExtValue(); 11653 int CVal = (int) CVal64; 11654 // None of these constraints allow values larger than 32 bits. Check 11655 // that the value fits in an int. 11656 if (CVal != CVal64) 11657 return; 11658 11659 switch (ConstraintLetter) { 11660 case 'j': 11661 // Constant suitable for movw, must be between 0 and 11662 // 65535. 11663 if (Subtarget->hasV6T2Ops()) 11664 if (CVal >= 0 && CVal <= 65535) 11665 break; 11666 return; 11667 case 'I': 11668 if (Subtarget->isThumb1Only()) { 11669 // This must be a constant between 0 and 255, for ADD 11670 // immediates. 11671 if (CVal >= 0 && CVal <= 255) 11672 break; 11673 } else if (Subtarget->isThumb2()) { 11674 // A constant that can be used as an immediate value in a 11675 // data-processing instruction. 11676 if (ARM_AM::getT2SOImmVal(CVal) != -1) 11677 break; 11678 } else { 11679 // A constant that can be used as an immediate value in a 11680 // data-processing instruction. 11681 if (ARM_AM::getSOImmVal(CVal) != -1) 11682 break; 11683 } 11684 return; 11685 11686 case 'J': 11687 if (Subtarget->isThumb1Only()) { 11688 // This must be a constant between -255 and -1, for negated ADD 11689 // immediates. This can be used in GCC with an "n" modifier that 11690 // prints the negated value, for use with SUB instructions. It is 11691 // not useful otherwise but is implemented for compatibility. 11692 if (CVal >= -255 && CVal <= -1) 11693 break; 11694 } else { 11695 // This must be a constant between -4095 and 4095. It is not clear 11696 // what this constraint is intended for. Implemented for 11697 // compatibility with GCC. 11698 if (CVal >= -4095 && CVal <= 4095) 11699 break; 11700 } 11701 return; 11702 11703 case 'K': 11704 if (Subtarget->isThumb1Only()) { 11705 // A 32-bit value where only one byte has a nonzero value. Exclude 11706 // zero to match GCC. This constraint is used by GCC internally for 11707 // constants that can be loaded with a move/shift combination. 11708 // It is not useful otherwise but is implemented for compatibility. 11709 if (CVal != 0 && ARM_AM::isThumbImmShiftedVal(CVal)) 11710 break; 11711 } else if (Subtarget->isThumb2()) { 11712 // A constant whose bitwise inverse can be used as an immediate 11713 // value in a data-processing instruction. This can be used in GCC 11714 // with a "B" modifier that prints the inverted value, for use with 11715 // BIC and MVN instructions. It is not useful otherwise but is 11716 // implemented for compatibility. 11717 if (ARM_AM::getT2SOImmVal(~CVal) != -1) 11718 break; 11719 } else { 11720 // A constant whose bitwise inverse can be used as an immediate 11721 // value in a data-processing instruction. This can be used in GCC 11722 // with a "B" modifier that prints the inverted value, for use with 11723 // BIC and MVN instructions. It is not useful otherwise but is 11724 // implemented for compatibility. 11725 if (ARM_AM::getSOImmVal(~CVal) != -1) 11726 break; 11727 } 11728 return; 11729 11730 case 'L': 11731 if (Subtarget->isThumb1Only()) { 11732 // This must be a constant between -7 and 7, 11733 // for 3-operand ADD/SUB immediate instructions. 11734 if (CVal >= -7 && CVal < 7) 11735 break; 11736 } else if (Subtarget->isThumb2()) { 11737 // A constant whose negation can be used as an immediate value in a 11738 // data-processing instruction. This can be used in GCC with an "n" 11739 // modifier that prints the negated value, for use with SUB 11740 // instructions. It is not useful otherwise but is implemented for 11741 // compatibility. 11742 if (ARM_AM::getT2SOImmVal(-CVal) != -1) 11743 break; 11744 } else { 11745 // A constant whose negation can be used as an immediate value in a 11746 // data-processing instruction. This can be used in GCC with an "n" 11747 // modifier that prints the negated value, for use with SUB 11748 // instructions. It is not useful otherwise but is implemented for 11749 // compatibility. 11750 if (ARM_AM::getSOImmVal(-CVal) != -1) 11751 break; 11752 } 11753 return; 11754 11755 case 'M': 11756 if (Subtarget->isThumb1Only()) { 11757 // This must be a multiple of 4 between 0 and 1020, for 11758 // ADD sp + immediate. 11759 if ((CVal >= 0 && CVal <= 1020) && ((CVal & 3) == 0)) 11760 break; 11761 } else { 11762 // A power of two or a constant between 0 and 32. This is used in 11763 // GCC for the shift amount on shifted register operands, but it is 11764 // useful in general for any shift amounts. 11765 if ((CVal >= 0 && CVal <= 32) || ((CVal & (CVal - 1)) == 0)) 11766 break; 11767 } 11768 return; 11769 11770 case 'N': 11771 if (Subtarget->isThumb()) { // FIXME thumb2 11772 // This must be a constant between 0 and 31, for shift amounts. 11773 if (CVal >= 0 && CVal <= 31) 11774 break; 11775 } 11776 return; 11777 11778 case 'O': 11779 if (Subtarget->isThumb()) { // FIXME thumb2 11780 // This must be a multiple of 4 between -508 and 508, for 11781 // ADD/SUB sp = sp + immediate. 11782 if ((CVal >= -508 && CVal <= 508) && ((CVal & 3) == 0)) 11783 break; 11784 } 11785 return; 11786 } 11787 Result = DAG.getTargetConstant(CVal, SDLoc(Op), Op.getValueType()); 11788 break; 11789 } 11790 11791 if (Result.getNode()) { 11792 Ops.push_back(Result); 11793 return; 11794 } 11795 return TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG); 11796 } 11797 11798 static RTLIB::Libcall getDivRemLibcall( 11799 const SDNode *N, MVT::SimpleValueType SVT) { 11800 assert((N->getOpcode() == ISD::SDIVREM || N->getOpcode() == ISD::UDIVREM || 11801 N->getOpcode() == ISD::SREM || N->getOpcode() == ISD::UREM) && 11802 "Unhandled Opcode in getDivRemLibcall"); 11803 bool isSigned = N->getOpcode() == ISD::SDIVREM || 11804 N->getOpcode() == ISD::SREM; 11805 RTLIB::Libcall LC; 11806 switch (SVT) { 11807 default: llvm_unreachable("Unexpected request for libcall!"); 11808 case MVT::i8: LC = isSigned ? RTLIB::SDIVREM_I8 : RTLIB::UDIVREM_I8; break; 11809 case MVT::i16: LC = isSigned ? RTLIB::SDIVREM_I16 : RTLIB::UDIVREM_I16; break; 11810 case MVT::i32: LC = isSigned ? RTLIB::SDIVREM_I32 : RTLIB::UDIVREM_I32; break; 11811 case MVT::i64: LC = isSigned ? RTLIB::SDIVREM_I64 : RTLIB::UDIVREM_I64; break; 11812 } 11813 return LC; 11814 } 11815 11816 static TargetLowering::ArgListTy getDivRemArgList( 11817 const SDNode *N, LLVMContext *Context) { 11818 assert((N->getOpcode() == ISD::SDIVREM || N->getOpcode() == ISD::UDIVREM || 11819 N->getOpcode() == ISD::SREM || N->getOpcode() == ISD::UREM) && 11820 "Unhandled Opcode in getDivRemArgList"); 11821 bool isSigned = N->getOpcode() == ISD::SDIVREM || 11822 N->getOpcode() == ISD::SREM; 11823 TargetLowering::ArgListTy Args; 11824 TargetLowering::ArgListEntry Entry; 11825 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) { 11826 EVT ArgVT = N->getOperand(i).getValueType(); 11827 Type *ArgTy = ArgVT.getTypeForEVT(*Context); 11828 Entry.Node = N->getOperand(i); 11829 Entry.Ty = ArgTy; 11830 Entry.isSExt = isSigned; 11831 Entry.isZExt = !isSigned; 11832 Args.push_back(Entry); 11833 } 11834 return Args; 11835 } 11836 11837 SDValue ARMTargetLowering::LowerDivRem(SDValue Op, SelectionDAG &DAG) const { 11838 assert((Subtarget->isTargetAEABI() || Subtarget->isTargetAndroid() || 11839 Subtarget->isTargetGNUAEABI()) && 11840 "Register-based DivRem lowering only"); 11841 unsigned Opcode = Op->getOpcode(); 11842 assert((Opcode == ISD::SDIVREM || Opcode == ISD::UDIVREM) && 11843 "Invalid opcode for Div/Rem lowering"); 11844 bool isSigned = (Opcode == ISD::SDIVREM); 11845 EVT VT = Op->getValueType(0); 11846 Type *Ty = VT.getTypeForEVT(*DAG.getContext()); 11847 11848 RTLIB::Libcall LC = getDivRemLibcall(Op.getNode(), 11849 VT.getSimpleVT().SimpleTy); 11850 SDValue InChain = DAG.getEntryNode(); 11851 11852 TargetLowering::ArgListTy Args = getDivRemArgList(Op.getNode(), 11853 DAG.getContext()); 11854 11855 SDValue Callee = DAG.getExternalSymbol(getLibcallName(LC), 11856 getPointerTy(DAG.getDataLayout())); 11857 11858 Type *RetTy = (Type*)StructType::get(Ty, Ty, nullptr); 11859 11860 SDLoc dl(Op); 11861 TargetLowering::CallLoweringInfo CLI(DAG); 11862 CLI.setDebugLoc(dl).setChain(InChain) 11863 .setCallee(getLibcallCallingConv(LC), RetTy, Callee, std::move(Args), 0) 11864 .setInRegister().setSExtResult(isSigned).setZExtResult(!isSigned); 11865 11866 std::pair<SDValue, SDValue> CallInfo = LowerCallTo(CLI); 11867 return CallInfo.first; 11868 } 11869 11870 // Lowers REM using divmod helpers 11871 // see RTABI section 4.2/4.3 11872 SDValue ARMTargetLowering::LowerREM(SDNode *N, SelectionDAG &DAG) const { 11873 // Build return types (div and rem) 11874 std::vector<Type*> RetTyParams; 11875 Type *RetTyElement; 11876 11877 switch (N->getValueType(0).getSimpleVT().SimpleTy) { 11878 default: llvm_unreachable("Unexpected request for libcall!"); 11879 case MVT::i8: RetTyElement = Type::getInt8Ty(*DAG.getContext()); break; 11880 case MVT::i16: RetTyElement = Type::getInt16Ty(*DAG.getContext()); break; 11881 case MVT::i32: RetTyElement = Type::getInt32Ty(*DAG.getContext()); break; 11882 case MVT::i64: RetTyElement = Type::getInt64Ty(*DAG.getContext()); break; 11883 } 11884 11885 RetTyParams.push_back(RetTyElement); 11886 RetTyParams.push_back(RetTyElement); 11887 ArrayRef<Type*> ret = ArrayRef<Type*>(RetTyParams); 11888 Type *RetTy = StructType::get(*DAG.getContext(), ret); 11889 11890 RTLIB::Libcall LC = getDivRemLibcall(N, N->getValueType(0).getSimpleVT(). 11891 SimpleTy); 11892 SDValue InChain = DAG.getEntryNode(); 11893 TargetLowering::ArgListTy Args = getDivRemArgList(N, DAG.getContext()); 11894 bool isSigned = N->getOpcode() == ISD::SREM; 11895 SDValue Callee = DAG.getExternalSymbol(getLibcallName(LC), 11896 getPointerTy(DAG.getDataLayout())); 11897 11898 // Lower call 11899 CallLoweringInfo CLI(DAG); 11900 CLI.setChain(InChain) 11901 .setCallee(CallingConv::ARM_AAPCS, RetTy, Callee, std::move(Args), 0) 11902 .setSExtResult(isSigned).setZExtResult(!isSigned).setDebugLoc(SDLoc(N)); 11903 std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI); 11904 11905 // Return second (rem) result operand (first contains div) 11906 SDNode *ResNode = CallResult.first.getNode(); 11907 assert(ResNode->getNumOperands() == 2 && "divmod should return two operands"); 11908 return ResNode->getOperand(1); 11909 } 11910 11911 SDValue 11912 ARMTargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op, SelectionDAG &DAG) const { 11913 assert(Subtarget->isTargetWindows() && "unsupported target platform"); 11914 SDLoc DL(Op); 11915 11916 // Get the inputs. 11917 SDValue Chain = Op.getOperand(0); 11918 SDValue Size = Op.getOperand(1); 11919 11920 SDValue Words = DAG.getNode(ISD::SRL, DL, MVT::i32, Size, 11921 DAG.getConstant(2, DL, MVT::i32)); 11922 11923 SDValue Flag; 11924 Chain = DAG.getCopyToReg(Chain, DL, ARM::R4, Words, Flag); 11925 Flag = Chain.getValue(1); 11926 11927 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue); 11928 Chain = DAG.getNode(ARMISD::WIN__CHKSTK, DL, NodeTys, Chain, Flag); 11929 11930 SDValue NewSP = DAG.getCopyFromReg(Chain, DL, ARM::SP, MVT::i32); 11931 Chain = NewSP.getValue(1); 11932 11933 SDValue Ops[2] = { NewSP, Chain }; 11934 return DAG.getMergeValues(Ops, DL); 11935 } 11936 11937 SDValue ARMTargetLowering::LowerFP_EXTEND(SDValue Op, SelectionDAG &DAG) const { 11938 assert(Op.getValueType() == MVT::f64 && Subtarget->isFPOnlySP() && 11939 "Unexpected type for custom-lowering FP_EXTEND"); 11940 11941 RTLIB::Libcall LC; 11942 LC = RTLIB::getFPEXT(Op.getOperand(0).getValueType(), Op.getValueType()); 11943 11944 SDValue SrcVal = Op.getOperand(0); 11945 return makeLibCall(DAG, LC, Op.getValueType(), SrcVal, /*isSigned*/ false, 11946 SDLoc(Op)).first; 11947 } 11948 11949 SDValue ARMTargetLowering::LowerFP_ROUND(SDValue Op, SelectionDAG &DAG) const { 11950 assert(Op.getOperand(0).getValueType() == MVT::f64 && 11951 Subtarget->isFPOnlySP() && 11952 "Unexpected type for custom-lowering FP_ROUND"); 11953 11954 RTLIB::Libcall LC; 11955 LC = RTLIB::getFPROUND(Op.getOperand(0).getValueType(), Op.getValueType()); 11956 11957 SDValue SrcVal = Op.getOperand(0); 11958 return makeLibCall(DAG, LC, Op.getValueType(), SrcVal, /*isSigned*/ false, 11959 SDLoc(Op)).first; 11960 } 11961 11962 bool 11963 ARMTargetLowering::isOffsetFoldingLegal(const GlobalAddressSDNode *GA) const { 11964 // The ARM target isn't yet aware of offsets. 11965 return false; 11966 } 11967 11968 bool ARM::isBitFieldInvertedMask(unsigned v) { 11969 if (v == 0xffffffff) 11970 return false; 11971 11972 // there can be 1's on either or both "outsides", all the "inside" 11973 // bits must be 0's 11974 return isShiftedMask_32(~v); 11975 } 11976 11977 /// isFPImmLegal - Returns true if the target can instruction select the 11978 /// specified FP immediate natively. If false, the legalizer will 11979 /// materialize the FP immediate as a load from a constant pool. 11980 bool ARMTargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT) const { 11981 if (!Subtarget->hasVFP3()) 11982 return false; 11983 if (VT == MVT::f32) 11984 return ARM_AM::getFP32Imm(Imm) != -1; 11985 if (VT == MVT::f64 && !Subtarget->isFPOnlySP()) 11986 return ARM_AM::getFP64Imm(Imm) != -1; 11987 return false; 11988 } 11989 11990 /// getTgtMemIntrinsic - Represent NEON load and store intrinsics as 11991 /// MemIntrinsicNodes. The associated MachineMemOperands record the alignment 11992 /// specified in the intrinsic calls. 11993 bool ARMTargetLowering::getTgtMemIntrinsic(IntrinsicInfo &Info, 11994 const CallInst &I, 11995 unsigned Intrinsic) const { 11996 switch (Intrinsic) { 11997 case Intrinsic::arm_neon_vld1: 11998 case Intrinsic::arm_neon_vld2: 11999 case Intrinsic::arm_neon_vld3: 12000 case Intrinsic::arm_neon_vld4: 12001 case Intrinsic::arm_neon_vld2lane: 12002 case Intrinsic::arm_neon_vld3lane: 12003 case Intrinsic::arm_neon_vld4lane: { 12004 Info.opc = ISD::INTRINSIC_W_CHAIN; 12005 // Conservatively set memVT to the entire set of vectors loaded. 12006 auto &DL = I.getCalledFunction()->getParent()->getDataLayout(); 12007 uint64_t NumElts = DL.getTypeSizeInBits(I.getType()) / 64; 12008 Info.memVT = EVT::getVectorVT(I.getType()->getContext(), MVT::i64, NumElts); 12009 Info.ptrVal = I.getArgOperand(0); 12010 Info.offset = 0; 12011 Value *AlignArg = I.getArgOperand(I.getNumArgOperands() - 1); 12012 Info.align = cast<ConstantInt>(AlignArg)->getZExtValue(); 12013 Info.vol = false; // volatile loads with NEON intrinsics not supported 12014 Info.readMem = true; 12015 Info.writeMem = false; 12016 return true; 12017 } 12018 case Intrinsic::arm_neon_vst1: 12019 case Intrinsic::arm_neon_vst2: 12020 case Intrinsic::arm_neon_vst3: 12021 case Intrinsic::arm_neon_vst4: 12022 case Intrinsic::arm_neon_vst2lane: 12023 case Intrinsic::arm_neon_vst3lane: 12024 case Intrinsic::arm_neon_vst4lane: { 12025 Info.opc = ISD::INTRINSIC_VOID; 12026 // Conservatively set memVT to the entire set of vectors stored. 12027 auto &DL = I.getCalledFunction()->getParent()->getDataLayout(); 12028 unsigned NumElts = 0; 12029 for (unsigned ArgI = 1, ArgE = I.getNumArgOperands(); ArgI < ArgE; ++ArgI) { 12030 Type *ArgTy = I.getArgOperand(ArgI)->getType(); 12031 if (!ArgTy->isVectorTy()) 12032 break; 12033 NumElts += DL.getTypeSizeInBits(ArgTy) / 64; 12034 } 12035 Info.memVT = EVT::getVectorVT(I.getType()->getContext(), MVT::i64, NumElts); 12036 Info.ptrVal = I.getArgOperand(0); 12037 Info.offset = 0; 12038 Value *AlignArg = I.getArgOperand(I.getNumArgOperands() - 1); 12039 Info.align = cast<ConstantInt>(AlignArg)->getZExtValue(); 12040 Info.vol = false; // volatile stores with NEON intrinsics not supported 12041 Info.readMem = false; 12042 Info.writeMem = true; 12043 return true; 12044 } 12045 case Intrinsic::arm_ldaex: 12046 case Intrinsic::arm_ldrex: { 12047 auto &DL = I.getCalledFunction()->getParent()->getDataLayout(); 12048 PointerType *PtrTy = cast<PointerType>(I.getArgOperand(0)->getType()); 12049 Info.opc = ISD::INTRINSIC_W_CHAIN; 12050 Info.memVT = MVT::getVT(PtrTy->getElementType()); 12051 Info.ptrVal = I.getArgOperand(0); 12052 Info.offset = 0; 12053 Info.align = DL.getABITypeAlignment(PtrTy->getElementType()); 12054 Info.vol = true; 12055 Info.readMem = true; 12056 Info.writeMem = false; 12057 return true; 12058 } 12059 case Intrinsic::arm_stlex: 12060 case Intrinsic::arm_strex: { 12061 auto &DL = I.getCalledFunction()->getParent()->getDataLayout(); 12062 PointerType *PtrTy = cast<PointerType>(I.getArgOperand(1)->getType()); 12063 Info.opc = ISD::INTRINSIC_W_CHAIN; 12064 Info.memVT = MVT::getVT(PtrTy->getElementType()); 12065 Info.ptrVal = I.getArgOperand(1); 12066 Info.offset = 0; 12067 Info.align = DL.getABITypeAlignment(PtrTy->getElementType()); 12068 Info.vol = true; 12069 Info.readMem = false; 12070 Info.writeMem = true; 12071 return true; 12072 } 12073 case Intrinsic::arm_stlexd: 12074 case Intrinsic::arm_strexd: { 12075 Info.opc = ISD::INTRINSIC_W_CHAIN; 12076 Info.memVT = MVT::i64; 12077 Info.ptrVal = I.getArgOperand(2); 12078 Info.offset = 0; 12079 Info.align = 8; 12080 Info.vol = true; 12081 Info.readMem = false; 12082 Info.writeMem = true; 12083 return true; 12084 } 12085 case Intrinsic::arm_ldaexd: 12086 case Intrinsic::arm_ldrexd: { 12087 Info.opc = ISD::INTRINSIC_W_CHAIN; 12088 Info.memVT = MVT::i64; 12089 Info.ptrVal = I.getArgOperand(0); 12090 Info.offset = 0; 12091 Info.align = 8; 12092 Info.vol = true; 12093 Info.readMem = true; 12094 Info.writeMem = false; 12095 return true; 12096 } 12097 default: 12098 break; 12099 } 12100 12101 return false; 12102 } 12103 12104 /// \brief Returns true if it is beneficial to convert a load of a constant 12105 /// to just the constant itself. 12106 bool ARMTargetLowering::shouldConvertConstantLoadToIntImm(const APInt &Imm, 12107 Type *Ty) const { 12108 assert(Ty->isIntegerTy()); 12109 12110 unsigned Bits = Ty->getPrimitiveSizeInBits(); 12111 if (Bits == 0 || Bits > 32) 12112 return false; 12113 return true; 12114 } 12115 12116 Instruction* ARMTargetLowering::makeDMB(IRBuilder<> &Builder, 12117 ARM_MB::MemBOpt Domain) const { 12118 Module *M = Builder.GetInsertBlock()->getParent()->getParent(); 12119 12120 // First, if the target has no DMB, see what fallback we can use. 12121 if (!Subtarget->hasDataBarrier()) { 12122 // Some ARMv6 cpus can support data barriers with an mcr instruction. 12123 // Thumb1 and pre-v6 ARM mode use a libcall instead and should never get 12124 // here. 12125 if (Subtarget->hasV6Ops() && !Subtarget->isThumb()) { 12126 Function *MCR = llvm::Intrinsic::getDeclaration(M, Intrinsic::arm_mcr); 12127 Value* args[6] = {Builder.getInt32(15), Builder.getInt32(0), 12128 Builder.getInt32(0), Builder.getInt32(7), 12129 Builder.getInt32(10), Builder.getInt32(5)}; 12130 return Builder.CreateCall(MCR, args); 12131 } else { 12132 // Instead of using barriers, atomic accesses on these subtargets use 12133 // libcalls. 12134 llvm_unreachable("makeDMB on a target so old that it has no barriers"); 12135 } 12136 } else { 12137 Function *DMB = llvm::Intrinsic::getDeclaration(M, Intrinsic::arm_dmb); 12138 // Only a full system barrier exists in the M-class architectures. 12139 Domain = Subtarget->isMClass() ? ARM_MB::SY : Domain; 12140 Constant *CDomain = Builder.getInt32(Domain); 12141 return Builder.CreateCall(DMB, CDomain); 12142 } 12143 } 12144 12145 // Based on http://www.cl.cam.ac.uk/~pes20/cpp/cpp0xmappings.html 12146 Instruction* ARMTargetLowering::emitLeadingFence(IRBuilder<> &Builder, 12147 AtomicOrdering Ord, bool IsStore, 12148 bool IsLoad) const { 12149 switch (Ord) { 12150 case AtomicOrdering::NotAtomic: 12151 case AtomicOrdering::Unordered: 12152 llvm_unreachable("Invalid fence: unordered/non-atomic"); 12153 case AtomicOrdering::Monotonic: 12154 case AtomicOrdering::Acquire: 12155 return nullptr; // Nothing to do 12156 case AtomicOrdering::SequentiallyConsistent: 12157 if (!IsStore) 12158 return nullptr; // Nothing to do 12159 /*FALLTHROUGH*/ 12160 case AtomicOrdering::Release: 12161 case AtomicOrdering::AcquireRelease: 12162 if (Subtarget->isSwift()) 12163 return makeDMB(Builder, ARM_MB::ISHST); 12164 // FIXME: add a comment with a link to documentation justifying this. 12165 else 12166 return makeDMB(Builder, ARM_MB::ISH); 12167 } 12168 llvm_unreachable("Unknown fence ordering in emitLeadingFence"); 12169 } 12170 12171 Instruction* ARMTargetLowering::emitTrailingFence(IRBuilder<> &Builder, 12172 AtomicOrdering Ord, bool IsStore, 12173 bool IsLoad) const { 12174 switch (Ord) { 12175 case AtomicOrdering::NotAtomic: 12176 case AtomicOrdering::Unordered: 12177 llvm_unreachable("Invalid fence: unordered/not-atomic"); 12178 case AtomicOrdering::Monotonic: 12179 case AtomicOrdering::Release: 12180 return nullptr; // Nothing to do 12181 case AtomicOrdering::Acquire: 12182 case AtomicOrdering::AcquireRelease: 12183 case AtomicOrdering::SequentiallyConsistent: 12184 return makeDMB(Builder, ARM_MB::ISH); 12185 } 12186 llvm_unreachable("Unknown fence ordering in emitTrailingFence"); 12187 } 12188 12189 // Loads and stores less than 64-bits are already atomic; ones above that 12190 // are doomed anyway, so defer to the default libcall and blame the OS when 12191 // things go wrong. Cortex M doesn't have ldrexd/strexd though, so don't emit 12192 // anything for those. 12193 bool ARMTargetLowering::shouldExpandAtomicStoreInIR(StoreInst *SI) const { 12194 unsigned Size = SI->getValueOperand()->getType()->getPrimitiveSizeInBits(); 12195 return (Size == 64) && !Subtarget->isMClass(); 12196 } 12197 12198 // Loads and stores less than 64-bits are already atomic; ones above that 12199 // are doomed anyway, so defer to the default libcall and blame the OS when 12200 // things go wrong. Cortex M doesn't have ldrexd/strexd though, so don't emit 12201 // anything for those. 12202 // FIXME: ldrd and strd are atomic if the CPU has LPAE (e.g. A15 has that 12203 // guarantee, see DDI0406C ARM architecture reference manual, 12204 // sections A8.8.72-74 LDRD) 12205 TargetLowering::AtomicExpansionKind 12206 ARMTargetLowering::shouldExpandAtomicLoadInIR(LoadInst *LI) const { 12207 unsigned Size = LI->getType()->getPrimitiveSizeInBits(); 12208 return ((Size == 64) && !Subtarget->isMClass()) ? AtomicExpansionKind::LLOnly 12209 : AtomicExpansionKind::None; 12210 } 12211 12212 // For the real atomic operations, we have ldrex/strex up to 32 bits, 12213 // and up to 64 bits on the non-M profiles 12214 TargetLowering::AtomicExpansionKind 12215 ARMTargetLowering::shouldExpandAtomicRMWInIR(AtomicRMWInst *AI) const { 12216 unsigned Size = AI->getType()->getPrimitiveSizeInBits(); 12217 return (Size <= (Subtarget->isMClass() ? 32U : 64U)) 12218 ? AtomicExpansionKind::LLSC 12219 : AtomicExpansionKind::None; 12220 } 12221 12222 bool ARMTargetLowering::shouldExpandAtomicCmpXchgInIR( 12223 AtomicCmpXchgInst *AI) const { 12224 // At -O0, fast-regalloc cannot cope with the live vregs necessary to 12225 // implement cmpxchg without spilling. If the address being exchanged is also 12226 // on the stack and close enough to the spill slot, this can lead to a 12227 // situation where the monitor always gets cleared and the atomic operation 12228 // can never succeed. So at -O0 we need a late-expanded pseudo-inst instead. 12229 return getTargetMachine().getOptLevel() != 0; 12230 } 12231 12232 bool ARMTargetLowering::shouldInsertFencesForAtomic( 12233 const Instruction *I) const { 12234 return InsertFencesForAtomic; 12235 } 12236 12237 // This has so far only been implemented for MachO. 12238 bool ARMTargetLowering::useLoadStackGuardNode() const { 12239 return Subtarget->isTargetMachO(); 12240 } 12241 12242 bool ARMTargetLowering::canCombineStoreAndExtract(Type *VectorTy, Value *Idx, 12243 unsigned &Cost) const { 12244 // If we do not have NEON, vector types are not natively supported. 12245 if (!Subtarget->hasNEON()) 12246 return false; 12247 12248 // Floating point values and vector values map to the same register file. 12249 // Therefore, although we could do a store extract of a vector type, this is 12250 // better to leave at float as we have more freedom in the addressing mode for 12251 // those. 12252 if (VectorTy->isFPOrFPVectorTy()) 12253 return false; 12254 12255 // If the index is unknown at compile time, this is very expensive to lower 12256 // and it is not possible to combine the store with the extract. 12257 if (!isa<ConstantInt>(Idx)) 12258 return false; 12259 12260 assert(VectorTy->isVectorTy() && "VectorTy is not a vector type"); 12261 unsigned BitWidth = cast<VectorType>(VectorTy)->getBitWidth(); 12262 // We can do a store + vector extract on any vector that fits perfectly in a D 12263 // or Q register. 12264 if (BitWidth == 64 || BitWidth == 128) { 12265 Cost = 0; 12266 return true; 12267 } 12268 return false; 12269 } 12270 12271 bool ARMTargetLowering::isCheapToSpeculateCttz() const { 12272 return Subtarget->hasV6T2Ops(); 12273 } 12274 12275 bool ARMTargetLowering::isCheapToSpeculateCtlz() const { 12276 return Subtarget->hasV6T2Ops(); 12277 } 12278 12279 Value *ARMTargetLowering::emitLoadLinked(IRBuilder<> &Builder, Value *Addr, 12280 AtomicOrdering Ord) const { 12281 Module *M = Builder.GetInsertBlock()->getParent()->getParent(); 12282 Type *ValTy = cast<PointerType>(Addr->getType())->getElementType(); 12283 bool IsAcquire = isAcquireOrStronger(Ord); 12284 12285 // Since i64 isn't legal and intrinsics don't get type-lowered, the ldrexd 12286 // intrinsic must return {i32, i32} and we have to recombine them into a 12287 // single i64 here. 12288 if (ValTy->getPrimitiveSizeInBits() == 64) { 12289 Intrinsic::ID Int = 12290 IsAcquire ? Intrinsic::arm_ldaexd : Intrinsic::arm_ldrexd; 12291 Function *Ldrex = llvm::Intrinsic::getDeclaration(M, Int); 12292 12293 Addr = Builder.CreateBitCast(Addr, Type::getInt8PtrTy(M->getContext())); 12294 Value *LoHi = Builder.CreateCall(Ldrex, Addr, "lohi"); 12295 12296 Value *Lo = Builder.CreateExtractValue(LoHi, 0, "lo"); 12297 Value *Hi = Builder.CreateExtractValue(LoHi, 1, "hi"); 12298 if (!Subtarget->isLittle()) 12299 std::swap (Lo, Hi); 12300 Lo = Builder.CreateZExt(Lo, ValTy, "lo64"); 12301 Hi = Builder.CreateZExt(Hi, ValTy, "hi64"); 12302 return Builder.CreateOr( 12303 Lo, Builder.CreateShl(Hi, ConstantInt::get(ValTy, 32)), "val64"); 12304 } 12305 12306 Type *Tys[] = { Addr->getType() }; 12307 Intrinsic::ID Int = IsAcquire ? Intrinsic::arm_ldaex : Intrinsic::arm_ldrex; 12308 Function *Ldrex = llvm::Intrinsic::getDeclaration(M, Int, Tys); 12309 12310 return Builder.CreateTruncOrBitCast( 12311 Builder.CreateCall(Ldrex, Addr), 12312 cast<PointerType>(Addr->getType())->getElementType()); 12313 } 12314 12315 void ARMTargetLowering::emitAtomicCmpXchgNoStoreLLBalance( 12316 IRBuilder<> &Builder) const { 12317 if (!Subtarget->hasV7Ops()) 12318 return; 12319 Module *M = Builder.GetInsertBlock()->getParent()->getParent(); 12320 Builder.CreateCall(llvm::Intrinsic::getDeclaration(M, Intrinsic::arm_clrex)); 12321 } 12322 12323 Value *ARMTargetLowering::emitStoreConditional(IRBuilder<> &Builder, Value *Val, 12324 Value *Addr, 12325 AtomicOrdering Ord) const { 12326 Module *M = Builder.GetInsertBlock()->getParent()->getParent(); 12327 bool IsRelease = isReleaseOrStronger(Ord); 12328 12329 // Since the intrinsics must have legal type, the i64 intrinsics take two 12330 // parameters: "i32, i32". We must marshal Val into the appropriate form 12331 // before the call. 12332 if (Val->getType()->getPrimitiveSizeInBits() == 64) { 12333 Intrinsic::ID Int = 12334 IsRelease ? Intrinsic::arm_stlexd : Intrinsic::arm_strexd; 12335 Function *Strex = Intrinsic::getDeclaration(M, Int); 12336 Type *Int32Ty = Type::getInt32Ty(M->getContext()); 12337 12338 Value *Lo = Builder.CreateTrunc(Val, Int32Ty, "lo"); 12339 Value *Hi = Builder.CreateTrunc(Builder.CreateLShr(Val, 32), Int32Ty, "hi"); 12340 if (!Subtarget->isLittle()) 12341 std::swap (Lo, Hi); 12342 Addr = Builder.CreateBitCast(Addr, Type::getInt8PtrTy(M->getContext())); 12343 return Builder.CreateCall(Strex, {Lo, Hi, Addr}); 12344 } 12345 12346 Intrinsic::ID Int = IsRelease ? Intrinsic::arm_stlex : Intrinsic::arm_strex; 12347 Type *Tys[] = { Addr->getType() }; 12348 Function *Strex = Intrinsic::getDeclaration(M, Int, Tys); 12349 12350 return Builder.CreateCall( 12351 Strex, {Builder.CreateZExtOrBitCast( 12352 Val, Strex->getFunctionType()->getParamType(0)), 12353 Addr}); 12354 } 12355 12356 /// \brief Lower an interleaved load into a vldN intrinsic. 12357 /// 12358 /// E.g. Lower an interleaved load (Factor = 2): 12359 /// %wide.vec = load <8 x i32>, <8 x i32>* %ptr, align 4 12360 /// %v0 = shuffle %wide.vec, undef, <0, 2, 4, 6> ; Extract even elements 12361 /// %v1 = shuffle %wide.vec, undef, <1, 3, 5, 7> ; Extract odd elements 12362 /// 12363 /// Into: 12364 /// %vld2 = { <4 x i32>, <4 x i32> } call llvm.arm.neon.vld2(%ptr, 4) 12365 /// %vec0 = extractelement { <4 x i32>, <4 x i32> } %vld2, i32 0 12366 /// %vec1 = extractelement { <4 x i32>, <4 x i32> } %vld2, i32 1 12367 bool ARMTargetLowering::lowerInterleavedLoad( 12368 LoadInst *LI, ArrayRef<ShuffleVectorInst *> Shuffles, 12369 ArrayRef<unsigned> Indices, unsigned Factor) const { 12370 assert(Factor >= 2 && Factor <= getMaxSupportedInterleaveFactor() && 12371 "Invalid interleave factor"); 12372 assert(!Shuffles.empty() && "Empty shufflevector input"); 12373 assert(Shuffles.size() == Indices.size() && 12374 "Unmatched number of shufflevectors and indices"); 12375 12376 VectorType *VecTy = Shuffles[0]->getType(); 12377 Type *EltTy = VecTy->getVectorElementType(); 12378 12379 const DataLayout &DL = LI->getModule()->getDataLayout(); 12380 unsigned VecSize = DL.getTypeSizeInBits(VecTy); 12381 bool EltIs64Bits = DL.getTypeSizeInBits(EltTy) == 64; 12382 12383 // Skip if we do not have NEON and skip illegal vector types and vector types 12384 // with i64/f64 elements (vldN doesn't support i64/f64 elements). 12385 if (!Subtarget->hasNEON() || (VecSize != 64 && VecSize != 128) || EltIs64Bits) 12386 return false; 12387 12388 // A pointer vector can not be the return type of the ldN intrinsics. Need to 12389 // load integer vectors first and then convert to pointer vectors. 12390 if (EltTy->isPointerTy()) 12391 VecTy = 12392 VectorType::get(DL.getIntPtrType(EltTy), VecTy->getVectorNumElements()); 12393 12394 static const Intrinsic::ID LoadInts[3] = {Intrinsic::arm_neon_vld2, 12395 Intrinsic::arm_neon_vld3, 12396 Intrinsic::arm_neon_vld4}; 12397 12398 IRBuilder<> Builder(LI); 12399 SmallVector<Value *, 2> Ops; 12400 12401 Type *Int8Ptr = Builder.getInt8PtrTy(LI->getPointerAddressSpace()); 12402 Ops.push_back(Builder.CreateBitCast(LI->getPointerOperand(), Int8Ptr)); 12403 Ops.push_back(Builder.getInt32(LI->getAlignment())); 12404 12405 Type *Tys[] = { VecTy, Int8Ptr }; 12406 Function *VldnFunc = 12407 Intrinsic::getDeclaration(LI->getModule(), LoadInts[Factor - 2], Tys); 12408 CallInst *VldN = Builder.CreateCall(VldnFunc, Ops, "vldN"); 12409 12410 // Replace uses of each shufflevector with the corresponding vector loaded 12411 // by ldN. 12412 for (unsigned i = 0; i < Shuffles.size(); i++) { 12413 ShuffleVectorInst *SV = Shuffles[i]; 12414 unsigned Index = Indices[i]; 12415 12416 Value *SubVec = Builder.CreateExtractValue(VldN, Index); 12417 12418 // Convert the integer vector to pointer vector if the element is pointer. 12419 if (EltTy->isPointerTy()) 12420 SubVec = Builder.CreateIntToPtr(SubVec, SV->getType()); 12421 12422 SV->replaceAllUsesWith(SubVec); 12423 } 12424 12425 return true; 12426 } 12427 12428 /// \brief Get a mask consisting of sequential integers starting from \p Start. 12429 /// 12430 /// I.e. <Start, Start + 1, ..., Start + NumElts - 1> 12431 static Constant *getSequentialMask(IRBuilder<> &Builder, unsigned Start, 12432 unsigned NumElts) { 12433 SmallVector<Constant *, 16> Mask; 12434 for (unsigned i = 0; i < NumElts; i++) 12435 Mask.push_back(Builder.getInt32(Start + i)); 12436 12437 return ConstantVector::get(Mask); 12438 } 12439 12440 /// \brief Lower an interleaved store into a vstN intrinsic. 12441 /// 12442 /// E.g. Lower an interleaved store (Factor = 3): 12443 /// %i.vec = shuffle <8 x i32> %v0, <8 x i32> %v1, 12444 /// <0, 4, 8, 1, 5, 9, 2, 6, 10, 3, 7, 11> 12445 /// store <12 x i32> %i.vec, <12 x i32>* %ptr, align 4 12446 /// 12447 /// Into: 12448 /// %sub.v0 = shuffle <8 x i32> %v0, <8 x i32> v1, <0, 1, 2, 3> 12449 /// %sub.v1 = shuffle <8 x i32> %v0, <8 x i32> v1, <4, 5, 6, 7> 12450 /// %sub.v2 = shuffle <8 x i32> %v0, <8 x i32> v1, <8, 9, 10, 11> 12451 /// call void llvm.arm.neon.vst3(%ptr, %sub.v0, %sub.v1, %sub.v2, 4) 12452 /// 12453 /// Note that the new shufflevectors will be removed and we'll only generate one 12454 /// vst3 instruction in CodeGen. 12455 bool ARMTargetLowering::lowerInterleavedStore(StoreInst *SI, 12456 ShuffleVectorInst *SVI, 12457 unsigned Factor) const { 12458 assert(Factor >= 2 && Factor <= getMaxSupportedInterleaveFactor() && 12459 "Invalid interleave factor"); 12460 12461 VectorType *VecTy = SVI->getType(); 12462 assert(VecTy->getVectorNumElements() % Factor == 0 && 12463 "Invalid interleaved store"); 12464 12465 unsigned NumSubElts = VecTy->getVectorNumElements() / Factor; 12466 Type *EltTy = VecTy->getVectorElementType(); 12467 VectorType *SubVecTy = VectorType::get(EltTy, NumSubElts); 12468 12469 const DataLayout &DL = SI->getModule()->getDataLayout(); 12470 unsigned SubVecSize = DL.getTypeSizeInBits(SubVecTy); 12471 bool EltIs64Bits = DL.getTypeSizeInBits(EltTy) == 64; 12472 12473 // Skip if we do not have NEON and skip illegal vector types and vector types 12474 // with i64/f64 elements (vstN doesn't support i64/f64 elements). 12475 if (!Subtarget->hasNEON() || (SubVecSize != 64 && SubVecSize != 128) || 12476 EltIs64Bits) 12477 return false; 12478 12479 Value *Op0 = SVI->getOperand(0); 12480 Value *Op1 = SVI->getOperand(1); 12481 IRBuilder<> Builder(SI); 12482 12483 // StN intrinsics don't support pointer vectors as arguments. Convert pointer 12484 // vectors to integer vectors. 12485 if (EltTy->isPointerTy()) { 12486 Type *IntTy = DL.getIntPtrType(EltTy); 12487 12488 // Convert to the corresponding integer vector. 12489 Type *IntVecTy = 12490 VectorType::get(IntTy, Op0->getType()->getVectorNumElements()); 12491 Op0 = Builder.CreatePtrToInt(Op0, IntVecTy); 12492 Op1 = Builder.CreatePtrToInt(Op1, IntVecTy); 12493 12494 SubVecTy = VectorType::get(IntTy, NumSubElts); 12495 } 12496 12497 static const Intrinsic::ID StoreInts[3] = {Intrinsic::arm_neon_vst2, 12498 Intrinsic::arm_neon_vst3, 12499 Intrinsic::arm_neon_vst4}; 12500 SmallVector<Value *, 6> Ops; 12501 12502 Type *Int8Ptr = Builder.getInt8PtrTy(SI->getPointerAddressSpace()); 12503 Ops.push_back(Builder.CreateBitCast(SI->getPointerOperand(), Int8Ptr)); 12504 12505 Type *Tys[] = { Int8Ptr, SubVecTy }; 12506 Function *VstNFunc = Intrinsic::getDeclaration( 12507 SI->getModule(), StoreInts[Factor - 2], Tys); 12508 12509 // Split the shufflevector operands into sub vectors for the new vstN call. 12510 for (unsigned i = 0; i < Factor; i++) 12511 Ops.push_back(Builder.CreateShuffleVector( 12512 Op0, Op1, getSequentialMask(Builder, NumSubElts * i, NumSubElts))); 12513 12514 Ops.push_back(Builder.getInt32(SI->getAlignment())); 12515 Builder.CreateCall(VstNFunc, Ops); 12516 return true; 12517 } 12518 12519 enum HABaseType { 12520 HA_UNKNOWN = 0, 12521 HA_FLOAT, 12522 HA_DOUBLE, 12523 HA_VECT64, 12524 HA_VECT128 12525 }; 12526 12527 static bool isHomogeneousAggregate(Type *Ty, HABaseType &Base, 12528 uint64_t &Members) { 12529 if (auto *ST = dyn_cast<StructType>(Ty)) { 12530 for (unsigned i = 0; i < ST->getNumElements(); ++i) { 12531 uint64_t SubMembers = 0; 12532 if (!isHomogeneousAggregate(ST->getElementType(i), Base, SubMembers)) 12533 return false; 12534 Members += SubMembers; 12535 } 12536 } else if (auto *AT = dyn_cast<ArrayType>(Ty)) { 12537 uint64_t SubMembers = 0; 12538 if (!isHomogeneousAggregate(AT->getElementType(), Base, SubMembers)) 12539 return false; 12540 Members += SubMembers * AT->getNumElements(); 12541 } else if (Ty->isFloatTy()) { 12542 if (Base != HA_UNKNOWN && Base != HA_FLOAT) 12543 return false; 12544 Members = 1; 12545 Base = HA_FLOAT; 12546 } else if (Ty->isDoubleTy()) { 12547 if (Base != HA_UNKNOWN && Base != HA_DOUBLE) 12548 return false; 12549 Members = 1; 12550 Base = HA_DOUBLE; 12551 } else if (auto *VT = dyn_cast<VectorType>(Ty)) { 12552 Members = 1; 12553 switch (Base) { 12554 case HA_FLOAT: 12555 case HA_DOUBLE: 12556 return false; 12557 case HA_VECT64: 12558 return VT->getBitWidth() == 64; 12559 case HA_VECT128: 12560 return VT->getBitWidth() == 128; 12561 case HA_UNKNOWN: 12562 switch (VT->getBitWidth()) { 12563 case 64: 12564 Base = HA_VECT64; 12565 return true; 12566 case 128: 12567 Base = HA_VECT128; 12568 return true; 12569 default: 12570 return false; 12571 } 12572 } 12573 } 12574 12575 return (Members > 0 && Members <= 4); 12576 } 12577 12578 /// \brief Return true if a type is an AAPCS-VFP homogeneous aggregate or one of 12579 /// [N x i32] or [N x i64]. This allows front-ends to skip emitting padding when 12580 /// passing according to AAPCS rules. 12581 bool ARMTargetLowering::functionArgumentNeedsConsecutiveRegisters( 12582 Type *Ty, CallingConv::ID CallConv, bool isVarArg) const { 12583 if (getEffectiveCallingConv(CallConv, isVarArg) != 12584 CallingConv::ARM_AAPCS_VFP) 12585 return false; 12586 12587 HABaseType Base = HA_UNKNOWN; 12588 uint64_t Members = 0; 12589 bool IsHA = isHomogeneousAggregate(Ty, Base, Members); 12590 DEBUG(dbgs() << "isHA: " << IsHA << " "; Ty->dump()); 12591 12592 bool IsIntArray = Ty->isArrayTy() && Ty->getArrayElementType()->isIntegerTy(); 12593 return IsHA || IsIntArray; 12594 } 12595 12596 unsigned ARMTargetLowering::getExceptionPointerRegister( 12597 const Constant *PersonalityFn) const { 12598 // Platforms which do not use SjLj EH may return values in these registers 12599 // via the personality function. 12600 return Subtarget->useSjLjEH() ? ARM::NoRegister : ARM::R0; 12601 } 12602 12603 unsigned ARMTargetLowering::getExceptionSelectorRegister( 12604 const Constant *PersonalityFn) const { 12605 // Platforms which do not use SjLj EH may return values in these registers 12606 // via the personality function. 12607 return Subtarget->useSjLjEH() ? ARM::NoRegister : ARM::R1; 12608 } 12609 12610 void ARMTargetLowering::initializeSplitCSR(MachineBasicBlock *Entry) const { 12611 // Update IsSplitCSR in ARMFunctionInfo. 12612 ARMFunctionInfo *AFI = Entry->getParent()->getInfo<ARMFunctionInfo>(); 12613 AFI->setIsSplitCSR(true); 12614 } 12615 12616 void ARMTargetLowering::insertCopiesSplitCSR( 12617 MachineBasicBlock *Entry, 12618 const SmallVectorImpl<MachineBasicBlock *> &Exits) const { 12619 const ARMBaseRegisterInfo *TRI = Subtarget->getRegisterInfo(); 12620 const MCPhysReg *IStart = TRI->getCalleeSavedRegsViaCopy(Entry->getParent()); 12621 if (!IStart) 12622 return; 12623 12624 const TargetInstrInfo *TII = Subtarget->getInstrInfo(); 12625 MachineRegisterInfo *MRI = &Entry->getParent()->getRegInfo(); 12626 MachineBasicBlock::iterator MBBI = Entry->begin(); 12627 for (const MCPhysReg *I = IStart; *I; ++I) { 12628 const TargetRegisterClass *RC = nullptr; 12629 if (ARM::GPRRegClass.contains(*I)) 12630 RC = &ARM::GPRRegClass; 12631 else if (ARM::DPRRegClass.contains(*I)) 12632 RC = &ARM::DPRRegClass; 12633 else 12634 llvm_unreachable("Unexpected register class in CSRsViaCopy!"); 12635 12636 unsigned NewVR = MRI->createVirtualRegister(RC); 12637 // Create copy from CSR to a virtual register. 12638 // FIXME: this currently does not emit CFI pseudo-instructions, it works 12639 // fine for CXX_FAST_TLS since the C++-style TLS access functions should be 12640 // nounwind. If we want to generalize this later, we may need to emit 12641 // CFI pseudo-instructions. 12642 assert(Entry->getParent()->getFunction()->hasFnAttribute( 12643 Attribute::NoUnwind) && 12644 "Function should be nounwind in insertCopiesSplitCSR!"); 12645 Entry->addLiveIn(*I); 12646 BuildMI(*Entry, MBBI, DebugLoc(), TII->get(TargetOpcode::COPY), NewVR) 12647 .addReg(*I); 12648 12649 // Insert the copy-back instructions right before the terminator. 12650 for (auto *Exit : Exits) 12651 BuildMI(*Exit, Exit->getFirstTerminator(), DebugLoc(), 12652 TII->get(TargetOpcode::COPY), *I) 12653 .addReg(NewVR); 12654 } 12655 } 12656