1 //===-- ARMISelLowering.cpp - ARM DAG Lowering Implementation -------------===// 2 // 3 // The LLVM Compiler Infrastructure 4 // 5 // This file is distributed under the University of Illinois Open Source 6 // License. See LICENSE.TXT for details. 7 // 8 //===----------------------------------------------------------------------===// 9 // 10 // This file defines the interfaces that ARM uses to lower LLVM code into a 11 // selection DAG. 12 // 13 //===----------------------------------------------------------------------===// 14 15 #include "ARMISelLowering.h" 16 #include "ARMCallingConv.h" 17 #include "ARMConstantPoolValue.h" 18 #include "ARMMachineFunctionInfo.h" 19 #include "ARMPerfectShuffle.h" 20 #include "ARMSubtarget.h" 21 #include "ARMTargetMachine.h" 22 #include "ARMTargetObjectFile.h" 23 #include "MCTargetDesc/ARMAddressingModes.h" 24 #include "llvm/ADT/Statistic.h" 25 #include "llvm/ADT/StringExtras.h" 26 #include "llvm/ADT/StringSwitch.h" 27 #include "llvm/CodeGen/CallingConvLower.h" 28 #include "llvm/CodeGen/IntrinsicLowering.h" 29 #include "llvm/CodeGen/MachineBasicBlock.h" 30 #include "llvm/CodeGen/MachineFrameInfo.h" 31 #include "llvm/CodeGen/MachineFunction.h" 32 #include "llvm/CodeGen/MachineInstrBuilder.h" 33 #include "llvm/CodeGen/MachineJumpTableInfo.h" 34 #include "llvm/CodeGen/MachineModuleInfo.h" 35 #include "llvm/CodeGen/MachineRegisterInfo.h" 36 #include "llvm/CodeGen/SelectionDAG.h" 37 #include "llvm/IR/CallingConv.h" 38 #include "llvm/IR/Constants.h" 39 #include "llvm/IR/Function.h" 40 #include "llvm/IR/GlobalValue.h" 41 #include "llvm/IR/IRBuilder.h" 42 #include "llvm/IR/Instruction.h" 43 #include "llvm/IR/Instructions.h" 44 #include "llvm/IR/IntrinsicInst.h" 45 #include "llvm/IR/Intrinsics.h" 46 #include "llvm/IR/Type.h" 47 #include "llvm/MC/MCSectionMachO.h" 48 #include "llvm/Support/CommandLine.h" 49 #include "llvm/Support/Debug.h" 50 #include "llvm/Support/ErrorHandling.h" 51 #include "llvm/Support/MathExtras.h" 52 #include "llvm/Support/raw_ostream.h" 53 #include "llvm/Target/TargetOptions.h" 54 #include <utility> 55 using namespace llvm; 56 57 #define DEBUG_TYPE "arm-isel" 58 59 STATISTIC(NumTailCalls, "Number of tail calls"); 60 STATISTIC(NumMovwMovt, "Number of GAs materialized with movw + movt"); 61 STATISTIC(NumLoopByVals, "Number of loops generated for byval arguments"); 62 63 static cl::opt<bool> 64 ARMInterworking("arm-interworking", cl::Hidden, 65 cl::desc("Enable / disable ARM interworking (for debugging only)"), 66 cl::init(true)); 67 68 namespace { 69 class ARMCCState : public CCState { 70 public: 71 ARMCCState(CallingConv::ID CC, bool isVarArg, MachineFunction &MF, 72 SmallVectorImpl<CCValAssign> &locs, LLVMContext &C, 73 ParmContext PC) 74 : CCState(CC, isVarArg, MF, locs, C) { 75 assert(((PC == Call) || (PC == Prologue)) && 76 "ARMCCState users must specify whether their context is call" 77 "or prologue generation."); 78 CallOrPrologue = PC; 79 } 80 }; 81 } 82 83 // The APCS parameter registers. 84 static const MCPhysReg GPRArgRegs[] = { 85 ARM::R0, ARM::R1, ARM::R2, ARM::R3 86 }; 87 88 void ARMTargetLowering::addTypeForNEON(MVT VT, MVT PromotedLdStVT, 89 MVT PromotedBitwiseVT) { 90 if (VT != PromotedLdStVT) { 91 setOperationAction(ISD::LOAD, VT, Promote); 92 AddPromotedToType (ISD::LOAD, VT, PromotedLdStVT); 93 94 setOperationAction(ISD::STORE, VT, Promote); 95 AddPromotedToType (ISD::STORE, VT, PromotedLdStVT); 96 } 97 98 MVT ElemTy = VT.getVectorElementType(); 99 if (ElemTy != MVT::i64 && ElemTy != MVT::f64) 100 setOperationAction(ISD::SETCC, VT, Custom); 101 setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Custom); 102 setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom); 103 if (ElemTy == MVT::i32) { 104 setOperationAction(ISD::SINT_TO_FP, VT, Custom); 105 setOperationAction(ISD::UINT_TO_FP, VT, Custom); 106 setOperationAction(ISD::FP_TO_SINT, VT, Custom); 107 setOperationAction(ISD::FP_TO_UINT, VT, Custom); 108 } else { 109 setOperationAction(ISD::SINT_TO_FP, VT, Expand); 110 setOperationAction(ISD::UINT_TO_FP, VT, Expand); 111 setOperationAction(ISD::FP_TO_SINT, VT, Expand); 112 setOperationAction(ISD::FP_TO_UINT, VT, Expand); 113 } 114 setOperationAction(ISD::BUILD_VECTOR, VT, Custom); 115 setOperationAction(ISD::VECTOR_SHUFFLE, VT, Custom); 116 setOperationAction(ISD::CONCAT_VECTORS, VT, Legal); 117 setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Legal); 118 setOperationAction(ISD::SELECT, VT, Expand); 119 setOperationAction(ISD::SELECT_CC, VT, Expand); 120 setOperationAction(ISD::VSELECT, VT, Expand); 121 setOperationAction(ISD::SIGN_EXTEND_INREG, VT, Expand); 122 if (VT.isInteger()) { 123 setOperationAction(ISD::SHL, VT, Custom); 124 setOperationAction(ISD::SRA, VT, Custom); 125 setOperationAction(ISD::SRL, VT, Custom); 126 } 127 128 // Promote all bit-wise operations. 129 if (VT.isInteger() && VT != PromotedBitwiseVT) { 130 setOperationAction(ISD::AND, VT, Promote); 131 AddPromotedToType (ISD::AND, VT, PromotedBitwiseVT); 132 setOperationAction(ISD::OR, VT, Promote); 133 AddPromotedToType (ISD::OR, VT, PromotedBitwiseVT); 134 setOperationAction(ISD::XOR, VT, Promote); 135 AddPromotedToType (ISD::XOR, VT, PromotedBitwiseVT); 136 } 137 138 // Neon does not support vector divide/remainder operations. 139 setOperationAction(ISD::SDIV, VT, Expand); 140 setOperationAction(ISD::UDIV, VT, Expand); 141 setOperationAction(ISD::FDIV, VT, Expand); 142 setOperationAction(ISD::SREM, VT, Expand); 143 setOperationAction(ISD::UREM, VT, Expand); 144 setOperationAction(ISD::FREM, VT, Expand); 145 146 if (!VT.isFloatingPoint() && 147 VT != MVT::v2i64 && VT != MVT::v1i64) 148 for (unsigned Opcode : {ISD::SMIN, ISD::SMAX, ISD::UMIN, ISD::UMAX}) 149 setOperationAction(Opcode, VT, Legal); 150 } 151 152 void ARMTargetLowering::addDRTypeForNEON(MVT VT) { 153 addRegisterClass(VT, &ARM::DPRRegClass); 154 addTypeForNEON(VT, MVT::f64, MVT::v2i32); 155 } 156 157 void ARMTargetLowering::addQRTypeForNEON(MVT VT) { 158 addRegisterClass(VT, &ARM::DPairRegClass); 159 addTypeForNEON(VT, MVT::v2f64, MVT::v4i32); 160 } 161 162 ARMTargetLowering::ARMTargetLowering(const TargetMachine &TM, 163 const ARMSubtarget &STI) 164 : TargetLowering(TM), Subtarget(&STI) { 165 RegInfo = Subtarget->getRegisterInfo(); 166 Itins = Subtarget->getInstrItineraryData(); 167 168 setBooleanVectorContents(ZeroOrNegativeOneBooleanContent); 169 170 if (Subtarget->isTargetMachO()) { 171 // Uses VFP for Thumb libfuncs if available. 172 if (Subtarget->isThumb() && Subtarget->hasVFP2() && 173 Subtarget->hasARMOps() && !Subtarget->useSoftFloat()) { 174 static const struct { 175 const RTLIB::Libcall Op; 176 const char * const Name; 177 const ISD::CondCode Cond; 178 } LibraryCalls[] = { 179 // Single-precision floating-point arithmetic. 180 { RTLIB::ADD_F32, "__addsf3vfp", ISD::SETCC_INVALID }, 181 { RTLIB::SUB_F32, "__subsf3vfp", ISD::SETCC_INVALID }, 182 { RTLIB::MUL_F32, "__mulsf3vfp", ISD::SETCC_INVALID }, 183 { RTLIB::DIV_F32, "__divsf3vfp", ISD::SETCC_INVALID }, 184 185 // Double-precision floating-point arithmetic. 186 { RTLIB::ADD_F64, "__adddf3vfp", ISD::SETCC_INVALID }, 187 { RTLIB::SUB_F64, "__subdf3vfp", ISD::SETCC_INVALID }, 188 { RTLIB::MUL_F64, "__muldf3vfp", ISD::SETCC_INVALID }, 189 { RTLIB::DIV_F64, "__divdf3vfp", ISD::SETCC_INVALID }, 190 191 // Single-precision comparisons. 192 { RTLIB::OEQ_F32, "__eqsf2vfp", ISD::SETNE }, 193 { RTLIB::UNE_F32, "__nesf2vfp", ISD::SETNE }, 194 { RTLIB::OLT_F32, "__ltsf2vfp", ISD::SETNE }, 195 { RTLIB::OLE_F32, "__lesf2vfp", ISD::SETNE }, 196 { RTLIB::OGE_F32, "__gesf2vfp", ISD::SETNE }, 197 { RTLIB::OGT_F32, "__gtsf2vfp", ISD::SETNE }, 198 { RTLIB::UO_F32, "__unordsf2vfp", ISD::SETNE }, 199 { RTLIB::O_F32, "__unordsf2vfp", ISD::SETEQ }, 200 201 // Double-precision comparisons. 202 { RTLIB::OEQ_F64, "__eqdf2vfp", ISD::SETNE }, 203 { RTLIB::UNE_F64, "__nedf2vfp", ISD::SETNE }, 204 { RTLIB::OLT_F64, "__ltdf2vfp", ISD::SETNE }, 205 { RTLIB::OLE_F64, "__ledf2vfp", ISD::SETNE }, 206 { RTLIB::OGE_F64, "__gedf2vfp", ISD::SETNE }, 207 { RTLIB::OGT_F64, "__gtdf2vfp", ISD::SETNE }, 208 { RTLIB::UO_F64, "__unorddf2vfp", ISD::SETNE }, 209 { RTLIB::O_F64, "__unorddf2vfp", ISD::SETEQ }, 210 211 // Floating-point to integer conversions. 212 // i64 conversions are done via library routines even when generating VFP 213 // instructions, so use the same ones. 214 { RTLIB::FPTOSINT_F64_I32, "__fixdfsivfp", ISD::SETCC_INVALID }, 215 { RTLIB::FPTOUINT_F64_I32, "__fixunsdfsivfp", ISD::SETCC_INVALID }, 216 { RTLIB::FPTOSINT_F32_I32, "__fixsfsivfp", ISD::SETCC_INVALID }, 217 { RTLIB::FPTOUINT_F32_I32, "__fixunssfsivfp", ISD::SETCC_INVALID }, 218 219 // Conversions between floating types. 220 { RTLIB::FPROUND_F64_F32, "__truncdfsf2vfp", ISD::SETCC_INVALID }, 221 { RTLIB::FPEXT_F32_F64, "__extendsfdf2vfp", ISD::SETCC_INVALID }, 222 223 // Integer to floating-point conversions. 224 // i64 conversions are done via library routines even when generating VFP 225 // instructions, so use the same ones. 226 // FIXME: There appears to be some naming inconsistency in ARM libgcc: 227 // e.g., __floatunsidf vs. __floatunssidfvfp. 228 { RTLIB::SINTTOFP_I32_F64, "__floatsidfvfp", ISD::SETCC_INVALID }, 229 { RTLIB::UINTTOFP_I32_F64, "__floatunssidfvfp", ISD::SETCC_INVALID }, 230 { RTLIB::SINTTOFP_I32_F32, "__floatsisfvfp", ISD::SETCC_INVALID }, 231 { RTLIB::UINTTOFP_I32_F32, "__floatunssisfvfp", ISD::SETCC_INVALID }, 232 }; 233 234 for (const auto &LC : LibraryCalls) { 235 setLibcallName(LC.Op, LC.Name); 236 if (LC.Cond != ISD::SETCC_INVALID) 237 setCmpLibcallCC(LC.Op, LC.Cond); 238 } 239 } 240 241 // Set the correct calling convention for ARMv7k WatchOS. It's just 242 // AAPCS_VFP for functions as simple as libcalls. 243 if (Subtarget->isTargetWatchABI()) { 244 for (int i = 0; i < RTLIB::UNKNOWN_LIBCALL; ++i) 245 setLibcallCallingConv((RTLIB::Libcall)i, CallingConv::ARM_AAPCS_VFP); 246 } 247 } 248 249 // These libcalls are not available in 32-bit. 250 setLibcallName(RTLIB::SHL_I128, nullptr); 251 setLibcallName(RTLIB::SRL_I128, nullptr); 252 setLibcallName(RTLIB::SRA_I128, nullptr); 253 254 // RTLIB 255 if (Subtarget->isAAPCS_ABI() && 256 (Subtarget->isTargetAEABI() || Subtarget->isTargetGNUAEABI() || 257 Subtarget->isTargetAndroid())) { 258 static const struct { 259 const RTLIB::Libcall Op; 260 const char * const Name; 261 const CallingConv::ID CC; 262 const ISD::CondCode Cond; 263 } LibraryCalls[] = { 264 // Double-precision floating-point arithmetic helper functions 265 // RTABI chapter 4.1.2, Table 2 266 { RTLIB::ADD_F64, "__aeabi_dadd", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 267 { RTLIB::DIV_F64, "__aeabi_ddiv", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 268 { RTLIB::MUL_F64, "__aeabi_dmul", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 269 { RTLIB::SUB_F64, "__aeabi_dsub", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 270 271 // Double-precision floating-point comparison helper functions 272 // RTABI chapter 4.1.2, Table 3 273 { RTLIB::OEQ_F64, "__aeabi_dcmpeq", CallingConv::ARM_AAPCS, ISD::SETNE }, 274 { RTLIB::UNE_F64, "__aeabi_dcmpeq", CallingConv::ARM_AAPCS, ISD::SETEQ }, 275 { RTLIB::OLT_F64, "__aeabi_dcmplt", CallingConv::ARM_AAPCS, ISD::SETNE }, 276 { RTLIB::OLE_F64, "__aeabi_dcmple", CallingConv::ARM_AAPCS, ISD::SETNE }, 277 { RTLIB::OGE_F64, "__aeabi_dcmpge", CallingConv::ARM_AAPCS, ISD::SETNE }, 278 { RTLIB::OGT_F64, "__aeabi_dcmpgt", CallingConv::ARM_AAPCS, ISD::SETNE }, 279 { RTLIB::UO_F64, "__aeabi_dcmpun", CallingConv::ARM_AAPCS, ISD::SETNE }, 280 { RTLIB::O_F64, "__aeabi_dcmpun", CallingConv::ARM_AAPCS, ISD::SETEQ }, 281 282 // Single-precision floating-point arithmetic helper functions 283 // RTABI chapter 4.1.2, Table 4 284 { RTLIB::ADD_F32, "__aeabi_fadd", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 285 { RTLIB::DIV_F32, "__aeabi_fdiv", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 286 { RTLIB::MUL_F32, "__aeabi_fmul", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 287 { RTLIB::SUB_F32, "__aeabi_fsub", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 288 289 // Single-precision floating-point comparison helper functions 290 // RTABI chapter 4.1.2, Table 5 291 { RTLIB::OEQ_F32, "__aeabi_fcmpeq", CallingConv::ARM_AAPCS, ISD::SETNE }, 292 { RTLIB::UNE_F32, "__aeabi_fcmpeq", CallingConv::ARM_AAPCS, ISD::SETEQ }, 293 { RTLIB::OLT_F32, "__aeabi_fcmplt", CallingConv::ARM_AAPCS, ISD::SETNE }, 294 { RTLIB::OLE_F32, "__aeabi_fcmple", CallingConv::ARM_AAPCS, ISD::SETNE }, 295 { RTLIB::OGE_F32, "__aeabi_fcmpge", CallingConv::ARM_AAPCS, ISD::SETNE }, 296 { RTLIB::OGT_F32, "__aeabi_fcmpgt", CallingConv::ARM_AAPCS, ISD::SETNE }, 297 { RTLIB::UO_F32, "__aeabi_fcmpun", CallingConv::ARM_AAPCS, ISD::SETNE }, 298 { RTLIB::O_F32, "__aeabi_fcmpun", CallingConv::ARM_AAPCS, ISD::SETEQ }, 299 300 // Floating-point to integer conversions. 301 // RTABI chapter 4.1.2, Table 6 302 { RTLIB::FPTOSINT_F64_I32, "__aeabi_d2iz", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 303 { RTLIB::FPTOUINT_F64_I32, "__aeabi_d2uiz", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 304 { RTLIB::FPTOSINT_F64_I64, "__aeabi_d2lz", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 305 { RTLIB::FPTOUINT_F64_I64, "__aeabi_d2ulz", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 306 { RTLIB::FPTOSINT_F32_I32, "__aeabi_f2iz", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 307 { RTLIB::FPTOUINT_F32_I32, "__aeabi_f2uiz", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 308 { RTLIB::FPTOSINT_F32_I64, "__aeabi_f2lz", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 309 { RTLIB::FPTOUINT_F32_I64, "__aeabi_f2ulz", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 310 311 // Conversions between floating types. 312 // RTABI chapter 4.1.2, Table 7 313 { RTLIB::FPROUND_F64_F32, "__aeabi_d2f", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 314 { RTLIB::FPROUND_F64_F16, "__aeabi_d2h", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 315 { RTLIB::FPEXT_F32_F64, "__aeabi_f2d", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 316 317 // Integer to floating-point conversions. 318 // RTABI chapter 4.1.2, Table 8 319 { RTLIB::SINTTOFP_I32_F64, "__aeabi_i2d", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 320 { RTLIB::UINTTOFP_I32_F64, "__aeabi_ui2d", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 321 { RTLIB::SINTTOFP_I64_F64, "__aeabi_l2d", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 322 { RTLIB::UINTTOFP_I64_F64, "__aeabi_ul2d", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 323 { RTLIB::SINTTOFP_I32_F32, "__aeabi_i2f", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 324 { RTLIB::UINTTOFP_I32_F32, "__aeabi_ui2f", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 325 { RTLIB::SINTTOFP_I64_F32, "__aeabi_l2f", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 326 { RTLIB::UINTTOFP_I64_F32, "__aeabi_ul2f", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 327 328 // Long long helper functions 329 // RTABI chapter 4.2, Table 9 330 { RTLIB::MUL_I64, "__aeabi_lmul", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 331 { RTLIB::SHL_I64, "__aeabi_llsl", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 332 { RTLIB::SRL_I64, "__aeabi_llsr", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 333 { RTLIB::SRA_I64, "__aeabi_lasr", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 334 335 // Integer division functions 336 // RTABI chapter 4.3.1 337 { RTLIB::SDIV_I8, "__aeabi_idiv", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 338 { RTLIB::SDIV_I16, "__aeabi_idiv", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 339 { RTLIB::SDIV_I32, "__aeabi_idiv", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 340 { RTLIB::SDIV_I64, "__aeabi_ldivmod", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 341 { RTLIB::UDIV_I8, "__aeabi_uidiv", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 342 { RTLIB::UDIV_I16, "__aeabi_uidiv", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 343 { RTLIB::UDIV_I32, "__aeabi_uidiv", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 344 { RTLIB::UDIV_I64, "__aeabi_uldivmod", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 345 }; 346 347 for (const auto &LC : LibraryCalls) { 348 setLibcallName(LC.Op, LC.Name); 349 setLibcallCallingConv(LC.Op, LC.CC); 350 if (LC.Cond != ISD::SETCC_INVALID) 351 setCmpLibcallCC(LC.Op, LC.Cond); 352 } 353 354 // EABI dependent RTLIB 355 if (TM.Options.EABIVersion == EABI::EABI4 || 356 TM.Options.EABIVersion == EABI::EABI5) { 357 static const struct { 358 const RTLIB::Libcall Op; 359 const char *const Name; 360 const CallingConv::ID CC; 361 const ISD::CondCode Cond; 362 } MemOpsLibraryCalls[] = { 363 // Memory operations 364 // RTABI chapter 4.3.4 365 { RTLIB::MEMCPY, "__aeabi_memcpy", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 366 { RTLIB::MEMMOVE, "__aeabi_memmove", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 367 { RTLIB::MEMSET, "__aeabi_memset", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 368 }; 369 370 for (const auto &LC : MemOpsLibraryCalls) { 371 setLibcallName(LC.Op, LC.Name); 372 setLibcallCallingConv(LC.Op, LC.CC); 373 if (LC.Cond != ISD::SETCC_INVALID) 374 setCmpLibcallCC(LC.Op, LC.Cond); 375 } 376 } 377 } 378 379 if (Subtarget->isTargetWindows()) { 380 static const struct { 381 const RTLIB::Libcall Op; 382 const char * const Name; 383 const CallingConv::ID CC; 384 } LibraryCalls[] = { 385 { RTLIB::FPTOSINT_F32_I64, "__stoi64", CallingConv::ARM_AAPCS_VFP }, 386 { RTLIB::FPTOSINT_F64_I64, "__dtoi64", CallingConv::ARM_AAPCS_VFP }, 387 { RTLIB::FPTOUINT_F32_I64, "__stou64", CallingConv::ARM_AAPCS_VFP }, 388 { RTLIB::FPTOUINT_F64_I64, "__dtou64", CallingConv::ARM_AAPCS_VFP }, 389 { RTLIB::SINTTOFP_I64_F32, "__i64tos", CallingConv::ARM_AAPCS_VFP }, 390 { RTLIB::SINTTOFP_I64_F64, "__i64tod", CallingConv::ARM_AAPCS_VFP }, 391 { RTLIB::UINTTOFP_I64_F32, "__u64tos", CallingConv::ARM_AAPCS_VFP }, 392 { RTLIB::UINTTOFP_I64_F64, "__u64tod", CallingConv::ARM_AAPCS_VFP }, 393 }; 394 395 for (const auto &LC : LibraryCalls) { 396 setLibcallName(LC.Op, LC.Name); 397 setLibcallCallingConv(LC.Op, LC.CC); 398 } 399 } 400 401 // Use divmod compiler-rt calls for iOS 5.0 and later. 402 if (Subtarget->isTargetWatchOS() || 403 (Subtarget->isTargetIOS() && 404 !Subtarget->getTargetTriple().isOSVersionLT(5, 0))) { 405 setLibcallName(RTLIB::SDIVREM_I32, "__divmodsi4"); 406 setLibcallName(RTLIB::UDIVREM_I32, "__udivmodsi4"); 407 } 408 409 // The half <-> float conversion functions are always soft-float, but are 410 // needed for some targets which use a hard-float calling convention by 411 // default. 412 if (Subtarget->isAAPCS_ABI()) { 413 setLibcallCallingConv(RTLIB::FPROUND_F32_F16, CallingConv::ARM_AAPCS); 414 setLibcallCallingConv(RTLIB::FPROUND_F64_F16, CallingConv::ARM_AAPCS); 415 setLibcallCallingConv(RTLIB::FPEXT_F16_F32, CallingConv::ARM_AAPCS); 416 } else { 417 setLibcallCallingConv(RTLIB::FPROUND_F32_F16, CallingConv::ARM_APCS); 418 setLibcallCallingConv(RTLIB::FPROUND_F64_F16, CallingConv::ARM_APCS); 419 setLibcallCallingConv(RTLIB::FPEXT_F16_F32, CallingConv::ARM_APCS); 420 } 421 422 // In EABI, these functions have an __aeabi_ prefix, but in GNUEABI they have 423 // a __gnu_ prefix (which is the default). 424 if (Subtarget->isTargetAEABI()) { 425 setLibcallName(RTLIB::FPROUND_F32_F16, "__aeabi_f2h"); 426 setLibcallName(RTLIB::FPROUND_F64_F16, "__aeabi_d2h"); 427 setLibcallName(RTLIB::FPEXT_F16_F32, "__aeabi_h2f"); 428 } 429 430 if (Subtarget->isThumb1Only()) 431 addRegisterClass(MVT::i32, &ARM::tGPRRegClass); 432 else 433 addRegisterClass(MVT::i32, &ARM::GPRRegClass); 434 if (!Subtarget->useSoftFloat() && Subtarget->hasVFP2() && 435 !Subtarget->isThumb1Only()) { 436 addRegisterClass(MVT::f32, &ARM::SPRRegClass); 437 addRegisterClass(MVT::f64, &ARM::DPRRegClass); 438 } 439 440 for (MVT VT : MVT::vector_valuetypes()) { 441 for (MVT InnerVT : MVT::vector_valuetypes()) { 442 setTruncStoreAction(VT, InnerVT, Expand); 443 setLoadExtAction(ISD::SEXTLOAD, VT, InnerVT, Expand); 444 setLoadExtAction(ISD::ZEXTLOAD, VT, InnerVT, Expand); 445 setLoadExtAction(ISD::EXTLOAD, VT, InnerVT, Expand); 446 } 447 448 setOperationAction(ISD::MULHS, VT, Expand); 449 setOperationAction(ISD::SMUL_LOHI, VT, Expand); 450 setOperationAction(ISD::MULHU, VT, Expand); 451 setOperationAction(ISD::UMUL_LOHI, VT, Expand); 452 453 setOperationAction(ISD::BSWAP, VT, Expand); 454 } 455 456 setOperationAction(ISD::ConstantFP, MVT::f32, Custom); 457 setOperationAction(ISD::ConstantFP, MVT::f64, Custom); 458 459 setOperationAction(ISD::READ_REGISTER, MVT::i64, Custom); 460 setOperationAction(ISD::WRITE_REGISTER, MVT::i64, Custom); 461 462 if (Subtarget->hasNEON()) { 463 addDRTypeForNEON(MVT::v2f32); 464 addDRTypeForNEON(MVT::v8i8); 465 addDRTypeForNEON(MVT::v4i16); 466 addDRTypeForNEON(MVT::v2i32); 467 addDRTypeForNEON(MVT::v1i64); 468 469 addQRTypeForNEON(MVT::v4f32); 470 addQRTypeForNEON(MVT::v2f64); 471 addQRTypeForNEON(MVT::v16i8); 472 addQRTypeForNEON(MVT::v8i16); 473 addQRTypeForNEON(MVT::v4i32); 474 addQRTypeForNEON(MVT::v2i64); 475 476 // v2f64 is legal so that QR subregs can be extracted as f64 elements, but 477 // neither Neon nor VFP support any arithmetic operations on it. 478 // The same with v4f32. But keep in mind that vadd, vsub, vmul are natively 479 // supported for v4f32. 480 setOperationAction(ISD::FADD, MVT::v2f64, Expand); 481 setOperationAction(ISD::FSUB, MVT::v2f64, Expand); 482 setOperationAction(ISD::FMUL, MVT::v2f64, Expand); 483 // FIXME: Code duplication: FDIV and FREM are expanded always, see 484 // ARMTargetLowering::addTypeForNEON method for details. 485 setOperationAction(ISD::FDIV, MVT::v2f64, Expand); 486 setOperationAction(ISD::FREM, MVT::v2f64, Expand); 487 // FIXME: Create unittest. 488 // In another words, find a way when "copysign" appears in DAG with vector 489 // operands. 490 setOperationAction(ISD::FCOPYSIGN, MVT::v2f64, Expand); 491 // FIXME: Code duplication: SETCC has custom operation action, see 492 // ARMTargetLowering::addTypeForNEON method for details. 493 setOperationAction(ISD::SETCC, MVT::v2f64, Expand); 494 // FIXME: Create unittest for FNEG and for FABS. 495 setOperationAction(ISD::FNEG, MVT::v2f64, Expand); 496 setOperationAction(ISD::FABS, MVT::v2f64, Expand); 497 setOperationAction(ISD::FSQRT, MVT::v2f64, Expand); 498 setOperationAction(ISD::FSIN, MVT::v2f64, Expand); 499 setOperationAction(ISD::FCOS, MVT::v2f64, Expand); 500 setOperationAction(ISD::FPOWI, MVT::v2f64, Expand); 501 setOperationAction(ISD::FPOW, MVT::v2f64, Expand); 502 setOperationAction(ISD::FLOG, MVT::v2f64, Expand); 503 setOperationAction(ISD::FLOG2, MVT::v2f64, Expand); 504 setOperationAction(ISD::FLOG10, MVT::v2f64, Expand); 505 setOperationAction(ISD::FEXP, MVT::v2f64, Expand); 506 setOperationAction(ISD::FEXP2, MVT::v2f64, Expand); 507 // FIXME: Create unittest for FCEIL, FTRUNC, FRINT, FNEARBYINT, FFLOOR. 508 setOperationAction(ISD::FCEIL, MVT::v2f64, Expand); 509 setOperationAction(ISD::FTRUNC, MVT::v2f64, Expand); 510 setOperationAction(ISD::FRINT, MVT::v2f64, Expand); 511 setOperationAction(ISD::FNEARBYINT, MVT::v2f64, Expand); 512 setOperationAction(ISD::FFLOOR, MVT::v2f64, Expand); 513 setOperationAction(ISD::FMA, MVT::v2f64, Expand); 514 515 setOperationAction(ISD::FSQRT, MVT::v4f32, Expand); 516 setOperationAction(ISD::FSIN, MVT::v4f32, Expand); 517 setOperationAction(ISD::FCOS, MVT::v4f32, Expand); 518 setOperationAction(ISD::FPOWI, MVT::v4f32, Expand); 519 setOperationAction(ISD::FPOW, MVT::v4f32, Expand); 520 setOperationAction(ISD::FLOG, MVT::v4f32, Expand); 521 setOperationAction(ISD::FLOG2, MVT::v4f32, Expand); 522 setOperationAction(ISD::FLOG10, MVT::v4f32, Expand); 523 setOperationAction(ISD::FEXP, MVT::v4f32, Expand); 524 setOperationAction(ISD::FEXP2, MVT::v4f32, Expand); 525 setOperationAction(ISD::FCEIL, MVT::v4f32, Expand); 526 setOperationAction(ISD::FTRUNC, MVT::v4f32, Expand); 527 setOperationAction(ISD::FRINT, MVT::v4f32, Expand); 528 setOperationAction(ISD::FNEARBYINT, MVT::v4f32, Expand); 529 setOperationAction(ISD::FFLOOR, MVT::v4f32, Expand); 530 531 // Mark v2f32 intrinsics. 532 setOperationAction(ISD::FSQRT, MVT::v2f32, Expand); 533 setOperationAction(ISD::FSIN, MVT::v2f32, Expand); 534 setOperationAction(ISD::FCOS, MVT::v2f32, Expand); 535 setOperationAction(ISD::FPOWI, MVT::v2f32, Expand); 536 setOperationAction(ISD::FPOW, MVT::v2f32, Expand); 537 setOperationAction(ISD::FLOG, MVT::v2f32, Expand); 538 setOperationAction(ISD::FLOG2, MVT::v2f32, Expand); 539 setOperationAction(ISD::FLOG10, MVT::v2f32, Expand); 540 setOperationAction(ISD::FEXP, MVT::v2f32, Expand); 541 setOperationAction(ISD::FEXP2, MVT::v2f32, Expand); 542 setOperationAction(ISD::FCEIL, MVT::v2f32, Expand); 543 setOperationAction(ISD::FTRUNC, MVT::v2f32, Expand); 544 setOperationAction(ISD::FRINT, MVT::v2f32, Expand); 545 setOperationAction(ISD::FNEARBYINT, MVT::v2f32, Expand); 546 setOperationAction(ISD::FFLOOR, MVT::v2f32, Expand); 547 548 // Neon does not support some operations on v1i64 and v2i64 types. 549 setOperationAction(ISD::MUL, MVT::v1i64, Expand); 550 // Custom handling for some quad-vector types to detect VMULL. 551 setOperationAction(ISD::MUL, MVT::v8i16, Custom); 552 setOperationAction(ISD::MUL, MVT::v4i32, Custom); 553 setOperationAction(ISD::MUL, MVT::v2i64, Custom); 554 // Custom handling for some vector types to avoid expensive expansions 555 setOperationAction(ISD::SDIV, MVT::v4i16, Custom); 556 setOperationAction(ISD::SDIV, MVT::v8i8, Custom); 557 setOperationAction(ISD::UDIV, MVT::v4i16, Custom); 558 setOperationAction(ISD::UDIV, MVT::v8i8, Custom); 559 setOperationAction(ISD::SETCC, MVT::v1i64, Expand); 560 setOperationAction(ISD::SETCC, MVT::v2i64, Expand); 561 // Neon does not have single instruction SINT_TO_FP and UINT_TO_FP with 562 // a destination type that is wider than the source, and nor does 563 // it have a FP_TO_[SU]INT instruction with a narrower destination than 564 // source. 565 setOperationAction(ISD::SINT_TO_FP, MVT::v4i16, Custom); 566 setOperationAction(ISD::UINT_TO_FP, MVT::v4i16, Custom); 567 setOperationAction(ISD::FP_TO_UINT, MVT::v4i16, Custom); 568 setOperationAction(ISD::FP_TO_SINT, MVT::v4i16, Custom); 569 570 setOperationAction(ISD::FP_ROUND, MVT::v2f32, Expand); 571 setOperationAction(ISD::FP_EXTEND, MVT::v2f64, Expand); 572 573 // NEON does not have single instruction CTPOP for vectors with element 574 // types wider than 8-bits. However, custom lowering can leverage the 575 // v8i8/v16i8 vcnt instruction. 576 setOperationAction(ISD::CTPOP, MVT::v2i32, Custom); 577 setOperationAction(ISD::CTPOP, MVT::v4i32, Custom); 578 setOperationAction(ISD::CTPOP, MVT::v4i16, Custom); 579 setOperationAction(ISD::CTPOP, MVT::v8i16, Custom); 580 setOperationAction(ISD::CTPOP, MVT::v1i64, Expand); 581 setOperationAction(ISD::CTPOP, MVT::v2i64, Expand); 582 583 // NEON does not have single instruction CTTZ for vectors. 584 setOperationAction(ISD::CTTZ, MVT::v8i8, Custom); 585 setOperationAction(ISD::CTTZ, MVT::v4i16, Custom); 586 setOperationAction(ISD::CTTZ, MVT::v2i32, Custom); 587 setOperationAction(ISD::CTTZ, MVT::v1i64, Custom); 588 589 setOperationAction(ISD::CTTZ, MVT::v16i8, Custom); 590 setOperationAction(ISD::CTTZ, MVT::v8i16, Custom); 591 setOperationAction(ISD::CTTZ, MVT::v4i32, Custom); 592 setOperationAction(ISD::CTTZ, MVT::v2i64, Custom); 593 594 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::v8i8, Custom); 595 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::v4i16, Custom); 596 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::v2i32, Custom); 597 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::v1i64, Custom); 598 599 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::v16i8, Custom); 600 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::v8i16, Custom); 601 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::v4i32, Custom); 602 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::v2i64, Custom); 603 604 // NEON only has FMA instructions as of VFP4. 605 if (!Subtarget->hasVFP4()) { 606 setOperationAction(ISD::FMA, MVT::v2f32, Expand); 607 setOperationAction(ISD::FMA, MVT::v4f32, Expand); 608 } 609 610 setTargetDAGCombine(ISD::INTRINSIC_VOID); 611 setTargetDAGCombine(ISD::INTRINSIC_W_CHAIN); 612 setTargetDAGCombine(ISD::INTRINSIC_WO_CHAIN); 613 setTargetDAGCombine(ISD::SHL); 614 setTargetDAGCombine(ISD::SRL); 615 setTargetDAGCombine(ISD::SRA); 616 setTargetDAGCombine(ISD::SIGN_EXTEND); 617 setTargetDAGCombine(ISD::ZERO_EXTEND); 618 setTargetDAGCombine(ISD::ANY_EXTEND); 619 setTargetDAGCombine(ISD::BUILD_VECTOR); 620 setTargetDAGCombine(ISD::VECTOR_SHUFFLE); 621 setTargetDAGCombine(ISD::INSERT_VECTOR_ELT); 622 setTargetDAGCombine(ISD::STORE); 623 setTargetDAGCombine(ISD::FP_TO_SINT); 624 setTargetDAGCombine(ISD::FP_TO_UINT); 625 setTargetDAGCombine(ISD::FDIV); 626 setTargetDAGCombine(ISD::LOAD); 627 628 // It is legal to extload from v4i8 to v4i16 or v4i32. 629 for (MVT Ty : {MVT::v8i8, MVT::v4i8, MVT::v2i8, MVT::v4i16, MVT::v2i16, 630 MVT::v2i32}) { 631 for (MVT VT : MVT::integer_vector_valuetypes()) { 632 setLoadExtAction(ISD::EXTLOAD, VT, Ty, Legal); 633 setLoadExtAction(ISD::ZEXTLOAD, VT, Ty, Legal); 634 setLoadExtAction(ISD::SEXTLOAD, VT, Ty, Legal); 635 } 636 } 637 } 638 639 // ARM and Thumb2 support UMLAL/SMLAL. 640 if (!Subtarget->isThumb1Only()) 641 setTargetDAGCombine(ISD::ADDC); 642 643 if (Subtarget->isFPOnlySP()) { 644 // When targeting a floating-point unit with only single-precision 645 // operations, f64 is legal for the few double-precision instructions which 646 // are present However, no double-precision operations other than moves, 647 // loads and stores are provided by the hardware. 648 setOperationAction(ISD::FADD, MVT::f64, Expand); 649 setOperationAction(ISD::FSUB, MVT::f64, Expand); 650 setOperationAction(ISD::FMUL, MVT::f64, Expand); 651 setOperationAction(ISD::FMA, MVT::f64, Expand); 652 setOperationAction(ISD::FDIV, MVT::f64, Expand); 653 setOperationAction(ISD::FREM, MVT::f64, Expand); 654 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand); 655 setOperationAction(ISD::FGETSIGN, MVT::f64, Expand); 656 setOperationAction(ISD::FNEG, MVT::f64, Expand); 657 setOperationAction(ISD::FABS, MVT::f64, Expand); 658 setOperationAction(ISD::FSQRT, MVT::f64, Expand); 659 setOperationAction(ISD::FSIN, MVT::f64, Expand); 660 setOperationAction(ISD::FCOS, MVT::f64, Expand); 661 setOperationAction(ISD::FPOWI, MVT::f64, Expand); 662 setOperationAction(ISD::FPOW, MVT::f64, Expand); 663 setOperationAction(ISD::FLOG, MVT::f64, Expand); 664 setOperationAction(ISD::FLOG2, MVT::f64, Expand); 665 setOperationAction(ISD::FLOG10, MVT::f64, Expand); 666 setOperationAction(ISD::FEXP, MVT::f64, Expand); 667 setOperationAction(ISD::FEXP2, MVT::f64, Expand); 668 setOperationAction(ISD::FCEIL, MVT::f64, Expand); 669 setOperationAction(ISD::FTRUNC, MVT::f64, Expand); 670 setOperationAction(ISD::FRINT, MVT::f64, Expand); 671 setOperationAction(ISD::FNEARBYINT, MVT::f64, Expand); 672 setOperationAction(ISD::FFLOOR, MVT::f64, Expand); 673 setOperationAction(ISD::SINT_TO_FP, MVT::i32, Custom); 674 setOperationAction(ISD::UINT_TO_FP, MVT::i32, Custom); 675 setOperationAction(ISD::FP_TO_SINT, MVT::i32, Custom); 676 setOperationAction(ISD::FP_TO_UINT, MVT::i32, Custom); 677 setOperationAction(ISD::FP_TO_SINT, MVT::f64, Custom); 678 setOperationAction(ISD::FP_TO_UINT, MVT::f64, Custom); 679 setOperationAction(ISD::FP_ROUND, MVT::f32, Custom); 680 setOperationAction(ISD::FP_EXTEND, MVT::f64, Custom); 681 } 682 683 computeRegisterProperties(Subtarget->getRegisterInfo()); 684 685 // ARM does not have floating-point extending loads. 686 for (MVT VT : MVT::fp_valuetypes()) { 687 setLoadExtAction(ISD::EXTLOAD, VT, MVT::f32, Expand); 688 setLoadExtAction(ISD::EXTLOAD, VT, MVT::f16, Expand); 689 } 690 691 // ... or truncating stores 692 setTruncStoreAction(MVT::f64, MVT::f32, Expand); 693 setTruncStoreAction(MVT::f32, MVT::f16, Expand); 694 setTruncStoreAction(MVT::f64, MVT::f16, Expand); 695 696 // ARM does not have i1 sign extending load. 697 for (MVT VT : MVT::integer_valuetypes()) 698 setLoadExtAction(ISD::SEXTLOAD, VT, MVT::i1, Promote); 699 700 // ARM supports all 4 flavors of integer indexed load / store. 701 if (!Subtarget->isThumb1Only()) { 702 for (unsigned im = (unsigned)ISD::PRE_INC; 703 im != (unsigned)ISD::LAST_INDEXED_MODE; ++im) { 704 setIndexedLoadAction(im, MVT::i1, Legal); 705 setIndexedLoadAction(im, MVT::i8, Legal); 706 setIndexedLoadAction(im, MVT::i16, Legal); 707 setIndexedLoadAction(im, MVT::i32, Legal); 708 setIndexedStoreAction(im, MVT::i1, Legal); 709 setIndexedStoreAction(im, MVT::i8, Legal); 710 setIndexedStoreAction(im, MVT::i16, Legal); 711 setIndexedStoreAction(im, MVT::i32, Legal); 712 } 713 } 714 715 setOperationAction(ISD::SADDO, MVT::i32, Custom); 716 setOperationAction(ISD::UADDO, MVT::i32, Custom); 717 setOperationAction(ISD::SSUBO, MVT::i32, Custom); 718 setOperationAction(ISD::USUBO, MVT::i32, Custom); 719 720 // i64 operation support. 721 setOperationAction(ISD::MUL, MVT::i64, Expand); 722 setOperationAction(ISD::MULHU, MVT::i32, Expand); 723 if (Subtarget->isThumb1Only()) { 724 setOperationAction(ISD::UMUL_LOHI, MVT::i32, Expand); 725 setOperationAction(ISD::SMUL_LOHI, MVT::i32, Expand); 726 } 727 if (Subtarget->isThumb1Only() || !Subtarget->hasV6Ops() 728 || (Subtarget->isThumb2() && !Subtarget->hasDSP())) 729 setOperationAction(ISD::MULHS, MVT::i32, Expand); 730 731 setOperationAction(ISD::SHL_PARTS, MVT::i32, Custom); 732 setOperationAction(ISD::SRA_PARTS, MVT::i32, Custom); 733 setOperationAction(ISD::SRL_PARTS, MVT::i32, Custom); 734 setOperationAction(ISD::SRL, MVT::i64, Custom); 735 setOperationAction(ISD::SRA, MVT::i64, Custom); 736 737 if (!Subtarget->isThumb1Only()) { 738 // FIXME: We should do this for Thumb1 as well. 739 setOperationAction(ISD::ADDC, MVT::i32, Custom); 740 setOperationAction(ISD::ADDE, MVT::i32, Custom); 741 setOperationAction(ISD::SUBC, MVT::i32, Custom); 742 setOperationAction(ISD::SUBE, MVT::i32, Custom); 743 } 744 745 if (!Subtarget->isThumb1Only() && Subtarget->hasV6T2Ops()) 746 setOperationAction(ISD::BITREVERSE, MVT::i32, Legal); 747 748 // ARM does not have ROTL. 749 setOperationAction(ISD::ROTL, MVT::i32, Expand); 750 for (MVT VT : MVT::vector_valuetypes()) { 751 setOperationAction(ISD::ROTL, VT, Expand); 752 setOperationAction(ISD::ROTR, VT, Expand); 753 } 754 setOperationAction(ISD::CTTZ, MVT::i32, Custom); 755 setOperationAction(ISD::CTPOP, MVT::i32, Expand); 756 if (!Subtarget->hasV5TOps() || Subtarget->isThumb1Only()) 757 setOperationAction(ISD::CTLZ, MVT::i32, Expand); 758 759 // These just redirect to CTTZ and CTLZ on ARM. 760 setOperationAction(ISD::CTTZ_ZERO_UNDEF , MVT::i32 , Expand); 761 setOperationAction(ISD::CTLZ_ZERO_UNDEF , MVT::i32 , Expand); 762 763 // @llvm.readcyclecounter requires the Performance Monitors extension. 764 // Default to the 0 expansion on unsupported platforms. 765 // FIXME: Technically there are older ARM CPUs that have 766 // implementation-specific ways of obtaining this information. 767 if (Subtarget->hasPerfMon()) 768 setOperationAction(ISD::READCYCLECOUNTER, MVT::i64, Custom); 769 770 // Only ARMv6 has BSWAP. 771 if (!Subtarget->hasV6Ops()) 772 setOperationAction(ISD::BSWAP, MVT::i32, Expand); 773 774 bool hasDivide = Subtarget->isThumb() ? Subtarget->hasDivide() 775 : Subtarget->hasDivideInARMMode(); 776 if (!hasDivide) { 777 // These are expanded into libcalls if the cpu doesn't have HW divider. 778 setOperationAction(ISD::SDIV, MVT::i32, LibCall); 779 setOperationAction(ISD::UDIV, MVT::i32, LibCall); 780 } 781 782 if (Subtarget->isTargetWindows() && !Subtarget->hasDivide()) { 783 setOperationAction(ISD::SDIV, MVT::i32, Custom); 784 setOperationAction(ISD::UDIV, MVT::i32, Custom); 785 786 setOperationAction(ISD::SDIV, MVT::i64, Custom); 787 setOperationAction(ISD::UDIV, MVT::i64, Custom); 788 } 789 790 setOperationAction(ISD::SREM, MVT::i32, Expand); 791 setOperationAction(ISD::UREM, MVT::i32, Expand); 792 // Register based DivRem for AEABI (RTABI 4.2) 793 if (Subtarget->isTargetAEABI() || Subtarget->isTargetAndroid() || 794 Subtarget->isTargetGNUAEABI()) { 795 setOperationAction(ISD::SREM, MVT::i64, Custom); 796 setOperationAction(ISD::UREM, MVT::i64, Custom); 797 798 setLibcallName(RTLIB::SDIVREM_I8, "__aeabi_idivmod"); 799 setLibcallName(RTLIB::SDIVREM_I16, "__aeabi_idivmod"); 800 setLibcallName(RTLIB::SDIVREM_I32, "__aeabi_idivmod"); 801 setLibcallName(RTLIB::SDIVREM_I64, "__aeabi_ldivmod"); 802 setLibcallName(RTLIB::UDIVREM_I8, "__aeabi_uidivmod"); 803 setLibcallName(RTLIB::UDIVREM_I16, "__aeabi_uidivmod"); 804 setLibcallName(RTLIB::UDIVREM_I32, "__aeabi_uidivmod"); 805 setLibcallName(RTLIB::UDIVREM_I64, "__aeabi_uldivmod"); 806 807 setLibcallCallingConv(RTLIB::SDIVREM_I8, CallingConv::ARM_AAPCS); 808 setLibcallCallingConv(RTLIB::SDIVREM_I16, CallingConv::ARM_AAPCS); 809 setLibcallCallingConv(RTLIB::SDIVREM_I32, CallingConv::ARM_AAPCS); 810 setLibcallCallingConv(RTLIB::SDIVREM_I64, CallingConv::ARM_AAPCS); 811 setLibcallCallingConv(RTLIB::UDIVREM_I8, CallingConv::ARM_AAPCS); 812 setLibcallCallingConv(RTLIB::UDIVREM_I16, CallingConv::ARM_AAPCS); 813 setLibcallCallingConv(RTLIB::UDIVREM_I32, CallingConv::ARM_AAPCS); 814 setLibcallCallingConv(RTLIB::UDIVREM_I64, CallingConv::ARM_AAPCS); 815 816 setOperationAction(ISD::SDIVREM, MVT::i32, Custom); 817 setOperationAction(ISD::UDIVREM, MVT::i32, Custom); 818 setOperationAction(ISD::SDIVREM, MVT::i64, Custom); 819 setOperationAction(ISD::UDIVREM, MVT::i64, Custom); 820 } else { 821 setOperationAction(ISD::SDIVREM, MVT::i32, Expand); 822 setOperationAction(ISD::UDIVREM, MVT::i32, Expand); 823 } 824 825 setOperationAction(ISD::GlobalAddress, MVT::i32, Custom); 826 setOperationAction(ISD::ConstantPool, MVT::i32, Custom); 827 setOperationAction(ISD::GlobalTLSAddress, MVT::i32, Custom); 828 setOperationAction(ISD::BlockAddress, MVT::i32, Custom); 829 830 setOperationAction(ISD::TRAP, MVT::Other, Legal); 831 832 // Use the default implementation. 833 setOperationAction(ISD::VASTART, MVT::Other, Custom); 834 setOperationAction(ISD::VAARG, MVT::Other, Expand); 835 setOperationAction(ISD::VACOPY, MVT::Other, Expand); 836 setOperationAction(ISD::VAEND, MVT::Other, Expand); 837 setOperationAction(ISD::STACKSAVE, MVT::Other, Expand); 838 setOperationAction(ISD::STACKRESTORE, MVT::Other, Expand); 839 840 if (Subtarget->getTargetTriple().isWindowsItaniumEnvironment()) 841 setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i32, Custom); 842 else 843 setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i32, Expand); 844 845 // ARMv6 Thumb1 (except for CPUs that support dmb / dsb) and earlier use 846 // the default expansion. 847 InsertFencesForAtomic = false; 848 if (Subtarget->hasAnyDataBarrier() && 849 (!Subtarget->isThumb() || Subtarget->hasV8MBaselineOps())) { 850 // ATOMIC_FENCE needs custom lowering; the others should have been expanded 851 // to ldrex/strex loops already. 852 setOperationAction(ISD::ATOMIC_FENCE, MVT::Other, Custom); 853 if (!Subtarget->isThumb() || !Subtarget->isMClass()) 854 setOperationAction(ISD::ATOMIC_CMP_SWAP, MVT::i64, Custom); 855 856 // On v8, we have particularly efficient implementations of atomic fences 857 // if they can be combined with nearby atomic loads and stores. 858 if (!Subtarget->hasV8Ops() || getTargetMachine().getOptLevel() == 0) { 859 // Automatically insert fences (dmb ish) around ATOMIC_SWAP etc. 860 InsertFencesForAtomic = true; 861 } 862 } else { 863 // If there's anything we can use as a barrier, go through custom lowering 864 // for ATOMIC_FENCE. 865 setOperationAction(ISD::ATOMIC_FENCE, MVT::Other, 866 Subtarget->hasAnyDataBarrier() ? Custom : Expand); 867 868 // Set them all for expansion, which will force libcalls. 869 setOperationAction(ISD::ATOMIC_CMP_SWAP, MVT::i32, Expand); 870 setOperationAction(ISD::ATOMIC_SWAP, MVT::i32, Expand); 871 setOperationAction(ISD::ATOMIC_LOAD_ADD, MVT::i32, Expand); 872 setOperationAction(ISD::ATOMIC_LOAD_SUB, MVT::i32, Expand); 873 setOperationAction(ISD::ATOMIC_LOAD_AND, MVT::i32, Expand); 874 setOperationAction(ISD::ATOMIC_LOAD_OR, MVT::i32, Expand); 875 setOperationAction(ISD::ATOMIC_LOAD_XOR, MVT::i32, Expand); 876 setOperationAction(ISD::ATOMIC_LOAD_NAND, MVT::i32, Expand); 877 setOperationAction(ISD::ATOMIC_LOAD_MIN, MVT::i32, Expand); 878 setOperationAction(ISD::ATOMIC_LOAD_MAX, MVT::i32, Expand); 879 setOperationAction(ISD::ATOMIC_LOAD_UMIN, MVT::i32, Expand); 880 setOperationAction(ISD::ATOMIC_LOAD_UMAX, MVT::i32, Expand); 881 // Mark ATOMIC_LOAD and ATOMIC_STORE custom so we can handle the 882 // Unordered/Monotonic case. 883 setOperationAction(ISD::ATOMIC_LOAD, MVT::i32, Custom); 884 setOperationAction(ISD::ATOMIC_STORE, MVT::i32, Custom); 885 } 886 887 setOperationAction(ISD::PREFETCH, MVT::Other, Custom); 888 889 // Requires SXTB/SXTH, available on v6 and up in both ARM and Thumb modes. 890 if (!Subtarget->hasV6Ops()) { 891 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i16, Expand); 892 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i8, Expand); 893 } 894 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1, Expand); 895 896 if (!Subtarget->useSoftFloat() && Subtarget->hasVFP2() && 897 !Subtarget->isThumb1Only()) { 898 // Turn f64->i64 into VMOVRRD, i64 -> f64 to VMOVDRR 899 // iff target supports vfp2. 900 setOperationAction(ISD::BITCAST, MVT::i64, Custom); 901 setOperationAction(ISD::FLT_ROUNDS_, MVT::i32, Custom); 902 } 903 904 // We want to custom lower some of our intrinsics. 905 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom); 906 setOperationAction(ISD::EH_SJLJ_SETJMP, MVT::i32, Custom); 907 setOperationAction(ISD::EH_SJLJ_LONGJMP, MVT::Other, Custom); 908 setOperationAction(ISD::EH_SJLJ_SETUP_DISPATCH, MVT::Other, Custom); 909 if (Subtarget->useSjLjEH()) 910 setLibcallName(RTLIB::UNWIND_RESUME, "_Unwind_SjLj_Resume"); 911 912 setOperationAction(ISD::SETCC, MVT::i32, Expand); 913 setOperationAction(ISD::SETCC, MVT::f32, Expand); 914 setOperationAction(ISD::SETCC, MVT::f64, Expand); 915 setOperationAction(ISD::SELECT, MVT::i32, Custom); 916 setOperationAction(ISD::SELECT, MVT::f32, Custom); 917 setOperationAction(ISD::SELECT, MVT::f64, Custom); 918 setOperationAction(ISD::SELECT_CC, MVT::i32, Custom); 919 setOperationAction(ISD::SELECT_CC, MVT::f32, Custom); 920 setOperationAction(ISD::SELECT_CC, MVT::f64, Custom); 921 922 // Thumb-1 cannot currently select ARMISD::SUBE. 923 if (!Subtarget->isThumb1Only()) 924 setOperationAction(ISD::SETCCE, MVT::i32, Custom); 925 926 setOperationAction(ISD::BRCOND, MVT::Other, Expand); 927 setOperationAction(ISD::BR_CC, MVT::i32, Custom); 928 setOperationAction(ISD::BR_CC, MVT::f32, Custom); 929 setOperationAction(ISD::BR_CC, MVT::f64, Custom); 930 setOperationAction(ISD::BR_JT, MVT::Other, Custom); 931 932 // We don't support sin/cos/fmod/copysign/pow 933 setOperationAction(ISD::FSIN, MVT::f64, Expand); 934 setOperationAction(ISD::FSIN, MVT::f32, Expand); 935 setOperationAction(ISD::FCOS, MVT::f32, Expand); 936 setOperationAction(ISD::FCOS, MVT::f64, Expand); 937 setOperationAction(ISD::FSINCOS, MVT::f64, Expand); 938 setOperationAction(ISD::FSINCOS, MVT::f32, Expand); 939 setOperationAction(ISD::FREM, MVT::f64, Expand); 940 setOperationAction(ISD::FREM, MVT::f32, Expand); 941 if (!Subtarget->useSoftFloat() && Subtarget->hasVFP2() && 942 !Subtarget->isThumb1Only()) { 943 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Custom); 944 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom); 945 } 946 setOperationAction(ISD::FPOW, MVT::f64, Expand); 947 setOperationAction(ISD::FPOW, MVT::f32, Expand); 948 949 if (!Subtarget->hasVFP4()) { 950 setOperationAction(ISD::FMA, MVT::f64, Expand); 951 setOperationAction(ISD::FMA, MVT::f32, Expand); 952 } 953 954 // Various VFP goodness 955 if (!Subtarget->useSoftFloat() && !Subtarget->isThumb1Only()) { 956 // FP-ARMv8 adds f64 <-> f16 conversion. Before that it should be expanded. 957 if (!Subtarget->hasFPARMv8() || Subtarget->isFPOnlySP()) { 958 setOperationAction(ISD::FP16_TO_FP, MVT::f64, Expand); 959 setOperationAction(ISD::FP_TO_FP16, MVT::f64, Expand); 960 } 961 962 // fp16 is a special v7 extension that adds f16 <-> f32 conversions. 963 if (!Subtarget->hasFP16()) { 964 setOperationAction(ISD::FP16_TO_FP, MVT::f32, Expand); 965 setOperationAction(ISD::FP_TO_FP16, MVT::f32, Expand); 966 } 967 } 968 969 // Combine sin / cos into one node or libcall if possible. 970 if (Subtarget->hasSinCos()) { 971 setLibcallName(RTLIB::SINCOS_F32, "sincosf"); 972 setLibcallName(RTLIB::SINCOS_F64, "sincos"); 973 if (Subtarget->isTargetWatchABI()) { 974 setLibcallCallingConv(RTLIB::SINCOS_F32, CallingConv::ARM_AAPCS_VFP); 975 setLibcallCallingConv(RTLIB::SINCOS_F64, CallingConv::ARM_AAPCS_VFP); 976 } 977 if (Subtarget->isTargetIOS() || Subtarget->isTargetWatchOS()) { 978 // For iOS, we don't want to the normal expansion of a libcall to 979 // sincos. We want to issue a libcall to __sincos_stret. 980 setOperationAction(ISD::FSINCOS, MVT::f64, Custom); 981 setOperationAction(ISD::FSINCOS, MVT::f32, Custom); 982 } 983 } 984 985 // FP-ARMv8 implements a lot of rounding-like FP operations. 986 if (Subtarget->hasFPARMv8()) { 987 setOperationAction(ISD::FFLOOR, MVT::f32, Legal); 988 setOperationAction(ISD::FCEIL, MVT::f32, Legal); 989 setOperationAction(ISD::FROUND, MVT::f32, Legal); 990 setOperationAction(ISD::FTRUNC, MVT::f32, Legal); 991 setOperationAction(ISD::FNEARBYINT, MVT::f32, Legal); 992 setOperationAction(ISD::FRINT, MVT::f32, Legal); 993 setOperationAction(ISD::FMINNUM, MVT::f32, Legal); 994 setOperationAction(ISD::FMAXNUM, MVT::f32, Legal); 995 setOperationAction(ISD::FMINNUM, MVT::v2f32, Legal); 996 setOperationAction(ISD::FMAXNUM, MVT::v2f32, Legal); 997 setOperationAction(ISD::FMINNUM, MVT::v4f32, Legal); 998 setOperationAction(ISD::FMAXNUM, MVT::v4f32, Legal); 999 1000 if (!Subtarget->isFPOnlySP()) { 1001 setOperationAction(ISD::FFLOOR, MVT::f64, Legal); 1002 setOperationAction(ISD::FCEIL, MVT::f64, Legal); 1003 setOperationAction(ISD::FROUND, MVT::f64, Legal); 1004 setOperationAction(ISD::FTRUNC, MVT::f64, Legal); 1005 setOperationAction(ISD::FNEARBYINT, MVT::f64, Legal); 1006 setOperationAction(ISD::FRINT, MVT::f64, Legal); 1007 setOperationAction(ISD::FMINNUM, MVT::f64, Legal); 1008 setOperationAction(ISD::FMAXNUM, MVT::f64, Legal); 1009 } 1010 } 1011 1012 if (Subtarget->hasNEON()) { 1013 // vmin and vmax aren't available in a scalar form, so we use 1014 // a NEON instruction with an undef lane instead. 1015 setOperationAction(ISD::FMINNAN, MVT::f32, Legal); 1016 setOperationAction(ISD::FMAXNAN, MVT::f32, Legal); 1017 setOperationAction(ISD::FMINNAN, MVT::v2f32, Legal); 1018 setOperationAction(ISD::FMAXNAN, MVT::v2f32, Legal); 1019 setOperationAction(ISD::FMINNAN, MVT::v4f32, Legal); 1020 setOperationAction(ISD::FMAXNAN, MVT::v4f32, Legal); 1021 } 1022 1023 // We have target-specific dag combine patterns for the following nodes: 1024 // ARMISD::VMOVRRD - No need to call setTargetDAGCombine 1025 setTargetDAGCombine(ISD::ADD); 1026 setTargetDAGCombine(ISD::SUB); 1027 setTargetDAGCombine(ISD::MUL); 1028 setTargetDAGCombine(ISD::AND); 1029 setTargetDAGCombine(ISD::OR); 1030 setTargetDAGCombine(ISD::XOR); 1031 1032 if (Subtarget->hasV6Ops()) 1033 setTargetDAGCombine(ISD::SRL); 1034 1035 setStackPointerRegisterToSaveRestore(ARM::SP); 1036 1037 if (Subtarget->useSoftFloat() || Subtarget->isThumb1Only() || 1038 !Subtarget->hasVFP2()) 1039 setSchedulingPreference(Sched::RegPressure); 1040 else 1041 setSchedulingPreference(Sched::Hybrid); 1042 1043 //// temporary - rewrite interface to use type 1044 MaxStoresPerMemset = 8; 1045 MaxStoresPerMemsetOptSize = 4; 1046 MaxStoresPerMemcpy = 4; // For @llvm.memcpy -> sequence of stores 1047 MaxStoresPerMemcpyOptSize = 2; 1048 MaxStoresPerMemmove = 4; // For @llvm.memmove -> sequence of stores 1049 MaxStoresPerMemmoveOptSize = 2; 1050 1051 // On ARM arguments smaller than 4 bytes are extended, so all arguments 1052 // are at least 4 bytes aligned. 1053 setMinStackArgumentAlignment(4); 1054 1055 // Prefer likely predicted branches to selects on out-of-order cores. 1056 PredictableSelectIsExpensive = Subtarget->getSchedModel().isOutOfOrder(); 1057 1058 setMinFunctionAlignment(Subtarget->isThumb() ? 1 : 2); 1059 } 1060 1061 bool ARMTargetLowering::useSoftFloat() const { 1062 return Subtarget->useSoftFloat(); 1063 } 1064 1065 // FIXME: It might make sense to define the representative register class as the 1066 // nearest super-register that has a non-null superset. For example, DPR_VFP2 is 1067 // a super-register of SPR, and DPR is a superset if DPR_VFP2. Consequently, 1068 // SPR's representative would be DPR_VFP2. This should work well if register 1069 // pressure tracking were modified such that a register use would increment the 1070 // pressure of the register class's representative and all of it's super 1071 // classes' representatives transitively. We have not implemented this because 1072 // of the difficulty prior to coalescing of modeling operand register classes 1073 // due to the common occurrence of cross class copies and subregister insertions 1074 // and extractions. 1075 std::pair<const TargetRegisterClass *, uint8_t> 1076 ARMTargetLowering::findRepresentativeClass(const TargetRegisterInfo *TRI, 1077 MVT VT) const { 1078 const TargetRegisterClass *RRC = nullptr; 1079 uint8_t Cost = 1; 1080 switch (VT.SimpleTy) { 1081 default: 1082 return TargetLowering::findRepresentativeClass(TRI, VT); 1083 // Use DPR as representative register class for all floating point 1084 // and vector types. Since there are 32 SPR registers and 32 DPR registers so 1085 // the cost is 1 for both f32 and f64. 1086 case MVT::f32: case MVT::f64: case MVT::v8i8: case MVT::v4i16: 1087 case MVT::v2i32: case MVT::v1i64: case MVT::v2f32: 1088 RRC = &ARM::DPRRegClass; 1089 // When NEON is used for SP, only half of the register file is available 1090 // because operations that define both SP and DP results will be constrained 1091 // to the VFP2 class (D0-D15). We currently model this constraint prior to 1092 // coalescing by double-counting the SP regs. See the FIXME above. 1093 if (Subtarget->useNEONForSinglePrecisionFP()) 1094 Cost = 2; 1095 break; 1096 case MVT::v16i8: case MVT::v8i16: case MVT::v4i32: case MVT::v2i64: 1097 case MVT::v4f32: case MVT::v2f64: 1098 RRC = &ARM::DPRRegClass; 1099 Cost = 2; 1100 break; 1101 case MVT::v4i64: 1102 RRC = &ARM::DPRRegClass; 1103 Cost = 4; 1104 break; 1105 case MVT::v8i64: 1106 RRC = &ARM::DPRRegClass; 1107 Cost = 8; 1108 break; 1109 } 1110 return std::make_pair(RRC, Cost); 1111 } 1112 1113 const char *ARMTargetLowering::getTargetNodeName(unsigned Opcode) const { 1114 switch ((ARMISD::NodeType)Opcode) { 1115 case ARMISD::FIRST_NUMBER: break; 1116 case ARMISD::Wrapper: return "ARMISD::Wrapper"; 1117 case ARMISD::WrapperPIC: return "ARMISD::WrapperPIC"; 1118 case ARMISD::WrapperJT: return "ARMISD::WrapperJT"; 1119 case ARMISD::COPY_STRUCT_BYVAL: return "ARMISD::COPY_STRUCT_BYVAL"; 1120 case ARMISD::CALL: return "ARMISD::CALL"; 1121 case ARMISD::CALL_PRED: return "ARMISD::CALL_PRED"; 1122 case ARMISD::CALL_NOLINK: return "ARMISD::CALL_NOLINK"; 1123 case ARMISD::tCALL: return "ARMISD::tCALL"; 1124 case ARMISD::BRCOND: return "ARMISD::BRCOND"; 1125 case ARMISD::BR_JT: return "ARMISD::BR_JT"; 1126 case ARMISD::BR2_JT: return "ARMISD::BR2_JT"; 1127 case ARMISD::RET_FLAG: return "ARMISD::RET_FLAG"; 1128 case ARMISD::INTRET_FLAG: return "ARMISD::INTRET_FLAG"; 1129 case ARMISD::PIC_ADD: return "ARMISD::PIC_ADD"; 1130 case ARMISD::CMP: return "ARMISD::CMP"; 1131 case ARMISD::CMN: return "ARMISD::CMN"; 1132 case ARMISD::CMPZ: return "ARMISD::CMPZ"; 1133 case ARMISD::CMPFP: return "ARMISD::CMPFP"; 1134 case ARMISD::CMPFPw0: return "ARMISD::CMPFPw0"; 1135 case ARMISD::BCC_i64: return "ARMISD::BCC_i64"; 1136 case ARMISD::FMSTAT: return "ARMISD::FMSTAT"; 1137 1138 case ARMISD::CMOV: return "ARMISD::CMOV"; 1139 1140 case ARMISD::SRL_FLAG: return "ARMISD::SRL_FLAG"; 1141 case ARMISD::SRA_FLAG: return "ARMISD::SRA_FLAG"; 1142 case ARMISD::RRX: return "ARMISD::RRX"; 1143 1144 case ARMISD::ADDC: return "ARMISD::ADDC"; 1145 case ARMISD::ADDE: return "ARMISD::ADDE"; 1146 case ARMISD::SUBC: return "ARMISD::SUBC"; 1147 case ARMISD::SUBE: return "ARMISD::SUBE"; 1148 1149 case ARMISD::VMOVRRD: return "ARMISD::VMOVRRD"; 1150 case ARMISD::VMOVDRR: return "ARMISD::VMOVDRR"; 1151 1152 case ARMISD::EH_SJLJ_SETJMP: return "ARMISD::EH_SJLJ_SETJMP"; 1153 case ARMISD::EH_SJLJ_LONGJMP: return "ARMISD::EH_SJLJ_LONGJMP"; 1154 case ARMISD::EH_SJLJ_SETUP_DISPATCH: return "ARMISD::EH_SJLJ_SETUP_DISPATCH"; 1155 1156 case ARMISD::TC_RETURN: return "ARMISD::TC_RETURN"; 1157 1158 case ARMISD::THREAD_POINTER:return "ARMISD::THREAD_POINTER"; 1159 1160 case ARMISD::DYN_ALLOC: return "ARMISD::DYN_ALLOC"; 1161 1162 case ARMISD::MEMBARRIER_MCR: return "ARMISD::MEMBARRIER_MCR"; 1163 1164 case ARMISD::PRELOAD: return "ARMISD::PRELOAD"; 1165 1166 case ARMISD::WIN__CHKSTK: return "ARMISD:::WIN__CHKSTK"; 1167 case ARMISD::WIN__DBZCHK: return "ARMISD::WIN__DBZCHK"; 1168 1169 case ARMISD::VCEQ: return "ARMISD::VCEQ"; 1170 case ARMISD::VCEQZ: return "ARMISD::VCEQZ"; 1171 case ARMISD::VCGE: return "ARMISD::VCGE"; 1172 case ARMISD::VCGEZ: return "ARMISD::VCGEZ"; 1173 case ARMISD::VCLEZ: return "ARMISD::VCLEZ"; 1174 case ARMISD::VCGEU: return "ARMISD::VCGEU"; 1175 case ARMISD::VCGT: return "ARMISD::VCGT"; 1176 case ARMISD::VCGTZ: return "ARMISD::VCGTZ"; 1177 case ARMISD::VCLTZ: return "ARMISD::VCLTZ"; 1178 case ARMISD::VCGTU: return "ARMISD::VCGTU"; 1179 case ARMISD::VTST: return "ARMISD::VTST"; 1180 1181 case ARMISD::VSHL: return "ARMISD::VSHL"; 1182 case ARMISD::VSHRs: return "ARMISD::VSHRs"; 1183 case ARMISD::VSHRu: return "ARMISD::VSHRu"; 1184 case ARMISD::VRSHRs: return "ARMISD::VRSHRs"; 1185 case ARMISD::VRSHRu: return "ARMISD::VRSHRu"; 1186 case ARMISD::VRSHRN: return "ARMISD::VRSHRN"; 1187 case ARMISD::VQSHLs: return "ARMISD::VQSHLs"; 1188 case ARMISD::VQSHLu: return "ARMISD::VQSHLu"; 1189 case ARMISD::VQSHLsu: return "ARMISD::VQSHLsu"; 1190 case ARMISD::VQSHRNs: return "ARMISD::VQSHRNs"; 1191 case ARMISD::VQSHRNu: return "ARMISD::VQSHRNu"; 1192 case ARMISD::VQSHRNsu: return "ARMISD::VQSHRNsu"; 1193 case ARMISD::VQRSHRNs: return "ARMISD::VQRSHRNs"; 1194 case ARMISD::VQRSHRNu: return "ARMISD::VQRSHRNu"; 1195 case ARMISD::VQRSHRNsu: return "ARMISD::VQRSHRNsu"; 1196 case ARMISD::VSLI: return "ARMISD::VSLI"; 1197 case ARMISD::VSRI: return "ARMISD::VSRI"; 1198 case ARMISD::VGETLANEu: return "ARMISD::VGETLANEu"; 1199 case ARMISD::VGETLANEs: return "ARMISD::VGETLANEs"; 1200 case ARMISD::VMOVIMM: return "ARMISD::VMOVIMM"; 1201 case ARMISD::VMVNIMM: return "ARMISD::VMVNIMM"; 1202 case ARMISD::VMOVFPIMM: return "ARMISD::VMOVFPIMM"; 1203 case ARMISD::VDUP: return "ARMISD::VDUP"; 1204 case ARMISD::VDUPLANE: return "ARMISD::VDUPLANE"; 1205 case ARMISD::VEXT: return "ARMISD::VEXT"; 1206 case ARMISD::VREV64: return "ARMISD::VREV64"; 1207 case ARMISD::VREV32: return "ARMISD::VREV32"; 1208 case ARMISD::VREV16: return "ARMISD::VREV16"; 1209 case ARMISD::VZIP: return "ARMISD::VZIP"; 1210 case ARMISD::VUZP: return "ARMISD::VUZP"; 1211 case ARMISD::VTRN: return "ARMISD::VTRN"; 1212 case ARMISD::VTBL1: return "ARMISD::VTBL1"; 1213 case ARMISD::VTBL2: return "ARMISD::VTBL2"; 1214 case ARMISD::VMULLs: return "ARMISD::VMULLs"; 1215 case ARMISD::VMULLu: return "ARMISD::VMULLu"; 1216 case ARMISD::UMLAL: return "ARMISD::UMLAL"; 1217 case ARMISD::SMLAL: return "ARMISD::SMLAL"; 1218 case ARMISD::BUILD_VECTOR: return "ARMISD::BUILD_VECTOR"; 1219 case ARMISD::BFI: return "ARMISD::BFI"; 1220 case ARMISD::VORRIMM: return "ARMISD::VORRIMM"; 1221 case ARMISD::VBICIMM: return "ARMISD::VBICIMM"; 1222 case ARMISD::VBSL: return "ARMISD::VBSL"; 1223 case ARMISD::MEMCPY: return "ARMISD::MEMCPY"; 1224 case ARMISD::VLD2DUP: return "ARMISD::VLD2DUP"; 1225 case ARMISD::VLD3DUP: return "ARMISD::VLD3DUP"; 1226 case ARMISD::VLD4DUP: return "ARMISD::VLD4DUP"; 1227 case ARMISD::VLD1_UPD: return "ARMISD::VLD1_UPD"; 1228 case ARMISD::VLD2_UPD: return "ARMISD::VLD2_UPD"; 1229 case ARMISD::VLD3_UPD: return "ARMISD::VLD3_UPD"; 1230 case ARMISD::VLD4_UPD: return "ARMISD::VLD4_UPD"; 1231 case ARMISD::VLD2LN_UPD: return "ARMISD::VLD2LN_UPD"; 1232 case ARMISD::VLD3LN_UPD: return "ARMISD::VLD3LN_UPD"; 1233 case ARMISD::VLD4LN_UPD: return "ARMISD::VLD4LN_UPD"; 1234 case ARMISD::VLD2DUP_UPD: return "ARMISD::VLD2DUP_UPD"; 1235 case ARMISD::VLD3DUP_UPD: return "ARMISD::VLD3DUP_UPD"; 1236 case ARMISD::VLD4DUP_UPD: return "ARMISD::VLD4DUP_UPD"; 1237 case ARMISD::VST1_UPD: return "ARMISD::VST1_UPD"; 1238 case ARMISD::VST2_UPD: return "ARMISD::VST2_UPD"; 1239 case ARMISD::VST3_UPD: return "ARMISD::VST3_UPD"; 1240 case ARMISD::VST4_UPD: return "ARMISD::VST4_UPD"; 1241 case ARMISD::VST2LN_UPD: return "ARMISD::VST2LN_UPD"; 1242 case ARMISD::VST3LN_UPD: return "ARMISD::VST3LN_UPD"; 1243 case ARMISD::VST4LN_UPD: return "ARMISD::VST4LN_UPD"; 1244 } 1245 return nullptr; 1246 } 1247 1248 EVT ARMTargetLowering::getSetCCResultType(const DataLayout &DL, LLVMContext &, 1249 EVT VT) const { 1250 if (!VT.isVector()) 1251 return getPointerTy(DL); 1252 return VT.changeVectorElementTypeToInteger(); 1253 } 1254 1255 /// getRegClassFor - Return the register class that should be used for the 1256 /// specified value type. 1257 const TargetRegisterClass *ARMTargetLowering::getRegClassFor(MVT VT) const { 1258 // Map v4i64 to QQ registers but do not make the type legal. Similarly map 1259 // v8i64 to QQQQ registers. v4i64 and v8i64 are only used for REG_SEQUENCE to 1260 // load / store 4 to 8 consecutive D registers. 1261 if (Subtarget->hasNEON()) { 1262 if (VT == MVT::v4i64) 1263 return &ARM::QQPRRegClass; 1264 if (VT == MVT::v8i64) 1265 return &ARM::QQQQPRRegClass; 1266 } 1267 return TargetLowering::getRegClassFor(VT); 1268 } 1269 1270 // memcpy, and other memory intrinsics, typically tries to use LDM/STM if the 1271 // source/dest is aligned and the copy size is large enough. We therefore want 1272 // to align such objects passed to memory intrinsics. 1273 bool ARMTargetLowering::shouldAlignPointerArgs(CallInst *CI, unsigned &MinSize, 1274 unsigned &PrefAlign) const { 1275 if (!isa<MemIntrinsic>(CI)) 1276 return false; 1277 MinSize = 8; 1278 // On ARM11 onwards (excluding M class) 8-byte aligned LDM is typically 1 1279 // cycle faster than 4-byte aligned LDM. 1280 PrefAlign = (Subtarget->hasV6Ops() && !Subtarget->isMClass() ? 8 : 4); 1281 return true; 1282 } 1283 1284 // Create a fast isel object. 1285 FastISel * 1286 ARMTargetLowering::createFastISel(FunctionLoweringInfo &funcInfo, 1287 const TargetLibraryInfo *libInfo) const { 1288 return ARM::createFastISel(funcInfo, libInfo); 1289 } 1290 1291 Sched::Preference ARMTargetLowering::getSchedulingPreference(SDNode *N) const { 1292 unsigned NumVals = N->getNumValues(); 1293 if (!NumVals) 1294 return Sched::RegPressure; 1295 1296 for (unsigned i = 0; i != NumVals; ++i) { 1297 EVT VT = N->getValueType(i); 1298 if (VT == MVT::Glue || VT == MVT::Other) 1299 continue; 1300 if (VT.isFloatingPoint() || VT.isVector()) 1301 return Sched::ILP; 1302 } 1303 1304 if (!N->isMachineOpcode()) 1305 return Sched::RegPressure; 1306 1307 // Load are scheduled for latency even if there instruction itinerary 1308 // is not available. 1309 const TargetInstrInfo *TII = Subtarget->getInstrInfo(); 1310 const MCInstrDesc &MCID = TII->get(N->getMachineOpcode()); 1311 1312 if (MCID.getNumDefs() == 0) 1313 return Sched::RegPressure; 1314 if (!Itins->isEmpty() && 1315 Itins->getOperandCycle(MCID.getSchedClass(), 0) > 2) 1316 return Sched::ILP; 1317 1318 return Sched::RegPressure; 1319 } 1320 1321 //===----------------------------------------------------------------------===// 1322 // Lowering Code 1323 //===----------------------------------------------------------------------===// 1324 1325 /// IntCCToARMCC - Convert a DAG integer condition code to an ARM CC 1326 static ARMCC::CondCodes IntCCToARMCC(ISD::CondCode CC) { 1327 switch (CC) { 1328 default: llvm_unreachable("Unknown condition code!"); 1329 case ISD::SETNE: return ARMCC::NE; 1330 case ISD::SETEQ: return ARMCC::EQ; 1331 case ISD::SETGT: return ARMCC::GT; 1332 case ISD::SETGE: return ARMCC::GE; 1333 case ISD::SETLT: return ARMCC::LT; 1334 case ISD::SETLE: return ARMCC::LE; 1335 case ISD::SETUGT: return ARMCC::HI; 1336 case ISD::SETUGE: return ARMCC::HS; 1337 case ISD::SETULT: return ARMCC::LO; 1338 case ISD::SETULE: return ARMCC::LS; 1339 } 1340 } 1341 1342 /// FPCCToARMCC - Convert a DAG fp condition code to an ARM CC. 1343 static void FPCCToARMCC(ISD::CondCode CC, ARMCC::CondCodes &CondCode, 1344 ARMCC::CondCodes &CondCode2) { 1345 CondCode2 = ARMCC::AL; 1346 switch (CC) { 1347 default: llvm_unreachable("Unknown FP condition!"); 1348 case ISD::SETEQ: 1349 case ISD::SETOEQ: CondCode = ARMCC::EQ; break; 1350 case ISD::SETGT: 1351 case ISD::SETOGT: CondCode = ARMCC::GT; break; 1352 case ISD::SETGE: 1353 case ISD::SETOGE: CondCode = ARMCC::GE; break; 1354 case ISD::SETOLT: CondCode = ARMCC::MI; break; 1355 case ISD::SETOLE: CondCode = ARMCC::LS; break; 1356 case ISD::SETONE: CondCode = ARMCC::MI; CondCode2 = ARMCC::GT; break; 1357 case ISD::SETO: CondCode = ARMCC::VC; break; 1358 case ISD::SETUO: CondCode = ARMCC::VS; break; 1359 case ISD::SETUEQ: CondCode = ARMCC::EQ; CondCode2 = ARMCC::VS; break; 1360 case ISD::SETUGT: CondCode = ARMCC::HI; break; 1361 case ISD::SETUGE: CondCode = ARMCC::PL; break; 1362 case ISD::SETLT: 1363 case ISD::SETULT: CondCode = ARMCC::LT; break; 1364 case ISD::SETLE: 1365 case ISD::SETULE: CondCode = ARMCC::LE; break; 1366 case ISD::SETNE: 1367 case ISD::SETUNE: CondCode = ARMCC::NE; break; 1368 } 1369 } 1370 1371 //===----------------------------------------------------------------------===// 1372 // Calling Convention Implementation 1373 //===----------------------------------------------------------------------===// 1374 1375 #include "ARMGenCallingConv.inc" 1376 1377 /// getEffectiveCallingConv - Get the effective calling convention, taking into 1378 /// account presence of floating point hardware and calling convention 1379 /// limitations, such as support for variadic functions. 1380 CallingConv::ID 1381 ARMTargetLowering::getEffectiveCallingConv(CallingConv::ID CC, 1382 bool isVarArg) const { 1383 switch (CC) { 1384 default: 1385 llvm_unreachable("Unsupported calling convention"); 1386 case CallingConv::ARM_AAPCS: 1387 case CallingConv::ARM_APCS: 1388 case CallingConv::GHC: 1389 return CC; 1390 case CallingConv::PreserveMost: 1391 return CallingConv::PreserveMost; 1392 case CallingConv::ARM_AAPCS_VFP: 1393 case CallingConv::Swift: 1394 return isVarArg ? CallingConv::ARM_AAPCS : CallingConv::ARM_AAPCS_VFP; 1395 case CallingConv::C: 1396 if (!Subtarget->isAAPCS_ABI()) 1397 return CallingConv::ARM_APCS; 1398 else if (Subtarget->hasVFP2() && !Subtarget->isThumb1Only() && 1399 getTargetMachine().Options.FloatABIType == FloatABI::Hard && 1400 !isVarArg) 1401 return CallingConv::ARM_AAPCS_VFP; 1402 else 1403 return CallingConv::ARM_AAPCS; 1404 case CallingConv::Fast: 1405 case CallingConv::CXX_FAST_TLS: 1406 if (!Subtarget->isAAPCS_ABI()) { 1407 if (Subtarget->hasVFP2() && !Subtarget->isThumb1Only() && !isVarArg) 1408 return CallingConv::Fast; 1409 return CallingConv::ARM_APCS; 1410 } else if (Subtarget->hasVFP2() && !Subtarget->isThumb1Only() && !isVarArg) 1411 return CallingConv::ARM_AAPCS_VFP; 1412 else 1413 return CallingConv::ARM_AAPCS; 1414 } 1415 } 1416 1417 /// CCAssignFnForNode - Selects the correct CCAssignFn for the given 1418 /// CallingConvention. 1419 CCAssignFn *ARMTargetLowering::CCAssignFnForNode(CallingConv::ID CC, 1420 bool Return, 1421 bool isVarArg) const { 1422 switch (getEffectiveCallingConv(CC, isVarArg)) { 1423 default: 1424 llvm_unreachable("Unsupported calling convention"); 1425 case CallingConv::ARM_APCS: 1426 return (Return ? RetCC_ARM_APCS : CC_ARM_APCS); 1427 case CallingConv::ARM_AAPCS: 1428 return (Return ? RetCC_ARM_AAPCS : CC_ARM_AAPCS); 1429 case CallingConv::ARM_AAPCS_VFP: 1430 return (Return ? RetCC_ARM_AAPCS_VFP : CC_ARM_AAPCS_VFP); 1431 case CallingConv::Fast: 1432 return (Return ? RetFastCC_ARM_APCS : FastCC_ARM_APCS); 1433 case CallingConv::GHC: 1434 return (Return ? RetCC_ARM_APCS : CC_ARM_APCS_GHC); 1435 case CallingConv::PreserveMost: 1436 return (Return ? RetCC_ARM_AAPCS : CC_ARM_AAPCS); 1437 } 1438 } 1439 1440 /// LowerCallResult - Lower the result values of a call into the 1441 /// appropriate copies out of appropriate physical registers. 1442 SDValue 1443 ARMTargetLowering::LowerCallResult(SDValue Chain, SDValue InFlag, 1444 CallingConv::ID CallConv, bool isVarArg, 1445 const SmallVectorImpl<ISD::InputArg> &Ins, 1446 SDLoc dl, SelectionDAG &DAG, 1447 SmallVectorImpl<SDValue> &InVals, 1448 bool isThisReturn, SDValue ThisVal) const { 1449 1450 // Assign locations to each value returned by this call. 1451 SmallVector<CCValAssign, 16> RVLocs; 1452 ARMCCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs, 1453 *DAG.getContext(), Call); 1454 CCInfo.AnalyzeCallResult(Ins, 1455 CCAssignFnForNode(CallConv, /* Return*/ true, 1456 isVarArg)); 1457 1458 // Copy all of the result registers out of their specified physreg. 1459 for (unsigned i = 0; i != RVLocs.size(); ++i) { 1460 CCValAssign VA = RVLocs[i]; 1461 1462 // Pass 'this' value directly from the argument to return value, to avoid 1463 // reg unit interference 1464 if (i == 0 && isThisReturn) { 1465 assert(!VA.needsCustom() && VA.getLocVT() == MVT::i32 && 1466 "unexpected return calling convention register assignment"); 1467 InVals.push_back(ThisVal); 1468 continue; 1469 } 1470 1471 SDValue Val; 1472 if (VA.needsCustom()) { 1473 // Handle f64 or half of a v2f64. 1474 SDValue Lo = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32, 1475 InFlag); 1476 Chain = Lo.getValue(1); 1477 InFlag = Lo.getValue(2); 1478 VA = RVLocs[++i]; // skip ahead to next loc 1479 SDValue Hi = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32, 1480 InFlag); 1481 Chain = Hi.getValue(1); 1482 InFlag = Hi.getValue(2); 1483 if (!Subtarget->isLittle()) 1484 std::swap (Lo, Hi); 1485 Val = DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi); 1486 1487 if (VA.getLocVT() == MVT::v2f64) { 1488 SDValue Vec = DAG.getNode(ISD::UNDEF, dl, MVT::v2f64); 1489 Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Vec, Val, 1490 DAG.getConstant(0, dl, MVT::i32)); 1491 1492 VA = RVLocs[++i]; // skip ahead to next loc 1493 Lo = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32, InFlag); 1494 Chain = Lo.getValue(1); 1495 InFlag = Lo.getValue(2); 1496 VA = RVLocs[++i]; // skip ahead to next loc 1497 Hi = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32, InFlag); 1498 Chain = Hi.getValue(1); 1499 InFlag = Hi.getValue(2); 1500 if (!Subtarget->isLittle()) 1501 std::swap (Lo, Hi); 1502 Val = DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi); 1503 Val = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Vec, Val, 1504 DAG.getConstant(1, dl, MVT::i32)); 1505 } 1506 } else { 1507 Val = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), VA.getLocVT(), 1508 InFlag); 1509 Chain = Val.getValue(1); 1510 InFlag = Val.getValue(2); 1511 } 1512 1513 switch (VA.getLocInfo()) { 1514 default: llvm_unreachable("Unknown loc info!"); 1515 case CCValAssign::Full: break; 1516 case CCValAssign::BCvt: 1517 Val = DAG.getNode(ISD::BITCAST, dl, VA.getValVT(), Val); 1518 break; 1519 } 1520 1521 InVals.push_back(Val); 1522 } 1523 1524 return Chain; 1525 } 1526 1527 /// LowerMemOpCallTo - Store the argument to the stack. 1528 SDValue 1529 ARMTargetLowering::LowerMemOpCallTo(SDValue Chain, 1530 SDValue StackPtr, SDValue Arg, 1531 SDLoc dl, SelectionDAG &DAG, 1532 const CCValAssign &VA, 1533 ISD::ArgFlagsTy Flags) const { 1534 unsigned LocMemOffset = VA.getLocMemOffset(); 1535 SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset, dl); 1536 PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(DAG.getDataLayout()), 1537 StackPtr, PtrOff); 1538 return DAG.getStore( 1539 Chain, dl, Arg, PtrOff, 1540 MachinePointerInfo::getStack(DAG.getMachineFunction(), LocMemOffset), 1541 false, false, 0); 1542 } 1543 1544 void ARMTargetLowering::PassF64ArgInRegs(SDLoc dl, SelectionDAG &DAG, 1545 SDValue Chain, SDValue &Arg, 1546 RegsToPassVector &RegsToPass, 1547 CCValAssign &VA, CCValAssign &NextVA, 1548 SDValue &StackPtr, 1549 SmallVectorImpl<SDValue> &MemOpChains, 1550 ISD::ArgFlagsTy Flags) const { 1551 1552 SDValue fmrrd = DAG.getNode(ARMISD::VMOVRRD, dl, 1553 DAG.getVTList(MVT::i32, MVT::i32), Arg); 1554 unsigned id = Subtarget->isLittle() ? 0 : 1; 1555 RegsToPass.push_back(std::make_pair(VA.getLocReg(), fmrrd.getValue(id))); 1556 1557 if (NextVA.isRegLoc()) 1558 RegsToPass.push_back(std::make_pair(NextVA.getLocReg(), fmrrd.getValue(1-id))); 1559 else { 1560 assert(NextVA.isMemLoc()); 1561 if (!StackPtr.getNode()) 1562 StackPtr = DAG.getCopyFromReg(Chain, dl, ARM::SP, 1563 getPointerTy(DAG.getDataLayout())); 1564 1565 MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, fmrrd.getValue(1-id), 1566 dl, DAG, NextVA, 1567 Flags)); 1568 } 1569 } 1570 1571 /// LowerCall - Lowering a call into a callseq_start <- 1572 /// ARMISD:CALL <- callseq_end chain. Also add input and output parameter 1573 /// nodes. 1574 SDValue 1575 ARMTargetLowering::LowerCall(TargetLowering::CallLoweringInfo &CLI, 1576 SmallVectorImpl<SDValue> &InVals) const { 1577 SelectionDAG &DAG = CLI.DAG; 1578 SDLoc &dl = CLI.DL; 1579 SmallVectorImpl<ISD::OutputArg> &Outs = CLI.Outs; 1580 SmallVectorImpl<SDValue> &OutVals = CLI.OutVals; 1581 SmallVectorImpl<ISD::InputArg> &Ins = CLI.Ins; 1582 SDValue Chain = CLI.Chain; 1583 SDValue Callee = CLI.Callee; 1584 bool &isTailCall = CLI.IsTailCall; 1585 CallingConv::ID CallConv = CLI.CallConv; 1586 bool doesNotRet = CLI.DoesNotReturn; 1587 bool isVarArg = CLI.IsVarArg; 1588 1589 MachineFunction &MF = DAG.getMachineFunction(); 1590 bool isStructRet = (Outs.empty()) ? false : Outs[0].Flags.isSRet(); 1591 bool isThisReturn = false; 1592 bool isSibCall = false; 1593 auto Attr = MF.getFunction()->getFnAttribute("disable-tail-calls"); 1594 1595 // Disable tail calls if they're not supported. 1596 if (!Subtarget->supportsTailCall() || Attr.getValueAsString() == "true") 1597 isTailCall = false; 1598 1599 if (isTailCall) { 1600 // Check if it's really possible to do a tail call. 1601 isTailCall = IsEligibleForTailCallOptimization(Callee, CallConv, 1602 isVarArg, isStructRet, MF.getFunction()->hasStructRetAttr(), 1603 Outs, OutVals, Ins, DAG); 1604 if (!isTailCall && CLI.CS && CLI.CS->isMustTailCall()) 1605 report_fatal_error("failed to perform tail call elimination on a call " 1606 "site marked musttail"); 1607 // We don't support GuaranteedTailCallOpt for ARM, only automatically 1608 // detected sibcalls. 1609 if (isTailCall) { 1610 ++NumTailCalls; 1611 isSibCall = true; 1612 } 1613 } 1614 1615 // Analyze operands of the call, assigning locations to each operand. 1616 SmallVector<CCValAssign, 16> ArgLocs; 1617 ARMCCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), ArgLocs, 1618 *DAG.getContext(), Call); 1619 CCInfo.AnalyzeCallOperands(Outs, 1620 CCAssignFnForNode(CallConv, /* Return*/ false, 1621 isVarArg)); 1622 1623 // Get a count of how many bytes are to be pushed on the stack. 1624 unsigned NumBytes = CCInfo.getNextStackOffset(); 1625 1626 // For tail calls, memory operands are available in our caller's stack. 1627 if (isSibCall) 1628 NumBytes = 0; 1629 1630 // Adjust the stack pointer for the new arguments... 1631 // These operations are automatically eliminated by the prolog/epilog pass 1632 if (!isSibCall) 1633 Chain = DAG.getCALLSEQ_START(Chain, 1634 DAG.getIntPtrConstant(NumBytes, dl, true), dl); 1635 1636 SDValue StackPtr = 1637 DAG.getCopyFromReg(Chain, dl, ARM::SP, getPointerTy(DAG.getDataLayout())); 1638 1639 RegsToPassVector RegsToPass; 1640 SmallVector<SDValue, 8> MemOpChains; 1641 1642 // Walk the register/memloc assignments, inserting copies/loads. In the case 1643 // of tail call optimization, arguments are handled later. 1644 for (unsigned i = 0, realArgIdx = 0, e = ArgLocs.size(); 1645 i != e; 1646 ++i, ++realArgIdx) { 1647 CCValAssign &VA = ArgLocs[i]; 1648 SDValue Arg = OutVals[realArgIdx]; 1649 ISD::ArgFlagsTy Flags = Outs[realArgIdx].Flags; 1650 bool isByVal = Flags.isByVal(); 1651 1652 // Promote the value if needed. 1653 switch (VA.getLocInfo()) { 1654 default: llvm_unreachable("Unknown loc info!"); 1655 case CCValAssign::Full: break; 1656 case CCValAssign::SExt: 1657 Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), Arg); 1658 break; 1659 case CCValAssign::ZExt: 1660 Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, VA.getLocVT(), Arg); 1661 break; 1662 case CCValAssign::AExt: 1663 Arg = DAG.getNode(ISD::ANY_EXTEND, dl, VA.getLocVT(), Arg); 1664 break; 1665 case CCValAssign::BCvt: 1666 Arg = DAG.getNode(ISD::BITCAST, dl, VA.getLocVT(), Arg); 1667 break; 1668 } 1669 1670 // f64 and v2f64 might be passed in i32 pairs and must be split into pieces 1671 if (VA.needsCustom()) { 1672 if (VA.getLocVT() == MVT::v2f64) { 1673 SDValue Op0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg, 1674 DAG.getConstant(0, dl, MVT::i32)); 1675 SDValue Op1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg, 1676 DAG.getConstant(1, dl, MVT::i32)); 1677 1678 PassF64ArgInRegs(dl, DAG, Chain, Op0, RegsToPass, 1679 VA, ArgLocs[++i], StackPtr, MemOpChains, Flags); 1680 1681 VA = ArgLocs[++i]; // skip ahead to next loc 1682 if (VA.isRegLoc()) { 1683 PassF64ArgInRegs(dl, DAG, Chain, Op1, RegsToPass, 1684 VA, ArgLocs[++i], StackPtr, MemOpChains, Flags); 1685 } else { 1686 assert(VA.isMemLoc()); 1687 1688 MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, Op1, 1689 dl, DAG, VA, Flags)); 1690 } 1691 } else { 1692 PassF64ArgInRegs(dl, DAG, Chain, Arg, RegsToPass, VA, ArgLocs[++i], 1693 StackPtr, MemOpChains, Flags); 1694 } 1695 } else if (VA.isRegLoc()) { 1696 if (realArgIdx == 0 && Flags.isReturned() && Outs[0].VT == MVT::i32) { 1697 assert(VA.getLocVT() == MVT::i32 && 1698 "unexpected calling convention register assignment"); 1699 assert(!Ins.empty() && Ins[0].VT == MVT::i32 && 1700 "unexpected use of 'returned'"); 1701 isThisReturn = true; 1702 } 1703 RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg)); 1704 } else if (isByVal) { 1705 assert(VA.isMemLoc()); 1706 unsigned offset = 0; 1707 1708 // True if this byval aggregate will be split between registers 1709 // and memory. 1710 unsigned ByValArgsCount = CCInfo.getInRegsParamsCount(); 1711 unsigned CurByValIdx = CCInfo.getInRegsParamsProcessed(); 1712 1713 if (CurByValIdx < ByValArgsCount) { 1714 1715 unsigned RegBegin, RegEnd; 1716 CCInfo.getInRegsParamInfo(CurByValIdx, RegBegin, RegEnd); 1717 1718 EVT PtrVT = 1719 DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout()); 1720 unsigned int i, j; 1721 for (i = 0, j = RegBegin; j < RegEnd; i++, j++) { 1722 SDValue Const = DAG.getConstant(4*i, dl, MVT::i32); 1723 SDValue AddArg = DAG.getNode(ISD::ADD, dl, PtrVT, Arg, Const); 1724 SDValue Load = DAG.getLoad(PtrVT, dl, Chain, AddArg, 1725 MachinePointerInfo(), 1726 false, false, false, 1727 DAG.InferPtrAlignment(AddArg)); 1728 MemOpChains.push_back(Load.getValue(1)); 1729 RegsToPass.push_back(std::make_pair(j, Load)); 1730 } 1731 1732 // If parameter size outsides register area, "offset" value 1733 // helps us to calculate stack slot for remained part properly. 1734 offset = RegEnd - RegBegin; 1735 1736 CCInfo.nextInRegsParam(); 1737 } 1738 1739 if (Flags.getByValSize() > 4*offset) { 1740 auto PtrVT = getPointerTy(DAG.getDataLayout()); 1741 unsigned LocMemOffset = VA.getLocMemOffset(); 1742 SDValue StkPtrOff = DAG.getIntPtrConstant(LocMemOffset, dl); 1743 SDValue Dst = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, StkPtrOff); 1744 SDValue SrcOffset = DAG.getIntPtrConstant(4*offset, dl); 1745 SDValue Src = DAG.getNode(ISD::ADD, dl, PtrVT, Arg, SrcOffset); 1746 SDValue SizeNode = DAG.getConstant(Flags.getByValSize() - 4*offset, dl, 1747 MVT::i32); 1748 SDValue AlignNode = DAG.getConstant(Flags.getByValAlign(), dl, 1749 MVT::i32); 1750 1751 SDVTList VTs = DAG.getVTList(MVT::Other, MVT::Glue); 1752 SDValue Ops[] = { Chain, Dst, Src, SizeNode, AlignNode}; 1753 MemOpChains.push_back(DAG.getNode(ARMISD::COPY_STRUCT_BYVAL, dl, VTs, 1754 Ops)); 1755 } 1756 } else if (!isSibCall) { 1757 assert(VA.isMemLoc()); 1758 1759 MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, Arg, 1760 dl, DAG, VA, Flags)); 1761 } 1762 } 1763 1764 if (!MemOpChains.empty()) 1765 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains); 1766 1767 // Build a sequence of copy-to-reg nodes chained together with token chain 1768 // and flag operands which copy the outgoing args into the appropriate regs. 1769 SDValue InFlag; 1770 // Tail call byval lowering might overwrite argument registers so in case of 1771 // tail call optimization the copies to registers are lowered later. 1772 if (!isTailCall) 1773 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) { 1774 Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first, 1775 RegsToPass[i].second, InFlag); 1776 InFlag = Chain.getValue(1); 1777 } 1778 1779 // For tail calls lower the arguments to the 'real' stack slot. 1780 if (isTailCall) { 1781 // Force all the incoming stack arguments to be loaded from the stack 1782 // before any new outgoing arguments are stored to the stack, because the 1783 // outgoing stack slots may alias the incoming argument stack slots, and 1784 // the alias isn't otherwise explicit. This is slightly more conservative 1785 // than necessary, because it means that each store effectively depends 1786 // on every argument instead of just those arguments it would clobber. 1787 1788 // Do not flag preceding copytoreg stuff together with the following stuff. 1789 InFlag = SDValue(); 1790 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) { 1791 Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first, 1792 RegsToPass[i].second, InFlag); 1793 InFlag = Chain.getValue(1); 1794 } 1795 InFlag = SDValue(); 1796 } 1797 1798 // If the callee is a GlobalAddress/ExternalSymbol node (quite common, every 1799 // direct call is) turn it into a TargetGlobalAddress/TargetExternalSymbol 1800 // node so that legalize doesn't hack it. 1801 bool isDirect = false; 1802 bool isARMFunc = false; 1803 bool isLocalARMFunc = false; 1804 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>(); 1805 auto PtrVt = getPointerTy(DAG.getDataLayout()); 1806 1807 if (Subtarget->genLongCalls()) { 1808 assert((Subtarget->isTargetWindows() || 1809 getTargetMachine().getRelocationModel() == Reloc::Static) && 1810 "long-calls with non-static relocation model!"); 1811 // Handle a global address or an external symbol. If it's not one of 1812 // those, the target's already in a register, so we don't need to do 1813 // anything extra. 1814 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) { 1815 const GlobalValue *GV = G->getGlobal(); 1816 // Create a constant pool entry for the callee address 1817 unsigned ARMPCLabelIndex = AFI->createPICLabelUId(); 1818 ARMConstantPoolValue *CPV = 1819 ARMConstantPoolConstant::Create(GV, ARMPCLabelIndex, ARMCP::CPValue, 0); 1820 1821 // Get the address of the callee into a register 1822 SDValue CPAddr = DAG.getTargetConstantPool(CPV, PtrVt, 4); 1823 CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr); 1824 Callee = DAG.getLoad( 1825 PtrVt, dl, DAG.getEntryNode(), CPAddr, 1826 MachinePointerInfo::getConstantPool(DAG.getMachineFunction()), false, 1827 false, false, 0); 1828 } else if (ExternalSymbolSDNode *S=dyn_cast<ExternalSymbolSDNode>(Callee)) { 1829 const char *Sym = S->getSymbol(); 1830 1831 // Create a constant pool entry for the callee address 1832 unsigned ARMPCLabelIndex = AFI->createPICLabelUId(); 1833 ARMConstantPoolValue *CPV = 1834 ARMConstantPoolSymbol::Create(*DAG.getContext(), Sym, 1835 ARMPCLabelIndex, 0); 1836 // Get the address of the callee into a register 1837 SDValue CPAddr = DAG.getTargetConstantPool(CPV, PtrVt, 4); 1838 CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr); 1839 Callee = DAG.getLoad( 1840 PtrVt, dl, DAG.getEntryNode(), CPAddr, 1841 MachinePointerInfo::getConstantPool(DAG.getMachineFunction()), false, 1842 false, false, 0); 1843 } 1844 } else if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) { 1845 const GlobalValue *GV = G->getGlobal(); 1846 isDirect = true; 1847 bool isDef = GV->isStrongDefinitionForLinker(); 1848 bool isStub = (!isDef && Subtarget->isTargetMachO()) && 1849 getTargetMachine().getRelocationModel() != Reloc::Static; 1850 isARMFunc = !Subtarget->isThumb() || (isStub && !Subtarget->isMClass()); 1851 // ARM call to a local ARM function is predicable. 1852 isLocalARMFunc = !Subtarget->isThumb() && (isDef || !ARMInterworking); 1853 // tBX takes a register source operand. 1854 if (isStub && Subtarget->isThumb1Only() && !Subtarget->hasV5TOps()) { 1855 assert(Subtarget->isTargetMachO() && "WrapperPIC use on non-MachO?"); 1856 Callee = DAG.getNode( 1857 ARMISD::WrapperPIC, dl, PtrVt, 1858 DAG.getTargetGlobalAddress(GV, dl, PtrVt, 0, ARMII::MO_NONLAZY)); 1859 Callee = DAG.getLoad(PtrVt, dl, DAG.getEntryNode(), Callee, 1860 MachinePointerInfo::getGOT(DAG.getMachineFunction()), 1861 false, false, true, 0); 1862 } else if (Subtarget->isTargetCOFF()) { 1863 assert(Subtarget->isTargetWindows() && 1864 "Windows is the only supported COFF target"); 1865 unsigned TargetFlags = GV->hasDLLImportStorageClass() 1866 ? ARMII::MO_DLLIMPORT 1867 : ARMII::MO_NO_FLAG; 1868 Callee = 1869 DAG.getTargetGlobalAddress(GV, dl, PtrVt, /*Offset=*/0, TargetFlags); 1870 if (GV->hasDLLImportStorageClass()) 1871 Callee = 1872 DAG.getLoad(PtrVt, dl, DAG.getEntryNode(), 1873 DAG.getNode(ARMISD::Wrapper, dl, PtrVt, Callee), 1874 MachinePointerInfo::getGOT(DAG.getMachineFunction()), 1875 false, false, false, 0); 1876 } else { 1877 // On ELF targets for PIC code, direct calls should go through the PLT 1878 unsigned OpFlags = 0; 1879 if (Subtarget->isTargetELF() && 1880 getTargetMachine().getRelocationModel() == Reloc::PIC_) 1881 OpFlags = ARMII::MO_PLT; 1882 Callee = DAG.getTargetGlobalAddress(GV, dl, PtrVt, 0, OpFlags); 1883 } 1884 } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) { 1885 isDirect = true; 1886 bool isStub = Subtarget->isTargetMachO() && 1887 getTargetMachine().getRelocationModel() != Reloc::Static; 1888 isARMFunc = !Subtarget->isThumb() || (isStub && !Subtarget->isMClass()); 1889 // tBX takes a register source operand. 1890 const char *Sym = S->getSymbol(); 1891 if (isARMFunc && Subtarget->isThumb1Only() && !Subtarget->hasV5TOps()) { 1892 unsigned ARMPCLabelIndex = AFI->createPICLabelUId(); 1893 ARMConstantPoolValue *CPV = 1894 ARMConstantPoolSymbol::Create(*DAG.getContext(), Sym, 1895 ARMPCLabelIndex, 4); 1896 SDValue CPAddr = DAG.getTargetConstantPool(CPV, PtrVt, 4); 1897 CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr); 1898 Callee = DAG.getLoad( 1899 PtrVt, dl, DAG.getEntryNode(), CPAddr, 1900 MachinePointerInfo::getConstantPool(DAG.getMachineFunction()), false, 1901 false, false, 0); 1902 SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, dl, MVT::i32); 1903 Callee = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVt, Callee, PICLabel); 1904 } else { 1905 unsigned OpFlags = 0; 1906 // On ELF targets for PIC code, direct calls should go through the PLT 1907 if (Subtarget->isTargetELF() && 1908 getTargetMachine().getRelocationModel() == Reloc::PIC_) 1909 OpFlags = ARMII::MO_PLT; 1910 Callee = DAG.getTargetExternalSymbol(Sym, PtrVt, OpFlags); 1911 } 1912 } 1913 1914 // FIXME: handle tail calls differently. 1915 unsigned CallOpc; 1916 if (Subtarget->isThumb()) { 1917 if ((!isDirect || isARMFunc) && !Subtarget->hasV5TOps()) 1918 CallOpc = ARMISD::CALL_NOLINK; 1919 else 1920 CallOpc = isARMFunc ? ARMISD::CALL : ARMISD::tCALL; 1921 } else { 1922 if (!isDirect && !Subtarget->hasV5TOps()) 1923 CallOpc = ARMISD::CALL_NOLINK; 1924 else if (doesNotRet && isDirect && Subtarget->hasRAS() && 1925 // Emit regular call when code size is the priority 1926 !MF.getFunction()->optForMinSize()) 1927 // "mov lr, pc; b _foo" to avoid confusing the RSP 1928 CallOpc = ARMISD::CALL_NOLINK; 1929 else 1930 CallOpc = isLocalARMFunc ? ARMISD::CALL_PRED : ARMISD::CALL; 1931 } 1932 1933 std::vector<SDValue> Ops; 1934 Ops.push_back(Chain); 1935 Ops.push_back(Callee); 1936 1937 // Add argument registers to the end of the list so that they are known live 1938 // into the call. 1939 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) 1940 Ops.push_back(DAG.getRegister(RegsToPass[i].first, 1941 RegsToPass[i].second.getValueType())); 1942 1943 // Add a register mask operand representing the call-preserved registers. 1944 if (!isTailCall) { 1945 const uint32_t *Mask; 1946 const ARMBaseRegisterInfo *ARI = Subtarget->getRegisterInfo(); 1947 if (isThisReturn) { 1948 // For 'this' returns, use the R0-preserving mask if applicable 1949 Mask = ARI->getThisReturnPreservedMask(MF, CallConv); 1950 if (!Mask) { 1951 // Set isThisReturn to false if the calling convention is not one that 1952 // allows 'returned' to be modeled in this way, so LowerCallResult does 1953 // not try to pass 'this' straight through 1954 isThisReturn = false; 1955 Mask = ARI->getCallPreservedMask(MF, CallConv); 1956 } 1957 } else 1958 Mask = ARI->getCallPreservedMask(MF, CallConv); 1959 1960 assert(Mask && "Missing call preserved mask for calling convention"); 1961 Ops.push_back(DAG.getRegisterMask(Mask)); 1962 } 1963 1964 if (InFlag.getNode()) 1965 Ops.push_back(InFlag); 1966 1967 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue); 1968 if (isTailCall) { 1969 MF.getFrameInfo()->setHasTailCall(); 1970 return DAG.getNode(ARMISD::TC_RETURN, dl, NodeTys, Ops); 1971 } 1972 1973 // Returns a chain and a flag for retval copy to use. 1974 Chain = DAG.getNode(CallOpc, dl, NodeTys, Ops); 1975 InFlag = Chain.getValue(1); 1976 1977 Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, dl, true), 1978 DAG.getIntPtrConstant(0, dl, true), InFlag, dl); 1979 if (!Ins.empty()) 1980 InFlag = Chain.getValue(1); 1981 1982 // Handle result values, copying them out of physregs into vregs that we 1983 // return. 1984 return LowerCallResult(Chain, InFlag, CallConv, isVarArg, Ins, dl, DAG, 1985 InVals, isThisReturn, 1986 isThisReturn ? OutVals[0] : SDValue()); 1987 } 1988 1989 /// HandleByVal - Every parameter *after* a byval parameter is passed 1990 /// on the stack. Remember the next parameter register to allocate, 1991 /// and then confiscate the rest of the parameter registers to insure 1992 /// this. 1993 void ARMTargetLowering::HandleByVal(CCState *State, unsigned &Size, 1994 unsigned Align) const { 1995 assert((State->getCallOrPrologue() == Prologue || 1996 State->getCallOrPrologue() == Call) && 1997 "unhandled ParmContext"); 1998 1999 // Byval (as with any stack) slots are always at least 4 byte aligned. 2000 Align = std::max(Align, 4U); 2001 2002 unsigned Reg = State->AllocateReg(GPRArgRegs); 2003 if (!Reg) 2004 return; 2005 2006 unsigned AlignInRegs = Align / 4; 2007 unsigned Waste = (ARM::R4 - Reg) % AlignInRegs; 2008 for (unsigned i = 0; i < Waste; ++i) 2009 Reg = State->AllocateReg(GPRArgRegs); 2010 2011 if (!Reg) 2012 return; 2013 2014 unsigned Excess = 4 * (ARM::R4 - Reg); 2015 2016 // Special case when NSAA != SP and parameter size greater than size of 2017 // all remained GPR regs. In that case we can't split parameter, we must 2018 // send it to stack. We also must set NCRN to R4, so waste all 2019 // remained registers. 2020 const unsigned NSAAOffset = State->getNextStackOffset(); 2021 if (NSAAOffset != 0 && Size > Excess) { 2022 while (State->AllocateReg(GPRArgRegs)) 2023 ; 2024 return; 2025 } 2026 2027 // First register for byval parameter is the first register that wasn't 2028 // allocated before this method call, so it would be "reg". 2029 // If parameter is small enough to be saved in range [reg, r4), then 2030 // the end (first after last) register would be reg + param-size-in-regs, 2031 // else parameter would be splitted between registers and stack, 2032 // end register would be r4 in this case. 2033 unsigned ByValRegBegin = Reg; 2034 unsigned ByValRegEnd = std::min<unsigned>(Reg + Size / 4, ARM::R4); 2035 State->addInRegsParamInfo(ByValRegBegin, ByValRegEnd); 2036 // Note, first register is allocated in the beginning of function already, 2037 // allocate remained amount of registers we need. 2038 for (unsigned i = Reg + 1; i != ByValRegEnd; ++i) 2039 State->AllocateReg(GPRArgRegs); 2040 // A byval parameter that is split between registers and memory needs its 2041 // size truncated here. 2042 // In the case where the entire structure fits in registers, we set the 2043 // size in memory to zero. 2044 Size = std::max<int>(Size - Excess, 0); 2045 } 2046 2047 /// MatchingStackOffset - Return true if the given stack call argument is 2048 /// already available in the same position (relatively) of the caller's 2049 /// incoming argument stack. 2050 static 2051 bool MatchingStackOffset(SDValue Arg, unsigned Offset, ISD::ArgFlagsTy Flags, 2052 MachineFrameInfo *MFI, const MachineRegisterInfo *MRI, 2053 const TargetInstrInfo *TII) { 2054 unsigned Bytes = Arg.getValueType().getSizeInBits() / 8; 2055 int FI = INT_MAX; 2056 if (Arg.getOpcode() == ISD::CopyFromReg) { 2057 unsigned VR = cast<RegisterSDNode>(Arg.getOperand(1))->getReg(); 2058 if (!TargetRegisterInfo::isVirtualRegister(VR)) 2059 return false; 2060 MachineInstr *Def = MRI->getVRegDef(VR); 2061 if (!Def) 2062 return false; 2063 if (!Flags.isByVal()) { 2064 if (!TII->isLoadFromStackSlot(Def, FI)) 2065 return false; 2066 } else { 2067 return false; 2068 } 2069 } else if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Arg)) { 2070 if (Flags.isByVal()) 2071 // ByVal argument is passed in as a pointer but it's now being 2072 // dereferenced. e.g. 2073 // define @foo(%struct.X* %A) { 2074 // tail call @bar(%struct.X* byval %A) 2075 // } 2076 return false; 2077 SDValue Ptr = Ld->getBasePtr(); 2078 FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr); 2079 if (!FINode) 2080 return false; 2081 FI = FINode->getIndex(); 2082 } else 2083 return false; 2084 2085 assert(FI != INT_MAX); 2086 if (!MFI->isFixedObjectIndex(FI)) 2087 return false; 2088 return Offset == MFI->getObjectOffset(FI) && Bytes == MFI->getObjectSize(FI); 2089 } 2090 2091 /// IsEligibleForTailCallOptimization - Check whether the call is eligible 2092 /// for tail call optimization. Targets which want to do tail call 2093 /// optimization should implement this function. 2094 bool 2095 ARMTargetLowering::IsEligibleForTailCallOptimization(SDValue Callee, 2096 CallingConv::ID CalleeCC, 2097 bool isVarArg, 2098 bool isCalleeStructRet, 2099 bool isCallerStructRet, 2100 const SmallVectorImpl<ISD::OutputArg> &Outs, 2101 const SmallVectorImpl<SDValue> &OutVals, 2102 const SmallVectorImpl<ISD::InputArg> &Ins, 2103 SelectionDAG& DAG) const { 2104 MachineFunction &MF = DAG.getMachineFunction(); 2105 const Function *CallerF = MF.getFunction(); 2106 CallingConv::ID CallerCC = CallerF->getCallingConv(); 2107 2108 assert(Subtarget->supportsTailCall()); 2109 2110 // Look for obvious safe cases to perform tail call optimization that do not 2111 // require ABI changes. This is what gcc calls sibcall. 2112 2113 // Do not sibcall optimize vararg calls unless the call site is not passing 2114 // any arguments. 2115 if (isVarArg && !Outs.empty()) 2116 return false; 2117 2118 // Exception-handling functions need a special set of instructions to indicate 2119 // a return to the hardware. Tail-calling another function would probably 2120 // break this. 2121 if (CallerF->hasFnAttribute("interrupt")) 2122 return false; 2123 2124 // Also avoid sibcall optimization if either caller or callee uses struct 2125 // return semantics. 2126 if (isCalleeStructRet || isCallerStructRet) 2127 return false; 2128 2129 // Externally-defined functions with weak linkage should not be 2130 // tail-called on ARM when the OS does not support dynamic 2131 // pre-emption of symbols, as the AAELF spec requires normal calls 2132 // to undefined weak functions to be replaced with a NOP or jump to the 2133 // next instruction. The behaviour of branch instructions in this 2134 // situation (as used for tail calls) is implementation-defined, so we 2135 // cannot rely on the linker replacing the tail call with a return. 2136 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) { 2137 const GlobalValue *GV = G->getGlobal(); 2138 const Triple &TT = getTargetMachine().getTargetTriple(); 2139 if (GV->hasExternalWeakLinkage() && 2140 (!TT.isOSWindows() || TT.isOSBinFormatELF() || TT.isOSBinFormatMachO())) 2141 return false; 2142 } 2143 2144 // Check that the call results are passed in the same way. 2145 LLVMContext &C = *DAG.getContext(); 2146 if (!CCState::resultsCompatible(CalleeCC, CallerCC, MF, C, Ins, 2147 CCAssignFnForNode(CalleeCC, true, isVarArg), 2148 CCAssignFnForNode(CallerCC, true, isVarArg))) 2149 return false; 2150 // The callee has to preserve all registers the caller needs to preserve. 2151 const ARMBaseRegisterInfo *TRI = Subtarget->getRegisterInfo(); 2152 const uint32_t *CallerPreserved = TRI->getCallPreservedMask(MF, CallerCC); 2153 if (CalleeCC != CallerCC) { 2154 const uint32_t *CalleePreserved = TRI->getCallPreservedMask(MF, CalleeCC); 2155 if (!TRI->regmaskSubsetEqual(CallerPreserved, CalleePreserved)) 2156 return false; 2157 } 2158 2159 // If Caller's vararg or byval argument has been split between registers and 2160 // stack, do not perform tail call, since part of the argument is in caller's 2161 // local frame. 2162 const ARMFunctionInfo *AFI_Caller = MF.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, MF, ArgLocs, C, Call); 2173 CCInfo.AnalyzeCallOperands(Outs, 2174 CCAssignFnForNode(CalleeCC, false, isVarArg)); 2175 if (CCInfo.getNextStackOffset()) { 2176 // Check if the arguments are already laid out in the right way as 2177 // the caller's fixed stack objects. 2178 MachineFrameInfo *MFI = MF.getFrameInfo(); 2179 const MachineRegisterInfo *MRI = &MF.getRegInfo(); 2180 const TargetInstrInfo *TII = Subtarget->getInstrInfo(); 2181 for (unsigned i = 0, realArgIdx = 0, e = ArgLocs.size(); 2182 i != e; 2183 ++i, ++realArgIdx) { 2184 CCValAssign &VA = ArgLocs[i]; 2185 EVT RegVT = VA.getLocVT(); 2186 SDValue Arg = OutVals[realArgIdx]; 2187 ISD::ArgFlagsTy Flags = Outs[realArgIdx].Flags; 2188 if (VA.getLocInfo() == CCValAssign::Indirect) 2189 return false; 2190 if (VA.needsCustom()) { 2191 // f64 and vector types are split into multiple registers or 2192 // register/stack-slot combinations. The types will not match 2193 // the registers; give up on memory f64 refs until we figure 2194 // out what to do about this. 2195 if (!VA.isRegLoc()) 2196 return false; 2197 if (!ArgLocs[++i].isRegLoc()) 2198 return false; 2199 if (RegVT == MVT::v2f64) { 2200 if (!ArgLocs[++i].isRegLoc()) 2201 return false; 2202 if (!ArgLocs[++i].isRegLoc()) 2203 return false; 2204 } 2205 } else if (!VA.isRegLoc()) { 2206 if (!MatchingStackOffset(Arg, VA.getLocMemOffset(), Flags, 2207 MFI, MRI, TII)) 2208 return false; 2209 } 2210 } 2211 } 2212 2213 const MachineRegisterInfo &MRI = MF.getRegInfo(); 2214 if (!parametersInCSRMatch(MRI, CallerPreserved, ArgLocs, OutVals)) 2215 return false; 2216 } 2217 2218 return true; 2219 } 2220 2221 bool 2222 ARMTargetLowering::CanLowerReturn(CallingConv::ID CallConv, 2223 MachineFunction &MF, bool isVarArg, 2224 const SmallVectorImpl<ISD::OutputArg> &Outs, 2225 LLVMContext &Context) const { 2226 SmallVector<CCValAssign, 16> RVLocs; 2227 CCState CCInfo(CallConv, isVarArg, MF, RVLocs, Context); 2228 return CCInfo.CheckReturn(Outs, CCAssignFnForNode(CallConv, /*Return=*/true, 2229 isVarArg)); 2230 } 2231 2232 static SDValue LowerInterruptReturn(SmallVectorImpl<SDValue> &RetOps, 2233 SDLoc DL, SelectionDAG &DAG) { 2234 const MachineFunction &MF = DAG.getMachineFunction(); 2235 const Function *F = MF.getFunction(); 2236 2237 StringRef IntKind = F->getFnAttribute("interrupt").getValueAsString(); 2238 2239 // See ARM ARM v7 B1.8.3. On exception entry LR is set to a possibly offset 2240 // version of the "preferred return address". These offsets affect the return 2241 // instruction if this is a return from PL1 without hypervisor extensions. 2242 // IRQ/FIQ: +4 "subs pc, lr, #4" 2243 // SWI: 0 "subs pc, lr, #0" 2244 // ABORT: +4 "subs pc, lr, #4" 2245 // UNDEF: +4/+2 "subs pc, lr, #0" 2246 // UNDEF varies depending on where the exception came from ARM or Thumb 2247 // mode. Alongside GCC, we throw our hands up in disgust and pretend it's 0. 2248 2249 int64_t LROffset; 2250 if (IntKind == "" || IntKind == "IRQ" || IntKind == "FIQ" || 2251 IntKind == "ABORT") 2252 LROffset = 4; 2253 else if (IntKind == "SWI" || IntKind == "UNDEF") 2254 LROffset = 0; 2255 else 2256 report_fatal_error("Unsupported interrupt attribute. If present, value " 2257 "must be one of: IRQ, FIQ, SWI, ABORT or UNDEF"); 2258 2259 RetOps.insert(RetOps.begin() + 1, 2260 DAG.getConstant(LROffset, DL, MVT::i32, false)); 2261 2262 return DAG.getNode(ARMISD::INTRET_FLAG, DL, MVT::Other, RetOps); 2263 } 2264 2265 SDValue 2266 ARMTargetLowering::LowerReturn(SDValue Chain, 2267 CallingConv::ID CallConv, bool isVarArg, 2268 const SmallVectorImpl<ISD::OutputArg> &Outs, 2269 const SmallVectorImpl<SDValue> &OutVals, 2270 SDLoc dl, SelectionDAG &DAG) const { 2271 2272 // CCValAssign - represent the assignment of the return value to a location. 2273 SmallVector<CCValAssign, 16> RVLocs; 2274 2275 // CCState - Info about the registers and stack slots. 2276 ARMCCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs, 2277 *DAG.getContext(), Call); 2278 2279 // Analyze outgoing return values. 2280 CCInfo.AnalyzeReturn(Outs, CCAssignFnForNode(CallConv, /* Return */ true, 2281 isVarArg)); 2282 2283 SDValue Flag; 2284 SmallVector<SDValue, 4> RetOps; 2285 RetOps.push_back(Chain); // Operand #0 = Chain (updated below) 2286 bool isLittleEndian = Subtarget->isLittle(); 2287 2288 MachineFunction &MF = DAG.getMachineFunction(); 2289 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>(); 2290 AFI->setReturnRegsCount(RVLocs.size()); 2291 2292 // Copy the result values into the output registers. 2293 for (unsigned i = 0, realRVLocIdx = 0; 2294 i != RVLocs.size(); 2295 ++i, ++realRVLocIdx) { 2296 CCValAssign &VA = RVLocs[i]; 2297 assert(VA.isRegLoc() && "Can only return in registers!"); 2298 2299 SDValue Arg = OutVals[realRVLocIdx]; 2300 2301 switch (VA.getLocInfo()) { 2302 default: llvm_unreachable("Unknown loc info!"); 2303 case CCValAssign::Full: break; 2304 case CCValAssign::BCvt: 2305 Arg = DAG.getNode(ISD::BITCAST, dl, VA.getLocVT(), Arg); 2306 break; 2307 } 2308 2309 if (VA.needsCustom()) { 2310 if (VA.getLocVT() == MVT::v2f64) { 2311 // Extract the first half and return it in two registers. 2312 SDValue Half = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg, 2313 DAG.getConstant(0, dl, MVT::i32)); 2314 SDValue HalfGPRs = DAG.getNode(ARMISD::VMOVRRD, dl, 2315 DAG.getVTList(MVT::i32, MVT::i32), Half); 2316 2317 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), 2318 HalfGPRs.getValue(isLittleEndian ? 0 : 1), 2319 Flag); 2320 Flag = Chain.getValue(1); 2321 RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT())); 2322 VA = RVLocs[++i]; // skip ahead to next loc 2323 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), 2324 HalfGPRs.getValue(isLittleEndian ? 1 : 0), 2325 Flag); 2326 Flag = Chain.getValue(1); 2327 RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT())); 2328 VA = RVLocs[++i]; // skip ahead to next loc 2329 2330 // Extract the 2nd half and fall through to handle it as an f64 value. 2331 Arg = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg, 2332 DAG.getConstant(1, dl, MVT::i32)); 2333 } 2334 // Legalize ret f64 -> ret 2 x i32. We always have fmrrd if f64 is 2335 // available. 2336 SDValue fmrrd = DAG.getNode(ARMISD::VMOVRRD, dl, 2337 DAG.getVTList(MVT::i32, MVT::i32), Arg); 2338 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), 2339 fmrrd.getValue(isLittleEndian ? 0 : 1), 2340 Flag); 2341 Flag = Chain.getValue(1); 2342 RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT())); 2343 VA = RVLocs[++i]; // skip ahead to next loc 2344 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), 2345 fmrrd.getValue(isLittleEndian ? 1 : 0), 2346 Flag); 2347 } else 2348 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), Arg, Flag); 2349 2350 // Guarantee that all emitted copies are 2351 // stuck together, avoiding something bad. 2352 Flag = Chain.getValue(1); 2353 RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT())); 2354 } 2355 const ARMBaseRegisterInfo *TRI = Subtarget->getRegisterInfo(); 2356 const MCPhysReg *I = 2357 TRI->getCalleeSavedRegsViaCopy(&DAG.getMachineFunction()); 2358 if (I) { 2359 for (; *I; ++I) { 2360 if (ARM::GPRRegClass.contains(*I)) 2361 RetOps.push_back(DAG.getRegister(*I, MVT::i32)); 2362 else if (ARM::DPRRegClass.contains(*I)) 2363 RetOps.push_back(DAG.getRegister(*I, MVT::getFloatingPointVT(64))); 2364 else 2365 llvm_unreachable("Unexpected register class in CSRsViaCopy!"); 2366 } 2367 } 2368 2369 // Update chain and glue. 2370 RetOps[0] = Chain; 2371 if (Flag.getNode()) 2372 RetOps.push_back(Flag); 2373 2374 // CPUs which aren't M-class use a special sequence to return from 2375 // exceptions (roughly, any instruction setting pc and cpsr simultaneously, 2376 // though we use "subs pc, lr, #N"). 2377 // 2378 // M-class CPUs actually use a normal return sequence with a special 2379 // (hardware-provided) value in LR, so the normal code path works. 2380 if (DAG.getMachineFunction().getFunction()->hasFnAttribute("interrupt") && 2381 !Subtarget->isMClass()) { 2382 if (Subtarget->isThumb1Only()) 2383 report_fatal_error("interrupt attribute is not supported in Thumb1"); 2384 return LowerInterruptReturn(RetOps, dl, DAG); 2385 } 2386 2387 return DAG.getNode(ARMISD::RET_FLAG, dl, MVT::Other, RetOps); 2388 } 2389 2390 bool ARMTargetLowering::isUsedByReturnOnly(SDNode *N, SDValue &Chain) const { 2391 if (N->getNumValues() != 1) 2392 return false; 2393 if (!N->hasNUsesOfValue(1, 0)) 2394 return false; 2395 2396 SDValue TCChain = Chain; 2397 SDNode *Copy = *N->use_begin(); 2398 if (Copy->getOpcode() == ISD::CopyToReg) { 2399 // If the copy has a glue operand, we conservatively assume it isn't safe to 2400 // perform a tail call. 2401 if (Copy->getOperand(Copy->getNumOperands()-1).getValueType() == MVT::Glue) 2402 return false; 2403 TCChain = Copy->getOperand(0); 2404 } else if (Copy->getOpcode() == ARMISD::VMOVRRD) { 2405 SDNode *VMov = Copy; 2406 // f64 returned in a pair of GPRs. 2407 SmallPtrSet<SDNode*, 2> Copies; 2408 for (SDNode::use_iterator UI = VMov->use_begin(), UE = VMov->use_end(); 2409 UI != UE; ++UI) { 2410 if (UI->getOpcode() != ISD::CopyToReg) 2411 return false; 2412 Copies.insert(*UI); 2413 } 2414 if (Copies.size() > 2) 2415 return false; 2416 2417 for (SDNode::use_iterator UI = VMov->use_begin(), UE = VMov->use_end(); 2418 UI != UE; ++UI) { 2419 SDValue UseChain = UI->getOperand(0); 2420 if (Copies.count(UseChain.getNode())) 2421 // Second CopyToReg 2422 Copy = *UI; 2423 else { 2424 // We are at the top of this chain. 2425 // If the copy has a glue operand, we conservatively assume it 2426 // isn't safe to perform a tail call. 2427 if (UI->getOperand(UI->getNumOperands()-1).getValueType() == MVT::Glue) 2428 return false; 2429 // First CopyToReg 2430 TCChain = UseChain; 2431 } 2432 } 2433 } else if (Copy->getOpcode() == ISD::BITCAST) { 2434 // f32 returned in a single GPR. 2435 if (!Copy->hasOneUse()) 2436 return false; 2437 Copy = *Copy->use_begin(); 2438 if (Copy->getOpcode() != ISD::CopyToReg || !Copy->hasNUsesOfValue(1, 0)) 2439 return false; 2440 // If the copy has a glue operand, we conservatively assume it isn't safe to 2441 // perform a tail call. 2442 if (Copy->getOperand(Copy->getNumOperands()-1).getValueType() == MVT::Glue) 2443 return false; 2444 TCChain = Copy->getOperand(0); 2445 } else { 2446 return false; 2447 } 2448 2449 bool HasRet = false; 2450 for (SDNode::use_iterator UI = Copy->use_begin(), UE = Copy->use_end(); 2451 UI != UE; ++UI) { 2452 if (UI->getOpcode() != ARMISD::RET_FLAG && 2453 UI->getOpcode() != ARMISD::INTRET_FLAG) 2454 return false; 2455 HasRet = true; 2456 } 2457 2458 if (!HasRet) 2459 return false; 2460 2461 Chain = TCChain; 2462 return true; 2463 } 2464 2465 bool ARMTargetLowering::mayBeEmittedAsTailCall(CallInst *CI) const { 2466 if (!Subtarget->supportsTailCall()) 2467 return false; 2468 2469 auto Attr = 2470 CI->getParent()->getParent()->getFnAttribute("disable-tail-calls"); 2471 if (!CI->isTailCall() || Attr.getValueAsString() == "true") 2472 return false; 2473 2474 return true; 2475 } 2476 2477 // Trying to write a 64 bit value so need to split into two 32 bit values first, 2478 // and pass the lower and high parts through. 2479 static SDValue LowerWRITE_REGISTER(SDValue Op, SelectionDAG &DAG) { 2480 SDLoc DL(Op); 2481 SDValue WriteValue = Op->getOperand(2); 2482 2483 // This function is only supposed to be called for i64 type argument. 2484 assert(WriteValue.getValueType() == MVT::i64 2485 && "LowerWRITE_REGISTER called for non-i64 type argument."); 2486 2487 SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, WriteValue, 2488 DAG.getConstant(0, DL, MVT::i32)); 2489 SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, WriteValue, 2490 DAG.getConstant(1, DL, MVT::i32)); 2491 SDValue Ops[] = { Op->getOperand(0), Op->getOperand(1), Lo, Hi }; 2492 return DAG.getNode(ISD::WRITE_REGISTER, DL, MVT::Other, Ops); 2493 } 2494 2495 // ConstantPool, JumpTable, GlobalAddress, and ExternalSymbol are lowered as 2496 // their target counterpart wrapped in the ARMISD::Wrapper node. Suppose N is 2497 // one of the above mentioned nodes. It has to be wrapped because otherwise 2498 // Select(N) returns N. So the raw TargetGlobalAddress nodes, etc. can only 2499 // be used to form addressing mode. These wrapped nodes will be selected 2500 // into MOVi. 2501 static SDValue LowerConstantPool(SDValue Op, SelectionDAG &DAG) { 2502 EVT PtrVT = Op.getValueType(); 2503 // FIXME there is no actual debug info here 2504 SDLoc dl(Op); 2505 ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op); 2506 SDValue Res; 2507 if (CP->isMachineConstantPoolEntry()) 2508 Res = DAG.getTargetConstantPool(CP->getMachineCPVal(), PtrVT, 2509 CP->getAlignment()); 2510 else 2511 Res = DAG.getTargetConstantPool(CP->getConstVal(), PtrVT, 2512 CP->getAlignment()); 2513 return DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Res); 2514 } 2515 2516 unsigned ARMTargetLowering::getJumpTableEncoding() const { 2517 return MachineJumpTableInfo::EK_Inline; 2518 } 2519 2520 SDValue ARMTargetLowering::LowerBlockAddress(SDValue Op, 2521 SelectionDAG &DAG) const { 2522 MachineFunction &MF = DAG.getMachineFunction(); 2523 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>(); 2524 unsigned ARMPCLabelIndex = 0; 2525 SDLoc DL(Op); 2526 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 2527 const BlockAddress *BA = cast<BlockAddressSDNode>(Op)->getBlockAddress(); 2528 Reloc::Model RelocM = getTargetMachine().getRelocationModel(); 2529 SDValue CPAddr; 2530 if (RelocM == Reloc::Static) { 2531 CPAddr = DAG.getTargetConstantPool(BA, PtrVT, 4); 2532 } else { 2533 unsigned PCAdj = Subtarget->isThumb() ? 4 : 8; 2534 ARMPCLabelIndex = AFI->createPICLabelUId(); 2535 ARMConstantPoolValue *CPV = 2536 ARMConstantPoolConstant::Create(BA, ARMPCLabelIndex, 2537 ARMCP::CPBlockAddress, PCAdj); 2538 CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4); 2539 } 2540 CPAddr = DAG.getNode(ARMISD::Wrapper, DL, PtrVT, CPAddr); 2541 SDValue Result = 2542 DAG.getLoad(PtrVT, DL, DAG.getEntryNode(), CPAddr, 2543 MachinePointerInfo::getConstantPool(DAG.getMachineFunction()), 2544 false, false, false, 0); 2545 if (RelocM == Reloc::Static) 2546 return Result; 2547 SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, DL, MVT::i32); 2548 return DAG.getNode(ARMISD::PIC_ADD, DL, PtrVT, Result, PICLabel); 2549 } 2550 2551 /// \brief Convert a TLS address reference into the correct sequence of loads 2552 /// and calls to compute the variable's address for Darwin, and return an 2553 /// SDValue containing the final node. 2554 2555 /// Darwin only has one TLS scheme which must be capable of dealing with the 2556 /// fully general situation, in the worst case. This means: 2557 /// + "extern __thread" declaration. 2558 /// + Defined in a possibly unknown dynamic library. 2559 /// 2560 /// The general system is that each __thread variable has a [3 x i32] descriptor 2561 /// which contains information used by the runtime to calculate the address. The 2562 /// only part of this the compiler needs to know about is the first word, which 2563 /// contains a function pointer that must be called with the address of the 2564 /// entire descriptor in "r0". 2565 /// 2566 /// Since this descriptor may be in a different unit, in general access must 2567 /// proceed along the usual ARM rules. A common sequence to produce is: 2568 /// 2569 /// movw rT1, :lower16:_var$non_lazy_ptr 2570 /// movt rT1, :upper16:_var$non_lazy_ptr 2571 /// ldr r0, [rT1] 2572 /// ldr rT2, [r0] 2573 /// blx rT2 2574 /// [...address now in r0...] 2575 SDValue 2576 ARMTargetLowering::LowerGlobalTLSAddressDarwin(SDValue Op, 2577 SelectionDAG &DAG) const { 2578 assert(Subtarget->isTargetDarwin() && "TLS only supported on Darwin"); 2579 SDLoc DL(Op); 2580 2581 // First step is to get the address of the actua global symbol. This is where 2582 // the TLS descriptor lives. 2583 SDValue DescAddr = LowerGlobalAddressDarwin(Op, DAG); 2584 2585 // The first entry in the descriptor is a function pointer that we must call 2586 // to obtain the address of the variable. 2587 SDValue Chain = DAG.getEntryNode(); 2588 SDValue FuncTLVGet = 2589 DAG.getLoad(MVT::i32, DL, Chain, DescAddr, 2590 MachinePointerInfo::getGOT(DAG.getMachineFunction()), 2591 false, true, true, 4); 2592 Chain = FuncTLVGet.getValue(1); 2593 2594 MachineFunction &F = DAG.getMachineFunction(); 2595 MachineFrameInfo *MFI = F.getFrameInfo(); 2596 MFI->setAdjustsStack(true); 2597 2598 // TLS calls preserve all registers except those that absolutely must be 2599 // trashed: R0 (it takes an argument), LR (it's a call) and CPSR (let's not be 2600 // silly). 2601 auto TRI = 2602 getTargetMachine().getSubtargetImpl(*F.getFunction())->getRegisterInfo(); 2603 auto ARI = static_cast<const ARMRegisterInfo *>(TRI); 2604 const uint32_t *Mask = ARI->getTLSCallPreservedMask(DAG.getMachineFunction()); 2605 2606 // Finally, we can make the call. This is just a degenerate version of a 2607 // normal AArch64 call node: r0 takes the address of the descriptor, and 2608 // returns the address of the variable in this thread. 2609 Chain = DAG.getCopyToReg(Chain, DL, ARM::R0, DescAddr, SDValue()); 2610 Chain = 2611 DAG.getNode(ARMISD::CALL, DL, DAG.getVTList(MVT::Other, MVT::Glue), 2612 Chain, FuncTLVGet, DAG.getRegister(ARM::R0, MVT::i32), 2613 DAG.getRegisterMask(Mask), Chain.getValue(1)); 2614 return DAG.getCopyFromReg(Chain, DL, ARM::R0, MVT::i32, Chain.getValue(1)); 2615 } 2616 2617 SDValue 2618 ARMTargetLowering::LowerGlobalTLSAddressWindows(SDValue Op, 2619 SelectionDAG &DAG) const { 2620 assert(Subtarget->isTargetWindows() && "Windows specific TLS lowering"); 2621 SDValue Chain = DAG.getEntryNode(); 2622 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 2623 SDLoc DL(Op); 2624 2625 // Load the current TEB (thread environment block) 2626 SDValue Ops[] = {Chain, 2627 DAG.getConstant(Intrinsic::arm_mrc, DL, MVT::i32), 2628 DAG.getConstant(15, DL, MVT::i32), 2629 DAG.getConstant(0, DL, MVT::i32), 2630 DAG.getConstant(13, DL, MVT::i32), 2631 DAG.getConstant(0, DL, MVT::i32), 2632 DAG.getConstant(2, DL, MVT::i32)}; 2633 SDValue CurrentTEB = DAG.getNode(ISD::INTRINSIC_W_CHAIN, DL, 2634 DAG.getVTList(MVT::i32, MVT::Other), Ops); 2635 2636 SDValue TEB = CurrentTEB.getValue(0); 2637 Chain = CurrentTEB.getValue(1); 2638 2639 // Load the ThreadLocalStoragePointer from the TEB 2640 // A pointer to the TLS array is located at offset 0x2c from the TEB. 2641 SDValue TLSArray = 2642 DAG.getNode(ISD::ADD, DL, PtrVT, TEB, DAG.getIntPtrConstant(0x2c, DL)); 2643 TLSArray = DAG.getLoad(PtrVT, DL, Chain, TLSArray, MachinePointerInfo(), 2644 false, false, false, 0); 2645 2646 // The pointer to the thread's TLS data area is at the TLS Index scaled by 4 2647 // offset into the TLSArray. 2648 2649 // Load the TLS index from the C runtime 2650 SDValue TLSIndex = 2651 DAG.getTargetExternalSymbol("_tls_index", PtrVT, ARMII::MO_NO_FLAG); 2652 TLSIndex = DAG.getNode(ARMISD::Wrapper, DL, PtrVT, TLSIndex); 2653 TLSIndex = DAG.getLoad(PtrVT, DL, Chain, TLSIndex, MachinePointerInfo(), 2654 false, false, false, 0); 2655 2656 SDValue Slot = DAG.getNode(ISD::SHL, DL, PtrVT, TLSIndex, 2657 DAG.getConstant(2, DL, MVT::i32)); 2658 SDValue TLS = DAG.getLoad(PtrVT, DL, Chain, 2659 DAG.getNode(ISD::ADD, DL, PtrVT, TLSArray, Slot), 2660 MachinePointerInfo(), false, false, false, 0); 2661 2662 return DAG.getNode(ISD::ADD, DL, PtrVT, TLS, 2663 LowerGlobalAddressWindows(Op, DAG)); 2664 } 2665 2666 // Lower ISD::GlobalTLSAddress using the "general dynamic" model 2667 SDValue 2668 ARMTargetLowering::LowerToTLSGeneralDynamicModel(GlobalAddressSDNode *GA, 2669 SelectionDAG &DAG) const { 2670 SDLoc dl(GA); 2671 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 2672 unsigned char PCAdj = Subtarget->isThumb() ? 4 : 8; 2673 MachineFunction &MF = DAG.getMachineFunction(); 2674 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>(); 2675 unsigned ARMPCLabelIndex = AFI->createPICLabelUId(); 2676 ARMConstantPoolValue *CPV = 2677 ARMConstantPoolConstant::Create(GA->getGlobal(), ARMPCLabelIndex, 2678 ARMCP::CPValue, PCAdj, ARMCP::TLSGD, true); 2679 SDValue Argument = DAG.getTargetConstantPool(CPV, PtrVT, 4); 2680 Argument = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Argument); 2681 Argument = 2682 DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Argument, 2683 MachinePointerInfo::getConstantPool(DAG.getMachineFunction()), 2684 false, false, false, 0); 2685 SDValue Chain = Argument.getValue(1); 2686 2687 SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, dl, MVT::i32); 2688 Argument = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Argument, PICLabel); 2689 2690 // call __tls_get_addr. 2691 ArgListTy Args; 2692 ArgListEntry Entry; 2693 Entry.Node = Argument; 2694 Entry.Ty = (Type *) Type::getInt32Ty(*DAG.getContext()); 2695 Args.push_back(Entry); 2696 2697 // FIXME: is there useful debug info available here? 2698 TargetLowering::CallLoweringInfo CLI(DAG); 2699 CLI.setDebugLoc(dl).setChain(Chain) 2700 .setCallee(CallingConv::C, Type::getInt32Ty(*DAG.getContext()), 2701 DAG.getExternalSymbol("__tls_get_addr", PtrVT), std::move(Args), 2702 0); 2703 2704 std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI); 2705 return CallResult.first; 2706 } 2707 2708 // Lower ISD::GlobalTLSAddress using the "initial exec" or 2709 // "local exec" model. 2710 SDValue 2711 ARMTargetLowering::LowerToTLSExecModels(GlobalAddressSDNode *GA, 2712 SelectionDAG &DAG, 2713 TLSModel::Model model) const { 2714 const GlobalValue *GV = GA->getGlobal(); 2715 SDLoc dl(GA); 2716 SDValue Offset; 2717 SDValue Chain = DAG.getEntryNode(); 2718 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 2719 // Get the Thread Pointer 2720 SDValue ThreadPointer = DAG.getNode(ARMISD::THREAD_POINTER, dl, PtrVT); 2721 2722 if (model == TLSModel::InitialExec) { 2723 MachineFunction &MF = DAG.getMachineFunction(); 2724 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>(); 2725 unsigned ARMPCLabelIndex = AFI->createPICLabelUId(); 2726 // Initial exec model. 2727 unsigned char PCAdj = Subtarget->isThumb() ? 4 : 8; 2728 ARMConstantPoolValue *CPV = 2729 ARMConstantPoolConstant::Create(GA->getGlobal(), ARMPCLabelIndex, 2730 ARMCP::CPValue, PCAdj, ARMCP::GOTTPOFF, 2731 true); 2732 Offset = DAG.getTargetConstantPool(CPV, PtrVT, 4); 2733 Offset = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Offset); 2734 Offset = DAG.getLoad( 2735 PtrVT, dl, Chain, Offset, 2736 MachinePointerInfo::getConstantPool(DAG.getMachineFunction()), false, 2737 false, false, 0); 2738 Chain = Offset.getValue(1); 2739 2740 SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, dl, MVT::i32); 2741 Offset = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Offset, PICLabel); 2742 2743 Offset = DAG.getLoad( 2744 PtrVT, dl, Chain, Offset, 2745 MachinePointerInfo::getConstantPool(DAG.getMachineFunction()), false, 2746 false, false, 0); 2747 } else { 2748 // local exec model 2749 assert(model == TLSModel::LocalExec); 2750 ARMConstantPoolValue *CPV = 2751 ARMConstantPoolConstant::Create(GV, ARMCP::TPOFF); 2752 Offset = DAG.getTargetConstantPool(CPV, PtrVT, 4); 2753 Offset = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Offset); 2754 Offset = DAG.getLoad( 2755 PtrVT, dl, Chain, Offset, 2756 MachinePointerInfo::getConstantPool(DAG.getMachineFunction()), false, 2757 false, false, 0); 2758 } 2759 2760 // The address of the thread local variable is the add of the thread 2761 // pointer with the offset of the variable. 2762 return DAG.getNode(ISD::ADD, dl, PtrVT, ThreadPointer, Offset); 2763 } 2764 2765 SDValue 2766 ARMTargetLowering::LowerGlobalTLSAddress(SDValue Op, SelectionDAG &DAG) const { 2767 if (Subtarget->isTargetDarwin()) 2768 return LowerGlobalTLSAddressDarwin(Op, DAG); 2769 2770 if (Subtarget->isTargetWindows()) 2771 return LowerGlobalTLSAddressWindows(Op, DAG); 2772 2773 // TODO: implement the "local dynamic" model 2774 assert(Subtarget->isTargetELF() && "Only ELF implemented here"); 2775 GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op); 2776 if (DAG.getTarget().Options.EmulatedTLS) 2777 return LowerToTLSEmulatedModel(GA, DAG); 2778 2779 TLSModel::Model model = getTargetMachine().getTLSModel(GA->getGlobal()); 2780 2781 switch (model) { 2782 case TLSModel::GeneralDynamic: 2783 case TLSModel::LocalDynamic: 2784 return LowerToTLSGeneralDynamicModel(GA, DAG); 2785 case TLSModel::InitialExec: 2786 case TLSModel::LocalExec: 2787 return LowerToTLSExecModels(GA, DAG, model); 2788 } 2789 llvm_unreachable("bogus TLS model"); 2790 } 2791 2792 SDValue ARMTargetLowering::LowerGlobalAddressELF(SDValue Op, 2793 SelectionDAG &DAG) const { 2794 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 2795 SDLoc dl(Op); 2796 const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal(); 2797 if (getTargetMachine().getRelocationModel() == Reloc::PIC_) { 2798 bool UseGOT_PREL = 2799 !(GV->hasHiddenVisibility() || GV->hasLocalLinkage()); 2800 2801 MachineFunction &MF = DAG.getMachineFunction(); 2802 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>(); 2803 unsigned ARMPCLabelIndex = AFI->createPICLabelUId(); 2804 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 2805 SDLoc dl(Op); 2806 unsigned PCAdj = Subtarget->isThumb() ? 4 : 8; 2807 ARMConstantPoolValue *CPV = ARMConstantPoolConstant::Create( 2808 GV, ARMPCLabelIndex, ARMCP::CPValue, PCAdj, 2809 UseGOT_PREL ? ARMCP::GOT_PREL : ARMCP::no_modifier, 2810 /*AddCurrentAddress=*/UseGOT_PREL); 2811 SDValue CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4); 2812 CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr); 2813 SDValue Result = DAG.getLoad( 2814 PtrVT, dl, DAG.getEntryNode(), CPAddr, 2815 MachinePointerInfo::getConstantPool(DAG.getMachineFunction()), false, 2816 false, false, 0); 2817 SDValue Chain = Result.getValue(1); 2818 SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, dl, MVT::i32); 2819 Result = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Result, PICLabel); 2820 if (UseGOT_PREL) 2821 Result = DAG.getLoad(PtrVT, dl, Chain, Result, 2822 MachinePointerInfo::getGOT(DAG.getMachineFunction()), 2823 false, false, false, 0); 2824 return Result; 2825 } 2826 2827 // If we have T2 ops, we can materialize the address directly via movt/movw 2828 // pair. This is always cheaper. 2829 if (Subtarget->useMovt(DAG.getMachineFunction())) { 2830 ++NumMovwMovt; 2831 // FIXME: Once remat is capable of dealing with instructions with register 2832 // operands, expand this into two nodes. 2833 return DAG.getNode(ARMISD::Wrapper, dl, PtrVT, 2834 DAG.getTargetGlobalAddress(GV, dl, PtrVT)); 2835 } else { 2836 SDValue CPAddr = DAG.getTargetConstantPool(GV, PtrVT, 4); 2837 CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr); 2838 return DAG.getLoad( 2839 PtrVT, dl, DAG.getEntryNode(), CPAddr, 2840 MachinePointerInfo::getConstantPool(DAG.getMachineFunction()), false, 2841 false, false, 0); 2842 } 2843 } 2844 2845 SDValue ARMTargetLowering::LowerGlobalAddressDarwin(SDValue Op, 2846 SelectionDAG &DAG) const { 2847 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 2848 SDLoc dl(Op); 2849 const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal(); 2850 Reloc::Model RelocM = getTargetMachine().getRelocationModel(); 2851 2852 if (Subtarget->useMovt(DAG.getMachineFunction())) 2853 ++NumMovwMovt; 2854 2855 // FIXME: Once remat is capable of dealing with instructions with register 2856 // operands, expand this into multiple nodes 2857 unsigned Wrapper = 2858 RelocM == Reloc::PIC_ ? ARMISD::WrapperPIC : ARMISD::Wrapper; 2859 2860 SDValue G = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, ARMII::MO_NONLAZY); 2861 SDValue Result = DAG.getNode(Wrapper, dl, PtrVT, G); 2862 2863 if (Subtarget->GVIsIndirectSymbol(GV, RelocM)) 2864 Result = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Result, 2865 MachinePointerInfo::getGOT(DAG.getMachineFunction()), 2866 false, false, false, 0); 2867 return Result; 2868 } 2869 2870 SDValue ARMTargetLowering::LowerGlobalAddressWindows(SDValue Op, 2871 SelectionDAG &DAG) const { 2872 assert(Subtarget->isTargetWindows() && "non-Windows COFF is not supported"); 2873 assert(Subtarget->useMovt(DAG.getMachineFunction()) && 2874 "Windows on ARM expects to use movw/movt"); 2875 2876 const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal(); 2877 const ARMII::TOF TargetFlags = 2878 (GV->hasDLLImportStorageClass() ? ARMII::MO_DLLIMPORT : ARMII::MO_NO_FLAG); 2879 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 2880 SDValue Result; 2881 SDLoc DL(Op); 2882 2883 ++NumMovwMovt; 2884 2885 // FIXME: Once remat is capable of dealing with instructions with register 2886 // operands, expand this into two nodes. 2887 Result = DAG.getNode(ARMISD::Wrapper, DL, PtrVT, 2888 DAG.getTargetGlobalAddress(GV, DL, PtrVT, /*Offset=*/0, 2889 TargetFlags)); 2890 if (GV->hasDLLImportStorageClass()) 2891 Result = DAG.getLoad(PtrVT, DL, DAG.getEntryNode(), Result, 2892 MachinePointerInfo::getGOT(DAG.getMachineFunction()), 2893 false, false, false, 0); 2894 return Result; 2895 } 2896 2897 SDValue 2898 ARMTargetLowering::LowerEH_SJLJ_SETJMP(SDValue Op, SelectionDAG &DAG) const { 2899 SDLoc dl(Op); 2900 SDValue Val = DAG.getConstant(0, dl, MVT::i32); 2901 return DAG.getNode(ARMISD::EH_SJLJ_SETJMP, dl, 2902 DAG.getVTList(MVT::i32, MVT::Other), Op.getOperand(0), 2903 Op.getOperand(1), Val); 2904 } 2905 2906 SDValue 2907 ARMTargetLowering::LowerEH_SJLJ_LONGJMP(SDValue Op, SelectionDAG &DAG) const { 2908 SDLoc dl(Op); 2909 return DAG.getNode(ARMISD::EH_SJLJ_LONGJMP, dl, MVT::Other, Op.getOperand(0), 2910 Op.getOperand(1), DAG.getConstant(0, dl, MVT::i32)); 2911 } 2912 2913 SDValue ARMTargetLowering::LowerEH_SJLJ_SETUP_DISPATCH(SDValue Op, 2914 SelectionDAG &DAG) const { 2915 SDLoc dl(Op); 2916 return DAG.getNode(ARMISD::EH_SJLJ_SETUP_DISPATCH, dl, MVT::Other, 2917 Op.getOperand(0)); 2918 } 2919 2920 SDValue 2921 ARMTargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op, SelectionDAG &DAG, 2922 const ARMSubtarget *Subtarget) const { 2923 unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue(); 2924 SDLoc dl(Op); 2925 switch (IntNo) { 2926 default: return SDValue(); // Don't custom lower most intrinsics. 2927 case Intrinsic::arm_rbit: { 2928 assert(Op.getOperand(1).getValueType() == MVT::i32 && 2929 "RBIT intrinsic must have i32 type!"); 2930 return DAG.getNode(ISD::BITREVERSE, dl, MVT::i32, Op.getOperand(1)); 2931 } 2932 case Intrinsic::thread_pointer: { 2933 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 2934 return DAG.getNode(ARMISD::THREAD_POINTER, dl, PtrVT); 2935 } 2936 case Intrinsic::eh_sjlj_lsda: { 2937 MachineFunction &MF = DAG.getMachineFunction(); 2938 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>(); 2939 unsigned ARMPCLabelIndex = AFI->createPICLabelUId(); 2940 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 2941 Reloc::Model RelocM = getTargetMachine().getRelocationModel(); 2942 SDValue CPAddr; 2943 unsigned PCAdj = (RelocM != Reloc::PIC_) 2944 ? 0 : (Subtarget->isThumb() ? 4 : 8); 2945 ARMConstantPoolValue *CPV = 2946 ARMConstantPoolConstant::Create(MF.getFunction(), ARMPCLabelIndex, 2947 ARMCP::CPLSDA, PCAdj); 2948 CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4); 2949 CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr); 2950 SDValue Result = DAG.getLoad( 2951 PtrVT, dl, DAG.getEntryNode(), CPAddr, 2952 MachinePointerInfo::getConstantPool(DAG.getMachineFunction()), false, 2953 false, false, 0); 2954 2955 if (RelocM == Reloc::PIC_) { 2956 SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, dl, MVT::i32); 2957 Result = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Result, PICLabel); 2958 } 2959 return Result; 2960 } 2961 case Intrinsic::arm_neon_vmulls: 2962 case Intrinsic::arm_neon_vmullu: { 2963 unsigned NewOpc = (IntNo == Intrinsic::arm_neon_vmulls) 2964 ? ARMISD::VMULLs : ARMISD::VMULLu; 2965 return DAG.getNode(NewOpc, SDLoc(Op), Op.getValueType(), 2966 Op.getOperand(1), Op.getOperand(2)); 2967 } 2968 case Intrinsic::arm_neon_vminnm: 2969 case Intrinsic::arm_neon_vmaxnm: { 2970 unsigned NewOpc = (IntNo == Intrinsic::arm_neon_vminnm) 2971 ? ISD::FMINNUM : ISD::FMAXNUM; 2972 return DAG.getNode(NewOpc, SDLoc(Op), Op.getValueType(), 2973 Op.getOperand(1), Op.getOperand(2)); 2974 } 2975 case Intrinsic::arm_neon_vminu: 2976 case Intrinsic::arm_neon_vmaxu: { 2977 if (Op.getValueType().isFloatingPoint()) 2978 return SDValue(); 2979 unsigned NewOpc = (IntNo == Intrinsic::arm_neon_vminu) 2980 ? ISD::UMIN : ISD::UMAX; 2981 return DAG.getNode(NewOpc, SDLoc(Op), Op.getValueType(), 2982 Op.getOperand(1), Op.getOperand(2)); 2983 } 2984 case Intrinsic::arm_neon_vmins: 2985 case Intrinsic::arm_neon_vmaxs: { 2986 // v{min,max}s is overloaded between signed integers and floats. 2987 if (!Op.getValueType().isFloatingPoint()) { 2988 unsigned NewOpc = (IntNo == Intrinsic::arm_neon_vmins) 2989 ? ISD::SMIN : ISD::SMAX; 2990 return DAG.getNode(NewOpc, SDLoc(Op), Op.getValueType(), 2991 Op.getOperand(1), Op.getOperand(2)); 2992 } 2993 unsigned NewOpc = (IntNo == Intrinsic::arm_neon_vmins) 2994 ? ISD::FMINNAN : ISD::FMAXNAN; 2995 return DAG.getNode(NewOpc, SDLoc(Op), Op.getValueType(), 2996 Op.getOperand(1), Op.getOperand(2)); 2997 } 2998 } 2999 } 3000 3001 static SDValue LowerATOMIC_FENCE(SDValue Op, SelectionDAG &DAG, 3002 const ARMSubtarget *Subtarget) { 3003 // FIXME: handle "fence singlethread" more efficiently. 3004 SDLoc dl(Op); 3005 if (!Subtarget->hasDataBarrier()) { 3006 // Some ARMv6 cpus can support data barriers with an mcr instruction. 3007 // Thumb1 and pre-v6 ARM mode use a libcall instead and should never get 3008 // here. 3009 assert(Subtarget->hasV6Ops() && !Subtarget->isThumb() && 3010 "Unexpected ISD::ATOMIC_FENCE encountered. Should be libcall!"); 3011 return DAG.getNode(ARMISD::MEMBARRIER_MCR, dl, MVT::Other, Op.getOperand(0), 3012 DAG.getConstant(0, dl, MVT::i32)); 3013 } 3014 3015 ConstantSDNode *OrdN = cast<ConstantSDNode>(Op.getOperand(1)); 3016 AtomicOrdering Ord = static_cast<AtomicOrdering>(OrdN->getZExtValue()); 3017 ARM_MB::MemBOpt Domain = ARM_MB::ISH; 3018 if (Subtarget->isMClass()) { 3019 // Only a full system barrier exists in the M-class architectures. 3020 Domain = ARM_MB::SY; 3021 } else if (Subtarget->isSwift() && Ord == AtomicOrdering::Release) { 3022 // Swift happens to implement ISHST barriers in a way that's compatible with 3023 // Release semantics but weaker than ISH so we'd be fools not to use 3024 // it. Beware: other processors probably don't! 3025 Domain = ARM_MB::ISHST; 3026 } 3027 3028 return DAG.getNode(ISD::INTRINSIC_VOID, dl, MVT::Other, Op.getOperand(0), 3029 DAG.getConstant(Intrinsic::arm_dmb, dl, MVT::i32), 3030 DAG.getConstant(Domain, dl, MVT::i32)); 3031 } 3032 3033 static SDValue LowerPREFETCH(SDValue Op, SelectionDAG &DAG, 3034 const ARMSubtarget *Subtarget) { 3035 // ARM pre v5TE and Thumb1 does not have preload instructions. 3036 if (!(Subtarget->isThumb2() || 3037 (!Subtarget->isThumb1Only() && Subtarget->hasV5TEOps()))) 3038 // Just preserve the chain. 3039 return Op.getOperand(0); 3040 3041 SDLoc dl(Op); 3042 unsigned isRead = ~cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue() & 1; 3043 if (!isRead && 3044 (!Subtarget->hasV7Ops() || !Subtarget->hasMPExtension())) 3045 // ARMv7 with MP extension has PLDW. 3046 return Op.getOperand(0); 3047 3048 unsigned isData = cast<ConstantSDNode>(Op.getOperand(4))->getZExtValue(); 3049 if (Subtarget->isThumb()) { 3050 // Invert the bits. 3051 isRead = ~isRead & 1; 3052 isData = ~isData & 1; 3053 } 3054 3055 return DAG.getNode(ARMISD::PRELOAD, dl, MVT::Other, Op.getOperand(0), 3056 Op.getOperand(1), DAG.getConstant(isRead, dl, MVT::i32), 3057 DAG.getConstant(isData, dl, MVT::i32)); 3058 } 3059 3060 static SDValue LowerVASTART(SDValue Op, SelectionDAG &DAG) { 3061 MachineFunction &MF = DAG.getMachineFunction(); 3062 ARMFunctionInfo *FuncInfo = MF.getInfo<ARMFunctionInfo>(); 3063 3064 // vastart just stores the address of the VarArgsFrameIndex slot into the 3065 // memory location argument. 3066 SDLoc dl(Op); 3067 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout()); 3068 SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT); 3069 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue(); 3070 return DAG.getStore(Op.getOperand(0), dl, FR, Op.getOperand(1), 3071 MachinePointerInfo(SV), false, false, 0); 3072 } 3073 3074 SDValue 3075 ARMTargetLowering::GetF64FormalArgument(CCValAssign &VA, CCValAssign &NextVA, 3076 SDValue &Root, SelectionDAG &DAG, 3077 SDLoc dl) const { 3078 MachineFunction &MF = DAG.getMachineFunction(); 3079 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>(); 3080 3081 const TargetRegisterClass *RC; 3082 if (AFI->isThumb1OnlyFunction()) 3083 RC = &ARM::tGPRRegClass; 3084 else 3085 RC = &ARM::GPRRegClass; 3086 3087 // Transform the arguments stored in physical registers into virtual ones. 3088 unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC); 3089 SDValue ArgValue = DAG.getCopyFromReg(Root, dl, Reg, MVT::i32); 3090 3091 SDValue ArgValue2; 3092 if (NextVA.isMemLoc()) { 3093 MachineFrameInfo *MFI = MF.getFrameInfo(); 3094 int FI = MFI->CreateFixedObject(4, NextVA.getLocMemOffset(), true); 3095 3096 // Create load node to retrieve arguments from the stack. 3097 SDValue FIN = DAG.getFrameIndex(FI, getPointerTy(DAG.getDataLayout())); 3098 ArgValue2 = DAG.getLoad( 3099 MVT::i32, dl, Root, FIN, 3100 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI), false, 3101 false, false, 0); 3102 } else { 3103 Reg = MF.addLiveIn(NextVA.getLocReg(), RC); 3104 ArgValue2 = DAG.getCopyFromReg(Root, dl, Reg, MVT::i32); 3105 } 3106 if (!Subtarget->isLittle()) 3107 std::swap (ArgValue, ArgValue2); 3108 return DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, ArgValue, ArgValue2); 3109 } 3110 3111 // The remaining GPRs hold either the beginning of variable-argument 3112 // data, or the beginning of an aggregate passed by value (usually 3113 // byval). Either way, we allocate stack slots adjacent to the data 3114 // provided by our caller, and store the unallocated registers there. 3115 // If this is a variadic function, the va_list pointer will begin with 3116 // these values; otherwise, this reassembles a (byval) structure that 3117 // was split between registers and memory. 3118 // Return: The frame index registers were stored into. 3119 int 3120 ARMTargetLowering::StoreByValRegs(CCState &CCInfo, SelectionDAG &DAG, 3121 SDLoc dl, SDValue &Chain, 3122 const Value *OrigArg, 3123 unsigned InRegsParamRecordIdx, 3124 int ArgOffset, 3125 unsigned ArgSize) const { 3126 // Currently, two use-cases possible: 3127 // Case #1. Non-var-args function, and we meet first byval parameter. 3128 // Setup first unallocated register as first byval register; 3129 // eat all remained registers 3130 // (these two actions are performed by HandleByVal method). 3131 // Then, here, we initialize stack frame with 3132 // "store-reg" instructions. 3133 // Case #2. Var-args function, that doesn't contain byval parameters. 3134 // The same: eat all remained unallocated registers, 3135 // initialize stack frame. 3136 3137 MachineFunction &MF = DAG.getMachineFunction(); 3138 MachineFrameInfo *MFI = MF.getFrameInfo(); 3139 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>(); 3140 unsigned RBegin, REnd; 3141 if (InRegsParamRecordIdx < CCInfo.getInRegsParamsCount()) { 3142 CCInfo.getInRegsParamInfo(InRegsParamRecordIdx, RBegin, REnd); 3143 } else { 3144 unsigned RBeginIdx = CCInfo.getFirstUnallocated(GPRArgRegs); 3145 RBegin = RBeginIdx == 4 ? (unsigned)ARM::R4 : GPRArgRegs[RBeginIdx]; 3146 REnd = ARM::R4; 3147 } 3148 3149 if (REnd != RBegin) 3150 ArgOffset = -4 * (ARM::R4 - RBegin); 3151 3152 auto PtrVT = getPointerTy(DAG.getDataLayout()); 3153 int FrameIndex = MFI->CreateFixedObject(ArgSize, ArgOffset, false); 3154 SDValue FIN = DAG.getFrameIndex(FrameIndex, PtrVT); 3155 3156 SmallVector<SDValue, 4> MemOps; 3157 const TargetRegisterClass *RC = 3158 AFI->isThumb1OnlyFunction() ? &ARM::tGPRRegClass : &ARM::GPRRegClass; 3159 3160 for (unsigned Reg = RBegin, i = 0; Reg < REnd; ++Reg, ++i) { 3161 unsigned VReg = MF.addLiveIn(Reg, RC); 3162 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i32); 3163 SDValue Store = 3164 DAG.getStore(Val.getValue(1), dl, Val, FIN, 3165 MachinePointerInfo(OrigArg, 4 * i), false, false, 0); 3166 MemOps.push_back(Store); 3167 FIN = DAG.getNode(ISD::ADD, dl, PtrVT, FIN, DAG.getConstant(4, dl, PtrVT)); 3168 } 3169 3170 if (!MemOps.empty()) 3171 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOps); 3172 return FrameIndex; 3173 } 3174 3175 // Setup stack frame, the va_list pointer will start from. 3176 void 3177 ARMTargetLowering::VarArgStyleRegisters(CCState &CCInfo, SelectionDAG &DAG, 3178 SDLoc dl, SDValue &Chain, 3179 unsigned ArgOffset, 3180 unsigned TotalArgRegsSaveSize, 3181 bool ForceMutable) const { 3182 MachineFunction &MF = DAG.getMachineFunction(); 3183 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>(); 3184 3185 // Try to store any remaining integer argument regs 3186 // to their spots on the stack so that they may be loaded by deferencing 3187 // the result of va_next. 3188 // If there is no regs to be stored, just point address after last 3189 // argument passed via stack. 3190 int FrameIndex = StoreByValRegs(CCInfo, DAG, dl, Chain, nullptr, 3191 CCInfo.getInRegsParamsCount(), 3192 CCInfo.getNextStackOffset(), 4); 3193 AFI->setVarArgsFrameIndex(FrameIndex); 3194 } 3195 3196 SDValue 3197 ARMTargetLowering::LowerFormalArguments(SDValue Chain, 3198 CallingConv::ID CallConv, bool isVarArg, 3199 const SmallVectorImpl<ISD::InputArg> 3200 &Ins, 3201 SDLoc dl, SelectionDAG &DAG, 3202 SmallVectorImpl<SDValue> &InVals) 3203 const { 3204 MachineFunction &MF = DAG.getMachineFunction(); 3205 MachineFrameInfo *MFI = MF.getFrameInfo(); 3206 3207 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>(); 3208 3209 // Assign locations to all of the incoming arguments. 3210 SmallVector<CCValAssign, 16> ArgLocs; 3211 ARMCCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), ArgLocs, 3212 *DAG.getContext(), Prologue); 3213 CCInfo.AnalyzeFormalArguments(Ins, 3214 CCAssignFnForNode(CallConv, /* Return*/ false, 3215 isVarArg)); 3216 3217 SmallVector<SDValue, 16> ArgValues; 3218 SDValue ArgValue; 3219 Function::const_arg_iterator CurOrigArg = MF.getFunction()->arg_begin(); 3220 unsigned CurArgIdx = 0; 3221 3222 // Initially ArgRegsSaveSize is zero. 3223 // Then we increase this value each time we meet byval parameter. 3224 // We also increase this value in case of varargs function. 3225 AFI->setArgRegsSaveSize(0); 3226 3227 // Calculate the amount of stack space that we need to allocate to store 3228 // byval and variadic arguments that are passed in registers. 3229 // We need to know this before we allocate the first byval or variadic 3230 // argument, as they will be allocated a stack slot below the CFA (Canonical 3231 // Frame Address, the stack pointer at entry to the function). 3232 unsigned ArgRegBegin = ARM::R4; 3233 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) { 3234 if (CCInfo.getInRegsParamsProcessed() >= CCInfo.getInRegsParamsCount()) 3235 break; 3236 3237 CCValAssign &VA = ArgLocs[i]; 3238 unsigned Index = VA.getValNo(); 3239 ISD::ArgFlagsTy Flags = Ins[Index].Flags; 3240 if (!Flags.isByVal()) 3241 continue; 3242 3243 assert(VA.isMemLoc() && "unexpected byval pointer in reg"); 3244 unsigned RBegin, REnd; 3245 CCInfo.getInRegsParamInfo(CCInfo.getInRegsParamsProcessed(), RBegin, REnd); 3246 ArgRegBegin = std::min(ArgRegBegin, RBegin); 3247 3248 CCInfo.nextInRegsParam(); 3249 } 3250 CCInfo.rewindByValRegsInfo(); 3251 3252 int lastInsIndex = -1; 3253 if (isVarArg && MFI->hasVAStart()) { 3254 unsigned RegIdx = CCInfo.getFirstUnallocated(GPRArgRegs); 3255 if (RegIdx != array_lengthof(GPRArgRegs)) 3256 ArgRegBegin = std::min(ArgRegBegin, (unsigned)GPRArgRegs[RegIdx]); 3257 } 3258 3259 unsigned TotalArgRegsSaveSize = 4 * (ARM::R4 - ArgRegBegin); 3260 AFI->setArgRegsSaveSize(TotalArgRegsSaveSize); 3261 auto PtrVT = getPointerTy(DAG.getDataLayout()); 3262 3263 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) { 3264 CCValAssign &VA = ArgLocs[i]; 3265 if (Ins[VA.getValNo()].isOrigArg()) { 3266 std::advance(CurOrigArg, 3267 Ins[VA.getValNo()].getOrigArgIndex() - CurArgIdx); 3268 CurArgIdx = Ins[VA.getValNo()].getOrigArgIndex(); 3269 } 3270 // Arguments stored in registers. 3271 if (VA.isRegLoc()) { 3272 EVT RegVT = VA.getLocVT(); 3273 3274 if (VA.needsCustom()) { 3275 // f64 and vector types are split up into multiple registers or 3276 // combinations of registers and stack slots. 3277 if (VA.getLocVT() == MVT::v2f64) { 3278 SDValue ArgValue1 = GetF64FormalArgument(VA, ArgLocs[++i], 3279 Chain, DAG, dl); 3280 VA = ArgLocs[++i]; // skip ahead to next loc 3281 SDValue ArgValue2; 3282 if (VA.isMemLoc()) { 3283 int FI = MFI->CreateFixedObject(8, VA.getLocMemOffset(), true); 3284 SDValue FIN = DAG.getFrameIndex(FI, PtrVT); 3285 ArgValue2 = DAG.getLoad( 3286 MVT::f64, dl, Chain, FIN, 3287 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI), 3288 false, false, false, 0); 3289 } else { 3290 ArgValue2 = GetF64FormalArgument(VA, ArgLocs[++i], 3291 Chain, DAG, dl); 3292 } 3293 ArgValue = DAG.getNode(ISD::UNDEF, dl, MVT::v2f64); 3294 ArgValue = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, 3295 ArgValue, ArgValue1, 3296 DAG.getIntPtrConstant(0, dl)); 3297 ArgValue = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, 3298 ArgValue, ArgValue2, 3299 DAG.getIntPtrConstant(1, dl)); 3300 } else 3301 ArgValue = GetF64FormalArgument(VA, ArgLocs[++i], Chain, DAG, dl); 3302 3303 } else { 3304 const TargetRegisterClass *RC; 3305 3306 if (RegVT == MVT::f32) 3307 RC = &ARM::SPRRegClass; 3308 else if (RegVT == MVT::f64) 3309 RC = &ARM::DPRRegClass; 3310 else if (RegVT == MVT::v2f64) 3311 RC = &ARM::QPRRegClass; 3312 else if (RegVT == MVT::i32) 3313 RC = AFI->isThumb1OnlyFunction() ? &ARM::tGPRRegClass 3314 : &ARM::GPRRegClass; 3315 else 3316 llvm_unreachable("RegVT not supported by FORMAL_ARGUMENTS Lowering"); 3317 3318 // Transform the arguments in physical registers into virtual ones. 3319 unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC); 3320 ArgValue = DAG.getCopyFromReg(Chain, dl, Reg, RegVT); 3321 } 3322 3323 // If this is an 8 or 16-bit value, it is really passed promoted 3324 // to 32 bits. Insert an assert[sz]ext to capture this, then 3325 // truncate to the right size. 3326 switch (VA.getLocInfo()) { 3327 default: llvm_unreachable("Unknown loc info!"); 3328 case CCValAssign::Full: break; 3329 case CCValAssign::BCvt: 3330 ArgValue = DAG.getNode(ISD::BITCAST, dl, VA.getValVT(), ArgValue); 3331 break; 3332 case CCValAssign::SExt: 3333 ArgValue = DAG.getNode(ISD::AssertSext, dl, RegVT, ArgValue, 3334 DAG.getValueType(VA.getValVT())); 3335 ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue); 3336 break; 3337 case CCValAssign::ZExt: 3338 ArgValue = DAG.getNode(ISD::AssertZext, dl, RegVT, ArgValue, 3339 DAG.getValueType(VA.getValVT())); 3340 ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue); 3341 break; 3342 } 3343 3344 InVals.push_back(ArgValue); 3345 3346 } else { // VA.isRegLoc() 3347 3348 // sanity check 3349 assert(VA.isMemLoc()); 3350 assert(VA.getValVT() != MVT::i64 && "i64 should already be lowered"); 3351 3352 int index = VA.getValNo(); 3353 3354 // Some Ins[] entries become multiple ArgLoc[] entries. 3355 // Process them only once. 3356 if (index != lastInsIndex) 3357 { 3358 ISD::ArgFlagsTy Flags = Ins[index].Flags; 3359 // FIXME: For now, all byval parameter objects are marked mutable. 3360 // This can be changed with more analysis. 3361 // In case of tail call optimization mark all arguments mutable. 3362 // Since they could be overwritten by lowering of arguments in case of 3363 // a tail call. 3364 if (Flags.isByVal()) { 3365 assert(Ins[index].isOrigArg() && 3366 "Byval arguments cannot be implicit"); 3367 unsigned CurByValIndex = CCInfo.getInRegsParamsProcessed(); 3368 3369 int FrameIndex = StoreByValRegs( 3370 CCInfo, DAG, dl, Chain, &*CurOrigArg, CurByValIndex, 3371 VA.getLocMemOffset(), Flags.getByValSize()); 3372 InVals.push_back(DAG.getFrameIndex(FrameIndex, PtrVT)); 3373 CCInfo.nextInRegsParam(); 3374 } else { 3375 unsigned FIOffset = VA.getLocMemOffset(); 3376 int FI = MFI->CreateFixedObject(VA.getLocVT().getSizeInBits()/8, 3377 FIOffset, true); 3378 3379 // Create load nodes to retrieve arguments from the stack. 3380 SDValue FIN = DAG.getFrameIndex(FI, PtrVT); 3381 InVals.push_back(DAG.getLoad( 3382 VA.getValVT(), dl, Chain, FIN, 3383 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI), 3384 false, false, false, 0)); 3385 } 3386 lastInsIndex = index; 3387 } 3388 } 3389 } 3390 3391 // varargs 3392 if (isVarArg && MFI->hasVAStart()) 3393 VarArgStyleRegisters(CCInfo, DAG, dl, Chain, 3394 CCInfo.getNextStackOffset(), 3395 TotalArgRegsSaveSize); 3396 3397 AFI->setArgumentStackSize(CCInfo.getNextStackOffset()); 3398 3399 return Chain; 3400 } 3401 3402 /// isFloatingPointZero - Return true if this is +0.0. 3403 static bool isFloatingPointZero(SDValue Op) { 3404 if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Op)) 3405 return CFP->getValueAPF().isPosZero(); 3406 else if (ISD::isEXTLoad(Op.getNode()) || ISD::isNON_EXTLoad(Op.getNode())) { 3407 // Maybe this has already been legalized into the constant pool? 3408 if (Op.getOperand(1).getOpcode() == ARMISD::Wrapper) { 3409 SDValue WrapperOp = Op.getOperand(1).getOperand(0); 3410 if (ConstantPoolSDNode *CP = dyn_cast<ConstantPoolSDNode>(WrapperOp)) 3411 if (const ConstantFP *CFP = dyn_cast<ConstantFP>(CP->getConstVal())) 3412 return CFP->getValueAPF().isPosZero(); 3413 } 3414 } else if (Op->getOpcode() == ISD::BITCAST && 3415 Op->getValueType(0) == MVT::f64) { 3416 // Handle (ISD::BITCAST (ARMISD::VMOVIMM (ISD::TargetConstant 0)) MVT::f64) 3417 // created by LowerConstantFP(). 3418 SDValue BitcastOp = Op->getOperand(0); 3419 if (BitcastOp->getOpcode() == ARMISD::VMOVIMM && 3420 isNullConstant(BitcastOp->getOperand(0))) 3421 return true; 3422 } 3423 return false; 3424 } 3425 3426 /// Returns appropriate ARM CMP (cmp) and corresponding condition code for 3427 /// the given operands. 3428 SDValue 3429 ARMTargetLowering::getARMCmp(SDValue LHS, SDValue RHS, ISD::CondCode CC, 3430 SDValue &ARMcc, SelectionDAG &DAG, 3431 SDLoc dl) const { 3432 if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS.getNode())) { 3433 unsigned C = RHSC->getZExtValue(); 3434 if (!isLegalICmpImmediate(C)) { 3435 // Constant does not fit, try adjusting it by one? 3436 switch (CC) { 3437 default: break; 3438 case ISD::SETLT: 3439 case ISD::SETGE: 3440 if (C != 0x80000000 && isLegalICmpImmediate(C-1)) { 3441 CC = (CC == ISD::SETLT) ? ISD::SETLE : ISD::SETGT; 3442 RHS = DAG.getConstant(C - 1, dl, MVT::i32); 3443 } 3444 break; 3445 case ISD::SETULT: 3446 case ISD::SETUGE: 3447 if (C != 0 && isLegalICmpImmediate(C-1)) { 3448 CC = (CC == ISD::SETULT) ? ISD::SETULE : ISD::SETUGT; 3449 RHS = DAG.getConstant(C - 1, dl, MVT::i32); 3450 } 3451 break; 3452 case ISD::SETLE: 3453 case ISD::SETGT: 3454 if (C != 0x7fffffff && isLegalICmpImmediate(C+1)) { 3455 CC = (CC == ISD::SETLE) ? ISD::SETLT : ISD::SETGE; 3456 RHS = DAG.getConstant(C + 1, dl, MVT::i32); 3457 } 3458 break; 3459 case ISD::SETULE: 3460 case ISD::SETUGT: 3461 if (C != 0xffffffff && isLegalICmpImmediate(C+1)) { 3462 CC = (CC == ISD::SETULE) ? ISD::SETULT : ISD::SETUGE; 3463 RHS = DAG.getConstant(C + 1, dl, MVT::i32); 3464 } 3465 break; 3466 } 3467 } 3468 } 3469 3470 ARMCC::CondCodes CondCode = IntCCToARMCC(CC); 3471 ARMISD::NodeType CompareType; 3472 switch (CondCode) { 3473 default: 3474 CompareType = ARMISD::CMP; 3475 break; 3476 case ARMCC::EQ: 3477 case ARMCC::NE: 3478 // Uses only Z Flag 3479 CompareType = ARMISD::CMPZ; 3480 break; 3481 } 3482 ARMcc = DAG.getConstant(CondCode, dl, MVT::i32); 3483 return DAG.getNode(CompareType, dl, MVT::Glue, LHS, RHS); 3484 } 3485 3486 /// Returns a appropriate VFP CMP (fcmp{s|d}+fmstat) for the given operands. 3487 SDValue 3488 ARMTargetLowering::getVFPCmp(SDValue LHS, SDValue RHS, SelectionDAG &DAG, 3489 SDLoc dl) const { 3490 assert(!Subtarget->isFPOnlySP() || RHS.getValueType() != MVT::f64); 3491 SDValue Cmp; 3492 if (!isFloatingPointZero(RHS)) 3493 Cmp = DAG.getNode(ARMISD::CMPFP, dl, MVT::Glue, LHS, RHS); 3494 else 3495 Cmp = DAG.getNode(ARMISD::CMPFPw0, dl, MVT::Glue, LHS); 3496 return DAG.getNode(ARMISD::FMSTAT, dl, MVT::Glue, Cmp); 3497 } 3498 3499 /// duplicateCmp - Glue values can have only one use, so this function 3500 /// duplicates a comparison node. 3501 SDValue 3502 ARMTargetLowering::duplicateCmp(SDValue Cmp, SelectionDAG &DAG) const { 3503 unsigned Opc = Cmp.getOpcode(); 3504 SDLoc DL(Cmp); 3505 if (Opc == ARMISD::CMP || Opc == ARMISD::CMPZ) 3506 return DAG.getNode(Opc, DL, MVT::Glue, Cmp.getOperand(0),Cmp.getOperand(1)); 3507 3508 assert(Opc == ARMISD::FMSTAT && "unexpected comparison operation"); 3509 Cmp = Cmp.getOperand(0); 3510 Opc = Cmp.getOpcode(); 3511 if (Opc == ARMISD::CMPFP) 3512 Cmp = DAG.getNode(Opc, DL, MVT::Glue, Cmp.getOperand(0),Cmp.getOperand(1)); 3513 else { 3514 assert(Opc == ARMISD::CMPFPw0 && "unexpected operand of FMSTAT"); 3515 Cmp = DAG.getNode(Opc, DL, MVT::Glue, Cmp.getOperand(0)); 3516 } 3517 return DAG.getNode(ARMISD::FMSTAT, DL, MVT::Glue, Cmp); 3518 } 3519 3520 std::pair<SDValue, SDValue> 3521 ARMTargetLowering::getARMXALUOOp(SDValue Op, SelectionDAG &DAG, 3522 SDValue &ARMcc) const { 3523 assert(Op.getValueType() == MVT::i32 && "Unsupported value type"); 3524 3525 SDValue Value, OverflowCmp; 3526 SDValue LHS = Op.getOperand(0); 3527 SDValue RHS = Op.getOperand(1); 3528 SDLoc dl(Op); 3529 3530 // FIXME: We are currently always generating CMPs because we don't support 3531 // generating CMN through the backend. This is not as good as the natural 3532 // CMP case because it causes a register dependency and cannot be folded 3533 // later. 3534 3535 switch (Op.getOpcode()) { 3536 default: 3537 llvm_unreachable("Unknown overflow instruction!"); 3538 case ISD::SADDO: 3539 ARMcc = DAG.getConstant(ARMCC::VC, dl, MVT::i32); 3540 Value = DAG.getNode(ISD::ADD, dl, Op.getValueType(), LHS, RHS); 3541 OverflowCmp = DAG.getNode(ARMISD::CMP, dl, MVT::Glue, Value, LHS); 3542 break; 3543 case ISD::UADDO: 3544 ARMcc = DAG.getConstant(ARMCC::HS, dl, MVT::i32); 3545 Value = DAG.getNode(ISD::ADD, dl, Op.getValueType(), LHS, RHS); 3546 OverflowCmp = DAG.getNode(ARMISD::CMP, dl, MVT::Glue, Value, LHS); 3547 break; 3548 case ISD::SSUBO: 3549 ARMcc = DAG.getConstant(ARMCC::VC, dl, MVT::i32); 3550 Value = DAG.getNode(ISD::SUB, dl, Op.getValueType(), LHS, RHS); 3551 OverflowCmp = DAG.getNode(ARMISD::CMP, dl, MVT::Glue, LHS, RHS); 3552 break; 3553 case ISD::USUBO: 3554 ARMcc = DAG.getConstant(ARMCC::HS, dl, MVT::i32); 3555 Value = DAG.getNode(ISD::SUB, dl, Op.getValueType(), LHS, RHS); 3556 OverflowCmp = DAG.getNode(ARMISD::CMP, dl, MVT::Glue, LHS, RHS); 3557 break; 3558 } // switch (...) 3559 3560 return std::make_pair(Value, OverflowCmp); 3561 } 3562 3563 3564 SDValue 3565 ARMTargetLowering::LowerXALUO(SDValue Op, SelectionDAG &DAG) const { 3566 // Let legalize expand this if it isn't a legal type yet. 3567 if (!DAG.getTargetLoweringInfo().isTypeLegal(Op.getValueType())) 3568 return SDValue(); 3569 3570 SDValue Value, OverflowCmp; 3571 SDValue ARMcc; 3572 std::tie(Value, OverflowCmp) = getARMXALUOOp(Op, DAG, ARMcc); 3573 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32); 3574 SDLoc dl(Op); 3575 // We use 0 and 1 as false and true values. 3576 SDValue TVal = DAG.getConstant(1, dl, MVT::i32); 3577 SDValue FVal = DAG.getConstant(0, dl, MVT::i32); 3578 EVT VT = Op.getValueType(); 3579 3580 SDValue Overflow = DAG.getNode(ARMISD::CMOV, dl, VT, TVal, FVal, 3581 ARMcc, CCR, OverflowCmp); 3582 3583 SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32); 3584 return DAG.getNode(ISD::MERGE_VALUES, dl, VTs, Value, Overflow); 3585 } 3586 3587 3588 SDValue ARMTargetLowering::LowerSELECT(SDValue Op, SelectionDAG &DAG) const { 3589 SDValue Cond = Op.getOperand(0); 3590 SDValue SelectTrue = Op.getOperand(1); 3591 SDValue SelectFalse = Op.getOperand(2); 3592 SDLoc dl(Op); 3593 unsigned Opc = Cond.getOpcode(); 3594 3595 if (Cond.getResNo() == 1 && 3596 (Opc == ISD::SADDO || Opc == ISD::UADDO || Opc == ISD::SSUBO || 3597 Opc == ISD::USUBO)) { 3598 if (!DAG.getTargetLoweringInfo().isTypeLegal(Cond->getValueType(0))) 3599 return SDValue(); 3600 3601 SDValue Value, OverflowCmp; 3602 SDValue ARMcc; 3603 std::tie(Value, OverflowCmp) = getARMXALUOOp(Cond, DAG, ARMcc); 3604 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32); 3605 EVT VT = Op.getValueType(); 3606 3607 return getCMOV(dl, VT, SelectTrue, SelectFalse, ARMcc, CCR, 3608 OverflowCmp, DAG); 3609 } 3610 3611 // Convert: 3612 // 3613 // (select (cmov 1, 0, cond), t, f) -> (cmov t, f, cond) 3614 // (select (cmov 0, 1, cond), t, f) -> (cmov f, t, cond) 3615 // 3616 if (Cond.getOpcode() == ARMISD::CMOV && Cond.hasOneUse()) { 3617 const ConstantSDNode *CMOVTrue = 3618 dyn_cast<ConstantSDNode>(Cond.getOperand(0)); 3619 const ConstantSDNode *CMOVFalse = 3620 dyn_cast<ConstantSDNode>(Cond.getOperand(1)); 3621 3622 if (CMOVTrue && CMOVFalse) { 3623 unsigned CMOVTrueVal = CMOVTrue->getZExtValue(); 3624 unsigned CMOVFalseVal = CMOVFalse->getZExtValue(); 3625 3626 SDValue True; 3627 SDValue False; 3628 if (CMOVTrueVal == 1 && CMOVFalseVal == 0) { 3629 True = SelectTrue; 3630 False = SelectFalse; 3631 } else if (CMOVTrueVal == 0 && CMOVFalseVal == 1) { 3632 True = SelectFalse; 3633 False = SelectTrue; 3634 } 3635 3636 if (True.getNode() && False.getNode()) { 3637 EVT VT = Op.getValueType(); 3638 SDValue ARMcc = Cond.getOperand(2); 3639 SDValue CCR = Cond.getOperand(3); 3640 SDValue Cmp = duplicateCmp(Cond.getOperand(4), DAG); 3641 assert(True.getValueType() == VT); 3642 return getCMOV(dl, VT, True, False, ARMcc, CCR, Cmp, DAG); 3643 } 3644 } 3645 } 3646 3647 // ARM's BooleanContents value is UndefinedBooleanContent. Mask out the 3648 // undefined bits before doing a full-word comparison with zero. 3649 Cond = DAG.getNode(ISD::AND, dl, Cond.getValueType(), Cond, 3650 DAG.getConstant(1, dl, Cond.getValueType())); 3651 3652 return DAG.getSelectCC(dl, Cond, 3653 DAG.getConstant(0, dl, Cond.getValueType()), 3654 SelectTrue, SelectFalse, ISD::SETNE); 3655 } 3656 3657 static void checkVSELConstraints(ISD::CondCode CC, ARMCC::CondCodes &CondCode, 3658 bool &swpCmpOps, bool &swpVselOps) { 3659 // Start by selecting the GE condition code for opcodes that return true for 3660 // 'equality' 3661 if (CC == ISD::SETUGE || CC == ISD::SETOGE || CC == ISD::SETOLE || 3662 CC == ISD::SETULE) 3663 CondCode = ARMCC::GE; 3664 3665 // and GT for opcodes that return false for 'equality'. 3666 else if (CC == ISD::SETUGT || CC == ISD::SETOGT || CC == ISD::SETOLT || 3667 CC == ISD::SETULT) 3668 CondCode = ARMCC::GT; 3669 3670 // Since we are constrained to GE/GT, if the opcode contains 'less', we need 3671 // to swap the compare operands. 3672 if (CC == ISD::SETOLE || CC == ISD::SETULE || CC == ISD::SETOLT || 3673 CC == ISD::SETULT) 3674 swpCmpOps = true; 3675 3676 // Both GT and GE are ordered comparisons, and return false for 'unordered'. 3677 // If we have an unordered opcode, we need to swap the operands to the VSEL 3678 // instruction (effectively negating the condition). 3679 // 3680 // This also has the effect of swapping which one of 'less' or 'greater' 3681 // returns true, so we also swap the compare operands. It also switches 3682 // whether we return true for 'equality', so we compensate by picking the 3683 // opposite condition code to our original choice. 3684 if (CC == ISD::SETULE || CC == ISD::SETULT || CC == ISD::SETUGE || 3685 CC == ISD::SETUGT) { 3686 swpCmpOps = !swpCmpOps; 3687 swpVselOps = !swpVselOps; 3688 CondCode = CondCode == ARMCC::GT ? ARMCC::GE : ARMCC::GT; 3689 } 3690 3691 // 'ordered' is 'anything but unordered', so use the VS condition code and 3692 // swap the VSEL operands. 3693 if (CC == ISD::SETO) { 3694 CondCode = ARMCC::VS; 3695 swpVselOps = true; 3696 } 3697 3698 // 'unordered or not equal' is 'anything but equal', so use the EQ condition 3699 // code and swap the VSEL operands. 3700 if (CC == ISD::SETUNE) { 3701 CondCode = ARMCC::EQ; 3702 swpVselOps = true; 3703 } 3704 } 3705 3706 SDValue ARMTargetLowering::getCMOV(SDLoc dl, EVT VT, SDValue FalseVal, 3707 SDValue TrueVal, SDValue ARMcc, SDValue CCR, 3708 SDValue Cmp, SelectionDAG &DAG) const { 3709 if (Subtarget->isFPOnlySP() && VT == MVT::f64) { 3710 FalseVal = DAG.getNode(ARMISD::VMOVRRD, dl, 3711 DAG.getVTList(MVT::i32, MVT::i32), FalseVal); 3712 TrueVal = DAG.getNode(ARMISD::VMOVRRD, dl, 3713 DAG.getVTList(MVT::i32, MVT::i32), TrueVal); 3714 3715 SDValue TrueLow = TrueVal.getValue(0); 3716 SDValue TrueHigh = TrueVal.getValue(1); 3717 SDValue FalseLow = FalseVal.getValue(0); 3718 SDValue FalseHigh = FalseVal.getValue(1); 3719 3720 SDValue Low = DAG.getNode(ARMISD::CMOV, dl, MVT::i32, FalseLow, TrueLow, 3721 ARMcc, CCR, Cmp); 3722 SDValue High = DAG.getNode(ARMISD::CMOV, dl, MVT::i32, FalseHigh, TrueHigh, 3723 ARMcc, CCR, duplicateCmp(Cmp, DAG)); 3724 3725 return DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Low, High); 3726 } else { 3727 return DAG.getNode(ARMISD::CMOV, dl, VT, FalseVal, TrueVal, ARMcc, CCR, 3728 Cmp); 3729 } 3730 } 3731 3732 SDValue ARMTargetLowering::LowerSELECT_CC(SDValue Op, SelectionDAG &DAG) const { 3733 EVT VT = Op.getValueType(); 3734 SDValue LHS = Op.getOperand(0); 3735 SDValue RHS = Op.getOperand(1); 3736 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(4))->get(); 3737 SDValue TrueVal = Op.getOperand(2); 3738 SDValue FalseVal = Op.getOperand(3); 3739 SDLoc dl(Op); 3740 3741 if (Subtarget->isFPOnlySP() && LHS.getValueType() == MVT::f64) { 3742 DAG.getTargetLoweringInfo().softenSetCCOperands(DAG, MVT::f64, LHS, RHS, CC, 3743 dl); 3744 3745 // If softenSetCCOperands only returned one value, we should compare it to 3746 // zero. 3747 if (!RHS.getNode()) { 3748 RHS = DAG.getConstant(0, dl, LHS.getValueType()); 3749 CC = ISD::SETNE; 3750 } 3751 } 3752 3753 if (LHS.getValueType() == MVT::i32) { 3754 // Try to generate VSEL on ARMv8. 3755 // The VSEL instruction can't use all the usual ARM condition 3756 // codes: it only has two bits to select the condition code, so it's 3757 // constrained to use only GE, GT, VS and EQ. 3758 // 3759 // To implement all the various ISD::SETXXX opcodes, we sometimes need to 3760 // swap the operands of the previous compare instruction (effectively 3761 // inverting the compare condition, swapping 'less' and 'greater') and 3762 // sometimes need to swap the operands to the VSEL (which inverts the 3763 // condition in the sense of firing whenever the previous condition didn't) 3764 if (Subtarget->hasFPARMv8() && (TrueVal.getValueType() == MVT::f32 || 3765 TrueVal.getValueType() == MVT::f64)) { 3766 ARMCC::CondCodes CondCode = IntCCToARMCC(CC); 3767 if (CondCode == ARMCC::LT || CondCode == ARMCC::LE || 3768 CondCode == ARMCC::VC || CondCode == ARMCC::NE) { 3769 CC = ISD::getSetCCInverse(CC, true); 3770 std::swap(TrueVal, FalseVal); 3771 } 3772 } 3773 3774 SDValue ARMcc; 3775 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32); 3776 SDValue Cmp = getARMCmp(LHS, RHS, CC, ARMcc, DAG, dl); 3777 return getCMOV(dl, VT, FalseVal, TrueVal, ARMcc, CCR, Cmp, DAG); 3778 } 3779 3780 ARMCC::CondCodes CondCode, CondCode2; 3781 FPCCToARMCC(CC, CondCode, CondCode2); 3782 3783 // Try to generate VMAXNM/VMINNM on ARMv8. 3784 if (Subtarget->hasFPARMv8() && (TrueVal.getValueType() == MVT::f32 || 3785 TrueVal.getValueType() == MVT::f64)) { 3786 bool swpCmpOps = false; 3787 bool swpVselOps = false; 3788 checkVSELConstraints(CC, CondCode, swpCmpOps, swpVselOps); 3789 3790 if (CondCode == ARMCC::GT || CondCode == ARMCC::GE || 3791 CondCode == ARMCC::VS || CondCode == ARMCC::EQ) { 3792 if (swpCmpOps) 3793 std::swap(LHS, RHS); 3794 if (swpVselOps) 3795 std::swap(TrueVal, FalseVal); 3796 } 3797 } 3798 3799 SDValue ARMcc = DAG.getConstant(CondCode, dl, MVT::i32); 3800 SDValue Cmp = getVFPCmp(LHS, RHS, DAG, dl); 3801 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32); 3802 SDValue Result = getCMOV(dl, VT, FalseVal, TrueVal, ARMcc, CCR, Cmp, DAG); 3803 if (CondCode2 != ARMCC::AL) { 3804 SDValue ARMcc2 = DAG.getConstant(CondCode2, dl, MVT::i32); 3805 // FIXME: Needs another CMP because flag can have but one use. 3806 SDValue Cmp2 = getVFPCmp(LHS, RHS, DAG, dl); 3807 Result = getCMOV(dl, VT, Result, TrueVal, ARMcc2, CCR, Cmp2, DAG); 3808 } 3809 return Result; 3810 } 3811 3812 /// canChangeToInt - Given the fp compare operand, return true if it is suitable 3813 /// to morph to an integer compare sequence. 3814 static bool canChangeToInt(SDValue Op, bool &SeenZero, 3815 const ARMSubtarget *Subtarget) { 3816 SDNode *N = Op.getNode(); 3817 if (!N->hasOneUse()) 3818 // Otherwise it requires moving the value from fp to integer registers. 3819 return false; 3820 if (!N->getNumValues()) 3821 return false; 3822 EVT VT = Op.getValueType(); 3823 if (VT != MVT::f32 && !Subtarget->isFPBrccSlow()) 3824 // f32 case is generally profitable. f64 case only makes sense when vcmpe + 3825 // vmrs are very slow, e.g. cortex-a8. 3826 return false; 3827 3828 if (isFloatingPointZero(Op)) { 3829 SeenZero = true; 3830 return true; 3831 } 3832 return ISD::isNormalLoad(N); 3833 } 3834 3835 static SDValue bitcastf32Toi32(SDValue Op, SelectionDAG &DAG) { 3836 if (isFloatingPointZero(Op)) 3837 return DAG.getConstant(0, SDLoc(Op), MVT::i32); 3838 3839 if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Op)) 3840 return DAG.getLoad(MVT::i32, SDLoc(Op), 3841 Ld->getChain(), Ld->getBasePtr(), Ld->getPointerInfo(), 3842 Ld->isVolatile(), Ld->isNonTemporal(), 3843 Ld->isInvariant(), Ld->getAlignment()); 3844 3845 llvm_unreachable("Unknown VFP cmp argument!"); 3846 } 3847 3848 static void expandf64Toi32(SDValue Op, SelectionDAG &DAG, 3849 SDValue &RetVal1, SDValue &RetVal2) { 3850 SDLoc dl(Op); 3851 3852 if (isFloatingPointZero(Op)) { 3853 RetVal1 = DAG.getConstant(0, dl, MVT::i32); 3854 RetVal2 = DAG.getConstant(0, dl, MVT::i32); 3855 return; 3856 } 3857 3858 if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Op)) { 3859 SDValue Ptr = Ld->getBasePtr(); 3860 RetVal1 = DAG.getLoad(MVT::i32, dl, 3861 Ld->getChain(), Ptr, 3862 Ld->getPointerInfo(), 3863 Ld->isVolatile(), Ld->isNonTemporal(), 3864 Ld->isInvariant(), Ld->getAlignment()); 3865 3866 EVT PtrType = Ptr.getValueType(); 3867 unsigned NewAlign = MinAlign(Ld->getAlignment(), 4); 3868 SDValue NewPtr = DAG.getNode(ISD::ADD, dl, 3869 PtrType, Ptr, DAG.getConstant(4, dl, PtrType)); 3870 RetVal2 = DAG.getLoad(MVT::i32, dl, 3871 Ld->getChain(), NewPtr, 3872 Ld->getPointerInfo().getWithOffset(4), 3873 Ld->isVolatile(), Ld->isNonTemporal(), 3874 Ld->isInvariant(), NewAlign); 3875 return; 3876 } 3877 3878 llvm_unreachable("Unknown VFP cmp argument!"); 3879 } 3880 3881 /// OptimizeVFPBrcond - With -enable-unsafe-fp-math, it's legal to optimize some 3882 /// f32 and even f64 comparisons to integer ones. 3883 SDValue 3884 ARMTargetLowering::OptimizeVFPBrcond(SDValue Op, SelectionDAG &DAG) const { 3885 SDValue Chain = Op.getOperand(0); 3886 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(1))->get(); 3887 SDValue LHS = Op.getOperand(2); 3888 SDValue RHS = Op.getOperand(3); 3889 SDValue Dest = Op.getOperand(4); 3890 SDLoc dl(Op); 3891 3892 bool LHSSeenZero = false; 3893 bool LHSOk = canChangeToInt(LHS, LHSSeenZero, Subtarget); 3894 bool RHSSeenZero = false; 3895 bool RHSOk = canChangeToInt(RHS, RHSSeenZero, Subtarget); 3896 if (LHSOk && RHSOk && (LHSSeenZero || RHSSeenZero)) { 3897 // If unsafe fp math optimization is enabled and there are no other uses of 3898 // the CMP operands, and the condition code is EQ or NE, we can optimize it 3899 // to an integer comparison. 3900 if (CC == ISD::SETOEQ) 3901 CC = ISD::SETEQ; 3902 else if (CC == ISD::SETUNE) 3903 CC = ISD::SETNE; 3904 3905 SDValue Mask = DAG.getConstant(0x7fffffff, dl, MVT::i32); 3906 SDValue ARMcc; 3907 if (LHS.getValueType() == MVT::f32) { 3908 LHS = DAG.getNode(ISD::AND, dl, MVT::i32, 3909 bitcastf32Toi32(LHS, DAG), Mask); 3910 RHS = DAG.getNode(ISD::AND, dl, MVT::i32, 3911 bitcastf32Toi32(RHS, DAG), Mask); 3912 SDValue Cmp = getARMCmp(LHS, RHS, CC, ARMcc, DAG, dl); 3913 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32); 3914 return DAG.getNode(ARMISD::BRCOND, dl, MVT::Other, 3915 Chain, Dest, ARMcc, CCR, Cmp); 3916 } 3917 3918 SDValue LHS1, LHS2; 3919 SDValue RHS1, RHS2; 3920 expandf64Toi32(LHS, DAG, LHS1, LHS2); 3921 expandf64Toi32(RHS, DAG, RHS1, RHS2); 3922 LHS2 = DAG.getNode(ISD::AND, dl, MVT::i32, LHS2, Mask); 3923 RHS2 = DAG.getNode(ISD::AND, dl, MVT::i32, RHS2, Mask); 3924 ARMCC::CondCodes CondCode = IntCCToARMCC(CC); 3925 ARMcc = DAG.getConstant(CondCode, dl, MVT::i32); 3926 SDVTList VTList = DAG.getVTList(MVT::Other, MVT::Glue); 3927 SDValue Ops[] = { Chain, ARMcc, LHS1, LHS2, RHS1, RHS2, Dest }; 3928 return DAG.getNode(ARMISD::BCC_i64, dl, VTList, Ops); 3929 } 3930 3931 return SDValue(); 3932 } 3933 3934 SDValue ARMTargetLowering::LowerBR_CC(SDValue Op, SelectionDAG &DAG) const { 3935 SDValue Chain = Op.getOperand(0); 3936 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(1))->get(); 3937 SDValue LHS = Op.getOperand(2); 3938 SDValue RHS = Op.getOperand(3); 3939 SDValue Dest = Op.getOperand(4); 3940 SDLoc dl(Op); 3941 3942 if (Subtarget->isFPOnlySP() && LHS.getValueType() == MVT::f64) { 3943 DAG.getTargetLoweringInfo().softenSetCCOperands(DAG, MVT::f64, LHS, RHS, CC, 3944 dl); 3945 3946 // If softenSetCCOperands only returned one value, we should compare it to 3947 // zero. 3948 if (!RHS.getNode()) { 3949 RHS = DAG.getConstant(0, dl, LHS.getValueType()); 3950 CC = ISD::SETNE; 3951 } 3952 } 3953 3954 if (LHS.getValueType() == MVT::i32) { 3955 SDValue ARMcc; 3956 SDValue Cmp = getARMCmp(LHS, RHS, CC, ARMcc, DAG, dl); 3957 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32); 3958 return DAG.getNode(ARMISD::BRCOND, dl, MVT::Other, 3959 Chain, Dest, ARMcc, CCR, Cmp); 3960 } 3961 3962 assert(LHS.getValueType() == MVT::f32 || LHS.getValueType() == MVT::f64); 3963 3964 if (getTargetMachine().Options.UnsafeFPMath && 3965 (CC == ISD::SETEQ || CC == ISD::SETOEQ || 3966 CC == ISD::SETNE || CC == ISD::SETUNE)) { 3967 if (SDValue Result = OptimizeVFPBrcond(Op, DAG)) 3968 return Result; 3969 } 3970 3971 ARMCC::CondCodes CondCode, CondCode2; 3972 FPCCToARMCC(CC, CondCode, CondCode2); 3973 3974 SDValue ARMcc = DAG.getConstant(CondCode, dl, MVT::i32); 3975 SDValue Cmp = getVFPCmp(LHS, RHS, DAG, dl); 3976 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32); 3977 SDVTList VTList = DAG.getVTList(MVT::Other, MVT::Glue); 3978 SDValue Ops[] = { Chain, Dest, ARMcc, CCR, Cmp }; 3979 SDValue Res = DAG.getNode(ARMISD::BRCOND, dl, VTList, Ops); 3980 if (CondCode2 != ARMCC::AL) { 3981 ARMcc = DAG.getConstant(CondCode2, dl, MVT::i32); 3982 SDValue Ops[] = { Res, Dest, ARMcc, CCR, Res.getValue(1) }; 3983 Res = DAG.getNode(ARMISD::BRCOND, dl, VTList, Ops); 3984 } 3985 return Res; 3986 } 3987 3988 SDValue ARMTargetLowering::LowerBR_JT(SDValue Op, SelectionDAG &DAG) const { 3989 SDValue Chain = Op.getOperand(0); 3990 SDValue Table = Op.getOperand(1); 3991 SDValue Index = Op.getOperand(2); 3992 SDLoc dl(Op); 3993 3994 EVT PTy = getPointerTy(DAG.getDataLayout()); 3995 JumpTableSDNode *JT = cast<JumpTableSDNode>(Table); 3996 SDValue JTI = DAG.getTargetJumpTable(JT->getIndex(), PTy); 3997 Table = DAG.getNode(ARMISD::WrapperJT, dl, MVT::i32, JTI); 3998 Index = DAG.getNode(ISD::MUL, dl, PTy, Index, DAG.getConstant(4, dl, PTy)); 3999 SDValue Addr = DAG.getNode(ISD::ADD, dl, PTy, Index, Table); 4000 if (Subtarget->isThumb2()) { 4001 // Thumb2 uses a two-level jump. That is, it jumps into the jump table 4002 // which does another jump to the destination. This also makes it easier 4003 // to translate it to TBB / TBH later. 4004 // FIXME: This might not work if the function is extremely large. 4005 return DAG.getNode(ARMISD::BR2_JT, dl, MVT::Other, Chain, 4006 Addr, Op.getOperand(2), JTI); 4007 } 4008 if (getTargetMachine().getRelocationModel() == Reloc::PIC_) { 4009 Addr = 4010 DAG.getLoad((EVT)MVT::i32, dl, Chain, Addr, 4011 MachinePointerInfo::getJumpTable(DAG.getMachineFunction()), 4012 false, false, false, 0); 4013 Chain = Addr.getValue(1); 4014 Addr = DAG.getNode(ISD::ADD, dl, PTy, Addr, Table); 4015 return DAG.getNode(ARMISD::BR_JT, dl, MVT::Other, Chain, Addr, JTI); 4016 } else { 4017 Addr = 4018 DAG.getLoad(PTy, dl, Chain, Addr, 4019 MachinePointerInfo::getJumpTable(DAG.getMachineFunction()), 4020 false, false, false, 0); 4021 Chain = Addr.getValue(1); 4022 return DAG.getNode(ARMISD::BR_JT, dl, MVT::Other, Chain, Addr, JTI); 4023 } 4024 } 4025 4026 static SDValue LowerVectorFP_TO_INT(SDValue Op, SelectionDAG &DAG) { 4027 EVT VT = Op.getValueType(); 4028 SDLoc dl(Op); 4029 4030 if (Op.getValueType().getVectorElementType() == MVT::i32) { 4031 if (Op.getOperand(0).getValueType().getVectorElementType() == MVT::f32) 4032 return Op; 4033 return DAG.UnrollVectorOp(Op.getNode()); 4034 } 4035 4036 assert(Op.getOperand(0).getValueType() == MVT::v4f32 && 4037 "Invalid type for custom lowering!"); 4038 if (VT != MVT::v4i16) 4039 return DAG.UnrollVectorOp(Op.getNode()); 4040 4041 Op = DAG.getNode(Op.getOpcode(), dl, MVT::v4i32, Op.getOperand(0)); 4042 return DAG.getNode(ISD::TRUNCATE, dl, VT, Op); 4043 } 4044 4045 SDValue ARMTargetLowering::LowerFP_TO_INT(SDValue Op, SelectionDAG &DAG) const { 4046 EVT VT = Op.getValueType(); 4047 if (VT.isVector()) 4048 return LowerVectorFP_TO_INT(Op, DAG); 4049 if (Subtarget->isFPOnlySP() && Op.getOperand(0).getValueType() == MVT::f64) { 4050 RTLIB::Libcall LC; 4051 if (Op.getOpcode() == ISD::FP_TO_SINT) 4052 LC = RTLIB::getFPTOSINT(Op.getOperand(0).getValueType(), 4053 Op.getValueType()); 4054 else 4055 LC = RTLIB::getFPTOUINT(Op.getOperand(0).getValueType(), 4056 Op.getValueType()); 4057 return makeLibCall(DAG, LC, Op.getValueType(), Op.getOperand(0), 4058 /*isSigned*/ false, SDLoc(Op)).first; 4059 } 4060 4061 return Op; 4062 } 4063 4064 static SDValue LowerVectorINT_TO_FP(SDValue Op, SelectionDAG &DAG) { 4065 EVT VT = Op.getValueType(); 4066 SDLoc dl(Op); 4067 4068 if (Op.getOperand(0).getValueType().getVectorElementType() == MVT::i32) { 4069 if (VT.getVectorElementType() == MVT::f32) 4070 return Op; 4071 return DAG.UnrollVectorOp(Op.getNode()); 4072 } 4073 4074 assert(Op.getOperand(0).getValueType() == MVT::v4i16 && 4075 "Invalid type for custom lowering!"); 4076 if (VT != MVT::v4f32) 4077 return DAG.UnrollVectorOp(Op.getNode()); 4078 4079 unsigned CastOpc; 4080 unsigned Opc; 4081 switch (Op.getOpcode()) { 4082 default: llvm_unreachable("Invalid opcode!"); 4083 case ISD::SINT_TO_FP: 4084 CastOpc = ISD::SIGN_EXTEND; 4085 Opc = ISD::SINT_TO_FP; 4086 break; 4087 case ISD::UINT_TO_FP: 4088 CastOpc = ISD::ZERO_EXTEND; 4089 Opc = ISD::UINT_TO_FP; 4090 break; 4091 } 4092 4093 Op = DAG.getNode(CastOpc, dl, MVT::v4i32, Op.getOperand(0)); 4094 return DAG.getNode(Opc, dl, VT, Op); 4095 } 4096 4097 SDValue ARMTargetLowering::LowerINT_TO_FP(SDValue Op, SelectionDAG &DAG) const { 4098 EVT VT = Op.getValueType(); 4099 if (VT.isVector()) 4100 return LowerVectorINT_TO_FP(Op, DAG); 4101 if (Subtarget->isFPOnlySP() && Op.getValueType() == MVT::f64) { 4102 RTLIB::Libcall LC; 4103 if (Op.getOpcode() == ISD::SINT_TO_FP) 4104 LC = RTLIB::getSINTTOFP(Op.getOperand(0).getValueType(), 4105 Op.getValueType()); 4106 else 4107 LC = RTLIB::getUINTTOFP(Op.getOperand(0).getValueType(), 4108 Op.getValueType()); 4109 return makeLibCall(DAG, LC, Op.getValueType(), Op.getOperand(0), 4110 /*isSigned*/ false, SDLoc(Op)).first; 4111 } 4112 4113 return Op; 4114 } 4115 4116 SDValue ARMTargetLowering::LowerFCOPYSIGN(SDValue Op, SelectionDAG &DAG) const { 4117 // Implement fcopysign with a fabs and a conditional fneg. 4118 SDValue Tmp0 = Op.getOperand(0); 4119 SDValue Tmp1 = Op.getOperand(1); 4120 SDLoc dl(Op); 4121 EVT VT = Op.getValueType(); 4122 EVT SrcVT = Tmp1.getValueType(); 4123 bool InGPR = Tmp0.getOpcode() == ISD::BITCAST || 4124 Tmp0.getOpcode() == ARMISD::VMOVDRR; 4125 bool UseNEON = !InGPR && Subtarget->hasNEON(); 4126 4127 if (UseNEON) { 4128 // Use VBSL to copy the sign bit. 4129 unsigned EncodedVal = ARM_AM::createNEONModImm(0x6, 0x80); 4130 SDValue Mask = DAG.getNode(ARMISD::VMOVIMM, dl, MVT::v2i32, 4131 DAG.getTargetConstant(EncodedVal, dl, MVT::i32)); 4132 EVT OpVT = (VT == MVT::f32) ? MVT::v2i32 : MVT::v1i64; 4133 if (VT == MVT::f64) 4134 Mask = DAG.getNode(ARMISD::VSHL, dl, OpVT, 4135 DAG.getNode(ISD::BITCAST, dl, OpVT, Mask), 4136 DAG.getConstant(32, dl, MVT::i32)); 4137 else /*if (VT == MVT::f32)*/ 4138 Tmp0 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f32, Tmp0); 4139 if (SrcVT == MVT::f32) { 4140 Tmp1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f32, Tmp1); 4141 if (VT == MVT::f64) 4142 Tmp1 = DAG.getNode(ARMISD::VSHL, dl, OpVT, 4143 DAG.getNode(ISD::BITCAST, dl, OpVT, Tmp1), 4144 DAG.getConstant(32, dl, MVT::i32)); 4145 } else if (VT == MVT::f32) 4146 Tmp1 = DAG.getNode(ARMISD::VSHRu, dl, MVT::v1i64, 4147 DAG.getNode(ISD::BITCAST, dl, MVT::v1i64, Tmp1), 4148 DAG.getConstant(32, dl, MVT::i32)); 4149 Tmp0 = DAG.getNode(ISD::BITCAST, dl, OpVT, Tmp0); 4150 Tmp1 = DAG.getNode(ISD::BITCAST, dl, OpVT, Tmp1); 4151 4152 SDValue AllOnes = DAG.getTargetConstant(ARM_AM::createNEONModImm(0xe, 0xff), 4153 dl, MVT::i32); 4154 AllOnes = DAG.getNode(ARMISD::VMOVIMM, dl, MVT::v8i8, AllOnes); 4155 SDValue MaskNot = DAG.getNode(ISD::XOR, dl, OpVT, Mask, 4156 DAG.getNode(ISD::BITCAST, dl, OpVT, AllOnes)); 4157 4158 SDValue Res = DAG.getNode(ISD::OR, dl, OpVT, 4159 DAG.getNode(ISD::AND, dl, OpVT, Tmp1, Mask), 4160 DAG.getNode(ISD::AND, dl, OpVT, Tmp0, MaskNot)); 4161 if (VT == MVT::f32) { 4162 Res = DAG.getNode(ISD::BITCAST, dl, MVT::v2f32, Res); 4163 Res = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f32, Res, 4164 DAG.getConstant(0, dl, MVT::i32)); 4165 } else { 4166 Res = DAG.getNode(ISD::BITCAST, dl, MVT::f64, Res); 4167 } 4168 4169 return Res; 4170 } 4171 4172 // Bitcast operand 1 to i32. 4173 if (SrcVT == MVT::f64) 4174 Tmp1 = DAG.getNode(ARMISD::VMOVRRD, dl, DAG.getVTList(MVT::i32, MVT::i32), 4175 Tmp1).getValue(1); 4176 Tmp1 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Tmp1); 4177 4178 // Or in the signbit with integer operations. 4179 SDValue Mask1 = DAG.getConstant(0x80000000, dl, MVT::i32); 4180 SDValue Mask2 = DAG.getConstant(0x7fffffff, dl, MVT::i32); 4181 Tmp1 = DAG.getNode(ISD::AND, dl, MVT::i32, Tmp1, Mask1); 4182 if (VT == MVT::f32) { 4183 Tmp0 = DAG.getNode(ISD::AND, dl, MVT::i32, 4184 DAG.getNode(ISD::BITCAST, dl, MVT::i32, Tmp0), Mask2); 4185 return DAG.getNode(ISD::BITCAST, dl, MVT::f32, 4186 DAG.getNode(ISD::OR, dl, MVT::i32, Tmp0, Tmp1)); 4187 } 4188 4189 // f64: Or the high part with signbit and then combine two parts. 4190 Tmp0 = DAG.getNode(ARMISD::VMOVRRD, dl, DAG.getVTList(MVT::i32, MVT::i32), 4191 Tmp0); 4192 SDValue Lo = Tmp0.getValue(0); 4193 SDValue Hi = DAG.getNode(ISD::AND, dl, MVT::i32, Tmp0.getValue(1), Mask2); 4194 Hi = DAG.getNode(ISD::OR, dl, MVT::i32, Hi, Tmp1); 4195 return DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi); 4196 } 4197 4198 SDValue ARMTargetLowering::LowerRETURNADDR(SDValue Op, SelectionDAG &DAG) const{ 4199 MachineFunction &MF = DAG.getMachineFunction(); 4200 MachineFrameInfo *MFI = MF.getFrameInfo(); 4201 MFI->setReturnAddressIsTaken(true); 4202 4203 if (verifyReturnAddressArgumentIsConstant(Op, DAG)) 4204 return SDValue(); 4205 4206 EVT VT = Op.getValueType(); 4207 SDLoc dl(Op); 4208 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue(); 4209 if (Depth) { 4210 SDValue FrameAddr = LowerFRAMEADDR(Op, DAG); 4211 SDValue Offset = DAG.getConstant(4, dl, MVT::i32); 4212 return DAG.getLoad(VT, dl, DAG.getEntryNode(), 4213 DAG.getNode(ISD::ADD, dl, VT, FrameAddr, Offset), 4214 MachinePointerInfo(), false, false, false, 0); 4215 } 4216 4217 // Return LR, which contains the return address. Mark it an implicit live-in. 4218 unsigned Reg = MF.addLiveIn(ARM::LR, getRegClassFor(MVT::i32)); 4219 return DAG.getCopyFromReg(DAG.getEntryNode(), dl, Reg, VT); 4220 } 4221 4222 SDValue ARMTargetLowering::LowerFRAMEADDR(SDValue Op, SelectionDAG &DAG) const { 4223 const ARMBaseRegisterInfo &ARI = 4224 *static_cast<const ARMBaseRegisterInfo*>(RegInfo); 4225 MachineFunction &MF = DAG.getMachineFunction(); 4226 MachineFrameInfo *MFI = MF.getFrameInfo(); 4227 MFI->setFrameAddressIsTaken(true); 4228 4229 EVT VT = Op.getValueType(); 4230 SDLoc dl(Op); // FIXME probably not meaningful 4231 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue(); 4232 unsigned FrameReg = ARI.getFrameRegister(MF); 4233 SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, VT); 4234 while (Depth--) 4235 FrameAddr = DAG.getLoad(VT, dl, DAG.getEntryNode(), FrameAddr, 4236 MachinePointerInfo(), 4237 false, false, false, 0); 4238 return FrameAddr; 4239 } 4240 4241 // FIXME? Maybe this could be a TableGen attribute on some registers and 4242 // this table could be generated automatically from RegInfo. 4243 unsigned ARMTargetLowering::getRegisterByName(const char* RegName, EVT VT, 4244 SelectionDAG &DAG) const { 4245 unsigned Reg = StringSwitch<unsigned>(RegName) 4246 .Case("sp", ARM::SP) 4247 .Default(0); 4248 if (Reg) 4249 return Reg; 4250 report_fatal_error(Twine("Invalid register name \"" 4251 + StringRef(RegName) + "\".")); 4252 } 4253 4254 // Result is 64 bit value so split into two 32 bit values and return as a 4255 // pair of values. 4256 static void ExpandREAD_REGISTER(SDNode *N, SmallVectorImpl<SDValue> &Results, 4257 SelectionDAG &DAG) { 4258 SDLoc DL(N); 4259 4260 // This function is only supposed to be called for i64 type destination. 4261 assert(N->getValueType(0) == MVT::i64 4262 && "ExpandREAD_REGISTER called for non-i64 type result."); 4263 4264 SDValue Read = DAG.getNode(ISD::READ_REGISTER, DL, 4265 DAG.getVTList(MVT::i32, MVT::i32, MVT::Other), 4266 N->getOperand(0), 4267 N->getOperand(1)); 4268 4269 Results.push_back(DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, Read.getValue(0), 4270 Read.getValue(1))); 4271 Results.push_back(Read.getOperand(0)); 4272 } 4273 4274 /// \p BC is a bitcast that is about to be turned into a VMOVDRR. 4275 /// When \p DstVT, the destination type of \p BC, is on the vector 4276 /// register bank and the source of bitcast, \p Op, operates on the same bank, 4277 /// it might be possible to combine them, such that everything stays on the 4278 /// vector register bank. 4279 /// \p return The node that would replace \p BT, if the combine 4280 /// is possible. 4281 static SDValue CombineVMOVDRRCandidateWithVecOp(const SDNode *BC, 4282 SelectionDAG &DAG) { 4283 SDValue Op = BC->getOperand(0); 4284 EVT DstVT = BC->getValueType(0); 4285 4286 // The only vector instruction that can produce a scalar (remember, 4287 // since the bitcast was about to be turned into VMOVDRR, the source 4288 // type is i64) from a vector is EXTRACT_VECTOR_ELT. 4289 // Moreover, we can do this combine only if there is one use. 4290 // Finally, if the destination type is not a vector, there is not 4291 // much point on forcing everything on the vector bank. 4292 if (!DstVT.isVector() || Op.getOpcode() != ISD::EXTRACT_VECTOR_ELT || 4293 !Op.hasOneUse()) 4294 return SDValue(); 4295 4296 // If the index is not constant, we will introduce an additional 4297 // multiply that will stick. 4298 // Give up in that case. 4299 ConstantSDNode *Index = dyn_cast<ConstantSDNode>(Op.getOperand(1)); 4300 if (!Index) 4301 return SDValue(); 4302 unsigned DstNumElt = DstVT.getVectorNumElements(); 4303 4304 // Compute the new index. 4305 const APInt &APIntIndex = Index->getAPIntValue(); 4306 APInt NewIndex(APIntIndex.getBitWidth(), DstNumElt); 4307 NewIndex *= APIntIndex; 4308 // Check if the new constant index fits into i32. 4309 if (NewIndex.getBitWidth() > 32) 4310 return SDValue(); 4311 4312 // vMTy bitcast(i64 extractelt vNi64 src, i32 index) -> 4313 // vMTy extractsubvector vNxMTy (bitcast vNi64 src), i32 index*M) 4314 SDLoc dl(Op); 4315 SDValue ExtractSrc = Op.getOperand(0); 4316 EVT VecVT = EVT::getVectorVT( 4317 *DAG.getContext(), DstVT.getScalarType(), 4318 ExtractSrc.getValueType().getVectorNumElements() * DstNumElt); 4319 SDValue BitCast = DAG.getNode(ISD::BITCAST, dl, VecVT, ExtractSrc); 4320 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DstVT, BitCast, 4321 DAG.getConstant(NewIndex.getZExtValue(), dl, MVT::i32)); 4322 } 4323 4324 /// ExpandBITCAST - If the target supports VFP, this function is called to 4325 /// expand a bit convert where either the source or destination type is i64 to 4326 /// use a VMOVDRR or VMOVRRD node. This should not be done when the non-i64 4327 /// operand type is illegal (e.g., v2f32 for a target that doesn't support 4328 /// vectors), since the legalizer won't know what to do with that. 4329 static SDValue ExpandBITCAST(SDNode *N, SelectionDAG &DAG) { 4330 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 4331 SDLoc dl(N); 4332 SDValue Op = N->getOperand(0); 4333 4334 // This function is only supposed to be called for i64 types, either as the 4335 // source or destination of the bit convert. 4336 EVT SrcVT = Op.getValueType(); 4337 EVT DstVT = N->getValueType(0); 4338 assert((SrcVT == MVT::i64 || DstVT == MVT::i64) && 4339 "ExpandBITCAST called for non-i64 type"); 4340 4341 // Turn i64->f64 into VMOVDRR. 4342 if (SrcVT == MVT::i64 && TLI.isTypeLegal(DstVT)) { 4343 // Do not force values to GPRs (this is what VMOVDRR does for the inputs) 4344 // if we can combine the bitcast with its source. 4345 if (SDValue Val = CombineVMOVDRRCandidateWithVecOp(N, DAG)) 4346 return Val; 4347 4348 SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, Op, 4349 DAG.getConstant(0, dl, MVT::i32)); 4350 SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, Op, 4351 DAG.getConstant(1, dl, MVT::i32)); 4352 return DAG.getNode(ISD::BITCAST, dl, DstVT, 4353 DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi)); 4354 } 4355 4356 // Turn f64->i64 into VMOVRRD. 4357 if (DstVT == MVT::i64 && TLI.isTypeLegal(SrcVT)) { 4358 SDValue Cvt; 4359 if (DAG.getDataLayout().isBigEndian() && SrcVT.isVector() && 4360 SrcVT.getVectorNumElements() > 1) 4361 Cvt = DAG.getNode(ARMISD::VMOVRRD, dl, 4362 DAG.getVTList(MVT::i32, MVT::i32), 4363 DAG.getNode(ARMISD::VREV64, dl, SrcVT, Op)); 4364 else 4365 Cvt = DAG.getNode(ARMISD::VMOVRRD, dl, 4366 DAG.getVTList(MVT::i32, MVT::i32), Op); 4367 // Merge the pieces into a single i64 value. 4368 return DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Cvt, Cvt.getValue(1)); 4369 } 4370 4371 return SDValue(); 4372 } 4373 4374 /// getZeroVector - Returns a vector of specified type with all zero elements. 4375 /// Zero vectors are used to represent vector negation and in those cases 4376 /// will be implemented with the NEON VNEG instruction. However, VNEG does 4377 /// not support i64 elements, so sometimes the zero vectors will need to be 4378 /// explicitly constructed. Regardless, use a canonical VMOV to create the 4379 /// zero vector. 4380 static SDValue getZeroVector(EVT VT, SelectionDAG &DAG, SDLoc dl) { 4381 assert(VT.isVector() && "Expected a vector type"); 4382 // The canonical modified immediate encoding of a zero vector is....0! 4383 SDValue EncodedVal = DAG.getTargetConstant(0, dl, MVT::i32); 4384 EVT VmovVT = VT.is128BitVector() ? MVT::v4i32 : MVT::v2i32; 4385 SDValue Vmov = DAG.getNode(ARMISD::VMOVIMM, dl, VmovVT, EncodedVal); 4386 return DAG.getNode(ISD::BITCAST, dl, VT, Vmov); 4387 } 4388 4389 /// LowerShiftRightParts - Lower SRA_PARTS, which returns two 4390 /// i32 values and take a 2 x i32 value to shift plus a shift amount. 4391 SDValue ARMTargetLowering::LowerShiftRightParts(SDValue Op, 4392 SelectionDAG &DAG) const { 4393 assert(Op.getNumOperands() == 3 && "Not a double-shift!"); 4394 EVT VT = Op.getValueType(); 4395 unsigned VTBits = VT.getSizeInBits(); 4396 SDLoc dl(Op); 4397 SDValue ShOpLo = Op.getOperand(0); 4398 SDValue ShOpHi = Op.getOperand(1); 4399 SDValue ShAmt = Op.getOperand(2); 4400 SDValue ARMcc; 4401 unsigned Opc = (Op.getOpcode() == ISD::SRA_PARTS) ? ISD::SRA : ISD::SRL; 4402 4403 assert(Op.getOpcode() == ISD::SRA_PARTS || Op.getOpcode() == ISD::SRL_PARTS); 4404 4405 SDValue RevShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32, 4406 DAG.getConstant(VTBits, dl, MVT::i32), ShAmt); 4407 SDValue Tmp1 = DAG.getNode(ISD::SRL, dl, VT, ShOpLo, ShAmt); 4408 SDValue ExtraShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32, ShAmt, 4409 DAG.getConstant(VTBits, dl, MVT::i32)); 4410 SDValue Tmp2 = DAG.getNode(ISD::SHL, dl, VT, ShOpHi, RevShAmt); 4411 SDValue FalseVal = DAG.getNode(ISD::OR, dl, VT, Tmp1, Tmp2); 4412 SDValue TrueVal = DAG.getNode(Opc, dl, VT, ShOpHi, ExtraShAmt); 4413 4414 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32); 4415 SDValue Cmp = getARMCmp(ExtraShAmt, DAG.getConstant(0, dl, MVT::i32), 4416 ISD::SETGE, ARMcc, DAG, dl); 4417 SDValue Hi = DAG.getNode(Opc, dl, VT, ShOpHi, ShAmt); 4418 SDValue Lo = DAG.getNode(ARMISD::CMOV, dl, VT, FalseVal, TrueVal, ARMcc, 4419 CCR, Cmp); 4420 4421 SDValue Ops[2] = { Lo, Hi }; 4422 return DAG.getMergeValues(Ops, dl); 4423 } 4424 4425 /// LowerShiftLeftParts - Lower SHL_PARTS, which returns two 4426 /// i32 values and take a 2 x i32 value to shift plus a shift amount. 4427 SDValue ARMTargetLowering::LowerShiftLeftParts(SDValue Op, 4428 SelectionDAG &DAG) const { 4429 assert(Op.getNumOperands() == 3 && "Not a double-shift!"); 4430 EVT VT = Op.getValueType(); 4431 unsigned VTBits = VT.getSizeInBits(); 4432 SDLoc dl(Op); 4433 SDValue ShOpLo = Op.getOperand(0); 4434 SDValue ShOpHi = Op.getOperand(1); 4435 SDValue ShAmt = Op.getOperand(2); 4436 SDValue ARMcc; 4437 4438 assert(Op.getOpcode() == ISD::SHL_PARTS); 4439 SDValue RevShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32, 4440 DAG.getConstant(VTBits, dl, MVT::i32), ShAmt); 4441 SDValue Tmp1 = DAG.getNode(ISD::SRL, dl, VT, ShOpLo, RevShAmt); 4442 SDValue ExtraShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32, ShAmt, 4443 DAG.getConstant(VTBits, dl, MVT::i32)); 4444 SDValue Tmp2 = DAG.getNode(ISD::SHL, dl, VT, ShOpHi, ShAmt); 4445 SDValue Tmp3 = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ExtraShAmt); 4446 4447 SDValue FalseVal = DAG.getNode(ISD::OR, dl, VT, Tmp1, Tmp2); 4448 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32); 4449 SDValue Cmp = getARMCmp(ExtraShAmt, DAG.getConstant(0, dl, MVT::i32), 4450 ISD::SETGE, ARMcc, DAG, dl); 4451 SDValue Lo = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ShAmt); 4452 SDValue Hi = DAG.getNode(ARMISD::CMOV, dl, VT, FalseVal, Tmp3, ARMcc, 4453 CCR, Cmp); 4454 4455 SDValue Ops[2] = { Lo, Hi }; 4456 return DAG.getMergeValues(Ops, dl); 4457 } 4458 4459 SDValue ARMTargetLowering::LowerFLT_ROUNDS_(SDValue Op, 4460 SelectionDAG &DAG) const { 4461 // The rounding mode is in bits 23:22 of the FPSCR. 4462 // The ARM rounding mode value to FLT_ROUNDS mapping is 0->1, 1->2, 2->3, 3->0 4463 // The formula we use to implement this is (((FPSCR + 1 << 22) >> 22) & 3) 4464 // so that the shift + and get folded into a bitfield extract. 4465 SDLoc dl(Op); 4466 SDValue FPSCR = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::i32, 4467 DAG.getConstant(Intrinsic::arm_get_fpscr, dl, 4468 MVT::i32)); 4469 SDValue FltRounds = DAG.getNode(ISD::ADD, dl, MVT::i32, FPSCR, 4470 DAG.getConstant(1U << 22, dl, MVT::i32)); 4471 SDValue RMODE = DAG.getNode(ISD::SRL, dl, MVT::i32, FltRounds, 4472 DAG.getConstant(22, dl, MVT::i32)); 4473 return DAG.getNode(ISD::AND, dl, MVT::i32, RMODE, 4474 DAG.getConstant(3, dl, MVT::i32)); 4475 } 4476 4477 static SDValue LowerCTTZ(SDNode *N, SelectionDAG &DAG, 4478 const ARMSubtarget *ST) { 4479 SDLoc dl(N); 4480 EVT VT = N->getValueType(0); 4481 if (VT.isVector()) { 4482 assert(ST->hasNEON()); 4483 4484 // Compute the least significant set bit: LSB = X & -X 4485 SDValue X = N->getOperand(0); 4486 SDValue NX = DAG.getNode(ISD::SUB, dl, VT, getZeroVector(VT, DAG, dl), X); 4487 SDValue LSB = DAG.getNode(ISD::AND, dl, VT, X, NX); 4488 4489 EVT ElemTy = VT.getVectorElementType(); 4490 4491 if (ElemTy == MVT::i8) { 4492 // Compute with: cttz(x) = ctpop(lsb - 1) 4493 SDValue One = DAG.getNode(ARMISD::VMOVIMM, dl, VT, 4494 DAG.getTargetConstant(1, dl, ElemTy)); 4495 SDValue Bits = DAG.getNode(ISD::SUB, dl, VT, LSB, One); 4496 return DAG.getNode(ISD::CTPOP, dl, VT, Bits); 4497 } 4498 4499 if ((ElemTy == MVT::i16 || ElemTy == MVT::i32) && 4500 (N->getOpcode() == ISD::CTTZ_ZERO_UNDEF)) { 4501 // Compute with: cttz(x) = (width - 1) - ctlz(lsb), if x != 0 4502 unsigned NumBits = ElemTy.getSizeInBits(); 4503 SDValue WidthMinus1 = 4504 DAG.getNode(ARMISD::VMOVIMM, dl, VT, 4505 DAG.getTargetConstant(NumBits - 1, dl, ElemTy)); 4506 SDValue CTLZ = DAG.getNode(ISD::CTLZ, dl, VT, LSB); 4507 return DAG.getNode(ISD::SUB, dl, VT, WidthMinus1, CTLZ); 4508 } 4509 4510 // Compute with: cttz(x) = ctpop(lsb - 1) 4511 4512 // Since we can only compute the number of bits in a byte with vcnt.8, we 4513 // have to gather the result with pairwise addition (vpaddl) for i16, i32, 4514 // and i64. 4515 4516 // Compute LSB - 1. 4517 SDValue Bits; 4518 if (ElemTy == MVT::i64) { 4519 // Load constant 0xffff'ffff'ffff'ffff to register. 4520 SDValue FF = DAG.getNode(ARMISD::VMOVIMM, dl, VT, 4521 DAG.getTargetConstant(0x1eff, dl, MVT::i32)); 4522 Bits = DAG.getNode(ISD::ADD, dl, VT, LSB, FF); 4523 } else { 4524 SDValue One = DAG.getNode(ARMISD::VMOVIMM, dl, VT, 4525 DAG.getTargetConstant(1, dl, ElemTy)); 4526 Bits = DAG.getNode(ISD::SUB, dl, VT, LSB, One); 4527 } 4528 4529 // Count #bits with vcnt.8. 4530 EVT VT8Bit = VT.is64BitVector() ? MVT::v8i8 : MVT::v16i8; 4531 SDValue BitsVT8 = DAG.getNode(ISD::BITCAST, dl, VT8Bit, Bits); 4532 SDValue Cnt8 = DAG.getNode(ISD::CTPOP, dl, VT8Bit, BitsVT8); 4533 4534 // Gather the #bits with vpaddl (pairwise add.) 4535 EVT VT16Bit = VT.is64BitVector() ? MVT::v4i16 : MVT::v8i16; 4536 SDValue Cnt16 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT16Bit, 4537 DAG.getTargetConstant(Intrinsic::arm_neon_vpaddlu, dl, MVT::i32), 4538 Cnt8); 4539 if (ElemTy == MVT::i16) 4540 return Cnt16; 4541 4542 EVT VT32Bit = VT.is64BitVector() ? MVT::v2i32 : MVT::v4i32; 4543 SDValue Cnt32 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT32Bit, 4544 DAG.getTargetConstant(Intrinsic::arm_neon_vpaddlu, dl, MVT::i32), 4545 Cnt16); 4546 if (ElemTy == MVT::i32) 4547 return Cnt32; 4548 4549 assert(ElemTy == MVT::i64); 4550 SDValue Cnt64 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT, 4551 DAG.getTargetConstant(Intrinsic::arm_neon_vpaddlu, dl, MVT::i32), 4552 Cnt32); 4553 return Cnt64; 4554 } 4555 4556 if (!ST->hasV6T2Ops()) 4557 return SDValue(); 4558 4559 SDValue rbit = DAG.getNode(ISD::BITREVERSE, dl, VT, N->getOperand(0)); 4560 return DAG.getNode(ISD::CTLZ, dl, VT, rbit); 4561 } 4562 4563 /// getCTPOP16BitCounts - Returns a v8i8/v16i8 vector containing the bit-count 4564 /// for each 16-bit element from operand, repeated. The basic idea is to 4565 /// leverage vcnt to get the 8-bit counts, gather and add the results. 4566 /// 4567 /// Trace for v4i16: 4568 /// input = [v0 v1 v2 v3 ] (vi 16-bit element) 4569 /// cast: N0 = [w0 w1 w2 w3 w4 w5 w6 w7] (v0 = [w0 w1], wi 8-bit element) 4570 /// vcnt: N1 = [b0 b1 b2 b3 b4 b5 b6 b7] (bi = bit-count of 8-bit element wi) 4571 /// vrev: N2 = [b1 b0 b3 b2 b5 b4 b7 b6] 4572 /// [b0 b1 b2 b3 b4 b5 b6 b7] 4573 /// +[b1 b0 b3 b2 b5 b4 b7 b6] 4574 /// N3=N1+N2 = [k0 k0 k1 k1 k2 k2 k3 k3] (k0 = b0+b1 = bit-count of 16-bit v0, 4575 /// vuzp: = [k0 k1 k2 k3 k0 k1 k2 k3] each ki is 8-bits) 4576 static SDValue getCTPOP16BitCounts(SDNode *N, SelectionDAG &DAG) { 4577 EVT VT = N->getValueType(0); 4578 SDLoc DL(N); 4579 4580 EVT VT8Bit = VT.is64BitVector() ? MVT::v8i8 : MVT::v16i8; 4581 SDValue N0 = DAG.getNode(ISD::BITCAST, DL, VT8Bit, N->getOperand(0)); 4582 SDValue N1 = DAG.getNode(ISD::CTPOP, DL, VT8Bit, N0); 4583 SDValue N2 = DAG.getNode(ARMISD::VREV16, DL, VT8Bit, N1); 4584 SDValue N3 = DAG.getNode(ISD::ADD, DL, VT8Bit, N1, N2); 4585 return DAG.getNode(ARMISD::VUZP, DL, VT8Bit, N3, N3); 4586 } 4587 4588 /// lowerCTPOP16BitElements - Returns a v4i16/v8i16 vector containing the 4589 /// bit-count for each 16-bit element from the operand. We need slightly 4590 /// different sequencing for v4i16 and v8i16 to stay within NEON's available 4591 /// 64/128-bit registers. 4592 /// 4593 /// Trace for v4i16: 4594 /// input = [v0 v1 v2 v3 ] (vi 16-bit element) 4595 /// v8i8: BitCounts = [k0 k1 k2 k3 k0 k1 k2 k3 ] (ki is the bit-count of vi) 4596 /// v8i16:Extended = [k0 k1 k2 k3 k0 k1 k2 k3 ] 4597 /// v4i16:Extracted = [k0 k1 k2 k3 ] 4598 static SDValue lowerCTPOP16BitElements(SDNode *N, SelectionDAG &DAG) { 4599 EVT VT = N->getValueType(0); 4600 SDLoc DL(N); 4601 4602 SDValue BitCounts = getCTPOP16BitCounts(N, DAG); 4603 if (VT.is64BitVector()) { 4604 SDValue Extended = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::v8i16, BitCounts); 4605 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v4i16, Extended, 4606 DAG.getIntPtrConstant(0, DL)); 4607 } else { 4608 SDValue Extracted = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v8i8, 4609 BitCounts, DAG.getIntPtrConstant(0, DL)); 4610 return DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::v8i16, Extracted); 4611 } 4612 } 4613 4614 /// lowerCTPOP32BitElements - Returns a v2i32/v4i32 vector containing the 4615 /// bit-count for each 32-bit element from the operand. The idea here is 4616 /// to split the vector into 16-bit elements, leverage the 16-bit count 4617 /// routine, and then combine the results. 4618 /// 4619 /// Trace for v2i32 (v4i32 similar with Extracted/Extended exchanged): 4620 /// input = [v0 v1 ] (vi: 32-bit elements) 4621 /// Bitcast = [w0 w1 w2 w3 ] (wi: 16-bit elements, v0 = [w0 w1]) 4622 /// Counts16 = [k0 k1 k2 k3 ] (ki: 16-bit elements, bit-count of wi) 4623 /// vrev: N0 = [k1 k0 k3 k2 ] 4624 /// [k0 k1 k2 k3 ] 4625 /// N1 =+[k1 k0 k3 k2 ] 4626 /// [k0 k2 k1 k3 ] 4627 /// N2 =+[k1 k3 k0 k2 ] 4628 /// [k0 k2 k1 k3 ] 4629 /// Extended =+[k1 k3 k0 k2 ] 4630 /// [k0 k2 ] 4631 /// Extracted=+[k1 k3 ] 4632 /// 4633 static SDValue lowerCTPOP32BitElements(SDNode *N, SelectionDAG &DAG) { 4634 EVT VT = N->getValueType(0); 4635 SDLoc DL(N); 4636 4637 EVT VT16Bit = VT.is64BitVector() ? MVT::v4i16 : MVT::v8i16; 4638 4639 SDValue Bitcast = DAG.getNode(ISD::BITCAST, DL, VT16Bit, N->getOperand(0)); 4640 SDValue Counts16 = lowerCTPOP16BitElements(Bitcast.getNode(), DAG); 4641 SDValue N0 = DAG.getNode(ARMISD::VREV32, DL, VT16Bit, Counts16); 4642 SDValue N1 = DAG.getNode(ISD::ADD, DL, VT16Bit, Counts16, N0); 4643 SDValue N2 = DAG.getNode(ARMISD::VUZP, DL, VT16Bit, N1, N1); 4644 4645 if (VT.is64BitVector()) { 4646 SDValue Extended = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::v4i32, N2); 4647 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2i32, Extended, 4648 DAG.getIntPtrConstant(0, DL)); 4649 } else { 4650 SDValue Extracted = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v4i16, N2, 4651 DAG.getIntPtrConstant(0, DL)); 4652 return DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::v4i32, Extracted); 4653 } 4654 } 4655 4656 static SDValue LowerCTPOP(SDNode *N, SelectionDAG &DAG, 4657 const ARMSubtarget *ST) { 4658 EVT VT = N->getValueType(0); 4659 4660 assert(ST->hasNEON() && "Custom ctpop lowering requires NEON."); 4661 assert((VT == MVT::v2i32 || VT == MVT::v4i32 || 4662 VT == MVT::v4i16 || VT == MVT::v8i16) && 4663 "Unexpected type for custom ctpop lowering"); 4664 4665 if (VT.getVectorElementType() == MVT::i32) 4666 return lowerCTPOP32BitElements(N, DAG); 4667 else 4668 return lowerCTPOP16BitElements(N, DAG); 4669 } 4670 4671 static SDValue LowerShift(SDNode *N, SelectionDAG &DAG, 4672 const ARMSubtarget *ST) { 4673 EVT VT = N->getValueType(0); 4674 SDLoc dl(N); 4675 4676 if (!VT.isVector()) 4677 return SDValue(); 4678 4679 // Lower vector shifts on NEON to use VSHL. 4680 assert(ST->hasNEON() && "unexpected vector shift"); 4681 4682 // Left shifts translate directly to the vshiftu intrinsic. 4683 if (N->getOpcode() == ISD::SHL) 4684 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT, 4685 DAG.getConstant(Intrinsic::arm_neon_vshiftu, dl, 4686 MVT::i32), 4687 N->getOperand(0), N->getOperand(1)); 4688 4689 assert((N->getOpcode() == ISD::SRA || 4690 N->getOpcode() == ISD::SRL) && "unexpected vector shift opcode"); 4691 4692 // NEON uses the same intrinsics for both left and right shifts. For 4693 // right shifts, the shift amounts are negative, so negate the vector of 4694 // shift amounts. 4695 EVT ShiftVT = N->getOperand(1).getValueType(); 4696 SDValue NegatedCount = DAG.getNode(ISD::SUB, dl, ShiftVT, 4697 getZeroVector(ShiftVT, DAG, dl), 4698 N->getOperand(1)); 4699 Intrinsic::ID vshiftInt = (N->getOpcode() == ISD::SRA ? 4700 Intrinsic::arm_neon_vshifts : 4701 Intrinsic::arm_neon_vshiftu); 4702 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT, 4703 DAG.getConstant(vshiftInt, dl, MVT::i32), 4704 N->getOperand(0), NegatedCount); 4705 } 4706 4707 static SDValue Expand64BitShift(SDNode *N, SelectionDAG &DAG, 4708 const ARMSubtarget *ST) { 4709 EVT VT = N->getValueType(0); 4710 SDLoc dl(N); 4711 4712 // We can get here for a node like i32 = ISD::SHL i32, i64 4713 if (VT != MVT::i64) 4714 return SDValue(); 4715 4716 assert((N->getOpcode() == ISD::SRL || N->getOpcode() == ISD::SRA) && 4717 "Unknown shift to lower!"); 4718 4719 // We only lower SRA, SRL of 1 here, all others use generic lowering. 4720 if (!isOneConstant(N->getOperand(1))) 4721 return SDValue(); 4722 4723 // If we are in thumb mode, we don't have RRX. 4724 if (ST->isThumb1Only()) return SDValue(); 4725 4726 // Okay, we have a 64-bit SRA or SRL of 1. Lower this to an RRX expr. 4727 SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(0), 4728 DAG.getConstant(0, dl, MVT::i32)); 4729 SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(0), 4730 DAG.getConstant(1, dl, MVT::i32)); 4731 4732 // First, build a SRA_FLAG/SRL_FLAG op, which shifts the top part by one and 4733 // captures the result into a carry flag. 4734 unsigned Opc = N->getOpcode() == ISD::SRL ? ARMISD::SRL_FLAG:ARMISD::SRA_FLAG; 4735 Hi = DAG.getNode(Opc, dl, DAG.getVTList(MVT::i32, MVT::Glue), Hi); 4736 4737 // The low part is an ARMISD::RRX operand, which shifts the carry in. 4738 Lo = DAG.getNode(ARMISD::RRX, dl, MVT::i32, Lo, Hi.getValue(1)); 4739 4740 // Merge the pieces into a single i64 value. 4741 return DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Lo, Hi); 4742 } 4743 4744 static SDValue LowerVSETCC(SDValue Op, SelectionDAG &DAG) { 4745 SDValue TmpOp0, TmpOp1; 4746 bool Invert = false; 4747 bool Swap = false; 4748 unsigned Opc = 0; 4749 4750 SDValue Op0 = Op.getOperand(0); 4751 SDValue Op1 = Op.getOperand(1); 4752 SDValue CC = Op.getOperand(2); 4753 EVT CmpVT = Op0.getValueType().changeVectorElementTypeToInteger(); 4754 EVT VT = Op.getValueType(); 4755 ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get(); 4756 SDLoc dl(Op); 4757 4758 if (CmpVT.getVectorElementType() == MVT::i64) 4759 // 64-bit comparisons are not legal. We've marked SETCC as non-Custom, 4760 // but it's possible that our operands are 64-bit but our result is 32-bit. 4761 // Bail in this case. 4762 return SDValue(); 4763 4764 if (Op1.getValueType().isFloatingPoint()) { 4765 switch (SetCCOpcode) { 4766 default: llvm_unreachable("Illegal FP comparison"); 4767 case ISD::SETUNE: 4768 case ISD::SETNE: Invert = true; // Fallthrough 4769 case ISD::SETOEQ: 4770 case ISD::SETEQ: Opc = ARMISD::VCEQ; break; 4771 case ISD::SETOLT: 4772 case ISD::SETLT: Swap = true; // Fallthrough 4773 case ISD::SETOGT: 4774 case ISD::SETGT: Opc = ARMISD::VCGT; break; 4775 case ISD::SETOLE: 4776 case ISD::SETLE: Swap = true; // Fallthrough 4777 case ISD::SETOGE: 4778 case ISD::SETGE: Opc = ARMISD::VCGE; break; 4779 case ISD::SETUGE: Swap = true; // Fallthrough 4780 case ISD::SETULE: Invert = true; Opc = ARMISD::VCGT; break; 4781 case ISD::SETUGT: Swap = true; // Fallthrough 4782 case ISD::SETULT: Invert = true; Opc = ARMISD::VCGE; break; 4783 case ISD::SETUEQ: Invert = true; // Fallthrough 4784 case ISD::SETONE: 4785 // Expand this to (OLT | OGT). 4786 TmpOp0 = Op0; 4787 TmpOp1 = Op1; 4788 Opc = ISD::OR; 4789 Op0 = DAG.getNode(ARMISD::VCGT, dl, CmpVT, TmpOp1, TmpOp0); 4790 Op1 = DAG.getNode(ARMISD::VCGT, dl, CmpVT, TmpOp0, TmpOp1); 4791 break; 4792 case ISD::SETUO: Invert = true; // Fallthrough 4793 case ISD::SETO: 4794 // Expand this to (OLT | OGE). 4795 TmpOp0 = Op0; 4796 TmpOp1 = Op1; 4797 Opc = ISD::OR; 4798 Op0 = DAG.getNode(ARMISD::VCGT, dl, CmpVT, TmpOp1, TmpOp0); 4799 Op1 = DAG.getNode(ARMISD::VCGE, dl, CmpVT, TmpOp0, TmpOp1); 4800 break; 4801 } 4802 } else { 4803 // Integer comparisons. 4804 switch (SetCCOpcode) { 4805 default: llvm_unreachable("Illegal integer comparison"); 4806 case ISD::SETNE: Invert = true; 4807 case ISD::SETEQ: Opc = ARMISD::VCEQ; break; 4808 case ISD::SETLT: Swap = true; 4809 case ISD::SETGT: Opc = ARMISD::VCGT; break; 4810 case ISD::SETLE: Swap = true; 4811 case ISD::SETGE: Opc = ARMISD::VCGE; break; 4812 case ISD::SETULT: Swap = true; 4813 case ISD::SETUGT: Opc = ARMISD::VCGTU; break; 4814 case ISD::SETULE: Swap = true; 4815 case ISD::SETUGE: Opc = ARMISD::VCGEU; break; 4816 } 4817 4818 // Detect VTST (Vector Test Bits) = icmp ne (and (op0, op1), zero). 4819 if (Opc == ARMISD::VCEQ) { 4820 4821 SDValue AndOp; 4822 if (ISD::isBuildVectorAllZeros(Op1.getNode())) 4823 AndOp = Op0; 4824 else if (ISD::isBuildVectorAllZeros(Op0.getNode())) 4825 AndOp = Op1; 4826 4827 // Ignore bitconvert. 4828 if (AndOp.getNode() && AndOp.getOpcode() == ISD::BITCAST) 4829 AndOp = AndOp.getOperand(0); 4830 4831 if (AndOp.getNode() && AndOp.getOpcode() == ISD::AND) { 4832 Opc = ARMISD::VTST; 4833 Op0 = DAG.getNode(ISD::BITCAST, dl, CmpVT, AndOp.getOperand(0)); 4834 Op1 = DAG.getNode(ISD::BITCAST, dl, CmpVT, AndOp.getOperand(1)); 4835 Invert = !Invert; 4836 } 4837 } 4838 } 4839 4840 if (Swap) 4841 std::swap(Op0, Op1); 4842 4843 // If one of the operands is a constant vector zero, attempt to fold the 4844 // comparison to a specialized compare-against-zero form. 4845 SDValue SingleOp; 4846 if (ISD::isBuildVectorAllZeros(Op1.getNode())) 4847 SingleOp = Op0; 4848 else if (ISD::isBuildVectorAllZeros(Op0.getNode())) { 4849 if (Opc == ARMISD::VCGE) 4850 Opc = ARMISD::VCLEZ; 4851 else if (Opc == ARMISD::VCGT) 4852 Opc = ARMISD::VCLTZ; 4853 SingleOp = Op1; 4854 } 4855 4856 SDValue Result; 4857 if (SingleOp.getNode()) { 4858 switch (Opc) { 4859 case ARMISD::VCEQ: 4860 Result = DAG.getNode(ARMISD::VCEQZ, dl, CmpVT, SingleOp); break; 4861 case ARMISD::VCGE: 4862 Result = DAG.getNode(ARMISD::VCGEZ, dl, CmpVT, SingleOp); break; 4863 case ARMISD::VCLEZ: 4864 Result = DAG.getNode(ARMISD::VCLEZ, dl, CmpVT, SingleOp); break; 4865 case ARMISD::VCGT: 4866 Result = DAG.getNode(ARMISD::VCGTZ, dl, CmpVT, SingleOp); break; 4867 case ARMISD::VCLTZ: 4868 Result = DAG.getNode(ARMISD::VCLTZ, dl, CmpVT, SingleOp); break; 4869 default: 4870 Result = DAG.getNode(Opc, dl, CmpVT, Op0, Op1); 4871 } 4872 } else { 4873 Result = DAG.getNode(Opc, dl, CmpVT, Op0, Op1); 4874 } 4875 4876 Result = DAG.getSExtOrTrunc(Result, dl, VT); 4877 4878 if (Invert) 4879 Result = DAG.getNOT(dl, Result, VT); 4880 4881 return Result; 4882 } 4883 4884 static SDValue LowerSETCCE(SDValue Op, SelectionDAG &DAG) { 4885 SDValue LHS = Op.getOperand(0); 4886 SDValue RHS = Op.getOperand(1); 4887 SDValue Carry = Op.getOperand(2); 4888 SDValue Cond = Op.getOperand(3); 4889 SDLoc DL(Op); 4890 4891 assert(LHS.getSimpleValueType().isInteger() && "SETCCE is integer only."); 4892 4893 assert(Carry.getOpcode() != ISD::CARRY_FALSE); 4894 SDVTList VTs = DAG.getVTList(LHS.getValueType(), MVT::i32); 4895 SDValue Cmp = DAG.getNode(ARMISD::SUBE, DL, VTs, LHS, RHS, Carry); 4896 4897 SDValue FVal = DAG.getConstant(0, DL, MVT::i32); 4898 SDValue TVal = DAG.getConstant(1, DL, MVT::i32); 4899 SDValue ARMcc = DAG.getConstant( 4900 IntCCToARMCC(cast<CondCodeSDNode>(Cond)->get()), DL, MVT::i32); 4901 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32); 4902 SDValue Chain = DAG.getCopyToReg(DAG.getEntryNode(), DL, ARM::CPSR, 4903 Cmp.getValue(1), SDValue()); 4904 return DAG.getNode(ARMISD::CMOV, DL, Op.getValueType(), FVal, TVal, ARMcc, 4905 CCR, Chain.getValue(1)); 4906 } 4907 4908 /// isNEONModifiedImm - Check if the specified splat value corresponds to a 4909 /// valid vector constant for a NEON instruction with a "modified immediate" 4910 /// operand (e.g., VMOV). If so, return the encoded value. 4911 static SDValue isNEONModifiedImm(uint64_t SplatBits, uint64_t SplatUndef, 4912 unsigned SplatBitSize, SelectionDAG &DAG, 4913 SDLoc dl, EVT &VT, bool is128Bits, 4914 NEONModImmType type) { 4915 unsigned OpCmode, Imm; 4916 4917 // SplatBitSize is set to the smallest size that splats the vector, so a 4918 // zero vector will always have SplatBitSize == 8. However, NEON modified 4919 // immediate instructions others than VMOV do not support the 8-bit encoding 4920 // of a zero vector, and the default encoding of zero is supposed to be the 4921 // 32-bit version. 4922 if (SplatBits == 0) 4923 SplatBitSize = 32; 4924 4925 switch (SplatBitSize) { 4926 case 8: 4927 if (type != VMOVModImm) 4928 return SDValue(); 4929 // Any 1-byte value is OK. Op=0, Cmode=1110. 4930 assert((SplatBits & ~0xff) == 0 && "one byte splat value is too big"); 4931 OpCmode = 0xe; 4932 Imm = SplatBits; 4933 VT = is128Bits ? MVT::v16i8 : MVT::v8i8; 4934 break; 4935 4936 case 16: 4937 // NEON's 16-bit VMOV supports splat values where only one byte is nonzero. 4938 VT = is128Bits ? MVT::v8i16 : MVT::v4i16; 4939 if ((SplatBits & ~0xff) == 0) { 4940 // Value = 0x00nn: Op=x, Cmode=100x. 4941 OpCmode = 0x8; 4942 Imm = SplatBits; 4943 break; 4944 } 4945 if ((SplatBits & ~0xff00) == 0) { 4946 // Value = 0xnn00: Op=x, Cmode=101x. 4947 OpCmode = 0xa; 4948 Imm = SplatBits >> 8; 4949 break; 4950 } 4951 return SDValue(); 4952 4953 case 32: 4954 // NEON's 32-bit VMOV supports splat values where: 4955 // * only one byte is nonzero, or 4956 // * the least significant byte is 0xff and the second byte is nonzero, or 4957 // * the least significant 2 bytes are 0xff and the third is nonzero. 4958 VT = is128Bits ? MVT::v4i32 : MVT::v2i32; 4959 if ((SplatBits & ~0xff) == 0) { 4960 // Value = 0x000000nn: Op=x, Cmode=000x. 4961 OpCmode = 0; 4962 Imm = SplatBits; 4963 break; 4964 } 4965 if ((SplatBits & ~0xff00) == 0) { 4966 // Value = 0x0000nn00: Op=x, Cmode=001x. 4967 OpCmode = 0x2; 4968 Imm = SplatBits >> 8; 4969 break; 4970 } 4971 if ((SplatBits & ~0xff0000) == 0) { 4972 // Value = 0x00nn0000: Op=x, Cmode=010x. 4973 OpCmode = 0x4; 4974 Imm = SplatBits >> 16; 4975 break; 4976 } 4977 if ((SplatBits & ~0xff000000) == 0) { 4978 // Value = 0xnn000000: Op=x, Cmode=011x. 4979 OpCmode = 0x6; 4980 Imm = SplatBits >> 24; 4981 break; 4982 } 4983 4984 // cmode == 0b1100 and cmode == 0b1101 are not supported for VORR or VBIC 4985 if (type == OtherModImm) return SDValue(); 4986 4987 if ((SplatBits & ~0xffff) == 0 && 4988 ((SplatBits | SplatUndef) & 0xff) == 0xff) { 4989 // Value = 0x0000nnff: Op=x, Cmode=1100. 4990 OpCmode = 0xc; 4991 Imm = SplatBits >> 8; 4992 break; 4993 } 4994 4995 if ((SplatBits & ~0xffffff) == 0 && 4996 ((SplatBits | SplatUndef) & 0xffff) == 0xffff) { 4997 // Value = 0x00nnffff: Op=x, Cmode=1101. 4998 OpCmode = 0xd; 4999 Imm = SplatBits >> 16; 5000 break; 5001 } 5002 5003 // Note: there are a few 32-bit splat values (specifically: 00ffff00, 5004 // ff000000, ff0000ff, and ffff00ff) that are valid for VMOV.I64 but not 5005 // VMOV.I32. A (very) minor optimization would be to replicate the value 5006 // and fall through here to test for a valid 64-bit splat. But, then the 5007 // caller would also need to check and handle the change in size. 5008 return SDValue(); 5009 5010 case 64: { 5011 if (type != VMOVModImm) 5012 return SDValue(); 5013 // NEON has a 64-bit VMOV splat where each byte is either 0 or 0xff. 5014 uint64_t BitMask = 0xff; 5015 uint64_t Val = 0; 5016 unsigned ImmMask = 1; 5017 Imm = 0; 5018 for (int ByteNum = 0; ByteNum < 8; ++ByteNum) { 5019 if (((SplatBits | SplatUndef) & BitMask) == BitMask) { 5020 Val |= BitMask; 5021 Imm |= ImmMask; 5022 } else if ((SplatBits & BitMask) != 0) { 5023 return SDValue(); 5024 } 5025 BitMask <<= 8; 5026 ImmMask <<= 1; 5027 } 5028 5029 if (DAG.getDataLayout().isBigEndian()) 5030 // swap higher and lower 32 bit word 5031 Imm = ((Imm & 0xf) << 4) | ((Imm & 0xf0) >> 4); 5032 5033 // Op=1, Cmode=1110. 5034 OpCmode = 0x1e; 5035 VT = is128Bits ? MVT::v2i64 : MVT::v1i64; 5036 break; 5037 } 5038 5039 default: 5040 llvm_unreachable("unexpected size for isNEONModifiedImm"); 5041 } 5042 5043 unsigned EncodedVal = ARM_AM::createNEONModImm(OpCmode, Imm); 5044 return DAG.getTargetConstant(EncodedVal, dl, MVT::i32); 5045 } 5046 5047 SDValue ARMTargetLowering::LowerConstantFP(SDValue Op, SelectionDAG &DAG, 5048 const ARMSubtarget *ST) const { 5049 if (!ST->hasVFP3()) 5050 return SDValue(); 5051 5052 bool IsDouble = Op.getValueType() == MVT::f64; 5053 ConstantFPSDNode *CFP = cast<ConstantFPSDNode>(Op); 5054 5055 // Use the default (constant pool) lowering for double constants when we have 5056 // an SP-only FPU 5057 if (IsDouble && Subtarget->isFPOnlySP()) 5058 return SDValue(); 5059 5060 // Try splatting with a VMOV.f32... 5061 APFloat FPVal = CFP->getValueAPF(); 5062 int ImmVal = IsDouble ? ARM_AM::getFP64Imm(FPVal) : ARM_AM::getFP32Imm(FPVal); 5063 5064 if (ImmVal != -1) { 5065 if (IsDouble || !ST->useNEONForSinglePrecisionFP()) { 5066 // We have code in place to select a valid ConstantFP already, no need to 5067 // do any mangling. 5068 return Op; 5069 } 5070 5071 // It's a float and we are trying to use NEON operations where 5072 // possible. Lower it to a splat followed by an extract. 5073 SDLoc DL(Op); 5074 SDValue NewVal = DAG.getTargetConstant(ImmVal, DL, MVT::i32); 5075 SDValue VecConstant = DAG.getNode(ARMISD::VMOVFPIMM, DL, MVT::v2f32, 5076 NewVal); 5077 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32, VecConstant, 5078 DAG.getConstant(0, DL, MVT::i32)); 5079 } 5080 5081 // The rest of our options are NEON only, make sure that's allowed before 5082 // proceeding.. 5083 if (!ST->hasNEON() || (!IsDouble && !ST->useNEONForSinglePrecisionFP())) 5084 return SDValue(); 5085 5086 EVT VMovVT; 5087 uint64_t iVal = FPVal.bitcastToAPInt().getZExtValue(); 5088 5089 // It wouldn't really be worth bothering for doubles except for one very 5090 // important value, which does happen to match: 0.0. So make sure we don't do 5091 // anything stupid. 5092 if (IsDouble && (iVal & 0xffffffff) != (iVal >> 32)) 5093 return SDValue(); 5094 5095 // Try a VMOV.i32 (FIXME: i8, i16, or i64 could work too). 5096 SDValue NewVal = isNEONModifiedImm(iVal & 0xffffffffU, 0, 32, DAG, SDLoc(Op), 5097 VMovVT, false, VMOVModImm); 5098 if (NewVal != SDValue()) { 5099 SDLoc DL(Op); 5100 SDValue VecConstant = DAG.getNode(ARMISD::VMOVIMM, DL, VMovVT, 5101 NewVal); 5102 if (IsDouble) 5103 return DAG.getNode(ISD::BITCAST, DL, MVT::f64, VecConstant); 5104 5105 // It's a float: cast and extract a vector element. 5106 SDValue VecFConstant = DAG.getNode(ISD::BITCAST, DL, MVT::v2f32, 5107 VecConstant); 5108 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32, VecFConstant, 5109 DAG.getConstant(0, DL, MVT::i32)); 5110 } 5111 5112 // Finally, try a VMVN.i32 5113 NewVal = isNEONModifiedImm(~iVal & 0xffffffffU, 0, 32, DAG, SDLoc(Op), VMovVT, 5114 false, VMVNModImm); 5115 if (NewVal != SDValue()) { 5116 SDLoc DL(Op); 5117 SDValue VecConstant = DAG.getNode(ARMISD::VMVNIMM, DL, VMovVT, NewVal); 5118 5119 if (IsDouble) 5120 return DAG.getNode(ISD::BITCAST, DL, MVT::f64, VecConstant); 5121 5122 // It's a float: cast and extract a vector element. 5123 SDValue VecFConstant = DAG.getNode(ISD::BITCAST, DL, MVT::v2f32, 5124 VecConstant); 5125 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32, VecFConstant, 5126 DAG.getConstant(0, DL, MVT::i32)); 5127 } 5128 5129 return SDValue(); 5130 } 5131 5132 // check if an VEXT instruction can handle the shuffle mask when the 5133 // vector sources of the shuffle are the same. 5134 static bool isSingletonVEXTMask(ArrayRef<int> M, EVT VT, unsigned &Imm) { 5135 unsigned NumElts = VT.getVectorNumElements(); 5136 5137 // Assume that the first shuffle index is not UNDEF. Fail if it is. 5138 if (M[0] < 0) 5139 return false; 5140 5141 Imm = M[0]; 5142 5143 // If this is a VEXT shuffle, the immediate value is the index of the first 5144 // element. The other shuffle indices must be the successive elements after 5145 // the first one. 5146 unsigned ExpectedElt = Imm; 5147 for (unsigned i = 1; i < NumElts; ++i) { 5148 // Increment the expected index. If it wraps around, just follow it 5149 // back to index zero and keep going. 5150 ++ExpectedElt; 5151 if (ExpectedElt == NumElts) 5152 ExpectedElt = 0; 5153 5154 if (M[i] < 0) continue; // ignore UNDEF indices 5155 if (ExpectedElt != static_cast<unsigned>(M[i])) 5156 return false; 5157 } 5158 5159 return true; 5160 } 5161 5162 5163 static bool isVEXTMask(ArrayRef<int> M, EVT VT, 5164 bool &ReverseVEXT, unsigned &Imm) { 5165 unsigned NumElts = VT.getVectorNumElements(); 5166 ReverseVEXT = false; 5167 5168 // Assume that the first shuffle index is not UNDEF. Fail if it is. 5169 if (M[0] < 0) 5170 return false; 5171 5172 Imm = M[0]; 5173 5174 // If this is a VEXT shuffle, the immediate value is the index of the first 5175 // element. The other shuffle indices must be the successive elements after 5176 // the first one. 5177 unsigned ExpectedElt = Imm; 5178 for (unsigned i = 1; i < NumElts; ++i) { 5179 // Increment the expected index. If it wraps around, it may still be 5180 // a VEXT but the source vectors must be swapped. 5181 ExpectedElt += 1; 5182 if (ExpectedElt == NumElts * 2) { 5183 ExpectedElt = 0; 5184 ReverseVEXT = true; 5185 } 5186 5187 if (M[i] < 0) continue; // ignore UNDEF indices 5188 if (ExpectedElt != static_cast<unsigned>(M[i])) 5189 return false; 5190 } 5191 5192 // Adjust the index value if the source operands will be swapped. 5193 if (ReverseVEXT) 5194 Imm -= NumElts; 5195 5196 return true; 5197 } 5198 5199 /// isVREVMask - Check if a vector shuffle corresponds to a VREV 5200 /// instruction with the specified blocksize. (The order of the elements 5201 /// within each block of the vector is reversed.) 5202 static bool isVREVMask(ArrayRef<int> M, EVT VT, unsigned BlockSize) { 5203 assert((BlockSize==16 || BlockSize==32 || BlockSize==64) && 5204 "Only possible block sizes for VREV are: 16, 32, 64"); 5205 5206 unsigned EltSz = VT.getVectorElementType().getSizeInBits(); 5207 if (EltSz == 64) 5208 return false; 5209 5210 unsigned NumElts = VT.getVectorNumElements(); 5211 unsigned BlockElts = M[0] + 1; 5212 // If the first shuffle index is UNDEF, be optimistic. 5213 if (M[0] < 0) 5214 BlockElts = BlockSize / EltSz; 5215 5216 if (BlockSize <= EltSz || BlockSize != BlockElts * EltSz) 5217 return false; 5218 5219 for (unsigned i = 0; i < NumElts; ++i) { 5220 if (M[i] < 0) continue; // ignore UNDEF indices 5221 if ((unsigned) M[i] != (i - i%BlockElts) + (BlockElts - 1 - i%BlockElts)) 5222 return false; 5223 } 5224 5225 return true; 5226 } 5227 5228 static bool isVTBLMask(ArrayRef<int> M, EVT VT) { 5229 // We can handle <8 x i8> vector shuffles. If the index in the mask is out of 5230 // range, then 0 is placed into the resulting vector. So pretty much any mask 5231 // of 8 elements can work here. 5232 return VT == MVT::v8i8 && M.size() == 8; 5233 } 5234 5235 // Checks whether the shuffle mask represents a vector transpose (VTRN) by 5236 // checking that pairs of elements in the shuffle mask represent the same index 5237 // in each vector, incrementing the expected index by 2 at each step. 5238 // e.g. For v1,v2 of type v4i32 a valid shuffle mask is: [0, 4, 2, 6] 5239 // v1={a,b,c,d} => x=shufflevector v1, v2 shufflemask => x={a,e,c,g} 5240 // v2={e,f,g,h} 5241 // WhichResult gives the offset for each element in the mask based on which 5242 // of the two results it belongs to. 5243 // 5244 // The transpose can be represented either as: 5245 // result1 = shufflevector v1, v2, result1_shuffle_mask 5246 // result2 = shufflevector v1, v2, result2_shuffle_mask 5247 // where v1/v2 and the shuffle masks have the same number of elements 5248 // (here WhichResult (see below) indicates which result is being checked) 5249 // 5250 // or as: 5251 // results = shufflevector v1, v2, shuffle_mask 5252 // where both results are returned in one vector and the shuffle mask has twice 5253 // as many elements as v1/v2 (here WhichResult will always be 0 if true) here we 5254 // want to check the low half and high half of the shuffle mask as if it were 5255 // the other case 5256 static bool isVTRNMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) { 5257 unsigned EltSz = VT.getVectorElementType().getSizeInBits(); 5258 if (EltSz == 64) 5259 return false; 5260 5261 unsigned NumElts = VT.getVectorNumElements(); 5262 if (M.size() != NumElts && M.size() != NumElts*2) 5263 return false; 5264 5265 // If the mask is twice as long as the input vector then we need to check the 5266 // upper and lower parts of the mask with a matching value for WhichResult 5267 // FIXME: A mask with only even values will be rejected in case the first 5268 // element is undefined, e.g. [-1, 4, 2, 6] will be rejected, because only 5269 // M[0] is used to determine WhichResult 5270 for (unsigned i = 0; i < M.size(); i += NumElts) { 5271 if (M.size() == NumElts * 2) 5272 WhichResult = i / NumElts; 5273 else 5274 WhichResult = M[i] == 0 ? 0 : 1; 5275 for (unsigned j = 0; j < NumElts; j += 2) { 5276 if ((M[i+j] >= 0 && (unsigned) M[i+j] != j + WhichResult) || 5277 (M[i+j+1] >= 0 && (unsigned) M[i+j+1] != j + NumElts + WhichResult)) 5278 return false; 5279 } 5280 } 5281 5282 if (M.size() == NumElts*2) 5283 WhichResult = 0; 5284 5285 return true; 5286 } 5287 5288 /// isVTRN_v_undef_Mask - Special case of isVTRNMask for canonical form of 5289 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef". 5290 /// Mask is e.g., <0, 0, 2, 2> instead of <0, 4, 2, 6>. 5291 static bool isVTRN_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult){ 5292 unsigned EltSz = VT.getVectorElementType().getSizeInBits(); 5293 if (EltSz == 64) 5294 return false; 5295 5296 unsigned NumElts = VT.getVectorNumElements(); 5297 if (M.size() != NumElts && M.size() != NumElts*2) 5298 return false; 5299 5300 for (unsigned i = 0; i < M.size(); i += NumElts) { 5301 if (M.size() == NumElts * 2) 5302 WhichResult = i / NumElts; 5303 else 5304 WhichResult = M[i] == 0 ? 0 : 1; 5305 for (unsigned j = 0; j < NumElts; j += 2) { 5306 if ((M[i+j] >= 0 && (unsigned) M[i+j] != j + WhichResult) || 5307 (M[i+j+1] >= 0 && (unsigned) M[i+j+1] != j + WhichResult)) 5308 return false; 5309 } 5310 } 5311 5312 if (M.size() == NumElts*2) 5313 WhichResult = 0; 5314 5315 return true; 5316 } 5317 5318 // Checks whether the shuffle mask represents a vector unzip (VUZP) by checking 5319 // that the mask elements are either all even and in steps of size 2 or all odd 5320 // and in steps of size 2. 5321 // e.g. For v1,v2 of type v4i32 a valid shuffle mask is: [0, 2, 4, 6] 5322 // v1={a,b,c,d} => x=shufflevector v1, v2 shufflemask => x={a,c,e,g} 5323 // v2={e,f,g,h} 5324 // Requires similar checks to that of isVTRNMask with 5325 // respect the how results are returned. 5326 static bool isVUZPMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) { 5327 unsigned EltSz = VT.getVectorElementType().getSizeInBits(); 5328 if (EltSz == 64) 5329 return false; 5330 5331 unsigned NumElts = VT.getVectorNumElements(); 5332 if (M.size() != NumElts && M.size() != NumElts*2) 5333 return false; 5334 5335 for (unsigned i = 0; i < M.size(); i += NumElts) { 5336 WhichResult = M[i] == 0 ? 0 : 1; 5337 for (unsigned j = 0; j < NumElts; ++j) { 5338 if (M[i+j] >= 0 && (unsigned) M[i+j] != 2 * j + WhichResult) 5339 return false; 5340 } 5341 } 5342 5343 if (M.size() == NumElts*2) 5344 WhichResult = 0; 5345 5346 // VUZP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32. 5347 if (VT.is64BitVector() && EltSz == 32) 5348 return false; 5349 5350 return true; 5351 } 5352 5353 /// isVUZP_v_undef_Mask - Special case of isVUZPMask for canonical form of 5354 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef". 5355 /// Mask is e.g., <0, 2, 0, 2> instead of <0, 2, 4, 6>, 5356 static bool isVUZP_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult){ 5357 unsigned EltSz = VT.getVectorElementType().getSizeInBits(); 5358 if (EltSz == 64) 5359 return false; 5360 5361 unsigned NumElts = VT.getVectorNumElements(); 5362 if (M.size() != NumElts && M.size() != NumElts*2) 5363 return false; 5364 5365 unsigned Half = NumElts / 2; 5366 for (unsigned i = 0; i < M.size(); i += NumElts) { 5367 WhichResult = M[i] == 0 ? 0 : 1; 5368 for (unsigned j = 0; j < NumElts; j += Half) { 5369 unsigned Idx = WhichResult; 5370 for (unsigned k = 0; k < Half; ++k) { 5371 int MIdx = M[i + j + k]; 5372 if (MIdx >= 0 && (unsigned) MIdx != Idx) 5373 return false; 5374 Idx += 2; 5375 } 5376 } 5377 } 5378 5379 if (M.size() == NumElts*2) 5380 WhichResult = 0; 5381 5382 // VUZP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32. 5383 if (VT.is64BitVector() && EltSz == 32) 5384 return false; 5385 5386 return true; 5387 } 5388 5389 // Checks whether the shuffle mask represents a vector zip (VZIP) by checking 5390 // that pairs of elements of the shufflemask represent the same index in each 5391 // vector incrementing sequentially through the vectors. 5392 // e.g. For v1,v2 of type v4i32 a valid shuffle mask is: [0, 4, 1, 5] 5393 // v1={a,b,c,d} => x=shufflevector v1, v2 shufflemask => x={a,e,b,f} 5394 // v2={e,f,g,h} 5395 // Requires similar checks to that of isVTRNMask with respect the how results 5396 // are returned. 5397 static bool isVZIPMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) { 5398 unsigned EltSz = VT.getVectorElementType().getSizeInBits(); 5399 if (EltSz == 64) 5400 return false; 5401 5402 unsigned NumElts = VT.getVectorNumElements(); 5403 if (M.size() != NumElts && M.size() != NumElts*2) 5404 return false; 5405 5406 for (unsigned i = 0; i < M.size(); i += NumElts) { 5407 WhichResult = M[i] == 0 ? 0 : 1; 5408 unsigned Idx = WhichResult * NumElts / 2; 5409 for (unsigned j = 0; j < NumElts; j += 2) { 5410 if ((M[i+j] >= 0 && (unsigned) M[i+j] != Idx) || 5411 (M[i+j+1] >= 0 && (unsigned) M[i+j+1] != Idx + NumElts)) 5412 return false; 5413 Idx += 1; 5414 } 5415 } 5416 5417 if (M.size() == NumElts*2) 5418 WhichResult = 0; 5419 5420 // VZIP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32. 5421 if (VT.is64BitVector() && EltSz == 32) 5422 return false; 5423 5424 return true; 5425 } 5426 5427 /// isVZIP_v_undef_Mask - Special case of isVZIPMask for canonical form of 5428 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef". 5429 /// Mask is e.g., <0, 0, 1, 1> instead of <0, 4, 1, 5>. 5430 static bool isVZIP_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult){ 5431 unsigned EltSz = VT.getVectorElementType().getSizeInBits(); 5432 if (EltSz == 64) 5433 return false; 5434 5435 unsigned NumElts = VT.getVectorNumElements(); 5436 if (M.size() != NumElts && M.size() != NumElts*2) 5437 return false; 5438 5439 for (unsigned i = 0; i < M.size(); i += NumElts) { 5440 WhichResult = M[i] == 0 ? 0 : 1; 5441 unsigned Idx = WhichResult * NumElts / 2; 5442 for (unsigned j = 0; j < NumElts; j += 2) { 5443 if ((M[i+j] >= 0 && (unsigned) M[i+j] != Idx) || 5444 (M[i+j+1] >= 0 && (unsigned) M[i+j+1] != Idx)) 5445 return false; 5446 Idx += 1; 5447 } 5448 } 5449 5450 if (M.size() == NumElts*2) 5451 WhichResult = 0; 5452 5453 // VZIP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32. 5454 if (VT.is64BitVector() && EltSz == 32) 5455 return false; 5456 5457 return true; 5458 } 5459 5460 /// Check if \p ShuffleMask is a NEON two-result shuffle (VZIP, VUZP, VTRN), 5461 /// and return the corresponding ARMISD opcode if it is, or 0 if it isn't. 5462 static unsigned isNEONTwoResultShuffleMask(ArrayRef<int> ShuffleMask, EVT VT, 5463 unsigned &WhichResult, 5464 bool &isV_UNDEF) { 5465 isV_UNDEF = false; 5466 if (isVTRNMask(ShuffleMask, VT, WhichResult)) 5467 return ARMISD::VTRN; 5468 if (isVUZPMask(ShuffleMask, VT, WhichResult)) 5469 return ARMISD::VUZP; 5470 if (isVZIPMask(ShuffleMask, VT, WhichResult)) 5471 return ARMISD::VZIP; 5472 5473 isV_UNDEF = true; 5474 if (isVTRN_v_undef_Mask(ShuffleMask, VT, WhichResult)) 5475 return ARMISD::VTRN; 5476 if (isVUZP_v_undef_Mask(ShuffleMask, VT, WhichResult)) 5477 return ARMISD::VUZP; 5478 if (isVZIP_v_undef_Mask(ShuffleMask, VT, WhichResult)) 5479 return ARMISD::VZIP; 5480 5481 return 0; 5482 } 5483 5484 /// \return true if this is a reverse operation on an vector. 5485 static bool isReverseMask(ArrayRef<int> M, EVT VT) { 5486 unsigned NumElts = VT.getVectorNumElements(); 5487 // Make sure the mask has the right size. 5488 if (NumElts != M.size()) 5489 return false; 5490 5491 // Look for <15, ..., 3, -1, 1, 0>. 5492 for (unsigned i = 0; i != NumElts; ++i) 5493 if (M[i] >= 0 && M[i] != (int) (NumElts - 1 - i)) 5494 return false; 5495 5496 return true; 5497 } 5498 5499 // If N is an integer constant that can be moved into a register in one 5500 // instruction, return an SDValue of such a constant (will become a MOV 5501 // instruction). Otherwise return null. 5502 static SDValue IsSingleInstrConstant(SDValue N, SelectionDAG &DAG, 5503 const ARMSubtarget *ST, SDLoc dl) { 5504 uint64_t Val; 5505 if (!isa<ConstantSDNode>(N)) 5506 return SDValue(); 5507 Val = cast<ConstantSDNode>(N)->getZExtValue(); 5508 5509 if (ST->isThumb1Only()) { 5510 if (Val <= 255 || ~Val <= 255) 5511 return DAG.getConstant(Val, dl, MVT::i32); 5512 } else { 5513 if (ARM_AM::getSOImmVal(Val) != -1 || ARM_AM::getSOImmVal(~Val) != -1) 5514 return DAG.getConstant(Val, dl, MVT::i32); 5515 } 5516 return SDValue(); 5517 } 5518 5519 // If this is a case we can't handle, return null and let the default 5520 // expansion code take care of it. 5521 SDValue ARMTargetLowering::LowerBUILD_VECTOR(SDValue Op, SelectionDAG &DAG, 5522 const ARMSubtarget *ST) const { 5523 BuildVectorSDNode *BVN = cast<BuildVectorSDNode>(Op.getNode()); 5524 SDLoc dl(Op); 5525 EVT VT = Op.getValueType(); 5526 5527 APInt SplatBits, SplatUndef; 5528 unsigned SplatBitSize; 5529 bool HasAnyUndefs; 5530 if (BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs)) { 5531 if (SplatBitSize <= 64) { 5532 // Check if an immediate VMOV works. 5533 EVT VmovVT; 5534 SDValue Val = isNEONModifiedImm(SplatBits.getZExtValue(), 5535 SplatUndef.getZExtValue(), SplatBitSize, 5536 DAG, dl, VmovVT, VT.is128BitVector(), 5537 VMOVModImm); 5538 if (Val.getNode()) { 5539 SDValue Vmov = DAG.getNode(ARMISD::VMOVIMM, dl, VmovVT, Val); 5540 return DAG.getNode(ISD::BITCAST, dl, VT, Vmov); 5541 } 5542 5543 // Try an immediate VMVN. 5544 uint64_t NegatedImm = (~SplatBits).getZExtValue(); 5545 Val = isNEONModifiedImm(NegatedImm, 5546 SplatUndef.getZExtValue(), SplatBitSize, 5547 DAG, dl, VmovVT, VT.is128BitVector(), 5548 VMVNModImm); 5549 if (Val.getNode()) { 5550 SDValue Vmov = DAG.getNode(ARMISD::VMVNIMM, dl, VmovVT, Val); 5551 return DAG.getNode(ISD::BITCAST, dl, VT, Vmov); 5552 } 5553 5554 // Use vmov.f32 to materialize other v2f32 and v4f32 splats. 5555 if ((VT == MVT::v2f32 || VT == MVT::v4f32) && SplatBitSize == 32) { 5556 int ImmVal = ARM_AM::getFP32Imm(SplatBits); 5557 if (ImmVal != -1) { 5558 SDValue Val = DAG.getTargetConstant(ImmVal, dl, MVT::i32); 5559 return DAG.getNode(ARMISD::VMOVFPIMM, dl, VT, Val); 5560 } 5561 } 5562 } 5563 } 5564 5565 // Scan through the operands to see if only one value is used. 5566 // 5567 // As an optimisation, even if more than one value is used it may be more 5568 // profitable to splat with one value then change some lanes. 5569 // 5570 // Heuristically we decide to do this if the vector has a "dominant" value, 5571 // defined as splatted to more than half of the lanes. 5572 unsigned NumElts = VT.getVectorNumElements(); 5573 bool isOnlyLowElement = true; 5574 bool usesOnlyOneValue = true; 5575 bool hasDominantValue = false; 5576 bool isConstant = true; 5577 5578 // Map of the number of times a particular SDValue appears in the 5579 // element list. 5580 DenseMap<SDValue, unsigned> ValueCounts; 5581 SDValue Value; 5582 for (unsigned i = 0; i < NumElts; ++i) { 5583 SDValue V = Op.getOperand(i); 5584 if (V.isUndef()) 5585 continue; 5586 if (i > 0) 5587 isOnlyLowElement = false; 5588 if (!isa<ConstantFPSDNode>(V) && !isa<ConstantSDNode>(V)) 5589 isConstant = false; 5590 5591 ValueCounts.insert(std::make_pair(V, 0)); 5592 unsigned &Count = ValueCounts[V]; 5593 5594 // Is this value dominant? (takes up more than half of the lanes) 5595 if (++Count > (NumElts / 2)) { 5596 hasDominantValue = true; 5597 Value = V; 5598 } 5599 } 5600 if (ValueCounts.size() != 1) 5601 usesOnlyOneValue = false; 5602 if (!Value.getNode() && ValueCounts.size() > 0) 5603 Value = ValueCounts.begin()->first; 5604 5605 if (ValueCounts.size() == 0) 5606 return DAG.getUNDEF(VT); 5607 5608 // Loads are better lowered with insert_vector_elt/ARMISD::BUILD_VECTOR. 5609 // Keep going if we are hitting this case. 5610 if (isOnlyLowElement && !ISD::isNormalLoad(Value.getNode())) 5611 return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Value); 5612 5613 unsigned EltSize = VT.getVectorElementType().getSizeInBits(); 5614 5615 // Use VDUP for non-constant splats. For f32 constant splats, reduce to 5616 // i32 and try again. 5617 if (hasDominantValue && EltSize <= 32) { 5618 if (!isConstant) { 5619 SDValue N; 5620 5621 // If we are VDUPing a value that comes directly from a vector, that will 5622 // cause an unnecessary move to and from a GPR, where instead we could 5623 // just use VDUPLANE. We can only do this if the lane being extracted 5624 // is at a constant index, as the VDUP from lane instructions only have 5625 // constant-index forms. 5626 ConstantSDNode *constIndex; 5627 if (Value->getOpcode() == ISD::EXTRACT_VECTOR_ELT && 5628 (constIndex = dyn_cast<ConstantSDNode>(Value->getOperand(1)))) { 5629 // We need to create a new undef vector to use for the VDUPLANE if the 5630 // size of the vector from which we get the value is different than the 5631 // size of the vector that we need to create. We will insert the element 5632 // such that the register coalescer will remove unnecessary copies. 5633 if (VT != Value->getOperand(0).getValueType()) { 5634 unsigned index = constIndex->getAPIntValue().getLimitedValue() % 5635 VT.getVectorNumElements(); 5636 N = DAG.getNode(ARMISD::VDUPLANE, dl, VT, 5637 DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, DAG.getUNDEF(VT), 5638 Value, DAG.getConstant(index, dl, MVT::i32)), 5639 DAG.getConstant(index, dl, MVT::i32)); 5640 } else 5641 N = DAG.getNode(ARMISD::VDUPLANE, dl, VT, 5642 Value->getOperand(0), Value->getOperand(1)); 5643 } else 5644 N = DAG.getNode(ARMISD::VDUP, dl, VT, Value); 5645 5646 if (!usesOnlyOneValue) { 5647 // The dominant value was splatted as 'N', but we now have to insert 5648 // all differing elements. 5649 for (unsigned I = 0; I < NumElts; ++I) { 5650 if (Op.getOperand(I) == Value) 5651 continue; 5652 SmallVector<SDValue, 3> Ops; 5653 Ops.push_back(N); 5654 Ops.push_back(Op.getOperand(I)); 5655 Ops.push_back(DAG.getConstant(I, dl, MVT::i32)); 5656 N = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Ops); 5657 } 5658 } 5659 return N; 5660 } 5661 if (VT.getVectorElementType().isFloatingPoint()) { 5662 SmallVector<SDValue, 8> Ops; 5663 for (unsigned i = 0; i < NumElts; ++i) 5664 Ops.push_back(DAG.getNode(ISD::BITCAST, dl, MVT::i32, 5665 Op.getOperand(i))); 5666 EVT VecVT = EVT::getVectorVT(*DAG.getContext(), MVT::i32, NumElts); 5667 SDValue Val = DAG.getNode(ISD::BUILD_VECTOR, dl, VecVT, Ops); 5668 Val = LowerBUILD_VECTOR(Val, DAG, ST); 5669 if (Val.getNode()) 5670 return DAG.getNode(ISD::BITCAST, dl, VT, Val); 5671 } 5672 if (usesOnlyOneValue) { 5673 SDValue Val = IsSingleInstrConstant(Value, DAG, ST, dl); 5674 if (isConstant && Val.getNode()) 5675 return DAG.getNode(ARMISD::VDUP, dl, VT, Val); 5676 } 5677 } 5678 5679 // If all elements are constants and the case above didn't get hit, fall back 5680 // to the default expansion, which will generate a load from the constant 5681 // pool. 5682 if (isConstant) 5683 return SDValue(); 5684 5685 // Empirical tests suggest this is rarely worth it for vectors of length <= 2. 5686 if (NumElts >= 4) { 5687 SDValue shuffle = ReconstructShuffle(Op, DAG); 5688 if (shuffle != SDValue()) 5689 return shuffle; 5690 } 5691 5692 // Vectors with 32- or 64-bit elements can be built by directly assigning 5693 // the subregisters. Lower it to an ARMISD::BUILD_VECTOR so the operands 5694 // will be legalized. 5695 if (EltSize >= 32) { 5696 // Do the expansion with floating-point types, since that is what the VFP 5697 // registers are defined to use, and since i64 is not legal. 5698 EVT EltVT = EVT::getFloatingPointVT(EltSize); 5699 EVT VecVT = EVT::getVectorVT(*DAG.getContext(), EltVT, NumElts); 5700 SmallVector<SDValue, 8> Ops; 5701 for (unsigned i = 0; i < NumElts; ++i) 5702 Ops.push_back(DAG.getNode(ISD::BITCAST, dl, EltVT, Op.getOperand(i))); 5703 SDValue Val = DAG.getNode(ARMISD::BUILD_VECTOR, dl, VecVT, Ops); 5704 return DAG.getNode(ISD::BITCAST, dl, VT, Val); 5705 } 5706 5707 // If all else fails, just use a sequence of INSERT_VECTOR_ELT when we 5708 // know the default expansion would otherwise fall back on something even 5709 // worse. For a vector with one or two non-undef values, that's 5710 // scalar_to_vector for the elements followed by a shuffle (provided the 5711 // shuffle is valid for the target) and materialization element by element 5712 // on the stack followed by a load for everything else. 5713 if (!isConstant && !usesOnlyOneValue) { 5714 SDValue Vec = DAG.getUNDEF(VT); 5715 for (unsigned i = 0 ; i < NumElts; ++i) { 5716 SDValue V = Op.getOperand(i); 5717 if (V.isUndef()) 5718 continue; 5719 SDValue LaneIdx = DAG.getConstant(i, dl, MVT::i32); 5720 Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Vec, V, LaneIdx); 5721 } 5722 return Vec; 5723 } 5724 5725 return SDValue(); 5726 } 5727 5728 // Gather data to see if the operation can be modelled as a 5729 // shuffle in combination with VEXTs. 5730 SDValue ARMTargetLowering::ReconstructShuffle(SDValue Op, 5731 SelectionDAG &DAG) const { 5732 assert(Op.getOpcode() == ISD::BUILD_VECTOR && "Unknown opcode!"); 5733 SDLoc dl(Op); 5734 EVT VT = Op.getValueType(); 5735 unsigned NumElts = VT.getVectorNumElements(); 5736 5737 struct ShuffleSourceInfo { 5738 SDValue Vec; 5739 unsigned MinElt; 5740 unsigned MaxElt; 5741 5742 // We may insert some combination of BITCASTs and VEXT nodes to force Vec to 5743 // be compatible with the shuffle we intend to construct. As a result 5744 // ShuffleVec will be some sliding window into the original Vec. 5745 SDValue ShuffleVec; 5746 5747 // Code should guarantee that element i in Vec starts at element "WindowBase 5748 // + i * WindowScale in ShuffleVec". 5749 int WindowBase; 5750 int WindowScale; 5751 5752 bool operator ==(SDValue OtherVec) { return Vec == OtherVec; } 5753 ShuffleSourceInfo(SDValue Vec) 5754 : Vec(Vec), MinElt(UINT_MAX), MaxElt(0), ShuffleVec(Vec), WindowBase(0), 5755 WindowScale(1) {} 5756 }; 5757 5758 // First gather all vectors used as an immediate source for this BUILD_VECTOR 5759 // node. 5760 SmallVector<ShuffleSourceInfo, 2> Sources; 5761 for (unsigned i = 0; i < NumElts; ++i) { 5762 SDValue V = Op.getOperand(i); 5763 if (V.isUndef()) 5764 continue; 5765 else if (V.getOpcode() != ISD::EXTRACT_VECTOR_ELT) { 5766 // A shuffle can only come from building a vector from various 5767 // elements of other vectors. 5768 return SDValue(); 5769 } else if (!isa<ConstantSDNode>(V.getOperand(1))) { 5770 // Furthermore, shuffles require a constant mask, whereas extractelts 5771 // accept variable indices. 5772 return SDValue(); 5773 } 5774 5775 // Add this element source to the list if it's not already there. 5776 SDValue SourceVec = V.getOperand(0); 5777 auto Source = std::find(Sources.begin(), Sources.end(), SourceVec); 5778 if (Source == Sources.end()) 5779 Source = Sources.insert(Sources.end(), ShuffleSourceInfo(SourceVec)); 5780 5781 // Update the minimum and maximum lane number seen. 5782 unsigned EltNo = cast<ConstantSDNode>(V.getOperand(1))->getZExtValue(); 5783 Source->MinElt = std::min(Source->MinElt, EltNo); 5784 Source->MaxElt = std::max(Source->MaxElt, EltNo); 5785 } 5786 5787 // Currently only do something sane when at most two source vectors 5788 // are involved. 5789 if (Sources.size() > 2) 5790 return SDValue(); 5791 5792 // Find out the smallest element size among result and two sources, and use 5793 // it as element size to build the shuffle_vector. 5794 EVT SmallestEltTy = VT.getVectorElementType(); 5795 for (auto &Source : Sources) { 5796 EVT SrcEltTy = Source.Vec.getValueType().getVectorElementType(); 5797 if (SrcEltTy.bitsLT(SmallestEltTy)) 5798 SmallestEltTy = SrcEltTy; 5799 } 5800 unsigned ResMultiplier = 5801 VT.getVectorElementType().getSizeInBits() / SmallestEltTy.getSizeInBits(); 5802 NumElts = VT.getSizeInBits() / SmallestEltTy.getSizeInBits(); 5803 EVT ShuffleVT = EVT::getVectorVT(*DAG.getContext(), SmallestEltTy, NumElts); 5804 5805 // If the source vector is too wide or too narrow, we may nevertheless be able 5806 // to construct a compatible shuffle either by concatenating it with UNDEF or 5807 // extracting a suitable range of elements. 5808 for (auto &Src : Sources) { 5809 EVT SrcVT = Src.ShuffleVec.getValueType(); 5810 5811 if (SrcVT.getSizeInBits() == VT.getSizeInBits()) 5812 continue; 5813 5814 // This stage of the search produces a source with the same element type as 5815 // the original, but with a total width matching the BUILD_VECTOR output. 5816 EVT EltVT = SrcVT.getVectorElementType(); 5817 unsigned NumSrcElts = VT.getSizeInBits() / EltVT.getSizeInBits(); 5818 EVT DestVT = EVT::getVectorVT(*DAG.getContext(), EltVT, NumSrcElts); 5819 5820 if (SrcVT.getSizeInBits() < VT.getSizeInBits()) { 5821 if (2 * SrcVT.getSizeInBits() != VT.getSizeInBits()) 5822 return SDValue(); 5823 // We can pad out the smaller vector for free, so if it's part of a 5824 // shuffle... 5825 Src.ShuffleVec = 5826 DAG.getNode(ISD::CONCAT_VECTORS, dl, DestVT, Src.ShuffleVec, 5827 DAG.getUNDEF(Src.ShuffleVec.getValueType())); 5828 continue; 5829 } 5830 5831 if (SrcVT.getSizeInBits() != 2 * VT.getSizeInBits()) 5832 return SDValue(); 5833 5834 if (Src.MaxElt - Src.MinElt >= NumSrcElts) { 5835 // Span too large for a VEXT to cope 5836 return SDValue(); 5837 } 5838 5839 if (Src.MinElt >= NumSrcElts) { 5840 // The extraction can just take the second half 5841 Src.ShuffleVec = 5842 DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DestVT, Src.ShuffleVec, 5843 DAG.getConstant(NumSrcElts, dl, MVT::i32)); 5844 Src.WindowBase = -NumSrcElts; 5845 } else if (Src.MaxElt < NumSrcElts) { 5846 // The extraction can just take the first half 5847 Src.ShuffleVec = 5848 DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DestVT, Src.ShuffleVec, 5849 DAG.getConstant(0, dl, MVT::i32)); 5850 } else { 5851 // An actual VEXT is needed 5852 SDValue VEXTSrc1 = 5853 DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DestVT, Src.ShuffleVec, 5854 DAG.getConstant(0, dl, MVT::i32)); 5855 SDValue VEXTSrc2 = 5856 DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DestVT, Src.ShuffleVec, 5857 DAG.getConstant(NumSrcElts, dl, MVT::i32)); 5858 5859 Src.ShuffleVec = DAG.getNode(ARMISD::VEXT, dl, DestVT, VEXTSrc1, 5860 VEXTSrc2, 5861 DAG.getConstant(Src.MinElt, dl, MVT::i32)); 5862 Src.WindowBase = -Src.MinElt; 5863 } 5864 } 5865 5866 // Another possible incompatibility occurs from the vector element types. We 5867 // can fix this by bitcasting the source vectors to the same type we intend 5868 // for the shuffle. 5869 for (auto &Src : Sources) { 5870 EVT SrcEltTy = Src.ShuffleVec.getValueType().getVectorElementType(); 5871 if (SrcEltTy == SmallestEltTy) 5872 continue; 5873 assert(ShuffleVT.getVectorElementType() == SmallestEltTy); 5874 Src.ShuffleVec = DAG.getNode(ISD::BITCAST, dl, ShuffleVT, Src.ShuffleVec); 5875 Src.WindowScale = SrcEltTy.getSizeInBits() / SmallestEltTy.getSizeInBits(); 5876 Src.WindowBase *= Src.WindowScale; 5877 } 5878 5879 // Final sanity check before we try to actually produce a shuffle. 5880 DEBUG( 5881 for (auto Src : Sources) 5882 assert(Src.ShuffleVec.getValueType() == ShuffleVT); 5883 ); 5884 5885 // The stars all align, our next step is to produce the mask for the shuffle. 5886 SmallVector<int, 8> Mask(ShuffleVT.getVectorNumElements(), -1); 5887 int BitsPerShuffleLane = ShuffleVT.getVectorElementType().getSizeInBits(); 5888 for (unsigned i = 0; i < VT.getVectorNumElements(); ++i) { 5889 SDValue Entry = Op.getOperand(i); 5890 if (Entry.isUndef()) 5891 continue; 5892 5893 auto Src = std::find(Sources.begin(), Sources.end(), Entry.getOperand(0)); 5894 int EltNo = cast<ConstantSDNode>(Entry.getOperand(1))->getSExtValue(); 5895 5896 // EXTRACT_VECTOR_ELT performs an implicit any_ext; BUILD_VECTOR an implicit 5897 // trunc. So only std::min(SrcBits, DestBits) actually get defined in this 5898 // segment. 5899 EVT OrigEltTy = Entry.getOperand(0).getValueType().getVectorElementType(); 5900 int BitsDefined = std::min(OrigEltTy.getSizeInBits(), 5901 VT.getVectorElementType().getSizeInBits()); 5902 int LanesDefined = BitsDefined / BitsPerShuffleLane; 5903 5904 // This source is expected to fill ResMultiplier lanes of the final shuffle, 5905 // starting at the appropriate offset. 5906 int *LaneMask = &Mask[i * ResMultiplier]; 5907 5908 int ExtractBase = EltNo * Src->WindowScale + Src->WindowBase; 5909 ExtractBase += NumElts * (Src - Sources.begin()); 5910 for (int j = 0; j < LanesDefined; ++j) 5911 LaneMask[j] = ExtractBase + j; 5912 } 5913 5914 // Final check before we try to produce nonsense... 5915 if (!isShuffleMaskLegal(Mask, ShuffleVT)) 5916 return SDValue(); 5917 5918 // We can't handle more than two sources. This should have already 5919 // been checked before this point. 5920 assert(Sources.size() <= 2 && "Too many sources!"); 5921 5922 SDValue ShuffleOps[] = { DAG.getUNDEF(ShuffleVT), DAG.getUNDEF(ShuffleVT) }; 5923 for (unsigned i = 0; i < Sources.size(); ++i) 5924 ShuffleOps[i] = Sources[i].ShuffleVec; 5925 5926 SDValue Shuffle = DAG.getVectorShuffle(ShuffleVT, dl, ShuffleOps[0], 5927 ShuffleOps[1], &Mask[0]); 5928 return DAG.getNode(ISD::BITCAST, dl, VT, Shuffle); 5929 } 5930 5931 /// isShuffleMaskLegal - Targets can use this to indicate that they only 5932 /// support *some* VECTOR_SHUFFLE operations, those with specific masks. 5933 /// By default, if a target supports the VECTOR_SHUFFLE node, all mask values 5934 /// are assumed to be legal. 5935 bool 5936 ARMTargetLowering::isShuffleMaskLegal(const SmallVectorImpl<int> &M, 5937 EVT VT) const { 5938 if (VT.getVectorNumElements() == 4 && 5939 (VT.is128BitVector() || VT.is64BitVector())) { 5940 unsigned PFIndexes[4]; 5941 for (unsigned i = 0; i != 4; ++i) { 5942 if (M[i] < 0) 5943 PFIndexes[i] = 8; 5944 else 5945 PFIndexes[i] = M[i]; 5946 } 5947 5948 // Compute the index in the perfect shuffle table. 5949 unsigned PFTableIndex = 5950 PFIndexes[0]*9*9*9+PFIndexes[1]*9*9+PFIndexes[2]*9+PFIndexes[3]; 5951 unsigned PFEntry = PerfectShuffleTable[PFTableIndex]; 5952 unsigned Cost = (PFEntry >> 30); 5953 5954 if (Cost <= 4) 5955 return true; 5956 } 5957 5958 bool ReverseVEXT, isV_UNDEF; 5959 unsigned Imm, WhichResult; 5960 5961 unsigned EltSize = VT.getVectorElementType().getSizeInBits(); 5962 return (EltSize >= 32 || 5963 ShuffleVectorSDNode::isSplatMask(&M[0], VT) || 5964 isVREVMask(M, VT, 64) || 5965 isVREVMask(M, VT, 32) || 5966 isVREVMask(M, VT, 16) || 5967 isVEXTMask(M, VT, ReverseVEXT, Imm) || 5968 isVTBLMask(M, VT) || 5969 isNEONTwoResultShuffleMask(M, VT, WhichResult, isV_UNDEF) || 5970 ((VT == MVT::v8i16 || VT == MVT::v16i8) && isReverseMask(M, VT))); 5971 } 5972 5973 /// GeneratePerfectShuffle - Given an entry in the perfect-shuffle table, emit 5974 /// the specified operations to build the shuffle. 5975 static SDValue GeneratePerfectShuffle(unsigned PFEntry, SDValue LHS, 5976 SDValue RHS, SelectionDAG &DAG, 5977 SDLoc dl) { 5978 unsigned OpNum = (PFEntry >> 26) & 0x0F; 5979 unsigned LHSID = (PFEntry >> 13) & ((1 << 13)-1); 5980 unsigned RHSID = (PFEntry >> 0) & ((1 << 13)-1); 5981 5982 enum { 5983 OP_COPY = 0, // Copy, used for things like <u,u,u,3> to say it is <0,1,2,3> 5984 OP_VREV, 5985 OP_VDUP0, 5986 OP_VDUP1, 5987 OP_VDUP2, 5988 OP_VDUP3, 5989 OP_VEXT1, 5990 OP_VEXT2, 5991 OP_VEXT3, 5992 OP_VUZPL, // VUZP, left result 5993 OP_VUZPR, // VUZP, right result 5994 OP_VZIPL, // VZIP, left result 5995 OP_VZIPR, // VZIP, right result 5996 OP_VTRNL, // VTRN, left result 5997 OP_VTRNR // VTRN, right result 5998 }; 5999 6000 if (OpNum == OP_COPY) { 6001 if (LHSID == (1*9+2)*9+3) return LHS; 6002 assert(LHSID == ((4*9+5)*9+6)*9+7 && "Illegal OP_COPY!"); 6003 return RHS; 6004 } 6005 6006 SDValue OpLHS, OpRHS; 6007 OpLHS = GeneratePerfectShuffle(PerfectShuffleTable[LHSID], LHS, RHS, DAG, dl); 6008 OpRHS = GeneratePerfectShuffle(PerfectShuffleTable[RHSID], LHS, RHS, DAG, dl); 6009 EVT VT = OpLHS.getValueType(); 6010 6011 switch (OpNum) { 6012 default: llvm_unreachable("Unknown shuffle opcode!"); 6013 case OP_VREV: 6014 // VREV divides the vector in half and swaps within the half. 6015 if (VT.getVectorElementType() == MVT::i32 || 6016 VT.getVectorElementType() == MVT::f32) 6017 return DAG.getNode(ARMISD::VREV64, dl, VT, OpLHS); 6018 // vrev <4 x i16> -> VREV32 6019 if (VT.getVectorElementType() == MVT::i16) 6020 return DAG.getNode(ARMISD::VREV32, dl, VT, OpLHS); 6021 // vrev <4 x i8> -> VREV16 6022 assert(VT.getVectorElementType() == MVT::i8); 6023 return DAG.getNode(ARMISD::VREV16, dl, VT, OpLHS); 6024 case OP_VDUP0: 6025 case OP_VDUP1: 6026 case OP_VDUP2: 6027 case OP_VDUP3: 6028 return DAG.getNode(ARMISD::VDUPLANE, dl, VT, 6029 OpLHS, DAG.getConstant(OpNum-OP_VDUP0, dl, MVT::i32)); 6030 case OP_VEXT1: 6031 case OP_VEXT2: 6032 case OP_VEXT3: 6033 return DAG.getNode(ARMISD::VEXT, dl, VT, 6034 OpLHS, OpRHS, 6035 DAG.getConstant(OpNum - OP_VEXT1 + 1, dl, MVT::i32)); 6036 case OP_VUZPL: 6037 case OP_VUZPR: 6038 return DAG.getNode(ARMISD::VUZP, dl, DAG.getVTList(VT, VT), 6039 OpLHS, OpRHS).getValue(OpNum-OP_VUZPL); 6040 case OP_VZIPL: 6041 case OP_VZIPR: 6042 return DAG.getNode(ARMISD::VZIP, dl, DAG.getVTList(VT, VT), 6043 OpLHS, OpRHS).getValue(OpNum-OP_VZIPL); 6044 case OP_VTRNL: 6045 case OP_VTRNR: 6046 return DAG.getNode(ARMISD::VTRN, dl, DAG.getVTList(VT, VT), 6047 OpLHS, OpRHS).getValue(OpNum-OP_VTRNL); 6048 } 6049 } 6050 6051 static SDValue LowerVECTOR_SHUFFLEv8i8(SDValue Op, 6052 ArrayRef<int> ShuffleMask, 6053 SelectionDAG &DAG) { 6054 // Check to see if we can use the VTBL instruction. 6055 SDValue V1 = Op.getOperand(0); 6056 SDValue V2 = Op.getOperand(1); 6057 SDLoc DL(Op); 6058 6059 SmallVector<SDValue, 8> VTBLMask; 6060 for (ArrayRef<int>::iterator 6061 I = ShuffleMask.begin(), E = ShuffleMask.end(); I != E; ++I) 6062 VTBLMask.push_back(DAG.getConstant(*I, DL, MVT::i32)); 6063 6064 if (V2.getNode()->isUndef()) 6065 return DAG.getNode(ARMISD::VTBL1, DL, MVT::v8i8, V1, 6066 DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v8i8, VTBLMask)); 6067 6068 return DAG.getNode(ARMISD::VTBL2, DL, MVT::v8i8, V1, V2, 6069 DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v8i8, VTBLMask)); 6070 } 6071 6072 static SDValue LowerReverse_VECTOR_SHUFFLEv16i8_v8i16(SDValue Op, 6073 SelectionDAG &DAG) { 6074 SDLoc DL(Op); 6075 SDValue OpLHS = Op.getOperand(0); 6076 EVT VT = OpLHS.getValueType(); 6077 6078 assert((VT == MVT::v8i16 || VT == MVT::v16i8) && 6079 "Expect an v8i16/v16i8 type"); 6080 OpLHS = DAG.getNode(ARMISD::VREV64, DL, VT, OpLHS); 6081 // For a v16i8 type: After the VREV, we have got <8, ...15, 8, ..., 0>. Now, 6082 // extract the first 8 bytes into the top double word and the last 8 bytes 6083 // into the bottom double word. The v8i16 case is similar. 6084 unsigned ExtractNum = (VT == MVT::v16i8) ? 8 : 4; 6085 return DAG.getNode(ARMISD::VEXT, DL, VT, OpLHS, OpLHS, 6086 DAG.getConstant(ExtractNum, DL, MVT::i32)); 6087 } 6088 6089 static SDValue LowerVECTOR_SHUFFLE(SDValue Op, SelectionDAG &DAG) { 6090 SDValue V1 = Op.getOperand(0); 6091 SDValue V2 = Op.getOperand(1); 6092 SDLoc dl(Op); 6093 EVT VT = Op.getValueType(); 6094 ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(Op.getNode()); 6095 6096 // Convert shuffles that are directly supported on NEON to target-specific 6097 // DAG nodes, instead of keeping them as shuffles and matching them again 6098 // during code selection. This is more efficient and avoids the possibility 6099 // of inconsistencies between legalization and selection. 6100 // FIXME: floating-point vectors should be canonicalized to integer vectors 6101 // of the same time so that they get CSEd properly. 6102 ArrayRef<int> ShuffleMask = SVN->getMask(); 6103 6104 unsigned EltSize = VT.getVectorElementType().getSizeInBits(); 6105 if (EltSize <= 32) { 6106 if (ShuffleVectorSDNode::isSplatMask(&ShuffleMask[0], VT)) { 6107 int Lane = SVN->getSplatIndex(); 6108 // If this is undef splat, generate it via "just" vdup, if possible. 6109 if (Lane == -1) Lane = 0; 6110 6111 // Test if V1 is a SCALAR_TO_VECTOR. 6112 if (Lane == 0 && V1.getOpcode() == ISD::SCALAR_TO_VECTOR) { 6113 return DAG.getNode(ARMISD::VDUP, dl, VT, V1.getOperand(0)); 6114 } 6115 // Test if V1 is a BUILD_VECTOR which is equivalent to a SCALAR_TO_VECTOR 6116 // (and probably will turn into a SCALAR_TO_VECTOR once legalization 6117 // reaches it). 6118 if (Lane == 0 && V1.getOpcode() == ISD::BUILD_VECTOR && 6119 !isa<ConstantSDNode>(V1.getOperand(0))) { 6120 bool IsScalarToVector = true; 6121 for (unsigned i = 1, e = V1.getNumOperands(); i != e; ++i) 6122 if (!V1.getOperand(i).isUndef()) { 6123 IsScalarToVector = false; 6124 break; 6125 } 6126 if (IsScalarToVector) 6127 return DAG.getNode(ARMISD::VDUP, dl, VT, V1.getOperand(0)); 6128 } 6129 return DAG.getNode(ARMISD::VDUPLANE, dl, VT, V1, 6130 DAG.getConstant(Lane, dl, MVT::i32)); 6131 } 6132 6133 bool ReverseVEXT; 6134 unsigned Imm; 6135 if (isVEXTMask(ShuffleMask, VT, ReverseVEXT, Imm)) { 6136 if (ReverseVEXT) 6137 std::swap(V1, V2); 6138 return DAG.getNode(ARMISD::VEXT, dl, VT, V1, V2, 6139 DAG.getConstant(Imm, dl, MVT::i32)); 6140 } 6141 6142 if (isVREVMask(ShuffleMask, VT, 64)) 6143 return DAG.getNode(ARMISD::VREV64, dl, VT, V1); 6144 if (isVREVMask(ShuffleMask, VT, 32)) 6145 return DAG.getNode(ARMISD::VREV32, dl, VT, V1); 6146 if (isVREVMask(ShuffleMask, VT, 16)) 6147 return DAG.getNode(ARMISD::VREV16, dl, VT, V1); 6148 6149 if (V2->isUndef() && isSingletonVEXTMask(ShuffleMask, VT, Imm)) { 6150 return DAG.getNode(ARMISD::VEXT, dl, VT, V1, V1, 6151 DAG.getConstant(Imm, dl, MVT::i32)); 6152 } 6153 6154 // Check for Neon shuffles that modify both input vectors in place. 6155 // If both results are used, i.e., if there are two shuffles with the same 6156 // source operands and with masks corresponding to both results of one of 6157 // these operations, DAG memoization will ensure that a single node is 6158 // used for both shuffles. 6159 unsigned WhichResult; 6160 bool isV_UNDEF; 6161 if (unsigned ShuffleOpc = isNEONTwoResultShuffleMask( 6162 ShuffleMask, VT, WhichResult, isV_UNDEF)) { 6163 if (isV_UNDEF) 6164 V2 = V1; 6165 return DAG.getNode(ShuffleOpc, dl, DAG.getVTList(VT, VT), V1, V2) 6166 .getValue(WhichResult); 6167 } 6168 6169 // Also check for these shuffles through CONCAT_VECTORS: we canonicalize 6170 // shuffles that produce a result larger than their operands with: 6171 // shuffle(concat(v1, undef), concat(v2, undef)) 6172 // -> 6173 // shuffle(concat(v1, v2), undef) 6174 // because we can access quad vectors (see PerformVECTOR_SHUFFLECombine). 6175 // 6176 // This is useful in the general case, but there are special cases where 6177 // native shuffles produce larger results: the two-result ops. 6178 // 6179 // Look through the concat when lowering them: 6180 // shuffle(concat(v1, v2), undef) 6181 // -> 6182 // concat(VZIP(v1, v2):0, :1) 6183 // 6184 if (V1->getOpcode() == ISD::CONCAT_VECTORS && V2->isUndef()) { 6185 SDValue SubV1 = V1->getOperand(0); 6186 SDValue SubV2 = V1->getOperand(1); 6187 EVT SubVT = SubV1.getValueType(); 6188 6189 // We expect these to have been canonicalized to -1. 6190 assert(std::all_of(ShuffleMask.begin(), ShuffleMask.end(), [&](int i) { 6191 return i < (int)VT.getVectorNumElements(); 6192 }) && "Unexpected shuffle index into UNDEF operand!"); 6193 6194 if (unsigned ShuffleOpc = isNEONTwoResultShuffleMask( 6195 ShuffleMask, SubVT, WhichResult, isV_UNDEF)) { 6196 if (isV_UNDEF) 6197 SubV2 = SubV1; 6198 assert((WhichResult == 0) && 6199 "In-place shuffle of concat can only have one result!"); 6200 SDValue Res = DAG.getNode(ShuffleOpc, dl, DAG.getVTList(SubVT, SubVT), 6201 SubV1, SubV2); 6202 return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, Res.getValue(0), 6203 Res.getValue(1)); 6204 } 6205 } 6206 } 6207 6208 // If the shuffle is not directly supported and it has 4 elements, use 6209 // the PerfectShuffle-generated table to synthesize it from other shuffles. 6210 unsigned NumElts = VT.getVectorNumElements(); 6211 if (NumElts == 4) { 6212 unsigned PFIndexes[4]; 6213 for (unsigned i = 0; i != 4; ++i) { 6214 if (ShuffleMask[i] < 0) 6215 PFIndexes[i] = 8; 6216 else 6217 PFIndexes[i] = ShuffleMask[i]; 6218 } 6219 6220 // Compute the index in the perfect shuffle table. 6221 unsigned PFTableIndex = 6222 PFIndexes[0]*9*9*9+PFIndexes[1]*9*9+PFIndexes[2]*9+PFIndexes[3]; 6223 unsigned PFEntry = PerfectShuffleTable[PFTableIndex]; 6224 unsigned Cost = (PFEntry >> 30); 6225 6226 if (Cost <= 4) 6227 return GeneratePerfectShuffle(PFEntry, V1, V2, DAG, dl); 6228 } 6229 6230 // Implement shuffles with 32- or 64-bit elements as ARMISD::BUILD_VECTORs. 6231 if (EltSize >= 32) { 6232 // Do the expansion with floating-point types, since that is what the VFP 6233 // registers are defined to use, and since i64 is not legal. 6234 EVT EltVT = EVT::getFloatingPointVT(EltSize); 6235 EVT VecVT = EVT::getVectorVT(*DAG.getContext(), EltVT, NumElts); 6236 V1 = DAG.getNode(ISD::BITCAST, dl, VecVT, V1); 6237 V2 = DAG.getNode(ISD::BITCAST, dl, VecVT, V2); 6238 SmallVector<SDValue, 8> Ops; 6239 for (unsigned i = 0; i < NumElts; ++i) { 6240 if (ShuffleMask[i] < 0) 6241 Ops.push_back(DAG.getUNDEF(EltVT)); 6242 else 6243 Ops.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, EltVT, 6244 ShuffleMask[i] < (int)NumElts ? V1 : V2, 6245 DAG.getConstant(ShuffleMask[i] & (NumElts-1), 6246 dl, MVT::i32))); 6247 } 6248 SDValue Val = DAG.getNode(ARMISD::BUILD_VECTOR, dl, VecVT, Ops); 6249 return DAG.getNode(ISD::BITCAST, dl, VT, Val); 6250 } 6251 6252 if ((VT == MVT::v8i16 || VT == MVT::v16i8) && isReverseMask(ShuffleMask, VT)) 6253 return LowerReverse_VECTOR_SHUFFLEv16i8_v8i16(Op, DAG); 6254 6255 if (VT == MVT::v8i8) 6256 if (SDValue NewOp = LowerVECTOR_SHUFFLEv8i8(Op, ShuffleMask, DAG)) 6257 return NewOp; 6258 6259 return SDValue(); 6260 } 6261 6262 static SDValue LowerINSERT_VECTOR_ELT(SDValue Op, SelectionDAG &DAG) { 6263 // INSERT_VECTOR_ELT is legal only for immediate indexes. 6264 SDValue Lane = Op.getOperand(2); 6265 if (!isa<ConstantSDNode>(Lane)) 6266 return SDValue(); 6267 6268 return Op; 6269 } 6270 6271 static SDValue LowerEXTRACT_VECTOR_ELT(SDValue Op, SelectionDAG &DAG) { 6272 // EXTRACT_VECTOR_ELT is legal only for immediate indexes. 6273 SDValue Lane = Op.getOperand(1); 6274 if (!isa<ConstantSDNode>(Lane)) 6275 return SDValue(); 6276 6277 SDValue Vec = Op.getOperand(0); 6278 if (Op.getValueType() == MVT::i32 && 6279 Vec.getValueType().getVectorElementType().getSizeInBits() < 32) { 6280 SDLoc dl(Op); 6281 return DAG.getNode(ARMISD::VGETLANEu, dl, MVT::i32, Vec, Lane); 6282 } 6283 6284 return Op; 6285 } 6286 6287 static SDValue LowerCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG) { 6288 // The only time a CONCAT_VECTORS operation can have legal types is when 6289 // two 64-bit vectors are concatenated to a 128-bit vector. 6290 assert(Op.getValueType().is128BitVector() && Op.getNumOperands() == 2 && 6291 "unexpected CONCAT_VECTORS"); 6292 SDLoc dl(Op); 6293 SDValue Val = DAG.getUNDEF(MVT::v2f64); 6294 SDValue Op0 = Op.getOperand(0); 6295 SDValue Op1 = Op.getOperand(1); 6296 if (!Op0.isUndef()) 6297 Val = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Val, 6298 DAG.getNode(ISD::BITCAST, dl, MVT::f64, Op0), 6299 DAG.getIntPtrConstant(0, dl)); 6300 if (!Op1.isUndef()) 6301 Val = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Val, 6302 DAG.getNode(ISD::BITCAST, dl, MVT::f64, Op1), 6303 DAG.getIntPtrConstant(1, dl)); 6304 return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Val); 6305 } 6306 6307 /// isExtendedBUILD_VECTOR - Check if N is a constant BUILD_VECTOR where each 6308 /// element has been zero/sign-extended, depending on the isSigned parameter, 6309 /// from an integer type half its size. 6310 static bool isExtendedBUILD_VECTOR(SDNode *N, SelectionDAG &DAG, 6311 bool isSigned) { 6312 // A v2i64 BUILD_VECTOR will have been legalized to a BITCAST from v4i32. 6313 EVT VT = N->getValueType(0); 6314 if (VT == MVT::v2i64 && N->getOpcode() == ISD::BITCAST) { 6315 SDNode *BVN = N->getOperand(0).getNode(); 6316 if (BVN->getValueType(0) != MVT::v4i32 || 6317 BVN->getOpcode() != ISD::BUILD_VECTOR) 6318 return false; 6319 unsigned LoElt = DAG.getDataLayout().isBigEndian() ? 1 : 0; 6320 unsigned HiElt = 1 - LoElt; 6321 ConstantSDNode *Lo0 = dyn_cast<ConstantSDNode>(BVN->getOperand(LoElt)); 6322 ConstantSDNode *Hi0 = dyn_cast<ConstantSDNode>(BVN->getOperand(HiElt)); 6323 ConstantSDNode *Lo1 = dyn_cast<ConstantSDNode>(BVN->getOperand(LoElt+2)); 6324 ConstantSDNode *Hi1 = dyn_cast<ConstantSDNode>(BVN->getOperand(HiElt+2)); 6325 if (!Lo0 || !Hi0 || !Lo1 || !Hi1) 6326 return false; 6327 if (isSigned) { 6328 if (Hi0->getSExtValue() == Lo0->getSExtValue() >> 32 && 6329 Hi1->getSExtValue() == Lo1->getSExtValue() >> 32) 6330 return true; 6331 } else { 6332 if (Hi0->isNullValue() && Hi1->isNullValue()) 6333 return true; 6334 } 6335 return false; 6336 } 6337 6338 if (N->getOpcode() != ISD::BUILD_VECTOR) 6339 return false; 6340 6341 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) { 6342 SDNode *Elt = N->getOperand(i).getNode(); 6343 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Elt)) { 6344 unsigned EltSize = VT.getVectorElementType().getSizeInBits(); 6345 unsigned HalfSize = EltSize / 2; 6346 if (isSigned) { 6347 if (!isIntN(HalfSize, C->getSExtValue())) 6348 return false; 6349 } else { 6350 if (!isUIntN(HalfSize, C->getZExtValue())) 6351 return false; 6352 } 6353 continue; 6354 } 6355 return false; 6356 } 6357 6358 return true; 6359 } 6360 6361 /// isSignExtended - Check if a node is a vector value that is sign-extended 6362 /// or a constant BUILD_VECTOR with sign-extended elements. 6363 static bool isSignExtended(SDNode *N, SelectionDAG &DAG) { 6364 if (N->getOpcode() == ISD::SIGN_EXTEND || ISD::isSEXTLoad(N)) 6365 return true; 6366 if (isExtendedBUILD_VECTOR(N, DAG, true)) 6367 return true; 6368 return false; 6369 } 6370 6371 /// isZeroExtended - Check if a node is a vector value that is zero-extended 6372 /// or a constant BUILD_VECTOR with zero-extended elements. 6373 static bool isZeroExtended(SDNode *N, SelectionDAG &DAG) { 6374 if (N->getOpcode() == ISD::ZERO_EXTEND || ISD::isZEXTLoad(N)) 6375 return true; 6376 if (isExtendedBUILD_VECTOR(N, DAG, false)) 6377 return true; 6378 return false; 6379 } 6380 6381 static EVT getExtensionTo64Bits(const EVT &OrigVT) { 6382 if (OrigVT.getSizeInBits() >= 64) 6383 return OrigVT; 6384 6385 assert(OrigVT.isSimple() && "Expecting a simple value type"); 6386 6387 MVT::SimpleValueType OrigSimpleTy = OrigVT.getSimpleVT().SimpleTy; 6388 switch (OrigSimpleTy) { 6389 default: llvm_unreachable("Unexpected Vector Type"); 6390 case MVT::v2i8: 6391 case MVT::v2i16: 6392 return MVT::v2i32; 6393 case MVT::v4i8: 6394 return MVT::v4i16; 6395 } 6396 } 6397 6398 /// AddRequiredExtensionForVMULL - Add a sign/zero extension to extend the total 6399 /// value size to 64 bits. We need a 64-bit D register as an operand to VMULL. 6400 /// We insert the required extension here to get the vector to fill a D register. 6401 static SDValue AddRequiredExtensionForVMULL(SDValue N, SelectionDAG &DAG, 6402 const EVT &OrigTy, 6403 const EVT &ExtTy, 6404 unsigned ExtOpcode) { 6405 // The vector originally had a size of OrigTy. It was then extended to ExtTy. 6406 // We expect the ExtTy to be 128-bits total. If the OrigTy is less than 6407 // 64-bits we need to insert a new extension so that it will be 64-bits. 6408 assert(ExtTy.is128BitVector() && "Unexpected extension size"); 6409 if (OrigTy.getSizeInBits() >= 64) 6410 return N; 6411 6412 // Must extend size to at least 64 bits to be used as an operand for VMULL. 6413 EVT NewVT = getExtensionTo64Bits(OrigTy); 6414 6415 return DAG.getNode(ExtOpcode, SDLoc(N), NewVT, N); 6416 } 6417 6418 /// SkipLoadExtensionForVMULL - return a load of the original vector size that 6419 /// does not do any sign/zero extension. If the original vector is less 6420 /// than 64 bits, an appropriate extension will be added after the load to 6421 /// reach a total size of 64 bits. We have to add the extension separately 6422 /// because ARM does not have a sign/zero extending load for vectors. 6423 static SDValue SkipLoadExtensionForVMULL(LoadSDNode *LD, SelectionDAG& DAG) { 6424 EVT ExtendedTy = getExtensionTo64Bits(LD->getMemoryVT()); 6425 6426 // The load already has the right type. 6427 if (ExtendedTy == LD->getMemoryVT()) 6428 return DAG.getLoad(LD->getMemoryVT(), SDLoc(LD), LD->getChain(), 6429 LD->getBasePtr(), LD->getPointerInfo(), LD->isVolatile(), 6430 LD->isNonTemporal(), LD->isInvariant(), 6431 LD->getAlignment()); 6432 6433 // We need to create a zextload/sextload. We cannot just create a load 6434 // followed by a zext/zext node because LowerMUL is also run during normal 6435 // operation legalization where we can't create illegal types. 6436 return DAG.getExtLoad(LD->getExtensionType(), SDLoc(LD), ExtendedTy, 6437 LD->getChain(), LD->getBasePtr(), LD->getPointerInfo(), 6438 LD->getMemoryVT(), LD->isVolatile(), LD->isInvariant(), 6439 LD->isNonTemporal(), LD->getAlignment()); 6440 } 6441 6442 /// SkipExtensionForVMULL - For a node that is a SIGN_EXTEND, ZERO_EXTEND, 6443 /// extending load, or BUILD_VECTOR with extended elements, return the 6444 /// unextended value. The unextended vector should be 64 bits so that it can 6445 /// be used as an operand to a VMULL instruction. If the original vector size 6446 /// before extension is less than 64 bits we add a an extension to resize 6447 /// the vector to 64 bits. 6448 static SDValue SkipExtensionForVMULL(SDNode *N, SelectionDAG &DAG) { 6449 if (N->getOpcode() == ISD::SIGN_EXTEND || N->getOpcode() == ISD::ZERO_EXTEND) 6450 return AddRequiredExtensionForVMULL(N->getOperand(0), DAG, 6451 N->getOperand(0)->getValueType(0), 6452 N->getValueType(0), 6453 N->getOpcode()); 6454 6455 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) 6456 return SkipLoadExtensionForVMULL(LD, DAG); 6457 6458 // Otherwise, the value must be a BUILD_VECTOR. For v2i64, it will 6459 // have been legalized as a BITCAST from v4i32. 6460 if (N->getOpcode() == ISD::BITCAST) { 6461 SDNode *BVN = N->getOperand(0).getNode(); 6462 assert(BVN->getOpcode() == ISD::BUILD_VECTOR && 6463 BVN->getValueType(0) == MVT::v4i32 && "expected v4i32 BUILD_VECTOR"); 6464 unsigned LowElt = DAG.getDataLayout().isBigEndian() ? 1 : 0; 6465 return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), MVT::v2i32, 6466 BVN->getOperand(LowElt), BVN->getOperand(LowElt+2)); 6467 } 6468 // Construct a new BUILD_VECTOR with elements truncated to half the size. 6469 assert(N->getOpcode() == ISD::BUILD_VECTOR && "expected BUILD_VECTOR"); 6470 EVT VT = N->getValueType(0); 6471 unsigned EltSize = VT.getVectorElementType().getSizeInBits() / 2; 6472 unsigned NumElts = VT.getVectorNumElements(); 6473 MVT TruncVT = MVT::getIntegerVT(EltSize); 6474 SmallVector<SDValue, 8> Ops; 6475 SDLoc dl(N); 6476 for (unsigned i = 0; i != NumElts; ++i) { 6477 ConstantSDNode *C = cast<ConstantSDNode>(N->getOperand(i)); 6478 const APInt &CInt = C->getAPIntValue(); 6479 // Element types smaller than 32 bits are not legal, so use i32 elements. 6480 // The values are implicitly truncated so sext vs. zext doesn't matter. 6481 Ops.push_back(DAG.getConstant(CInt.zextOrTrunc(32), dl, MVT::i32)); 6482 } 6483 return DAG.getNode(ISD::BUILD_VECTOR, dl, 6484 MVT::getVectorVT(TruncVT, NumElts), Ops); 6485 } 6486 6487 static bool isAddSubSExt(SDNode *N, SelectionDAG &DAG) { 6488 unsigned Opcode = N->getOpcode(); 6489 if (Opcode == ISD::ADD || Opcode == ISD::SUB) { 6490 SDNode *N0 = N->getOperand(0).getNode(); 6491 SDNode *N1 = N->getOperand(1).getNode(); 6492 return N0->hasOneUse() && N1->hasOneUse() && 6493 isSignExtended(N0, DAG) && isSignExtended(N1, DAG); 6494 } 6495 return false; 6496 } 6497 6498 static bool isAddSubZExt(SDNode *N, SelectionDAG &DAG) { 6499 unsigned Opcode = N->getOpcode(); 6500 if (Opcode == ISD::ADD || Opcode == ISD::SUB) { 6501 SDNode *N0 = N->getOperand(0).getNode(); 6502 SDNode *N1 = N->getOperand(1).getNode(); 6503 return N0->hasOneUse() && N1->hasOneUse() && 6504 isZeroExtended(N0, DAG) && isZeroExtended(N1, DAG); 6505 } 6506 return false; 6507 } 6508 6509 static SDValue LowerMUL(SDValue Op, SelectionDAG &DAG) { 6510 // Multiplications are only custom-lowered for 128-bit vectors so that 6511 // VMULL can be detected. Otherwise v2i64 multiplications are not legal. 6512 EVT VT = Op.getValueType(); 6513 assert(VT.is128BitVector() && VT.isInteger() && 6514 "unexpected type for custom-lowering ISD::MUL"); 6515 SDNode *N0 = Op.getOperand(0).getNode(); 6516 SDNode *N1 = Op.getOperand(1).getNode(); 6517 unsigned NewOpc = 0; 6518 bool isMLA = false; 6519 bool isN0SExt = isSignExtended(N0, DAG); 6520 bool isN1SExt = isSignExtended(N1, DAG); 6521 if (isN0SExt && isN1SExt) 6522 NewOpc = ARMISD::VMULLs; 6523 else { 6524 bool isN0ZExt = isZeroExtended(N0, DAG); 6525 bool isN1ZExt = isZeroExtended(N1, DAG); 6526 if (isN0ZExt && isN1ZExt) 6527 NewOpc = ARMISD::VMULLu; 6528 else if (isN1SExt || isN1ZExt) { 6529 // Look for (s/zext A + s/zext B) * (s/zext C). We want to turn these 6530 // into (s/zext A * s/zext C) + (s/zext B * s/zext C) 6531 if (isN1SExt && isAddSubSExt(N0, DAG)) { 6532 NewOpc = ARMISD::VMULLs; 6533 isMLA = true; 6534 } else if (isN1ZExt && isAddSubZExt(N0, DAG)) { 6535 NewOpc = ARMISD::VMULLu; 6536 isMLA = true; 6537 } else if (isN0ZExt && isAddSubZExt(N1, DAG)) { 6538 std::swap(N0, N1); 6539 NewOpc = ARMISD::VMULLu; 6540 isMLA = true; 6541 } 6542 } 6543 6544 if (!NewOpc) { 6545 if (VT == MVT::v2i64) 6546 // Fall through to expand this. It is not legal. 6547 return SDValue(); 6548 else 6549 // Other vector multiplications are legal. 6550 return Op; 6551 } 6552 } 6553 6554 // Legalize to a VMULL instruction. 6555 SDLoc DL(Op); 6556 SDValue Op0; 6557 SDValue Op1 = SkipExtensionForVMULL(N1, DAG); 6558 if (!isMLA) { 6559 Op0 = SkipExtensionForVMULL(N0, DAG); 6560 assert(Op0.getValueType().is64BitVector() && 6561 Op1.getValueType().is64BitVector() && 6562 "unexpected types for extended operands to VMULL"); 6563 return DAG.getNode(NewOpc, DL, VT, Op0, Op1); 6564 } 6565 6566 // Optimizing (zext A + zext B) * C, to (VMULL A, C) + (VMULL B, C) during 6567 // isel lowering to take advantage of no-stall back to back vmul + vmla. 6568 // vmull q0, d4, d6 6569 // vmlal q0, d5, d6 6570 // is faster than 6571 // vaddl q0, d4, d5 6572 // vmovl q1, d6 6573 // vmul q0, q0, q1 6574 SDValue N00 = SkipExtensionForVMULL(N0->getOperand(0).getNode(), DAG); 6575 SDValue N01 = SkipExtensionForVMULL(N0->getOperand(1).getNode(), DAG); 6576 EVT Op1VT = Op1.getValueType(); 6577 return DAG.getNode(N0->getOpcode(), DL, VT, 6578 DAG.getNode(NewOpc, DL, VT, 6579 DAG.getNode(ISD::BITCAST, DL, Op1VT, N00), Op1), 6580 DAG.getNode(NewOpc, DL, VT, 6581 DAG.getNode(ISD::BITCAST, DL, Op1VT, N01), Op1)); 6582 } 6583 6584 static SDValue 6585 LowerSDIV_v4i8(SDValue X, SDValue Y, SDLoc dl, SelectionDAG &DAG) { 6586 // TODO: Should this propagate fast-math-flags? 6587 6588 // Convert to float 6589 // float4 xf = vcvt_f32_s32(vmovl_s16(a.lo)); 6590 // float4 yf = vcvt_f32_s32(vmovl_s16(b.lo)); 6591 X = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, X); 6592 Y = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, Y); 6593 X = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, X); 6594 Y = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, Y); 6595 // Get reciprocal estimate. 6596 // float4 recip = vrecpeq_f32(yf); 6597 Y = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32, 6598 DAG.getConstant(Intrinsic::arm_neon_vrecpe, dl, MVT::i32), 6599 Y); 6600 // Because char has a smaller range than uchar, we can actually get away 6601 // without any newton steps. This requires that we use a weird bias 6602 // of 0xb000, however (again, this has been exhaustively tested). 6603 // float4 result = as_float4(as_int4(xf*recip) + 0xb000); 6604 X = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, X, Y); 6605 X = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, X); 6606 Y = DAG.getConstant(0xb000, dl, MVT::v4i32); 6607 X = DAG.getNode(ISD::ADD, dl, MVT::v4i32, X, Y); 6608 X = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, X); 6609 // Convert back to short. 6610 X = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::v4i32, X); 6611 X = DAG.getNode(ISD::TRUNCATE, dl, MVT::v4i16, X); 6612 return X; 6613 } 6614 6615 static SDValue 6616 LowerSDIV_v4i16(SDValue N0, SDValue N1, SDLoc dl, SelectionDAG &DAG) { 6617 // TODO: Should this propagate fast-math-flags? 6618 6619 SDValue N2; 6620 // Convert to float. 6621 // float4 yf = vcvt_f32_s32(vmovl_s16(y)); 6622 // float4 xf = vcvt_f32_s32(vmovl_s16(x)); 6623 N0 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, N0); 6624 N1 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, N1); 6625 N0 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N0); 6626 N1 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N1); 6627 6628 // Use reciprocal estimate and one refinement step. 6629 // float4 recip = vrecpeq_f32(yf); 6630 // recip *= vrecpsq_f32(yf, recip); 6631 N2 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32, 6632 DAG.getConstant(Intrinsic::arm_neon_vrecpe, dl, MVT::i32), 6633 N1); 6634 N1 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32, 6635 DAG.getConstant(Intrinsic::arm_neon_vrecps, dl, MVT::i32), 6636 N1, N2); 6637 N2 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N1, N2); 6638 // Because short has a smaller range than ushort, we can actually get away 6639 // with only a single newton step. This requires that we use a weird bias 6640 // of 89, however (again, this has been exhaustively tested). 6641 // float4 result = as_float4(as_int4(xf*recip) + 0x89); 6642 N0 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N0, N2); 6643 N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, N0); 6644 N1 = DAG.getConstant(0x89, dl, MVT::v4i32); 6645 N0 = DAG.getNode(ISD::ADD, dl, MVT::v4i32, N0, N1); 6646 N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, N0); 6647 // Convert back to integer and return. 6648 // return vmovn_s32(vcvt_s32_f32(result)); 6649 N0 = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::v4i32, N0); 6650 N0 = DAG.getNode(ISD::TRUNCATE, dl, MVT::v4i16, N0); 6651 return N0; 6652 } 6653 6654 static SDValue LowerSDIV(SDValue Op, SelectionDAG &DAG) { 6655 EVT VT = Op.getValueType(); 6656 assert((VT == MVT::v4i16 || VT == MVT::v8i8) && 6657 "unexpected type for custom-lowering ISD::SDIV"); 6658 6659 SDLoc dl(Op); 6660 SDValue N0 = Op.getOperand(0); 6661 SDValue N1 = Op.getOperand(1); 6662 SDValue N2, N3; 6663 6664 if (VT == MVT::v8i8) { 6665 N0 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v8i16, N0); 6666 N1 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v8i16, N1); 6667 6668 N2 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0, 6669 DAG.getIntPtrConstant(4, dl)); 6670 N3 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1, 6671 DAG.getIntPtrConstant(4, dl)); 6672 N0 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0, 6673 DAG.getIntPtrConstant(0, dl)); 6674 N1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1, 6675 DAG.getIntPtrConstant(0, dl)); 6676 6677 N0 = LowerSDIV_v4i8(N0, N1, dl, DAG); // v4i16 6678 N2 = LowerSDIV_v4i8(N2, N3, dl, DAG); // v4i16 6679 6680 N0 = DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v8i16, N0, N2); 6681 N0 = LowerCONCAT_VECTORS(N0, DAG); 6682 6683 N0 = DAG.getNode(ISD::TRUNCATE, dl, MVT::v8i8, N0); 6684 return N0; 6685 } 6686 return LowerSDIV_v4i16(N0, N1, dl, DAG); 6687 } 6688 6689 static SDValue LowerUDIV(SDValue Op, SelectionDAG &DAG) { 6690 // TODO: Should this propagate fast-math-flags? 6691 EVT VT = Op.getValueType(); 6692 assert((VT == MVT::v4i16 || VT == MVT::v8i8) && 6693 "unexpected type for custom-lowering ISD::UDIV"); 6694 6695 SDLoc dl(Op); 6696 SDValue N0 = Op.getOperand(0); 6697 SDValue N1 = Op.getOperand(1); 6698 SDValue N2, N3; 6699 6700 if (VT == MVT::v8i8) { 6701 N0 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v8i16, N0); 6702 N1 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v8i16, N1); 6703 6704 N2 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0, 6705 DAG.getIntPtrConstant(4, dl)); 6706 N3 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1, 6707 DAG.getIntPtrConstant(4, dl)); 6708 N0 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0, 6709 DAG.getIntPtrConstant(0, dl)); 6710 N1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1, 6711 DAG.getIntPtrConstant(0, dl)); 6712 6713 N0 = LowerSDIV_v4i16(N0, N1, dl, DAG); // v4i16 6714 N2 = LowerSDIV_v4i16(N2, N3, dl, DAG); // v4i16 6715 6716 N0 = DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v8i16, N0, N2); 6717 N0 = LowerCONCAT_VECTORS(N0, DAG); 6718 6719 N0 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v8i8, 6720 DAG.getConstant(Intrinsic::arm_neon_vqmovnsu, dl, 6721 MVT::i32), 6722 N0); 6723 return N0; 6724 } 6725 6726 // v4i16 sdiv ... Convert to float. 6727 // float4 yf = vcvt_f32_s32(vmovl_u16(y)); 6728 // float4 xf = vcvt_f32_s32(vmovl_u16(x)); 6729 N0 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v4i32, N0); 6730 N1 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v4i32, N1); 6731 N0 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N0); 6732 SDValue BN1 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N1); 6733 6734 // Use reciprocal estimate and two refinement steps. 6735 // float4 recip = vrecpeq_f32(yf); 6736 // recip *= vrecpsq_f32(yf, recip); 6737 // recip *= vrecpsq_f32(yf, recip); 6738 N2 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32, 6739 DAG.getConstant(Intrinsic::arm_neon_vrecpe, dl, MVT::i32), 6740 BN1); 6741 N1 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32, 6742 DAG.getConstant(Intrinsic::arm_neon_vrecps, dl, MVT::i32), 6743 BN1, N2); 6744 N2 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N1, N2); 6745 N1 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32, 6746 DAG.getConstant(Intrinsic::arm_neon_vrecps, dl, MVT::i32), 6747 BN1, N2); 6748 N2 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N1, N2); 6749 // Simply multiplying by the reciprocal estimate can leave us a few ulps 6750 // too low, so we add 2 ulps (exhaustive testing shows that this is enough, 6751 // and that it will never cause us to return an answer too large). 6752 // float4 result = as_float4(as_int4(xf*recip) + 2); 6753 N0 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N0, N2); 6754 N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, N0); 6755 N1 = DAG.getConstant(2, dl, MVT::v4i32); 6756 N0 = DAG.getNode(ISD::ADD, dl, MVT::v4i32, N0, N1); 6757 N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, N0); 6758 // Convert back to integer and return. 6759 // return vmovn_u32(vcvt_s32_f32(result)); 6760 N0 = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::v4i32, N0); 6761 N0 = DAG.getNode(ISD::TRUNCATE, dl, MVT::v4i16, N0); 6762 return N0; 6763 } 6764 6765 static SDValue LowerADDC_ADDE_SUBC_SUBE(SDValue Op, SelectionDAG &DAG) { 6766 EVT VT = Op.getNode()->getValueType(0); 6767 SDVTList VTs = DAG.getVTList(VT, MVT::i32); 6768 6769 unsigned Opc; 6770 bool ExtraOp = false; 6771 switch (Op.getOpcode()) { 6772 default: llvm_unreachable("Invalid code"); 6773 case ISD::ADDC: Opc = ARMISD::ADDC; break; 6774 case ISD::ADDE: Opc = ARMISD::ADDE; ExtraOp = true; break; 6775 case ISD::SUBC: Opc = ARMISD::SUBC; break; 6776 case ISD::SUBE: Opc = ARMISD::SUBE; ExtraOp = true; break; 6777 } 6778 6779 if (!ExtraOp) 6780 return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0), 6781 Op.getOperand(1)); 6782 return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0), 6783 Op.getOperand(1), Op.getOperand(2)); 6784 } 6785 6786 SDValue ARMTargetLowering::LowerFSINCOS(SDValue Op, SelectionDAG &DAG) const { 6787 assert(Subtarget->isTargetDarwin()); 6788 6789 // For iOS, we want to call an alternative entry point: __sincos_stret, 6790 // return values are passed via sret. 6791 SDLoc dl(Op); 6792 SDValue Arg = Op.getOperand(0); 6793 EVT ArgVT = Arg.getValueType(); 6794 Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext()); 6795 auto PtrVT = getPointerTy(DAG.getDataLayout()); 6796 6797 MachineFrameInfo *FrameInfo = DAG.getMachineFunction().getFrameInfo(); 6798 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 6799 6800 // Pair of floats / doubles used to pass the result. 6801 Type *RetTy = StructType::get(ArgTy, ArgTy, nullptr); 6802 auto &DL = DAG.getDataLayout(); 6803 6804 ArgListTy Args; 6805 bool ShouldUseSRet = Subtarget->isAPCS_ABI(); 6806 SDValue SRet; 6807 if (ShouldUseSRet) { 6808 // Create stack object for sret. 6809 const uint64_t ByteSize = DL.getTypeAllocSize(RetTy); 6810 const unsigned StackAlign = DL.getPrefTypeAlignment(RetTy); 6811 int FrameIdx = FrameInfo->CreateStackObject(ByteSize, StackAlign, false); 6812 SRet = DAG.getFrameIndex(FrameIdx, TLI.getPointerTy(DL)); 6813 6814 ArgListEntry Entry; 6815 Entry.Node = SRet; 6816 Entry.Ty = RetTy->getPointerTo(); 6817 Entry.isSExt = false; 6818 Entry.isZExt = false; 6819 Entry.isSRet = true; 6820 Args.push_back(Entry); 6821 RetTy = Type::getVoidTy(*DAG.getContext()); 6822 } 6823 6824 ArgListEntry Entry; 6825 Entry.Node = Arg; 6826 Entry.Ty = ArgTy; 6827 Entry.isSExt = false; 6828 Entry.isZExt = false; 6829 Args.push_back(Entry); 6830 6831 const char *LibcallName = 6832 (ArgVT == MVT::f64) ? "__sincos_stret" : "__sincosf_stret"; 6833 RTLIB::Libcall LC = 6834 (ArgVT == MVT::f64) ? RTLIB::SINCOS_F64 : RTLIB::SINCOS_F32; 6835 CallingConv::ID CC = getLibcallCallingConv(LC); 6836 SDValue Callee = DAG.getExternalSymbol(LibcallName, getPointerTy(DL)); 6837 6838 TargetLowering::CallLoweringInfo CLI(DAG); 6839 CLI.setDebugLoc(dl) 6840 .setChain(DAG.getEntryNode()) 6841 .setCallee(CC, RetTy, Callee, std::move(Args), 0) 6842 .setDiscardResult(ShouldUseSRet); 6843 std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI); 6844 6845 if (!ShouldUseSRet) 6846 return CallResult.first; 6847 6848 SDValue LoadSin = DAG.getLoad(ArgVT, dl, CallResult.second, SRet, 6849 MachinePointerInfo(), false, false, false, 0); 6850 6851 // Address of cos field. 6852 SDValue Add = DAG.getNode(ISD::ADD, dl, PtrVT, SRet, 6853 DAG.getIntPtrConstant(ArgVT.getStoreSize(), dl)); 6854 SDValue LoadCos = DAG.getLoad(ArgVT, dl, LoadSin.getValue(1), Add, 6855 MachinePointerInfo(), false, false, false, 0); 6856 6857 SDVTList Tys = DAG.getVTList(ArgVT, ArgVT); 6858 return DAG.getNode(ISD::MERGE_VALUES, dl, Tys, 6859 LoadSin.getValue(0), LoadCos.getValue(0)); 6860 } 6861 6862 SDValue ARMTargetLowering::LowerWindowsDIVLibCall(SDValue Op, SelectionDAG &DAG, 6863 bool Signed, 6864 SDValue &Chain) const { 6865 EVT VT = Op.getValueType(); 6866 assert((VT == MVT::i32 || VT == MVT::i64) && 6867 "unexpected type for custom lowering DIV"); 6868 SDLoc dl(Op); 6869 6870 const auto &DL = DAG.getDataLayout(); 6871 const auto &TLI = DAG.getTargetLoweringInfo(); 6872 6873 const char *Name = nullptr; 6874 if (Signed) 6875 Name = (VT == MVT::i32) ? "__rt_sdiv" : "__rt_sdiv64"; 6876 else 6877 Name = (VT == MVT::i32) ? "__rt_udiv" : "__rt_udiv64"; 6878 6879 SDValue ES = DAG.getExternalSymbol(Name, TLI.getPointerTy(DL)); 6880 6881 ARMTargetLowering::ArgListTy Args; 6882 6883 for (auto AI : {1, 0}) { 6884 ArgListEntry Arg; 6885 Arg.Node = Op.getOperand(AI); 6886 Arg.Ty = Arg.Node.getValueType().getTypeForEVT(*DAG.getContext()); 6887 Args.push_back(Arg); 6888 } 6889 6890 CallLoweringInfo CLI(DAG); 6891 CLI.setDebugLoc(dl) 6892 .setChain(Chain) 6893 .setCallee(CallingConv::ARM_AAPCS_VFP, VT.getTypeForEVT(*DAG.getContext()), 6894 ES, std::move(Args), 0); 6895 6896 return LowerCallTo(CLI).first; 6897 } 6898 6899 SDValue ARMTargetLowering::LowerDIV_Windows(SDValue Op, SelectionDAG &DAG, 6900 bool Signed) const { 6901 assert(Op.getValueType() == MVT::i32 && 6902 "unexpected type for custom lowering DIV"); 6903 SDLoc dl(Op); 6904 6905 SDValue DBZCHK = DAG.getNode(ARMISD::WIN__DBZCHK, dl, MVT::Other, 6906 DAG.getEntryNode(), Op.getOperand(1)); 6907 6908 return LowerWindowsDIVLibCall(Op, DAG, Signed, DBZCHK); 6909 } 6910 6911 void ARMTargetLowering::ExpandDIV_Windows( 6912 SDValue Op, SelectionDAG &DAG, bool Signed, 6913 SmallVectorImpl<SDValue> &Results) const { 6914 const auto &DL = DAG.getDataLayout(); 6915 const auto &TLI = DAG.getTargetLoweringInfo(); 6916 6917 assert(Op.getValueType() == MVT::i64 && 6918 "unexpected type for custom lowering DIV"); 6919 SDLoc dl(Op); 6920 6921 SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, Op.getOperand(1), 6922 DAG.getConstant(0, dl, MVT::i32)); 6923 SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, Op.getOperand(1), 6924 DAG.getConstant(1, dl, MVT::i32)); 6925 SDValue Or = DAG.getNode(ISD::OR, dl, MVT::i32, Lo, Hi); 6926 6927 SDValue DBZCHK = 6928 DAG.getNode(ARMISD::WIN__DBZCHK, dl, MVT::Other, DAG.getEntryNode(), Or); 6929 6930 SDValue Result = LowerWindowsDIVLibCall(Op, DAG, Signed, DBZCHK); 6931 6932 SDValue Lower = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, Result); 6933 SDValue Upper = DAG.getNode(ISD::SRL, dl, MVT::i64, Result, 6934 DAG.getConstant(32, dl, TLI.getPointerTy(DL))); 6935 Upper = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, Upper); 6936 6937 Results.push_back(Lower); 6938 Results.push_back(Upper); 6939 } 6940 6941 static SDValue LowerAtomicLoadStore(SDValue Op, SelectionDAG &DAG) { 6942 if (isStrongerThanMonotonic(cast<AtomicSDNode>(Op)->getOrdering())) 6943 // Acquire/Release load/store is not legal for targets without a dmb or 6944 // equivalent available. 6945 return SDValue(); 6946 6947 // Monotonic load/store is legal for all targets. 6948 return Op; 6949 } 6950 6951 static void ReplaceREADCYCLECOUNTER(SDNode *N, 6952 SmallVectorImpl<SDValue> &Results, 6953 SelectionDAG &DAG, 6954 const ARMSubtarget *Subtarget) { 6955 SDLoc DL(N); 6956 // Under Power Management extensions, the cycle-count is: 6957 // mrc p15, #0, <Rt>, c9, c13, #0 6958 SDValue Ops[] = { N->getOperand(0), // Chain 6959 DAG.getConstant(Intrinsic::arm_mrc, DL, MVT::i32), 6960 DAG.getConstant(15, DL, MVT::i32), 6961 DAG.getConstant(0, DL, MVT::i32), 6962 DAG.getConstant(9, DL, MVT::i32), 6963 DAG.getConstant(13, DL, MVT::i32), 6964 DAG.getConstant(0, DL, MVT::i32) 6965 }; 6966 6967 SDValue Cycles32 = DAG.getNode(ISD::INTRINSIC_W_CHAIN, DL, 6968 DAG.getVTList(MVT::i32, MVT::Other), Ops); 6969 Results.push_back(DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, Cycles32, 6970 DAG.getConstant(0, DL, MVT::i32))); 6971 Results.push_back(Cycles32.getValue(1)); 6972 } 6973 6974 static SDValue createGPRPairNode(SelectionDAG &DAG, SDValue V) { 6975 SDLoc dl(V.getNode()); 6976 SDValue VLo = DAG.getAnyExtOrTrunc(V, dl, MVT::i32); 6977 SDValue VHi = DAG.getAnyExtOrTrunc( 6978 DAG.getNode(ISD::SRL, dl, MVT::i64, V, DAG.getConstant(32, dl, MVT::i32)), 6979 dl, MVT::i32); 6980 SDValue RegClass = 6981 DAG.getTargetConstant(ARM::GPRPairRegClassID, dl, MVT::i32); 6982 SDValue SubReg0 = DAG.getTargetConstant(ARM::gsub_0, dl, MVT::i32); 6983 SDValue SubReg1 = DAG.getTargetConstant(ARM::gsub_1, dl, MVT::i32); 6984 const SDValue Ops[] = { RegClass, VLo, SubReg0, VHi, SubReg1 }; 6985 return SDValue( 6986 DAG.getMachineNode(TargetOpcode::REG_SEQUENCE, dl, MVT::Untyped, Ops), 0); 6987 } 6988 6989 static void ReplaceCMP_SWAP_64Results(SDNode *N, 6990 SmallVectorImpl<SDValue> & Results, 6991 SelectionDAG &DAG) { 6992 assert(N->getValueType(0) == MVT::i64 && 6993 "AtomicCmpSwap on types less than 64 should be legal"); 6994 SDValue Ops[] = {N->getOperand(1), 6995 createGPRPairNode(DAG, N->getOperand(2)), 6996 createGPRPairNode(DAG, N->getOperand(3)), 6997 N->getOperand(0)}; 6998 SDNode *CmpSwap = DAG.getMachineNode( 6999 ARM::CMP_SWAP_64, SDLoc(N), 7000 DAG.getVTList(MVT::Untyped, MVT::i32, MVT::Other), Ops); 7001 7002 MachineFunction &MF = DAG.getMachineFunction(); 7003 MachineSDNode::mmo_iterator MemOp = MF.allocateMemRefsArray(1); 7004 MemOp[0] = cast<MemSDNode>(N)->getMemOperand(); 7005 cast<MachineSDNode>(CmpSwap)->setMemRefs(MemOp, MemOp + 1); 7006 7007 Results.push_back(DAG.getTargetExtractSubreg(ARM::gsub_0, SDLoc(N), MVT::i32, 7008 SDValue(CmpSwap, 0))); 7009 Results.push_back(DAG.getTargetExtractSubreg(ARM::gsub_1, SDLoc(N), MVT::i32, 7010 SDValue(CmpSwap, 0))); 7011 Results.push_back(SDValue(CmpSwap, 2)); 7012 } 7013 7014 SDValue ARMTargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const { 7015 switch (Op.getOpcode()) { 7016 default: llvm_unreachable("Don't know how to custom lower this!"); 7017 case ISD::WRITE_REGISTER: return LowerWRITE_REGISTER(Op, DAG); 7018 case ISD::ConstantPool: return LowerConstantPool(Op, DAG); 7019 case ISD::BlockAddress: return LowerBlockAddress(Op, DAG); 7020 case ISD::GlobalAddress: 7021 switch (Subtarget->getTargetTriple().getObjectFormat()) { 7022 default: llvm_unreachable("unknown object format"); 7023 case Triple::COFF: 7024 return LowerGlobalAddressWindows(Op, DAG); 7025 case Triple::ELF: 7026 return LowerGlobalAddressELF(Op, DAG); 7027 case Triple::MachO: 7028 return LowerGlobalAddressDarwin(Op, DAG); 7029 } 7030 case ISD::GlobalTLSAddress: return LowerGlobalTLSAddress(Op, DAG); 7031 case ISD::SELECT: return LowerSELECT(Op, DAG); 7032 case ISD::SELECT_CC: return LowerSELECT_CC(Op, DAG); 7033 case ISD::BR_CC: return LowerBR_CC(Op, DAG); 7034 case ISD::BR_JT: return LowerBR_JT(Op, DAG); 7035 case ISD::VASTART: return LowerVASTART(Op, DAG); 7036 case ISD::ATOMIC_FENCE: return LowerATOMIC_FENCE(Op, DAG, Subtarget); 7037 case ISD::PREFETCH: return LowerPREFETCH(Op, DAG, Subtarget); 7038 case ISD::SINT_TO_FP: 7039 case ISD::UINT_TO_FP: return LowerINT_TO_FP(Op, DAG); 7040 case ISD::FP_TO_SINT: 7041 case ISD::FP_TO_UINT: return LowerFP_TO_INT(Op, DAG); 7042 case ISD::FCOPYSIGN: return LowerFCOPYSIGN(Op, DAG); 7043 case ISD::RETURNADDR: return LowerRETURNADDR(Op, DAG); 7044 case ISD::FRAMEADDR: return LowerFRAMEADDR(Op, DAG); 7045 case ISD::EH_SJLJ_SETJMP: return LowerEH_SJLJ_SETJMP(Op, DAG); 7046 case ISD::EH_SJLJ_LONGJMP: return LowerEH_SJLJ_LONGJMP(Op, DAG); 7047 case ISD::EH_SJLJ_SETUP_DISPATCH: return LowerEH_SJLJ_SETUP_DISPATCH(Op, DAG); 7048 case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG, 7049 Subtarget); 7050 case ISD::BITCAST: return ExpandBITCAST(Op.getNode(), DAG); 7051 case ISD::SHL: 7052 case ISD::SRL: 7053 case ISD::SRA: return LowerShift(Op.getNode(), DAG, Subtarget); 7054 case ISD::SREM: return LowerREM(Op.getNode(), DAG); 7055 case ISD::UREM: return LowerREM(Op.getNode(), DAG); 7056 case ISD::SHL_PARTS: return LowerShiftLeftParts(Op, DAG); 7057 case ISD::SRL_PARTS: 7058 case ISD::SRA_PARTS: return LowerShiftRightParts(Op, DAG); 7059 case ISD::CTTZ: 7060 case ISD::CTTZ_ZERO_UNDEF: return LowerCTTZ(Op.getNode(), DAG, Subtarget); 7061 case ISD::CTPOP: return LowerCTPOP(Op.getNode(), DAG, Subtarget); 7062 case ISD::SETCC: return LowerVSETCC(Op, DAG); 7063 case ISD::SETCCE: return LowerSETCCE(Op, DAG); 7064 case ISD::ConstantFP: return LowerConstantFP(Op, DAG, Subtarget); 7065 case ISD::BUILD_VECTOR: return LowerBUILD_VECTOR(Op, DAG, Subtarget); 7066 case ISD::VECTOR_SHUFFLE: return LowerVECTOR_SHUFFLE(Op, DAG); 7067 case ISD::INSERT_VECTOR_ELT: return LowerINSERT_VECTOR_ELT(Op, DAG); 7068 case ISD::EXTRACT_VECTOR_ELT: return LowerEXTRACT_VECTOR_ELT(Op, DAG); 7069 case ISD::CONCAT_VECTORS: return LowerCONCAT_VECTORS(Op, DAG); 7070 case ISD::FLT_ROUNDS_: return LowerFLT_ROUNDS_(Op, DAG); 7071 case ISD::MUL: return LowerMUL(Op, DAG); 7072 case ISD::SDIV: 7073 if (Subtarget->isTargetWindows()) 7074 return LowerDIV_Windows(Op, DAG, /* Signed */ true); 7075 return LowerSDIV(Op, DAG); 7076 case ISD::UDIV: 7077 if (Subtarget->isTargetWindows()) 7078 return LowerDIV_Windows(Op, DAG, /* Signed */ false); 7079 return LowerUDIV(Op, DAG); 7080 case ISD::ADDC: 7081 case ISD::ADDE: 7082 case ISD::SUBC: 7083 case ISD::SUBE: return LowerADDC_ADDE_SUBC_SUBE(Op, DAG); 7084 case ISD::SADDO: 7085 case ISD::UADDO: 7086 case ISD::SSUBO: 7087 case ISD::USUBO: 7088 return LowerXALUO(Op, DAG); 7089 case ISD::ATOMIC_LOAD: 7090 case ISD::ATOMIC_STORE: return LowerAtomicLoadStore(Op, DAG); 7091 case ISD::FSINCOS: return LowerFSINCOS(Op, DAG); 7092 case ISD::SDIVREM: 7093 case ISD::UDIVREM: return LowerDivRem(Op, DAG); 7094 case ISD::DYNAMIC_STACKALLOC: 7095 if (Subtarget->getTargetTriple().isWindowsItaniumEnvironment()) 7096 return LowerDYNAMIC_STACKALLOC(Op, DAG); 7097 llvm_unreachable("Don't know how to custom lower this!"); 7098 case ISD::FP_ROUND: return LowerFP_ROUND(Op, DAG); 7099 case ISD::FP_EXTEND: return LowerFP_EXTEND(Op, DAG); 7100 case ARMISD::WIN__DBZCHK: return SDValue(); 7101 } 7102 } 7103 7104 /// ReplaceNodeResults - Replace the results of node with an illegal result 7105 /// type with new values built out of custom code. 7106 void ARMTargetLowering::ReplaceNodeResults(SDNode *N, 7107 SmallVectorImpl<SDValue> &Results, 7108 SelectionDAG &DAG) const { 7109 SDValue Res; 7110 switch (N->getOpcode()) { 7111 default: 7112 llvm_unreachable("Don't know how to custom expand this!"); 7113 case ISD::READ_REGISTER: 7114 ExpandREAD_REGISTER(N, Results, DAG); 7115 break; 7116 case ISD::BITCAST: 7117 Res = ExpandBITCAST(N, DAG); 7118 break; 7119 case ISD::SRL: 7120 case ISD::SRA: 7121 Res = Expand64BitShift(N, DAG, Subtarget); 7122 break; 7123 case ISD::SREM: 7124 case ISD::UREM: 7125 Res = LowerREM(N, DAG); 7126 break; 7127 case ISD::SDIVREM: 7128 case ISD::UDIVREM: 7129 Res = LowerDivRem(SDValue(N, 0), DAG); 7130 assert(Res.getNumOperands() == 2 && "DivRem needs two values"); 7131 Results.push_back(Res.getValue(0)); 7132 Results.push_back(Res.getValue(1)); 7133 return; 7134 case ISD::READCYCLECOUNTER: 7135 ReplaceREADCYCLECOUNTER(N, Results, DAG, Subtarget); 7136 return; 7137 case ISD::UDIV: 7138 case ISD::SDIV: 7139 assert(Subtarget->isTargetWindows() && "can only expand DIV on Windows"); 7140 return ExpandDIV_Windows(SDValue(N, 0), DAG, N->getOpcode() == ISD::SDIV, 7141 Results); 7142 case ISD::ATOMIC_CMP_SWAP: 7143 ReplaceCMP_SWAP_64Results(N, Results, DAG); 7144 return; 7145 } 7146 if (Res.getNode()) 7147 Results.push_back(Res); 7148 } 7149 7150 //===----------------------------------------------------------------------===// 7151 // ARM Scheduler Hooks 7152 //===----------------------------------------------------------------------===// 7153 7154 /// SetupEntryBlockForSjLj - Insert code into the entry block that creates and 7155 /// registers the function context. 7156 void ARMTargetLowering:: 7157 SetupEntryBlockForSjLj(MachineInstr *MI, MachineBasicBlock *MBB, 7158 MachineBasicBlock *DispatchBB, int FI) const { 7159 const TargetInstrInfo *TII = Subtarget->getInstrInfo(); 7160 DebugLoc dl = MI->getDebugLoc(); 7161 MachineFunction *MF = MBB->getParent(); 7162 MachineRegisterInfo *MRI = &MF->getRegInfo(); 7163 MachineConstantPool *MCP = MF->getConstantPool(); 7164 ARMFunctionInfo *AFI = MF->getInfo<ARMFunctionInfo>(); 7165 const Function *F = MF->getFunction(); 7166 7167 bool isThumb = Subtarget->isThumb(); 7168 bool isThumb2 = Subtarget->isThumb2(); 7169 7170 unsigned PCLabelId = AFI->createPICLabelUId(); 7171 unsigned PCAdj = (isThumb || isThumb2) ? 4 : 8; 7172 ARMConstantPoolValue *CPV = 7173 ARMConstantPoolMBB::Create(F->getContext(), DispatchBB, PCLabelId, PCAdj); 7174 unsigned CPI = MCP->getConstantPoolIndex(CPV, 4); 7175 7176 const TargetRegisterClass *TRC = isThumb ? &ARM::tGPRRegClass 7177 : &ARM::GPRRegClass; 7178 7179 // Grab constant pool and fixed stack memory operands. 7180 MachineMemOperand *CPMMO = 7181 MF->getMachineMemOperand(MachinePointerInfo::getConstantPool(*MF), 7182 MachineMemOperand::MOLoad, 4, 4); 7183 7184 MachineMemOperand *FIMMOSt = 7185 MF->getMachineMemOperand(MachinePointerInfo::getFixedStack(*MF, FI), 7186 MachineMemOperand::MOStore, 4, 4); 7187 7188 // Load the address of the dispatch MBB into the jump buffer. 7189 if (isThumb2) { 7190 // Incoming value: jbuf 7191 // ldr.n r5, LCPI1_1 7192 // orr r5, r5, #1 7193 // add r5, pc 7194 // str r5, [$jbuf, #+4] ; &jbuf[1] 7195 unsigned NewVReg1 = MRI->createVirtualRegister(TRC); 7196 AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::t2LDRpci), NewVReg1) 7197 .addConstantPoolIndex(CPI) 7198 .addMemOperand(CPMMO)); 7199 // Set the low bit because of thumb mode. 7200 unsigned NewVReg2 = MRI->createVirtualRegister(TRC); 7201 AddDefaultCC( 7202 AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::t2ORRri), NewVReg2) 7203 .addReg(NewVReg1, RegState::Kill) 7204 .addImm(0x01))); 7205 unsigned NewVReg3 = MRI->createVirtualRegister(TRC); 7206 BuildMI(*MBB, MI, dl, TII->get(ARM::tPICADD), NewVReg3) 7207 .addReg(NewVReg2, RegState::Kill) 7208 .addImm(PCLabelId); 7209 AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::t2STRi12)) 7210 .addReg(NewVReg3, RegState::Kill) 7211 .addFrameIndex(FI) 7212 .addImm(36) // &jbuf[1] :: pc 7213 .addMemOperand(FIMMOSt)); 7214 } else if (isThumb) { 7215 // Incoming value: jbuf 7216 // ldr.n r1, LCPI1_4 7217 // add r1, pc 7218 // mov r2, #1 7219 // orrs r1, r2 7220 // add r2, $jbuf, #+4 ; &jbuf[1] 7221 // str r1, [r2] 7222 unsigned NewVReg1 = MRI->createVirtualRegister(TRC); 7223 AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::tLDRpci), NewVReg1) 7224 .addConstantPoolIndex(CPI) 7225 .addMemOperand(CPMMO)); 7226 unsigned NewVReg2 = MRI->createVirtualRegister(TRC); 7227 BuildMI(*MBB, MI, dl, TII->get(ARM::tPICADD), NewVReg2) 7228 .addReg(NewVReg1, RegState::Kill) 7229 .addImm(PCLabelId); 7230 // Set the low bit because of thumb mode. 7231 unsigned NewVReg3 = MRI->createVirtualRegister(TRC); 7232 AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::tMOVi8), NewVReg3) 7233 .addReg(ARM::CPSR, RegState::Define) 7234 .addImm(1)); 7235 unsigned NewVReg4 = MRI->createVirtualRegister(TRC); 7236 AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::tORR), NewVReg4) 7237 .addReg(ARM::CPSR, RegState::Define) 7238 .addReg(NewVReg2, RegState::Kill) 7239 .addReg(NewVReg3, RegState::Kill)); 7240 unsigned NewVReg5 = MRI->createVirtualRegister(TRC); 7241 BuildMI(*MBB, MI, dl, TII->get(ARM::tADDframe), NewVReg5) 7242 .addFrameIndex(FI) 7243 .addImm(36); // &jbuf[1] :: pc 7244 AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::tSTRi)) 7245 .addReg(NewVReg4, RegState::Kill) 7246 .addReg(NewVReg5, RegState::Kill) 7247 .addImm(0) 7248 .addMemOperand(FIMMOSt)); 7249 } else { 7250 // Incoming value: jbuf 7251 // ldr r1, LCPI1_1 7252 // add r1, pc, r1 7253 // str r1, [$jbuf, #+4] ; &jbuf[1] 7254 unsigned NewVReg1 = MRI->createVirtualRegister(TRC); 7255 AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::LDRi12), NewVReg1) 7256 .addConstantPoolIndex(CPI) 7257 .addImm(0) 7258 .addMemOperand(CPMMO)); 7259 unsigned NewVReg2 = MRI->createVirtualRegister(TRC); 7260 AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::PICADD), NewVReg2) 7261 .addReg(NewVReg1, RegState::Kill) 7262 .addImm(PCLabelId)); 7263 AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::STRi12)) 7264 .addReg(NewVReg2, RegState::Kill) 7265 .addFrameIndex(FI) 7266 .addImm(36) // &jbuf[1] :: pc 7267 .addMemOperand(FIMMOSt)); 7268 } 7269 } 7270 7271 void ARMTargetLowering::EmitSjLjDispatchBlock(MachineInstr *MI, 7272 MachineBasicBlock *MBB) const { 7273 const TargetInstrInfo *TII = Subtarget->getInstrInfo(); 7274 DebugLoc dl = MI->getDebugLoc(); 7275 MachineFunction *MF = MBB->getParent(); 7276 MachineRegisterInfo *MRI = &MF->getRegInfo(); 7277 MachineFrameInfo *MFI = MF->getFrameInfo(); 7278 int FI = MFI->getFunctionContextIndex(); 7279 7280 const TargetRegisterClass *TRC = Subtarget->isThumb() ? &ARM::tGPRRegClass 7281 : &ARM::GPRnopcRegClass; 7282 7283 // Get a mapping of the call site numbers to all of the landing pads they're 7284 // associated with. 7285 DenseMap<unsigned, SmallVector<MachineBasicBlock*, 2> > CallSiteNumToLPad; 7286 unsigned MaxCSNum = 0; 7287 MachineModuleInfo &MMI = MF->getMMI(); 7288 for (MachineFunction::iterator BB = MF->begin(), E = MF->end(); BB != E; 7289 ++BB) { 7290 if (!BB->isEHPad()) continue; 7291 7292 // FIXME: We should assert that the EH_LABEL is the first MI in the landing 7293 // pad. 7294 for (MachineBasicBlock::iterator 7295 II = BB->begin(), IE = BB->end(); II != IE; ++II) { 7296 if (!II->isEHLabel()) continue; 7297 7298 MCSymbol *Sym = II->getOperand(0).getMCSymbol(); 7299 if (!MMI.hasCallSiteLandingPad(Sym)) continue; 7300 7301 SmallVectorImpl<unsigned> &CallSiteIdxs = MMI.getCallSiteLandingPad(Sym); 7302 for (SmallVectorImpl<unsigned>::iterator 7303 CSI = CallSiteIdxs.begin(), CSE = CallSiteIdxs.end(); 7304 CSI != CSE; ++CSI) { 7305 CallSiteNumToLPad[*CSI].push_back(&*BB); 7306 MaxCSNum = std::max(MaxCSNum, *CSI); 7307 } 7308 break; 7309 } 7310 } 7311 7312 // Get an ordered list of the machine basic blocks for the jump table. 7313 std::vector<MachineBasicBlock*> LPadList; 7314 SmallPtrSet<MachineBasicBlock*, 32> InvokeBBs; 7315 LPadList.reserve(CallSiteNumToLPad.size()); 7316 for (unsigned I = 1; I <= MaxCSNum; ++I) { 7317 SmallVectorImpl<MachineBasicBlock*> &MBBList = CallSiteNumToLPad[I]; 7318 for (SmallVectorImpl<MachineBasicBlock*>::iterator 7319 II = MBBList.begin(), IE = MBBList.end(); II != IE; ++II) { 7320 LPadList.push_back(*II); 7321 InvokeBBs.insert((*II)->pred_begin(), (*II)->pred_end()); 7322 } 7323 } 7324 7325 assert(!LPadList.empty() && 7326 "No landing pad destinations for the dispatch jump table!"); 7327 7328 // Create the jump table and associated information. 7329 MachineJumpTableInfo *JTI = 7330 MF->getOrCreateJumpTableInfo(MachineJumpTableInfo::EK_Inline); 7331 unsigned MJTI = JTI->createJumpTableIndex(LPadList); 7332 Reloc::Model RelocM = getTargetMachine().getRelocationModel(); 7333 7334 // Create the MBBs for the dispatch code. 7335 7336 // Shove the dispatch's address into the return slot in the function context. 7337 MachineBasicBlock *DispatchBB = MF->CreateMachineBasicBlock(); 7338 DispatchBB->setIsEHPad(); 7339 7340 MachineBasicBlock *TrapBB = MF->CreateMachineBasicBlock(); 7341 unsigned trap_opcode; 7342 if (Subtarget->isThumb()) 7343 trap_opcode = ARM::tTRAP; 7344 else 7345 trap_opcode = Subtarget->useNaClTrap() ? ARM::TRAPNaCl : ARM::TRAP; 7346 7347 BuildMI(TrapBB, dl, TII->get(trap_opcode)); 7348 DispatchBB->addSuccessor(TrapBB); 7349 7350 MachineBasicBlock *DispContBB = MF->CreateMachineBasicBlock(); 7351 DispatchBB->addSuccessor(DispContBB); 7352 7353 // Insert and MBBs. 7354 MF->insert(MF->end(), DispatchBB); 7355 MF->insert(MF->end(), DispContBB); 7356 MF->insert(MF->end(), TrapBB); 7357 7358 // Insert code into the entry block that creates and registers the function 7359 // context. 7360 SetupEntryBlockForSjLj(MI, MBB, DispatchBB, FI); 7361 7362 MachineMemOperand *FIMMOLd = MF->getMachineMemOperand( 7363 MachinePointerInfo::getFixedStack(*MF, FI), 7364 MachineMemOperand::MOLoad | MachineMemOperand::MOVolatile, 4, 4); 7365 7366 MachineInstrBuilder MIB; 7367 MIB = BuildMI(DispatchBB, dl, TII->get(ARM::Int_eh_sjlj_dispatchsetup)); 7368 7369 const ARMBaseInstrInfo *AII = static_cast<const ARMBaseInstrInfo*>(TII); 7370 const ARMBaseRegisterInfo &RI = AII->getRegisterInfo(); 7371 7372 // Add a register mask with no preserved registers. This results in all 7373 // registers being marked as clobbered. 7374 MIB.addRegMask(RI.getNoPreservedMask()); 7375 7376 unsigned NumLPads = LPadList.size(); 7377 if (Subtarget->isThumb2()) { 7378 unsigned NewVReg1 = MRI->createVirtualRegister(TRC); 7379 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::t2LDRi12), NewVReg1) 7380 .addFrameIndex(FI) 7381 .addImm(4) 7382 .addMemOperand(FIMMOLd)); 7383 7384 if (NumLPads < 256) { 7385 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::t2CMPri)) 7386 .addReg(NewVReg1) 7387 .addImm(LPadList.size())); 7388 } else { 7389 unsigned VReg1 = MRI->createVirtualRegister(TRC); 7390 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::t2MOVi16), VReg1) 7391 .addImm(NumLPads & 0xFFFF)); 7392 7393 unsigned VReg2 = VReg1; 7394 if ((NumLPads & 0xFFFF0000) != 0) { 7395 VReg2 = MRI->createVirtualRegister(TRC); 7396 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::t2MOVTi16), VReg2) 7397 .addReg(VReg1) 7398 .addImm(NumLPads >> 16)); 7399 } 7400 7401 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::t2CMPrr)) 7402 .addReg(NewVReg1) 7403 .addReg(VReg2)); 7404 } 7405 7406 BuildMI(DispatchBB, dl, TII->get(ARM::t2Bcc)) 7407 .addMBB(TrapBB) 7408 .addImm(ARMCC::HI) 7409 .addReg(ARM::CPSR); 7410 7411 unsigned NewVReg3 = MRI->createVirtualRegister(TRC); 7412 AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::t2LEApcrelJT),NewVReg3) 7413 .addJumpTableIndex(MJTI)); 7414 7415 unsigned NewVReg4 = MRI->createVirtualRegister(TRC); 7416 AddDefaultCC( 7417 AddDefaultPred( 7418 BuildMI(DispContBB, dl, TII->get(ARM::t2ADDrs), NewVReg4) 7419 .addReg(NewVReg3, RegState::Kill) 7420 .addReg(NewVReg1) 7421 .addImm(ARM_AM::getSORegOpc(ARM_AM::lsl, 2)))); 7422 7423 BuildMI(DispContBB, dl, TII->get(ARM::t2BR_JT)) 7424 .addReg(NewVReg4, RegState::Kill) 7425 .addReg(NewVReg1) 7426 .addJumpTableIndex(MJTI); 7427 } else if (Subtarget->isThumb()) { 7428 unsigned NewVReg1 = MRI->createVirtualRegister(TRC); 7429 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::tLDRspi), NewVReg1) 7430 .addFrameIndex(FI) 7431 .addImm(1) 7432 .addMemOperand(FIMMOLd)); 7433 7434 if (NumLPads < 256) { 7435 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::tCMPi8)) 7436 .addReg(NewVReg1) 7437 .addImm(NumLPads)); 7438 } else { 7439 MachineConstantPool *ConstantPool = MF->getConstantPool(); 7440 Type *Int32Ty = Type::getInt32Ty(MF->getFunction()->getContext()); 7441 const Constant *C = ConstantInt::get(Int32Ty, NumLPads); 7442 7443 // MachineConstantPool wants an explicit alignment. 7444 unsigned Align = MF->getDataLayout().getPrefTypeAlignment(Int32Ty); 7445 if (Align == 0) 7446 Align = MF->getDataLayout().getTypeAllocSize(C->getType()); 7447 unsigned Idx = ConstantPool->getConstantPoolIndex(C, Align); 7448 7449 unsigned VReg1 = MRI->createVirtualRegister(TRC); 7450 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::tLDRpci)) 7451 .addReg(VReg1, RegState::Define) 7452 .addConstantPoolIndex(Idx)); 7453 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::tCMPr)) 7454 .addReg(NewVReg1) 7455 .addReg(VReg1)); 7456 } 7457 7458 BuildMI(DispatchBB, dl, TII->get(ARM::tBcc)) 7459 .addMBB(TrapBB) 7460 .addImm(ARMCC::HI) 7461 .addReg(ARM::CPSR); 7462 7463 unsigned NewVReg2 = MRI->createVirtualRegister(TRC); 7464 AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::tLSLri), NewVReg2) 7465 .addReg(ARM::CPSR, RegState::Define) 7466 .addReg(NewVReg1) 7467 .addImm(2)); 7468 7469 unsigned NewVReg3 = MRI->createVirtualRegister(TRC); 7470 AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::tLEApcrelJT), NewVReg3) 7471 .addJumpTableIndex(MJTI)); 7472 7473 unsigned NewVReg4 = MRI->createVirtualRegister(TRC); 7474 AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::tADDrr), NewVReg4) 7475 .addReg(ARM::CPSR, RegState::Define) 7476 .addReg(NewVReg2, RegState::Kill) 7477 .addReg(NewVReg3)); 7478 7479 MachineMemOperand *JTMMOLd = MF->getMachineMemOperand( 7480 MachinePointerInfo::getJumpTable(*MF), MachineMemOperand::MOLoad, 4, 4); 7481 7482 unsigned NewVReg5 = MRI->createVirtualRegister(TRC); 7483 AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::tLDRi), NewVReg5) 7484 .addReg(NewVReg4, RegState::Kill) 7485 .addImm(0) 7486 .addMemOperand(JTMMOLd)); 7487 7488 unsigned NewVReg6 = NewVReg5; 7489 if (RelocM == Reloc::PIC_) { 7490 NewVReg6 = MRI->createVirtualRegister(TRC); 7491 AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::tADDrr), NewVReg6) 7492 .addReg(ARM::CPSR, RegState::Define) 7493 .addReg(NewVReg5, RegState::Kill) 7494 .addReg(NewVReg3)); 7495 } 7496 7497 BuildMI(DispContBB, dl, TII->get(ARM::tBR_JTr)) 7498 .addReg(NewVReg6, RegState::Kill) 7499 .addJumpTableIndex(MJTI); 7500 } else { 7501 unsigned NewVReg1 = MRI->createVirtualRegister(TRC); 7502 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::LDRi12), NewVReg1) 7503 .addFrameIndex(FI) 7504 .addImm(4) 7505 .addMemOperand(FIMMOLd)); 7506 7507 if (NumLPads < 256) { 7508 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::CMPri)) 7509 .addReg(NewVReg1) 7510 .addImm(NumLPads)); 7511 } else if (Subtarget->hasV6T2Ops() && isUInt<16>(NumLPads)) { 7512 unsigned VReg1 = MRI->createVirtualRegister(TRC); 7513 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::MOVi16), VReg1) 7514 .addImm(NumLPads & 0xFFFF)); 7515 7516 unsigned VReg2 = VReg1; 7517 if ((NumLPads & 0xFFFF0000) != 0) { 7518 VReg2 = MRI->createVirtualRegister(TRC); 7519 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::MOVTi16), VReg2) 7520 .addReg(VReg1) 7521 .addImm(NumLPads >> 16)); 7522 } 7523 7524 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::CMPrr)) 7525 .addReg(NewVReg1) 7526 .addReg(VReg2)); 7527 } else { 7528 MachineConstantPool *ConstantPool = MF->getConstantPool(); 7529 Type *Int32Ty = Type::getInt32Ty(MF->getFunction()->getContext()); 7530 const Constant *C = ConstantInt::get(Int32Ty, NumLPads); 7531 7532 // MachineConstantPool wants an explicit alignment. 7533 unsigned Align = MF->getDataLayout().getPrefTypeAlignment(Int32Ty); 7534 if (Align == 0) 7535 Align = MF->getDataLayout().getTypeAllocSize(C->getType()); 7536 unsigned Idx = ConstantPool->getConstantPoolIndex(C, Align); 7537 7538 unsigned VReg1 = MRI->createVirtualRegister(TRC); 7539 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::LDRcp)) 7540 .addReg(VReg1, RegState::Define) 7541 .addConstantPoolIndex(Idx) 7542 .addImm(0)); 7543 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::CMPrr)) 7544 .addReg(NewVReg1) 7545 .addReg(VReg1, RegState::Kill)); 7546 } 7547 7548 BuildMI(DispatchBB, dl, TII->get(ARM::Bcc)) 7549 .addMBB(TrapBB) 7550 .addImm(ARMCC::HI) 7551 .addReg(ARM::CPSR); 7552 7553 unsigned NewVReg3 = MRI->createVirtualRegister(TRC); 7554 AddDefaultCC( 7555 AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::MOVsi), NewVReg3) 7556 .addReg(NewVReg1) 7557 .addImm(ARM_AM::getSORegOpc(ARM_AM::lsl, 2)))); 7558 unsigned NewVReg4 = MRI->createVirtualRegister(TRC); 7559 AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::LEApcrelJT), NewVReg4) 7560 .addJumpTableIndex(MJTI)); 7561 7562 MachineMemOperand *JTMMOLd = MF->getMachineMemOperand( 7563 MachinePointerInfo::getJumpTable(*MF), MachineMemOperand::MOLoad, 4, 4); 7564 unsigned NewVReg5 = MRI->createVirtualRegister(TRC); 7565 AddDefaultPred( 7566 BuildMI(DispContBB, dl, TII->get(ARM::LDRrs), NewVReg5) 7567 .addReg(NewVReg3, RegState::Kill) 7568 .addReg(NewVReg4) 7569 .addImm(0) 7570 .addMemOperand(JTMMOLd)); 7571 7572 if (RelocM == Reloc::PIC_) { 7573 BuildMI(DispContBB, dl, TII->get(ARM::BR_JTadd)) 7574 .addReg(NewVReg5, RegState::Kill) 7575 .addReg(NewVReg4) 7576 .addJumpTableIndex(MJTI); 7577 } else { 7578 BuildMI(DispContBB, dl, TII->get(ARM::BR_JTr)) 7579 .addReg(NewVReg5, RegState::Kill) 7580 .addJumpTableIndex(MJTI); 7581 } 7582 } 7583 7584 // Add the jump table entries as successors to the MBB. 7585 SmallPtrSet<MachineBasicBlock*, 8> SeenMBBs; 7586 for (std::vector<MachineBasicBlock*>::iterator 7587 I = LPadList.begin(), E = LPadList.end(); I != E; ++I) { 7588 MachineBasicBlock *CurMBB = *I; 7589 if (SeenMBBs.insert(CurMBB).second) 7590 DispContBB->addSuccessor(CurMBB); 7591 } 7592 7593 // N.B. the order the invoke BBs are processed in doesn't matter here. 7594 const MCPhysReg *SavedRegs = RI.getCalleeSavedRegs(MF); 7595 SmallVector<MachineBasicBlock*, 64> MBBLPads; 7596 for (MachineBasicBlock *BB : InvokeBBs) { 7597 7598 // Remove the landing pad successor from the invoke block and replace it 7599 // with the new dispatch block. 7600 SmallVector<MachineBasicBlock*, 4> Successors(BB->succ_begin(), 7601 BB->succ_end()); 7602 while (!Successors.empty()) { 7603 MachineBasicBlock *SMBB = Successors.pop_back_val(); 7604 if (SMBB->isEHPad()) { 7605 BB->removeSuccessor(SMBB); 7606 MBBLPads.push_back(SMBB); 7607 } 7608 } 7609 7610 BB->addSuccessor(DispatchBB, BranchProbability::getZero()); 7611 BB->normalizeSuccProbs(); 7612 7613 // Find the invoke call and mark all of the callee-saved registers as 7614 // 'implicit defined' so that they're spilled. This prevents code from 7615 // moving instructions to before the EH block, where they will never be 7616 // executed. 7617 for (MachineBasicBlock::reverse_iterator 7618 II = BB->rbegin(), IE = BB->rend(); II != IE; ++II) { 7619 if (!II->isCall()) continue; 7620 7621 DenseMap<unsigned, bool> DefRegs; 7622 for (MachineInstr::mop_iterator 7623 OI = II->operands_begin(), OE = II->operands_end(); 7624 OI != OE; ++OI) { 7625 if (!OI->isReg()) continue; 7626 DefRegs[OI->getReg()] = true; 7627 } 7628 7629 MachineInstrBuilder MIB(*MF, &*II); 7630 7631 for (unsigned i = 0; SavedRegs[i] != 0; ++i) { 7632 unsigned Reg = SavedRegs[i]; 7633 if (Subtarget->isThumb2() && 7634 !ARM::tGPRRegClass.contains(Reg) && 7635 !ARM::hGPRRegClass.contains(Reg)) 7636 continue; 7637 if (Subtarget->isThumb1Only() && !ARM::tGPRRegClass.contains(Reg)) 7638 continue; 7639 if (!Subtarget->isThumb() && !ARM::GPRRegClass.contains(Reg)) 7640 continue; 7641 if (!DefRegs[Reg]) 7642 MIB.addReg(Reg, RegState::ImplicitDefine | RegState::Dead); 7643 } 7644 7645 break; 7646 } 7647 } 7648 7649 // Mark all former landing pads as non-landing pads. The dispatch is the only 7650 // landing pad now. 7651 for (SmallVectorImpl<MachineBasicBlock*>::iterator 7652 I = MBBLPads.begin(), E = MBBLPads.end(); I != E; ++I) 7653 (*I)->setIsEHPad(false); 7654 7655 // The instruction is gone now. 7656 MI->eraseFromParent(); 7657 } 7658 7659 static 7660 MachineBasicBlock *OtherSucc(MachineBasicBlock *MBB, MachineBasicBlock *Succ) { 7661 for (MachineBasicBlock::succ_iterator I = MBB->succ_begin(), 7662 E = MBB->succ_end(); I != E; ++I) 7663 if (*I != Succ) 7664 return *I; 7665 llvm_unreachable("Expecting a BB with two successors!"); 7666 } 7667 7668 /// Return the load opcode for a given load size. If load size >= 8, 7669 /// neon opcode will be returned. 7670 static unsigned getLdOpcode(unsigned LdSize, bool IsThumb1, bool IsThumb2) { 7671 if (LdSize >= 8) 7672 return LdSize == 16 ? ARM::VLD1q32wb_fixed 7673 : LdSize == 8 ? ARM::VLD1d32wb_fixed : 0; 7674 if (IsThumb1) 7675 return LdSize == 4 ? ARM::tLDRi 7676 : LdSize == 2 ? ARM::tLDRHi 7677 : LdSize == 1 ? ARM::tLDRBi : 0; 7678 if (IsThumb2) 7679 return LdSize == 4 ? ARM::t2LDR_POST 7680 : LdSize == 2 ? ARM::t2LDRH_POST 7681 : LdSize == 1 ? ARM::t2LDRB_POST : 0; 7682 return LdSize == 4 ? ARM::LDR_POST_IMM 7683 : LdSize == 2 ? ARM::LDRH_POST 7684 : LdSize == 1 ? ARM::LDRB_POST_IMM : 0; 7685 } 7686 7687 /// Return the store opcode for a given store size. If store size >= 8, 7688 /// neon opcode will be returned. 7689 static unsigned getStOpcode(unsigned StSize, bool IsThumb1, bool IsThumb2) { 7690 if (StSize >= 8) 7691 return StSize == 16 ? ARM::VST1q32wb_fixed 7692 : StSize == 8 ? ARM::VST1d32wb_fixed : 0; 7693 if (IsThumb1) 7694 return StSize == 4 ? ARM::tSTRi 7695 : StSize == 2 ? ARM::tSTRHi 7696 : StSize == 1 ? ARM::tSTRBi : 0; 7697 if (IsThumb2) 7698 return StSize == 4 ? ARM::t2STR_POST 7699 : StSize == 2 ? ARM::t2STRH_POST 7700 : StSize == 1 ? ARM::t2STRB_POST : 0; 7701 return StSize == 4 ? ARM::STR_POST_IMM 7702 : StSize == 2 ? ARM::STRH_POST 7703 : StSize == 1 ? ARM::STRB_POST_IMM : 0; 7704 } 7705 7706 /// Emit a post-increment load operation with given size. The instructions 7707 /// will be added to BB at Pos. 7708 static void emitPostLd(MachineBasicBlock *BB, MachineInstr *Pos, 7709 const TargetInstrInfo *TII, DebugLoc dl, 7710 unsigned LdSize, unsigned Data, unsigned AddrIn, 7711 unsigned AddrOut, bool IsThumb1, bool IsThumb2) { 7712 unsigned LdOpc = getLdOpcode(LdSize, IsThumb1, IsThumb2); 7713 assert(LdOpc != 0 && "Should have a load opcode"); 7714 if (LdSize >= 8) { 7715 AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(LdOpc), Data) 7716 .addReg(AddrOut, RegState::Define).addReg(AddrIn) 7717 .addImm(0)); 7718 } else if (IsThumb1) { 7719 // load + update AddrIn 7720 AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(LdOpc), Data) 7721 .addReg(AddrIn).addImm(0)); 7722 MachineInstrBuilder MIB = 7723 BuildMI(*BB, Pos, dl, TII->get(ARM::tADDi8), AddrOut); 7724 MIB = AddDefaultT1CC(MIB); 7725 MIB.addReg(AddrIn).addImm(LdSize); 7726 AddDefaultPred(MIB); 7727 } else if (IsThumb2) { 7728 AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(LdOpc), Data) 7729 .addReg(AddrOut, RegState::Define).addReg(AddrIn) 7730 .addImm(LdSize)); 7731 } else { // arm 7732 AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(LdOpc), Data) 7733 .addReg(AddrOut, RegState::Define).addReg(AddrIn) 7734 .addReg(0).addImm(LdSize)); 7735 } 7736 } 7737 7738 /// Emit a post-increment store operation with given size. The instructions 7739 /// will be added to BB at Pos. 7740 static void emitPostSt(MachineBasicBlock *BB, MachineInstr *Pos, 7741 const TargetInstrInfo *TII, DebugLoc dl, 7742 unsigned StSize, unsigned Data, unsigned AddrIn, 7743 unsigned AddrOut, bool IsThumb1, bool IsThumb2) { 7744 unsigned StOpc = getStOpcode(StSize, IsThumb1, IsThumb2); 7745 assert(StOpc != 0 && "Should have a store opcode"); 7746 if (StSize >= 8) { 7747 AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(StOpc), AddrOut) 7748 .addReg(AddrIn).addImm(0).addReg(Data)); 7749 } else if (IsThumb1) { 7750 // store + update AddrIn 7751 AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(StOpc)).addReg(Data) 7752 .addReg(AddrIn).addImm(0)); 7753 MachineInstrBuilder MIB = 7754 BuildMI(*BB, Pos, dl, TII->get(ARM::tADDi8), AddrOut); 7755 MIB = AddDefaultT1CC(MIB); 7756 MIB.addReg(AddrIn).addImm(StSize); 7757 AddDefaultPred(MIB); 7758 } else if (IsThumb2) { 7759 AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(StOpc), AddrOut) 7760 .addReg(Data).addReg(AddrIn).addImm(StSize)); 7761 } else { // arm 7762 AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(StOpc), AddrOut) 7763 .addReg(Data).addReg(AddrIn).addReg(0) 7764 .addImm(StSize)); 7765 } 7766 } 7767 7768 MachineBasicBlock * 7769 ARMTargetLowering::EmitStructByval(MachineInstr *MI, 7770 MachineBasicBlock *BB) const { 7771 // This pseudo instruction has 3 operands: dst, src, size 7772 // We expand it to a loop if size > Subtarget->getMaxInlineSizeThreshold(). 7773 // Otherwise, we will generate unrolled scalar copies. 7774 const TargetInstrInfo *TII = Subtarget->getInstrInfo(); 7775 const BasicBlock *LLVM_BB = BB->getBasicBlock(); 7776 MachineFunction::iterator It = ++BB->getIterator(); 7777 7778 unsigned dest = MI->getOperand(0).getReg(); 7779 unsigned src = MI->getOperand(1).getReg(); 7780 unsigned SizeVal = MI->getOperand(2).getImm(); 7781 unsigned Align = MI->getOperand(3).getImm(); 7782 DebugLoc dl = MI->getDebugLoc(); 7783 7784 MachineFunction *MF = BB->getParent(); 7785 MachineRegisterInfo &MRI = MF->getRegInfo(); 7786 unsigned UnitSize = 0; 7787 const TargetRegisterClass *TRC = nullptr; 7788 const TargetRegisterClass *VecTRC = nullptr; 7789 7790 bool IsThumb1 = Subtarget->isThumb1Only(); 7791 bool IsThumb2 = Subtarget->isThumb2(); 7792 7793 if (Align & 1) { 7794 UnitSize = 1; 7795 } else if (Align & 2) { 7796 UnitSize = 2; 7797 } else { 7798 // Check whether we can use NEON instructions. 7799 if (!MF->getFunction()->hasFnAttribute(Attribute::NoImplicitFloat) && 7800 Subtarget->hasNEON()) { 7801 if ((Align % 16 == 0) && SizeVal >= 16) 7802 UnitSize = 16; 7803 else if ((Align % 8 == 0) && SizeVal >= 8) 7804 UnitSize = 8; 7805 } 7806 // Can't use NEON instructions. 7807 if (UnitSize == 0) 7808 UnitSize = 4; 7809 } 7810 7811 // Select the correct opcode and register class for unit size load/store 7812 bool IsNeon = UnitSize >= 8; 7813 TRC = (IsThumb1 || IsThumb2) ? &ARM::tGPRRegClass : &ARM::GPRRegClass; 7814 if (IsNeon) 7815 VecTRC = UnitSize == 16 ? &ARM::DPairRegClass 7816 : UnitSize == 8 ? &ARM::DPRRegClass 7817 : nullptr; 7818 7819 unsigned BytesLeft = SizeVal % UnitSize; 7820 unsigned LoopSize = SizeVal - BytesLeft; 7821 7822 if (SizeVal <= Subtarget->getMaxInlineSizeThreshold()) { 7823 // Use LDR and STR to copy. 7824 // [scratch, srcOut] = LDR_POST(srcIn, UnitSize) 7825 // [destOut] = STR_POST(scratch, destIn, UnitSize) 7826 unsigned srcIn = src; 7827 unsigned destIn = dest; 7828 for (unsigned i = 0; i < LoopSize; i+=UnitSize) { 7829 unsigned srcOut = MRI.createVirtualRegister(TRC); 7830 unsigned destOut = MRI.createVirtualRegister(TRC); 7831 unsigned scratch = MRI.createVirtualRegister(IsNeon ? VecTRC : TRC); 7832 emitPostLd(BB, MI, TII, dl, UnitSize, scratch, srcIn, srcOut, 7833 IsThumb1, IsThumb2); 7834 emitPostSt(BB, MI, TII, dl, UnitSize, scratch, destIn, destOut, 7835 IsThumb1, IsThumb2); 7836 srcIn = srcOut; 7837 destIn = destOut; 7838 } 7839 7840 // Handle the leftover bytes with LDRB and STRB. 7841 // [scratch, srcOut] = LDRB_POST(srcIn, 1) 7842 // [destOut] = STRB_POST(scratch, destIn, 1) 7843 for (unsigned i = 0; i < BytesLeft; i++) { 7844 unsigned srcOut = MRI.createVirtualRegister(TRC); 7845 unsigned destOut = MRI.createVirtualRegister(TRC); 7846 unsigned scratch = MRI.createVirtualRegister(TRC); 7847 emitPostLd(BB, MI, TII, dl, 1, scratch, srcIn, srcOut, 7848 IsThumb1, IsThumb2); 7849 emitPostSt(BB, MI, TII, dl, 1, scratch, destIn, destOut, 7850 IsThumb1, IsThumb2); 7851 srcIn = srcOut; 7852 destIn = destOut; 7853 } 7854 MI->eraseFromParent(); // The instruction is gone now. 7855 return BB; 7856 } 7857 7858 // Expand the pseudo op to a loop. 7859 // thisMBB: 7860 // ... 7861 // movw varEnd, # --> with thumb2 7862 // movt varEnd, # 7863 // ldrcp varEnd, idx --> without thumb2 7864 // fallthrough --> loopMBB 7865 // loopMBB: 7866 // PHI varPhi, varEnd, varLoop 7867 // PHI srcPhi, src, srcLoop 7868 // PHI destPhi, dst, destLoop 7869 // [scratch, srcLoop] = LDR_POST(srcPhi, UnitSize) 7870 // [destLoop] = STR_POST(scratch, destPhi, UnitSize) 7871 // subs varLoop, varPhi, #UnitSize 7872 // bne loopMBB 7873 // fallthrough --> exitMBB 7874 // exitMBB: 7875 // epilogue to handle left-over bytes 7876 // [scratch, srcOut] = LDRB_POST(srcLoop, 1) 7877 // [destOut] = STRB_POST(scratch, destLoop, 1) 7878 MachineBasicBlock *loopMBB = MF->CreateMachineBasicBlock(LLVM_BB); 7879 MachineBasicBlock *exitMBB = MF->CreateMachineBasicBlock(LLVM_BB); 7880 MF->insert(It, loopMBB); 7881 MF->insert(It, exitMBB); 7882 7883 // Transfer the remainder of BB and its successor edges to exitMBB. 7884 exitMBB->splice(exitMBB->begin(), BB, 7885 std::next(MachineBasicBlock::iterator(MI)), BB->end()); 7886 exitMBB->transferSuccessorsAndUpdatePHIs(BB); 7887 7888 // Load an immediate to varEnd. 7889 unsigned varEnd = MRI.createVirtualRegister(TRC); 7890 if (Subtarget->useMovt(*MF)) { 7891 unsigned Vtmp = varEnd; 7892 if ((LoopSize & 0xFFFF0000) != 0) 7893 Vtmp = MRI.createVirtualRegister(TRC); 7894 AddDefaultPred(BuildMI(BB, dl, 7895 TII->get(IsThumb2 ? ARM::t2MOVi16 : ARM::MOVi16), 7896 Vtmp).addImm(LoopSize & 0xFFFF)); 7897 7898 if ((LoopSize & 0xFFFF0000) != 0) 7899 AddDefaultPred(BuildMI(BB, dl, 7900 TII->get(IsThumb2 ? ARM::t2MOVTi16 : ARM::MOVTi16), 7901 varEnd) 7902 .addReg(Vtmp) 7903 .addImm(LoopSize >> 16)); 7904 } else { 7905 MachineConstantPool *ConstantPool = MF->getConstantPool(); 7906 Type *Int32Ty = Type::getInt32Ty(MF->getFunction()->getContext()); 7907 const Constant *C = ConstantInt::get(Int32Ty, LoopSize); 7908 7909 // MachineConstantPool wants an explicit alignment. 7910 unsigned Align = MF->getDataLayout().getPrefTypeAlignment(Int32Ty); 7911 if (Align == 0) 7912 Align = MF->getDataLayout().getTypeAllocSize(C->getType()); 7913 unsigned Idx = ConstantPool->getConstantPoolIndex(C, Align); 7914 7915 if (IsThumb1) 7916 AddDefaultPred(BuildMI(*BB, MI, dl, TII->get(ARM::tLDRpci)).addReg( 7917 varEnd, RegState::Define).addConstantPoolIndex(Idx)); 7918 else 7919 AddDefaultPred(BuildMI(*BB, MI, dl, TII->get(ARM::LDRcp)).addReg( 7920 varEnd, RegState::Define).addConstantPoolIndex(Idx).addImm(0)); 7921 } 7922 BB->addSuccessor(loopMBB); 7923 7924 // Generate the loop body: 7925 // varPhi = PHI(varLoop, varEnd) 7926 // srcPhi = PHI(srcLoop, src) 7927 // destPhi = PHI(destLoop, dst) 7928 MachineBasicBlock *entryBB = BB; 7929 BB = loopMBB; 7930 unsigned varLoop = MRI.createVirtualRegister(TRC); 7931 unsigned varPhi = MRI.createVirtualRegister(TRC); 7932 unsigned srcLoop = MRI.createVirtualRegister(TRC); 7933 unsigned srcPhi = MRI.createVirtualRegister(TRC); 7934 unsigned destLoop = MRI.createVirtualRegister(TRC); 7935 unsigned destPhi = MRI.createVirtualRegister(TRC); 7936 7937 BuildMI(*BB, BB->begin(), dl, TII->get(ARM::PHI), varPhi) 7938 .addReg(varLoop).addMBB(loopMBB) 7939 .addReg(varEnd).addMBB(entryBB); 7940 BuildMI(BB, dl, TII->get(ARM::PHI), srcPhi) 7941 .addReg(srcLoop).addMBB(loopMBB) 7942 .addReg(src).addMBB(entryBB); 7943 BuildMI(BB, dl, TII->get(ARM::PHI), destPhi) 7944 .addReg(destLoop).addMBB(loopMBB) 7945 .addReg(dest).addMBB(entryBB); 7946 7947 // [scratch, srcLoop] = LDR_POST(srcPhi, UnitSize) 7948 // [destLoop] = STR_POST(scratch, destPhi, UnitSiz) 7949 unsigned scratch = MRI.createVirtualRegister(IsNeon ? VecTRC : TRC); 7950 emitPostLd(BB, BB->end(), TII, dl, UnitSize, scratch, srcPhi, srcLoop, 7951 IsThumb1, IsThumb2); 7952 emitPostSt(BB, BB->end(), TII, dl, UnitSize, scratch, destPhi, destLoop, 7953 IsThumb1, IsThumb2); 7954 7955 // Decrement loop variable by UnitSize. 7956 if (IsThumb1) { 7957 MachineInstrBuilder MIB = 7958 BuildMI(*BB, BB->end(), dl, TII->get(ARM::tSUBi8), varLoop); 7959 MIB = AddDefaultT1CC(MIB); 7960 MIB.addReg(varPhi).addImm(UnitSize); 7961 AddDefaultPred(MIB); 7962 } else { 7963 MachineInstrBuilder MIB = 7964 BuildMI(*BB, BB->end(), dl, 7965 TII->get(IsThumb2 ? ARM::t2SUBri : ARM::SUBri), varLoop); 7966 AddDefaultCC(AddDefaultPred(MIB.addReg(varPhi).addImm(UnitSize))); 7967 MIB->getOperand(5).setReg(ARM::CPSR); 7968 MIB->getOperand(5).setIsDef(true); 7969 } 7970 BuildMI(*BB, BB->end(), dl, 7971 TII->get(IsThumb1 ? ARM::tBcc : IsThumb2 ? ARM::t2Bcc : ARM::Bcc)) 7972 .addMBB(loopMBB).addImm(ARMCC::NE).addReg(ARM::CPSR); 7973 7974 // loopMBB can loop back to loopMBB or fall through to exitMBB. 7975 BB->addSuccessor(loopMBB); 7976 BB->addSuccessor(exitMBB); 7977 7978 // Add epilogue to handle BytesLeft. 7979 BB = exitMBB; 7980 MachineInstr *StartOfExit = exitMBB->begin(); 7981 7982 // [scratch, srcOut] = LDRB_POST(srcLoop, 1) 7983 // [destOut] = STRB_POST(scratch, destLoop, 1) 7984 unsigned srcIn = srcLoop; 7985 unsigned destIn = destLoop; 7986 for (unsigned i = 0; i < BytesLeft; i++) { 7987 unsigned srcOut = MRI.createVirtualRegister(TRC); 7988 unsigned destOut = MRI.createVirtualRegister(TRC); 7989 unsigned scratch = MRI.createVirtualRegister(TRC); 7990 emitPostLd(BB, StartOfExit, TII, dl, 1, scratch, srcIn, srcOut, 7991 IsThumb1, IsThumb2); 7992 emitPostSt(BB, StartOfExit, TII, dl, 1, scratch, destIn, destOut, 7993 IsThumb1, IsThumb2); 7994 srcIn = srcOut; 7995 destIn = destOut; 7996 } 7997 7998 MI->eraseFromParent(); // The instruction is gone now. 7999 return BB; 8000 } 8001 8002 MachineBasicBlock * 8003 ARMTargetLowering::EmitLowered__chkstk(MachineInstr *MI, 8004 MachineBasicBlock *MBB) const { 8005 const TargetMachine &TM = getTargetMachine(); 8006 const TargetInstrInfo &TII = *Subtarget->getInstrInfo(); 8007 DebugLoc DL = MI->getDebugLoc(); 8008 8009 assert(Subtarget->isTargetWindows() && 8010 "__chkstk is only supported on Windows"); 8011 assert(Subtarget->isThumb2() && "Windows on ARM requires Thumb-2 mode"); 8012 8013 // __chkstk takes the number of words to allocate on the stack in R4, and 8014 // returns the stack adjustment in number of bytes in R4. This will not 8015 // clober any other registers (other than the obvious lr). 8016 // 8017 // Although, technically, IP should be considered a register which may be 8018 // clobbered, the call itself will not touch it. Windows on ARM is a pure 8019 // thumb-2 environment, so there is no interworking required. As a result, we 8020 // do not expect a veneer to be emitted by the linker, clobbering IP. 8021 // 8022 // Each module receives its own copy of __chkstk, so no import thunk is 8023 // required, again, ensuring that IP is not clobbered. 8024 // 8025 // Finally, although some linkers may theoretically provide a trampoline for 8026 // out of range calls (which is quite common due to a 32M range limitation of 8027 // branches for Thumb), we can generate the long-call version via 8028 // -mcmodel=large, alleviating the need for the trampoline which may clobber 8029 // IP. 8030 8031 switch (TM.getCodeModel()) { 8032 case CodeModel::Small: 8033 case CodeModel::Medium: 8034 case CodeModel::Default: 8035 case CodeModel::Kernel: 8036 BuildMI(*MBB, MI, DL, TII.get(ARM::tBL)) 8037 .addImm((unsigned)ARMCC::AL).addReg(0) 8038 .addExternalSymbol("__chkstk") 8039 .addReg(ARM::R4, RegState::Implicit | RegState::Kill) 8040 .addReg(ARM::R4, RegState::Implicit | RegState::Define) 8041 .addReg(ARM::R12, RegState::Implicit | RegState::Define | RegState::Dead); 8042 break; 8043 case CodeModel::Large: 8044 case CodeModel::JITDefault: { 8045 MachineRegisterInfo &MRI = MBB->getParent()->getRegInfo(); 8046 unsigned Reg = MRI.createVirtualRegister(&ARM::rGPRRegClass); 8047 8048 BuildMI(*MBB, MI, DL, TII.get(ARM::t2MOVi32imm), Reg) 8049 .addExternalSymbol("__chkstk"); 8050 BuildMI(*MBB, MI, DL, TII.get(ARM::tBLXr)) 8051 .addImm((unsigned)ARMCC::AL).addReg(0) 8052 .addReg(Reg, RegState::Kill) 8053 .addReg(ARM::R4, RegState::Implicit | RegState::Kill) 8054 .addReg(ARM::R4, RegState::Implicit | RegState::Define) 8055 .addReg(ARM::R12, RegState::Implicit | RegState::Define | RegState::Dead); 8056 break; 8057 } 8058 } 8059 8060 AddDefaultCC(AddDefaultPred(BuildMI(*MBB, MI, DL, TII.get(ARM::t2SUBrr), 8061 ARM::SP) 8062 .addReg(ARM::SP).addReg(ARM::R4))); 8063 8064 MI->eraseFromParent(); 8065 return MBB; 8066 } 8067 8068 MachineBasicBlock * 8069 ARMTargetLowering::EmitLowered__dbzchk(MachineInstr *MI, 8070 MachineBasicBlock *MBB) const { 8071 DebugLoc DL = MI->getDebugLoc(); 8072 MachineFunction *MF = MBB->getParent(); 8073 const TargetInstrInfo *TII = Subtarget->getInstrInfo(); 8074 8075 MachineBasicBlock *ContBB = MF->CreateMachineBasicBlock(); 8076 MF->insert(++MBB->getIterator(), ContBB); 8077 ContBB->splice(ContBB->begin(), MBB, 8078 std::next(MachineBasicBlock::iterator(MI)), MBB->end()); 8079 ContBB->transferSuccessorsAndUpdatePHIs(MBB); 8080 8081 MachineBasicBlock *TrapBB = MF->CreateMachineBasicBlock(); 8082 MF->push_back(TrapBB); 8083 BuildMI(TrapBB, DL, TII->get(ARM::t2UDF)).addImm(249); 8084 MBB->addSuccessor(TrapBB); 8085 8086 BuildMI(*MBB, MI, DL, TII->get(ARM::tCBZ)) 8087 .addReg(MI->getOperand(0).getReg()) 8088 .addMBB(TrapBB); 8089 AddDefaultPred(BuildMI(*MBB, MI, DL, TII->get(ARM::t2B)).addMBB(ContBB)); 8090 MBB->addSuccessor(ContBB); 8091 8092 MI->eraseFromParent(); 8093 return ContBB; 8094 } 8095 8096 MachineBasicBlock * 8097 ARMTargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI, 8098 MachineBasicBlock *BB) const { 8099 const TargetInstrInfo *TII = Subtarget->getInstrInfo(); 8100 DebugLoc dl = MI->getDebugLoc(); 8101 bool isThumb2 = Subtarget->isThumb2(); 8102 switch (MI->getOpcode()) { 8103 default: { 8104 MI->dump(); 8105 llvm_unreachable("Unexpected instr type to insert"); 8106 } 8107 // The Thumb2 pre-indexed stores have the same MI operands, they just 8108 // define them differently in the .td files from the isel patterns, so 8109 // they need pseudos. 8110 case ARM::t2STR_preidx: 8111 MI->setDesc(TII->get(ARM::t2STR_PRE)); 8112 return BB; 8113 case ARM::t2STRB_preidx: 8114 MI->setDesc(TII->get(ARM::t2STRB_PRE)); 8115 return BB; 8116 case ARM::t2STRH_preidx: 8117 MI->setDesc(TII->get(ARM::t2STRH_PRE)); 8118 return BB; 8119 8120 case ARM::STRi_preidx: 8121 case ARM::STRBi_preidx: { 8122 unsigned NewOpc = MI->getOpcode() == ARM::STRi_preidx ? 8123 ARM::STR_PRE_IMM : ARM::STRB_PRE_IMM; 8124 // Decode the offset. 8125 unsigned Offset = MI->getOperand(4).getImm(); 8126 bool isSub = ARM_AM::getAM2Op(Offset) == ARM_AM::sub; 8127 Offset = ARM_AM::getAM2Offset(Offset); 8128 if (isSub) 8129 Offset = -Offset; 8130 8131 MachineMemOperand *MMO = *MI->memoperands_begin(); 8132 BuildMI(*BB, MI, dl, TII->get(NewOpc)) 8133 .addOperand(MI->getOperand(0)) // Rn_wb 8134 .addOperand(MI->getOperand(1)) // Rt 8135 .addOperand(MI->getOperand(2)) // Rn 8136 .addImm(Offset) // offset (skip GPR==zero_reg) 8137 .addOperand(MI->getOperand(5)) // pred 8138 .addOperand(MI->getOperand(6)) 8139 .addMemOperand(MMO); 8140 MI->eraseFromParent(); 8141 return BB; 8142 } 8143 case ARM::STRr_preidx: 8144 case ARM::STRBr_preidx: 8145 case ARM::STRH_preidx: { 8146 unsigned NewOpc; 8147 switch (MI->getOpcode()) { 8148 default: llvm_unreachable("unexpected opcode!"); 8149 case ARM::STRr_preidx: NewOpc = ARM::STR_PRE_REG; break; 8150 case ARM::STRBr_preidx: NewOpc = ARM::STRB_PRE_REG; break; 8151 case ARM::STRH_preidx: NewOpc = ARM::STRH_PRE; break; 8152 } 8153 MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(NewOpc)); 8154 for (unsigned i = 0; i < MI->getNumOperands(); ++i) 8155 MIB.addOperand(MI->getOperand(i)); 8156 MI->eraseFromParent(); 8157 return BB; 8158 } 8159 8160 case ARM::tMOVCCr_pseudo: { 8161 // To "insert" a SELECT_CC instruction, we actually have to insert the 8162 // diamond control-flow pattern. The incoming instruction knows the 8163 // destination vreg to set, the condition code register to branch on, the 8164 // true/false values to select between, and a branch opcode to use. 8165 const BasicBlock *LLVM_BB = BB->getBasicBlock(); 8166 MachineFunction::iterator It = ++BB->getIterator(); 8167 8168 // thisMBB: 8169 // ... 8170 // TrueVal = ... 8171 // cmpTY ccX, r1, r2 8172 // bCC copy1MBB 8173 // fallthrough --> copy0MBB 8174 MachineBasicBlock *thisMBB = BB; 8175 MachineFunction *F = BB->getParent(); 8176 MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB); 8177 MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB); 8178 F->insert(It, copy0MBB); 8179 F->insert(It, sinkMBB); 8180 8181 // Transfer the remainder of BB and its successor edges to sinkMBB. 8182 sinkMBB->splice(sinkMBB->begin(), BB, 8183 std::next(MachineBasicBlock::iterator(MI)), BB->end()); 8184 sinkMBB->transferSuccessorsAndUpdatePHIs(BB); 8185 8186 BB->addSuccessor(copy0MBB); 8187 BB->addSuccessor(sinkMBB); 8188 8189 BuildMI(BB, dl, TII->get(ARM::tBcc)).addMBB(sinkMBB) 8190 .addImm(MI->getOperand(3).getImm()).addReg(MI->getOperand(4).getReg()); 8191 8192 // copy0MBB: 8193 // %FalseValue = ... 8194 // # fallthrough to sinkMBB 8195 BB = copy0MBB; 8196 8197 // Update machine-CFG edges 8198 BB->addSuccessor(sinkMBB); 8199 8200 // sinkMBB: 8201 // %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ] 8202 // ... 8203 BB = sinkMBB; 8204 BuildMI(*BB, BB->begin(), dl, 8205 TII->get(ARM::PHI), MI->getOperand(0).getReg()) 8206 .addReg(MI->getOperand(1).getReg()).addMBB(copy0MBB) 8207 .addReg(MI->getOperand(2).getReg()).addMBB(thisMBB); 8208 8209 MI->eraseFromParent(); // The pseudo instruction is gone now. 8210 return BB; 8211 } 8212 8213 case ARM::BCCi64: 8214 case ARM::BCCZi64: { 8215 // If there is an unconditional branch to the other successor, remove it. 8216 BB->erase(std::next(MachineBasicBlock::iterator(MI)), BB->end()); 8217 8218 // Compare both parts that make up the double comparison separately for 8219 // equality. 8220 bool RHSisZero = MI->getOpcode() == ARM::BCCZi64; 8221 8222 unsigned LHS1 = MI->getOperand(1).getReg(); 8223 unsigned LHS2 = MI->getOperand(2).getReg(); 8224 if (RHSisZero) { 8225 AddDefaultPred(BuildMI(BB, dl, 8226 TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri)) 8227 .addReg(LHS1).addImm(0)); 8228 BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri)) 8229 .addReg(LHS2).addImm(0) 8230 .addImm(ARMCC::EQ).addReg(ARM::CPSR); 8231 } else { 8232 unsigned RHS1 = MI->getOperand(3).getReg(); 8233 unsigned RHS2 = MI->getOperand(4).getReg(); 8234 AddDefaultPred(BuildMI(BB, dl, 8235 TII->get(isThumb2 ? ARM::t2CMPrr : ARM::CMPrr)) 8236 .addReg(LHS1).addReg(RHS1)); 8237 BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPrr : ARM::CMPrr)) 8238 .addReg(LHS2).addReg(RHS2) 8239 .addImm(ARMCC::EQ).addReg(ARM::CPSR); 8240 } 8241 8242 MachineBasicBlock *destMBB = MI->getOperand(RHSisZero ? 3 : 5).getMBB(); 8243 MachineBasicBlock *exitMBB = OtherSucc(BB, destMBB); 8244 if (MI->getOperand(0).getImm() == ARMCC::NE) 8245 std::swap(destMBB, exitMBB); 8246 8247 BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc)) 8248 .addMBB(destMBB).addImm(ARMCC::EQ).addReg(ARM::CPSR); 8249 if (isThumb2) 8250 AddDefaultPred(BuildMI(BB, dl, TII->get(ARM::t2B)).addMBB(exitMBB)); 8251 else 8252 BuildMI(BB, dl, TII->get(ARM::B)) .addMBB(exitMBB); 8253 8254 MI->eraseFromParent(); // The pseudo instruction is gone now. 8255 return BB; 8256 } 8257 8258 case ARM::Int_eh_sjlj_setjmp: 8259 case ARM::Int_eh_sjlj_setjmp_nofp: 8260 case ARM::tInt_eh_sjlj_setjmp: 8261 case ARM::t2Int_eh_sjlj_setjmp: 8262 case ARM::t2Int_eh_sjlj_setjmp_nofp: 8263 return BB; 8264 8265 case ARM::Int_eh_sjlj_setup_dispatch: 8266 EmitSjLjDispatchBlock(MI, BB); 8267 return BB; 8268 8269 case ARM::ABS: 8270 case ARM::t2ABS: { 8271 // To insert an ABS instruction, we have to insert the 8272 // diamond control-flow pattern. The incoming instruction knows the 8273 // source vreg to test against 0, the destination vreg to set, 8274 // the condition code register to branch on, the 8275 // true/false values to select between, and a branch opcode to use. 8276 // It transforms 8277 // V1 = ABS V0 8278 // into 8279 // V2 = MOVS V0 8280 // BCC (branch to SinkBB if V0 >= 0) 8281 // RSBBB: V3 = RSBri V2, 0 (compute ABS if V2 < 0) 8282 // SinkBB: V1 = PHI(V2, V3) 8283 const BasicBlock *LLVM_BB = BB->getBasicBlock(); 8284 MachineFunction::iterator BBI = ++BB->getIterator(); 8285 MachineFunction *Fn = BB->getParent(); 8286 MachineBasicBlock *RSBBB = Fn->CreateMachineBasicBlock(LLVM_BB); 8287 MachineBasicBlock *SinkBB = Fn->CreateMachineBasicBlock(LLVM_BB); 8288 Fn->insert(BBI, RSBBB); 8289 Fn->insert(BBI, SinkBB); 8290 8291 unsigned int ABSSrcReg = MI->getOperand(1).getReg(); 8292 unsigned int ABSDstReg = MI->getOperand(0).getReg(); 8293 bool ABSSrcKIll = MI->getOperand(1).isKill(); 8294 bool isThumb2 = Subtarget->isThumb2(); 8295 MachineRegisterInfo &MRI = Fn->getRegInfo(); 8296 // In Thumb mode S must not be specified if source register is the SP or 8297 // PC and if destination register is the SP, so restrict register class 8298 unsigned NewRsbDstReg = 8299 MRI.createVirtualRegister(isThumb2 ? &ARM::rGPRRegClass : &ARM::GPRRegClass); 8300 8301 // Transfer the remainder of BB and its successor edges to sinkMBB. 8302 SinkBB->splice(SinkBB->begin(), BB, 8303 std::next(MachineBasicBlock::iterator(MI)), BB->end()); 8304 SinkBB->transferSuccessorsAndUpdatePHIs(BB); 8305 8306 BB->addSuccessor(RSBBB); 8307 BB->addSuccessor(SinkBB); 8308 8309 // fall through to SinkMBB 8310 RSBBB->addSuccessor(SinkBB); 8311 8312 // insert a cmp at the end of BB 8313 AddDefaultPred(BuildMI(BB, dl, 8314 TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri)) 8315 .addReg(ABSSrcReg).addImm(0)); 8316 8317 // insert a bcc with opposite CC to ARMCC::MI at the end of BB 8318 BuildMI(BB, dl, 8319 TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc)).addMBB(SinkBB) 8320 .addImm(ARMCC::getOppositeCondition(ARMCC::MI)).addReg(ARM::CPSR); 8321 8322 // insert rsbri in RSBBB 8323 // Note: BCC and rsbri will be converted into predicated rsbmi 8324 // by if-conversion pass 8325 BuildMI(*RSBBB, RSBBB->begin(), dl, 8326 TII->get(isThumb2 ? ARM::t2RSBri : ARM::RSBri), NewRsbDstReg) 8327 .addReg(ABSSrcReg, ABSSrcKIll ? RegState::Kill : 0) 8328 .addImm(0).addImm((unsigned)ARMCC::AL).addReg(0).addReg(0); 8329 8330 // insert PHI in SinkBB, 8331 // reuse ABSDstReg to not change uses of ABS instruction 8332 BuildMI(*SinkBB, SinkBB->begin(), dl, 8333 TII->get(ARM::PHI), ABSDstReg) 8334 .addReg(NewRsbDstReg).addMBB(RSBBB) 8335 .addReg(ABSSrcReg).addMBB(BB); 8336 8337 // remove ABS instruction 8338 MI->eraseFromParent(); 8339 8340 // return last added BB 8341 return SinkBB; 8342 } 8343 case ARM::COPY_STRUCT_BYVAL_I32: 8344 ++NumLoopByVals; 8345 return EmitStructByval(MI, BB); 8346 case ARM::WIN__CHKSTK: 8347 return EmitLowered__chkstk(MI, BB); 8348 case ARM::WIN__DBZCHK: 8349 return EmitLowered__dbzchk(MI, BB); 8350 } 8351 } 8352 8353 /// \brief Attaches vregs to MEMCPY that it will use as scratch registers 8354 /// when it is expanded into LDM/STM. This is done as a post-isel lowering 8355 /// instead of as a custom inserter because we need the use list from the SDNode. 8356 static void attachMEMCPYScratchRegs(const ARMSubtarget *Subtarget, 8357 MachineInstr *MI, const SDNode *Node) { 8358 bool isThumb1 = Subtarget->isThumb1Only(); 8359 8360 DebugLoc DL = MI->getDebugLoc(); 8361 MachineFunction *MF = MI->getParent()->getParent(); 8362 MachineRegisterInfo &MRI = MF->getRegInfo(); 8363 MachineInstrBuilder MIB(*MF, MI); 8364 8365 // If the new dst/src is unused mark it as dead. 8366 if (!Node->hasAnyUseOfValue(0)) { 8367 MI->getOperand(0).setIsDead(true); 8368 } 8369 if (!Node->hasAnyUseOfValue(1)) { 8370 MI->getOperand(1).setIsDead(true); 8371 } 8372 8373 // The MEMCPY both defines and kills the scratch registers. 8374 for (unsigned I = 0; I != MI->getOperand(4).getImm(); ++I) { 8375 unsigned TmpReg = MRI.createVirtualRegister(isThumb1 ? &ARM::tGPRRegClass 8376 : &ARM::GPRRegClass); 8377 MIB.addReg(TmpReg, RegState::Define|RegState::Dead); 8378 } 8379 } 8380 8381 void ARMTargetLowering::AdjustInstrPostInstrSelection(MachineInstr *MI, 8382 SDNode *Node) const { 8383 if (MI->getOpcode() == ARM::MEMCPY) { 8384 attachMEMCPYScratchRegs(Subtarget, MI, Node); 8385 return; 8386 } 8387 8388 const MCInstrDesc *MCID = &MI->getDesc(); 8389 // Adjust potentially 's' setting instructions after isel, i.e. ADC, SBC, RSB, 8390 // RSC. Coming out of isel, they have an implicit CPSR def, but the optional 8391 // operand is still set to noreg. If needed, set the optional operand's 8392 // register to CPSR, and remove the redundant implicit def. 8393 // 8394 // e.g. ADCS (..., CPSR<imp-def>) -> ADC (... opt:CPSR<def>). 8395 8396 // Rename pseudo opcodes. 8397 unsigned NewOpc = convertAddSubFlagsOpcode(MI->getOpcode()); 8398 if (NewOpc) { 8399 const ARMBaseInstrInfo *TII = Subtarget->getInstrInfo(); 8400 MCID = &TII->get(NewOpc); 8401 8402 assert(MCID->getNumOperands() == MI->getDesc().getNumOperands() + 1 && 8403 "converted opcode should be the same except for cc_out"); 8404 8405 MI->setDesc(*MCID); 8406 8407 // Add the optional cc_out operand 8408 MI->addOperand(MachineOperand::CreateReg(0, /*isDef=*/true)); 8409 } 8410 unsigned ccOutIdx = MCID->getNumOperands() - 1; 8411 8412 // Any ARM instruction that sets the 's' bit should specify an optional 8413 // "cc_out" operand in the last operand position. 8414 if (!MI->hasOptionalDef() || !MCID->OpInfo[ccOutIdx].isOptionalDef()) { 8415 assert(!NewOpc && "Optional cc_out operand required"); 8416 return; 8417 } 8418 // Look for an implicit def of CPSR added by MachineInstr ctor. Remove it 8419 // since we already have an optional CPSR def. 8420 bool definesCPSR = false; 8421 bool deadCPSR = false; 8422 for (unsigned i = MCID->getNumOperands(), e = MI->getNumOperands(); 8423 i != e; ++i) { 8424 const MachineOperand &MO = MI->getOperand(i); 8425 if (MO.isReg() && MO.isDef() && MO.getReg() == ARM::CPSR) { 8426 definesCPSR = true; 8427 if (MO.isDead()) 8428 deadCPSR = true; 8429 MI->RemoveOperand(i); 8430 break; 8431 } 8432 } 8433 if (!definesCPSR) { 8434 assert(!NewOpc && "Optional cc_out operand required"); 8435 return; 8436 } 8437 assert(deadCPSR == !Node->hasAnyUseOfValue(1) && "inconsistent dead flag"); 8438 if (deadCPSR) { 8439 assert(!MI->getOperand(ccOutIdx).getReg() && 8440 "expect uninitialized optional cc_out operand"); 8441 return; 8442 } 8443 8444 // If this instruction was defined with an optional CPSR def and its dag node 8445 // had a live implicit CPSR def, then activate the optional CPSR def. 8446 MachineOperand &MO = MI->getOperand(ccOutIdx); 8447 MO.setReg(ARM::CPSR); 8448 MO.setIsDef(true); 8449 } 8450 8451 //===----------------------------------------------------------------------===// 8452 // ARM Optimization Hooks 8453 //===----------------------------------------------------------------------===// 8454 8455 // Helper function that checks if N is a null or all ones constant. 8456 static inline bool isZeroOrAllOnes(SDValue N, bool AllOnes) { 8457 return AllOnes ? isAllOnesConstant(N) : isNullConstant(N); 8458 } 8459 8460 // Return true if N is conditionally 0 or all ones. 8461 // Detects these expressions where cc is an i1 value: 8462 // 8463 // (select cc 0, y) [AllOnes=0] 8464 // (select cc y, 0) [AllOnes=0] 8465 // (zext cc) [AllOnes=0] 8466 // (sext cc) [AllOnes=0/1] 8467 // (select cc -1, y) [AllOnes=1] 8468 // (select cc y, -1) [AllOnes=1] 8469 // 8470 // Invert is set when N is the null/all ones constant when CC is false. 8471 // OtherOp is set to the alternative value of N. 8472 static bool isConditionalZeroOrAllOnes(SDNode *N, bool AllOnes, 8473 SDValue &CC, bool &Invert, 8474 SDValue &OtherOp, 8475 SelectionDAG &DAG) { 8476 switch (N->getOpcode()) { 8477 default: return false; 8478 case ISD::SELECT: { 8479 CC = N->getOperand(0); 8480 SDValue N1 = N->getOperand(1); 8481 SDValue N2 = N->getOperand(2); 8482 if (isZeroOrAllOnes(N1, AllOnes)) { 8483 Invert = false; 8484 OtherOp = N2; 8485 return true; 8486 } 8487 if (isZeroOrAllOnes(N2, AllOnes)) { 8488 Invert = true; 8489 OtherOp = N1; 8490 return true; 8491 } 8492 return false; 8493 } 8494 case ISD::ZERO_EXTEND: 8495 // (zext cc) can never be the all ones value. 8496 if (AllOnes) 8497 return false; 8498 // Fall through. 8499 case ISD::SIGN_EXTEND: { 8500 SDLoc dl(N); 8501 EVT VT = N->getValueType(0); 8502 CC = N->getOperand(0); 8503 if (CC.getValueType() != MVT::i1) 8504 return false; 8505 Invert = !AllOnes; 8506 if (AllOnes) 8507 // When looking for an AllOnes constant, N is an sext, and the 'other' 8508 // value is 0. 8509 OtherOp = DAG.getConstant(0, dl, VT); 8510 else if (N->getOpcode() == ISD::ZERO_EXTEND) 8511 // When looking for a 0 constant, N can be zext or sext. 8512 OtherOp = DAG.getConstant(1, dl, VT); 8513 else 8514 OtherOp = DAG.getConstant(APInt::getAllOnesValue(VT.getSizeInBits()), dl, 8515 VT); 8516 return true; 8517 } 8518 } 8519 } 8520 8521 // Combine a constant select operand into its use: 8522 // 8523 // (add (select cc, 0, c), x) -> (select cc, x, (add, x, c)) 8524 // (sub x, (select cc, 0, c)) -> (select cc, x, (sub, x, c)) 8525 // (and (select cc, -1, c), x) -> (select cc, x, (and, x, c)) [AllOnes=1] 8526 // (or (select cc, 0, c), x) -> (select cc, x, (or, x, c)) 8527 // (xor (select cc, 0, c), x) -> (select cc, x, (xor, x, c)) 8528 // 8529 // The transform is rejected if the select doesn't have a constant operand that 8530 // is null, or all ones when AllOnes is set. 8531 // 8532 // Also recognize sext/zext from i1: 8533 // 8534 // (add (zext cc), x) -> (select cc (add x, 1), x) 8535 // (add (sext cc), x) -> (select cc (add x, -1), x) 8536 // 8537 // These transformations eventually create predicated instructions. 8538 // 8539 // @param N The node to transform. 8540 // @param Slct The N operand that is a select. 8541 // @param OtherOp The other N operand (x above). 8542 // @param DCI Context. 8543 // @param AllOnes Require the select constant to be all ones instead of null. 8544 // @returns The new node, or SDValue() on failure. 8545 static 8546 SDValue combineSelectAndUse(SDNode *N, SDValue Slct, SDValue OtherOp, 8547 TargetLowering::DAGCombinerInfo &DCI, 8548 bool AllOnes = false) { 8549 SelectionDAG &DAG = DCI.DAG; 8550 EVT VT = N->getValueType(0); 8551 SDValue NonConstantVal; 8552 SDValue CCOp; 8553 bool SwapSelectOps; 8554 if (!isConditionalZeroOrAllOnes(Slct.getNode(), AllOnes, CCOp, SwapSelectOps, 8555 NonConstantVal, DAG)) 8556 return SDValue(); 8557 8558 // Slct is now know to be the desired identity constant when CC is true. 8559 SDValue TrueVal = OtherOp; 8560 SDValue FalseVal = DAG.getNode(N->getOpcode(), SDLoc(N), VT, 8561 OtherOp, NonConstantVal); 8562 // Unless SwapSelectOps says CC should be false. 8563 if (SwapSelectOps) 8564 std::swap(TrueVal, FalseVal); 8565 8566 return DAG.getNode(ISD::SELECT, SDLoc(N), VT, 8567 CCOp, TrueVal, FalseVal); 8568 } 8569 8570 // Attempt combineSelectAndUse on each operand of a commutative operator N. 8571 static 8572 SDValue combineSelectAndUseCommutative(SDNode *N, bool AllOnes, 8573 TargetLowering::DAGCombinerInfo &DCI) { 8574 SDValue N0 = N->getOperand(0); 8575 SDValue N1 = N->getOperand(1); 8576 if (N0.getNode()->hasOneUse()) 8577 if (SDValue Result = combineSelectAndUse(N, N0, N1, DCI, AllOnes)) 8578 return Result; 8579 if (N1.getNode()->hasOneUse()) 8580 if (SDValue Result = combineSelectAndUse(N, N1, N0, DCI, AllOnes)) 8581 return Result; 8582 return SDValue(); 8583 } 8584 8585 // AddCombineToVPADDL- For pair-wise add on neon, use the vpaddl instruction 8586 // (only after legalization). 8587 static SDValue AddCombineToVPADDL(SDNode *N, SDValue N0, SDValue N1, 8588 TargetLowering::DAGCombinerInfo &DCI, 8589 const ARMSubtarget *Subtarget) { 8590 8591 // Only perform optimization if after legalize, and if NEON is available. We 8592 // also expected both operands to be BUILD_VECTORs. 8593 if (DCI.isBeforeLegalize() || !Subtarget->hasNEON() 8594 || N0.getOpcode() != ISD::BUILD_VECTOR 8595 || N1.getOpcode() != ISD::BUILD_VECTOR) 8596 return SDValue(); 8597 8598 // Check output type since VPADDL operand elements can only be 8, 16, or 32. 8599 EVT VT = N->getValueType(0); 8600 if (!VT.isInteger() || VT.getVectorElementType() == MVT::i64) 8601 return SDValue(); 8602 8603 // Check that the vector operands are of the right form. 8604 // N0 and N1 are BUILD_VECTOR nodes with N number of EXTRACT_VECTOR 8605 // operands, where N is the size of the formed vector. 8606 // Each EXTRACT_VECTOR should have the same input vector and odd or even 8607 // index such that we have a pair wise add pattern. 8608 8609 // Grab the vector that all EXTRACT_VECTOR nodes should be referencing. 8610 if (N0->getOperand(0)->getOpcode() != ISD::EXTRACT_VECTOR_ELT) 8611 return SDValue(); 8612 SDValue Vec = N0->getOperand(0)->getOperand(0); 8613 SDNode *V = Vec.getNode(); 8614 unsigned nextIndex = 0; 8615 8616 // For each operands to the ADD which are BUILD_VECTORs, 8617 // check to see if each of their operands are an EXTRACT_VECTOR with 8618 // the same vector and appropriate index. 8619 for (unsigned i = 0, e = N0->getNumOperands(); i != e; ++i) { 8620 if (N0->getOperand(i)->getOpcode() == ISD::EXTRACT_VECTOR_ELT 8621 && N1->getOperand(i)->getOpcode() == ISD::EXTRACT_VECTOR_ELT) { 8622 8623 SDValue ExtVec0 = N0->getOperand(i); 8624 SDValue ExtVec1 = N1->getOperand(i); 8625 8626 // First operand is the vector, verify its the same. 8627 if (V != ExtVec0->getOperand(0).getNode() || 8628 V != ExtVec1->getOperand(0).getNode()) 8629 return SDValue(); 8630 8631 // Second is the constant, verify its correct. 8632 ConstantSDNode *C0 = dyn_cast<ConstantSDNode>(ExtVec0->getOperand(1)); 8633 ConstantSDNode *C1 = dyn_cast<ConstantSDNode>(ExtVec1->getOperand(1)); 8634 8635 // For the constant, we want to see all the even or all the odd. 8636 if (!C0 || !C1 || C0->getZExtValue() != nextIndex 8637 || C1->getZExtValue() != nextIndex+1) 8638 return SDValue(); 8639 8640 // Increment index. 8641 nextIndex+=2; 8642 } else 8643 return SDValue(); 8644 } 8645 8646 // Create VPADDL node. 8647 SelectionDAG &DAG = DCI.DAG; 8648 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 8649 8650 SDLoc dl(N); 8651 8652 // Build operand list. 8653 SmallVector<SDValue, 8> Ops; 8654 Ops.push_back(DAG.getConstant(Intrinsic::arm_neon_vpaddls, dl, 8655 TLI.getPointerTy(DAG.getDataLayout()))); 8656 8657 // Input is the vector. 8658 Ops.push_back(Vec); 8659 8660 // Get widened type and narrowed type. 8661 MVT widenType; 8662 unsigned numElem = VT.getVectorNumElements(); 8663 8664 EVT inputLaneType = Vec.getValueType().getVectorElementType(); 8665 switch (inputLaneType.getSimpleVT().SimpleTy) { 8666 case MVT::i8: widenType = MVT::getVectorVT(MVT::i16, numElem); break; 8667 case MVT::i16: widenType = MVT::getVectorVT(MVT::i32, numElem); break; 8668 case MVT::i32: widenType = MVT::getVectorVT(MVT::i64, numElem); break; 8669 default: 8670 llvm_unreachable("Invalid vector element type for padd optimization."); 8671 } 8672 8673 SDValue tmp = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, widenType, Ops); 8674 unsigned ExtOp = VT.bitsGT(tmp.getValueType()) ? ISD::ANY_EXTEND : ISD::TRUNCATE; 8675 return DAG.getNode(ExtOp, dl, VT, tmp); 8676 } 8677 8678 static SDValue findMUL_LOHI(SDValue V) { 8679 if (V->getOpcode() == ISD::UMUL_LOHI || 8680 V->getOpcode() == ISD::SMUL_LOHI) 8681 return V; 8682 return SDValue(); 8683 } 8684 8685 static SDValue AddCombineTo64bitMLAL(SDNode *AddcNode, 8686 TargetLowering::DAGCombinerInfo &DCI, 8687 const ARMSubtarget *Subtarget) { 8688 8689 if (Subtarget->isThumb1Only()) return SDValue(); 8690 8691 // Only perform the checks after legalize when the pattern is available. 8692 if (DCI.isBeforeLegalize()) return SDValue(); 8693 8694 // Look for multiply add opportunities. 8695 // The pattern is a ISD::UMUL_LOHI followed by two add nodes, where 8696 // each add nodes consumes a value from ISD::UMUL_LOHI and there is 8697 // a glue link from the first add to the second add. 8698 // If we find this pattern, we can replace the U/SMUL_LOHI, ADDC, and ADDE by 8699 // a S/UMLAL instruction. 8700 // UMUL_LOHI 8701 // / :lo \ :hi 8702 // / \ [no multiline comment] 8703 // loAdd -> ADDE | 8704 // \ :glue / 8705 // \ / 8706 // ADDC <- hiAdd 8707 // 8708 assert(AddcNode->getOpcode() == ISD::ADDC && "Expect an ADDC"); 8709 SDValue AddcOp0 = AddcNode->getOperand(0); 8710 SDValue AddcOp1 = AddcNode->getOperand(1); 8711 8712 // Check if the two operands are from the same mul_lohi node. 8713 if (AddcOp0.getNode() == AddcOp1.getNode()) 8714 return SDValue(); 8715 8716 assert(AddcNode->getNumValues() == 2 && 8717 AddcNode->getValueType(0) == MVT::i32 && 8718 "Expect ADDC with two result values. First: i32"); 8719 8720 // Check that we have a glued ADDC node. 8721 if (AddcNode->getValueType(1) != MVT::Glue) 8722 return SDValue(); 8723 8724 // Check that the ADDC adds the low result of the S/UMUL_LOHI. 8725 if (AddcOp0->getOpcode() != ISD::UMUL_LOHI && 8726 AddcOp0->getOpcode() != ISD::SMUL_LOHI && 8727 AddcOp1->getOpcode() != ISD::UMUL_LOHI && 8728 AddcOp1->getOpcode() != ISD::SMUL_LOHI) 8729 return SDValue(); 8730 8731 // Look for the glued ADDE. 8732 SDNode* AddeNode = AddcNode->getGluedUser(); 8733 if (!AddeNode) 8734 return SDValue(); 8735 8736 // Make sure it is really an ADDE. 8737 if (AddeNode->getOpcode() != ISD::ADDE) 8738 return SDValue(); 8739 8740 assert(AddeNode->getNumOperands() == 3 && 8741 AddeNode->getOperand(2).getValueType() == MVT::Glue && 8742 "ADDE node has the wrong inputs"); 8743 8744 // Check for the triangle shape. 8745 SDValue AddeOp0 = AddeNode->getOperand(0); 8746 SDValue AddeOp1 = AddeNode->getOperand(1); 8747 8748 // Make sure that the ADDE operands are not coming from the same node. 8749 if (AddeOp0.getNode() == AddeOp1.getNode()) 8750 return SDValue(); 8751 8752 // Find the MUL_LOHI node walking up ADDE's operands. 8753 bool IsLeftOperandMUL = false; 8754 SDValue MULOp = findMUL_LOHI(AddeOp0); 8755 if (MULOp == SDValue()) 8756 MULOp = findMUL_LOHI(AddeOp1); 8757 else 8758 IsLeftOperandMUL = true; 8759 if (MULOp == SDValue()) 8760 return SDValue(); 8761 8762 // Figure out the right opcode. 8763 unsigned Opc = MULOp->getOpcode(); 8764 unsigned FinalOpc = (Opc == ISD::SMUL_LOHI) ? ARMISD::SMLAL : ARMISD::UMLAL; 8765 8766 // Figure out the high and low input values to the MLAL node. 8767 SDValue* HiAdd = nullptr; 8768 SDValue* LoMul = nullptr; 8769 SDValue* LowAdd = nullptr; 8770 8771 // Ensure that ADDE is from high result of ISD::SMUL_LOHI. 8772 if ((AddeOp0 != MULOp.getValue(1)) && (AddeOp1 != MULOp.getValue(1))) 8773 return SDValue(); 8774 8775 if (IsLeftOperandMUL) 8776 HiAdd = &AddeOp1; 8777 else 8778 HiAdd = &AddeOp0; 8779 8780 8781 // Ensure that LoMul and LowAdd are taken from correct ISD::SMUL_LOHI node 8782 // whose low result is fed to the ADDC we are checking. 8783 8784 if (AddcOp0 == MULOp.getValue(0)) { 8785 LoMul = &AddcOp0; 8786 LowAdd = &AddcOp1; 8787 } 8788 if (AddcOp1 == MULOp.getValue(0)) { 8789 LoMul = &AddcOp1; 8790 LowAdd = &AddcOp0; 8791 } 8792 8793 if (!LoMul) 8794 return SDValue(); 8795 8796 // Create the merged node. 8797 SelectionDAG &DAG = DCI.DAG; 8798 8799 // Build operand list. 8800 SmallVector<SDValue, 8> Ops; 8801 Ops.push_back(LoMul->getOperand(0)); 8802 Ops.push_back(LoMul->getOperand(1)); 8803 Ops.push_back(*LowAdd); 8804 Ops.push_back(*HiAdd); 8805 8806 SDValue MLALNode = DAG.getNode(FinalOpc, SDLoc(AddcNode), 8807 DAG.getVTList(MVT::i32, MVT::i32), Ops); 8808 8809 // Replace the ADDs' nodes uses by the MLA node's values. 8810 SDValue HiMLALResult(MLALNode.getNode(), 1); 8811 DAG.ReplaceAllUsesOfValueWith(SDValue(AddeNode, 0), HiMLALResult); 8812 8813 SDValue LoMLALResult(MLALNode.getNode(), 0); 8814 DAG.ReplaceAllUsesOfValueWith(SDValue(AddcNode, 0), LoMLALResult); 8815 8816 // Return original node to notify the driver to stop replacing. 8817 SDValue resNode(AddcNode, 0); 8818 return resNode; 8819 } 8820 8821 /// PerformADDCCombine - Target-specific dag combine transform from 8822 /// ISD::ADDC, ISD::ADDE, and ISD::MUL_LOHI to MLAL. 8823 static SDValue PerformADDCCombine(SDNode *N, 8824 TargetLowering::DAGCombinerInfo &DCI, 8825 const ARMSubtarget *Subtarget) { 8826 8827 return AddCombineTo64bitMLAL(N, DCI, Subtarget); 8828 8829 } 8830 8831 /// PerformADDCombineWithOperands - Try DAG combinations for an ADD with 8832 /// operands N0 and N1. This is a helper for PerformADDCombine that is 8833 /// called with the default operands, and if that fails, with commuted 8834 /// operands. 8835 static SDValue PerformADDCombineWithOperands(SDNode *N, SDValue N0, SDValue N1, 8836 TargetLowering::DAGCombinerInfo &DCI, 8837 const ARMSubtarget *Subtarget){ 8838 8839 // Attempt to create vpaddl for this add. 8840 if (SDValue Result = AddCombineToVPADDL(N, N0, N1, DCI, Subtarget)) 8841 return Result; 8842 8843 // fold (add (select cc, 0, c), x) -> (select cc, x, (add, x, c)) 8844 if (N0.getNode()->hasOneUse()) 8845 if (SDValue Result = combineSelectAndUse(N, N0, N1, DCI)) 8846 return Result; 8847 return SDValue(); 8848 } 8849 8850 /// PerformADDCombine - Target-specific dag combine xforms for ISD::ADD. 8851 /// 8852 static SDValue PerformADDCombine(SDNode *N, 8853 TargetLowering::DAGCombinerInfo &DCI, 8854 const ARMSubtarget *Subtarget) { 8855 SDValue N0 = N->getOperand(0); 8856 SDValue N1 = N->getOperand(1); 8857 8858 // First try with the default operand order. 8859 if (SDValue Result = PerformADDCombineWithOperands(N, N0, N1, DCI, Subtarget)) 8860 return Result; 8861 8862 // If that didn't work, try again with the operands commuted. 8863 return PerformADDCombineWithOperands(N, N1, N0, DCI, Subtarget); 8864 } 8865 8866 /// PerformSUBCombine - Target-specific dag combine xforms for ISD::SUB. 8867 /// 8868 static SDValue PerformSUBCombine(SDNode *N, 8869 TargetLowering::DAGCombinerInfo &DCI) { 8870 SDValue N0 = N->getOperand(0); 8871 SDValue N1 = N->getOperand(1); 8872 8873 // fold (sub x, (select cc, 0, c)) -> (select cc, x, (sub, x, c)) 8874 if (N1.getNode()->hasOneUse()) 8875 if (SDValue Result = combineSelectAndUse(N, N1, N0, DCI)) 8876 return Result; 8877 8878 return SDValue(); 8879 } 8880 8881 /// PerformVMULCombine 8882 /// Distribute (A + B) * C to (A * C) + (B * C) to take advantage of the 8883 /// special multiplier accumulator forwarding. 8884 /// vmul d3, d0, d2 8885 /// vmla d3, d1, d2 8886 /// is faster than 8887 /// vadd d3, d0, d1 8888 /// vmul d3, d3, d2 8889 // However, for (A + B) * (A + B), 8890 // vadd d2, d0, d1 8891 // vmul d3, d0, d2 8892 // vmla d3, d1, d2 8893 // is slower than 8894 // vadd d2, d0, d1 8895 // vmul d3, d2, d2 8896 static SDValue PerformVMULCombine(SDNode *N, 8897 TargetLowering::DAGCombinerInfo &DCI, 8898 const ARMSubtarget *Subtarget) { 8899 if (!Subtarget->hasVMLxForwarding()) 8900 return SDValue(); 8901 8902 SelectionDAG &DAG = DCI.DAG; 8903 SDValue N0 = N->getOperand(0); 8904 SDValue N1 = N->getOperand(1); 8905 unsigned Opcode = N0.getOpcode(); 8906 if (Opcode != ISD::ADD && Opcode != ISD::SUB && 8907 Opcode != ISD::FADD && Opcode != ISD::FSUB) { 8908 Opcode = N1.getOpcode(); 8909 if (Opcode != ISD::ADD && Opcode != ISD::SUB && 8910 Opcode != ISD::FADD && Opcode != ISD::FSUB) 8911 return SDValue(); 8912 std::swap(N0, N1); 8913 } 8914 8915 if (N0 == N1) 8916 return SDValue(); 8917 8918 EVT VT = N->getValueType(0); 8919 SDLoc DL(N); 8920 SDValue N00 = N0->getOperand(0); 8921 SDValue N01 = N0->getOperand(1); 8922 return DAG.getNode(Opcode, DL, VT, 8923 DAG.getNode(ISD::MUL, DL, VT, N00, N1), 8924 DAG.getNode(ISD::MUL, DL, VT, N01, N1)); 8925 } 8926 8927 static SDValue PerformMULCombine(SDNode *N, 8928 TargetLowering::DAGCombinerInfo &DCI, 8929 const ARMSubtarget *Subtarget) { 8930 SelectionDAG &DAG = DCI.DAG; 8931 8932 if (Subtarget->isThumb1Only()) 8933 return SDValue(); 8934 8935 if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer()) 8936 return SDValue(); 8937 8938 EVT VT = N->getValueType(0); 8939 if (VT.is64BitVector() || VT.is128BitVector()) 8940 return PerformVMULCombine(N, DCI, Subtarget); 8941 if (VT != MVT::i32) 8942 return SDValue(); 8943 8944 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(1)); 8945 if (!C) 8946 return SDValue(); 8947 8948 int64_t MulAmt = C->getSExtValue(); 8949 unsigned ShiftAmt = countTrailingZeros<uint64_t>(MulAmt); 8950 8951 ShiftAmt = ShiftAmt & (32 - 1); 8952 SDValue V = N->getOperand(0); 8953 SDLoc DL(N); 8954 8955 SDValue Res; 8956 MulAmt >>= ShiftAmt; 8957 8958 if (MulAmt >= 0) { 8959 if (isPowerOf2_32(MulAmt - 1)) { 8960 // (mul x, 2^N + 1) => (add (shl x, N), x) 8961 Res = DAG.getNode(ISD::ADD, DL, VT, 8962 V, 8963 DAG.getNode(ISD::SHL, DL, VT, 8964 V, 8965 DAG.getConstant(Log2_32(MulAmt - 1), DL, 8966 MVT::i32))); 8967 } else if (isPowerOf2_32(MulAmt + 1)) { 8968 // (mul x, 2^N - 1) => (sub (shl x, N), x) 8969 Res = DAG.getNode(ISD::SUB, DL, VT, 8970 DAG.getNode(ISD::SHL, DL, VT, 8971 V, 8972 DAG.getConstant(Log2_32(MulAmt + 1), DL, 8973 MVT::i32)), 8974 V); 8975 } else 8976 return SDValue(); 8977 } else { 8978 uint64_t MulAmtAbs = -MulAmt; 8979 if (isPowerOf2_32(MulAmtAbs + 1)) { 8980 // (mul x, -(2^N - 1)) => (sub x, (shl x, N)) 8981 Res = DAG.getNode(ISD::SUB, DL, VT, 8982 V, 8983 DAG.getNode(ISD::SHL, DL, VT, 8984 V, 8985 DAG.getConstant(Log2_32(MulAmtAbs + 1), DL, 8986 MVT::i32))); 8987 } else if (isPowerOf2_32(MulAmtAbs - 1)) { 8988 // (mul x, -(2^N + 1)) => - (add (shl x, N), x) 8989 Res = DAG.getNode(ISD::ADD, DL, VT, 8990 V, 8991 DAG.getNode(ISD::SHL, DL, VT, 8992 V, 8993 DAG.getConstant(Log2_32(MulAmtAbs - 1), DL, 8994 MVT::i32))); 8995 Res = DAG.getNode(ISD::SUB, DL, VT, 8996 DAG.getConstant(0, DL, MVT::i32), Res); 8997 8998 } else 8999 return SDValue(); 9000 } 9001 9002 if (ShiftAmt != 0) 9003 Res = DAG.getNode(ISD::SHL, DL, VT, 9004 Res, DAG.getConstant(ShiftAmt, DL, MVT::i32)); 9005 9006 // Do not add new nodes to DAG combiner worklist. 9007 DCI.CombineTo(N, Res, false); 9008 return SDValue(); 9009 } 9010 9011 static SDValue PerformANDCombine(SDNode *N, 9012 TargetLowering::DAGCombinerInfo &DCI, 9013 const ARMSubtarget *Subtarget) { 9014 9015 // Attempt to use immediate-form VBIC 9016 BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(N->getOperand(1)); 9017 SDLoc dl(N); 9018 EVT VT = N->getValueType(0); 9019 SelectionDAG &DAG = DCI.DAG; 9020 9021 if(!DAG.getTargetLoweringInfo().isTypeLegal(VT)) 9022 return SDValue(); 9023 9024 APInt SplatBits, SplatUndef; 9025 unsigned SplatBitSize; 9026 bool HasAnyUndefs; 9027 if (BVN && 9028 BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs)) { 9029 if (SplatBitSize <= 64) { 9030 EVT VbicVT; 9031 SDValue Val = isNEONModifiedImm((~SplatBits).getZExtValue(), 9032 SplatUndef.getZExtValue(), SplatBitSize, 9033 DAG, dl, VbicVT, VT.is128BitVector(), 9034 OtherModImm); 9035 if (Val.getNode()) { 9036 SDValue Input = 9037 DAG.getNode(ISD::BITCAST, dl, VbicVT, N->getOperand(0)); 9038 SDValue Vbic = DAG.getNode(ARMISD::VBICIMM, dl, VbicVT, Input, Val); 9039 return DAG.getNode(ISD::BITCAST, dl, VT, Vbic); 9040 } 9041 } 9042 } 9043 9044 if (!Subtarget->isThumb1Only()) { 9045 // fold (and (select cc, -1, c), x) -> (select cc, x, (and, x, c)) 9046 if (SDValue Result = combineSelectAndUseCommutative(N, true, DCI)) 9047 return Result; 9048 } 9049 9050 return SDValue(); 9051 } 9052 9053 /// PerformORCombine - Target-specific dag combine xforms for ISD::OR 9054 static SDValue PerformORCombine(SDNode *N, 9055 TargetLowering::DAGCombinerInfo &DCI, 9056 const ARMSubtarget *Subtarget) { 9057 // Attempt to use immediate-form VORR 9058 BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(N->getOperand(1)); 9059 SDLoc dl(N); 9060 EVT VT = N->getValueType(0); 9061 SelectionDAG &DAG = DCI.DAG; 9062 9063 if(!DAG.getTargetLoweringInfo().isTypeLegal(VT)) 9064 return SDValue(); 9065 9066 APInt SplatBits, SplatUndef; 9067 unsigned SplatBitSize; 9068 bool HasAnyUndefs; 9069 if (BVN && Subtarget->hasNEON() && 9070 BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs)) { 9071 if (SplatBitSize <= 64) { 9072 EVT VorrVT; 9073 SDValue Val = isNEONModifiedImm(SplatBits.getZExtValue(), 9074 SplatUndef.getZExtValue(), SplatBitSize, 9075 DAG, dl, VorrVT, VT.is128BitVector(), 9076 OtherModImm); 9077 if (Val.getNode()) { 9078 SDValue Input = 9079 DAG.getNode(ISD::BITCAST, dl, VorrVT, N->getOperand(0)); 9080 SDValue Vorr = DAG.getNode(ARMISD::VORRIMM, dl, VorrVT, Input, Val); 9081 return DAG.getNode(ISD::BITCAST, dl, VT, Vorr); 9082 } 9083 } 9084 } 9085 9086 if (!Subtarget->isThumb1Only()) { 9087 // fold (or (select cc, 0, c), x) -> (select cc, x, (or, x, c)) 9088 if (SDValue Result = combineSelectAndUseCommutative(N, false, DCI)) 9089 return Result; 9090 } 9091 9092 // The code below optimizes (or (and X, Y), Z). 9093 // The AND operand needs to have a single user to make these optimizations 9094 // profitable. 9095 SDValue N0 = N->getOperand(0); 9096 if (N0.getOpcode() != ISD::AND || !N0.hasOneUse()) 9097 return SDValue(); 9098 SDValue N1 = N->getOperand(1); 9099 9100 // (or (and B, A), (and C, ~A)) => (VBSL A, B, C) when A is a constant. 9101 if (Subtarget->hasNEON() && N1.getOpcode() == ISD::AND && VT.isVector() && 9102 DAG.getTargetLoweringInfo().isTypeLegal(VT)) { 9103 APInt SplatUndef; 9104 unsigned SplatBitSize; 9105 bool HasAnyUndefs; 9106 9107 APInt SplatBits0, SplatBits1; 9108 BuildVectorSDNode *BVN0 = dyn_cast<BuildVectorSDNode>(N0->getOperand(1)); 9109 BuildVectorSDNode *BVN1 = dyn_cast<BuildVectorSDNode>(N1->getOperand(1)); 9110 // Ensure that the second operand of both ands are constants 9111 if (BVN0 && BVN0->isConstantSplat(SplatBits0, SplatUndef, SplatBitSize, 9112 HasAnyUndefs) && !HasAnyUndefs) { 9113 if (BVN1 && BVN1->isConstantSplat(SplatBits1, SplatUndef, SplatBitSize, 9114 HasAnyUndefs) && !HasAnyUndefs) { 9115 // Ensure that the bit width of the constants are the same and that 9116 // the splat arguments are logical inverses as per the pattern we 9117 // are trying to simplify. 9118 if (SplatBits0.getBitWidth() == SplatBits1.getBitWidth() && 9119 SplatBits0 == ~SplatBits1) { 9120 // Canonicalize the vector type to make instruction selection 9121 // simpler. 9122 EVT CanonicalVT = VT.is128BitVector() ? MVT::v4i32 : MVT::v2i32; 9123 SDValue Result = DAG.getNode(ARMISD::VBSL, dl, CanonicalVT, 9124 N0->getOperand(1), 9125 N0->getOperand(0), 9126 N1->getOperand(0)); 9127 return DAG.getNode(ISD::BITCAST, dl, VT, Result); 9128 } 9129 } 9130 } 9131 } 9132 9133 // Try to use the ARM/Thumb2 BFI (bitfield insert) instruction when 9134 // reasonable. 9135 9136 // BFI is only available on V6T2+ 9137 if (Subtarget->isThumb1Only() || !Subtarget->hasV6T2Ops()) 9138 return SDValue(); 9139 9140 SDLoc DL(N); 9141 // 1) or (and A, mask), val => ARMbfi A, val, mask 9142 // iff (val & mask) == val 9143 // 9144 // 2) or (and A, mask), (and B, mask2) => ARMbfi A, (lsr B, amt), mask 9145 // 2a) iff isBitFieldInvertedMask(mask) && isBitFieldInvertedMask(~mask2) 9146 // && mask == ~mask2 9147 // 2b) iff isBitFieldInvertedMask(~mask) && isBitFieldInvertedMask(mask2) 9148 // && ~mask == mask2 9149 // (i.e., copy a bitfield value into another bitfield of the same width) 9150 9151 if (VT != MVT::i32) 9152 return SDValue(); 9153 9154 SDValue N00 = N0.getOperand(0); 9155 9156 // The value and the mask need to be constants so we can verify this is 9157 // actually a bitfield set. If the mask is 0xffff, we can do better 9158 // via a movt instruction, so don't use BFI in that case. 9159 SDValue MaskOp = N0.getOperand(1); 9160 ConstantSDNode *MaskC = dyn_cast<ConstantSDNode>(MaskOp); 9161 if (!MaskC) 9162 return SDValue(); 9163 unsigned Mask = MaskC->getZExtValue(); 9164 if (Mask == 0xffff) 9165 return SDValue(); 9166 SDValue Res; 9167 // Case (1): or (and A, mask), val => ARMbfi A, val, mask 9168 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1); 9169 if (N1C) { 9170 unsigned Val = N1C->getZExtValue(); 9171 if ((Val & ~Mask) != Val) 9172 return SDValue(); 9173 9174 if (ARM::isBitFieldInvertedMask(Mask)) { 9175 Val >>= countTrailingZeros(~Mask); 9176 9177 Res = DAG.getNode(ARMISD::BFI, DL, VT, N00, 9178 DAG.getConstant(Val, DL, MVT::i32), 9179 DAG.getConstant(Mask, DL, MVT::i32)); 9180 9181 // Do not add new nodes to DAG combiner worklist. 9182 DCI.CombineTo(N, Res, false); 9183 return SDValue(); 9184 } 9185 } else if (N1.getOpcode() == ISD::AND) { 9186 // case (2) or (and A, mask), (and B, mask2) => ARMbfi A, (lsr B, amt), mask 9187 ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1)); 9188 if (!N11C) 9189 return SDValue(); 9190 unsigned Mask2 = N11C->getZExtValue(); 9191 9192 // Mask and ~Mask2 (or reverse) must be equivalent for the BFI pattern 9193 // as is to match. 9194 if (ARM::isBitFieldInvertedMask(Mask) && 9195 (Mask == ~Mask2)) { 9196 // The pack halfword instruction works better for masks that fit it, 9197 // so use that when it's available. 9198 if (Subtarget->hasT2ExtractPack() && 9199 (Mask == 0xffff || Mask == 0xffff0000)) 9200 return SDValue(); 9201 // 2a 9202 unsigned amt = countTrailingZeros(Mask2); 9203 Res = DAG.getNode(ISD::SRL, DL, VT, N1.getOperand(0), 9204 DAG.getConstant(amt, DL, MVT::i32)); 9205 Res = DAG.getNode(ARMISD::BFI, DL, VT, N00, Res, 9206 DAG.getConstant(Mask, DL, MVT::i32)); 9207 // Do not add new nodes to DAG combiner worklist. 9208 DCI.CombineTo(N, Res, false); 9209 return SDValue(); 9210 } else if (ARM::isBitFieldInvertedMask(~Mask) && 9211 (~Mask == Mask2)) { 9212 // The pack halfword instruction works better for masks that fit it, 9213 // so use that when it's available. 9214 if (Subtarget->hasT2ExtractPack() && 9215 (Mask2 == 0xffff || Mask2 == 0xffff0000)) 9216 return SDValue(); 9217 // 2b 9218 unsigned lsb = countTrailingZeros(Mask); 9219 Res = DAG.getNode(ISD::SRL, DL, VT, N00, 9220 DAG.getConstant(lsb, DL, MVT::i32)); 9221 Res = DAG.getNode(ARMISD::BFI, DL, VT, N1.getOperand(0), Res, 9222 DAG.getConstant(Mask2, DL, MVT::i32)); 9223 // Do not add new nodes to DAG combiner worklist. 9224 DCI.CombineTo(N, Res, false); 9225 return SDValue(); 9226 } 9227 } 9228 9229 if (DAG.MaskedValueIsZero(N1, MaskC->getAPIntValue()) && 9230 N00.getOpcode() == ISD::SHL && isa<ConstantSDNode>(N00.getOperand(1)) && 9231 ARM::isBitFieldInvertedMask(~Mask)) { 9232 // Case (3): or (and (shl A, #shamt), mask), B => ARMbfi B, A, ~mask 9233 // where lsb(mask) == #shamt and masked bits of B are known zero. 9234 SDValue ShAmt = N00.getOperand(1); 9235 unsigned ShAmtC = cast<ConstantSDNode>(ShAmt)->getZExtValue(); 9236 unsigned LSB = countTrailingZeros(Mask); 9237 if (ShAmtC != LSB) 9238 return SDValue(); 9239 9240 Res = DAG.getNode(ARMISD::BFI, DL, VT, N1, N00.getOperand(0), 9241 DAG.getConstant(~Mask, DL, MVT::i32)); 9242 9243 // Do not add new nodes to DAG combiner worklist. 9244 DCI.CombineTo(N, Res, false); 9245 } 9246 9247 return SDValue(); 9248 } 9249 9250 static SDValue PerformXORCombine(SDNode *N, 9251 TargetLowering::DAGCombinerInfo &DCI, 9252 const ARMSubtarget *Subtarget) { 9253 EVT VT = N->getValueType(0); 9254 SelectionDAG &DAG = DCI.DAG; 9255 9256 if(!DAG.getTargetLoweringInfo().isTypeLegal(VT)) 9257 return SDValue(); 9258 9259 if (!Subtarget->isThumb1Only()) { 9260 // fold (xor (select cc, 0, c), x) -> (select cc, x, (xor, x, c)) 9261 if (SDValue Result = combineSelectAndUseCommutative(N, false, DCI)) 9262 return Result; 9263 } 9264 9265 return SDValue(); 9266 } 9267 9268 // ParseBFI - given a BFI instruction in N, extract the "from" value (Rn) and return it, 9269 // and fill in FromMask and ToMask with (consecutive) bits in "from" to be extracted and 9270 // their position in "to" (Rd). 9271 static SDValue ParseBFI(SDNode *N, APInt &ToMask, APInt &FromMask) { 9272 assert(N->getOpcode() == ARMISD::BFI); 9273 9274 SDValue From = N->getOperand(1); 9275 ToMask = ~cast<ConstantSDNode>(N->getOperand(2))->getAPIntValue(); 9276 FromMask = APInt::getLowBitsSet(ToMask.getBitWidth(), ToMask.countPopulation()); 9277 9278 // If the Base came from a SHR #C, we can deduce that it is really testing bit 9279 // #C in the base of the SHR. 9280 if (From->getOpcode() == ISD::SRL && 9281 isa<ConstantSDNode>(From->getOperand(1))) { 9282 APInt Shift = cast<ConstantSDNode>(From->getOperand(1))->getAPIntValue(); 9283 assert(Shift.getLimitedValue() < 32 && "Shift too large!"); 9284 FromMask <<= Shift.getLimitedValue(31); 9285 From = From->getOperand(0); 9286 } 9287 9288 return From; 9289 } 9290 9291 // If A and B contain one contiguous set of bits, does A | B == A . B? 9292 // 9293 // Neither A nor B must be zero. 9294 static bool BitsProperlyConcatenate(const APInt &A, const APInt &B) { 9295 unsigned LastActiveBitInA = A.countTrailingZeros(); 9296 unsigned FirstActiveBitInB = B.getBitWidth() - B.countLeadingZeros() - 1; 9297 return LastActiveBitInA - 1 == FirstActiveBitInB; 9298 } 9299 9300 static SDValue FindBFIToCombineWith(SDNode *N) { 9301 // We have a BFI in N. Follow a possible chain of BFIs and find a BFI it can combine with, 9302 // if one exists. 9303 APInt ToMask, FromMask; 9304 SDValue From = ParseBFI(N, ToMask, FromMask); 9305 SDValue To = N->getOperand(0); 9306 9307 // Now check for a compatible BFI to merge with. We can pass through BFIs that 9308 // aren't compatible, but not if they set the same bit in their destination as 9309 // we do (or that of any BFI we're going to combine with). 9310 SDValue V = To; 9311 APInt CombinedToMask = ToMask; 9312 while (V.getOpcode() == ARMISD::BFI) { 9313 APInt NewToMask, NewFromMask; 9314 SDValue NewFrom = ParseBFI(V.getNode(), NewToMask, NewFromMask); 9315 if (NewFrom != From) { 9316 // This BFI has a different base. Keep going. 9317 CombinedToMask |= NewToMask; 9318 V = V.getOperand(0); 9319 continue; 9320 } 9321 9322 // Do the written bits conflict with any we've seen so far? 9323 if ((NewToMask & CombinedToMask).getBoolValue()) 9324 // Conflicting bits - bail out because going further is unsafe. 9325 return SDValue(); 9326 9327 // Are the new bits contiguous when combined with the old bits? 9328 if (BitsProperlyConcatenate(ToMask, NewToMask) && 9329 BitsProperlyConcatenate(FromMask, NewFromMask)) 9330 return V; 9331 if (BitsProperlyConcatenate(NewToMask, ToMask) && 9332 BitsProperlyConcatenate(NewFromMask, FromMask)) 9333 return V; 9334 9335 // We've seen a write to some bits, so track it. 9336 CombinedToMask |= NewToMask; 9337 // Keep going... 9338 V = V.getOperand(0); 9339 } 9340 9341 return SDValue(); 9342 } 9343 9344 static SDValue PerformBFICombine(SDNode *N, 9345 TargetLowering::DAGCombinerInfo &DCI) { 9346 SDValue N1 = N->getOperand(1); 9347 if (N1.getOpcode() == ISD::AND) { 9348 // (bfi A, (and B, Mask1), Mask2) -> (bfi A, B, Mask2) iff 9349 // the bits being cleared by the AND are not demanded by the BFI. 9350 ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1)); 9351 if (!N11C) 9352 return SDValue(); 9353 unsigned InvMask = cast<ConstantSDNode>(N->getOperand(2))->getZExtValue(); 9354 unsigned LSB = countTrailingZeros(~InvMask); 9355 unsigned Width = (32 - countLeadingZeros(~InvMask)) - LSB; 9356 assert(Width < 9357 static_cast<unsigned>(std::numeric_limits<unsigned>::digits) && 9358 "undefined behavior"); 9359 unsigned Mask = (1u << Width) - 1; 9360 unsigned Mask2 = N11C->getZExtValue(); 9361 if ((Mask & (~Mask2)) == 0) 9362 return DCI.DAG.getNode(ARMISD::BFI, SDLoc(N), N->getValueType(0), 9363 N->getOperand(0), N1.getOperand(0), 9364 N->getOperand(2)); 9365 } else if (N->getOperand(0).getOpcode() == ARMISD::BFI) { 9366 // We have a BFI of a BFI. Walk up the BFI chain to see how long it goes. 9367 // Keep track of any consecutive bits set that all come from the same base 9368 // value. We can combine these together into a single BFI. 9369 SDValue CombineBFI = FindBFIToCombineWith(N); 9370 if (CombineBFI == SDValue()) 9371 return SDValue(); 9372 9373 // We've found a BFI. 9374 APInt ToMask1, FromMask1; 9375 SDValue From1 = ParseBFI(N, ToMask1, FromMask1); 9376 9377 APInt ToMask2, FromMask2; 9378 SDValue From2 = ParseBFI(CombineBFI.getNode(), ToMask2, FromMask2); 9379 assert(From1 == From2); 9380 (void)From2; 9381 9382 // First, unlink CombineBFI. 9383 DCI.DAG.ReplaceAllUsesWith(CombineBFI, CombineBFI.getOperand(0)); 9384 // Then create a new BFI, combining the two together. 9385 APInt NewFromMask = FromMask1 | FromMask2; 9386 APInt NewToMask = ToMask1 | ToMask2; 9387 9388 EVT VT = N->getValueType(0); 9389 SDLoc dl(N); 9390 9391 if (NewFromMask[0] == 0) 9392 From1 = DCI.DAG.getNode( 9393 ISD::SRL, dl, VT, From1, 9394 DCI.DAG.getConstant(NewFromMask.countTrailingZeros(), dl, VT)); 9395 return DCI.DAG.getNode(ARMISD::BFI, dl, VT, N->getOperand(0), From1, 9396 DCI.DAG.getConstant(~NewToMask, dl, VT)); 9397 } 9398 return SDValue(); 9399 } 9400 9401 /// PerformVMOVRRDCombine - Target-specific dag combine xforms for 9402 /// ARMISD::VMOVRRD. 9403 static SDValue PerformVMOVRRDCombine(SDNode *N, 9404 TargetLowering::DAGCombinerInfo &DCI, 9405 const ARMSubtarget *Subtarget) { 9406 // vmovrrd(vmovdrr x, y) -> x,y 9407 SDValue InDouble = N->getOperand(0); 9408 if (InDouble.getOpcode() == ARMISD::VMOVDRR && !Subtarget->isFPOnlySP()) 9409 return DCI.CombineTo(N, InDouble.getOperand(0), InDouble.getOperand(1)); 9410 9411 // vmovrrd(load f64) -> (load i32), (load i32) 9412 SDNode *InNode = InDouble.getNode(); 9413 if (ISD::isNormalLoad(InNode) && InNode->hasOneUse() && 9414 InNode->getValueType(0) == MVT::f64 && 9415 InNode->getOperand(1).getOpcode() == ISD::FrameIndex && 9416 !cast<LoadSDNode>(InNode)->isVolatile()) { 9417 // TODO: Should this be done for non-FrameIndex operands? 9418 LoadSDNode *LD = cast<LoadSDNode>(InNode); 9419 9420 SelectionDAG &DAG = DCI.DAG; 9421 SDLoc DL(LD); 9422 SDValue BasePtr = LD->getBasePtr(); 9423 SDValue NewLD1 = DAG.getLoad(MVT::i32, DL, LD->getChain(), BasePtr, 9424 LD->getPointerInfo(), LD->isVolatile(), 9425 LD->isNonTemporal(), LD->isInvariant(), 9426 LD->getAlignment()); 9427 9428 SDValue OffsetPtr = DAG.getNode(ISD::ADD, DL, MVT::i32, BasePtr, 9429 DAG.getConstant(4, DL, MVT::i32)); 9430 SDValue NewLD2 = DAG.getLoad(MVT::i32, DL, NewLD1.getValue(1), OffsetPtr, 9431 LD->getPointerInfo(), LD->isVolatile(), 9432 LD->isNonTemporal(), LD->isInvariant(), 9433 std::min(4U, LD->getAlignment() / 2)); 9434 9435 DAG.ReplaceAllUsesOfValueWith(SDValue(LD, 1), NewLD2.getValue(1)); 9436 if (DCI.DAG.getDataLayout().isBigEndian()) 9437 std::swap (NewLD1, NewLD2); 9438 SDValue Result = DCI.CombineTo(N, NewLD1, NewLD2); 9439 return Result; 9440 } 9441 9442 return SDValue(); 9443 } 9444 9445 /// PerformVMOVDRRCombine - Target-specific dag combine xforms for 9446 /// ARMISD::VMOVDRR. This is also used for BUILD_VECTORs with 2 operands. 9447 static SDValue PerformVMOVDRRCombine(SDNode *N, SelectionDAG &DAG) { 9448 // N=vmovrrd(X); vmovdrr(N:0, N:1) -> bit_convert(X) 9449 SDValue Op0 = N->getOperand(0); 9450 SDValue Op1 = N->getOperand(1); 9451 if (Op0.getOpcode() == ISD::BITCAST) 9452 Op0 = Op0.getOperand(0); 9453 if (Op1.getOpcode() == ISD::BITCAST) 9454 Op1 = Op1.getOperand(0); 9455 if (Op0.getOpcode() == ARMISD::VMOVRRD && 9456 Op0.getNode() == Op1.getNode() && 9457 Op0.getResNo() == 0 && Op1.getResNo() == 1) 9458 return DAG.getNode(ISD::BITCAST, SDLoc(N), 9459 N->getValueType(0), Op0.getOperand(0)); 9460 return SDValue(); 9461 } 9462 9463 /// hasNormalLoadOperand - Check if any of the operands of a BUILD_VECTOR node 9464 /// are normal, non-volatile loads. If so, it is profitable to bitcast an 9465 /// i64 vector to have f64 elements, since the value can then be loaded 9466 /// directly into a VFP register. 9467 static bool hasNormalLoadOperand(SDNode *N) { 9468 unsigned NumElts = N->getValueType(0).getVectorNumElements(); 9469 for (unsigned i = 0; i < NumElts; ++i) { 9470 SDNode *Elt = N->getOperand(i).getNode(); 9471 if (ISD::isNormalLoad(Elt) && !cast<LoadSDNode>(Elt)->isVolatile()) 9472 return true; 9473 } 9474 return false; 9475 } 9476 9477 /// PerformBUILD_VECTORCombine - Target-specific dag combine xforms for 9478 /// ISD::BUILD_VECTOR. 9479 static SDValue PerformBUILD_VECTORCombine(SDNode *N, 9480 TargetLowering::DAGCombinerInfo &DCI, 9481 const ARMSubtarget *Subtarget) { 9482 // build_vector(N=ARMISD::VMOVRRD(X), N:1) -> bit_convert(X): 9483 // VMOVRRD is introduced when legalizing i64 types. It forces the i64 value 9484 // into a pair of GPRs, which is fine when the value is used as a scalar, 9485 // but if the i64 value is converted to a vector, we need to undo the VMOVRRD. 9486 SelectionDAG &DAG = DCI.DAG; 9487 if (N->getNumOperands() == 2) 9488 if (SDValue RV = PerformVMOVDRRCombine(N, DAG)) 9489 return RV; 9490 9491 // Load i64 elements as f64 values so that type legalization does not split 9492 // them up into i32 values. 9493 EVT VT = N->getValueType(0); 9494 if (VT.getVectorElementType() != MVT::i64 || !hasNormalLoadOperand(N)) 9495 return SDValue(); 9496 SDLoc dl(N); 9497 SmallVector<SDValue, 8> Ops; 9498 unsigned NumElts = VT.getVectorNumElements(); 9499 for (unsigned i = 0; i < NumElts; ++i) { 9500 SDValue V = DAG.getNode(ISD::BITCAST, dl, MVT::f64, N->getOperand(i)); 9501 Ops.push_back(V); 9502 // Make the DAGCombiner fold the bitcast. 9503 DCI.AddToWorklist(V.getNode()); 9504 } 9505 EVT FloatVT = EVT::getVectorVT(*DAG.getContext(), MVT::f64, NumElts); 9506 SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, FloatVT, Ops); 9507 return DAG.getNode(ISD::BITCAST, dl, VT, BV); 9508 } 9509 9510 /// \brief Target-specific dag combine xforms for ARMISD::BUILD_VECTOR. 9511 static SDValue 9512 PerformARMBUILD_VECTORCombine(SDNode *N, TargetLowering::DAGCombinerInfo &DCI) { 9513 // ARMISD::BUILD_VECTOR is introduced when legalizing ISD::BUILD_VECTOR. 9514 // At that time, we may have inserted bitcasts from integer to float. 9515 // If these bitcasts have survived DAGCombine, change the lowering of this 9516 // BUILD_VECTOR in something more vector friendly, i.e., that does not 9517 // force to use floating point types. 9518 9519 // Make sure we can change the type of the vector. 9520 // This is possible iff: 9521 // 1. The vector is only used in a bitcast to a integer type. I.e., 9522 // 1.1. Vector is used only once. 9523 // 1.2. Use is a bit convert to an integer type. 9524 // 2. The size of its operands are 32-bits (64-bits are not legal). 9525 EVT VT = N->getValueType(0); 9526 EVT EltVT = VT.getVectorElementType(); 9527 9528 // Check 1.1. and 2. 9529 if (EltVT.getSizeInBits() != 32 || !N->hasOneUse()) 9530 return SDValue(); 9531 9532 // By construction, the input type must be float. 9533 assert(EltVT == MVT::f32 && "Unexpected type!"); 9534 9535 // Check 1.2. 9536 SDNode *Use = *N->use_begin(); 9537 if (Use->getOpcode() != ISD::BITCAST || 9538 Use->getValueType(0).isFloatingPoint()) 9539 return SDValue(); 9540 9541 // Check profitability. 9542 // Model is, if more than half of the relevant operands are bitcast from 9543 // i32, turn the build_vector into a sequence of insert_vector_elt. 9544 // Relevant operands are everything that is not statically 9545 // (i.e., at compile time) bitcasted. 9546 unsigned NumOfBitCastedElts = 0; 9547 unsigned NumElts = VT.getVectorNumElements(); 9548 unsigned NumOfRelevantElts = NumElts; 9549 for (unsigned Idx = 0; Idx < NumElts; ++Idx) { 9550 SDValue Elt = N->getOperand(Idx); 9551 if (Elt->getOpcode() == ISD::BITCAST) { 9552 // Assume only bit cast to i32 will go away. 9553 if (Elt->getOperand(0).getValueType() == MVT::i32) 9554 ++NumOfBitCastedElts; 9555 } else if (Elt.isUndef() || isa<ConstantSDNode>(Elt)) 9556 // Constants are statically casted, thus do not count them as 9557 // relevant operands. 9558 --NumOfRelevantElts; 9559 } 9560 9561 // Check if more than half of the elements require a non-free bitcast. 9562 if (NumOfBitCastedElts <= NumOfRelevantElts / 2) 9563 return SDValue(); 9564 9565 SelectionDAG &DAG = DCI.DAG; 9566 // Create the new vector type. 9567 EVT VecVT = EVT::getVectorVT(*DAG.getContext(), MVT::i32, NumElts); 9568 // Check if the type is legal. 9569 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 9570 if (!TLI.isTypeLegal(VecVT)) 9571 return SDValue(); 9572 9573 // Combine: 9574 // ARMISD::BUILD_VECTOR E1, E2, ..., EN. 9575 // => BITCAST INSERT_VECTOR_ELT 9576 // (INSERT_VECTOR_ELT (...), (BITCAST EN-1), N-1), 9577 // (BITCAST EN), N. 9578 SDValue Vec = DAG.getUNDEF(VecVT); 9579 SDLoc dl(N); 9580 for (unsigned Idx = 0 ; Idx < NumElts; ++Idx) { 9581 SDValue V = N->getOperand(Idx); 9582 if (V.isUndef()) 9583 continue; 9584 if (V.getOpcode() == ISD::BITCAST && 9585 V->getOperand(0).getValueType() == MVT::i32) 9586 // Fold obvious case. 9587 V = V.getOperand(0); 9588 else { 9589 V = DAG.getNode(ISD::BITCAST, SDLoc(V), MVT::i32, V); 9590 // Make the DAGCombiner fold the bitcasts. 9591 DCI.AddToWorklist(V.getNode()); 9592 } 9593 SDValue LaneIdx = DAG.getConstant(Idx, dl, MVT::i32); 9594 Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VecVT, Vec, V, LaneIdx); 9595 } 9596 Vec = DAG.getNode(ISD::BITCAST, dl, VT, Vec); 9597 // Make the DAGCombiner fold the bitcasts. 9598 DCI.AddToWorklist(Vec.getNode()); 9599 return Vec; 9600 } 9601 9602 /// PerformInsertEltCombine - Target-specific dag combine xforms for 9603 /// ISD::INSERT_VECTOR_ELT. 9604 static SDValue PerformInsertEltCombine(SDNode *N, 9605 TargetLowering::DAGCombinerInfo &DCI) { 9606 // Bitcast an i64 load inserted into a vector to f64. 9607 // Otherwise, the i64 value will be legalized to a pair of i32 values. 9608 EVT VT = N->getValueType(0); 9609 SDNode *Elt = N->getOperand(1).getNode(); 9610 if (VT.getVectorElementType() != MVT::i64 || 9611 !ISD::isNormalLoad(Elt) || cast<LoadSDNode>(Elt)->isVolatile()) 9612 return SDValue(); 9613 9614 SelectionDAG &DAG = DCI.DAG; 9615 SDLoc dl(N); 9616 EVT FloatVT = EVT::getVectorVT(*DAG.getContext(), MVT::f64, 9617 VT.getVectorNumElements()); 9618 SDValue Vec = DAG.getNode(ISD::BITCAST, dl, FloatVT, N->getOperand(0)); 9619 SDValue V = DAG.getNode(ISD::BITCAST, dl, MVT::f64, N->getOperand(1)); 9620 // Make the DAGCombiner fold the bitcasts. 9621 DCI.AddToWorklist(Vec.getNode()); 9622 DCI.AddToWorklist(V.getNode()); 9623 SDValue InsElt = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, FloatVT, 9624 Vec, V, N->getOperand(2)); 9625 return DAG.getNode(ISD::BITCAST, dl, VT, InsElt); 9626 } 9627 9628 /// PerformVECTOR_SHUFFLECombine - Target-specific dag combine xforms for 9629 /// ISD::VECTOR_SHUFFLE. 9630 static SDValue PerformVECTOR_SHUFFLECombine(SDNode *N, SelectionDAG &DAG) { 9631 // The LLVM shufflevector instruction does not require the shuffle mask 9632 // length to match the operand vector length, but ISD::VECTOR_SHUFFLE does 9633 // have that requirement. When translating to ISD::VECTOR_SHUFFLE, if the 9634 // operands do not match the mask length, they are extended by concatenating 9635 // them with undef vectors. That is probably the right thing for other 9636 // targets, but for NEON it is better to concatenate two double-register 9637 // size vector operands into a single quad-register size vector. Do that 9638 // transformation here: 9639 // shuffle(concat(v1, undef), concat(v2, undef)) -> 9640 // shuffle(concat(v1, v2), undef) 9641 SDValue Op0 = N->getOperand(0); 9642 SDValue Op1 = N->getOperand(1); 9643 if (Op0.getOpcode() != ISD::CONCAT_VECTORS || 9644 Op1.getOpcode() != ISD::CONCAT_VECTORS || 9645 Op0.getNumOperands() != 2 || 9646 Op1.getNumOperands() != 2) 9647 return SDValue(); 9648 SDValue Concat0Op1 = Op0.getOperand(1); 9649 SDValue Concat1Op1 = Op1.getOperand(1); 9650 if (!Concat0Op1.isUndef() || !Concat1Op1.isUndef()) 9651 return SDValue(); 9652 // Skip the transformation if any of the types are illegal. 9653 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 9654 EVT VT = N->getValueType(0); 9655 if (!TLI.isTypeLegal(VT) || 9656 !TLI.isTypeLegal(Concat0Op1.getValueType()) || 9657 !TLI.isTypeLegal(Concat1Op1.getValueType())) 9658 return SDValue(); 9659 9660 SDValue NewConcat = DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT, 9661 Op0.getOperand(0), Op1.getOperand(0)); 9662 // Translate the shuffle mask. 9663 SmallVector<int, 16> NewMask; 9664 unsigned NumElts = VT.getVectorNumElements(); 9665 unsigned HalfElts = NumElts/2; 9666 ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N); 9667 for (unsigned n = 0; n < NumElts; ++n) { 9668 int MaskElt = SVN->getMaskElt(n); 9669 int NewElt = -1; 9670 if (MaskElt < (int)HalfElts) 9671 NewElt = MaskElt; 9672 else if (MaskElt >= (int)NumElts && MaskElt < (int)(NumElts + HalfElts)) 9673 NewElt = HalfElts + MaskElt - NumElts; 9674 NewMask.push_back(NewElt); 9675 } 9676 return DAG.getVectorShuffle(VT, SDLoc(N), NewConcat, 9677 DAG.getUNDEF(VT), NewMask.data()); 9678 } 9679 9680 /// CombineBaseUpdate - Target-specific DAG combine function for VLDDUP, 9681 /// NEON load/store intrinsics, and generic vector load/stores, to merge 9682 /// base address updates. 9683 /// For generic load/stores, the memory type is assumed to be a vector. 9684 /// The caller is assumed to have checked legality. 9685 static SDValue CombineBaseUpdate(SDNode *N, 9686 TargetLowering::DAGCombinerInfo &DCI) { 9687 SelectionDAG &DAG = DCI.DAG; 9688 const bool isIntrinsic = (N->getOpcode() == ISD::INTRINSIC_VOID || 9689 N->getOpcode() == ISD::INTRINSIC_W_CHAIN); 9690 const bool isStore = N->getOpcode() == ISD::STORE; 9691 const unsigned AddrOpIdx = ((isIntrinsic || isStore) ? 2 : 1); 9692 SDValue Addr = N->getOperand(AddrOpIdx); 9693 MemSDNode *MemN = cast<MemSDNode>(N); 9694 SDLoc dl(N); 9695 9696 // Search for a use of the address operand that is an increment. 9697 for (SDNode::use_iterator UI = Addr.getNode()->use_begin(), 9698 UE = Addr.getNode()->use_end(); UI != UE; ++UI) { 9699 SDNode *User = *UI; 9700 if (User->getOpcode() != ISD::ADD || 9701 UI.getUse().getResNo() != Addr.getResNo()) 9702 continue; 9703 9704 // Check that the add is independent of the load/store. Otherwise, folding 9705 // it would create a cycle. 9706 if (User->isPredecessorOf(N) || N->isPredecessorOf(User)) 9707 continue; 9708 9709 // Find the new opcode for the updating load/store. 9710 bool isLoadOp = true; 9711 bool isLaneOp = false; 9712 unsigned NewOpc = 0; 9713 unsigned NumVecs = 0; 9714 if (isIntrinsic) { 9715 unsigned IntNo = cast<ConstantSDNode>(N->getOperand(1))->getZExtValue(); 9716 switch (IntNo) { 9717 default: llvm_unreachable("unexpected intrinsic for Neon base update"); 9718 case Intrinsic::arm_neon_vld1: NewOpc = ARMISD::VLD1_UPD; 9719 NumVecs = 1; break; 9720 case Intrinsic::arm_neon_vld2: NewOpc = ARMISD::VLD2_UPD; 9721 NumVecs = 2; break; 9722 case Intrinsic::arm_neon_vld3: NewOpc = ARMISD::VLD3_UPD; 9723 NumVecs = 3; break; 9724 case Intrinsic::arm_neon_vld4: NewOpc = ARMISD::VLD4_UPD; 9725 NumVecs = 4; break; 9726 case Intrinsic::arm_neon_vld2lane: NewOpc = ARMISD::VLD2LN_UPD; 9727 NumVecs = 2; isLaneOp = true; break; 9728 case Intrinsic::arm_neon_vld3lane: NewOpc = ARMISD::VLD3LN_UPD; 9729 NumVecs = 3; isLaneOp = true; break; 9730 case Intrinsic::arm_neon_vld4lane: NewOpc = ARMISD::VLD4LN_UPD; 9731 NumVecs = 4; isLaneOp = true; break; 9732 case Intrinsic::arm_neon_vst1: NewOpc = ARMISD::VST1_UPD; 9733 NumVecs = 1; isLoadOp = false; break; 9734 case Intrinsic::arm_neon_vst2: NewOpc = ARMISD::VST2_UPD; 9735 NumVecs = 2; isLoadOp = false; break; 9736 case Intrinsic::arm_neon_vst3: NewOpc = ARMISD::VST3_UPD; 9737 NumVecs = 3; isLoadOp = false; break; 9738 case Intrinsic::arm_neon_vst4: NewOpc = ARMISD::VST4_UPD; 9739 NumVecs = 4; isLoadOp = false; break; 9740 case Intrinsic::arm_neon_vst2lane: NewOpc = ARMISD::VST2LN_UPD; 9741 NumVecs = 2; isLoadOp = false; isLaneOp = true; break; 9742 case Intrinsic::arm_neon_vst3lane: NewOpc = ARMISD::VST3LN_UPD; 9743 NumVecs = 3; isLoadOp = false; isLaneOp = true; break; 9744 case Intrinsic::arm_neon_vst4lane: NewOpc = ARMISD::VST4LN_UPD; 9745 NumVecs = 4; isLoadOp = false; isLaneOp = true; break; 9746 } 9747 } else { 9748 isLaneOp = true; 9749 switch (N->getOpcode()) { 9750 default: llvm_unreachable("unexpected opcode for Neon base update"); 9751 case ARMISD::VLD2DUP: NewOpc = ARMISD::VLD2DUP_UPD; NumVecs = 2; break; 9752 case ARMISD::VLD3DUP: NewOpc = ARMISD::VLD3DUP_UPD; NumVecs = 3; break; 9753 case ARMISD::VLD4DUP: NewOpc = ARMISD::VLD4DUP_UPD; NumVecs = 4; break; 9754 case ISD::LOAD: NewOpc = ARMISD::VLD1_UPD; 9755 NumVecs = 1; isLaneOp = false; break; 9756 case ISD::STORE: NewOpc = ARMISD::VST1_UPD; 9757 NumVecs = 1; isLaneOp = false; isLoadOp = false; break; 9758 } 9759 } 9760 9761 // Find the size of memory referenced by the load/store. 9762 EVT VecTy; 9763 if (isLoadOp) { 9764 VecTy = N->getValueType(0); 9765 } else if (isIntrinsic) { 9766 VecTy = N->getOperand(AddrOpIdx+1).getValueType(); 9767 } else { 9768 assert(isStore && "Node has to be a load, a store, or an intrinsic!"); 9769 VecTy = N->getOperand(1).getValueType(); 9770 } 9771 9772 unsigned NumBytes = NumVecs * VecTy.getSizeInBits() / 8; 9773 if (isLaneOp) 9774 NumBytes /= VecTy.getVectorNumElements(); 9775 9776 // If the increment is a constant, it must match the memory ref size. 9777 SDValue Inc = User->getOperand(User->getOperand(0) == Addr ? 1 : 0); 9778 if (ConstantSDNode *CInc = dyn_cast<ConstantSDNode>(Inc.getNode())) { 9779 uint64_t IncVal = CInc->getZExtValue(); 9780 if (IncVal != NumBytes) 9781 continue; 9782 } else if (NumBytes >= 3 * 16) { 9783 // VLD3/4 and VST3/4 for 128-bit vectors are implemented with two 9784 // separate instructions that make it harder to use a non-constant update. 9785 continue; 9786 } 9787 9788 // OK, we found an ADD we can fold into the base update. 9789 // Now, create a _UPD node, taking care of not breaking alignment. 9790 9791 EVT AlignedVecTy = VecTy; 9792 unsigned Alignment = MemN->getAlignment(); 9793 9794 // If this is a less-than-standard-aligned load/store, change the type to 9795 // match the standard alignment. 9796 // The alignment is overlooked when selecting _UPD variants; and it's 9797 // easier to introduce bitcasts here than fix that. 9798 // There are 3 ways to get to this base-update combine: 9799 // - intrinsics: they are assumed to be properly aligned (to the standard 9800 // alignment of the memory type), so we don't need to do anything. 9801 // - ARMISD::VLDx nodes: they are only generated from the aforementioned 9802 // intrinsics, so, likewise, there's nothing to do. 9803 // - generic load/store instructions: the alignment is specified as an 9804 // explicit operand, rather than implicitly as the standard alignment 9805 // of the memory type (like the intrisics). We need to change the 9806 // memory type to match the explicit alignment. That way, we don't 9807 // generate non-standard-aligned ARMISD::VLDx nodes. 9808 if (isa<LSBaseSDNode>(N)) { 9809 if (Alignment == 0) 9810 Alignment = 1; 9811 if (Alignment < VecTy.getScalarSizeInBits() / 8) { 9812 MVT EltTy = MVT::getIntegerVT(Alignment * 8); 9813 assert(NumVecs == 1 && "Unexpected multi-element generic load/store."); 9814 assert(!isLaneOp && "Unexpected generic load/store lane."); 9815 unsigned NumElts = NumBytes / (EltTy.getSizeInBits() / 8); 9816 AlignedVecTy = MVT::getVectorVT(EltTy, NumElts); 9817 } 9818 // Don't set an explicit alignment on regular load/stores that we want 9819 // to transform to VLD/VST 1_UPD nodes. 9820 // This matches the behavior of regular load/stores, which only get an 9821 // explicit alignment if the MMO alignment is larger than the standard 9822 // alignment of the memory type. 9823 // Intrinsics, however, always get an explicit alignment, set to the 9824 // alignment of the MMO. 9825 Alignment = 1; 9826 } 9827 9828 // Create the new updating load/store node. 9829 // First, create an SDVTList for the new updating node's results. 9830 EVT Tys[6]; 9831 unsigned NumResultVecs = (isLoadOp ? NumVecs : 0); 9832 unsigned n; 9833 for (n = 0; n < NumResultVecs; ++n) 9834 Tys[n] = AlignedVecTy; 9835 Tys[n++] = MVT::i32; 9836 Tys[n] = MVT::Other; 9837 SDVTList SDTys = DAG.getVTList(makeArrayRef(Tys, NumResultVecs+2)); 9838 9839 // Then, gather the new node's operands. 9840 SmallVector<SDValue, 8> Ops; 9841 Ops.push_back(N->getOperand(0)); // incoming chain 9842 Ops.push_back(N->getOperand(AddrOpIdx)); 9843 Ops.push_back(Inc); 9844 9845 if (StoreSDNode *StN = dyn_cast<StoreSDNode>(N)) { 9846 // Try to match the intrinsic's signature 9847 Ops.push_back(StN->getValue()); 9848 } else { 9849 // Loads (and of course intrinsics) match the intrinsics' signature, 9850 // so just add all but the alignment operand. 9851 for (unsigned i = AddrOpIdx + 1; i < N->getNumOperands() - 1; ++i) 9852 Ops.push_back(N->getOperand(i)); 9853 } 9854 9855 // For all node types, the alignment operand is always the last one. 9856 Ops.push_back(DAG.getConstant(Alignment, dl, MVT::i32)); 9857 9858 // If this is a non-standard-aligned STORE, the penultimate operand is the 9859 // stored value. Bitcast it to the aligned type. 9860 if (AlignedVecTy != VecTy && N->getOpcode() == ISD::STORE) { 9861 SDValue &StVal = Ops[Ops.size()-2]; 9862 StVal = DAG.getNode(ISD::BITCAST, dl, AlignedVecTy, StVal); 9863 } 9864 9865 SDValue UpdN = DAG.getMemIntrinsicNode(NewOpc, dl, SDTys, 9866 Ops, AlignedVecTy, 9867 MemN->getMemOperand()); 9868 9869 // Update the uses. 9870 SmallVector<SDValue, 5> NewResults; 9871 for (unsigned i = 0; i < NumResultVecs; ++i) 9872 NewResults.push_back(SDValue(UpdN.getNode(), i)); 9873 9874 // If this is an non-standard-aligned LOAD, the first result is the loaded 9875 // value. Bitcast it to the expected result type. 9876 if (AlignedVecTy != VecTy && N->getOpcode() == ISD::LOAD) { 9877 SDValue &LdVal = NewResults[0]; 9878 LdVal = DAG.getNode(ISD::BITCAST, dl, VecTy, LdVal); 9879 } 9880 9881 NewResults.push_back(SDValue(UpdN.getNode(), NumResultVecs+1)); // chain 9882 DCI.CombineTo(N, NewResults); 9883 DCI.CombineTo(User, SDValue(UpdN.getNode(), NumResultVecs)); 9884 9885 break; 9886 } 9887 return SDValue(); 9888 } 9889 9890 static SDValue PerformVLDCombine(SDNode *N, 9891 TargetLowering::DAGCombinerInfo &DCI) { 9892 if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer()) 9893 return SDValue(); 9894 9895 return CombineBaseUpdate(N, DCI); 9896 } 9897 9898 /// CombineVLDDUP - For a VDUPLANE node N, check if its source operand is a 9899 /// vldN-lane (N > 1) intrinsic, and if all the other uses of that intrinsic 9900 /// are also VDUPLANEs. If so, combine them to a vldN-dup operation and 9901 /// return true. 9902 static bool CombineVLDDUP(SDNode *N, TargetLowering::DAGCombinerInfo &DCI) { 9903 SelectionDAG &DAG = DCI.DAG; 9904 EVT VT = N->getValueType(0); 9905 // vldN-dup instructions only support 64-bit vectors for N > 1. 9906 if (!VT.is64BitVector()) 9907 return false; 9908 9909 // Check if the VDUPLANE operand is a vldN-dup intrinsic. 9910 SDNode *VLD = N->getOperand(0).getNode(); 9911 if (VLD->getOpcode() != ISD::INTRINSIC_W_CHAIN) 9912 return false; 9913 unsigned NumVecs = 0; 9914 unsigned NewOpc = 0; 9915 unsigned IntNo = cast<ConstantSDNode>(VLD->getOperand(1))->getZExtValue(); 9916 if (IntNo == Intrinsic::arm_neon_vld2lane) { 9917 NumVecs = 2; 9918 NewOpc = ARMISD::VLD2DUP; 9919 } else if (IntNo == Intrinsic::arm_neon_vld3lane) { 9920 NumVecs = 3; 9921 NewOpc = ARMISD::VLD3DUP; 9922 } else if (IntNo == Intrinsic::arm_neon_vld4lane) { 9923 NumVecs = 4; 9924 NewOpc = ARMISD::VLD4DUP; 9925 } else { 9926 return false; 9927 } 9928 9929 // First check that all the vldN-lane uses are VDUPLANEs and that the lane 9930 // numbers match the load. 9931 unsigned VLDLaneNo = 9932 cast<ConstantSDNode>(VLD->getOperand(NumVecs+3))->getZExtValue(); 9933 for (SDNode::use_iterator UI = VLD->use_begin(), UE = VLD->use_end(); 9934 UI != UE; ++UI) { 9935 // Ignore uses of the chain result. 9936 if (UI.getUse().getResNo() == NumVecs) 9937 continue; 9938 SDNode *User = *UI; 9939 if (User->getOpcode() != ARMISD::VDUPLANE || 9940 VLDLaneNo != cast<ConstantSDNode>(User->getOperand(1))->getZExtValue()) 9941 return false; 9942 } 9943 9944 // Create the vldN-dup node. 9945 EVT Tys[5]; 9946 unsigned n; 9947 for (n = 0; n < NumVecs; ++n) 9948 Tys[n] = VT; 9949 Tys[n] = MVT::Other; 9950 SDVTList SDTys = DAG.getVTList(makeArrayRef(Tys, NumVecs+1)); 9951 SDValue Ops[] = { VLD->getOperand(0), VLD->getOperand(2) }; 9952 MemIntrinsicSDNode *VLDMemInt = cast<MemIntrinsicSDNode>(VLD); 9953 SDValue VLDDup = DAG.getMemIntrinsicNode(NewOpc, SDLoc(VLD), SDTys, 9954 Ops, VLDMemInt->getMemoryVT(), 9955 VLDMemInt->getMemOperand()); 9956 9957 // Update the uses. 9958 for (SDNode::use_iterator UI = VLD->use_begin(), UE = VLD->use_end(); 9959 UI != UE; ++UI) { 9960 unsigned ResNo = UI.getUse().getResNo(); 9961 // Ignore uses of the chain result. 9962 if (ResNo == NumVecs) 9963 continue; 9964 SDNode *User = *UI; 9965 DCI.CombineTo(User, SDValue(VLDDup.getNode(), ResNo)); 9966 } 9967 9968 // Now the vldN-lane intrinsic is dead except for its chain result. 9969 // Update uses of the chain. 9970 std::vector<SDValue> VLDDupResults; 9971 for (unsigned n = 0; n < NumVecs; ++n) 9972 VLDDupResults.push_back(SDValue(VLDDup.getNode(), n)); 9973 VLDDupResults.push_back(SDValue(VLDDup.getNode(), NumVecs)); 9974 DCI.CombineTo(VLD, VLDDupResults); 9975 9976 return true; 9977 } 9978 9979 /// PerformVDUPLANECombine - Target-specific dag combine xforms for 9980 /// ARMISD::VDUPLANE. 9981 static SDValue PerformVDUPLANECombine(SDNode *N, 9982 TargetLowering::DAGCombinerInfo &DCI) { 9983 SDValue Op = N->getOperand(0); 9984 9985 // If the source is a vldN-lane (N > 1) intrinsic, and all the other uses 9986 // of that intrinsic are also VDUPLANEs, combine them to a vldN-dup operation. 9987 if (CombineVLDDUP(N, DCI)) 9988 return SDValue(N, 0); 9989 9990 // If the source is already a VMOVIMM or VMVNIMM splat, the VDUPLANE is 9991 // redundant. Ignore bit_converts for now; element sizes are checked below. 9992 while (Op.getOpcode() == ISD::BITCAST) 9993 Op = Op.getOperand(0); 9994 if (Op.getOpcode() != ARMISD::VMOVIMM && Op.getOpcode() != ARMISD::VMVNIMM) 9995 return SDValue(); 9996 9997 // Make sure the VMOV element size is not bigger than the VDUPLANE elements. 9998 unsigned EltSize = Op.getValueType().getVectorElementType().getSizeInBits(); 9999 // The canonical VMOV for a zero vector uses a 32-bit element size. 10000 unsigned Imm = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue(); 10001 unsigned EltBits; 10002 if (ARM_AM::decodeNEONModImm(Imm, EltBits) == 0) 10003 EltSize = 8; 10004 EVT VT = N->getValueType(0); 10005 if (EltSize > VT.getVectorElementType().getSizeInBits()) 10006 return SDValue(); 10007 10008 return DCI.DAG.getNode(ISD::BITCAST, SDLoc(N), VT, Op); 10009 } 10010 10011 static SDValue PerformLOADCombine(SDNode *N, 10012 TargetLowering::DAGCombinerInfo &DCI) { 10013 EVT VT = N->getValueType(0); 10014 10015 // If this is a legal vector load, try to combine it into a VLD1_UPD. 10016 if (ISD::isNormalLoad(N) && VT.isVector() && 10017 DCI.DAG.getTargetLoweringInfo().isTypeLegal(VT)) 10018 return CombineBaseUpdate(N, DCI); 10019 10020 return SDValue(); 10021 } 10022 10023 /// PerformSTORECombine - Target-specific dag combine xforms for 10024 /// ISD::STORE. 10025 static SDValue PerformSTORECombine(SDNode *N, 10026 TargetLowering::DAGCombinerInfo &DCI) { 10027 StoreSDNode *St = cast<StoreSDNode>(N); 10028 if (St->isVolatile()) 10029 return SDValue(); 10030 10031 // Optimize trunc store (of multiple scalars) to shuffle and store. First, 10032 // pack all of the elements in one place. Next, store to memory in fewer 10033 // chunks. 10034 SDValue StVal = St->getValue(); 10035 EVT VT = StVal.getValueType(); 10036 if (St->isTruncatingStore() && VT.isVector()) { 10037 SelectionDAG &DAG = DCI.DAG; 10038 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 10039 EVT StVT = St->getMemoryVT(); 10040 unsigned NumElems = VT.getVectorNumElements(); 10041 assert(StVT != VT && "Cannot truncate to the same type"); 10042 unsigned FromEltSz = VT.getVectorElementType().getSizeInBits(); 10043 unsigned ToEltSz = StVT.getVectorElementType().getSizeInBits(); 10044 10045 // From, To sizes and ElemCount must be pow of two 10046 if (!isPowerOf2_32(NumElems * FromEltSz * ToEltSz)) return SDValue(); 10047 10048 // We are going to use the original vector elt for storing. 10049 // Accumulated smaller vector elements must be a multiple of the store size. 10050 if (0 != (NumElems * FromEltSz) % ToEltSz) return SDValue(); 10051 10052 unsigned SizeRatio = FromEltSz / ToEltSz; 10053 assert(SizeRatio * NumElems * ToEltSz == VT.getSizeInBits()); 10054 10055 // Create a type on which we perform the shuffle. 10056 EVT WideVecVT = EVT::getVectorVT(*DAG.getContext(), StVT.getScalarType(), 10057 NumElems*SizeRatio); 10058 assert(WideVecVT.getSizeInBits() == VT.getSizeInBits()); 10059 10060 SDLoc DL(St); 10061 SDValue WideVec = DAG.getNode(ISD::BITCAST, DL, WideVecVT, StVal); 10062 SmallVector<int, 8> ShuffleVec(NumElems * SizeRatio, -1); 10063 for (unsigned i = 0; i < NumElems; ++i) 10064 ShuffleVec[i] = DAG.getDataLayout().isBigEndian() 10065 ? (i + 1) * SizeRatio - 1 10066 : i * SizeRatio; 10067 10068 // Can't shuffle using an illegal type. 10069 if (!TLI.isTypeLegal(WideVecVT)) return SDValue(); 10070 10071 SDValue Shuff = DAG.getVectorShuffle(WideVecVT, DL, WideVec, 10072 DAG.getUNDEF(WideVec.getValueType()), 10073 ShuffleVec.data()); 10074 // At this point all of the data is stored at the bottom of the 10075 // register. We now need to save it to mem. 10076 10077 // Find the largest store unit 10078 MVT StoreType = MVT::i8; 10079 for (MVT Tp : MVT::integer_valuetypes()) { 10080 if (TLI.isTypeLegal(Tp) && Tp.getSizeInBits() <= NumElems * ToEltSz) 10081 StoreType = Tp; 10082 } 10083 // Didn't find a legal store type. 10084 if (!TLI.isTypeLegal(StoreType)) 10085 return SDValue(); 10086 10087 // Bitcast the original vector into a vector of store-size units 10088 EVT StoreVecVT = EVT::getVectorVT(*DAG.getContext(), 10089 StoreType, VT.getSizeInBits()/EVT(StoreType).getSizeInBits()); 10090 assert(StoreVecVT.getSizeInBits() == VT.getSizeInBits()); 10091 SDValue ShuffWide = DAG.getNode(ISD::BITCAST, DL, StoreVecVT, Shuff); 10092 SmallVector<SDValue, 8> Chains; 10093 SDValue Increment = DAG.getConstant(StoreType.getSizeInBits() / 8, DL, 10094 TLI.getPointerTy(DAG.getDataLayout())); 10095 SDValue BasePtr = St->getBasePtr(); 10096 10097 // Perform one or more big stores into memory. 10098 unsigned E = (ToEltSz*NumElems)/StoreType.getSizeInBits(); 10099 for (unsigned I = 0; I < E; I++) { 10100 SDValue SubVec = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, 10101 StoreType, ShuffWide, 10102 DAG.getIntPtrConstant(I, DL)); 10103 SDValue Ch = DAG.getStore(St->getChain(), DL, SubVec, BasePtr, 10104 St->getPointerInfo(), St->isVolatile(), 10105 St->isNonTemporal(), St->getAlignment()); 10106 BasePtr = DAG.getNode(ISD::ADD, DL, BasePtr.getValueType(), BasePtr, 10107 Increment); 10108 Chains.push_back(Ch); 10109 } 10110 return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Chains); 10111 } 10112 10113 if (!ISD::isNormalStore(St)) 10114 return SDValue(); 10115 10116 // Split a store of a VMOVDRR into two integer stores to avoid mixing NEON and 10117 // ARM stores of arguments in the same cache line. 10118 if (StVal.getNode()->getOpcode() == ARMISD::VMOVDRR && 10119 StVal.getNode()->hasOneUse()) { 10120 SelectionDAG &DAG = DCI.DAG; 10121 bool isBigEndian = DAG.getDataLayout().isBigEndian(); 10122 SDLoc DL(St); 10123 SDValue BasePtr = St->getBasePtr(); 10124 SDValue NewST1 = DAG.getStore(St->getChain(), DL, 10125 StVal.getNode()->getOperand(isBigEndian ? 1 : 0 ), 10126 BasePtr, St->getPointerInfo(), St->isVolatile(), 10127 St->isNonTemporal(), St->getAlignment()); 10128 10129 SDValue OffsetPtr = DAG.getNode(ISD::ADD, DL, MVT::i32, BasePtr, 10130 DAG.getConstant(4, DL, MVT::i32)); 10131 return DAG.getStore(NewST1.getValue(0), DL, 10132 StVal.getNode()->getOperand(isBigEndian ? 0 : 1), 10133 OffsetPtr, St->getPointerInfo(), St->isVolatile(), 10134 St->isNonTemporal(), 10135 std::min(4U, St->getAlignment() / 2)); 10136 } 10137 10138 if (StVal.getValueType() == MVT::i64 && 10139 StVal.getNode()->getOpcode() == ISD::EXTRACT_VECTOR_ELT) { 10140 10141 // Bitcast an i64 store extracted from a vector to f64. 10142 // Otherwise, the i64 value will be legalized to a pair of i32 values. 10143 SelectionDAG &DAG = DCI.DAG; 10144 SDLoc dl(StVal); 10145 SDValue IntVec = StVal.getOperand(0); 10146 EVT FloatVT = EVT::getVectorVT(*DAG.getContext(), MVT::f64, 10147 IntVec.getValueType().getVectorNumElements()); 10148 SDValue Vec = DAG.getNode(ISD::BITCAST, dl, FloatVT, IntVec); 10149 SDValue ExtElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, 10150 Vec, StVal.getOperand(1)); 10151 dl = SDLoc(N); 10152 SDValue V = DAG.getNode(ISD::BITCAST, dl, MVT::i64, ExtElt); 10153 // Make the DAGCombiner fold the bitcasts. 10154 DCI.AddToWorklist(Vec.getNode()); 10155 DCI.AddToWorklist(ExtElt.getNode()); 10156 DCI.AddToWorklist(V.getNode()); 10157 return DAG.getStore(St->getChain(), dl, V, St->getBasePtr(), 10158 St->getPointerInfo(), St->isVolatile(), 10159 St->isNonTemporal(), St->getAlignment(), 10160 St->getAAInfo()); 10161 } 10162 10163 // If this is a legal vector store, try to combine it into a VST1_UPD. 10164 if (ISD::isNormalStore(N) && VT.isVector() && 10165 DCI.DAG.getTargetLoweringInfo().isTypeLegal(VT)) 10166 return CombineBaseUpdate(N, DCI); 10167 10168 return SDValue(); 10169 } 10170 10171 /// PerformVCVTCombine - VCVT (floating-point to fixed-point, Advanced SIMD) 10172 /// can replace combinations of VMUL and VCVT (floating-point to integer) 10173 /// when the VMUL has a constant operand that is a power of 2. 10174 /// 10175 /// Example (assume d17 = <float 8.000000e+00, float 8.000000e+00>): 10176 /// vmul.f32 d16, d17, d16 10177 /// vcvt.s32.f32 d16, d16 10178 /// becomes: 10179 /// vcvt.s32.f32 d16, d16, #3 10180 static SDValue PerformVCVTCombine(SDNode *N, SelectionDAG &DAG, 10181 const ARMSubtarget *Subtarget) { 10182 if (!Subtarget->hasNEON()) 10183 return SDValue(); 10184 10185 SDValue Op = N->getOperand(0); 10186 if (!Op.getValueType().isVector() || !Op.getValueType().isSimple() || 10187 Op.getOpcode() != ISD::FMUL) 10188 return SDValue(); 10189 10190 SDValue ConstVec = Op->getOperand(1); 10191 if (!isa<BuildVectorSDNode>(ConstVec)) 10192 return SDValue(); 10193 10194 MVT FloatTy = Op.getSimpleValueType().getVectorElementType(); 10195 uint32_t FloatBits = FloatTy.getSizeInBits(); 10196 MVT IntTy = N->getSimpleValueType(0).getVectorElementType(); 10197 uint32_t IntBits = IntTy.getSizeInBits(); 10198 unsigned NumLanes = Op.getValueType().getVectorNumElements(); 10199 if (FloatBits != 32 || IntBits > 32 || NumLanes > 4) { 10200 // These instructions only exist converting from f32 to i32. We can handle 10201 // smaller integers by generating an extra truncate, but larger ones would 10202 // be lossy. We also can't handle more then 4 lanes, since these intructions 10203 // only support v2i32/v4i32 types. 10204 return SDValue(); 10205 } 10206 10207 BitVector UndefElements; 10208 BuildVectorSDNode *BV = cast<BuildVectorSDNode>(ConstVec); 10209 int32_t C = BV->getConstantFPSplatPow2ToLog2Int(&UndefElements, 33); 10210 if (C == -1 || C == 0 || C > 32) 10211 return SDValue(); 10212 10213 SDLoc dl(N); 10214 bool isSigned = N->getOpcode() == ISD::FP_TO_SINT; 10215 unsigned IntrinsicOpcode = isSigned ? Intrinsic::arm_neon_vcvtfp2fxs : 10216 Intrinsic::arm_neon_vcvtfp2fxu; 10217 SDValue FixConv = DAG.getNode( 10218 ISD::INTRINSIC_WO_CHAIN, dl, NumLanes == 2 ? MVT::v2i32 : MVT::v4i32, 10219 DAG.getConstant(IntrinsicOpcode, dl, MVT::i32), Op->getOperand(0), 10220 DAG.getConstant(C, dl, MVT::i32)); 10221 10222 if (IntBits < FloatBits) 10223 FixConv = DAG.getNode(ISD::TRUNCATE, dl, N->getValueType(0), FixConv); 10224 10225 return FixConv; 10226 } 10227 10228 /// PerformVDIVCombine - VCVT (fixed-point to floating-point, Advanced SIMD) 10229 /// can replace combinations of VCVT (integer to floating-point) and VDIV 10230 /// when the VDIV has a constant operand that is a power of 2. 10231 /// 10232 /// Example (assume d17 = <float 8.000000e+00, float 8.000000e+00>): 10233 /// vcvt.f32.s32 d16, d16 10234 /// vdiv.f32 d16, d17, d16 10235 /// becomes: 10236 /// vcvt.f32.s32 d16, d16, #3 10237 static SDValue PerformVDIVCombine(SDNode *N, SelectionDAG &DAG, 10238 const ARMSubtarget *Subtarget) { 10239 if (!Subtarget->hasNEON()) 10240 return SDValue(); 10241 10242 SDValue Op = N->getOperand(0); 10243 unsigned OpOpcode = Op.getNode()->getOpcode(); 10244 if (!N->getValueType(0).isVector() || !N->getValueType(0).isSimple() || 10245 (OpOpcode != ISD::SINT_TO_FP && OpOpcode != ISD::UINT_TO_FP)) 10246 return SDValue(); 10247 10248 SDValue ConstVec = N->getOperand(1); 10249 if (!isa<BuildVectorSDNode>(ConstVec)) 10250 return SDValue(); 10251 10252 MVT FloatTy = N->getSimpleValueType(0).getVectorElementType(); 10253 uint32_t FloatBits = FloatTy.getSizeInBits(); 10254 MVT IntTy = Op.getOperand(0).getSimpleValueType().getVectorElementType(); 10255 uint32_t IntBits = IntTy.getSizeInBits(); 10256 unsigned NumLanes = Op.getValueType().getVectorNumElements(); 10257 if (FloatBits != 32 || IntBits > 32 || NumLanes > 4) { 10258 // These instructions only exist converting from i32 to f32. We can handle 10259 // smaller integers by generating an extra extend, but larger ones would 10260 // be lossy. We also can't handle more then 4 lanes, since these intructions 10261 // only support v2i32/v4i32 types. 10262 return SDValue(); 10263 } 10264 10265 BitVector UndefElements; 10266 BuildVectorSDNode *BV = cast<BuildVectorSDNode>(ConstVec); 10267 int32_t C = BV->getConstantFPSplatPow2ToLog2Int(&UndefElements, 33); 10268 if (C == -1 || C == 0 || C > 32) 10269 return SDValue(); 10270 10271 SDLoc dl(N); 10272 bool isSigned = OpOpcode == ISD::SINT_TO_FP; 10273 SDValue ConvInput = Op.getOperand(0); 10274 if (IntBits < FloatBits) 10275 ConvInput = DAG.getNode(isSigned ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND, 10276 dl, NumLanes == 2 ? MVT::v2i32 : MVT::v4i32, 10277 ConvInput); 10278 10279 unsigned IntrinsicOpcode = isSigned ? Intrinsic::arm_neon_vcvtfxs2fp : 10280 Intrinsic::arm_neon_vcvtfxu2fp; 10281 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, 10282 Op.getValueType(), 10283 DAG.getConstant(IntrinsicOpcode, dl, MVT::i32), 10284 ConvInput, DAG.getConstant(C, dl, MVT::i32)); 10285 } 10286 10287 /// Getvshiftimm - Check if this is a valid build_vector for the immediate 10288 /// operand of a vector shift operation, where all the elements of the 10289 /// build_vector must have the same constant integer value. 10290 static bool getVShiftImm(SDValue Op, unsigned ElementBits, int64_t &Cnt) { 10291 // Ignore bit_converts. 10292 while (Op.getOpcode() == ISD::BITCAST) 10293 Op = Op.getOperand(0); 10294 BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(Op.getNode()); 10295 APInt SplatBits, SplatUndef; 10296 unsigned SplatBitSize; 10297 bool HasAnyUndefs; 10298 if (! BVN || ! BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, 10299 HasAnyUndefs, ElementBits) || 10300 SplatBitSize > ElementBits) 10301 return false; 10302 Cnt = SplatBits.getSExtValue(); 10303 return true; 10304 } 10305 10306 /// isVShiftLImm - Check if this is a valid build_vector for the immediate 10307 /// operand of a vector shift left operation. That value must be in the range: 10308 /// 0 <= Value < ElementBits for a left shift; or 10309 /// 0 <= Value <= ElementBits for a long left shift. 10310 static bool isVShiftLImm(SDValue Op, EVT VT, bool isLong, int64_t &Cnt) { 10311 assert(VT.isVector() && "vector shift count is not a vector type"); 10312 int64_t ElementBits = VT.getVectorElementType().getSizeInBits(); 10313 if (! getVShiftImm(Op, ElementBits, Cnt)) 10314 return false; 10315 return (Cnt >= 0 && (isLong ? Cnt-1 : Cnt) < ElementBits); 10316 } 10317 10318 /// isVShiftRImm - Check if this is a valid build_vector for the immediate 10319 /// operand of a vector shift right operation. For a shift opcode, the value 10320 /// is positive, but for an intrinsic the value count must be negative. The 10321 /// absolute value must be in the range: 10322 /// 1 <= |Value| <= ElementBits for a right shift; or 10323 /// 1 <= |Value| <= ElementBits/2 for a narrow right shift. 10324 static bool isVShiftRImm(SDValue Op, EVT VT, bool isNarrow, bool isIntrinsic, 10325 int64_t &Cnt) { 10326 assert(VT.isVector() && "vector shift count is not a vector type"); 10327 int64_t ElementBits = VT.getVectorElementType().getSizeInBits(); 10328 if (! getVShiftImm(Op, ElementBits, Cnt)) 10329 return false; 10330 if (!isIntrinsic) 10331 return (Cnt >= 1 && Cnt <= (isNarrow ? ElementBits/2 : ElementBits)); 10332 if (Cnt >= -(isNarrow ? ElementBits/2 : ElementBits) && Cnt <= -1) { 10333 Cnt = -Cnt; 10334 return true; 10335 } 10336 return false; 10337 } 10338 10339 /// PerformIntrinsicCombine - ARM-specific DAG combining for intrinsics. 10340 static SDValue PerformIntrinsicCombine(SDNode *N, SelectionDAG &DAG) { 10341 unsigned IntNo = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue(); 10342 switch (IntNo) { 10343 default: 10344 // Don't do anything for most intrinsics. 10345 break; 10346 10347 // Vector shifts: check for immediate versions and lower them. 10348 // Note: This is done during DAG combining instead of DAG legalizing because 10349 // the build_vectors for 64-bit vector element shift counts are generally 10350 // not legal, and it is hard to see their values after they get legalized to 10351 // loads from a constant pool. 10352 case Intrinsic::arm_neon_vshifts: 10353 case Intrinsic::arm_neon_vshiftu: 10354 case Intrinsic::arm_neon_vrshifts: 10355 case Intrinsic::arm_neon_vrshiftu: 10356 case Intrinsic::arm_neon_vrshiftn: 10357 case Intrinsic::arm_neon_vqshifts: 10358 case Intrinsic::arm_neon_vqshiftu: 10359 case Intrinsic::arm_neon_vqshiftsu: 10360 case Intrinsic::arm_neon_vqshiftns: 10361 case Intrinsic::arm_neon_vqshiftnu: 10362 case Intrinsic::arm_neon_vqshiftnsu: 10363 case Intrinsic::arm_neon_vqrshiftns: 10364 case Intrinsic::arm_neon_vqrshiftnu: 10365 case Intrinsic::arm_neon_vqrshiftnsu: { 10366 EVT VT = N->getOperand(1).getValueType(); 10367 int64_t Cnt; 10368 unsigned VShiftOpc = 0; 10369 10370 switch (IntNo) { 10371 case Intrinsic::arm_neon_vshifts: 10372 case Intrinsic::arm_neon_vshiftu: 10373 if (isVShiftLImm(N->getOperand(2), VT, false, Cnt)) { 10374 VShiftOpc = ARMISD::VSHL; 10375 break; 10376 } 10377 if (isVShiftRImm(N->getOperand(2), VT, false, true, Cnt)) { 10378 VShiftOpc = (IntNo == Intrinsic::arm_neon_vshifts ? 10379 ARMISD::VSHRs : ARMISD::VSHRu); 10380 break; 10381 } 10382 return SDValue(); 10383 10384 case Intrinsic::arm_neon_vrshifts: 10385 case Intrinsic::arm_neon_vrshiftu: 10386 if (isVShiftRImm(N->getOperand(2), VT, false, true, Cnt)) 10387 break; 10388 return SDValue(); 10389 10390 case Intrinsic::arm_neon_vqshifts: 10391 case Intrinsic::arm_neon_vqshiftu: 10392 if (isVShiftLImm(N->getOperand(2), VT, false, Cnt)) 10393 break; 10394 return SDValue(); 10395 10396 case Intrinsic::arm_neon_vqshiftsu: 10397 if (isVShiftLImm(N->getOperand(2), VT, false, Cnt)) 10398 break; 10399 llvm_unreachable("invalid shift count for vqshlu intrinsic"); 10400 10401 case Intrinsic::arm_neon_vrshiftn: 10402 case Intrinsic::arm_neon_vqshiftns: 10403 case Intrinsic::arm_neon_vqshiftnu: 10404 case Intrinsic::arm_neon_vqshiftnsu: 10405 case Intrinsic::arm_neon_vqrshiftns: 10406 case Intrinsic::arm_neon_vqrshiftnu: 10407 case Intrinsic::arm_neon_vqrshiftnsu: 10408 // Narrowing shifts require an immediate right shift. 10409 if (isVShiftRImm(N->getOperand(2), VT, true, true, Cnt)) 10410 break; 10411 llvm_unreachable("invalid shift count for narrowing vector shift " 10412 "intrinsic"); 10413 10414 default: 10415 llvm_unreachable("unhandled vector shift"); 10416 } 10417 10418 switch (IntNo) { 10419 case Intrinsic::arm_neon_vshifts: 10420 case Intrinsic::arm_neon_vshiftu: 10421 // Opcode already set above. 10422 break; 10423 case Intrinsic::arm_neon_vrshifts: 10424 VShiftOpc = ARMISD::VRSHRs; break; 10425 case Intrinsic::arm_neon_vrshiftu: 10426 VShiftOpc = ARMISD::VRSHRu; break; 10427 case Intrinsic::arm_neon_vrshiftn: 10428 VShiftOpc = ARMISD::VRSHRN; break; 10429 case Intrinsic::arm_neon_vqshifts: 10430 VShiftOpc = ARMISD::VQSHLs; break; 10431 case Intrinsic::arm_neon_vqshiftu: 10432 VShiftOpc = ARMISD::VQSHLu; break; 10433 case Intrinsic::arm_neon_vqshiftsu: 10434 VShiftOpc = ARMISD::VQSHLsu; break; 10435 case Intrinsic::arm_neon_vqshiftns: 10436 VShiftOpc = ARMISD::VQSHRNs; break; 10437 case Intrinsic::arm_neon_vqshiftnu: 10438 VShiftOpc = ARMISD::VQSHRNu; break; 10439 case Intrinsic::arm_neon_vqshiftnsu: 10440 VShiftOpc = ARMISD::VQSHRNsu; break; 10441 case Intrinsic::arm_neon_vqrshiftns: 10442 VShiftOpc = ARMISD::VQRSHRNs; break; 10443 case Intrinsic::arm_neon_vqrshiftnu: 10444 VShiftOpc = ARMISD::VQRSHRNu; break; 10445 case Intrinsic::arm_neon_vqrshiftnsu: 10446 VShiftOpc = ARMISD::VQRSHRNsu; break; 10447 } 10448 10449 SDLoc dl(N); 10450 return DAG.getNode(VShiftOpc, dl, N->getValueType(0), 10451 N->getOperand(1), DAG.getConstant(Cnt, dl, MVT::i32)); 10452 } 10453 10454 case Intrinsic::arm_neon_vshiftins: { 10455 EVT VT = N->getOperand(1).getValueType(); 10456 int64_t Cnt; 10457 unsigned VShiftOpc = 0; 10458 10459 if (isVShiftLImm(N->getOperand(3), VT, false, Cnt)) 10460 VShiftOpc = ARMISD::VSLI; 10461 else if (isVShiftRImm(N->getOperand(3), VT, false, true, Cnt)) 10462 VShiftOpc = ARMISD::VSRI; 10463 else { 10464 llvm_unreachable("invalid shift count for vsli/vsri intrinsic"); 10465 } 10466 10467 SDLoc dl(N); 10468 return DAG.getNode(VShiftOpc, dl, N->getValueType(0), 10469 N->getOperand(1), N->getOperand(2), 10470 DAG.getConstant(Cnt, dl, MVT::i32)); 10471 } 10472 10473 case Intrinsic::arm_neon_vqrshifts: 10474 case Intrinsic::arm_neon_vqrshiftu: 10475 // No immediate versions of these to check for. 10476 break; 10477 } 10478 10479 return SDValue(); 10480 } 10481 10482 /// PerformShiftCombine - Checks for immediate versions of vector shifts and 10483 /// lowers them. As with the vector shift intrinsics, this is done during DAG 10484 /// combining instead of DAG legalizing because the build_vectors for 64-bit 10485 /// vector element shift counts are generally not legal, and it is hard to see 10486 /// their values after they get legalized to loads from a constant pool. 10487 static SDValue PerformShiftCombine(SDNode *N, SelectionDAG &DAG, 10488 const ARMSubtarget *ST) { 10489 EVT VT = N->getValueType(0); 10490 if (N->getOpcode() == ISD::SRL && VT == MVT::i32 && ST->hasV6Ops()) { 10491 // Canonicalize (srl (bswap x), 16) to (rotr (bswap x), 16) if the high 10492 // 16-bits of x is zero. This optimizes rev + lsr 16 to rev16. 10493 SDValue N1 = N->getOperand(1); 10494 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(N1)) { 10495 SDValue N0 = N->getOperand(0); 10496 if (C->getZExtValue() == 16 && N0.getOpcode() == ISD::BSWAP && 10497 DAG.MaskedValueIsZero(N0.getOperand(0), 10498 APInt::getHighBitsSet(32, 16))) 10499 return DAG.getNode(ISD::ROTR, SDLoc(N), VT, N0, N1); 10500 } 10501 } 10502 10503 // Nothing to be done for scalar shifts. 10504 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 10505 if (!VT.isVector() || !TLI.isTypeLegal(VT)) 10506 return SDValue(); 10507 10508 assert(ST->hasNEON() && "unexpected vector shift"); 10509 int64_t Cnt; 10510 10511 switch (N->getOpcode()) { 10512 default: llvm_unreachable("unexpected shift opcode"); 10513 10514 case ISD::SHL: 10515 if (isVShiftLImm(N->getOperand(1), VT, false, Cnt)) { 10516 SDLoc dl(N); 10517 return DAG.getNode(ARMISD::VSHL, dl, VT, N->getOperand(0), 10518 DAG.getConstant(Cnt, dl, MVT::i32)); 10519 } 10520 break; 10521 10522 case ISD::SRA: 10523 case ISD::SRL: 10524 if (isVShiftRImm(N->getOperand(1), VT, false, false, Cnt)) { 10525 unsigned VShiftOpc = (N->getOpcode() == ISD::SRA ? 10526 ARMISD::VSHRs : ARMISD::VSHRu); 10527 SDLoc dl(N); 10528 return DAG.getNode(VShiftOpc, dl, VT, N->getOperand(0), 10529 DAG.getConstant(Cnt, dl, MVT::i32)); 10530 } 10531 } 10532 return SDValue(); 10533 } 10534 10535 /// PerformExtendCombine - Target-specific DAG combining for ISD::SIGN_EXTEND, 10536 /// ISD::ZERO_EXTEND, and ISD::ANY_EXTEND. 10537 static SDValue PerformExtendCombine(SDNode *N, SelectionDAG &DAG, 10538 const ARMSubtarget *ST) { 10539 SDValue N0 = N->getOperand(0); 10540 10541 // Check for sign- and zero-extensions of vector extract operations of 8- 10542 // and 16-bit vector elements. NEON supports these directly. They are 10543 // handled during DAG combining because type legalization will promote them 10544 // to 32-bit types and it is messy to recognize the operations after that. 10545 if (ST->hasNEON() && N0.getOpcode() == ISD::EXTRACT_VECTOR_ELT) { 10546 SDValue Vec = N0.getOperand(0); 10547 SDValue Lane = N0.getOperand(1); 10548 EVT VT = N->getValueType(0); 10549 EVT EltVT = N0.getValueType(); 10550 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 10551 10552 if (VT == MVT::i32 && 10553 (EltVT == MVT::i8 || EltVT == MVT::i16) && 10554 TLI.isTypeLegal(Vec.getValueType()) && 10555 isa<ConstantSDNode>(Lane)) { 10556 10557 unsigned Opc = 0; 10558 switch (N->getOpcode()) { 10559 default: llvm_unreachable("unexpected opcode"); 10560 case ISD::SIGN_EXTEND: 10561 Opc = ARMISD::VGETLANEs; 10562 break; 10563 case ISD::ZERO_EXTEND: 10564 case ISD::ANY_EXTEND: 10565 Opc = ARMISD::VGETLANEu; 10566 break; 10567 } 10568 return DAG.getNode(Opc, SDLoc(N), VT, Vec, Lane); 10569 } 10570 } 10571 10572 return SDValue(); 10573 } 10574 10575 static void computeKnownBits(SelectionDAG &DAG, SDValue Op, APInt &KnownZero, 10576 APInt &KnownOne) { 10577 if (Op.getOpcode() == ARMISD::BFI) { 10578 // Conservatively, we can recurse down the first operand 10579 // and just mask out all affected bits. 10580 computeKnownBits(DAG, Op.getOperand(0), KnownZero, KnownOne); 10581 10582 // The operand to BFI is already a mask suitable for removing the bits it 10583 // sets. 10584 ConstantSDNode *CI = cast<ConstantSDNode>(Op.getOperand(2)); 10585 APInt Mask = CI->getAPIntValue(); 10586 KnownZero &= Mask; 10587 KnownOne &= Mask; 10588 return; 10589 } 10590 if (Op.getOpcode() == ARMISD::CMOV) { 10591 APInt KZ2(KnownZero.getBitWidth(), 0); 10592 APInt KO2(KnownOne.getBitWidth(), 0); 10593 computeKnownBits(DAG, Op.getOperand(1), KnownZero, KnownOne); 10594 computeKnownBits(DAG, Op.getOperand(2), KZ2, KO2); 10595 10596 KnownZero &= KZ2; 10597 KnownOne &= KO2; 10598 return; 10599 } 10600 return DAG.computeKnownBits(Op, KnownZero, KnownOne); 10601 } 10602 10603 SDValue ARMTargetLowering::PerformCMOVToBFICombine(SDNode *CMOV, SelectionDAG &DAG) const { 10604 // If we have a CMOV, OR and AND combination such as: 10605 // if (x & CN) 10606 // y |= CM; 10607 // 10608 // And: 10609 // * CN is a single bit; 10610 // * All bits covered by CM are known zero in y 10611 // 10612 // Then we can convert this into a sequence of BFI instructions. This will 10613 // always be a win if CM is a single bit, will always be no worse than the 10614 // TST&OR sequence if CM is two bits, and for thumb will be no worse if CM is 10615 // three bits (due to the extra IT instruction). 10616 10617 SDValue Op0 = CMOV->getOperand(0); 10618 SDValue Op1 = CMOV->getOperand(1); 10619 auto CCNode = cast<ConstantSDNode>(CMOV->getOperand(2)); 10620 auto CC = CCNode->getAPIntValue().getLimitedValue(); 10621 SDValue CmpZ = CMOV->getOperand(4); 10622 10623 // The compare must be against zero. 10624 if (!isNullConstant(CmpZ->getOperand(1))) 10625 return SDValue(); 10626 10627 assert(CmpZ->getOpcode() == ARMISD::CMPZ); 10628 SDValue And = CmpZ->getOperand(0); 10629 if (And->getOpcode() != ISD::AND) 10630 return SDValue(); 10631 ConstantSDNode *AndC = dyn_cast<ConstantSDNode>(And->getOperand(1)); 10632 if (!AndC || !AndC->getAPIntValue().isPowerOf2()) 10633 return SDValue(); 10634 SDValue X = And->getOperand(0); 10635 10636 if (CC == ARMCC::EQ) { 10637 // We're performing an "equal to zero" compare. Swap the operands so we 10638 // canonicalize on a "not equal to zero" compare. 10639 std::swap(Op0, Op1); 10640 } else { 10641 assert(CC == ARMCC::NE && "How can a CMPZ node not be EQ or NE?"); 10642 } 10643 10644 if (Op1->getOpcode() != ISD::OR) 10645 return SDValue(); 10646 10647 ConstantSDNode *OrC = dyn_cast<ConstantSDNode>(Op1->getOperand(1)); 10648 if (!OrC) 10649 return SDValue(); 10650 SDValue Y = Op1->getOperand(0); 10651 10652 if (Op0 != Y) 10653 return SDValue(); 10654 10655 // Now, is it profitable to continue? 10656 APInt OrCI = OrC->getAPIntValue(); 10657 unsigned Heuristic = Subtarget->isThumb() ? 3 : 2; 10658 if (OrCI.countPopulation() > Heuristic) 10659 return SDValue(); 10660 10661 // Lastly, can we determine that the bits defined by OrCI 10662 // are zero in Y? 10663 APInt KnownZero, KnownOne; 10664 computeKnownBits(DAG, Y, KnownZero, KnownOne); 10665 if ((OrCI & KnownZero) != OrCI) 10666 return SDValue(); 10667 10668 // OK, we can do the combine. 10669 SDValue V = Y; 10670 SDLoc dl(X); 10671 EVT VT = X.getValueType(); 10672 unsigned BitInX = AndC->getAPIntValue().logBase2(); 10673 10674 if (BitInX != 0) { 10675 // We must shift X first. 10676 X = DAG.getNode(ISD::SRL, dl, VT, X, 10677 DAG.getConstant(BitInX, dl, VT)); 10678 } 10679 10680 for (unsigned BitInY = 0, NumActiveBits = OrCI.getActiveBits(); 10681 BitInY < NumActiveBits; ++BitInY) { 10682 if (OrCI[BitInY] == 0) 10683 continue; 10684 APInt Mask(VT.getSizeInBits(), 0); 10685 Mask.setBit(BitInY); 10686 V = DAG.getNode(ARMISD::BFI, dl, VT, V, X, 10687 // Confusingly, the operand is an *inverted* mask. 10688 DAG.getConstant(~Mask, dl, VT)); 10689 } 10690 10691 return V; 10692 } 10693 10694 /// PerformBRCONDCombine - Target-specific DAG combining for ARMISD::BRCOND. 10695 SDValue 10696 ARMTargetLowering::PerformBRCONDCombine(SDNode *N, SelectionDAG &DAG) const { 10697 SDValue Cmp = N->getOperand(4); 10698 if (Cmp.getOpcode() != ARMISD::CMPZ) 10699 // Only looking at NE cases. 10700 return SDValue(); 10701 10702 EVT VT = N->getValueType(0); 10703 SDLoc dl(N); 10704 SDValue LHS = Cmp.getOperand(0); 10705 SDValue RHS = Cmp.getOperand(1); 10706 SDValue Chain = N->getOperand(0); 10707 SDValue BB = N->getOperand(1); 10708 SDValue ARMcc = N->getOperand(2); 10709 ARMCC::CondCodes CC = 10710 (ARMCC::CondCodes)cast<ConstantSDNode>(ARMcc)->getZExtValue(); 10711 10712 // (brcond Chain BB ne CPSR (cmpz (and (cmov 0 1 CC CPSR Cmp) 1) 0)) 10713 // -> (brcond Chain BB CC CPSR Cmp) 10714 if (CC == ARMCC::NE && LHS.getOpcode() == ISD::AND && LHS->hasOneUse() && 10715 LHS->getOperand(0)->getOpcode() == ARMISD::CMOV && 10716 LHS->getOperand(0)->hasOneUse()) { 10717 auto *LHS00C = dyn_cast<ConstantSDNode>(LHS->getOperand(0)->getOperand(0)); 10718 auto *LHS01C = dyn_cast<ConstantSDNode>(LHS->getOperand(0)->getOperand(1)); 10719 auto *LHS1C = dyn_cast<ConstantSDNode>(LHS->getOperand(1)); 10720 auto *RHSC = dyn_cast<ConstantSDNode>(RHS); 10721 if ((LHS00C && LHS00C->getZExtValue() == 0) && 10722 (LHS01C && LHS01C->getZExtValue() == 1) && 10723 (LHS1C && LHS1C->getZExtValue() == 1) && 10724 (RHSC && RHSC->getZExtValue() == 0)) { 10725 return DAG.getNode( 10726 ARMISD::BRCOND, dl, VT, Chain, BB, LHS->getOperand(0)->getOperand(2), 10727 LHS->getOperand(0)->getOperand(3), LHS->getOperand(0)->getOperand(4)); 10728 } 10729 } 10730 10731 return SDValue(); 10732 } 10733 10734 /// PerformCMOVCombine - Target-specific DAG combining for ARMISD::CMOV. 10735 SDValue 10736 ARMTargetLowering::PerformCMOVCombine(SDNode *N, SelectionDAG &DAG) const { 10737 SDValue Cmp = N->getOperand(4); 10738 if (Cmp.getOpcode() != ARMISD::CMPZ) 10739 // Only looking at EQ and NE cases. 10740 return SDValue(); 10741 10742 EVT VT = N->getValueType(0); 10743 SDLoc dl(N); 10744 SDValue LHS = Cmp.getOperand(0); 10745 SDValue RHS = Cmp.getOperand(1); 10746 SDValue FalseVal = N->getOperand(0); 10747 SDValue TrueVal = N->getOperand(1); 10748 SDValue ARMcc = N->getOperand(2); 10749 ARMCC::CondCodes CC = 10750 (ARMCC::CondCodes)cast<ConstantSDNode>(ARMcc)->getZExtValue(); 10751 10752 // BFI is only available on V6T2+. 10753 if (!Subtarget->isThumb1Only() && Subtarget->hasV6T2Ops()) { 10754 SDValue R = PerformCMOVToBFICombine(N, DAG); 10755 if (R) 10756 return R; 10757 } 10758 10759 // Simplify 10760 // mov r1, r0 10761 // cmp r1, x 10762 // mov r0, y 10763 // moveq r0, x 10764 // to 10765 // cmp r0, x 10766 // movne r0, y 10767 // 10768 // mov r1, r0 10769 // cmp r1, x 10770 // mov r0, x 10771 // movne r0, y 10772 // to 10773 // cmp r0, x 10774 // movne r0, y 10775 /// FIXME: Turn this into a target neutral optimization? 10776 SDValue Res; 10777 if (CC == ARMCC::NE && FalseVal == RHS && FalseVal != LHS) { 10778 Res = DAG.getNode(ARMISD::CMOV, dl, VT, LHS, TrueVal, ARMcc, 10779 N->getOperand(3), Cmp); 10780 } else if (CC == ARMCC::EQ && TrueVal == RHS) { 10781 SDValue ARMcc; 10782 SDValue NewCmp = getARMCmp(LHS, RHS, ISD::SETNE, ARMcc, DAG, dl); 10783 Res = DAG.getNode(ARMISD::CMOV, dl, VT, LHS, FalseVal, ARMcc, 10784 N->getOperand(3), NewCmp); 10785 } 10786 10787 // (cmov F T ne CPSR (cmpz (cmov 0 1 CC CPSR Cmp) 0)) 10788 // -> (cmov F T CC CPSR Cmp) 10789 if (CC == ARMCC::NE && LHS.getOpcode() == ARMISD::CMOV && LHS->hasOneUse()) { 10790 auto *LHS0C = dyn_cast<ConstantSDNode>(LHS->getOperand(0)); 10791 auto *LHS1C = dyn_cast<ConstantSDNode>(LHS->getOperand(1)); 10792 auto *RHSC = dyn_cast<ConstantSDNode>(RHS); 10793 if ((LHS0C && LHS0C->getZExtValue() == 0) && 10794 (LHS1C && LHS1C->getZExtValue() == 1) && 10795 (RHSC && RHSC->getZExtValue() == 0)) { 10796 return DAG.getNode(ARMISD::CMOV, dl, VT, FalseVal, TrueVal, 10797 LHS->getOperand(2), LHS->getOperand(3), 10798 LHS->getOperand(4)); 10799 } 10800 } 10801 10802 if (Res.getNode()) { 10803 APInt KnownZero, KnownOne; 10804 DAG.computeKnownBits(SDValue(N,0), KnownZero, KnownOne); 10805 // Capture demanded bits information that would be otherwise lost. 10806 if (KnownZero == 0xfffffffe) 10807 Res = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Res, 10808 DAG.getValueType(MVT::i1)); 10809 else if (KnownZero == 0xffffff00) 10810 Res = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Res, 10811 DAG.getValueType(MVT::i8)); 10812 else if (KnownZero == 0xffff0000) 10813 Res = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Res, 10814 DAG.getValueType(MVT::i16)); 10815 } 10816 10817 return Res; 10818 } 10819 10820 SDValue ARMTargetLowering::PerformDAGCombine(SDNode *N, 10821 DAGCombinerInfo &DCI) const { 10822 switch (N->getOpcode()) { 10823 default: break; 10824 case ISD::ADDC: return PerformADDCCombine(N, DCI, Subtarget); 10825 case ISD::ADD: return PerformADDCombine(N, DCI, Subtarget); 10826 case ISD::SUB: return PerformSUBCombine(N, DCI); 10827 case ISD::MUL: return PerformMULCombine(N, DCI, Subtarget); 10828 case ISD::OR: return PerformORCombine(N, DCI, Subtarget); 10829 case ISD::XOR: return PerformXORCombine(N, DCI, Subtarget); 10830 case ISD::AND: return PerformANDCombine(N, DCI, Subtarget); 10831 case ARMISD::BFI: return PerformBFICombine(N, DCI); 10832 case ARMISD::VMOVRRD: return PerformVMOVRRDCombine(N, DCI, Subtarget); 10833 case ARMISD::VMOVDRR: return PerformVMOVDRRCombine(N, DCI.DAG); 10834 case ISD::STORE: return PerformSTORECombine(N, DCI); 10835 case ISD::BUILD_VECTOR: return PerformBUILD_VECTORCombine(N, DCI, Subtarget); 10836 case ISD::INSERT_VECTOR_ELT: return PerformInsertEltCombine(N, DCI); 10837 case ISD::VECTOR_SHUFFLE: return PerformVECTOR_SHUFFLECombine(N, DCI.DAG); 10838 case ARMISD::VDUPLANE: return PerformVDUPLANECombine(N, DCI); 10839 case ISD::FP_TO_SINT: 10840 case ISD::FP_TO_UINT: 10841 return PerformVCVTCombine(N, DCI.DAG, Subtarget); 10842 case ISD::FDIV: 10843 return PerformVDIVCombine(N, DCI.DAG, Subtarget); 10844 case ISD::INTRINSIC_WO_CHAIN: return PerformIntrinsicCombine(N, DCI.DAG); 10845 case ISD::SHL: 10846 case ISD::SRA: 10847 case ISD::SRL: return PerformShiftCombine(N, DCI.DAG, Subtarget); 10848 case ISD::SIGN_EXTEND: 10849 case ISD::ZERO_EXTEND: 10850 case ISD::ANY_EXTEND: return PerformExtendCombine(N, DCI.DAG, Subtarget); 10851 case ARMISD::CMOV: return PerformCMOVCombine(N, DCI.DAG); 10852 case ARMISD::BRCOND: return PerformBRCONDCombine(N, DCI.DAG); 10853 case ISD::LOAD: return PerformLOADCombine(N, DCI); 10854 case ARMISD::VLD2DUP: 10855 case ARMISD::VLD3DUP: 10856 case ARMISD::VLD4DUP: 10857 return PerformVLDCombine(N, DCI); 10858 case ARMISD::BUILD_VECTOR: 10859 return PerformARMBUILD_VECTORCombine(N, DCI); 10860 case ISD::INTRINSIC_VOID: 10861 case ISD::INTRINSIC_W_CHAIN: 10862 switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) { 10863 case Intrinsic::arm_neon_vld1: 10864 case Intrinsic::arm_neon_vld2: 10865 case Intrinsic::arm_neon_vld3: 10866 case Intrinsic::arm_neon_vld4: 10867 case Intrinsic::arm_neon_vld2lane: 10868 case Intrinsic::arm_neon_vld3lane: 10869 case Intrinsic::arm_neon_vld4lane: 10870 case Intrinsic::arm_neon_vst1: 10871 case Intrinsic::arm_neon_vst2: 10872 case Intrinsic::arm_neon_vst3: 10873 case Intrinsic::arm_neon_vst4: 10874 case Intrinsic::arm_neon_vst2lane: 10875 case Intrinsic::arm_neon_vst3lane: 10876 case Intrinsic::arm_neon_vst4lane: 10877 return PerformVLDCombine(N, DCI); 10878 default: break; 10879 } 10880 break; 10881 } 10882 return SDValue(); 10883 } 10884 10885 bool ARMTargetLowering::isDesirableToTransformToIntegerOp(unsigned Opc, 10886 EVT VT) const { 10887 return (VT == MVT::f32) && (Opc == ISD::LOAD || Opc == ISD::STORE); 10888 } 10889 10890 bool ARMTargetLowering::allowsMisalignedMemoryAccesses(EVT VT, 10891 unsigned, 10892 unsigned, 10893 bool *Fast) const { 10894 // The AllowsUnaliged flag models the SCTLR.A setting in ARM cpus 10895 bool AllowsUnaligned = Subtarget->allowsUnalignedMem(); 10896 10897 switch (VT.getSimpleVT().SimpleTy) { 10898 default: 10899 return false; 10900 case MVT::i8: 10901 case MVT::i16: 10902 case MVT::i32: { 10903 // Unaligned access can use (for example) LRDB, LRDH, LDR 10904 if (AllowsUnaligned) { 10905 if (Fast) 10906 *Fast = Subtarget->hasV7Ops(); 10907 return true; 10908 } 10909 return false; 10910 } 10911 case MVT::f64: 10912 case MVT::v2f64: { 10913 // For any little-endian targets with neon, we can support unaligned ld/st 10914 // of D and Q (e.g. {D0,D1}) registers by using vld1.i8/vst1.i8. 10915 // A big-endian target may also explicitly support unaligned accesses 10916 if (Subtarget->hasNEON() && (AllowsUnaligned || Subtarget->isLittle())) { 10917 if (Fast) 10918 *Fast = true; 10919 return true; 10920 } 10921 return false; 10922 } 10923 } 10924 } 10925 10926 static bool memOpAlign(unsigned DstAlign, unsigned SrcAlign, 10927 unsigned AlignCheck) { 10928 return ((SrcAlign == 0 || SrcAlign % AlignCheck == 0) && 10929 (DstAlign == 0 || DstAlign % AlignCheck == 0)); 10930 } 10931 10932 EVT ARMTargetLowering::getOptimalMemOpType(uint64_t Size, 10933 unsigned DstAlign, unsigned SrcAlign, 10934 bool IsMemset, bool ZeroMemset, 10935 bool MemcpyStrSrc, 10936 MachineFunction &MF) const { 10937 const Function *F = MF.getFunction(); 10938 10939 // See if we can use NEON instructions for this... 10940 if ((!IsMemset || ZeroMemset) && Subtarget->hasNEON() && 10941 !F->hasFnAttribute(Attribute::NoImplicitFloat)) { 10942 bool Fast; 10943 if (Size >= 16 && 10944 (memOpAlign(SrcAlign, DstAlign, 16) || 10945 (allowsMisalignedMemoryAccesses(MVT::v2f64, 0, 1, &Fast) && Fast))) { 10946 return MVT::v2f64; 10947 } else if (Size >= 8 && 10948 (memOpAlign(SrcAlign, DstAlign, 8) || 10949 (allowsMisalignedMemoryAccesses(MVT::f64, 0, 1, &Fast) && 10950 Fast))) { 10951 return MVT::f64; 10952 } 10953 } 10954 10955 // Lowering to i32/i16 if the size permits. 10956 if (Size >= 4) 10957 return MVT::i32; 10958 else if (Size >= 2) 10959 return MVT::i16; 10960 10961 // Let the target-independent logic figure it out. 10962 return MVT::Other; 10963 } 10964 10965 bool ARMTargetLowering::isZExtFree(SDValue Val, EVT VT2) const { 10966 if (Val.getOpcode() != ISD::LOAD) 10967 return false; 10968 10969 EVT VT1 = Val.getValueType(); 10970 if (!VT1.isSimple() || !VT1.isInteger() || 10971 !VT2.isSimple() || !VT2.isInteger()) 10972 return false; 10973 10974 switch (VT1.getSimpleVT().SimpleTy) { 10975 default: break; 10976 case MVT::i1: 10977 case MVT::i8: 10978 case MVT::i16: 10979 // 8-bit and 16-bit loads implicitly zero-extend to 32-bits. 10980 return true; 10981 } 10982 10983 return false; 10984 } 10985 10986 bool ARMTargetLowering::isVectorLoadExtDesirable(SDValue ExtVal) const { 10987 EVT VT = ExtVal.getValueType(); 10988 10989 if (!isTypeLegal(VT)) 10990 return false; 10991 10992 // Don't create a loadext if we can fold the extension into a wide/long 10993 // instruction. 10994 // If there's more than one user instruction, the loadext is desirable no 10995 // matter what. There can be two uses by the same instruction. 10996 if (ExtVal->use_empty() || 10997 !ExtVal->use_begin()->isOnlyUserOf(ExtVal.getNode())) 10998 return true; 10999 11000 SDNode *U = *ExtVal->use_begin(); 11001 if ((U->getOpcode() == ISD::ADD || U->getOpcode() == ISD::SUB || 11002 U->getOpcode() == ISD::SHL || U->getOpcode() == ARMISD::VSHL)) 11003 return false; 11004 11005 return true; 11006 } 11007 11008 bool ARMTargetLowering::allowTruncateForTailCall(Type *Ty1, Type *Ty2) const { 11009 if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy()) 11010 return false; 11011 11012 if (!isTypeLegal(EVT::getEVT(Ty1))) 11013 return false; 11014 11015 assert(Ty1->getPrimitiveSizeInBits() <= 64 && "i128 is probably not a noop"); 11016 11017 // Assuming the caller doesn't have a zeroext or signext return parameter, 11018 // truncation all the way down to i1 is valid. 11019 return true; 11020 } 11021 11022 11023 static bool isLegalT1AddressImmediate(int64_t V, EVT VT) { 11024 if (V < 0) 11025 return false; 11026 11027 unsigned Scale = 1; 11028 switch (VT.getSimpleVT().SimpleTy) { 11029 default: return false; 11030 case MVT::i1: 11031 case MVT::i8: 11032 // Scale == 1; 11033 break; 11034 case MVT::i16: 11035 // Scale == 2; 11036 Scale = 2; 11037 break; 11038 case MVT::i32: 11039 // Scale == 4; 11040 Scale = 4; 11041 break; 11042 } 11043 11044 if ((V & (Scale - 1)) != 0) 11045 return false; 11046 V /= Scale; 11047 return V == (V & ((1LL << 5) - 1)); 11048 } 11049 11050 static bool isLegalT2AddressImmediate(int64_t V, EVT VT, 11051 const ARMSubtarget *Subtarget) { 11052 bool isNeg = false; 11053 if (V < 0) { 11054 isNeg = true; 11055 V = - V; 11056 } 11057 11058 switch (VT.getSimpleVT().SimpleTy) { 11059 default: return false; 11060 case MVT::i1: 11061 case MVT::i8: 11062 case MVT::i16: 11063 case MVT::i32: 11064 // + imm12 or - imm8 11065 if (isNeg) 11066 return V == (V & ((1LL << 8) - 1)); 11067 return V == (V & ((1LL << 12) - 1)); 11068 case MVT::f32: 11069 case MVT::f64: 11070 // Same as ARM mode. FIXME: NEON? 11071 if (!Subtarget->hasVFP2()) 11072 return false; 11073 if ((V & 3) != 0) 11074 return false; 11075 V >>= 2; 11076 return V == (V & ((1LL << 8) - 1)); 11077 } 11078 } 11079 11080 /// isLegalAddressImmediate - Return true if the integer value can be used 11081 /// as the offset of the target addressing mode for load / store of the 11082 /// given type. 11083 static bool isLegalAddressImmediate(int64_t V, EVT VT, 11084 const ARMSubtarget *Subtarget) { 11085 if (V == 0) 11086 return true; 11087 11088 if (!VT.isSimple()) 11089 return false; 11090 11091 if (Subtarget->isThumb1Only()) 11092 return isLegalT1AddressImmediate(V, VT); 11093 else if (Subtarget->isThumb2()) 11094 return isLegalT2AddressImmediate(V, VT, Subtarget); 11095 11096 // ARM mode. 11097 if (V < 0) 11098 V = - V; 11099 switch (VT.getSimpleVT().SimpleTy) { 11100 default: return false; 11101 case MVT::i1: 11102 case MVT::i8: 11103 case MVT::i32: 11104 // +- imm12 11105 return V == (V & ((1LL << 12) - 1)); 11106 case MVT::i16: 11107 // +- imm8 11108 return V == (V & ((1LL << 8) - 1)); 11109 case MVT::f32: 11110 case MVT::f64: 11111 if (!Subtarget->hasVFP2()) // FIXME: NEON? 11112 return false; 11113 if ((V & 3) != 0) 11114 return false; 11115 V >>= 2; 11116 return V == (V & ((1LL << 8) - 1)); 11117 } 11118 } 11119 11120 bool ARMTargetLowering::isLegalT2ScaledAddressingMode(const AddrMode &AM, 11121 EVT VT) const { 11122 int Scale = AM.Scale; 11123 if (Scale < 0) 11124 return false; 11125 11126 switch (VT.getSimpleVT().SimpleTy) { 11127 default: return false; 11128 case MVT::i1: 11129 case MVT::i8: 11130 case MVT::i16: 11131 case MVT::i32: 11132 if (Scale == 1) 11133 return true; 11134 // r + r << imm 11135 Scale = Scale & ~1; 11136 return Scale == 2 || Scale == 4 || Scale == 8; 11137 case MVT::i64: 11138 // r + r 11139 if (((unsigned)AM.HasBaseReg + Scale) <= 2) 11140 return true; 11141 return false; 11142 case MVT::isVoid: 11143 // Note, we allow "void" uses (basically, uses that aren't loads or 11144 // stores), because arm allows folding a scale into many arithmetic 11145 // operations. This should be made more precise and revisited later. 11146 11147 // Allow r << imm, but the imm has to be a multiple of two. 11148 if (Scale & 1) return false; 11149 return isPowerOf2_32(Scale); 11150 } 11151 } 11152 11153 /// isLegalAddressingMode - Return true if the addressing mode represented 11154 /// by AM is legal for this target, for a load/store of the specified type. 11155 bool ARMTargetLowering::isLegalAddressingMode(const DataLayout &DL, 11156 const AddrMode &AM, Type *Ty, 11157 unsigned AS) const { 11158 EVT VT = getValueType(DL, Ty, true); 11159 if (!isLegalAddressImmediate(AM.BaseOffs, VT, Subtarget)) 11160 return false; 11161 11162 // Can never fold addr of global into load/store. 11163 if (AM.BaseGV) 11164 return false; 11165 11166 switch (AM.Scale) { 11167 case 0: // no scale reg, must be "r+i" or "r", or "i". 11168 break; 11169 case 1: 11170 if (Subtarget->isThumb1Only()) 11171 return false; 11172 // FALL THROUGH. 11173 default: 11174 // ARM doesn't support any R+R*scale+imm addr modes. 11175 if (AM.BaseOffs) 11176 return false; 11177 11178 if (!VT.isSimple()) 11179 return false; 11180 11181 if (Subtarget->isThumb2()) 11182 return isLegalT2ScaledAddressingMode(AM, VT); 11183 11184 int Scale = AM.Scale; 11185 switch (VT.getSimpleVT().SimpleTy) { 11186 default: return false; 11187 case MVT::i1: 11188 case MVT::i8: 11189 case MVT::i32: 11190 if (Scale < 0) Scale = -Scale; 11191 if (Scale == 1) 11192 return true; 11193 // r + r << imm 11194 return isPowerOf2_32(Scale & ~1); 11195 case MVT::i16: 11196 case MVT::i64: 11197 // r + r 11198 if (((unsigned)AM.HasBaseReg + Scale) <= 2) 11199 return true; 11200 return false; 11201 11202 case MVT::isVoid: 11203 // Note, we allow "void" uses (basically, uses that aren't loads or 11204 // stores), because arm allows folding a scale into many arithmetic 11205 // operations. This should be made more precise and revisited later. 11206 11207 // Allow r << imm, but the imm has to be a multiple of two. 11208 if (Scale & 1) return false; 11209 return isPowerOf2_32(Scale); 11210 } 11211 } 11212 return true; 11213 } 11214 11215 /// isLegalICmpImmediate - Return true if the specified immediate is legal 11216 /// icmp immediate, that is the target has icmp instructions which can compare 11217 /// a register against the immediate without having to materialize the 11218 /// immediate into a register. 11219 bool ARMTargetLowering::isLegalICmpImmediate(int64_t Imm) const { 11220 // Thumb2 and ARM modes can use cmn for negative immediates. 11221 if (!Subtarget->isThumb()) 11222 return ARM_AM::getSOImmVal(std::abs(Imm)) != -1; 11223 if (Subtarget->isThumb2()) 11224 return ARM_AM::getT2SOImmVal(std::abs(Imm)) != -1; 11225 // Thumb1 doesn't have cmn, and only 8-bit immediates. 11226 return Imm >= 0 && Imm <= 255; 11227 } 11228 11229 /// isLegalAddImmediate - Return true if the specified immediate is a legal add 11230 /// *or sub* immediate, that is the target has add or sub instructions which can 11231 /// add a register with the immediate without having to materialize the 11232 /// immediate into a register. 11233 bool ARMTargetLowering::isLegalAddImmediate(int64_t Imm) const { 11234 // Same encoding for add/sub, just flip the sign. 11235 int64_t AbsImm = std::abs(Imm); 11236 if (!Subtarget->isThumb()) 11237 return ARM_AM::getSOImmVal(AbsImm) != -1; 11238 if (Subtarget->isThumb2()) 11239 return ARM_AM::getT2SOImmVal(AbsImm) != -1; 11240 // Thumb1 only has 8-bit unsigned immediate. 11241 return AbsImm >= 0 && AbsImm <= 255; 11242 } 11243 11244 static bool getARMIndexedAddressParts(SDNode *Ptr, EVT VT, 11245 bool isSEXTLoad, SDValue &Base, 11246 SDValue &Offset, bool &isInc, 11247 SelectionDAG &DAG) { 11248 if (Ptr->getOpcode() != ISD::ADD && Ptr->getOpcode() != ISD::SUB) 11249 return false; 11250 11251 if (VT == MVT::i16 || ((VT == MVT::i8 || VT == MVT::i1) && isSEXTLoad)) { 11252 // AddressingMode 3 11253 Base = Ptr->getOperand(0); 11254 if (ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(Ptr->getOperand(1))) { 11255 int RHSC = (int)RHS->getZExtValue(); 11256 if (RHSC < 0 && RHSC > -256) { 11257 assert(Ptr->getOpcode() == ISD::ADD); 11258 isInc = false; 11259 Offset = DAG.getConstant(-RHSC, SDLoc(Ptr), RHS->getValueType(0)); 11260 return true; 11261 } 11262 } 11263 isInc = (Ptr->getOpcode() == ISD::ADD); 11264 Offset = Ptr->getOperand(1); 11265 return true; 11266 } else if (VT == MVT::i32 || VT == MVT::i8 || VT == MVT::i1) { 11267 // AddressingMode 2 11268 if (ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(Ptr->getOperand(1))) { 11269 int RHSC = (int)RHS->getZExtValue(); 11270 if (RHSC < 0 && RHSC > -0x1000) { 11271 assert(Ptr->getOpcode() == ISD::ADD); 11272 isInc = false; 11273 Offset = DAG.getConstant(-RHSC, SDLoc(Ptr), RHS->getValueType(0)); 11274 Base = Ptr->getOperand(0); 11275 return true; 11276 } 11277 } 11278 11279 if (Ptr->getOpcode() == ISD::ADD) { 11280 isInc = true; 11281 ARM_AM::ShiftOpc ShOpcVal= 11282 ARM_AM::getShiftOpcForNode(Ptr->getOperand(0).getOpcode()); 11283 if (ShOpcVal != ARM_AM::no_shift) { 11284 Base = Ptr->getOperand(1); 11285 Offset = Ptr->getOperand(0); 11286 } else { 11287 Base = Ptr->getOperand(0); 11288 Offset = Ptr->getOperand(1); 11289 } 11290 return true; 11291 } 11292 11293 isInc = (Ptr->getOpcode() == ISD::ADD); 11294 Base = Ptr->getOperand(0); 11295 Offset = Ptr->getOperand(1); 11296 return true; 11297 } 11298 11299 // FIXME: Use VLDM / VSTM to emulate indexed FP load / store. 11300 return false; 11301 } 11302 11303 static bool getT2IndexedAddressParts(SDNode *Ptr, EVT VT, 11304 bool isSEXTLoad, SDValue &Base, 11305 SDValue &Offset, bool &isInc, 11306 SelectionDAG &DAG) { 11307 if (Ptr->getOpcode() != ISD::ADD && Ptr->getOpcode() != ISD::SUB) 11308 return false; 11309 11310 Base = Ptr->getOperand(0); 11311 if (ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(Ptr->getOperand(1))) { 11312 int RHSC = (int)RHS->getZExtValue(); 11313 if (RHSC < 0 && RHSC > -0x100) { // 8 bits. 11314 assert(Ptr->getOpcode() == ISD::ADD); 11315 isInc = false; 11316 Offset = DAG.getConstant(-RHSC, SDLoc(Ptr), RHS->getValueType(0)); 11317 return true; 11318 } else if (RHSC > 0 && RHSC < 0x100) { // 8 bit, no zero. 11319 isInc = Ptr->getOpcode() == ISD::ADD; 11320 Offset = DAG.getConstant(RHSC, SDLoc(Ptr), RHS->getValueType(0)); 11321 return true; 11322 } 11323 } 11324 11325 return false; 11326 } 11327 11328 /// getPreIndexedAddressParts - returns true by value, base pointer and 11329 /// offset pointer and addressing mode by reference if the node's address 11330 /// can be legally represented as pre-indexed load / store address. 11331 bool 11332 ARMTargetLowering::getPreIndexedAddressParts(SDNode *N, SDValue &Base, 11333 SDValue &Offset, 11334 ISD::MemIndexedMode &AM, 11335 SelectionDAG &DAG) const { 11336 if (Subtarget->isThumb1Only()) 11337 return false; 11338 11339 EVT VT; 11340 SDValue Ptr; 11341 bool isSEXTLoad = false; 11342 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) { 11343 Ptr = LD->getBasePtr(); 11344 VT = LD->getMemoryVT(); 11345 isSEXTLoad = LD->getExtensionType() == ISD::SEXTLOAD; 11346 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) { 11347 Ptr = ST->getBasePtr(); 11348 VT = ST->getMemoryVT(); 11349 } else 11350 return false; 11351 11352 bool isInc; 11353 bool isLegal = false; 11354 if (Subtarget->isThumb2()) 11355 isLegal = getT2IndexedAddressParts(Ptr.getNode(), VT, isSEXTLoad, Base, 11356 Offset, isInc, DAG); 11357 else 11358 isLegal = getARMIndexedAddressParts(Ptr.getNode(), VT, isSEXTLoad, Base, 11359 Offset, isInc, DAG); 11360 if (!isLegal) 11361 return false; 11362 11363 AM = isInc ? ISD::PRE_INC : ISD::PRE_DEC; 11364 return true; 11365 } 11366 11367 /// getPostIndexedAddressParts - returns true by value, base pointer and 11368 /// offset pointer and addressing mode by reference if this node can be 11369 /// combined with a load / store to form a post-indexed load / store. 11370 bool ARMTargetLowering::getPostIndexedAddressParts(SDNode *N, SDNode *Op, 11371 SDValue &Base, 11372 SDValue &Offset, 11373 ISD::MemIndexedMode &AM, 11374 SelectionDAG &DAG) const { 11375 if (Subtarget->isThumb1Only()) 11376 return false; 11377 11378 EVT VT; 11379 SDValue Ptr; 11380 bool isSEXTLoad = false; 11381 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) { 11382 VT = LD->getMemoryVT(); 11383 Ptr = LD->getBasePtr(); 11384 isSEXTLoad = LD->getExtensionType() == ISD::SEXTLOAD; 11385 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) { 11386 VT = ST->getMemoryVT(); 11387 Ptr = ST->getBasePtr(); 11388 } else 11389 return false; 11390 11391 bool isInc; 11392 bool isLegal = false; 11393 if (Subtarget->isThumb2()) 11394 isLegal = getT2IndexedAddressParts(Op, VT, isSEXTLoad, Base, Offset, 11395 isInc, DAG); 11396 else 11397 isLegal = getARMIndexedAddressParts(Op, VT, isSEXTLoad, Base, Offset, 11398 isInc, DAG); 11399 if (!isLegal) 11400 return false; 11401 11402 if (Ptr != Base) { 11403 // Swap base ptr and offset to catch more post-index load / store when 11404 // it's legal. In Thumb2 mode, offset must be an immediate. 11405 if (Ptr == Offset && Op->getOpcode() == ISD::ADD && 11406 !Subtarget->isThumb2()) 11407 std::swap(Base, Offset); 11408 11409 // Post-indexed load / store update the base pointer. 11410 if (Ptr != Base) 11411 return false; 11412 } 11413 11414 AM = isInc ? ISD::POST_INC : ISD::POST_DEC; 11415 return true; 11416 } 11417 11418 void ARMTargetLowering::computeKnownBitsForTargetNode(const SDValue Op, 11419 APInt &KnownZero, 11420 APInt &KnownOne, 11421 const SelectionDAG &DAG, 11422 unsigned Depth) const { 11423 unsigned BitWidth = KnownOne.getBitWidth(); 11424 KnownZero = KnownOne = APInt(BitWidth, 0); 11425 switch (Op.getOpcode()) { 11426 default: break; 11427 case ARMISD::ADDC: 11428 case ARMISD::ADDE: 11429 case ARMISD::SUBC: 11430 case ARMISD::SUBE: 11431 // These nodes' second result is a boolean 11432 if (Op.getResNo() == 0) 11433 break; 11434 KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - 1); 11435 break; 11436 case ARMISD::CMOV: { 11437 // Bits are known zero/one if known on the LHS and RHS. 11438 DAG.computeKnownBits(Op.getOperand(0), KnownZero, KnownOne, Depth+1); 11439 if (KnownZero == 0 && KnownOne == 0) return; 11440 11441 APInt KnownZeroRHS, KnownOneRHS; 11442 DAG.computeKnownBits(Op.getOperand(1), KnownZeroRHS, KnownOneRHS, Depth+1); 11443 KnownZero &= KnownZeroRHS; 11444 KnownOne &= KnownOneRHS; 11445 return; 11446 } 11447 case ISD::INTRINSIC_W_CHAIN: { 11448 ConstantSDNode *CN = cast<ConstantSDNode>(Op->getOperand(1)); 11449 Intrinsic::ID IntID = static_cast<Intrinsic::ID>(CN->getZExtValue()); 11450 switch (IntID) { 11451 default: return; 11452 case Intrinsic::arm_ldaex: 11453 case Intrinsic::arm_ldrex: { 11454 EVT VT = cast<MemIntrinsicSDNode>(Op)->getMemoryVT(); 11455 unsigned MemBits = VT.getScalarType().getSizeInBits(); 11456 KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - MemBits); 11457 return; 11458 } 11459 } 11460 } 11461 } 11462 } 11463 11464 //===----------------------------------------------------------------------===// 11465 // ARM Inline Assembly Support 11466 //===----------------------------------------------------------------------===// 11467 11468 bool ARMTargetLowering::ExpandInlineAsm(CallInst *CI) const { 11469 // Looking for "rev" which is V6+. 11470 if (!Subtarget->hasV6Ops()) 11471 return false; 11472 11473 InlineAsm *IA = cast<InlineAsm>(CI->getCalledValue()); 11474 std::string AsmStr = IA->getAsmString(); 11475 SmallVector<StringRef, 4> AsmPieces; 11476 SplitString(AsmStr, AsmPieces, ";\n"); 11477 11478 switch (AsmPieces.size()) { 11479 default: return false; 11480 case 1: 11481 AsmStr = AsmPieces[0]; 11482 AsmPieces.clear(); 11483 SplitString(AsmStr, AsmPieces, " \t,"); 11484 11485 // rev $0, $1 11486 if (AsmPieces.size() == 3 && 11487 AsmPieces[0] == "rev" && AsmPieces[1] == "$0" && AsmPieces[2] == "$1" && 11488 IA->getConstraintString().compare(0, 4, "=l,l") == 0) { 11489 IntegerType *Ty = dyn_cast<IntegerType>(CI->getType()); 11490 if (Ty && Ty->getBitWidth() == 32) 11491 return IntrinsicLowering::LowerToByteSwap(CI); 11492 } 11493 break; 11494 } 11495 11496 return false; 11497 } 11498 11499 /// getConstraintType - Given a constraint letter, return the type of 11500 /// constraint it is for this target. 11501 ARMTargetLowering::ConstraintType 11502 ARMTargetLowering::getConstraintType(StringRef Constraint) const { 11503 if (Constraint.size() == 1) { 11504 switch (Constraint[0]) { 11505 default: break; 11506 case 'l': return C_RegisterClass; 11507 case 'w': return C_RegisterClass; 11508 case 'h': return C_RegisterClass; 11509 case 'x': return C_RegisterClass; 11510 case 't': return C_RegisterClass; 11511 case 'j': return C_Other; // Constant for movw. 11512 // An address with a single base register. Due to the way we 11513 // currently handle addresses it is the same as an 'r' memory constraint. 11514 case 'Q': return C_Memory; 11515 } 11516 } else if (Constraint.size() == 2) { 11517 switch (Constraint[0]) { 11518 default: break; 11519 // All 'U+' constraints are addresses. 11520 case 'U': return C_Memory; 11521 } 11522 } 11523 return TargetLowering::getConstraintType(Constraint); 11524 } 11525 11526 /// Examine constraint type and operand type and determine a weight value. 11527 /// This object must already have been set up with the operand type 11528 /// and the current alternative constraint selected. 11529 TargetLowering::ConstraintWeight 11530 ARMTargetLowering::getSingleConstraintMatchWeight( 11531 AsmOperandInfo &info, const char *constraint) const { 11532 ConstraintWeight weight = CW_Invalid; 11533 Value *CallOperandVal = info.CallOperandVal; 11534 // If we don't have a value, we can't do a match, 11535 // but allow it at the lowest weight. 11536 if (!CallOperandVal) 11537 return CW_Default; 11538 Type *type = CallOperandVal->getType(); 11539 // Look at the constraint type. 11540 switch (*constraint) { 11541 default: 11542 weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint); 11543 break; 11544 case 'l': 11545 if (type->isIntegerTy()) { 11546 if (Subtarget->isThumb()) 11547 weight = CW_SpecificReg; 11548 else 11549 weight = CW_Register; 11550 } 11551 break; 11552 case 'w': 11553 if (type->isFloatingPointTy()) 11554 weight = CW_Register; 11555 break; 11556 } 11557 return weight; 11558 } 11559 11560 typedef std::pair<unsigned, const TargetRegisterClass*> RCPair; 11561 RCPair ARMTargetLowering::getRegForInlineAsmConstraint( 11562 const TargetRegisterInfo *TRI, StringRef Constraint, MVT VT) const { 11563 if (Constraint.size() == 1) { 11564 // GCC ARM Constraint Letters 11565 switch (Constraint[0]) { 11566 case 'l': // Low regs or general regs. 11567 if (Subtarget->isThumb()) 11568 return RCPair(0U, &ARM::tGPRRegClass); 11569 return RCPair(0U, &ARM::GPRRegClass); 11570 case 'h': // High regs or no regs. 11571 if (Subtarget->isThumb()) 11572 return RCPair(0U, &ARM::hGPRRegClass); 11573 break; 11574 case 'r': 11575 if (Subtarget->isThumb1Only()) 11576 return RCPair(0U, &ARM::tGPRRegClass); 11577 return RCPair(0U, &ARM::GPRRegClass); 11578 case 'w': 11579 if (VT == MVT::Other) 11580 break; 11581 if (VT == MVT::f32) 11582 return RCPair(0U, &ARM::SPRRegClass); 11583 if (VT.getSizeInBits() == 64) 11584 return RCPair(0U, &ARM::DPRRegClass); 11585 if (VT.getSizeInBits() == 128) 11586 return RCPair(0U, &ARM::QPRRegClass); 11587 break; 11588 case 'x': 11589 if (VT == MVT::Other) 11590 break; 11591 if (VT == MVT::f32) 11592 return RCPair(0U, &ARM::SPR_8RegClass); 11593 if (VT.getSizeInBits() == 64) 11594 return RCPair(0U, &ARM::DPR_8RegClass); 11595 if (VT.getSizeInBits() == 128) 11596 return RCPair(0U, &ARM::QPR_8RegClass); 11597 break; 11598 case 't': 11599 if (VT == MVT::f32) 11600 return RCPair(0U, &ARM::SPRRegClass); 11601 break; 11602 } 11603 } 11604 if (StringRef("{cc}").equals_lower(Constraint)) 11605 return std::make_pair(unsigned(ARM::CPSR), &ARM::CCRRegClass); 11606 11607 return TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT); 11608 } 11609 11610 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops 11611 /// vector. If it is invalid, don't add anything to Ops. 11612 void ARMTargetLowering::LowerAsmOperandForConstraint(SDValue Op, 11613 std::string &Constraint, 11614 std::vector<SDValue>&Ops, 11615 SelectionDAG &DAG) const { 11616 SDValue Result; 11617 11618 // Currently only support length 1 constraints. 11619 if (Constraint.length() != 1) return; 11620 11621 char ConstraintLetter = Constraint[0]; 11622 switch (ConstraintLetter) { 11623 default: break; 11624 case 'j': 11625 case 'I': case 'J': case 'K': case 'L': 11626 case 'M': case 'N': case 'O': 11627 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op); 11628 if (!C) 11629 return; 11630 11631 int64_t CVal64 = C->getSExtValue(); 11632 int CVal = (int) CVal64; 11633 // None of these constraints allow values larger than 32 bits. Check 11634 // that the value fits in an int. 11635 if (CVal != CVal64) 11636 return; 11637 11638 switch (ConstraintLetter) { 11639 case 'j': 11640 // Constant suitable for movw, must be between 0 and 11641 // 65535. 11642 if (Subtarget->hasV6T2Ops()) 11643 if (CVal >= 0 && CVal <= 65535) 11644 break; 11645 return; 11646 case 'I': 11647 if (Subtarget->isThumb1Only()) { 11648 // This must be a constant between 0 and 255, for ADD 11649 // immediates. 11650 if (CVal >= 0 && CVal <= 255) 11651 break; 11652 } else if (Subtarget->isThumb2()) { 11653 // A constant that can be used as an immediate value in a 11654 // data-processing instruction. 11655 if (ARM_AM::getT2SOImmVal(CVal) != -1) 11656 break; 11657 } else { 11658 // A constant that can be used as an immediate value in a 11659 // data-processing instruction. 11660 if (ARM_AM::getSOImmVal(CVal) != -1) 11661 break; 11662 } 11663 return; 11664 11665 case 'J': 11666 if (Subtarget->isThumb1Only()) { 11667 // This must be a constant between -255 and -1, for negated ADD 11668 // immediates. This can be used in GCC with an "n" modifier that 11669 // prints the negated value, for use with SUB instructions. It is 11670 // not useful otherwise but is implemented for compatibility. 11671 if (CVal >= -255 && CVal <= -1) 11672 break; 11673 } else { 11674 // This must be a constant between -4095 and 4095. It is not clear 11675 // what this constraint is intended for. Implemented for 11676 // compatibility with GCC. 11677 if (CVal >= -4095 && CVal <= 4095) 11678 break; 11679 } 11680 return; 11681 11682 case 'K': 11683 if (Subtarget->isThumb1Only()) { 11684 // A 32-bit value where only one byte has a nonzero value. Exclude 11685 // zero to match GCC. This constraint is used by GCC internally for 11686 // constants that can be loaded with a move/shift combination. 11687 // It is not useful otherwise but is implemented for compatibility. 11688 if (CVal != 0 && ARM_AM::isThumbImmShiftedVal(CVal)) 11689 break; 11690 } else if (Subtarget->isThumb2()) { 11691 // A constant whose bitwise inverse can be used as an immediate 11692 // value in a data-processing instruction. This can be used in GCC 11693 // with a "B" modifier that prints the inverted value, for use with 11694 // BIC and MVN instructions. It is not useful otherwise but is 11695 // implemented for compatibility. 11696 if (ARM_AM::getT2SOImmVal(~CVal) != -1) 11697 break; 11698 } else { 11699 // A constant whose bitwise inverse can be used as an immediate 11700 // value in a data-processing instruction. This can be used in GCC 11701 // with a "B" modifier that prints the inverted value, for use with 11702 // BIC and MVN instructions. It is not useful otherwise but is 11703 // implemented for compatibility. 11704 if (ARM_AM::getSOImmVal(~CVal) != -1) 11705 break; 11706 } 11707 return; 11708 11709 case 'L': 11710 if (Subtarget->isThumb1Only()) { 11711 // This must be a constant between -7 and 7, 11712 // for 3-operand ADD/SUB immediate instructions. 11713 if (CVal >= -7 && CVal < 7) 11714 break; 11715 } else if (Subtarget->isThumb2()) { 11716 // A constant whose negation can be used as an immediate value in a 11717 // data-processing instruction. This can be used in GCC with an "n" 11718 // modifier that prints the negated value, for use with SUB 11719 // instructions. It is not useful otherwise but is implemented for 11720 // compatibility. 11721 if (ARM_AM::getT2SOImmVal(-CVal) != -1) 11722 break; 11723 } else { 11724 // A constant whose negation can be used as an immediate value in a 11725 // data-processing instruction. This can be used in GCC with an "n" 11726 // modifier that prints the negated value, for use with SUB 11727 // instructions. It is not useful otherwise but is implemented for 11728 // compatibility. 11729 if (ARM_AM::getSOImmVal(-CVal) != -1) 11730 break; 11731 } 11732 return; 11733 11734 case 'M': 11735 if (Subtarget->isThumb1Only()) { 11736 // This must be a multiple of 4 between 0 and 1020, for 11737 // ADD sp + immediate. 11738 if ((CVal >= 0 && CVal <= 1020) && ((CVal & 3) == 0)) 11739 break; 11740 } else { 11741 // A power of two or a constant between 0 and 32. This is used in 11742 // GCC for the shift amount on shifted register operands, but it is 11743 // useful in general for any shift amounts. 11744 if ((CVal >= 0 && CVal <= 32) || ((CVal & (CVal - 1)) == 0)) 11745 break; 11746 } 11747 return; 11748 11749 case 'N': 11750 if (Subtarget->isThumb()) { // FIXME thumb2 11751 // This must be a constant between 0 and 31, for shift amounts. 11752 if (CVal >= 0 && CVal <= 31) 11753 break; 11754 } 11755 return; 11756 11757 case 'O': 11758 if (Subtarget->isThumb()) { // FIXME thumb2 11759 // This must be a multiple of 4 between -508 and 508, for 11760 // ADD/SUB sp = sp + immediate. 11761 if ((CVal >= -508 && CVal <= 508) && ((CVal & 3) == 0)) 11762 break; 11763 } 11764 return; 11765 } 11766 Result = DAG.getTargetConstant(CVal, SDLoc(Op), Op.getValueType()); 11767 break; 11768 } 11769 11770 if (Result.getNode()) { 11771 Ops.push_back(Result); 11772 return; 11773 } 11774 return TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG); 11775 } 11776 11777 static RTLIB::Libcall getDivRemLibcall( 11778 const SDNode *N, MVT::SimpleValueType SVT) { 11779 assert((N->getOpcode() == ISD::SDIVREM || N->getOpcode() == ISD::UDIVREM || 11780 N->getOpcode() == ISD::SREM || N->getOpcode() == ISD::UREM) && 11781 "Unhandled Opcode in getDivRemLibcall"); 11782 bool isSigned = N->getOpcode() == ISD::SDIVREM || 11783 N->getOpcode() == ISD::SREM; 11784 RTLIB::Libcall LC; 11785 switch (SVT) { 11786 default: llvm_unreachable("Unexpected request for libcall!"); 11787 case MVT::i8: LC = isSigned ? RTLIB::SDIVREM_I8 : RTLIB::UDIVREM_I8; break; 11788 case MVT::i16: LC = isSigned ? RTLIB::SDIVREM_I16 : RTLIB::UDIVREM_I16; break; 11789 case MVT::i32: LC = isSigned ? RTLIB::SDIVREM_I32 : RTLIB::UDIVREM_I32; break; 11790 case MVT::i64: LC = isSigned ? RTLIB::SDIVREM_I64 : RTLIB::UDIVREM_I64; break; 11791 } 11792 return LC; 11793 } 11794 11795 static TargetLowering::ArgListTy getDivRemArgList( 11796 const SDNode *N, LLVMContext *Context) { 11797 assert((N->getOpcode() == ISD::SDIVREM || N->getOpcode() == ISD::UDIVREM || 11798 N->getOpcode() == ISD::SREM || N->getOpcode() == ISD::UREM) && 11799 "Unhandled Opcode in getDivRemArgList"); 11800 bool isSigned = N->getOpcode() == ISD::SDIVREM || 11801 N->getOpcode() == ISD::SREM; 11802 TargetLowering::ArgListTy Args; 11803 TargetLowering::ArgListEntry Entry; 11804 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) { 11805 EVT ArgVT = N->getOperand(i).getValueType(); 11806 Type *ArgTy = ArgVT.getTypeForEVT(*Context); 11807 Entry.Node = N->getOperand(i); 11808 Entry.Ty = ArgTy; 11809 Entry.isSExt = isSigned; 11810 Entry.isZExt = !isSigned; 11811 Args.push_back(Entry); 11812 } 11813 return Args; 11814 } 11815 11816 SDValue ARMTargetLowering::LowerDivRem(SDValue Op, SelectionDAG &DAG) const { 11817 assert((Subtarget->isTargetAEABI() || Subtarget->isTargetAndroid() || 11818 Subtarget->isTargetGNUAEABI()) && 11819 "Register-based DivRem lowering only"); 11820 unsigned Opcode = Op->getOpcode(); 11821 assert((Opcode == ISD::SDIVREM || Opcode == ISD::UDIVREM) && 11822 "Invalid opcode for Div/Rem lowering"); 11823 bool isSigned = (Opcode == ISD::SDIVREM); 11824 EVT VT = Op->getValueType(0); 11825 Type *Ty = VT.getTypeForEVT(*DAG.getContext()); 11826 11827 RTLIB::Libcall LC = getDivRemLibcall(Op.getNode(), 11828 VT.getSimpleVT().SimpleTy); 11829 SDValue InChain = DAG.getEntryNode(); 11830 11831 TargetLowering::ArgListTy Args = getDivRemArgList(Op.getNode(), 11832 DAG.getContext()); 11833 11834 SDValue Callee = DAG.getExternalSymbol(getLibcallName(LC), 11835 getPointerTy(DAG.getDataLayout())); 11836 11837 Type *RetTy = (Type*)StructType::get(Ty, Ty, nullptr); 11838 11839 SDLoc dl(Op); 11840 TargetLowering::CallLoweringInfo CLI(DAG); 11841 CLI.setDebugLoc(dl).setChain(InChain) 11842 .setCallee(getLibcallCallingConv(LC), RetTy, Callee, std::move(Args), 0) 11843 .setInRegister().setSExtResult(isSigned).setZExtResult(!isSigned); 11844 11845 std::pair<SDValue, SDValue> CallInfo = LowerCallTo(CLI); 11846 return CallInfo.first; 11847 } 11848 11849 // Lowers REM using divmod helpers 11850 // see RTABI section 4.2/4.3 11851 SDValue ARMTargetLowering::LowerREM(SDNode *N, SelectionDAG &DAG) const { 11852 // Build return types (div and rem) 11853 std::vector<Type*> RetTyParams; 11854 Type *RetTyElement; 11855 11856 switch (N->getValueType(0).getSimpleVT().SimpleTy) { 11857 default: llvm_unreachable("Unexpected request for libcall!"); 11858 case MVT::i8: RetTyElement = Type::getInt8Ty(*DAG.getContext()); break; 11859 case MVT::i16: RetTyElement = Type::getInt16Ty(*DAG.getContext()); break; 11860 case MVT::i32: RetTyElement = Type::getInt32Ty(*DAG.getContext()); break; 11861 case MVT::i64: RetTyElement = Type::getInt64Ty(*DAG.getContext()); break; 11862 } 11863 11864 RetTyParams.push_back(RetTyElement); 11865 RetTyParams.push_back(RetTyElement); 11866 ArrayRef<Type*> ret = ArrayRef<Type*>(RetTyParams); 11867 Type *RetTy = StructType::get(*DAG.getContext(), ret); 11868 11869 RTLIB::Libcall LC = getDivRemLibcall(N, N->getValueType(0).getSimpleVT(). 11870 SimpleTy); 11871 SDValue InChain = DAG.getEntryNode(); 11872 TargetLowering::ArgListTy Args = getDivRemArgList(N, DAG.getContext()); 11873 bool isSigned = N->getOpcode() == ISD::SREM; 11874 SDValue Callee = DAG.getExternalSymbol(getLibcallName(LC), 11875 getPointerTy(DAG.getDataLayout())); 11876 11877 // Lower call 11878 CallLoweringInfo CLI(DAG); 11879 CLI.setChain(InChain) 11880 .setCallee(CallingConv::ARM_AAPCS, RetTy, Callee, std::move(Args), 0) 11881 .setSExtResult(isSigned).setZExtResult(!isSigned).setDebugLoc(SDLoc(N)); 11882 std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI); 11883 11884 // Return second (rem) result operand (first contains div) 11885 SDNode *ResNode = CallResult.first.getNode(); 11886 assert(ResNode->getNumOperands() == 2 && "divmod should return two operands"); 11887 return ResNode->getOperand(1); 11888 } 11889 11890 SDValue 11891 ARMTargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op, SelectionDAG &DAG) const { 11892 assert(Subtarget->isTargetWindows() && "unsupported target platform"); 11893 SDLoc DL(Op); 11894 11895 // Get the inputs. 11896 SDValue Chain = Op.getOperand(0); 11897 SDValue Size = Op.getOperand(1); 11898 11899 SDValue Words = DAG.getNode(ISD::SRL, DL, MVT::i32, Size, 11900 DAG.getConstant(2, DL, MVT::i32)); 11901 11902 SDValue Flag; 11903 Chain = DAG.getCopyToReg(Chain, DL, ARM::R4, Words, Flag); 11904 Flag = Chain.getValue(1); 11905 11906 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue); 11907 Chain = DAG.getNode(ARMISD::WIN__CHKSTK, DL, NodeTys, Chain, Flag); 11908 11909 SDValue NewSP = DAG.getCopyFromReg(Chain, DL, ARM::SP, MVT::i32); 11910 Chain = NewSP.getValue(1); 11911 11912 SDValue Ops[2] = { NewSP, Chain }; 11913 return DAG.getMergeValues(Ops, DL); 11914 } 11915 11916 SDValue ARMTargetLowering::LowerFP_EXTEND(SDValue Op, SelectionDAG &DAG) const { 11917 assert(Op.getValueType() == MVT::f64 && Subtarget->isFPOnlySP() && 11918 "Unexpected type for custom-lowering FP_EXTEND"); 11919 11920 RTLIB::Libcall LC; 11921 LC = RTLIB::getFPEXT(Op.getOperand(0).getValueType(), Op.getValueType()); 11922 11923 SDValue SrcVal = Op.getOperand(0); 11924 return makeLibCall(DAG, LC, Op.getValueType(), SrcVal, /*isSigned*/ false, 11925 SDLoc(Op)).first; 11926 } 11927 11928 SDValue ARMTargetLowering::LowerFP_ROUND(SDValue Op, SelectionDAG &DAG) const { 11929 assert(Op.getOperand(0).getValueType() == MVT::f64 && 11930 Subtarget->isFPOnlySP() && 11931 "Unexpected type for custom-lowering FP_ROUND"); 11932 11933 RTLIB::Libcall LC; 11934 LC = RTLIB::getFPROUND(Op.getOperand(0).getValueType(), Op.getValueType()); 11935 11936 SDValue SrcVal = Op.getOperand(0); 11937 return makeLibCall(DAG, LC, Op.getValueType(), SrcVal, /*isSigned*/ false, 11938 SDLoc(Op)).first; 11939 } 11940 11941 bool 11942 ARMTargetLowering::isOffsetFoldingLegal(const GlobalAddressSDNode *GA) const { 11943 // The ARM target isn't yet aware of offsets. 11944 return false; 11945 } 11946 11947 bool ARM::isBitFieldInvertedMask(unsigned v) { 11948 if (v == 0xffffffff) 11949 return false; 11950 11951 // there can be 1's on either or both "outsides", all the "inside" 11952 // bits must be 0's 11953 return isShiftedMask_32(~v); 11954 } 11955 11956 /// isFPImmLegal - Returns true if the target can instruction select the 11957 /// specified FP immediate natively. If false, the legalizer will 11958 /// materialize the FP immediate as a load from a constant pool. 11959 bool ARMTargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT) const { 11960 if (!Subtarget->hasVFP3()) 11961 return false; 11962 if (VT == MVT::f32) 11963 return ARM_AM::getFP32Imm(Imm) != -1; 11964 if (VT == MVT::f64 && !Subtarget->isFPOnlySP()) 11965 return ARM_AM::getFP64Imm(Imm) != -1; 11966 return false; 11967 } 11968 11969 /// getTgtMemIntrinsic - Represent NEON load and store intrinsics as 11970 /// MemIntrinsicNodes. The associated MachineMemOperands record the alignment 11971 /// specified in the intrinsic calls. 11972 bool ARMTargetLowering::getTgtMemIntrinsic(IntrinsicInfo &Info, 11973 const CallInst &I, 11974 unsigned Intrinsic) const { 11975 switch (Intrinsic) { 11976 case Intrinsic::arm_neon_vld1: 11977 case Intrinsic::arm_neon_vld2: 11978 case Intrinsic::arm_neon_vld3: 11979 case Intrinsic::arm_neon_vld4: 11980 case Intrinsic::arm_neon_vld2lane: 11981 case Intrinsic::arm_neon_vld3lane: 11982 case Intrinsic::arm_neon_vld4lane: { 11983 Info.opc = ISD::INTRINSIC_W_CHAIN; 11984 // Conservatively set memVT to the entire set of vectors loaded. 11985 auto &DL = I.getCalledFunction()->getParent()->getDataLayout(); 11986 uint64_t NumElts = DL.getTypeSizeInBits(I.getType()) / 64; 11987 Info.memVT = EVT::getVectorVT(I.getType()->getContext(), MVT::i64, NumElts); 11988 Info.ptrVal = I.getArgOperand(0); 11989 Info.offset = 0; 11990 Value *AlignArg = I.getArgOperand(I.getNumArgOperands() - 1); 11991 Info.align = cast<ConstantInt>(AlignArg)->getZExtValue(); 11992 Info.vol = false; // volatile loads with NEON intrinsics not supported 11993 Info.readMem = true; 11994 Info.writeMem = false; 11995 return true; 11996 } 11997 case Intrinsic::arm_neon_vst1: 11998 case Intrinsic::arm_neon_vst2: 11999 case Intrinsic::arm_neon_vst3: 12000 case Intrinsic::arm_neon_vst4: 12001 case Intrinsic::arm_neon_vst2lane: 12002 case Intrinsic::arm_neon_vst3lane: 12003 case Intrinsic::arm_neon_vst4lane: { 12004 Info.opc = ISD::INTRINSIC_VOID; 12005 // Conservatively set memVT to the entire set of vectors stored. 12006 auto &DL = I.getCalledFunction()->getParent()->getDataLayout(); 12007 unsigned NumElts = 0; 12008 for (unsigned ArgI = 1, ArgE = I.getNumArgOperands(); ArgI < ArgE; ++ArgI) { 12009 Type *ArgTy = I.getArgOperand(ArgI)->getType(); 12010 if (!ArgTy->isVectorTy()) 12011 break; 12012 NumElts += DL.getTypeSizeInBits(ArgTy) / 64; 12013 } 12014 Info.memVT = EVT::getVectorVT(I.getType()->getContext(), MVT::i64, NumElts); 12015 Info.ptrVal = I.getArgOperand(0); 12016 Info.offset = 0; 12017 Value *AlignArg = I.getArgOperand(I.getNumArgOperands() - 1); 12018 Info.align = cast<ConstantInt>(AlignArg)->getZExtValue(); 12019 Info.vol = false; // volatile stores with NEON intrinsics not supported 12020 Info.readMem = false; 12021 Info.writeMem = true; 12022 return true; 12023 } 12024 case Intrinsic::arm_ldaex: 12025 case Intrinsic::arm_ldrex: { 12026 auto &DL = I.getCalledFunction()->getParent()->getDataLayout(); 12027 PointerType *PtrTy = cast<PointerType>(I.getArgOperand(0)->getType()); 12028 Info.opc = ISD::INTRINSIC_W_CHAIN; 12029 Info.memVT = MVT::getVT(PtrTy->getElementType()); 12030 Info.ptrVal = I.getArgOperand(0); 12031 Info.offset = 0; 12032 Info.align = DL.getABITypeAlignment(PtrTy->getElementType()); 12033 Info.vol = true; 12034 Info.readMem = true; 12035 Info.writeMem = false; 12036 return true; 12037 } 12038 case Intrinsic::arm_stlex: 12039 case Intrinsic::arm_strex: { 12040 auto &DL = I.getCalledFunction()->getParent()->getDataLayout(); 12041 PointerType *PtrTy = cast<PointerType>(I.getArgOperand(1)->getType()); 12042 Info.opc = ISD::INTRINSIC_W_CHAIN; 12043 Info.memVT = MVT::getVT(PtrTy->getElementType()); 12044 Info.ptrVal = I.getArgOperand(1); 12045 Info.offset = 0; 12046 Info.align = DL.getABITypeAlignment(PtrTy->getElementType()); 12047 Info.vol = true; 12048 Info.readMem = false; 12049 Info.writeMem = true; 12050 return true; 12051 } 12052 case Intrinsic::arm_stlexd: 12053 case Intrinsic::arm_strexd: { 12054 Info.opc = ISD::INTRINSIC_W_CHAIN; 12055 Info.memVT = MVT::i64; 12056 Info.ptrVal = I.getArgOperand(2); 12057 Info.offset = 0; 12058 Info.align = 8; 12059 Info.vol = true; 12060 Info.readMem = false; 12061 Info.writeMem = true; 12062 return true; 12063 } 12064 case Intrinsic::arm_ldaexd: 12065 case Intrinsic::arm_ldrexd: { 12066 Info.opc = ISD::INTRINSIC_W_CHAIN; 12067 Info.memVT = MVT::i64; 12068 Info.ptrVal = I.getArgOperand(0); 12069 Info.offset = 0; 12070 Info.align = 8; 12071 Info.vol = true; 12072 Info.readMem = true; 12073 Info.writeMem = false; 12074 return true; 12075 } 12076 default: 12077 break; 12078 } 12079 12080 return false; 12081 } 12082 12083 /// \brief Returns true if it is beneficial to convert a load of a constant 12084 /// to just the constant itself. 12085 bool ARMTargetLowering::shouldConvertConstantLoadToIntImm(const APInt &Imm, 12086 Type *Ty) const { 12087 assert(Ty->isIntegerTy()); 12088 12089 unsigned Bits = Ty->getPrimitiveSizeInBits(); 12090 if (Bits == 0 || Bits > 32) 12091 return false; 12092 return true; 12093 } 12094 12095 Instruction* ARMTargetLowering::makeDMB(IRBuilder<> &Builder, 12096 ARM_MB::MemBOpt Domain) const { 12097 Module *M = Builder.GetInsertBlock()->getParent()->getParent(); 12098 12099 // First, if the target has no DMB, see what fallback we can use. 12100 if (!Subtarget->hasDataBarrier()) { 12101 // Some ARMv6 cpus can support data barriers with an mcr instruction. 12102 // Thumb1 and pre-v6 ARM mode use a libcall instead and should never get 12103 // here. 12104 if (Subtarget->hasV6Ops() && !Subtarget->isThumb()) { 12105 Function *MCR = llvm::Intrinsic::getDeclaration(M, Intrinsic::arm_mcr); 12106 Value* args[6] = {Builder.getInt32(15), Builder.getInt32(0), 12107 Builder.getInt32(0), Builder.getInt32(7), 12108 Builder.getInt32(10), Builder.getInt32(5)}; 12109 return Builder.CreateCall(MCR, args); 12110 } else { 12111 // Instead of using barriers, atomic accesses on these subtargets use 12112 // libcalls. 12113 llvm_unreachable("makeDMB on a target so old that it has no barriers"); 12114 } 12115 } else { 12116 Function *DMB = llvm::Intrinsic::getDeclaration(M, Intrinsic::arm_dmb); 12117 // Only a full system barrier exists in the M-class architectures. 12118 Domain = Subtarget->isMClass() ? ARM_MB::SY : Domain; 12119 Constant *CDomain = Builder.getInt32(Domain); 12120 return Builder.CreateCall(DMB, CDomain); 12121 } 12122 } 12123 12124 // Based on http://www.cl.cam.ac.uk/~pes20/cpp/cpp0xmappings.html 12125 Instruction* ARMTargetLowering::emitLeadingFence(IRBuilder<> &Builder, 12126 AtomicOrdering Ord, bool IsStore, 12127 bool IsLoad) const { 12128 switch (Ord) { 12129 case AtomicOrdering::NotAtomic: 12130 case AtomicOrdering::Unordered: 12131 llvm_unreachable("Invalid fence: unordered/non-atomic"); 12132 case AtomicOrdering::Monotonic: 12133 case AtomicOrdering::Acquire: 12134 return nullptr; // Nothing to do 12135 case AtomicOrdering::SequentiallyConsistent: 12136 if (!IsStore) 12137 return nullptr; // Nothing to do 12138 /*FALLTHROUGH*/ 12139 case AtomicOrdering::Release: 12140 case AtomicOrdering::AcquireRelease: 12141 if (Subtarget->isSwift()) 12142 return makeDMB(Builder, ARM_MB::ISHST); 12143 // FIXME: add a comment with a link to documentation justifying this. 12144 else 12145 return makeDMB(Builder, ARM_MB::ISH); 12146 } 12147 llvm_unreachable("Unknown fence ordering in emitLeadingFence"); 12148 } 12149 12150 Instruction* ARMTargetLowering::emitTrailingFence(IRBuilder<> &Builder, 12151 AtomicOrdering Ord, bool IsStore, 12152 bool IsLoad) const { 12153 switch (Ord) { 12154 case AtomicOrdering::NotAtomic: 12155 case AtomicOrdering::Unordered: 12156 llvm_unreachable("Invalid fence: unordered/not-atomic"); 12157 case AtomicOrdering::Monotonic: 12158 case AtomicOrdering::Release: 12159 return nullptr; // Nothing to do 12160 case AtomicOrdering::Acquire: 12161 case AtomicOrdering::AcquireRelease: 12162 case AtomicOrdering::SequentiallyConsistent: 12163 return makeDMB(Builder, ARM_MB::ISH); 12164 } 12165 llvm_unreachable("Unknown fence ordering in emitTrailingFence"); 12166 } 12167 12168 // Loads and stores less than 64-bits are already atomic; ones above that 12169 // are doomed anyway, so defer to the default libcall and blame the OS when 12170 // things go wrong. Cortex M doesn't have ldrexd/strexd though, so don't emit 12171 // anything for those. 12172 bool ARMTargetLowering::shouldExpandAtomicStoreInIR(StoreInst *SI) const { 12173 unsigned Size = SI->getValueOperand()->getType()->getPrimitiveSizeInBits(); 12174 return (Size == 64) && !Subtarget->isMClass(); 12175 } 12176 12177 // Loads and stores less than 64-bits are already atomic; ones above that 12178 // are doomed anyway, so defer to the default libcall and blame the OS when 12179 // things go wrong. Cortex M doesn't have ldrexd/strexd though, so don't emit 12180 // anything for those. 12181 // FIXME: ldrd and strd are atomic if the CPU has LPAE (e.g. A15 has that 12182 // guarantee, see DDI0406C ARM architecture reference manual, 12183 // sections A8.8.72-74 LDRD) 12184 TargetLowering::AtomicExpansionKind 12185 ARMTargetLowering::shouldExpandAtomicLoadInIR(LoadInst *LI) const { 12186 unsigned Size = LI->getType()->getPrimitiveSizeInBits(); 12187 return ((Size == 64) && !Subtarget->isMClass()) ? AtomicExpansionKind::LLOnly 12188 : AtomicExpansionKind::None; 12189 } 12190 12191 // For the real atomic operations, we have ldrex/strex up to 32 bits, 12192 // and up to 64 bits on the non-M profiles 12193 TargetLowering::AtomicExpansionKind 12194 ARMTargetLowering::shouldExpandAtomicRMWInIR(AtomicRMWInst *AI) const { 12195 unsigned Size = AI->getType()->getPrimitiveSizeInBits(); 12196 return (Size <= (Subtarget->isMClass() ? 32U : 64U)) 12197 ? AtomicExpansionKind::LLSC 12198 : AtomicExpansionKind::None; 12199 } 12200 12201 bool ARMTargetLowering::shouldExpandAtomicCmpXchgInIR( 12202 AtomicCmpXchgInst *AI) const { 12203 // At -O0, fast-regalloc cannot cope with the live vregs necessary to 12204 // implement cmpxchg without spilling. If the address being exchanged is also 12205 // on the stack and close enough to the spill slot, this can lead to a 12206 // situation where the monitor always gets cleared and the atomic operation 12207 // can never succeed. So at -O0 we need a late-expanded pseudo-inst instead. 12208 return getTargetMachine().getOptLevel() != 0; 12209 } 12210 12211 bool ARMTargetLowering::shouldInsertFencesForAtomic( 12212 const Instruction *I) const { 12213 return InsertFencesForAtomic; 12214 } 12215 12216 // This has so far only been implemented for MachO. 12217 bool ARMTargetLowering::useLoadStackGuardNode() const { 12218 return Subtarget->isTargetMachO(); 12219 } 12220 12221 bool ARMTargetLowering::canCombineStoreAndExtract(Type *VectorTy, Value *Idx, 12222 unsigned &Cost) const { 12223 // If we do not have NEON, vector types are not natively supported. 12224 if (!Subtarget->hasNEON()) 12225 return false; 12226 12227 // Floating point values and vector values map to the same register file. 12228 // Therefore, although we could do a store extract of a vector type, this is 12229 // better to leave at float as we have more freedom in the addressing mode for 12230 // those. 12231 if (VectorTy->isFPOrFPVectorTy()) 12232 return false; 12233 12234 // If the index is unknown at compile time, this is very expensive to lower 12235 // and it is not possible to combine the store with the extract. 12236 if (!isa<ConstantInt>(Idx)) 12237 return false; 12238 12239 assert(VectorTy->isVectorTy() && "VectorTy is not a vector type"); 12240 unsigned BitWidth = cast<VectorType>(VectorTy)->getBitWidth(); 12241 // We can do a store + vector extract on any vector that fits perfectly in a D 12242 // or Q register. 12243 if (BitWidth == 64 || BitWidth == 128) { 12244 Cost = 0; 12245 return true; 12246 } 12247 return false; 12248 } 12249 12250 bool ARMTargetLowering::isCheapToSpeculateCttz() const { 12251 return Subtarget->hasV6T2Ops(); 12252 } 12253 12254 bool ARMTargetLowering::isCheapToSpeculateCtlz() const { 12255 return Subtarget->hasV6T2Ops(); 12256 } 12257 12258 Value *ARMTargetLowering::emitLoadLinked(IRBuilder<> &Builder, Value *Addr, 12259 AtomicOrdering Ord) const { 12260 Module *M = Builder.GetInsertBlock()->getParent()->getParent(); 12261 Type *ValTy = cast<PointerType>(Addr->getType())->getElementType(); 12262 bool IsAcquire = isAcquireOrStronger(Ord); 12263 12264 // Since i64 isn't legal and intrinsics don't get type-lowered, the ldrexd 12265 // intrinsic must return {i32, i32} and we have to recombine them into a 12266 // single i64 here. 12267 if (ValTy->getPrimitiveSizeInBits() == 64) { 12268 Intrinsic::ID Int = 12269 IsAcquire ? Intrinsic::arm_ldaexd : Intrinsic::arm_ldrexd; 12270 Function *Ldrex = llvm::Intrinsic::getDeclaration(M, Int); 12271 12272 Addr = Builder.CreateBitCast(Addr, Type::getInt8PtrTy(M->getContext())); 12273 Value *LoHi = Builder.CreateCall(Ldrex, Addr, "lohi"); 12274 12275 Value *Lo = Builder.CreateExtractValue(LoHi, 0, "lo"); 12276 Value *Hi = Builder.CreateExtractValue(LoHi, 1, "hi"); 12277 if (!Subtarget->isLittle()) 12278 std::swap (Lo, Hi); 12279 Lo = Builder.CreateZExt(Lo, ValTy, "lo64"); 12280 Hi = Builder.CreateZExt(Hi, ValTy, "hi64"); 12281 return Builder.CreateOr( 12282 Lo, Builder.CreateShl(Hi, ConstantInt::get(ValTy, 32)), "val64"); 12283 } 12284 12285 Type *Tys[] = { Addr->getType() }; 12286 Intrinsic::ID Int = IsAcquire ? Intrinsic::arm_ldaex : Intrinsic::arm_ldrex; 12287 Function *Ldrex = llvm::Intrinsic::getDeclaration(M, Int, Tys); 12288 12289 return Builder.CreateTruncOrBitCast( 12290 Builder.CreateCall(Ldrex, Addr), 12291 cast<PointerType>(Addr->getType())->getElementType()); 12292 } 12293 12294 void ARMTargetLowering::emitAtomicCmpXchgNoStoreLLBalance( 12295 IRBuilder<> &Builder) const { 12296 if (!Subtarget->hasV7Ops()) 12297 return; 12298 Module *M = Builder.GetInsertBlock()->getParent()->getParent(); 12299 Builder.CreateCall(llvm::Intrinsic::getDeclaration(M, Intrinsic::arm_clrex)); 12300 } 12301 12302 Value *ARMTargetLowering::emitStoreConditional(IRBuilder<> &Builder, Value *Val, 12303 Value *Addr, 12304 AtomicOrdering Ord) const { 12305 Module *M = Builder.GetInsertBlock()->getParent()->getParent(); 12306 bool IsRelease = isReleaseOrStronger(Ord); 12307 12308 // Since the intrinsics must have legal type, the i64 intrinsics take two 12309 // parameters: "i32, i32". We must marshal Val into the appropriate form 12310 // before the call. 12311 if (Val->getType()->getPrimitiveSizeInBits() == 64) { 12312 Intrinsic::ID Int = 12313 IsRelease ? Intrinsic::arm_stlexd : Intrinsic::arm_strexd; 12314 Function *Strex = Intrinsic::getDeclaration(M, Int); 12315 Type *Int32Ty = Type::getInt32Ty(M->getContext()); 12316 12317 Value *Lo = Builder.CreateTrunc(Val, Int32Ty, "lo"); 12318 Value *Hi = Builder.CreateTrunc(Builder.CreateLShr(Val, 32), Int32Ty, "hi"); 12319 if (!Subtarget->isLittle()) 12320 std::swap (Lo, Hi); 12321 Addr = Builder.CreateBitCast(Addr, Type::getInt8PtrTy(M->getContext())); 12322 return Builder.CreateCall(Strex, {Lo, Hi, Addr}); 12323 } 12324 12325 Intrinsic::ID Int = IsRelease ? Intrinsic::arm_stlex : Intrinsic::arm_strex; 12326 Type *Tys[] = { Addr->getType() }; 12327 Function *Strex = Intrinsic::getDeclaration(M, Int, Tys); 12328 12329 return Builder.CreateCall( 12330 Strex, {Builder.CreateZExtOrBitCast( 12331 Val, Strex->getFunctionType()->getParamType(0)), 12332 Addr}); 12333 } 12334 12335 /// \brief Lower an interleaved load into a vldN intrinsic. 12336 /// 12337 /// E.g. Lower an interleaved load (Factor = 2): 12338 /// %wide.vec = load <8 x i32>, <8 x i32>* %ptr, align 4 12339 /// %v0 = shuffle %wide.vec, undef, <0, 2, 4, 6> ; Extract even elements 12340 /// %v1 = shuffle %wide.vec, undef, <1, 3, 5, 7> ; Extract odd elements 12341 /// 12342 /// Into: 12343 /// %vld2 = { <4 x i32>, <4 x i32> } call llvm.arm.neon.vld2(%ptr, 4) 12344 /// %vec0 = extractelement { <4 x i32>, <4 x i32> } %vld2, i32 0 12345 /// %vec1 = extractelement { <4 x i32>, <4 x i32> } %vld2, i32 1 12346 bool ARMTargetLowering::lowerInterleavedLoad( 12347 LoadInst *LI, ArrayRef<ShuffleVectorInst *> Shuffles, 12348 ArrayRef<unsigned> Indices, unsigned Factor) const { 12349 assert(Factor >= 2 && Factor <= getMaxSupportedInterleaveFactor() && 12350 "Invalid interleave factor"); 12351 assert(!Shuffles.empty() && "Empty shufflevector input"); 12352 assert(Shuffles.size() == Indices.size() && 12353 "Unmatched number of shufflevectors and indices"); 12354 12355 VectorType *VecTy = Shuffles[0]->getType(); 12356 Type *EltTy = VecTy->getVectorElementType(); 12357 12358 const DataLayout &DL = LI->getModule()->getDataLayout(); 12359 unsigned VecSize = DL.getTypeSizeInBits(VecTy); 12360 bool EltIs64Bits = DL.getTypeSizeInBits(EltTy) == 64; 12361 12362 // Skip if we do not have NEON and skip illegal vector types and vector types 12363 // with i64/f64 elements (vldN doesn't support i64/f64 elements). 12364 if (!Subtarget->hasNEON() || (VecSize != 64 && VecSize != 128) || EltIs64Bits) 12365 return false; 12366 12367 // A pointer vector can not be the return type of the ldN intrinsics. Need to 12368 // load integer vectors first and then convert to pointer vectors. 12369 if (EltTy->isPointerTy()) 12370 VecTy = 12371 VectorType::get(DL.getIntPtrType(EltTy), VecTy->getVectorNumElements()); 12372 12373 static const Intrinsic::ID LoadInts[3] = {Intrinsic::arm_neon_vld2, 12374 Intrinsic::arm_neon_vld3, 12375 Intrinsic::arm_neon_vld4}; 12376 12377 IRBuilder<> Builder(LI); 12378 SmallVector<Value *, 2> Ops; 12379 12380 Type *Int8Ptr = Builder.getInt8PtrTy(LI->getPointerAddressSpace()); 12381 Ops.push_back(Builder.CreateBitCast(LI->getPointerOperand(), Int8Ptr)); 12382 Ops.push_back(Builder.getInt32(LI->getAlignment())); 12383 12384 Type *Tys[] = { VecTy, Int8Ptr }; 12385 Function *VldnFunc = 12386 Intrinsic::getDeclaration(LI->getModule(), LoadInts[Factor - 2], Tys); 12387 CallInst *VldN = Builder.CreateCall(VldnFunc, Ops, "vldN"); 12388 12389 // Replace uses of each shufflevector with the corresponding vector loaded 12390 // by ldN. 12391 for (unsigned i = 0; i < Shuffles.size(); i++) { 12392 ShuffleVectorInst *SV = Shuffles[i]; 12393 unsigned Index = Indices[i]; 12394 12395 Value *SubVec = Builder.CreateExtractValue(VldN, Index); 12396 12397 // Convert the integer vector to pointer vector if the element is pointer. 12398 if (EltTy->isPointerTy()) 12399 SubVec = Builder.CreateIntToPtr(SubVec, SV->getType()); 12400 12401 SV->replaceAllUsesWith(SubVec); 12402 } 12403 12404 return true; 12405 } 12406 12407 /// \brief Get a mask consisting of sequential integers starting from \p Start. 12408 /// 12409 /// I.e. <Start, Start + 1, ..., Start + NumElts - 1> 12410 static Constant *getSequentialMask(IRBuilder<> &Builder, unsigned Start, 12411 unsigned NumElts) { 12412 SmallVector<Constant *, 16> Mask; 12413 for (unsigned i = 0; i < NumElts; i++) 12414 Mask.push_back(Builder.getInt32(Start + i)); 12415 12416 return ConstantVector::get(Mask); 12417 } 12418 12419 /// \brief Lower an interleaved store into a vstN intrinsic. 12420 /// 12421 /// E.g. Lower an interleaved store (Factor = 3): 12422 /// %i.vec = shuffle <8 x i32> %v0, <8 x i32> %v1, 12423 /// <0, 4, 8, 1, 5, 9, 2, 6, 10, 3, 7, 11> 12424 /// store <12 x i32> %i.vec, <12 x i32>* %ptr, align 4 12425 /// 12426 /// Into: 12427 /// %sub.v0 = shuffle <8 x i32> %v0, <8 x i32> v1, <0, 1, 2, 3> 12428 /// %sub.v1 = shuffle <8 x i32> %v0, <8 x i32> v1, <4, 5, 6, 7> 12429 /// %sub.v2 = shuffle <8 x i32> %v0, <8 x i32> v1, <8, 9, 10, 11> 12430 /// call void llvm.arm.neon.vst3(%ptr, %sub.v0, %sub.v1, %sub.v2, 4) 12431 /// 12432 /// Note that the new shufflevectors will be removed and we'll only generate one 12433 /// vst3 instruction in CodeGen. 12434 bool ARMTargetLowering::lowerInterleavedStore(StoreInst *SI, 12435 ShuffleVectorInst *SVI, 12436 unsigned Factor) const { 12437 assert(Factor >= 2 && Factor <= getMaxSupportedInterleaveFactor() && 12438 "Invalid interleave factor"); 12439 12440 VectorType *VecTy = SVI->getType(); 12441 assert(VecTy->getVectorNumElements() % Factor == 0 && 12442 "Invalid interleaved store"); 12443 12444 unsigned NumSubElts = VecTy->getVectorNumElements() / Factor; 12445 Type *EltTy = VecTy->getVectorElementType(); 12446 VectorType *SubVecTy = VectorType::get(EltTy, NumSubElts); 12447 12448 const DataLayout &DL = SI->getModule()->getDataLayout(); 12449 unsigned SubVecSize = DL.getTypeSizeInBits(SubVecTy); 12450 bool EltIs64Bits = DL.getTypeSizeInBits(EltTy) == 64; 12451 12452 // Skip if we do not have NEON and skip illegal vector types and vector types 12453 // with i64/f64 elements (vstN doesn't support i64/f64 elements). 12454 if (!Subtarget->hasNEON() || (SubVecSize != 64 && SubVecSize != 128) || 12455 EltIs64Bits) 12456 return false; 12457 12458 Value *Op0 = SVI->getOperand(0); 12459 Value *Op1 = SVI->getOperand(1); 12460 IRBuilder<> Builder(SI); 12461 12462 // StN intrinsics don't support pointer vectors as arguments. Convert pointer 12463 // vectors to integer vectors. 12464 if (EltTy->isPointerTy()) { 12465 Type *IntTy = DL.getIntPtrType(EltTy); 12466 12467 // Convert to the corresponding integer vector. 12468 Type *IntVecTy = 12469 VectorType::get(IntTy, Op0->getType()->getVectorNumElements()); 12470 Op0 = Builder.CreatePtrToInt(Op0, IntVecTy); 12471 Op1 = Builder.CreatePtrToInt(Op1, IntVecTy); 12472 12473 SubVecTy = VectorType::get(IntTy, NumSubElts); 12474 } 12475 12476 static const Intrinsic::ID StoreInts[3] = {Intrinsic::arm_neon_vst2, 12477 Intrinsic::arm_neon_vst3, 12478 Intrinsic::arm_neon_vst4}; 12479 SmallVector<Value *, 6> Ops; 12480 12481 Type *Int8Ptr = Builder.getInt8PtrTy(SI->getPointerAddressSpace()); 12482 Ops.push_back(Builder.CreateBitCast(SI->getPointerOperand(), Int8Ptr)); 12483 12484 Type *Tys[] = { Int8Ptr, SubVecTy }; 12485 Function *VstNFunc = Intrinsic::getDeclaration( 12486 SI->getModule(), StoreInts[Factor - 2], Tys); 12487 12488 // Split the shufflevector operands into sub vectors for the new vstN call. 12489 for (unsigned i = 0; i < Factor; i++) 12490 Ops.push_back(Builder.CreateShuffleVector( 12491 Op0, Op1, getSequentialMask(Builder, NumSubElts * i, NumSubElts))); 12492 12493 Ops.push_back(Builder.getInt32(SI->getAlignment())); 12494 Builder.CreateCall(VstNFunc, Ops); 12495 return true; 12496 } 12497 12498 enum HABaseType { 12499 HA_UNKNOWN = 0, 12500 HA_FLOAT, 12501 HA_DOUBLE, 12502 HA_VECT64, 12503 HA_VECT128 12504 }; 12505 12506 static bool isHomogeneousAggregate(Type *Ty, HABaseType &Base, 12507 uint64_t &Members) { 12508 if (auto *ST = dyn_cast<StructType>(Ty)) { 12509 for (unsigned i = 0; i < ST->getNumElements(); ++i) { 12510 uint64_t SubMembers = 0; 12511 if (!isHomogeneousAggregate(ST->getElementType(i), Base, SubMembers)) 12512 return false; 12513 Members += SubMembers; 12514 } 12515 } else if (auto *AT = dyn_cast<ArrayType>(Ty)) { 12516 uint64_t SubMembers = 0; 12517 if (!isHomogeneousAggregate(AT->getElementType(), Base, SubMembers)) 12518 return false; 12519 Members += SubMembers * AT->getNumElements(); 12520 } else if (Ty->isFloatTy()) { 12521 if (Base != HA_UNKNOWN && Base != HA_FLOAT) 12522 return false; 12523 Members = 1; 12524 Base = HA_FLOAT; 12525 } else if (Ty->isDoubleTy()) { 12526 if (Base != HA_UNKNOWN && Base != HA_DOUBLE) 12527 return false; 12528 Members = 1; 12529 Base = HA_DOUBLE; 12530 } else if (auto *VT = dyn_cast<VectorType>(Ty)) { 12531 Members = 1; 12532 switch (Base) { 12533 case HA_FLOAT: 12534 case HA_DOUBLE: 12535 return false; 12536 case HA_VECT64: 12537 return VT->getBitWidth() == 64; 12538 case HA_VECT128: 12539 return VT->getBitWidth() == 128; 12540 case HA_UNKNOWN: 12541 switch (VT->getBitWidth()) { 12542 case 64: 12543 Base = HA_VECT64; 12544 return true; 12545 case 128: 12546 Base = HA_VECT128; 12547 return true; 12548 default: 12549 return false; 12550 } 12551 } 12552 } 12553 12554 return (Members > 0 && Members <= 4); 12555 } 12556 12557 /// \brief Return true if a type is an AAPCS-VFP homogeneous aggregate or one of 12558 /// [N x i32] or [N x i64]. This allows front-ends to skip emitting padding when 12559 /// passing according to AAPCS rules. 12560 bool ARMTargetLowering::functionArgumentNeedsConsecutiveRegisters( 12561 Type *Ty, CallingConv::ID CallConv, bool isVarArg) const { 12562 if (getEffectiveCallingConv(CallConv, isVarArg) != 12563 CallingConv::ARM_AAPCS_VFP) 12564 return false; 12565 12566 HABaseType Base = HA_UNKNOWN; 12567 uint64_t Members = 0; 12568 bool IsHA = isHomogeneousAggregate(Ty, Base, Members); 12569 DEBUG(dbgs() << "isHA: " << IsHA << " "; Ty->dump()); 12570 12571 bool IsIntArray = Ty->isArrayTy() && Ty->getArrayElementType()->isIntegerTy(); 12572 return IsHA || IsIntArray; 12573 } 12574 12575 unsigned ARMTargetLowering::getExceptionPointerRegister( 12576 const Constant *PersonalityFn) const { 12577 // Platforms which do not use SjLj EH may return values in these registers 12578 // via the personality function. 12579 return Subtarget->useSjLjEH() ? ARM::NoRegister : ARM::R0; 12580 } 12581 12582 unsigned ARMTargetLowering::getExceptionSelectorRegister( 12583 const Constant *PersonalityFn) const { 12584 // Platforms which do not use SjLj EH may return values in these registers 12585 // via the personality function. 12586 return Subtarget->useSjLjEH() ? ARM::NoRegister : ARM::R1; 12587 } 12588 12589 void ARMTargetLowering::initializeSplitCSR(MachineBasicBlock *Entry) const { 12590 // Update IsSplitCSR in ARMFunctionInfo. 12591 ARMFunctionInfo *AFI = Entry->getParent()->getInfo<ARMFunctionInfo>(); 12592 AFI->setIsSplitCSR(true); 12593 } 12594 12595 void ARMTargetLowering::insertCopiesSplitCSR( 12596 MachineBasicBlock *Entry, 12597 const SmallVectorImpl<MachineBasicBlock *> &Exits) const { 12598 const ARMBaseRegisterInfo *TRI = Subtarget->getRegisterInfo(); 12599 const MCPhysReg *IStart = TRI->getCalleeSavedRegsViaCopy(Entry->getParent()); 12600 if (!IStart) 12601 return; 12602 12603 const TargetInstrInfo *TII = Subtarget->getInstrInfo(); 12604 MachineRegisterInfo *MRI = &Entry->getParent()->getRegInfo(); 12605 MachineBasicBlock::iterator MBBI = Entry->begin(); 12606 for (const MCPhysReg *I = IStart; *I; ++I) { 12607 const TargetRegisterClass *RC = nullptr; 12608 if (ARM::GPRRegClass.contains(*I)) 12609 RC = &ARM::GPRRegClass; 12610 else if (ARM::DPRRegClass.contains(*I)) 12611 RC = &ARM::DPRRegClass; 12612 else 12613 llvm_unreachable("Unexpected register class in CSRsViaCopy!"); 12614 12615 unsigned NewVR = MRI->createVirtualRegister(RC); 12616 // Create copy from CSR to a virtual register. 12617 // FIXME: this currently does not emit CFI pseudo-instructions, it works 12618 // fine for CXX_FAST_TLS since the C++-style TLS access functions should be 12619 // nounwind. If we want to generalize this later, we may need to emit 12620 // CFI pseudo-instructions. 12621 assert(Entry->getParent()->getFunction()->hasFnAttribute( 12622 Attribute::NoUnwind) && 12623 "Function should be nounwind in insertCopiesSplitCSR!"); 12624 Entry->addLiveIn(*I); 12625 BuildMI(*Entry, MBBI, DebugLoc(), TII->get(TargetOpcode::COPY), NewVR) 12626 .addReg(*I); 12627 12628 // Insert the copy-back instructions right before the terminator. 12629 for (auto *Exit : Exits) 12630 BuildMI(*Exit, Exit->getFirstTerminator(), DebugLoc(), 12631 TII->get(TargetOpcode::COPY), *I) 12632 .addReg(NewVR); 12633 } 12634 } 12635