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 "ARMBaseInstrInfo.h" 16 #include "ARMBaseRegisterInfo.h" 17 #include "ARMCallingConv.h" 18 #include "ARMConstantPoolValue.h" 19 #include "ARMISelLowering.h" 20 #include "ARMMachineFunctionInfo.h" 21 #include "ARMPerfectShuffle.h" 22 #include "ARMRegisterInfo.h" 23 #include "ARMSelectionDAGInfo.h" 24 #include "ARMSubtarget.h" 25 #include "MCTargetDesc/ARMAddressingModes.h" 26 #include "MCTargetDesc/ARMBaseInfo.h" 27 #include "llvm/ADT/APFloat.h" 28 #include "llvm/ADT/APInt.h" 29 #include "llvm/ADT/ArrayRef.h" 30 #include "llvm/ADT/BitVector.h" 31 #include "llvm/ADT/DenseMap.h" 32 #include "llvm/ADT/SmallPtrSet.h" 33 #include "llvm/ADT/SmallVector.h" 34 #include "llvm/ADT/Statistic.h" 35 #include "llvm/ADT/STLExtras.h" 36 #include "llvm/ADT/StringExtras.h" 37 #include "llvm/ADT/StringSwitch.h" 38 #include "llvm/ADT/StringRef.h" 39 #include "llvm/ADT/Triple.h" 40 #include "llvm/ADT/Twine.h" 41 #include "llvm/Analysis/VectorUtils.h" 42 #include "llvm/CodeGen/CallingConvLower.h" 43 #include "llvm/CodeGen/ISDOpcodes.h" 44 #include "llvm/CodeGen/IntrinsicLowering.h" 45 #include "llvm/CodeGen/MachineBasicBlock.h" 46 #include "llvm/CodeGen/MachineConstantPool.h" 47 #include "llvm/CodeGen/MachineFrameInfo.h" 48 #include "llvm/CodeGen/MachineFunction.h" 49 #include "llvm/CodeGen/MachineInstr.h" 50 #include "llvm/CodeGen/MachineInstrBuilder.h" 51 #include "llvm/CodeGen/MachineJumpTableInfo.h" 52 #include "llvm/CodeGen/MachineMemOperand.h" 53 #include "llvm/CodeGen/MachineOperand.h" 54 #include "llvm/CodeGen/MachineRegisterInfo.h" 55 #include "llvm/CodeGen/MachineValueType.h" 56 #include "llvm/CodeGen/RuntimeLibcalls.h" 57 #include "llvm/CodeGen/SelectionDAG.h" 58 #include "llvm/CodeGen/SelectionDAGNodes.h" 59 #include "llvm/CodeGen/ValueTypes.h" 60 #include "llvm/IR/Attributes.h" 61 #include "llvm/IR/CallingConv.h" 62 #include "llvm/IR/Constant.h" 63 #include "llvm/IR/Constants.h" 64 #include "llvm/IR/Function.h" 65 #include "llvm/IR/DataLayout.h" 66 #include "llvm/IR/DebugLoc.h" 67 #include "llvm/IR/DerivedTypes.h" 68 #include "llvm/IR/Function.h" 69 #include "llvm/IR/GlobalAlias.h" 70 #include "llvm/IR/GlobalValue.h" 71 #include "llvm/IR/GlobalVariable.h" 72 #include "llvm/IR/IRBuilder.h" 73 #include "llvm/IR/InlineAsm.h" 74 #include "llvm/IR/Instruction.h" 75 #include "llvm/IR/Instructions.h" 76 #include "llvm/IR/IntrinsicInst.h" 77 #include "llvm/IR/Intrinsics.h" 78 #include "llvm/IR/Module.h" 79 #include "llvm/IR/Type.h" 80 #include "llvm/IR/User.h" 81 #include "llvm/IR/Value.h" 82 #include "llvm/MC/MCInstrDesc.h" 83 #include "llvm/MC/MCInstrItineraries.h" 84 #include "llvm/MC/MCRegisterInfo.h" 85 #include "llvm/MC/MCSchedule.h" 86 #include "llvm/Support/AtomicOrdering.h" 87 #include "llvm/Support/BranchProbability.h" 88 #include "llvm/Support/Casting.h" 89 #include "llvm/Support/CodeGen.h" 90 #include "llvm/Support/CommandLine.h" 91 #include "llvm/Support/Compiler.h" 92 #include "llvm/Support/Debug.h" 93 #include "llvm/Support/ErrorHandling.h" 94 #include "llvm/Support/MathExtras.h" 95 #include "llvm/Support/raw_ostream.h" 96 #include "llvm/Target/TargetInstrInfo.h" 97 #include "llvm/Target/TargetMachine.h" 98 #include "llvm/Target/TargetOptions.h" 99 #include <algorithm> 100 #include <cassert> 101 #include <cstdint> 102 #include <cstdlib> 103 #include <iterator> 104 #include <limits> 105 #include <tuple> 106 #include <string> 107 #include <utility> 108 #include <vector> 109 110 using namespace llvm; 111 112 #define DEBUG_TYPE "arm-isel" 113 114 STATISTIC(NumTailCalls, "Number of tail calls"); 115 STATISTIC(NumMovwMovt, "Number of GAs materialized with movw + movt"); 116 STATISTIC(NumLoopByVals, "Number of loops generated for byval arguments"); 117 STATISTIC(NumConstpoolPromoted, 118 "Number of constants with their storage promoted into constant pools"); 119 120 static cl::opt<bool> 121 ARMInterworking("arm-interworking", cl::Hidden, 122 cl::desc("Enable / disable ARM interworking (for debugging only)"), 123 cl::init(true)); 124 125 static cl::opt<bool> EnableConstpoolPromotion( 126 "arm-promote-constant", cl::Hidden, 127 cl::desc("Enable / disable promotion of unnamed_addr constants into " 128 "constant pools"), 129 cl::init(true)); 130 static cl::opt<unsigned> ConstpoolPromotionMaxSize( 131 "arm-promote-constant-max-size", cl::Hidden, 132 cl::desc("Maximum size of constant to promote into a constant pool"), 133 cl::init(64)); 134 static cl::opt<unsigned> ConstpoolPromotionMaxTotal( 135 "arm-promote-constant-max-total", cl::Hidden, 136 cl::desc("Maximum size of ALL constants to promote into a constant pool"), 137 cl::init(128)); 138 139 // The APCS parameter registers. 140 static const MCPhysReg GPRArgRegs[] = { 141 ARM::R0, ARM::R1, ARM::R2, ARM::R3 142 }; 143 144 void ARMTargetLowering::addTypeForNEON(MVT VT, MVT PromotedLdStVT, 145 MVT PromotedBitwiseVT) { 146 if (VT != PromotedLdStVT) { 147 setOperationAction(ISD::LOAD, VT, Promote); 148 AddPromotedToType (ISD::LOAD, VT, PromotedLdStVT); 149 150 setOperationAction(ISD::STORE, VT, Promote); 151 AddPromotedToType (ISD::STORE, VT, PromotedLdStVT); 152 } 153 154 MVT ElemTy = VT.getVectorElementType(); 155 if (ElemTy != MVT::f64) 156 setOperationAction(ISD::SETCC, VT, Custom); 157 setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Custom); 158 setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom); 159 if (ElemTy == MVT::i32) { 160 setOperationAction(ISD::SINT_TO_FP, VT, Custom); 161 setOperationAction(ISD::UINT_TO_FP, VT, Custom); 162 setOperationAction(ISD::FP_TO_SINT, VT, Custom); 163 setOperationAction(ISD::FP_TO_UINT, VT, Custom); 164 } else { 165 setOperationAction(ISD::SINT_TO_FP, VT, Expand); 166 setOperationAction(ISD::UINT_TO_FP, VT, Expand); 167 setOperationAction(ISD::FP_TO_SINT, VT, Expand); 168 setOperationAction(ISD::FP_TO_UINT, VT, Expand); 169 } 170 setOperationAction(ISD::BUILD_VECTOR, VT, Custom); 171 setOperationAction(ISD::VECTOR_SHUFFLE, VT, Custom); 172 setOperationAction(ISD::CONCAT_VECTORS, VT, Legal); 173 setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Legal); 174 setOperationAction(ISD::SELECT, VT, Expand); 175 setOperationAction(ISD::SELECT_CC, VT, Expand); 176 setOperationAction(ISD::VSELECT, VT, Expand); 177 setOperationAction(ISD::SIGN_EXTEND_INREG, VT, Expand); 178 if (VT.isInteger()) { 179 setOperationAction(ISD::SHL, VT, Custom); 180 setOperationAction(ISD::SRA, VT, Custom); 181 setOperationAction(ISD::SRL, VT, Custom); 182 } 183 184 // Promote all bit-wise operations. 185 if (VT.isInteger() && VT != PromotedBitwiseVT) { 186 setOperationAction(ISD::AND, VT, Promote); 187 AddPromotedToType (ISD::AND, VT, PromotedBitwiseVT); 188 setOperationAction(ISD::OR, VT, Promote); 189 AddPromotedToType (ISD::OR, VT, PromotedBitwiseVT); 190 setOperationAction(ISD::XOR, VT, Promote); 191 AddPromotedToType (ISD::XOR, VT, PromotedBitwiseVT); 192 } 193 194 // Neon does not support vector divide/remainder operations. 195 setOperationAction(ISD::SDIV, VT, Expand); 196 setOperationAction(ISD::UDIV, VT, Expand); 197 setOperationAction(ISD::FDIV, VT, Expand); 198 setOperationAction(ISD::SREM, VT, Expand); 199 setOperationAction(ISD::UREM, VT, Expand); 200 setOperationAction(ISD::FREM, VT, Expand); 201 202 if (!VT.isFloatingPoint() && 203 VT != MVT::v2i64 && VT != MVT::v1i64) 204 for (unsigned Opcode : {ISD::SMIN, ISD::SMAX, ISD::UMIN, ISD::UMAX}) 205 setOperationAction(Opcode, VT, Legal); 206 } 207 208 void ARMTargetLowering::addDRTypeForNEON(MVT VT) { 209 addRegisterClass(VT, &ARM::DPRRegClass); 210 addTypeForNEON(VT, MVT::f64, MVT::v2i32); 211 } 212 213 void ARMTargetLowering::addQRTypeForNEON(MVT VT) { 214 addRegisterClass(VT, &ARM::DPairRegClass); 215 addTypeForNEON(VT, MVT::v2f64, MVT::v4i32); 216 } 217 218 ARMTargetLowering::ARMTargetLowering(const TargetMachine &TM, 219 const ARMSubtarget &STI) 220 : TargetLowering(TM), Subtarget(&STI) { 221 RegInfo = Subtarget->getRegisterInfo(); 222 Itins = Subtarget->getInstrItineraryData(); 223 224 setBooleanVectorContents(ZeroOrNegativeOneBooleanContent); 225 226 if (!Subtarget->isTargetDarwin() && !Subtarget->isTargetIOS() && 227 !Subtarget->isTargetWatchOS()) { 228 const auto &E = Subtarget->getTargetTriple().getEnvironment(); 229 230 bool IsHFTarget = E == Triple::EABIHF || E == Triple::GNUEABIHF || 231 E == Triple::MuslEABIHF; 232 // Windows is a special case. Technically, we will replace all of the "GNU" 233 // calls with calls to MSVCRT if appropriate and adjust the calling 234 // convention then. 235 IsHFTarget = IsHFTarget || Subtarget->isTargetWindows(); 236 237 for (int LCID = 0; LCID < RTLIB::UNKNOWN_LIBCALL; ++LCID) 238 setLibcallCallingConv(static_cast<RTLIB::Libcall>(LCID), 239 IsHFTarget ? CallingConv::ARM_AAPCS_VFP 240 : CallingConv::ARM_AAPCS); 241 } 242 243 if (Subtarget->isTargetMachO()) { 244 // Uses VFP for Thumb libfuncs if available. 245 if (Subtarget->isThumb() && Subtarget->hasVFP2() && 246 Subtarget->hasARMOps() && !Subtarget->useSoftFloat()) { 247 static const struct { 248 const RTLIB::Libcall Op; 249 const char * const Name; 250 const ISD::CondCode Cond; 251 } LibraryCalls[] = { 252 // Single-precision floating-point arithmetic. 253 { RTLIB::ADD_F32, "__addsf3vfp", ISD::SETCC_INVALID }, 254 { RTLIB::SUB_F32, "__subsf3vfp", ISD::SETCC_INVALID }, 255 { RTLIB::MUL_F32, "__mulsf3vfp", ISD::SETCC_INVALID }, 256 { RTLIB::DIV_F32, "__divsf3vfp", ISD::SETCC_INVALID }, 257 258 // Double-precision floating-point arithmetic. 259 { RTLIB::ADD_F64, "__adddf3vfp", ISD::SETCC_INVALID }, 260 { RTLIB::SUB_F64, "__subdf3vfp", ISD::SETCC_INVALID }, 261 { RTLIB::MUL_F64, "__muldf3vfp", ISD::SETCC_INVALID }, 262 { RTLIB::DIV_F64, "__divdf3vfp", ISD::SETCC_INVALID }, 263 264 // Single-precision comparisons. 265 { RTLIB::OEQ_F32, "__eqsf2vfp", ISD::SETNE }, 266 { RTLIB::UNE_F32, "__nesf2vfp", ISD::SETNE }, 267 { RTLIB::OLT_F32, "__ltsf2vfp", ISD::SETNE }, 268 { RTLIB::OLE_F32, "__lesf2vfp", ISD::SETNE }, 269 { RTLIB::OGE_F32, "__gesf2vfp", ISD::SETNE }, 270 { RTLIB::OGT_F32, "__gtsf2vfp", ISD::SETNE }, 271 { RTLIB::UO_F32, "__unordsf2vfp", ISD::SETNE }, 272 { RTLIB::O_F32, "__unordsf2vfp", ISD::SETEQ }, 273 274 // Double-precision comparisons. 275 { RTLIB::OEQ_F64, "__eqdf2vfp", ISD::SETNE }, 276 { RTLIB::UNE_F64, "__nedf2vfp", ISD::SETNE }, 277 { RTLIB::OLT_F64, "__ltdf2vfp", ISD::SETNE }, 278 { RTLIB::OLE_F64, "__ledf2vfp", ISD::SETNE }, 279 { RTLIB::OGE_F64, "__gedf2vfp", ISD::SETNE }, 280 { RTLIB::OGT_F64, "__gtdf2vfp", ISD::SETNE }, 281 { RTLIB::UO_F64, "__unorddf2vfp", ISD::SETNE }, 282 { RTLIB::O_F64, "__unorddf2vfp", ISD::SETEQ }, 283 284 // Floating-point to integer conversions. 285 // i64 conversions are done via library routines even when generating VFP 286 // instructions, so use the same ones. 287 { RTLIB::FPTOSINT_F64_I32, "__fixdfsivfp", ISD::SETCC_INVALID }, 288 { RTLIB::FPTOUINT_F64_I32, "__fixunsdfsivfp", ISD::SETCC_INVALID }, 289 { RTLIB::FPTOSINT_F32_I32, "__fixsfsivfp", ISD::SETCC_INVALID }, 290 { RTLIB::FPTOUINT_F32_I32, "__fixunssfsivfp", ISD::SETCC_INVALID }, 291 292 // Conversions between floating types. 293 { RTLIB::FPROUND_F64_F32, "__truncdfsf2vfp", ISD::SETCC_INVALID }, 294 { RTLIB::FPEXT_F32_F64, "__extendsfdf2vfp", ISD::SETCC_INVALID }, 295 296 // Integer to floating-point conversions. 297 // i64 conversions are done via library routines even when generating VFP 298 // instructions, so use the same ones. 299 // FIXME: There appears to be some naming inconsistency in ARM libgcc: 300 // e.g., __floatunsidf vs. __floatunssidfvfp. 301 { RTLIB::SINTTOFP_I32_F64, "__floatsidfvfp", ISD::SETCC_INVALID }, 302 { RTLIB::UINTTOFP_I32_F64, "__floatunssidfvfp", ISD::SETCC_INVALID }, 303 { RTLIB::SINTTOFP_I32_F32, "__floatsisfvfp", ISD::SETCC_INVALID }, 304 { RTLIB::UINTTOFP_I32_F32, "__floatunssisfvfp", ISD::SETCC_INVALID }, 305 }; 306 307 for (const auto &LC : LibraryCalls) { 308 setLibcallName(LC.Op, LC.Name); 309 if (LC.Cond != ISD::SETCC_INVALID) 310 setCmpLibcallCC(LC.Op, LC.Cond); 311 } 312 } 313 314 // Set the correct calling convention for ARMv7k WatchOS. It's just 315 // AAPCS_VFP for functions as simple as libcalls. 316 if (Subtarget->isTargetWatchABI()) { 317 for (int i = 0; i < RTLIB::UNKNOWN_LIBCALL; ++i) 318 setLibcallCallingConv((RTLIB::Libcall)i, CallingConv::ARM_AAPCS_VFP); 319 } 320 } 321 322 // These libcalls are not available in 32-bit. 323 setLibcallName(RTLIB::SHL_I128, nullptr); 324 setLibcallName(RTLIB::SRL_I128, nullptr); 325 setLibcallName(RTLIB::SRA_I128, nullptr); 326 327 // RTLIB 328 if (Subtarget->isAAPCS_ABI() && 329 (Subtarget->isTargetAEABI() || Subtarget->isTargetGNUAEABI() || 330 Subtarget->isTargetMuslAEABI() || Subtarget->isTargetAndroid())) { 331 static const struct { 332 const RTLIB::Libcall Op; 333 const char * const Name; 334 const CallingConv::ID CC; 335 const ISD::CondCode Cond; 336 } LibraryCalls[] = { 337 // Double-precision floating-point arithmetic helper functions 338 // RTABI chapter 4.1.2, Table 2 339 { RTLIB::ADD_F64, "__aeabi_dadd", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 340 { RTLIB::DIV_F64, "__aeabi_ddiv", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 341 { RTLIB::MUL_F64, "__aeabi_dmul", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 342 { RTLIB::SUB_F64, "__aeabi_dsub", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 343 344 // Double-precision floating-point comparison helper functions 345 // RTABI chapter 4.1.2, Table 3 346 { RTLIB::OEQ_F64, "__aeabi_dcmpeq", CallingConv::ARM_AAPCS, ISD::SETNE }, 347 { RTLIB::UNE_F64, "__aeabi_dcmpeq", CallingConv::ARM_AAPCS, ISD::SETEQ }, 348 { RTLIB::OLT_F64, "__aeabi_dcmplt", CallingConv::ARM_AAPCS, ISD::SETNE }, 349 { RTLIB::OLE_F64, "__aeabi_dcmple", CallingConv::ARM_AAPCS, ISD::SETNE }, 350 { RTLIB::OGE_F64, "__aeabi_dcmpge", CallingConv::ARM_AAPCS, ISD::SETNE }, 351 { RTLIB::OGT_F64, "__aeabi_dcmpgt", CallingConv::ARM_AAPCS, ISD::SETNE }, 352 { RTLIB::UO_F64, "__aeabi_dcmpun", CallingConv::ARM_AAPCS, ISD::SETNE }, 353 { RTLIB::O_F64, "__aeabi_dcmpun", CallingConv::ARM_AAPCS, ISD::SETEQ }, 354 355 // Single-precision floating-point arithmetic helper functions 356 // RTABI chapter 4.1.2, Table 4 357 { RTLIB::ADD_F32, "__aeabi_fadd", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 358 { RTLIB::DIV_F32, "__aeabi_fdiv", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 359 { RTLIB::MUL_F32, "__aeabi_fmul", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 360 { RTLIB::SUB_F32, "__aeabi_fsub", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 361 362 // Single-precision floating-point comparison helper functions 363 // RTABI chapter 4.1.2, Table 5 364 { RTLIB::OEQ_F32, "__aeabi_fcmpeq", CallingConv::ARM_AAPCS, ISD::SETNE }, 365 { RTLIB::UNE_F32, "__aeabi_fcmpeq", CallingConv::ARM_AAPCS, ISD::SETEQ }, 366 { RTLIB::OLT_F32, "__aeabi_fcmplt", CallingConv::ARM_AAPCS, ISD::SETNE }, 367 { RTLIB::OLE_F32, "__aeabi_fcmple", CallingConv::ARM_AAPCS, ISD::SETNE }, 368 { RTLIB::OGE_F32, "__aeabi_fcmpge", CallingConv::ARM_AAPCS, ISD::SETNE }, 369 { RTLIB::OGT_F32, "__aeabi_fcmpgt", CallingConv::ARM_AAPCS, ISD::SETNE }, 370 { RTLIB::UO_F32, "__aeabi_fcmpun", CallingConv::ARM_AAPCS, ISD::SETNE }, 371 { RTLIB::O_F32, "__aeabi_fcmpun", CallingConv::ARM_AAPCS, ISD::SETEQ }, 372 373 // Floating-point to integer conversions. 374 // RTABI chapter 4.1.2, Table 6 375 { RTLIB::FPTOSINT_F64_I32, "__aeabi_d2iz", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 376 { RTLIB::FPTOUINT_F64_I32, "__aeabi_d2uiz", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 377 { RTLIB::FPTOSINT_F64_I64, "__aeabi_d2lz", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 378 { RTLIB::FPTOUINT_F64_I64, "__aeabi_d2ulz", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 379 { RTLIB::FPTOSINT_F32_I32, "__aeabi_f2iz", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 380 { RTLIB::FPTOUINT_F32_I32, "__aeabi_f2uiz", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 381 { RTLIB::FPTOSINT_F32_I64, "__aeabi_f2lz", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 382 { RTLIB::FPTOUINT_F32_I64, "__aeabi_f2ulz", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 383 384 // Conversions between floating types. 385 // RTABI chapter 4.1.2, Table 7 386 { RTLIB::FPROUND_F64_F32, "__aeabi_d2f", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 387 { RTLIB::FPROUND_F64_F16, "__aeabi_d2h", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 388 { RTLIB::FPEXT_F32_F64, "__aeabi_f2d", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 389 390 // Integer to floating-point conversions. 391 // RTABI chapter 4.1.2, Table 8 392 { RTLIB::SINTTOFP_I32_F64, "__aeabi_i2d", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 393 { RTLIB::UINTTOFP_I32_F64, "__aeabi_ui2d", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 394 { RTLIB::SINTTOFP_I64_F64, "__aeabi_l2d", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 395 { RTLIB::UINTTOFP_I64_F64, "__aeabi_ul2d", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 396 { RTLIB::SINTTOFP_I32_F32, "__aeabi_i2f", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 397 { RTLIB::UINTTOFP_I32_F32, "__aeabi_ui2f", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 398 { RTLIB::SINTTOFP_I64_F32, "__aeabi_l2f", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 399 { RTLIB::UINTTOFP_I64_F32, "__aeabi_ul2f", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 400 401 // Long long helper functions 402 // RTABI chapter 4.2, Table 9 403 { RTLIB::MUL_I64, "__aeabi_lmul", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 404 { RTLIB::SHL_I64, "__aeabi_llsl", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 405 { RTLIB::SRL_I64, "__aeabi_llsr", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 406 { RTLIB::SRA_I64, "__aeabi_lasr", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 407 408 // Integer division functions 409 // RTABI chapter 4.3.1 410 { RTLIB::SDIV_I8, "__aeabi_idiv", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 411 { RTLIB::SDIV_I16, "__aeabi_idiv", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 412 { RTLIB::SDIV_I32, "__aeabi_idiv", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 413 { RTLIB::SDIV_I64, "__aeabi_ldivmod", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 414 { RTLIB::UDIV_I8, "__aeabi_uidiv", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 415 { RTLIB::UDIV_I16, "__aeabi_uidiv", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 416 { RTLIB::UDIV_I32, "__aeabi_uidiv", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 417 { RTLIB::UDIV_I64, "__aeabi_uldivmod", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 418 }; 419 420 for (const auto &LC : LibraryCalls) { 421 setLibcallName(LC.Op, LC.Name); 422 setLibcallCallingConv(LC.Op, LC.CC); 423 if (LC.Cond != ISD::SETCC_INVALID) 424 setCmpLibcallCC(LC.Op, LC.Cond); 425 } 426 427 // EABI dependent RTLIB 428 if (TM.Options.EABIVersion == EABI::EABI4 || 429 TM.Options.EABIVersion == EABI::EABI5) { 430 static const struct { 431 const RTLIB::Libcall Op; 432 const char *const Name; 433 const CallingConv::ID CC; 434 const ISD::CondCode Cond; 435 } MemOpsLibraryCalls[] = { 436 // Memory operations 437 // RTABI chapter 4.3.4 438 { RTLIB::MEMCPY, "__aeabi_memcpy", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 439 { RTLIB::MEMMOVE, "__aeabi_memmove", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 440 { RTLIB::MEMSET, "__aeabi_memset", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 441 }; 442 443 for (const auto &LC : MemOpsLibraryCalls) { 444 setLibcallName(LC.Op, LC.Name); 445 setLibcallCallingConv(LC.Op, LC.CC); 446 if (LC.Cond != ISD::SETCC_INVALID) 447 setCmpLibcallCC(LC.Op, LC.Cond); 448 } 449 } 450 } 451 452 if (Subtarget->isTargetWindows()) { 453 static const struct { 454 const RTLIB::Libcall Op; 455 const char * const Name; 456 const CallingConv::ID CC; 457 } LibraryCalls[] = { 458 { RTLIB::FPTOSINT_F32_I64, "__stoi64", CallingConv::ARM_AAPCS_VFP }, 459 { RTLIB::FPTOSINT_F64_I64, "__dtoi64", CallingConv::ARM_AAPCS_VFP }, 460 { RTLIB::FPTOUINT_F32_I64, "__stou64", CallingConv::ARM_AAPCS_VFP }, 461 { RTLIB::FPTOUINT_F64_I64, "__dtou64", CallingConv::ARM_AAPCS_VFP }, 462 { RTLIB::SINTTOFP_I64_F32, "__i64tos", CallingConv::ARM_AAPCS_VFP }, 463 { RTLIB::SINTTOFP_I64_F64, "__i64tod", CallingConv::ARM_AAPCS_VFP }, 464 { RTLIB::UINTTOFP_I64_F32, "__u64tos", CallingConv::ARM_AAPCS_VFP }, 465 { RTLIB::UINTTOFP_I64_F64, "__u64tod", CallingConv::ARM_AAPCS_VFP }, 466 }; 467 468 for (const auto &LC : LibraryCalls) { 469 setLibcallName(LC.Op, LC.Name); 470 setLibcallCallingConv(LC.Op, LC.CC); 471 } 472 } 473 474 // Use divmod compiler-rt calls for iOS 5.0 and later. 475 if (Subtarget->isTargetWatchOS() || 476 (Subtarget->isTargetIOS() && 477 !Subtarget->getTargetTriple().isOSVersionLT(5, 0))) { 478 setLibcallName(RTLIB::SDIVREM_I32, "__divmodsi4"); 479 setLibcallName(RTLIB::UDIVREM_I32, "__udivmodsi4"); 480 } 481 482 // The half <-> float conversion functions are always soft-float on 483 // non-watchos platforms, but are needed for some targets which use a 484 // hard-float calling convention by default. 485 if (!Subtarget->isTargetWatchABI()) { 486 if (Subtarget->isAAPCS_ABI()) { 487 setLibcallCallingConv(RTLIB::FPROUND_F32_F16, CallingConv::ARM_AAPCS); 488 setLibcallCallingConv(RTLIB::FPROUND_F64_F16, CallingConv::ARM_AAPCS); 489 setLibcallCallingConv(RTLIB::FPEXT_F16_F32, CallingConv::ARM_AAPCS); 490 } else { 491 setLibcallCallingConv(RTLIB::FPROUND_F32_F16, CallingConv::ARM_APCS); 492 setLibcallCallingConv(RTLIB::FPROUND_F64_F16, CallingConv::ARM_APCS); 493 setLibcallCallingConv(RTLIB::FPEXT_F16_F32, CallingConv::ARM_APCS); 494 } 495 } 496 497 // In EABI, these functions have an __aeabi_ prefix, but in GNUEABI they have 498 // a __gnu_ prefix (which is the default). 499 if (Subtarget->isTargetAEABI()) { 500 static const struct { 501 const RTLIB::Libcall Op; 502 const char * const Name; 503 const CallingConv::ID CC; 504 } LibraryCalls[] = { 505 { RTLIB::FPROUND_F32_F16, "__aeabi_f2h", CallingConv::ARM_AAPCS }, 506 { RTLIB::FPROUND_F64_F16, "__aeabi_d2h", CallingConv::ARM_AAPCS }, 507 { RTLIB::FPEXT_F16_F32, "__aeabi_h2f", CallingConv::ARM_AAPCS }, 508 }; 509 510 for (const auto &LC : LibraryCalls) { 511 setLibcallName(LC.Op, LC.Name); 512 setLibcallCallingConv(LC.Op, LC.CC); 513 } 514 } 515 516 if (Subtarget->isThumb1Only()) 517 addRegisterClass(MVT::i32, &ARM::tGPRRegClass); 518 else 519 addRegisterClass(MVT::i32, &ARM::GPRRegClass); 520 521 if (!Subtarget->useSoftFloat() && Subtarget->hasVFP2() && 522 !Subtarget->isThumb1Only()) { 523 addRegisterClass(MVT::f32, &ARM::SPRRegClass); 524 addRegisterClass(MVT::f64, &ARM::DPRRegClass); 525 } 526 527 for (MVT VT : MVT::vector_valuetypes()) { 528 for (MVT InnerVT : MVT::vector_valuetypes()) { 529 setTruncStoreAction(VT, InnerVT, Expand); 530 setLoadExtAction(ISD::SEXTLOAD, VT, InnerVT, Expand); 531 setLoadExtAction(ISD::ZEXTLOAD, VT, InnerVT, Expand); 532 setLoadExtAction(ISD::EXTLOAD, VT, InnerVT, Expand); 533 } 534 535 setOperationAction(ISD::MULHS, VT, Expand); 536 setOperationAction(ISD::SMUL_LOHI, VT, Expand); 537 setOperationAction(ISD::MULHU, VT, Expand); 538 setOperationAction(ISD::UMUL_LOHI, VT, Expand); 539 540 setOperationAction(ISD::BSWAP, VT, Expand); 541 } 542 543 setOperationAction(ISD::ConstantFP, MVT::f32, Custom); 544 setOperationAction(ISD::ConstantFP, MVT::f64, Custom); 545 546 setOperationAction(ISD::READ_REGISTER, MVT::i64, Custom); 547 setOperationAction(ISD::WRITE_REGISTER, MVT::i64, Custom); 548 549 if (Subtarget->hasNEON()) { 550 addDRTypeForNEON(MVT::v2f32); 551 addDRTypeForNEON(MVT::v8i8); 552 addDRTypeForNEON(MVT::v4i16); 553 addDRTypeForNEON(MVT::v2i32); 554 addDRTypeForNEON(MVT::v1i64); 555 556 addQRTypeForNEON(MVT::v4f32); 557 addQRTypeForNEON(MVT::v2f64); 558 addQRTypeForNEON(MVT::v16i8); 559 addQRTypeForNEON(MVT::v8i16); 560 addQRTypeForNEON(MVT::v4i32); 561 addQRTypeForNEON(MVT::v2i64); 562 563 // v2f64 is legal so that QR subregs can be extracted as f64 elements, but 564 // neither Neon nor VFP support any arithmetic operations on it. 565 // The same with v4f32. But keep in mind that vadd, vsub, vmul are natively 566 // supported for v4f32. 567 setOperationAction(ISD::FADD, MVT::v2f64, Expand); 568 setOperationAction(ISD::FSUB, MVT::v2f64, Expand); 569 setOperationAction(ISD::FMUL, MVT::v2f64, Expand); 570 // FIXME: Code duplication: FDIV and FREM are expanded always, see 571 // ARMTargetLowering::addTypeForNEON method for details. 572 setOperationAction(ISD::FDIV, MVT::v2f64, Expand); 573 setOperationAction(ISD::FREM, MVT::v2f64, Expand); 574 // FIXME: Create unittest. 575 // In another words, find a way when "copysign" appears in DAG with vector 576 // operands. 577 setOperationAction(ISD::FCOPYSIGN, MVT::v2f64, Expand); 578 // FIXME: Code duplication: SETCC has custom operation action, see 579 // ARMTargetLowering::addTypeForNEON method for details. 580 setOperationAction(ISD::SETCC, MVT::v2f64, Expand); 581 // FIXME: Create unittest for FNEG and for FABS. 582 setOperationAction(ISD::FNEG, MVT::v2f64, Expand); 583 setOperationAction(ISD::FABS, MVT::v2f64, Expand); 584 setOperationAction(ISD::FSQRT, MVT::v2f64, Expand); 585 setOperationAction(ISD::FSIN, MVT::v2f64, Expand); 586 setOperationAction(ISD::FCOS, MVT::v2f64, Expand); 587 setOperationAction(ISD::FPOWI, MVT::v2f64, Expand); 588 setOperationAction(ISD::FPOW, MVT::v2f64, Expand); 589 setOperationAction(ISD::FLOG, MVT::v2f64, Expand); 590 setOperationAction(ISD::FLOG2, MVT::v2f64, Expand); 591 setOperationAction(ISD::FLOG10, MVT::v2f64, Expand); 592 setOperationAction(ISD::FEXP, MVT::v2f64, Expand); 593 setOperationAction(ISD::FEXP2, MVT::v2f64, Expand); 594 // FIXME: Create unittest for FCEIL, FTRUNC, FRINT, FNEARBYINT, FFLOOR. 595 setOperationAction(ISD::FCEIL, MVT::v2f64, Expand); 596 setOperationAction(ISD::FTRUNC, MVT::v2f64, Expand); 597 setOperationAction(ISD::FRINT, MVT::v2f64, Expand); 598 setOperationAction(ISD::FNEARBYINT, MVT::v2f64, Expand); 599 setOperationAction(ISD::FFLOOR, MVT::v2f64, Expand); 600 setOperationAction(ISD::FMA, MVT::v2f64, Expand); 601 602 setOperationAction(ISD::FSQRT, MVT::v4f32, Expand); 603 setOperationAction(ISD::FSIN, MVT::v4f32, Expand); 604 setOperationAction(ISD::FCOS, MVT::v4f32, Expand); 605 setOperationAction(ISD::FPOWI, MVT::v4f32, Expand); 606 setOperationAction(ISD::FPOW, MVT::v4f32, Expand); 607 setOperationAction(ISD::FLOG, MVT::v4f32, Expand); 608 setOperationAction(ISD::FLOG2, MVT::v4f32, Expand); 609 setOperationAction(ISD::FLOG10, MVT::v4f32, Expand); 610 setOperationAction(ISD::FEXP, MVT::v4f32, Expand); 611 setOperationAction(ISD::FEXP2, MVT::v4f32, Expand); 612 setOperationAction(ISD::FCEIL, MVT::v4f32, Expand); 613 setOperationAction(ISD::FTRUNC, MVT::v4f32, Expand); 614 setOperationAction(ISD::FRINT, MVT::v4f32, Expand); 615 setOperationAction(ISD::FNEARBYINT, MVT::v4f32, Expand); 616 setOperationAction(ISD::FFLOOR, MVT::v4f32, Expand); 617 618 // Mark v2f32 intrinsics. 619 setOperationAction(ISD::FSQRT, MVT::v2f32, Expand); 620 setOperationAction(ISD::FSIN, MVT::v2f32, Expand); 621 setOperationAction(ISD::FCOS, MVT::v2f32, Expand); 622 setOperationAction(ISD::FPOWI, MVT::v2f32, Expand); 623 setOperationAction(ISD::FPOW, MVT::v2f32, Expand); 624 setOperationAction(ISD::FLOG, MVT::v2f32, Expand); 625 setOperationAction(ISD::FLOG2, MVT::v2f32, Expand); 626 setOperationAction(ISD::FLOG10, MVT::v2f32, Expand); 627 setOperationAction(ISD::FEXP, MVT::v2f32, Expand); 628 setOperationAction(ISD::FEXP2, MVT::v2f32, Expand); 629 setOperationAction(ISD::FCEIL, MVT::v2f32, Expand); 630 setOperationAction(ISD::FTRUNC, MVT::v2f32, Expand); 631 setOperationAction(ISD::FRINT, MVT::v2f32, Expand); 632 setOperationAction(ISD::FNEARBYINT, MVT::v2f32, Expand); 633 setOperationAction(ISD::FFLOOR, MVT::v2f32, Expand); 634 635 // Neon does not support some operations on v1i64 and v2i64 types. 636 setOperationAction(ISD::MUL, MVT::v1i64, Expand); 637 // Custom handling for some quad-vector types to detect VMULL. 638 setOperationAction(ISD::MUL, MVT::v8i16, Custom); 639 setOperationAction(ISD::MUL, MVT::v4i32, Custom); 640 setOperationAction(ISD::MUL, MVT::v2i64, Custom); 641 // Custom handling for some vector types to avoid expensive expansions 642 setOperationAction(ISD::SDIV, MVT::v4i16, Custom); 643 setOperationAction(ISD::SDIV, MVT::v8i8, Custom); 644 setOperationAction(ISD::UDIV, MVT::v4i16, Custom); 645 setOperationAction(ISD::UDIV, MVT::v8i8, Custom); 646 // Neon does not have single instruction SINT_TO_FP and UINT_TO_FP with 647 // a destination type that is wider than the source, and nor does 648 // it have a FP_TO_[SU]INT instruction with a narrower destination than 649 // source. 650 setOperationAction(ISD::SINT_TO_FP, MVT::v4i16, Custom); 651 setOperationAction(ISD::UINT_TO_FP, MVT::v4i16, Custom); 652 setOperationAction(ISD::FP_TO_UINT, MVT::v4i16, Custom); 653 setOperationAction(ISD::FP_TO_SINT, MVT::v4i16, Custom); 654 655 setOperationAction(ISD::FP_ROUND, MVT::v2f32, Expand); 656 setOperationAction(ISD::FP_EXTEND, MVT::v2f64, Expand); 657 658 // NEON does not have single instruction CTPOP for vectors with element 659 // types wider than 8-bits. However, custom lowering can leverage the 660 // v8i8/v16i8 vcnt instruction. 661 setOperationAction(ISD::CTPOP, MVT::v2i32, Custom); 662 setOperationAction(ISD::CTPOP, MVT::v4i32, Custom); 663 setOperationAction(ISD::CTPOP, MVT::v4i16, Custom); 664 setOperationAction(ISD::CTPOP, MVT::v8i16, Custom); 665 setOperationAction(ISD::CTPOP, MVT::v1i64, Expand); 666 setOperationAction(ISD::CTPOP, MVT::v2i64, Expand); 667 668 setOperationAction(ISD::CTLZ, MVT::v1i64, Expand); 669 setOperationAction(ISD::CTLZ, MVT::v2i64, Expand); 670 671 // NEON does not have single instruction CTTZ for vectors. 672 setOperationAction(ISD::CTTZ, MVT::v8i8, Custom); 673 setOperationAction(ISD::CTTZ, MVT::v4i16, Custom); 674 setOperationAction(ISD::CTTZ, MVT::v2i32, Custom); 675 setOperationAction(ISD::CTTZ, MVT::v1i64, Custom); 676 677 setOperationAction(ISD::CTTZ, MVT::v16i8, Custom); 678 setOperationAction(ISD::CTTZ, MVT::v8i16, Custom); 679 setOperationAction(ISD::CTTZ, MVT::v4i32, Custom); 680 setOperationAction(ISD::CTTZ, MVT::v2i64, Custom); 681 682 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::v8i8, Custom); 683 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::v4i16, Custom); 684 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::v2i32, Custom); 685 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::v1i64, Custom); 686 687 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::v16i8, Custom); 688 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::v8i16, Custom); 689 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::v4i32, Custom); 690 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::v2i64, Custom); 691 692 // NEON only has FMA instructions as of VFP4. 693 if (!Subtarget->hasVFP4()) { 694 setOperationAction(ISD::FMA, MVT::v2f32, Expand); 695 setOperationAction(ISD::FMA, MVT::v4f32, Expand); 696 } 697 698 setTargetDAGCombine(ISD::INTRINSIC_VOID); 699 setTargetDAGCombine(ISD::INTRINSIC_W_CHAIN); 700 setTargetDAGCombine(ISD::INTRINSIC_WO_CHAIN); 701 setTargetDAGCombine(ISD::SHL); 702 setTargetDAGCombine(ISD::SRL); 703 setTargetDAGCombine(ISD::SRA); 704 setTargetDAGCombine(ISD::SIGN_EXTEND); 705 setTargetDAGCombine(ISD::ZERO_EXTEND); 706 setTargetDAGCombine(ISD::ANY_EXTEND); 707 setTargetDAGCombine(ISD::BUILD_VECTOR); 708 setTargetDAGCombine(ISD::VECTOR_SHUFFLE); 709 setTargetDAGCombine(ISD::INSERT_VECTOR_ELT); 710 setTargetDAGCombine(ISD::STORE); 711 setTargetDAGCombine(ISD::FP_TO_SINT); 712 setTargetDAGCombine(ISD::FP_TO_UINT); 713 setTargetDAGCombine(ISD::FDIV); 714 setTargetDAGCombine(ISD::LOAD); 715 716 // It is legal to extload from v4i8 to v4i16 or v4i32. 717 for (MVT Ty : {MVT::v8i8, MVT::v4i8, MVT::v2i8, MVT::v4i16, MVT::v2i16, 718 MVT::v2i32}) { 719 for (MVT VT : MVT::integer_vector_valuetypes()) { 720 setLoadExtAction(ISD::EXTLOAD, VT, Ty, Legal); 721 setLoadExtAction(ISD::ZEXTLOAD, VT, Ty, Legal); 722 setLoadExtAction(ISD::SEXTLOAD, VT, Ty, Legal); 723 } 724 } 725 } 726 727 if (Subtarget->isFPOnlySP()) { 728 // When targeting a floating-point unit with only single-precision 729 // operations, f64 is legal for the few double-precision instructions which 730 // are present However, no double-precision operations other than moves, 731 // loads and stores are provided by the hardware. 732 setOperationAction(ISD::FADD, MVT::f64, Expand); 733 setOperationAction(ISD::FSUB, MVT::f64, Expand); 734 setOperationAction(ISD::FMUL, MVT::f64, Expand); 735 setOperationAction(ISD::FMA, MVT::f64, Expand); 736 setOperationAction(ISD::FDIV, MVT::f64, Expand); 737 setOperationAction(ISD::FREM, MVT::f64, Expand); 738 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand); 739 setOperationAction(ISD::FGETSIGN, MVT::f64, Expand); 740 setOperationAction(ISD::FNEG, MVT::f64, Expand); 741 setOperationAction(ISD::FABS, MVT::f64, Expand); 742 setOperationAction(ISD::FSQRT, MVT::f64, Expand); 743 setOperationAction(ISD::FSIN, MVT::f64, Expand); 744 setOperationAction(ISD::FCOS, MVT::f64, Expand); 745 setOperationAction(ISD::FPOWI, MVT::f64, Expand); 746 setOperationAction(ISD::FPOW, MVT::f64, Expand); 747 setOperationAction(ISD::FLOG, MVT::f64, Expand); 748 setOperationAction(ISD::FLOG2, MVT::f64, Expand); 749 setOperationAction(ISD::FLOG10, MVT::f64, Expand); 750 setOperationAction(ISD::FEXP, MVT::f64, Expand); 751 setOperationAction(ISD::FEXP2, MVT::f64, Expand); 752 setOperationAction(ISD::FCEIL, MVT::f64, Expand); 753 setOperationAction(ISD::FTRUNC, MVT::f64, Expand); 754 setOperationAction(ISD::FRINT, MVT::f64, Expand); 755 setOperationAction(ISD::FNEARBYINT, MVT::f64, Expand); 756 setOperationAction(ISD::FFLOOR, MVT::f64, Expand); 757 setOperationAction(ISD::SINT_TO_FP, MVT::i32, Custom); 758 setOperationAction(ISD::UINT_TO_FP, MVT::i32, Custom); 759 setOperationAction(ISD::FP_TO_SINT, MVT::i32, Custom); 760 setOperationAction(ISD::FP_TO_UINT, MVT::i32, Custom); 761 setOperationAction(ISD::FP_TO_SINT, MVT::f64, Custom); 762 setOperationAction(ISD::FP_TO_UINT, MVT::f64, Custom); 763 setOperationAction(ISD::FP_ROUND, MVT::f32, Custom); 764 setOperationAction(ISD::FP_EXTEND, MVT::f64, Custom); 765 } 766 767 computeRegisterProperties(Subtarget->getRegisterInfo()); 768 769 // ARM does not have floating-point extending loads. 770 for (MVT VT : MVT::fp_valuetypes()) { 771 setLoadExtAction(ISD::EXTLOAD, VT, MVT::f32, Expand); 772 setLoadExtAction(ISD::EXTLOAD, VT, MVT::f16, Expand); 773 } 774 775 // ... or truncating stores 776 setTruncStoreAction(MVT::f64, MVT::f32, Expand); 777 setTruncStoreAction(MVT::f32, MVT::f16, Expand); 778 setTruncStoreAction(MVT::f64, MVT::f16, Expand); 779 780 // ARM does not have i1 sign extending load. 781 for (MVT VT : MVT::integer_valuetypes()) 782 setLoadExtAction(ISD::SEXTLOAD, VT, MVT::i1, Promote); 783 784 // ARM supports all 4 flavors of integer indexed load / store. 785 if (!Subtarget->isThumb1Only()) { 786 for (unsigned im = (unsigned)ISD::PRE_INC; 787 im != (unsigned)ISD::LAST_INDEXED_MODE; ++im) { 788 setIndexedLoadAction(im, MVT::i1, Legal); 789 setIndexedLoadAction(im, MVT::i8, Legal); 790 setIndexedLoadAction(im, MVT::i16, Legal); 791 setIndexedLoadAction(im, MVT::i32, Legal); 792 setIndexedStoreAction(im, MVT::i1, Legal); 793 setIndexedStoreAction(im, MVT::i8, Legal); 794 setIndexedStoreAction(im, MVT::i16, Legal); 795 setIndexedStoreAction(im, MVT::i32, Legal); 796 } 797 } else { 798 // Thumb-1 has limited post-inc load/store support - LDM r0!, {r1}. 799 setIndexedLoadAction(ISD::POST_INC, MVT::i32, Legal); 800 setIndexedStoreAction(ISD::POST_INC, MVT::i32, Legal); 801 } 802 803 setOperationAction(ISD::SADDO, MVT::i32, Custom); 804 setOperationAction(ISD::UADDO, MVT::i32, Custom); 805 setOperationAction(ISD::SSUBO, MVT::i32, Custom); 806 setOperationAction(ISD::USUBO, MVT::i32, Custom); 807 808 // i64 operation support. 809 setOperationAction(ISD::MUL, MVT::i64, Expand); 810 setOperationAction(ISD::MULHU, MVT::i32, Expand); 811 if (Subtarget->isThumb1Only()) { 812 setOperationAction(ISD::UMUL_LOHI, MVT::i32, Expand); 813 setOperationAction(ISD::SMUL_LOHI, MVT::i32, Expand); 814 } 815 if (Subtarget->isThumb1Only() || !Subtarget->hasV6Ops() 816 || (Subtarget->isThumb2() && !Subtarget->hasDSP())) 817 setOperationAction(ISD::MULHS, MVT::i32, Expand); 818 819 setOperationAction(ISD::SHL_PARTS, MVT::i32, Custom); 820 setOperationAction(ISD::SRA_PARTS, MVT::i32, Custom); 821 setOperationAction(ISD::SRL_PARTS, MVT::i32, Custom); 822 setOperationAction(ISD::SRL, MVT::i64, Custom); 823 setOperationAction(ISD::SRA, MVT::i64, Custom); 824 825 setOperationAction(ISD::ADDC, MVT::i32, Custom); 826 setOperationAction(ISD::ADDE, MVT::i32, Custom); 827 setOperationAction(ISD::SUBC, MVT::i32, Custom); 828 setOperationAction(ISD::SUBE, MVT::i32, Custom); 829 830 if (!Subtarget->isThumb1Only() && Subtarget->hasV6T2Ops()) 831 setOperationAction(ISD::BITREVERSE, MVT::i32, Legal); 832 833 // ARM does not have ROTL. 834 setOperationAction(ISD::ROTL, MVT::i32, Expand); 835 for (MVT VT : MVT::vector_valuetypes()) { 836 setOperationAction(ISD::ROTL, VT, Expand); 837 setOperationAction(ISD::ROTR, VT, Expand); 838 } 839 setOperationAction(ISD::CTTZ, MVT::i32, Custom); 840 setOperationAction(ISD::CTPOP, MVT::i32, Expand); 841 if (!Subtarget->hasV5TOps() || Subtarget->isThumb1Only()) 842 setOperationAction(ISD::CTLZ, MVT::i32, Expand); 843 844 // @llvm.readcyclecounter requires the Performance Monitors extension. 845 // Default to the 0 expansion on unsupported platforms. 846 // FIXME: Technically there are older ARM CPUs that have 847 // implementation-specific ways of obtaining this information. 848 if (Subtarget->hasPerfMon()) 849 setOperationAction(ISD::READCYCLECOUNTER, MVT::i64, Custom); 850 851 // Only ARMv6 has BSWAP. 852 if (!Subtarget->hasV6Ops()) 853 setOperationAction(ISD::BSWAP, MVT::i32, Expand); 854 855 bool hasDivide = Subtarget->isThumb() ? Subtarget->hasDivide() 856 : Subtarget->hasDivideInARMMode(); 857 if (!hasDivide) { 858 // These are expanded into libcalls if the cpu doesn't have HW divider. 859 setOperationAction(ISD::SDIV, MVT::i32, LibCall); 860 setOperationAction(ISD::UDIV, MVT::i32, LibCall); 861 } 862 863 if (Subtarget->isTargetWindows() && !Subtarget->hasDivide()) { 864 setOperationAction(ISD::SDIV, MVT::i32, Custom); 865 setOperationAction(ISD::UDIV, MVT::i32, Custom); 866 867 setOperationAction(ISD::SDIV, MVT::i64, Custom); 868 setOperationAction(ISD::UDIV, MVT::i64, Custom); 869 } 870 871 setOperationAction(ISD::SREM, MVT::i32, Expand); 872 setOperationAction(ISD::UREM, MVT::i32, Expand); 873 874 // Register based DivRem for AEABI (RTABI 4.2) 875 if (Subtarget->isTargetAEABI() || Subtarget->isTargetAndroid() || 876 Subtarget->isTargetGNUAEABI() || Subtarget->isTargetMuslAEABI() || 877 Subtarget->isTargetWindows()) { 878 setOperationAction(ISD::SREM, MVT::i64, Custom); 879 setOperationAction(ISD::UREM, MVT::i64, Custom); 880 HasStandaloneRem = false; 881 882 if (Subtarget->isTargetWindows()) { 883 const struct { 884 const RTLIB::Libcall Op; 885 const char * const Name; 886 const CallingConv::ID CC; 887 } LibraryCalls[] = { 888 { RTLIB::SDIVREM_I8, "__rt_sdiv", CallingConv::ARM_AAPCS }, 889 { RTLIB::SDIVREM_I16, "__rt_sdiv", CallingConv::ARM_AAPCS }, 890 { RTLIB::SDIVREM_I32, "__rt_sdiv", CallingConv::ARM_AAPCS }, 891 { RTLIB::SDIVREM_I64, "__rt_sdiv64", CallingConv::ARM_AAPCS }, 892 893 { RTLIB::UDIVREM_I8, "__rt_udiv", CallingConv::ARM_AAPCS }, 894 { RTLIB::UDIVREM_I16, "__rt_udiv", CallingConv::ARM_AAPCS }, 895 { RTLIB::UDIVREM_I32, "__rt_udiv", CallingConv::ARM_AAPCS }, 896 { RTLIB::UDIVREM_I64, "__rt_udiv64", CallingConv::ARM_AAPCS }, 897 }; 898 899 for (const auto &LC : LibraryCalls) { 900 setLibcallName(LC.Op, LC.Name); 901 setLibcallCallingConv(LC.Op, LC.CC); 902 } 903 } else { 904 const struct { 905 const RTLIB::Libcall Op; 906 const char * const Name; 907 const CallingConv::ID CC; 908 } LibraryCalls[] = { 909 { RTLIB::SDIVREM_I8, "__aeabi_idivmod", CallingConv::ARM_AAPCS }, 910 { RTLIB::SDIVREM_I16, "__aeabi_idivmod", CallingConv::ARM_AAPCS }, 911 { RTLIB::SDIVREM_I32, "__aeabi_idivmod", CallingConv::ARM_AAPCS }, 912 { RTLIB::SDIVREM_I64, "__aeabi_ldivmod", CallingConv::ARM_AAPCS }, 913 914 { RTLIB::UDIVREM_I8, "__aeabi_uidivmod", CallingConv::ARM_AAPCS }, 915 { RTLIB::UDIVREM_I16, "__aeabi_uidivmod", CallingConv::ARM_AAPCS }, 916 { RTLIB::UDIVREM_I32, "__aeabi_uidivmod", CallingConv::ARM_AAPCS }, 917 { RTLIB::UDIVREM_I64, "__aeabi_uldivmod", CallingConv::ARM_AAPCS }, 918 }; 919 920 for (const auto &LC : LibraryCalls) { 921 setLibcallName(LC.Op, LC.Name); 922 setLibcallCallingConv(LC.Op, LC.CC); 923 } 924 } 925 926 setOperationAction(ISD::SDIVREM, MVT::i32, Custom); 927 setOperationAction(ISD::UDIVREM, MVT::i32, Custom); 928 setOperationAction(ISD::SDIVREM, MVT::i64, Custom); 929 setOperationAction(ISD::UDIVREM, MVT::i64, Custom); 930 } else { 931 setOperationAction(ISD::SDIVREM, MVT::i32, Expand); 932 setOperationAction(ISD::UDIVREM, MVT::i32, Expand); 933 } 934 935 if (Subtarget->isTargetWindows() && Subtarget->getTargetTriple().isOSMSVCRT()) 936 for (auto &VT : {MVT::f32, MVT::f64}) 937 setOperationAction(ISD::FPOWI, VT, Custom); 938 939 setOperationAction(ISD::GlobalAddress, MVT::i32, Custom); 940 setOperationAction(ISD::ConstantPool, MVT::i32, Custom); 941 setOperationAction(ISD::GlobalTLSAddress, MVT::i32, Custom); 942 setOperationAction(ISD::BlockAddress, MVT::i32, Custom); 943 944 setOperationAction(ISD::TRAP, MVT::Other, Legal); 945 946 // Use the default implementation. 947 setOperationAction(ISD::VASTART, MVT::Other, Custom); 948 setOperationAction(ISD::VAARG, MVT::Other, Expand); 949 setOperationAction(ISD::VACOPY, MVT::Other, Expand); 950 setOperationAction(ISD::VAEND, MVT::Other, Expand); 951 setOperationAction(ISD::STACKSAVE, MVT::Other, Expand); 952 setOperationAction(ISD::STACKRESTORE, MVT::Other, Expand); 953 954 if (Subtarget->getTargetTriple().isWindowsItaniumEnvironment()) 955 setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i32, Custom); 956 else 957 setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i32, Expand); 958 959 // ARMv6 Thumb1 (except for CPUs that support dmb / dsb) and earlier use 960 // the default expansion. 961 InsertFencesForAtomic = false; 962 if (Subtarget->hasAnyDataBarrier() && 963 (!Subtarget->isThumb() || Subtarget->hasV8MBaselineOps())) { 964 // ATOMIC_FENCE needs custom lowering; the others should have been expanded 965 // to ldrex/strex loops already. 966 setOperationAction(ISD::ATOMIC_FENCE, MVT::Other, Custom); 967 if (!Subtarget->isThumb() || !Subtarget->isMClass()) 968 setOperationAction(ISD::ATOMIC_CMP_SWAP, MVT::i64, Custom); 969 970 // On v8, we have particularly efficient implementations of atomic fences 971 // if they can be combined with nearby atomic loads and stores. 972 if (!Subtarget->hasV8Ops() || getTargetMachine().getOptLevel() == 0) { 973 // Automatically insert fences (dmb ish) around ATOMIC_SWAP etc. 974 InsertFencesForAtomic = true; 975 } 976 } else { 977 // If there's anything we can use as a barrier, go through custom lowering 978 // for ATOMIC_FENCE. 979 // If target has DMB in thumb, Fences can be inserted. 980 if (Subtarget->hasDataBarrier()) 981 InsertFencesForAtomic = true; 982 983 setOperationAction(ISD::ATOMIC_FENCE, MVT::Other, 984 Subtarget->hasAnyDataBarrier() ? Custom : Expand); 985 986 // Set them all for expansion, which will force libcalls. 987 setOperationAction(ISD::ATOMIC_CMP_SWAP, MVT::i32, Expand); 988 setOperationAction(ISD::ATOMIC_SWAP, MVT::i32, Expand); 989 setOperationAction(ISD::ATOMIC_LOAD_ADD, MVT::i32, Expand); 990 setOperationAction(ISD::ATOMIC_LOAD_SUB, MVT::i32, Expand); 991 setOperationAction(ISD::ATOMIC_LOAD_AND, MVT::i32, Expand); 992 setOperationAction(ISD::ATOMIC_LOAD_OR, MVT::i32, Expand); 993 setOperationAction(ISD::ATOMIC_LOAD_XOR, MVT::i32, Expand); 994 setOperationAction(ISD::ATOMIC_LOAD_NAND, MVT::i32, Expand); 995 setOperationAction(ISD::ATOMIC_LOAD_MIN, MVT::i32, Expand); 996 setOperationAction(ISD::ATOMIC_LOAD_MAX, MVT::i32, Expand); 997 setOperationAction(ISD::ATOMIC_LOAD_UMIN, MVT::i32, Expand); 998 setOperationAction(ISD::ATOMIC_LOAD_UMAX, MVT::i32, Expand); 999 // Mark ATOMIC_LOAD and ATOMIC_STORE custom so we can handle the 1000 // Unordered/Monotonic case. 1001 if (!InsertFencesForAtomic) { 1002 setOperationAction(ISD::ATOMIC_LOAD, MVT::i32, Custom); 1003 setOperationAction(ISD::ATOMIC_STORE, MVT::i32, Custom); 1004 } 1005 } 1006 1007 setOperationAction(ISD::PREFETCH, MVT::Other, Custom); 1008 1009 // Requires SXTB/SXTH, available on v6 and up in both ARM and Thumb modes. 1010 if (!Subtarget->hasV6Ops()) { 1011 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i16, Expand); 1012 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i8, Expand); 1013 } 1014 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1, Expand); 1015 1016 if (!Subtarget->useSoftFloat() && Subtarget->hasVFP2() && 1017 !Subtarget->isThumb1Only()) { 1018 // Turn f64->i64 into VMOVRRD, i64 -> f64 to VMOVDRR 1019 // iff target supports vfp2. 1020 setOperationAction(ISD::BITCAST, MVT::i64, Custom); 1021 setOperationAction(ISD::FLT_ROUNDS_, MVT::i32, Custom); 1022 } 1023 1024 // We want to custom lower some of our intrinsics. 1025 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom); 1026 setOperationAction(ISD::EH_SJLJ_SETJMP, MVT::i32, Custom); 1027 setOperationAction(ISD::EH_SJLJ_LONGJMP, MVT::Other, Custom); 1028 setOperationAction(ISD::EH_SJLJ_SETUP_DISPATCH, MVT::Other, Custom); 1029 if (Subtarget->useSjLjEH()) 1030 setLibcallName(RTLIB::UNWIND_RESUME, "_Unwind_SjLj_Resume"); 1031 1032 setOperationAction(ISD::SETCC, MVT::i32, Expand); 1033 setOperationAction(ISD::SETCC, MVT::f32, Expand); 1034 setOperationAction(ISD::SETCC, MVT::f64, Expand); 1035 setOperationAction(ISD::SELECT, MVT::i32, Custom); 1036 setOperationAction(ISD::SELECT, MVT::f32, Custom); 1037 setOperationAction(ISD::SELECT, MVT::f64, Custom); 1038 setOperationAction(ISD::SELECT_CC, MVT::i32, Custom); 1039 setOperationAction(ISD::SELECT_CC, MVT::f32, Custom); 1040 setOperationAction(ISD::SELECT_CC, MVT::f64, Custom); 1041 1042 // Thumb-1 cannot currently select ARMISD::SUBE. 1043 if (!Subtarget->isThumb1Only()) 1044 setOperationAction(ISD::SETCCE, MVT::i32, Custom); 1045 1046 setOperationAction(ISD::BRCOND, MVT::Other, Expand); 1047 setOperationAction(ISD::BR_CC, MVT::i32, Custom); 1048 setOperationAction(ISD::BR_CC, MVT::f32, Custom); 1049 setOperationAction(ISD::BR_CC, MVT::f64, Custom); 1050 setOperationAction(ISD::BR_JT, MVT::Other, Custom); 1051 1052 // We don't support sin/cos/fmod/copysign/pow 1053 setOperationAction(ISD::FSIN, MVT::f64, Expand); 1054 setOperationAction(ISD::FSIN, MVT::f32, Expand); 1055 setOperationAction(ISD::FCOS, MVT::f32, Expand); 1056 setOperationAction(ISD::FCOS, MVT::f64, Expand); 1057 setOperationAction(ISD::FSINCOS, MVT::f64, Expand); 1058 setOperationAction(ISD::FSINCOS, MVT::f32, Expand); 1059 setOperationAction(ISD::FREM, MVT::f64, Expand); 1060 setOperationAction(ISD::FREM, MVT::f32, Expand); 1061 if (!Subtarget->useSoftFloat() && Subtarget->hasVFP2() && 1062 !Subtarget->isThumb1Only()) { 1063 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Custom); 1064 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom); 1065 } 1066 setOperationAction(ISD::FPOW, MVT::f64, Expand); 1067 setOperationAction(ISD::FPOW, MVT::f32, Expand); 1068 1069 if (!Subtarget->hasVFP4()) { 1070 setOperationAction(ISD::FMA, MVT::f64, Expand); 1071 setOperationAction(ISD::FMA, MVT::f32, Expand); 1072 } 1073 1074 // Various VFP goodness 1075 if (!Subtarget->useSoftFloat() && !Subtarget->isThumb1Only()) { 1076 // FP-ARMv8 adds f64 <-> f16 conversion. Before that it should be expanded. 1077 if (!Subtarget->hasFPARMv8() || Subtarget->isFPOnlySP()) { 1078 setOperationAction(ISD::FP16_TO_FP, MVT::f64, Expand); 1079 setOperationAction(ISD::FP_TO_FP16, MVT::f64, Expand); 1080 } 1081 1082 // fp16 is a special v7 extension that adds f16 <-> f32 conversions. 1083 if (!Subtarget->hasFP16()) { 1084 setOperationAction(ISD::FP16_TO_FP, MVT::f32, Expand); 1085 setOperationAction(ISD::FP_TO_FP16, MVT::f32, Expand); 1086 } 1087 } 1088 1089 // Combine sin / cos into one node or libcall if possible. 1090 if (Subtarget->hasSinCos()) { 1091 setLibcallName(RTLIB::SINCOS_F32, "sincosf"); 1092 setLibcallName(RTLIB::SINCOS_F64, "sincos"); 1093 if (Subtarget->isTargetWatchABI()) { 1094 setLibcallCallingConv(RTLIB::SINCOS_F32, CallingConv::ARM_AAPCS_VFP); 1095 setLibcallCallingConv(RTLIB::SINCOS_F64, CallingConv::ARM_AAPCS_VFP); 1096 } 1097 if (Subtarget->isTargetIOS() || Subtarget->isTargetWatchOS()) { 1098 // For iOS, we don't want to the normal expansion of a libcall to 1099 // sincos. We want to issue a libcall to __sincos_stret. 1100 setOperationAction(ISD::FSINCOS, MVT::f64, Custom); 1101 setOperationAction(ISD::FSINCOS, MVT::f32, Custom); 1102 } 1103 } 1104 1105 // FP-ARMv8 implements a lot of rounding-like FP operations. 1106 if (Subtarget->hasFPARMv8()) { 1107 setOperationAction(ISD::FFLOOR, MVT::f32, Legal); 1108 setOperationAction(ISD::FCEIL, MVT::f32, Legal); 1109 setOperationAction(ISD::FROUND, MVT::f32, Legal); 1110 setOperationAction(ISD::FTRUNC, MVT::f32, Legal); 1111 setOperationAction(ISD::FNEARBYINT, MVT::f32, Legal); 1112 setOperationAction(ISD::FRINT, MVT::f32, Legal); 1113 setOperationAction(ISD::FMINNUM, MVT::f32, Legal); 1114 setOperationAction(ISD::FMAXNUM, MVT::f32, Legal); 1115 setOperationAction(ISD::FMINNUM, MVT::v2f32, Legal); 1116 setOperationAction(ISD::FMAXNUM, MVT::v2f32, Legal); 1117 setOperationAction(ISD::FMINNUM, MVT::v4f32, Legal); 1118 setOperationAction(ISD::FMAXNUM, MVT::v4f32, Legal); 1119 1120 if (!Subtarget->isFPOnlySP()) { 1121 setOperationAction(ISD::FFLOOR, MVT::f64, Legal); 1122 setOperationAction(ISD::FCEIL, MVT::f64, Legal); 1123 setOperationAction(ISD::FROUND, MVT::f64, Legal); 1124 setOperationAction(ISD::FTRUNC, MVT::f64, Legal); 1125 setOperationAction(ISD::FNEARBYINT, MVT::f64, Legal); 1126 setOperationAction(ISD::FRINT, MVT::f64, Legal); 1127 setOperationAction(ISD::FMINNUM, MVT::f64, Legal); 1128 setOperationAction(ISD::FMAXNUM, MVT::f64, Legal); 1129 } 1130 } 1131 1132 if (Subtarget->hasNEON()) { 1133 // vmin and vmax aren't available in a scalar form, so we use 1134 // a NEON instruction with an undef lane instead. 1135 setOperationAction(ISD::FMINNAN, MVT::f32, Legal); 1136 setOperationAction(ISD::FMAXNAN, MVT::f32, Legal); 1137 setOperationAction(ISD::FMINNAN, MVT::v2f32, Legal); 1138 setOperationAction(ISD::FMAXNAN, MVT::v2f32, Legal); 1139 setOperationAction(ISD::FMINNAN, MVT::v4f32, Legal); 1140 setOperationAction(ISD::FMAXNAN, MVT::v4f32, Legal); 1141 } 1142 1143 // We have target-specific dag combine patterns for the following nodes: 1144 // ARMISD::VMOVRRD - No need to call setTargetDAGCombine 1145 setTargetDAGCombine(ISD::ADD); 1146 setTargetDAGCombine(ISD::SUB); 1147 setTargetDAGCombine(ISD::MUL); 1148 setTargetDAGCombine(ISD::AND); 1149 setTargetDAGCombine(ISD::OR); 1150 setTargetDAGCombine(ISD::XOR); 1151 1152 if (Subtarget->hasV6Ops()) 1153 setTargetDAGCombine(ISD::SRL); 1154 1155 setStackPointerRegisterToSaveRestore(ARM::SP); 1156 1157 if (Subtarget->useSoftFloat() || Subtarget->isThumb1Only() || 1158 !Subtarget->hasVFP2()) 1159 setSchedulingPreference(Sched::RegPressure); 1160 else 1161 setSchedulingPreference(Sched::Hybrid); 1162 1163 //// temporary - rewrite interface to use type 1164 MaxStoresPerMemset = 8; 1165 MaxStoresPerMemsetOptSize = 4; 1166 MaxStoresPerMemcpy = 4; // For @llvm.memcpy -> sequence of stores 1167 MaxStoresPerMemcpyOptSize = 2; 1168 MaxStoresPerMemmove = 4; // For @llvm.memmove -> sequence of stores 1169 MaxStoresPerMemmoveOptSize = 2; 1170 1171 // On ARM arguments smaller than 4 bytes are extended, so all arguments 1172 // are at least 4 bytes aligned. 1173 setMinStackArgumentAlignment(4); 1174 1175 // Prefer likely predicted branches to selects on out-of-order cores. 1176 PredictableSelectIsExpensive = Subtarget->getSchedModel().isOutOfOrder(); 1177 1178 setMinFunctionAlignment(Subtarget->isThumb() ? 1 : 2); 1179 } 1180 1181 bool ARMTargetLowering::useSoftFloat() const { 1182 return Subtarget->useSoftFloat(); 1183 } 1184 1185 // FIXME: It might make sense to define the representative register class as the 1186 // nearest super-register that has a non-null superset. For example, DPR_VFP2 is 1187 // a super-register of SPR, and DPR is a superset if DPR_VFP2. Consequently, 1188 // SPR's representative would be DPR_VFP2. This should work well if register 1189 // pressure tracking were modified such that a register use would increment the 1190 // pressure of the register class's representative and all of it's super 1191 // classes' representatives transitively. We have not implemented this because 1192 // of the difficulty prior to coalescing of modeling operand register classes 1193 // due to the common occurrence of cross class copies and subregister insertions 1194 // and extractions. 1195 std::pair<const TargetRegisterClass *, uint8_t> 1196 ARMTargetLowering::findRepresentativeClass(const TargetRegisterInfo *TRI, 1197 MVT VT) const { 1198 const TargetRegisterClass *RRC = nullptr; 1199 uint8_t Cost = 1; 1200 switch (VT.SimpleTy) { 1201 default: 1202 return TargetLowering::findRepresentativeClass(TRI, VT); 1203 // Use DPR as representative register class for all floating point 1204 // and vector types. Since there are 32 SPR registers and 32 DPR registers so 1205 // the cost is 1 for both f32 and f64. 1206 case MVT::f32: case MVT::f64: case MVT::v8i8: case MVT::v4i16: 1207 case MVT::v2i32: case MVT::v1i64: case MVT::v2f32: 1208 RRC = &ARM::DPRRegClass; 1209 // When NEON is used for SP, only half of the register file is available 1210 // because operations that define both SP and DP results will be constrained 1211 // to the VFP2 class (D0-D15). We currently model this constraint prior to 1212 // coalescing by double-counting the SP regs. See the FIXME above. 1213 if (Subtarget->useNEONForSinglePrecisionFP()) 1214 Cost = 2; 1215 break; 1216 case MVT::v16i8: case MVT::v8i16: case MVT::v4i32: case MVT::v2i64: 1217 case MVT::v4f32: case MVT::v2f64: 1218 RRC = &ARM::DPRRegClass; 1219 Cost = 2; 1220 break; 1221 case MVT::v4i64: 1222 RRC = &ARM::DPRRegClass; 1223 Cost = 4; 1224 break; 1225 case MVT::v8i64: 1226 RRC = &ARM::DPRRegClass; 1227 Cost = 8; 1228 break; 1229 } 1230 return std::make_pair(RRC, Cost); 1231 } 1232 1233 const char *ARMTargetLowering::getTargetNodeName(unsigned Opcode) const { 1234 switch ((ARMISD::NodeType)Opcode) { 1235 case ARMISD::FIRST_NUMBER: break; 1236 case ARMISD::Wrapper: return "ARMISD::Wrapper"; 1237 case ARMISD::WrapperPIC: return "ARMISD::WrapperPIC"; 1238 case ARMISD::WrapperJT: return "ARMISD::WrapperJT"; 1239 case ARMISD::COPY_STRUCT_BYVAL: return "ARMISD::COPY_STRUCT_BYVAL"; 1240 case ARMISD::CALL: return "ARMISD::CALL"; 1241 case ARMISD::CALL_PRED: return "ARMISD::CALL_PRED"; 1242 case ARMISD::CALL_NOLINK: return "ARMISD::CALL_NOLINK"; 1243 case ARMISD::BRCOND: return "ARMISD::BRCOND"; 1244 case ARMISD::BR_JT: return "ARMISD::BR_JT"; 1245 case ARMISD::BR2_JT: return "ARMISD::BR2_JT"; 1246 case ARMISD::RET_FLAG: return "ARMISD::RET_FLAG"; 1247 case ARMISD::INTRET_FLAG: return "ARMISD::INTRET_FLAG"; 1248 case ARMISD::PIC_ADD: return "ARMISD::PIC_ADD"; 1249 case ARMISD::CMP: return "ARMISD::CMP"; 1250 case ARMISD::CMN: return "ARMISD::CMN"; 1251 case ARMISD::CMPZ: return "ARMISD::CMPZ"; 1252 case ARMISD::CMPFP: return "ARMISD::CMPFP"; 1253 case ARMISD::CMPFPw0: return "ARMISD::CMPFPw0"; 1254 case ARMISD::BCC_i64: return "ARMISD::BCC_i64"; 1255 case ARMISD::FMSTAT: return "ARMISD::FMSTAT"; 1256 1257 case ARMISD::CMOV: return "ARMISD::CMOV"; 1258 1259 case ARMISD::SSAT: return "ARMISD::SSAT"; 1260 1261 case ARMISD::SRL_FLAG: return "ARMISD::SRL_FLAG"; 1262 case ARMISD::SRA_FLAG: return "ARMISD::SRA_FLAG"; 1263 case ARMISD::RRX: return "ARMISD::RRX"; 1264 1265 case ARMISD::ADDC: return "ARMISD::ADDC"; 1266 case ARMISD::ADDE: return "ARMISD::ADDE"; 1267 case ARMISD::SUBC: return "ARMISD::SUBC"; 1268 case ARMISD::SUBE: return "ARMISD::SUBE"; 1269 1270 case ARMISD::VMOVRRD: return "ARMISD::VMOVRRD"; 1271 case ARMISD::VMOVDRR: return "ARMISD::VMOVDRR"; 1272 1273 case ARMISD::EH_SJLJ_SETJMP: return "ARMISD::EH_SJLJ_SETJMP"; 1274 case ARMISD::EH_SJLJ_LONGJMP: return "ARMISD::EH_SJLJ_LONGJMP"; 1275 case ARMISD::EH_SJLJ_SETUP_DISPATCH: return "ARMISD::EH_SJLJ_SETUP_DISPATCH"; 1276 1277 case ARMISD::TC_RETURN: return "ARMISD::TC_RETURN"; 1278 1279 case ARMISD::THREAD_POINTER:return "ARMISD::THREAD_POINTER"; 1280 1281 case ARMISD::DYN_ALLOC: return "ARMISD::DYN_ALLOC"; 1282 1283 case ARMISD::MEMBARRIER_MCR: return "ARMISD::MEMBARRIER_MCR"; 1284 1285 case ARMISD::PRELOAD: return "ARMISD::PRELOAD"; 1286 1287 case ARMISD::WIN__CHKSTK: return "ARMISD::WIN__CHKSTK"; 1288 case ARMISD::WIN__DBZCHK: return "ARMISD::WIN__DBZCHK"; 1289 1290 case ARMISD::VCEQ: return "ARMISD::VCEQ"; 1291 case ARMISD::VCEQZ: return "ARMISD::VCEQZ"; 1292 case ARMISD::VCGE: return "ARMISD::VCGE"; 1293 case ARMISD::VCGEZ: return "ARMISD::VCGEZ"; 1294 case ARMISD::VCLEZ: return "ARMISD::VCLEZ"; 1295 case ARMISD::VCGEU: return "ARMISD::VCGEU"; 1296 case ARMISD::VCGT: return "ARMISD::VCGT"; 1297 case ARMISD::VCGTZ: return "ARMISD::VCGTZ"; 1298 case ARMISD::VCLTZ: return "ARMISD::VCLTZ"; 1299 case ARMISD::VCGTU: return "ARMISD::VCGTU"; 1300 case ARMISD::VTST: return "ARMISD::VTST"; 1301 1302 case ARMISD::VSHL: return "ARMISD::VSHL"; 1303 case ARMISD::VSHRs: return "ARMISD::VSHRs"; 1304 case ARMISD::VSHRu: return "ARMISD::VSHRu"; 1305 case ARMISD::VRSHRs: return "ARMISD::VRSHRs"; 1306 case ARMISD::VRSHRu: return "ARMISD::VRSHRu"; 1307 case ARMISD::VRSHRN: return "ARMISD::VRSHRN"; 1308 case ARMISD::VQSHLs: return "ARMISD::VQSHLs"; 1309 case ARMISD::VQSHLu: return "ARMISD::VQSHLu"; 1310 case ARMISD::VQSHLsu: return "ARMISD::VQSHLsu"; 1311 case ARMISD::VQSHRNs: return "ARMISD::VQSHRNs"; 1312 case ARMISD::VQSHRNu: return "ARMISD::VQSHRNu"; 1313 case ARMISD::VQSHRNsu: return "ARMISD::VQSHRNsu"; 1314 case ARMISD::VQRSHRNs: return "ARMISD::VQRSHRNs"; 1315 case ARMISD::VQRSHRNu: return "ARMISD::VQRSHRNu"; 1316 case ARMISD::VQRSHRNsu: return "ARMISD::VQRSHRNsu"; 1317 case ARMISD::VSLI: return "ARMISD::VSLI"; 1318 case ARMISD::VSRI: return "ARMISD::VSRI"; 1319 case ARMISD::VGETLANEu: return "ARMISD::VGETLANEu"; 1320 case ARMISD::VGETLANEs: return "ARMISD::VGETLANEs"; 1321 case ARMISD::VMOVIMM: return "ARMISD::VMOVIMM"; 1322 case ARMISD::VMVNIMM: return "ARMISD::VMVNIMM"; 1323 case ARMISD::VMOVFPIMM: return "ARMISD::VMOVFPIMM"; 1324 case ARMISD::VDUP: return "ARMISD::VDUP"; 1325 case ARMISD::VDUPLANE: return "ARMISD::VDUPLANE"; 1326 case ARMISD::VEXT: return "ARMISD::VEXT"; 1327 case ARMISD::VREV64: return "ARMISD::VREV64"; 1328 case ARMISD::VREV32: return "ARMISD::VREV32"; 1329 case ARMISD::VREV16: return "ARMISD::VREV16"; 1330 case ARMISD::VZIP: return "ARMISD::VZIP"; 1331 case ARMISD::VUZP: return "ARMISD::VUZP"; 1332 case ARMISD::VTRN: return "ARMISD::VTRN"; 1333 case ARMISD::VTBL1: return "ARMISD::VTBL1"; 1334 case ARMISD::VTBL2: return "ARMISD::VTBL2"; 1335 case ARMISD::VMULLs: return "ARMISD::VMULLs"; 1336 case ARMISD::VMULLu: return "ARMISD::VMULLu"; 1337 case ARMISD::UMAAL: return "ARMISD::UMAAL"; 1338 case ARMISD::UMLAL: return "ARMISD::UMLAL"; 1339 case ARMISD::SMLAL: return "ARMISD::SMLAL"; 1340 case ARMISD::SMLALBB: return "ARMISD::SMLALBB"; 1341 case ARMISD::SMLALBT: return "ARMISD::SMLALBT"; 1342 case ARMISD::SMLALTB: return "ARMISD::SMLALTB"; 1343 case ARMISD::SMLALTT: return "ARMISD::SMLALTT"; 1344 case ARMISD::SMULWB: return "ARMISD::SMULWB"; 1345 case ARMISD::SMULWT: return "ARMISD::SMULWT"; 1346 case ARMISD::BUILD_VECTOR: return "ARMISD::BUILD_VECTOR"; 1347 case ARMISD::BFI: return "ARMISD::BFI"; 1348 case ARMISD::VORRIMM: return "ARMISD::VORRIMM"; 1349 case ARMISD::VBICIMM: return "ARMISD::VBICIMM"; 1350 case ARMISD::VBSL: return "ARMISD::VBSL"; 1351 case ARMISD::MEMCPY: return "ARMISD::MEMCPY"; 1352 case ARMISD::VLD1DUP: return "ARMISD::VLD1DUP"; 1353 case ARMISD::VLD2DUP: return "ARMISD::VLD2DUP"; 1354 case ARMISD::VLD3DUP: return "ARMISD::VLD3DUP"; 1355 case ARMISD::VLD4DUP: return "ARMISD::VLD4DUP"; 1356 case ARMISD::VLD1_UPD: return "ARMISD::VLD1_UPD"; 1357 case ARMISD::VLD2_UPD: return "ARMISD::VLD2_UPD"; 1358 case ARMISD::VLD3_UPD: return "ARMISD::VLD3_UPD"; 1359 case ARMISD::VLD4_UPD: return "ARMISD::VLD4_UPD"; 1360 case ARMISD::VLD2LN_UPD: return "ARMISD::VLD2LN_UPD"; 1361 case ARMISD::VLD3LN_UPD: return "ARMISD::VLD3LN_UPD"; 1362 case ARMISD::VLD4LN_UPD: return "ARMISD::VLD4LN_UPD"; 1363 case ARMISD::VLD1DUP_UPD: return "ARMISD::VLD1DUP_UPD"; 1364 case ARMISD::VLD2DUP_UPD: return "ARMISD::VLD2DUP_UPD"; 1365 case ARMISD::VLD3DUP_UPD: return "ARMISD::VLD3DUP_UPD"; 1366 case ARMISD::VLD4DUP_UPD: return "ARMISD::VLD4DUP_UPD"; 1367 case ARMISD::VST1_UPD: return "ARMISD::VST1_UPD"; 1368 case ARMISD::VST2_UPD: return "ARMISD::VST2_UPD"; 1369 case ARMISD::VST3_UPD: return "ARMISD::VST3_UPD"; 1370 case ARMISD::VST4_UPD: return "ARMISD::VST4_UPD"; 1371 case ARMISD::VST2LN_UPD: return "ARMISD::VST2LN_UPD"; 1372 case ARMISD::VST3LN_UPD: return "ARMISD::VST3LN_UPD"; 1373 case ARMISD::VST4LN_UPD: return "ARMISD::VST4LN_UPD"; 1374 } 1375 return nullptr; 1376 } 1377 1378 EVT ARMTargetLowering::getSetCCResultType(const DataLayout &DL, LLVMContext &, 1379 EVT VT) const { 1380 if (!VT.isVector()) 1381 return getPointerTy(DL); 1382 return VT.changeVectorElementTypeToInteger(); 1383 } 1384 1385 /// getRegClassFor - Return the register class that should be used for the 1386 /// specified value type. 1387 const TargetRegisterClass *ARMTargetLowering::getRegClassFor(MVT VT) const { 1388 // Map v4i64 to QQ registers but do not make the type legal. Similarly map 1389 // v8i64 to QQQQ registers. v4i64 and v8i64 are only used for REG_SEQUENCE to 1390 // load / store 4 to 8 consecutive D registers. 1391 if (Subtarget->hasNEON()) { 1392 if (VT == MVT::v4i64) 1393 return &ARM::QQPRRegClass; 1394 if (VT == MVT::v8i64) 1395 return &ARM::QQQQPRRegClass; 1396 } 1397 return TargetLowering::getRegClassFor(VT); 1398 } 1399 1400 // memcpy, and other memory intrinsics, typically tries to use LDM/STM if the 1401 // source/dest is aligned and the copy size is large enough. We therefore want 1402 // to align such objects passed to memory intrinsics. 1403 bool ARMTargetLowering::shouldAlignPointerArgs(CallInst *CI, unsigned &MinSize, 1404 unsigned &PrefAlign) const { 1405 if (!isa<MemIntrinsic>(CI)) 1406 return false; 1407 MinSize = 8; 1408 // On ARM11 onwards (excluding M class) 8-byte aligned LDM is typically 1 1409 // cycle faster than 4-byte aligned LDM. 1410 PrefAlign = (Subtarget->hasV6Ops() && !Subtarget->isMClass() ? 8 : 4); 1411 return true; 1412 } 1413 1414 // Create a fast isel object. 1415 FastISel * 1416 ARMTargetLowering::createFastISel(FunctionLoweringInfo &funcInfo, 1417 const TargetLibraryInfo *libInfo) const { 1418 return ARM::createFastISel(funcInfo, libInfo); 1419 } 1420 1421 Sched::Preference ARMTargetLowering::getSchedulingPreference(SDNode *N) const { 1422 unsigned NumVals = N->getNumValues(); 1423 if (!NumVals) 1424 return Sched::RegPressure; 1425 1426 for (unsigned i = 0; i != NumVals; ++i) { 1427 EVT VT = N->getValueType(i); 1428 if (VT == MVT::Glue || VT == MVT::Other) 1429 continue; 1430 if (VT.isFloatingPoint() || VT.isVector()) 1431 return Sched::ILP; 1432 } 1433 1434 if (!N->isMachineOpcode()) 1435 return Sched::RegPressure; 1436 1437 // Load are scheduled for latency even if there instruction itinerary 1438 // is not available. 1439 const TargetInstrInfo *TII = Subtarget->getInstrInfo(); 1440 const MCInstrDesc &MCID = TII->get(N->getMachineOpcode()); 1441 1442 if (MCID.getNumDefs() == 0) 1443 return Sched::RegPressure; 1444 if (!Itins->isEmpty() && 1445 Itins->getOperandCycle(MCID.getSchedClass(), 0) > 2) 1446 return Sched::ILP; 1447 1448 return Sched::RegPressure; 1449 } 1450 1451 //===----------------------------------------------------------------------===// 1452 // Lowering Code 1453 //===----------------------------------------------------------------------===// 1454 1455 static bool isSRL16(const SDValue &Op) { 1456 if (Op.getOpcode() != ISD::SRL) 1457 return false; 1458 if (auto Const = dyn_cast<ConstantSDNode>(Op.getOperand(1))) 1459 return Const->getZExtValue() == 16; 1460 return false; 1461 } 1462 1463 static bool isSRA16(const SDValue &Op) { 1464 if (Op.getOpcode() != ISD::SRA) 1465 return false; 1466 if (auto Const = dyn_cast<ConstantSDNode>(Op.getOperand(1))) 1467 return Const->getZExtValue() == 16; 1468 return false; 1469 } 1470 1471 static bool isSHL16(const SDValue &Op) { 1472 if (Op.getOpcode() != ISD::SHL) 1473 return false; 1474 if (auto Const = dyn_cast<ConstantSDNode>(Op.getOperand(1))) 1475 return Const->getZExtValue() == 16; 1476 return false; 1477 } 1478 1479 // Check for a signed 16-bit value. We special case SRA because it makes it 1480 // more simple when also looking for SRAs that aren't sign extending a 1481 // smaller value. Without the check, we'd need to take extra care with 1482 // checking order for some operations. 1483 static bool isS16(const SDValue &Op, SelectionDAG &DAG) { 1484 if (isSRA16(Op)) 1485 return isSHL16(Op.getOperand(0)); 1486 return DAG.ComputeNumSignBits(Op) == 17; 1487 } 1488 1489 /// IntCCToARMCC - Convert a DAG integer condition code to an ARM CC 1490 static ARMCC::CondCodes IntCCToARMCC(ISD::CondCode CC) { 1491 switch (CC) { 1492 default: llvm_unreachable("Unknown condition code!"); 1493 case ISD::SETNE: return ARMCC::NE; 1494 case ISD::SETEQ: return ARMCC::EQ; 1495 case ISD::SETGT: return ARMCC::GT; 1496 case ISD::SETGE: return ARMCC::GE; 1497 case ISD::SETLT: return ARMCC::LT; 1498 case ISD::SETLE: return ARMCC::LE; 1499 case ISD::SETUGT: return ARMCC::HI; 1500 case ISD::SETUGE: return ARMCC::HS; 1501 case ISD::SETULT: return ARMCC::LO; 1502 case ISD::SETULE: return ARMCC::LS; 1503 } 1504 } 1505 1506 /// FPCCToARMCC - Convert a DAG fp condition code to an ARM CC. 1507 static void FPCCToARMCC(ISD::CondCode CC, ARMCC::CondCodes &CondCode, 1508 ARMCC::CondCodes &CondCode2, bool &InvalidOnQNaN) { 1509 CondCode2 = ARMCC::AL; 1510 InvalidOnQNaN = true; 1511 switch (CC) { 1512 default: llvm_unreachable("Unknown FP condition!"); 1513 case ISD::SETEQ: 1514 case ISD::SETOEQ: 1515 CondCode = ARMCC::EQ; 1516 InvalidOnQNaN = false; 1517 break; 1518 case ISD::SETGT: 1519 case ISD::SETOGT: CondCode = ARMCC::GT; break; 1520 case ISD::SETGE: 1521 case ISD::SETOGE: CondCode = ARMCC::GE; break; 1522 case ISD::SETOLT: CondCode = ARMCC::MI; break; 1523 case ISD::SETOLE: CondCode = ARMCC::LS; break; 1524 case ISD::SETONE: 1525 CondCode = ARMCC::MI; 1526 CondCode2 = ARMCC::GT; 1527 InvalidOnQNaN = false; 1528 break; 1529 case ISD::SETO: CondCode = ARMCC::VC; break; 1530 case ISD::SETUO: CondCode = ARMCC::VS; break; 1531 case ISD::SETUEQ: 1532 CondCode = ARMCC::EQ; 1533 CondCode2 = ARMCC::VS; 1534 InvalidOnQNaN = false; 1535 break; 1536 case ISD::SETUGT: CondCode = ARMCC::HI; break; 1537 case ISD::SETUGE: CondCode = ARMCC::PL; break; 1538 case ISD::SETLT: 1539 case ISD::SETULT: CondCode = ARMCC::LT; break; 1540 case ISD::SETLE: 1541 case ISD::SETULE: CondCode = ARMCC::LE; break; 1542 case ISD::SETNE: 1543 case ISD::SETUNE: 1544 CondCode = ARMCC::NE; 1545 InvalidOnQNaN = false; 1546 break; 1547 } 1548 } 1549 1550 //===----------------------------------------------------------------------===// 1551 // Calling Convention Implementation 1552 //===----------------------------------------------------------------------===// 1553 1554 #include "ARMGenCallingConv.inc" 1555 1556 /// getEffectiveCallingConv - Get the effective calling convention, taking into 1557 /// account presence of floating point hardware and calling convention 1558 /// limitations, such as support for variadic functions. 1559 CallingConv::ID 1560 ARMTargetLowering::getEffectiveCallingConv(CallingConv::ID CC, 1561 bool isVarArg) const { 1562 switch (CC) { 1563 default: 1564 llvm_unreachable("Unsupported calling convention"); 1565 case CallingConv::ARM_AAPCS: 1566 case CallingConv::ARM_APCS: 1567 case CallingConv::GHC: 1568 return CC; 1569 case CallingConv::PreserveMost: 1570 return CallingConv::PreserveMost; 1571 case CallingConv::ARM_AAPCS_VFP: 1572 case CallingConv::Swift: 1573 return isVarArg ? CallingConv::ARM_AAPCS : CallingConv::ARM_AAPCS_VFP; 1574 case CallingConv::C: 1575 if (!Subtarget->isAAPCS_ABI()) 1576 return CallingConv::ARM_APCS; 1577 else if (Subtarget->hasVFP2() && !Subtarget->isThumb1Only() && 1578 getTargetMachine().Options.FloatABIType == FloatABI::Hard && 1579 !isVarArg) 1580 return CallingConv::ARM_AAPCS_VFP; 1581 else 1582 return CallingConv::ARM_AAPCS; 1583 case CallingConv::Fast: 1584 case CallingConv::CXX_FAST_TLS: 1585 if (!Subtarget->isAAPCS_ABI()) { 1586 if (Subtarget->hasVFP2() && !Subtarget->isThumb1Only() && !isVarArg) 1587 return CallingConv::Fast; 1588 return CallingConv::ARM_APCS; 1589 } else if (Subtarget->hasVFP2() && !Subtarget->isThumb1Only() && !isVarArg) 1590 return CallingConv::ARM_AAPCS_VFP; 1591 else 1592 return CallingConv::ARM_AAPCS; 1593 } 1594 } 1595 1596 CCAssignFn *ARMTargetLowering::CCAssignFnForCall(CallingConv::ID CC, 1597 bool isVarArg) const { 1598 return CCAssignFnForNode(CC, false, isVarArg); 1599 } 1600 1601 CCAssignFn *ARMTargetLowering::CCAssignFnForReturn(CallingConv::ID CC, 1602 bool isVarArg) const { 1603 return CCAssignFnForNode(CC, true, isVarArg); 1604 } 1605 1606 /// CCAssignFnForNode - Selects the correct CCAssignFn for the given 1607 /// CallingConvention. 1608 CCAssignFn *ARMTargetLowering::CCAssignFnForNode(CallingConv::ID CC, 1609 bool Return, 1610 bool isVarArg) const { 1611 switch (getEffectiveCallingConv(CC, isVarArg)) { 1612 default: 1613 llvm_unreachable("Unsupported calling convention"); 1614 case CallingConv::ARM_APCS: 1615 return (Return ? RetCC_ARM_APCS : CC_ARM_APCS); 1616 case CallingConv::ARM_AAPCS: 1617 return (Return ? RetCC_ARM_AAPCS : CC_ARM_AAPCS); 1618 case CallingConv::ARM_AAPCS_VFP: 1619 return (Return ? RetCC_ARM_AAPCS_VFP : CC_ARM_AAPCS_VFP); 1620 case CallingConv::Fast: 1621 return (Return ? RetFastCC_ARM_APCS : FastCC_ARM_APCS); 1622 case CallingConv::GHC: 1623 return (Return ? RetCC_ARM_APCS : CC_ARM_APCS_GHC); 1624 case CallingConv::PreserveMost: 1625 return (Return ? RetCC_ARM_AAPCS : CC_ARM_AAPCS); 1626 } 1627 } 1628 1629 /// LowerCallResult - Lower the result values of a call into the 1630 /// appropriate copies out of appropriate physical registers. 1631 SDValue ARMTargetLowering::LowerCallResult( 1632 SDValue Chain, SDValue InFlag, CallingConv::ID CallConv, bool isVarArg, 1633 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl, 1634 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals, bool isThisReturn, 1635 SDValue ThisVal) const { 1636 1637 // Assign locations to each value returned by this call. 1638 SmallVector<CCValAssign, 16> RVLocs; 1639 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs, 1640 *DAG.getContext()); 1641 CCInfo.AnalyzeCallResult(Ins, CCAssignFnForReturn(CallConv, isVarArg)); 1642 1643 // Copy all of the result registers out of their specified physreg. 1644 for (unsigned i = 0; i != RVLocs.size(); ++i) { 1645 CCValAssign VA = RVLocs[i]; 1646 1647 // Pass 'this' value directly from the argument to return value, to avoid 1648 // reg unit interference 1649 if (i == 0 && isThisReturn) { 1650 assert(!VA.needsCustom() && VA.getLocVT() == MVT::i32 && 1651 "unexpected return calling convention register assignment"); 1652 InVals.push_back(ThisVal); 1653 continue; 1654 } 1655 1656 SDValue Val; 1657 if (VA.needsCustom()) { 1658 // Handle f64 or half of a v2f64. 1659 SDValue Lo = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32, 1660 InFlag); 1661 Chain = Lo.getValue(1); 1662 InFlag = Lo.getValue(2); 1663 VA = RVLocs[++i]; // skip ahead to next loc 1664 SDValue Hi = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32, 1665 InFlag); 1666 Chain = Hi.getValue(1); 1667 InFlag = Hi.getValue(2); 1668 if (!Subtarget->isLittle()) 1669 std::swap (Lo, Hi); 1670 Val = DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi); 1671 1672 if (VA.getLocVT() == MVT::v2f64) { 1673 SDValue Vec = DAG.getNode(ISD::UNDEF, dl, MVT::v2f64); 1674 Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Vec, Val, 1675 DAG.getConstant(0, dl, MVT::i32)); 1676 1677 VA = RVLocs[++i]; // skip ahead to next loc 1678 Lo = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32, InFlag); 1679 Chain = Lo.getValue(1); 1680 InFlag = Lo.getValue(2); 1681 VA = RVLocs[++i]; // skip ahead to next loc 1682 Hi = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32, InFlag); 1683 Chain = Hi.getValue(1); 1684 InFlag = Hi.getValue(2); 1685 if (!Subtarget->isLittle()) 1686 std::swap (Lo, Hi); 1687 Val = DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi); 1688 Val = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Vec, Val, 1689 DAG.getConstant(1, dl, MVT::i32)); 1690 } 1691 } else { 1692 Val = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), VA.getLocVT(), 1693 InFlag); 1694 Chain = Val.getValue(1); 1695 InFlag = Val.getValue(2); 1696 } 1697 1698 switch (VA.getLocInfo()) { 1699 default: llvm_unreachable("Unknown loc info!"); 1700 case CCValAssign::Full: break; 1701 case CCValAssign::BCvt: 1702 Val = DAG.getNode(ISD::BITCAST, dl, VA.getValVT(), Val); 1703 break; 1704 } 1705 1706 InVals.push_back(Val); 1707 } 1708 1709 return Chain; 1710 } 1711 1712 /// LowerMemOpCallTo - Store the argument to the stack. 1713 SDValue ARMTargetLowering::LowerMemOpCallTo(SDValue Chain, SDValue StackPtr, 1714 SDValue Arg, const SDLoc &dl, 1715 SelectionDAG &DAG, 1716 const CCValAssign &VA, 1717 ISD::ArgFlagsTy Flags) const { 1718 unsigned LocMemOffset = VA.getLocMemOffset(); 1719 SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset, dl); 1720 PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(DAG.getDataLayout()), 1721 StackPtr, PtrOff); 1722 return DAG.getStore( 1723 Chain, dl, Arg, PtrOff, 1724 MachinePointerInfo::getStack(DAG.getMachineFunction(), LocMemOffset)); 1725 } 1726 1727 void ARMTargetLowering::PassF64ArgInRegs(const SDLoc &dl, SelectionDAG &DAG, 1728 SDValue Chain, SDValue &Arg, 1729 RegsToPassVector &RegsToPass, 1730 CCValAssign &VA, CCValAssign &NextVA, 1731 SDValue &StackPtr, 1732 SmallVectorImpl<SDValue> &MemOpChains, 1733 ISD::ArgFlagsTy Flags) const { 1734 1735 SDValue fmrrd = DAG.getNode(ARMISD::VMOVRRD, dl, 1736 DAG.getVTList(MVT::i32, MVT::i32), Arg); 1737 unsigned id = Subtarget->isLittle() ? 0 : 1; 1738 RegsToPass.push_back(std::make_pair(VA.getLocReg(), fmrrd.getValue(id))); 1739 1740 if (NextVA.isRegLoc()) 1741 RegsToPass.push_back(std::make_pair(NextVA.getLocReg(), fmrrd.getValue(1-id))); 1742 else { 1743 assert(NextVA.isMemLoc()); 1744 if (!StackPtr.getNode()) 1745 StackPtr = DAG.getCopyFromReg(Chain, dl, ARM::SP, 1746 getPointerTy(DAG.getDataLayout())); 1747 1748 MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, fmrrd.getValue(1-id), 1749 dl, DAG, NextVA, 1750 Flags)); 1751 } 1752 } 1753 1754 /// LowerCall - Lowering a call into a callseq_start <- 1755 /// ARMISD:CALL <- callseq_end chain. Also add input and output parameter 1756 /// nodes. 1757 SDValue 1758 ARMTargetLowering::LowerCall(TargetLowering::CallLoweringInfo &CLI, 1759 SmallVectorImpl<SDValue> &InVals) const { 1760 SelectionDAG &DAG = CLI.DAG; 1761 SDLoc &dl = CLI.DL; 1762 SmallVectorImpl<ISD::OutputArg> &Outs = CLI.Outs; 1763 SmallVectorImpl<SDValue> &OutVals = CLI.OutVals; 1764 SmallVectorImpl<ISD::InputArg> &Ins = CLI.Ins; 1765 SDValue Chain = CLI.Chain; 1766 SDValue Callee = CLI.Callee; 1767 bool &isTailCall = CLI.IsTailCall; 1768 CallingConv::ID CallConv = CLI.CallConv; 1769 bool doesNotRet = CLI.DoesNotReturn; 1770 bool isVarArg = CLI.IsVarArg; 1771 1772 MachineFunction &MF = DAG.getMachineFunction(); 1773 bool isStructRet = (Outs.empty()) ? false : Outs[0].Flags.isSRet(); 1774 bool isThisReturn = false; 1775 bool isSibCall = false; 1776 auto Attr = MF.getFunction()->getFnAttribute("disable-tail-calls"); 1777 1778 // Disable tail calls if they're not supported. 1779 if (!Subtarget->supportsTailCall() || Attr.getValueAsString() == "true") 1780 isTailCall = false; 1781 1782 if (isTailCall) { 1783 // Check if it's really possible to do a tail call. 1784 isTailCall = IsEligibleForTailCallOptimization(Callee, CallConv, 1785 isVarArg, isStructRet, MF.getFunction()->hasStructRetAttr(), 1786 Outs, OutVals, Ins, DAG); 1787 if (!isTailCall && CLI.CS && CLI.CS->isMustTailCall()) 1788 report_fatal_error("failed to perform tail call elimination on a call " 1789 "site marked musttail"); 1790 // We don't support GuaranteedTailCallOpt for ARM, only automatically 1791 // detected sibcalls. 1792 if (isTailCall) { 1793 ++NumTailCalls; 1794 isSibCall = true; 1795 } 1796 } 1797 1798 // Analyze operands of the call, assigning locations to each operand. 1799 SmallVector<CCValAssign, 16> ArgLocs; 1800 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), ArgLocs, 1801 *DAG.getContext()); 1802 CCInfo.AnalyzeCallOperands(Outs, CCAssignFnForCall(CallConv, isVarArg)); 1803 1804 // Get a count of how many bytes are to be pushed on the stack. 1805 unsigned NumBytes = CCInfo.getNextStackOffset(); 1806 1807 // For tail calls, memory operands are available in our caller's stack. 1808 if (isSibCall) 1809 NumBytes = 0; 1810 1811 // Adjust the stack pointer for the new arguments... 1812 // These operations are automatically eliminated by the prolog/epilog pass 1813 if (!isSibCall) 1814 Chain = DAG.getCALLSEQ_START(Chain, 1815 DAG.getIntPtrConstant(NumBytes, dl, true), dl); 1816 1817 SDValue StackPtr = 1818 DAG.getCopyFromReg(Chain, dl, ARM::SP, getPointerTy(DAG.getDataLayout())); 1819 1820 RegsToPassVector RegsToPass; 1821 SmallVector<SDValue, 8> MemOpChains; 1822 1823 // Walk the register/memloc assignments, inserting copies/loads. In the case 1824 // of tail call optimization, arguments are handled later. 1825 for (unsigned i = 0, realArgIdx = 0, e = ArgLocs.size(); 1826 i != e; 1827 ++i, ++realArgIdx) { 1828 CCValAssign &VA = ArgLocs[i]; 1829 SDValue Arg = OutVals[realArgIdx]; 1830 ISD::ArgFlagsTy Flags = Outs[realArgIdx].Flags; 1831 bool isByVal = Flags.isByVal(); 1832 1833 // Promote the value if needed. 1834 switch (VA.getLocInfo()) { 1835 default: llvm_unreachable("Unknown loc info!"); 1836 case CCValAssign::Full: break; 1837 case CCValAssign::SExt: 1838 Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), Arg); 1839 break; 1840 case CCValAssign::ZExt: 1841 Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, VA.getLocVT(), Arg); 1842 break; 1843 case CCValAssign::AExt: 1844 Arg = DAG.getNode(ISD::ANY_EXTEND, dl, VA.getLocVT(), Arg); 1845 break; 1846 case CCValAssign::BCvt: 1847 Arg = DAG.getNode(ISD::BITCAST, dl, VA.getLocVT(), Arg); 1848 break; 1849 } 1850 1851 // f64 and v2f64 might be passed in i32 pairs and must be split into pieces 1852 if (VA.needsCustom()) { 1853 if (VA.getLocVT() == MVT::v2f64) { 1854 SDValue Op0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg, 1855 DAG.getConstant(0, dl, MVT::i32)); 1856 SDValue Op1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg, 1857 DAG.getConstant(1, dl, MVT::i32)); 1858 1859 PassF64ArgInRegs(dl, DAG, Chain, Op0, RegsToPass, 1860 VA, ArgLocs[++i], StackPtr, MemOpChains, Flags); 1861 1862 VA = ArgLocs[++i]; // skip ahead to next loc 1863 if (VA.isRegLoc()) { 1864 PassF64ArgInRegs(dl, DAG, Chain, Op1, RegsToPass, 1865 VA, ArgLocs[++i], StackPtr, MemOpChains, Flags); 1866 } else { 1867 assert(VA.isMemLoc()); 1868 1869 MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, Op1, 1870 dl, DAG, VA, Flags)); 1871 } 1872 } else { 1873 PassF64ArgInRegs(dl, DAG, Chain, Arg, RegsToPass, VA, ArgLocs[++i], 1874 StackPtr, MemOpChains, Flags); 1875 } 1876 } else if (VA.isRegLoc()) { 1877 if (realArgIdx == 0 && Flags.isReturned() && !Flags.isSwiftSelf() && 1878 Outs[0].VT == MVT::i32) { 1879 assert(VA.getLocVT() == MVT::i32 && 1880 "unexpected calling convention register assignment"); 1881 assert(!Ins.empty() && Ins[0].VT == MVT::i32 && 1882 "unexpected use of 'returned'"); 1883 isThisReturn = true; 1884 } 1885 RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg)); 1886 } else if (isByVal) { 1887 assert(VA.isMemLoc()); 1888 unsigned offset = 0; 1889 1890 // True if this byval aggregate will be split between registers 1891 // and memory. 1892 unsigned ByValArgsCount = CCInfo.getInRegsParamsCount(); 1893 unsigned CurByValIdx = CCInfo.getInRegsParamsProcessed(); 1894 1895 if (CurByValIdx < ByValArgsCount) { 1896 1897 unsigned RegBegin, RegEnd; 1898 CCInfo.getInRegsParamInfo(CurByValIdx, RegBegin, RegEnd); 1899 1900 EVT PtrVT = 1901 DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout()); 1902 unsigned int i, j; 1903 for (i = 0, j = RegBegin; j < RegEnd; i++, j++) { 1904 SDValue Const = DAG.getConstant(4*i, dl, MVT::i32); 1905 SDValue AddArg = DAG.getNode(ISD::ADD, dl, PtrVT, Arg, Const); 1906 SDValue Load = DAG.getLoad(PtrVT, dl, Chain, AddArg, 1907 MachinePointerInfo(), 1908 DAG.InferPtrAlignment(AddArg)); 1909 MemOpChains.push_back(Load.getValue(1)); 1910 RegsToPass.push_back(std::make_pair(j, Load)); 1911 } 1912 1913 // If parameter size outsides register area, "offset" value 1914 // helps us to calculate stack slot for remained part properly. 1915 offset = RegEnd - RegBegin; 1916 1917 CCInfo.nextInRegsParam(); 1918 } 1919 1920 if (Flags.getByValSize() > 4*offset) { 1921 auto PtrVT = getPointerTy(DAG.getDataLayout()); 1922 unsigned LocMemOffset = VA.getLocMemOffset(); 1923 SDValue StkPtrOff = DAG.getIntPtrConstant(LocMemOffset, dl); 1924 SDValue Dst = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, StkPtrOff); 1925 SDValue SrcOffset = DAG.getIntPtrConstant(4*offset, dl); 1926 SDValue Src = DAG.getNode(ISD::ADD, dl, PtrVT, Arg, SrcOffset); 1927 SDValue SizeNode = DAG.getConstant(Flags.getByValSize() - 4*offset, dl, 1928 MVT::i32); 1929 SDValue AlignNode = DAG.getConstant(Flags.getByValAlign(), dl, 1930 MVT::i32); 1931 1932 SDVTList VTs = DAG.getVTList(MVT::Other, MVT::Glue); 1933 SDValue Ops[] = { Chain, Dst, Src, SizeNode, AlignNode}; 1934 MemOpChains.push_back(DAG.getNode(ARMISD::COPY_STRUCT_BYVAL, dl, VTs, 1935 Ops)); 1936 } 1937 } else if (!isSibCall) { 1938 assert(VA.isMemLoc()); 1939 1940 MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, Arg, 1941 dl, DAG, VA, Flags)); 1942 } 1943 } 1944 1945 if (!MemOpChains.empty()) 1946 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains); 1947 1948 // Build a sequence of copy-to-reg nodes chained together with token chain 1949 // and flag operands which copy the outgoing args into the appropriate regs. 1950 SDValue InFlag; 1951 // Tail call byval lowering might overwrite argument registers so in case of 1952 // tail call optimization the copies to registers are lowered later. 1953 if (!isTailCall) 1954 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) { 1955 Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first, 1956 RegsToPass[i].second, InFlag); 1957 InFlag = Chain.getValue(1); 1958 } 1959 1960 // For tail calls lower the arguments to the 'real' stack slot. 1961 if (isTailCall) { 1962 // Force all the incoming stack arguments to be loaded from the stack 1963 // before any new outgoing arguments are stored to the stack, because the 1964 // outgoing stack slots may alias the incoming argument stack slots, and 1965 // the alias isn't otherwise explicit. This is slightly more conservative 1966 // than necessary, because it means that each store effectively depends 1967 // on every argument instead of just those arguments it would clobber. 1968 1969 // Do not flag preceding copytoreg stuff together with the following stuff. 1970 InFlag = SDValue(); 1971 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) { 1972 Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first, 1973 RegsToPass[i].second, InFlag); 1974 InFlag = Chain.getValue(1); 1975 } 1976 InFlag = SDValue(); 1977 } 1978 1979 // If the callee is a GlobalAddress/ExternalSymbol node (quite common, every 1980 // direct call is) turn it into a TargetGlobalAddress/TargetExternalSymbol 1981 // node so that legalize doesn't hack it. 1982 bool isDirect = false; 1983 1984 const TargetMachine &TM = getTargetMachine(); 1985 const Module *Mod = MF.getFunction()->getParent(); 1986 const GlobalValue *GV = nullptr; 1987 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) 1988 GV = G->getGlobal(); 1989 bool isStub = 1990 !TM.shouldAssumeDSOLocal(*Mod, GV) && Subtarget->isTargetMachO(); 1991 1992 bool isARMFunc = !Subtarget->isThumb() || (isStub && !Subtarget->isMClass()); 1993 bool isLocalARMFunc = false; 1994 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>(); 1995 auto PtrVt = getPointerTy(DAG.getDataLayout()); 1996 1997 if (Subtarget->genLongCalls()) { 1998 assert((!isPositionIndependent() || Subtarget->isTargetWindows()) && 1999 "long-calls codegen is not position independent!"); 2000 // Handle a global address or an external symbol. If it's not one of 2001 // those, the target's already in a register, so we don't need to do 2002 // anything extra. 2003 if (isa<GlobalAddressSDNode>(Callee)) { 2004 // Create a constant pool entry for the callee address 2005 unsigned ARMPCLabelIndex = AFI->createPICLabelUId(); 2006 ARMConstantPoolValue *CPV = 2007 ARMConstantPoolConstant::Create(GV, ARMPCLabelIndex, ARMCP::CPValue, 0); 2008 2009 // Get the address of the callee into a register 2010 SDValue CPAddr = DAG.getTargetConstantPool(CPV, PtrVt, 4); 2011 CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr); 2012 Callee = DAG.getLoad( 2013 PtrVt, dl, DAG.getEntryNode(), CPAddr, 2014 MachinePointerInfo::getConstantPool(DAG.getMachineFunction())); 2015 } else if (ExternalSymbolSDNode *S=dyn_cast<ExternalSymbolSDNode>(Callee)) { 2016 const char *Sym = S->getSymbol(); 2017 2018 // Create a constant pool entry for the callee address 2019 unsigned ARMPCLabelIndex = AFI->createPICLabelUId(); 2020 ARMConstantPoolValue *CPV = 2021 ARMConstantPoolSymbol::Create(*DAG.getContext(), Sym, 2022 ARMPCLabelIndex, 0); 2023 // Get the address of the callee into a register 2024 SDValue CPAddr = DAG.getTargetConstantPool(CPV, PtrVt, 4); 2025 CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr); 2026 Callee = DAG.getLoad( 2027 PtrVt, dl, DAG.getEntryNode(), CPAddr, 2028 MachinePointerInfo::getConstantPool(DAG.getMachineFunction())); 2029 } 2030 } else if (isa<GlobalAddressSDNode>(Callee)) { 2031 // If we're optimizing for minimum size and the function is called three or 2032 // more times in this block, we can improve codesize by calling indirectly 2033 // as BLXr has a 16-bit encoding. 2034 auto *GV = cast<GlobalAddressSDNode>(Callee)->getGlobal(); 2035 auto *BB = CLI.CS->getParent(); 2036 bool PreferIndirect = 2037 Subtarget->isThumb() && MF.getFunction()->optForMinSize() && 2038 count_if(GV->users(), [&BB](const User *U) { 2039 return isa<Instruction>(U) && cast<Instruction>(U)->getParent() == BB; 2040 }) > 2; 2041 2042 if (!PreferIndirect) { 2043 isDirect = true; 2044 bool isDef = GV->isStrongDefinitionForLinker(); 2045 2046 // ARM call to a local ARM function is predicable. 2047 isLocalARMFunc = !Subtarget->isThumb() && (isDef || !ARMInterworking); 2048 // tBX takes a register source operand. 2049 if (isStub && Subtarget->isThumb1Only() && !Subtarget->hasV5TOps()) { 2050 assert(Subtarget->isTargetMachO() && "WrapperPIC use on non-MachO?"); 2051 Callee = DAG.getNode( 2052 ARMISD::WrapperPIC, dl, PtrVt, 2053 DAG.getTargetGlobalAddress(GV, dl, PtrVt, 0, ARMII::MO_NONLAZY)); 2054 Callee = DAG.getLoad( 2055 PtrVt, dl, DAG.getEntryNode(), Callee, 2056 MachinePointerInfo::getGOT(DAG.getMachineFunction()), 2057 /* Alignment = */ 0, MachineMemOperand::MODereferenceable | 2058 MachineMemOperand::MOInvariant); 2059 } else if (Subtarget->isTargetCOFF()) { 2060 assert(Subtarget->isTargetWindows() && 2061 "Windows is the only supported COFF target"); 2062 unsigned TargetFlags = GV->hasDLLImportStorageClass() 2063 ? ARMII::MO_DLLIMPORT 2064 : ARMII::MO_NO_FLAG; 2065 Callee = DAG.getTargetGlobalAddress(GV, dl, PtrVt, /*Offset=*/0, 2066 TargetFlags); 2067 if (GV->hasDLLImportStorageClass()) 2068 Callee = 2069 DAG.getLoad(PtrVt, dl, DAG.getEntryNode(), 2070 DAG.getNode(ARMISD::Wrapper, dl, PtrVt, Callee), 2071 MachinePointerInfo::getGOT(DAG.getMachineFunction())); 2072 } else { 2073 Callee = DAG.getTargetGlobalAddress(GV, dl, PtrVt, 0, 0); 2074 } 2075 } 2076 } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) { 2077 isDirect = true; 2078 // tBX takes a register source operand. 2079 const char *Sym = S->getSymbol(); 2080 if (isARMFunc && Subtarget->isThumb1Only() && !Subtarget->hasV5TOps()) { 2081 unsigned ARMPCLabelIndex = AFI->createPICLabelUId(); 2082 ARMConstantPoolValue *CPV = 2083 ARMConstantPoolSymbol::Create(*DAG.getContext(), Sym, 2084 ARMPCLabelIndex, 4); 2085 SDValue CPAddr = DAG.getTargetConstantPool(CPV, PtrVt, 4); 2086 CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr); 2087 Callee = DAG.getLoad( 2088 PtrVt, dl, DAG.getEntryNode(), CPAddr, 2089 MachinePointerInfo::getConstantPool(DAG.getMachineFunction())); 2090 SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, dl, MVT::i32); 2091 Callee = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVt, Callee, PICLabel); 2092 } else { 2093 Callee = DAG.getTargetExternalSymbol(Sym, PtrVt, 0); 2094 } 2095 } 2096 2097 // FIXME: handle tail calls differently. 2098 unsigned CallOpc; 2099 if (Subtarget->isThumb()) { 2100 if ((!isDirect || isARMFunc) && !Subtarget->hasV5TOps()) 2101 CallOpc = ARMISD::CALL_NOLINK; 2102 else 2103 CallOpc = ARMISD::CALL; 2104 } else { 2105 if (!isDirect && !Subtarget->hasV5TOps()) 2106 CallOpc = ARMISD::CALL_NOLINK; 2107 else if (doesNotRet && isDirect && Subtarget->hasRetAddrStack() && 2108 // Emit regular call when code size is the priority 2109 !MF.getFunction()->optForMinSize()) 2110 // "mov lr, pc; b _foo" to avoid confusing the RSP 2111 CallOpc = ARMISD::CALL_NOLINK; 2112 else 2113 CallOpc = isLocalARMFunc ? ARMISD::CALL_PRED : ARMISD::CALL; 2114 } 2115 2116 std::vector<SDValue> Ops; 2117 Ops.push_back(Chain); 2118 Ops.push_back(Callee); 2119 2120 // Add argument registers to the end of the list so that they are known live 2121 // into the call. 2122 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) 2123 Ops.push_back(DAG.getRegister(RegsToPass[i].first, 2124 RegsToPass[i].second.getValueType())); 2125 2126 // Add a register mask operand representing the call-preserved registers. 2127 if (!isTailCall) { 2128 const uint32_t *Mask; 2129 const ARMBaseRegisterInfo *ARI = Subtarget->getRegisterInfo(); 2130 if (isThisReturn) { 2131 // For 'this' returns, use the R0-preserving mask if applicable 2132 Mask = ARI->getThisReturnPreservedMask(MF, CallConv); 2133 if (!Mask) { 2134 // Set isThisReturn to false if the calling convention is not one that 2135 // allows 'returned' to be modeled in this way, so LowerCallResult does 2136 // not try to pass 'this' straight through 2137 isThisReturn = false; 2138 Mask = ARI->getCallPreservedMask(MF, CallConv); 2139 } 2140 } else 2141 Mask = ARI->getCallPreservedMask(MF, CallConv); 2142 2143 assert(Mask && "Missing call preserved mask for calling convention"); 2144 Ops.push_back(DAG.getRegisterMask(Mask)); 2145 } 2146 2147 if (InFlag.getNode()) 2148 Ops.push_back(InFlag); 2149 2150 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue); 2151 if (isTailCall) { 2152 MF.getFrameInfo().setHasTailCall(); 2153 return DAG.getNode(ARMISD::TC_RETURN, dl, NodeTys, Ops); 2154 } 2155 2156 // Returns a chain and a flag for retval copy to use. 2157 Chain = DAG.getNode(CallOpc, dl, NodeTys, Ops); 2158 InFlag = Chain.getValue(1); 2159 2160 Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, dl, true), 2161 DAG.getIntPtrConstant(0, dl, true), InFlag, dl); 2162 if (!Ins.empty()) 2163 InFlag = Chain.getValue(1); 2164 2165 // Handle result values, copying them out of physregs into vregs that we 2166 // return. 2167 return LowerCallResult(Chain, InFlag, CallConv, isVarArg, Ins, dl, DAG, 2168 InVals, isThisReturn, 2169 isThisReturn ? OutVals[0] : SDValue()); 2170 } 2171 2172 /// HandleByVal - Every parameter *after* a byval parameter is passed 2173 /// on the stack. Remember the next parameter register to allocate, 2174 /// and then confiscate the rest of the parameter registers to insure 2175 /// this. 2176 void ARMTargetLowering::HandleByVal(CCState *State, unsigned &Size, 2177 unsigned Align) const { 2178 // Byval (as with any stack) slots are always at least 4 byte aligned. 2179 Align = std::max(Align, 4U); 2180 2181 unsigned Reg = State->AllocateReg(GPRArgRegs); 2182 if (!Reg) 2183 return; 2184 2185 unsigned AlignInRegs = Align / 4; 2186 unsigned Waste = (ARM::R4 - Reg) % AlignInRegs; 2187 for (unsigned i = 0; i < Waste; ++i) 2188 Reg = State->AllocateReg(GPRArgRegs); 2189 2190 if (!Reg) 2191 return; 2192 2193 unsigned Excess = 4 * (ARM::R4 - Reg); 2194 2195 // Special case when NSAA != SP and parameter size greater than size of 2196 // all remained GPR regs. In that case we can't split parameter, we must 2197 // send it to stack. We also must set NCRN to R4, so waste all 2198 // remained registers. 2199 const unsigned NSAAOffset = State->getNextStackOffset(); 2200 if (NSAAOffset != 0 && Size > Excess) { 2201 while (State->AllocateReg(GPRArgRegs)) 2202 ; 2203 return; 2204 } 2205 2206 // First register for byval parameter is the first register that wasn't 2207 // allocated before this method call, so it would be "reg". 2208 // If parameter is small enough to be saved in range [reg, r4), then 2209 // the end (first after last) register would be reg + param-size-in-regs, 2210 // else parameter would be splitted between registers and stack, 2211 // end register would be r4 in this case. 2212 unsigned ByValRegBegin = Reg; 2213 unsigned ByValRegEnd = std::min<unsigned>(Reg + Size / 4, ARM::R4); 2214 State->addInRegsParamInfo(ByValRegBegin, ByValRegEnd); 2215 // Note, first register is allocated in the beginning of function already, 2216 // allocate remained amount of registers we need. 2217 for (unsigned i = Reg + 1; i != ByValRegEnd; ++i) 2218 State->AllocateReg(GPRArgRegs); 2219 // A byval parameter that is split between registers and memory needs its 2220 // size truncated here. 2221 // In the case where the entire structure fits in registers, we set the 2222 // size in memory to zero. 2223 Size = std::max<int>(Size - Excess, 0); 2224 } 2225 2226 /// MatchingStackOffset - Return true if the given stack call argument is 2227 /// already available in the same position (relatively) of the caller's 2228 /// incoming argument stack. 2229 static 2230 bool MatchingStackOffset(SDValue Arg, unsigned Offset, ISD::ArgFlagsTy Flags, 2231 MachineFrameInfo &MFI, const MachineRegisterInfo *MRI, 2232 const TargetInstrInfo *TII) { 2233 unsigned Bytes = Arg.getValueSizeInBits() / 8; 2234 int FI = std::numeric_limits<int>::max(); 2235 if (Arg.getOpcode() == ISD::CopyFromReg) { 2236 unsigned VR = cast<RegisterSDNode>(Arg.getOperand(1))->getReg(); 2237 if (!TargetRegisterInfo::isVirtualRegister(VR)) 2238 return false; 2239 MachineInstr *Def = MRI->getVRegDef(VR); 2240 if (!Def) 2241 return false; 2242 if (!Flags.isByVal()) { 2243 if (!TII->isLoadFromStackSlot(*Def, FI)) 2244 return false; 2245 } else { 2246 return false; 2247 } 2248 } else if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Arg)) { 2249 if (Flags.isByVal()) 2250 // ByVal argument is passed in as a pointer but it's now being 2251 // dereferenced. e.g. 2252 // define @foo(%struct.X* %A) { 2253 // tail call @bar(%struct.X* byval %A) 2254 // } 2255 return false; 2256 SDValue Ptr = Ld->getBasePtr(); 2257 FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr); 2258 if (!FINode) 2259 return false; 2260 FI = FINode->getIndex(); 2261 } else 2262 return false; 2263 2264 assert(FI != std::numeric_limits<int>::max()); 2265 if (!MFI.isFixedObjectIndex(FI)) 2266 return false; 2267 return Offset == MFI.getObjectOffset(FI) && Bytes == MFI.getObjectSize(FI); 2268 } 2269 2270 /// IsEligibleForTailCallOptimization - Check whether the call is eligible 2271 /// for tail call optimization. Targets which want to do tail call 2272 /// optimization should implement this function. 2273 bool 2274 ARMTargetLowering::IsEligibleForTailCallOptimization(SDValue Callee, 2275 CallingConv::ID CalleeCC, 2276 bool isVarArg, 2277 bool isCalleeStructRet, 2278 bool isCallerStructRet, 2279 const SmallVectorImpl<ISD::OutputArg> &Outs, 2280 const SmallVectorImpl<SDValue> &OutVals, 2281 const SmallVectorImpl<ISD::InputArg> &Ins, 2282 SelectionDAG& DAG) const { 2283 MachineFunction &MF = DAG.getMachineFunction(); 2284 const Function *CallerF = MF.getFunction(); 2285 CallingConv::ID CallerCC = CallerF->getCallingConv(); 2286 2287 assert(Subtarget->supportsTailCall()); 2288 2289 // Look for obvious safe cases to perform tail call optimization that do not 2290 // require ABI changes. This is what gcc calls sibcall. 2291 2292 // Exception-handling functions need a special set of instructions to indicate 2293 // a return to the hardware. Tail-calling another function would probably 2294 // break this. 2295 if (CallerF->hasFnAttribute("interrupt")) 2296 return false; 2297 2298 // Also avoid sibcall optimization if either caller or callee uses struct 2299 // return semantics. 2300 if (isCalleeStructRet || isCallerStructRet) 2301 return false; 2302 2303 // Externally-defined functions with weak linkage should not be 2304 // tail-called on ARM when the OS does not support dynamic 2305 // pre-emption of symbols, as the AAELF spec requires normal calls 2306 // to undefined weak functions to be replaced with a NOP or jump to the 2307 // next instruction. The behaviour of branch instructions in this 2308 // situation (as used for tail calls) is implementation-defined, so we 2309 // cannot rely on the linker replacing the tail call with a return. 2310 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) { 2311 const GlobalValue *GV = G->getGlobal(); 2312 const Triple &TT = getTargetMachine().getTargetTriple(); 2313 if (GV->hasExternalWeakLinkage() && 2314 (!TT.isOSWindows() || TT.isOSBinFormatELF() || TT.isOSBinFormatMachO())) 2315 return false; 2316 } 2317 2318 // Check that the call results are passed in the same way. 2319 LLVMContext &C = *DAG.getContext(); 2320 if (!CCState::resultsCompatible(CalleeCC, CallerCC, MF, C, Ins, 2321 CCAssignFnForReturn(CalleeCC, isVarArg), 2322 CCAssignFnForReturn(CallerCC, isVarArg))) 2323 return false; 2324 // The callee has to preserve all registers the caller needs to preserve. 2325 const ARMBaseRegisterInfo *TRI = Subtarget->getRegisterInfo(); 2326 const uint32_t *CallerPreserved = TRI->getCallPreservedMask(MF, CallerCC); 2327 if (CalleeCC != CallerCC) { 2328 const uint32_t *CalleePreserved = TRI->getCallPreservedMask(MF, CalleeCC); 2329 if (!TRI->regmaskSubsetEqual(CallerPreserved, CalleePreserved)) 2330 return false; 2331 } 2332 2333 // If Caller's vararg or byval argument has been split between registers and 2334 // stack, do not perform tail call, since part of the argument is in caller's 2335 // local frame. 2336 const ARMFunctionInfo *AFI_Caller = MF.getInfo<ARMFunctionInfo>(); 2337 if (AFI_Caller->getArgRegsSaveSize()) 2338 return false; 2339 2340 // If the callee takes no arguments then go on to check the results of the 2341 // call. 2342 if (!Outs.empty()) { 2343 // Check if stack adjustment is needed. For now, do not do this if any 2344 // argument is passed on the stack. 2345 SmallVector<CCValAssign, 16> ArgLocs; 2346 CCState CCInfo(CalleeCC, isVarArg, MF, ArgLocs, C); 2347 CCInfo.AnalyzeCallOperands(Outs, CCAssignFnForCall(CalleeCC, isVarArg)); 2348 if (CCInfo.getNextStackOffset()) { 2349 // Check if the arguments are already laid out in the right way as 2350 // the caller's fixed stack objects. 2351 MachineFrameInfo &MFI = MF.getFrameInfo(); 2352 const MachineRegisterInfo *MRI = &MF.getRegInfo(); 2353 const TargetInstrInfo *TII = Subtarget->getInstrInfo(); 2354 for (unsigned i = 0, realArgIdx = 0, e = ArgLocs.size(); 2355 i != e; 2356 ++i, ++realArgIdx) { 2357 CCValAssign &VA = ArgLocs[i]; 2358 EVT RegVT = VA.getLocVT(); 2359 SDValue Arg = OutVals[realArgIdx]; 2360 ISD::ArgFlagsTy Flags = Outs[realArgIdx].Flags; 2361 if (VA.getLocInfo() == CCValAssign::Indirect) 2362 return false; 2363 if (VA.needsCustom()) { 2364 // f64 and vector types are split into multiple registers or 2365 // register/stack-slot combinations. The types will not match 2366 // the registers; give up on memory f64 refs until we figure 2367 // out what to do about this. 2368 if (!VA.isRegLoc()) 2369 return false; 2370 if (!ArgLocs[++i].isRegLoc()) 2371 return false; 2372 if (RegVT == MVT::v2f64) { 2373 if (!ArgLocs[++i].isRegLoc()) 2374 return false; 2375 if (!ArgLocs[++i].isRegLoc()) 2376 return false; 2377 } 2378 } else if (!VA.isRegLoc()) { 2379 if (!MatchingStackOffset(Arg, VA.getLocMemOffset(), Flags, 2380 MFI, MRI, TII)) 2381 return false; 2382 } 2383 } 2384 } 2385 2386 const MachineRegisterInfo &MRI = MF.getRegInfo(); 2387 if (!parametersInCSRMatch(MRI, CallerPreserved, ArgLocs, OutVals)) 2388 return false; 2389 } 2390 2391 return true; 2392 } 2393 2394 bool 2395 ARMTargetLowering::CanLowerReturn(CallingConv::ID CallConv, 2396 MachineFunction &MF, bool isVarArg, 2397 const SmallVectorImpl<ISD::OutputArg> &Outs, 2398 LLVMContext &Context) const { 2399 SmallVector<CCValAssign, 16> RVLocs; 2400 CCState CCInfo(CallConv, isVarArg, MF, RVLocs, Context); 2401 return CCInfo.CheckReturn(Outs, CCAssignFnForReturn(CallConv, isVarArg)); 2402 } 2403 2404 static SDValue LowerInterruptReturn(SmallVectorImpl<SDValue> &RetOps, 2405 const SDLoc &DL, SelectionDAG &DAG) { 2406 const MachineFunction &MF = DAG.getMachineFunction(); 2407 const Function *F = MF.getFunction(); 2408 2409 StringRef IntKind = F->getFnAttribute("interrupt").getValueAsString(); 2410 2411 // See ARM ARM v7 B1.8.3. On exception entry LR is set to a possibly offset 2412 // version of the "preferred return address". These offsets affect the return 2413 // instruction if this is a return from PL1 without hypervisor extensions. 2414 // IRQ/FIQ: +4 "subs pc, lr, #4" 2415 // SWI: 0 "subs pc, lr, #0" 2416 // ABORT: +4 "subs pc, lr, #4" 2417 // UNDEF: +4/+2 "subs pc, lr, #0" 2418 // UNDEF varies depending on where the exception came from ARM or Thumb 2419 // mode. Alongside GCC, we throw our hands up in disgust and pretend it's 0. 2420 2421 int64_t LROffset; 2422 if (IntKind == "" || IntKind == "IRQ" || IntKind == "FIQ" || 2423 IntKind == "ABORT") 2424 LROffset = 4; 2425 else if (IntKind == "SWI" || IntKind == "UNDEF") 2426 LROffset = 0; 2427 else 2428 report_fatal_error("Unsupported interrupt attribute. If present, value " 2429 "must be one of: IRQ, FIQ, SWI, ABORT or UNDEF"); 2430 2431 RetOps.insert(RetOps.begin() + 1, 2432 DAG.getConstant(LROffset, DL, MVT::i32, false)); 2433 2434 return DAG.getNode(ARMISD::INTRET_FLAG, DL, MVT::Other, RetOps); 2435 } 2436 2437 SDValue 2438 ARMTargetLowering::LowerReturn(SDValue Chain, CallingConv::ID CallConv, 2439 bool isVarArg, 2440 const SmallVectorImpl<ISD::OutputArg> &Outs, 2441 const SmallVectorImpl<SDValue> &OutVals, 2442 const SDLoc &dl, SelectionDAG &DAG) const { 2443 2444 // CCValAssign - represent the assignment of the return value to a location. 2445 SmallVector<CCValAssign, 16> RVLocs; 2446 2447 // CCState - Info about the registers and stack slots. 2448 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs, 2449 *DAG.getContext()); 2450 2451 // Analyze outgoing return values. 2452 CCInfo.AnalyzeReturn(Outs, CCAssignFnForReturn(CallConv, isVarArg)); 2453 2454 SDValue Flag; 2455 SmallVector<SDValue, 4> RetOps; 2456 RetOps.push_back(Chain); // Operand #0 = Chain (updated below) 2457 bool isLittleEndian = Subtarget->isLittle(); 2458 2459 MachineFunction &MF = DAG.getMachineFunction(); 2460 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>(); 2461 AFI->setReturnRegsCount(RVLocs.size()); 2462 2463 // Copy the result values into the output registers. 2464 for (unsigned i = 0, realRVLocIdx = 0; 2465 i != RVLocs.size(); 2466 ++i, ++realRVLocIdx) { 2467 CCValAssign &VA = RVLocs[i]; 2468 assert(VA.isRegLoc() && "Can only return in registers!"); 2469 2470 SDValue Arg = OutVals[realRVLocIdx]; 2471 2472 switch (VA.getLocInfo()) { 2473 default: llvm_unreachable("Unknown loc info!"); 2474 case CCValAssign::Full: break; 2475 case CCValAssign::BCvt: 2476 Arg = DAG.getNode(ISD::BITCAST, dl, VA.getLocVT(), Arg); 2477 break; 2478 } 2479 2480 if (VA.needsCustom()) { 2481 if (VA.getLocVT() == MVT::v2f64) { 2482 // Extract the first half and return it in two registers. 2483 SDValue Half = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg, 2484 DAG.getConstant(0, dl, MVT::i32)); 2485 SDValue HalfGPRs = DAG.getNode(ARMISD::VMOVRRD, dl, 2486 DAG.getVTList(MVT::i32, MVT::i32), Half); 2487 2488 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), 2489 HalfGPRs.getValue(isLittleEndian ? 0 : 1), 2490 Flag); 2491 Flag = Chain.getValue(1); 2492 RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT())); 2493 VA = RVLocs[++i]; // skip ahead to next loc 2494 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), 2495 HalfGPRs.getValue(isLittleEndian ? 1 : 0), 2496 Flag); 2497 Flag = Chain.getValue(1); 2498 RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT())); 2499 VA = RVLocs[++i]; // skip ahead to next loc 2500 2501 // Extract the 2nd half and fall through to handle it as an f64 value. 2502 Arg = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg, 2503 DAG.getConstant(1, dl, MVT::i32)); 2504 } 2505 // Legalize ret f64 -> ret 2 x i32. We always have fmrrd if f64 is 2506 // available. 2507 SDValue fmrrd = DAG.getNode(ARMISD::VMOVRRD, dl, 2508 DAG.getVTList(MVT::i32, MVT::i32), Arg); 2509 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), 2510 fmrrd.getValue(isLittleEndian ? 0 : 1), 2511 Flag); 2512 Flag = Chain.getValue(1); 2513 RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT())); 2514 VA = RVLocs[++i]; // skip ahead to next loc 2515 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), 2516 fmrrd.getValue(isLittleEndian ? 1 : 0), 2517 Flag); 2518 } else 2519 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), Arg, Flag); 2520 2521 // Guarantee that all emitted copies are 2522 // stuck together, avoiding something bad. 2523 Flag = Chain.getValue(1); 2524 RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT())); 2525 } 2526 const ARMBaseRegisterInfo *TRI = Subtarget->getRegisterInfo(); 2527 const MCPhysReg *I = 2528 TRI->getCalleeSavedRegsViaCopy(&DAG.getMachineFunction()); 2529 if (I) { 2530 for (; *I; ++I) { 2531 if (ARM::GPRRegClass.contains(*I)) 2532 RetOps.push_back(DAG.getRegister(*I, MVT::i32)); 2533 else if (ARM::DPRRegClass.contains(*I)) 2534 RetOps.push_back(DAG.getRegister(*I, MVT::getFloatingPointVT(64))); 2535 else 2536 llvm_unreachable("Unexpected register class in CSRsViaCopy!"); 2537 } 2538 } 2539 2540 // Update chain and glue. 2541 RetOps[0] = Chain; 2542 if (Flag.getNode()) 2543 RetOps.push_back(Flag); 2544 2545 // CPUs which aren't M-class use a special sequence to return from 2546 // exceptions (roughly, any instruction setting pc and cpsr simultaneously, 2547 // though we use "subs pc, lr, #N"). 2548 // 2549 // M-class CPUs actually use a normal return sequence with a special 2550 // (hardware-provided) value in LR, so the normal code path works. 2551 if (DAG.getMachineFunction().getFunction()->hasFnAttribute("interrupt") && 2552 !Subtarget->isMClass()) { 2553 if (Subtarget->isThumb1Only()) 2554 report_fatal_error("interrupt attribute is not supported in Thumb1"); 2555 return LowerInterruptReturn(RetOps, dl, DAG); 2556 } 2557 2558 return DAG.getNode(ARMISD::RET_FLAG, dl, MVT::Other, RetOps); 2559 } 2560 2561 bool ARMTargetLowering::isUsedByReturnOnly(SDNode *N, SDValue &Chain) const { 2562 if (N->getNumValues() != 1) 2563 return false; 2564 if (!N->hasNUsesOfValue(1, 0)) 2565 return false; 2566 2567 SDValue TCChain = Chain; 2568 SDNode *Copy = *N->use_begin(); 2569 if (Copy->getOpcode() == ISD::CopyToReg) { 2570 // If the copy has a glue operand, we conservatively assume it isn't safe to 2571 // perform a tail call. 2572 if (Copy->getOperand(Copy->getNumOperands()-1).getValueType() == MVT::Glue) 2573 return false; 2574 TCChain = Copy->getOperand(0); 2575 } else if (Copy->getOpcode() == ARMISD::VMOVRRD) { 2576 SDNode *VMov = Copy; 2577 // f64 returned in a pair of GPRs. 2578 SmallPtrSet<SDNode*, 2> Copies; 2579 for (SDNode::use_iterator UI = VMov->use_begin(), UE = VMov->use_end(); 2580 UI != UE; ++UI) { 2581 if (UI->getOpcode() != ISD::CopyToReg) 2582 return false; 2583 Copies.insert(*UI); 2584 } 2585 if (Copies.size() > 2) 2586 return false; 2587 2588 for (SDNode::use_iterator UI = VMov->use_begin(), UE = VMov->use_end(); 2589 UI != UE; ++UI) { 2590 SDValue UseChain = UI->getOperand(0); 2591 if (Copies.count(UseChain.getNode())) 2592 // Second CopyToReg 2593 Copy = *UI; 2594 else { 2595 // We are at the top of this chain. 2596 // If the copy has a glue operand, we conservatively assume it 2597 // isn't safe to perform a tail call. 2598 if (UI->getOperand(UI->getNumOperands()-1).getValueType() == MVT::Glue) 2599 return false; 2600 // First CopyToReg 2601 TCChain = UseChain; 2602 } 2603 } 2604 } else if (Copy->getOpcode() == ISD::BITCAST) { 2605 // f32 returned in a single GPR. 2606 if (!Copy->hasOneUse()) 2607 return false; 2608 Copy = *Copy->use_begin(); 2609 if (Copy->getOpcode() != ISD::CopyToReg || !Copy->hasNUsesOfValue(1, 0)) 2610 return false; 2611 // If the copy has a glue operand, we conservatively assume it isn't safe to 2612 // perform a tail call. 2613 if (Copy->getOperand(Copy->getNumOperands()-1).getValueType() == MVT::Glue) 2614 return false; 2615 TCChain = Copy->getOperand(0); 2616 } else { 2617 return false; 2618 } 2619 2620 bool HasRet = false; 2621 for (SDNode::use_iterator UI = Copy->use_begin(), UE = Copy->use_end(); 2622 UI != UE; ++UI) { 2623 if (UI->getOpcode() != ARMISD::RET_FLAG && 2624 UI->getOpcode() != ARMISD::INTRET_FLAG) 2625 return false; 2626 HasRet = true; 2627 } 2628 2629 if (!HasRet) 2630 return false; 2631 2632 Chain = TCChain; 2633 return true; 2634 } 2635 2636 bool ARMTargetLowering::mayBeEmittedAsTailCall(CallInst *CI) const { 2637 if (!Subtarget->supportsTailCall()) 2638 return false; 2639 2640 auto Attr = 2641 CI->getParent()->getParent()->getFnAttribute("disable-tail-calls"); 2642 if (!CI->isTailCall() || Attr.getValueAsString() == "true") 2643 return false; 2644 2645 return true; 2646 } 2647 2648 // Trying to write a 64 bit value so need to split into two 32 bit values first, 2649 // and pass the lower and high parts through. 2650 static SDValue LowerWRITE_REGISTER(SDValue Op, SelectionDAG &DAG) { 2651 SDLoc DL(Op); 2652 SDValue WriteValue = Op->getOperand(2); 2653 2654 // This function is only supposed to be called for i64 type argument. 2655 assert(WriteValue.getValueType() == MVT::i64 2656 && "LowerWRITE_REGISTER called for non-i64 type argument."); 2657 2658 SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, WriteValue, 2659 DAG.getConstant(0, DL, MVT::i32)); 2660 SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, WriteValue, 2661 DAG.getConstant(1, DL, MVT::i32)); 2662 SDValue Ops[] = { Op->getOperand(0), Op->getOperand(1), Lo, Hi }; 2663 return DAG.getNode(ISD::WRITE_REGISTER, DL, MVT::Other, Ops); 2664 } 2665 2666 // ConstantPool, JumpTable, GlobalAddress, and ExternalSymbol are lowered as 2667 // their target counterpart wrapped in the ARMISD::Wrapper node. Suppose N is 2668 // one of the above mentioned nodes. It has to be wrapped because otherwise 2669 // Select(N) returns N. So the raw TargetGlobalAddress nodes, etc. can only 2670 // be used to form addressing mode. These wrapped nodes will be selected 2671 // into MOVi. 2672 static SDValue LowerConstantPool(SDValue Op, SelectionDAG &DAG) { 2673 EVT PtrVT = Op.getValueType(); 2674 // FIXME there is no actual debug info here 2675 SDLoc dl(Op); 2676 ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op); 2677 SDValue Res; 2678 if (CP->isMachineConstantPoolEntry()) 2679 Res = DAG.getTargetConstantPool(CP->getMachineCPVal(), PtrVT, 2680 CP->getAlignment()); 2681 else 2682 Res = DAG.getTargetConstantPool(CP->getConstVal(), PtrVT, 2683 CP->getAlignment()); 2684 return DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Res); 2685 } 2686 2687 unsigned ARMTargetLowering::getJumpTableEncoding() const { 2688 return MachineJumpTableInfo::EK_Inline; 2689 } 2690 2691 SDValue ARMTargetLowering::LowerBlockAddress(SDValue Op, 2692 SelectionDAG &DAG) const { 2693 MachineFunction &MF = DAG.getMachineFunction(); 2694 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>(); 2695 unsigned ARMPCLabelIndex = 0; 2696 SDLoc DL(Op); 2697 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 2698 const BlockAddress *BA = cast<BlockAddressSDNode>(Op)->getBlockAddress(); 2699 SDValue CPAddr; 2700 bool IsPositionIndependent = isPositionIndependent() || Subtarget->isROPI(); 2701 if (!IsPositionIndependent) { 2702 CPAddr = DAG.getTargetConstantPool(BA, PtrVT, 4); 2703 } else { 2704 unsigned PCAdj = Subtarget->isThumb() ? 4 : 8; 2705 ARMPCLabelIndex = AFI->createPICLabelUId(); 2706 ARMConstantPoolValue *CPV = 2707 ARMConstantPoolConstant::Create(BA, ARMPCLabelIndex, 2708 ARMCP::CPBlockAddress, PCAdj); 2709 CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4); 2710 } 2711 CPAddr = DAG.getNode(ARMISD::Wrapper, DL, PtrVT, CPAddr); 2712 SDValue Result = DAG.getLoad( 2713 PtrVT, DL, DAG.getEntryNode(), CPAddr, 2714 MachinePointerInfo::getConstantPool(DAG.getMachineFunction())); 2715 if (!IsPositionIndependent) 2716 return Result; 2717 SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, DL, MVT::i32); 2718 return DAG.getNode(ARMISD::PIC_ADD, DL, PtrVT, Result, PICLabel); 2719 } 2720 2721 /// \brief Convert a TLS address reference into the correct sequence of loads 2722 /// and calls to compute the variable's address for Darwin, and return an 2723 /// SDValue containing the final node. 2724 2725 /// Darwin only has one TLS scheme which must be capable of dealing with the 2726 /// fully general situation, in the worst case. This means: 2727 /// + "extern __thread" declaration. 2728 /// + Defined in a possibly unknown dynamic library. 2729 /// 2730 /// The general system is that each __thread variable has a [3 x i32] descriptor 2731 /// which contains information used by the runtime to calculate the address. The 2732 /// only part of this the compiler needs to know about is the first word, which 2733 /// contains a function pointer that must be called with the address of the 2734 /// entire descriptor in "r0". 2735 /// 2736 /// Since this descriptor may be in a different unit, in general access must 2737 /// proceed along the usual ARM rules. A common sequence to produce is: 2738 /// 2739 /// movw rT1, :lower16:_var$non_lazy_ptr 2740 /// movt rT1, :upper16:_var$non_lazy_ptr 2741 /// ldr r0, [rT1] 2742 /// ldr rT2, [r0] 2743 /// blx rT2 2744 /// [...address now in r0...] 2745 SDValue 2746 ARMTargetLowering::LowerGlobalTLSAddressDarwin(SDValue Op, 2747 SelectionDAG &DAG) const { 2748 assert(Subtarget->isTargetDarwin() && "TLS only supported on Darwin"); 2749 SDLoc DL(Op); 2750 2751 // First step is to get the address of the actua global symbol. This is where 2752 // the TLS descriptor lives. 2753 SDValue DescAddr = LowerGlobalAddressDarwin(Op, DAG); 2754 2755 // The first entry in the descriptor is a function pointer that we must call 2756 // to obtain the address of the variable. 2757 SDValue Chain = DAG.getEntryNode(); 2758 SDValue FuncTLVGet = DAG.getLoad( 2759 MVT::i32, DL, Chain, DescAddr, 2760 MachinePointerInfo::getGOT(DAG.getMachineFunction()), 2761 /* Alignment = */ 4, 2762 MachineMemOperand::MONonTemporal | MachineMemOperand::MODereferenceable | 2763 MachineMemOperand::MOInvariant); 2764 Chain = FuncTLVGet.getValue(1); 2765 2766 MachineFunction &F = DAG.getMachineFunction(); 2767 MachineFrameInfo &MFI = F.getFrameInfo(); 2768 MFI.setAdjustsStack(true); 2769 2770 // TLS calls preserve all registers except those that absolutely must be 2771 // trashed: R0 (it takes an argument), LR (it's a call) and CPSR (let's not be 2772 // silly). 2773 auto TRI = 2774 getTargetMachine().getSubtargetImpl(*F.getFunction())->getRegisterInfo(); 2775 auto ARI = static_cast<const ARMRegisterInfo *>(TRI); 2776 const uint32_t *Mask = ARI->getTLSCallPreservedMask(DAG.getMachineFunction()); 2777 2778 // Finally, we can make the call. This is just a degenerate version of a 2779 // normal AArch64 call node: r0 takes the address of the descriptor, and 2780 // returns the address of the variable in this thread. 2781 Chain = DAG.getCopyToReg(Chain, DL, ARM::R0, DescAddr, SDValue()); 2782 Chain = 2783 DAG.getNode(ARMISD::CALL, DL, DAG.getVTList(MVT::Other, MVT::Glue), 2784 Chain, FuncTLVGet, DAG.getRegister(ARM::R0, MVT::i32), 2785 DAG.getRegisterMask(Mask), Chain.getValue(1)); 2786 return DAG.getCopyFromReg(Chain, DL, ARM::R0, MVT::i32, Chain.getValue(1)); 2787 } 2788 2789 SDValue 2790 ARMTargetLowering::LowerGlobalTLSAddressWindows(SDValue Op, 2791 SelectionDAG &DAG) const { 2792 assert(Subtarget->isTargetWindows() && "Windows specific TLS lowering"); 2793 2794 SDValue Chain = DAG.getEntryNode(); 2795 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 2796 SDLoc DL(Op); 2797 2798 // Load the current TEB (thread environment block) 2799 SDValue Ops[] = {Chain, 2800 DAG.getConstant(Intrinsic::arm_mrc, DL, MVT::i32), 2801 DAG.getConstant(15, DL, MVT::i32), 2802 DAG.getConstant(0, DL, MVT::i32), 2803 DAG.getConstant(13, DL, MVT::i32), 2804 DAG.getConstant(0, DL, MVT::i32), 2805 DAG.getConstant(2, DL, MVT::i32)}; 2806 SDValue CurrentTEB = DAG.getNode(ISD::INTRINSIC_W_CHAIN, DL, 2807 DAG.getVTList(MVT::i32, MVT::Other), Ops); 2808 2809 SDValue TEB = CurrentTEB.getValue(0); 2810 Chain = CurrentTEB.getValue(1); 2811 2812 // Load the ThreadLocalStoragePointer from the TEB 2813 // A pointer to the TLS array is located at offset 0x2c from the TEB. 2814 SDValue TLSArray = 2815 DAG.getNode(ISD::ADD, DL, PtrVT, TEB, DAG.getIntPtrConstant(0x2c, DL)); 2816 TLSArray = DAG.getLoad(PtrVT, DL, Chain, TLSArray, MachinePointerInfo()); 2817 2818 // The pointer to the thread's TLS data area is at the TLS Index scaled by 4 2819 // offset into the TLSArray. 2820 2821 // Load the TLS index from the C runtime 2822 SDValue TLSIndex = 2823 DAG.getTargetExternalSymbol("_tls_index", PtrVT, ARMII::MO_NO_FLAG); 2824 TLSIndex = DAG.getNode(ARMISD::Wrapper, DL, PtrVT, TLSIndex); 2825 TLSIndex = DAG.getLoad(PtrVT, DL, Chain, TLSIndex, MachinePointerInfo()); 2826 2827 SDValue Slot = DAG.getNode(ISD::SHL, DL, PtrVT, TLSIndex, 2828 DAG.getConstant(2, DL, MVT::i32)); 2829 SDValue TLS = DAG.getLoad(PtrVT, DL, Chain, 2830 DAG.getNode(ISD::ADD, DL, PtrVT, TLSArray, Slot), 2831 MachinePointerInfo()); 2832 2833 // Get the offset of the start of the .tls section (section base) 2834 const auto *GA = cast<GlobalAddressSDNode>(Op); 2835 auto *CPV = ARMConstantPoolConstant::Create(GA->getGlobal(), ARMCP::SECREL); 2836 SDValue Offset = DAG.getLoad( 2837 PtrVT, DL, Chain, DAG.getNode(ARMISD::Wrapper, DL, MVT::i32, 2838 DAG.getTargetConstantPool(CPV, PtrVT, 4)), 2839 MachinePointerInfo::getConstantPool(DAG.getMachineFunction())); 2840 2841 return DAG.getNode(ISD::ADD, DL, PtrVT, TLS, Offset); 2842 } 2843 2844 // Lower ISD::GlobalTLSAddress using the "general dynamic" model 2845 SDValue 2846 ARMTargetLowering::LowerToTLSGeneralDynamicModel(GlobalAddressSDNode *GA, 2847 SelectionDAG &DAG) const { 2848 SDLoc dl(GA); 2849 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 2850 unsigned char PCAdj = Subtarget->isThumb() ? 4 : 8; 2851 MachineFunction &MF = DAG.getMachineFunction(); 2852 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>(); 2853 unsigned ARMPCLabelIndex = AFI->createPICLabelUId(); 2854 ARMConstantPoolValue *CPV = 2855 ARMConstantPoolConstant::Create(GA->getGlobal(), ARMPCLabelIndex, 2856 ARMCP::CPValue, PCAdj, ARMCP::TLSGD, true); 2857 SDValue Argument = DAG.getTargetConstantPool(CPV, PtrVT, 4); 2858 Argument = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Argument); 2859 Argument = DAG.getLoad( 2860 PtrVT, dl, DAG.getEntryNode(), Argument, 2861 MachinePointerInfo::getConstantPool(DAG.getMachineFunction())); 2862 SDValue Chain = Argument.getValue(1); 2863 2864 SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, dl, MVT::i32); 2865 Argument = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Argument, PICLabel); 2866 2867 // call __tls_get_addr. 2868 ArgListTy Args; 2869 ArgListEntry Entry; 2870 Entry.Node = Argument; 2871 Entry.Ty = (Type *) Type::getInt32Ty(*DAG.getContext()); 2872 Args.push_back(Entry); 2873 2874 // FIXME: is there useful debug info available here? 2875 TargetLowering::CallLoweringInfo CLI(DAG); 2876 CLI.setDebugLoc(dl).setChain(Chain).setLibCallee( 2877 CallingConv::C, Type::getInt32Ty(*DAG.getContext()), 2878 DAG.getExternalSymbol("__tls_get_addr", PtrVT), std::move(Args)); 2879 2880 std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI); 2881 return CallResult.first; 2882 } 2883 2884 // Lower ISD::GlobalTLSAddress using the "initial exec" or 2885 // "local exec" model. 2886 SDValue 2887 ARMTargetLowering::LowerToTLSExecModels(GlobalAddressSDNode *GA, 2888 SelectionDAG &DAG, 2889 TLSModel::Model model) const { 2890 const GlobalValue *GV = GA->getGlobal(); 2891 SDLoc dl(GA); 2892 SDValue Offset; 2893 SDValue Chain = DAG.getEntryNode(); 2894 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 2895 // Get the Thread Pointer 2896 SDValue ThreadPointer = DAG.getNode(ARMISD::THREAD_POINTER, dl, PtrVT); 2897 2898 if (model == TLSModel::InitialExec) { 2899 MachineFunction &MF = DAG.getMachineFunction(); 2900 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>(); 2901 unsigned ARMPCLabelIndex = AFI->createPICLabelUId(); 2902 // Initial exec model. 2903 unsigned char PCAdj = Subtarget->isThumb() ? 4 : 8; 2904 ARMConstantPoolValue *CPV = 2905 ARMConstantPoolConstant::Create(GA->getGlobal(), ARMPCLabelIndex, 2906 ARMCP::CPValue, PCAdj, ARMCP::GOTTPOFF, 2907 true); 2908 Offset = DAG.getTargetConstantPool(CPV, PtrVT, 4); 2909 Offset = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Offset); 2910 Offset = DAG.getLoad( 2911 PtrVT, dl, Chain, Offset, 2912 MachinePointerInfo::getConstantPool(DAG.getMachineFunction())); 2913 Chain = Offset.getValue(1); 2914 2915 SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, dl, MVT::i32); 2916 Offset = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Offset, PICLabel); 2917 2918 Offset = DAG.getLoad( 2919 PtrVT, dl, Chain, Offset, 2920 MachinePointerInfo::getConstantPool(DAG.getMachineFunction())); 2921 } else { 2922 // local exec model 2923 assert(model == TLSModel::LocalExec); 2924 ARMConstantPoolValue *CPV = 2925 ARMConstantPoolConstant::Create(GV, ARMCP::TPOFF); 2926 Offset = DAG.getTargetConstantPool(CPV, PtrVT, 4); 2927 Offset = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Offset); 2928 Offset = DAG.getLoad( 2929 PtrVT, dl, Chain, Offset, 2930 MachinePointerInfo::getConstantPool(DAG.getMachineFunction())); 2931 } 2932 2933 // The address of the thread local variable is the add of the thread 2934 // pointer with the offset of the variable. 2935 return DAG.getNode(ISD::ADD, dl, PtrVT, ThreadPointer, Offset); 2936 } 2937 2938 SDValue 2939 ARMTargetLowering::LowerGlobalTLSAddress(SDValue Op, SelectionDAG &DAG) const { 2940 if (Subtarget->isTargetDarwin()) 2941 return LowerGlobalTLSAddressDarwin(Op, DAG); 2942 2943 if (Subtarget->isTargetWindows()) 2944 return LowerGlobalTLSAddressWindows(Op, DAG); 2945 2946 // TODO: implement the "local dynamic" model 2947 assert(Subtarget->isTargetELF() && "Only ELF implemented here"); 2948 GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op); 2949 if (DAG.getTarget().Options.EmulatedTLS) 2950 return LowerToTLSEmulatedModel(GA, DAG); 2951 2952 TLSModel::Model model = getTargetMachine().getTLSModel(GA->getGlobal()); 2953 2954 switch (model) { 2955 case TLSModel::GeneralDynamic: 2956 case TLSModel::LocalDynamic: 2957 return LowerToTLSGeneralDynamicModel(GA, DAG); 2958 case TLSModel::InitialExec: 2959 case TLSModel::LocalExec: 2960 return LowerToTLSExecModels(GA, DAG, model); 2961 } 2962 llvm_unreachable("bogus TLS model"); 2963 } 2964 2965 /// Return true if all users of V are within function F, looking through 2966 /// ConstantExprs. 2967 static bool allUsersAreInFunction(const Value *V, const Function *F) { 2968 SmallVector<const User*,4> Worklist; 2969 for (auto *U : V->users()) 2970 Worklist.push_back(U); 2971 while (!Worklist.empty()) { 2972 auto *U = Worklist.pop_back_val(); 2973 if (isa<ConstantExpr>(U)) { 2974 for (auto *UU : U->users()) 2975 Worklist.push_back(UU); 2976 continue; 2977 } 2978 2979 auto *I = dyn_cast<Instruction>(U); 2980 if (!I || I->getParent()->getParent() != F) 2981 return false; 2982 } 2983 return true; 2984 } 2985 2986 /// Return true if all users of V are within some (any) function, looking through 2987 /// ConstantExprs. In other words, are there any global constant users? 2988 static bool allUsersAreInFunctions(const Value *V) { 2989 SmallVector<const User*,4> Worklist; 2990 for (auto *U : V->users()) 2991 Worklist.push_back(U); 2992 while (!Worklist.empty()) { 2993 auto *U = Worklist.pop_back_val(); 2994 if (isa<ConstantExpr>(U)) { 2995 for (auto *UU : U->users()) 2996 Worklist.push_back(UU); 2997 continue; 2998 } 2999 3000 if (!isa<Instruction>(U)) 3001 return false; 3002 } 3003 return true; 3004 } 3005 3006 // Return true if T is an integer, float or an array/vector of either. 3007 static bool isSimpleType(Type *T) { 3008 if (T->isIntegerTy() || T->isFloatingPointTy()) 3009 return true; 3010 Type *SubT = nullptr; 3011 if (T->isArrayTy()) 3012 SubT = T->getArrayElementType(); 3013 else if (T->isVectorTy()) 3014 SubT = T->getVectorElementType(); 3015 else 3016 return false; 3017 return SubT->isIntegerTy() || SubT->isFloatingPointTy(); 3018 } 3019 3020 static SDValue promoteToConstantPool(const GlobalValue *GV, SelectionDAG &DAG, 3021 EVT PtrVT, const SDLoc &dl) { 3022 // If we're creating a pool entry for a constant global with unnamed address, 3023 // and the global is small enough, we can emit it inline into the constant pool 3024 // to save ourselves an indirection. 3025 // 3026 // This is a win if the constant is only used in one function (so it doesn't 3027 // need to be duplicated) or duplicating the constant wouldn't increase code 3028 // size (implying the constant is no larger than 4 bytes). 3029 const Function *F = DAG.getMachineFunction().getFunction(); 3030 3031 // We rely on this decision to inline being idemopotent and unrelated to the 3032 // use-site. We know that if we inline a variable at one use site, we'll 3033 // inline it elsewhere too (and reuse the constant pool entry). Fast-isel 3034 // doesn't know about this optimization, so bail out if it's enabled else 3035 // we could decide to inline here (and thus never emit the GV) but require 3036 // the GV from fast-isel generated code. 3037 if (!EnableConstpoolPromotion || 3038 DAG.getMachineFunction().getTarget().Options.EnableFastISel) 3039 return SDValue(); 3040 3041 auto *GVar = dyn_cast<GlobalVariable>(GV); 3042 if (!GVar || !GVar->hasInitializer() || 3043 !GVar->isConstant() || !GVar->hasGlobalUnnamedAddr() || 3044 !GVar->hasLocalLinkage()) 3045 return SDValue(); 3046 3047 // Ensure that we don't try and inline any type that contains pointers. If 3048 // we inline a value that contains relocations, we move the relocations from 3049 // .data to .text which is not ideal. 3050 auto *Init = GVar->getInitializer(); 3051 if (!isSimpleType(Init->getType())) 3052 return SDValue(); 3053 3054 // The constant islands pass can only really deal with alignment requests 3055 // <= 4 bytes and cannot pad constants itself. Therefore we cannot promote 3056 // any type wanting greater alignment requirements than 4 bytes. We also 3057 // can only promote constants that are multiples of 4 bytes in size or 3058 // are paddable to a multiple of 4. Currently we only try and pad constants 3059 // that are strings for simplicity. 3060 auto *CDAInit = dyn_cast<ConstantDataArray>(Init); 3061 unsigned Size = DAG.getDataLayout().getTypeAllocSize(Init->getType()); 3062 unsigned Align = GVar->getAlignment(); 3063 unsigned RequiredPadding = 4 - (Size % 4); 3064 bool PaddingPossible = 3065 RequiredPadding == 4 || (CDAInit && CDAInit->isString()); 3066 if (!PaddingPossible || Align > 4 || Size > ConstpoolPromotionMaxSize || 3067 Size == 0) 3068 return SDValue(); 3069 3070 unsigned PaddedSize = Size + ((RequiredPadding == 4) ? 0 : RequiredPadding); 3071 MachineFunction &MF = DAG.getMachineFunction(); 3072 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>(); 3073 3074 // We can't bloat the constant pool too much, else the ConstantIslands pass 3075 // may fail to converge. If we haven't promoted this global yet (it may have 3076 // multiple uses), and promoting it would increase the constant pool size (Sz 3077 // > 4), ensure we have space to do so up to MaxTotal. 3078 if (!AFI->getGlobalsPromotedToConstantPool().count(GVar) && Size > 4) 3079 if (AFI->getPromotedConstpoolIncrease() + PaddedSize - 4 >= 3080 ConstpoolPromotionMaxTotal) 3081 return SDValue(); 3082 3083 // This is only valid if all users are in a single function OR it has users 3084 // in multiple functions but it no larger than a pointer. We also check if 3085 // GVar has constant (non-ConstantExpr) users. If so, it essentially has its 3086 // address taken. 3087 if (!allUsersAreInFunction(GVar, F) && 3088 !(Size <= 4 && allUsersAreInFunctions(GVar))) 3089 return SDValue(); 3090 3091 // We're going to inline this global. Pad it out if needed. 3092 if (RequiredPadding != 4) { 3093 StringRef S = CDAInit->getAsString(); 3094 3095 SmallVector<uint8_t,16> V(S.size()); 3096 std::copy(S.bytes_begin(), S.bytes_end(), V.begin()); 3097 while (RequiredPadding--) 3098 V.push_back(0); 3099 Init = ConstantDataArray::get(*DAG.getContext(), V); 3100 } 3101 3102 auto CPVal = ARMConstantPoolConstant::Create(GVar, Init); 3103 SDValue CPAddr = 3104 DAG.getTargetConstantPool(CPVal, PtrVT, /*Align=*/4); 3105 if (!AFI->getGlobalsPromotedToConstantPool().count(GVar)) { 3106 AFI->markGlobalAsPromotedToConstantPool(GVar); 3107 AFI->setPromotedConstpoolIncrease(AFI->getPromotedConstpoolIncrease() + 3108 PaddedSize - 4); 3109 } 3110 ++NumConstpoolPromoted; 3111 return DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr); 3112 } 3113 3114 static bool isReadOnly(const GlobalValue *GV) { 3115 if (const GlobalAlias *GA = dyn_cast<GlobalAlias>(GV)) 3116 GV = GA->getBaseObject(); 3117 return (isa<GlobalVariable>(GV) && cast<GlobalVariable>(GV)->isConstant()) || 3118 isa<Function>(GV); 3119 } 3120 3121 SDValue ARMTargetLowering::LowerGlobalAddressELF(SDValue Op, 3122 SelectionDAG &DAG) const { 3123 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 3124 SDLoc dl(Op); 3125 const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal(); 3126 const TargetMachine &TM = getTargetMachine(); 3127 bool IsRO = isReadOnly(GV); 3128 3129 // promoteToConstantPool only if not generating XO text section 3130 if (TM.shouldAssumeDSOLocal(*GV->getParent(), GV) && !Subtarget->genExecuteOnly()) 3131 if (SDValue V = promoteToConstantPool(GV, DAG, PtrVT, dl)) 3132 return V; 3133 3134 if (isPositionIndependent()) { 3135 bool UseGOT_PREL = !TM.shouldAssumeDSOLocal(*GV->getParent(), GV); 3136 3137 MachineFunction &MF = DAG.getMachineFunction(); 3138 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>(); 3139 unsigned ARMPCLabelIndex = AFI->createPICLabelUId(); 3140 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 3141 SDLoc dl(Op); 3142 unsigned PCAdj = Subtarget->isThumb() ? 4 : 8; 3143 ARMConstantPoolValue *CPV = ARMConstantPoolConstant::Create( 3144 GV, ARMPCLabelIndex, ARMCP::CPValue, PCAdj, 3145 UseGOT_PREL ? ARMCP::GOT_PREL : ARMCP::no_modifier, 3146 /*AddCurrentAddress=*/UseGOT_PREL); 3147 SDValue CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4); 3148 CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr); 3149 SDValue Result = DAG.getLoad( 3150 PtrVT, dl, DAG.getEntryNode(), CPAddr, 3151 MachinePointerInfo::getConstantPool(DAG.getMachineFunction())); 3152 SDValue Chain = Result.getValue(1); 3153 SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, dl, MVT::i32); 3154 Result = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Result, PICLabel); 3155 if (UseGOT_PREL) 3156 Result = 3157 DAG.getLoad(PtrVT, dl, Chain, Result, 3158 MachinePointerInfo::getGOT(DAG.getMachineFunction())); 3159 return Result; 3160 } else if (Subtarget->isROPI() && IsRO) { 3161 // PC-relative. 3162 SDValue G = DAG.getTargetGlobalAddress(GV, dl, PtrVT); 3163 SDValue Result = DAG.getNode(ARMISD::WrapperPIC, dl, PtrVT, G); 3164 return Result; 3165 } else if (Subtarget->isRWPI() && !IsRO) { 3166 // SB-relative. 3167 SDValue RelAddr; 3168 if (Subtarget->useMovt(DAG.getMachineFunction())) { 3169 ++NumMovwMovt; 3170 SDValue G = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, ARMII::MO_SBREL); 3171 RelAddr = DAG.getNode(ARMISD::Wrapper, dl, PtrVT, G); 3172 } else { // use literal pool for address constant 3173 ARMConstantPoolValue *CPV = 3174 ARMConstantPoolConstant::Create(GV, ARMCP::SBREL); 3175 SDValue CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4); 3176 CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr); 3177 RelAddr = DAG.getLoad( 3178 PtrVT, dl, DAG.getEntryNode(), CPAddr, 3179 MachinePointerInfo::getConstantPool(DAG.getMachineFunction())); 3180 } 3181 SDValue SB = DAG.getCopyFromReg(DAG.getEntryNode(), dl, ARM::R9, PtrVT); 3182 SDValue Result = DAG.getNode(ISD::ADD, dl, PtrVT, SB, RelAddr); 3183 return Result; 3184 } 3185 3186 // If we have T2 ops, we can materialize the address directly via movt/movw 3187 // pair. This is always cheaper. 3188 if (Subtarget->useMovt(DAG.getMachineFunction())) { 3189 ++NumMovwMovt; 3190 // FIXME: Once remat is capable of dealing with instructions with register 3191 // operands, expand this into two nodes. 3192 return DAG.getNode(ARMISD::Wrapper, dl, PtrVT, 3193 DAG.getTargetGlobalAddress(GV, dl, PtrVT)); 3194 } else { 3195 SDValue CPAddr = DAG.getTargetConstantPool(GV, PtrVT, 4); 3196 CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr); 3197 return DAG.getLoad( 3198 PtrVT, dl, DAG.getEntryNode(), CPAddr, 3199 MachinePointerInfo::getConstantPool(DAG.getMachineFunction())); 3200 } 3201 } 3202 3203 SDValue ARMTargetLowering::LowerGlobalAddressDarwin(SDValue Op, 3204 SelectionDAG &DAG) const { 3205 assert(!Subtarget->isROPI() && !Subtarget->isRWPI() && 3206 "ROPI/RWPI not currently supported for Darwin"); 3207 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 3208 SDLoc dl(Op); 3209 const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal(); 3210 3211 if (Subtarget->useMovt(DAG.getMachineFunction())) 3212 ++NumMovwMovt; 3213 3214 // FIXME: Once remat is capable of dealing with instructions with register 3215 // operands, expand this into multiple nodes 3216 unsigned Wrapper = 3217 isPositionIndependent() ? ARMISD::WrapperPIC : ARMISD::Wrapper; 3218 3219 SDValue G = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, ARMII::MO_NONLAZY); 3220 SDValue Result = DAG.getNode(Wrapper, dl, PtrVT, G); 3221 3222 if (Subtarget->isGVIndirectSymbol(GV)) 3223 Result = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Result, 3224 MachinePointerInfo::getGOT(DAG.getMachineFunction())); 3225 return Result; 3226 } 3227 3228 SDValue ARMTargetLowering::LowerGlobalAddressWindows(SDValue Op, 3229 SelectionDAG &DAG) const { 3230 assert(Subtarget->isTargetWindows() && "non-Windows COFF is not supported"); 3231 assert(Subtarget->useMovt(DAG.getMachineFunction()) && 3232 "Windows on ARM expects to use movw/movt"); 3233 assert(!Subtarget->isROPI() && !Subtarget->isRWPI() && 3234 "ROPI/RWPI not currently supported for Windows"); 3235 3236 const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal(); 3237 const ARMII::TOF TargetFlags = 3238 (GV->hasDLLImportStorageClass() ? ARMII::MO_DLLIMPORT : ARMII::MO_NO_FLAG); 3239 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 3240 SDValue Result; 3241 SDLoc DL(Op); 3242 3243 ++NumMovwMovt; 3244 3245 // FIXME: Once remat is capable of dealing with instructions with register 3246 // operands, expand this into two nodes. 3247 Result = DAG.getNode(ARMISD::Wrapper, DL, PtrVT, 3248 DAG.getTargetGlobalAddress(GV, DL, PtrVT, /*Offset=*/0, 3249 TargetFlags)); 3250 if (GV->hasDLLImportStorageClass()) 3251 Result = DAG.getLoad(PtrVT, DL, DAG.getEntryNode(), Result, 3252 MachinePointerInfo::getGOT(DAG.getMachineFunction())); 3253 return Result; 3254 } 3255 3256 SDValue 3257 ARMTargetLowering::LowerEH_SJLJ_SETJMP(SDValue Op, SelectionDAG &DAG) const { 3258 SDLoc dl(Op); 3259 SDValue Val = DAG.getConstant(0, dl, MVT::i32); 3260 return DAG.getNode(ARMISD::EH_SJLJ_SETJMP, dl, 3261 DAG.getVTList(MVT::i32, MVT::Other), Op.getOperand(0), 3262 Op.getOperand(1), Val); 3263 } 3264 3265 SDValue 3266 ARMTargetLowering::LowerEH_SJLJ_LONGJMP(SDValue Op, SelectionDAG &DAG) const { 3267 SDLoc dl(Op); 3268 return DAG.getNode(ARMISD::EH_SJLJ_LONGJMP, dl, MVT::Other, Op.getOperand(0), 3269 Op.getOperand(1), DAG.getConstant(0, dl, MVT::i32)); 3270 } 3271 3272 SDValue ARMTargetLowering::LowerEH_SJLJ_SETUP_DISPATCH(SDValue Op, 3273 SelectionDAG &DAG) const { 3274 SDLoc dl(Op); 3275 return DAG.getNode(ARMISD::EH_SJLJ_SETUP_DISPATCH, dl, MVT::Other, 3276 Op.getOperand(0)); 3277 } 3278 3279 SDValue 3280 ARMTargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op, SelectionDAG &DAG, 3281 const ARMSubtarget *Subtarget) const { 3282 unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue(); 3283 SDLoc dl(Op); 3284 switch (IntNo) { 3285 default: return SDValue(); // Don't custom lower most intrinsics. 3286 case Intrinsic::thread_pointer: { 3287 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 3288 return DAG.getNode(ARMISD::THREAD_POINTER, dl, PtrVT); 3289 } 3290 case Intrinsic::eh_sjlj_lsda: { 3291 MachineFunction &MF = DAG.getMachineFunction(); 3292 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>(); 3293 unsigned ARMPCLabelIndex = AFI->createPICLabelUId(); 3294 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 3295 SDValue CPAddr; 3296 bool IsPositionIndependent = isPositionIndependent(); 3297 unsigned PCAdj = IsPositionIndependent ? (Subtarget->isThumb() ? 4 : 8) : 0; 3298 ARMConstantPoolValue *CPV = 3299 ARMConstantPoolConstant::Create(MF.getFunction(), ARMPCLabelIndex, 3300 ARMCP::CPLSDA, PCAdj); 3301 CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4); 3302 CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr); 3303 SDValue Result = DAG.getLoad( 3304 PtrVT, dl, DAG.getEntryNode(), CPAddr, 3305 MachinePointerInfo::getConstantPool(DAG.getMachineFunction())); 3306 3307 if (IsPositionIndependent) { 3308 SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, dl, MVT::i32); 3309 Result = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Result, PICLabel); 3310 } 3311 return Result; 3312 } 3313 case Intrinsic::arm_neon_vmulls: 3314 case Intrinsic::arm_neon_vmullu: { 3315 unsigned NewOpc = (IntNo == Intrinsic::arm_neon_vmulls) 3316 ? ARMISD::VMULLs : ARMISD::VMULLu; 3317 return DAG.getNode(NewOpc, SDLoc(Op), Op.getValueType(), 3318 Op.getOperand(1), Op.getOperand(2)); 3319 } 3320 case Intrinsic::arm_neon_vminnm: 3321 case Intrinsic::arm_neon_vmaxnm: { 3322 unsigned NewOpc = (IntNo == Intrinsic::arm_neon_vminnm) 3323 ? ISD::FMINNUM : ISD::FMAXNUM; 3324 return DAG.getNode(NewOpc, SDLoc(Op), Op.getValueType(), 3325 Op.getOperand(1), Op.getOperand(2)); 3326 } 3327 case Intrinsic::arm_neon_vminu: 3328 case Intrinsic::arm_neon_vmaxu: { 3329 if (Op.getValueType().isFloatingPoint()) 3330 return SDValue(); 3331 unsigned NewOpc = (IntNo == Intrinsic::arm_neon_vminu) 3332 ? ISD::UMIN : ISD::UMAX; 3333 return DAG.getNode(NewOpc, SDLoc(Op), Op.getValueType(), 3334 Op.getOperand(1), Op.getOperand(2)); 3335 } 3336 case Intrinsic::arm_neon_vmins: 3337 case Intrinsic::arm_neon_vmaxs: { 3338 // v{min,max}s is overloaded between signed integers and floats. 3339 if (!Op.getValueType().isFloatingPoint()) { 3340 unsigned NewOpc = (IntNo == Intrinsic::arm_neon_vmins) 3341 ? ISD::SMIN : ISD::SMAX; 3342 return DAG.getNode(NewOpc, SDLoc(Op), Op.getValueType(), 3343 Op.getOperand(1), Op.getOperand(2)); 3344 } 3345 unsigned NewOpc = (IntNo == Intrinsic::arm_neon_vmins) 3346 ? ISD::FMINNAN : ISD::FMAXNAN; 3347 return DAG.getNode(NewOpc, SDLoc(Op), Op.getValueType(), 3348 Op.getOperand(1), Op.getOperand(2)); 3349 } 3350 } 3351 } 3352 3353 static SDValue LowerATOMIC_FENCE(SDValue Op, SelectionDAG &DAG, 3354 const ARMSubtarget *Subtarget) { 3355 // FIXME: handle "fence singlethread" more efficiently. 3356 SDLoc dl(Op); 3357 if (!Subtarget->hasDataBarrier()) { 3358 // Some ARMv6 cpus can support data barriers with an mcr instruction. 3359 // Thumb1 and pre-v6 ARM mode use a libcall instead and should never get 3360 // here. 3361 assert(Subtarget->hasV6Ops() && !Subtarget->isThumb() && 3362 "Unexpected ISD::ATOMIC_FENCE encountered. Should be libcall!"); 3363 return DAG.getNode(ARMISD::MEMBARRIER_MCR, dl, MVT::Other, Op.getOperand(0), 3364 DAG.getConstant(0, dl, MVT::i32)); 3365 } 3366 3367 ConstantSDNode *OrdN = cast<ConstantSDNode>(Op.getOperand(1)); 3368 AtomicOrdering Ord = static_cast<AtomicOrdering>(OrdN->getZExtValue()); 3369 ARM_MB::MemBOpt Domain = ARM_MB::ISH; 3370 if (Subtarget->isMClass()) { 3371 // Only a full system barrier exists in the M-class architectures. 3372 Domain = ARM_MB::SY; 3373 } else if (Subtarget->preferISHSTBarriers() && 3374 Ord == AtomicOrdering::Release) { 3375 // Swift happens to implement ISHST barriers in a way that's compatible with 3376 // Release semantics but weaker than ISH so we'd be fools not to use 3377 // it. Beware: other processors probably don't! 3378 Domain = ARM_MB::ISHST; 3379 } 3380 3381 return DAG.getNode(ISD::INTRINSIC_VOID, dl, MVT::Other, Op.getOperand(0), 3382 DAG.getConstant(Intrinsic::arm_dmb, dl, MVT::i32), 3383 DAG.getConstant(Domain, dl, MVT::i32)); 3384 } 3385 3386 static SDValue LowerPREFETCH(SDValue Op, SelectionDAG &DAG, 3387 const ARMSubtarget *Subtarget) { 3388 // ARM pre v5TE and Thumb1 does not have preload instructions. 3389 if (!(Subtarget->isThumb2() || 3390 (!Subtarget->isThumb1Only() && Subtarget->hasV5TEOps()))) 3391 // Just preserve the chain. 3392 return Op.getOperand(0); 3393 3394 SDLoc dl(Op); 3395 unsigned isRead = ~cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue() & 1; 3396 if (!isRead && 3397 (!Subtarget->hasV7Ops() || !Subtarget->hasMPExtension())) 3398 // ARMv7 with MP extension has PLDW. 3399 return Op.getOperand(0); 3400 3401 unsigned isData = cast<ConstantSDNode>(Op.getOperand(4))->getZExtValue(); 3402 if (Subtarget->isThumb()) { 3403 // Invert the bits. 3404 isRead = ~isRead & 1; 3405 isData = ~isData & 1; 3406 } 3407 3408 return DAG.getNode(ARMISD::PRELOAD, dl, MVT::Other, Op.getOperand(0), 3409 Op.getOperand(1), DAG.getConstant(isRead, dl, MVT::i32), 3410 DAG.getConstant(isData, dl, MVT::i32)); 3411 } 3412 3413 static SDValue LowerVASTART(SDValue Op, SelectionDAG &DAG) { 3414 MachineFunction &MF = DAG.getMachineFunction(); 3415 ARMFunctionInfo *FuncInfo = MF.getInfo<ARMFunctionInfo>(); 3416 3417 // vastart just stores the address of the VarArgsFrameIndex slot into the 3418 // memory location argument. 3419 SDLoc dl(Op); 3420 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout()); 3421 SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT); 3422 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue(); 3423 return DAG.getStore(Op.getOperand(0), dl, FR, Op.getOperand(1), 3424 MachinePointerInfo(SV)); 3425 } 3426 3427 SDValue ARMTargetLowering::GetF64FormalArgument(CCValAssign &VA, 3428 CCValAssign &NextVA, 3429 SDValue &Root, 3430 SelectionDAG &DAG, 3431 const SDLoc &dl) const { 3432 MachineFunction &MF = DAG.getMachineFunction(); 3433 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>(); 3434 3435 const TargetRegisterClass *RC; 3436 if (AFI->isThumb1OnlyFunction()) 3437 RC = &ARM::tGPRRegClass; 3438 else 3439 RC = &ARM::GPRRegClass; 3440 3441 // Transform the arguments stored in physical registers into virtual ones. 3442 unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC); 3443 SDValue ArgValue = DAG.getCopyFromReg(Root, dl, Reg, MVT::i32); 3444 3445 SDValue ArgValue2; 3446 if (NextVA.isMemLoc()) { 3447 MachineFrameInfo &MFI = MF.getFrameInfo(); 3448 int FI = MFI.CreateFixedObject(4, NextVA.getLocMemOffset(), true); 3449 3450 // Create load node to retrieve arguments from the stack. 3451 SDValue FIN = DAG.getFrameIndex(FI, getPointerTy(DAG.getDataLayout())); 3452 ArgValue2 = DAG.getLoad( 3453 MVT::i32, dl, Root, FIN, 3454 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI)); 3455 } else { 3456 Reg = MF.addLiveIn(NextVA.getLocReg(), RC); 3457 ArgValue2 = DAG.getCopyFromReg(Root, dl, Reg, MVT::i32); 3458 } 3459 if (!Subtarget->isLittle()) 3460 std::swap (ArgValue, ArgValue2); 3461 return DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, ArgValue, ArgValue2); 3462 } 3463 3464 // The remaining GPRs hold either the beginning of variable-argument 3465 // data, or the beginning of an aggregate passed by value (usually 3466 // byval). Either way, we allocate stack slots adjacent to the data 3467 // provided by our caller, and store the unallocated registers there. 3468 // If this is a variadic function, the va_list pointer will begin with 3469 // these values; otherwise, this reassembles a (byval) structure that 3470 // was split between registers and memory. 3471 // Return: The frame index registers were stored into. 3472 int ARMTargetLowering::StoreByValRegs(CCState &CCInfo, SelectionDAG &DAG, 3473 const SDLoc &dl, SDValue &Chain, 3474 const Value *OrigArg, 3475 unsigned InRegsParamRecordIdx, 3476 int ArgOffset, unsigned ArgSize) const { 3477 // Currently, two use-cases possible: 3478 // Case #1. Non-var-args function, and we meet first byval parameter. 3479 // Setup first unallocated register as first byval register; 3480 // eat all remained registers 3481 // (these two actions are performed by HandleByVal method). 3482 // Then, here, we initialize stack frame with 3483 // "store-reg" instructions. 3484 // Case #2. Var-args function, that doesn't contain byval parameters. 3485 // The same: eat all remained unallocated registers, 3486 // initialize stack frame. 3487 3488 MachineFunction &MF = DAG.getMachineFunction(); 3489 MachineFrameInfo &MFI = MF.getFrameInfo(); 3490 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>(); 3491 unsigned RBegin, REnd; 3492 if (InRegsParamRecordIdx < CCInfo.getInRegsParamsCount()) { 3493 CCInfo.getInRegsParamInfo(InRegsParamRecordIdx, RBegin, REnd); 3494 } else { 3495 unsigned RBeginIdx = CCInfo.getFirstUnallocated(GPRArgRegs); 3496 RBegin = RBeginIdx == 4 ? (unsigned)ARM::R4 : GPRArgRegs[RBeginIdx]; 3497 REnd = ARM::R4; 3498 } 3499 3500 if (REnd != RBegin) 3501 ArgOffset = -4 * (ARM::R4 - RBegin); 3502 3503 auto PtrVT = getPointerTy(DAG.getDataLayout()); 3504 int FrameIndex = MFI.CreateFixedObject(ArgSize, ArgOffset, false); 3505 SDValue FIN = DAG.getFrameIndex(FrameIndex, PtrVT); 3506 3507 SmallVector<SDValue, 4> MemOps; 3508 const TargetRegisterClass *RC = 3509 AFI->isThumb1OnlyFunction() ? &ARM::tGPRRegClass : &ARM::GPRRegClass; 3510 3511 for (unsigned Reg = RBegin, i = 0; Reg < REnd; ++Reg, ++i) { 3512 unsigned VReg = MF.addLiveIn(Reg, RC); 3513 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i32); 3514 SDValue Store = DAG.getStore(Val.getValue(1), dl, Val, FIN, 3515 MachinePointerInfo(OrigArg, 4 * i)); 3516 MemOps.push_back(Store); 3517 FIN = DAG.getNode(ISD::ADD, dl, PtrVT, FIN, DAG.getConstant(4, dl, PtrVT)); 3518 } 3519 3520 if (!MemOps.empty()) 3521 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOps); 3522 return FrameIndex; 3523 } 3524 3525 // Setup stack frame, the va_list pointer will start from. 3526 void ARMTargetLowering::VarArgStyleRegisters(CCState &CCInfo, SelectionDAG &DAG, 3527 const SDLoc &dl, SDValue &Chain, 3528 unsigned ArgOffset, 3529 unsigned TotalArgRegsSaveSize, 3530 bool ForceMutable) const { 3531 MachineFunction &MF = DAG.getMachineFunction(); 3532 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>(); 3533 3534 // Try to store any remaining integer argument regs 3535 // to their spots on the stack so that they may be loaded by dereferencing 3536 // the result of va_next. 3537 // If there is no regs to be stored, just point address after last 3538 // argument passed via stack. 3539 int FrameIndex = StoreByValRegs(CCInfo, DAG, dl, Chain, nullptr, 3540 CCInfo.getInRegsParamsCount(), 3541 CCInfo.getNextStackOffset(), 4); 3542 AFI->setVarArgsFrameIndex(FrameIndex); 3543 } 3544 3545 SDValue ARMTargetLowering::LowerFormalArguments( 3546 SDValue Chain, CallingConv::ID CallConv, bool isVarArg, 3547 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl, 3548 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const { 3549 MachineFunction &MF = DAG.getMachineFunction(); 3550 MachineFrameInfo &MFI = MF.getFrameInfo(); 3551 3552 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>(); 3553 3554 // Assign locations to all of the incoming arguments. 3555 SmallVector<CCValAssign, 16> ArgLocs; 3556 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), ArgLocs, 3557 *DAG.getContext()); 3558 CCInfo.AnalyzeFormalArguments(Ins, CCAssignFnForCall(CallConv, isVarArg)); 3559 3560 SmallVector<SDValue, 16> ArgValues; 3561 SDValue ArgValue; 3562 Function::const_arg_iterator CurOrigArg = MF.getFunction()->arg_begin(); 3563 unsigned CurArgIdx = 0; 3564 3565 // Initially ArgRegsSaveSize is zero. 3566 // Then we increase this value each time we meet byval parameter. 3567 // We also increase this value in case of varargs function. 3568 AFI->setArgRegsSaveSize(0); 3569 3570 // Calculate the amount of stack space that we need to allocate to store 3571 // byval and variadic arguments that are passed in registers. 3572 // We need to know this before we allocate the first byval or variadic 3573 // argument, as they will be allocated a stack slot below the CFA (Canonical 3574 // Frame Address, the stack pointer at entry to the function). 3575 unsigned ArgRegBegin = ARM::R4; 3576 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) { 3577 if (CCInfo.getInRegsParamsProcessed() >= CCInfo.getInRegsParamsCount()) 3578 break; 3579 3580 CCValAssign &VA = ArgLocs[i]; 3581 unsigned Index = VA.getValNo(); 3582 ISD::ArgFlagsTy Flags = Ins[Index].Flags; 3583 if (!Flags.isByVal()) 3584 continue; 3585 3586 assert(VA.isMemLoc() && "unexpected byval pointer in reg"); 3587 unsigned RBegin, REnd; 3588 CCInfo.getInRegsParamInfo(CCInfo.getInRegsParamsProcessed(), RBegin, REnd); 3589 ArgRegBegin = std::min(ArgRegBegin, RBegin); 3590 3591 CCInfo.nextInRegsParam(); 3592 } 3593 CCInfo.rewindByValRegsInfo(); 3594 3595 int lastInsIndex = -1; 3596 if (isVarArg && MFI.hasVAStart()) { 3597 unsigned RegIdx = CCInfo.getFirstUnallocated(GPRArgRegs); 3598 if (RegIdx != array_lengthof(GPRArgRegs)) 3599 ArgRegBegin = std::min(ArgRegBegin, (unsigned)GPRArgRegs[RegIdx]); 3600 } 3601 3602 unsigned TotalArgRegsSaveSize = 4 * (ARM::R4 - ArgRegBegin); 3603 AFI->setArgRegsSaveSize(TotalArgRegsSaveSize); 3604 auto PtrVT = getPointerTy(DAG.getDataLayout()); 3605 3606 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) { 3607 CCValAssign &VA = ArgLocs[i]; 3608 if (Ins[VA.getValNo()].isOrigArg()) { 3609 std::advance(CurOrigArg, 3610 Ins[VA.getValNo()].getOrigArgIndex() - CurArgIdx); 3611 CurArgIdx = Ins[VA.getValNo()].getOrigArgIndex(); 3612 } 3613 // Arguments stored in registers. 3614 if (VA.isRegLoc()) { 3615 EVT RegVT = VA.getLocVT(); 3616 3617 if (VA.needsCustom()) { 3618 // f64 and vector types are split up into multiple registers or 3619 // combinations of registers and stack slots. 3620 if (VA.getLocVT() == MVT::v2f64) { 3621 SDValue ArgValue1 = GetF64FormalArgument(VA, ArgLocs[++i], 3622 Chain, DAG, dl); 3623 VA = ArgLocs[++i]; // skip ahead to next loc 3624 SDValue ArgValue2; 3625 if (VA.isMemLoc()) { 3626 int FI = MFI.CreateFixedObject(8, VA.getLocMemOffset(), true); 3627 SDValue FIN = DAG.getFrameIndex(FI, PtrVT); 3628 ArgValue2 = DAG.getLoad(MVT::f64, dl, Chain, FIN, 3629 MachinePointerInfo::getFixedStack( 3630 DAG.getMachineFunction(), FI)); 3631 } else { 3632 ArgValue2 = GetF64FormalArgument(VA, ArgLocs[++i], 3633 Chain, DAG, dl); 3634 } 3635 ArgValue = DAG.getNode(ISD::UNDEF, dl, MVT::v2f64); 3636 ArgValue = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, 3637 ArgValue, ArgValue1, 3638 DAG.getIntPtrConstant(0, dl)); 3639 ArgValue = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, 3640 ArgValue, ArgValue2, 3641 DAG.getIntPtrConstant(1, dl)); 3642 } else 3643 ArgValue = GetF64FormalArgument(VA, ArgLocs[++i], Chain, DAG, dl); 3644 3645 } else { 3646 const TargetRegisterClass *RC; 3647 3648 if (RegVT == MVT::f32) 3649 RC = &ARM::SPRRegClass; 3650 else if (RegVT == MVT::f64) 3651 RC = &ARM::DPRRegClass; 3652 else if (RegVT == MVT::v2f64) 3653 RC = &ARM::QPRRegClass; 3654 else if (RegVT == MVT::i32) 3655 RC = AFI->isThumb1OnlyFunction() ? &ARM::tGPRRegClass 3656 : &ARM::GPRRegClass; 3657 else 3658 llvm_unreachable("RegVT not supported by FORMAL_ARGUMENTS Lowering"); 3659 3660 // Transform the arguments in physical registers into virtual ones. 3661 unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC); 3662 ArgValue = DAG.getCopyFromReg(Chain, dl, Reg, RegVT); 3663 } 3664 3665 // If this is an 8 or 16-bit value, it is really passed promoted 3666 // to 32 bits. Insert an assert[sz]ext to capture this, then 3667 // truncate to the right size. 3668 switch (VA.getLocInfo()) { 3669 default: llvm_unreachable("Unknown loc info!"); 3670 case CCValAssign::Full: break; 3671 case CCValAssign::BCvt: 3672 ArgValue = DAG.getNode(ISD::BITCAST, dl, VA.getValVT(), ArgValue); 3673 break; 3674 case CCValAssign::SExt: 3675 ArgValue = DAG.getNode(ISD::AssertSext, dl, RegVT, ArgValue, 3676 DAG.getValueType(VA.getValVT())); 3677 ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue); 3678 break; 3679 case CCValAssign::ZExt: 3680 ArgValue = DAG.getNode(ISD::AssertZext, dl, RegVT, ArgValue, 3681 DAG.getValueType(VA.getValVT())); 3682 ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue); 3683 break; 3684 } 3685 3686 InVals.push_back(ArgValue); 3687 3688 } else { // VA.isRegLoc() 3689 // sanity check 3690 assert(VA.isMemLoc()); 3691 assert(VA.getValVT() != MVT::i64 && "i64 should already be lowered"); 3692 3693 int index = VA.getValNo(); 3694 3695 // Some Ins[] entries become multiple ArgLoc[] entries. 3696 // Process them only once. 3697 if (index != lastInsIndex) 3698 { 3699 ISD::ArgFlagsTy Flags = Ins[index].Flags; 3700 // FIXME: For now, all byval parameter objects are marked mutable. 3701 // This can be changed with more analysis. 3702 // In case of tail call optimization mark all arguments mutable. 3703 // Since they could be overwritten by lowering of arguments in case of 3704 // a tail call. 3705 if (Flags.isByVal()) { 3706 assert(Ins[index].isOrigArg() && 3707 "Byval arguments cannot be implicit"); 3708 unsigned CurByValIndex = CCInfo.getInRegsParamsProcessed(); 3709 3710 int FrameIndex = StoreByValRegs( 3711 CCInfo, DAG, dl, Chain, &*CurOrigArg, CurByValIndex, 3712 VA.getLocMemOffset(), Flags.getByValSize()); 3713 InVals.push_back(DAG.getFrameIndex(FrameIndex, PtrVT)); 3714 CCInfo.nextInRegsParam(); 3715 } else { 3716 unsigned FIOffset = VA.getLocMemOffset(); 3717 int FI = MFI.CreateFixedObject(VA.getLocVT().getSizeInBits()/8, 3718 FIOffset, true); 3719 3720 // Create load nodes to retrieve arguments from the stack. 3721 SDValue FIN = DAG.getFrameIndex(FI, PtrVT); 3722 InVals.push_back(DAG.getLoad(VA.getValVT(), dl, Chain, FIN, 3723 MachinePointerInfo::getFixedStack( 3724 DAG.getMachineFunction(), FI))); 3725 } 3726 lastInsIndex = index; 3727 } 3728 } 3729 } 3730 3731 // varargs 3732 if (isVarArg && MFI.hasVAStart()) 3733 VarArgStyleRegisters(CCInfo, DAG, dl, Chain, 3734 CCInfo.getNextStackOffset(), 3735 TotalArgRegsSaveSize); 3736 3737 AFI->setArgumentStackSize(CCInfo.getNextStackOffset()); 3738 3739 return Chain; 3740 } 3741 3742 /// isFloatingPointZero - Return true if this is +0.0. 3743 static bool isFloatingPointZero(SDValue Op) { 3744 if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Op)) 3745 return CFP->getValueAPF().isPosZero(); 3746 else if (ISD::isEXTLoad(Op.getNode()) || ISD::isNON_EXTLoad(Op.getNode())) { 3747 // Maybe this has already been legalized into the constant pool? 3748 if (Op.getOperand(1).getOpcode() == ARMISD::Wrapper) { 3749 SDValue WrapperOp = Op.getOperand(1).getOperand(0); 3750 if (ConstantPoolSDNode *CP = dyn_cast<ConstantPoolSDNode>(WrapperOp)) 3751 if (const ConstantFP *CFP = dyn_cast<ConstantFP>(CP->getConstVal())) 3752 return CFP->getValueAPF().isPosZero(); 3753 } 3754 } else if (Op->getOpcode() == ISD::BITCAST && 3755 Op->getValueType(0) == MVT::f64) { 3756 // Handle (ISD::BITCAST (ARMISD::VMOVIMM (ISD::TargetConstant 0)) MVT::f64) 3757 // created by LowerConstantFP(). 3758 SDValue BitcastOp = Op->getOperand(0); 3759 if (BitcastOp->getOpcode() == ARMISD::VMOVIMM && 3760 isNullConstant(BitcastOp->getOperand(0))) 3761 return true; 3762 } 3763 return false; 3764 } 3765 3766 /// Returns appropriate ARM CMP (cmp) and corresponding condition code for 3767 /// the given operands. 3768 SDValue ARMTargetLowering::getARMCmp(SDValue LHS, SDValue RHS, ISD::CondCode CC, 3769 SDValue &ARMcc, SelectionDAG &DAG, 3770 const SDLoc &dl) const { 3771 if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS.getNode())) { 3772 unsigned C = RHSC->getZExtValue(); 3773 if (!isLegalICmpImmediate(C)) { 3774 // Constant does not fit, try adjusting it by one? 3775 switch (CC) { 3776 default: break; 3777 case ISD::SETLT: 3778 case ISD::SETGE: 3779 if (C != 0x80000000 && isLegalICmpImmediate(C-1)) { 3780 CC = (CC == ISD::SETLT) ? ISD::SETLE : ISD::SETGT; 3781 RHS = DAG.getConstant(C - 1, dl, MVT::i32); 3782 } 3783 break; 3784 case ISD::SETULT: 3785 case ISD::SETUGE: 3786 if (C != 0 && isLegalICmpImmediate(C-1)) { 3787 CC = (CC == ISD::SETULT) ? ISD::SETULE : ISD::SETUGT; 3788 RHS = DAG.getConstant(C - 1, dl, MVT::i32); 3789 } 3790 break; 3791 case ISD::SETLE: 3792 case ISD::SETGT: 3793 if (C != 0x7fffffff && isLegalICmpImmediate(C+1)) { 3794 CC = (CC == ISD::SETLE) ? ISD::SETLT : ISD::SETGE; 3795 RHS = DAG.getConstant(C + 1, dl, MVT::i32); 3796 } 3797 break; 3798 case ISD::SETULE: 3799 case ISD::SETUGT: 3800 if (C != 0xffffffff && isLegalICmpImmediate(C+1)) { 3801 CC = (CC == ISD::SETULE) ? ISD::SETULT : ISD::SETUGE; 3802 RHS = DAG.getConstant(C + 1, dl, MVT::i32); 3803 } 3804 break; 3805 } 3806 } 3807 } 3808 3809 ARMCC::CondCodes CondCode = IntCCToARMCC(CC); 3810 ARMISD::NodeType CompareType; 3811 switch (CondCode) { 3812 default: 3813 CompareType = ARMISD::CMP; 3814 break; 3815 case ARMCC::EQ: 3816 case ARMCC::NE: 3817 // Uses only Z Flag 3818 CompareType = ARMISD::CMPZ; 3819 break; 3820 } 3821 ARMcc = DAG.getConstant(CondCode, dl, MVT::i32); 3822 return DAG.getNode(CompareType, dl, MVT::Glue, LHS, RHS); 3823 } 3824 3825 /// Returns a appropriate VFP CMP (fcmp{s|d}+fmstat) for the given operands. 3826 SDValue ARMTargetLowering::getVFPCmp(SDValue LHS, SDValue RHS, 3827 SelectionDAG &DAG, const SDLoc &dl, 3828 bool InvalidOnQNaN) const { 3829 assert(!Subtarget->isFPOnlySP() || RHS.getValueType() != MVT::f64); 3830 SDValue Cmp; 3831 SDValue C = DAG.getConstant(InvalidOnQNaN, dl, MVT::i32); 3832 if (!isFloatingPointZero(RHS)) 3833 Cmp = DAG.getNode(ARMISD::CMPFP, dl, MVT::Glue, LHS, RHS, C); 3834 else 3835 Cmp = DAG.getNode(ARMISD::CMPFPw0, dl, MVT::Glue, LHS, C); 3836 return DAG.getNode(ARMISD::FMSTAT, dl, MVT::Glue, Cmp); 3837 } 3838 3839 /// duplicateCmp - Glue values can have only one use, so this function 3840 /// duplicates a comparison node. 3841 SDValue 3842 ARMTargetLowering::duplicateCmp(SDValue Cmp, SelectionDAG &DAG) const { 3843 unsigned Opc = Cmp.getOpcode(); 3844 SDLoc DL(Cmp); 3845 if (Opc == ARMISD::CMP || Opc == ARMISD::CMPZ) 3846 return DAG.getNode(Opc, DL, MVT::Glue, Cmp.getOperand(0),Cmp.getOperand(1)); 3847 3848 assert(Opc == ARMISD::FMSTAT && "unexpected comparison operation"); 3849 Cmp = Cmp.getOperand(0); 3850 Opc = Cmp.getOpcode(); 3851 if (Opc == ARMISD::CMPFP) 3852 Cmp = DAG.getNode(Opc, DL, MVT::Glue, Cmp.getOperand(0), 3853 Cmp.getOperand(1), Cmp.getOperand(2)); 3854 else { 3855 assert(Opc == ARMISD::CMPFPw0 && "unexpected operand of FMSTAT"); 3856 Cmp = DAG.getNode(Opc, DL, MVT::Glue, Cmp.getOperand(0), 3857 Cmp.getOperand(1)); 3858 } 3859 return DAG.getNode(ARMISD::FMSTAT, DL, MVT::Glue, Cmp); 3860 } 3861 3862 std::pair<SDValue, SDValue> 3863 ARMTargetLowering::getARMXALUOOp(SDValue Op, SelectionDAG &DAG, 3864 SDValue &ARMcc) const { 3865 assert(Op.getValueType() == MVT::i32 && "Unsupported value type"); 3866 3867 SDValue Value, OverflowCmp; 3868 SDValue LHS = Op.getOperand(0); 3869 SDValue RHS = Op.getOperand(1); 3870 SDLoc dl(Op); 3871 3872 // FIXME: We are currently always generating CMPs because we don't support 3873 // generating CMN through the backend. This is not as good as the natural 3874 // CMP case because it causes a register dependency and cannot be folded 3875 // later. 3876 3877 switch (Op.getOpcode()) { 3878 default: 3879 llvm_unreachable("Unknown overflow instruction!"); 3880 case ISD::SADDO: 3881 ARMcc = DAG.getConstant(ARMCC::VC, dl, MVT::i32); 3882 Value = DAG.getNode(ISD::ADD, dl, Op.getValueType(), LHS, RHS); 3883 OverflowCmp = DAG.getNode(ARMISD::CMP, dl, MVT::Glue, Value, LHS); 3884 break; 3885 case ISD::UADDO: 3886 ARMcc = DAG.getConstant(ARMCC::HS, dl, MVT::i32); 3887 Value = DAG.getNode(ISD::ADD, dl, Op.getValueType(), LHS, RHS); 3888 OverflowCmp = DAG.getNode(ARMISD::CMP, dl, MVT::Glue, Value, LHS); 3889 break; 3890 case ISD::SSUBO: 3891 ARMcc = DAG.getConstant(ARMCC::VC, dl, MVT::i32); 3892 Value = DAG.getNode(ISD::SUB, dl, Op.getValueType(), LHS, RHS); 3893 OverflowCmp = DAG.getNode(ARMISD::CMP, dl, MVT::Glue, LHS, RHS); 3894 break; 3895 case ISD::USUBO: 3896 ARMcc = DAG.getConstant(ARMCC::HS, dl, MVT::i32); 3897 Value = DAG.getNode(ISD::SUB, dl, Op.getValueType(), LHS, RHS); 3898 OverflowCmp = DAG.getNode(ARMISD::CMP, dl, MVT::Glue, LHS, RHS); 3899 break; 3900 } // switch (...) 3901 3902 return std::make_pair(Value, OverflowCmp); 3903 } 3904 3905 SDValue 3906 ARMTargetLowering::LowerXALUO(SDValue Op, SelectionDAG &DAG) const { 3907 // Let legalize expand this if it isn't a legal type yet. 3908 if (!DAG.getTargetLoweringInfo().isTypeLegal(Op.getValueType())) 3909 return SDValue(); 3910 3911 SDValue Value, OverflowCmp; 3912 SDValue ARMcc; 3913 std::tie(Value, OverflowCmp) = getARMXALUOOp(Op, DAG, ARMcc); 3914 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32); 3915 SDLoc dl(Op); 3916 // We use 0 and 1 as false and true values. 3917 SDValue TVal = DAG.getConstant(1, dl, MVT::i32); 3918 SDValue FVal = DAG.getConstant(0, dl, MVT::i32); 3919 EVT VT = Op.getValueType(); 3920 3921 SDValue Overflow = DAG.getNode(ARMISD::CMOV, dl, VT, TVal, FVal, 3922 ARMcc, CCR, OverflowCmp); 3923 3924 SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32); 3925 return DAG.getNode(ISD::MERGE_VALUES, dl, VTs, Value, Overflow); 3926 } 3927 3928 SDValue ARMTargetLowering::LowerSELECT(SDValue Op, SelectionDAG &DAG) const { 3929 SDValue Cond = Op.getOperand(0); 3930 SDValue SelectTrue = Op.getOperand(1); 3931 SDValue SelectFalse = Op.getOperand(2); 3932 SDLoc dl(Op); 3933 unsigned Opc = Cond.getOpcode(); 3934 3935 if (Cond.getResNo() == 1 && 3936 (Opc == ISD::SADDO || Opc == ISD::UADDO || Opc == ISD::SSUBO || 3937 Opc == ISD::USUBO)) { 3938 if (!DAG.getTargetLoweringInfo().isTypeLegal(Cond->getValueType(0))) 3939 return SDValue(); 3940 3941 SDValue Value, OverflowCmp; 3942 SDValue ARMcc; 3943 std::tie(Value, OverflowCmp) = getARMXALUOOp(Cond, DAG, ARMcc); 3944 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32); 3945 EVT VT = Op.getValueType(); 3946 3947 return getCMOV(dl, VT, SelectTrue, SelectFalse, ARMcc, CCR, 3948 OverflowCmp, DAG); 3949 } 3950 3951 // Convert: 3952 // 3953 // (select (cmov 1, 0, cond), t, f) -> (cmov t, f, cond) 3954 // (select (cmov 0, 1, cond), t, f) -> (cmov f, t, cond) 3955 // 3956 if (Cond.getOpcode() == ARMISD::CMOV && Cond.hasOneUse()) { 3957 const ConstantSDNode *CMOVTrue = 3958 dyn_cast<ConstantSDNode>(Cond.getOperand(0)); 3959 const ConstantSDNode *CMOVFalse = 3960 dyn_cast<ConstantSDNode>(Cond.getOperand(1)); 3961 3962 if (CMOVTrue && CMOVFalse) { 3963 unsigned CMOVTrueVal = CMOVTrue->getZExtValue(); 3964 unsigned CMOVFalseVal = CMOVFalse->getZExtValue(); 3965 3966 SDValue True; 3967 SDValue False; 3968 if (CMOVTrueVal == 1 && CMOVFalseVal == 0) { 3969 True = SelectTrue; 3970 False = SelectFalse; 3971 } else if (CMOVTrueVal == 0 && CMOVFalseVal == 1) { 3972 True = SelectFalse; 3973 False = SelectTrue; 3974 } 3975 3976 if (True.getNode() && False.getNode()) { 3977 EVT VT = Op.getValueType(); 3978 SDValue ARMcc = Cond.getOperand(2); 3979 SDValue CCR = Cond.getOperand(3); 3980 SDValue Cmp = duplicateCmp(Cond.getOperand(4), DAG); 3981 assert(True.getValueType() == VT); 3982 return getCMOV(dl, VT, True, False, ARMcc, CCR, Cmp, DAG); 3983 } 3984 } 3985 } 3986 3987 // ARM's BooleanContents value is UndefinedBooleanContent. Mask out the 3988 // undefined bits before doing a full-word comparison with zero. 3989 Cond = DAG.getNode(ISD::AND, dl, Cond.getValueType(), Cond, 3990 DAG.getConstant(1, dl, Cond.getValueType())); 3991 3992 return DAG.getSelectCC(dl, Cond, 3993 DAG.getConstant(0, dl, Cond.getValueType()), 3994 SelectTrue, SelectFalse, ISD::SETNE); 3995 } 3996 3997 static void checkVSELConstraints(ISD::CondCode CC, ARMCC::CondCodes &CondCode, 3998 bool &swpCmpOps, bool &swpVselOps) { 3999 // Start by selecting the GE condition code for opcodes that return true for 4000 // 'equality' 4001 if (CC == ISD::SETUGE || CC == ISD::SETOGE || CC == ISD::SETOLE || 4002 CC == ISD::SETULE) 4003 CondCode = ARMCC::GE; 4004 4005 // and GT for opcodes that return false for 'equality'. 4006 else if (CC == ISD::SETUGT || CC == ISD::SETOGT || CC == ISD::SETOLT || 4007 CC == ISD::SETULT) 4008 CondCode = ARMCC::GT; 4009 4010 // Since we are constrained to GE/GT, if the opcode contains 'less', we need 4011 // to swap the compare operands. 4012 if (CC == ISD::SETOLE || CC == ISD::SETULE || CC == ISD::SETOLT || 4013 CC == ISD::SETULT) 4014 swpCmpOps = true; 4015 4016 // Both GT and GE are ordered comparisons, and return false for 'unordered'. 4017 // If we have an unordered opcode, we need to swap the operands to the VSEL 4018 // instruction (effectively negating the condition). 4019 // 4020 // This also has the effect of swapping which one of 'less' or 'greater' 4021 // returns true, so we also swap the compare operands. It also switches 4022 // whether we return true for 'equality', so we compensate by picking the 4023 // opposite condition code to our original choice. 4024 if (CC == ISD::SETULE || CC == ISD::SETULT || CC == ISD::SETUGE || 4025 CC == ISD::SETUGT) { 4026 swpCmpOps = !swpCmpOps; 4027 swpVselOps = !swpVselOps; 4028 CondCode = CondCode == ARMCC::GT ? ARMCC::GE : ARMCC::GT; 4029 } 4030 4031 // 'ordered' is 'anything but unordered', so use the VS condition code and 4032 // swap the VSEL operands. 4033 if (CC == ISD::SETO) { 4034 CondCode = ARMCC::VS; 4035 swpVselOps = true; 4036 } 4037 4038 // 'unordered or not equal' is 'anything but equal', so use the EQ condition 4039 // code and swap the VSEL operands. 4040 if (CC == ISD::SETUNE) { 4041 CondCode = ARMCC::EQ; 4042 swpVselOps = true; 4043 } 4044 } 4045 4046 SDValue ARMTargetLowering::getCMOV(const SDLoc &dl, EVT VT, SDValue FalseVal, 4047 SDValue TrueVal, SDValue ARMcc, SDValue CCR, 4048 SDValue Cmp, SelectionDAG &DAG) const { 4049 if (Subtarget->isFPOnlySP() && VT == MVT::f64) { 4050 FalseVal = DAG.getNode(ARMISD::VMOVRRD, dl, 4051 DAG.getVTList(MVT::i32, MVT::i32), FalseVal); 4052 TrueVal = DAG.getNode(ARMISD::VMOVRRD, dl, 4053 DAG.getVTList(MVT::i32, MVT::i32), TrueVal); 4054 4055 SDValue TrueLow = TrueVal.getValue(0); 4056 SDValue TrueHigh = TrueVal.getValue(1); 4057 SDValue FalseLow = FalseVal.getValue(0); 4058 SDValue FalseHigh = FalseVal.getValue(1); 4059 4060 SDValue Low = DAG.getNode(ARMISD::CMOV, dl, MVT::i32, FalseLow, TrueLow, 4061 ARMcc, CCR, Cmp); 4062 SDValue High = DAG.getNode(ARMISD::CMOV, dl, MVT::i32, FalseHigh, TrueHigh, 4063 ARMcc, CCR, duplicateCmp(Cmp, DAG)); 4064 4065 return DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Low, High); 4066 } else { 4067 return DAG.getNode(ARMISD::CMOV, dl, VT, FalseVal, TrueVal, ARMcc, CCR, 4068 Cmp); 4069 } 4070 } 4071 4072 static bool isGTorGE(ISD::CondCode CC) { 4073 return CC == ISD::SETGT || CC == ISD::SETGE; 4074 } 4075 4076 static bool isLTorLE(ISD::CondCode CC) { 4077 return CC == ISD::SETLT || CC == ISD::SETLE; 4078 } 4079 4080 // See if a conditional (LHS CC RHS ? TrueVal : FalseVal) is lower-saturating. 4081 // All of these conditions (and their <= and >= counterparts) will do: 4082 // x < k ? k : x 4083 // x > k ? x : k 4084 // k < x ? x : k 4085 // k > x ? k : x 4086 static bool isLowerSaturate(const SDValue LHS, const SDValue RHS, 4087 const SDValue TrueVal, const SDValue FalseVal, 4088 const ISD::CondCode CC, const SDValue K) { 4089 return (isGTorGE(CC) && 4090 ((K == LHS && K == TrueVal) || (K == RHS && K == FalseVal))) || 4091 (isLTorLE(CC) && 4092 ((K == RHS && K == TrueVal) || (K == LHS && K == FalseVal))); 4093 } 4094 4095 // Similar to isLowerSaturate(), but checks for upper-saturating conditions. 4096 static bool isUpperSaturate(const SDValue LHS, const SDValue RHS, 4097 const SDValue TrueVal, const SDValue FalseVal, 4098 const ISD::CondCode CC, const SDValue K) { 4099 return (isGTorGE(CC) && 4100 ((K == RHS && K == TrueVal) || (K == LHS && K == FalseVal))) || 4101 (isLTorLE(CC) && 4102 ((K == LHS && K == TrueVal) || (K == RHS && K == FalseVal))); 4103 } 4104 4105 // Check if two chained conditionals could be converted into SSAT. 4106 // 4107 // SSAT can replace a set of two conditional selectors that bound a number to an 4108 // interval of type [k, ~k] when k + 1 is a power of 2. Here are some examples: 4109 // 4110 // x < -k ? -k : (x > k ? k : x) 4111 // x < -k ? -k : (x < k ? x : k) 4112 // x > -k ? (x > k ? k : x) : -k 4113 // x < k ? (x < -k ? -k : x) : k 4114 // etc. 4115 // 4116 // It returns true if the conversion can be done, false otherwise. 4117 // Additionally, the variable is returned in parameter V and the constant in K. 4118 static bool isSaturatingConditional(const SDValue &Op, SDValue &V, 4119 uint64_t &K) { 4120 SDValue LHS1 = Op.getOperand(0); 4121 SDValue RHS1 = Op.getOperand(1); 4122 SDValue TrueVal1 = Op.getOperand(2); 4123 SDValue FalseVal1 = Op.getOperand(3); 4124 ISD::CondCode CC1 = cast<CondCodeSDNode>(Op.getOperand(4))->get(); 4125 4126 const SDValue Op2 = isa<ConstantSDNode>(TrueVal1) ? FalseVal1 : TrueVal1; 4127 if (Op2.getOpcode() != ISD::SELECT_CC) 4128 return false; 4129 4130 SDValue LHS2 = Op2.getOperand(0); 4131 SDValue RHS2 = Op2.getOperand(1); 4132 SDValue TrueVal2 = Op2.getOperand(2); 4133 SDValue FalseVal2 = Op2.getOperand(3); 4134 ISD::CondCode CC2 = cast<CondCodeSDNode>(Op2.getOperand(4))->get(); 4135 4136 // Find out which are the constants and which are the variables 4137 // in each conditional 4138 SDValue *K1 = isa<ConstantSDNode>(LHS1) ? &LHS1 : isa<ConstantSDNode>(RHS1) 4139 ? &RHS1 4140 : nullptr; 4141 SDValue *K2 = isa<ConstantSDNode>(LHS2) ? &LHS2 : isa<ConstantSDNode>(RHS2) 4142 ? &RHS2 4143 : nullptr; 4144 SDValue K2Tmp = isa<ConstantSDNode>(TrueVal2) ? TrueVal2 : FalseVal2; 4145 SDValue V1Tmp = (K1 && *K1 == LHS1) ? RHS1 : LHS1; 4146 SDValue V2Tmp = (K2 && *K2 == LHS2) ? RHS2 : LHS2; 4147 SDValue V2 = (K2Tmp == TrueVal2) ? FalseVal2 : TrueVal2; 4148 4149 // We must detect cases where the original operations worked with 16- or 4150 // 8-bit values. In such case, V2Tmp != V2 because the comparison operations 4151 // must work with sign-extended values but the select operations return 4152 // the original non-extended value. 4153 SDValue V2TmpReg = V2Tmp; 4154 if (V2Tmp->getOpcode() == ISD::SIGN_EXTEND_INREG) 4155 V2TmpReg = V2Tmp->getOperand(0); 4156 4157 // Check that the registers and the constants have the correct values 4158 // in both conditionals 4159 if (!K1 || !K2 || *K1 == Op2 || *K2 != K2Tmp || V1Tmp != V2Tmp || 4160 V2TmpReg != V2) 4161 return false; 4162 4163 // Figure out which conditional is saturating the lower/upper bound. 4164 const SDValue *LowerCheckOp = 4165 isLowerSaturate(LHS1, RHS1, TrueVal1, FalseVal1, CC1, *K1) 4166 ? &Op 4167 : isLowerSaturate(LHS2, RHS2, TrueVal2, FalseVal2, CC2, *K2) 4168 ? &Op2 4169 : nullptr; 4170 const SDValue *UpperCheckOp = 4171 isUpperSaturate(LHS1, RHS1, TrueVal1, FalseVal1, CC1, *K1) 4172 ? &Op 4173 : isUpperSaturate(LHS2, RHS2, TrueVal2, FalseVal2, CC2, *K2) 4174 ? &Op2 4175 : nullptr; 4176 4177 if (!UpperCheckOp || !LowerCheckOp || LowerCheckOp == UpperCheckOp) 4178 return false; 4179 4180 // Check that the constant in the lower-bound check is 4181 // the opposite of the constant in the upper-bound check 4182 // in 1's complement. 4183 int64_t Val1 = cast<ConstantSDNode>(*K1)->getSExtValue(); 4184 int64_t Val2 = cast<ConstantSDNode>(*K2)->getSExtValue(); 4185 int64_t PosVal = std::max(Val1, Val2); 4186 4187 if (((Val1 > Val2 && UpperCheckOp == &Op) || 4188 (Val1 < Val2 && UpperCheckOp == &Op2)) && 4189 Val1 == ~Val2 && isPowerOf2_64(PosVal + 1)) { 4190 4191 V = V2; 4192 K = (uint64_t)PosVal; // At this point, PosVal is guaranteed to be positive 4193 return true; 4194 } 4195 4196 return false; 4197 } 4198 4199 SDValue ARMTargetLowering::LowerSELECT_CC(SDValue Op, SelectionDAG &DAG) const { 4200 EVT VT = Op.getValueType(); 4201 SDLoc dl(Op); 4202 4203 // Try to convert two saturating conditional selects into a single SSAT 4204 SDValue SatValue; 4205 uint64_t SatConstant; 4206 if (((!Subtarget->isThumb() && Subtarget->hasV6Ops()) || Subtarget->isThumb2()) && 4207 isSaturatingConditional(Op, SatValue, SatConstant)) 4208 return DAG.getNode(ARMISD::SSAT, dl, VT, SatValue, 4209 DAG.getConstant(countTrailingOnes(SatConstant), dl, VT)); 4210 4211 SDValue LHS = Op.getOperand(0); 4212 SDValue RHS = Op.getOperand(1); 4213 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(4))->get(); 4214 SDValue TrueVal = Op.getOperand(2); 4215 SDValue FalseVal = Op.getOperand(3); 4216 4217 if (Subtarget->isFPOnlySP() && LHS.getValueType() == MVT::f64) { 4218 DAG.getTargetLoweringInfo().softenSetCCOperands(DAG, MVT::f64, LHS, RHS, CC, 4219 dl); 4220 4221 // If softenSetCCOperands only returned one value, we should compare it to 4222 // zero. 4223 if (!RHS.getNode()) { 4224 RHS = DAG.getConstant(0, dl, LHS.getValueType()); 4225 CC = ISD::SETNE; 4226 } 4227 } 4228 4229 if (LHS.getValueType() == MVT::i32) { 4230 // Try to generate VSEL on ARMv8. 4231 // The VSEL instruction can't use all the usual ARM condition 4232 // codes: it only has two bits to select the condition code, so it's 4233 // constrained to use only GE, GT, VS and EQ. 4234 // 4235 // To implement all the various ISD::SETXXX opcodes, we sometimes need to 4236 // swap the operands of the previous compare instruction (effectively 4237 // inverting the compare condition, swapping 'less' and 'greater') and 4238 // sometimes need to swap the operands to the VSEL (which inverts the 4239 // condition in the sense of firing whenever the previous condition didn't) 4240 if (Subtarget->hasFPARMv8() && (TrueVal.getValueType() == MVT::f32 || 4241 TrueVal.getValueType() == MVT::f64)) { 4242 ARMCC::CondCodes CondCode = IntCCToARMCC(CC); 4243 if (CondCode == ARMCC::LT || CondCode == ARMCC::LE || 4244 CondCode == ARMCC::VC || CondCode == ARMCC::NE) { 4245 CC = ISD::getSetCCInverse(CC, true); 4246 std::swap(TrueVal, FalseVal); 4247 } 4248 } 4249 4250 SDValue ARMcc; 4251 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32); 4252 SDValue Cmp = getARMCmp(LHS, RHS, CC, ARMcc, DAG, dl); 4253 return getCMOV(dl, VT, FalseVal, TrueVal, ARMcc, CCR, Cmp, DAG); 4254 } 4255 4256 ARMCC::CondCodes CondCode, CondCode2; 4257 bool InvalidOnQNaN; 4258 FPCCToARMCC(CC, CondCode, CondCode2, InvalidOnQNaN); 4259 4260 // Try to generate VMAXNM/VMINNM on ARMv8. 4261 if (Subtarget->hasFPARMv8() && (TrueVal.getValueType() == MVT::f32 || 4262 TrueVal.getValueType() == MVT::f64)) { 4263 bool swpCmpOps = false; 4264 bool swpVselOps = false; 4265 checkVSELConstraints(CC, CondCode, swpCmpOps, swpVselOps); 4266 4267 if (CondCode == ARMCC::GT || CondCode == ARMCC::GE || 4268 CondCode == ARMCC::VS || CondCode == ARMCC::EQ) { 4269 if (swpCmpOps) 4270 std::swap(LHS, RHS); 4271 if (swpVselOps) 4272 std::swap(TrueVal, FalseVal); 4273 } 4274 } 4275 4276 SDValue ARMcc = DAG.getConstant(CondCode, dl, MVT::i32); 4277 SDValue Cmp = getVFPCmp(LHS, RHS, DAG, dl, InvalidOnQNaN); 4278 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32); 4279 SDValue Result = getCMOV(dl, VT, FalseVal, TrueVal, ARMcc, CCR, Cmp, DAG); 4280 if (CondCode2 != ARMCC::AL) { 4281 SDValue ARMcc2 = DAG.getConstant(CondCode2, dl, MVT::i32); 4282 // FIXME: Needs another CMP because flag can have but one use. 4283 SDValue Cmp2 = getVFPCmp(LHS, RHS, DAG, dl, InvalidOnQNaN); 4284 Result = getCMOV(dl, VT, Result, TrueVal, ARMcc2, CCR, Cmp2, DAG); 4285 } 4286 return Result; 4287 } 4288 4289 /// canChangeToInt - Given the fp compare operand, return true if it is suitable 4290 /// to morph to an integer compare sequence. 4291 static bool canChangeToInt(SDValue Op, bool &SeenZero, 4292 const ARMSubtarget *Subtarget) { 4293 SDNode *N = Op.getNode(); 4294 if (!N->hasOneUse()) 4295 // Otherwise it requires moving the value from fp to integer registers. 4296 return false; 4297 if (!N->getNumValues()) 4298 return false; 4299 EVT VT = Op.getValueType(); 4300 if (VT != MVT::f32 && !Subtarget->isFPBrccSlow()) 4301 // f32 case is generally profitable. f64 case only makes sense when vcmpe + 4302 // vmrs are very slow, e.g. cortex-a8. 4303 return false; 4304 4305 if (isFloatingPointZero(Op)) { 4306 SeenZero = true; 4307 return true; 4308 } 4309 return ISD::isNormalLoad(N); 4310 } 4311 4312 static SDValue bitcastf32Toi32(SDValue Op, SelectionDAG &DAG) { 4313 if (isFloatingPointZero(Op)) 4314 return DAG.getConstant(0, SDLoc(Op), MVT::i32); 4315 4316 if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Op)) 4317 return DAG.getLoad(MVT::i32, SDLoc(Op), Ld->getChain(), Ld->getBasePtr(), 4318 Ld->getPointerInfo(), Ld->getAlignment(), 4319 Ld->getMemOperand()->getFlags()); 4320 4321 llvm_unreachable("Unknown VFP cmp argument!"); 4322 } 4323 4324 static void expandf64Toi32(SDValue Op, SelectionDAG &DAG, 4325 SDValue &RetVal1, SDValue &RetVal2) { 4326 SDLoc dl(Op); 4327 4328 if (isFloatingPointZero(Op)) { 4329 RetVal1 = DAG.getConstant(0, dl, MVT::i32); 4330 RetVal2 = DAG.getConstant(0, dl, MVT::i32); 4331 return; 4332 } 4333 4334 if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Op)) { 4335 SDValue Ptr = Ld->getBasePtr(); 4336 RetVal1 = 4337 DAG.getLoad(MVT::i32, dl, Ld->getChain(), Ptr, Ld->getPointerInfo(), 4338 Ld->getAlignment(), Ld->getMemOperand()->getFlags()); 4339 4340 EVT PtrType = Ptr.getValueType(); 4341 unsigned NewAlign = MinAlign(Ld->getAlignment(), 4); 4342 SDValue NewPtr = DAG.getNode(ISD::ADD, dl, 4343 PtrType, Ptr, DAG.getConstant(4, dl, PtrType)); 4344 RetVal2 = DAG.getLoad(MVT::i32, dl, Ld->getChain(), NewPtr, 4345 Ld->getPointerInfo().getWithOffset(4), NewAlign, 4346 Ld->getMemOperand()->getFlags()); 4347 return; 4348 } 4349 4350 llvm_unreachable("Unknown VFP cmp argument!"); 4351 } 4352 4353 /// OptimizeVFPBrcond - With -enable-unsafe-fp-math, it's legal to optimize some 4354 /// f32 and even f64 comparisons to integer ones. 4355 SDValue 4356 ARMTargetLowering::OptimizeVFPBrcond(SDValue Op, SelectionDAG &DAG) const { 4357 SDValue Chain = Op.getOperand(0); 4358 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(1))->get(); 4359 SDValue LHS = Op.getOperand(2); 4360 SDValue RHS = Op.getOperand(3); 4361 SDValue Dest = Op.getOperand(4); 4362 SDLoc dl(Op); 4363 4364 bool LHSSeenZero = false; 4365 bool LHSOk = canChangeToInt(LHS, LHSSeenZero, Subtarget); 4366 bool RHSSeenZero = false; 4367 bool RHSOk = canChangeToInt(RHS, RHSSeenZero, Subtarget); 4368 if (LHSOk && RHSOk && (LHSSeenZero || RHSSeenZero)) { 4369 // If unsafe fp math optimization is enabled and there are no other uses of 4370 // the CMP operands, and the condition code is EQ or NE, we can optimize it 4371 // to an integer comparison. 4372 if (CC == ISD::SETOEQ) 4373 CC = ISD::SETEQ; 4374 else if (CC == ISD::SETUNE) 4375 CC = ISD::SETNE; 4376 4377 SDValue Mask = DAG.getConstant(0x7fffffff, dl, MVT::i32); 4378 SDValue ARMcc; 4379 if (LHS.getValueType() == MVT::f32) { 4380 LHS = DAG.getNode(ISD::AND, dl, MVT::i32, 4381 bitcastf32Toi32(LHS, DAG), Mask); 4382 RHS = DAG.getNode(ISD::AND, dl, MVT::i32, 4383 bitcastf32Toi32(RHS, DAG), Mask); 4384 SDValue Cmp = getARMCmp(LHS, RHS, CC, ARMcc, DAG, dl); 4385 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32); 4386 return DAG.getNode(ARMISD::BRCOND, dl, MVT::Other, 4387 Chain, Dest, ARMcc, CCR, Cmp); 4388 } 4389 4390 SDValue LHS1, LHS2; 4391 SDValue RHS1, RHS2; 4392 expandf64Toi32(LHS, DAG, LHS1, LHS2); 4393 expandf64Toi32(RHS, DAG, RHS1, RHS2); 4394 LHS2 = DAG.getNode(ISD::AND, dl, MVT::i32, LHS2, Mask); 4395 RHS2 = DAG.getNode(ISD::AND, dl, MVT::i32, RHS2, Mask); 4396 ARMCC::CondCodes CondCode = IntCCToARMCC(CC); 4397 ARMcc = DAG.getConstant(CondCode, dl, MVT::i32); 4398 SDVTList VTList = DAG.getVTList(MVT::Other, MVT::Glue); 4399 SDValue Ops[] = { Chain, ARMcc, LHS1, LHS2, RHS1, RHS2, Dest }; 4400 return DAG.getNode(ARMISD::BCC_i64, dl, VTList, Ops); 4401 } 4402 4403 return SDValue(); 4404 } 4405 4406 SDValue ARMTargetLowering::LowerBR_CC(SDValue Op, SelectionDAG &DAG) const { 4407 SDValue Chain = Op.getOperand(0); 4408 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(1))->get(); 4409 SDValue LHS = Op.getOperand(2); 4410 SDValue RHS = Op.getOperand(3); 4411 SDValue Dest = Op.getOperand(4); 4412 SDLoc dl(Op); 4413 4414 if (Subtarget->isFPOnlySP() && LHS.getValueType() == MVT::f64) { 4415 DAG.getTargetLoweringInfo().softenSetCCOperands(DAG, MVT::f64, LHS, RHS, CC, 4416 dl); 4417 4418 // If softenSetCCOperands only returned one value, we should compare it to 4419 // zero. 4420 if (!RHS.getNode()) { 4421 RHS = DAG.getConstant(0, dl, LHS.getValueType()); 4422 CC = ISD::SETNE; 4423 } 4424 } 4425 4426 if (LHS.getValueType() == MVT::i32) { 4427 SDValue ARMcc; 4428 SDValue Cmp = getARMCmp(LHS, RHS, CC, ARMcc, DAG, dl); 4429 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32); 4430 return DAG.getNode(ARMISD::BRCOND, dl, MVT::Other, 4431 Chain, Dest, ARMcc, CCR, Cmp); 4432 } 4433 4434 assert(LHS.getValueType() == MVT::f32 || LHS.getValueType() == MVT::f64); 4435 4436 if (getTargetMachine().Options.UnsafeFPMath && 4437 (CC == ISD::SETEQ || CC == ISD::SETOEQ || 4438 CC == ISD::SETNE || CC == ISD::SETUNE)) { 4439 if (SDValue Result = OptimizeVFPBrcond(Op, DAG)) 4440 return Result; 4441 } 4442 4443 ARMCC::CondCodes CondCode, CondCode2; 4444 bool InvalidOnQNaN; 4445 FPCCToARMCC(CC, CondCode, CondCode2, InvalidOnQNaN); 4446 4447 SDValue ARMcc = DAG.getConstant(CondCode, dl, MVT::i32); 4448 SDValue Cmp = getVFPCmp(LHS, RHS, DAG, dl, InvalidOnQNaN); 4449 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32); 4450 SDVTList VTList = DAG.getVTList(MVT::Other, MVT::Glue); 4451 SDValue Ops[] = { Chain, Dest, ARMcc, CCR, Cmp }; 4452 SDValue Res = DAG.getNode(ARMISD::BRCOND, dl, VTList, Ops); 4453 if (CondCode2 != ARMCC::AL) { 4454 ARMcc = DAG.getConstant(CondCode2, dl, MVT::i32); 4455 SDValue Ops[] = { Res, Dest, ARMcc, CCR, Res.getValue(1) }; 4456 Res = DAG.getNode(ARMISD::BRCOND, dl, VTList, Ops); 4457 } 4458 return Res; 4459 } 4460 4461 SDValue ARMTargetLowering::LowerBR_JT(SDValue Op, SelectionDAG &DAG) const { 4462 SDValue Chain = Op.getOperand(0); 4463 SDValue Table = Op.getOperand(1); 4464 SDValue Index = Op.getOperand(2); 4465 SDLoc dl(Op); 4466 4467 EVT PTy = getPointerTy(DAG.getDataLayout()); 4468 JumpTableSDNode *JT = cast<JumpTableSDNode>(Table); 4469 SDValue JTI = DAG.getTargetJumpTable(JT->getIndex(), PTy); 4470 Table = DAG.getNode(ARMISD::WrapperJT, dl, MVT::i32, JTI); 4471 Index = DAG.getNode(ISD::MUL, dl, PTy, Index, DAG.getConstant(4, dl, PTy)); 4472 SDValue Addr = DAG.getNode(ISD::ADD, dl, PTy, Index, Table); 4473 if (Subtarget->isThumb2() || (Subtarget->hasV8MBaselineOps() && Subtarget->isThumb())) { 4474 // Thumb2 and ARMv8-M use a two-level jump. That is, it jumps into the jump table 4475 // which does another jump to the destination. This also makes it easier 4476 // to translate it to TBB / TBH later (Thumb2 only). 4477 // FIXME: This might not work if the function is extremely large. 4478 return DAG.getNode(ARMISD::BR2_JT, dl, MVT::Other, Chain, 4479 Addr, Op.getOperand(2), JTI); 4480 } 4481 if (isPositionIndependent() || Subtarget->isROPI()) { 4482 Addr = 4483 DAG.getLoad((EVT)MVT::i32, dl, Chain, Addr, 4484 MachinePointerInfo::getJumpTable(DAG.getMachineFunction())); 4485 Chain = Addr.getValue(1); 4486 Addr = DAG.getNode(ISD::ADD, dl, PTy, Addr, Table); 4487 return DAG.getNode(ARMISD::BR_JT, dl, MVT::Other, Chain, Addr, JTI); 4488 } else { 4489 Addr = 4490 DAG.getLoad(PTy, dl, Chain, Addr, 4491 MachinePointerInfo::getJumpTable(DAG.getMachineFunction())); 4492 Chain = Addr.getValue(1); 4493 return DAG.getNode(ARMISD::BR_JT, dl, MVT::Other, Chain, Addr, JTI); 4494 } 4495 } 4496 4497 static SDValue LowerVectorFP_TO_INT(SDValue Op, SelectionDAG &DAG) { 4498 EVT VT = Op.getValueType(); 4499 SDLoc dl(Op); 4500 4501 if (Op.getValueType().getVectorElementType() == MVT::i32) { 4502 if (Op.getOperand(0).getValueType().getVectorElementType() == MVT::f32) 4503 return Op; 4504 return DAG.UnrollVectorOp(Op.getNode()); 4505 } 4506 4507 assert(Op.getOperand(0).getValueType() == MVT::v4f32 && 4508 "Invalid type for custom lowering!"); 4509 if (VT != MVT::v4i16) 4510 return DAG.UnrollVectorOp(Op.getNode()); 4511 4512 Op = DAG.getNode(Op.getOpcode(), dl, MVT::v4i32, Op.getOperand(0)); 4513 return DAG.getNode(ISD::TRUNCATE, dl, VT, Op); 4514 } 4515 4516 SDValue ARMTargetLowering::LowerFP_TO_INT(SDValue Op, SelectionDAG &DAG) const { 4517 EVT VT = Op.getValueType(); 4518 if (VT.isVector()) 4519 return LowerVectorFP_TO_INT(Op, DAG); 4520 if (Subtarget->isFPOnlySP() && Op.getOperand(0).getValueType() == MVT::f64) { 4521 RTLIB::Libcall LC; 4522 if (Op.getOpcode() == ISD::FP_TO_SINT) 4523 LC = RTLIB::getFPTOSINT(Op.getOperand(0).getValueType(), 4524 Op.getValueType()); 4525 else 4526 LC = RTLIB::getFPTOUINT(Op.getOperand(0).getValueType(), 4527 Op.getValueType()); 4528 return makeLibCall(DAG, LC, Op.getValueType(), Op.getOperand(0), 4529 /*isSigned*/ false, SDLoc(Op)).first; 4530 } 4531 4532 return Op; 4533 } 4534 4535 static SDValue LowerVectorINT_TO_FP(SDValue Op, SelectionDAG &DAG) { 4536 EVT VT = Op.getValueType(); 4537 SDLoc dl(Op); 4538 4539 if (Op.getOperand(0).getValueType().getVectorElementType() == MVT::i32) { 4540 if (VT.getVectorElementType() == MVT::f32) 4541 return Op; 4542 return DAG.UnrollVectorOp(Op.getNode()); 4543 } 4544 4545 assert(Op.getOperand(0).getValueType() == MVT::v4i16 && 4546 "Invalid type for custom lowering!"); 4547 if (VT != MVT::v4f32) 4548 return DAG.UnrollVectorOp(Op.getNode()); 4549 4550 unsigned CastOpc; 4551 unsigned Opc; 4552 switch (Op.getOpcode()) { 4553 default: llvm_unreachable("Invalid opcode!"); 4554 case ISD::SINT_TO_FP: 4555 CastOpc = ISD::SIGN_EXTEND; 4556 Opc = ISD::SINT_TO_FP; 4557 break; 4558 case ISD::UINT_TO_FP: 4559 CastOpc = ISD::ZERO_EXTEND; 4560 Opc = ISD::UINT_TO_FP; 4561 break; 4562 } 4563 4564 Op = DAG.getNode(CastOpc, dl, MVT::v4i32, Op.getOperand(0)); 4565 return DAG.getNode(Opc, dl, VT, Op); 4566 } 4567 4568 SDValue ARMTargetLowering::LowerINT_TO_FP(SDValue Op, SelectionDAG &DAG) const { 4569 EVT VT = Op.getValueType(); 4570 if (VT.isVector()) 4571 return LowerVectorINT_TO_FP(Op, DAG); 4572 if (Subtarget->isFPOnlySP() && Op.getValueType() == MVT::f64) { 4573 RTLIB::Libcall LC; 4574 if (Op.getOpcode() == ISD::SINT_TO_FP) 4575 LC = RTLIB::getSINTTOFP(Op.getOperand(0).getValueType(), 4576 Op.getValueType()); 4577 else 4578 LC = RTLIB::getUINTTOFP(Op.getOperand(0).getValueType(), 4579 Op.getValueType()); 4580 return makeLibCall(DAG, LC, Op.getValueType(), Op.getOperand(0), 4581 /*isSigned*/ false, SDLoc(Op)).first; 4582 } 4583 4584 return Op; 4585 } 4586 4587 SDValue ARMTargetLowering::LowerFCOPYSIGN(SDValue Op, SelectionDAG &DAG) const { 4588 // Implement fcopysign with a fabs and a conditional fneg. 4589 SDValue Tmp0 = Op.getOperand(0); 4590 SDValue Tmp1 = Op.getOperand(1); 4591 SDLoc dl(Op); 4592 EVT VT = Op.getValueType(); 4593 EVT SrcVT = Tmp1.getValueType(); 4594 bool InGPR = Tmp0.getOpcode() == ISD::BITCAST || 4595 Tmp0.getOpcode() == ARMISD::VMOVDRR; 4596 bool UseNEON = !InGPR && Subtarget->hasNEON(); 4597 4598 if (UseNEON) { 4599 // Use VBSL to copy the sign bit. 4600 unsigned EncodedVal = ARM_AM::createNEONModImm(0x6, 0x80); 4601 SDValue Mask = DAG.getNode(ARMISD::VMOVIMM, dl, MVT::v2i32, 4602 DAG.getTargetConstant(EncodedVal, dl, MVT::i32)); 4603 EVT OpVT = (VT == MVT::f32) ? MVT::v2i32 : MVT::v1i64; 4604 if (VT == MVT::f64) 4605 Mask = DAG.getNode(ARMISD::VSHL, dl, OpVT, 4606 DAG.getNode(ISD::BITCAST, dl, OpVT, Mask), 4607 DAG.getConstant(32, dl, MVT::i32)); 4608 else /*if (VT == MVT::f32)*/ 4609 Tmp0 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f32, Tmp0); 4610 if (SrcVT == MVT::f32) { 4611 Tmp1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f32, Tmp1); 4612 if (VT == MVT::f64) 4613 Tmp1 = DAG.getNode(ARMISD::VSHL, dl, OpVT, 4614 DAG.getNode(ISD::BITCAST, dl, OpVT, Tmp1), 4615 DAG.getConstant(32, dl, MVT::i32)); 4616 } else if (VT == MVT::f32) 4617 Tmp1 = DAG.getNode(ARMISD::VSHRu, dl, MVT::v1i64, 4618 DAG.getNode(ISD::BITCAST, dl, MVT::v1i64, Tmp1), 4619 DAG.getConstant(32, dl, MVT::i32)); 4620 Tmp0 = DAG.getNode(ISD::BITCAST, dl, OpVT, Tmp0); 4621 Tmp1 = DAG.getNode(ISD::BITCAST, dl, OpVT, Tmp1); 4622 4623 SDValue AllOnes = DAG.getTargetConstant(ARM_AM::createNEONModImm(0xe, 0xff), 4624 dl, MVT::i32); 4625 AllOnes = DAG.getNode(ARMISD::VMOVIMM, dl, MVT::v8i8, AllOnes); 4626 SDValue MaskNot = DAG.getNode(ISD::XOR, dl, OpVT, Mask, 4627 DAG.getNode(ISD::BITCAST, dl, OpVT, AllOnes)); 4628 4629 SDValue Res = DAG.getNode(ISD::OR, dl, OpVT, 4630 DAG.getNode(ISD::AND, dl, OpVT, Tmp1, Mask), 4631 DAG.getNode(ISD::AND, dl, OpVT, Tmp0, MaskNot)); 4632 if (VT == MVT::f32) { 4633 Res = DAG.getNode(ISD::BITCAST, dl, MVT::v2f32, Res); 4634 Res = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f32, Res, 4635 DAG.getConstant(0, dl, MVT::i32)); 4636 } else { 4637 Res = DAG.getNode(ISD::BITCAST, dl, MVT::f64, Res); 4638 } 4639 4640 return Res; 4641 } 4642 4643 // Bitcast operand 1 to i32. 4644 if (SrcVT == MVT::f64) 4645 Tmp1 = DAG.getNode(ARMISD::VMOVRRD, dl, DAG.getVTList(MVT::i32, MVT::i32), 4646 Tmp1).getValue(1); 4647 Tmp1 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Tmp1); 4648 4649 // Or in the signbit with integer operations. 4650 SDValue Mask1 = DAG.getConstant(0x80000000, dl, MVT::i32); 4651 SDValue Mask2 = DAG.getConstant(0x7fffffff, dl, MVT::i32); 4652 Tmp1 = DAG.getNode(ISD::AND, dl, MVT::i32, Tmp1, Mask1); 4653 if (VT == MVT::f32) { 4654 Tmp0 = DAG.getNode(ISD::AND, dl, MVT::i32, 4655 DAG.getNode(ISD::BITCAST, dl, MVT::i32, Tmp0), Mask2); 4656 return DAG.getNode(ISD::BITCAST, dl, MVT::f32, 4657 DAG.getNode(ISD::OR, dl, MVT::i32, Tmp0, Tmp1)); 4658 } 4659 4660 // f64: Or the high part with signbit and then combine two parts. 4661 Tmp0 = DAG.getNode(ARMISD::VMOVRRD, dl, DAG.getVTList(MVT::i32, MVT::i32), 4662 Tmp0); 4663 SDValue Lo = Tmp0.getValue(0); 4664 SDValue Hi = DAG.getNode(ISD::AND, dl, MVT::i32, Tmp0.getValue(1), Mask2); 4665 Hi = DAG.getNode(ISD::OR, dl, MVT::i32, Hi, Tmp1); 4666 return DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi); 4667 } 4668 4669 SDValue ARMTargetLowering::LowerRETURNADDR(SDValue Op, SelectionDAG &DAG) const{ 4670 MachineFunction &MF = DAG.getMachineFunction(); 4671 MachineFrameInfo &MFI = MF.getFrameInfo(); 4672 MFI.setReturnAddressIsTaken(true); 4673 4674 if (verifyReturnAddressArgumentIsConstant(Op, DAG)) 4675 return SDValue(); 4676 4677 EVT VT = Op.getValueType(); 4678 SDLoc dl(Op); 4679 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue(); 4680 if (Depth) { 4681 SDValue FrameAddr = LowerFRAMEADDR(Op, DAG); 4682 SDValue Offset = DAG.getConstant(4, dl, MVT::i32); 4683 return DAG.getLoad(VT, dl, DAG.getEntryNode(), 4684 DAG.getNode(ISD::ADD, dl, VT, FrameAddr, Offset), 4685 MachinePointerInfo()); 4686 } 4687 4688 // Return LR, which contains the return address. Mark it an implicit live-in. 4689 unsigned Reg = MF.addLiveIn(ARM::LR, getRegClassFor(MVT::i32)); 4690 return DAG.getCopyFromReg(DAG.getEntryNode(), dl, Reg, VT); 4691 } 4692 4693 SDValue ARMTargetLowering::LowerFRAMEADDR(SDValue Op, SelectionDAG &DAG) const { 4694 const ARMBaseRegisterInfo &ARI = 4695 *static_cast<const ARMBaseRegisterInfo*>(RegInfo); 4696 MachineFunction &MF = DAG.getMachineFunction(); 4697 MachineFrameInfo &MFI = MF.getFrameInfo(); 4698 MFI.setFrameAddressIsTaken(true); 4699 4700 EVT VT = Op.getValueType(); 4701 SDLoc dl(Op); // FIXME probably not meaningful 4702 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue(); 4703 unsigned FrameReg = ARI.getFrameRegister(MF); 4704 SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, VT); 4705 while (Depth--) 4706 FrameAddr = DAG.getLoad(VT, dl, DAG.getEntryNode(), FrameAddr, 4707 MachinePointerInfo()); 4708 return FrameAddr; 4709 } 4710 4711 // FIXME? Maybe this could be a TableGen attribute on some registers and 4712 // this table could be generated automatically from RegInfo. 4713 unsigned ARMTargetLowering::getRegisterByName(const char* RegName, EVT VT, 4714 SelectionDAG &DAG) const { 4715 unsigned Reg = StringSwitch<unsigned>(RegName) 4716 .Case("sp", ARM::SP) 4717 .Default(0); 4718 if (Reg) 4719 return Reg; 4720 report_fatal_error(Twine("Invalid register name \"" 4721 + StringRef(RegName) + "\".")); 4722 } 4723 4724 // Result is 64 bit value so split into two 32 bit values and return as a 4725 // pair of values. 4726 static void ExpandREAD_REGISTER(SDNode *N, SmallVectorImpl<SDValue> &Results, 4727 SelectionDAG &DAG) { 4728 SDLoc DL(N); 4729 4730 // This function is only supposed to be called for i64 type destination. 4731 assert(N->getValueType(0) == MVT::i64 4732 && "ExpandREAD_REGISTER called for non-i64 type result."); 4733 4734 SDValue Read = DAG.getNode(ISD::READ_REGISTER, DL, 4735 DAG.getVTList(MVT::i32, MVT::i32, MVT::Other), 4736 N->getOperand(0), 4737 N->getOperand(1)); 4738 4739 Results.push_back(DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, Read.getValue(0), 4740 Read.getValue(1))); 4741 Results.push_back(Read.getOperand(0)); 4742 } 4743 4744 /// \p BC is a bitcast that is about to be turned into a VMOVDRR. 4745 /// When \p DstVT, the destination type of \p BC, is on the vector 4746 /// register bank and the source of bitcast, \p Op, operates on the same bank, 4747 /// it might be possible to combine them, such that everything stays on the 4748 /// vector register bank. 4749 /// \p return The node that would replace \p BT, if the combine 4750 /// is possible. 4751 static SDValue CombineVMOVDRRCandidateWithVecOp(const SDNode *BC, 4752 SelectionDAG &DAG) { 4753 SDValue Op = BC->getOperand(0); 4754 EVT DstVT = BC->getValueType(0); 4755 4756 // The only vector instruction that can produce a scalar (remember, 4757 // since the bitcast was about to be turned into VMOVDRR, the source 4758 // type is i64) from a vector is EXTRACT_VECTOR_ELT. 4759 // Moreover, we can do this combine only if there is one use. 4760 // Finally, if the destination type is not a vector, there is not 4761 // much point on forcing everything on the vector bank. 4762 if (!DstVT.isVector() || Op.getOpcode() != ISD::EXTRACT_VECTOR_ELT || 4763 !Op.hasOneUse()) 4764 return SDValue(); 4765 4766 // If the index is not constant, we will introduce an additional 4767 // multiply that will stick. 4768 // Give up in that case. 4769 ConstantSDNode *Index = dyn_cast<ConstantSDNode>(Op.getOperand(1)); 4770 if (!Index) 4771 return SDValue(); 4772 unsigned DstNumElt = DstVT.getVectorNumElements(); 4773 4774 // Compute the new index. 4775 const APInt &APIntIndex = Index->getAPIntValue(); 4776 APInt NewIndex(APIntIndex.getBitWidth(), DstNumElt); 4777 NewIndex *= APIntIndex; 4778 // Check if the new constant index fits into i32. 4779 if (NewIndex.getBitWidth() > 32) 4780 return SDValue(); 4781 4782 // vMTy bitcast(i64 extractelt vNi64 src, i32 index) -> 4783 // vMTy extractsubvector vNxMTy (bitcast vNi64 src), i32 index*M) 4784 SDLoc dl(Op); 4785 SDValue ExtractSrc = Op.getOperand(0); 4786 EVT VecVT = EVT::getVectorVT( 4787 *DAG.getContext(), DstVT.getScalarType(), 4788 ExtractSrc.getValueType().getVectorNumElements() * DstNumElt); 4789 SDValue BitCast = DAG.getNode(ISD::BITCAST, dl, VecVT, ExtractSrc); 4790 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DstVT, BitCast, 4791 DAG.getConstant(NewIndex.getZExtValue(), dl, MVT::i32)); 4792 } 4793 4794 /// ExpandBITCAST - If the target supports VFP, this function is called to 4795 /// expand a bit convert where either the source or destination type is i64 to 4796 /// use a VMOVDRR or VMOVRRD node. This should not be done when the non-i64 4797 /// operand type is illegal (e.g., v2f32 for a target that doesn't support 4798 /// vectors), since the legalizer won't know what to do with that. 4799 static SDValue ExpandBITCAST(SDNode *N, SelectionDAG &DAG) { 4800 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 4801 SDLoc dl(N); 4802 SDValue Op = N->getOperand(0); 4803 4804 // This function is only supposed to be called for i64 types, either as the 4805 // source or destination of the bit convert. 4806 EVT SrcVT = Op.getValueType(); 4807 EVT DstVT = N->getValueType(0); 4808 assert((SrcVT == MVT::i64 || DstVT == MVT::i64) && 4809 "ExpandBITCAST called for non-i64 type"); 4810 4811 // Turn i64->f64 into VMOVDRR. 4812 if (SrcVT == MVT::i64 && TLI.isTypeLegal(DstVT)) { 4813 // Do not force values to GPRs (this is what VMOVDRR does for the inputs) 4814 // if we can combine the bitcast with its source. 4815 if (SDValue Val = CombineVMOVDRRCandidateWithVecOp(N, DAG)) 4816 return Val; 4817 4818 SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, Op, 4819 DAG.getConstant(0, dl, MVT::i32)); 4820 SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, Op, 4821 DAG.getConstant(1, dl, MVT::i32)); 4822 return DAG.getNode(ISD::BITCAST, dl, DstVT, 4823 DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi)); 4824 } 4825 4826 // Turn f64->i64 into VMOVRRD. 4827 if (DstVT == MVT::i64 && TLI.isTypeLegal(SrcVT)) { 4828 SDValue Cvt; 4829 if (DAG.getDataLayout().isBigEndian() && SrcVT.isVector() && 4830 SrcVT.getVectorNumElements() > 1) 4831 Cvt = DAG.getNode(ARMISD::VMOVRRD, dl, 4832 DAG.getVTList(MVT::i32, MVT::i32), 4833 DAG.getNode(ARMISD::VREV64, dl, SrcVT, Op)); 4834 else 4835 Cvt = DAG.getNode(ARMISD::VMOVRRD, dl, 4836 DAG.getVTList(MVT::i32, MVT::i32), Op); 4837 // Merge the pieces into a single i64 value. 4838 return DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Cvt, Cvt.getValue(1)); 4839 } 4840 4841 return SDValue(); 4842 } 4843 4844 /// getZeroVector - Returns a vector of specified type with all zero elements. 4845 /// Zero vectors are used to represent vector negation and in those cases 4846 /// will be implemented with the NEON VNEG instruction. However, VNEG does 4847 /// not support i64 elements, so sometimes the zero vectors will need to be 4848 /// explicitly constructed. Regardless, use a canonical VMOV to create the 4849 /// zero vector. 4850 static SDValue getZeroVector(EVT VT, SelectionDAG &DAG, const SDLoc &dl) { 4851 assert(VT.isVector() && "Expected a vector type"); 4852 // The canonical modified immediate encoding of a zero vector is....0! 4853 SDValue EncodedVal = DAG.getTargetConstant(0, dl, MVT::i32); 4854 EVT VmovVT = VT.is128BitVector() ? MVT::v4i32 : MVT::v2i32; 4855 SDValue Vmov = DAG.getNode(ARMISD::VMOVIMM, dl, VmovVT, EncodedVal); 4856 return DAG.getNode(ISD::BITCAST, dl, VT, Vmov); 4857 } 4858 4859 /// LowerShiftRightParts - Lower SRA_PARTS, which returns two 4860 /// i32 values and take a 2 x i32 value to shift plus a shift amount. 4861 SDValue ARMTargetLowering::LowerShiftRightParts(SDValue Op, 4862 SelectionDAG &DAG) const { 4863 assert(Op.getNumOperands() == 3 && "Not a double-shift!"); 4864 EVT VT = Op.getValueType(); 4865 unsigned VTBits = VT.getSizeInBits(); 4866 SDLoc dl(Op); 4867 SDValue ShOpLo = Op.getOperand(0); 4868 SDValue ShOpHi = Op.getOperand(1); 4869 SDValue ShAmt = Op.getOperand(2); 4870 SDValue ARMcc; 4871 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32); 4872 unsigned Opc = (Op.getOpcode() == ISD::SRA_PARTS) ? ISD::SRA : ISD::SRL; 4873 4874 assert(Op.getOpcode() == ISD::SRA_PARTS || Op.getOpcode() == ISD::SRL_PARTS); 4875 4876 SDValue RevShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32, 4877 DAG.getConstant(VTBits, dl, MVT::i32), ShAmt); 4878 SDValue Tmp1 = DAG.getNode(ISD::SRL, dl, VT, ShOpLo, ShAmt); 4879 SDValue ExtraShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32, ShAmt, 4880 DAG.getConstant(VTBits, dl, MVT::i32)); 4881 SDValue Tmp2 = DAG.getNode(ISD::SHL, dl, VT, ShOpHi, RevShAmt); 4882 SDValue LoSmallShift = DAG.getNode(ISD::OR, dl, VT, Tmp1, Tmp2); 4883 SDValue LoBigShift = DAG.getNode(Opc, dl, VT, ShOpHi, ExtraShAmt); 4884 SDValue CmpLo = getARMCmp(ExtraShAmt, DAG.getConstant(0, dl, MVT::i32), 4885 ISD::SETGE, ARMcc, DAG, dl); 4886 SDValue Lo = DAG.getNode(ARMISD::CMOV, dl, VT, LoSmallShift, LoBigShift, 4887 ARMcc, CCR, CmpLo); 4888 4889 4890 SDValue HiSmallShift = DAG.getNode(Opc, dl, VT, ShOpHi, ShAmt); 4891 SDValue HiBigShift = Opc == ISD::SRA 4892 ? DAG.getNode(Opc, dl, VT, ShOpHi, 4893 DAG.getConstant(VTBits - 1, dl, VT)) 4894 : DAG.getConstant(0, dl, VT); 4895 SDValue CmpHi = getARMCmp(ExtraShAmt, DAG.getConstant(0, dl, MVT::i32), 4896 ISD::SETGE, ARMcc, DAG, dl); 4897 SDValue Hi = DAG.getNode(ARMISD::CMOV, dl, VT, HiSmallShift, HiBigShift, 4898 ARMcc, CCR, CmpHi); 4899 4900 SDValue Ops[2] = { Lo, Hi }; 4901 return DAG.getMergeValues(Ops, dl); 4902 } 4903 4904 /// LowerShiftLeftParts - Lower SHL_PARTS, which returns two 4905 /// i32 values and take a 2 x i32 value to shift plus a shift amount. 4906 SDValue ARMTargetLowering::LowerShiftLeftParts(SDValue Op, 4907 SelectionDAG &DAG) const { 4908 assert(Op.getNumOperands() == 3 && "Not a double-shift!"); 4909 EVT VT = Op.getValueType(); 4910 unsigned VTBits = VT.getSizeInBits(); 4911 SDLoc dl(Op); 4912 SDValue ShOpLo = Op.getOperand(0); 4913 SDValue ShOpHi = Op.getOperand(1); 4914 SDValue ShAmt = Op.getOperand(2); 4915 SDValue ARMcc; 4916 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32); 4917 4918 assert(Op.getOpcode() == ISD::SHL_PARTS); 4919 SDValue RevShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32, 4920 DAG.getConstant(VTBits, dl, MVT::i32), ShAmt); 4921 SDValue Tmp1 = DAG.getNode(ISD::SRL, dl, VT, ShOpLo, RevShAmt); 4922 SDValue Tmp2 = DAG.getNode(ISD::SHL, dl, VT, ShOpHi, ShAmt); 4923 SDValue HiSmallShift = DAG.getNode(ISD::OR, dl, VT, Tmp1, Tmp2); 4924 4925 SDValue ExtraShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32, ShAmt, 4926 DAG.getConstant(VTBits, dl, MVT::i32)); 4927 SDValue HiBigShift = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ExtraShAmt); 4928 SDValue CmpHi = getARMCmp(ExtraShAmt, DAG.getConstant(0, dl, MVT::i32), 4929 ISD::SETGE, ARMcc, DAG, dl); 4930 SDValue Hi = DAG.getNode(ARMISD::CMOV, dl, VT, HiSmallShift, HiBigShift, 4931 ARMcc, CCR, CmpHi); 4932 4933 SDValue CmpLo = getARMCmp(ExtraShAmt, DAG.getConstant(0, dl, MVT::i32), 4934 ISD::SETGE, ARMcc, DAG, dl); 4935 SDValue LoSmallShift = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ShAmt); 4936 SDValue Lo = DAG.getNode(ARMISD::CMOV, dl, VT, LoSmallShift, 4937 DAG.getConstant(0, dl, VT), ARMcc, CCR, CmpLo); 4938 4939 SDValue Ops[2] = { Lo, Hi }; 4940 return DAG.getMergeValues(Ops, dl); 4941 } 4942 4943 SDValue ARMTargetLowering::LowerFLT_ROUNDS_(SDValue Op, 4944 SelectionDAG &DAG) const { 4945 // The rounding mode is in bits 23:22 of the FPSCR. 4946 // The ARM rounding mode value to FLT_ROUNDS mapping is 0->1, 1->2, 2->3, 3->0 4947 // The formula we use to implement this is (((FPSCR + 1 << 22) >> 22) & 3) 4948 // so that the shift + and get folded into a bitfield extract. 4949 SDLoc dl(Op); 4950 SDValue Ops[] = { DAG.getEntryNode(), 4951 DAG.getConstant(Intrinsic::arm_get_fpscr, dl, MVT::i32) }; 4952 4953 SDValue FPSCR = DAG.getNode(ISD::INTRINSIC_W_CHAIN, dl, MVT::i32, Ops); 4954 SDValue FltRounds = DAG.getNode(ISD::ADD, dl, MVT::i32, FPSCR, 4955 DAG.getConstant(1U << 22, dl, MVT::i32)); 4956 SDValue RMODE = DAG.getNode(ISD::SRL, dl, MVT::i32, FltRounds, 4957 DAG.getConstant(22, dl, MVT::i32)); 4958 return DAG.getNode(ISD::AND, dl, MVT::i32, RMODE, 4959 DAG.getConstant(3, dl, MVT::i32)); 4960 } 4961 4962 static SDValue LowerCTTZ(SDNode *N, SelectionDAG &DAG, 4963 const ARMSubtarget *ST) { 4964 SDLoc dl(N); 4965 EVT VT = N->getValueType(0); 4966 if (VT.isVector()) { 4967 assert(ST->hasNEON()); 4968 4969 // Compute the least significant set bit: LSB = X & -X 4970 SDValue X = N->getOperand(0); 4971 SDValue NX = DAG.getNode(ISD::SUB, dl, VT, getZeroVector(VT, DAG, dl), X); 4972 SDValue LSB = DAG.getNode(ISD::AND, dl, VT, X, NX); 4973 4974 EVT ElemTy = VT.getVectorElementType(); 4975 4976 if (ElemTy == MVT::i8) { 4977 // Compute with: cttz(x) = ctpop(lsb - 1) 4978 SDValue One = DAG.getNode(ARMISD::VMOVIMM, dl, VT, 4979 DAG.getTargetConstant(1, dl, ElemTy)); 4980 SDValue Bits = DAG.getNode(ISD::SUB, dl, VT, LSB, One); 4981 return DAG.getNode(ISD::CTPOP, dl, VT, Bits); 4982 } 4983 4984 if ((ElemTy == MVT::i16 || ElemTy == MVT::i32) && 4985 (N->getOpcode() == ISD::CTTZ_ZERO_UNDEF)) { 4986 // Compute with: cttz(x) = (width - 1) - ctlz(lsb), if x != 0 4987 unsigned NumBits = ElemTy.getSizeInBits(); 4988 SDValue WidthMinus1 = 4989 DAG.getNode(ARMISD::VMOVIMM, dl, VT, 4990 DAG.getTargetConstant(NumBits - 1, dl, ElemTy)); 4991 SDValue CTLZ = DAG.getNode(ISD::CTLZ, dl, VT, LSB); 4992 return DAG.getNode(ISD::SUB, dl, VT, WidthMinus1, CTLZ); 4993 } 4994 4995 // Compute with: cttz(x) = ctpop(lsb - 1) 4996 4997 // Since we can only compute the number of bits in a byte with vcnt.8, we 4998 // have to gather the result with pairwise addition (vpaddl) for i16, i32, 4999 // and i64. 5000 5001 // Compute LSB - 1. 5002 SDValue Bits; 5003 if (ElemTy == MVT::i64) { 5004 // Load constant 0xffff'ffff'ffff'ffff to register. 5005 SDValue FF = DAG.getNode(ARMISD::VMOVIMM, dl, VT, 5006 DAG.getTargetConstant(0x1eff, dl, MVT::i32)); 5007 Bits = DAG.getNode(ISD::ADD, dl, VT, LSB, FF); 5008 } else { 5009 SDValue One = DAG.getNode(ARMISD::VMOVIMM, dl, VT, 5010 DAG.getTargetConstant(1, dl, ElemTy)); 5011 Bits = DAG.getNode(ISD::SUB, dl, VT, LSB, One); 5012 } 5013 5014 // Count #bits with vcnt.8. 5015 EVT VT8Bit = VT.is64BitVector() ? MVT::v8i8 : MVT::v16i8; 5016 SDValue BitsVT8 = DAG.getNode(ISD::BITCAST, dl, VT8Bit, Bits); 5017 SDValue Cnt8 = DAG.getNode(ISD::CTPOP, dl, VT8Bit, BitsVT8); 5018 5019 // Gather the #bits with vpaddl (pairwise add.) 5020 EVT VT16Bit = VT.is64BitVector() ? MVT::v4i16 : MVT::v8i16; 5021 SDValue Cnt16 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT16Bit, 5022 DAG.getTargetConstant(Intrinsic::arm_neon_vpaddlu, dl, MVT::i32), 5023 Cnt8); 5024 if (ElemTy == MVT::i16) 5025 return Cnt16; 5026 5027 EVT VT32Bit = VT.is64BitVector() ? MVT::v2i32 : MVT::v4i32; 5028 SDValue Cnt32 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT32Bit, 5029 DAG.getTargetConstant(Intrinsic::arm_neon_vpaddlu, dl, MVT::i32), 5030 Cnt16); 5031 if (ElemTy == MVT::i32) 5032 return Cnt32; 5033 5034 assert(ElemTy == MVT::i64); 5035 SDValue Cnt64 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT, 5036 DAG.getTargetConstant(Intrinsic::arm_neon_vpaddlu, dl, MVT::i32), 5037 Cnt32); 5038 return Cnt64; 5039 } 5040 5041 if (!ST->hasV6T2Ops()) 5042 return SDValue(); 5043 5044 SDValue rbit = DAG.getNode(ISD::BITREVERSE, dl, VT, N->getOperand(0)); 5045 return DAG.getNode(ISD::CTLZ, dl, VT, rbit); 5046 } 5047 5048 /// getCTPOP16BitCounts - Returns a v8i8/v16i8 vector containing the bit-count 5049 /// for each 16-bit element from operand, repeated. The basic idea is to 5050 /// leverage vcnt to get the 8-bit counts, gather and add the results. 5051 /// 5052 /// Trace for v4i16: 5053 /// input = [v0 v1 v2 v3 ] (vi 16-bit element) 5054 /// cast: N0 = [w0 w1 w2 w3 w4 w5 w6 w7] (v0 = [w0 w1], wi 8-bit element) 5055 /// vcnt: N1 = [b0 b1 b2 b3 b4 b5 b6 b7] (bi = bit-count of 8-bit element wi) 5056 /// vrev: N2 = [b1 b0 b3 b2 b5 b4 b7 b6] 5057 /// [b0 b1 b2 b3 b4 b5 b6 b7] 5058 /// +[b1 b0 b3 b2 b5 b4 b7 b6] 5059 /// N3=N1+N2 = [k0 k0 k1 k1 k2 k2 k3 k3] (k0 = b0+b1 = bit-count of 16-bit v0, 5060 /// vuzp: = [k0 k1 k2 k3 k0 k1 k2 k3] each ki is 8-bits) 5061 static SDValue getCTPOP16BitCounts(SDNode *N, SelectionDAG &DAG) { 5062 EVT VT = N->getValueType(0); 5063 SDLoc DL(N); 5064 5065 EVT VT8Bit = VT.is64BitVector() ? MVT::v8i8 : MVT::v16i8; 5066 SDValue N0 = DAG.getNode(ISD::BITCAST, DL, VT8Bit, N->getOperand(0)); 5067 SDValue N1 = DAG.getNode(ISD::CTPOP, DL, VT8Bit, N0); 5068 SDValue N2 = DAG.getNode(ARMISD::VREV16, DL, VT8Bit, N1); 5069 SDValue N3 = DAG.getNode(ISD::ADD, DL, VT8Bit, N1, N2); 5070 return DAG.getNode(ARMISD::VUZP, DL, VT8Bit, N3, N3); 5071 } 5072 5073 /// lowerCTPOP16BitElements - Returns a v4i16/v8i16 vector containing the 5074 /// bit-count for each 16-bit element from the operand. We need slightly 5075 /// different sequencing for v4i16 and v8i16 to stay within NEON's available 5076 /// 64/128-bit registers. 5077 /// 5078 /// Trace for v4i16: 5079 /// input = [v0 v1 v2 v3 ] (vi 16-bit element) 5080 /// v8i8: BitCounts = [k0 k1 k2 k3 k0 k1 k2 k3 ] (ki is the bit-count of vi) 5081 /// v8i16:Extended = [k0 k1 k2 k3 k0 k1 k2 k3 ] 5082 /// v4i16:Extracted = [k0 k1 k2 k3 ] 5083 static SDValue lowerCTPOP16BitElements(SDNode *N, SelectionDAG &DAG) { 5084 EVT VT = N->getValueType(0); 5085 SDLoc DL(N); 5086 5087 SDValue BitCounts = getCTPOP16BitCounts(N, DAG); 5088 if (VT.is64BitVector()) { 5089 SDValue Extended = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::v8i16, BitCounts); 5090 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v4i16, Extended, 5091 DAG.getIntPtrConstant(0, DL)); 5092 } else { 5093 SDValue Extracted = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v8i8, 5094 BitCounts, DAG.getIntPtrConstant(0, DL)); 5095 return DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::v8i16, Extracted); 5096 } 5097 } 5098 5099 /// lowerCTPOP32BitElements - Returns a v2i32/v4i32 vector containing the 5100 /// bit-count for each 32-bit element from the operand. The idea here is 5101 /// to split the vector into 16-bit elements, leverage the 16-bit count 5102 /// routine, and then combine the results. 5103 /// 5104 /// Trace for v2i32 (v4i32 similar with Extracted/Extended exchanged): 5105 /// input = [v0 v1 ] (vi: 32-bit elements) 5106 /// Bitcast = [w0 w1 w2 w3 ] (wi: 16-bit elements, v0 = [w0 w1]) 5107 /// Counts16 = [k0 k1 k2 k3 ] (ki: 16-bit elements, bit-count of wi) 5108 /// vrev: N0 = [k1 k0 k3 k2 ] 5109 /// [k0 k1 k2 k3 ] 5110 /// N1 =+[k1 k0 k3 k2 ] 5111 /// [k0 k2 k1 k3 ] 5112 /// N2 =+[k1 k3 k0 k2 ] 5113 /// [k0 k2 k1 k3 ] 5114 /// Extended =+[k1 k3 k0 k2 ] 5115 /// [k0 k2 ] 5116 /// Extracted=+[k1 k3 ] 5117 /// 5118 static SDValue lowerCTPOP32BitElements(SDNode *N, SelectionDAG &DAG) { 5119 EVT VT = N->getValueType(0); 5120 SDLoc DL(N); 5121 5122 EVT VT16Bit = VT.is64BitVector() ? MVT::v4i16 : MVT::v8i16; 5123 5124 SDValue Bitcast = DAG.getNode(ISD::BITCAST, DL, VT16Bit, N->getOperand(0)); 5125 SDValue Counts16 = lowerCTPOP16BitElements(Bitcast.getNode(), DAG); 5126 SDValue N0 = DAG.getNode(ARMISD::VREV32, DL, VT16Bit, Counts16); 5127 SDValue N1 = DAG.getNode(ISD::ADD, DL, VT16Bit, Counts16, N0); 5128 SDValue N2 = DAG.getNode(ARMISD::VUZP, DL, VT16Bit, N1, N1); 5129 5130 if (VT.is64BitVector()) { 5131 SDValue Extended = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::v4i32, N2); 5132 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2i32, Extended, 5133 DAG.getIntPtrConstant(0, DL)); 5134 } else { 5135 SDValue Extracted = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v4i16, N2, 5136 DAG.getIntPtrConstant(0, DL)); 5137 return DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::v4i32, Extracted); 5138 } 5139 } 5140 5141 static SDValue LowerCTPOP(SDNode *N, SelectionDAG &DAG, 5142 const ARMSubtarget *ST) { 5143 EVT VT = N->getValueType(0); 5144 5145 assert(ST->hasNEON() && "Custom ctpop lowering requires NEON."); 5146 assert((VT == MVT::v2i32 || VT == MVT::v4i32 || 5147 VT == MVT::v4i16 || VT == MVT::v8i16) && 5148 "Unexpected type for custom ctpop lowering"); 5149 5150 if (VT.getVectorElementType() == MVT::i32) 5151 return lowerCTPOP32BitElements(N, DAG); 5152 else 5153 return lowerCTPOP16BitElements(N, DAG); 5154 } 5155 5156 static SDValue LowerShift(SDNode *N, SelectionDAG &DAG, 5157 const ARMSubtarget *ST) { 5158 EVT VT = N->getValueType(0); 5159 SDLoc dl(N); 5160 5161 if (!VT.isVector()) 5162 return SDValue(); 5163 5164 // Lower vector shifts on NEON to use VSHL. 5165 assert(ST->hasNEON() && "unexpected vector shift"); 5166 5167 // Left shifts translate directly to the vshiftu intrinsic. 5168 if (N->getOpcode() == ISD::SHL) 5169 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT, 5170 DAG.getConstant(Intrinsic::arm_neon_vshiftu, dl, 5171 MVT::i32), 5172 N->getOperand(0), N->getOperand(1)); 5173 5174 assert((N->getOpcode() == ISD::SRA || 5175 N->getOpcode() == ISD::SRL) && "unexpected vector shift opcode"); 5176 5177 // NEON uses the same intrinsics for both left and right shifts. For 5178 // right shifts, the shift amounts are negative, so negate the vector of 5179 // shift amounts. 5180 EVT ShiftVT = N->getOperand(1).getValueType(); 5181 SDValue NegatedCount = DAG.getNode(ISD::SUB, dl, ShiftVT, 5182 getZeroVector(ShiftVT, DAG, dl), 5183 N->getOperand(1)); 5184 Intrinsic::ID vshiftInt = (N->getOpcode() == ISD::SRA ? 5185 Intrinsic::arm_neon_vshifts : 5186 Intrinsic::arm_neon_vshiftu); 5187 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT, 5188 DAG.getConstant(vshiftInt, dl, MVT::i32), 5189 N->getOperand(0), NegatedCount); 5190 } 5191 5192 static SDValue Expand64BitShift(SDNode *N, SelectionDAG &DAG, 5193 const ARMSubtarget *ST) { 5194 EVT VT = N->getValueType(0); 5195 SDLoc dl(N); 5196 5197 // We can get here for a node like i32 = ISD::SHL i32, i64 5198 if (VT != MVT::i64) 5199 return SDValue(); 5200 5201 assert((N->getOpcode() == ISD::SRL || N->getOpcode() == ISD::SRA) && 5202 "Unknown shift to lower!"); 5203 5204 // We only lower SRA, SRL of 1 here, all others use generic lowering. 5205 if (!isOneConstant(N->getOperand(1))) 5206 return SDValue(); 5207 5208 // If we are in thumb mode, we don't have RRX. 5209 if (ST->isThumb1Only()) return SDValue(); 5210 5211 // Okay, we have a 64-bit SRA or SRL of 1. Lower this to an RRX expr. 5212 SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(0), 5213 DAG.getConstant(0, dl, MVT::i32)); 5214 SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(0), 5215 DAG.getConstant(1, dl, MVT::i32)); 5216 5217 // First, build a SRA_FLAG/SRL_FLAG op, which shifts the top part by one and 5218 // captures the result into a carry flag. 5219 unsigned Opc = N->getOpcode() == ISD::SRL ? ARMISD::SRL_FLAG:ARMISD::SRA_FLAG; 5220 Hi = DAG.getNode(Opc, dl, DAG.getVTList(MVT::i32, MVT::Glue), Hi); 5221 5222 // The low part is an ARMISD::RRX operand, which shifts the carry in. 5223 Lo = DAG.getNode(ARMISD::RRX, dl, MVT::i32, Lo, Hi.getValue(1)); 5224 5225 // Merge the pieces into a single i64 value. 5226 return DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Lo, Hi); 5227 } 5228 5229 static SDValue LowerVSETCC(SDValue Op, SelectionDAG &DAG) { 5230 SDValue TmpOp0, TmpOp1; 5231 bool Invert = false; 5232 bool Swap = false; 5233 unsigned Opc = 0; 5234 5235 SDValue Op0 = Op.getOperand(0); 5236 SDValue Op1 = Op.getOperand(1); 5237 SDValue CC = Op.getOperand(2); 5238 EVT CmpVT = Op0.getValueType().changeVectorElementTypeToInteger(); 5239 EVT VT = Op.getValueType(); 5240 ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get(); 5241 SDLoc dl(Op); 5242 5243 if (Op0.getValueType().getVectorElementType() == MVT::i64 && 5244 (SetCCOpcode == ISD::SETEQ || SetCCOpcode == ISD::SETNE)) { 5245 // Special-case integer 64-bit equality comparisons. They aren't legal, 5246 // but they can be lowered with a few vector instructions. 5247 unsigned CmpElements = CmpVT.getVectorNumElements() * 2; 5248 EVT SplitVT = EVT::getVectorVT(*DAG.getContext(), MVT::i32, CmpElements); 5249 SDValue CastOp0 = DAG.getNode(ISD::BITCAST, dl, SplitVT, Op0); 5250 SDValue CastOp1 = DAG.getNode(ISD::BITCAST, dl, SplitVT, Op1); 5251 SDValue Cmp = DAG.getNode(ISD::SETCC, dl, SplitVT, CastOp0, CastOp1, 5252 DAG.getCondCode(ISD::SETEQ)); 5253 SDValue Reversed = DAG.getNode(ARMISD::VREV64, dl, SplitVT, Cmp); 5254 SDValue Merged = DAG.getNode(ISD::AND, dl, SplitVT, Cmp, Reversed); 5255 Merged = DAG.getNode(ISD::BITCAST, dl, CmpVT, Merged); 5256 if (SetCCOpcode == ISD::SETNE) 5257 Merged = DAG.getNOT(dl, Merged, CmpVT); 5258 Merged = DAG.getSExtOrTrunc(Merged, dl, VT); 5259 return Merged; 5260 } 5261 5262 if (CmpVT.getVectorElementType() == MVT::i64) 5263 // 64-bit comparisons are not legal in general. 5264 return SDValue(); 5265 5266 if (Op1.getValueType().isFloatingPoint()) { 5267 switch (SetCCOpcode) { 5268 default: llvm_unreachable("Illegal FP comparison"); 5269 case ISD::SETUNE: 5270 case ISD::SETNE: Invert = true; LLVM_FALLTHROUGH; 5271 case ISD::SETOEQ: 5272 case ISD::SETEQ: Opc = ARMISD::VCEQ; break; 5273 case ISD::SETOLT: 5274 case ISD::SETLT: Swap = true; LLVM_FALLTHROUGH; 5275 case ISD::SETOGT: 5276 case ISD::SETGT: Opc = ARMISD::VCGT; break; 5277 case ISD::SETOLE: 5278 case ISD::SETLE: Swap = true; LLVM_FALLTHROUGH; 5279 case ISD::SETOGE: 5280 case ISD::SETGE: Opc = ARMISD::VCGE; break; 5281 case ISD::SETUGE: Swap = true; LLVM_FALLTHROUGH; 5282 case ISD::SETULE: Invert = true; Opc = ARMISD::VCGT; break; 5283 case ISD::SETUGT: Swap = true; LLVM_FALLTHROUGH; 5284 case ISD::SETULT: Invert = true; Opc = ARMISD::VCGE; break; 5285 case ISD::SETUEQ: Invert = true; LLVM_FALLTHROUGH; 5286 case ISD::SETONE: 5287 // Expand this to (OLT | OGT). 5288 TmpOp0 = Op0; 5289 TmpOp1 = Op1; 5290 Opc = ISD::OR; 5291 Op0 = DAG.getNode(ARMISD::VCGT, dl, CmpVT, TmpOp1, TmpOp0); 5292 Op1 = DAG.getNode(ARMISD::VCGT, dl, CmpVT, TmpOp0, TmpOp1); 5293 break; 5294 case ISD::SETUO: 5295 Invert = true; 5296 LLVM_FALLTHROUGH; 5297 case ISD::SETO: 5298 // Expand this to (OLT | OGE). 5299 TmpOp0 = Op0; 5300 TmpOp1 = Op1; 5301 Opc = ISD::OR; 5302 Op0 = DAG.getNode(ARMISD::VCGT, dl, CmpVT, TmpOp1, TmpOp0); 5303 Op1 = DAG.getNode(ARMISD::VCGE, dl, CmpVT, TmpOp0, TmpOp1); 5304 break; 5305 } 5306 } else { 5307 // Integer comparisons. 5308 switch (SetCCOpcode) { 5309 default: llvm_unreachable("Illegal integer comparison"); 5310 case ISD::SETNE: Invert = true; 5311 case ISD::SETEQ: Opc = ARMISD::VCEQ; break; 5312 case ISD::SETLT: Swap = true; 5313 case ISD::SETGT: Opc = ARMISD::VCGT; break; 5314 case ISD::SETLE: Swap = true; 5315 case ISD::SETGE: Opc = ARMISD::VCGE; break; 5316 case ISD::SETULT: Swap = true; 5317 case ISD::SETUGT: Opc = ARMISD::VCGTU; break; 5318 case ISD::SETULE: Swap = true; 5319 case ISD::SETUGE: Opc = ARMISD::VCGEU; break; 5320 } 5321 5322 // Detect VTST (Vector Test Bits) = icmp ne (and (op0, op1), zero). 5323 if (Opc == ARMISD::VCEQ) { 5324 5325 SDValue AndOp; 5326 if (ISD::isBuildVectorAllZeros(Op1.getNode())) 5327 AndOp = Op0; 5328 else if (ISD::isBuildVectorAllZeros(Op0.getNode())) 5329 AndOp = Op1; 5330 5331 // Ignore bitconvert. 5332 if (AndOp.getNode() && AndOp.getOpcode() == ISD::BITCAST) 5333 AndOp = AndOp.getOperand(0); 5334 5335 if (AndOp.getNode() && AndOp.getOpcode() == ISD::AND) { 5336 Opc = ARMISD::VTST; 5337 Op0 = DAG.getNode(ISD::BITCAST, dl, CmpVT, AndOp.getOperand(0)); 5338 Op1 = DAG.getNode(ISD::BITCAST, dl, CmpVT, AndOp.getOperand(1)); 5339 Invert = !Invert; 5340 } 5341 } 5342 } 5343 5344 if (Swap) 5345 std::swap(Op0, Op1); 5346 5347 // If one of the operands is a constant vector zero, attempt to fold the 5348 // comparison to a specialized compare-against-zero form. 5349 SDValue SingleOp; 5350 if (ISD::isBuildVectorAllZeros(Op1.getNode())) 5351 SingleOp = Op0; 5352 else if (ISD::isBuildVectorAllZeros(Op0.getNode())) { 5353 if (Opc == ARMISD::VCGE) 5354 Opc = ARMISD::VCLEZ; 5355 else if (Opc == ARMISD::VCGT) 5356 Opc = ARMISD::VCLTZ; 5357 SingleOp = Op1; 5358 } 5359 5360 SDValue Result; 5361 if (SingleOp.getNode()) { 5362 switch (Opc) { 5363 case ARMISD::VCEQ: 5364 Result = DAG.getNode(ARMISD::VCEQZ, dl, CmpVT, SingleOp); break; 5365 case ARMISD::VCGE: 5366 Result = DAG.getNode(ARMISD::VCGEZ, dl, CmpVT, SingleOp); break; 5367 case ARMISD::VCLEZ: 5368 Result = DAG.getNode(ARMISD::VCLEZ, dl, CmpVT, SingleOp); break; 5369 case ARMISD::VCGT: 5370 Result = DAG.getNode(ARMISD::VCGTZ, dl, CmpVT, SingleOp); break; 5371 case ARMISD::VCLTZ: 5372 Result = DAG.getNode(ARMISD::VCLTZ, dl, CmpVT, SingleOp); break; 5373 default: 5374 Result = DAG.getNode(Opc, dl, CmpVT, Op0, Op1); 5375 } 5376 } else { 5377 Result = DAG.getNode(Opc, dl, CmpVT, Op0, Op1); 5378 } 5379 5380 Result = DAG.getSExtOrTrunc(Result, dl, VT); 5381 5382 if (Invert) 5383 Result = DAG.getNOT(dl, Result, VT); 5384 5385 return Result; 5386 } 5387 5388 static SDValue LowerSETCCE(SDValue Op, SelectionDAG &DAG) { 5389 SDValue LHS = Op.getOperand(0); 5390 SDValue RHS = Op.getOperand(1); 5391 SDValue Carry = Op.getOperand(2); 5392 SDValue Cond = Op.getOperand(3); 5393 SDLoc DL(Op); 5394 5395 assert(LHS.getSimpleValueType().isInteger() && "SETCCE is integer only."); 5396 5397 assert(Carry.getOpcode() != ISD::CARRY_FALSE); 5398 SDVTList VTs = DAG.getVTList(LHS.getValueType(), MVT::i32); 5399 SDValue Cmp = DAG.getNode(ARMISD::SUBE, DL, VTs, LHS, RHS, Carry); 5400 5401 SDValue FVal = DAG.getConstant(0, DL, MVT::i32); 5402 SDValue TVal = DAG.getConstant(1, DL, MVT::i32); 5403 SDValue ARMcc = DAG.getConstant( 5404 IntCCToARMCC(cast<CondCodeSDNode>(Cond)->get()), DL, MVT::i32); 5405 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32); 5406 SDValue Chain = DAG.getCopyToReg(DAG.getEntryNode(), DL, ARM::CPSR, 5407 Cmp.getValue(1), SDValue()); 5408 return DAG.getNode(ARMISD::CMOV, DL, Op.getValueType(), FVal, TVal, ARMcc, 5409 CCR, Chain.getValue(1)); 5410 } 5411 5412 /// isNEONModifiedImm - Check if the specified splat value corresponds to a 5413 /// valid vector constant for a NEON instruction with a "modified immediate" 5414 /// operand (e.g., VMOV). If so, return the encoded value. 5415 static SDValue isNEONModifiedImm(uint64_t SplatBits, uint64_t SplatUndef, 5416 unsigned SplatBitSize, SelectionDAG &DAG, 5417 const SDLoc &dl, EVT &VT, bool is128Bits, 5418 NEONModImmType type) { 5419 unsigned OpCmode, Imm; 5420 5421 // SplatBitSize is set to the smallest size that splats the vector, so a 5422 // zero vector will always have SplatBitSize == 8. However, NEON modified 5423 // immediate instructions others than VMOV do not support the 8-bit encoding 5424 // of a zero vector, and the default encoding of zero is supposed to be the 5425 // 32-bit version. 5426 if (SplatBits == 0) 5427 SplatBitSize = 32; 5428 5429 switch (SplatBitSize) { 5430 case 8: 5431 if (type != VMOVModImm) 5432 return SDValue(); 5433 // Any 1-byte value is OK. Op=0, Cmode=1110. 5434 assert((SplatBits & ~0xff) == 0 && "one byte splat value is too big"); 5435 OpCmode = 0xe; 5436 Imm = SplatBits; 5437 VT = is128Bits ? MVT::v16i8 : MVT::v8i8; 5438 break; 5439 5440 case 16: 5441 // NEON's 16-bit VMOV supports splat values where only one byte is nonzero. 5442 VT = is128Bits ? MVT::v8i16 : MVT::v4i16; 5443 if ((SplatBits & ~0xff) == 0) { 5444 // Value = 0x00nn: Op=x, Cmode=100x. 5445 OpCmode = 0x8; 5446 Imm = SplatBits; 5447 break; 5448 } 5449 if ((SplatBits & ~0xff00) == 0) { 5450 // Value = 0xnn00: Op=x, Cmode=101x. 5451 OpCmode = 0xa; 5452 Imm = SplatBits >> 8; 5453 break; 5454 } 5455 return SDValue(); 5456 5457 case 32: 5458 // NEON's 32-bit VMOV supports splat values where: 5459 // * only one byte is nonzero, or 5460 // * the least significant byte is 0xff and the second byte is nonzero, or 5461 // * the least significant 2 bytes are 0xff and the third is nonzero. 5462 VT = is128Bits ? MVT::v4i32 : MVT::v2i32; 5463 if ((SplatBits & ~0xff) == 0) { 5464 // Value = 0x000000nn: Op=x, Cmode=000x. 5465 OpCmode = 0; 5466 Imm = SplatBits; 5467 break; 5468 } 5469 if ((SplatBits & ~0xff00) == 0) { 5470 // Value = 0x0000nn00: Op=x, Cmode=001x. 5471 OpCmode = 0x2; 5472 Imm = SplatBits >> 8; 5473 break; 5474 } 5475 if ((SplatBits & ~0xff0000) == 0) { 5476 // Value = 0x00nn0000: Op=x, Cmode=010x. 5477 OpCmode = 0x4; 5478 Imm = SplatBits >> 16; 5479 break; 5480 } 5481 if ((SplatBits & ~0xff000000) == 0) { 5482 // Value = 0xnn000000: Op=x, Cmode=011x. 5483 OpCmode = 0x6; 5484 Imm = SplatBits >> 24; 5485 break; 5486 } 5487 5488 // cmode == 0b1100 and cmode == 0b1101 are not supported for VORR or VBIC 5489 if (type == OtherModImm) return SDValue(); 5490 5491 if ((SplatBits & ~0xffff) == 0 && 5492 ((SplatBits | SplatUndef) & 0xff) == 0xff) { 5493 // Value = 0x0000nnff: Op=x, Cmode=1100. 5494 OpCmode = 0xc; 5495 Imm = SplatBits >> 8; 5496 break; 5497 } 5498 5499 if ((SplatBits & ~0xffffff) == 0 && 5500 ((SplatBits | SplatUndef) & 0xffff) == 0xffff) { 5501 // Value = 0x00nnffff: Op=x, Cmode=1101. 5502 OpCmode = 0xd; 5503 Imm = SplatBits >> 16; 5504 break; 5505 } 5506 5507 // Note: there are a few 32-bit splat values (specifically: 00ffff00, 5508 // ff000000, ff0000ff, and ffff00ff) that are valid for VMOV.I64 but not 5509 // VMOV.I32. A (very) minor optimization would be to replicate the value 5510 // and fall through here to test for a valid 64-bit splat. But, then the 5511 // caller would also need to check and handle the change in size. 5512 return SDValue(); 5513 5514 case 64: { 5515 if (type != VMOVModImm) 5516 return SDValue(); 5517 // NEON has a 64-bit VMOV splat where each byte is either 0 or 0xff. 5518 uint64_t BitMask = 0xff; 5519 uint64_t Val = 0; 5520 unsigned ImmMask = 1; 5521 Imm = 0; 5522 for (int ByteNum = 0; ByteNum < 8; ++ByteNum) { 5523 if (((SplatBits | SplatUndef) & BitMask) == BitMask) { 5524 Val |= BitMask; 5525 Imm |= ImmMask; 5526 } else if ((SplatBits & BitMask) != 0) { 5527 return SDValue(); 5528 } 5529 BitMask <<= 8; 5530 ImmMask <<= 1; 5531 } 5532 5533 if (DAG.getDataLayout().isBigEndian()) 5534 // swap higher and lower 32 bit word 5535 Imm = ((Imm & 0xf) << 4) | ((Imm & 0xf0) >> 4); 5536 5537 // Op=1, Cmode=1110. 5538 OpCmode = 0x1e; 5539 VT = is128Bits ? MVT::v2i64 : MVT::v1i64; 5540 break; 5541 } 5542 5543 default: 5544 llvm_unreachable("unexpected size for isNEONModifiedImm"); 5545 } 5546 5547 unsigned EncodedVal = ARM_AM::createNEONModImm(OpCmode, Imm); 5548 return DAG.getTargetConstant(EncodedVal, dl, MVT::i32); 5549 } 5550 5551 SDValue ARMTargetLowering::LowerConstantFP(SDValue Op, SelectionDAG &DAG, 5552 const ARMSubtarget *ST) const { 5553 bool IsDouble = Op.getValueType() == MVT::f64; 5554 ConstantFPSDNode *CFP = cast<ConstantFPSDNode>(Op); 5555 const APFloat &FPVal = CFP->getValueAPF(); 5556 5557 // Prevent floating-point constants from using literal loads 5558 // when execute-only is enabled. 5559 if (ST->genExecuteOnly()) { 5560 APInt INTVal = FPVal.bitcastToAPInt(); 5561 SDLoc DL(CFP); 5562 if (IsDouble) { 5563 SDValue Lo = DAG.getConstant(INTVal.trunc(32), DL, MVT::i32); 5564 SDValue Hi = DAG.getConstant(INTVal.lshr(32).trunc(32), DL, MVT::i32); 5565 if (!ST->isLittle()) 5566 std::swap(Lo, Hi); 5567 return DAG.getNode(ARMISD::VMOVDRR, DL, MVT::f64, Lo, Hi); 5568 } else { 5569 return DAG.getConstant(INTVal, DL, MVT::i32); 5570 } 5571 } 5572 5573 if (!ST->hasVFP3()) 5574 return SDValue(); 5575 5576 // Use the default (constant pool) lowering for double constants when we have 5577 // an SP-only FPU 5578 if (IsDouble && Subtarget->isFPOnlySP()) 5579 return SDValue(); 5580 5581 // Try splatting with a VMOV.f32... 5582 int ImmVal = IsDouble ? ARM_AM::getFP64Imm(FPVal) : ARM_AM::getFP32Imm(FPVal); 5583 5584 if (ImmVal != -1) { 5585 if (IsDouble || !ST->useNEONForSinglePrecisionFP()) { 5586 // We have code in place to select a valid ConstantFP already, no need to 5587 // do any mangling. 5588 return Op; 5589 } 5590 5591 // It's a float and we are trying to use NEON operations where 5592 // possible. Lower it to a splat followed by an extract. 5593 SDLoc DL(Op); 5594 SDValue NewVal = DAG.getTargetConstant(ImmVal, DL, MVT::i32); 5595 SDValue VecConstant = DAG.getNode(ARMISD::VMOVFPIMM, DL, MVT::v2f32, 5596 NewVal); 5597 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32, VecConstant, 5598 DAG.getConstant(0, DL, MVT::i32)); 5599 } 5600 5601 // The rest of our options are NEON only, make sure that's allowed before 5602 // proceeding.. 5603 if (!ST->hasNEON() || (!IsDouble && !ST->useNEONForSinglePrecisionFP())) 5604 return SDValue(); 5605 5606 EVT VMovVT; 5607 uint64_t iVal = FPVal.bitcastToAPInt().getZExtValue(); 5608 5609 // It wouldn't really be worth bothering for doubles except for one very 5610 // important value, which does happen to match: 0.0. So make sure we don't do 5611 // anything stupid. 5612 if (IsDouble && (iVal & 0xffffffff) != (iVal >> 32)) 5613 return SDValue(); 5614 5615 // Try a VMOV.i32 (FIXME: i8, i16, or i64 could work too). 5616 SDValue NewVal = isNEONModifiedImm(iVal & 0xffffffffU, 0, 32, DAG, SDLoc(Op), 5617 VMovVT, false, VMOVModImm); 5618 if (NewVal != SDValue()) { 5619 SDLoc DL(Op); 5620 SDValue VecConstant = DAG.getNode(ARMISD::VMOVIMM, DL, VMovVT, 5621 NewVal); 5622 if (IsDouble) 5623 return DAG.getNode(ISD::BITCAST, DL, MVT::f64, VecConstant); 5624 5625 // It's a float: cast and extract a vector element. 5626 SDValue VecFConstant = DAG.getNode(ISD::BITCAST, DL, MVT::v2f32, 5627 VecConstant); 5628 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32, VecFConstant, 5629 DAG.getConstant(0, DL, MVT::i32)); 5630 } 5631 5632 // Finally, try a VMVN.i32 5633 NewVal = isNEONModifiedImm(~iVal & 0xffffffffU, 0, 32, DAG, SDLoc(Op), VMovVT, 5634 false, VMVNModImm); 5635 if (NewVal != SDValue()) { 5636 SDLoc DL(Op); 5637 SDValue VecConstant = DAG.getNode(ARMISD::VMVNIMM, DL, VMovVT, NewVal); 5638 5639 if (IsDouble) 5640 return DAG.getNode(ISD::BITCAST, DL, MVT::f64, VecConstant); 5641 5642 // It's a float: cast and extract a vector element. 5643 SDValue VecFConstant = DAG.getNode(ISD::BITCAST, DL, MVT::v2f32, 5644 VecConstant); 5645 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32, VecFConstant, 5646 DAG.getConstant(0, DL, MVT::i32)); 5647 } 5648 5649 return SDValue(); 5650 } 5651 5652 // check if an VEXT instruction can handle the shuffle mask when the 5653 // vector sources of the shuffle are the same. 5654 static bool isSingletonVEXTMask(ArrayRef<int> M, EVT VT, unsigned &Imm) { 5655 unsigned NumElts = VT.getVectorNumElements(); 5656 5657 // Assume that the first shuffle index is not UNDEF. Fail if it is. 5658 if (M[0] < 0) 5659 return false; 5660 5661 Imm = M[0]; 5662 5663 // If this is a VEXT shuffle, the immediate value is the index of the first 5664 // element. The other shuffle indices must be the successive elements after 5665 // the first one. 5666 unsigned ExpectedElt = Imm; 5667 for (unsigned i = 1; i < NumElts; ++i) { 5668 // Increment the expected index. If it wraps around, just follow it 5669 // back to index zero and keep going. 5670 ++ExpectedElt; 5671 if (ExpectedElt == NumElts) 5672 ExpectedElt = 0; 5673 5674 if (M[i] < 0) continue; // ignore UNDEF indices 5675 if (ExpectedElt != static_cast<unsigned>(M[i])) 5676 return false; 5677 } 5678 5679 return true; 5680 } 5681 5682 static bool isVEXTMask(ArrayRef<int> M, EVT VT, 5683 bool &ReverseVEXT, unsigned &Imm) { 5684 unsigned NumElts = VT.getVectorNumElements(); 5685 ReverseVEXT = false; 5686 5687 // Assume that the first shuffle index is not UNDEF. Fail if it is. 5688 if (M[0] < 0) 5689 return false; 5690 5691 Imm = M[0]; 5692 5693 // If this is a VEXT shuffle, the immediate value is the index of the first 5694 // element. The other shuffle indices must be the successive elements after 5695 // the first one. 5696 unsigned ExpectedElt = Imm; 5697 for (unsigned i = 1; i < NumElts; ++i) { 5698 // Increment the expected index. If it wraps around, it may still be 5699 // a VEXT but the source vectors must be swapped. 5700 ExpectedElt += 1; 5701 if (ExpectedElt == NumElts * 2) { 5702 ExpectedElt = 0; 5703 ReverseVEXT = true; 5704 } 5705 5706 if (M[i] < 0) continue; // ignore UNDEF indices 5707 if (ExpectedElt != static_cast<unsigned>(M[i])) 5708 return false; 5709 } 5710 5711 // Adjust the index value if the source operands will be swapped. 5712 if (ReverseVEXT) 5713 Imm -= NumElts; 5714 5715 return true; 5716 } 5717 5718 /// isVREVMask - Check if a vector shuffle corresponds to a VREV 5719 /// instruction with the specified blocksize. (The order of the elements 5720 /// within each block of the vector is reversed.) 5721 static bool isVREVMask(ArrayRef<int> M, EVT VT, unsigned BlockSize) { 5722 assert((BlockSize==16 || BlockSize==32 || BlockSize==64) && 5723 "Only possible block sizes for VREV are: 16, 32, 64"); 5724 5725 unsigned EltSz = VT.getScalarSizeInBits(); 5726 if (EltSz == 64) 5727 return false; 5728 5729 unsigned NumElts = VT.getVectorNumElements(); 5730 unsigned BlockElts = M[0] + 1; 5731 // If the first shuffle index is UNDEF, be optimistic. 5732 if (M[0] < 0) 5733 BlockElts = BlockSize / EltSz; 5734 5735 if (BlockSize <= EltSz || BlockSize != BlockElts * EltSz) 5736 return false; 5737 5738 for (unsigned i = 0; i < NumElts; ++i) { 5739 if (M[i] < 0) continue; // ignore UNDEF indices 5740 if ((unsigned) M[i] != (i - i%BlockElts) + (BlockElts - 1 - i%BlockElts)) 5741 return false; 5742 } 5743 5744 return true; 5745 } 5746 5747 static bool isVTBLMask(ArrayRef<int> M, EVT VT) { 5748 // We can handle <8 x i8> vector shuffles. If the index in the mask is out of 5749 // range, then 0 is placed into the resulting vector. So pretty much any mask 5750 // of 8 elements can work here. 5751 return VT == MVT::v8i8 && M.size() == 8; 5752 } 5753 5754 // Checks whether the shuffle mask represents a vector transpose (VTRN) by 5755 // checking that pairs of elements in the shuffle mask represent the same index 5756 // in each vector, incrementing the expected index by 2 at each step. 5757 // e.g. For v1,v2 of type v4i32 a valid shuffle mask is: [0, 4, 2, 6] 5758 // v1={a,b,c,d} => x=shufflevector v1, v2 shufflemask => x={a,e,c,g} 5759 // v2={e,f,g,h} 5760 // WhichResult gives the offset for each element in the mask based on which 5761 // of the two results it belongs to. 5762 // 5763 // The transpose can be represented either as: 5764 // result1 = shufflevector v1, v2, result1_shuffle_mask 5765 // result2 = shufflevector v1, v2, result2_shuffle_mask 5766 // where v1/v2 and the shuffle masks have the same number of elements 5767 // (here WhichResult (see below) indicates which result is being checked) 5768 // 5769 // or as: 5770 // results = shufflevector v1, v2, shuffle_mask 5771 // where both results are returned in one vector and the shuffle mask has twice 5772 // as many elements as v1/v2 (here WhichResult will always be 0 if true) here we 5773 // want to check the low half and high half of the shuffle mask as if it were 5774 // the other case 5775 static bool isVTRNMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) { 5776 unsigned EltSz = VT.getScalarSizeInBits(); 5777 if (EltSz == 64) 5778 return false; 5779 5780 unsigned NumElts = VT.getVectorNumElements(); 5781 if (M.size() != NumElts && M.size() != NumElts*2) 5782 return false; 5783 5784 // If the mask is twice as long as the input vector then we need to check the 5785 // upper and lower parts of the mask with a matching value for WhichResult 5786 // FIXME: A mask with only even values will be rejected in case the first 5787 // element is undefined, e.g. [-1, 4, 2, 6] will be rejected, because only 5788 // M[0] is used to determine WhichResult 5789 for (unsigned i = 0; i < M.size(); i += NumElts) { 5790 if (M.size() == NumElts * 2) 5791 WhichResult = i / NumElts; 5792 else 5793 WhichResult = M[i] == 0 ? 0 : 1; 5794 for (unsigned j = 0; j < NumElts; j += 2) { 5795 if ((M[i+j] >= 0 && (unsigned) M[i+j] != j + WhichResult) || 5796 (M[i+j+1] >= 0 && (unsigned) M[i+j+1] != j + NumElts + WhichResult)) 5797 return false; 5798 } 5799 } 5800 5801 if (M.size() == NumElts*2) 5802 WhichResult = 0; 5803 5804 return true; 5805 } 5806 5807 /// isVTRN_v_undef_Mask - Special case of isVTRNMask for canonical form of 5808 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef". 5809 /// Mask is e.g., <0, 0, 2, 2> instead of <0, 4, 2, 6>. 5810 static bool isVTRN_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult){ 5811 unsigned EltSz = VT.getScalarSizeInBits(); 5812 if (EltSz == 64) 5813 return false; 5814 5815 unsigned NumElts = VT.getVectorNumElements(); 5816 if (M.size() != NumElts && M.size() != NumElts*2) 5817 return false; 5818 5819 for (unsigned i = 0; i < M.size(); i += NumElts) { 5820 if (M.size() == NumElts * 2) 5821 WhichResult = i / NumElts; 5822 else 5823 WhichResult = M[i] == 0 ? 0 : 1; 5824 for (unsigned j = 0; j < NumElts; j += 2) { 5825 if ((M[i+j] >= 0 && (unsigned) M[i+j] != j + WhichResult) || 5826 (M[i+j+1] >= 0 && (unsigned) M[i+j+1] != j + WhichResult)) 5827 return false; 5828 } 5829 } 5830 5831 if (M.size() == NumElts*2) 5832 WhichResult = 0; 5833 5834 return true; 5835 } 5836 5837 // Checks whether the shuffle mask represents a vector unzip (VUZP) by checking 5838 // that the mask elements are either all even and in steps of size 2 or all odd 5839 // and in steps of size 2. 5840 // e.g. For v1,v2 of type v4i32 a valid shuffle mask is: [0, 2, 4, 6] 5841 // v1={a,b,c,d} => x=shufflevector v1, v2 shufflemask => x={a,c,e,g} 5842 // v2={e,f,g,h} 5843 // Requires similar checks to that of isVTRNMask with 5844 // respect the how results are returned. 5845 static bool isVUZPMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) { 5846 unsigned EltSz = VT.getScalarSizeInBits(); 5847 if (EltSz == 64) 5848 return false; 5849 5850 unsigned NumElts = VT.getVectorNumElements(); 5851 if (M.size() != NumElts && M.size() != NumElts*2) 5852 return false; 5853 5854 for (unsigned i = 0; i < M.size(); i += NumElts) { 5855 WhichResult = M[i] == 0 ? 0 : 1; 5856 for (unsigned j = 0; j < NumElts; ++j) { 5857 if (M[i+j] >= 0 && (unsigned) M[i+j] != 2 * j + WhichResult) 5858 return false; 5859 } 5860 } 5861 5862 if (M.size() == NumElts*2) 5863 WhichResult = 0; 5864 5865 // VUZP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32. 5866 if (VT.is64BitVector() && EltSz == 32) 5867 return false; 5868 5869 return true; 5870 } 5871 5872 /// isVUZP_v_undef_Mask - Special case of isVUZPMask for canonical form of 5873 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef". 5874 /// Mask is e.g., <0, 2, 0, 2> instead of <0, 2, 4, 6>, 5875 static bool isVUZP_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult){ 5876 unsigned EltSz = VT.getScalarSizeInBits(); 5877 if (EltSz == 64) 5878 return false; 5879 5880 unsigned NumElts = VT.getVectorNumElements(); 5881 if (M.size() != NumElts && M.size() != NumElts*2) 5882 return false; 5883 5884 unsigned Half = NumElts / 2; 5885 for (unsigned i = 0; i < M.size(); i += NumElts) { 5886 WhichResult = M[i] == 0 ? 0 : 1; 5887 for (unsigned j = 0; j < NumElts; j += Half) { 5888 unsigned Idx = WhichResult; 5889 for (unsigned k = 0; k < Half; ++k) { 5890 int MIdx = M[i + j + k]; 5891 if (MIdx >= 0 && (unsigned) MIdx != Idx) 5892 return false; 5893 Idx += 2; 5894 } 5895 } 5896 } 5897 5898 if (M.size() == NumElts*2) 5899 WhichResult = 0; 5900 5901 // VUZP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32. 5902 if (VT.is64BitVector() && EltSz == 32) 5903 return false; 5904 5905 return true; 5906 } 5907 5908 // Checks whether the shuffle mask represents a vector zip (VZIP) by checking 5909 // that pairs of elements of the shufflemask represent the same index in each 5910 // vector incrementing sequentially through the vectors. 5911 // e.g. For v1,v2 of type v4i32 a valid shuffle mask is: [0, 4, 1, 5] 5912 // v1={a,b,c,d} => x=shufflevector v1, v2 shufflemask => x={a,e,b,f} 5913 // v2={e,f,g,h} 5914 // Requires similar checks to that of isVTRNMask with respect the how results 5915 // are returned. 5916 static bool isVZIPMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) { 5917 unsigned EltSz = VT.getScalarSizeInBits(); 5918 if (EltSz == 64) 5919 return false; 5920 5921 unsigned NumElts = VT.getVectorNumElements(); 5922 if (M.size() != NumElts && M.size() != NumElts*2) 5923 return false; 5924 5925 for (unsigned i = 0; i < M.size(); i += NumElts) { 5926 WhichResult = M[i] == 0 ? 0 : 1; 5927 unsigned Idx = WhichResult * NumElts / 2; 5928 for (unsigned j = 0; j < NumElts; j += 2) { 5929 if ((M[i+j] >= 0 && (unsigned) M[i+j] != Idx) || 5930 (M[i+j+1] >= 0 && (unsigned) M[i+j+1] != Idx + NumElts)) 5931 return false; 5932 Idx += 1; 5933 } 5934 } 5935 5936 if (M.size() == NumElts*2) 5937 WhichResult = 0; 5938 5939 // VZIP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32. 5940 if (VT.is64BitVector() && EltSz == 32) 5941 return false; 5942 5943 return true; 5944 } 5945 5946 /// isVZIP_v_undef_Mask - Special case of isVZIPMask for canonical form of 5947 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef". 5948 /// Mask is e.g., <0, 0, 1, 1> instead of <0, 4, 1, 5>. 5949 static bool isVZIP_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult){ 5950 unsigned EltSz = VT.getScalarSizeInBits(); 5951 if (EltSz == 64) 5952 return false; 5953 5954 unsigned NumElts = VT.getVectorNumElements(); 5955 if (M.size() != NumElts && M.size() != NumElts*2) 5956 return false; 5957 5958 for (unsigned i = 0; i < M.size(); i += NumElts) { 5959 WhichResult = M[i] == 0 ? 0 : 1; 5960 unsigned Idx = WhichResult * NumElts / 2; 5961 for (unsigned j = 0; j < NumElts; j += 2) { 5962 if ((M[i+j] >= 0 && (unsigned) M[i+j] != Idx) || 5963 (M[i+j+1] >= 0 && (unsigned) M[i+j+1] != Idx)) 5964 return false; 5965 Idx += 1; 5966 } 5967 } 5968 5969 if (M.size() == NumElts*2) 5970 WhichResult = 0; 5971 5972 // VZIP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32. 5973 if (VT.is64BitVector() && EltSz == 32) 5974 return false; 5975 5976 return true; 5977 } 5978 5979 /// Check if \p ShuffleMask is a NEON two-result shuffle (VZIP, VUZP, VTRN), 5980 /// and return the corresponding ARMISD opcode if it is, or 0 if it isn't. 5981 static unsigned isNEONTwoResultShuffleMask(ArrayRef<int> ShuffleMask, EVT VT, 5982 unsigned &WhichResult, 5983 bool &isV_UNDEF) { 5984 isV_UNDEF = false; 5985 if (isVTRNMask(ShuffleMask, VT, WhichResult)) 5986 return ARMISD::VTRN; 5987 if (isVUZPMask(ShuffleMask, VT, WhichResult)) 5988 return ARMISD::VUZP; 5989 if (isVZIPMask(ShuffleMask, VT, WhichResult)) 5990 return ARMISD::VZIP; 5991 5992 isV_UNDEF = true; 5993 if (isVTRN_v_undef_Mask(ShuffleMask, VT, WhichResult)) 5994 return ARMISD::VTRN; 5995 if (isVUZP_v_undef_Mask(ShuffleMask, VT, WhichResult)) 5996 return ARMISD::VUZP; 5997 if (isVZIP_v_undef_Mask(ShuffleMask, VT, WhichResult)) 5998 return ARMISD::VZIP; 5999 6000 return 0; 6001 } 6002 6003 /// \return true if this is a reverse operation on an vector. 6004 static bool isReverseMask(ArrayRef<int> M, EVT VT) { 6005 unsigned NumElts = VT.getVectorNumElements(); 6006 // Make sure the mask has the right size. 6007 if (NumElts != M.size()) 6008 return false; 6009 6010 // Look for <15, ..., 3, -1, 1, 0>. 6011 for (unsigned i = 0; i != NumElts; ++i) 6012 if (M[i] >= 0 && M[i] != (int) (NumElts - 1 - i)) 6013 return false; 6014 6015 return true; 6016 } 6017 6018 // If N is an integer constant that can be moved into a register in one 6019 // instruction, return an SDValue of such a constant (will become a MOV 6020 // instruction). Otherwise return null. 6021 static SDValue IsSingleInstrConstant(SDValue N, SelectionDAG &DAG, 6022 const ARMSubtarget *ST, const SDLoc &dl) { 6023 uint64_t Val; 6024 if (!isa<ConstantSDNode>(N)) 6025 return SDValue(); 6026 Val = cast<ConstantSDNode>(N)->getZExtValue(); 6027 6028 if (ST->isThumb1Only()) { 6029 if (Val <= 255 || ~Val <= 255) 6030 return DAG.getConstant(Val, dl, MVT::i32); 6031 } else { 6032 if (ARM_AM::getSOImmVal(Val) != -1 || ARM_AM::getSOImmVal(~Val) != -1) 6033 return DAG.getConstant(Val, dl, MVT::i32); 6034 } 6035 return SDValue(); 6036 } 6037 6038 // If this is a case we can't handle, return null and let the default 6039 // expansion code take care of it. 6040 SDValue ARMTargetLowering::LowerBUILD_VECTOR(SDValue Op, SelectionDAG &DAG, 6041 const ARMSubtarget *ST) const { 6042 BuildVectorSDNode *BVN = cast<BuildVectorSDNode>(Op.getNode()); 6043 SDLoc dl(Op); 6044 EVT VT = Op.getValueType(); 6045 6046 APInt SplatBits, SplatUndef; 6047 unsigned SplatBitSize; 6048 bool HasAnyUndefs; 6049 if (BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs)) { 6050 if (SplatUndef.isAllOnesValue()) 6051 return DAG.getUNDEF(VT); 6052 6053 if (SplatBitSize <= 64) { 6054 // Check if an immediate VMOV works. 6055 EVT VmovVT; 6056 SDValue Val = isNEONModifiedImm(SplatBits.getZExtValue(), 6057 SplatUndef.getZExtValue(), SplatBitSize, 6058 DAG, dl, VmovVT, VT.is128BitVector(), 6059 VMOVModImm); 6060 if (Val.getNode()) { 6061 SDValue Vmov = DAG.getNode(ARMISD::VMOVIMM, dl, VmovVT, Val); 6062 return DAG.getNode(ISD::BITCAST, dl, VT, Vmov); 6063 } 6064 6065 // Try an immediate VMVN. 6066 uint64_t NegatedImm = (~SplatBits).getZExtValue(); 6067 Val = isNEONModifiedImm(NegatedImm, 6068 SplatUndef.getZExtValue(), SplatBitSize, 6069 DAG, dl, VmovVT, VT.is128BitVector(), 6070 VMVNModImm); 6071 if (Val.getNode()) { 6072 SDValue Vmov = DAG.getNode(ARMISD::VMVNIMM, dl, VmovVT, Val); 6073 return DAG.getNode(ISD::BITCAST, dl, VT, Vmov); 6074 } 6075 6076 // Use vmov.f32 to materialize other v2f32 and v4f32 splats. 6077 if ((VT == MVT::v2f32 || VT == MVT::v4f32) && SplatBitSize == 32) { 6078 int ImmVal = ARM_AM::getFP32Imm(SplatBits); 6079 if (ImmVal != -1) { 6080 SDValue Val = DAG.getTargetConstant(ImmVal, dl, MVT::i32); 6081 return DAG.getNode(ARMISD::VMOVFPIMM, dl, VT, Val); 6082 } 6083 } 6084 } 6085 } 6086 6087 // Scan through the operands to see if only one value is used. 6088 // 6089 // As an optimisation, even if more than one value is used it may be more 6090 // profitable to splat with one value then change some lanes. 6091 // 6092 // Heuristically we decide to do this if the vector has a "dominant" value, 6093 // defined as splatted to more than half of the lanes. 6094 unsigned NumElts = VT.getVectorNumElements(); 6095 bool isOnlyLowElement = true; 6096 bool usesOnlyOneValue = true; 6097 bool hasDominantValue = false; 6098 bool isConstant = true; 6099 6100 // Map of the number of times a particular SDValue appears in the 6101 // element list. 6102 DenseMap<SDValue, unsigned> ValueCounts; 6103 SDValue Value; 6104 for (unsigned i = 0; i < NumElts; ++i) { 6105 SDValue V = Op.getOperand(i); 6106 if (V.isUndef()) 6107 continue; 6108 if (i > 0) 6109 isOnlyLowElement = false; 6110 if (!isa<ConstantFPSDNode>(V) && !isa<ConstantSDNode>(V)) 6111 isConstant = false; 6112 6113 ValueCounts.insert(std::make_pair(V, 0)); 6114 unsigned &Count = ValueCounts[V]; 6115 6116 // Is this value dominant? (takes up more than half of the lanes) 6117 if (++Count > (NumElts / 2)) { 6118 hasDominantValue = true; 6119 Value = V; 6120 } 6121 } 6122 if (ValueCounts.size() != 1) 6123 usesOnlyOneValue = false; 6124 if (!Value.getNode() && !ValueCounts.empty()) 6125 Value = ValueCounts.begin()->first; 6126 6127 if (ValueCounts.empty()) 6128 return DAG.getUNDEF(VT); 6129 6130 // Loads are better lowered with insert_vector_elt/ARMISD::BUILD_VECTOR. 6131 // Keep going if we are hitting this case. 6132 if (isOnlyLowElement && !ISD::isNormalLoad(Value.getNode())) 6133 return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Value); 6134 6135 unsigned EltSize = VT.getScalarSizeInBits(); 6136 6137 // Use VDUP for non-constant splats. For f32 constant splats, reduce to 6138 // i32 and try again. 6139 if (hasDominantValue && EltSize <= 32) { 6140 if (!isConstant) { 6141 SDValue N; 6142 6143 // If we are VDUPing a value that comes directly from a vector, that will 6144 // cause an unnecessary move to and from a GPR, where instead we could 6145 // just use VDUPLANE. We can only do this if the lane being extracted 6146 // is at a constant index, as the VDUP from lane instructions only have 6147 // constant-index forms. 6148 ConstantSDNode *constIndex; 6149 if (Value->getOpcode() == ISD::EXTRACT_VECTOR_ELT && 6150 (constIndex = dyn_cast<ConstantSDNode>(Value->getOperand(1)))) { 6151 // We need to create a new undef vector to use for the VDUPLANE if the 6152 // size of the vector from which we get the value is different than the 6153 // size of the vector that we need to create. We will insert the element 6154 // such that the register coalescer will remove unnecessary copies. 6155 if (VT != Value->getOperand(0).getValueType()) { 6156 unsigned index = constIndex->getAPIntValue().getLimitedValue() % 6157 VT.getVectorNumElements(); 6158 N = DAG.getNode(ARMISD::VDUPLANE, dl, VT, 6159 DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, DAG.getUNDEF(VT), 6160 Value, DAG.getConstant(index, dl, MVT::i32)), 6161 DAG.getConstant(index, dl, MVT::i32)); 6162 } else 6163 N = DAG.getNode(ARMISD::VDUPLANE, dl, VT, 6164 Value->getOperand(0), Value->getOperand(1)); 6165 } else 6166 N = DAG.getNode(ARMISD::VDUP, dl, VT, Value); 6167 6168 if (!usesOnlyOneValue) { 6169 // The dominant value was splatted as 'N', but we now have to insert 6170 // all differing elements. 6171 for (unsigned I = 0; I < NumElts; ++I) { 6172 if (Op.getOperand(I) == Value) 6173 continue; 6174 SmallVector<SDValue, 3> Ops; 6175 Ops.push_back(N); 6176 Ops.push_back(Op.getOperand(I)); 6177 Ops.push_back(DAG.getConstant(I, dl, MVT::i32)); 6178 N = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Ops); 6179 } 6180 } 6181 return N; 6182 } 6183 if (VT.getVectorElementType().isFloatingPoint()) { 6184 SmallVector<SDValue, 8> Ops; 6185 for (unsigned i = 0; i < NumElts; ++i) 6186 Ops.push_back(DAG.getNode(ISD::BITCAST, dl, MVT::i32, 6187 Op.getOperand(i))); 6188 EVT VecVT = EVT::getVectorVT(*DAG.getContext(), MVT::i32, NumElts); 6189 SDValue Val = DAG.getBuildVector(VecVT, dl, Ops); 6190 Val = LowerBUILD_VECTOR(Val, DAG, ST); 6191 if (Val.getNode()) 6192 return DAG.getNode(ISD::BITCAST, dl, VT, Val); 6193 } 6194 if (usesOnlyOneValue) { 6195 SDValue Val = IsSingleInstrConstant(Value, DAG, ST, dl); 6196 if (isConstant && Val.getNode()) 6197 return DAG.getNode(ARMISD::VDUP, dl, VT, Val); 6198 } 6199 } 6200 6201 // If all elements are constants and the case above didn't get hit, fall back 6202 // to the default expansion, which will generate a load from the constant 6203 // pool. 6204 if (isConstant) 6205 return SDValue(); 6206 6207 // Empirical tests suggest this is rarely worth it for vectors of length <= 2. 6208 if (NumElts >= 4) { 6209 SDValue shuffle = ReconstructShuffle(Op, DAG); 6210 if (shuffle != SDValue()) 6211 return shuffle; 6212 } 6213 6214 if (VT.is128BitVector() && VT != MVT::v2f64 && VT != MVT::v4f32) { 6215 // If we haven't found an efficient lowering, try splitting a 128-bit vector 6216 // into two 64-bit vectors; we might discover a better way to lower it. 6217 SmallVector<SDValue, 64> Ops(Op->op_begin(), Op->op_begin() + NumElts); 6218 EVT ExtVT = VT.getVectorElementType(); 6219 EVT HVT = EVT::getVectorVT(*DAG.getContext(), ExtVT, NumElts / 2); 6220 SDValue Lower = 6221 DAG.getBuildVector(HVT, dl, makeArrayRef(&Ops[0], NumElts / 2)); 6222 if (Lower.getOpcode() == ISD::BUILD_VECTOR) 6223 Lower = LowerBUILD_VECTOR(Lower, DAG, ST); 6224 SDValue Upper = DAG.getBuildVector( 6225 HVT, dl, makeArrayRef(&Ops[NumElts / 2], NumElts / 2)); 6226 if (Upper.getOpcode() == ISD::BUILD_VECTOR) 6227 Upper = LowerBUILD_VECTOR(Upper, DAG, ST); 6228 if (Lower && Upper) 6229 return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, Lower, Upper); 6230 } 6231 6232 // Vectors with 32- or 64-bit elements can be built by directly assigning 6233 // the subregisters. Lower it to an ARMISD::BUILD_VECTOR so the operands 6234 // will be legalized. 6235 if (EltSize >= 32) { 6236 // Do the expansion with floating-point types, since that is what the VFP 6237 // registers are defined to use, and since i64 is not legal. 6238 EVT EltVT = EVT::getFloatingPointVT(EltSize); 6239 EVT VecVT = EVT::getVectorVT(*DAG.getContext(), EltVT, NumElts); 6240 SmallVector<SDValue, 8> Ops; 6241 for (unsigned i = 0; i < NumElts; ++i) 6242 Ops.push_back(DAG.getNode(ISD::BITCAST, dl, EltVT, Op.getOperand(i))); 6243 SDValue Val = DAG.getNode(ARMISD::BUILD_VECTOR, dl, VecVT, Ops); 6244 return DAG.getNode(ISD::BITCAST, dl, VT, Val); 6245 } 6246 6247 // If all else fails, just use a sequence of INSERT_VECTOR_ELT when we 6248 // know the default expansion would otherwise fall back on something even 6249 // worse. For a vector with one or two non-undef values, that's 6250 // scalar_to_vector for the elements followed by a shuffle (provided the 6251 // shuffle is valid for the target) and materialization element by element 6252 // on the stack followed by a load for everything else. 6253 if (!isConstant && !usesOnlyOneValue) { 6254 SDValue Vec = DAG.getUNDEF(VT); 6255 for (unsigned i = 0 ; i < NumElts; ++i) { 6256 SDValue V = Op.getOperand(i); 6257 if (V.isUndef()) 6258 continue; 6259 SDValue LaneIdx = DAG.getConstant(i, dl, MVT::i32); 6260 Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Vec, V, LaneIdx); 6261 } 6262 return Vec; 6263 } 6264 6265 return SDValue(); 6266 } 6267 6268 // Gather data to see if the operation can be modelled as a 6269 // shuffle in combination with VEXTs. 6270 SDValue ARMTargetLowering::ReconstructShuffle(SDValue Op, 6271 SelectionDAG &DAG) const { 6272 assert(Op.getOpcode() == ISD::BUILD_VECTOR && "Unknown opcode!"); 6273 SDLoc dl(Op); 6274 EVT VT = Op.getValueType(); 6275 unsigned NumElts = VT.getVectorNumElements(); 6276 6277 struct ShuffleSourceInfo { 6278 SDValue Vec; 6279 unsigned MinElt = std::numeric_limits<unsigned>::max(); 6280 unsigned MaxElt = 0; 6281 6282 // We may insert some combination of BITCASTs and VEXT nodes to force Vec to 6283 // be compatible with the shuffle we intend to construct. As a result 6284 // ShuffleVec will be some sliding window into the original Vec. 6285 SDValue ShuffleVec; 6286 6287 // Code should guarantee that element i in Vec starts at element "WindowBase 6288 // + i * WindowScale in ShuffleVec". 6289 int WindowBase = 0; 6290 int WindowScale = 1; 6291 6292 ShuffleSourceInfo(SDValue Vec) : Vec(Vec), ShuffleVec(Vec) {} 6293 6294 bool operator ==(SDValue OtherVec) { return Vec == OtherVec; } 6295 }; 6296 6297 // First gather all vectors used as an immediate source for this BUILD_VECTOR 6298 // node. 6299 SmallVector<ShuffleSourceInfo, 2> Sources; 6300 for (unsigned i = 0; i < NumElts; ++i) { 6301 SDValue V = Op.getOperand(i); 6302 if (V.isUndef()) 6303 continue; 6304 else if (V.getOpcode() != ISD::EXTRACT_VECTOR_ELT) { 6305 // A shuffle can only come from building a vector from various 6306 // elements of other vectors. 6307 return SDValue(); 6308 } else if (!isa<ConstantSDNode>(V.getOperand(1))) { 6309 // Furthermore, shuffles require a constant mask, whereas extractelts 6310 // accept variable indices. 6311 return SDValue(); 6312 } 6313 6314 // Add this element source to the list if it's not already there. 6315 SDValue SourceVec = V.getOperand(0); 6316 auto Source = llvm::find(Sources, SourceVec); 6317 if (Source == Sources.end()) 6318 Source = Sources.insert(Sources.end(), ShuffleSourceInfo(SourceVec)); 6319 6320 // Update the minimum and maximum lane number seen. 6321 unsigned EltNo = cast<ConstantSDNode>(V.getOperand(1))->getZExtValue(); 6322 Source->MinElt = std::min(Source->MinElt, EltNo); 6323 Source->MaxElt = std::max(Source->MaxElt, EltNo); 6324 } 6325 6326 // Currently only do something sane when at most two source vectors 6327 // are involved. 6328 if (Sources.size() > 2) 6329 return SDValue(); 6330 6331 // Find out the smallest element size among result and two sources, and use 6332 // it as element size to build the shuffle_vector. 6333 EVT SmallestEltTy = VT.getVectorElementType(); 6334 for (auto &Source : Sources) { 6335 EVT SrcEltTy = Source.Vec.getValueType().getVectorElementType(); 6336 if (SrcEltTy.bitsLT(SmallestEltTy)) 6337 SmallestEltTy = SrcEltTy; 6338 } 6339 unsigned ResMultiplier = 6340 VT.getScalarSizeInBits() / SmallestEltTy.getSizeInBits(); 6341 NumElts = VT.getSizeInBits() / SmallestEltTy.getSizeInBits(); 6342 EVT ShuffleVT = EVT::getVectorVT(*DAG.getContext(), SmallestEltTy, NumElts); 6343 6344 // If the source vector is too wide or too narrow, we may nevertheless be able 6345 // to construct a compatible shuffle either by concatenating it with UNDEF or 6346 // extracting a suitable range of elements. 6347 for (auto &Src : Sources) { 6348 EVT SrcVT = Src.ShuffleVec.getValueType(); 6349 6350 if (SrcVT.getSizeInBits() == VT.getSizeInBits()) 6351 continue; 6352 6353 // This stage of the search produces a source with the same element type as 6354 // the original, but with a total width matching the BUILD_VECTOR output. 6355 EVT EltVT = SrcVT.getVectorElementType(); 6356 unsigned NumSrcElts = VT.getSizeInBits() / EltVT.getSizeInBits(); 6357 EVT DestVT = EVT::getVectorVT(*DAG.getContext(), EltVT, NumSrcElts); 6358 6359 if (SrcVT.getSizeInBits() < VT.getSizeInBits()) { 6360 if (2 * SrcVT.getSizeInBits() != VT.getSizeInBits()) 6361 return SDValue(); 6362 // We can pad out the smaller vector for free, so if it's part of a 6363 // shuffle... 6364 Src.ShuffleVec = 6365 DAG.getNode(ISD::CONCAT_VECTORS, dl, DestVT, Src.ShuffleVec, 6366 DAG.getUNDEF(Src.ShuffleVec.getValueType())); 6367 continue; 6368 } 6369 6370 if (SrcVT.getSizeInBits() != 2 * VT.getSizeInBits()) 6371 return SDValue(); 6372 6373 if (Src.MaxElt - Src.MinElt >= NumSrcElts) { 6374 // Span too large for a VEXT to cope 6375 return SDValue(); 6376 } 6377 6378 if (Src.MinElt >= NumSrcElts) { 6379 // The extraction can just take the second half 6380 Src.ShuffleVec = 6381 DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DestVT, Src.ShuffleVec, 6382 DAG.getConstant(NumSrcElts, dl, MVT::i32)); 6383 Src.WindowBase = -NumSrcElts; 6384 } else if (Src.MaxElt < NumSrcElts) { 6385 // The extraction can just take the first half 6386 Src.ShuffleVec = 6387 DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DestVT, Src.ShuffleVec, 6388 DAG.getConstant(0, dl, MVT::i32)); 6389 } else { 6390 // An actual VEXT is needed 6391 SDValue VEXTSrc1 = 6392 DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DestVT, Src.ShuffleVec, 6393 DAG.getConstant(0, dl, MVT::i32)); 6394 SDValue VEXTSrc2 = 6395 DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DestVT, Src.ShuffleVec, 6396 DAG.getConstant(NumSrcElts, dl, MVT::i32)); 6397 6398 Src.ShuffleVec = DAG.getNode(ARMISD::VEXT, dl, DestVT, VEXTSrc1, 6399 VEXTSrc2, 6400 DAG.getConstant(Src.MinElt, dl, MVT::i32)); 6401 Src.WindowBase = -Src.MinElt; 6402 } 6403 } 6404 6405 // Another possible incompatibility occurs from the vector element types. We 6406 // can fix this by bitcasting the source vectors to the same type we intend 6407 // for the shuffle. 6408 for (auto &Src : Sources) { 6409 EVT SrcEltTy = Src.ShuffleVec.getValueType().getVectorElementType(); 6410 if (SrcEltTy == SmallestEltTy) 6411 continue; 6412 assert(ShuffleVT.getVectorElementType() == SmallestEltTy); 6413 Src.ShuffleVec = DAG.getNode(ISD::BITCAST, dl, ShuffleVT, Src.ShuffleVec); 6414 Src.WindowScale = SrcEltTy.getSizeInBits() / SmallestEltTy.getSizeInBits(); 6415 Src.WindowBase *= Src.WindowScale; 6416 } 6417 6418 // Final sanity check before we try to actually produce a shuffle. 6419 DEBUG( 6420 for (auto Src : Sources) 6421 assert(Src.ShuffleVec.getValueType() == ShuffleVT); 6422 ); 6423 6424 // The stars all align, our next step is to produce the mask for the shuffle. 6425 SmallVector<int, 8> Mask(ShuffleVT.getVectorNumElements(), -1); 6426 int BitsPerShuffleLane = ShuffleVT.getScalarSizeInBits(); 6427 for (unsigned i = 0; i < VT.getVectorNumElements(); ++i) { 6428 SDValue Entry = Op.getOperand(i); 6429 if (Entry.isUndef()) 6430 continue; 6431 6432 auto Src = llvm::find(Sources, Entry.getOperand(0)); 6433 int EltNo = cast<ConstantSDNode>(Entry.getOperand(1))->getSExtValue(); 6434 6435 // EXTRACT_VECTOR_ELT performs an implicit any_ext; BUILD_VECTOR an implicit 6436 // trunc. So only std::min(SrcBits, DestBits) actually get defined in this 6437 // segment. 6438 EVT OrigEltTy = Entry.getOperand(0).getValueType().getVectorElementType(); 6439 int BitsDefined = std::min(OrigEltTy.getSizeInBits(), 6440 VT.getScalarSizeInBits()); 6441 int LanesDefined = BitsDefined / BitsPerShuffleLane; 6442 6443 // This source is expected to fill ResMultiplier lanes of the final shuffle, 6444 // starting at the appropriate offset. 6445 int *LaneMask = &Mask[i * ResMultiplier]; 6446 6447 int ExtractBase = EltNo * Src->WindowScale + Src->WindowBase; 6448 ExtractBase += NumElts * (Src - Sources.begin()); 6449 for (int j = 0; j < LanesDefined; ++j) 6450 LaneMask[j] = ExtractBase + j; 6451 } 6452 6453 // Final check before we try to produce nonsense... 6454 if (!isShuffleMaskLegal(Mask, ShuffleVT)) 6455 return SDValue(); 6456 6457 // We can't handle more than two sources. This should have already 6458 // been checked before this point. 6459 assert(Sources.size() <= 2 && "Too many sources!"); 6460 6461 SDValue ShuffleOps[] = { DAG.getUNDEF(ShuffleVT), DAG.getUNDEF(ShuffleVT) }; 6462 for (unsigned i = 0; i < Sources.size(); ++i) 6463 ShuffleOps[i] = Sources[i].ShuffleVec; 6464 6465 SDValue Shuffle = DAG.getVectorShuffle(ShuffleVT, dl, ShuffleOps[0], 6466 ShuffleOps[1], Mask); 6467 return DAG.getNode(ISD::BITCAST, dl, VT, Shuffle); 6468 } 6469 6470 /// isShuffleMaskLegal - Targets can use this to indicate that they only 6471 /// support *some* VECTOR_SHUFFLE operations, those with specific masks. 6472 /// By default, if a target supports the VECTOR_SHUFFLE node, all mask values 6473 /// are assumed to be legal. 6474 bool 6475 ARMTargetLowering::isShuffleMaskLegal(const SmallVectorImpl<int> &M, 6476 EVT VT) const { 6477 if (VT.getVectorNumElements() == 4 && 6478 (VT.is128BitVector() || VT.is64BitVector())) { 6479 unsigned PFIndexes[4]; 6480 for (unsigned i = 0; i != 4; ++i) { 6481 if (M[i] < 0) 6482 PFIndexes[i] = 8; 6483 else 6484 PFIndexes[i] = M[i]; 6485 } 6486 6487 // Compute the index in the perfect shuffle table. 6488 unsigned PFTableIndex = 6489 PFIndexes[0]*9*9*9+PFIndexes[1]*9*9+PFIndexes[2]*9+PFIndexes[3]; 6490 unsigned PFEntry = PerfectShuffleTable[PFTableIndex]; 6491 unsigned Cost = (PFEntry >> 30); 6492 6493 if (Cost <= 4) 6494 return true; 6495 } 6496 6497 bool ReverseVEXT, isV_UNDEF; 6498 unsigned Imm, WhichResult; 6499 6500 unsigned EltSize = VT.getScalarSizeInBits(); 6501 return (EltSize >= 32 || 6502 ShuffleVectorSDNode::isSplatMask(&M[0], VT) || 6503 isVREVMask(M, VT, 64) || 6504 isVREVMask(M, VT, 32) || 6505 isVREVMask(M, VT, 16) || 6506 isVEXTMask(M, VT, ReverseVEXT, Imm) || 6507 isVTBLMask(M, VT) || 6508 isNEONTwoResultShuffleMask(M, VT, WhichResult, isV_UNDEF) || 6509 ((VT == MVT::v8i16 || VT == MVT::v16i8) && isReverseMask(M, VT))); 6510 } 6511 6512 /// GeneratePerfectShuffle - Given an entry in the perfect-shuffle table, emit 6513 /// the specified operations to build the shuffle. 6514 static SDValue GeneratePerfectShuffle(unsigned PFEntry, SDValue LHS, 6515 SDValue RHS, SelectionDAG &DAG, 6516 const SDLoc &dl) { 6517 unsigned OpNum = (PFEntry >> 26) & 0x0F; 6518 unsigned LHSID = (PFEntry >> 13) & ((1 << 13)-1); 6519 unsigned RHSID = (PFEntry >> 0) & ((1 << 13)-1); 6520 6521 enum { 6522 OP_COPY = 0, // Copy, used for things like <u,u,u,3> to say it is <0,1,2,3> 6523 OP_VREV, 6524 OP_VDUP0, 6525 OP_VDUP1, 6526 OP_VDUP2, 6527 OP_VDUP3, 6528 OP_VEXT1, 6529 OP_VEXT2, 6530 OP_VEXT3, 6531 OP_VUZPL, // VUZP, left result 6532 OP_VUZPR, // VUZP, right result 6533 OP_VZIPL, // VZIP, left result 6534 OP_VZIPR, // VZIP, right result 6535 OP_VTRNL, // VTRN, left result 6536 OP_VTRNR // VTRN, right result 6537 }; 6538 6539 if (OpNum == OP_COPY) { 6540 if (LHSID == (1*9+2)*9+3) return LHS; 6541 assert(LHSID == ((4*9+5)*9+6)*9+7 && "Illegal OP_COPY!"); 6542 return RHS; 6543 } 6544 6545 SDValue OpLHS, OpRHS; 6546 OpLHS = GeneratePerfectShuffle(PerfectShuffleTable[LHSID], LHS, RHS, DAG, dl); 6547 OpRHS = GeneratePerfectShuffle(PerfectShuffleTable[RHSID], LHS, RHS, DAG, dl); 6548 EVT VT = OpLHS.getValueType(); 6549 6550 switch (OpNum) { 6551 default: llvm_unreachable("Unknown shuffle opcode!"); 6552 case OP_VREV: 6553 // VREV divides the vector in half and swaps within the half. 6554 if (VT.getVectorElementType() == MVT::i32 || 6555 VT.getVectorElementType() == MVT::f32) 6556 return DAG.getNode(ARMISD::VREV64, dl, VT, OpLHS); 6557 // vrev <4 x i16> -> VREV32 6558 if (VT.getVectorElementType() == MVT::i16) 6559 return DAG.getNode(ARMISD::VREV32, dl, VT, OpLHS); 6560 // vrev <4 x i8> -> VREV16 6561 assert(VT.getVectorElementType() == MVT::i8); 6562 return DAG.getNode(ARMISD::VREV16, dl, VT, OpLHS); 6563 case OP_VDUP0: 6564 case OP_VDUP1: 6565 case OP_VDUP2: 6566 case OP_VDUP3: 6567 return DAG.getNode(ARMISD::VDUPLANE, dl, VT, 6568 OpLHS, DAG.getConstant(OpNum-OP_VDUP0, dl, MVT::i32)); 6569 case OP_VEXT1: 6570 case OP_VEXT2: 6571 case OP_VEXT3: 6572 return DAG.getNode(ARMISD::VEXT, dl, VT, 6573 OpLHS, OpRHS, 6574 DAG.getConstant(OpNum - OP_VEXT1 + 1, dl, MVT::i32)); 6575 case OP_VUZPL: 6576 case OP_VUZPR: 6577 return DAG.getNode(ARMISD::VUZP, dl, DAG.getVTList(VT, VT), 6578 OpLHS, OpRHS).getValue(OpNum-OP_VUZPL); 6579 case OP_VZIPL: 6580 case OP_VZIPR: 6581 return DAG.getNode(ARMISD::VZIP, dl, DAG.getVTList(VT, VT), 6582 OpLHS, OpRHS).getValue(OpNum-OP_VZIPL); 6583 case OP_VTRNL: 6584 case OP_VTRNR: 6585 return DAG.getNode(ARMISD::VTRN, dl, DAG.getVTList(VT, VT), 6586 OpLHS, OpRHS).getValue(OpNum-OP_VTRNL); 6587 } 6588 } 6589 6590 static SDValue LowerVECTOR_SHUFFLEv8i8(SDValue Op, 6591 ArrayRef<int> ShuffleMask, 6592 SelectionDAG &DAG) { 6593 // Check to see if we can use the VTBL instruction. 6594 SDValue V1 = Op.getOperand(0); 6595 SDValue V2 = Op.getOperand(1); 6596 SDLoc DL(Op); 6597 6598 SmallVector<SDValue, 8> VTBLMask; 6599 for (ArrayRef<int>::iterator 6600 I = ShuffleMask.begin(), E = ShuffleMask.end(); I != E; ++I) 6601 VTBLMask.push_back(DAG.getConstant(*I, DL, MVT::i32)); 6602 6603 if (V2.getNode()->isUndef()) 6604 return DAG.getNode(ARMISD::VTBL1, DL, MVT::v8i8, V1, 6605 DAG.getBuildVector(MVT::v8i8, DL, VTBLMask)); 6606 6607 return DAG.getNode(ARMISD::VTBL2, DL, MVT::v8i8, V1, V2, 6608 DAG.getBuildVector(MVT::v8i8, DL, VTBLMask)); 6609 } 6610 6611 static SDValue LowerReverse_VECTOR_SHUFFLEv16i8_v8i16(SDValue Op, 6612 SelectionDAG &DAG) { 6613 SDLoc DL(Op); 6614 SDValue OpLHS = Op.getOperand(0); 6615 EVT VT = OpLHS.getValueType(); 6616 6617 assert((VT == MVT::v8i16 || VT == MVT::v16i8) && 6618 "Expect an v8i16/v16i8 type"); 6619 OpLHS = DAG.getNode(ARMISD::VREV64, DL, VT, OpLHS); 6620 // For a v16i8 type: After the VREV, we have got <8, ...15, 8, ..., 0>. Now, 6621 // extract the first 8 bytes into the top double word and the last 8 bytes 6622 // into the bottom double word. The v8i16 case is similar. 6623 unsigned ExtractNum = (VT == MVT::v16i8) ? 8 : 4; 6624 return DAG.getNode(ARMISD::VEXT, DL, VT, OpLHS, OpLHS, 6625 DAG.getConstant(ExtractNum, DL, MVT::i32)); 6626 } 6627 6628 static SDValue LowerVECTOR_SHUFFLE(SDValue Op, SelectionDAG &DAG) { 6629 SDValue V1 = Op.getOperand(0); 6630 SDValue V2 = Op.getOperand(1); 6631 SDLoc dl(Op); 6632 EVT VT = Op.getValueType(); 6633 ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(Op.getNode()); 6634 6635 // Convert shuffles that are directly supported on NEON to target-specific 6636 // DAG nodes, instead of keeping them as shuffles and matching them again 6637 // during code selection. This is more efficient and avoids the possibility 6638 // of inconsistencies between legalization and selection. 6639 // FIXME: floating-point vectors should be canonicalized to integer vectors 6640 // of the same time so that they get CSEd properly. 6641 ArrayRef<int> ShuffleMask = SVN->getMask(); 6642 6643 unsigned EltSize = VT.getScalarSizeInBits(); 6644 if (EltSize <= 32) { 6645 if (SVN->isSplat()) { 6646 int Lane = SVN->getSplatIndex(); 6647 // If this is undef splat, generate it via "just" vdup, if possible. 6648 if (Lane == -1) Lane = 0; 6649 6650 // Test if V1 is a SCALAR_TO_VECTOR. 6651 if (Lane == 0 && V1.getOpcode() == ISD::SCALAR_TO_VECTOR) { 6652 return DAG.getNode(ARMISD::VDUP, dl, VT, V1.getOperand(0)); 6653 } 6654 // Test if V1 is a BUILD_VECTOR which is equivalent to a SCALAR_TO_VECTOR 6655 // (and probably will turn into a SCALAR_TO_VECTOR once legalization 6656 // reaches it). 6657 if (Lane == 0 && V1.getOpcode() == ISD::BUILD_VECTOR && 6658 !isa<ConstantSDNode>(V1.getOperand(0))) { 6659 bool IsScalarToVector = true; 6660 for (unsigned i = 1, e = V1.getNumOperands(); i != e; ++i) 6661 if (!V1.getOperand(i).isUndef()) { 6662 IsScalarToVector = false; 6663 break; 6664 } 6665 if (IsScalarToVector) 6666 return DAG.getNode(ARMISD::VDUP, dl, VT, V1.getOperand(0)); 6667 } 6668 return DAG.getNode(ARMISD::VDUPLANE, dl, VT, V1, 6669 DAG.getConstant(Lane, dl, MVT::i32)); 6670 } 6671 6672 bool ReverseVEXT; 6673 unsigned Imm; 6674 if (isVEXTMask(ShuffleMask, VT, ReverseVEXT, Imm)) { 6675 if (ReverseVEXT) 6676 std::swap(V1, V2); 6677 return DAG.getNode(ARMISD::VEXT, dl, VT, V1, V2, 6678 DAG.getConstant(Imm, dl, MVT::i32)); 6679 } 6680 6681 if (isVREVMask(ShuffleMask, VT, 64)) 6682 return DAG.getNode(ARMISD::VREV64, dl, VT, V1); 6683 if (isVREVMask(ShuffleMask, VT, 32)) 6684 return DAG.getNode(ARMISD::VREV32, dl, VT, V1); 6685 if (isVREVMask(ShuffleMask, VT, 16)) 6686 return DAG.getNode(ARMISD::VREV16, dl, VT, V1); 6687 6688 if (V2->isUndef() && isSingletonVEXTMask(ShuffleMask, VT, Imm)) { 6689 return DAG.getNode(ARMISD::VEXT, dl, VT, V1, V1, 6690 DAG.getConstant(Imm, dl, MVT::i32)); 6691 } 6692 6693 // Check for Neon shuffles that modify both input vectors in place. 6694 // If both results are used, i.e., if there are two shuffles with the same 6695 // source operands and with masks corresponding to both results of one of 6696 // these operations, DAG memoization will ensure that a single node is 6697 // used for both shuffles. 6698 unsigned WhichResult; 6699 bool isV_UNDEF; 6700 if (unsigned ShuffleOpc = isNEONTwoResultShuffleMask( 6701 ShuffleMask, VT, WhichResult, isV_UNDEF)) { 6702 if (isV_UNDEF) 6703 V2 = V1; 6704 return DAG.getNode(ShuffleOpc, dl, DAG.getVTList(VT, VT), V1, V2) 6705 .getValue(WhichResult); 6706 } 6707 6708 // Also check for these shuffles through CONCAT_VECTORS: we canonicalize 6709 // shuffles that produce a result larger than their operands with: 6710 // shuffle(concat(v1, undef), concat(v2, undef)) 6711 // -> 6712 // shuffle(concat(v1, v2), undef) 6713 // because we can access quad vectors (see PerformVECTOR_SHUFFLECombine). 6714 // 6715 // This is useful in the general case, but there are special cases where 6716 // native shuffles produce larger results: the two-result ops. 6717 // 6718 // Look through the concat when lowering them: 6719 // shuffle(concat(v1, v2), undef) 6720 // -> 6721 // concat(VZIP(v1, v2):0, :1) 6722 // 6723 if (V1->getOpcode() == ISD::CONCAT_VECTORS && V2->isUndef()) { 6724 SDValue SubV1 = V1->getOperand(0); 6725 SDValue SubV2 = V1->getOperand(1); 6726 EVT SubVT = SubV1.getValueType(); 6727 6728 // We expect these to have been canonicalized to -1. 6729 assert(llvm::all_of(ShuffleMask, [&](int i) { 6730 return i < (int)VT.getVectorNumElements(); 6731 }) && "Unexpected shuffle index into UNDEF operand!"); 6732 6733 if (unsigned ShuffleOpc = isNEONTwoResultShuffleMask( 6734 ShuffleMask, SubVT, WhichResult, isV_UNDEF)) { 6735 if (isV_UNDEF) 6736 SubV2 = SubV1; 6737 assert((WhichResult == 0) && 6738 "In-place shuffle of concat can only have one result!"); 6739 SDValue Res = DAG.getNode(ShuffleOpc, dl, DAG.getVTList(SubVT, SubVT), 6740 SubV1, SubV2); 6741 return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, Res.getValue(0), 6742 Res.getValue(1)); 6743 } 6744 } 6745 } 6746 6747 // If the shuffle is not directly supported and it has 4 elements, use 6748 // the PerfectShuffle-generated table to synthesize it from other shuffles. 6749 unsigned NumElts = VT.getVectorNumElements(); 6750 if (NumElts == 4) { 6751 unsigned PFIndexes[4]; 6752 for (unsigned i = 0; i != 4; ++i) { 6753 if (ShuffleMask[i] < 0) 6754 PFIndexes[i] = 8; 6755 else 6756 PFIndexes[i] = ShuffleMask[i]; 6757 } 6758 6759 // Compute the index in the perfect shuffle table. 6760 unsigned PFTableIndex = 6761 PFIndexes[0]*9*9*9+PFIndexes[1]*9*9+PFIndexes[2]*9+PFIndexes[3]; 6762 unsigned PFEntry = PerfectShuffleTable[PFTableIndex]; 6763 unsigned Cost = (PFEntry >> 30); 6764 6765 if (Cost <= 4) 6766 return GeneratePerfectShuffle(PFEntry, V1, V2, DAG, dl); 6767 } 6768 6769 // Implement shuffles with 32- or 64-bit elements as ARMISD::BUILD_VECTORs. 6770 if (EltSize >= 32) { 6771 // Do the expansion with floating-point types, since that is what the VFP 6772 // registers are defined to use, and since i64 is not legal. 6773 EVT EltVT = EVT::getFloatingPointVT(EltSize); 6774 EVT VecVT = EVT::getVectorVT(*DAG.getContext(), EltVT, NumElts); 6775 V1 = DAG.getNode(ISD::BITCAST, dl, VecVT, V1); 6776 V2 = DAG.getNode(ISD::BITCAST, dl, VecVT, V2); 6777 SmallVector<SDValue, 8> Ops; 6778 for (unsigned i = 0; i < NumElts; ++i) { 6779 if (ShuffleMask[i] < 0) 6780 Ops.push_back(DAG.getUNDEF(EltVT)); 6781 else 6782 Ops.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, EltVT, 6783 ShuffleMask[i] < (int)NumElts ? V1 : V2, 6784 DAG.getConstant(ShuffleMask[i] & (NumElts-1), 6785 dl, MVT::i32))); 6786 } 6787 SDValue Val = DAG.getNode(ARMISD::BUILD_VECTOR, dl, VecVT, Ops); 6788 return DAG.getNode(ISD::BITCAST, dl, VT, Val); 6789 } 6790 6791 if ((VT == MVT::v8i16 || VT == MVT::v16i8) && isReverseMask(ShuffleMask, VT)) 6792 return LowerReverse_VECTOR_SHUFFLEv16i8_v8i16(Op, DAG); 6793 6794 if (VT == MVT::v8i8) 6795 if (SDValue NewOp = LowerVECTOR_SHUFFLEv8i8(Op, ShuffleMask, DAG)) 6796 return NewOp; 6797 6798 return SDValue(); 6799 } 6800 6801 static SDValue LowerINSERT_VECTOR_ELT(SDValue Op, SelectionDAG &DAG) { 6802 // INSERT_VECTOR_ELT is legal only for immediate indexes. 6803 SDValue Lane = Op.getOperand(2); 6804 if (!isa<ConstantSDNode>(Lane)) 6805 return SDValue(); 6806 6807 return Op; 6808 } 6809 6810 static SDValue LowerEXTRACT_VECTOR_ELT(SDValue Op, SelectionDAG &DAG) { 6811 // EXTRACT_VECTOR_ELT is legal only for immediate indexes. 6812 SDValue Lane = Op.getOperand(1); 6813 if (!isa<ConstantSDNode>(Lane)) 6814 return SDValue(); 6815 6816 SDValue Vec = Op.getOperand(0); 6817 if (Op.getValueType() == MVT::i32 && Vec.getScalarValueSizeInBits() < 32) { 6818 SDLoc dl(Op); 6819 return DAG.getNode(ARMISD::VGETLANEu, dl, MVT::i32, Vec, Lane); 6820 } 6821 6822 return Op; 6823 } 6824 6825 static SDValue LowerCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG) { 6826 // The only time a CONCAT_VECTORS operation can have legal types is when 6827 // two 64-bit vectors are concatenated to a 128-bit vector. 6828 assert(Op.getValueType().is128BitVector() && Op.getNumOperands() == 2 && 6829 "unexpected CONCAT_VECTORS"); 6830 SDLoc dl(Op); 6831 SDValue Val = DAG.getUNDEF(MVT::v2f64); 6832 SDValue Op0 = Op.getOperand(0); 6833 SDValue Op1 = Op.getOperand(1); 6834 if (!Op0.isUndef()) 6835 Val = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Val, 6836 DAG.getNode(ISD::BITCAST, dl, MVT::f64, Op0), 6837 DAG.getIntPtrConstant(0, dl)); 6838 if (!Op1.isUndef()) 6839 Val = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Val, 6840 DAG.getNode(ISD::BITCAST, dl, MVT::f64, Op1), 6841 DAG.getIntPtrConstant(1, dl)); 6842 return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Val); 6843 } 6844 6845 /// isExtendedBUILD_VECTOR - Check if N is a constant BUILD_VECTOR where each 6846 /// element has been zero/sign-extended, depending on the isSigned parameter, 6847 /// from an integer type half its size. 6848 static bool isExtendedBUILD_VECTOR(SDNode *N, SelectionDAG &DAG, 6849 bool isSigned) { 6850 // A v2i64 BUILD_VECTOR will have been legalized to a BITCAST from v4i32. 6851 EVT VT = N->getValueType(0); 6852 if (VT == MVT::v2i64 && N->getOpcode() == ISD::BITCAST) { 6853 SDNode *BVN = N->getOperand(0).getNode(); 6854 if (BVN->getValueType(0) != MVT::v4i32 || 6855 BVN->getOpcode() != ISD::BUILD_VECTOR) 6856 return false; 6857 unsigned LoElt = DAG.getDataLayout().isBigEndian() ? 1 : 0; 6858 unsigned HiElt = 1 - LoElt; 6859 ConstantSDNode *Lo0 = dyn_cast<ConstantSDNode>(BVN->getOperand(LoElt)); 6860 ConstantSDNode *Hi0 = dyn_cast<ConstantSDNode>(BVN->getOperand(HiElt)); 6861 ConstantSDNode *Lo1 = dyn_cast<ConstantSDNode>(BVN->getOperand(LoElt+2)); 6862 ConstantSDNode *Hi1 = dyn_cast<ConstantSDNode>(BVN->getOperand(HiElt+2)); 6863 if (!Lo0 || !Hi0 || !Lo1 || !Hi1) 6864 return false; 6865 if (isSigned) { 6866 if (Hi0->getSExtValue() == Lo0->getSExtValue() >> 32 && 6867 Hi1->getSExtValue() == Lo1->getSExtValue() >> 32) 6868 return true; 6869 } else { 6870 if (Hi0->isNullValue() && Hi1->isNullValue()) 6871 return true; 6872 } 6873 return false; 6874 } 6875 6876 if (N->getOpcode() != ISD::BUILD_VECTOR) 6877 return false; 6878 6879 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) { 6880 SDNode *Elt = N->getOperand(i).getNode(); 6881 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Elt)) { 6882 unsigned EltSize = VT.getScalarSizeInBits(); 6883 unsigned HalfSize = EltSize / 2; 6884 if (isSigned) { 6885 if (!isIntN(HalfSize, C->getSExtValue())) 6886 return false; 6887 } else { 6888 if (!isUIntN(HalfSize, C->getZExtValue())) 6889 return false; 6890 } 6891 continue; 6892 } 6893 return false; 6894 } 6895 6896 return true; 6897 } 6898 6899 /// isSignExtended - Check if a node is a vector value that is sign-extended 6900 /// or a constant BUILD_VECTOR with sign-extended elements. 6901 static bool isSignExtended(SDNode *N, SelectionDAG &DAG) { 6902 if (N->getOpcode() == ISD::SIGN_EXTEND || ISD::isSEXTLoad(N)) 6903 return true; 6904 if (isExtendedBUILD_VECTOR(N, DAG, true)) 6905 return true; 6906 return false; 6907 } 6908 6909 /// isZeroExtended - Check if a node is a vector value that is zero-extended 6910 /// or a constant BUILD_VECTOR with zero-extended elements. 6911 static bool isZeroExtended(SDNode *N, SelectionDAG &DAG) { 6912 if (N->getOpcode() == ISD::ZERO_EXTEND || ISD::isZEXTLoad(N)) 6913 return true; 6914 if (isExtendedBUILD_VECTOR(N, DAG, false)) 6915 return true; 6916 return false; 6917 } 6918 6919 static EVT getExtensionTo64Bits(const EVT &OrigVT) { 6920 if (OrigVT.getSizeInBits() >= 64) 6921 return OrigVT; 6922 6923 assert(OrigVT.isSimple() && "Expecting a simple value type"); 6924 6925 MVT::SimpleValueType OrigSimpleTy = OrigVT.getSimpleVT().SimpleTy; 6926 switch (OrigSimpleTy) { 6927 default: llvm_unreachable("Unexpected Vector Type"); 6928 case MVT::v2i8: 6929 case MVT::v2i16: 6930 return MVT::v2i32; 6931 case MVT::v4i8: 6932 return MVT::v4i16; 6933 } 6934 } 6935 6936 /// AddRequiredExtensionForVMULL - Add a sign/zero extension to extend the total 6937 /// value size to 64 bits. We need a 64-bit D register as an operand to VMULL. 6938 /// We insert the required extension here to get the vector to fill a D register. 6939 static SDValue AddRequiredExtensionForVMULL(SDValue N, SelectionDAG &DAG, 6940 const EVT &OrigTy, 6941 const EVT &ExtTy, 6942 unsigned ExtOpcode) { 6943 // The vector originally had a size of OrigTy. It was then extended to ExtTy. 6944 // We expect the ExtTy to be 128-bits total. If the OrigTy is less than 6945 // 64-bits we need to insert a new extension so that it will be 64-bits. 6946 assert(ExtTy.is128BitVector() && "Unexpected extension size"); 6947 if (OrigTy.getSizeInBits() >= 64) 6948 return N; 6949 6950 // Must extend size to at least 64 bits to be used as an operand for VMULL. 6951 EVT NewVT = getExtensionTo64Bits(OrigTy); 6952 6953 return DAG.getNode(ExtOpcode, SDLoc(N), NewVT, N); 6954 } 6955 6956 /// SkipLoadExtensionForVMULL - return a load of the original vector size that 6957 /// does not do any sign/zero extension. If the original vector is less 6958 /// than 64 bits, an appropriate extension will be added after the load to 6959 /// reach a total size of 64 bits. We have to add the extension separately 6960 /// because ARM does not have a sign/zero extending load for vectors. 6961 static SDValue SkipLoadExtensionForVMULL(LoadSDNode *LD, SelectionDAG& DAG) { 6962 EVT ExtendedTy = getExtensionTo64Bits(LD->getMemoryVT()); 6963 6964 // The load already has the right type. 6965 if (ExtendedTy == LD->getMemoryVT()) 6966 return DAG.getLoad(LD->getMemoryVT(), SDLoc(LD), LD->getChain(), 6967 LD->getBasePtr(), LD->getPointerInfo(), 6968 LD->getAlignment(), LD->getMemOperand()->getFlags()); 6969 6970 // We need to create a zextload/sextload. We cannot just create a load 6971 // followed by a zext/zext node because LowerMUL is also run during normal 6972 // operation legalization where we can't create illegal types. 6973 return DAG.getExtLoad(LD->getExtensionType(), SDLoc(LD), ExtendedTy, 6974 LD->getChain(), LD->getBasePtr(), LD->getPointerInfo(), 6975 LD->getMemoryVT(), LD->getAlignment(), 6976 LD->getMemOperand()->getFlags()); 6977 } 6978 6979 /// SkipExtensionForVMULL - For a node that is a SIGN_EXTEND, ZERO_EXTEND, 6980 /// extending load, or BUILD_VECTOR with extended elements, return the 6981 /// unextended value. The unextended vector should be 64 bits so that it can 6982 /// be used as an operand to a VMULL instruction. If the original vector size 6983 /// before extension is less than 64 bits we add a an extension to resize 6984 /// the vector to 64 bits. 6985 static SDValue SkipExtensionForVMULL(SDNode *N, SelectionDAG &DAG) { 6986 if (N->getOpcode() == ISD::SIGN_EXTEND || N->getOpcode() == ISD::ZERO_EXTEND) 6987 return AddRequiredExtensionForVMULL(N->getOperand(0), DAG, 6988 N->getOperand(0)->getValueType(0), 6989 N->getValueType(0), 6990 N->getOpcode()); 6991 6992 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) 6993 return SkipLoadExtensionForVMULL(LD, DAG); 6994 6995 // Otherwise, the value must be a BUILD_VECTOR. For v2i64, it will 6996 // have been legalized as a BITCAST from v4i32. 6997 if (N->getOpcode() == ISD::BITCAST) { 6998 SDNode *BVN = N->getOperand(0).getNode(); 6999 assert(BVN->getOpcode() == ISD::BUILD_VECTOR && 7000 BVN->getValueType(0) == MVT::v4i32 && "expected v4i32 BUILD_VECTOR"); 7001 unsigned LowElt = DAG.getDataLayout().isBigEndian() ? 1 : 0; 7002 return DAG.getBuildVector( 7003 MVT::v2i32, SDLoc(N), 7004 {BVN->getOperand(LowElt), BVN->getOperand(LowElt + 2)}); 7005 } 7006 // Construct a new BUILD_VECTOR with elements truncated to half the size. 7007 assert(N->getOpcode() == ISD::BUILD_VECTOR && "expected BUILD_VECTOR"); 7008 EVT VT = N->getValueType(0); 7009 unsigned EltSize = VT.getScalarSizeInBits() / 2; 7010 unsigned NumElts = VT.getVectorNumElements(); 7011 MVT TruncVT = MVT::getIntegerVT(EltSize); 7012 SmallVector<SDValue, 8> Ops; 7013 SDLoc dl(N); 7014 for (unsigned i = 0; i != NumElts; ++i) { 7015 ConstantSDNode *C = cast<ConstantSDNode>(N->getOperand(i)); 7016 const APInt &CInt = C->getAPIntValue(); 7017 // Element types smaller than 32 bits are not legal, so use i32 elements. 7018 // The values are implicitly truncated so sext vs. zext doesn't matter. 7019 Ops.push_back(DAG.getConstant(CInt.zextOrTrunc(32), dl, MVT::i32)); 7020 } 7021 return DAG.getBuildVector(MVT::getVectorVT(TruncVT, NumElts), dl, Ops); 7022 } 7023 7024 static bool isAddSubSExt(SDNode *N, SelectionDAG &DAG) { 7025 unsigned Opcode = N->getOpcode(); 7026 if (Opcode == ISD::ADD || Opcode == ISD::SUB) { 7027 SDNode *N0 = N->getOperand(0).getNode(); 7028 SDNode *N1 = N->getOperand(1).getNode(); 7029 return N0->hasOneUse() && N1->hasOneUse() && 7030 isSignExtended(N0, DAG) && isSignExtended(N1, DAG); 7031 } 7032 return false; 7033 } 7034 7035 static bool isAddSubZExt(SDNode *N, SelectionDAG &DAG) { 7036 unsigned Opcode = N->getOpcode(); 7037 if (Opcode == ISD::ADD || Opcode == ISD::SUB) { 7038 SDNode *N0 = N->getOperand(0).getNode(); 7039 SDNode *N1 = N->getOperand(1).getNode(); 7040 return N0->hasOneUse() && N1->hasOneUse() && 7041 isZeroExtended(N0, DAG) && isZeroExtended(N1, DAG); 7042 } 7043 return false; 7044 } 7045 7046 static SDValue LowerMUL(SDValue Op, SelectionDAG &DAG) { 7047 // Multiplications are only custom-lowered for 128-bit vectors so that 7048 // VMULL can be detected. Otherwise v2i64 multiplications are not legal. 7049 EVT VT = Op.getValueType(); 7050 assert(VT.is128BitVector() && VT.isInteger() && 7051 "unexpected type for custom-lowering ISD::MUL"); 7052 SDNode *N0 = Op.getOperand(0).getNode(); 7053 SDNode *N1 = Op.getOperand(1).getNode(); 7054 unsigned NewOpc = 0; 7055 bool isMLA = false; 7056 bool isN0SExt = isSignExtended(N0, DAG); 7057 bool isN1SExt = isSignExtended(N1, DAG); 7058 if (isN0SExt && isN1SExt) 7059 NewOpc = ARMISD::VMULLs; 7060 else { 7061 bool isN0ZExt = isZeroExtended(N0, DAG); 7062 bool isN1ZExt = isZeroExtended(N1, DAG); 7063 if (isN0ZExt && isN1ZExt) 7064 NewOpc = ARMISD::VMULLu; 7065 else if (isN1SExt || isN1ZExt) { 7066 // Look for (s/zext A + s/zext B) * (s/zext C). We want to turn these 7067 // into (s/zext A * s/zext C) + (s/zext B * s/zext C) 7068 if (isN1SExt && isAddSubSExt(N0, DAG)) { 7069 NewOpc = ARMISD::VMULLs; 7070 isMLA = true; 7071 } else if (isN1ZExt && isAddSubZExt(N0, DAG)) { 7072 NewOpc = ARMISD::VMULLu; 7073 isMLA = true; 7074 } else if (isN0ZExt && isAddSubZExt(N1, DAG)) { 7075 std::swap(N0, N1); 7076 NewOpc = ARMISD::VMULLu; 7077 isMLA = true; 7078 } 7079 } 7080 7081 if (!NewOpc) { 7082 if (VT == MVT::v2i64) 7083 // Fall through to expand this. It is not legal. 7084 return SDValue(); 7085 else 7086 // Other vector multiplications are legal. 7087 return Op; 7088 } 7089 } 7090 7091 // Legalize to a VMULL instruction. 7092 SDLoc DL(Op); 7093 SDValue Op0; 7094 SDValue Op1 = SkipExtensionForVMULL(N1, DAG); 7095 if (!isMLA) { 7096 Op0 = SkipExtensionForVMULL(N0, DAG); 7097 assert(Op0.getValueType().is64BitVector() && 7098 Op1.getValueType().is64BitVector() && 7099 "unexpected types for extended operands to VMULL"); 7100 return DAG.getNode(NewOpc, DL, VT, Op0, Op1); 7101 } 7102 7103 // Optimizing (zext A + zext B) * C, to (VMULL A, C) + (VMULL B, C) during 7104 // isel lowering to take advantage of no-stall back to back vmul + vmla. 7105 // vmull q0, d4, d6 7106 // vmlal q0, d5, d6 7107 // is faster than 7108 // vaddl q0, d4, d5 7109 // vmovl q1, d6 7110 // vmul q0, q0, q1 7111 SDValue N00 = SkipExtensionForVMULL(N0->getOperand(0).getNode(), DAG); 7112 SDValue N01 = SkipExtensionForVMULL(N0->getOperand(1).getNode(), DAG); 7113 EVT Op1VT = Op1.getValueType(); 7114 return DAG.getNode(N0->getOpcode(), DL, VT, 7115 DAG.getNode(NewOpc, DL, VT, 7116 DAG.getNode(ISD::BITCAST, DL, Op1VT, N00), Op1), 7117 DAG.getNode(NewOpc, DL, VT, 7118 DAG.getNode(ISD::BITCAST, DL, Op1VT, N01), Op1)); 7119 } 7120 7121 static SDValue LowerSDIV_v4i8(SDValue X, SDValue Y, const SDLoc &dl, 7122 SelectionDAG &DAG) { 7123 // TODO: Should this propagate fast-math-flags? 7124 7125 // Convert to float 7126 // float4 xf = vcvt_f32_s32(vmovl_s16(a.lo)); 7127 // float4 yf = vcvt_f32_s32(vmovl_s16(b.lo)); 7128 X = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, X); 7129 Y = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, Y); 7130 X = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, X); 7131 Y = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, Y); 7132 // Get reciprocal estimate. 7133 // float4 recip = vrecpeq_f32(yf); 7134 Y = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32, 7135 DAG.getConstant(Intrinsic::arm_neon_vrecpe, dl, MVT::i32), 7136 Y); 7137 // Because char has a smaller range than uchar, we can actually get away 7138 // without any newton steps. This requires that we use a weird bias 7139 // of 0xb000, however (again, this has been exhaustively tested). 7140 // float4 result = as_float4(as_int4(xf*recip) + 0xb000); 7141 X = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, X, Y); 7142 X = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, X); 7143 Y = DAG.getConstant(0xb000, dl, MVT::v4i32); 7144 X = DAG.getNode(ISD::ADD, dl, MVT::v4i32, X, Y); 7145 X = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, X); 7146 // Convert back to short. 7147 X = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::v4i32, X); 7148 X = DAG.getNode(ISD::TRUNCATE, dl, MVT::v4i16, X); 7149 return X; 7150 } 7151 7152 static SDValue LowerSDIV_v4i16(SDValue N0, SDValue N1, const SDLoc &dl, 7153 SelectionDAG &DAG) { 7154 // TODO: Should this propagate fast-math-flags? 7155 7156 SDValue N2; 7157 // Convert to float. 7158 // float4 yf = vcvt_f32_s32(vmovl_s16(y)); 7159 // float4 xf = vcvt_f32_s32(vmovl_s16(x)); 7160 N0 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, N0); 7161 N1 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, N1); 7162 N0 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N0); 7163 N1 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N1); 7164 7165 // Use reciprocal estimate and one refinement step. 7166 // float4 recip = vrecpeq_f32(yf); 7167 // recip *= vrecpsq_f32(yf, recip); 7168 N2 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32, 7169 DAG.getConstant(Intrinsic::arm_neon_vrecpe, dl, MVT::i32), 7170 N1); 7171 N1 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32, 7172 DAG.getConstant(Intrinsic::arm_neon_vrecps, dl, MVT::i32), 7173 N1, N2); 7174 N2 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N1, N2); 7175 // Because short has a smaller range than ushort, we can actually get away 7176 // with only a single newton step. This requires that we use a weird bias 7177 // of 89, however (again, this has been exhaustively tested). 7178 // float4 result = as_float4(as_int4(xf*recip) + 0x89); 7179 N0 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N0, N2); 7180 N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, N0); 7181 N1 = DAG.getConstant(0x89, dl, MVT::v4i32); 7182 N0 = DAG.getNode(ISD::ADD, dl, MVT::v4i32, N0, N1); 7183 N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, N0); 7184 // Convert back to integer and return. 7185 // return vmovn_s32(vcvt_s32_f32(result)); 7186 N0 = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::v4i32, N0); 7187 N0 = DAG.getNode(ISD::TRUNCATE, dl, MVT::v4i16, N0); 7188 return N0; 7189 } 7190 7191 static SDValue LowerSDIV(SDValue Op, SelectionDAG &DAG) { 7192 EVT VT = Op.getValueType(); 7193 assert((VT == MVT::v4i16 || VT == MVT::v8i8) && 7194 "unexpected type for custom-lowering ISD::SDIV"); 7195 7196 SDLoc dl(Op); 7197 SDValue N0 = Op.getOperand(0); 7198 SDValue N1 = Op.getOperand(1); 7199 SDValue N2, N3; 7200 7201 if (VT == MVT::v8i8) { 7202 N0 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v8i16, N0); 7203 N1 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v8i16, N1); 7204 7205 N2 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0, 7206 DAG.getIntPtrConstant(4, dl)); 7207 N3 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1, 7208 DAG.getIntPtrConstant(4, dl)); 7209 N0 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0, 7210 DAG.getIntPtrConstant(0, dl)); 7211 N1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1, 7212 DAG.getIntPtrConstant(0, dl)); 7213 7214 N0 = LowerSDIV_v4i8(N0, N1, dl, DAG); // v4i16 7215 N2 = LowerSDIV_v4i8(N2, N3, dl, DAG); // v4i16 7216 7217 N0 = DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v8i16, N0, N2); 7218 N0 = LowerCONCAT_VECTORS(N0, DAG); 7219 7220 N0 = DAG.getNode(ISD::TRUNCATE, dl, MVT::v8i8, N0); 7221 return N0; 7222 } 7223 return LowerSDIV_v4i16(N0, N1, dl, DAG); 7224 } 7225 7226 static SDValue LowerUDIV(SDValue Op, SelectionDAG &DAG) { 7227 // TODO: Should this propagate fast-math-flags? 7228 EVT VT = Op.getValueType(); 7229 assert((VT == MVT::v4i16 || VT == MVT::v8i8) && 7230 "unexpected type for custom-lowering ISD::UDIV"); 7231 7232 SDLoc dl(Op); 7233 SDValue N0 = Op.getOperand(0); 7234 SDValue N1 = Op.getOperand(1); 7235 SDValue N2, N3; 7236 7237 if (VT == MVT::v8i8) { 7238 N0 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v8i16, N0); 7239 N1 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v8i16, N1); 7240 7241 N2 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0, 7242 DAG.getIntPtrConstant(4, dl)); 7243 N3 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1, 7244 DAG.getIntPtrConstant(4, dl)); 7245 N0 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0, 7246 DAG.getIntPtrConstant(0, dl)); 7247 N1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1, 7248 DAG.getIntPtrConstant(0, dl)); 7249 7250 N0 = LowerSDIV_v4i16(N0, N1, dl, DAG); // v4i16 7251 N2 = LowerSDIV_v4i16(N2, N3, dl, DAG); // v4i16 7252 7253 N0 = DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v8i16, N0, N2); 7254 N0 = LowerCONCAT_VECTORS(N0, DAG); 7255 7256 N0 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v8i8, 7257 DAG.getConstant(Intrinsic::arm_neon_vqmovnsu, dl, 7258 MVT::i32), 7259 N0); 7260 return N0; 7261 } 7262 7263 // v4i16 sdiv ... Convert to float. 7264 // float4 yf = vcvt_f32_s32(vmovl_u16(y)); 7265 // float4 xf = vcvt_f32_s32(vmovl_u16(x)); 7266 N0 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v4i32, N0); 7267 N1 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v4i32, N1); 7268 N0 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N0); 7269 SDValue BN1 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N1); 7270 7271 // Use reciprocal estimate and two refinement steps. 7272 // float4 recip = vrecpeq_f32(yf); 7273 // recip *= vrecpsq_f32(yf, recip); 7274 // recip *= vrecpsq_f32(yf, recip); 7275 N2 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32, 7276 DAG.getConstant(Intrinsic::arm_neon_vrecpe, dl, MVT::i32), 7277 BN1); 7278 N1 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32, 7279 DAG.getConstant(Intrinsic::arm_neon_vrecps, dl, MVT::i32), 7280 BN1, N2); 7281 N2 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N1, N2); 7282 N1 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32, 7283 DAG.getConstant(Intrinsic::arm_neon_vrecps, dl, MVT::i32), 7284 BN1, N2); 7285 N2 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N1, N2); 7286 // Simply multiplying by the reciprocal estimate can leave us a few ulps 7287 // too low, so we add 2 ulps (exhaustive testing shows that this is enough, 7288 // and that it will never cause us to return an answer too large). 7289 // float4 result = as_float4(as_int4(xf*recip) + 2); 7290 N0 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N0, N2); 7291 N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, N0); 7292 N1 = DAG.getConstant(2, dl, MVT::v4i32); 7293 N0 = DAG.getNode(ISD::ADD, dl, MVT::v4i32, N0, N1); 7294 N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, N0); 7295 // Convert back to integer and return. 7296 // return vmovn_u32(vcvt_s32_f32(result)); 7297 N0 = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::v4i32, N0); 7298 N0 = DAG.getNode(ISD::TRUNCATE, dl, MVT::v4i16, N0); 7299 return N0; 7300 } 7301 7302 static SDValue LowerADDC_ADDE_SUBC_SUBE(SDValue Op, SelectionDAG &DAG) { 7303 EVT VT = Op.getNode()->getValueType(0); 7304 SDVTList VTs = DAG.getVTList(VT, MVT::i32); 7305 7306 unsigned Opc; 7307 bool ExtraOp = false; 7308 switch (Op.getOpcode()) { 7309 default: llvm_unreachable("Invalid code"); 7310 case ISD::ADDC: Opc = ARMISD::ADDC; break; 7311 case ISD::ADDE: Opc = ARMISD::ADDE; ExtraOp = true; break; 7312 case ISD::SUBC: Opc = ARMISD::SUBC; break; 7313 case ISD::SUBE: Opc = ARMISD::SUBE; ExtraOp = true; break; 7314 } 7315 7316 if (!ExtraOp) 7317 return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0), 7318 Op.getOperand(1)); 7319 return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0), 7320 Op.getOperand(1), Op.getOperand(2)); 7321 } 7322 7323 SDValue ARMTargetLowering::LowerFSINCOS(SDValue Op, SelectionDAG &DAG) const { 7324 assert(Subtarget->isTargetDarwin()); 7325 7326 // For iOS, we want to call an alternative entry point: __sincos_stret, 7327 // return values are passed via sret. 7328 SDLoc dl(Op); 7329 SDValue Arg = Op.getOperand(0); 7330 EVT ArgVT = Arg.getValueType(); 7331 Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext()); 7332 auto PtrVT = getPointerTy(DAG.getDataLayout()); 7333 7334 MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo(); 7335 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 7336 7337 // Pair of floats / doubles used to pass the result. 7338 Type *RetTy = StructType::get(ArgTy, ArgTy, nullptr); 7339 auto &DL = DAG.getDataLayout(); 7340 7341 ArgListTy Args; 7342 bool ShouldUseSRet = Subtarget->isAPCS_ABI(); 7343 SDValue SRet; 7344 if (ShouldUseSRet) { 7345 // Create stack object for sret. 7346 const uint64_t ByteSize = DL.getTypeAllocSize(RetTy); 7347 const unsigned StackAlign = DL.getPrefTypeAlignment(RetTy); 7348 int FrameIdx = MFI.CreateStackObject(ByteSize, StackAlign, false); 7349 SRet = DAG.getFrameIndex(FrameIdx, TLI.getPointerTy(DL)); 7350 7351 ArgListEntry Entry; 7352 Entry.Node = SRet; 7353 Entry.Ty = RetTy->getPointerTo(); 7354 Entry.IsSExt = false; 7355 Entry.IsZExt = false; 7356 Entry.IsSRet = true; 7357 Args.push_back(Entry); 7358 RetTy = Type::getVoidTy(*DAG.getContext()); 7359 } 7360 7361 ArgListEntry Entry; 7362 Entry.Node = Arg; 7363 Entry.Ty = ArgTy; 7364 Entry.IsSExt = false; 7365 Entry.IsZExt = false; 7366 Args.push_back(Entry); 7367 7368 const char *LibcallName = 7369 (ArgVT == MVT::f64) ? "__sincos_stret" : "__sincosf_stret"; 7370 RTLIB::Libcall LC = 7371 (ArgVT == MVT::f64) ? RTLIB::SINCOS_F64 : RTLIB::SINCOS_F32; 7372 CallingConv::ID CC = getLibcallCallingConv(LC); 7373 SDValue Callee = DAG.getExternalSymbol(LibcallName, getPointerTy(DL)); 7374 7375 TargetLowering::CallLoweringInfo CLI(DAG); 7376 CLI.setDebugLoc(dl) 7377 .setChain(DAG.getEntryNode()) 7378 .setCallee(CC, RetTy, Callee, std::move(Args)) 7379 .setDiscardResult(ShouldUseSRet); 7380 std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI); 7381 7382 if (!ShouldUseSRet) 7383 return CallResult.first; 7384 7385 SDValue LoadSin = 7386 DAG.getLoad(ArgVT, dl, CallResult.second, SRet, MachinePointerInfo()); 7387 7388 // Address of cos field. 7389 SDValue Add = DAG.getNode(ISD::ADD, dl, PtrVT, SRet, 7390 DAG.getIntPtrConstant(ArgVT.getStoreSize(), dl)); 7391 SDValue LoadCos = 7392 DAG.getLoad(ArgVT, dl, LoadSin.getValue(1), Add, MachinePointerInfo()); 7393 7394 SDVTList Tys = DAG.getVTList(ArgVT, ArgVT); 7395 return DAG.getNode(ISD::MERGE_VALUES, dl, Tys, 7396 LoadSin.getValue(0), LoadCos.getValue(0)); 7397 } 7398 7399 SDValue ARMTargetLowering::LowerWindowsDIVLibCall(SDValue Op, SelectionDAG &DAG, 7400 bool Signed, 7401 SDValue &Chain) const { 7402 EVT VT = Op.getValueType(); 7403 assert((VT == MVT::i32 || VT == MVT::i64) && 7404 "unexpected type for custom lowering DIV"); 7405 SDLoc dl(Op); 7406 7407 const auto &DL = DAG.getDataLayout(); 7408 const auto &TLI = DAG.getTargetLoweringInfo(); 7409 7410 const char *Name = nullptr; 7411 if (Signed) 7412 Name = (VT == MVT::i32) ? "__rt_sdiv" : "__rt_sdiv64"; 7413 else 7414 Name = (VT == MVT::i32) ? "__rt_udiv" : "__rt_udiv64"; 7415 7416 SDValue ES = DAG.getExternalSymbol(Name, TLI.getPointerTy(DL)); 7417 7418 ARMTargetLowering::ArgListTy Args; 7419 7420 for (auto AI : {1, 0}) { 7421 ArgListEntry Arg; 7422 Arg.Node = Op.getOperand(AI); 7423 Arg.Ty = Arg.Node.getValueType().getTypeForEVT(*DAG.getContext()); 7424 Args.push_back(Arg); 7425 } 7426 7427 CallLoweringInfo CLI(DAG); 7428 CLI.setDebugLoc(dl) 7429 .setChain(Chain) 7430 .setCallee(CallingConv::ARM_AAPCS_VFP, VT.getTypeForEVT(*DAG.getContext()), 7431 ES, std::move(Args)); 7432 7433 return LowerCallTo(CLI).first; 7434 } 7435 7436 SDValue ARMTargetLowering::LowerDIV_Windows(SDValue Op, SelectionDAG &DAG, 7437 bool Signed) const { 7438 assert(Op.getValueType() == MVT::i32 && 7439 "unexpected type for custom lowering DIV"); 7440 SDLoc dl(Op); 7441 7442 SDValue DBZCHK = DAG.getNode(ARMISD::WIN__DBZCHK, dl, MVT::Other, 7443 DAG.getEntryNode(), Op.getOperand(1)); 7444 7445 return LowerWindowsDIVLibCall(Op, DAG, Signed, DBZCHK); 7446 } 7447 7448 static SDValue WinDBZCheckDenominator(SelectionDAG &DAG, SDNode *N, SDValue InChain) { 7449 SDLoc DL(N); 7450 SDValue Op = N->getOperand(1); 7451 if (N->getValueType(0) == MVT::i32) 7452 return DAG.getNode(ARMISD::WIN__DBZCHK, DL, MVT::Other, InChain, Op); 7453 SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, Op, 7454 DAG.getConstant(0, DL, MVT::i32)); 7455 SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, Op, 7456 DAG.getConstant(1, DL, MVT::i32)); 7457 return DAG.getNode(ARMISD::WIN__DBZCHK, DL, MVT::Other, InChain, 7458 DAG.getNode(ISD::OR, DL, MVT::i32, Lo, Hi)); 7459 } 7460 7461 void ARMTargetLowering::ExpandDIV_Windows( 7462 SDValue Op, SelectionDAG &DAG, bool Signed, 7463 SmallVectorImpl<SDValue> &Results) const { 7464 const auto &DL = DAG.getDataLayout(); 7465 const auto &TLI = DAG.getTargetLoweringInfo(); 7466 7467 assert(Op.getValueType() == MVT::i64 && 7468 "unexpected type for custom lowering DIV"); 7469 SDLoc dl(Op); 7470 7471 SDValue DBZCHK = WinDBZCheckDenominator(DAG, Op.getNode(), DAG.getEntryNode()); 7472 7473 SDValue Result = LowerWindowsDIVLibCall(Op, DAG, Signed, DBZCHK); 7474 7475 SDValue Lower = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, Result); 7476 SDValue Upper = DAG.getNode(ISD::SRL, dl, MVT::i64, Result, 7477 DAG.getConstant(32, dl, TLI.getPointerTy(DL))); 7478 Upper = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, Upper); 7479 7480 Results.push_back(Lower); 7481 Results.push_back(Upper); 7482 } 7483 7484 static SDValue LowerAtomicLoadStore(SDValue Op, SelectionDAG &DAG) { 7485 if (isStrongerThanMonotonic(cast<AtomicSDNode>(Op)->getOrdering())) 7486 // Acquire/Release load/store is not legal for targets without a dmb or 7487 // equivalent available. 7488 return SDValue(); 7489 7490 // Monotonic load/store is legal for all targets. 7491 return Op; 7492 } 7493 7494 static void ReplaceREADCYCLECOUNTER(SDNode *N, 7495 SmallVectorImpl<SDValue> &Results, 7496 SelectionDAG &DAG, 7497 const ARMSubtarget *Subtarget) { 7498 SDLoc DL(N); 7499 // Under Power Management extensions, the cycle-count is: 7500 // mrc p15, #0, <Rt>, c9, c13, #0 7501 SDValue Ops[] = { N->getOperand(0), // Chain 7502 DAG.getConstant(Intrinsic::arm_mrc, DL, MVT::i32), 7503 DAG.getConstant(15, DL, MVT::i32), 7504 DAG.getConstant(0, DL, MVT::i32), 7505 DAG.getConstant(9, DL, MVT::i32), 7506 DAG.getConstant(13, DL, MVT::i32), 7507 DAG.getConstant(0, DL, MVT::i32) 7508 }; 7509 7510 SDValue Cycles32 = DAG.getNode(ISD::INTRINSIC_W_CHAIN, DL, 7511 DAG.getVTList(MVT::i32, MVT::Other), Ops); 7512 Results.push_back(DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, Cycles32, 7513 DAG.getConstant(0, DL, MVT::i32))); 7514 Results.push_back(Cycles32.getValue(1)); 7515 } 7516 7517 static SDValue createGPRPairNode(SelectionDAG &DAG, SDValue V) { 7518 SDLoc dl(V.getNode()); 7519 SDValue VLo = DAG.getAnyExtOrTrunc(V, dl, MVT::i32); 7520 SDValue VHi = DAG.getAnyExtOrTrunc( 7521 DAG.getNode(ISD::SRL, dl, MVT::i64, V, DAG.getConstant(32, dl, MVT::i32)), 7522 dl, MVT::i32); 7523 SDValue RegClass = 7524 DAG.getTargetConstant(ARM::GPRPairRegClassID, dl, MVT::i32); 7525 SDValue SubReg0 = DAG.getTargetConstant(ARM::gsub_0, dl, MVT::i32); 7526 SDValue SubReg1 = DAG.getTargetConstant(ARM::gsub_1, dl, MVT::i32); 7527 const SDValue Ops[] = { RegClass, VLo, SubReg0, VHi, SubReg1 }; 7528 return SDValue( 7529 DAG.getMachineNode(TargetOpcode::REG_SEQUENCE, dl, MVT::Untyped, Ops), 0); 7530 } 7531 7532 static void ReplaceCMP_SWAP_64Results(SDNode *N, 7533 SmallVectorImpl<SDValue> & Results, 7534 SelectionDAG &DAG) { 7535 assert(N->getValueType(0) == MVT::i64 && 7536 "AtomicCmpSwap on types less than 64 should be legal"); 7537 SDValue Ops[] = {N->getOperand(1), 7538 createGPRPairNode(DAG, N->getOperand(2)), 7539 createGPRPairNode(DAG, N->getOperand(3)), 7540 N->getOperand(0)}; 7541 SDNode *CmpSwap = DAG.getMachineNode( 7542 ARM::CMP_SWAP_64, SDLoc(N), 7543 DAG.getVTList(MVT::Untyped, MVT::i32, MVT::Other), Ops); 7544 7545 MachineFunction &MF = DAG.getMachineFunction(); 7546 MachineSDNode::mmo_iterator MemOp = MF.allocateMemRefsArray(1); 7547 MemOp[0] = cast<MemSDNode>(N)->getMemOperand(); 7548 cast<MachineSDNode>(CmpSwap)->setMemRefs(MemOp, MemOp + 1); 7549 7550 Results.push_back(DAG.getTargetExtractSubreg(ARM::gsub_0, SDLoc(N), MVT::i32, 7551 SDValue(CmpSwap, 0))); 7552 Results.push_back(DAG.getTargetExtractSubreg(ARM::gsub_1, SDLoc(N), MVT::i32, 7553 SDValue(CmpSwap, 0))); 7554 Results.push_back(SDValue(CmpSwap, 2)); 7555 } 7556 7557 static SDValue LowerFPOWI(SDValue Op, const ARMSubtarget &Subtarget, 7558 SelectionDAG &DAG) { 7559 const auto &TLI = DAG.getTargetLoweringInfo(); 7560 7561 assert(Subtarget.getTargetTriple().isOSMSVCRT() && 7562 "Custom lowering is MSVCRT specific!"); 7563 7564 SDLoc dl(Op); 7565 SDValue Val = Op.getOperand(0); 7566 MVT Ty = Val->getSimpleValueType(0); 7567 SDValue Exponent = DAG.getNode(ISD::SINT_TO_FP, dl, Ty, Op.getOperand(1)); 7568 SDValue Callee = DAG.getExternalSymbol(Ty == MVT::f32 ? "powf" : "pow", 7569 TLI.getPointerTy(DAG.getDataLayout())); 7570 7571 TargetLowering::ArgListTy Args; 7572 TargetLowering::ArgListEntry Entry; 7573 7574 Entry.Node = Val; 7575 Entry.Ty = Val.getValueType().getTypeForEVT(*DAG.getContext()); 7576 Entry.IsZExt = true; 7577 Args.push_back(Entry); 7578 7579 Entry.Node = Exponent; 7580 Entry.Ty = Exponent.getValueType().getTypeForEVT(*DAG.getContext()); 7581 Entry.IsZExt = true; 7582 Args.push_back(Entry); 7583 7584 Type *LCRTy = Val.getValueType().getTypeForEVT(*DAG.getContext()); 7585 7586 // In the in-chain to the call is the entry node If we are emitting a 7587 // tailcall, the chain will be mutated if the node has a non-entry input 7588 // chain. 7589 SDValue InChain = DAG.getEntryNode(); 7590 SDValue TCChain = InChain; 7591 7592 const auto *F = DAG.getMachineFunction().getFunction(); 7593 bool IsTC = TLI.isInTailCallPosition(DAG, Op.getNode(), TCChain) && 7594 F->getReturnType() == LCRTy; 7595 if (IsTC) 7596 InChain = TCChain; 7597 7598 TargetLowering::CallLoweringInfo CLI(DAG); 7599 CLI.setDebugLoc(dl) 7600 .setChain(InChain) 7601 .setCallee(CallingConv::ARM_AAPCS_VFP, LCRTy, Callee, std::move(Args)) 7602 .setTailCall(IsTC); 7603 std::pair<SDValue, SDValue> CI = TLI.LowerCallTo(CLI); 7604 7605 // Return the chain (the DAG root) if it is a tail call 7606 return !CI.second.getNode() ? DAG.getRoot() : CI.first; 7607 } 7608 7609 SDValue ARMTargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const { 7610 switch (Op.getOpcode()) { 7611 default: llvm_unreachable("Don't know how to custom lower this!"); 7612 case ISD::WRITE_REGISTER: return LowerWRITE_REGISTER(Op, DAG); 7613 case ISD::ConstantPool: 7614 if (Subtarget->genExecuteOnly()) 7615 llvm_unreachable("execute-only should not generate constant pools"); 7616 return LowerConstantPool(Op, DAG); 7617 case ISD::BlockAddress: return LowerBlockAddress(Op, DAG); 7618 case ISD::GlobalAddress: 7619 switch (Subtarget->getTargetTriple().getObjectFormat()) { 7620 default: llvm_unreachable("unknown object format"); 7621 case Triple::COFF: 7622 return LowerGlobalAddressWindows(Op, DAG); 7623 case Triple::ELF: 7624 return LowerGlobalAddressELF(Op, DAG); 7625 case Triple::MachO: 7626 return LowerGlobalAddressDarwin(Op, DAG); 7627 } 7628 case ISD::GlobalTLSAddress: return LowerGlobalTLSAddress(Op, DAG); 7629 case ISD::SELECT: return LowerSELECT(Op, DAG); 7630 case ISD::SELECT_CC: return LowerSELECT_CC(Op, DAG); 7631 case ISD::BR_CC: return LowerBR_CC(Op, DAG); 7632 case ISD::BR_JT: return LowerBR_JT(Op, DAG); 7633 case ISD::VASTART: return LowerVASTART(Op, DAG); 7634 case ISD::ATOMIC_FENCE: return LowerATOMIC_FENCE(Op, DAG, Subtarget); 7635 case ISD::PREFETCH: return LowerPREFETCH(Op, DAG, Subtarget); 7636 case ISD::SINT_TO_FP: 7637 case ISD::UINT_TO_FP: return LowerINT_TO_FP(Op, DAG); 7638 case ISD::FP_TO_SINT: 7639 case ISD::FP_TO_UINT: return LowerFP_TO_INT(Op, DAG); 7640 case ISD::FCOPYSIGN: return LowerFCOPYSIGN(Op, DAG); 7641 case ISD::RETURNADDR: return LowerRETURNADDR(Op, DAG); 7642 case ISD::FRAMEADDR: return LowerFRAMEADDR(Op, DAG); 7643 case ISD::EH_SJLJ_SETJMP: return LowerEH_SJLJ_SETJMP(Op, DAG); 7644 case ISD::EH_SJLJ_LONGJMP: return LowerEH_SJLJ_LONGJMP(Op, DAG); 7645 case ISD::EH_SJLJ_SETUP_DISPATCH: return LowerEH_SJLJ_SETUP_DISPATCH(Op, DAG); 7646 case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG, 7647 Subtarget); 7648 case ISD::BITCAST: return ExpandBITCAST(Op.getNode(), DAG); 7649 case ISD::SHL: 7650 case ISD::SRL: 7651 case ISD::SRA: return LowerShift(Op.getNode(), DAG, Subtarget); 7652 case ISD::SREM: return LowerREM(Op.getNode(), DAG); 7653 case ISD::UREM: return LowerREM(Op.getNode(), DAG); 7654 case ISD::SHL_PARTS: return LowerShiftLeftParts(Op, DAG); 7655 case ISD::SRL_PARTS: 7656 case ISD::SRA_PARTS: return LowerShiftRightParts(Op, DAG); 7657 case ISD::CTTZ: 7658 case ISD::CTTZ_ZERO_UNDEF: return LowerCTTZ(Op.getNode(), DAG, Subtarget); 7659 case ISD::CTPOP: return LowerCTPOP(Op.getNode(), DAG, Subtarget); 7660 case ISD::SETCC: return LowerVSETCC(Op, DAG); 7661 case ISD::SETCCE: return LowerSETCCE(Op, DAG); 7662 case ISD::ConstantFP: return LowerConstantFP(Op, DAG, Subtarget); 7663 case ISD::BUILD_VECTOR: return LowerBUILD_VECTOR(Op, DAG, Subtarget); 7664 case ISD::VECTOR_SHUFFLE: return LowerVECTOR_SHUFFLE(Op, DAG); 7665 case ISD::INSERT_VECTOR_ELT: return LowerINSERT_VECTOR_ELT(Op, DAG); 7666 case ISD::EXTRACT_VECTOR_ELT: return LowerEXTRACT_VECTOR_ELT(Op, DAG); 7667 case ISD::CONCAT_VECTORS: return LowerCONCAT_VECTORS(Op, DAG); 7668 case ISD::FLT_ROUNDS_: return LowerFLT_ROUNDS_(Op, DAG); 7669 case ISD::MUL: return LowerMUL(Op, DAG); 7670 case ISD::SDIV: 7671 if (Subtarget->isTargetWindows() && !Op.getValueType().isVector()) 7672 return LowerDIV_Windows(Op, DAG, /* Signed */ true); 7673 return LowerSDIV(Op, DAG); 7674 case ISD::UDIV: 7675 if (Subtarget->isTargetWindows() && !Op.getValueType().isVector()) 7676 return LowerDIV_Windows(Op, DAG, /* Signed */ false); 7677 return LowerUDIV(Op, DAG); 7678 case ISD::ADDC: 7679 case ISD::ADDE: 7680 case ISD::SUBC: 7681 case ISD::SUBE: return LowerADDC_ADDE_SUBC_SUBE(Op, DAG); 7682 case ISD::SADDO: 7683 case ISD::UADDO: 7684 case ISD::SSUBO: 7685 case ISD::USUBO: 7686 return LowerXALUO(Op, DAG); 7687 case ISD::ATOMIC_LOAD: 7688 case ISD::ATOMIC_STORE: return LowerAtomicLoadStore(Op, DAG); 7689 case ISD::FSINCOS: return LowerFSINCOS(Op, DAG); 7690 case ISD::SDIVREM: 7691 case ISD::UDIVREM: return LowerDivRem(Op, DAG); 7692 case ISD::DYNAMIC_STACKALLOC: 7693 if (Subtarget->getTargetTriple().isWindowsItaniumEnvironment()) 7694 return LowerDYNAMIC_STACKALLOC(Op, DAG); 7695 llvm_unreachable("Don't know how to custom lower this!"); 7696 case ISD::FP_ROUND: return LowerFP_ROUND(Op, DAG); 7697 case ISD::FP_EXTEND: return LowerFP_EXTEND(Op, DAG); 7698 case ISD::FPOWI: return LowerFPOWI(Op, *Subtarget, DAG); 7699 case ARMISD::WIN__DBZCHK: return SDValue(); 7700 } 7701 } 7702 7703 /// ReplaceNodeResults - Replace the results of node with an illegal result 7704 /// type with new values built out of custom code. 7705 void ARMTargetLowering::ReplaceNodeResults(SDNode *N, 7706 SmallVectorImpl<SDValue> &Results, 7707 SelectionDAG &DAG) const { 7708 SDValue Res; 7709 switch (N->getOpcode()) { 7710 default: 7711 llvm_unreachable("Don't know how to custom expand this!"); 7712 case ISD::READ_REGISTER: 7713 ExpandREAD_REGISTER(N, Results, DAG); 7714 break; 7715 case ISD::BITCAST: 7716 Res = ExpandBITCAST(N, DAG); 7717 break; 7718 case ISD::SRL: 7719 case ISD::SRA: 7720 Res = Expand64BitShift(N, DAG, Subtarget); 7721 break; 7722 case ISD::SREM: 7723 case ISD::UREM: 7724 Res = LowerREM(N, DAG); 7725 break; 7726 case ISD::SDIVREM: 7727 case ISD::UDIVREM: 7728 Res = LowerDivRem(SDValue(N, 0), DAG); 7729 assert(Res.getNumOperands() == 2 && "DivRem needs two values"); 7730 Results.push_back(Res.getValue(0)); 7731 Results.push_back(Res.getValue(1)); 7732 return; 7733 case ISD::READCYCLECOUNTER: 7734 ReplaceREADCYCLECOUNTER(N, Results, DAG, Subtarget); 7735 return; 7736 case ISD::UDIV: 7737 case ISD::SDIV: 7738 assert(Subtarget->isTargetWindows() && "can only expand DIV on Windows"); 7739 return ExpandDIV_Windows(SDValue(N, 0), DAG, N->getOpcode() == ISD::SDIV, 7740 Results); 7741 case ISD::ATOMIC_CMP_SWAP: 7742 ReplaceCMP_SWAP_64Results(N, Results, DAG); 7743 return; 7744 } 7745 if (Res.getNode()) 7746 Results.push_back(Res); 7747 } 7748 7749 //===----------------------------------------------------------------------===// 7750 // ARM Scheduler Hooks 7751 //===----------------------------------------------------------------------===// 7752 7753 /// SetupEntryBlockForSjLj - Insert code into the entry block that creates and 7754 /// registers the function context. 7755 void ARMTargetLowering::SetupEntryBlockForSjLj(MachineInstr &MI, 7756 MachineBasicBlock *MBB, 7757 MachineBasicBlock *DispatchBB, 7758 int FI) const { 7759 assert(!Subtarget->isROPI() && !Subtarget->isRWPI() && 7760 "ROPI/RWPI not currently supported with SjLj"); 7761 const TargetInstrInfo *TII = Subtarget->getInstrInfo(); 7762 DebugLoc dl = MI.getDebugLoc(); 7763 MachineFunction *MF = MBB->getParent(); 7764 MachineRegisterInfo *MRI = &MF->getRegInfo(); 7765 MachineConstantPool *MCP = MF->getConstantPool(); 7766 ARMFunctionInfo *AFI = MF->getInfo<ARMFunctionInfo>(); 7767 const Function *F = MF->getFunction(); 7768 7769 bool isThumb = Subtarget->isThumb(); 7770 bool isThumb2 = Subtarget->isThumb2(); 7771 7772 unsigned PCLabelId = AFI->createPICLabelUId(); 7773 unsigned PCAdj = (isThumb || isThumb2) ? 4 : 8; 7774 ARMConstantPoolValue *CPV = 7775 ARMConstantPoolMBB::Create(F->getContext(), DispatchBB, PCLabelId, PCAdj); 7776 unsigned CPI = MCP->getConstantPoolIndex(CPV, 4); 7777 7778 const TargetRegisterClass *TRC = isThumb ? &ARM::tGPRRegClass 7779 : &ARM::GPRRegClass; 7780 7781 // Grab constant pool and fixed stack memory operands. 7782 MachineMemOperand *CPMMO = 7783 MF->getMachineMemOperand(MachinePointerInfo::getConstantPool(*MF), 7784 MachineMemOperand::MOLoad, 4, 4); 7785 7786 MachineMemOperand *FIMMOSt = 7787 MF->getMachineMemOperand(MachinePointerInfo::getFixedStack(*MF, FI), 7788 MachineMemOperand::MOStore, 4, 4); 7789 7790 // Load the address of the dispatch MBB into the jump buffer. 7791 if (isThumb2) { 7792 // Incoming value: jbuf 7793 // ldr.n r5, LCPI1_1 7794 // orr r5, r5, #1 7795 // add r5, pc 7796 // str r5, [$jbuf, #+4] ; &jbuf[1] 7797 unsigned NewVReg1 = MRI->createVirtualRegister(TRC); 7798 BuildMI(*MBB, MI, dl, TII->get(ARM::t2LDRpci), NewVReg1) 7799 .addConstantPoolIndex(CPI) 7800 .addMemOperand(CPMMO) 7801 .add(predOps(ARMCC::AL)); 7802 // Set the low bit because of thumb mode. 7803 unsigned NewVReg2 = MRI->createVirtualRegister(TRC); 7804 BuildMI(*MBB, MI, dl, TII->get(ARM::t2ORRri), NewVReg2) 7805 .addReg(NewVReg1, RegState::Kill) 7806 .addImm(0x01) 7807 .add(predOps(ARMCC::AL)) 7808 .add(condCodeOp()); 7809 unsigned NewVReg3 = MRI->createVirtualRegister(TRC); 7810 BuildMI(*MBB, MI, dl, TII->get(ARM::tPICADD), NewVReg3) 7811 .addReg(NewVReg2, RegState::Kill) 7812 .addImm(PCLabelId); 7813 BuildMI(*MBB, MI, dl, TII->get(ARM::t2STRi12)) 7814 .addReg(NewVReg3, RegState::Kill) 7815 .addFrameIndex(FI) 7816 .addImm(36) // &jbuf[1] :: pc 7817 .addMemOperand(FIMMOSt) 7818 .add(predOps(ARMCC::AL)); 7819 } else if (isThumb) { 7820 // Incoming value: jbuf 7821 // ldr.n r1, LCPI1_4 7822 // add r1, pc 7823 // mov r2, #1 7824 // orrs r1, r2 7825 // add r2, $jbuf, #+4 ; &jbuf[1] 7826 // str r1, [r2] 7827 unsigned NewVReg1 = MRI->createVirtualRegister(TRC); 7828 BuildMI(*MBB, MI, dl, TII->get(ARM::tLDRpci), NewVReg1) 7829 .addConstantPoolIndex(CPI) 7830 .addMemOperand(CPMMO) 7831 .add(predOps(ARMCC::AL)); 7832 unsigned NewVReg2 = MRI->createVirtualRegister(TRC); 7833 BuildMI(*MBB, MI, dl, TII->get(ARM::tPICADD), NewVReg2) 7834 .addReg(NewVReg1, RegState::Kill) 7835 .addImm(PCLabelId); 7836 // Set the low bit because of thumb mode. 7837 unsigned NewVReg3 = MRI->createVirtualRegister(TRC); 7838 BuildMI(*MBB, MI, dl, TII->get(ARM::tMOVi8), NewVReg3) 7839 .addReg(ARM::CPSR, RegState::Define) 7840 .addImm(1) 7841 .add(predOps(ARMCC::AL)); 7842 unsigned NewVReg4 = MRI->createVirtualRegister(TRC); 7843 BuildMI(*MBB, MI, dl, TII->get(ARM::tORR), NewVReg4) 7844 .addReg(ARM::CPSR, RegState::Define) 7845 .addReg(NewVReg2, RegState::Kill) 7846 .addReg(NewVReg3, RegState::Kill) 7847 .add(predOps(ARMCC::AL)); 7848 unsigned NewVReg5 = MRI->createVirtualRegister(TRC); 7849 BuildMI(*MBB, MI, dl, TII->get(ARM::tADDframe), NewVReg5) 7850 .addFrameIndex(FI) 7851 .addImm(36); // &jbuf[1] :: pc 7852 BuildMI(*MBB, MI, dl, TII->get(ARM::tSTRi)) 7853 .addReg(NewVReg4, RegState::Kill) 7854 .addReg(NewVReg5, RegState::Kill) 7855 .addImm(0) 7856 .addMemOperand(FIMMOSt) 7857 .add(predOps(ARMCC::AL)); 7858 } else { 7859 // Incoming value: jbuf 7860 // ldr r1, LCPI1_1 7861 // add r1, pc, r1 7862 // str r1, [$jbuf, #+4] ; &jbuf[1] 7863 unsigned NewVReg1 = MRI->createVirtualRegister(TRC); 7864 BuildMI(*MBB, MI, dl, TII->get(ARM::LDRi12), NewVReg1) 7865 .addConstantPoolIndex(CPI) 7866 .addImm(0) 7867 .addMemOperand(CPMMO) 7868 .add(predOps(ARMCC::AL)); 7869 unsigned NewVReg2 = MRI->createVirtualRegister(TRC); 7870 BuildMI(*MBB, MI, dl, TII->get(ARM::PICADD), NewVReg2) 7871 .addReg(NewVReg1, RegState::Kill) 7872 .addImm(PCLabelId) 7873 .add(predOps(ARMCC::AL)); 7874 BuildMI(*MBB, MI, dl, TII->get(ARM::STRi12)) 7875 .addReg(NewVReg2, RegState::Kill) 7876 .addFrameIndex(FI) 7877 .addImm(36) // &jbuf[1] :: pc 7878 .addMemOperand(FIMMOSt) 7879 .add(predOps(ARMCC::AL)); 7880 } 7881 } 7882 7883 void ARMTargetLowering::EmitSjLjDispatchBlock(MachineInstr &MI, 7884 MachineBasicBlock *MBB) const { 7885 const TargetInstrInfo *TII = Subtarget->getInstrInfo(); 7886 DebugLoc dl = MI.getDebugLoc(); 7887 MachineFunction *MF = MBB->getParent(); 7888 MachineRegisterInfo *MRI = &MF->getRegInfo(); 7889 MachineFrameInfo &MFI = MF->getFrameInfo(); 7890 int FI = MFI.getFunctionContextIndex(); 7891 7892 const TargetRegisterClass *TRC = Subtarget->isThumb() ? &ARM::tGPRRegClass 7893 : &ARM::GPRnopcRegClass; 7894 7895 // Get a mapping of the call site numbers to all of the landing pads they're 7896 // associated with. 7897 DenseMap<unsigned, SmallVector<MachineBasicBlock*, 2>> CallSiteNumToLPad; 7898 unsigned MaxCSNum = 0; 7899 for (MachineFunction::iterator BB = MF->begin(), E = MF->end(); BB != E; 7900 ++BB) { 7901 if (!BB->isEHPad()) continue; 7902 7903 // FIXME: We should assert that the EH_LABEL is the first MI in the landing 7904 // pad. 7905 for (MachineBasicBlock::iterator 7906 II = BB->begin(), IE = BB->end(); II != IE; ++II) { 7907 if (!II->isEHLabel()) continue; 7908 7909 MCSymbol *Sym = II->getOperand(0).getMCSymbol(); 7910 if (!MF->hasCallSiteLandingPad(Sym)) continue; 7911 7912 SmallVectorImpl<unsigned> &CallSiteIdxs = MF->getCallSiteLandingPad(Sym); 7913 for (SmallVectorImpl<unsigned>::iterator 7914 CSI = CallSiteIdxs.begin(), CSE = CallSiteIdxs.end(); 7915 CSI != CSE; ++CSI) { 7916 CallSiteNumToLPad[*CSI].push_back(&*BB); 7917 MaxCSNum = std::max(MaxCSNum, *CSI); 7918 } 7919 break; 7920 } 7921 } 7922 7923 // Get an ordered list of the machine basic blocks for the jump table. 7924 std::vector<MachineBasicBlock*> LPadList; 7925 SmallPtrSet<MachineBasicBlock*, 32> InvokeBBs; 7926 LPadList.reserve(CallSiteNumToLPad.size()); 7927 for (unsigned I = 1; I <= MaxCSNum; ++I) { 7928 SmallVectorImpl<MachineBasicBlock*> &MBBList = CallSiteNumToLPad[I]; 7929 for (SmallVectorImpl<MachineBasicBlock*>::iterator 7930 II = MBBList.begin(), IE = MBBList.end(); II != IE; ++II) { 7931 LPadList.push_back(*II); 7932 InvokeBBs.insert((*II)->pred_begin(), (*II)->pred_end()); 7933 } 7934 } 7935 7936 assert(!LPadList.empty() && 7937 "No landing pad destinations for the dispatch jump table!"); 7938 7939 // Create the jump table and associated information. 7940 MachineJumpTableInfo *JTI = 7941 MF->getOrCreateJumpTableInfo(MachineJumpTableInfo::EK_Inline); 7942 unsigned MJTI = JTI->createJumpTableIndex(LPadList); 7943 7944 // Create the MBBs for the dispatch code. 7945 7946 // Shove the dispatch's address into the return slot in the function context. 7947 MachineBasicBlock *DispatchBB = MF->CreateMachineBasicBlock(); 7948 DispatchBB->setIsEHPad(); 7949 7950 MachineBasicBlock *TrapBB = MF->CreateMachineBasicBlock(); 7951 unsigned trap_opcode; 7952 if (Subtarget->isThumb()) 7953 trap_opcode = ARM::tTRAP; 7954 else 7955 trap_opcode = Subtarget->useNaClTrap() ? ARM::TRAPNaCl : ARM::TRAP; 7956 7957 BuildMI(TrapBB, dl, TII->get(trap_opcode)); 7958 DispatchBB->addSuccessor(TrapBB); 7959 7960 MachineBasicBlock *DispContBB = MF->CreateMachineBasicBlock(); 7961 DispatchBB->addSuccessor(DispContBB); 7962 7963 // Insert and MBBs. 7964 MF->insert(MF->end(), DispatchBB); 7965 MF->insert(MF->end(), DispContBB); 7966 MF->insert(MF->end(), TrapBB); 7967 7968 // Insert code into the entry block that creates and registers the function 7969 // context. 7970 SetupEntryBlockForSjLj(MI, MBB, DispatchBB, FI); 7971 7972 MachineMemOperand *FIMMOLd = MF->getMachineMemOperand( 7973 MachinePointerInfo::getFixedStack(*MF, FI), 7974 MachineMemOperand::MOLoad | MachineMemOperand::MOVolatile, 4, 4); 7975 7976 MachineInstrBuilder MIB; 7977 MIB = BuildMI(DispatchBB, dl, TII->get(ARM::Int_eh_sjlj_dispatchsetup)); 7978 7979 const ARMBaseInstrInfo *AII = static_cast<const ARMBaseInstrInfo*>(TII); 7980 const ARMBaseRegisterInfo &RI = AII->getRegisterInfo(); 7981 7982 // Add a register mask with no preserved registers. This results in all 7983 // registers being marked as clobbered. This can't work if the dispatch block 7984 // is in a Thumb1 function and is linked with ARM code which uses the FP 7985 // registers, as there is no way to preserve the FP registers in Thumb1 mode. 7986 MIB.addRegMask(RI.getSjLjDispatchPreservedMask(*MF)); 7987 7988 bool IsPositionIndependent = isPositionIndependent(); 7989 unsigned NumLPads = LPadList.size(); 7990 if (Subtarget->isThumb2()) { 7991 unsigned NewVReg1 = MRI->createVirtualRegister(TRC); 7992 BuildMI(DispatchBB, dl, TII->get(ARM::t2LDRi12), NewVReg1) 7993 .addFrameIndex(FI) 7994 .addImm(4) 7995 .addMemOperand(FIMMOLd) 7996 .add(predOps(ARMCC::AL)); 7997 7998 if (NumLPads < 256) { 7999 BuildMI(DispatchBB, dl, TII->get(ARM::t2CMPri)) 8000 .addReg(NewVReg1) 8001 .addImm(LPadList.size()) 8002 .add(predOps(ARMCC::AL)); 8003 } else { 8004 unsigned VReg1 = MRI->createVirtualRegister(TRC); 8005 BuildMI(DispatchBB, dl, TII->get(ARM::t2MOVi16), VReg1) 8006 .addImm(NumLPads & 0xFFFF) 8007 .add(predOps(ARMCC::AL)); 8008 8009 unsigned VReg2 = VReg1; 8010 if ((NumLPads & 0xFFFF0000) != 0) { 8011 VReg2 = MRI->createVirtualRegister(TRC); 8012 BuildMI(DispatchBB, dl, TII->get(ARM::t2MOVTi16), VReg2) 8013 .addReg(VReg1) 8014 .addImm(NumLPads >> 16) 8015 .add(predOps(ARMCC::AL)); 8016 } 8017 8018 BuildMI(DispatchBB, dl, TII->get(ARM::t2CMPrr)) 8019 .addReg(NewVReg1) 8020 .addReg(VReg2) 8021 .add(predOps(ARMCC::AL)); 8022 } 8023 8024 BuildMI(DispatchBB, dl, TII->get(ARM::t2Bcc)) 8025 .addMBB(TrapBB) 8026 .addImm(ARMCC::HI) 8027 .addReg(ARM::CPSR); 8028 8029 unsigned NewVReg3 = MRI->createVirtualRegister(TRC); 8030 BuildMI(DispContBB, dl, TII->get(ARM::t2LEApcrelJT), NewVReg3) 8031 .addJumpTableIndex(MJTI) 8032 .add(predOps(ARMCC::AL)); 8033 8034 unsigned NewVReg4 = MRI->createVirtualRegister(TRC); 8035 BuildMI(DispContBB, dl, TII->get(ARM::t2ADDrs), NewVReg4) 8036 .addReg(NewVReg3, RegState::Kill) 8037 .addReg(NewVReg1) 8038 .addImm(ARM_AM::getSORegOpc(ARM_AM::lsl, 2)) 8039 .add(predOps(ARMCC::AL)) 8040 .add(condCodeOp()); 8041 8042 BuildMI(DispContBB, dl, TII->get(ARM::t2BR_JT)) 8043 .addReg(NewVReg4, RegState::Kill) 8044 .addReg(NewVReg1) 8045 .addJumpTableIndex(MJTI); 8046 } else if (Subtarget->isThumb()) { 8047 unsigned NewVReg1 = MRI->createVirtualRegister(TRC); 8048 BuildMI(DispatchBB, dl, TII->get(ARM::tLDRspi), NewVReg1) 8049 .addFrameIndex(FI) 8050 .addImm(1) 8051 .addMemOperand(FIMMOLd) 8052 .add(predOps(ARMCC::AL)); 8053 8054 if (NumLPads < 256) { 8055 BuildMI(DispatchBB, dl, TII->get(ARM::tCMPi8)) 8056 .addReg(NewVReg1) 8057 .addImm(NumLPads) 8058 .add(predOps(ARMCC::AL)); 8059 } else { 8060 MachineConstantPool *ConstantPool = MF->getConstantPool(); 8061 Type *Int32Ty = Type::getInt32Ty(MF->getFunction()->getContext()); 8062 const Constant *C = ConstantInt::get(Int32Ty, NumLPads); 8063 8064 // MachineConstantPool wants an explicit alignment. 8065 unsigned Align = MF->getDataLayout().getPrefTypeAlignment(Int32Ty); 8066 if (Align == 0) 8067 Align = MF->getDataLayout().getTypeAllocSize(C->getType()); 8068 unsigned Idx = ConstantPool->getConstantPoolIndex(C, Align); 8069 8070 unsigned VReg1 = MRI->createVirtualRegister(TRC); 8071 BuildMI(DispatchBB, dl, TII->get(ARM::tLDRpci)) 8072 .addReg(VReg1, RegState::Define) 8073 .addConstantPoolIndex(Idx) 8074 .add(predOps(ARMCC::AL)); 8075 BuildMI(DispatchBB, dl, TII->get(ARM::tCMPr)) 8076 .addReg(NewVReg1) 8077 .addReg(VReg1) 8078 .add(predOps(ARMCC::AL)); 8079 } 8080 8081 BuildMI(DispatchBB, dl, TII->get(ARM::tBcc)) 8082 .addMBB(TrapBB) 8083 .addImm(ARMCC::HI) 8084 .addReg(ARM::CPSR); 8085 8086 unsigned NewVReg2 = MRI->createVirtualRegister(TRC); 8087 BuildMI(DispContBB, dl, TII->get(ARM::tLSLri), NewVReg2) 8088 .addReg(ARM::CPSR, RegState::Define) 8089 .addReg(NewVReg1) 8090 .addImm(2) 8091 .add(predOps(ARMCC::AL)); 8092 8093 unsigned NewVReg3 = MRI->createVirtualRegister(TRC); 8094 BuildMI(DispContBB, dl, TII->get(ARM::tLEApcrelJT), NewVReg3) 8095 .addJumpTableIndex(MJTI) 8096 .add(predOps(ARMCC::AL)); 8097 8098 unsigned NewVReg4 = MRI->createVirtualRegister(TRC); 8099 BuildMI(DispContBB, dl, TII->get(ARM::tADDrr), NewVReg4) 8100 .addReg(ARM::CPSR, RegState::Define) 8101 .addReg(NewVReg2, RegState::Kill) 8102 .addReg(NewVReg3) 8103 .add(predOps(ARMCC::AL)); 8104 8105 MachineMemOperand *JTMMOLd = MF->getMachineMemOperand( 8106 MachinePointerInfo::getJumpTable(*MF), MachineMemOperand::MOLoad, 4, 4); 8107 8108 unsigned NewVReg5 = MRI->createVirtualRegister(TRC); 8109 BuildMI(DispContBB, dl, TII->get(ARM::tLDRi), NewVReg5) 8110 .addReg(NewVReg4, RegState::Kill) 8111 .addImm(0) 8112 .addMemOperand(JTMMOLd) 8113 .add(predOps(ARMCC::AL)); 8114 8115 unsigned NewVReg6 = NewVReg5; 8116 if (IsPositionIndependent) { 8117 NewVReg6 = MRI->createVirtualRegister(TRC); 8118 BuildMI(DispContBB, dl, TII->get(ARM::tADDrr), NewVReg6) 8119 .addReg(ARM::CPSR, RegState::Define) 8120 .addReg(NewVReg5, RegState::Kill) 8121 .addReg(NewVReg3) 8122 .add(predOps(ARMCC::AL)); 8123 } 8124 8125 BuildMI(DispContBB, dl, TII->get(ARM::tBR_JTr)) 8126 .addReg(NewVReg6, RegState::Kill) 8127 .addJumpTableIndex(MJTI); 8128 } else { 8129 unsigned NewVReg1 = MRI->createVirtualRegister(TRC); 8130 BuildMI(DispatchBB, dl, TII->get(ARM::LDRi12), NewVReg1) 8131 .addFrameIndex(FI) 8132 .addImm(4) 8133 .addMemOperand(FIMMOLd) 8134 .add(predOps(ARMCC::AL)); 8135 8136 if (NumLPads < 256) { 8137 BuildMI(DispatchBB, dl, TII->get(ARM::CMPri)) 8138 .addReg(NewVReg1) 8139 .addImm(NumLPads) 8140 .add(predOps(ARMCC::AL)); 8141 } else if (Subtarget->hasV6T2Ops() && isUInt<16>(NumLPads)) { 8142 unsigned VReg1 = MRI->createVirtualRegister(TRC); 8143 BuildMI(DispatchBB, dl, TII->get(ARM::MOVi16), VReg1) 8144 .addImm(NumLPads & 0xFFFF) 8145 .add(predOps(ARMCC::AL)); 8146 8147 unsigned VReg2 = VReg1; 8148 if ((NumLPads & 0xFFFF0000) != 0) { 8149 VReg2 = MRI->createVirtualRegister(TRC); 8150 BuildMI(DispatchBB, dl, TII->get(ARM::MOVTi16), VReg2) 8151 .addReg(VReg1) 8152 .addImm(NumLPads >> 16) 8153 .add(predOps(ARMCC::AL)); 8154 } 8155 8156 BuildMI(DispatchBB, dl, TII->get(ARM::CMPrr)) 8157 .addReg(NewVReg1) 8158 .addReg(VReg2) 8159 .add(predOps(ARMCC::AL)); 8160 } else { 8161 MachineConstantPool *ConstantPool = MF->getConstantPool(); 8162 Type *Int32Ty = Type::getInt32Ty(MF->getFunction()->getContext()); 8163 const Constant *C = ConstantInt::get(Int32Ty, NumLPads); 8164 8165 // MachineConstantPool wants an explicit alignment. 8166 unsigned Align = MF->getDataLayout().getPrefTypeAlignment(Int32Ty); 8167 if (Align == 0) 8168 Align = MF->getDataLayout().getTypeAllocSize(C->getType()); 8169 unsigned Idx = ConstantPool->getConstantPoolIndex(C, Align); 8170 8171 unsigned VReg1 = MRI->createVirtualRegister(TRC); 8172 BuildMI(DispatchBB, dl, TII->get(ARM::LDRcp)) 8173 .addReg(VReg1, RegState::Define) 8174 .addConstantPoolIndex(Idx) 8175 .addImm(0) 8176 .add(predOps(ARMCC::AL)); 8177 BuildMI(DispatchBB, dl, TII->get(ARM::CMPrr)) 8178 .addReg(NewVReg1) 8179 .addReg(VReg1, RegState::Kill) 8180 .add(predOps(ARMCC::AL)); 8181 } 8182 8183 BuildMI(DispatchBB, dl, TII->get(ARM::Bcc)) 8184 .addMBB(TrapBB) 8185 .addImm(ARMCC::HI) 8186 .addReg(ARM::CPSR); 8187 8188 unsigned NewVReg3 = MRI->createVirtualRegister(TRC); 8189 BuildMI(DispContBB, dl, TII->get(ARM::MOVsi), NewVReg3) 8190 .addReg(NewVReg1) 8191 .addImm(ARM_AM::getSORegOpc(ARM_AM::lsl, 2)) 8192 .add(predOps(ARMCC::AL)) 8193 .add(condCodeOp()); 8194 unsigned NewVReg4 = MRI->createVirtualRegister(TRC); 8195 BuildMI(DispContBB, dl, TII->get(ARM::LEApcrelJT), NewVReg4) 8196 .addJumpTableIndex(MJTI) 8197 .add(predOps(ARMCC::AL)); 8198 8199 MachineMemOperand *JTMMOLd = MF->getMachineMemOperand( 8200 MachinePointerInfo::getJumpTable(*MF), MachineMemOperand::MOLoad, 4, 4); 8201 unsigned NewVReg5 = MRI->createVirtualRegister(TRC); 8202 BuildMI(DispContBB, dl, TII->get(ARM::LDRrs), NewVReg5) 8203 .addReg(NewVReg3, RegState::Kill) 8204 .addReg(NewVReg4) 8205 .addImm(0) 8206 .addMemOperand(JTMMOLd) 8207 .add(predOps(ARMCC::AL)); 8208 8209 if (IsPositionIndependent) { 8210 BuildMI(DispContBB, dl, TII->get(ARM::BR_JTadd)) 8211 .addReg(NewVReg5, RegState::Kill) 8212 .addReg(NewVReg4) 8213 .addJumpTableIndex(MJTI); 8214 } else { 8215 BuildMI(DispContBB, dl, TII->get(ARM::BR_JTr)) 8216 .addReg(NewVReg5, RegState::Kill) 8217 .addJumpTableIndex(MJTI); 8218 } 8219 } 8220 8221 // Add the jump table entries as successors to the MBB. 8222 SmallPtrSet<MachineBasicBlock*, 8> SeenMBBs; 8223 for (std::vector<MachineBasicBlock*>::iterator 8224 I = LPadList.begin(), E = LPadList.end(); I != E; ++I) { 8225 MachineBasicBlock *CurMBB = *I; 8226 if (SeenMBBs.insert(CurMBB).second) 8227 DispContBB->addSuccessor(CurMBB); 8228 } 8229 8230 // N.B. the order the invoke BBs are processed in doesn't matter here. 8231 const MCPhysReg *SavedRegs = RI.getCalleeSavedRegs(MF); 8232 SmallVector<MachineBasicBlock*, 64> MBBLPads; 8233 for (MachineBasicBlock *BB : InvokeBBs) { 8234 8235 // Remove the landing pad successor from the invoke block and replace it 8236 // with the new dispatch block. 8237 SmallVector<MachineBasicBlock*, 4> Successors(BB->succ_begin(), 8238 BB->succ_end()); 8239 while (!Successors.empty()) { 8240 MachineBasicBlock *SMBB = Successors.pop_back_val(); 8241 if (SMBB->isEHPad()) { 8242 BB->removeSuccessor(SMBB); 8243 MBBLPads.push_back(SMBB); 8244 } 8245 } 8246 8247 BB->addSuccessor(DispatchBB, BranchProbability::getZero()); 8248 BB->normalizeSuccProbs(); 8249 8250 // Find the invoke call and mark all of the callee-saved registers as 8251 // 'implicit defined' so that they're spilled. This prevents code from 8252 // moving instructions to before the EH block, where they will never be 8253 // executed. 8254 for (MachineBasicBlock::reverse_iterator 8255 II = BB->rbegin(), IE = BB->rend(); II != IE; ++II) { 8256 if (!II->isCall()) continue; 8257 8258 DenseMap<unsigned, bool> DefRegs; 8259 for (MachineInstr::mop_iterator 8260 OI = II->operands_begin(), OE = II->operands_end(); 8261 OI != OE; ++OI) { 8262 if (!OI->isReg()) continue; 8263 DefRegs[OI->getReg()] = true; 8264 } 8265 8266 MachineInstrBuilder MIB(*MF, &*II); 8267 8268 for (unsigned i = 0; SavedRegs[i] != 0; ++i) { 8269 unsigned Reg = SavedRegs[i]; 8270 if (Subtarget->isThumb2() && 8271 !ARM::tGPRRegClass.contains(Reg) && 8272 !ARM::hGPRRegClass.contains(Reg)) 8273 continue; 8274 if (Subtarget->isThumb1Only() && !ARM::tGPRRegClass.contains(Reg)) 8275 continue; 8276 if (!Subtarget->isThumb() && !ARM::GPRRegClass.contains(Reg)) 8277 continue; 8278 if (!DefRegs[Reg]) 8279 MIB.addReg(Reg, RegState::ImplicitDefine | RegState::Dead); 8280 } 8281 8282 break; 8283 } 8284 } 8285 8286 // Mark all former landing pads as non-landing pads. The dispatch is the only 8287 // landing pad now. 8288 for (SmallVectorImpl<MachineBasicBlock*>::iterator 8289 I = MBBLPads.begin(), E = MBBLPads.end(); I != E; ++I) 8290 (*I)->setIsEHPad(false); 8291 8292 // The instruction is gone now. 8293 MI.eraseFromParent(); 8294 } 8295 8296 static 8297 MachineBasicBlock *OtherSucc(MachineBasicBlock *MBB, MachineBasicBlock *Succ) { 8298 for (MachineBasicBlock::succ_iterator I = MBB->succ_begin(), 8299 E = MBB->succ_end(); I != E; ++I) 8300 if (*I != Succ) 8301 return *I; 8302 llvm_unreachable("Expecting a BB with two successors!"); 8303 } 8304 8305 /// Return the load opcode for a given load size. If load size >= 8, 8306 /// neon opcode will be returned. 8307 static unsigned getLdOpcode(unsigned LdSize, bool IsThumb1, bool IsThumb2) { 8308 if (LdSize >= 8) 8309 return LdSize == 16 ? ARM::VLD1q32wb_fixed 8310 : LdSize == 8 ? ARM::VLD1d32wb_fixed : 0; 8311 if (IsThumb1) 8312 return LdSize == 4 ? ARM::tLDRi 8313 : LdSize == 2 ? ARM::tLDRHi 8314 : LdSize == 1 ? ARM::tLDRBi : 0; 8315 if (IsThumb2) 8316 return LdSize == 4 ? ARM::t2LDR_POST 8317 : LdSize == 2 ? ARM::t2LDRH_POST 8318 : LdSize == 1 ? ARM::t2LDRB_POST : 0; 8319 return LdSize == 4 ? ARM::LDR_POST_IMM 8320 : LdSize == 2 ? ARM::LDRH_POST 8321 : LdSize == 1 ? ARM::LDRB_POST_IMM : 0; 8322 } 8323 8324 /// Return the store opcode for a given store size. If store size >= 8, 8325 /// neon opcode will be returned. 8326 static unsigned getStOpcode(unsigned StSize, bool IsThumb1, bool IsThumb2) { 8327 if (StSize >= 8) 8328 return StSize == 16 ? ARM::VST1q32wb_fixed 8329 : StSize == 8 ? ARM::VST1d32wb_fixed : 0; 8330 if (IsThumb1) 8331 return StSize == 4 ? ARM::tSTRi 8332 : StSize == 2 ? ARM::tSTRHi 8333 : StSize == 1 ? ARM::tSTRBi : 0; 8334 if (IsThumb2) 8335 return StSize == 4 ? ARM::t2STR_POST 8336 : StSize == 2 ? ARM::t2STRH_POST 8337 : StSize == 1 ? ARM::t2STRB_POST : 0; 8338 return StSize == 4 ? ARM::STR_POST_IMM 8339 : StSize == 2 ? ARM::STRH_POST 8340 : StSize == 1 ? ARM::STRB_POST_IMM : 0; 8341 } 8342 8343 /// Emit a post-increment load operation with given size. The instructions 8344 /// will be added to BB at Pos. 8345 static void emitPostLd(MachineBasicBlock *BB, MachineBasicBlock::iterator Pos, 8346 const TargetInstrInfo *TII, const DebugLoc &dl, 8347 unsigned LdSize, unsigned Data, unsigned AddrIn, 8348 unsigned AddrOut, bool IsThumb1, bool IsThumb2) { 8349 unsigned LdOpc = getLdOpcode(LdSize, IsThumb1, IsThumb2); 8350 assert(LdOpc != 0 && "Should have a load opcode"); 8351 if (LdSize >= 8) { 8352 BuildMI(*BB, Pos, dl, TII->get(LdOpc), Data) 8353 .addReg(AddrOut, RegState::Define) 8354 .addReg(AddrIn) 8355 .addImm(0) 8356 .add(predOps(ARMCC::AL)); 8357 } else if (IsThumb1) { 8358 // load + update AddrIn 8359 BuildMI(*BB, Pos, dl, TII->get(LdOpc), Data) 8360 .addReg(AddrIn) 8361 .addImm(0) 8362 .add(predOps(ARMCC::AL)); 8363 BuildMI(*BB, Pos, dl, TII->get(ARM::tADDi8), AddrOut) 8364 .add(t1CondCodeOp()) 8365 .addReg(AddrIn) 8366 .addImm(LdSize) 8367 .add(predOps(ARMCC::AL)); 8368 } else if (IsThumb2) { 8369 BuildMI(*BB, Pos, dl, TII->get(LdOpc), Data) 8370 .addReg(AddrOut, RegState::Define) 8371 .addReg(AddrIn) 8372 .addImm(LdSize) 8373 .add(predOps(ARMCC::AL)); 8374 } else { // arm 8375 BuildMI(*BB, Pos, dl, TII->get(LdOpc), Data) 8376 .addReg(AddrOut, RegState::Define) 8377 .addReg(AddrIn) 8378 .addReg(0) 8379 .addImm(LdSize) 8380 .add(predOps(ARMCC::AL)); 8381 } 8382 } 8383 8384 /// Emit a post-increment store operation with given size. The instructions 8385 /// will be added to BB at Pos. 8386 static void emitPostSt(MachineBasicBlock *BB, MachineBasicBlock::iterator Pos, 8387 const TargetInstrInfo *TII, const DebugLoc &dl, 8388 unsigned StSize, unsigned Data, unsigned AddrIn, 8389 unsigned AddrOut, bool IsThumb1, bool IsThumb2) { 8390 unsigned StOpc = getStOpcode(StSize, IsThumb1, IsThumb2); 8391 assert(StOpc != 0 && "Should have a store opcode"); 8392 if (StSize >= 8) { 8393 BuildMI(*BB, Pos, dl, TII->get(StOpc), AddrOut) 8394 .addReg(AddrIn) 8395 .addImm(0) 8396 .addReg(Data) 8397 .add(predOps(ARMCC::AL)); 8398 } else if (IsThumb1) { 8399 // store + update AddrIn 8400 BuildMI(*BB, Pos, dl, TII->get(StOpc)) 8401 .addReg(Data) 8402 .addReg(AddrIn) 8403 .addImm(0) 8404 .add(predOps(ARMCC::AL)); 8405 BuildMI(*BB, Pos, dl, TII->get(ARM::tADDi8), AddrOut) 8406 .add(t1CondCodeOp()) 8407 .addReg(AddrIn) 8408 .addImm(StSize) 8409 .add(predOps(ARMCC::AL)); 8410 } else if (IsThumb2) { 8411 BuildMI(*BB, Pos, dl, TII->get(StOpc), AddrOut) 8412 .addReg(Data) 8413 .addReg(AddrIn) 8414 .addImm(StSize) 8415 .add(predOps(ARMCC::AL)); 8416 } else { // arm 8417 BuildMI(*BB, Pos, dl, TII->get(StOpc), AddrOut) 8418 .addReg(Data) 8419 .addReg(AddrIn) 8420 .addReg(0) 8421 .addImm(StSize) 8422 .add(predOps(ARMCC::AL)); 8423 } 8424 } 8425 8426 MachineBasicBlock * 8427 ARMTargetLowering::EmitStructByval(MachineInstr &MI, 8428 MachineBasicBlock *BB) const { 8429 // This pseudo instruction has 3 operands: dst, src, size 8430 // We expand it to a loop if size > Subtarget->getMaxInlineSizeThreshold(). 8431 // Otherwise, we will generate unrolled scalar copies. 8432 const TargetInstrInfo *TII = Subtarget->getInstrInfo(); 8433 const BasicBlock *LLVM_BB = BB->getBasicBlock(); 8434 MachineFunction::iterator It = ++BB->getIterator(); 8435 8436 unsigned dest = MI.getOperand(0).getReg(); 8437 unsigned src = MI.getOperand(1).getReg(); 8438 unsigned SizeVal = MI.getOperand(2).getImm(); 8439 unsigned Align = MI.getOperand(3).getImm(); 8440 DebugLoc dl = MI.getDebugLoc(); 8441 8442 MachineFunction *MF = BB->getParent(); 8443 MachineRegisterInfo &MRI = MF->getRegInfo(); 8444 unsigned UnitSize = 0; 8445 const TargetRegisterClass *TRC = nullptr; 8446 const TargetRegisterClass *VecTRC = nullptr; 8447 8448 bool IsThumb1 = Subtarget->isThumb1Only(); 8449 bool IsThumb2 = Subtarget->isThumb2(); 8450 bool IsThumb = Subtarget->isThumb(); 8451 8452 if (Align & 1) { 8453 UnitSize = 1; 8454 } else if (Align & 2) { 8455 UnitSize = 2; 8456 } else { 8457 // Check whether we can use NEON instructions. 8458 if (!MF->getFunction()->hasFnAttribute(Attribute::NoImplicitFloat) && 8459 Subtarget->hasNEON()) { 8460 if ((Align % 16 == 0) && SizeVal >= 16) 8461 UnitSize = 16; 8462 else if ((Align % 8 == 0) && SizeVal >= 8) 8463 UnitSize = 8; 8464 } 8465 // Can't use NEON instructions. 8466 if (UnitSize == 0) 8467 UnitSize = 4; 8468 } 8469 8470 // Select the correct opcode and register class for unit size load/store 8471 bool IsNeon = UnitSize >= 8; 8472 TRC = IsThumb ? &ARM::tGPRRegClass : &ARM::GPRRegClass; 8473 if (IsNeon) 8474 VecTRC = UnitSize == 16 ? &ARM::DPairRegClass 8475 : UnitSize == 8 ? &ARM::DPRRegClass 8476 : nullptr; 8477 8478 unsigned BytesLeft = SizeVal % UnitSize; 8479 unsigned LoopSize = SizeVal - BytesLeft; 8480 8481 if (SizeVal <= Subtarget->getMaxInlineSizeThreshold()) { 8482 // Use LDR and STR to copy. 8483 // [scratch, srcOut] = LDR_POST(srcIn, UnitSize) 8484 // [destOut] = STR_POST(scratch, destIn, UnitSize) 8485 unsigned srcIn = src; 8486 unsigned destIn = dest; 8487 for (unsigned i = 0; i < LoopSize; i+=UnitSize) { 8488 unsigned srcOut = MRI.createVirtualRegister(TRC); 8489 unsigned destOut = MRI.createVirtualRegister(TRC); 8490 unsigned scratch = MRI.createVirtualRegister(IsNeon ? VecTRC : TRC); 8491 emitPostLd(BB, MI, TII, dl, UnitSize, scratch, srcIn, srcOut, 8492 IsThumb1, IsThumb2); 8493 emitPostSt(BB, MI, TII, dl, UnitSize, scratch, destIn, destOut, 8494 IsThumb1, IsThumb2); 8495 srcIn = srcOut; 8496 destIn = destOut; 8497 } 8498 8499 // Handle the leftover bytes with LDRB and STRB. 8500 // [scratch, srcOut] = LDRB_POST(srcIn, 1) 8501 // [destOut] = STRB_POST(scratch, destIn, 1) 8502 for (unsigned i = 0; i < BytesLeft; i++) { 8503 unsigned srcOut = MRI.createVirtualRegister(TRC); 8504 unsigned destOut = MRI.createVirtualRegister(TRC); 8505 unsigned scratch = MRI.createVirtualRegister(TRC); 8506 emitPostLd(BB, MI, TII, dl, 1, scratch, srcIn, srcOut, 8507 IsThumb1, IsThumb2); 8508 emitPostSt(BB, MI, TII, dl, 1, scratch, destIn, destOut, 8509 IsThumb1, IsThumb2); 8510 srcIn = srcOut; 8511 destIn = destOut; 8512 } 8513 MI.eraseFromParent(); // The instruction is gone now. 8514 return BB; 8515 } 8516 8517 // Expand the pseudo op to a loop. 8518 // thisMBB: 8519 // ... 8520 // movw varEnd, # --> with thumb2 8521 // movt varEnd, # 8522 // ldrcp varEnd, idx --> without thumb2 8523 // fallthrough --> loopMBB 8524 // loopMBB: 8525 // PHI varPhi, varEnd, varLoop 8526 // PHI srcPhi, src, srcLoop 8527 // PHI destPhi, dst, destLoop 8528 // [scratch, srcLoop] = LDR_POST(srcPhi, UnitSize) 8529 // [destLoop] = STR_POST(scratch, destPhi, UnitSize) 8530 // subs varLoop, varPhi, #UnitSize 8531 // bne loopMBB 8532 // fallthrough --> exitMBB 8533 // exitMBB: 8534 // epilogue to handle left-over bytes 8535 // [scratch, srcOut] = LDRB_POST(srcLoop, 1) 8536 // [destOut] = STRB_POST(scratch, destLoop, 1) 8537 MachineBasicBlock *loopMBB = MF->CreateMachineBasicBlock(LLVM_BB); 8538 MachineBasicBlock *exitMBB = MF->CreateMachineBasicBlock(LLVM_BB); 8539 MF->insert(It, loopMBB); 8540 MF->insert(It, exitMBB); 8541 8542 // Transfer the remainder of BB and its successor edges to exitMBB. 8543 exitMBB->splice(exitMBB->begin(), BB, 8544 std::next(MachineBasicBlock::iterator(MI)), BB->end()); 8545 exitMBB->transferSuccessorsAndUpdatePHIs(BB); 8546 8547 // Load an immediate to varEnd. 8548 unsigned varEnd = MRI.createVirtualRegister(TRC); 8549 if (Subtarget->useMovt(*MF)) { 8550 unsigned Vtmp = varEnd; 8551 if ((LoopSize & 0xFFFF0000) != 0) 8552 Vtmp = MRI.createVirtualRegister(TRC); 8553 BuildMI(BB, dl, TII->get(IsThumb ? ARM::t2MOVi16 : ARM::MOVi16), Vtmp) 8554 .addImm(LoopSize & 0xFFFF) 8555 .add(predOps(ARMCC::AL)); 8556 8557 if ((LoopSize & 0xFFFF0000) != 0) 8558 BuildMI(BB, dl, TII->get(IsThumb ? ARM::t2MOVTi16 : ARM::MOVTi16), varEnd) 8559 .addReg(Vtmp) 8560 .addImm(LoopSize >> 16) 8561 .add(predOps(ARMCC::AL)); 8562 } else { 8563 MachineConstantPool *ConstantPool = MF->getConstantPool(); 8564 Type *Int32Ty = Type::getInt32Ty(MF->getFunction()->getContext()); 8565 const Constant *C = ConstantInt::get(Int32Ty, LoopSize); 8566 8567 // MachineConstantPool wants an explicit alignment. 8568 unsigned Align = MF->getDataLayout().getPrefTypeAlignment(Int32Ty); 8569 if (Align == 0) 8570 Align = MF->getDataLayout().getTypeAllocSize(C->getType()); 8571 unsigned Idx = ConstantPool->getConstantPoolIndex(C, Align); 8572 8573 if (IsThumb) 8574 BuildMI(*BB, MI, dl, TII->get(ARM::tLDRpci)) 8575 .addReg(varEnd, RegState::Define) 8576 .addConstantPoolIndex(Idx) 8577 .add(predOps(ARMCC::AL)); 8578 else 8579 BuildMI(*BB, MI, dl, TII->get(ARM::LDRcp)) 8580 .addReg(varEnd, RegState::Define) 8581 .addConstantPoolIndex(Idx) 8582 .addImm(0) 8583 .add(predOps(ARMCC::AL)); 8584 } 8585 BB->addSuccessor(loopMBB); 8586 8587 // Generate the loop body: 8588 // varPhi = PHI(varLoop, varEnd) 8589 // srcPhi = PHI(srcLoop, src) 8590 // destPhi = PHI(destLoop, dst) 8591 MachineBasicBlock *entryBB = BB; 8592 BB = loopMBB; 8593 unsigned varLoop = MRI.createVirtualRegister(TRC); 8594 unsigned varPhi = MRI.createVirtualRegister(TRC); 8595 unsigned srcLoop = MRI.createVirtualRegister(TRC); 8596 unsigned srcPhi = MRI.createVirtualRegister(TRC); 8597 unsigned destLoop = MRI.createVirtualRegister(TRC); 8598 unsigned destPhi = MRI.createVirtualRegister(TRC); 8599 8600 BuildMI(*BB, BB->begin(), dl, TII->get(ARM::PHI), varPhi) 8601 .addReg(varLoop).addMBB(loopMBB) 8602 .addReg(varEnd).addMBB(entryBB); 8603 BuildMI(BB, dl, TII->get(ARM::PHI), srcPhi) 8604 .addReg(srcLoop).addMBB(loopMBB) 8605 .addReg(src).addMBB(entryBB); 8606 BuildMI(BB, dl, TII->get(ARM::PHI), destPhi) 8607 .addReg(destLoop).addMBB(loopMBB) 8608 .addReg(dest).addMBB(entryBB); 8609 8610 // [scratch, srcLoop] = LDR_POST(srcPhi, UnitSize) 8611 // [destLoop] = STR_POST(scratch, destPhi, UnitSiz) 8612 unsigned scratch = MRI.createVirtualRegister(IsNeon ? VecTRC : TRC); 8613 emitPostLd(BB, BB->end(), TII, dl, UnitSize, scratch, srcPhi, srcLoop, 8614 IsThumb1, IsThumb2); 8615 emitPostSt(BB, BB->end(), TII, dl, UnitSize, scratch, destPhi, destLoop, 8616 IsThumb1, IsThumb2); 8617 8618 // Decrement loop variable by UnitSize. 8619 if (IsThumb1) { 8620 BuildMI(*BB, BB->end(), dl, TII->get(ARM::tSUBi8), varLoop) 8621 .add(t1CondCodeOp()) 8622 .addReg(varPhi) 8623 .addImm(UnitSize) 8624 .add(predOps(ARMCC::AL)); 8625 } else { 8626 MachineInstrBuilder MIB = 8627 BuildMI(*BB, BB->end(), dl, 8628 TII->get(IsThumb2 ? ARM::t2SUBri : ARM::SUBri), varLoop); 8629 MIB.addReg(varPhi) 8630 .addImm(UnitSize) 8631 .add(predOps(ARMCC::AL)) 8632 .add(condCodeOp()); 8633 MIB->getOperand(5).setReg(ARM::CPSR); 8634 MIB->getOperand(5).setIsDef(true); 8635 } 8636 BuildMI(*BB, BB->end(), dl, 8637 TII->get(IsThumb1 ? ARM::tBcc : IsThumb2 ? ARM::t2Bcc : ARM::Bcc)) 8638 .addMBB(loopMBB).addImm(ARMCC::NE).addReg(ARM::CPSR); 8639 8640 // loopMBB can loop back to loopMBB or fall through to exitMBB. 8641 BB->addSuccessor(loopMBB); 8642 BB->addSuccessor(exitMBB); 8643 8644 // Add epilogue to handle BytesLeft. 8645 BB = exitMBB; 8646 auto StartOfExit = exitMBB->begin(); 8647 8648 // [scratch, srcOut] = LDRB_POST(srcLoop, 1) 8649 // [destOut] = STRB_POST(scratch, destLoop, 1) 8650 unsigned srcIn = srcLoop; 8651 unsigned destIn = destLoop; 8652 for (unsigned i = 0; i < BytesLeft; i++) { 8653 unsigned srcOut = MRI.createVirtualRegister(TRC); 8654 unsigned destOut = MRI.createVirtualRegister(TRC); 8655 unsigned scratch = MRI.createVirtualRegister(TRC); 8656 emitPostLd(BB, StartOfExit, TII, dl, 1, scratch, srcIn, srcOut, 8657 IsThumb1, IsThumb2); 8658 emitPostSt(BB, StartOfExit, TII, dl, 1, scratch, destIn, destOut, 8659 IsThumb1, IsThumb2); 8660 srcIn = srcOut; 8661 destIn = destOut; 8662 } 8663 8664 MI.eraseFromParent(); // The instruction is gone now. 8665 return BB; 8666 } 8667 8668 MachineBasicBlock * 8669 ARMTargetLowering::EmitLowered__chkstk(MachineInstr &MI, 8670 MachineBasicBlock *MBB) const { 8671 const TargetMachine &TM = getTargetMachine(); 8672 const TargetInstrInfo &TII = *Subtarget->getInstrInfo(); 8673 DebugLoc DL = MI.getDebugLoc(); 8674 8675 assert(Subtarget->isTargetWindows() && 8676 "__chkstk is only supported on Windows"); 8677 assert(Subtarget->isThumb2() && "Windows on ARM requires Thumb-2 mode"); 8678 8679 // __chkstk takes the number of words to allocate on the stack in R4, and 8680 // returns the stack adjustment in number of bytes in R4. This will not 8681 // clober any other registers (other than the obvious lr). 8682 // 8683 // Although, technically, IP should be considered a register which may be 8684 // clobbered, the call itself will not touch it. Windows on ARM is a pure 8685 // thumb-2 environment, so there is no interworking required. As a result, we 8686 // do not expect a veneer to be emitted by the linker, clobbering IP. 8687 // 8688 // Each module receives its own copy of __chkstk, so no import thunk is 8689 // required, again, ensuring that IP is not clobbered. 8690 // 8691 // Finally, although some linkers may theoretically provide a trampoline for 8692 // out of range calls (which is quite common due to a 32M range limitation of 8693 // branches for Thumb), we can generate the long-call version via 8694 // -mcmodel=large, alleviating the need for the trampoline which may clobber 8695 // IP. 8696 8697 switch (TM.getCodeModel()) { 8698 case CodeModel::Small: 8699 case CodeModel::Medium: 8700 case CodeModel::Default: 8701 case CodeModel::Kernel: 8702 BuildMI(*MBB, MI, DL, TII.get(ARM::tBL)) 8703 .add(predOps(ARMCC::AL)) 8704 .addExternalSymbol("__chkstk") 8705 .addReg(ARM::R4, RegState::Implicit | RegState::Kill) 8706 .addReg(ARM::R4, RegState::Implicit | RegState::Define) 8707 .addReg(ARM::R12, 8708 RegState::Implicit | RegState::Define | RegState::Dead); 8709 break; 8710 case CodeModel::Large: 8711 case CodeModel::JITDefault: { 8712 MachineRegisterInfo &MRI = MBB->getParent()->getRegInfo(); 8713 unsigned Reg = MRI.createVirtualRegister(&ARM::rGPRRegClass); 8714 8715 BuildMI(*MBB, MI, DL, TII.get(ARM::t2MOVi32imm), Reg) 8716 .addExternalSymbol("__chkstk"); 8717 BuildMI(*MBB, MI, DL, TII.get(ARM::tBLXr)) 8718 .add(predOps(ARMCC::AL)) 8719 .addReg(Reg, RegState::Kill) 8720 .addReg(ARM::R4, RegState::Implicit | RegState::Kill) 8721 .addReg(ARM::R4, RegState::Implicit | RegState::Define) 8722 .addReg(ARM::R12, 8723 RegState::Implicit | RegState::Define | RegState::Dead); 8724 break; 8725 } 8726 } 8727 8728 BuildMI(*MBB, MI, DL, TII.get(ARM::t2SUBrr), ARM::SP) 8729 .addReg(ARM::SP, RegState::Kill) 8730 .addReg(ARM::R4, RegState::Kill) 8731 .setMIFlags(MachineInstr::FrameSetup) 8732 .add(predOps(ARMCC::AL)) 8733 .add(condCodeOp()); 8734 8735 MI.eraseFromParent(); 8736 return MBB; 8737 } 8738 8739 MachineBasicBlock * 8740 ARMTargetLowering::EmitLowered__dbzchk(MachineInstr &MI, 8741 MachineBasicBlock *MBB) const { 8742 DebugLoc DL = MI.getDebugLoc(); 8743 MachineFunction *MF = MBB->getParent(); 8744 const TargetInstrInfo *TII = Subtarget->getInstrInfo(); 8745 8746 MachineBasicBlock *ContBB = MF->CreateMachineBasicBlock(); 8747 MF->insert(++MBB->getIterator(), ContBB); 8748 ContBB->splice(ContBB->begin(), MBB, 8749 std::next(MachineBasicBlock::iterator(MI)), MBB->end()); 8750 ContBB->transferSuccessorsAndUpdatePHIs(MBB); 8751 MBB->addSuccessor(ContBB); 8752 8753 MachineBasicBlock *TrapBB = MF->CreateMachineBasicBlock(); 8754 BuildMI(TrapBB, DL, TII->get(ARM::t__brkdiv0)); 8755 MF->push_back(TrapBB); 8756 MBB->addSuccessor(TrapBB); 8757 8758 BuildMI(*MBB, MI, DL, TII->get(ARM::tCMPi8)) 8759 .addReg(MI.getOperand(0).getReg()) 8760 .addImm(0) 8761 .add(predOps(ARMCC::AL)); 8762 BuildMI(*MBB, MI, DL, TII->get(ARM::t2Bcc)) 8763 .addMBB(TrapBB) 8764 .addImm(ARMCC::EQ) 8765 .addReg(ARM::CPSR); 8766 8767 MI.eraseFromParent(); 8768 return ContBB; 8769 } 8770 8771 MachineBasicBlock * 8772 ARMTargetLowering::EmitInstrWithCustomInserter(MachineInstr &MI, 8773 MachineBasicBlock *BB) const { 8774 const TargetInstrInfo *TII = Subtarget->getInstrInfo(); 8775 DebugLoc dl = MI.getDebugLoc(); 8776 bool isThumb2 = Subtarget->isThumb2(); 8777 switch (MI.getOpcode()) { 8778 default: { 8779 MI.print(errs()); 8780 llvm_unreachable("Unexpected instr type to insert"); 8781 } 8782 8783 // Thumb1 post-indexed loads are really just single-register LDMs. 8784 case ARM::tLDR_postidx: { 8785 BuildMI(*BB, MI, dl, TII->get(ARM::tLDMIA_UPD)) 8786 .add(MI.getOperand(1)) // Rn_wb 8787 .add(MI.getOperand(2)) // Rn 8788 .add(MI.getOperand(3)) // PredImm 8789 .add(MI.getOperand(4)) // PredReg 8790 .add(MI.getOperand(0)); // Rt 8791 MI.eraseFromParent(); 8792 return BB; 8793 } 8794 8795 // The Thumb2 pre-indexed stores have the same MI operands, they just 8796 // define them differently in the .td files from the isel patterns, so 8797 // they need pseudos. 8798 case ARM::t2STR_preidx: 8799 MI.setDesc(TII->get(ARM::t2STR_PRE)); 8800 return BB; 8801 case ARM::t2STRB_preidx: 8802 MI.setDesc(TII->get(ARM::t2STRB_PRE)); 8803 return BB; 8804 case ARM::t2STRH_preidx: 8805 MI.setDesc(TII->get(ARM::t2STRH_PRE)); 8806 return BB; 8807 8808 case ARM::STRi_preidx: 8809 case ARM::STRBi_preidx: { 8810 unsigned NewOpc = MI.getOpcode() == ARM::STRi_preidx ? ARM::STR_PRE_IMM 8811 : ARM::STRB_PRE_IMM; 8812 // Decode the offset. 8813 unsigned Offset = MI.getOperand(4).getImm(); 8814 bool isSub = ARM_AM::getAM2Op(Offset) == ARM_AM::sub; 8815 Offset = ARM_AM::getAM2Offset(Offset); 8816 if (isSub) 8817 Offset = -Offset; 8818 8819 MachineMemOperand *MMO = *MI.memoperands_begin(); 8820 BuildMI(*BB, MI, dl, TII->get(NewOpc)) 8821 .add(MI.getOperand(0)) // Rn_wb 8822 .add(MI.getOperand(1)) // Rt 8823 .add(MI.getOperand(2)) // Rn 8824 .addImm(Offset) // offset (skip GPR==zero_reg) 8825 .add(MI.getOperand(5)) // pred 8826 .add(MI.getOperand(6)) 8827 .addMemOperand(MMO); 8828 MI.eraseFromParent(); 8829 return BB; 8830 } 8831 case ARM::STRr_preidx: 8832 case ARM::STRBr_preidx: 8833 case ARM::STRH_preidx: { 8834 unsigned NewOpc; 8835 switch (MI.getOpcode()) { 8836 default: llvm_unreachable("unexpected opcode!"); 8837 case ARM::STRr_preidx: NewOpc = ARM::STR_PRE_REG; break; 8838 case ARM::STRBr_preidx: NewOpc = ARM::STRB_PRE_REG; break; 8839 case ARM::STRH_preidx: NewOpc = ARM::STRH_PRE; break; 8840 } 8841 MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(NewOpc)); 8842 for (unsigned i = 0; i < MI.getNumOperands(); ++i) 8843 MIB.add(MI.getOperand(i)); 8844 MI.eraseFromParent(); 8845 return BB; 8846 } 8847 8848 case ARM::tMOVCCr_pseudo: { 8849 // To "insert" a SELECT_CC instruction, we actually have to insert the 8850 // diamond control-flow pattern. The incoming instruction knows the 8851 // destination vreg to set, the condition code register to branch on, the 8852 // true/false values to select between, and a branch opcode to use. 8853 const BasicBlock *LLVM_BB = BB->getBasicBlock(); 8854 MachineFunction::iterator It = ++BB->getIterator(); 8855 8856 // thisMBB: 8857 // ... 8858 // TrueVal = ... 8859 // cmpTY ccX, r1, r2 8860 // bCC copy1MBB 8861 // fallthrough --> copy0MBB 8862 MachineBasicBlock *thisMBB = BB; 8863 MachineFunction *F = BB->getParent(); 8864 MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB); 8865 MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB); 8866 F->insert(It, copy0MBB); 8867 F->insert(It, sinkMBB); 8868 8869 // Transfer the remainder of BB and its successor edges to sinkMBB. 8870 sinkMBB->splice(sinkMBB->begin(), BB, 8871 std::next(MachineBasicBlock::iterator(MI)), BB->end()); 8872 sinkMBB->transferSuccessorsAndUpdatePHIs(BB); 8873 8874 BB->addSuccessor(copy0MBB); 8875 BB->addSuccessor(sinkMBB); 8876 8877 BuildMI(BB, dl, TII->get(ARM::tBcc)) 8878 .addMBB(sinkMBB) 8879 .addImm(MI.getOperand(3).getImm()) 8880 .addReg(MI.getOperand(4).getReg()); 8881 8882 // copy0MBB: 8883 // %FalseValue = ... 8884 // # fallthrough to sinkMBB 8885 BB = copy0MBB; 8886 8887 // Update machine-CFG edges 8888 BB->addSuccessor(sinkMBB); 8889 8890 // sinkMBB: 8891 // %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ] 8892 // ... 8893 BB = sinkMBB; 8894 BuildMI(*BB, BB->begin(), dl, TII->get(ARM::PHI), MI.getOperand(0).getReg()) 8895 .addReg(MI.getOperand(1).getReg()) 8896 .addMBB(copy0MBB) 8897 .addReg(MI.getOperand(2).getReg()) 8898 .addMBB(thisMBB); 8899 8900 MI.eraseFromParent(); // The pseudo instruction is gone now. 8901 return BB; 8902 } 8903 8904 case ARM::BCCi64: 8905 case ARM::BCCZi64: { 8906 // If there is an unconditional branch to the other successor, remove it. 8907 BB->erase(std::next(MachineBasicBlock::iterator(MI)), BB->end()); 8908 8909 // Compare both parts that make up the double comparison separately for 8910 // equality. 8911 bool RHSisZero = MI.getOpcode() == ARM::BCCZi64; 8912 8913 unsigned LHS1 = MI.getOperand(1).getReg(); 8914 unsigned LHS2 = MI.getOperand(2).getReg(); 8915 if (RHSisZero) { 8916 BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri)) 8917 .addReg(LHS1) 8918 .addImm(0) 8919 .add(predOps(ARMCC::AL)); 8920 BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri)) 8921 .addReg(LHS2).addImm(0) 8922 .addImm(ARMCC::EQ).addReg(ARM::CPSR); 8923 } else { 8924 unsigned RHS1 = MI.getOperand(3).getReg(); 8925 unsigned RHS2 = MI.getOperand(4).getReg(); 8926 BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPrr : ARM::CMPrr)) 8927 .addReg(LHS1) 8928 .addReg(RHS1) 8929 .add(predOps(ARMCC::AL)); 8930 BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPrr : ARM::CMPrr)) 8931 .addReg(LHS2).addReg(RHS2) 8932 .addImm(ARMCC::EQ).addReg(ARM::CPSR); 8933 } 8934 8935 MachineBasicBlock *destMBB = MI.getOperand(RHSisZero ? 3 : 5).getMBB(); 8936 MachineBasicBlock *exitMBB = OtherSucc(BB, destMBB); 8937 if (MI.getOperand(0).getImm() == ARMCC::NE) 8938 std::swap(destMBB, exitMBB); 8939 8940 BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc)) 8941 .addMBB(destMBB).addImm(ARMCC::EQ).addReg(ARM::CPSR); 8942 if (isThumb2) 8943 BuildMI(BB, dl, TII->get(ARM::t2B)) 8944 .addMBB(exitMBB) 8945 .add(predOps(ARMCC::AL)); 8946 else 8947 BuildMI(BB, dl, TII->get(ARM::B)) .addMBB(exitMBB); 8948 8949 MI.eraseFromParent(); // The pseudo instruction is gone now. 8950 return BB; 8951 } 8952 8953 case ARM::Int_eh_sjlj_setjmp: 8954 case ARM::Int_eh_sjlj_setjmp_nofp: 8955 case ARM::tInt_eh_sjlj_setjmp: 8956 case ARM::t2Int_eh_sjlj_setjmp: 8957 case ARM::t2Int_eh_sjlj_setjmp_nofp: 8958 return BB; 8959 8960 case ARM::Int_eh_sjlj_setup_dispatch: 8961 EmitSjLjDispatchBlock(MI, BB); 8962 return BB; 8963 8964 case ARM::ABS: 8965 case ARM::t2ABS: { 8966 // To insert an ABS instruction, we have to insert the 8967 // diamond control-flow pattern. The incoming instruction knows the 8968 // source vreg to test against 0, the destination vreg to set, 8969 // the condition code register to branch on, the 8970 // true/false values to select between, and a branch opcode to use. 8971 // It transforms 8972 // V1 = ABS V0 8973 // into 8974 // V2 = MOVS V0 8975 // BCC (branch to SinkBB if V0 >= 0) 8976 // RSBBB: V3 = RSBri V2, 0 (compute ABS if V2 < 0) 8977 // SinkBB: V1 = PHI(V2, V3) 8978 const BasicBlock *LLVM_BB = BB->getBasicBlock(); 8979 MachineFunction::iterator BBI = ++BB->getIterator(); 8980 MachineFunction *Fn = BB->getParent(); 8981 MachineBasicBlock *RSBBB = Fn->CreateMachineBasicBlock(LLVM_BB); 8982 MachineBasicBlock *SinkBB = Fn->CreateMachineBasicBlock(LLVM_BB); 8983 Fn->insert(BBI, RSBBB); 8984 Fn->insert(BBI, SinkBB); 8985 8986 unsigned int ABSSrcReg = MI.getOperand(1).getReg(); 8987 unsigned int ABSDstReg = MI.getOperand(0).getReg(); 8988 bool ABSSrcKIll = MI.getOperand(1).isKill(); 8989 bool isThumb2 = Subtarget->isThumb2(); 8990 MachineRegisterInfo &MRI = Fn->getRegInfo(); 8991 // In Thumb mode S must not be specified if source register is the SP or 8992 // PC and if destination register is the SP, so restrict register class 8993 unsigned NewRsbDstReg = 8994 MRI.createVirtualRegister(isThumb2 ? &ARM::rGPRRegClass : &ARM::GPRRegClass); 8995 8996 // Transfer the remainder of BB and its successor edges to sinkMBB. 8997 SinkBB->splice(SinkBB->begin(), BB, 8998 std::next(MachineBasicBlock::iterator(MI)), BB->end()); 8999 SinkBB->transferSuccessorsAndUpdatePHIs(BB); 9000 9001 BB->addSuccessor(RSBBB); 9002 BB->addSuccessor(SinkBB); 9003 9004 // fall through to SinkMBB 9005 RSBBB->addSuccessor(SinkBB); 9006 9007 // insert a cmp at the end of BB 9008 BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri)) 9009 .addReg(ABSSrcReg) 9010 .addImm(0) 9011 .add(predOps(ARMCC::AL)); 9012 9013 // insert a bcc with opposite CC to ARMCC::MI at the end of BB 9014 BuildMI(BB, dl, 9015 TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc)).addMBB(SinkBB) 9016 .addImm(ARMCC::getOppositeCondition(ARMCC::MI)).addReg(ARM::CPSR); 9017 9018 // insert rsbri in RSBBB 9019 // Note: BCC and rsbri will be converted into predicated rsbmi 9020 // by if-conversion pass 9021 BuildMI(*RSBBB, RSBBB->begin(), dl, 9022 TII->get(isThumb2 ? ARM::t2RSBri : ARM::RSBri), NewRsbDstReg) 9023 .addReg(ABSSrcReg, ABSSrcKIll ? RegState::Kill : 0) 9024 .addImm(0) 9025 .add(predOps(ARMCC::AL)) 9026 .add(condCodeOp()); 9027 9028 // insert PHI in SinkBB, 9029 // reuse ABSDstReg to not change uses of ABS instruction 9030 BuildMI(*SinkBB, SinkBB->begin(), dl, 9031 TII->get(ARM::PHI), ABSDstReg) 9032 .addReg(NewRsbDstReg).addMBB(RSBBB) 9033 .addReg(ABSSrcReg).addMBB(BB); 9034 9035 // remove ABS instruction 9036 MI.eraseFromParent(); 9037 9038 // return last added BB 9039 return SinkBB; 9040 } 9041 case ARM::COPY_STRUCT_BYVAL_I32: 9042 ++NumLoopByVals; 9043 return EmitStructByval(MI, BB); 9044 case ARM::WIN__CHKSTK: 9045 return EmitLowered__chkstk(MI, BB); 9046 case ARM::WIN__DBZCHK: 9047 return EmitLowered__dbzchk(MI, BB); 9048 } 9049 } 9050 9051 /// \brief Attaches vregs to MEMCPY that it will use as scratch registers 9052 /// when it is expanded into LDM/STM. This is done as a post-isel lowering 9053 /// instead of as a custom inserter because we need the use list from the SDNode. 9054 static void attachMEMCPYScratchRegs(const ARMSubtarget *Subtarget, 9055 MachineInstr &MI, const SDNode *Node) { 9056 bool isThumb1 = Subtarget->isThumb1Only(); 9057 9058 DebugLoc DL = MI.getDebugLoc(); 9059 MachineFunction *MF = MI.getParent()->getParent(); 9060 MachineRegisterInfo &MRI = MF->getRegInfo(); 9061 MachineInstrBuilder MIB(*MF, MI); 9062 9063 // If the new dst/src is unused mark it as dead. 9064 if (!Node->hasAnyUseOfValue(0)) { 9065 MI.getOperand(0).setIsDead(true); 9066 } 9067 if (!Node->hasAnyUseOfValue(1)) { 9068 MI.getOperand(1).setIsDead(true); 9069 } 9070 9071 // The MEMCPY both defines and kills the scratch registers. 9072 for (unsigned I = 0; I != MI.getOperand(4).getImm(); ++I) { 9073 unsigned TmpReg = MRI.createVirtualRegister(isThumb1 ? &ARM::tGPRRegClass 9074 : &ARM::GPRRegClass); 9075 MIB.addReg(TmpReg, RegState::Define|RegState::Dead); 9076 } 9077 } 9078 9079 void ARMTargetLowering::AdjustInstrPostInstrSelection(MachineInstr &MI, 9080 SDNode *Node) const { 9081 if (MI.getOpcode() == ARM::MEMCPY) { 9082 attachMEMCPYScratchRegs(Subtarget, MI, Node); 9083 return; 9084 } 9085 9086 const MCInstrDesc *MCID = &MI.getDesc(); 9087 // Adjust potentially 's' setting instructions after isel, i.e. ADC, SBC, RSB, 9088 // RSC. Coming out of isel, they have an implicit CPSR def, but the optional 9089 // operand is still set to noreg. If needed, set the optional operand's 9090 // register to CPSR, and remove the redundant implicit def. 9091 // 9092 // e.g. ADCS (..., CPSR<imp-def>) -> ADC (... opt:CPSR<def>). 9093 9094 // Rename pseudo opcodes. 9095 unsigned NewOpc = convertAddSubFlagsOpcode(MI.getOpcode()); 9096 unsigned ccOutIdx; 9097 if (NewOpc) { 9098 const ARMBaseInstrInfo *TII = Subtarget->getInstrInfo(); 9099 MCID = &TII->get(NewOpc); 9100 9101 assert(MCID->getNumOperands() == 9102 MI.getDesc().getNumOperands() + 5 - MI.getDesc().getSize() 9103 && "converted opcode should be the same except for cc_out" 9104 " (and, on Thumb1, pred)"); 9105 9106 MI.setDesc(*MCID); 9107 9108 // Add the optional cc_out operand 9109 MI.addOperand(MachineOperand::CreateReg(0, /*isDef=*/true)); 9110 9111 // On Thumb1, move all input operands to the end, then add the predicate 9112 if (Subtarget->isThumb1Only()) { 9113 for (unsigned c = MCID->getNumOperands() - 4; c--;) { 9114 MI.addOperand(MI.getOperand(1)); 9115 MI.RemoveOperand(1); 9116 } 9117 9118 // Restore the ties 9119 for (unsigned i = MI.getNumOperands(); i--;) { 9120 const MachineOperand& op = MI.getOperand(i); 9121 if (op.isReg() && op.isUse()) { 9122 int DefIdx = MCID->getOperandConstraint(i, MCOI::TIED_TO); 9123 if (DefIdx != -1) 9124 MI.tieOperands(DefIdx, i); 9125 } 9126 } 9127 9128 MI.addOperand(MachineOperand::CreateImm(ARMCC::AL)); 9129 MI.addOperand(MachineOperand::CreateReg(0, /*isDef=*/false)); 9130 ccOutIdx = 1; 9131 } else 9132 ccOutIdx = MCID->getNumOperands() - 1; 9133 } else 9134 ccOutIdx = MCID->getNumOperands() - 1; 9135 9136 // Any ARM instruction that sets the 's' bit should specify an optional 9137 // "cc_out" operand in the last operand position. 9138 if (!MI.hasOptionalDef() || !MCID->OpInfo[ccOutIdx].isOptionalDef()) { 9139 assert(!NewOpc && "Optional cc_out operand required"); 9140 return; 9141 } 9142 // Look for an implicit def of CPSR added by MachineInstr ctor. Remove it 9143 // since we already have an optional CPSR def. 9144 bool definesCPSR = false; 9145 bool deadCPSR = false; 9146 for (unsigned i = MCID->getNumOperands(), e = MI.getNumOperands(); i != e; 9147 ++i) { 9148 const MachineOperand &MO = MI.getOperand(i); 9149 if (MO.isReg() && MO.isDef() && MO.getReg() == ARM::CPSR) { 9150 definesCPSR = true; 9151 if (MO.isDead()) 9152 deadCPSR = true; 9153 MI.RemoveOperand(i); 9154 break; 9155 } 9156 } 9157 if (!definesCPSR) { 9158 assert(!NewOpc && "Optional cc_out operand required"); 9159 return; 9160 } 9161 assert(deadCPSR == !Node->hasAnyUseOfValue(1) && "inconsistent dead flag"); 9162 if (deadCPSR) { 9163 assert(!MI.getOperand(ccOutIdx).getReg() && 9164 "expect uninitialized optional cc_out operand"); 9165 // Thumb1 instructions must have the S bit even if the CPSR is dead. 9166 if (!Subtarget->isThumb1Only()) 9167 return; 9168 } 9169 9170 // If this instruction was defined with an optional CPSR def and its dag node 9171 // had a live implicit CPSR def, then activate the optional CPSR def. 9172 MachineOperand &MO = MI.getOperand(ccOutIdx); 9173 MO.setReg(ARM::CPSR); 9174 MO.setIsDef(true); 9175 } 9176 9177 //===----------------------------------------------------------------------===// 9178 // ARM Optimization Hooks 9179 //===----------------------------------------------------------------------===// 9180 9181 // Helper function that checks if N is a null or all ones constant. 9182 static inline bool isZeroOrAllOnes(SDValue N, bool AllOnes) { 9183 return AllOnes ? isAllOnesConstant(N) : isNullConstant(N); 9184 } 9185 9186 // Return true if N is conditionally 0 or all ones. 9187 // Detects these expressions where cc is an i1 value: 9188 // 9189 // (select cc 0, y) [AllOnes=0] 9190 // (select cc y, 0) [AllOnes=0] 9191 // (zext cc) [AllOnes=0] 9192 // (sext cc) [AllOnes=0/1] 9193 // (select cc -1, y) [AllOnes=1] 9194 // (select cc y, -1) [AllOnes=1] 9195 // 9196 // Invert is set when N is the null/all ones constant when CC is false. 9197 // OtherOp is set to the alternative value of N. 9198 static bool isConditionalZeroOrAllOnes(SDNode *N, bool AllOnes, 9199 SDValue &CC, bool &Invert, 9200 SDValue &OtherOp, 9201 SelectionDAG &DAG) { 9202 switch (N->getOpcode()) { 9203 default: return false; 9204 case ISD::SELECT: { 9205 CC = N->getOperand(0); 9206 SDValue N1 = N->getOperand(1); 9207 SDValue N2 = N->getOperand(2); 9208 if (isZeroOrAllOnes(N1, AllOnes)) { 9209 Invert = false; 9210 OtherOp = N2; 9211 return true; 9212 } 9213 if (isZeroOrAllOnes(N2, AllOnes)) { 9214 Invert = true; 9215 OtherOp = N1; 9216 return true; 9217 } 9218 return false; 9219 } 9220 case ISD::ZERO_EXTEND: 9221 // (zext cc) can never be the all ones value. 9222 if (AllOnes) 9223 return false; 9224 LLVM_FALLTHROUGH; 9225 case ISD::SIGN_EXTEND: { 9226 SDLoc dl(N); 9227 EVT VT = N->getValueType(0); 9228 CC = N->getOperand(0); 9229 if (CC.getValueType() != MVT::i1 || CC.getOpcode() != ISD::SETCC) 9230 return false; 9231 Invert = !AllOnes; 9232 if (AllOnes) 9233 // When looking for an AllOnes constant, N is an sext, and the 'other' 9234 // value is 0. 9235 OtherOp = DAG.getConstant(0, dl, VT); 9236 else if (N->getOpcode() == ISD::ZERO_EXTEND) 9237 // When looking for a 0 constant, N can be zext or sext. 9238 OtherOp = DAG.getConstant(1, dl, VT); 9239 else 9240 OtherOp = DAG.getConstant(APInt::getAllOnesValue(VT.getSizeInBits()), dl, 9241 VT); 9242 return true; 9243 } 9244 } 9245 } 9246 9247 // Combine a constant select operand into its use: 9248 // 9249 // (add (select cc, 0, c), x) -> (select cc, x, (add, x, c)) 9250 // (sub x, (select cc, 0, c)) -> (select cc, x, (sub, x, c)) 9251 // (and (select cc, -1, c), x) -> (select cc, x, (and, x, c)) [AllOnes=1] 9252 // (or (select cc, 0, c), x) -> (select cc, x, (or, x, c)) 9253 // (xor (select cc, 0, c), x) -> (select cc, x, (xor, x, c)) 9254 // 9255 // The transform is rejected if the select doesn't have a constant operand that 9256 // is null, or all ones when AllOnes is set. 9257 // 9258 // Also recognize sext/zext from i1: 9259 // 9260 // (add (zext cc), x) -> (select cc (add x, 1), x) 9261 // (add (sext cc), x) -> (select cc (add x, -1), x) 9262 // 9263 // These transformations eventually create predicated instructions. 9264 // 9265 // @param N The node to transform. 9266 // @param Slct The N operand that is a select. 9267 // @param OtherOp The other N operand (x above). 9268 // @param DCI Context. 9269 // @param AllOnes Require the select constant to be all ones instead of null. 9270 // @returns The new node, or SDValue() on failure. 9271 static 9272 SDValue combineSelectAndUse(SDNode *N, SDValue Slct, SDValue OtherOp, 9273 TargetLowering::DAGCombinerInfo &DCI, 9274 bool AllOnes = false) { 9275 SelectionDAG &DAG = DCI.DAG; 9276 EVT VT = N->getValueType(0); 9277 SDValue NonConstantVal; 9278 SDValue CCOp; 9279 bool SwapSelectOps; 9280 if (!isConditionalZeroOrAllOnes(Slct.getNode(), AllOnes, CCOp, SwapSelectOps, 9281 NonConstantVal, DAG)) 9282 return SDValue(); 9283 9284 // Slct is now know to be the desired identity constant when CC is true. 9285 SDValue TrueVal = OtherOp; 9286 SDValue FalseVal = DAG.getNode(N->getOpcode(), SDLoc(N), VT, 9287 OtherOp, NonConstantVal); 9288 // Unless SwapSelectOps says CC should be false. 9289 if (SwapSelectOps) 9290 std::swap(TrueVal, FalseVal); 9291 9292 return DAG.getNode(ISD::SELECT, SDLoc(N), VT, 9293 CCOp, TrueVal, FalseVal); 9294 } 9295 9296 // Attempt combineSelectAndUse on each operand of a commutative operator N. 9297 static 9298 SDValue combineSelectAndUseCommutative(SDNode *N, bool AllOnes, 9299 TargetLowering::DAGCombinerInfo &DCI) { 9300 SDValue N0 = N->getOperand(0); 9301 SDValue N1 = N->getOperand(1); 9302 if (N0.getNode()->hasOneUse()) 9303 if (SDValue Result = combineSelectAndUse(N, N0, N1, DCI, AllOnes)) 9304 return Result; 9305 if (N1.getNode()->hasOneUse()) 9306 if (SDValue Result = combineSelectAndUse(N, N1, N0, DCI, AllOnes)) 9307 return Result; 9308 return SDValue(); 9309 } 9310 9311 static bool IsVUZPShuffleNode(SDNode *N) { 9312 // VUZP shuffle node. 9313 if (N->getOpcode() == ARMISD::VUZP) 9314 return true; 9315 9316 // "VUZP" on i32 is an alias for VTRN. 9317 if (N->getOpcode() == ARMISD::VTRN && N->getValueType(0) == MVT::v2i32) 9318 return true; 9319 9320 return false; 9321 } 9322 9323 static SDValue AddCombineToVPADD(SDNode *N, SDValue N0, SDValue N1, 9324 TargetLowering::DAGCombinerInfo &DCI, 9325 const ARMSubtarget *Subtarget) { 9326 // Look for ADD(VUZP.0, VUZP.1). 9327 if (!IsVUZPShuffleNode(N0.getNode()) || N0.getNode() != N1.getNode() || 9328 N0 == N1) 9329 return SDValue(); 9330 9331 // Make sure the ADD is a 64-bit add; there is no 128-bit VPADD. 9332 if (!N->getValueType(0).is64BitVector()) 9333 return SDValue(); 9334 9335 // Generate vpadd. 9336 SelectionDAG &DAG = DCI.DAG; 9337 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 9338 SDLoc dl(N); 9339 SDNode *Unzip = N0.getNode(); 9340 EVT VT = N->getValueType(0); 9341 9342 SmallVector<SDValue, 8> Ops; 9343 Ops.push_back(DAG.getConstant(Intrinsic::arm_neon_vpadd, dl, 9344 TLI.getPointerTy(DAG.getDataLayout()))); 9345 Ops.push_back(Unzip->getOperand(0)); 9346 Ops.push_back(Unzip->getOperand(1)); 9347 9348 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT, Ops); 9349 } 9350 9351 static SDValue AddCombineVUZPToVPADDL(SDNode *N, SDValue N0, SDValue N1, 9352 TargetLowering::DAGCombinerInfo &DCI, 9353 const ARMSubtarget *Subtarget) { 9354 // Check for two extended operands. 9355 if (!(N0.getOpcode() == ISD::SIGN_EXTEND && 9356 N1.getOpcode() == ISD::SIGN_EXTEND) && 9357 !(N0.getOpcode() == ISD::ZERO_EXTEND && 9358 N1.getOpcode() == ISD::ZERO_EXTEND)) 9359 return SDValue(); 9360 9361 SDValue N00 = N0.getOperand(0); 9362 SDValue N10 = N1.getOperand(0); 9363 9364 // Look for ADD(SEXT(VUZP.0), SEXT(VUZP.1)) 9365 if (!IsVUZPShuffleNode(N00.getNode()) || N00.getNode() != N10.getNode() || 9366 N00 == N10) 9367 return SDValue(); 9368 9369 // We only recognize Q register paddl here; this can't be reached until 9370 // after type legalization. 9371 if (!N00.getValueType().is64BitVector() || 9372 !N0.getValueType().is128BitVector()) 9373 return SDValue(); 9374 9375 // Generate vpaddl. 9376 SelectionDAG &DAG = DCI.DAG; 9377 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 9378 SDLoc dl(N); 9379 EVT VT = N->getValueType(0); 9380 9381 SmallVector<SDValue, 8> Ops; 9382 // Form vpaddl.sN or vpaddl.uN depending on the kind of extension. 9383 unsigned Opcode; 9384 if (N0.getOpcode() == ISD::SIGN_EXTEND) 9385 Opcode = Intrinsic::arm_neon_vpaddls; 9386 else 9387 Opcode = Intrinsic::arm_neon_vpaddlu; 9388 Ops.push_back(DAG.getConstant(Opcode, dl, 9389 TLI.getPointerTy(DAG.getDataLayout()))); 9390 EVT ElemTy = N00.getValueType().getVectorElementType(); 9391 unsigned NumElts = VT.getVectorNumElements(); 9392 EVT ConcatVT = EVT::getVectorVT(*DAG.getContext(), ElemTy, NumElts * 2); 9393 SDValue Concat = DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), ConcatVT, 9394 N00.getOperand(0), N00.getOperand(1)); 9395 Ops.push_back(Concat); 9396 9397 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT, Ops); 9398 } 9399 9400 // FIXME: This function shouldn't be necessary; if we lower BUILD_VECTOR in 9401 // an appropriate manner, we end up with ADD(VUZP(ZEXT(N))), which is 9402 // much easier to match. 9403 static SDValue 9404 AddCombineBUILD_VECTORToVPADDL(SDNode *N, SDValue N0, SDValue N1, 9405 TargetLowering::DAGCombinerInfo &DCI, 9406 const ARMSubtarget *Subtarget) { 9407 // Only perform optimization if after legalize, and if NEON is available. We 9408 // also expected both operands to be BUILD_VECTORs. 9409 if (DCI.isBeforeLegalize() || !Subtarget->hasNEON() 9410 || N0.getOpcode() != ISD::BUILD_VECTOR 9411 || N1.getOpcode() != ISD::BUILD_VECTOR) 9412 return SDValue(); 9413 9414 // Check output type since VPADDL operand elements can only be 8, 16, or 32. 9415 EVT VT = N->getValueType(0); 9416 if (!VT.isInteger() || VT.getVectorElementType() == MVT::i64) 9417 return SDValue(); 9418 9419 // Check that the vector operands are of the right form. 9420 // N0 and N1 are BUILD_VECTOR nodes with N number of EXTRACT_VECTOR 9421 // operands, where N is the size of the formed vector. 9422 // Each EXTRACT_VECTOR should have the same input vector and odd or even 9423 // index such that we have a pair wise add pattern. 9424 9425 // Grab the vector that all EXTRACT_VECTOR nodes should be referencing. 9426 if (N0->getOperand(0)->getOpcode() != ISD::EXTRACT_VECTOR_ELT) 9427 return SDValue(); 9428 SDValue Vec = N0->getOperand(0)->getOperand(0); 9429 SDNode *V = Vec.getNode(); 9430 unsigned nextIndex = 0; 9431 9432 // For each operands to the ADD which are BUILD_VECTORs, 9433 // check to see if each of their operands are an EXTRACT_VECTOR with 9434 // the same vector and appropriate index. 9435 for (unsigned i = 0, e = N0->getNumOperands(); i != e; ++i) { 9436 if (N0->getOperand(i)->getOpcode() == ISD::EXTRACT_VECTOR_ELT 9437 && N1->getOperand(i)->getOpcode() == ISD::EXTRACT_VECTOR_ELT) { 9438 9439 SDValue ExtVec0 = N0->getOperand(i); 9440 SDValue ExtVec1 = N1->getOperand(i); 9441 9442 // First operand is the vector, verify its the same. 9443 if (V != ExtVec0->getOperand(0).getNode() || 9444 V != ExtVec1->getOperand(0).getNode()) 9445 return SDValue(); 9446 9447 // Second is the constant, verify its correct. 9448 ConstantSDNode *C0 = dyn_cast<ConstantSDNode>(ExtVec0->getOperand(1)); 9449 ConstantSDNode *C1 = dyn_cast<ConstantSDNode>(ExtVec1->getOperand(1)); 9450 9451 // For the constant, we want to see all the even or all the odd. 9452 if (!C0 || !C1 || C0->getZExtValue() != nextIndex 9453 || C1->getZExtValue() != nextIndex+1) 9454 return SDValue(); 9455 9456 // Increment index. 9457 nextIndex+=2; 9458 } else 9459 return SDValue(); 9460 } 9461 9462 // Don't generate vpaddl+vmovn; we'll match it to vpadd later. 9463 if (Vec.getValueType().getVectorElementType() == VT.getVectorElementType()) 9464 return SDValue(); 9465 9466 // Create VPADDL node. 9467 SelectionDAG &DAG = DCI.DAG; 9468 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 9469 9470 SDLoc dl(N); 9471 9472 // Build operand list. 9473 SmallVector<SDValue, 8> Ops; 9474 Ops.push_back(DAG.getConstant(Intrinsic::arm_neon_vpaddls, dl, 9475 TLI.getPointerTy(DAG.getDataLayout()))); 9476 9477 // Input is the vector. 9478 Ops.push_back(Vec); 9479 9480 // Get widened type and narrowed type. 9481 MVT widenType; 9482 unsigned numElem = VT.getVectorNumElements(); 9483 9484 EVT inputLaneType = Vec.getValueType().getVectorElementType(); 9485 switch (inputLaneType.getSimpleVT().SimpleTy) { 9486 case MVT::i8: widenType = MVT::getVectorVT(MVT::i16, numElem); break; 9487 case MVT::i16: widenType = MVT::getVectorVT(MVT::i32, numElem); break; 9488 case MVT::i32: widenType = MVT::getVectorVT(MVT::i64, numElem); break; 9489 default: 9490 llvm_unreachable("Invalid vector element type for padd optimization."); 9491 } 9492 9493 SDValue tmp = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, widenType, Ops); 9494 unsigned ExtOp = VT.bitsGT(tmp.getValueType()) ? ISD::ANY_EXTEND : ISD::TRUNCATE; 9495 return DAG.getNode(ExtOp, dl, VT, tmp); 9496 } 9497 9498 static SDValue findMUL_LOHI(SDValue V) { 9499 if (V->getOpcode() == ISD::UMUL_LOHI || 9500 V->getOpcode() == ISD::SMUL_LOHI) 9501 return V; 9502 return SDValue(); 9503 } 9504 9505 static SDValue AddCombineTo64BitSMLAL16(SDNode *AddcNode, SDNode *AddeNode, 9506 TargetLowering::DAGCombinerInfo &DCI, 9507 const ARMSubtarget *Subtarget) { 9508 9509 if (Subtarget->isThumb()) { 9510 if (!Subtarget->hasDSP()) 9511 return SDValue(); 9512 } else if (!Subtarget->hasV5TEOps()) 9513 return SDValue(); 9514 9515 // SMLALBB, SMLALBT, SMLALTB, SMLALTT multiply two 16-bit values and 9516 // accumulates the product into a 64-bit value. The 16-bit values will 9517 // be sign extended somehow or SRA'd into 32-bit values 9518 // (addc (adde (mul 16bit, 16bit), lo), hi) 9519 SDValue Mul = AddcNode->getOperand(0); 9520 SDValue Lo = AddcNode->getOperand(1); 9521 if (Mul.getOpcode() != ISD::MUL) { 9522 Lo = AddcNode->getOperand(0); 9523 Mul = AddcNode->getOperand(1); 9524 if (Mul.getOpcode() != ISD::MUL) 9525 return SDValue(); 9526 } 9527 9528 SDValue SRA = AddeNode->getOperand(0); 9529 SDValue Hi = AddeNode->getOperand(1); 9530 if (SRA.getOpcode() != ISD::SRA) { 9531 SRA = AddeNode->getOperand(1); 9532 Hi = AddeNode->getOperand(0); 9533 if (SRA.getOpcode() != ISD::SRA) 9534 return SDValue(); 9535 } 9536 if (auto Const = dyn_cast<ConstantSDNode>(SRA.getOperand(1))) { 9537 if (Const->getZExtValue() != 31) 9538 return SDValue(); 9539 } else 9540 return SDValue(); 9541 9542 if (SRA.getOperand(0) != Mul) 9543 return SDValue(); 9544 9545 SelectionDAG &DAG = DCI.DAG; 9546 SDLoc dl(AddcNode); 9547 unsigned Opcode = 0; 9548 SDValue Op0; 9549 SDValue Op1; 9550 9551 if (isS16(Mul.getOperand(0), DAG) && isS16(Mul.getOperand(1), DAG)) { 9552 Opcode = ARMISD::SMLALBB; 9553 Op0 = Mul.getOperand(0); 9554 Op1 = Mul.getOperand(1); 9555 } else if (isS16(Mul.getOperand(0), DAG) && isSRA16(Mul.getOperand(1))) { 9556 Opcode = ARMISD::SMLALBT; 9557 Op0 = Mul.getOperand(0); 9558 Op1 = Mul.getOperand(1).getOperand(0); 9559 } else if (isSRA16(Mul.getOperand(0)) && isS16(Mul.getOperand(1), DAG)) { 9560 Opcode = ARMISD::SMLALTB; 9561 Op0 = Mul.getOperand(0).getOperand(0); 9562 Op1 = Mul.getOperand(1); 9563 } else if (isSRA16(Mul.getOperand(0)) && isSRA16(Mul.getOperand(1))) { 9564 Opcode = ARMISD::SMLALTT; 9565 Op0 = Mul->getOperand(0).getOperand(0); 9566 Op1 = Mul->getOperand(1).getOperand(0); 9567 } 9568 9569 if (!Op0 || !Op1) 9570 return SDValue(); 9571 9572 SDValue SMLAL = DAG.getNode(Opcode, dl, DAG.getVTList(MVT::i32, MVT::i32), 9573 Op0, Op1, Lo, Hi); 9574 // Replace the ADDs' nodes uses by the MLA node's values. 9575 SDValue HiMLALResult(SMLAL.getNode(), 1); 9576 SDValue LoMLALResult(SMLAL.getNode(), 0); 9577 9578 DAG.ReplaceAllUsesOfValueWith(SDValue(AddcNode, 0), LoMLALResult); 9579 DAG.ReplaceAllUsesOfValueWith(SDValue(AddeNode, 0), HiMLALResult); 9580 9581 // Return original node to notify the driver to stop replacing. 9582 SDValue resNode(AddcNode, 0); 9583 return resNode; 9584 } 9585 9586 static SDValue AddCombineTo64bitMLAL(SDNode *AddeNode, 9587 TargetLowering::DAGCombinerInfo &DCI, 9588 const ARMSubtarget *Subtarget) { 9589 // Look for multiply add opportunities. 9590 // The pattern is a ISD::UMUL_LOHI followed by two add nodes, where 9591 // each add nodes consumes a value from ISD::UMUL_LOHI and there is 9592 // a glue link from the first add to the second add. 9593 // If we find this pattern, we can replace the U/SMUL_LOHI, ADDC, and ADDE by 9594 // a S/UMLAL instruction. 9595 // UMUL_LOHI 9596 // / :lo \ :hi 9597 // / \ [no multiline comment] 9598 // loAdd -> ADDE | 9599 // \ :glue / 9600 // \ / 9601 // ADDC <- hiAdd 9602 // 9603 assert(AddeNode->getOpcode() == ARMISD::ADDE && "Expect an ADDE"); 9604 9605 assert(AddeNode->getNumOperands() == 3 && 9606 AddeNode->getOperand(2).getValueType() == MVT::i32 && 9607 "ADDE node has the wrong inputs"); 9608 9609 // Check that we have a glued ADDC node. 9610 SDNode* AddcNode = AddeNode->getOperand(2).getNode(); 9611 if (AddcNode->getOpcode() != ARMISD::ADDC) 9612 return SDValue(); 9613 9614 SDValue AddcOp0 = AddcNode->getOperand(0); 9615 SDValue AddcOp1 = AddcNode->getOperand(1); 9616 9617 // Check if the two operands are from the same mul_lohi node. 9618 if (AddcOp0.getNode() == AddcOp1.getNode()) 9619 return SDValue(); 9620 9621 assert(AddcNode->getNumValues() == 2 && 9622 AddcNode->getValueType(0) == MVT::i32 && 9623 "Expect ADDC with two result values. First: i32"); 9624 9625 // Check that the ADDC adds the low result of the S/UMUL_LOHI. If not, it 9626 // maybe a SMLAL which multiplies two 16-bit values. 9627 if (AddcOp0->getOpcode() != ISD::UMUL_LOHI && 9628 AddcOp0->getOpcode() != ISD::SMUL_LOHI && 9629 AddcOp1->getOpcode() != ISD::UMUL_LOHI && 9630 AddcOp1->getOpcode() != ISD::SMUL_LOHI) 9631 return AddCombineTo64BitSMLAL16(AddcNode, AddeNode, DCI, Subtarget); 9632 9633 // Check for the triangle shape. 9634 SDValue AddeOp0 = AddeNode->getOperand(0); 9635 SDValue AddeOp1 = AddeNode->getOperand(1); 9636 9637 // Make sure that the ADDE operands are not coming from the same node. 9638 if (AddeOp0.getNode() == AddeOp1.getNode()) 9639 return SDValue(); 9640 9641 // Find the MUL_LOHI node walking up ADDE's operands. 9642 bool IsLeftOperandMUL = false; 9643 SDValue MULOp = findMUL_LOHI(AddeOp0); 9644 if (MULOp == SDValue()) 9645 MULOp = findMUL_LOHI(AddeOp1); 9646 else 9647 IsLeftOperandMUL = true; 9648 if (MULOp == SDValue()) 9649 return SDValue(); 9650 9651 // Figure out the right opcode. 9652 unsigned Opc = MULOp->getOpcode(); 9653 unsigned FinalOpc = (Opc == ISD::SMUL_LOHI) ? ARMISD::SMLAL : ARMISD::UMLAL; 9654 9655 // Figure out the high and low input values to the MLAL node. 9656 SDValue* HiAdd = nullptr; 9657 SDValue* LoMul = nullptr; 9658 SDValue* LowAdd = nullptr; 9659 9660 // Ensure that ADDE is from high result of ISD::SMUL_LOHI. 9661 if ((AddeOp0 != MULOp.getValue(1)) && (AddeOp1 != MULOp.getValue(1))) 9662 return SDValue(); 9663 9664 if (IsLeftOperandMUL) 9665 HiAdd = &AddeOp1; 9666 else 9667 HiAdd = &AddeOp0; 9668 9669 9670 // Ensure that LoMul and LowAdd are taken from correct ISD::SMUL_LOHI node 9671 // whose low result is fed to the ADDC we are checking. 9672 9673 if (AddcOp0 == MULOp.getValue(0)) { 9674 LoMul = &AddcOp0; 9675 LowAdd = &AddcOp1; 9676 } 9677 if (AddcOp1 == MULOp.getValue(0)) { 9678 LoMul = &AddcOp1; 9679 LowAdd = &AddcOp0; 9680 } 9681 9682 if (!LoMul) 9683 return SDValue(); 9684 9685 // Create the merged node. 9686 SelectionDAG &DAG = DCI.DAG; 9687 9688 // Build operand list. 9689 SmallVector<SDValue, 8> Ops; 9690 Ops.push_back(LoMul->getOperand(0)); 9691 Ops.push_back(LoMul->getOperand(1)); 9692 Ops.push_back(*LowAdd); 9693 Ops.push_back(*HiAdd); 9694 9695 SDValue MLALNode = DAG.getNode(FinalOpc, SDLoc(AddcNode), 9696 DAG.getVTList(MVT::i32, MVT::i32), Ops); 9697 9698 // Replace the ADDs' nodes uses by the MLA node's values. 9699 SDValue HiMLALResult(MLALNode.getNode(), 1); 9700 DAG.ReplaceAllUsesOfValueWith(SDValue(AddeNode, 0), HiMLALResult); 9701 9702 SDValue LoMLALResult(MLALNode.getNode(), 0); 9703 DAG.ReplaceAllUsesOfValueWith(SDValue(AddcNode, 0), LoMLALResult); 9704 9705 // Return original node to notify the driver to stop replacing. 9706 return SDValue(AddeNode, 0); 9707 } 9708 9709 static SDValue AddCombineTo64bitUMAAL(SDNode *AddeNode, 9710 TargetLowering::DAGCombinerInfo &DCI, 9711 const ARMSubtarget *Subtarget) { 9712 // UMAAL is similar to UMLAL except that it adds two unsigned values. 9713 // While trying to combine for the other MLAL nodes, first search for the 9714 // chance to use UMAAL. Check if Addc uses a node which has already 9715 // been combined into a UMLAL. The other pattern is UMLAL using Addc/Adde 9716 // as the addend, and it's handled in PerformUMLALCombine. 9717 9718 if (!Subtarget->hasV6Ops() || !Subtarget->hasDSP()) 9719 return AddCombineTo64bitMLAL(AddeNode, DCI, Subtarget); 9720 9721 // Check that we have a glued ADDC node. 9722 SDNode* AddcNode = AddeNode->getOperand(2).getNode(); 9723 if (AddcNode->getOpcode() != ARMISD::ADDC) 9724 return SDValue(); 9725 9726 // Find the converted UMAAL or quit if it doesn't exist. 9727 SDNode *UmlalNode = nullptr; 9728 SDValue AddHi; 9729 if (AddcNode->getOperand(0).getOpcode() == ARMISD::UMLAL) { 9730 UmlalNode = AddcNode->getOperand(0).getNode(); 9731 AddHi = AddcNode->getOperand(1); 9732 } else if (AddcNode->getOperand(1).getOpcode() == ARMISD::UMLAL) { 9733 UmlalNode = AddcNode->getOperand(1).getNode(); 9734 AddHi = AddcNode->getOperand(0); 9735 } else { 9736 return AddCombineTo64bitMLAL(AddeNode, DCI, Subtarget); 9737 } 9738 9739 // The ADDC should be glued to an ADDE node, which uses the same UMLAL as 9740 // the ADDC as well as Zero. 9741 if (!isNullConstant(UmlalNode->getOperand(3))) 9742 return SDValue(); 9743 9744 if ((isNullConstant(AddeNode->getOperand(0)) && 9745 AddeNode->getOperand(1).getNode() == UmlalNode) || 9746 (AddeNode->getOperand(0).getNode() == UmlalNode && 9747 isNullConstant(AddeNode->getOperand(1)))) { 9748 9749 SelectionDAG &DAG = DCI.DAG; 9750 SDValue Ops[] = { UmlalNode->getOperand(0), UmlalNode->getOperand(1), 9751 UmlalNode->getOperand(2), AddHi }; 9752 SDValue UMAAL = DAG.getNode(ARMISD::UMAAL, SDLoc(AddcNode), 9753 DAG.getVTList(MVT::i32, MVT::i32), Ops); 9754 9755 // Replace the ADDs' nodes uses by the UMAAL node's values. 9756 DAG.ReplaceAllUsesOfValueWith(SDValue(AddeNode, 0), SDValue(UMAAL.getNode(), 1)); 9757 DAG.ReplaceAllUsesOfValueWith(SDValue(AddcNode, 0), SDValue(UMAAL.getNode(), 0)); 9758 9759 // Return original node to notify the driver to stop replacing. 9760 return SDValue(AddeNode, 0); 9761 } 9762 return SDValue(); 9763 } 9764 9765 static SDValue PerformUMLALCombine(SDNode *N, SelectionDAG &DAG, 9766 const ARMSubtarget *Subtarget) { 9767 if (!Subtarget->hasV6Ops() || !Subtarget->hasDSP()) 9768 return SDValue(); 9769 9770 // Check that we have a pair of ADDC and ADDE as operands. 9771 // Both addends of the ADDE must be zero. 9772 SDNode* AddcNode = N->getOperand(2).getNode(); 9773 SDNode* AddeNode = N->getOperand(3).getNode(); 9774 if ((AddcNode->getOpcode() == ARMISD::ADDC) && 9775 (AddeNode->getOpcode() == ARMISD::ADDE) && 9776 isNullConstant(AddeNode->getOperand(0)) && 9777 isNullConstant(AddeNode->getOperand(1)) && 9778 (AddeNode->getOperand(2).getNode() == AddcNode)) 9779 return DAG.getNode(ARMISD::UMAAL, SDLoc(N), 9780 DAG.getVTList(MVT::i32, MVT::i32), 9781 {N->getOperand(0), N->getOperand(1), 9782 AddcNode->getOperand(0), AddcNode->getOperand(1)}); 9783 else 9784 return SDValue(); 9785 } 9786 9787 static SDValue PerformAddcSubcCombine(SDNode *N, SelectionDAG &DAG, 9788 const ARMSubtarget *Subtarget) { 9789 if (Subtarget->isThumb1Only()) { 9790 SDValue RHS = N->getOperand(1); 9791 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS)) { 9792 int32_t imm = C->getSExtValue(); 9793 if (imm < 0 && imm > INT_MIN) { 9794 SDLoc DL(N); 9795 RHS = DAG.getConstant(-imm, DL, MVT::i32); 9796 unsigned Opcode = (N->getOpcode() == ARMISD::ADDC) ? ARMISD::SUBC 9797 : ARMISD::ADDC; 9798 return DAG.getNode(Opcode, DL, N->getVTList(), N->getOperand(0), RHS); 9799 } 9800 } 9801 } 9802 return SDValue(); 9803 } 9804 9805 static SDValue PerformAddeSubeCombine(SDNode *N, SelectionDAG &DAG, 9806 const ARMSubtarget *Subtarget) { 9807 if (Subtarget->isThumb1Only()) { 9808 SDValue RHS = N->getOperand(1); 9809 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS)) { 9810 int64_t imm = C->getSExtValue(); 9811 if (imm < 0) { 9812 SDLoc DL(N); 9813 9814 // The with-carry-in form matches bitwise not instead of the negation. 9815 // Effectively, the inverse interpretation of the carry flag already 9816 // accounts for part of the negation. 9817 RHS = DAG.getConstant(~imm, DL, MVT::i32); 9818 9819 unsigned Opcode = (N->getOpcode() == ARMISD::ADDE) ? ARMISD::SUBE 9820 : ARMISD::ADDE; 9821 return DAG.getNode(Opcode, DL, N->getVTList(), 9822 N->getOperand(0), RHS, N->getOperand(2)); 9823 } 9824 } 9825 } 9826 return SDValue(); 9827 } 9828 9829 /// PerformADDECombine - Target-specific dag combine transform from 9830 /// ARMISD::ADDC, ARMISD::ADDE, and ISD::MUL_LOHI to MLAL or 9831 /// ARMISD::ADDC, ARMISD::ADDE and ARMISD::UMLAL to ARMISD::UMAAL 9832 static SDValue PerformADDECombine(SDNode *N, 9833 TargetLowering::DAGCombinerInfo &DCI, 9834 const ARMSubtarget *Subtarget) { 9835 // Only ARM and Thumb2 support UMLAL/SMLAL. 9836 if (Subtarget->isThumb1Only()) 9837 return PerformAddeSubeCombine(N, DCI.DAG, Subtarget); 9838 9839 // Only perform the checks after legalize when the pattern is available. 9840 if (DCI.isBeforeLegalize()) return SDValue(); 9841 9842 return AddCombineTo64bitUMAAL(N, DCI, Subtarget); 9843 } 9844 9845 /// PerformADDCombineWithOperands - Try DAG combinations for an ADD with 9846 /// operands N0 and N1. This is a helper for PerformADDCombine that is 9847 /// called with the default operands, and if that fails, with commuted 9848 /// operands. 9849 static SDValue PerformADDCombineWithOperands(SDNode *N, SDValue N0, SDValue N1, 9850 TargetLowering::DAGCombinerInfo &DCI, 9851 const ARMSubtarget *Subtarget){ 9852 // Attempt to create vpadd for this add. 9853 if (SDValue Result = AddCombineToVPADD(N, N0, N1, DCI, Subtarget)) 9854 return Result; 9855 9856 // Attempt to create vpaddl for this add. 9857 if (SDValue Result = AddCombineVUZPToVPADDL(N, N0, N1, DCI, Subtarget)) 9858 return Result; 9859 if (SDValue Result = AddCombineBUILD_VECTORToVPADDL(N, N0, N1, DCI, 9860 Subtarget)) 9861 return Result; 9862 9863 // fold (add (select cc, 0, c), x) -> (select cc, x, (add, x, c)) 9864 if (N0.getNode()->hasOneUse()) 9865 if (SDValue Result = combineSelectAndUse(N, N0, N1, DCI)) 9866 return Result; 9867 return SDValue(); 9868 } 9869 9870 /// PerformADDCombine - Target-specific dag combine xforms for ISD::ADD. 9871 /// 9872 static SDValue PerformADDCombine(SDNode *N, 9873 TargetLowering::DAGCombinerInfo &DCI, 9874 const ARMSubtarget *Subtarget) { 9875 SDValue N0 = N->getOperand(0); 9876 SDValue N1 = N->getOperand(1); 9877 9878 // First try with the default operand order. 9879 if (SDValue Result = PerformADDCombineWithOperands(N, N0, N1, DCI, Subtarget)) 9880 return Result; 9881 9882 // If that didn't work, try again with the operands commuted. 9883 return PerformADDCombineWithOperands(N, N1, N0, DCI, Subtarget); 9884 } 9885 9886 /// PerformSUBCombine - Target-specific dag combine xforms for ISD::SUB. 9887 /// 9888 static SDValue PerformSUBCombine(SDNode *N, 9889 TargetLowering::DAGCombinerInfo &DCI) { 9890 SDValue N0 = N->getOperand(0); 9891 SDValue N1 = N->getOperand(1); 9892 9893 // fold (sub x, (select cc, 0, c)) -> (select cc, x, (sub, x, c)) 9894 if (N1.getNode()->hasOneUse()) 9895 if (SDValue Result = combineSelectAndUse(N, N1, N0, DCI)) 9896 return Result; 9897 9898 return SDValue(); 9899 } 9900 9901 /// PerformVMULCombine 9902 /// Distribute (A + B) * C to (A * C) + (B * C) to take advantage of the 9903 /// special multiplier accumulator forwarding. 9904 /// vmul d3, d0, d2 9905 /// vmla d3, d1, d2 9906 /// is faster than 9907 /// vadd d3, d0, d1 9908 /// vmul d3, d3, d2 9909 // However, for (A + B) * (A + B), 9910 // vadd d2, d0, d1 9911 // vmul d3, d0, d2 9912 // vmla d3, d1, d2 9913 // is slower than 9914 // vadd d2, d0, d1 9915 // vmul d3, d2, d2 9916 static SDValue PerformVMULCombine(SDNode *N, 9917 TargetLowering::DAGCombinerInfo &DCI, 9918 const ARMSubtarget *Subtarget) { 9919 if (!Subtarget->hasVMLxForwarding()) 9920 return SDValue(); 9921 9922 SelectionDAG &DAG = DCI.DAG; 9923 SDValue N0 = N->getOperand(0); 9924 SDValue N1 = N->getOperand(1); 9925 unsigned Opcode = N0.getOpcode(); 9926 if (Opcode != ISD::ADD && Opcode != ISD::SUB && 9927 Opcode != ISD::FADD && Opcode != ISD::FSUB) { 9928 Opcode = N1.getOpcode(); 9929 if (Opcode != ISD::ADD && Opcode != ISD::SUB && 9930 Opcode != ISD::FADD && Opcode != ISD::FSUB) 9931 return SDValue(); 9932 std::swap(N0, N1); 9933 } 9934 9935 if (N0 == N1) 9936 return SDValue(); 9937 9938 EVT VT = N->getValueType(0); 9939 SDLoc DL(N); 9940 SDValue N00 = N0->getOperand(0); 9941 SDValue N01 = N0->getOperand(1); 9942 return DAG.getNode(Opcode, DL, VT, 9943 DAG.getNode(ISD::MUL, DL, VT, N00, N1), 9944 DAG.getNode(ISD::MUL, DL, VT, N01, N1)); 9945 } 9946 9947 static SDValue PerformMULCombine(SDNode *N, 9948 TargetLowering::DAGCombinerInfo &DCI, 9949 const ARMSubtarget *Subtarget) { 9950 SelectionDAG &DAG = DCI.DAG; 9951 9952 if (Subtarget->isThumb1Only()) 9953 return SDValue(); 9954 9955 if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer()) 9956 return SDValue(); 9957 9958 EVT VT = N->getValueType(0); 9959 if (VT.is64BitVector() || VT.is128BitVector()) 9960 return PerformVMULCombine(N, DCI, Subtarget); 9961 if (VT != MVT::i32) 9962 return SDValue(); 9963 9964 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(1)); 9965 if (!C) 9966 return SDValue(); 9967 9968 int64_t MulAmt = C->getSExtValue(); 9969 unsigned ShiftAmt = countTrailingZeros<uint64_t>(MulAmt); 9970 9971 ShiftAmt = ShiftAmt & (32 - 1); 9972 SDValue V = N->getOperand(0); 9973 SDLoc DL(N); 9974 9975 SDValue Res; 9976 MulAmt >>= ShiftAmt; 9977 9978 if (MulAmt >= 0) { 9979 if (isPowerOf2_32(MulAmt - 1)) { 9980 // (mul x, 2^N + 1) => (add (shl x, N), x) 9981 Res = DAG.getNode(ISD::ADD, DL, VT, 9982 V, 9983 DAG.getNode(ISD::SHL, DL, VT, 9984 V, 9985 DAG.getConstant(Log2_32(MulAmt - 1), DL, 9986 MVT::i32))); 9987 } else if (isPowerOf2_32(MulAmt + 1)) { 9988 // (mul x, 2^N - 1) => (sub (shl x, N), x) 9989 Res = DAG.getNode(ISD::SUB, DL, VT, 9990 DAG.getNode(ISD::SHL, DL, VT, 9991 V, 9992 DAG.getConstant(Log2_32(MulAmt + 1), DL, 9993 MVT::i32)), 9994 V); 9995 } else 9996 return SDValue(); 9997 } else { 9998 uint64_t MulAmtAbs = -MulAmt; 9999 if (isPowerOf2_32(MulAmtAbs + 1)) { 10000 // (mul x, -(2^N - 1)) => (sub x, (shl x, N)) 10001 Res = DAG.getNode(ISD::SUB, DL, VT, 10002 V, 10003 DAG.getNode(ISD::SHL, DL, VT, 10004 V, 10005 DAG.getConstant(Log2_32(MulAmtAbs + 1), DL, 10006 MVT::i32))); 10007 } else if (isPowerOf2_32(MulAmtAbs - 1)) { 10008 // (mul x, -(2^N + 1)) => - (add (shl x, N), x) 10009 Res = DAG.getNode(ISD::ADD, DL, VT, 10010 V, 10011 DAG.getNode(ISD::SHL, DL, VT, 10012 V, 10013 DAG.getConstant(Log2_32(MulAmtAbs - 1), DL, 10014 MVT::i32))); 10015 Res = DAG.getNode(ISD::SUB, DL, VT, 10016 DAG.getConstant(0, DL, MVT::i32), Res); 10017 10018 } else 10019 return SDValue(); 10020 } 10021 10022 if (ShiftAmt != 0) 10023 Res = DAG.getNode(ISD::SHL, DL, VT, 10024 Res, DAG.getConstant(ShiftAmt, DL, MVT::i32)); 10025 10026 // Do not add new nodes to DAG combiner worklist. 10027 DCI.CombineTo(N, Res, false); 10028 return SDValue(); 10029 } 10030 10031 static SDValue PerformANDCombine(SDNode *N, 10032 TargetLowering::DAGCombinerInfo &DCI, 10033 const ARMSubtarget *Subtarget) { 10034 // Attempt to use immediate-form VBIC 10035 BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(N->getOperand(1)); 10036 SDLoc dl(N); 10037 EVT VT = N->getValueType(0); 10038 SelectionDAG &DAG = DCI.DAG; 10039 10040 if(!DAG.getTargetLoweringInfo().isTypeLegal(VT)) 10041 return SDValue(); 10042 10043 APInt SplatBits, SplatUndef; 10044 unsigned SplatBitSize; 10045 bool HasAnyUndefs; 10046 if (BVN && 10047 BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs)) { 10048 if (SplatBitSize <= 64) { 10049 EVT VbicVT; 10050 SDValue Val = isNEONModifiedImm((~SplatBits).getZExtValue(), 10051 SplatUndef.getZExtValue(), SplatBitSize, 10052 DAG, dl, VbicVT, VT.is128BitVector(), 10053 OtherModImm); 10054 if (Val.getNode()) { 10055 SDValue Input = 10056 DAG.getNode(ISD::BITCAST, dl, VbicVT, N->getOperand(0)); 10057 SDValue Vbic = DAG.getNode(ARMISD::VBICIMM, dl, VbicVT, Input, Val); 10058 return DAG.getNode(ISD::BITCAST, dl, VT, Vbic); 10059 } 10060 } 10061 } 10062 10063 if (!Subtarget->isThumb1Only()) { 10064 // fold (and (select cc, -1, c), x) -> (select cc, x, (and, x, c)) 10065 if (SDValue Result = combineSelectAndUseCommutative(N, true, DCI)) 10066 return Result; 10067 } 10068 10069 return SDValue(); 10070 } 10071 10072 // Try combining OR nodes to SMULWB, SMULWT. 10073 static SDValue PerformORCombineToSMULWBT(SDNode *OR, 10074 TargetLowering::DAGCombinerInfo &DCI, 10075 const ARMSubtarget *Subtarget) { 10076 if (!Subtarget->hasV6Ops() || 10077 (Subtarget->isThumb() && 10078 (!Subtarget->hasThumb2() || !Subtarget->hasDSP()))) 10079 return SDValue(); 10080 10081 SDValue SRL = OR->getOperand(0); 10082 SDValue SHL = OR->getOperand(1); 10083 10084 if (SRL.getOpcode() != ISD::SRL || SHL.getOpcode() != ISD::SHL) { 10085 SRL = OR->getOperand(1); 10086 SHL = OR->getOperand(0); 10087 } 10088 if (!isSRL16(SRL) || !isSHL16(SHL)) 10089 return SDValue(); 10090 10091 // The first operands to the shifts need to be the two results from the 10092 // same smul_lohi node. 10093 if ((SRL.getOperand(0).getNode() != SHL.getOperand(0).getNode()) || 10094 SRL.getOperand(0).getOpcode() != ISD::SMUL_LOHI) 10095 return SDValue(); 10096 10097 SDNode *SMULLOHI = SRL.getOperand(0).getNode(); 10098 if (SRL.getOperand(0) != SDValue(SMULLOHI, 0) || 10099 SHL.getOperand(0) != SDValue(SMULLOHI, 1)) 10100 return SDValue(); 10101 10102 // Now we have: 10103 // (or (srl (smul_lohi ?, ?), 16), (shl (smul_lohi ?, ?), 16))) 10104 // For SMUL[B|T] smul_lohi will take a 32-bit and a 16-bit arguments. 10105 // For SMUWB the 16-bit value will signed extended somehow. 10106 // For SMULWT only the SRA is required. 10107 // Check both sides of SMUL_LOHI 10108 SDValue OpS16 = SMULLOHI->getOperand(0); 10109 SDValue OpS32 = SMULLOHI->getOperand(1); 10110 10111 SelectionDAG &DAG = DCI.DAG; 10112 if (!isS16(OpS16, DAG) && !isSRA16(OpS16)) { 10113 OpS16 = OpS32; 10114 OpS32 = SMULLOHI->getOperand(0); 10115 } 10116 10117 SDLoc dl(OR); 10118 unsigned Opcode = 0; 10119 if (isS16(OpS16, DAG)) 10120 Opcode = ARMISD::SMULWB; 10121 else if (isSRA16(OpS16)) { 10122 Opcode = ARMISD::SMULWT; 10123 OpS16 = OpS16->getOperand(0); 10124 } 10125 else 10126 return SDValue(); 10127 10128 SDValue Res = DAG.getNode(Opcode, dl, MVT::i32, OpS32, OpS16); 10129 DAG.ReplaceAllUsesOfValueWith(SDValue(OR, 0), Res); 10130 return SDValue(OR, 0); 10131 } 10132 10133 /// PerformORCombine - Target-specific dag combine xforms for ISD::OR 10134 static SDValue PerformORCombine(SDNode *N, 10135 TargetLowering::DAGCombinerInfo &DCI, 10136 const ARMSubtarget *Subtarget) { 10137 // Attempt to use immediate-form VORR 10138 BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(N->getOperand(1)); 10139 SDLoc dl(N); 10140 EVT VT = N->getValueType(0); 10141 SelectionDAG &DAG = DCI.DAG; 10142 10143 if(!DAG.getTargetLoweringInfo().isTypeLegal(VT)) 10144 return SDValue(); 10145 10146 APInt SplatBits, SplatUndef; 10147 unsigned SplatBitSize; 10148 bool HasAnyUndefs; 10149 if (BVN && Subtarget->hasNEON() && 10150 BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs)) { 10151 if (SplatBitSize <= 64) { 10152 EVT VorrVT; 10153 SDValue Val = isNEONModifiedImm(SplatBits.getZExtValue(), 10154 SplatUndef.getZExtValue(), SplatBitSize, 10155 DAG, dl, VorrVT, VT.is128BitVector(), 10156 OtherModImm); 10157 if (Val.getNode()) { 10158 SDValue Input = 10159 DAG.getNode(ISD::BITCAST, dl, VorrVT, N->getOperand(0)); 10160 SDValue Vorr = DAG.getNode(ARMISD::VORRIMM, dl, VorrVT, Input, Val); 10161 return DAG.getNode(ISD::BITCAST, dl, VT, Vorr); 10162 } 10163 } 10164 } 10165 10166 if (!Subtarget->isThumb1Only()) { 10167 // fold (or (select cc, 0, c), x) -> (select cc, x, (or, x, c)) 10168 if (SDValue Result = combineSelectAndUseCommutative(N, false, DCI)) 10169 return Result; 10170 if (SDValue Result = PerformORCombineToSMULWBT(N, DCI, Subtarget)) 10171 return Result; 10172 } 10173 10174 // The code below optimizes (or (and X, Y), Z). 10175 // The AND operand needs to have a single user to make these optimizations 10176 // profitable. 10177 SDValue N0 = N->getOperand(0); 10178 if (N0.getOpcode() != ISD::AND || !N0.hasOneUse()) 10179 return SDValue(); 10180 SDValue N1 = N->getOperand(1); 10181 10182 // (or (and B, A), (and C, ~A)) => (VBSL A, B, C) when A is a constant. 10183 if (Subtarget->hasNEON() && N1.getOpcode() == ISD::AND && VT.isVector() && 10184 DAG.getTargetLoweringInfo().isTypeLegal(VT)) { 10185 APInt SplatUndef; 10186 unsigned SplatBitSize; 10187 bool HasAnyUndefs; 10188 10189 APInt SplatBits0, SplatBits1; 10190 BuildVectorSDNode *BVN0 = dyn_cast<BuildVectorSDNode>(N0->getOperand(1)); 10191 BuildVectorSDNode *BVN1 = dyn_cast<BuildVectorSDNode>(N1->getOperand(1)); 10192 // Ensure that the second operand of both ands are constants 10193 if (BVN0 && BVN0->isConstantSplat(SplatBits0, SplatUndef, SplatBitSize, 10194 HasAnyUndefs) && !HasAnyUndefs) { 10195 if (BVN1 && BVN1->isConstantSplat(SplatBits1, SplatUndef, SplatBitSize, 10196 HasAnyUndefs) && !HasAnyUndefs) { 10197 // Ensure that the bit width of the constants are the same and that 10198 // the splat arguments are logical inverses as per the pattern we 10199 // are trying to simplify. 10200 if (SplatBits0.getBitWidth() == SplatBits1.getBitWidth() && 10201 SplatBits0 == ~SplatBits1) { 10202 // Canonicalize the vector type to make instruction selection 10203 // simpler. 10204 EVT CanonicalVT = VT.is128BitVector() ? MVT::v4i32 : MVT::v2i32; 10205 SDValue Result = DAG.getNode(ARMISD::VBSL, dl, CanonicalVT, 10206 N0->getOperand(1), 10207 N0->getOperand(0), 10208 N1->getOperand(0)); 10209 return DAG.getNode(ISD::BITCAST, dl, VT, Result); 10210 } 10211 } 10212 } 10213 } 10214 10215 // Try to use the ARM/Thumb2 BFI (bitfield insert) instruction when 10216 // reasonable. 10217 10218 // BFI is only available on V6T2+ 10219 if (Subtarget->isThumb1Only() || !Subtarget->hasV6T2Ops()) 10220 return SDValue(); 10221 10222 SDLoc DL(N); 10223 // 1) or (and A, mask), val => ARMbfi A, val, mask 10224 // iff (val & mask) == val 10225 // 10226 // 2) or (and A, mask), (and B, mask2) => ARMbfi A, (lsr B, amt), mask 10227 // 2a) iff isBitFieldInvertedMask(mask) && isBitFieldInvertedMask(~mask2) 10228 // && mask == ~mask2 10229 // 2b) iff isBitFieldInvertedMask(~mask) && isBitFieldInvertedMask(mask2) 10230 // && ~mask == mask2 10231 // (i.e., copy a bitfield value into another bitfield of the same width) 10232 10233 if (VT != MVT::i32) 10234 return SDValue(); 10235 10236 SDValue N00 = N0.getOperand(0); 10237 10238 // The value and the mask need to be constants so we can verify this is 10239 // actually a bitfield set. If the mask is 0xffff, we can do better 10240 // via a movt instruction, so don't use BFI in that case. 10241 SDValue MaskOp = N0.getOperand(1); 10242 ConstantSDNode *MaskC = dyn_cast<ConstantSDNode>(MaskOp); 10243 if (!MaskC) 10244 return SDValue(); 10245 unsigned Mask = MaskC->getZExtValue(); 10246 if (Mask == 0xffff) 10247 return SDValue(); 10248 SDValue Res; 10249 // Case (1): or (and A, mask), val => ARMbfi A, val, mask 10250 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1); 10251 if (N1C) { 10252 unsigned Val = N1C->getZExtValue(); 10253 if ((Val & ~Mask) != Val) 10254 return SDValue(); 10255 10256 if (ARM::isBitFieldInvertedMask(Mask)) { 10257 Val >>= countTrailingZeros(~Mask); 10258 10259 Res = DAG.getNode(ARMISD::BFI, DL, VT, N00, 10260 DAG.getConstant(Val, DL, MVT::i32), 10261 DAG.getConstant(Mask, DL, MVT::i32)); 10262 10263 // Do not add new nodes to DAG combiner worklist. 10264 DCI.CombineTo(N, Res, false); 10265 return SDValue(); 10266 } 10267 } else if (N1.getOpcode() == ISD::AND) { 10268 // case (2) or (and A, mask), (and B, mask2) => ARMbfi A, (lsr B, amt), mask 10269 ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1)); 10270 if (!N11C) 10271 return SDValue(); 10272 unsigned Mask2 = N11C->getZExtValue(); 10273 10274 // Mask and ~Mask2 (or reverse) must be equivalent for the BFI pattern 10275 // as is to match. 10276 if (ARM::isBitFieldInvertedMask(Mask) && 10277 (Mask == ~Mask2)) { 10278 // The pack halfword instruction works better for masks that fit it, 10279 // so use that when it's available. 10280 if (Subtarget->hasDSP() && 10281 (Mask == 0xffff || Mask == 0xffff0000)) 10282 return SDValue(); 10283 // 2a 10284 unsigned amt = countTrailingZeros(Mask2); 10285 Res = DAG.getNode(ISD::SRL, DL, VT, N1.getOperand(0), 10286 DAG.getConstant(amt, DL, MVT::i32)); 10287 Res = DAG.getNode(ARMISD::BFI, DL, VT, N00, Res, 10288 DAG.getConstant(Mask, DL, MVT::i32)); 10289 // Do not add new nodes to DAG combiner worklist. 10290 DCI.CombineTo(N, Res, false); 10291 return SDValue(); 10292 } else if (ARM::isBitFieldInvertedMask(~Mask) && 10293 (~Mask == Mask2)) { 10294 // The pack halfword instruction works better for masks that fit it, 10295 // so use that when it's available. 10296 if (Subtarget->hasDSP() && 10297 (Mask2 == 0xffff || Mask2 == 0xffff0000)) 10298 return SDValue(); 10299 // 2b 10300 unsigned lsb = countTrailingZeros(Mask); 10301 Res = DAG.getNode(ISD::SRL, DL, VT, N00, 10302 DAG.getConstant(lsb, DL, MVT::i32)); 10303 Res = DAG.getNode(ARMISD::BFI, DL, VT, N1.getOperand(0), Res, 10304 DAG.getConstant(Mask2, DL, MVT::i32)); 10305 // Do not add new nodes to DAG combiner worklist. 10306 DCI.CombineTo(N, Res, false); 10307 return SDValue(); 10308 } 10309 } 10310 10311 if (DAG.MaskedValueIsZero(N1, MaskC->getAPIntValue()) && 10312 N00.getOpcode() == ISD::SHL && isa<ConstantSDNode>(N00.getOperand(1)) && 10313 ARM::isBitFieldInvertedMask(~Mask)) { 10314 // Case (3): or (and (shl A, #shamt), mask), B => ARMbfi B, A, ~mask 10315 // where lsb(mask) == #shamt and masked bits of B are known zero. 10316 SDValue ShAmt = N00.getOperand(1); 10317 unsigned ShAmtC = cast<ConstantSDNode>(ShAmt)->getZExtValue(); 10318 unsigned LSB = countTrailingZeros(Mask); 10319 if (ShAmtC != LSB) 10320 return SDValue(); 10321 10322 Res = DAG.getNode(ARMISD::BFI, DL, VT, N1, N00.getOperand(0), 10323 DAG.getConstant(~Mask, DL, MVT::i32)); 10324 10325 // Do not add new nodes to DAG combiner worklist. 10326 DCI.CombineTo(N, Res, false); 10327 } 10328 10329 return SDValue(); 10330 } 10331 10332 static SDValue PerformXORCombine(SDNode *N, 10333 TargetLowering::DAGCombinerInfo &DCI, 10334 const ARMSubtarget *Subtarget) { 10335 EVT VT = N->getValueType(0); 10336 SelectionDAG &DAG = DCI.DAG; 10337 10338 if(!DAG.getTargetLoweringInfo().isTypeLegal(VT)) 10339 return SDValue(); 10340 10341 if (!Subtarget->isThumb1Only()) { 10342 // fold (xor (select cc, 0, c), x) -> (select cc, x, (xor, x, c)) 10343 if (SDValue Result = combineSelectAndUseCommutative(N, false, DCI)) 10344 return Result; 10345 } 10346 10347 return SDValue(); 10348 } 10349 10350 // ParseBFI - given a BFI instruction in N, extract the "from" value (Rn) and return it, 10351 // and fill in FromMask and ToMask with (consecutive) bits in "from" to be extracted and 10352 // their position in "to" (Rd). 10353 static SDValue ParseBFI(SDNode *N, APInt &ToMask, APInt &FromMask) { 10354 assert(N->getOpcode() == ARMISD::BFI); 10355 10356 SDValue From = N->getOperand(1); 10357 ToMask = ~cast<ConstantSDNode>(N->getOperand(2))->getAPIntValue(); 10358 FromMask = APInt::getLowBitsSet(ToMask.getBitWidth(), ToMask.countPopulation()); 10359 10360 // If the Base came from a SHR #C, we can deduce that it is really testing bit 10361 // #C in the base of the SHR. 10362 if (From->getOpcode() == ISD::SRL && 10363 isa<ConstantSDNode>(From->getOperand(1))) { 10364 APInt Shift = cast<ConstantSDNode>(From->getOperand(1))->getAPIntValue(); 10365 assert(Shift.getLimitedValue() < 32 && "Shift too large!"); 10366 FromMask <<= Shift.getLimitedValue(31); 10367 From = From->getOperand(0); 10368 } 10369 10370 return From; 10371 } 10372 10373 // If A and B contain one contiguous set of bits, does A | B == A . B? 10374 // 10375 // Neither A nor B must be zero. 10376 static bool BitsProperlyConcatenate(const APInt &A, const APInt &B) { 10377 unsigned LastActiveBitInA = A.countTrailingZeros(); 10378 unsigned FirstActiveBitInB = B.getBitWidth() - B.countLeadingZeros() - 1; 10379 return LastActiveBitInA - 1 == FirstActiveBitInB; 10380 } 10381 10382 static SDValue FindBFIToCombineWith(SDNode *N) { 10383 // We have a BFI in N. Follow a possible chain of BFIs and find a BFI it can combine with, 10384 // if one exists. 10385 APInt ToMask, FromMask; 10386 SDValue From = ParseBFI(N, ToMask, FromMask); 10387 SDValue To = N->getOperand(0); 10388 10389 // Now check for a compatible BFI to merge with. We can pass through BFIs that 10390 // aren't compatible, but not if they set the same bit in their destination as 10391 // we do (or that of any BFI we're going to combine with). 10392 SDValue V = To; 10393 APInt CombinedToMask = ToMask; 10394 while (V.getOpcode() == ARMISD::BFI) { 10395 APInt NewToMask, NewFromMask; 10396 SDValue NewFrom = ParseBFI(V.getNode(), NewToMask, NewFromMask); 10397 if (NewFrom != From) { 10398 // This BFI has a different base. Keep going. 10399 CombinedToMask |= NewToMask; 10400 V = V.getOperand(0); 10401 continue; 10402 } 10403 10404 // Do the written bits conflict with any we've seen so far? 10405 if ((NewToMask & CombinedToMask).getBoolValue()) 10406 // Conflicting bits - bail out because going further is unsafe. 10407 return SDValue(); 10408 10409 // Are the new bits contiguous when combined with the old bits? 10410 if (BitsProperlyConcatenate(ToMask, NewToMask) && 10411 BitsProperlyConcatenate(FromMask, NewFromMask)) 10412 return V; 10413 if (BitsProperlyConcatenate(NewToMask, ToMask) && 10414 BitsProperlyConcatenate(NewFromMask, FromMask)) 10415 return V; 10416 10417 // We've seen a write to some bits, so track it. 10418 CombinedToMask |= NewToMask; 10419 // Keep going... 10420 V = V.getOperand(0); 10421 } 10422 10423 return SDValue(); 10424 } 10425 10426 static SDValue PerformBFICombine(SDNode *N, 10427 TargetLowering::DAGCombinerInfo &DCI) { 10428 SDValue N1 = N->getOperand(1); 10429 if (N1.getOpcode() == ISD::AND) { 10430 // (bfi A, (and B, Mask1), Mask2) -> (bfi A, B, Mask2) iff 10431 // the bits being cleared by the AND are not demanded by the BFI. 10432 ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1)); 10433 if (!N11C) 10434 return SDValue(); 10435 unsigned InvMask = cast<ConstantSDNode>(N->getOperand(2))->getZExtValue(); 10436 unsigned LSB = countTrailingZeros(~InvMask); 10437 unsigned Width = (32 - countLeadingZeros(~InvMask)) - LSB; 10438 assert(Width < 10439 static_cast<unsigned>(std::numeric_limits<unsigned>::digits) && 10440 "undefined behavior"); 10441 unsigned Mask = (1u << Width) - 1; 10442 unsigned Mask2 = N11C->getZExtValue(); 10443 if ((Mask & (~Mask2)) == 0) 10444 return DCI.DAG.getNode(ARMISD::BFI, SDLoc(N), N->getValueType(0), 10445 N->getOperand(0), N1.getOperand(0), 10446 N->getOperand(2)); 10447 } else if (N->getOperand(0).getOpcode() == ARMISD::BFI) { 10448 // We have a BFI of a BFI. Walk up the BFI chain to see how long it goes. 10449 // Keep track of any consecutive bits set that all come from the same base 10450 // value. We can combine these together into a single BFI. 10451 SDValue CombineBFI = FindBFIToCombineWith(N); 10452 if (CombineBFI == SDValue()) 10453 return SDValue(); 10454 10455 // We've found a BFI. 10456 APInt ToMask1, FromMask1; 10457 SDValue From1 = ParseBFI(N, ToMask1, FromMask1); 10458 10459 APInt ToMask2, FromMask2; 10460 SDValue From2 = ParseBFI(CombineBFI.getNode(), ToMask2, FromMask2); 10461 assert(From1 == From2); 10462 (void)From2; 10463 10464 // First, unlink CombineBFI. 10465 DCI.DAG.ReplaceAllUsesWith(CombineBFI, CombineBFI.getOperand(0)); 10466 // Then create a new BFI, combining the two together. 10467 APInt NewFromMask = FromMask1 | FromMask2; 10468 APInt NewToMask = ToMask1 | ToMask2; 10469 10470 EVT VT = N->getValueType(0); 10471 SDLoc dl(N); 10472 10473 if (NewFromMask[0] == 0) 10474 From1 = DCI.DAG.getNode( 10475 ISD::SRL, dl, VT, From1, 10476 DCI.DAG.getConstant(NewFromMask.countTrailingZeros(), dl, VT)); 10477 return DCI.DAG.getNode(ARMISD::BFI, dl, VT, N->getOperand(0), From1, 10478 DCI.DAG.getConstant(~NewToMask, dl, VT)); 10479 } 10480 return SDValue(); 10481 } 10482 10483 /// PerformVMOVRRDCombine - Target-specific dag combine xforms for 10484 /// ARMISD::VMOVRRD. 10485 static SDValue PerformVMOVRRDCombine(SDNode *N, 10486 TargetLowering::DAGCombinerInfo &DCI, 10487 const ARMSubtarget *Subtarget) { 10488 // vmovrrd(vmovdrr x, y) -> x,y 10489 SDValue InDouble = N->getOperand(0); 10490 if (InDouble.getOpcode() == ARMISD::VMOVDRR && !Subtarget->isFPOnlySP()) 10491 return DCI.CombineTo(N, InDouble.getOperand(0), InDouble.getOperand(1)); 10492 10493 // vmovrrd(load f64) -> (load i32), (load i32) 10494 SDNode *InNode = InDouble.getNode(); 10495 if (ISD::isNormalLoad(InNode) && InNode->hasOneUse() && 10496 InNode->getValueType(0) == MVT::f64 && 10497 InNode->getOperand(1).getOpcode() == ISD::FrameIndex && 10498 !cast<LoadSDNode>(InNode)->isVolatile()) { 10499 // TODO: Should this be done for non-FrameIndex operands? 10500 LoadSDNode *LD = cast<LoadSDNode>(InNode); 10501 10502 SelectionDAG &DAG = DCI.DAG; 10503 SDLoc DL(LD); 10504 SDValue BasePtr = LD->getBasePtr(); 10505 SDValue NewLD1 = 10506 DAG.getLoad(MVT::i32, DL, LD->getChain(), BasePtr, LD->getPointerInfo(), 10507 LD->getAlignment(), LD->getMemOperand()->getFlags()); 10508 10509 SDValue OffsetPtr = DAG.getNode(ISD::ADD, DL, MVT::i32, BasePtr, 10510 DAG.getConstant(4, DL, MVT::i32)); 10511 SDValue NewLD2 = DAG.getLoad( 10512 MVT::i32, DL, NewLD1.getValue(1), OffsetPtr, LD->getPointerInfo(), 10513 std::min(4U, LD->getAlignment() / 2), LD->getMemOperand()->getFlags()); 10514 10515 DAG.ReplaceAllUsesOfValueWith(SDValue(LD, 1), NewLD2.getValue(1)); 10516 if (DCI.DAG.getDataLayout().isBigEndian()) 10517 std::swap (NewLD1, NewLD2); 10518 SDValue Result = DCI.CombineTo(N, NewLD1, NewLD2); 10519 return Result; 10520 } 10521 10522 return SDValue(); 10523 } 10524 10525 /// PerformVMOVDRRCombine - Target-specific dag combine xforms for 10526 /// ARMISD::VMOVDRR. This is also used for BUILD_VECTORs with 2 operands. 10527 static SDValue PerformVMOVDRRCombine(SDNode *N, SelectionDAG &DAG) { 10528 // N=vmovrrd(X); vmovdrr(N:0, N:1) -> bit_convert(X) 10529 SDValue Op0 = N->getOperand(0); 10530 SDValue Op1 = N->getOperand(1); 10531 if (Op0.getOpcode() == ISD::BITCAST) 10532 Op0 = Op0.getOperand(0); 10533 if (Op1.getOpcode() == ISD::BITCAST) 10534 Op1 = Op1.getOperand(0); 10535 if (Op0.getOpcode() == ARMISD::VMOVRRD && 10536 Op0.getNode() == Op1.getNode() && 10537 Op0.getResNo() == 0 && Op1.getResNo() == 1) 10538 return DAG.getNode(ISD::BITCAST, SDLoc(N), 10539 N->getValueType(0), Op0.getOperand(0)); 10540 return SDValue(); 10541 } 10542 10543 /// hasNormalLoadOperand - Check if any of the operands of a BUILD_VECTOR node 10544 /// are normal, non-volatile loads. If so, it is profitable to bitcast an 10545 /// i64 vector to have f64 elements, since the value can then be loaded 10546 /// directly into a VFP register. 10547 static bool hasNormalLoadOperand(SDNode *N) { 10548 unsigned NumElts = N->getValueType(0).getVectorNumElements(); 10549 for (unsigned i = 0; i < NumElts; ++i) { 10550 SDNode *Elt = N->getOperand(i).getNode(); 10551 if (ISD::isNormalLoad(Elt) && !cast<LoadSDNode>(Elt)->isVolatile()) 10552 return true; 10553 } 10554 return false; 10555 } 10556 10557 /// PerformBUILD_VECTORCombine - Target-specific dag combine xforms for 10558 /// ISD::BUILD_VECTOR. 10559 static SDValue PerformBUILD_VECTORCombine(SDNode *N, 10560 TargetLowering::DAGCombinerInfo &DCI, 10561 const ARMSubtarget *Subtarget) { 10562 // build_vector(N=ARMISD::VMOVRRD(X), N:1) -> bit_convert(X): 10563 // VMOVRRD is introduced when legalizing i64 types. It forces the i64 value 10564 // into a pair of GPRs, which is fine when the value is used as a scalar, 10565 // but if the i64 value is converted to a vector, we need to undo the VMOVRRD. 10566 SelectionDAG &DAG = DCI.DAG; 10567 if (N->getNumOperands() == 2) 10568 if (SDValue RV = PerformVMOVDRRCombine(N, DAG)) 10569 return RV; 10570 10571 // Load i64 elements as f64 values so that type legalization does not split 10572 // them up into i32 values. 10573 EVT VT = N->getValueType(0); 10574 if (VT.getVectorElementType() != MVT::i64 || !hasNormalLoadOperand(N)) 10575 return SDValue(); 10576 SDLoc dl(N); 10577 SmallVector<SDValue, 8> Ops; 10578 unsigned NumElts = VT.getVectorNumElements(); 10579 for (unsigned i = 0; i < NumElts; ++i) { 10580 SDValue V = DAG.getNode(ISD::BITCAST, dl, MVT::f64, N->getOperand(i)); 10581 Ops.push_back(V); 10582 // Make the DAGCombiner fold the bitcast. 10583 DCI.AddToWorklist(V.getNode()); 10584 } 10585 EVT FloatVT = EVT::getVectorVT(*DAG.getContext(), MVT::f64, NumElts); 10586 SDValue BV = DAG.getBuildVector(FloatVT, dl, Ops); 10587 return DAG.getNode(ISD::BITCAST, dl, VT, BV); 10588 } 10589 10590 /// \brief Target-specific dag combine xforms for ARMISD::BUILD_VECTOR. 10591 static SDValue 10592 PerformARMBUILD_VECTORCombine(SDNode *N, TargetLowering::DAGCombinerInfo &DCI) { 10593 // ARMISD::BUILD_VECTOR is introduced when legalizing ISD::BUILD_VECTOR. 10594 // At that time, we may have inserted bitcasts from integer to float. 10595 // If these bitcasts have survived DAGCombine, change the lowering of this 10596 // BUILD_VECTOR in something more vector friendly, i.e., that does not 10597 // force to use floating point types. 10598 10599 // Make sure we can change the type of the vector. 10600 // This is possible iff: 10601 // 1. The vector is only used in a bitcast to a integer type. I.e., 10602 // 1.1. Vector is used only once. 10603 // 1.2. Use is a bit convert to an integer type. 10604 // 2. The size of its operands are 32-bits (64-bits are not legal). 10605 EVT VT = N->getValueType(0); 10606 EVT EltVT = VT.getVectorElementType(); 10607 10608 // Check 1.1. and 2. 10609 if (EltVT.getSizeInBits() != 32 || !N->hasOneUse()) 10610 return SDValue(); 10611 10612 // By construction, the input type must be float. 10613 assert(EltVT == MVT::f32 && "Unexpected type!"); 10614 10615 // Check 1.2. 10616 SDNode *Use = *N->use_begin(); 10617 if (Use->getOpcode() != ISD::BITCAST || 10618 Use->getValueType(0).isFloatingPoint()) 10619 return SDValue(); 10620 10621 // Check profitability. 10622 // Model is, if more than half of the relevant operands are bitcast from 10623 // i32, turn the build_vector into a sequence of insert_vector_elt. 10624 // Relevant operands are everything that is not statically 10625 // (i.e., at compile time) bitcasted. 10626 unsigned NumOfBitCastedElts = 0; 10627 unsigned NumElts = VT.getVectorNumElements(); 10628 unsigned NumOfRelevantElts = NumElts; 10629 for (unsigned Idx = 0; Idx < NumElts; ++Idx) { 10630 SDValue Elt = N->getOperand(Idx); 10631 if (Elt->getOpcode() == ISD::BITCAST) { 10632 // Assume only bit cast to i32 will go away. 10633 if (Elt->getOperand(0).getValueType() == MVT::i32) 10634 ++NumOfBitCastedElts; 10635 } else if (Elt.isUndef() || isa<ConstantSDNode>(Elt)) 10636 // Constants are statically casted, thus do not count them as 10637 // relevant operands. 10638 --NumOfRelevantElts; 10639 } 10640 10641 // Check if more than half of the elements require a non-free bitcast. 10642 if (NumOfBitCastedElts <= NumOfRelevantElts / 2) 10643 return SDValue(); 10644 10645 SelectionDAG &DAG = DCI.DAG; 10646 // Create the new vector type. 10647 EVT VecVT = EVT::getVectorVT(*DAG.getContext(), MVT::i32, NumElts); 10648 // Check if the type is legal. 10649 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 10650 if (!TLI.isTypeLegal(VecVT)) 10651 return SDValue(); 10652 10653 // Combine: 10654 // ARMISD::BUILD_VECTOR E1, E2, ..., EN. 10655 // => BITCAST INSERT_VECTOR_ELT 10656 // (INSERT_VECTOR_ELT (...), (BITCAST EN-1), N-1), 10657 // (BITCAST EN), N. 10658 SDValue Vec = DAG.getUNDEF(VecVT); 10659 SDLoc dl(N); 10660 for (unsigned Idx = 0 ; Idx < NumElts; ++Idx) { 10661 SDValue V = N->getOperand(Idx); 10662 if (V.isUndef()) 10663 continue; 10664 if (V.getOpcode() == ISD::BITCAST && 10665 V->getOperand(0).getValueType() == MVT::i32) 10666 // Fold obvious case. 10667 V = V.getOperand(0); 10668 else { 10669 V = DAG.getNode(ISD::BITCAST, SDLoc(V), MVT::i32, V); 10670 // Make the DAGCombiner fold the bitcasts. 10671 DCI.AddToWorklist(V.getNode()); 10672 } 10673 SDValue LaneIdx = DAG.getConstant(Idx, dl, MVT::i32); 10674 Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VecVT, Vec, V, LaneIdx); 10675 } 10676 Vec = DAG.getNode(ISD::BITCAST, dl, VT, Vec); 10677 // Make the DAGCombiner fold the bitcasts. 10678 DCI.AddToWorklist(Vec.getNode()); 10679 return Vec; 10680 } 10681 10682 /// PerformInsertEltCombine - Target-specific dag combine xforms for 10683 /// ISD::INSERT_VECTOR_ELT. 10684 static SDValue PerformInsertEltCombine(SDNode *N, 10685 TargetLowering::DAGCombinerInfo &DCI) { 10686 // Bitcast an i64 load inserted into a vector to f64. 10687 // Otherwise, the i64 value will be legalized to a pair of i32 values. 10688 EVT VT = N->getValueType(0); 10689 SDNode *Elt = N->getOperand(1).getNode(); 10690 if (VT.getVectorElementType() != MVT::i64 || 10691 !ISD::isNormalLoad(Elt) || cast<LoadSDNode>(Elt)->isVolatile()) 10692 return SDValue(); 10693 10694 SelectionDAG &DAG = DCI.DAG; 10695 SDLoc dl(N); 10696 EVT FloatVT = EVT::getVectorVT(*DAG.getContext(), MVT::f64, 10697 VT.getVectorNumElements()); 10698 SDValue Vec = DAG.getNode(ISD::BITCAST, dl, FloatVT, N->getOperand(0)); 10699 SDValue V = DAG.getNode(ISD::BITCAST, dl, MVT::f64, N->getOperand(1)); 10700 // Make the DAGCombiner fold the bitcasts. 10701 DCI.AddToWorklist(Vec.getNode()); 10702 DCI.AddToWorklist(V.getNode()); 10703 SDValue InsElt = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, FloatVT, 10704 Vec, V, N->getOperand(2)); 10705 return DAG.getNode(ISD::BITCAST, dl, VT, InsElt); 10706 } 10707 10708 /// PerformVECTOR_SHUFFLECombine - Target-specific dag combine xforms for 10709 /// ISD::VECTOR_SHUFFLE. 10710 static SDValue PerformVECTOR_SHUFFLECombine(SDNode *N, SelectionDAG &DAG) { 10711 // The LLVM shufflevector instruction does not require the shuffle mask 10712 // length to match the operand vector length, but ISD::VECTOR_SHUFFLE does 10713 // have that requirement. When translating to ISD::VECTOR_SHUFFLE, if the 10714 // operands do not match the mask length, they are extended by concatenating 10715 // them with undef vectors. That is probably the right thing for other 10716 // targets, but for NEON it is better to concatenate two double-register 10717 // size vector operands into a single quad-register size vector. Do that 10718 // transformation here: 10719 // shuffle(concat(v1, undef), concat(v2, undef)) -> 10720 // shuffle(concat(v1, v2), undef) 10721 SDValue Op0 = N->getOperand(0); 10722 SDValue Op1 = N->getOperand(1); 10723 if (Op0.getOpcode() != ISD::CONCAT_VECTORS || 10724 Op1.getOpcode() != ISD::CONCAT_VECTORS || 10725 Op0.getNumOperands() != 2 || 10726 Op1.getNumOperands() != 2) 10727 return SDValue(); 10728 SDValue Concat0Op1 = Op0.getOperand(1); 10729 SDValue Concat1Op1 = Op1.getOperand(1); 10730 if (!Concat0Op1.isUndef() || !Concat1Op1.isUndef()) 10731 return SDValue(); 10732 // Skip the transformation if any of the types are illegal. 10733 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 10734 EVT VT = N->getValueType(0); 10735 if (!TLI.isTypeLegal(VT) || 10736 !TLI.isTypeLegal(Concat0Op1.getValueType()) || 10737 !TLI.isTypeLegal(Concat1Op1.getValueType())) 10738 return SDValue(); 10739 10740 SDValue NewConcat = DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT, 10741 Op0.getOperand(0), Op1.getOperand(0)); 10742 // Translate the shuffle mask. 10743 SmallVector<int, 16> NewMask; 10744 unsigned NumElts = VT.getVectorNumElements(); 10745 unsigned HalfElts = NumElts/2; 10746 ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N); 10747 for (unsigned n = 0; n < NumElts; ++n) { 10748 int MaskElt = SVN->getMaskElt(n); 10749 int NewElt = -1; 10750 if (MaskElt < (int)HalfElts) 10751 NewElt = MaskElt; 10752 else if (MaskElt >= (int)NumElts && MaskElt < (int)(NumElts + HalfElts)) 10753 NewElt = HalfElts + MaskElt - NumElts; 10754 NewMask.push_back(NewElt); 10755 } 10756 return DAG.getVectorShuffle(VT, SDLoc(N), NewConcat, 10757 DAG.getUNDEF(VT), NewMask); 10758 } 10759 10760 /// CombineBaseUpdate - Target-specific DAG combine function for VLDDUP, 10761 /// NEON load/store intrinsics, and generic vector load/stores, to merge 10762 /// base address updates. 10763 /// For generic load/stores, the memory type is assumed to be a vector. 10764 /// The caller is assumed to have checked legality. 10765 static SDValue CombineBaseUpdate(SDNode *N, 10766 TargetLowering::DAGCombinerInfo &DCI) { 10767 SelectionDAG &DAG = DCI.DAG; 10768 const bool isIntrinsic = (N->getOpcode() == ISD::INTRINSIC_VOID || 10769 N->getOpcode() == ISD::INTRINSIC_W_CHAIN); 10770 const bool isStore = N->getOpcode() == ISD::STORE; 10771 const unsigned AddrOpIdx = ((isIntrinsic || isStore) ? 2 : 1); 10772 SDValue Addr = N->getOperand(AddrOpIdx); 10773 MemSDNode *MemN = cast<MemSDNode>(N); 10774 SDLoc dl(N); 10775 10776 // Search for a use of the address operand that is an increment. 10777 for (SDNode::use_iterator UI = Addr.getNode()->use_begin(), 10778 UE = Addr.getNode()->use_end(); UI != UE; ++UI) { 10779 SDNode *User = *UI; 10780 if (User->getOpcode() != ISD::ADD || 10781 UI.getUse().getResNo() != Addr.getResNo()) 10782 continue; 10783 10784 // Check that the add is independent of the load/store. Otherwise, folding 10785 // it would create a cycle. 10786 if (User->isPredecessorOf(N) || N->isPredecessorOf(User)) 10787 continue; 10788 10789 // Find the new opcode for the updating load/store. 10790 bool isLoadOp = true; 10791 bool isLaneOp = false; 10792 unsigned NewOpc = 0; 10793 unsigned NumVecs = 0; 10794 if (isIntrinsic) { 10795 unsigned IntNo = cast<ConstantSDNode>(N->getOperand(1))->getZExtValue(); 10796 switch (IntNo) { 10797 default: llvm_unreachable("unexpected intrinsic for Neon base update"); 10798 case Intrinsic::arm_neon_vld1: NewOpc = ARMISD::VLD1_UPD; 10799 NumVecs = 1; break; 10800 case Intrinsic::arm_neon_vld2: NewOpc = ARMISD::VLD2_UPD; 10801 NumVecs = 2; break; 10802 case Intrinsic::arm_neon_vld3: NewOpc = ARMISD::VLD3_UPD; 10803 NumVecs = 3; break; 10804 case Intrinsic::arm_neon_vld4: NewOpc = ARMISD::VLD4_UPD; 10805 NumVecs = 4; break; 10806 case Intrinsic::arm_neon_vld2lane: NewOpc = ARMISD::VLD2LN_UPD; 10807 NumVecs = 2; isLaneOp = true; break; 10808 case Intrinsic::arm_neon_vld3lane: NewOpc = ARMISD::VLD3LN_UPD; 10809 NumVecs = 3; isLaneOp = true; break; 10810 case Intrinsic::arm_neon_vld4lane: NewOpc = ARMISD::VLD4LN_UPD; 10811 NumVecs = 4; isLaneOp = true; break; 10812 case Intrinsic::arm_neon_vst1: NewOpc = ARMISD::VST1_UPD; 10813 NumVecs = 1; isLoadOp = false; break; 10814 case Intrinsic::arm_neon_vst2: NewOpc = ARMISD::VST2_UPD; 10815 NumVecs = 2; isLoadOp = false; break; 10816 case Intrinsic::arm_neon_vst3: NewOpc = ARMISD::VST3_UPD; 10817 NumVecs = 3; isLoadOp = false; break; 10818 case Intrinsic::arm_neon_vst4: NewOpc = ARMISD::VST4_UPD; 10819 NumVecs = 4; isLoadOp = false; break; 10820 case Intrinsic::arm_neon_vst2lane: NewOpc = ARMISD::VST2LN_UPD; 10821 NumVecs = 2; isLoadOp = false; isLaneOp = true; break; 10822 case Intrinsic::arm_neon_vst3lane: NewOpc = ARMISD::VST3LN_UPD; 10823 NumVecs = 3; isLoadOp = false; isLaneOp = true; break; 10824 case Intrinsic::arm_neon_vst4lane: NewOpc = ARMISD::VST4LN_UPD; 10825 NumVecs = 4; isLoadOp = false; isLaneOp = true; break; 10826 } 10827 } else { 10828 isLaneOp = true; 10829 switch (N->getOpcode()) { 10830 default: llvm_unreachable("unexpected opcode for Neon base update"); 10831 case ARMISD::VLD1DUP: NewOpc = ARMISD::VLD1DUP_UPD; NumVecs = 1; break; 10832 case ARMISD::VLD2DUP: NewOpc = ARMISD::VLD2DUP_UPD; NumVecs = 2; break; 10833 case ARMISD::VLD3DUP: NewOpc = ARMISD::VLD3DUP_UPD; NumVecs = 3; break; 10834 case ARMISD::VLD4DUP: NewOpc = ARMISD::VLD4DUP_UPD; NumVecs = 4; break; 10835 case ISD::LOAD: NewOpc = ARMISD::VLD1_UPD; 10836 NumVecs = 1; isLaneOp = false; break; 10837 case ISD::STORE: NewOpc = ARMISD::VST1_UPD; 10838 NumVecs = 1; isLaneOp = false; isLoadOp = false; break; 10839 } 10840 } 10841 10842 // Find the size of memory referenced by the load/store. 10843 EVT VecTy; 10844 if (isLoadOp) { 10845 VecTy = N->getValueType(0); 10846 } else if (isIntrinsic) { 10847 VecTy = N->getOperand(AddrOpIdx+1).getValueType(); 10848 } else { 10849 assert(isStore && "Node has to be a load, a store, or an intrinsic!"); 10850 VecTy = N->getOperand(1).getValueType(); 10851 } 10852 10853 unsigned NumBytes = NumVecs * VecTy.getSizeInBits() / 8; 10854 if (isLaneOp) 10855 NumBytes /= VecTy.getVectorNumElements(); 10856 10857 // If the increment is a constant, it must match the memory ref size. 10858 SDValue Inc = User->getOperand(User->getOperand(0) == Addr ? 1 : 0); 10859 if (ConstantSDNode *CInc = dyn_cast<ConstantSDNode>(Inc.getNode())) { 10860 uint64_t IncVal = CInc->getZExtValue(); 10861 if (IncVal != NumBytes) 10862 continue; 10863 } else if (NumBytes >= 3 * 16) { 10864 // VLD3/4 and VST3/4 for 128-bit vectors are implemented with two 10865 // separate instructions that make it harder to use a non-constant update. 10866 continue; 10867 } 10868 10869 // OK, we found an ADD we can fold into the base update. 10870 // Now, create a _UPD node, taking care of not breaking alignment. 10871 10872 EVT AlignedVecTy = VecTy; 10873 unsigned Alignment = MemN->getAlignment(); 10874 10875 // If this is a less-than-standard-aligned load/store, change the type to 10876 // match the standard alignment. 10877 // The alignment is overlooked when selecting _UPD variants; and it's 10878 // easier to introduce bitcasts here than fix that. 10879 // There are 3 ways to get to this base-update combine: 10880 // - intrinsics: they are assumed to be properly aligned (to the standard 10881 // alignment of the memory type), so we don't need to do anything. 10882 // - ARMISD::VLDx nodes: they are only generated from the aforementioned 10883 // intrinsics, so, likewise, there's nothing to do. 10884 // - generic load/store instructions: the alignment is specified as an 10885 // explicit operand, rather than implicitly as the standard alignment 10886 // of the memory type (like the intrisics). We need to change the 10887 // memory type to match the explicit alignment. That way, we don't 10888 // generate non-standard-aligned ARMISD::VLDx nodes. 10889 if (isa<LSBaseSDNode>(N)) { 10890 if (Alignment == 0) 10891 Alignment = 1; 10892 if (Alignment < VecTy.getScalarSizeInBits() / 8) { 10893 MVT EltTy = MVT::getIntegerVT(Alignment * 8); 10894 assert(NumVecs == 1 && "Unexpected multi-element generic load/store."); 10895 assert(!isLaneOp && "Unexpected generic load/store lane."); 10896 unsigned NumElts = NumBytes / (EltTy.getSizeInBits() / 8); 10897 AlignedVecTy = MVT::getVectorVT(EltTy, NumElts); 10898 } 10899 // Don't set an explicit alignment on regular load/stores that we want 10900 // to transform to VLD/VST 1_UPD nodes. 10901 // This matches the behavior of regular load/stores, which only get an 10902 // explicit alignment if the MMO alignment is larger than the standard 10903 // alignment of the memory type. 10904 // Intrinsics, however, always get an explicit alignment, set to the 10905 // alignment of the MMO. 10906 Alignment = 1; 10907 } 10908 10909 // Create the new updating load/store node. 10910 // First, create an SDVTList for the new updating node's results. 10911 EVT Tys[6]; 10912 unsigned NumResultVecs = (isLoadOp ? NumVecs : 0); 10913 unsigned n; 10914 for (n = 0; n < NumResultVecs; ++n) 10915 Tys[n] = AlignedVecTy; 10916 Tys[n++] = MVT::i32; 10917 Tys[n] = MVT::Other; 10918 SDVTList SDTys = DAG.getVTList(makeArrayRef(Tys, NumResultVecs+2)); 10919 10920 // Then, gather the new node's operands. 10921 SmallVector<SDValue, 8> Ops; 10922 Ops.push_back(N->getOperand(0)); // incoming chain 10923 Ops.push_back(N->getOperand(AddrOpIdx)); 10924 Ops.push_back(Inc); 10925 10926 if (StoreSDNode *StN = dyn_cast<StoreSDNode>(N)) { 10927 // Try to match the intrinsic's signature 10928 Ops.push_back(StN->getValue()); 10929 } else { 10930 // Loads (and of course intrinsics) match the intrinsics' signature, 10931 // so just add all but the alignment operand. 10932 for (unsigned i = AddrOpIdx + 1; i < N->getNumOperands() - 1; ++i) 10933 Ops.push_back(N->getOperand(i)); 10934 } 10935 10936 // For all node types, the alignment operand is always the last one. 10937 Ops.push_back(DAG.getConstant(Alignment, dl, MVT::i32)); 10938 10939 // If this is a non-standard-aligned STORE, the penultimate operand is the 10940 // stored value. Bitcast it to the aligned type. 10941 if (AlignedVecTy != VecTy && N->getOpcode() == ISD::STORE) { 10942 SDValue &StVal = Ops[Ops.size()-2]; 10943 StVal = DAG.getNode(ISD::BITCAST, dl, AlignedVecTy, StVal); 10944 } 10945 10946 EVT LoadVT = isLaneOp ? VecTy.getVectorElementType() : AlignedVecTy; 10947 SDValue UpdN = DAG.getMemIntrinsicNode(NewOpc, dl, SDTys, Ops, LoadVT, 10948 MemN->getMemOperand()); 10949 10950 // Update the uses. 10951 SmallVector<SDValue, 5> NewResults; 10952 for (unsigned i = 0; i < NumResultVecs; ++i) 10953 NewResults.push_back(SDValue(UpdN.getNode(), i)); 10954 10955 // If this is an non-standard-aligned LOAD, the first result is the loaded 10956 // value. Bitcast it to the expected result type. 10957 if (AlignedVecTy != VecTy && N->getOpcode() == ISD::LOAD) { 10958 SDValue &LdVal = NewResults[0]; 10959 LdVal = DAG.getNode(ISD::BITCAST, dl, VecTy, LdVal); 10960 } 10961 10962 NewResults.push_back(SDValue(UpdN.getNode(), NumResultVecs+1)); // chain 10963 DCI.CombineTo(N, NewResults); 10964 DCI.CombineTo(User, SDValue(UpdN.getNode(), NumResultVecs)); 10965 10966 break; 10967 } 10968 return SDValue(); 10969 } 10970 10971 static SDValue PerformVLDCombine(SDNode *N, 10972 TargetLowering::DAGCombinerInfo &DCI) { 10973 if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer()) 10974 return SDValue(); 10975 10976 return CombineBaseUpdate(N, DCI); 10977 } 10978 10979 /// CombineVLDDUP - For a VDUPLANE node N, check if its source operand is a 10980 /// vldN-lane (N > 1) intrinsic, and if all the other uses of that intrinsic 10981 /// are also VDUPLANEs. If so, combine them to a vldN-dup operation and 10982 /// return true. 10983 static bool CombineVLDDUP(SDNode *N, TargetLowering::DAGCombinerInfo &DCI) { 10984 SelectionDAG &DAG = DCI.DAG; 10985 EVT VT = N->getValueType(0); 10986 // vldN-dup instructions only support 64-bit vectors for N > 1. 10987 if (!VT.is64BitVector()) 10988 return false; 10989 10990 // Check if the VDUPLANE operand is a vldN-dup intrinsic. 10991 SDNode *VLD = N->getOperand(0).getNode(); 10992 if (VLD->getOpcode() != ISD::INTRINSIC_W_CHAIN) 10993 return false; 10994 unsigned NumVecs = 0; 10995 unsigned NewOpc = 0; 10996 unsigned IntNo = cast<ConstantSDNode>(VLD->getOperand(1))->getZExtValue(); 10997 if (IntNo == Intrinsic::arm_neon_vld2lane) { 10998 NumVecs = 2; 10999 NewOpc = ARMISD::VLD2DUP; 11000 } else if (IntNo == Intrinsic::arm_neon_vld3lane) { 11001 NumVecs = 3; 11002 NewOpc = ARMISD::VLD3DUP; 11003 } else if (IntNo == Intrinsic::arm_neon_vld4lane) { 11004 NumVecs = 4; 11005 NewOpc = ARMISD::VLD4DUP; 11006 } else { 11007 return false; 11008 } 11009 11010 // First check that all the vldN-lane uses are VDUPLANEs and that the lane 11011 // numbers match the load. 11012 unsigned VLDLaneNo = 11013 cast<ConstantSDNode>(VLD->getOperand(NumVecs+3))->getZExtValue(); 11014 for (SDNode::use_iterator UI = VLD->use_begin(), UE = VLD->use_end(); 11015 UI != UE; ++UI) { 11016 // Ignore uses of the chain result. 11017 if (UI.getUse().getResNo() == NumVecs) 11018 continue; 11019 SDNode *User = *UI; 11020 if (User->getOpcode() != ARMISD::VDUPLANE || 11021 VLDLaneNo != cast<ConstantSDNode>(User->getOperand(1))->getZExtValue()) 11022 return false; 11023 } 11024 11025 // Create the vldN-dup node. 11026 EVT Tys[5]; 11027 unsigned n; 11028 for (n = 0; n < NumVecs; ++n) 11029 Tys[n] = VT; 11030 Tys[n] = MVT::Other; 11031 SDVTList SDTys = DAG.getVTList(makeArrayRef(Tys, NumVecs+1)); 11032 SDValue Ops[] = { VLD->getOperand(0), VLD->getOperand(2) }; 11033 MemIntrinsicSDNode *VLDMemInt = cast<MemIntrinsicSDNode>(VLD); 11034 SDValue VLDDup = DAG.getMemIntrinsicNode(NewOpc, SDLoc(VLD), SDTys, 11035 Ops, VLDMemInt->getMemoryVT(), 11036 VLDMemInt->getMemOperand()); 11037 11038 // Update the uses. 11039 for (SDNode::use_iterator UI = VLD->use_begin(), UE = VLD->use_end(); 11040 UI != UE; ++UI) { 11041 unsigned ResNo = UI.getUse().getResNo(); 11042 // Ignore uses of the chain result. 11043 if (ResNo == NumVecs) 11044 continue; 11045 SDNode *User = *UI; 11046 DCI.CombineTo(User, SDValue(VLDDup.getNode(), ResNo)); 11047 } 11048 11049 // Now the vldN-lane intrinsic is dead except for its chain result. 11050 // Update uses of the chain. 11051 std::vector<SDValue> VLDDupResults; 11052 for (unsigned n = 0; n < NumVecs; ++n) 11053 VLDDupResults.push_back(SDValue(VLDDup.getNode(), n)); 11054 VLDDupResults.push_back(SDValue(VLDDup.getNode(), NumVecs)); 11055 DCI.CombineTo(VLD, VLDDupResults); 11056 11057 return true; 11058 } 11059 11060 /// PerformVDUPLANECombine - Target-specific dag combine xforms for 11061 /// ARMISD::VDUPLANE. 11062 static SDValue PerformVDUPLANECombine(SDNode *N, 11063 TargetLowering::DAGCombinerInfo &DCI) { 11064 SDValue Op = N->getOperand(0); 11065 11066 // If the source is a vldN-lane (N > 1) intrinsic, and all the other uses 11067 // of that intrinsic are also VDUPLANEs, combine them to a vldN-dup operation. 11068 if (CombineVLDDUP(N, DCI)) 11069 return SDValue(N, 0); 11070 11071 // If the source is already a VMOVIMM or VMVNIMM splat, the VDUPLANE is 11072 // redundant. Ignore bit_converts for now; element sizes are checked below. 11073 while (Op.getOpcode() == ISD::BITCAST) 11074 Op = Op.getOperand(0); 11075 if (Op.getOpcode() != ARMISD::VMOVIMM && Op.getOpcode() != ARMISD::VMVNIMM) 11076 return SDValue(); 11077 11078 // Make sure the VMOV element size is not bigger than the VDUPLANE elements. 11079 unsigned EltSize = Op.getScalarValueSizeInBits(); 11080 // The canonical VMOV for a zero vector uses a 32-bit element size. 11081 unsigned Imm = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue(); 11082 unsigned EltBits; 11083 if (ARM_AM::decodeNEONModImm(Imm, EltBits) == 0) 11084 EltSize = 8; 11085 EVT VT = N->getValueType(0); 11086 if (EltSize > VT.getScalarSizeInBits()) 11087 return SDValue(); 11088 11089 return DCI.DAG.getNode(ISD::BITCAST, SDLoc(N), VT, Op); 11090 } 11091 11092 /// PerformVDUPCombine - Target-specific dag combine xforms for ARMISD::VDUP. 11093 static SDValue PerformVDUPCombine(SDNode *N, 11094 TargetLowering::DAGCombinerInfo &DCI) { 11095 SelectionDAG &DAG = DCI.DAG; 11096 SDValue Op = N->getOperand(0); 11097 11098 // Match VDUP(LOAD) -> VLD1DUP. 11099 // We match this pattern here rather than waiting for isel because the 11100 // transform is only legal for unindexed loads. 11101 LoadSDNode *LD = dyn_cast<LoadSDNode>(Op.getNode()); 11102 if (LD && Op.hasOneUse() && LD->isUnindexed() && 11103 LD->getMemoryVT() == N->getValueType(0).getVectorElementType()) { 11104 SDValue Ops[] = { LD->getOperand(0), LD->getOperand(1), 11105 DAG.getConstant(LD->getAlignment(), SDLoc(N), MVT::i32) }; 11106 SDVTList SDTys = DAG.getVTList(N->getValueType(0), MVT::Other); 11107 SDValue VLDDup = DAG.getMemIntrinsicNode(ARMISD::VLD1DUP, SDLoc(N), SDTys, 11108 Ops, LD->getMemoryVT(), 11109 LD->getMemOperand()); 11110 DAG.ReplaceAllUsesOfValueWith(SDValue(LD, 1), VLDDup.getValue(1)); 11111 return VLDDup; 11112 } 11113 11114 return SDValue(); 11115 } 11116 11117 static SDValue PerformLOADCombine(SDNode *N, 11118 TargetLowering::DAGCombinerInfo &DCI) { 11119 EVT VT = N->getValueType(0); 11120 11121 // If this is a legal vector load, try to combine it into a VLD1_UPD. 11122 if (ISD::isNormalLoad(N) && VT.isVector() && 11123 DCI.DAG.getTargetLoweringInfo().isTypeLegal(VT)) 11124 return CombineBaseUpdate(N, DCI); 11125 11126 return SDValue(); 11127 } 11128 11129 /// PerformSTORECombine - Target-specific dag combine xforms for 11130 /// ISD::STORE. 11131 static SDValue PerformSTORECombine(SDNode *N, 11132 TargetLowering::DAGCombinerInfo &DCI) { 11133 StoreSDNode *St = cast<StoreSDNode>(N); 11134 if (St->isVolatile()) 11135 return SDValue(); 11136 11137 // Optimize trunc store (of multiple scalars) to shuffle and store. First, 11138 // pack all of the elements in one place. Next, store to memory in fewer 11139 // chunks. 11140 SDValue StVal = St->getValue(); 11141 EVT VT = StVal.getValueType(); 11142 if (St->isTruncatingStore() && VT.isVector()) { 11143 SelectionDAG &DAG = DCI.DAG; 11144 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 11145 EVT StVT = St->getMemoryVT(); 11146 unsigned NumElems = VT.getVectorNumElements(); 11147 assert(StVT != VT && "Cannot truncate to the same type"); 11148 unsigned FromEltSz = VT.getScalarSizeInBits(); 11149 unsigned ToEltSz = StVT.getScalarSizeInBits(); 11150 11151 // From, To sizes and ElemCount must be pow of two 11152 if (!isPowerOf2_32(NumElems * FromEltSz * ToEltSz)) return SDValue(); 11153 11154 // We are going to use the original vector elt for storing. 11155 // Accumulated smaller vector elements must be a multiple of the store size. 11156 if (0 != (NumElems * FromEltSz) % ToEltSz) return SDValue(); 11157 11158 unsigned SizeRatio = FromEltSz / ToEltSz; 11159 assert(SizeRatio * NumElems * ToEltSz == VT.getSizeInBits()); 11160 11161 // Create a type on which we perform the shuffle. 11162 EVT WideVecVT = EVT::getVectorVT(*DAG.getContext(), StVT.getScalarType(), 11163 NumElems*SizeRatio); 11164 assert(WideVecVT.getSizeInBits() == VT.getSizeInBits()); 11165 11166 SDLoc DL(St); 11167 SDValue WideVec = DAG.getNode(ISD::BITCAST, DL, WideVecVT, StVal); 11168 SmallVector<int, 8> ShuffleVec(NumElems * SizeRatio, -1); 11169 for (unsigned i = 0; i < NumElems; ++i) 11170 ShuffleVec[i] = DAG.getDataLayout().isBigEndian() 11171 ? (i + 1) * SizeRatio - 1 11172 : i * SizeRatio; 11173 11174 // Can't shuffle using an illegal type. 11175 if (!TLI.isTypeLegal(WideVecVT)) return SDValue(); 11176 11177 SDValue Shuff = DAG.getVectorShuffle(WideVecVT, DL, WideVec, 11178 DAG.getUNDEF(WideVec.getValueType()), 11179 ShuffleVec); 11180 // At this point all of the data is stored at the bottom of the 11181 // register. We now need to save it to mem. 11182 11183 // Find the largest store unit 11184 MVT StoreType = MVT::i8; 11185 for (MVT Tp : MVT::integer_valuetypes()) { 11186 if (TLI.isTypeLegal(Tp) && Tp.getSizeInBits() <= NumElems * ToEltSz) 11187 StoreType = Tp; 11188 } 11189 // Didn't find a legal store type. 11190 if (!TLI.isTypeLegal(StoreType)) 11191 return SDValue(); 11192 11193 // Bitcast the original vector into a vector of store-size units 11194 EVT StoreVecVT = EVT::getVectorVT(*DAG.getContext(), 11195 StoreType, VT.getSizeInBits()/EVT(StoreType).getSizeInBits()); 11196 assert(StoreVecVT.getSizeInBits() == VT.getSizeInBits()); 11197 SDValue ShuffWide = DAG.getNode(ISD::BITCAST, DL, StoreVecVT, Shuff); 11198 SmallVector<SDValue, 8> Chains; 11199 SDValue Increment = DAG.getConstant(StoreType.getSizeInBits() / 8, DL, 11200 TLI.getPointerTy(DAG.getDataLayout())); 11201 SDValue BasePtr = St->getBasePtr(); 11202 11203 // Perform one or more big stores into memory. 11204 unsigned E = (ToEltSz*NumElems)/StoreType.getSizeInBits(); 11205 for (unsigned I = 0; I < E; I++) { 11206 SDValue SubVec = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, 11207 StoreType, ShuffWide, 11208 DAG.getIntPtrConstant(I, DL)); 11209 SDValue Ch = DAG.getStore(St->getChain(), DL, SubVec, BasePtr, 11210 St->getPointerInfo(), St->getAlignment(), 11211 St->getMemOperand()->getFlags()); 11212 BasePtr = DAG.getNode(ISD::ADD, DL, BasePtr.getValueType(), BasePtr, 11213 Increment); 11214 Chains.push_back(Ch); 11215 } 11216 return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Chains); 11217 } 11218 11219 if (!ISD::isNormalStore(St)) 11220 return SDValue(); 11221 11222 // Split a store of a VMOVDRR into two integer stores to avoid mixing NEON and 11223 // ARM stores of arguments in the same cache line. 11224 if (StVal.getNode()->getOpcode() == ARMISD::VMOVDRR && 11225 StVal.getNode()->hasOneUse()) { 11226 SelectionDAG &DAG = DCI.DAG; 11227 bool isBigEndian = DAG.getDataLayout().isBigEndian(); 11228 SDLoc DL(St); 11229 SDValue BasePtr = St->getBasePtr(); 11230 SDValue NewST1 = DAG.getStore( 11231 St->getChain(), DL, StVal.getNode()->getOperand(isBigEndian ? 1 : 0), 11232 BasePtr, St->getPointerInfo(), St->getAlignment(), 11233 St->getMemOperand()->getFlags()); 11234 11235 SDValue OffsetPtr = DAG.getNode(ISD::ADD, DL, MVT::i32, BasePtr, 11236 DAG.getConstant(4, DL, MVT::i32)); 11237 return DAG.getStore(NewST1.getValue(0), DL, 11238 StVal.getNode()->getOperand(isBigEndian ? 0 : 1), 11239 OffsetPtr, St->getPointerInfo(), 11240 std::min(4U, St->getAlignment() / 2), 11241 St->getMemOperand()->getFlags()); 11242 } 11243 11244 if (StVal.getValueType() == MVT::i64 && 11245 StVal.getNode()->getOpcode() == ISD::EXTRACT_VECTOR_ELT) { 11246 11247 // Bitcast an i64 store extracted from a vector to f64. 11248 // Otherwise, the i64 value will be legalized to a pair of i32 values. 11249 SelectionDAG &DAG = DCI.DAG; 11250 SDLoc dl(StVal); 11251 SDValue IntVec = StVal.getOperand(0); 11252 EVT FloatVT = EVT::getVectorVT(*DAG.getContext(), MVT::f64, 11253 IntVec.getValueType().getVectorNumElements()); 11254 SDValue Vec = DAG.getNode(ISD::BITCAST, dl, FloatVT, IntVec); 11255 SDValue ExtElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, 11256 Vec, StVal.getOperand(1)); 11257 dl = SDLoc(N); 11258 SDValue V = DAG.getNode(ISD::BITCAST, dl, MVT::i64, ExtElt); 11259 // Make the DAGCombiner fold the bitcasts. 11260 DCI.AddToWorklist(Vec.getNode()); 11261 DCI.AddToWorklist(ExtElt.getNode()); 11262 DCI.AddToWorklist(V.getNode()); 11263 return DAG.getStore(St->getChain(), dl, V, St->getBasePtr(), 11264 St->getPointerInfo(), St->getAlignment(), 11265 St->getMemOperand()->getFlags(), St->getAAInfo()); 11266 } 11267 11268 // If this is a legal vector store, try to combine it into a VST1_UPD. 11269 if (ISD::isNormalStore(N) && VT.isVector() && 11270 DCI.DAG.getTargetLoweringInfo().isTypeLegal(VT)) 11271 return CombineBaseUpdate(N, DCI); 11272 11273 return SDValue(); 11274 } 11275 11276 /// PerformVCVTCombine - VCVT (floating-point to fixed-point, Advanced SIMD) 11277 /// can replace combinations of VMUL and VCVT (floating-point to integer) 11278 /// when the VMUL has a constant operand that is a power of 2. 11279 /// 11280 /// Example (assume d17 = <float 8.000000e+00, float 8.000000e+00>): 11281 /// vmul.f32 d16, d17, d16 11282 /// vcvt.s32.f32 d16, d16 11283 /// becomes: 11284 /// vcvt.s32.f32 d16, d16, #3 11285 static SDValue PerformVCVTCombine(SDNode *N, SelectionDAG &DAG, 11286 const ARMSubtarget *Subtarget) { 11287 if (!Subtarget->hasNEON()) 11288 return SDValue(); 11289 11290 SDValue Op = N->getOperand(0); 11291 if (!Op.getValueType().isVector() || !Op.getValueType().isSimple() || 11292 Op.getOpcode() != ISD::FMUL) 11293 return SDValue(); 11294 11295 SDValue ConstVec = Op->getOperand(1); 11296 if (!isa<BuildVectorSDNode>(ConstVec)) 11297 return SDValue(); 11298 11299 MVT FloatTy = Op.getSimpleValueType().getVectorElementType(); 11300 uint32_t FloatBits = FloatTy.getSizeInBits(); 11301 MVT IntTy = N->getSimpleValueType(0).getVectorElementType(); 11302 uint32_t IntBits = IntTy.getSizeInBits(); 11303 unsigned NumLanes = Op.getValueType().getVectorNumElements(); 11304 if (FloatBits != 32 || IntBits > 32 || NumLanes > 4) { 11305 // These instructions only exist converting from f32 to i32. We can handle 11306 // smaller integers by generating an extra truncate, but larger ones would 11307 // be lossy. We also can't handle more then 4 lanes, since these intructions 11308 // only support v2i32/v4i32 types. 11309 return SDValue(); 11310 } 11311 11312 BitVector UndefElements; 11313 BuildVectorSDNode *BV = cast<BuildVectorSDNode>(ConstVec); 11314 int32_t C = BV->getConstantFPSplatPow2ToLog2Int(&UndefElements, 33); 11315 if (C == -1 || C == 0 || C > 32) 11316 return SDValue(); 11317 11318 SDLoc dl(N); 11319 bool isSigned = N->getOpcode() == ISD::FP_TO_SINT; 11320 unsigned IntrinsicOpcode = isSigned ? Intrinsic::arm_neon_vcvtfp2fxs : 11321 Intrinsic::arm_neon_vcvtfp2fxu; 11322 SDValue FixConv = DAG.getNode( 11323 ISD::INTRINSIC_WO_CHAIN, dl, NumLanes == 2 ? MVT::v2i32 : MVT::v4i32, 11324 DAG.getConstant(IntrinsicOpcode, dl, MVT::i32), Op->getOperand(0), 11325 DAG.getConstant(C, dl, MVT::i32)); 11326 11327 if (IntBits < FloatBits) 11328 FixConv = DAG.getNode(ISD::TRUNCATE, dl, N->getValueType(0), FixConv); 11329 11330 return FixConv; 11331 } 11332 11333 /// PerformVDIVCombine - VCVT (fixed-point to floating-point, Advanced SIMD) 11334 /// can replace combinations of VCVT (integer to floating-point) and VDIV 11335 /// when the VDIV has a constant operand that is a power of 2. 11336 /// 11337 /// Example (assume d17 = <float 8.000000e+00, float 8.000000e+00>): 11338 /// vcvt.f32.s32 d16, d16 11339 /// vdiv.f32 d16, d17, d16 11340 /// becomes: 11341 /// vcvt.f32.s32 d16, d16, #3 11342 static SDValue PerformVDIVCombine(SDNode *N, SelectionDAG &DAG, 11343 const ARMSubtarget *Subtarget) { 11344 if (!Subtarget->hasNEON()) 11345 return SDValue(); 11346 11347 SDValue Op = N->getOperand(0); 11348 unsigned OpOpcode = Op.getNode()->getOpcode(); 11349 if (!N->getValueType(0).isVector() || !N->getValueType(0).isSimple() || 11350 (OpOpcode != ISD::SINT_TO_FP && OpOpcode != ISD::UINT_TO_FP)) 11351 return SDValue(); 11352 11353 SDValue ConstVec = N->getOperand(1); 11354 if (!isa<BuildVectorSDNode>(ConstVec)) 11355 return SDValue(); 11356 11357 MVT FloatTy = N->getSimpleValueType(0).getVectorElementType(); 11358 uint32_t FloatBits = FloatTy.getSizeInBits(); 11359 MVT IntTy = Op.getOperand(0).getSimpleValueType().getVectorElementType(); 11360 uint32_t IntBits = IntTy.getSizeInBits(); 11361 unsigned NumLanes = Op.getValueType().getVectorNumElements(); 11362 if (FloatBits != 32 || IntBits > 32 || NumLanes > 4) { 11363 // These instructions only exist converting from i32 to f32. We can handle 11364 // smaller integers by generating an extra extend, but larger ones would 11365 // be lossy. We also can't handle more then 4 lanes, since these intructions 11366 // only support v2i32/v4i32 types. 11367 return SDValue(); 11368 } 11369 11370 BitVector UndefElements; 11371 BuildVectorSDNode *BV = cast<BuildVectorSDNode>(ConstVec); 11372 int32_t C = BV->getConstantFPSplatPow2ToLog2Int(&UndefElements, 33); 11373 if (C == -1 || C == 0 || C > 32) 11374 return SDValue(); 11375 11376 SDLoc dl(N); 11377 bool isSigned = OpOpcode == ISD::SINT_TO_FP; 11378 SDValue ConvInput = Op.getOperand(0); 11379 if (IntBits < FloatBits) 11380 ConvInput = DAG.getNode(isSigned ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND, 11381 dl, NumLanes == 2 ? MVT::v2i32 : MVT::v4i32, 11382 ConvInput); 11383 11384 unsigned IntrinsicOpcode = isSigned ? Intrinsic::arm_neon_vcvtfxs2fp : 11385 Intrinsic::arm_neon_vcvtfxu2fp; 11386 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, 11387 Op.getValueType(), 11388 DAG.getConstant(IntrinsicOpcode, dl, MVT::i32), 11389 ConvInput, DAG.getConstant(C, dl, MVT::i32)); 11390 } 11391 11392 /// Getvshiftimm - Check if this is a valid build_vector for the immediate 11393 /// operand of a vector shift operation, where all the elements of the 11394 /// build_vector must have the same constant integer value. 11395 static bool getVShiftImm(SDValue Op, unsigned ElementBits, int64_t &Cnt) { 11396 // Ignore bit_converts. 11397 while (Op.getOpcode() == ISD::BITCAST) 11398 Op = Op.getOperand(0); 11399 BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(Op.getNode()); 11400 APInt SplatBits, SplatUndef; 11401 unsigned SplatBitSize; 11402 bool HasAnyUndefs; 11403 if (! BVN || ! BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, 11404 HasAnyUndefs, ElementBits) || 11405 SplatBitSize > ElementBits) 11406 return false; 11407 Cnt = SplatBits.getSExtValue(); 11408 return true; 11409 } 11410 11411 /// isVShiftLImm - Check if this is a valid build_vector for the immediate 11412 /// operand of a vector shift left operation. That value must be in the range: 11413 /// 0 <= Value < ElementBits for a left shift; or 11414 /// 0 <= Value <= ElementBits for a long left shift. 11415 static bool isVShiftLImm(SDValue Op, EVT VT, bool isLong, int64_t &Cnt) { 11416 assert(VT.isVector() && "vector shift count is not a vector type"); 11417 int64_t ElementBits = VT.getScalarSizeInBits(); 11418 if (! getVShiftImm(Op, ElementBits, Cnt)) 11419 return false; 11420 return (Cnt >= 0 && (isLong ? Cnt-1 : Cnt) < ElementBits); 11421 } 11422 11423 /// isVShiftRImm - Check if this is a valid build_vector for the immediate 11424 /// operand of a vector shift right operation. For a shift opcode, the value 11425 /// is positive, but for an intrinsic the value count must be negative. The 11426 /// absolute value must be in the range: 11427 /// 1 <= |Value| <= ElementBits for a right shift; or 11428 /// 1 <= |Value| <= ElementBits/2 for a narrow right shift. 11429 static bool isVShiftRImm(SDValue Op, EVT VT, bool isNarrow, bool isIntrinsic, 11430 int64_t &Cnt) { 11431 assert(VT.isVector() && "vector shift count is not a vector type"); 11432 int64_t ElementBits = VT.getScalarSizeInBits(); 11433 if (! getVShiftImm(Op, ElementBits, Cnt)) 11434 return false; 11435 if (!isIntrinsic) 11436 return (Cnt >= 1 && Cnt <= (isNarrow ? ElementBits/2 : ElementBits)); 11437 if (Cnt >= -(isNarrow ? ElementBits/2 : ElementBits) && Cnt <= -1) { 11438 Cnt = -Cnt; 11439 return true; 11440 } 11441 return false; 11442 } 11443 11444 /// PerformIntrinsicCombine - ARM-specific DAG combining for intrinsics. 11445 static SDValue PerformIntrinsicCombine(SDNode *N, SelectionDAG &DAG) { 11446 unsigned IntNo = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue(); 11447 switch (IntNo) { 11448 default: 11449 // Don't do anything for most intrinsics. 11450 break; 11451 11452 // Vector shifts: check for immediate versions and lower them. 11453 // Note: This is done during DAG combining instead of DAG legalizing because 11454 // the build_vectors for 64-bit vector element shift counts are generally 11455 // not legal, and it is hard to see their values after they get legalized to 11456 // loads from a constant pool. 11457 case Intrinsic::arm_neon_vshifts: 11458 case Intrinsic::arm_neon_vshiftu: 11459 case Intrinsic::arm_neon_vrshifts: 11460 case Intrinsic::arm_neon_vrshiftu: 11461 case Intrinsic::arm_neon_vrshiftn: 11462 case Intrinsic::arm_neon_vqshifts: 11463 case Intrinsic::arm_neon_vqshiftu: 11464 case Intrinsic::arm_neon_vqshiftsu: 11465 case Intrinsic::arm_neon_vqshiftns: 11466 case Intrinsic::arm_neon_vqshiftnu: 11467 case Intrinsic::arm_neon_vqshiftnsu: 11468 case Intrinsic::arm_neon_vqrshiftns: 11469 case Intrinsic::arm_neon_vqrshiftnu: 11470 case Intrinsic::arm_neon_vqrshiftnsu: { 11471 EVT VT = N->getOperand(1).getValueType(); 11472 int64_t Cnt; 11473 unsigned VShiftOpc = 0; 11474 11475 switch (IntNo) { 11476 case Intrinsic::arm_neon_vshifts: 11477 case Intrinsic::arm_neon_vshiftu: 11478 if (isVShiftLImm(N->getOperand(2), VT, false, Cnt)) { 11479 VShiftOpc = ARMISD::VSHL; 11480 break; 11481 } 11482 if (isVShiftRImm(N->getOperand(2), VT, false, true, Cnt)) { 11483 VShiftOpc = (IntNo == Intrinsic::arm_neon_vshifts ? 11484 ARMISD::VSHRs : ARMISD::VSHRu); 11485 break; 11486 } 11487 return SDValue(); 11488 11489 case Intrinsic::arm_neon_vrshifts: 11490 case Intrinsic::arm_neon_vrshiftu: 11491 if (isVShiftRImm(N->getOperand(2), VT, false, true, Cnt)) 11492 break; 11493 return SDValue(); 11494 11495 case Intrinsic::arm_neon_vqshifts: 11496 case Intrinsic::arm_neon_vqshiftu: 11497 if (isVShiftLImm(N->getOperand(2), VT, false, Cnt)) 11498 break; 11499 return SDValue(); 11500 11501 case Intrinsic::arm_neon_vqshiftsu: 11502 if (isVShiftLImm(N->getOperand(2), VT, false, Cnt)) 11503 break; 11504 llvm_unreachable("invalid shift count for vqshlu intrinsic"); 11505 11506 case Intrinsic::arm_neon_vrshiftn: 11507 case Intrinsic::arm_neon_vqshiftns: 11508 case Intrinsic::arm_neon_vqshiftnu: 11509 case Intrinsic::arm_neon_vqshiftnsu: 11510 case Intrinsic::arm_neon_vqrshiftns: 11511 case Intrinsic::arm_neon_vqrshiftnu: 11512 case Intrinsic::arm_neon_vqrshiftnsu: 11513 // Narrowing shifts require an immediate right shift. 11514 if (isVShiftRImm(N->getOperand(2), VT, true, true, Cnt)) 11515 break; 11516 llvm_unreachable("invalid shift count for narrowing vector shift " 11517 "intrinsic"); 11518 11519 default: 11520 llvm_unreachable("unhandled vector shift"); 11521 } 11522 11523 switch (IntNo) { 11524 case Intrinsic::arm_neon_vshifts: 11525 case Intrinsic::arm_neon_vshiftu: 11526 // Opcode already set above. 11527 break; 11528 case Intrinsic::arm_neon_vrshifts: 11529 VShiftOpc = ARMISD::VRSHRs; break; 11530 case Intrinsic::arm_neon_vrshiftu: 11531 VShiftOpc = ARMISD::VRSHRu; break; 11532 case Intrinsic::arm_neon_vrshiftn: 11533 VShiftOpc = ARMISD::VRSHRN; break; 11534 case Intrinsic::arm_neon_vqshifts: 11535 VShiftOpc = ARMISD::VQSHLs; break; 11536 case Intrinsic::arm_neon_vqshiftu: 11537 VShiftOpc = ARMISD::VQSHLu; break; 11538 case Intrinsic::arm_neon_vqshiftsu: 11539 VShiftOpc = ARMISD::VQSHLsu; break; 11540 case Intrinsic::arm_neon_vqshiftns: 11541 VShiftOpc = ARMISD::VQSHRNs; break; 11542 case Intrinsic::arm_neon_vqshiftnu: 11543 VShiftOpc = ARMISD::VQSHRNu; break; 11544 case Intrinsic::arm_neon_vqshiftnsu: 11545 VShiftOpc = ARMISD::VQSHRNsu; break; 11546 case Intrinsic::arm_neon_vqrshiftns: 11547 VShiftOpc = ARMISD::VQRSHRNs; break; 11548 case Intrinsic::arm_neon_vqrshiftnu: 11549 VShiftOpc = ARMISD::VQRSHRNu; break; 11550 case Intrinsic::arm_neon_vqrshiftnsu: 11551 VShiftOpc = ARMISD::VQRSHRNsu; break; 11552 } 11553 11554 SDLoc dl(N); 11555 return DAG.getNode(VShiftOpc, dl, N->getValueType(0), 11556 N->getOperand(1), DAG.getConstant(Cnt, dl, MVT::i32)); 11557 } 11558 11559 case Intrinsic::arm_neon_vshiftins: { 11560 EVT VT = N->getOperand(1).getValueType(); 11561 int64_t Cnt; 11562 unsigned VShiftOpc = 0; 11563 11564 if (isVShiftLImm(N->getOperand(3), VT, false, Cnt)) 11565 VShiftOpc = ARMISD::VSLI; 11566 else if (isVShiftRImm(N->getOperand(3), VT, false, true, Cnt)) 11567 VShiftOpc = ARMISD::VSRI; 11568 else { 11569 llvm_unreachable("invalid shift count for vsli/vsri intrinsic"); 11570 } 11571 11572 SDLoc dl(N); 11573 return DAG.getNode(VShiftOpc, dl, N->getValueType(0), 11574 N->getOperand(1), N->getOperand(2), 11575 DAG.getConstant(Cnt, dl, MVT::i32)); 11576 } 11577 11578 case Intrinsic::arm_neon_vqrshifts: 11579 case Intrinsic::arm_neon_vqrshiftu: 11580 // No immediate versions of these to check for. 11581 break; 11582 } 11583 11584 return SDValue(); 11585 } 11586 11587 /// PerformShiftCombine - Checks for immediate versions of vector shifts and 11588 /// lowers them. As with the vector shift intrinsics, this is done during DAG 11589 /// combining instead of DAG legalizing because the build_vectors for 64-bit 11590 /// vector element shift counts are generally not legal, and it is hard to see 11591 /// their values after they get legalized to loads from a constant pool. 11592 static SDValue PerformShiftCombine(SDNode *N, SelectionDAG &DAG, 11593 const ARMSubtarget *ST) { 11594 EVT VT = N->getValueType(0); 11595 if (N->getOpcode() == ISD::SRL && VT == MVT::i32 && ST->hasV6Ops()) { 11596 // Canonicalize (srl (bswap x), 16) to (rotr (bswap x), 16) if the high 11597 // 16-bits of x is zero. This optimizes rev + lsr 16 to rev16. 11598 SDValue N1 = N->getOperand(1); 11599 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(N1)) { 11600 SDValue N0 = N->getOperand(0); 11601 if (C->getZExtValue() == 16 && N0.getOpcode() == ISD::BSWAP && 11602 DAG.MaskedValueIsZero(N0.getOperand(0), 11603 APInt::getHighBitsSet(32, 16))) 11604 return DAG.getNode(ISD::ROTR, SDLoc(N), VT, N0, N1); 11605 } 11606 } 11607 11608 // Nothing to be done for scalar shifts. 11609 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 11610 if (!VT.isVector() || !TLI.isTypeLegal(VT)) 11611 return SDValue(); 11612 11613 assert(ST->hasNEON() && "unexpected vector shift"); 11614 int64_t Cnt; 11615 11616 switch (N->getOpcode()) { 11617 default: llvm_unreachable("unexpected shift opcode"); 11618 11619 case ISD::SHL: 11620 if (isVShiftLImm(N->getOperand(1), VT, false, Cnt)) { 11621 SDLoc dl(N); 11622 return DAG.getNode(ARMISD::VSHL, dl, VT, N->getOperand(0), 11623 DAG.getConstant(Cnt, dl, MVT::i32)); 11624 } 11625 break; 11626 11627 case ISD::SRA: 11628 case ISD::SRL: 11629 if (isVShiftRImm(N->getOperand(1), VT, false, false, Cnt)) { 11630 unsigned VShiftOpc = (N->getOpcode() == ISD::SRA ? 11631 ARMISD::VSHRs : ARMISD::VSHRu); 11632 SDLoc dl(N); 11633 return DAG.getNode(VShiftOpc, dl, VT, N->getOperand(0), 11634 DAG.getConstant(Cnt, dl, MVT::i32)); 11635 } 11636 } 11637 return SDValue(); 11638 } 11639 11640 /// PerformExtendCombine - Target-specific DAG combining for ISD::SIGN_EXTEND, 11641 /// ISD::ZERO_EXTEND, and ISD::ANY_EXTEND. 11642 static SDValue PerformExtendCombine(SDNode *N, SelectionDAG &DAG, 11643 const ARMSubtarget *ST) { 11644 SDValue N0 = N->getOperand(0); 11645 11646 // Check for sign- and zero-extensions of vector extract operations of 8- 11647 // and 16-bit vector elements. NEON supports these directly. They are 11648 // handled during DAG combining because type legalization will promote them 11649 // to 32-bit types and it is messy to recognize the operations after that. 11650 if (ST->hasNEON() && N0.getOpcode() == ISD::EXTRACT_VECTOR_ELT) { 11651 SDValue Vec = N0.getOperand(0); 11652 SDValue Lane = N0.getOperand(1); 11653 EVT VT = N->getValueType(0); 11654 EVT EltVT = N0.getValueType(); 11655 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 11656 11657 if (VT == MVT::i32 && 11658 (EltVT == MVT::i8 || EltVT == MVT::i16) && 11659 TLI.isTypeLegal(Vec.getValueType()) && 11660 isa<ConstantSDNode>(Lane)) { 11661 11662 unsigned Opc = 0; 11663 switch (N->getOpcode()) { 11664 default: llvm_unreachable("unexpected opcode"); 11665 case ISD::SIGN_EXTEND: 11666 Opc = ARMISD::VGETLANEs; 11667 break; 11668 case ISD::ZERO_EXTEND: 11669 case ISD::ANY_EXTEND: 11670 Opc = ARMISD::VGETLANEu; 11671 break; 11672 } 11673 return DAG.getNode(Opc, SDLoc(N), VT, Vec, Lane); 11674 } 11675 } 11676 11677 return SDValue(); 11678 } 11679 11680 static void computeKnownBits(SelectionDAG &DAG, SDValue Op, APInt &KnownZero, 11681 APInt &KnownOne) { 11682 if (Op.getOpcode() == ARMISD::BFI) { 11683 // Conservatively, we can recurse down the first operand 11684 // and just mask out all affected bits. 11685 computeKnownBits(DAG, Op.getOperand(0), KnownZero, KnownOne); 11686 11687 // The operand to BFI is already a mask suitable for removing the bits it 11688 // sets. 11689 ConstantSDNode *CI = cast<ConstantSDNode>(Op.getOperand(2)); 11690 const APInt &Mask = CI->getAPIntValue(); 11691 KnownZero &= Mask; 11692 KnownOne &= Mask; 11693 return; 11694 } 11695 if (Op.getOpcode() == ARMISD::CMOV) { 11696 APInt KZ2(KnownZero.getBitWidth(), 0); 11697 APInt KO2(KnownOne.getBitWidth(), 0); 11698 computeKnownBits(DAG, Op.getOperand(0), KnownZero, KnownOne); 11699 computeKnownBits(DAG, Op.getOperand(1), KZ2, KO2); 11700 11701 KnownZero &= KZ2; 11702 KnownOne &= KO2; 11703 return; 11704 } 11705 return DAG.computeKnownBits(Op, KnownZero, KnownOne); 11706 } 11707 11708 SDValue ARMTargetLowering::PerformCMOVToBFICombine(SDNode *CMOV, SelectionDAG &DAG) const { 11709 // If we have a CMOV, OR and AND combination such as: 11710 // if (x & CN) 11711 // y |= CM; 11712 // 11713 // And: 11714 // * CN is a single bit; 11715 // * All bits covered by CM are known zero in y 11716 // 11717 // Then we can convert this into a sequence of BFI instructions. This will 11718 // always be a win if CM is a single bit, will always be no worse than the 11719 // TST&OR sequence if CM is two bits, and for thumb will be no worse if CM is 11720 // three bits (due to the extra IT instruction). 11721 11722 SDValue Op0 = CMOV->getOperand(0); 11723 SDValue Op1 = CMOV->getOperand(1); 11724 auto CCNode = cast<ConstantSDNode>(CMOV->getOperand(2)); 11725 auto CC = CCNode->getAPIntValue().getLimitedValue(); 11726 SDValue CmpZ = CMOV->getOperand(4); 11727 11728 // The compare must be against zero. 11729 if (!isNullConstant(CmpZ->getOperand(1))) 11730 return SDValue(); 11731 11732 assert(CmpZ->getOpcode() == ARMISD::CMPZ); 11733 SDValue And = CmpZ->getOperand(0); 11734 if (And->getOpcode() != ISD::AND) 11735 return SDValue(); 11736 ConstantSDNode *AndC = dyn_cast<ConstantSDNode>(And->getOperand(1)); 11737 if (!AndC || !AndC->getAPIntValue().isPowerOf2()) 11738 return SDValue(); 11739 SDValue X = And->getOperand(0); 11740 11741 if (CC == ARMCC::EQ) { 11742 // We're performing an "equal to zero" compare. Swap the operands so we 11743 // canonicalize on a "not equal to zero" compare. 11744 std::swap(Op0, Op1); 11745 } else { 11746 assert(CC == ARMCC::NE && "How can a CMPZ node not be EQ or NE?"); 11747 } 11748 11749 if (Op1->getOpcode() != ISD::OR) 11750 return SDValue(); 11751 11752 ConstantSDNode *OrC = dyn_cast<ConstantSDNode>(Op1->getOperand(1)); 11753 if (!OrC) 11754 return SDValue(); 11755 SDValue Y = Op1->getOperand(0); 11756 11757 if (Op0 != Y) 11758 return SDValue(); 11759 11760 // Now, is it profitable to continue? 11761 APInt OrCI = OrC->getAPIntValue(); 11762 unsigned Heuristic = Subtarget->isThumb() ? 3 : 2; 11763 if (OrCI.countPopulation() > Heuristic) 11764 return SDValue(); 11765 11766 // Lastly, can we determine that the bits defined by OrCI 11767 // are zero in Y? 11768 APInt KnownZero, KnownOne; 11769 computeKnownBits(DAG, Y, KnownZero, KnownOne); 11770 if ((OrCI & KnownZero) != OrCI) 11771 return SDValue(); 11772 11773 // OK, we can do the combine. 11774 SDValue V = Y; 11775 SDLoc dl(X); 11776 EVT VT = X.getValueType(); 11777 unsigned BitInX = AndC->getAPIntValue().logBase2(); 11778 11779 if (BitInX != 0) { 11780 // We must shift X first. 11781 X = DAG.getNode(ISD::SRL, dl, VT, X, 11782 DAG.getConstant(BitInX, dl, VT)); 11783 } 11784 11785 for (unsigned BitInY = 0, NumActiveBits = OrCI.getActiveBits(); 11786 BitInY < NumActiveBits; ++BitInY) { 11787 if (OrCI[BitInY] == 0) 11788 continue; 11789 APInt Mask(VT.getSizeInBits(), 0); 11790 Mask.setBit(BitInY); 11791 V = DAG.getNode(ARMISD::BFI, dl, VT, V, X, 11792 // Confusingly, the operand is an *inverted* mask. 11793 DAG.getConstant(~Mask, dl, VT)); 11794 } 11795 11796 return V; 11797 } 11798 11799 /// PerformBRCONDCombine - Target-specific DAG combining for ARMISD::BRCOND. 11800 SDValue 11801 ARMTargetLowering::PerformBRCONDCombine(SDNode *N, SelectionDAG &DAG) const { 11802 SDValue Cmp = N->getOperand(4); 11803 if (Cmp.getOpcode() != ARMISD::CMPZ) 11804 // Only looking at NE cases. 11805 return SDValue(); 11806 11807 EVT VT = N->getValueType(0); 11808 SDLoc dl(N); 11809 SDValue LHS = Cmp.getOperand(0); 11810 SDValue RHS = Cmp.getOperand(1); 11811 SDValue Chain = N->getOperand(0); 11812 SDValue BB = N->getOperand(1); 11813 SDValue ARMcc = N->getOperand(2); 11814 ARMCC::CondCodes CC = 11815 (ARMCC::CondCodes)cast<ConstantSDNode>(ARMcc)->getZExtValue(); 11816 11817 // (brcond Chain BB ne CPSR (cmpz (and (cmov 0 1 CC CPSR Cmp) 1) 0)) 11818 // -> (brcond Chain BB CC CPSR Cmp) 11819 if (CC == ARMCC::NE && LHS.getOpcode() == ISD::AND && LHS->hasOneUse() && 11820 LHS->getOperand(0)->getOpcode() == ARMISD::CMOV && 11821 LHS->getOperand(0)->hasOneUse()) { 11822 auto *LHS00C = dyn_cast<ConstantSDNode>(LHS->getOperand(0)->getOperand(0)); 11823 auto *LHS01C = dyn_cast<ConstantSDNode>(LHS->getOperand(0)->getOperand(1)); 11824 auto *LHS1C = dyn_cast<ConstantSDNode>(LHS->getOperand(1)); 11825 auto *RHSC = dyn_cast<ConstantSDNode>(RHS); 11826 if ((LHS00C && LHS00C->getZExtValue() == 0) && 11827 (LHS01C && LHS01C->getZExtValue() == 1) && 11828 (LHS1C && LHS1C->getZExtValue() == 1) && 11829 (RHSC && RHSC->getZExtValue() == 0)) { 11830 return DAG.getNode( 11831 ARMISD::BRCOND, dl, VT, Chain, BB, LHS->getOperand(0)->getOperand(2), 11832 LHS->getOperand(0)->getOperand(3), LHS->getOperand(0)->getOperand(4)); 11833 } 11834 } 11835 11836 return SDValue(); 11837 } 11838 11839 /// PerformCMOVCombine - Target-specific DAG combining for ARMISD::CMOV. 11840 SDValue 11841 ARMTargetLowering::PerformCMOVCombine(SDNode *N, SelectionDAG &DAG) const { 11842 SDValue Cmp = N->getOperand(4); 11843 if (Cmp.getOpcode() != ARMISD::CMPZ) 11844 // Only looking at EQ and NE cases. 11845 return SDValue(); 11846 11847 EVT VT = N->getValueType(0); 11848 SDLoc dl(N); 11849 SDValue LHS = Cmp.getOperand(0); 11850 SDValue RHS = Cmp.getOperand(1); 11851 SDValue FalseVal = N->getOperand(0); 11852 SDValue TrueVal = N->getOperand(1); 11853 SDValue ARMcc = N->getOperand(2); 11854 ARMCC::CondCodes CC = 11855 (ARMCC::CondCodes)cast<ConstantSDNode>(ARMcc)->getZExtValue(); 11856 11857 // BFI is only available on V6T2+. 11858 if (!Subtarget->isThumb1Only() && Subtarget->hasV6T2Ops()) { 11859 SDValue R = PerformCMOVToBFICombine(N, DAG); 11860 if (R) 11861 return R; 11862 } 11863 11864 // Simplify 11865 // mov r1, r0 11866 // cmp r1, x 11867 // mov r0, y 11868 // moveq r0, x 11869 // to 11870 // cmp r0, x 11871 // movne r0, y 11872 // 11873 // mov r1, r0 11874 // cmp r1, x 11875 // mov r0, x 11876 // movne r0, y 11877 // to 11878 // cmp r0, x 11879 // movne r0, y 11880 /// FIXME: Turn this into a target neutral optimization? 11881 SDValue Res; 11882 if (CC == ARMCC::NE && FalseVal == RHS && FalseVal != LHS) { 11883 Res = DAG.getNode(ARMISD::CMOV, dl, VT, LHS, TrueVal, ARMcc, 11884 N->getOperand(3), Cmp); 11885 } else if (CC == ARMCC::EQ && TrueVal == RHS) { 11886 SDValue ARMcc; 11887 SDValue NewCmp = getARMCmp(LHS, RHS, ISD::SETNE, ARMcc, DAG, dl); 11888 Res = DAG.getNode(ARMISD::CMOV, dl, VT, LHS, FalseVal, ARMcc, 11889 N->getOperand(3), NewCmp); 11890 } 11891 11892 // (cmov F T ne CPSR (cmpz (cmov 0 1 CC CPSR Cmp) 0)) 11893 // -> (cmov F T CC CPSR Cmp) 11894 if (CC == ARMCC::NE && LHS.getOpcode() == ARMISD::CMOV && LHS->hasOneUse()) { 11895 auto *LHS0C = dyn_cast<ConstantSDNode>(LHS->getOperand(0)); 11896 auto *LHS1C = dyn_cast<ConstantSDNode>(LHS->getOperand(1)); 11897 auto *RHSC = dyn_cast<ConstantSDNode>(RHS); 11898 if ((LHS0C && LHS0C->getZExtValue() == 0) && 11899 (LHS1C && LHS1C->getZExtValue() == 1) && 11900 (RHSC && RHSC->getZExtValue() == 0)) { 11901 return DAG.getNode(ARMISD::CMOV, dl, VT, FalseVal, TrueVal, 11902 LHS->getOperand(2), LHS->getOperand(3), 11903 LHS->getOperand(4)); 11904 } 11905 } 11906 11907 if (Res.getNode()) { 11908 APInt KnownZero, KnownOne; 11909 DAG.computeKnownBits(SDValue(N,0), KnownZero, KnownOne); 11910 // Capture demanded bits information that would be otherwise lost. 11911 if (KnownZero == 0xfffffffe) 11912 Res = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Res, 11913 DAG.getValueType(MVT::i1)); 11914 else if (KnownZero == 0xffffff00) 11915 Res = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Res, 11916 DAG.getValueType(MVT::i8)); 11917 else if (KnownZero == 0xffff0000) 11918 Res = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Res, 11919 DAG.getValueType(MVT::i16)); 11920 } 11921 11922 return Res; 11923 } 11924 11925 SDValue ARMTargetLowering::PerformDAGCombine(SDNode *N, 11926 DAGCombinerInfo &DCI) const { 11927 switch (N->getOpcode()) { 11928 default: break; 11929 case ARMISD::ADDE: return PerformADDECombine(N, DCI, Subtarget); 11930 case ARMISD::UMLAL: return PerformUMLALCombine(N, DCI.DAG, Subtarget); 11931 case ISD::ADD: return PerformADDCombine(N, DCI, Subtarget); 11932 case ISD::SUB: return PerformSUBCombine(N, DCI); 11933 case ISD::MUL: return PerformMULCombine(N, DCI, Subtarget); 11934 case ISD::OR: return PerformORCombine(N, DCI, Subtarget); 11935 case ISD::XOR: return PerformXORCombine(N, DCI, Subtarget); 11936 case ISD::AND: return PerformANDCombine(N, DCI, Subtarget); 11937 case ARMISD::ADDC: 11938 case ARMISD::SUBC: return PerformAddcSubcCombine(N, DCI.DAG, Subtarget); 11939 case ARMISD::SUBE: return PerformAddeSubeCombine(N, DCI.DAG, Subtarget); 11940 case ARMISD::BFI: return PerformBFICombine(N, DCI); 11941 case ARMISD::VMOVRRD: return PerformVMOVRRDCombine(N, DCI, Subtarget); 11942 case ARMISD::VMOVDRR: return PerformVMOVDRRCombine(N, DCI.DAG); 11943 case ISD::STORE: return PerformSTORECombine(N, DCI); 11944 case ISD::BUILD_VECTOR: return PerformBUILD_VECTORCombine(N, DCI, Subtarget); 11945 case ISD::INSERT_VECTOR_ELT: return PerformInsertEltCombine(N, DCI); 11946 case ISD::VECTOR_SHUFFLE: return PerformVECTOR_SHUFFLECombine(N, DCI.DAG); 11947 case ARMISD::VDUPLANE: return PerformVDUPLANECombine(N, DCI); 11948 case ARMISD::VDUP: return PerformVDUPCombine(N, DCI); 11949 case ISD::FP_TO_SINT: 11950 case ISD::FP_TO_UINT: 11951 return PerformVCVTCombine(N, DCI.DAG, Subtarget); 11952 case ISD::FDIV: 11953 return PerformVDIVCombine(N, DCI.DAG, Subtarget); 11954 case ISD::INTRINSIC_WO_CHAIN: return PerformIntrinsicCombine(N, DCI.DAG); 11955 case ISD::SHL: 11956 case ISD::SRA: 11957 case ISD::SRL: return PerformShiftCombine(N, DCI.DAG, Subtarget); 11958 case ISD::SIGN_EXTEND: 11959 case ISD::ZERO_EXTEND: 11960 case ISD::ANY_EXTEND: return PerformExtendCombine(N, DCI.DAG, Subtarget); 11961 case ARMISD::CMOV: return PerformCMOVCombine(N, DCI.DAG); 11962 case ARMISD::BRCOND: return PerformBRCONDCombine(N, DCI.DAG); 11963 case ISD::LOAD: return PerformLOADCombine(N, DCI); 11964 case ARMISD::VLD1DUP: 11965 case ARMISD::VLD2DUP: 11966 case ARMISD::VLD3DUP: 11967 case ARMISD::VLD4DUP: 11968 return PerformVLDCombine(N, DCI); 11969 case ARMISD::BUILD_VECTOR: 11970 return PerformARMBUILD_VECTORCombine(N, DCI); 11971 case ARMISD::SMULWB: { 11972 unsigned BitWidth = N->getValueType(0).getSizeInBits(); 11973 APInt DemandedMask = APInt::getLowBitsSet(BitWidth, 16); 11974 if (SimplifyDemandedBits(N->getOperand(1), DemandedMask, DCI)) 11975 return SDValue(); 11976 break; 11977 } 11978 case ARMISD::SMULWT: { 11979 unsigned BitWidth = N->getValueType(0).getSizeInBits(); 11980 APInt DemandedMask = APInt::getHighBitsSet(BitWidth, 16); 11981 if (SimplifyDemandedBits(N->getOperand(1), DemandedMask, DCI)) 11982 return SDValue(); 11983 break; 11984 } 11985 case ARMISD::SMLALBB: { 11986 unsigned BitWidth = N->getValueType(0).getSizeInBits(); 11987 APInt DemandedMask = APInt::getLowBitsSet(BitWidth, 16); 11988 if ((SimplifyDemandedBits(N->getOperand(0), DemandedMask, DCI)) || 11989 (SimplifyDemandedBits(N->getOperand(1), DemandedMask, DCI))) 11990 return SDValue(); 11991 break; 11992 } 11993 case ARMISD::SMLALBT: { 11994 unsigned LowWidth = N->getOperand(0).getValueType().getSizeInBits(); 11995 APInt LowMask = APInt::getLowBitsSet(LowWidth, 16); 11996 unsigned HighWidth = N->getOperand(1).getValueType().getSizeInBits(); 11997 APInt HighMask = APInt::getHighBitsSet(HighWidth, 16); 11998 if ((SimplifyDemandedBits(N->getOperand(0), LowMask, DCI)) || 11999 (SimplifyDemandedBits(N->getOperand(1), HighMask, DCI))) 12000 return SDValue(); 12001 break; 12002 } 12003 case ARMISD::SMLALTB: { 12004 unsigned HighWidth = N->getOperand(0).getValueType().getSizeInBits(); 12005 APInt HighMask = APInt::getHighBitsSet(HighWidth, 16); 12006 unsigned LowWidth = N->getOperand(1).getValueType().getSizeInBits(); 12007 APInt LowMask = APInt::getLowBitsSet(LowWidth, 16); 12008 if ((SimplifyDemandedBits(N->getOperand(0), HighMask, DCI)) || 12009 (SimplifyDemandedBits(N->getOperand(1), LowMask, DCI))) 12010 return SDValue(); 12011 break; 12012 } 12013 case ARMISD::SMLALTT: { 12014 unsigned BitWidth = N->getValueType(0).getSizeInBits(); 12015 APInt DemandedMask = APInt::getHighBitsSet(BitWidth, 16); 12016 if ((SimplifyDemandedBits(N->getOperand(0), DemandedMask, DCI)) || 12017 (SimplifyDemandedBits(N->getOperand(1), DemandedMask, DCI))) 12018 return SDValue(); 12019 break; 12020 } 12021 case ISD::INTRINSIC_VOID: 12022 case ISD::INTRINSIC_W_CHAIN: 12023 switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) { 12024 case Intrinsic::arm_neon_vld1: 12025 case Intrinsic::arm_neon_vld2: 12026 case Intrinsic::arm_neon_vld3: 12027 case Intrinsic::arm_neon_vld4: 12028 case Intrinsic::arm_neon_vld2lane: 12029 case Intrinsic::arm_neon_vld3lane: 12030 case Intrinsic::arm_neon_vld4lane: 12031 case Intrinsic::arm_neon_vst1: 12032 case Intrinsic::arm_neon_vst2: 12033 case Intrinsic::arm_neon_vst3: 12034 case Intrinsic::arm_neon_vst4: 12035 case Intrinsic::arm_neon_vst2lane: 12036 case Intrinsic::arm_neon_vst3lane: 12037 case Intrinsic::arm_neon_vst4lane: 12038 return PerformVLDCombine(N, DCI); 12039 default: break; 12040 } 12041 break; 12042 } 12043 return SDValue(); 12044 } 12045 12046 bool ARMTargetLowering::isDesirableToTransformToIntegerOp(unsigned Opc, 12047 EVT VT) const { 12048 return (VT == MVT::f32) && (Opc == ISD::LOAD || Opc == ISD::STORE); 12049 } 12050 12051 bool ARMTargetLowering::allowsMisalignedMemoryAccesses(EVT VT, 12052 unsigned, 12053 unsigned, 12054 bool *Fast) const { 12055 // The AllowsUnaliged flag models the SCTLR.A setting in ARM cpus 12056 bool AllowsUnaligned = Subtarget->allowsUnalignedMem(); 12057 12058 switch (VT.getSimpleVT().SimpleTy) { 12059 default: 12060 return false; 12061 case MVT::i8: 12062 case MVT::i16: 12063 case MVT::i32: { 12064 // Unaligned access can use (for example) LRDB, LRDH, LDR 12065 if (AllowsUnaligned) { 12066 if (Fast) 12067 *Fast = Subtarget->hasV7Ops(); 12068 return true; 12069 } 12070 return false; 12071 } 12072 case MVT::f64: 12073 case MVT::v2f64: { 12074 // For any little-endian targets with neon, we can support unaligned ld/st 12075 // of D and Q (e.g. {D0,D1}) registers by using vld1.i8/vst1.i8. 12076 // A big-endian target may also explicitly support unaligned accesses 12077 if (Subtarget->hasNEON() && (AllowsUnaligned || Subtarget->isLittle())) { 12078 if (Fast) 12079 *Fast = true; 12080 return true; 12081 } 12082 return false; 12083 } 12084 } 12085 } 12086 12087 static bool memOpAlign(unsigned DstAlign, unsigned SrcAlign, 12088 unsigned AlignCheck) { 12089 return ((SrcAlign == 0 || SrcAlign % AlignCheck == 0) && 12090 (DstAlign == 0 || DstAlign % AlignCheck == 0)); 12091 } 12092 12093 EVT ARMTargetLowering::getOptimalMemOpType(uint64_t Size, 12094 unsigned DstAlign, unsigned SrcAlign, 12095 bool IsMemset, bool ZeroMemset, 12096 bool MemcpyStrSrc, 12097 MachineFunction &MF) const { 12098 const Function *F = MF.getFunction(); 12099 12100 // See if we can use NEON instructions for this... 12101 if ((!IsMemset || ZeroMemset) && Subtarget->hasNEON() && 12102 !F->hasFnAttribute(Attribute::NoImplicitFloat)) { 12103 bool Fast; 12104 if (Size >= 16 && 12105 (memOpAlign(SrcAlign, DstAlign, 16) || 12106 (allowsMisalignedMemoryAccesses(MVT::v2f64, 0, 1, &Fast) && Fast))) { 12107 return MVT::v2f64; 12108 } else if (Size >= 8 && 12109 (memOpAlign(SrcAlign, DstAlign, 8) || 12110 (allowsMisalignedMemoryAccesses(MVT::f64, 0, 1, &Fast) && 12111 Fast))) { 12112 return MVT::f64; 12113 } 12114 } 12115 12116 // Lowering to i32/i16 if the size permits. 12117 if (Size >= 4) 12118 return MVT::i32; 12119 else if (Size >= 2) 12120 return MVT::i16; 12121 12122 // Let the target-independent logic figure it out. 12123 return MVT::Other; 12124 } 12125 12126 bool ARMTargetLowering::isZExtFree(SDValue Val, EVT VT2) const { 12127 if (Val.getOpcode() != ISD::LOAD) 12128 return false; 12129 12130 EVT VT1 = Val.getValueType(); 12131 if (!VT1.isSimple() || !VT1.isInteger() || 12132 !VT2.isSimple() || !VT2.isInteger()) 12133 return false; 12134 12135 switch (VT1.getSimpleVT().SimpleTy) { 12136 default: break; 12137 case MVT::i1: 12138 case MVT::i8: 12139 case MVT::i16: 12140 // 8-bit and 16-bit loads implicitly zero-extend to 32-bits. 12141 return true; 12142 } 12143 12144 return false; 12145 } 12146 12147 bool ARMTargetLowering::isVectorLoadExtDesirable(SDValue ExtVal) const { 12148 EVT VT = ExtVal.getValueType(); 12149 12150 if (!isTypeLegal(VT)) 12151 return false; 12152 12153 // Don't create a loadext if we can fold the extension into a wide/long 12154 // instruction. 12155 // If there's more than one user instruction, the loadext is desirable no 12156 // matter what. There can be two uses by the same instruction. 12157 if (ExtVal->use_empty() || 12158 !ExtVal->use_begin()->isOnlyUserOf(ExtVal.getNode())) 12159 return true; 12160 12161 SDNode *U = *ExtVal->use_begin(); 12162 if ((U->getOpcode() == ISD::ADD || U->getOpcode() == ISD::SUB || 12163 U->getOpcode() == ISD::SHL || U->getOpcode() == ARMISD::VSHL)) 12164 return false; 12165 12166 return true; 12167 } 12168 12169 bool ARMTargetLowering::allowTruncateForTailCall(Type *Ty1, Type *Ty2) const { 12170 if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy()) 12171 return false; 12172 12173 if (!isTypeLegal(EVT::getEVT(Ty1))) 12174 return false; 12175 12176 assert(Ty1->getPrimitiveSizeInBits() <= 64 && "i128 is probably not a noop"); 12177 12178 // Assuming the caller doesn't have a zeroext or signext return parameter, 12179 // truncation all the way down to i1 is valid. 12180 return true; 12181 } 12182 12183 int ARMTargetLowering::getScalingFactorCost(const DataLayout &DL, 12184 const AddrMode &AM, Type *Ty, 12185 unsigned AS) const { 12186 if (isLegalAddressingMode(DL, AM, Ty, AS)) { 12187 if (Subtarget->hasFPAO()) 12188 return AM.Scale < 0 ? 1 : 0; // positive offsets execute faster 12189 return 0; 12190 } 12191 return -1; 12192 } 12193 12194 12195 static bool isLegalT1AddressImmediate(int64_t V, EVT VT) { 12196 if (V < 0) 12197 return false; 12198 12199 unsigned Scale = 1; 12200 switch (VT.getSimpleVT().SimpleTy) { 12201 default: return false; 12202 case MVT::i1: 12203 case MVT::i8: 12204 // Scale == 1; 12205 break; 12206 case MVT::i16: 12207 // Scale == 2; 12208 Scale = 2; 12209 break; 12210 case MVT::i32: 12211 // Scale == 4; 12212 Scale = 4; 12213 break; 12214 } 12215 12216 if ((V & (Scale - 1)) != 0) 12217 return false; 12218 V /= Scale; 12219 return V == (V & ((1LL << 5) - 1)); 12220 } 12221 12222 static bool isLegalT2AddressImmediate(int64_t V, EVT VT, 12223 const ARMSubtarget *Subtarget) { 12224 bool isNeg = false; 12225 if (V < 0) { 12226 isNeg = true; 12227 V = - V; 12228 } 12229 12230 switch (VT.getSimpleVT().SimpleTy) { 12231 default: return false; 12232 case MVT::i1: 12233 case MVT::i8: 12234 case MVT::i16: 12235 case MVT::i32: 12236 // + imm12 or - imm8 12237 if (isNeg) 12238 return V == (V & ((1LL << 8) - 1)); 12239 return V == (V & ((1LL << 12) - 1)); 12240 case MVT::f32: 12241 case MVT::f64: 12242 // Same as ARM mode. FIXME: NEON? 12243 if (!Subtarget->hasVFP2()) 12244 return false; 12245 if ((V & 3) != 0) 12246 return false; 12247 V >>= 2; 12248 return V == (V & ((1LL << 8) - 1)); 12249 } 12250 } 12251 12252 /// isLegalAddressImmediate - Return true if the integer value can be used 12253 /// as the offset of the target addressing mode for load / store of the 12254 /// given type. 12255 static bool isLegalAddressImmediate(int64_t V, EVT VT, 12256 const ARMSubtarget *Subtarget) { 12257 if (V == 0) 12258 return true; 12259 12260 if (!VT.isSimple()) 12261 return false; 12262 12263 if (Subtarget->isThumb1Only()) 12264 return isLegalT1AddressImmediate(V, VT); 12265 else if (Subtarget->isThumb2()) 12266 return isLegalT2AddressImmediate(V, VT, Subtarget); 12267 12268 // ARM mode. 12269 if (V < 0) 12270 V = - V; 12271 switch (VT.getSimpleVT().SimpleTy) { 12272 default: return false; 12273 case MVT::i1: 12274 case MVT::i8: 12275 case MVT::i32: 12276 // +- imm12 12277 return V == (V & ((1LL << 12) - 1)); 12278 case MVT::i16: 12279 // +- imm8 12280 return V == (V & ((1LL << 8) - 1)); 12281 case MVT::f32: 12282 case MVT::f64: 12283 if (!Subtarget->hasVFP2()) // FIXME: NEON? 12284 return false; 12285 if ((V & 3) != 0) 12286 return false; 12287 V >>= 2; 12288 return V == (V & ((1LL << 8) - 1)); 12289 } 12290 } 12291 12292 bool ARMTargetLowering::isLegalT2ScaledAddressingMode(const AddrMode &AM, 12293 EVT VT) const { 12294 int Scale = AM.Scale; 12295 if (Scale < 0) 12296 return false; 12297 12298 switch (VT.getSimpleVT().SimpleTy) { 12299 default: return false; 12300 case MVT::i1: 12301 case MVT::i8: 12302 case MVT::i16: 12303 case MVT::i32: 12304 if (Scale == 1) 12305 return true; 12306 // r + r << imm 12307 Scale = Scale & ~1; 12308 return Scale == 2 || Scale == 4 || Scale == 8; 12309 case MVT::i64: 12310 // r + r 12311 if (((unsigned)AM.HasBaseReg + Scale) <= 2) 12312 return true; 12313 return false; 12314 case MVT::isVoid: 12315 // Note, we allow "void" uses (basically, uses that aren't loads or 12316 // stores), because arm allows folding a scale into many arithmetic 12317 // operations. This should be made more precise and revisited later. 12318 12319 // Allow r << imm, but the imm has to be a multiple of two. 12320 if (Scale & 1) return false; 12321 return isPowerOf2_32(Scale); 12322 } 12323 } 12324 12325 /// isLegalAddressingMode - Return true if the addressing mode represented 12326 /// by AM is legal for this target, for a load/store of the specified type. 12327 bool ARMTargetLowering::isLegalAddressingMode(const DataLayout &DL, 12328 const AddrMode &AM, Type *Ty, 12329 unsigned AS) const { 12330 EVT VT = getValueType(DL, Ty, true); 12331 if (!isLegalAddressImmediate(AM.BaseOffs, VT, Subtarget)) 12332 return false; 12333 12334 // Can never fold addr of global into load/store. 12335 if (AM.BaseGV) 12336 return false; 12337 12338 switch (AM.Scale) { 12339 case 0: // no scale reg, must be "r+i" or "r", or "i". 12340 break; 12341 case 1: 12342 if (Subtarget->isThumb1Only()) 12343 return false; 12344 LLVM_FALLTHROUGH; 12345 default: 12346 // ARM doesn't support any R+R*scale+imm addr modes. 12347 if (AM.BaseOffs) 12348 return false; 12349 12350 if (!VT.isSimple()) 12351 return false; 12352 12353 if (Subtarget->isThumb2()) 12354 return isLegalT2ScaledAddressingMode(AM, VT); 12355 12356 int Scale = AM.Scale; 12357 switch (VT.getSimpleVT().SimpleTy) { 12358 default: return false; 12359 case MVT::i1: 12360 case MVT::i8: 12361 case MVT::i32: 12362 if (Scale < 0) Scale = -Scale; 12363 if (Scale == 1) 12364 return true; 12365 // r + r << imm 12366 return isPowerOf2_32(Scale & ~1); 12367 case MVT::i16: 12368 case MVT::i64: 12369 // r + r 12370 if (((unsigned)AM.HasBaseReg + Scale) <= 2) 12371 return true; 12372 return false; 12373 12374 case MVT::isVoid: 12375 // Note, we allow "void" uses (basically, uses that aren't loads or 12376 // stores), because arm allows folding a scale into many arithmetic 12377 // operations. This should be made more precise and revisited later. 12378 12379 // Allow r << imm, but the imm has to be a multiple of two. 12380 if (Scale & 1) return false; 12381 return isPowerOf2_32(Scale); 12382 } 12383 } 12384 return true; 12385 } 12386 12387 /// isLegalICmpImmediate - Return true if the specified immediate is legal 12388 /// icmp immediate, that is the target has icmp instructions which can compare 12389 /// a register against the immediate without having to materialize the 12390 /// immediate into a register. 12391 bool ARMTargetLowering::isLegalICmpImmediate(int64_t Imm) const { 12392 // Thumb2 and ARM modes can use cmn for negative immediates. 12393 if (!Subtarget->isThumb()) 12394 return ARM_AM::getSOImmVal(std::abs(Imm)) != -1; 12395 if (Subtarget->isThumb2()) 12396 return ARM_AM::getT2SOImmVal(std::abs(Imm)) != -1; 12397 // Thumb1 doesn't have cmn, and only 8-bit immediates. 12398 return Imm >= 0 && Imm <= 255; 12399 } 12400 12401 /// isLegalAddImmediate - Return true if the specified immediate is a legal add 12402 /// *or sub* immediate, that is the target has add or sub instructions which can 12403 /// add a register with the immediate without having to materialize the 12404 /// immediate into a register. 12405 bool ARMTargetLowering::isLegalAddImmediate(int64_t Imm) const { 12406 // Same encoding for add/sub, just flip the sign. 12407 int64_t AbsImm = std::abs(Imm); 12408 if (!Subtarget->isThumb()) 12409 return ARM_AM::getSOImmVal(AbsImm) != -1; 12410 if (Subtarget->isThumb2()) 12411 return ARM_AM::getT2SOImmVal(AbsImm) != -1; 12412 // Thumb1 only has 8-bit unsigned immediate. 12413 return AbsImm >= 0 && AbsImm <= 255; 12414 } 12415 12416 static bool getARMIndexedAddressParts(SDNode *Ptr, EVT VT, 12417 bool isSEXTLoad, SDValue &Base, 12418 SDValue &Offset, bool &isInc, 12419 SelectionDAG &DAG) { 12420 if (Ptr->getOpcode() != ISD::ADD && Ptr->getOpcode() != ISD::SUB) 12421 return false; 12422 12423 if (VT == MVT::i16 || ((VT == MVT::i8 || VT == MVT::i1) && isSEXTLoad)) { 12424 // AddressingMode 3 12425 Base = Ptr->getOperand(0); 12426 if (ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(Ptr->getOperand(1))) { 12427 int RHSC = (int)RHS->getZExtValue(); 12428 if (RHSC < 0 && RHSC > -256) { 12429 assert(Ptr->getOpcode() == ISD::ADD); 12430 isInc = false; 12431 Offset = DAG.getConstant(-RHSC, SDLoc(Ptr), RHS->getValueType(0)); 12432 return true; 12433 } 12434 } 12435 isInc = (Ptr->getOpcode() == ISD::ADD); 12436 Offset = Ptr->getOperand(1); 12437 return true; 12438 } else if (VT == MVT::i32 || VT == MVT::i8 || VT == MVT::i1) { 12439 // AddressingMode 2 12440 if (ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(Ptr->getOperand(1))) { 12441 int RHSC = (int)RHS->getZExtValue(); 12442 if (RHSC < 0 && RHSC > -0x1000) { 12443 assert(Ptr->getOpcode() == ISD::ADD); 12444 isInc = false; 12445 Offset = DAG.getConstant(-RHSC, SDLoc(Ptr), RHS->getValueType(0)); 12446 Base = Ptr->getOperand(0); 12447 return true; 12448 } 12449 } 12450 12451 if (Ptr->getOpcode() == ISD::ADD) { 12452 isInc = true; 12453 ARM_AM::ShiftOpc ShOpcVal= 12454 ARM_AM::getShiftOpcForNode(Ptr->getOperand(0).getOpcode()); 12455 if (ShOpcVal != ARM_AM::no_shift) { 12456 Base = Ptr->getOperand(1); 12457 Offset = Ptr->getOperand(0); 12458 } else { 12459 Base = Ptr->getOperand(0); 12460 Offset = Ptr->getOperand(1); 12461 } 12462 return true; 12463 } 12464 12465 isInc = (Ptr->getOpcode() == ISD::ADD); 12466 Base = Ptr->getOperand(0); 12467 Offset = Ptr->getOperand(1); 12468 return true; 12469 } 12470 12471 // FIXME: Use VLDM / VSTM to emulate indexed FP load / store. 12472 return false; 12473 } 12474 12475 static bool getT2IndexedAddressParts(SDNode *Ptr, EVT VT, 12476 bool isSEXTLoad, SDValue &Base, 12477 SDValue &Offset, bool &isInc, 12478 SelectionDAG &DAG) { 12479 if (Ptr->getOpcode() != ISD::ADD && Ptr->getOpcode() != ISD::SUB) 12480 return false; 12481 12482 Base = Ptr->getOperand(0); 12483 if (ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(Ptr->getOperand(1))) { 12484 int RHSC = (int)RHS->getZExtValue(); 12485 if (RHSC < 0 && RHSC > -0x100) { // 8 bits. 12486 assert(Ptr->getOpcode() == ISD::ADD); 12487 isInc = false; 12488 Offset = DAG.getConstant(-RHSC, SDLoc(Ptr), RHS->getValueType(0)); 12489 return true; 12490 } else if (RHSC > 0 && RHSC < 0x100) { // 8 bit, no zero. 12491 isInc = Ptr->getOpcode() == ISD::ADD; 12492 Offset = DAG.getConstant(RHSC, SDLoc(Ptr), RHS->getValueType(0)); 12493 return true; 12494 } 12495 } 12496 12497 return false; 12498 } 12499 12500 /// getPreIndexedAddressParts - returns true by value, base pointer and 12501 /// offset pointer and addressing mode by reference if the node's address 12502 /// can be legally represented as pre-indexed load / store address. 12503 bool 12504 ARMTargetLowering::getPreIndexedAddressParts(SDNode *N, SDValue &Base, 12505 SDValue &Offset, 12506 ISD::MemIndexedMode &AM, 12507 SelectionDAG &DAG) const { 12508 if (Subtarget->isThumb1Only()) 12509 return false; 12510 12511 EVT VT; 12512 SDValue Ptr; 12513 bool isSEXTLoad = false; 12514 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) { 12515 Ptr = LD->getBasePtr(); 12516 VT = LD->getMemoryVT(); 12517 isSEXTLoad = LD->getExtensionType() == ISD::SEXTLOAD; 12518 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) { 12519 Ptr = ST->getBasePtr(); 12520 VT = ST->getMemoryVT(); 12521 } else 12522 return false; 12523 12524 bool isInc; 12525 bool isLegal = false; 12526 if (Subtarget->isThumb2()) 12527 isLegal = getT2IndexedAddressParts(Ptr.getNode(), VT, isSEXTLoad, Base, 12528 Offset, isInc, DAG); 12529 else 12530 isLegal = getARMIndexedAddressParts(Ptr.getNode(), VT, isSEXTLoad, Base, 12531 Offset, isInc, DAG); 12532 if (!isLegal) 12533 return false; 12534 12535 AM = isInc ? ISD::PRE_INC : ISD::PRE_DEC; 12536 return true; 12537 } 12538 12539 /// getPostIndexedAddressParts - returns true by value, base pointer and 12540 /// offset pointer and addressing mode by reference if this node can be 12541 /// combined with a load / store to form a post-indexed load / store. 12542 bool ARMTargetLowering::getPostIndexedAddressParts(SDNode *N, SDNode *Op, 12543 SDValue &Base, 12544 SDValue &Offset, 12545 ISD::MemIndexedMode &AM, 12546 SelectionDAG &DAG) const { 12547 EVT VT; 12548 SDValue Ptr; 12549 bool isSEXTLoad = false, isNonExt; 12550 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) { 12551 VT = LD->getMemoryVT(); 12552 Ptr = LD->getBasePtr(); 12553 isSEXTLoad = LD->getExtensionType() == ISD::SEXTLOAD; 12554 isNonExt = LD->getExtensionType() == ISD::NON_EXTLOAD; 12555 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) { 12556 VT = ST->getMemoryVT(); 12557 Ptr = ST->getBasePtr(); 12558 isNonExt = !ST->isTruncatingStore(); 12559 } else 12560 return false; 12561 12562 if (Subtarget->isThumb1Only()) { 12563 // Thumb-1 can do a limited post-inc load or store as an updating LDM. It 12564 // must be non-extending/truncating, i32, with an offset of 4. 12565 assert(Op->getValueType(0) == MVT::i32 && "Non-i32 post-inc op?!"); 12566 if (Op->getOpcode() != ISD::ADD || !isNonExt) 12567 return false; 12568 auto *RHS = dyn_cast<ConstantSDNode>(Op->getOperand(1)); 12569 if (!RHS || RHS->getZExtValue() != 4) 12570 return false; 12571 12572 Offset = Op->getOperand(1); 12573 Base = Op->getOperand(0); 12574 AM = ISD::POST_INC; 12575 return true; 12576 } 12577 12578 bool isInc; 12579 bool isLegal = false; 12580 if (Subtarget->isThumb2()) 12581 isLegal = getT2IndexedAddressParts(Op, VT, isSEXTLoad, Base, Offset, 12582 isInc, DAG); 12583 else 12584 isLegal = getARMIndexedAddressParts(Op, VT, isSEXTLoad, Base, Offset, 12585 isInc, DAG); 12586 if (!isLegal) 12587 return false; 12588 12589 if (Ptr != Base) { 12590 // Swap base ptr and offset to catch more post-index load / store when 12591 // it's legal. In Thumb2 mode, offset must be an immediate. 12592 if (Ptr == Offset && Op->getOpcode() == ISD::ADD && 12593 !Subtarget->isThumb2()) 12594 std::swap(Base, Offset); 12595 12596 // Post-indexed load / store update the base pointer. 12597 if (Ptr != Base) 12598 return false; 12599 } 12600 12601 AM = isInc ? ISD::POST_INC : ISD::POST_DEC; 12602 return true; 12603 } 12604 12605 void ARMTargetLowering::computeKnownBitsForTargetNode(const SDValue Op, 12606 APInt &KnownZero, 12607 APInt &KnownOne, 12608 const APInt &DemandedElts, 12609 const SelectionDAG &DAG, 12610 unsigned Depth) const { 12611 unsigned BitWidth = KnownOne.getBitWidth(); 12612 KnownZero = KnownOne = APInt(BitWidth, 0); 12613 switch (Op.getOpcode()) { 12614 default: break; 12615 case ARMISD::ADDC: 12616 case ARMISD::ADDE: 12617 case ARMISD::SUBC: 12618 case ARMISD::SUBE: 12619 // These nodes' second result is a boolean 12620 if (Op.getResNo() == 0) 12621 break; 12622 KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - 1); 12623 break; 12624 case ARMISD::CMOV: { 12625 // Bits are known zero/one if known on the LHS and RHS. 12626 DAG.computeKnownBits(Op.getOperand(0), KnownZero, KnownOne, Depth+1); 12627 if (KnownZero == 0 && KnownOne == 0) return; 12628 12629 APInt KnownZeroRHS, KnownOneRHS; 12630 DAG.computeKnownBits(Op.getOperand(1), KnownZeroRHS, KnownOneRHS, Depth+1); 12631 KnownZero &= KnownZeroRHS; 12632 KnownOne &= KnownOneRHS; 12633 return; 12634 } 12635 case ISD::INTRINSIC_W_CHAIN: { 12636 ConstantSDNode *CN = cast<ConstantSDNode>(Op->getOperand(1)); 12637 Intrinsic::ID IntID = static_cast<Intrinsic::ID>(CN->getZExtValue()); 12638 switch (IntID) { 12639 default: return; 12640 case Intrinsic::arm_ldaex: 12641 case Intrinsic::arm_ldrex: { 12642 EVT VT = cast<MemIntrinsicSDNode>(Op)->getMemoryVT(); 12643 unsigned MemBits = VT.getScalarSizeInBits(); 12644 KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - MemBits); 12645 return; 12646 } 12647 } 12648 } 12649 } 12650 } 12651 12652 //===----------------------------------------------------------------------===// 12653 // ARM Inline Assembly Support 12654 //===----------------------------------------------------------------------===// 12655 12656 bool ARMTargetLowering::ExpandInlineAsm(CallInst *CI) const { 12657 // Looking for "rev" which is V6+. 12658 if (!Subtarget->hasV6Ops()) 12659 return false; 12660 12661 InlineAsm *IA = cast<InlineAsm>(CI->getCalledValue()); 12662 std::string AsmStr = IA->getAsmString(); 12663 SmallVector<StringRef, 4> AsmPieces; 12664 SplitString(AsmStr, AsmPieces, ";\n"); 12665 12666 switch (AsmPieces.size()) { 12667 default: return false; 12668 case 1: 12669 AsmStr = AsmPieces[0]; 12670 AsmPieces.clear(); 12671 SplitString(AsmStr, AsmPieces, " \t,"); 12672 12673 // rev $0, $1 12674 if (AsmPieces.size() == 3 && 12675 AsmPieces[0] == "rev" && AsmPieces[1] == "$0" && AsmPieces[2] == "$1" && 12676 IA->getConstraintString().compare(0, 4, "=l,l") == 0) { 12677 IntegerType *Ty = dyn_cast<IntegerType>(CI->getType()); 12678 if (Ty && Ty->getBitWidth() == 32) 12679 return IntrinsicLowering::LowerToByteSwap(CI); 12680 } 12681 break; 12682 } 12683 12684 return false; 12685 } 12686 12687 const char *ARMTargetLowering::LowerXConstraint(EVT ConstraintVT) const { 12688 // At this point, we have to lower this constraint to something else, so we 12689 // lower it to an "r" or "w". However, by doing this we will force the result 12690 // to be in register, while the X constraint is much more permissive. 12691 // 12692 // Although we are correct (we are free to emit anything, without 12693 // constraints), we might break use cases that would expect us to be more 12694 // efficient and emit something else. 12695 if (!Subtarget->hasVFP2()) 12696 return "r"; 12697 if (ConstraintVT.isFloatingPoint()) 12698 return "w"; 12699 if (ConstraintVT.isVector() && Subtarget->hasNEON() && 12700 (ConstraintVT.getSizeInBits() == 64 || 12701 ConstraintVT.getSizeInBits() == 128)) 12702 return "w"; 12703 12704 return "r"; 12705 } 12706 12707 /// getConstraintType - Given a constraint letter, return the type of 12708 /// constraint it is for this target. 12709 ARMTargetLowering::ConstraintType 12710 ARMTargetLowering::getConstraintType(StringRef Constraint) const { 12711 if (Constraint.size() == 1) { 12712 switch (Constraint[0]) { 12713 default: break; 12714 case 'l': return C_RegisterClass; 12715 case 'w': return C_RegisterClass; 12716 case 'h': return C_RegisterClass; 12717 case 'x': return C_RegisterClass; 12718 case 't': return C_RegisterClass; 12719 case 'j': return C_Other; // Constant for movw. 12720 // An address with a single base register. Due to the way we 12721 // currently handle addresses it is the same as an 'r' memory constraint. 12722 case 'Q': return C_Memory; 12723 } 12724 } else if (Constraint.size() == 2) { 12725 switch (Constraint[0]) { 12726 default: break; 12727 // All 'U+' constraints are addresses. 12728 case 'U': return C_Memory; 12729 } 12730 } 12731 return TargetLowering::getConstraintType(Constraint); 12732 } 12733 12734 /// Examine constraint type and operand type and determine a weight value. 12735 /// This object must already have been set up with the operand type 12736 /// and the current alternative constraint selected. 12737 TargetLowering::ConstraintWeight 12738 ARMTargetLowering::getSingleConstraintMatchWeight( 12739 AsmOperandInfo &info, const char *constraint) const { 12740 ConstraintWeight weight = CW_Invalid; 12741 Value *CallOperandVal = info.CallOperandVal; 12742 // If we don't have a value, we can't do a match, 12743 // but allow it at the lowest weight. 12744 if (!CallOperandVal) 12745 return CW_Default; 12746 Type *type = CallOperandVal->getType(); 12747 // Look at the constraint type. 12748 switch (*constraint) { 12749 default: 12750 weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint); 12751 break; 12752 case 'l': 12753 if (type->isIntegerTy()) { 12754 if (Subtarget->isThumb()) 12755 weight = CW_SpecificReg; 12756 else 12757 weight = CW_Register; 12758 } 12759 break; 12760 case 'w': 12761 if (type->isFloatingPointTy()) 12762 weight = CW_Register; 12763 break; 12764 } 12765 return weight; 12766 } 12767 12768 typedef std::pair<unsigned, const TargetRegisterClass*> RCPair; 12769 RCPair ARMTargetLowering::getRegForInlineAsmConstraint( 12770 const TargetRegisterInfo *TRI, StringRef Constraint, MVT VT) const { 12771 if (Constraint.size() == 1) { 12772 // GCC ARM Constraint Letters 12773 switch (Constraint[0]) { 12774 case 'l': // Low regs or general regs. 12775 if (Subtarget->isThumb()) 12776 return RCPair(0U, &ARM::tGPRRegClass); 12777 return RCPair(0U, &ARM::GPRRegClass); 12778 case 'h': // High regs or no regs. 12779 if (Subtarget->isThumb()) 12780 return RCPair(0U, &ARM::hGPRRegClass); 12781 break; 12782 case 'r': 12783 if (Subtarget->isThumb1Only()) 12784 return RCPair(0U, &ARM::tGPRRegClass); 12785 return RCPair(0U, &ARM::GPRRegClass); 12786 case 'w': 12787 if (VT == MVT::Other) 12788 break; 12789 if (VT == MVT::f32) 12790 return RCPair(0U, &ARM::SPRRegClass); 12791 if (VT.getSizeInBits() == 64) 12792 return RCPair(0U, &ARM::DPRRegClass); 12793 if (VT.getSizeInBits() == 128) 12794 return RCPair(0U, &ARM::QPRRegClass); 12795 break; 12796 case 'x': 12797 if (VT == MVT::Other) 12798 break; 12799 if (VT == MVT::f32) 12800 return RCPair(0U, &ARM::SPR_8RegClass); 12801 if (VT.getSizeInBits() == 64) 12802 return RCPair(0U, &ARM::DPR_8RegClass); 12803 if (VT.getSizeInBits() == 128) 12804 return RCPair(0U, &ARM::QPR_8RegClass); 12805 break; 12806 case 't': 12807 if (VT == MVT::f32) 12808 return RCPair(0U, &ARM::SPRRegClass); 12809 break; 12810 } 12811 } 12812 if (StringRef("{cc}").equals_lower(Constraint)) 12813 return std::make_pair(unsigned(ARM::CPSR), &ARM::CCRRegClass); 12814 12815 return TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT); 12816 } 12817 12818 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops 12819 /// vector. If it is invalid, don't add anything to Ops. 12820 void ARMTargetLowering::LowerAsmOperandForConstraint(SDValue Op, 12821 std::string &Constraint, 12822 std::vector<SDValue>&Ops, 12823 SelectionDAG &DAG) const { 12824 SDValue Result; 12825 12826 // Currently only support length 1 constraints. 12827 if (Constraint.length() != 1) return; 12828 12829 char ConstraintLetter = Constraint[0]; 12830 switch (ConstraintLetter) { 12831 default: break; 12832 case 'j': 12833 case 'I': case 'J': case 'K': case 'L': 12834 case 'M': case 'N': case 'O': 12835 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op); 12836 if (!C) 12837 return; 12838 12839 int64_t CVal64 = C->getSExtValue(); 12840 int CVal = (int) CVal64; 12841 // None of these constraints allow values larger than 32 bits. Check 12842 // that the value fits in an int. 12843 if (CVal != CVal64) 12844 return; 12845 12846 switch (ConstraintLetter) { 12847 case 'j': 12848 // Constant suitable for movw, must be between 0 and 12849 // 65535. 12850 if (Subtarget->hasV6T2Ops()) 12851 if (CVal >= 0 && CVal <= 65535) 12852 break; 12853 return; 12854 case 'I': 12855 if (Subtarget->isThumb1Only()) { 12856 // This must be a constant between 0 and 255, for ADD 12857 // immediates. 12858 if (CVal >= 0 && CVal <= 255) 12859 break; 12860 } else if (Subtarget->isThumb2()) { 12861 // A constant that can be used as an immediate value in a 12862 // data-processing instruction. 12863 if (ARM_AM::getT2SOImmVal(CVal) != -1) 12864 break; 12865 } else { 12866 // A constant that can be used as an immediate value in a 12867 // data-processing instruction. 12868 if (ARM_AM::getSOImmVal(CVal) != -1) 12869 break; 12870 } 12871 return; 12872 12873 case 'J': 12874 if (Subtarget->isThumb1Only()) { 12875 // This must be a constant between -255 and -1, for negated ADD 12876 // immediates. This can be used in GCC with an "n" modifier that 12877 // prints the negated value, for use with SUB instructions. It is 12878 // not useful otherwise but is implemented for compatibility. 12879 if (CVal >= -255 && CVal <= -1) 12880 break; 12881 } else { 12882 // This must be a constant between -4095 and 4095. It is not clear 12883 // what this constraint is intended for. Implemented for 12884 // compatibility with GCC. 12885 if (CVal >= -4095 && CVal <= 4095) 12886 break; 12887 } 12888 return; 12889 12890 case 'K': 12891 if (Subtarget->isThumb1Only()) { 12892 // A 32-bit value where only one byte has a nonzero value. Exclude 12893 // zero to match GCC. This constraint is used by GCC internally for 12894 // constants that can be loaded with a move/shift combination. 12895 // It is not useful otherwise but is implemented for compatibility. 12896 if (CVal != 0 && ARM_AM::isThumbImmShiftedVal(CVal)) 12897 break; 12898 } else if (Subtarget->isThumb2()) { 12899 // A constant whose bitwise inverse can be used as an immediate 12900 // value in a data-processing instruction. This can be used in GCC 12901 // with a "B" modifier that prints the inverted value, for use with 12902 // BIC and MVN instructions. It is not useful otherwise but is 12903 // implemented for compatibility. 12904 if (ARM_AM::getT2SOImmVal(~CVal) != -1) 12905 break; 12906 } else { 12907 // A constant whose bitwise inverse can be used as an immediate 12908 // value in a data-processing instruction. This can be used in GCC 12909 // with a "B" modifier that prints the inverted value, for use with 12910 // BIC and MVN instructions. It is not useful otherwise but is 12911 // implemented for compatibility. 12912 if (ARM_AM::getSOImmVal(~CVal) != -1) 12913 break; 12914 } 12915 return; 12916 12917 case 'L': 12918 if (Subtarget->isThumb1Only()) { 12919 // This must be a constant between -7 and 7, 12920 // for 3-operand ADD/SUB immediate instructions. 12921 if (CVal >= -7 && CVal < 7) 12922 break; 12923 } else if (Subtarget->isThumb2()) { 12924 // A constant whose negation can be used as an immediate value in a 12925 // data-processing instruction. This can be used in GCC with an "n" 12926 // modifier that prints the negated value, for use with SUB 12927 // instructions. It is not useful otherwise but is implemented for 12928 // compatibility. 12929 if (ARM_AM::getT2SOImmVal(-CVal) != -1) 12930 break; 12931 } else { 12932 // A constant whose negation can be used as an immediate value in a 12933 // data-processing instruction. This can be used in GCC with an "n" 12934 // modifier that prints the negated value, for use with SUB 12935 // instructions. It is not useful otherwise but is implemented for 12936 // compatibility. 12937 if (ARM_AM::getSOImmVal(-CVal) != -1) 12938 break; 12939 } 12940 return; 12941 12942 case 'M': 12943 if (Subtarget->isThumb1Only()) { 12944 // This must be a multiple of 4 between 0 and 1020, for 12945 // ADD sp + immediate. 12946 if ((CVal >= 0 && CVal <= 1020) && ((CVal & 3) == 0)) 12947 break; 12948 } else { 12949 // A power of two or a constant between 0 and 32. This is used in 12950 // GCC for the shift amount on shifted register operands, but it is 12951 // useful in general for any shift amounts. 12952 if ((CVal >= 0 && CVal <= 32) || ((CVal & (CVal - 1)) == 0)) 12953 break; 12954 } 12955 return; 12956 12957 case 'N': 12958 if (Subtarget->isThumb()) { // FIXME thumb2 12959 // This must be a constant between 0 and 31, for shift amounts. 12960 if (CVal >= 0 && CVal <= 31) 12961 break; 12962 } 12963 return; 12964 12965 case 'O': 12966 if (Subtarget->isThumb()) { // FIXME thumb2 12967 // This must be a multiple of 4 between -508 and 508, for 12968 // ADD/SUB sp = sp + immediate. 12969 if ((CVal >= -508 && CVal <= 508) && ((CVal & 3) == 0)) 12970 break; 12971 } 12972 return; 12973 } 12974 Result = DAG.getTargetConstant(CVal, SDLoc(Op), Op.getValueType()); 12975 break; 12976 } 12977 12978 if (Result.getNode()) { 12979 Ops.push_back(Result); 12980 return; 12981 } 12982 return TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG); 12983 } 12984 12985 static RTLIB::Libcall getDivRemLibcall( 12986 const SDNode *N, MVT::SimpleValueType SVT) { 12987 assert((N->getOpcode() == ISD::SDIVREM || N->getOpcode() == ISD::UDIVREM || 12988 N->getOpcode() == ISD::SREM || N->getOpcode() == ISD::UREM) && 12989 "Unhandled Opcode in getDivRemLibcall"); 12990 bool isSigned = N->getOpcode() == ISD::SDIVREM || 12991 N->getOpcode() == ISD::SREM; 12992 RTLIB::Libcall LC; 12993 switch (SVT) { 12994 default: llvm_unreachable("Unexpected request for libcall!"); 12995 case MVT::i8: LC = isSigned ? RTLIB::SDIVREM_I8 : RTLIB::UDIVREM_I8; break; 12996 case MVT::i16: LC = isSigned ? RTLIB::SDIVREM_I16 : RTLIB::UDIVREM_I16; break; 12997 case MVT::i32: LC = isSigned ? RTLIB::SDIVREM_I32 : RTLIB::UDIVREM_I32; break; 12998 case MVT::i64: LC = isSigned ? RTLIB::SDIVREM_I64 : RTLIB::UDIVREM_I64; break; 12999 } 13000 return LC; 13001 } 13002 13003 static TargetLowering::ArgListTy getDivRemArgList( 13004 const SDNode *N, LLVMContext *Context, const ARMSubtarget *Subtarget) { 13005 assert((N->getOpcode() == ISD::SDIVREM || N->getOpcode() == ISD::UDIVREM || 13006 N->getOpcode() == ISD::SREM || N->getOpcode() == ISD::UREM) && 13007 "Unhandled Opcode in getDivRemArgList"); 13008 bool isSigned = N->getOpcode() == ISD::SDIVREM || 13009 N->getOpcode() == ISD::SREM; 13010 TargetLowering::ArgListTy Args; 13011 TargetLowering::ArgListEntry Entry; 13012 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) { 13013 EVT ArgVT = N->getOperand(i).getValueType(); 13014 Type *ArgTy = ArgVT.getTypeForEVT(*Context); 13015 Entry.Node = N->getOperand(i); 13016 Entry.Ty = ArgTy; 13017 Entry.IsSExt = isSigned; 13018 Entry.IsZExt = !isSigned; 13019 Args.push_back(Entry); 13020 } 13021 if (Subtarget->isTargetWindows() && Args.size() >= 2) 13022 std::swap(Args[0], Args[1]); 13023 return Args; 13024 } 13025 13026 SDValue ARMTargetLowering::LowerDivRem(SDValue Op, SelectionDAG &DAG) const { 13027 assert((Subtarget->isTargetAEABI() || Subtarget->isTargetAndroid() || 13028 Subtarget->isTargetGNUAEABI() || Subtarget->isTargetMuslAEABI() || 13029 Subtarget->isTargetWindows()) && 13030 "Register-based DivRem lowering only"); 13031 unsigned Opcode = Op->getOpcode(); 13032 assert((Opcode == ISD::SDIVREM || Opcode == ISD::UDIVREM) && 13033 "Invalid opcode for Div/Rem lowering"); 13034 bool isSigned = (Opcode == ISD::SDIVREM); 13035 EVT VT = Op->getValueType(0); 13036 Type *Ty = VT.getTypeForEVT(*DAG.getContext()); 13037 SDLoc dl(Op); 13038 13039 // If the target has hardware divide, use divide + multiply + subtract: 13040 // div = a / b 13041 // rem = a - b * div 13042 // return {div, rem} 13043 // This should be lowered into UDIV/SDIV + MLS later on. 13044 if (Subtarget->hasDivide() && Op->getValueType(0).isSimple() && 13045 Op->getSimpleValueType(0) == MVT::i32) { 13046 unsigned DivOpcode = isSigned ? ISD::SDIV : ISD::UDIV; 13047 const SDValue Dividend = Op->getOperand(0); 13048 const SDValue Divisor = Op->getOperand(1); 13049 SDValue Div = DAG.getNode(DivOpcode, dl, VT, Dividend, Divisor); 13050 SDValue Mul = DAG.getNode(ISD::MUL, dl, VT, Div, Divisor); 13051 SDValue Rem = DAG.getNode(ISD::SUB, dl, VT, Dividend, Mul); 13052 13053 SDValue Values[2] = {Div, Rem}; 13054 return DAG.getNode(ISD::MERGE_VALUES, dl, DAG.getVTList(VT, VT), Values); 13055 } 13056 13057 RTLIB::Libcall LC = getDivRemLibcall(Op.getNode(), 13058 VT.getSimpleVT().SimpleTy); 13059 SDValue InChain = DAG.getEntryNode(); 13060 13061 TargetLowering::ArgListTy Args = getDivRemArgList(Op.getNode(), 13062 DAG.getContext(), 13063 Subtarget); 13064 13065 SDValue Callee = DAG.getExternalSymbol(getLibcallName(LC), 13066 getPointerTy(DAG.getDataLayout())); 13067 13068 Type *RetTy = (Type*)StructType::get(Ty, Ty, nullptr); 13069 13070 if (Subtarget->isTargetWindows()) 13071 InChain = WinDBZCheckDenominator(DAG, Op.getNode(), InChain); 13072 13073 TargetLowering::CallLoweringInfo CLI(DAG); 13074 CLI.setDebugLoc(dl).setChain(InChain) 13075 .setCallee(getLibcallCallingConv(LC), RetTy, Callee, std::move(Args)) 13076 .setInRegister().setSExtResult(isSigned).setZExtResult(!isSigned); 13077 13078 std::pair<SDValue, SDValue> CallInfo = LowerCallTo(CLI); 13079 return CallInfo.first; 13080 } 13081 13082 // Lowers REM using divmod helpers 13083 // see RTABI section 4.2/4.3 13084 SDValue ARMTargetLowering::LowerREM(SDNode *N, SelectionDAG &DAG) const { 13085 // Build return types (div and rem) 13086 std::vector<Type*> RetTyParams; 13087 Type *RetTyElement; 13088 13089 switch (N->getValueType(0).getSimpleVT().SimpleTy) { 13090 default: llvm_unreachable("Unexpected request for libcall!"); 13091 case MVT::i8: RetTyElement = Type::getInt8Ty(*DAG.getContext()); break; 13092 case MVT::i16: RetTyElement = Type::getInt16Ty(*DAG.getContext()); break; 13093 case MVT::i32: RetTyElement = Type::getInt32Ty(*DAG.getContext()); break; 13094 case MVT::i64: RetTyElement = Type::getInt64Ty(*DAG.getContext()); break; 13095 } 13096 13097 RetTyParams.push_back(RetTyElement); 13098 RetTyParams.push_back(RetTyElement); 13099 ArrayRef<Type*> ret = ArrayRef<Type*>(RetTyParams); 13100 Type *RetTy = StructType::get(*DAG.getContext(), ret); 13101 13102 RTLIB::Libcall LC = getDivRemLibcall(N, N->getValueType(0).getSimpleVT(). 13103 SimpleTy); 13104 SDValue InChain = DAG.getEntryNode(); 13105 TargetLowering::ArgListTy Args = getDivRemArgList(N, DAG.getContext(), 13106 Subtarget); 13107 bool isSigned = N->getOpcode() == ISD::SREM; 13108 SDValue Callee = DAG.getExternalSymbol(getLibcallName(LC), 13109 getPointerTy(DAG.getDataLayout())); 13110 13111 if (Subtarget->isTargetWindows()) 13112 InChain = WinDBZCheckDenominator(DAG, N, InChain); 13113 13114 // Lower call 13115 CallLoweringInfo CLI(DAG); 13116 CLI.setChain(InChain) 13117 .setCallee(CallingConv::ARM_AAPCS, RetTy, Callee, std::move(Args)) 13118 .setSExtResult(isSigned).setZExtResult(!isSigned).setDebugLoc(SDLoc(N)); 13119 std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI); 13120 13121 // Return second (rem) result operand (first contains div) 13122 SDNode *ResNode = CallResult.first.getNode(); 13123 assert(ResNode->getNumOperands() == 2 && "divmod should return two operands"); 13124 return ResNode->getOperand(1); 13125 } 13126 13127 SDValue 13128 ARMTargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op, SelectionDAG &DAG) const { 13129 assert(Subtarget->isTargetWindows() && "unsupported target platform"); 13130 SDLoc DL(Op); 13131 13132 // Get the inputs. 13133 SDValue Chain = Op.getOperand(0); 13134 SDValue Size = Op.getOperand(1); 13135 13136 SDValue Words = DAG.getNode(ISD::SRL, DL, MVT::i32, Size, 13137 DAG.getConstant(2, DL, MVT::i32)); 13138 13139 SDValue Flag; 13140 Chain = DAG.getCopyToReg(Chain, DL, ARM::R4, Words, Flag); 13141 Flag = Chain.getValue(1); 13142 13143 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue); 13144 Chain = DAG.getNode(ARMISD::WIN__CHKSTK, DL, NodeTys, Chain, Flag); 13145 13146 SDValue NewSP = DAG.getCopyFromReg(Chain, DL, ARM::SP, MVT::i32); 13147 Chain = NewSP.getValue(1); 13148 13149 SDValue Ops[2] = { NewSP, Chain }; 13150 return DAG.getMergeValues(Ops, DL); 13151 } 13152 13153 SDValue ARMTargetLowering::LowerFP_EXTEND(SDValue Op, SelectionDAG &DAG) const { 13154 assert(Op.getValueType() == MVT::f64 && Subtarget->isFPOnlySP() && 13155 "Unexpected type for custom-lowering FP_EXTEND"); 13156 13157 RTLIB::Libcall LC; 13158 LC = RTLIB::getFPEXT(Op.getOperand(0).getValueType(), Op.getValueType()); 13159 13160 SDValue SrcVal = Op.getOperand(0); 13161 return makeLibCall(DAG, LC, Op.getValueType(), SrcVal, /*isSigned*/ false, 13162 SDLoc(Op)).first; 13163 } 13164 13165 SDValue ARMTargetLowering::LowerFP_ROUND(SDValue Op, SelectionDAG &DAG) const { 13166 assert(Op.getOperand(0).getValueType() == MVT::f64 && 13167 Subtarget->isFPOnlySP() && 13168 "Unexpected type for custom-lowering FP_ROUND"); 13169 13170 RTLIB::Libcall LC; 13171 LC = RTLIB::getFPROUND(Op.getOperand(0).getValueType(), Op.getValueType()); 13172 13173 SDValue SrcVal = Op.getOperand(0); 13174 return makeLibCall(DAG, LC, Op.getValueType(), SrcVal, /*isSigned*/ false, 13175 SDLoc(Op)).first; 13176 } 13177 13178 bool 13179 ARMTargetLowering::isOffsetFoldingLegal(const GlobalAddressSDNode *GA) const { 13180 // The ARM target isn't yet aware of offsets. 13181 return false; 13182 } 13183 13184 bool ARM::isBitFieldInvertedMask(unsigned v) { 13185 if (v == 0xffffffff) 13186 return false; 13187 13188 // there can be 1's on either or both "outsides", all the "inside" 13189 // bits must be 0's 13190 return isShiftedMask_32(~v); 13191 } 13192 13193 /// isFPImmLegal - Returns true if the target can instruction select the 13194 /// specified FP immediate natively. If false, the legalizer will 13195 /// materialize the FP immediate as a load from a constant pool. 13196 bool ARMTargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT) const { 13197 if (!Subtarget->hasVFP3()) 13198 return false; 13199 if (VT == MVT::f32) 13200 return ARM_AM::getFP32Imm(Imm) != -1; 13201 if (VT == MVT::f64 && !Subtarget->isFPOnlySP()) 13202 return ARM_AM::getFP64Imm(Imm) != -1; 13203 return false; 13204 } 13205 13206 /// getTgtMemIntrinsic - Represent NEON load and store intrinsics as 13207 /// MemIntrinsicNodes. The associated MachineMemOperands record the alignment 13208 /// specified in the intrinsic calls. 13209 bool ARMTargetLowering::getTgtMemIntrinsic(IntrinsicInfo &Info, 13210 const CallInst &I, 13211 unsigned Intrinsic) const { 13212 switch (Intrinsic) { 13213 case Intrinsic::arm_neon_vld1: 13214 case Intrinsic::arm_neon_vld2: 13215 case Intrinsic::arm_neon_vld3: 13216 case Intrinsic::arm_neon_vld4: 13217 case Intrinsic::arm_neon_vld2lane: 13218 case Intrinsic::arm_neon_vld3lane: 13219 case Intrinsic::arm_neon_vld4lane: { 13220 Info.opc = ISD::INTRINSIC_W_CHAIN; 13221 // Conservatively set memVT to the entire set of vectors loaded. 13222 auto &DL = I.getCalledFunction()->getParent()->getDataLayout(); 13223 uint64_t NumElts = DL.getTypeSizeInBits(I.getType()) / 64; 13224 Info.memVT = EVT::getVectorVT(I.getType()->getContext(), MVT::i64, NumElts); 13225 Info.ptrVal = I.getArgOperand(0); 13226 Info.offset = 0; 13227 Value *AlignArg = I.getArgOperand(I.getNumArgOperands() - 1); 13228 Info.align = cast<ConstantInt>(AlignArg)->getZExtValue(); 13229 Info.vol = false; // volatile loads with NEON intrinsics not supported 13230 Info.readMem = true; 13231 Info.writeMem = false; 13232 return true; 13233 } 13234 case Intrinsic::arm_neon_vst1: 13235 case Intrinsic::arm_neon_vst2: 13236 case Intrinsic::arm_neon_vst3: 13237 case Intrinsic::arm_neon_vst4: 13238 case Intrinsic::arm_neon_vst2lane: 13239 case Intrinsic::arm_neon_vst3lane: 13240 case Intrinsic::arm_neon_vst4lane: { 13241 Info.opc = ISD::INTRINSIC_VOID; 13242 // Conservatively set memVT to the entire set of vectors stored. 13243 auto &DL = I.getCalledFunction()->getParent()->getDataLayout(); 13244 unsigned NumElts = 0; 13245 for (unsigned ArgI = 1, ArgE = I.getNumArgOperands(); ArgI < ArgE; ++ArgI) { 13246 Type *ArgTy = I.getArgOperand(ArgI)->getType(); 13247 if (!ArgTy->isVectorTy()) 13248 break; 13249 NumElts += DL.getTypeSizeInBits(ArgTy) / 64; 13250 } 13251 Info.memVT = EVT::getVectorVT(I.getType()->getContext(), MVT::i64, NumElts); 13252 Info.ptrVal = I.getArgOperand(0); 13253 Info.offset = 0; 13254 Value *AlignArg = I.getArgOperand(I.getNumArgOperands() - 1); 13255 Info.align = cast<ConstantInt>(AlignArg)->getZExtValue(); 13256 Info.vol = false; // volatile stores with NEON intrinsics not supported 13257 Info.readMem = false; 13258 Info.writeMem = true; 13259 return true; 13260 } 13261 case Intrinsic::arm_ldaex: 13262 case Intrinsic::arm_ldrex: { 13263 auto &DL = I.getCalledFunction()->getParent()->getDataLayout(); 13264 PointerType *PtrTy = cast<PointerType>(I.getArgOperand(0)->getType()); 13265 Info.opc = ISD::INTRINSIC_W_CHAIN; 13266 Info.memVT = MVT::getVT(PtrTy->getElementType()); 13267 Info.ptrVal = I.getArgOperand(0); 13268 Info.offset = 0; 13269 Info.align = DL.getABITypeAlignment(PtrTy->getElementType()); 13270 Info.vol = true; 13271 Info.readMem = true; 13272 Info.writeMem = false; 13273 return true; 13274 } 13275 case Intrinsic::arm_stlex: 13276 case Intrinsic::arm_strex: { 13277 auto &DL = I.getCalledFunction()->getParent()->getDataLayout(); 13278 PointerType *PtrTy = cast<PointerType>(I.getArgOperand(1)->getType()); 13279 Info.opc = ISD::INTRINSIC_W_CHAIN; 13280 Info.memVT = MVT::getVT(PtrTy->getElementType()); 13281 Info.ptrVal = I.getArgOperand(1); 13282 Info.offset = 0; 13283 Info.align = DL.getABITypeAlignment(PtrTy->getElementType()); 13284 Info.vol = true; 13285 Info.readMem = false; 13286 Info.writeMem = true; 13287 return true; 13288 } 13289 case Intrinsic::arm_stlexd: 13290 case Intrinsic::arm_strexd: 13291 Info.opc = ISD::INTRINSIC_W_CHAIN; 13292 Info.memVT = MVT::i64; 13293 Info.ptrVal = I.getArgOperand(2); 13294 Info.offset = 0; 13295 Info.align = 8; 13296 Info.vol = true; 13297 Info.readMem = false; 13298 Info.writeMem = true; 13299 return true; 13300 13301 case Intrinsic::arm_ldaexd: 13302 case Intrinsic::arm_ldrexd: 13303 Info.opc = ISD::INTRINSIC_W_CHAIN; 13304 Info.memVT = MVT::i64; 13305 Info.ptrVal = I.getArgOperand(0); 13306 Info.offset = 0; 13307 Info.align = 8; 13308 Info.vol = true; 13309 Info.readMem = true; 13310 Info.writeMem = false; 13311 return true; 13312 13313 default: 13314 break; 13315 } 13316 13317 return false; 13318 } 13319 13320 /// \brief Returns true if it is beneficial to convert a load of a constant 13321 /// to just the constant itself. 13322 bool ARMTargetLowering::shouldConvertConstantLoadToIntImm(const APInt &Imm, 13323 Type *Ty) const { 13324 assert(Ty->isIntegerTy()); 13325 13326 unsigned Bits = Ty->getPrimitiveSizeInBits(); 13327 if (Bits == 0 || Bits > 32) 13328 return false; 13329 return true; 13330 } 13331 13332 bool ARMTargetLowering::isExtractSubvectorCheap(EVT ResVT, 13333 unsigned Index) const { 13334 if (!isOperationLegalOrCustom(ISD::EXTRACT_SUBVECTOR, ResVT)) 13335 return false; 13336 13337 return (Index == 0 || Index == ResVT.getVectorNumElements()); 13338 } 13339 13340 Instruction* ARMTargetLowering::makeDMB(IRBuilder<> &Builder, 13341 ARM_MB::MemBOpt Domain) const { 13342 Module *M = Builder.GetInsertBlock()->getParent()->getParent(); 13343 13344 // First, if the target has no DMB, see what fallback we can use. 13345 if (!Subtarget->hasDataBarrier()) { 13346 // Some ARMv6 cpus can support data barriers with an mcr instruction. 13347 // Thumb1 and pre-v6 ARM mode use a libcall instead and should never get 13348 // here. 13349 if (Subtarget->hasV6Ops() && !Subtarget->isThumb()) { 13350 Function *MCR = Intrinsic::getDeclaration(M, Intrinsic::arm_mcr); 13351 Value* args[6] = {Builder.getInt32(15), Builder.getInt32(0), 13352 Builder.getInt32(0), Builder.getInt32(7), 13353 Builder.getInt32(10), Builder.getInt32(5)}; 13354 return Builder.CreateCall(MCR, args); 13355 } else { 13356 // Instead of using barriers, atomic accesses on these subtargets use 13357 // libcalls. 13358 llvm_unreachable("makeDMB on a target so old that it has no barriers"); 13359 } 13360 } else { 13361 Function *DMB = Intrinsic::getDeclaration(M, Intrinsic::arm_dmb); 13362 // Only a full system barrier exists in the M-class architectures. 13363 Domain = Subtarget->isMClass() ? ARM_MB::SY : Domain; 13364 Constant *CDomain = Builder.getInt32(Domain); 13365 return Builder.CreateCall(DMB, CDomain); 13366 } 13367 } 13368 13369 // Based on http://www.cl.cam.ac.uk/~pes20/cpp/cpp0xmappings.html 13370 Instruction* ARMTargetLowering::emitLeadingFence(IRBuilder<> &Builder, 13371 AtomicOrdering Ord, bool IsStore, 13372 bool IsLoad) const { 13373 switch (Ord) { 13374 case AtomicOrdering::NotAtomic: 13375 case AtomicOrdering::Unordered: 13376 llvm_unreachable("Invalid fence: unordered/non-atomic"); 13377 case AtomicOrdering::Monotonic: 13378 case AtomicOrdering::Acquire: 13379 return nullptr; // Nothing to do 13380 case AtomicOrdering::SequentiallyConsistent: 13381 if (!IsStore) 13382 return nullptr; // Nothing to do 13383 /*FALLTHROUGH*/ 13384 case AtomicOrdering::Release: 13385 case AtomicOrdering::AcquireRelease: 13386 if (Subtarget->preferISHSTBarriers()) 13387 return makeDMB(Builder, ARM_MB::ISHST); 13388 // FIXME: add a comment with a link to documentation justifying this. 13389 else 13390 return makeDMB(Builder, ARM_MB::ISH); 13391 } 13392 llvm_unreachable("Unknown fence ordering in emitLeadingFence"); 13393 } 13394 13395 Instruction* ARMTargetLowering::emitTrailingFence(IRBuilder<> &Builder, 13396 AtomicOrdering Ord, bool IsStore, 13397 bool IsLoad) const { 13398 switch (Ord) { 13399 case AtomicOrdering::NotAtomic: 13400 case AtomicOrdering::Unordered: 13401 llvm_unreachable("Invalid fence: unordered/not-atomic"); 13402 case AtomicOrdering::Monotonic: 13403 case AtomicOrdering::Release: 13404 return nullptr; // Nothing to do 13405 case AtomicOrdering::Acquire: 13406 case AtomicOrdering::AcquireRelease: 13407 case AtomicOrdering::SequentiallyConsistent: 13408 return makeDMB(Builder, ARM_MB::ISH); 13409 } 13410 llvm_unreachable("Unknown fence ordering in emitTrailingFence"); 13411 } 13412 13413 // Loads and stores less than 64-bits are already atomic; ones above that 13414 // are doomed anyway, so defer to the default libcall and blame the OS when 13415 // things go wrong. Cortex M doesn't have ldrexd/strexd though, so don't emit 13416 // anything for those. 13417 bool ARMTargetLowering::shouldExpandAtomicStoreInIR(StoreInst *SI) const { 13418 unsigned Size = SI->getValueOperand()->getType()->getPrimitiveSizeInBits(); 13419 return (Size == 64) && !Subtarget->isMClass(); 13420 } 13421 13422 // Loads and stores less than 64-bits are already atomic; ones above that 13423 // are doomed anyway, so defer to the default libcall and blame the OS when 13424 // things go wrong. Cortex M doesn't have ldrexd/strexd though, so don't emit 13425 // anything for those. 13426 // FIXME: ldrd and strd are atomic if the CPU has LPAE (e.g. A15 has that 13427 // guarantee, see DDI0406C ARM architecture reference manual, 13428 // sections A8.8.72-74 LDRD) 13429 TargetLowering::AtomicExpansionKind 13430 ARMTargetLowering::shouldExpandAtomicLoadInIR(LoadInst *LI) const { 13431 unsigned Size = LI->getType()->getPrimitiveSizeInBits(); 13432 return ((Size == 64) && !Subtarget->isMClass()) ? AtomicExpansionKind::LLOnly 13433 : AtomicExpansionKind::None; 13434 } 13435 13436 // For the real atomic operations, we have ldrex/strex up to 32 bits, 13437 // and up to 64 bits on the non-M profiles 13438 TargetLowering::AtomicExpansionKind 13439 ARMTargetLowering::shouldExpandAtomicRMWInIR(AtomicRMWInst *AI) const { 13440 unsigned Size = AI->getType()->getPrimitiveSizeInBits(); 13441 bool hasAtomicRMW = !Subtarget->isThumb() || Subtarget->hasV8MBaselineOps(); 13442 return (Size <= (Subtarget->isMClass() ? 32U : 64U) && hasAtomicRMW) 13443 ? AtomicExpansionKind::LLSC 13444 : AtomicExpansionKind::None; 13445 } 13446 13447 bool ARMTargetLowering::shouldExpandAtomicCmpXchgInIR( 13448 AtomicCmpXchgInst *AI) const { 13449 // At -O0, fast-regalloc cannot cope with the live vregs necessary to 13450 // implement cmpxchg without spilling. If the address being exchanged is also 13451 // on the stack and close enough to the spill slot, this can lead to a 13452 // situation where the monitor always gets cleared and the atomic operation 13453 // can never succeed. So at -O0 we need a late-expanded pseudo-inst instead. 13454 bool hasAtomicCmpXchg = 13455 !Subtarget->isThumb() || Subtarget->hasV8MBaselineOps(); 13456 return getTargetMachine().getOptLevel() != 0 && hasAtomicCmpXchg; 13457 } 13458 13459 bool ARMTargetLowering::shouldInsertFencesForAtomic( 13460 const Instruction *I) const { 13461 return InsertFencesForAtomic; 13462 } 13463 13464 // This has so far only been implemented for MachO. 13465 bool ARMTargetLowering::useLoadStackGuardNode() const { 13466 return Subtarget->isTargetMachO(); 13467 } 13468 13469 bool ARMTargetLowering::canCombineStoreAndExtract(Type *VectorTy, Value *Idx, 13470 unsigned &Cost) const { 13471 // If we do not have NEON, vector types are not natively supported. 13472 if (!Subtarget->hasNEON()) 13473 return false; 13474 13475 // Floating point values and vector values map to the same register file. 13476 // Therefore, although we could do a store extract of a vector type, this is 13477 // better to leave at float as we have more freedom in the addressing mode for 13478 // those. 13479 if (VectorTy->isFPOrFPVectorTy()) 13480 return false; 13481 13482 // If the index is unknown at compile time, this is very expensive to lower 13483 // and it is not possible to combine the store with the extract. 13484 if (!isa<ConstantInt>(Idx)) 13485 return false; 13486 13487 assert(VectorTy->isVectorTy() && "VectorTy is not a vector type"); 13488 unsigned BitWidth = cast<VectorType>(VectorTy)->getBitWidth(); 13489 // We can do a store + vector extract on any vector that fits perfectly in a D 13490 // or Q register. 13491 if (BitWidth == 64 || BitWidth == 128) { 13492 Cost = 0; 13493 return true; 13494 } 13495 return false; 13496 } 13497 13498 bool ARMTargetLowering::isCheapToSpeculateCttz() const { 13499 return Subtarget->hasV6T2Ops(); 13500 } 13501 13502 bool ARMTargetLowering::isCheapToSpeculateCtlz() const { 13503 return Subtarget->hasV6T2Ops(); 13504 } 13505 13506 Value *ARMTargetLowering::emitLoadLinked(IRBuilder<> &Builder, Value *Addr, 13507 AtomicOrdering Ord) const { 13508 Module *M = Builder.GetInsertBlock()->getParent()->getParent(); 13509 Type *ValTy = cast<PointerType>(Addr->getType())->getElementType(); 13510 bool IsAcquire = isAcquireOrStronger(Ord); 13511 13512 // Since i64 isn't legal and intrinsics don't get type-lowered, the ldrexd 13513 // intrinsic must return {i32, i32} and we have to recombine them into a 13514 // single i64 here. 13515 if (ValTy->getPrimitiveSizeInBits() == 64) { 13516 Intrinsic::ID Int = 13517 IsAcquire ? Intrinsic::arm_ldaexd : Intrinsic::arm_ldrexd; 13518 Function *Ldrex = Intrinsic::getDeclaration(M, Int); 13519 13520 Addr = Builder.CreateBitCast(Addr, Type::getInt8PtrTy(M->getContext())); 13521 Value *LoHi = Builder.CreateCall(Ldrex, Addr, "lohi"); 13522 13523 Value *Lo = Builder.CreateExtractValue(LoHi, 0, "lo"); 13524 Value *Hi = Builder.CreateExtractValue(LoHi, 1, "hi"); 13525 if (!Subtarget->isLittle()) 13526 std::swap (Lo, Hi); 13527 Lo = Builder.CreateZExt(Lo, ValTy, "lo64"); 13528 Hi = Builder.CreateZExt(Hi, ValTy, "hi64"); 13529 return Builder.CreateOr( 13530 Lo, Builder.CreateShl(Hi, ConstantInt::get(ValTy, 32)), "val64"); 13531 } 13532 13533 Type *Tys[] = { Addr->getType() }; 13534 Intrinsic::ID Int = IsAcquire ? Intrinsic::arm_ldaex : Intrinsic::arm_ldrex; 13535 Function *Ldrex = Intrinsic::getDeclaration(M, Int, Tys); 13536 13537 return Builder.CreateTruncOrBitCast( 13538 Builder.CreateCall(Ldrex, Addr), 13539 cast<PointerType>(Addr->getType())->getElementType()); 13540 } 13541 13542 void ARMTargetLowering::emitAtomicCmpXchgNoStoreLLBalance( 13543 IRBuilder<> &Builder) const { 13544 if (!Subtarget->hasV7Ops()) 13545 return; 13546 Module *M = Builder.GetInsertBlock()->getParent()->getParent(); 13547 Builder.CreateCall(Intrinsic::getDeclaration(M, Intrinsic::arm_clrex)); 13548 } 13549 13550 Value *ARMTargetLowering::emitStoreConditional(IRBuilder<> &Builder, Value *Val, 13551 Value *Addr, 13552 AtomicOrdering Ord) const { 13553 Module *M = Builder.GetInsertBlock()->getParent()->getParent(); 13554 bool IsRelease = isReleaseOrStronger(Ord); 13555 13556 // Since the intrinsics must have legal type, the i64 intrinsics take two 13557 // parameters: "i32, i32". We must marshal Val into the appropriate form 13558 // before the call. 13559 if (Val->getType()->getPrimitiveSizeInBits() == 64) { 13560 Intrinsic::ID Int = 13561 IsRelease ? Intrinsic::arm_stlexd : Intrinsic::arm_strexd; 13562 Function *Strex = Intrinsic::getDeclaration(M, Int); 13563 Type *Int32Ty = Type::getInt32Ty(M->getContext()); 13564 13565 Value *Lo = Builder.CreateTrunc(Val, Int32Ty, "lo"); 13566 Value *Hi = Builder.CreateTrunc(Builder.CreateLShr(Val, 32), Int32Ty, "hi"); 13567 if (!Subtarget->isLittle()) 13568 std::swap (Lo, Hi); 13569 Addr = Builder.CreateBitCast(Addr, Type::getInt8PtrTy(M->getContext())); 13570 return Builder.CreateCall(Strex, {Lo, Hi, Addr}); 13571 } 13572 13573 Intrinsic::ID Int = IsRelease ? Intrinsic::arm_stlex : Intrinsic::arm_strex; 13574 Type *Tys[] = { Addr->getType() }; 13575 Function *Strex = Intrinsic::getDeclaration(M, Int, Tys); 13576 13577 return Builder.CreateCall( 13578 Strex, {Builder.CreateZExtOrBitCast( 13579 Val, Strex->getFunctionType()->getParamType(0)), 13580 Addr}); 13581 } 13582 13583 /// A helper function for determining the number of interleaved accesses we 13584 /// will generate when lowering accesses of the given type. 13585 static unsigned getNumInterleavedAccesses(VectorType *VecTy, 13586 const DataLayout &DL) { 13587 return (DL.getTypeSizeInBits(VecTy) + 127) / 128; 13588 } 13589 13590 /// \brief Lower an interleaved load into a vldN intrinsic. 13591 /// 13592 /// E.g. Lower an interleaved load (Factor = 2): 13593 /// %wide.vec = load <8 x i32>, <8 x i32>* %ptr, align 4 13594 /// %v0 = shuffle %wide.vec, undef, <0, 2, 4, 6> ; Extract even elements 13595 /// %v1 = shuffle %wide.vec, undef, <1, 3, 5, 7> ; Extract odd elements 13596 /// 13597 /// Into: 13598 /// %vld2 = { <4 x i32>, <4 x i32> } call llvm.arm.neon.vld2(%ptr, 4) 13599 /// %vec0 = extractelement { <4 x i32>, <4 x i32> } %vld2, i32 0 13600 /// %vec1 = extractelement { <4 x i32>, <4 x i32> } %vld2, i32 1 13601 bool ARMTargetLowering::lowerInterleavedLoad( 13602 LoadInst *LI, ArrayRef<ShuffleVectorInst *> Shuffles, 13603 ArrayRef<unsigned> Indices, unsigned Factor) const { 13604 assert(Factor >= 2 && Factor <= getMaxSupportedInterleaveFactor() && 13605 "Invalid interleave factor"); 13606 assert(!Shuffles.empty() && "Empty shufflevector input"); 13607 assert(Shuffles.size() == Indices.size() && 13608 "Unmatched number of shufflevectors and indices"); 13609 13610 VectorType *VecTy = Shuffles[0]->getType(); 13611 Type *EltTy = VecTy->getVectorElementType(); 13612 13613 const DataLayout &DL = LI->getModule()->getDataLayout(); 13614 unsigned VecSize = DL.getTypeSizeInBits(VecTy); 13615 bool EltIs64Bits = DL.getTypeSizeInBits(EltTy) == 64; 13616 13617 // Skip if we do not have NEON and skip illegal vector types and vector types 13618 // with i64/f64 elements (vldN doesn't support i64/f64 elements). We can 13619 // "legalize" wide vector types into multiple interleaved accesses as long as 13620 // the vector types are divisible by 128. 13621 if (!Subtarget->hasNEON() || (VecSize != 64 && VecSize % 128 != 0) || 13622 EltIs64Bits) 13623 return false; 13624 13625 // Skip if the vector has f16 elements: even though we could do an i16 vldN, 13626 // we can't hold the f16 vectors and will end up converting via f32. 13627 if (EltTy->isHalfTy()) 13628 return false; 13629 13630 unsigned NumLoads = getNumInterleavedAccesses(VecTy, DL); 13631 13632 // A pointer vector can not be the return type of the ldN intrinsics. Need to 13633 // load integer vectors first and then convert to pointer vectors. 13634 if (EltTy->isPointerTy()) 13635 VecTy = 13636 VectorType::get(DL.getIntPtrType(EltTy), VecTy->getVectorNumElements()); 13637 13638 IRBuilder<> Builder(LI); 13639 13640 // The base address of the load. 13641 Value *BaseAddr = LI->getPointerOperand(); 13642 13643 if (NumLoads > 1) { 13644 // If we're going to generate more than one load, reset the sub-vector type 13645 // to something legal. 13646 VecTy = VectorType::get(VecTy->getVectorElementType(), 13647 VecTy->getVectorNumElements() / NumLoads); 13648 13649 // We will compute the pointer operand of each load from the original base 13650 // address using GEPs. Cast the base address to a pointer to the scalar 13651 // element type. 13652 BaseAddr = Builder.CreateBitCast( 13653 BaseAddr, VecTy->getVectorElementType()->getPointerTo( 13654 LI->getPointerAddressSpace())); 13655 } 13656 13657 assert(isTypeLegal(EVT::getEVT(VecTy)) && "Illegal vldN vector type!"); 13658 13659 Type *Int8Ptr = Builder.getInt8PtrTy(LI->getPointerAddressSpace()); 13660 Type *Tys[] = {VecTy, Int8Ptr}; 13661 static const Intrinsic::ID LoadInts[3] = {Intrinsic::arm_neon_vld2, 13662 Intrinsic::arm_neon_vld3, 13663 Intrinsic::arm_neon_vld4}; 13664 Function *VldnFunc = 13665 Intrinsic::getDeclaration(LI->getModule(), LoadInts[Factor - 2], Tys); 13666 13667 // Holds sub-vectors extracted from the load intrinsic return values. The 13668 // sub-vectors are associated with the shufflevector instructions they will 13669 // replace. 13670 DenseMap<ShuffleVectorInst *, SmallVector<Value *, 4>> SubVecs; 13671 13672 for (unsigned LoadCount = 0; LoadCount < NumLoads; ++LoadCount) { 13673 13674 // If we're generating more than one load, compute the base address of 13675 // subsequent loads as an offset from the previous. 13676 if (LoadCount > 0) 13677 BaseAddr = Builder.CreateConstGEP1_32( 13678 BaseAddr, VecTy->getVectorNumElements() * Factor); 13679 13680 SmallVector<Value *, 2> Ops; 13681 Ops.push_back(Builder.CreateBitCast(BaseAddr, Int8Ptr)); 13682 Ops.push_back(Builder.getInt32(LI->getAlignment())); 13683 13684 CallInst *VldN = Builder.CreateCall(VldnFunc, Ops, "vldN"); 13685 13686 // Replace uses of each shufflevector with the corresponding vector loaded 13687 // by ldN. 13688 for (unsigned i = 0; i < Shuffles.size(); i++) { 13689 ShuffleVectorInst *SV = Shuffles[i]; 13690 unsigned Index = Indices[i]; 13691 13692 Value *SubVec = Builder.CreateExtractValue(VldN, Index); 13693 13694 // Convert the integer vector to pointer vector if the element is pointer. 13695 if (EltTy->isPointerTy()) 13696 SubVec = Builder.CreateIntToPtr(SubVec, SV->getType()); 13697 13698 SubVecs[SV].push_back(SubVec); 13699 } 13700 } 13701 13702 // Replace uses of the shufflevector instructions with the sub-vectors 13703 // returned by the load intrinsic. If a shufflevector instruction is 13704 // associated with more than one sub-vector, those sub-vectors will be 13705 // concatenated into a single wide vector. 13706 for (ShuffleVectorInst *SVI : Shuffles) { 13707 auto &SubVec = SubVecs[SVI]; 13708 auto *WideVec = 13709 SubVec.size() > 1 ? concatenateVectors(Builder, SubVec) : SubVec[0]; 13710 SVI->replaceAllUsesWith(WideVec); 13711 } 13712 13713 return true; 13714 } 13715 13716 /// \brief Lower an interleaved store into a vstN intrinsic. 13717 /// 13718 /// E.g. Lower an interleaved store (Factor = 3): 13719 /// %i.vec = shuffle <8 x i32> %v0, <8 x i32> %v1, 13720 /// <0, 4, 8, 1, 5, 9, 2, 6, 10, 3, 7, 11> 13721 /// store <12 x i32> %i.vec, <12 x i32>* %ptr, align 4 13722 /// 13723 /// Into: 13724 /// %sub.v0 = shuffle <8 x i32> %v0, <8 x i32> v1, <0, 1, 2, 3> 13725 /// %sub.v1 = shuffle <8 x i32> %v0, <8 x i32> v1, <4, 5, 6, 7> 13726 /// %sub.v2 = shuffle <8 x i32> %v0, <8 x i32> v1, <8, 9, 10, 11> 13727 /// call void llvm.arm.neon.vst3(%ptr, %sub.v0, %sub.v1, %sub.v2, 4) 13728 /// 13729 /// Note that the new shufflevectors will be removed and we'll only generate one 13730 /// vst3 instruction in CodeGen. 13731 /// 13732 /// Example for a more general valid mask (Factor 3). Lower: 13733 /// %i.vec = shuffle <32 x i32> %v0, <32 x i32> %v1, 13734 /// <4, 32, 16, 5, 33, 17, 6, 34, 18, 7, 35, 19> 13735 /// store <12 x i32> %i.vec, <12 x i32>* %ptr 13736 /// 13737 /// Into: 13738 /// %sub.v0 = shuffle <32 x i32> %v0, <32 x i32> v1, <4, 5, 6, 7> 13739 /// %sub.v1 = shuffle <32 x i32> %v0, <32 x i32> v1, <32, 33, 34, 35> 13740 /// %sub.v2 = shuffle <32 x i32> %v0, <32 x i32> v1, <16, 17, 18, 19> 13741 /// call void llvm.arm.neon.vst3(%ptr, %sub.v0, %sub.v1, %sub.v2, 4) 13742 bool ARMTargetLowering::lowerInterleavedStore(StoreInst *SI, 13743 ShuffleVectorInst *SVI, 13744 unsigned Factor) const { 13745 assert(Factor >= 2 && Factor <= getMaxSupportedInterleaveFactor() && 13746 "Invalid interleave factor"); 13747 13748 VectorType *VecTy = SVI->getType(); 13749 assert(VecTy->getVectorNumElements() % Factor == 0 && 13750 "Invalid interleaved store"); 13751 13752 unsigned LaneLen = VecTy->getVectorNumElements() / Factor; 13753 Type *EltTy = VecTy->getVectorElementType(); 13754 VectorType *SubVecTy = VectorType::get(EltTy, LaneLen); 13755 13756 const DataLayout &DL = SI->getModule()->getDataLayout(); 13757 unsigned SubVecSize = DL.getTypeSizeInBits(SubVecTy); 13758 bool EltIs64Bits = DL.getTypeSizeInBits(EltTy) == 64; 13759 13760 // Skip if we do not have NEON and skip illegal vector types and vector types 13761 // with i64/f64 elements (vldN doesn't support i64/f64 elements). We can 13762 // "legalize" wide vector types into multiple interleaved accesses as long as 13763 // the vector types are divisible by 128. 13764 if (!Subtarget->hasNEON() || (SubVecSize != 64 && SubVecSize % 128 != 0) || 13765 EltIs64Bits) 13766 return false; 13767 13768 // Skip if the vector has f16 elements: even though we could do an i16 vldN, 13769 // we can't hold the f16 vectors and will end up converting via f32. 13770 if (EltTy->isHalfTy()) 13771 return false; 13772 13773 unsigned NumStores = getNumInterleavedAccesses(SubVecTy, DL); 13774 13775 Value *Op0 = SVI->getOperand(0); 13776 Value *Op1 = SVI->getOperand(1); 13777 IRBuilder<> Builder(SI); 13778 13779 // StN intrinsics don't support pointer vectors as arguments. Convert pointer 13780 // vectors to integer vectors. 13781 if (EltTy->isPointerTy()) { 13782 Type *IntTy = DL.getIntPtrType(EltTy); 13783 13784 // Convert to the corresponding integer vector. 13785 Type *IntVecTy = 13786 VectorType::get(IntTy, Op0->getType()->getVectorNumElements()); 13787 Op0 = Builder.CreatePtrToInt(Op0, IntVecTy); 13788 Op1 = Builder.CreatePtrToInt(Op1, IntVecTy); 13789 13790 SubVecTy = VectorType::get(IntTy, LaneLen); 13791 } 13792 13793 // The base address of the store. 13794 Value *BaseAddr = SI->getPointerOperand(); 13795 13796 if (NumStores > 1) { 13797 // If we're going to generate more than one store, reset the lane length 13798 // and sub-vector type to something legal. 13799 LaneLen /= NumStores; 13800 SubVecTy = VectorType::get(SubVecTy->getVectorElementType(), LaneLen); 13801 13802 // We will compute the pointer operand of each store from the original base 13803 // address using GEPs. Cast the base address to a pointer to the scalar 13804 // element type. 13805 BaseAddr = Builder.CreateBitCast( 13806 BaseAddr, SubVecTy->getVectorElementType()->getPointerTo( 13807 SI->getPointerAddressSpace())); 13808 } 13809 13810 assert(isTypeLegal(EVT::getEVT(SubVecTy)) && "Illegal vstN vector type!"); 13811 13812 auto Mask = SVI->getShuffleMask(); 13813 13814 Type *Int8Ptr = Builder.getInt8PtrTy(SI->getPointerAddressSpace()); 13815 Type *Tys[] = {Int8Ptr, SubVecTy}; 13816 static const Intrinsic::ID StoreInts[3] = {Intrinsic::arm_neon_vst2, 13817 Intrinsic::arm_neon_vst3, 13818 Intrinsic::arm_neon_vst4}; 13819 13820 for (unsigned StoreCount = 0; StoreCount < NumStores; ++StoreCount) { 13821 13822 // If we generating more than one store, we compute the base address of 13823 // subsequent stores as an offset from the previous. 13824 if (StoreCount > 0) 13825 BaseAddr = Builder.CreateConstGEP1_32(BaseAddr, LaneLen * Factor); 13826 13827 SmallVector<Value *, 6> Ops; 13828 Ops.push_back(Builder.CreateBitCast(BaseAddr, Int8Ptr)); 13829 13830 Function *VstNFunc = 13831 Intrinsic::getDeclaration(SI->getModule(), StoreInts[Factor - 2], Tys); 13832 13833 // Split the shufflevector operands into sub vectors for the new vstN call. 13834 for (unsigned i = 0; i < Factor; i++) { 13835 unsigned IdxI = StoreCount * LaneLen * Factor + i; 13836 if (Mask[IdxI] >= 0) { 13837 Ops.push_back(Builder.CreateShuffleVector( 13838 Op0, Op1, createSequentialMask(Builder, Mask[IdxI], LaneLen, 0))); 13839 } else { 13840 unsigned StartMask = 0; 13841 for (unsigned j = 1; j < LaneLen; j++) { 13842 unsigned IdxJ = StoreCount * LaneLen * Factor + j; 13843 if (Mask[IdxJ * Factor + IdxI] >= 0) { 13844 StartMask = Mask[IdxJ * Factor + IdxI] - IdxJ; 13845 break; 13846 } 13847 } 13848 // Note: If all elements in a chunk are undefs, StartMask=0! 13849 // Note: Filling undef gaps with random elements is ok, since 13850 // those elements were being written anyway (with undefs). 13851 // In the case of all undefs we're defaulting to using elems from 0 13852 // Note: StartMask cannot be negative, it's checked in 13853 // isReInterleaveMask 13854 Ops.push_back(Builder.CreateShuffleVector( 13855 Op0, Op1, createSequentialMask(Builder, StartMask, LaneLen, 0))); 13856 } 13857 } 13858 13859 Ops.push_back(Builder.getInt32(SI->getAlignment())); 13860 Builder.CreateCall(VstNFunc, Ops); 13861 } 13862 return true; 13863 } 13864 13865 enum HABaseType { 13866 HA_UNKNOWN = 0, 13867 HA_FLOAT, 13868 HA_DOUBLE, 13869 HA_VECT64, 13870 HA_VECT128 13871 }; 13872 13873 static bool isHomogeneousAggregate(Type *Ty, HABaseType &Base, 13874 uint64_t &Members) { 13875 if (auto *ST = dyn_cast<StructType>(Ty)) { 13876 for (unsigned i = 0; i < ST->getNumElements(); ++i) { 13877 uint64_t SubMembers = 0; 13878 if (!isHomogeneousAggregate(ST->getElementType(i), Base, SubMembers)) 13879 return false; 13880 Members += SubMembers; 13881 } 13882 } else if (auto *AT = dyn_cast<ArrayType>(Ty)) { 13883 uint64_t SubMembers = 0; 13884 if (!isHomogeneousAggregate(AT->getElementType(), Base, SubMembers)) 13885 return false; 13886 Members += SubMembers * AT->getNumElements(); 13887 } else if (Ty->isFloatTy()) { 13888 if (Base != HA_UNKNOWN && Base != HA_FLOAT) 13889 return false; 13890 Members = 1; 13891 Base = HA_FLOAT; 13892 } else if (Ty->isDoubleTy()) { 13893 if (Base != HA_UNKNOWN && Base != HA_DOUBLE) 13894 return false; 13895 Members = 1; 13896 Base = HA_DOUBLE; 13897 } else if (auto *VT = dyn_cast<VectorType>(Ty)) { 13898 Members = 1; 13899 switch (Base) { 13900 case HA_FLOAT: 13901 case HA_DOUBLE: 13902 return false; 13903 case HA_VECT64: 13904 return VT->getBitWidth() == 64; 13905 case HA_VECT128: 13906 return VT->getBitWidth() == 128; 13907 case HA_UNKNOWN: 13908 switch (VT->getBitWidth()) { 13909 case 64: 13910 Base = HA_VECT64; 13911 return true; 13912 case 128: 13913 Base = HA_VECT128; 13914 return true; 13915 default: 13916 return false; 13917 } 13918 } 13919 } 13920 13921 return (Members > 0 && Members <= 4); 13922 } 13923 13924 /// \brief Return true if a type is an AAPCS-VFP homogeneous aggregate or one of 13925 /// [N x i32] or [N x i64]. This allows front-ends to skip emitting padding when 13926 /// passing according to AAPCS rules. 13927 bool ARMTargetLowering::functionArgumentNeedsConsecutiveRegisters( 13928 Type *Ty, CallingConv::ID CallConv, bool isVarArg) const { 13929 if (getEffectiveCallingConv(CallConv, isVarArg) != 13930 CallingConv::ARM_AAPCS_VFP) 13931 return false; 13932 13933 HABaseType Base = HA_UNKNOWN; 13934 uint64_t Members = 0; 13935 bool IsHA = isHomogeneousAggregate(Ty, Base, Members); 13936 DEBUG(dbgs() << "isHA: " << IsHA << " "; Ty->dump()); 13937 13938 bool IsIntArray = Ty->isArrayTy() && Ty->getArrayElementType()->isIntegerTy(); 13939 return IsHA || IsIntArray; 13940 } 13941 13942 unsigned ARMTargetLowering::getExceptionPointerRegister( 13943 const Constant *PersonalityFn) const { 13944 // Platforms which do not use SjLj EH may return values in these registers 13945 // via the personality function. 13946 return Subtarget->useSjLjEH() ? ARM::NoRegister : ARM::R0; 13947 } 13948 13949 unsigned ARMTargetLowering::getExceptionSelectorRegister( 13950 const Constant *PersonalityFn) const { 13951 // Platforms which do not use SjLj EH may return values in these registers 13952 // via the personality function. 13953 return Subtarget->useSjLjEH() ? ARM::NoRegister : ARM::R1; 13954 } 13955 13956 void ARMTargetLowering::initializeSplitCSR(MachineBasicBlock *Entry) const { 13957 // Update IsSplitCSR in ARMFunctionInfo. 13958 ARMFunctionInfo *AFI = Entry->getParent()->getInfo<ARMFunctionInfo>(); 13959 AFI->setIsSplitCSR(true); 13960 } 13961 13962 void ARMTargetLowering::insertCopiesSplitCSR( 13963 MachineBasicBlock *Entry, 13964 const SmallVectorImpl<MachineBasicBlock *> &Exits) const { 13965 const ARMBaseRegisterInfo *TRI = Subtarget->getRegisterInfo(); 13966 const MCPhysReg *IStart = TRI->getCalleeSavedRegsViaCopy(Entry->getParent()); 13967 if (!IStart) 13968 return; 13969 13970 const TargetInstrInfo *TII = Subtarget->getInstrInfo(); 13971 MachineRegisterInfo *MRI = &Entry->getParent()->getRegInfo(); 13972 MachineBasicBlock::iterator MBBI = Entry->begin(); 13973 for (const MCPhysReg *I = IStart; *I; ++I) { 13974 const TargetRegisterClass *RC = nullptr; 13975 if (ARM::GPRRegClass.contains(*I)) 13976 RC = &ARM::GPRRegClass; 13977 else if (ARM::DPRRegClass.contains(*I)) 13978 RC = &ARM::DPRRegClass; 13979 else 13980 llvm_unreachable("Unexpected register class in CSRsViaCopy!"); 13981 13982 unsigned NewVR = MRI->createVirtualRegister(RC); 13983 // Create copy from CSR to a virtual register. 13984 // FIXME: this currently does not emit CFI pseudo-instructions, it works 13985 // fine for CXX_FAST_TLS since the C++-style TLS access functions should be 13986 // nounwind. If we want to generalize this later, we may need to emit 13987 // CFI pseudo-instructions. 13988 assert(Entry->getParent()->getFunction()->hasFnAttribute( 13989 Attribute::NoUnwind) && 13990 "Function should be nounwind in insertCopiesSplitCSR!"); 13991 Entry->addLiveIn(*I); 13992 BuildMI(*Entry, MBBI, DebugLoc(), TII->get(TargetOpcode::COPY), NewVR) 13993 .addReg(*I); 13994 13995 // Insert the copy-back instructions right before the terminator. 13996 for (auto *Exit : Exits) 13997 BuildMI(*Exit, Exit->getFirstTerminator(), DebugLoc(), 13998 TII->get(TargetOpcode::COPY), *I) 13999 .addReg(NewVR); 14000 } 14001 } 14002