1 //===-- ARMISelLowering.cpp - ARM DAG Lowering Implementation -------------===// 2 // 3 // The LLVM Compiler Infrastructure 4 // 5 // This file is distributed under the University of Illinois Open Source 6 // License. See LICENSE.TXT for details. 7 // 8 //===----------------------------------------------------------------------===// 9 // 10 // This file defines the interfaces that ARM uses to lower LLVM code into a 11 // selection DAG. 12 // 13 //===----------------------------------------------------------------------===// 14 15 #include "ARMISelLowering.h" 16 #include "ARMBaseInstrInfo.h" 17 #include "ARMBaseRegisterInfo.h" 18 #include "ARMCallingConv.h" 19 #include "ARMConstantPoolValue.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/STLExtras.h" 33 #include "llvm/ADT/SmallPtrSet.h" 34 #include "llvm/ADT/SmallVector.h" 35 #include "llvm/ADT/Statistic.h" 36 #include "llvm/ADT/StringExtras.h" 37 #include "llvm/ADT/StringRef.h" 38 #include "llvm/ADT/StringSwitch.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/DataLayout.h" 65 #include "llvm/IR/DebugLoc.h" 66 #include "llvm/IR/DerivedTypes.h" 67 #include "llvm/IR/Function.h" 68 #include "llvm/IR/GlobalAlias.h" 69 #include "llvm/IR/GlobalValue.h" 70 #include "llvm/IR/GlobalVariable.h" 71 #include "llvm/IR/IRBuilder.h" 72 #include "llvm/IR/InlineAsm.h" 73 #include "llvm/IR/Instruction.h" 74 #include "llvm/IR/Instructions.h" 75 #include "llvm/IR/IntrinsicInst.h" 76 #include "llvm/IR/Intrinsics.h" 77 #include "llvm/IR/Module.h" 78 #include "llvm/IR/Type.h" 79 #include "llvm/IR/User.h" 80 #include "llvm/IR/Value.h" 81 #include "llvm/MC/MCInstrDesc.h" 82 #include "llvm/MC/MCInstrItineraries.h" 83 #include "llvm/MC/MCRegisterInfo.h" 84 #include "llvm/MC/MCSchedule.h" 85 #include "llvm/Support/AtomicOrdering.h" 86 #include "llvm/Support/BranchProbability.h" 87 #include "llvm/Support/Casting.h" 88 #include "llvm/Support/CodeGen.h" 89 #include "llvm/Support/CommandLine.h" 90 #include "llvm/Support/Compiler.h" 91 #include "llvm/Support/Debug.h" 92 #include "llvm/Support/ErrorHandling.h" 93 #include "llvm/Support/KnownBits.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 <string> 106 #include <tuple> 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(false)); // FIXME: set to true by default once PR32780 is fixed 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 (auto Opcode : {ISD::ABS, 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 setBooleanContents(ZeroOrOneBooleanContent); 225 setBooleanVectorContents(ZeroOrNegativeOneBooleanContent); 226 227 if (!Subtarget->isTargetDarwin() && !Subtarget->isTargetIOS() && 228 !Subtarget->isTargetWatchOS()) { 229 const auto &E = Subtarget->getTargetTriple().getEnvironment(); 230 231 bool IsHFTarget = E == Triple::EABIHF || E == Triple::GNUEABIHF || 232 E == Triple::MuslEABIHF; 233 // Windows is a special case. Technically, we will replace all of the "GNU" 234 // calls with calls to MSVCRT if appropriate and adjust the calling 235 // convention then. 236 IsHFTarget = IsHFTarget || Subtarget->isTargetWindows(); 237 238 for (int LCID = 0; LCID < RTLIB::UNKNOWN_LIBCALL; ++LCID) 239 setLibcallCallingConv(static_cast<RTLIB::Libcall>(LCID), 240 IsHFTarget ? CallingConv::ARM_AAPCS_VFP 241 : CallingConv::ARM_AAPCS); 242 } 243 244 if (Subtarget->isTargetMachO()) { 245 // Uses VFP for Thumb libfuncs if available. 246 if (Subtarget->isThumb() && Subtarget->hasVFP2() && 247 Subtarget->hasARMOps() && !Subtarget->useSoftFloat()) { 248 static const struct { 249 const RTLIB::Libcall Op; 250 const char * const Name; 251 const ISD::CondCode Cond; 252 } LibraryCalls[] = { 253 // Single-precision floating-point arithmetic. 254 { RTLIB::ADD_F32, "__addsf3vfp", ISD::SETCC_INVALID }, 255 { RTLIB::SUB_F32, "__subsf3vfp", ISD::SETCC_INVALID }, 256 { RTLIB::MUL_F32, "__mulsf3vfp", ISD::SETCC_INVALID }, 257 { RTLIB::DIV_F32, "__divsf3vfp", ISD::SETCC_INVALID }, 258 259 // Double-precision floating-point arithmetic. 260 { RTLIB::ADD_F64, "__adddf3vfp", ISD::SETCC_INVALID }, 261 { RTLIB::SUB_F64, "__subdf3vfp", ISD::SETCC_INVALID }, 262 { RTLIB::MUL_F64, "__muldf3vfp", ISD::SETCC_INVALID }, 263 { RTLIB::DIV_F64, "__divdf3vfp", ISD::SETCC_INVALID }, 264 265 // Single-precision comparisons. 266 { RTLIB::OEQ_F32, "__eqsf2vfp", ISD::SETNE }, 267 { RTLIB::UNE_F32, "__nesf2vfp", ISD::SETNE }, 268 { RTLIB::OLT_F32, "__ltsf2vfp", ISD::SETNE }, 269 { RTLIB::OLE_F32, "__lesf2vfp", ISD::SETNE }, 270 { RTLIB::OGE_F32, "__gesf2vfp", ISD::SETNE }, 271 { RTLIB::OGT_F32, "__gtsf2vfp", ISD::SETNE }, 272 { RTLIB::UO_F32, "__unordsf2vfp", ISD::SETNE }, 273 { RTLIB::O_F32, "__unordsf2vfp", ISD::SETEQ }, 274 275 // Double-precision comparisons. 276 { RTLIB::OEQ_F64, "__eqdf2vfp", ISD::SETNE }, 277 { RTLIB::UNE_F64, "__nedf2vfp", ISD::SETNE }, 278 { RTLIB::OLT_F64, "__ltdf2vfp", ISD::SETNE }, 279 { RTLIB::OLE_F64, "__ledf2vfp", ISD::SETNE }, 280 { RTLIB::OGE_F64, "__gedf2vfp", ISD::SETNE }, 281 { RTLIB::OGT_F64, "__gtdf2vfp", ISD::SETNE }, 282 { RTLIB::UO_F64, "__unorddf2vfp", ISD::SETNE }, 283 { RTLIB::O_F64, "__unorddf2vfp", ISD::SETEQ }, 284 285 // Floating-point to integer conversions. 286 // i64 conversions are done via library routines even when generating VFP 287 // instructions, so use the same ones. 288 { RTLIB::FPTOSINT_F64_I32, "__fixdfsivfp", ISD::SETCC_INVALID }, 289 { RTLIB::FPTOUINT_F64_I32, "__fixunsdfsivfp", ISD::SETCC_INVALID }, 290 { RTLIB::FPTOSINT_F32_I32, "__fixsfsivfp", ISD::SETCC_INVALID }, 291 { RTLIB::FPTOUINT_F32_I32, "__fixunssfsivfp", ISD::SETCC_INVALID }, 292 293 // Conversions between floating types. 294 { RTLIB::FPROUND_F64_F32, "__truncdfsf2vfp", ISD::SETCC_INVALID }, 295 { RTLIB::FPEXT_F32_F64, "__extendsfdf2vfp", ISD::SETCC_INVALID }, 296 297 // Integer to floating-point conversions. 298 // i64 conversions are done via library routines even when generating VFP 299 // instructions, so use the same ones. 300 // FIXME: There appears to be some naming inconsistency in ARM libgcc: 301 // e.g., __floatunsidf vs. __floatunssidfvfp. 302 { RTLIB::SINTTOFP_I32_F64, "__floatsidfvfp", ISD::SETCC_INVALID }, 303 { RTLIB::UINTTOFP_I32_F64, "__floatunssidfvfp", ISD::SETCC_INVALID }, 304 { RTLIB::SINTTOFP_I32_F32, "__floatsisfvfp", ISD::SETCC_INVALID }, 305 { RTLIB::UINTTOFP_I32_F32, "__floatunssisfvfp", ISD::SETCC_INVALID }, 306 }; 307 308 for (const auto &LC : LibraryCalls) { 309 setLibcallName(LC.Op, LC.Name); 310 if (LC.Cond != ISD::SETCC_INVALID) 311 setCmpLibcallCC(LC.Op, LC.Cond); 312 } 313 } 314 315 // Set the correct calling convention for ARMv7k WatchOS. It's just 316 // AAPCS_VFP for functions as simple as libcalls. 317 if (Subtarget->isTargetWatchABI()) { 318 for (int i = 0; i < RTLIB::UNKNOWN_LIBCALL; ++i) 319 setLibcallCallingConv((RTLIB::Libcall)i, CallingConv::ARM_AAPCS_VFP); 320 } 321 } 322 323 // These libcalls are not available in 32-bit. 324 setLibcallName(RTLIB::SHL_I128, nullptr); 325 setLibcallName(RTLIB::SRL_I128, nullptr); 326 setLibcallName(RTLIB::SRA_I128, nullptr); 327 328 // RTLIB 329 if (Subtarget->isAAPCS_ABI() && 330 (Subtarget->isTargetAEABI() || Subtarget->isTargetGNUAEABI() || 331 Subtarget->isTargetMuslAEABI() || Subtarget->isTargetAndroid())) { 332 static const struct { 333 const RTLIB::Libcall Op; 334 const char * const Name; 335 const CallingConv::ID CC; 336 const ISD::CondCode Cond; 337 } LibraryCalls[] = { 338 // Double-precision floating-point arithmetic helper functions 339 // RTABI chapter 4.1.2, Table 2 340 { RTLIB::ADD_F64, "__aeabi_dadd", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 341 { RTLIB::DIV_F64, "__aeabi_ddiv", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 342 { RTLIB::MUL_F64, "__aeabi_dmul", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 343 { RTLIB::SUB_F64, "__aeabi_dsub", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 344 345 // Double-precision floating-point comparison helper functions 346 // RTABI chapter 4.1.2, Table 3 347 { RTLIB::OEQ_F64, "__aeabi_dcmpeq", CallingConv::ARM_AAPCS, ISD::SETNE }, 348 { RTLIB::UNE_F64, "__aeabi_dcmpeq", CallingConv::ARM_AAPCS, ISD::SETEQ }, 349 { RTLIB::OLT_F64, "__aeabi_dcmplt", CallingConv::ARM_AAPCS, ISD::SETNE }, 350 { RTLIB::OLE_F64, "__aeabi_dcmple", CallingConv::ARM_AAPCS, ISD::SETNE }, 351 { RTLIB::OGE_F64, "__aeabi_dcmpge", CallingConv::ARM_AAPCS, ISD::SETNE }, 352 { RTLIB::OGT_F64, "__aeabi_dcmpgt", CallingConv::ARM_AAPCS, ISD::SETNE }, 353 { RTLIB::UO_F64, "__aeabi_dcmpun", CallingConv::ARM_AAPCS, ISD::SETNE }, 354 { RTLIB::O_F64, "__aeabi_dcmpun", CallingConv::ARM_AAPCS, ISD::SETEQ }, 355 356 // Single-precision floating-point arithmetic helper functions 357 // RTABI chapter 4.1.2, Table 4 358 { RTLIB::ADD_F32, "__aeabi_fadd", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 359 { RTLIB::DIV_F32, "__aeabi_fdiv", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 360 { RTLIB::MUL_F32, "__aeabi_fmul", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 361 { RTLIB::SUB_F32, "__aeabi_fsub", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 362 363 // Single-precision floating-point comparison helper functions 364 // RTABI chapter 4.1.2, Table 5 365 { RTLIB::OEQ_F32, "__aeabi_fcmpeq", CallingConv::ARM_AAPCS, ISD::SETNE }, 366 { RTLIB::UNE_F32, "__aeabi_fcmpeq", CallingConv::ARM_AAPCS, ISD::SETEQ }, 367 { RTLIB::OLT_F32, "__aeabi_fcmplt", CallingConv::ARM_AAPCS, ISD::SETNE }, 368 { RTLIB::OLE_F32, "__aeabi_fcmple", CallingConv::ARM_AAPCS, ISD::SETNE }, 369 { RTLIB::OGE_F32, "__aeabi_fcmpge", CallingConv::ARM_AAPCS, ISD::SETNE }, 370 { RTLIB::OGT_F32, "__aeabi_fcmpgt", CallingConv::ARM_AAPCS, ISD::SETNE }, 371 { RTLIB::UO_F32, "__aeabi_fcmpun", CallingConv::ARM_AAPCS, ISD::SETNE }, 372 { RTLIB::O_F32, "__aeabi_fcmpun", CallingConv::ARM_AAPCS, ISD::SETEQ }, 373 374 // Floating-point to integer conversions. 375 // RTABI chapter 4.1.2, Table 6 376 { RTLIB::FPTOSINT_F64_I32, "__aeabi_d2iz", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 377 { RTLIB::FPTOUINT_F64_I32, "__aeabi_d2uiz", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 378 { RTLIB::FPTOSINT_F64_I64, "__aeabi_d2lz", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 379 { RTLIB::FPTOUINT_F64_I64, "__aeabi_d2ulz", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 380 { RTLIB::FPTOSINT_F32_I32, "__aeabi_f2iz", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 381 { RTLIB::FPTOUINT_F32_I32, "__aeabi_f2uiz", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 382 { RTLIB::FPTOSINT_F32_I64, "__aeabi_f2lz", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 383 { RTLIB::FPTOUINT_F32_I64, "__aeabi_f2ulz", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 384 385 // Conversions between floating types. 386 // RTABI chapter 4.1.2, Table 7 387 { RTLIB::FPROUND_F64_F32, "__aeabi_d2f", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 388 { RTLIB::FPROUND_F64_F16, "__aeabi_d2h", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 389 { RTLIB::FPEXT_F32_F64, "__aeabi_f2d", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 390 391 // Integer to floating-point conversions. 392 // RTABI chapter 4.1.2, Table 8 393 { RTLIB::SINTTOFP_I32_F64, "__aeabi_i2d", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 394 { RTLIB::UINTTOFP_I32_F64, "__aeabi_ui2d", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 395 { RTLIB::SINTTOFP_I64_F64, "__aeabi_l2d", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 396 { RTLIB::UINTTOFP_I64_F64, "__aeabi_ul2d", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 397 { RTLIB::SINTTOFP_I32_F32, "__aeabi_i2f", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 398 { RTLIB::UINTTOFP_I32_F32, "__aeabi_ui2f", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 399 { RTLIB::SINTTOFP_I64_F32, "__aeabi_l2f", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 400 { RTLIB::UINTTOFP_I64_F32, "__aeabi_ul2f", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 401 402 // Long long helper functions 403 // RTABI chapter 4.2, Table 9 404 { RTLIB::MUL_I64, "__aeabi_lmul", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 405 { RTLIB::SHL_I64, "__aeabi_llsl", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 406 { RTLIB::SRL_I64, "__aeabi_llsr", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 407 { RTLIB::SRA_I64, "__aeabi_lasr", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 408 409 // Integer division functions 410 // RTABI chapter 4.3.1 411 { RTLIB::SDIV_I8, "__aeabi_idiv", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 412 { RTLIB::SDIV_I16, "__aeabi_idiv", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 413 { RTLIB::SDIV_I32, "__aeabi_idiv", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 414 { RTLIB::SDIV_I64, "__aeabi_ldivmod", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 415 { RTLIB::UDIV_I8, "__aeabi_uidiv", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 416 { RTLIB::UDIV_I16, "__aeabi_uidiv", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 417 { RTLIB::UDIV_I32, "__aeabi_uidiv", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 418 { RTLIB::UDIV_I64, "__aeabi_uldivmod", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 419 }; 420 421 for (const auto &LC : LibraryCalls) { 422 setLibcallName(LC.Op, LC.Name); 423 setLibcallCallingConv(LC.Op, LC.CC); 424 if (LC.Cond != ISD::SETCC_INVALID) 425 setCmpLibcallCC(LC.Op, LC.Cond); 426 } 427 428 // EABI dependent RTLIB 429 if (TM.Options.EABIVersion == EABI::EABI4 || 430 TM.Options.EABIVersion == EABI::EABI5) { 431 static const struct { 432 const RTLIB::Libcall Op; 433 const char *const Name; 434 const CallingConv::ID CC; 435 const ISD::CondCode Cond; 436 } MemOpsLibraryCalls[] = { 437 // Memory operations 438 // RTABI chapter 4.3.4 439 { RTLIB::MEMCPY, "__aeabi_memcpy", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 440 { RTLIB::MEMMOVE, "__aeabi_memmove", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 441 { RTLIB::MEMSET, "__aeabi_memset", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 442 }; 443 444 for (const auto &LC : MemOpsLibraryCalls) { 445 setLibcallName(LC.Op, LC.Name); 446 setLibcallCallingConv(LC.Op, LC.CC); 447 if (LC.Cond != ISD::SETCC_INVALID) 448 setCmpLibcallCC(LC.Op, LC.Cond); 449 } 450 } 451 } 452 453 if (Subtarget->isTargetWindows()) { 454 static const struct { 455 const RTLIB::Libcall Op; 456 const char * const Name; 457 const CallingConv::ID CC; 458 } LibraryCalls[] = { 459 { RTLIB::FPTOSINT_F32_I64, "__stoi64", CallingConv::ARM_AAPCS_VFP }, 460 { RTLIB::FPTOSINT_F64_I64, "__dtoi64", CallingConv::ARM_AAPCS_VFP }, 461 { RTLIB::FPTOUINT_F32_I64, "__stou64", CallingConv::ARM_AAPCS_VFP }, 462 { RTLIB::FPTOUINT_F64_I64, "__dtou64", CallingConv::ARM_AAPCS_VFP }, 463 { RTLIB::SINTTOFP_I64_F32, "__i64tos", CallingConv::ARM_AAPCS_VFP }, 464 { RTLIB::SINTTOFP_I64_F64, "__i64tod", CallingConv::ARM_AAPCS_VFP }, 465 { RTLIB::UINTTOFP_I64_F32, "__u64tos", CallingConv::ARM_AAPCS_VFP }, 466 { RTLIB::UINTTOFP_I64_F64, "__u64tod", CallingConv::ARM_AAPCS_VFP }, 467 }; 468 469 for (const auto &LC : LibraryCalls) { 470 setLibcallName(LC.Op, LC.Name); 471 setLibcallCallingConv(LC.Op, LC.CC); 472 } 473 } 474 475 // Use divmod compiler-rt calls for iOS 5.0 and later. 476 if (Subtarget->isTargetMachO() && 477 !(Subtarget->isTargetIOS() && 478 Subtarget->getTargetTriple().isOSVersionLT(5, 0))) { 479 setLibcallName(RTLIB::SDIVREM_I32, "__divmodsi4"); 480 setLibcallName(RTLIB::UDIVREM_I32, "__udivmodsi4"); 481 } 482 483 // The half <-> float conversion functions are always soft-float on 484 // non-watchos platforms, but are needed for some targets which use a 485 // hard-float calling convention by default. 486 if (!Subtarget->isTargetWatchABI()) { 487 if (Subtarget->isAAPCS_ABI()) { 488 setLibcallCallingConv(RTLIB::FPROUND_F32_F16, CallingConv::ARM_AAPCS); 489 setLibcallCallingConv(RTLIB::FPROUND_F64_F16, CallingConv::ARM_AAPCS); 490 setLibcallCallingConv(RTLIB::FPEXT_F16_F32, CallingConv::ARM_AAPCS); 491 } else { 492 setLibcallCallingConv(RTLIB::FPROUND_F32_F16, CallingConv::ARM_APCS); 493 setLibcallCallingConv(RTLIB::FPROUND_F64_F16, CallingConv::ARM_APCS); 494 setLibcallCallingConv(RTLIB::FPEXT_F16_F32, CallingConv::ARM_APCS); 495 } 496 } 497 498 // In EABI, these functions have an __aeabi_ prefix, but in GNUEABI they have 499 // a __gnu_ prefix (which is the default). 500 if (Subtarget->isTargetAEABI()) { 501 static const struct { 502 const RTLIB::Libcall Op; 503 const char * const Name; 504 const CallingConv::ID CC; 505 } LibraryCalls[] = { 506 { RTLIB::FPROUND_F32_F16, "__aeabi_f2h", CallingConv::ARM_AAPCS }, 507 { RTLIB::FPROUND_F64_F16, "__aeabi_d2h", CallingConv::ARM_AAPCS }, 508 { RTLIB::FPEXT_F16_F32, "__aeabi_h2f", CallingConv::ARM_AAPCS }, 509 }; 510 511 for (const auto &LC : LibraryCalls) { 512 setLibcallName(LC.Op, LC.Name); 513 setLibcallCallingConv(LC.Op, LC.CC); 514 } 515 } 516 517 if (Subtarget->isThumb1Only()) 518 addRegisterClass(MVT::i32, &ARM::tGPRRegClass); 519 else 520 addRegisterClass(MVT::i32, &ARM::GPRRegClass); 521 522 if (!Subtarget->useSoftFloat() && Subtarget->hasVFP2() && 523 !Subtarget->isThumb1Only()) { 524 addRegisterClass(MVT::f32, &ARM::SPRRegClass); 525 addRegisterClass(MVT::f64, &ARM::DPRRegClass); 526 } 527 528 for (MVT VT : MVT::vector_valuetypes()) { 529 for (MVT InnerVT : MVT::vector_valuetypes()) { 530 setTruncStoreAction(VT, InnerVT, Expand); 531 setLoadExtAction(ISD::SEXTLOAD, VT, InnerVT, Expand); 532 setLoadExtAction(ISD::ZEXTLOAD, VT, InnerVT, Expand); 533 setLoadExtAction(ISD::EXTLOAD, VT, InnerVT, Expand); 534 } 535 536 setOperationAction(ISD::MULHS, VT, Expand); 537 setOperationAction(ISD::SMUL_LOHI, VT, Expand); 538 setOperationAction(ISD::MULHU, VT, Expand); 539 setOperationAction(ISD::UMUL_LOHI, VT, Expand); 540 541 setOperationAction(ISD::BSWAP, VT, Expand); 542 } 543 544 setOperationAction(ISD::ConstantFP, MVT::f32, Custom); 545 setOperationAction(ISD::ConstantFP, MVT::f64, Custom); 546 547 setOperationAction(ISD::READ_REGISTER, MVT::i64, Custom); 548 setOperationAction(ISD::WRITE_REGISTER, MVT::i64, Custom); 549 550 if (Subtarget->hasNEON()) { 551 addDRTypeForNEON(MVT::v2f32); 552 addDRTypeForNEON(MVT::v8i8); 553 addDRTypeForNEON(MVT::v4i16); 554 addDRTypeForNEON(MVT::v2i32); 555 addDRTypeForNEON(MVT::v1i64); 556 557 addQRTypeForNEON(MVT::v4f32); 558 addQRTypeForNEON(MVT::v2f64); 559 addQRTypeForNEON(MVT::v16i8); 560 addQRTypeForNEON(MVT::v8i16); 561 addQRTypeForNEON(MVT::v4i32); 562 addQRTypeForNEON(MVT::v2i64); 563 564 // v2f64 is legal so that QR subregs can be extracted as f64 elements, but 565 // neither Neon nor VFP support any arithmetic operations on it. 566 // The same with v4f32. But keep in mind that vadd, vsub, vmul are natively 567 // supported for v4f32. 568 setOperationAction(ISD::FADD, MVT::v2f64, Expand); 569 setOperationAction(ISD::FSUB, MVT::v2f64, Expand); 570 setOperationAction(ISD::FMUL, MVT::v2f64, Expand); 571 // FIXME: Code duplication: FDIV and FREM are expanded always, see 572 // ARMTargetLowering::addTypeForNEON method for details. 573 setOperationAction(ISD::FDIV, MVT::v2f64, Expand); 574 setOperationAction(ISD::FREM, MVT::v2f64, Expand); 575 // FIXME: Create unittest. 576 // In another words, find a way when "copysign" appears in DAG with vector 577 // operands. 578 setOperationAction(ISD::FCOPYSIGN, MVT::v2f64, Expand); 579 // FIXME: Code duplication: SETCC has custom operation action, see 580 // ARMTargetLowering::addTypeForNEON method for details. 581 setOperationAction(ISD::SETCC, MVT::v2f64, Expand); 582 // FIXME: Create unittest for FNEG and for FABS. 583 setOperationAction(ISD::FNEG, MVT::v2f64, Expand); 584 setOperationAction(ISD::FABS, MVT::v2f64, Expand); 585 setOperationAction(ISD::FSQRT, MVT::v2f64, Expand); 586 setOperationAction(ISD::FSIN, MVT::v2f64, Expand); 587 setOperationAction(ISD::FCOS, 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::FPOW, MVT::v4f32, Expand); 606 setOperationAction(ISD::FLOG, MVT::v4f32, Expand); 607 setOperationAction(ISD::FLOG2, MVT::v4f32, Expand); 608 setOperationAction(ISD::FLOG10, MVT::v4f32, Expand); 609 setOperationAction(ISD::FEXP, MVT::v4f32, Expand); 610 setOperationAction(ISD::FEXP2, MVT::v4f32, Expand); 611 setOperationAction(ISD::FCEIL, MVT::v4f32, Expand); 612 setOperationAction(ISD::FTRUNC, MVT::v4f32, Expand); 613 setOperationAction(ISD::FRINT, MVT::v4f32, Expand); 614 setOperationAction(ISD::FNEARBYINT, MVT::v4f32, Expand); 615 setOperationAction(ISD::FFLOOR, MVT::v4f32, Expand); 616 617 // Mark v2f32 intrinsics. 618 setOperationAction(ISD::FSQRT, MVT::v2f32, Expand); 619 setOperationAction(ISD::FSIN, MVT::v2f32, Expand); 620 setOperationAction(ISD::FCOS, MVT::v2f32, Expand); 621 setOperationAction(ISD::FPOW, MVT::v2f32, Expand); 622 setOperationAction(ISD::FLOG, MVT::v2f32, Expand); 623 setOperationAction(ISD::FLOG2, MVT::v2f32, Expand); 624 setOperationAction(ISD::FLOG10, MVT::v2f32, Expand); 625 setOperationAction(ISD::FEXP, MVT::v2f32, Expand); 626 setOperationAction(ISD::FEXP2, MVT::v2f32, Expand); 627 setOperationAction(ISD::FCEIL, MVT::v2f32, Expand); 628 setOperationAction(ISD::FTRUNC, MVT::v2f32, Expand); 629 setOperationAction(ISD::FRINT, MVT::v2f32, Expand); 630 setOperationAction(ISD::FNEARBYINT, MVT::v2f32, Expand); 631 setOperationAction(ISD::FFLOOR, MVT::v2f32, Expand); 632 633 // Neon does not support some operations on v1i64 and v2i64 types. 634 setOperationAction(ISD::MUL, MVT::v1i64, Expand); 635 // Custom handling for some quad-vector types to detect VMULL. 636 setOperationAction(ISD::MUL, MVT::v8i16, Custom); 637 setOperationAction(ISD::MUL, MVT::v4i32, Custom); 638 setOperationAction(ISD::MUL, MVT::v2i64, Custom); 639 // Custom handling for some vector types to avoid expensive expansions 640 setOperationAction(ISD::SDIV, MVT::v4i16, Custom); 641 setOperationAction(ISD::SDIV, MVT::v8i8, Custom); 642 setOperationAction(ISD::UDIV, MVT::v4i16, Custom); 643 setOperationAction(ISD::UDIV, MVT::v8i8, Custom); 644 // Neon does not have single instruction SINT_TO_FP and UINT_TO_FP with 645 // a destination type that is wider than the source, and nor does 646 // it have a FP_TO_[SU]INT instruction with a narrower destination than 647 // source. 648 setOperationAction(ISD::SINT_TO_FP, MVT::v4i16, Custom); 649 setOperationAction(ISD::UINT_TO_FP, MVT::v4i16, Custom); 650 setOperationAction(ISD::FP_TO_UINT, MVT::v4i16, Custom); 651 setOperationAction(ISD::FP_TO_SINT, MVT::v4i16, Custom); 652 653 setOperationAction(ISD::FP_ROUND, MVT::v2f32, Expand); 654 setOperationAction(ISD::FP_EXTEND, MVT::v2f64, Expand); 655 656 // NEON does not have single instruction CTPOP for vectors with element 657 // types wider than 8-bits. However, custom lowering can leverage the 658 // v8i8/v16i8 vcnt instruction. 659 setOperationAction(ISD::CTPOP, MVT::v2i32, Custom); 660 setOperationAction(ISD::CTPOP, MVT::v4i32, Custom); 661 setOperationAction(ISD::CTPOP, MVT::v4i16, Custom); 662 setOperationAction(ISD::CTPOP, MVT::v8i16, Custom); 663 setOperationAction(ISD::CTPOP, MVT::v1i64, Expand); 664 setOperationAction(ISD::CTPOP, MVT::v2i64, Expand); 665 666 setOperationAction(ISD::CTLZ, MVT::v1i64, Expand); 667 setOperationAction(ISD::CTLZ, MVT::v2i64, Expand); 668 669 // NEON does not have single instruction CTTZ for vectors. 670 setOperationAction(ISD::CTTZ, MVT::v8i8, Custom); 671 setOperationAction(ISD::CTTZ, MVT::v4i16, Custom); 672 setOperationAction(ISD::CTTZ, MVT::v2i32, Custom); 673 setOperationAction(ISD::CTTZ, MVT::v1i64, Custom); 674 675 setOperationAction(ISD::CTTZ, MVT::v16i8, Custom); 676 setOperationAction(ISD::CTTZ, MVT::v8i16, Custom); 677 setOperationAction(ISD::CTTZ, MVT::v4i32, Custom); 678 setOperationAction(ISD::CTTZ, MVT::v2i64, Custom); 679 680 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::v8i8, Custom); 681 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::v4i16, Custom); 682 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::v2i32, Custom); 683 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::v1i64, Custom); 684 685 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::v16i8, Custom); 686 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::v8i16, Custom); 687 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::v4i32, Custom); 688 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::v2i64, Custom); 689 690 // NEON only has FMA instructions as of VFP4. 691 if (!Subtarget->hasVFP4()) { 692 setOperationAction(ISD::FMA, MVT::v2f32, Expand); 693 setOperationAction(ISD::FMA, MVT::v4f32, Expand); 694 } 695 696 setTargetDAGCombine(ISD::INTRINSIC_VOID); 697 setTargetDAGCombine(ISD::INTRINSIC_W_CHAIN); 698 setTargetDAGCombine(ISD::INTRINSIC_WO_CHAIN); 699 setTargetDAGCombine(ISD::SHL); 700 setTargetDAGCombine(ISD::SRL); 701 setTargetDAGCombine(ISD::SRA); 702 setTargetDAGCombine(ISD::SIGN_EXTEND); 703 setTargetDAGCombine(ISD::ZERO_EXTEND); 704 setTargetDAGCombine(ISD::ANY_EXTEND); 705 setTargetDAGCombine(ISD::BUILD_VECTOR); 706 setTargetDAGCombine(ISD::VECTOR_SHUFFLE); 707 setTargetDAGCombine(ISD::INSERT_VECTOR_ELT); 708 setTargetDAGCombine(ISD::STORE); 709 setTargetDAGCombine(ISD::FP_TO_SINT); 710 setTargetDAGCombine(ISD::FP_TO_UINT); 711 setTargetDAGCombine(ISD::FDIV); 712 setTargetDAGCombine(ISD::LOAD); 713 714 // It is legal to extload from v4i8 to v4i16 or v4i32. 715 for (MVT Ty : {MVT::v8i8, MVT::v4i8, MVT::v2i8, MVT::v4i16, MVT::v2i16, 716 MVT::v2i32}) { 717 for (MVT VT : MVT::integer_vector_valuetypes()) { 718 setLoadExtAction(ISD::EXTLOAD, VT, Ty, Legal); 719 setLoadExtAction(ISD::ZEXTLOAD, VT, Ty, Legal); 720 setLoadExtAction(ISD::SEXTLOAD, VT, Ty, Legal); 721 } 722 } 723 } 724 725 if (Subtarget->isFPOnlySP()) { 726 // When targeting a floating-point unit with only single-precision 727 // operations, f64 is legal for the few double-precision instructions which 728 // are present However, no double-precision operations other than moves, 729 // loads and stores are provided by the hardware. 730 setOperationAction(ISD::FADD, MVT::f64, Expand); 731 setOperationAction(ISD::FSUB, MVT::f64, Expand); 732 setOperationAction(ISD::FMUL, MVT::f64, Expand); 733 setOperationAction(ISD::FMA, MVT::f64, Expand); 734 setOperationAction(ISD::FDIV, MVT::f64, Expand); 735 setOperationAction(ISD::FREM, MVT::f64, Expand); 736 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand); 737 setOperationAction(ISD::FGETSIGN, MVT::f64, Expand); 738 setOperationAction(ISD::FNEG, MVT::f64, Expand); 739 setOperationAction(ISD::FABS, MVT::f64, Expand); 740 setOperationAction(ISD::FSQRT, MVT::f64, Expand); 741 setOperationAction(ISD::FSIN, MVT::f64, Expand); 742 setOperationAction(ISD::FCOS, MVT::f64, Expand); 743 setOperationAction(ISD::FPOW, MVT::f64, Expand); 744 setOperationAction(ISD::FLOG, MVT::f64, Expand); 745 setOperationAction(ISD::FLOG2, MVT::f64, Expand); 746 setOperationAction(ISD::FLOG10, MVT::f64, Expand); 747 setOperationAction(ISD::FEXP, MVT::f64, Expand); 748 setOperationAction(ISD::FEXP2, MVT::f64, Expand); 749 setOperationAction(ISD::FCEIL, MVT::f64, Expand); 750 setOperationAction(ISD::FTRUNC, MVT::f64, Expand); 751 setOperationAction(ISD::FRINT, MVT::f64, Expand); 752 setOperationAction(ISD::FNEARBYINT, MVT::f64, Expand); 753 setOperationAction(ISD::FFLOOR, MVT::f64, Expand); 754 setOperationAction(ISD::SINT_TO_FP, MVT::i32, Custom); 755 setOperationAction(ISD::UINT_TO_FP, MVT::i32, Custom); 756 setOperationAction(ISD::FP_TO_SINT, MVT::i32, Custom); 757 setOperationAction(ISD::FP_TO_UINT, MVT::i32, Custom); 758 setOperationAction(ISD::FP_TO_SINT, MVT::f64, Custom); 759 setOperationAction(ISD::FP_TO_UINT, MVT::f64, Custom); 760 setOperationAction(ISD::FP_ROUND, MVT::f32, Custom); 761 setOperationAction(ISD::FP_EXTEND, MVT::f64, Custom); 762 } 763 764 computeRegisterProperties(Subtarget->getRegisterInfo()); 765 766 // ARM does not have floating-point extending loads. 767 for (MVT VT : MVT::fp_valuetypes()) { 768 setLoadExtAction(ISD::EXTLOAD, VT, MVT::f32, Expand); 769 setLoadExtAction(ISD::EXTLOAD, VT, MVT::f16, Expand); 770 } 771 772 // ... or truncating stores 773 setTruncStoreAction(MVT::f64, MVT::f32, Expand); 774 setTruncStoreAction(MVT::f32, MVT::f16, Expand); 775 setTruncStoreAction(MVT::f64, MVT::f16, Expand); 776 777 // ARM does not have i1 sign extending load. 778 for (MVT VT : MVT::integer_valuetypes()) 779 setLoadExtAction(ISD::SEXTLOAD, VT, MVT::i1, Promote); 780 781 // ARM supports all 4 flavors of integer indexed load / store. 782 if (!Subtarget->isThumb1Only()) { 783 for (unsigned im = (unsigned)ISD::PRE_INC; 784 im != (unsigned)ISD::LAST_INDEXED_MODE; ++im) { 785 setIndexedLoadAction(im, MVT::i1, Legal); 786 setIndexedLoadAction(im, MVT::i8, Legal); 787 setIndexedLoadAction(im, MVT::i16, Legal); 788 setIndexedLoadAction(im, MVT::i32, Legal); 789 setIndexedStoreAction(im, MVT::i1, Legal); 790 setIndexedStoreAction(im, MVT::i8, Legal); 791 setIndexedStoreAction(im, MVT::i16, Legal); 792 setIndexedStoreAction(im, MVT::i32, Legal); 793 } 794 } else { 795 // Thumb-1 has limited post-inc load/store support - LDM r0!, {r1}. 796 setIndexedLoadAction(ISD::POST_INC, MVT::i32, Legal); 797 setIndexedStoreAction(ISD::POST_INC, MVT::i32, Legal); 798 } 799 800 setOperationAction(ISD::SADDO, MVT::i32, Custom); 801 setOperationAction(ISD::UADDO, MVT::i32, Custom); 802 setOperationAction(ISD::SSUBO, MVT::i32, Custom); 803 setOperationAction(ISD::USUBO, MVT::i32, Custom); 804 805 // i64 operation support. 806 setOperationAction(ISD::MUL, MVT::i64, Expand); 807 setOperationAction(ISD::MULHU, MVT::i32, Expand); 808 if (Subtarget->isThumb1Only()) { 809 setOperationAction(ISD::UMUL_LOHI, MVT::i32, Expand); 810 setOperationAction(ISD::SMUL_LOHI, MVT::i32, Expand); 811 } 812 if (Subtarget->isThumb1Only() || !Subtarget->hasV6Ops() 813 || (Subtarget->isThumb2() && !Subtarget->hasDSP())) 814 setOperationAction(ISD::MULHS, MVT::i32, Expand); 815 816 setOperationAction(ISD::SHL_PARTS, MVT::i32, Custom); 817 setOperationAction(ISD::SRA_PARTS, MVT::i32, Custom); 818 setOperationAction(ISD::SRL_PARTS, MVT::i32, Custom); 819 setOperationAction(ISD::SRL, MVT::i64, Custom); 820 setOperationAction(ISD::SRA, MVT::i64, Custom); 821 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::i64, Custom); 822 823 setOperationAction(ISD::ADDC, MVT::i32, Custom); 824 setOperationAction(ISD::ADDE, MVT::i32, Custom); 825 setOperationAction(ISD::SUBC, MVT::i32, Custom); 826 setOperationAction(ISD::SUBE, MVT::i32, Custom); 827 828 if (!Subtarget->isThumb1Only() && Subtarget->hasV6T2Ops()) 829 setOperationAction(ISD::BITREVERSE, MVT::i32, Legal); 830 831 // ARM does not have ROTL. 832 setOperationAction(ISD::ROTL, MVT::i32, Expand); 833 for (MVT VT : MVT::vector_valuetypes()) { 834 setOperationAction(ISD::ROTL, VT, Expand); 835 setOperationAction(ISD::ROTR, VT, Expand); 836 } 837 setOperationAction(ISD::CTTZ, MVT::i32, Custom); 838 setOperationAction(ISD::CTPOP, MVT::i32, Expand); 839 if (!Subtarget->hasV5TOps() || Subtarget->isThumb1Only()) 840 setOperationAction(ISD::CTLZ, MVT::i32, Expand); 841 842 // @llvm.readcyclecounter requires the Performance Monitors extension. 843 // Default to the 0 expansion on unsupported platforms. 844 // FIXME: Technically there are older ARM CPUs that have 845 // implementation-specific ways of obtaining this information. 846 if (Subtarget->hasPerfMon()) 847 setOperationAction(ISD::READCYCLECOUNTER, MVT::i64, Custom); 848 849 // Only ARMv6 has BSWAP. 850 if (!Subtarget->hasV6Ops()) 851 setOperationAction(ISD::BSWAP, MVT::i32, Expand); 852 853 bool hasDivide = Subtarget->isThumb() ? Subtarget->hasDivideInThumbMode() 854 : Subtarget->hasDivideInARMMode(); 855 if (!hasDivide) { 856 // These are expanded into libcalls if the cpu doesn't have HW divider. 857 setOperationAction(ISD::SDIV, MVT::i32, LibCall); 858 setOperationAction(ISD::UDIV, MVT::i32, LibCall); 859 } 860 861 if (Subtarget->isTargetWindows() && !Subtarget->hasDivideInThumbMode()) { 862 setOperationAction(ISD::SDIV, MVT::i32, Custom); 863 setOperationAction(ISD::UDIV, MVT::i32, Custom); 864 865 setOperationAction(ISD::SDIV, MVT::i64, Custom); 866 setOperationAction(ISD::UDIV, MVT::i64, Custom); 867 } 868 869 setOperationAction(ISD::SREM, MVT::i32, Expand); 870 setOperationAction(ISD::UREM, MVT::i32, Expand); 871 872 // Register based DivRem for AEABI (RTABI 4.2) 873 if (Subtarget->isTargetAEABI() || Subtarget->isTargetAndroid() || 874 Subtarget->isTargetGNUAEABI() || Subtarget->isTargetMuslAEABI() || 875 Subtarget->isTargetWindows()) { 876 setOperationAction(ISD::SREM, MVT::i64, Custom); 877 setOperationAction(ISD::UREM, MVT::i64, Custom); 878 HasStandaloneRem = false; 879 880 if (Subtarget->isTargetWindows()) { 881 const struct { 882 const RTLIB::Libcall Op; 883 const char * const Name; 884 const CallingConv::ID CC; 885 } LibraryCalls[] = { 886 { RTLIB::SDIVREM_I8, "__rt_sdiv", CallingConv::ARM_AAPCS }, 887 { RTLIB::SDIVREM_I16, "__rt_sdiv", CallingConv::ARM_AAPCS }, 888 { RTLIB::SDIVREM_I32, "__rt_sdiv", CallingConv::ARM_AAPCS }, 889 { RTLIB::SDIVREM_I64, "__rt_sdiv64", CallingConv::ARM_AAPCS }, 890 891 { RTLIB::UDIVREM_I8, "__rt_udiv", CallingConv::ARM_AAPCS }, 892 { RTLIB::UDIVREM_I16, "__rt_udiv", CallingConv::ARM_AAPCS }, 893 { RTLIB::UDIVREM_I32, "__rt_udiv", CallingConv::ARM_AAPCS }, 894 { RTLIB::UDIVREM_I64, "__rt_udiv64", CallingConv::ARM_AAPCS }, 895 }; 896 897 for (const auto &LC : LibraryCalls) { 898 setLibcallName(LC.Op, LC.Name); 899 setLibcallCallingConv(LC.Op, LC.CC); 900 } 901 } else { 902 const struct { 903 const RTLIB::Libcall Op; 904 const char * const Name; 905 const CallingConv::ID CC; 906 } LibraryCalls[] = { 907 { RTLIB::SDIVREM_I8, "__aeabi_idivmod", CallingConv::ARM_AAPCS }, 908 { RTLIB::SDIVREM_I16, "__aeabi_idivmod", CallingConv::ARM_AAPCS }, 909 { RTLIB::SDIVREM_I32, "__aeabi_idivmod", CallingConv::ARM_AAPCS }, 910 { RTLIB::SDIVREM_I64, "__aeabi_ldivmod", CallingConv::ARM_AAPCS }, 911 912 { RTLIB::UDIVREM_I8, "__aeabi_uidivmod", CallingConv::ARM_AAPCS }, 913 { RTLIB::UDIVREM_I16, "__aeabi_uidivmod", CallingConv::ARM_AAPCS }, 914 { RTLIB::UDIVREM_I32, "__aeabi_uidivmod", CallingConv::ARM_AAPCS }, 915 { RTLIB::UDIVREM_I64, "__aeabi_uldivmod", CallingConv::ARM_AAPCS }, 916 }; 917 918 for (const auto &LC : LibraryCalls) { 919 setLibcallName(LC.Op, LC.Name); 920 setLibcallCallingConv(LC.Op, LC.CC); 921 } 922 } 923 924 setOperationAction(ISD::SDIVREM, MVT::i32, Custom); 925 setOperationAction(ISD::UDIVREM, MVT::i32, Custom); 926 setOperationAction(ISD::SDIVREM, MVT::i64, Custom); 927 setOperationAction(ISD::UDIVREM, MVT::i64, Custom); 928 } else { 929 setOperationAction(ISD::SDIVREM, MVT::i32, Expand); 930 setOperationAction(ISD::UDIVREM, MVT::i32, Expand); 931 } 932 933 if (Subtarget->isTargetWindows() && Subtarget->getTargetTriple().isOSMSVCRT()) 934 for (auto &VT : {MVT::f32, MVT::f64}) 935 setOperationAction(ISD::FPOWI, VT, Custom); 936 937 setOperationAction(ISD::GlobalAddress, MVT::i32, Custom); 938 setOperationAction(ISD::ConstantPool, MVT::i32, Custom); 939 setOperationAction(ISD::GlobalTLSAddress, MVT::i32, Custom); 940 setOperationAction(ISD::BlockAddress, MVT::i32, Custom); 941 942 setOperationAction(ISD::TRAP, MVT::Other, Legal); 943 944 // Use the default implementation. 945 setOperationAction(ISD::VASTART, MVT::Other, Custom); 946 setOperationAction(ISD::VAARG, MVT::Other, Expand); 947 setOperationAction(ISD::VACOPY, MVT::Other, Expand); 948 setOperationAction(ISD::VAEND, MVT::Other, Expand); 949 setOperationAction(ISD::STACKSAVE, MVT::Other, Expand); 950 setOperationAction(ISD::STACKRESTORE, MVT::Other, Expand); 951 952 if (Subtarget->getTargetTriple().isWindowsItaniumEnvironment()) 953 setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i32, Custom); 954 else 955 setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i32, Expand); 956 957 // ARMv6 Thumb1 (except for CPUs that support dmb / dsb) and earlier use 958 // the default expansion. 959 InsertFencesForAtomic = false; 960 if (Subtarget->hasAnyDataBarrier() && 961 (!Subtarget->isThumb() || Subtarget->hasV8MBaselineOps())) { 962 // ATOMIC_FENCE needs custom lowering; the others should have been expanded 963 // to ldrex/strex loops already. 964 setOperationAction(ISD::ATOMIC_FENCE, MVT::Other, Custom); 965 if (!Subtarget->isThumb() || !Subtarget->isMClass()) 966 setOperationAction(ISD::ATOMIC_CMP_SWAP, MVT::i64, Custom); 967 968 // On v8, we have particularly efficient implementations of atomic fences 969 // if they can be combined with nearby atomic loads and stores. 970 if (!Subtarget->hasV8Ops() || getTargetMachine().getOptLevel() == 0) { 971 // Automatically insert fences (dmb ish) around ATOMIC_SWAP etc. 972 InsertFencesForAtomic = true; 973 } 974 } else { 975 // If there's anything we can use as a barrier, go through custom lowering 976 // for ATOMIC_FENCE. 977 // If target has DMB in thumb, Fences can be inserted. 978 if (Subtarget->hasDataBarrier()) 979 InsertFencesForAtomic = true; 980 981 setOperationAction(ISD::ATOMIC_FENCE, MVT::Other, 982 Subtarget->hasAnyDataBarrier() ? Custom : Expand); 983 984 // Set them all for expansion, which will force libcalls. 985 setOperationAction(ISD::ATOMIC_CMP_SWAP, MVT::i32, Expand); 986 setOperationAction(ISD::ATOMIC_SWAP, MVT::i32, Expand); 987 setOperationAction(ISD::ATOMIC_LOAD_ADD, MVT::i32, Expand); 988 setOperationAction(ISD::ATOMIC_LOAD_SUB, MVT::i32, Expand); 989 setOperationAction(ISD::ATOMIC_LOAD_AND, MVT::i32, Expand); 990 setOperationAction(ISD::ATOMIC_LOAD_OR, MVT::i32, Expand); 991 setOperationAction(ISD::ATOMIC_LOAD_XOR, MVT::i32, Expand); 992 setOperationAction(ISD::ATOMIC_LOAD_NAND, MVT::i32, Expand); 993 setOperationAction(ISD::ATOMIC_LOAD_MIN, MVT::i32, Expand); 994 setOperationAction(ISD::ATOMIC_LOAD_MAX, MVT::i32, Expand); 995 setOperationAction(ISD::ATOMIC_LOAD_UMIN, MVT::i32, Expand); 996 setOperationAction(ISD::ATOMIC_LOAD_UMAX, MVT::i32, Expand); 997 // Mark ATOMIC_LOAD and ATOMIC_STORE custom so we can handle the 998 // Unordered/Monotonic case. 999 if (!InsertFencesForAtomic) { 1000 setOperationAction(ISD::ATOMIC_LOAD, MVT::i32, Custom); 1001 setOperationAction(ISD::ATOMIC_STORE, MVT::i32, Custom); 1002 } 1003 } 1004 1005 setOperationAction(ISD::PREFETCH, MVT::Other, Custom); 1006 1007 // Requires SXTB/SXTH, available on v6 and up in both ARM and Thumb modes. 1008 if (!Subtarget->hasV6Ops()) { 1009 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i16, Expand); 1010 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i8, Expand); 1011 } 1012 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1, Expand); 1013 1014 if (!Subtarget->useSoftFloat() && Subtarget->hasVFP2() && 1015 !Subtarget->isThumb1Only()) { 1016 // Turn f64->i64 into VMOVRRD, i64 -> f64 to VMOVDRR 1017 // iff target supports vfp2. 1018 setOperationAction(ISD::BITCAST, MVT::i64, Custom); 1019 setOperationAction(ISD::FLT_ROUNDS_, MVT::i32, Custom); 1020 } 1021 1022 // We want to custom lower some of our intrinsics. 1023 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom); 1024 setOperationAction(ISD::EH_SJLJ_SETJMP, MVT::i32, Custom); 1025 setOperationAction(ISD::EH_SJLJ_LONGJMP, MVT::Other, Custom); 1026 setOperationAction(ISD::EH_SJLJ_SETUP_DISPATCH, MVT::Other, Custom); 1027 if (Subtarget->useSjLjEH()) 1028 setLibcallName(RTLIB::UNWIND_RESUME, "_Unwind_SjLj_Resume"); 1029 1030 setOperationAction(ISD::SETCC, MVT::i32, Expand); 1031 setOperationAction(ISD::SETCC, MVT::f32, Expand); 1032 setOperationAction(ISD::SETCC, MVT::f64, Expand); 1033 setOperationAction(ISD::SELECT, MVT::i32, Custom); 1034 setOperationAction(ISD::SELECT, MVT::f32, Custom); 1035 setOperationAction(ISD::SELECT, MVT::f64, Custom); 1036 setOperationAction(ISD::SELECT_CC, MVT::i32, Custom); 1037 setOperationAction(ISD::SELECT_CC, MVT::f32, Custom); 1038 setOperationAction(ISD::SELECT_CC, MVT::f64, Custom); 1039 1040 // Thumb-1 cannot currently select ARMISD::SUBE. 1041 if (!Subtarget->isThumb1Only()) 1042 setOperationAction(ISD::SETCCE, MVT::i32, Custom); 1043 1044 setOperationAction(ISD::BRCOND, MVT::Other, Expand); 1045 setOperationAction(ISD::BR_CC, MVT::i32, Custom); 1046 setOperationAction(ISD::BR_CC, MVT::f32, Custom); 1047 setOperationAction(ISD::BR_CC, MVT::f64, Custom); 1048 setOperationAction(ISD::BR_JT, MVT::Other, Custom); 1049 1050 // We don't support sin/cos/fmod/copysign/pow 1051 setOperationAction(ISD::FSIN, MVT::f64, Expand); 1052 setOperationAction(ISD::FSIN, MVT::f32, Expand); 1053 setOperationAction(ISD::FCOS, MVT::f32, Expand); 1054 setOperationAction(ISD::FCOS, MVT::f64, Expand); 1055 setOperationAction(ISD::FSINCOS, MVT::f64, Expand); 1056 setOperationAction(ISD::FSINCOS, MVT::f32, Expand); 1057 setOperationAction(ISD::FREM, MVT::f64, Expand); 1058 setOperationAction(ISD::FREM, MVT::f32, Expand); 1059 if (!Subtarget->useSoftFloat() && Subtarget->hasVFP2() && 1060 !Subtarget->isThumb1Only()) { 1061 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Custom); 1062 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom); 1063 } 1064 setOperationAction(ISD::FPOW, MVT::f64, Expand); 1065 setOperationAction(ISD::FPOW, MVT::f32, Expand); 1066 1067 if (!Subtarget->hasVFP4()) { 1068 setOperationAction(ISD::FMA, MVT::f64, Expand); 1069 setOperationAction(ISD::FMA, MVT::f32, Expand); 1070 } 1071 1072 // Various VFP goodness 1073 if (!Subtarget->useSoftFloat() && !Subtarget->isThumb1Only()) { 1074 // FP-ARMv8 adds f64 <-> f16 conversion. Before that it should be expanded. 1075 if (!Subtarget->hasFPARMv8() || Subtarget->isFPOnlySP()) { 1076 setOperationAction(ISD::FP16_TO_FP, MVT::f64, Expand); 1077 setOperationAction(ISD::FP_TO_FP16, MVT::f64, Expand); 1078 } 1079 1080 // fp16 is a special v7 extension that adds f16 <-> f32 conversions. 1081 if (!Subtarget->hasFP16()) { 1082 setOperationAction(ISD::FP16_TO_FP, MVT::f32, Expand); 1083 setOperationAction(ISD::FP_TO_FP16, MVT::f32, Expand); 1084 } 1085 } 1086 1087 // Combine sin / cos into one node or libcall if possible. 1088 if (Subtarget->hasSinCos()) { 1089 setLibcallName(RTLIB::SINCOS_F32, "sincosf"); 1090 setLibcallName(RTLIB::SINCOS_F64, "sincos"); 1091 if (Subtarget->isTargetWatchABI()) { 1092 setLibcallCallingConv(RTLIB::SINCOS_F32, CallingConv::ARM_AAPCS_VFP); 1093 setLibcallCallingConv(RTLIB::SINCOS_F64, CallingConv::ARM_AAPCS_VFP); 1094 } 1095 if (Subtarget->isTargetIOS() || Subtarget->isTargetWatchOS()) { 1096 // For iOS, we don't want to the normal expansion of a libcall to 1097 // sincos. We want to issue a libcall to __sincos_stret. 1098 setOperationAction(ISD::FSINCOS, MVT::f64, Custom); 1099 setOperationAction(ISD::FSINCOS, MVT::f32, Custom); 1100 } 1101 } 1102 1103 // FP-ARMv8 implements a lot of rounding-like FP operations. 1104 if (Subtarget->hasFPARMv8()) { 1105 setOperationAction(ISD::FFLOOR, MVT::f32, Legal); 1106 setOperationAction(ISD::FCEIL, MVT::f32, Legal); 1107 setOperationAction(ISD::FROUND, MVT::f32, Legal); 1108 setOperationAction(ISD::FTRUNC, MVT::f32, Legal); 1109 setOperationAction(ISD::FNEARBYINT, MVT::f32, Legal); 1110 setOperationAction(ISD::FRINT, MVT::f32, Legal); 1111 setOperationAction(ISD::FMINNUM, MVT::f32, Legal); 1112 setOperationAction(ISD::FMAXNUM, MVT::f32, Legal); 1113 setOperationAction(ISD::FMINNUM, MVT::v2f32, Legal); 1114 setOperationAction(ISD::FMAXNUM, MVT::v2f32, Legal); 1115 setOperationAction(ISD::FMINNUM, MVT::v4f32, Legal); 1116 setOperationAction(ISD::FMAXNUM, MVT::v4f32, Legal); 1117 1118 if (!Subtarget->isFPOnlySP()) { 1119 setOperationAction(ISD::FFLOOR, MVT::f64, Legal); 1120 setOperationAction(ISD::FCEIL, MVT::f64, Legal); 1121 setOperationAction(ISD::FROUND, MVT::f64, Legal); 1122 setOperationAction(ISD::FTRUNC, MVT::f64, Legal); 1123 setOperationAction(ISD::FNEARBYINT, MVT::f64, Legal); 1124 setOperationAction(ISD::FRINT, MVT::f64, Legal); 1125 setOperationAction(ISD::FMINNUM, MVT::f64, Legal); 1126 setOperationAction(ISD::FMAXNUM, MVT::f64, Legal); 1127 } 1128 } 1129 1130 if (Subtarget->hasNEON()) { 1131 // vmin and vmax aren't available in a scalar form, so we use 1132 // a NEON instruction with an undef lane instead. 1133 setOperationAction(ISD::FMINNAN, MVT::f32, Legal); 1134 setOperationAction(ISD::FMAXNAN, MVT::f32, Legal); 1135 setOperationAction(ISD::FMINNAN, MVT::v2f32, Legal); 1136 setOperationAction(ISD::FMAXNAN, MVT::v2f32, Legal); 1137 setOperationAction(ISD::FMINNAN, MVT::v4f32, Legal); 1138 setOperationAction(ISD::FMAXNAN, MVT::v4f32, Legal); 1139 } 1140 1141 // We have target-specific dag combine patterns for the following nodes: 1142 // ARMISD::VMOVRRD - No need to call setTargetDAGCombine 1143 setTargetDAGCombine(ISD::ADD); 1144 setTargetDAGCombine(ISD::SUB); 1145 setTargetDAGCombine(ISD::MUL); 1146 setTargetDAGCombine(ISD::AND); 1147 setTargetDAGCombine(ISD::OR); 1148 setTargetDAGCombine(ISD::XOR); 1149 1150 if (Subtarget->hasV6Ops()) 1151 setTargetDAGCombine(ISD::SRL); 1152 1153 setStackPointerRegisterToSaveRestore(ARM::SP); 1154 1155 if (Subtarget->useSoftFloat() || Subtarget->isThumb1Only() || 1156 !Subtarget->hasVFP2()) 1157 setSchedulingPreference(Sched::RegPressure); 1158 else 1159 setSchedulingPreference(Sched::Hybrid); 1160 1161 //// temporary - rewrite interface to use type 1162 MaxStoresPerMemset = 8; 1163 MaxStoresPerMemsetOptSize = 4; 1164 MaxStoresPerMemcpy = 4; // For @llvm.memcpy -> sequence of stores 1165 MaxStoresPerMemcpyOptSize = 2; 1166 MaxStoresPerMemmove = 4; // For @llvm.memmove -> sequence of stores 1167 MaxStoresPerMemmoveOptSize = 2; 1168 1169 // On ARM arguments smaller than 4 bytes are extended, so all arguments 1170 // are at least 4 bytes aligned. 1171 setMinStackArgumentAlignment(4); 1172 1173 // Prefer likely predicted branches to selects on out-of-order cores. 1174 PredictableSelectIsExpensive = Subtarget->getSchedModel().isOutOfOrder(); 1175 1176 setMinFunctionAlignment(Subtarget->isThumb() ? 1 : 2); 1177 } 1178 1179 bool ARMTargetLowering::useSoftFloat() const { 1180 return Subtarget->useSoftFloat(); 1181 } 1182 1183 // FIXME: It might make sense to define the representative register class as the 1184 // nearest super-register that has a non-null superset. For example, DPR_VFP2 is 1185 // a super-register of SPR, and DPR is a superset if DPR_VFP2. Consequently, 1186 // SPR's representative would be DPR_VFP2. This should work well if register 1187 // pressure tracking were modified such that a register use would increment the 1188 // pressure of the register class's representative and all of it's super 1189 // classes' representatives transitively. We have not implemented this because 1190 // of the difficulty prior to coalescing of modeling operand register classes 1191 // due to the common occurrence of cross class copies and subregister insertions 1192 // and extractions. 1193 std::pair<const TargetRegisterClass *, uint8_t> 1194 ARMTargetLowering::findRepresentativeClass(const TargetRegisterInfo *TRI, 1195 MVT VT) const { 1196 const TargetRegisterClass *RRC = nullptr; 1197 uint8_t Cost = 1; 1198 switch (VT.SimpleTy) { 1199 default: 1200 return TargetLowering::findRepresentativeClass(TRI, VT); 1201 // Use DPR as representative register class for all floating point 1202 // and vector types. Since there are 32 SPR registers and 32 DPR registers so 1203 // the cost is 1 for both f32 and f64. 1204 case MVT::f32: case MVT::f64: case MVT::v8i8: case MVT::v4i16: 1205 case MVT::v2i32: case MVT::v1i64: case MVT::v2f32: 1206 RRC = &ARM::DPRRegClass; 1207 // When NEON is used for SP, only half of the register file is available 1208 // because operations that define both SP and DP results will be constrained 1209 // to the VFP2 class (D0-D15). We currently model this constraint prior to 1210 // coalescing by double-counting the SP regs. See the FIXME above. 1211 if (Subtarget->useNEONForSinglePrecisionFP()) 1212 Cost = 2; 1213 break; 1214 case MVT::v16i8: case MVT::v8i16: case MVT::v4i32: case MVT::v2i64: 1215 case MVT::v4f32: case MVT::v2f64: 1216 RRC = &ARM::DPRRegClass; 1217 Cost = 2; 1218 break; 1219 case MVT::v4i64: 1220 RRC = &ARM::DPRRegClass; 1221 Cost = 4; 1222 break; 1223 case MVT::v8i64: 1224 RRC = &ARM::DPRRegClass; 1225 Cost = 8; 1226 break; 1227 } 1228 return std::make_pair(RRC, Cost); 1229 } 1230 1231 const char *ARMTargetLowering::getTargetNodeName(unsigned Opcode) const { 1232 switch ((ARMISD::NodeType)Opcode) { 1233 case ARMISD::FIRST_NUMBER: break; 1234 case ARMISD::Wrapper: return "ARMISD::Wrapper"; 1235 case ARMISD::WrapperPIC: return "ARMISD::WrapperPIC"; 1236 case ARMISD::WrapperJT: return "ARMISD::WrapperJT"; 1237 case ARMISD::COPY_STRUCT_BYVAL: return "ARMISD::COPY_STRUCT_BYVAL"; 1238 case ARMISD::CALL: return "ARMISD::CALL"; 1239 case ARMISD::CALL_PRED: return "ARMISD::CALL_PRED"; 1240 case ARMISD::CALL_NOLINK: return "ARMISD::CALL_NOLINK"; 1241 case ARMISD::BRCOND: return "ARMISD::BRCOND"; 1242 case ARMISD::BR_JT: return "ARMISD::BR_JT"; 1243 case ARMISD::BR2_JT: return "ARMISD::BR2_JT"; 1244 case ARMISD::RET_FLAG: return "ARMISD::RET_FLAG"; 1245 case ARMISD::INTRET_FLAG: return "ARMISD::INTRET_FLAG"; 1246 case ARMISD::PIC_ADD: return "ARMISD::PIC_ADD"; 1247 case ARMISD::CMP: return "ARMISD::CMP"; 1248 case ARMISD::CMN: return "ARMISD::CMN"; 1249 case ARMISD::CMPZ: return "ARMISD::CMPZ"; 1250 case ARMISD::CMPFP: return "ARMISD::CMPFP"; 1251 case ARMISD::CMPFPw0: return "ARMISD::CMPFPw0"; 1252 case ARMISD::BCC_i64: return "ARMISD::BCC_i64"; 1253 case ARMISD::FMSTAT: return "ARMISD::FMSTAT"; 1254 1255 case ARMISD::CMOV: return "ARMISD::CMOV"; 1256 1257 case ARMISD::SSAT: return "ARMISD::SSAT"; 1258 1259 case ARMISD::SRL_FLAG: return "ARMISD::SRL_FLAG"; 1260 case ARMISD::SRA_FLAG: return "ARMISD::SRA_FLAG"; 1261 case ARMISD::RRX: return "ARMISD::RRX"; 1262 1263 case ARMISD::ADDC: return "ARMISD::ADDC"; 1264 case ARMISD::ADDE: return "ARMISD::ADDE"; 1265 case ARMISD::SUBC: return "ARMISD::SUBC"; 1266 case ARMISD::SUBE: return "ARMISD::SUBE"; 1267 1268 case ARMISD::VMOVRRD: return "ARMISD::VMOVRRD"; 1269 case ARMISD::VMOVDRR: return "ARMISD::VMOVDRR"; 1270 1271 case ARMISD::EH_SJLJ_SETJMP: return "ARMISD::EH_SJLJ_SETJMP"; 1272 case ARMISD::EH_SJLJ_LONGJMP: return "ARMISD::EH_SJLJ_LONGJMP"; 1273 case ARMISD::EH_SJLJ_SETUP_DISPATCH: return "ARMISD::EH_SJLJ_SETUP_DISPATCH"; 1274 1275 case ARMISD::TC_RETURN: return "ARMISD::TC_RETURN"; 1276 1277 case ARMISD::THREAD_POINTER:return "ARMISD::THREAD_POINTER"; 1278 1279 case ARMISD::DYN_ALLOC: return "ARMISD::DYN_ALLOC"; 1280 1281 case ARMISD::MEMBARRIER_MCR: return "ARMISD::MEMBARRIER_MCR"; 1282 1283 case ARMISD::PRELOAD: return "ARMISD::PRELOAD"; 1284 1285 case ARMISD::WIN__CHKSTK: return "ARMISD::WIN__CHKSTK"; 1286 case ARMISD::WIN__DBZCHK: return "ARMISD::WIN__DBZCHK"; 1287 1288 case ARMISD::VCEQ: return "ARMISD::VCEQ"; 1289 case ARMISD::VCEQZ: return "ARMISD::VCEQZ"; 1290 case ARMISD::VCGE: return "ARMISD::VCGE"; 1291 case ARMISD::VCGEZ: return "ARMISD::VCGEZ"; 1292 case ARMISD::VCLEZ: return "ARMISD::VCLEZ"; 1293 case ARMISD::VCGEU: return "ARMISD::VCGEU"; 1294 case ARMISD::VCGT: return "ARMISD::VCGT"; 1295 case ARMISD::VCGTZ: return "ARMISD::VCGTZ"; 1296 case ARMISD::VCLTZ: return "ARMISD::VCLTZ"; 1297 case ARMISD::VCGTU: return "ARMISD::VCGTU"; 1298 case ARMISD::VTST: return "ARMISD::VTST"; 1299 1300 case ARMISD::VSHL: return "ARMISD::VSHL"; 1301 case ARMISD::VSHRs: return "ARMISD::VSHRs"; 1302 case ARMISD::VSHRu: return "ARMISD::VSHRu"; 1303 case ARMISD::VRSHRs: return "ARMISD::VRSHRs"; 1304 case ARMISD::VRSHRu: return "ARMISD::VRSHRu"; 1305 case ARMISD::VRSHRN: return "ARMISD::VRSHRN"; 1306 case ARMISD::VQSHLs: return "ARMISD::VQSHLs"; 1307 case ARMISD::VQSHLu: return "ARMISD::VQSHLu"; 1308 case ARMISD::VQSHLsu: return "ARMISD::VQSHLsu"; 1309 case ARMISD::VQSHRNs: return "ARMISD::VQSHRNs"; 1310 case ARMISD::VQSHRNu: return "ARMISD::VQSHRNu"; 1311 case ARMISD::VQSHRNsu: return "ARMISD::VQSHRNsu"; 1312 case ARMISD::VQRSHRNs: return "ARMISD::VQRSHRNs"; 1313 case ARMISD::VQRSHRNu: return "ARMISD::VQRSHRNu"; 1314 case ARMISD::VQRSHRNsu: return "ARMISD::VQRSHRNsu"; 1315 case ARMISD::VSLI: return "ARMISD::VSLI"; 1316 case ARMISD::VSRI: return "ARMISD::VSRI"; 1317 case ARMISD::VGETLANEu: return "ARMISD::VGETLANEu"; 1318 case ARMISD::VGETLANEs: return "ARMISD::VGETLANEs"; 1319 case ARMISD::VMOVIMM: return "ARMISD::VMOVIMM"; 1320 case ARMISD::VMVNIMM: return "ARMISD::VMVNIMM"; 1321 case ARMISD::VMOVFPIMM: return "ARMISD::VMOVFPIMM"; 1322 case ARMISD::VDUP: return "ARMISD::VDUP"; 1323 case ARMISD::VDUPLANE: return "ARMISD::VDUPLANE"; 1324 case ARMISD::VEXT: return "ARMISD::VEXT"; 1325 case ARMISD::VREV64: return "ARMISD::VREV64"; 1326 case ARMISD::VREV32: return "ARMISD::VREV32"; 1327 case ARMISD::VREV16: return "ARMISD::VREV16"; 1328 case ARMISD::VZIP: return "ARMISD::VZIP"; 1329 case ARMISD::VUZP: return "ARMISD::VUZP"; 1330 case ARMISD::VTRN: return "ARMISD::VTRN"; 1331 case ARMISD::VTBL1: return "ARMISD::VTBL1"; 1332 case ARMISD::VTBL2: return "ARMISD::VTBL2"; 1333 case ARMISD::VMULLs: return "ARMISD::VMULLs"; 1334 case ARMISD::VMULLu: return "ARMISD::VMULLu"; 1335 case ARMISD::UMAAL: return "ARMISD::UMAAL"; 1336 case ARMISD::UMLAL: return "ARMISD::UMLAL"; 1337 case ARMISD::SMLAL: return "ARMISD::SMLAL"; 1338 case ARMISD::SMLALBB: return "ARMISD::SMLALBB"; 1339 case ARMISD::SMLALBT: return "ARMISD::SMLALBT"; 1340 case ARMISD::SMLALTB: return "ARMISD::SMLALTB"; 1341 case ARMISD::SMLALTT: return "ARMISD::SMLALTT"; 1342 case ARMISD::SMULWB: return "ARMISD::SMULWB"; 1343 case ARMISD::SMULWT: return "ARMISD::SMULWT"; 1344 case ARMISD::SMLALD: return "ARMISD::SMLALD"; 1345 case ARMISD::SMLALDX: return "ARMISD::SMLALDX"; 1346 case ARMISD::SMLSLD: return "ARMISD::SMLSLD"; 1347 case ARMISD::SMLSLDX: return "ARMISD::SMLSLDX"; 1348 case ARMISD::BUILD_VECTOR: return "ARMISD::BUILD_VECTOR"; 1349 case ARMISD::BFI: return "ARMISD::BFI"; 1350 case ARMISD::VORRIMM: return "ARMISD::VORRIMM"; 1351 case ARMISD::VBICIMM: return "ARMISD::VBICIMM"; 1352 case ARMISD::VBSL: return "ARMISD::VBSL"; 1353 case ARMISD::MEMCPY: return "ARMISD::MEMCPY"; 1354 case ARMISD::VLD1DUP: return "ARMISD::VLD1DUP"; 1355 case ARMISD::VLD2DUP: return "ARMISD::VLD2DUP"; 1356 case ARMISD::VLD3DUP: return "ARMISD::VLD3DUP"; 1357 case ARMISD::VLD4DUP: return "ARMISD::VLD4DUP"; 1358 case ARMISD::VLD1_UPD: return "ARMISD::VLD1_UPD"; 1359 case ARMISD::VLD2_UPD: return "ARMISD::VLD2_UPD"; 1360 case ARMISD::VLD3_UPD: return "ARMISD::VLD3_UPD"; 1361 case ARMISD::VLD4_UPD: return "ARMISD::VLD4_UPD"; 1362 case ARMISD::VLD2LN_UPD: return "ARMISD::VLD2LN_UPD"; 1363 case ARMISD::VLD3LN_UPD: return "ARMISD::VLD3LN_UPD"; 1364 case ARMISD::VLD4LN_UPD: return "ARMISD::VLD4LN_UPD"; 1365 case ARMISD::VLD1DUP_UPD: return "ARMISD::VLD1DUP_UPD"; 1366 case ARMISD::VLD2DUP_UPD: return "ARMISD::VLD2DUP_UPD"; 1367 case ARMISD::VLD3DUP_UPD: return "ARMISD::VLD3DUP_UPD"; 1368 case ARMISD::VLD4DUP_UPD: return "ARMISD::VLD4DUP_UPD"; 1369 case ARMISD::VST1_UPD: return "ARMISD::VST1_UPD"; 1370 case ARMISD::VST2_UPD: return "ARMISD::VST2_UPD"; 1371 case ARMISD::VST3_UPD: return "ARMISD::VST3_UPD"; 1372 case ARMISD::VST4_UPD: return "ARMISD::VST4_UPD"; 1373 case ARMISD::VST2LN_UPD: return "ARMISD::VST2LN_UPD"; 1374 case ARMISD::VST3LN_UPD: return "ARMISD::VST3LN_UPD"; 1375 case ARMISD::VST4LN_UPD: return "ARMISD::VST4LN_UPD"; 1376 } 1377 return nullptr; 1378 } 1379 1380 EVT ARMTargetLowering::getSetCCResultType(const DataLayout &DL, LLVMContext &, 1381 EVT VT) const { 1382 if (!VT.isVector()) 1383 return getPointerTy(DL); 1384 return VT.changeVectorElementTypeToInteger(); 1385 } 1386 1387 /// getRegClassFor - Return the register class that should be used for the 1388 /// specified value type. 1389 const TargetRegisterClass *ARMTargetLowering::getRegClassFor(MVT VT) const { 1390 // Map v4i64 to QQ registers but do not make the type legal. Similarly map 1391 // v8i64 to QQQQ registers. v4i64 and v8i64 are only used for REG_SEQUENCE to 1392 // load / store 4 to 8 consecutive D registers. 1393 if (Subtarget->hasNEON()) { 1394 if (VT == MVT::v4i64) 1395 return &ARM::QQPRRegClass; 1396 if (VT == MVT::v8i64) 1397 return &ARM::QQQQPRRegClass; 1398 } 1399 return TargetLowering::getRegClassFor(VT); 1400 } 1401 1402 // memcpy, and other memory intrinsics, typically tries to use LDM/STM if the 1403 // source/dest is aligned and the copy size is large enough. We therefore want 1404 // to align such objects passed to memory intrinsics. 1405 bool ARMTargetLowering::shouldAlignPointerArgs(CallInst *CI, unsigned &MinSize, 1406 unsigned &PrefAlign) const { 1407 if (!isa<MemIntrinsic>(CI)) 1408 return false; 1409 MinSize = 8; 1410 // On ARM11 onwards (excluding M class) 8-byte aligned LDM is typically 1 1411 // cycle faster than 4-byte aligned LDM. 1412 PrefAlign = (Subtarget->hasV6Ops() && !Subtarget->isMClass() ? 8 : 4); 1413 return true; 1414 } 1415 1416 // Create a fast isel object. 1417 FastISel * 1418 ARMTargetLowering::createFastISel(FunctionLoweringInfo &funcInfo, 1419 const TargetLibraryInfo *libInfo) const { 1420 return ARM::createFastISel(funcInfo, libInfo); 1421 } 1422 1423 Sched::Preference ARMTargetLowering::getSchedulingPreference(SDNode *N) const { 1424 unsigned NumVals = N->getNumValues(); 1425 if (!NumVals) 1426 return Sched::RegPressure; 1427 1428 for (unsigned i = 0; i != NumVals; ++i) { 1429 EVT VT = N->getValueType(i); 1430 if (VT == MVT::Glue || VT == MVT::Other) 1431 continue; 1432 if (VT.isFloatingPoint() || VT.isVector()) 1433 return Sched::ILP; 1434 } 1435 1436 if (!N->isMachineOpcode()) 1437 return Sched::RegPressure; 1438 1439 // Load are scheduled for latency even if there instruction itinerary 1440 // is not available. 1441 const TargetInstrInfo *TII = Subtarget->getInstrInfo(); 1442 const MCInstrDesc &MCID = TII->get(N->getMachineOpcode()); 1443 1444 if (MCID.getNumDefs() == 0) 1445 return Sched::RegPressure; 1446 if (!Itins->isEmpty() && 1447 Itins->getOperandCycle(MCID.getSchedClass(), 0) > 2) 1448 return Sched::ILP; 1449 1450 return Sched::RegPressure; 1451 } 1452 1453 //===----------------------------------------------------------------------===// 1454 // Lowering Code 1455 //===----------------------------------------------------------------------===// 1456 1457 static bool isSRL16(const SDValue &Op) { 1458 if (Op.getOpcode() != ISD::SRL) 1459 return false; 1460 if (auto Const = dyn_cast<ConstantSDNode>(Op.getOperand(1))) 1461 return Const->getZExtValue() == 16; 1462 return false; 1463 } 1464 1465 static bool isSRA16(const SDValue &Op) { 1466 if (Op.getOpcode() != ISD::SRA) 1467 return false; 1468 if (auto Const = dyn_cast<ConstantSDNode>(Op.getOperand(1))) 1469 return Const->getZExtValue() == 16; 1470 return false; 1471 } 1472 1473 static bool isSHL16(const SDValue &Op) { 1474 if (Op.getOpcode() != ISD::SHL) 1475 return false; 1476 if (auto Const = dyn_cast<ConstantSDNode>(Op.getOperand(1))) 1477 return Const->getZExtValue() == 16; 1478 return false; 1479 } 1480 1481 // Check for a signed 16-bit value. We special case SRA because it makes it 1482 // more simple when also looking for SRAs that aren't sign extending a 1483 // smaller value. Without the check, we'd need to take extra care with 1484 // checking order for some operations. 1485 static bool isS16(const SDValue &Op, SelectionDAG &DAG) { 1486 if (isSRA16(Op)) 1487 return isSHL16(Op.getOperand(0)); 1488 return DAG.ComputeNumSignBits(Op) == 17; 1489 } 1490 1491 /// IntCCToARMCC - Convert a DAG integer condition code to an ARM CC 1492 static ARMCC::CondCodes IntCCToARMCC(ISD::CondCode CC) { 1493 switch (CC) { 1494 default: llvm_unreachable("Unknown condition code!"); 1495 case ISD::SETNE: return ARMCC::NE; 1496 case ISD::SETEQ: return ARMCC::EQ; 1497 case ISD::SETGT: return ARMCC::GT; 1498 case ISD::SETGE: return ARMCC::GE; 1499 case ISD::SETLT: return ARMCC::LT; 1500 case ISD::SETLE: return ARMCC::LE; 1501 case ISD::SETUGT: return ARMCC::HI; 1502 case ISD::SETUGE: return ARMCC::HS; 1503 case ISD::SETULT: return ARMCC::LO; 1504 case ISD::SETULE: return ARMCC::LS; 1505 } 1506 } 1507 1508 /// FPCCToARMCC - Convert a DAG fp condition code to an ARM CC. 1509 static void FPCCToARMCC(ISD::CondCode CC, ARMCC::CondCodes &CondCode, 1510 ARMCC::CondCodes &CondCode2, bool &InvalidOnQNaN) { 1511 CondCode2 = ARMCC::AL; 1512 InvalidOnQNaN = true; 1513 switch (CC) { 1514 default: llvm_unreachable("Unknown FP condition!"); 1515 case ISD::SETEQ: 1516 case ISD::SETOEQ: 1517 CondCode = ARMCC::EQ; 1518 InvalidOnQNaN = false; 1519 break; 1520 case ISD::SETGT: 1521 case ISD::SETOGT: CondCode = ARMCC::GT; break; 1522 case ISD::SETGE: 1523 case ISD::SETOGE: CondCode = ARMCC::GE; break; 1524 case ISD::SETOLT: CondCode = ARMCC::MI; break; 1525 case ISD::SETOLE: CondCode = ARMCC::LS; break; 1526 case ISD::SETONE: 1527 CondCode = ARMCC::MI; 1528 CondCode2 = ARMCC::GT; 1529 InvalidOnQNaN = false; 1530 break; 1531 case ISD::SETO: CondCode = ARMCC::VC; break; 1532 case ISD::SETUO: CondCode = ARMCC::VS; break; 1533 case ISD::SETUEQ: 1534 CondCode = ARMCC::EQ; 1535 CondCode2 = ARMCC::VS; 1536 InvalidOnQNaN = false; 1537 break; 1538 case ISD::SETUGT: CondCode = ARMCC::HI; break; 1539 case ISD::SETUGE: CondCode = ARMCC::PL; break; 1540 case ISD::SETLT: 1541 case ISD::SETULT: CondCode = ARMCC::LT; break; 1542 case ISD::SETLE: 1543 case ISD::SETULE: CondCode = ARMCC::LE; break; 1544 case ISD::SETNE: 1545 case ISD::SETUNE: 1546 CondCode = ARMCC::NE; 1547 InvalidOnQNaN = false; 1548 break; 1549 } 1550 } 1551 1552 //===----------------------------------------------------------------------===// 1553 // Calling Convention Implementation 1554 //===----------------------------------------------------------------------===// 1555 1556 #include "ARMGenCallingConv.inc" 1557 1558 /// getEffectiveCallingConv - Get the effective calling convention, taking into 1559 /// account presence of floating point hardware and calling convention 1560 /// limitations, such as support for variadic functions. 1561 CallingConv::ID 1562 ARMTargetLowering::getEffectiveCallingConv(CallingConv::ID CC, 1563 bool isVarArg) const { 1564 switch (CC) { 1565 default: 1566 report_fatal_error("Unsupported calling convention"); 1567 case CallingConv::ARM_AAPCS: 1568 case CallingConv::ARM_APCS: 1569 case CallingConv::GHC: 1570 return CC; 1571 case CallingConv::PreserveMost: 1572 return CallingConv::PreserveMost; 1573 case CallingConv::ARM_AAPCS_VFP: 1574 case CallingConv::Swift: 1575 return isVarArg ? CallingConv::ARM_AAPCS : CallingConv::ARM_AAPCS_VFP; 1576 case CallingConv::C: 1577 if (!Subtarget->isAAPCS_ABI()) 1578 return CallingConv::ARM_APCS; 1579 else if (Subtarget->hasVFP2() && !Subtarget->isThumb1Only() && 1580 getTargetMachine().Options.FloatABIType == FloatABI::Hard && 1581 !isVarArg) 1582 return CallingConv::ARM_AAPCS_VFP; 1583 else 1584 return CallingConv::ARM_AAPCS; 1585 case CallingConv::Fast: 1586 case CallingConv::CXX_FAST_TLS: 1587 if (!Subtarget->isAAPCS_ABI()) { 1588 if (Subtarget->hasVFP2() && !Subtarget->isThumb1Only() && !isVarArg) 1589 return CallingConv::Fast; 1590 return CallingConv::ARM_APCS; 1591 } else if (Subtarget->hasVFP2() && !Subtarget->isThumb1Only() && !isVarArg) 1592 return CallingConv::ARM_AAPCS_VFP; 1593 else 1594 return CallingConv::ARM_AAPCS; 1595 } 1596 } 1597 1598 CCAssignFn *ARMTargetLowering::CCAssignFnForCall(CallingConv::ID CC, 1599 bool isVarArg) const { 1600 return CCAssignFnForNode(CC, false, isVarArg); 1601 } 1602 1603 CCAssignFn *ARMTargetLowering::CCAssignFnForReturn(CallingConv::ID CC, 1604 bool isVarArg) const { 1605 return CCAssignFnForNode(CC, true, isVarArg); 1606 } 1607 1608 /// CCAssignFnForNode - Selects the correct CCAssignFn for the given 1609 /// CallingConvention. 1610 CCAssignFn *ARMTargetLowering::CCAssignFnForNode(CallingConv::ID CC, 1611 bool Return, 1612 bool isVarArg) const { 1613 switch (getEffectiveCallingConv(CC, isVarArg)) { 1614 default: 1615 report_fatal_error("Unsupported calling convention"); 1616 case CallingConv::ARM_APCS: 1617 return (Return ? RetCC_ARM_APCS : CC_ARM_APCS); 1618 case CallingConv::ARM_AAPCS: 1619 return (Return ? RetCC_ARM_AAPCS : CC_ARM_AAPCS); 1620 case CallingConv::ARM_AAPCS_VFP: 1621 return (Return ? RetCC_ARM_AAPCS_VFP : CC_ARM_AAPCS_VFP); 1622 case CallingConv::Fast: 1623 return (Return ? RetFastCC_ARM_APCS : FastCC_ARM_APCS); 1624 case CallingConv::GHC: 1625 return (Return ? RetCC_ARM_APCS : CC_ARM_APCS_GHC); 1626 case CallingConv::PreserveMost: 1627 return (Return ? RetCC_ARM_AAPCS : CC_ARM_AAPCS); 1628 } 1629 } 1630 1631 /// LowerCallResult - Lower the result values of a call into the 1632 /// appropriate copies out of appropriate physical registers. 1633 SDValue ARMTargetLowering::LowerCallResult( 1634 SDValue Chain, SDValue InFlag, CallingConv::ID CallConv, bool isVarArg, 1635 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl, 1636 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals, bool isThisReturn, 1637 SDValue ThisVal) const { 1638 1639 // Assign locations to each value returned by this call. 1640 SmallVector<CCValAssign, 16> RVLocs; 1641 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs, 1642 *DAG.getContext()); 1643 CCInfo.AnalyzeCallResult(Ins, CCAssignFnForReturn(CallConv, isVarArg)); 1644 1645 // Copy all of the result registers out of their specified physreg. 1646 for (unsigned i = 0; i != RVLocs.size(); ++i) { 1647 CCValAssign VA = RVLocs[i]; 1648 1649 // Pass 'this' value directly from the argument to return value, to avoid 1650 // reg unit interference 1651 if (i == 0 && isThisReturn) { 1652 assert(!VA.needsCustom() && VA.getLocVT() == MVT::i32 && 1653 "unexpected return calling convention register assignment"); 1654 InVals.push_back(ThisVal); 1655 continue; 1656 } 1657 1658 SDValue Val; 1659 if (VA.needsCustom()) { 1660 // Handle f64 or half of a v2f64. 1661 SDValue Lo = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32, 1662 InFlag); 1663 Chain = Lo.getValue(1); 1664 InFlag = Lo.getValue(2); 1665 VA = RVLocs[++i]; // skip ahead to next loc 1666 SDValue Hi = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32, 1667 InFlag); 1668 Chain = Hi.getValue(1); 1669 InFlag = Hi.getValue(2); 1670 if (!Subtarget->isLittle()) 1671 std::swap (Lo, Hi); 1672 Val = DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi); 1673 1674 if (VA.getLocVT() == MVT::v2f64) { 1675 SDValue Vec = DAG.getNode(ISD::UNDEF, dl, MVT::v2f64); 1676 Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Vec, Val, 1677 DAG.getConstant(0, dl, MVT::i32)); 1678 1679 VA = RVLocs[++i]; // skip ahead to next loc 1680 Lo = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32, InFlag); 1681 Chain = Lo.getValue(1); 1682 InFlag = Lo.getValue(2); 1683 VA = RVLocs[++i]; // skip ahead to next loc 1684 Hi = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32, InFlag); 1685 Chain = Hi.getValue(1); 1686 InFlag = Hi.getValue(2); 1687 if (!Subtarget->isLittle()) 1688 std::swap (Lo, Hi); 1689 Val = DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi); 1690 Val = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Vec, Val, 1691 DAG.getConstant(1, dl, MVT::i32)); 1692 } 1693 } else { 1694 Val = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), VA.getLocVT(), 1695 InFlag); 1696 Chain = Val.getValue(1); 1697 InFlag = Val.getValue(2); 1698 } 1699 1700 switch (VA.getLocInfo()) { 1701 default: llvm_unreachable("Unknown loc info!"); 1702 case CCValAssign::Full: break; 1703 case CCValAssign::BCvt: 1704 Val = DAG.getNode(ISD::BITCAST, dl, VA.getValVT(), Val); 1705 break; 1706 } 1707 1708 InVals.push_back(Val); 1709 } 1710 1711 return Chain; 1712 } 1713 1714 /// LowerMemOpCallTo - Store the argument to the stack. 1715 SDValue ARMTargetLowering::LowerMemOpCallTo(SDValue Chain, SDValue StackPtr, 1716 SDValue Arg, const SDLoc &dl, 1717 SelectionDAG &DAG, 1718 const CCValAssign &VA, 1719 ISD::ArgFlagsTy Flags) const { 1720 unsigned LocMemOffset = VA.getLocMemOffset(); 1721 SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset, dl); 1722 PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(DAG.getDataLayout()), 1723 StackPtr, PtrOff); 1724 return DAG.getStore( 1725 Chain, dl, Arg, PtrOff, 1726 MachinePointerInfo::getStack(DAG.getMachineFunction(), LocMemOffset)); 1727 } 1728 1729 void ARMTargetLowering::PassF64ArgInRegs(const SDLoc &dl, SelectionDAG &DAG, 1730 SDValue Chain, SDValue &Arg, 1731 RegsToPassVector &RegsToPass, 1732 CCValAssign &VA, CCValAssign &NextVA, 1733 SDValue &StackPtr, 1734 SmallVectorImpl<SDValue> &MemOpChains, 1735 ISD::ArgFlagsTy Flags) const { 1736 1737 SDValue fmrrd = DAG.getNode(ARMISD::VMOVRRD, dl, 1738 DAG.getVTList(MVT::i32, MVT::i32), Arg); 1739 unsigned id = Subtarget->isLittle() ? 0 : 1; 1740 RegsToPass.push_back(std::make_pair(VA.getLocReg(), fmrrd.getValue(id))); 1741 1742 if (NextVA.isRegLoc()) 1743 RegsToPass.push_back(std::make_pair(NextVA.getLocReg(), fmrrd.getValue(1-id))); 1744 else { 1745 assert(NextVA.isMemLoc()); 1746 if (!StackPtr.getNode()) 1747 StackPtr = DAG.getCopyFromReg(Chain, dl, ARM::SP, 1748 getPointerTy(DAG.getDataLayout())); 1749 1750 MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, fmrrd.getValue(1-id), 1751 dl, DAG, NextVA, 1752 Flags)); 1753 } 1754 } 1755 1756 /// LowerCall - Lowering a call into a callseq_start <- 1757 /// ARMISD:CALL <- callseq_end chain. Also add input and output parameter 1758 /// nodes. 1759 SDValue 1760 ARMTargetLowering::LowerCall(TargetLowering::CallLoweringInfo &CLI, 1761 SmallVectorImpl<SDValue> &InVals) const { 1762 SelectionDAG &DAG = CLI.DAG; 1763 SDLoc &dl = CLI.DL; 1764 SmallVectorImpl<ISD::OutputArg> &Outs = CLI.Outs; 1765 SmallVectorImpl<SDValue> &OutVals = CLI.OutVals; 1766 SmallVectorImpl<ISD::InputArg> &Ins = CLI.Ins; 1767 SDValue Chain = CLI.Chain; 1768 SDValue Callee = CLI.Callee; 1769 bool &isTailCall = CLI.IsTailCall; 1770 CallingConv::ID CallConv = CLI.CallConv; 1771 bool doesNotRet = CLI.DoesNotReturn; 1772 bool isVarArg = CLI.IsVarArg; 1773 1774 MachineFunction &MF = DAG.getMachineFunction(); 1775 bool isStructRet = (Outs.empty()) ? false : Outs[0].Flags.isSRet(); 1776 bool isThisReturn = false; 1777 bool isSibCall = false; 1778 auto Attr = MF.getFunction()->getFnAttribute("disable-tail-calls"); 1779 1780 // Disable tail calls if they're not supported. 1781 if (!Subtarget->supportsTailCall() || Attr.getValueAsString() == "true") 1782 isTailCall = false; 1783 1784 if (isTailCall) { 1785 // Check if it's really possible to do a tail call. 1786 isTailCall = IsEligibleForTailCallOptimization(Callee, CallConv, 1787 isVarArg, isStructRet, MF.getFunction()->hasStructRetAttr(), 1788 Outs, OutVals, Ins, DAG); 1789 if (!isTailCall && CLI.CS && CLI.CS.isMustTailCall()) 1790 report_fatal_error("failed to perform tail call elimination on a call " 1791 "site marked musttail"); 1792 // We don't support GuaranteedTailCallOpt for ARM, only automatically 1793 // detected sibcalls. 1794 if (isTailCall) { 1795 ++NumTailCalls; 1796 isSibCall = true; 1797 } 1798 } 1799 1800 // Analyze operands of the call, assigning locations to each operand. 1801 SmallVector<CCValAssign, 16> ArgLocs; 1802 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), ArgLocs, 1803 *DAG.getContext()); 1804 CCInfo.AnalyzeCallOperands(Outs, CCAssignFnForCall(CallConv, isVarArg)); 1805 1806 // Get a count of how many bytes are to be pushed on the stack. 1807 unsigned NumBytes = CCInfo.getNextStackOffset(); 1808 1809 // For tail calls, memory operands are available in our caller's stack. 1810 if (isSibCall) 1811 NumBytes = 0; 1812 1813 // Adjust the stack pointer for the new arguments... 1814 // These operations are automatically eliminated by the prolog/epilog pass 1815 if (!isSibCall) 1816 Chain = DAG.getCALLSEQ_START(Chain, NumBytes, 0, dl); 1817 1818 SDValue StackPtr = 1819 DAG.getCopyFromReg(Chain, dl, ARM::SP, getPointerTy(DAG.getDataLayout())); 1820 1821 RegsToPassVector RegsToPass; 1822 SmallVector<SDValue, 8> MemOpChains; 1823 1824 // Walk the register/memloc assignments, inserting copies/loads. In the case 1825 // of tail call optimization, arguments are handled later. 1826 for (unsigned i = 0, realArgIdx = 0, e = ArgLocs.size(); 1827 i != e; 1828 ++i, ++realArgIdx) { 1829 CCValAssign &VA = ArgLocs[i]; 1830 SDValue Arg = OutVals[realArgIdx]; 1831 ISD::ArgFlagsTy Flags = Outs[realArgIdx].Flags; 1832 bool isByVal = Flags.isByVal(); 1833 1834 // Promote the value if needed. 1835 switch (VA.getLocInfo()) { 1836 default: llvm_unreachable("Unknown loc info!"); 1837 case CCValAssign::Full: break; 1838 case CCValAssign::SExt: 1839 Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), Arg); 1840 break; 1841 case CCValAssign::ZExt: 1842 Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, VA.getLocVT(), Arg); 1843 break; 1844 case CCValAssign::AExt: 1845 Arg = DAG.getNode(ISD::ANY_EXTEND, dl, VA.getLocVT(), Arg); 1846 break; 1847 case CCValAssign::BCvt: 1848 Arg = DAG.getNode(ISD::BITCAST, dl, VA.getLocVT(), Arg); 1849 break; 1850 } 1851 1852 // f64 and v2f64 might be passed in i32 pairs and must be split into pieces 1853 if (VA.needsCustom()) { 1854 if (VA.getLocVT() == MVT::v2f64) { 1855 SDValue Op0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg, 1856 DAG.getConstant(0, dl, MVT::i32)); 1857 SDValue Op1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg, 1858 DAG.getConstant(1, dl, MVT::i32)); 1859 1860 PassF64ArgInRegs(dl, DAG, Chain, Op0, RegsToPass, 1861 VA, ArgLocs[++i], StackPtr, MemOpChains, Flags); 1862 1863 VA = ArgLocs[++i]; // skip ahead to next loc 1864 if (VA.isRegLoc()) { 1865 PassF64ArgInRegs(dl, DAG, Chain, Op1, RegsToPass, 1866 VA, ArgLocs[++i], StackPtr, MemOpChains, Flags); 1867 } else { 1868 assert(VA.isMemLoc()); 1869 1870 MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, Op1, 1871 dl, DAG, VA, Flags)); 1872 } 1873 } else { 1874 PassF64ArgInRegs(dl, DAG, Chain, Arg, RegsToPass, VA, ArgLocs[++i], 1875 StackPtr, MemOpChains, Flags); 1876 } 1877 } else if (VA.isRegLoc()) { 1878 if (realArgIdx == 0 && Flags.isReturned() && !Flags.isSwiftSelf() && 1879 Outs[0].VT == MVT::i32) { 1880 assert(VA.getLocVT() == MVT::i32 && 1881 "unexpected calling convention register assignment"); 1882 assert(!Ins.empty() && Ins[0].VT == MVT::i32 && 1883 "unexpected use of 'returned'"); 1884 isThisReturn = true; 1885 } 1886 RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg)); 1887 } else if (isByVal) { 1888 assert(VA.isMemLoc()); 1889 unsigned offset = 0; 1890 1891 // True if this byval aggregate will be split between registers 1892 // and memory. 1893 unsigned ByValArgsCount = CCInfo.getInRegsParamsCount(); 1894 unsigned CurByValIdx = CCInfo.getInRegsParamsProcessed(); 1895 1896 if (CurByValIdx < ByValArgsCount) { 1897 1898 unsigned RegBegin, RegEnd; 1899 CCInfo.getInRegsParamInfo(CurByValIdx, RegBegin, RegEnd); 1900 1901 EVT PtrVT = 1902 DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout()); 1903 unsigned int i, j; 1904 for (i = 0, j = RegBegin; j < RegEnd; i++, j++) { 1905 SDValue Const = DAG.getConstant(4*i, dl, MVT::i32); 1906 SDValue AddArg = DAG.getNode(ISD::ADD, dl, PtrVT, Arg, Const); 1907 SDValue Load = DAG.getLoad(PtrVT, dl, Chain, AddArg, 1908 MachinePointerInfo(), 1909 DAG.InferPtrAlignment(AddArg)); 1910 MemOpChains.push_back(Load.getValue(1)); 1911 RegsToPass.push_back(std::make_pair(j, Load)); 1912 } 1913 1914 // If parameter size outsides register area, "offset" value 1915 // helps us to calculate stack slot for remained part properly. 1916 offset = RegEnd - RegBegin; 1917 1918 CCInfo.nextInRegsParam(); 1919 } 1920 1921 if (Flags.getByValSize() > 4*offset) { 1922 auto PtrVT = getPointerTy(DAG.getDataLayout()); 1923 unsigned LocMemOffset = VA.getLocMemOffset(); 1924 SDValue StkPtrOff = DAG.getIntPtrConstant(LocMemOffset, dl); 1925 SDValue Dst = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, StkPtrOff); 1926 SDValue SrcOffset = DAG.getIntPtrConstant(4*offset, dl); 1927 SDValue Src = DAG.getNode(ISD::ADD, dl, PtrVT, Arg, SrcOffset); 1928 SDValue SizeNode = DAG.getConstant(Flags.getByValSize() - 4*offset, dl, 1929 MVT::i32); 1930 SDValue AlignNode = DAG.getConstant(Flags.getByValAlign(), dl, 1931 MVT::i32); 1932 1933 SDVTList VTs = DAG.getVTList(MVT::Other, MVT::Glue); 1934 SDValue Ops[] = { Chain, Dst, Src, SizeNode, AlignNode}; 1935 MemOpChains.push_back(DAG.getNode(ARMISD::COPY_STRUCT_BYVAL, dl, VTs, 1936 Ops)); 1937 } 1938 } else if (!isSibCall) { 1939 assert(VA.isMemLoc()); 1940 1941 MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, Arg, 1942 dl, DAG, VA, Flags)); 1943 } 1944 } 1945 1946 if (!MemOpChains.empty()) 1947 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains); 1948 1949 // Build a sequence of copy-to-reg nodes chained together with token chain 1950 // and flag operands which copy the outgoing args into the appropriate regs. 1951 SDValue InFlag; 1952 // Tail call byval lowering might overwrite argument registers so in case of 1953 // tail call optimization the copies to registers are lowered later. 1954 if (!isTailCall) 1955 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) { 1956 Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first, 1957 RegsToPass[i].second, InFlag); 1958 InFlag = Chain.getValue(1); 1959 } 1960 1961 // For tail calls lower the arguments to the 'real' stack slot. 1962 if (isTailCall) { 1963 // Force all the incoming stack arguments to be loaded from the stack 1964 // before any new outgoing arguments are stored to the stack, because the 1965 // outgoing stack slots may alias the incoming argument stack slots, and 1966 // the alias isn't otherwise explicit. This is slightly more conservative 1967 // than necessary, because it means that each store effectively depends 1968 // on every argument instead of just those arguments it would clobber. 1969 1970 // Do not flag preceding copytoreg stuff together with the following stuff. 1971 InFlag = SDValue(); 1972 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) { 1973 Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first, 1974 RegsToPass[i].second, InFlag); 1975 InFlag = Chain.getValue(1); 1976 } 1977 InFlag = SDValue(); 1978 } 1979 1980 // If the callee is a GlobalAddress/ExternalSymbol node (quite common, every 1981 // direct call is) turn it into a TargetGlobalAddress/TargetExternalSymbol 1982 // node so that legalize doesn't hack it. 1983 bool isDirect = false; 1984 1985 const TargetMachine &TM = getTargetMachine(); 1986 const Module *Mod = MF.getFunction()->getParent(); 1987 const GlobalValue *GV = nullptr; 1988 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) 1989 GV = G->getGlobal(); 1990 bool isStub = 1991 !TM.shouldAssumeDSOLocal(*Mod, GV) && Subtarget->isTargetMachO(); 1992 1993 bool isARMFunc = !Subtarget->isThumb() || (isStub && !Subtarget->isMClass()); 1994 bool isLocalARMFunc = false; 1995 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>(); 1996 auto PtrVt = getPointerTy(DAG.getDataLayout()); 1997 1998 if (Subtarget->genLongCalls()) { 1999 assert((!isPositionIndependent() || Subtarget->isTargetWindows()) && 2000 "long-calls codegen is not position independent!"); 2001 // Handle a global address or an external symbol. If it's not one of 2002 // those, the target's already in a register, so we don't need to do 2003 // anything extra. 2004 if (isa<GlobalAddressSDNode>(Callee)) { 2005 // Create a constant pool entry for the callee address 2006 unsigned ARMPCLabelIndex = AFI->createPICLabelUId(); 2007 ARMConstantPoolValue *CPV = 2008 ARMConstantPoolConstant::Create(GV, ARMPCLabelIndex, ARMCP::CPValue, 0); 2009 2010 // Get the address of the callee into a register 2011 SDValue CPAddr = DAG.getTargetConstantPool(CPV, PtrVt, 4); 2012 CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr); 2013 Callee = DAG.getLoad( 2014 PtrVt, dl, DAG.getEntryNode(), CPAddr, 2015 MachinePointerInfo::getConstantPool(DAG.getMachineFunction())); 2016 } else if (ExternalSymbolSDNode *S=dyn_cast<ExternalSymbolSDNode>(Callee)) { 2017 const char *Sym = S->getSymbol(); 2018 2019 // Create a constant pool entry for the callee address 2020 unsigned ARMPCLabelIndex = AFI->createPICLabelUId(); 2021 ARMConstantPoolValue *CPV = 2022 ARMConstantPoolSymbol::Create(*DAG.getContext(), Sym, 2023 ARMPCLabelIndex, 0); 2024 // Get the address of the callee into a register 2025 SDValue CPAddr = DAG.getTargetConstantPool(CPV, PtrVt, 4); 2026 CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr); 2027 Callee = DAG.getLoad( 2028 PtrVt, dl, DAG.getEntryNode(), CPAddr, 2029 MachinePointerInfo::getConstantPool(DAG.getMachineFunction())); 2030 } 2031 } else if (isa<GlobalAddressSDNode>(Callee)) { 2032 // If we're optimizing for minimum size and the function is called three or 2033 // more times in this block, we can improve codesize by calling indirectly 2034 // as BLXr has a 16-bit encoding. 2035 auto *GV = cast<GlobalAddressSDNode>(Callee)->getGlobal(); 2036 auto *BB = CLI.CS.getParent(); 2037 bool PreferIndirect = 2038 Subtarget->isThumb() && MF.getFunction()->optForMinSize() && 2039 count_if(GV->users(), [&BB](const User *U) { 2040 return isa<Instruction>(U) && cast<Instruction>(U)->getParent() == BB; 2041 }) > 2; 2042 2043 if (!PreferIndirect) { 2044 isDirect = true; 2045 bool isDef = GV->isStrongDefinitionForLinker(); 2046 2047 // ARM call to a local ARM function is predicable. 2048 isLocalARMFunc = !Subtarget->isThumb() && (isDef || !ARMInterworking); 2049 // tBX takes a register source operand. 2050 if (isStub && Subtarget->isThumb1Only() && !Subtarget->hasV5TOps()) { 2051 assert(Subtarget->isTargetMachO() && "WrapperPIC use on non-MachO?"); 2052 Callee = DAG.getNode( 2053 ARMISD::WrapperPIC, dl, PtrVt, 2054 DAG.getTargetGlobalAddress(GV, dl, PtrVt, 0, ARMII::MO_NONLAZY)); 2055 Callee = DAG.getLoad( 2056 PtrVt, dl, DAG.getEntryNode(), Callee, 2057 MachinePointerInfo::getGOT(DAG.getMachineFunction()), 2058 /* Alignment = */ 0, MachineMemOperand::MODereferenceable | 2059 MachineMemOperand::MOInvariant); 2060 } else if (Subtarget->isTargetCOFF()) { 2061 assert(Subtarget->isTargetWindows() && 2062 "Windows is the only supported COFF target"); 2063 unsigned TargetFlags = GV->hasDLLImportStorageClass() 2064 ? ARMII::MO_DLLIMPORT 2065 : ARMII::MO_NO_FLAG; 2066 Callee = DAG.getTargetGlobalAddress(GV, dl, PtrVt, /*Offset=*/0, 2067 TargetFlags); 2068 if (GV->hasDLLImportStorageClass()) 2069 Callee = 2070 DAG.getLoad(PtrVt, dl, DAG.getEntryNode(), 2071 DAG.getNode(ARMISD::Wrapper, dl, PtrVt, Callee), 2072 MachinePointerInfo::getGOT(DAG.getMachineFunction())); 2073 } else { 2074 Callee = DAG.getTargetGlobalAddress(GV, dl, PtrVt, 0, 0); 2075 } 2076 } 2077 } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) { 2078 isDirect = true; 2079 // tBX takes a register source operand. 2080 const char *Sym = S->getSymbol(); 2081 if (isARMFunc && Subtarget->isThumb1Only() && !Subtarget->hasV5TOps()) { 2082 unsigned ARMPCLabelIndex = AFI->createPICLabelUId(); 2083 ARMConstantPoolValue *CPV = 2084 ARMConstantPoolSymbol::Create(*DAG.getContext(), Sym, 2085 ARMPCLabelIndex, 4); 2086 SDValue CPAddr = DAG.getTargetConstantPool(CPV, PtrVt, 4); 2087 CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr); 2088 Callee = DAG.getLoad( 2089 PtrVt, dl, DAG.getEntryNode(), CPAddr, 2090 MachinePointerInfo::getConstantPool(DAG.getMachineFunction())); 2091 SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, dl, MVT::i32); 2092 Callee = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVt, Callee, PICLabel); 2093 } else { 2094 Callee = DAG.getTargetExternalSymbol(Sym, PtrVt, 0); 2095 } 2096 } 2097 2098 // FIXME: handle tail calls differently. 2099 unsigned CallOpc; 2100 if (Subtarget->isThumb()) { 2101 if ((!isDirect || isARMFunc) && !Subtarget->hasV5TOps()) 2102 CallOpc = ARMISD::CALL_NOLINK; 2103 else 2104 CallOpc = ARMISD::CALL; 2105 } else { 2106 if (!isDirect && !Subtarget->hasV5TOps()) 2107 CallOpc = ARMISD::CALL_NOLINK; 2108 else if (doesNotRet && isDirect && Subtarget->hasRetAddrStack() && 2109 // Emit regular call when code size is the priority 2110 !MF.getFunction()->optForMinSize()) 2111 // "mov lr, pc; b _foo" to avoid confusing the RSP 2112 CallOpc = ARMISD::CALL_NOLINK; 2113 else 2114 CallOpc = isLocalARMFunc ? ARMISD::CALL_PRED : ARMISD::CALL; 2115 } 2116 2117 std::vector<SDValue> Ops; 2118 Ops.push_back(Chain); 2119 Ops.push_back(Callee); 2120 2121 // Add argument registers to the end of the list so that they are known live 2122 // into the call. 2123 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) 2124 Ops.push_back(DAG.getRegister(RegsToPass[i].first, 2125 RegsToPass[i].second.getValueType())); 2126 2127 // Add a register mask operand representing the call-preserved registers. 2128 if (!isTailCall) { 2129 const uint32_t *Mask; 2130 const ARMBaseRegisterInfo *ARI = Subtarget->getRegisterInfo(); 2131 if (isThisReturn) { 2132 // For 'this' returns, use the R0-preserving mask if applicable 2133 Mask = ARI->getThisReturnPreservedMask(MF, CallConv); 2134 if (!Mask) { 2135 // Set isThisReturn to false if the calling convention is not one that 2136 // allows 'returned' to be modeled in this way, so LowerCallResult does 2137 // not try to pass 'this' straight through 2138 isThisReturn = false; 2139 Mask = ARI->getCallPreservedMask(MF, CallConv); 2140 } 2141 } else 2142 Mask = ARI->getCallPreservedMask(MF, CallConv); 2143 2144 assert(Mask && "Missing call preserved mask for calling convention"); 2145 Ops.push_back(DAG.getRegisterMask(Mask)); 2146 } 2147 2148 if (InFlag.getNode()) 2149 Ops.push_back(InFlag); 2150 2151 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue); 2152 if (isTailCall) { 2153 MF.getFrameInfo().setHasTailCall(); 2154 return DAG.getNode(ARMISD::TC_RETURN, dl, NodeTys, Ops); 2155 } 2156 2157 // Returns a chain and a flag for retval copy to use. 2158 Chain = DAG.getNode(CallOpc, dl, NodeTys, Ops); 2159 InFlag = Chain.getValue(1); 2160 2161 Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, dl, true), 2162 DAG.getIntPtrConstant(0, dl, true), InFlag, dl); 2163 if (!Ins.empty()) 2164 InFlag = Chain.getValue(1); 2165 2166 // Handle result values, copying them out of physregs into vregs that we 2167 // return. 2168 return LowerCallResult(Chain, InFlag, CallConv, isVarArg, Ins, dl, DAG, 2169 InVals, isThisReturn, 2170 isThisReturn ? OutVals[0] : SDValue()); 2171 } 2172 2173 /// HandleByVal - Every parameter *after* a byval parameter is passed 2174 /// on the stack. Remember the next parameter register to allocate, 2175 /// and then confiscate the rest of the parameter registers to insure 2176 /// this. 2177 void ARMTargetLowering::HandleByVal(CCState *State, unsigned &Size, 2178 unsigned Align) const { 2179 // Byval (as with any stack) slots are always at least 4 byte aligned. 2180 Align = std::max(Align, 4U); 2181 2182 unsigned Reg = State->AllocateReg(GPRArgRegs); 2183 if (!Reg) 2184 return; 2185 2186 unsigned AlignInRegs = Align / 4; 2187 unsigned Waste = (ARM::R4 - Reg) % AlignInRegs; 2188 for (unsigned i = 0; i < Waste; ++i) 2189 Reg = State->AllocateReg(GPRArgRegs); 2190 2191 if (!Reg) 2192 return; 2193 2194 unsigned Excess = 4 * (ARM::R4 - Reg); 2195 2196 // Special case when NSAA != SP and parameter size greater than size of 2197 // all remained GPR regs. In that case we can't split parameter, we must 2198 // send it to stack. We also must set NCRN to R4, so waste all 2199 // remained registers. 2200 const unsigned NSAAOffset = State->getNextStackOffset(); 2201 if (NSAAOffset != 0 && Size > Excess) { 2202 while (State->AllocateReg(GPRArgRegs)) 2203 ; 2204 return; 2205 } 2206 2207 // First register for byval parameter is the first register that wasn't 2208 // allocated before this method call, so it would be "reg". 2209 // If parameter is small enough to be saved in range [reg, r4), then 2210 // the end (first after last) register would be reg + param-size-in-regs, 2211 // else parameter would be splitted between registers and stack, 2212 // end register would be r4 in this case. 2213 unsigned ByValRegBegin = Reg; 2214 unsigned ByValRegEnd = std::min<unsigned>(Reg + Size / 4, ARM::R4); 2215 State->addInRegsParamInfo(ByValRegBegin, ByValRegEnd); 2216 // Note, first register is allocated in the beginning of function already, 2217 // allocate remained amount of registers we need. 2218 for (unsigned i = Reg + 1; i != ByValRegEnd; ++i) 2219 State->AllocateReg(GPRArgRegs); 2220 // A byval parameter that is split between registers and memory needs its 2221 // size truncated here. 2222 // In the case where the entire structure fits in registers, we set the 2223 // size in memory to zero. 2224 Size = std::max<int>(Size - Excess, 0); 2225 } 2226 2227 /// MatchingStackOffset - Return true if the given stack call argument is 2228 /// already available in the same position (relatively) of the caller's 2229 /// incoming argument stack. 2230 static 2231 bool MatchingStackOffset(SDValue Arg, unsigned Offset, ISD::ArgFlagsTy Flags, 2232 MachineFrameInfo &MFI, const MachineRegisterInfo *MRI, 2233 const TargetInstrInfo *TII) { 2234 unsigned Bytes = Arg.getValueSizeInBits() / 8; 2235 int FI = std::numeric_limits<int>::max(); 2236 if (Arg.getOpcode() == ISD::CopyFromReg) { 2237 unsigned VR = cast<RegisterSDNode>(Arg.getOperand(1))->getReg(); 2238 if (!TargetRegisterInfo::isVirtualRegister(VR)) 2239 return false; 2240 MachineInstr *Def = MRI->getVRegDef(VR); 2241 if (!Def) 2242 return false; 2243 if (!Flags.isByVal()) { 2244 if (!TII->isLoadFromStackSlot(*Def, FI)) 2245 return false; 2246 } else { 2247 return false; 2248 } 2249 } else if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Arg)) { 2250 if (Flags.isByVal()) 2251 // ByVal argument is passed in as a pointer but it's now being 2252 // dereferenced. e.g. 2253 // define @foo(%struct.X* %A) { 2254 // tail call @bar(%struct.X* byval %A) 2255 // } 2256 return false; 2257 SDValue Ptr = Ld->getBasePtr(); 2258 FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr); 2259 if (!FINode) 2260 return false; 2261 FI = FINode->getIndex(); 2262 } else 2263 return false; 2264 2265 assert(FI != std::numeric_limits<int>::max()); 2266 if (!MFI.isFixedObjectIndex(FI)) 2267 return false; 2268 return Offset == MFI.getObjectOffset(FI) && Bytes == MFI.getObjectSize(FI); 2269 } 2270 2271 /// IsEligibleForTailCallOptimization - Check whether the call is eligible 2272 /// for tail call optimization. Targets which want to do tail call 2273 /// optimization should implement this function. 2274 bool 2275 ARMTargetLowering::IsEligibleForTailCallOptimization(SDValue Callee, 2276 CallingConv::ID CalleeCC, 2277 bool isVarArg, 2278 bool isCalleeStructRet, 2279 bool isCallerStructRet, 2280 const SmallVectorImpl<ISD::OutputArg> &Outs, 2281 const SmallVectorImpl<SDValue> &OutVals, 2282 const SmallVectorImpl<ISD::InputArg> &Ins, 2283 SelectionDAG& DAG) const { 2284 MachineFunction &MF = DAG.getMachineFunction(); 2285 const Function *CallerF = MF.getFunction(); 2286 CallingConv::ID CallerCC = CallerF->getCallingConv(); 2287 2288 assert(Subtarget->supportsTailCall()); 2289 2290 // Look for obvious safe cases to perform tail call optimization that do not 2291 // require ABI changes. This is what gcc calls sibcall. 2292 2293 // Exception-handling functions need a special set of instructions to indicate 2294 // a return to the hardware. Tail-calling another function would probably 2295 // break this. 2296 if (CallerF->hasFnAttribute("interrupt")) 2297 return false; 2298 2299 // Also avoid sibcall optimization if either caller or callee uses struct 2300 // return semantics. 2301 if (isCalleeStructRet || isCallerStructRet) 2302 return false; 2303 2304 // Externally-defined functions with weak linkage should not be 2305 // tail-called on ARM when the OS does not support dynamic 2306 // pre-emption of symbols, as the AAELF spec requires normal calls 2307 // to undefined weak functions to be replaced with a NOP or jump to the 2308 // next instruction. The behaviour of branch instructions in this 2309 // situation (as used for tail calls) is implementation-defined, so we 2310 // cannot rely on the linker replacing the tail call with a return. 2311 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) { 2312 const GlobalValue *GV = G->getGlobal(); 2313 const Triple &TT = getTargetMachine().getTargetTriple(); 2314 if (GV->hasExternalWeakLinkage() && 2315 (!TT.isOSWindows() || TT.isOSBinFormatELF() || TT.isOSBinFormatMachO())) 2316 return false; 2317 } 2318 2319 // Check that the call results are passed in the same way. 2320 LLVMContext &C = *DAG.getContext(); 2321 if (!CCState::resultsCompatible(CalleeCC, CallerCC, MF, C, Ins, 2322 CCAssignFnForReturn(CalleeCC, isVarArg), 2323 CCAssignFnForReturn(CallerCC, isVarArg))) 2324 return false; 2325 // The callee has to preserve all registers the caller needs to preserve. 2326 const ARMBaseRegisterInfo *TRI = Subtarget->getRegisterInfo(); 2327 const uint32_t *CallerPreserved = TRI->getCallPreservedMask(MF, CallerCC); 2328 if (CalleeCC != CallerCC) { 2329 const uint32_t *CalleePreserved = TRI->getCallPreservedMask(MF, CalleeCC); 2330 if (!TRI->regmaskSubsetEqual(CallerPreserved, CalleePreserved)) 2331 return false; 2332 } 2333 2334 // If Caller's vararg or byval argument has been split between registers and 2335 // stack, do not perform tail call, since part of the argument is in caller's 2336 // local frame. 2337 const ARMFunctionInfo *AFI_Caller = MF.getInfo<ARMFunctionInfo>(); 2338 if (AFI_Caller->getArgRegsSaveSize()) 2339 return false; 2340 2341 // If the callee takes no arguments then go on to check the results of the 2342 // call. 2343 if (!Outs.empty()) { 2344 // Check if stack adjustment is needed. For now, do not do this if any 2345 // argument is passed on the stack. 2346 SmallVector<CCValAssign, 16> ArgLocs; 2347 CCState CCInfo(CalleeCC, isVarArg, MF, ArgLocs, C); 2348 CCInfo.AnalyzeCallOperands(Outs, CCAssignFnForCall(CalleeCC, isVarArg)); 2349 if (CCInfo.getNextStackOffset()) { 2350 // Check if the arguments are already laid out in the right way as 2351 // the caller's fixed stack objects. 2352 MachineFrameInfo &MFI = MF.getFrameInfo(); 2353 const MachineRegisterInfo *MRI = &MF.getRegInfo(); 2354 const TargetInstrInfo *TII = Subtarget->getInstrInfo(); 2355 for (unsigned i = 0, realArgIdx = 0, e = ArgLocs.size(); 2356 i != e; 2357 ++i, ++realArgIdx) { 2358 CCValAssign &VA = ArgLocs[i]; 2359 EVT RegVT = VA.getLocVT(); 2360 SDValue Arg = OutVals[realArgIdx]; 2361 ISD::ArgFlagsTy Flags = Outs[realArgIdx].Flags; 2362 if (VA.getLocInfo() == CCValAssign::Indirect) 2363 return false; 2364 if (VA.needsCustom()) { 2365 // f64 and vector types are split into multiple registers or 2366 // register/stack-slot combinations. The types will not match 2367 // the registers; give up on memory f64 refs until we figure 2368 // out what to do about this. 2369 if (!VA.isRegLoc()) 2370 return false; 2371 if (!ArgLocs[++i].isRegLoc()) 2372 return false; 2373 if (RegVT == MVT::v2f64) { 2374 if (!ArgLocs[++i].isRegLoc()) 2375 return false; 2376 if (!ArgLocs[++i].isRegLoc()) 2377 return false; 2378 } 2379 } else if (!VA.isRegLoc()) { 2380 if (!MatchingStackOffset(Arg, VA.getLocMemOffset(), Flags, 2381 MFI, MRI, TII)) 2382 return false; 2383 } 2384 } 2385 } 2386 2387 const MachineRegisterInfo &MRI = MF.getRegInfo(); 2388 if (!parametersInCSRMatch(MRI, CallerPreserved, ArgLocs, OutVals)) 2389 return false; 2390 } 2391 2392 return true; 2393 } 2394 2395 bool 2396 ARMTargetLowering::CanLowerReturn(CallingConv::ID CallConv, 2397 MachineFunction &MF, bool isVarArg, 2398 const SmallVectorImpl<ISD::OutputArg> &Outs, 2399 LLVMContext &Context) const { 2400 SmallVector<CCValAssign, 16> RVLocs; 2401 CCState CCInfo(CallConv, isVarArg, MF, RVLocs, Context); 2402 return CCInfo.CheckReturn(Outs, CCAssignFnForReturn(CallConv, isVarArg)); 2403 } 2404 2405 static SDValue LowerInterruptReturn(SmallVectorImpl<SDValue> &RetOps, 2406 const SDLoc &DL, SelectionDAG &DAG) { 2407 const MachineFunction &MF = DAG.getMachineFunction(); 2408 const Function *F = MF.getFunction(); 2409 2410 StringRef IntKind = F->getFnAttribute("interrupt").getValueAsString(); 2411 2412 // See ARM ARM v7 B1.8.3. On exception entry LR is set to a possibly offset 2413 // version of the "preferred return address". These offsets affect the return 2414 // instruction if this is a return from PL1 without hypervisor extensions. 2415 // IRQ/FIQ: +4 "subs pc, lr, #4" 2416 // SWI: 0 "subs pc, lr, #0" 2417 // ABORT: +4 "subs pc, lr, #4" 2418 // UNDEF: +4/+2 "subs pc, lr, #0" 2419 // UNDEF varies depending on where the exception came from ARM or Thumb 2420 // mode. Alongside GCC, we throw our hands up in disgust and pretend it's 0. 2421 2422 int64_t LROffset; 2423 if (IntKind == "" || IntKind == "IRQ" || IntKind == "FIQ" || 2424 IntKind == "ABORT") 2425 LROffset = 4; 2426 else if (IntKind == "SWI" || IntKind == "UNDEF") 2427 LROffset = 0; 2428 else 2429 report_fatal_error("Unsupported interrupt attribute. If present, value " 2430 "must be one of: IRQ, FIQ, SWI, ABORT or UNDEF"); 2431 2432 RetOps.insert(RetOps.begin() + 1, 2433 DAG.getConstant(LROffset, DL, MVT::i32, false)); 2434 2435 return DAG.getNode(ARMISD::INTRET_FLAG, DL, MVT::Other, RetOps); 2436 } 2437 2438 SDValue 2439 ARMTargetLowering::LowerReturn(SDValue Chain, CallingConv::ID CallConv, 2440 bool isVarArg, 2441 const SmallVectorImpl<ISD::OutputArg> &Outs, 2442 const SmallVectorImpl<SDValue> &OutVals, 2443 const SDLoc &dl, SelectionDAG &DAG) const { 2444 2445 // CCValAssign - represent the assignment of the return value to a location. 2446 SmallVector<CCValAssign, 16> RVLocs; 2447 2448 // CCState - Info about the registers and stack slots. 2449 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs, 2450 *DAG.getContext()); 2451 2452 // Analyze outgoing return values. 2453 CCInfo.AnalyzeReturn(Outs, CCAssignFnForReturn(CallConv, isVarArg)); 2454 2455 SDValue Flag; 2456 SmallVector<SDValue, 4> RetOps; 2457 RetOps.push_back(Chain); // Operand #0 = Chain (updated below) 2458 bool isLittleEndian = Subtarget->isLittle(); 2459 2460 MachineFunction &MF = DAG.getMachineFunction(); 2461 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>(); 2462 AFI->setReturnRegsCount(RVLocs.size()); 2463 2464 // Copy the result values into the output registers. 2465 for (unsigned i = 0, realRVLocIdx = 0; 2466 i != RVLocs.size(); 2467 ++i, ++realRVLocIdx) { 2468 CCValAssign &VA = RVLocs[i]; 2469 assert(VA.isRegLoc() && "Can only return in registers!"); 2470 2471 SDValue Arg = OutVals[realRVLocIdx]; 2472 2473 switch (VA.getLocInfo()) { 2474 default: llvm_unreachable("Unknown loc info!"); 2475 case CCValAssign::Full: break; 2476 case CCValAssign::BCvt: 2477 Arg = DAG.getNode(ISD::BITCAST, dl, VA.getLocVT(), Arg); 2478 break; 2479 } 2480 2481 if (VA.needsCustom()) { 2482 if (VA.getLocVT() == MVT::v2f64) { 2483 // Extract the first half and return it in two registers. 2484 SDValue Half = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg, 2485 DAG.getConstant(0, dl, MVT::i32)); 2486 SDValue HalfGPRs = DAG.getNode(ARMISD::VMOVRRD, dl, 2487 DAG.getVTList(MVT::i32, MVT::i32), Half); 2488 2489 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), 2490 HalfGPRs.getValue(isLittleEndian ? 0 : 1), 2491 Flag); 2492 Flag = Chain.getValue(1); 2493 RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT())); 2494 VA = RVLocs[++i]; // skip ahead to next loc 2495 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), 2496 HalfGPRs.getValue(isLittleEndian ? 1 : 0), 2497 Flag); 2498 Flag = Chain.getValue(1); 2499 RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT())); 2500 VA = RVLocs[++i]; // skip ahead to next loc 2501 2502 // Extract the 2nd half and fall through to handle it as an f64 value. 2503 Arg = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg, 2504 DAG.getConstant(1, dl, MVT::i32)); 2505 } 2506 // Legalize ret f64 -> ret 2 x i32. We always have fmrrd if f64 is 2507 // available. 2508 SDValue fmrrd = DAG.getNode(ARMISD::VMOVRRD, dl, 2509 DAG.getVTList(MVT::i32, MVT::i32), Arg); 2510 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), 2511 fmrrd.getValue(isLittleEndian ? 0 : 1), 2512 Flag); 2513 Flag = Chain.getValue(1); 2514 RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT())); 2515 VA = RVLocs[++i]; // skip ahead to next loc 2516 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), 2517 fmrrd.getValue(isLittleEndian ? 1 : 0), 2518 Flag); 2519 } else 2520 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), Arg, Flag); 2521 2522 // Guarantee that all emitted copies are 2523 // stuck together, avoiding something bad. 2524 Flag = Chain.getValue(1); 2525 RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT())); 2526 } 2527 const ARMBaseRegisterInfo *TRI = Subtarget->getRegisterInfo(); 2528 const MCPhysReg *I = 2529 TRI->getCalleeSavedRegsViaCopy(&DAG.getMachineFunction()); 2530 if (I) { 2531 for (; *I; ++I) { 2532 if (ARM::GPRRegClass.contains(*I)) 2533 RetOps.push_back(DAG.getRegister(*I, MVT::i32)); 2534 else if (ARM::DPRRegClass.contains(*I)) 2535 RetOps.push_back(DAG.getRegister(*I, MVT::getFloatingPointVT(64))); 2536 else 2537 llvm_unreachable("Unexpected register class in CSRsViaCopy!"); 2538 } 2539 } 2540 2541 // Update chain and glue. 2542 RetOps[0] = Chain; 2543 if (Flag.getNode()) 2544 RetOps.push_back(Flag); 2545 2546 // CPUs which aren't M-class use a special sequence to return from 2547 // exceptions (roughly, any instruction setting pc and cpsr simultaneously, 2548 // though we use "subs pc, lr, #N"). 2549 // 2550 // M-class CPUs actually use a normal return sequence with a special 2551 // (hardware-provided) value in LR, so the normal code path works. 2552 if (DAG.getMachineFunction().getFunction()->hasFnAttribute("interrupt") && 2553 !Subtarget->isMClass()) { 2554 if (Subtarget->isThumb1Only()) 2555 report_fatal_error("interrupt attribute is not supported in Thumb1"); 2556 return LowerInterruptReturn(RetOps, dl, DAG); 2557 } 2558 2559 return DAG.getNode(ARMISD::RET_FLAG, dl, MVT::Other, RetOps); 2560 } 2561 2562 bool ARMTargetLowering::isUsedByReturnOnly(SDNode *N, SDValue &Chain) const { 2563 if (N->getNumValues() != 1) 2564 return false; 2565 if (!N->hasNUsesOfValue(1, 0)) 2566 return false; 2567 2568 SDValue TCChain = Chain; 2569 SDNode *Copy = *N->use_begin(); 2570 if (Copy->getOpcode() == ISD::CopyToReg) { 2571 // If the copy has a glue operand, we conservatively assume it isn't safe to 2572 // perform a tail call. 2573 if (Copy->getOperand(Copy->getNumOperands()-1).getValueType() == MVT::Glue) 2574 return false; 2575 TCChain = Copy->getOperand(0); 2576 } else if (Copy->getOpcode() == ARMISD::VMOVRRD) { 2577 SDNode *VMov = Copy; 2578 // f64 returned in a pair of GPRs. 2579 SmallPtrSet<SDNode*, 2> Copies; 2580 for (SDNode::use_iterator UI = VMov->use_begin(), UE = VMov->use_end(); 2581 UI != UE; ++UI) { 2582 if (UI->getOpcode() != ISD::CopyToReg) 2583 return false; 2584 Copies.insert(*UI); 2585 } 2586 if (Copies.size() > 2) 2587 return false; 2588 2589 for (SDNode::use_iterator UI = VMov->use_begin(), UE = VMov->use_end(); 2590 UI != UE; ++UI) { 2591 SDValue UseChain = UI->getOperand(0); 2592 if (Copies.count(UseChain.getNode())) 2593 // Second CopyToReg 2594 Copy = *UI; 2595 else { 2596 // We are at the top of this chain. 2597 // If the copy has a glue operand, we conservatively assume it 2598 // isn't safe to perform a tail call. 2599 if (UI->getOperand(UI->getNumOperands()-1).getValueType() == MVT::Glue) 2600 return false; 2601 // First CopyToReg 2602 TCChain = UseChain; 2603 } 2604 } 2605 } else if (Copy->getOpcode() == ISD::BITCAST) { 2606 // f32 returned in a single GPR. 2607 if (!Copy->hasOneUse()) 2608 return false; 2609 Copy = *Copy->use_begin(); 2610 if (Copy->getOpcode() != ISD::CopyToReg || !Copy->hasNUsesOfValue(1, 0)) 2611 return false; 2612 // If the copy has a glue operand, we conservatively assume it isn't safe to 2613 // perform a tail call. 2614 if (Copy->getOperand(Copy->getNumOperands()-1).getValueType() == MVT::Glue) 2615 return false; 2616 TCChain = Copy->getOperand(0); 2617 } else { 2618 return false; 2619 } 2620 2621 bool HasRet = false; 2622 for (SDNode::use_iterator UI = Copy->use_begin(), UE = Copy->use_end(); 2623 UI != UE; ++UI) { 2624 if (UI->getOpcode() != ARMISD::RET_FLAG && 2625 UI->getOpcode() != ARMISD::INTRET_FLAG) 2626 return false; 2627 HasRet = true; 2628 } 2629 2630 if (!HasRet) 2631 return false; 2632 2633 Chain = TCChain; 2634 return true; 2635 } 2636 2637 bool ARMTargetLowering::mayBeEmittedAsTailCall(const CallInst *CI) const { 2638 if (!Subtarget->supportsTailCall()) 2639 return false; 2640 2641 auto Attr = 2642 CI->getParent()->getParent()->getFnAttribute("disable-tail-calls"); 2643 if (!CI->isTailCall() || Attr.getValueAsString() == "true") 2644 return false; 2645 2646 return true; 2647 } 2648 2649 // Trying to write a 64 bit value so need to split into two 32 bit values first, 2650 // and pass the lower and high parts through. 2651 static SDValue LowerWRITE_REGISTER(SDValue Op, SelectionDAG &DAG) { 2652 SDLoc DL(Op); 2653 SDValue WriteValue = Op->getOperand(2); 2654 2655 // This function is only supposed to be called for i64 type argument. 2656 assert(WriteValue.getValueType() == MVT::i64 2657 && "LowerWRITE_REGISTER called for non-i64 type argument."); 2658 2659 SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, WriteValue, 2660 DAG.getConstant(0, DL, MVT::i32)); 2661 SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, WriteValue, 2662 DAG.getConstant(1, DL, MVT::i32)); 2663 SDValue Ops[] = { Op->getOperand(0), Op->getOperand(1), Lo, Hi }; 2664 return DAG.getNode(ISD::WRITE_REGISTER, DL, MVT::Other, Ops); 2665 } 2666 2667 // ConstantPool, JumpTable, GlobalAddress, and ExternalSymbol are lowered as 2668 // their target counterpart wrapped in the ARMISD::Wrapper node. Suppose N is 2669 // one of the above mentioned nodes. It has to be wrapped because otherwise 2670 // Select(N) returns N. So the raw TargetGlobalAddress nodes, etc. can only 2671 // be used to form addressing mode. These wrapped nodes will be selected 2672 // into MOVi. 2673 SDValue ARMTargetLowering::LowerConstantPool(SDValue Op, 2674 SelectionDAG &DAG) const { 2675 EVT PtrVT = Op.getValueType(); 2676 // FIXME there is no actual debug info here 2677 SDLoc dl(Op); 2678 ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op); 2679 SDValue Res; 2680 2681 // When generating execute-only code Constant Pools must be promoted to the 2682 // global data section. It's a bit ugly that we can't share them across basic 2683 // blocks, but this way we guarantee that execute-only behaves correct with 2684 // position-independent addressing modes. 2685 if (Subtarget->genExecuteOnly()) { 2686 auto AFI = DAG.getMachineFunction().getInfo<ARMFunctionInfo>(); 2687 auto T = const_cast<Type*>(CP->getType()); 2688 auto C = const_cast<Constant*>(CP->getConstVal()); 2689 auto M = const_cast<Module*>(DAG.getMachineFunction(). 2690 getFunction()->getParent()); 2691 auto GV = new GlobalVariable( 2692 *M, T, /*isConst=*/true, GlobalVariable::InternalLinkage, C, 2693 Twine(DAG.getDataLayout().getPrivateGlobalPrefix()) + "CP" + 2694 Twine(DAG.getMachineFunction().getFunctionNumber()) + "_" + 2695 Twine(AFI->createPICLabelUId()) 2696 ); 2697 SDValue GA = DAG.getTargetGlobalAddress(dyn_cast<GlobalValue>(GV), 2698 dl, PtrVT); 2699 return LowerGlobalAddress(GA, DAG); 2700 } 2701 2702 if (CP->isMachineConstantPoolEntry()) 2703 Res = DAG.getTargetConstantPool(CP->getMachineCPVal(), PtrVT, 2704 CP->getAlignment()); 2705 else 2706 Res = DAG.getTargetConstantPool(CP->getConstVal(), PtrVT, 2707 CP->getAlignment()); 2708 return DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Res); 2709 } 2710 2711 unsigned ARMTargetLowering::getJumpTableEncoding() const { 2712 return MachineJumpTableInfo::EK_Inline; 2713 } 2714 2715 SDValue ARMTargetLowering::LowerBlockAddress(SDValue Op, 2716 SelectionDAG &DAG) const { 2717 MachineFunction &MF = DAG.getMachineFunction(); 2718 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>(); 2719 unsigned ARMPCLabelIndex = 0; 2720 SDLoc DL(Op); 2721 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 2722 const BlockAddress *BA = cast<BlockAddressSDNode>(Op)->getBlockAddress(); 2723 SDValue CPAddr; 2724 bool IsPositionIndependent = isPositionIndependent() || Subtarget->isROPI(); 2725 if (!IsPositionIndependent) { 2726 CPAddr = DAG.getTargetConstantPool(BA, PtrVT, 4); 2727 } else { 2728 unsigned PCAdj = Subtarget->isThumb() ? 4 : 8; 2729 ARMPCLabelIndex = AFI->createPICLabelUId(); 2730 ARMConstantPoolValue *CPV = 2731 ARMConstantPoolConstant::Create(BA, ARMPCLabelIndex, 2732 ARMCP::CPBlockAddress, PCAdj); 2733 CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4); 2734 } 2735 CPAddr = DAG.getNode(ARMISD::Wrapper, DL, PtrVT, CPAddr); 2736 SDValue Result = DAG.getLoad( 2737 PtrVT, DL, DAG.getEntryNode(), CPAddr, 2738 MachinePointerInfo::getConstantPool(DAG.getMachineFunction())); 2739 if (!IsPositionIndependent) 2740 return Result; 2741 SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, DL, MVT::i32); 2742 return DAG.getNode(ARMISD::PIC_ADD, DL, PtrVT, Result, PICLabel); 2743 } 2744 2745 /// \brief Convert a TLS address reference into the correct sequence of loads 2746 /// and calls to compute the variable's address for Darwin, and return an 2747 /// SDValue containing the final node. 2748 2749 /// Darwin only has one TLS scheme which must be capable of dealing with the 2750 /// fully general situation, in the worst case. This means: 2751 /// + "extern __thread" declaration. 2752 /// + Defined in a possibly unknown dynamic library. 2753 /// 2754 /// The general system is that each __thread variable has a [3 x i32] descriptor 2755 /// which contains information used by the runtime to calculate the address. The 2756 /// only part of this the compiler needs to know about is the first word, which 2757 /// contains a function pointer that must be called with the address of the 2758 /// entire descriptor in "r0". 2759 /// 2760 /// Since this descriptor may be in a different unit, in general access must 2761 /// proceed along the usual ARM rules. A common sequence to produce is: 2762 /// 2763 /// movw rT1, :lower16:_var$non_lazy_ptr 2764 /// movt rT1, :upper16:_var$non_lazy_ptr 2765 /// ldr r0, [rT1] 2766 /// ldr rT2, [r0] 2767 /// blx rT2 2768 /// [...address now in r0...] 2769 SDValue 2770 ARMTargetLowering::LowerGlobalTLSAddressDarwin(SDValue Op, 2771 SelectionDAG &DAG) const { 2772 assert(Subtarget->isTargetDarwin() && "TLS only supported on Darwin"); 2773 SDLoc DL(Op); 2774 2775 // First step is to get the address of the actua global symbol. This is where 2776 // the TLS descriptor lives. 2777 SDValue DescAddr = LowerGlobalAddressDarwin(Op, DAG); 2778 2779 // The first entry in the descriptor is a function pointer that we must call 2780 // to obtain the address of the variable. 2781 SDValue Chain = DAG.getEntryNode(); 2782 SDValue FuncTLVGet = DAG.getLoad( 2783 MVT::i32, DL, Chain, DescAddr, 2784 MachinePointerInfo::getGOT(DAG.getMachineFunction()), 2785 /* Alignment = */ 4, 2786 MachineMemOperand::MONonTemporal | MachineMemOperand::MODereferenceable | 2787 MachineMemOperand::MOInvariant); 2788 Chain = FuncTLVGet.getValue(1); 2789 2790 MachineFunction &F = DAG.getMachineFunction(); 2791 MachineFrameInfo &MFI = F.getFrameInfo(); 2792 MFI.setAdjustsStack(true); 2793 2794 // TLS calls preserve all registers except those that absolutely must be 2795 // trashed: R0 (it takes an argument), LR (it's a call) and CPSR (let's not be 2796 // silly). 2797 auto TRI = 2798 getTargetMachine().getSubtargetImpl(*F.getFunction())->getRegisterInfo(); 2799 auto ARI = static_cast<const ARMRegisterInfo *>(TRI); 2800 const uint32_t *Mask = ARI->getTLSCallPreservedMask(DAG.getMachineFunction()); 2801 2802 // Finally, we can make the call. This is just a degenerate version of a 2803 // normal AArch64 call node: r0 takes the address of the descriptor, and 2804 // returns the address of the variable in this thread. 2805 Chain = DAG.getCopyToReg(Chain, DL, ARM::R0, DescAddr, SDValue()); 2806 Chain = 2807 DAG.getNode(ARMISD::CALL, DL, DAG.getVTList(MVT::Other, MVT::Glue), 2808 Chain, FuncTLVGet, DAG.getRegister(ARM::R0, MVT::i32), 2809 DAG.getRegisterMask(Mask), Chain.getValue(1)); 2810 return DAG.getCopyFromReg(Chain, DL, ARM::R0, MVT::i32, Chain.getValue(1)); 2811 } 2812 2813 SDValue 2814 ARMTargetLowering::LowerGlobalTLSAddressWindows(SDValue Op, 2815 SelectionDAG &DAG) const { 2816 assert(Subtarget->isTargetWindows() && "Windows specific TLS lowering"); 2817 2818 SDValue Chain = DAG.getEntryNode(); 2819 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 2820 SDLoc DL(Op); 2821 2822 // Load the current TEB (thread environment block) 2823 SDValue Ops[] = {Chain, 2824 DAG.getConstant(Intrinsic::arm_mrc, DL, MVT::i32), 2825 DAG.getConstant(15, DL, MVT::i32), 2826 DAG.getConstant(0, DL, MVT::i32), 2827 DAG.getConstant(13, DL, MVT::i32), 2828 DAG.getConstant(0, DL, MVT::i32), 2829 DAG.getConstant(2, DL, MVT::i32)}; 2830 SDValue CurrentTEB = DAG.getNode(ISD::INTRINSIC_W_CHAIN, DL, 2831 DAG.getVTList(MVT::i32, MVT::Other), Ops); 2832 2833 SDValue TEB = CurrentTEB.getValue(0); 2834 Chain = CurrentTEB.getValue(1); 2835 2836 // Load the ThreadLocalStoragePointer from the TEB 2837 // A pointer to the TLS array is located at offset 0x2c from the TEB. 2838 SDValue TLSArray = 2839 DAG.getNode(ISD::ADD, DL, PtrVT, TEB, DAG.getIntPtrConstant(0x2c, DL)); 2840 TLSArray = DAG.getLoad(PtrVT, DL, Chain, TLSArray, MachinePointerInfo()); 2841 2842 // The pointer to the thread's TLS data area is at the TLS Index scaled by 4 2843 // offset into the TLSArray. 2844 2845 // Load the TLS index from the C runtime 2846 SDValue TLSIndex = 2847 DAG.getTargetExternalSymbol("_tls_index", PtrVT, ARMII::MO_NO_FLAG); 2848 TLSIndex = DAG.getNode(ARMISD::Wrapper, DL, PtrVT, TLSIndex); 2849 TLSIndex = DAG.getLoad(PtrVT, DL, Chain, TLSIndex, MachinePointerInfo()); 2850 2851 SDValue Slot = DAG.getNode(ISD::SHL, DL, PtrVT, TLSIndex, 2852 DAG.getConstant(2, DL, MVT::i32)); 2853 SDValue TLS = DAG.getLoad(PtrVT, DL, Chain, 2854 DAG.getNode(ISD::ADD, DL, PtrVT, TLSArray, Slot), 2855 MachinePointerInfo()); 2856 2857 // Get the offset of the start of the .tls section (section base) 2858 const auto *GA = cast<GlobalAddressSDNode>(Op); 2859 auto *CPV = ARMConstantPoolConstant::Create(GA->getGlobal(), ARMCP::SECREL); 2860 SDValue Offset = DAG.getLoad( 2861 PtrVT, DL, Chain, DAG.getNode(ARMISD::Wrapper, DL, MVT::i32, 2862 DAG.getTargetConstantPool(CPV, PtrVT, 4)), 2863 MachinePointerInfo::getConstantPool(DAG.getMachineFunction())); 2864 2865 return DAG.getNode(ISD::ADD, DL, PtrVT, TLS, Offset); 2866 } 2867 2868 // Lower ISD::GlobalTLSAddress using the "general dynamic" model 2869 SDValue 2870 ARMTargetLowering::LowerToTLSGeneralDynamicModel(GlobalAddressSDNode *GA, 2871 SelectionDAG &DAG) const { 2872 SDLoc dl(GA); 2873 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 2874 unsigned char PCAdj = Subtarget->isThumb() ? 4 : 8; 2875 MachineFunction &MF = DAG.getMachineFunction(); 2876 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>(); 2877 unsigned ARMPCLabelIndex = AFI->createPICLabelUId(); 2878 ARMConstantPoolValue *CPV = 2879 ARMConstantPoolConstant::Create(GA->getGlobal(), ARMPCLabelIndex, 2880 ARMCP::CPValue, PCAdj, ARMCP::TLSGD, true); 2881 SDValue Argument = DAG.getTargetConstantPool(CPV, PtrVT, 4); 2882 Argument = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Argument); 2883 Argument = DAG.getLoad( 2884 PtrVT, dl, DAG.getEntryNode(), Argument, 2885 MachinePointerInfo::getConstantPool(DAG.getMachineFunction())); 2886 SDValue Chain = Argument.getValue(1); 2887 2888 SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, dl, MVT::i32); 2889 Argument = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Argument, PICLabel); 2890 2891 // call __tls_get_addr. 2892 ArgListTy Args; 2893 ArgListEntry Entry; 2894 Entry.Node = Argument; 2895 Entry.Ty = (Type *) Type::getInt32Ty(*DAG.getContext()); 2896 Args.push_back(Entry); 2897 2898 // FIXME: is there useful debug info available here? 2899 TargetLowering::CallLoweringInfo CLI(DAG); 2900 CLI.setDebugLoc(dl).setChain(Chain).setLibCallee( 2901 CallingConv::C, Type::getInt32Ty(*DAG.getContext()), 2902 DAG.getExternalSymbol("__tls_get_addr", PtrVT), std::move(Args)); 2903 2904 std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI); 2905 return CallResult.first; 2906 } 2907 2908 // Lower ISD::GlobalTLSAddress using the "initial exec" or 2909 // "local exec" model. 2910 SDValue 2911 ARMTargetLowering::LowerToTLSExecModels(GlobalAddressSDNode *GA, 2912 SelectionDAG &DAG, 2913 TLSModel::Model model) const { 2914 const GlobalValue *GV = GA->getGlobal(); 2915 SDLoc dl(GA); 2916 SDValue Offset; 2917 SDValue Chain = DAG.getEntryNode(); 2918 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 2919 // Get the Thread Pointer 2920 SDValue ThreadPointer = DAG.getNode(ARMISD::THREAD_POINTER, dl, PtrVT); 2921 2922 if (model == TLSModel::InitialExec) { 2923 MachineFunction &MF = DAG.getMachineFunction(); 2924 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>(); 2925 unsigned ARMPCLabelIndex = AFI->createPICLabelUId(); 2926 // Initial exec model. 2927 unsigned char PCAdj = Subtarget->isThumb() ? 4 : 8; 2928 ARMConstantPoolValue *CPV = 2929 ARMConstantPoolConstant::Create(GA->getGlobal(), ARMPCLabelIndex, 2930 ARMCP::CPValue, PCAdj, ARMCP::GOTTPOFF, 2931 true); 2932 Offset = DAG.getTargetConstantPool(CPV, PtrVT, 4); 2933 Offset = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Offset); 2934 Offset = DAG.getLoad( 2935 PtrVT, dl, Chain, Offset, 2936 MachinePointerInfo::getConstantPool(DAG.getMachineFunction())); 2937 Chain = Offset.getValue(1); 2938 2939 SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, dl, MVT::i32); 2940 Offset = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Offset, PICLabel); 2941 2942 Offset = DAG.getLoad( 2943 PtrVT, dl, Chain, Offset, 2944 MachinePointerInfo::getConstantPool(DAG.getMachineFunction())); 2945 } else { 2946 // local exec model 2947 assert(model == TLSModel::LocalExec); 2948 ARMConstantPoolValue *CPV = 2949 ARMConstantPoolConstant::Create(GV, ARMCP::TPOFF); 2950 Offset = DAG.getTargetConstantPool(CPV, PtrVT, 4); 2951 Offset = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Offset); 2952 Offset = DAG.getLoad( 2953 PtrVT, dl, Chain, Offset, 2954 MachinePointerInfo::getConstantPool(DAG.getMachineFunction())); 2955 } 2956 2957 // The address of the thread local variable is the add of the thread 2958 // pointer with the offset of the variable. 2959 return DAG.getNode(ISD::ADD, dl, PtrVT, ThreadPointer, Offset); 2960 } 2961 2962 SDValue 2963 ARMTargetLowering::LowerGlobalTLSAddress(SDValue Op, SelectionDAG &DAG) const { 2964 if (Subtarget->isTargetDarwin()) 2965 return LowerGlobalTLSAddressDarwin(Op, DAG); 2966 2967 if (Subtarget->isTargetWindows()) 2968 return LowerGlobalTLSAddressWindows(Op, DAG); 2969 2970 // TODO: implement the "local dynamic" model 2971 assert(Subtarget->isTargetELF() && "Only ELF implemented here"); 2972 GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op); 2973 if (DAG.getTarget().Options.EmulatedTLS) 2974 return LowerToTLSEmulatedModel(GA, DAG); 2975 2976 TLSModel::Model model = getTargetMachine().getTLSModel(GA->getGlobal()); 2977 2978 switch (model) { 2979 case TLSModel::GeneralDynamic: 2980 case TLSModel::LocalDynamic: 2981 return LowerToTLSGeneralDynamicModel(GA, DAG); 2982 case TLSModel::InitialExec: 2983 case TLSModel::LocalExec: 2984 return LowerToTLSExecModels(GA, DAG, model); 2985 } 2986 llvm_unreachable("bogus TLS model"); 2987 } 2988 2989 /// Return true if all users of V are within function F, looking through 2990 /// ConstantExprs. 2991 static bool allUsersAreInFunction(const Value *V, const Function *F) { 2992 SmallVector<const User*,4> Worklist; 2993 for (auto *U : V->users()) 2994 Worklist.push_back(U); 2995 while (!Worklist.empty()) { 2996 auto *U = Worklist.pop_back_val(); 2997 if (isa<ConstantExpr>(U)) { 2998 for (auto *UU : U->users()) 2999 Worklist.push_back(UU); 3000 continue; 3001 } 3002 3003 auto *I = dyn_cast<Instruction>(U); 3004 if (!I || I->getParent()->getParent() != F) 3005 return false; 3006 } 3007 return true; 3008 } 3009 3010 /// Return true if all users of V are within some (any) function, looking through 3011 /// ConstantExprs. In other words, are there any global constant users? 3012 static bool allUsersAreInFunctions(const Value *V) { 3013 SmallVector<const User*,4> Worklist; 3014 for (auto *U : V->users()) 3015 Worklist.push_back(U); 3016 while (!Worklist.empty()) { 3017 auto *U = Worklist.pop_back_val(); 3018 if (isa<ConstantExpr>(U)) { 3019 for (auto *UU : U->users()) 3020 Worklist.push_back(UU); 3021 continue; 3022 } 3023 3024 if (!isa<Instruction>(U)) 3025 return false; 3026 } 3027 return true; 3028 } 3029 3030 // Return true if T is an integer, float or an array/vector of either. 3031 static bool isSimpleType(Type *T) { 3032 if (T->isIntegerTy() || T->isFloatingPointTy()) 3033 return true; 3034 Type *SubT = nullptr; 3035 if (T->isArrayTy()) 3036 SubT = T->getArrayElementType(); 3037 else if (T->isVectorTy()) 3038 SubT = T->getVectorElementType(); 3039 else 3040 return false; 3041 return SubT->isIntegerTy() || SubT->isFloatingPointTy(); 3042 } 3043 3044 static SDValue promoteToConstantPool(const GlobalValue *GV, SelectionDAG &DAG, 3045 EVT PtrVT, const SDLoc &dl) { 3046 // If we're creating a pool entry for a constant global with unnamed address, 3047 // and the global is small enough, we can emit it inline into the constant pool 3048 // to save ourselves an indirection. 3049 // 3050 // This is a win if the constant is only used in one function (so it doesn't 3051 // need to be duplicated) or duplicating the constant wouldn't increase code 3052 // size (implying the constant is no larger than 4 bytes). 3053 const Function *F = DAG.getMachineFunction().getFunction(); 3054 3055 // We rely on this decision to inline being idemopotent and unrelated to the 3056 // use-site. We know that if we inline a variable at one use site, we'll 3057 // inline it elsewhere too (and reuse the constant pool entry). Fast-isel 3058 // doesn't know about this optimization, so bail out if it's enabled else 3059 // we could decide to inline here (and thus never emit the GV) but require 3060 // the GV from fast-isel generated code. 3061 if (!EnableConstpoolPromotion || 3062 DAG.getMachineFunction().getTarget().Options.EnableFastISel) 3063 return SDValue(); 3064 3065 auto *GVar = dyn_cast<GlobalVariable>(GV); 3066 if (!GVar || !GVar->hasInitializer() || 3067 !GVar->isConstant() || !GVar->hasGlobalUnnamedAddr() || 3068 !GVar->hasLocalLinkage()) 3069 return SDValue(); 3070 3071 // Ensure that we don't try and inline any type that contains pointers. If 3072 // we inline a value that contains relocations, we move the relocations from 3073 // .data to .text which is not ideal. 3074 auto *Init = GVar->getInitializer(); 3075 if (!isSimpleType(Init->getType())) 3076 return SDValue(); 3077 3078 // The constant islands pass can only really deal with alignment requests 3079 // <= 4 bytes and cannot pad constants itself. Therefore we cannot promote 3080 // any type wanting greater alignment requirements than 4 bytes. We also 3081 // can only promote constants that are multiples of 4 bytes in size or 3082 // are paddable to a multiple of 4. Currently we only try and pad constants 3083 // that are strings for simplicity. 3084 auto *CDAInit = dyn_cast<ConstantDataArray>(Init); 3085 unsigned Size = DAG.getDataLayout().getTypeAllocSize(Init->getType()); 3086 unsigned Align = GVar->getAlignment(); 3087 unsigned RequiredPadding = 4 - (Size % 4); 3088 bool PaddingPossible = 3089 RequiredPadding == 4 || (CDAInit && CDAInit->isString()); 3090 if (!PaddingPossible || Align > 4 || Size > ConstpoolPromotionMaxSize || 3091 Size == 0) 3092 return SDValue(); 3093 3094 unsigned PaddedSize = Size + ((RequiredPadding == 4) ? 0 : RequiredPadding); 3095 MachineFunction &MF = DAG.getMachineFunction(); 3096 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>(); 3097 3098 // We can't bloat the constant pool too much, else the ConstantIslands pass 3099 // may fail to converge. If we haven't promoted this global yet (it may have 3100 // multiple uses), and promoting it would increase the constant pool size (Sz 3101 // > 4), ensure we have space to do so up to MaxTotal. 3102 if (!AFI->getGlobalsPromotedToConstantPool().count(GVar) && Size > 4) 3103 if (AFI->getPromotedConstpoolIncrease() + PaddedSize - 4 >= 3104 ConstpoolPromotionMaxTotal) 3105 return SDValue(); 3106 3107 // This is only valid if all users are in a single function OR it has users 3108 // in multiple functions but it no larger than a pointer. We also check if 3109 // GVar has constant (non-ConstantExpr) users. If so, it essentially has its 3110 // address taken. 3111 if (!allUsersAreInFunction(GVar, F) && 3112 !(Size <= 4 && allUsersAreInFunctions(GVar))) 3113 return SDValue(); 3114 3115 // We're going to inline this global. Pad it out if needed. 3116 if (RequiredPadding != 4) { 3117 StringRef S = CDAInit->getAsString(); 3118 3119 SmallVector<uint8_t,16> V(S.size()); 3120 std::copy(S.bytes_begin(), S.bytes_end(), V.begin()); 3121 while (RequiredPadding--) 3122 V.push_back(0); 3123 Init = ConstantDataArray::get(*DAG.getContext(), V); 3124 } 3125 3126 auto CPVal = ARMConstantPoolConstant::Create(GVar, Init); 3127 SDValue CPAddr = 3128 DAG.getTargetConstantPool(CPVal, PtrVT, /*Align=*/4); 3129 if (!AFI->getGlobalsPromotedToConstantPool().count(GVar)) { 3130 AFI->markGlobalAsPromotedToConstantPool(GVar); 3131 AFI->setPromotedConstpoolIncrease(AFI->getPromotedConstpoolIncrease() + 3132 PaddedSize - 4); 3133 } 3134 ++NumConstpoolPromoted; 3135 return DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr); 3136 } 3137 3138 bool ARMTargetLowering::isReadOnly(const GlobalValue *GV) const { 3139 if (const GlobalAlias *GA = dyn_cast<GlobalAlias>(GV)) 3140 GV = GA->getBaseObject(); 3141 return (isa<GlobalVariable>(GV) && cast<GlobalVariable>(GV)->isConstant()) || 3142 isa<Function>(GV); 3143 } 3144 3145 SDValue ARMTargetLowering::LowerGlobalAddress(SDValue Op, 3146 SelectionDAG &DAG) const { 3147 switch (Subtarget->getTargetTriple().getObjectFormat()) { 3148 default: llvm_unreachable("unknown object format"); 3149 case Triple::COFF: 3150 return LowerGlobalAddressWindows(Op, DAG); 3151 case Triple::ELF: 3152 return LowerGlobalAddressELF(Op, DAG); 3153 case Triple::MachO: 3154 return LowerGlobalAddressDarwin(Op, DAG); 3155 } 3156 } 3157 3158 SDValue ARMTargetLowering::LowerGlobalAddressELF(SDValue Op, 3159 SelectionDAG &DAG) const { 3160 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 3161 SDLoc dl(Op); 3162 const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal(); 3163 const TargetMachine &TM = getTargetMachine(); 3164 bool IsRO = isReadOnly(GV); 3165 3166 // promoteToConstantPool only if not generating XO text section 3167 if (TM.shouldAssumeDSOLocal(*GV->getParent(), GV) && !Subtarget->genExecuteOnly()) 3168 if (SDValue V = promoteToConstantPool(GV, DAG, PtrVT, dl)) 3169 return V; 3170 3171 if (isPositionIndependent()) { 3172 bool UseGOT_PREL = !TM.shouldAssumeDSOLocal(*GV->getParent(), GV); 3173 3174 MachineFunction &MF = DAG.getMachineFunction(); 3175 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>(); 3176 unsigned ARMPCLabelIndex = AFI->createPICLabelUId(); 3177 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 3178 SDLoc dl(Op); 3179 unsigned PCAdj = Subtarget->isThumb() ? 4 : 8; 3180 ARMConstantPoolValue *CPV = ARMConstantPoolConstant::Create( 3181 GV, ARMPCLabelIndex, ARMCP::CPValue, PCAdj, 3182 UseGOT_PREL ? ARMCP::GOT_PREL : ARMCP::no_modifier, 3183 /*AddCurrentAddress=*/UseGOT_PREL); 3184 SDValue CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4); 3185 CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr); 3186 SDValue Result = DAG.getLoad( 3187 PtrVT, dl, DAG.getEntryNode(), CPAddr, 3188 MachinePointerInfo::getConstantPool(DAG.getMachineFunction())); 3189 SDValue Chain = Result.getValue(1); 3190 SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, dl, MVT::i32); 3191 Result = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Result, PICLabel); 3192 if (UseGOT_PREL) 3193 Result = 3194 DAG.getLoad(PtrVT, dl, Chain, Result, 3195 MachinePointerInfo::getGOT(DAG.getMachineFunction())); 3196 return Result; 3197 } else if (Subtarget->isROPI() && IsRO) { 3198 // PC-relative. 3199 SDValue G = DAG.getTargetGlobalAddress(GV, dl, PtrVT); 3200 SDValue Result = DAG.getNode(ARMISD::WrapperPIC, dl, PtrVT, G); 3201 return Result; 3202 } else if (Subtarget->isRWPI() && !IsRO) { 3203 // SB-relative. 3204 SDValue RelAddr; 3205 if (Subtarget->useMovt(DAG.getMachineFunction())) { 3206 ++NumMovwMovt; 3207 SDValue G = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, ARMII::MO_SBREL); 3208 RelAddr = DAG.getNode(ARMISD::Wrapper, dl, PtrVT, G); 3209 } else { // use literal pool for address constant 3210 ARMConstantPoolValue *CPV = 3211 ARMConstantPoolConstant::Create(GV, ARMCP::SBREL); 3212 SDValue CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4); 3213 CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr); 3214 RelAddr = DAG.getLoad( 3215 PtrVT, dl, DAG.getEntryNode(), CPAddr, 3216 MachinePointerInfo::getConstantPool(DAG.getMachineFunction())); 3217 } 3218 SDValue SB = DAG.getCopyFromReg(DAG.getEntryNode(), dl, ARM::R9, PtrVT); 3219 SDValue Result = DAG.getNode(ISD::ADD, dl, PtrVT, SB, RelAddr); 3220 return Result; 3221 } 3222 3223 // If we have T2 ops, we can materialize the address directly via movt/movw 3224 // pair. This is always cheaper. 3225 if (Subtarget->useMovt(DAG.getMachineFunction())) { 3226 ++NumMovwMovt; 3227 // FIXME: Once remat is capable of dealing with instructions with register 3228 // operands, expand this into two nodes. 3229 return DAG.getNode(ARMISD::Wrapper, dl, PtrVT, 3230 DAG.getTargetGlobalAddress(GV, dl, PtrVT)); 3231 } else { 3232 SDValue CPAddr = DAG.getTargetConstantPool(GV, PtrVT, 4); 3233 CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr); 3234 return DAG.getLoad( 3235 PtrVT, dl, DAG.getEntryNode(), CPAddr, 3236 MachinePointerInfo::getConstantPool(DAG.getMachineFunction())); 3237 } 3238 } 3239 3240 SDValue ARMTargetLowering::LowerGlobalAddressDarwin(SDValue Op, 3241 SelectionDAG &DAG) const { 3242 assert(!Subtarget->isROPI() && !Subtarget->isRWPI() && 3243 "ROPI/RWPI not currently supported for Darwin"); 3244 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 3245 SDLoc dl(Op); 3246 const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal(); 3247 3248 if (Subtarget->useMovt(DAG.getMachineFunction())) 3249 ++NumMovwMovt; 3250 3251 // FIXME: Once remat is capable of dealing with instructions with register 3252 // operands, expand this into multiple nodes 3253 unsigned Wrapper = 3254 isPositionIndependent() ? ARMISD::WrapperPIC : ARMISD::Wrapper; 3255 3256 SDValue G = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, ARMII::MO_NONLAZY); 3257 SDValue Result = DAG.getNode(Wrapper, dl, PtrVT, G); 3258 3259 if (Subtarget->isGVIndirectSymbol(GV)) 3260 Result = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Result, 3261 MachinePointerInfo::getGOT(DAG.getMachineFunction())); 3262 return Result; 3263 } 3264 3265 SDValue ARMTargetLowering::LowerGlobalAddressWindows(SDValue Op, 3266 SelectionDAG &DAG) const { 3267 assert(Subtarget->isTargetWindows() && "non-Windows COFF is not supported"); 3268 assert(Subtarget->useMovt(DAG.getMachineFunction()) && 3269 "Windows on ARM expects to use movw/movt"); 3270 assert(!Subtarget->isROPI() && !Subtarget->isRWPI() && 3271 "ROPI/RWPI not currently supported for Windows"); 3272 3273 const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal(); 3274 const ARMII::TOF TargetFlags = 3275 (GV->hasDLLImportStorageClass() ? ARMII::MO_DLLIMPORT : ARMII::MO_NO_FLAG); 3276 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 3277 SDValue Result; 3278 SDLoc DL(Op); 3279 3280 ++NumMovwMovt; 3281 3282 // FIXME: Once remat is capable of dealing with instructions with register 3283 // operands, expand this into two nodes. 3284 Result = DAG.getNode(ARMISD::Wrapper, DL, PtrVT, 3285 DAG.getTargetGlobalAddress(GV, DL, PtrVT, /*Offset=*/0, 3286 TargetFlags)); 3287 if (GV->hasDLLImportStorageClass()) 3288 Result = DAG.getLoad(PtrVT, DL, DAG.getEntryNode(), Result, 3289 MachinePointerInfo::getGOT(DAG.getMachineFunction())); 3290 return Result; 3291 } 3292 3293 SDValue 3294 ARMTargetLowering::LowerEH_SJLJ_SETJMP(SDValue Op, SelectionDAG &DAG) const { 3295 SDLoc dl(Op); 3296 SDValue Val = DAG.getConstant(0, dl, MVT::i32); 3297 return DAG.getNode(ARMISD::EH_SJLJ_SETJMP, dl, 3298 DAG.getVTList(MVT::i32, MVT::Other), Op.getOperand(0), 3299 Op.getOperand(1), Val); 3300 } 3301 3302 SDValue 3303 ARMTargetLowering::LowerEH_SJLJ_LONGJMP(SDValue Op, SelectionDAG &DAG) const { 3304 SDLoc dl(Op); 3305 return DAG.getNode(ARMISD::EH_SJLJ_LONGJMP, dl, MVT::Other, Op.getOperand(0), 3306 Op.getOperand(1), DAG.getConstant(0, dl, MVT::i32)); 3307 } 3308 3309 SDValue ARMTargetLowering::LowerEH_SJLJ_SETUP_DISPATCH(SDValue Op, 3310 SelectionDAG &DAG) const { 3311 SDLoc dl(Op); 3312 return DAG.getNode(ARMISD::EH_SJLJ_SETUP_DISPATCH, dl, MVT::Other, 3313 Op.getOperand(0)); 3314 } 3315 3316 SDValue 3317 ARMTargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op, SelectionDAG &DAG, 3318 const ARMSubtarget *Subtarget) const { 3319 unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue(); 3320 SDLoc dl(Op); 3321 switch (IntNo) { 3322 default: return SDValue(); // Don't custom lower most intrinsics. 3323 case Intrinsic::thread_pointer: { 3324 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 3325 return DAG.getNode(ARMISD::THREAD_POINTER, dl, PtrVT); 3326 } 3327 case Intrinsic::eh_sjlj_lsda: { 3328 MachineFunction &MF = DAG.getMachineFunction(); 3329 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>(); 3330 unsigned ARMPCLabelIndex = AFI->createPICLabelUId(); 3331 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 3332 SDValue CPAddr; 3333 bool IsPositionIndependent = isPositionIndependent(); 3334 unsigned PCAdj = IsPositionIndependent ? (Subtarget->isThumb() ? 4 : 8) : 0; 3335 ARMConstantPoolValue *CPV = 3336 ARMConstantPoolConstant::Create(MF.getFunction(), ARMPCLabelIndex, 3337 ARMCP::CPLSDA, PCAdj); 3338 CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4); 3339 CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr); 3340 SDValue Result = DAG.getLoad( 3341 PtrVT, dl, DAG.getEntryNode(), CPAddr, 3342 MachinePointerInfo::getConstantPool(DAG.getMachineFunction())); 3343 3344 if (IsPositionIndependent) { 3345 SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, dl, MVT::i32); 3346 Result = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Result, PICLabel); 3347 } 3348 return Result; 3349 } 3350 case Intrinsic::arm_neon_vabs: 3351 return DAG.getNode(ISD::ABS, SDLoc(Op), Op.getValueType(), 3352 Op.getOperand(1)); 3353 case Intrinsic::arm_neon_vmulls: 3354 case Intrinsic::arm_neon_vmullu: { 3355 unsigned NewOpc = (IntNo == Intrinsic::arm_neon_vmulls) 3356 ? ARMISD::VMULLs : ARMISD::VMULLu; 3357 return DAG.getNode(NewOpc, SDLoc(Op), Op.getValueType(), 3358 Op.getOperand(1), Op.getOperand(2)); 3359 } 3360 case Intrinsic::arm_neon_vminnm: 3361 case Intrinsic::arm_neon_vmaxnm: { 3362 unsigned NewOpc = (IntNo == Intrinsic::arm_neon_vminnm) 3363 ? ISD::FMINNUM : ISD::FMAXNUM; 3364 return DAG.getNode(NewOpc, SDLoc(Op), Op.getValueType(), 3365 Op.getOperand(1), Op.getOperand(2)); 3366 } 3367 case Intrinsic::arm_neon_vminu: 3368 case Intrinsic::arm_neon_vmaxu: { 3369 if (Op.getValueType().isFloatingPoint()) 3370 return SDValue(); 3371 unsigned NewOpc = (IntNo == Intrinsic::arm_neon_vminu) 3372 ? ISD::UMIN : ISD::UMAX; 3373 return DAG.getNode(NewOpc, SDLoc(Op), Op.getValueType(), 3374 Op.getOperand(1), Op.getOperand(2)); 3375 } 3376 case Intrinsic::arm_neon_vmins: 3377 case Intrinsic::arm_neon_vmaxs: { 3378 // v{min,max}s is overloaded between signed integers and floats. 3379 if (!Op.getValueType().isFloatingPoint()) { 3380 unsigned NewOpc = (IntNo == Intrinsic::arm_neon_vmins) 3381 ? ISD::SMIN : ISD::SMAX; 3382 return DAG.getNode(NewOpc, SDLoc(Op), Op.getValueType(), 3383 Op.getOperand(1), Op.getOperand(2)); 3384 } 3385 unsigned NewOpc = (IntNo == Intrinsic::arm_neon_vmins) 3386 ? ISD::FMINNAN : ISD::FMAXNAN; 3387 return DAG.getNode(NewOpc, SDLoc(Op), Op.getValueType(), 3388 Op.getOperand(1), Op.getOperand(2)); 3389 } 3390 case Intrinsic::arm_neon_vtbl1: 3391 return DAG.getNode(ARMISD::VTBL1, SDLoc(Op), Op.getValueType(), 3392 Op.getOperand(1), Op.getOperand(2)); 3393 case Intrinsic::arm_neon_vtbl2: 3394 return DAG.getNode(ARMISD::VTBL2, SDLoc(Op), Op.getValueType(), 3395 Op.getOperand(1), Op.getOperand(2), Op.getOperand(3)); 3396 } 3397 } 3398 3399 static SDValue LowerATOMIC_FENCE(SDValue Op, SelectionDAG &DAG, 3400 const ARMSubtarget *Subtarget) { 3401 SDLoc dl(Op); 3402 ConstantSDNode *SSIDNode = cast<ConstantSDNode>(Op.getOperand(2)); 3403 auto SSID = static_cast<SyncScope::ID>(SSIDNode->getZExtValue()); 3404 if (SSID == SyncScope::SingleThread) 3405 return Op; 3406 3407 if (!Subtarget->hasDataBarrier()) { 3408 // Some ARMv6 cpus can support data barriers with an mcr instruction. 3409 // Thumb1 and pre-v6 ARM mode use a libcall instead and should never get 3410 // here. 3411 assert(Subtarget->hasV6Ops() && !Subtarget->isThumb() && 3412 "Unexpected ISD::ATOMIC_FENCE encountered. Should be libcall!"); 3413 return DAG.getNode(ARMISD::MEMBARRIER_MCR, dl, MVT::Other, Op.getOperand(0), 3414 DAG.getConstant(0, dl, MVT::i32)); 3415 } 3416 3417 ConstantSDNode *OrdN = cast<ConstantSDNode>(Op.getOperand(1)); 3418 AtomicOrdering Ord = static_cast<AtomicOrdering>(OrdN->getZExtValue()); 3419 ARM_MB::MemBOpt Domain = ARM_MB::ISH; 3420 if (Subtarget->isMClass()) { 3421 // Only a full system barrier exists in the M-class architectures. 3422 Domain = ARM_MB::SY; 3423 } else if (Subtarget->preferISHSTBarriers() && 3424 Ord == AtomicOrdering::Release) { 3425 // Swift happens to implement ISHST barriers in a way that's compatible with 3426 // Release semantics but weaker than ISH so we'd be fools not to use 3427 // it. Beware: other processors probably don't! 3428 Domain = ARM_MB::ISHST; 3429 } 3430 3431 return DAG.getNode(ISD::INTRINSIC_VOID, dl, MVT::Other, Op.getOperand(0), 3432 DAG.getConstant(Intrinsic::arm_dmb, dl, MVT::i32), 3433 DAG.getConstant(Domain, dl, MVT::i32)); 3434 } 3435 3436 static SDValue LowerPREFETCH(SDValue Op, SelectionDAG &DAG, 3437 const ARMSubtarget *Subtarget) { 3438 // ARM pre v5TE and Thumb1 does not have preload instructions. 3439 if (!(Subtarget->isThumb2() || 3440 (!Subtarget->isThumb1Only() && Subtarget->hasV5TEOps()))) 3441 // Just preserve the chain. 3442 return Op.getOperand(0); 3443 3444 SDLoc dl(Op); 3445 unsigned isRead = ~cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue() & 1; 3446 if (!isRead && 3447 (!Subtarget->hasV7Ops() || !Subtarget->hasMPExtension())) 3448 // ARMv7 with MP extension has PLDW. 3449 return Op.getOperand(0); 3450 3451 unsigned isData = cast<ConstantSDNode>(Op.getOperand(4))->getZExtValue(); 3452 if (Subtarget->isThumb()) { 3453 // Invert the bits. 3454 isRead = ~isRead & 1; 3455 isData = ~isData & 1; 3456 } 3457 3458 return DAG.getNode(ARMISD::PRELOAD, dl, MVT::Other, Op.getOperand(0), 3459 Op.getOperand(1), DAG.getConstant(isRead, dl, MVT::i32), 3460 DAG.getConstant(isData, dl, MVT::i32)); 3461 } 3462 3463 static SDValue LowerVASTART(SDValue Op, SelectionDAG &DAG) { 3464 MachineFunction &MF = DAG.getMachineFunction(); 3465 ARMFunctionInfo *FuncInfo = MF.getInfo<ARMFunctionInfo>(); 3466 3467 // vastart just stores the address of the VarArgsFrameIndex slot into the 3468 // memory location argument. 3469 SDLoc dl(Op); 3470 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout()); 3471 SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT); 3472 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue(); 3473 return DAG.getStore(Op.getOperand(0), dl, FR, Op.getOperand(1), 3474 MachinePointerInfo(SV)); 3475 } 3476 3477 SDValue ARMTargetLowering::GetF64FormalArgument(CCValAssign &VA, 3478 CCValAssign &NextVA, 3479 SDValue &Root, 3480 SelectionDAG &DAG, 3481 const SDLoc &dl) const { 3482 MachineFunction &MF = DAG.getMachineFunction(); 3483 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>(); 3484 3485 const TargetRegisterClass *RC; 3486 if (AFI->isThumb1OnlyFunction()) 3487 RC = &ARM::tGPRRegClass; 3488 else 3489 RC = &ARM::GPRRegClass; 3490 3491 // Transform the arguments stored in physical registers into virtual ones. 3492 unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC); 3493 SDValue ArgValue = DAG.getCopyFromReg(Root, dl, Reg, MVT::i32); 3494 3495 SDValue ArgValue2; 3496 if (NextVA.isMemLoc()) { 3497 MachineFrameInfo &MFI = MF.getFrameInfo(); 3498 int FI = MFI.CreateFixedObject(4, NextVA.getLocMemOffset(), true); 3499 3500 // Create load node to retrieve arguments from the stack. 3501 SDValue FIN = DAG.getFrameIndex(FI, getPointerTy(DAG.getDataLayout())); 3502 ArgValue2 = DAG.getLoad( 3503 MVT::i32, dl, Root, FIN, 3504 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI)); 3505 } else { 3506 Reg = MF.addLiveIn(NextVA.getLocReg(), RC); 3507 ArgValue2 = DAG.getCopyFromReg(Root, dl, Reg, MVT::i32); 3508 } 3509 if (!Subtarget->isLittle()) 3510 std::swap (ArgValue, ArgValue2); 3511 return DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, ArgValue, ArgValue2); 3512 } 3513 3514 // The remaining GPRs hold either the beginning of variable-argument 3515 // data, or the beginning of an aggregate passed by value (usually 3516 // byval). Either way, we allocate stack slots adjacent to the data 3517 // provided by our caller, and store the unallocated registers there. 3518 // If this is a variadic function, the va_list pointer will begin with 3519 // these values; otherwise, this reassembles a (byval) structure that 3520 // was split between registers and memory. 3521 // Return: The frame index registers were stored into. 3522 int ARMTargetLowering::StoreByValRegs(CCState &CCInfo, SelectionDAG &DAG, 3523 const SDLoc &dl, SDValue &Chain, 3524 const Value *OrigArg, 3525 unsigned InRegsParamRecordIdx, 3526 int ArgOffset, unsigned ArgSize) const { 3527 // Currently, two use-cases possible: 3528 // Case #1. Non-var-args function, and we meet first byval parameter. 3529 // Setup first unallocated register as first byval register; 3530 // eat all remained registers 3531 // (these two actions are performed by HandleByVal method). 3532 // Then, here, we initialize stack frame with 3533 // "store-reg" instructions. 3534 // Case #2. Var-args function, that doesn't contain byval parameters. 3535 // The same: eat all remained unallocated registers, 3536 // initialize stack frame. 3537 3538 MachineFunction &MF = DAG.getMachineFunction(); 3539 MachineFrameInfo &MFI = MF.getFrameInfo(); 3540 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>(); 3541 unsigned RBegin, REnd; 3542 if (InRegsParamRecordIdx < CCInfo.getInRegsParamsCount()) { 3543 CCInfo.getInRegsParamInfo(InRegsParamRecordIdx, RBegin, REnd); 3544 } else { 3545 unsigned RBeginIdx = CCInfo.getFirstUnallocated(GPRArgRegs); 3546 RBegin = RBeginIdx == 4 ? (unsigned)ARM::R4 : GPRArgRegs[RBeginIdx]; 3547 REnd = ARM::R4; 3548 } 3549 3550 if (REnd != RBegin) 3551 ArgOffset = -4 * (ARM::R4 - RBegin); 3552 3553 auto PtrVT = getPointerTy(DAG.getDataLayout()); 3554 int FrameIndex = MFI.CreateFixedObject(ArgSize, ArgOffset, false); 3555 SDValue FIN = DAG.getFrameIndex(FrameIndex, PtrVT); 3556 3557 SmallVector<SDValue, 4> MemOps; 3558 const TargetRegisterClass *RC = 3559 AFI->isThumb1OnlyFunction() ? &ARM::tGPRRegClass : &ARM::GPRRegClass; 3560 3561 for (unsigned Reg = RBegin, i = 0; Reg < REnd; ++Reg, ++i) { 3562 unsigned VReg = MF.addLiveIn(Reg, RC); 3563 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i32); 3564 SDValue Store = DAG.getStore(Val.getValue(1), dl, Val, FIN, 3565 MachinePointerInfo(OrigArg, 4 * i)); 3566 MemOps.push_back(Store); 3567 FIN = DAG.getNode(ISD::ADD, dl, PtrVT, FIN, DAG.getConstant(4, dl, PtrVT)); 3568 } 3569 3570 if (!MemOps.empty()) 3571 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOps); 3572 return FrameIndex; 3573 } 3574 3575 // Setup stack frame, the va_list pointer will start from. 3576 void ARMTargetLowering::VarArgStyleRegisters(CCState &CCInfo, SelectionDAG &DAG, 3577 const SDLoc &dl, SDValue &Chain, 3578 unsigned ArgOffset, 3579 unsigned TotalArgRegsSaveSize, 3580 bool ForceMutable) const { 3581 MachineFunction &MF = DAG.getMachineFunction(); 3582 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>(); 3583 3584 // Try to store any remaining integer argument regs 3585 // to their spots on the stack so that they may be loaded by dereferencing 3586 // the result of va_next. 3587 // If there is no regs to be stored, just point address after last 3588 // argument passed via stack. 3589 int FrameIndex = StoreByValRegs(CCInfo, DAG, dl, Chain, nullptr, 3590 CCInfo.getInRegsParamsCount(), 3591 CCInfo.getNextStackOffset(), 4); 3592 AFI->setVarArgsFrameIndex(FrameIndex); 3593 } 3594 3595 SDValue ARMTargetLowering::LowerFormalArguments( 3596 SDValue Chain, CallingConv::ID CallConv, bool isVarArg, 3597 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl, 3598 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const { 3599 MachineFunction &MF = DAG.getMachineFunction(); 3600 MachineFrameInfo &MFI = MF.getFrameInfo(); 3601 3602 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>(); 3603 3604 // Assign locations to all of the incoming arguments. 3605 SmallVector<CCValAssign, 16> ArgLocs; 3606 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), ArgLocs, 3607 *DAG.getContext()); 3608 CCInfo.AnalyzeFormalArguments(Ins, CCAssignFnForCall(CallConv, isVarArg)); 3609 3610 SmallVector<SDValue, 16> ArgValues; 3611 SDValue ArgValue; 3612 Function::const_arg_iterator CurOrigArg = MF.getFunction()->arg_begin(); 3613 unsigned CurArgIdx = 0; 3614 3615 // Initially ArgRegsSaveSize is zero. 3616 // Then we increase this value each time we meet byval parameter. 3617 // We also increase this value in case of varargs function. 3618 AFI->setArgRegsSaveSize(0); 3619 3620 // Calculate the amount of stack space that we need to allocate to store 3621 // byval and variadic arguments that are passed in registers. 3622 // We need to know this before we allocate the first byval or variadic 3623 // argument, as they will be allocated a stack slot below the CFA (Canonical 3624 // Frame Address, the stack pointer at entry to the function). 3625 unsigned ArgRegBegin = ARM::R4; 3626 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) { 3627 if (CCInfo.getInRegsParamsProcessed() >= CCInfo.getInRegsParamsCount()) 3628 break; 3629 3630 CCValAssign &VA = ArgLocs[i]; 3631 unsigned Index = VA.getValNo(); 3632 ISD::ArgFlagsTy Flags = Ins[Index].Flags; 3633 if (!Flags.isByVal()) 3634 continue; 3635 3636 assert(VA.isMemLoc() && "unexpected byval pointer in reg"); 3637 unsigned RBegin, REnd; 3638 CCInfo.getInRegsParamInfo(CCInfo.getInRegsParamsProcessed(), RBegin, REnd); 3639 ArgRegBegin = std::min(ArgRegBegin, RBegin); 3640 3641 CCInfo.nextInRegsParam(); 3642 } 3643 CCInfo.rewindByValRegsInfo(); 3644 3645 int lastInsIndex = -1; 3646 if (isVarArg && MFI.hasVAStart()) { 3647 unsigned RegIdx = CCInfo.getFirstUnallocated(GPRArgRegs); 3648 if (RegIdx != array_lengthof(GPRArgRegs)) 3649 ArgRegBegin = std::min(ArgRegBegin, (unsigned)GPRArgRegs[RegIdx]); 3650 } 3651 3652 unsigned TotalArgRegsSaveSize = 4 * (ARM::R4 - ArgRegBegin); 3653 AFI->setArgRegsSaveSize(TotalArgRegsSaveSize); 3654 auto PtrVT = getPointerTy(DAG.getDataLayout()); 3655 3656 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) { 3657 CCValAssign &VA = ArgLocs[i]; 3658 if (Ins[VA.getValNo()].isOrigArg()) { 3659 std::advance(CurOrigArg, 3660 Ins[VA.getValNo()].getOrigArgIndex() - CurArgIdx); 3661 CurArgIdx = Ins[VA.getValNo()].getOrigArgIndex(); 3662 } 3663 // Arguments stored in registers. 3664 if (VA.isRegLoc()) { 3665 EVT RegVT = VA.getLocVT(); 3666 3667 if (VA.needsCustom()) { 3668 // f64 and vector types are split up into multiple registers or 3669 // combinations of registers and stack slots. 3670 if (VA.getLocVT() == MVT::v2f64) { 3671 SDValue ArgValue1 = GetF64FormalArgument(VA, ArgLocs[++i], 3672 Chain, DAG, dl); 3673 VA = ArgLocs[++i]; // skip ahead to next loc 3674 SDValue ArgValue2; 3675 if (VA.isMemLoc()) { 3676 int FI = MFI.CreateFixedObject(8, VA.getLocMemOffset(), true); 3677 SDValue FIN = DAG.getFrameIndex(FI, PtrVT); 3678 ArgValue2 = DAG.getLoad(MVT::f64, dl, Chain, FIN, 3679 MachinePointerInfo::getFixedStack( 3680 DAG.getMachineFunction(), FI)); 3681 } else { 3682 ArgValue2 = GetF64FormalArgument(VA, ArgLocs[++i], 3683 Chain, DAG, dl); 3684 } 3685 ArgValue = DAG.getNode(ISD::UNDEF, dl, MVT::v2f64); 3686 ArgValue = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, 3687 ArgValue, ArgValue1, 3688 DAG.getIntPtrConstant(0, dl)); 3689 ArgValue = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, 3690 ArgValue, ArgValue2, 3691 DAG.getIntPtrConstant(1, dl)); 3692 } else 3693 ArgValue = GetF64FormalArgument(VA, ArgLocs[++i], Chain, DAG, dl); 3694 3695 } else { 3696 const TargetRegisterClass *RC; 3697 3698 if (RegVT == MVT::f32) 3699 RC = &ARM::SPRRegClass; 3700 else if (RegVT == MVT::f64) 3701 RC = &ARM::DPRRegClass; 3702 else if (RegVT == MVT::v2f64) 3703 RC = &ARM::QPRRegClass; 3704 else if (RegVT == MVT::i32) 3705 RC = AFI->isThumb1OnlyFunction() ? &ARM::tGPRRegClass 3706 : &ARM::GPRRegClass; 3707 else 3708 llvm_unreachable("RegVT not supported by FORMAL_ARGUMENTS Lowering"); 3709 3710 // Transform the arguments in physical registers into virtual ones. 3711 unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC); 3712 ArgValue = DAG.getCopyFromReg(Chain, dl, Reg, RegVT); 3713 } 3714 3715 // If this is an 8 or 16-bit value, it is really passed promoted 3716 // to 32 bits. Insert an assert[sz]ext to capture this, then 3717 // truncate to the right size. 3718 switch (VA.getLocInfo()) { 3719 default: llvm_unreachable("Unknown loc info!"); 3720 case CCValAssign::Full: break; 3721 case CCValAssign::BCvt: 3722 ArgValue = DAG.getNode(ISD::BITCAST, dl, VA.getValVT(), ArgValue); 3723 break; 3724 case CCValAssign::SExt: 3725 ArgValue = DAG.getNode(ISD::AssertSext, dl, RegVT, ArgValue, 3726 DAG.getValueType(VA.getValVT())); 3727 ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue); 3728 break; 3729 case CCValAssign::ZExt: 3730 ArgValue = DAG.getNode(ISD::AssertZext, dl, RegVT, ArgValue, 3731 DAG.getValueType(VA.getValVT())); 3732 ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue); 3733 break; 3734 } 3735 3736 InVals.push_back(ArgValue); 3737 3738 } else { // VA.isRegLoc() 3739 // sanity check 3740 assert(VA.isMemLoc()); 3741 assert(VA.getValVT() != MVT::i64 && "i64 should already be lowered"); 3742 3743 int index = VA.getValNo(); 3744 3745 // Some Ins[] entries become multiple ArgLoc[] entries. 3746 // Process them only once. 3747 if (index != lastInsIndex) 3748 { 3749 ISD::ArgFlagsTy Flags = Ins[index].Flags; 3750 // FIXME: For now, all byval parameter objects are marked mutable. 3751 // This can be changed with more analysis. 3752 // In case of tail call optimization mark all arguments mutable. 3753 // Since they could be overwritten by lowering of arguments in case of 3754 // a tail call. 3755 if (Flags.isByVal()) { 3756 assert(Ins[index].isOrigArg() && 3757 "Byval arguments cannot be implicit"); 3758 unsigned CurByValIndex = CCInfo.getInRegsParamsProcessed(); 3759 3760 int FrameIndex = StoreByValRegs( 3761 CCInfo, DAG, dl, Chain, &*CurOrigArg, CurByValIndex, 3762 VA.getLocMemOffset(), Flags.getByValSize()); 3763 InVals.push_back(DAG.getFrameIndex(FrameIndex, PtrVT)); 3764 CCInfo.nextInRegsParam(); 3765 } else { 3766 unsigned FIOffset = VA.getLocMemOffset(); 3767 int FI = MFI.CreateFixedObject(VA.getLocVT().getSizeInBits()/8, 3768 FIOffset, true); 3769 3770 // Create load nodes to retrieve arguments from the stack. 3771 SDValue FIN = DAG.getFrameIndex(FI, PtrVT); 3772 InVals.push_back(DAG.getLoad(VA.getValVT(), dl, Chain, FIN, 3773 MachinePointerInfo::getFixedStack( 3774 DAG.getMachineFunction(), FI))); 3775 } 3776 lastInsIndex = index; 3777 } 3778 } 3779 } 3780 3781 // varargs 3782 if (isVarArg && MFI.hasVAStart()) 3783 VarArgStyleRegisters(CCInfo, DAG, dl, Chain, 3784 CCInfo.getNextStackOffset(), 3785 TotalArgRegsSaveSize); 3786 3787 AFI->setArgumentStackSize(CCInfo.getNextStackOffset()); 3788 3789 return Chain; 3790 } 3791 3792 /// isFloatingPointZero - Return true if this is +0.0. 3793 static bool isFloatingPointZero(SDValue Op) { 3794 if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Op)) 3795 return CFP->getValueAPF().isPosZero(); 3796 else if (ISD::isEXTLoad(Op.getNode()) || ISD::isNON_EXTLoad(Op.getNode())) { 3797 // Maybe this has already been legalized into the constant pool? 3798 if (Op.getOperand(1).getOpcode() == ARMISD::Wrapper) { 3799 SDValue WrapperOp = Op.getOperand(1).getOperand(0); 3800 if (ConstantPoolSDNode *CP = dyn_cast<ConstantPoolSDNode>(WrapperOp)) 3801 if (const ConstantFP *CFP = dyn_cast<ConstantFP>(CP->getConstVal())) 3802 return CFP->getValueAPF().isPosZero(); 3803 } 3804 } else if (Op->getOpcode() == ISD::BITCAST && 3805 Op->getValueType(0) == MVT::f64) { 3806 // Handle (ISD::BITCAST (ARMISD::VMOVIMM (ISD::TargetConstant 0)) MVT::f64) 3807 // created by LowerConstantFP(). 3808 SDValue BitcastOp = Op->getOperand(0); 3809 if (BitcastOp->getOpcode() == ARMISD::VMOVIMM && 3810 isNullConstant(BitcastOp->getOperand(0))) 3811 return true; 3812 } 3813 return false; 3814 } 3815 3816 /// Returns appropriate ARM CMP (cmp) and corresponding condition code for 3817 /// the given operands. 3818 SDValue ARMTargetLowering::getARMCmp(SDValue LHS, SDValue RHS, ISD::CondCode CC, 3819 SDValue &ARMcc, SelectionDAG &DAG, 3820 const SDLoc &dl) const { 3821 if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS.getNode())) { 3822 unsigned C = RHSC->getZExtValue(); 3823 if (!isLegalICmpImmediate(C)) { 3824 // Constant does not fit, try adjusting it by one? 3825 switch (CC) { 3826 default: break; 3827 case ISD::SETLT: 3828 case ISD::SETGE: 3829 if (C != 0x80000000 && isLegalICmpImmediate(C-1)) { 3830 CC = (CC == ISD::SETLT) ? ISD::SETLE : ISD::SETGT; 3831 RHS = DAG.getConstant(C - 1, dl, MVT::i32); 3832 } 3833 break; 3834 case ISD::SETULT: 3835 case ISD::SETUGE: 3836 if (C != 0 && isLegalICmpImmediate(C-1)) { 3837 CC = (CC == ISD::SETULT) ? ISD::SETULE : ISD::SETUGT; 3838 RHS = DAG.getConstant(C - 1, dl, MVT::i32); 3839 } 3840 break; 3841 case ISD::SETLE: 3842 case ISD::SETGT: 3843 if (C != 0x7fffffff && isLegalICmpImmediate(C+1)) { 3844 CC = (CC == ISD::SETLE) ? ISD::SETLT : ISD::SETGE; 3845 RHS = DAG.getConstant(C + 1, dl, MVT::i32); 3846 } 3847 break; 3848 case ISD::SETULE: 3849 case ISD::SETUGT: 3850 if (C != 0xffffffff && isLegalICmpImmediate(C+1)) { 3851 CC = (CC == ISD::SETULE) ? ISD::SETULT : ISD::SETUGE; 3852 RHS = DAG.getConstant(C + 1, dl, MVT::i32); 3853 } 3854 break; 3855 } 3856 } 3857 } 3858 3859 ARMCC::CondCodes CondCode = IntCCToARMCC(CC); 3860 ARMISD::NodeType CompareType; 3861 switch (CondCode) { 3862 default: 3863 CompareType = ARMISD::CMP; 3864 break; 3865 case ARMCC::EQ: 3866 case ARMCC::NE: 3867 // Uses only Z Flag 3868 CompareType = ARMISD::CMPZ; 3869 break; 3870 } 3871 ARMcc = DAG.getConstant(CondCode, dl, MVT::i32); 3872 return DAG.getNode(CompareType, dl, MVT::Glue, LHS, RHS); 3873 } 3874 3875 /// Returns a appropriate VFP CMP (fcmp{s|d}+fmstat) for the given operands. 3876 SDValue ARMTargetLowering::getVFPCmp(SDValue LHS, SDValue RHS, 3877 SelectionDAG &DAG, const SDLoc &dl, 3878 bool InvalidOnQNaN) const { 3879 assert(!Subtarget->isFPOnlySP() || RHS.getValueType() != MVT::f64); 3880 SDValue Cmp; 3881 SDValue C = DAG.getConstant(InvalidOnQNaN, dl, MVT::i32); 3882 if (!isFloatingPointZero(RHS)) 3883 Cmp = DAG.getNode(ARMISD::CMPFP, dl, MVT::Glue, LHS, RHS, C); 3884 else 3885 Cmp = DAG.getNode(ARMISD::CMPFPw0, dl, MVT::Glue, LHS, C); 3886 return DAG.getNode(ARMISD::FMSTAT, dl, MVT::Glue, Cmp); 3887 } 3888 3889 /// duplicateCmp - Glue values can have only one use, so this function 3890 /// duplicates a comparison node. 3891 SDValue 3892 ARMTargetLowering::duplicateCmp(SDValue Cmp, SelectionDAG &DAG) const { 3893 unsigned Opc = Cmp.getOpcode(); 3894 SDLoc DL(Cmp); 3895 if (Opc == ARMISD::CMP || Opc == ARMISD::CMPZ) 3896 return DAG.getNode(Opc, DL, MVT::Glue, Cmp.getOperand(0),Cmp.getOperand(1)); 3897 3898 assert(Opc == ARMISD::FMSTAT && "unexpected comparison operation"); 3899 Cmp = Cmp.getOperand(0); 3900 Opc = Cmp.getOpcode(); 3901 if (Opc == ARMISD::CMPFP) 3902 Cmp = DAG.getNode(Opc, DL, MVT::Glue, Cmp.getOperand(0), 3903 Cmp.getOperand(1), Cmp.getOperand(2)); 3904 else { 3905 assert(Opc == ARMISD::CMPFPw0 && "unexpected operand of FMSTAT"); 3906 Cmp = DAG.getNode(Opc, DL, MVT::Glue, Cmp.getOperand(0), 3907 Cmp.getOperand(1)); 3908 } 3909 return DAG.getNode(ARMISD::FMSTAT, DL, MVT::Glue, Cmp); 3910 } 3911 3912 std::pair<SDValue, SDValue> 3913 ARMTargetLowering::getARMXALUOOp(SDValue Op, SelectionDAG &DAG, 3914 SDValue &ARMcc) const { 3915 assert(Op.getValueType() == MVT::i32 && "Unsupported value type"); 3916 3917 SDValue Value, OverflowCmp; 3918 SDValue LHS = Op.getOperand(0); 3919 SDValue RHS = Op.getOperand(1); 3920 SDLoc dl(Op); 3921 3922 // FIXME: We are currently always generating CMPs because we don't support 3923 // generating CMN through the backend. This is not as good as the natural 3924 // CMP case because it causes a register dependency and cannot be folded 3925 // later. 3926 3927 switch (Op.getOpcode()) { 3928 default: 3929 llvm_unreachable("Unknown overflow instruction!"); 3930 case ISD::SADDO: 3931 ARMcc = DAG.getConstant(ARMCC::VC, dl, MVT::i32); 3932 Value = DAG.getNode(ISD::ADD, dl, Op.getValueType(), LHS, RHS); 3933 OverflowCmp = DAG.getNode(ARMISD::CMP, dl, MVT::Glue, Value, LHS); 3934 break; 3935 case ISD::UADDO: 3936 ARMcc = DAG.getConstant(ARMCC::HS, dl, MVT::i32); 3937 Value = DAG.getNode(ISD::ADD, dl, Op.getValueType(), LHS, RHS); 3938 OverflowCmp = DAG.getNode(ARMISD::CMP, dl, MVT::Glue, Value, LHS); 3939 break; 3940 case ISD::SSUBO: 3941 ARMcc = DAG.getConstant(ARMCC::VC, dl, MVT::i32); 3942 Value = DAG.getNode(ISD::SUB, dl, Op.getValueType(), LHS, RHS); 3943 OverflowCmp = DAG.getNode(ARMISD::CMP, dl, MVT::Glue, LHS, RHS); 3944 break; 3945 case ISD::USUBO: 3946 ARMcc = DAG.getConstant(ARMCC::HS, dl, MVT::i32); 3947 Value = DAG.getNode(ISD::SUB, dl, Op.getValueType(), LHS, RHS); 3948 OverflowCmp = DAG.getNode(ARMISD::CMP, dl, MVT::Glue, LHS, RHS); 3949 break; 3950 } // switch (...) 3951 3952 return std::make_pair(Value, OverflowCmp); 3953 } 3954 3955 SDValue 3956 ARMTargetLowering::LowerXALUO(SDValue Op, SelectionDAG &DAG) const { 3957 // Let legalize expand this if it isn't a legal type yet. 3958 if (!DAG.getTargetLoweringInfo().isTypeLegal(Op.getValueType())) 3959 return SDValue(); 3960 3961 SDValue Value, OverflowCmp; 3962 SDValue ARMcc; 3963 std::tie(Value, OverflowCmp) = getARMXALUOOp(Op, DAG, ARMcc); 3964 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32); 3965 SDLoc dl(Op); 3966 // We use 0 and 1 as false and true values. 3967 SDValue TVal = DAG.getConstant(1, dl, MVT::i32); 3968 SDValue FVal = DAG.getConstant(0, dl, MVT::i32); 3969 EVT VT = Op.getValueType(); 3970 3971 SDValue Overflow = DAG.getNode(ARMISD::CMOV, dl, VT, TVal, FVal, 3972 ARMcc, CCR, OverflowCmp); 3973 3974 SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32); 3975 return DAG.getNode(ISD::MERGE_VALUES, dl, VTs, Value, Overflow); 3976 } 3977 3978 SDValue ARMTargetLowering::LowerSELECT(SDValue Op, SelectionDAG &DAG) const { 3979 SDValue Cond = Op.getOperand(0); 3980 SDValue SelectTrue = Op.getOperand(1); 3981 SDValue SelectFalse = Op.getOperand(2); 3982 SDLoc dl(Op); 3983 unsigned Opc = Cond.getOpcode(); 3984 3985 if (Cond.getResNo() == 1 && 3986 (Opc == ISD::SADDO || Opc == ISD::UADDO || Opc == ISD::SSUBO || 3987 Opc == ISD::USUBO)) { 3988 if (!DAG.getTargetLoweringInfo().isTypeLegal(Cond->getValueType(0))) 3989 return SDValue(); 3990 3991 SDValue Value, OverflowCmp; 3992 SDValue ARMcc; 3993 std::tie(Value, OverflowCmp) = getARMXALUOOp(Cond, DAG, ARMcc); 3994 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32); 3995 EVT VT = Op.getValueType(); 3996 3997 return getCMOV(dl, VT, SelectTrue, SelectFalse, ARMcc, CCR, 3998 OverflowCmp, DAG); 3999 } 4000 4001 // Convert: 4002 // 4003 // (select (cmov 1, 0, cond), t, f) -> (cmov t, f, cond) 4004 // (select (cmov 0, 1, cond), t, f) -> (cmov f, t, cond) 4005 // 4006 if (Cond.getOpcode() == ARMISD::CMOV && Cond.hasOneUse()) { 4007 const ConstantSDNode *CMOVTrue = 4008 dyn_cast<ConstantSDNode>(Cond.getOperand(0)); 4009 const ConstantSDNode *CMOVFalse = 4010 dyn_cast<ConstantSDNode>(Cond.getOperand(1)); 4011 4012 if (CMOVTrue && CMOVFalse) { 4013 unsigned CMOVTrueVal = CMOVTrue->getZExtValue(); 4014 unsigned CMOVFalseVal = CMOVFalse->getZExtValue(); 4015 4016 SDValue True; 4017 SDValue False; 4018 if (CMOVTrueVal == 1 && CMOVFalseVal == 0) { 4019 True = SelectTrue; 4020 False = SelectFalse; 4021 } else if (CMOVTrueVal == 0 && CMOVFalseVal == 1) { 4022 True = SelectFalse; 4023 False = SelectTrue; 4024 } 4025 4026 if (True.getNode() && False.getNode()) { 4027 EVT VT = Op.getValueType(); 4028 SDValue ARMcc = Cond.getOperand(2); 4029 SDValue CCR = Cond.getOperand(3); 4030 SDValue Cmp = duplicateCmp(Cond.getOperand(4), DAG); 4031 assert(True.getValueType() == VT); 4032 return getCMOV(dl, VT, True, False, ARMcc, CCR, Cmp, DAG); 4033 } 4034 } 4035 } 4036 4037 // ARM's BooleanContents value is UndefinedBooleanContent. Mask out the 4038 // undefined bits before doing a full-word comparison with zero. 4039 Cond = DAG.getNode(ISD::AND, dl, Cond.getValueType(), Cond, 4040 DAG.getConstant(1, dl, Cond.getValueType())); 4041 4042 return DAG.getSelectCC(dl, Cond, 4043 DAG.getConstant(0, dl, Cond.getValueType()), 4044 SelectTrue, SelectFalse, ISD::SETNE); 4045 } 4046 4047 static void checkVSELConstraints(ISD::CondCode CC, ARMCC::CondCodes &CondCode, 4048 bool &swpCmpOps, bool &swpVselOps) { 4049 // Start by selecting the GE condition code for opcodes that return true for 4050 // 'equality' 4051 if (CC == ISD::SETUGE || CC == ISD::SETOGE || CC == ISD::SETOLE || 4052 CC == ISD::SETULE) 4053 CondCode = ARMCC::GE; 4054 4055 // and GT for opcodes that return false for 'equality'. 4056 else if (CC == ISD::SETUGT || CC == ISD::SETOGT || CC == ISD::SETOLT || 4057 CC == ISD::SETULT) 4058 CondCode = ARMCC::GT; 4059 4060 // Since we are constrained to GE/GT, if the opcode contains 'less', we need 4061 // to swap the compare operands. 4062 if (CC == ISD::SETOLE || CC == ISD::SETULE || CC == ISD::SETOLT || 4063 CC == ISD::SETULT) 4064 swpCmpOps = true; 4065 4066 // Both GT and GE are ordered comparisons, and return false for 'unordered'. 4067 // If we have an unordered opcode, we need to swap the operands to the VSEL 4068 // instruction (effectively negating the condition). 4069 // 4070 // This also has the effect of swapping which one of 'less' or 'greater' 4071 // returns true, so we also swap the compare operands. It also switches 4072 // whether we return true for 'equality', so we compensate by picking the 4073 // opposite condition code to our original choice. 4074 if (CC == ISD::SETULE || CC == ISD::SETULT || CC == ISD::SETUGE || 4075 CC == ISD::SETUGT) { 4076 swpCmpOps = !swpCmpOps; 4077 swpVselOps = !swpVselOps; 4078 CondCode = CondCode == ARMCC::GT ? ARMCC::GE : ARMCC::GT; 4079 } 4080 4081 // 'ordered' is 'anything but unordered', so use the VS condition code and 4082 // swap the VSEL operands. 4083 if (CC == ISD::SETO) { 4084 CondCode = ARMCC::VS; 4085 swpVselOps = true; 4086 } 4087 4088 // 'unordered or not equal' is 'anything but equal', so use the EQ condition 4089 // code and swap the VSEL operands. 4090 if (CC == ISD::SETUNE) { 4091 CondCode = ARMCC::EQ; 4092 swpVselOps = true; 4093 } 4094 } 4095 4096 SDValue ARMTargetLowering::getCMOV(const SDLoc &dl, EVT VT, SDValue FalseVal, 4097 SDValue TrueVal, SDValue ARMcc, SDValue CCR, 4098 SDValue Cmp, SelectionDAG &DAG) const { 4099 if (Subtarget->isFPOnlySP() && VT == MVT::f64) { 4100 FalseVal = DAG.getNode(ARMISD::VMOVRRD, dl, 4101 DAG.getVTList(MVT::i32, MVT::i32), FalseVal); 4102 TrueVal = DAG.getNode(ARMISD::VMOVRRD, dl, 4103 DAG.getVTList(MVT::i32, MVT::i32), TrueVal); 4104 4105 SDValue TrueLow = TrueVal.getValue(0); 4106 SDValue TrueHigh = TrueVal.getValue(1); 4107 SDValue FalseLow = FalseVal.getValue(0); 4108 SDValue FalseHigh = FalseVal.getValue(1); 4109 4110 SDValue Low = DAG.getNode(ARMISD::CMOV, dl, MVT::i32, FalseLow, TrueLow, 4111 ARMcc, CCR, Cmp); 4112 SDValue High = DAG.getNode(ARMISD::CMOV, dl, MVT::i32, FalseHigh, TrueHigh, 4113 ARMcc, CCR, duplicateCmp(Cmp, DAG)); 4114 4115 return DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Low, High); 4116 } else { 4117 return DAG.getNode(ARMISD::CMOV, dl, VT, FalseVal, TrueVal, ARMcc, CCR, 4118 Cmp); 4119 } 4120 } 4121 4122 static bool isGTorGE(ISD::CondCode CC) { 4123 return CC == ISD::SETGT || CC == ISD::SETGE; 4124 } 4125 4126 static bool isLTorLE(ISD::CondCode CC) { 4127 return CC == ISD::SETLT || CC == ISD::SETLE; 4128 } 4129 4130 // See if a conditional (LHS CC RHS ? TrueVal : FalseVal) is lower-saturating. 4131 // All of these conditions (and their <= and >= counterparts) will do: 4132 // x < k ? k : x 4133 // x > k ? x : k 4134 // k < x ? x : k 4135 // k > x ? k : x 4136 static bool isLowerSaturate(const SDValue LHS, const SDValue RHS, 4137 const SDValue TrueVal, const SDValue FalseVal, 4138 const ISD::CondCode CC, const SDValue K) { 4139 return (isGTorGE(CC) && 4140 ((K == LHS && K == TrueVal) || (K == RHS && K == FalseVal))) || 4141 (isLTorLE(CC) && 4142 ((K == RHS && K == TrueVal) || (K == LHS && K == FalseVal))); 4143 } 4144 4145 // Similar to isLowerSaturate(), but checks for upper-saturating conditions. 4146 static bool isUpperSaturate(const SDValue LHS, const SDValue RHS, 4147 const SDValue TrueVal, const SDValue FalseVal, 4148 const ISD::CondCode CC, const SDValue K) { 4149 return (isGTorGE(CC) && 4150 ((K == RHS && K == TrueVal) || (K == LHS && K == FalseVal))) || 4151 (isLTorLE(CC) && 4152 ((K == LHS && K == TrueVal) || (K == RHS && K == FalseVal))); 4153 } 4154 4155 // Check if two chained conditionals could be converted into SSAT. 4156 // 4157 // SSAT can replace a set of two conditional selectors that bound a number to an 4158 // interval of type [k, ~k] when k + 1 is a power of 2. Here are some examples: 4159 // 4160 // x < -k ? -k : (x > k ? k : x) 4161 // x < -k ? -k : (x < k ? x : k) 4162 // x > -k ? (x > k ? k : x) : -k 4163 // x < k ? (x < -k ? -k : x) : k 4164 // etc. 4165 // 4166 // It returns true if the conversion can be done, false otherwise. 4167 // Additionally, the variable is returned in parameter V and the constant in K. 4168 static bool isSaturatingConditional(const SDValue &Op, SDValue &V, 4169 uint64_t &K) { 4170 SDValue LHS1 = Op.getOperand(0); 4171 SDValue RHS1 = Op.getOperand(1); 4172 SDValue TrueVal1 = Op.getOperand(2); 4173 SDValue FalseVal1 = Op.getOperand(3); 4174 ISD::CondCode CC1 = cast<CondCodeSDNode>(Op.getOperand(4))->get(); 4175 4176 const SDValue Op2 = isa<ConstantSDNode>(TrueVal1) ? FalseVal1 : TrueVal1; 4177 if (Op2.getOpcode() != ISD::SELECT_CC) 4178 return false; 4179 4180 SDValue LHS2 = Op2.getOperand(0); 4181 SDValue RHS2 = Op2.getOperand(1); 4182 SDValue TrueVal2 = Op2.getOperand(2); 4183 SDValue FalseVal2 = Op2.getOperand(3); 4184 ISD::CondCode CC2 = cast<CondCodeSDNode>(Op2.getOperand(4))->get(); 4185 4186 // Find out which are the constants and which are the variables 4187 // in each conditional 4188 SDValue *K1 = isa<ConstantSDNode>(LHS1) ? &LHS1 : isa<ConstantSDNode>(RHS1) 4189 ? &RHS1 4190 : nullptr; 4191 SDValue *K2 = isa<ConstantSDNode>(LHS2) ? &LHS2 : isa<ConstantSDNode>(RHS2) 4192 ? &RHS2 4193 : nullptr; 4194 SDValue K2Tmp = isa<ConstantSDNode>(TrueVal2) ? TrueVal2 : FalseVal2; 4195 SDValue V1Tmp = (K1 && *K1 == LHS1) ? RHS1 : LHS1; 4196 SDValue V2Tmp = (K2 && *K2 == LHS2) ? RHS2 : LHS2; 4197 SDValue V2 = (K2Tmp == TrueVal2) ? FalseVal2 : TrueVal2; 4198 4199 // We must detect cases where the original operations worked with 16- or 4200 // 8-bit values. In such case, V2Tmp != V2 because the comparison operations 4201 // must work with sign-extended values but the select operations return 4202 // the original non-extended value. 4203 SDValue V2TmpReg = V2Tmp; 4204 if (V2Tmp->getOpcode() == ISD::SIGN_EXTEND_INREG) 4205 V2TmpReg = V2Tmp->getOperand(0); 4206 4207 // Check that the registers and the constants have the correct values 4208 // in both conditionals 4209 if (!K1 || !K2 || *K1 == Op2 || *K2 != K2Tmp || V1Tmp != V2Tmp || 4210 V2TmpReg != V2) 4211 return false; 4212 4213 // Figure out which conditional is saturating the lower/upper bound. 4214 const SDValue *LowerCheckOp = 4215 isLowerSaturate(LHS1, RHS1, TrueVal1, FalseVal1, CC1, *K1) 4216 ? &Op 4217 : isLowerSaturate(LHS2, RHS2, TrueVal2, FalseVal2, CC2, *K2) 4218 ? &Op2 4219 : nullptr; 4220 const SDValue *UpperCheckOp = 4221 isUpperSaturate(LHS1, RHS1, TrueVal1, FalseVal1, CC1, *K1) 4222 ? &Op 4223 : isUpperSaturate(LHS2, RHS2, TrueVal2, FalseVal2, CC2, *K2) 4224 ? &Op2 4225 : nullptr; 4226 4227 if (!UpperCheckOp || !LowerCheckOp || LowerCheckOp == UpperCheckOp) 4228 return false; 4229 4230 // Check that the constant in the lower-bound check is 4231 // the opposite of the constant in the upper-bound check 4232 // in 1's complement. 4233 int64_t Val1 = cast<ConstantSDNode>(*K1)->getSExtValue(); 4234 int64_t Val2 = cast<ConstantSDNode>(*K2)->getSExtValue(); 4235 int64_t PosVal = std::max(Val1, Val2); 4236 4237 if (((Val1 > Val2 && UpperCheckOp == &Op) || 4238 (Val1 < Val2 && UpperCheckOp == &Op2)) && 4239 Val1 == ~Val2 && isPowerOf2_64(PosVal + 1)) { 4240 4241 V = V2; 4242 K = (uint64_t)PosVal; // At this point, PosVal is guaranteed to be positive 4243 return true; 4244 } 4245 4246 return false; 4247 } 4248 4249 SDValue ARMTargetLowering::LowerSELECT_CC(SDValue Op, SelectionDAG &DAG) const { 4250 EVT VT = Op.getValueType(); 4251 SDLoc dl(Op); 4252 4253 // Try to convert two saturating conditional selects into a single SSAT 4254 SDValue SatValue; 4255 uint64_t SatConstant; 4256 if (((!Subtarget->isThumb() && Subtarget->hasV6Ops()) || Subtarget->isThumb2()) && 4257 isSaturatingConditional(Op, SatValue, SatConstant)) 4258 return DAG.getNode(ARMISD::SSAT, dl, VT, SatValue, 4259 DAG.getConstant(countTrailingOnes(SatConstant), dl, VT)); 4260 4261 SDValue LHS = Op.getOperand(0); 4262 SDValue RHS = Op.getOperand(1); 4263 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(4))->get(); 4264 SDValue TrueVal = Op.getOperand(2); 4265 SDValue FalseVal = Op.getOperand(3); 4266 4267 if (Subtarget->isFPOnlySP() && LHS.getValueType() == MVT::f64) { 4268 DAG.getTargetLoweringInfo().softenSetCCOperands(DAG, MVT::f64, LHS, RHS, CC, 4269 dl); 4270 4271 // If softenSetCCOperands only returned one value, we should compare it to 4272 // zero. 4273 if (!RHS.getNode()) { 4274 RHS = DAG.getConstant(0, dl, LHS.getValueType()); 4275 CC = ISD::SETNE; 4276 } 4277 } 4278 4279 if (LHS.getValueType() == MVT::i32) { 4280 // Try to generate VSEL on ARMv8. 4281 // The VSEL instruction can't use all the usual ARM condition 4282 // codes: it only has two bits to select the condition code, so it's 4283 // constrained to use only GE, GT, VS and EQ. 4284 // 4285 // To implement all the various ISD::SETXXX opcodes, we sometimes need to 4286 // swap the operands of the previous compare instruction (effectively 4287 // inverting the compare condition, swapping 'less' and 'greater') and 4288 // sometimes need to swap the operands to the VSEL (which inverts the 4289 // condition in the sense of firing whenever the previous condition didn't) 4290 if (Subtarget->hasFPARMv8() && (TrueVal.getValueType() == MVT::f32 || 4291 TrueVal.getValueType() == MVT::f64)) { 4292 ARMCC::CondCodes CondCode = IntCCToARMCC(CC); 4293 if (CondCode == ARMCC::LT || CondCode == ARMCC::LE || 4294 CondCode == ARMCC::VC || CondCode == ARMCC::NE) { 4295 CC = ISD::getSetCCInverse(CC, true); 4296 std::swap(TrueVal, FalseVal); 4297 } 4298 } 4299 4300 SDValue ARMcc; 4301 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32); 4302 SDValue Cmp = getARMCmp(LHS, RHS, CC, ARMcc, DAG, dl); 4303 return getCMOV(dl, VT, FalseVal, TrueVal, ARMcc, CCR, Cmp, DAG); 4304 } 4305 4306 ARMCC::CondCodes CondCode, CondCode2; 4307 bool InvalidOnQNaN; 4308 FPCCToARMCC(CC, CondCode, CondCode2, InvalidOnQNaN); 4309 4310 // Try to generate VMAXNM/VMINNM on ARMv8. 4311 if (Subtarget->hasFPARMv8() && (TrueVal.getValueType() == MVT::f32 || 4312 TrueVal.getValueType() == MVT::f64)) { 4313 bool swpCmpOps = false; 4314 bool swpVselOps = false; 4315 checkVSELConstraints(CC, CondCode, swpCmpOps, swpVselOps); 4316 4317 if (CondCode == ARMCC::GT || CondCode == ARMCC::GE || 4318 CondCode == ARMCC::VS || CondCode == ARMCC::EQ) { 4319 if (swpCmpOps) 4320 std::swap(LHS, RHS); 4321 if (swpVselOps) 4322 std::swap(TrueVal, FalseVal); 4323 } 4324 } 4325 4326 SDValue ARMcc = DAG.getConstant(CondCode, dl, MVT::i32); 4327 SDValue Cmp = getVFPCmp(LHS, RHS, DAG, dl, InvalidOnQNaN); 4328 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32); 4329 SDValue Result = getCMOV(dl, VT, FalseVal, TrueVal, ARMcc, CCR, Cmp, DAG); 4330 if (CondCode2 != ARMCC::AL) { 4331 SDValue ARMcc2 = DAG.getConstant(CondCode2, dl, MVT::i32); 4332 // FIXME: Needs another CMP because flag can have but one use. 4333 SDValue Cmp2 = getVFPCmp(LHS, RHS, DAG, dl, InvalidOnQNaN); 4334 Result = getCMOV(dl, VT, Result, TrueVal, ARMcc2, CCR, Cmp2, DAG); 4335 } 4336 return Result; 4337 } 4338 4339 /// canChangeToInt - Given the fp compare operand, return true if it is suitable 4340 /// to morph to an integer compare sequence. 4341 static bool canChangeToInt(SDValue Op, bool &SeenZero, 4342 const ARMSubtarget *Subtarget) { 4343 SDNode *N = Op.getNode(); 4344 if (!N->hasOneUse()) 4345 // Otherwise it requires moving the value from fp to integer registers. 4346 return false; 4347 if (!N->getNumValues()) 4348 return false; 4349 EVT VT = Op.getValueType(); 4350 if (VT != MVT::f32 && !Subtarget->isFPBrccSlow()) 4351 // f32 case is generally profitable. f64 case only makes sense when vcmpe + 4352 // vmrs are very slow, e.g. cortex-a8. 4353 return false; 4354 4355 if (isFloatingPointZero(Op)) { 4356 SeenZero = true; 4357 return true; 4358 } 4359 return ISD::isNormalLoad(N); 4360 } 4361 4362 static SDValue bitcastf32Toi32(SDValue Op, SelectionDAG &DAG) { 4363 if (isFloatingPointZero(Op)) 4364 return DAG.getConstant(0, SDLoc(Op), MVT::i32); 4365 4366 if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Op)) 4367 return DAG.getLoad(MVT::i32, SDLoc(Op), Ld->getChain(), Ld->getBasePtr(), 4368 Ld->getPointerInfo(), Ld->getAlignment(), 4369 Ld->getMemOperand()->getFlags()); 4370 4371 llvm_unreachable("Unknown VFP cmp argument!"); 4372 } 4373 4374 static void expandf64Toi32(SDValue Op, SelectionDAG &DAG, 4375 SDValue &RetVal1, SDValue &RetVal2) { 4376 SDLoc dl(Op); 4377 4378 if (isFloatingPointZero(Op)) { 4379 RetVal1 = DAG.getConstant(0, dl, MVT::i32); 4380 RetVal2 = DAG.getConstant(0, dl, MVT::i32); 4381 return; 4382 } 4383 4384 if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Op)) { 4385 SDValue Ptr = Ld->getBasePtr(); 4386 RetVal1 = 4387 DAG.getLoad(MVT::i32, dl, Ld->getChain(), Ptr, Ld->getPointerInfo(), 4388 Ld->getAlignment(), Ld->getMemOperand()->getFlags()); 4389 4390 EVT PtrType = Ptr.getValueType(); 4391 unsigned NewAlign = MinAlign(Ld->getAlignment(), 4); 4392 SDValue NewPtr = DAG.getNode(ISD::ADD, dl, 4393 PtrType, Ptr, DAG.getConstant(4, dl, PtrType)); 4394 RetVal2 = DAG.getLoad(MVT::i32, dl, Ld->getChain(), NewPtr, 4395 Ld->getPointerInfo().getWithOffset(4), NewAlign, 4396 Ld->getMemOperand()->getFlags()); 4397 return; 4398 } 4399 4400 llvm_unreachable("Unknown VFP cmp argument!"); 4401 } 4402 4403 /// OptimizeVFPBrcond - With -enable-unsafe-fp-math, it's legal to optimize some 4404 /// f32 and even f64 comparisons to integer ones. 4405 SDValue 4406 ARMTargetLowering::OptimizeVFPBrcond(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 bool LHSSeenZero = false; 4415 bool LHSOk = canChangeToInt(LHS, LHSSeenZero, Subtarget); 4416 bool RHSSeenZero = false; 4417 bool RHSOk = canChangeToInt(RHS, RHSSeenZero, Subtarget); 4418 if (LHSOk && RHSOk && (LHSSeenZero || RHSSeenZero)) { 4419 // If unsafe fp math optimization is enabled and there are no other uses of 4420 // the CMP operands, and the condition code is EQ or NE, we can optimize it 4421 // to an integer comparison. 4422 if (CC == ISD::SETOEQ) 4423 CC = ISD::SETEQ; 4424 else if (CC == ISD::SETUNE) 4425 CC = ISD::SETNE; 4426 4427 SDValue Mask = DAG.getConstant(0x7fffffff, dl, MVT::i32); 4428 SDValue ARMcc; 4429 if (LHS.getValueType() == MVT::f32) { 4430 LHS = DAG.getNode(ISD::AND, dl, MVT::i32, 4431 bitcastf32Toi32(LHS, DAG), Mask); 4432 RHS = DAG.getNode(ISD::AND, dl, MVT::i32, 4433 bitcastf32Toi32(RHS, DAG), Mask); 4434 SDValue Cmp = getARMCmp(LHS, RHS, CC, ARMcc, DAG, dl); 4435 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32); 4436 return DAG.getNode(ARMISD::BRCOND, dl, MVT::Other, 4437 Chain, Dest, ARMcc, CCR, Cmp); 4438 } 4439 4440 SDValue LHS1, LHS2; 4441 SDValue RHS1, RHS2; 4442 expandf64Toi32(LHS, DAG, LHS1, LHS2); 4443 expandf64Toi32(RHS, DAG, RHS1, RHS2); 4444 LHS2 = DAG.getNode(ISD::AND, dl, MVT::i32, LHS2, Mask); 4445 RHS2 = DAG.getNode(ISD::AND, dl, MVT::i32, RHS2, Mask); 4446 ARMCC::CondCodes CondCode = IntCCToARMCC(CC); 4447 ARMcc = DAG.getConstant(CondCode, dl, MVT::i32); 4448 SDVTList VTList = DAG.getVTList(MVT::Other, MVT::Glue); 4449 SDValue Ops[] = { Chain, ARMcc, LHS1, LHS2, RHS1, RHS2, Dest }; 4450 return DAG.getNode(ARMISD::BCC_i64, dl, VTList, Ops); 4451 } 4452 4453 return SDValue(); 4454 } 4455 4456 SDValue ARMTargetLowering::LowerBR_CC(SDValue Op, SelectionDAG &DAG) const { 4457 SDValue Chain = Op.getOperand(0); 4458 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(1))->get(); 4459 SDValue LHS = Op.getOperand(2); 4460 SDValue RHS = Op.getOperand(3); 4461 SDValue Dest = Op.getOperand(4); 4462 SDLoc dl(Op); 4463 4464 if (Subtarget->isFPOnlySP() && LHS.getValueType() == MVT::f64) { 4465 DAG.getTargetLoweringInfo().softenSetCCOperands(DAG, MVT::f64, LHS, RHS, CC, 4466 dl); 4467 4468 // If softenSetCCOperands only returned one value, we should compare it to 4469 // zero. 4470 if (!RHS.getNode()) { 4471 RHS = DAG.getConstant(0, dl, LHS.getValueType()); 4472 CC = ISD::SETNE; 4473 } 4474 } 4475 4476 if (LHS.getValueType() == MVT::i32) { 4477 SDValue ARMcc; 4478 SDValue Cmp = getARMCmp(LHS, RHS, CC, ARMcc, DAG, dl); 4479 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32); 4480 return DAG.getNode(ARMISD::BRCOND, dl, MVT::Other, 4481 Chain, Dest, ARMcc, CCR, Cmp); 4482 } 4483 4484 assert(LHS.getValueType() == MVT::f32 || LHS.getValueType() == MVT::f64); 4485 4486 if (getTargetMachine().Options.UnsafeFPMath && 4487 (CC == ISD::SETEQ || CC == ISD::SETOEQ || 4488 CC == ISD::SETNE || CC == ISD::SETUNE)) { 4489 if (SDValue Result = OptimizeVFPBrcond(Op, DAG)) 4490 return Result; 4491 } 4492 4493 ARMCC::CondCodes CondCode, CondCode2; 4494 bool InvalidOnQNaN; 4495 FPCCToARMCC(CC, CondCode, CondCode2, InvalidOnQNaN); 4496 4497 SDValue ARMcc = DAG.getConstant(CondCode, dl, MVT::i32); 4498 SDValue Cmp = getVFPCmp(LHS, RHS, DAG, dl, InvalidOnQNaN); 4499 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32); 4500 SDVTList VTList = DAG.getVTList(MVT::Other, MVT::Glue); 4501 SDValue Ops[] = { Chain, Dest, ARMcc, CCR, Cmp }; 4502 SDValue Res = DAG.getNode(ARMISD::BRCOND, dl, VTList, Ops); 4503 if (CondCode2 != ARMCC::AL) { 4504 ARMcc = DAG.getConstant(CondCode2, dl, MVT::i32); 4505 SDValue Ops[] = { Res, Dest, ARMcc, CCR, Res.getValue(1) }; 4506 Res = DAG.getNode(ARMISD::BRCOND, dl, VTList, Ops); 4507 } 4508 return Res; 4509 } 4510 4511 SDValue ARMTargetLowering::LowerBR_JT(SDValue Op, SelectionDAG &DAG) const { 4512 SDValue Chain = Op.getOperand(0); 4513 SDValue Table = Op.getOperand(1); 4514 SDValue Index = Op.getOperand(2); 4515 SDLoc dl(Op); 4516 4517 EVT PTy = getPointerTy(DAG.getDataLayout()); 4518 JumpTableSDNode *JT = cast<JumpTableSDNode>(Table); 4519 SDValue JTI = DAG.getTargetJumpTable(JT->getIndex(), PTy); 4520 Table = DAG.getNode(ARMISD::WrapperJT, dl, MVT::i32, JTI); 4521 Index = DAG.getNode(ISD::MUL, dl, PTy, Index, DAG.getConstant(4, dl, PTy)); 4522 SDValue Addr = DAG.getNode(ISD::ADD, dl, PTy, Index, Table); 4523 if (Subtarget->isThumb2() || (Subtarget->hasV8MBaselineOps() && Subtarget->isThumb())) { 4524 // Thumb2 and ARMv8-M use a two-level jump. That is, it jumps into the jump table 4525 // which does another jump to the destination. This also makes it easier 4526 // to translate it to TBB / TBH later (Thumb2 only). 4527 // FIXME: This might not work if the function is extremely large. 4528 return DAG.getNode(ARMISD::BR2_JT, dl, MVT::Other, Chain, 4529 Addr, Op.getOperand(2), JTI); 4530 } 4531 if (isPositionIndependent() || Subtarget->isROPI()) { 4532 Addr = 4533 DAG.getLoad((EVT)MVT::i32, dl, Chain, Addr, 4534 MachinePointerInfo::getJumpTable(DAG.getMachineFunction())); 4535 Chain = Addr.getValue(1); 4536 Addr = DAG.getNode(ISD::ADD, dl, PTy, Addr, Table); 4537 return DAG.getNode(ARMISD::BR_JT, dl, MVT::Other, Chain, Addr, JTI); 4538 } else { 4539 Addr = 4540 DAG.getLoad(PTy, dl, Chain, Addr, 4541 MachinePointerInfo::getJumpTable(DAG.getMachineFunction())); 4542 Chain = Addr.getValue(1); 4543 return DAG.getNode(ARMISD::BR_JT, dl, MVT::Other, Chain, Addr, JTI); 4544 } 4545 } 4546 4547 static SDValue LowerVectorFP_TO_INT(SDValue Op, SelectionDAG &DAG) { 4548 EVT VT = Op.getValueType(); 4549 SDLoc dl(Op); 4550 4551 if (Op.getValueType().getVectorElementType() == MVT::i32) { 4552 if (Op.getOperand(0).getValueType().getVectorElementType() == MVT::f32) 4553 return Op; 4554 return DAG.UnrollVectorOp(Op.getNode()); 4555 } 4556 4557 assert(Op.getOperand(0).getValueType() == MVT::v4f32 && 4558 "Invalid type for custom lowering!"); 4559 if (VT != MVT::v4i16) 4560 return DAG.UnrollVectorOp(Op.getNode()); 4561 4562 Op = DAG.getNode(Op.getOpcode(), dl, MVT::v4i32, Op.getOperand(0)); 4563 return DAG.getNode(ISD::TRUNCATE, dl, VT, Op); 4564 } 4565 4566 SDValue ARMTargetLowering::LowerFP_TO_INT(SDValue Op, SelectionDAG &DAG) const { 4567 EVT VT = Op.getValueType(); 4568 if (VT.isVector()) 4569 return LowerVectorFP_TO_INT(Op, DAG); 4570 if (Subtarget->isFPOnlySP() && Op.getOperand(0).getValueType() == MVT::f64) { 4571 RTLIB::Libcall LC; 4572 if (Op.getOpcode() == ISD::FP_TO_SINT) 4573 LC = RTLIB::getFPTOSINT(Op.getOperand(0).getValueType(), 4574 Op.getValueType()); 4575 else 4576 LC = RTLIB::getFPTOUINT(Op.getOperand(0).getValueType(), 4577 Op.getValueType()); 4578 return makeLibCall(DAG, LC, Op.getValueType(), Op.getOperand(0), 4579 /*isSigned*/ false, SDLoc(Op)).first; 4580 } 4581 4582 return Op; 4583 } 4584 4585 static SDValue LowerVectorINT_TO_FP(SDValue Op, SelectionDAG &DAG) { 4586 EVT VT = Op.getValueType(); 4587 SDLoc dl(Op); 4588 4589 if (Op.getOperand(0).getValueType().getVectorElementType() == MVT::i32) { 4590 if (VT.getVectorElementType() == MVT::f32) 4591 return Op; 4592 return DAG.UnrollVectorOp(Op.getNode()); 4593 } 4594 4595 assert(Op.getOperand(0).getValueType() == MVT::v4i16 && 4596 "Invalid type for custom lowering!"); 4597 if (VT != MVT::v4f32) 4598 return DAG.UnrollVectorOp(Op.getNode()); 4599 4600 unsigned CastOpc; 4601 unsigned Opc; 4602 switch (Op.getOpcode()) { 4603 default: llvm_unreachable("Invalid opcode!"); 4604 case ISD::SINT_TO_FP: 4605 CastOpc = ISD::SIGN_EXTEND; 4606 Opc = ISD::SINT_TO_FP; 4607 break; 4608 case ISD::UINT_TO_FP: 4609 CastOpc = ISD::ZERO_EXTEND; 4610 Opc = ISD::UINT_TO_FP; 4611 break; 4612 } 4613 4614 Op = DAG.getNode(CastOpc, dl, MVT::v4i32, Op.getOperand(0)); 4615 return DAG.getNode(Opc, dl, VT, Op); 4616 } 4617 4618 SDValue ARMTargetLowering::LowerINT_TO_FP(SDValue Op, SelectionDAG &DAG) const { 4619 EVT VT = Op.getValueType(); 4620 if (VT.isVector()) 4621 return LowerVectorINT_TO_FP(Op, DAG); 4622 if (Subtarget->isFPOnlySP() && Op.getValueType() == MVT::f64) { 4623 RTLIB::Libcall LC; 4624 if (Op.getOpcode() == ISD::SINT_TO_FP) 4625 LC = RTLIB::getSINTTOFP(Op.getOperand(0).getValueType(), 4626 Op.getValueType()); 4627 else 4628 LC = RTLIB::getUINTTOFP(Op.getOperand(0).getValueType(), 4629 Op.getValueType()); 4630 return makeLibCall(DAG, LC, Op.getValueType(), Op.getOperand(0), 4631 /*isSigned*/ false, SDLoc(Op)).first; 4632 } 4633 4634 return Op; 4635 } 4636 4637 SDValue ARMTargetLowering::LowerFCOPYSIGN(SDValue Op, SelectionDAG &DAG) const { 4638 // Implement fcopysign with a fabs and a conditional fneg. 4639 SDValue Tmp0 = Op.getOperand(0); 4640 SDValue Tmp1 = Op.getOperand(1); 4641 SDLoc dl(Op); 4642 EVT VT = Op.getValueType(); 4643 EVT SrcVT = Tmp1.getValueType(); 4644 bool InGPR = Tmp0.getOpcode() == ISD::BITCAST || 4645 Tmp0.getOpcode() == ARMISD::VMOVDRR; 4646 bool UseNEON = !InGPR && Subtarget->hasNEON(); 4647 4648 if (UseNEON) { 4649 // Use VBSL to copy the sign bit. 4650 unsigned EncodedVal = ARM_AM::createNEONModImm(0x6, 0x80); 4651 SDValue Mask = DAG.getNode(ARMISD::VMOVIMM, dl, MVT::v2i32, 4652 DAG.getTargetConstant(EncodedVal, dl, MVT::i32)); 4653 EVT OpVT = (VT == MVT::f32) ? MVT::v2i32 : MVT::v1i64; 4654 if (VT == MVT::f64) 4655 Mask = DAG.getNode(ARMISD::VSHL, dl, OpVT, 4656 DAG.getNode(ISD::BITCAST, dl, OpVT, Mask), 4657 DAG.getConstant(32, dl, MVT::i32)); 4658 else /*if (VT == MVT::f32)*/ 4659 Tmp0 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f32, Tmp0); 4660 if (SrcVT == MVT::f32) { 4661 Tmp1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f32, Tmp1); 4662 if (VT == MVT::f64) 4663 Tmp1 = DAG.getNode(ARMISD::VSHL, dl, OpVT, 4664 DAG.getNode(ISD::BITCAST, dl, OpVT, Tmp1), 4665 DAG.getConstant(32, dl, MVT::i32)); 4666 } else if (VT == MVT::f32) 4667 Tmp1 = DAG.getNode(ARMISD::VSHRu, dl, MVT::v1i64, 4668 DAG.getNode(ISD::BITCAST, dl, MVT::v1i64, Tmp1), 4669 DAG.getConstant(32, dl, MVT::i32)); 4670 Tmp0 = DAG.getNode(ISD::BITCAST, dl, OpVT, Tmp0); 4671 Tmp1 = DAG.getNode(ISD::BITCAST, dl, OpVT, Tmp1); 4672 4673 SDValue AllOnes = DAG.getTargetConstant(ARM_AM::createNEONModImm(0xe, 0xff), 4674 dl, MVT::i32); 4675 AllOnes = DAG.getNode(ARMISD::VMOVIMM, dl, MVT::v8i8, AllOnes); 4676 SDValue MaskNot = DAG.getNode(ISD::XOR, dl, OpVT, Mask, 4677 DAG.getNode(ISD::BITCAST, dl, OpVT, AllOnes)); 4678 4679 SDValue Res = DAG.getNode(ISD::OR, dl, OpVT, 4680 DAG.getNode(ISD::AND, dl, OpVT, Tmp1, Mask), 4681 DAG.getNode(ISD::AND, dl, OpVT, Tmp0, MaskNot)); 4682 if (VT == MVT::f32) { 4683 Res = DAG.getNode(ISD::BITCAST, dl, MVT::v2f32, Res); 4684 Res = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f32, Res, 4685 DAG.getConstant(0, dl, MVT::i32)); 4686 } else { 4687 Res = DAG.getNode(ISD::BITCAST, dl, MVT::f64, Res); 4688 } 4689 4690 return Res; 4691 } 4692 4693 // Bitcast operand 1 to i32. 4694 if (SrcVT == MVT::f64) 4695 Tmp1 = DAG.getNode(ARMISD::VMOVRRD, dl, DAG.getVTList(MVT::i32, MVT::i32), 4696 Tmp1).getValue(1); 4697 Tmp1 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Tmp1); 4698 4699 // Or in the signbit with integer operations. 4700 SDValue Mask1 = DAG.getConstant(0x80000000, dl, MVT::i32); 4701 SDValue Mask2 = DAG.getConstant(0x7fffffff, dl, MVT::i32); 4702 Tmp1 = DAG.getNode(ISD::AND, dl, MVT::i32, Tmp1, Mask1); 4703 if (VT == MVT::f32) { 4704 Tmp0 = DAG.getNode(ISD::AND, dl, MVT::i32, 4705 DAG.getNode(ISD::BITCAST, dl, MVT::i32, Tmp0), Mask2); 4706 return DAG.getNode(ISD::BITCAST, dl, MVT::f32, 4707 DAG.getNode(ISD::OR, dl, MVT::i32, Tmp0, Tmp1)); 4708 } 4709 4710 // f64: Or the high part with signbit and then combine two parts. 4711 Tmp0 = DAG.getNode(ARMISD::VMOVRRD, dl, DAG.getVTList(MVT::i32, MVT::i32), 4712 Tmp0); 4713 SDValue Lo = Tmp0.getValue(0); 4714 SDValue Hi = DAG.getNode(ISD::AND, dl, MVT::i32, Tmp0.getValue(1), Mask2); 4715 Hi = DAG.getNode(ISD::OR, dl, MVT::i32, Hi, Tmp1); 4716 return DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi); 4717 } 4718 4719 SDValue ARMTargetLowering::LowerRETURNADDR(SDValue Op, SelectionDAG &DAG) const{ 4720 MachineFunction &MF = DAG.getMachineFunction(); 4721 MachineFrameInfo &MFI = MF.getFrameInfo(); 4722 MFI.setReturnAddressIsTaken(true); 4723 4724 if (verifyReturnAddressArgumentIsConstant(Op, DAG)) 4725 return SDValue(); 4726 4727 EVT VT = Op.getValueType(); 4728 SDLoc dl(Op); 4729 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue(); 4730 if (Depth) { 4731 SDValue FrameAddr = LowerFRAMEADDR(Op, DAG); 4732 SDValue Offset = DAG.getConstant(4, dl, MVT::i32); 4733 return DAG.getLoad(VT, dl, DAG.getEntryNode(), 4734 DAG.getNode(ISD::ADD, dl, VT, FrameAddr, Offset), 4735 MachinePointerInfo()); 4736 } 4737 4738 // Return LR, which contains the return address. Mark it an implicit live-in. 4739 unsigned Reg = MF.addLiveIn(ARM::LR, getRegClassFor(MVT::i32)); 4740 return DAG.getCopyFromReg(DAG.getEntryNode(), dl, Reg, VT); 4741 } 4742 4743 SDValue ARMTargetLowering::LowerFRAMEADDR(SDValue Op, SelectionDAG &DAG) const { 4744 const ARMBaseRegisterInfo &ARI = 4745 *static_cast<const ARMBaseRegisterInfo*>(RegInfo); 4746 MachineFunction &MF = DAG.getMachineFunction(); 4747 MachineFrameInfo &MFI = MF.getFrameInfo(); 4748 MFI.setFrameAddressIsTaken(true); 4749 4750 EVT VT = Op.getValueType(); 4751 SDLoc dl(Op); // FIXME probably not meaningful 4752 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue(); 4753 unsigned FrameReg = ARI.getFrameRegister(MF); 4754 SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, VT); 4755 while (Depth--) 4756 FrameAddr = DAG.getLoad(VT, dl, DAG.getEntryNode(), FrameAddr, 4757 MachinePointerInfo()); 4758 return FrameAddr; 4759 } 4760 4761 // FIXME? Maybe this could be a TableGen attribute on some registers and 4762 // this table could be generated automatically from RegInfo. 4763 unsigned ARMTargetLowering::getRegisterByName(const char* RegName, EVT VT, 4764 SelectionDAG &DAG) const { 4765 unsigned Reg = StringSwitch<unsigned>(RegName) 4766 .Case("sp", ARM::SP) 4767 .Default(0); 4768 if (Reg) 4769 return Reg; 4770 report_fatal_error(Twine("Invalid register name \"" 4771 + StringRef(RegName) + "\".")); 4772 } 4773 4774 // Result is 64 bit value so split into two 32 bit values and return as a 4775 // pair of values. 4776 static void ExpandREAD_REGISTER(SDNode *N, SmallVectorImpl<SDValue> &Results, 4777 SelectionDAG &DAG) { 4778 SDLoc DL(N); 4779 4780 // This function is only supposed to be called for i64 type destination. 4781 assert(N->getValueType(0) == MVT::i64 4782 && "ExpandREAD_REGISTER called for non-i64 type result."); 4783 4784 SDValue Read = DAG.getNode(ISD::READ_REGISTER, DL, 4785 DAG.getVTList(MVT::i32, MVT::i32, MVT::Other), 4786 N->getOperand(0), 4787 N->getOperand(1)); 4788 4789 Results.push_back(DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, Read.getValue(0), 4790 Read.getValue(1))); 4791 Results.push_back(Read.getOperand(0)); 4792 } 4793 4794 /// \p BC is a bitcast that is about to be turned into a VMOVDRR. 4795 /// When \p DstVT, the destination type of \p BC, is on the vector 4796 /// register bank and the source of bitcast, \p Op, operates on the same bank, 4797 /// it might be possible to combine them, such that everything stays on the 4798 /// vector register bank. 4799 /// \p return The node that would replace \p BT, if the combine 4800 /// is possible. 4801 static SDValue CombineVMOVDRRCandidateWithVecOp(const SDNode *BC, 4802 SelectionDAG &DAG) { 4803 SDValue Op = BC->getOperand(0); 4804 EVT DstVT = BC->getValueType(0); 4805 4806 // The only vector instruction that can produce a scalar (remember, 4807 // since the bitcast was about to be turned into VMOVDRR, the source 4808 // type is i64) from a vector is EXTRACT_VECTOR_ELT. 4809 // Moreover, we can do this combine only if there is one use. 4810 // Finally, if the destination type is not a vector, there is not 4811 // much point on forcing everything on the vector bank. 4812 if (!DstVT.isVector() || Op.getOpcode() != ISD::EXTRACT_VECTOR_ELT || 4813 !Op.hasOneUse()) 4814 return SDValue(); 4815 4816 // If the index is not constant, we will introduce an additional 4817 // multiply that will stick. 4818 // Give up in that case. 4819 ConstantSDNode *Index = dyn_cast<ConstantSDNode>(Op.getOperand(1)); 4820 if (!Index) 4821 return SDValue(); 4822 unsigned DstNumElt = DstVT.getVectorNumElements(); 4823 4824 // Compute the new index. 4825 const APInt &APIntIndex = Index->getAPIntValue(); 4826 APInt NewIndex(APIntIndex.getBitWidth(), DstNumElt); 4827 NewIndex *= APIntIndex; 4828 // Check if the new constant index fits into i32. 4829 if (NewIndex.getBitWidth() > 32) 4830 return SDValue(); 4831 4832 // vMTy bitcast(i64 extractelt vNi64 src, i32 index) -> 4833 // vMTy extractsubvector vNxMTy (bitcast vNi64 src), i32 index*M) 4834 SDLoc dl(Op); 4835 SDValue ExtractSrc = Op.getOperand(0); 4836 EVT VecVT = EVT::getVectorVT( 4837 *DAG.getContext(), DstVT.getScalarType(), 4838 ExtractSrc.getValueType().getVectorNumElements() * DstNumElt); 4839 SDValue BitCast = DAG.getNode(ISD::BITCAST, dl, VecVT, ExtractSrc); 4840 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DstVT, BitCast, 4841 DAG.getConstant(NewIndex.getZExtValue(), dl, MVT::i32)); 4842 } 4843 4844 /// ExpandBITCAST - If the target supports VFP, this function is called to 4845 /// expand a bit convert where either the source or destination type is i64 to 4846 /// use a VMOVDRR or VMOVRRD node. This should not be done when the non-i64 4847 /// operand type is illegal (e.g., v2f32 for a target that doesn't support 4848 /// vectors), since the legalizer won't know what to do with that. 4849 static SDValue ExpandBITCAST(SDNode *N, SelectionDAG &DAG) { 4850 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 4851 SDLoc dl(N); 4852 SDValue Op = N->getOperand(0); 4853 4854 // This function is only supposed to be called for i64 types, either as the 4855 // source or destination of the bit convert. 4856 EVT SrcVT = Op.getValueType(); 4857 EVT DstVT = N->getValueType(0); 4858 assert((SrcVT == MVT::i64 || DstVT == MVT::i64) && 4859 "ExpandBITCAST called for non-i64 type"); 4860 4861 // Turn i64->f64 into VMOVDRR. 4862 if (SrcVT == MVT::i64 && TLI.isTypeLegal(DstVT)) { 4863 // Do not force values to GPRs (this is what VMOVDRR does for the inputs) 4864 // if we can combine the bitcast with its source. 4865 if (SDValue Val = CombineVMOVDRRCandidateWithVecOp(N, DAG)) 4866 return Val; 4867 4868 SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, Op, 4869 DAG.getConstant(0, dl, MVT::i32)); 4870 SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, Op, 4871 DAG.getConstant(1, dl, MVT::i32)); 4872 return DAG.getNode(ISD::BITCAST, dl, DstVT, 4873 DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi)); 4874 } 4875 4876 // Turn f64->i64 into VMOVRRD. 4877 if (DstVT == MVT::i64 && TLI.isTypeLegal(SrcVT)) { 4878 SDValue Cvt; 4879 if (DAG.getDataLayout().isBigEndian() && SrcVT.isVector() && 4880 SrcVT.getVectorNumElements() > 1) 4881 Cvt = DAG.getNode(ARMISD::VMOVRRD, dl, 4882 DAG.getVTList(MVT::i32, MVT::i32), 4883 DAG.getNode(ARMISD::VREV64, dl, SrcVT, Op)); 4884 else 4885 Cvt = DAG.getNode(ARMISD::VMOVRRD, dl, 4886 DAG.getVTList(MVT::i32, MVT::i32), Op); 4887 // Merge the pieces into a single i64 value. 4888 return DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Cvt, Cvt.getValue(1)); 4889 } 4890 4891 return SDValue(); 4892 } 4893 4894 /// getZeroVector - Returns a vector of specified type with all zero elements. 4895 /// Zero vectors are used to represent vector negation and in those cases 4896 /// will be implemented with the NEON VNEG instruction. However, VNEG does 4897 /// not support i64 elements, so sometimes the zero vectors will need to be 4898 /// explicitly constructed. Regardless, use a canonical VMOV to create the 4899 /// zero vector. 4900 static SDValue getZeroVector(EVT VT, SelectionDAG &DAG, const SDLoc &dl) { 4901 assert(VT.isVector() && "Expected a vector type"); 4902 // The canonical modified immediate encoding of a zero vector is....0! 4903 SDValue EncodedVal = DAG.getTargetConstant(0, dl, MVT::i32); 4904 EVT VmovVT = VT.is128BitVector() ? MVT::v4i32 : MVT::v2i32; 4905 SDValue Vmov = DAG.getNode(ARMISD::VMOVIMM, dl, VmovVT, EncodedVal); 4906 return DAG.getNode(ISD::BITCAST, dl, VT, Vmov); 4907 } 4908 4909 /// LowerShiftRightParts - Lower SRA_PARTS, which returns two 4910 /// i32 values and take a 2 x i32 value to shift plus a shift amount. 4911 SDValue ARMTargetLowering::LowerShiftRightParts(SDValue Op, 4912 SelectionDAG &DAG) const { 4913 assert(Op.getNumOperands() == 3 && "Not a double-shift!"); 4914 EVT VT = Op.getValueType(); 4915 unsigned VTBits = VT.getSizeInBits(); 4916 SDLoc dl(Op); 4917 SDValue ShOpLo = Op.getOperand(0); 4918 SDValue ShOpHi = Op.getOperand(1); 4919 SDValue ShAmt = Op.getOperand(2); 4920 SDValue ARMcc; 4921 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32); 4922 unsigned Opc = (Op.getOpcode() == ISD::SRA_PARTS) ? ISD::SRA : ISD::SRL; 4923 4924 assert(Op.getOpcode() == ISD::SRA_PARTS || Op.getOpcode() == ISD::SRL_PARTS); 4925 4926 SDValue RevShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32, 4927 DAG.getConstant(VTBits, dl, MVT::i32), ShAmt); 4928 SDValue Tmp1 = DAG.getNode(ISD::SRL, dl, VT, ShOpLo, ShAmt); 4929 SDValue ExtraShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32, ShAmt, 4930 DAG.getConstant(VTBits, dl, MVT::i32)); 4931 SDValue Tmp2 = DAG.getNode(ISD::SHL, dl, VT, ShOpHi, RevShAmt); 4932 SDValue LoSmallShift = DAG.getNode(ISD::OR, dl, VT, Tmp1, Tmp2); 4933 SDValue LoBigShift = DAG.getNode(Opc, dl, VT, ShOpHi, ExtraShAmt); 4934 SDValue CmpLo = getARMCmp(ExtraShAmt, DAG.getConstant(0, dl, MVT::i32), 4935 ISD::SETGE, ARMcc, DAG, dl); 4936 SDValue Lo = DAG.getNode(ARMISD::CMOV, dl, VT, LoSmallShift, LoBigShift, 4937 ARMcc, CCR, CmpLo); 4938 4939 4940 SDValue HiSmallShift = DAG.getNode(Opc, dl, VT, ShOpHi, ShAmt); 4941 SDValue HiBigShift = Opc == ISD::SRA 4942 ? DAG.getNode(Opc, dl, VT, ShOpHi, 4943 DAG.getConstant(VTBits - 1, dl, VT)) 4944 : DAG.getConstant(0, dl, VT); 4945 SDValue CmpHi = getARMCmp(ExtraShAmt, DAG.getConstant(0, dl, MVT::i32), 4946 ISD::SETGE, ARMcc, DAG, dl); 4947 SDValue Hi = DAG.getNode(ARMISD::CMOV, dl, VT, HiSmallShift, HiBigShift, 4948 ARMcc, CCR, CmpHi); 4949 4950 SDValue Ops[2] = { Lo, Hi }; 4951 return DAG.getMergeValues(Ops, dl); 4952 } 4953 4954 /// LowerShiftLeftParts - Lower SHL_PARTS, which returns two 4955 /// i32 values and take a 2 x i32 value to shift plus a shift amount. 4956 SDValue ARMTargetLowering::LowerShiftLeftParts(SDValue Op, 4957 SelectionDAG &DAG) const { 4958 assert(Op.getNumOperands() == 3 && "Not a double-shift!"); 4959 EVT VT = Op.getValueType(); 4960 unsigned VTBits = VT.getSizeInBits(); 4961 SDLoc dl(Op); 4962 SDValue ShOpLo = Op.getOperand(0); 4963 SDValue ShOpHi = Op.getOperand(1); 4964 SDValue ShAmt = Op.getOperand(2); 4965 SDValue ARMcc; 4966 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32); 4967 4968 assert(Op.getOpcode() == ISD::SHL_PARTS); 4969 SDValue RevShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32, 4970 DAG.getConstant(VTBits, dl, MVT::i32), ShAmt); 4971 SDValue Tmp1 = DAG.getNode(ISD::SRL, dl, VT, ShOpLo, RevShAmt); 4972 SDValue Tmp2 = DAG.getNode(ISD::SHL, dl, VT, ShOpHi, ShAmt); 4973 SDValue HiSmallShift = DAG.getNode(ISD::OR, dl, VT, Tmp1, Tmp2); 4974 4975 SDValue ExtraShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32, ShAmt, 4976 DAG.getConstant(VTBits, dl, MVT::i32)); 4977 SDValue HiBigShift = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ExtraShAmt); 4978 SDValue CmpHi = getARMCmp(ExtraShAmt, DAG.getConstant(0, dl, MVT::i32), 4979 ISD::SETGE, ARMcc, DAG, dl); 4980 SDValue Hi = DAG.getNode(ARMISD::CMOV, dl, VT, HiSmallShift, HiBigShift, 4981 ARMcc, CCR, CmpHi); 4982 4983 SDValue CmpLo = getARMCmp(ExtraShAmt, DAG.getConstant(0, dl, MVT::i32), 4984 ISD::SETGE, ARMcc, DAG, dl); 4985 SDValue LoSmallShift = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ShAmt); 4986 SDValue Lo = DAG.getNode(ARMISD::CMOV, dl, VT, LoSmallShift, 4987 DAG.getConstant(0, dl, VT), ARMcc, CCR, CmpLo); 4988 4989 SDValue Ops[2] = { Lo, Hi }; 4990 return DAG.getMergeValues(Ops, dl); 4991 } 4992 4993 SDValue ARMTargetLowering::LowerFLT_ROUNDS_(SDValue Op, 4994 SelectionDAG &DAG) const { 4995 // The rounding mode is in bits 23:22 of the FPSCR. 4996 // The ARM rounding mode value to FLT_ROUNDS mapping is 0->1, 1->2, 2->3, 3->0 4997 // The formula we use to implement this is (((FPSCR + 1 << 22) >> 22) & 3) 4998 // so that the shift + and get folded into a bitfield extract. 4999 SDLoc dl(Op); 5000 SDValue Ops[] = { DAG.getEntryNode(), 5001 DAG.getConstant(Intrinsic::arm_get_fpscr, dl, MVT::i32) }; 5002 5003 SDValue FPSCR = DAG.getNode(ISD::INTRINSIC_W_CHAIN, dl, MVT::i32, Ops); 5004 SDValue FltRounds = DAG.getNode(ISD::ADD, dl, MVT::i32, FPSCR, 5005 DAG.getConstant(1U << 22, dl, MVT::i32)); 5006 SDValue RMODE = DAG.getNode(ISD::SRL, dl, MVT::i32, FltRounds, 5007 DAG.getConstant(22, dl, MVT::i32)); 5008 return DAG.getNode(ISD::AND, dl, MVT::i32, RMODE, 5009 DAG.getConstant(3, dl, MVT::i32)); 5010 } 5011 5012 static SDValue LowerCTTZ(SDNode *N, SelectionDAG &DAG, 5013 const ARMSubtarget *ST) { 5014 SDLoc dl(N); 5015 EVT VT = N->getValueType(0); 5016 if (VT.isVector()) { 5017 assert(ST->hasNEON()); 5018 5019 // Compute the least significant set bit: LSB = X & -X 5020 SDValue X = N->getOperand(0); 5021 SDValue NX = DAG.getNode(ISD::SUB, dl, VT, getZeroVector(VT, DAG, dl), X); 5022 SDValue LSB = DAG.getNode(ISD::AND, dl, VT, X, NX); 5023 5024 EVT ElemTy = VT.getVectorElementType(); 5025 5026 if (ElemTy == MVT::i8) { 5027 // Compute with: cttz(x) = ctpop(lsb - 1) 5028 SDValue One = DAG.getNode(ARMISD::VMOVIMM, dl, VT, 5029 DAG.getTargetConstant(1, dl, ElemTy)); 5030 SDValue Bits = DAG.getNode(ISD::SUB, dl, VT, LSB, One); 5031 return DAG.getNode(ISD::CTPOP, dl, VT, Bits); 5032 } 5033 5034 if ((ElemTy == MVT::i16 || ElemTy == MVT::i32) && 5035 (N->getOpcode() == ISD::CTTZ_ZERO_UNDEF)) { 5036 // Compute with: cttz(x) = (width - 1) - ctlz(lsb), if x != 0 5037 unsigned NumBits = ElemTy.getSizeInBits(); 5038 SDValue WidthMinus1 = 5039 DAG.getNode(ARMISD::VMOVIMM, dl, VT, 5040 DAG.getTargetConstant(NumBits - 1, dl, ElemTy)); 5041 SDValue CTLZ = DAG.getNode(ISD::CTLZ, dl, VT, LSB); 5042 return DAG.getNode(ISD::SUB, dl, VT, WidthMinus1, CTLZ); 5043 } 5044 5045 // Compute with: cttz(x) = ctpop(lsb - 1) 5046 5047 // Since we can only compute the number of bits in a byte with vcnt.8, we 5048 // have to gather the result with pairwise addition (vpaddl) for i16, i32, 5049 // and i64. 5050 5051 // Compute LSB - 1. 5052 SDValue Bits; 5053 if (ElemTy == MVT::i64) { 5054 // Load constant 0xffff'ffff'ffff'ffff to register. 5055 SDValue FF = DAG.getNode(ARMISD::VMOVIMM, dl, VT, 5056 DAG.getTargetConstant(0x1eff, dl, MVT::i32)); 5057 Bits = DAG.getNode(ISD::ADD, dl, VT, LSB, FF); 5058 } else { 5059 SDValue One = DAG.getNode(ARMISD::VMOVIMM, dl, VT, 5060 DAG.getTargetConstant(1, dl, ElemTy)); 5061 Bits = DAG.getNode(ISD::SUB, dl, VT, LSB, One); 5062 } 5063 5064 // Count #bits with vcnt.8. 5065 EVT VT8Bit = VT.is64BitVector() ? MVT::v8i8 : MVT::v16i8; 5066 SDValue BitsVT8 = DAG.getNode(ISD::BITCAST, dl, VT8Bit, Bits); 5067 SDValue Cnt8 = DAG.getNode(ISD::CTPOP, dl, VT8Bit, BitsVT8); 5068 5069 // Gather the #bits with vpaddl (pairwise add.) 5070 EVT VT16Bit = VT.is64BitVector() ? MVT::v4i16 : MVT::v8i16; 5071 SDValue Cnt16 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT16Bit, 5072 DAG.getTargetConstant(Intrinsic::arm_neon_vpaddlu, dl, MVT::i32), 5073 Cnt8); 5074 if (ElemTy == MVT::i16) 5075 return Cnt16; 5076 5077 EVT VT32Bit = VT.is64BitVector() ? MVT::v2i32 : MVT::v4i32; 5078 SDValue Cnt32 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT32Bit, 5079 DAG.getTargetConstant(Intrinsic::arm_neon_vpaddlu, dl, MVT::i32), 5080 Cnt16); 5081 if (ElemTy == MVT::i32) 5082 return Cnt32; 5083 5084 assert(ElemTy == MVT::i64); 5085 SDValue Cnt64 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT, 5086 DAG.getTargetConstant(Intrinsic::arm_neon_vpaddlu, dl, MVT::i32), 5087 Cnt32); 5088 return Cnt64; 5089 } 5090 5091 if (!ST->hasV6T2Ops()) 5092 return SDValue(); 5093 5094 SDValue rbit = DAG.getNode(ISD::BITREVERSE, dl, VT, N->getOperand(0)); 5095 return DAG.getNode(ISD::CTLZ, dl, VT, rbit); 5096 } 5097 5098 /// getCTPOP16BitCounts - Returns a v8i8/v16i8 vector containing the bit-count 5099 /// for each 16-bit element from operand, repeated. The basic idea is to 5100 /// leverage vcnt to get the 8-bit counts, gather and add the results. 5101 /// 5102 /// Trace for v4i16: 5103 /// input = [v0 v1 v2 v3 ] (vi 16-bit element) 5104 /// cast: N0 = [w0 w1 w2 w3 w4 w5 w6 w7] (v0 = [w0 w1], wi 8-bit element) 5105 /// vcnt: N1 = [b0 b1 b2 b3 b4 b5 b6 b7] (bi = bit-count of 8-bit element wi) 5106 /// vrev: N2 = [b1 b0 b3 b2 b5 b4 b7 b6] 5107 /// [b0 b1 b2 b3 b4 b5 b6 b7] 5108 /// +[b1 b0 b3 b2 b5 b4 b7 b6] 5109 /// N3=N1+N2 = [k0 k0 k1 k1 k2 k2 k3 k3] (k0 = b0+b1 = bit-count of 16-bit v0, 5110 /// vuzp: = [k0 k1 k2 k3 k0 k1 k2 k3] each ki is 8-bits) 5111 static SDValue getCTPOP16BitCounts(SDNode *N, SelectionDAG &DAG) { 5112 EVT VT = N->getValueType(0); 5113 SDLoc DL(N); 5114 5115 EVT VT8Bit = VT.is64BitVector() ? MVT::v8i8 : MVT::v16i8; 5116 SDValue N0 = DAG.getNode(ISD::BITCAST, DL, VT8Bit, N->getOperand(0)); 5117 SDValue N1 = DAG.getNode(ISD::CTPOP, DL, VT8Bit, N0); 5118 SDValue N2 = DAG.getNode(ARMISD::VREV16, DL, VT8Bit, N1); 5119 SDValue N3 = DAG.getNode(ISD::ADD, DL, VT8Bit, N1, N2); 5120 return DAG.getNode(ARMISD::VUZP, DL, VT8Bit, N3, N3); 5121 } 5122 5123 /// lowerCTPOP16BitElements - Returns a v4i16/v8i16 vector containing the 5124 /// bit-count for each 16-bit element from the operand. We need slightly 5125 /// different sequencing for v4i16 and v8i16 to stay within NEON's available 5126 /// 64/128-bit registers. 5127 /// 5128 /// Trace for v4i16: 5129 /// input = [v0 v1 v2 v3 ] (vi 16-bit element) 5130 /// v8i8: BitCounts = [k0 k1 k2 k3 k0 k1 k2 k3 ] (ki is the bit-count of vi) 5131 /// v8i16:Extended = [k0 k1 k2 k3 k0 k1 k2 k3 ] 5132 /// v4i16:Extracted = [k0 k1 k2 k3 ] 5133 static SDValue lowerCTPOP16BitElements(SDNode *N, SelectionDAG &DAG) { 5134 EVT VT = N->getValueType(0); 5135 SDLoc DL(N); 5136 5137 SDValue BitCounts = getCTPOP16BitCounts(N, DAG); 5138 if (VT.is64BitVector()) { 5139 SDValue Extended = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::v8i16, BitCounts); 5140 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v4i16, Extended, 5141 DAG.getIntPtrConstant(0, DL)); 5142 } else { 5143 SDValue Extracted = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v8i8, 5144 BitCounts, DAG.getIntPtrConstant(0, DL)); 5145 return DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::v8i16, Extracted); 5146 } 5147 } 5148 5149 /// lowerCTPOP32BitElements - Returns a v2i32/v4i32 vector containing the 5150 /// bit-count for each 32-bit element from the operand. The idea here is 5151 /// to split the vector into 16-bit elements, leverage the 16-bit count 5152 /// routine, and then combine the results. 5153 /// 5154 /// Trace for v2i32 (v4i32 similar with Extracted/Extended exchanged): 5155 /// input = [v0 v1 ] (vi: 32-bit elements) 5156 /// Bitcast = [w0 w1 w2 w3 ] (wi: 16-bit elements, v0 = [w0 w1]) 5157 /// Counts16 = [k0 k1 k2 k3 ] (ki: 16-bit elements, bit-count of wi) 5158 /// vrev: N0 = [k1 k0 k3 k2 ] 5159 /// [k0 k1 k2 k3 ] 5160 /// N1 =+[k1 k0 k3 k2 ] 5161 /// [k0 k2 k1 k3 ] 5162 /// N2 =+[k1 k3 k0 k2 ] 5163 /// [k0 k2 k1 k3 ] 5164 /// Extended =+[k1 k3 k0 k2 ] 5165 /// [k0 k2 ] 5166 /// Extracted=+[k1 k3 ] 5167 /// 5168 static SDValue lowerCTPOP32BitElements(SDNode *N, SelectionDAG &DAG) { 5169 EVT VT = N->getValueType(0); 5170 SDLoc DL(N); 5171 5172 EVT VT16Bit = VT.is64BitVector() ? MVT::v4i16 : MVT::v8i16; 5173 5174 SDValue Bitcast = DAG.getNode(ISD::BITCAST, DL, VT16Bit, N->getOperand(0)); 5175 SDValue Counts16 = lowerCTPOP16BitElements(Bitcast.getNode(), DAG); 5176 SDValue N0 = DAG.getNode(ARMISD::VREV32, DL, VT16Bit, Counts16); 5177 SDValue N1 = DAG.getNode(ISD::ADD, DL, VT16Bit, Counts16, N0); 5178 SDValue N2 = DAG.getNode(ARMISD::VUZP, DL, VT16Bit, N1, N1); 5179 5180 if (VT.is64BitVector()) { 5181 SDValue Extended = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::v4i32, N2); 5182 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2i32, Extended, 5183 DAG.getIntPtrConstant(0, DL)); 5184 } else { 5185 SDValue Extracted = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v4i16, N2, 5186 DAG.getIntPtrConstant(0, DL)); 5187 return DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::v4i32, Extracted); 5188 } 5189 } 5190 5191 static SDValue LowerCTPOP(SDNode *N, SelectionDAG &DAG, 5192 const ARMSubtarget *ST) { 5193 EVT VT = N->getValueType(0); 5194 5195 assert(ST->hasNEON() && "Custom ctpop lowering requires NEON."); 5196 assert((VT == MVT::v2i32 || VT == MVT::v4i32 || 5197 VT == MVT::v4i16 || VT == MVT::v8i16) && 5198 "Unexpected type for custom ctpop lowering"); 5199 5200 if (VT.getVectorElementType() == MVT::i32) 5201 return lowerCTPOP32BitElements(N, DAG); 5202 else 5203 return lowerCTPOP16BitElements(N, DAG); 5204 } 5205 5206 static SDValue LowerShift(SDNode *N, SelectionDAG &DAG, 5207 const ARMSubtarget *ST) { 5208 EVT VT = N->getValueType(0); 5209 SDLoc dl(N); 5210 5211 if (!VT.isVector()) 5212 return SDValue(); 5213 5214 // Lower vector shifts on NEON to use VSHL. 5215 assert(ST->hasNEON() && "unexpected vector shift"); 5216 5217 // Left shifts translate directly to the vshiftu intrinsic. 5218 if (N->getOpcode() == ISD::SHL) 5219 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT, 5220 DAG.getConstant(Intrinsic::arm_neon_vshiftu, dl, 5221 MVT::i32), 5222 N->getOperand(0), N->getOperand(1)); 5223 5224 assert((N->getOpcode() == ISD::SRA || 5225 N->getOpcode() == ISD::SRL) && "unexpected vector shift opcode"); 5226 5227 // NEON uses the same intrinsics for both left and right shifts. For 5228 // right shifts, the shift amounts are negative, so negate the vector of 5229 // shift amounts. 5230 EVT ShiftVT = N->getOperand(1).getValueType(); 5231 SDValue NegatedCount = DAG.getNode(ISD::SUB, dl, ShiftVT, 5232 getZeroVector(ShiftVT, DAG, dl), 5233 N->getOperand(1)); 5234 Intrinsic::ID vshiftInt = (N->getOpcode() == ISD::SRA ? 5235 Intrinsic::arm_neon_vshifts : 5236 Intrinsic::arm_neon_vshiftu); 5237 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT, 5238 DAG.getConstant(vshiftInt, dl, MVT::i32), 5239 N->getOperand(0), NegatedCount); 5240 } 5241 5242 static SDValue Expand64BitShift(SDNode *N, SelectionDAG &DAG, 5243 const ARMSubtarget *ST) { 5244 EVT VT = N->getValueType(0); 5245 SDLoc dl(N); 5246 5247 // We can get here for a node like i32 = ISD::SHL i32, i64 5248 if (VT != MVT::i64) 5249 return SDValue(); 5250 5251 assert((N->getOpcode() == ISD::SRL || N->getOpcode() == ISD::SRA) && 5252 "Unknown shift to lower!"); 5253 5254 // We only lower SRA, SRL of 1 here, all others use generic lowering. 5255 if (!isOneConstant(N->getOperand(1))) 5256 return SDValue(); 5257 5258 // If we are in thumb mode, we don't have RRX. 5259 if (ST->isThumb1Only()) return SDValue(); 5260 5261 // Okay, we have a 64-bit SRA or SRL of 1. Lower this to an RRX expr. 5262 SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(0), 5263 DAG.getConstant(0, dl, MVT::i32)); 5264 SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(0), 5265 DAG.getConstant(1, dl, MVT::i32)); 5266 5267 // First, build a SRA_FLAG/SRL_FLAG op, which shifts the top part by one and 5268 // captures the result into a carry flag. 5269 unsigned Opc = N->getOpcode() == ISD::SRL ? ARMISD::SRL_FLAG:ARMISD::SRA_FLAG; 5270 Hi = DAG.getNode(Opc, dl, DAG.getVTList(MVT::i32, MVT::Glue), Hi); 5271 5272 // The low part is an ARMISD::RRX operand, which shifts the carry in. 5273 Lo = DAG.getNode(ARMISD::RRX, dl, MVT::i32, Lo, Hi.getValue(1)); 5274 5275 // Merge the pieces into a single i64 value. 5276 return DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Lo, Hi); 5277 } 5278 5279 static SDValue LowerVSETCC(SDValue Op, SelectionDAG &DAG) { 5280 SDValue TmpOp0, TmpOp1; 5281 bool Invert = false; 5282 bool Swap = false; 5283 unsigned Opc = 0; 5284 5285 SDValue Op0 = Op.getOperand(0); 5286 SDValue Op1 = Op.getOperand(1); 5287 SDValue CC = Op.getOperand(2); 5288 EVT CmpVT = Op0.getValueType().changeVectorElementTypeToInteger(); 5289 EVT VT = Op.getValueType(); 5290 ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get(); 5291 SDLoc dl(Op); 5292 5293 if (Op0.getValueType().getVectorElementType() == MVT::i64 && 5294 (SetCCOpcode == ISD::SETEQ || SetCCOpcode == ISD::SETNE)) { 5295 // Special-case integer 64-bit equality comparisons. They aren't legal, 5296 // but they can be lowered with a few vector instructions. 5297 unsigned CmpElements = CmpVT.getVectorNumElements() * 2; 5298 EVT SplitVT = EVT::getVectorVT(*DAG.getContext(), MVT::i32, CmpElements); 5299 SDValue CastOp0 = DAG.getNode(ISD::BITCAST, dl, SplitVT, Op0); 5300 SDValue CastOp1 = DAG.getNode(ISD::BITCAST, dl, SplitVT, Op1); 5301 SDValue Cmp = DAG.getNode(ISD::SETCC, dl, SplitVT, CastOp0, CastOp1, 5302 DAG.getCondCode(ISD::SETEQ)); 5303 SDValue Reversed = DAG.getNode(ARMISD::VREV64, dl, SplitVT, Cmp); 5304 SDValue Merged = DAG.getNode(ISD::AND, dl, SplitVT, Cmp, Reversed); 5305 Merged = DAG.getNode(ISD::BITCAST, dl, CmpVT, Merged); 5306 if (SetCCOpcode == ISD::SETNE) 5307 Merged = DAG.getNOT(dl, Merged, CmpVT); 5308 Merged = DAG.getSExtOrTrunc(Merged, dl, VT); 5309 return Merged; 5310 } 5311 5312 if (CmpVT.getVectorElementType() == MVT::i64) 5313 // 64-bit comparisons are not legal in general. 5314 return SDValue(); 5315 5316 if (Op1.getValueType().isFloatingPoint()) { 5317 switch (SetCCOpcode) { 5318 default: llvm_unreachable("Illegal FP comparison"); 5319 case ISD::SETUNE: 5320 case ISD::SETNE: Invert = true; LLVM_FALLTHROUGH; 5321 case ISD::SETOEQ: 5322 case ISD::SETEQ: Opc = ARMISD::VCEQ; break; 5323 case ISD::SETOLT: 5324 case ISD::SETLT: Swap = true; LLVM_FALLTHROUGH; 5325 case ISD::SETOGT: 5326 case ISD::SETGT: Opc = ARMISD::VCGT; break; 5327 case ISD::SETOLE: 5328 case ISD::SETLE: Swap = true; LLVM_FALLTHROUGH; 5329 case ISD::SETOGE: 5330 case ISD::SETGE: Opc = ARMISD::VCGE; break; 5331 case ISD::SETUGE: Swap = true; LLVM_FALLTHROUGH; 5332 case ISD::SETULE: Invert = true; Opc = ARMISD::VCGT; break; 5333 case ISD::SETUGT: Swap = true; LLVM_FALLTHROUGH; 5334 case ISD::SETULT: Invert = true; Opc = ARMISD::VCGE; break; 5335 case ISD::SETUEQ: Invert = true; LLVM_FALLTHROUGH; 5336 case ISD::SETONE: 5337 // Expand this to (OLT | OGT). 5338 TmpOp0 = Op0; 5339 TmpOp1 = Op1; 5340 Opc = ISD::OR; 5341 Op0 = DAG.getNode(ARMISD::VCGT, dl, CmpVT, TmpOp1, TmpOp0); 5342 Op1 = DAG.getNode(ARMISD::VCGT, dl, CmpVT, TmpOp0, TmpOp1); 5343 break; 5344 case ISD::SETUO: 5345 Invert = true; 5346 LLVM_FALLTHROUGH; 5347 case ISD::SETO: 5348 // Expand this to (OLT | OGE). 5349 TmpOp0 = Op0; 5350 TmpOp1 = Op1; 5351 Opc = ISD::OR; 5352 Op0 = DAG.getNode(ARMISD::VCGT, dl, CmpVT, TmpOp1, TmpOp0); 5353 Op1 = DAG.getNode(ARMISD::VCGE, dl, CmpVT, TmpOp0, TmpOp1); 5354 break; 5355 } 5356 } else { 5357 // Integer comparisons. 5358 switch (SetCCOpcode) { 5359 default: llvm_unreachable("Illegal integer comparison"); 5360 case ISD::SETNE: Invert = true; LLVM_FALLTHROUGH; 5361 case ISD::SETEQ: Opc = ARMISD::VCEQ; break; 5362 case ISD::SETLT: Swap = true; LLVM_FALLTHROUGH; 5363 case ISD::SETGT: Opc = ARMISD::VCGT; break; 5364 case ISD::SETLE: Swap = true; LLVM_FALLTHROUGH; 5365 case ISD::SETGE: Opc = ARMISD::VCGE; break; 5366 case ISD::SETULT: Swap = true; LLVM_FALLTHROUGH; 5367 case ISD::SETUGT: Opc = ARMISD::VCGTU; break; 5368 case ISD::SETULE: Swap = true; LLVM_FALLTHROUGH; 5369 case ISD::SETUGE: Opc = ARMISD::VCGEU; break; 5370 } 5371 5372 // Detect VTST (Vector Test Bits) = icmp ne (and (op0, op1), zero). 5373 if (Opc == ARMISD::VCEQ) { 5374 5375 SDValue AndOp; 5376 if (ISD::isBuildVectorAllZeros(Op1.getNode())) 5377 AndOp = Op0; 5378 else if (ISD::isBuildVectorAllZeros(Op0.getNode())) 5379 AndOp = Op1; 5380 5381 // Ignore bitconvert. 5382 if (AndOp.getNode() && AndOp.getOpcode() == ISD::BITCAST) 5383 AndOp = AndOp.getOperand(0); 5384 5385 if (AndOp.getNode() && AndOp.getOpcode() == ISD::AND) { 5386 Opc = ARMISD::VTST; 5387 Op0 = DAG.getNode(ISD::BITCAST, dl, CmpVT, AndOp.getOperand(0)); 5388 Op1 = DAG.getNode(ISD::BITCAST, dl, CmpVT, AndOp.getOperand(1)); 5389 Invert = !Invert; 5390 } 5391 } 5392 } 5393 5394 if (Swap) 5395 std::swap(Op0, Op1); 5396 5397 // If one of the operands is a constant vector zero, attempt to fold the 5398 // comparison to a specialized compare-against-zero form. 5399 SDValue SingleOp; 5400 if (ISD::isBuildVectorAllZeros(Op1.getNode())) 5401 SingleOp = Op0; 5402 else if (ISD::isBuildVectorAllZeros(Op0.getNode())) { 5403 if (Opc == ARMISD::VCGE) 5404 Opc = ARMISD::VCLEZ; 5405 else if (Opc == ARMISD::VCGT) 5406 Opc = ARMISD::VCLTZ; 5407 SingleOp = Op1; 5408 } 5409 5410 SDValue Result; 5411 if (SingleOp.getNode()) { 5412 switch (Opc) { 5413 case ARMISD::VCEQ: 5414 Result = DAG.getNode(ARMISD::VCEQZ, dl, CmpVT, SingleOp); break; 5415 case ARMISD::VCGE: 5416 Result = DAG.getNode(ARMISD::VCGEZ, dl, CmpVT, SingleOp); break; 5417 case ARMISD::VCLEZ: 5418 Result = DAG.getNode(ARMISD::VCLEZ, dl, CmpVT, SingleOp); break; 5419 case ARMISD::VCGT: 5420 Result = DAG.getNode(ARMISD::VCGTZ, dl, CmpVT, SingleOp); break; 5421 case ARMISD::VCLTZ: 5422 Result = DAG.getNode(ARMISD::VCLTZ, dl, CmpVT, SingleOp); break; 5423 default: 5424 Result = DAG.getNode(Opc, dl, CmpVT, Op0, Op1); 5425 } 5426 } else { 5427 Result = DAG.getNode(Opc, dl, CmpVT, Op0, Op1); 5428 } 5429 5430 Result = DAG.getSExtOrTrunc(Result, dl, VT); 5431 5432 if (Invert) 5433 Result = DAG.getNOT(dl, Result, VT); 5434 5435 return Result; 5436 } 5437 5438 static SDValue LowerSETCCE(SDValue Op, SelectionDAG &DAG) { 5439 SDValue LHS = Op.getOperand(0); 5440 SDValue RHS = Op.getOperand(1); 5441 SDValue Carry = Op.getOperand(2); 5442 SDValue Cond = Op.getOperand(3); 5443 SDLoc DL(Op); 5444 5445 assert(LHS.getSimpleValueType().isInteger() && "SETCCE is integer only."); 5446 5447 assert(Carry.getOpcode() != ISD::CARRY_FALSE); 5448 SDVTList VTs = DAG.getVTList(LHS.getValueType(), MVT::i32); 5449 SDValue Cmp = DAG.getNode(ARMISD::SUBE, DL, VTs, LHS, RHS, Carry); 5450 5451 SDValue FVal = DAG.getConstant(0, DL, MVT::i32); 5452 SDValue TVal = DAG.getConstant(1, DL, MVT::i32); 5453 SDValue ARMcc = DAG.getConstant( 5454 IntCCToARMCC(cast<CondCodeSDNode>(Cond)->get()), DL, MVT::i32); 5455 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32); 5456 SDValue Chain = DAG.getCopyToReg(DAG.getEntryNode(), DL, ARM::CPSR, 5457 Cmp.getValue(1), SDValue()); 5458 return DAG.getNode(ARMISD::CMOV, DL, Op.getValueType(), FVal, TVal, ARMcc, 5459 CCR, Chain.getValue(1)); 5460 } 5461 5462 /// isNEONModifiedImm - Check if the specified splat value corresponds to a 5463 /// valid vector constant for a NEON instruction with a "modified immediate" 5464 /// operand (e.g., VMOV). If so, return the encoded value. 5465 static SDValue isNEONModifiedImm(uint64_t SplatBits, uint64_t SplatUndef, 5466 unsigned SplatBitSize, SelectionDAG &DAG, 5467 const SDLoc &dl, EVT &VT, bool is128Bits, 5468 NEONModImmType type) { 5469 unsigned OpCmode, Imm; 5470 5471 // SplatBitSize is set to the smallest size that splats the vector, so a 5472 // zero vector will always have SplatBitSize == 8. However, NEON modified 5473 // immediate instructions others than VMOV do not support the 8-bit encoding 5474 // of a zero vector, and the default encoding of zero is supposed to be the 5475 // 32-bit version. 5476 if (SplatBits == 0) 5477 SplatBitSize = 32; 5478 5479 switch (SplatBitSize) { 5480 case 8: 5481 if (type != VMOVModImm) 5482 return SDValue(); 5483 // Any 1-byte value is OK. Op=0, Cmode=1110. 5484 assert((SplatBits & ~0xff) == 0 && "one byte splat value is too big"); 5485 OpCmode = 0xe; 5486 Imm = SplatBits; 5487 VT = is128Bits ? MVT::v16i8 : MVT::v8i8; 5488 break; 5489 5490 case 16: 5491 // NEON's 16-bit VMOV supports splat values where only one byte is nonzero. 5492 VT = is128Bits ? MVT::v8i16 : MVT::v4i16; 5493 if ((SplatBits & ~0xff) == 0) { 5494 // Value = 0x00nn: Op=x, Cmode=100x. 5495 OpCmode = 0x8; 5496 Imm = SplatBits; 5497 break; 5498 } 5499 if ((SplatBits & ~0xff00) == 0) { 5500 // Value = 0xnn00: Op=x, Cmode=101x. 5501 OpCmode = 0xa; 5502 Imm = SplatBits >> 8; 5503 break; 5504 } 5505 return SDValue(); 5506 5507 case 32: 5508 // NEON's 32-bit VMOV supports splat values where: 5509 // * only one byte is nonzero, or 5510 // * the least significant byte is 0xff and the second byte is nonzero, or 5511 // * the least significant 2 bytes are 0xff and the third is nonzero. 5512 VT = is128Bits ? MVT::v4i32 : MVT::v2i32; 5513 if ((SplatBits & ~0xff) == 0) { 5514 // Value = 0x000000nn: Op=x, Cmode=000x. 5515 OpCmode = 0; 5516 Imm = SplatBits; 5517 break; 5518 } 5519 if ((SplatBits & ~0xff00) == 0) { 5520 // Value = 0x0000nn00: Op=x, Cmode=001x. 5521 OpCmode = 0x2; 5522 Imm = SplatBits >> 8; 5523 break; 5524 } 5525 if ((SplatBits & ~0xff0000) == 0) { 5526 // Value = 0x00nn0000: Op=x, Cmode=010x. 5527 OpCmode = 0x4; 5528 Imm = SplatBits >> 16; 5529 break; 5530 } 5531 if ((SplatBits & ~0xff000000) == 0) { 5532 // Value = 0xnn000000: Op=x, Cmode=011x. 5533 OpCmode = 0x6; 5534 Imm = SplatBits >> 24; 5535 break; 5536 } 5537 5538 // cmode == 0b1100 and cmode == 0b1101 are not supported for VORR or VBIC 5539 if (type == OtherModImm) return SDValue(); 5540 5541 if ((SplatBits & ~0xffff) == 0 && 5542 ((SplatBits | SplatUndef) & 0xff) == 0xff) { 5543 // Value = 0x0000nnff: Op=x, Cmode=1100. 5544 OpCmode = 0xc; 5545 Imm = SplatBits >> 8; 5546 break; 5547 } 5548 5549 if ((SplatBits & ~0xffffff) == 0 && 5550 ((SplatBits | SplatUndef) & 0xffff) == 0xffff) { 5551 // Value = 0x00nnffff: Op=x, Cmode=1101. 5552 OpCmode = 0xd; 5553 Imm = SplatBits >> 16; 5554 break; 5555 } 5556 5557 // Note: there are a few 32-bit splat values (specifically: 00ffff00, 5558 // ff000000, ff0000ff, and ffff00ff) that are valid for VMOV.I64 but not 5559 // VMOV.I32. A (very) minor optimization would be to replicate the value 5560 // and fall through here to test for a valid 64-bit splat. But, then the 5561 // caller would also need to check and handle the change in size. 5562 return SDValue(); 5563 5564 case 64: { 5565 if (type != VMOVModImm) 5566 return SDValue(); 5567 // NEON has a 64-bit VMOV splat where each byte is either 0 or 0xff. 5568 uint64_t BitMask = 0xff; 5569 uint64_t Val = 0; 5570 unsigned ImmMask = 1; 5571 Imm = 0; 5572 for (int ByteNum = 0; ByteNum < 8; ++ByteNum) { 5573 if (((SplatBits | SplatUndef) & BitMask) == BitMask) { 5574 Val |= BitMask; 5575 Imm |= ImmMask; 5576 } else if ((SplatBits & BitMask) != 0) { 5577 return SDValue(); 5578 } 5579 BitMask <<= 8; 5580 ImmMask <<= 1; 5581 } 5582 5583 if (DAG.getDataLayout().isBigEndian()) 5584 // swap higher and lower 32 bit word 5585 Imm = ((Imm & 0xf) << 4) | ((Imm & 0xf0) >> 4); 5586 5587 // Op=1, Cmode=1110. 5588 OpCmode = 0x1e; 5589 VT = is128Bits ? MVT::v2i64 : MVT::v1i64; 5590 break; 5591 } 5592 5593 default: 5594 llvm_unreachable("unexpected size for isNEONModifiedImm"); 5595 } 5596 5597 unsigned EncodedVal = ARM_AM::createNEONModImm(OpCmode, Imm); 5598 return DAG.getTargetConstant(EncodedVal, dl, MVT::i32); 5599 } 5600 5601 SDValue ARMTargetLowering::LowerConstantFP(SDValue Op, SelectionDAG &DAG, 5602 const ARMSubtarget *ST) const { 5603 bool IsDouble = Op.getValueType() == MVT::f64; 5604 ConstantFPSDNode *CFP = cast<ConstantFPSDNode>(Op); 5605 const APFloat &FPVal = CFP->getValueAPF(); 5606 5607 // Prevent floating-point constants from using literal loads 5608 // when execute-only is enabled. 5609 if (ST->genExecuteOnly()) { 5610 APInt INTVal = FPVal.bitcastToAPInt(); 5611 SDLoc DL(CFP); 5612 if (IsDouble) { 5613 SDValue Lo = DAG.getConstant(INTVal.trunc(32), DL, MVT::i32); 5614 SDValue Hi = DAG.getConstant(INTVal.lshr(32).trunc(32), DL, MVT::i32); 5615 if (!ST->isLittle()) 5616 std::swap(Lo, Hi); 5617 return DAG.getNode(ARMISD::VMOVDRR, DL, MVT::f64, Lo, Hi); 5618 } else { 5619 return DAG.getConstant(INTVal, DL, MVT::i32); 5620 } 5621 } 5622 5623 if (!ST->hasVFP3()) 5624 return SDValue(); 5625 5626 // Use the default (constant pool) lowering for double constants when we have 5627 // an SP-only FPU 5628 if (IsDouble && Subtarget->isFPOnlySP()) 5629 return SDValue(); 5630 5631 // Try splatting with a VMOV.f32... 5632 int ImmVal = IsDouble ? ARM_AM::getFP64Imm(FPVal) : ARM_AM::getFP32Imm(FPVal); 5633 5634 if (ImmVal != -1) { 5635 if (IsDouble || !ST->useNEONForSinglePrecisionFP()) { 5636 // We have code in place to select a valid ConstantFP already, no need to 5637 // do any mangling. 5638 return Op; 5639 } 5640 5641 // It's a float and we are trying to use NEON operations where 5642 // possible. Lower it to a splat followed by an extract. 5643 SDLoc DL(Op); 5644 SDValue NewVal = DAG.getTargetConstant(ImmVal, DL, MVT::i32); 5645 SDValue VecConstant = DAG.getNode(ARMISD::VMOVFPIMM, DL, MVT::v2f32, 5646 NewVal); 5647 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32, VecConstant, 5648 DAG.getConstant(0, DL, MVT::i32)); 5649 } 5650 5651 // The rest of our options are NEON only, make sure that's allowed before 5652 // proceeding.. 5653 if (!ST->hasNEON() || (!IsDouble && !ST->useNEONForSinglePrecisionFP())) 5654 return SDValue(); 5655 5656 EVT VMovVT; 5657 uint64_t iVal = FPVal.bitcastToAPInt().getZExtValue(); 5658 5659 // It wouldn't really be worth bothering for doubles except for one very 5660 // important value, which does happen to match: 0.0. So make sure we don't do 5661 // anything stupid. 5662 if (IsDouble && (iVal & 0xffffffff) != (iVal >> 32)) 5663 return SDValue(); 5664 5665 // Try a VMOV.i32 (FIXME: i8, i16, or i64 could work too). 5666 SDValue NewVal = isNEONModifiedImm(iVal & 0xffffffffU, 0, 32, DAG, SDLoc(Op), 5667 VMovVT, false, VMOVModImm); 5668 if (NewVal != SDValue()) { 5669 SDLoc DL(Op); 5670 SDValue VecConstant = DAG.getNode(ARMISD::VMOVIMM, DL, VMovVT, 5671 NewVal); 5672 if (IsDouble) 5673 return DAG.getNode(ISD::BITCAST, DL, MVT::f64, VecConstant); 5674 5675 // It's a float: cast and extract a vector element. 5676 SDValue VecFConstant = DAG.getNode(ISD::BITCAST, DL, MVT::v2f32, 5677 VecConstant); 5678 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32, VecFConstant, 5679 DAG.getConstant(0, DL, MVT::i32)); 5680 } 5681 5682 // Finally, try a VMVN.i32 5683 NewVal = isNEONModifiedImm(~iVal & 0xffffffffU, 0, 32, DAG, SDLoc(Op), VMovVT, 5684 false, VMVNModImm); 5685 if (NewVal != SDValue()) { 5686 SDLoc DL(Op); 5687 SDValue VecConstant = DAG.getNode(ARMISD::VMVNIMM, DL, VMovVT, NewVal); 5688 5689 if (IsDouble) 5690 return DAG.getNode(ISD::BITCAST, DL, MVT::f64, VecConstant); 5691 5692 // It's a float: cast and extract a vector element. 5693 SDValue VecFConstant = DAG.getNode(ISD::BITCAST, DL, MVT::v2f32, 5694 VecConstant); 5695 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32, VecFConstant, 5696 DAG.getConstant(0, DL, MVT::i32)); 5697 } 5698 5699 return SDValue(); 5700 } 5701 5702 // check if an VEXT instruction can handle the shuffle mask when the 5703 // vector sources of the shuffle are the same. 5704 static bool isSingletonVEXTMask(ArrayRef<int> M, EVT VT, unsigned &Imm) { 5705 unsigned NumElts = VT.getVectorNumElements(); 5706 5707 // Assume that the first shuffle index is not UNDEF. Fail if it is. 5708 if (M[0] < 0) 5709 return false; 5710 5711 Imm = M[0]; 5712 5713 // If this is a VEXT shuffle, the immediate value is the index of the first 5714 // element. The other shuffle indices must be the successive elements after 5715 // the first one. 5716 unsigned ExpectedElt = Imm; 5717 for (unsigned i = 1; i < NumElts; ++i) { 5718 // Increment the expected index. If it wraps around, just follow it 5719 // back to index zero and keep going. 5720 ++ExpectedElt; 5721 if (ExpectedElt == NumElts) 5722 ExpectedElt = 0; 5723 5724 if (M[i] < 0) continue; // ignore UNDEF indices 5725 if (ExpectedElt != static_cast<unsigned>(M[i])) 5726 return false; 5727 } 5728 5729 return true; 5730 } 5731 5732 static bool isVEXTMask(ArrayRef<int> M, EVT VT, 5733 bool &ReverseVEXT, unsigned &Imm) { 5734 unsigned NumElts = VT.getVectorNumElements(); 5735 ReverseVEXT = false; 5736 5737 // Assume that the first shuffle index is not UNDEF. Fail if it is. 5738 if (M[0] < 0) 5739 return false; 5740 5741 Imm = M[0]; 5742 5743 // If this is a VEXT shuffle, the immediate value is the index of the first 5744 // element. The other shuffle indices must be the successive elements after 5745 // the first one. 5746 unsigned ExpectedElt = Imm; 5747 for (unsigned i = 1; i < NumElts; ++i) { 5748 // Increment the expected index. If it wraps around, it may still be 5749 // a VEXT but the source vectors must be swapped. 5750 ExpectedElt += 1; 5751 if (ExpectedElt == NumElts * 2) { 5752 ExpectedElt = 0; 5753 ReverseVEXT = true; 5754 } 5755 5756 if (M[i] < 0) continue; // ignore UNDEF indices 5757 if (ExpectedElt != static_cast<unsigned>(M[i])) 5758 return false; 5759 } 5760 5761 // Adjust the index value if the source operands will be swapped. 5762 if (ReverseVEXT) 5763 Imm -= NumElts; 5764 5765 return true; 5766 } 5767 5768 /// isVREVMask - Check if a vector shuffle corresponds to a VREV 5769 /// instruction with the specified blocksize. (The order of the elements 5770 /// within each block of the vector is reversed.) 5771 static bool isVREVMask(ArrayRef<int> M, EVT VT, unsigned BlockSize) { 5772 assert((BlockSize==16 || BlockSize==32 || BlockSize==64) && 5773 "Only possible block sizes for VREV are: 16, 32, 64"); 5774 5775 unsigned EltSz = VT.getScalarSizeInBits(); 5776 if (EltSz == 64) 5777 return false; 5778 5779 unsigned NumElts = VT.getVectorNumElements(); 5780 unsigned BlockElts = M[0] + 1; 5781 // If the first shuffle index is UNDEF, be optimistic. 5782 if (M[0] < 0) 5783 BlockElts = BlockSize / EltSz; 5784 5785 if (BlockSize <= EltSz || BlockSize != BlockElts * EltSz) 5786 return false; 5787 5788 for (unsigned i = 0; i < NumElts; ++i) { 5789 if (M[i] < 0) continue; // ignore UNDEF indices 5790 if ((unsigned) M[i] != (i - i%BlockElts) + (BlockElts - 1 - i%BlockElts)) 5791 return false; 5792 } 5793 5794 return true; 5795 } 5796 5797 static bool isVTBLMask(ArrayRef<int> M, EVT VT) { 5798 // We can handle <8 x i8> vector shuffles. If the index in the mask is out of 5799 // range, then 0 is placed into the resulting vector. So pretty much any mask 5800 // of 8 elements can work here. 5801 return VT == MVT::v8i8 && M.size() == 8; 5802 } 5803 5804 static unsigned SelectPairHalf(unsigned Elements, ArrayRef<int> Mask, 5805 unsigned Index) { 5806 if (Mask.size() == Elements * 2) 5807 return Index / Elements; 5808 return Mask[Index] == 0 ? 0 : 1; 5809 } 5810 5811 // Checks whether the shuffle mask represents a vector transpose (VTRN) by 5812 // checking that pairs of elements in the shuffle mask represent the same index 5813 // in each vector, incrementing the expected index by 2 at each step. 5814 // e.g. For v1,v2 of type v4i32 a valid shuffle mask is: [0, 4, 2, 6] 5815 // v1={a,b,c,d} => x=shufflevector v1, v2 shufflemask => x={a,e,c,g} 5816 // v2={e,f,g,h} 5817 // WhichResult gives the offset for each element in the mask based on which 5818 // of the two results it belongs to. 5819 // 5820 // The transpose can be represented either as: 5821 // result1 = shufflevector v1, v2, result1_shuffle_mask 5822 // result2 = shufflevector v1, v2, result2_shuffle_mask 5823 // where v1/v2 and the shuffle masks have the same number of elements 5824 // (here WhichResult (see below) indicates which result is being checked) 5825 // 5826 // or as: 5827 // results = shufflevector v1, v2, shuffle_mask 5828 // where both results are returned in one vector and the shuffle mask has twice 5829 // as many elements as v1/v2 (here WhichResult will always be 0 if true) here we 5830 // want to check the low half and high half of the shuffle mask as if it were 5831 // the other case 5832 static bool isVTRNMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) { 5833 unsigned EltSz = VT.getScalarSizeInBits(); 5834 if (EltSz == 64) 5835 return false; 5836 5837 unsigned NumElts = VT.getVectorNumElements(); 5838 if (M.size() != NumElts && M.size() != NumElts*2) 5839 return false; 5840 5841 // If the mask is twice as long as the input vector then we need to check the 5842 // upper and lower parts of the mask with a matching value for WhichResult 5843 // FIXME: A mask with only even values will be rejected in case the first 5844 // element is undefined, e.g. [-1, 4, 2, 6] will be rejected, because only 5845 // M[0] is used to determine WhichResult 5846 for (unsigned i = 0; i < M.size(); i += NumElts) { 5847 WhichResult = SelectPairHalf(NumElts, M, i); 5848 for (unsigned j = 0; j < NumElts; j += 2) { 5849 if ((M[i+j] >= 0 && (unsigned) M[i+j] != j + WhichResult) || 5850 (M[i+j+1] >= 0 && (unsigned) M[i+j+1] != j + NumElts + WhichResult)) 5851 return false; 5852 } 5853 } 5854 5855 if (M.size() == NumElts*2) 5856 WhichResult = 0; 5857 5858 return true; 5859 } 5860 5861 /// isVTRN_v_undef_Mask - Special case of isVTRNMask for canonical form of 5862 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef". 5863 /// Mask is e.g., <0, 0, 2, 2> instead of <0, 4, 2, 6>. 5864 static bool isVTRN_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult){ 5865 unsigned EltSz = VT.getScalarSizeInBits(); 5866 if (EltSz == 64) 5867 return false; 5868 5869 unsigned NumElts = VT.getVectorNumElements(); 5870 if (M.size() != NumElts && M.size() != NumElts*2) 5871 return false; 5872 5873 for (unsigned i = 0; i < M.size(); i += NumElts) { 5874 WhichResult = SelectPairHalf(NumElts, M, i); 5875 for (unsigned j = 0; j < NumElts; j += 2) { 5876 if ((M[i+j] >= 0 && (unsigned) M[i+j] != j + WhichResult) || 5877 (M[i+j+1] >= 0 && (unsigned) M[i+j+1] != j + WhichResult)) 5878 return false; 5879 } 5880 } 5881 5882 if (M.size() == NumElts*2) 5883 WhichResult = 0; 5884 5885 return true; 5886 } 5887 5888 // Checks whether the shuffle mask represents a vector unzip (VUZP) by checking 5889 // that the mask elements are either all even and in steps of size 2 or all odd 5890 // and in steps of size 2. 5891 // e.g. For v1,v2 of type v4i32 a valid shuffle mask is: [0, 2, 4, 6] 5892 // v1={a,b,c,d} => x=shufflevector v1, v2 shufflemask => x={a,c,e,g} 5893 // v2={e,f,g,h} 5894 // Requires similar checks to that of isVTRNMask with 5895 // respect the how results are returned. 5896 static bool isVUZPMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) { 5897 unsigned EltSz = VT.getScalarSizeInBits(); 5898 if (EltSz == 64) 5899 return false; 5900 5901 unsigned NumElts = VT.getVectorNumElements(); 5902 if (M.size() != NumElts && M.size() != NumElts*2) 5903 return false; 5904 5905 for (unsigned i = 0; i < M.size(); i += NumElts) { 5906 WhichResult = SelectPairHalf(NumElts, M, i); 5907 for (unsigned j = 0; j < NumElts; ++j) { 5908 if (M[i+j] >= 0 && (unsigned) M[i+j] != 2 * j + WhichResult) 5909 return false; 5910 } 5911 } 5912 5913 if (M.size() == NumElts*2) 5914 WhichResult = 0; 5915 5916 // VUZP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32. 5917 if (VT.is64BitVector() && EltSz == 32) 5918 return false; 5919 5920 return true; 5921 } 5922 5923 /// isVUZP_v_undef_Mask - Special case of isVUZPMask for canonical form of 5924 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef". 5925 /// Mask is e.g., <0, 2, 0, 2> instead of <0, 2, 4, 6>, 5926 static bool isVUZP_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult){ 5927 unsigned EltSz = VT.getScalarSizeInBits(); 5928 if (EltSz == 64) 5929 return false; 5930 5931 unsigned NumElts = VT.getVectorNumElements(); 5932 if (M.size() != NumElts && M.size() != NumElts*2) 5933 return false; 5934 5935 unsigned Half = NumElts / 2; 5936 for (unsigned i = 0; i < M.size(); i += NumElts) { 5937 WhichResult = SelectPairHalf(NumElts, M, i); 5938 for (unsigned j = 0; j < NumElts; j += Half) { 5939 unsigned Idx = WhichResult; 5940 for (unsigned k = 0; k < Half; ++k) { 5941 int MIdx = M[i + j + k]; 5942 if (MIdx >= 0 && (unsigned) MIdx != Idx) 5943 return false; 5944 Idx += 2; 5945 } 5946 } 5947 } 5948 5949 if (M.size() == NumElts*2) 5950 WhichResult = 0; 5951 5952 // VUZP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32. 5953 if (VT.is64BitVector() && EltSz == 32) 5954 return false; 5955 5956 return true; 5957 } 5958 5959 // Checks whether the shuffle mask represents a vector zip (VZIP) by checking 5960 // that pairs of elements of the shufflemask represent the same index in each 5961 // vector incrementing sequentially through the vectors. 5962 // e.g. For v1,v2 of type v4i32 a valid shuffle mask is: [0, 4, 1, 5] 5963 // v1={a,b,c,d} => x=shufflevector v1, v2 shufflemask => x={a,e,b,f} 5964 // v2={e,f,g,h} 5965 // Requires similar checks to that of isVTRNMask with respect the how results 5966 // are returned. 5967 static bool isVZIPMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) { 5968 unsigned EltSz = VT.getScalarSizeInBits(); 5969 if (EltSz == 64) 5970 return false; 5971 5972 unsigned NumElts = VT.getVectorNumElements(); 5973 if (M.size() != NumElts && M.size() != NumElts*2) 5974 return false; 5975 5976 for (unsigned i = 0; i < M.size(); i += NumElts) { 5977 WhichResult = SelectPairHalf(NumElts, M, i); 5978 unsigned Idx = WhichResult * NumElts / 2; 5979 for (unsigned j = 0; j < NumElts; j += 2) { 5980 if ((M[i+j] >= 0 && (unsigned) M[i+j] != Idx) || 5981 (M[i+j+1] >= 0 && (unsigned) M[i+j+1] != Idx + NumElts)) 5982 return false; 5983 Idx += 1; 5984 } 5985 } 5986 5987 if (M.size() == NumElts*2) 5988 WhichResult = 0; 5989 5990 // VZIP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32. 5991 if (VT.is64BitVector() && EltSz == 32) 5992 return false; 5993 5994 return true; 5995 } 5996 5997 /// isVZIP_v_undef_Mask - Special case of isVZIPMask for canonical form of 5998 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef". 5999 /// Mask is e.g., <0, 0, 1, 1> instead of <0, 4, 1, 5>. 6000 static bool isVZIP_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult){ 6001 unsigned EltSz = VT.getScalarSizeInBits(); 6002 if (EltSz == 64) 6003 return false; 6004 6005 unsigned NumElts = VT.getVectorNumElements(); 6006 if (M.size() != NumElts && M.size() != NumElts*2) 6007 return false; 6008 6009 for (unsigned i = 0; i < M.size(); i += NumElts) { 6010 WhichResult = SelectPairHalf(NumElts, M, i); 6011 unsigned Idx = WhichResult * NumElts / 2; 6012 for (unsigned j = 0; j < NumElts; j += 2) { 6013 if ((M[i+j] >= 0 && (unsigned) M[i+j] != Idx) || 6014 (M[i+j+1] >= 0 && (unsigned) M[i+j+1] != Idx)) 6015 return false; 6016 Idx += 1; 6017 } 6018 } 6019 6020 if (M.size() == NumElts*2) 6021 WhichResult = 0; 6022 6023 // VZIP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32. 6024 if (VT.is64BitVector() && EltSz == 32) 6025 return false; 6026 6027 return true; 6028 } 6029 6030 /// Check if \p ShuffleMask is a NEON two-result shuffle (VZIP, VUZP, VTRN), 6031 /// and return the corresponding ARMISD opcode if it is, or 0 if it isn't. 6032 static unsigned isNEONTwoResultShuffleMask(ArrayRef<int> ShuffleMask, EVT VT, 6033 unsigned &WhichResult, 6034 bool &isV_UNDEF) { 6035 isV_UNDEF = false; 6036 if (isVTRNMask(ShuffleMask, VT, WhichResult)) 6037 return ARMISD::VTRN; 6038 if (isVUZPMask(ShuffleMask, VT, WhichResult)) 6039 return ARMISD::VUZP; 6040 if (isVZIPMask(ShuffleMask, VT, WhichResult)) 6041 return ARMISD::VZIP; 6042 6043 isV_UNDEF = true; 6044 if (isVTRN_v_undef_Mask(ShuffleMask, VT, WhichResult)) 6045 return ARMISD::VTRN; 6046 if (isVUZP_v_undef_Mask(ShuffleMask, VT, WhichResult)) 6047 return ARMISD::VUZP; 6048 if (isVZIP_v_undef_Mask(ShuffleMask, VT, WhichResult)) 6049 return ARMISD::VZIP; 6050 6051 return 0; 6052 } 6053 6054 /// \return true if this is a reverse operation on an vector. 6055 static bool isReverseMask(ArrayRef<int> M, EVT VT) { 6056 unsigned NumElts = VT.getVectorNumElements(); 6057 // Make sure the mask has the right size. 6058 if (NumElts != M.size()) 6059 return false; 6060 6061 // Look for <15, ..., 3, -1, 1, 0>. 6062 for (unsigned i = 0; i != NumElts; ++i) 6063 if (M[i] >= 0 && M[i] != (int) (NumElts - 1 - i)) 6064 return false; 6065 6066 return true; 6067 } 6068 6069 // If N is an integer constant that can be moved into a register in one 6070 // instruction, return an SDValue of such a constant (will become a MOV 6071 // instruction). Otherwise return null. 6072 static SDValue IsSingleInstrConstant(SDValue N, SelectionDAG &DAG, 6073 const ARMSubtarget *ST, const SDLoc &dl) { 6074 uint64_t Val; 6075 if (!isa<ConstantSDNode>(N)) 6076 return SDValue(); 6077 Val = cast<ConstantSDNode>(N)->getZExtValue(); 6078 6079 if (ST->isThumb1Only()) { 6080 if (Val <= 255 || ~Val <= 255) 6081 return DAG.getConstant(Val, dl, MVT::i32); 6082 } else { 6083 if (ARM_AM::getSOImmVal(Val) != -1 || ARM_AM::getSOImmVal(~Val) != -1) 6084 return DAG.getConstant(Val, dl, MVT::i32); 6085 } 6086 return SDValue(); 6087 } 6088 6089 // If this is a case we can't handle, return null and let the default 6090 // expansion code take care of it. 6091 SDValue ARMTargetLowering::LowerBUILD_VECTOR(SDValue Op, SelectionDAG &DAG, 6092 const ARMSubtarget *ST) const { 6093 BuildVectorSDNode *BVN = cast<BuildVectorSDNode>(Op.getNode()); 6094 SDLoc dl(Op); 6095 EVT VT = Op.getValueType(); 6096 6097 APInt SplatBits, SplatUndef; 6098 unsigned SplatBitSize; 6099 bool HasAnyUndefs; 6100 if (BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs)) { 6101 if (SplatUndef.isAllOnesValue()) 6102 return DAG.getUNDEF(VT); 6103 6104 if (SplatBitSize <= 64) { 6105 // Check if an immediate VMOV works. 6106 EVT VmovVT; 6107 SDValue Val = isNEONModifiedImm(SplatBits.getZExtValue(), 6108 SplatUndef.getZExtValue(), SplatBitSize, 6109 DAG, dl, VmovVT, VT.is128BitVector(), 6110 VMOVModImm); 6111 if (Val.getNode()) { 6112 SDValue Vmov = DAG.getNode(ARMISD::VMOVIMM, dl, VmovVT, Val); 6113 return DAG.getNode(ISD::BITCAST, dl, VT, Vmov); 6114 } 6115 6116 // Try an immediate VMVN. 6117 uint64_t NegatedImm = (~SplatBits).getZExtValue(); 6118 Val = isNEONModifiedImm(NegatedImm, 6119 SplatUndef.getZExtValue(), SplatBitSize, 6120 DAG, dl, VmovVT, VT.is128BitVector(), 6121 VMVNModImm); 6122 if (Val.getNode()) { 6123 SDValue Vmov = DAG.getNode(ARMISD::VMVNIMM, dl, VmovVT, Val); 6124 return DAG.getNode(ISD::BITCAST, dl, VT, Vmov); 6125 } 6126 6127 // Use vmov.f32 to materialize other v2f32 and v4f32 splats. 6128 if ((VT == MVT::v2f32 || VT == MVT::v4f32) && SplatBitSize == 32) { 6129 int ImmVal = ARM_AM::getFP32Imm(SplatBits); 6130 if (ImmVal != -1) { 6131 SDValue Val = DAG.getTargetConstant(ImmVal, dl, MVT::i32); 6132 return DAG.getNode(ARMISD::VMOVFPIMM, dl, VT, Val); 6133 } 6134 } 6135 } 6136 } 6137 6138 // Scan through the operands to see if only one value is used. 6139 // 6140 // As an optimisation, even if more than one value is used it may be more 6141 // profitable to splat with one value then change some lanes. 6142 // 6143 // Heuristically we decide to do this if the vector has a "dominant" value, 6144 // defined as splatted to more than half of the lanes. 6145 unsigned NumElts = VT.getVectorNumElements(); 6146 bool isOnlyLowElement = true; 6147 bool usesOnlyOneValue = true; 6148 bool hasDominantValue = false; 6149 bool isConstant = true; 6150 6151 // Map of the number of times a particular SDValue appears in the 6152 // element list. 6153 DenseMap<SDValue, unsigned> ValueCounts; 6154 SDValue Value; 6155 for (unsigned i = 0; i < NumElts; ++i) { 6156 SDValue V = Op.getOperand(i); 6157 if (V.isUndef()) 6158 continue; 6159 if (i > 0) 6160 isOnlyLowElement = false; 6161 if (!isa<ConstantFPSDNode>(V) && !isa<ConstantSDNode>(V)) 6162 isConstant = false; 6163 6164 ValueCounts.insert(std::make_pair(V, 0)); 6165 unsigned &Count = ValueCounts[V]; 6166 6167 // Is this value dominant? (takes up more than half of the lanes) 6168 if (++Count > (NumElts / 2)) { 6169 hasDominantValue = true; 6170 Value = V; 6171 } 6172 } 6173 if (ValueCounts.size() != 1) 6174 usesOnlyOneValue = false; 6175 if (!Value.getNode() && !ValueCounts.empty()) 6176 Value = ValueCounts.begin()->first; 6177 6178 if (ValueCounts.empty()) 6179 return DAG.getUNDEF(VT); 6180 6181 // Loads are better lowered with insert_vector_elt/ARMISD::BUILD_VECTOR. 6182 // Keep going if we are hitting this case. 6183 if (isOnlyLowElement && !ISD::isNormalLoad(Value.getNode())) 6184 return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Value); 6185 6186 unsigned EltSize = VT.getScalarSizeInBits(); 6187 6188 // Use VDUP for non-constant splats. For f32 constant splats, reduce to 6189 // i32 and try again. 6190 if (hasDominantValue && EltSize <= 32) { 6191 if (!isConstant) { 6192 SDValue N; 6193 6194 // If we are VDUPing a value that comes directly from a vector, that will 6195 // cause an unnecessary move to and from a GPR, where instead we could 6196 // just use VDUPLANE. We can only do this if the lane being extracted 6197 // is at a constant index, as the VDUP from lane instructions only have 6198 // constant-index forms. 6199 ConstantSDNode *constIndex; 6200 if (Value->getOpcode() == ISD::EXTRACT_VECTOR_ELT && 6201 (constIndex = dyn_cast<ConstantSDNode>(Value->getOperand(1)))) { 6202 // We need to create a new undef vector to use for the VDUPLANE if the 6203 // size of the vector from which we get the value is different than the 6204 // size of the vector that we need to create. We will insert the element 6205 // such that the register coalescer will remove unnecessary copies. 6206 if (VT != Value->getOperand(0).getValueType()) { 6207 unsigned index = constIndex->getAPIntValue().getLimitedValue() % 6208 VT.getVectorNumElements(); 6209 N = DAG.getNode(ARMISD::VDUPLANE, dl, VT, 6210 DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, DAG.getUNDEF(VT), 6211 Value, DAG.getConstant(index, dl, MVT::i32)), 6212 DAG.getConstant(index, dl, MVT::i32)); 6213 } else 6214 N = DAG.getNode(ARMISD::VDUPLANE, dl, VT, 6215 Value->getOperand(0), Value->getOperand(1)); 6216 } else 6217 N = DAG.getNode(ARMISD::VDUP, dl, VT, Value); 6218 6219 if (!usesOnlyOneValue) { 6220 // The dominant value was splatted as 'N', but we now have to insert 6221 // all differing elements. 6222 for (unsigned I = 0; I < NumElts; ++I) { 6223 if (Op.getOperand(I) == Value) 6224 continue; 6225 SmallVector<SDValue, 3> Ops; 6226 Ops.push_back(N); 6227 Ops.push_back(Op.getOperand(I)); 6228 Ops.push_back(DAG.getConstant(I, dl, MVT::i32)); 6229 N = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Ops); 6230 } 6231 } 6232 return N; 6233 } 6234 if (VT.getVectorElementType().isFloatingPoint()) { 6235 SmallVector<SDValue, 8> Ops; 6236 for (unsigned i = 0; i < NumElts; ++i) 6237 Ops.push_back(DAG.getNode(ISD::BITCAST, dl, MVT::i32, 6238 Op.getOperand(i))); 6239 EVT VecVT = EVT::getVectorVT(*DAG.getContext(), MVT::i32, NumElts); 6240 SDValue Val = DAG.getBuildVector(VecVT, dl, Ops); 6241 Val = LowerBUILD_VECTOR(Val, DAG, ST); 6242 if (Val.getNode()) 6243 return DAG.getNode(ISD::BITCAST, dl, VT, Val); 6244 } 6245 if (usesOnlyOneValue) { 6246 SDValue Val = IsSingleInstrConstant(Value, DAG, ST, dl); 6247 if (isConstant && Val.getNode()) 6248 return DAG.getNode(ARMISD::VDUP, dl, VT, Val); 6249 } 6250 } 6251 6252 // If all elements are constants and the case above didn't get hit, fall back 6253 // to the default expansion, which will generate a load from the constant 6254 // pool. 6255 if (isConstant) 6256 return SDValue(); 6257 6258 // Empirical tests suggest this is rarely worth it for vectors of length <= 2. 6259 if (NumElts >= 4) { 6260 SDValue shuffle = ReconstructShuffle(Op, DAG); 6261 if (shuffle != SDValue()) 6262 return shuffle; 6263 } 6264 6265 if (VT.is128BitVector() && VT != MVT::v2f64 && VT != MVT::v4f32) { 6266 // If we haven't found an efficient lowering, try splitting a 128-bit vector 6267 // into two 64-bit vectors; we might discover a better way to lower it. 6268 SmallVector<SDValue, 64> Ops(Op->op_begin(), Op->op_begin() + NumElts); 6269 EVT ExtVT = VT.getVectorElementType(); 6270 EVT HVT = EVT::getVectorVT(*DAG.getContext(), ExtVT, NumElts / 2); 6271 SDValue Lower = 6272 DAG.getBuildVector(HVT, dl, makeArrayRef(&Ops[0], NumElts / 2)); 6273 if (Lower.getOpcode() == ISD::BUILD_VECTOR) 6274 Lower = LowerBUILD_VECTOR(Lower, DAG, ST); 6275 SDValue Upper = DAG.getBuildVector( 6276 HVT, dl, makeArrayRef(&Ops[NumElts / 2], NumElts / 2)); 6277 if (Upper.getOpcode() == ISD::BUILD_VECTOR) 6278 Upper = LowerBUILD_VECTOR(Upper, DAG, ST); 6279 if (Lower && Upper) 6280 return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, Lower, Upper); 6281 } 6282 6283 // Vectors with 32- or 64-bit elements can be built by directly assigning 6284 // the subregisters. Lower it to an ARMISD::BUILD_VECTOR so the operands 6285 // will be legalized. 6286 if (EltSize >= 32) { 6287 // Do the expansion with floating-point types, since that is what the VFP 6288 // registers are defined to use, and since i64 is not legal. 6289 EVT EltVT = EVT::getFloatingPointVT(EltSize); 6290 EVT VecVT = EVT::getVectorVT(*DAG.getContext(), EltVT, NumElts); 6291 SmallVector<SDValue, 8> Ops; 6292 for (unsigned i = 0; i < NumElts; ++i) 6293 Ops.push_back(DAG.getNode(ISD::BITCAST, dl, EltVT, Op.getOperand(i))); 6294 SDValue Val = DAG.getNode(ARMISD::BUILD_VECTOR, dl, VecVT, Ops); 6295 return DAG.getNode(ISD::BITCAST, dl, VT, Val); 6296 } 6297 6298 // If all else fails, just use a sequence of INSERT_VECTOR_ELT when we 6299 // know the default expansion would otherwise fall back on something even 6300 // worse. For a vector with one or two non-undef values, that's 6301 // scalar_to_vector for the elements followed by a shuffle (provided the 6302 // shuffle is valid for the target) and materialization element by element 6303 // on the stack followed by a load for everything else. 6304 if (!isConstant && !usesOnlyOneValue) { 6305 SDValue Vec = DAG.getUNDEF(VT); 6306 for (unsigned i = 0 ; i < NumElts; ++i) { 6307 SDValue V = Op.getOperand(i); 6308 if (V.isUndef()) 6309 continue; 6310 SDValue LaneIdx = DAG.getConstant(i, dl, MVT::i32); 6311 Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Vec, V, LaneIdx); 6312 } 6313 return Vec; 6314 } 6315 6316 return SDValue(); 6317 } 6318 6319 // Gather data to see if the operation can be modelled as a 6320 // shuffle in combination with VEXTs. 6321 SDValue ARMTargetLowering::ReconstructShuffle(SDValue Op, 6322 SelectionDAG &DAG) const { 6323 assert(Op.getOpcode() == ISD::BUILD_VECTOR && "Unknown opcode!"); 6324 SDLoc dl(Op); 6325 EVT VT = Op.getValueType(); 6326 unsigned NumElts = VT.getVectorNumElements(); 6327 6328 struct ShuffleSourceInfo { 6329 SDValue Vec; 6330 unsigned MinElt = std::numeric_limits<unsigned>::max(); 6331 unsigned MaxElt = 0; 6332 6333 // We may insert some combination of BITCASTs and VEXT nodes to force Vec to 6334 // be compatible with the shuffle we intend to construct. As a result 6335 // ShuffleVec will be some sliding window into the original Vec. 6336 SDValue ShuffleVec; 6337 6338 // Code should guarantee that element i in Vec starts at element "WindowBase 6339 // + i * WindowScale in ShuffleVec". 6340 int WindowBase = 0; 6341 int WindowScale = 1; 6342 6343 ShuffleSourceInfo(SDValue Vec) : Vec(Vec), ShuffleVec(Vec) {} 6344 6345 bool operator ==(SDValue OtherVec) { return Vec == OtherVec; } 6346 }; 6347 6348 // First gather all vectors used as an immediate source for this BUILD_VECTOR 6349 // node. 6350 SmallVector<ShuffleSourceInfo, 2> Sources; 6351 for (unsigned i = 0; i < NumElts; ++i) { 6352 SDValue V = Op.getOperand(i); 6353 if (V.isUndef()) 6354 continue; 6355 else if (V.getOpcode() != ISD::EXTRACT_VECTOR_ELT) { 6356 // A shuffle can only come from building a vector from various 6357 // elements of other vectors. 6358 return SDValue(); 6359 } else if (!isa<ConstantSDNode>(V.getOperand(1))) { 6360 // Furthermore, shuffles require a constant mask, whereas extractelts 6361 // accept variable indices. 6362 return SDValue(); 6363 } 6364 6365 // Add this element source to the list if it's not already there. 6366 SDValue SourceVec = V.getOperand(0); 6367 auto Source = llvm::find(Sources, SourceVec); 6368 if (Source == Sources.end()) 6369 Source = Sources.insert(Sources.end(), ShuffleSourceInfo(SourceVec)); 6370 6371 // Update the minimum and maximum lane number seen. 6372 unsigned EltNo = cast<ConstantSDNode>(V.getOperand(1))->getZExtValue(); 6373 Source->MinElt = std::min(Source->MinElt, EltNo); 6374 Source->MaxElt = std::max(Source->MaxElt, EltNo); 6375 } 6376 6377 // Currently only do something sane when at most two source vectors 6378 // are involved. 6379 if (Sources.size() > 2) 6380 return SDValue(); 6381 6382 // Find out the smallest element size among result and two sources, and use 6383 // it as element size to build the shuffle_vector. 6384 EVT SmallestEltTy = VT.getVectorElementType(); 6385 for (auto &Source : Sources) { 6386 EVT SrcEltTy = Source.Vec.getValueType().getVectorElementType(); 6387 if (SrcEltTy.bitsLT(SmallestEltTy)) 6388 SmallestEltTy = SrcEltTy; 6389 } 6390 unsigned ResMultiplier = 6391 VT.getScalarSizeInBits() / SmallestEltTy.getSizeInBits(); 6392 NumElts = VT.getSizeInBits() / SmallestEltTy.getSizeInBits(); 6393 EVT ShuffleVT = EVT::getVectorVT(*DAG.getContext(), SmallestEltTy, NumElts); 6394 6395 // If the source vector is too wide or too narrow, we may nevertheless be able 6396 // to construct a compatible shuffle either by concatenating it with UNDEF or 6397 // extracting a suitable range of elements. 6398 for (auto &Src : Sources) { 6399 EVT SrcVT = Src.ShuffleVec.getValueType(); 6400 6401 if (SrcVT.getSizeInBits() == VT.getSizeInBits()) 6402 continue; 6403 6404 // This stage of the search produces a source with the same element type as 6405 // the original, but with a total width matching the BUILD_VECTOR output. 6406 EVT EltVT = SrcVT.getVectorElementType(); 6407 unsigned NumSrcElts = VT.getSizeInBits() / EltVT.getSizeInBits(); 6408 EVT DestVT = EVT::getVectorVT(*DAG.getContext(), EltVT, NumSrcElts); 6409 6410 if (SrcVT.getSizeInBits() < VT.getSizeInBits()) { 6411 if (2 * SrcVT.getSizeInBits() != VT.getSizeInBits()) 6412 return SDValue(); 6413 // We can pad out the smaller vector for free, so if it's part of a 6414 // shuffle... 6415 Src.ShuffleVec = 6416 DAG.getNode(ISD::CONCAT_VECTORS, dl, DestVT, Src.ShuffleVec, 6417 DAG.getUNDEF(Src.ShuffleVec.getValueType())); 6418 continue; 6419 } 6420 6421 if (SrcVT.getSizeInBits() != 2 * VT.getSizeInBits()) 6422 return SDValue(); 6423 6424 if (Src.MaxElt - Src.MinElt >= NumSrcElts) { 6425 // Span too large for a VEXT to cope 6426 return SDValue(); 6427 } 6428 6429 if (Src.MinElt >= NumSrcElts) { 6430 // The extraction can just take the second half 6431 Src.ShuffleVec = 6432 DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DestVT, Src.ShuffleVec, 6433 DAG.getConstant(NumSrcElts, dl, MVT::i32)); 6434 Src.WindowBase = -NumSrcElts; 6435 } else if (Src.MaxElt < NumSrcElts) { 6436 // The extraction can just take the first half 6437 Src.ShuffleVec = 6438 DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DestVT, Src.ShuffleVec, 6439 DAG.getConstant(0, dl, MVT::i32)); 6440 } else { 6441 // An actual VEXT is needed 6442 SDValue VEXTSrc1 = 6443 DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DestVT, Src.ShuffleVec, 6444 DAG.getConstant(0, dl, MVT::i32)); 6445 SDValue VEXTSrc2 = 6446 DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DestVT, Src.ShuffleVec, 6447 DAG.getConstant(NumSrcElts, dl, MVT::i32)); 6448 6449 Src.ShuffleVec = DAG.getNode(ARMISD::VEXT, dl, DestVT, VEXTSrc1, 6450 VEXTSrc2, 6451 DAG.getConstant(Src.MinElt, dl, MVT::i32)); 6452 Src.WindowBase = -Src.MinElt; 6453 } 6454 } 6455 6456 // Another possible incompatibility occurs from the vector element types. We 6457 // can fix this by bitcasting the source vectors to the same type we intend 6458 // for the shuffle. 6459 for (auto &Src : Sources) { 6460 EVT SrcEltTy = Src.ShuffleVec.getValueType().getVectorElementType(); 6461 if (SrcEltTy == SmallestEltTy) 6462 continue; 6463 assert(ShuffleVT.getVectorElementType() == SmallestEltTy); 6464 Src.ShuffleVec = DAG.getNode(ISD::BITCAST, dl, ShuffleVT, Src.ShuffleVec); 6465 Src.WindowScale = SrcEltTy.getSizeInBits() / SmallestEltTy.getSizeInBits(); 6466 Src.WindowBase *= Src.WindowScale; 6467 } 6468 6469 // Final sanity check before we try to actually produce a shuffle. 6470 DEBUG( 6471 for (auto Src : Sources) 6472 assert(Src.ShuffleVec.getValueType() == ShuffleVT); 6473 ); 6474 6475 // The stars all align, our next step is to produce the mask for the shuffle. 6476 SmallVector<int, 8> Mask(ShuffleVT.getVectorNumElements(), -1); 6477 int BitsPerShuffleLane = ShuffleVT.getScalarSizeInBits(); 6478 for (unsigned i = 0; i < VT.getVectorNumElements(); ++i) { 6479 SDValue Entry = Op.getOperand(i); 6480 if (Entry.isUndef()) 6481 continue; 6482 6483 auto Src = llvm::find(Sources, Entry.getOperand(0)); 6484 int EltNo = cast<ConstantSDNode>(Entry.getOperand(1))->getSExtValue(); 6485 6486 // EXTRACT_VECTOR_ELT performs an implicit any_ext; BUILD_VECTOR an implicit 6487 // trunc. So only std::min(SrcBits, DestBits) actually get defined in this 6488 // segment. 6489 EVT OrigEltTy = Entry.getOperand(0).getValueType().getVectorElementType(); 6490 int BitsDefined = std::min(OrigEltTy.getSizeInBits(), 6491 VT.getScalarSizeInBits()); 6492 int LanesDefined = BitsDefined / BitsPerShuffleLane; 6493 6494 // This source is expected to fill ResMultiplier lanes of the final shuffle, 6495 // starting at the appropriate offset. 6496 int *LaneMask = &Mask[i * ResMultiplier]; 6497 6498 int ExtractBase = EltNo * Src->WindowScale + Src->WindowBase; 6499 ExtractBase += NumElts * (Src - Sources.begin()); 6500 for (int j = 0; j < LanesDefined; ++j) 6501 LaneMask[j] = ExtractBase + j; 6502 } 6503 6504 // Final check before we try to produce nonsense... 6505 if (!isShuffleMaskLegal(Mask, ShuffleVT)) 6506 return SDValue(); 6507 6508 // We can't handle more than two sources. This should have already 6509 // been checked before this point. 6510 assert(Sources.size() <= 2 && "Too many sources!"); 6511 6512 SDValue ShuffleOps[] = { DAG.getUNDEF(ShuffleVT), DAG.getUNDEF(ShuffleVT) }; 6513 for (unsigned i = 0; i < Sources.size(); ++i) 6514 ShuffleOps[i] = Sources[i].ShuffleVec; 6515 6516 SDValue Shuffle = DAG.getVectorShuffle(ShuffleVT, dl, ShuffleOps[0], 6517 ShuffleOps[1], Mask); 6518 return DAG.getNode(ISD::BITCAST, dl, VT, Shuffle); 6519 } 6520 6521 /// isShuffleMaskLegal - Targets can use this to indicate that they only 6522 /// support *some* VECTOR_SHUFFLE operations, those with specific masks. 6523 /// By default, if a target supports the VECTOR_SHUFFLE node, all mask values 6524 /// are assumed to be legal. 6525 bool ARMTargetLowering::isShuffleMaskLegal(ArrayRef<int> M, EVT VT) const { 6526 if (VT.getVectorNumElements() == 4 && 6527 (VT.is128BitVector() || VT.is64BitVector())) { 6528 unsigned PFIndexes[4]; 6529 for (unsigned i = 0; i != 4; ++i) { 6530 if (M[i] < 0) 6531 PFIndexes[i] = 8; 6532 else 6533 PFIndexes[i] = M[i]; 6534 } 6535 6536 // Compute the index in the perfect shuffle table. 6537 unsigned PFTableIndex = 6538 PFIndexes[0]*9*9*9+PFIndexes[1]*9*9+PFIndexes[2]*9+PFIndexes[3]; 6539 unsigned PFEntry = PerfectShuffleTable[PFTableIndex]; 6540 unsigned Cost = (PFEntry >> 30); 6541 6542 if (Cost <= 4) 6543 return true; 6544 } 6545 6546 bool ReverseVEXT, isV_UNDEF; 6547 unsigned Imm, WhichResult; 6548 6549 unsigned EltSize = VT.getScalarSizeInBits(); 6550 return (EltSize >= 32 || 6551 ShuffleVectorSDNode::isSplatMask(&M[0], VT) || 6552 isVREVMask(M, VT, 64) || 6553 isVREVMask(M, VT, 32) || 6554 isVREVMask(M, VT, 16) || 6555 isVEXTMask(M, VT, ReverseVEXT, Imm) || 6556 isVTBLMask(M, VT) || 6557 isNEONTwoResultShuffleMask(M, VT, WhichResult, isV_UNDEF) || 6558 ((VT == MVT::v8i16 || VT == MVT::v16i8) && isReverseMask(M, VT))); 6559 } 6560 6561 /// GeneratePerfectShuffle - Given an entry in the perfect-shuffle table, emit 6562 /// the specified operations to build the shuffle. 6563 static SDValue GeneratePerfectShuffle(unsigned PFEntry, SDValue LHS, 6564 SDValue RHS, SelectionDAG &DAG, 6565 const SDLoc &dl) { 6566 unsigned OpNum = (PFEntry >> 26) & 0x0F; 6567 unsigned LHSID = (PFEntry >> 13) & ((1 << 13)-1); 6568 unsigned RHSID = (PFEntry >> 0) & ((1 << 13)-1); 6569 6570 enum { 6571 OP_COPY = 0, // Copy, used for things like <u,u,u,3> to say it is <0,1,2,3> 6572 OP_VREV, 6573 OP_VDUP0, 6574 OP_VDUP1, 6575 OP_VDUP2, 6576 OP_VDUP3, 6577 OP_VEXT1, 6578 OP_VEXT2, 6579 OP_VEXT3, 6580 OP_VUZPL, // VUZP, left result 6581 OP_VUZPR, // VUZP, right result 6582 OP_VZIPL, // VZIP, left result 6583 OP_VZIPR, // VZIP, right result 6584 OP_VTRNL, // VTRN, left result 6585 OP_VTRNR // VTRN, right result 6586 }; 6587 6588 if (OpNum == OP_COPY) { 6589 if (LHSID == (1*9+2)*9+3) return LHS; 6590 assert(LHSID == ((4*9+5)*9+6)*9+7 && "Illegal OP_COPY!"); 6591 return RHS; 6592 } 6593 6594 SDValue OpLHS, OpRHS; 6595 OpLHS = GeneratePerfectShuffle(PerfectShuffleTable[LHSID], LHS, RHS, DAG, dl); 6596 OpRHS = GeneratePerfectShuffle(PerfectShuffleTable[RHSID], LHS, RHS, DAG, dl); 6597 EVT VT = OpLHS.getValueType(); 6598 6599 switch (OpNum) { 6600 default: llvm_unreachable("Unknown shuffle opcode!"); 6601 case OP_VREV: 6602 // VREV divides the vector in half and swaps within the half. 6603 if (VT.getVectorElementType() == MVT::i32 || 6604 VT.getVectorElementType() == MVT::f32) 6605 return DAG.getNode(ARMISD::VREV64, dl, VT, OpLHS); 6606 // vrev <4 x i16> -> VREV32 6607 if (VT.getVectorElementType() == MVT::i16) 6608 return DAG.getNode(ARMISD::VREV32, dl, VT, OpLHS); 6609 // vrev <4 x i8> -> VREV16 6610 assert(VT.getVectorElementType() == MVT::i8); 6611 return DAG.getNode(ARMISD::VREV16, dl, VT, OpLHS); 6612 case OP_VDUP0: 6613 case OP_VDUP1: 6614 case OP_VDUP2: 6615 case OP_VDUP3: 6616 return DAG.getNode(ARMISD::VDUPLANE, dl, VT, 6617 OpLHS, DAG.getConstant(OpNum-OP_VDUP0, dl, MVT::i32)); 6618 case OP_VEXT1: 6619 case OP_VEXT2: 6620 case OP_VEXT3: 6621 return DAG.getNode(ARMISD::VEXT, dl, VT, 6622 OpLHS, OpRHS, 6623 DAG.getConstant(OpNum - OP_VEXT1 + 1, dl, MVT::i32)); 6624 case OP_VUZPL: 6625 case OP_VUZPR: 6626 return DAG.getNode(ARMISD::VUZP, dl, DAG.getVTList(VT, VT), 6627 OpLHS, OpRHS).getValue(OpNum-OP_VUZPL); 6628 case OP_VZIPL: 6629 case OP_VZIPR: 6630 return DAG.getNode(ARMISD::VZIP, dl, DAG.getVTList(VT, VT), 6631 OpLHS, OpRHS).getValue(OpNum-OP_VZIPL); 6632 case OP_VTRNL: 6633 case OP_VTRNR: 6634 return DAG.getNode(ARMISD::VTRN, dl, DAG.getVTList(VT, VT), 6635 OpLHS, OpRHS).getValue(OpNum-OP_VTRNL); 6636 } 6637 } 6638 6639 static SDValue LowerVECTOR_SHUFFLEv8i8(SDValue Op, 6640 ArrayRef<int> ShuffleMask, 6641 SelectionDAG &DAG) { 6642 // Check to see if we can use the VTBL instruction. 6643 SDValue V1 = Op.getOperand(0); 6644 SDValue V2 = Op.getOperand(1); 6645 SDLoc DL(Op); 6646 6647 SmallVector<SDValue, 8> VTBLMask; 6648 for (ArrayRef<int>::iterator 6649 I = ShuffleMask.begin(), E = ShuffleMask.end(); I != E; ++I) 6650 VTBLMask.push_back(DAG.getConstant(*I, DL, MVT::i32)); 6651 6652 if (V2.getNode()->isUndef()) 6653 return DAG.getNode(ARMISD::VTBL1, DL, MVT::v8i8, V1, 6654 DAG.getBuildVector(MVT::v8i8, DL, VTBLMask)); 6655 6656 return DAG.getNode(ARMISD::VTBL2, DL, MVT::v8i8, V1, V2, 6657 DAG.getBuildVector(MVT::v8i8, DL, VTBLMask)); 6658 } 6659 6660 static SDValue LowerReverse_VECTOR_SHUFFLEv16i8_v8i16(SDValue Op, 6661 SelectionDAG &DAG) { 6662 SDLoc DL(Op); 6663 SDValue OpLHS = Op.getOperand(0); 6664 EVT VT = OpLHS.getValueType(); 6665 6666 assert((VT == MVT::v8i16 || VT == MVT::v16i8) && 6667 "Expect an v8i16/v16i8 type"); 6668 OpLHS = DAG.getNode(ARMISD::VREV64, DL, VT, OpLHS); 6669 // For a v16i8 type: After the VREV, we have got <8, ...15, 8, ..., 0>. Now, 6670 // extract the first 8 bytes into the top double word and the last 8 bytes 6671 // into the bottom double word. The v8i16 case is similar. 6672 unsigned ExtractNum = (VT == MVT::v16i8) ? 8 : 4; 6673 return DAG.getNode(ARMISD::VEXT, DL, VT, OpLHS, OpLHS, 6674 DAG.getConstant(ExtractNum, DL, MVT::i32)); 6675 } 6676 6677 static SDValue LowerVECTOR_SHUFFLE(SDValue Op, SelectionDAG &DAG) { 6678 SDValue V1 = Op.getOperand(0); 6679 SDValue V2 = Op.getOperand(1); 6680 SDLoc dl(Op); 6681 EVT VT = Op.getValueType(); 6682 ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(Op.getNode()); 6683 6684 // Convert shuffles that are directly supported on NEON to target-specific 6685 // DAG nodes, instead of keeping them as shuffles and matching them again 6686 // during code selection. This is more efficient and avoids the possibility 6687 // of inconsistencies between legalization and selection. 6688 // FIXME: floating-point vectors should be canonicalized to integer vectors 6689 // of the same time so that they get CSEd properly. 6690 ArrayRef<int> ShuffleMask = SVN->getMask(); 6691 6692 unsigned EltSize = VT.getScalarSizeInBits(); 6693 if (EltSize <= 32) { 6694 if (SVN->isSplat()) { 6695 int Lane = SVN->getSplatIndex(); 6696 // If this is undef splat, generate it via "just" vdup, if possible. 6697 if (Lane == -1) Lane = 0; 6698 6699 // Test if V1 is a SCALAR_TO_VECTOR. 6700 if (Lane == 0 && V1.getOpcode() == ISD::SCALAR_TO_VECTOR) { 6701 return DAG.getNode(ARMISD::VDUP, dl, VT, V1.getOperand(0)); 6702 } 6703 // Test if V1 is a BUILD_VECTOR which is equivalent to a SCALAR_TO_VECTOR 6704 // (and probably will turn into a SCALAR_TO_VECTOR once legalization 6705 // reaches it). 6706 if (Lane == 0 && V1.getOpcode() == ISD::BUILD_VECTOR && 6707 !isa<ConstantSDNode>(V1.getOperand(0))) { 6708 bool IsScalarToVector = true; 6709 for (unsigned i = 1, e = V1.getNumOperands(); i != e; ++i) 6710 if (!V1.getOperand(i).isUndef()) { 6711 IsScalarToVector = false; 6712 break; 6713 } 6714 if (IsScalarToVector) 6715 return DAG.getNode(ARMISD::VDUP, dl, VT, V1.getOperand(0)); 6716 } 6717 return DAG.getNode(ARMISD::VDUPLANE, dl, VT, V1, 6718 DAG.getConstant(Lane, dl, MVT::i32)); 6719 } 6720 6721 bool ReverseVEXT; 6722 unsigned Imm; 6723 if (isVEXTMask(ShuffleMask, VT, ReverseVEXT, Imm)) { 6724 if (ReverseVEXT) 6725 std::swap(V1, V2); 6726 return DAG.getNode(ARMISD::VEXT, dl, VT, V1, V2, 6727 DAG.getConstant(Imm, dl, MVT::i32)); 6728 } 6729 6730 if (isVREVMask(ShuffleMask, VT, 64)) 6731 return DAG.getNode(ARMISD::VREV64, dl, VT, V1); 6732 if (isVREVMask(ShuffleMask, VT, 32)) 6733 return DAG.getNode(ARMISD::VREV32, dl, VT, V1); 6734 if (isVREVMask(ShuffleMask, VT, 16)) 6735 return DAG.getNode(ARMISD::VREV16, dl, VT, V1); 6736 6737 if (V2->isUndef() && isSingletonVEXTMask(ShuffleMask, VT, Imm)) { 6738 return DAG.getNode(ARMISD::VEXT, dl, VT, V1, V1, 6739 DAG.getConstant(Imm, dl, MVT::i32)); 6740 } 6741 6742 // Check for Neon shuffles that modify both input vectors in place. 6743 // If both results are used, i.e., if there are two shuffles with the same 6744 // source operands and with masks corresponding to both results of one of 6745 // these operations, DAG memoization will ensure that a single node is 6746 // used for both shuffles. 6747 unsigned WhichResult; 6748 bool isV_UNDEF; 6749 if (unsigned ShuffleOpc = isNEONTwoResultShuffleMask( 6750 ShuffleMask, VT, WhichResult, isV_UNDEF)) { 6751 if (isV_UNDEF) 6752 V2 = V1; 6753 return DAG.getNode(ShuffleOpc, dl, DAG.getVTList(VT, VT), V1, V2) 6754 .getValue(WhichResult); 6755 } 6756 6757 // Also check for these shuffles through CONCAT_VECTORS: we canonicalize 6758 // shuffles that produce a result larger than their operands with: 6759 // shuffle(concat(v1, undef), concat(v2, undef)) 6760 // -> 6761 // shuffle(concat(v1, v2), undef) 6762 // because we can access quad vectors (see PerformVECTOR_SHUFFLECombine). 6763 // 6764 // This is useful in the general case, but there are special cases where 6765 // native shuffles produce larger results: the two-result ops. 6766 // 6767 // Look through the concat when lowering them: 6768 // shuffle(concat(v1, v2), undef) 6769 // -> 6770 // concat(VZIP(v1, v2):0, :1) 6771 // 6772 if (V1->getOpcode() == ISD::CONCAT_VECTORS && V2->isUndef()) { 6773 SDValue SubV1 = V1->getOperand(0); 6774 SDValue SubV2 = V1->getOperand(1); 6775 EVT SubVT = SubV1.getValueType(); 6776 6777 // We expect these to have been canonicalized to -1. 6778 assert(llvm::all_of(ShuffleMask, [&](int i) { 6779 return i < (int)VT.getVectorNumElements(); 6780 }) && "Unexpected shuffle index into UNDEF operand!"); 6781 6782 if (unsigned ShuffleOpc = isNEONTwoResultShuffleMask( 6783 ShuffleMask, SubVT, WhichResult, isV_UNDEF)) { 6784 if (isV_UNDEF) 6785 SubV2 = SubV1; 6786 assert((WhichResult == 0) && 6787 "In-place shuffle of concat can only have one result!"); 6788 SDValue Res = DAG.getNode(ShuffleOpc, dl, DAG.getVTList(SubVT, SubVT), 6789 SubV1, SubV2); 6790 return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, Res.getValue(0), 6791 Res.getValue(1)); 6792 } 6793 } 6794 } 6795 6796 // If the shuffle is not directly supported and it has 4 elements, use 6797 // the PerfectShuffle-generated table to synthesize it from other shuffles. 6798 unsigned NumElts = VT.getVectorNumElements(); 6799 if (NumElts == 4) { 6800 unsigned PFIndexes[4]; 6801 for (unsigned i = 0; i != 4; ++i) { 6802 if (ShuffleMask[i] < 0) 6803 PFIndexes[i] = 8; 6804 else 6805 PFIndexes[i] = ShuffleMask[i]; 6806 } 6807 6808 // Compute the index in the perfect shuffle table. 6809 unsigned PFTableIndex = 6810 PFIndexes[0]*9*9*9+PFIndexes[1]*9*9+PFIndexes[2]*9+PFIndexes[3]; 6811 unsigned PFEntry = PerfectShuffleTable[PFTableIndex]; 6812 unsigned Cost = (PFEntry >> 30); 6813 6814 if (Cost <= 4) 6815 return GeneratePerfectShuffle(PFEntry, V1, V2, DAG, dl); 6816 } 6817 6818 // Implement shuffles with 32- or 64-bit elements as ARMISD::BUILD_VECTORs. 6819 if (EltSize >= 32) { 6820 // Do the expansion with floating-point types, since that is what the VFP 6821 // registers are defined to use, and since i64 is not legal. 6822 EVT EltVT = EVT::getFloatingPointVT(EltSize); 6823 EVT VecVT = EVT::getVectorVT(*DAG.getContext(), EltVT, NumElts); 6824 V1 = DAG.getNode(ISD::BITCAST, dl, VecVT, V1); 6825 V2 = DAG.getNode(ISD::BITCAST, dl, VecVT, V2); 6826 SmallVector<SDValue, 8> Ops; 6827 for (unsigned i = 0; i < NumElts; ++i) { 6828 if (ShuffleMask[i] < 0) 6829 Ops.push_back(DAG.getUNDEF(EltVT)); 6830 else 6831 Ops.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, EltVT, 6832 ShuffleMask[i] < (int)NumElts ? V1 : V2, 6833 DAG.getConstant(ShuffleMask[i] & (NumElts-1), 6834 dl, MVT::i32))); 6835 } 6836 SDValue Val = DAG.getNode(ARMISD::BUILD_VECTOR, dl, VecVT, Ops); 6837 return DAG.getNode(ISD::BITCAST, dl, VT, Val); 6838 } 6839 6840 if ((VT == MVT::v8i16 || VT == MVT::v16i8) && isReverseMask(ShuffleMask, VT)) 6841 return LowerReverse_VECTOR_SHUFFLEv16i8_v8i16(Op, DAG); 6842 6843 if (VT == MVT::v8i8) 6844 if (SDValue NewOp = LowerVECTOR_SHUFFLEv8i8(Op, ShuffleMask, DAG)) 6845 return NewOp; 6846 6847 return SDValue(); 6848 } 6849 6850 static SDValue LowerINSERT_VECTOR_ELT(SDValue Op, SelectionDAG &DAG) { 6851 // INSERT_VECTOR_ELT is legal only for immediate indexes. 6852 SDValue Lane = Op.getOperand(2); 6853 if (!isa<ConstantSDNode>(Lane)) 6854 return SDValue(); 6855 6856 return Op; 6857 } 6858 6859 static SDValue LowerEXTRACT_VECTOR_ELT(SDValue Op, SelectionDAG &DAG) { 6860 // EXTRACT_VECTOR_ELT is legal only for immediate indexes. 6861 SDValue Lane = Op.getOperand(1); 6862 if (!isa<ConstantSDNode>(Lane)) 6863 return SDValue(); 6864 6865 SDValue Vec = Op.getOperand(0); 6866 if (Op.getValueType() == MVT::i32 && Vec.getScalarValueSizeInBits() < 32) { 6867 SDLoc dl(Op); 6868 return DAG.getNode(ARMISD::VGETLANEu, dl, MVT::i32, Vec, Lane); 6869 } 6870 6871 return Op; 6872 } 6873 6874 static SDValue LowerCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG) { 6875 // The only time a CONCAT_VECTORS operation can have legal types is when 6876 // two 64-bit vectors are concatenated to a 128-bit vector. 6877 assert(Op.getValueType().is128BitVector() && Op.getNumOperands() == 2 && 6878 "unexpected CONCAT_VECTORS"); 6879 SDLoc dl(Op); 6880 SDValue Val = DAG.getUNDEF(MVT::v2f64); 6881 SDValue Op0 = Op.getOperand(0); 6882 SDValue Op1 = Op.getOperand(1); 6883 if (!Op0.isUndef()) 6884 Val = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Val, 6885 DAG.getNode(ISD::BITCAST, dl, MVT::f64, Op0), 6886 DAG.getIntPtrConstant(0, dl)); 6887 if (!Op1.isUndef()) 6888 Val = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Val, 6889 DAG.getNode(ISD::BITCAST, dl, MVT::f64, Op1), 6890 DAG.getIntPtrConstant(1, dl)); 6891 return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Val); 6892 } 6893 6894 /// isExtendedBUILD_VECTOR - Check if N is a constant BUILD_VECTOR where each 6895 /// element has been zero/sign-extended, depending on the isSigned parameter, 6896 /// from an integer type half its size. 6897 static bool isExtendedBUILD_VECTOR(SDNode *N, SelectionDAG &DAG, 6898 bool isSigned) { 6899 // A v2i64 BUILD_VECTOR will have been legalized to a BITCAST from v4i32. 6900 EVT VT = N->getValueType(0); 6901 if (VT == MVT::v2i64 && N->getOpcode() == ISD::BITCAST) { 6902 SDNode *BVN = N->getOperand(0).getNode(); 6903 if (BVN->getValueType(0) != MVT::v4i32 || 6904 BVN->getOpcode() != ISD::BUILD_VECTOR) 6905 return false; 6906 unsigned LoElt = DAG.getDataLayout().isBigEndian() ? 1 : 0; 6907 unsigned HiElt = 1 - LoElt; 6908 ConstantSDNode *Lo0 = dyn_cast<ConstantSDNode>(BVN->getOperand(LoElt)); 6909 ConstantSDNode *Hi0 = dyn_cast<ConstantSDNode>(BVN->getOperand(HiElt)); 6910 ConstantSDNode *Lo1 = dyn_cast<ConstantSDNode>(BVN->getOperand(LoElt+2)); 6911 ConstantSDNode *Hi1 = dyn_cast<ConstantSDNode>(BVN->getOperand(HiElt+2)); 6912 if (!Lo0 || !Hi0 || !Lo1 || !Hi1) 6913 return false; 6914 if (isSigned) { 6915 if (Hi0->getSExtValue() == Lo0->getSExtValue() >> 32 && 6916 Hi1->getSExtValue() == Lo1->getSExtValue() >> 32) 6917 return true; 6918 } else { 6919 if (Hi0->isNullValue() && Hi1->isNullValue()) 6920 return true; 6921 } 6922 return false; 6923 } 6924 6925 if (N->getOpcode() != ISD::BUILD_VECTOR) 6926 return false; 6927 6928 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) { 6929 SDNode *Elt = N->getOperand(i).getNode(); 6930 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Elt)) { 6931 unsigned EltSize = VT.getScalarSizeInBits(); 6932 unsigned HalfSize = EltSize / 2; 6933 if (isSigned) { 6934 if (!isIntN(HalfSize, C->getSExtValue())) 6935 return false; 6936 } else { 6937 if (!isUIntN(HalfSize, C->getZExtValue())) 6938 return false; 6939 } 6940 continue; 6941 } 6942 return false; 6943 } 6944 6945 return true; 6946 } 6947 6948 /// isSignExtended - Check if a node is a vector value that is sign-extended 6949 /// or a constant BUILD_VECTOR with sign-extended elements. 6950 static bool isSignExtended(SDNode *N, SelectionDAG &DAG) { 6951 if (N->getOpcode() == ISD::SIGN_EXTEND || ISD::isSEXTLoad(N)) 6952 return true; 6953 if (isExtendedBUILD_VECTOR(N, DAG, true)) 6954 return true; 6955 return false; 6956 } 6957 6958 /// isZeroExtended - Check if a node is a vector value that is zero-extended 6959 /// or a constant BUILD_VECTOR with zero-extended elements. 6960 static bool isZeroExtended(SDNode *N, SelectionDAG &DAG) { 6961 if (N->getOpcode() == ISD::ZERO_EXTEND || ISD::isZEXTLoad(N)) 6962 return true; 6963 if (isExtendedBUILD_VECTOR(N, DAG, false)) 6964 return true; 6965 return false; 6966 } 6967 6968 static EVT getExtensionTo64Bits(const EVT &OrigVT) { 6969 if (OrigVT.getSizeInBits() >= 64) 6970 return OrigVT; 6971 6972 assert(OrigVT.isSimple() && "Expecting a simple value type"); 6973 6974 MVT::SimpleValueType OrigSimpleTy = OrigVT.getSimpleVT().SimpleTy; 6975 switch (OrigSimpleTy) { 6976 default: llvm_unreachable("Unexpected Vector Type"); 6977 case MVT::v2i8: 6978 case MVT::v2i16: 6979 return MVT::v2i32; 6980 case MVT::v4i8: 6981 return MVT::v4i16; 6982 } 6983 } 6984 6985 /// AddRequiredExtensionForVMULL - Add a sign/zero extension to extend the total 6986 /// value size to 64 bits. We need a 64-bit D register as an operand to VMULL. 6987 /// We insert the required extension here to get the vector to fill a D register. 6988 static SDValue AddRequiredExtensionForVMULL(SDValue N, SelectionDAG &DAG, 6989 const EVT &OrigTy, 6990 const EVT &ExtTy, 6991 unsigned ExtOpcode) { 6992 // The vector originally had a size of OrigTy. It was then extended to ExtTy. 6993 // We expect the ExtTy to be 128-bits total. If the OrigTy is less than 6994 // 64-bits we need to insert a new extension so that it will be 64-bits. 6995 assert(ExtTy.is128BitVector() && "Unexpected extension size"); 6996 if (OrigTy.getSizeInBits() >= 64) 6997 return N; 6998 6999 // Must extend size to at least 64 bits to be used as an operand for VMULL. 7000 EVT NewVT = getExtensionTo64Bits(OrigTy); 7001 7002 return DAG.getNode(ExtOpcode, SDLoc(N), NewVT, N); 7003 } 7004 7005 /// SkipLoadExtensionForVMULL - return a load of the original vector size that 7006 /// does not do any sign/zero extension. If the original vector is less 7007 /// than 64 bits, an appropriate extension will be added after the load to 7008 /// reach a total size of 64 bits. We have to add the extension separately 7009 /// because ARM does not have a sign/zero extending load for vectors. 7010 static SDValue SkipLoadExtensionForVMULL(LoadSDNode *LD, SelectionDAG& DAG) { 7011 EVT ExtendedTy = getExtensionTo64Bits(LD->getMemoryVT()); 7012 7013 // The load already has the right type. 7014 if (ExtendedTy == LD->getMemoryVT()) 7015 return DAG.getLoad(LD->getMemoryVT(), SDLoc(LD), LD->getChain(), 7016 LD->getBasePtr(), LD->getPointerInfo(), 7017 LD->getAlignment(), LD->getMemOperand()->getFlags()); 7018 7019 // We need to create a zextload/sextload. We cannot just create a load 7020 // followed by a zext/zext node because LowerMUL is also run during normal 7021 // operation legalization where we can't create illegal types. 7022 return DAG.getExtLoad(LD->getExtensionType(), SDLoc(LD), ExtendedTy, 7023 LD->getChain(), LD->getBasePtr(), LD->getPointerInfo(), 7024 LD->getMemoryVT(), LD->getAlignment(), 7025 LD->getMemOperand()->getFlags()); 7026 } 7027 7028 /// SkipExtensionForVMULL - For a node that is a SIGN_EXTEND, ZERO_EXTEND, 7029 /// extending load, or BUILD_VECTOR with extended elements, return the 7030 /// unextended value. The unextended vector should be 64 bits so that it can 7031 /// be used as an operand to a VMULL instruction. If the original vector size 7032 /// before extension is less than 64 bits we add a an extension to resize 7033 /// the vector to 64 bits. 7034 static SDValue SkipExtensionForVMULL(SDNode *N, SelectionDAG &DAG) { 7035 if (N->getOpcode() == ISD::SIGN_EXTEND || N->getOpcode() == ISD::ZERO_EXTEND) 7036 return AddRequiredExtensionForVMULL(N->getOperand(0), DAG, 7037 N->getOperand(0)->getValueType(0), 7038 N->getValueType(0), 7039 N->getOpcode()); 7040 7041 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) { 7042 assert((ISD::isSEXTLoad(LD) || ISD::isZEXTLoad(LD)) && 7043 "Expected extending load"); 7044 7045 SDValue newLoad = SkipLoadExtensionForVMULL(LD, DAG); 7046 DAG.ReplaceAllUsesOfValueWith(SDValue(LD, 1), newLoad.getValue(1)); 7047 unsigned Opcode = ISD::isSEXTLoad(LD) ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND; 7048 SDValue extLoad = 7049 DAG.getNode(Opcode, SDLoc(newLoad), LD->getValueType(0), newLoad); 7050 DAG.ReplaceAllUsesOfValueWith(SDValue(LD, 0), extLoad); 7051 7052 return newLoad; 7053 } 7054 7055 // Otherwise, the value must be a BUILD_VECTOR. For v2i64, it will 7056 // have been legalized as a BITCAST from v4i32. 7057 if (N->getOpcode() == ISD::BITCAST) { 7058 SDNode *BVN = N->getOperand(0).getNode(); 7059 assert(BVN->getOpcode() == ISD::BUILD_VECTOR && 7060 BVN->getValueType(0) == MVT::v4i32 && "expected v4i32 BUILD_VECTOR"); 7061 unsigned LowElt = DAG.getDataLayout().isBigEndian() ? 1 : 0; 7062 return DAG.getBuildVector( 7063 MVT::v2i32, SDLoc(N), 7064 {BVN->getOperand(LowElt), BVN->getOperand(LowElt + 2)}); 7065 } 7066 // Construct a new BUILD_VECTOR with elements truncated to half the size. 7067 assert(N->getOpcode() == ISD::BUILD_VECTOR && "expected BUILD_VECTOR"); 7068 EVT VT = N->getValueType(0); 7069 unsigned EltSize = VT.getScalarSizeInBits() / 2; 7070 unsigned NumElts = VT.getVectorNumElements(); 7071 MVT TruncVT = MVT::getIntegerVT(EltSize); 7072 SmallVector<SDValue, 8> Ops; 7073 SDLoc dl(N); 7074 for (unsigned i = 0; i != NumElts; ++i) { 7075 ConstantSDNode *C = cast<ConstantSDNode>(N->getOperand(i)); 7076 const APInt &CInt = C->getAPIntValue(); 7077 // Element types smaller than 32 bits are not legal, so use i32 elements. 7078 // The values are implicitly truncated so sext vs. zext doesn't matter. 7079 Ops.push_back(DAG.getConstant(CInt.zextOrTrunc(32), dl, MVT::i32)); 7080 } 7081 return DAG.getBuildVector(MVT::getVectorVT(TruncVT, NumElts), dl, Ops); 7082 } 7083 7084 static bool isAddSubSExt(SDNode *N, SelectionDAG &DAG) { 7085 unsigned Opcode = N->getOpcode(); 7086 if (Opcode == ISD::ADD || Opcode == ISD::SUB) { 7087 SDNode *N0 = N->getOperand(0).getNode(); 7088 SDNode *N1 = N->getOperand(1).getNode(); 7089 return N0->hasOneUse() && N1->hasOneUse() && 7090 isSignExtended(N0, DAG) && isSignExtended(N1, DAG); 7091 } 7092 return false; 7093 } 7094 7095 static bool isAddSubZExt(SDNode *N, SelectionDAG &DAG) { 7096 unsigned Opcode = N->getOpcode(); 7097 if (Opcode == ISD::ADD || Opcode == ISD::SUB) { 7098 SDNode *N0 = N->getOperand(0).getNode(); 7099 SDNode *N1 = N->getOperand(1).getNode(); 7100 return N0->hasOneUse() && N1->hasOneUse() && 7101 isZeroExtended(N0, DAG) && isZeroExtended(N1, DAG); 7102 } 7103 return false; 7104 } 7105 7106 static SDValue LowerMUL(SDValue Op, SelectionDAG &DAG) { 7107 // Multiplications are only custom-lowered for 128-bit vectors so that 7108 // VMULL can be detected. Otherwise v2i64 multiplications are not legal. 7109 EVT VT = Op.getValueType(); 7110 assert(VT.is128BitVector() && VT.isInteger() && 7111 "unexpected type for custom-lowering ISD::MUL"); 7112 SDNode *N0 = Op.getOperand(0).getNode(); 7113 SDNode *N1 = Op.getOperand(1).getNode(); 7114 unsigned NewOpc = 0; 7115 bool isMLA = false; 7116 bool isN0SExt = isSignExtended(N0, DAG); 7117 bool isN1SExt = isSignExtended(N1, DAG); 7118 if (isN0SExt && isN1SExt) 7119 NewOpc = ARMISD::VMULLs; 7120 else { 7121 bool isN0ZExt = isZeroExtended(N0, DAG); 7122 bool isN1ZExt = isZeroExtended(N1, DAG); 7123 if (isN0ZExt && isN1ZExt) 7124 NewOpc = ARMISD::VMULLu; 7125 else if (isN1SExt || isN1ZExt) { 7126 // Look for (s/zext A + s/zext B) * (s/zext C). We want to turn these 7127 // into (s/zext A * s/zext C) + (s/zext B * s/zext C) 7128 if (isN1SExt && isAddSubSExt(N0, DAG)) { 7129 NewOpc = ARMISD::VMULLs; 7130 isMLA = true; 7131 } else if (isN1ZExt && isAddSubZExt(N0, DAG)) { 7132 NewOpc = ARMISD::VMULLu; 7133 isMLA = true; 7134 } else if (isN0ZExt && isAddSubZExt(N1, DAG)) { 7135 std::swap(N0, N1); 7136 NewOpc = ARMISD::VMULLu; 7137 isMLA = true; 7138 } 7139 } 7140 7141 if (!NewOpc) { 7142 if (VT == MVT::v2i64) 7143 // Fall through to expand this. It is not legal. 7144 return SDValue(); 7145 else 7146 // Other vector multiplications are legal. 7147 return Op; 7148 } 7149 } 7150 7151 // Legalize to a VMULL instruction. 7152 SDLoc DL(Op); 7153 SDValue Op0; 7154 SDValue Op1 = SkipExtensionForVMULL(N1, DAG); 7155 if (!isMLA) { 7156 Op0 = SkipExtensionForVMULL(N0, DAG); 7157 assert(Op0.getValueType().is64BitVector() && 7158 Op1.getValueType().is64BitVector() && 7159 "unexpected types for extended operands to VMULL"); 7160 return DAG.getNode(NewOpc, DL, VT, Op0, Op1); 7161 } 7162 7163 // Optimizing (zext A + zext B) * C, to (VMULL A, C) + (VMULL B, C) during 7164 // isel lowering to take advantage of no-stall back to back vmul + vmla. 7165 // vmull q0, d4, d6 7166 // vmlal q0, d5, d6 7167 // is faster than 7168 // vaddl q0, d4, d5 7169 // vmovl q1, d6 7170 // vmul q0, q0, q1 7171 SDValue N00 = SkipExtensionForVMULL(N0->getOperand(0).getNode(), DAG); 7172 SDValue N01 = SkipExtensionForVMULL(N0->getOperand(1).getNode(), DAG); 7173 EVT Op1VT = Op1.getValueType(); 7174 return DAG.getNode(N0->getOpcode(), DL, VT, 7175 DAG.getNode(NewOpc, DL, VT, 7176 DAG.getNode(ISD::BITCAST, DL, Op1VT, N00), Op1), 7177 DAG.getNode(NewOpc, DL, VT, 7178 DAG.getNode(ISD::BITCAST, DL, Op1VT, N01), Op1)); 7179 } 7180 7181 static SDValue LowerSDIV_v4i8(SDValue X, SDValue Y, const SDLoc &dl, 7182 SelectionDAG &DAG) { 7183 // TODO: Should this propagate fast-math-flags? 7184 7185 // Convert to float 7186 // float4 xf = vcvt_f32_s32(vmovl_s16(a.lo)); 7187 // float4 yf = vcvt_f32_s32(vmovl_s16(b.lo)); 7188 X = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, X); 7189 Y = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, Y); 7190 X = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, X); 7191 Y = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, Y); 7192 // Get reciprocal estimate. 7193 // float4 recip = vrecpeq_f32(yf); 7194 Y = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32, 7195 DAG.getConstant(Intrinsic::arm_neon_vrecpe, dl, MVT::i32), 7196 Y); 7197 // Because char has a smaller range than uchar, we can actually get away 7198 // without any newton steps. This requires that we use a weird bias 7199 // of 0xb000, however (again, this has been exhaustively tested). 7200 // float4 result = as_float4(as_int4(xf*recip) + 0xb000); 7201 X = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, X, Y); 7202 X = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, X); 7203 Y = DAG.getConstant(0xb000, dl, MVT::v4i32); 7204 X = DAG.getNode(ISD::ADD, dl, MVT::v4i32, X, Y); 7205 X = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, X); 7206 // Convert back to short. 7207 X = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::v4i32, X); 7208 X = DAG.getNode(ISD::TRUNCATE, dl, MVT::v4i16, X); 7209 return X; 7210 } 7211 7212 static SDValue LowerSDIV_v4i16(SDValue N0, SDValue N1, const SDLoc &dl, 7213 SelectionDAG &DAG) { 7214 // TODO: Should this propagate fast-math-flags? 7215 7216 SDValue N2; 7217 // Convert to float. 7218 // float4 yf = vcvt_f32_s32(vmovl_s16(y)); 7219 // float4 xf = vcvt_f32_s32(vmovl_s16(x)); 7220 N0 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, N0); 7221 N1 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, N1); 7222 N0 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N0); 7223 N1 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N1); 7224 7225 // Use reciprocal estimate and one refinement step. 7226 // float4 recip = vrecpeq_f32(yf); 7227 // recip *= vrecpsq_f32(yf, recip); 7228 N2 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32, 7229 DAG.getConstant(Intrinsic::arm_neon_vrecpe, dl, MVT::i32), 7230 N1); 7231 N1 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32, 7232 DAG.getConstant(Intrinsic::arm_neon_vrecps, dl, MVT::i32), 7233 N1, N2); 7234 N2 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N1, N2); 7235 // Because short has a smaller range than ushort, we can actually get away 7236 // with only a single newton step. This requires that we use a weird bias 7237 // of 89, however (again, this has been exhaustively tested). 7238 // float4 result = as_float4(as_int4(xf*recip) + 0x89); 7239 N0 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N0, N2); 7240 N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, N0); 7241 N1 = DAG.getConstant(0x89, dl, MVT::v4i32); 7242 N0 = DAG.getNode(ISD::ADD, dl, MVT::v4i32, N0, N1); 7243 N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, N0); 7244 // Convert back to integer and return. 7245 // return vmovn_s32(vcvt_s32_f32(result)); 7246 N0 = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::v4i32, N0); 7247 N0 = DAG.getNode(ISD::TRUNCATE, dl, MVT::v4i16, N0); 7248 return N0; 7249 } 7250 7251 static SDValue LowerSDIV(SDValue Op, SelectionDAG &DAG) { 7252 EVT VT = Op.getValueType(); 7253 assert((VT == MVT::v4i16 || VT == MVT::v8i8) && 7254 "unexpected type for custom-lowering ISD::SDIV"); 7255 7256 SDLoc dl(Op); 7257 SDValue N0 = Op.getOperand(0); 7258 SDValue N1 = Op.getOperand(1); 7259 SDValue N2, N3; 7260 7261 if (VT == MVT::v8i8) { 7262 N0 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v8i16, N0); 7263 N1 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v8i16, N1); 7264 7265 N2 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0, 7266 DAG.getIntPtrConstant(4, dl)); 7267 N3 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1, 7268 DAG.getIntPtrConstant(4, dl)); 7269 N0 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0, 7270 DAG.getIntPtrConstant(0, dl)); 7271 N1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1, 7272 DAG.getIntPtrConstant(0, dl)); 7273 7274 N0 = LowerSDIV_v4i8(N0, N1, dl, DAG); // v4i16 7275 N2 = LowerSDIV_v4i8(N2, N3, dl, DAG); // v4i16 7276 7277 N0 = DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v8i16, N0, N2); 7278 N0 = LowerCONCAT_VECTORS(N0, DAG); 7279 7280 N0 = DAG.getNode(ISD::TRUNCATE, dl, MVT::v8i8, N0); 7281 return N0; 7282 } 7283 return LowerSDIV_v4i16(N0, N1, dl, DAG); 7284 } 7285 7286 static SDValue LowerUDIV(SDValue Op, SelectionDAG &DAG) { 7287 // TODO: Should this propagate fast-math-flags? 7288 EVT VT = Op.getValueType(); 7289 assert((VT == MVT::v4i16 || VT == MVT::v8i8) && 7290 "unexpected type for custom-lowering ISD::UDIV"); 7291 7292 SDLoc dl(Op); 7293 SDValue N0 = Op.getOperand(0); 7294 SDValue N1 = Op.getOperand(1); 7295 SDValue N2, N3; 7296 7297 if (VT == MVT::v8i8) { 7298 N0 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v8i16, N0); 7299 N1 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v8i16, N1); 7300 7301 N2 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0, 7302 DAG.getIntPtrConstant(4, dl)); 7303 N3 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1, 7304 DAG.getIntPtrConstant(4, dl)); 7305 N0 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0, 7306 DAG.getIntPtrConstant(0, dl)); 7307 N1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1, 7308 DAG.getIntPtrConstant(0, dl)); 7309 7310 N0 = LowerSDIV_v4i16(N0, N1, dl, DAG); // v4i16 7311 N2 = LowerSDIV_v4i16(N2, N3, dl, DAG); // v4i16 7312 7313 N0 = DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v8i16, N0, N2); 7314 N0 = LowerCONCAT_VECTORS(N0, DAG); 7315 7316 N0 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v8i8, 7317 DAG.getConstant(Intrinsic::arm_neon_vqmovnsu, dl, 7318 MVT::i32), 7319 N0); 7320 return N0; 7321 } 7322 7323 // v4i16 sdiv ... Convert to float. 7324 // float4 yf = vcvt_f32_s32(vmovl_u16(y)); 7325 // float4 xf = vcvt_f32_s32(vmovl_u16(x)); 7326 N0 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v4i32, N0); 7327 N1 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v4i32, N1); 7328 N0 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N0); 7329 SDValue BN1 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N1); 7330 7331 // Use reciprocal estimate and two refinement steps. 7332 // float4 recip = vrecpeq_f32(yf); 7333 // recip *= vrecpsq_f32(yf, recip); 7334 // recip *= vrecpsq_f32(yf, recip); 7335 N2 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32, 7336 DAG.getConstant(Intrinsic::arm_neon_vrecpe, dl, MVT::i32), 7337 BN1); 7338 N1 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32, 7339 DAG.getConstant(Intrinsic::arm_neon_vrecps, dl, MVT::i32), 7340 BN1, N2); 7341 N2 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N1, N2); 7342 N1 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32, 7343 DAG.getConstant(Intrinsic::arm_neon_vrecps, dl, MVT::i32), 7344 BN1, N2); 7345 N2 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N1, N2); 7346 // Simply multiplying by the reciprocal estimate can leave us a few ulps 7347 // too low, so we add 2 ulps (exhaustive testing shows that this is enough, 7348 // and that it will never cause us to return an answer too large). 7349 // float4 result = as_float4(as_int4(xf*recip) + 2); 7350 N0 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N0, N2); 7351 N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, N0); 7352 N1 = DAG.getConstant(2, dl, MVT::v4i32); 7353 N0 = DAG.getNode(ISD::ADD, dl, MVT::v4i32, N0, N1); 7354 N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, N0); 7355 // Convert back to integer and return. 7356 // return vmovn_u32(vcvt_s32_f32(result)); 7357 N0 = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::v4i32, N0); 7358 N0 = DAG.getNode(ISD::TRUNCATE, dl, MVT::v4i16, N0); 7359 return N0; 7360 } 7361 7362 static SDValue LowerADDC_ADDE_SUBC_SUBE(SDValue Op, SelectionDAG &DAG) { 7363 EVT VT = Op.getNode()->getValueType(0); 7364 SDVTList VTs = DAG.getVTList(VT, MVT::i32); 7365 7366 unsigned Opc; 7367 bool ExtraOp = false; 7368 switch (Op.getOpcode()) { 7369 default: llvm_unreachable("Invalid code"); 7370 case ISD::ADDC: Opc = ARMISD::ADDC; break; 7371 case ISD::ADDE: Opc = ARMISD::ADDE; ExtraOp = true; break; 7372 case ISD::SUBC: Opc = ARMISD::SUBC; break; 7373 case ISD::SUBE: Opc = ARMISD::SUBE; ExtraOp = true; break; 7374 } 7375 7376 if (!ExtraOp) 7377 return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0), 7378 Op.getOperand(1)); 7379 return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0), 7380 Op.getOperand(1), Op.getOperand(2)); 7381 } 7382 7383 SDValue ARMTargetLowering::LowerFSINCOS(SDValue Op, SelectionDAG &DAG) const { 7384 assert(Subtarget->isTargetDarwin()); 7385 7386 // For iOS, we want to call an alternative entry point: __sincos_stret, 7387 // return values are passed via sret. 7388 SDLoc dl(Op); 7389 SDValue Arg = Op.getOperand(0); 7390 EVT ArgVT = Arg.getValueType(); 7391 Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext()); 7392 auto PtrVT = getPointerTy(DAG.getDataLayout()); 7393 7394 MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo(); 7395 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 7396 7397 // Pair of floats / doubles used to pass the result. 7398 Type *RetTy = StructType::get(ArgTy, ArgTy); 7399 auto &DL = DAG.getDataLayout(); 7400 7401 ArgListTy Args; 7402 bool ShouldUseSRet = Subtarget->isAPCS_ABI(); 7403 SDValue SRet; 7404 if (ShouldUseSRet) { 7405 // Create stack object for sret. 7406 const uint64_t ByteSize = DL.getTypeAllocSize(RetTy); 7407 const unsigned StackAlign = DL.getPrefTypeAlignment(RetTy); 7408 int FrameIdx = MFI.CreateStackObject(ByteSize, StackAlign, false); 7409 SRet = DAG.getFrameIndex(FrameIdx, TLI.getPointerTy(DL)); 7410 7411 ArgListEntry Entry; 7412 Entry.Node = SRet; 7413 Entry.Ty = RetTy->getPointerTo(); 7414 Entry.IsSExt = false; 7415 Entry.IsZExt = false; 7416 Entry.IsSRet = true; 7417 Args.push_back(Entry); 7418 RetTy = Type::getVoidTy(*DAG.getContext()); 7419 } 7420 7421 ArgListEntry Entry; 7422 Entry.Node = Arg; 7423 Entry.Ty = ArgTy; 7424 Entry.IsSExt = false; 7425 Entry.IsZExt = false; 7426 Args.push_back(Entry); 7427 7428 const char *LibcallName = 7429 (ArgVT == MVT::f64) ? "__sincos_stret" : "__sincosf_stret"; 7430 RTLIB::Libcall LC = 7431 (ArgVT == MVT::f64) ? RTLIB::SINCOS_F64 : RTLIB::SINCOS_F32; 7432 CallingConv::ID CC = getLibcallCallingConv(LC); 7433 SDValue Callee = DAG.getExternalSymbol(LibcallName, getPointerTy(DL)); 7434 7435 TargetLowering::CallLoweringInfo CLI(DAG); 7436 CLI.setDebugLoc(dl) 7437 .setChain(DAG.getEntryNode()) 7438 .setCallee(CC, RetTy, Callee, std::move(Args)) 7439 .setDiscardResult(ShouldUseSRet); 7440 std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI); 7441 7442 if (!ShouldUseSRet) 7443 return CallResult.first; 7444 7445 SDValue LoadSin = 7446 DAG.getLoad(ArgVT, dl, CallResult.second, SRet, MachinePointerInfo()); 7447 7448 // Address of cos field. 7449 SDValue Add = DAG.getNode(ISD::ADD, dl, PtrVT, SRet, 7450 DAG.getIntPtrConstant(ArgVT.getStoreSize(), dl)); 7451 SDValue LoadCos = 7452 DAG.getLoad(ArgVT, dl, LoadSin.getValue(1), Add, MachinePointerInfo()); 7453 7454 SDVTList Tys = DAG.getVTList(ArgVT, ArgVT); 7455 return DAG.getNode(ISD::MERGE_VALUES, dl, Tys, 7456 LoadSin.getValue(0), LoadCos.getValue(0)); 7457 } 7458 7459 SDValue ARMTargetLowering::LowerWindowsDIVLibCall(SDValue Op, SelectionDAG &DAG, 7460 bool Signed, 7461 SDValue &Chain) const { 7462 EVT VT = Op.getValueType(); 7463 assert((VT == MVT::i32 || VT == MVT::i64) && 7464 "unexpected type for custom lowering DIV"); 7465 SDLoc dl(Op); 7466 7467 const auto &DL = DAG.getDataLayout(); 7468 const auto &TLI = DAG.getTargetLoweringInfo(); 7469 7470 const char *Name = nullptr; 7471 if (Signed) 7472 Name = (VT == MVT::i32) ? "__rt_sdiv" : "__rt_sdiv64"; 7473 else 7474 Name = (VT == MVT::i32) ? "__rt_udiv" : "__rt_udiv64"; 7475 7476 SDValue ES = DAG.getExternalSymbol(Name, TLI.getPointerTy(DL)); 7477 7478 ARMTargetLowering::ArgListTy Args; 7479 7480 for (auto AI : {1, 0}) { 7481 ArgListEntry Arg; 7482 Arg.Node = Op.getOperand(AI); 7483 Arg.Ty = Arg.Node.getValueType().getTypeForEVT(*DAG.getContext()); 7484 Args.push_back(Arg); 7485 } 7486 7487 CallLoweringInfo CLI(DAG); 7488 CLI.setDebugLoc(dl) 7489 .setChain(Chain) 7490 .setCallee(CallingConv::ARM_AAPCS_VFP, VT.getTypeForEVT(*DAG.getContext()), 7491 ES, std::move(Args)); 7492 7493 return LowerCallTo(CLI).first; 7494 } 7495 7496 SDValue ARMTargetLowering::LowerDIV_Windows(SDValue Op, SelectionDAG &DAG, 7497 bool Signed) const { 7498 assert(Op.getValueType() == MVT::i32 && 7499 "unexpected type for custom lowering DIV"); 7500 SDLoc dl(Op); 7501 7502 SDValue DBZCHK = DAG.getNode(ARMISD::WIN__DBZCHK, dl, MVT::Other, 7503 DAG.getEntryNode(), Op.getOperand(1)); 7504 7505 return LowerWindowsDIVLibCall(Op, DAG, Signed, DBZCHK); 7506 } 7507 7508 static SDValue WinDBZCheckDenominator(SelectionDAG &DAG, SDNode *N, SDValue InChain) { 7509 SDLoc DL(N); 7510 SDValue Op = N->getOperand(1); 7511 if (N->getValueType(0) == MVT::i32) 7512 return DAG.getNode(ARMISD::WIN__DBZCHK, DL, MVT::Other, InChain, Op); 7513 SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, Op, 7514 DAG.getConstant(0, DL, MVT::i32)); 7515 SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, Op, 7516 DAG.getConstant(1, DL, MVT::i32)); 7517 return DAG.getNode(ARMISD::WIN__DBZCHK, DL, MVT::Other, InChain, 7518 DAG.getNode(ISD::OR, DL, MVT::i32, Lo, Hi)); 7519 } 7520 7521 void ARMTargetLowering::ExpandDIV_Windows( 7522 SDValue Op, SelectionDAG &DAG, bool Signed, 7523 SmallVectorImpl<SDValue> &Results) const { 7524 const auto &DL = DAG.getDataLayout(); 7525 const auto &TLI = DAG.getTargetLoweringInfo(); 7526 7527 assert(Op.getValueType() == MVT::i64 && 7528 "unexpected type for custom lowering DIV"); 7529 SDLoc dl(Op); 7530 7531 SDValue DBZCHK = WinDBZCheckDenominator(DAG, Op.getNode(), DAG.getEntryNode()); 7532 7533 SDValue Result = LowerWindowsDIVLibCall(Op, DAG, Signed, DBZCHK); 7534 7535 SDValue Lower = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, Result); 7536 SDValue Upper = DAG.getNode(ISD::SRL, dl, MVT::i64, Result, 7537 DAG.getConstant(32, dl, TLI.getPointerTy(DL))); 7538 Upper = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, Upper); 7539 7540 Results.push_back(Lower); 7541 Results.push_back(Upper); 7542 } 7543 7544 static SDValue LowerAtomicLoadStore(SDValue Op, SelectionDAG &DAG) { 7545 if (isStrongerThanMonotonic(cast<AtomicSDNode>(Op)->getOrdering())) 7546 // Acquire/Release load/store is not legal for targets without a dmb or 7547 // equivalent available. 7548 return SDValue(); 7549 7550 // Monotonic load/store is legal for all targets. 7551 return Op; 7552 } 7553 7554 static void ReplaceREADCYCLECOUNTER(SDNode *N, 7555 SmallVectorImpl<SDValue> &Results, 7556 SelectionDAG &DAG, 7557 const ARMSubtarget *Subtarget) { 7558 SDLoc DL(N); 7559 // Under Power Management extensions, the cycle-count is: 7560 // mrc p15, #0, <Rt>, c9, c13, #0 7561 SDValue Ops[] = { N->getOperand(0), // Chain 7562 DAG.getConstant(Intrinsic::arm_mrc, DL, MVT::i32), 7563 DAG.getConstant(15, DL, MVT::i32), 7564 DAG.getConstant(0, DL, MVT::i32), 7565 DAG.getConstant(9, DL, MVT::i32), 7566 DAG.getConstant(13, DL, MVT::i32), 7567 DAG.getConstant(0, DL, MVT::i32) 7568 }; 7569 7570 SDValue Cycles32 = DAG.getNode(ISD::INTRINSIC_W_CHAIN, DL, 7571 DAG.getVTList(MVT::i32, MVT::Other), Ops); 7572 Results.push_back(DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, Cycles32, 7573 DAG.getConstant(0, DL, MVT::i32))); 7574 Results.push_back(Cycles32.getValue(1)); 7575 } 7576 7577 static SDValue createGPRPairNode(SelectionDAG &DAG, SDValue V) { 7578 SDLoc dl(V.getNode()); 7579 SDValue VLo = DAG.getAnyExtOrTrunc(V, dl, MVT::i32); 7580 SDValue VHi = DAG.getAnyExtOrTrunc( 7581 DAG.getNode(ISD::SRL, dl, MVT::i64, V, DAG.getConstant(32, dl, MVT::i32)), 7582 dl, MVT::i32); 7583 bool isBigEndian = DAG.getDataLayout().isBigEndian(); 7584 if (isBigEndian) 7585 std::swap (VLo, VHi); 7586 SDValue RegClass = 7587 DAG.getTargetConstant(ARM::GPRPairRegClassID, dl, MVT::i32); 7588 SDValue SubReg0 = DAG.getTargetConstant(ARM::gsub_0, dl, MVT::i32); 7589 SDValue SubReg1 = DAG.getTargetConstant(ARM::gsub_1, dl, MVT::i32); 7590 const SDValue Ops[] = { RegClass, VLo, SubReg0, VHi, SubReg1 }; 7591 return SDValue( 7592 DAG.getMachineNode(TargetOpcode::REG_SEQUENCE, dl, MVT::Untyped, Ops), 0); 7593 } 7594 7595 static void ReplaceCMP_SWAP_64Results(SDNode *N, 7596 SmallVectorImpl<SDValue> & Results, 7597 SelectionDAG &DAG) { 7598 assert(N->getValueType(0) == MVT::i64 && 7599 "AtomicCmpSwap on types less than 64 should be legal"); 7600 SDValue Ops[] = {N->getOperand(1), 7601 createGPRPairNode(DAG, N->getOperand(2)), 7602 createGPRPairNode(DAG, N->getOperand(3)), 7603 N->getOperand(0)}; 7604 SDNode *CmpSwap = DAG.getMachineNode( 7605 ARM::CMP_SWAP_64, SDLoc(N), 7606 DAG.getVTList(MVT::Untyped, MVT::i32, MVT::Other), Ops); 7607 7608 MachineFunction &MF = DAG.getMachineFunction(); 7609 MachineSDNode::mmo_iterator MemOp = MF.allocateMemRefsArray(1); 7610 MemOp[0] = cast<MemSDNode>(N)->getMemOperand(); 7611 cast<MachineSDNode>(CmpSwap)->setMemRefs(MemOp, MemOp + 1); 7612 7613 bool isBigEndian = DAG.getDataLayout().isBigEndian(); 7614 7615 Results.push_back( 7616 DAG.getTargetExtractSubreg(isBigEndian ? ARM::gsub_1 : ARM::gsub_0, 7617 SDLoc(N), MVT::i32, SDValue(CmpSwap, 0))); 7618 Results.push_back( 7619 DAG.getTargetExtractSubreg(isBigEndian ? ARM::gsub_0 : ARM::gsub_1, 7620 SDLoc(N), MVT::i32, SDValue(CmpSwap, 0))); 7621 Results.push_back(SDValue(CmpSwap, 2)); 7622 } 7623 7624 static SDValue LowerFPOWI(SDValue Op, const ARMSubtarget &Subtarget, 7625 SelectionDAG &DAG) { 7626 const auto &TLI = DAG.getTargetLoweringInfo(); 7627 7628 assert(Subtarget.getTargetTriple().isOSMSVCRT() && 7629 "Custom lowering is MSVCRT specific!"); 7630 7631 SDLoc dl(Op); 7632 SDValue Val = Op.getOperand(0); 7633 MVT Ty = Val->getSimpleValueType(0); 7634 SDValue Exponent = DAG.getNode(ISD::SINT_TO_FP, dl, Ty, Op.getOperand(1)); 7635 SDValue Callee = DAG.getExternalSymbol(Ty == MVT::f32 ? "powf" : "pow", 7636 TLI.getPointerTy(DAG.getDataLayout())); 7637 7638 TargetLowering::ArgListTy Args; 7639 TargetLowering::ArgListEntry Entry; 7640 7641 Entry.Node = Val; 7642 Entry.Ty = Val.getValueType().getTypeForEVT(*DAG.getContext()); 7643 Entry.IsZExt = true; 7644 Args.push_back(Entry); 7645 7646 Entry.Node = Exponent; 7647 Entry.Ty = Exponent.getValueType().getTypeForEVT(*DAG.getContext()); 7648 Entry.IsZExt = true; 7649 Args.push_back(Entry); 7650 7651 Type *LCRTy = Val.getValueType().getTypeForEVT(*DAG.getContext()); 7652 7653 // In the in-chain to the call is the entry node If we are emitting a 7654 // tailcall, the chain will be mutated if the node has a non-entry input 7655 // chain. 7656 SDValue InChain = DAG.getEntryNode(); 7657 SDValue TCChain = InChain; 7658 7659 const auto *F = DAG.getMachineFunction().getFunction(); 7660 bool IsTC = TLI.isInTailCallPosition(DAG, Op.getNode(), TCChain) && 7661 F->getReturnType() == LCRTy; 7662 if (IsTC) 7663 InChain = TCChain; 7664 7665 TargetLowering::CallLoweringInfo CLI(DAG); 7666 CLI.setDebugLoc(dl) 7667 .setChain(InChain) 7668 .setCallee(CallingConv::ARM_AAPCS_VFP, LCRTy, Callee, std::move(Args)) 7669 .setTailCall(IsTC); 7670 std::pair<SDValue, SDValue> CI = TLI.LowerCallTo(CLI); 7671 7672 // Return the chain (the DAG root) if it is a tail call 7673 return !CI.second.getNode() ? DAG.getRoot() : CI.first; 7674 } 7675 7676 SDValue ARMTargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const { 7677 switch (Op.getOpcode()) { 7678 default: llvm_unreachable("Don't know how to custom lower this!"); 7679 case ISD::WRITE_REGISTER: return LowerWRITE_REGISTER(Op, DAG); 7680 case ISD::ConstantPool: return LowerConstantPool(Op, DAG); 7681 case ISD::BlockAddress: return LowerBlockAddress(Op, DAG); 7682 case ISD::GlobalAddress: return LowerGlobalAddress(Op, DAG); 7683 case ISD::GlobalTLSAddress: return LowerGlobalTLSAddress(Op, DAG); 7684 case ISD::SELECT: return LowerSELECT(Op, DAG); 7685 case ISD::SELECT_CC: return LowerSELECT_CC(Op, DAG); 7686 case ISD::BR_CC: return LowerBR_CC(Op, DAG); 7687 case ISD::BR_JT: return LowerBR_JT(Op, DAG); 7688 case ISD::VASTART: return LowerVASTART(Op, DAG); 7689 case ISD::ATOMIC_FENCE: return LowerATOMIC_FENCE(Op, DAG, Subtarget); 7690 case ISD::PREFETCH: return LowerPREFETCH(Op, DAG, Subtarget); 7691 case ISD::SINT_TO_FP: 7692 case ISD::UINT_TO_FP: return LowerINT_TO_FP(Op, DAG); 7693 case ISD::FP_TO_SINT: 7694 case ISD::FP_TO_UINT: return LowerFP_TO_INT(Op, DAG); 7695 case ISD::FCOPYSIGN: return LowerFCOPYSIGN(Op, DAG); 7696 case ISD::RETURNADDR: return LowerRETURNADDR(Op, DAG); 7697 case ISD::FRAMEADDR: return LowerFRAMEADDR(Op, DAG); 7698 case ISD::EH_SJLJ_SETJMP: return LowerEH_SJLJ_SETJMP(Op, DAG); 7699 case ISD::EH_SJLJ_LONGJMP: return LowerEH_SJLJ_LONGJMP(Op, DAG); 7700 case ISD::EH_SJLJ_SETUP_DISPATCH: return LowerEH_SJLJ_SETUP_DISPATCH(Op, DAG); 7701 case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG, 7702 Subtarget); 7703 case ISD::BITCAST: return ExpandBITCAST(Op.getNode(), DAG); 7704 case ISD::SHL: 7705 case ISD::SRL: 7706 case ISD::SRA: return LowerShift(Op.getNode(), DAG, Subtarget); 7707 case ISD::SREM: return LowerREM(Op.getNode(), DAG); 7708 case ISD::UREM: return LowerREM(Op.getNode(), DAG); 7709 case ISD::SHL_PARTS: return LowerShiftLeftParts(Op, DAG); 7710 case ISD::SRL_PARTS: 7711 case ISD::SRA_PARTS: return LowerShiftRightParts(Op, DAG); 7712 case ISD::CTTZ: 7713 case ISD::CTTZ_ZERO_UNDEF: return LowerCTTZ(Op.getNode(), DAG, Subtarget); 7714 case ISD::CTPOP: return LowerCTPOP(Op.getNode(), DAG, Subtarget); 7715 case ISD::SETCC: return LowerVSETCC(Op, DAG); 7716 case ISD::SETCCE: return LowerSETCCE(Op, DAG); 7717 case ISD::ConstantFP: return LowerConstantFP(Op, DAG, Subtarget); 7718 case ISD::BUILD_VECTOR: return LowerBUILD_VECTOR(Op, DAG, Subtarget); 7719 case ISD::VECTOR_SHUFFLE: return LowerVECTOR_SHUFFLE(Op, DAG); 7720 case ISD::INSERT_VECTOR_ELT: return LowerINSERT_VECTOR_ELT(Op, DAG); 7721 case ISD::EXTRACT_VECTOR_ELT: return LowerEXTRACT_VECTOR_ELT(Op, DAG); 7722 case ISD::CONCAT_VECTORS: return LowerCONCAT_VECTORS(Op, DAG); 7723 case ISD::FLT_ROUNDS_: return LowerFLT_ROUNDS_(Op, DAG); 7724 case ISD::MUL: return LowerMUL(Op, DAG); 7725 case ISD::SDIV: 7726 if (Subtarget->isTargetWindows() && !Op.getValueType().isVector()) 7727 return LowerDIV_Windows(Op, DAG, /* Signed */ true); 7728 return LowerSDIV(Op, DAG); 7729 case ISD::UDIV: 7730 if (Subtarget->isTargetWindows() && !Op.getValueType().isVector()) 7731 return LowerDIV_Windows(Op, DAG, /* Signed */ false); 7732 return LowerUDIV(Op, DAG); 7733 case ISD::ADDC: 7734 case ISD::ADDE: 7735 case ISD::SUBC: 7736 case ISD::SUBE: return LowerADDC_ADDE_SUBC_SUBE(Op, DAG); 7737 case ISD::SADDO: 7738 case ISD::UADDO: 7739 case ISD::SSUBO: 7740 case ISD::USUBO: 7741 return LowerXALUO(Op, DAG); 7742 case ISD::ATOMIC_LOAD: 7743 case ISD::ATOMIC_STORE: return LowerAtomicLoadStore(Op, DAG); 7744 case ISD::FSINCOS: return LowerFSINCOS(Op, DAG); 7745 case ISD::SDIVREM: 7746 case ISD::UDIVREM: return LowerDivRem(Op, DAG); 7747 case ISD::DYNAMIC_STACKALLOC: 7748 if (Subtarget->getTargetTriple().isWindowsItaniumEnvironment()) 7749 return LowerDYNAMIC_STACKALLOC(Op, DAG); 7750 llvm_unreachable("Don't know how to custom lower this!"); 7751 case ISD::FP_ROUND: return LowerFP_ROUND(Op, DAG); 7752 case ISD::FP_EXTEND: return LowerFP_EXTEND(Op, DAG); 7753 case ISD::FPOWI: return LowerFPOWI(Op, *Subtarget, DAG); 7754 case ARMISD::WIN__DBZCHK: return SDValue(); 7755 } 7756 } 7757 7758 static void ReplaceLongIntrinsic(SDNode *N, SmallVectorImpl<SDValue> &Results, 7759 SelectionDAG &DAG) { 7760 unsigned IntNo = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue(); 7761 unsigned Opc = 0; 7762 if (IntNo == Intrinsic::arm_smlald) 7763 Opc = ARMISD::SMLALD; 7764 else if (IntNo == Intrinsic::arm_smlaldx) 7765 Opc = ARMISD::SMLALDX; 7766 else if (IntNo == Intrinsic::arm_smlsld) 7767 Opc = ARMISD::SMLSLD; 7768 else if (IntNo == Intrinsic::arm_smlsldx) 7769 Opc = ARMISD::SMLSLDX; 7770 else 7771 return; 7772 7773 SDLoc dl(N); 7774 SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, 7775 N->getOperand(3), 7776 DAG.getConstant(0, dl, MVT::i32)); 7777 SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, 7778 N->getOperand(3), 7779 DAG.getConstant(1, dl, MVT::i32)); 7780 7781 SDValue LongMul = DAG.getNode(Opc, dl, 7782 DAG.getVTList(MVT::i32, MVT::i32), 7783 N->getOperand(1), N->getOperand(2), 7784 Lo, Hi); 7785 Results.push_back(LongMul.getValue(0)); 7786 Results.push_back(LongMul.getValue(1)); 7787 } 7788 7789 /// ReplaceNodeResults - Replace the results of node with an illegal result 7790 /// type with new values built out of custom code. 7791 void ARMTargetLowering::ReplaceNodeResults(SDNode *N, 7792 SmallVectorImpl<SDValue> &Results, 7793 SelectionDAG &DAG) const { 7794 SDValue Res; 7795 switch (N->getOpcode()) { 7796 default: 7797 llvm_unreachable("Don't know how to custom expand this!"); 7798 case ISD::READ_REGISTER: 7799 ExpandREAD_REGISTER(N, Results, DAG); 7800 break; 7801 case ISD::BITCAST: 7802 Res = ExpandBITCAST(N, DAG); 7803 break; 7804 case ISD::SRL: 7805 case ISD::SRA: 7806 Res = Expand64BitShift(N, DAG, Subtarget); 7807 break; 7808 case ISD::SREM: 7809 case ISD::UREM: 7810 Res = LowerREM(N, DAG); 7811 break; 7812 case ISD::SDIVREM: 7813 case ISD::UDIVREM: 7814 Res = LowerDivRem(SDValue(N, 0), DAG); 7815 assert(Res.getNumOperands() == 2 && "DivRem needs two values"); 7816 Results.push_back(Res.getValue(0)); 7817 Results.push_back(Res.getValue(1)); 7818 return; 7819 case ISD::READCYCLECOUNTER: 7820 ReplaceREADCYCLECOUNTER(N, Results, DAG, Subtarget); 7821 return; 7822 case ISD::UDIV: 7823 case ISD::SDIV: 7824 assert(Subtarget->isTargetWindows() && "can only expand DIV on Windows"); 7825 return ExpandDIV_Windows(SDValue(N, 0), DAG, N->getOpcode() == ISD::SDIV, 7826 Results); 7827 case ISD::ATOMIC_CMP_SWAP: 7828 ReplaceCMP_SWAP_64Results(N, Results, DAG); 7829 return; 7830 case ISD::INTRINSIC_WO_CHAIN: 7831 return ReplaceLongIntrinsic(N, Results, DAG); 7832 } 7833 if (Res.getNode()) 7834 Results.push_back(Res); 7835 } 7836 7837 //===----------------------------------------------------------------------===// 7838 // ARM Scheduler Hooks 7839 //===----------------------------------------------------------------------===// 7840 7841 /// SetupEntryBlockForSjLj - Insert code into the entry block that creates and 7842 /// registers the function context. 7843 void ARMTargetLowering::SetupEntryBlockForSjLj(MachineInstr &MI, 7844 MachineBasicBlock *MBB, 7845 MachineBasicBlock *DispatchBB, 7846 int FI) const { 7847 assert(!Subtarget->isROPI() && !Subtarget->isRWPI() && 7848 "ROPI/RWPI not currently supported with SjLj"); 7849 const TargetInstrInfo *TII = Subtarget->getInstrInfo(); 7850 DebugLoc dl = MI.getDebugLoc(); 7851 MachineFunction *MF = MBB->getParent(); 7852 MachineRegisterInfo *MRI = &MF->getRegInfo(); 7853 MachineConstantPool *MCP = MF->getConstantPool(); 7854 ARMFunctionInfo *AFI = MF->getInfo<ARMFunctionInfo>(); 7855 const Function *F = MF->getFunction(); 7856 7857 bool isThumb = Subtarget->isThumb(); 7858 bool isThumb2 = Subtarget->isThumb2(); 7859 7860 unsigned PCLabelId = AFI->createPICLabelUId(); 7861 unsigned PCAdj = (isThumb || isThumb2) ? 4 : 8; 7862 ARMConstantPoolValue *CPV = 7863 ARMConstantPoolMBB::Create(F->getContext(), DispatchBB, PCLabelId, PCAdj); 7864 unsigned CPI = MCP->getConstantPoolIndex(CPV, 4); 7865 7866 const TargetRegisterClass *TRC = isThumb ? &ARM::tGPRRegClass 7867 : &ARM::GPRRegClass; 7868 7869 // Grab constant pool and fixed stack memory operands. 7870 MachineMemOperand *CPMMO = 7871 MF->getMachineMemOperand(MachinePointerInfo::getConstantPool(*MF), 7872 MachineMemOperand::MOLoad, 4, 4); 7873 7874 MachineMemOperand *FIMMOSt = 7875 MF->getMachineMemOperand(MachinePointerInfo::getFixedStack(*MF, FI), 7876 MachineMemOperand::MOStore, 4, 4); 7877 7878 // Load the address of the dispatch MBB into the jump buffer. 7879 if (isThumb2) { 7880 // Incoming value: jbuf 7881 // ldr.n r5, LCPI1_1 7882 // orr r5, r5, #1 7883 // add r5, pc 7884 // str r5, [$jbuf, #+4] ; &jbuf[1] 7885 unsigned NewVReg1 = MRI->createVirtualRegister(TRC); 7886 BuildMI(*MBB, MI, dl, TII->get(ARM::t2LDRpci), NewVReg1) 7887 .addConstantPoolIndex(CPI) 7888 .addMemOperand(CPMMO) 7889 .add(predOps(ARMCC::AL)); 7890 // Set the low bit because of thumb mode. 7891 unsigned NewVReg2 = MRI->createVirtualRegister(TRC); 7892 BuildMI(*MBB, MI, dl, TII->get(ARM::t2ORRri), NewVReg2) 7893 .addReg(NewVReg1, RegState::Kill) 7894 .addImm(0x01) 7895 .add(predOps(ARMCC::AL)) 7896 .add(condCodeOp()); 7897 unsigned NewVReg3 = MRI->createVirtualRegister(TRC); 7898 BuildMI(*MBB, MI, dl, TII->get(ARM::tPICADD), NewVReg3) 7899 .addReg(NewVReg2, RegState::Kill) 7900 .addImm(PCLabelId); 7901 BuildMI(*MBB, MI, dl, TII->get(ARM::t2STRi12)) 7902 .addReg(NewVReg3, RegState::Kill) 7903 .addFrameIndex(FI) 7904 .addImm(36) // &jbuf[1] :: pc 7905 .addMemOperand(FIMMOSt) 7906 .add(predOps(ARMCC::AL)); 7907 } else if (isThumb) { 7908 // Incoming value: jbuf 7909 // ldr.n r1, LCPI1_4 7910 // add r1, pc 7911 // mov r2, #1 7912 // orrs r1, r2 7913 // add r2, $jbuf, #+4 ; &jbuf[1] 7914 // str r1, [r2] 7915 unsigned NewVReg1 = MRI->createVirtualRegister(TRC); 7916 BuildMI(*MBB, MI, dl, TII->get(ARM::tLDRpci), NewVReg1) 7917 .addConstantPoolIndex(CPI) 7918 .addMemOperand(CPMMO) 7919 .add(predOps(ARMCC::AL)); 7920 unsigned NewVReg2 = MRI->createVirtualRegister(TRC); 7921 BuildMI(*MBB, MI, dl, TII->get(ARM::tPICADD), NewVReg2) 7922 .addReg(NewVReg1, RegState::Kill) 7923 .addImm(PCLabelId); 7924 // Set the low bit because of thumb mode. 7925 unsigned NewVReg3 = MRI->createVirtualRegister(TRC); 7926 BuildMI(*MBB, MI, dl, TII->get(ARM::tMOVi8), NewVReg3) 7927 .addReg(ARM::CPSR, RegState::Define) 7928 .addImm(1) 7929 .add(predOps(ARMCC::AL)); 7930 unsigned NewVReg4 = MRI->createVirtualRegister(TRC); 7931 BuildMI(*MBB, MI, dl, TII->get(ARM::tORR), NewVReg4) 7932 .addReg(ARM::CPSR, RegState::Define) 7933 .addReg(NewVReg2, RegState::Kill) 7934 .addReg(NewVReg3, RegState::Kill) 7935 .add(predOps(ARMCC::AL)); 7936 unsigned NewVReg5 = MRI->createVirtualRegister(TRC); 7937 BuildMI(*MBB, MI, dl, TII->get(ARM::tADDframe), NewVReg5) 7938 .addFrameIndex(FI) 7939 .addImm(36); // &jbuf[1] :: pc 7940 BuildMI(*MBB, MI, dl, TII->get(ARM::tSTRi)) 7941 .addReg(NewVReg4, RegState::Kill) 7942 .addReg(NewVReg5, RegState::Kill) 7943 .addImm(0) 7944 .addMemOperand(FIMMOSt) 7945 .add(predOps(ARMCC::AL)); 7946 } else { 7947 // Incoming value: jbuf 7948 // ldr r1, LCPI1_1 7949 // add r1, pc, r1 7950 // str r1, [$jbuf, #+4] ; &jbuf[1] 7951 unsigned NewVReg1 = MRI->createVirtualRegister(TRC); 7952 BuildMI(*MBB, MI, dl, TII->get(ARM::LDRi12), NewVReg1) 7953 .addConstantPoolIndex(CPI) 7954 .addImm(0) 7955 .addMemOperand(CPMMO) 7956 .add(predOps(ARMCC::AL)); 7957 unsigned NewVReg2 = MRI->createVirtualRegister(TRC); 7958 BuildMI(*MBB, MI, dl, TII->get(ARM::PICADD), NewVReg2) 7959 .addReg(NewVReg1, RegState::Kill) 7960 .addImm(PCLabelId) 7961 .add(predOps(ARMCC::AL)); 7962 BuildMI(*MBB, MI, dl, TII->get(ARM::STRi12)) 7963 .addReg(NewVReg2, RegState::Kill) 7964 .addFrameIndex(FI) 7965 .addImm(36) // &jbuf[1] :: pc 7966 .addMemOperand(FIMMOSt) 7967 .add(predOps(ARMCC::AL)); 7968 } 7969 } 7970 7971 void ARMTargetLowering::EmitSjLjDispatchBlock(MachineInstr &MI, 7972 MachineBasicBlock *MBB) const { 7973 const TargetInstrInfo *TII = Subtarget->getInstrInfo(); 7974 DebugLoc dl = MI.getDebugLoc(); 7975 MachineFunction *MF = MBB->getParent(); 7976 MachineRegisterInfo *MRI = &MF->getRegInfo(); 7977 MachineFrameInfo &MFI = MF->getFrameInfo(); 7978 int FI = MFI.getFunctionContextIndex(); 7979 7980 const TargetRegisterClass *TRC = Subtarget->isThumb() ? &ARM::tGPRRegClass 7981 : &ARM::GPRnopcRegClass; 7982 7983 // Get a mapping of the call site numbers to all of the landing pads they're 7984 // associated with. 7985 DenseMap<unsigned, SmallVector<MachineBasicBlock*, 2>> CallSiteNumToLPad; 7986 unsigned MaxCSNum = 0; 7987 for (MachineFunction::iterator BB = MF->begin(), E = MF->end(); BB != E; 7988 ++BB) { 7989 if (!BB->isEHPad()) continue; 7990 7991 // FIXME: We should assert that the EH_LABEL is the first MI in the landing 7992 // pad. 7993 for (MachineBasicBlock::iterator 7994 II = BB->begin(), IE = BB->end(); II != IE; ++II) { 7995 if (!II->isEHLabel()) continue; 7996 7997 MCSymbol *Sym = II->getOperand(0).getMCSymbol(); 7998 if (!MF->hasCallSiteLandingPad(Sym)) continue; 7999 8000 SmallVectorImpl<unsigned> &CallSiteIdxs = MF->getCallSiteLandingPad(Sym); 8001 for (SmallVectorImpl<unsigned>::iterator 8002 CSI = CallSiteIdxs.begin(), CSE = CallSiteIdxs.end(); 8003 CSI != CSE; ++CSI) { 8004 CallSiteNumToLPad[*CSI].push_back(&*BB); 8005 MaxCSNum = std::max(MaxCSNum, *CSI); 8006 } 8007 break; 8008 } 8009 } 8010 8011 // Get an ordered list of the machine basic blocks for the jump table. 8012 std::vector<MachineBasicBlock*> LPadList; 8013 SmallPtrSet<MachineBasicBlock*, 32> InvokeBBs; 8014 LPadList.reserve(CallSiteNumToLPad.size()); 8015 for (unsigned I = 1; I <= MaxCSNum; ++I) { 8016 SmallVectorImpl<MachineBasicBlock*> &MBBList = CallSiteNumToLPad[I]; 8017 for (SmallVectorImpl<MachineBasicBlock*>::iterator 8018 II = MBBList.begin(), IE = MBBList.end(); II != IE; ++II) { 8019 LPadList.push_back(*II); 8020 InvokeBBs.insert((*II)->pred_begin(), (*II)->pred_end()); 8021 } 8022 } 8023 8024 assert(!LPadList.empty() && 8025 "No landing pad destinations for the dispatch jump table!"); 8026 8027 // Create the jump table and associated information. 8028 MachineJumpTableInfo *JTI = 8029 MF->getOrCreateJumpTableInfo(MachineJumpTableInfo::EK_Inline); 8030 unsigned MJTI = JTI->createJumpTableIndex(LPadList); 8031 8032 // Create the MBBs for the dispatch code. 8033 8034 // Shove the dispatch's address into the return slot in the function context. 8035 MachineBasicBlock *DispatchBB = MF->CreateMachineBasicBlock(); 8036 DispatchBB->setIsEHPad(); 8037 8038 MachineBasicBlock *TrapBB = MF->CreateMachineBasicBlock(); 8039 unsigned trap_opcode; 8040 if (Subtarget->isThumb()) 8041 trap_opcode = ARM::tTRAP; 8042 else 8043 trap_opcode = Subtarget->useNaClTrap() ? ARM::TRAPNaCl : ARM::TRAP; 8044 8045 BuildMI(TrapBB, dl, TII->get(trap_opcode)); 8046 DispatchBB->addSuccessor(TrapBB); 8047 8048 MachineBasicBlock *DispContBB = MF->CreateMachineBasicBlock(); 8049 DispatchBB->addSuccessor(DispContBB); 8050 8051 // Insert and MBBs. 8052 MF->insert(MF->end(), DispatchBB); 8053 MF->insert(MF->end(), DispContBB); 8054 MF->insert(MF->end(), TrapBB); 8055 8056 // Insert code into the entry block that creates and registers the function 8057 // context. 8058 SetupEntryBlockForSjLj(MI, MBB, DispatchBB, FI); 8059 8060 MachineMemOperand *FIMMOLd = MF->getMachineMemOperand( 8061 MachinePointerInfo::getFixedStack(*MF, FI), 8062 MachineMemOperand::MOLoad | MachineMemOperand::MOVolatile, 4, 4); 8063 8064 MachineInstrBuilder MIB; 8065 MIB = BuildMI(DispatchBB, dl, TII->get(ARM::Int_eh_sjlj_dispatchsetup)); 8066 8067 const ARMBaseInstrInfo *AII = static_cast<const ARMBaseInstrInfo*>(TII); 8068 const ARMBaseRegisterInfo &RI = AII->getRegisterInfo(); 8069 8070 // Add a register mask with no preserved registers. This results in all 8071 // registers being marked as clobbered. This can't work if the dispatch block 8072 // is in a Thumb1 function and is linked with ARM code which uses the FP 8073 // registers, as there is no way to preserve the FP registers in Thumb1 mode. 8074 MIB.addRegMask(RI.getSjLjDispatchPreservedMask(*MF)); 8075 8076 bool IsPositionIndependent = isPositionIndependent(); 8077 unsigned NumLPads = LPadList.size(); 8078 if (Subtarget->isThumb2()) { 8079 unsigned NewVReg1 = MRI->createVirtualRegister(TRC); 8080 BuildMI(DispatchBB, dl, TII->get(ARM::t2LDRi12), NewVReg1) 8081 .addFrameIndex(FI) 8082 .addImm(4) 8083 .addMemOperand(FIMMOLd) 8084 .add(predOps(ARMCC::AL)); 8085 8086 if (NumLPads < 256) { 8087 BuildMI(DispatchBB, dl, TII->get(ARM::t2CMPri)) 8088 .addReg(NewVReg1) 8089 .addImm(LPadList.size()) 8090 .add(predOps(ARMCC::AL)); 8091 } else { 8092 unsigned VReg1 = MRI->createVirtualRegister(TRC); 8093 BuildMI(DispatchBB, dl, TII->get(ARM::t2MOVi16), VReg1) 8094 .addImm(NumLPads & 0xFFFF) 8095 .add(predOps(ARMCC::AL)); 8096 8097 unsigned VReg2 = VReg1; 8098 if ((NumLPads & 0xFFFF0000) != 0) { 8099 VReg2 = MRI->createVirtualRegister(TRC); 8100 BuildMI(DispatchBB, dl, TII->get(ARM::t2MOVTi16), VReg2) 8101 .addReg(VReg1) 8102 .addImm(NumLPads >> 16) 8103 .add(predOps(ARMCC::AL)); 8104 } 8105 8106 BuildMI(DispatchBB, dl, TII->get(ARM::t2CMPrr)) 8107 .addReg(NewVReg1) 8108 .addReg(VReg2) 8109 .add(predOps(ARMCC::AL)); 8110 } 8111 8112 BuildMI(DispatchBB, dl, TII->get(ARM::t2Bcc)) 8113 .addMBB(TrapBB) 8114 .addImm(ARMCC::HI) 8115 .addReg(ARM::CPSR); 8116 8117 unsigned NewVReg3 = MRI->createVirtualRegister(TRC); 8118 BuildMI(DispContBB, dl, TII->get(ARM::t2LEApcrelJT), NewVReg3) 8119 .addJumpTableIndex(MJTI) 8120 .add(predOps(ARMCC::AL)); 8121 8122 unsigned NewVReg4 = MRI->createVirtualRegister(TRC); 8123 BuildMI(DispContBB, dl, TII->get(ARM::t2ADDrs), NewVReg4) 8124 .addReg(NewVReg3, RegState::Kill) 8125 .addReg(NewVReg1) 8126 .addImm(ARM_AM::getSORegOpc(ARM_AM::lsl, 2)) 8127 .add(predOps(ARMCC::AL)) 8128 .add(condCodeOp()); 8129 8130 BuildMI(DispContBB, dl, TII->get(ARM::t2BR_JT)) 8131 .addReg(NewVReg4, RegState::Kill) 8132 .addReg(NewVReg1) 8133 .addJumpTableIndex(MJTI); 8134 } else if (Subtarget->isThumb()) { 8135 unsigned NewVReg1 = MRI->createVirtualRegister(TRC); 8136 BuildMI(DispatchBB, dl, TII->get(ARM::tLDRspi), NewVReg1) 8137 .addFrameIndex(FI) 8138 .addImm(1) 8139 .addMemOperand(FIMMOLd) 8140 .add(predOps(ARMCC::AL)); 8141 8142 if (NumLPads < 256) { 8143 BuildMI(DispatchBB, dl, TII->get(ARM::tCMPi8)) 8144 .addReg(NewVReg1) 8145 .addImm(NumLPads) 8146 .add(predOps(ARMCC::AL)); 8147 } else { 8148 MachineConstantPool *ConstantPool = MF->getConstantPool(); 8149 Type *Int32Ty = Type::getInt32Ty(MF->getFunction()->getContext()); 8150 const Constant *C = ConstantInt::get(Int32Ty, NumLPads); 8151 8152 // MachineConstantPool wants an explicit alignment. 8153 unsigned Align = MF->getDataLayout().getPrefTypeAlignment(Int32Ty); 8154 if (Align == 0) 8155 Align = MF->getDataLayout().getTypeAllocSize(C->getType()); 8156 unsigned Idx = ConstantPool->getConstantPoolIndex(C, Align); 8157 8158 unsigned VReg1 = MRI->createVirtualRegister(TRC); 8159 BuildMI(DispatchBB, dl, TII->get(ARM::tLDRpci)) 8160 .addReg(VReg1, RegState::Define) 8161 .addConstantPoolIndex(Idx) 8162 .add(predOps(ARMCC::AL)); 8163 BuildMI(DispatchBB, dl, TII->get(ARM::tCMPr)) 8164 .addReg(NewVReg1) 8165 .addReg(VReg1) 8166 .add(predOps(ARMCC::AL)); 8167 } 8168 8169 BuildMI(DispatchBB, dl, TII->get(ARM::tBcc)) 8170 .addMBB(TrapBB) 8171 .addImm(ARMCC::HI) 8172 .addReg(ARM::CPSR); 8173 8174 unsigned NewVReg2 = MRI->createVirtualRegister(TRC); 8175 BuildMI(DispContBB, dl, TII->get(ARM::tLSLri), NewVReg2) 8176 .addReg(ARM::CPSR, RegState::Define) 8177 .addReg(NewVReg1) 8178 .addImm(2) 8179 .add(predOps(ARMCC::AL)); 8180 8181 unsigned NewVReg3 = MRI->createVirtualRegister(TRC); 8182 BuildMI(DispContBB, dl, TII->get(ARM::tLEApcrelJT), NewVReg3) 8183 .addJumpTableIndex(MJTI) 8184 .add(predOps(ARMCC::AL)); 8185 8186 unsigned NewVReg4 = MRI->createVirtualRegister(TRC); 8187 BuildMI(DispContBB, dl, TII->get(ARM::tADDrr), NewVReg4) 8188 .addReg(ARM::CPSR, RegState::Define) 8189 .addReg(NewVReg2, RegState::Kill) 8190 .addReg(NewVReg3) 8191 .add(predOps(ARMCC::AL)); 8192 8193 MachineMemOperand *JTMMOLd = MF->getMachineMemOperand( 8194 MachinePointerInfo::getJumpTable(*MF), MachineMemOperand::MOLoad, 4, 4); 8195 8196 unsigned NewVReg5 = MRI->createVirtualRegister(TRC); 8197 BuildMI(DispContBB, dl, TII->get(ARM::tLDRi), NewVReg5) 8198 .addReg(NewVReg4, RegState::Kill) 8199 .addImm(0) 8200 .addMemOperand(JTMMOLd) 8201 .add(predOps(ARMCC::AL)); 8202 8203 unsigned NewVReg6 = NewVReg5; 8204 if (IsPositionIndependent) { 8205 NewVReg6 = MRI->createVirtualRegister(TRC); 8206 BuildMI(DispContBB, dl, TII->get(ARM::tADDrr), NewVReg6) 8207 .addReg(ARM::CPSR, RegState::Define) 8208 .addReg(NewVReg5, RegState::Kill) 8209 .addReg(NewVReg3) 8210 .add(predOps(ARMCC::AL)); 8211 } 8212 8213 BuildMI(DispContBB, dl, TII->get(ARM::tBR_JTr)) 8214 .addReg(NewVReg6, RegState::Kill) 8215 .addJumpTableIndex(MJTI); 8216 } else { 8217 unsigned NewVReg1 = MRI->createVirtualRegister(TRC); 8218 BuildMI(DispatchBB, dl, TII->get(ARM::LDRi12), NewVReg1) 8219 .addFrameIndex(FI) 8220 .addImm(4) 8221 .addMemOperand(FIMMOLd) 8222 .add(predOps(ARMCC::AL)); 8223 8224 if (NumLPads < 256) { 8225 BuildMI(DispatchBB, dl, TII->get(ARM::CMPri)) 8226 .addReg(NewVReg1) 8227 .addImm(NumLPads) 8228 .add(predOps(ARMCC::AL)); 8229 } else if (Subtarget->hasV6T2Ops() && isUInt<16>(NumLPads)) { 8230 unsigned VReg1 = MRI->createVirtualRegister(TRC); 8231 BuildMI(DispatchBB, dl, TII->get(ARM::MOVi16), VReg1) 8232 .addImm(NumLPads & 0xFFFF) 8233 .add(predOps(ARMCC::AL)); 8234 8235 unsigned VReg2 = VReg1; 8236 if ((NumLPads & 0xFFFF0000) != 0) { 8237 VReg2 = MRI->createVirtualRegister(TRC); 8238 BuildMI(DispatchBB, dl, TII->get(ARM::MOVTi16), VReg2) 8239 .addReg(VReg1) 8240 .addImm(NumLPads >> 16) 8241 .add(predOps(ARMCC::AL)); 8242 } 8243 8244 BuildMI(DispatchBB, dl, TII->get(ARM::CMPrr)) 8245 .addReg(NewVReg1) 8246 .addReg(VReg2) 8247 .add(predOps(ARMCC::AL)); 8248 } else { 8249 MachineConstantPool *ConstantPool = MF->getConstantPool(); 8250 Type *Int32Ty = Type::getInt32Ty(MF->getFunction()->getContext()); 8251 const Constant *C = ConstantInt::get(Int32Ty, NumLPads); 8252 8253 // MachineConstantPool wants an explicit alignment. 8254 unsigned Align = MF->getDataLayout().getPrefTypeAlignment(Int32Ty); 8255 if (Align == 0) 8256 Align = MF->getDataLayout().getTypeAllocSize(C->getType()); 8257 unsigned Idx = ConstantPool->getConstantPoolIndex(C, Align); 8258 8259 unsigned VReg1 = MRI->createVirtualRegister(TRC); 8260 BuildMI(DispatchBB, dl, TII->get(ARM::LDRcp)) 8261 .addReg(VReg1, RegState::Define) 8262 .addConstantPoolIndex(Idx) 8263 .addImm(0) 8264 .add(predOps(ARMCC::AL)); 8265 BuildMI(DispatchBB, dl, TII->get(ARM::CMPrr)) 8266 .addReg(NewVReg1) 8267 .addReg(VReg1, RegState::Kill) 8268 .add(predOps(ARMCC::AL)); 8269 } 8270 8271 BuildMI(DispatchBB, dl, TII->get(ARM::Bcc)) 8272 .addMBB(TrapBB) 8273 .addImm(ARMCC::HI) 8274 .addReg(ARM::CPSR); 8275 8276 unsigned NewVReg3 = MRI->createVirtualRegister(TRC); 8277 BuildMI(DispContBB, dl, TII->get(ARM::MOVsi), NewVReg3) 8278 .addReg(NewVReg1) 8279 .addImm(ARM_AM::getSORegOpc(ARM_AM::lsl, 2)) 8280 .add(predOps(ARMCC::AL)) 8281 .add(condCodeOp()); 8282 unsigned NewVReg4 = MRI->createVirtualRegister(TRC); 8283 BuildMI(DispContBB, dl, TII->get(ARM::LEApcrelJT), NewVReg4) 8284 .addJumpTableIndex(MJTI) 8285 .add(predOps(ARMCC::AL)); 8286 8287 MachineMemOperand *JTMMOLd = MF->getMachineMemOperand( 8288 MachinePointerInfo::getJumpTable(*MF), MachineMemOperand::MOLoad, 4, 4); 8289 unsigned NewVReg5 = MRI->createVirtualRegister(TRC); 8290 BuildMI(DispContBB, dl, TII->get(ARM::LDRrs), NewVReg5) 8291 .addReg(NewVReg3, RegState::Kill) 8292 .addReg(NewVReg4) 8293 .addImm(0) 8294 .addMemOperand(JTMMOLd) 8295 .add(predOps(ARMCC::AL)); 8296 8297 if (IsPositionIndependent) { 8298 BuildMI(DispContBB, dl, TII->get(ARM::BR_JTadd)) 8299 .addReg(NewVReg5, RegState::Kill) 8300 .addReg(NewVReg4) 8301 .addJumpTableIndex(MJTI); 8302 } else { 8303 BuildMI(DispContBB, dl, TII->get(ARM::BR_JTr)) 8304 .addReg(NewVReg5, RegState::Kill) 8305 .addJumpTableIndex(MJTI); 8306 } 8307 } 8308 8309 // Add the jump table entries as successors to the MBB. 8310 SmallPtrSet<MachineBasicBlock*, 8> SeenMBBs; 8311 for (std::vector<MachineBasicBlock*>::iterator 8312 I = LPadList.begin(), E = LPadList.end(); I != E; ++I) { 8313 MachineBasicBlock *CurMBB = *I; 8314 if (SeenMBBs.insert(CurMBB).second) 8315 DispContBB->addSuccessor(CurMBB); 8316 } 8317 8318 // N.B. the order the invoke BBs are processed in doesn't matter here. 8319 const MCPhysReg *SavedRegs = RI.getCalleeSavedRegs(MF); 8320 SmallVector<MachineBasicBlock*, 64> MBBLPads; 8321 for (MachineBasicBlock *BB : InvokeBBs) { 8322 8323 // Remove the landing pad successor from the invoke block and replace it 8324 // with the new dispatch block. 8325 SmallVector<MachineBasicBlock*, 4> Successors(BB->succ_begin(), 8326 BB->succ_end()); 8327 while (!Successors.empty()) { 8328 MachineBasicBlock *SMBB = Successors.pop_back_val(); 8329 if (SMBB->isEHPad()) { 8330 BB->removeSuccessor(SMBB); 8331 MBBLPads.push_back(SMBB); 8332 } 8333 } 8334 8335 BB->addSuccessor(DispatchBB, BranchProbability::getZero()); 8336 BB->normalizeSuccProbs(); 8337 8338 // Find the invoke call and mark all of the callee-saved registers as 8339 // 'implicit defined' so that they're spilled. This prevents code from 8340 // moving instructions to before the EH block, where they will never be 8341 // executed. 8342 for (MachineBasicBlock::reverse_iterator 8343 II = BB->rbegin(), IE = BB->rend(); II != IE; ++II) { 8344 if (!II->isCall()) continue; 8345 8346 DenseMap<unsigned, bool> DefRegs; 8347 for (MachineInstr::mop_iterator 8348 OI = II->operands_begin(), OE = II->operands_end(); 8349 OI != OE; ++OI) { 8350 if (!OI->isReg()) continue; 8351 DefRegs[OI->getReg()] = true; 8352 } 8353 8354 MachineInstrBuilder MIB(*MF, &*II); 8355 8356 for (unsigned i = 0; SavedRegs[i] != 0; ++i) { 8357 unsigned Reg = SavedRegs[i]; 8358 if (Subtarget->isThumb2() && 8359 !ARM::tGPRRegClass.contains(Reg) && 8360 !ARM::hGPRRegClass.contains(Reg)) 8361 continue; 8362 if (Subtarget->isThumb1Only() && !ARM::tGPRRegClass.contains(Reg)) 8363 continue; 8364 if (!Subtarget->isThumb() && !ARM::GPRRegClass.contains(Reg)) 8365 continue; 8366 if (!DefRegs[Reg]) 8367 MIB.addReg(Reg, RegState::ImplicitDefine | RegState::Dead); 8368 } 8369 8370 break; 8371 } 8372 } 8373 8374 // Mark all former landing pads as non-landing pads. The dispatch is the only 8375 // landing pad now. 8376 for (SmallVectorImpl<MachineBasicBlock*>::iterator 8377 I = MBBLPads.begin(), E = MBBLPads.end(); I != E; ++I) 8378 (*I)->setIsEHPad(false); 8379 8380 // The instruction is gone now. 8381 MI.eraseFromParent(); 8382 } 8383 8384 static 8385 MachineBasicBlock *OtherSucc(MachineBasicBlock *MBB, MachineBasicBlock *Succ) { 8386 for (MachineBasicBlock::succ_iterator I = MBB->succ_begin(), 8387 E = MBB->succ_end(); I != E; ++I) 8388 if (*I != Succ) 8389 return *I; 8390 llvm_unreachable("Expecting a BB with two successors!"); 8391 } 8392 8393 /// Return the load opcode for a given load size. If load size >= 8, 8394 /// neon opcode will be returned. 8395 static unsigned getLdOpcode(unsigned LdSize, bool IsThumb1, bool IsThumb2) { 8396 if (LdSize >= 8) 8397 return LdSize == 16 ? ARM::VLD1q32wb_fixed 8398 : LdSize == 8 ? ARM::VLD1d32wb_fixed : 0; 8399 if (IsThumb1) 8400 return LdSize == 4 ? ARM::tLDRi 8401 : LdSize == 2 ? ARM::tLDRHi 8402 : LdSize == 1 ? ARM::tLDRBi : 0; 8403 if (IsThumb2) 8404 return LdSize == 4 ? ARM::t2LDR_POST 8405 : LdSize == 2 ? ARM::t2LDRH_POST 8406 : LdSize == 1 ? ARM::t2LDRB_POST : 0; 8407 return LdSize == 4 ? ARM::LDR_POST_IMM 8408 : LdSize == 2 ? ARM::LDRH_POST 8409 : LdSize == 1 ? ARM::LDRB_POST_IMM : 0; 8410 } 8411 8412 /// Return the store opcode for a given store size. If store size >= 8, 8413 /// neon opcode will be returned. 8414 static unsigned getStOpcode(unsigned StSize, bool IsThumb1, bool IsThumb2) { 8415 if (StSize >= 8) 8416 return StSize == 16 ? ARM::VST1q32wb_fixed 8417 : StSize == 8 ? ARM::VST1d32wb_fixed : 0; 8418 if (IsThumb1) 8419 return StSize == 4 ? ARM::tSTRi 8420 : StSize == 2 ? ARM::tSTRHi 8421 : StSize == 1 ? ARM::tSTRBi : 0; 8422 if (IsThumb2) 8423 return StSize == 4 ? ARM::t2STR_POST 8424 : StSize == 2 ? ARM::t2STRH_POST 8425 : StSize == 1 ? ARM::t2STRB_POST : 0; 8426 return StSize == 4 ? ARM::STR_POST_IMM 8427 : StSize == 2 ? ARM::STRH_POST 8428 : StSize == 1 ? ARM::STRB_POST_IMM : 0; 8429 } 8430 8431 /// Emit a post-increment load operation with given size. The instructions 8432 /// will be added to BB at Pos. 8433 static void emitPostLd(MachineBasicBlock *BB, MachineBasicBlock::iterator Pos, 8434 const TargetInstrInfo *TII, const DebugLoc &dl, 8435 unsigned LdSize, unsigned Data, unsigned AddrIn, 8436 unsigned AddrOut, bool IsThumb1, bool IsThumb2) { 8437 unsigned LdOpc = getLdOpcode(LdSize, IsThumb1, IsThumb2); 8438 assert(LdOpc != 0 && "Should have a load opcode"); 8439 if (LdSize >= 8) { 8440 BuildMI(*BB, Pos, dl, TII->get(LdOpc), Data) 8441 .addReg(AddrOut, RegState::Define) 8442 .addReg(AddrIn) 8443 .addImm(0) 8444 .add(predOps(ARMCC::AL)); 8445 } else if (IsThumb1) { 8446 // load + update AddrIn 8447 BuildMI(*BB, Pos, dl, TII->get(LdOpc), Data) 8448 .addReg(AddrIn) 8449 .addImm(0) 8450 .add(predOps(ARMCC::AL)); 8451 BuildMI(*BB, Pos, dl, TII->get(ARM::tADDi8), AddrOut) 8452 .add(t1CondCodeOp()) 8453 .addReg(AddrIn) 8454 .addImm(LdSize) 8455 .add(predOps(ARMCC::AL)); 8456 } else if (IsThumb2) { 8457 BuildMI(*BB, Pos, dl, TII->get(LdOpc), Data) 8458 .addReg(AddrOut, RegState::Define) 8459 .addReg(AddrIn) 8460 .addImm(LdSize) 8461 .add(predOps(ARMCC::AL)); 8462 } else { // arm 8463 BuildMI(*BB, Pos, dl, TII->get(LdOpc), Data) 8464 .addReg(AddrOut, RegState::Define) 8465 .addReg(AddrIn) 8466 .addReg(0) 8467 .addImm(LdSize) 8468 .add(predOps(ARMCC::AL)); 8469 } 8470 } 8471 8472 /// Emit a post-increment store operation with given size. The instructions 8473 /// will be added to BB at Pos. 8474 static void emitPostSt(MachineBasicBlock *BB, MachineBasicBlock::iterator Pos, 8475 const TargetInstrInfo *TII, const DebugLoc &dl, 8476 unsigned StSize, unsigned Data, unsigned AddrIn, 8477 unsigned AddrOut, bool IsThumb1, bool IsThumb2) { 8478 unsigned StOpc = getStOpcode(StSize, IsThumb1, IsThumb2); 8479 assert(StOpc != 0 && "Should have a store opcode"); 8480 if (StSize >= 8) { 8481 BuildMI(*BB, Pos, dl, TII->get(StOpc), AddrOut) 8482 .addReg(AddrIn) 8483 .addImm(0) 8484 .addReg(Data) 8485 .add(predOps(ARMCC::AL)); 8486 } else if (IsThumb1) { 8487 // store + update AddrIn 8488 BuildMI(*BB, Pos, dl, TII->get(StOpc)) 8489 .addReg(Data) 8490 .addReg(AddrIn) 8491 .addImm(0) 8492 .add(predOps(ARMCC::AL)); 8493 BuildMI(*BB, Pos, dl, TII->get(ARM::tADDi8), AddrOut) 8494 .add(t1CondCodeOp()) 8495 .addReg(AddrIn) 8496 .addImm(StSize) 8497 .add(predOps(ARMCC::AL)); 8498 } else if (IsThumb2) { 8499 BuildMI(*BB, Pos, dl, TII->get(StOpc), AddrOut) 8500 .addReg(Data) 8501 .addReg(AddrIn) 8502 .addImm(StSize) 8503 .add(predOps(ARMCC::AL)); 8504 } else { // arm 8505 BuildMI(*BB, Pos, dl, TII->get(StOpc), AddrOut) 8506 .addReg(Data) 8507 .addReg(AddrIn) 8508 .addReg(0) 8509 .addImm(StSize) 8510 .add(predOps(ARMCC::AL)); 8511 } 8512 } 8513 8514 MachineBasicBlock * 8515 ARMTargetLowering::EmitStructByval(MachineInstr &MI, 8516 MachineBasicBlock *BB) const { 8517 // This pseudo instruction has 3 operands: dst, src, size 8518 // We expand it to a loop if size > Subtarget->getMaxInlineSizeThreshold(). 8519 // Otherwise, we will generate unrolled scalar copies. 8520 const TargetInstrInfo *TII = Subtarget->getInstrInfo(); 8521 const BasicBlock *LLVM_BB = BB->getBasicBlock(); 8522 MachineFunction::iterator It = ++BB->getIterator(); 8523 8524 unsigned dest = MI.getOperand(0).getReg(); 8525 unsigned src = MI.getOperand(1).getReg(); 8526 unsigned SizeVal = MI.getOperand(2).getImm(); 8527 unsigned Align = MI.getOperand(3).getImm(); 8528 DebugLoc dl = MI.getDebugLoc(); 8529 8530 MachineFunction *MF = BB->getParent(); 8531 MachineRegisterInfo &MRI = MF->getRegInfo(); 8532 unsigned UnitSize = 0; 8533 const TargetRegisterClass *TRC = nullptr; 8534 const TargetRegisterClass *VecTRC = nullptr; 8535 8536 bool IsThumb1 = Subtarget->isThumb1Only(); 8537 bool IsThumb2 = Subtarget->isThumb2(); 8538 bool IsThumb = Subtarget->isThumb(); 8539 8540 if (Align & 1) { 8541 UnitSize = 1; 8542 } else if (Align & 2) { 8543 UnitSize = 2; 8544 } else { 8545 // Check whether we can use NEON instructions. 8546 if (!MF->getFunction()->hasFnAttribute(Attribute::NoImplicitFloat) && 8547 Subtarget->hasNEON()) { 8548 if ((Align % 16 == 0) && SizeVal >= 16) 8549 UnitSize = 16; 8550 else if ((Align % 8 == 0) && SizeVal >= 8) 8551 UnitSize = 8; 8552 } 8553 // Can't use NEON instructions. 8554 if (UnitSize == 0) 8555 UnitSize = 4; 8556 } 8557 8558 // Select the correct opcode and register class for unit size load/store 8559 bool IsNeon = UnitSize >= 8; 8560 TRC = IsThumb ? &ARM::tGPRRegClass : &ARM::GPRRegClass; 8561 if (IsNeon) 8562 VecTRC = UnitSize == 16 ? &ARM::DPairRegClass 8563 : UnitSize == 8 ? &ARM::DPRRegClass 8564 : nullptr; 8565 8566 unsigned BytesLeft = SizeVal % UnitSize; 8567 unsigned LoopSize = SizeVal - BytesLeft; 8568 8569 if (SizeVal <= Subtarget->getMaxInlineSizeThreshold()) { 8570 // Use LDR and STR to copy. 8571 // [scratch, srcOut] = LDR_POST(srcIn, UnitSize) 8572 // [destOut] = STR_POST(scratch, destIn, UnitSize) 8573 unsigned srcIn = src; 8574 unsigned destIn = dest; 8575 for (unsigned i = 0; i < LoopSize; i+=UnitSize) { 8576 unsigned srcOut = MRI.createVirtualRegister(TRC); 8577 unsigned destOut = MRI.createVirtualRegister(TRC); 8578 unsigned scratch = MRI.createVirtualRegister(IsNeon ? VecTRC : TRC); 8579 emitPostLd(BB, MI, TII, dl, UnitSize, scratch, srcIn, srcOut, 8580 IsThumb1, IsThumb2); 8581 emitPostSt(BB, MI, TII, dl, UnitSize, scratch, destIn, destOut, 8582 IsThumb1, IsThumb2); 8583 srcIn = srcOut; 8584 destIn = destOut; 8585 } 8586 8587 // Handle the leftover bytes with LDRB and STRB. 8588 // [scratch, srcOut] = LDRB_POST(srcIn, 1) 8589 // [destOut] = STRB_POST(scratch, destIn, 1) 8590 for (unsigned i = 0; i < BytesLeft; i++) { 8591 unsigned srcOut = MRI.createVirtualRegister(TRC); 8592 unsigned destOut = MRI.createVirtualRegister(TRC); 8593 unsigned scratch = MRI.createVirtualRegister(TRC); 8594 emitPostLd(BB, MI, TII, dl, 1, scratch, srcIn, srcOut, 8595 IsThumb1, IsThumb2); 8596 emitPostSt(BB, MI, TII, dl, 1, scratch, destIn, destOut, 8597 IsThumb1, IsThumb2); 8598 srcIn = srcOut; 8599 destIn = destOut; 8600 } 8601 MI.eraseFromParent(); // The instruction is gone now. 8602 return BB; 8603 } 8604 8605 // Expand the pseudo op to a loop. 8606 // thisMBB: 8607 // ... 8608 // movw varEnd, # --> with thumb2 8609 // movt varEnd, # 8610 // ldrcp varEnd, idx --> without thumb2 8611 // fallthrough --> loopMBB 8612 // loopMBB: 8613 // PHI varPhi, varEnd, varLoop 8614 // PHI srcPhi, src, srcLoop 8615 // PHI destPhi, dst, destLoop 8616 // [scratch, srcLoop] = LDR_POST(srcPhi, UnitSize) 8617 // [destLoop] = STR_POST(scratch, destPhi, UnitSize) 8618 // subs varLoop, varPhi, #UnitSize 8619 // bne loopMBB 8620 // fallthrough --> exitMBB 8621 // exitMBB: 8622 // epilogue to handle left-over bytes 8623 // [scratch, srcOut] = LDRB_POST(srcLoop, 1) 8624 // [destOut] = STRB_POST(scratch, destLoop, 1) 8625 MachineBasicBlock *loopMBB = MF->CreateMachineBasicBlock(LLVM_BB); 8626 MachineBasicBlock *exitMBB = MF->CreateMachineBasicBlock(LLVM_BB); 8627 MF->insert(It, loopMBB); 8628 MF->insert(It, exitMBB); 8629 8630 // Transfer the remainder of BB and its successor edges to exitMBB. 8631 exitMBB->splice(exitMBB->begin(), BB, 8632 std::next(MachineBasicBlock::iterator(MI)), BB->end()); 8633 exitMBB->transferSuccessorsAndUpdatePHIs(BB); 8634 8635 // Load an immediate to varEnd. 8636 unsigned varEnd = MRI.createVirtualRegister(TRC); 8637 if (Subtarget->useMovt(*MF)) { 8638 unsigned Vtmp = varEnd; 8639 if ((LoopSize & 0xFFFF0000) != 0) 8640 Vtmp = MRI.createVirtualRegister(TRC); 8641 BuildMI(BB, dl, TII->get(IsThumb ? ARM::t2MOVi16 : ARM::MOVi16), Vtmp) 8642 .addImm(LoopSize & 0xFFFF) 8643 .add(predOps(ARMCC::AL)); 8644 8645 if ((LoopSize & 0xFFFF0000) != 0) 8646 BuildMI(BB, dl, TII->get(IsThumb ? ARM::t2MOVTi16 : ARM::MOVTi16), varEnd) 8647 .addReg(Vtmp) 8648 .addImm(LoopSize >> 16) 8649 .add(predOps(ARMCC::AL)); 8650 } else { 8651 MachineConstantPool *ConstantPool = MF->getConstantPool(); 8652 Type *Int32Ty = Type::getInt32Ty(MF->getFunction()->getContext()); 8653 const Constant *C = ConstantInt::get(Int32Ty, LoopSize); 8654 8655 // MachineConstantPool wants an explicit alignment. 8656 unsigned Align = MF->getDataLayout().getPrefTypeAlignment(Int32Ty); 8657 if (Align == 0) 8658 Align = MF->getDataLayout().getTypeAllocSize(C->getType()); 8659 unsigned Idx = ConstantPool->getConstantPoolIndex(C, Align); 8660 8661 if (IsThumb) 8662 BuildMI(*BB, MI, dl, TII->get(ARM::tLDRpci)) 8663 .addReg(varEnd, RegState::Define) 8664 .addConstantPoolIndex(Idx) 8665 .add(predOps(ARMCC::AL)); 8666 else 8667 BuildMI(*BB, MI, dl, TII->get(ARM::LDRcp)) 8668 .addReg(varEnd, RegState::Define) 8669 .addConstantPoolIndex(Idx) 8670 .addImm(0) 8671 .add(predOps(ARMCC::AL)); 8672 } 8673 BB->addSuccessor(loopMBB); 8674 8675 // Generate the loop body: 8676 // varPhi = PHI(varLoop, varEnd) 8677 // srcPhi = PHI(srcLoop, src) 8678 // destPhi = PHI(destLoop, dst) 8679 MachineBasicBlock *entryBB = BB; 8680 BB = loopMBB; 8681 unsigned varLoop = MRI.createVirtualRegister(TRC); 8682 unsigned varPhi = MRI.createVirtualRegister(TRC); 8683 unsigned srcLoop = MRI.createVirtualRegister(TRC); 8684 unsigned srcPhi = MRI.createVirtualRegister(TRC); 8685 unsigned destLoop = MRI.createVirtualRegister(TRC); 8686 unsigned destPhi = MRI.createVirtualRegister(TRC); 8687 8688 BuildMI(*BB, BB->begin(), dl, TII->get(ARM::PHI), varPhi) 8689 .addReg(varLoop).addMBB(loopMBB) 8690 .addReg(varEnd).addMBB(entryBB); 8691 BuildMI(BB, dl, TII->get(ARM::PHI), srcPhi) 8692 .addReg(srcLoop).addMBB(loopMBB) 8693 .addReg(src).addMBB(entryBB); 8694 BuildMI(BB, dl, TII->get(ARM::PHI), destPhi) 8695 .addReg(destLoop).addMBB(loopMBB) 8696 .addReg(dest).addMBB(entryBB); 8697 8698 // [scratch, srcLoop] = LDR_POST(srcPhi, UnitSize) 8699 // [destLoop] = STR_POST(scratch, destPhi, UnitSiz) 8700 unsigned scratch = MRI.createVirtualRegister(IsNeon ? VecTRC : TRC); 8701 emitPostLd(BB, BB->end(), TII, dl, UnitSize, scratch, srcPhi, srcLoop, 8702 IsThumb1, IsThumb2); 8703 emitPostSt(BB, BB->end(), TII, dl, UnitSize, scratch, destPhi, destLoop, 8704 IsThumb1, IsThumb2); 8705 8706 // Decrement loop variable by UnitSize. 8707 if (IsThumb1) { 8708 BuildMI(*BB, BB->end(), dl, TII->get(ARM::tSUBi8), varLoop) 8709 .add(t1CondCodeOp()) 8710 .addReg(varPhi) 8711 .addImm(UnitSize) 8712 .add(predOps(ARMCC::AL)); 8713 } else { 8714 MachineInstrBuilder MIB = 8715 BuildMI(*BB, BB->end(), dl, 8716 TII->get(IsThumb2 ? ARM::t2SUBri : ARM::SUBri), varLoop); 8717 MIB.addReg(varPhi) 8718 .addImm(UnitSize) 8719 .add(predOps(ARMCC::AL)) 8720 .add(condCodeOp()); 8721 MIB->getOperand(5).setReg(ARM::CPSR); 8722 MIB->getOperand(5).setIsDef(true); 8723 } 8724 BuildMI(*BB, BB->end(), dl, 8725 TII->get(IsThumb1 ? ARM::tBcc : IsThumb2 ? ARM::t2Bcc : ARM::Bcc)) 8726 .addMBB(loopMBB).addImm(ARMCC::NE).addReg(ARM::CPSR); 8727 8728 // loopMBB can loop back to loopMBB or fall through to exitMBB. 8729 BB->addSuccessor(loopMBB); 8730 BB->addSuccessor(exitMBB); 8731 8732 // Add epilogue to handle BytesLeft. 8733 BB = exitMBB; 8734 auto StartOfExit = exitMBB->begin(); 8735 8736 // [scratch, srcOut] = LDRB_POST(srcLoop, 1) 8737 // [destOut] = STRB_POST(scratch, destLoop, 1) 8738 unsigned srcIn = srcLoop; 8739 unsigned destIn = destLoop; 8740 for (unsigned i = 0; i < BytesLeft; i++) { 8741 unsigned srcOut = MRI.createVirtualRegister(TRC); 8742 unsigned destOut = MRI.createVirtualRegister(TRC); 8743 unsigned scratch = MRI.createVirtualRegister(TRC); 8744 emitPostLd(BB, StartOfExit, TII, dl, 1, scratch, srcIn, srcOut, 8745 IsThumb1, IsThumb2); 8746 emitPostSt(BB, StartOfExit, TII, dl, 1, scratch, destIn, destOut, 8747 IsThumb1, IsThumb2); 8748 srcIn = srcOut; 8749 destIn = destOut; 8750 } 8751 8752 MI.eraseFromParent(); // The instruction is gone now. 8753 return BB; 8754 } 8755 8756 MachineBasicBlock * 8757 ARMTargetLowering::EmitLowered__chkstk(MachineInstr &MI, 8758 MachineBasicBlock *MBB) const { 8759 const TargetMachine &TM = getTargetMachine(); 8760 const TargetInstrInfo &TII = *Subtarget->getInstrInfo(); 8761 DebugLoc DL = MI.getDebugLoc(); 8762 8763 assert(Subtarget->isTargetWindows() && 8764 "__chkstk is only supported on Windows"); 8765 assert(Subtarget->isThumb2() && "Windows on ARM requires Thumb-2 mode"); 8766 8767 // __chkstk takes the number of words to allocate on the stack in R4, and 8768 // returns the stack adjustment in number of bytes in R4. This will not 8769 // clober any other registers (other than the obvious lr). 8770 // 8771 // Although, technically, IP should be considered a register which may be 8772 // clobbered, the call itself will not touch it. Windows on ARM is a pure 8773 // thumb-2 environment, so there is no interworking required. As a result, we 8774 // do not expect a veneer to be emitted by the linker, clobbering IP. 8775 // 8776 // Each module receives its own copy of __chkstk, so no import thunk is 8777 // required, again, ensuring that IP is not clobbered. 8778 // 8779 // Finally, although some linkers may theoretically provide a trampoline for 8780 // out of range calls (which is quite common due to a 32M range limitation of 8781 // branches for Thumb), we can generate the long-call version via 8782 // -mcmodel=large, alleviating the need for the trampoline which may clobber 8783 // IP. 8784 8785 switch (TM.getCodeModel()) { 8786 case CodeModel::Small: 8787 case CodeModel::Medium: 8788 case CodeModel::Kernel: 8789 BuildMI(*MBB, MI, DL, TII.get(ARM::tBL)) 8790 .add(predOps(ARMCC::AL)) 8791 .addExternalSymbol("__chkstk") 8792 .addReg(ARM::R4, RegState::Implicit | RegState::Kill) 8793 .addReg(ARM::R4, RegState::Implicit | RegState::Define) 8794 .addReg(ARM::R12, 8795 RegState::Implicit | RegState::Define | RegState::Dead) 8796 .addReg(ARM::CPSR, 8797 RegState::Implicit | RegState::Define | RegState::Dead); 8798 break; 8799 case CodeModel::Large: { 8800 MachineRegisterInfo &MRI = MBB->getParent()->getRegInfo(); 8801 unsigned Reg = MRI.createVirtualRegister(&ARM::rGPRRegClass); 8802 8803 BuildMI(*MBB, MI, DL, TII.get(ARM::t2MOVi32imm), Reg) 8804 .addExternalSymbol("__chkstk"); 8805 BuildMI(*MBB, MI, DL, TII.get(ARM::tBLXr)) 8806 .add(predOps(ARMCC::AL)) 8807 .addReg(Reg, RegState::Kill) 8808 .addReg(ARM::R4, RegState::Implicit | RegState::Kill) 8809 .addReg(ARM::R4, RegState::Implicit | RegState::Define) 8810 .addReg(ARM::R12, 8811 RegState::Implicit | RegState::Define | RegState::Dead) 8812 .addReg(ARM::CPSR, 8813 RegState::Implicit | RegState::Define | RegState::Dead); 8814 break; 8815 } 8816 } 8817 8818 BuildMI(*MBB, MI, DL, TII.get(ARM::t2SUBrr), ARM::SP) 8819 .addReg(ARM::SP, RegState::Kill) 8820 .addReg(ARM::R4, RegState::Kill) 8821 .setMIFlags(MachineInstr::FrameSetup) 8822 .add(predOps(ARMCC::AL)) 8823 .add(condCodeOp()); 8824 8825 MI.eraseFromParent(); 8826 return MBB; 8827 } 8828 8829 MachineBasicBlock * 8830 ARMTargetLowering::EmitLowered__dbzchk(MachineInstr &MI, 8831 MachineBasicBlock *MBB) const { 8832 DebugLoc DL = MI.getDebugLoc(); 8833 MachineFunction *MF = MBB->getParent(); 8834 const TargetInstrInfo *TII = Subtarget->getInstrInfo(); 8835 8836 MachineBasicBlock *ContBB = MF->CreateMachineBasicBlock(); 8837 MF->insert(++MBB->getIterator(), ContBB); 8838 ContBB->splice(ContBB->begin(), MBB, 8839 std::next(MachineBasicBlock::iterator(MI)), MBB->end()); 8840 ContBB->transferSuccessorsAndUpdatePHIs(MBB); 8841 MBB->addSuccessor(ContBB); 8842 8843 MachineBasicBlock *TrapBB = MF->CreateMachineBasicBlock(); 8844 BuildMI(TrapBB, DL, TII->get(ARM::t__brkdiv0)); 8845 MF->push_back(TrapBB); 8846 MBB->addSuccessor(TrapBB); 8847 8848 BuildMI(*MBB, MI, DL, TII->get(ARM::tCMPi8)) 8849 .addReg(MI.getOperand(0).getReg()) 8850 .addImm(0) 8851 .add(predOps(ARMCC::AL)); 8852 BuildMI(*MBB, MI, DL, TII->get(ARM::t2Bcc)) 8853 .addMBB(TrapBB) 8854 .addImm(ARMCC::EQ) 8855 .addReg(ARM::CPSR); 8856 8857 MI.eraseFromParent(); 8858 return ContBB; 8859 } 8860 8861 MachineBasicBlock * 8862 ARMTargetLowering::EmitInstrWithCustomInserter(MachineInstr &MI, 8863 MachineBasicBlock *BB) const { 8864 const TargetInstrInfo *TII = Subtarget->getInstrInfo(); 8865 DebugLoc dl = MI.getDebugLoc(); 8866 bool isThumb2 = Subtarget->isThumb2(); 8867 switch (MI.getOpcode()) { 8868 default: { 8869 MI.print(errs()); 8870 llvm_unreachable("Unexpected instr type to insert"); 8871 } 8872 8873 // Thumb1 post-indexed loads are really just single-register LDMs. 8874 case ARM::tLDR_postidx: { 8875 BuildMI(*BB, MI, dl, TII->get(ARM::tLDMIA_UPD)) 8876 .add(MI.getOperand(1)) // Rn_wb 8877 .add(MI.getOperand(2)) // Rn 8878 .add(MI.getOperand(3)) // PredImm 8879 .add(MI.getOperand(4)) // PredReg 8880 .add(MI.getOperand(0)); // Rt 8881 MI.eraseFromParent(); 8882 return BB; 8883 } 8884 8885 // The Thumb2 pre-indexed stores have the same MI operands, they just 8886 // define them differently in the .td files from the isel patterns, so 8887 // they need pseudos. 8888 case ARM::t2STR_preidx: 8889 MI.setDesc(TII->get(ARM::t2STR_PRE)); 8890 return BB; 8891 case ARM::t2STRB_preidx: 8892 MI.setDesc(TII->get(ARM::t2STRB_PRE)); 8893 return BB; 8894 case ARM::t2STRH_preidx: 8895 MI.setDesc(TII->get(ARM::t2STRH_PRE)); 8896 return BB; 8897 8898 case ARM::STRi_preidx: 8899 case ARM::STRBi_preidx: { 8900 unsigned NewOpc = MI.getOpcode() == ARM::STRi_preidx ? ARM::STR_PRE_IMM 8901 : ARM::STRB_PRE_IMM; 8902 // Decode the offset. 8903 unsigned Offset = MI.getOperand(4).getImm(); 8904 bool isSub = ARM_AM::getAM2Op(Offset) == ARM_AM::sub; 8905 Offset = ARM_AM::getAM2Offset(Offset); 8906 if (isSub) 8907 Offset = -Offset; 8908 8909 MachineMemOperand *MMO = *MI.memoperands_begin(); 8910 BuildMI(*BB, MI, dl, TII->get(NewOpc)) 8911 .add(MI.getOperand(0)) // Rn_wb 8912 .add(MI.getOperand(1)) // Rt 8913 .add(MI.getOperand(2)) // Rn 8914 .addImm(Offset) // offset (skip GPR==zero_reg) 8915 .add(MI.getOperand(5)) // pred 8916 .add(MI.getOperand(6)) 8917 .addMemOperand(MMO); 8918 MI.eraseFromParent(); 8919 return BB; 8920 } 8921 case ARM::STRr_preidx: 8922 case ARM::STRBr_preidx: 8923 case ARM::STRH_preidx: { 8924 unsigned NewOpc; 8925 switch (MI.getOpcode()) { 8926 default: llvm_unreachable("unexpected opcode!"); 8927 case ARM::STRr_preidx: NewOpc = ARM::STR_PRE_REG; break; 8928 case ARM::STRBr_preidx: NewOpc = ARM::STRB_PRE_REG; break; 8929 case ARM::STRH_preidx: NewOpc = ARM::STRH_PRE; break; 8930 } 8931 MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(NewOpc)); 8932 for (unsigned i = 0; i < MI.getNumOperands(); ++i) 8933 MIB.add(MI.getOperand(i)); 8934 MI.eraseFromParent(); 8935 return BB; 8936 } 8937 8938 case ARM::tMOVCCr_pseudo: { 8939 // To "insert" a SELECT_CC instruction, we actually have to insert the 8940 // diamond control-flow pattern. The incoming instruction knows the 8941 // destination vreg to set, the condition code register to branch on, the 8942 // true/false values to select between, and a branch opcode to use. 8943 const BasicBlock *LLVM_BB = BB->getBasicBlock(); 8944 MachineFunction::iterator It = ++BB->getIterator(); 8945 8946 // thisMBB: 8947 // ... 8948 // TrueVal = ... 8949 // cmpTY ccX, r1, r2 8950 // bCC copy1MBB 8951 // fallthrough --> copy0MBB 8952 MachineBasicBlock *thisMBB = BB; 8953 MachineFunction *F = BB->getParent(); 8954 MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB); 8955 MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB); 8956 F->insert(It, copy0MBB); 8957 F->insert(It, sinkMBB); 8958 8959 // Transfer the remainder of BB and its successor edges to sinkMBB. 8960 sinkMBB->splice(sinkMBB->begin(), BB, 8961 std::next(MachineBasicBlock::iterator(MI)), BB->end()); 8962 sinkMBB->transferSuccessorsAndUpdatePHIs(BB); 8963 8964 BB->addSuccessor(copy0MBB); 8965 BB->addSuccessor(sinkMBB); 8966 8967 BuildMI(BB, dl, TII->get(ARM::tBcc)) 8968 .addMBB(sinkMBB) 8969 .addImm(MI.getOperand(3).getImm()) 8970 .addReg(MI.getOperand(4).getReg()); 8971 8972 // copy0MBB: 8973 // %FalseValue = ... 8974 // # fallthrough to sinkMBB 8975 BB = copy0MBB; 8976 8977 // Update machine-CFG edges 8978 BB->addSuccessor(sinkMBB); 8979 8980 // sinkMBB: 8981 // %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ] 8982 // ... 8983 BB = sinkMBB; 8984 BuildMI(*BB, BB->begin(), dl, TII->get(ARM::PHI), MI.getOperand(0).getReg()) 8985 .addReg(MI.getOperand(1).getReg()) 8986 .addMBB(copy0MBB) 8987 .addReg(MI.getOperand(2).getReg()) 8988 .addMBB(thisMBB); 8989 8990 MI.eraseFromParent(); // The pseudo instruction is gone now. 8991 return BB; 8992 } 8993 8994 case ARM::BCCi64: 8995 case ARM::BCCZi64: { 8996 // If there is an unconditional branch to the other successor, remove it. 8997 BB->erase(std::next(MachineBasicBlock::iterator(MI)), BB->end()); 8998 8999 // Compare both parts that make up the double comparison separately for 9000 // equality. 9001 bool RHSisZero = MI.getOpcode() == ARM::BCCZi64; 9002 9003 unsigned LHS1 = MI.getOperand(1).getReg(); 9004 unsigned LHS2 = MI.getOperand(2).getReg(); 9005 if (RHSisZero) { 9006 BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri)) 9007 .addReg(LHS1) 9008 .addImm(0) 9009 .add(predOps(ARMCC::AL)); 9010 BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri)) 9011 .addReg(LHS2).addImm(0) 9012 .addImm(ARMCC::EQ).addReg(ARM::CPSR); 9013 } else { 9014 unsigned RHS1 = MI.getOperand(3).getReg(); 9015 unsigned RHS2 = MI.getOperand(4).getReg(); 9016 BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPrr : ARM::CMPrr)) 9017 .addReg(LHS1) 9018 .addReg(RHS1) 9019 .add(predOps(ARMCC::AL)); 9020 BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPrr : ARM::CMPrr)) 9021 .addReg(LHS2).addReg(RHS2) 9022 .addImm(ARMCC::EQ).addReg(ARM::CPSR); 9023 } 9024 9025 MachineBasicBlock *destMBB = MI.getOperand(RHSisZero ? 3 : 5).getMBB(); 9026 MachineBasicBlock *exitMBB = OtherSucc(BB, destMBB); 9027 if (MI.getOperand(0).getImm() == ARMCC::NE) 9028 std::swap(destMBB, exitMBB); 9029 9030 BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc)) 9031 .addMBB(destMBB).addImm(ARMCC::EQ).addReg(ARM::CPSR); 9032 if (isThumb2) 9033 BuildMI(BB, dl, TII->get(ARM::t2B)) 9034 .addMBB(exitMBB) 9035 .add(predOps(ARMCC::AL)); 9036 else 9037 BuildMI(BB, dl, TII->get(ARM::B)) .addMBB(exitMBB); 9038 9039 MI.eraseFromParent(); // The pseudo instruction is gone now. 9040 return BB; 9041 } 9042 9043 case ARM::Int_eh_sjlj_setjmp: 9044 case ARM::Int_eh_sjlj_setjmp_nofp: 9045 case ARM::tInt_eh_sjlj_setjmp: 9046 case ARM::t2Int_eh_sjlj_setjmp: 9047 case ARM::t2Int_eh_sjlj_setjmp_nofp: 9048 return BB; 9049 9050 case ARM::Int_eh_sjlj_setup_dispatch: 9051 EmitSjLjDispatchBlock(MI, BB); 9052 return BB; 9053 9054 case ARM::ABS: 9055 case ARM::t2ABS: { 9056 // To insert an ABS instruction, we have to insert the 9057 // diamond control-flow pattern. The incoming instruction knows the 9058 // source vreg to test against 0, the destination vreg to set, 9059 // the condition code register to branch on, the 9060 // true/false values to select between, and a branch opcode to use. 9061 // It transforms 9062 // V1 = ABS V0 9063 // into 9064 // V2 = MOVS V0 9065 // BCC (branch to SinkBB if V0 >= 0) 9066 // RSBBB: V3 = RSBri V2, 0 (compute ABS if V2 < 0) 9067 // SinkBB: V1 = PHI(V2, V3) 9068 const BasicBlock *LLVM_BB = BB->getBasicBlock(); 9069 MachineFunction::iterator BBI = ++BB->getIterator(); 9070 MachineFunction *Fn = BB->getParent(); 9071 MachineBasicBlock *RSBBB = Fn->CreateMachineBasicBlock(LLVM_BB); 9072 MachineBasicBlock *SinkBB = Fn->CreateMachineBasicBlock(LLVM_BB); 9073 Fn->insert(BBI, RSBBB); 9074 Fn->insert(BBI, SinkBB); 9075 9076 unsigned int ABSSrcReg = MI.getOperand(1).getReg(); 9077 unsigned int ABSDstReg = MI.getOperand(0).getReg(); 9078 bool ABSSrcKIll = MI.getOperand(1).isKill(); 9079 bool isThumb2 = Subtarget->isThumb2(); 9080 MachineRegisterInfo &MRI = Fn->getRegInfo(); 9081 // In Thumb mode S must not be specified if source register is the SP or 9082 // PC and if destination register is the SP, so restrict register class 9083 unsigned NewRsbDstReg = 9084 MRI.createVirtualRegister(isThumb2 ? &ARM::rGPRRegClass : &ARM::GPRRegClass); 9085 9086 // Transfer the remainder of BB and its successor edges to sinkMBB. 9087 SinkBB->splice(SinkBB->begin(), BB, 9088 std::next(MachineBasicBlock::iterator(MI)), BB->end()); 9089 SinkBB->transferSuccessorsAndUpdatePHIs(BB); 9090 9091 BB->addSuccessor(RSBBB); 9092 BB->addSuccessor(SinkBB); 9093 9094 // fall through to SinkMBB 9095 RSBBB->addSuccessor(SinkBB); 9096 9097 // insert a cmp at the end of BB 9098 BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri)) 9099 .addReg(ABSSrcReg) 9100 .addImm(0) 9101 .add(predOps(ARMCC::AL)); 9102 9103 // insert a bcc with opposite CC to ARMCC::MI at the end of BB 9104 BuildMI(BB, dl, 9105 TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc)).addMBB(SinkBB) 9106 .addImm(ARMCC::getOppositeCondition(ARMCC::MI)).addReg(ARM::CPSR); 9107 9108 // insert rsbri in RSBBB 9109 // Note: BCC and rsbri will be converted into predicated rsbmi 9110 // by if-conversion pass 9111 BuildMI(*RSBBB, RSBBB->begin(), dl, 9112 TII->get(isThumb2 ? ARM::t2RSBri : ARM::RSBri), NewRsbDstReg) 9113 .addReg(ABSSrcReg, ABSSrcKIll ? RegState::Kill : 0) 9114 .addImm(0) 9115 .add(predOps(ARMCC::AL)) 9116 .add(condCodeOp()); 9117 9118 // insert PHI in SinkBB, 9119 // reuse ABSDstReg to not change uses of ABS instruction 9120 BuildMI(*SinkBB, SinkBB->begin(), dl, 9121 TII->get(ARM::PHI), ABSDstReg) 9122 .addReg(NewRsbDstReg).addMBB(RSBBB) 9123 .addReg(ABSSrcReg).addMBB(BB); 9124 9125 // remove ABS instruction 9126 MI.eraseFromParent(); 9127 9128 // return last added BB 9129 return SinkBB; 9130 } 9131 case ARM::COPY_STRUCT_BYVAL_I32: 9132 ++NumLoopByVals; 9133 return EmitStructByval(MI, BB); 9134 case ARM::WIN__CHKSTK: 9135 return EmitLowered__chkstk(MI, BB); 9136 case ARM::WIN__DBZCHK: 9137 return EmitLowered__dbzchk(MI, BB); 9138 } 9139 } 9140 9141 /// \brief Attaches vregs to MEMCPY that it will use as scratch registers 9142 /// when it is expanded into LDM/STM. This is done as a post-isel lowering 9143 /// instead of as a custom inserter because we need the use list from the SDNode. 9144 static void attachMEMCPYScratchRegs(const ARMSubtarget *Subtarget, 9145 MachineInstr &MI, const SDNode *Node) { 9146 bool isThumb1 = Subtarget->isThumb1Only(); 9147 9148 DebugLoc DL = MI.getDebugLoc(); 9149 MachineFunction *MF = MI.getParent()->getParent(); 9150 MachineRegisterInfo &MRI = MF->getRegInfo(); 9151 MachineInstrBuilder MIB(*MF, MI); 9152 9153 // If the new dst/src is unused mark it as dead. 9154 if (!Node->hasAnyUseOfValue(0)) { 9155 MI.getOperand(0).setIsDead(true); 9156 } 9157 if (!Node->hasAnyUseOfValue(1)) { 9158 MI.getOperand(1).setIsDead(true); 9159 } 9160 9161 // The MEMCPY both defines and kills the scratch registers. 9162 for (unsigned I = 0; I != MI.getOperand(4).getImm(); ++I) { 9163 unsigned TmpReg = MRI.createVirtualRegister(isThumb1 ? &ARM::tGPRRegClass 9164 : &ARM::GPRRegClass); 9165 MIB.addReg(TmpReg, RegState::Define|RegState::Dead); 9166 } 9167 } 9168 9169 void ARMTargetLowering::AdjustInstrPostInstrSelection(MachineInstr &MI, 9170 SDNode *Node) const { 9171 if (MI.getOpcode() == ARM::MEMCPY) { 9172 attachMEMCPYScratchRegs(Subtarget, MI, Node); 9173 return; 9174 } 9175 9176 const MCInstrDesc *MCID = &MI.getDesc(); 9177 // Adjust potentially 's' setting instructions after isel, i.e. ADC, SBC, RSB, 9178 // RSC. Coming out of isel, they have an implicit CPSR def, but the optional 9179 // operand is still set to noreg. If needed, set the optional operand's 9180 // register to CPSR, and remove the redundant implicit def. 9181 // 9182 // e.g. ADCS (..., CPSR<imp-def>) -> ADC (... opt:CPSR<def>). 9183 9184 // Rename pseudo opcodes. 9185 unsigned NewOpc = convertAddSubFlagsOpcode(MI.getOpcode()); 9186 unsigned ccOutIdx; 9187 if (NewOpc) { 9188 const ARMBaseInstrInfo *TII = Subtarget->getInstrInfo(); 9189 MCID = &TII->get(NewOpc); 9190 9191 assert(MCID->getNumOperands() == 9192 MI.getDesc().getNumOperands() + 5 - MI.getDesc().getSize() 9193 && "converted opcode should be the same except for cc_out" 9194 " (and, on Thumb1, pred)"); 9195 9196 MI.setDesc(*MCID); 9197 9198 // Add the optional cc_out operand 9199 MI.addOperand(MachineOperand::CreateReg(0, /*isDef=*/true)); 9200 9201 // On Thumb1, move all input operands to the end, then add the predicate 9202 if (Subtarget->isThumb1Only()) { 9203 for (unsigned c = MCID->getNumOperands() - 4; c--;) { 9204 MI.addOperand(MI.getOperand(1)); 9205 MI.RemoveOperand(1); 9206 } 9207 9208 // Restore the ties 9209 for (unsigned i = MI.getNumOperands(); i--;) { 9210 const MachineOperand& op = MI.getOperand(i); 9211 if (op.isReg() && op.isUse()) { 9212 int DefIdx = MCID->getOperandConstraint(i, MCOI::TIED_TO); 9213 if (DefIdx != -1) 9214 MI.tieOperands(DefIdx, i); 9215 } 9216 } 9217 9218 MI.addOperand(MachineOperand::CreateImm(ARMCC::AL)); 9219 MI.addOperand(MachineOperand::CreateReg(0, /*isDef=*/false)); 9220 ccOutIdx = 1; 9221 } else 9222 ccOutIdx = MCID->getNumOperands() - 1; 9223 } else 9224 ccOutIdx = MCID->getNumOperands() - 1; 9225 9226 // Any ARM instruction that sets the 's' bit should specify an optional 9227 // "cc_out" operand in the last operand position. 9228 if (!MI.hasOptionalDef() || !MCID->OpInfo[ccOutIdx].isOptionalDef()) { 9229 assert(!NewOpc && "Optional cc_out operand required"); 9230 return; 9231 } 9232 // Look for an implicit def of CPSR added by MachineInstr ctor. Remove it 9233 // since we already have an optional CPSR def. 9234 bool definesCPSR = false; 9235 bool deadCPSR = false; 9236 for (unsigned i = MCID->getNumOperands(), e = MI.getNumOperands(); i != e; 9237 ++i) { 9238 const MachineOperand &MO = MI.getOperand(i); 9239 if (MO.isReg() && MO.isDef() && MO.getReg() == ARM::CPSR) { 9240 definesCPSR = true; 9241 if (MO.isDead()) 9242 deadCPSR = true; 9243 MI.RemoveOperand(i); 9244 break; 9245 } 9246 } 9247 if (!definesCPSR) { 9248 assert(!NewOpc && "Optional cc_out operand required"); 9249 return; 9250 } 9251 assert(deadCPSR == !Node->hasAnyUseOfValue(1) && "inconsistent dead flag"); 9252 if (deadCPSR) { 9253 assert(!MI.getOperand(ccOutIdx).getReg() && 9254 "expect uninitialized optional cc_out operand"); 9255 // Thumb1 instructions must have the S bit even if the CPSR is dead. 9256 if (!Subtarget->isThumb1Only()) 9257 return; 9258 } 9259 9260 // If this instruction was defined with an optional CPSR def and its dag node 9261 // had a live implicit CPSR def, then activate the optional CPSR def. 9262 MachineOperand &MO = MI.getOperand(ccOutIdx); 9263 MO.setReg(ARM::CPSR); 9264 MO.setIsDef(true); 9265 } 9266 9267 //===----------------------------------------------------------------------===// 9268 // ARM Optimization Hooks 9269 //===----------------------------------------------------------------------===// 9270 9271 // Helper function that checks if N is a null or all ones constant. 9272 static inline bool isZeroOrAllOnes(SDValue N, bool AllOnes) { 9273 return AllOnes ? isAllOnesConstant(N) : isNullConstant(N); 9274 } 9275 9276 // Return true if N is conditionally 0 or all ones. 9277 // Detects these expressions where cc is an i1 value: 9278 // 9279 // (select cc 0, y) [AllOnes=0] 9280 // (select cc y, 0) [AllOnes=0] 9281 // (zext cc) [AllOnes=0] 9282 // (sext cc) [AllOnes=0/1] 9283 // (select cc -1, y) [AllOnes=1] 9284 // (select cc y, -1) [AllOnes=1] 9285 // 9286 // Invert is set when N is the null/all ones constant when CC is false. 9287 // OtherOp is set to the alternative value of N. 9288 static bool isConditionalZeroOrAllOnes(SDNode *N, bool AllOnes, 9289 SDValue &CC, bool &Invert, 9290 SDValue &OtherOp, 9291 SelectionDAG &DAG) { 9292 switch (N->getOpcode()) { 9293 default: return false; 9294 case ISD::SELECT: { 9295 CC = N->getOperand(0); 9296 SDValue N1 = N->getOperand(1); 9297 SDValue N2 = N->getOperand(2); 9298 if (isZeroOrAllOnes(N1, AllOnes)) { 9299 Invert = false; 9300 OtherOp = N2; 9301 return true; 9302 } 9303 if (isZeroOrAllOnes(N2, AllOnes)) { 9304 Invert = true; 9305 OtherOp = N1; 9306 return true; 9307 } 9308 return false; 9309 } 9310 case ISD::ZERO_EXTEND: 9311 // (zext cc) can never be the all ones value. 9312 if (AllOnes) 9313 return false; 9314 LLVM_FALLTHROUGH; 9315 case ISD::SIGN_EXTEND: { 9316 SDLoc dl(N); 9317 EVT VT = N->getValueType(0); 9318 CC = N->getOperand(0); 9319 if (CC.getValueType() != MVT::i1 || CC.getOpcode() != ISD::SETCC) 9320 return false; 9321 Invert = !AllOnes; 9322 if (AllOnes) 9323 // When looking for an AllOnes constant, N is an sext, and the 'other' 9324 // value is 0. 9325 OtherOp = DAG.getConstant(0, dl, VT); 9326 else if (N->getOpcode() == ISD::ZERO_EXTEND) 9327 // When looking for a 0 constant, N can be zext or sext. 9328 OtherOp = DAG.getConstant(1, dl, VT); 9329 else 9330 OtherOp = DAG.getConstant(APInt::getAllOnesValue(VT.getSizeInBits()), dl, 9331 VT); 9332 return true; 9333 } 9334 } 9335 } 9336 9337 // Combine a constant select operand into its use: 9338 // 9339 // (add (select cc, 0, c), x) -> (select cc, x, (add, x, c)) 9340 // (sub x, (select cc, 0, c)) -> (select cc, x, (sub, x, c)) 9341 // (and (select cc, -1, c), x) -> (select cc, x, (and, x, c)) [AllOnes=1] 9342 // (or (select cc, 0, c), x) -> (select cc, x, (or, x, c)) 9343 // (xor (select cc, 0, c), x) -> (select cc, x, (xor, x, c)) 9344 // 9345 // The transform is rejected if the select doesn't have a constant operand that 9346 // is null, or all ones when AllOnes is set. 9347 // 9348 // Also recognize sext/zext from i1: 9349 // 9350 // (add (zext cc), x) -> (select cc (add x, 1), x) 9351 // (add (sext cc), x) -> (select cc (add x, -1), x) 9352 // 9353 // These transformations eventually create predicated instructions. 9354 // 9355 // @param N The node to transform. 9356 // @param Slct The N operand that is a select. 9357 // @param OtherOp The other N operand (x above). 9358 // @param DCI Context. 9359 // @param AllOnes Require the select constant to be all ones instead of null. 9360 // @returns The new node, or SDValue() on failure. 9361 static 9362 SDValue combineSelectAndUse(SDNode *N, SDValue Slct, SDValue OtherOp, 9363 TargetLowering::DAGCombinerInfo &DCI, 9364 bool AllOnes = false) { 9365 SelectionDAG &DAG = DCI.DAG; 9366 EVT VT = N->getValueType(0); 9367 SDValue NonConstantVal; 9368 SDValue CCOp; 9369 bool SwapSelectOps; 9370 if (!isConditionalZeroOrAllOnes(Slct.getNode(), AllOnes, CCOp, SwapSelectOps, 9371 NonConstantVal, DAG)) 9372 return SDValue(); 9373 9374 // Slct is now know to be the desired identity constant when CC is true. 9375 SDValue TrueVal = OtherOp; 9376 SDValue FalseVal = DAG.getNode(N->getOpcode(), SDLoc(N), VT, 9377 OtherOp, NonConstantVal); 9378 // Unless SwapSelectOps says CC should be false. 9379 if (SwapSelectOps) 9380 std::swap(TrueVal, FalseVal); 9381 9382 return DAG.getNode(ISD::SELECT, SDLoc(N), VT, 9383 CCOp, TrueVal, FalseVal); 9384 } 9385 9386 // Attempt combineSelectAndUse on each operand of a commutative operator N. 9387 static 9388 SDValue combineSelectAndUseCommutative(SDNode *N, bool AllOnes, 9389 TargetLowering::DAGCombinerInfo &DCI) { 9390 SDValue N0 = N->getOperand(0); 9391 SDValue N1 = N->getOperand(1); 9392 if (N0.getNode()->hasOneUse()) 9393 if (SDValue Result = combineSelectAndUse(N, N0, N1, DCI, AllOnes)) 9394 return Result; 9395 if (N1.getNode()->hasOneUse()) 9396 if (SDValue Result = combineSelectAndUse(N, N1, N0, DCI, AllOnes)) 9397 return Result; 9398 return SDValue(); 9399 } 9400 9401 static bool IsVUZPShuffleNode(SDNode *N) { 9402 // VUZP shuffle node. 9403 if (N->getOpcode() == ARMISD::VUZP) 9404 return true; 9405 9406 // "VUZP" on i32 is an alias for VTRN. 9407 if (N->getOpcode() == ARMISD::VTRN && N->getValueType(0) == MVT::v2i32) 9408 return true; 9409 9410 return false; 9411 } 9412 9413 static SDValue AddCombineToVPADD(SDNode *N, SDValue N0, SDValue N1, 9414 TargetLowering::DAGCombinerInfo &DCI, 9415 const ARMSubtarget *Subtarget) { 9416 // Look for ADD(VUZP.0, VUZP.1). 9417 if (!IsVUZPShuffleNode(N0.getNode()) || N0.getNode() != N1.getNode() || 9418 N0 == N1) 9419 return SDValue(); 9420 9421 // Make sure the ADD is a 64-bit add; there is no 128-bit VPADD. 9422 if (!N->getValueType(0).is64BitVector()) 9423 return SDValue(); 9424 9425 // Generate vpadd. 9426 SelectionDAG &DAG = DCI.DAG; 9427 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 9428 SDLoc dl(N); 9429 SDNode *Unzip = N0.getNode(); 9430 EVT VT = N->getValueType(0); 9431 9432 SmallVector<SDValue, 8> Ops; 9433 Ops.push_back(DAG.getConstant(Intrinsic::arm_neon_vpadd, dl, 9434 TLI.getPointerTy(DAG.getDataLayout()))); 9435 Ops.push_back(Unzip->getOperand(0)); 9436 Ops.push_back(Unzip->getOperand(1)); 9437 9438 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT, Ops); 9439 } 9440 9441 static SDValue AddCombineVUZPToVPADDL(SDNode *N, SDValue N0, SDValue N1, 9442 TargetLowering::DAGCombinerInfo &DCI, 9443 const ARMSubtarget *Subtarget) { 9444 // Check for two extended operands. 9445 if (!(N0.getOpcode() == ISD::SIGN_EXTEND && 9446 N1.getOpcode() == ISD::SIGN_EXTEND) && 9447 !(N0.getOpcode() == ISD::ZERO_EXTEND && 9448 N1.getOpcode() == ISD::ZERO_EXTEND)) 9449 return SDValue(); 9450 9451 SDValue N00 = N0.getOperand(0); 9452 SDValue N10 = N1.getOperand(0); 9453 9454 // Look for ADD(SEXT(VUZP.0), SEXT(VUZP.1)) 9455 if (!IsVUZPShuffleNode(N00.getNode()) || N00.getNode() != N10.getNode() || 9456 N00 == N10) 9457 return SDValue(); 9458 9459 // We only recognize Q register paddl here; this can't be reached until 9460 // after type legalization. 9461 if (!N00.getValueType().is64BitVector() || 9462 !N0.getValueType().is128BitVector()) 9463 return SDValue(); 9464 9465 // Generate vpaddl. 9466 SelectionDAG &DAG = DCI.DAG; 9467 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 9468 SDLoc dl(N); 9469 EVT VT = N->getValueType(0); 9470 9471 SmallVector<SDValue, 8> Ops; 9472 // Form vpaddl.sN or vpaddl.uN depending on the kind of extension. 9473 unsigned Opcode; 9474 if (N0.getOpcode() == ISD::SIGN_EXTEND) 9475 Opcode = Intrinsic::arm_neon_vpaddls; 9476 else 9477 Opcode = Intrinsic::arm_neon_vpaddlu; 9478 Ops.push_back(DAG.getConstant(Opcode, dl, 9479 TLI.getPointerTy(DAG.getDataLayout()))); 9480 EVT ElemTy = N00.getValueType().getVectorElementType(); 9481 unsigned NumElts = VT.getVectorNumElements(); 9482 EVT ConcatVT = EVT::getVectorVT(*DAG.getContext(), ElemTy, NumElts * 2); 9483 SDValue Concat = DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), ConcatVT, 9484 N00.getOperand(0), N00.getOperand(1)); 9485 Ops.push_back(Concat); 9486 9487 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT, Ops); 9488 } 9489 9490 // FIXME: This function shouldn't be necessary; if we lower BUILD_VECTOR in 9491 // an appropriate manner, we end up with ADD(VUZP(ZEXT(N))), which is 9492 // much easier to match. 9493 static SDValue 9494 AddCombineBUILD_VECTORToVPADDL(SDNode *N, SDValue N0, SDValue N1, 9495 TargetLowering::DAGCombinerInfo &DCI, 9496 const ARMSubtarget *Subtarget) { 9497 // Only perform optimization if after legalize, and if NEON is available. We 9498 // also expected both operands to be BUILD_VECTORs. 9499 if (DCI.isBeforeLegalize() || !Subtarget->hasNEON() 9500 || N0.getOpcode() != ISD::BUILD_VECTOR 9501 || N1.getOpcode() != ISD::BUILD_VECTOR) 9502 return SDValue(); 9503 9504 // Check output type since VPADDL operand elements can only be 8, 16, or 32. 9505 EVT VT = N->getValueType(0); 9506 if (!VT.isInteger() || VT.getVectorElementType() == MVT::i64) 9507 return SDValue(); 9508 9509 // Check that the vector operands are of the right form. 9510 // N0 and N1 are BUILD_VECTOR nodes with N number of EXTRACT_VECTOR 9511 // operands, where N is the size of the formed vector. 9512 // Each EXTRACT_VECTOR should have the same input vector and odd or even 9513 // index such that we have a pair wise add pattern. 9514 9515 // Grab the vector that all EXTRACT_VECTOR nodes should be referencing. 9516 if (N0->getOperand(0)->getOpcode() != ISD::EXTRACT_VECTOR_ELT) 9517 return SDValue(); 9518 SDValue Vec = N0->getOperand(0)->getOperand(0); 9519 SDNode *V = Vec.getNode(); 9520 unsigned nextIndex = 0; 9521 9522 // For each operands to the ADD which are BUILD_VECTORs, 9523 // check to see if each of their operands are an EXTRACT_VECTOR with 9524 // the same vector and appropriate index. 9525 for (unsigned i = 0, e = N0->getNumOperands(); i != e; ++i) { 9526 if (N0->getOperand(i)->getOpcode() == ISD::EXTRACT_VECTOR_ELT 9527 && N1->getOperand(i)->getOpcode() == ISD::EXTRACT_VECTOR_ELT) { 9528 9529 SDValue ExtVec0 = N0->getOperand(i); 9530 SDValue ExtVec1 = N1->getOperand(i); 9531 9532 // First operand is the vector, verify its the same. 9533 if (V != ExtVec0->getOperand(0).getNode() || 9534 V != ExtVec1->getOperand(0).getNode()) 9535 return SDValue(); 9536 9537 // Second is the constant, verify its correct. 9538 ConstantSDNode *C0 = dyn_cast<ConstantSDNode>(ExtVec0->getOperand(1)); 9539 ConstantSDNode *C1 = dyn_cast<ConstantSDNode>(ExtVec1->getOperand(1)); 9540 9541 // For the constant, we want to see all the even or all the odd. 9542 if (!C0 || !C1 || C0->getZExtValue() != nextIndex 9543 || C1->getZExtValue() != nextIndex+1) 9544 return SDValue(); 9545 9546 // Increment index. 9547 nextIndex+=2; 9548 } else 9549 return SDValue(); 9550 } 9551 9552 // Don't generate vpaddl+vmovn; we'll match it to vpadd later. Also make sure 9553 // we're using the entire input vector, otherwise there's a size/legality 9554 // mismatch somewhere. 9555 if (nextIndex != Vec.getValueType().getVectorNumElements() || 9556 Vec.getValueType().getVectorElementType() == VT.getVectorElementType()) 9557 return SDValue(); 9558 9559 // Create VPADDL node. 9560 SelectionDAG &DAG = DCI.DAG; 9561 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 9562 9563 SDLoc dl(N); 9564 9565 // Build operand list. 9566 SmallVector<SDValue, 8> Ops; 9567 Ops.push_back(DAG.getConstant(Intrinsic::arm_neon_vpaddls, dl, 9568 TLI.getPointerTy(DAG.getDataLayout()))); 9569 9570 // Input is the vector. 9571 Ops.push_back(Vec); 9572 9573 // Get widened type and narrowed type. 9574 MVT widenType; 9575 unsigned numElem = VT.getVectorNumElements(); 9576 9577 EVT inputLaneType = Vec.getValueType().getVectorElementType(); 9578 switch (inputLaneType.getSimpleVT().SimpleTy) { 9579 case MVT::i8: widenType = MVT::getVectorVT(MVT::i16, numElem); break; 9580 case MVT::i16: widenType = MVT::getVectorVT(MVT::i32, numElem); break; 9581 case MVT::i32: widenType = MVT::getVectorVT(MVT::i64, numElem); break; 9582 default: 9583 llvm_unreachable("Invalid vector element type for padd optimization."); 9584 } 9585 9586 SDValue tmp = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, widenType, Ops); 9587 unsigned ExtOp = VT.bitsGT(tmp.getValueType()) ? ISD::ANY_EXTEND : ISD::TRUNCATE; 9588 return DAG.getNode(ExtOp, dl, VT, tmp); 9589 } 9590 9591 static SDValue findMUL_LOHI(SDValue V) { 9592 if (V->getOpcode() == ISD::UMUL_LOHI || 9593 V->getOpcode() == ISD::SMUL_LOHI) 9594 return V; 9595 return SDValue(); 9596 } 9597 9598 static SDValue AddCombineTo64BitSMLAL16(SDNode *AddcNode, SDNode *AddeNode, 9599 TargetLowering::DAGCombinerInfo &DCI, 9600 const ARMSubtarget *Subtarget) { 9601 9602 if (Subtarget->isThumb()) { 9603 if (!Subtarget->hasDSP()) 9604 return SDValue(); 9605 } else if (!Subtarget->hasV5TEOps()) 9606 return SDValue(); 9607 9608 // SMLALBB, SMLALBT, SMLALTB, SMLALTT multiply two 16-bit values and 9609 // accumulates the product into a 64-bit value. The 16-bit values will 9610 // be sign extended somehow or SRA'd into 32-bit values 9611 // (addc (adde (mul 16bit, 16bit), lo), hi) 9612 SDValue Mul = AddcNode->getOperand(0); 9613 SDValue Lo = AddcNode->getOperand(1); 9614 if (Mul.getOpcode() != ISD::MUL) { 9615 Lo = AddcNode->getOperand(0); 9616 Mul = AddcNode->getOperand(1); 9617 if (Mul.getOpcode() != ISD::MUL) 9618 return SDValue(); 9619 } 9620 9621 SDValue SRA = AddeNode->getOperand(0); 9622 SDValue Hi = AddeNode->getOperand(1); 9623 if (SRA.getOpcode() != ISD::SRA) { 9624 SRA = AddeNode->getOperand(1); 9625 Hi = AddeNode->getOperand(0); 9626 if (SRA.getOpcode() != ISD::SRA) 9627 return SDValue(); 9628 } 9629 if (auto Const = dyn_cast<ConstantSDNode>(SRA.getOperand(1))) { 9630 if (Const->getZExtValue() != 31) 9631 return SDValue(); 9632 } else 9633 return SDValue(); 9634 9635 if (SRA.getOperand(0) != Mul) 9636 return SDValue(); 9637 9638 SelectionDAG &DAG = DCI.DAG; 9639 SDLoc dl(AddcNode); 9640 unsigned Opcode = 0; 9641 SDValue Op0; 9642 SDValue Op1; 9643 9644 if (isS16(Mul.getOperand(0), DAG) && isS16(Mul.getOperand(1), DAG)) { 9645 Opcode = ARMISD::SMLALBB; 9646 Op0 = Mul.getOperand(0); 9647 Op1 = Mul.getOperand(1); 9648 } else if (isS16(Mul.getOperand(0), DAG) && isSRA16(Mul.getOperand(1))) { 9649 Opcode = ARMISD::SMLALBT; 9650 Op0 = Mul.getOperand(0); 9651 Op1 = Mul.getOperand(1).getOperand(0); 9652 } else if (isSRA16(Mul.getOperand(0)) && isS16(Mul.getOperand(1), DAG)) { 9653 Opcode = ARMISD::SMLALTB; 9654 Op0 = Mul.getOperand(0).getOperand(0); 9655 Op1 = Mul.getOperand(1); 9656 } else if (isSRA16(Mul.getOperand(0)) && isSRA16(Mul.getOperand(1))) { 9657 Opcode = ARMISD::SMLALTT; 9658 Op0 = Mul->getOperand(0).getOperand(0); 9659 Op1 = Mul->getOperand(1).getOperand(0); 9660 } 9661 9662 if (!Op0 || !Op1) 9663 return SDValue(); 9664 9665 SDValue SMLAL = DAG.getNode(Opcode, dl, DAG.getVTList(MVT::i32, MVT::i32), 9666 Op0, Op1, Lo, Hi); 9667 // Replace the ADDs' nodes uses by the MLA node's values. 9668 SDValue HiMLALResult(SMLAL.getNode(), 1); 9669 SDValue LoMLALResult(SMLAL.getNode(), 0); 9670 9671 DAG.ReplaceAllUsesOfValueWith(SDValue(AddcNode, 0), LoMLALResult); 9672 DAG.ReplaceAllUsesOfValueWith(SDValue(AddeNode, 0), HiMLALResult); 9673 9674 // Return original node to notify the driver to stop replacing. 9675 SDValue resNode(AddcNode, 0); 9676 return resNode; 9677 } 9678 9679 static SDValue AddCombineTo64bitMLAL(SDNode *AddeNode, 9680 TargetLowering::DAGCombinerInfo &DCI, 9681 const ARMSubtarget *Subtarget) { 9682 // Look for multiply add opportunities. 9683 // The pattern is a ISD::UMUL_LOHI followed by two add nodes, where 9684 // each add nodes consumes a value from ISD::UMUL_LOHI and there is 9685 // a glue link from the first add to the second add. 9686 // If we find this pattern, we can replace the U/SMUL_LOHI, ADDC, and ADDE by 9687 // a S/UMLAL instruction. 9688 // UMUL_LOHI 9689 // / :lo \ :hi 9690 // / \ [no multiline comment] 9691 // loAdd -> ADDE | 9692 // \ :glue / 9693 // \ / 9694 // ADDC <- hiAdd 9695 // 9696 assert(AddeNode->getOpcode() == ARMISD::ADDE && "Expect an ADDE"); 9697 9698 assert(AddeNode->getNumOperands() == 3 && 9699 AddeNode->getOperand(2).getValueType() == MVT::i32 && 9700 "ADDE node has the wrong inputs"); 9701 9702 // Check that we have a glued ADDC node. 9703 SDNode* AddcNode = AddeNode->getOperand(2).getNode(); 9704 if (AddcNode->getOpcode() != ARMISD::ADDC) 9705 return SDValue(); 9706 9707 SDValue AddcOp0 = AddcNode->getOperand(0); 9708 SDValue AddcOp1 = AddcNode->getOperand(1); 9709 9710 // Check if the two operands are from the same mul_lohi node. 9711 if (AddcOp0.getNode() == AddcOp1.getNode()) 9712 return SDValue(); 9713 9714 assert(AddcNode->getNumValues() == 2 && 9715 AddcNode->getValueType(0) == MVT::i32 && 9716 "Expect ADDC with two result values. First: i32"); 9717 9718 // Check that the ADDC adds the low result of the S/UMUL_LOHI. If not, it 9719 // maybe a SMLAL which multiplies two 16-bit values. 9720 if (AddcOp0->getOpcode() != ISD::UMUL_LOHI && 9721 AddcOp0->getOpcode() != ISD::SMUL_LOHI && 9722 AddcOp1->getOpcode() != ISD::UMUL_LOHI && 9723 AddcOp1->getOpcode() != ISD::SMUL_LOHI) 9724 return AddCombineTo64BitSMLAL16(AddcNode, AddeNode, DCI, Subtarget); 9725 9726 // Check for the triangle shape. 9727 SDValue AddeOp0 = AddeNode->getOperand(0); 9728 SDValue AddeOp1 = AddeNode->getOperand(1); 9729 9730 // Make sure that the ADDE operands are not coming from the same node. 9731 if (AddeOp0.getNode() == AddeOp1.getNode()) 9732 return SDValue(); 9733 9734 // Find the MUL_LOHI node walking up ADDE's operands. 9735 bool IsLeftOperandMUL = false; 9736 SDValue MULOp = findMUL_LOHI(AddeOp0); 9737 if (MULOp == SDValue()) 9738 MULOp = findMUL_LOHI(AddeOp1); 9739 else 9740 IsLeftOperandMUL = true; 9741 if (MULOp == SDValue()) 9742 return SDValue(); 9743 9744 // Figure out the right opcode. 9745 unsigned Opc = MULOp->getOpcode(); 9746 unsigned FinalOpc = (Opc == ISD::SMUL_LOHI) ? ARMISD::SMLAL : ARMISD::UMLAL; 9747 9748 // Figure out the high and low input values to the MLAL node. 9749 SDValue* HiAdd = nullptr; 9750 SDValue* LoMul = nullptr; 9751 SDValue* LowAdd = nullptr; 9752 9753 // Ensure that ADDE is from high result of ISD::SMUL_LOHI. 9754 if ((AddeOp0 != MULOp.getValue(1)) && (AddeOp1 != MULOp.getValue(1))) 9755 return SDValue(); 9756 9757 if (IsLeftOperandMUL) 9758 HiAdd = &AddeOp1; 9759 else 9760 HiAdd = &AddeOp0; 9761 9762 9763 // Ensure that LoMul and LowAdd are taken from correct ISD::SMUL_LOHI node 9764 // whose low result is fed to the ADDC we are checking. 9765 9766 if (AddcOp0 == MULOp.getValue(0)) { 9767 LoMul = &AddcOp0; 9768 LowAdd = &AddcOp1; 9769 } 9770 if (AddcOp1 == MULOp.getValue(0)) { 9771 LoMul = &AddcOp1; 9772 LowAdd = &AddcOp0; 9773 } 9774 9775 if (!LoMul) 9776 return SDValue(); 9777 9778 // Create the merged node. 9779 SelectionDAG &DAG = DCI.DAG; 9780 9781 // Build operand list. 9782 SmallVector<SDValue, 8> Ops; 9783 Ops.push_back(LoMul->getOperand(0)); 9784 Ops.push_back(LoMul->getOperand(1)); 9785 Ops.push_back(*LowAdd); 9786 Ops.push_back(*HiAdd); 9787 9788 SDValue MLALNode = DAG.getNode(FinalOpc, SDLoc(AddcNode), 9789 DAG.getVTList(MVT::i32, MVT::i32), Ops); 9790 9791 // Replace the ADDs' nodes uses by the MLA node's values. 9792 SDValue HiMLALResult(MLALNode.getNode(), 1); 9793 DAG.ReplaceAllUsesOfValueWith(SDValue(AddeNode, 0), HiMLALResult); 9794 9795 SDValue LoMLALResult(MLALNode.getNode(), 0); 9796 DAG.ReplaceAllUsesOfValueWith(SDValue(AddcNode, 0), LoMLALResult); 9797 9798 // Return original node to notify the driver to stop replacing. 9799 return SDValue(AddeNode, 0); 9800 } 9801 9802 static SDValue AddCombineTo64bitUMAAL(SDNode *AddeNode, 9803 TargetLowering::DAGCombinerInfo &DCI, 9804 const ARMSubtarget *Subtarget) { 9805 // UMAAL is similar to UMLAL except that it adds two unsigned values. 9806 // While trying to combine for the other MLAL nodes, first search for the 9807 // chance to use UMAAL. Check if Addc uses a node which has already 9808 // been combined into a UMLAL. The other pattern is UMLAL using Addc/Adde 9809 // as the addend, and it's handled in PerformUMLALCombine. 9810 9811 if (!Subtarget->hasV6Ops() || !Subtarget->hasDSP()) 9812 return AddCombineTo64bitMLAL(AddeNode, DCI, Subtarget); 9813 9814 // Check that we have a glued ADDC node. 9815 SDNode* AddcNode = AddeNode->getOperand(2).getNode(); 9816 if (AddcNode->getOpcode() != ARMISD::ADDC) 9817 return SDValue(); 9818 9819 // Find the converted UMAAL or quit if it doesn't exist. 9820 SDNode *UmlalNode = nullptr; 9821 SDValue AddHi; 9822 if (AddcNode->getOperand(0).getOpcode() == ARMISD::UMLAL) { 9823 UmlalNode = AddcNode->getOperand(0).getNode(); 9824 AddHi = AddcNode->getOperand(1); 9825 } else if (AddcNode->getOperand(1).getOpcode() == ARMISD::UMLAL) { 9826 UmlalNode = AddcNode->getOperand(1).getNode(); 9827 AddHi = AddcNode->getOperand(0); 9828 } else { 9829 return AddCombineTo64bitMLAL(AddeNode, DCI, Subtarget); 9830 } 9831 9832 // The ADDC should be glued to an ADDE node, which uses the same UMLAL as 9833 // the ADDC as well as Zero. 9834 if (!isNullConstant(UmlalNode->getOperand(3))) 9835 return SDValue(); 9836 9837 if ((isNullConstant(AddeNode->getOperand(0)) && 9838 AddeNode->getOperand(1).getNode() == UmlalNode) || 9839 (AddeNode->getOperand(0).getNode() == UmlalNode && 9840 isNullConstant(AddeNode->getOperand(1)))) { 9841 9842 SelectionDAG &DAG = DCI.DAG; 9843 SDValue Ops[] = { UmlalNode->getOperand(0), UmlalNode->getOperand(1), 9844 UmlalNode->getOperand(2), AddHi }; 9845 SDValue UMAAL = DAG.getNode(ARMISD::UMAAL, SDLoc(AddcNode), 9846 DAG.getVTList(MVT::i32, MVT::i32), Ops); 9847 9848 // Replace the ADDs' nodes uses by the UMAAL node's values. 9849 DAG.ReplaceAllUsesOfValueWith(SDValue(AddeNode, 0), SDValue(UMAAL.getNode(), 1)); 9850 DAG.ReplaceAllUsesOfValueWith(SDValue(AddcNode, 0), SDValue(UMAAL.getNode(), 0)); 9851 9852 // Return original node to notify the driver to stop replacing. 9853 return SDValue(AddeNode, 0); 9854 } 9855 return SDValue(); 9856 } 9857 9858 static SDValue PerformUMLALCombine(SDNode *N, SelectionDAG &DAG, 9859 const ARMSubtarget *Subtarget) { 9860 if (!Subtarget->hasV6Ops() || !Subtarget->hasDSP()) 9861 return SDValue(); 9862 9863 // Check that we have a pair of ADDC and ADDE as operands. 9864 // Both addends of the ADDE must be zero. 9865 SDNode* AddcNode = N->getOperand(2).getNode(); 9866 SDNode* AddeNode = N->getOperand(3).getNode(); 9867 if ((AddcNode->getOpcode() == ARMISD::ADDC) && 9868 (AddeNode->getOpcode() == ARMISD::ADDE) && 9869 isNullConstant(AddeNode->getOperand(0)) && 9870 isNullConstant(AddeNode->getOperand(1)) && 9871 (AddeNode->getOperand(2).getNode() == AddcNode)) 9872 return DAG.getNode(ARMISD::UMAAL, SDLoc(N), 9873 DAG.getVTList(MVT::i32, MVT::i32), 9874 {N->getOperand(0), N->getOperand(1), 9875 AddcNode->getOperand(0), AddcNode->getOperand(1)}); 9876 else 9877 return SDValue(); 9878 } 9879 9880 static SDValue PerformAddcSubcCombine(SDNode *N, SelectionDAG &DAG, 9881 const ARMSubtarget *Subtarget) { 9882 if (Subtarget->isThumb1Only()) { 9883 SDValue RHS = N->getOperand(1); 9884 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS)) { 9885 int32_t imm = C->getSExtValue(); 9886 if (imm < 0 && imm > INT_MIN) { 9887 SDLoc DL(N); 9888 RHS = DAG.getConstant(-imm, DL, MVT::i32); 9889 unsigned Opcode = (N->getOpcode() == ARMISD::ADDC) ? ARMISD::SUBC 9890 : ARMISD::ADDC; 9891 return DAG.getNode(Opcode, DL, N->getVTList(), N->getOperand(0), RHS); 9892 } 9893 } 9894 } 9895 return SDValue(); 9896 } 9897 9898 static SDValue PerformAddeSubeCombine(SDNode *N, SelectionDAG &DAG, 9899 const ARMSubtarget *Subtarget) { 9900 if (Subtarget->isThumb1Only()) { 9901 SDValue RHS = N->getOperand(1); 9902 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS)) { 9903 int64_t imm = C->getSExtValue(); 9904 if (imm < 0) { 9905 SDLoc DL(N); 9906 9907 // The with-carry-in form matches bitwise not instead of the negation. 9908 // Effectively, the inverse interpretation of the carry flag already 9909 // accounts for part of the negation. 9910 RHS = DAG.getConstant(~imm, DL, MVT::i32); 9911 9912 unsigned Opcode = (N->getOpcode() == ARMISD::ADDE) ? ARMISD::SUBE 9913 : ARMISD::ADDE; 9914 return DAG.getNode(Opcode, DL, N->getVTList(), 9915 N->getOperand(0), RHS, N->getOperand(2)); 9916 } 9917 } 9918 } 9919 return SDValue(); 9920 } 9921 9922 /// PerformADDECombine - Target-specific dag combine transform from 9923 /// ARMISD::ADDC, ARMISD::ADDE, and ISD::MUL_LOHI to MLAL or 9924 /// ARMISD::ADDC, ARMISD::ADDE and ARMISD::UMLAL to ARMISD::UMAAL 9925 static SDValue PerformADDECombine(SDNode *N, 9926 TargetLowering::DAGCombinerInfo &DCI, 9927 const ARMSubtarget *Subtarget) { 9928 // Only ARM and Thumb2 support UMLAL/SMLAL. 9929 if (Subtarget->isThumb1Only()) 9930 return PerformAddeSubeCombine(N, DCI.DAG, Subtarget); 9931 9932 // Only perform the checks after legalize when the pattern is available. 9933 if (DCI.isBeforeLegalize()) return SDValue(); 9934 9935 return AddCombineTo64bitUMAAL(N, DCI, Subtarget); 9936 } 9937 9938 /// PerformADDCombineWithOperands - Try DAG combinations for an ADD with 9939 /// operands N0 and N1. This is a helper for PerformADDCombine that is 9940 /// called with the default operands, and if that fails, with commuted 9941 /// operands. 9942 static SDValue PerformADDCombineWithOperands(SDNode *N, SDValue N0, SDValue N1, 9943 TargetLowering::DAGCombinerInfo &DCI, 9944 const ARMSubtarget *Subtarget){ 9945 // Attempt to create vpadd for this add. 9946 if (SDValue Result = AddCombineToVPADD(N, N0, N1, DCI, Subtarget)) 9947 return Result; 9948 9949 // Attempt to create vpaddl for this add. 9950 if (SDValue Result = AddCombineVUZPToVPADDL(N, N0, N1, DCI, Subtarget)) 9951 return Result; 9952 if (SDValue Result = AddCombineBUILD_VECTORToVPADDL(N, N0, N1, DCI, 9953 Subtarget)) 9954 return Result; 9955 9956 // fold (add (select cc, 0, c), x) -> (select cc, x, (add, x, c)) 9957 if (N0.getNode()->hasOneUse()) 9958 if (SDValue Result = combineSelectAndUse(N, N0, N1, DCI)) 9959 return Result; 9960 return SDValue(); 9961 } 9962 9963 /// PerformADDCombine - Target-specific dag combine xforms for ISD::ADD. 9964 /// 9965 static SDValue PerformADDCombine(SDNode *N, 9966 TargetLowering::DAGCombinerInfo &DCI, 9967 const ARMSubtarget *Subtarget) { 9968 SDValue N0 = N->getOperand(0); 9969 SDValue N1 = N->getOperand(1); 9970 9971 // First try with the default operand order. 9972 if (SDValue Result = PerformADDCombineWithOperands(N, N0, N1, DCI, Subtarget)) 9973 return Result; 9974 9975 // If that didn't work, try again with the operands commuted. 9976 return PerformADDCombineWithOperands(N, N1, N0, DCI, Subtarget); 9977 } 9978 9979 /// PerformSUBCombine - Target-specific dag combine xforms for ISD::SUB. 9980 /// 9981 static SDValue PerformSUBCombine(SDNode *N, 9982 TargetLowering::DAGCombinerInfo &DCI) { 9983 SDValue N0 = N->getOperand(0); 9984 SDValue N1 = N->getOperand(1); 9985 9986 // fold (sub x, (select cc, 0, c)) -> (select cc, x, (sub, x, c)) 9987 if (N1.getNode()->hasOneUse()) 9988 if (SDValue Result = combineSelectAndUse(N, N1, N0, DCI)) 9989 return Result; 9990 9991 return SDValue(); 9992 } 9993 9994 /// PerformVMULCombine 9995 /// Distribute (A + B) * C to (A * C) + (B * C) to take advantage of the 9996 /// special multiplier accumulator forwarding. 9997 /// vmul d3, d0, d2 9998 /// vmla d3, d1, d2 9999 /// is faster than 10000 /// vadd d3, d0, d1 10001 /// vmul d3, d3, d2 10002 // However, for (A + B) * (A + B), 10003 // vadd d2, d0, d1 10004 // vmul d3, d0, d2 10005 // vmla d3, d1, d2 10006 // is slower than 10007 // vadd d2, d0, d1 10008 // vmul d3, d2, d2 10009 static SDValue PerformVMULCombine(SDNode *N, 10010 TargetLowering::DAGCombinerInfo &DCI, 10011 const ARMSubtarget *Subtarget) { 10012 if (!Subtarget->hasVMLxForwarding()) 10013 return SDValue(); 10014 10015 SelectionDAG &DAG = DCI.DAG; 10016 SDValue N0 = N->getOperand(0); 10017 SDValue N1 = N->getOperand(1); 10018 unsigned Opcode = N0.getOpcode(); 10019 if (Opcode != ISD::ADD && Opcode != ISD::SUB && 10020 Opcode != ISD::FADD && Opcode != ISD::FSUB) { 10021 Opcode = N1.getOpcode(); 10022 if (Opcode != ISD::ADD && Opcode != ISD::SUB && 10023 Opcode != ISD::FADD && Opcode != ISD::FSUB) 10024 return SDValue(); 10025 std::swap(N0, N1); 10026 } 10027 10028 if (N0 == N1) 10029 return SDValue(); 10030 10031 EVT VT = N->getValueType(0); 10032 SDLoc DL(N); 10033 SDValue N00 = N0->getOperand(0); 10034 SDValue N01 = N0->getOperand(1); 10035 return DAG.getNode(Opcode, DL, VT, 10036 DAG.getNode(ISD::MUL, DL, VT, N00, N1), 10037 DAG.getNode(ISD::MUL, DL, VT, N01, N1)); 10038 } 10039 10040 static SDValue PerformMULCombine(SDNode *N, 10041 TargetLowering::DAGCombinerInfo &DCI, 10042 const ARMSubtarget *Subtarget) { 10043 SelectionDAG &DAG = DCI.DAG; 10044 10045 if (Subtarget->isThumb1Only()) 10046 return SDValue(); 10047 10048 if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer()) 10049 return SDValue(); 10050 10051 EVT VT = N->getValueType(0); 10052 if (VT.is64BitVector() || VT.is128BitVector()) 10053 return PerformVMULCombine(N, DCI, Subtarget); 10054 if (VT != MVT::i32) 10055 return SDValue(); 10056 10057 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(1)); 10058 if (!C) 10059 return SDValue(); 10060 10061 int64_t MulAmt = C->getSExtValue(); 10062 unsigned ShiftAmt = countTrailingZeros<uint64_t>(MulAmt); 10063 10064 ShiftAmt = ShiftAmt & (32 - 1); 10065 SDValue V = N->getOperand(0); 10066 SDLoc DL(N); 10067 10068 SDValue Res; 10069 MulAmt >>= ShiftAmt; 10070 10071 if (MulAmt >= 0) { 10072 if (isPowerOf2_32(MulAmt - 1)) { 10073 // (mul x, 2^N + 1) => (add (shl x, N), x) 10074 Res = DAG.getNode(ISD::ADD, DL, VT, 10075 V, 10076 DAG.getNode(ISD::SHL, DL, VT, 10077 V, 10078 DAG.getConstant(Log2_32(MulAmt - 1), DL, 10079 MVT::i32))); 10080 } else if (isPowerOf2_32(MulAmt + 1)) { 10081 // (mul x, 2^N - 1) => (sub (shl x, N), x) 10082 Res = DAG.getNode(ISD::SUB, DL, VT, 10083 DAG.getNode(ISD::SHL, DL, VT, 10084 V, 10085 DAG.getConstant(Log2_32(MulAmt + 1), DL, 10086 MVT::i32)), 10087 V); 10088 } else 10089 return SDValue(); 10090 } else { 10091 uint64_t MulAmtAbs = -MulAmt; 10092 if (isPowerOf2_32(MulAmtAbs + 1)) { 10093 // (mul x, -(2^N - 1)) => (sub x, (shl x, N)) 10094 Res = DAG.getNode(ISD::SUB, DL, VT, 10095 V, 10096 DAG.getNode(ISD::SHL, DL, VT, 10097 V, 10098 DAG.getConstant(Log2_32(MulAmtAbs + 1), DL, 10099 MVT::i32))); 10100 } else if (isPowerOf2_32(MulAmtAbs - 1)) { 10101 // (mul x, -(2^N + 1)) => - (add (shl x, N), x) 10102 Res = DAG.getNode(ISD::ADD, DL, VT, 10103 V, 10104 DAG.getNode(ISD::SHL, DL, VT, 10105 V, 10106 DAG.getConstant(Log2_32(MulAmtAbs - 1), DL, 10107 MVT::i32))); 10108 Res = DAG.getNode(ISD::SUB, DL, VT, 10109 DAG.getConstant(0, DL, MVT::i32), Res); 10110 10111 } else 10112 return SDValue(); 10113 } 10114 10115 if (ShiftAmt != 0) 10116 Res = DAG.getNode(ISD::SHL, DL, VT, 10117 Res, DAG.getConstant(ShiftAmt, DL, MVT::i32)); 10118 10119 // Do not add new nodes to DAG combiner worklist. 10120 DCI.CombineTo(N, Res, false); 10121 return SDValue(); 10122 } 10123 10124 static SDValue PerformANDCombine(SDNode *N, 10125 TargetLowering::DAGCombinerInfo &DCI, 10126 const ARMSubtarget *Subtarget) { 10127 // Attempt to use immediate-form VBIC 10128 BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(N->getOperand(1)); 10129 SDLoc dl(N); 10130 EVT VT = N->getValueType(0); 10131 SelectionDAG &DAG = DCI.DAG; 10132 10133 if(!DAG.getTargetLoweringInfo().isTypeLegal(VT)) 10134 return SDValue(); 10135 10136 APInt SplatBits, SplatUndef; 10137 unsigned SplatBitSize; 10138 bool HasAnyUndefs; 10139 if (BVN && 10140 BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs)) { 10141 if (SplatBitSize <= 64) { 10142 EVT VbicVT; 10143 SDValue Val = isNEONModifiedImm((~SplatBits).getZExtValue(), 10144 SplatUndef.getZExtValue(), SplatBitSize, 10145 DAG, dl, VbicVT, VT.is128BitVector(), 10146 OtherModImm); 10147 if (Val.getNode()) { 10148 SDValue Input = 10149 DAG.getNode(ISD::BITCAST, dl, VbicVT, N->getOperand(0)); 10150 SDValue Vbic = DAG.getNode(ARMISD::VBICIMM, dl, VbicVT, Input, Val); 10151 return DAG.getNode(ISD::BITCAST, dl, VT, Vbic); 10152 } 10153 } 10154 } 10155 10156 if (!Subtarget->isThumb1Only()) { 10157 // fold (and (select cc, -1, c), x) -> (select cc, x, (and, x, c)) 10158 if (SDValue Result = combineSelectAndUseCommutative(N, true, DCI)) 10159 return Result; 10160 } 10161 10162 return SDValue(); 10163 } 10164 10165 // Try combining OR nodes to SMULWB, SMULWT. 10166 static SDValue PerformORCombineToSMULWBT(SDNode *OR, 10167 TargetLowering::DAGCombinerInfo &DCI, 10168 const ARMSubtarget *Subtarget) { 10169 if (!Subtarget->hasV6Ops() || 10170 (Subtarget->isThumb() && 10171 (!Subtarget->hasThumb2() || !Subtarget->hasDSP()))) 10172 return SDValue(); 10173 10174 SDValue SRL = OR->getOperand(0); 10175 SDValue SHL = OR->getOperand(1); 10176 10177 if (SRL.getOpcode() != ISD::SRL || SHL.getOpcode() != ISD::SHL) { 10178 SRL = OR->getOperand(1); 10179 SHL = OR->getOperand(0); 10180 } 10181 if (!isSRL16(SRL) || !isSHL16(SHL)) 10182 return SDValue(); 10183 10184 // The first operands to the shifts need to be the two results from the 10185 // same smul_lohi node. 10186 if ((SRL.getOperand(0).getNode() != SHL.getOperand(0).getNode()) || 10187 SRL.getOperand(0).getOpcode() != ISD::SMUL_LOHI) 10188 return SDValue(); 10189 10190 SDNode *SMULLOHI = SRL.getOperand(0).getNode(); 10191 if (SRL.getOperand(0) != SDValue(SMULLOHI, 0) || 10192 SHL.getOperand(0) != SDValue(SMULLOHI, 1)) 10193 return SDValue(); 10194 10195 // Now we have: 10196 // (or (srl (smul_lohi ?, ?), 16), (shl (smul_lohi ?, ?), 16))) 10197 // For SMUL[B|T] smul_lohi will take a 32-bit and a 16-bit arguments. 10198 // For SMUWB the 16-bit value will signed extended somehow. 10199 // For SMULWT only the SRA is required. 10200 // Check both sides of SMUL_LOHI 10201 SDValue OpS16 = SMULLOHI->getOperand(0); 10202 SDValue OpS32 = SMULLOHI->getOperand(1); 10203 10204 SelectionDAG &DAG = DCI.DAG; 10205 if (!isS16(OpS16, DAG) && !isSRA16(OpS16)) { 10206 OpS16 = OpS32; 10207 OpS32 = SMULLOHI->getOperand(0); 10208 } 10209 10210 SDLoc dl(OR); 10211 unsigned Opcode = 0; 10212 if (isS16(OpS16, DAG)) 10213 Opcode = ARMISD::SMULWB; 10214 else if (isSRA16(OpS16)) { 10215 Opcode = ARMISD::SMULWT; 10216 OpS16 = OpS16->getOperand(0); 10217 } 10218 else 10219 return SDValue(); 10220 10221 SDValue Res = DAG.getNode(Opcode, dl, MVT::i32, OpS32, OpS16); 10222 DAG.ReplaceAllUsesOfValueWith(SDValue(OR, 0), Res); 10223 return SDValue(OR, 0); 10224 } 10225 10226 /// PerformORCombine - Target-specific dag combine xforms for ISD::OR 10227 static SDValue PerformORCombine(SDNode *N, 10228 TargetLowering::DAGCombinerInfo &DCI, 10229 const ARMSubtarget *Subtarget) { 10230 // Attempt to use immediate-form VORR 10231 BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(N->getOperand(1)); 10232 SDLoc dl(N); 10233 EVT VT = N->getValueType(0); 10234 SelectionDAG &DAG = DCI.DAG; 10235 10236 if(!DAG.getTargetLoweringInfo().isTypeLegal(VT)) 10237 return SDValue(); 10238 10239 APInt SplatBits, SplatUndef; 10240 unsigned SplatBitSize; 10241 bool HasAnyUndefs; 10242 if (BVN && Subtarget->hasNEON() && 10243 BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs)) { 10244 if (SplatBitSize <= 64) { 10245 EVT VorrVT; 10246 SDValue Val = isNEONModifiedImm(SplatBits.getZExtValue(), 10247 SplatUndef.getZExtValue(), SplatBitSize, 10248 DAG, dl, VorrVT, VT.is128BitVector(), 10249 OtherModImm); 10250 if (Val.getNode()) { 10251 SDValue Input = 10252 DAG.getNode(ISD::BITCAST, dl, VorrVT, N->getOperand(0)); 10253 SDValue Vorr = DAG.getNode(ARMISD::VORRIMM, dl, VorrVT, Input, Val); 10254 return DAG.getNode(ISD::BITCAST, dl, VT, Vorr); 10255 } 10256 } 10257 } 10258 10259 if (!Subtarget->isThumb1Only()) { 10260 // fold (or (select cc, 0, c), x) -> (select cc, x, (or, x, c)) 10261 if (SDValue Result = combineSelectAndUseCommutative(N, false, DCI)) 10262 return Result; 10263 if (SDValue Result = PerformORCombineToSMULWBT(N, DCI, Subtarget)) 10264 return Result; 10265 } 10266 10267 // The code below optimizes (or (and X, Y), Z). 10268 // The AND operand needs to have a single user to make these optimizations 10269 // profitable. 10270 SDValue N0 = N->getOperand(0); 10271 if (N0.getOpcode() != ISD::AND || !N0.hasOneUse()) 10272 return SDValue(); 10273 SDValue N1 = N->getOperand(1); 10274 10275 // (or (and B, A), (and C, ~A)) => (VBSL A, B, C) when A is a constant. 10276 if (Subtarget->hasNEON() && N1.getOpcode() == ISD::AND && VT.isVector() && 10277 DAG.getTargetLoweringInfo().isTypeLegal(VT)) { 10278 APInt SplatUndef; 10279 unsigned SplatBitSize; 10280 bool HasAnyUndefs; 10281 10282 APInt SplatBits0, SplatBits1; 10283 BuildVectorSDNode *BVN0 = dyn_cast<BuildVectorSDNode>(N0->getOperand(1)); 10284 BuildVectorSDNode *BVN1 = dyn_cast<BuildVectorSDNode>(N1->getOperand(1)); 10285 // Ensure that the second operand of both ands are constants 10286 if (BVN0 && BVN0->isConstantSplat(SplatBits0, SplatUndef, SplatBitSize, 10287 HasAnyUndefs) && !HasAnyUndefs) { 10288 if (BVN1 && BVN1->isConstantSplat(SplatBits1, SplatUndef, SplatBitSize, 10289 HasAnyUndefs) && !HasAnyUndefs) { 10290 // Ensure that the bit width of the constants are the same and that 10291 // the splat arguments are logical inverses as per the pattern we 10292 // are trying to simplify. 10293 if (SplatBits0.getBitWidth() == SplatBits1.getBitWidth() && 10294 SplatBits0 == ~SplatBits1) { 10295 // Canonicalize the vector type to make instruction selection 10296 // simpler. 10297 EVT CanonicalVT = VT.is128BitVector() ? MVT::v4i32 : MVT::v2i32; 10298 SDValue Result = DAG.getNode(ARMISD::VBSL, dl, CanonicalVT, 10299 N0->getOperand(1), 10300 N0->getOperand(0), 10301 N1->getOperand(0)); 10302 return DAG.getNode(ISD::BITCAST, dl, VT, Result); 10303 } 10304 } 10305 } 10306 } 10307 10308 // Try to use the ARM/Thumb2 BFI (bitfield insert) instruction when 10309 // reasonable. 10310 10311 // BFI is only available on V6T2+ 10312 if (Subtarget->isThumb1Only() || !Subtarget->hasV6T2Ops()) 10313 return SDValue(); 10314 10315 SDLoc DL(N); 10316 // 1) or (and A, mask), val => ARMbfi A, val, mask 10317 // iff (val & mask) == val 10318 // 10319 // 2) or (and A, mask), (and B, mask2) => ARMbfi A, (lsr B, amt), mask 10320 // 2a) iff isBitFieldInvertedMask(mask) && isBitFieldInvertedMask(~mask2) 10321 // && mask == ~mask2 10322 // 2b) iff isBitFieldInvertedMask(~mask) && isBitFieldInvertedMask(mask2) 10323 // && ~mask == mask2 10324 // (i.e., copy a bitfield value into another bitfield of the same width) 10325 10326 if (VT != MVT::i32) 10327 return SDValue(); 10328 10329 SDValue N00 = N0.getOperand(0); 10330 10331 // The value and the mask need to be constants so we can verify this is 10332 // actually a bitfield set. If the mask is 0xffff, we can do better 10333 // via a movt instruction, so don't use BFI in that case. 10334 SDValue MaskOp = N0.getOperand(1); 10335 ConstantSDNode *MaskC = dyn_cast<ConstantSDNode>(MaskOp); 10336 if (!MaskC) 10337 return SDValue(); 10338 unsigned Mask = MaskC->getZExtValue(); 10339 if (Mask == 0xffff) 10340 return SDValue(); 10341 SDValue Res; 10342 // Case (1): or (and A, mask), val => ARMbfi A, val, mask 10343 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1); 10344 if (N1C) { 10345 unsigned Val = N1C->getZExtValue(); 10346 if ((Val & ~Mask) != Val) 10347 return SDValue(); 10348 10349 if (ARM::isBitFieldInvertedMask(Mask)) { 10350 Val >>= countTrailingZeros(~Mask); 10351 10352 Res = DAG.getNode(ARMISD::BFI, DL, VT, N00, 10353 DAG.getConstant(Val, DL, MVT::i32), 10354 DAG.getConstant(Mask, DL, MVT::i32)); 10355 10356 // Do not add new nodes to DAG combiner worklist. 10357 DCI.CombineTo(N, Res, false); 10358 return SDValue(); 10359 } 10360 } else if (N1.getOpcode() == ISD::AND) { 10361 // case (2) or (and A, mask), (and B, mask2) => ARMbfi A, (lsr B, amt), mask 10362 ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1)); 10363 if (!N11C) 10364 return SDValue(); 10365 unsigned Mask2 = N11C->getZExtValue(); 10366 10367 // Mask and ~Mask2 (or reverse) must be equivalent for the BFI pattern 10368 // as is to match. 10369 if (ARM::isBitFieldInvertedMask(Mask) && 10370 (Mask == ~Mask2)) { 10371 // The pack halfword instruction works better for masks that fit it, 10372 // so use that when it's available. 10373 if (Subtarget->hasDSP() && 10374 (Mask == 0xffff || Mask == 0xffff0000)) 10375 return SDValue(); 10376 // 2a 10377 unsigned amt = countTrailingZeros(Mask2); 10378 Res = DAG.getNode(ISD::SRL, DL, VT, N1.getOperand(0), 10379 DAG.getConstant(amt, DL, MVT::i32)); 10380 Res = DAG.getNode(ARMISD::BFI, DL, VT, N00, Res, 10381 DAG.getConstant(Mask, DL, MVT::i32)); 10382 // Do not add new nodes to DAG combiner worklist. 10383 DCI.CombineTo(N, Res, false); 10384 return SDValue(); 10385 } else if (ARM::isBitFieldInvertedMask(~Mask) && 10386 (~Mask == Mask2)) { 10387 // The pack halfword instruction works better for masks that fit it, 10388 // so use that when it's available. 10389 if (Subtarget->hasDSP() && 10390 (Mask2 == 0xffff || Mask2 == 0xffff0000)) 10391 return SDValue(); 10392 // 2b 10393 unsigned lsb = countTrailingZeros(Mask); 10394 Res = DAG.getNode(ISD::SRL, DL, VT, N00, 10395 DAG.getConstant(lsb, DL, MVT::i32)); 10396 Res = DAG.getNode(ARMISD::BFI, DL, VT, N1.getOperand(0), Res, 10397 DAG.getConstant(Mask2, DL, MVT::i32)); 10398 // Do not add new nodes to DAG combiner worklist. 10399 DCI.CombineTo(N, Res, false); 10400 return SDValue(); 10401 } 10402 } 10403 10404 if (DAG.MaskedValueIsZero(N1, MaskC->getAPIntValue()) && 10405 N00.getOpcode() == ISD::SHL && isa<ConstantSDNode>(N00.getOperand(1)) && 10406 ARM::isBitFieldInvertedMask(~Mask)) { 10407 // Case (3): or (and (shl A, #shamt), mask), B => ARMbfi B, A, ~mask 10408 // where lsb(mask) == #shamt and masked bits of B are known zero. 10409 SDValue ShAmt = N00.getOperand(1); 10410 unsigned ShAmtC = cast<ConstantSDNode>(ShAmt)->getZExtValue(); 10411 unsigned LSB = countTrailingZeros(Mask); 10412 if (ShAmtC != LSB) 10413 return SDValue(); 10414 10415 Res = DAG.getNode(ARMISD::BFI, DL, VT, N1, N00.getOperand(0), 10416 DAG.getConstant(~Mask, DL, MVT::i32)); 10417 10418 // Do not add new nodes to DAG combiner worklist. 10419 DCI.CombineTo(N, Res, false); 10420 } 10421 10422 return SDValue(); 10423 } 10424 10425 static SDValue PerformXORCombine(SDNode *N, 10426 TargetLowering::DAGCombinerInfo &DCI, 10427 const ARMSubtarget *Subtarget) { 10428 EVT VT = N->getValueType(0); 10429 SelectionDAG &DAG = DCI.DAG; 10430 10431 if(!DAG.getTargetLoweringInfo().isTypeLegal(VT)) 10432 return SDValue(); 10433 10434 if (!Subtarget->isThumb1Only()) { 10435 // fold (xor (select cc, 0, c), x) -> (select cc, x, (xor, x, c)) 10436 if (SDValue Result = combineSelectAndUseCommutative(N, false, DCI)) 10437 return Result; 10438 } 10439 10440 return SDValue(); 10441 } 10442 10443 // ParseBFI - given a BFI instruction in N, extract the "from" value (Rn) and return it, 10444 // and fill in FromMask and ToMask with (consecutive) bits in "from" to be extracted and 10445 // their position in "to" (Rd). 10446 static SDValue ParseBFI(SDNode *N, APInt &ToMask, APInt &FromMask) { 10447 assert(N->getOpcode() == ARMISD::BFI); 10448 10449 SDValue From = N->getOperand(1); 10450 ToMask = ~cast<ConstantSDNode>(N->getOperand(2))->getAPIntValue(); 10451 FromMask = APInt::getLowBitsSet(ToMask.getBitWidth(), ToMask.countPopulation()); 10452 10453 // If the Base came from a SHR #C, we can deduce that it is really testing bit 10454 // #C in the base of the SHR. 10455 if (From->getOpcode() == ISD::SRL && 10456 isa<ConstantSDNode>(From->getOperand(1))) { 10457 APInt Shift = cast<ConstantSDNode>(From->getOperand(1))->getAPIntValue(); 10458 assert(Shift.getLimitedValue() < 32 && "Shift too large!"); 10459 FromMask <<= Shift.getLimitedValue(31); 10460 From = From->getOperand(0); 10461 } 10462 10463 return From; 10464 } 10465 10466 // If A and B contain one contiguous set of bits, does A | B == A . B? 10467 // 10468 // Neither A nor B must be zero. 10469 static bool BitsProperlyConcatenate(const APInt &A, const APInt &B) { 10470 unsigned LastActiveBitInA = A.countTrailingZeros(); 10471 unsigned FirstActiveBitInB = B.getBitWidth() - B.countLeadingZeros() - 1; 10472 return LastActiveBitInA - 1 == FirstActiveBitInB; 10473 } 10474 10475 static SDValue FindBFIToCombineWith(SDNode *N) { 10476 // We have a BFI in N. Follow a possible chain of BFIs and find a BFI it can combine with, 10477 // if one exists. 10478 APInt ToMask, FromMask; 10479 SDValue From = ParseBFI(N, ToMask, FromMask); 10480 SDValue To = N->getOperand(0); 10481 10482 // Now check for a compatible BFI to merge with. We can pass through BFIs that 10483 // aren't compatible, but not if they set the same bit in their destination as 10484 // we do (or that of any BFI we're going to combine with). 10485 SDValue V = To; 10486 APInt CombinedToMask = ToMask; 10487 while (V.getOpcode() == ARMISD::BFI) { 10488 APInt NewToMask, NewFromMask; 10489 SDValue NewFrom = ParseBFI(V.getNode(), NewToMask, NewFromMask); 10490 if (NewFrom != From) { 10491 // This BFI has a different base. Keep going. 10492 CombinedToMask |= NewToMask; 10493 V = V.getOperand(0); 10494 continue; 10495 } 10496 10497 // Do the written bits conflict with any we've seen so far? 10498 if ((NewToMask & CombinedToMask).getBoolValue()) 10499 // Conflicting bits - bail out because going further is unsafe. 10500 return SDValue(); 10501 10502 // Are the new bits contiguous when combined with the old bits? 10503 if (BitsProperlyConcatenate(ToMask, NewToMask) && 10504 BitsProperlyConcatenate(FromMask, NewFromMask)) 10505 return V; 10506 if (BitsProperlyConcatenate(NewToMask, ToMask) && 10507 BitsProperlyConcatenate(NewFromMask, FromMask)) 10508 return V; 10509 10510 // We've seen a write to some bits, so track it. 10511 CombinedToMask |= NewToMask; 10512 // Keep going... 10513 V = V.getOperand(0); 10514 } 10515 10516 return SDValue(); 10517 } 10518 10519 static SDValue PerformBFICombine(SDNode *N, 10520 TargetLowering::DAGCombinerInfo &DCI) { 10521 SDValue N1 = N->getOperand(1); 10522 if (N1.getOpcode() == ISD::AND) { 10523 // (bfi A, (and B, Mask1), Mask2) -> (bfi A, B, Mask2) iff 10524 // the bits being cleared by the AND are not demanded by the BFI. 10525 ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1)); 10526 if (!N11C) 10527 return SDValue(); 10528 unsigned InvMask = cast<ConstantSDNode>(N->getOperand(2))->getZExtValue(); 10529 unsigned LSB = countTrailingZeros(~InvMask); 10530 unsigned Width = (32 - countLeadingZeros(~InvMask)) - LSB; 10531 assert(Width < 10532 static_cast<unsigned>(std::numeric_limits<unsigned>::digits) && 10533 "undefined behavior"); 10534 unsigned Mask = (1u << Width) - 1; 10535 unsigned Mask2 = N11C->getZExtValue(); 10536 if ((Mask & (~Mask2)) == 0) 10537 return DCI.DAG.getNode(ARMISD::BFI, SDLoc(N), N->getValueType(0), 10538 N->getOperand(0), N1.getOperand(0), 10539 N->getOperand(2)); 10540 } else if (N->getOperand(0).getOpcode() == ARMISD::BFI) { 10541 // We have a BFI of a BFI. Walk up the BFI chain to see how long it goes. 10542 // Keep track of any consecutive bits set that all come from the same base 10543 // value. We can combine these together into a single BFI. 10544 SDValue CombineBFI = FindBFIToCombineWith(N); 10545 if (CombineBFI == SDValue()) 10546 return SDValue(); 10547 10548 // We've found a BFI. 10549 APInt ToMask1, FromMask1; 10550 SDValue From1 = ParseBFI(N, ToMask1, FromMask1); 10551 10552 APInt ToMask2, FromMask2; 10553 SDValue From2 = ParseBFI(CombineBFI.getNode(), ToMask2, FromMask2); 10554 assert(From1 == From2); 10555 (void)From2; 10556 10557 // First, unlink CombineBFI. 10558 DCI.DAG.ReplaceAllUsesWith(CombineBFI, CombineBFI.getOperand(0)); 10559 // Then create a new BFI, combining the two together. 10560 APInt NewFromMask = FromMask1 | FromMask2; 10561 APInt NewToMask = ToMask1 | ToMask2; 10562 10563 EVT VT = N->getValueType(0); 10564 SDLoc dl(N); 10565 10566 if (NewFromMask[0] == 0) 10567 From1 = DCI.DAG.getNode( 10568 ISD::SRL, dl, VT, From1, 10569 DCI.DAG.getConstant(NewFromMask.countTrailingZeros(), dl, VT)); 10570 return DCI.DAG.getNode(ARMISD::BFI, dl, VT, N->getOperand(0), From1, 10571 DCI.DAG.getConstant(~NewToMask, dl, VT)); 10572 } 10573 return SDValue(); 10574 } 10575 10576 /// PerformVMOVRRDCombine - Target-specific dag combine xforms for 10577 /// ARMISD::VMOVRRD. 10578 static SDValue PerformVMOVRRDCombine(SDNode *N, 10579 TargetLowering::DAGCombinerInfo &DCI, 10580 const ARMSubtarget *Subtarget) { 10581 // vmovrrd(vmovdrr x, y) -> x,y 10582 SDValue InDouble = N->getOperand(0); 10583 if (InDouble.getOpcode() == ARMISD::VMOVDRR && !Subtarget->isFPOnlySP()) 10584 return DCI.CombineTo(N, InDouble.getOperand(0), InDouble.getOperand(1)); 10585 10586 // vmovrrd(load f64) -> (load i32), (load i32) 10587 SDNode *InNode = InDouble.getNode(); 10588 if (ISD::isNormalLoad(InNode) && InNode->hasOneUse() && 10589 InNode->getValueType(0) == MVT::f64 && 10590 InNode->getOperand(1).getOpcode() == ISD::FrameIndex && 10591 !cast<LoadSDNode>(InNode)->isVolatile()) { 10592 // TODO: Should this be done for non-FrameIndex operands? 10593 LoadSDNode *LD = cast<LoadSDNode>(InNode); 10594 10595 SelectionDAG &DAG = DCI.DAG; 10596 SDLoc DL(LD); 10597 SDValue BasePtr = LD->getBasePtr(); 10598 SDValue NewLD1 = 10599 DAG.getLoad(MVT::i32, DL, LD->getChain(), BasePtr, LD->getPointerInfo(), 10600 LD->getAlignment(), LD->getMemOperand()->getFlags()); 10601 10602 SDValue OffsetPtr = DAG.getNode(ISD::ADD, DL, MVT::i32, BasePtr, 10603 DAG.getConstant(4, DL, MVT::i32)); 10604 SDValue NewLD2 = DAG.getLoad( 10605 MVT::i32, DL, NewLD1.getValue(1), OffsetPtr, LD->getPointerInfo(), 10606 std::min(4U, LD->getAlignment() / 2), LD->getMemOperand()->getFlags()); 10607 10608 DAG.ReplaceAllUsesOfValueWith(SDValue(LD, 1), NewLD2.getValue(1)); 10609 if (DCI.DAG.getDataLayout().isBigEndian()) 10610 std::swap (NewLD1, NewLD2); 10611 SDValue Result = DCI.CombineTo(N, NewLD1, NewLD2); 10612 return Result; 10613 } 10614 10615 return SDValue(); 10616 } 10617 10618 /// PerformVMOVDRRCombine - Target-specific dag combine xforms for 10619 /// ARMISD::VMOVDRR. This is also used for BUILD_VECTORs with 2 operands. 10620 static SDValue PerformVMOVDRRCombine(SDNode *N, SelectionDAG &DAG) { 10621 // N=vmovrrd(X); vmovdrr(N:0, N:1) -> bit_convert(X) 10622 SDValue Op0 = N->getOperand(0); 10623 SDValue Op1 = N->getOperand(1); 10624 if (Op0.getOpcode() == ISD::BITCAST) 10625 Op0 = Op0.getOperand(0); 10626 if (Op1.getOpcode() == ISD::BITCAST) 10627 Op1 = Op1.getOperand(0); 10628 if (Op0.getOpcode() == ARMISD::VMOVRRD && 10629 Op0.getNode() == Op1.getNode() && 10630 Op0.getResNo() == 0 && Op1.getResNo() == 1) 10631 return DAG.getNode(ISD::BITCAST, SDLoc(N), 10632 N->getValueType(0), Op0.getOperand(0)); 10633 return SDValue(); 10634 } 10635 10636 /// hasNormalLoadOperand - Check if any of the operands of a BUILD_VECTOR node 10637 /// are normal, non-volatile loads. If so, it is profitable to bitcast an 10638 /// i64 vector to have f64 elements, since the value can then be loaded 10639 /// directly into a VFP register. 10640 static bool hasNormalLoadOperand(SDNode *N) { 10641 unsigned NumElts = N->getValueType(0).getVectorNumElements(); 10642 for (unsigned i = 0; i < NumElts; ++i) { 10643 SDNode *Elt = N->getOperand(i).getNode(); 10644 if (ISD::isNormalLoad(Elt) && !cast<LoadSDNode>(Elt)->isVolatile()) 10645 return true; 10646 } 10647 return false; 10648 } 10649 10650 /// PerformBUILD_VECTORCombine - Target-specific dag combine xforms for 10651 /// ISD::BUILD_VECTOR. 10652 static SDValue PerformBUILD_VECTORCombine(SDNode *N, 10653 TargetLowering::DAGCombinerInfo &DCI, 10654 const ARMSubtarget *Subtarget) { 10655 // build_vector(N=ARMISD::VMOVRRD(X), N:1) -> bit_convert(X): 10656 // VMOVRRD is introduced when legalizing i64 types. It forces the i64 value 10657 // into a pair of GPRs, which is fine when the value is used as a scalar, 10658 // but if the i64 value is converted to a vector, we need to undo the VMOVRRD. 10659 SelectionDAG &DAG = DCI.DAG; 10660 if (N->getNumOperands() == 2) 10661 if (SDValue RV = PerformVMOVDRRCombine(N, DAG)) 10662 return RV; 10663 10664 // Load i64 elements as f64 values so that type legalization does not split 10665 // them up into i32 values. 10666 EVT VT = N->getValueType(0); 10667 if (VT.getVectorElementType() != MVT::i64 || !hasNormalLoadOperand(N)) 10668 return SDValue(); 10669 SDLoc dl(N); 10670 SmallVector<SDValue, 8> Ops; 10671 unsigned NumElts = VT.getVectorNumElements(); 10672 for (unsigned i = 0; i < NumElts; ++i) { 10673 SDValue V = DAG.getNode(ISD::BITCAST, dl, MVT::f64, N->getOperand(i)); 10674 Ops.push_back(V); 10675 // Make the DAGCombiner fold the bitcast. 10676 DCI.AddToWorklist(V.getNode()); 10677 } 10678 EVT FloatVT = EVT::getVectorVT(*DAG.getContext(), MVT::f64, NumElts); 10679 SDValue BV = DAG.getBuildVector(FloatVT, dl, Ops); 10680 return DAG.getNode(ISD::BITCAST, dl, VT, BV); 10681 } 10682 10683 /// \brief Target-specific dag combine xforms for ARMISD::BUILD_VECTOR. 10684 static SDValue 10685 PerformARMBUILD_VECTORCombine(SDNode *N, TargetLowering::DAGCombinerInfo &DCI) { 10686 // ARMISD::BUILD_VECTOR is introduced when legalizing ISD::BUILD_VECTOR. 10687 // At that time, we may have inserted bitcasts from integer to float. 10688 // If these bitcasts have survived DAGCombine, change the lowering of this 10689 // BUILD_VECTOR in something more vector friendly, i.e., that does not 10690 // force to use floating point types. 10691 10692 // Make sure we can change the type of the vector. 10693 // This is possible iff: 10694 // 1. The vector is only used in a bitcast to a integer type. I.e., 10695 // 1.1. Vector is used only once. 10696 // 1.2. Use is a bit convert to an integer type. 10697 // 2. The size of its operands are 32-bits (64-bits are not legal). 10698 EVT VT = N->getValueType(0); 10699 EVT EltVT = VT.getVectorElementType(); 10700 10701 // Check 1.1. and 2. 10702 if (EltVT.getSizeInBits() != 32 || !N->hasOneUse()) 10703 return SDValue(); 10704 10705 // By construction, the input type must be float. 10706 assert(EltVT == MVT::f32 && "Unexpected type!"); 10707 10708 // Check 1.2. 10709 SDNode *Use = *N->use_begin(); 10710 if (Use->getOpcode() != ISD::BITCAST || 10711 Use->getValueType(0).isFloatingPoint()) 10712 return SDValue(); 10713 10714 // Check profitability. 10715 // Model is, if more than half of the relevant operands are bitcast from 10716 // i32, turn the build_vector into a sequence of insert_vector_elt. 10717 // Relevant operands are everything that is not statically 10718 // (i.e., at compile time) bitcasted. 10719 unsigned NumOfBitCastedElts = 0; 10720 unsigned NumElts = VT.getVectorNumElements(); 10721 unsigned NumOfRelevantElts = NumElts; 10722 for (unsigned Idx = 0; Idx < NumElts; ++Idx) { 10723 SDValue Elt = N->getOperand(Idx); 10724 if (Elt->getOpcode() == ISD::BITCAST) { 10725 // Assume only bit cast to i32 will go away. 10726 if (Elt->getOperand(0).getValueType() == MVT::i32) 10727 ++NumOfBitCastedElts; 10728 } else if (Elt.isUndef() || isa<ConstantSDNode>(Elt)) 10729 // Constants are statically casted, thus do not count them as 10730 // relevant operands. 10731 --NumOfRelevantElts; 10732 } 10733 10734 // Check if more than half of the elements require a non-free bitcast. 10735 if (NumOfBitCastedElts <= NumOfRelevantElts / 2) 10736 return SDValue(); 10737 10738 SelectionDAG &DAG = DCI.DAG; 10739 // Create the new vector type. 10740 EVT VecVT = EVT::getVectorVT(*DAG.getContext(), MVT::i32, NumElts); 10741 // Check if the type is legal. 10742 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 10743 if (!TLI.isTypeLegal(VecVT)) 10744 return SDValue(); 10745 10746 // Combine: 10747 // ARMISD::BUILD_VECTOR E1, E2, ..., EN. 10748 // => BITCAST INSERT_VECTOR_ELT 10749 // (INSERT_VECTOR_ELT (...), (BITCAST EN-1), N-1), 10750 // (BITCAST EN), N. 10751 SDValue Vec = DAG.getUNDEF(VecVT); 10752 SDLoc dl(N); 10753 for (unsigned Idx = 0 ; Idx < NumElts; ++Idx) { 10754 SDValue V = N->getOperand(Idx); 10755 if (V.isUndef()) 10756 continue; 10757 if (V.getOpcode() == ISD::BITCAST && 10758 V->getOperand(0).getValueType() == MVT::i32) 10759 // Fold obvious case. 10760 V = V.getOperand(0); 10761 else { 10762 V = DAG.getNode(ISD::BITCAST, SDLoc(V), MVT::i32, V); 10763 // Make the DAGCombiner fold the bitcasts. 10764 DCI.AddToWorklist(V.getNode()); 10765 } 10766 SDValue LaneIdx = DAG.getConstant(Idx, dl, MVT::i32); 10767 Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VecVT, Vec, V, LaneIdx); 10768 } 10769 Vec = DAG.getNode(ISD::BITCAST, dl, VT, Vec); 10770 // Make the DAGCombiner fold the bitcasts. 10771 DCI.AddToWorklist(Vec.getNode()); 10772 return Vec; 10773 } 10774 10775 /// PerformInsertEltCombine - Target-specific dag combine xforms for 10776 /// ISD::INSERT_VECTOR_ELT. 10777 static SDValue PerformInsertEltCombine(SDNode *N, 10778 TargetLowering::DAGCombinerInfo &DCI) { 10779 // Bitcast an i64 load inserted into a vector to f64. 10780 // Otherwise, the i64 value will be legalized to a pair of i32 values. 10781 EVT VT = N->getValueType(0); 10782 SDNode *Elt = N->getOperand(1).getNode(); 10783 if (VT.getVectorElementType() != MVT::i64 || 10784 !ISD::isNormalLoad(Elt) || cast<LoadSDNode>(Elt)->isVolatile()) 10785 return SDValue(); 10786 10787 SelectionDAG &DAG = DCI.DAG; 10788 SDLoc dl(N); 10789 EVT FloatVT = EVT::getVectorVT(*DAG.getContext(), MVT::f64, 10790 VT.getVectorNumElements()); 10791 SDValue Vec = DAG.getNode(ISD::BITCAST, dl, FloatVT, N->getOperand(0)); 10792 SDValue V = DAG.getNode(ISD::BITCAST, dl, MVT::f64, N->getOperand(1)); 10793 // Make the DAGCombiner fold the bitcasts. 10794 DCI.AddToWorklist(Vec.getNode()); 10795 DCI.AddToWorklist(V.getNode()); 10796 SDValue InsElt = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, FloatVT, 10797 Vec, V, N->getOperand(2)); 10798 return DAG.getNode(ISD::BITCAST, dl, VT, InsElt); 10799 } 10800 10801 /// PerformVECTOR_SHUFFLECombine - Target-specific dag combine xforms for 10802 /// ISD::VECTOR_SHUFFLE. 10803 static SDValue PerformVECTOR_SHUFFLECombine(SDNode *N, SelectionDAG &DAG) { 10804 // The LLVM shufflevector instruction does not require the shuffle mask 10805 // length to match the operand vector length, but ISD::VECTOR_SHUFFLE does 10806 // have that requirement. When translating to ISD::VECTOR_SHUFFLE, if the 10807 // operands do not match the mask length, they are extended by concatenating 10808 // them with undef vectors. That is probably the right thing for other 10809 // targets, but for NEON it is better to concatenate two double-register 10810 // size vector operands into a single quad-register size vector. Do that 10811 // transformation here: 10812 // shuffle(concat(v1, undef), concat(v2, undef)) -> 10813 // shuffle(concat(v1, v2), undef) 10814 SDValue Op0 = N->getOperand(0); 10815 SDValue Op1 = N->getOperand(1); 10816 if (Op0.getOpcode() != ISD::CONCAT_VECTORS || 10817 Op1.getOpcode() != ISD::CONCAT_VECTORS || 10818 Op0.getNumOperands() != 2 || 10819 Op1.getNumOperands() != 2) 10820 return SDValue(); 10821 SDValue Concat0Op1 = Op0.getOperand(1); 10822 SDValue Concat1Op1 = Op1.getOperand(1); 10823 if (!Concat0Op1.isUndef() || !Concat1Op1.isUndef()) 10824 return SDValue(); 10825 // Skip the transformation if any of the types are illegal. 10826 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 10827 EVT VT = N->getValueType(0); 10828 if (!TLI.isTypeLegal(VT) || 10829 !TLI.isTypeLegal(Concat0Op1.getValueType()) || 10830 !TLI.isTypeLegal(Concat1Op1.getValueType())) 10831 return SDValue(); 10832 10833 SDValue NewConcat = DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT, 10834 Op0.getOperand(0), Op1.getOperand(0)); 10835 // Translate the shuffle mask. 10836 SmallVector<int, 16> NewMask; 10837 unsigned NumElts = VT.getVectorNumElements(); 10838 unsigned HalfElts = NumElts/2; 10839 ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N); 10840 for (unsigned n = 0; n < NumElts; ++n) { 10841 int MaskElt = SVN->getMaskElt(n); 10842 int NewElt = -1; 10843 if (MaskElt < (int)HalfElts) 10844 NewElt = MaskElt; 10845 else if (MaskElt >= (int)NumElts && MaskElt < (int)(NumElts + HalfElts)) 10846 NewElt = HalfElts + MaskElt - NumElts; 10847 NewMask.push_back(NewElt); 10848 } 10849 return DAG.getVectorShuffle(VT, SDLoc(N), NewConcat, 10850 DAG.getUNDEF(VT), NewMask); 10851 } 10852 10853 /// CombineBaseUpdate - Target-specific DAG combine function for VLDDUP, 10854 /// NEON load/store intrinsics, and generic vector load/stores, to merge 10855 /// base address updates. 10856 /// For generic load/stores, the memory type is assumed to be a vector. 10857 /// The caller is assumed to have checked legality. 10858 static SDValue CombineBaseUpdate(SDNode *N, 10859 TargetLowering::DAGCombinerInfo &DCI) { 10860 SelectionDAG &DAG = DCI.DAG; 10861 const bool isIntrinsic = (N->getOpcode() == ISD::INTRINSIC_VOID || 10862 N->getOpcode() == ISD::INTRINSIC_W_CHAIN); 10863 const bool isStore = N->getOpcode() == ISD::STORE; 10864 const unsigned AddrOpIdx = ((isIntrinsic || isStore) ? 2 : 1); 10865 SDValue Addr = N->getOperand(AddrOpIdx); 10866 MemSDNode *MemN = cast<MemSDNode>(N); 10867 SDLoc dl(N); 10868 10869 // Search for a use of the address operand that is an increment. 10870 for (SDNode::use_iterator UI = Addr.getNode()->use_begin(), 10871 UE = Addr.getNode()->use_end(); UI != UE; ++UI) { 10872 SDNode *User = *UI; 10873 if (User->getOpcode() != ISD::ADD || 10874 UI.getUse().getResNo() != Addr.getResNo()) 10875 continue; 10876 10877 // Check that the add is independent of the load/store. Otherwise, folding 10878 // it would create a cycle. 10879 if (User->isPredecessorOf(N) || N->isPredecessorOf(User)) 10880 continue; 10881 10882 // Find the new opcode for the updating load/store. 10883 bool isLoadOp = true; 10884 bool isLaneOp = false; 10885 unsigned NewOpc = 0; 10886 unsigned NumVecs = 0; 10887 if (isIntrinsic) { 10888 unsigned IntNo = cast<ConstantSDNode>(N->getOperand(1))->getZExtValue(); 10889 switch (IntNo) { 10890 default: llvm_unreachable("unexpected intrinsic for Neon base update"); 10891 case Intrinsic::arm_neon_vld1: NewOpc = ARMISD::VLD1_UPD; 10892 NumVecs = 1; break; 10893 case Intrinsic::arm_neon_vld2: NewOpc = ARMISD::VLD2_UPD; 10894 NumVecs = 2; break; 10895 case Intrinsic::arm_neon_vld3: NewOpc = ARMISD::VLD3_UPD; 10896 NumVecs = 3; break; 10897 case Intrinsic::arm_neon_vld4: NewOpc = ARMISD::VLD4_UPD; 10898 NumVecs = 4; break; 10899 case Intrinsic::arm_neon_vld2lane: NewOpc = ARMISD::VLD2LN_UPD; 10900 NumVecs = 2; isLaneOp = true; break; 10901 case Intrinsic::arm_neon_vld3lane: NewOpc = ARMISD::VLD3LN_UPD; 10902 NumVecs = 3; isLaneOp = true; break; 10903 case Intrinsic::arm_neon_vld4lane: NewOpc = ARMISD::VLD4LN_UPD; 10904 NumVecs = 4; isLaneOp = true; break; 10905 case Intrinsic::arm_neon_vst1: NewOpc = ARMISD::VST1_UPD; 10906 NumVecs = 1; isLoadOp = false; break; 10907 case Intrinsic::arm_neon_vst2: NewOpc = ARMISD::VST2_UPD; 10908 NumVecs = 2; isLoadOp = false; break; 10909 case Intrinsic::arm_neon_vst3: NewOpc = ARMISD::VST3_UPD; 10910 NumVecs = 3; isLoadOp = false; break; 10911 case Intrinsic::arm_neon_vst4: NewOpc = ARMISD::VST4_UPD; 10912 NumVecs = 4; isLoadOp = false; break; 10913 case Intrinsic::arm_neon_vst2lane: NewOpc = ARMISD::VST2LN_UPD; 10914 NumVecs = 2; isLoadOp = false; isLaneOp = true; break; 10915 case Intrinsic::arm_neon_vst3lane: NewOpc = ARMISD::VST3LN_UPD; 10916 NumVecs = 3; isLoadOp = false; isLaneOp = true; break; 10917 case Intrinsic::arm_neon_vst4lane: NewOpc = ARMISD::VST4LN_UPD; 10918 NumVecs = 4; isLoadOp = false; isLaneOp = true; break; 10919 } 10920 } else { 10921 isLaneOp = true; 10922 switch (N->getOpcode()) { 10923 default: llvm_unreachable("unexpected opcode for Neon base update"); 10924 case ARMISD::VLD1DUP: NewOpc = ARMISD::VLD1DUP_UPD; NumVecs = 1; break; 10925 case ARMISD::VLD2DUP: NewOpc = ARMISD::VLD2DUP_UPD; NumVecs = 2; break; 10926 case ARMISD::VLD3DUP: NewOpc = ARMISD::VLD3DUP_UPD; NumVecs = 3; break; 10927 case ARMISD::VLD4DUP: NewOpc = ARMISD::VLD4DUP_UPD; NumVecs = 4; break; 10928 case ISD::LOAD: NewOpc = ARMISD::VLD1_UPD; 10929 NumVecs = 1; isLaneOp = false; break; 10930 case ISD::STORE: NewOpc = ARMISD::VST1_UPD; 10931 NumVecs = 1; isLaneOp = false; isLoadOp = false; break; 10932 } 10933 } 10934 10935 // Find the size of memory referenced by the load/store. 10936 EVT VecTy; 10937 if (isLoadOp) { 10938 VecTy = N->getValueType(0); 10939 } else if (isIntrinsic) { 10940 VecTy = N->getOperand(AddrOpIdx+1).getValueType(); 10941 } else { 10942 assert(isStore && "Node has to be a load, a store, or an intrinsic!"); 10943 VecTy = N->getOperand(1).getValueType(); 10944 } 10945 10946 unsigned NumBytes = NumVecs * VecTy.getSizeInBits() / 8; 10947 if (isLaneOp) 10948 NumBytes /= VecTy.getVectorNumElements(); 10949 10950 // If the increment is a constant, it must match the memory ref size. 10951 SDValue Inc = User->getOperand(User->getOperand(0) == Addr ? 1 : 0); 10952 ConstantSDNode *CInc = dyn_cast<ConstantSDNode>(Inc.getNode()); 10953 if (NumBytes >= 3 * 16 && (!CInc || CInc->getZExtValue() != NumBytes)) { 10954 // VLD3/4 and VST3/4 for 128-bit vectors are implemented with two 10955 // separate instructions that make it harder to use a non-constant update. 10956 continue; 10957 } 10958 10959 // OK, we found an ADD we can fold into the base update. 10960 // Now, create a _UPD node, taking care of not breaking alignment. 10961 10962 EVT AlignedVecTy = VecTy; 10963 unsigned Alignment = MemN->getAlignment(); 10964 10965 // If this is a less-than-standard-aligned load/store, change the type to 10966 // match the standard alignment. 10967 // The alignment is overlooked when selecting _UPD variants; and it's 10968 // easier to introduce bitcasts here than fix that. 10969 // There are 3 ways to get to this base-update combine: 10970 // - intrinsics: they are assumed to be properly aligned (to the standard 10971 // alignment of the memory type), so we don't need to do anything. 10972 // - ARMISD::VLDx nodes: they are only generated from the aforementioned 10973 // intrinsics, so, likewise, there's nothing to do. 10974 // - generic load/store instructions: the alignment is specified as an 10975 // explicit operand, rather than implicitly as the standard alignment 10976 // of the memory type (like the intrisics). We need to change the 10977 // memory type to match the explicit alignment. That way, we don't 10978 // generate non-standard-aligned ARMISD::VLDx nodes. 10979 if (isa<LSBaseSDNode>(N)) { 10980 if (Alignment == 0) 10981 Alignment = 1; 10982 if (Alignment < VecTy.getScalarSizeInBits() / 8) { 10983 MVT EltTy = MVT::getIntegerVT(Alignment * 8); 10984 assert(NumVecs == 1 && "Unexpected multi-element generic load/store."); 10985 assert(!isLaneOp && "Unexpected generic load/store lane."); 10986 unsigned NumElts = NumBytes / (EltTy.getSizeInBits() / 8); 10987 AlignedVecTy = MVT::getVectorVT(EltTy, NumElts); 10988 } 10989 // Don't set an explicit alignment on regular load/stores that we want 10990 // to transform to VLD/VST 1_UPD nodes. 10991 // This matches the behavior of regular load/stores, which only get an 10992 // explicit alignment if the MMO alignment is larger than the standard 10993 // alignment of the memory type. 10994 // Intrinsics, however, always get an explicit alignment, set to the 10995 // alignment of the MMO. 10996 Alignment = 1; 10997 } 10998 10999 // Create the new updating load/store node. 11000 // First, create an SDVTList for the new updating node's results. 11001 EVT Tys[6]; 11002 unsigned NumResultVecs = (isLoadOp ? NumVecs : 0); 11003 unsigned n; 11004 for (n = 0; n < NumResultVecs; ++n) 11005 Tys[n] = AlignedVecTy; 11006 Tys[n++] = MVT::i32; 11007 Tys[n] = MVT::Other; 11008 SDVTList SDTys = DAG.getVTList(makeArrayRef(Tys, NumResultVecs+2)); 11009 11010 // Then, gather the new node's operands. 11011 SmallVector<SDValue, 8> Ops; 11012 Ops.push_back(N->getOperand(0)); // incoming chain 11013 Ops.push_back(N->getOperand(AddrOpIdx)); 11014 Ops.push_back(Inc); 11015 11016 if (StoreSDNode *StN = dyn_cast<StoreSDNode>(N)) { 11017 // Try to match the intrinsic's signature 11018 Ops.push_back(StN->getValue()); 11019 } else { 11020 // Loads (and of course intrinsics) match the intrinsics' signature, 11021 // so just add all but the alignment operand. 11022 for (unsigned i = AddrOpIdx + 1; i < N->getNumOperands() - 1; ++i) 11023 Ops.push_back(N->getOperand(i)); 11024 } 11025 11026 // For all node types, the alignment operand is always the last one. 11027 Ops.push_back(DAG.getConstant(Alignment, dl, MVT::i32)); 11028 11029 // If this is a non-standard-aligned STORE, the penultimate operand is the 11030 // stored value. Bitcast it to the aligned type. 11031 if (AlignedVecTy != VecTy && N->getOpcode() == ISD::STORE) { 11032 SDValue &StVal = Ops[Ops.size()-2]; 11033 StVal = DAG.getNode(ISD::BITCAST, dl, AlignedVecTy, StVal); 11034 } 11035 11036 EVT LoadVT = isLaneOp ? VecTy.getVectorElementType() : AlignedVecTy; 11037 SDValue UpdN = DAG.getMemIntrinsicNode(NewOpc, dl, SDTys, Ops, LoadVT, 11038 MemN->getMemOperand()); 11039 11040 // Update the uses. 11041 SmallVector<SDValue, 5> NewResults; 11042 for (unsigned i = 0; i < NumResultVecs; ++i) 11043 NewResults.push_back(SDValue(UpdN.getNode(), i)); 11044 11045 // If this is an non-standard-aligned LOAD, the first result is the loaded 11046 // value. Bitcast it to the expected result type. 11047 if (AlignedVecTy != VecTy && N->getOpcode() == ISD::LOAD) { 11048 SDValue &LdVal = NewResults[0]; 11049 LdVal = DAG.getNode(ISD::BITCAST, dl, VecTy, LdVal); 11050 } 11051 11052 NewResults.push_back(SDValue(UpdN.getNode(), NumResultVecs+1)); // chain 11053 DCI.CombineTo(N, NewResults); 11054 DCI.CombineTo(User, SDValue(UpdN.getNode(), NumResultVecs)); 11055 11056 break; 11057 } 11058 return SDValue(); 11059 } 11060 11061 static SDValue PerformVLDCombine(SDNode *N, 11062 TargetLowering::DAGCombinerInfo &DCI) { 11063 if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer()) 11064 return SDValue(); 11065 11066 return CombineBaseUpdate(N, DCI); 11067 } 11068 11069 /// CombineVLDDUP - For a VDUPLANE node N, check if its source operand is a 11070 /// vldN-lane (N > 1) intrinsic, and if all the other uses of that intrinsic 11071 /// are also VDUPLANEs. If so, combine them to a vldN-dup operation and 11072 /// return true. 11073 static bool CombineVLDDUP(SDNode *N, TargetLowering::DAGCombinerInfo &DCI) { 11074 SelectionDAG &DAG = DCI.DAG; 11075 EVT VT = N->getValueType(0); 11076 // vldN-dup instructions only support 64-bit vectors for N > 1. 11077 if (!VT.is64BitVector()) 11078 return false; 11079 11080 // Check if the VDUPLANE operand is a vldN-dup intrinsic. 11081 SDNode *VLD = N->getOperand(0).getNode(); 11082 if (VLD->getOpcode() != ISD::INTRINSIC_W_CHAIN) 11083 return false; 11084 unsigned NumVecs = 0; 11085 unsigned NewOpc = 0; 11086 unsigned IntNo = cast<ConstantSDNode>(VLD->getOperand(1))->getZExtValue(); 11087 if (IntNo == Intrinsic::arm_neon_vld2lane) { 11088 NumVecs = 2; 11089 NewOpc = ARMISD::VLD2DUP; 11090 } else if (IntNo == Intrinsic::arm_neon_vld3lane) { 11091 NumVecs = 3; 11092 NewOpc = ARMISD::VLD3DUP; 11093 } else if (IntNo == Intrinsic::arm_neon_vld4lane) { 11094 NumVecs = 4; 11095 NewOpc = ARMISD::VLD4DUP; 11096 } else { 11097 return false; 11098 } 11099 11100 // First check that all the vldN-lane uses are VDUPLANEs and that the lane 11101 // numbers match the load. 11102 unsigned VLDLaneNo = 11103 cast<ConstantSDNode>(VLD->getOperand(NumVecs+3))->getZExtValue(); 11104 for (SDNode::use_iterator UI = VLD->use_begin(), UE = VLD->use_end(); 11105 UI != UE; ++UI) { 11106 // Ignore uses of the chain result. 11107 if (UI.getUse().getResNo() == NumVecs) 11108 continue; 11109 SDNode *User = *UI; 11110 if (User->getOpcode() != ARMISD::VDUPLANE || 11111 VLDLaneNo != cast<ConstantSDNode>(User->getOperand(1))->getZExtValue()) 11112 return false; 11113 } 11114 11115 // Create the vldN-dup node. 11116 EVT Tys[5]; 11117 unsigned n; 11118 for (n = 0; n < NumVecs; ++n) 11119 Tys[n] = VT; 11120 Tys[n] = MVT::Other; 11121 SDVTList SDTys = DAG.getVTList(makeArrayRef(Tys, NumVecs+1)); 11122 SDValue Ops[] = { VLD->getOperand(0), VLD->getOperand(2) }; 11123 MemIntrinsicSDNode *VLDMemInt = cast<MemIntrinsicSDNode>(VLD); 11124 SDValue VLDDup = DAG.getMemIntrinsicNode(NewOpc, SDLoc(VLD), SDTys, 11125 Ops, VLDMemInt->getMemoryVT(), 11126 VLDMemInt->getMemOperand()); 11127 11128 // Update the uses. 11129 for (SDNode::use_iterator UI = VLD->use_begin(), UE = VLD->use_end(); 11130 UI != UE; ++UI) { 11131 unsigned ResNo = UI.getUse().getResNo(); 11132 // Ignore uses of the chain result. 11133 if (ResNo == NumVecs) 11134 continue; 11135 SDNode *User = *UI; 11136 DCI.CombineTo(User, SDValue(VLDDup.getNode(), ResNo)); 11137 } 11138 11139 // Now the vldN-lane intrinsic is dead except for its chain result. 11140 // Update uses of the chain. 11141 std::vector<SDValue> VLDDupResults; 11142 for (unsigned n = 0; n < NumVecs; ++n) 11143 VLDDupResults.push_back(SDValue(VLDDup.getNode(), n)); 11144 VLDDupResults.push_back(SDValue(VLDDup.getNode(), NumVecs)); 11145 DCI.CombineTo(VLD, VLDDupResults); 11146 11147 return true; 11148 } 11149 11150 /// PerformVDUPLANECombine - Target-specific dag combine xforms for 11151 /// ARMISD::VDUPLANE. 11152 static SDValue PerformVDUPLANECombine(SDNode *N, 11153 TargetLowering::DAGCombinerInfo &DCI) { 11154 SDValue Op = N->getOperand(0); 11155 11156 // If the source is a vldN-lane (N > 1) intrinsic, and all the other uses 11157 // of that intrinsic are also VDUPLANEs, combine them to a vldN-dup operation. 11158 if (CombineVLDDUP(N, DCI)) 11159 return SDValue(N, 0); 11160 11161 // If the source is already a VMOVIMM or VMVNIMM splat, the VDUPLANE is 11162 // redundant. Ignore bit_converts for now; element sizes are checked below. 11163 while (Op.getOpcode() == ISD::BITCAST) 11164 Op = Op.getOperand(0); 11165 if (Op.getOpcode() != ARMISD::VMOVIMM && Op.getOpcode() != ARMISD::VMVNIMM) 11166 return SDValue(); 11167 11168 // Make sure the VMOV element size is not bigger than the VDUPLANE elements. 11169 unsigned EltSize = Op.getScalarValueSizeInBits(); 11170 // The canonical VMOV for a zero vector uses a 32-bit element size. 11171 unsigned Imm = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue(); 11172 unsigned EltBits; 11173 if (ARM_AM::decodeNEONModImm(Imm, EltBits) == 0) 11174 EltSize = 8; 11175 EVT VT = N->getValueType(0); 11176 if (EltSize > VT.getScalarSizeInBits()) 11177 return SDValue(); 11178 11179 return DCI.DAG.getNode(ISD::BITCAST, SDLoc(N), VT, Op); 11180 } 11181 11182 /// PerformVDUPCombine - Target-specific dag combine xforms for ARMISD::VDUP. 11183 static SDValue PerformVDUPCombine(SDNode *N, 11184 TargetLowering::DAGCombinerInfo &DCI) { 11185 SelectionDAG &DAG = DCI.DAG; 11186 SDValue Op = N->getOperand(0); 11187 11188 // Match VDUP(LOAD) -> VLD1DUP. 11189 // We match this pattern here rather than waiting for isel because the 11190 // transform is only legal for unindexed loads. 11191 LoadSDNode *LD = dyn_cast<LoadSDNode>(Op.getNode()); 11192 if (LD && Op.hasOneUse() && LD->isUnindexed() && 11193 LD->getMemoryVT() == N->getValueType(0).getVectorElementType()) { 11194 SDValue Ops[] = { LD->getOperand(0), LD->getOperand(1), 11195 DAG.getConstant(LD->getAlignment(), SDLoc(N), MVT::i32) }; 11196 SDVTList SDTys = DAG.getVTList(N->getValueType(0), MVT::Other); 11197 SDValue VLDDup = DAG.getMemIntrinsicNode(ARMISD::VLD1DUP, SDLoc(N), SDTys, 11198 Ops, LD->getMemoryVT(), 11199 LD->getMemOperand()); 11200 DAG.ReplaceAllUsesOfValueWith(SDValue(LD, 1), VLDDup.getValue(1)); 11201 return VLDDup; 11202 } 11203 11204 return SDValue(); 11205 } 11206 11207 static SDValue PerformLOADCombine(SDNode *N, 11208 TargetLowering::DAGCombinerInfo &DCI) { 11209 EVT VT = N->getValueType(0); 11210 11211 // If this is a legal vector load, try to combine it into a VLD1_UPD. 11212 if (ISD::isNormalLoad(N) && VT.isVector() && 11213 DCI.DAG.getTargetLoweringInfo().isTypeLegal(VT)) 11214 return CombineBaseUpdate(N, DCI); 11215 11216 return SDValue(); 11217 } 11218 11219 /// PerformSTORECombine - Target-specific dag combine xforms for 11220 /// ISD::STORE. 11221 static SDValue PerformSTORECombine(SDNode *N, 11222 TargetLowering::DAGCombinerInfo &DCI) { 11223 StoreSDNode *St = cast<StoreSDNode>(N); 11224 if (St->isVolatile()) 11225 return SDValue(); 11226 11227 // Optimize trunc store (of multiple scalars) to shuffle and store. First, 11228 // pack all of the elements in one place. Next, store to memory in fewer 11229 // chunks. 11230 SDValue StVal = St->getValue(); 11231 EVT VT = StVal.getValueType(); 11232 if (St->isTruncatingStore() && VT.isVector()) { 11233 SelectionDAG &DAG = DCI.DAG; 11234 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 11235 EVT StVT = St->getMemoryVT(); 11236 unsigned NumElems = VT.getVectorNumElements(); 11237 assert(StVT != VT && "Cannot truncate to the same type"); 11238 unsigned FromEltSz = VT.getScalarSizeInBits(); 11239 unsigned ToEltSz = StVT.getScalarSizeInBits(); 11240 11241 // From, To sizes and ElemCount must be pow of two 11242 if (!isPowerOf2_32(NumElems * FromEltSz * ToEltSz)) return SDValue(); 11243 11244 // We are going to use the original vector elt for storing. 11245 // Accumulated smaller vector elements must be a multiple of the store size. 11246 if (0 != (NumElems * FromEltSz) % ToEltSz) return SDValue(); 11247 11248 unsigned SizeRatio = FromEltSz / ToEltSz; 11249 assert(SizeRatio * NumElems * ToEltSz == VT.getSizeInBits()); 11250 11251 // Create a type on which we perform the shuffle. 11252 EVT WideVecVT = EVT::getVectorVT(*DAG.getContext(), StVT.getScalarType(), 11253 NumElems*SizeRatio); 11254 assert(WideVecVT.getSizeInBits() == VT.getSizeInBits()); 11255 11256 SDLoc DL(St); 11257 SDValue WideVec = DAG.getNode(ISD::BITCAST, DL, WideVecVT, StVal); 11258 SmallVector<int, 8> ShuffleVec(NumElems * SizeRatio, -1); 11259 for (unsigned i = 0; i < NumElems; ++i) 11260 ShuffleVec[i] = DAG.getDataLayout().isBigEndian() 11261 ? (i + 1) * SizeRatio - 1 11262 : i * SizeRatio; 11263 11264 // Can't shuffle using an illegal type. 11265 if (!TLI.isTypeLegal(WideVecVT)) return SDValue(); 11266 11267 SDValue Shuff = DAG.getVectorShuffle(WideVecVT, DL, WideVec, 11268 DAG.getUNDEF(WideVec.getValueType()), 11269 ShuffleVec); 11270 // At this point all of the data is stored at the bottom of the 11271 // register. We now need to save it to mem. 11272 11273 // Find the largest store unit 11274 MVT StoreType = MVT::i8; 11275 for (MVT Tp : MVT::integer_valuetypes()) { 11276 if (TLI.isTypeLegal(Tp) && Tp.getSizeInBits() <= NumElems * ToEltSz) 11277 StoreType = Tp; 11278 } 11279 // Didn't find a legal store type. 11280 if (!TLI.isTypeLegal(StoreType)) 11281 return SDValue(); 11282 11283 // Bitcast the original vector into a vector of store-size units 11284 EVT StoreVecVT = EVT::getVectorVT(*DAG.getContext(), 11285 StoreType, VT.getSizeInBits()/EVT(StoreType).getSizeInBits()); 11286 assert(StoreVecVT.getSizeInBits() == VT.getSizeInBits()); 11287 SDValue ShuffWide = DAG.getNode(ISD::BITCAST, DL, StoreVecVT, Shuff); 11288 SmallVector<SDValue, 8> Chains; 11289 SDValue Increment = DAG.getConstant(StoreType.getSizeInBits() / 8, DL, 11290 TLI.getPointerTy(DAG.getDataLayout())); 11291 SDValue BasePtr = St->getBasePtr(); 11292 11293 // Perform one or more big stores into memory. 11294 unsigned E = (ToEltSz*NumElems)/StoreType.getSizeInBits(); 11295 for (unsigned I = 0; I < E; I++) { 11296 SDValue SubVec = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, 11297 StoreType, ShuffWide, 11298 DAG.getIntPtrConstant(I, DL)); 11299 SDValue Ch = DAG.getStore(St->getChain(), DL, SubVec, BasePtr, 11300 St->getPointerInfo(), St->getAlignment(), 11301 St->getMemOperand()->getFlags()); 11302 BasePtr = DAG.getNode(ISD::ADD, DL, BasePtr.getValueType(), BasePtr, 11303 Increment); 11304 Chains.push_back(Ch); 11305 } 11306 return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Chains); 11307 } 11308 11309 if (!ISD::isNormalStore(St)) 11310 return SDValue(); 11311 11312 // Split a store of a VMOVDRR into two integer stores to avoid mixing NEON and 11313 // ARM stores of arguments in the same cache line. 11314 if (StVal.getNode()->getOpcode() == ARMISD::VMOVDRR && 11315 StVal.getNode()->hasOneUse()) { 11316 SelectionDAG &DAG = DCI.DAG; 11317 bool isBigEndian = DAG.getDataLayout().isBigEndian(); 11318 SDLoc DL(St); 11319 SDValue BasePtr = St->getBasePtr(); 11320 SDValue NewST1 = DAG.getStore( 11321 St->getChain(), DL, StVal.getNode()->getOperand(isBigEndian ? 1 : 0), 11322 BasePtr, St->getPointerInfo(), St->getAlignment(), 11323 St->getMemOperand()->getFlags()); 11324 11325 SDValue OffsetPtr = DAG.getNode(ISD::ADD, DL, MVT::i32, BasePtr, 11326 DAG.getConstant(4, DL, MVT::i32)); 11327 return DAG.getStore(NewST1.getValue(0), DL, 11328 StVal.getNode()->getOperand(isBigEndian ? 0 : 1), 11329 OffsetPtr, St->getPointerInfo(), 11330 std::min(4U, St->getAlignment() / 2), 11331 St->getMemOperand()->getFlags()); 11332 } 11333 11334 if (StVal.getValueType() == MVT::i64 && 11335 StVal.getNode()->getOpcode() == ISD::EXTRACT_VECTOR_ELT) { 11336 11337 // Bitcast an i64 store extracted from a vector to f64. 11338 // Otherwise, the i64 value will be legalized to a pair of i32 values. 11339 SelectionDAG &DAG = DCI.DAG; 11340 SDLoc dl(StVal); 11341 SDValue IntVec = StVal.getOperand(0); 11342 EVT FloatVT = EVT::getVectorVT(*DAG.getContext(), MVT::f64, 11343 IntVec.getValueType().getVectorNumElements()); 11344 SDValue Vec = DAG.getNode(ISD::BITCAST, dl, FloatVT, IntVec); 11345 SDValue ExtElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, 11346 Vec, StVal.getOperand(1)); 11347 dl = SDLoc(N); 11348 SDValue V = DAG.getNode(ISD::BITCAST, dl, MVT::i64, ExtElt); 11349 // Make the DAGCombiner fold the bitcasts. 11350 DCI.AddToWorklist(Vec.getNode()); 11351 DCI.AddToWorklist(ExtElt.getNode()); 11352 DCI.AddToWorklist(V.getNode()); 11353 return DAG.getStore(St->getChain(), dl, V, St->getBasePtr(), 11354 St->getPointerInfo(), St->getAlignment(), 11355 St->getMemOperand()->getFlags(), St->getAAInfo()); 11356 } 11357 11358 // If this is a legal vector store, try to combine it into a VST1_UPD. 11359 if (ISD::isNormalStore(N) && VT.isVector() && 11360 DCI.DAG.getTargetLoweringInfo().isTypeLegal(VT)) 11361 return CombineBaseUpdate(N, DCI); 11362 11363 return SDValue(); 11364 } 11365 11366 /// PerformVCVTCombine - VCVT (floating-point to fixed-point, Advanced SIMD) 11367 /// can replace combinations of VMUL and VCVT (floating-point to integer) 11368 /// when the VMUL has a constant operand that is a power of 2. 11369 /// 11370 /// Example (assume d17 = <float 8.000000e+00, float 8.000000e+00>): 11371 /// vmul.f32 d16, d17, d16 11372 /// vcvt.s32.f32 d16, d16 11373 /// becomes: 11374 /// vcvt.s32.f32 d16, d16, #3 11375 static SDValue PerformVCVTCombine(SDNode *N, SelectionDAG &DAG, 11376 const ARMSubtarget *Subtarget) { 11377 if (!Subtarget->hasNEON()) 11378 return SDValue(); 11379 11380 SDValue Op = N->getOperand(0); 11381 if (!Op.getValueType().isVector() || !Op.getValueType().isSimple() || 11382 Op.getOpcode() != ISD::FMUL) 11383 return SDValue(); 11384 11385 SDValue ConstVec = Op->getOperand(1); 11386 if (!isa<BuildVectorSDNode>(ConstVec)) 11387 return SDValue(); 11388 11389 MVT FloatTy = Op.getSimpleValueType().getVectorElementType(); 11390 uint32_t FloatBits = FloatTy.getSizeInBits(); 11391 MVT IntTy = N->getSimpleValueType(0).getVectorElementType(); 11392 uint32_t IntBits = IntTy.getSizeInBits(); 11393 unsigned NumLanes = Op.getValueType().getVectorNumElements(); 11394 if (FloatBits != 32 || IntBits > 32 || NumLanes > 4) { 11395 // These instructions only exist converting from f32 to i32. We can handle 11396 // smaller integers by generating an extra truncate, but larger ones would 11397 // be lossy. We also can't handle more then 4 lanes, since these intructions 11398 // only support v2i32/v4i32 types. 11399 return SDValue(); 11400 } 11401 11402 BitVector UndefElements; 11403 BuildVectorSDNode *BV = cast<BuildVectorSDNode>(ConstVec); 11404 int32_t C = BV->getConstantFPSplatPow2ToLog2Int(&UndefElements, 33); 11405 if (C == -1 || C == 0 || C > 32) 11406 return SDValue(); 11407 11408 SDLoc dl(N); 11409 bool isSigned = N->getOpcode() == ISD::FP_TO_SINT; 11410 unsigned IntrinsicOpcode = isSigned ? Intrinsic::arm_neon_vcvtfp2fxs : 11411 Intrinsic::arm_neon_vcvtfp2fxu; 11412 SDValue FixConv = DAG.getNode( 11413 ISD::INTRINSIC_WO_CHAIN, dl, NumLanes == 2 ? MVT::v2i32 : MVT::v4i32, 11414 DAG.getConstant(IntrinsicOpcode, dl, MVT::i32), Op->getOperand(0), 11415 DAG.getConstant(C, dl, MVT::i32)); 11416 11417 if (IntBits < FloatBits) 11418 FixConv = DAG.getNode(ISD::TRUNCATE, dl, N->getValueType(0), FixConv); 11419 11420 return FixConv; 11421 } 11422 11423 /// PerformVDIVCombine - VCVT (fixed-point to floating-point, Advanced SIMD) 11424 /// can replace combinations of VCVT (integer to floating-point) and VDIV 11425 /// when the VDIV has a constant operand that is a power of 2. 11426 /// 11427 /// Example (assume d17 = <float 8.000000e+00, float 8.000000e+00>): 11428 /// vcvt.f32.s32 d16, d16 11429 /// vdiv.f32 d16, d17, d16 11430 /// becomes: 11431 /// vcvt.f32.s32 d16, d16, #3 11432 static SDValue PerformVDIVCombine(SDNode *N, SelectionDAG &DAG, 11433 const ARMSubtarget *Subtarget) { 11434 if (!Subtarget->hasNEON()) 11435 return SDValue(); 11436 11437 SDValue Op = N->getOperand(0); 11438 unsigned OpOpcode = Op.getNode()->getOpcode(); 11439 if (!N->getValueType(0).isVector() || !N->getValueType(0).isSimple() || 11440 (OpOpcode != ISD::SINT_TO_FP && OpOpcode != ISD::UINT_TO_FP)) 11441 return SDValue(); 11442 11443 SDValue ConstVec = N->getOperand(1); 11444 if (!isa<BuildVectorSDNode>(ConstVec)) 11445 return SDValue(); 11446 11447 MVT FloatTy = N->getSimpleValueType(0).getVectorElementType(); 11448 uint32_t FloatBits = FloatTy.getSizeInBits(); 11449 MVT IntTy = Op.getOperand(0).getSimpleValueType().getVectorElementType(); 11450 uint32_t IntBits = IntTy.getSizeInBits(); 11451 unsigned NumLanes = Op.getValueType().getVectorNumElements(); 11452 if (FloatBits != 32 || IntBits > 32 || NumLanes > 4) { 11453 // These instructions only exist converting from i32 to f32. We can handle 11454 // smaller integers by generating an extra extend, but larger ones would 11455 // be lossy. We also can't handle more then 4 lanes, since these intructions 11456 // only support v2i32/v4i32 types. 11457 return SDValue(); 11458 } 11459 11460 BitVector UndefElements; 11461 BuildVectorSDNode *BV = cast<BuildVectorSDNode>(ConstVec); 11462 int32_t C = BV->getConstantFPSplatPow2ToLog2Int(&UndefElements, 33); 11463 if (C == -1 || C == 0 || C > 32) 11464 return SDValue(); 11465 11466 SDLoc dl(N); 11467 bool isSigned = OpOpcode == ISD::SINT_TO_FP; 11468 SDValue ConvInput = Op.getOperand(0); 11469 if (IntBits < FloatBits) 11470 ConvInput = DAG.getNode(isSigned ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND, 11471 dl, NumLanes == 2 ? MVT::v2i32 : MVT::v4i32, 11472 ConvInput); 11473 11474 unsigned IntrinsicOpcode = isSigned ? Intrinsic::arm_neon_vcvtfxs2fp : 11475 Intrinsic::arm_neon_vcvtfxu2fp; 11476 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, 11477 Op.getValueType(), 11478 DAG.getConstant(IntrinsicOpcode, dl, MVT::i32), 11479 ConvInput, DAG.getConstant(C, dl, MVT::i32)); 11480 } 11481 11482 /// Getvshiftimm - Check if this is a valid build_vector for the immediate 11483 /// operand of a vector shift operation, where all the elements of the 11484 /// build_vector must have the same constant integer value. 11485 static bool getVShiftImm(SDValue Op, unsigned ElementBits, int64_t &Cnt) { 11486 // Ignore bit_converts. 11487 while (Op.getOpcode() == ISD::BITCAST) 11488 Op = Op.getOperand(0); 11489 BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(Op.getNode()); 11490 APInt SplatBits, SplatUndef; 11491 unsigned SplatBitSize; 11492 bool HasAnyUndefs; 11493 if (! BVN || ! BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, 11494 HasAnyUndefs, ElementBits) || 11495 SplatBitSize > ElementBits) 11496 return false; 11497 Cnt = SplatBits.getSExtValue(); 11498 return true; 11499 } 11500 11501 /// isVShiftLImm - Check if this is a valid build_vector for the immediate 11502 /// operand of a vector shift left operation. That value must be in the range: 11503 /// 0 <= Value < ElementBits for a left shift; or 11504 /// 0 <= Value <= ElementBits for a long left shift. 11505 static bool isVShiftLImm(SDValue Op, EVT VT, bool isLong, int64_t &Cnt) { 11506 assert(VT.isVector() && "vector shift count is not a vector type"); 11507 int64_t ElementBits = VT.getScalarSizeInBits(); 11508 if (! getVShiftImm(Op, ElementBits, Cnt)) 11509 return false; 11510 return (Cnt >= 0 && (isLong ? Cnt-1 : Cnt) < ElementBits); 11511 } 11512 11513 /// isVShiftRImm - Check if this is a valid build_vector for the immediate 11514 /// operand of a vector shift right operation. For a shift opcode, the value 11515 /// is positive, but for an intrinsic the value count must be negative. The 11516 /// absolute value must be in the range: 11517 /// 1 <= |Value| <= ElementBits for a right shift; or 11518 /// 1 <= |Value| <= ElementBits/2 for a narrow right shift. 11519 static bool isVShiftRImm(SDValue Op, EVT VT, bool isNarrow, bool isIntrinsic, 11520 int64_t &Cnt) { 11521 assert(VT.isVector() && "vector shift count is not a vector type"); 11522 int64_t ElementBits = VT.getScalarSizeInBits(); 11523 if (! getVShiftImm(Op, ElementBits, Cnt)) 11524 return false; 11525 if (!isIntrinsic) 11526 return (Cnt >= 1 && Cnt <= (isNarrow ? ElementBits/2 : ElementBits)); 11527 if (Cnt >= -(isNarrow ? ElementBits/2 : ElementBits) && Cnt <= -1) { 11528 Cnt = -Cnt; 11529 return true; 11530 } 11531 return false; 11532 } 11533 11534 /// PerformIntrinsicCombine - ARM-specific DAG combining for intrinsics. 11535 static SDValue PerformIntrinsicCombine(SDNode *N, SelectionDAG &DAG) { 11536 unsigned IntNo = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue(); 11537 switch (IntNo) { 11538 default: 11539 // Don't do anything for most intrinsics. 11540 break; 11541 11542 // Vector shifts: check for immediate versions and lower them. 11543 // Note: This is done during DAG combining instead of DAG legalizing because 11544 // the build_vectors for 64-bit vector element shift counts are generally 11545 // not legal, and it is hard to see their values after they get legalized to 11546 // loads from a constant pool. 11547 case Intrinsic::arm_neon_vshifts: 11548 case Intrinsic::arm_neon_vshiftu: 11549 case Intrinsic::arm_neon_vrshifts: 11550 case Intrinsic::arm_neon_vrshiftu: 11551 case Intrinsic::arm_neon_vrshiftn: 11552 case Intrinsic::arm_neon_vqshifts: 11553 case Intrinsic::arm_neon_vqshiftu: 11554 case Intrinsic::arm_neon_vqshiftsu: 11555 case Intrinsic::arm_neon_vqshiftns: 11556 case Intrinsic::arm_neon_vqshiftnu: 11557 case Intrinsic::arm_neon_vqshiftnsu: 11558 case Intrinsic::arm_neon_vqrshiftns: 11559 case Intrinsic::arm_neon_vqrshiftnu: 11560 case Intrinsic::arm_neon_vqrshiftnsu: { 11561 EVT VT = N->getOperand(1).getValueType(); 11562 int64_t Cnt; 11563 unsigned VShiftOpc = 0; 11564 11565 switch (IntNo) { 11566 case Intrinsic::arm_neon_vshifts: 11567 case Intrinsic::arm_neon_vshiftu: 11568 if (isVShiftLImm(N->getOperand(2), VT, false, Cnt)) { 11569 VShiftOpc = ARMISD::VSHL; 11570 break; 11571 } 11572 if (isVShiftRImm(N->getOperand(2), VT, false, true, Cnt)) { 11573 VShiftOpc = (IntNo == Intrinsic::arm_neon_vshifts ? 11574 ARMISD::VSHRs : ARMISD::VSHRu); 11575 break; 11576 } 11577 return SDValue(); 11578 11579 case Intrinsic::arm_neon_vrshifts: 11580 case Intrinsic::arm_neon_vrshiftu: 11581 if (isVShiftRImm(N->getOperand(2), VT, false, true, Cnt)) 11582 break; 11583 return SDValue(); 11584 11585 case Intrinsic::arm_neon_vqshifts: 11586 case Intrinsic::arm_neon_vqshiftu: 11587 if (isVShiftLImm(N->getOperand(2), VT, false, Cnt)) 11588 break; 11589 return SDValue(); 11590 11591 case Intrinsic::arm_neon_vqshiftsu: 11592 if (isVShiftLImm(N->getOperand(2), VT, false, Cnt)) 11593 break; 11594 llvm_unreachable("invalid shift count for vqshlu intrinsic"); 11595 11596 case Intrinsic::arm_neon_vrshiftn: 11597 case Intrinsic::arm_neon_vqshiftns: 11598 case Intrinsic::arm_neon_vqshiftnu: 11599 case Intrinsic::arm_neon_vqshiftnsu: 11600 case Intrinsic::arm_neon_vqrshiftns: 11601 case Intrinsic::arm_neon_vqrshiftnu: 11602 case Intrinsic::arm_neon_vqrshiftnsu: 11603 // Narrowing shifts require an immediate right shift. 11604 if (isVShiftRImm(N->getOperand(2), VT, true, true, Cnt)) 11605 break; 11606 llvm_unreachable("invalid shift count for narrowing vector shift " 11607 "intrinsic"); 11608 11609 default: 11610 llvm_unreachable("unhandled vector shift"); 11611 } 11612 11613 switch (IntNo) { 11614 case Intrinsic::arm_neon_vshifts: 11615 case Intrinsic::arm_neon_vshiftu: 11616 // Opcode already set above. 11617 break; 11618 case Intrinsic::arm_neon_vrshifts: 11619 VShiftOpc = ARMISD::VRSHRs; break; 11620 case Intrinsic::arm_neon_vrshiftu: 11621 VShiftOpc = ARMISD::VRSHRu; break; 11622 case Intrinsic::arm_neon_vrshiftn: 11623 VShiftOpc = ARMISD::VRSHRN; break; 11624 case Intrinsic::arm_neon_vqshifts: 11625 VShiftOpc = ARMISD::VQSHLs; break; 11626 case Intrinsic::arm_neon_vqshiftu: 11627 VShiftOpc = ARMISD::VQSHLu; break; 11628 case Intrinsic::arm_neon_vqshiftsu: 11629 VShiftOpc = ARMISD::VQSHLsu; break; 11630 case Intrinsic::arm_neon_vqshiftns: 11631 VShiftOpc = ARMISD::VQSHRNs; break; 11632 case Intrinsic::arm_neon_vqshiftnu: 11633 VShiftOpc = ARMISD::VQSHRNu; break; 11634 case Intrinsic::arm_neon_vqshiftnsu: 11635 VShiftOpc = ARMISD::VQSHRNsu; break; 11636 case Intrinsic::arm_neon_vqrshiftns: 11637 VShiftOpc = ARMISD::VQRSHRNs; break; 11638 case Intrinsic::arm_neon_vqrshiftnu: 11639 VShiftOpc = ARMISD::VQRSHRNu; break; 11640 case Intrinsic::arm_neon_vqrshiftnsu: 11641 VShiftOpc = ARMISD::VQRSHRNsu; break; 11642 } 11643 11644 SDLoc dl(N); 11645 return DAG.getNode(VShiftOpc, dl, N->getValueType(0), 11646 N->getOperand(1), DAG.getConstant(Cnt, dl, MVT::i32)); 11647 } 11648 11649 case Intrinsic::arm_neon_vshiftins: { 11650 EVT VT = N->getOperand(1).getValueType(); 11651 int64_t Cnt; 11652 unsigned VShiftOpc = 0; 11653 11654 if (isVShiftLImm(N->getOperand(3), VT, false, Cnt)) 11655 VShiftOpc = ARMISD::VSLI; 11656 else if (isVShiftRImm(N->getOperand(3), VT, false, true, Cnt)) 11657 VShiftOpc = ARMISD::VSRI; 11658 else { 11659 llvm_unreachable("invalid shift count for vsli/vsri intrinsic"); 11660 } 11661 11662 SDLoc dl(N); 11663 return DAG.getNode(VShiftOpc, dl, N->getValueType(0), 11664 N->getOperand(1), N->getOperand(2), 11665 DAG.getConstant(Cnt, dl, MVT::i32)); 11666 } 11667 11668 case Intrinsic::arm_neon_vqrshifts: 11669 case Intrinsic::arm_neon_vqrshiftu: 11670 // No immediate versions of these to check for. 11671 break; 11672 } 11673 11674 return SDValue(); 11675 } 11676 11677 /// PerformShiftCombine - Checks for immediate versions of vector shifts and 11678 /// lowers them. As with the vector shift intrinsics, this is done during DAG 11679 /// combining instead of DAG legalizing because the build_vectors for 64-bit 11680 /// vector element shift counts are generally not legal, and it is hard to see 11681 /// their values after they get legalized to loads from a constant pool. 11682 static SDValue PerformShiftCombine(SDNode *N, SelectionDAG &DAG, 11683 const ARMSubtarget *ST) { 11684 EVT VT = N->getValueType(0); 11685 if (N->getOpcode() == ISD::SRL && VT == MVT::i32 && ST->hasV6Ops()) { 11686 // Canonicalize (srl (bswap x), 16) to (rotr (bswap x), 16) if the high 11687 // 16-bits of x is zero. This optimizes rev + lsr 16 to rev16. 11688 SDValue N1 = N->getOperand(1); 11689 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(N1)) { 11690 SDValue N0 = N->getOperand(0); 11691 if (C->getZExtValue() == 16 && N0.getOpcode() == ISD::BSWAP && 11692 DAG.MaskedValueIsZero(N0.getOperand(0), 11693 APInt::getHighBitsSet(32, 16))) 11694 return DAG.getNode(ISD::ROTR, SDLoc(N), VT, N0, N1); 11695 } 11696 } 11697 11698 // Nothing to be done for scalar shifts. 11699 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 11700 if (!VT.isVector() || !TLI.isTypeLegal(VT)) 11701 return SDValue(); 11702 11703 assert(ST->hasNEON() && "unexpected vector shift"); 11704 int64_t Cnt; 11705 11706 switch (N->getOpcode()) { 11707 default: llvm_unreachable("unexpected shift opcode"); 11708 11709 case ISD::SHL: 11710 if (isVShiftLImm(N->getOperand(1), VT, false, Cnt)) { 11711 SDLoc dl(N); 11712 return DAG.getNode(ARMISD::VSHL, dl, VT, N->getOperand(0), 11713 DAG.getConstant(Cnt, dl, MVT::i32)); 11714 } 11715 break; 11716 11717 case ISD::SRA: 11718 case ISD::SRL: 11719 if (isVShiftRImm(N->getOperand(1), VT, false, false, Cnt)) { 11720 unsigned VShiftOpc = (N->getOpcode() == ISD::SRA ? 11721 ARMISD::VSHRs : ARMISD::VSHRu); 11722 SDLoc dl(N); 11723 return DAG.getNode(VShiftOpc, dl, VT, N->getOperand(0), 11724 DAG.getConstant(Cnt, dl, MVT::i32)); 11725 } 11726 } 11727 return SDValue(); 11728 } 11729 11730 /// PerformExtendCombine - Target-specific DAG combining for ISD::SIGN_EXTEND, 11731 /// ISD::ZERO_EXTEND, and ISD::ANY_EXTEND. 11732 static SDValue PerformExtendCombine(SDNode *N, SelectionDAG &DAG, 11733 const ARMSubtarget *ST) { 11734 SDValue N0 = N->getOperand(0); 11735 11736 // Check for sign- and zero-extensions of vector extract operations of 8- 11737 // and 16-bit vector elements. NEON supports these directly. They are 11738 // handled during DAG combining because type legalization will promote them 11739 // to 32-bit types and it is messy to recognize the operations after that. 11740 if (ST->hasNEON() && N0.getOpcode() == ISD::EXTRACT_VECTOR_ELT) { 11741 SDValue Vec = N0.getOperand(0); 11742 SDValue Lane = N0.getOperand(1); 11743 EVT VT = N->getValueType(0); 11744 EVT EltVT = N0.getValueType(); 11745 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 11746 11747 if (VT == MVT::i32 && 11748 (EltVT == MVT::i8 || EltVT == MVT::i16) && 11749 TLI.isTypeLegal(Vec.getValueType()) && 11750 isa<ConstantSDNode>(Lane)) { 11751 11752 unsigned Opc = 0; 11753 switch (N->getOpcode()) { 11754 default: llvm_unreachable("unexpected opcode"); 11755 case ISD::SIGN_EXTEND: 11756 Opc = ARMISD::VGETLANEs; 11757 break; 11758 case ISD::ZERO_EXTEND: 11759 case ISD::ANY_EXTEND: 11760 Opc = ARMISD::VGETLANEu; 11761 break; 11762 } 11763 return DAG.getNode(Opc, SDLoc(N), VT, Vec, Lane); 11764 } 11765 } 11766 11767 return SDValue(); 11768 } 11769 11770 SDValue ARMTargetLowering::PerformCMOVToBFICombine(SDNode *CMOV, SelectionDAG &DAG) const { 11771 // If we have a CMOV, OR and AND combination such as: 11772 // if (x & CN) 11773 // y |= CM; 11774 // 11775 // And: 11776 // * CN is a single bit; 11777 // * All bits covered by CM are known zero in y 11778 // 11779 // Then we can convert this into a sequence of BFI instructions. This will 11780 // always be a win if CM is a single bit, will always be no worse than the 11781 // TST&OR sequence if CM is two bits, and for thumb will be no worse if CM is 11782 // three bits (due to the extra IT instruction). 11783 11784 SDValue Op0 = CMOV->getOperand(0); 11785 SDValue Op1 = CMOV->getOperand(1); 11786 auto CCNode = cast<ConstantSDNode>(CMOV->getOperand(2)); 11787 auto CC = CCNode->getAPIntValue().getLimitedValue(); 11788 SDValue CmpZ = CMOV->getOperand(4); 11789 11790 // The compare must be against zero. 11791 if (!isNullConstant(CmpZ->getOperand(1))) 11792 return SDValue(); 11793 11794 assert(CmpZ->getOpcode() == ARMISD::CMPZ); 11795 SDValue And = CmpZ->getOperand(0); 11796 if (And->getOpcode() != ISD::AND) 11797 return SDValue(); 11798 ConstantSDNode *AndC = dyn_cast<ConstantSDNode>(And->getOperand(1)); 11799 if (!AndC || !AndC->getAPIntValue().isPowerOf2()) 11800 return SDValue(); 11801 SDValue X = And->getOperand(0); 11802 11803 if (CC == ARMCC::EQ) { 11804 // We're performing an "equal to zero" compare. Swap the operands so we 11805 // canonicalize on a "not equal to zero" compare. 11806 std::swap(Op0, Op1); 11807 } else { 11808 assert(CC == ARMCC::NE && "How can a CMPZ node not be EQ or NE?"); 11809 } 11810 11811 if (Op1->getOpcode() != ISD::OR) 11812 return SDValue(); 11813 11814 ConstantSDNode *OrC = dyn_cast<ConstantSDNode>(Op1->getOperand(1)); 11815 if (!OrC) 11816 return SDValue(); 11817 SDValue Y = Op1->getOperand(0); 11818 11819 if (Op0 != Y) 11820 return SDValue(); 11821 11822 // Now, is it profitable to continue? 11823 APInt OrCI = OrC->getAPIntValue(); 11824 unsigned Heuristic = Subtarget->isThumb() ? 3 : 2; 11825 if (OrCI.countPopulation() > Heuristic) 11826 return SDValue(); 11827 11828 // Lastly, can we determine that the bits defined by OrCI 11829 // are zero in Y? 11830 KnownBits Known; 11831 DAG.computeKnownBits(Y, Known); 11832 if ((OrCI & Known.Zero) != OrCI) 11833 return SDValue(); 11834 11835 // OK, we can do the combine. 11836 SDValue V = Y; 11837 SDLoc dl(X); 11838 EVT VT = X.getValueType(); 11839 unsigned BitInX = AndC->getAPIntValue().logBase2(); 11840 11841 if (BitInX != 0) { 11842 // We must shift X first. 11843 X = DAG.getNode(ISD::SRL, dl, VT, X, 11844 DAG.getConstant(BitInX, dl, VT)); 11845 } 11846 11847 for (unsigned BitInY = 0, NumActiveBits = OrCI.getActiveBits(); 11848 BitInY < NumActiveBits; ++BitInY) { 11849 if (OrCI[BitInY] == 0) 11850 continue; 11851 APInt Mask(VT.getSizeInBits(), 0); 11852 Mask.setBit(BitInY); 11853 V = DAG.getNode(ARMISD::BFI, dl, VT, V, X, 11854 // Confusingly, the operand is an *inverted* mask. 11855 DAG.getConstant(~Mask, dl, VT)); 11856 } 11857 11858 return V; 11859 } 11860 11861 /// PerformBRCONDCombine - Target-specific DAG combining for ARMISD::BRCOND. 11862 SDValue 11863 ARMTargetLowering::PerformBRCONDCombine(SDNode *N, SelectionDAG &DAG) const { 11864 SDValue Cmp = N->getOperand(4); 11865 if (Cmp.getOpcode() != ARMISD::CMPZ) 11866 // Only looking at NE cases. 11867 return SDValue(); 11868 11869 EVT VT = N->getValueType(0); 11870 SDLoc dl(N); 11871 SDValue LHS = Cmp.getOperand(0); 11872 SDValue RHS = Cmp.getOperand(1); 11873 SDValue Chain = N->getOperand(0); 11874 SDValue BB = N->getOperand(1); 11875 SDValue ARMcc = N->getOperand(2); 11876 ARMCC::CondCodes CC = 11877 (ARMCC::CondCodes)cast<ConstantSDNode>(ARMcc)->getZExtValue(); 11878 11879 // (brcond Chain BB ne CPSR (cmpz (and (cmov 0 1 CC CPSR Cmp) 1) 0)) 11880 // -> (brcond Chain BB CC CPSR Cmp) 11881 if (CC == ARMCC::NE && LHS.getOpcode() == ISD::AND && LHS->hasOneUse() && 11882 LHS->getOperand(0)->getOpcode() == ARMISD::CMOV && 11883 LHS->getOperand(0)->hasOneUse()) { 11884 auto *LHS00C = dyn_cast<ConstantSDNode>(LHS->getOperand(0)->getOperand(0)); 11885 auto *LHS01C = dyn_cast<ConstantSDNode>(LHS->getOperand(0)->getOperand(1)); 11886 auto *LHS1C = dyn_cast<ConstantSDNode>(LHS->getOperand(1)); 11887 auto *RHSC = dyn_cast<ConstantSDNode>(RHS); 11888 if ((LHS00C && LHS00C->getZExtValue() == 0) && 11889 (LHS01C && LHS01C->getZExtValue() == 1) && 11890 (LHS1C && LHS1C->getZExtValue() == 1) && 11891 (RHSC && RHSC->getZExtValue() == 0)) { 11892 return DAG.getNode( 11893 ARMISD::BRCOND, dl, VT, Chain, BB, LHS->getOperand(0)->getOperand(2), 11894 LHS->getOperand(0)->getOperand(3), LHS->getOperand(0)->getOperand(4)); 11895 } 11896 } 11897 11898 return SDValue(); 11899 } 11900 11901 /// PerformCMOVCombine - Target-specific DAG combining for ARMISD::CMOV. 11902 SDValue 11903 ARMTargetLowering::PerformCMOVCombine(SDNode *N, SelectionDAG &DAG) const { 11904 SDValue Cmp = N->getOperand(4); 11905 if (Cmp.getOpcode() != ARMISD::CMPZ) 11906 // Only looking at EQ and NE cases. 11907 return SDValue(); 11908 11909 EVT VT = N->getValueType(0); 11910 SDLoc dl(N); 11911 SDValue LHS = Cmp.getOperand(0); 11912 SDValue RHS = Cmp.getOperand(1); 11913 SDValue FalseVal = N->getOperand(0); 11914 SDValue TrueVal = N->getOperand(1); 11915 SDValue ARMcc = N->getOperand(2); 11916 ARMCC::CondCodes CC = 11917 (ARMCC::CondCodes)cast<ConstantSDNode>(ARMcc)->getZExtValue(); 11918 11919 // BFI is only available on V6T2+. 11920 if (!Subtarget->isThumb1Only() && Subtarget->hasV6T2Ops()) { 11921 SDValue R = PerformCMOVToBFICombine(N, DAG); 11922 if (R) 11923 return R; 11924 } 11925 11926 // Simplify 11927 // mov r1, r0 11928 // cmp r1, x 11929 // mov r0, y 11930 // moveq r0, x 11931 // to 11932 // cmp r0, x 11933 // movne r0, y 11934 // 11935 // mov r1, r0 11936 // cmp r1, x 11937 // mov r0, x 11938 // movne r0, y 11939 // to 11940 // cmp r0, x 11941 // movne r0, y 11942 /// FIXME: Turn this into a target neutral optimization? 11943 SDValue Res; 11944 if (CC == ARMCC::NE && FalseVal == RHS && FalseVal != LHS) { 11945 Res = DAG.getNode(ARMISD::CMOV, dl, VT, LHS, TrueVal, ARMcc, 11946 N->getOperand(3), Cmp); 11947 } else if (CC == ARMCC::EQ && TrueVal == RHS) { 11948 SDValue ARMcc; 11949 SDValue NewCmp = getARMCmp(LHS, RHS, ISD::SETNE, ARMcc, DAG, dl); 11950 Res = DAG.getNode(ARMISD::CMOV, dl, VT, LHS, FalseVal, ARMcc, 11951 N->getOperand(3), NewCmp); 11952 } 11953 11954 // (cmov F T ne CPSR (cmpz (cmov 0 1 CC CPSR Cmp) 0)) 11955 // -> (cmov F T CC CPSR Cmp) 11956 if (CC == ARMCC::NE && LHS.getOpcode() == ARMISD::CMOV && LHS->hasOneUse()) { 11957 auto *LHS0C = dyn_cast<ConstantSDNode>(LHS->getOperand(0)); 11958 auto *LHS1C = dyn_cast<ConstantSDNode>(LHS->getOperand(1)); 11959 auto *RHSC = dyn_cast<ConstantSDNode>(RHS); 11960 if ((LHS0C && LHS0C->getZExtValue() == 0) && 11961 (LHS1C && LHS1C->getZExtValue() == 1) && 11962 (RHSC && RHSC->getZExtValue() == 0)) { 11963 return DAG.getNode(ARMISD::CMOV, dl, VT, FalseVal, TrueVal, 11964 LHS->getOperand(2), LHS->getOperand(3), 11965 LHS->getOperand(4)); 11966 } 11967 } 11968 11969 if (Res.getNode()) { 11970 KnownBits Known; 11971 DAG.computeKnownBits(SDValue(N,0), Known); 11972 // Capture demanded bits information that would be otherwise lost. 11973 if (Known.Zero == 0xfffffffe) 11974 Res = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Res, 11975 DAG.getValueType(MVT::i1)); 11976 else if (Known.Zero == 0xffffff00) 11977 Res = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Res, 11978 DAG.getValueType(MVT::i8)); 11979 else if (Known.Zero == 0xffff0000) 11980 Res = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Res, 11981 DAG.getValueType(MVT::i16)); 11982 } 11983 11984 return Res; 11985 } 11986 11987 SDValue ARMTargetLowering::PerformDAGCombine(SDNode *N, 11988 DAGCombinerInfo &DCI) const { 11989 switch (N->getOpcode()) { 11990 default: break; 11991 case ARMISD::ADDE: return PerformADDECombine(N, DCI, Subtarget); 11992 case ARMISD::UMLAL: return PerformUMLALCombine(N, DCI.DAG, Subtarget); 11993 case ISD::ADD: return PerformADDCombine(N, DCI, Subtarget); 11994 case ISD::SUB: return PerformSUBCombine(N, DCI); 11995 case ISD::MUL: return PerformMULCombine(N, DCI, Subtarget); 11996 case ISD::OR: return PerformORCombine(N, DCI, Subtarget); 11997 case ISD::XOR: return PerformXORCombine(N, DCI, Subtarget); 11998 case ISD::AND: return PerformANDCombine(N, DCI, Subtarget); 11999 case ARMISD::ADDC: 12000 case ARMISD::SUBC: return PerformAddcSubcCombine(N, DCI.DAG, Subtarget); 12001 case ARMISD::SUBE: return PerformAddeSubeCombine(N, DCI.DAG, Subtarget); 12002 case ARMISD::BFI: return PerformBFICombine(N, DCI); 12003 case ARMISD::VMOVRRD: return PerformVMOVRRDCombine(N, DCI, Subtarget); 12004 case ARMISD::VMOVDRR: return PerformVMOVDRRCombine(N, DCI.DAG); 12005 case ISD::STORE: return PerformSTORECombine(N, DCI); 12006 case ISD::BUILD_VECTOR: return PerformBUILD_VECTORCombine(N, DCI, Subtarget); 12007 case ISD::INSERT_VECTOR_ELT: return PerformInsertEltCombine(N, DCI); 12008 case ISD::VECTOR_SHUFFLE: return PerformVECTOR_SHUFFLECombine(N, DCI.DAG); 12009 case ARMISD::VDUPLANE: return PerformVDUPLANECombine(N, DCI); 12010 case ARMISD::VDUP: return PerformVDUPCombine(N, DCI); 12011 case ISD::FP_TO_SINT: 12012 case ISD::FP_TO_UINT: 12013 return PerformVCVTCombine(N, DCI.DAG, Subtarget); 12014 case ISD::FDIV: 12015 return PerformVDIVCombine(N, DCI.DAG, Subtarget); 12016 case ISD::INTRINSIC_WO_CHAIN: return PerformIntrinsicCombine(N, DCI.DAG); 12017 case ISD::SHL: 12018 case ISD::SRA: 12019 case ISD::SRL: return PerformShiftCombine(N, DCI.DAG, Subtarget); 12020 case ISD::SIGN_EXTEND: 12021 case ISD::ZERO_EXTEND: 12022 case ISD::ANY_EXTEND: return PerformExtendCombine(N, DCI.DAG, Subtarget); 12023 case ARMISD::CMOV: return PerformCMOVCombine(N, DCI.DAG); 12024 case ARMISD::BRCOND: return PerformBRCONDCombine(N, DCI.DAG); 12025 case ISD::LOAD: return PerformLOADCombine(N, DCI); 12026 case ARMISD::VLD1DUP: 12027 case ARMISD::VLD2DUP: 12028 case ARMISD::VLD3DUP: 12029 case ARMISD::VLD4DUP: 12030 return PerformVLDCombine(N, DCI); 12031 case ARMISD::BUILD_VECTOR: 12032 return PerformARMBUILD_VECTORCombine(N, DCI); 12033 case ARMISD::SMULWB: { 12034 unsigned BitWidth = N->getValueType(0).getSizeInBits(); 12035 APInt DemandedMask = APInt::getLowBitsSet(BitWidth, 16); 12036 if (SimplifyDemandedBits(N->getOperand(1), DemandedMask, DCI)) 12037 return SDValue(); 12038 break; 12039 } 12040 case ARMISD::SMULWT: { 12041 unsigned BitWidth = N->getValueType(0).getSizeInBits(); 12042 APInt DemandedMask = APInt::getHighBitsSet(BitWidth, 16); 12043 if (SimplifyDemandedBits(N->getOperand(1), DemandedMask, DCI)) 12044 return SDValue(); 12045 break; 12046 } 12047 case ARMISD::SMLALBB: { 12048 unsigned BitWidth = N->getValueType(0).getSizeInBits(); 12049 APInt DemandedMask = APInt::getLowBitsSet(BitWidth, 16); 12050 if ((SimplifyDemandedBits(N->getOperand(0), DemandedMask, DCI)) || 12051 (SimplifyDemandedBits(N->getOperand(1), DemandedMask, DCI))) 12052 return SDValue(); 12053 break; 12054 } 12055 case ARMISD::SMLALBT: { 12056 unsigned LowWidth = N->getOperand(0).getValueType().getSizeInBits(); 12057 APInt LowMask = APInt::getLowBitsSet(LowWidth, 16); 12058 unsigned HighWidth = N->getOperand(1).getValueType().getSizeInBits(); 12059 APInt HighMask = APInt::getHighBitsSet(HighWidth, 16); 12060 if ((SimplifyDemandedBits(N->getOperand(0), LowMask, DCI)) || 12061 (SimplifyDemandedBits(N->getOperand(1), HighMask, DCI))) 12062 return SDValue(); 12063 break; 12064 } 12065 case ARMISD::SMLALTB: { 12066 unsigned HighWidth = N->getOperand(0).getValueType().getSizeInBits(); 12067 APInt HighMask = APInt::getHighBitsSet(HighWidth, 16); 12068 unsigned LowWidth = N->getOperand(1).getValueType().getSizeInBits(); 12069 APInt LowMask = APInt::getLowBitsSet(LowWidth, 16); 12070 if ((SimplifyDemandedBits(N->getOperand(0), HighMask, DCI)) || 12071 (SimplifyDemandedBits(N->getOperand(1), LowMask, DCI))) 12072 return SDValue(); 12073 break; 12074 } 12075 case ARMISD::SMLALTT: { 12076 unsigned BitWidth = N->getValueType(0).getSizeInBits(); 12077 APInt DemandedMask = APInt::getHighBitsSet(BitWidth, 16); 12078 if ((SimplifyDemandedBits(N->getOperand(0), DemandedMask, DCI)) || 12079 (SimplifyDemandedBits(N->getOperand(1), DemandedMask, DCI))) 12080 return SDValue(); 12081 break; 12082 } 12083 case ISD::INTRINSIC_VOID: 12084 case ISD::INTRINSIC_W_CHAIN: 12085 switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) { 12086 case Intrinsic::arm_neon_vld1: 12087 case Intrinsic::arm_neon_vld2: 12088 case Intrinsic::arm_neon_vld3: 12089 case Intrinsic::arm_neon_vld4: 12090 case Intrinsic::arm_neon_vld2lane: 12091 case Intrinsic::arm_neon_vld3lane: 12092 case Intrinsic::arm_neon_vld4lane: 12093 case Intrinsic::arm_neon_vst1: 12094 case Intrinsic::arm_neon_vst2: 12095 case Intrinsic::arm_neon_vst3: 12096 case Intrinsic::arm_neon_vst4: 12097 case Intrinsic::arm_neon_vst2lane: 12098 case Intrinsic::arm_neon_vst3lane: 12099 case Intrinsic::arm_neon_vst4lane: 12100 return PerformVLDCombine(N, DCI); 12101 default: break; 12102 } 12103 break; 12104 } 12105 return SDValue(); 12106 } 12107 12108 bool ARMTargetLowering::isDesirableToTransformToIntegerOp(unsigned Opc, 12109 EVT VT) const { 12110 return (VT == MVT::f32) && (Opc == ISD::LOAD || Opc == ISD::STORE); 12111 } 12112 12113 bool ARMTargetLowering::allowsMisalignedMemoryAccesses(EVT VT, 12114 unsigned, 12115 unsigned, 12116 bool *Fast) const { 12117 // The AllowsUnaliged flag models the SCTLR.A setting in ARM cpus 12118 bool AllowsUnaligned = Subtarget->allowsUnalignedMem(); 12119 12120 switch (VT.getSimpleVT().SimpleTy) { 12121 default: 12122 return false; 12123 case MVT::i8: 12124 case MVT::i16: 12125 case MVT::i32: { 12126 // Unaligned access can use (for example) LRDB, LRDH, LDR 12127 if (AllowsUnaligned) { 12128 if (Fast) 12129 *Fast = Subtarget->hasV7Ops(); 12130 return true; 12131 } 12132 return false; 12133 } 12134 case MVT::f64: 12135 case MVT::v2f64: { 12136 // For any little-endian targets with neon, we can support unaligned ld/st 12137 // of D and Q (e.g. {D0,D1}) registers by using vld1.i8/vst1.i8. 12138 // A big-endian target may also explicitly support unaligned accesses 12139 if (Subtarget->hasNEON() && (AllowsUnaligned || Subtarget->isLittle())) { 12140 if (Fast) 12141 *Fast = true; 12142 return true; 12143 } 12144 return false; 12145 } 12146 } 12147 } 12148 12149 static bool memOpAlign(unsigned DstAlign, unsigned SrcAlign, 12150 unsigned AlignCheck) { 12151 return ((SrcAlign == 0 || SrcAlign % AlignCheck == 0) && 12152 (DstAlign == 0 || DstAlign % AlignCheck == 0)); 12153 } 12154 12155 EVT ARMTargetLowering::getOptimalMemOpType(uint64_t Size, 12156 unsigned DstAlign, unsigned SrcAlign, 12157 bool IsMemset, bool ZeroMemset, 12158 bool MemcpyStrSrc, 12159 MachineFunction &MF) const { 12160 const Function *F = MF.getFunction(); 12161 12162 // See if we can use NEON instructions for this... 12163 if ((!IsMemset || ZeroMemset) && Subtarget->hasNEON() && 12164 !F->hasFnAttribute(Attribute::NoImplicitFloat)) { 12165 bool Fast; 12166 if (Size >= 16 && 12167 (memOpAlign(SrcAlign, DstAlign, 16) || 12168 (allowsMisalignedMemoryAccesses(MVT::v2f64, 0, 1, &Fast) && Fast))) { 12169 return MVT::v2f64; 12170 } else if (Size >= 8 && 12171 (memOpAlign(SrcAlign, DstAlign, 8) || 12172 (allowsMisalignedMemoryAccesses(MVT::f64, 0, 1, &Fast) && 12173 Fast))) { 12174 return MVT::f64; 12175 } 12176 } 12177 12178 // Let the target-independent logic figure it out. 12179 return MVT::Other; 12180 } 12181 12182 bool ARMTargetLowering::isZExtFree(SDValue Val, EVT VT2) const { 12183 if (Val.getOpcode() != ISD::LOAD) 12184 return false; 12185 12186 EVT VT1 = Val.getValueType(); 12187 if (!VT1.isSimple() || !VT1.isInteger() || 12188 !VT2.isSimple() || !VT2.isInteger()) 12189 return false; 12190 12191 switch (VT1.getSimpleVT().SimpleTy) { 12192 default: break; 12193 case MVT::i1: 12194 case MVT::i8: 12195 case MVT::i16: 12196 // 8-bit and 16-bit loads implicitly zero-extend to 32-bits. 12197 return true; 12198 } 12199 12200 return false; 12201 } 12202 12203 bool ARMTargetLowering::isVectorLoadExtDesirable(SDValue ExtVal) const { 12204 EVT VT = ExtVal.getValueType(); 12205 12206 if (!isTypeLegal(VT)) 12207 return false; 12208 12209 // Don't create a loadext if we can fold the extension into a wide/long 12210 // instruction. 12211 // If there's more than one user instruction, the loadext is desirable no 12212 // matter what. There can be two uses by the same instruction. 12213 if (ExtVal->use_empty() || 12214 !ExtVal->use_begin()->isOnlyUserOf(ExtVal.getNode())) 12215 return true; 12216 12217 SDNode *U = *ExtVal->use_begin(); 12218 if ((U->getOpcode() == ISD::ADD || U->getOpcode() == ISD::SUB || 12219 U->getOpcode() == ISD::SHL || U->getOpcode() == ARMISD::VSHL)) 12220 return false; 12221 12222 return true; 12223 } 12224 12225 bool ARMTargetLowering::allowTruncateForTailCall(Type *Ty1, Type *Ty2) const { 12226 if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy()) 12227 return false; 12228 12229 if (!isTypeLegal(EVT::getEVT(Ty1))) 12230 return false; 12231 12232 assert(Ty1->getPrimitiveSizeInBits() <= 64 && "i128 is probably not a noop"); 12233 12234 // Assuming the caller doesn't have a zeroext or signext return parameter, 12235 // truncation all the way down to i1 is valid. 12236 return true; 12237 } 12238 12239 int ARMTargetLowering::getScalingFactorCost(const DataLayout &DL, 12240 const AddrMode &AM, Type *Ty, 12241 unsigned AS) const { 12242 if (isLegalAddressingMode(DL, AM, Ty, AS)) { 12243 if (Subtarget->hasFPAO()) 12244 return AM.Scale < 0 ? 1 : 0; // positive offsets execute faster 12245 return 0; 12246 } 12247 return -1; 12248 } 12249 12250 12251 static bool isLegalT1AddressImmediate(int64_t V, EVT VT) { 12252 if (V < 0) 12253 return false; 12254 12255 unsigned Scale = 1; 12256 switch (VT.getSimpleVT().SimpleTy) { 12257 default: return false; 12258 case MVT::i1: 12259 case MVT::i8: 12260 // Scale == 1; 12261 break; 12262 case MVT::i16: 12263 // Scale == 2; 12264 Scale = 2; 12265 break; 12266 case MVT::i32: 12267 // Scale == 4; 12268 Scale = 4; 12269 break; 12270 } 12271 12272 if ((V & (Scale - 1)) != 0) 12273 return false; 12274 V /= Scale; 12275 return V == (V & ((1LL << 5) - 1)); 12276 } 12277 12278 static bool isLegalT2AddressImmediate(int64_t V, EVT VT, 12279 const ARMSubtarget *Subtarget) { 12280 bool isNeg = false; 12281 if (V < 0) { 12282 isNeg = true; 12283 V = - V; 12284 } 12285 12286 switch (VT.getSimpleVT().SimpleTy) { 12287 default: return false; 12288 case MVT::i1: 12289 case MVT::i8: 12290 case MVT::i16: 12291 case MVT::i32: 12292 // + imm12 or - imm8 12293 if (isNeg) 12294 return V == (V & ((1LL << 8) - 1)); 12295 return V == (V & ((1LL << 12) - 1)); 12296 case MVT::f32: 12297 case MVT::f64: 12298 // Same as ARM mode. FIXME: NEON? 12299 if (!Subtarget->hasVFP2()) 12300 return false; 12301 if ((V & 3) != 0) 12302 return false; 12303 V >>= 2; 12304 return V == (V & ((1LL << 8) - 1)); 12305 } 12306 } 12307 12308 /// isLegalAddressImmediate - Return true if the integer value can be used 12309 /// as the offset of the target addressing mode for load / store of the 12310 /// given type. 12311 static bool isLegalAddressImmediate(int64_t V, EVT VT, 12312 const ARMSubtarget *Subtarget) { 12313 if (V == 0) 12314 return true; 12315 12316 if (!VT.isSimple()) 12317 return false; 12318 12319 if (Subtarget->isThumb1Only()) 12320 return isLegalT1AddressImmediate(V, VT); 12321 else if (Subtarget->isThumb2()) 12322 return isLegalT2AddressImmediate(V, VT, Subtarget); 12323 12324 // ARM mode. 12325 if (V < 0) 12326 V = - V; 12327 switch (VT.getSimpleVT().SimpleTy) { 12328 default: return false; 12329 case MVT::i1: 12330 case MVT::i8: 12331 case MVT::i32: 12332 // +- imm12 12333 return V == (V & ((1LL << 12) - 1)); 12334 case MVT::i16: 12335 // +- imm8 12336 return V == (V & ((1LL << 8) - 1)); 12337 case MVT::f32: 12338 case MVT::f64: 12339 if (!Subtarget->hasVFP2()) // FIXME: NEON? 12340 return false; 12341 if ((V & 3) != 0) 12342 return false; 12343 V >>= 2; 12344 return V == (V & ((1LL << 8) - 1)); 12345 } 12346 } 12347 12348 bool ARMTargetLowering::isLegalT2ScaledAddressingMode(const AddrMode &AM, 12349 EVT VT) const { 12350 int Scale = AM.Scale; 12351 if (Scale < 0) 12352 return false; 12353 12354 switch (VT.getSimpleVT().SimpleTy) { 12355 default: return false; 12356 case MVT::i1: 12357 case MVT::i8: 12358 case MVT::i16: 12359 case MVT::i32: 12360 if (Scale == 1) 12361 return true; 12362 // r + r << imm 12363 Scale = Scale & ~1; 12364 return Scale == 2 || Scale == 4 || Scale == 8; 12365 case MVT::i64: 12366 // FIXME: What are we trying to model here? ldrd doesn't have an r + r 12367 // version in Thumb mode. 12368 // r + r 12369 if (Scale == 1) 12370 return true; 12371 // r * 2 (this can be lowered to r + r). 12372 if (!AM.HasBaseReg && Scale == 2) 12373 return true; 12374 return false; 12375 case MVT::isVoid: 12376 // Note, we allow "void" uses (basically, uses that aren't loads or 12377 // stores), because arm allows folding a scale into many arithmetic 12378 // operations. This should be made more precise and revisited later. 12379 12380 // Allow r << imm, but the imm has to be a multiple of two. 12381 if (Scale & 1) return false; 12382 return isPowerOf2_32(Scale); 12383 } 12384 } 12385 12386 bool ARMTargetLowering::isLegalT1ScaledAddressingMode(const AddrMode &AM, 12387 EVT VT) const { 12388 const int Scale = AM.Scale; 12389 12390 // Negative scales are not supported in Thumb1. 12391 if (Scale < 0) 12392 return false; 12393 12394 // Thumb1 addressing modes do not support register scaling excepting the 12395 // following cases: 12396 // 1. Scale == 1 means no scaling. 12397 // 2. Scale == 2 this can be lowered to r + r if there is no base register. 12398 return (Scale == 1) || (!AM.HasBaseReg && Scale == 2); 12399 } 12400 12401 /// isLegalAddressingMode - Return true if the addressing mode represented 12402 /// by AM is legal for this target, for a load/store of the specified type. 12403 bool ARMTargetLowering::isLegalAddressingMode(const DataLayout &DL, 12404 const AddrMode &AM, Type *Ty, 12405 unsigned AS, Instruction *I) const { 12406 EVT VT = getValueType(DL, Ty, true); 12407 if (!isLegalAddressImmediate(AM.BaseOffs, VT, Subtarget)) 12408 return false; 12409 12410 // Can never fold addr of global into load/store. 12411 if (AM.BaseGV) 12412 return false; 12413 12414 switch (AM.Scale) { 12415 case 0: // no scale reg, must be "r+i" or "r", or "i". 12416 break; 12417 default: 12418 // ARM doesn't support any R+R*scale+imm addr modes. 12419 if (AM.BaseOffs) 12420 return false; 12421 12422 if (!VT.isSimple()) 12423 return false; 12424 12425 if (Subtarget->isThumb1Only()) 12426 return isLegalT1ScaledAddressingMode(AM, VT); 12427 12428 if (Subtarget->isThumb2()) 12429 return isLegalT2ScaledAddressingMode(AM, VT); 12430 12431 int Scale = AM.Scale; 12432 switch (VT.getSimpleVT().SimpleTy) { 12433 default: return false; 12434 case MVT::i1: 12435 case MVT::i8: 12436 case MVT::i32: 12437 if (Scale < 0) Scale = -Scale; 12438 if (Scale == 1) 12439 return true; 12440 // r + r << imm 12441 return isPowerOf2_32(Scale & ~1); 12442 case MVT::i16: 12443 case MVT::i64: 12444 // r +/- r 12445 if (Scale == 1 || (AM.HasBaseReg && Scale == -1)) 12446 return true; 12447 // r * 2 (this can be lowered to r + r). 12448 if (!AM.HasBaseReg && Scale == 2) 12449 return true; 12450 return false; 12451 12452 case MVT::isVoid: 12453 // Note, we allow "void" uses (basically, uses that aren't loads or 12454 // stores), because arm allows folding a scale into many arithmetic 12455 // operations. This should be made more precise and revisited later. 12456 12457 // Allow r << imm, but the imm has to be a multiple of two. 12458 if (Scale & 1) return false; 12459 return isPowerOf2_32(Scale); 12460 } 12461 } 12462 return true; 12463 } 12464 12465 /// isLegalICmpImmediate - Return true if the specified immediate is legal 12466 /// icmp immediate, that is the target has icmp instructions which can compare 12467 /// a register against the immediate without having to materialize the 12468 /// immediate into a register. 12469 bool ARMTargetLowering::isLegalICmpImmediate(int64_t Imm) const { 12470 // Thumb2 and ARM modes can use cmn for negative immediates. 12471 if (!Subtarget->isThumb()) 12472 return ARM_AM::getSOImmVal(std::abs(Imm)) != -1; 12473 if (Subtarget->isThumb2()) 12474 return ARM_AM::getT2SOImmVal(std::abs(Imm)) != -1; 12475 // Thumb1 doesn't have cmn, and only 8-bit immediates. 12476 return Imm >= 0 && Imm <= 255; 12477 } 12478 12479 /// isLegalAddImmediate - Return true if the specified immediate is a legal add 12480 /// *or sub* immediate, that is the target has add or sub instructions which can 12481 /// add a register with the immediate without having to materialize the 12482 /// immediate into a register. 12483 bool ARMTargetLowering::isLegalAddImmediate(int64_t Imm) const { 12484 // Same encoding for add/sub, just flip the sign. 12485 int64_t AbsImm = std::abs(Imm); 12486 if (!Subtarget->isThumb()) 12487 return ARM_AM::getSOImmVal(AbsImm) != -1; 12488 if (Subtarget->isThumb2()) 12489 return ARM_AM::getT2SOImmVal(AbsImm) != -1; 12490 // Thumb1 only has 8-bit unsigned immediate. 12491 return AbsImm >= 0 && AbsImm <= 255; 12492 } 12493 12494 static bool getARMIndexedAddressParts(SDNode *Ptr, EVT VT, 12495 bool isSEXTLoad, SDValue &Base, 12496 SDValue &Offset, bool &isInc, 12497 SelectionDAG &DAG) { 12498 if (Ptr->getOpcode() != ISD::ADD && Ptr->getOpcode() != ISD::SUB) 12499 return false; 12500 12501 if (VT == MVT::i16 || ((VT == MVT::i8 || VT == MVT::i1) && isSEXTLoad)) { 12502 // AddressingMode 3 12503 Base = Ptr->getOperand(0); 12504 if (ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(Ptr->getOperand(1))) { 12505 int RHSC = (int)RHS->getZExtValue(); 12506 if (RHSC < 0 && RHSC > -256) { 12507 assert(Ptr->getOpcode() == ISD::ADD); 12508 isInc = false; 12509 Offset = DAG.getConstant(-RHSC, SDLoc(Ptr), RHS->getValueType(0)); 12510 return true; 12511 } 12512 } 12513 isInc = (Ptr->getOpcode() == ISD::ADD); 12514 Offset = Ptr->getOperand(1); 12515 return true; 12516 } else if (VT == MVT::i32 || VT == MVT::i8 || VT == MVT::i1) { 12517 // AddressingMode 2 12518 if (ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(Ptr->getOperand(1))) { 12519 int RHSC = (int)RHS->getZExtValue(); 12520 if (RHSC < 0 && RHSC > -0x1000) { 12521 assert(Ptr->getOpcode() == ISD::ADD); 12522 isInc = false; 12523 Offset = DAG.getConstant(-RHSC, SDLoc(Ptr), RHS->getValueType(0)); 12524 Base = Ptr->getOperand(0); 12525 return true; 12526 } 12527 } 12528 12529 if (Ptr->getOpcode() == ISD::ADD) { 12530 isInc = true; 12531 ARM_AM::ShiftOpc ShOpcVal= 12532 ARM_AM::getShiftOpcForNode(Ptr->getOperand(0).getOpcode()); 12533 if (ShOpcVal != ARM_AM::no_shift) { 12534 Base = Ptr->getOperand(1); 12535 Offset = Ptr->getOperand(0); 12536 } else { 12537 Base = Ptr->getOperand(0); 12538 Offset = Ptr->getOperand(1); 12539 } 12540 return true; 12541 } 12542 12543 isInc = (Ptr->getOpcode() == ISD::ADD); 12544 Base = Ptr->getOperand(0); 12545 Offset = Ptr->getOperand(1); 12546 return true; 12547 } 12548 12549 // FIXME: Use VLDM / VSTM to emulate indexed FP load / store. 12550 return false; 12551 } 12552 12553 static bool getT2IndexedAddressParts(SDNode *Ptr, EVT VT, 12554 bool isSEXTLoad, SDValue &Base, 12555 SDValue &Offset, bool &isInc, 12556 SelectionDAG &DAG) { 12557 if (Ptr->getOpcode() != ISD::ADD && Ptr->getOpcode() != ISD::SUB) 12558 return false; 12559 12560 Base = Ptr->getOperand(0); 12561 if (ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(Ptr->getOperand(1))) { 12562 int RHSC = (int)RHS->getZExtValue(); 12563 if (RHSC < 0 && RHSC > -0x100) { // 8 bits. 12564 assert(Ptr->getOpcode() == ISD::ADD); 12565 isInc = false; 12566 Offset = DAG.getConstant(-RHSC, SDLoc(Ptr), RHS->getValueType(0)); 12567 return true; 12568 } else if (RHSC > 0 && RHSC < 0x100) { // 8 bit, no zero. 12569 isInc = Ptr->getOpcode() == ISD::ADD; 12570 Offset = DAG.getConstant(RHSC, SDLoc(Ptr), RHS->getValueType(0)); 12571 return true; 12572 } 12573 } 12574 12575 return false; 12576 } 12577 12578 /// getPreIndexedAddressParts - returns true by value, base pointer and 12579 /// offset pointer and addressing mode by reference if the node's address 12580 /// can be legally represented as pre-indexed load / store address. 12581 bool 12582 ARMTargetLowering::getPreIndexedAddressParts(SDNode *N, SDValue &Base, 12583 SDValue &Offset, 12584 ISD::MemIndexedMode &AM, 12585 SelectionDAG &DAG) const { 12586 if (Subtarget->isThumb1Only()) 12587 return false; 12588 12589 EVT VT; 12590 SDValue Ptr; 12591 bool isSEXTLoad = false; 12592 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) { 12593 Ptr = LD->getBasePtr(); 12594 VT = LD->getMemoryVT(); 12595 isSEXTLoad = LD->getExtensionType() == ISD::SEXTLOAD; 12596 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) { 12597 Ptr = ST->getBasePtr(); 12598 VT = ST->getMemoryVT(); 12599 } else 12600 return false; 12601 12602 bool isInc; 12603 bool isLegal = false; 12604 if (Subtarget->isThumb2()) 12605 isLegal = getT2IndexedAddressParts(Ptr.getNode(), VT, isSEXTLoad, Base, 12606 Offset, isInc, DAG); 12607 else 12608 isLegal = getARMIndexedAddressParts(Ptr.getNode(), VT, isSEXTLoad, Base, 12609 Offset, isInc, DAG); 12610 if (!isLegal) 12611 return false; 12612 12613 AM = isInc ? ISD::PRE_INC : ISD::PRE_DEC; 12614 return true; 12615 } 12616 12617 /// getPostIndexedAddressParts - returns true by value, base pointer and 12618 /// offset pointer and addressing mode by reference if this node can be 12619 /// combined with a load / store to form a post-indexed load / store. 12620 bool ARMTargetLowering::getPostIndexedAddressParts(SDNode *N, SDNode *Op, 12621 SDValue &Base, 12622 SDValue &Offset, 12623 ISD::MemIndexedMode &AM, 12624 SelectionDAG &DAG) const { 12625 EVT VT; 12626 SDValue Ptr; 12627 bool isSEXTLoad = false, isNonExt; 12628 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) { 12629 VT = LD->getMemoryVT(); 12630 Ptr = LD->getBasePtr(); 12631 isSEXTLoad = LD->getExtensionType() == ISD::SEXTLOAD; 12632 isNonExt = LD->getExtensionType() == ISD::NON_EXTLOAD; 12633 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) { 12634 VT = ST->getMemoryVT(); 12635 Ptr = ST->getBasePtr(); 12636 isNonExt = !ST->isTruncatingStore(); 12637 } else 12638 return false; 12639 12640 if (Subtarget->isThumb1Only()) { 12641 // Thumb-1 can do a limited post-inc load or store as an updating LDM. It 12642 // must be non-extending/truncating, i32, with an offset of 4. 12643 assert(Op->getValueType(0) == MVT::i32 && "Non-i32 post-inc op?!"); 12644 if (Op->getOpcode() != ISD::ADD || !isNonExt) 12645 return false; 12646 auto *RHS = dyn_cast<ConstantSDNode>(Op->getOperand(1)); 12647 if (!RHS || RHS->getZExtValue() != 4) 12648 return false; 12649 12650 Offset = Op->getOperand(1); 12651 Base = Op->getOperand(0); 12652 AM = ISD::POST_INC; 12653 return true; 12654 } 12655 12656 bool isInc; 12657 bool isLegal = false; 12658 if (Subtarget->isThumb2()) 12659 isLegal = getT2IndexedAddressParts(Op, VT, isSEXTLoad, Base, Offset, 12660 isInc, DAG); 12661 else 12662 isLegal = getARMIndexedAddressParts(Op, VT, isSEXTLoad, Base, Offset, 12663 isInc, DAG); 12664 if (!isLegal) 12665 return false; 12666 12667 if (Ptr != Base) { 12668 // Swap base ptr and offset to catch more post-index load / store when 12669 // it's legal. In Thumb2 mode, offset must be an immediate. 12670 if (Ptr == Offset && Op->getOpcode() == ISD::ADD && 12671 !Subtarget->isThumb2()) 12672 std::swap(Base, Offset); 12673 12674 // Post-indexed load / store update the base pointer. 12675 if (Ptr != Base) 12676 return false; 12677 } 12678 12679 AM = isInc ? ISD::POST_INC : ISD::POST_DEC; 12680 return true; 12681 } 12682 12683 void ARMTargetLowering::computeKnownBitsForTargetNode(const SDValue Op, 12684 KnownBits &Known, 12685 const APInt &DemandedElts, 12686 const SelectionDAG &DAG, 12687 unsigned Depth) const { 12688 unsigned BitWidth = Known.getBitWidth(); 12689 Known.resetAll(); 12690 switch (Op.getOpcode()) { 12691 default: break; 12692 case ARMISD::ADDC: 12693 case ARMISD::ADDE: 12694 case ARMISD::SUBC: 12695 case ARMISD::SUBE: 12696 // These nodes' second result is a boolean 12697 if (Op.getResNo() == 0) 12698 break; 12699 Known.Zero |= APInt::getHighBitsSet(BitWidth, BitWidth - 1); 12700 break; 12701 case ARMISD::CMOV: { 12702 // Bits are known zero/one if known on the LHS and RHS. 12703 DAG.computeKnownBits(Op.getOperand(0), Known, Depth+1); 12704 if (Known.isUnknown()) 12705 return; 12706 12707 KnownBits KnownRHS; 12708 DAG.computeKnownBits(Op.getOperand(1), KnownRHS, Depth+1); 12709 Known.Zero &= KnownRHS.Zero; 12710 Known.One &= KnownRHS.One; 12711 return; 12712 } 12713 case ISD::INTRINSIC_W_CHAIN: { 12714 ConstantSDNode *CN = cast<ConstantSDNode>(Op->getOperand(1)); 12715 Intrinsic::ID IntID = static_cast<Intrinsic::ID>(CN->getZExtValue()); 12716 switch (IntID) { 12717 default: return; 12718 case Intrinsic::arm_ldaex: 12719 case Intrinsic::arm_ldrex: { 12720 EVT VT = cast<MemIntrinsicSDNode>(Op)->getMemoryVT(); 12721 unsigned MemBits = VT.getScalarSizeInBits(); 12722 Known.Zero |= APInt::getHighBitsSet(BitWidth, BitWidth - MemBits); 12723 return; 12724 } 12725 } 12726 } 12727 case ARMISD::BFI: { 12728 // Conservatively, we can recurse down the first operand 12729 // and just mask out all affected bits. 12730 DAG.computeKnownBits(Op.getOperand(0), Known, Depth + 1); 12731 12732 // The operand to BFI is already a mask suitable for removing the bits it 12733 // sets. 12734 ConstantSDNode *CI = cast<ConstantSDNode>(Op.getOperand(2)); 12735 const APInt &Mask = CI->getAPIntValue(); 12736 Known.Zero &= Mask; 12737 Known.One &= Mask; 12738 return; 12739 } 12740 } 12741 } 12742 12743 //===----------------------------------------------------------------------===// 12744 // ARM Inline Assembly Support 12745 //===----------------------------------------------------------------------===// 12746 12747 bool ARMTargetLowering::ExpandInlineAsm(CallInst *CI) const { 12748 // Looking for "rev" which is V6+. 12749 if (!Subtarget->hasV6Ops()) 12750 return false; 12751 12752 InlineAsm *IA = cast<InlineAsm>(CI->getCalledValue()); 12753 std::string AsmStr = IA->getAsmString(); 12754 SmallVector<StringRef, 4> AsmPieces; 12755 SplitString(AsmStr, AsmPieces, ";\n"); 12756 12757 switch (AsmPieces.size()) { 12758 default: return false; 12759 case 1: 12760 AsmStr = AsmPieces[0]; 12761 AsmPieces.clear(); 12762 SplitString(AsmStr, AsmPieces, " \t,"); 12763 12764 // rev $0, $1 12765 if (AsmPieces.size() == 3 && 12766 AsmPieces[0] == "rev" && AsmPieces[1] == "$0" && AsmPieces[2] == "$1" && 12767 IA->getConstraintString().compare(0, 4, "=l,l") == 0) { 12768 IntegerType *Ty = dyn_cast<IntegerType>(CI->getType()); 12769 if (Ty && Ty->getBitWidth() == 32) 12770 return IntrinsicLowering::LowerToByteSwap(CI); 12771 } 12772 break; 12773 } 12774 12775 return false; 12776 } 12777 12778 const char *ARMTargetLowering::LowerXConstraint(EVT ConstraintVT) const { 12779 // At this point, we have to lower this constraint to something else, so we 12780 // lower it to an "r" or "w". However, by doing this we will force the result 12781 // to be in register, while the X constraint is much more permissive. 12782 // 12783 // Although we are correct (we are free to emit anything, without 12784 // constraints), we might break use cases that would expect us to be more 12785 // efficient and emit something else. 12786 if (!Subtarget->hasVFP2()) 12787 return "r"; 12788 if (ConstraintVT.isFloatingPoint()) 12789 return "w"; 12790 if (ConstraintVT.isVector() && Subtarget->hasNEON() && 12791 (ConstraintVT.getSizeInBits() == 64 || 12792 ConstraintVT.getSizeInBits() == 128)) 12793 return "w"; 12794 12795 return "r"; 12796 } 12797 12798 /// getConstraintType - Given a constraint letter, return the type of 12799 /// constraint it is for this target. 12800 ARMTargetLowering::ConstraintType 12801 ARMTargetLowering::getConstraintType(StringRef Constraint) const { 12802 if (Constraint.size() == 1) { 12803 switch (Constraint[0]) { 12804 default: break; 12805 case 'l': return C_RegisterClass; 12806 case 'w': return C_RegisterClass; 12807 case 'h': return C_RegisterClass; 12808 case 'x': return C_RegisterClass; 12809 case 't': return C_RegisterClass; 12810 case 'j': return C_Other; // Constant for movw. 12811 // An address with a single base register. Due to the way we 12812 // currently handle addresses it is the same as an 'r' memory constraint. 12813 case 'Q': return C_Memory; 12814 } 12815 } else if (Constraint.size() == 2) { 12816 switch (Constraint[0]) { 12817 default: break; 12818 // All 'U+' constraints are addresses. 12819 case 'U': return C_Memory; 12820 } 12821 } 12822 return TargetLowering::getConstraintType(Constraint); 12823 } 12824 12825 /// Examine constraint type and operand type and determine a weight value. 12826 /// This object must already have been set up with the operand type 12827 /// and the current alternative constraint selected. 12828 TargetLowering::ConstraintWeight 12829 ARMTargetLowering::getSingleConstraintMatchWeight( 12830 AsmOperandInfo &info, const char *constraint) const { 12831 ConstraintWeight weight = CW_Invalid; 12832 Value *CallOperandVal = info.CallOperandVal; 12833 // If we don't have a value, we can't do a match, 12834 // but allow it at the lowest weight. 12835 if (!CallOperandVal) 12836 return CW_Default; 12837 Type *type = CallOperandVal->getType(); 12838 // Look at the constraint type. 12839 switch (*constraint) { 12840 default: 12841 weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint); 12842 break; 12843 case 'l': 12844 if (type->isIntegerTy()) { 12845 if (Subtarget->isThumb()) 12846 weight = CW_SpecificReg; 12847 else 12848 weight = CW_Register; 12849 } 12850 break; 12851 case 'w': 12852 if (type->isFloatingPointTy()) 12853 weight = CW_Register; 12854 break; 12855 } 12856 return weight; 12857 } 12858 12859 typedef std::pair<unsigned, const TargetRegisterClass*> RCPair; 12860 RCPair ARMTargetLowering::getRegForInlineAsmConstraint( 12861 const TargetRegisterInfo *TRI, StringRef Constraint, MVT VT) const { 12862 if (Constraint.size() == 1) { 12863 // GCC ARM Constraint Letters 12864 switch (Constraint[0]) { 12865 case 'l': // Low regs or general regs. 12866 if (Subtarget->isThumb()) 12867 return RCPair(0U, &ARM::tGPRRegClass); 12868 return RCPair(0U, &ARM::GPRRegClass); 12869 case 'h': // High regs or no regs. 12870 if (Subtarget->isThumb()) 12871 return RCPair(0U, &ARM::hGPRRegClass); 12872 break; 12873 case 'r': 12874 if (Subtarget->isThumb1Only()) 12875 return RCPair(0U, &ARM::tGPRRegClass); 12876 return RCPair(0U, &ARM::GPRRegClass); 12877 case 'w': 12878 if (VT == MVT::Other) 12879 break; 12880 if (VT == MVT::f32) 12881 return RCPair(0U, &ARM::SPRRegClass); 12882 if (VT.getSizeInBits() == 64) 12883 return RCPair(0U, &ARM::DPRRegClass); 12884 if (VT.getSizeInBits() == 128) 12885 return RCPair(0U, &ARM::QPRRegClass); 12886 break; 12887 case 'x': 12888 if (VT == MVT::Other) 12889 break; 12890 if (VT == MVT::f32) 12891 return RCPair(0U, &ARM::SPR_8RegClass); 12892 if (VT.getSizeInBits() == 64) 12893 return RCPair(0U, &ARM::DPR_8RegClass); 12894 if (VT.getSizeInBits() == 128) 12895 return RCPair(0U, &ARM::QPR_8RegClass); 12896 break; 12897 case 't': 12898 if (VT == MVT::f32) 12899 return RCPair(0U, &ARM::SPRRegClass); 12900 break; 12901 } 12902 } 12903 if (StringRef("{cc}").equals_lower(Constraint)) 12904 return std::make_pair(unsigned(ARM::CPSR), &ARM::CCRRegClass); 12905 12906 return TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT); 12907 } 12908 12909 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops 12910 /// vector. If it is invalid, don't add anything to Ops. 12911 void ARMTargetLowering::LowerAsmOperandForConstraint(SDValue Op, 12912 std::string &Constraint, 12913 std::vector<SDValue>&Ops, 12914 SelectionDAG &DAG) const { 12915 SDValue Result; 12916 12917 // Currently only support length 1 constraints. 12918 if (Constraint.length() != 1) return; 12919 12920 char ConstraintLetter = Constraint[0]; 12921 switch (ConstraintLetter) { 12922 default: break; 12923 case 'j': 12924 case 'I': case 'J': case 'K': case 'L': 12925 case 'M': case 'N': case 'O': 12926 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op); 12927 if (!C) 12928 return; 12929 12930 int64_t CVal64 = C->getSExtValue(); 12931 int CVal = (int) CVal64; 12932 // None of these constraints allow values larger than 32 bits. Check 12933 // that the value fits in an int. 12934 if (CVal != CVal64) 12935 return; 12936 12937 switch (ConstraintLetter) { 12938 case 'j': 12939 // Constant suitable for movw, must be between 0 and 12940 // 65535. 12941 if (Subtarget->hasV6T2Ops()) 12942 if (CVal >= 0 && CVal <= 65535) 12943 break; 12944 return; 12945 case 'I': 12946 if (Subtarget->isThumb1Only()) { 12947 // This must be a constant between 0 and 255, for ADD 12948 // immediates. 12949 if (CVal >= 0 && CVal <= 255) 12950 break; 12951 } else if (Subtarget->isThumb2()) { 12952 // A constant that can be used as an immediate value in a 12953 // data-processing instruction. 12954 if (ARM_AM::getT2SOImmVal(CVal) != -1) 12955 break; 12956 } else { 12957 // A constant that can be used as an immediate value in a 12958 // data-processing instruction. 12959 if (ARM_AM::getSOImmVal(CVal) != -1) 12960 break; 12961 } 12962 return; 12963 12964 case 'J': 12965 if (Subtarget->isThumb1Only()) { 12966 // This must be a constant between -255 and -1, for negated ADD 12967 // immediates. This can be used in GCC with an "n" modifier that 12968 // prints the negated value, for use with SUB instructions. It is 12969 // not useful otherwise but is implemented for compatibility. 12970 if (CVal >= -255 && CVal <= -1) 12971 break; 12972 } else { 12973 // This must be a constant between -4095 and 4095. It is not clear 12974 // what this constraint is intended for. Implemented for 12975 // compatibility with GCC. 12976 if (CVal >= -4095 && CVal <= 4095) 12977 break; 12978 } 12979 return; 12980 12981 case 'K': 12982 if (Subtarget->isThumb1Only()) { 12983 // A 32-bit value where only one byte has a nonzero value. Exclude 12984 // zero to match GCC. This constraint is used by GCC internally for 12985 // constants that can be loaded with a move/shift combination. 12986 // It is not useful otherwise but is implemented for compatibility. 12987 if (CVal != 0 && ARM_AM::isThumbImmShiftedVal(CVal)) 12988 break; 12989 } else if (Subtarget->isThumb2()) { 12990 // A constant whose bitwise inverse can be used as an immediate 12991 // value in a data-processing instruction. This can be used in GCC 12992 // with a "B" modifier that prints the inverted value, for use with 12993 // BIC and MVN instructions. It is not useful otherwise but is 12994 // implemented for compatibility. 12995 if (ARM_AM::getT2SOImmVal(~CVal) != -1) 12996 break; 12997 } else { 12998 // A constant whose bitwise inverse can be used as an immediate 12999 // value in a data-processing instruction. This can be used in GCC 13000 // with a "B" modifier that prints the inverted value, for use with 13001 // BIC and MVN instructions. It is not useful otherwise but is 13002 // implemented for compatibility. 13003 if (ARM_AM::getSOImmVal(~CVal) != -1) 13004 break; 13005 } 13006 return; 13007 13008 case 'L': 13009 if (Subtarget->isThumb1Only()) { 13010 // This must be a constant between -7 and 7, 13011 // for 3-operand ADD/SUB immediate instructions. 13012 if (CVal >= -7 && CVal < 7) 13013 break; 13014 } else if (Subtarget->isThumb2()) { 13015 // A constant whose negation can be used as an immediate value in a 13016 // data-processing instruction. This can be used in GCC with an "n" 13017 // modifier that prints the negated value, for use with SUB 13018 // instructions. It is not useful otherwise but is implemented for 13019 // compatibility. 13020 if (ARM_AM::getT2SOImmVal(-CVal) != -1) 13021 break; 13022 } else { 13023 // A constant whose negation can be used as an immediate value in a 13024 // data-processing instruction. This can be used in GCC with an "n" 13025 // modifier that prints the negated value, for use with SUB 13026 // instructions. It is not useful otherwise but is implemented for 13027 // compatibility. 13028 if (ARM_AM::getSOImmVal(-CVal) != -1) 13029 break; 13030 } 13031 return; 13032 13033 case 'M': 13034 if (Subtarget->isThumb1Only()) { 13035 // This must be a multiple of 4 between 0 and 1020, for 13036 // ADD sp + immediate. 13037 if ((CVal >= 0 && CVal <= 1020) && ((CVal & 3) == 0)) 13038 break; 13039 } else { 13040 // A power of two or a constant between 0 and 32. This is used in 13041 // GCC for the shift amount on shifted register operands, but it is 13042 // useful in general for any shift amounts. 13043 if ((CVal >= 0 && CVal <= 32) || ((CVal & (CVal - 1)) == 0)) 13044 break; 13045 } 13046 return; 13047 13048 case 'N': 13049 if (Subtarget->isThumb()) { // FIXME thumb2 13050 // This must be a constant between 0 and 31, for shift amounts. 13051 if (CVal >= 0 && CVal <= 31) 13052 break; 13053 } 13054 return; 13055 13056 case 'O': 13057 if (Subtarget->isThumb()) { // FIXME thumb2 13058 // This must be a multiple of 4 between -508 and 508, for 13059 // ADD/SUB sp = sp + immediate. 13060 if ((CVal >= -508 && CVal <= 508) && ((CVal & 3) == 0)) 13061 break; 13062 } 13063 return; 13064 } 13065 Result = DAG.getTargetConstant(CVal, SDLoc(Op), Op.getValueType()); 13066 break; 13067 } 13068 13069 if (Result.getNode()) { 13070 Ops.push_back(Result); 13071 return; 13072 } 13073 return TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG); 13074 } 13075 13076 static RTLIB::Libcall getDivRemLibcall( 13077 const SDNode *N, MVT::SimpleValueType SVT) { 13078 assert((N->getOpcode() == ISD::SDIVREM || N->getOpcode() == ISD::UDIVREM || 13079 N->getOpcode() == ISD::SREM || N->getOpcode() == ISD::UREM) && 13080 "Unhandled Opcode in getDivRemLibcall"); 13081 bool isSigned = N->getOpcode() == ISD::SDIVREM || 13082 N->getOpcode() == ISD::SREM; 13083 RTLIB::Libcall LC; 13084 switch (SVT) { 13085 default: llvm_unreachable("Unexpected request for libcall!"); 13086 case MVT::i8: LC = isSigned ? RTLIB::SDIVREM_I8 : RTLIB::UDIVREM_I8; break; 13087 case MVT::i16: LC = isSigned ? RTLIB::SDIVREM_I16 : RTLIB::UDIVREM_I16; break; 13088 case MVT::i32: LC = isSigned ? RTLIB::SDIVREM_I32 : RTLIB::UDIVREM_I32; break; 13089 case MVT::i64: LC = isSigned ? RTLIB::SDIVREM_I64 : RTLIB::UDIVREM_I64; break; 13090 } 13091 return LC; 13092 } 13093 13094 static TargetLowering::ArgListTy getDivRemArgList( 13095 const SDNode *N, LLVMContext *Context, const ARMSubtarget *Subtarget) { 13096 assert((N->getOpcode() == ISD::SDIVREM || N->getOpcode() == ISD::UDIVREM || 13097 N->getOpcode() == ISD::SREM || N->getOpcode() == ISD::UREM) && 13098 "Unhandled Opcode in getDivRemArgList"); 13099 bool isSigned = N->getOpcode() == ISD::SDIVREM || 13100 N->getOpcode() == ISD::SREM; 13101 TargetLowering::ArgListTy Args; 13102 TargetLowering::ArgListEntry Entry; 13103 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) { 13104 EVT ArgVT = N->getOperand(i).getValueType(); 13105 Type *ArgTy = ArgVT.getTypeForEVT(*Context); 13106 Entry.Node = N->getOperand(i); 13107 Entry.Ty = ArgTy; 13108 Entry.IsSExt = isSigned; 13109 Entry.IsZExt = !isSigned; 13110 Args.push_back(Entry); 13111 } 13112 if (Subtarget->isTargetWindows() && Args.size() >= 2) 13113 std::swap(Args[0], Args[1]); 13114 return Args; 13115 } 13116 13117 SDValue ARMTargetLowering::LowerDivRem(SDValue Op, SelectionDAG &DAG) const { 13118 assert((Subtarget->isTargetAEABI() || Subtarget->isTargetAndroid() || 13119 Subtarget->isTargetGNUAEABI() || Subtarget->isTargetMuslAEABI() || 13120 Subtarget->isTargetWindows()) && 13121 "Register-based DivRem lowering only"); 13122 unsigned Opcode = Op->getOpcode(); 13123 assert((Opcode == ISD::SDIVREM || Opcode == ISD::UDIVREM) && 13124 "Invalid opcode for Div/Rem lowering"); 13125 bool isSigned = (Opcode == ISD::SDIVREM); 13126 EVT VT = Op->getValueType(0); 13127 Type *Ty = VT.getTypeForEVT(*DAG.getContext()); 13128 SDLoc dl(Op); 13129 13130 // If the target has hardware divide, use divide + multiply + subtract: 13131 // div = a / b 13132 // rem = a - b * div 13133 // return {div, rem} 13134 // This should be lowered into UDIV/SDIV + MLS later on. 13135 bool hasDivide = Subtarget->isThumb() ? Subtarget->hasDivideInThumbMode() 13136 : Subtarget->hasDivideInARMMode(); 13137 if (hasDivide && Op->getValueType(0).isSimple() && 13138 Op->getSimpleValueType(0) == MVT::i32) { 13139 unsigned DivOpcode = isSigned ? ISD::SDIV : ISD::UDIV; 13140 const SDValue Dividend = Op->getOperand(0); 13141 const SDValue Divisor = Op->getOperand(1); 13142 SDValue Div = DAG.getNode(DivOpcode, dl, VT, Dividend, Divisor); 13143 SDValue Mul = DAG.getNode(ISD::MUL, dl, VT, Div, Divisor); 13144 SDValue Rem = DAG.getNode(ISD::SUB, dl, VT, Dividend, Mul); 13145 13146 SDValue Values[2] = {Div, Rem}; 13147 return DAG.getNode(ISD::MERGE_VALUES, dl, DAG.getVTList(VT, VT), Values); 13148 } 13149 13150 RTLIB::Libcall LC = getDivRemLibcall(Op.getNode(), 13151 VT.getSimpleVT().SimpleTy); 13152 SDValue InChain = DAG.getEntryNode(); 13153 13154 TargetLowering::ArgListTy Args = getDivRemArgList(Op.getNode(), 13155 DAG.getContext(), 13156 Subtarget); 13157 13158 SDValue Callee = DAG.getExternalSymbol(getLibcallName(LC), 13159 getPointerTy(DAG.getDataLayout())); 13160 13161 Type *RetTy = StructType::get(Ty, Ty); 13162 13163 if (Subtarget->isTargetWindows()) 13164 InChain = WinDBZCheckDenominator(DAG, Op.getNode(), InChain); 13165 13166 TargetLowering::CallLoweringInfo CLI(DAG); 13167 CLI.setDebugLoc(dl).setChain(InChain) 13168 .setCallee(getLibcallCallingConv(LC), RetTy, Callee, std::move(Args)) 13169 .setInRegister().setSExtResult(isSigned).setZExtResult(!isSigned); 13170 13171 std::pair<SDValue, SDValue> CallInfo = LowerCallTo(CLI); 13172 return CallInfo.first; 13173 } 13174 13175 // Lowers REM using divmod helpers 13176 // see RTABI section 4.2/4.3 13177 SDValue ARMTargetLowering::LowerREM(SDNode *N, SelectionDAG &DAG) const { 13178 // Build return types (div and rem) 13179 std::vector<Type*> RetTyParams; 13180 Type *RetTyElement; 13181 13182 switch (N->getValueType(0).getSimpleVT().SimpleTy) { 13183 default: llvm_unreachable("Unexpected request for libcall!"); 13184 case MVT::i8: RetTyElement = Type::getInt8Ty(*DAG.getContext()); break; 13185 case MVT::i16: RetTyElement = Type::getInt16Ty(*DAG.getContext()); break; 13186 case MVT::i32: RetTyElement = Type::getInt32Ty(*DAG.getContext()); break; 13187 case MVT::i64: RetTyElement = Type::getInt64Ty(*DAG.getContext()); break; 13188 } 13189 13190 RetTyParams.push_back(RetTyElement); 13191 RetTyParams.push_back(RetTyElement); 13192 ArrayRef<Type*> ret = ArrayRef<Type*>(RetTyParams); 13193 Type *RetTy = StructType::get(*DAG.getContext(), ret); 13194 13195 RTLIB::Libcall LC = getDivRemLibcall(N, N->getValueType(0).getSimpleVT(). 13196 SimpleTy); 13197 SDValue InChain = DAG.getEntryNode(); 13198 TargetLowering::ArgListTy Args = getDivRemArgList(N, DAG.getContext(), 13199 Subtarget); 13200 bool isSigned = N->getOpcode() == ISD::SREM; 13201 SDValue Callee = DAG.getExternalSymbol(getLibcallName(LC), 13202 getPointerTy(DAG.getDataLayout())); 13203 13204 if (Subtarget->isTargetWindows()) 13205 InChain = WinDBZCheckDenominator(DAG, N, InChain); 13206 13207 // Lower call 13208 CallLoweringInfo CLI(DAG); 13209 CLI.setChain(InChain) 13210 .setCallee(CallingConv::ARM_AAPCS, RetTy, Callee, std::move(Args)) 13211 .setSExtResult(isSigned).setZExtResult(!isSigned).setDebugLoc(SDLoc(N)); 13212 std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI); 13213 13214 // Return second (rem) result operand (first contains div) 13215 SDNode *ResNode = CallResult.first.getNode(); 13216 assert(ResNode->getNumOperands() == 2 && "divmod should return two operands"); 13217 return ResNode->getOperand(1); 13218 } 13219 13220 SDValue 13221 ARMTargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op, SelectionDAG &DAG) const { 13222 assert(Subtarget->isTargetWindows() && "unsupported target platform"); 13223 SDLoc DL(Op); 13224 13225 // Get the inputs. 13226 SDValue Chain = Op.getOperand(0); 13227 SDValue Size = Op.getOperand(1); 13228 13229 SDValue Words = DAG.getNode(ISD::SRL, DL, MVT::i32, Size, 13230 DAG.getConstant(2, DL, MVT::i32)); 13231 13232 SDValue Flag; 13233 Chain = DAG.getCopyToReg(Chain, DL, ARM::R4, Words, Flag); 13234 Flag = Chain.getValue(1); 13235 13236 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue); 13237 Chain = DAG.getNode(ARMISD::WIN__CHKSTK, DL, NodeTys, Chain, Flag); 13238 13239 SDValue NewSP = DAG.getCopyFromReg(Chain, DL, ARM::SP, MVT::i32); 13240 Chain = NewSP.getValue(1); 13241 13242 SDValue Ops[2] = { NewSP, Chain }; 13243 return DAG.getMergeValues(Ops, DL); 13244 } 13245 13246 SDValue ARMTargetLowering::LowerFP_EXTEND(SDValue Op, SelectionDAG &DAG) const { 13247 assert(Op.getValueType() == MVT::f64 && Subtarget->isFPOnlySP() && 13248 "Unexpected type for custom-lowering FP_EXTEND"); 13249 13250 RTLIB::Libcall LC; 13251 LC = RTLIB::getFPEXT(Op.getOperand(0).getValueType(), Op.getValueType()); 13252 13253 SDValue SrcVal = Op.getOperand(0); 13254 return makeLibCall(DAG, LC, Op.getValueType(), SrcVal, /*isSigned*/ false, 13255 SDLoc(Op)).first; 13256 } 13257 13258 SDValue ARMTargetLowering::LowerFP_ROUND(SDValue Op, SelectionDAG &DAG) const { 13259 assert(Op.getOperand(0).getValueType() == MVT::f64 && 13260 Subtarget->isFPOnlySP() && 13261 "Unexpected type for custom-lowering FP_ROUND"); 13262 13263 RTLIB::Libcall LC; 13264 LC = RTLIB::getFPROUND(Op.getOperand(0).getValueType(), Op.getValueType()); 13265 13266 SDValue SrcVal = Op.getOperand(0); 13267 return makeLibCall(DAG, LC, Op.getValueType(), SrcVal, /*isSigned*/ false, 13268 SDLoc(Op)).first; 13269 } 13270 13271 bool 13272 ARMTargetLowering::isOffsetFoldingLegal(const GlobalAddressSDNode *GA) const { 13273 // The ARM target isn't yet aware of offsets. 13274 return false; 13275 } 13276 13277 bool ARM::isBitFieldInvertedMask(unsigned v) { 13278 if (v == 0xffffffff) 13279 return false; 13280 13281 // there can be 1's on either or both "outsides", all the "inside" 13282 // bits must be 0's 13283 return isShiftedMask_32(~v); 13284 } 13285 13286 /// isFPImmLegal - Returns true if the target can instruction select the 13287 /// specified FP immediate natively. If false, the legalizer will 13288 /// materialize the FP immediate as a load from a constant pool. 13289 bool ARMTargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT) const { 13290 if (!Subtarget->hasVFP3()) 13291 return false; 13292 if (VT == MVT::f32) 13293 return ARM_AM::getFP32Imm(Imm) != -1; 13294 if (VT == MVT::f64 && !Subtarget->isFPOnlySP()) 13295 return ARM_AM::getFP64Imm(Imm) != -1; 13296 return false; 13297 } 13298 13299 /// getTgtMemIntrinsic - Represent NEON load and store intrinsics as 13300 /// MemIntrinsicNodes. The associated MachineMemOperands record the alignment 13301 /// specified in the intrinsic calls. 13302 bool ARMTargetLowering::getTgtMemIntrinsic(IntrinsicInfo &Info, 13303 const CallInst &I, 13304 unsigned Intrinsic) const { 13305 switch (Intrinsic) { 13306 case Intrinsic::arm_neon_vld1: 13307 case Intrinsic::arm_neon_vld2: 13308 case Intrinsic::arm_neon_vld3: 13309 case Intrinsic::arm_neon_vld4: 13310 case Intrinsic::arm_neon_vld2lane: 13311 case Intrinsic::arm_neon_vld3lane: 13312 case Intrinsic::arm_neon_vld4lane: { 13313 Info.opc = ISD::INTRINSIC_W_CHAIN; 13314 // Conservatively set memVT to the entire set of vectors loaded. 13315 auto &DL = I.getCalledFunction()->getParent()->getDataLayout(); 13316 uint64_t NumElts = DL.getTypeSizeInBits(I.getType()) / 64; 13317 Info.memVT = EVT::getVectorVT(I.getType()->getContext(), MVT::i64, NumElts); 13318 Info.ptrVal = I.getArgOperand(0); 13319 Info.offset = 0; 13320 Value *AlignArg = I.getArgOperand(I.getNumArgOperands() - 1); 13321 Info.align = cast<ConstantInt>(AlignArg)->getZExtValue(); 13322 Info.vol = false; // volatile loads with NEON intrinsics not supported 13323 Info.readMem = true; 13324 Info.writeMem = false; 13325 return true; 13326 } 13327 case Intrinsic::arm_neon_vst1: 13328 case Intrinsic::arm_neon_vst2: 13329 case Intrinsic::arm_neon_vst3: 13330 case Intrinsic::arm_neon_vst4: 13331 case Intrinsic::arm_neon_vst2lane: 13332 case Intrinsic::arm_neon_vst3lane: 13333 case Intrinsic::arm_neon_vst4lane: { 13334 Info.opc = ISD::INTRINSIC_VOID; 13335 // Conservatively set memVT to the entire set of vectors stored. 13336 auto &DL = I.getCalledFunction()->getParent()->getDataLayout(); 13337 unsigned NumElts = 0; 13338 for (unsigned ArgI = 1, ArgE = I.getNumArgOperands(); ArgI < ArgE; ++ArgI) { 13339 Type *ArgTy = I.getArgOperand(ArgI)->getType(); 13340 if (!ArgTy->isVectorTy()) 13341 break; 13342 NumElts += DL.getTypeSizeInBits(ArgTy) / 64; 13343 } 13344 Info.memVT = EVT::getVectorVT(I.getType()->getContext(), MVT::i64, NumElts); 13345 Info.ptrVal = I.getArgOperand(0); 13346 Info.offset = 0; 13347 Value *AlignArg = I.getArgOperand(I.getNumArgOperands() - 1); 13348 Info.align = cast<ConstantInt>(AlignArg)->getZExtValue(); 13349 Info.vol = false; // volatile stores with NEON intrinsics not supported 13350 Info.readMem = false; 13351 Info.writeMem = true; 13352 return true; 13353 } 13354 case Intrinsic::arm_ldaex: 13355 case Intrinsic::arm_ldrex: { 13356 auto &DL = I.getCalledFunction()->getParent()->getDataLayout(); 13357 PointerType *PtrTy = cast<PointerType>(I.getArgOperand(0)->getType()); 13358 Info.opc = ISD::INTRINSIC_W_CHAIN; 13359 Info.memVT = MVT::getVT(PtrTy->getElementType()); 13360 Info.ptrVal = I.getArgOperand(0); 13361 Info.offset = 0; 13362 Info.align = DL.getABITypeAlignment(PtrTy->getElementType()); 13363 Info.vol = true; 13364 Info.readMem = true; 13365 Info.writeMem = false; 13366 return true; 13367 } 13368 case Intrinsic::arm_stlex: 13369 case Intrinsic::arm_strex: { 13370 auto &DL = I.getCalledFunction()->getParent()->getDataLayout(); 13371 PointerType *PtrTy = cast<PointerType>(I.getArgOperand(1)->getType()); 13372 Info.opc = ISD::INTRINSIC_W_CHAIN; 13373 Info.memVT = MVT::getVT(PtrTy->getElementType()); 13374 Info.ptrVal = I.getArgOperand(1); 13375 Info.offset = 0; 13376 Info.align = DL.getABITypeAlignment(PtrTy->getElementType()); 13377 Info.vol = true; 13378 Info.readMem = false; 13379 Info.writeMem = true; 13380 return true; 13381 } 13382 case Intrinsic::arm_stlexd: 13383 case Intrinsic::arm_strexd: 13384 Info.opc = ISD::INTRINSIC_W_CHAIN; 13385 Info.memVT = MVT::i64; 13386 Info.ptrVal = I.getArgOperand(2); 13387 Info.offset = 0; 13388 Info.align = 8; 13389 Info.vol = true; 13390 Info.readMem = false; 13391 Info.writeMem = true; 13392 return true; 13393 13394 case Intrinsic::arm_ldaexd: 13395 case Intrinsic::arm_ldrexd: 13396 Info.opc = ISD::INTRINSIC_W_CHAIN; 13397 Info.memVT = MVT::i64; 13398 Info.ptrVal = I.getArgOperand(0); 13399 Info.offset = 0; 13400 Info.align = 8; 13401 Info.vol = true; 13402 Info.readMem = true; 13403 Info.writeMem = false; 13404 return true; 13405 13406 default: 13407 break; 13408 } 13409 13410 return false; 13411 } 13412 13413 /// \brief Returns true if it is beneficial to convert a load of a constant 13414 /// to just the constant itself. 13415 bool ARMTargetLowering::shouldConvertConstantLoadToIntImm(const APInt &Imm, 13416 Type *Ty) const { 13417 assert(Ty->isIntegerTy()); 13418 13419 unsigned Bits = Ty->getPrimitiveSizeInBits(); 13420 if (Bits == 0 || Bits > 32) 13421 return false; 13422 return true; 13423 } 13424 13425 bool ARMTargetLowering::isExtractSubvectorCheap(EVT ResVT, EVT SrcVT, 13426 unsigned Index) const { 13427 if (!isOperationLegalOrCustom(ISD::EXTRACT_SUBVECTOR, ResVT)) 13428 return false; 13429 13430 return (Index == 0 || Index == ResVT.getVectorNumElements()); 13431 } 13432 13433 Instruction* ARMTargetLowering::makeDMB(IRBuilder<> &Builder, 13434 ARM_MB::MemBOpt Domain) const { 13435 Module *M = Builder.GetInsertBlock()->getParent()->getParent(); 13436 13437 // First, if the target has no DMB, see what fallback we can use. 13438 if (!Subtarget->hasDataBarrier()) { 13439 // Some ARMv6 cpus can support data barriers with an mcr instruction. 13440 // Thumb1 and pre-v6 ARM mode use a libcall instead and should never get 13441 // here. 13442 if (Subtarget->hasV6Ops() && !Subtarget->isThumb()) { 13443 Function *MCR = Intrinsic::getDeclaration(M, Intrinsic::arm_mcr); 13444 Value* args[6] = {Builder.getInt32(15), Builder.getInt32(0), 13445 Builder.getInt32(0), Builder.getInt32(7), 13446 Builder.getInt32(10), Builder.getInt32(5)}; 13447 return Builder.CreateCall(MCR, args); 13448 } else { 13449 // Instead of using barriers, atomic accesses on these subtargets use 13450 // libcalls. 13451 llvm_unreachable("makeDMB on a target so old that it has no barriers"); 13452 } 13453 } else { 13454 Function *DMB = Intrinsic::getDeclaration(M, Intrinsic::arm_dmb); 13455 // Only a full system barrier exists in the M-class architectures. 13456 Domain = Subtarget->isMClass() ? ARM_MB::SY : Domain; 13457 Constant *CDomain = Builder.getInt32(Domain); 13458 return Builder.CreateCall(DMB, CDomain); 13459 } 13460 } 13461 13462 // Based on http://www.cl.cam.ac.uk/~pes20/cpp/cpp0xmappings.html 13463 Instruction *ARMTargetLowering::emitLeadingFence(IRBuilder<> &Builder, 13464 Instruction *Inst, 13465 AtomicOrdering Ord) const { 13466 switch (Ord) { 13467 case AtomicOrdering::NotAtomic: 13468 case AtomicOrdering::Unordered: 13469 llvm_unreachable("Invalid fence: unordered/non-atomic"); 13470 case AtomicOrdering::Monotonic: 13471 case AtomicOrdering::Acquire: 13472 return nullptr; // Nothing to do 13473 case AtomicOrdering::SequentiallyConsistent: 13474 if (!Inst->hasAtomicStore()) 13475 return nullptr; // Nothing to do 13476 /*FALLTHROUGH*/ 13477 case AtomicOrdering::Release: 13478 case AtomicOrdering::AcquireRelease: 13479 if (Subtarget->preferISHSTBarriers()) 13480 return makeDMB(Builder, ARM_MB::ISHST); 13481 // FIXME: add a comment with a link to documentation justifying this. 13482 else 13483 return makeDMB(Builder, ARM_MB::ISH); 13484 } 13485 llvm_unreachable("Unknown fence ordering in emitLeadingFence"); 13486 } 13487 13488 Instruction *ARMTargetLowering::emitTrailingFence(IRBuilder<> &Builder, 13489 Instruction *Inst, 13490 AtomicOrdering Ord) const { 13491 switch (Ord) { 13492 case AtomicOrdering::NotAtomic: 13493 case AtomicOrdering::Unordered: 13494 llvm_unreachable("Invalid fence: unordered/not-atomic"); 13495 case AtomicOrdering::Monotonic: 13496 case AtomicOrdering::Release: 13497 return nullptr; // Nothing to do 13498 case AtomicOrdering::Acquire: 13499 case AtomicOrdering::AcquireRelease: 13500 case AtomicOrdering::SequentiallyConsistent: 13501 return makeDMB(Builder, ARM_MB::ISH); 13502 } 13503 llvm_unreachable("Unknown fence ordering in emitTrailingFence"); 13504 } 13505 13506 // Loads and stores less than 64-bits are already atomic; ones above that 13507 // are doomed anyway, so defer to the default libcall and blame the OS when 13508 // things go wrong. Cortex M doesn't have ldrexd/strexd though, so don't emit 13509 // anything for those. 13510 bool ARMTargetLowering::shouldExpandAtomicStoreInIR(StoreInst *SI) const { 13511 unsigned Size = SI->getValueOperand()->getType()->getPrimitiveSizeInBits(); 13512 return (Size == 64) && !Subtarget->isMClass(); 13513 } 13514 13515 // Loads and stores less than 64-bits are already atomic; ones above that 13516 // are doomed anyway, so defer to the default libcall and blame the OS when 13517 // things go wrong. Cortex M doesn't have ldrexd/strexd though, so don't emit 13518 // anything for those. 13519 // FIXME: ldrd and strd are atomic if the CPU has LPAE (e.g. A15 has that 13520 // guarantee, see DDI0406C ARM architecture reference manual, 13521 // sections A8.8.72-74 LDRD) 13522 TargetLowering::AtomicExpansionKind 13523 ARMTargetLowering::shouldExpandAtomicLoadInIR(LoadInst *LI) const { 13524 unsigned Size = LI->getType()->getPrimitiveSizeInBits(); 13525 return ((Size == 64) && !Subtarget->isMClass()) ? AtomicExpansionKind::LLOnly 13526 : AtomicExpansionKind::None; 13527 } 13528 13529 // For the real atomic operations, we have ldrex/strex up to 32 bits, 13530 // and up to 64 bits on the non-M profiles 13531 TargetLowering::AtomicExpansionKind 13532 ARMTargetLowering::shouldExpandAtomicRMWInIR(AtomicRMWInst *AI) const { 13533 unsigned Size = AI->getType()->getPrimitiveSizeInBits(); 13534 bool hasAtomicRMW = !Subtarget->isThumb() || Subtarget->hasV8MBaselineOps(); 13535 return (Size <= (Subtarget->isMClass() ? 32U : 64U) && hasAtomicRMW) 13536 ? AtomicExpansionKind::LLSC 13537 : AtomicExpansionKind::None; 13538 } 13539 13540 bool ARMTargetLowering::shouldExpandAtomicCmpXchgInIR( 13541 AtomicCmpXchgInst *AI) const { 13542 // At -O0, fast-regalloc cannot cope with the live vregs necessary to 13543 // implement cmpxchg without spilling. If the address being exchanged is also 13544 // on the stack and close enough to the spill slot, this can lead to a 13545 // situation where the monitor always gets cleared and the atomic operation 13546 // can never succeed. So at -O0 we need a late-expanded pseudo-inst instead. 13547 bool hasAtomicCmpXchg = 13548 !Subtarget->isThumb() || Subtarget->hasV8MBaselineOps(); 13549 return getTargetMachine().getOptLevel() != 0 && hasAtomicCmpXchg; 13550 } 13551 13552 bool ARMTargetLowering::shouldInsertFencesForAtomic( 13553 const Instruction *I) const { 13554 return InsertFencesForAtomic; 13555 } 13556 13557 // This has so far only been implemented for MachO. 13558 bool ARMTargetLowering::useLoadStackGuardNode() const { 13559 return Subtarget->isTargetMachO(); 13560 } 13561 13562 bool ARMTargetLowering::canCombineStoreAndExtract(Type *VectorTy, Value *Idx, 13563 unsigned &Cost) const { 13564 // If we do not have NEON, vector types are not natively supported. 13565 if (!Subtarget->hasNEON()) 13566 return false; 13567 13568 // Floating point values and vector values map to the same register file. 13569 // Therefore, although we could do a store extract of a vector type, this is 13570 // better to leave at float as we have more freedom in the addressing mode for 13571 // those. 13572 if (VectorTy->isFPOrFPVectorTy()) 13573 return false; 13574 13575 // If the index is unknown at compile time, this is very expensive to lower 13576 // and it is not possible to combine the store with the extract. 13577 if (!isa<ConstantInt>(Idx)) 13578 return false; 13579 13580 assert(VectorTy->isVectorTy() && "VectorTy is not a vector type"); 13581 unsigned BitWidth = cast<VectorType>(VectorTy)->getBitWidth(); 13582 // We can do a store + vector extract on any vector that fits perfectly in a D 13583 // or Q register. 13584 if (BitWidth == 64 || BitWidth == 128) { 13585 Cost = 0; 13586 return true; 13587 } 13588 return false; 13589 } 13590 13591 bool ARMTargetLowering::isCheapToSpeculateCttz() const { 13592 return Subtarget->hasV6T2Ops(); 13593 } 13594 13595 bool ARMTargetLowering::isCheapToSpeculateCtlz() const { 13596 return Subtarget->hasV6T2Ops(); 13597 } 13598 13599 Value *ARMTargetLowering::emitLoadLinked(IRBuilder<> &Builder, Value *Addr, 13600 AtomicOrdering Ord) const { 13601 Module *M = Builder.GetInsertBlock()->getParent()->getParent(); 13602 Type *ValTy = cast<PointerType>(Addr->getType())->getElementType(); 13603 bool IsAcquire = isAcquireOrStronger(Ord); 13604 13605 // Since i64 isn't legal and intrinsics don't get type-lowered, the ldrexd 13606 // intrinsic must return {i32, i32} and we have to recombine them into a 13607 // single i64 here. 13608 if (ValTy->getPrimitiveSizeInBits() == 64) { 13609 Intrinsic::ID Int = 13610 IsAcquire ? Intrinsic::arm_ldaexd : Intrinsic::arm_ldrexd; 13611 Function *Ldrex = Intrinsic::getDeclaration(M, Int); 13612 13613 Addr = Builder.CreateBitCast(Addr, Type::getInt8PtrTy(M->getContext())); 13614 Value *LoHi = Builder.CreateCall(Ldrex, Addr, "lohi"); 13615 13616 Value *Lo = Builder.CreateExtractValue(LoHi, 0, "lo"); 13617 Value *Hi = Builder.CreateExtractValue(LoHi, 1, "hi"); 13618 if (!Subtarget->isLittle()) 13619 std::swap (Lo, Hi); 13620 Lo = Builder.CreateZExt(Lo, ValTy, "lo64"); 13621 Hi = Builder.CreateZExt(Hi, ValTy, "hi64"); 13622 return Builder.CreateOr( 13623 Lo, Builder.CreateShl(Hi, ConstantInt::get(ValTy, 32)), "val64"); 13624 } 13625 13626 Type *Tys[] = { Addr->getType() }; 13627 Intrinsic::ID Int = IsAcquire ? Intrinsic::arm_ldaex : Intrinsic::arm_ldrex; 13628 Function *Ldrex = Intrinsic::getDeclaration(M, Int, Tys); 13629 13630 return Builder.CreateTruncOrBitCast( 13631 Builder.CreateCall(Ldrex, Addr), 13632 cast<PointerType>(Addr->getType())->getElementType()); 13633 } 13634 13635 void ARMTargetLowering::emitAtomicCmpXchgNoStoreLLBalance( 13636 IRBuilder<> &Builder) const { 13637 if (!Subtarget->hasV7Ops()) 13638 return; 13639 Module *M = Builder.GetInsertBlock()->getParent()->getParent(); 13640 Builder.CreateCall(Intrinsic::getDeclaration(M, Intrinsic::arm_clrex)); 13641 } 13642 13643 Value *ARMTargetLowering::emitStoreConditional(IRBuilder<> &Builder, Value *Val, 13644 Value *Addr, 13645 AtomicOrdering Ord) const { 13646 Module *M = Builder.GetInsertBlock()->getParent()->getParent(); 13647 bool IsRelease = isReleaseOrStronger(Ord); 13648 13649 // Since the intrinsics must have legal type, the i64 intrinsics take two 13650 // parameters: "i32, i32". We must marshal Val into the appropriate form 13651 // before the call. 13652 if (Val->getType()->getPrimitiveSizeInBits() == 64) { 13653 Intrinsic::ID Int = 13654 IsRelease ? Intrinsic::arm_stlexd : Intrinsic::arm_strexd; 13655 Function *Strex = Intrinsic::getDeclaration(M, Int); 13656 Type *Int32Ty = Type::getInt32Ty(M->getContext()); 13657 13658 Value *Lo = Builder.CreateTrunc(Val, Int32Ty, "lo"); 13659 Value *Hi = Builder.CreateTrunc(Builder.CreateLShr(Val, 32), Int32Ty, "hi"); 13660 if (!Subtarget->isLittle()) 13661 std::swap (Lo, Hi); 13662 Addr = Builder.CreateBitCast(Addr, Type::getInt8PtrTy(M->getContext())); 13663 return Builder.CreateCall(Strex, {Lo, Hi, Addr}); 13664 } 13665 13666 Intrinsic::ID Int = IsRelease ? Intrinsic::arm_stlex : Intrinsic::arm_strex; 13667 Type *Tys[] = { Addr->getType() }; 13668 Function *Strex = Intrinsic::getDeclaration(M, Int, Tys); 13669 13670 return Builder.CreateCall( 13671 Strex, {Builder.CreateZExtOrBitCast( 13672 Val, Strex->getFunctionType()->getParamType(0)), 13673 Addr}); 13674 } 13675 13676 /// A helper function for determining the number of interleaved accesses we 13677 /// will generate when lowering accesses of the given type. 13678 unsigned 13679 ARMTargetLowering::getNumInterleavedAccesses(VectorType *VecTy, 13680 const DataLayout &DL) const { 13681 return (DL.getTypeSizeInBits(VecTy) + 127) / 128; 13682 } 13683 13684 bool ARMTargetLowering::isLegalInterleavedAccessType( 13685 VectorType *VecTy, const DataLayout &DL) const { 13686 13687 unsigned VecSize = DL.getTypeSizeInBits(VecTy); 13688 unsigned ElSize = DL.getTypeSizeInBits(VecTy->getElementType()); 13689 13690 // Ensure the vector doesn't have f16 elements. Even though we could do an 13691 // i16 vldN, we can't hold the f16 vectors and will end up converting via 13692 // f32. 13693 if (VecTy->getElementType()->isHalfTy()) 13694 return false; 13695 13696 // Ensure the number of vector elements is greater than 1. 13697 if (VecTy->getNumElements() < 2) 13698 return false; 13699 13700 // Ensure the element type is legal. 13701 if (ElSize != 8 && ElSize != 16 && ElSize != 32) 13702 return false; 13703 13704 // Ensure the total vector size is 64 or a multiple of 128. Types larger than 13705 // 128 will be split into multiple interleaved accesses. 13706 return VecSize == 64 || VecSize % 128 == 0; 13707 } 13708 13709 /// \brief Lower an interleaved load into a vldN intrinsic. 13710 /// 13711 /// E.g. Lower an interleaved load (Factor = 2): 13712 /// %wide.vec = load <8 x i32>, <8 x i32>* %ptr, align 4 13713 /// %v0 = shuffle %wide.vec, undef, <0, 2, 4, 6> ; Extract even elements 13714 /// %v1 = shuffle %wide.vec, undef, <1, 3, 5, 7> ; Extract odd elements 13715 /// 13716 /// Into: 13717 /// %vld2 = { <4 x i32>, <4 x i32> } call llvm.arm.neon.vld2(%ptr, 4) 13718 /// %vec0 = extractelement { <4 x i32>, <4 x i32> } %vld2, i32 0 13719 /// %vec1 = extractelement { <4 x i32>, <4 x i32> } %vld2, i32 1 13720 bool ARMTargetLowering::lowerInterleavedLoad( 13721 LoadInst *LI, ArrayRef<ShuffleVectorInst *> Shuffles, 13722 ArrayRef<unsigned> Indices, unsigned Factor) const { 13723 assert(Factor >= 2 && Factor <= getMaxSupportedInterleaveFactor() && 13724 "Invalid interleave factor"); 13725 assert(!Shuffles.empty() && "Empty shufflevector input"); 13726 assert(Shuffles.size() == Indices.size() && 13727 "Unmatched number of shufflevectors and indices"); 13728 13729 VectorType *VecTy = Shuffles[0]->getType(); 13730 Type *EltTy = VecTy->getVectorElementType(); 13731 13732 const DataLayout &DL = LI->getModule()->getDataLayout(); 13733 13734 // Skip if we do not have NEON and skip illegal vector types. We can 13735 // "legalize" wide vector types into multiple interleaved accesses as long as 13736 // the vector types are divisible by 128. 13737 if (!Subtarget->hasNEON() || !isLegalInterleavedAccessType(VecTy, DL)) 13738 return false; 13739 13740 unsigned NumLoads = getNumInterleavedAccesses(VecTy, DL); 13741 13742 // A pointer vector can not be the return type of the ldN intrinsics. Need to 13743 // load integer vectors first and then convert to pointer vectors. 13744 if (EltTy->isPointerTy()) 13745 VecTy = 13746 VectorType::get(DL.getIntPtrType(EltTy), VecTy->getVectorNumElements()); 13747 13748 IRBuilder<> Builder(LI); 13749 13750 // The base address of the load. 13751 Value *BaseAddr = LI->getPointerOperand(); 13752 13753 if (NumLoads > 1) { 13754 // If we're going to generate more than one load, reset the sub-vector type 13755 // to something legal. 13756 VecTy = VectorType::get(VecTy->getVectorElementType(), 13757 VecTy->getVectorNumElements() / NumLoads); 13758 13759 // We will compute the pointer operand of each load from the original base 13760 // address using GEPs. Cast the base address to a pointer to the scalar 13761 // element type. 13762 BaseAddr = Builder.CreateBitCast( 13763 BaseAddr, VecTy->getVectorElementType()->getPointerTo( 13764 LI->getPointerAddressSpace())); 13765 } 13766 13767 assert(isTypeLegal(EVT::getEVT(VecTy)) && "Illegal vldN vector type!"); 13768 13769 Type *Int8Ptr = Builder.getInt8PtrTy(LI->getPointerAddressSpace()); 13770 Type *Tys[] = {VecTy, Int8Ptr}; 13771 static const Intrinsic::ID LoadInts[3] = {Intrinsic::arm_neon_vld2, 13772 Intrinsic::arm_neon_vld3, 13773 Intrinsic::arm_neon_vld4}; 13774 Function *VldnFunc = 13775 Intrinsic::getDeclaration(LI->getModule(), LoadInts[Factor - 2], Tys); 13776 13777 // Holds sub-vectors extracted from the load intrinsic return values. The 13778 // sub-vectors are associated with the shufflevector instructions they will 13779 // replace. 13780 DenseMap<ShuffleVectorInst *, SmallVector<Value *, 4>> SubVecs; 13781 13782 for (unsigned LoadCount = 0; LoadCount < NumLoads; ++LoadCount) { 13783 13784 // If we're generating more than one load, compute the base address of 13785 // subsequent loads as an offset from the previous. 13786 if (LoadCount > 0) 13787 BaseAddr = Builder.CreateConstGEP1_32( 13788 BaseAddr, VecTy->getVectorNumElements() * Factor); 13789 13790 SmallVector<Value *, 2> Ops; 13791 Ops.push_back(Builder.CreateBitCast(BaseAddr, Int8Ptr)); 13792 Ops.push_back(Builder.getInt32(LI->getAlignment())); 13793 13794 CallInst *VldN = Builder.CreateCall(VldnFunc, Ops, "vldN"); 13795 13796 // Replace uses of each shufflevector with the corresponding vector loaded 13797 // by ldN. 13798 for (unsigned i = 0; i < Shuffles.size(); i++) { 13799 ShuffleVectorInst *SV = Shuffles[i]; 13800 unsigned Index = Indices[i]; 13801 13802 Value *SubVec = Builder.CreateExtractValue(VldN, Index); 13803 13804 // Convert the integer vector to pointer vector if the element is pointer. 13805 if (EltTy->isPointerTy()) 13806 SubVec = Builder.CreateIntToPtr( 13807 SubVec, VectorType::get(SV->getType()->getVectorElementType(), 13808 VecTy->getVectorNumElements())); 13809 13810 SubVecs[SV].push_back(SubVec); 13811 } 13812 } 13813 13814 // Replace uses of the shufflevector instructions with the sub-vectors 13815 // returned by the load intrinsic. If a shufflevector instruction is 13816 // associated with more than one sub-vector, those sub-vectors will be 13817 // concatenated into a single wide vector. 13818 for (ShuffleVectorInst *SVI : Shuffles) { 13819 auto &SubVec = SubVecs[SVI]; 13820 auto *WideVec = 13821 SubVec.size() > 1 ? concatenateVectors(Builder, SubVec) : SubVec[0]; 13822 SVI->replaceAllUsesWith(WideVec); 13823 } 13824 13825 return true; 13826 } 13827 13828 /// \brief Lower an interleaved store into a vstN intrinsic. 13829 /// 13830 /// E.g. Lower an interleaved store (Factor = 3): 13831 /// %i.vec = shuffle <8 x i32> %v0, <8 x i32> %v1, 13832 /// <0, 4, 8, 1, 5, 9, 2, 6, 10, 3, 7, 11> 13833 /// store <12 x i32> %i.vec, <12 x i32>* %ptr, align 4 13834 /// 13835 /// Into: 13836 /// %sub.v0 = shuffle <8 x i32> %v0, <8 x i32> v1, <0, 1, 2, 3> 13837 /// %sub.v1 = shuffle <8 x i32> %v0, <8 x i32> v1, <4, 5, 6, 7> 13838 /// %sub.v2 = shuffle <8 x i32> %v0, <8 x i32> v1, <8, 9, 10, 11> 13839 /// call void llvm.arm.neon.vst3(%ptr, %sub.v0, %sub.v1, %sub.v2, 4) 13840 /// 13841 /// Note that the new shufflevectors will be removed and we'll only generate one 13842 /// vst3 instruction in CodeGen. 13843 /// 13844 /// Example for a more general valid mask (Factor 3). Lower: 13845 /// %i.vec = shuffle <32 x i32> %v0, <32 x i32> %v1, 13846 /// <4, 32, 16, 5, 33, 17, 6, 34, 18, 7, 35, 19> 13847 /// store <12 x i32> %i.vec, <12 x i32>* %ptr 13848 /// 13849 /// Into: 13850 /// %sub.v0 = shuffle <32 x i32> %v0, <32 x i32> v1, <4, 5, 6, 7> 13851 /// %sub.v1 = shuffle <32 x i32> %v0, <32 x i32> v1, <32, 33, 34, 35> 13852 /// %sub.v2 = shuffle <32 x i32> %v0, <32 x i32> v1, <16, 17, 18, 19> 13853 /// call void llvm.arm.neon.vst3(%ptr, %sub.v0, %sub.v1, %sub.v2, 4) 13854 bool ARMTargetLowering::lowerInterleavedStore(StoreInst *SI, 13855 ShuffleVectorInst *SVI, 13856 unsigned Factor) const { 13857 assert(Factor >= 2 && Factor <= getMaxSupportedInterleaveFactor() && 13858 "Invalid interleave factor"); 13859 13860 VectorType *VecTy = SVI->getType(); 13861 assert(VecTy->getVectorNumElements() % Factor == 0 && 13862 "Invalid interleaved store"); 13863 13864 unsigned LaneLen = VecTy->getVectorNumElements() / Factor; 13865 Type *EltTy = VecTy->getVectorElementType(); 13866 VectorType *SubVecTy = VectorType::get(EltTy, LaneLen); 13867 13868 const DataLayout &DL = SI->getModule()->getDataLayout(); 13869 13870 // Skip if we do not have NEON and skip illegal vector types. We can 13871 // "legalize" wide vector types into multiple interleaved accesses as long as 13872 // the vector types are divisible by 128. 13873 if (!Subtarget->hasNEON() || !isLegalInterleavedAccessType(SubVecTy, DL)) 13874 return false; 13875 13876 unsigned NumStores = getNumInterleavedAccesses(SubVecTy, DL); 13877 13878 Value *Op0 = SVI->getOperand(0); 13879 Value *Op1 = SVI->getOperand(1); 13880 IRBuilder<> Builder(SI); 13881 13882 // StN intrinsics don't support pointer vectors as arguments. Convert pointer 13883 // vectors to integer vectors. 13884 if (EltTy->isPointerTy()) { 13885 Type *IntTy = DL.getIntPtrType(EltTy); 13886 13887 // Convert to the corresponding integer vector. 13888 Type *IntVecTy = 13889 VectorType::get(IntTy, Op0->getType()->getVectorNumElements()); 13890 Op0 = Builder.CreatePtrToInt(Op0, IntVecTy); 13891 Op1 = Builder.CreatePtrToInt(Op1, IntVecTy); 13892 13893 SubVecTy = VectorType::get(IntTy, LaneLen); 13894 } 13895 13896 // The base address of the store. 13897 Value *BaseAddr = SI->getPointerOperand(); 13898 13899 if (NumStores > 1) { 13900 // If we're going to generate more than one store, reset the lane length 13901 // and sub-vector type to something legal. 13902 LaneLen /= NumStores; 13903 SubVecTy = VectorType::get(SubVecTy->getVectorElementType(), LaneLen); 13904 13905 // We will compute the pointer operand of each store from the original base 13906 // address using GEPs. Cast the base address to a pointer to the scalar 13907 // element type. 13908 BaseAddr = Builder.CreateBitCast( 13909 BaseAddr, SubVecTy->getVectorElementType()->getPointerTo( 13910 SI->getPointerAddressSpace())); 13911 } 13912 13913 assert(isTypeLegal(EVT::getEVT(SubVecTy)) && "Illegal vstN vector type!"); 13914 13915 auto Mask = SVI->getShuffleMask(); 13916 13917 Type *Int8Ptr = Builder.getInt8PtrTy(SI->getPointerAddressSpace()); 13918 Type *Tys[] = {Int8Ptr, SubVecTy}; 13919 static const Intrinsic::ID StoreInts[3] = {Intrinsic::arm_neon_vst2, 13920 Intrinsic::arm_neon_vst3, 13921 Intrinsic::arm_neon_vst4}; 13922 13923 for (unsigned StoreCount = 0; StoreCount < NumStores; ++StoreCount) { 13924 13925 // If we generating more than one store, we compute the base address of 13926 // subsequent stores as an offset from the previous. 13927 if (StoreCount > 0) 13928 BaseAddr = Builder.CreateConstGEP1_32(BaseAddr, LaneLen * Factor); 13929 13930 SmallVector<Value *, 6> Ops; 13931 Ops.push_back(Builder.CreateBitCast(BaseAddr, Int8Ptr)); 13932 13933 Function *VstNFunc = 13934 Intrinsic::getDeclaration(SI->getModule(), StoreInts[Factor - 2], Tys); 13935 13936 // Split the shufflevector operands into sub vectors for the new vstN call. 13937 for (unsigned i = 0; i < Factor; i++) { 13938 unsigned IdxI = StoreCount * LaneLen * Factor + i; 13939 if (Mask[IdxI] >= 0) { 13940 Ops.push_back(Builder.CreateShuffleVector( 13941 Op0, Op1, createSequentialMask(Builder, Mask[IdxI], LaneLen, 0))); 13942 } else { 13943 unsigned StartMask = 0; 13944 for (unsigned j = 1; j < LaneLen; j++) { 13945 unsigned IdxJ = StoreCount * LaneLen * Factor + j; 13946 if (Mask[IdxJ * Factor + IdxI] >= 0) { 13947 StartMask = Mask[IdxJ * Factor + IdxI] - IdxJ; 13948 break; 13949 } 13950 } 13951 // Note: If all elements in a chunk are undefs, StartMask=0! 13952 // Note: Filling undef gaps with random elements is ok, since 13953 // those elements were being written anyway (with undefs). 13954 // In the case of all undefs we're defaulting to using elems from 0 13955 // Note: StartMask cannot be negative, it's checked in 13956 // isReInterleaveMask 13957 Ops.push_back(Builder.CreateShuffleVector( 13958 Op0, Op1, createSequentialMask(Builder, StartMask, LaneLen, 0))); 13959 } 13960 } 13961 13962 Ops.push_back(Builder.getInt32(SI->getAlignment())); 13963 Builder.CreateCall(VstNFunc, Ops); 13964 } 13965 return true; 13966 } 13967 13968 enum HABaseType { 13969 HA_UNKNOWN = 0, 13970 HA_FLOAT, 13971 HA_DOUBLE, 13972 HA_VECT64, 13973 HA_VECT128 13974 }; 13975 13976 static bool isHomogeneousAggregate(Type *Ty, HABaseType &Base, 13977 uint64_t &Members) { 13978 if (auto *ST = dyn_cast<StructType>(Ty)) { 13979 for (unsigned i = 0; i < ST->getNumElements(); ++i) { 13980 uint64_t SubMembers = 0; 13981 if (!isHomogeneousAggregate(ST->getElementType(i), Base, SubMembers)) 13982 return false; 13983 Members += SubMembers; 13984 } 13985 } else if (auto *AT = dyn_cast<ArrayType>(Ty)) { 13986 uint64_t SubMembers = 0; 13987 if (!isHomogeneousAggregate(AT->getElementType(), Base, SubMembers)) 13988 return false; 13989 Members += SubMembers * AT->getNumElements(); 13990 } else if (Ty->isFloatTy()) { 13991 if (Base != HA_UNKNOWN && Base != HA_FLOAT) 13992 return false; 13993 Members = 1; 13994 Base = HA_FLOAT; 13995 } else if (Ty->isDoubleTy()) { 13996 if (Base != HA_UNKNOWN && Base != HA_DOUBLE) 13997 return false; 13998 Members = 1; 13999 Base = HA_DOUBLE; 14000 } else if (auto *VT = dyn_cast<VectorType>(Ty)) { 14001 Members = 1; 14002 switch (Base) { 14003 case HA_FLOAT: 14004 case HA_DOUBLE: 14005 return false; 14006 case HA_VECT64: 14007 return VT->getBitWidth() == 64; 14008 case HA_VECT128: 14009 return VT->getBitWidth() == 128; 14010 case HA_UNKNOWN: 14011 switch (VT->getBitWidth()) { 14012 case 64: 14013 Base = HA_VECT64; 14014 return true; 14015 case 128: 14016 Base = HA_VECT128; 14017 return true; 14018 default: 14019 return false; 14020 } 14021 } 14022 } 14023 14024 return (Members > 0 && Members <= 4); 14025 } 14026 14027 /// \brief Return true if a type is an AAPCS-VFP homogeneous aggregate or one of 14028 /// [N x i32] or [N x i64]. This allows front-ends to skip emitting padding when 14029 /// passing according to AAPCS rules. 14030 bool ARMTargetLowering::functionArgumentNeedsConsecutiveRegisters( 14031 Type *Ty, CallingConv::ID CallConv, bool isVarArg) const { 14032 if (getEffectiveCallingConv(CallConv, isVarArg) != 14033 CallingConv::ARM_AAPCS_VFP) 14034 return false; 14035 14036 HABaseType Base = HA_UNKNOWN; 14037 uint64_t Members = 0; 14038 bool IsHA = isHomogeneousAggregate(Ty, Base, Members); 14039 DEBUG(dbgs() << "isHA: " << IsHA << " "; Ty->dump()); 14040 14041 bool IsIntArray = Ty->isArrayTy() && Ty->getArrayElementType()->isIntegerTy(); 14042 return IsHA || IsIntArray; 14043 } 14044 14045 unsigned ARMTargetLowering::getExceptionPointerRegister( 14046 const Constant *PersonalityFn) const { 14047 // Platforms which do not use SjLj EH may return values in these registers 14048 // via the personality function. 14049 return Subtarget->useSjLjEH() ? ARM::NoRegister : ARM::R0; 14050 } 14051 14052 unsigned ARMTargetLowering::getExceptionSelectorRegister( 14053 const Constant *PersonalityFn) const { 14054 // Platforms which do not use SjLj EH may return values in these registers 14055 // via the personality function. 14056 return Subtarget->useSjLjEH() ? ARM::NoRegister : ARM::R1; 14057 } 14058 14059 void ARMTargetLowering::initializeSplitCSR(MachineBasicBlock *Entry) const { 14060 // Update IsSplitCSR in ARMFunctionInfo. 14061 ARMFunctionInfo *AFI = Entry->getParent()->getInfo<ARMFunctionInfo>(); 14062 AFI->setIsSplitCSR(true); 14063 } 14064 14065 void ARMTargetLowering::insertCopiesSplitCSR( 14066 MachineBasicBlock *Entry, 14067 const SmallVectorImpl<MachineBasicBlock *> &Exits) const { 14068 const ARMBaseRegisterInfo *TRI = Subtarget->getRegisterInfo(); 14069 const MCPhysReg *IStart = TRI->getCalleeSavedRegsViaCopy(Entry->getParent()); 14070 if (!IStart) 14071 return; 14072 14073 const TargetInstrInfo *TII = Subtarget->getInstrInfo(); 14074 MachineRegisterInfo *MRI = &Entry->getParent()->getRegInfo(); 14075 MachineBasicBlock::iterator MBBI = Entry->begin(); 14076 for (const MCPhysReg *I = IStart; *I; ++I) { 14077 const TargetRegisterClass *RC = nullptr; 14078 if (ARM::GPRRegClass.contains(*I)) 14079 RC = &ARM::GPRRegClass; 14080 else if (ARM::DPRRegClass.contains(*I)) 14081 RC = &ARM::DPRRegClass; 14082 else 14083 llvm_unreachable("Unexpected register class in CSRsViaCopy!"); 14084 14085 unsigned NewVR = MRI->createVirtualRegister(RC); 14086 // Create copy from CSR to a virtual register. 14087 // FIXME: this currently does not emit CFI pseudo-instructions, it works 14088 // fine for CXX_FAST_TLS since the C++-style TLS access functions should be 14089 // nounwind. If we want to generalize this later, we may need to emit 14090 // CFI pseudo-instructions. 14091 assert(Entry->getParent()->getFunction()->hasFnAttribute( 14092 Attribute::NoUnwind) && 14093 "Function should be nounwind in insertCopiesSplitCSR!"); 14094 Entry->addLiveIn(*I); 14095 BuildMI(*Entry, MBBI, DebugLoc(), TII->get(TargetOpcode::COPY), NewVR) 14096 .addReg(*I); 14097 14098 // Insert the copy-back instructions right before the terminator. 14099 for (auto *Exit : Exits) 14100 BuildMI(*Exit, Exit->getFirstTerminator(), DebugLoc(), 14101 TII->get(TargetOpcode::COPY), *I) 14102 .addReg(NewVR); 14103 } 14104 } 14105 14106 void ARMTargetLowering::finalizeLowering(MachineFunction &MF) const { 14107 MF.getFrameInfo().computeMaxCallFrameSize(MF); 14108 TargetLoweringBase::finalizeLowering(MF); 14109 } 14110