1 //===-- ARMISelLowering.cpp - ARM DAG Lowering Implementation -------------===// 2 // 3 // The LLVM Compiler Infrastructure 4 // 5 // This file is distributed under the University of Illinois Open Source 6 // License. See LICENSE.TXT for details. 7 // 8 //===----------------------------------------------------------------------===// 9 // 10 // This file defines the interfaces that ARM uses to lower LLVM code into a 11 // selection DAG. 12 // 13 //===----------------------------------------------------------------------===// 14 15 #include "ARMISelLowering.h" 16 #include "ARMCallingConv.h" 17 #include "ARMConstantPoolValue.h" 18 #include "ARMMachineFunctionInfo.h" 19 #include "ARMPerfectShuffle.h" 20 #include "ARMSubtarget.h" 21 #include "ARMTargetMachine.h" 22 #include "ARMTargetObjectFile.h" 23 #include "MCTargetDesc/ARMAddressingModes.h" 24 #include "llvm/ADT/Statistic.h" 25 #include "llvm/ADT/StringExtras.h" 26 #include "llvm/ADT/StringSwitch.h" 27 #include "llvm/CodeGen/CallingConvLower.h" 28 #include "llvm/CodeGen/IntrinsicLowering.h" 29 #include "llvm/CodeGen/MachineBasicBlock.h" 30 #include "llvm/CodeGen/MachineFrameInfo.h" 31 #include "llvm/CodeGen/MachineFunction.h" 32 #include "llvm/CodeGen/MachineInstrBuilder.h" 33 #include "llvm/CodeGen/MachineJumpTableInfo.h" 34 #include "llvm/CodeGen/MachineModuleInfo.h" 35 #include "llvm/CodeGen/MachineRegisterInfo.h" 36 #include "llvm/CodeGen/SelectionDAG.h" 37 #include "llvm/IR/CallingConv.h" 38 #include "llvm/IR/Constants.h" 39 #include "llvm/IR/Function.h" 40 #include "llvm/IR/GlobalValue.h" 41 #include "llvm/IR/IRBuilder.h" 42 #include "llvm/IR/Instruction.h" 43 #include "llvm/IR/Instructions.h" 44 #include "llvm/IR/IntrinsicInst.h" 45 #include "llvm/IR/Intrinsics.h" 46 #include "llvm/IR/Type.h" 47 #include "llvm/MC/MCSectionMachO.h" 48 #include "llvm/Support/CommandLine.h" 49 #include "llvm/Support/Debug.h" 50 #include "llvm/Support/ErrorHandling.h" 51 #include "llvm/Support/MathExtras.h" 52 #include "llvm/Support/raw_ostream.h" 53 #include "llvm/Target/TargetOptions.h" 54 #include <utility> 55 using namespace llvm; 56 57 #define DEBUG_TYPE "arm-isel" 58 59 STATISTIC(NumTailCalls, "Number of tail calls"); 60 STATISTIC(NumMovwMovt, "Number of GAs materialized with movw + movt"); 61 STATISTIC(NumLoopByVals, "Number of loops generated for byval arguments"); 62 63 static cl::opt<bool> 64 ARMInterworking("arm-interworking", cl::Hidden, 65 cl::desc("Enable / disable ARM interworking (for debugging only)"), 66 cl::init(true)); 67 68 namespace { 69 class ARMCCState : public CCState { 70 public: 71 ARMCCState(CallingConv::ID CC, bool isVarArg, MachineFunction &MF, 72 SmallVectorImpl<CCValAssign> &locs, LLVMContext &C, 73 ParmContext PC) 74 : CCState(CC, isVarArg, MF, locs, C) { 75 assert(((PC == Call) || (PC == Prologue)) && 76 "ARMCCState users must specify whether their context is call" 77 "or prologue generation."); 78 CallOrPrologue = PC; 79 } 80 }; 81 } 82 83 // The APCS parameter registers. 84 static const MCPhysReg GPRArgRegs[] = { 85 ARM::R0, ARM::R1, ARM::R2, ARM::R3 86 }; 87 88 void ARMTargetLowering::addTypeForNEON(MVT VT, MVT PromotedLdStVT, 89 MVT PromotedBitwiseVT) { 90 if (VT != PromotedLdStVT) { 91 setOperationAction(ISD::LOAD, VT, Promote); 92 AddPromotedToType (ISD::LOAD, VT, PromotedLdStVT); 93 94 setOperationAction(ISD::STORE, VT, Promote); 95 AddPromotedToType (ISD::STORE, VT, PromotedLdStVT); 96 } 97 98 MVT ElemTy = VT.getVectorElementType(); 99 if (ElemTy != MVT::i64 && ElemTy != MVT::f64) 100 setOperationAction(ISD::SETCC, VT, Custom); 101 setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Custom); 102 setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom); 103 if (ElemTy == MVT::i32) { 104 setOperationAction(ISD::SINT_TO_FP, VT, Custom); 105 setOperationAction(ISD::UINT_TO_FP, VT, Custom); 106 setOperationAction(ISD::FP_TO_SINT, VT, Custom); 107 setOperationAction(ISD::FP_TO_UINT, VT, Custom); 108 } else { 109 setOperationAction(ISD::SINT_TO_FP, VT, Expand); 110 setOperationAction(ISD::UINT_TO_FP, VT, Expand); 111 setOperationAction(ISD::FP_TO_SINT, VT, Expand); 112 setOperationAction(ISD::FP_TO_UINT, VT, Expand); 113 } 114 setOperationAction(ISD::BUILD_VECTOR, VT, Custom); 115 setOperationAction(ISD::VECTOR_SHUFFLE, VT, Custom); 116 setOperationAction(ISD::CONCAT_VECTORS, VT, Legal); 117 setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Legal); 118 setOperationAction(ISD::SELECT, VT, Expand); 119 setOperationAction(ISD::SELECT_CC, VT, Expand); 120 setOperationAction(ISD::VSELECT, VT, Expand); 121 setOperationAction(ISD::SIGN_EXTEND_INREG, VT, Expand); 122 if (VT.isInteger()) { 123 setOperationAction(ISD::SHL, VT, Custom); 124 setOperationAction(ISD::SRA, VT, Custom); 125 setOperationAction(ISD::SRL, VT, Custom); 126 } 127 128 // Promote all bit-wise operations. 129 if (VT.isInteger() && VT != PromotedBitwiseVT) { 130 setOperationAction(ISD::AND, VT, Promote); 131 AddPromotedToType (ISD::AND, VT, PromotedBitwiseVT); 132 setOperationAction(ISD::OR, VT, Promote); 133 AddPromotedToType (ISD::OR, VT, PromotedBitwiseVT); 134 setOperationAction(ISD::XOR, VT, Promote); 135 AddPromotedToType (ISD::XOR, VT, PromotedBitwiseVT); 136 } 137 138 // Neon does not support vector divide/remainder operations. 139 setOperationAction(ISD::SDIV, VT, Expand); 140 setOperationAction(ISD::UDIV, VT, Expand); 141 setOperationAction(ISD::FDIV, VT, Expand); 142 setOperationAction(ISD::SREM, VT, Expand); 143 setOperationAction(ISD::UREM, VT, Expand); 144 setOperationAction(ISD::FREM, VT, Expand); 145 146 if (!VT.isFloatingPoint() && 147 VT != MVT::v2i64 && VT != MVT::v1i64) 148 for (unsigned Opcode : {ISD::SMIN, ISD::SMAX, ISD::UMIN, ISD::UMAX}) 149 setOperationAction(Opcode, VT, Legal); 150 } 151 152 void ARMTargetLowering::addDRTypeForNEON(MVT VT) { 153 addRegisterClass(VT, &ARM::DPRRegClass); 154 addTypeForNEON(VT, MVT::f64, MVT::v2i32); 155 } 156 157 void ARMTargetLowering::addQRTypeForNEON(MVT VT) { 158 addRegisterClass(VT, &ARM::DPairRegClass); 159 addTypeForNEON(VT, MVT::v2f64, MVT::v4i32); 160 } 161 162 ARMTargetLowering::ARMTargetLowering(const TargetMachine &TM, 163 const ARMSubtarget &STI) 164 : TargetLowering(TM), Subtarget(&STI) { 165 RegInfo = Subtarget->getRegisterInfo(); 166 Itins = Subtarget->getInstrItineraryData(); 167 168 setBooleanVectorContents(ZeroOrNegativeOneBooleanContent); 169 170 if (Subtarget->isTargetMachO()) { 171 // Uses VFP for Thumb libfuncs if available. 172 if (Subtarget->isThumb() && Subtarget->hasVFP2() && 173 Subtarget->hasARMOps() && !Subtarget->useSoftFloat()) { 174 static const struct { 175 const RTLIB::Libcall Op; 176 const char * const Name; 177 const ISD::CondCode Cond; 178 } LibraryCalls[] = { 179 // Single-precision floating-point arithmetic. 180 { RTLIB::ADD_F32, "__addsf3vfp", ISD::SETCC_INVALID }, 181 { RTLIB::SUB_F32, "__subsf3vfp", ISD::SETCC_INVALID }, 182 { RTLIB::MUL_F32, "__mulsf3vfp", ISD::SETCC_INVALID }, 183 { RTLIB::DIV_F32, "__divsf3vfp", ISD::SETCC_INVALID }, 184 185 // Double-precision floating-point arithmetic. 186 { RTLIB::ADD_F64, "__adddf3vfp", ISD::SETCC_INVALID }, 187 { RTLIB::SUB_F64, "__subdf3vfp", ISD::SETCC_INVALID }, 188 { RTLIB::MUL_F64, "__muldf3vfp", ISD::SETCC_INVALID }, 189 { RTLIB::DIV_F64, "__divdf3vfp", ISD::SETCC_INVALID }, 190 191 // Single-precision comparisons. 192 { RTLIB::OEQ_F32, "__eqsf2vfp", ISD::SETNE }, 193 { RTLIB::UNE_F32, "__nesf2vfp", ISD::SETNE }, 194 { RTLIB::OLT_F32, "__ltsf2vfp", ISD::SETNE }, 195 { RTLIB::OLE_F32, "__lesf2vfp", ISD::SETNE }, 196 { RTLIB::OGE_F32, "__gesf2vfp", ISD::SETNE }, 197 { RTLIB::OGT_F32, "__gtsf2vfp", ISD::SETNE }, 198 { RTLIB::UO_F32, "__unordsf2vfp", ISD::SETNE }, 199 { RTLIB::O_F32, "__unordsf2vfp", ISD::SETEQ }, 200 201 // Double-precision comparisons. 202 { RTLIB::OEQ_F64, "__eqdf2vfp", ISD::SETNE }, 203 { RTLIB::UNE_F64, "__nedf2vfp", ISD::SETNE }, 204 { RTLIB::OLT_F64, "__ltdf2vfp", ISD::SETNE }, 205 { RTLIB::OLE_F64, "__ledf2vfp", ISD::SETNE }, 206 { RTLIB::OGE_F64, "__gedf2vfp", ISD::SETNE }, 207 { RTLIB::OGT_F64, "__gtdf2vfp", ISD::SETNE }, 208 { RTLIB::UO_F64, "__unorddf2vfp", ISD::SETNE }, 209 { RTLIB::O_F64, "__unorddf2vfp", ISD::SETEQ }, 210 211 // Floating-point to integer conversions. 212 // i64 conversions are done via library routines even when generating VFP 213 // instructions, so use the same ones. 214 { RTLIB::FPTOSINT_F64_I32, "__fixdfsivfp", ISD::SETCC_INVALID }, 215 { RTLIB::FPTOUINT_F64_I32, "__fixunsdfsivfp", ISD::SETCC_INVALID }, 216 { RTLIB::FPTOSINT_F32_I32, "__fixsfsivfp", ISD::SETCC_INVALID }, 217 { RTLIB::FPTOUINT_F32_I32, "__fixunssfsivfp", ISD::SETCC_INVALID }, 218 219 // Conversions between floating types. 220 { RTLIB::FPROUND_F64_F32, "__truncdfsf2vfp", ISD::SETCC_INVALID }, 221 { RTLIB::FPEXT_F32_F64, "__extendsfdf2vfp", ISD::SETCC_INVALID }, 222 223 // Integer to floating-point conversions. 224 // i64 conversions are done via library routines even when generating VFP 225 // instructions, so use the same ones. 226 // FIXME: There appears to be some naming inconsistency in ARM libgcc: 227 // e.g., __floatunsidf vs. __floatunssidfvfp. 228 { RTLIB::SINTTOFP_I32_F64, "__floatsidfvfp", ISD::SETCC_INVALID }, 229 { RTLIB::UINTTOFP_I32_F64, "__floatunssidfvfp", ISD::SETCC_INVALID }, 230 { RTLIB::SINTTOFP_I32_F32, "__floatsisfvfp", ISD::SETCC_INVALID }, 231 { RTLIB::UINTTOFP_I32_F32, "__floatunssisfvfp", ISD::SETCC_INVALID }, 232 }; 233 234 for (const auto &LC : LibraryCalls) { 235 setLibcallName(LC.Op, LC.Name); 236 if (LC.Cond != ISD::SETCC_INVALID) 237 setCmpLibcallCC(LC.Op, LC.Cond); 238 } 239 } 240 241 // Set the correct calling convention for ARMv7k WatchOS. It's just 242 // AAPCS_VFP for functions as simple as libcalls. 243 if (Subtarget->isTargetWatchABI()) { 244 for (int i = 0; i < RTLIB::UNKNOWN_LIBCALL; ++i) 245 setLibcallCallingConv((RTLIB::Libcall)i, CallingConv::ARM_AAPCS_VFP); 246 } 247 } 248 249 // These libcalls are not available in 32-bit. 250 setLibcallName(RTLIB::SHL_I128, nullptr); 251 setLibcallName(RTLIB::SRL_I128, nullptr); 252 setLibcallName(RTLIB::SRA_I128, nullptr); 253 254 // RTLIB 255 if (Subtarget->isAAPCS_ABI() && 256 (Subtarget->isTargetAEABI() || Subtarget->isTargetGNUAEABI() || 257 Subtarget->isTargetAndroid())) { 258 static const struct { 259 const RTLIB::Libcall Op; 260 const char * const Name; 261 const CallingConv::ID CC; 262 const ISD::CondCode Cond; 263 } LibraryCalls[] = { 264 // Double-precision floating-point arithmetic helper functions 265 // RTABI chapter 4.1.2, Table 2 266 { RTLIB::ADD_F64, "__aeabi_dadd", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 267 { RTLIB::DIV_F64, "__aeabi_ddiv", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 268 { RTLIB::MUL_F64, "__aeabi_dmul", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 269 { RTLIB::SUB_F64, "__aeabi_dsub", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 270 271 // Double-precision floating-point comparison helper functions 272 // RTABI chapter 4.1.2, Table 3 273 { RTLIB::OEQ_F64, "__aeabi_dcmpeq", CallingConv::ARM_AAPCS, ISD::SETNE }, 274 { RTLIB::UNE_F64, "__aeabi_dcmpeq", CallingConv::ARM_AAPCS, ISD::SETEQ }, 275 { RTLIB::OLT_F64, "__aeabi_dcmplt", CallingConv::ARM_AAPCS, ISD::SETNE }, 276 { RTLIB::OLE_F64, "__aeabi_dcmple", CallingConv::ARM_AAPCS, ISD::SETNE }, 277 { RTLIB::OGE_F64, "__aeabi_dcmpge", CallingConv::ARM_AAPCS, ISD::SETNE }, 278 { RTLIB::OGT_F64, "__aeabi_dcmpgt", CallingConv::ARM_AAPCS, ISD::SETNE }, 279 { RTLIB::UO_F64, "__aeabi_dcmpun", CallingConv::ARM_AAPCS, ISD::SETNE }, 280 { RTLIB::O_F64, "__aeabi_dcmpun", CallingConv::ARM_AAPCS, ISD::SETEQ }, 281 282 // Single-precision floating-point arithmetic helper functions 283 // RTABI chapter 4.1.2, Table 4 284 { RTLIB::ADD_F32, "__aeabi_fadd", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 285 { RTLIB::DIV_F32, "__aeabi_fdiv", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 286 { RTLIB::MUL_F32, "__aeabi_fmul", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 287 { RTLIB::SUB_F32, "__aeabi_fsub", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 288 289 // Single-precision floating-point comparison helper functions 290 // RTABI chapter 4.1.2, Table 5 291 { RTLIB::OEQ_F32, "__aeabi_fcmpeq", CallingConv::ARM_AAPCS, ISD::SETNE }, 292 { RTLIB::UNE_F32, "__aeabi_fcmpeq", CallingConv::ARM_AAPCS, ISD::SETEQ }, 293 { RTLIB::OLT_F32, "__aeabi_fcmplt", CallingConv::ARM_AAPCS, ISD::SETNE }, 294 { RTLIB::OLE_F32, "__aeabi_fcmple", CallingConv::ARM_AAPCS, ISD::SETNE }, 295 { RTLIB::OGE_F32, "__aeabi_fcmpge", CallingConv::ARM_AAPCS, ISD::SETNE }, 296 { RTLIB::OGT_F32, "__aeabi_fcmpgt", CallingConv::ARM_AAPCS, ISD::SETNE }, 297 { RTLIB::UO_F32, "__aeabi_fcmpun", CallingConv::ARM_AAPCS, ISD::SETNE }, 298 { RTLIB::O_F32, "__aeabi_fcmpun", CallingConv::ARM_AAPCS, ISD::SETEQ }, 299 300 // Floating-point to integer conversions. 301 // RTABI chapter 4.1.2, Table 6 302 { RTLIB::FPTOSINT_F64_I32, "__aeabi_d2iz", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 303 { RTLIB::FPTOUINT_F64_I32, "__aeabi_d2uiz", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 304 { RTLIB::FPTOSINT_F64_I64, "__aeabi_d2lz", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 305 { RTLIB::FPTOUINT_F64_I64, "__aeabi_d2ulz", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 306 { RTLIB::FPTOSINT_F32_I32, "__aeabi_f2iz", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 307 { RTLIB::FPTOUINT_F32_I32, "__aeabi_f2uiz", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 308 { RTLIB::FPTOSINT_F32_I64, "__aeabi_f2lz", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 309 { RTLIB::FPTOUINT_F32_I64, "__aeabi_f2ulz", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 310 311 // Conversions between floating types. 312 // RTABI chapter 4.1.2, Table 7 313 { RTLIB::FPROUND_F64_F32, "__aeabi_d2f", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 314 { RTLIB::FPROUND_F64_F16, "__aeabi_d2h", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 315 { RTLIB::FPEXT_F32_F64, "__aeabi_f2d", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 316 317 // Integer to floating-point conversions. 318 // RTABI chapter 4.1.2, Table 8 319 { RTLIB::SINTTOFP_I32_F64, "__aeabi_i2d", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 320 { RTLIB::UINTTOFP_I32_F64, "__aeabi_ui2d", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 321 { RTLIB::SINTTOFP_I64_F64, "__aeabi_l2d", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 322 { RTLIB::UINTTOFP_I64_F64, "__aeabi_ul2d", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 323 { RTLIB::SINTTOFP_I32_F32, "__aeabi_i2f", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 324 { RTLIB::UINTTOFP_I32_F32, "__aeabi_ui2f", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 325 { RTLIB::SINTTOFP_I64_F32, "__aeabi_l2f", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 326 { RTLIB::UINTTOFP_I64_F32, "__aeabi_ul2f", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 327 328 // Long long helper functions 329 // RTABI chapter 4.2, Table 9 330 { RTLIB::MUL_I64, "__aeabi_lmul", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 331 { RTLIB::SHL_I64, "__aeabi_llsl", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 332 { RTLIB::SRL_I64, "__aeabi_llsr", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 333 { RTLIB::SRA_I64, "__aeabi_lasr", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 334 335 // Integer division functions 336 // RTABI chapter 4.3.1 337 { RTLIB::SDIV_I8, "__aeabi_idiv", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 338 { RTLIB::SDIV_I16, "__aeabi_idiv", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 339 { RTLIB::SDIV_I32, "__aeabi_idiv", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 340 { RTLIB::SDIV_I64, "__aeabi_ldivmod", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 341 { RTLIB::UDIV_I8, "__aeabi_uidiv", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 342 { RTLIB::UDIV_I16, "__aeabi_uidiv", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 343 { RTLIB::UDIV_I32, "__aeabi_uidiv", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 344 { RTLIB::UDIV_I64, "__aeabi_uldivmod", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 345 }; 346 347 for (const auto &LC : LibraryCalls) { 348 setLibcallName(LC.Op, LC.Name); 349 setLibcallCallingConv(LC.Op, LC.CC); 350 if (LC.Cond != ISD::SETCC_INVALID) 351 setCmpLibcallCC(LC.Op, LC.Cond); 352 } 353 354 // EABI dependent RTLIB 355 if (TM.Options.EABIVersion == EABI::EABI4 || 356 TM.Options.EABIVersion == EABI::EABI5) { 357 static const struct { 358 const RTLIB::Libcall Op; 359 const char *const Name; 360 const CallingConv::ID CC; 361 const ISD::CondCode Cond; 362 } MemOpsLibraryCalls[] = { 363 // Memory operations 364 // RTABI chapter 4.3.4 365 { RTLIB::MEMCPY, "__aeabi_memcpy", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 366 { RTLIB::MEMMOVE, "__aeabi_memmove", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 367 { RTLIB::MEMSET, "__aeabi_memset", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 368 }; 369 370 for (const auto &LC : MemOpsLibraryCalls) { 371 setLibcallName(LC.Op, LC.Name); 372 setLibcallCallingConv(LC.Op, LC.CC); 373 if (LC.Cond != ISD::SETCC_INVALID) 374 setCmpLibcallCC(LC.Op, LC.Cond); 375 } 376 } 377 } 378 379 if (Subtarget->isTargetWindows()) { 380 static const struct { 381 const RTLIB::Libcall Op; 382 const char * const Name; 383 const CallingConv::ID CC; 384 } LibraryCalls[] = { 385 { RTLIB::FPTOSINT_F32_I64, "__stoi64", CallingConv::ARM_AAPCS_VFP }, 386 { RTLIB::FPTOSINT_F64_I64, "__dtoi64", CallingConv::ARM_AAPCS_VFP }, 387 { RTLIB::FPTOUINT_F32_I64, "__stou64", CallingConv::ARM_AAPCS_VFP }, 388 { RTLIB::FPTOUINT_F64_I64, "__dtou64", CallingConv::ARM_AAPCS_VFP }, 389 { RTLIB::SINTTOFP_I64_F32, "__i64tos", CallingConv::ARM_AAPCS_VFP }, 390 { RTLIB::SINTTOFP_I64_F64, "__i64tod", CallingConv::ARM_AAPCS_VFP }, 391 { RTLIB::UINTTOFP_I64_F32, "__u64tos", CallingConv::ARM_AAPCS_VFP }, 392 { RTLIB::UINTTOFP_I64_F64, "__u64tod", CallingConv::ARM_AAPCS_VFP }, 393 { RTLIB::SDIV_I32, "__rt_sdiv", CallingConv::ARM_AAPCS_VFP }, 394 { RTLIB::UDIV_I32, "__rt_udiv", CallingConv::ARM_AAPCS_VFP }, 395 { RTLIB::SDIV_I64, "__rt_sdiv64", CallingConv::ARM_AAPCS_VFP }, 396 { RTLIB::UDIV_I64, "__rt_udiv64", CallingConv::ARM_AAPCS_VFP }, 397 }; 398 399 for (const auto &LC : LibraryCalls) { 400 setLibcallName(LC.Op, LC.Name); 401 setLibcallCallingConv(LC.Op, LC.CC); 402 } 403 } 404 405 // Use divmod compiler-rt calls for iOS 5.0 and later. 406 if (Subtarget->isTargetWatchOS() || 407 (Subtarget->isTargetIOS() && 408 !Subtarget->getTargetTriple().isOSVersionLT(5, 0))) { 409 setLibcallName(RTLIB::SDIVREM_I32, "__divmodsi4"); 410 setLibcallName(RTLIB::UDIVREM_I32, "__udivmodsi4"); 411 } 412 413 // The half <-> float conversion functions are always soft-float, but are 414 // needed for some targets which use a hard-float calling convention by 415 // default. 416 if (Subtarget->isAAPCS_ABI()) { 417 setLibcallCallingConv(RTLIB::FPROUND_F32_F16, CallingConv::ARM_AAPCS); 418 setLibcallCallingConv(RTLIB::FPROUND_F64_F16, CallingConv::ARM_AAPCS); 419 setLibcallCallingConv(RTLIB::FPEXT_F16_F32, CallingConv::ARM_AAPCS); 420 } else { 421 setLibcallCallingConv(RTLIB::FPROUND_F32_F16, CallingConv::ARM_APCS); 422 setLibcallCallingConv(RTLIB::FPROUND_F64_F16, CallingConv::ARM_APCS); 423 setLibcallCallingConv(RTLIB::FPEXT_F16_F32, CallingConv::ARM_APCS); 424 } 425 426 // In EABI, these functions have an __aeabi_ prefix, but in GNUEABI they have 427 // a __gnu_ prefix (which is the default). 428 if (Subtarget->isTargetAEABI()) { 429 setLibcallName(RTLIB::FPROUND_F32_F16, "__aeabi_f2h"); 430 setLibcallName(RTLIB::FPROUND_F64_F16, "__aeabi_d2h"); 431 setLibcallName(RTLIB::FPEXT_F16_F32, "__aeabi_h2f"); 432 } 433 434 if (Subtarget->isThumb1Only()) 435 addRegisterClass(MVT::i32, &ARM::tGPRRegClass); 436 else 437 addRegisterClass(MVT::i32, &ARM::GPRRegClass); 438 if (!Subtarget->useSoftFloat() && Subtarget->hasVFP2() && 439 !Subtarget->isThumb1Only()) { 440 addRegisterClass(MVT::f32, &ARM::SPRRegClass); 441 addRegisterClass(MVT::f64, &ARM::DPRRegClass); 442 } 443 444 for (MVT VT : MVT::vector_valuetypes()) { 445 for (MVT InnerVT : MVT::vector_valuetypes()) { 446 setTruncStoreAction(VT, InnerVT, Expand); 447 setLoadExtAction(ISD::SEXTLOAD, VT, InnerVT, Expand); 448 setLoadExtAction(ISD::ZEXTLOAD, VT, InnerVT, Expand); 449 setLoadExtAction(ISD::EXTLOAD, VT, InnerVT, Expand); 450 } 451 452 setOperationAction(ISD::MULHS, VT, Expand); 453 setOperationAction(ISD::SMUL_LOHI, VT, Expand); 454 setOperationAction(ISD::MULHU, VT, Expand); 455 setOperationAction(ISD::UMUL_LOHI, VT, Expand); 456 457 setOperationAction(ISD::BSWAP, VT, Expand); 458 } 459 460 setOperationAction(ISD::ConstantFP, MVT::f32, Custom); 461 setOperationAction(ISD::ConstantFP, MVT::f64, Custom); 462 463 setOperationAction(ISD::READ_REGISTER, MVT::i64, Custom); 464 setOperationAction(ISD::WRITE_REGISTER, MVT::i64, Custom); 465 466 if (Subtarget->hasNEON()) { 467 addDRTypeForNEON(MVT::v2f32); 468 addDRTypeForNEON(MVT::v8i8); 469 addDRTypeForNEON(MVT::v4i16); 470 addDRTypeForNEON(MVT::v2i32); 471 addDRTypeForNEON(MVT::v1i64); 472 473 addQRTypeForNEON(MVT::v4f32); 474 addQRTypeForNEON(MVT::v2f64); 475 addQRTypeForNEON(MVT::v16i8); 476 addQRTypeForNEON(MVT::v8i16); 477 addQRTypeForNEON(MVT::v4i32); 478 addQRTypeForNEON(MVT::v2i64); 479 480 // v2f64 is legal so that QR subregs can be extracted as f64 elements, but 481 // neither Neon nor VFP support any arithmetic operations on it. 482 // The same with v4f32. But keep in mind that vadd, vsub, vmul are natively 483 // supported for v4f32. 484 setOperationAction(ISD::FADD, MVT::v2f64, Expand); 485 setOperationAction(ISD::FSUB, MVT::v2f64, Expand); 486 setOperationAction(ISD::FMUL, MVT::v2f64, Expand); 487 // FIXME: Code duplication: FDIV and FREM are expanded always, see 488 // ARMTargetLowering::addTypeForNEON method for details. 489 setOperationAction(ISD::FDIV, MVT::v2f64, Expand); 490 setOperationAction(ISD::FREM, MVT::v2f64, Expand); 491 // FIXME: Create unittest. 492 // In another words, find a way when "copysign" appears in DAG with vector 493 // operands. 494 setOperationAction(ISD::FCOPYSIGN, MVT::v2f64, Expand); 495 // FIXME: Code duplication: SETCC has custom operation action, see 496 // ARMTargetLowering::addTypeForNEON method for details. 497 setOperationAction(ISD::SETCC, MVT::v2f64, Expand); 498 // FIXME: Create unittest for FNEG and for FABS. 499 setOperationAction(ISD::FNEG, MVT::v2f64, Expand); 500 setOperationAction(ISD::FABS, MVT::v2f64, Expand); 501 setOperationAction(ISD::FSQRT, MVT::v2f64, Expand); 502 setOperationAction(ISD::FSIN, MVT::v2f64, Expand); 503 setOperationAction(ISD::FCOS, MVT::v2f64, Expand); 504 setOperationAction(ISD::FPOWI, MVT::v2f64, Expand); 505 setOperationAction(ISD::FPOW, MVT::v2f64, Expand); 506 setOperationAction(ISD::FLOG, MVT::v2f64, Expand); 507 setOperationAction(ISD::FLOG2, MVT::v2f64, Expand); 508 setOperationAction(ISD::FLOG10, MVT::v2f64, Expand); 509 setOperationAction(ISD::FEXP, MVT::v2f64, Expand); 510 setOperationAction(ISD::FEXP2, MVT::v2f64, Expand); 511 // FIXME: Create unittest for FCEIL, FTRUNC, FRINT, FNEARBYINT, FFLOOR. 512 setOperationAction(ISD::FCEIL, MVT::v2f64, Expand); 513 setOperationAction(ISD::FTRUNC, MVT::v2f64, Expand); 514 setOperationAction(ISD::FRINT, MVT::v2f64, Expand); 515 setOperationAction(ISD::FNEARBYINT, MVT::v2f64, Expand); 516 setOperationAction(ISD::FFLOOR, MVT::v2f64, Expand); 517 setOperationAction(ISD::FMA, MVT::v2f64, Expand); 518 519 setOperationAction(ISD::FSQRT, MVT::v4f32, Expand); 520 setOperationAction(ISD::FSIN, MVT::v4f32, Expand); 521 setOperationAction(ISD::FCOS, MVT::v4f32, Expand); 522 setOperationAction(ISD::FPOWI, MVT::v4f32, Expand); 523 setOperationAction(ISD::FPOW, MVT::v4f32, Expand); 524 setOperationAction(ISD::FLOG, MVT::v4f32, Expand); 525 setOperationAction(ISD::FLOG2, MVT::v4f32, Expand); 526 setOperationAction(ISD::FLOG10, MVT::v4f32, Expand); 527 setOperationAction(ISD::FEXP, MVT::v4f32, Expand); 528 setOperationAction(ISD::FEXP2, MVT::v4f32, Expand); 529 setOperationAction(ISD::FCEIL, MVT::v4f32, Expand); 530 setOperationAction(ISD::FTRUNC, MVT::v4f32, Expand); 531 setOperationAction(ISD::FRINT, MVT::v4f32, Expand); 532 setOperationAction(ISD::FNEARBYINT, MVT::v4f32, Expand); 533 setOperationAction(ISD::FFLOOR, MVT::v4f32, Expand); 534 535 // Mark v2f32 intrinsics. 536 setOperationAction(ISD::FSQRT, MVT::v2f32, Expand); 537 setOperationAction(ISD::FSIN, MVT::v2f32, Expand); 538 setOperationAction(ISD::FCOS, MVT::v2f32, Expand); 539 setOperationAction(ISD::FPOWI, MVT::v2f32, Expand); 540 setOperationAction(ISD::FPOW, MVT::v2f32, Expand); 541 setOperationAction(ISD::FLOG, MVT::v2f32, Expand); 542 setOperationAction(ISD::FLOG2, MVT::v2f32, Expand); 543 setOperationAction(ISD::FLOG10, MVT::v2f32, Expand); 544 setOperationAction(ISD::FEXP, MVT::v2f32, Expand); 545 setOperationAction(ISD::FEXP2, MVT::v2f32, Expand); 546 setOperationAction(ISD::FCEIL, MVT::v2f32, Expand); 547 setOperationAction(ISD::FTRUNC, MVT::v2f32, Expand); 548 setOperationAction(ISD::FRINT, MVT::v2f32, Expand); 549 setOperationAction(ISD::FNEARBYINT, MVT::v2f32, Expand); 550 setOperationAction(ISD::FFLOOR, MVT::v2f32, Expand); 551 552 // Neon does not support some operations on v1i64 and v2i64 types. 553 setOperationAction(ISD::MUL, MVT::v1i64, Expand); 554 // Custom handling for some quad-vector types to detect VMULL. 555 setOperationAction(ISD::MUL, MVT::v8i16, Custom); 556 setOperationAction(ISD::MUL, MVT::v4i32, Custom); 557 setOperationAction(ISD::MUL, MVT::v2i64, Custom); 558 // Custom handling for some vector types to avoid expensive expansions 559 setOperationAction(ISD::SDIV, MVT::v4i16, Custom); 560 setOperationAction(ISD::SDIV, MVT::v8i8, Custom); 561 setOperationAction(ISD::UDIV, MVT::v4i16, Custom); 562 setOperationAction(ISD::UDIV, MVT::v8i8, Custom); 563 setOperationAction(ISD::SETCC, MVT::v1i64, Expand); 564 setOperationAction(ISD::SETCC, MVT::v2i64, Expand); 565 // Neon does not have single instruction SINT_TO_FP and UINT_TO_FP with 566 // a destination type that is wider than the source, and nor does 567 // it have a FP_TO_[SU]INT instruction with a narrower destination than 568 // source. 569 setOperationAction(ISD::SINT_TO_FP, MVT::v4i16, Custom); 570 setOperationAction(ISD::UINT_TO_FP, MVT::v4i16, Custom); 571 setOperationAction(ISD::FP_TO_UINT, MVT::v4i16, Custom); 572 setOperationAction(ISD::FP_TO_SINT, MVT::v4i16, Custom); 573 574 setOperationAction(ISD::FP_ROUND, MVT::v2f32, Expand); 575 setOperationAction(ISD::FP_EXTEND, MVT::v2f64, Expand); 576 577 // NEON does not have single instruction CTPOP for vectors with element 578 // types wider than 8-bits. However, custom lowering can leverage the 579 // v8i8/v16i8 vcnt instruction. 580 setOperationAction(ISD::CTPOP, MVT::v2i32, Custom); 581 setOperationAction(ISD::CTPOP, MVT::v4i32, Custom); 582 setOperationAction(ISD::CTPOP, MVT::v4i16, Custom); 583 setOperationAction(ISD::CTPOP, MVT::v8i16, Custom); 584 585 // NEON does not have single instruction CTTZ for vectors. 586 setOperationAction(ISD::CTTZ, MVT::v8i8, Custom); 587 setOperationAction(ISD::CTTZ, MVT::v4i16, Custom); 588 setOperationAction(ISD::CTTZ, MVT::v2i32, Custom); 589 setOperationAction(ISD::CTTZ, MVT::v1i64, Custom); 590 591 setOperationAction(ISD::CTTZ, MVT::v16i8, Custom); 592 setOperationAction(ISD::CTTZ, MVT::v8i16, Custom); 593 setOperationAction(ISD::CTTZ, MVT::v4i32, Custom); 594 setOperationAction(ISD::CTTZ, MVT::v2i64, Custom); 595 596 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::v8i8, Custom); 597 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::v4i16, Custom); 598 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::v2i32, Custom); 599 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::v1i64, Custom); 600 601 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::v16i8, Custom); 602 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::v8i16, Custom); 603 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::v4i32, Custom); 604 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::v2i64, Custom); 605 606 // NEON only has FMA instructions as of VFP4. 607 if (!Subtarget->hasVFP4()) { 608 setOperationAction(ISD::FMA, MVT::v2f32, Expand); 609 setOperationAction(ISD::FMA, MVT::v4f32, Expand); 610 } 611 612 setTargetDAGCombine(ISD::INTRINSIC_VOID); 613 setTargetDAGCombine(ISD::INTRINSIC_W_CHAIN); 614 setTargetDAGCombine(ISD::INTRINSIC_WO_CHAIN); 615 setTargetDAGCombine(ISD::SHL); 616 setTargetDAGCombine(ISD::SRL); 617 setTargetDAGCombine(ISD::SRA); 618 setTargetDAGCombine(ISD::SIGN_EXTEND); 619 setTargetDAGCombine(ISD::ZERO_EXTEND); 620 setTargetDAGCombine(ISD::ANY_EXTEND); 621 setTargetDAGCombine(ISD::BUILD_VECTOR); 622 setTargetDAGCombine(ISD::VECTOR_SHUFFLE); 623 setTargetDAGCombine(ISD::INSERT_VECTOR_ELT); 624 setTargetDAGCombine(ISD::STORE); 625 setTargetDAGCombine(ISD::FP_TO_SINT); 626 setTargetDAGCombine(ISD::FP_TO_UINT); 627 setTargetDAGCombine(ISD::FDIV); 628 setTargetDAGCombine(ISD::LOAD); 629 630 // It is legal to extload from v4i8 to v4i16 or v4i32. 631 for (MVT Ty : {MVT::v8i8, MVT::v4i8, MVT::v2i8, MVT::v4i16, MVT::v2i16, 632 MVT::v2i32}) { 633 for (MVT VT : MVT::integer_vector_valuetypes()) { 634 setLoadExtAction(ISD::EXTLOAD, VT, Ty, Legal); 635 setLoadExtAction(ISD::ZEXTLOAD, VT, Ty, Legal); 636 setLoadExtAction(ISD::SEXTLOAD, VT, Ty, Legal); 637 } 638 } 639 } 640 641 // ARM and Thumb2 support UMLAL/SMLAL. 642 if (!Subtarget->isThumb1Only()) 643 setTargetDAGCombine(ISD::ADDC); 644 645 if (Subtarget->isFPOnlySP()) { 646 // When targeting a floating-point unit with only single-precision 647 // operations, f64 is legal for the few double-precision instructions which 648 // are present However, no double-precision operations other than moves, 649 // loads and stores are provided by the hardware. 650 setOperationAction(ISD::FADD, MVT::f64, Expand); 651 setOperationAction(ISD::FSUB, MVT::f64, Expand); 652 setOperationAction(ISD::FMUL, MVT::f64, Expand); 653 setOperationAction(ISD::FMA, MVT::f64, Expand); 654 setOperationAction(ISD::FDIV, MVT::f64, Expand); 655 setOperationAction(ISD::FREM, MVT::f64, Expand); 656 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand); 657 setOperationAction(ISD::FGETSIGN, MVT::f64, Expand); 658 setOperationAction(ISD::FNEG, MVT::f64, Expand); 659 setOperationAction(ISD::FABS, MVT::f64, Expand); 660 setOperationAction(ISD::FSQRT, MVT::f64, Expand); 661 setOperationAction(ISD::FSIN, MVT::f64, Expand); 662 setOperationAction(ISD::FCOS, MVT::f64, Expand); 663 setOperationAction(ISD::FPOWI, MVT::f64, Expand); 664 setOperationAction(ISD::FPOW, MVT::f64, Expand); 665 setOperationAction(ISD::FLOG, MVT::f64, Expand); 666 setOperationAction(ISD::FLOG2, MVT::f64, Expand); 667 setOperationAction(ISD::FLOG10, MVT::f64, Expand); 668 setOperationAction(ISD::FEXP, MVT::f64, Expand); 669 setOperationAction(ISD::FEXP2, MVT::f64, Expand); 670 setOperationAction(ISD::FCEIL, MVT::f64, Expand); 671 setOperationAction(ISD::FTRUNC, MVT::f64, Expand); 672 setOperationAction(ISD::FRINT, MVT::f64, Expand); 673 setOperationAction(ISD::FNEARBYINT, MVT::f64, Expand); 674 setOperationAction(ISD::FFLOOR, MVT::f64, Expand); 675 setOperationAction(ISD::SINT_TO_FP, MVT::i32, Custom); 676 setOperationAction(ISD::UINT_TO_FP, MVT::i32, Custom); 677 setOperationAction(ISD::FP_TO_SINT, MVT::i32, Custom); 678 setOperationAction(ISD::FP_TO_UINT, MVT::i32, Custom); 679 setOperationAction(ISD::FP_TO_SINT, MVT::f64, Custom); 680 setOperationAction(ISD::FP_TO_UINT, MVT::f64, Custom); 681 setOperationAction(ISD::FP_ROUND, MVT::f32, Custom); 682 setOperationAction(ISD::FP_EXTEND, MVT::f64, Custom); 683 } 684 685 computeRegisterProperties(Subtarget->getRegisterInfo()); 686 687 // ARM does not have floating-point extending loads. 688 for (MVT VT : MVT::fp_valuetypes()) { 689 setLoadExtAction(ISD::EXTLOAD, VT, MVT::f32, Expand); 690 setLoadExtAction(ISD::EXTLOAD, VT, MVT::f16, Expand); 691 } 692 693 // ... or truncating stores 694 setTruncStoreAction(MVT::f64, MVT::f32, Expand); 695 setTruncStoreAction(MVT::f32, MVT::f16, Expand); 696 setTruncStoreAction(MVT::f64, MVT::f16, Expand); 697 698 // ARM does not have i1 sign extending load. 699 for (MVT VT : MVT::integer_valuetypes()) 700 setLoadExtAction(ISD::SEXTLOAD, VT, MVT::i1, Promote); 701 702 // ARM supports all 4 flavors of integer indexed load / store. 703 if (!Subtarget->isThumb1Only()) { 704 for (unsigned im = (unsigned)ISD::PRE_INC; 705 im != (unsigned)ISD::LAST_INDEXED_MODE; ++im) { 706 setIndexedLoadAction(im, MVT::i1, Legal); 707 setIndexedLoadAction(im, MVT::i8, Legal); 708 setIndexedLoadAction(im, MVT::i16, Legal); 709 setIndexedLoadAction(im, MVT::i32, Legal); 710 setIndexedStoreAction(im, MVT::i1, Legal); 711 setIndexedStoreAction(im, MVT::i8, Legal); 712 setIndexedStoreAction(im, MVT::i16, Legal); 713 setIndexedStoreAction(im, MVT::i32, Legal); 714 } 715 } 716 717 setOperationAction(ISD::SADDO, MVT::i32, Custom); 718 setOperationAction(ISD::UADDO, MVT::i32, Custom); 719 setOperationAction(ISD::SSUBO, MVT::i32, Custom); 720 setOperationAction(ISD::USUBO, MVT::i32, Custom); 721 722 // i64 operation support. 723 setOperationAction(ISD::MUL, MVT::i64, Expand); 724 setOperationAction(ISD::MULHU, MVT::i32, Expand); 725 if (Subtarget->isThumb1Only()) { 726 setOperationAction(ISD::UMUL_LOHI, MVT::i32, Expand); 727 setOperationAction(ISD::SMUL_LOHI, MVT::i32, Expand); 728 } 729 if (Subtarget->isThumb1Only() || !Subtarget->hasV6Ops() 730 || (Subtarget->isThumb2() && !Subtarget->hasDSP())) 731 setOperationAction(ISD::MULHS, MVT::i32, Expand); 732 733 setOperationAction(ISD::SHL_PARTS, MVT::i32, Custom); 734 setOperationAction(ISD::SRA_PARTS, MVT::i32, Custom); 735 setOperationAction(ISD::SRL_PARTS, MVT::i32, Custom); 736 setOperationAction(ISD::SRL, MVT::i64, Custom); 737 setOperationAction(ISD::SRA, MVT::i64, Custom); 738 739 if (!Subtarget->isThumb1Only()) { 740 // FIXME: We should do this for Thumb1 as well. 741 setOperationAction(ISD::ADDC, MVT::i32, Custom); 742 setOperationAction(ISD::ADDE, MVT::i32, Custom); 743 setOperationAction(ISD::SUBC, MVT::i32, Custom); 744 setOperationAction(ISD::SUBE, MVT::i32, Custom); 745 } 746 747 if (!Subtarget->isThumb1Only() && Subtarget->hasV6T2Ops()) 748 setOperationAction(ISD::BITREVERSE, MVT::i32, Legal); 749 750 // ARM does not have ROTL. 751 setOperationAction(ISD::ROTL, MVT::i32, Expand); 752 for (MVT VT : MVT::vector_valuetypes()) { 753 setOperationAction(ISD::ROTL, VT, Expand); 754 setOperationAction(ISD::ROTR, VT, Expand); 755 } 756 setOperationAction(ISD::CTTZ, MVT::i32, Custom); 757 setOperationAction(ISD::CTPOP, MVT::i32, Expand); 758 if (!Subtarget->hasV5TOps() || Subtarget->isThumb1Only()) 759 setOperationAction(ISD::CTLZ, MVT::i32, Expand); 760 761 // These just redirect to CTTZ and CTLZ on ARM. 762 setOperationAction(ISD::CTTZ_ZERO_UNDEF , MVT::i32 , Expand); 763 setOperationAction(ISD::CTLZ_ZERO_UNDEF , MVT::i32 , Expand); 764 765 // @llvm.readcyclecounter requires the Performance Monitors extension. 766 // Default to the 0 expansion on unsupported platforms. 767 // FIXME: Technically there are older ARM CPUs that have 768 // implementation-specific ways of obtaining this information. 769 if (Subtarget->hasPerfMon()) 770 setOperationAction(ISD::READCYCLECOUNTER, MVT::i64, Custom); 771 772 // Only ARMv6 has BSWAP. 773 if (!Subtarget->hasV6Ops()) 774 setOperationAction(ISD::BSWAP, MVT::i32, Expand); 775 776 bool hasDivide = Subtarget->isThumb() ? Subtarget->hasDivide() 777 : Subtarget->hasDivideInARMMode(); 778 if (!hasDivide) { 779 // These are expanded into libcalls if the cpu doesn't have HW divider. 780 setOperationAction(ISD::SDIV, MVT::i32, LibCall); 781 setOperationAction(ISD::UDIV, MVT::i32, LibCall); 782 } 783 784 setOperationAction(ISD::SREM, MVT::i32, Expand); 785 setOperationAction(ISD::UREM, MVT::i32, Expand); 786 // Register based DivRem for AEABI (RTABI 4.2) 787 if (Subtarget->isTargetAEABI() || Subtarget->isTargetAndroid() || 788 Subtarget->isTargetGNUAEABI()) { 789 setOperationAction(ISD::SREM, MVT::i64, Custom); 790 setOperationAction(ISD::UREM, MVT::i64, Custom); 791 792 setLibcallName(RTLIB::SDIVREM_I8, "__aeabi_idivmod"); 793 setLibcallName(RTLIB::SDIVREM_I16, "__aeabi_idivmod"); 794 setLibcallName(RTLIB::SDIVREM_I32, "__aeabi_idivmod"); 795 setLibcallName(RTLIB::SDIVREM_I64, "__aeabi_ldivmod"); 796 setLibcallName(RTLIB::UDIVREM_I8, "__aeabi_uidivmod"); 797 setLibcallName(RTLIB::UDIVREM_I16, "__aeabi_uidivmod"); 798 setLibcallName(RTLIB::UDIVREM_I32, "__aeabi_uidivmod"); 799 setLibcallName(RTLIB::UDIVREM_I64, "__aeabi_uldivmod"); 800 801 setLibcallCallingConv(RTLIB::SDIVREM_I8, CallingConv::ARM_AAPCS); 802 setLibcallCallingConv(RTLIB::SDIVREM_I16, CallingConv::ARM_AAPCS); 803 setLibcallCallingConv(RTLIB::SDIVREM_I32, CallingConv::ARM_AAPCS); 804 setLibcallCallingConv(RTLIB::SDIVREM_I64, CallingConv::ARM_AAPCS); 805 setLibcallCallingConv(RTLIB::UDIVREM_I8, CallingConv::ARM_AAPCS); 806 setLibcallCallingConv(RTLIB::UDIVREM_I16, CallingConv::ARM_AAPCS); 807 setLibcallCallingConv(RTLIB::UDIVREM_I32, CallingConv::ARM_AAPCS); 808 setLibcallCallingConv(RTLIB::UDIVREM_I64, CallingConv::ARM_AAPCS); 809 810 setOperationAction(ISD::SDIVREM, MVT::i32, Custom); 811 setOperationAction(ISD::UDIVREM, MVT::i32, Custom); 812 } else { 813 setOperationAction(ISD::SDIVREM, MVT::i32, Expand); 814 setOperationAction(ISD::UDIVREM, MVT::i32, Expand); 815 } 816 817 setOperationAction(ISD::GlobalAddress, MVT::i32, Custom); 818 setOperationAction(ISD::ConstantPool, MVT::i32, Custom); 819 setOperationAction(ISD::GlobalTLSAddress, MVT::i32, Custom); 820 setOperationAction(ISD::BlockAddress, MVT::i32, Custom); 821 822 setOperationAction(ISD::TRAP, MVT::Other, Legal); 823 824 // Use the default implementation. 825 setOperationAction(ISD::VASTART, MVT::Other, Custom); 826 setOperationAction(ISD::VAARG, MVT::Other, Expand); 827 setOperationAction(ISD::VACOPY, MVT::Other, Expand); 828 setOperationAction(ISD::VAEND, MVT::Other, Expand); 829 setOperationAction(ISD::STACKSAVE, MVT::Other, Expand); 830 setOperationAction(ISD::STACKRESTORE, MVT::Other, Expand); 831 832 if (Subtarget->getTargetTriple().isWindowsItaniumEnvironment()) 833 setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i32, Custom); 834 else 835 setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i32, Expand); 836 837 // ARMv6 Thumb1 (except for CPUs that support dmb / dsb) and earlier use 838 // the default expansion. If we are targeting a single threaded system, 839 // then set them all for expand so we can lower them later into their 840 // non-atomic form. 841 if (TM.Options.ThreadModel == ThreadModel::Single) 842 setOperationAction(ISD::ATOMIC_FENCE, MVT::Other, Expand); 843 else if (Subtarget->hasAnyDataBarrier() && (!Subtarget->isThumb() || 844 Subtarget->hasV8MBaselineOps())) { 845 // ATOMIC_FENCE needs custom lowering; the others should have been expanded 846 // to ldrex/strex loops already. 847 setOperationAction(ISD::ATOMIC_FENCE, MVT::Other, Custom); 848 849 // On v8, we have particularly efficient implementations of atomic fences 850 // if they can be combined with nearby atomic loads and stores. 851 if (!Subtarget->hasV8Ops()) { 852 // Automatically insert fences (dmb ish) around ATOMIC_SWAP etc. 853 setInsertFencesForAtomic(true); 854 } 855 } else { 856 // If there's anything we can use as a barrier, go through custom lowering 857 // for ATOMIC_FENCE. 858 setOperationAction(ISD::ATOMIC_FENCE, MVT::Other, 859 Subtarget->hasAnyDataBarrier() ? Custom : Expand); 860 861 // Set them all for expansion, which will force libcalls. 862 setOperationAction(ISD::ATOMIC_CMP_SWAP, MVT::i32, Expand); 863 setOperationAction(ISD::ATOMIC_SWAP, MVT::i32, Expand); 864 setOperationAction(ISD::ATOMIC_LOAD_ADD, MVT::i32, Expand); 865 setOperationAction(ISD::ATOMIC_LOAD_SUB, MVT::i32, Expand); 866 setOperationAction(ISD::ATOMIC_LOAD_AND, MVT::i32, Expand); 867 setOperationAction(ISD::ATOMIC_LOAD_OR, MVT::i32, Expand); 868 setOperationAction(ISD::ATOMIC_LOAD_XOR, MVT::i32, Expand); 869 setOperationAction(ISD::ATOMIC_LOAD_NAND, MVT::i32, Expand); 870 setOperationAction(ISD::ATOMIC_LOAD_MIN, MVT::i32, Expand); 871 setOperationAction(ISD::ATOMIC_LOAD_MAX, MVT::i32, Expand); 872 setOperationAction(ISD::ATOMIC_LOAD_UMIN, MVT::i32, Expand); 873 setOperationAction(ISD::ATOMIC_LOAD_UMAX, MVT::i32, Expand); 874 // Mark ATOMIC_LOAD and ATOMIC_STORE custom so we can handle the 875 // Unordered/Monotonic case. 876 setOperationAction(ISD::ATOMIC_LOAD, MVT::i32, Custom); 877 setOperationAction(ISD::ATOMIC_STORE, MVT::i32, Custom); 878 } 879 880 setOperationAction(ISD::PREFETCH, MVT::Other, Custom); 881 882 // Requires SXTB/SXTH, available on v6 and up in both ARM and Thumb modes. 883 if (!Subtarget->hasV6Ops()) { 884 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i16, Expand); 885 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i8, Expand); 886 } 887 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1, Expand); 888 889 if (!Subtarget->useSoftFloat() && Subtarget->hasVFP2() && 890 !Subtarget->isThumb1Only()) { 891 // Turn f64->i64 into VMOVRRD, i64 -> f64 to VMOVDRR 892 // iff target supports vfp2. 893 setOperationAction(ISD::BITCAST, MVT::i64, Custom); 894 setOperationAction(ISD::FLT_ROUNDS_, MVT::i32, Custom); 895 } 896 897 // We want to custom lower some of our intrinsics. 898 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom); 899 setOperationAction(ISD::EH_SJLJ_SETJMP, MVT::i32, Custom); 900 setOperationAction(ISD::EH_SJLJ_LONGJMP, MVT::Other, Custom); 901 setOperationAction(ISD::EH_SJLJ_SETUP_DISPATCH, MVT::Other, Custom); 902 if (Subtarget->useSjLjEH()) 903 setLibcallName(RTLIB::UNWIND_RESUME, "_Unwind_SjLj_Resume"); 904 905 setOperationAction(ISD::SETCC, MVT::i32, Expand); 906 setOperationAction(ISD::SETCC, MVT::f32, Expand); 907 setOperationAction(ISD::SETCC, MVT::f64, Expand); 908 setOperationAction(ISD::SELECT, MVT::i32, Custom); 909 setOperationAction(ISD::SELECT, MVT::f32, Custom); 910 setOperationAction(ISD::SELECT, MVT::f64, Custom); 911 setOperationAction(ISD::SELECT_CC, MVT::i32, Custom); 912 setOperationAction(ISD::SELECT_CC, MVT::f32, Custom); 913 setOperationAction(ISD::SELECT_CC, MVT::f64, Custom); 914 915 setOperationAction(ISD::BRCOND, MVT::Other, Expand); 916 setOperationAction(ISD::BR_CC, MVT::i32, Custom); 917 setOperationAction(ISD::BR_CC, MVT::f32, Custom); 918 setOperationAction(ISD::BR_CC, MVT::f64, Custom); 919 setOperationAction(ISD::BR_JT, MVT::Other, Custom); 920 921 // We don't support sin/cos/fmod/copysign/pow 922 setOperationAction(ISD::FSIN, MVT::f64, Expand); 923 setOperationAction(ISD::FSIN, MVT::f32, Expand); 924 setOperationAction(ISD::FCOS, MVT::f32, Expand); 925 setOperationAction(ISD::FCOS, MVT::f64, Expand); 926 setOperationAction(ISD::FSINCOS, MVT::f64, Expand); 927 setOperationAction(ISD::FSINCOS, MVT::f32, Expand); 928 setOperationAction(ISD::FREM, MVT::f64, Expand); 929 setOperationAction(ISD::FREM, MVT::f32, Expand); 930 if (!Subtarget->useSoftFloat() && Subtarget->hasVFP2() && 931 !Subtarget->isThumb1Only()) { 932 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Custom); 933 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom); 934 } 935 setOperationAction(ISD::FPOW, MVT::f64, Expand); 936 setOperationAction(ISD::FPOW, MVT::f32, Expand); 937 938 if (!Subtarget->hasVFP4()) { 939 setOperationAction(ISD::FMA, MVT::f64, Expand); 940 setOperationAction(ISD::FMA, MVT::f32, Expand); 941 } 942 943 // Various VFP goodness 944 if (!Subtarget->useSoftFloat() && !Subtarget->isThumb1Only()) { 945 // FP-ARMv8 adds f64 <-> f16 conversion. Before that it should be expanded. 946 if (!Subtarget->hasFPARMv8() || Subtarget->isFPOnlySP()) { 947 setOperationAction(ISD::FP16_TO_FP, MVT::f64, Expand); 948 setOperationAction(ISD::FP_TO_FP16, MVT::f64, Expand); 949 } 950 951 // fp16 is a special v7 extension that adds f16 <-> f32 conversions. 952 if (!Subtarget->hasFP16()) { 953 setOperationAction(ISD::FP16_TO_FP, MVT::f32, Expand); 954 setOperationAction(ISD::FP_TO_FP16, MVT::f32, Expand); 955 } 956 } 957 958 // Combine sin / cos into one node or libcall if possible. 959 if (Subtarget->hasSinCos()) { 960 setLibcallName(RTLIB::SINCOS_F32, "sincosf"); 961 setLibcallName(RTLIB::SINCOS_F64, "sincos"); 962 if (Subtarget->isTargetWatchABI()) { 963 setLibcallCallingConv(RTLIB::SINCOS_F32, CallingConv::ARM_AAPCS_VFP); 964 setLibcallCallingConv(RTLIB::SINCOS_F64, CallingConv::ARM_AAPCS_VFP); 965 } 966 if (Subtarget->isTargetIOS() || Subtarget->isTargetWatchOS()) { 967 // For iOS, we don't want to the normal expansion of a libcall to 968 // sincos. We want to issue a libcall to __sincos_stret. 969 setOperationAction(ISD::FSINCOS, MVT::f64, Custom); 970 setOperationAction(ISD::FSINCOS, MVT::f32, Custom); 971 } 972 } 973 974 // FP-ARMv8 implements a lot of rounding-like FP operations. 975 if (Subtarget->hasFPARMv8()) { 976 setOperationAction(ISD::FFLOOR, MVT::f32, Legal); 977 setOperationAction(ISD::FCEIL, MVT::f32, Legal); 978 setOperationAction(ISD::FROUND, MVT::f32, Legal); 979 setOperationAction(ISD::FTRUNC, MVT::f32, Legal); 980 setOperationAction(ISD::FNEARBYINT, MVT::f32, Legal); 981 setOperationAction(ISD::FRINT, MVT::f32, Legal); 982 setOperationAction(ISD::FMINNUM, MVT::f32, Legal); 983 setOperationAction(ISD::FMAXNUM, MVT::f32, Legal); 984 setOperationAction(ISD::FMINNUM, MVT::v2f32, Legal); 985 setOperationAction(ISD::FMAXNUM, MVT::v2f32, Legal); 986 setOperationAction(ISD::FMINNUM, MVT::v4f32, Legal); 987 setOperationAction(ISD::FMAXNUM, MVT::v4f32, Legal); 988 989 if (!Subtarget->isFPOnlySP()) { 990 setOperationAction(ISD::FFLOOR, MVT::f64, Legal); 991 setOperationAction(ISD::FCEIL, MVT::f64, Legal); 992 setOperationAction(ISD::FROUND, MVT::f64, Legal); 993 setOperationAction(ISD::FTRUNC, MVT::f64, Legal); 994 setOperationAction(ISD::FNEARBYINT, MVT::f64, Legal); 995 setOperationAction(ISD::FRINT, MVT::f64, Legal); 996 setOperationAction(ISD::FMINNUM, MVT::f64, Legal); 997 setOperationAction(ISD::FMAXNUM, MVT::f64, Legal); 998 } 999 } 1000 1001 if (Subtarget->hasNEON()) { 1002 // vmin and vmax aren't available in a scalar form, so we use 1003 // a NEON instruction with an undef lane instead. 1004 setOperationAction(ISD::FMINNAN, MVT::f32, Legal); 1005 setOperationAction(ISD::FMAXNAN, MVT::f32, Legal); 1006 setOperationAction(ISD::FMINNAN, MVT::v2f32, Legal); 1007 setOperationAction(ISD::FMAXNAN, MVT::v2f32, Legal); 1008 setOperationAction(ISD::FMINNAN, MVT::v4f32, Legal); 1009 setOperationAction(ISD::FMAXNAN, MVT::v4f32, Legal); 1010 } 1011 1012 // We have target-specific dag combine patterns for the following nodes: 1013 // ARMISD::VMOVRRD - No need to call setTargetDAGCombine 1014 setTargetDAGCombine(ISD::ADD); 1015 setTargetDAGCombine(ISD::SUB); 1016 setTargetDAGCombine(ISD::MUL); 1017 setTargetDAGCombine(ISD::AND); 1018 setTargetDAGCombine(ISD::OR); 1019 setTargetDAGCombine(ISD::XOR); 1020 1021 if (Subtarget->hasV6Ops()) 1022 setTargetDAGCombine(ISD::SRL); 1023 1024 setStackPointerRegisterToSaveRestore(ARM::SP); 1025 1026 if (Subtarget->useSoftFloat() || Subtarget->isThumb1Only() || 1027 !Subtarget->hasVFP2()) 1028 setSchedulingPreference(Sched::RegPressure); 1029 else 1030 setSchedulingPreference(Sched::Hybrid); 1031 1032 //// temporary - rewrite interface to use type 1033 MaxStoresPerMemset = 8; 1034 MaxStoresPerMemsetOptSize = 4; 1035 MaxStoresPerMemcpy = 4; // For @llvm.memcpy -> sequence of stores 1036 MaxStoresPerMemcpyOptSize = 2; 1037 MaxStoresPerMemmove = 4; // For @llvm.memmove -> sequence of stores 1038 MaxStoresPerMemmoveOptSize = 2; 1039 1040 // On ARM arguments smaller than 4 bytes are extended, so all arguments 1041 // are at least 4 bytes aligned. 1042 setMinStackArgumentAlignment(4); 1043 1044 // Prefer likely predicted branches to selects on out-of-order cores. 1045 PredictableSelectIsExpensive = Subtarget->getSchedModel().isOutOfOrder(); 1046 1047 setMinFunctionAlignment(Subtarget->isThumb() ? 1 : 2); 1048 } 1049 1050 bool ARMTargetLowering::useSoftFloat() const { 1051 return Subtarget->useSoftFloat(); 1052 } 1053 1054 // FIXME: It might make sense to define the representative register class as the 1055 // nearest super-register that has a non-null superset. For example, DPR_VFP2 is 1056 // a super-register of SPR, and DPR is a superset if DPR_VFP2. Consequently, 1057 // SPR's representative would be DPR_VFP2. This should work well if register 1058 // pressure tracking were modified such that a register use would increment the 1059 // pressure of the register class's representative and all of it's super 1060 // classes' representatives transitively. We have not implemented this because 1061 // of the difficulty prior to coalescing of modeling operand register classes 1062 // due to the common occurrence of cross class copies and subregister insertions 1063 // and extractions. 1064 std::pair<const TargetRegisterClass *, uint8_t> 1065 ARMTargetLowering::findRepresentativeClass(const TargetRegisterInfo *TRI, 1066 MVT VT) const { 1067 const TargetRegisterClass *RRC = nullptr; 1068 uint8_t Cost = 1; 1069 switch (VT.SimpleTy) { 1070 default: 1071 return TargetLowering::findRepresentativeClass(TRI, VT); 1072 // Use DPR as representative register class for all floating point 1073 // and vector types. Since there are 32 SPR registers and 32 DPR registers so 1074 // the cost is 1 for both f32 and f64. 1075 case MVT::f32: case MVT::f64: case MVT::v8i8: case MVT::v4i16: 1076 case MVT::v2i32: case MVT::v1i64: case MVT::v2f32: 1077 RRC = &ARM::DPRRegClass; 1078 // When NEON is used for SP, only half of the register file is available 1079 // because operations that define both SP and DP results will be constrained 1080 // to the VFP2 class (D0-D15). We currently model this constraint prior to 1081 // coalescing by double-counting the SP regs. See the FIXME above. 1082 if (Subtarget->useNEONForSinglePrecisionFP()) 1083 Cost = 2; 1084 break; 1085 case MVT::v16i8: case MVT::v8i16: case MVT::v4i32: case MVT::v2i64: 1086 case MVT::v4f32: case MVT::v2f64: 1087 RRC = &ARM::DPRRegClass; 1088 Cost = 2; 1089 break; 1090 case MVT::v4i64: 1091 RRC = &ARM::DPRRegClass; 1092 Cost = 4; 1093 break; 1094 case MVT::v8i64: 1095 RRC = &ARM::DPRRegClass; 1096 Cost = 8; 1097 break; 1098 } 1099 return std::make_pair(RRC, Cost); 1100 } 1101 1102 const char *ARMTargetLowering::getTargetNodeName(unsigned Opcode) const { 1103 switch ((ARMISD::NodeType)Opcode) { 1104 case ARMISD::FIRST_NUMBER: break; 1105 case ARMISD::Wrapper: return "ARMISD::Wrapper"; 1106 case ARMISD::WrapperPIC: return "ARMISD::WrapperPIC"; 1107 case ARMISD::WrapperJT: return "ARMISD::WrapperJT"; 1108 case ARMISD::COPY_STRUCT_BYVAL: return "ARMISD::COPY_STRUCT_BYVAL"; 1109 case ARMISD::CALL: return "ARMISD::CALL"; 1110 case ARMISD::CALL_PRED: return "ARMISD::CALL_PRED"; 1111 case ARMISD::CALL_NOLINK: return "ARMISD::CALL_NOLINK"; 1112 case ARMISD::tCALL: return "ARMISD::tCALL"; 1113 case ARMISD::BRCOND: return "ARMISD::BRCOND"; 1114 case ARMISD::BR_JT: return "ARMISD::BR_JT"; 1115 case ARMISD::BR2_JT: return "ARMISD::BR2_JT"; 1116 case ARMISD::RET_FLAG: return "ARMISD::RET_FLAG"; 1117 case ARMISD::INTRET_FLAG: return "ARMISD::INTRET_FLAG"; 1118 case ARMISD::PIC_ADD: return "ARMISD::PIC_ADD"; 1119 case ARMISD::CMP: return "ARMISD::CMP"; 1120 case ARMISD::CMN: return "ARMISD::CMN"; 1121 case ARMISD::CMPZ: return "ARMISD::CMPZ"; 1122 case ARMISD::CMPFP: return "ARMISD::CMPFP"; 1123 case ARMISD::CMPFPw0: return "ARMISD::CMPFPw0"; 1124 case ARMISD::BCC_i64: return "ARMISD::BCC_i64"; 1125 case ARMISD::FMSTAT: return "ARMISD::FMSTAT"; 1126 1127 case ARMISD::CMOV: return "ARMISD::CMOV"; 1128 1129 case ARMISD::SRL_FLAG: return "ARMISD::SRL_FLAG"; 1130 case ARMISD::SRA_FLAG: return "ARMISD::SRA_FLAG"; 1131 case ARMISD::RRX: return "ARMISD::RRX"; 1132 1133 case ARMISD::ADDC: return "ARMISD::ADDC"; 1134 case ARMISD::ADDE: return "ARMISD::ADDE"; 1135 case ARMISD::SUBC: return "ARMISD::SUBC"; 1136 case ARMISD::SUBE: return "ARMISD::SUBE"; 1137 1138 case ARMISD::VMOVRRD: return "ARMISD::VMOVRRD"; 1139 case ARMISD::VMOVDRR: return "ARMISD::VMOVDRR"; 1140 1141 case ARMISD::EH_SJLJ_SETJMP: return "ARMISD::EH_SJLJ_SETJMP"; 1142 case ARMISD::EH_SJLJ_LONGJMP: return "ARMISD::EH_SJLJ_LONGJMP"; 1143 case ARMISD::EH_SJLJ_SETUP_DISPATCH: return "ARMISD::EH_SJLJ_SETUP_DISPATCH"; 1144 1145 case ARMISD::TC_RETURN: return "ARMISD::TC_RETURN"; 1146 1147 case ARMISD::THREAD_POINTER:return "ARMISD::THREAD_POINTER"; 1148 1149 case ARMISD::DYN_ALLOC: return "ARMISD::DYN_ALLOC"; 1150 1151 case ARMISD::MEMBARRIER_MCR: return "ARMISD::MEMBARRIER_MCR"; 1152 1153 case ARMISD::PRELOAD: return "ARMISD::PRELOAD"; 1154 1155 case ARMISD::WIN__CHKSTK: return "ARMISD:::WIN__CHKSTK"; 1156 case ARMISD::WIN__DBZCHK: return "ARMISD::WIN__DBZCHK"; 1157 1158 case ARMISD::VCEQ: return "ARMISD::VCEQ"; 1159 case ARMISD::VCEQZ: return "ARMISD::VCEQZ"; 1160 case ARMISD::VCGE: return "ARMISD::VCGE"; 1161 case ARMISD::VCGEZ: return "ARMISD::VCGEZ"; 1162 case ARMISD::VCLEZ: return "ARMISD::VCLEZ"; 1163 case ARMISD::VCGEU: return "ARMISD::VCGEU"; 1164 case ARMISD::VCGT: return "ARMISD::VCGT"; 1165 case ARMISD::VCGTZ: return "ARMISD::VCGTZ"; 1166 case ARMISD::VCLTZ: return "ARMISD::VCLTZ"; 1167 case ARMISD::VCGTU: return "ARMISD::VCGTU"; 1168 case ARMISD::VTST: return "ARMISD::VTST"; 1169 1170 case ARMISD::VSHL: return "ARMISD::VSHL"; 1171 case ARMISD::VSHRs: return "ARMISD::VSHRs"; 1172 case ARMISD::VSHRu: return "ARMISD::VSHRu"; 1173 case ARMISD::VRSHRs: return "ARMISD::VRSHRs"; 1174 case ARMISD::VRSHRu: return "ARMISD::VRSHRu"; 1175 case ARMISD::VRSHRN: return "ARMISD::VRSHRN"; 1176 case ARMISD::VQSHLs: return "ARMISD::VQSHLs"; 1177 case ARMISD::VQSHLu: return "ARMISD::VQSHLu"; 1178 case ARMISD::VQSHLsu: return "ARMISD::VQSHLsu"; 1179 case ARMISD::VQSHRNs: return "ARMISD::VQSHRNs"; 1180 case ARMISD::VQSHRNu: return "ARMISD::VQSHRNu"; 1181 case ARMISD::VQSHRNsu: return "ARMISD::VQSHRNsu"; 1182 case ARMISD::VQRSHRNs: return "ARMISD::VQRSHRNs"; 1183 case ARMISD::VQRSHRNu: return "ARMISD::VQRSHRNu"; 1184 case ARMISD::VQRSHRNsu: return "ARMISD::VQRSHRNsu"; 1185 case ARMISD::VSLI: return "ARMISD::VSLI"; 1186 case ARMISD::VSRI: return "ARMISD::VSRI"; 1187 case ARMISD::VGETLANEu: return "ARMISD::VGETLANEu"; 1188 case ARMISD::VGETLANEs: return "ARMISD::VGETLANEs"; 1189 case ARMISD::VMOVIMM: return "ARMISD::VMOVIMM"; 1190 case ARMISD::VMVNIMM: return "ARMISD::VMVNIMM"; 1191 case ARMISD::VMOVFPIMM: return "ARMISD::VMOVFPIMM"; 1192 case ARMISD::VDUP: return "ARMISD::VDUP"; 1193 case ARMISD::VDUPLANE: return "ARMISD::VDUPLANE"; 1194 case ARMISD::VEXT: return "ARMISD::VEXT"; 1195 case ARMISD::VREV64: return "ARMISD::VREV64"; 1196 case ARMISD::VREV32: return "ARMISD::VREV32"; 1197 case ARMISD::VREV16: return "ARMISD::VREV16"; 1198 case ARMISD::VZIP: return "ARMISD::VZIP"; 1199 case ARMISD::VUZP: return "ARMISD::VUZP"; 1200 case ARMISD::VTRN: return "ARMISD::VTRN"; 1201 case ARMISD::VTBL1: return "ARMISD::VTBL1"; 1202 case ARMISD::VTBL2: return "ARMISD::VTBL2"; 1203 case ARMISD::VMULLs: return "ARMISD::VMULLs"; 1204 case ARMISD::VMULLu: return "ARMISD::VMULLu"; 1205 case ARMISD::UMLAL: return "ARMISD::UMLAL"; 1206 case ARMISD::SMLAL: return "ARMISD::SMLAL"; 1207 case ARMISD::BUILD_VECTOR: return "ARMISD::BUILD_VECTOR"; 1208 case ARMISD::BFI: return "ARMISD::BFI"; 1209 case ARMISD::VORRIMM: return "ARMISD::VORRIMM"; 1210 case ARMISD::VBICIMM: return "ARMISD::VBICIMM"; 1211 case ARMISD::VBSL: return "ARMISD::VBSL"; 1212 case ARMISD::MEMCPY: return "ARMISD::MEMCPY"; 1213 case ARMISD::VLD2DUP: return "ARMISD::VLD2DUP"; 1214 case ARMISD::VLD3DUP: return "ARMISD::VLD3DUP"; 1215 case ARMISD::VLD4DUP: return "ARMISD::VLD4DUP"; 1216 case ARMISD::VLD1_UPD: return "ARMISD::VLD1_UPD"; 1217 case ARMISD::VLD2_UPD: return "ARMISD::VLD2_UPD"; 1218 case ARMISD::VLD3_UPD: return "ARMISD::VLD3_UPD"; 1219 case ARMISD::VLD4_UPD: return "ARMISD::VLD4_UPD"; 1220 case ARMISD::VLD2LN_UPD: return "ARMISD::VLD2LN_UPD"; 1221 case ARMISD::VLD3LN_UPD: return "ARMISD::VLD3LN_UPD"; 1222 case ARMISD::VLD4LN_UPD: return "ARMISD::VLD4LN_UPD"; 1223 case ARMISD::VLD2DUP_UPD: return "ARMISD::VLD2DUP_UPD"; 1224 case ARMISD::VLD3DUP_UPD: return "ARMISD::VLD3DUP_UPD"; 1225 case ARMISD::VLD4DUP_UPD: return "ARMISD::VLD4DUP_UPD"; 1226 case ARMISD::VST1_UPD: return "ARMISD::VST1_UPD"; 1227 case ARMISD::VST2_UPD: return "ARMISD::VST2_UPD"; 1228 case ARMISD::VST3_UPD: return "ARMISD::VST3_UPD"; 1229 case ARMISD::VST4_UPD: return "ARMISD::VST4_UPD"; 1230 case ARMISD::VST2LN_UPD: return "ARMISD::VST2LN_UPD"; 1231 case ARMISD::VST3LN_UPD: return "ARMISD::VST3LN_UPD"; 1232 case ARMISD::VST4LN_UPD: return "ARMISD::VST4LN_UPD"; 1233 } 1234 return nullptr; 1235 } 1236 1237 EVT ARMTargetLowering::getSetCCResultType(const DataLayout &DL, LLVMContext &, 1238 EVT VT) const { 1239 if (!VT.isVector()) 1240 return getPointerTy(DL); 1241 return VT.changeVectorElementTypeToInteger(); 1242 } 1243 1244 /// getRegClassFor - Return the register class that should be used for the 1245 /// specified value type. 1246 const TargetRegisterClass *ARMTargetLowering::getRegClassFor(MVT VT) const { 1247 // Map v4i64 to QQ registers but do not make the type legal. Similarly map 1248 // v8i64 to QQQQ registers. v4i64 and v8i64 are only used for REG_SEQUENCE to 1249 // load / store 4 to 8 consecutive D registers. 1250 if (Subtarget->hasNEON()) { 1251 if (VT == MVT::v4i64) 1252 return &ARM::QQPRRegClass; 1253 if (VT == MVT::v8i64) 1254 return &ARM::QQQQPRRegClass; 1255 } 1256 return TargetLowering::getRegClassFor(VT); 1257 } 1258 1259 // memcpy, and other memory intrinsics, typically tries to use LDM/STM if the 1260 // source/dest is aligned and the copy size is large enough. We therefore want 1261 // to align such objects passed to memory intrinsics. 1262 bool ARMTargetLowering::shouldAlignPointerArgs(CallInst *CI, unsigned &MinSize, 1263 unsigned &PrefAlign) const { 1264 if (!isa<MemIntrinsic>(CI)) 1265 return false; 1266 MinSize = 8; 1267 // On ARM11 onwards (excluding M class) 8-byte aligned LDM is typically 1 1268 // cycle faster than 4-byte aligned LDM. 1269 PrefAlign = (Subtarget->hasV6Ops() && !Subtarget->isMClass() ? 8 : 4); 1270 return true; 1271 } 1272 1273 // Create a fast isel object. 1274 FastISel * 1275 ARMTargetLowering::createFastISel(FunctionLoweringInfo &funcInfo, 1276 const TargetLibraryInfo *libInfo) const { 1277 return ARM::createFastISel(funcInfo, libInfo); 1278 } 1279 1280 Sched::Preference ARMTargetLowering::getSchedulingPreference(SDNode *N) const { 1281 unsigned NumVals = N->getNumValues(); 1282 if (!NumVals) 1283 return Sched::RegPressure; 1284 1285 for (unsigned i = 0; i != NumVals; ++i) { 1286 EVT VT = N->getValueType(i); 1287 if (VT == MVT::Glue || VT == MVT::Other) 1288 continue; 1289 if (VT.isFloatingPoint() || VT.isVector()) 1290 return Sched::ILP; 1291 } 1292 1293 if (!N->isMachineOpcode()) 1294 return Sched::RegPressure; 1295 1296 // Load are scheduled for latency even if there instruction itinerary 1297 // is not available. 1298 const TargetInstrInfo *TII = Subtarget->getInstrInfo(); 1299 const MCInstrDesc &MCID = TII->get(N->getMachineOpcode()); 1300 1301 if (MCID.getNumDefs() == 0) 1302 return Sched::RegPressure; 1303 if (!Itins->isEmpty() && 1304 Itins->getOperandCycle(MCID.getSchedClass(), 0) > 2) 1305 return Sched::ILP; 1306 1307 return Sched::RegPressure; 1308 } 1309 1310 //===----------------------------------------------------------------------===// 1311 // Lowering Code 1312 //===----------------------------------------------------------------------===// 1313 1314 /// IntCCToARMCC - Convert a DAG integer condition code to an ARM CC 1315 static ARMCC::CondCodes IntCCToARMCC(ISD::CondCode CC) { 1316 switch (CC) { 1317 default: llvm_unreachable("Unknown condition code!"); 1318 case ISD::SETNE: return ARMCC::NE; 1319 case ISD::SETEQ: return ARMCC::EQ; 1320 case ISD::SETGT: return ARMCC::GT; 1321 case ISD::SETGE: return ARMCC::GE; 1322 case ISD::SETLT: return ARMCC::LT; 1323 case ISD::SETLE: return ARMCC::LE; 1324 case ISD::SETUGT: return ARMCC::HI; 1325 case ISD::SETUGE: return ARMCC::HS; 1326 case ISD::SETULT: return ARMCC::LO; 1327 case ISD::SETULE: return ARMCC::LS; 1328 } 1329 } 1330 1331 /// FPCCToARMCC - Convert a DAG fp condition code to an ARM CC. 1332 static void FPCCToARMCC(ISD::CondCode CC, ARMCC::CondCodes &CondCode, 1333 ARMCC::CondCodes &CondCode2) { 1334 CondCode2 = ARMCC::AL; 1335 switch (CC) { 1336 default: llvm_unreachable("Unknown FP condition!"); 1337 case ISD::SETEQ: 1338 case ISD::SETOEQ: CondCode = ARMCC::EQ; break; 1339 case ISD::SETGT: 1340 case ISD::SETOGT: CondCode = ARMCC::GT; break; 1341 case ISD::SETGE: 1342 case ISD::SETOGE: CondCode = ARMCC::GE; break; 1343 case ISD::SETOLT: CondCode = ARMCC::MI; break; 1344 case ISD::SETOLE: CondCode = ARMCC::LS; break; 1345 case ISD::SETONE: CondCode = ARMCC::MI; CondCode2 = ARMCC::GT; break; 1346 case ISD::SETO: CondCode = ARMCC::VC; break; 1347 case ISD::SETUO: CondCode = ARMCC::VS; break; 1348 case ISD::SETUEQ: CondCode = ARMCC::EQ; CondCode2 = ARMCC::VS; break; 1349 case ISD::SETUGT: CondCode = ARMCC::HI; break; 1350 case ISD::SETUGE: CondCode = ARMCC::PL; break; 1351 case ISD::SETLT: 1352 case ISD::SETULT: CondCode = ARMCC::LT; break; 1353 case ISD::SETLE: 1354 case ISD::SETULE: CondCode = ARMCC::LE; break; 1355 case ISD::SETNE: 1356 case ISD::SETUNE: CondCode = ARMCC::NE; break; 1357 } 1358 } 1359 1360 //===----------------------------------------------------------------------===// 1361 // Calling Convention Implementation 1362 //===----------------------------------------------------------------------===// 1363 1364 #include "ARMGenCallingConv.inc" 1365 1366 /// getEffectiveCallingConv - Get the effective calling convention, taking into 1367 /// account presence of floating point hardware and calling convention 1368 /// limitations, such as support for variadic functions. 1369 CallingConv::ID 1370 ARMTargetLowering::getEffectiveCallingConv(CallingConv::ID CC, 1371 bool isVarArg) const { 1372 switch (CC) { 1373 default: 1374 llvm_unreachable("Unsupported calling convention"); 1375 case CallingConv::ARM_AAPCS: 1376 case CallingConv::ARM_APCS: 1377 case CallingConv::GHC: 1378 return CC; 1379 case CallingConv::ARM_AAPCS_VFP: 1380 return isVarArg ? CallingConv::ARM_AAPCS : CallingConv::ARM_AAPCS_VFP; 1381 case CallingConv::C: 1382 if (!Subtarget->isAAPCS_ABI()) 1383 return CallingConv::ARM_APCS; 1384 else if (Subtarget->hasVFP2() && !Subtarget->isThumb1Only() && 1385 getTargetMachine().Options.FloatABIType == FloatABI::Hard && 1386 !isVarArg) 1387 return CallingConv::ARM_AAPCS_VFP; 1388 else 1389 return CallingConv::ARM_AAPCS; 1390 case CallingConv::Fast: 1391 case CallingConv::CXX_FAST_TLS: 1392 if (!Subtarget->isAAPCS_ABI()) { 1393 if (Subtarget->hasVFP2() && !Subtarget->isThumb1Only() && !isVarArg) 1394 return CallingConv::Fast; 1395 return CallingConv::ARM_APCS; 1396 } else if (Subtarget->hasVFP2() && !Subtarget->isThumb1Only() && !isVarArg) 1397 return CallingConv::ARM_AAPCS_VFP; 1398 else 1399 return CallingConv::ARM_AAPCS; 1400 } 1401 } 1402 1403 /// CCAssignFnForNode - Selects the correct CCAssignFn for the given 1404 /// CallingConvention. 1405 CCAssignFn *ARMTargetLowering::CCAssignFnForNode(CallingConv::ID CC, 1406 bool Return, 1407 bool isVarArg) const { 1408 switch (getEffectiveCallingConv(CC, isVarArg)) { 1409 default: 1410 llvm_unreachable("Unsupported calling convention"); 1411 case CallingConv::ARM_APCS: 1412 return (Return ? RetCC_ARM_APCS : CC_ARM_APCS); 1413 case CallingConv::ARM_AAPCS: 1414 return (Return ? RetCC_ARM_AAPCS : CC_ARM_AAPCS); 1415 case CallingConv::ARM_AAPCS_VFP: 1416 return (Return ? RetCC_ARM_AAPCS_VFP : CC_ARM_AAPCS_VFP); 1417 case CallingConv::Fast: 1418 return (Return ? RetFastCC_ARM_APCS : FastCC_ARM_APCS); 1419 case CallingConv::GHC: 1420 return (Return ? RetCC_ARM_APCS : CC_ARM_APCS_GHC); 1421 } 1422 } 1423 1424 /// LowerCallResult - Lower the result values of a call into the 1425 /// appropriate copies out of appropriate physical registers. 1426 SDValue 1427 ARMTargetLowering::LowerCallResult(SDValue Chain, SDValue InFlag, 1428 CallingConv::ID CallConv, bool isVarArg, 1429 const SmallVectorImpl<ISD::InputArg> &Ins, 1430 SDLoc dl, SelectionDAG &DAG, 1431 SmallVectorImpl<SDValue> &InVals, 1432 bool isThisReturn, SDValue ThisVal) const { 1433 1434 // Assign locations to each value returned by this call. 1435 SmallVector<CCValAssign, 16> RVLocs; 1436 ARMCCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs, 1437 *DAG.getContext(), Call); 1438 CCInfo.AnalyzeCallResult(Ins, 1439 CCAssignFnForNode(CallConv, /* Return*/ true, 1440 isVarArg)); 1441 1442 // Copy all of the result registers out of their specified physreg. 1443 for (unsigned i = 0; i != RVLocs.size(); ++i) { 1444 CCValAssign VA = RVLocs[i]; 1445 1446 // Pass 'this' value directly from the argument to return value, to avoid 1447 // reg unit interference 1448 if (i == 0 && isThisReturn) { 1449 assert(!VA.needsCustom() && VA.getLocVT() == MVT::i32 && 1450 "unexpected return calling convention register assignment"); 1451 InVals.push_back(ThisVal); 1452 continue; 1453 } 1454 1455 SDValue Val; 1456 if (VA.needsCustom()) { 1457 // Handle f64 or half of a v2f64. 1458 SDValue Lo = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32, 1459 InFlag); 1460 Chain = Lo.getValue(1); 1461 InFlag = Lo.getValue(2); 1462 VA = RVLocs[++i]; // skip ahead to next loc 1463 SDValue Hi = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32, 1464 InFlag); 1465 Chain = Hi.getValue(1); 1466 InFlag = Hi.getValue(2); 1467 if (!Subtarget->isLittle()) 1468 std::swap (Lo, Hi); 1469 Val = DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi); 1470 1471 if (VA.getLocVT() == MVT::v2f64) { 1472 SDValue Vec = DAG.getNode(ISD::UNDEF, dl, MVT::v2f64); 1473 Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Vec, Val, 1474 DAG.getConstant(0, dl, MVT::i32)); 1475 1476 VA = RVLocs[++i]; // skip ahead to next loc 1477 Lo = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32, InFlag); 1478 Chain = Lo.getValue(1); 1479 InFlag = Lo.getValue(2); 1480 VA = RVLocs[++i]; // skip ahead to next loc 1481 Hi = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32, InFlag); 1482 Chain = Hi.getValue(1); 1483 InFlag = Hi.getValue(2); 1484 if (!Subtarget->isLittle()) 1485 std::swap (Lo, Hi); 1486 Val = DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi); 1487 Val = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Vec, Val, 1488 DAG.getConstant(1, dl, MVT::i32)); 1489 } 1490 } else { 1491 Val = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), VA.getLocVT(), 1492 InFlag); 1493 Chain = Val.getValue(1); 1494 InFlag = Val.getValue(2); 1495 } 1496 1497 switch (VA.getLocInfo()) { 1498 default: llvm_unreachable("Unknown loc info!"); 1499 case CCValAssign::Full: break; 1500 case CCValAssign::BCvt: 1501 Val = DAG.getNode(ISD::BITCAST, dl, VA.getValVT(), Val); 1502 break; 1503 } 1504 1505 InVals.push_back(Val); 1506 } 1507 1508 return Chain; 1509 } 1510 1511 /// LowerMemOpCallTo - Store the argument to the stack. 1512 SDValue 1513 ARMTargetLowering::LowerMemOpCallTo(SDValue Chain, 1514 SDValue StackPtr, SDValue Arg, 1515 SDLoc dl, SelectionDAG &DAG, 1516 const CCValAssign &VA, 1517 ISD::ArgFlagsTy Flags) const { 1518 unsigned LocMemOffset = VA.getLocMemOffset(); 1519 SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset, dl); 1520 PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(DAG.getDataLayout()), 1521 StackPtr, PtrOff); 1522 return DAG.getStore( 1523 Chain, dl, Arg, PtrOff, 1524 MachinePointerInfo::getStack(DAG.getMachineFunction(), LocMemOffset), 1525 false, false, 0); 1526 } 1527 1528 void ARMTargetLowering::PassF64ArgInRegs(SDLoc dl, SelectionDAG &DAG, 1529 SDValue Chain, SDValue &Arg, 1530 RegsToPassVector &RegsToPass, 1531 CCValAssign &VA, CCValAssign &NextVA, 1532 SDValue &StackPtr, 1533 SmallVectorImpl<SDValue> &MemOpChains, 1534 ISD::ArgFlagsTy Flags) const { 1535 1536 SDValue fmrrd = DAG.getNode(ARMISD::VMOVRRD, dl, 1537 DAG.getVTList(MVT::i32, MVT::i32), Arg); 1538 unsigned id = Subtarget->isLittle() ? 0 : 1; 1539 RegsToPass.push_back(std::make_pair(VA.getLocReg(), fmrrd.getValue(id))); 1540 1541 if (NextVA.isRegLoc()) 1542 RegsToPass.push_back(std::make_pair(NextVA.getLocReg(), fmrrd.getValue(1-id))); 1543 else { 1544 assert(NextVA.isMemLoc()); 1545 if (!StackPtr.getNode()) 1546 StackPtr = DAG.getCopyFromReg(Chain, dl, ARM::SP, 1547 getPointerTy(DAG.getDataLayout())); 1548 1549 MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, fmrrd.getValue(1-id), 1550 dl, DAG, NextVA, 1551 Flags)); 1552 } 1553 } 1554 1555 /// LowerCall - Lowering a call into a callseq_start <- 1556 /// ARMISD:CALL <- callseq_end chain. Also add input and output parameter 1557 /// nodes. 1558 SDValue 1559 ARMTargetLowering::LowerCall(TargetLowering::CallLoweringInfo &CLI, 1560 SmallVectorImpl<SDValue> &InVals) const { 1561 SelectionDAG &DAG = CLI.DAG; 1562 SDLoc &dl = CLI.DL; 1563 SmallVectorImpl<ISD::OutputArg> &Outs = CLI.Outs; 1564 SmallVectorImpl<SDValue> &OutVals = CLI.OutVals; 1565 SmallVectorImpl<ISD::InputArg> &Ins = CLI.Ins; 1566 SDValue Chain = CLI.Chain; 1567 SDValue Callee = CLI.Callee; 1568 bool &isTailCall = CLI.IsTailCall; 1569 CallingConv::ID CallConv = CLI.CallConv; 1570 bool doesNotRet = CLI.DoesNotReturn; 1571 bool isVarArg = CLI.IsVarArg; 1572 1573 MachineFunction &MF = DAG.getMachineFunction(); 1574 bool isStructRet = (Outs.empty()) ? false : Outs[0].Flags.isSRet(); 1575 bool isThisReturn = false; 1576 bool isSibCall = false; 1577 auto Attr = MF.getFunction()->getFnAttribute("disable-tail-calls"); 1578 1579 // Disable tail calls if they're not supported. 1580 if (!Subtarget->supportsTailCall() || Attr.getValueAsString() == "true") 1581 isTailCall = false; 1582 1583 if (isTailCall) { 1584 // Check if it's really possible to do a tail call. 1585 isTailCall = IsEligibleForTailCallOptimization(Callee, CallConv, 1586 isVarArg, isStructRet, MF.getFunction()->hasStructRetAttr(), 1587 Outs, OutVals, Ins, DAG); 1588 if (!isTailCall && CLI.CS && CLI.CS->isMustTailCall()) 1589 report_fatal_error("failed to perform tail call elimination on a call " 1590 "site marked musttail"); 1591 // We don't support GuaranteedTailCallOpt for ARM, only automatically 1592 // detected sibcalls. 1593 if (isTailCall) { 1594 ++NumTailCalls; 1595 isSibCall = true; 1596 } 1597 } 1598 1599 // Analyze operands of the call, assigning locations to each operand. 1600 SmallVector<CCValAssign, 16> ArgLocs; 1601 ARMCCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), ArgLocs, 1602 *DAG.getContext(), Call); 1603 CCInfo.AnalyzeCallOperands(Outs, 1604 CCAssignFnForNode(CallConv, /* Return*/ false, 1605 isVarArg)); 1606 1607 // Get a count of how many bytes are to be pushed on the stack. 1608 unsigned NumBytes = CCInfo.getNextStackOffset(); 1609 1610 // For tail calls, memory operands are available in our caller's stack. 1611 if (isSibCall) 1612 NumBytes = 0; 1613 1614 // Adjust the stack pointer for the new arguments... 1615 // These operations are automatically eliminated by the prolog/epilog pass 1616 if (!isSibCall) 1617 Chain = DAG.getCALLSEQ_START(Chain, 1618 DAG.getIntPtrConstant(NumBytes, dl, true), dl); 1619 1620 SDValue StackPtr = 1621 DAG.getCopyFromReg(Chain, dl, ARM::SP, getPointerTy(DAG.getDataLayout())); 1622 1623 RegsToPassVector RegsToPass; 1624 SmallVector<SDValue, 8> MemOpChains; 1625 1626 // Walk the register/memloc assignments, inserting copies/loads. In the case 1627 // of tail call optimization, arguments are handled later. 1628 for (unsigned i = 0, realArgIdx = 0, e = ArgLocs.size(); 1629 i != e; 1630 ++i, ++realArgIdx) { 1631 CCValAssign &VA = ArgLocs[i]; 1632 SDValue Arg = OutVals[realArgIdx]; 1633 ISD::ArgFlagsTy Flags = Outs[realArgIdx].Flags; 1634 bool isByVal = Flags.isByVal(); 1635 1636 // Promote the value if needed. 1637 switch (VA.getLocInfo()) { 1638 default: llvm_unreachable("Unknown loc info!"); 1639 case CCValAssign::Full: break; 1640 case CCValAssign::SExt: 1641 Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), Arg); 1642 break; 1643 case CCValAssign::ZExt: 1644 Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, VA.getLocVT(), Arg); 1645 break; 1646 case CCValAssign::AExt: 1647 Arg = DAG.getNode(ISD::ANY_EXTEND, dl, VA.getLocVT(), Arg); 1648 break; 1649 case CCValAssign::BCvt: 1650 Arg = DAG.getNode(ISD::BITCAST, dl, VA.getLocVT(), Arg); 1651 break; 1652 } 1653 1654 // f64 and v2f64 might be passed in i32 pairs and must be split into pieces 1655 if (VA.needsCustom()) { 1656 if (VA.getLocVT() == MVT::v2f64) { 1657 SDValue Op0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg, 1658 DAG.getConstant(0, dl, MVT::i32)); 1659 SDValue Op1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg, 1660 DAG.getConstant(1, dl, MVT::i32)); 1661 1662 PassF64ArgInRegs(dl, DAG, Chain, Op0, RegsToPass, 1663 VA, ArgLocs[++i], StackPtr, MemOpChains, Flags); 1664 1665 VA = ArgLocs[++i]; // skip ahead to next loc 1666 if (VA.isRegLoc()) { 1667 PassF64ArgInRegs(dl, DAG, Chain, Op1, RegsToPass, 1668 VA, ArgLocs[++i], StackPtr, MemOpChains, Flags); 1669 } else { 1670 assert(VA.isMemLoc()); 1671 1672 MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, Op1, 1673 dl, DAG, VA, Flags)); 1674 } 1675 } else { 1676 PassF64ArgInRegs(dl, DAG, Chain, Arg, RegsToPass, VA, ArgLocs[++i], 1677 StackPtr, MemOpChains, Flags); 1678 } 1679 } else if (VA.isRegLoc()) { 1680 if (realArgIdx == 0 && Flags.isReturned() && Outs[0].VT == MVT::i32) { 1681 assert(VA.getLocVT() == MVT::i32 && 1682 "unexpected calling convention register assignment"); 1683 assert(!Ins.empty() && Ins[0].VT == MVT::i32 && 1684 "unexpected use of 'returned'"); 1685 isThisReturn = true; 1686 } 1687 RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg)); 1688 } else if (isByVal) { 1689 assert(VA.isMemLoc()); 1690 unsigned offset = 0; 1691 1692 // True if this byval aggregate will be split between registers 1693 // and memory. 1694 unsigned ByValArgsCount = CCInfo.getInRegsParamsCount(); 1695 unsigned CurByValIdx = CCInfo.getInRegsParamsProcessed(); 1696 1697 if (CurByValIdx < ByValArgsCount) { 1698 1699 unsigned RegBegin, RegEnd; 1700 CCInfo.getInRegsParamInfo(CurByValIdx, RegBegin, RegEnd); 1701 1702 EVT PtrVT = 1703 DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout()); 1704 unsigned int i, j; 1705 for (i = 0, j = RegBegin; j < RegEnd; i++, j++) { 1706 SDValue Const = DAG.getConstant(4*i, dl, MVT::i32); 1707 SDValue AddArg = DAG.getNode(ISD::ADD, dl, PtrVT, Arg, Const); 1708 SDValue Load = DAG.getLoad(PtrVT, dl, Chain, AddArg, 1709 MachinePointerInfo(), 1710 false, false, false, 1711 DAG.InferPtrAlignment(AddArg)); 1712 MemOpChains.push_back(Load.getValue(1)); 1713 RegsToPass.push_back(std::make_pair(j, Load)); 1714 } 1715 1716 // If parameter size outsides register area, "offset" value 1717 // helps us to calculate stack slot for remained part properly. 1718 offset = RegEnd - RegBegin; 1719 1720 CCInfo.nextInRegsParam(); 1721 } 1722 1723 if (Flags.getByValSize() > 4*offset) { 1724 auto PtrVT = getPointerTy(DAG.getDataLayout()); 1725 unsigned LocMemOffset = VA.getLocMemOffset(); 1726 SDValue StkPtrOff = DAG.getIntPtrConstant(LocMemOffset, dl); 1727 SDValue Dst = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, StkPtrOff); 1728 SDValue SrcOffset = DAG.getIntPtrConstant(4*offset, dl); 1729 SDValue Src = DAG.getNode(ISD::ADD, dl, PtrVT, Arg, SrcOffset); 1730 SDValue SizeNode = DAG.getConstant(Flags.getByValSize() - 4*offset, dl, 1731 MVT::i32); 1732 SDValue AlignNode = DAG.getConstant(Flags.getByValAlign(), dl, 1733 MVT::i32); 1734 1735 SDVTList VTs = DAG.getVTList(MVT::Other, MVT::Glue); 1736 SDValue Ops[] = { Chain, Dst, Src, SizeNode, AlignNode}; 1737 MemOpChains.push_back(DAG.getNode(ARMISD::COPY_STRUCT_BYVAL, dl, VTs, 1738 Ops)); 1739 } 1740 } else if (!isSibCall) { 1741 assert(VA.isMemLoc()); 1742 1743 MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, Arg, 1744 dl, DAG, VA, Flags)); 1745 } 1746 } 1747 1748 if (!MemOpChains.empty()) 1749 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains); 1750 1751 // Build a sequence of copy-to-reg nodes chained together with token chain 1752 // and flag operands which copy the outgoing args into the appropriate regs. 1753 SDValue InFlag; 1754 // Tail call byval lowering might overwrite argument registers so in case of 1755 // tail call optimization the copies to registers are lowered later. 1756 if (!isTailCall) 1757 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) { 1758 Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first, 1759 RegsToPass[i].second, InFlag); 1760 InFlag = Chain.getValue(1); 1761 } 1762 1763 // For tail calls lower the arguments to the 'real' stack slot. 1764 if (isTailCall) { 1765 // Force all the incoming stack arguments to be loaded from the stack 1766 // before any new outgoing arguments are stored to the stack, because the 1767 // outgoing stack slots may alias the incoming argument stack slots, and 1768 // the alias isn't otherwise explicit. This is slightly more conservative 1769 // than necessary, because it means that each store effectively depends 1770 // on every argument instead of just those arguments it would clobber. 1771 1772 // Do not flag preceding copytoreg stuff together with the following stuff. 1773 InFlag = SDValue(); 1774 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) { 1775 Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first, 1776 RegsToPass[i].second, InFlag); 1777 InFlag = Chain.getValue(1); 1778 } 1779 InFlag = SDValue(); 1780 } 1781 1782 // If the callee is a GlobalAddress/ExternalSymbol node (quite common, every 1783 // direct call is) turn it into a TargetGlobalAddress/TargetExternalSymbol 1784 // node so that legalize doesn't hack it. 1785 bool isDirect = false; 1786 bool isARMFunc = false; 1787 bool isLocalARMFunc = false; 1788 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>(); 1789 auto PtrVt = getPointerTy(DAG.getDataLayout()); 1790 1791 if (Subtarget->genLongCalls()) { 1792 assert((Subtarget->isTargetWindows() || 1793 getTargetMachine().getRelocationModel() == Reloc::Static) && 1794 "long-calls with non-static relocation model!"); 1795 // Handle a global address or an external symbol. If it's not one of 1796 // those, the target's already in a register, so we don't need to do 1797 // anything extra. 1798 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) { 1799 const GlobalValue *GV = G->getGlobal(); 1800 // Create a constant pool entry for the callee address 1801 unsigned ARMPCLabelIndex = AFI->createPICLabelUId(); 1802 ARMConstantPoolValue *CPV = 1803 ARMConstantPoolConstant::Create(GV, ARMPCLabelIndex, ARMCP::CPValue, 0); 1804 1805 // Get the address of the callee into a register 1806 SDValue CPAddr = DAG.getTargetConstantPool(CPV, PtrVt, 4); 1807 CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr); 1808 Callee = DAG.getLoad( 1809 PtrVt, dl, DAG.getEntryNode(), CPAddr, 1810 MachinePointerInfo::getConstantPool(DAG.getMachineFunction()), false, 1811 false, false, 0); 1812 } else if (ExternalSymbolSDNode *S=dyn_cast<ExternalSymbolSDNode>(Callee)) { 1813 const char *Sym = S->getSymbol(); 1814 1815 // Create a constant pool entry for the callee address 1816 unsigned ARMPCLabelIndex = AFI->createPICLabelUId(); 1817 ARMConstantPoolValue *CPV = 1818 ARMConstantPoolSymbol::Create(*DAG.getContext(), Sym, 1819 ARMPCLabelIndex, 0); 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 } 1828 } else if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) { 1829 const GlobalValue *GV = G->getGlobal(); 1830 isDirect = true; 1831 bool isDef = GV->isStrongDefinitionForLinker(); 1832 bool isStub = (!isDef && Subtarget->isTargetMachO()) && 1833 getTargetMachine().getRelocationModel() != Reloc::Static; 1834 isARMFunc = !Subtarget->isThumb() || (isStub && !Subtarget->isMClass()); 1835 // ARM call to a local ARM function is predicable. 1836 isLocalARMFunc = !Subtarget->isThumb() && (isDef || !ARMInterworking); 1837 // tBX takes a register source operand. 1838 if (isStub && Subtarget->isThumb1Only() && !Subtarget->hasV5TOps()) { 1839 assert(Subtarget->isTargetMachO() && "WrapperPIC use on non-MachO?"); 1840 Callee = DAG.getNode( 1841 ARMISD::WrapperPIC, dl, PtrVt, 1842 DAG.getTargetGlobalAddress(GV, dl, PtrVt, 0, ARMII::MO_NONLAZY)); 1843 Callee = DAG.getLoad(PtrVt, dl, DAG.getEntryNode(), Callee, 1844 MachinePointerInfo::getGOT(DAG.getMachineFunction()), 1845 false, false, true, 0); 1846 } else if (Subtarget->isTargetCOFF()) { 1847 assert(Subtarget->isTargetWindows() && 1848 "Windows is the only supported COFF target"); 1849 unsigned TargetFlags = GV->hasDLLImportStorageClass() 1850 ? ARMII::MO_DLLIMPORT 1851 : ARMII::MO_NO_FLAG; 1852 Callee = 1853 DAG.getTargetGlobalAddress(GV, dl, PtrVt, /*Offset=*/0, TargetFlags); 1854 if (GV->hasDLLImportStorageClass()) 1855 Callee = 1856 DAG.getLoad(PtrVt, dl, DAG.getEntryNode(), 1857 DAG.getNode(ARMISD::Wrapper, dl, PtrVt, Callee), 1858 MachinePointerInfo::getGOT(DAG.getMachineFunction()), 1859 false, false, false, 0); 1860 } else { 1861 // On ELF targets for PIC code, direct calls should go through the PLT 1862 unsigned OpFlags = 0; 1863 if (Subtarget->isTargetELF() && 1864 getTargetMachine().getRelocationModel() == Reloc::PIC_) 1865 OpFlags = ARMII::MO_PLT; 1866 Callee = DAG.getTargetGlobalAddress(GV, dl, PtrVt, 0, OpFlags); 1867 } 1868 } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) { 1869 isDirect = true; 1870 bool isStub = Subtarget->isTargetMachO() && 1871 getTargetMachine().getRelocationModel() != Reloc::Static; 1872 isARMFunc = !Subtarget->isThumb() || (isStub && !Subtarget->isMClass()); 1873 // tBX takes a register source operand. 1874 const char *Sym = S->getSymbol(); 1875 if (isARMFunc && Subtarget->isThumb1Only() && !Subtarget->hasV5TOps()) { 1876 unsigned ARMPCLabelIndex = AFI->createPICLabelUId(); 1877 ARMConstantPoolValue *CPV = 1878 ARMConstantPoolSymbol::Create(*DAG.getContext(), Sym, 1879 ARMPCLabelIndex, 4); 1880 SDValue CPAddr = DAG.getTargetConstantPool(CPV, PtrVt, 4); 1881 CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr); 1882 Callee = DAG.getLoad( 1883 PtrVt, dl, DAG.getEntryNode(), CPAddr, 1884 MachinePointerInfo::getConstantPool(DAG.getMachineFunction()), false, 1885 false, false, 0); 1886 SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, dl, MVT::i32); 1887 Callee = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVt, Callee, PICLabel); 1888 } else { 1889 unsigned OpFlags = 0; 1890 // On ELF targets for PIC code, direct calls should go through the PLT 1891 if (Subtarget->isTargetELF() && 1892 getTargetMachine().getRelocationModel() == Reloc::PIC_) 1893 OpFlags = ARMII::MO_PLT; 1894 Callee = DAG.getTargetExternalSymbol(Sym, PtrVt, OpFlags); 1895 } 1896 } 1897 1898 // FIXME: handle tail calls differently. 1899 unsigned CallOpc; 1900 if (Subtarget->isThumb()) { 1901 if ((!isDirect || isARMFunc) && !Subtarget->hasV5TOps()) 1902 CallOpc = ARMISD::CALL_NOLINK; 1903 else 1904 CallOpc = isARMFunc ? ARMISD::CALL : ARMISD::tCALL; 1905 } else { 1906 if (!isDirect && !Subtarget->hasV5TOps()) 1907 CallOpc = ARMISD::CALL_NOLINK; 1908 else if (doesNotRet && isDirect && Subtarget->hasRAS() && 1909 // Emit regular call when code size is the priority 1910 !MF.getFunction()->optForMinSize()) 1911 // "mov lr, pc; b _foo" to avoid confusing the RSP 1912 CallOpc = ARMISD::CALL_NOLINK; 1913 else 1914 CallOpc = isLocalARMFunc ? ARMISD::CALL_PRED : ARMISD::CALL; 1915 } 1916 1917 std::vector<SDValue> Ops; 1918 Ops.push_back(Chain); 1919 Ops.push_back(Callee); 1920 1921 // Add argument registers to the end of the list so that they are known live 1922 // into the call. 1923 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) 1924 Ops.push_back(DAG.getRegister(RegsToPass[i].first, 1925 RegsToPass[i].second.getValueType())); 1926 1927 // Add a register mask operand representing the call-preserved registers. 1928 if (!isTailCall) { 1929 const uint32_t *Mask; 1930 const ARMBaseRegisterInfo *ARI = Subtarget->getRegisterInfo(); 1931 if (isThisReturn) { 1932 // For 'this' returns, use the R0-preserving mask if applicable 1933 Mask = ARI->getThisReturnPreservedMask(MF, CallConv); 1934 if (!Mask) { 1935 // Set isThisReturn to false if the calling convention is not one that 1936 // allows 'returned' to be modeled in this way, so LowerCallResult does 1937 // not try to pass 'this' straight through 1938 isThisReturn = false; 1939 Mask = ARI->getCallPreservedMask(MF, CallConv); 1940 } 1941 } else 1942 Mask = ARI->getCallPreservedMask(MF, CallConv); 1943 1944 assert(Mask && "Missing call preserved mask for calling convention"); 1945 Ops.push_back(DAG.getRegisterMask(Mask)); 1946 } 1947 1948 if (InFlag.getNode()) 1949 Ops.push_back(InFlag); 1950 1951 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue); 1952 if (isTailCall) { 1953 MF.getFrameInfo()->setHasTailCall(); 1954 return DAG.getNode(ARMISD::TC_RETURN, dl, NodeTys, Ops); 1955 } 1956 1957 // Returns a chain and a flag for retval copy to use. 1958 Chain = DAG.getNode(CallOpc, dl, NodeTys, Ops); 1959 InFlag = Chain.getValue(1); 1960 1961 Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, dl, true), 1962 DAG.getIntPtrConstant(0, dl, true), InFlag, dl); 1963 if (!Ins.empty()) 1964 InFlag = Chain.getValue(1); 1965 1966 // Handle result values, copying them out of physregs into vregs that we 1967 // return. 1968 return LowerCallResult(Chain, InFlag, CallConv, isVarArg, Ins, dl, DAG, 1969 InVals, isThisReturn, 1970 isThisReturn ? OutVals[0] : SDValue()); 1971 } 1972 1973 /// HandleByVal - Every parameter *after* a byval parameter is passed 1974 /// on the stack. Remember the next parameter register to allocate, 1975 /// and then confiscate the rest of the parameter registers to insure 1976 /// this. 1977 void ARMTargetLowering::HandleByVal(CCState *State, unsigned &Size, 1978 unsigned Align) const { 1979 assert((State->getCallOrPrologue() == Prologue || 1980 State->getCallOrPrologue() == Call) && 1981 "unhandled ParmContext"); 1982 1983 // Byval (as with any stack) slots are always at least 4 byte aligned. 1984 Align = std::max(Align, 4U); 1985 1986 unsigned Reg = State->AllocateReg(GPRArgRegs); 1987 if (!Reg) 1988 return; 1989 1990 unsigned AlignInRegs = Align / 4; 1991 unsigned Waste = (ARM::R4 - Reg) % AlignInRegs; 1992 for (unsigned i = 0; i < Waste; ++i) 1993 Reg = State->AllocateReg(GPRArgRegs); 1994 1995 if (!Reg) 1996 return; 1997 1998 unsigned Excess = 4 * (ARM::R4 - Reg); 1999 2000 // Special case when NSAA != SP and parameter size greater than size of 2001 // all remained GPR regs. In that case we can't split parameter, we must 2002 // send it to stack. We also must set NCRN to R4, so waste all 2003 // remained registers. 2004 const unsigned NSAAOffset = State->getNextStackOffset(); 2005 if (NSAAOffset != 0 && Size > Excess) { 2006 while (State->AllocateReg(GPRArgRegs)) 2007 ; 2008 return; 2009 } 2010 2011 // First register for byval parameter is the first register that wasn't 2012 // allocated before this method call, so it would be "reg". 2013 // If parameter is small enough to be saved in range [reg, r4), then 2014 // the end (first after last) register would be reg + param-size-in-regs, 2015 // else parameter would be splitted between registers and stack, 2016 // end register would be r4 in this case. 2017 unsigned ByValRegBegin = Reg; 2018 unsigned ByValRegEnd = std::min<unsigned>(Reg + Size / 4, ARM::R4); 2019 State->addInRegsParamInfo(ByValRegBegin, ByValRegEnd); 2020 // Note, first register is allocated in the beginning of function already, 2021 // allocate remained amount of registers we need. 2022 for (unsigned i = Reg + 1; i != ByValRegEnd; ++i) 2023 State->AllocateReg(GPRArgRegs); 2024 // A byval parameter that is split between registers and memory needs its 2025 // size truncated here. 2026 // In the case where the entire structure fits in registers, we set the 2027 // size in memory to zero. 2028 Size = std::max<int>(Size - Excess, 0); 2029 } 2030 2031 /// MatchingStackOffset - Return true if the given stack call argument is 2032 /// already available in the same position (relatively) of the caller's 2033 /// incoming argument stack. 2034 static 2035 bool MatchingStackOffset(SDValue Arg, unsigned Offset, ISD::ArgFlagsTy Flags, 2036 MachineFrameInfo *MFI, const MachineRegisterInfo *MRI, 2037 const TargetInstrInfo *TII) { 2038 unsigned Bytes = Arg.getValueType().getSizeInBits() / 8; 2039 int FI = INT_MAX; 2040 if (Arg.getOpcode() == ISD::CopyFromReg) { 2041 unsigned VR = cast<RegisterSDNode>(Arg.getOperand(1))->getReg(); 2042 if (!TargetRegisterInfo::isVirtualRegister(VR)) 2043 return false; 2044 MachineInstr *Def = MRI->getVRegDef(VR); 2045 if (!Def) 2046 return false; 2047 if (!Flags.isByVal()) { 2048 if (!TII->isLoadFromStackSlot(Def, FI)) 2049 return false; 2050 } else { 2051 return false; 2052 } 2053 } else if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Arg)) { 2054 if (Flags.isByVal()) 2055 // ByVal argument is passed in as a pointer but it's now being 2056 // dereferenced. e.g. 2057 // define @foo(%struct.X* %A) { 2058 // tail call @bar(%struct.X* byval %A) 2059 // } 2060 return false; 2061 SDValue Ptr = Ld->getBasePtr(); 2062 FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr); 2063 if (!FINode) 2064 return false; 2065 FI = FINode->getIndex(); 2066 } else 2067 return false; 2068 2069 assert(FI != INT_MAX); 2070 if (!MFI->isFixedObjectIndex(FI)) 2071 return false; 2072 return Offset == MFI->getObjectOffset(FI) && Bytes == MFI->getObjectSize(FI); 2073 } 2074 2075 /// IsEligibleForTailCallOptimization - Check whether the call is eligible 2076 /// for tail call optimization. Targets which want to do tail call 2077 /// optimization should implement this function. 2078 bool 2079 ARMTargetLowering::IsEligibleForTailCallOptimization(SDValue Callee, 2080 CallingConv::ID CalleeCC, 2081 bool isVarArg, 2082 bool isCalleeStructRet, 2083 bool isCallerStructRet, 2084 const SmallVectorImpl<ISD::OutputArg> &Outs, 2085 const SmallVectorImpl<SDValue> &OutVals, 2086 const SmallVectorImpl<ISD::InputArg> &Ins, 2087 SelectionDAG& DAG) const { 2088 const Function *CallerF = DAG.getMachineFunction().getFunction(); 2089 CallingConv::ID CallerCC = CallerF->getCallingConv(); 2090 bool CCMatch = CallerCC == CalleeCC; 2091 2092 assert(Subtarget->supportsTailCall()); 2093 2094 // Look for obvious safe cases to perform tail call optimization that do not 2095 // require ABI changes. This is what gcc calls sibcall. 2096 2097 // Do not sibcall optimize vararg calls unless the call site is not passing 2098 // any arguments. 2099 if (isVarArg && !Outs.empty()) 2100 return false; 2101 2102 // Exception-handling functions need a special set of instructions to indicate 2103 // a return to the hardware. Tail-calling another function would probably 2104 // break this. 2105 if (CallerF->hasFnAttribute("interrupt")) 2106 return false; 2107 2108 // Also avoid sibcall optimization if either caller or callee uses struct 2109 // return semantics. 2110 if (isCalleeStructRet || isCallerStructRet) 2111 return false; 2112 2113 // Externally-defined functions with weak linkage should not be 2114 // tail-called on ARM when the OS does not support dynamic 2115 // pre-emption of symbols, as the AAELF spec requires normal calls 2116 // to undefined weak functions to be replaced with a NOP or jump to the 2117 // next instruction. The behaviour of branch instructions in this 2118 // situation (as used for tail calls) is implementation-defined, so we 2119 // cannot rely on the linker replacing the tail call with a return. 2120 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) { 2121 const GlobalValue *GV = G->getGlobal(); 2122 const Triple &TT = getTargetMachine().getTargetTriple(); 2123 if (GV->hasExternalWeakLinkage() && 2124 (!TT.isOSWindows() || TT.isOSBinFormatELF() || TT.isOSBinFormatMachO())) 2125 return false; 2126 } 2127 2128 // If the calling conventions do not match, then we'd better make sure the 2129 // results are returned in the same way as what the caller expects. 2130 if (!CCMatch) { 2131 SmallVector<CCValAssign, 16> RVLocs1; 2132 ARMCCState CCInfo1(CalleeCC, false, DAG.getMachineFunction(), RVLocs1, 2133 *DAG.getContext(), Call); 2134 CCInfo1.AnalyzeCallResult(Ins, CCAssignFnForNode(CalleeCC, true, isVarArg)); 2135 2136 SmallVector<CCValAssign, 16> RVLocs2; 2137 ARMCCState CCInfo2(CallerCC, false, DAG.getMachineFunction(), RVLocs2, 2138 *DAG.getContext(), Call); 2139 CCInfo2.AnalyzeCallResult(Ins, CCAssignFnForNode(CallerCC, true, isVarArg)); 2140 2141 if (RVLocs1.size() != RVLocs2.size()) 2142 return false; 2143 for (unsigned i = 0, e = RVLocs1.size(); i != e; ++i) { 2144 if (RVLocs1[i].isRegLoc() != RVLocs2[i].isRegLoc()) 2145 return false; 2146 if (RVLocs1[i].getLocInfo() != RVLocs2[i].getLocInfo()) 2147 return false; 2148 if (RVLocs1[i].isRegLoc()) { 2149 if (RVLocs1[i].getLocReg() != RVLocs2[i].getLocReg()) 2150 return false; 2151 } else { 2152 if (RVLocs1[i].getLocMemOffset() != RVLocs2[i].getLocMemOffset()) 2153 return false; 2154 } 2155 } 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 = DAG.getMachineFunction(). 2162 getInfo<ARMFunctionInfo>(); 2163 if (AFI_Caller->getArgRegsSaveSize()) 2164 return false; 2165 2166 // If the callee takes no arguments then go on to check the results of the 2167 // call. 2168 if (!Outs.empty()) { 2169 // Check if stack adjustment is needed. For now, do not do this if any 2170 // argument is passed on the stack. 2171 SmallVector<CCValAssign, 16> ArgLocs; 2172 ARMCCState CCInfo(CalleeCC, isVarArg, DAG.getMachineFunction(), ArgLocs, 2173 *DAG.getContext(), Call); 2174 CCInfo.AnalyzeCallOperands(Outs, 2175 CCAssignFnForNode(CalleeCC, false, isVarArg)); 2176 if (CCInfo.getNextStackOffset()) { 2177 MachineFunction &MF = DAG.getMachineFunction(); 2178 2179 // Check if the arguments are already laid out in the right way as 2180 // the caller's fixed stack objects. 2181 MachineFrameInfo *MFI = MF.getFrameInfo(); 2182 const MachineRegisterInfo *MRI = &MF.getRegInfo(); 2183 const TargetInstrInfo *TII = Subtarget->getInstrInfo(); 2184 for (unsigned i = 0, realArgIdx = 0, e = ArgLocs.size(); 2185 i != e; 2186 ++i, ++realArgIdx) { 2187 CCValAssign &VA = ArgLocs[i]; 2188 EVT RegVT = VA.getLocVT(); 2189 SDValue Arg = OutVals[realArgIdx]; 2190 ISD::ArgFlagsTy Flags = Outs[realArgIdx].Flags; 2191 if (VA.getLocInfo() == CCValAssign::Indirect) 2192 return false; 2193 if (VA.needsCustom()) { 2194 // f64 and vector types are split into multiple registers or 2195 // register/stack-slot combinations. The types will not match 2196 // the registers; give up on memory f64 refs until we figure 2197 // out what to do about this. 2198 if (!VA.isRegLoc()) 2199 return false; 2200 if (!ArgLocs[++i].isRegLoc()) 2201 return false; 2202 if (RegVT == MVT::v2f64) { 2203 if (!ArgLocs[++i].isRegLoc()) 2204 return false; 2205 if (!ArgLocs[++i].isRegLoc()) 2206 return false; 2207 } 2208 } else if (!VA.isRegLoc()) { 2209 if (!MatchingStackOffset(Arg, VA.getLocMemOffset(), Flags, 2210 MFI, MRI, TII)) 2211 return false; 2212 } 2213 } 2214 } 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::arm_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 == 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 /// isNEONModifiedImm - Check if the specified splat value corresponds to a 4884 /// valid vector constant for a NEON instruction with a "modified immediate" 4885 /// operand (e.g., VMOV). If so, return the encoded value. 4886 static SDValue isNEONModifiedImm(uint64_t SplatBits, uint64_t SplatUndef, 4887 unsigned SplatBitSize, SelectionDAG &DAG, 4888 SDLoc dl, EVT &VT, bool is128Bits, 4889 NEONModImmType type) { 4890 unsigned OpCmode, Imm; 4891 4892 // SplatBitSize is set to the smallest size that splats the vector, so a 4893 // zero vector will always have SplatBitSize == 8. However, NEON modified 4894 // immediate instructions others than VMOV do not support the 8-bit encoding 4895 // of a zero vector, and the default encoding of zero is supposed to be the 4896 // 32-bit version. 4897 if (SplatBits == 0) 4898 SplatBitSize = 32; 4899 4900 switch (SplatBitSize) { 4901 case 8: 4902 if (type != VMOVModImm) 4903 return SDValue(); 4904 // Any 1-byte value is OK. Op=0, Cmode=1110. 4905 assert((SplatBits & ~0xff) == 0 && "one byte splat value is too big"); 4906 OpCmode = 0xe; 4907 Imm = SplatBits; 4908 VT = is128Bits ? MVT::v16i8 : MVT::v8i8; 4909 break; 4910 4911 case 16: 4912 // NEON's 16-bit VMOV supports splat values where only one byte is nonzero. 4913 VT = is128Bits ? MVT::v8i16 : MVT::v4i16; 4914 if ((SplatBits & ~0xff) == 0) { 4915 // Value = 0x00nn: Op=x, Cmode=100x. 4916 OpCmode = 0x8; 4917 Imm = SplatBits; 4918 break; 4919 } 4920 if ((SplatBits & ~0xff00) == 0) { 4921 // Value = 0xnn00: Op=x, Cmode=101x. 4922 OpCmode = 0xa; 4923 Imm = SplatBits >> 8; 4924 break; 4925 } 4926 return SDValue(); 4927 4928 case 32: 4929 // NEON's 32-bit VMOV supports splat values where: 4930 // * only one byte is nonzero, or 4931 // * the least significant byte is 0xff and the second byte is nonzero, or 4932 // * the least significant 2 bytes are 0xff and the third is nonzero. 4933 VT = is128Bits ? MVT::v4i32 : MVT::v2i32; 4934 if ((SplatBits & ~0xff) == 0) { 4935 // Value = 0x000000nn: Op=x, Cmode=000x. 4936 OpCmode = 0; 4937 Imm = SplatBits; 4938 break; 4939 } 4940 if ((SplatBits & ~0xff00) == 0) { 4941 // Value = 0x0000nn00: Op=x, Cmode=001x. 4942 OpCmode = 0x2; 4943 Imm = SplatBits >> 8; 4944 break; 4945 } 4946 if ((SplatBits & ~0xff0000) == 0) { 4947 // Value = 0x00nn0000: Op=x, Cmode=010x. 4948 OpCmode = 0x4; 4949 Imm = SplatBits >> 16; 4950 break; 4951 } 4952 if ((SplatBits & ~0xff000000) == 0) { 4953 // Value = 0xnn000000: Op=x, Cmode=011x. 4954 OpCmode = 0x6; 4955 Imm = SplatBits >> 24; 4956 break; 4957 } 4958 4959 // cmode == 0b1100 and cmode == 0b1101 are not supported for VORR or VBIC 4960 if (type == OtherModImm) return SDValue(); 4961 4962 if ((SplatBits & ~0xffff) == 0 && 4963 ((SplatBits | SplatUndef) & 0xff) == 0xff) { 4964 // Value = 0x0000nnff: Op=x, Cmode=1100. 4965 OpCmode = 0xc; 4966 Imm = SplatBits >> 8; 4967 break; 4968 } 4969 4970 if ((SplatBits & ~0xffffff) == 0 && 4971 ((SplatBits | SplatUndef) & 0xffff) == 0xffff) { 4972 // Value = 0x00nnffff: Op=x, Cmode=1101. 4973 OpCmode = 0xd; 4974 Imm = SplatBits >> 16; 4975 break; 4976 } 4977 4978 // Note: there are a few 32-bit splat values (specifically: 00ffff00, 4979 // ff000000, ff0000ff, and ffff00ff) that are valid for VMOV.I64 but not 4980 // VMOV.I32. A (very) minor optimization would be to replicate the value 4981 // and fall through here to test for a valid 64-bit splat. But, then the 4982 // caller would also need to check and handle the change in size. 4983 return SDValue(); 4984 4985 case 64: { 4986 if (type != VMOVModImm) 4987 return SDValue(); 4988 // NEON has a 64-bit VMOV splat where each byte is either 0 or 0xff. 4989 uint64_t BitMask = 0xff; 4990 uint64_t Val = 0; 4991 unsigned ImmMask = 1; 4992 Imm = 0; 4993 for (int ByteNum = 0; ByteNum < 8; ++ByteNum) { 4994 if (((SplatBits | SplatUndef) & BitMask) == BitMask) { 4995 Val |= BitMask; 4996 Imm |= ImmMask; 4997 } else if ((SplatBits & BitMask) != 0) { 4998 return SDValue(); 4999 } 5000 BitMask <<= 8; 5001 ImmMask <<= 1; 5002 } 5003 5004 if (DAG.getDataLayout().isBigEndian()) 5005 // swap higher and lower 32 bit word 5006 Imm = ((Imm & 0xf) << 4) | ((Imm & 0xf0) >> 4); 5007 5008 // Op=1, Cmode=1110. 5009 OpCmode = 0x1e; 5010 VT = is128Bits ? MVT::v2i64 : MVT::v1i64; 5011 break; 5012 } 5013 5014 default: 5015 llvm_unreachable("unexpected size for isNEONModifiedImm"); 5016 } 5017 5018 unsigned EncodedVal = ARM_AM::createNEONModImm(OpCmode, Imm); 5019 return DAG.getTargetConstant(EncodedVal, dl, MVT::i32); 5020 } 5021 5022 SDValue ARMTargetLowering::LowerConstantFP(SDValue Op, SelectionDAG &DAG, 5023 const ARMSubtarget *ST) const { 5024 if (!ST->hasVFP3()) 5025 return SDValue(); 5026 5027 bool IsDouble = Op.getValueType() == MVT::f64; 5028 ConstantFPSDNode *CFP = cast<ConstantFPSDNode>(Op); 5029 5030 // Use the default (constant pool) lowering for double constants when we have 5031 // an SP-only FPU 5032 if (IsDouble && Subtarget->isFPOnlySP()) 5033 return SDValue(); 5034 5035 // Try splatting with a VMOV.f32... 5036 APFloat FPVal = CFP->getValueAPF(); 5037 int ImmVal = IsDouble ? ARM_AM::getFP64Imm(FPVal) : ARM_AM::getFP32Imm(FPVal); 5038 5039 if (ImmVal != -1) { 5040 if (IsDouble || !ST->useNEONForSinglePrecisionFP()) { 5041 // We have code in place to select a valid ConstantFP already, no need to 5042 // do any mangling. 5043 return Op; 5044 } 5045 5046 // It's a float and we are trying to use NEON operations where 5047 // possible. Lower it to a splat followed by an extract. 5048 SDLoc DL(Op); 5049 SDValue NewVal = DAG.getTargetConstant(ImmVal, DL, MVT::i32); 5050 SDValue VecConstant = DAG.getNode(ARMISD::VMOVFPIMM, DL, MVT::v2f32, 5051 NewVal); 5052 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32, VecConstant, 5053 DAG.getConstant(0, DL, MVT::i32)); 5054 } 5055 5056 // The rest of our options are NEON only, make sure that's allowed before 5057 // proceeding.. 5058 if (!ST->hasNEON() || (!IsDouble && !ST->useNEONForSinglePrecisionFP())) 5059 return SDValue(); 5060 5061 EVT VMovVT; 5062 uint64_t iVal = FPVal.bitcastToAPInt().getZExtValue(); 5063 5064 // It wouldn't really be worth bothering for doubles except for one very 5065 // important value, which does happen to match: 0.0. So make sure we don't do 5066 // anything stupid. 5067 if (IsDouble && (iVal & 0xffffffff) != (iVal >> 32)) 5068 return SDValue(); 5069 5070 // Try a VMOV.i32 (FIXME: i8, i16, or i64 could work too). 5071 SDValue NewVal = isNEONModifiedImm(iVal & 0xffffffffU, 0, 32, DAG, SDLoc(Op), 5072 VMovVT, false, VMOVModImm); 5073 if (NewVal != SDValue()) { 5074 SDLoc DL(Op); 5075 SDValue VecConstant = DAG.getNode(ARMISD::VMOVIMM, DL, VMovVT, 5076 NewVal); 5077 if (IsDouble) 5078 return DAG.getNode(ISD::BITCAST, DL, MVT::f64, VecConstant); 5079 5080 // It's a float: cast and extract a vector element. 5081 SDValue VecFConstant = DAG.getNode(ISD::BITCAST, DL, MVT::v2f32, 5082 VecConstant); 5083 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32, VecFConstant, 5084 DAG.getConstant(0, DL, MVT::i32)); 5085 } 5086 5087 // Finally, try a VMVN.i32 5088 NewVal = isNEONModifiedImm(~iVal & 0xffffffffU, 0, 32, DAG, SDLoc(Op), VMovVT, 5089 false, VMVNModImm); 5090 if (NewVal != SDValue()) { 5091 SDLoc DL(Op); 5092 SDValue VecConstant = DAG.getNode(ARMISD::VMVNIMM, DL, VMovVT, NewVal); 5093 5094 if (IsDouble) 5095 return DAG.getNode(ISD::BITCAST, DL, MVT::f64, VecConstant); 5096 5097 // It's a float: cast and extract a vector element. 5098 SDValue VecFConstant = DAG.getNode(ISD::BITCAST, DL, MVT::v2f32, 5099 VecConstant); 5100 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32, VecFConstant, 5101 DAG.getConstant(0, DL, MVT::i32)); 5102 } 5103 5104 return SDValue(); 5105 } 5106 5107 // check if an VEXT instruction can handle the shuffle mask when the 5108 // vector sources of the shuffle are the same. 5109 static bool isSingletonVEXTMask(ArrayRef<int> M, EVT VT, unsigned &Imm) { 5110 unsigned NumElts = VT.getVectorNumElements(); 5111 5112 // Assume that the first shuffle index is not UNDEF. Fail if it is. 5113 if (M[0] < 0) 5114 return false; 5115 5116 Imm = M[0]; 5117 5118 // If this is a VEXT shuffle, the immediate value is the index of the first 5119 // element. The other shuffle indices must be the successive elements after 5120 // the first one. 5121 unsigned ExpectedElt = Imm; 5122 for (unsigned i = 1; i < NumElts; ++i) { 5123 // Increment the expected index. If it wraps around, just follow it 5124 // back to index zero and keep going. 5125 ++ExpectedElt; 5126 if (ExpectedElt == NumElts) 5127 ExpectedElt = 0; 5128 5129 if (M[i] < 0) continue; // ignore UNDEF indices 5130 if (ExpectedElt != static_cast<unsigned>(M[i])) 5131 return false; 5132 } 5133 5134 return true; 5135 } 5136 5137 5138 static bool isVEXTMask(ArrayRef<int> M, EVT VT, 5139 bool &ReverseVEXT, unsigned &Imm) { 5140 unsigned NumElts = VT.getVectorNumElements(); 5141 ReverseVEXT = false; 5142 5143 // Assume that the first shuffle index is not UNDEF. Fail if it is. 5144 if (M[0] < 0) 5145 return false; 5146 5147 Imm = M[0]; 5148 5149 // If this is a VEXT shuffle, the immediate value is the index of the first 5150 // element. The other shuffle indices must be the successive elements after 5151 // the first one. 5152 unsigned ExpectedElt = Imm; 5153 for (unsigned i = 1; i < NumElts; ++i) { 5154 // Increment the expected index. If it wraps around, it may still be 5155 // a VEXT but the source vectors must be swapped. 5156 ExpectedElt += 1; 5157 if (ExpectedElt == NumElts * 2) { 5158 ExpectedElt = 0; 5159 ReverseVEXT = true; 5160 } 5161 5162 if (M[i] < 0) continue; // ignore UNDEF indices 5163 if (ExpectedElt != static_cast<unsigned>(M[i])) 5164 return false; 5165 } 5166 5167 // Adjust the index value if the source operands will be swapped. 5168 if (ReverseVEXT) 5169 Imm -= NumElts; 5170 5171 return true; 5172 } 5173 5174 /// isVREVMask - Check if a vector shuffle corresponds to a VREV 5175 /// instruction with the specified blocksize. (The order of the elements 5176 /// within each block of the vector is reversed.) 5177 static bool isVREVMask(ArrayRef<int> M, EVT VT, unsigned BlockSize) { 5178 assert((BlockSize==16 || BlockSize==32 || BlockSize==64) && 5179 "Only possible block sizes for VREV are: 16, 32, 64"); 5180 5181 unsigned EltSz = VT.getVectorElementType().getSizeInBits(); 5182 if (EltSz == 64) 5183 return false; 5184 5185 unsigned NumElts = VT.getVectorNumElements(); 5186 unsigned BlockElts = M[0] + 1; 5187 // If the first shuffle index is UNDEF, be optimistic. 5188 if (M[0] < 0) 5189 BlockElts = BlockSize / EltSz; 5190 5191 if (BlockSize <= EltSz || BlockSize != BlockElts * EltSz) 5192 return false; 5193 5194 for (unsigned i = 0; i < NumElts; ++i) { 5195 if (M[i] < 0) continue; // ignore UNDEF indices 5196 if ((unsigned) M[i] != (i - i%BlockElts) + (BlockElts - 1 - i%BlockElts)) 5197 return false; 5198 } 5199 5200 return true; 5201 } 5202 5203 static bool isVTBLMask(ArrayRef<int> M, EVT VT) { 5204 // We can handle <8 x i8> vector shuffles. If the index in the mask is out of 5205 // range, then 0 is placed into the resulting vector. So pretty much any mask 5206 // of 8 elements can work here. 5207 return VT == MVT::v8i8 && M.size() == 8; 5208 } 5209 5210 // Checks whether the shuffle mask represents a vector transpose (VTRN) by 5211 // checking that pairs of elements in the shuffle mask represent the same index 5212 // in each vector, incrementing the expected index by 2 at each step. 5213 // e.g. For v1,v2 of type v4i32 a valid shuffle mask is: [0, 4, 2, 6] 5214 // v1={a,b,c,d} => x=shufflevector v1, v2 shufflemask => x={a,e,c,g} 5215 // v2={e,f,g,h} 5216 // WhichResult gives the offset for each element in the mask based on which 5217 // of the two results it belongs to. 5218 // 5219 // The transpose can be represented either as: 5220 // result1 = shufflevector v1, v2, result1_shuffle_mask 5221 // result2 = shufflevector v1, v2, result2_shuffle_mask 5222 // where v1/v2 and the shuffle masks have the same number of elements 5223 // (here WhichResult (see below) indicates which result is being checked) 5224 // 5225 // or as: 5226 // results = shufflevector v1, v2, shuffle_mask 5227 // where both results are returned in one vector and the shuffle mask has twice 5228 // as many elements as v1/v2 (here WhichResult will always be 0 if true) here we 5229 // want to check the low half and high half of the shuffle mask as if it were 5230 // the other case 5231 static bool isVTRNMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) { 5232 unsigned EltSz = VT.getVectorElementType().getSizeInBits(); 5233 if (EltSz == 64) 5234 return false; 5235 5236 unsigned NumElts = VT.getVectorNumElements(); 5237 if (M.size() != NumElts && M.size() != NumElts*2) 5238 return false; 5239 5240 // If the mask is twice as long as the input vector then we need to check the 5241 // upper and lower parts of the mask with a matching value for WhichResult 5242 // FIXME: A mask with only even values will be rejected in case the first 5243 // element is undefined, e.g. [-1, 4, 2, 6] will be rejected, because only 5244 // M[0] is used to determine WhichResult 5245 for (unsigned i = 0; i < M.size(); i += NumElts) { 5246 if (M.size() == NumElts * 2) 5247 WhichResult = i / NumElts; 5248 else 5249 WhichResult = M[i] == 0 ? 0 : 1; 5250 for (unsigned j = 0; j < NumElts; j += 2) { 5251 if ((M[i+j] >= 0 && (unsigned) M[i+j] != j + WhichResult) || 5252 (M[i+j+1] >= 0 && (unsigned) M[i+j+1] != j + NumElts + WhichResult)) 5253 return false; 5254 } 5255 } 5256 5257 if (M.size() == NumElts*2) 5258 WhichResult = 0; 5259 5260 return true; 5261 } 5262 5263 /// isVTRN_v_undef_Mask - Special case of isVTRNMask for canonical form of 5264 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef". 5265 /// Mask is e.g., <0, 0, 2, 2> instead of <0, 4, 2, 6>. 5266 static bool isVTRN_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult){ 5267 unsigned EltSz = VT.getVectorElementType().getSizeInBits(); 5268 if (EltSz == 64) 5269 return false; 5270 5271 unsigned NumElts = VT.getVectorNumElements(); 5272 if (M.size() != NumElts && M.size() != NumElts*2) 5273 return false; 5274 5275 for (unsigned i = 0; i < M.size(); i += NumElts) { 5276 if (M.size() == NumElts * 2) 5277 WhichResult = i / NumElts; 5278 else 5279 WhichResult = M[i] == 0 ? 0 : 1; 5280 for (unsigned j = 0; j < NumElts; j += 2) { 5281 if ((M[i+j] >= 0 && (unsigned) M[i+j] != j + WhichResult) || 5282 (M[i+j+1] >= 0 && (unsigned) M[i+j+1] != j + WhichResult)) 5283 return false; 5284 } 5285 } 5286 5287 if (M.size() == NumElts*2) 5288 WhichResult = 0; 5289 5290 return true; 5291 } 5292 5293 // Checks whether the shuffle mask represents a vector unzip (VUZP) by checking 5294 // that the mask elements are either all even and in steps of size 2 or all odd 5295 // and in steps of size 2. 5296 // e.g. For v1,v2 of type v4i32 a valid shuffle mask is: [0, 2, 4, 6] 5297 // v1={a,b,c,d} => x=shufflevector v1, v2 shufflemask => x={a,c,e,g} 5298 // v2={e,f,g,h} 5299 // Requires similar checks to that of isVTRNMask with 5300 // respect the how results are returned. 5301 static bool isVUZPMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) { 5302 unsigned EltSz = VT.getVectorElementType().getSizeInBits(); 5303 if (EltSz == 64) 5304 return false; 5305 5306 unsigned NumElts = VT.getVectorNumElements(); 5307 if (M.size() != NumElts && M.size() != NumElts*2) 5308 return false; 5309 5310 for (unsigned i = 0; i < M.size(); i += NumElts) { 5311 WhichResult = M[i] == 0 ? 0 : 1; 5312 for (unsigned j = 0; j < NumElts; ++j) { 5313 if (M[i+j] >= 0 && (unsigned) M[i+j] != 2 * j + WhichResult) 5314 return false; 5315 } 5316 } 5317 5318 if (M.size() == NumElts*2) 5319 WhichResult = 0; 5320 5321 // VUZP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32. 5322 if (VT.is64BitVector() && EltSz == 32) 5323 return false; 5324 5325 return true; 5326 } 5327 5328 /// isVUZP_v_undef_Mask - Special case of isVUZPMask for canonical form of 5329 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef". 5330 /// Mask is e.g., <0, 2, 0, 2> instead of <0, 2, 4, 6>, 5331 static bool isVUZP_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult){ 5332 unsigned EltSz = VT.getVectorElementType().getSizeInBits(); 5333 if (EltSz == 64) 5334 return false; 5335 5336 unsigned NumElts = VT.getVectorNumElements(); 5337 if (M.size() != NumElts && M.size() != NumElts*2) 5338 return false; 5339 5340 unsigned Half = NumElts / 2; 5341 for (unsigned i = 0; i < M.size(); i += NumElts) { 5342 WhichResult = M[i] == 0 ? 0 : 1; 5343 for (unsigned j = 0; j < NumElts; j += Half) { 5344 unsigned Idx = WhichResult; 5345 for (unsigned k = 0; k < Half; ++k) { 5346 int MIdx = M[i + j + k]; 5347 if (MIdx >= 0 && (unsigned) MIdx != Idx) 5348 return false; 5349 Idx += 2; 5350 } 5351 } 5352 } 5353 5354 if (M.size() == NumElts*2) 5355 WhichResult = 0; 5356 5357 // VUZP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32. 5358 if (VT.is64BitVector() && EltSz == 32) 5359 return false; 5360 5361 return true; 5362 } 5363 5364 // Checks whether the shuffle mask represents a vector zip (VZIP) by checking 5365 // that pairs of elements of the shufflemask represent the same index in each 5366 // vector incrementing sequentially through the vectors. 5367 // e.g. For v1,v2 of type v4i32 a valid shuffle mask is: [0, 4, 1, 5] 5368 // v1={a,b,c,d} => x=shufflevector v1, v2 shufflemask => x={a,e,b,f} 5369 // v2={e,f,g,h} 5370 // Requires similar checks to that of isVTRNMask with respect the how results 5371 // are returned. 5372 static bool isVZIPMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) { 5373 unsigned EltSz = VT.getVectorElementType().getSizeInBits(); 5374 if (EltSz == 64) 5375 return false; 5376 5377 unsigned NumElts = VT.getVectorNumElements(); 5378 if (M.size() != NumElts && M.size() != NumElts*2) 5379 return false; 5380 5381 for (unsigned i = 0; i < M.size(); i += NumElts) { 5382 WhichResult = M[i] == 0 ? 0 : 1; 5383 unsigned Idx = WhichResult * NumElts / 2; 5384 for (unsigned j = 0; j < NumElts; j += 2) { 5385 if ((M[i+j] >= 0 && (unsigned) M[i+j] != Idx) || 5386 (M[i+j+1] >= 0 && (unsigned) M[i+j+1] != Idx + NumElts)) 5387 return false; 5388 Idx += 1; 5389 } 5390 } 5391 5392 if (M.size() == NumElts*2) 5393 WhichResult = 0; 5394 5395 // VZIP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32. 5396 if (VT.is64BitVector() && EltSz == 32) 5397 return false; 5398 5399 return true; 5400 } 5401 5402 /// isVZIP_v_undef_Mask - Special case of isVZIPMask for canonical form of 5403 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef". 5404 /// Mask is e.g., <0, 0, 1, 1> instead of <0, 4, 1, 5>. 5405 static bool isVZIP_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult){ 5406 unsigned EltSz = VT.getVectorElementType().getSizeInBits(); 5407 if (EltSz == 64) 5408 return false; 5409 5410 unsigned NumElts = VT.getVectorNumElements(); 5411 if (M.size() != NumElts && M.size() != NumElts*2) 5412 return false; 5413 5414 for (unsigned i = 0; i < M.size(); i += NumElts) { 5415 WhichResult = M[i] == 0 ? 0 : 1; 5416 unsigned Idx = WhichResult * NumElts / 2; 5417 for (unsigned j = 0; j < NumElts; j += 2) { 5418 if ((M[i+j] >= 0 && (unsigned) M[i+j] != Idx) || 5419 (M[i+j+1] >= 0 && (unsigned) M[i+j+1] != Idx)) 5420 return false; 5421 Idx += 1; 5422 } 5423 } 5424 5425 if (M.size() == NumElts*2) 5426 WhichResult = 0; 5427 5428 // VZIP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32. 5429 if (VT.is64BitVector() && EltSz == 32) 5430 return false; 5431 5432 return true; 5433 } 5434 5435 /// Check if \p ShuffleMask is a NEON two-result shuffle (VZIP, VUZP, VTRN), 5436 /// and return the corresponding ARMISD opcode if it is, or 0 if it isn't. 5437 static unsigned isNEONTwoResultShuffleMask(ArrayRef<int> ShuffleMask, EVT VT, 5438 unsigned &WhichResult, 5439 bool &isV_UNDEF) { 5440 isV_UNDEF = false; 5441 if (isVTRNMask(ShuffleMask, VT, WhichResult)) 5442 return ARMISD::VTRN; 5443 if (isVUZPMask(ShuffleMask, VT, WhichResult)) 5444 return ARMISD::VUZP; 5445 if (isVZIPMask(ShuffleMask, VT, WhichResult)) 5446 return ARMISD::VZIP; 5447 5448 isV_UNDEF = true; 5449 if (isVTRN_v_undef_Mask(ShuffleMask, VT, WhichResult)) 5450 return ARMISD::VTRN; 5451 if (isVUZP_v_undef_Mask(ShuffleMask, VT, WhichResult)) 5452 return ARMISD::VUZP; 5453 if (isVZIP_v_undef_Mask(ShuffleMask, VT, WhichResult)) 5454 return ARMISD::VZIP; 5455 5456 return 0; 5457 } 5458 5459 /// \return true if this is a reverse operation on an vector. 5460 static bool isReverseMask(ArrayRef<int> M, EVT VT) { 5461 unsigned NumElts = VT.getVectorNumElements(); 5462 // Make sure the mask has the right size. 5463 if (NumElts != M.size()) 5464 return false; 5465 5466 // Look for <15, ..., 3, -1, 1, 0>. 5467 for (unsigned i = 0; i != NumElts; ++i) 5468 if (M[i] >= 0 && M[i] != (int) (NumElts - 1 - i)) 5469 return false; 5470 5471 return true; 5472 } 5473 5474 // If N is an integer constant that can be moved into a register in one 5475 // instruction, return an SDValue of such a constant (will become a MOV 5476 // instruction). Otherwise return null. 5477 static SDValue IsSingleInstrConstant(SDValue N, SelectionDAG &DAG, 5478 const ARMSubtarget *ST, SDLoc dl) { 5479 uint64_t Val; 5480 if (!isa<ConstantSDNode>(N)) 5481 return SDValue(); 5482 Val = cast<ConstantSDNode>(N)->getZExtValue(); 5483 5484 if (ST->isThumb1Only()) { 5485 if (Val <= 255 || ~Val <= 255) 5486 return DAG.getConstant(Val, dl, MVT::i32); 5487 } else { 5488 if (ARM_AM::getSOImmVal(Val) != -1 || ARM_AM::getSOImmVal(~Val) != -1) 5489 return DAG.getConstant(Val, dl, MVT::i32); 5490 } 5491 return SDValue(); 5492 } 5493 5494 // If this is a case we can't handle, return null and let the default 5495 // expansion code take care of it. 5496 SDValue ARMTargetLowering::LowerBUILD_VECTOR(SDValue Op, SelectionDAG &DAG, 5497 const ARMSubtarget *ST) const { 5498 BuildVectorSDNode *BVN = cast<BuildVectorSDNode>(Op.getNode()); 5499 SDLoc dl(Op); 5500 EVT VT = Op.getValueType(); 5501 5502 APInt SplatBits, SplatUndef; 5503 unsigned SplatBitSize; 5504 bool HasAnyUndefs; 5505 if (BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs)) { 5506 if (SplatBitSize <= 64) { 5507 // Check if an immediate VMOV works. 5508 EVT VmovVT; 5509 SDValue Val = isNEONModifiedImm(SplatBits.getZExtValue(), 5510 SplatUndef.getZExtValue(), SplatBitSize, 5511 DAG, dl, VmovVT, VT.is128BitVector(), 5512 VMOVModImm); 5513 if (Val.getNode()) { 5514 SDValue Vmov = DAG.getNode(ARMISD::VMOVIMM, dl, VmovVT, Val); 5515 return DAG.getNode(ISD::BITCAST, dl, VT, Vmov); 5516 } 5517 5518 // Try an immediate VMVN. 5519 uint64_t NegatedImm = (~SplatBits).getZExtValue(); 5520 Val = isNEONModifiedImm(NegatedImm, 5521 SplatUndef.getZExtValue(), SplatBitSize, 5522 DAG, dl, VmovVT, VT.is128BitVector(), 5523 VMVNModImm); 5524 if (Val.getNode()) { 5525 SDValue Vmov = DAG.getNode(ARMISD::VMVNIMM, dl, VmovVT, Val); 5526 return DAG.getNode(ISD::BITCAST, dl, VT, Vmov); 5527 } 5528 5529 // Use vmov.f32 to materialize other v2f32 and v4f32 splats. 5530 if ((VT == MVT::v2f32 || VT == MVT::v4f32) && SplatBitSize == 32) { 5531 int ImmVal = ARM_AM::getFP32Imm(SplatBits); 5532 if (ImmVal != -1) { 5533 SDValue Val = DAG.getTargetConstant(ImmVal, dl, MVT::i32); 5534 return DAG.getNode(ARMISD::VMOVFPIMM, dl, VT, Val); 5535 } 5536 } 5537 } 5538 } 5539 5540 // Scan through the operands to see if only one value is used. 5541 // 5542 // As an optimisation, even if more than one value is used it may be more 5543 // profitable to splat with one value then change some lanes. 5544 // 5545 // Heuristically we decide to do this if the vector has a "dominant" value, 5546 // defined as splatted to more than half of the lanes. 5547 unsigned NumElts = VT.getVectorNumElements(); 5548 bool isOnlyLowElement = true; 5549 bool usesOnlyOneValue = true; 5550 bool hasDominantValue = false; 5551 bool isConstant = true; 5552 5553 // Map of the number of times a particular SDValue appears in the 5554 // element list. 5555 DenseMap<SDValue, unsigned> ValueCounts; 5556 SDValue Value; 5557 for (unsigned i = 0; i < NumElts; ++i) { 5558 SDValue V = Op.getOperand(i); 5559 if (V.getOpcode() == ISD::UNDEF) 5560 continue; 5561 if (i > 0) 5562 isOnlyLowElement = false; 5563 if (!isa<ConstantFPSDNode>(V) && !isa<ConstantSDNode>(V)) 5564 isConstant = false; 5565 5566 ValueCounts.insert(std::make_pair(V, 0)); 5567 unsigned &Count = ValueCounts[V]; 5568 5569 // Is this value dominant? (takes up more than half of the lanes) 5570 if (++Count > (NumElts / 2)) { 5571 hasDominantValue = true; 5572 Value = V; 5573 } 5574 } 5575 if (ValueCounts.size() != 1) 5576 usesOnlyOneValue = false; 5577 if (!Value.getNode() && ValueCounts.size() > 0) 5578 Value = ValueCounts.begin()->first; 5579 5580 if (ValueCounts.size() == 0) 5581 return DAG.getUNDEF(VT); 5582 5583 // Loads are better lowered with insert_vector_elt/ARMISD::BUILD_VECTOR. 5584 // Keep going if we are hitting this case. 5585 if (isOnlyLowElement && !ISD::isNormalLoad(Value.getNode())) 5586 return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Value); 5587 5588 unsigned EltSize = VT.getVectorElementType().getSizeInBits(); 5589 5590 // Use VDUP for non-constant splats. For f32 constant splats, reduce to 5591 // i32 and try again. 5592 if (hasDominantValue && EltSize <= 32) { 5593 if (!isConstant) { 5594 SDValue N; 5595 5596 // If we are VDUPing a value that comes directly from a vector, that will 5597 // cause an unnecessary move to and from a GPR, where instead we could 5598 // just use VDUPLANE. We can only do this if the lane being extracted 5599 // is at a constant index, as the VDUP from lane instructions only have 5600 // constant-index forms. 5601 ConstantSDNode *constIndex; 5602 if (Value->getOpcode() == ISD::EXTRACT_VECTOR_ELT && 5603 (constIndex = dyn_cast<ConstantSDNode>(Value->getOperand(1)))) { 5604 // We need to create a new undef vector to use for the VDUPLANE if the 5605 // size of the vector from which we get the value is different than the 5606 // size of the vector that we need to create. We will insert the element 5607 // such that the register coalescer will remove unnecessary copies. 5608 if (VT != Value->getOperand(0).getValueType()) { 5609 unsigned index = constIndex->getAPIntValue().getLimitedValue() % 5610 VT.getVectorNumElements(); 5611 N = DAG.getNode(ARMISD::VDUPLANE, dl, VT, 5612 DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, DAG.getUNDEF(VT), 5613 Value, DAG.getConstant(index, dl, MVT::i32)), 5614 DAG.getConstant(index, dl, MVT::i32)); 5615 } else 5616 N = DAG.getNode(ARMISD::VDUPLANE, dl, VT, 5617 Value->getOperand(0), Value->getOperand(1)); 5618 } else 5619 N = DAG.getNode(ARMISD::VDUP, dl, VT, Value); 5620 5621 if (!usesOnlyOneValue) { 5622 // The dominant value was splatted as 'N', but we now have to insert 5623 // all differing elements. 5624 for (unsigned I = 0; I < NumElts; ++I) { 5625 if (Op.getOperand(I) == Value) 5626 continue; 5627 SmallVector<SDValue, 3> Ops; 5628 Ops.push_back(N); 5629 Ops.push_back(Op.getOperand(I)); 5630 Ops.push_back(DAG.getConstant(I, dl, MVT::i32)); 5631 N = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Ops); 5632 } 5633 } 5634 return N; 5635 } 5636 if (VT.getVectorElementType().isFloatingPoint()) { 5637 SmallVector<SDValue, 8> Ops; 5638 for (unsigned i = 0; i < NumElts; ++i) 5639 Ops.push_back(DAG.getNode(ISD::BITCAST, dl, MVT::i32, 5640 Op.getOperand(i))); 5641 EVT VecVT = EVT::getVectorVT(*DAG.getContext(), MVT::i32, NumElts); 5642 SDValue Val = DAG.getNode(ISD::BUILD_VECTOR, dl, VecVT, Ops); 5643 Val = LowerBUILD_VECTOR(Val, DAG, ST); 5644 if (Val.getNode()) 5645 return DAG.getNode(ISD::BITCAST, dl, VT, Val); 5646 } 5647 if (usesOnlyOneValue) { 5648 SDValue Val = IsSingleInstrConstant(Value, DAG, ST, dl); 5649 if (isConstant && Val.getNode()) 5650 return DAG.getNode(ARMISD::VDUP, dl, VT, Val); 5651 } 5652 } 5653 5654 // If all elements are constants and the case above didn't get hit, fall back 5655 // to the default expansion, which will generate a load from the constant 5656 // pool. 5657 if (isConstant) 5658 return SDValue(); 5659 5660 // Empirical tests suggest this is rarely worth it for vectors of length <= 2. 5661 if (NumElts >= 4) { 5662 SDValue shuffle = ReconstructShuffle(Op, DAG); 5663 if (shuffle != SDValue()) 5664 return shuffle; 5665 } 5666 5667 // Vectors with 32- or 64-bit elements can be built by directly assigning 5668 // the subregisters. Lower it to an ARMISD::BUILD_VECTOR so the operands 5669 // will be legalized. 5670 if (EltSize >= 32) { 5671 // Do the expansion with floating-point types, since that is what the VFP 5672 // registers are defined to use, and since i64 is not legal. 5673 EVT EltVT = EVT::getFloatingPointVT(EltSize); 5674 EVT VecVT = EVT::getVectorVT(*DAG.getContext(), EltVT, NumElts); 5675 SmallVector<SDValue, 8> Ops; 5676 for (unsigned i = 0; i < NumElts; ++i) 5677 Ops.push_back(DAG.getNode(ISD::BITCAST, dl, EltVT, Op.getOperand(i))); 5678 SDValue Val = DAG.getNode(ARMISD::BUILD_VECTOR, dl, VecVT, Ops); 5679 return DAG.getNode(ISD::BITCAST, dl, VT, Val); 5680 } 5681 5682 // If all else fails, just use a sequence of INSERT_VECTOR_ELT when we 5683 // know the default expansion would otherwise fall back on something even 5684 // worse. For a vector with one or two non-undef values, that's 5685 // scalar_to_vector for the elements followed by a shuffle (provided the 5686 // shuffle is valid for the target) and materialization element by element 5687 // on the stack followed by a load for everything else. 5688 if (!isConstant && !usesOnlyOneValue) { 5689 SDValue Vec = DAG.getUNDEF(VT); 5690 for (unsigned i = 0 ; i < NumElts; ++i) { 5691 SDValue V = Op.getOperand(i); 5692 if (V.getOpcode() == ISD::UNDEF) 5693 continue; 5694 SDValue LaneIdx = DAG.getConstant(i, dl, MVT::i32); 5695 Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Vec, V, LaneIdx); 5696 } 5697 return Vec; 5698 } 5699 5700 return SDValue(); 5701 } 5702 5703 // Gather data to see if the operation can be modelled as a 5704 // shuffle in combination with VEXTs. 5705 SDValue ARMTargetLowering::ReconstructShuffle(SDValue Op, 5706 SelectionDAG &DAG) const { 5707 assert(Op.getOpcode() == ISD::BUILD_VECTOR && "Unknown opcode!"); 5708 SDLoc dl(Op); 5709 EVT VT = Op.getValueType(); 5710 unsigned NumElts = VT.getVectorNumElements(); 5711 5712 struct ShuffleSourceInfo { 5713 SDValue Vec; 5714 unsigned MinElt; 5715 unsigned MaxElt; 5716 5717 // We may insert some combination of BITCASTs and VEXT nodes to force Vec to 5718 // be compatible with the shuffle we intend to construct. As a result 5719 // ShuffleVec will be some sliding window into the original Vec. 5720 SDValue ShuffleVec; 5721 5722 // Code should guarantee that element i in Vec starts at element "WindowBase 5723 // + i * WindowScale in ShuffleVec". 5724 int WindowBase; 5725 int WindowScale; 5726 5727 bool operator ==(SDValue OtherVec) { return Vec == OtherVec; } 5728 ShuffleSourceInfo(SDValue Vec) 5729 : Vec(Vec), MinElt(UINT_MAX), MaxElt(0), ShuffleVec(Vec), WindowBase(0), 5730 WindowScale(1) {} 5731 }; 5732 5733 // First gather all vectors used as an immediate source for this BUILD_VECTOR 5734 // node. 5735 SmallVector<ShuffleSourceInfo, 2> Sources; 5736 for (unsigned i = 0; i < NumElts; ++i) { 5737 SDValue V = Op.getOperand(i); 5738 if (V.getOpcode() == ISD::UNDEF) 5739 continue; 5740 else if (V.getOpcode() != ISD::EXTRACT_VECTOR_ELT) { 5741 // A shuffle can only come from building a vector from various 5742 // elements of other vectors. 5743 return SDValue(); 5744 } else if (!isa<ConstantSDNode>(V.getOperand(1))) { 5745 // Furthermore, shuffles require a constant mask, whereas extractelts 5746 // accept variable indices. 5747 return SDValue(); 5748 } 5749 5750 // Add this element source to the list if it's not already there. 5751 SDValue SourceVec = V.getOperand(0); 5752 auto Source = std::find(Sources.begin(), Sources.end(), SourceVec); 5753 if (Source == Sources.end()) 5754 Source = Sources.insert(Sources.end(), ShuffleSourceInfo(SourceVec)); 5755 5756 // Update the minimum and maximum lane number seen. 5757 unsigned EltNo = cast<ConstantSDNode>(V.getOperand(1))->getZExtValue(); 5758 Source->MinElt = std::min(Source->MinElt, EltNo); 5759 Source->MaxElt = std::max(Source->MaxElt, EltNo); 5760 } 5761 5762 // Currently only do something sane when at most two source vectors 5763 // are involved. 5764 if (Sources.size() > 2) 5765 return SDValue(); 5766 5767 // Find out the smallest element size among result and two sources, and use 5768 // it as element size to build the shuffle_vector. 5769 EVT SmallestEltTy = VT.getVectorElementType(); 5770 for (auto &Source : Sources) { 5771 EVT SrcEltTy = Source.Vec.getValueType().getVectorElementType(); 5772 if (SrcEltTy.bitsLT(SmallestEltTy)) 5773 SmallestEltTy = SrcEltTy; 5774 } 5775 unsigned ResMultiplier = 5776 VT.getVectorElementType().getSizeInBits() / SmallestEltTy.getSizeInBits(); 5777 NumElts = VT.getSizeInBits() / SmallestEltTy.getSizeInBits(); 5778 EVT ShuffleVT = EVT::getVectorVT(*DAG.getContext(), SmallestEltTy, NumElts); 5779 5780 // If the source vector is too wide or too narrow, we may nevertheless be able 5781 // to construct a compatible shuffle either by concatenating it with UNDEF or 5782 // extracting a suitable range of elements. 5783 for (auto &Src : Sources) { 5784 EVT SrcVT = Src.ShuffleVec.getValueType(); 5785 5786 if (SrcVT.getSizeInBits() == VT.getSizeInBits()) 5787 continue; 5788 5789 // This stage of the search produces a source with the same element type as 5790 // the original, but with a total width matching the BUILD_VECTOR output. 5791 EVT EltVT = SrcVT.getVectorElementType(); 5792 unsigned NumSrcElts = VT.getSizeInBits() / EltVT.getSizeInBits(); 5793 EVT DestVT = EVT::getVectorVT(*DAG.getContext(), EltVT, NumSrcElts); 5794 5795 if (SrcVT.getSizeInBits() < VT.getSizeInBits()) { 5796 if (2 * SrcVT.getSizeInBits() != VT.getSizeInBits()) 5797 return SDValue(); 5798 // We can pad out the smaller vector for free, so if it's part of a 5799 // shuffle... 5800 Src.ShuffleVec = 5801 DAG.getNode(ISD::CONCAT_VECTORS, dl, DestVT, Src.ShuffleVec, 5802 DAG.getUNDEF(Src.ShuffleVec.getValueType())); 5803 continue; 5804 } 5805 5806 if (SrcVT.getSizeInBits() != 2 * VT.getSizeInBits()) 5807 return SDValue(); 5808 5809 if (Src.MaxElt - Src.MinElt >= NumSrcElts) { 5810 // Span too large for a VEXT to cope 5811 return SDValue(); 5812 } 5813 5814 if (Src.MinElt >= NumSrcElts) { 5815 // The extraction can just take the second half 5816 Src.ShuffleVec = 5817 DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DestVT, Src.ShuffleVec, 5818 DAG.getConstant(NumSrcElts, dl, MVT::i32)); 5819 Src.WindowBase = -NumSrcElts; 5820 } else if (Src.MaxElt < NumSrcElts) { 5821 // The extraction can just take the first half 5822 Src.ShuffleVec = 5823 DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DestVT, Src.ShuffleVec, 5824 DAG.getConstant(0, dl, MVT::i32)); 5825 } else { 5826 // An actual VEXT is needed 5827 SDValue VEXTSrc1 = 5828 DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DestVT, Src.ShuffleVec, 5829 DAG.getConstant(0, dl, MVT::i32)); 5830 SDValue VEXTSrc2 = 5831 DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DestVT, Src.ShuffleVec, 5832 DAG.getConstant(NumSrcElts, dl, MVT::i32)); 5833 5834 Src.ShuffleVec = DAG.getNode(ARMISD::VEXT, dl, DestVT, VEXTSrc1, 5835 VEXTSrc2, 5836 DAG.getConstant(Src.MinElt, dl, MVT::i32)); 5837 Src.WindowBase = -Src.MinElt; 5838 } 5839 } 5840 5841 // Another possible incompatibility occurs from the vector element types. We 5842 // can fix this by bitcasting the source vectors to the same type we intend 5843 // for the shuffle. 5844 for (auto &Src : Sources) { 5845 EVT SrcEltTy = Src.ShuffleVec.getValueType().getVectorElementType(); 5846 if (SrcEltTy == SmallestEltTy) 5847 continue; 5848 assert(ShuffleVT.getVectorElementType() == SmallestEltTy); 5849 Src.ShuffleVec = DAG.getNode(ISD::BITCAST, dl, ShuffleVT, Src.ShuffleVec); 5850 Src.WindowScale = SrcEltTy.getSizeInBits() / SmallestEltTy.getSizeInBits(); 5851 Src.WindowBase *= Src.WindowScale; 5852 } 5853 5854 // Final sanity check before we try to actually produce a shuffle. 5855 DEBUG( 5856 for (auto Src : Sources) 5857 assert(Src.ShuffleVec.getValueType() == ShuffleVT); 5858 ); 5859 5860 // The stars all align, our next step is to produce the mask for the shuffle. 5861 SmallVector<int, 8> Mask(ShuffleVT.getVectorNumElements(), -1); 5862 int BitsPerShuffleLane = ShuffleVT.getVectorElementType().getSizeInBits(); 5863 for (unsigned i = 0; i < VT.getVectorNumElements(); ++i) { 5864 SDValue Entry = Op.getOperand(i); 5865 if (Entry.getOpcode() == ISD::UNDEF) 5866 continue; 5867 5868 auto Src = std::find(Sources.begin(), Sources.end(), Entry.getOperand(0)); 5869 int EltNo = cast<ConstantSDNode>(Entry.getOperand(1))->getSExtValue(); 5870 5871 // EXTRACT_VECTOR_ELT performs an implicit any_ext; BUILD_VECTOR an implicit 5872 // trunc. So only std::min(SrcBits, DestBits) actually get defined in this 5873 // segment. 5874 EVT OrigEltTy = Entry.getOperand(0).getValueType().getVectorElementType(); 5875 int BitsDefined = std::min(OrigEltTy.getSizeInBits(), 5876 VT.getVectorElementType().getSizeInBits()); 5877 int LanesDefined = BitsDefined / BitsPerShuffleLane; 5878 5879 // This source is expected to fill ResMultiplier lanes of the final shuffle, 5880 // starting at the appropriate offset. 5881 int *LaneMask = &Mask[i * ResMultiplier]; 5882 5883 int ExtractBase = EltNo * Src->WindowScale + Src->WindowBase; 5884 ExtractBase += NumElts * (Src - Sources.begin()); 5885 for (int j = 0; j < LanesDefined; ++j) 5886 LaneMask[j] = ExtractBase + j; 5887 } 5888 5889 // Final check before we try to produce nonsense... 5890 if (!isShuffleMaskLegal(Mask, ShuffleVT)) 5891 return SDValue(); 5892 5893 // We can't handle more than two sources. This should have already 5894 // been checked before this point. 5895 assert(Sources.size() <= 2 && "Too many sources!"); 5896 5897 SDValue ShuffleOps[] = { DAG.getUNDEF(ShuffleVT), DAG.getUNDEF(ShuffleVT) }; 5898 for (unsigned i = 0; i < Sources.size(); ++i) 5899 ShuffleOps[i] = Sources[i].ShuffleVec; 5900 5901 SDValue Shuffle = DAG.getVectorShuffle(ShuffleVT, dl, ShuffleOps[0], 5902 ShuffleOps[1], &Mask[0]); 5903 return DAG.getNode(ISD::BITCAST, dl, VT, Shuffle); 5904 } 5905 5906 /// isShuffleMaskLegal - Targets can use this to indicate that they only 5907 /// support *some* VECTOR_SHUFFLE operations, those with specific masks. 5908 /// By default, if a target supports the VECTOR_SHUFFLE node, all mask values 5909 /// are assumed to be legal. 5910 bool 5911 ARMTargetLowering::isShuffleMaskLegal(const SmallVectorImpl<int> &M, 5912 EVT VT) const { 5913 if (VT.getVectorNumElements() == 4 && 5914 (VT.is128BitVector() || VT.is64BitVector())) { 5915 unsigned PFIndexes[4]; 5916 for (unsigned i = 0; i != 4; ++i) { 5917 if (M[i] < 0) 5918 PFIndexes[i] = 8; 5919 else 5920 PFIndexes[i] = M[i]; 5921 } 5922 5923 // Compute the index in the perfect shuffle table. 5924 unsigned PFTableIndex = 5925 PFIndexes[0]*9*9*9+PFIndexes[1]*9*9+PFIndexes[2]*9+PFIndexes[3]; 5926 unsigned PFEntry = PerfectShuffleTable[PFTableIndex]; 5927 unsigned Cost = (PFEntry >> 30); 5928 5929 if (Cost <= 4) 5930 return true; 5931 } 5932 5933 bool ReverseVEXT, isV_UNDEF; 5934 unsigned Imm, WhichResult; 5935 5936 unsigned EltSize = VT.getVectorElementType().getSizeInBits(); 5937 return (EltSize >= 32 || 5938 ShuffleVectorSDNode::isSplatMask(&M[0], VT) || 5939 isVREVMask(M, VT, 64) || 5940 isVREVMask(M, VT, 32) || 5941 isVREVMask(M, VT, 16) || 5942 isVEXTMask(M, VT, ReverseVEXT, Imm) || 5943 isVTBLMask(M, VT) || 5944 isNEONTwoResultShuffleMask(M, VT, WhichResult, isV_UNDEF) || 5945 ((VT == MVT::v8i16 || VT == MVT::v16i8) && isReverseMask(M, VT))); 5946 } 5947 5948 /// GeneratePerfectShuffle - Given an entry in the perfect-shuffle table, emit 5949 /// the specified operations to build the shuffle. 5950 static SDValue GeneratePerfectShuffle(unsigned PFEntry, SDValue LHS, 5951 SDValue RHS, SelectionDAG &DAG, 5952 SDLoc dl) { 5953 unsigned OpNum = (PFEntry >> 26) & 0x0F; 5954 unsigned LHSID = (PFEntry >> 13) & ((1 << 13)-1); 5955 unsigned RHSID = (PFEntry >> 0) & ((1 << 13)-1); 5956 5957 enum { 5958 OP_COPY = 0, // Copy, used for things like <u,u,u,3> to say it is <0,1,2,3> 5959 OP_VREV, 5960 OP_VDUP0, 5961 OP_VDUP1, 5962 OP_VDUP2, 5963 OP_VDUP3, 5964 OP_VEXT1, 5965 OP_VEXT2, 5966 OP_VEXT3, 5967 OP_VUZPL, // VUZP, left result 5968 OP_VUZPR, // VUZP, right result 5969 OP_VZIPL, // VZIP, left result 5970 OP_VZIPR, // VZIP, right result 5971 OP_VTRNL, // VTRN, left result 5972 OP_VTRNR // VTRN, right result 5973 }; 5974 5975 if (OpNum == OP_COPY) { 5976 if (LHSID == (1*9+2)*9+3) return LHS; 5977 assert(LHSID == ((4*9+5)*9+6)*9+7 && "Illegal OP_COPY!"); 5978 return RHS; 5979 } 5980 5981 SDValue OpLHS, OpRHS; 5982 OpLHS = GeneratePerfectShuffle(PerfectShuffleTable[LHSID], LHS, RHS, DAG, dl); 5983 OpRHS = GeneratePerfectShuffle(PerfectShuffleTable[RHSID], LHS, RHS, DAG, dl); 5984 EVT VT = OpLHS.getValueType(); 5985 5986 switch (OpNum) { 5987 default: llvm_unreachable("Unknown shuffle opcode!"); 5988 case OP_VREV: 5989 // VREV divides the vector in half and swaps within the half. 5990 if (VT.getVectorElementType() == MVT::i32 || 5991 VT.getVectorElementType() == MVT::f32) 5992 return DAG.getNode(ARMISD::VREV64, dl, VT, OpLHS); 5993 // vrev <4 x i16> -> VREV32 5994 if (VT.getVectorElementType() == MVT::i16) 5995 return DAG.getNode(ARMISD::VREV32, dl, VT, OpLHS); 5996 // vrev <4 x i8> -> VREV16 5997 assert(VT.getVectorElementType() == MVT::i8); 5998 return DAG.getNode(ARMISD::VREV16, dl, VT, OpLHS); 5999 case OP_VDUP0: 6000 case OP_VDUP1: 6001 case OP_VDUP2: 6002 case OP_VDUP3: 6003 return DAG.getNode(ARMISD::VDUPLANE, dl, VT, 6004 OpLHS, DAG.getConstant(OpNum-OP_VDUP0, dl, MVT::i32)); 6005 case OP_VEXT1: 6006 case OP_VEXT2: 6007 case OP_VEXT3: 6008 return DAG.getNode(ARMISD::VEXT, dl, VT, 6009 OpLHS, OpRHS, 6010 DAG.getConstant(OpNum - OP_VEXT1 + 1, dl, MVT::i32)); 6011 case OP_VUZPL: 6012 case OP_VUZPR: 6013 return DAG.getNode(ARMISD::VUZP, dl, DAG.getVTList(VT, VT), 6014 OpLHS, OpRHS).getValue(OpNum-OP_VUZPL); 6015 case OP_VZIPL: 6016 case OP_VZIPR: 6017 return DAG.getNode(ARMISD::VZIP, dl, DAG.getVTList(VT, VT), 6018 OpLHS, OpRHS).getValue(OpNum-OP_VZIPL); 6019 case OP_VTRNL: 6020 case OP_VTRNR: 6021 return DAG.getNode(ARMISD::VTRN, dl, DAG.getVTList(VT, VT), 6022 OpLHS, OpRHS).getValue(OpNum-OP_VTRNL); 6023 } 6024 } 6025 6026 static SDValue LowerVECTOR_SHUFFLEv8i8(SDValue Op, 6027 ArrayRef<int> ShuffleMask, 6028 SelectionDAG &DAG) { 6029 // Check to see if we can use the VTBL instruction. 6030 SDValue V1 = Op.getOperand(0); 6031 SDValue V2 = Op.getOperand(1); 6032 SDLoc DL(Op); 6033 6034 SmallVector<SDValue, 8> VTBLMask; 6035 for (ArrayRef<int>::iterator 6036 I = ShuffleMask.begin(), E = ShuffleMask.end(); I != E; ++I) 6037 VTBLMask.push_back(DAG.getConstant(*I, DL, MVT::i32)); 6038 6039 if (V2.getNode()->getOpcode() == ISD::UNDEF) 6040 return DAG.getNode(ARMISD::VTBL1, DL, MVT::v8i8, V1, 6041 DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v8i8, VTBLMask)); 6042 6043 return DAG.getNode(ARMISD::VTBL2, DL, MVT::v8i8, V1, V2, 6044 DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v8i8, VTBLMask)); 6045 } 6046 6047 static SDValue LowerReverse_VECTOR_SHUFFLEv16i8_v8i16(SDValue Op, 6048 SelectionDAG &DAG) { 6049 SDLoc DL(Op); 6050 SDValue OpLHS = Op.getOperand(0); 6051 EVT VT = OpLHS.getValueType(); 6052 6053 assert((VT == MVT::v8i16 || VT == MVT::v16i8) && 6054 "Expect an v8i16/v16i8 type"); 6055 OpLHS = DAG.getNode(ARMISD::VREV64, DL, VT, OpLHS); 6056 // For a v16i8 type: After the VREV, we have got <8, ...15, 8, ..., 0>. Now, 6057 // extract the first 8 bytes into the top double word and the last 8 bytes 6058 // into the bottom double word. The v8i16 case is similar. 6059 unsigned ExtractNum = (VT == MVT::v16i8) ? 8 : 4; 6060 return DAG.getNode(ARMISD::VEXT, DL, VT, OpLHS, OpLHS, 6061 DAG.getConstant(ExtractNum, DL, MVT::i32)); 6062 } 6063 6064 static SDValue LowerVECTOR_SHUFFLE(SDValue Op, SelectionDAG &DAG) { 6065 SDValue V1 = Op.getOperand(0); 6066 SDValue V2 = Op.getOperand(1); 6067 SDLoc dl(Op); 6068 EVT VT = Op.getValueType(); 6069 ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(Op.getNode()); 6070 6071 // Convert shuffles that are directly supported on NEON to target-specific 6072 // DAG nodes, instead of keeping them as shuffles and matching them again 6073 // during code selection. This is more efficient and avoids the possibility 6074 // of inconsistencies between legalization and selection. 6075 // FIXME: floating-point vectors should be canonicalized to integer vectors 6076 // of the same time so that they get CSEd properly. 6077 ArrayRef<int> ShuffleMask = SVN->getMask(); 6078 6079 unsigned EltSize = VT.getVectorElementType().getSizeInBits(); 6080 if (EltSize <= 32) { 6081 if (ShuffleVectorSDNode::isSplatMask(&ShuffleMask[0], VT)) { 6082 int Lane = SVN->getSplatIndex(); 6083 // If this is undef splat, generate it via "just" vdup, if possible. 6084 if (Lane == -1) Lane = 0; 6085 6086 // Test if V1 is a SCALAR_TO_VECTOR. 6087 if (Lane == 0 && V1.getOpcode() == ISD::SCALAR_TO_VECTOR) { 6088 return DAG.getNode(ARMISD::VDUP, dl, VT, V1.getOperand(0)); 6089 } 6090 // Test if V1 is a BUILD_VECTOR which is equivalent to a SCALAR_TO_VECTOR 6091 // (and probably will turn into a SCALAR_TO_VECTOR once legalization 6092 // reaches it). 6093 if (Lane == 0 && V1.getOpcode() == ISD::BUILD_VECTOR && 6094 !isa<ConstantSDNode>(V1.getOperand(0))) { 6095 bool IsScalarToVector = true; 6096 for (unsigned i = 1, e = V1.getNumOperands(); i != e; ++i) 6097 if (V1.getOperand(i).getOpcode() != ISD::UNDEF) { 6098 IsScalarToVector = false; 6099 break; 6100 } 6101 if (IsScalarToVector) 6102 return DAG.getNode(ARMISD::VDUP, dl, VT, V1.getOperand(0)); 6103 } 6104 return DAG.getNode(ARMISD::VDUPLANE, dl, VT, V1, 6105 DAG.getConstant(Lane, dl, MVT::i32)); 6106 } 6107 6108 bool ReverseVEXT; 6109 unsigned Imm; 6110 if (isVEXTMask(ShuffleMask, VT, ReverseVEXT, Imm)) { 6111 if (ReverseVEXT) 6112 std::swap(V1, V2); 6113 return DAG.getNode(ARMISD::VEXT, dl, VT, V1, V2, 6114 DAG.getConstant(Imm, dl, MVT::i32)); 6115 } 6116 6117 if (isVREVMask(ShuffleMask, VT, 64)) 6118 return DAG.getNode(ARMISD::VREV64, dl, VT, V1); 6119 if (isVREVMask(ShuffleMask, VT, 32)) 6120 return DAG.getNode(ARMISD::VREV32, dl, VT, V1); 6121 if (isVREVMask(ShuffleMask, VT, 16)) 6122 return DAG.getNode(ARMISD::VREV16, dl, VT, V1); 6123 6124 if (V2->getOpcode() == ISD::UNDEF && 6125 isSingletonVEXTMask(ShuffleMask, VT, Imm)) { 6126 return DAG.getNode(ARMISD::VEXT, dl, VT, V1, V1, 6127 DAG.getConstant(Imm, dl, MVT::i32)); 6128 } 6129 6130 // Check for Neon shuffles that modify both input vectors in place. 6131 // If both results are used, i.e., if there are two shuffles with the same 6132 // source operands and with masks corresponding to both results of one of 6133 // these operations, DAG memoization will ensure that a single node is 6134 // used for both shuffles. 6135 unsigned WhichResult; 6136 bool isV_UNDEF; 6137 if (unsigned ShuffleOpc = isNEONTwoResultShuffleMask( 6138 ShuffleMask, VT, WhichResult, isV_UNDEF)) { 6139 if (isV_UNDEF) 6140 V2 = V1; 6141 return DAG.getNode(ShuffleOpc, dl, DAG.getVTList(VT, VT), V1, V2) 6142 .getValue(WhichResult); 6143 } 6144 6145 // Also check for these shuffles through CONCAT_VECTORS: we canonicalize 6146 // shuffles that produce a result larger than their operands with: 6147 // shuffle(concat(v1, undef), concat(v2, undef)) 6148 // -> 6149 // shuffle(concat(v1, v2), undef) 6150 // because we can access quad vectors (see PerformVECTOR_SHUFFLECombine). 6151 // 6152 // This is useful in the general case, but there are special cases where 6153 // native shuffles produce larger results: the two-result ops. 6154 // 6155 // Look through the concat when lowering them: 6156 // shuffle(concat(v1, v2), undef) 6157 // -> 6158 // concat(VZIP(v1, v2):0, :1) 6159 // 6160 if (V1->getOpcode() == ISD::CONCAT_VECTORS && 6161 V2->getOpcode() == ISD::UNDEF) { 6162 SDValue SubV1 = V1->getOperand(0); 6163 SDValue SubV2 = V1->getOperand(1); 6164 EVT SubVT = SubV1.getValueType(); 6165 6166 // We expect these to have been canonicalized to -1. 6167 assert(std::all_of(ShuffleMask.begin(), ShuffleMask.end(), [&](int i) { 6168 return i < (int)VT.getVectorNumElements(); 6169 }) && "Unexpected shuffle index into UNDEF operand!"); 6170 6171 if (unsigned ShuffleOpc = isNEONTwoResultShuffleMask( 6172 ShuffleMask, SubVT, WhichResult, isV_UNDEF)) { 6173 if (isV_UNDEF) 6174 SubV2 = SubV1; 6175 assert((WhichResult == 0) && 6176 "In-place shuffle of concat can only have one result!"); 6177 SDValue Res = DAG.getNode(ShuffleOpc, dl, DAG.getVTList(SubVT, SubVT), 6178 SubV1, SubV2); 6179 return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, Res.getValue(0), 6180 Res.getValue(1)); 6181 } 6182 } 6183 } 6184 6185 // If the shuffle is not directly supported and it has 4 elements, use 6186 // the PerfectShuffle-generated table to synthesize it from other shuffles. 6187 unsigned NumElts = VT.getVectorNumElements(); 6188 if (NumElts == 4) { 6189 unsigned PFIndexes[4]; 6190 for (unsigned i = 0; i != 4; ++i) { 6191 if (ShuffleMask[i] < 0) 6192 PFIndexes[i] = 8; 6193 else 6194 PFIndexes[i] = ShuffleMask[i]; 6195 } 6196 6197 // Compute the index in the perfect shuffle table. 6198 unsigned PFTableIndex = 6199 PFIndexes[0]*9*9*9+PFIndexes[1]*9*9+PFIndexes[2]*9+PFIndexes[3]; 6200 unsigned PFEntry = PerfectShuffleTable[PFTableIndex]; 6201 unsigned Cost = (PFEntry >> 30); 6202 6203 if (Cost <= 4) 6204 return GeneratePerfectShuffle(PFEntry, V1, V2, DAG, dl); 6205 } 6206 6207 // Implement shuffles with 32- or 64-bit elements as ARMISD::BUILD_VECTORs. 6208 if (EltSize >= 32) { 6209 // Do the expansion with floating-point types, since that is what the VFP 6210 // registers are defined to use, and since i64 is not legal. 6211 EVT EltVT = EVT::getFloatingPointVT(EltSize); 6212 EVT VecVT = EVT::getVectorVT(*DAG.getContext(), EltVT, NumElts); 6213 V1 = DAG.getNode(ISD::BITCAST, dl, VecVT, V1); 6214 V2 = DAG.getNode(ISD::BITCAST, dl, VecVT, V2); 6215 SmallVector<SDValue, 8> Ops; 6216 for (unsigned i = 0; i < NumElts; ++i) { 6217 if (ShuffleMask[i] < 0) 6218 Ops.push_back(DAG.getUNDEF(EltVT)); 6219 else 6220 Ops.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, EltVT, 6221 ShuffleMask[i] < (int)NumElts ? V1 : V2, 6222 DAG.getConstant(ShuffleMask[i] & (NumElts-1), 6223 dl, MVT::i32))); 6224 } 6225 SDValue Val = DAG.getNode(ARMISD::BUILD_VECTOR, dl, VecVT, Ops); 6226 return DAG.getNode(ISD::BITCAST, dl, VT, Val); 6227 } 6228 6229 if ((VT == MVT::v8i16 || VT == MVT::v16i8) && isReverseMask(ShuffleMask, VT)) 6230 return LowerReverse_VECTOR_SHUFFLEv16i8_v8i16(Op, DAG); 6231 6232 if (VT == MVT::v8i8) 6233 if (SDValue NewOp = LowerVECTOR_SHUFFLEv8i8(Op, ShuffleMask, DAG)) 6234 return NewOp; 6235 6236 return SDValue(); 6237 } 6238 6239 static SDValue LowerINSERT_VECTOR_ELT(SDValue Op, SelectionDAG &DAG) { 6240 // INSERT_VECTOR_ELT is legal only for immediate indexes. 6241 SDValue Lane = Op.getOperand(2); 6242 if (!isa<ConstantSDNode>(Lane)) 6243 return SDValue(); 6244 6245 return Op; 6246 } 6247 6248 static SDValue LowerEXTRACT_VECTOR_ELT(SDValue Op, SelectionDAG &DAG) { 6249 // EXTRACT_VECTOR_ELT is legal only for immediate indexes. 6250 SDValue Lane = Op.getOperand(1); 6251 if (!isa<ConstantSDNode>(Lane)) 6252 return SDValue(); 6253 6254 SDValue Vec = Op.getOperand(0); 6255 if (Op.getValueType() == MVT::i32 && 6256 Vec.getValueType().getVectorElementType().getSizeInBits() < 32) { 6257 SDLoc dl(Op); 6258 return DAG.getNode(ARMISD::VGETLANEu, dl, MVT::i32, Vec, Lane); 6259 } 6260 6261 return Op; 6262 } 6263 6264 static SDValue LowerCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG) { 6265 // The only time a CONCAT_VECTORS operation can have legal types is when 6266 // two 64-bit vectors are concatenated to a 128-bit vector. 6267 assert(Op.getValueType().is128BitVector() && Op.getNumOperands() == 2 && 6268 "unexpected CONCAT_VECTORS"); 6269 SDLoc dl(Op); 6270 SDValue Val = DAG.getUNDEF(MVT::v2f64); 6271 SDValue Op0 = Op.getOperand(0); 6272 SDValue Op1 = Op.getOperand(1); 6273 if (Op0.getOpcode() != ISD::UNDEF) 6274 Val = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Val, 6275 DAG.getNode(ISD::BITCAST, dl, MVT::f64, Op0), 6276 DAG.getIntPtrConstant(0, dl)); 6277 if (Op1.getOpcode() != ISD::UNDEF) 6278 Val = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Val, 6279 DAG.getNode(ISD::BITCAST, dl, MVT::f64, Op1), 6280 DAG.getIntPtrConstant(1, dl)); 6281 return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Val); 6282 } 6283 6284 /// isExtendedBUILD_VECTOR - Check if N is a constant BUILD_VECTOR where each 6285 /// element has been zero/sign-extended, depending on the isSigned parameter, 6286 /// from an integer type half its size. 6287 static bool isExtendedBUILD_VECTOR(SDNode *N, SelectionDAG &DAG, 6288 bool isSigned) { 6289 // A v2i64 BUILD_VECTOR will have been legalized to a BITCAST from v4i32. 6290 EVT VT = N->getValueType(0); 6291 if (VT == MVT::v2i64 && N->getOpcode() == ISD::BITCAST) { 6292 SDNode *BVN = N->getOperand(0).getNode(); 6293 if (BVN->getValueType(0) != MVT::v4i32 || 6294 BVN->getOpcode() != ISD::BUILD_VECTOR) 6295 return false; 6296 unsigned LoElt = DAG.getDataLayout().isBigEndian() ? 1 : 0; 6297 unsigned HiElt = 1 - LoElt; 6298 ConstantSDNode *Lo0 = dyn_cast<ConstantSDNode>(BVN->getOperand(LoElt)); 6299 ConstantSDNode *Hi0 = dyn_cast<ConstantSDNode>(BVN->getOperand(HiElt)); 6300 ConstantSDNode *Lo1 = dyn_cast<ConstantSDNode>(BVN->getOperand(LoElt+2)); 6301 ConstantSDNode *Hi1 = dyn_cast<ConstantSDNode>(BVN->getOperand(HiElt+2)); 6302 if (!Lo0 || !Hi0 || !Lo1 || !Hi1) 6303 return false; 6304 if (isSigned) { 6305 if (Hi0->getSExtValue() == Lo0->getSExtValue() >> 32 && 6306 Hi1->getSExtValue() == Lo1->getSExtValue() >> 32) 6307 return true; 6308 } else { 6309 if (Hi0->isNullValue() && Hi1->isNullValue()) 6310 return true; 6311 } 6312 return false; 6313 } 6314 6315 if (N->getOpcode() != ISD::BUILD_VECTOR) 6316 return false; 6317 6318 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) { 6319 SDNode *Elt = N->getOperand(i).getNode(); 6320 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Elt)) { 6321 unsigned EltSize = VT.getVectorElementType().getSizeInBits(); 6322 unsigned HalfSize = EltSize / 2; 6323 if (isSigned) { 6324 if (!isIntN(HalfSize, C->getSExtValue())) 6325 return false; 6326 } else { 6327 if (!isUIntN(HalfSize, C->getZExtValue())) 6328 return false; 6329 } 6330 continue; 6331 } 6332 return false; 6333 } 6334 6335 return true; 6336 } 6337 6338 /// isSignExtended - Check if a node is a vector value that is sign-extended 6339 /// or a constant BUILD_VECTOR with sign-extended elements. 6340 static bool isSignExtended(SDNode *N, SelectionDAG &DAG) { 6341 if (N->getOpcode() == ISD::SIGN_EXTEND || ISD::isSEXTLoad(N)) 6342 return true; 6343 if (isExtendedBUILD_VECTOR(N, DAG, true)) 6344 return true; 6345 return false; 6346 } 6347 6348 /// isZeroExtended - Check if a node is a vector value that is zero-extended 6349 /// or a constant BUILD_VECTOR with zero-extended elements. 6350 static bool isZeroExtended(SDNode *N, SelectionDAG &DAG) { 6351 if (N->getOpcode() == ISD::ZERO_EXTEND || ISD::isZEXTLoad(N)) 6352 return true; 6353 if (isExtendedBUILD_VECTOR(N, DAG, false)) 6354 return true; 6355 return false; 6356 } 6357 6358 static EVT getExtensionTo64Bits(const EVT &OrigVT) { 6359 if (OrigVT.getSizeInBits() >= 64) 6360 return OrigVT; 6361 6362 assert(OrigVT.isSimple() && "Expecting a simple value type"); 6363 6364 MVT::SimpleValueType OrigSimpleTy = OrigVT.getSimpleVT().SimpleTy; 6365 switch (OrigSimpleTy) { 6366 default: llvm_unreachable("Unexpected Vector Type"); 6367 case MVT::v2i8: 6368 case MVT::v2i16: 6369 return MVT::v2i32; 6370 case MVT::v4i8: 6371 return MVT::v4i16; 6372 } 6373 } 6374 6375 /// AddRequiredExtensionForVMULL - Add a sign/zero extension to extend the total 6376 /// value size to 64 bits. We need a 64-bit D register as an operand to VMULL. 6377 /// We insert the required extension here to get the vector to fill a D register. 6378 static SDValue AddRequiredExtensionForVMULL(SDValue N, SelectionDAG &DAG, 6379 const EVT &OrigTy, 6380 const EVT &ExtTy, 6381 unsigned ExtOpcode) { 6382 // The vector originally had a size of OrigTy. It was then extended to ExtTy. 6383 // We expect the ExtTy to be 128-bits total. If the OrigTy is less than 6384 // 64-bits we need to insert a new extension so that it will be 64-bits. 6385 assert(ExtTy.is128BitVector() && "Unexpected extension size"); 6386 if (OrigTy.getSizeInBits() >= 64) 6387 return N; 6388 6389 // Must extend size to at least 64 bits to be used as an operand for VMULL. 6390 EVT NewVT = getExtensionTo64Bits(OrigTy); 6391 6392 return DAG.getNode(ExtOpcode, SDLoc(N), NewVT, N); 6393 } 6394 6395 /// SkipLoadExtensionForVMULL - return a load of the original vector size that 6396 /// does not do any sign/zero extension. If the original vector is less 6397 /// than 64 bits, an appropriate extension will be added after the load to 6398 /// reach a total size of 64 bits. We have to add the extension separately 6399 /// because ARM does not have a sign/zero extending load for vectors. 6400 static SDValue SkipLoadExtensionForVMULL(LoadSDNode *LD, SelectionDAG& DAG) { 6401 EVT ExtendedTy = getExtensionTo64Bits(LD->getMemoryVT()); 6402 6403 // The load already has the right type. 6404 if (ExtendedTy == LD->getMemoryVT()) 6405 return DAG.getLoad(LD->getMemoryVT(), SDLoc(LD), LD->getChain(), 6406 LD->getBasePtr(), LD->getPointerInfo(), LD->isVolatile(), 6407 LD->isNonTemporal(), LD->isInvariant(), 6408 LD->getAlignment()); 6409 6410 // We need to create a zextload/sextload. We cannot just create a load 6411 // followed by a zext/zext node because LowerMUL is also run during normal 6412 // operation legalization where we can't create illegal types. 6413 return DAG.getExtLoad(LD->getExtensionType(), SDLoc(LD), ExtendedTy, 6414 LD->getChain(), LD->getBasePtr(), LD->getPointerInfo(), 6415 LD->getMemoryVT(), LD->isVolatile(), LD->isInvariant(), 6416 LD->isNonTemporal(), LD->getAlignment()); 6417 } 6418 6419 /// SkipExtensionForVMULL - For a node that is a SIGN_EXTEND, ZERO_EXTEND, 6420 /// extending load, or BUILD_VECTOR with extended elements, return the 6421 /// unextended value. The unextended vector should be 64 bits so that it can 6422 /// be used as an operand to a VMULL instruction. If the original vector size 6423 /// before extension is less than 64 bits we add a an extension to resize 6424 /// the vector to 64 bits. 6425 static SDValue SkipExtensionForVMULL(SDNode *N, SelectionDAG &DAG) { 6426 if (N->getOpcode() == ISD::SIGN_EXTEND || N->getOpcode() == ISD::ZERO_EXTEND) 6427 return AddRequiredExtensionForVMULL(N->getOperand(0), DAG, 6428 N->getOperand(0)->getValueType(0), 6429 N->getValueType(0), 6430 N->getOpcode()); 6431 6432 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) 6433 return SkipLoadExtensionForVMULL(LD, DAG); 6434 6435 // Otherwise, the value must be a BUILD_VECTOR. For v2i64, it will 6436 // have been legalized as a BITCAST from v4i32. 6437 if (N->getOpcode() == ISD::BITCAST) { 6438 SDNode *BVN = N->getOperand(0).getNode(); 6439 assert(BVN->getOpcode() == ISD::BUILD_VECTOR && 6440 BVN->getValueType(0) == MVT::v4i32 && "expected v4i32 BUILD_VECTOR"); 6441 unsigned LowElt = DAG.getDataLayout().isBigEndian() ? 1 : 0; 6442 return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), MVT::v2i32, 6443 BVN->getOperand(LowElt), BVN->getOperand(LowElt+2)); 6444 } 6445 // Construct a new BUILD_VECTOR with elements truncated to half the size. 6446 assert(N->getOpcode() == ISD::BUILD_VECTOR && "expected BUILD_VECTOR"); 6447 EVT VT = N->getValueType(0); 6448 unsigned EltSize = VT.getVectorElementType().getSizeInBits() / 2; 6449 unsigned NumElts = VT.getVectorNumElements(); 6450 MVT TruncVT = MVT::getIntegerVT(EltSize); 6451 SmallVector<SDValue, 8> Ops; 6452 SDLoc dl(N); 6453 for (unsigned i = 0; i != NumElts; ++i) { 6454 ConstantSDNode *C = cast<ConstantSDNode>(N->getOperand(i)); 6455 const APInt &CInt = C->getAPIntValue(); 6456 // Element types smaller than 32 bits are not legal, so use i32 elements. 6457 // The values are implicitly truncated so sext vs. zext doesn't matter. 6458 Ops.push_back(DAG.getConstant(CInt.zextOrTrunc(32), dl, MVT::i32)); 6459 } 6460 return DAG.getNode(ISD::BUILD_VECTOR, dl, 6461 MVT::getVectorVT(TruncVT, NumElts), Ops); 6462 } 6463 6464 static bool isAddSubSExt(SDNode *N, SelectionDAG &DAG) { 6465 unsigned Opcode = N->getOpcode(); 6466 if (Opcode == ISD::ADD || Opcode == ISD::SUB) { 6467 SDNode *N0 = N->getOperand(0).getNode(); 6468 SDNode *N1 = N->getOperand(1).getNode(); 6469 return N0->hasOneUse() && N1->hasOneUse() && 6470 isSignExtended(N0, DAG) && isSignExtended(N1, DAG); 6471 } 6472 return false; 6473 } 6474 6475 static bool isAddSubZExt(SDNode *N, SelectionDAG &DAG) { 6476 unsigned Opcode = N->getOpcode(); 6477 if (Opcode == ISD::ADD || Opcode == ISD::SUB) { 6478 SDNode *N0 = N->getOperand(0).getNode(); 6479 SDNode *N1 = N->getOperand(1).getNode(); 6480 return N0->hasOneUse() && N1->hasOneUse() && 6481 isZeroExtended(N0, DAG) && isZeroExtended(N1, DAG); 6482 } 6483 return false; 6484 } 6485 6486 static SDValue LowerMUL(SDValue Op, SelectionDAG &DAG) { 6487 // Multiplications are only custom-lowered for 128-bit vectors so that 6488 // VMULL can be detected. Otherwise v2i64 multiplications are not legal. 6489 EVT VT = Op.getValueType(); 6490 assert(VT.is128BitVector() && VT.isInteger() && 6491 "unexpected type for custom-lowering ISD::MUL"); 6492 SDNode *N0 = Op.getOperand(0).getNode(); 6493 SDNode *N1 = Op.getOperand(1).getNode(); 6494 unsigned NewOpc = 0; 6495 bool isMLA = false; 6496 bool isN0SExt = isSignExtended(N0, DAG); 6497 bool isN1SExt = isSignExtended(N1, DAG); 6498 if (isN0SExt && isN1SExt) 6499 NewOpc = ARMISD::VMULLs; 6500 else { 6501 bool isN0ZExt = isZeroExtended(N0, DAG); 6502 bool isN1ZExt = isZeroExtended(N1, DAG); 6503 if (isN0ZExt && isN1ZExt) 6504 NewOpc = ARMISD::VMULLu; 6505 else if (isN1SExt || isN1ZExt) { 6506 // Look for (s/zext A + s/zext B) * (s/zext C). We want to turn these 6507 // into (s/zext A * s/zext C) + (s/zext B * s/zext C) 6508 if (isN1SExt && isAddSubSExt(N0, DAG)) { 6509 NewOpc = ARMISD::VMULLs; 6510 isMLA = true; 6511 } else if (isN1ZExt && isAddSubZExt(N0, DAG)) { 6512 NewOpc = ARMISD::VMULLu; 6513 isMLA = true; 6514 } else if (isN0ZExt && isAddSubZExt(N1, DAG)) { 6515 std::swap(N0, N1); 6516 NewOpc = ARMISD::VMULLu; 6517 isMLA = true; 6518 } 6519 } 6520 6521 if (!NewOpc) { 6522 if (VT == MVT::v2i64) 6523 // Fall through to expand this. It is not legal. 6524 return SDValue(); 6525 else 6526 // Other vector multiplications are legal. 6527 return Op; 6528 } 6529 } 6530 6531 // Legalize to a VMULL instruction. 6532 SDLoc DL(Op); 6533 SDValue Op0; 6534 SDValue Op1 = SkipExtensionForVMULL(N1, DAG); 6535 if (!isMLA) { 6536 Op0 = SkipExtensionForVMULL(N0, DAG); 6537 assert(Op0.getValueType().is64BitVector() && 6538 Op1.getValueType().is64BitVector() && 6539 "unexpected types for extended operands to VMULL"); 6540 return DAG.getNode(NewOpc, DL, VT, Op0, Op1); 6541 } 6542 6543 // Optimizing (zext A + zext B) * C, to (VMULL A, C) + (VMULL B, C) during 6544 // isel lowering to take advantage of no-stall back to back vmul + vmla. 6545 // vmull q0, d4, d6 6546 // vmlal q0, d5, d6 6547 // is faster than 6548 // vaddl q0, d4, d5 6549 // vmovl q1, d6 6550 // vmul q0, q0, q1 6551 SDValue N00 = SkipExtensionForVMULL(N0->getOperand(0).getNode(), DAG); 6552 SDValue N01 = SkipExtensionForVMULL(N0->getOperand(1).getNode(), DAG); 6553 EVT Op1VT = Op1.getValueType(); 6554 return DAG.getNode(N0->getOpcode(), DL, VT, 6555 DAG.getNode(NewOpc, DL, VT, 6556 DAG.getNode(ISD::BITCAST, DL, Op1VT, N00), Op1), 6557 DAG.getNode(NewOpc, DL, VT, 6558 DAG.getNode(ISD::BITCAST, DL, Op1VT, N01), Op1)); 6559 } 6560 6561 static SDValue 6562 LowerSDIV_v4i8(SDValue X, SDValue Y, SDLoc dl, SelectionDAG &DAG) { 6563 // TODO: Should this propagate fast-math-flags? 6564 6565 // Convert to float 6566 // float4 xf = vcvt_f32_s32(vmovl_s16(a.lo)); 6567 // float4 yf = vcvt_f32_s32(vmovl_s16(b.lo)); 6568 X = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, X); 6569 Y = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, Y); 6570 X = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, X); 6571 Y = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, Y); 6572 // Get reciprocal estimate. 6573 // float4 recip = vrecpeq_f32(yf); 6574 Y = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32, 6575 DAG.getConstant(Intrinsic::arm_neon_vrecpe, dl, MVT::i32), 6576 Y); 6577 // Because char has a smaller range than uchar, we can actually get away 6578 // without any newton steps. This requires that we use a weird bias 6579 // of 0xb000, however (again, this has been exhaustively tested). 6580 // float4 result = as_float4(as_int4(xf*recip) + 0xb000); 6581 X = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, X, Y); 6582 X = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, X); 6583 Y = DAG.getConstant(0xb000, dl, MVT::v4i32); 6584 X = DAG.getNode(ISD::ADD, dl, MVT::v4i32, X, Y); 6585 X = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, X); 6586 // Convert back to short. 6587 X = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::v4i32, X); 6588 X = DAG.getNode(ISD::TRUNCATE, dl, MVT::v4i16, X); 6589 return X; 6590 } 6591 6592 static SDValue 6593 LowerSDIV_v4i16(SDValue N0, SDValue N1, SDLoc dl, SelectionDAG &DAG) { 6594 // TODO: Should this propagate fast-math-flags? 6595 6596 SDValue N2; 6597 // Convert to float. 6598 // float4 yf = vcvt_f32_s32(vmovl_s16(y)); 6599 // float4 xf = vcvt_f32_s32(vmovl_s16(x)); 6600 N0 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, N0); 6601 N1 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, N1); 6602 N0 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N0); 6603 N1 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N1); 6604 6605 // Use reciprocal estimate and one refinement step. 6606 // float4 recip = vrecpeq_f32(yf); 6607 // recip *= vrecpsq_f32(yf, recip); 6608 N2 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32, 6609 DAG.getConstant(Intrinsic::arm_neon_vrecpe, dl, MVT::i32), 6610 N1); 6611 N1 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32, 6612 DAG.getConstant(Intrinsic::arm_neon_vrecps, dl, MVT::i32), 6613 N1, N2); 6614 N2 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N1, N2); 6615 // Because short has a smaller range than ushort, we can actually get away 6616 // with only a single newton step. This requires that we use a weird bias 6617 // of 89, however (again, this has been exhaustively tested). 6618 // float4 result = as_float4(as_int4(xf*recip) + 0x89); 6619 N0 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N0, N2); 6620 N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, N0); 6621 N1 = DAG.getConstant(0x89, dl, MVT::v4i32); 6622 N0 = DAG.getNode(ISD::ADD, dl, MVT::v4i32, N0, N1); 6623 N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, N0); 6624 // Convert back to integer and return. 6625 // return vmovn_s32(vcvt_s32_f32(result)); 6626 N0 = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::v4i32, N0); 6627 N0 = DAG.getNode(ISD::TRUNCATE, dl, MVT::v4i16, N0); 6628 return N0; 6629 } 6630 6631 static SDValue LowerSDIV(SDValue Op, SelectionDAG &DAG) { 6632 EVT VT = Op.getValueType(); 6633 assert((VT == MVT::v4i16 || VT == MVT::v8i8) && 6634 "unexpected type for custom-lowering ISD::SDIV"); 6635 6636 SDLoc dl(Op); 6637 SDValue N0 = Op.getOperand(0); 6638 SDValue N1 = Op.getOperand(1); 6639 SDValue N2, N3; 6640 6641 if (VT == MVT::v8i8) { 6642 N0 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v8i16, N0); 6643 N1 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v8i16, N1); 6644 6645 N2 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0, 6646 DAG.getIntPtrConstant(4, dl)); 6647 N3 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1, 6648 DAG.getIntPtrConstant(4, dl)); 6649 N0 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0, 6650 DAG.getIntPtrConstant(0, dl)); 6651 N1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1, 6652 DAG.getIntPtrConstant(0, dl)); 6653 6654 N0 = LowerSDIV_v4i8(N0, N1, dl, DAG); // v4i16 6655 N2 = LowerSDIV_v4i8(N2, N3, dl, DAG); // v4i16 6656 6657 N0 = DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v8i16, N0, N2); 6658 N0 = LowerCONCAT_VECTORS(N0, DAG); 6659 6660 N0 = DAG.getNode(ISD::TRUNCATE, dl, MVT::v8i8, N0); 6661 return N0; 6662 } 6663 return LowerSDIV_v4i16(N0, N1, dl, DAG); 6664 } 6665 6666 static SDValue LowerUDIV(SDValue Op, SelectionDAG &DAG) { 6667 // TODO: Should this propagate fast-math-flags? 6668 EVT VT = Op.getValueType(); 6669 assert((VT == MVT::v4i16 || VT == MVT::v8i8) && 6670 "unexpected type for custom-lowering ISD::UDIV"); 6671 6672 SDLoc dl(Op); 6673 SDValue N0 = Op.getOperand(0); 6674 SDValue N1 = Op.getOperand(1); 6675 SDValue N2, N3; 6676 6677 if (VT == MVT::v8i8) { 6678 N0 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v8i16, N0); 6679 N1 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v8i16, N1); 6680 6681 N2 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0, 6682 DAG.getIntPtrConstant(4, dl)); 6683 N3 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1, 6684 DAG.getIntPtrConstant(4, dl)); 6685 N0 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0, 6686 DAG.getIntPtrConstant(0, dl)); 6687 N1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1, 6688 DAG.getIntPtrConstant(0, dl)); 6689 6690 N0 = LowerSDIV_v4i16(N0, N1, dl, DAG); // v4i16 6691 N2 = LowerSDIV_v4i16(N2, N3, dl, DAG); // v4i16 6692 6693 N0 = DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v8i16, N0, N2); 6694 N0 = LowerCONCAT_VECTORS(N0, DAG); 6695 6696 N0 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v8i8, 6697 DAG.getConstant(Intrinsic::arm_neon_vqmovnsu, dl, 6698 MVT::i32), 6699 N0); 6700 return N0; 6701 } 6702 6703 // v4i16 sdiv ... Convert to float. 6704 // float4 yf = vcvt_f32_s32(vmovl_u16(y)); 6705 // float4 xf = vcvt_f32_s32(vmovl_u16(x)); 6706 N0 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v4i32, N0); 6707 N1 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v4i32, N1); 6708 N0 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N0); 6709 SDValue BN1 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N1); 6710 6711 // Use reciprocal estimate and two refinement steps. 6712 // float4 recip = vrecpeq_f32(yf); 6713 // recip *= vrecpsq_f32(yf, recip); 6714 // recip *= vrecpsq_f32(yf, recip); 6715 N2 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32, 6716 DAG.getConstant(Intrinsic::arm_neon_vrecpe, dl, MVT::i32), 6717 BN1); 6718 N1 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32, 6719 DAG.getConstant(Intrinsic::arm_neon_vrecps, dl, MVT::i32), 6720 BN1, N2); 6721 N2 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N1, N2); 6722 N1 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32, 6723 DAG.getConstant(Intrinsic::arm_neon_vrecps, dl, MVT::i32), 6724 BN1, N2); 6725 N2 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N1, N2); 6726 // Simply multiplying by the reciprocal estimate can leave us a few ulps 6727 // too low, so we add 2 ulps (exhaustive testing shows that this is enough, 6728 // and that it will never cause us to return an answer too large). 6729 // float4 result = as_float4(as_int4(xf*recip) + 2); 6730 N0 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N0, N2); 6731 N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, N0); 6732 N1 = DAG.getConstant(2, dl, MVT::v4i32); 6733 N0 = DAG.getNode(ISD::ADD, dl, MVT::v4i32, N0, N1); 6734 N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, N0); 6735 // Convert back to integer and return. 6736 // return vmovn_u32(vcvt_s32_f32(result)); 6737 N0 = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::v4i32, N0); 6738 N0 = DAG.getNode(ISD::TRUNCATE, dl, MVT::v4i16, N0); 6739 return N0; 6740 } 6741 6742 static SDValue LowerADDC_ADDE_SUBC_SUBE(SDValue Op, SelectionDAG &DAG) { 6743 EVT VT = Op.getNode()->getValueType(0); 6744 SDVTList VTs = DAG.getVTList(VT, MVT::i32); 6745 6746 unsigned Opc; 6747 bool ExtraOp = false; 6748 switch (Op.getOpcode()) { 6749 default: llvm_unreachable("Invalid code"); 6750 case ISD::ADDC: Opc = ARMISD::ADDC; break; 6751 case ISD::ADDE: Opc = ARMISD::ADDE; ExtraOp = true; break; 6752 case ISD::SUBC: Opc = ARMISD::SUBC; break; 6753 case ISD::SUBE: Opc = ARMISD::SUBE; ExtraOp = true; break; 6754 } 6755 6756 if (!ExtraOp) 6757 return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0), 6758 Op.getOperand(1)); 6759 return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0), 6760 Op.getOperand(1), Op.getOperand(2)); 6761 } 6762 6763 SDValue ARMTargetLowering::LowerFSINCOS(SDValue Op, SelectionDAG &DAG) const { 6764 assert(Subtarget->isTargetDarwin()); 6765 6766 // For iOS, we want to call an alternative entry point: __sincos_stret, 6767 // return values are passed via sret. 6768 SDLoc dl(Op); 6769 SDValue Arg = Op.getOperand(0); 6770 EVT ArgVT = Arg.getValueType(); 6771 Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext()); 6772 auto PtrVT = getPointerTy(DAG.getDataLayout()); 6773 6774 MachineFrameInfo *FrameInfo = DAG.getMachineFunction().getFrameInfo(); 6775 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 6776 6777 // Pair of floats / doubles used to pass the result. 6778 Type *RetTy = StructType::get(ArgTy, ArgTy, nullptr); 6779 auto &DL = DAG.getDataLayout(); 6780 6781 ArgListTy Args; 6782 bool ShouldUseSRet = Subtarget->isAPCS_ABI(); 6783 SDValue SRet; 6784 if (ShouldUseSRet) { 6785 // Create stack object for sret. 6786 const uint64_t ByteSize = DL.getTypeAllocSize(RetTy); 6787 const unsigned StackAlign = DL.getPrefTypeAlignment(RetTy); 6788 int FrameIdx = FrameInfo->CreateStackObject(ByteSize, StackAlign, false); 6789 SRet = DAG.getFrameIndex(FrameIdx, TLI.getPointerTy(DL)); 6790 6791 ArgListEntry Entry; 6792 Entry.Node = SRet; 6793 Entry.Ty = RetTy->getPointerTo(); 6794 Entry.isSExt = false; 6795 Entry.isZExt = false; 6796 Entry.isSRet = true; 6797 Args.push_back(Entry); 6798 RetTy = Type::getVoidTy(*DAG.getContext()); 6799 } 6800 6801 ArgListEntry Entry; 6802 Entry.Node = Arg; 6803 Entry.Ty = ArgTy; 6804 Entry.isSExt = false; 6805 Entry.isZExt = false; 6806 Args.push_back(Entry); 6807 6808 const char *LibcallName = 6809 (ArgVT == MVT::f64) ? "__sincos_stret" : "__sincosf_stret"; 6810 RTLIB::Libcall LC = 6811 (ArgVT == MVT::f64) ? RTLIB::SINCOS_F64 : RTLIB::SINCOS_F32; 6812 CallingConv::ID CC = getLibcallCallingConv(LC); 6813 SDValue Callee = DAG.getExternalSymbol(LibcallName, getPointerTy(DL)); 6814 6815 TargetLowering::CallLoweringInfo CLI(DAG); 6816 CLI.setDebugLoc(dl) 6817 .setChain(DAG.getEntryNode()) 6818 .setCallee(CC, RetTy, Callee, std::move(Args), 0) 6819 .setDiscardResult(ShouldUseSRet); 6820 std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI); 6821 6822 if (!ShouldUseSRet) 6823 return CallResult.first; 6824 6825 SDValue LoadSin = DAG.getLoad(ArgVT, dl, CallResult.second, SRet, 6826 MachinePointerInfo(), false, false, false, 0); 6827 6828 // Address of cos field. 6829 SDValue Add = DAG.getNode(ISD::ADD, dl, PtrVT, SRet, 6830 DAG.getIntPtrConstant(ArgVT.getStoreSize(), dl)); 6831 SDValue LoadCos = DAG.getLoad(ArgVT, dl, LoadSin.getValue(1), Add, 6832 MachinePointerInfo(), false, false, false, 0); 6833 6834 SDVTList Tys = DAG.getVTList(ArgVT, ArgVT); 6835 return DAG.getNode(ISD::MERGE_VALUES, dl, Tys, 6836 LoadSin.getValue(0), LoadCos.getValue(0)); 6837 } 6838 6839 SDValue ARMTargetLowering::LowerWindowsDIVLibCall(SDValue Op, SelectionDAG &DAG, 6840 bool Signed, 6841 SDValue &Chain) const { 6842 EVT VT = Op.getValueType(); 6843 assert((VT == MVT::i32 || VT == MVT::i64) && 6844 "unexpected type for custom lowering DIV"); 6845 SDLoc dl(Op); 6846 6847 const auto &DL = DAG.getDataLayout(); 6848 const auto &TLI = DAG.getTargetLoweringInfo(); 6849 6850 const char *Name = nullptr; 6851 if (Signed) 6852 Name = (VT == MVT::i32) ? "__rt_sdiv" : "__rt_sdiv64"; 6853 else 6854 Name = (VT == MVT::i32) ? "__rt_udiv" : "__rt_udiv64"; 6855 6856 SDValue ES = DAG.getExternalSymbol(Name, TLI.getPointerTy(DL)); 6857 6858 ARMTargetLowering::ArgListTy Args; 6859 6860 for (auto AI : {1, 0}) { 6861 ArgListEntry Arg; 6862 Arg.Node = Op.getOperand(AI); 6863 Arg.Ty = Arg.Node.getValueType().getTypeForEVT(*DAG.getContext()); 6864 Args.push_back(Arg); 6865 } 6866 6867 CallLoweringInfo CLI(DAG); 6868 CLI.setDebugLoc(dl) 6869 .setChain(Chain) 6870 .setCallee(CallingConv::ARM_AAPCS_VFP, VT.getTypeForEVT(*DAG.getContext()), 6871 ES, std::move(Args), 0); 6872 6873 return LowerCallTo(CLI).first; 6874 } 6875 6876 SDValue ARMTargetLowering::LowerDIV_Windows(SDValue Op, SelectionDAG &DAG, 6877 bool Signed) const { 6878 assert(Op.getValueType() == MVT::i32 && 6879 "unexpected type for custom lowering DIV"); 6880 SDLoc dl(Op); 6881 6882 SDValue DBZCHK = DAG.getNode(ARMISD::WIN__DBZCHK, dl, MVT::Other, 6883 DAG.getEntryNode(), Op.getOperand(1)); 6884 6885 return LowerWindowsDIVLibCall(Op, DAG, Signed, DBZCHK); 6886 } 6887 6888 void ARMTargetLowering::ExpandDIV_Windows( 6889 SDValue Op, SelectionDAG &DAG, bool Signed, 6890 SmallVectorImpl<SDValue> &Results) const { 6891 const auto &DL = DAG.getDataLayout(); 6892 const auto &TLI = DAG.getTargetLoweringInfo(); 6893 6894 assert(Op.getValueType() == MVT::i64 && 6895 "unexpected type for custom lowering DIV"); 6896 SDLoc dl(Op); 6897 6898 SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, Op.getOperand(1), 6899 DAG.getConstant(0, dl, MVT::i32)); 6900 SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, Op.getOperand(1), 6901 DAG.getConstant(1, dl, MVT::i32)); 6902 SDValue Or = DAG.getNode(ISD::OR, dl, MVT::i32, Lo, Hi); 6903 6904 SDValue DBZCHK = 6905 DAG.getNode(ARMISD::WIN__DBZCHK, dl, MVT::Other, DAG.getEntryNode(), Or); 6906 6907 SDValue Result = LowerWindowsDIVLibCall(Op, DAG, Signed, DBZCHK); 6908 6909 SDValue Lower = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, Result); 6910 SDValue Upper = DAG.getNode(ISD::SRL, dl, MVT::i64, Result, 6911 DAG.getConstant(32, dl, TLI.getPointerTy(DL))); 6912 Upper = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, Upper); 6913 6914 Results.push_back(Lower); 6915 Results.push_back(Upper); 6916 } 6917 6918 static SDValue LowerAtomicLoadStore(SDValue Op, SelectionDAG &DAG) { 6919 // Monotonic load/store is legal for all targets 6920 if (cast<AtomicSDNode>(Op)->getOrdering() <= Monotonic) 6921 return Op; 6922 6923 // Acquire/Release load/store is not legal for targets without a 6924 // dmb or equivalent available. 6925 return SDValue(); 6926 } 6927 6928 static void ReplaceREADCYCLECOUNTER(SDNode *N, 6929 SmallVectorImpl<SDValue> &Results, 6930 SelectionDAG &DAG, 6931 const ARMSubtarget *Subtarget) { 6932 SDLoc DL(N); 6933 // Under Power Management extensions, the cycle-count is: 6934 // mrc p15, #0, <Rt>, c9, c13, #0 6935 SDValue Ops[] = { N->getOperand(0), // Chain 6936 DAG.getConstant(Intrinsic::arm_mrc, DL, MVT::i32), 6937 DAG.getConstant(15, DL, MVT::i32), 6938 DAG.getConstant(0, DL, MVT::i32), 6939 DAG.getConstant(9, DL, MVT::i32), 6940 DAG.getConstant(13, DL, MVT::i32), 6941 DAG.getConstant(0, DL, MVT::i32) 6942 }; 6943 6944 SDValue Cycles32 = DAG.getNode(ISD::INTRINSIC_W_CHAIN, DL, 6945 DAG.getVTList(MVT::i32, MVT::Other), Ops); 6946 Results.push_back(DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, Cycles32, 6947 DAG.getConstant(0, DL, MVT::i32))); 6948 Results.push_back(Cycles32.getValue(1)); 6949 } 6950 6951 SDValue ARMTargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const { 6952 switch (Op.getOpcode()) { 6953 default: llvm_unreachable("Don't know how to custom lower this!"); 6954 case ISD::WRITE_REGISTER: return LowerWRITE_REGISTER(Op, DAG); 6955 case ISD::ConstantPool: return LowerConstantPool(Op, DAG); 6956 case ISD::BlockAddress: return LowerBlockAddress(Op, DAG); 6957 case ISD::GlobalAddress: 6958 switch (Subtarget->getTargetTriple().getObjectFormat()) { 6959 default: llvm_unreachable("unknown object format"); 6960 case Triple::COFF: 6961 return LowerGlobalAddressWindows(Op, DAG); 6962 case Triple::ELF: 6963 return LowerGlobalAddressELF(Op, DAG); 6964 case Triple::MachO: 6965 return LowerGlobalAddressDarwin(Op, DAG); 6966 } 6967 case ISD::GlobalTLSAddress: return LowerGlobalTLSAddress(Op, DAG); 6968 case ISD::SELECT: return LowerSELECT(Op, DAG); 6969 case ISD::SELECT_CC: return LowerSELECT_CC(Op, DAG); 6970 case ISD::BR_CC: return LowerBR_CC(Op, DAG); 6971 case ISD::BR_JT: return LowerBR_JT(Op, DAG); 6972 case ISD::VASTART: return LowerVASTART(Op, DAG); 6973 case ISD::ATOMIC_FENCE: return LowerATOMIC_FENCE(Op, DAG, Subtarget); 6974 case ISD::PREFETCH: return LowerPREFETCH(Op, DAG, Subtarget); 6975 case ISD::SINT_TO_FP: 6976 case ISD::UINT_TO_FP: return LowerINT_TO_FP(Op, DAG); 6977 case ISD::FP_TO_SINT: 6978 case ISD::FP_TO_UINT: return LowerFP_TO_INT(Op, DAG); 6979 case ISD::FCOPYSIGN: return LowerFCOPYSIGN(Op, DAG); 6980 case ISD::RETURNADDR: return LowerRETURNADDR(Op, DAG); 6981 case ISD::FRAMEADDR: return LowerFRAMEADDR(Op, DAG); 6982 case ISD::EH_SJLJ_SETJMP: return LowerEH_SJLJ_SETJMP(Op, DAG); 6983 case ISD::EH_SJLJ_LONGJMP: return LowerEH_SJLJ_LONGJMP(Op, DAG); 6984 case ISD::EH_SJLJ_SETUP_DISPATCH: return LowerEH_SJLJ_SETUP_DISPATCH(Op, DAG); 6985 case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG, 6986 Subtarget); 6987 case ISD::BITCAST: return ExpandBITCAST(Op.getNode(), DAG); 6988 case ISD::SHL: 6989 case ISD::SRL: 6990 case ISD::SRA: return LowerShift(Op.getNode(), DAG, Subtarget); 6991 case ISD::SREM: return LowerREM(Op.getNode(), DAG); 6992 case ISD::UREM: return LowerREM(Op.getNode(), DAG); 6993 case ISD::SHL_PARTS: return LowerShiftLeftParts(Op, DAG); 6994 case ISD::SRL_PARTS: 6995 case ISD::SRA_PARTS: return LowerShiftRightParts(Op, DAG); 6996 case ISD::CTTZ: 6997 case ISD::CTTZ_ZERO_UNDEF: return LowerCTTZ(Op.getNode(), DAG, Subtarget); 6998 case ISD::CTPOP: return LowerCTPOP(Op.getNode(), DAG, Subtarget); 6999 case ISD::SETCC: return LowerVSETCC(Op, DAG); 7000 case ISD::ConstantFP: return LowerConstantFP(Op, DAG, Subtarget); 7001 case ISD::BUILD_VECTOR: return LowerBUILD_VECTOR(Op, DAG, Subtarget); 7002 case ISD::VECTOR_SHUFFLE: return LowerVECTOR_SHUFFLE(Op, DAG); 7003 case ISD::INSERT_VECTOR_ELT: return LowerINSERT_VECTOR_ELT(Op, DAG); 7004 case ISD::EXTRACT_VECTOR_ELT: return LowerEXTRACT_VECTOR_ELT(Op, DAG); 7005 case ISD::CONCAT_VECTORS: return LowerCONCAT_VECTORS(Op, DAG); 7006 case ISD::FLT_ROUNDS_: return LowerFLT_ROUNDS_(Op, DAG); 7007 case ISD::MUL: return LowerMUL(Op, DAG); 7008 case ISD::SDIV: return LowerSDIV(Op, DAG); 7009 case ISD::UDIV: return LowerUDIV(Op, DAG); 7010 case ISD::ADDC: 7011 case ISD::ADDE: 7012 case ISD::SUBC: 7013 case ISD::SUBE: return LowerADDC_ADDE_SUBC_SUBE(Op, DAG); 7014 case ISD::SADDO: 7015 case ISD::UADDO: 7016 case ISD::SSUBO: 7017 case ISD::USUBO: 7018 return LowerXALUO(Op, DAG); 7019 case ISD::ATOMIC_LOAD: 7020 case ISD::ATOMIC_STORE: return LowerAtomicLoadStore(Op, DAG); 7021 case ISD::FSINCOS: return LowerFSINCOS(Op, DAG); 7022 case ISD::SDIVREM: 7023 case ISD::UDIVREM: return LowerDivRem(Op, DAG); 7024 case ISD::DYNAMIC_STACKALLOC: 7025 if (Subtarget->getTargetTriple().isWindowsItaniumEnvironment()) 7026 return LowerDYNAMIC_STACKALLOC(Op, DAG); 7027 llvm_unreachable("Don't know how to custom lower this!"); 7028 case ISD::FP_ROUND: return LowerFP_ROUND(Op, DAG); 7029 case ISD::FP_EXTEND: return LowerFP_EXTEND(Op, DAG); 7030 case ARMISD::WIN__DBZCHK: return SDValue(); 7031 } 7032 } 7033 7034 /// ReplaceNodeResults - Replace the results of node with an illegal result 7035 /// type with new values built out of custom code. 7036 void ARMTargetLowering::ReplaceNodeResults(SDNode *N, 7037 SmallVectorImpl<SDValue> &Results, 7038 SelectionDAG &DAG) const { 7039 SDValue Res; 7040 switch (N->getOpcode()) { 7041 default: 7042 llvm_unreachable("Don't know how to custom expand this!"); 7043 case ISD::READ_REGISTER: 7044 ExpandREAD_REGISTER(N, Results, DAG); 7045 break; 7046 case ISD::BITCAST: 7047 Res = ExpandBITCAST(N, DAG); 7048 break; 7049 case ISD::SRL: 7050 case ISD::SRA: 7051 Res = Expand64BitShift(N, DAG, Subtarget); 7052 break; 7053 case ISD::SREM: 7054 case ISD::UREM: 7055 Res = LowerREM(N, DAG); 7056 break; 7057 case ISD::READCYCLECOUNTER: 7058 ReplaceREADCYCLECOUNTER(N, Results, DAG, Subtarget); 7059 return; 7060 case ISD::UDIV: 7061 case ISD::SDIV: 7062 assert(Subtarget->isTargetWindows() && "can only expand DIV on Windows"); 7063 return ExpandDIV_Windows(SDValue(N, 0), DAG, N->getOpcode() == ISD::SDIV, 7064 Results); 7065 } 7066 if (Res.getNode()) 7067 Results.push_back(Res); 7068 } 7069 7070 //===----------------------------------------------------------------------===// 7071 // ARM Scheduler Hooks 7072 //===----------------------------------------------------------------------===// 7073 7074 /// SetupEntryBlockForSjLj - Insert code into the entry block that creates and 7075 /// registers the function context. 7076 void ARMTargetLowering:: 7077 SetupEntryBlockForSjLj(MachineInstr *MI, MachineBasicBlock *MBB, 7078 MachineBasicBlock *DispatchBB, int FI) const { 7079 const TargetInstrInfo *TII = Subtarget->getInstrInfo(); 7080 DebugLoc dl = MI->getDebugLoc(); 7081 MachineFunction *MF = MBB->getParent(); 7082 MachineRegisterInfo *MRI = &MF->getRegInfo(); 7083 MachineConstantPool *MCP = MF->getConstantPool(); 7084 ARMFunctionInfo *AFI = MF->getInfo<ARMFunctionInfo>(); 7085 const Function *F = MF->getFunction(); 7086 7087 bool isThumb = Subtarget->isThumb(); 7088 bool isThumb2 = Subtarget->isThumb2(); 7089 7090 unsigned PCLabelId = AFI->createPICLabelUId(); 7091 unsigned PCAdj = (isThumb || isThumb2) ? 4 : 8; 7092 ARMConstantPoolValue *CPV = 7093 ARMConstantPoolMBB::Create(F->getContext(), DispatchBB, PCLabelId, PCAdj); 7094 unsigned CPI = MCP->getConstantPoolIndex(CPV, 4); 7095 7096 const TargetRegisterClass *TRC = isThumb ? &ARM::tGPRRegClass 7097 : &ARM::GPRRegClass; 7098 7099 // Grab constant pool and fixed stack memory operands. 7100 MachineMemOperand *CPMMO = 7101 MF->getMachineMemOperand(MachinePointerInfo::getConstantPool(*MF), 7102 MachineMemOperand::MOLoad, 4, 4); 7103 7104 MachineMemOperand *FIMMOSt = 7105 MF->getMachineMemOperand(MachinePointerInfo::getFixedStack(*MF, FI), 7106 MachineMemOperand::MOStore, 4, 4); 7107 7108 // Load the address of the dispatch MBB into the jump buffer. 7109 if (isThumb2) { 7110 // Incoming value: jbuf 7111 // ldr.n r5, LCPI1_1 7112 // orr r5, r5, #1 7113 // add r5, pc 7114 // str r5, [$jbuf, #+4] ; &jbuf[1] 7115 unsigned NewVReg1 = MRI->createVirtualRegister(TRC); 7116 AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::t2LDRpci), NewVReg1) 7117 .addConstantPoolIndex(CPI) 7118 .addMemOperand(CPMMO)); 7119 // Set the low bit because of thumb mode. 7120 unsigned NewVReg2 = MRI->createVirtualRegister(TRC); 7121 AddDefaultCC( 7122 AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::t2ORRri), NewVReg2) 7123 .addReg(NewVReg1, RegState::Kill) 7124 .addImm(0x01))); 7125 unsigned NewVReg3 = MRI->createVirtualRegister(TRC); 7126 BuildMI(*MBB, MI, dl, TII->get(ARM::tPICADD), NewVReg3) 7127 .addReg(NewVReg2, RegState::Kill) 7128 .addImm(PCLabelId); 7129 AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::t2STRi12)) 7130 .addReg(NewVReg3, RegState::Kill) 7131 .addFrameIndex(FI) 7132 .addImm(36) // &jbuf[1] :: pc 7133 .addMemOperand(FIMMOSt)); 7134 } else if (isThumb) { 7135 // Incoming value: jbuf 7136 // ldr.n r1, LCPI1_4 7137 // add r1, pc 7138 // mov r2, #1 7139 // orrs r1, r2 7140 // add r2, $jbuf, #+4 ; &jbuf[1] 7141 // str r1, [r2] 7142 unsigned NewVReg1 = MRI->createVirtualRegister(TRC); 7143 AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::tLDRpci), NewVReg1) 7144 .addConstantPoolIndex(CPI) 7145 .addMemOperand(CPMMO)); 7146 unsigned NewVReg2 = MRI->createVirtualRegister(TRC); 7147 BuildMI(*MBB, MI, dl, TII->get(ARM::tPICADD), NewVReg2) 7148 .addReg(NewVReg1, RegState::Kill) 7149 .addImm(PCLabelId); 7150 // Set the low bit because of thumb mode. 7151 unsigned NewVReg3 = MRI->createVirtualRegister(TRC); 7152 AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::tMOVi8), NewVReg3) 7153 .addReg(ARM::CPSR, RegState::Define) 7154 .addImm(1)); 7155 unsigned NewVReg4 = MRI->createVirtualRegister(TRC); 7156 AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::tORR), NewVReg4) 7157 .addReg(ARM::CPSR, RegState::Define) 7158 .addReg(NewVReg2, RegState::Kill) 7159 .addReg(NewVReg3, RegState::Kill)); 7160 unsigned NewVReg5 = MRI->createVirtualRegister(TRC); 7161 BuildMI(*MBB, MI, dl, TII->get(ARM::tADDframe), NewVReg5) 7162 .addFrameIndex(FI) 7163 .addImm(36); // &jbuf[1] :: pc 7164 AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::tSTRi)) 7165 .addReg(NewVReg4, RegState::Kill) 7166 .addReg(NewVReg5, RegState::Kill) 7167 .addImm(0) 7168 .addMemOperand(FIMMOSt)); 7169 } else { 7170 // Incoming value: jbuf 7171 // ldr r1, LCPI1_1 7172 // add r1, pc, r1 7173 // str r1, [$jbuf, #+4] ; &jbuf[1] 7174 unsigned NewVReg1 = MRI->createVirtualRegister(TRC); 7175 AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::LDRi12), NewVReg1) 7176 .addConstantPoolIndex(CPI) 7177 .addImm(0) 7178 .addMemOperand(CPMMO)); 7179 unsigned NewVReg2 = MRI->createVirtualRegister(TRC); 7180 AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::PICADD), NewVReg2) 7181 .addReg(NewVReg1, RegState::Kill) 7182 .addImm(PCLabelId)); 7183 AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::STRi12)) 7184 .addReg(NewVReg2, RegState::Kill) 7185 .addFrameIndex(FI) 7186 .addImm(36) // &jbuf[1] :: pc 7187 .addMemOperand(FIMMOSt)); 7188 } 7189 } 7190 7191 void ARMTargetLowering::EmitSjLjDispatchBlock(MachineInstr *MI, 7192 MachineBasicBlock *MBB) const { 7193 const TargetInstrInfo *TII = Subtarget->getInstrInfo(); 7194 DebugLoc dl = MI->getDebugLoc(); 7195 MachineFunction *MF = MBB->getParent(); 7196 MachineRegisterInfo *MRI = &MF->getRegInfo(); 7197 MachineFrameInfo *MFI = MF->getFrameInfo(); 7198 int FI = MFI->getFunctionContextIndex(); 7199 7200 const TargetRegisterClass *TRC = Subtarget->isThumb() ? &ARM::tGPRRegClass 7201 : &ARM::GPRnopcRegClass; 7202 7203 // Get a mapping of the call site numbers to all of the landing pads they're 7204 // associated with. 7205 DenseMap<unsigned, SmallVector<MachineBasicBlock*, 2> > CallSiteNumToLPad; 7206 unsigned MaxCSNum = 0; 7207 MachineModuleInfo &MMI = MF->getMMI(); 7208 for (MachineFunction::iterator BB = MF->begin(), E = MF->end(); BB != E; 7209 ++BB) { 7210 if (!BB->isEHPad()) continue; 7211 7212 // FIXME: We should assert that the EH_LABEL is the first MI in the landing 7213 // pad. 7214 for (MachineBasicBlock::iterator 7215 II = BB->begin(), IE = BB->end(); II != IE; ++II) { 7216 if (!II->isEHLabel()) continue; 7217 7218 MCSymbol *Sym = II->getOperand(0).getMCSymbol(); 7219 if (!MMI.hasCallSiteLandingPad(Sym)) continue; 7220 7221 SmallVectorImpl<unsigned> &CallSiteIdxs = MMI.getCallSiteLandingPad(Sym); 7222 for (SmallVectorImpl<unsigned>::iterator 7223 CSI = CallSiteIdxs.begin(), CSE = CallSiteIdxs.end(); 7224 CSI != CSE; ++CSI) { 7225 CallSiteNumToLPad[*CSI].push_back(&*BB); 7226 MaxCSNum = std::max(MaxCSNum, *CSI); 7227 } 7228 break; 7229 } 7230 } 7231 7232 // Get an ordered list of the machine basic blocks for the jump table. 7233 std::vector<MachineBasicBlock*> LPadList; 7234 SmallPtrSet<MachineBasicBlock*, 32> InvokeBBs; 7235 LPadList.reserve(CallSiteNumToLPad.size()); 7236 for (unsigned I = 1; I <= MaxCSNum; ++I) { 7237 SmallVectorImpl<MachineBasicBlock*> &MBBList = CallSiteNumToLPad[I]; 7238 for (SmallVectorImpl<MachineBasicBlock*>::iterator 7239 II = MBBList.begin(), IE = MBBList.end(); II != IE; ++II) { 7240 LPadList.push_back(*II); 7241 InvokeBBs.insert((*II)->pred_begin(), (*II)->pred_end()); 7242 } 7243 } 7244 7245 assert(!LPadList.empty() && 7246 "No landing pad destinations for the dispatch jump table!"); 7247 7248 // Create the jump table and associated information. 7249 MachineJumpTableInfo *JTI = 7250 MF->getOrCreateJumpTableInfo(MachineJumpTableInfo::EK_Inline); 7251 unsigned MJTI = JTI->createJumpTableIndex(LPadList); 7252 Reloc::Model RelocM = getTargetMachine().getRelocationModel(); 7253 7254 // Create the MBBs for the dispatch code. 7255 7256 // Shove the dispatch's address into the return slot in the function context. 7257 MachineBasicBlock *DispatchBB = MF->CreateMachineBasicBlock(); 7258 DispatchBB->setIsEHPad(); 7259 7260 MachineBasicBlock *TrapBB = MF->CreateMachineBasicBlock(); 7261 unsigned trap_opcode; 7262 if (Subtarget->isThumb()) 7263 trap_opcode = ARM::tTRAP; 7264 else 7265 trap_opcode = Subtarget->useNaClTrap() ? ARM::TRAPNaCl : ARM::TRAP; 7266 7267 BuildMI(TrapBB, dl, TII->get(trap_opcode)); 7268 DispatchBB->addSuccessor(TrapBB); 7269 7270 MachineBasicBlock *DispContBB = MF->CreateMachineBasicBlock(); 7271 DispatchBB->addSuccessor(DispContBB); 7272 7273 // Insert and MBBs. 7274 MF->insert(MF->end(), DispatchBB); 7275 MF->insert(MF->end(), DispContBB); 7276 MF->insert(MF->end(), TrapBB); 7277 7278 // Insert code into the entry block that creates and registers the function 7279 // context. 7280 SetupEntryBlockForSjLj(MI, MBB, DispatchBB, FI); 7281 7282 MachineMemOperand *FIMMOLd = MF->getMachineMemOperand( 7283 MachinePointerInfo::getFixedStack(*MF, FI), 7284 MachineMemOperand::MOLoad | MachineMemOperand::MOVolatile, 4, 4); 7285 7286 MachineInstrBuilder MIB; 7287 MIB = BuildMI(DispatchBB, dl, TII->get(ARM::Int_eh_sjlj_dispatchsetup)); 7288 7289 const ARMBaseInstrInfo *AII = static_cast<const ARMBaseInstrInfo*>(TII); 7290 const ARMBaseRegisterInfo &RI = AII->getRegisterInfo(); 7291 7292 // Add a register mask with no preserved registers. This results in all 7293 // registers being marked as clobbered. 7294 MIB.addRegMask(RI.getNoPreservedMask()); 7295 7296 unsigned NumLPads = LPadList.size(); 7297 if (Subtarget->isThumb2()) { 7298 unsigned NewVReg1 = MRI->createVirtualRegister(TRC); 7299 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::t2LDRi12), NewVReg1) 7300 .addFrameIndex(FI) 7301 .addImm(4) 7302 .addMemOperand(FIMMOLd)); 7303 7304 if (NumLPads < 256) { 7305 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::t2CMPri)) 7306 .addReg(NewVReg1) 7307 .addImm(LPadList.size())); 7308 } else { 7309 unsigned VReg1 = MRI->createVirtualRegister(TRC); 7310 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::t2MOVi16), VReg1) 7311 .addImm(NumLPads & 0xFFFF)); 7312 7313 unsigned VReg2 = VReg1; 7314 if ((NumLPads & 0xFFFF0000) != 0) { 7315 VReg2 = MRI->createVirtualRegister(TRC); 7316 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::t2MOVTi16), VReg2) 7317 .addReg(VReg1) 7318 .addImm(NumLPads >> 16)); 7319 } 7320 7321 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::t2CMPrr)) 7322 .addReg(NewVReg1) 7323 .addReg(VReg2)); 7324 } 7325 7326 BuildMI(DispatchBB, dl, TII->get(ARM::t2Bcc)) 7327 .addMBB(TrapBB) 7328 .addImm(ARMCC::HI) 7329 .addReg(ARM::CPSR); 7330 7331 unsigned NewVReg3 = MRI->createVirtualRegister(TRC); 7332 AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::t2LEApcrelJT),NewVReg3) 7333 .addJumpTableIndex(MJTI)); 7334 7335 unsigned NewVReg4 = MRI->createVirtualRegister(TRC); 7336 AddDefaultCC( 7337 AddDefaultPred( 7338 BuildMI(DispContBB, dl, TII->get(ARM::t2ADDrs), NewVReg4) 7339 .addReg(NewVReg3, RegState::Kill) 7340 .addReg(NewVReg1) 7341 .addImm(ARM_AM::getSORegOpc(ARM_AM::lsl, 2)))); 7342 7343 BuildMI(DispContBB, dl, TII->get(ARM::t2BR_JT)) 7344 .addReg(NewVReg4, RegState::Kill) 7345 .addReg(NewVReg1) 7346 .addJumpTableIndex(MJTI); 7347 } else if (Subtarget->isThumb()) { 7348 unsigned NewVReg1 = MRI->createVirtualRegister(TRC); 7349 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::tLDRspi), NewVReg1) 7350 .addFrameIndex(FI) 7351 .addImm(1) 7352 .addMemOperand(FIMMOLd)); 7353 7354 if (NumLPads < 256) { 7355 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::tCMPi8)) 7356 .addReg(NewVReg1) 7357 .addImm(NumLPads)); 7358 } else { 7359 MachineConstantPool *ConstantPool = MF->getConstantPool(); 7360 Type *Int32Ty = Type::getInt32Ty(MF->getFunction()->getContext()); 7361 const Constant *C = ConstantInt::get(Int32Ty, NumLPads); 7362 7363 // MachineConstantPool wants an explicit alignment. 7364 unsigned Align = MF->getDataLayout().getPrefTypeAlignment(Int32Ty); 7365 if (Align == 0) 7366 Align = MF->getDataLayout().getTypeAllocSize(C->getType()); 7367 unsigned Idx = ConstantPool->getConstantPoolIndex(C, Align); 7368 7369 unsigned VReg1 = MRI->createVirtualRegister(TRC); 7370 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::tLDRpci)) 7371 .addReg(VReg1, RegState::Define) 7372 .addConstantPoolIndex(Idx)); 7373 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::tCMPr)) 7374 .addReg(NewVReg1) 7375 .addReg(VReg1)); 7376 } 7377 7378 BuildMI(DispatchBB, dl, TII->get(ARM::tBcc)) 7379 .addMBB(TrapBB) 7380 .addImm(ARMCC::HI) 7381 .addReg(ARM::CPSR); 7382 7383 unsigned NewVReg2 = MRI->createVirtualRegister(TRC); 7384 AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::tLSLri), NewVReg2) 7385 .addReg(ARM::CPSR, RegState::Define) 7386 .addReg(NewVReg1) 7387 .addImm(2)); 7388 7389 unsigned NewVReg3 = MRI->createVirtualRegister(TRC); 7390 AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::tLEApcrelJT), NewVReg3) 7391 .addJumpTableIndex(MJTI)); 7392 7393 unsigned NewVReg4 = MRI->createVirtualRegister(TRC); 7394 AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::tADDrr), NewVReg4) 7395 .addReg(ARM::CPSR, RegState::Define) 7396 .addReg(NewVReg2, RegState::Kill) 7397 .addReg(NewVReg3)); 7398 7399 MachineMemOperand *JTMMOLd = MF->getMachineMemOperand( 7400 MachinePointerInfo::getJumpTable(*MF), MachineMemOperand::MOLoad, 4, 4); 7401 7402 unsigned NewVReg5 = MRI->createVirtualRegister(TRC); 7403 AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::tLDRi), NewVReg5) 7404 .addReg(NewVReg4, RegState::Kill) 7405 .addImm(0) 7406 .addMemOperand(JTMMOLd)); 7407 7408 unsigned NewVReg6 = NewVReg5; 7409 if (RelocM == Reloc::PIC_) { 7410 NewVReg6 = MRI->createVirtualRegister(TRC); 7411 AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::tADDrr), NewVReg6) 7412 .addReg(ARM::CPSR, RegState::Define) 7413 .addReg(NewVReg5, RegState::Kill) 7414 .addReg(NewVReg3)); 7415 } 7416 7417 BuildMI(DispContBB, dl, TII->get(ARM::tBR_JTr)) 7418 .addReg(NewVReg6, RegState::Kill) 7419 .addJumpTableIndex(MJTI); 7420 } else { 7421 unsigned NewVReg1 = MRI->createVirtualRegister(TRC); 7422 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::LDRi12), NewVReg1) 7423 .addFrameIndex(FI) 7424 .addImm(4) 7425 .addMemOperand(FIMMOLd)); 7426 7427 if (NumLPads < 256) { 7428 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::CMPri)) 7429 .addReg(NewVReg1) 7430 .addImm(NumLPads)); 7431 } else if (Subtarget->hasV6T2Ops() && isUInt<16>(NumLPads)) { 7432 unsigned VReg1 = MRI->createVirtualRegister(TRC); 7433 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::MOVi16), VReg1) 7434 .addImm(NumLPads & 0xFFFF)); 7435 7436 unsigned VReg2 = VReg1; 7437 if ((NumLPads & 0xFFFF0000) != 0) { 7438 VReg2 = MRI->createVirtualRegister(TRC); 7439 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::MOVTi16), VReg2) 7440 .addReg(VReg1) 7441 .addImm(NumLPads >> 16)); 7442 } 7443 7444 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::CMPrr)) 7445 .addReg(NewVReg1) 7446 .addReg(VReg2)); 7447 } else { 7448 MachineConstantPool *ConstantPool = MF->getConstantPool(); 7449 Type *Int32Ty = Type::getInt32Ty(MF->getFunction()->getContext()); 7450 const Constant *C = ConstantInt::get(Int32Ty, NumLPads); 7451 7452 // MachineConstantPool wants an explicit alignment. 7453 unsigned Align = MF->getDataLayout().getPrefTypeAlignment(Int32Ty); 7454 if (Align == 0) 7455 Align = MF->getDataLayout().getTypeAllocSize(C->getType()); 7456 unsigned Idx = ConstantPool->getConstantPoolIndex(C, Align); 7457 7458 unsigned VReg1 = MRI->createVirtualRegister(TRC); 7459 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::LDRcp)) 7460 .addReg(VReg1, RegState::Define) 7461 .addConstantPoolIndex(Idx) 7462 .addImm(0)); 7463 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::CMPrr)) 7464 .addReg(NewVReg1) 7465 .addReg(VReg1, RegState::Kill)); 7466 } 7467 7468 BuildMI(DispatchBB, dl, TII->get(ARM::Bcc)) 7469 .addMBB(TrapBB) 7470 .addImm(ARMCC::HI) 7471 .addReg(ARM::CPSR); 7472 7473 unsigned NewVReg3 = MRI->createVirtualRegister(TRC); 7474 AddDefaultCC( 7475 AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::MOVsi), NewVReg3) 7476 .addReg(NewVReg1) 7477 .addImm(ARM_AM::getSORegOpc(ARM_AM::lsl, 2)))); 7478 unsigned NewVReg4 = MRI->createVirtualRegister(TRC); 7479 AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::LEApcrelJT), NewVReg4) 7480 .addJumpTableIndex(MJTI)); 7481 7482 MachineMemOperand *JTMMOLd = MF->getMachineMemOperand( 7483 MachinePointerInfo::getJumpTable(*MF), MachineMemOperand::MOLoad, 4, 4); 7484 unsigned NewVReg5 = MRI->createVirtualRegister(TRC); 7485 AddDefaultPred( 7486 BuildMI(DispContBB, dl, TII->get(ARM::LDRrs), NewVReg5) 7487 .addReg(NewVReg3, RegState::Kill) 7488 .addReg(NewVReg4) 7489 .addImm(0) 7490 .addMemOperand(JTMMOLd)); 7491 7492 if (RelocM == Reloc::PIC_) { 7493 BuildMI(DispContBB, dl, TII->get(ARM::BR_JTadd)) 7494 .addReg(NewVReg5, RegState::Kill) 7495 .addReg(NewVReg4) 7496 .addJumpTableIndex(MJTI); 7497 } else { 7498 BuildMI(DispContBB, dl, TII->get(ARM::BR_JTr)) 7499 .addReg(NewVReg5, RegState::Kill) 7500 .addJumpTableIndex(MJTI); 7501 } 7502 } 7503 7504 // Add the jump table entries as successors to the MBB. 7505 SmallPtrSet<MachineBasicBlock*, 8> SeenMBBs; 7506 for (std::vector<MachineBasicBlock*>::iterator 7507 I = LPadList.begin(), E = LPadList.end(); I != E; ++I) { 7508 MachineBasicBlock *CurMBB = *I; 7509 if (SeenMBBs.insert(CurMBB).second) 7510 DispContBB->addSuccessor(CurMBB); 7511 } 7512 7513 // N.B. the order the invoke BBs are processed in doesn't matter here. 7514 const MCPhysReg *SavedRegs = RI.getCalleeSavedRegs(MF); 7515 SmallVector<MachineBasicBlock*, 64> MBBLPads; 7516 for (MachineBasicBlock *BB : InvokeBBs) { 7517 7518 // Remove the landing pad successor from the invoke block and replace it 7519 // with the new dispatch block. 7520 SmallVector<MachineBasicBlock*, 4> Successors(BB->succ_begin(), 7521 BB->succ_end()); 7522 while (!Successors.empty()) { 7523 MachineBasicBlock *SMBB = Successors.pop_back_val(); 7524 if (SMBB->isEHPad()) { 7525 BB->removeSuccessor(SMBB); 7526 MBBLPads.push_back(SMBB); 7527 } 7528 } 7529 7530 BB->addSuccessor(DispatchBB, BranchProbability::getZero()); 7531 BB->normalizeSuccProbs(); 7532 7533 // Find the invoke call and mark all of the callee-saved registers as 7534 // 'implicit defined' so that they're spilled. This prevents code from 7535 // moving instructions to before the EH block, where they will never be 7536 // executed. 7537 for (MachineBasicBlock::reverse_iterator 7538 II = BB->rbegin(), IE = BB->rend(); II != IE; ++II) { 7539 if (!II->isCall()) continue; 7540 7541 DenseMap<unsigned, bool> DefRegs; 7542 for (MachineInstr::mop_iterator 7543 OI = II->operands_begin(), OE = II->operands_end(); 7544 OI != OE; ++OI) { 7545 if (!OI->isReg()) continue; 7546 DefRegs[OI->getReg()] = true; 7547 } 7548 7549 MachineInstrBuilder MIB(*MF, &*II); 7550 7551 for (unsigned i = 0; SavedRegs[i] != 0; ++i) { 7552 unsigned Reg = SavedRegs[i]; 7553 if (Subtarget->isThumb2() && 7554 !ARM::tGPRRegClass.contains(Reg) && 7555 !ARM::hGPRRegClass.contains(Reg)) 7556 continue; 7557 if (Subtarget->isThumb1Only() && !ARM::tGPRRegClass.contains(Reg)) 7558 continue; 7559 if (!Subtarget->isThumb() && !ARM::GPRRegClass.contains(Reg)) 7560 continue; 7561 if (!DefRegs[Reg]) 7562 MIB.addReg(Reg, RegState::ImplicitDefine | RegState::Dead); 7563 } 7564 7565 break; 7566 } 7567 } 7568 7569 // Mark all former landing pads as non-landing pads. The dispatch is the only 7570 // landing pad now. 7571 for (SmallVectorImpl<MachineBasicBlock*>::iterator 7572 I = MBBLPads.begin(), E = MBBLPads.end(); I != E; ++I) 7573 (*I)->setIsEHPad(false); 7574 7575 // The instruction is gone now. 7576 MI->eraseFromParent(); 7577 } 7578 7579 static 7580 MachineBasicBlock *OtherSucc(MachineBasicBlock *MBB, MachineBasicBlock *Succ) { 7581 for (MachineBasicBlock::succ_iterator I = MBB->succ_begin(), 7582 E = MBB->succ_end(); I != E; ++I) 7583 if (*I != Succ) 7584 return *I; 7585 llvm_unreachable("Expecting a BB with two successors!"); 7586 } 7587 7588 /// Return the load opcode for a given load size. If load size >= 8, 7589 /// neon opcode will be returned. 7590 static unsigned getLdOpcode(unsigned LdSize, bool IsThumb1, bool IsThumb2) { 7591 if (LdSize >= 8) 7592 return LdSize == 16 ? ARM::VLD1q32wb_fixed 7593 : LdSize == 8 ? ARM::VLD1d32wb_fixed : 0; 7594 if (IsThumb1) 7595 return LdSize == 4 ? ARM::tLDRi 7596 : LdSize == 2 ? ARM::tLDRHi 7597 : LdSize == 1 ? ARM::tLDRBi : 0; 7598 if (IsThumb2) 7599 return LdSize == 4 ? ARM::t2LDR_POST 7600 : LdSize == 2 ? ARM::t2LDRH_POST 7601 : LdSize == 1 ? ARM::t2LDRB_POST : 0; 7602 return LdSize == 4 ? ARM::LDR_POST_IMM 7603 : LdSize == 2 ? ARM::LDRH_POST 7604 : LdSize == 1 ? ARM::LDRB_POST_IMM : 0; 7605 } 7606 7607 /// Return the store opcode for a given store size. If store size >= 8, 7608 /// neon opcode will be returned. 7609 static unsigned getStOpcode(unsigned StSize, bool IsThumb1, bool IsThumb2) { 7610 if (StSize >= 8) 7611 return StSize == 16 ? ARM::VST1q32wb_fixed 7612 : StSize == 8 ? ARM::VST1d32wb_fixed : 0; 7613 if (IsThumb1) 7614 return StSize == 4 ? ARM::tSTRi 7615 : StSize == 2 ? ARM::tSTRHi 7616 : StSize == 1 ? ARM::tSTRBi : 0; 7617 if (IsThumb2) 7618 return StSize == 4 ? ARM::t2STR_POST 7619 : StSize == 2 ? ARM::t2STRH_POST 7620 : StSize == 1 ? ARM::t2STRB_POST : 0; 7621 return StSize == 4 ? ARM::STR_POST_IMM 7622 : StSize == 2 ? ARM::STRH_POST 7623 : StSize == 1 ? ARM::STRB_POST_IMM : 0; 7624 } 7625 7626 /// Emit a post-increment load operation with given size. The instructions 7627 /// will be added to BB at Pos. 7628 static void emitPostLd(MachineBasicBlock *BB, MachineInstr *Pos, 7629 const TargetInstrInfo *TII, DebugLoc dl, 7630 unsigned LdSize, unsigned Data, unsigned AddrIn, 7631 unsigned AddrOut, bool IsThumb1, bool IsThumb2) { 7632 unsigned LdOpc = getLdOpcode(LdSize, IsThumb1, IsThumb2); 7633 assert(LdOpc != 0 && "Should have a load opcode"); 7634 if (LdSize >= 8) { 7635 AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(LdOpc), Data) 7636 .addReg(AddrOut, RegState::Define).addReg(AddrIn) 7637 .addImm(0)); 7638 } else if (IsThumb1) { 7639 // load + update AddrIn 7640 AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(LdOpc), Data) 7641 .addReg(AddrIn).addImm(0)); 7642 MachineInstrBuilder MIB = 7643 BuildMI(*BB, Pos, dl, TII->get(ARM::tADDi8), AddrOut); 7644 MIB = AddDefaultT1CC(MIB); 7645 MIB.addReg(AddrIn).addImm(LdSize); 7646 AddDefaultPred(MIB); 7647 } else if (IsThumb2) { 7648 AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(LdOpc), Data) 7649 .addReg(AddrOut, RegState::Define).addReg(AddrIn) 7650 .addImm(LdSize)); 7651 } else { // arm 7652 AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(LdOpc), Data) 7653 .addReg(AddrOut, RegState::Define).addReg(AddrIn) 7654 .addReg(0).addImm(LdSize)); 7655 } 7656 } 7657 7658 /// Emit a post-increment store operation with given size. The instructions 7659 /// will be added to BB at Pos. 7660 static void emitPostSt(MachineBasicBlock *BB, MachineInstr *Pos, 7661 const TargetInstrInfo *TII, DebugLoc dl, 7662 unsigned StSize, unsigned Data, unsigned AddrIn, 7663 unsigned AddrOut, bool IsThumb1, bool IsThumb2) { 7664 unsigned StOpc = getStOpcode(StSize, IsThumb1, IsThumb2); 7665 assert(StOpc != 0 && "Should have a store opcode"); 7666 if (StSize >= 8) { 7667 AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(StOpc), AddrOut) 7668 .addReg(AddrIn).addImm(0).addReg(Data)); 7669 } else if (IsThumb1) { 7670 // store + update AddrIn 7671 AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(StOpc)).addReg(Data) 7672 .addReg(AddrIn).addImm(0)); 7673 MachineInstrBuilder MIB = 7674 BuildMI(*BB, Pos, dl, TII->get(ARM::tADDi8), AddrOut); 7675 MIB = AddDefaultT1CC(MIB); 7676 MIB.addReg(AddrIn).addImm(StSize); 7677 AddDefaultPred(MIB); 7678 } else if (IsThumb2) { 7679 AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(StOpc), AddrOut) 7680 .addReg(Data).addReg(AddrIn).addImm(StSize)); 7681 } else { // arm 7682 AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(StOpc), AddrOut) 7683 .addReg(Data).addReg(AddrIn).addReg(0) 7684 .addImm(StSize)); 7685 } 7686 } 7687 7688 MachineBasicBlock * 7689 ARMTargetLowering::EmitStructByval(MachineInstr *MI, 7690 MachineBasicBlock *BB) const { 7691 // This pseudo instruction has 3 operands: dst, src, size 7692 // We expand it to a loop if size > Subtarget->getMaxInlineSizeThreshold(). 7693 // Otherwise, we will generate unrolled scalar copies. 7694 const TargetInstrInfo *TII = Subtarget->getInstrInfo(); 7695 const BasicBlock *LLVM_BB = BB->getBasicBlock(); 7696 MachineFunction::iterator It = ++BB->getIterator(); 7697 7698 unsigned dest = MI->getOperand(0).getReg(); 7699 unsigned src = MI->getOperand(1).getReg(); 7700 unsigned SizeVal = MI->getOperand(2).getImm(); 7701 unsigned Align = MI->getOperand(3).getImm(); 7702 DebugLoc dl = MI->getDebugLoc(); 7703 7704 MachineFunction *MF = BB->getParent(); 7705 MachineRegisterInfo &MRI = MF->getRegInfo(); 7706 unsigned UnitSize = 0; 7707 const TargetRegisterClass *TRC = nullptr; 7708 const TargetRegisterClass *VecTRC = nullptr; 7709 7710 bool IsThumb1 = Subtarget->isThumb1Only(); 7711 bool IsThumb2 = Subtarget->isThumb2(); 7712 7713 if (Align & 1) { 7714 UnitSize = 1; 7715 } else if (Align & 2) { 7716 UnitSize = 2; 7717 } else { 7718 // Check whether we can use NEON instructions. 7719 if (!MF->getFunction()->hasFnAttribute(Attribute::NoImplicitFloat) && 7720 Subtarget->hasNEON()) { 7721 if ((Align % 16 == 0) && SizeVal >= 16) 7722 UnitSize = 16; 7723 else if ((Align % 8 == 0) && SizeVal >= 8) 7724 UnitSize = 8; 7725 } 7726 // Can't use NEON instructions. 7727 if (UnitSize == 0) 7728 UnitSize = 4; 7729 } 7730 7731 // Select the correct opcode and register class for unit size load/store 7732 bool IsNeon = UnitSize >= 8; 7733 TRC = (IsThumb1 || IsThumb2) ? &ARM::tGPRRegClass : &ARM::GPRRegClass; 7734 if (IsNeon) 7735 VecTRC = UnitSize == 16 ? &ARM::DPairRegClass 7736 : UnitSize == 8 ? &ARM::DPRRegClass 7737 : nullptr; 7738 7739 unsigned BytesLeft = SizeVal % UnitSize; 7740 unsigned LoopSize = SizeVal - BytesLeft; 7741 7742 if (SizeVal <= Subtarget->getMaxInlineSizeThreshold()) { 7743 // Use LDR and STR to copy. 7744 // [scratch, srcOut] = LDR_POST(srcIn, UnitSize) 7745 // [destOut] = STR_POST(scratch, destIn, UnitSize) 7746 unsigned srcIn = src; 7747 unsigned destIn = dest; 7748 for (unsigned i = 0; i < LoopSize; i+=UnitSize) { 7749 unsigned srcOut = MRI.createVirtualRegister(TRC); 7750 unsigned destOut = MRI.createVirtualRegister(TRC); 7751 unsigned scratch = MRI.createVirtualRegister(IsNeon ? VecTRC : TRC); 7752 emitPostLd(BB, MI, TII, dl, UnitSize, scratch, srcIn, srcOut, 7753 IsThumb1, IsThumb2); 7754 emitPostSt(BB, MI, TII, dl, UnitSize, scratch, destIn, destOut, 7755 IsThumb1, IsThumb2); 7756 srcIn = srcOut; 7757 destIn = destOut; 7758 } 7759 7760 // Handle the leftover bytes with LDRB and STRB. 7761 // [scratch, srcOut] = LDRB_POST(srcIn, 1) 7762 // [destOut] = STRB_POST(scratch, destIn, 1) 7763 for (unsigned i = 0; i < BytesLeft; i++) { 7764 unsigned srcOut = MRI.createVirtualRegister(TRC); 7765 unsigned destOut = MRI.createVirtualRegister(TRC); 7766 unsigned scratch = MRI.createVirtualRegister(TRC); 7767 emitPostLd(BB, MI, TII, dl, 1, scratch, srcIn, srcOut, 7768 IsThumb1, IsThumb2); 7769 emitPostSt(BB, MI, TII, dl, 1, scratch, destIn, destOut, 7770 IsThumb1, IsThumb2); 7771 srcIn = srcOut; 7772 destIn = destOut; 7773 } 7774 MI->eraseFromParent(); // The instruction is gone now. 7775 return BB; 7776 } 7777 7778 // Expand the pseudo op to a loop. 7779 // thisMBB: 7780 // ... 7781 // movw varEnd, # --> with thumb2 7782 // movt varEnd, # 7783 // ldrcp varEnd, idx --> without thumb2 7784 // fallthrough --> loopMBB 7785 // loopMBB: 7786 // PHI varPhi, varEnd, varLoop 7787 // PHI srcPhi, src, srcLoop 7788 // PHI destPhi, dst, destLoop 7789 // [scratch, srcLoop] = LDR_POST(srcPhi, UnitSize) 7790 // [destLoop] = STR_POST(scratch, destPhi, UnitSize) 7791 // subs varLoop, varPhi, #UnitSize 7792 // bne loopMBB 7793 // fallthrough --> exitMBB 7794 // exitMBB: 7795 // epilogue to handle left-over bytes 7796 // [scratch, srcOut] = LDRB_POST(srcLoop, 1) 7797 // [destOut] = STRB_POST(scratch, destLoop, 1) 7798 MachineBasicBlock *loopMBB = MF->CreateMachineBasicBlock(LLVM_BB); 7799 MachineBasicBlock *exitMBB = MF->CreateMachineBasicBlock(LLVM_BB); 7800 MF->insert(It, loopMBB); 7801 MF->insert(It, exitMBB); 7802 7803 // Transfer the remainder of BB and its successor edges to exitMBB. 7804 exitMBB->splice(exitMBB->begin(), BB, 7805 std::next(MachineBasicBlock::iterator(MI)), BB->end()); 7806 exitMBB->transferSuccessorsAndUpdatePHIs(BB); 7807 7808 // Load an immediate to varEnd. 7809 unsigned varEnd = MRI.createVirtualRegister(TRC); 7810 if (Subtarget->useMovt(*MF)) { 7811 unsigned Vtmp = varEnd; 7812 if ((LoopSize & 0xFFFF0000) != 0) 7813 Vtmp = MRI.createVirtualRegister(TRC); 7814 AddDefaultPred(BuildMI(BB, dl, 7815 TII->get(IsThumb2 ? ARM::t2MOVi16 : ARM::MOVi16), 7816 Vtmp).addImm(LoopSize & 0xFFFF)); 7817 7818 if ((LoopSize & 0xFFFF0000) != 0) 7819 AddDefaultPred(BuildMI(BB, dl, 7820 TII->get(IsThumb2 ? ARM::t2MOVTi16 : ARM::MOVTi16), 7821 varEnd) 7822 .addReg(Vtmp) 7823 .addImm(LoopSize >> 16)); 7824 } else { 7825 MachineConstantPool *ConstantPool = MF->getConstantPool(); 7826 Type *Int32Ty = Type::getInt32Ty(MF->getFunction()->getContext()); 7827 const Constant *C = ConstantInt::get(Int32Ty, LoopSize); 7828 7829 // MachineConstantPool wants an explicit alignment. 7830 unsigned Align = MF->getDataLayout().getPrefTypeAlignment(Int32Ty); 7831 if (Align == 0) 7832 Align = MF->getDataLayout().getTypeAllocSize(C->getType()); 7833 unsigned Idx = ConstantPool->getConstantPoolIndex(C, Align); 7834 7835 if (IsThumb1) 7836 AddDefaultPred(BuildMI(*BB, MI, dl, TII->get(ARM::tLDRpci)).addReg( 7837 varEnd, RegState::Define).addConstantPoolIndex(Idx)); 7838 else 7839 AddDefaultPred(BuildMI(*BB, MI, dl, TII->get(ARM::LDRcp)).addReg( 7840 varEnd, RegState::Define).addConstantPoolIndex(Idx).addImm(0)); 7841 } 7842 BB->addSuccessor(loopMBB); 7843 7844 // Generate the loop body: 7845 // varPhi = PHI(varLoop, varEnd) 7846 // srcPhi = PHI(srcLoop, src) 7847 // destPhi = PHI(destLoop, dst) 7848 MachineBasicBlock *entryBB = BB; 7849 BB = loopMBB; 7850 unsigned varLoop = MRI.createVirtualRegister(TRC); 7851 unsigned varPhi = MRI.createVirtualRegister(TRC); 7852 unsigned srcLoop = MRI.createVirtualRegister(TRC); 7853 unsigned srcPhi = MRI.createVirtualRegister(TRC); 7854 unsigned destLoop = MRI.createVirtualRegister(TRC); 7855 unsigned destPhi = MRI.createVirtualRegister(TRC); 7856 7857 BuildMI(*BB, BB->begin(), dl, TII->get(ARM::PHI), varPhi) 7858 .addReg(varLoop).addMBB(loopMBB) 7859 .addReg(varEnd).addMBB(entryBB); 7860 BuildMI(BB, dl, TII->get(ARM::PHI), srcPhi) 7861 .addReg(srcLoop).addMBB(loopMBB) 7862 .addReg(src).addMBB(entryBB); 7863 BuildMI(BB, dl, TII->get(ARM::PHI), destPhi) 7864 .addReg(destLoop).addMBB(loopMBB) 7865 .addReg(dest).addMBB(entryBB); 7866 7867 // [scratch, srcLoop] = LDR_POST(srcPhi, UnitSize) 7868 // [destLoop] = STR_POST(scratch, destPhi, UnitSiz) 7869 unsigned scratch = MRI.createVirtualRegister(IsNeon ? VecTRC : TRC); 7870 emitPostLd(BB, BB->end(), TII, dl, UnitSize, scratch, srcPhi, srcLoop, 7871 IsThumb1, IsThumb2); 7872 emitPostSt(BB, BB->end(), TII, dl, UnitSize, scratch, destPhi, destLoop, 7873 IsThumb1, IsThumb2); 7874 7875 // Decrement loop variable by UnitSize. 7876 if (IsThumb1) { 7877 MachineInstrBuilder MIB = 7878 BuildMI(*BB, BB->end(), dl, TII->get(ARM::tSUBi8), varLoop); 7879 MIB = AddDefaultT1CC(MIB); 7880 MIB.addReg(varPhi).addImm(UnitSize); 7881 AddDefaultPred(MIB); 7882 } else { 7883 MachineInstrBuilder MIB = 7884 BuildMI(*BB, BB->end(), dl, 7885 TII->get(IsThumb2 ? ARM::t2SUBri : ARM::SUBri), varLoop); 7886 AddDefaultCC(AddDefaultPred(MIB.addReg(varPhi).addImm(UnitSize))); 7887 MIB->getOperand(5).setReg(ARM::CPSR); 7888 MIB->getOperand(5).setIsDef(true); 7889 } 7890 BuildMI(*BB, BB->end(), dl, 7891 TII->get(IsThumb1 ? ARM::tBcc : IsThumb2 ? ARM::t2Bcc : ARM::Bcc)) 7892 .addMBB(loopMBB).addImm(ARMCC::NE).addReg(ARM::CPSR); 7893 7894 // loopMBB can loop back to loopMBB or fall through to exitMBB. 7895 BB->addSuccessor(loopMBB); 7896 BB->addSuccessor(exitMBB); 7897 7898 // Add epilogue to handle BytesLeft. 7899 BB = exitMBB; 7900 MachineInstr *StartOfExit = exitMBB->begin(); 7901 7902 // [scratch, srcOut] = LDRB_POST(srcLoop, 1) 7903 // [destOut] = STRB_POST(scratch, destLoop, 1) 7904 unsigned srcIn = srcLoop; 7905 unsigned destIn = destLoop; 7906 for (unsigned i = 0; i < BytesLeft; i++) { 7907 unsigned srcOut = MRI.createVirtualRegister(TRC); 7908 unsigned destOut = MRI.createVirtualRegister(TRC); 7909 unsigned scratch = MRI.createVirtualRegister(TRC); 7910 emitPostLd(BB, StartOfExit, TII, dl, 1, scratch, srcIn, srcOut, 7911 IsThumb1, IsThumb2); 7912 emitPostSt(BB, StartOfExit, TII, dl, 1, scratch, destIn, destOut, 7913 IsThumb1, IsThumb2); 7914 srcIn = srcOut; 7915 destIn = destOut; 7916 } 7917 7918 MI->eraseFromParent(); // The instruction is gone now. 7919 return BB; 7920 } 7921 7922 MachineBasicBlock * 7923 ARMTargetLowering::EmitLowered__chkstk(MachineInstr *MI, 7924 MachineBasicBlock *MBB) const { 7925 const TargetMachine &TM = getTargetMachine(); 7926 const TargetInstrInfo &TII = *Subtarget->getInstrInfo(); 7927 DebugLoc DL = MI->getDebugLoc(); 7928 7929 assert(Subtarget->isTargetWindows() && 7930 "__chkstk is only supported on Windows"); 7931 assert(Subtarget->isThumb2() && "Windows on ARM requires Thumb-2 mode"); 7932 7933 // __chkstk takes the number of words to allocate on the stack in R4, and 7934 // returns the stack adjustment in number of bytes in R4. This will not 7935 // clober any other registers (other than the obvious lr). 7936 // 7937 // Although, technically, IP should be considered a register which may be 7938 // clobbered, the call itself will not touch it. Windows on ARM is a pure 7939 // thumb-2 environment, so there is no interworking required. As a result, we 7940 // do not expect a veneer to be emitted by the linker, clobbering IP. 7941 // 7942 // Each module receives its own copy of __chkstk, so no import thunk is 7943 // required, again, ensuring that IP is not clobbered. 7944 // 7945 // Finally, although some linkers may theoretically provide a trampoline for 7946 // out of range calls (which is quite common due to a 32M range limitation of 7947 // branches for Thumb), we can generate the long-call version via 7948 // -mcmodel=large, alleviating the need for the trampoline which may clobber 7949 // IP. 7950 7951 switch (TM.getCodeModel()) { 7952 case CodeModel::Small: 7953 case CodeModel::Medium: 7954 case CodeModel::Default: 7955 case CodeModel::Kernel: 7956 BuildMI(*MBB, MI, DL, TII.get(ARM::tBL)) 7957 .addImm((unsigned)ARMCC::AL).addReg(0) 7958 .addExternalSymbol("__chkstk") 7959 .addReg(ARM::R4, RegState::Implicit | RegState::Kill) 7960 .addReg(ARM::R4, RegState::Implicit | RegState::Define) 7961 .addReg(ARM::R12, RegState::Implicit | RegState::Define | RegState::Dead); 7962 break; 7963 case CodeModel::Large: 7964 case CodeModel::JITDefault: { 7965 MachineRegisterInfo &MRI = MBB->getParent()->getRegInfo(); 7966 unsigned Reg = MRI.createVirtualRegister(&ARM::rGPRRegClass); 7967 7968 BuildMI(*MBB, MI, DL, TII.get(ARM::t2MOVi32imm), Reg) 7969 .addExternalSymbol("__chkstk"); 7970 BuildMI(*MBB, MI, DL, TII.get(ARM::tBLXr)) 7971 .addImm((unsigned)ARMCC::AL).addReg(0) 7972 .addReg(Reg, RegState::Kill) 7973 .addReg(ARM::R4, RegState::Implicit | RegState::Kill) 7974 .addReg(ARM::R4, RegState::Implicit | RegState::Define) 7975 .addReg(ARM::R12, RegState::Implicit | RegState::Define | RegState::Dead); 7976 break; 7977 } 7978 } 7979 7980 AddDefaultCC(AddDefaultPred(BuildMI(*MBB, MI, DL, TII.get(ARM::t2SUBrr), 7981 ARM::SP) 7982 .addReg(ARM::SP).addReg(ARM::R4))); 7983 7984 MI->eraseFromParent(); 7985 return MBB; 7986 } 7987 7988 MachineBasicBlock * 7989 ARMTargetLowering::EmitLowered__dbzchk(MachineInstr *MI, 7990 MachineBasicBlock *MBB) const { 7991 DebugLoc DL = MI->getDebugLoc(); 7992 MachineFunction *MF = MBB->getParent(); 7993 const TargetInstrInfo *TII = Subtarget->getInstrInfo(); 7994 7995 MachineBasicBlock *ContBB = MF->CreateMachineBasicBlock(); 7996 MF->push_back(ContBB); 7997 ContBB->splice(ContBB->begin(), MBB, 7998 std::next(MachineBasicBlock::iterator(MI)), MBB->end()); 7999 MBB->addSuccessor(ContBB); 8000 8001 MachineBasicBlock *TrapBB = MF->CreateMachineBasicBlock(); 8002 MF->push_back(TrapBB); 8003 BuildMI(TrapBB, DL, TII->get(ARM::t2UDF)).addImm(249); 8004 MBB->addSuccessor(TrapBB); 8005 8006 BuildMI(*MBB, MI, DL, TII->get(ARM::tCBZ)) 8007 .addReg(MI->getOperand(0).getReg()) 8008 .addMBB(TrapBB); 8009 8010 MI->eraseFromParent(); 8011 return ContBB; 8012 } 8013 8014 MachineBasicBlock * 8015 ARMTargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI, 8016 MachineBasicBlock *BB) const { 8017 const TargetInstrInfo *TII = Subtarget->getInstrInfo(); 8018 DebugLoc dl = MI->getDebugLoc(); 8019 bool isThumb2 = Subtarget->isThumb2(); 8020 switch (MI->getOpcode()) { 8021 default: { 8022 MI->dump(); 8023 llvm_unreachable("Unexpected instr type to insert"); 8024 } 8025 // The Thumb2 pre-indexed stores have the same MI operands, they just 8026 // define them differently in the .td files from the isel patterns, so 8027 // they need pseudos. 8028 case ARM::t2STR_preidx: 8029 MI->setDesc(TII->get(ARM::t2STR_PRE)); 8030 return BB; 8031 case ARM::t2STRB_preidx: 8032 MI->setDesc(TII->get(ARM::t2STRB_PRE)); 8033 return BB; 8034 case ARM::t2STRH_preidx: 8035 MI->setDesc(TII->get(ARM::t2STRH_PRE)); 8036 return BB; 8037 8038 case ARM::STRi_preidx: 8039 case ARM::STRBi_preidx: { 8040 unsigned NewOpc = MI->getOpcode() == ARM::STRi_preidx ? 8041 ARM::STR_PRE_IMM : ARM::STRB_PRE_IMM; 8042 // Decode the offset. 8043 unsigned Offset = MI->getOperand(4).getImm(); 8044 bool isSub = ARM_AM::getAM2Op(Offset) == ARM_AM::sub; 8045 Offset = ARM_AM::getAM2Offset(Offset); 8046 if (isSub) 8047 Offset = -Offset; 8048 8049 MachineMemOperand *MMO = *MI->memoperands_begin(); 8050 BuildMI(*BB, MI, dl, TII->get(NewOpc)) 8051 .addOperand(MI->getOperand(0)) // Rn_wb 8052 .addOperand(MI->getOperand(1)) // Rt 8053 .addOperand(MI->getOperand(2)) // Rn 8054 .addImm(Offset) // offset (skip GPR==zero_reg) 8055 .addOperand(MI->getOperand(5)) // pred 8056 .addOperand(MI->getOperand(6)) 8057 .addMemOperand(MMO); 8058 MI->eraseFromParent(); 8059 return BB; 8060 } 8061 case ARM::STRr_preidx: 8062 case ARM::STRBr_preidx: 8063 case ARM::STRH_preidx: { 8064 unsigned NewOpc; 8065 switch (MI->getOpcode()) { 8066 default: llvm_unreachable("unexpected opcode!"); 8067 case ARM::STRr_preidx: NewOpc = ARM::STR_PRE_REG; break; 8068 case ARM::STRBr_preidx: NewOpc = ARM::STRB_PRE_REG; break; 8069 case ARM::STRH_preidx: NewOpc = ARM::STRH_PRE; break; 8070 } 8071 MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(NewOpc)); 8072 for (unsigned i = 0; i < MI->getNumOperands(); ++i) 8073 MIB.addOperand(MI->getOperand(i)); 8074 MI->eraseFromParent(); 8075 return BB; 8076 } 8077 8078 case ARM::tMOVCCr_pseudo: { 8079 // To "insert" a SELECT_CC instruction, we actually have to insert the 8080 // diamond control-flow pattern. The incoming instruction knows the 8081 // destination vreg to set, the condition code register to branch on, the 8082 // true/false values to select between, and a branch opcode to use. 8083 const BasicBlock *LLVM_BB = BB->getBasicBlock(); 8084 MachineFunction::iterator It = ++BB->getIterator(); 8085 8086 // thisMBB: 8087 // ... 8088 // TrueVal = ... 8089 // cmpTY ccX, r1, r2 8090 // bCC copy1MBB 8091 // fallthrough --> copy0MBB 8092 MachineBasicBlock *thisMBB = BB; 8093 MachineFunction *F = BB->getParent(); 8094 MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB); 8095 MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB); 8096 F->insert(It, copy0MBB); 8097 F->insert(It, sinkMBB); 8098 8099 // Transfer the remainder of BB and its successor edges to sinkMBB. 8100 sinkMBB->splice(sinkMBB->begin(), BB, 8101 std::next(MachineBasicBlock::iterator(MI)), BB->end()); 8102 sinkMBB->transferSuccessorsAndUpdatePHIs(BB); 8103 8104 BB->addSuccessor(copy0MBB); 8105 BB->addSuccessor(sinkMBB); 8106 8107 BuildMI(BB, dl, TII->get(ARM::tBcc)).addMBB(sinkMBB) 8108 .addImm(MI->getOperand(3).getImm()).addReg(MI->getOperand(4).getReg()); 8109 8110 // copy0MBB: 8111 // %FalseValue = ... 8112 // # fallthrough to sinkMBB 8113 BB = copy0MBB; 8114 8115 // Update machine-CFG edges 8116 BB->addSuccessor(sinkMBB); 8117 8118 // sinkMBB: 8119 // %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ] 8120 // ... 8121 BB = sinkMBB; 8122 BuildMI(*BB, BB->begin(), dl, 8123 TII->get(ARM::PHI), MI->getOperand(0).getReg()) 8124 .addReg(MI->getOperand(1).getReg()).addMBB(copy0MBB) 8125 .addReg(MI->getOperand(2).getReg()).addMBB(thisMBB); 8126 8127 MI->eraseFromParent(); // The pseudo instruction is gone now. 8128 return BB; 8129 } 8130 8131 case ARM::BCCi64: 8132 case ARM::BCCZi64: { 8133 // If there is an unconditional branch to the other successor, remove it. 8134 BB->erase(std::next(MachineBasicBlock::iterator(MI)), BB->end()); 8135 8136 // Compare both parts that make up the double comparison separately for 8137 // equality. 8138 bool RHSisZero = MI->getOpcode() == ARM::BCCZi64; 8139 8140 unsigned LHS1 = MI->getOperand(1).getReg(); 8141 unsigned LHS2 = MI->getOperand(2).getReg(); 8142 if (RHSisZero) { 8143 AddDefaultPred(BuildMI(BB, dl, 8144 TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri)) 8145 .addReg(LHS1).addImm(0)); 8146 BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri)) 8147 .addReg(LHS2).addImm(0) 8148 .addImm(ARMCC::EQ).addReg(ARM::CPSR); 8149 } else { 8150 unsigned RHS1 = MI->getOperand(3).getReg(); 8151 unsigned RHS2 = MI->getOperand(4).getReg(); 8152 AddDefaultPred(BuildMI(BB, dl, 8153 TII->get(isThumb2 ? ARM::t2CMPrr : ARM::CMPrr)) 8154 .addReg(LHS1).addReg(RHS1)); 8155 BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPrr : ARM::CMPrr)) 8156 .addReg(LHS2).addReg(RHS2) 8157 .addImm(ARMCC::EQ).addReg(ARM::CPSR); 8158 } 8159 8160 MachineBasicBlock *destMBB = MI->getOperand(RHSisZero ? 3 : 5).getMBB(); 8161 MachineBasicBlock *exitMBB = OtherSucc(BB, destMBB); 8162 if (MI->getOperand(0).getImm() == ARMCC::NE) 8163 std::swap(destMBB, exitMBB); 8164 8165 BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc)) 8166 .addMBB(destMBB).addImm(ARMCC::EQ).addReg(ARM::CPSR); 8167 if (isThumb2) 8168 AddDefaultPred(BuildMI(BB, dl, TII->get(ARM::t2B)).addMBB(exitMBB)); 8169 else 8170 BuildMI(BB, dl, TII->get(ARM::B)) .addMBB(exitMBB); 8171 8172 MI->eraseFromParent(); // The pseudo instruction is gone now. 8173 return BB; 8174 } 8175 8176 case ARM::Int_eh_sjlj_setjmp: 8177 case ARM::Int_eh_sjlj_setjmp_nofp: 8178 case ARM::tInt_eh_sjlj_setjmp: 8179 case ARM::t2Int_eh_sjlj_setjmp: 8180 case ARM::t2Int_eh_sjlj_setjmp_nofp: 8181 return BB; 8182 8183 case ARM::Int_eh_sjlj_setup_dispatch: 8184 EmitSjLjDispatchBlock(MI, BB); 8185 return BB; 8186 8187 case ARM::ABS: 8188 case ARM::t2ABS: { 8189 // To insert an ABS instruction, we have to insert the 8190 // diamond control-flow pattern. The incoming instruction knows the 8191 // source vreg to test against 0, the destination vreg to set, 8192 // the condition code register to branch on, the 8193 // true/false values to select between, and a branch opcode to use. 8194 // It transforms 8195 // V1 = ABS V0 8196 // into 8197 // V2 = MOVS V0 8198 // BCC (branch to SinkBB if V0 >= 0) 8199 // RSBBB: V3 = RSBri V2, 0 (compute ABS if V2 < 0) 8200 // SinkBB: V1 = PHI(V2, V3) 8201 const BasicBlock *LLVM_BB = BB->getBasicBlock(); 8202 MachineFunction::iterator BBI = ++BB->getIterator(); 8203 MachineFunction *Fn = BB->getParent(); 8204 MachineBasicBlock *RSBBB = Fn->CreateMachineBasicBlock(LLVM_BB); 8205 MachineBasicBlock *SinkBB = Fn->CreateMachineBasicBlock(LLVM_BB); 8206 Fn->insert(BBI, RSBBB); 8207 Fn->insert(BBI, SinkBB); 8208 8209 unsigned int ABSSrcReg = MI->getOperand(1).getReg(); 8210 unsigned int ABSDstReg = MI->getOperand(0).getReg(); 8211 bool ABSSrcKIll = MI->getOperand(1).isKill(); 8212 bool isThumb2 = Subtarget->isThumb2(); 8213 MachineRegisterInfo &MRI = Fn->getRegInfo(); 8214 // In Thumb mode S must not be specified if source register is the SP or 8215 // PC and if destination register is the SP, so restrict register class 8216 unsigned NewRsbDstReg = 8217 MRI.createVirtualRegister(isThumb2 ? &ARM::rGPRRegClass : &ARM::GPRRegClass); 8218 8219 // Transfer the remainder of BB and its successor edges to sinkMBB. 8220 SinkBB->splice(SinkBB->begin(), BB, 8221 std::next(MachineBasicBlock::iterator(MI)), BB->end()); 8222 SinkBB->transferSuccessorsAndUpdatePHIs(BB); 8223 8224 BB->addSuccessor(RSBBB); 8225 BB->addSuccessor(SinkBB); 8226 8227 // fall through to SinkMBB 8228 RSBBB->addSuccessor(SinkBB); 8229 8230 // insert a cmp at the end of BB 8231 AddDefaultPred(BuildMI(BB, dl, 8232 TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri)) 8233 .addReg(ABSSrcReg).addImm(0)); 8234 8235 // insert a bcc with opposite CC to ARMCC::MI at the end of BB 8236 BuildMI(BB, dl, 8237 TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc)).addMBB(SinkBB) 8238 .addImm(ARMCC::getOppositeCondition(ARMCC::MI)).addReg(ARM::CPSR); 8239 8240 // insert rsbri in RSBBB 8241 // Note: BCC and rsbri will be converted into predicated rsbmi 8242 // by if-conversion pass 8243 BuildMI(*RSBBB, RSBBB->begin(), dl, 8244 TII->get(isThumb2 ? ARM::t2RSBri : ARM::RSBri), NewRsbDstReg) 8245 .addReg(ABSSrcReg, ABSSrcKIll ? RegState::Kill : 0) 8246 .addImm(0).addImm((unsigned)ARMCC::AL).addReg(0).addReg(0); 8247 8248 // insert PHI in SinkBB, 8249 // reuse ABSDstReg to not change uses of ABS instruction 8250 BuildMI(*SinkBB, SinkBB->begin(), dl, 8251 TII->get(ARM::PHI), ABSDstReg) 8252 .addReg(NewRsbDstReg).addMBB(RSBBB) 8253 .addReg(ABSSrcReg).addMBB(BB); 8254 8255 // remove ABS instruction 8256 MI->eraseFromParent(); 8257 8258 // return last added BB 8259 return SinkBB; 8260 } 8261 case ARM::COPY_STRUCT_BYVAL_I32: 8262 ++NumLoopByVals; 8263 return EmitStructByval(MI, BB); 8264 case ARM::WIN__CHKSTK: 8265 return EmitLowered__chkstk(MI, BB); 8266 case ARM::WIN__DBZCHK: 8267 return EmitLowered__dbzchk(MI, BB); 8268 } 8269 } 8270 8271 /// \brief Attaches vregs to MEMCPY that it will use as scratch registers 8272 /// when it is expanded into LDM/STM. This is done as a post-isel lowering 8273 /// instead of as a custom inserter because we need the use list from the SDNode. 8274 static void attachMEMCPYScratchRegs(const ARMSubtarget *Subtarget, 8275 MachineInstr *MI, const SDNode *Node) { 8276 bool isThumb1 = Subtarget->isThumb1Only(); 8277 8278 DebugLoc DL = MI->getDebugLoc(); 8279 MachineFunction *MF = MI->getParent()->getParent(); 8280 MachineRegisterInfo &MRI = MF->getRegInfo(); 8281 MachineInstrBuilder MIB(*MF, MI); 8282 8283 // If the new dst/src is unused mark it as dead. 8284 if (!Node->hasAnyUseOfValue(0)) { 8285 MI->getOperand(0).setIsDead(true); 8286 } 8287 if (!Node->hasAnyUseOfValue(1)) { 8288 MI->getOperand(1).setIsDead(true); 8289 } 8290 8291 // The MEMCPY both defines and kills the scratch registers. 8292 for (unsigned I = 0; I != MI->getOperand(4).getImm(); ++I) { 8293 unsigned TmpReg = MRI.createVirtualRegister(isThumb1 ? &ARM::tGPRRegClass 8294 : &ARM::GPRRegClass); 8295 MIB.addReg(TmpReg, RegState::Define|RegState::Dead); 8296 } 8297 } 8298 8299 void ARMTargetLowering::AdjustInstrPostInstrSelection(MachineInstr *MI, 8300 SDNode *Node) const { 8301 if (MI->getOpcode() == ARM::MEMCPY) { 8302 attachMEMCPYScratchRegs(Subtarget, MI, Node); 8303 return; 8304 } 8305 8306 const MCInstrDesc *MCID = &MI->getDesc(); 8307 // Adjust potentially 's' setting instructions after isel, i.e. ADC, SBC, RSB, 8308 // RSC. Coming out of isel, they have an implicit CPSR def, but the optional 8309 // operand is still set to noreg. If needed, set the optional operand's 8310 // register to CPSR, and remove the redundant implicit def. 8311 // 8312 // e.g. ADCS (..., CPSR<imp-def>) -> ADC (... opt:CPSR<def>). 8313 8314 // Rename pseudo opcodes. 8315 unsigned NewOpc = convertAddSubFlagsOpcode(MI->getOpcode()); 8316 if (NewOpc) { 8317 const ARMBaseInstrInfo *TII = Subtarget->getInstrInfo(); 8318 MCID = &TII->get(NewOpc); 8319 8320 assert(MCID->getNumOperands() == MI->getDesc().getNumOperands() + 1 && 8321 "converted opcode should be the same except for cc_out"); 8322 8323 MI->setDesc(*MCID); 8324 8325 // Add the optional cc_out operand 8326 MI->addOperand(MachineOperand::CreateReg(0, /*isDef=*/true)); 8327 } 8328 unsigned ccOutIdx = MCID->getNumOperands() - 1; 8329 8330 // Any ARM instruction that sets the 's' bit should specify an optional 8331 // "cc_out" operand in the last operand position. 8332 if (!MI->hasOptionalDef() || !MCID->OpInfo[ccOutIdx].isOptionalDef()) { 8333 assert(!NewOpc && "Optional cc_out operand required"); 8334 return; 8335 } 8336 // Look for an implicit def of CPSR added by MachineInstr ctor. Remove it 8337 // since we already have an optional CPSR def. 8338 bool definesCPSR = false; 8339 bool deadCPSR = false; 8340 for (unsigned i = MCID->getNumOperands(), e = MI->getNumOperands(); 8341 i != e; ++i) { 8342 const MachineOperand &MO = MI->getOperand(i); 8343 if (MO.isReg() && MO.isDef() && MO.getReg() == ARM::CPSR) { 8344 definesCPSR = true; 8345 if (MO.isDead()) 8346 deadCPSR = true; 8347 MI->RemoveOperand(i); 8348 break; 8349 } 8350 } 8351 if (!definesCPSR) { 8352 assert(!NewOpc && "Optional cc_out operand required"); 8353 return; 8354 } 8355 assert(deadCPSR == !Node->hasAnyUseOfValue(1) && "inconsistent dead flag"); 8356 if (deadCPSR) { 8357 assert(!MI->getOperand(ccOutIdx).getReg() && 8358 "expect uninitialized optional cc_out operand"); 8359 return; 8360 } 8361 8362 // If this instruction was defined with an optional CPSR def and its dag node 8363 // had a live implicit CPSR def, then activate the optional CPSR def. 8364 MachineOperand &MO = MI->getOperand(ccOutIdx); 8365 MO.setReg(ARM::CPSR); 8366 MO.setIsDef(true); 8367 } 8368 8369 //===----------------------------------------------------------------------===// 8370 // ARM Optimization Hooks 8371 //===----------------------------------------------------------------------===// 8372 8373 // Helper function that checks if N is a null or all ones constant. 8374 static inline bool isZeroOrAllOnes(SDValue N, bool AllOnes) { 8375 return AllOnes ? isAllOnesConstant(N) : isNullConstant(N); 8376 } 8377 8378 // Return true if N is conditionally 0 or all ones. 8379 // Detects these expressions where cc is an i1 value: 8380 // 8381 // (select cc 0, y) [AllOnes=0] 8382 // (select cc y, 0) [AllOnes=0] 8383 // (zext cc) [AllOnes=0] 8384 // (sext cc) [AllOnes=0/1] 8385 // (select cc -1, y) [AllOnes=1] 8386 // (select cc y, -1) [AllOnes=1] 8387 // 8388 // Invert is set when N is the null/all ones constant when CC is false. 8389 // OtherOp is set to the alternative value of N. 8390 static bool isConditionalZeroOrAllOnes(SDNode *N, bool AllOnes, 8391 SDValue &CC, bool &Invert, 8392 SDValue &OtherOp, 8393 SelectionDAG &DAG) { 8394 switch (N->getOpcode()) { 8395 default: return false; 8396 case ISD::SELECT: { 8397 CC = N->getOperand(0); 8398 SDValue N1 = N->getOperand(1); 8399 SDValue N2 = N->getOperand(2); 8400 if (isZeroOrAllOnes(N1, AllOnes)) { 8401 Invert = false; 8402 OtherOp = N2; 8403 return true; 8404 } 8405 if (isZeroOrAllOnes(N2, AllOnes)) { 8406 Invert = true; 8407 OtherOp = N1; 8408 return true; 8409 } 8410 return false; 8411 } 8412 case ISD::ZERO_EXTEND: 8413 // (zext cc) can never be the all ones value. 8414 if (AllOnes) 8415 return false; 8416 // Fall through. 8417 case ISD::SIGN_EXTEND: { 8418 SDLoc dl(N); 8419 EVT VT = N->getValueType(0); 8420 CC = N->getOperand(0); 8421 if (CC.getValueType() != MVT::i1) 8422 return false; 8423 Invert = !AllOnes; 8424 if (AllOnes) 8425 // When looking for an AllOnes constant, N is an sext, and the 'other' 8426 // value is 0. 8427 OtherOp = DAG.getConstant(0, dl, VT); 8428 else if (N->getOpcode() == ISD::ZERO_EXTEND) 8429 // When looking for a 0 constant, N can be zext or sext. 8430 OtherOp = DAG.getConstant(1, dl, VT); 8431 else 8432 OtherOp = DAG.getConstant(APInt::getAllOnesValue(VT.getSizeInBits()), dl, 8433 VT); 8434 return true; 8435 } 8436 } 8437 } 8438 8439 // Combine a constant select operand into its use: 8440 // 8441 // (add (select cc, 0, c), x) -> (select cc, x, (add, x, c)) 8442 // (sub x, (select cc, 0, c)) -> (select cc, x, (sub, x, c)) 8443 // (and (select cc, -1, c), x) -> (select cc, x, (and, x, c)) [AllOnes=1] 8444 // (or (select cc, 0, c), x) -> (select cc, x, (or, x, c)) 8445 // (xor (select cc, 0, c), x) -> (select cc, x, (xor, x, c)) 8446 // 8447 // The transform is rejected if the select doesn't have a constant operand that 8448 // is null, or all ones when AllOnes is set. 8449 // 8450 // Also recognize sext/zext from i1: 8451 // 8452 // (add (zext cc), x) -> (select cc (add x, 1), x) 8453 // (add (sext cc), x) -> (select cc (add x, -1), x) 8454 // 8455 // These transformations eventually create predicated instructions. 8456 // 8457 // @param N The node to transform. 8458 // @param Slct The N operand that is a select. 8459 // @param OtherOp The other N operand (x above). 8460 // @param DCI Context. 8461 // @param AllOnes Require the select constant to be all ones instead of null. 8462 // @returns The new node, or SDValue() on failure. 8463 static 8464 SDValue combineSelectAndUse(SDNode *N, SDValue Slct, SDValue OtherOp, 8465 TargetLowering::DAGCombinerInfo &DCI, 8466 bool AllOnes = false) { 8467 SelectionDAG &DAG = DCI.DAG; 8468 EVT VT = N->getValueType(0); 8469 SDValue NonConstantVal; 8470 SDValue CCOp; 8471 bool SwapSelectOps; 8472 if (!isConditionalZeroOrAllOnes(Slct.getNode(), AllOnes, CCOp, SwapSelectOps, 8473 NonConstantVal, DAG)) 8474 return SDValue(); 8475 8476 // Slct is now know to be the desired identity constant when CC is true. 8477 SDValue TrueVal = OtherOp; 8478 SDValue FalseVal = DAG.getNode(N->getOpcode(), SDLoc(N), VT, 8479 OtherOp, NonConstantVal); 8480 // Unless SwapSelectOps says CC should be false. 8481 if (SwapSelectOps) 8482 std::swap(TrueVal, FalseVal); 8483 8484 return DAG.getNode(ISD::SELECT, SDLoc(N), VT, 8485 CCOp, TrueVal, FalseVal); 8486 } 8487 8488 // Attempt combineSelectAndUse on each operand of a commutative operator N. 8489 static 8490 SDValue combineSelectAndUseCommutative(SDNode *N, bool AllOnes, 8491 TargetLowering::DAGCombinerInfo &DCI) { 8492 SDValue N0 = N->getOperand(0); 8493 SDValue N1 = N->getOperand(1); 8494 if (N0.getNode()->hasOneUse()) 8495 if (SDValue Result = combineSelectAndUse(N, N0, N1, DCI, AllOnes)) 8496 return Result; 8497 if (N1.getNode()->hasOneUse()) 8498 if (SDValue Result = combineSelectAndUse(N, N1, N0, DCI, AllOnes)) 8499 return Result; 8500 return SDValue(); 8501 } 8502 8503 // AddCombineToVPADDL- For pair-wise add on neon, use the vpaddl instruction 8504 // (only after legalization). 8505 static SDValue AddCombineToVPADDL(SDNode *N, SDValue N0, SDValue N1, 8506 TargetLowering::DAGCombinerInfo &DCI, 8507 const ARMSubtarget *Subtarget) { 8508 8509 // Only perform optimization if after legalize, and if NEON is available. We 8510 // also expected both operands to be BUILD_VECTORs. 8511 if (DCI.isBeforeLegalize() || !Subtarget->hasNEON() 8512 || N0.getOpcode() != ISD::BUILD_VECTOR 8513 || N1.getOpcode() != ISD::BUILD_VECTOR) 8514 return SDValue(); 8515 8516 // Check output type since VPADDL operand elements can only be 8, 16, or 32. 8517 EVT VT = N->getValueType(0); 8518 if (!VT.isInteger() || VT.getVectorElementType() == MVT::i64) 8519 return SDValue(); 8520 8521 // Check that the vector operands are of the right form. 8522 // N0 and N1 are BUILD_VECTOR nodes with N number of EXTRACT_VECTOR 8523 // operands, where N is the size of the formed vector. 8524 // Each EXTRACT_VECTOR should have the same input vector and odd or even 8525 // index such that we have a pair wise add pattern. 8526 8527 // Grab the vector that all EXTRACT_VECTOR nodes should be referencing. 8528 if (N0->getOperand(0)->getOpcode() != ISD::EXTRACT_VECTOR_ELT) 8529 return SDValue(); 8530 SDValue Vec = N0->getOperand(0)->getOperand(0); 8531 SDNode *V = Vec.getNode(); 8532 unsigned nextIndex = 0; 8533 8534 // For each operands to the ADD which are BUILD_VECTORs, 8535 // check to see if each of their operands are an EXTRACT_VECTOR with 8536 // the same vector and appropriate index. 8537 for (unsigned i = 0, e = N0->getNumOperands(); i != e; ++i) { 8538 if (N0->getOperand(i)->getOpcode() == ISD::EXTRACT_VECTOR_ELT 8539 && N1->getOperand(i)->getOpcode() == ISD::EXTRACT_VECTOR_ELT) { 8540 8541 SDValue ExtVec0 = N0->getOperand(i); 8542 SDValue ExtVec1 = N1->getOperand(i); 8543 8544 // First operand is the vector, verify its the same. 8545 if (V != ExtVec0->getOperand(0).getNode() || 8546 V != ExtVec1->getOperand(0).getNode()) 8547 return SDValue(); 8548 8549 // Second is the constant, verify its correct. 8550 ConstantSDNode *C0 = dyn_cast<ConstantSDNode>(ExtVec0->getOperand(1)); 8551 ConstantSDNode *C1 = dyn_cast<ConstantSDNode>(ExtVec1->getOperand(1)); 8552 8553 // For the constant, we want to see all the even or all the odd. 8554 if (!C0 || !C1 || C0->getZExtValue() != nextIndex 8555 || C1->getZExtValue() != nextIndex+1) 8556 return SDValue(); 8557 8558 // Increment index. 8559 nextIndex+=2; 8560 } else 8561 return SDValue(); 8562 } 8563 8564 // Create VPADDL node. 8565 SelectionDAG &DAG = DCI.DAG; 8566 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 8567 8568 SDLoc dl(N); 8569 8570 // Build operand list. 8571 SmallVector<SDValue, 8> Ops; 8572 Ops.push_back(DAG.getConstant(Intrinsic::arm_neon_vpaddls, dl, 8573 TLI.getPointerTy(DAG.getDataLayout()))); 8574 8575 // Input is the vector. 8576 Ops.push_back(Vec); 8577 8578 // Get widened type and narrowed type. 8579 MVT widenType; 8580 unsigned numElem = VT.getVectorNumElements(); 8581 8582 EVT inputLaneType = Vec.getValueType().getVectorElementType(); 8583 switch (inputLaneType.getSimpleVT().SimpleTy) { 8584 case MVT::i8: widenType = MVT::getVectorVT(MVT::i16, numElem); break; 8585 case MVT::i16: widenType = MVT::getVectorVT(MVT::i32, numElem); break; 8586 case MVT::i32: widenType = MVT::getVectorVT(MVT::i64, numElem); break; 8587 default: 8588 llvm_unreachable("Invalid vector element type for padd optimization."); 8589 } 8590 8591 SDValue tmp = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, widenType, Ops); 8592 unsigned ExtOp = VT.bitsGT(tmp.getValueType()) ? ISD::ANY_EXTEND : ISD::TRUNCATE; 8593 return DAG.getNode(ExtOp, dl, VT, tmp); 8594 } 8595 8596 static SDValue findMUL_LOHI(SDValue V) { 8597 if (V->getOpcode() == ISD::UMUL_LOHI || 8598 V->getOpcode() == ISD::SMUL_LOHI) 8599 return V; 8600 return SDValue(); 8601 } 8602 8603 static SDValue AddCombineTo64bitMLAL(SDNode *AddcNode, 8604 TargetLowering::DAGCombinerInfo &DCI, 8605 const ARMSubtarget *Subtarget) { 8606 8607 if (Subtarget->isThumb1Only()) return SDValue(); 8608 8609 // Only perform the checks after legalize when the pattern is available. 8610 if (DCI.isBeforeLegalize()) return SDValue(); 8611 8612 // Look for multiply add opportunities. 8613 // The pattern is a ISD::UMUL_LOHI followed by two add nodes, where 8614 // each add nodes consumes a value from ISD::UMUL_LOHI and there is 8615 // a glue link from the first add to the second add. 8616 // If we find this pattern, we can replace the U/SMUL_LOHI, ADDC, and ADDE by 8617 // a S/UMLAL instruction. 8618 // UMUL_LOHI 8619 // / :lo \ :hi 8620 // / \ [no multiline comment] 8621 // loAdd -> ADDE | 8622 // \ :glue / 8623 // \ / 8624 // ADDC <- hiAdd 8625 // 8626 assert(AddcNode->getOpcode() == ISD::ADDC && "Expect an ADDC"); 8627 SDValue AddcOp0 = AddcNode->getOperand(0); 8628 SDValue AddcOp1 = AddcNode->getOperand(1); 8629 8630 // Check if the two operands are from the same mul_lohi node. 8631 if (AddcOp0.getNode() == AddcOp1.getNode()) 8632 return SDValue(); 8633 8634 assert(AddcNode->getNumValues() == 2 && 8635 AddcNode->getValueType(0) == MVT::i32 && 8636 "Expect ADDC with two result values. First: i32"); 8637 8638 // Check that we have a glued ADDC node. 8639 if (AddcNode->getValueType(1) != MVT::Glue) 8640 return SDValue(); 8641 8642 // Check that the ADDC adds the low result of the S/UMUL_LOHI. 8643 if (AddcOp0->getOpcode() != ISD::UMUL_LOHI && 8644 AddcOp0->getOpcode() != ISD::SMUL_LOHI && 8645 AddcOp1->getOpcode() != ISD::UMUL_LOHI && 8646 AddcOp1->getOpcode() != ISD::SMUL_LOHI) 8647 return SDValue(); 8648 8649 // Look for the glued ADDE. 8650 SDNode* AddeNode = AddcNode->getGluedUser(); 8651 if (!AddeNode) 8652 return SDValue(); 8653 8654 // Make sure it is really an ADDE. 8655 if (AddeNode->getOpcode() != ISD::ADDE) 8656 return SDValue(); 8657 8658 assert(AddeNode->getNumOperands() == 3 && 8659 AddeNode->getOperand(2).getValueType() == MVT::Glue && 8660 "ADDE node has the wrong inputs"); 8661 8662 // Check for the triangle shape. 8663 SDValue AddeOp0 = AddeNode->getOperand(0); 8664 SDValue AddeOp1 = AddeNode->getOperand(1); 8665 8666 // Make sure that the ADDE operands are not coming from the same node. 8667 if (AddeOp0.getNode() == AddeOp1.getNode()) 8668 return SDValue(); 8669 8670 // Find the MUL_LOHI node walking up ADDE's operands. 8671 bool IsLeftOperandMUL = false; 8672 SDValue MULOp = findMUL_LOHI(AddeOp0); 8673 if (MULOp == SDValue()) 8674 MULOp = findMUL_LOHI(AddeOp1); 8675 else 8676 IsLeftOperandMUL = true; 8677 if (MULOp == SDValue()) 8678 return SDValue(); 8679 8680 // Figure out the right opcode. 8681 unsigned Opc = MULOp->getOpcode(); 8682 unsigned FinalOpc = (Opc == ISD::SMUL_LOHI) ? ARMISD::SMLAL : ARMISD::UMLAL; 8683 8684 // Figure out the high and low input values to the MLAL node. 8685 SDValue* HiAdd = nullptr; 8686 SDValue* LoMul = nullptr; 8687 SDValue* LowAdd = nullptr; 8688 8689 // Ensure that ADDE is from high result of ISD::SMUL_LOHI. 8690 if ((AddeOp0 != MULOp.getValue(1)) && (AddeOp1 != MULOp.getValue(1))) 8691 return SDValue(); 8692 8693 if (IsLeftOperandMUL) 8694 HiAdd = &AddeOp1; 8695 else 8696 HiAdd = &AddeOp0; 8697 8698 8699 // Ensure that LoMul and LowAdd are taken from correct ISD::SMUL_LOHI node 8700 // whose low result is fed to the ADDC we are checking. 8701 8702 if (AddcOp0 == MULOp.getValue(0)) { 8703 LoMul = &AddcOp0; 8704 LowAdd = &AddcOp1; 8705 } 8706 if (AddcOp1 == MULOp.getValue(0)) { 8707 LoMul = &AddcOp1; 8708 LowAdd = &AddcOp0; 8709 } 8710 8711 if (!LoMul) 8712 return SDValue(); 8713 8714 // Create the merged node. 8715 SelectionDAG &DAG = DCI.DAG; 8716 8717 // Build operand list. 8718 SmallVector<SDValue, 8> Ops; 8719 Ops.push_back(LoMul->getOperand(0)); 8720 Ops.push_back(LoMul->getOperand(1)); 8721 Ops.push_back(*LowAdd); 8722 Ops.push_back(*HiAdd); 8723 8724 SDValue MLALNode = DAG.getNode(FinalOpc, SDLoc(AddcNode), 8725 DAG.getVTList(MVT::i32, MVT::i32), Ops); 8726 8727 // Replace the ADDs' nodes uses by the MLA node's values. 8728 SDValue HiMLALResult(MLALNode.getNode(), 1); 8729 DAG.ReplaceAllUsesOfValueWith(SDValue(AddeNode, 0), HiMLALResult); 8730 8731 SDValue LoMLALResult(MLALNode.getNode(), 0); 8732 DAG.ReplaceAllUsesOfValueWith(SDValue(AddcNode, 0), LoMLALResult); 8733 8734 // Return original node to notify the driver to stop replacing. 8735 SDValue resNode(AddcNode, 0); 8736 return resNode; 8737 } 8738 8739 /// PerformADDCCombine - Target-specific dag combine transform from 8740 /// ISD::ADDC, ISD::ADDE, and ISD::MUL_LOHI to MLAL. 8741 static SDValue PerformADDCCombine(SDNode *N, 8742 TargetLowering::DAGCombinerInfo &DCI, 8743 const ARMSubtarget *Subtarget) { 8744 8745 return AddCombineTo64bitMLAL(N, DCI, Subtarget); 8746 8747 } 8748 8749 /// PerformADDCombineWithOperands - Try DAG combinations for an ADD with 8750 /// operands N0 and N1. This is a helper for PerformADDCombine that is 8751 /// called with the default operands, and if that fails, with commuted 8752 /// operands. 8753 static SDValue PerformADDCombineWithOperands(SDNode *N, SDValue N0, SDValue N1, 8754 TargetLowering::DAGCombinerInfo &DCI, 8755 const ARMSubtarget *Subtarget){ 8756 8757 // Attempt to create vpaddl for this add. 8758 if (SDValue Result = AddCombineToVPADDL(N, N0, N1, DCI, Subtarget)) 8759 return Result; 8760 8761 // fold (add (select cc, 0, c), x) -> (select cc, x, (add, x, c)) 8762 if (N0.getNode()->hasOneUse()) 8763 if (SDValue Result = combineSelectAndUse(N, N0, N1, DCI)) 8764 return Result; 8765 return SDValue(); 8766 } 8767 8768 /// PerformADDCombine - Target-specific dag combine xforms for ISD::ADD. 8769 /// 8770 static SDValue PerformADDCombine(SDNode *N, 8771 TargetLowering::DAGCombinerInfo &DCI, 8772 const ARMSubtarget *Subtarget) { 8773 SDValue N0 = N->getOperand(0); 8774 SDValue N1 = N->getOperand(1); 8775 8776 // First try with the default operand order. 8777 if (SDValue Result = PerformADDCombineWithOperands(N, N0, N1, DCI, Subtarget)) 8778 return Result; 8779 8780 // If that didn't work, try again with the operands commuted. 8781 return PerformADDCombineWithOperands(N, N1, N0, DCI, Subtarget); 8782 } 8783 8784 /// PerformSUBCombine - Target-specific dag combine xforms for ISD::SUB. 8785 /// 8786 static SDValue PerformSUBCombine(SDNode *N, 8787 TargetLowering::DAGCombinerInfo &DCI) { 8788 SDValue N0 = N->getOperand(0); 8789 SDValue N1 = N->getOperand(1); 8790 8791 // fold (sub x, (select cc, 0, c)) -> (select cc, x, (sub, x, c)) 8792 if (N1.getNode()->hasOneUse()) 8793 if (SDValue Result = combineSelectAndUse(N, N1, N0, DCI)) 8794 return Result; 8795 8796 return SDValue(); 8797 } 8798 8799 /// PerformVMULCombine 8800 /// Distribute (A + B) * C to (A * C) + (B * C) to take advantage of the 8801 /// special multiplier accumulator forwarding. 8802 /// vmul d3, d0, d2 8803 /// vmla d3, d1, d2 8804 /// is faster than 8805 /// vadd d3, d0, d1 8806 /// vmul d3, d3, d2 8807 // However, for (A + B) * (A + B), 8808 // vadd d2, d0, d1 8809 // vmul d3, d0, d2 8810 // vmla d3, d1, d2 8811 // is slower than 8812 // vadd d2, d0, d1 8813 // vmul d3, d2, d2 8814 static SDValue PerformVMULCombine(SDNode *N, 8815 TargetLowering::DAGCombinerInfo &DCI, 8816 const ARMSubtarget *Subtarget) { 8817 if (!Subtarget->hasVMLxForwarding()) 8818 return SDValue(); 8819 8820 SelectionDAG &DAG = DCI.DAG; 8821 SDValue N0 = N->getOperand(0); 8822 SDValue N1 = N->getOperand(1); 8823 unsigned Opcode = N0.getOpcode(); 8824 if (Opcode != ISD::ADD && Opcode != ISD::SUB && 8825 Opcode != ISD::FADD && Opcode != ISD::FSUB) { 8826 Opcode = N1.getOpcode(); 8827 if (Opcode != ISD::ADD && Opcode != ISD::SUB && 8828 Opcode != ISD::FADD && Opcode != ISD::FSUB) 8829 return SDValue(); 8830 std::swap(N0, N1); 8831 } 8832 8833 if (N0 == N1) 8834 return SDValue(); 8835 8836 EVT VT = N->getValueType(0); 8837 SDLoc DL(N); 8838 SDValue N00 = N0->getOperand(0); 8839 SDValue N01 = N0->getOperand(1); 8840 return DAG.getNode(Opcode, DL, VT, 8841 DAG.getNode(ISD::MUL, DL, VT, N00, N1), 8842 DAG.getNode(ISD::MUL, DL, VT, N01, N1)); 8843 } 8844 8845 static SDValue PerformMULCombine(SDNode *N, 8846 TargetLowering::DAGCombinerInfo &DCI, 8847 const ARMSubtarget *Subtarget) { 8848 SelectionDAG &DAG = DCI.DAG; 8849 8850 if (Subtarget->isThumb1Only()) 8851 return SDValue(); 8852 8853 if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer()) 8854 return SDValue(); 8855 8856 EVT VT = N->getValueType(0); 8857 if (VT.is64BitVector() || VT.is128BitVector()) 8858 return PerformVMULCombine(N, DCI, Subtarget); 8859 if (VT != MVT::i32) 8860 return SDValue(); 8861 8862 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(1)); 8863 if (!C) 8864 return SDValue(); 8865 8866 int64_t MulAmt = C->getSExtValue(); 8867 unsigned ShiftAmt = countTrailingZeros<uint64_t>(MulAmt); 8868 8869 ShiftAmt = ShiftAmt & (32 - 1); 8870 SDValue V = N->getOperand(0); 8871 SDLoc DL(N); 8872 8873 SDValue Res; 8874 MulAmt >>= ShiftAmt; 8875 8876 if (MulAmt >= 0) { 8877 if (isPowerOf2_32(MulAmt - 1)) { 8878 // (mul x, 2^N + 1) => (add (shl x, N), x) 8879 Res = DAG.getNode(ISD::ADD, DL, VT, 8880 V, 8881 DAG.getNode(ISD::SHL, DL, VT, 8882 V, 8883 DAG.getConstant(Log2_32(MulAmt - 1), DL, 8884 MVT::i32))); 8885 } else if (isPowerOf2_32(MulAmt + 1)) { 8886 // (mul x, 2^N - 1) => (sub (shl x, N), x) 8887 Res = DAG.getNode(ISD::SUB, DL, VT, 8888 DAG.getNode(ISD::SHL, DL, VT, 8889 V, 8890 DAG.getConstant(Log2_32(MulAmt + 1), DL, 8891 MVT::i32)), 8892 V); 8893 } else 8894 return SDValue(); 8895 } else { 8896 uint64_t MulAmtAbs = -MulAmt; 8897 if (isPowerOf2_32(MulAmtAbs + 1)) { 8898 // (mul x, -(2^N - 1)) => (sub x, (shl x, N)) 8899 Res = DAG.getNode(ISD::SUB, DL, VT, 8900 V, 8901 DAG.getNode(ISD::SHL, DL, VT, 8902 V, 8903 DAG.getConstant(Log2_32(MulAmtAbs + 1), DL, 8904 MVT::i32))); 8905 } else if (isPowerOf2_32(MulAmtAbs - 1)) { 8906 // (mul x, -(2^N + 1)) => - (add (shl x, N), x) 8907 Res = DAG.getNode(ISD::ADD, DL, VT, 8908 V, 8909 DAG.getNode(ISD::SHL, DL, VT, 8910 V, 8911 DAG.getConstant(Log2_32(MulAmtAbs - 1), DL, 8912 MVT::i32))); 8913 Res = DAG.getNode(ISD::SUB, DL, VT, 8914 DAG.getConstant(0, DL, MVT::i32), Res); 8915 8916 } else 8917 return SDValue(); 8918 } 8919 8920 if (ShiftAmt != 0) 8921 Res = DAG.getNode(ISD::SHL, DL, VT, 8922 Res, DAG.getConstant(ShiftAmt, DL, MVT::i32)); 8923 8924 // Do not add new nodes to DAG combiner worklist. 8925 DCI.CombineTo(N, Res, false); 8926 return SDValue(); 8927 } 8928 8929 static SDValue PerformANDCombine(SDNode *N, 8930 TargetLowering::DAGCombinerInfo &DCI, 8931 const ARMSubtarget *Subtarget) { 8932 8933 // Attempt to use immediate-form VBIC 8934 BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(N->getOperand(1)); 8935 SDLoc dl(N); 8936 EVT VT = N->getValueType(0); 8937 SelectionDAG &DAG = DCI.DAG; 8938 8939 if(!DAG.getTargetLoweringInfo().isTypeLegal(VT)) 8940 return SDValue(); 8941 8942 APInt SplatBits, SplatUndef; 8943 unsigned SplatBitSize; 8944 bool HasAnyUndefs; 8945 if (BVN && 8946 BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs)) { 8947 if (SplatBitSize <= 64) { 8948 EVT VbicVT; 8949 SDValue Val = isNEONModifiedImm((~SplatBits).getZExtValue(), 8950 SplatUndef.getZExtValue(), SplatBitSize, 8951 DAG, dl, VbicVT, VT.is128BitVector(), 8952 OtherModImm); 8953 if (Val.getNode()) { 8954 SDValue Input = 8955 DAG.getNode(ISD::BITCAST, dl, VbicVT, N->getOperand(0)); 8956 SDValue Vbic = DAG.getNode(ARMISD::VBICIMM, dl, VbicVT, Input, Val); 8957 return DAG.getNode(ISD::BITCAST, dl, VT, Vbic); 8958 } 8959 } 8960 } 8961 8962 if (!Subtarget->isThumb1Only()) { 8963 // fold (and (select cc, -1, c), x) -> (select cc, x, (and, x, c)) 8964 if (SDValue Result = combineSelectAndUseCommutative(N, true, DCI)) 8965 return Result; 8966 } 8967 8968 return SDValue(); 8969 } 8970 8971 /// PerformORCombine - Target-specific dag combine xforms for ISD::OR 8972 static SDValue PerformORCombine(SDNode *N, 8973 TargetLowering::DAGCombinerInfo &DCI, 8974 const ARMSubtarget *Subtarget) { 8975 // Attempt to use immediate-form VORR 8976 BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(N->getOperand(1)); 8977 SDLoc dl(N); 8978 EVT VT = N->getValueType(0); 8979 SelectionDAG &DAG = DCI.DAG; 8980 8981 if(!DAG.getTargetLoweringInfo().isTypeLegal(VT)) 8982 return SDValue(); 8983 8984 APInt SplatBits, SplatUndef; 8985 unsigned SplatBitSize; 8986 bool HasAnyUndefs; 8987 if (BVN && Subtarget->hasNEON() && 8988 BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs)) { 8989 if (SplatBitSize <= 64) { 8990 EVT VorrVT; 8991 SDValue Val = isNEONModifiedImm(SplatBits.getZExtValue(), 8992 SplatUndef.getZExtValue(), SplatBitSize, 8993 DAG, dl, VorrVT, VT.is128BitVector(), 8994 OtherModImm); 8995 if (Val.getNode()) { 8996 SDValue Input = 8997 DAG.getNode(ISD::BITCAST, dl, VorrVT, N->getOperand(0)); 8998 SDValue Vorr = DAG.getNode(ARMISD::VORRIMM, dl, VorrVT, Input, Val); 8999 return DAG.getNode(ISD::BITCAST, dl, VT, Vorr); 9000 } 9001 } 9002 } 9003 9004 if (!Subtarget->isThumb1Only()) { 9005 // fold (or (select cc, 0, c), x) -> (select cc, x, (or, x, c)) 9006 if (SDValue Result = combineSelectAndUseCommutative(N, false, DCI)) 9007 return Result; 9008 } 9009 9010 // The code below optimizes (or (and X, Y), Z). 9011 // The AND operand needs to have a single user to make these optimizations 9012 // profitable. 9013 SDValue N0 = N->getOperand(0); 9014 if (N0.getOpcode() != ISD::AND || !N0.hasOneUse()) 9015 return SDValue(); 9016 SDValue N1 = N->getOperand(1); 9017 9018 // (or (and B, A), (and C, ~A)) => (VBSL A, B, C) when A is a constant. 9019 if (Subtarget->hasNEON() && N1.getOpcode() == ISD::AND && VT.isVector() && 9020 DAG.getTargetLoweringInfo().isTypeLegal(VT)) { 9021 APInt SplatUndef; 9022 unsigned SplatBitSize; 9023 bool HasAnyUndefs; 9024 9025 APInt SplatBits0, SplatBits1; 9026 BuildVectorSDNode *BVN0 = dyn_cast<BuildVectorSDNode>(N0->getOperand(1)); 9027 BuildVectorSDNode *BVN1 = dyn_cast<BuildVectorSDNode>(N1->getOperand(1)); 9028 // Ensure that the second operand of both ands are constants 9029 if (BVN0 && BVN0->isConstantSplat(SplatBits0, SplatUndef, SplatBitSize, 9030 HasAnyUndefs) && !HasAnyUndefs) { 9031 if (BVN1 && BVN1->isConstantSplat(SplatBits1, SplatUndef, SplatBitSize, 9032 HasAnyUndefs) && !HasAnyUndefs) { 9033 // Ensure that the bit width of the constants are the same and that 9034 // the splat arguments are logical inverses as per the pattern we 9035 // are trying to simplify. 9036 if (SplatBits0.getBitWidth() == SplatBits1.getBitWidth() && 9037 SplatBits0 == ~SplatBits1) { 9038 // Canonicalize the vector type to make instruction selection 9039 // simpler. 9040 EVT CanonicalVT = VT.is128BitVector() ? MVT::v4i32 : MVT::v2i32; 9041 SDValue Result = DAG.getNode(ARMISD::VBSL, dl, CanonicalVT, 9042 N0->getOperand(1), 9043 N0->getOperand(0), 9044 N1->getOperand(0)); 9045 return DAG.getNode(ISD::BITCAST, dl, VT, Result); 9046 } 9047 } 9048 } 9049 } 9050 9051 // Try to use the ARM/Thumb2 BFI (bitfield insert) instruction when 9052 // reasonable. 9053 9054 // BFI is only available on V6T2+ 9055 if (Subtarget->isThumb1Only() || !Subtarget->hasV6T2Ops()) 9056 return SDValue(); 9057 9058 SDLoc DL(N); 9059 // 1) or (and A, mask), val => ARMbfi A, val, mask 9060 // iff (val & mask) == val 9061 // 9062 // 2) or (and A, mask), (and B, mask2) => ARMbfi A, (lsr B, amt), mask 9063 // 2a) iff isBitFieldInvertedMask(mask) && isBitFieldInvertedMask(~mask2) 9064 // && mask == ~mask2 9065 // 2b) iff isBitFieldInvertedMask(~mask) && isBitFieldInvertedMask(mask2) 9066 // && ~mask == mask2 9067 // (i.e., copy a bitfield value into another bitfield of the same width) 9068 9069 if (VT != MVT::i32) 9070 return SDValue(); 9071 9072 SDValue N00 = N0.getOperand(0); 9073 9074 // The value and the mask need to be constants so we can verify this is 9075 // actually a bitfield set. If the mask is 0xffff, we can do better 9076 // via a movt instruction, so don't use BFI in that case. 9077 SDValue MaskOp = N0.getOperand(1); 9078 ConstantSDNode *MaskC = dyn_cast<ConstantSDNode>(MaskOp); 9079 if (!MaskC) 9080 return SDValue(); 9081 unsigned Mask = MaskC->getZExtValue(); 9082 if (Mask == 0xffff) 9083 return SDValue(); 9084 SDValue Res; 9085 // Case (1): or (and A, mask), val => ARMbfi A, val, mask 9086 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1); 9087 if (N1C) { 9088 unsigned Val = N1C->getZExtValue(); 9089 if ((Val & ~Mask) != Val) 9090 return SDValue(); 9091 9092 if (ARM::isBitFieldInvertedMask(Mask)) { 9093 Val >>= countTrailingZeros(~Mask); 9094 9095 Res = DAG.getNode(ARMISD::BFI, DL, VT, N00, 9096 DAG.getConstant(Val, DL, MVT::i32), 9097 DAG.getConstant(Mask, DL, MVT::i32)); 9098 9099 // Do not add new nodes to DAG combiner worklist. 9100 DCI.CombineTo(N, Res, false); 9101 return SDValue(); 9102 } 9103 } else if (N1.getOpcode() == ISD::AND) { 9104 // case (2) or (and A, mask), (and B, mask2) => ARMbfi A, (lsr B, amt), mask 9105 ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1)); 9106 if (!N11C) 9107 return SDValue(); 9108 unsigned Mask2 = N11C->getZExtValue(); 9109 9110 // Mask and ~Mask2 (or reverse) must be equivalent for the BFI pattern 9111 // as is to match. 9112 if (ARM::isBitFieldInvertedMask(Mask) && 9113 (Mask == ~Mask2)) { 9114 // The pack halfword instruction works better for masks that fit it, 9115 // so use that when it's available. 9116 if (Subtarget->hasT2ExtractPack() && 9117 (Mask == 0xffff || Mask == 0xffff0000)) 9118 return SDValue(); 9119 // 2a 9120 unsigned amt = countTrailingZeros(Mask2); 9121 Res = DAG.getNode(ISD::SRL, DL, VT, N1.getOperand(0), 9122 DAG.getConstant(amt, DL, MVT::i32)); 9123 Res = DAG.getNode(ARMISD::BFI, DL, VT, N00, Res, 9124 DAG.getConstant(Mask, DL, MVT::i32)); 9125 // Do not add new nodes to DAG combiner worklist. 9126 DCI.CombineTo(N, Res, false); 9127 return SDValue(); 9128 } else if (ARM::isBitFieldInvertedMask(~Mask) && 9129 (~Mask == Mask2)) { 9130 // The pack halfword instruction works better for masks that fit it, 9131 // so use that when it's available. 9132 if (Subtarget->hasT2ExtractPack() && 9133 (Mask2 == 0xffff || Mask2 == 0xffff0000)) 9134 return SDValue(); 9135 // 2b 9136 unsigned lsb = countTrailingZeros(Mask); 9137 Res = DAG.getNode(ISD::SRL, DL, VT, N00, 9138 DAG.getConstant(lsb, DL, MVT::i32)); 9139 Res = DAG.getNode(ARMISD::BFI, DL, VT, N1.getOperand(0), Res, 9140 DAG.getConstant(Mask2, DL, MVT::i32)); 9141 // Do not add new nodes to DAG combiner worklist. 9142 DCI.CombineTo(N, Res, false); 9143 return SDValue(); 9144 } 9145 } 9146 9147 if (DAG.MaskedValueIsZero(N1, MaskC->getAPIntValue()) && 9148 N00.getOpcode() == ISD::SHL && isa<ConstantSDNode>(N00.getOperand(1)) && 9149 ARM::isBitFieldInvertedMask(~Mask)) { 9150 // Case (3): or (and (shl A, #shamt), mask), B => ARMbfi B, A, ~mask 9151 // where lsb(mask) == #shamt and masked bits of B are known zero. 9152 SDValue ShAmt = N00.getOperand(1); 9153 unsigned ShAmtC = cast<ConstantSDNode>(ShAmt)->getZExtValue(); 9154 unsigned LSB = countTrailingZeros(Mask); 9155 if (ShAmtC != LSB) 9156 return SDValue(); 9157 9158 Res = DAG.getNode(ARMISD::BFI, DL, VT, N1, N00.getOperand(0), 9159 DAG.getConstant(~Mask, DL, MVT::i32)); 9160 9161 // Do not add new nodes to DAG combiner worklist. 9162 DCI.CombineTo(N, Res, false); 9163 } 9164 9165 return SDValue(); 9166 } 9167 9168 static SDValue PerformXORCombine(SDNode *N, 9169 TargetLowering::DAGCombinerInfo &DCI, 9170 const ARMSubtarget *Subtarget) { 9171 EVT VT = N->getValueType(0); 9172 SelectionDAG &DAG = DCI.DAG; 9173 9174 if(!DAG.getTargetLoweringInfo().isTypeLegal(VT)) 9175 return SDValue(); 9176 9177 if (!Subtarget->isThumb1Only()) { 9178 // fold (xor (select cc, 0, c), x) -> (select cc, x, (xor, x, c)) 9179 if (SDValue Result = combineSelectAndUseCommutative(N, false, DCI)) 9180 return Result; 9181 } 9182 9183 return SDValue(); 9184 } 9185 9186 // ParseBFI - given a BFI instruction in N, extract the "from" value (Rn) and return it, 9187 // and fill in FromMask and ToMask with (consecutive) bits in "from" to be extracted and 9188 // their position in "to" (Rd). 9189 static SDValue ParseBFI(SDNode *N, APInt &ToMask, APInt &FromMask) { 9190 assert(N->getOpcode() == ARMISD::BFI); 9191 9192 SDValue From = N->getOperand(1); 9193 ToMask = ~cast<ConstantSDNode>(N->getOperand(2))->getAPIntValue(); 9194 FromMask = APInt::getLowBitsSet(ToMask.getBitWidth(), ToMask.countPopulation()); 9195 9196 // If the Base came from a SHR #C, we can deduce that it is really testing bit 9197 // #C in the base of the SHR. 9198 if (From->getOpcode() == ISD::SRL && 9199 isa<ConstantSDNode>(From->getOperand(1))) { 9200 APInt Shift = cast<ConstantSDNode>(From->getOperand(1))->getAPIntValue(); 9201 assert(Shift.getLimitedValue() < 32 && "Shift too large!"); 9202 FromMask <<= Shift.getLimitedValue(31); 9203 From = From->getOperand(0); 9204 } 9205 9206 return From; 9207 } 9208 9209 // If A and B contain one contiguous set of bits, does A | B == A . B? 9210 // 9211 // Neither A nor B must be zero. 9212 static bool BitsProperlyConcatenate(const APInt &A, const APInt &B) { 9213 unsigned LastActiveBitInA = A.countTrailingZeros(); 9214 unsigned FirstActiveBitInB = B.getBitWidth() - B.countLeadingZeros() - 1; 9215 return LastActiveBitInA - 1 == FirstActiveBitInB; 9216 } 9217 9218 static SDValue FindBFIToCombineWith(SDNode *N) { 9219 // We have a BFI in N. Follow a possible chain of BFIs and find a BFI it can combine with, 9220 // if one exists. 9221 APInt ToMask, FromMask; 9222 SDValue From = ParseBFI(N, ToMask, FromMask); 9223 SDValue To = N->getOperand(0); 9224 9225 // Now check for a compatible BFI to merge with. We can pass through BFIs that 9226 // aren't compatible, but not if they set the same bit in their destination as 9227 // we do (or that of any BFI we're going to combine with). 9228 SDValue V = To; 9229 APInt CombinedToMask = ToMask; 9230 while (V.getOpcode() == ARMISD::BFI) { 9231 APInt NewToMask, NewFromMask; 9232 SDValue NewFrom = ParseBFI(V.getNode(), NewToMask, NewFromMask); 9233 if (NewFrom != From) { 9234 // This BFI has a different base. Keep going. 9235 CombinedToMask |= NewToMask; 9236 V = V.getOperand(0); 9237 continue; 9238 } 9239 9240 // Do the written bits conflict with any we've seen so far? 9241 if ((NewToMask & CombinedToMask).getBoolValue()) 9242 // Conflicting bits - bail out because going further is unsafe. 9243 return SDValue(); 9244 9245 // Are the new bits contiguous when combined with the old bits? 9246 if (BitsProperlyConcatenate(ToMask, NewToMask) && 9247 BitsProperlyConcatenate(FromMask, NewFromMask)) 9248 return V; 9249 if (BitsProperlyConcatenate(NewToMask, ToMask) && 9250 BitsProperlyConcatenate(NewFromMask, FromMask)) 9251 return V; 9252 9253 // We've seen a write to some bits, so track it. 9254 CombinedToMask |= NewToMask; 9255 // Keep going... 9256 V = V.getOperand(0); 9257 } 9258 9259 return SDValue(); 9260 } 9261 9262 static SDValue PerformBFICombine(SDNode *N, 9263 TargetLowering::DAGCombinerInfo &DCI) { 9264 SDValue N1 = N->getOperand(1); 9265 if (N1.getOpcode() == ISD::AND) { 9266 // (bfi A, (and B, Mask1), Mask2) -> (bfi A, B, Mask2) iff 9267 // the bits being cleared by the AND are not demanded by the BFI. 9268 ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1)); 9269 if (!N11C) 9270 return SDValue(); 9271 unsigned InvMask = cast<ConstantSDNode>(N->getOperand(2))->getZExtValue(); 9272 unsigned LSB = countTrailingZeros(~InvMask); 9273 unsigned Width = (32 - countLeadingZeros(~InvMask)) - LSB; 9274 assert(Width < 9275 static_cast<unsigned>(std::numeric_limits<unsigned>::digits) && 9276 "undefined behavior"); 9277 unsigned Mask = (1u << Width) - 1; 9278 unsigned Mask2 = N11C->getZExtValue(); 9279 if ((Mask & (~Mask2)) == 0) 9280 return DCI.DAG.getNode(ARMISD::BFI, SDLoc(N), N->getValueType(0), 9281 N->getOperand(0), N1.getOperand(0), 9282 N->getOperand(2)); 9283 } else if (N->getOperand(0).getOpcode() == ARMISD::BFI) { 9284 // We have a BFI of a BFI. Walk up the BFI chain to see how long it goes. 9285 // Keep track of any consecutive bits set that all come from the same base 9286 // value. We can combine these together into a single BFI. 9287 SDValue CombineBFI = FindBFIToCombineWith(N); 9288 if (CombineBFI == SDValue()) 9289 return SDValue(); 9290 9291 // We've found a BFI. 9292 APInt ToMask1, FromMask1; 9293 SDValue From1 = ParseBFI(N, ToMask1, FromMask1); 9294 9295 APInt ToMask2, FromMask2; 9296 SDValue From2 = ParseBFI(CombineBFI.getNode(), ToMask2, FromMask2); 9297 assert(From1 == From2); 9298 (void)From2; 9299 9300 // First, unlink CombineBFI. 9301 DCI.DAG.ReplaceAllUsesWith(CombineBFI, CombineBFI.getOperand(0)); 9302 // Then create a new BFI, combining the two together. 9303 APInt NewFromMask = FromMask1 | FromMask2; 9304 APInt NewToMask = ToMask1 | ToMask2; 9305 9306 EVT VT = N->getValueType(0); 9307 SDLoc dl(N); 9308 9309 if (NewFromMask[0] == 0) 9310 From1 = DCI.DAG.getNode( 9311 ISD::SRL, dl, VT, From1, 9312 DCI.DAG.getConstant(NewFromMask.countTrailingZeros(), dl, VT)); 9313 return DCI.DAG.getNode(ARMISD::BFI, dl, VT, N->getOperand(0), From1, 9314 DCI.DAG.getConstant(~NewToMask, dl, VT)); 9315 } 9316 return SDValue(); 9317 } 9318 9319 /// PerformVMOVRRDCombine - Target-specific dag combine xforms for 9320 /// ARMISD::VMOVRRD. 9321 static SDValue PerformVMOVRRDCombine(SDNode *N, 9322 TargetLowering::DAGCombinerInfo &DCI, 9323 const ARMSubtarget *Subtarget) { 9324 // vmovrrd(vmovdrr x, y) -> x,y 9325 SDValue InDouble = N->getOperand(0); 9326 if (InDouble.getOpcode() == ARMISD::VMOVDRR && !Subtarget->isFPOnlySP()) 9327 return DCI.CombineTo(N, InDouble.getOperand(0), InDouble.getOperand(1)); 9328 9329 // vmovrrd(load f64) -> (load i32), (load i32) 9330 SDNode *InNode = InDouble.getNode(); 9331 if (ISD::isNormalLoad(InNode) && InNode->hasOneUse() && 9332 InNode->getValueType(0) == MVT::f64 && 9333 InNode->getOperand(1).getOpcode() == ISD::FrameIndex && 9334 !cast<LoadSDNode>(InNode)->isVolatile()) { 9335 // TODO: Should this be done for non-FrameIndex operands? 9336 LoadSDNode *LD = cast<LoadSDNode>(InNode); 9337 9338 SelectionDAG &DAG = DCI.DAG; 9339 SDLoc DL(LD); 9340 SDValue BasePtr = LD->getBasePtr(); 9341 SDValue NewLD1 = DAG.getLoad(MVT::i32, DL, LD->getChain(), BasePtr, 9342 LD->getPointerInfo(), LD->isVolatile(), 9343 LD->isNonTemporal(), LD->isInvariant(), 9344 LD->getAlignment()); 9345 9346 SDValue OffsetPtr = DAG.getNode(ISD::ADD, DL, MVT::i32, BasePtr, 9347 DAG.getConstant(4, DL, MVT::i32)); 9348 SDValue NewLD2 = DAG.getLoad(MVT::i32, DL, NewLD1.getValue(1), OffsetPtr, 9349 LD->getPointerInfo(), LD->isVolatile(), 9350 LD->isNonTemporal(), LD->isInvariant(), 9351 std::min(4U, LD->getAlignment() / 2)); 9352 9353 DAG.ReplaceAllUsesOfValueWith(SDValue(LD, 1), NewLD2.getValue(1)); 9354 if (DCI.DAG.getDataLayout().isBigEndian()) 9355 std::swap (NewLD1, NewLD2); 9356 SDValue Result = DCI.CombineTo(N, NewLD1, NewLD2); 9357 return Result; 9358 } 9359 9360 return SDValue(); 9361 } 9362 9363 /// PerformVMOVDRRCombine - Target-specific dag combine xforms for 9364 /// ARMISD::VMOVDRR. This is also used for BUILD_VECTORs with 2 operands. 9365 static SDValue PerformVMOVDRRCombine(SDNode *N, SelectionDAG &DAG) { 9366 // N=vmovrrd(X); vmovdrr(N:0, N:1) -> bit_convert(X) 9367 SDValue Op0 = N->getOperand(0); 9368 SDValue Op1 = N->getOperand(1); 9369 if (Op0.getOpcode() == ISD::BITCAST) 9370 Op0 = Op0.getOperand(0); 9371 if (Op1.getOpcode() == ISD::BITCAST) 9372 Op1 = Op1.getOperand(0); 9373 if (Op0.getOpcode() == ARMISD::VMOVRRD && 9374 Op0.getNode() == Op1.getNode() && 9375 Op0.getResNo() == 0 && Op1.getResNo() == 1) 9376 return DAG.getNode(ISD::BITCAST, SDLoc(N), 9377 N->getValueType(0), Op0.getOperand(0)); 9378 return SDValue(); 9379 } 9380 9381 /// hasNormalLoadOperand - Check if any of the operands of a BUILD_VECTOR node 9382 /// are normal, non-volatile loads. If so, it is profitable to bitcast an 9383 /// i64 vector to have f64 elements, since the value can then be loaded 9384 /// directly into a VFP register. 9385 static bool hasNormalLoadOperand(SDNode *N) { 9386 unsigned NumElts = N->getValueType(0).getVectorNumElements(); 9387 for (unsigned i = 0; i < NumElts; ++i) { 9388 SDNode *Elt = N->getOperand(i).getNode(); 9389 if (ISD::isNormalLoad(Elt) && !cast<LoadSDNode>(Elt)->isVolatile()) 9390 return true; 9391 } 9392 return false; 9393 } 9394 9395 /// PerformBUILD_VECTORCombine - Target-specific dag combine xforms for 9396 /// ISD::BUILD_VECTOR. 9397 static SDValue PerformBUILD_VECTORCombine(SDNode *N, 9398 TargetLowering::DAGCombinerInfo &DCI, 9399 const ARMSubtarget *Subtarget) { 9400 // build_vector(N=ARMISD::VMOVRRD(X), N:1) -> bit_convert(X): 9401 // VMOVRRD is introduced when legalizing i64 types. It forces the i64 value 9402 // into a pair of GPRs, which is fine when the value is used as a scalar, 9403 // but if the i64 value is converted to a vector, we need to undo the VMOVRRD. 9404 SelectionDAG &DAG = DCI.DAG; 9405 if (N->getNumOperands() == 2) 9406 if (SDValue RV = PerformVMOVDRRCombine(N, DAG)) 9407 return RV; 9408 9409 // Load i64 elements as f64 values so that type legalization does not split 9410 // them up into i32 values. 9411 EVT VT = N->getValueType(0); 9412 if (VT.getVectorElementType() != MVT::i64 || !hasNormalLoadOperand(N)) 9413 return SDValue(); 9414 SDLoc dl(N); 9415 SmallVector<SDValue, 8> Ops; 9416 unsigned NumElts = VT.getVectorNumElements(); 9417 for (unsigned i = 0; i < NumElts; ++i) { 9418 SDValue V = DAG.getNode(ISD::BITCAST, dl, MVT::f64, N->getOperand(i)); 9419 Ops.push_back(V); 9420 // Make the DAGCombiner fold the bitcast. 9421 DCI.AddToWorklist(V.getNode()); 9422 } 9423 EVT FloatVT = EVT::getVectorVT(*DAG.getContext(), MVT::f64, NumElts); 9424 SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, FloatVT, Ops); 9425 return DAG.getNode(ISD::BITCAST, dl, VT, BV); 9426 } 9427 9428 /// \brief Target-specific dag combine xforms for ARMISD::BUILD_VECTOR. 9429 static SDValue 9430 PerformARMBUILD_VECTORCombine(SDNode *N, TargetLowering::DAGCombinerInfo &DCI) { 9431 // ARMISD::BUILD_VECTOR is introduced when legalizing ISD::BUILD_VECTOR. 9432 // At that time, we may have inserted bitcasts from integer to float. 9433 // If these bitcasts have survived DAGCombine, change the lowering of this 9434 // BUILD_VECTOR in something more vector friendly, i.e., that does not 9435 // force to use floating point types. 9436 9437 // Make sure we can change the type of the vector. 9438 // This is possible iff: 9439 // 1. The vector is only used in a bitcast to a integer type. I.e., 9440 // 1.1. Vector is used only once. 9441 // 1.2. Use is a bit convert to an integer type. 9442 // 2. The size of its operands are 32-bits (64-bits are not legal). 9443 EVT VT = N->getValueType(0); 9444 EVT EltVT = VT.getVectorElementType(); 9445 9446 // Check 1.1. and 2. 9447 if (EltVT.getSizeInBits() != 32 || !N->hasOneUse()) 9448 return SDValue(); 9449 9450 // By construction, the input type must be float. 9451 assert(EltVT == MVT::f32 && "Unexpected type!"); 9452 9453 // Check 1.2. 9454 SDNode *Use = *N->use_begin(); 9455 if (Use->getOpcode() != ISD::BITCAST || 9456 Use->getValueType(0).isFloatingPoint()) 9457 return SDValue(); 9458 9459 // Check profitability. 9460 // Model is, if more than half of the relevant operands are bitcast from 9461 // i32, turn the build_vector into a sequence of insert_vector_elt. 9462 // Relevant operands are everything that is not statically 9463 // (i.e., at compile time) bitcasted. 9464 unsigned NumOfBitCastedElts = 0; 9465 unsigned NumElts = VT.getVectorNumElements(); 9466 unsigned NumOfRelevantElts = NumElts; 9467 for (unsigned Idx = 0; Idx < NumElts; ++Idx) { 9468 SDValue Elt = N->getOperand(Idx); 9469 if (Elt->getOpcode() == ISD::BITCAST) { 9470 // Assume only bit cast to i32 will go away. 9471 if (Elt->getOperand(0).getValueType() == MVT::i32) 9472 ++NumOfBitCastedElts; 9473 } else if (Elt.getOpcode() == ISD::UNDEF || isa<ConstantSDNode>(Elt)) 9474 // Constants are statically casted, thus do not count them as 9475 // relevant operands. 9476 --NumOfRelevantElts; 9477 } 9478 9479 // Check if more than half of the elements require a non-free bitcast. 9480 if (NumOfBitCastedElts <= NumOfRelevantElts / 2) 9481 return SDValue(); 9482 9483 SelectionDAG &DAG = DCI.DAG; 9484 // Create the new vector type. 9485 EVT VecVT = EVT::getVectorVT(*DAG.getContext(), MVT::i32, NumElts); 9486 // Check if the type is legal. 9487 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 9488 if (!TLI.isTypeLegal(VecVT)) 9489 return SDValue(); 9490 9491 // Combine: 9492 // ARMISD::BUILD_VECTOR E1, E2, ..., EN. 9493 // => BITCAST INSERT_VECTOR_ELT 9494 // (INSERT_VECTOR_ELT (...), (BITCAST EN-1), N-1), 9495 // (BITCAST EN), N. 9496 SDValue Vec = DAG.getUNDEF(VecVT); 9497 SDLoc dl(N); 9498 for (unsigned Idx = 0 ; Idx < NumElts; ++Idx) { 9499 SDValue V = N->getOperand(Idx); 9500 if (V.getOpcode() == ISD::UNDEF) 9501 continue; 9502 if (V.getOpcode() == ISD::BITCAST && 9503 V->getOperand(0).getValueType() == MVT::i32) 9504 // Fold obvious case. 9505 V = V.getOperand(0); 9506 else { 9507 V = DAG.getNode(ISD::BITCAST, SDLoc(V), MVT::i32, V); 9508 // Make the DAGCombiner fold the bitcasts. 9509 DCI.AddToWorklist(V.getNode()); 9510 } 9511 SDValue LaneIdx = DAG.getConstant(Idx, dl, MVT::i32); 9512 Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VecVT, Vec, V, LaneIdx); 9513 } 9514 Vec = DAG.getNode(ISD::BITCAST, dl, VT, Vec); 9515 // Make the DAGCombiner fold the bitcasts. 9516 DCI.AddToWorklist(Vec.getNode()); 9517 return Vec; 9518 } 9519 9520 /// PerformInsertEltCombine - Target-specific dag combine xforms for 9521 /// ISD::INSERT_VECTOR_ELT. 9522 static SDValue PerformInsertEltCombine(SDNode *N, 9523 TargetLowering::DAGCombinerInfo &DCI) { 9524 // Bitcast an i64 load inserted into a vector to f64. 9525 // Otherwise, the i64 value will be legalized to a pair of i32 values. 9526 EVT VT = N->getValueType(0); 9527 SDNode *Elt = N->getOperand(1).getNode(); 9528 if (VT.getVectorElementType() != MVT::i64 || 9529 !ISD::isNormalLoad(Elt) || cast<LoadSDNode>(Elt)->isVolatile()) 9530 return SDValue(); 9531 9532 SelectionDAG &DAG = DCI.DAG; 9533 SDLoc dl(N); 9534 EVT FloatVT = EVT::getVectorVT(*DAG.getContext(), MVT::f64, 9535 VT.getVectorNumElements()); 9536 SDValue Vec = DAG.getNode(ISD::BITCAST, dl, FloatVT, N->getOperand(0)); 9537 SDValue V = DAG.getNode(ISD::BITCAST, dl, MVT::f64, N->getOperand(1)); 9538 // Make the DAGCombiner fold the bitcasts. 9539 DCI.AddToWorklist(Vec.getNode()); 9540 DCI.AddToWorklist(V.getNode()); 9541 SDValue InsElt = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, FloatVT, 9542 Vec, V, N->getOperand(2)); 9543 return DAG.getNode(ISD::BITCAST, dl, VT, InsElt); 9544 } 9545 9546 /// PerformVECTOR_SHUFFLECombine - Target-specific dag combine xforms for 9547 /// ISD::VECTOR_SHUFFLE. 9548 static SDValue PerformVECTOR_SHUFFLECombine(SDNode *N, SelectionDAG &DAG) { 9549 // The LLVM shufflevector instruction does not require the shuffle mask 9550 // length to match the operand vector length, but ISD::VECTOR_SHUFFLE does 9551 // have that requirement. When translating to ISD::VECTOR_SHUFFLE, if the 9552 // operands do not match the mask length, they are extended by concatenating 9553 // them with undef vectors. That is probably the right thing for other 9554 // targets, but for NEON it is better to concatenate two double-register 9555 // size vector operands into a single quad-register size vector. Do that 9556 // transformation here: 9557 // shuffle(concat(v1, undef), concat(v2, undef)) -> 9558 // shuffle(concat(v1, v2), undef) 9559 SDValue Op0 = N->getOperand(0); 9560 SDValue Op1 = N->getOperand(1); 9561 if (Op0.getOpcode() != ISD::CONCAT_VECTORS || 9562 Op1.getOpcode() != ISD::CONCAT_VECTORS || 9563 Op0.getNumOperands() != 2 || 9564 Op1.getNumOperands() != 2) 9565 return SDValue(); 9566 SDValue Concat0Op1 = Op0.getOperand(1); 9567 SDValue Concat1Op1 = Op1.getOperand(1); 9568 if (Concat0Op1.getOpcode() != ISD::UNDEF || 9569 Concat1Op1.getOpcode() != ISD::UNDEF) 9570 return SDValue(); 9571 // Skip the transformation if any of the types are illegal. 9572 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 9573 EVT VT = N->getValueType(0); 9574 if (!TLI.isTypeLegal(VT) || 9575 !TLI.isTypeLegal(Concat0Op1.getValueType()) || 9576 !TLI.isTypeLegal(Concat1Op1.getValueType())) 9577 return SDValue(); 9578 9579 SDValue NewConcat = DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT, 9580 Op0.getOperand(0), Op1.getOperand(0)); 9581 // Translate the shuffle mask. 9582 SmallVector<int, 16> NewMask; 9583 unsigned NumElts = VT.getVectorNumElements(); 9584 unsigned HalfElts = NumElts/2; 9585 ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N); 9586 for (unsigned n = 0; n < NumElts; ++n) { 9587 int MaskElt = SVN->getMaskElt(n); 9588 int NewElt = -1; 9589 if (MaskElt < (int)HalfElts) 9590 NewElt = MaskElt; 9591 else if (MaskElt >= (int)NumElts && MaskElt < (int)(NumElts + HalfElts)) 9592 NewElt = HalfElts + MaskElt - NumElts; 9593 NewMask.push_back(NewElt); 9594 } 9595 return DAG.getVectorShuffle(VT, SDLoc(N), NewConcat, 9596 DAG.getUNDEF(VT), NewMask.data()); 9597 } 9598 9599 /// CombineBaseUpdate - Target-specific DAG combine function for VLDDUP, 9600 /// NEON load/store intrinsics, and generic vector load/stores, to merge 9601 /// base address updates. 9602 /// For generic load/stores, the memory type is assumed to be a vector. 9603 /// The caller is assumed to have checked legality. 9604 static SDValue CombineBaseUpdate(SDNode *N, 9605 TargetLowering::DAGCombinerInfo &DCI) { 9606 SelectionDAG &DAG = DCI.DAG; 9607 const bool isIntrinsic = (N->getOpcode() == ISD::INTRINSIC_VOID || 9608 N->getOpcode() == ISD::INTRINSIC_W_CHAIN); 9609 const bool isStore = N->getOpcode() == ISD::STORE; 9610 const unsigned AddrOpIdx = ((isIntrinsic || isStore) ? 2 : 1); 9611 SDValue Addr = N->getOperand(AddrOpIdx); 9612 MemSDNode *MemN = cast<MemSDNode>(N); 9613 SDLoc dl(N); 9614 9615 // Search for a use of the address operand that is an increment. 9616 for (SDNode::use_iterator UI = Addr.getNode()->use_begin(), 9617 UE = Addr.getNode()->use_end(); UI != UE; ++UI) { 9618 SDNode *User = *UI; 9619 if (User->getOpcode() != ISD::ADD || 9620 UI.getUse().getResNo() != Addr.getResNo()) 9621 continue; 9622 9623 // Check that the add is independent of the load/store. Otherwise, folding 9624 // it would create a cycle. 9625 if (User->isPredecessorOf(N) || N->isPredecessorOf(User)) 9626 continue; 9627 9628 // Find the new opcode for the updating load/store. 9629 bool isLoadOp = true; 9630 bool isLaneOp = false; 9631 unsigned NewOpc = 0; 9632 unsigned NumVecs = 0; 9633 if (isIntrinsic) { 9634 unsigned IntNo = cast<ConstantSDNode>(N->getOperand(1))->getZExtValue(); 9635 switch (IntNo) { 9636 default: llvm_unreachable("unexpected intrinsic for Neon base update"); 9637 case Intrinsic::arm_neon_vld1: NewOpc = ARMISD::VLD1_UPD; 9638 NumVecs = 1; break; 9639 case Intrinsic::arm_neon_vld2: NewOpc = ARMISD::VLD2_UPD; 9640 NumVecs = 2; break; 9641 case Intrinsic::arm_neon_vld3: NewOpc = ARMISD::VLD3_UPD; 9642 NumVecs = 3; break; 9643 case Intrinsic::arm_neon_vld4: NewOpc = ARMISD::VLD4_UPD; 9644 NumVecs = 4; break; 9645 case Intrinsic::arm_neon_vld2lane: NewOpc = ARMISD::VLD2LN_UPD; 9646 NumVecs = 2; isLaneOp = true; break; 9647 case Intrinsic::arm_neon_vld3lane: NewOpc = ARMISD::VLD3LN_UPD; 9648 NumVecs = 3; isLaneOp = true; break; 9649 case Intrinsic::arm_neon_vld4lane: NewOpc = ARMISD::VLD4LN_UPD; 9650 NumVecs = 4; isLaneOp = true; break; 9651 case Intrinsic::arm_neon_vst1: NewOpc = ARMISD::VST1_UPD; 9652 NumVecs = 1; isLoadOp = false; break; 9653 case Intrinsic::arm_neon_vst2: NewOpc = ARMISD::VST2_UPD; 9654 NumVecs = 2; isLoadOp = false; break; 9655 case Intrinsic::arm_neon_vst3: NewOpc = ARMISD::VST3_UPD; 9656 NumVecs = 3; isLoadOp = false; break; 9657 case Intrinsic::arm_neon_vst4: NewOpc = ARMISD::VST4_UPD; 9658 NumVecs = 4; isLoadOp = false; break; 9659 case Intrinsic::arm_neon_vst2lane: NewOpc = ARMISD::VST2LN_UPD; 9660 NumVecs = 2; isLoadOp = false; isLaneOp = true; break; 9661 case Intrinsic::arm_neon_vst3lane: NewOpc = ARMISD::VST3LN_UPD; 9662 NumVecs = 3; isLoadOp = false; isLaneOp = true; break; 9663 case Intrinsic::arm_neon_vst4lane: NewOpc = ARMISD::VST4LN_UPD; 9664 NumVecs = 4; isLoadOp = false; isLaneOp = true; break; 9665 } 9666 } else { 9667 isLaneOp = true; 9668 switch (N->getOpcode()) { 9669 default: llvm_unreachable("unexpected opcode for Neon base update"); 9670 case ARMISD::VLD2DUP: NewOpc = ARMISD::VLD2DUP_UPD; NumVecs = 2; break; 9671 case ARMISD::VLD3DUP: NewOpc = ARMISD::VLD3DUP_UPD; NumVecs = 3; break; 9672 case ARMISD::VLD4DUP: NewOpc = ARMISD::VLD4DUP_UPD; NumVecs = 4; break; 9673 case ISD::LOAD: NewOpc = ARMISD::VLD1_UPD; 9674 NumVecs = 1; isLaneOp = false; break; 9675 case ISD::STORE: NewOpc = ARMISD::VST1_UPD; 9676 NumVecs = 1; isLaneOp = false; isLoadOp = false; break; 9677 } 9678 } 9679 9680 // Find the size of memory referenced by the load/store. 9681 EVT VecTy; 9682 if (isLoadOp) { 9683 VecTy = N->getValueType(0); 9684 } else if (isIntrinsic) { 9685 VecTy = N->getOperand(AddrOpIdx+1).getValueType(); 9686 } else { 9687 assert(isStore && "Node has to be a load, a store, or an intrinsic!"); 9688 VecTy = N->getOperand(1).getValueType(); 9689 } 9690 9691 unsigned NumBytes = NumVecs * VecTy.getSizeInBits() / 8; 9692 if (isLaneOp) 9693 NumBytes /= VecTy.getVectorNumElements(); 9694 9695 // If the increment is a constant, it must match the memory ref size. 9696 SDValue Inc = User->getOperand(User->getOperand(0) == Addr ? 1 : 0); 9697 if (ConstantSDNode *CInc = dyn_cast<ConstantSDNode>(Inc.getNode())) { 9698 uint64_t IncVal = CInc->getZExtValue(); 9699 if (IncVal != NumBytes) 9700 continue; 9701 } else if (NumBytes >= 3 * 16) { 9702 // VLD3/4 and VST3/4 for 128-bit vectors are implemented with two 9703 // separate instructions that make it harder to use a non-constant update. 9704 continue; 9705 } 9706 9707 // OK, we found an ADD we can fold into the base update. 9708 // Now, create a _UPD node, taking care of not breaking alignment. 9709 9710 EVT AlignedVecTy = VecTy; 9711 unsigned Alignment = MemN->getAlignment(); 9712 9713 // If this is a less-than-standard-aligned load/store, change the type to 9714 // match the standard alignment. 9715 // The alignment is overlooked when selecting _UPD variants; and it's 9716 // easier to introduce bitcasts here than fix that. 9717 // There are 3 ways to get to this base-update combine: 9718 // - intrinsics: they are assumed to be properly aligned (to the standard 9719 // alignment of the memory type), so we don't need to do anything. 9720 // - ARMISD::VLDx nodes: they are only generated from the aforementioned 9721 // intrinsics, so, likewise, there's nothing to do. 9722 // - generic load/store instructions: the alignment is specified as an 9723 // explicit operand, rather than implicitly as the standard alignment 9724 // of the memory type (like the intrisics). We need to change the 9725 // memory type to match the explicit alignment. That way, we don't 9726 // generate non-standard-aligned ARMISD::VLDx nodes. 9727 if (isa<LSBaseSDNode>(N)) { 9728 if (Alignment == 0) 9729 Alignment = 1; 9730 if (Alignment < VecTy.getScalarSizeInBits() / 8) { 9731 MVT EltTy = MVT::getIntegerVT(Alignment * 8); 9732 assert(NumVecs == 1 && "Unexpected multi-element generic load/store."); 9733 assert(!isLaneOp && "Unexpected generic load/store lane."); 9734 unsigned NumElts = NumBytes / (EltTy.getSizeInBits() / 8); 9735 AlignedVecTy = MVT::getVectorVT(EltTy, NumElts); 9736 } 9737 // Don't set an explicit alignment on regular load/stores that we want 9738 // to transform to VLD/VST 1_UPD nodes. 9739 // This matches the behavior of regular load/stores, which only get an 9740 // explicit alignment if the MMO alignment is larger than the standard 9741 // alignment of the memory type. 9742 // Intrinsics, however, always get an explicit alignment, set to the 9743 // alignment of the MMO. 9744 Alignment = 1; 9745 } 9746 9747 // Create the new updating load/store node. 9748 // First, create an SDVTList for the new updating node's results. 9749 EVT Tys[6]; 9750 unsigned NumResultVecs = (isLoadOp ? NumVecs : 0); 9751 unsigned n; 9752 for (n = 0; n < NumResultVecs; ++n) 9753 Tys[n] = AlignedVecTy; 9754 Tys[n++] = MVT::i32; 9755 Tys[n] = MVT::Other; 9756 SDVTList SDTys = DAG.getVTList(makeArrayRef(Tys, NumResultVecs+2)); 9757 9758 // Then, gather the new node's operands. 9759 SmallVector<SDValue, 8> Ops; 9760 Ops.push_back(N->getOperand(0)); // incoming chain 9761 Ops.push_back(N->getOperand(AddrOpIdx)); 9762 Ops.push_back(Inc); 9763 9764 if (StoreSDNode *StN = dyn_cast<StoreSDNode>(N)) { 9765 // Try to match the intrinsic's signature 9766 Ops.push_back(StN->getValue()); 9767 } else { 9768 // Loads (and of course intrinsics) match the intrinsics' signature, 9769 // so just add all but the alignment operand. 9770 for (unsigned i = AddrOpIdx + 1; i < N->getNumOperands() - 1; ++i) 9771 Ops.push_back(N->getOperand(i)); 9772 } 9773 9774 // For all node types, the alignment operand is always the last one. 9775 Ops.push_back(DAG.getConstant(Alignment, dl, MVT::i32)); 9776 9777 // If this is a non-standard-aligned STORE, the penultimate operand is the 9778 // stored value. Bitcast it to the aligned type. 9779 if (AlignedVecTy != VecTy && N->getOpcode() == ISD::STORE) { 9780 SDValue &StVal = Ops[Ops.size()-2]; 9781 StVal = DAG.getNode(ISD::BITCAST, dl, AlignedVecTy, StVal); 9782 } 9783 9784 SDValue UpdN = DAG.getMemIntrinsicNode(NewOpc, dl, SDTys, 9785 Ops, AlignedVecTy, 9786 MemN->getMemOperand()); 9787 9788 // Update the uses. 9789 SmallVector<SDValue, 5> NewResults; 9790 for (unsigned i = 0; i < NumResultVecs; ++i) 9791 NewResults.push_back(SDValue(UpdN.getNode(), i)); 9792 9793 // If this is an non-standard-aligned LOAD, the first result is the loaded 9794 // value. Bitcast it to the expected result type. 9795 if (AlignedVecTy != VecTy && N->getOpcode() == ISD::LOAD) { 9796 SDValue &LdVal = NewResults[0]; 9797 LdVal = DAG.getNode(ISD::BITCAST, dl, VecTy, LdVal); 9798 } 9799 9800 NewResults.push_back(SDValue(UpdN.getNode(), NumResultVecs+1)); // chain 9801 DCI.CombineTo(N, NewResults); 9802 DCI.CombineTo(User, SDValue(UpdN.getNode(), NumResultVecs)); 9803 9804 break; 9805 } 9806 return SDValue(); 9807 } 9808 9809 static SDValue PerformVLDCombine(SDNode *N, 9810 TargetLowering::DAGCombinerInfo &DCI) { 9811 if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer()) 9812 return SDValue(); 9813 9814 return CombineBaseUpdate(N, DCI); 9815 } 9816 9817 /// CombineVLDDUP - For a VDUPLANE node N, check if its source operand is a 9818 /// vldN-lane (N > 1) intrinsic, and if all the other uses of that intrinsic 9819 /// are also VDUPLANEs. If so, combine them to a vldN-dup operation and 9820 /// return true. 9821 static bool CombineVLDDUP(SDNode *N, TargetLowering::DAGCombinerInfo &DCI) { 9822 SelectionDAG &DAG = DCI.DAG; 9823 EVT VT = N->getValueType(0); 9824 // vldN-dup instructions only support 64-bit vectors for N > 1. 9825 if (!VT.is64BitVector()) 9826 return false; 9827 9828 // Check if the VDUPLANE operand is a vldN-dup intrinsic. 9829 SDNode *VLD = N->getOperand(0).getNode(); 9830 if (VLD->getOpcode() != ISD::INTRINSIC_W_CHAIN) 9831 return false; 9832 unsigned NumVecs = 0; 9833 unsigned NewOpc = 0; 9834 unsigned IntNo = cast<ConstantSDNode>(VLD->getOperand(1))->getZExtValue(); 9835 if (IntNo == Intrinsic::arm_neon_vld2lane) { 9836 NumVecs = 2; 9837 NewOpc = ARMISD::VLD2DUP; 9838 } else if (IntNo == Intrinsic::arm_neon_vld3lane) { 9839 NumVecs = 3; 9840 NewOpc = ARMISD::VLD3DUP; 9841 } else if (IntNo == Intrinsic::arm_neon_vld4lane) { 9842 NumVecs = 4; 9843 NewOpc = ARMISD::VLD4DUP; 9844 } else { 9845 return false; 9846 } 9847 9848 // First check that all the vldN-lane uses are VDUPLANEs and that the lane 9849 // numbers match the load. 9850 unsigned VLDLaneNo = 9851 cast<ConstantSDNode>(VLD->getOperand(NumVecs+3))->getZExtValue(); 9852 for (SDNode::use_iterator UI = VLD->use_begin(), UE = VLD->use_end(); 9853 UI != UE; ++UI) { 9854 // Ignore uses of the chain result. 9855 if (UI.getUse().getResNo() == NumVecs) 9856 continue; 9857 SDNode *User = *UI; 9858 if (User->getOpcode() != ARMISD::VDUPLANE || 9859 VLDLaneNo != cast<ConstantSDNode>(User->getOperand(1))->getZExtValue()) 9860 return false; 9861 } 9862 9863 // Create the vldN-dup node. 9864 EVT Tys[5]; 9865 unsigned n; 9866 for (n = 0; n < NumVecs; ++n) 9867 Tys[n] = VT; 9868 Tys[n] = MVT::Other; 9869 SDVTList SDTys = DAG.getVTList(makeArrayRef(Tys, NumVecs+1)); 9870 SDValue Ops[] = { VLD->getOperand(0), VLD->getOperand(2) }; 9871 MemIntrinsicSDNode *VLDMemInt = cast<MemIntrinsicSDNode>(VLD); 9872 SDValue VLDDup = DAG.getMemIntrinsicNode(NewOpc, SDLoc(VLD), SDTys, 9873 Ops, VLDMemInt->getMemoryVT(), 9874 VLDMemInt->getMemOperand()); 9875 9876 // Update the uses. 9877 for (SDNode::use_iterator UI = VLD->use_begin(), UE = VLD->use_end(); 9878 UI != UE; ++UI) { 9879 unsigned ResNo = UI.getUse().getResNo(); 9880 // Ignore uses of the chain result. 9881 if (ResNo == NumVecs) 9882 continue; 9883 SDNode *User = *UI; 9884 DCI.CombineTo(User, SDValue(VLDDup.getNode(), ResNo)); 9885 } 9886 9887 // Now the vldN-lane intrinsic is dead except for its chain result. 9888 // Update uses of the chain. 9889 std::vector<SDValue> VLDDupResults; 9890 for (unsigned n = 0; n < NumVecs; ++n) 9891 VLDDupResults.push_back(SDValue(VLDDup.getNode(), n)); 9892 VLDDupResults.push_back(SDValue(VLDDup.getNode(), NumVecs)); 9893 DCI.CombineTo(VLD, VLDDupResults); 9894 9895 return true; 9896 } 9897 9898 /// PerformVDUPLANECombine - Target-specific dag combine xforms for 9899 /// ARMISD::VDUPLANE. 9900 static SDValue PerformVDUPLANECombine(SDNode *N, 9901 TargetLowering::DAGCombinerInfo &DCI) { 9902 SDValue Op = N->getOperand(0); 9903 9904 // If the source is a vldN-lane (N > 1) intrinsic, and all the other uses 9905 // of that intrinsic are also VDUPLANEs, combine them to a vldN-dup operation. 9906 if (CombineVLDDUP(N, DCI)) 9907 return SDValue(N, 0); 9908 9909 // If the source is already a VMOVIMM or VMVNIMM splat, the VDUPLANE is 9910 // redundant. Ignore bit_converts for now; element sizes are checked below. 9911 while (Op.getOpcode() == ISD::BITCAST) 9912 Op = Op.getOperand(0); 9913 if (Op.getOpcode() != ARMISD::VMOVIMM && Op.getOpcode() != ARMISD::VMVNIMM) 9914 return SDValue(); 9915 9916 // Make sure the VMOV element size is not bigger than the VDUPLANE elements. 9917 unsigned EltSize = Op.getValueType().getVectorElementType().getSizeInBits(); 9918 // The canonical VMOV for a zero vector uses a 32-bit element size. 9919 unsigned Imm = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue(); 9920 unsigned EltBits; 9921 if (ARM_AM::decodeNEONModImm(Imm, EltBits) == 0) 9922 EltSize = 8; 9923 EVT VT = N->getValueType(0); 9924 if (EltSize > VT.getVectorElementType().getSizeInBits()) 9925 return SDValue(); 9926 9927 return DCI.DAG.getNode(ISD::BITCAST, SDLoc(N), VT, Op); 9928 } 9929 9930 static SDValue PerformLOADCombine(SDNode *N, 9931 TargetLowering::DAGCombinerInfo &DCI) { 9932 EVT VT = N->getValueType(0); 9933 9934 // If this is a legal vector load, try to combine it into a VLD1_UPD. 9935 if (ISD::isNormalLoad(N) && VT.isVector() && 9936 DCI.DAG.getTargetLoweringInfo().isTypeLegal(VT)) 9937 return CombineBaseUpdate(N, DCI); 9938 9939 return SDValue(); 9940 } 9941 9942 /// PerformSTORECombine - Target-specific dag combine xforms for 9943 /// ISD::STORE. 9944 static SDValue PerformSTORECombine(SDNode *N, 9945 TargetLowering::DAGCombinerInfo &DCI) { 9946 StoreSDNode *St = cast<StoreSDNode>(N); 9947 if (St->isVolatile()) 9948 return SDValue(); 9949 9950 // Optimize trunc store (of multiple scalars) to shuffle and store. First, 9951 // pack all of the elements in one place. Next, store to memory in fewer 9952 // chunks. 9953 SDValue StVal = St->getValue(); 9954 EVT VT = StVal.getValueType(); 9955 if (St->isTruncatingStore() && VT.isVector()) { 9956 SelectionDAG &DAG = DCI.DAG; 9957 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 9958 EVT StVT = St->getMemoryVT(); 9959 unsigned NumElems = VT.getVectorNumElements(); 9960 assert(StVT != VT && "Cannot truncate to the same type"); 9961 unsigned FromEltSz = VT.getVectorElementType().getSizeInBits(); 9962 unsigned ToEltSz = StVT.getVectorElementType().getSizeInBits(); 9963 9964 // From, To sizes and ElemCount must be pow of two 9965 if (!isPowerOf2_32(NumElems * FromEltSz * ToEltSz)) return SDValue(); 9966 9967 // We are going to use the original vector elt for storing. 9968 // Accumulated smaller vector elements must be a multiple of the store size. 9969 if (0 != (NumElems * FromEltSz) % ToEltSz) return SDValue(); 9970 9971 unsigned SizeRatio = FromEltSz / ToEltSz; 9972 assert(SizeRatio * NumElems * ToEltSz == VT.getSizeInBits()); 9973 9974 // Create a type on which we perform the shuffle. 9975 EVT WideVecVT = EVT::getVectorVT(*DAG.getContext(), StVT.getScalarType(), 9976 NumElems*SizeRatio); 9977 assert(WideVecVT.getSizeInBits() == VT.getSizeInBits()); 9978 9979 SDLoc DL(St); 9980 SDValue WideVec = DAG.getNode(ISD::BITCAST, DL, WideVecVT, StVal); 9981 SmallVector<int, 8> ShuffleVec(NumElems * SizeRatio, -1); 9982 for (unsigned i = 0; i < NumElems; ++i) 9983 ShuffleVec[i] = DAG.getDataLayout().isBigEndian() 9984 ? (i + 1) * SizeRatio - 1 9985 : i * SizeRatio; 9986 9987 // Can't shuffle using an illegal type. 9988 if (!TLI.isTypeLegal(WideVecVT)) return SDValue(); 9989 9990 SDValue Shuff = DAG.getVectorShuffle(WideVecVT, DL, WideVec, 9991 DAG.getUNDEF(WideVec.getValueType()), 9992 ShuffleVec.data()); 9993 // At this point all of the data is stored at the bottom of the 9994 // register. We now need to save it to mem. 9995 9996 // Find the largest store unit 9997 MVT StoreType = MVT::i8; 9998 for (MVT Tp : MVT::integer_valuetypes()) { 9999 if (TLI.isTypeLegal(Tp) && Tp.getSizeInBits() <= NumElems * ToEltSz) 10000 StoreType = Tp; 10001 } 10002 // Didn't find a legal store type. 10003 if (!TLI.isTypeLegal(StoreType)) 10004 return SDValue(); 10005 10006 // Bitcast the original vector into a vector of store-size units 10007 EVT StoreVecVT = EVT::getVectorVT(*DAG.getContext(), 10008 StoreType, VT.getSizeInBits()/EVT(StoreType).getSizeInBits()); 10009 assert(StoreVecVT.getSizeInBits() == VT.getSizeInBits()); 10010 SDValue ShuffWide = DAG.getNode(ISD::BITCAST, DL, StoreVecVT, Shuff); 10011 SmallVector<SDValue, 8> Chains; 10012 SDValue Increment = DAG.getConstant(StoreType.getSizeInBits() / 8, DL, 10013 TLI.getPointerTy(DAG.getDataLayout())); 10014 SDValue BasePtr = St->getBasePtr(); 10015 10016 // Perform one or more big stores into memory. 10017 unsigned E = (ToEltSz*NumElems)/StoreType.getSizeInBits(); 10018 for (unsigned I = 0; I < E; I++) { 10019 SDValue SubVec = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, 10020 StoreType, ShuffWide, 10021 DAG.getIntPtrConstant(I, DL)); 10022 SDValue Ch = DAG.getStore(St->getChain(), DL, SubVec, BasePtr, 10023 St->getPointerInfo(), St->isVolatile(), 10024 St->isNonTemporal(), St->getAlignment()); 10025 BasePtr = DAG.getNode(ISD::ADD, DL, BasePtr.getValueType(), BasePtr, 10026 Increment); 10027 Chains.push_back(Ch); 10028 } 10029 return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Chains); 10030 } 10031 10032 if (!ISD::isNormalStore(St)) 10033 return SDValue(); 10034 10035 // Split a store of a VMOVDRR into two integer stores to avoid mixing NEON and 10036 // ARM stores of arguments in the same cache line. 10037 if (StVal.getNode()->getOpcode() == ARMISD::VMOVDRR && 10038 StVal.getNode()->hasOneUse()) { 10039 SelectionDAG &DAG = DCI.DAG; 10040 bool isBigEndian = DAG.getDataLayout().isBigEndian(); 10041 SDLoc DL(St); 10042 SDValue BasePtr = St->getBasePtr(); 10043 SDValue NewST1 = DAG.getStore(St->getChain(), DL, 10044 StVal.getNode()->getOperand(isBigEndian ? 1 : 0 ), 10045 BasePtr, St->getPointerInfo(), St->isVolatile(), 10046 St->isNonTemporal(), St->getAlignment()); 10047 10048 SDValue OffsetPtr = DAG.getNode(ISD::ADD, DL, MVT::i32, BasePtr, 10049 DAG.getConstant(4, DL, MVT::i32)); 10050 return DAG.getStore(NewST1.getValue(0), DL, 10051 StVal.getNode()->getOperand(isBigEndian ? 0 : 1), 10052 OffsetPtr, St->getPointerInfo(), St->isVolatile(), 10053 St->isNonTemporal(), 10054 std::min(4U, St->getAlignment() / 2)); 10055 } 10056 10057 if (StVal.getValueType() == MVT::i64 && 10058 StVal.getNode()->getOpcode() == ISD::EXTRACT_VECTOR_ELT) { 10059 10060 // Bitcast an i64 store extracted from a vector to f64. 10061 // Otherwise, the i64 value will be legalized to a pair of i32 values. 10062 SelectionDAG &DAG = DCI.DAG; 10063 SDLoc dl(StVal); 10064 SDValue IntVec = StVal.getOperand(0); 10065 EVT FloatVT = EVT::getVectorVT(*DAG.getContext(), MVT::f64, 10066 IntVec.getValueType().getVectorNumElements()); 10067 SDValue Vec = DAG.getNode(ISD::BITCAST, dl, FloatVT, IntVec); 10068 SDValue ExtElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, 10069 Vec, StVal.getOperand(1)); 10070 dl = SDLoc(N); 10071 SDValue V = DAG.getNode(ISD::BITCAST, dl, MVT::i64, ExtElt); 10072 // Make the DAGCombiner fold the bitcasts. 10073 DCI.AddToWorklist(Vec.getNode()); 10074 DCI.AddToWorklist(ExtElt.getNode()); 10075 DCI.AddToWorklist(V.getNode()); 10076 return DAG.getStore(St->getChain(), dl, V, St->getBasePtr(), 10077 St->getPointerInfo(), St->isVolatile(), 10078 St->isNonTemporal(), St->getAlignment(), 10079 St->getAAInfo()); 10080 } 10081 10082 // If this is a legal vector store, try to combine it into a VST1_UPD. 10083 if (ISD::isNormalStore(N) && VT.isVector() && 10084 DCI.DAG.getTargetLoweringInfo().isTypeLegal(VT)) 10085 return CombineBaseUpdate(N, DCI); 10086 10087 return SDValue(); 10088 } 10089 10090 /// PerformVCVTCombine - VCVT (floating-point to fixed-point, Advanced SIMD) 10091 /// can replace combinations of VMUL and VCVT (floating-point to integer) 10092 /// when the VMUL has a constant operand that is a power of 2. 10093 /// 10094 /// Example (assume d17 = <float 8.000000e+00, float 8.000000e+00>): 10095 /// vmul.f32 d16, d17, d16 10096 /// vcvt.s32.f32 d16, d16 10097 /// becomes: 10098 /// vcvt.s32.f32 d16, d16, #3 10099 static SDValue PerformVCVTCombine(SDNode *N, SelectionDAG &DAG, 10100 const ARMSubtarget *Subtarget) { 10101 if (!Subtarget->hasNEON()) 10102 return SDValue(); 10103 10104 SDValue Op = N->getOperand(0); 10105 if (!Op.getValueType().isVector() || Op.getOpcode() != ISD::FMUL) 10106 return SDValue(); 10107 10108 SDValue ConstVec = Op->getOperand(1); 10109 if (!isa<BuildVectorSDNode>(ConstVec)) 10110 return SDValue(); 10111 10112 MVT FloatTy = Op.getSimpleValueType().getVectorElementType(); 10113 uint32_t FloatBits = FloatTy.getSizeInBits(); 10114 MVT IntTy = N->getSimpleValueType(0).getVectorElementType(); 10115 uint32_t IntBits = IntTy.getSizeInBits(); 10116 unsigned NumLanes = Op.getValueType().getVectorNumElements(); 10117 if (FloatBits != 32 || IntBits > 32 || NumLanes > 4) { 10118 // These instructions only exist converting from f32 to i32. We can handle 10119 // smaller integers by generating an extra truncate, but larger ones would 10120 // be lossy. We also can't handle more then 4 lanes, since these intructions 10121 // only support v2i32/v4i32 types. 10122 return SDValue(); 10123 } 10124 10125 BitVector UndefElements; 10126 BuildVectorSDNode *BV = cast<BuildVectorSDNode>(ConstVec); 10127 int32_t C = BV->getConstantFPSplatPow2ToLog2Int(&UndefElements, 33); 10128 if (C == -1 || C == 0 || C > 32) 10129 return SDValue(); 10130 10131 SDLoc dl(N); 10132 bool isSigned = N->getOpcode() == ISD::FP_TO_SINT; 10133 unsigned IntrinsicOpcode = isSigned ? Intrinsic::arm_neon_vcvtfp2fxs : 10134 Intrinsic::arm_neon_vcvtfp2fxu; 10135 SDValue FixConv = DAG.getNode( 10136 ISD::INTRINSIC_WO_CHAIN, dl, NumLanes == 2 ? MVT::v2i32 : MVT::v4i32, 10137 DAG.getConstant(IntrinsicOpcode, dl, MVT::i32), Op->getOperand(0), 10138 DAG.getConstant(C, dl, MVT::i32)); 10139 10140 if (IntBits < FloatBits) 10141 FixConv = DAG.getNode(ISD::TRUNCATE, dl, N->getValueType(0), FixConv); 10142 10143 return FixConv; 10144 } 10145 10146 /// PerformVDIVCombine - VCVT (fixed-point to floating-point, Advanced SIMD) 10147 /// can replace combinations of VCVT (integer to floating-point) and VDIV 10148 /// when the VDIV has a constant operand that is a power of 2. 10149 /// 10150 /// Example (assume d17 = <float 8.000000e+00, float 8.000000e+00>): 10151 /// vcvt.f32.s32 d16, d16 10152 /// vdiv.f32 d16, d17, d16 10153 /// becomes: 10154 /// vcvt.f32.s32 d16, d16, #3 10155 static SDValue PerformVDIVCombine(SDNode *N, SelectionDAG &DAG, 10156 const ARMSubtarget *Subtarget) { 10157 if (!Subtarget->hasNEON()) 10158 return SDValue(); 10159 10160 SDValue Op = N->getOperand(0); 10161 unsigned OpOpcode = Op.getNode()->getOpcode(); 10162 if (!N->getValueType(0).isVector() || 10163 (OpOpcode != ISD::SINT_TO_FP && OpOpcode != ISD::UINT_TO_FP)) 10164 return SDValue(); 10165 10166 SDValue ConstVec = N->getOperand(1); 10167 if (!isa<BuildVectorSDNode>(ConstVec)) 10168 return SDValue(); 10169 10170 MVT FloatTy = N->getSimpleValueType(0).getVectorElementType(); 10171 uint32_t FloatBits = FloatTy.getSizeInBits(); 10172 MVT IntTy = Op.getOperand(0).getSimpleValueType().getVectorElementType(); 10173 uint32_t IntBits = IntTy.getSizeInBits(); 10174 unsigned NumLanes = Op.getValueType().getVectorNumElements(); 10175 if (FloatBits != 32 || IntBits > 32 || NumLanes > 4) { 10176 // These instructions only exist converting from i32 to f32. We can handle 10177 // smaller integers by generating an extra extend, but larger ones would 10178 // be lossy. We also can't handle more then 4 lanes, since these intructions 10179 // only support v2i32/v4i32 types. 10180 return SDValue(); 10181 } 10182 10183 BitVector UndefElements; 10184 BuildVectorSDNode *BV = cast<BuildVectorSDNode>(ConstVec); 10185 int32_t C = BV->getConstantFPSplatPow2ToLog2Int(&UndefElements, 33); 10186 if (C == -1 || C == 0 || C > 32) 10187 return SDValue(); 10188 10189 SDLoc dl(N); 10190 bool isSigned = OpOpcode == ISD::SINT_TO_FP; 10191 SDValue ConvInput = Op.getOperand(0); 10192 if (IntBits < FloatBits) 10193 ConvInput = DAG.getNode(isSigned ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND, 10194 dl, NumLanes == 2 ? MVT::v2i32 : MVT::v4i32, 10195 ConvInput); 10196 10197 unsigned IntrinsicOpcode = isSigned ? Intrinsic::arm_neon_vcvtfxs2fp : 10198 Intrinsic::arm_neon_vcvtfxu2fp; 10199 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, 10200 Op.getValueType(), 10201 DAG.getConstant(IntrinsicOpcode, dl, MVT::i32), 10202 ConvInput, DAG.getConstant(C, dl, MVT::i32)); 10203 } 10204 10205 /// Getvshiftimm - Check if this is a valid build_vector for the immediate 10206 /// operand of a vector shift operation, where all the elements of the 10207 /// build_vector must have the same constant integer value. 10208 static bool getVShiftImm(SDValue Op, unsigned ElementBits, int64_t &Cnt) { 10209 // Ignore bit_converts. 10210 while (Op.getOpcode() == ISD::BITCAST) 10211 Op = Op.getOperand(0); 10212 BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(Op.getNode()); 10213 APInt SplatBits, SplatUndef; 10214 unsigned SplatBitSize; 10215 bool HasAnyUndefs; 10216 if (! BVN || ! BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, 10217 HasAnyUndefs, ElementBits) || 10218 SplatBitSize > ElementBits) 10219 return false; 10220 Cnt = SplatBits.getSExtValue(); 10221 return true; 10222 } 10223 10224 /// isVShiftLImm - Check if this is a valid build_vector for the immediate 10225 /// operand of a vector shift left operation. That value must be in the range: 10226 /// 0 <= Value < ElementBits for a left shift; or 10227 /// 0 <= Value <= ElementBits for a long left shift. 10228 static bool isVShiftLImm(SDValue Op, EVT VT, bool isLong, int64_t &Cnt) { 10229 assert(VT.isVector() && "vector shift count is not a vector type"); 10230 int64_t ElementBits = VT.getVectorElementType().getSizeInBits(); 10231 if (! getVShiftImm(Op, ElementBits, Cnt)) 10232 return false; 10233 return (Cnt >= 0 && (isLong ? Cnt-1 : Cnt) < ElementBits); 10234 } 10235 10236 /// isVShiftRImm - Check if this is a valid build_vector for the immediate 10237 /// operand of a vector shift right operation. For a shift opcode, the value 10238 /// is positive, but for an intrinsic the value count must be negative. The 10239 /// absolute value must be in the range: 10240 /// 1 <= |Value| <= ElementBits for a right shift; or 10241 /// 1 <= |Value| <= ElementBits/2 for a narrow right shift. 10242 static bool isVShiftRImm(SDValue Op, EVT VT, bool isNarrow, bool isIntrinsic, 10243 int64_t &Cnt) { 10244 assert(VT.isVector() && "vector shift count is not a vector type"); 10245 int64_t ElementBits = VT.getVectorElementType().getSizeInBits(); 10246 if (! getVShiftImm(Op, ElementBits, Cnt)) 10247 return false; 10248 if (!isIntrinsic) 10249 return (Cnt >= 1 && Cnt <= (isNarrow ? ElementBits/2 : ElementBits)); 10250 if (Cnt >= -(isNarrow ? ElementBits/2 : ElementBits) && Cnt <= -1) { 10251 Cnt = -Cnt; 10252 return true; 10253 } 10254 return false; 10255 } 10256 10257 /// PerformIntrinsicCombine - ARM-specific DAG combining for intrinsics. 10258 static SDValue PerformIntrinsicCombine(SDNode *N, SelectionDAG &DAG) { 10259 unsigned IntNo = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue(); 10260 switch (IntNo) { 10261 default: 10262 // Don't do anything for most intrinsics. 10263 break; 10264 10265 // Vector shifts: check for immediate versions and lower them. 10266 // Note: This is done during DAG combining instead of DAG legalizing because 10267 // the build_vectors for 64-bit vector element shift counts are generally 10268 // not legal, and it is hard to see their values after they get legalized to 10269 // loads from a constant pool. 10270 case Intrinsic::arm_neon_vshifts: 10271 case Intrinsic::arm_neon_vshiftu: 10272 case Intrinsic::arm_neon_vrshifts: 10273 case Intrinsic::arm_neon_vrshiftu: 10274 case Intrinsic::arm_neon_vrshiftn: 10275 case Intrinsic::arm_neon_vqshifts: 10276 case Intrinsic::arm_neon_vqshiftu: 10277 case Intrinsic::arm_neon_vqshiftsu: 10278 case Intrinsic::arm_neon_vqshiftns: 10279 case Intrinsic::arm_neon_vqshiftnu: 10280 case Intrinsic::arm_neon_vqshiftnsu: 10281 case Intrinsic::arm_neon_vqrshiftns: 10282 case Intrinsic::arm_neon_vqrshiftnu: 10283 case Intrinsic::arm_neon_vqrshiftnsu: { 10284 EVT VT = N->getOperand(1).getValueType(); 10285 int64_t Cnt; 10286 unsigned VShiftOpc = 0; 10287 10288 switch (IntNo) { 10289 case Intrinsic::arm_neon_vshifts: 10290 case Intrinsic::arm_neon_vshiftu: 10291 if (isVShiftLImm(N->getOperand(2), VT, false, Cnt)) { 10292 VShiftOpc = ARMISD::VSHL; 10293 break; 10294 } 10295 if (isVShiftRImm(N->getOperand(2), VT, false, true, Cnt)) { 10296 VShiftOpc = (IntNo == Intrinsic::arm_neon_vshifts ? 10297 ARMISD::VSHRs : ARMISD::VSHRu); 10298 break; 10299 } 10300 return SDValue(); 10301 10302 case Intrinsic::arm_neon_vrshifts: 10303 case Intrinsic::arm_neon_vrshiftu: 10304 if (isVShiftRImm(N->getOperand(2), VT, false, true, Cnt)) 10305 break; 10306 return SDValue(); 10307 10308 case Intrinsic::arm_neon_vqshifts: 10309 case Intrinsic::arm_neon_vqshiftu: 10310 if (isVShiftLImm(N->getOperand(2), VT, false, Cnt)) 10311 break; 10312 return SDValue(); 10313 10314 case Intrinsic::arm_neon_vqshiftsu: 10315 if (isVShiftLImm(N->getOperand(2), VT, false, Cnt)) 10316 break; 10317 llvm_unreachable("invalid shift count for vqshlu intrinsic"); 10318 10319 case Intrinsic::arm_neon_vrshiftn: 10320 case Intrinsic::arm_neon_vqshiftns: 10321 case Intrinsic::arm_neon_vqshiftnu: 10322 case Intrinsic::arm_neon_vqshiftnsu: 10323 case Intrinsic::arm_neon_vqrshiftns: 10324 case Intrinsic::arm_neon_vqrshiftnu: 10325 case Intrinsic::arm_neon_vqrshiftnsu: 10326 // Narrowing shifts require an immediate right shift. 10327 if (isVShiftRImm(N->getOperand(2), VT, true, true, Cnt)) 10328 break; 10329 llvm_unreachable("invalid shift count for narrowing vector shift " 10330 "intrinsic"); 10331 10332 default: 10333 llvm_unreachable("unhandled vector shift"); 10334 } 10335 10336 switch (IntNo) { 10337 case Intrinsic::arm_neon_vshifts: 10338 case Intrinsic::arm_neon_vshiftu: 10339 // Opcode already set above. 10340 break; 10341 case Intrinsic::arm_neon_vrshifts: 10342 VShiftOpc = ARMISD::VRSHRs; break; 10343 case Intrinsic::arm_neon_vrshiftu: 10344 VShiftOpc = ARMISD::VRSHRu; break; 10345 case Intrinsic::arm_neon_vrshiftn: 10346 VShiftOpc = ARMISD::VRSHRN; break; 10347 case Intrinsic::arm_neon_vqshifts: 10348 VShiftOpc = ARMISD::VQSHLs; break; 10349 case Intrinsic::arm_neon_vqshiftu: 10350 VShiftOpc = ARMISD::VQSHLu; break; 10351 case Intrinsic::arm_neon_vqshiftsu: 10352 VShiftOpc = ARMISD::VQSHLsu; break; 10353 case Intrinsic::arm_neon_vqshiftns: 10354 VShiftOpc = ARMISD::VQSHRNs; break; 10355 case Intrinsic::arm_neon_vqshiftnu: 10356 VShiftOpc = ARMISD::VQSHRNu; break; 10357 case Intrinsic::arm_neon_vqshiftnsu: 10358 VShiftOpc = ARMISD::VQSHRNsu; break; 10359 case Intrinsic::arm_neon_vqrshiftns: 10360 VShiftOpc = ARMISD::VQRSHRNs; break; 10361 case Intrinsic::arm_neon_vqrshiftnu: 10362 VShiftOpc = ARMISD::VQRSHRNu; break; 10363 case Intrinsic::arm_neon_vqrshiftnsu: 10364 VShiftOpc = ARMISD::VQRSHRNsu; break; 10365 } 10366 10367 SDLoc dl(N); 10368 return DAG.getNode(VShiftOpc, dl, N->getValueType(0), 10369 N->getOperand(1), DAG.getConstant(Cnt, dl, MVT::i32)); 10370 } 10371 10372 case Intrinsic::arm_neon_vshiftins: { 10373 EVT VT = N->getOperand(1).getValueType(); 10374 int64_t Cnt; 10375 unsigned VShiftOpc = 0; 10376 10377 if (isVShiftLImm(N->getOperand(3), VT, false, Cnt)) 10378 VShiftOpc = ARMISD::VSLI; 10379 else if (isVShiftRImm(N->getOperand(3), VT, false, true, Cnt)) 10380 VShiftOpc = ARMISD::VSRI; 10381 else { 10382 llvm_unreachable("invalid shift count for vsli/vsri intrinsic"); 10383 } 10384 10385 SDLoc dl(N); 10386 return DAG.getNode(VShiftOpc, dl, N->getValueType(0), 10387 N->getOperand(1), N->getOperand(2), 10388 DAG.getConstant(Cnt, dl, MVT::i32)); 10389 } 10390 10391 case Intrinsic::arm_neon_vqrshifts: 10392 case Intrinsic::arm_neon_vqrshiftu: 10393 // No immediate versions of these to check for. 10394 break; 10395 } 10396 10397 return SDValue(); 10398 } 10399 10400 /// PerformShiftCombine - Checks for immediate versions of vector shifts and 10401 /// lowers them. As with the vector shift intrinsics, this is done during DAG 10402 /// combining instead of DAG legalizing because the build_vectors for 64-bit 10403 /// vector element shift counts are generally not legal, and it is hard to see 10404 /// their values after they get legalized to loads from a constant pool. 10405 static SDValue PerformShiftCombine(SDNode *N, SelectionDAG &DAG, 10406 const ARMSubtarget *ST) { 10407 EVT VT = N->getValueType(0); 10408 if (N->getOpcode() == ISD::SRL && VT == MVT::i32 && ST->hasV6Ops()) { 10409 // Canonicalize (srl (bswap x), 16) to (rotr (bswap x), 16) if the high 10410 // 16-bits of x is zero. This optimizes rev + lsr 16 to rev16. 10411 SDValue N1 = N->getOperand(1); 10412 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(N1)) { 10413 SDValue N0 = N->getOperand(0); 10414 if (C->getZExtValue() == 16 && N0.getOpcode() == ISD::BSWAP && 10415 DAG.MaskedValueIsZero(N0.getOperand(0), 10416 APInt::getHighBitsSet(32, 16))) 10417 return DAG.getNode(ISD::ROTR, SDLoc(N), VT, N0, N1); 10418 } 10419 } 10420 10421 // Nothing to be done for scalar shifts. 10422 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 10423 if (!VT.isVector() || !TLI.isTypeLegal(VT)) 10424 return SDValue(); 10425 10426 assert(ST->hasNEON() && "unexpected vector shift"); 10427 int64_t Cnt; 10428 10429 switch (N->getOpcode()) { 10430 default: llvm_unreachable("unexpected shift opcode"); 10431 10432 case ISD::SHL: 10433 if (isVShiftLImm(N->getOperand(1), VT, false, Cnt)) { 10434 SDLoc dl(N); 10435 return DAG.getNode(ARMISD::VSHL, dl, VT, N->getOperand(0), 10436 DAG.getConstant(Cnt, dl, MVT::i32)); 10437 } 10438 break; 10439 10440 case ISD::SRA: 10441 case ISD::SRL: 10442 if (isVShiftRImm(N->getOperand(1), VT, false, false, Cnt)) { 10443 unsigned VShiftOpc = (N->getOpcode() == ISD::SRA ? 10444 ARMISD::VSHRs : ARMISD::VSHRu); 10445 SDLoc dl(N); 10446 return DAG.getNode(VShiftOpc, dl, VT, N->getOperand(0), 10447 DAG.getConstant(Cnt, dl, MVT::i32)); 10448 } 10449 } 10450 return SDValue(); 10451 } 10452 10453 /// PerformExtendCombine - Target-specific DAG combining for ISD::SIGN_EXTEND, 10454 /// ISD::ZERO_EXTEND, and ISD::ANY_EXTEND. 10455 static SDValue PerformExtendCombine(SDNode *N, SelectionDAG &DAG, 10456 const ARMSubtarget *ST) { 10457 SDValue N0 = N->getOperand(0); 10458 10459 // Check for sign- and zero-extensions of vector extract operations of 8- 10460 // and 16-bit vector elements. NEON supports these directly. They are 10461 // handled during DAG combining because type legalization will promote them 10462 // to 32-bit types and it is messy to recognize the operations after that. 10463 if (ST->hasNEON() && N0.getOpcode() == ISD::EXTRACT_VECTOR_ELT) { 10464 SDValue Vec = N0.getOperand(0); 10465 SDValue Lane = N0.getOperand(1); 10466 EVT VT = N->getValueType(0); 10467 EVT EltVT = N0.getValueType(); 10468 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 10469 10470 if (VT == MVT::i32 && 10471 (EltVT == MVT::i8 || EltVT == MVT::i16) && 10472 TLI.isTypeLegal(Vec.getValueType()) && 10473 isa<ConstantSDNode>(Lane)) { 10474 10475 unsigned Opc = 0; 10476 switch (N->getOpcode()) { 10477 default: llvm_unreachable("unexpected opcode"); 10478 case ISD::SIGN_EXTEND: 10479 Opc = ARMISD::VGETLANEs; 10480 break; 10481 case ISD::ZERO_EXTEND: 10482 case ISD::ANY_EXTEND: 10483 Opc = ARMISD::VGETLANEu; 10484 break; 10485 } 10486 return DAG.getNode(Opc, SDLoc(N), VT, Vec, Lane); 10487 } 10488 } 10489 10490 return SDValue(); 10491 } 10492 10493 static void computeKnownBits(SelectionDAG &DAG, SDValue Op, APInt &KnownZero, 10494 APInt &KnownOne) { 10495 if (Op.getOpcode() == ARMISD::BFI) { 10496 // Conservatively, we can recurse down the first operand 10497 // and just mask out all affected bits. 10498 computeKnownBits(DAG, Op.getOperand(0), KnownZero, KnownOne); 10499 10500 // The operand to BFI is already a mask suitable for removing the bits it 10501 // sets. 10502 ConstantSDNode *CI = cast<ConstantSDNode>(Op.getOperand(2)); 10503 APInt Mask = CI->getAPIntValue(); 10504 KnownZero &= Mask; 10505 KnownOne &= Mask; 10506 return; 10507 } 10508 if (Op.getOpcode() == ARMISD::CMOV) { 10509 APInt KZ2(KnownZero.getBitWidth(), 0); 10510 APInt KO2(KnownOne.getBitWidth(), 0); 10511 computeKnownBits(DAG, Op.getOperand(1), KnownZero, KnownOne); 10512 computeKnownBits(DAG, Op.getOperand(2), KZ2, KO2); 10513 10514 KnownZero &= KZ2; 10515 KnownOne &= KO2; 10516 return; 10517 } 10518 return DAG.computeKnownBits(Op, KnownZero, KnownOne); 10519 } 10520 10521 SDValue ARMTargetLowering::PerformCMOVToBFICombine(SDNode *CMOV, SelectionDAG &DAG) const { 10522 // If we have a CMOV, OR and AND combination such as: 10523 // if (x & CN) 10524 // y |= CM; 10525 // 10526 // And: 10527 // * CN is a single bit; 10528 // * All bits covered by CM are known zero in y 10529 // 10530 // Then we can convert this into a sequence of BFI instructions. This will 10531 // always be a win if CM is a single bit, will always be no worse than the 10532 // TST&OR sequence if CM is two bits, and for thumb will be no worse if CM is 10533 // three bits (due to the extra IT instruction). 10534 10535 SDValue Op0 = CMOV->getOperand(0); 10536 SDValue Op1 = CMOV->getOperand(1); 10537 auto CCNode = cast<ConstantSDNode>(CMOV->getOperand(2)); 10538 auto CC = CCNode->getAPIntValue().getLimitedValue(); 10539 SDValue CmpZ = CMOV->getOperand(4); 10540 10541 // The compare must be against zero. 10542 if (!isNullConstant(CmpZ->getOperand(1))) 10543 return SDValue(); 10544 10545 assert(CmpZ->getOpcode() == ARMISD::CMPZ); 10546 SDValue And = CmpZ->getOperand(0); 10547 if (And->getOpcode() != ISD::AND) 10548 return SDValue(); 10549 ConstantSDNode *AndC = dyn_cast<ConstantSDNode>(And->getOperand(1)); 10550 if (!AndC || !AndC->getAPIntValue().isPowerOf2()) 10551 return SDValue(); 10552 SDValue X = And->getOperand(0); 10553 10554 if (CC == ARMCC::EQ) { 10555 // We're performing an "equal to zero" compare. Swap the operands so we 10556 // canonicalize on a "not equal to zero" compare. 10557 std::swap(Op0, Op1); 10558 } else { 10559 assert(CC == ARMCC::NE && "How can a CMPZ node not be EQ or NE?"); 10560 } 10561 10562 if (Op1->getOpcode() != ISD::OR) 10563 return SDValue(); 10564 10565 ConstantSDNode *OrC = dyn_cast<ConstantSDNode>(Op1->getOperand(1)); 10566 if (!OrC) 10567 return SDValue(); 10568 SDValue Y = Op1->getOperand(0); 10569 10570 if (Op0 != Y) 10571 return SDValue(); 10572 10573 // Now, is it profitable to continue? 10574 APInt OrCI = OrC->getAPIntValue(); 10575 unsigned Heuristic = Subtarget->isThumb() ? 3 : 2; 10576 if (OrCI.countPopulation() > Heuristic) 10577 return SDValue(); 10578 10579 // Lastly, can we determine that the bits defined by OrCI 10580 // are zero in Y? 10581 APInt KnownZero, KnownOne; 10582 computeKnownBits(DAG, Y, KnownZero, KnownOne); 10583 if ((OrCI & KnownZero) != OrCI) 10584 return SDValue(); 10585 10586 // OK, we can do the combine. 10587 SDValue V = Y; 10588 SDLoc dl(X); 10589 EVT VT = X.getValueType(); 10590 unsigned BitInX = AndC->getAPIntValue().logBase2(); 10591 10592 if (BitInX != 0) { 10593 // We must shift X first. 10594 X = DAG.getNode(ISD::SRL, dl, VT, X, 10595 DAG.getConstant(BitInX, dl, VT)); 10596 } 10597 10598 for (unsigned BitInY = 0, NumActiveBits = OrCI.getActiveBits(); 10599 BitInY < NumActiveBits; ++BitInY) { 10600 if (OrCI[BitInY] == 0) 10601 continue; 10602 APInt Mask(VT.getSizeInBits(), 0); 10603 Mask.setBit(BitInY); 10604 V = DAG.getNode(ARMISD::BFI, dl, VT, V, X, 10605 // Confusingly, the operand is an *inverted* mask. 10606 DAG.getConstant(~Mask, dl, VT)); 10607 } 10608 10609 return V; 10610 } 10611 10612 /// PerformCMOVCombine - Target-specific DAG combining for ARMISD::CMOV. 10613 SDValue 10614 ARMTargetLowering::PerformCMOVCombine(SDNode *N, SelectionDAG &DAG) const { 10615 SDValue Cmp = N->getOperand(4); 10616 if (Cmp.getOpcode() != ARMISD::CMPZ) 10617 // Only looking at EQ and NE cases. 10618 return SDValue(); 10619 10620 EVT VT = N->getValueType(0); 10621 SDLoc dl(N); 10622 SDValue LHS = Cmp.getOperand(0); 10623 SDValue RHS = Cmp.getOperand(1); 10624 SDValue FalseVal = N->getOperand(0); 10625 SDValue TrueVal = N->getOperand(1); 10626 SDValue ARMcc = N->getOperand(2); 10627 ARMCC::CondCodes CC = 10628 (ARMCC::CondCodes)cast<ConstantSDNode>(ARMcc)->getZExtValue(); 10629 10630 // BFI is only available on V6T2+. 10631 if (!Subtarget->isThumb1Only() && Subtarget->hasV6T2Ops()) { 10632 SDValue R = PerformCMOVToBFICombine(N, DAG); 10633 if (R) 10634 return R; 10635 } 10636 10637 // Simplify 10638 // mov r1, r0 10639 // cmp r1, x 10640 // mov r0, y 10641 // moveq r0, x 10642 // to 10643 // cmp r0, x 10644 // movne r0, y 10645 // 10646 // mov r1, r0 10647 // cmp r1, x 10648 // mov r0, x 10649 // movne r0, y 10650 // to 10651 // cmp r0, x 10652 // movne r0, y 10653 /// FIXME: Turn this into a target neutral optimization? 10654 SDValue Res; 10655 if (CC == ARMCC::NE && FalseVal == RHS && FalseVal != LHS) { 10656 Res = DAG.getNode(ARMISD::CMOV, dl, VT, LHS, TrueVal, ARMcc, 10657 N->getOperand(3), Cmp); 10658 } else if (CC == ARMCC::EQ && TrueVal == RHS) { 10659 SDValue ARMcc; 10660 SDValue NewCmp = getARMCmp(LHS, RHS, ISD::SETNE, ARMcc, DAG, dl); 10661 Res = DAG.getNode(ARMISD::CMOV, dl, VT, LHS, FalseVal, ARMcc, 10662 N->getOperand(3), NewCmp); 10663 } 10664 10665 if (Res.getNode()) { 10666 APInt KnownZero, KnownOne; 10667 DAG.computeKnownBits(SDValue(N,0), KnownZero, KnownOne); 10668 // Capture demanded bits information that would be otherwise lost. 10669 if (KnownZero == 0xfffffffe) 10670 Res = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Res, 10671 DAG.getValueType(MVT::i1)); 10672 else if (KnownZero == 0xffffff00) 10673 Res = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Res, 10674 DAG.getValueType(MVT::i8)); 10675 else if (KnownZero == 0xffff0000) 10676 Res = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Res, 10677 DAG.getValueType(MVT::i16)); 10678 } 10679 10680 return Res; 10681 } 10682 10683 SDValue ARMTargetLowering::PerformDAGCombine(SDNode *N, 10684 DAGCombinerInfo &DCI) const { 10685 switch (N->getOpcode()) { 10686 default: break; 10687 case ISD::ADDC: return PerformADDCCombine(N, DCI, Subtarget); 10688 case ISD::ADD: return PerformADDCombine(N, DCI, Subtarget); 10689 case ISD::SUB: return PerformSUBCombine(N, DCI); 10690 case ISD::MUL: return PerformMULCombine(N, DCI, Subtarget); 10691 case ISD::OR: return PerformORCombine(N, DCI, Subtarget); 10692 case ISD::XOR: return PerformXORCombine(N, DCI, Subtarget); 10693 case ISD::AND: return PerformANDCombine(N, DCI, Subtarget); 10694 case ARMISD::BFI: return PerformBFICombine(N, DCI); 10695 case ARMISD::VMOVRRD: return PerformVMOVRRDCombine(N, DCI, Subtarget); 10696 case ARMISD::VMOVDRR: return PerformVMOVDRRCombine(N, DCI.DAG); 10697 case ISD::STORE: return PerformSTORECombine(N, DCI); 10698 case ISD::BUILD_VECTOR: return PerformBUILD_VECTORCombine(N, DCI, Subtarget); 10699 case ISD::INSERT_VECTOR_ELT: return PerformInsertEltCombine(N, DCI); 10700 case ISD::VECTOR_SHUFFLE: return PerformVECTOR_SHUFFLECombine(N, DCI.DAG); 10701 case ARMISD::VDUPLANE: return PerformVDUPLANECombine(N, DCI); 10702 case ISD::FP_TO_SINT: 10703 case ISD::FP_TO_UINT: 10704 return PerformVCVTCombine(N, DCI.DAG, Subtarget); 10705 case ISD::FDIV: 10706 return PerformVDIVCombine(N, DCI.DAG, Subtarget); 10707 case ISD::INTRINSIC_WO_CHAIN: return PerformIntrinsicCombine(N, DCI.DAG); 10708 case ISD::SHL: 10709 case ISD::SRA: 10710 case ISD::SRL: return PerformShiftCombine(N, DCI.DAG, Subtarget); 10711 case ISD::SIGN_EXTEND: 10712 case ISD::ZERO_EXTEND: 10713 case ISD::ANY_EXTEND: return PerformExtendCombine(N, DCI.DAG, Subtarget); 10714 case ARMISD::CMOV: return PerformCMOVCombine(N, DCI.DAG); 10715 case ISD::LOAD: return PerformLOADCombine(N, DCI); 10716 case ARMISD::VLD2DUP: 10717 case ARMISD::VLD3DUP: 10718 case ARMISD::VLD4DUP: 10719 return PerformVLDCombine(N, DCI); 10720 case ARMISD::BUILD_VECTOR: 10721 return PerformARMBUILD_VECTORCombine(N, DCI); 10722 case ISD::INTRINSIC_VOID: 10723 case ISD::INTRINSIC_W_CHAIN: 10724 switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) { 10725 case Intrinsic::arm_neon_vld1: 10726 case Intrinsic::arm_neon_vld2: 10727 case Intrinsic::arm_neon_vld3: 10728 case Intrinsic::arm_neon_vld4: 10729 case Intrinsic::arm_neon_vld2lane: 10730 case Intrinsic::arm_neon_vld3lane: 10731 case Intrinsic::arm_neon_vld4lane: 10732 case Intrinsic::arm_neon_vst1: 10733 case Intrinsic::arm_neon_vst2: 10734 case Intrinsic::arm_neon_vst3: 10735 case Intrinsic::arm_neon_vst4: 10736 case Intrinsic::arm_neon_vst2lane: 10737 case Intrinsic::arm_neon_vst3lane: 10738 case Intrinsic::arm_neon_vst4lane: 10739 return PerformVLDCombine(N, DCI); 10740 default: break; 10741 } 10742 break; 10743 } 10744 return SDValue(); 10745 } 10746 10747 bool ARMTargetLowering::isDesirableToTransformToIntegerOp(unsigned Opc, 10748 EVT VT) const { 10749 return (VT == MVT::f32) && (Opc == ISD::LOAD || Opc == ISD::STORE); 10750 } 10751 10752 bool ARMTargetLowering::allowsMisalignedMemoryAccesses(EVT VT, 10753 unsigned, 10754 unsigned, 10755 bool *Fast) const { 10756 // The AllowsUnaliged flag models the SCTLR.A setting in ARM cpus 10757 bool AllowsUnaligned = Subtarget->allowsUnalignedMem(); 10758 10759 switch (VT.getSimpleVT().SimpleTy) { 10760 default: 10761 return false; 10762 case MVT::i8: 10763 case MVT::i16: 10764 case MVT::i32: { 10765 // Unaligned access can use (for example) LRDB, LRDH, LDR 10766 if (AllowsUnaligned) { 10767 if (Fast) 10768 *Fast = Subtarget->hasV7Ops(); 10769 return true; 10770 } 10771 return false; 10772 } 10773 case MVT::f64: 10774 case MVT::v2f64: { 10775 // For any little-endian targets with neon, we can support unaligned ld/st 10776 // of D and Q (e.g. {D0,D1}) registers by using vld1.i8/vst1.i8. 10777 // A big-endian target may also explicitly support unaligned accesses 10778 if (Subtarget->hasNEON() && (AllowsUnaligned || Subtarget->isLittle())) { 10779 if (Fast) 10780 *Fast = true; 10781 return true; 10782 } 10783 return false; 10784 } 10785 } 10786 } 10787 10788 static bool memOpAlign(unsigned DstAlign, unsigned SrcAlign, 10789 unsigned AlignCheck) { 10790 return ((SrcAlign == 0 || SrcAlign % AlignCheck == 0) && 10791 (DstAlign == 0 || DstAlign % AlignCheck == 0)); 10792 } 10793 10794 EVT ARMTargetLowering::getOptimalMemOpType(uint64_t Size, 10795 unsigned DstAlign, unsigned SrcAlign, 10796 bool IsMemset, bool ZeroMemset, 10797 bool MemcpyStrSrc, 10798 MachineFunction &MF) const { 10799 const Function *F = MF.getFunction(); 10800 10801 // See if we can use NEON instructions for this... 10802 if ((!IsMemset || ZeroMemset) && Subtarget->hasNEON() && 10803 !F->hasFnAttribute(Attribute::NoImplicitFloat)) { 10804 bool Fast; 10805 if (Size >= 16 && 10806 (memOpAlign(SrcAlign, DstAlign, 16) || 10807 (allowsMisalignedMemoryAccesses(MVT::v2f64, 0, 1, &Fast) && Fast))) { 10808 return MVT::v2f64; 10809 } else if (Size >= 8 && 10810 (memOpAlign(SrcAlign, DstAlign, 8) || 10811 (allowsMisalignedMemoryAccesses(MVT::f64, 0, 1, &Fast) && 10812 Fast))) { 10813 return MVT::f64; 10814 } 10815 } 10816 10817 // Lowering to i32/i16 if the size permits. 10818 if (Size >= 4) 10819 return MVT::i32; 10820 else if (Size >= 2) 10821 return MVT::i16; 10822 10823 // Let the target-independent logic figure it out. 10824 return MVT::Other; 10825 } 10826 10827 bool ARMTargetLowering::isZExtFree(SDValue Val, EVT VT2) const { 10828 if (Val.getOpcode() != ISD::LOAD) 10829 return false; 10830 10831 EVT VT1 = Val.getValueType(); 10832 if (!VT1.isSimple() || !VT1.isInteger() || 10833 !VT2.isSimple() || !VT2.isInteger()) 10834 return false; 10835 10836 switch (VT1.getSimpleVT().SimpleTy) { 10837 default: break; 10838 case MVT::i1: 10839 case MVT::i8: 10840 case MVT::i16: 10841 // 8-bit and 16-bit loads implicitly zero-extend to 32-bits. 10842 return true; 10843 } 10844 10845 return false; 10846 } 10847 10848 bool ARMTargetLowering::isVectorLoadExtDesirable(SDValue ExtVal) const { 10849 EVT VT = ExtVal.getValueType(); 10850 10851 if (!isTypeLegal(VT)) 10852 return false; 10853 10854 // Don't create a loadext if we can fold the extension into a wide/long 10855 // instruction. 10856 // If there's more than one user instruction, the loadext is desirable no 10857 // matter what. There can be two uses by the same instruction. 10858 if (ExtVal->use_empty() || 10859 !ExtVal->use_begin()->isOnlyUserOf(ExtVal.getNode())) 10860 return true; 10861 10862 SDNode *U = *ExtVal->use_begin(); 10863 if ((U->getOpcode() == ISD::ADD || U->getOpcode() == ISD::SUB || 10864 U->getOpcode() == ISD::SHL || U->getOpcode() == ARMISD::VSHL)) 10865 return false; 10866 10867 return true; 10868 } 10869 10870 bool ARMTargetLowering::allowTruncateForTailCall(Type *Ty1, Type *Ty2) const { 10871 if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy()) 10872 return false; 10873 10874 if (!isTypeLegal(EVT::getEVT(Ty1))) 10875 return false; 10876 10877 assert(Ty1->getPrimitiveSizeInBits() <= 64 && "i128 is probably not a noop"); 10878 10879 // Assuming the caller doesn't have a zeroext or signext return parameter, 10880 // truncation all the way down to i1 is valid. 10881 return true; 10882 } 10883 10884 10885 static bool isLegalT1AddressImmediate(int64_t V, EVT VT) { 10886 if (V < 0) 10887 return false; 10888 10889 unsigned Scale = 1; 10890 switch (VT.getSimpleVT().SimpleTy) { 10891 default: return false; 10892 case MVT::i1: 10893 case MVT::i8: 10894 // Scale == 1; 10895 break; 10896 case MVT::i16: 10897 // Scale == 2; 10898 Scale = 2; 10899 break; 10900 case MVT::i32: 10901 // Scale == 4; 10902 Scale = 4; 10903 break; 10904 } 10905 10906 if ((V & (Scale - 1)) != 0) 10907 return false; 10908 V /= Scale; 10909 return V == (V & ((1LL << 5) - 1)); 10910 } 10911 10912 static bool isLegalT2AddressImmediate(int64_t V, EVT VT, 10913 const ARMSubtarget *Subtarget) { 10914 bool isNeg = false; 10915 if (V < 0) { 10916 isNeg = true; 10917 V = - V; 10918 } 10919 10920 switch (VT.getSimpleVT().SimpleTy) { 10921 default: return false; 10922 case MVT::i1: 10923 case MVT::i8: 10924 case MVT::i16: 10925 case MVT::i32: 10926 // + imm12 or - imm8 10927 if (isNeg) 10928 return V == (V & ((1LL << 8) - 1)); 10929 return V == (V & ((1LL << 12) - 1)); 10930 case MVT::f32: 10931 case MVT::f64: 10932 // Same as ARM mode. FIXME: NEON? 10933 if (!Subtarget->hasVFP2()) 10934 return false; 10935 if ((V & 3) != 0) 10936 return false; 10937 V >>= 2; 10938 return V == (V & ((1LL << 8) - 1)); 10939 } 10940 } 10941 10942 /// isLegalAddressImmediate - Return true if the integer value can be used 10943 /// as the offset of the target addressing mode for load / store of the 10944 /// given type. 10945 static bool isLegalAddressImmediate(int64_t V, EVT VT, 10946 const ARMSubtarget *Subtarget) { 10947 if (V == 0) 10948 return true; 10949 10950 if (!VT.isSimple()) 10951 return false; 10952 10953 if (Subtarget->isThumb1Only()) 10954 return isLegalT1AddressImmediate(V, VT); 10955 else if (Subtarget->isThumb2()) 10956 return isLegalT2AddressImmediate(V, VT, Subtarget); 10957 10958 // ARM mode. 10959 if (V < 0) 10960 V = - V; 10961 switch (VT.getSimpleVT().SimpleTy) { 10962 default: return false; 10963 case MVT::i1: 10964 case MVT::i8: 10965 case MVT::i32: 10966 // +- imm12 10967 return V == (V & ((1LL << 12) - 1)); 10968 case MVT::i16: 10969 // +- imm8 10970 return V == (V & ((1LL << 8) - 1)); 10971 case MVT::f32: 10972 case MVT::f64: 10973 if (!Subtarget->hasVFP2()) // FIXME: NEON? 10974 return false; 10975 if ((V & 3) != 0) 10976 return false; 10977 V >>= 2; 10978 return V == (V & ((1LL << 8) - 1)); 10979 } 10980 } 10981 10982 bool ARMTargetLowering::isLegalT2ScaledAddressingMode(const AddrMode &AM, 10983 EVT VT) const { 10984 int Scale = AM.Scale; 10985 if (Scale < 0) 10986 return false; 10987 10988 switch (VT.getSimpleVT().SimpleTy) { 10989 default: return false; 10990 case MVT::i1: 10991 case MVT::i8: 10992 case MVT::i16: 10993 case MVT::i32: 10994 if (Scale == 1) 10995 return true; 10996 // r + r << imm 10997 Scale = Scale & ~1; 10998 return Scale == 2 || Scale == 4 || Scale == 8; 10999 case MVT::i64: 11000 // r + r 11001 if (((unsigned)AM.HasBaseReg + Scale) <= 2) 11002 return true; 11003 return false; 11004 case MVT::isVoid: 11005 // Note, we allow "void" uses (basically, uses that aren't loads or 11006 // stores), because arm allows folding a scale into many arithmetic 11007 // operations. This should be made more precise and revisited later. 11008 11009 // Allow r << imm, but the imm has to be a multiple of two. 11010 if (Scale & 1) return false; 11011 return isPowerOf2_32(Scale); 11012 } 11013 } 11014 11015 /// isLegalAddressingMode - Return true if the addressing mode represented 11016 /// by AM is legal for this target, for a load/store of the specified type. 11017 bool ARMTargetLowering::isLegalAddressingMode(const DataLayout &DL, 11018 const AddrMode &AM, Type *Ty, 11019 unsigned AS) const { 11020 EVT VT = getValueType(DL, Ty, true); 11021 if (!isLegalAddressImmediate(AM.BaseOffs, VT, Subtarget)) 11022 return false; 11023 11024 // Can never fold addr of global into load/store. 11025 if (AM.BaseGV) 11026 return false; 11027 11028 switch (AM.Scale) { 11029 case 0: // no scale reg, must be "r+i" or "r", or "i". 11030 break; 11031 case 1: 11032 if (Subtarget->isThumb1Only()) 11033 return false; 11034 // FALL THROUGH. 11035 default: 11036 // ARM doesn't support any R+R*scale+imm addr modes. 11037 if (AM.BaseOffs) 11038 return false; 11039 11040 if (!VT.isSimple()) 11041 return false; 11042 11043 if (Subtarget->isThumb2()) 11044 return isLegalT2ScaledAddressingMode(AM, VT); 11045 11046 int Scale = AM.Scale; 11047 switch (VT.getSimpleVT().SimpleTy) { 11048 default: return false; 11049 case MVT::i1: 11050 case MVT::i8: 11051 case MVT::i32: 11052 if (Scale < 0) Scale = -Scale; 11053 if (Scale == 1) 11054 return true; 11055 // r + r << imm 11056 return isPowerOf2_32(Scale & ~1); 11057 case MVT::i16: 11058 case MVT::i64: 11059 // r + r 11060 if (((unsigned)AM.HasBaseReg + Scale) <= 2) 11061 return true; 11062 return false; 11063 11064 case MVT::isVoid: 11065 // Note, we allow "void" uses (basically, uses that aren't loads or 11066 // stores), because arm allows folding a scale into many arithmetic 11067 // operations. This should be made more precise and revisited later. 11068 11069 // Allow r << imm, but the imm has to be a multiple of two. 11070 if (Scale & 1) return false; 11071 return isPowerOf2_32(Scale); 11072 } 11073 } 11074 return true; 11075 } 11076 11077 /// isLegalICmpImmediate - Return true if the specified immediate is legal 11078 /// icmp immediate, that is the target has icmp instructions which can compare 11079 /// a register against the immediate without having to materialize the 11080 /// immediate into a register. 11081 bool ARMTargetLowering::isLegalICmpImmediate(int64_t Imm) const { 11082 // Thumb2 and ARM modes can use cmn for negative immediates. 11083 if (!Subtarget->isThumb()) 11084 return ARM_AM::getSOImmVal(std::abs(Imm)) != -1; 11085 if (Subtarget->isThumb2()) 11086 return ARM_AM::getT2SOImmVal(std::abs(Imm)) != -1; 11087 // Thumb1 doesn't have cmn, and only 8-bit immediates. 11088 return Imm >= 0 && Imm <= 255; 11089 } 11090 11091 /// isLegalAddImmediate - Return true if the specified immediate is a legal add 11092 /// *or sub* immediate, that is the target has add or sub instructions which can 11093 /// add a register with the immediate without having to materialize the 11094 /// immediate into a register. 11095 bool ARMTargetLowering::isLegalAddImmediate(int64_t Imm) const { 11096 // Same encoding for add/sub, just flip the sign. 11097 int64_t AbsImm = std::abs(Imm); 11098 if (!Subtarget->isThumb()) 11099 return ARM_AM::getSOImmVal(AbsImm) != -1; 11100 if (Subtarget->isThumb2()) 11101 return ARM_AM::getT2SOImmVal(AbsImm) != -1; 11102 // Thumb1 only has 8-bit unsigned immediate. 11103 return AbsImm >= 0 && AbsImm <= 255; 11104 } 11105 11106 static bool getARMIndexedAddressParts(SDNode *Ptr, EVT VT, 11107 bool isSEXTLoad, SDValue &Base, 11108 SDValue &Offset, bool &isInc, 11109 SelectionDAG &DAG) { 11110 if (Ptr->getOpcode() != ISD::ADD && Ptr->getOpcode() != ISD::SUB) 11111 return false; 11112 11113 if (VT == MVT::i16 || ((VT == MVT::i8 || VT == MVT::i1) && isSEXTLoad)) { 11114 // AddressingMode 3 11115 Base = Ptr->getOperand(0); 11116 if (ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(Ptr->getOperand(1))) { 11117 int RHSC = (int)RHS->getZExtValue(); 11118 if (RHSC < 0 && RHSC > -256) { 11119 assert(Ptr->getOpcode() == ISD::ADD); 11120 isInc = false; 11121 Offset = DAG.getConstant(-RHSC, SDLoc(Ptr), RHS->getValueType(0)); 11122 return true; 11123 } 11124 } 11125 isInc = (Ptr->getOpcode() == ISD::ADD); 11126 Offset = Ptr->getOperand(1); 11127 return true; 11128 } else if (VT == MVT::i32 || VT == MVT::i8 || VT == MVT::i1) { 11129 // AddressingMode 2 11130 if (ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(Ptr->getOperand(1))) { 11131 int RHSC = (int)RHS->getZExtValue(); 11132 if (RHSC < 0 && RHSC > -0x1000) { 11133 assert(Ptr->getOpcode() == ISD::ADD); 11134 isInc = false; 11135 Offset = DAG.getConstant(-RHSC, SDLoc(Ptr), RHS->getValueType(0)); 11136 Base = Ptr->getOperand(0); 11137 return true; 11138 } 11139 } 11140 11141 if (Ptr->getOpcode() == ISD::ADD) { 11142 isInc = true; 11143 ARM_AM::ShiftOpc ShOpcVal= 11144 ARM_AM::getShiftOpcForNode(Ptr->getOperand(0).getOpcode()); 11145 if (ShOpcVal != ARM_AM::no_shift) { 11146 Base = Ptr->getOperand(1); 11147 Offset = Ptr->getOperand(0); 11148 } else { 11149 Base = Ptr->getOperand(0); 11150 Offset = Ptr->getOperand(1); 11151 } 11152 return true; 11153 } 11154 11155 isInc = (Ptr->getOpcode() == ISD::ADD); 11156 Base = Ptr->getOperand(0); 11157 Offset = Ptr->getOperand(1); 11158 return true; 11159 } 11160 11161 // FIXME: Use VLDM / VSTM to emulate indexed FP load / store. 11162 return false; 11163 } 11164 11165 static bool getT2IndexedAddressParts(SDNode *Ptr, EVT VT, 11166 bool isSEXTLoad, SDValue &Base, 11167 SDValue &Offset, bool &isInc, 11168 SelectionDAG &DAG) { 11169 if (Ptr->getOpcode() != ISD::ADD && Ptr->getOpcode() != ISD::SUB) 11170 return false; 11171 11172 Base = Ptr->getOperand(0); 11173 if (ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(Ptr->getOperand(1))) { 11174 int RHSC = (int)RHS->getZExtValue(); 11175 if (RHSC < 0 && RHSC > -0x100) { // 8 bits. 11176 assert(Ptr->getOpcode() == ISD::ADD); 11177 isInc = false; 11178 Offset = DAG.getConstant(-RHSC, SDLoc(Ptr), RHS->getValueType(0)); 11179 return true; 11180 } else if (RHSC > 0 && RHSC < 0x100) { // 8 bit, no zero. 11181 isInc = Ptr->getOpcode() == ISD::ADD; 11182 Offset = DAG.getConstant(RHSC, SDLoc(Ptr), RHS->getValueType(0)); 11183 return true; 11184 } 11185 } 11186 11187 return false; 11188 } 11189 11190 /// getPreIndexedAddressParts - returns true by value, base pointer and 11191 /// offset pointer and addressing mode by reference if the node's address 11192 /// can be legally represented as pre-indexed load / store address. 11193 bool 11194 ARMTargetLowering::getPreIndexedAddressParts(SDNode *N, SDValue &Base, 11195 SDValue &Offset, 11196 ISD::MemIndexedMode &AM, 11197 SelectionDAG &DAG) const { 11198 if (Subtarget->isThumb1Only()) 11199 return false; 11200 11201 EVT VT; 11202 SDValue Ptr; 11203 bool isSEXTLoad = false; 11204 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) { 11205 Ptr = LD->getBasePtr(); 11206 VT = LD->getMemoryVT(); 11207 isSEXTLoad = LD->getExtensionType() == ISD::SEXTLOAD; 11208 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) { 11209 Ptr = ST->getBasePtr(); 11210 VT = ST->getMemoryVT(); 11211 } else 11212 return false; 11213 11214 bool isInc; 11215 bool isLegal = false; 11216 if (Subtarget->isThumb2()) 11217 isLegal = getT2IndexedAddressParts(Ptr.getNode(), VT, isSEXTLoad, Base, 11218 Offset, isInc, DAG); 11219 else 11220 isLegal = getARMIndexedAddressParts(Ptr.getNode(), VT, isSEXTLoad, Base, 11221 Offset, isInc, DAG); 11222 if (!isLegal) 11223 return false; 11224 11225 AM = isInc ? ISD::PRE_INC : ISD::PRE_DEC; 11226 return true; 11227 } 11228 11229 /// getPostIndexedAddressParts - returns true by value, base pointer and 11230 /// offset pointer and addressing mode by reference if this node can be 11231 /// combined with a load / store to form a post-indexed load / store. 11232 bool ARMTargetLowering::getPostIndexedAddressParts(SDNode *N, SDNode *Op, 11233 SDValue &Base, 11234 SDValue &Offset, 11235 ISD::MemIndexedMode &AM, 11236 SelectionDAG &DAG) const { 11237 if (Subtarget->isThumb1Only()) 11238 return false; 11239 11240 EVT VT; 11241 SDValue Ptr; 11242 bool isSEXTLoad = false; 11243 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) { 11244 VT = LD->getMemoryVT(); 11245 Ptr = LD->getBasePtr(); 11246 isSEXTLoad = LD->getExtensionType() == ISD::SEXTLOAD; 11247 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) { 11248 VT = ST->getMemoryVT(); 11249 Ptr = ST->getBasePtr(); 11250 } else 11251 return false; 11252 11253 bool isInc; 11254 bool isLegal = false; 11255 if (Subtarget->isThumb2()) 11256 isLegal = getT2IndexedAddressParts(Op, VT, isSEXTLoad, Base, Offset, 11257 isInc, DAG); 11258 else 11259 isLegal = getARMIndexedAddressParts(Op, VT, isSEXTLoad, Base, Offset, 11260 isInc, DAG); 11261 if (!isLegal) 11262 return false; 11263 11264 if (Ptr != Base) { 11265 // Swap base ptr and offset to catch more post-index load / store when 11266 // it's legal. In Thumb2 mode, offset must be an immediate. 11267 if (Ptr == Offset && Op->getOpcode() == ISD::ADD && 11268 !Subtarget->isThumb2()) 11269 std::swap(Base, Offset); 11270 11271 // Post-indexed load / store update the base pointer. 11272 if (Ptr != Base) 11273 return false; 11274 } 11275 11276 AM = isInc ? ISD::POST_INC : ISD::POST_DEC; 11277 return true; 11278 } 11279 11280 void ARMTargetLowering::computeKnownBitsForTargetNode(const SDValue Op, 11281 APInt &KnownZero, 11282 APInt &KnownOne, 11283 const SelectionDAG &DAG, 11284 unsigned Depth) const { 11285 unsigned BitWidth = KnownOne.getBitWidth(); 11286 KnownZero = KnownOne = APInt(BitWidth, 0); 11287 switch (Op.getOpcode()) { 11288 default: break; 11289 case ARMISD::ADDC: 11290 case ARMISD::ADDE: 11291 case ARMISD::SUBC: 11292 case ARMISD::SUBE: 11293 // These nodes' second result is a boolean 11294 if (Op.getResNo() == 0) 11295 break; 11296 KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - 1); 11297 break; 11298 case ARMISD::CMOV: { 11299 // Bits are known zero/one if known on the LHS and RHS. 11300 DAG.computeKnownBits(Op.getOperand(0), KnownZero, KnownOne, Depth+1); 11301 if (KnownZero == 0 && KnownOne == 0) return; 11302 11303 APInt KnownZeroRHS, KnownOneRHS; 11304 DAG.computeKnownBits(Op.getOperand(1), KnownZeroRHS, KnownOneRHS, Depth+1); 11305 KnownZero &= KnownZeroRHS; 11306 KnownOne &= KnownOneRHS; 11307 return; 11308 } 11309 case ISD::INTRINSIC_W_CHAIN: { 11310 ConstantSDNode *CN = cast<ConstantSDNode>(Op->getOperand(1)); 11311 Intrinsic::ID IntID = static_cast<Intrinsic::ID>(CN->getZExtValue()); 11312 switch (IntID) { 11313 default: return; 11314 case Intrinsic::arm_ldaex: 11315 case Intrinsic::arm_ldrex: { 11316 EVT VT = cast<MemIntrinsicSDNode>(Op)->getMemoryVT(); 11317 unsigned MemBits = VT.getScalarType().getSizeInBits(); 11318 KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - MemBits); 11319 return; 11320 } 11321 } 11322 } 11323 } 11324 } 11325 11326 //===----------------------------------------------------------------------===// 11327 // ARM Inline Assembly Support 11328 //===----------------------------------------------------------------------===// 11329 11330 bool ARMTargetLowering::ExpandInlineAsm(CallInst *CI) const { 11331 // Looking for "rev" which is V6+. 11332 if (!Subtarget->hasV6Ops()) 11333 return false; 11334 11335 InlineAsm *IA = cast<InlineAsm>(CI->getCalledValue()); 11336 std::string AsmStr = IA->getAsmString(); 11337 SmallVector<StringRef, 4> AsmPieces; 11338 SplitString(AsmStr, AsmPieces, ";\n"); 11339 11340 switch (AsmPieces.size()) { 11341 default: return false; 11342 case 1: 11343 AsmStr = AsmPieces[0]; 11344 AsmPieces.clear(); 11345 SplitString(AsmStr, AsmPieces, " \t,"); 11346 11347 // rev $0, $1 11348 if (AsmPieces.size() == 3 && 11349 AsmPieces[0] == "rev" && AsmPieces[1] == "$0" && AsmPieces[2] == "$1" && 11350 IA->getConstraintString().compare(0, 4, "=l,l") == 0) { 11351 IntegerType *Ty = dyn_cast<IntegerType>(CI->getType()); 11352 if (Ty && Ty->getBitWidth() == 32) 11353 return IntrinsicLowering::LowerToByteSwap(CI); 11354 } 11355 break; 11356 } 11357 11358 return false; 11359 } 11360 11361 /// getConstraintType - Given a constraint letter, return the type of 11362 /// constraint it is for this target. 11363 ARMTargetLowering::ConstraintType 11364 ARMTargetLowering::getConstraintType(StringRef Constraint) const { 11365 if (Constraint.size() == 1) { 11366 switch (Constraint[0]) { 11367 default: break; 11368 case 'l': return C_RegisterClass; 11369 case 'w': return C_RegisterClass; 11370 case 'h': return C_RegisterClass; 11371 case 'x': return C_RegisterClass; 11372 case 't': return C_RegisterClass; 11373 case 'j': return C_Other; // Constant for movw. 11374 // An address with a single base register. Due to the way we 11375 // currently handle addresses it is the same as an 'r' memory constraint. 11376 case 'Q': return C_Memory; 11377 } 11378 } else if (Constraint.size() == 2) { 11379 switch (Constraint[0]) { 11380 default: break; 11381 // All 'U+' constraints are addresses. 11382 case 'U': return C_Memory; 11383 } 11384 } 11385 return TargetLowering::getConstraintType(Constraint); 11386 } 11387 11388 /// Examine constraint type and operand type and determine a weight value. 11389 /// This object must already have been set up with the operand type 11390 /// and the current alternative constraint selected. 11391 TargetLowering::ConstraintWeight 11392 ARMTargetLowering::getSingleConstraintMatchWeight( 11393 AsmOperandInfo &info, const char *constraint) const { 11394 ConstraintWeight weight = CW_Invalid; 11395 Value *CallOperandVal = info.CallOperandVal; 11396 // If we don't have a value, we can't do a match, 11397 // but allow it at the lowest weight. 11398 if (!CallOperandVal) 11399 return CW_Default; 11400 Type *type = CallOperandVal->getType(); 11401 // Look at the constraint type. 11402 switch (*constraint) { 11403 default: 11404 weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint); 11405 break; 11406 case 'l': 11407 if (type->isIntegerTy()) { 11408 if (Subtarget->isThumb()) 11409 weight = CW_SpecificReg; 11410 else 11411 weight = CW_Register; 11412 } 11413 break; 11414 case 'w': 11415 if (type->isFloatingPointTy()) 11416 weight = CW_Register; 11417 break; 11418 } 11419 return weight; 11420 } 11421 11422 typedef std::pair<unsigned, const TargetRegisterClass*> RCPair; 11423 RCPair ARMTargetLowering::getRegForInlineAsmConstraint( 11424 const TargetRegisterInfo *TRI, StringRef Constraint, MVT VT) const { 11425 if (Constraint.size() == 1) { 11426 // GCC ARM Constraint Letters 11427 switch (Constraint[0]) { 11428 case 'l': // Low regs or general regs. 11429 if (Subtarget->isThumb()) 11430 return RCPair(0U, &ARM::tGPRRegClass); 11431 return RCPair(0U, &ARM::GPRRegClass); 11432 case 'h': // High regs or no regs. 11433 if (Subtarget->isThumb()) 11434 return RCPair(0U, &ARM::hGPRRegClass); 11435 break; 11436 case 'r': 11437 if (Subtarget->isThumb1Only()) 11438 return RCPair(0U, &ARM::tGPRRegClass); 11439 return RCPair(0U, &ARM::GPRRegClass); 11440 case 'w': 11441 if (VT == MVT::Other) 11442 break; 11443 if (VT == MVT::f32) 11444 return RCPair(0U, &ARM::SPRRegClass); 11445 if (VT.getSizeInBits() == 64) 11446 return RCPair(0U, &ARM::DPRRegClass); 11447 if (VT.getSizeInBits() == 128) 11448 return RCPair(0U, &ARM::QPRRegClass); 11449 break; 11450 case 'x': 11451 if (VT == MVT::Other) 11452 break; 11453 if (VT == MVT::f32) 11454 return RCPair(0U, &ARM::SPR_8RegClass); 11455 if (VT.getSizeInBits() == 64) 11456 return RCPair(0U, &ARM::DPR_8RegClass); 11457 if (VT.getSizeInBits() == 128) 11458 return RCPair(0U, &ARM::QPR_8RegClass); 11459 break; 11460 case 't': 11461 if (VT == MVT::f32) 11462 return RCPair(0U, &ARM::SPRRegClass); 11463 break; 11464 } 11465 } 11466 if (StringRef("{cc}").equals_lower(Constraint)) 11467 return std::make_pair(unsigned(ARM::CPSR), &ARM::CCRRegClass); 11468 11469 return TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT); 11470 } 11471 11472 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops 11473 /// vector. If it is invalid, don't add anything to Ops. 11474 void ARMTargetLowering::LowerAsmOperandForConstraint(SDValue Op, 11475 std::string &Constraint, 11476 std::vector<SDValue>&Ops, 11477 SelectionDAG &DAG) const { 11478 SDValue Result; 11479 11480 // Currently only support length 1 constraints. 11481 if (Constraint.length() != 1) return; 11482 11483 char ConstraintLetter = Constraint[0]; 11484 switch (ConstraintLetter) { 11485 default: break; 11486 case 'j': 11487 case 'I': case 'J': case 'K': case 'L': 11488 case 'M': case 'N': case 'O': 11489 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op); 11490 if (!C) 11491 return; 11492 11493 int64_t CVal64 = C->getSExtValue(); 11494 int CVal = (int) CVal64; 11495 // None of these constraints allow values larger than 32 bits. Check 11496 // that the value fits in an int. 11497 if (CVal != CVal64) 11498 return; 11499 11500 switch (ConstraintLetter) { 11501 case 'j': 11502 // Constant suitable for movw, must be between 0 and 11503 // 65535. 11504 if (Subtarget->hasV6T2Ops()) 11505 if (CVal >= 0 && CVal <= 65535) 11506 break; 11507 return; 11508 case 'I': 11509 if (Subtarget->isThumb1Only()) { 11510 // This must be a constant between 0 and 255, for ADD 11511 // immediates. 11512 if (CVal >= 0 && CVal <= 255) 11513 break; 11514 } else if (Subtarget->isThumb2()) { 11515 // A constant that can be used as an immediate value in a 11516 // data-processing instruction. 11517 if (ARM_AM::getT2SOImmVal(CVal) != -1) 11518 break; 11519 } else { 11520 // A constant that can be used as an immediate value in a 11521 // data-processing instruction. 11522 if (ARM_AM::getSOImmVal(CVal) != -1) 11523 break; 11524 } 11525 return; 11526 11527 case 'J': 11528 if (Subtarget->isThumb1Only()) { 11529 // This must be a constant between -255 and -1, for negated ADD 11530 // immediates. This can be used in GCC with an "n" modifier that 11531 // prints the negated value, for use with SUB instructions. It is 11532 // not useful otherwise but is implemented for compatibility. 11533 if (CVal >= -255 && CVal <= -1) 11534 break; 11535 } else { 11536 // This must be a constant between -4095 and 4095. It is not clear 11537 // what this constraint is intended for. Implemented for 11538 // compatibility with GCC. 11539 if (CVal >= -4095 && CVal <= 4095) 11540 break; 11541 } 11542 return; 11543 11544 case 'K': 11545 if (Subtarget->isThumb1Only()) { 11546 // A 32-bit value where only one byte has a nonzero value. Exclude 11547 // zero to match GCC. This constraint is used by GCC internally for 11548 // constants that can be loaded with a move/shift combination. 11549 // It is not useful otherwise but is implemented for compatibility. 11550 if (CVal != 0 && ARM_AM::isThumbImmShiftedVal(CVal)) 11551 break; 11552 } else if (Subtarget->isThumb2()) { 11553 // A constant whose bitwise inverse can be used as an immediate 11554 // value in a data-processing instruction. This can be used in GCC 11555 // with a "B" modifier that prints the inverted value, for use with 11556 // BIC and MVN instructions. It is not useful otherwise but is 11557 // implemented for compatibility. 11558 if (ARM_AM::getT2SOImmVal(~CVal) != -1) 11559 break; 11560 } else { 11561 // A constant whose bitwise inverse can be used as an immediate 11562 // value in a data-processing instruction. This can be used in GCC 11563 // with a "B" modifier that prints the inverted value, for use with 11564 // BIC and MVN instructions. It is not useful otherwise but is 11565 // implemented for compatibility. 11566 if (ARM_AM::getSOImmVal(~CVal) != -1) 11567 break; 11568 } 11569 return; 11570 11571 case 'L': 11572 if (Subtarget->isThumb1Only()) { 11573 // This must be a constant between -7 and 7, 11574 // for 3-operand ADD/SUB immediate instructions. 11575 if (CVal >= -7 && CVal < 7) 11576 break; 11577 } else if (Subtarget->isThumb2()) { 11578 // A constant whose negation can be used as an immediate value in a 11579 // data-processing instruction. This can be used in GCC with an "n" 11580 // modifier that prints the negated value, for use with SUB 11581 // instructions. It is not useful otherwise but is implemented for 11582 // compatibility. 11583 if (ARM_AM::getT2SOImmVal(-CVal) != -1) 11584 break; 11585 } else { 11586 // A constant whose negation can be used as an immediate value in a 11587 // data-processing instruction. This can be used in GCC with an "n" 11588 // modifier that prints the negated value, for use with SUB 11589 // instructions. It is not useful otherwise but is implemented for 11590 // compatibility. 11591 if (ARM_AM::getSOImmVal(-CVal) != -1) 11592 break; 11593 } 11594 return; 11595 11596 case 'M': 11597 if (Subtarget->isThumb1Only()) { 11598 // This must be a multiple of 4 between 0 and 1020, for 11599 // ADD sp + immediate. 11600 if ((CVal >= 0 && CVal <= 1020) && ((CVal & 3) == 0)) 11601 break; 11602 } else { 11603 // A power of two or a constant between 0 and 32. This is used in 11604 // GCC for the shift amount on shifted register operands, but it is 11605 // useful in general for any shift amounts. 11606 if ((CVal >= 0 && CVal <= 32) || ((CVal & (CVal - 1)) == 0)) 11607 break; 11608 } 11609 return; 11610 11611 case 'N': 11612 if (Subtarget->isThumb()) { // FIXME thumb2 11613 // This must be a constant between 0 and 31, for shift amounts. 11614 if (CVal >= 0 && CVal <= 31) 11615 break; 11616 } 11617 return; 11618 11619 case 'O': 11620 if (Subtarget->isThumb()) { // FIXME thumb2 11621 // This must be a multiple of 4 between -508 and 508, for 11622 // ADD/SUB sp = sp + immediate. 11623 if ((CVal >= -508 && CVal <= 508) && ((CVal & 3) == 0)) 11624 break; 11625 } 11626 return; 11627 } 11628 Result = DAG.getTargetConstant(CVal, SDLoc(Op), Op.getValueType()); 11629 break; 11630 } 11631 11632 if (Result.getNode()) { 11633 Ops.push_back(Result); 11634 return; 11635 } 11636 return TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG); 11637 } 11638 11639 static RTLIB::Libcall getDivRemLibcall( 11640 const SDNode *N, MVT::SimpleValueType SVT) { 11641 assert((N->getOpcode() == ISD::SDIVREM || N->getOpcode() == ISD::UDIVREM || 11642 N->getOpcode() == ISD::SREM || N->getOpcode() == ISD::UREM) && 11643 "Unhandled Opcode in getDivRemLibcall"); 11644 bool isSigned = N->getOpcode() == ISD::SDIVREM || 11645 N->getOpcode() == ISD::SREM; 11646 RTLIB::Libcall LC; 11647 switch (SVT) { 11648 default: llvm_unreachable("Unexpected request for libcall!"); 11649 case MVT::i8: LC = isSigned ? RTLIB::SDIVREM_I8 : RTLIB::UDIVREM_I8; break; 11650 case MVT::i16: LC = isSigned ? RTLIB::SDIVREM_I16 : RTLIB::UDIVREM_I16; break; 11651 case MVT::i32: LC = isSigned ? RTLIB::SDIVREM_I32 : RTLIB::UDIVREM_I32; break; 11652 case MVT::i64: LC = isSigned ? RTLIB::SDIVREM_I64 : RTLIB::UDIVREM_I64; break; 11653 } 11654 return LC; 11655 } 11656 11657 static TargetLowering::ArgListTy getDivRemArgList( 11658 const SDNode *N, LLVMContext *Context) { 11659 assert((N->getOpcode() == ISD::SDIVREM || N->getOpcode() == ISD::UDIVREM || 11660 N->getOpcode() == ISD::SREM || N->getOpcode() == ISD::UREM) && 11661 "Unhandled Opcode in getDivRemArgList"); 11662 bool isSigned = N->getOpcode() == ISD::SDIVREM || 11663 N->getOpcode() == ISD::SREM; 11664 TargetLowering::ArgListTy Args; 11665 TargetLowering::ArgListEntry Entry; 11666 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) { 11667 EVT ArgVT = N->getOperand(i).getValueType(); 11668 Type *ArgTy = ArgVT.getTypeForEVT(*Context); 11669 Entry.Node = N->getOperand(i); 11670 Entry.Ty = ArgTy; 11671 Entry.isSExt = isSigned; 11672 Entry.isZExt = !isSigned; 11673 Args.push_back(Entry); 11674 } 11675 return Args; 11676 } 11677 11678 SDValue ARMTargetLowering::LowerDivRem(SDValue Op, SelectionDAG &DAG) const { 11679 assert((Subtarget->isTargetAEABI() || Subtarget->isTargetAndroid() || 11680 Subtarget->isTargetGNUAEABI()) && 11681 "Register-based DivRem lowering only"); 11682 unsigned Opcode = Op->getOpcode(); 11683 assert((Opcode == ISD::SDIVREM || Opcode == ISD::UDIVREM) && 11684 "Invalid opcode for Div/Rem lowering"); 11685 bool isSigned = (Opcode == ISD::SDIVREM); 11686 EVT VT = Op->getValueType(0); 11687 Type *Ty = VT.getTypeForEVT(*DAG.getContext()); 11688 11689 RTLIB::Libcall LC = getDivRemLibcall(Op.getNode(), 11690 VT.getSimpleVT().SimpleTy); 11691 SDValue InChain = DAG.getEntryNode(); 11692 11693 TargetLowering::ArgListTy Args = getDivRemArgList(Op.getNode(), 11694 DAG.getContext()); 11695 11696 SDValue Callee = DAG.getExternalSymbol(getLibcallName(LC), 11697 getPointerTy(DAG.getDataLayout())); 11698 11699 Type *RetTy = (Type*)StructType::get(Ty, Ty, nullptr); 11700 11701 SDLoc dl(Op); 11702 TargetLowering::CallLoweringInfo CLI(DAG); 11703 CLI.setDebugLoc(dl).setChain(InChain) 11704 .setCallee(getLibcallCallingConv(LC), RetTy, Callee, std::move(Args), 0) 11705 .setInRegister().setSExtResult(isSigned).setZExtResult(!isSigned); 11706 11707 std::pair<SDValue, SDValue> CallInfo = LowerCallTo(CLI); 11708 return CallInfo.first; 11709 } 11710 11711 // Lowers REM using divmod helpers 11712 // see RTABI section 4.2/4.3 11713 SDValue ARMTargetLowering::LowerREM(SDNode *N, SelectionDAG &DAG) const { 11714 // Build return types (div and rem) 11715 std::vector<Type*> RetTyParams; 11716 Type *RetTyElement; 11717 11718 switch (N->getValueType(0).getSimpleVT().SimpleTy) { 11719 default: llvm_unreachable("Unexpected request for libcall!"); 11720 case MVT::i8: RetTyElement = Type::getInt8Ty(*DAG.getContext()); break; 11721 case MVT::i16: RetTyElement = Type::getInt16Ty(*DAG.getContext()); break; 11722 case MVT::i32: RetTyElement = Type::getInt32Ty(*DAG.getContext()); break; 11723 case MVT::i64: RetTyElement = Type::getInt64Ty(*DAG.getContext()); break; 11724 } 11725 11726 RetTyParams.push_back(RetTyElement); 11727 RetTyParams.push_back(RetTyElement); 11728 ArrayRef<Type*> ret = ArrayRef<Type*>(RetTyParams); 11729 Type *RetTy = StructType::get(*DAG.getContext(), ret); 11730 11731 RTLIB::Libcall LC = getDivRemLibcall(N, N->getValueType(0).getSimpleVT(). 11732 SimpleTy); 11733 SDValue InChain = DAG.getEntryNode(); 11734 TargetLowering::ArgListTy Args = getDivRemArgList(N, DAG.getContext()); 11735 bool isSigned = N->getOpcode() == ISD::SREM; 11736 SDValue Callee = DAG.getExternalSymbol(getLibcallName(LC), 11737 getPointerTy(DAG.getDataLayout())); 11738 11739 // Lower call 11740 CallLoweringInfo CLI(DAG); 11741 CLI.setChain(InChain) 11742 .setCallee(CallingConv::ARM_AAPCS, RetTy, Callee, std::move(Args), 0) 11743 .setSExtResult(isSigned).setZExtResult(!isSigned).setDebugLoc(SDLoc(N)); 11744 std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI); 11745 11746 // Return second (rem) result operand (first contains div) 11747 SDNode *ResNode = CallResult.first.getNode(); 11748 assert(ResNode->getNumOperands() == 2 && "divmod should return two operands"); 11749 return ResNode->getOperand(1); 11750 } 11751 11752 SDValue 11753 ARMTargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op, SelectionDAG &DAG) const { 11754 assert(Subtarget->isTargetWindows() && "unsupported target platform"); 11755 SDLoc DL(Op); 11756 11757 // Get the inputs. 11758 SDValue Chain = Op.getOperand(0); 11759 SDValue Size = Op.getOperand(1); 11760 11761 SDValue Words = DAG.getNode(ISD::SRL, DL, MVT::i32, Size, 11762 DAG.getConstant(2, DL, MVT::i32)); 11763 11764 SDValue Flag; 11765 Chain = DAG.getCopyToReg(Chain, DL, ARM::R4, Words, Flag); 11766 Flag = Chain.getValue(1); 11767 11768 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue); 11769 Chain = DAG.getNode(ARMISD::WIN__CHKSTK, DL, NodeTys, Chain, Flag); 11770 11771 SDValue NewSP = DAG.getCopyFromReg(Chain, DL, ARM::SP, MVT::i32); 11772 Chain = NewSP.getValue(1); 11773 11774 SDValue Ops[2] = { NewSP, Chain }; 11775 return DAG.getMergeValues(Ops, DL); 11776 } 11777 11778 SDValue ARMTargetLowering::LowerFP_EXTEND(SDValue Op, SelectionDAG &DAG) const { 11779 assert(Op.getValueType() == MVT::f64 && Subtarget->isFPOnlySP() && 11780 "Unexpected type for custom-lowering FP_EXTEND"); 11781 11782 RTLIB::Libcall LC; 11783 LC = RTLIB::getFPEXT(Op.getOperand(0).getValueType(), Op.getValueType()); 11784 11785 SDValue SrcVal = Op.getOperand(0); 11786 return makeLibCall(DAG, LC, Op.getValueType(), SrcVal, /*isSigned*/ false, 11787 SDLoc(Op)).first; 11788 } 11789 11790 SDValue ARMTargetLowering::LowerFP_ROUND(SDValue Op, SelectionDAG &DAG) const { 11791 assert(Op.getOperand(0).getValueType() == MVT::f64 && 11792 Subtarget->isFPOnlySP() && 11793 "Unexpected type for custom-lowering FP_ROUND"); 11794 11795 RTLIB::Libcall LC; 11796 LC = RTLIB::getFPROUND(Op.getOperand(0).getValueType(), Op.getValueType()); 11797 11798 SDValue SrcVal = Op.getOperand(0); 11799 return makeLibCall(DAG, LC, Op.getValueType(), SrcVal, /*isSigned*/ false, 11800 SDLoc(Op)).first; 11801 } 11802 11803 bool 11804 ARMTargetLowering::isOffsetFoldingLegal(const GlobalAddressSDNode *GA) const { 11805 // The ARM target isn't yet aware of offsets. 11806 return false; 11807 } 11808 11809 bool ARM::isBitFieldInvertedMask(unsigned v) { 11810 if (v == 0xffffffff) 11811 return false; 11812 11813 // there can be 1's on either or both "outsides", all the "inside" 11814 // bits must be 0's 11815 return isShiftedMask_32(~v); 11816 } 11817 11818 /// isFPImmLegal - Returns true if the target can instruction select the 11819 /// specified FP immediate natively. If false, the legalizer will 11820 /// materialize the FP immediate as a load from a constant pool. 11821 bool ARMTargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT) const { 11822 if (!Subtarget->hasVFP3()) 11823 return false; 11824 if (VT == MVT::f32) 11825 return ARM_AM::getFP32Imm(Imm) != -1; 11826 if (VT == MVT::f64 && !Subtarget->isFPOnlySP()) 11827 return ARM_AM::getFP64Imm(Imm) != -1; 11828 return false; 11829 } 11830 11831 /// getTgtMemIntrinsic - Represent NEON load and store intrinsics as 11832 /// MemIntrinsicNodes. The associated MachineMemOperands record the alignment 11833 /// specified in the intrinsic calls. 11834 bool ARMTargetLowering::getTgtMemIntrinsic(IntrinsicInfo &Info, 11835 const CallInst &I, 11836 unsigned Intrinsic) const { 11837 switch (Intrinsic) { 11838 case Intrinsic::arm_neon_vld1: 11839 case Intrinsic::arm_neon_vld2: 11840 case Intrinsic::arm_neon_vld3: 11841 case Intrinsic::arm_neon_vld4: 11842 case Intrinsic::arm_neon_vld2lane: 11843 case Intrinsic::arm_neon_vld3lane: 11844 case Intrinsic::arm_neon_vld4lane: { 11845 Info.opc = ISD::INTRINSIC_W_CHAIN; 11846 // Conservatively set memVT to the entire set of vectors loaded. 11847 auto &DL = I.getCalledFunction()->getParent()->getDataLayout(); 11848 uint64_t NumElts = DL.getTypeSizeInBits(I.getType()) / 64; 11849 Info.memVT = EVT::getVectorVT(I.getType()->getContext(), MVT::i64, NumElts); 11850 Info.ptrVal = I.getArgOperand(0); 11851 Info.offset = 0; 11852 Value *AlignArg = I.getArgOperand(I.getNumArgOperands() - 1); 11853 Info.align = cast<ConstantInt>(AlignArg)->getZExtValue(); 11854 Info.vol = false; // volatile loads with NEON intrinsics not supported 11855 Info.readMem = true; 11856 Info.writeMem = false; 11857 return true; 11858 } 11859 case Intrinsic::arm_neon_vst1: 11860 case Intrinsic::arm_neon_vst2: 11861 case Intrinsic::arm_neon_vst3: 11862 case Intrinsic::arm_neon_vst4: 11863 case Intrinsic::arm_neon_vst2lane: 11864 case Intrinsic::arm_neon_vst3lane: 11865 case Intrinsic::arm_neon_vst4lane: { 11866 Info.opc = ISD::INTRINSIC_VOID; 11867 // Conservatively set memVT to the entire set of vectors stored. 11868 auto &DL = I.getCalledFunction()->getParent()->getDataLayout(); 11869 unsigned NumElts = 0; 11870 for (unsigned ArgI = 1, ArgE = I.getNumArgOperands(); ArgI < ArgE; ++ArgI) { 11871 Type *ArgTy = I.getArgOperand(ArgI)->getType(); 11872 if (!ArgTy->isVectorTy()) 11873 break; 11874 NumElts += DL.getTypeSizeInBits(ArgTy) / 64; 11875 } 11876 Info.memVT = EVT::getVectorVT(I.getType()->getContext(), MVT::i64, NumElts); 11877 Info.ptrVal = I.getArgOperand(0); 11878 Info.offset = 0; 11879 Value *AlignArg = I.getArgOperand(I.getNumArgOperands() - 1); 11880 Info.align = cast<ConstantInt>(AlignArg)->getZExtValue(); 11881 Info.vol = false; // volatile stores with NEON intrinsics not supported 11882 Info.readMem = false; 11883 Info.writeMem = true; 11884 return true; 11885 } 11886 case Intrinsic::arm_ldaex: 11887 case Intrinsic::arm_ldrex: { 11888 auto &DL = I.getCalledFunction()->getParent()->getDataLayout(); 11889 PointerType *PtrTy = cast<PointerType>(I.getArgOperand(0)->getType()); 11890 Info.opc = ISD::INTRINSIC_W_CHAIN; 11891 Info.memVT = MVT::getVT(PtrTy->getElementType()); 11892 Info.ptrVal = I.getArgOperand(0); 11893 Info.offset = 0; 11894 Info.align = DL.getABITypeAlignment(PtrTy->getElementType()); 11895 Info.vol = true; 11896 Info.readMem = true; 11897 Info.writeMem = false; 11898 return true; 11899 } 11900 case Intrinsic::arm_stlex: 11901 case Intrinsic::arm_strex: { 11902 auto &DL = I.getCalledFunction()->getParent()->getDataLayout(); 11903 PointerType *PtrTy = cast<PointerType>(I.getArgOperand(1)->getType()); 11904 Info.opc = ISD::INTRINSIC_W_CHAIN; 11905 Info.memVT = MVT::getVT(PtrTy->getElementType()); 11906 Info.ptrVal = I.getArgOperand(1); 11907 Info.offset = 0; 11908 Info.align = DL.getABITypeAlignment(PtrTy->getElementType()); 11909 Info.vol = true; 11910 Info.readMem = false; 11911 Info.writeMem = true; 11912 return true; 11913 } 11914 case Intrinsic::arm_stlexd: 11915 case Intrinsic::arm_strexd: { 11916 Info.opc = ISD::INTRINSIC_W_CHAIN; 11917 Info.memVT = MVT::i64; 11918 Info.ptrVal = I.getArgOperand(2); 11919 Info.offset = 0; 11920 Info.align = 8; 11921 Info.vol = true; 11922 Info.readMem = false; 11923 Info.writeMem = true; 11924 return true; 11925 } 11926 case Intrinsic::arm_ldaexd: 11927 case Intrinsic::arm_ldrexd: { 11928 Info.opc = ISD::INTRINSIC_W_CHAIN; 11929 Info.memVT = MVT::i64; 11930 Info.ptrVal = I.getArgOperand(0); 11931 Info.offset = 0; 11932 Info.align = 8; 11933 Info.vol = true; 11934 Info.readMem = true; 11935 Info.writeMem = false; 11936 return true; 11937 } 11938 default: 11939 break; 11940 } 11941 11942 return false; 11943 } 11944 11945 /// \brief Returns true if it is beneficial to convert a load of a constant 11946 /// to just the constant itself. 11947 bool ARMTargetLowering::shouldConvertConstantLoadToIntImm(const APInt &Imm, 11948 Type *Ty) const { 11949 assert(Ty->isIntegerTy()); 11950 11951 unsigned Bits = Ty->getPrimitiveSizeInBits(); 11952 if (Bits == 0 || Bits > 32) 11953 return false; 11954 return true; 11955 } 11956 11957 Instruction* ARMTargetLowering::makeDMB(IRBuilder<> &Builder, 11958 ARM_MB::MemBOpt Domain) const { 11959 Module *M = Builder.GetInsertBlock()->getParent()->getParent(); 11960 11961 // First, if the target has no DMB, see what fallback we can use. 11962 if (!Subtarget->hasDataBarrier()) { 11963 // Some ARMv6 cpus can support data barriers with an mcr instruction. 11964 // Thumb1 and pre-v6 ARM mode use a libcall instead and should never get 11965 // here. 11966 if (Subtarget->hasV6Ops() && !Subtarget->isThumb()) { 11967 Function *MCR = llvm::Intrinsic::getDeclaration(M, Intrinsic::arm_mcr); 11968 Value* args[6] = {Builder.getInt32(15), Builder.getInt32(0), 11969 Builder.getInt32(0), Builder.getInt32(7), 11970 Builder.getInt32(10), Builder.getInt32(5)}; 11971 return Builder.CreateCall(MCR, args); 11972 } else { 11973 // Instead of using barriers, atomic accesses on these subtargets use 11974 // libcalls. 11975 llvm_unreachable("makeDMB on a target so old that it has no barriers"); 11976 } 11977 } else { 11978 Function *DMB = llvm::Intrinsic::getDeclaration(M, Intrinsic::arm_dmb); 11979 // Only a full system barrier exists in the M-class architectures. 11980 Domain = Subtarget->isMClass() ? ARM_MB::SY : Domain; 11981 Constant *CDomain = Builder.getInt32(Domain); 11982 return Builder.CreateCall(DMB, CDomain); 11983 } 11984 } 11985 11986 // Based on http://www.cl.cam.ac.uk/~pes20/cpp/cpp0xmappings.html 11987 Instruction* ARMTargetLowering::emitLeadingFence(IRBuilder<> &Builder, 11988 AtomicOrdering Ord, bool IsStore, 11989 bool IsLoad) const { 11990 if (!getInsertFencesForAtomic()) 11991 return nullptr; 11992 11993 switch (Ord) { 11994 case NotAtomic: 11995 case Unordered: 11996 llvm_unreachable("Invalid fence: unordered/non-atomic"); 11997 case Monotonic: 11998 case Acquire: 11999 return nullptr; // Nothing to do 12000 case SequentiallyConsistent: 12001 if (!IsStore) 12002 return nullptr; // Nothing to do 12003 /*FALLTHROUGH*/ 12004 case Release: 12005 case AcquireRelease: 12006 if (Subtarget->isSwift()) 12007 return makeDMB(Builder, ARM_MB::ISHST); 12008 // FIXME: add a comment with a link to documentation justifying this. 12009 else 12010 return makeDMB(Builder, ARM_MB::ISH); 12011 } 12012 llvm_unreachable("Unknown fence ordering in emitLeadingFence"); 12013 } 12014 12015 Instruction* ARMTargetLowering::emitTrailingFence(IRBuilder<> &Builder, 12016 AtomicOrdering Ord, bool IsStore, 12017 bool IsLoad) const { 12018 if (!getInsertFencesForAtomic()) 12019 return nullptr; 12020 12021 switch (Ord) { 12022 case NotAtomic: 12023 case Unordered: 12024 llvm_unreachable("Invalid fence: unordered/not-atomic"); 12025 case Monotonic: 12026 case Release: 12027 return nullptr; // Nothing to do 12028 case Acquire: 12029 case AcquireRelease: 12030 case SequentiallyConsistent: 12031 return makeDMB(Builder, ARM_MB::ISH); 12032 } 12033 llvm_unreachable("Unknown fence ordering in emitTrailingFence"); 12034 } 12035 12036 // Loads and stores less than 64-bits are already atomic; ones above that 12037 // are doomed anyway, so defer to the default libcall and blame the OS when 12038 // things go wrong. Cortex M doesn't have ldrexd/strexd though, so don't emit 12039 // anything for those. 12040 bool ARMTargetLowering::shouldExpandAtomicStoreInIR(StoreInst *SI) const { 12041 unsigned Size = SI->getValueOperand()->getType()->getPrimitiveSizeInBits(); 12042 return (Size == 64) && !Subtarget->isMClass(); 12043 } 12044 12045 // Loads and stores less than 64-bits are already atomic; ones above that 12046 // are doomed anyway, so defer to the default libcall and blame the OS when 12047 // things go wrong. Cortex M doesn't have ldrexd/strexd though, so don't emit 12048 // anything for those. 12049 // FIXME: ldrd and strd are atomic if the CPU has LPAE (e.g. A15 has that 12050 // guarantee, see DDI0406C ARM architecture reference manual, 12051 // sections A8.8.72-74 LDRD) 12052 TargetLowering::AtomicExpansionKind 12053 ARMTargetLowering::shouldExpandAtomicLoadInIR(LoadInst *LI) const { 12054 unsigned Size = LI->getType()->getPrimitiveSizeInBits(); 12055 return ((Size == 64) && !Subtarget->isMClass()) ? AtomicExpansionKind::LLOnly 12056 : AtomicExpansionKind::None; 12057 } 12058 12059 // For the real atomic operations, we have ldrex/strex up to 32 bits, 12060 // and up to 64 bits on the non-M profiles 12061 TargetLowering::AtomicExpansionKind 12062 ARMTargetLowering::shouldExpandAtomicRMWInIR(AtomicRMWInst *AI) const { 12063 unsigned Size = AI->getType()->getPrimitiveSizeInBits(); 12064 return (Size <= (Subtarget->isMClass() ? 32U : 64U)) 12065 ? AtomicExpansionKind::LLSC 12066 : AtomicExpansionKind::None; 12067 } 12068 12069 bool ARMTargetLowering::shouldExpandAtomicCmpXchgInIR( 12070 AtomicCmpXchgInst *AI) const { 12071 return true; 12072 } 12073 12074 // This has so far only been implemented for MachO. 12075 bool ARMTargetLowering::useLoadStackGuardNode() const { 12076 return Subtarget->isTargetMachO(); 12077 } 12078 12079 bool ARMTargetLowering::canCombineStoreAndExtract(Type *VectorTy, Value *Idx, 12080 unsigned &Cost) const { 12081 // If we do not have NEON, vector types are not natively supported. 12082 if (!Subtarget->hasNEON()) 12083 return false; 12084 12085 // Floating point values and vector values map to the same register file. 12086 // Therefore, although we could do a store extract of a vector type, this is 12087 // better to leave at float as we have more freedom in the addressing mode for 12088 // those. 12089 if (VectorTy->isFPOrFPVectorTy()) 12090 return false; 12091 12092 // If the index is unknown at compile time, this is very expensive to lower 12093 // and it is not possible to combine the store with the extract. 12094 if (!isa<ConstantInt>(Idx)) 12095 return false; 12096 12097 assert(VectorTy->isVectorTy() && "VectorTy is not a vector type"); 12098 unsigned BitWidth = cast<VectorType>(VectorTy)->getBitWidth(); 12099 // We can do a store + vector extract on any vector that fits perfectly in a D 12100 // or Q register. 12101 if (BitWidth == 64 || BitWidth == 128) { 12102 Cost = 0; 12103 return true; 12104 } 12105 return false; 12106 } 12107 12108 bool ARMTargetLowering::isCheapToSpeculateCttz() const { 12109 return Subtarget->hasV6T2Ops(); 12110 } 12111 12112 bool ARMTargetLowering::isCheapToSpeculateCtlz() const { 12113 return Subtarget->hasV6T2Ops(); 12114 } 12115 12116 Value *ARMTargetLowering::emitLoadLinked(IRBuilder<> &Builder, Value *Addr, 12117 AtomicOrdering Ord) const { 12118 Module *M = Builder.GetInsertBlock()->getParent()->getParent(); 12119 Type *ValTy = cast<PointerType>(Addr->getType())->getElementType(); 12120 bool IsAcquire = isAtLeastAcquire(Ord); 12121 12122 // Since i64 isn't legal and intrinsics don't get type-lowered, the ldrexd 12123 // intrinsic must return {i32, i32} and we have to recombine them into a 12124 // single i64 here. 12125 if (ValTy->getPrimitiveSizeInBits() == 64) { 12126 Intrinsic::ID Int = 12127 IsAcquire ? Intrinsic::arm_ldaexd : Intrinsic::arm_ldrexd; 12128 Function *Ldrex = llvm::Intrinsic::getDeclaration(M, Int); 12129 12130 Addr = Builder.CreateBitCast(Addr, Type::getInt8PtrTy(M->getContext())); 12131 Value *LoHi = Builder.CreateCall(Ldrex, Addr, "lohi"); 12132 12133 Value *Lo = Builder.CreateExtractValue(LoHi, 0, "lo"); 12134 Value *Hi = Builder.CreateExtractValue(LoHi, 1, "hi"); 12135 if (!Subtarget->isLittle()) 12136 std::swap (Lo, Hi); 12137 Lo = Builder.CreateZExt(Lo, ValTy, "lo64"); 12138 Hi = Builder.CreateZExt(Hi, ValTy, "hi64"); 12139 return Builder.CreateOr( 12140 Lo, Builder.CreateShl(Hi, ConstantInt::get(ValTy, 32)), "val64"); 12141 } 12142 12143 Type *Tys[] = { Addr->getType() }; 12144 Intrinsic::ID Int = IsAcquire ? Intrinsic::arm_ldaex : Intrinsic::arm_ldrex; 12145 Function *Ldrex = llvm::Intrinsic::getDeclaration(M, Int, Tys); 12146 12147 return Builder.CreateTruncOrBitCast( 12148 Builder.CreateCall(Ldrex, Addr), 12149 cast<PointerType>(Addr->getType())->getElementType()); 12150 } 12151 12152 void ARMTargetLowering::emitAtomicCmpXchgNoStoreLLBalance( 12153 IRBuilder<> &Builder) const { 12154 if (!Subtarget->hasV7Ops()) 12155 return; 12156 Module *M = Builder.GetInsertBlock()->getParent()->getParent(); 12157 Builder.CreateCall(llvm::Intrinsic::getDeclaration(M, Intrinsic::arm_clrex)); 12158 } 12159 12160 Value *ARMTargetLowering::emitStoreConditional(IRBuilder<> &Builder, Value *Val, 12161 Value *Addr, 12162 AtomicOrdering Ord) const { 12163 Module *M = Builder.GetInsertBlock()->getParent()->getParent(); 12164 bool IsRelease = isAtLeastRelease(Ord); 12165 12166 // Since the intrinsics must have legal type, the i64 intrinsics take two 12167 // parameters: "i32, i32". We must marshal Val into the appropriate form 12168 // before the call. 12169 if (Val->getType()->getPrimitiveSizeInBits() == 64) { 12170 Intrinsic::ID Int = 12171 IsRelease ? Intrinsic::arm_stlexd : Intrinsic::arm_strexd; 12172 Function *Strex = Intrinsic::getDeclaration(M, Int); 12173 Type *Int32Ty = Type::getInt32Ty(M->getContext()); 12174 12175 Value *Lo = Builder.CreateTrunc(Val, Int32Ty, "lo"); 12176 Value *Hi = Builder.CreateTrunc(Builder.CreateLShr(Val, 32), Int32Ty, "hi"); 12177 if (!Subtarget->isLittle()) 12178 std::swap (Lo, Hi); 12179 Addr = Builder.CreateBitCast(Addr, Type::getInt8PtrTy(M->getContext())); 12180 return Builder.CreateCall(Strex, {Lo, Hi, Addr}); 12181 } 12182 12183 Intrinsic::ID Int = IsRelease ? Intrinsic::arm_stlex : Intrinsic::arm_strex; 12184 Type *Tys[] = { Addr->getType() }; 12185 Function *Strex = Intrinsic::getDeclaration(M, Int, Tys); 12186 12187 return Builder.CreateCall( 12188 Strex, {Builder.CreateZExtOrBitCast( 12189 Val, Strex->getFunctionType()->getParamType(0)), 12190 Addr}); 12191 } 12192 12193 /// \brief Lower an interleaved load into a vldN intrinsic. 12194 /// 12195 /// E.g. Lower an interleaved load (Factor = 2): 12196 /// %wide.vec = load <8 x i32>, <8 x i32>* %ptr, align 4 12197 /// %v0 = shuffle %wide.vec, undef, <0, 2, 4, 6> ; Extract even elements 12198 /// %v1 = shuffle %wide.vec, undef, <1, 3, 5, 7> ; Extract odd elements 12199 /// 12200 /// Into: 12201 /// %vld2 = { <4 x i32>, <4 x i32> } call llvm.arm.neon.vld2(%ptr, 4) 12202 /// %vec0 = extractelement { <4 x i32>, <4 x i32> } %vld2, i32 0 12203 /// %vec1 = extractelement { <4 x i32>, <4 x i32> } %vld2, i32 1 12204 bool ARMTargetLowering::lowerInterleavedLoad( 12205 LoadInst *LI, ArrayRef<ShuffleVectorInst *> Shuffles, 12206 ArrayRef<unsigned> Indices, unsigned Factor) const { 12207 assert(Factor >= 2 && Factor <= getMaxSupportedInterleaveFactor() && 12208 "Invalid interleave factor"); 12209 assert(!Shuffles.empty() && "Empty shufflevector input"); 12210 assert(Shuffles.size() == Indices.size() && 12211 "Unmatched number of shufflevectors and indices"); 12212 12213 VectorType *VecTy = Shuffles[0]->getType(); 12214 Type *EltTy = VecTy->getVectorElementType(); 12215 12216 const DataLayout &DL = LI->getModule()->getDataLayout(); 12217 unsigned VecSize = DL.getTypeSizeInBits(VecTy); 12218 bool EltIs64Bits = DL.getTypeSizeInBits(EltTy) == 64; 12219 12220 // Skip if we do not have NEON and skip illegal vector types and vector types 12221 // with i64/f64 elements (vldN doesn't support i64/f64 elements). 12222 if (!Subtarget->hasNEON() || (VecSize != 64 && VecSize != 128) || EltIs64Bits) 12223 return false; 12224 12225 // A pointer vector can not be the return type of the ldN intrinsics. Need to 12226 // load integer vectors first and then convert to pointer vectors. 12227 if (EltTy->isPointerTy()) 12228 VecTy = 12229 VectorType::get(DL.getIntPtrType(EltTy), VecTy->getVectorNumElements()); 12230 12231 static const Intrinsic::ID LoadInts[3] = {Intrinsic::arm_neon_vld2, 12232 Intrinsic::arm_neon_vld3, 12233 Intrinsic::arm_neon_vld4}; 12234 12235 IRBuilder<> Builder(LI); 12236 SmallVector<Value *, 2> Ops; 12237 12238 Type *Int8Ptr = Builder.getInt8PtrTy(LI->getPointerAddressSpace()); 12239 Ops.push_back(Builder.CreateBitCast(LI->getPointerOperand(), Int8Ptr)); 12240 Ops.push_back(Builder.getInt32(LI->getAlignment())); 12241 12242 Type *Tys[] = { VecTy, Int8Ptr }; 12243 Function *VldnFunc = 12244 Intrinsic::getDeclaration(LI->getModule(), LoadInts[Factor - 2], Tys); 12245 CallInst *VldN = Builder.CreateCall(VldnFunc, Ops, "vldN"); 12246 12247 // Replace uses of each shufflevector with the corresponding vector loaded 12248 // by ldN. 12249 for (unsigned i = 0; i < Shuffles.size(); i++) { 12250 ShuffleVectorInst *SV = Shuffles[i]; 12251 unsigned Index = Indices[i]; 12252 12253 Value *SubVec = Builder.CreateExtractValue(VldN, Index); 12254 12255 // Convert the integer vector to pointer vector if the element is pointer. 12256 if (EltTy->isPointerTy()) 12257 SubVec = Builder.CreateIntToPtr(SubVec, SV->getType()); 12258 12259 SV->replaceAllUsesWith(SubVec); 12260 } 12261 12262 return true; 12263 } 12264 12265 /// \brief Get a mask consisting of sequential integers starting from \p Start. 12266 /// 12267 /// I.e. <Start, Start + 1, ..., Start + NumElts - 1> 12268 static Constant *getSequentialMask(IRBuilder<> &Builder, unsigned Start, 12269 unsigned NumElts) { 12270 SmallVector<Constant *, 16> Mask; 12271 for (unsigned i = 0; i < NumElts; i++) 12272 Mask.push_back(Builder.getInt32(Start + i)); 12273 12274 return ConstantVector::get(Mask); 12275 } 12276 12277 /// \brief Lower an interleaved store into a vstN intrinsic. 12278 /// 12279 /// E.g. Lower an interleaved store (Factor = 3): 12280 /// %i.vec = shuffle <8 x i32> %v0, <8 x i32> %v1, 12281 /// <0, 4, 8, 1, 5, 9, 2, 6, 10, 3, 7, 11> 12282 /// store <12 x i32> %i.vec, <12 x i32>* %ptr, align 4 12283 /// 12284 /// Into: 12285 /// %sub.v0 = shuffle <8 x i32> %v0, <8 x i32> v1, <0, 1, 2, 3> 12286 /// %sub.v1 = shuffle <8 x i32> %v0, <8 x i32> v1, <4, 5, 6, 7> 12287 /// %sub.v2 = shuffle <8 x i32> %v0, <8 x i32> v1, <8, 9, 10, 11> 12288 /// call void llvm.arm.neon.vst3(%ptr, %sub.v0, %sub.v1, %sub.v2, 4) 12289 /// 12290 /// Note that the new shufflevectors will be removed and we'll only generate one 12291 /// vst3 instruction in CodeGen. 12292 bool ARMTargetLowering::lowerInterleavedStore(StoreInst *SI, 12293 ShuffleVectorInst *SVI, 12294 unsigned Factor) const { 12295 assert(Factor >= 2 && Factor <= getMaxSupportedInterleaveFactor() && 12296 "Invalid interleave factor"); 12297 12298 VectorType *VecTy = SVI->getType(); 12299 assert(VecTy->getVectorNumElements() % Factor == 0 && 12300 "Invalid interleaved store"); 12301 12302 unsigned NumSubElts = VecTy->getVectorNumElements() / Factor; 12303 Type *EltTy = VecTy->getVectorElementType(); 12304 VectorType *SubVecTy = VectorType::get(EltTy, NumSubElts); 12305 12306 const DataLayout &DL = SI->getModule()->getDataLayout(); 12307 unsigned SubVecSize = DL.getTypeSizeInBits(SubVecTy); 12308 bool EltIs64Bits = DL.getTypeSizeInBits(EltTy) == 64; 12309 12310 // Skip if we do not have NEON and skip illegal vector types and vector types 12311 // with i64/f64 elements (vstN doesn't support i64/f64 elements). 12312 if (!Subtarget->hasNEON() || (SubVecSize != 64 && SubVecSize != 128) || 12313 EltIs64Bits) 12314 return false; 12315 12316 Value *Op0 = SVI->getOperand(0); 12317 Value *Op1 = SVI->getOperand(1); 12318 IRBuilder<> Builder(SI); 12319 12320 // StN intrinsics don't support pointer vectors as arguments. Convert pointer 12321 // vectors to integer vectors. 12322 if (EltTy->isPointerTy()) { 12323 Type *IntTy = DL.getIntPtrType(EltTy); 12324 12325 // Convert to the corresponding integer vector. 12326 Type *IntVecTy = 12327 VectorType::get(IntTy, Op0->getType()->getVectorNumElements()); 12328 Op0 = Builder.CreatePtrToInt(Op0, IntVecTy); 12329 Op1 = Builder.CreatePtrToInt(Op1, IntVecTy); 12330 12331 SubVecTy = VectorType::get(IntTy, NumSubElts); 12332 } 12333 12334 static const Intrinsic::ID StoreInts[3] = {Intrinsic::arm_neon_vst2, 12335 Intrinsic::arm_neon_vst3, 12336 Intrinsic::arm_neon_vst4}; 12337 SmallVector<Value *, 6> Ops; 12338 12339 Type *Int8Ptr = Builder.getInt8PtrTy(SI->getPointerAddressSpace()); 12340 Ops.push_back(Builder.CreateBitCast(SI->getPointerOperand(), Int8Ptr)); 12341 12342 Type *Tys[] = { Int8Ptr, SubVecTy }; 12343 Function *VstNFunc = Intrinsic::getDeclaration( 12344 SI->getModule(), StoreInts[Factor - 2], Tys); 12345 12346 // Split the shufflevector operands into sub vectors for the new vstN call. 12347 for (unsigned i = 0; i < Factor; i++) 12348 Ops.push_back(Builder.CreateShuffleVector( 12349 Op0, Op1, getSequentialMask(Builder, NumSubElts * i, NumSubElts))); 12350 12351 Ops.push_back(Builder.getInt32(SI->getAlignment())); 12352 Builder.CreateCall(VstNFunc, Ops); 12353 return true; 12354 } 12355 12356 enum HABaseType { 12357 HA_UNKNOWN = 0, 12358 HA_FLOAT, 12359 HA_DOUBLE, 12360 HA_VECT64, 12361 HA_VECT128 12362 }; 12363 12364 static bool isHomogeneousAggregate(Type *Ty, HABaseType &Base, 12365 uint64_t &Members) { 12366 if (auto *ST = dyn_cast<StructType>(Ty)) { 12367 for (unsigned i = 0; i < ST->getNumElements(); ++i) { 12368 uint64_t SubMembers = 0; 12369 if (!isHomogeneousAggregate(ST->getElementType(i), Base, SubMembers)) 12370 return false; 12371 Members += SubMembers; 12372 } 12373 } else if (auto *AT = dyn_cast<ArrayType>(Ty)) { 12374 uint64_t SubMembers = 0; 12375 if (!isHomogeneousAggregate(AT->getElementType(), Base, SubMembers)) 12376 return false; 12377 Members += SubMembers * AT->getNumElements(); 12378 } else if (Ty->isFloatTy()) { 12379 if (Base != HA_UNKNOWN && Base != HA_FLOAT) 12380 return false; 12381 Members = 1; 12382 Base = HA_FLOAT; 12383 } else if (Ty->isDoubleTy()) { 12384 if (Base != HA_UNKNOWN && Base != HA_DOUBLE) 12385 return false; 12386 Members = 1; 12387 Base = HA_DOUBLE; 12388 } else if (auto *VT = dyn_cast<VectorType>(Ty)) { 12389 Members = 1; 12390 switch (Base) { 12391 case HA_FLOAT: 12392 case HA_DOUBLE: 12393 return false; 12394 case HA_VECT64: 12395 return VT->getBitWidth() == 64; 12396 case HA_VECT128: 12397 return VT->getBitWidth() == 128; 12398 case HA_UNKNOWN: 12399 switch (VT->getBitWidth()) { 12400 case 64: 12401 Base = HA_VECT64; 12402 return true; 12403 case 128: 12404 Base = HA_VECT128; 12405 return true; 12406 default: 12407 return false; 12408 } 12409 } 12410 } 12411 12412 return (Members > 0 && Members <= 4); 12413 } 12414 12415 /// \brief Return true if a type is an AAPCS-VFP homogeneous aggregate or one of 12416 /// [N x i32] or [N x i64]. This allows front-ends to skip emitting padding when 12417 /// passing according to AAPCS rules. 12418 bool ARMTargetLowering::functionArgumentNeedsConsecutiveRegisters( 12419 Type *Ty, CallingConv::ID CallConv, bool isVarArg) const { 12420 if (getEffectiveCallingConv(CallConv, isVarArg) != 12421 CallingConv::ARM_AAPCS_VFP) 12422 return false; 12423 12424 HABaseType Base = HA_UNKNOWN; 12425 uint64_t Members = 0; 12426 bool IsHA = isHomogeneousAggregate(Ty, Base, Members); 12427 DEBUG(dbgs() << "isHA: " << IsHA << " "; Ty->dump()); 12428 12429 bool IsIntArray = Ty->isArrayTy() && Ty->getArrayElementType()->isIntegerTy(); 12430 return IsHA || IsIntArray; 12431 } 12432 12433 unsigned ARMTargetLowering::getExceptionPointerRegister( 12434 const Constant *PersonalityFn) const { 12435 // Platforms which do not use SjLj EH may return values in these registers 12436 // via the personality function. 12437 return Subtarget->useSjLjEH() ? ARM::NoRegister : ARM::R0; 12438 } 12439 12440 unsigned ARMTargetLowering::getExceptionSelectorRegister( 12441 const Constant *PersonalityFn) const { 12442 // Platforms which do not use SjLj EH may return values in these registers 12443 // via the personality function. 12444 return Subtarget->useSjLjEH() ? ARM::NoRegister : ARM::R1; 12445 } 12446 12447 void ARMTargetLowering::initializeSplitCSR(MachineBasicBlock *Entry) const { 12448 // Update IsSplitCSR in ARMFunctionInfo. 12449 ARMFunctionInfo *AFI = Entry->getParent()->getInfo<ARMFunctionInfo>(); 12450 AFI->setIsSplitCSR(true); 12451 } 12452 12453 void ARMTargetLowering::insertCopiesSplitCSR( 12454 MachineBasicBlock *Entry, 12455 const SmallVectorImpl<MachineBasicBlock *> &Exits) const { 12456 const ARMBaseRegisterInfo *TRI = Subtarget->getRegisterInfo(); 12457 const MCPhysReg *IStart = TRI->getCalleeSavedRegsViaCopy(Entry->getParent()); 12458 if (!IStart) 12459 return; 12460 12461 const TargetInstrInfo *TII = Subtarget->getInstrInfo(); 12462 MachineRegisterInfo *MRI = &Entry->getParent()->getRegInfo(); 12463 MachineBasicBlock::iterator MBBI = Entry->begin(); 12464 for (const MCPhysReg *I = IStart; *I; ++I) { 12465 const TargetRegisterClass *RC = nullptr; 12466 if (ARM::GPRRegClass.contains(*I)) 12467 RC = &ARM::GPRRegClass; 12468 else if (ARM::DPRRegClass.contains(*I)) 12469 RC = &ARM::DPRRegClass; 12470 else 12471 llvm_unreachable("Unexpected register class in CSRsViaCopy!"); 12472 12473 unsigned NewVR = MRI->createVirtualRegister(RC); 12474 // Create copy from CSR to a virtual register. 12475 // FIXME: this currently does not emit CFI pseudo-instructions, it works 12476 // fine for CXX_FAST_TLS since the C++-style TLS access functions should be 12477 // nounwind. If we want to generalize this later, we may need to emit 12478 // CFI pseudo-instructions. 12479 assert(Entry->getParent()->getFunction()->hasFnAttribute( 12480 Attribute::NoUnwind) && 12481 "Function should be nounwind in insertCopiesSplitCSR!"); 12482 Entry->addLiveIn(*I); 12483 BuildMI(*Entry, MBBI, DebugLoc(), TII->get(TargetOpcode::COPY), NewVR) 12484 .addReg(*I); 12485 12486 // Insert the copy-back instructions right before the terminator. 12487 for (auto *Exit : Exits) 12488 BuildMI(*Exit, Exit->getFirstTerminator(), DebugLoc(), 12489 TII->get(TargetOpcode::COPY), *I) 12490 .addReg(NewVR); 12491 } 12492 } 12493