1 //===- ARMISelLowering.cpp - ARM DAG Lowering Implementation --------------===// 2 // 3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. 4 // See https://llvm.org/LICENSE.txt for license information. 5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception 6 // 7 //===----------------------------------------------------------------------===// 8 // 9 // This file defines the interfaces that ARM uses to lower LLVM code into a 10 // selection DAG. 11 // 12 //===----------------------------------------------------------------------===// 13 14 #include "ARMISelLowering.h" 15 #include "ARMBaseInstrInfo.h" 16 #include "ARMBaseRegisterInfo.h" 17 #include "ARMCallingConv.h" 18 #include "ARMConstantPoolValue.h" 19 #include "ARMMachineFunctionInfo.h" 20 #include "ARMPerfectShuffle.h" 21 #include "ARMRegisterInfo.h" 22 #include "ARMSelectionDAGInfo.h" 23 #include "ARMSubtarget.h" 24 #include "MCTargetDesc/ARMAddressingModes.h" 25 #include "MCTargetDesc/ARMBaseInfo.h" 26 #include "Utils/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/RuntimeLibcalls.h" 56 #include "llvm/CodeGen/SelectionDAG.h" 57 #include "llvm/CodeGen/SelectionDAGNodes.h" 58 #include "llvm/CodeGen/TargetInstrInfo.h" 59 #include "llvm/CodeGen/TargetLowering.h" 60 #include "llvm/CodeGen/TargetOpcodes.h" 61 #include "llvm/CodeGen/TargetRegisterInfo.h" 62 #include "llvm/CodeGen/TargetSubtargetInfo.h" 63 #include "llvm/CodeGen/ValueTypes.h" 64 #include "llvm/IR/Attributes.h" 65 #include "llvm/IR/CallingConv.h" 66 #include "llvm/IR/Constant.h" 67 #include "llvm/IR/Constants.h" 68 #include "llvm/IR/DataLayout.h" 69 #include "llvm/IR/DebugLoc.h" 70 #include "llvm/IR/DerivedTypes.h" 71 #include "llvm/IR/Function.h" 72 #include "llvm/IR/GlobalAlias.h" 73 #include "llvm/IR/GlobalValue.h" 74 #include "llvm/IR/GlobalVariable.h" 75 #include "llvm/IR/IRBuilder.h" 76 #include "llvm/IR/InlineAsm.h" 77 #include "llvm/IR/Instruction.h" 78 #include "llvm/IR/Instructions.h" 79 #include "llvm/IR/IntrinsicInst.h" 80 #include "llvm/IR/Intrinsics.h" 81 #include "llvm/IR/Module.h" 82 #include "llvm/IR/PatternMatch.h" 83 #include "llvm/IR/Type.h" 84 #include "llvm/IR/User.h" 85 #include "llvm/IR/Value.h" 86 #include "llvm/MC/MCInstrDesc.h" 87 #include "llvm/MC/MCInstrItineraries.h" 88 #include "llvm/MC/MCRegisterInfo.h" 89 #include "llvm/MC/MCSchedule.h" 90 #include "llvm/Support/AtomicOrdering.h" 91 #include "llvm/Support/BranchProbability.h" 92 #include "llvm/Support/Casting.h" 93 #include "llvm/Support/CodeGen.h" 94 #include "llvm/Support/CommandLine.h" 95 #include "llvm/Support/Compiler.h" 96 #include "llvm/Support/Debug.h" 97 #include "llvm/Support/ErrorHandling.h" 98 #include "llvm/Support/KnownBits.h" 99 #include "llvm/Support/MachineValueType.h" 100 #include "llvm/Support/MathExtras.h" 101 #include "llvm/Support/raw_ostream.h" 102 #include "llvm/Target/TargetMachine.h" 103 #include "llvm/Target/TargetOptions.h" 104 #include <algorithm> 105 #include <cassert> 106 #include <cstdint> 107 #include <cstdlib> 108 #include <iterator> 109 #include <limits> 110 #include <string> 111 #include <tuple> 112 #include <utility> 113 #include <vector> 114 115 using namespace llvm; 116 using namespace llvm::PatternMatch; 117 118 #define DEBUG_TYPE "arm-isel" 119 120 STATISTIC(NumTailCalls, "Number of tail calls"); 121 STATISTIC(NumMovwMovt, "Number of GAs materialized with movw + movt"); 122 STATISTIC(NumLoopByVals, "Number of loops generated for byval arguments"); 123 STATISTIC(NumConstpoolPromoted, 124 "Number of constants with their storage promoted into constant pools"); 125 126 static cl::opt<bool> 127 ARMInterworking("arm-interworking", cl::Hidden, 128 cl::desc("Enable / disable ARM interworking (for debugging only)"), 129 cl::init(true)); 130 131 static cl::opt<bool> EnableConstpoolPromotion( 132 "arm-promote-constant", cl::Hidden, 133 cl::desc("Enable / disable promotion of unnamed_addr constants into " 134 "constant pools"), 135 cl::init(false)); // FIXME: set to true by default once PR32780 is fixed 136 static cl::opt<unsigned> ConstpoolPromotionMaxSize( 137 "arm-promote-constant-max-size", cl::Hidden, 138 cl::desc("Maximum size of constant to promote into a constant pool"), 139 cl::init(64)); 140 static cl::opt<unsigned> ConstpoolPromotionMaxTotal( 141 "arm-promote-constant-max-total", cl::Hidden, 142 cl::desc("Maximum size of ALL constants to promote into a constant pool"), 143 cl::init(128)); 144 145 // The APCS parameter registers. 146 static const MCPhysReg GPRArgRegs[] = { 147 ARM::R0, ARM::R1, ARM::R2, ARM::R3 148 }; 149 150 void ARMTargetLowering::addTypeForNEON(MVT VT, MVT PromotedLdStVT, 151 MVT PromotedBitwiseVT) { 152 if (VT != PromotedLdStVT) { 153 setOperationAction(ISD::LOAD, VT, Promote); 154 AddPromotedToType (ISD::LOAD, VT, PromotedLdStVT); 155 156 setOperationAction(ISD::STORE, VT, Promote); 157 AddPromotedToType (ISD::STORE, VT, PromotedLdStVT); 158 } 159 160 MVT ElemTy = VT.getVectorElementType(); 161 if (ElemTy != MVT::f64) 162 setOperationAction(ISD::SETCC, VT, Custom); 163 setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Custom); 164 setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom); 165 if (ElemTy == MVT::i32) { 166 setOperationAction(ISD::SINT_TO_FP, VT, Custom); 167 setOperationAction(ISD::UINT_TO_FP, VT, Custom); 168 setOperationAction(ISD::FP_TO_SINT, VT, Custom); 169 setOperationAction(ISD::FP_TO_UINT, VT, Custom); 170 } else { 171 setOperationAction(ISD::SINT_TO_FP, VT, Expand); 172 setOperationAction(ISD::UINT_TO_FP, VT, Expand); 173 setOperationAction(ISD::FP_TO_SINT, VT, Expand); 174 setOperationAction(ISD::FP_TO_UINT, VT, Expand); 175 } 176 setOperationAction(ISD::BUILD_VECTOR, VT, Custom); 177 setOperationAction(ISD::VECTOR_SHUFFLE, VT, Custom); 178 setOperationAction(ISD::CONCAT_VECTORS, VT, Legal); 179 setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Legal); 180 setOperationAction(ISD::SELECT, VT, Expand); 181 setOperationAction(ISD::SELECT_CC, VT, Expand); 182 setOperationAction(ISD::VSELECT, VT, Expand); 183 setOperationAction(ISD::SIGN_EXTEND_INREG, VT, Expand); 184 if (VT.isInteger()) { 185 setOperationAction(ISD::SHL, VT, Custom); 186 setOperationAction(ISD::SRA, VT, Custom); 187 setOperationAction(ISD::SRL, VT, Custom); 188 } 189 190 // Promote all bit-wise operations. 191 if (VT.isInteger() && VT != PromotedBitwiseVT) { 192 setOperationAction(ISD::AND, VT, Promote); 193 AddPromotedToType (ISD::AND, VT, PromotedBitwiseVT); 194 setOperationAction(ISD::OR, VT, Promote); 195 AddPromotedToType (ISD::OR, VT, PromotedBitwiseVT); 196 setOperationAction(ISD::XOR, VT, Promote); 197 AddPromotedToType (ISD::XOR, VT, PromotedBitwiseVT); 198 } 199 200 // Neon does not support vector divide/remainder operations. 201 setOperationAction(ISD::SDIV, VT, Expand); 202 setOperationAction(ISD::UDIV, VT, Expand); 203 setOperationAction(ISD::FDIV, VT, Expand); 204 setOperationAction(ISD::SREM, VT, Expand); 205 setOperationAction(ISD::UREM, VT, Expand); 206 setOperationAction(ISD::FREM, VT, Expand); 207 208 if (!VT.isFloatingPoint() && 209 VT != MVT::v2i64 && VT != MVT::v1i64) 210 for (auto Opcode : {ISD::ABS, ISD::SMIN, ISD::SMAX, ISD::UMIN, ISD::UMAX}) 211 setOperationAction(Opcode, VT, Legal); 212 } 213 214 void ARMTargetLowering::addDRTypeForNEON(MVT VT) { 215 addRegisterClass(VT, &ARM::DPRRegClass); 216 addTypeForNEON(VT, MVT::f64, MVT::v2i32); 217 } 218 219 void ARMTargetLowering::addQRTypeForNEON(MVT VT) { 220 addRegisterClass(VT, &ARM::DPairRegClass); 221 addTypeForNEON(VT, MVT::v2f64, MVT::v4i32); 222 } 223 224 void ARMTargetLowering::setAllExpand(MVT VT) { 225 for (unsigned Opc = 0; Opc < ISD::BUILTIN_OP_END; ++Opc) 226 setOperationAction(Opc, VT, Expand); 227 228 // We support these really simple operations even on types where all 229 // the actual arithmetic has to be broken down into simpler 230 // operations or turned into library calls. 231 setOperationAction(ISD::BITCAST, VT, Legal); 232 setOperationAction(ISD::LOAD, VT, Legal); 233 setOperationAction(ISD::STORE, VT, Legal); 234 setOperationAction(ISD::UNDEF, VT, Legal); 235 } 236 237 void ARMTargetLowering::addAllExtLoads(const MVT From, const MVT To, 238 LegalizeAction Action) { 239 setLoadExtAction(ISD::EXTLOAD, From, To, Action); 240 setLoadExtAction(ISD::ZEXTLOAD, From, To, Action); 241 setLoadExtAction(ISD::SEXTLOAD, From, To, Action); 242 } 243 244 void ARMTargetLowering::addMVEVectorTypes(bool HasMVEFP) { 245 const MVT IntTypes[] = { MVT::v16i8, MVT::v8i16, MVT::v4i32 }; 246 247 for (auto VT : IntTypes) { 248 addRegisterClass(VT, &ARM::QPRRegClass); 249 setOperationAction(ISD::VECTOR_SHUFFLE, VT, Custom); 250 setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Custom); 251 setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom); 252 setOperationAction(ISD::BUILD_VECTOR, VT, Custom); 253 254 // No native support for these. 255 setOperationAction(ISD::UDIV, VT, Expand); 256 setOperationAction(ISD::SDIV, VT, Expand); 257 setOperationAction(ISD::UREM, VT, Expand); 258 setOperationAction(ISD::SREM, VT, Expand); 259 } 260 261 const MVT FloatTypes[] = { MVT::v8f16, MVT::v4f32 }; 262 for (auto VT : FloatTypes) { 263 addRegisterClass(VT, &ARM::QPRRegClass); 264 if (!HasMVEFP) 265 setAllExpand(VT); 266 267 // These are legal or custom whether we have MVE.fp or not 268 setOperationAction(ISD::VECTOR_SHUFFLE, VT, Custom); 269 setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Custom); 270 setOperationAction(ISD::INSERT_VECTOR_ELT, VT.getVectorElementType(), Custom); 271 setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom); 272 setOperationAction(ISD::BUILD_VECTOR, VT, Custom); 273 setOperationAction(ISD::BUILD_VECTOR, VT.getVectorElementType(), Custom); 274 setOperationAction(ISD::SCALAR_TO_VECTOR, VT, Legal); 275 276 if (HasMVEFP) { 277 // No native support for these. 278 setOperationAction(ISD::FDIV, VT, Expand); 279 setOperationAction(ISD::FREM, VT, Expand); 280 setOperationAction(ISD::FSQRT, VT, Expand); 281 setOperationAction(ISD::FSIN, VT, Expand); 282 setOperationAction(ISD::FCOS, VT, Expand); 283 setOperationAction(ISD::FPOW, VT, Expand); 284 setOperationAction(ISD::FLOG, VT, Expand); 285 setOperationAction(ISD::FLOG2, VT, Expand); 286 setOperationAction(ISD::FLOG10, VT, Expand); 287 setOperationAction(ISD::FEXP, VT, Expand); 288 setOperationAction(ISD::FEXP2, VT, Expand); 289 } 290 } 291 292 // We 'support' these types up to bitcast/load/store level, regardless of 293 // MVE integer-only / float support. Only doing FP data processing on the FP 294 // vector types is inhibited at integer-only level. 295 const MVT LongTypes[] = { MVT::v2i64, MVT::v2f64 }; 296 for (auto VT : LongTypes) { 297 addRegisterClass(VT, &ARM::QPRRegClass); 298 setAllExpand(VT); 299 setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Custom); 300 setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom); 301 setOperationAction(ISD::BUILD_VECTOR, VT, Custom); 302 } 303 304 // It is legal to extload from v4i8 to v4i16 or v4i32. 305 addAllExtLoads(MVT::v8i16, MVT::v8i8, Legal); 306 addAllExtLoads(MVT::v4i32, MVT::v4i16, Legal); 307 addAllExtLoads(MVT::v4i32, MVT::v4i8, Legal); 308 309 // Some truncating stores are legal too. 310 setTruncStoreAction(MVT::v4i32, MVT::v4i16, Legal); 311 setTruncStoreAction(MVT::v4i32, MVT::v4i8, Legal); 312 setTruncStoreAction(MVT::v8i16, MVT::v8i8, Legal); 313 } 314 315 ARMTargetLowering::ARMTargetLowering(const TargetMachine &TM, 316 const ARMSubtarget &STI) 317 : TargetLowering(TM), Subtarget(&STI) { 318 RegInfo = Subtarget->getRegisterInfo(); 319 Itins = Subtarget->getInstrItineraryData(); 320 321 setBooleanContents(ZeroOrOneBooleanContent); 322 setBooleanVectorContents(ZeroOrNegativeOneBooleanContent); 323 324 if (!Subtarget->isTargetDarwin() && !Subtarget->isTargetIOS() && 325 !Subtarget->isTargetWatchOS()) { 326 bool IsHFTarget = TM.Options.FloatABIType == FloatABI::Hard; 327 for (int LCID = 0; LCID < RTLIB::UNKNOWN_LIBCALL; ++LCID) 328 setLibcallCallingConv(static_cast<RTLIB::Libcall>(LCID), 329 IsHFTarget ? CallingConv::ARM_AAPCS_VFP 330 : CallingConv::ARM_AAPCS); 331 } 332 333 if (Subtarget->isTargetMachO()) { 334 // Uses VFP for Thumb libfuncs if available. 335 if (Subtarget->isThumb() && Subtarget->hasVFP2Base() && 336 Subtarget->hasARMOps() && !Subtarget->useSoftFloat()) { 337 static const struct { 338 const RTLIB::Libcall Op; 339 const char * const Name; 340 const ISD::CondCode Cond; 341 } LibraryCalls[] = { 342 // Single-precision floating-point arithmetic. 343 { RTLIB::ADD_F32, "__addsf3vfp", ISD::SETCC_INVALID }, 344 { RTLIB::SUB_F32, "__subsf3vfp", ISD::SETCC_INVALID }, 345 { RTLIB::MUL_F32, "__mulsf3vfp", ISD::SETCC_INVALID }, 346 { RTLIB::DIV_F32, "__divsf3vfp", ISD::SETCC_INVALID }, 347 348 // Double-precision floating-point arithmetic. 349 { RTLIB::ADD_F64, "__adddf3vfp", ISD::SETCC_INVALID }, 350 { RTLIB::SUB_F64, "__subdf3vfp", ISD::SETCC_INVALID }, 351 { RTLIB::MUL_F64, "__muldf3vfp", ISD::SETCC_INVALID }, 352 { RTLIB::DIV_F64, "__divdf3vfp", ISD::SETCC_INVALID }, 353 354 // Single-precision comparisons. 355 { RTLIB::OEQ_F32, "__eqsf2vfp", ISD::SETNE }, 356 { RTLIB::UNE_F32, "__nesf2vfp", ISD::SETNE }, 357 { RTLIB::OLT_F32, "__ltsf2vfp", ISD::SETNE }, 358 { RTLIB::OLE_F32, "__lesf2vfp", ISD::SETNE }, 359 { RTLIB::OGE_F32, "__gesf2vfp", ISD::SETNE }, 360 { RTLIB::OGT_F32, "__gtsf2vfp", ISD::SETNE }, 361 { RTLIB::UO_F32, "__unordsf2vfp", ISD::SETNE }, 362 { RTLIB::O_F32, "__unordsf2vfp", ISD::SETEQ }, 363 364 // Double-precision comparisons. 365 { RTLIB::OEQ_F64, "__eqdf2vfp", ISD::SETNE }, 366 { RTLIB::UNE_F64, "__nedf2vfp", ISD::SETNE }, 367 { RTLIB::OLT_F64, "__ltdf2vfp", ISD::SETNE }, 368 { RTLIB::OLE_F64, "__ledf2vfp", ISD::SETNE }, 369 { RTLIB::OGE_F64, "__gedf2vfp", ISD::SETNE }, 370 { RTLIB::OGT_F64, "__gtdf2vfp", ISD::SETNE }, 371 { RTLIB::UO_F64, "__unorddf2vfp", ISD::SETNE }, 372 { RTLIB::O_F64, "__unorddf2vfp", ISD::SETEQ }, 373 374 // Floating-point to integer conversions. 375 // i64 conversions are done via library routines even when generating VFP 376 // instructions, so use the same ones. 377 { RTLIB::FPTOSINT_F64_I32, "__fixdfsivfp", ISD::SETCC_INVALID }, 378 { RTLIB::FPTOUINT_F64_I32, "__fixunsdfsivfp", ISD::SETCC_INVALID }, 379 { RTLIB::FPTOSINT_F32_I32, "__fixsfsivfp", ISD::SETCC_INVALID }, 380 { RTLIB::FPTOUINT_F32_I32, "__fixunssfsivfp", ISD::SETCC_INVALID }, 381 382 // Conversions between floating types. 383 { RTLIB::FPROUND_F64_F32, "__truncdfsf2vfp", ISD::SETCC_INVALID }, 384 { RTLIB::FPEXT_F32_F64, "__extendsfdf2vfp", ISD::SETCC_INVALID }, 385 386 // Integer to floating-point conversions. 387 // i64 conversions are done via library routines even when generating VFP 388 // instructions, so use the same ones. 389 // FIXME: There appears to be some naming inconsistency in ARM libgcc: 390 // e.g., __floatunsidf vs. __floatunssidfvfp. 391 { RTLIB::SINTTOFP_I32_F64, "__floatsidfvfp", ISD::SETCC_INVALID }, 392 { RTLIB::UINTTOFP_I32_F64, "__floatunssidfvfp", ISD::SETCC_INVALID }, 393 { RTLIB::SINTTOFP_I32_F32, "__floatsisfvfp", ISD::SETCC_INVALID }, 394 { RTLIB::UINTTOFP_I32_F32, "__floatunssisfvfp", ISD::SETCC_INVALID }, 395 }; 396 397 for (const auto &LC : LibraryCalls) { 398 setLibcallName(LC.Op, LC.Name); 399 if (LC.Cond != ISD::SETCC_INVALID) 400 setCmpLibcallCC(LC.Op, LC.Cond); 401 } 402 } 403 } 404 405 // These libcalls are not available in 32-bit. 406 setLibcallName(RTLIB::SHL_I128, nullptr); 407 setLibcallName(RTLIB::SRL_I128, nullptr); 408 setLibcallName(RTLIB::SRA_I128, nullptr); 409 410 // RTLIB 411 if (Subtarget->isAAPCS_ABI() && 412 (Subtarget->isTargetAEABI() || Subtarget->isTargetGNUAEABI() || 413 Subtarget->isTargetMuslAEABI() || Subtarget->isTargetAndroid())) { 414 static const struct { 415 const RTLIB::Libcall Op; 416 const char * const Name; 417 const CallingConv::ID CC; 418 const ISD::CondCode Cond; 419 } LibraryCalls[] = { 420 // Double-precision floating-point arithmetic helper functions 421 // RTABI chapter 4.1.2, Table 2 422 { RTLIB::ADD_F64, "__aeabi_dadd", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 423 { RTLIB::DIV_F64, "__aeabi_ddiv", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 424 { RTLIB::MUL_F64, "__aeabi_dmul", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 425 { RTLIB::SUB_F64, "__aeabi_dsub", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 426 427 // Double-precision floating-point comparison helper functions 428 // RTABI chapter 4.1.2, Table 3 429 { RTLIB::OEQ_F64, "__aeabi_dcmpeq", CallingConv::ARM_AAPCS, ISD::SETNE }, 430 { RTLIB::UNE_F64, "__aeabi_dcmpeq", CallingConv::ARM_AAPCS, ISD::SETEQ }, 431 { RTLIB::OLT_F64, "__aeabi_dcmplt", CallingConv::ARM_AAPCS, ISD::SETNE }, 432 { RTLIB::OLE_F64, "__aeabi_dcmple", CallingConv::ARM_AAPCS, ISD::SETNE }, 433 { RTLIB::OGE_F64, "__aeabi_dcmpge", CallingConv::ARM_AAPCS, ISD::SETNE }, 434 { RTLIB::OGT_F64, "__aeabi_dcmpgt", CallingConv::ARM_AAPCS, ISD::SETNE }, 435 { RTLIB::UO_F64, "__aeabi_dcmpun", CallingConv::ARM_AAPCS, ISD::SETNE }, 436 { RTLIB::O_F64, "__aeabi_dcmpun", CallingConv::ARM_AAPCS, ISD::SETEQ }, 437 438 // Single-precision floating-point arithmetic helper functions 439 // RTABI chapter 4.1.2, Table 4 440 { RTLIB::ADD_F32, "__aeabi_fadd", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 441 { RTLIB::DIV_F32, "__aeabi_fdiv", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 442 { RTLIB::MUL_F32, "__aeabi_fmul", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 443 { RTLIB::SUB_F32, "__aeabi_fsub", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 444 445 // Single-precision floating-point comparison helper functions 446 // RTABI chapter 4.1.2, Table 5 447 { RTLIB::OEQ_F32, "__aeabi_fcmpeq", CallingConv::ARM_AAPCS, ISD::SETNE }, 448 { RTLIB::UNE_F32, "__aeabi_fcmpeq", CallingConv::ARM_AAPCS, ISD::SETEQ }, 449 { RTLIB::OLT_F32, "__aeabi_fcmplt", CallingConv::ARM_AAPCS, ISD::SETNE }, 450 { RTLIB::OLE_F32, "__aeabi_fcmple", CallingConv::ARM_AAPCS, ISD::SETNE }, 451 { RTLIB::OGE_F32, "__aeabi_fcmpge", CallingConv::ARM_AAPCS, ISD::SETNE }, 452 { RTLIB::OGT_F32, "__aeabi_fcmpgt", CallingConv::ARM_AAPCS, ISD::SETNE }, 453 { RTLIB::UO_F32, "__aeabi_fcmpun", CallingConv::ARM_AAPCS, ISD::SETNE }, 454 { RTLIB::O_F32, "__aeabi_fcmpun", CallingConv::ARM_AAPCS, ISD::SETEQ }, 455 456 // Floating-point to integer conversions. 457 // RTABI chapter 4.1.2, Table 6 458 { RTLIB::FPTOSINT_F64_I32, "__aeabi_d2iz", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 459 { RTLIB::FPTOUINT_F64_I32, "__aeabi_d2uiz", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 460 { RTLIB::FPTOSINT_F64_I64, "__aeabi_d2lz", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 461 { RTLIB::FPTOUINT_F64_I64, "__aeabi_d2ulz", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 462 { RTLIB::FPTOSINT_F32_I32, "__aeabi_f2iz", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 463 { RTLIB::FPTOUINT_F32_I32, "__aeabi_f2uiz", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 464 { RTLIB::FPTOSINT_F32_I64, "__aeabi_f2lz", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 465 { RTLIB::FPTOUINT_F32_I64, "__aeabi_f2ulz", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 466 467 // Conversions between floating types. 468 // RTABI chapter 4.1.2, Table 7 469 { RTLIB::FPROUND_F64_F32, "__aeabi_d2f", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 470 { RTLIB::FPROUND_F64_F16, "__aeabi_d2h", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 471 { RTLIB::FPEXT_F32_F64, "__aeabi_f2d", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 472 473 // Integer to floating-point conversions. 474 // RTABI chapter 4.1.2, Table 8 475 { RTLIB::SINTTOFP_I32_F64, "__aeabi_i2d", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 476 { RTLIB::UINTTOFP_I32_F64, "__aeabi_ui2d", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 477 { RTLIB::SINTTOFP_I64_F64, "__aeabi_l2d", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 478 { RTLIB::UINTTOFP_I64_F64, "__aeabi_ul2d", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 479 { RTLIB::SINTTOFP_I32_F32, "__aeabi_i2f", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 480 { RTLIB::UINTTOFP_I32_F32, "__aeabi_ui2f", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 481 { RTLIB::SINTTOFP_I64_F32, "__aeabi_l2f", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 482 { RTLIB::UINTTOFP_I64_F32, "__aeabi_ul2f", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 483 484 // Long long helper functions 485 // RTABI chapter 4.2, Table 9 486 { RTLIB::MUL_I64, "__aeabi_lmul", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 487 { RTLIB::SHL_I64, "__aeabi_llsl", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 488 { RTLIB::SRL_I64, "__aeabi_llsr", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 489 { RTLIB::SRA_I64, "__aeabi_lasr", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 490 491 // Integer division functions 492 // RTABI chapter 4.3.1 493 { RTLIB::SDIV_I8, "__aeabi_idiv", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 494 { RTLIB::SDIV_I16, "__aeabi_idiv", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 495 { RTLIB::SDIV_I32, "__aeabi_idiv", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 496 { RTLIB::SDIV_I64, "__aeabi_ldivmod", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 497 { RTLIB::UDIV_I8, "__aeabi_uidiv", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 498 { RTLIB::UDIV_I16, "__aeabi_uidiv", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 499 { RTLIB::UDIV_I32, "__aeabi_uidiv", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 500 { RTLIB::UDIV_I64, "__aeabi_uldivmod", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 501 }; 502 503 for (const auto &LC : LibraryCalls) { 504 setLibcallName(LC.Op, LC.Name); 505 setLibcallCallingConv(LC.Op, LC.CC); 506 if (LC.Cond != ISD::SETCC_INVALID) 507 setCmpLibcallCC(LC.Op, LC.Cond); 508 } 509 510 // EABI dependent RTLIB 511 if (TM.Options.EABIVersion == EABI::EABI4 || 512 TM.Options.EABIVersion == EABI::EABI5) { 513 static const struct { 514 const RTLIB::Libcall Op; 515 const char *const Name; 516 const CallingConv::ID CC; 517 const ISD::CondCode Cond; 518 } MemOpsLibraryCalls[] = { 519 // Memory operations 520 // RTABI chapter 4.3.4 521 { RTLIB::MEMCPY, "__aeabi_memcpy", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 522 { RTLIB::MEMMOVE, "__aeabi_memmove", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 523 { RTLIB::MEMSET, "__aeabi_memset", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 524 }; 525 526 for (const auto &LC : MemOpsLibraryCalls) { 527 setLibcallName(LC.Op, LC.Name); 528 setLibcallCallingConv(LC.Op, LC.CC); 529 if (LC.Cond != ISD::SETCC_INVALID) 530 setCmpLibcallCC(LC.Op, LC.Cond); 531 } 532 } 533 } 534 535 if (Subtarget->isTargetWindows()) { 536 static const struct { 537 const RTLIB::Libcall Op; 538 const char * const Name; 539 const CallingConv::ID CC; 540 } LibraryCalls[] = { 541 { RTLIB::FPTOSINT_F32_I64, "__stoi64", CallingConv::ARM_AAPCS_VFP }, 542 { RTLIB::FPTOSINT_F64_I64, "__dtoi64", CallingConv::ARM_AAPCS_VFP }, 543 { RTLIB::FPTOUINT_F32_I64, "__stou64", CallingConv::ARM_AAPCS_VFP }, 544 { RTLIB::FPTOUINT_F64_I64, "__dtou64", CallingConv::ARM_AAPCS_VFP }, 545 { RTLIB::SINTTOFP_I64_F32, "__i64tos", CallingConv::ARM_AAPCS_VFP }, 546 { RTLIB::SINTTOFP_I64_F64, "__i64tod", CallingConv::ARM_AAPCS_VFP }, 547 { RTLIB::UINTTOFP_I64_F32, "__u64tos", CallingConv::ARM_AAPCS_VFP }, 548 { RTLIB::UINTTOFP_I64_F64, "__u64tod", CallingConv::ARM_AAPCS_VFP }, 549 }; 550 551 for (const auto &LC : LibraryCalls) { 552 setLibcallName(LC.Op, LC.Name); 553 setLibcallCallingConv(LC.Op, LC.CC); 554 } 555 } 556 557 // Use divmod compiler-rt calls for iOS 5.0 and later. 558 if (Subtarget->isTargetMachO() && 559 !(Subtarget->isTargetIOS() && 560 Subtarget->getTargetTriple().isOSVersionLT(5, 0))) { 561 setLibcallName(RTLIB::SDIVREM_I32, "__divmodsi4"); 562 setLibcallName(RTLIB::UDIVREM_I32, "__udivmodsi4"); 563 } 564 565 // The half <-> float conversion functions are always soft-float on 566 // non-watchos platforms, but are needed for some targets which use a 567 // hard-float calling convention by default. 568 if (!Subtarget->isTargetWatchABI()) { 569 if (Subtarget->isAAPCS_ABI()) { 570 setLibcallCallingConv(RTLIB::FPROUND_F32_F16, CallingConv::ARM_AAPCS); 571 setLibcallCallingConv(RTLIB::FPROUND_F64_F16, CallingConv::ARM_AAPCS); 572 setLibcallCallingConv(RTLIB::FPEXT_F16_F32, CallingConv::ARM_AAPCS); 573 } else { 574 setLibcallCallingConv(RTLIB::FPROUND_F32_F16, CallingConv::ARM_APCS); 575 setLibcallCallingConv(RTLIB::FPROUND_F64_F16, CallingConv::ARM_APCS); 576 setLibcallCallingConv(RTLIB::FPEXT_F16_F32, CallingConv::ARM_APCS); 577 } 578 } 579 580 // In EABI, these functions have an __aeabi_ prefix, but in GNUEABI they have 581 // a __gnu_ prefix (which is the default). 582 if (Subtarget->isTargetAEABI()) { 583 static const struct { 584 const RTLIB::Libcall Op; 585 const char * const Name; 586 const CallingConv::ID CC; 587 } LibraryCalls[] = { 588 { RTLIB::FPROUND_F32_F16, "__aeabi_f2h", CallingConv::ARM_AAPCS }, 589 { RTLIB::FPROUND_F64_F16, "__aeabi_d2h", CallingConv::ARM_AAPCS }, 590 { RTLIB::FPEXT_F16_F32, "__aeabi_h2f", CallingConv::ARM_AAPCS }, 591 }; 592 593 for (const auto &LC : LibraryCalls) { 594 setLibcallName(LC.Op, LC.Name); 595 setLibcallCallingConv(LC.Op, LC.CC); 596 } 597 } 598 599 if (Subtarget->isThumb1Only()) 600 addRegisterClass(MVT::i32, &ARM::tGPRRegClass); 601 else 602 addRegisterClass(MVT::i32, &ARM::GPRRegClass); 603 604 if (!Subtarget->useSoftFloat() && !Subtarget->isThumb1Only() && 605 Subtarget->hasFPRegs()) { 606 addRegisterClass(MVT::f32, &ARM::SPRRegClass); 607 addRegisterClass(MVT::f64, &ARM::DPRRegClass); 608 if (!Subtarget->hasVFP2Base()) 609 setAllExpand(MVT::f32); 610 if (!Subtarget->hasFP64()) 611 setAllExpand(MVT::f64); 612 } 613 614 if (Subtarget->hasFullFP16()) { 615 addRegisterClass(MVT::f16, &ARM::HPRRegClass); 616 setOperationAction(ISD::BITCAST, MVT::i16, Custom); 617 setOperationAction(ISD::BITCAST, MVT::i32, Custom); 618 setOperationAction(ISD::BITCAST, MVT::f16, Custom); 619 620 setOperationAction(ISD::FMINNUM, MVT::f16, Legal); 621 setOperationAction(ISD::FMAXNUM, MVT::f16, Legal); 622 } 623 624 for (MVT VT : MVT::vector_valuetypes()) { 625 for (MVT InnerVT : MVT::vector_valuetypes()) { 626 setTruncStoreAction(VT, InnerVT, Expand); 627 addAllExtLoads(VT, InnerVT, Expand); 628 } 629 630 setOperationAction(ISD::MULHS, VT, Expand); 631 setOperationAction(ISD::SMUL_LOHI, VT, Expand); 632 setOperationAction(ISD::MULHU, VT, Expand); 633 setOperationAction(ISD::UMUL_LOHI, VT, Expand); 634 635 setOperationAction(ISD::BSWAP, VT, Expand); 636 } 637 638 setOperationAction(ISD::ConstantFP, MVT::f32, Custom); 639 setOperationAction(ISD::ConstantFP, MVT::f64, Custom); 640 641 setOperationAction(ISD::READ_REGISTER, MVT::i64, Custom); 642 setOperationAction(ISD::WRITE_REGISTER, MVT::i64, Custom); 643 644 if (Subtarget->hasMVEIntegerOps()) 645 addMVEVectorTypes(Subtarget->hasMVEFloatOps()); 646 647 // Combine low-overhead loop intrinsics so that we can lower i1 types. 648 if (Subtarget->hasLOB()) 649 setTargetDAGCombine(ISD::BRCOND); 650 651 if (Subtarget->hasNEON()) { 652 addDRTypeForNEON(MVT::v2f32); 653 addDRTypeForNEON(MVT::v8i8); 654 addDRTypeForNEON(MVT::v4i16); 655 addDRTypeForNEON(MVT::v2i32); 656 addDRTypeForNEON(MVT::v1i64); 657 658 addQRTypeForNEON(MVT::v4f32); 659 addQRTypeForNEON(MVT::v2f64); 660 addQRTypeForNEON(MVT::v16i8); 661 addQRTypeForNEON(MVT::v8i16); 662 addQRTypeForNEON(MVT::v4i32); 663 addQRTypeForNEON(MVT::v2i64); 664 665 if (Subtarget->hasFullFP16()) { 666 addQRTypeForNEON(MVT::v8f16); 667 addDRTypeForNEON(MVT::v4f16); 668 } 669 } 670 671 if (Subtarget->hasMVEIntegerOps() || Subtarget->hasNEON()) { 672 // v2f64 is legal so that QR subregs can be extracted as f64 elements, but 673 // none of Neon, MVE or VFP supports any arithmetic operations on it. 674 setOperationAction(ISD::FADD, MVT::v2f64, Expand); 675 setOperationAction(ISD::FSUB, MVT::v2f64, Expand); 676 setOperationAction(ISD::FMUL, MVT::v2f64, Expand); 677 // FIXME: Code duplication: FDIV and FREM are expanded always, see 678 // ARMTargetLowering::addTypeForNEON method for details. 679 setOperationAction(ISD::FDIV, MVT::v2f64, Expand); 680 setOperationAction(ISD::FREM, MVT::v2f64, Expand); 681 // FIXME: Create unittest. 682 // In another words, find a way when "copysign" appears in DAG with vector 683 // operands. 684 setOperationAction(ISD::FCOPYSIGN, MVT::v2f64, Expand); 685 // FIXME: Code duplication: SETCC has custom operation action, see 686 // ARMTargetLowering::addTypeForNEON method for details. 687 setOperationAction(ISD::SETCC, MVT::v2f64, Expand); 688 // FIXME: Create unittest for FNEG and for FABS. 689 setOperationAction(ISD::FNEG, MVT::v2f64, Expand); 690 setOperationAction(ISD::FABS, MVT::v2f64, Expand); 691 setOperationAction(ISD::FSQRT, MVT::v2f64, Expand); 692 setOperationAction(ISD::FSIN, MVT::v2f64, Expand); 693 setOperationAction(ISD::FCOS, MVT::v2f64, Expand); 694 setOperationAction(ISD::FPOW, MVT::v2f64, Expand); 695 setOperationAction(ISD::FLOG, MVT::v2f64, Expand); 696 setOperationAction(ISD::FLOG2, MVT::v2f64, Expand); 697 setOperationAction(ISD::FLOG10, MVT::v2f64, Expand); 698 setOperationAction(ISD::FEXP, MVT::v2f64, Expand); 699 setOperationAction(ISD::FEXP2, MVT::v2f64, Expand); 700 // FIXME: Create unittest for FCEIL, FTRUNC, FRINT, FNEARBYINT, FFLOOR. 701 setOperationAction(ISD::FCEIL, MVT::v2f64, Expand); 702 setOperationAction(ISD::FTRUNC, MVT::v2f64, Expand); 703 setOperationAction(ISD::FRINT, MVT::v2f64, Expand); 704 setOperationAction(ISD::FNEARBYINT, MVT::v2f64, Expand); 705 setOperationAction(ISD::FFLOOR, MVT::v2f64, Expand); 706 setOperationAction(ISD::FMA, MVT::v2f64, Expand); 707 } 708 709 if (Subtarget->hasNEON()) { 710 // The same with v4f32. But keep in mind that vadd, vsub, vmul are natively 711 // supported for v4f32. 712 setOperationAction(ISD::FSQRT, MVT::v4f32, Expand); 713 setOperationAction(ISD::FSIN, MVT::v4f32, Expand); 714 setOperationAction(ISD::FCOS, MVT::v4f32, Expand); 715 setOperationAction(ISD::FPOW, MVT::v4f32, Expand); 716 setOperationAction(ISD::FLOG, MVT::v4f32, Expand); 717 setOperationAction(ISD::FLOG2, MVT::v4f32, Expand); 718 setOperationAction(ISD::FLOG10, MVT::v4f32, Expand); 719 setOperationAction(ISD::FEXP, MVT::v4f32, Expand); 720 setOperationAction(ISD::FEXP2, MVT::v4f32, Expand); 721 setOperationAction(ISD::FCEIL, MVT::v4f32, Expand); 722 setOperationAction(ISD::FTRUNC, MVT::v4f32, Expand); 723 setOperationAction(ISD::FRINT, MVT::v4f32, Expand); 724 setOperationAction(ISD::FNEARBYINT, MVT::v4f32, Expand); 725 setOperationAction(ISD::FFLOOR, MVT::v4f32, Expand); 726 727 // Mark v2f32 intrinsics. 728 setOperationAction(ISD::FSQRT, MVT::v2f32, Expand); 729 setOperationAction(ISD::FSIN, MVT::v2f32, Expand); 730 setOperationAction(ISD::FCOS, MVT::v2f32, Expand); 731 setOperationAction(ISD::FPOW, MVT::v2f32, Expand); 732 setOperationAction(ISD::FLOG, MVT::v2f32, Expand); 733 setOperationAction(ISD::FLOG2, MVT::v2f32, Expand); 734 setOperationAction(ISD::FLOG10, MVT::v2f32, Expand); 735 setOperationAction(ISD::FEXP, MVT::v2f32, Expand); 736 setOperationAction(ISD::FEXP2, MVT::v2f32, Expand); 737 setOperationAction(ISD::FCEIL, MVT::v2f32, Expand); 738 setOperationAction(ISD::FTRUNC, MVT::v2f32, Expand); 739 setOperationAction(ISD::FRINT, MVT::v2f32, Expand); 740 setOperationAction(ISD::FNEARBYINT, MVT::v2f32, Expand); 741 setOperationAction(ISD::FFLOOR, MVT::v2f32, Expand); 742 743 // Neon does not support some operations on v1i64 and v2i64 types. 744 setOperationAction(ISD::MUL, MVT::v1i64, Expand); 745 // Custom handling for some quad-vector types to detect VMULL. 746 setOperationAction(ISD::MUL, MVT::v8i16, Custom); 747 setOperationAction(ISD::MUL, MVT::v4i32, Custom); 748 setOperationAction(ISD::MUL, MVT::v2i64, Custom); 749 // Custom handling for some vector types to avoid expensive expansions 750 setOperationAction(ISD::SDIV, MVT::v4i16, Custom); 751 setOperationAction(ISD::SDIV, MVT::v8i8, Custom); 752 setOperationAction(ISD::UDIV, MVT::v4i16, Custom); 753 setOperationAction(ISD::UDIV, MVT::v8i8, Custom); 754 // Neon does not have single instruction SINT_TO_FP and UINT_TO_FP with 755 // a destination type that is wider than the source, and nor does 756 // it have a FP_TO_[SU]INT instruction with a narrower destination than 757 // source. 758 setOperationAction(ISD::SINT_TO_FP, MVT::v4i16, Custom); 759 setOperationAction(ISD::SINT_TO_FP, MVT::v8i16, Custom); 760 setOperationAction(ISD::UINT_TO_FP, MVT::v4i16, Custom); 761 setOperationAction(ISD::UINT_TO_FP, MVT::v8i16, Custom); 762 setOperationAction(ISD::FP_TO_UINT, MVT::v4i16, Custom); 763 setOperationAction(ISD::FP_TO_UINT, MVT::v8i16, Custom); 764 setOperationAction(ISD::FP_TO_SINT, MVT::v4i16, Custom); 765 setOperationAction(ISD::FP_TO_SINT, MVT::v8i16, Custom); 766 767 setOperationAction(ISD::FP_ROUND, MVT::v2f32, Expand); 768 setOperationAction(ISD::FP_EXTEND, MVT::v2f64, Expand); 769 770 // NEON does not have single instruction CTPOP for vectors with element 771 // types wider than 8-bits. However, custom lowering can leverage the 772 // v8i8/v16i8 vcnt instruction. 773 setOperationAction(ISD::CTPOP, MVT::v2i32, Custom); 774 setOperationAction(ISD::CTPOP, MVT::v4i32, Custom); 775 setOperationAction(ISD::CTPOP, MVT::v4i16, Custom); 776 setOperationAction(ISD::CTPOP, MVT::v8i16, Custom); 777 setOperationAction(ISD::CTPOP, MVT::v1i64, Custom); 778 setOperationAction(ISD::CTPOP, MVT::v2i64, Custom); 779 780 setOperationAction(ISD::CTLZ, MVT::v1i64, Expand); 781 setOperationAction(ISD::CTLZ, MVT::v2i64, Expand); 782 783 // NEON does not have single instruction CTTZ for vectors. 784 setOperationAction(ISD::CTTZ, MVT::v8i8, Custom); 785 setOperationAction(ISD::CTTZ, MVT::v4i16, Custom); 786 setOperationAction(ISD::CTTZ, MVT::v2i32, Custom); 787 setOperationAction(ISD::CTTZ, MVT::v1i64, Custom); 788 789 setOperationAction(ISD::CTTZ, MVT::v16i8, Custom); 790 setOperationAction(ISD::CTTZ, MVT::v8i16, Custom); 791 setOperationAction(ISD::CTTZ, MVT::v4i32, Custom); 792 setOperationAction(ISD::CTTZ, MVT::v2i64, Custom); 793 794 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::v8i8, Custom); 795 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::v4i16, Custom); 796 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::v2i32, Custom); 797 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::v1i64, Custom); 798 799 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::v16i8, Custom); 800 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::v8i16, Custom); 801 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::v4i32, Custom); 802 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::v2i64, Custom); 803 804 // NEON only has FMA instructions as of VFP4. 805 if (!Subtarget->hasVFP4Base()) { 806 setOperationAction(ISD::FMA, MVT::v2f32, Expand); 807 setOperationAction(ISD::FMA, MVT::v4f32, Expand); 808 } 809 810 setTargetDAGCombine(ISD::INTRINSIC_VOID); 811 setTargetDAGCombine(ISD::INTRINSIC_W_CHAIN); 812 setTargetDAGCombine(ISD::INTRINSIC_WO_CHAIN); 813 setTargetDAGCombine(ISD::SHL); 814 setTargetDAGCombine(ISD::SRL); 815 setTargetDAGCombine(ISD::SRA); 816 setTargetDAGCombine(ISD::SIGN_EXTEND); 817 setTargetDAGCombine(ISD::ZERO_EXTEND); 818 setTargetDAGCombine(ISD::ANY_EXTEND); 819 setTargetDAGCombine(ISD::BUILD_VECTOR); 820 setTargetDAGCombine(ISD::VECTOR_SHUFFLE); 821 setTargetDAGCombine(ISD::INSERT_VECTOR_ELT); 822 setTargetDAGCombine(ISD::STORE); 823 setTargetDAGCombine(ISD::FP_TO_SINT); 824 setTargetDAGCombine(ISD::FP_TO_UINT); 825 setTargetDAGCombine(ISD::FDIV); 826 setTargetDAGCombine(ISD::LOAD); 827 828 // It is legal to extload from v4i8 to v4i16 or v4i32. 829 for (MVT Ty : {MVT::v8i8, MVT::v4i8, MVT::v2i8, MVT::v4i16, MVT::v2i16, 830 MVT::v2i32}) { 831 for (MVT VT : MVT::integer_vector_valuetypes()) { 832 setLoadExtAction(ISD::EXTLOAD, VT, Ty, Legal); 833 setLoadExtAction(ISD::ZEXTLOAD, VT, Ty, Legal); 834 setLoadExtAction(ISD::SEXTLOAD, VT, Ty, Legal); 835 } 836 } 837 } 838 839 if (!Subtarget->hasFP64()) { 840 // When targeting a floating-point unit with only single-precision 841 // operations, f64 is legal for the few double-precision instructions which 842 // are present However, no double-precision operations other than moves, 843 // loads and stores are provided by the hardware. 844 setOperationAction(ISD::FADD, MVT::f64, Expand); 845 setOperationAction(ISD::FSUB, MVT::f64, Expand); 846 setOperationAction(ISD::FMUL, MVT::f64, Expand); 847 setOperationAction(ISD::FMA, MVT::f64, Expand); 848 setOperationAction(ISD::FDIV, MVT::f64, Expand); 849 setOperationAction(ISD::FREM, MVT::f64, Expand); 850 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand); 851 setOperationAction(ISD::FGETSIGN, MVT::f64, Expand); 852 setOperationAction(ISD::FNEG, MVT::f64, Expand); 853 setOperationAction(ISD::FABS, MVT::f64, Expand); 854 setOperationAction(ISD::FSQRT, MVT::f64, Expand); 855 setOperationAction(ISD::FSIN, MVT::f64, Expand); 856 setOperationAction(ISD::FCOS, MVT::f64, Expand); 857 setOperationAction(ISD::FPOW, MVT::f64, Expand); 858 setOperationAction(ISD::FLOG, MVT::f64, Expand); 859 setOperationAction(ISD::FLOG2, MVT::f64, Expand); 860 setOperationAction(ISD::FLOG10, MVT::f64, Expand); 861 setOperationAction(ISD::FEXP, MVT::f64, Expand); 862 setOperationAction(ISD::FEXP2, MVT::f64, Expand); 863 setOperationAction(ISD::FCEIL, MVT::f64, Expand); 864 setOperationAction(ISD::FTRUNC, MVT::f64, Expand); 865 setOperationAction(ISD::FRINT, MVT::f64, Expand); 866 setOperationAction(ISD::FNEARBYINT, MVT::f64, Expand); 867 setOperationAction(ISD::FFLOOR, MVT::f64, Expand); 868 setOperationAction(ISD::SINT_TO_FP, MVT::i32, Custom); 869 setOperationAction(ISD::UINT_TO_FP, MVT::i32, Custom); 870 setOperationAction(ISD::FP_TO_SINT, MVT::i32, Custom); 871 setOperationAction(ISD::FP_TO_UINT, MVT::i32, Custom); 872 setOperationAction(ISD::FP_TO_SINT, MVT::f64, Custom); 873 setOperationAction(ISD::FP_TO_UINT, MVT::f64, Custom); 874 setOperationAction(ISD::FP_ROUND, MVT::f32, Custom); 875 } 876 877 if (!Subtarget->hasFP64() || !Subtarget->hasFPARMv8Base()){ 878 setOperationAction(ISD::FP_EXTEND, MVT::f64, Custom); 879 setOperationAction(ISD::FP_ROUND, MVT::f16, Custom); 880 } 881 882 if (!Subtarget->hasFP16()) 883 setOperationAction(ISD::FP_EXTEND, MVT::f32, Custom); 884 885 if (!Subtarget->hasFP64()) 886 setOperationAction(ISD::FP_ROUND, MVT::f32, Custom); 887 888 computeRegisterProperties(Subtarget->getRegisterInfo()); 889 890 // ARM does not have floating-point extending loads. 891 for (MVT VT : MVT::fp_valuetypes()) { 892 setLoadExtAction(ISD::EXTLOAD, VT, MVT::f32, Expand); 893 setLoadExtAction(ISD::EXTLOAD, VT, MVT::f16, Expand); 894 } 895 896 // ... or truncating stores 897 setTruncStoreAction(MVT::f64, MVT::f32, Expand); 898 setTruncStoreAction(MVT::f32, MVT::f16, Expand); 899 setTruncStoreAction(MVT::f64, MVT::f16, Expand); 900 901 // ARM does not have i1 sign extending load. 902 for (MVT VT : MVT::integer_valuetypes()) 903 setLoadExtAction(ISD::SEXTLOAD, VT, MVT::i1, Promote); 904 905 // ARM supports all 4 flavors of integer indexed load / store. 906 if (!Subtarget->isThumb1Only()) { 907 for (unsigned im = (unsigned)ISD::PRE_INC; 908 im != (unsigned)ISD::LAST_INDEXED_MODE; ++im) { 909 setIndexedLoadAction(im, MVT::i1, Legal); 910 setIndexedLoadAction(im, MVT::i8, Legal); 911 setIndexedLoadAction(im, MVT::i16, Legal); 912 setIndexedLoadAction(im, MVT::i32, Legal); 913 setIndexedStoreAction(im, MVT::i1, Legal); 914 setIndexedStoreAction(im, MVT::i8, Legal); 915 setIndexedStoreAction(im, MVT::i16, Legal); 916 setIndexedStoreAction(im, MVT::i32, Legal); 917 } 918 } else { 919 // Thumb-1 has limited post-inc load/store support - LDM r0!, {r1}. 920 setIndexedLoadAction(ISD::POST_INC, MVT::i32, Legal); 921 setIndexedStoreAction(ISD::POST_INC, MVT::i32, Legal); 922 } 923 924 setOperationAction(ISD::SADDO, MVT::i32, Custom); 925 setOperationAction(ISD::UADDO, MVT::i32, Custom); 926 setOperationAction(ISD::SSUBO, MVT::i32, Custom); 927 setOperationAction(ISD::USUBO, MVT::i32, Custom); 928 929 setOperationAction(ISD::ADDCARRY, MVT::i32, Custom); 930 setOperationAction(ISD::SUBCARRY, MVT::i32, Custom); 931 932 // i64 operation support. 933 setOperationAction(ISD::MUL, MVT::i64, Expand); 934 setOperationAction(ISD::MULHU, MVT::i32, Expand); 935 if (Subtarget->isThumb1Only()) { 936 setOperationAction(ISD::UMUL_LOHI, MVT::i32, Expand); 937 setOperationAction(ISD::SMUL_LOHI, MVT::i32, Expand); 938 } 939 if (Subtarget->isThumb1Only() || !Subtarget->hasV6Ops() 940 || (Subtarget->isThumb2() && !Subtarget->hasDSP())) 941 setOperationAction(ISD::MULHS, MVT::i32, Expand); 942 943 setOperationAction(ISD::SHL_PARTS, MVT::i32, Custom); 944 setOperationAction(ISD::SRA_PARTS, MVT::i32, Custom); 945 setOperationAction(ISD::SRL_PARTS, MVT::i32, Custom); 946 setOperationAction(ISD::SRL, MVT::i64, Custom); 947 setOperationAction(ISD::SRA, MVT::i64, Custom); 948 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::i64, Custom); 949 950 // MVE lowers 64 bit shifts to lsll and lsrl 951 // assuming that ISD::SRL and SRA of i64 are already marked custom 952 if (Subtarget->hasMVEIntegerOps()) 953 setOperationAction(ISD::SHL, MVT::i64, Custom); 954 955 // Expand to __aeabi_l{lsl,lsr,asr} calls for Thumb1. 956 if (Subtarget->isThumb1Only()) { 957 setOperationAction(ISD::SHL_PARTS, MVT::i32, Expand); 958 setOperationAction(ISD::SRA_PARTS, MVT::i32, Expand); 959 setOperationAction(ISD::SRL_PARTS, MVT::i32, Expand); 960 } 961 962 if (!Subtarget->isThumb1Only() && Subtarget->hasV6T2Ops()) 963 setOperationAction(ISD::BITREVERSE, MVT::i32, Legal); 964 965 // ARM does not have ROTL. 966 setOperationAction(ISD::ROTL, MVT::i32, Expand); 967 for (MVT VT : MVT::vector_valuetypes()) { 968 setOperationAction(ISD::ROTL, VT, Expand); 969 setOperationAction(ISD::ROTR, VT, Expand); 970 } 971 setOperationAction(ISD::CTTZ, MVT::i32, Custom); 972 setOperationAction(ISD::CTPOP, MVT::i32, Expand); 973 if (!Subtarget->hasV5TOps() || Subtarget->isThumb1Only()) { 974 setOperationAction(ISD::CTLZ, MVT::i32, Expand); 975 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i32, LibCall); 976 } 977 978 // @llvm.readcyclecounter requires the Performance Monitors extension. 979 // Default to the 0 expansion on unsupported platforms. 980 // FIXME: Technically there are older ARM CPUs that have 981 // implementation-specific ways of obtaining this information. 982 if (Subtarget->hasPerfMon()) 983 setOperationAction(ISD::READCYCLECOUNTER, MVT::i64, Custom); 984 985 // Only ARMv6 has BSWAP. 986 if (!Subtarget->hasV6Ops()) 987 setOperationAction(ISD::BSWAP, MVT::i32, Expand); 988 989 bool hasDivide = Subtarget->isThumb() ? Subtarget->hasDivideInThumbMode() 990 : Subtarget->hasDivideInARMMode(); 991 if (!hasDivide) { 992 // These are expanded into libcalls if the cpu doesn't have HW divider. 993 setOperationAction(ISD::SDIV, MVT::i32, LibCall); 994 setOperationAction(ISD::UDIV, MVT::i32, LibCall); 995 } 996 997 if (Subtarget->isTargetWindows() && !Subtarget->hasDivideInThumbMode()) { 998 setOperationAction(ISD::SDIV, MVT::i32, Custom); 999 setOperationAction(ISD::UDIV, MVT::i32, Custom); 1000 1001 setOperationAction(ISD::SDIV, MVT::i64, Custom); 1002 setOperationAction(ISD::UDIV, MVT::i64, Custom); 1003 } 1004 1005 setOperationAction(ISD::SREM, MVT::i32, Expand); 1006 setOperationAction(ISD::UREM, MVT::i32, Expand); 1007 1008 // Register based DivRem for AEABI (RTABI 4.2) 1009 if (Subtarget->isTargetAEABI() || Subtarget->isTargetAndroid() || 1010 Subtarget->isTargetGNUAEABI() || Subtarget->isTargetMuslAEABI() || 1011 Subtarget->isTargetWindows()) { 1012 setOperationAction(ISD::SREM, MVT::i64, Custom); 1013 setOperationAction(ISD::UREM, MVT::i64, Custom); 1014 HasStandaloneRem = false; 1015 1016 if (Subtarget->isTargetWindows()) { 1017 const struct { 1018 const RTLIB::Libcall Op; 1019 const char * const Name; 1020 const CallingConv::ID CC; 1021 } LibraryCalls[] = { 1022 { RTLIB::SDIVREM_I8, "__rt_sdiv", CallingConv::ARM_AAPCS }, 1023 { RTLIB::SDIVREM_I16, "__rt_sdiv", CallingConv::ARM_AAPCS }, 1024 { RTLIB::SDIVREM_I32, "__rt_sdiv", CallingConv::ARM_AAPCS }, 1025 { RTLIB::SDIVREM_I64, "__rt_sdiv64", CallingConv::ARM_AAPCS }, 1026 1027 { RTLIB::UDIVREM_I8, "__rt_udiv", CallingConv::ARM_AAPCS }, 1028 { RTLIB::UDIVREM_I16, "__rt_udiv", CallingConv::ARM_AAPCS }, 1029 { RTLIB::UDIVREM_I32, "__rt_udiv", CallingConv::ARM_AAPCS }, 1030 { RTLIB::UDIVREM_I64, "__rt_udiv64", CallingConv::ARM_AAPCS }, 1031 }; 1032 1033 for (const auto &LC : LibraryCalls) { 1034 setLibcallName(LC.Op, LC.Name); 1035 setLibcallCallingConv(LC.Op, LC.CC); 1036 } 1037 } else { 1038 const struct { 1039 const RTLIB::Libcall Op; 1040 const char * const Name; 1041 const CallingConv::ID CC; 1042 } LibraryCalls[] = { 1043 { RTLIB::SDIVREM_I8, "__aeabi_idivmod", CallingConv::ARM_AAPCS }, 1044 { RTLIB::SDIVREM_I16, "__aeabi_idivmod", CallingConv::ARM_AAPCS }, 1045 { RTLIB::SDIVREM_I32, "__aeabi_idivmod", CallingConv::ARM_AAPCS }, 1046 { RTLIB::SDIVREM_I64, "__aeabi_ldivmod", CallingConv::ARM_AAPCS }, 1047 1048 { RTLIB::UDIVREM_I8, "__aeabi_uidivmod", CallingConv::ARM_AAPCS }, 1049 { RTLIB::UDIVREM_I16, "__aeabi_uidivmod", CallingConv::ARM_AAPCS }, 1050 { RTLIB::UDIVREM_I32, "__aeabi_uidivmod", CallingConv::ARM_AAPCS }, 1051 { RTLIB::UDIVREM_I64, "__aeabi_uldivmod", CallingConv::ARM_AAPCS }, 1052 }; 1053 1054 for (const auto &LC : LibraryCalls) { 1055 setLibcallName(LC.Op, LC.Name); 1056 setLibcallCallingConv(LC.Op, LC.CC); 1057 } 1058 } 1059 1060 setOperationAction(ISD::SDIVREM, MVT::i32, Custom); 1061 setOperationAction(ISD::UDIVREM, MVT::i32, Custom); 1062 setOperationAction(ISD::SDIVREM, MVT::i64, Custom); 1063 setOperationAction(ISD::UDIVREM, MVT::i64, Custom); 1064 } else { 1065 setOperationAction(ISD::SDIVREM, MVT::i32, Expand); 1066 setOperationAction(ISD::UDIVREM, MVT::i32, Expand); 1067 } 1068 1069 if (Subtarget->isTargetWindows() && Subtarget->getTargetTriple().isOSMSVCRT()) 1070 for (auto &VT : {MVT::f32, MVT::f64}) 1071 setOperationAction(ISD::FPOWI, VT, Custom); 1072 1073 setOperationAction(ISD::GlobalAddress, MVT::i32, Custom); 1074 setOperationAction(ISD::ConstantPool, MVT::i32, Custom); 1075 setOperationAction(ISD::GlobalTLSAddress, MVT::i32, Custom); 1076 setOperationAction(ISD::BlockAddress, MVT::i32, Custom); 1077 1078 setOperationAction(ISD::TRAP, MVT::Other, Legal); 1079 setOperationAction(ISD::DEBUGTRAP, MVT::Other, Legal); 1080 1081 // Use the default implementation. 1082 setOperationAction(ISD::VASTART, MVT::Other, Custom); 1083 setOperationAction(ISD::VAARG, MVT::Other, Expand); 1084 setOperationAction(ISD::VACOPY, MVT::Other, Expand); 1085 setOperationAction(ISD::VAEND, MVT::Other, Expand); 1086 setOperationAction(ISD::STACKSAVE, MVT::Other, Expand); 1087 setOperationAction(ISD::STACKRESTORE, MVT::Other, Expand); 1088 1089 if (Subtarget->isTargetWindows()) 1090 setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i32, Custom); 1091 else 1092 setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i32, Expand); 1093 1094 // ARMv6 Thumb1 (except for CPUs that support dmb / dsb) and earlier use 1095 // the default expansion. 1096 InsertFencesForAtomic = false; 1097 if (Subtarget->hasAnyDataBarrier() && 1098 (!Subtarget->isThumb() || Subtarget->hasV8MBaselineOps())) { 1099 // ATOMIC_FENCE needs custom lowering; the others should have been expanded 1100 // to ldrex/strex loops already. 1101 setOperationAction(ISD::ATOMIC_FENCE, MVT::Other, Custom); 1102 if (!Subtarget->isThumb() || !Subtarget->isMClass()) 1103 setOperationAction(ISD::ATOMIC_CMP_SWAP, MVT::i64, Custom); 1104 1105 // On v8, we have particularly efficient implementations of atomic fences 1106 // if they can be combined with nearby atomic loads and stores. 1107 if (!Subtarget->hasAcquireRelease() || 1108 getTargetMachine().getOptLevel() == 0) { 1109 // Automatically insert fences (dmb ish) around ATOMIC_SWAP etc. 1110 InsertFencesForAtomic = true; 1111 } 1112 } else { 1113 // If there's anything we can use as a barrier, go through custom lowering 1114 // for ATOMIC_FENCE. 1115 // If target has DMB in thumb, Fences can be inserted. 1116 if (Subtarget->hasDataBarrier()) 1117 InsertFencesForAtomic = true; 1118 1119 setOperationAction(ISD::ATOMIC_FENCE, MVT::Other, 1120 Subtarget->hasAnyDataBarrier() ? Custom : Expand); 1121 1122 // Set them all for expansion, which will force libcalls. 1123 setOperationAction(ISD::ATOMIC_CMP_SWAP, MVT::i32, Expand); 1124 setOperationAction(ISD::ATOMIC_SWAP, MVT::i32, Expand); 1125 setOperationAction(ISD::ATOMIC_LOAD_ADD, MVT::i32, Expand); 1126 setOperationAction(ISD::ATOMIC_LOAD_SUB, MVT::i32, Expand); 1127 setOperationAction(ISD::ATOMIC_LOAD_AND, MVT::i32, Expand); 1128 setOperationAction(ISD::ATOMIC_LOAD_OR, MVT::i32, Expand); 1129 setOperationAction(ISD::ATOMIC_LOAD_XOR, MVT::i32, Expand); 1130 setOperationAction(ISD::ATOMIC_LOAD_NAND, MVT::i32, Expand); 1131 setOperationAction(ISD::ATOMIC_LOAD_MIN, MVT::i32, Expand); 1132 setOperationAction(ISD::ATOMIC_LOAD_MAX, MVT::i32, Expand); 1133 setOperationAction(ISD::ATOMIC_LOAD_UMIN, MVT::i32, Expand); 1134 setOperationAction(ISD::ATOMIC_LOAD_UMAX, MVT::i32, Expand); 1135 // Mark ATOMIC_LOAD and ATOMIC_STORE custom so we can handle the 1136 // Unordered/Monotonic case. 1137 if (!InsertFencesForAtomic) { 1138 setOperationAction(ISD::ATOMIC_LOAD, MVT::i32, Custom); 1139 setOperationAction(ISD::ATOMIC_STORE, MVT::i32, Custom); 1140 } 1141 } 1142 1143 setOperationAction(ISD::PREFETCH, MVT::Other, Custom); 1144 1145 // Requires SXTB/SXTH, available on v6 and up in both ARM and Thumb modes. 1146 if (!Subtarget->hasV6Ops()) { 1147 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i16, Expand); 1148 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i8, Expand); 1149 } 1150 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1, Expand); 1151 1152 if (!Subtarget->useSoftFloat() && Subtarget->hasFPRegs() && 1153 !Subtarget->isThumb1Only()) { 1154 // Turn f64->i64 into VMOVRRD, i64 -> f64 to VMOVDRR 1155 // iff target supports vfp2. 1156 setOperationAction(ISD::BITCAST, MVT::i64, Custom); 1157 setOperationAction(ISD::FLT_ROUNDS_, MVT::i32, Custom); 1158 } 1159 1160 // We want to custom lower some of our intrinsics. 1161 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom); 1162 setOperationAction(ISD::EH_SJLJ_SETJMP, MVT::i32, Custom); 1163 setOperationAction(ISD::EH_SJLJ_LONGJMP, MVT::Other, Custom); 1164 setOperationAction(ISD::EH_SJLJ_SETUP_DISPATCH, MVT::Other, Custom); 1165 if (Subtarget->useSjLjEH()) 1166 setLibcallName(RTLIB::UNWIND_RESUME, "_Unwind_SjLj_Resume"); 1167 1168 setOperationAction(ISD::SETCC, MVT::i32, Expand); 1169 setOperationAction(ISD::SETCC, MVT::f32, Expand); 1170 setOperationAction(ISD::SETCC, MVT::f64, Expand); 1171 setOperationAction(ISD::SELECT, MVT::i32, Custom); 1172 setOperationAction(ISD::SELECT, MVT::f32, Custom); 1173 setOperationAction(ISD::SELECT, MVT::f64, Custom); 1174 setOperationAction(ISD::SELECT_CC, MVT::i32, Custom); 1175 setOperationAction(ISD::SELECT_CC, MVT::f32, Custom); 1176 setOperationAction(ISD::SELECT_CC, MVT::f64, Custom); 1177 if (Subtarget->hasFullFP16()) { 1178 setOperationAction(ISD::SETCC, MVT::f16, Expand); 1179 setOperationAction(ISD::SELECT, MVT::f16, Custom); 1180 setOperationAction(ISD::SELECT_CC, MVT::f16, Custom); 1181 } 1182 1183 setOperationAction(ISD::SETCCCARRY, MVT::i32, Custom); 1184 1185 setOperationAction(ISD::BRCOND, MVT::Other, Custom); 1186 setOperationAction(ISD::BR_CC, MVT::i32, Custom); 1187 if (Subtarget->hasFullFP16()) 1188 setOperationAction(ISD::BR_CC, MVT::f16, Custom); 1189 setOperationAction(ISD::BR_CC, MVT::f32, Custom); 1190 setOperationAction(ISD::BR_CC, MVT::f64, Custom); 1191 setOperationAction(ISD::BR_JT, MVT::Other, Custom); 1192 1193 // We don't support sin/cos/fmod/copysign/pow 1194 setOperationAction(ISD::FSIN, MVT::f64, Expand); 1195 setOperationAction(ISD::FSIN, MVT::f32, Expand); 1196 setOperationAction(ISD::FCOS, MVT::f32, Expand); 1197 setOperationAction(ISD::FCOS, MVT::f64, Expand); 1198 setOperationAction(ISD::FSINCOS, MVT::f64, Expand); 1199 setOperationAction(ISD::FSINCOS, MVT::f32, Expand); 1200 setOperationAction(ISD::FREM, MVT::f64, Expand); 1201 setOperationAction(ISD::FREM, MVT::f32, Expand); 1202 if (!Subtarget->useSoftFloat() && Subtarget->hasVFP2Base() && 1203 !Subtarget->isThumb1Only()) { 1204 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Custom); 1205 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom); 1206 } 1207 setOperationAction(ISD::FPOW, MVT::f64, Expand); 1208 setOperationAction(ISD::FPOW, MVT::f32, Expand); 1209 1210 if (!Subtarget->hasVFP4Base()) { 1211 setOperationAction(ISD::FMA, MVT::f64, Expand); 1212 setOperationAction(ISD::FMA, MVT::f32, Expand); 1213 } 1214 1215 // Various VFP goodness 1216 if (!Subtarget->useSoftFloat() && !Subtarget->isThumb1Only()) { 1217 // FP-ARMv8 adds f64 <-> f16 conversion. Before that it should be expanded. 1218 if (!Subtarget->hasFPARMv8Base() || !Subtarget->hasFP64()) { 1219 setOperationAction(ISD::FP16_TO_FP, MVT::f64, Expand); 1220 setOperationAction(ISD::FP_TO_FP16, MVT::f64, Expand); 1221 } 1222 1223 // fp16 is a special v7 extension that adds f16 <-> f32 conversions. 1224 if (!Subtarget->hasFP16()) { 1225 setOperationAction(ISD::FP16_TO_FP, MVT::f32, Expand); 1226 setOperationAction(ISD::FP_TO_FP16, MVT::f32, Expand); 1227 } 1228 } 1229 1230 // Use __sincos_stret if available. 1231 if (getLibcallName(RTLIB::SINCOS_STRET_F32) != nullptr && 1232 getLibcallName(RTLIB::SINCOS_STRET_F64) != nullptr) { 1233 setOperationAction(ISD::FSINCOS, MVT::f64, Custom); 1234 setOperationAction(ISD::FSINCOS, MVT::f32, Custom); 1235 } 1236 1237 // FP-ARMv8 implements a lot of rounding-like FP operations. 1238 if (Subtarget->hasFPARMv8Base()) { 1239 setOperationAction(ISD::FFLOOR, MVT::f32, Legal); 1240 setOperationAction(ISD::FCEIL, MVT::f32, Legal); 1241 setOperationAction(ISD::FROUND, MVT::f32, Legal); 1242 setOperationAction(ISD::FTRUNC, MVT::f32, Legal); 1243 setOperationAction(ISD::FNEARBYINT, MVT::f32, Legal); 1244 setOperationAction(ISD::FRINT, MVT::f32, Legal); 1245 setOperationAction(ISD::FMINNUM, MVT::f32, Legal); 1246 setOperationAction(ISD::FMAXNUM, MVT::f32, Legal); 1247 setOperationAction(ISD::FMINNUM, MVT::v2f32, Legal); 1248 setOperationAction(ISD::FMAXNUM, MVT::v2f32, Legal); 1249 setOperationAction(ISD::FMINNUM, MVT::v4f32, Legal); 1250 setOperationAction(ISD::FMAXNUM, MVT::v4f32, Legal); 1251 1252 if (Subtarget->hasFP64()) { 1253 setOperationAction(ISD::FFLOOR, MVT::f64, Legal); 1254 setOperationAction(ISD::FCEIL, MVT::f64, Legal); 1255 setOperationAction(ISD::FROUND, MVT::f64, Legal); 1256 setOperationAction(ISD::FTRUNC, MVT::f64, Legal); 1257 setOperationAction(ISD::FNEARBYINT, MVT::f64, Legal); 1258 setOperationAction(ISD::FRINT, MVT::f64, Legal); 1259 setOperationAction(ISD::FMINNUM, MVT::f64, Legal); 1260 setOperationAction(ISD::FMAXNUM, MVT::f64, Legal); 1261 } 1262 } 1263 1264 // FP16 often need to be promoted to call lib functions 1265 if (Subtarget->hasFullFP16()) { 1266 setOperationAction(ISD::FREM, MVT::f16, Promote); 1267 setOperationAction(ISD::FCOPYSIGN, MVT::f16, Expand); 1268 setOperationAction(ISD::FSIN, MVT::f16, Promote); 1269 setOperationAction(ISD::FCOS, MVT::f16, Promote); 1270 setOperationAction(ISD::FSINCOS, MVT::f16, Promote); 1271 setOperationAction(ISD::FPOWI, MVT::f16, Promote); 1272 setOperationAction(ISD::FPOW, MVT::f16, Promote); 1273 setOperationAction(ISD::FEXP, MVT::f16, Promote); 1274 setOperationAction(ISD::FEXP2, MVT::f16, Promote); 1275 setOperationAction(ISD::FLOG, MVT::f16, Promote); 1276 setOperationAction(ISD::FLOG10, MVT::f16, Promote); 1277 setOperationAction(ISD::FLOG2, MVT::f16, Promote); 1278 1279 setOperationAction(ISD::FROUND, MVT::f16, Legal); 1280 } 1281 1282 if (Subtarget->hasNEON()) { 1283 // vmin and vmax aren't available in a scalar form, so we use 1284 // a NEON instruction with an undef lane instead. 1285 setOperationAction(ISD::FMINIMUM, MVT::f16, Legal); 1286 setOperationAction(ISD::FMAXIMUM, MVT::f16, Legal); 1287 setOperationAction(ISD::FMINIMUM, MVT::f32, Legal); 1288 setOperationAction(ISD::FMAXIMUM, MVT::f32, Legal); 1289 setOperationAction(ISD::FMINIMUM, MVT::v2f32, Legal); 1290 setOperationAction(ISD::FMAXIMUM, MVT::v2f32, Legal); 1291 setOperationAction(ISD::FMINIMUM, MVT::v4f32, Legal); 1292 setOperationAction(ISD::FMAXIMUM, MVT::v4f32, Legal); 1293 1294 if (Subtarget->hasFullFP16()) { 1295 setOperationAction(ISD::FMINNUM, MVT::v4f16, Legal); 1296 setOperationAction(ISD::FMAXNUM, MVT::v4f16, Legal); 1297 setOperationAction(ISD::FMINNUM, MVT::v8f16, Legal); 1298 setOperationAction(ISD::FMAXNUM, MVT::v8f16, Legal); 1299 1300 setOperationAction(ISD::FMINIMUM, MVT::v4f16, Legal); 1301 setOperationAction(ISD::FMAXIMUM, MVT::v4f16, Legal); 1302 setOperationAction(ISD::FMINIMUM, MVT::v8f16, Legal); 1303 setOperationAction(ISD::FMAXIMUM, MVT::v8f16, Legal); 1304 } 1305 } 1306 1307 // We have target-specific dag combine patterns for the following nodes: 1308 // ARMISD::VMOVRRD - No need to call setTargetDAGCombine 1309 setTargetDAGCombine(ISD::ADD); 1310 setTargetDAGCombine(ISD::SUB); 1311 setTargetDAGCombine(ISD::MUL); 1312 setTargetDAGCombine(ISD::AND); 1313 setTargetDAGCombine(ISD::OR); 1314 setTargetDAGCombine(ISD::XOR); 1315 1316 if (Subtarget->hasV6Ops()) 1317 setTargetDAGCombine(ISD::SRL); 1318 if (Subtarget->isThumb1Only()) 1319 setTargetDAGCombine(ISD::SHL); 1320 1321 setStackPointerRegisterToSaveRestore(ARM::SP); 1322 1323 if (Subtarget->useSoftFloat() || Subtarget->isThumb1Only() || 1324 !Subtarget->hasVFP2Base() || Subtarget->hasMinSize()) 1325 setSchedulingPreference(Sched::RegPressure); 1326 else 1327 setSchedulingPreference(Sched::Hybrid); 1328 1329 //// temporary - rewrite interface to use type 1330 MaxStoresPerMemset = 8; 1331 MaxStoresPerMemsetOptSize = 4; 1332 MaxStoresPerMemcpy = 4; // For @llvm.memcpy -> sequence of stores 1333 MaxStoresPerMemcpyOptSize = 2; 1334 MaxStoresPerMemmove = 4; // For @llvm.memmove -> sequence of stores 1335 MaxStoresPerMemmoveOptSize = 2; 1336 1337 // On ARM arguments smaller than 4 bytes are extended, so all arguments 1338 // are at least 4 bytes aligned. 1339 setMinStackArgumentAlignment(4); 1340 1341 // Prefer likely predicted branches to selects on out-of-order cores. 1342 PredictableSelectIsExpensive = Subtarget->getSchedModel().isOutOfOrder(); 1343 1344 setPrefLoopAlignment(Subtarget->getPrefLoopAlignment()); 1345 1346 setMinFunctionAlignment(Subtarget->isThumb() ? 1 : 2); 1347 1348 if (Subtarget->isThumb() || Subtarget->isThumb2()) 1349 setTargetDAGCombine(ISD::ABS); 1350 } 1351 1352 bool ARMTargetLowering::useSoftFloat() const { 1353 return Subtarget->useSoftFloat(); 1354 } 1355 1356 // FIXME: It might make sense to define the representative register class as the 1357 // nearest super-register that has a non-null superset. For example, DPR_VFP2 is 1358 // a super-register of SPR, and DPR is a superset if DPR_VFP2. Consequently, 1359 // SPR's representative would be DPR_VFP2. This should work well if register 1360 // pressure tracking were modified such that a register use would increment the 1361 // pressure of the register class's representative and all of it's super 1362 // classes' representatives transitively. We have not implemented this because 1363 // of the difficulty prior to coalescing of modeling operand register classes 1364 // due to the common occurrence of cross class copies and subregister insertions 1365 // and extractions. 1366 std::pair<const TargetRegisterClass *, uint8_t> 1367 ARMTargetLowering::findRepresentativeClass(const TargetRegisterInfo *TRI, 1368 MVT VT) const { 1369 const TargetRegisterClass *RRC = nullptr; 1370 uint8_t Cost = 1; 1371 switch (VT.SimpleTy) { 1372 default: 1373 return TargetLowering::findRepresentativeClass(TRI, VT); 1374 // Use DPR as representative register class for all floating point 1375 // and vector types. Since there are 32 SPR registers and 32 DPR registers so 1376 // the cost is 1 for both f32 and f64. 1377 case MVT::f32: case MVT::f64: case MVT::v8i8: case MVT::v4i16: 1378 case MVT::v2i32: case MVT::v1i64: case MVT::v2f32: 1379 RRC = &ARM::DPRRegClass; 1380 // When NEON is used for SP, only half of the register file is available 1381 // because operations that define both SP and DP results will be constrained 1382 // to the VFP2 class (D0-D15). We currently model this constraint prior to 1383 // coalescing by double-counting the SP regs. See the FIXME above. 1384 if (Subtarget->useNEONForSinglePrecisionFP()) 1385 Cost = 2; 1386 break; 1387 case MVT::v16i8: case MVT::v8i16: case MVT::v4i32: case MVT::v2i64: 1388 case MVT::v4f32: case MVT::v2f64: 1389 RRC = &ARM::DPRRegClass; 1390 Cost = 2; 1391 break; 1392 case MVT::v4i64: 1393 RRC = &ARM::DPRRegClass; 1394 Cost = 4; 1395 break; 1396 case MVT::v8i64: 1397 RRC = &ARM::DPRRegClass; 1398 Cost = 8; 1399 break; 1400 } 1401 return std::make_pair(RRC, Cost); 1402 } 1403 1404 const char *ARMTargetLowering::getTargetNodeName(unsigned Opcode) const { 1405 switch ((ARMISD::NodeType)Opcode) { 1406 case ARMISD::FIRST_NUMBER: break; 1407 case ARMISD::Wrapper: return "ARMISD::Wrapper"; 1408 case ARMISD::WrapperPIC: return "ARMISD::WrapperPIC"; 1409 case ARMISD::WrapperJT: return "ARMISD::WrapperJT"; 1410 case ARMISD::COPY_STRUCT_BYVAL: return "ARMISD::COPY_STRUCT_BYVAL"; 1411 case ARMISD::CALL: return "ARMISD::CALL"; 1412 case ARMISD::CALL_PRED: return "ARMISD::CALL_PRED"; 1413 case ARMISD::CALL_NOLINK: return "ARMISD::CALL_NOLINK"; 1414 case ARMISD::BRCOND: return "ARMISD::BRCOND"; 1415 case ARMISD::BR_JT: return "ARMISD::BR_JT"; 1416 case ARMISD::BR2_JT: return "ARMISD::BR2_JT"; 1417 case ARMISD::RET_FLAG: return "ARMISD::RET_FLAG"; 1418 case ARMISD::INTRET_FLAG: return "ARMISD::INTRET_FLAG"; 1419 case ARMISD::PIC_ADD: return "ARMISD::PIC_ADD"; 1420 case ARMISD::CMP: return "ARMISD::CMP"; 1421 case ARMISD::CMN: return "ARMISD::CMN"; 1422 case ARMISD::CMPZ: return "ARMISD::CMPZ"; 1423 case ARMISD::CMPFP: return "ARMISD::CMPFP"; 1424 case ARMISD::CMPFPw0: return "ARMISD::CMPFPw0"; 1425 case ARMISD::BCC_i64: return "ARMISD::BCC_i64"; 1426 case ARMISD::FMSTAT: return "ARMISD::FMSTAT"; 1427 1428 case ARMISD::CMOV: return "ARMISD::CMOV"; 1429 case ARMISD::SUBS: return "ARMISD::SUBS"; 1430 1431 case ARMISD::SSAT: return "ARMISD::SSAT"; 1432 case ARMISD::USAT: return "ARMISD::USAT"; 1433 1434 case ARMISD::ASRL: return "ARMISD::ASRL"; 1435 case ARMISD::LSRL: return "ARMISD::LSRL"; 1436 case ARMISD::LSLL: return "ARMISD::LSLL"; 1437 1438 case ARMISD::SRL_FLAG: return "ARMISD::SRL_FLAG"; 1439 case ARMISD::SRA_FLAG: return "ARMISD::SRA_FLAG"; 1440 case ARMISD::RRX: return "ARMISD::RRX"; 1441 1442 case ARMISD::ADDC: return "ARMISD::ADDC"; 1443 case ARMISD::ADDE: return "ARMISD::ADDE"; 1444 case ARMISD::SUBC: return "ARMISD::SUBC"; 1445 case ARMISD::SUBE: return "ARMISD::SUBE"; 1446 1447 case ARMISD::VMOVRRD: return "ARMISD::VMOVRRD"; 1448 case ARMISD::VMOVDRR: return "ARMISD::VMOVDRR"; 1449 case ARMISD::VMOVhr: return "ARMISD::VMOVhr"; 1450 case ARMISD::VMOVrh: return "ARMISD::VMOVrh"; 1451 case ARMISD::VMOVSR: return "ARMISD::VMOVSR"; 1452 1453 case ARMISD::EH_SJLJ_SETJMP: return "ARMISD::EH_SJLJ_SETJMP"; 1454 case ARMISD::EH_SJLJ_LONGJMP: return "ARMISD::EH_SJLJ_LONGJMP"; 1455 case ARMISD::EH_SJLJ_SETUP_DISPATCH: return "ARMISD::EH_SJLJ_SETUP_DISPATCH"; 1456 1457 case ARMISD::TC_RETURN: return "ARMISD::TC_RETURN"; 1458 1459 case ARMISD::THREAD_POINTER:return "ARMISD::THREAD_POINTER"; 1460 1461 case ARMISD::DYN_ALLOC: return "ARMISD::DYN_ALLOC"; 1462 1463 case ARMISD::MEMBARRIER_MCR: return "ARMISD::MEMBARRIER_MCR"; 1464 1465 case ARMISD::PRELOAD: return "ARMISD::PRELOAD"; 1466 1467 case ARMISD::WIN__CHKSTK: return "ARMISD::WIN__CHKSTK"; 1468 case ARMISD::WIN__DBZCHK: return "ARMISD::WIN__DBZCHK"; 1469 1470 case ARMISD::VCEQ: return "ARMISD::VCEQ"; 1471 case ARMISD::VCEQZ: return "ARMISD::VCEQZ"; 1472 case ARMISD::VCGE: return "ARMISD::VCGE"; 1473 case ARMISD::VCGEZ: return "ARMISD::VCGEZ"; 1474 case ARMISD::VCLEZ: return "ARMISD::VCLEZ"; 1475 case ARMISD::VCGEU: return "ARMISD::VCGEU"; 1476 case ARMISD::VCGT: return "ARMISD::VCGT"; 1477 case ARMISD::VCGTZ: return "ARMISD::VCGTZ"; 1478 case ARMISD::VCLTZ: return "ARMISD::VCLTZ"; 1479 case ARMISD::VCGTU: return "ARMISD::VCGTU"; 1480 case ARMISD::VTST: return "ARMISD::VTST"; 1481 1482 case ARMISD::VSHL: return "ARMISD::VSHL"; 1483 case ARMISD::VSHRs: return "ARMISD::VSHRs"; 1484 case ARMISD::VSHRu: return "ARMISD::VSHRu"; 1485 case ARMISD::VRSHRs: return "ARMISD::VRSHRs"; 1486 case ARMISD::VRSHRu: return "ARMISD::VRSHRu"; 1487 case ARMISD::VRSHRN: return "ARMISD::VRSHRN"; 1488 case ARMISD::VQSHLs: return "ARMISD::VQSHLs"; 1489 case ARMISD::VQSHLu: return "ARMISD::VQSHLu"; 1490 case ARMISD::VQSHLsu: return "ARMISD::VQSHLsu"; 1491 case ARMISD::VQSHRNs: return "ARMISD::VQSHRNs"; 1492 case ARMISD::VQSHRNu: return "ARMISD::VQSHRNu"; 1493 case ARMISD::VQSHRNsu: return "ARMISD::VQSHRNsu"; 1494 case ARMISD::VQRSHRNs: return "ARMISD::VQRSHRNs"; 1495 case ARMISD::VQRSHRNu: return "ARMISD::VQRSHRNu"; 1496 case ARMISD::VQRSHRNsu: return "ARMISD::VQRSHRNsu"; 1497 case ARMISD::VSLI: return "ARMISD::VSLI"; 1498 case ARMISD::VSRI: return "ARMISD::VSRI"; 1499 case ARMISD::VGETLANEu: return "ARMISD::VGETLANEu"; 1500 case ARMISD::VGETLANEs: return "ARMISD::VGETLANEs"; 1501 case ARMISD::VMOVIMM: return "ARMISD::VMOVIMM"; 1502 case ARMISD::VMVNIMM: return "ARMISD::VMVNIMM"; 1503 case ARMISD::VMOVFPIMM: return "ARMISD::VMOVFPIMM"; 1504 case ARMISD::VDUP: return "ARMISD::VDUP"; 1505 case ARMISD::VDUPLANE: return "ARMISD::VDUPLANE"; 1506 case ARMISD::VEXT: return "ARMISD::VEXT"; 1507 case ARMISD::VREV64: return "ARMISD::VREV64"; 1508 case ARMISD::VREV32: return "ARMISD::VREV32"; 1509 case ARMISD::VREV16: return "ARMISD::VREV16"; 1510 case ARMISD::VZIP: return "ARMISD::VZIP"; 1511 case ARMISD::VUZP: return "ARMISD::VUZP"; 1512 case ARMISD::VTRN: return "ARMISD::VTRN"; 1513 case ARMISD::VTBL1: return "ARMISD::VTBL1"; 1514 case ARMISD::VTBL2: return "ARMISD::VTBL2"; 1515 case ARMISD::VMULLs: return "ARMISD::VMULLs"; 1516 case ARMISD::VMULLu: return "ARMISD::VMULLu"; 1517 case ARMISD::UMAAL: return "ARMISD::UMAAL"; 1518 case ARMISD::UMLAL: return "ARMISD::UMLAL"; 1519 case ARMISD::SMLAL: return "ARMISD::SMLAL"; 1520 case ARMISD::SMLALBB: return "ARMISD::SMLALBB"; 1521 case ARMISD::SMLALBT: return "ARMISD::SMLALBT"; 1522 case ARMISD::SMLALTB: return "ARMISD::SMLALTB"; 1523 case ARMISD::SMLALTT: return "ARMISD::SMLALTT"; 1524 case ARMISD::SMULWB: return "ARMISD::SMULWB"; 1525 case ARMISD::SMULWT: return "ARMISD::SMULWT"; 1526 case ARMISD::SMLALD: return "ARMISD::SMLALD"; 1527 case ARMISD::SMLALDX: return "ARMISD::SMLALDX"; 1528 case ARMISD::SMLSLD: return "ARMISD::SMLSLD"; 1529 case ARMISD::SMLSLDX: return "ARMISD::SMLSLDX"; 1530 case ARMISD::SMMLAR: return "ARMISD::SMMLAR"; 1531 case ARMISD::SMMLSR: return "ARMISD::SMMLSR"; 1532 case ARMISD::BUILD_VECTOR: return "ARMISD::BUILD_VECTOR"; 1533 case ARMISD::BFI: return "ARMISD::BFI"; 1534 case ARMISD::VORRIMM: return "ARMISD::VORRIMM"; 1535 case ARMISD::VBICIMM: return "ARMISD::VBICIMM"; 1536 case ARMISD::VBSL: return "ARMISD::VBSL"; 1537 case ARMISD::MEMCPY: return "ARMISD::MEMCPY"; 1538 case ARMISD::VLD1DUP: return "ARMISD::VLD1DUP"; 1539 case ARMISD::VLD2DUP: return "ARMISD::VLD2DUP"; 1540 case ARMISD::VLD3DUP: return "ARMISD::VLD3DUP"; 1541 case ARMISD::VLD4DUP: return "ARMISD::VLD4DUP"; 1542 case ARMISD::VLD1_UPD: return "ARMISD::VLD1_UPD"; 1543 case ARMISD::VLD2_UPD: return "ARMISD::VLD2_UPD"; 1544 case ARMISD::VLD3_UPD: return "ARMISD::VLD3_UPD"; 1545 case ARMISD::VLD4_UPD: return "ARMISD::VLD4_UPD"; 1546 case ARMISD::VLD2LN_UPD: return "ARMISD::VLD2LN_UPD"; 1547 case ARMISD::VLD3LN_UPD: return "ARMISD::VLD3LN_UPD"; 1548 case ARMISD::VLD4LN_UPD: return "ARMISD::VLD4LN_UPD"; 1549 case ARMISD::VLD1DUP_UPD: return "ARMISD::VLD1DUP_UPD"; 1550 case ARMISD::VLD2DUP_UPD: return "ARMISD::VLD2DUP_UPD"; 1551 case ARMISD::VLD3DUP_UPD: return "ARMISD::VLD3DUP_UPD"; 1552 case ARMISD::VLD4DUP_UPD: return "ARMISD::VLD4DUP_UPD"; 1553 case ARMISD::VST1_UPD: return "ARMISD::VST1_UPD"; 1554 case ARMISD::VST2_UPD: return "ARMISD::VST2_UPD"; 1555 case ARMISD::VST3_UPD: return "ARMISD::VST3_UPD"; 1556 case ARMISD::VST4_UPD: return "ARMISD::VST4_UPD"; 1557 case ARMISD::VST2LN_UPD: return "ARMISD::VST2LN_UPD"; 1558 case ARMISD::VST3LN_UPD: return "ARMISD::VST3LN_UPD"; 1559 case ARMISD::VST4LN_UPD: return "ARMISD::VST4LN_UPD"; 1560 case ARMISD::WLS: return "ARMISD::WLS"; 1561 } 1562 return nullptr; 1563 } 1564 1565 EVT ARMTargetLowering::getSetCCResultType(const DataLayout &DL, LLVMContext &, 1566 EVT VT) const { 1567 if (!VT.isVector()) 1568 return getPointerTy(DL); 1569 return VT.changeVectorElementTypeToInteger(); 1570 } 1571 1572 /// getRegClassFor - Return the register class that should be used for the 1573 /// specified value type. 1574 const TargetRegisterClass * 1575 ARMTargetLowering::getRegClassFor(MVT VT, bool isDivergent) const { 1576 (void)isDivergent; 1577 // Map v4i64 to QQ registers but do not make the type legal. Similarly map 1578 // v8i64 to QQQQ registers. v4i64 and v8i64 are only used for REG_SEQUENCE to 1579 // load / store 4 to 8 consecutive NEON D registers, or 2 to 4 consecutive 1580 // MVE Q registers. 1581 if (Subtarget->hasNEON() || Subtarget->hasMVEIntegerOps()) { 1582 if (VT == MVT::v4i64) 1583 return &ARM::QQPRRegClass; 1584 if (VT == MVT::v8i64) 1585 return &ARM::QQQQPRRegClass; 1586 } 1587 return TargetLowering::getRegClassFor(VT); 1588 } 1589 1590 // memcpy, and other memory intrinsics, typically tries to use LDM/STM if the 1591 // source/dest is aligned and the copy size is large enough. We therefore want 1592 // to align such objects passed to memory intrinsics. 1593 bool ARMTargetLowering::shouldAlignPointerArgs(CallInst *CI, unsigned &MinSize, 1594 unsigned &PrefAlign) const { 1595 if (!isa<MemIntrinsic>(CI)) 1596 return false; 1597 MinSize = 8; 1598 // On ARM11 onwards (excluding M class) 8-byte aligned LDM is typically 1 1599 // cycle faster than 4-byte aligned LDM. 1600 PrefAlign = (Subtarget->hasV6Ops() && !Subtarget->isMClass() ? 8 : 4); 1601 return true; 1602 } 1603 1604 // Create a fast isel object. 1605 FastISel * 1606 ARMTargetLowering::createFastISel(FunctionLoweringInfo &funcInfo, 1607 const TargetLibraryInfo *libInfo) const { 1608 return ARM::createFastISel(funcInfo, libInfo); 1609 } 1610 1611 Sched::Preference ARMTargetLowering::getSchedulingPreference(SDNode *N) const { 1612 unsigned NumVals = N->getNumValues(); 1613 if (!NumVals) 1614 return Sched::RegPressure; 1615 1616 for (unsigned i = 0; i != NumVals; ++i) { 1617 EVT VT = N->getValueType(i); 1618 if (VT == MVT::Glue || VT == MVT::Other) 1619 continue; 1620 if (VT.isFloatingPoint() || VT.isVector()) 1621 return Sched::ILP; 1622 } 1623 1624 if (!N->isMachineOpcode()) 1625 return Sched::RegPressure; 1626 1627 // Load are scheduled for latency even if there instruction itinerary 1628 // is not available. 1629 const TargetInstrInfo *TII = Subtarget->getInstrInfo(); 1630 const MCInstrDesc &MCID = TII->get(N->getMachineOpcode()); 1631 1632 if (MCID.getNumDefs() == 0) 1633 return Sched::RegPressure; 1634 if (!Itins->isEmpty() && 1635 Itins->getOperandCycle(MCID.getSchedClass(), 0) > 2) 1636 return Sched::ILP; 1637 1638 return Sched::RegPressure; 1639 } 1640 1641 //===----------------------------------------------------------------------===// 1642 // Lowering Code 1643 //===----------------------------------------------------------------------===// 1644 1645 static bool isSRL16(const SDValue &Op) { 1646 if (Op.getOpcode() != ISD::SRL) 1647 return false; 1648 if (auto Const = dyn_cast<ConstantSDNode>(Op.getOperand(1))) 1649 return Const->getZExtValue() == 16; 1650 return false; 1651 } 1652 1653 static bool isSRA16(const SDValue &Op) { 1654 if (Op.getOpcode() != ISD::SRA) 1655 return false; 1656 if (auto Const = dyn_cast<ConstantSDNode>(Op.getOperand(1))) 1657 return Const->getZExtValue() == 16; 1658 return false; 1659 } 1660 1661 static bool isSHL16(const SDValue &Op) { 1662 if (Op.getOpcode() != ISD::SHL) 1663 return false; 1664 if (auto Const = dyn_cast<ConstantSDNode>(Op.getOperand(1))) 1665 return Const->getZExtValue() == 16; 1666 return false; 1667 } 1668 1669 // Check for a signed 16-bit value. We special case SRA because it makes it 1670 // more simple when also looking for SRAs that aren't sign extending a 1671 // smaller value. Without the check, we'd need to take extra care with 1672 // checking order for some operations. 1673 static bool isS16(const SDValue &Op, SelectionDAG &DAG) { 1674 if (isSRA16(Op)) 1675 return isSHL16(Op.getOperand(0)); 1676 return DAG.ComputeNumSignBits(Op) == 17; 1677 } 1678 1679 /// IntCCToARMCC - Convert a DAG integer condition code to an ARM CC 1680 static ARMCC::CondCodes IntCCToARMCC(ISD::CondCode CC) { 1681 switch (CC) { 1682 default: llvm_unreachable("Unknown condition code!"); 1683 case ISD::SETNE: return ARMCC::NE; 1684 case ISD::SETEQ: return ARMCC::EQ; 1685 case ISD::SETGT: return ARMCC::GT; 1686 case ISD::SETGE: return ARMCC::GE; 1687 case ISD::SETLT: return ARMCC::LT; 1688 case ISD::SETLE: return ARMCC::LE; 1689 case ISD::SETUGT: return ARMCC::HI; 1690 case ISD::SETUGE: return ARMCC::HS; 1691 case ISD::SETULT: return ARMCC::LO; 1692 case ISD::SETULE: return ARMCC::LS; 1693 } 1694 } 1695 1696 /// FPCCToARMCC - Convert a DAG fp condition code to an ARM CC. 1697 static void FPCCToARMCC(ISD::CondCode CC, ARMCC::CondCodes &CondCode, 1698 ARMCC::CondCodes &CondCode2, bool &InvalidOnQNaN) { 1699 CondCode2 = ARMCC::AL; 1700 InvalidOnQNaN = true; 1701 switch (CC) { 1702 default: llvm_unreachable("Unknown FP condition!"); 1703 case ISD::SETEQ: 1704 case ISD::SETOEQ: 1705 CondCode = ARMCC::EQ; 1706 InvalidOnQNaN = false; 1707 break; 1708 case ISD::SETGT: 1709 case ISD::SETOGT: CondCode = ARMCC::GT; break; 1710 case ISD::SETGE: 1711 case ISD::SETOGE: CondCode = ARMCC::GE; break; 1712 case ISD::SETOLT: CondCode = ARMCC::MI; break; 1713 case ISD::SETOLE: CondCode = ARMCC::LS; break; 1714 case ISD::SETONE: 1715 CondCode = ARMCC::MI; 1716 CondCode2 = ARMCC::GT; 1717 InvalidOnQNaN = false; 1718 break; 1719 case ISD::SETO: CondCode = ARMCC::VC; break; 1720 case ISD::SETUO: CondCode = ARMCC::VS; break; 1721 case ISD::SETUEQ: 1722 CondCode = ARMCC::EQ; 1723 CondCode2 = ARMCC::VS; 1724 InvalidOnQNaN = false; 1725 break; 1726 case ISD::SETUGT: CondCode = ARMCC::HI; break; 1727 case ISD::SETUGE: CondCode = ARMCC::PL; break; 1728 case ISD::SETLT: 1729 case ISD::SETULT: CondCode = ARMCC::LT; break; 1730 case ISD::SETLE: 1731 case ISD::SETULE: CondCode = ARMCC::LE; break; 1732 case ISD::SETNE: 1733 case ISD::SETUNE: 1734 CondCode = ARMCC::NE; 1735 InvalidOnQNaN = false; 1736 break; 1737 } 1738 } 1739 1740 //===----------------------------------------------------------------------===// 1741 // Calling Convention Implementation 1742 //===----------------------------------------------------------------------===// 1743 1744 /// getEffectiveCallingConv - Get the effective calling convention, taking into 1745 /// account presence of floating point hardware and calling convention 1746 /// limitations, such as support for variadic functions. 1747 CallingConv::ID 1748 ARMTargetLowering::getEffectiveCallingConv(CallingConv::ID CC, 1749 bool isVarArg) const { 1750 switch (CC) { 1751 default: 1752 report_fatal_error("Unsupported calling convention"); 1753 case CallingConv::ARM_AAPCS: 1754 case CallingConv::ARM_APCS: 1755 case CallingConv::GHC: 1756 return CC; 1757 case CallingConv::PreserveMost: 1758 return CallingConv::PreserveMost; 1759 case CallingConv::ARM_AAPCS_VFP: 1760 case CallingConv::Swift: 1761 return isVarArg ? CallingConv::ARM_AAPCS : CallingConv::ARM_AAPCS_VFP; 1762 case CallingConv::C: 1763 if (!Subtarget->isAAPCS_ABI()) 1764 return CallingConv::ARM_APCS; 1765 else if (Subtarget->hasVFP2Base() && !Subtarget->isThumb1Only() && 1766 getTargetMachine().Options.FloatABIType == FloatABI::Hard && 1767 !isVarArg) 1768 return CallingConv::ARM_AAPCS_VFP; 1769 else 1770 return CallingConv::ARM_AAPCS; 1771 case CallingConv::Fast: 1772 case CallingConv::CXX_FAST_TLS: 1773 if (!Subtarget->isAAPCS_ABI()) { 1774 if (Subtarget->hasVFP2Base() && !Subtarget->isThumb1Only() && !isVarArg) 1775 return CallingConv::Fast; 1776 return CallingConv::ARM_APCS; 1777 } else if (Subtarget->hasVFP2Base() && 1778 !Subtarget->isThumb1Only() && !isVarArg) 1779 return CallingConv::ARM_AAPCS_VFP; 1780 else 1781 return CallingConv::ARM_AAPCS; 1782 } 1783 } 1784 1785 CCAssignFn *ARMTargetLowering::CCAssignFnForCall(CallingConv::ID CC, 1786 bool isVarArg) const { 1787 return CCAssignFnForNode(CC, false, isVarArg); 1788 } 1789 1790 CCAssignFn *ARMTargetLowering::CCAssignFnForReturn(CallingConv::ID CC, 1791 bool isVarArg) const { 1792 return CCAssignFnForNode(CC, true, isVarArg); 1793 } 1794 1795 /// CCAssignFnForNode - Selects the correct CCAssignFn for the given 1796 /// CallingConvention. 1797 CCAssignFn *ARMTargetLowering::CCAssignFnForNode(CallingConv::ID CC, 1798 bool Return, 1799 bool isVarArg) const { 1800 switch (getEffectiveCallingConv(CC, isVarArg)) { 1801 default: 1802 report_fatal_error("Unsupported calling convention"); 1803 case CallingConv::ARM_APCS: 1804 return (Return ? RetCC_ARM_APCS : CC_ARM_APCS); 1805 case CallingConv::ARM_AAPCS: 1806 return (Return ? RetCC_ARM_AAPCS : CC_ARM_AAPCS); 1807 case CallingConv::ARM_AAPCS_VFP: 1808 return (Return ? RetCC_ARM_AAPCS_VFP : CC_ARM_AAPCS_VFP); 1809 case CallingConv::Fast: 1810 return (Return ? RetFastCC_ARM_APCS : FastCC_ARM_APCS); 1811 case CallingConv::GHC: 1812 return (Return ? RetCC_ARM_APCS : CC_ARM_APCS_GHC); 1813 case CallingConv::PreserveMost: 1814 return (Return ? RetCC_ARM_AAPCS : CC_ARM_AAPCS); 1815 } 1816 } 1817 1818 /// LowerCallResult - Lower the result values of a call into the 1819 /// appropriate copies out of appropriate physical registers. 1820 SDValue ARMTargetLowering::LowerCallResult( 1821 SDValue Chain, SDValue InFlag, CallingConv::ID CallConv, bool isVarArg, 1822 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl, 1823 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals, bool isThisReturn, 1824 SDValue ThisVal) const { 1825 // Assign locations to each value returned by this call. 1826 SmallVector<CCValAssign, 16> RVLocs; 1827 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs, 1828 *DAG.getContext()); 1829 CCInfo.AnalyzeCallResult(Ins, CCAssignFnForReturn(CallConv, isVarArg)); 1830 1831 // Copy all of the result registers out of their specified physreg. 1832 for (unsigned i = 0; i != RVLocs.size(); ++i) { 1833 CCValAssign VA = RVLocs[i]; 1834 1835 // Pass 'this' value directly from the argument to return value, to avoid 1836 // reg unit interference 1837 if (i == 0 && isThisReturn) { 1838 assert(!VA.needsCustom() && VA.getLocVT() == MVT::i32 && 1839 "unexpected return calling convention register assignment"); 1840 InVals.push_back(ThisVal); 1841 continue; 1842 } 1843 1844 SDValue Val; 1845 if (VA.needsCustom()) { 1846 // Handle f64 or half of a v2f64. 1847 SDValue Lo = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32, 1848 InFlag); 1849 Chain = Lo.getValue(1); 1850 InFlag = Lo.getValue(2); 1851 VA = RVLocs[++i]; // skip ahead to next loc 1852 SDValue Hi = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32, 1853 InFlag); 1854 Chain = Hi.getValue(1); 1855 InFlag = Hi.getValue(2); 1856 if (!Subtarget->isLittle()) 1857 std::swap (Lo, Hi); 1858 Val = DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi); 1859 1860 if (VA.getLocVT() == MVT::v2f64) { 1861 SDValue Vec = DAG.getNode(ISD::UNDEF, dl, MVT::v2f64); 1862 Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Vec, Val, 1863 DAG.getConstant(0, dl, MVT::i32)); 1864 1865 VA = RVLocs[++i]; // skip ahead to next loc 1866 Lo = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32, InFlag); 1867 Chain = Lo.getValue(1); 1868 InFlag = Lo.getValue(2); 1869 VA = RVLocs[++i]; // skip ahead to next loc 1870 Hi = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32, InFlag); 1871 Chain = Hi.getValue(1); 1872 InFlag = Hi.getValue(2); 1873 if (!Subtarget->isLittle()) 1874 std::swap (Lo, Hi); 1875 Val = DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi); 1876 Val = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Vec, Val, 1877 DAG.getConstant(1, dl, MVT::i32)); 1878 } 1879 } else { 1880 Val = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), VA.getLocVT(), 1881 InFlag); 1882 Chain = Val.getValue(1); 1883 InFlag = Val.getValue(2); 1884 } 1885 1886 switch (VA.getLocInfo()) { 1887 default: llvm_unreachable("Unknown loc info!"); 1888 case CCValAssign::Full: break; 1889 case CCValAssign::BCvt: 1890 Val = DAG.getNode(ISD::BITCAST, dl, VA.getValVT(), Val); 1891 break; 1892 } 1893 1894 InVals.push_back(Val); 1895 } 1896 1897 return Chain; 1898 } 1899 1900 /// LowerMemOpCallTo - Store the argument to the stack. 1901 SDValue ARMTargetLowering::LowerMemOpCallTo(SDValue Chain, SDValue StackPtr, 1902 SDValue Arg, const SDLoc &dl, 1903 SelectionDAG &DAG, 1904 const CCValAssign &VA, 1905 ISD::ArgFlagsTy Flags) const { 1906 unsigned LocMemOffset = VA.getLocMemOffset(); 1907 SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset, dl); 1908 PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(DAG.getDataLayout()), 1909 StackPtr, PtrOff); 1910 return DAG.getStore( 1911 Chain, dl, Arg, PtrOff, 1912 MachinePointerInfo::getStack(DAG.getMachineFunction(), LocMemOffset)); 1913 } 1914 1915 void ARMTargetLowering::PassF64ArgInRegs(const SDLoc &dl, SelectionDAG &DAG, 1916 SDValue Chain, SDValue &Arg, 1917 RegsToPassVector &RegsToPass, 1918 CCValAssign &VA, CCValAssign &NextVA, 1919 SDValue &StackPtr, 1920 SmallVectorImpl<SDValue> &MemOpChains, 1921 ISD::ArgFlagsTy Flags) const { 1922 SDValue fmrrd = DAG.getNode(ARMISD::VMOVRRD, dl, 1923 DAG.getVTList(MVT::i32, MVT::i32), Arg); 1924 unsigned id = Subtarget->isLittle() ? 0 : 1; 1925 RegsToPass.push_back(std::make_pair(VA.getLocReg(), fmrrd.getValue(id))); 1926 1927 if (NextVA.isRegLoc()) 1928 RegsToPass.push_back(std::make_pair(NextVA.getLocReg(), fmrrd.getValue(1-id))); 1929 else { 1930 assert(NextVA.isMemLoc()); 1931 if (!StackPtr.getNode()) 1932 StackPtr = DAG.getCopyFromReg(Chain, dl, ARM::SP, 1933 getPointerTy(DAG.getDataLayout())); 1934 1935 MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, fmrrd.getValue(1-id), 1936 dl, DAG, NextVA, 1937 Flags)); 1938 } 1939 } 1940 1941 /// LowerCall - Lowering a call into a callseq_start <- 1942 /// ARMISD:CALL <- callseq_end chain. Also add input and output parameter 1943 /// nodes. 1944 SDValue 1945 ARMTargetLowering::LowerCall(TargetLowering::CallLoweringInfo &CLI, 1946 SmallVectorImpl<SDValue> &InVals) const { 1947 SelectionDAG &DAG = CLI.DAG; 1948 SDLoc &dl = CLI.DL; 1949 SmallVectorImpl<ISD::OutputArg> &Outs = CLI.Outs; 1950 SmallVectorImpl<SDValue> &OutVals = CLI.OutVals; 1951 SmallVectorImpl<ISD::InputArg> &Ins = CLI.Ins; 1952 SDValue Chain = CLI.Chain; 1953 SDValue Callee = CLI.Callee; 1954 bool &isTailCall = CLI.IsTailCall; 1955 CallingConv::ID CallConv = CLI.CallConv; 1956 bool doesNotRet = CLI.DoesNotReturn; 1957 bool isVarArg = CLI.IsVarArg; 1958 1959 MachineFunction &MF = DAG.getMachineFunction(); 1960 bool isStructRet = (Outs.empty()) ? false : Outs[0].Flags.isSRet(); 1961 bool isThisReturn = false; 1962 auto Attr = MF.getFunction().getFnAttribute("disable-tail-calls"); 1963 bool PreferIndirect = false; 1964 1965 // Disable tail calls if they're not supported. 1966 if (!Subtarget->supportsTailCall() || Attr.getValueAsString() == "true") 1967 isTailCall = false; 1968 1969 if (isa<GlobalAddressSDNode>(Callee)) { 1970 // If we're optimizing for minimum size and the function is called three or 1971 // more times in this block, we can improve codesize by calling indirectly 1972 // as BLXr has a 16-bit encoding. 1973 auto *GV = cast<GlobalAddressSDNode>(Callee)->getGlobal(); 1974 auto *BB = CLI.CS.getParent(); 1975 PreferIndirect = 1976 Subtarget->isThumb() && Subtarget->hasMinSize() && 1977 count_if(GV->users(), [&BB](const User *U) { 1978 return isa<Instruction>(U) && cast<Instruction>(U)->getParent() == BB; 1979 }) > 2; 1980 } 1981 if (isTailCall) { 1982 // Check if it's really possible to do a tail call. 1983 isTailCall = IsEligibleForTailCallOptimization( 1984 Callee, CallConv, isVarArg, isStructRet, 1985 MF.getFunction().hasStructRetAttr(), Outs, OutVals, Ins, DAG, 1986 PreferIndirect); 1987 if (!isTailCall && CLI.CS && CLI.CS.isMustTailCall()) 1988 report_fatal_error("failed to perform tail call elimination on a call " 1989 "site marked musttail"); 1990 // We don't support GuaranteedTailCallOpt for ARM, only automatically 1991 // detected sibcalls. 1992 if (isTailCall) 1993 ++NumTailCalls; 1994 } 1995 1996 // Analyze operands of the call, assigning locations to each operand. 1997 SmallVector<CCValAssign, 16> ArgLocs; 1998 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), ArgLocs, 1999 *DAG.getContext()); 2000 CCInfo.AnalyzeCallOperands(Outs, CCAssignFnForCall(CallConv, isVarArg)); 2001 2002 // Get a count of how many bytes are to be pushed on the stack. 2003 unsigned NumBytes = CCInfo.getNextStackOffset(); 2004 2005 if (isTailCall) { 2006 // For tail calls, memory operands are available in our caller's stack. 2007 NumBytes = 0; 2008 } else { 2009 // Adjust the stack pointer for the new arguments... 2010 // These operations are automatically eliminated by the prolog/epilog pass 2011 Chain = DAG.getCALLSEQ_START(Chain, NumBytes, 0, dl); 2012 } 2013 2014 SDValue StackPtr = 2015 DAG.getCopyFromReg(Chain, dl, ARM::SP, getPointerTy(DAG.getDataLayout())); 2016 2017 RegsToPassVector RegsToPass; 2018 SmallVector<SDValue, 8> MemOpChains; 2019 2020 // Walk the register/memloc assignments, inserting copies/loads. In the case 2021 // of tail call optimization, arguments are handled later. 2022 for (unsigned i = 0, realArgIdx = 0, e = ArgLocs.size(); 2023 i != e; 2024 ++i, ++realArgIdx) { 2025 CCValAssign &VA = ArgLocs[i]; 2026 SDValue Arg = OutVals[realArgIdx]; 2027 ISD::ArgFlagsTy Flags = Outs[realArgIdx].Flags; 2028 bool isByVal = Flags.isByVal(); 2029 2030 // Promote the value if needed. 2031 switch (VA.getLocInfo()) { 2032 default: llvm_unreachable("Unknown loc info!"); 2033 case CCValAssign::Full: break; 2034 case CCValAssign::SExt: 2035 Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), Arg); 2036 break; 2037 case CCValAssign::ZExt: 2038 Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, VA.getLocVT(), Arg); 2039 break; 2040 case CCValAssign::AExt: 2041 Arg = DAG.getNode(ISD::ANY_EXTEND, dl, VA.getLocVT(), Arg); 2042 break; 2043 case CCValAssign::BCvt: 2044 Arg = DAG.getNode(ISD::BITCAST, dl, VA.getLocVT(), Arg); 2045 break; 2046 } 2047 2048 // f64 and v2f64 might be passed in i32 pairs and must be split into pieces 2049 if (VA.needsCustom()) { 2050 if (VA.getLocVT() == MVT::v2f64) { 2051 SDValue Op0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg, 2052 DAG.getConstant(0, dl, MVT::i32)); 2053 SDValue Op1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg, 2054 DAG.getConstant(1, dl, MVT::i32)); 2055 2056 PassF64ArgInRegs(dl, DAG, Chain, Op0, RegsToPass, 2057 VA, ArgLocs[++i], StackPtr, MemOpChains, Flags); 2058 2059 VA = ArgLocs[++i]; // skip ahead to next loc 2060 if (VA.isRegLoc()) { 2061 PassF64ArgInRegs(dl, DAG, Chain, Op1, RegsToPass, 2062 VA, ArgLocs[++i], StackPtr, MemOpChains, Flags); 2063 } else { 2064 assert(VA.isMemLoc()); 2065 2066 MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, Op1, 2067 dl, DAG, VA, Flags)); 2068 } 2069 } else { 2070 PassF64ArgInRegs(dl, DAG, Chain, Arg, RegsToPass, VA, ArgLocs[++i], 2071 StackPtr, MemOpChains, Flags); 2072 } 2073 } else if (VA.isRegLoc()) { 2074 if (realArgIdx == 0 && Flags.isReturned() && !Flags.isSwiftSelf() && 2075 Outs[0].VT == MVT::i32) { 2076 assert(VA.getLocVT() == MVT::i32 && 2077 "unexpected calling convention register assignment"); 2078 assert(!Ins.empty() && Ins[0].VT == MVT::i32 && 2079 "unexpected use of 'returned'"); 2080 isThisReturn = true; 2081 } 2082 RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg)); 2083 } else if (isByVal) { 2084 assert(VA.isMemLoc()); 2085 unsigned offset = 0; 2086 2087 // True if this byval aggregate will be split between registers 2088 // and memory. 2089 unsigned ByValArgsCount = CCInfo.getInRegsParamsCount(); 2090 unsigned CurByValIdx = CCInfo.getInRegsParamsProcessed(); 2091 2092 if (CurByValIdx < ByValArgsCount) { 2093 2094 unsigned RegBegin, RegEnd; 2095 CCInfo.getInRegsParamInfo(CurByValIdx, RegBegin, RegEnd); 2096 2097 EVT PtrVT = 2098 DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout()); 2099 unsigned int i, j; 2100 for (i = 0, j = RegBegin; j < RegEnd; i++, j++) { 2101 SDValue Const = DAG.getConstant(4*i, dl, MVT::i32); 2102 SDValue AddArg = DAG.getNode(ISD::ADD, dl, PtrVT, Arg, Const); 2103 SDValue Load = DAG.getLoad(PtrVT, dl, Chain, AddArg, 2104 MachinePointerInfo(), 2105 DAG.InferPtrAlignment(AddArg)); 2106 MemOpChains.push_back(Load.getValue(1)); 2107 RegsToPass.push_back(std::make_pair(j, Load)); 2108 } 2109 2110 // If parameter size outsides register area, "offset" value 2111 // helps us to calculate stack slot for remained part properly. 2112 offset = RegEnd - RegBegin; 2113 2114 CCInfo.nextInRegsParam(); 2115 } 2116 2117 if (Flags.getByValSize() > 4*offset) { 2118 auto PtrVT = getPointerTy(DAG.getDataLayout()); 2119 unsigned LocMemOffset = VA.getLocMemOffset(); 2120 SDValue StkPtrOff = DAG.getIntPtrConstant(LocMemOffset, dl); 2121 SDValue Dst = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, StkPtrOff); 2122 SDValue SrcOffset = DAG.getIntPtrConstant(4*offset, dl); 2123 SDValue Src = DAG.getNode(ISD::ADD, dl, PtrVT, Arg, SrcOffset); 2124 SDValue SizeNode = DAG.getConstant(Flags.getByValSize() - 4*offset, dl, 2125 MVT::i32); 2126 SDValue AlignNode = DAG.getConstant(Flags.getByValAlign(), dl, 2127 MVT::i32); 2128 2129 SDVTList VTs = DAG.getVTList(MVT::Other, MVT::Glue); 2130 SDValue Ops[] = { Chain, Dst, Src, SizeNode, AlignNode}; 2131 MemOpChains.push_back(DAG.getNode(ARMISD::COPY_STRUCT_BYVAL, dl, VTs, 2132 Ops)); 2133 } 2134 } else if (!isTailCall) { 2135 assert(VA.isMemLoc()); 2136 2137 MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, Arg, 2138 dl, DAG, VA, Flags)); 2139 } 2140 } 2141 2142 if (!MemOpChains.empty()) 2143 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains); 2144 2145 // Build a sequence of copy-to-reg nodes chained together with token chain 2146 // and flag operands which copy the outgoing args into the appropriate regs. 2147 SDValue InFlag; 2148 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) { 2149 Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first, 2150 RegsToPass[i].second, InFlag); 2151 InFlag = Chain.getValue(1); 2152 } 2153 2154 // If the callee is a GlobalAddress/ExternalSymbol node (quite common, every 2155 // direct call is) turn it into a TargetGlobalAddress/TargetExternalSymbol 2156 // node so that legalize doesn't hack it. 2157 bool isDirect = false; 2158 2159 const TargetMachine &TM = getTargetMachine(); 2160 const Module *Mod = MF.getFunction().getParent(); 2161 const GlobalValue *GV = nullptr; 2162 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) 2163 GV = G->getGlobal(); 2164 bool isStub = 2165 !TM.shouldAssumeDSOLocal(*Mod, GV) && Subtarget->isTargetMachO(); 2166 2167 bool isARMFunc = !Subtarget->isThumb() || (isStub && !Subtarget->isMClass()); 2168 bool isLocalARMFunc = false; 2169 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>(); 2170 auto PtrVt = getPointerTy(DAG.getDataLayout()); 2171 2172 if (Subtarget->genLongCalls()) { 2173 assert((!isPositionIndependent() || Subtarget->isTargetWindows()) && 2174 "long-calls codegen is not position independent!"); 2175 // Handle a global address or an external symbol. If it's not one of 2176 // those, the target's already in a register, so we don't need to do 2177 // anything extra. 2178 if (isa<GlobalAddressSDNode>(Callee)) { 2179 // Create a constant pool entry for the callee address 2180 unsigned ARMPCLabelIndex = AFI->createPICLabelUId(); 2181 ARMConstantPoolValue *CPV = 2182 ARMConstantPoolConstant::Create(GV, ARMPCLabelIndex, ARMCP::CPValue, 0); 2183 2184 // Get the address of the callee into a register 2185 SDValue CPAddr = DAG.getTargetConstantPool(CPV, PtrVt, 4); 2186 CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr); 2187 Callee = DAG.getLoad( 2188 PtrVt, dl, DAG.getEntryNode(), CPAddr, 2189 MachinePointerInfo::getConstantPool(DAG.getMachineFunction())); 2190 } else if (ExternalSymbolSDNode *S=dyn_cast<ExternalSymbolSDNode>(Callee)) { 2191 const char *Sym = S->getSymbol(); 2192 2193 // Create a constant pool entry for the callee address 2194 unsigned ARMPCLabelIndex = AFI->createPICLabelUId(); 2195 ARMConstantPoolValue *CPV = 2196 ARMConstantPoolSymbol::Create(*DAG.getContext(), Sym, 2197 ARMPCLabelIndex, 0); 2198 // Get the address of the callee into a register 2199 SDValue CPAddr = DAG.getTargetConstantPool(CPV, PtrVt, 4); 2200 CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr); 2201 Callee = DAG.getLoad( 2202 PtrVt, dl, DAG.getEntryNode(), CPAddr, 2203 MachinePointerInfo::getConstantPool(DAG.getMachineFunction())); 2204 } 2205 } else if (isa<GlobalAddressSDNode>(Callee)) { 2206 if (!PreferIndirect) { 2207 isDirect = true; 2208 bool isDef = GV->isStrongDefinitionForLinker(); 2209 2210 // ARM call to a local ARM function is predicable. 2211 isLocalARMFunc = !Subtarget->isThumb() && (isDef || !ARMInterworking); 2212 // tBX takes a register source operand. 2213 if (isStub && Subtarget->isThumb1Only() && !Subtarget->hasV5TOps()) { 2214 assert(Subtarget->isTargetMachO() && "WrapperPIC use on non-MachO?"); 2215 Callee = DAG.getNode( 2216 ARMISD::WrapperPIC, dl, PtrVt, 2217 DAG.getTargetGlobalAddress(GV, dl, PtrVt, 0, ARMII::MO_NONLAZY)); 2218 Callee = DAG.getLoad( 2219 PtrVt, dl, DAG.getEntryNode(), Callee, 2220 MachinePointerInfo::getGOT(DAG.getMachineFunction()), 2221 /* Alignment = */ 0, MachineMemOperand::MODereferenceable | 2222 MachineMemOperand::MOInvariant); 2223 } else if (Subtarget->isTargetCOFF()) { 2224 assert(Subtarget->isTargetWindows() && 2225 "Windows is the only supported COFF target"); 2226 unsigned TargetFlags = GV->hasDLLImportStorageClass() 2227 ? ARMII::MO_DLLIMPORT 2228 : ARMII::MO_NO_FLAG; 2229 Callee = DAG.getTargetGlobalAddress(GV, dl, PtrVt, /*Offset=*/0, 2230 TargetFlags); 2231 if (GV->hasDLLImportStorageClass()) 2232 Callee = 2233 DAG.getLoad(PtrVt, dl, DAG.getEntryNode(), 2234 DAG.getNode(ARMISD::Wrapper, dl, PtrVt, Callee), 2235 MachinePointerInfo::getGOT(DAG.getMachineFunction())); 2236 } else { 2237 Callee = DAG.getTargetGlobalAddress(GV, dl, PtrVt, 0, 0); 2238 } 2239 } 2240 } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) { 2241 isDirect = true; 2242 // tBX takes a register source operand. 2243 const char *Sym = S->getSymbol(); 2244 if (isARMFunc && Subtarget->isThumb1Only() && !Subtarget->hasV5TOps()) { 2245 unsigned ARMPCLabelIndex = AFI->createPICLabelUId(); 2246 ARMConstantPoolValue *CPV = 2247 ARMConstantPoolSymbol::Create(*DAG.getContext(), Sym, 2248 ARMPCLabelIndex, 4); 2249 SDValue CPAddr = DAG.getTargetConstantPool(CPV, PtrVt, 4); 2250 CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr); 2251 Callee = DAG.getLoad( 2252 PtrVt, dl, DAG.getEntryNode(), CPAddr, 2253 MachinePointerInfo::getConstantPool(DAG.getMachineFunction())); 2254 SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, dl, MVT::i32); 2255 Callee = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVt, Callee, PICLabel); 2256 } else { 2257 Callee = DAG.getTargetExternalSymbol(Sym, PtrVt, 0); 2258 } 2259 } 2260 2261 // FIXME: handle tail calls differently. 2262 unsigned CallOpc; 2263 if (Subtarget->isThumb()) { 2264 if ((!isDirect || isARMFunc) && !Subtarget->hasV5TOps()) 2265 CallOpc = ARMISD::CALL_NOLINK; 2266 else 2267 CallOpc = ARMISD::CALL; 2268 } else { 2269 if (!isDirect && !Subtarget->hasV5TOps()) 2270 CallOpc = ARMISD::CALL_NOLINK; 2271 else if (doesNotRet && isDirect && Subtarget->hasRetAddrStack() && 2272 // Emit regular call when code size is the priority 2273 !Subtarget->hasMinSize()) 2274 // "mov lr, pc; b _foo" to avoid confusing the RSP 2275 CallOpc = ARMISD::CALL_NOLINK; 2276 else 2277 CallOpc = isLocalARMFunc ? ARMISD::CALL_PRED : ARMISD::CALL; 2278 } 2279 2280 std::vector<SDValue> Ops; 2281 Ops.push_back(Chain); 2282 Ops.push_back(Callee); 2283 2284 // Add argument registers to the end of the list so that they are known live 2285 // into the call. 2286 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) 2287 Ops.push_back(DAG.getRegister(RegsToPass[i].first, 2288 RegsToPass[i].second.getValueType())); 2289 2290 // Add a register mask operand representing the call-preserved registers. 2291 if (!isTailCall) { 2292 const uint32_t *Mask; 2293 const ARMBaseRegisterInfo *ARI = Subtarget->getRegisterInfo(); 2294 if (isThisReturn) { 2295 // For 'this' returns, use the R0-preserving mask if applicable 2296 Mask = ARI->getThisReturnPreservedMask(MF, CallConv); 2297 if (!Mask) { 2298 // Set isThisReturn to false if the calling convention is not one that 2299 // allows 'returned' to be modeled in this way, so LowerCallResult does 2300 // not try to pass 'this' straight through 2301 isThisReturn = false; 2302 Mask = ARI->getCallPreservedMask(MF, CallConv); 2303 } 2304 } else 2305 Mask = ARI->getCallPreservedMask(MF, CallConv); 2306 2307 assert(Mask && "Missing call preserved mask for calling convention"); 2308 Ops.push_back(DAG.getRegisterMask(Mask)); 2309 } 2310 2311 if (InFlag.getNode()) 2312 Ops.push_back(InFlag); 2313 2314 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue); 2315 if (isTailCall) { 2316 MF.getFrameInfo().setHasTailCall(); 2317 return DAG.getNode(ARMISD::TC_RETURN, dl, NodeTys, Ops); 2318 } 2319 2320 // Returns a chain and a flag for retval copy to use. 2321 Chain = DAG.getNode(CallOpc, dl, NodeTys, Ops); 2322 InFlag = Chain.getValue(1); 2323 2324 Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, dl, true), 2325 DAG.getIntPtrConstant(0, dl, true), InFlag, dl); 2326 if (!Ins.empty()) 2327 InFlag = Chain.getValue(1); 2328 2329 // Handle result values, copying them out of physregs into vregs that we 2330 // return. 2331 return LowerCallResult(Chain, InFlag, CallConv, isVarArg, Ins, dl, DAG, 2332 InVals, isThisReturn, 2333 isThisReturn ? OutVals[0] : SDValue()); 2334 } 2335 2336 /// HandleByVal - Every parameter *after* a byval parameter is passed 2337 /// on the stack. Remember the next parameter register to allocate, 2338 /// and then confiscate the rest of the parameter registers to insure 2339 /// this. 2340 void ARMTargetLowering::HandleByVal(CCState *State, unsigned &Size, 2341 unsigned Align) const { 2342 // Byval (as with any stack) slots are always at least 4 byte aligned. 2343 Align = std::max(Align, 4U); 2344 2345 unsigned Reg = State->AllocateReg(GPRArgRegs); 2346 if (!Reg) 2347 return; 2348 2349 unsigned AlignInRegs = Align / 4; 2350 unsigned Waste = (ARM::R4 - Reg) % AlignInRegs; 2351 for (unsigned i = 0; i < Waste; ++i) 2352 Reg = State->AllocateReg(GPRArgRegs); 2353 2354 if (!Reg) 2355 return; 2356 2357 unsigned Excess = 4 * (ARM::R4 - Reg); 2358 2359 // Special case when NSAA != SP and parameter size greater than size of 2360 // all remained GPR regs. In that case we can't split parameter, we must 2361 // send it to stack. We also must set NCRN to R4, so waste all 2362 // remained registers. 2363 const unsigned NSAAOffset = State->getNextStackOffset(); 2364 if (NSAAOffset != 0 && Size > Excess) { 2365 while (State->AllocateReg(GPRArgRegs)) 2366 ; 2367 return; 2368 } 2369 2370 // First register for byval parameter is the first register that wasn't 2371 // allocated before this method call, so it would be "reg". 2372 // If parameter is small enough to be saved in range [reg, r4), then 2373 // the end (first after last) register would be reg + param-size-in-regs, 2374 // else parameter would be splitted between registers and stack, 2375 // end register would be r4 in this case. 2376 unsigned ByValRegBegin = Reg; 2377 unsigned ByValRegEnd = std::min<unsigned>(Reg + Size / 4, ARM::R4); 2378 State->addInRegsParamInfo(ByValRegBegin, ByValRegEnd); 2379 // Note, first register is allocated in the beginning of function already, 2380 // allocate remained amount of registers we need. 2381 for (unsigned i = Reg + 1; i != ByValRegEnd; ++i) 2382 State->AllocateReg(GPRArgRegs); 2383 // A byval parameter that is split between registers and memory needs its 2384 // size truncated here. 2385 // In the case where the entire structure fits in registers, we set the 2386 // size in memory to zero. 2387 Size = std::max<int>(Size - Excess, 0); 2388 } 2389 2390 /// MatchingStackOffset - Return true if the given stack call argument is 2391 /// already available in the same position (relatively) of the caller's 2392 /// incoming argument stack. 2393 static 2394 bool MatchingStackOffset(SDValue Arg, unsigned Offset, ISD::ArgFlagsTy Flags, 2395 MachineFrameInfo &MFI, const MachineRegisterInfo *MRI, 2396 const TargetInstrInfo *TII) { 2397 unsigned Bytes = Arg.getValueSizeInBits() / 8; 2398 int FI = std::numeric_limits<int>::max(); 2399 if (Arg.getOpcode() == ISD::CopyFromReg) { 2400 unsigned VR = cast<RegisterSDNode>(Arg.getOperand(1))->getReg(); 2401 if (!TargetRegisterInfo::isVirtualRegister(VR)) 2402 return false; 2403 MachineInstr *Def = MRI->getVRegDef(VR); 2404 if (!Def) 2405 return false; 2406 if (!Flags.isByVal()) { 2407 if (!TII->isLoadFromStackSlot(*Def, FI)) 2408 return false; 2409 } else { 2410 return false; 2411 } 2412 } else if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Arg)) { 2413 if (Flags.isByVal()) 2414 // ByVal argument is passed in as a pointer but it's now being 2415 // dereferenced. e.g. 2416 // define @foo(%struct.X* %A) { 2417 // tail call @bar(%struct.X* byval %A) 2418 // } 2419 return false; 2420 SDValue Ptr = Ld->getBasePtr(); 2421 FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr); 2422 if (!FINode) 2423 return false; 2424 FI = FINode->getIndex(); 2425 } else 2426 return false; 2427 2428 assert(FI != std::numeric_limits<int>::max()); 2429 if (!MFI.isFixedObjectIndex(FI)) 2430 return false; 2431 return Offset == MFI.getObjectOffset(FI) && Bytes == MFI.getObjectSize(FI); 2432 } 2433 2434 /// IsEligibleForTailCallOptimization - Check whether the call is eligible 2435 /// for tail call optimization. Targets which want to do tail call 2436 /// optimization should implement this function. 2437 bool ARMTargetLowering::IsEligibleForTailCallOptimization( 2438 SDValue Callee, CallingConv::ID CalleeCC, bool isVarArg, 2439 bool isCalleeStructRet, bool isCallerStructRet, 2440 const SmallVectorImpl<ISD::OutputArg> &Outs, 2441 const SmallVectorImpl<SDValue> &OutVals, 2442 const SmallVectorImpl<ISD::InputArg> &Ins, SelectionDAG &DAG, 2443 const bool isIndirect) const { 2444 MachineFunction &MF = DAG.getMachineFunction(); 2445 const Function &CallerF = MF.getFunction(); 2446 CallingConv::ID CallerCC = CallerF.getCallingConv(); 2447 2448 assert(Subtarget->supportsTailCall()); 2449 2450 // Indirect tail calls cannot be optimized for Thumb1 if the args 2451 // to the call take up r0-r3. The reason is that there are no legal registers 2452 // left to hold the pointer to the function to be called. 2453 if (Subtarget->isThumb1Only() && Outs.size() >= 4 && 2454 (!isa<GlobalAddressSDNode>(Callee.getNode()) || isIndirect)) 2455 return false; 2456 2457 // Look for obvious safe cases to perform tail call optimization that do not 2458 // require ABI changes. This is what gcc calls sibcall. 2459 2460 // Exception-handling functions need a special set of instructions to indicate 2461 // a return to the hardware. Tail-calling another function would probably 2462 // break this. 2463 if (CallerF.hasFnAttribute("interrupt")) 2464 return false; 2465 2466 // Also avoid sibcall optimization if either caller or callee uses struct 2467 // return semantics. 2468 if (isCalleeStructRet || isCallerStructRet) 2469 return false; 2470 2471 // Externally-defined functions with weak linkage should not be 2472 // tail-called on ARM when the OS does not support dynamic 2473 // pre-emption of symbols, as the AAELF spec requires normal calls 2474 // to undefined weak functions to be replaced with a NOP or jump to the 2475 // next instruction. The behaviour of branch instructions in this 2476 // situation (as used for tail calls) is implementation-defined, so we 2477 // cannot rely on the linker replacing the tail call with a return. 2478 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) { 2479 const GlobalValue *GV = G->getGlobal(); 2480 const Triple &TT = getTargetMachine().getTargetTriple(); 2481 if (GV->hasExternalWeakLinkage() && 2482 (!TT.isOSWindows() || TT.isOSBinFormatELF() || TT.isOSBinFormatMachO())) 2483 return false; 2484 } 2485 2486 // Check that the call results are passed in the same way. 2487 LLVMContext &C = *DAG.getContext(); 2488 if (!CCState::resultsCompatible(CalleeCC, CallerCC, MF, C, Ins, 2489 CCAssignFnForReturn(CalleeCC, isVarArg), 2490 CCAssignFnForReturn(CallerCC, isVarArg))) 2491 return false; 2492 // The callee has to preserve all registers the caller needs to preserve. 2493 const ARMBaseRegisterInfo *TRI = Subtarget->getRegisterInfo(); 2494 const uint32_t *CallerPreserved = TRI->getCallPreservedMask(MF, CallerCC); 2495 if (CalleeCC != CallerCC) { 2496 const uint32_t *CalleePreserved = TRI->getCallPreservedMask(MF, CalleeCC); 2497 if (!TRI->regmaskSubsetEqual(CallerPreserved, CalleePreserved)) 2498 return false; 2499 } 2500 2501 // If Caller's vararg or byval argument has been split between registers and 2502 // stack, do not perform tail call, since part of the argument is in caller's 2503 // local frame. 2504 const ARMFunctionInfo *AFI_Caller = MF.getInfo<ARMFunctionInfo>(); 2505 if (AFI_Caller->getArgRegsSaveSize()) 2506 return false; 2507 2508 // If the callee takes no arguments then go on to check the results of the 2509 // call. 2510 if (!Outs.empty()) { 2511 // Check if stack adjustment is needed. For now, do not do this if any 2512 // argument is passed on the stack. 2513 SmallVector<CCValAssign, 16> ArgLocs; 2514 CCState CCInfo(CalleeCC, isVarArg, MF, ArgLocs, C); 2515 CCInfo.AnalyzeCallOperands(Outs, CCAssignFnForCall(CalleeCC, isVarArg)); 2516 if (CCInfo.getNextStackOffset()) { 2517 // Check if the arguments are already laid out in the right way as 2518 // the caller's fixed stack objects. 2519 MachineFrameInfo &MFI = MF.getFrameInfo(); 2520 const MachineRegisterInfo *MRI = &MF.getRegInfo(); 2521 const TargetInstrInfo *TII = Subtarget->getInstrInfo(); 2522 for (unsigned i = 0, realArgIdx = 0, e = ArgLocs.size(); 2523 i != e; 2524 ++i, ++realArgIdx) { 2525 CCValAssign &VA = ArgLocs[i]; 2526 EVT RegVT = VA.getLocVT(); 2527 SDValue Arg = OutVals[realArgIdx]; 2528 ISD::ArgFlagsTy Flags = Outs[realArgIdx].Flags; 2529 if (VA.getLocInfo() == CCValAssign::Indirect) 2530 return false; 2531 if (VA.needsCustom()) { 2532 // f64 and vector types are split into multiple registers or 2533 // register/stack-slot combinations. The types will not match 2534 // the registers; give up on memory f64 refs until we figure 2535 // out what to do about this. 2536 if (!VA.isRegLoc()) 2537 return false; 2538 if (!ArgLocs[++i].isRegLoc()) 2539 return false; 2540 if (RegVT == MVT::v2f64) { 2541 if (!ArgLocs[++i].isRegLoc()) 2542 return false; 2543 if (!ArgLocs[++i].isRegLoc()) 2544 return false; 2545 } 2546 } else if (!VA.isRegLoc()) { 2547 if (!MatchingStackOffset(Arg, VA.getLocMemOffset(), Flags, 2548 MFI, MRI, TII)) 2549 return false; 2550 } 2551 } 2552 } 2553 2554 const MachineRegisterInfo &MRI = MF.getRegInfo(); 2555 if (!parametersInCSRMatch(MRI, CallerPreserved, ArgLocs, OutVals)) 2556 return false; 2557 } 2558 2559 return true; 2560 } 2561 2562 bool 2563 ARMTargetLowering::CanLowerReturn(CallingConv::ID CallConv, 2564 MachineFunction &MF, bool isVarArg, 2565 const SmallVectorImpl<ISD::OutputArg> &Outs, 2566 LLVMContext &Context) const { 2567 SmallVector<CCValAssign, 16> RVLocs; 2568 CCState CCInfo(CallConv, isVarArg, MF, RVLocs, Context); 2569 return CCInfo.CheckReturn(Outs, CCAssignFnForReturn(CallConv, isVarArg)); 2570 } 2571 2572 static SDValue LowerInterruptReturn(SmallVectorImpl<SDValue> &RetOps, 2573 const SDLoc &DL, SelectionDAG &DAG) { 2574 const MachineFunction &MF = DAG.getMachineFunction(); 2575 const Function &F = MF.getFunction(); 2576 2577 StringRef IntKind = F.getFnAttribute("interrupt").getValueAsString(); 2578 2579 // See ARM ARM v7 B1.8.3. On exception entry LR is set to a possibly offset 2580 // version of the "preferred return address". These offsets affect the return 2581 // instruction if this is a return from PL1 without hypervisor extensions. 2582 // IRQ/FIQ: +4 "subs pc, lr, #4" 2583 // SWI: 0 "subs pc, lr, #0" 2584 // ABORT: +4 "subs pc, lr, #4" 2585 // UNDEF: +4/+2 "subs pc, lr, #0" 2586 // UNDEF varies depending on where the exception came from ARM or Thumb 2587 // mode. Alongside GCC, we throw our hands up in disgust and pretend it's 0. 2588 2589 int64_t LROffset; 2590 if (IntKind == "" || IntKind == "IRQ" || IntKind == "FIQ" || 2591 IntKind == "ABORT") 2592 LROffset = 4; 2593 else if (IntKind == "SWI" || IntKind == "UNDEF") 2594 LROffset = 0; 2595 else 2596 report_fatal_error("Unsupported interrupt attribute. If present, value " 2597 "must be one of: IRQ, FIQ, SWI, ABORT or UNDEF"); 2598 2599 RetOps.insert(RetOps.begin() + 1, 2600 DAG.getConstant(LROffset, DL, MVT::i32, false)); 2601 2602 return DAG.getNode(ARMISD::INTRET_FLAG, DL, MVT::Other, RetOps); 2603 } 2604 2605 SDValue 2606 ARMTargetLowering::LowerReturn(SDValue Chain, CallingConv::ID CallConv, 2607 bool isVarArg, 2608 const SmallVectorImpl<ISD::OutputArg> &Outs, 2609 const SmallVectorImpl<SDValue> &OutVals, 2610 const SDLoc &dl, SelectionDAG &DAG) const { 2611 // CCValAssign - represent the assignment of the return value to a location. 2612 SmallVector<CCValAssign, 16> RVLocs; 2613 2614 // CCState - Info about the registers and stack slots. 2615 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs, 2616 *DAG.getContext()); 2617 2618 // Analyze outgoing return values. 2619 CCInfo.AnalyzeReturn(Outs, CCAssignFnForReturn(CallConv, isVarArg)); 2620 2621 SDValue Flag; 2622 SmallVector<SDValue, 4> RetOps; 2623 RetOps.push_back(Chain); // Operand #0 = Chain (updated below) 2624 bool isLittleEndian = Subtarget->isLittle(); 2625 2626 MachineFunction &MF = DAG.getMachineFunction(); 2627 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>(); 2628 AFI->setReturnRegsCount(RVLocs.size()); 2629 2630 // Copy the result values into the output registers. 2631 for (unsigned i = 0, realRVLocIdx = 0; 2632 i != RVLocs.size(); 2633 ++i, ++realRVLocIdx) { 2634 CCValAssign &VA = RVLocs[i]; 2635 assert(VA.isRegLoc() && "Can only return in registers!"); 2636 2637 SDValue Arg = OutVals[realRVLocIdx]; 2638 bool ReturnF16 = false; 2639 2640 if (Subtarget->hasFullFP16() && Subtarget->isTargetHardFloat()) { 2641 // Half-precision return values can be returned like this: 2642 // 2643 // t11 f16 = fadd ... 2644 // t12: i16 = bitcast t11 2645 // t13: i32 = zero_extend t12 2646 // t14: f32 = bitcast t13 <~~~~~~~ Arg 2647 // 2648 // to avoid code generation for bitcasts, we simply set Arg to the node 2649 // that produces the f16 value, t11 in this case. 2650 // 2651 if (Arg.getValueType() == MVT::f32 && Arg.getOpcode() == ISD::BITCAST) { 2652 SDValue ZE = Arg.getOperand(0); 2653 if (ZE.getOpcode() == ISD::ZERO_EXTEND && ZE.getValueType() == MVT::i32) { 2654 SDValue BC = ZE.getOperand(0); 2655 if (BC.getOpcode() == ISD::BITCAST && BC.getValueType() == MVT::i16) { 2656 Arg = BC.getOperand(0); 2657 ReturnF16 = true; 2658 } 2659 } 2660 } 2661 } 2662 2663 switch (VA.getLocInfo()) { 2664 default: llvm_unreachable("Unknown loc info!"); 2665 case CCValAssign::Full: break; 2666 case CCValAssign::BCvt: 2667 if (!ReturnF16) 2668 Arg = DAG.getNode(ISD::BITCAST, dl, VA.getLocVT(), Arg); 2669 break; 2670 } 2671 2672 if (VA.needsCustom()) { 2673 if (VA.getLocVT() == MVT::v2f64) { 2674 // Extract the first half and return it in two registers. 2675 SDValue Half = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg, 2676 DAG.getConstant(0, dl, MVT::i32)); 2677 SDValue HalfGPRs = DAG.getNode(ARMISD::VMOVRRD, dl, 2678 DAG.getVTList(MVT::i32, MVT::i32), Half); 2679 2680 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), 2681 HalfGPRs.getValue(isLittleEndian ? 0 : 1), 2682 Flag); 2683 Flag = Chain.getValue(1); 2684 RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT())); 2685 VA = RVLocs[++i]; // skip ahead to next loc 2686 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), 2687 HalfGPRs.getValue(isLittleEndian ? 1 : 0), 2688 Flag); 2689 Flag = Chain.getValue(1); 2690 RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT())); 2691 VA = RVLocs[++i]; // skip ahead to next loc 2692 2693 // Extract the 2nd half and fall through to handle it as an f64 value. 2694 Arg = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg, 2695 DAG.getConstant(1, dl, MVT::i32)); 2696 } 2697 // Legalize ret f64 -> ret 2 x i32. We always have fmrrd if f64 is 2698 // available. 2699 SDValue fmrrd = DAG.getNode(ARMISD::VMOVRRD, dl, 2700 DAG.getVTList(MVT::i32, MVT::i32), Arg); 2701 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), 2702 fmrrd.getValue(isLittleEndian ? 0 : 1), 2703 Flag); 2704 Flag = Chain.getValue(1); 2705 RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT())); 2706 VA = RVLocs[++i]; // skip ahead to next loc 2707 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), 2708 fmrrd.getValue(isLittleEndian ? 1 : 0), 2709 Flag); 2710 } else 2711 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), Arg, Flag); 2712 2713 // Guarantee that all emitted copies are 2714 // stuck together, avoiding something bad. 2715 Flag = Chain.getValue(1); 2716 RetOps.push_back(DAG.getRegister(VA.getLocReg(), 2717 ReturnF16 ? MVT::f16 : VA.getLocVT())); 2718 } 2719 const ARMBaseRegisterInfo *TRI = Subtarget->getRegisterInfo(); 2720 const MCPhysReg *I = 2721 TRI->getCalleeSavedRegsViaCopy(&DAG.getMachineFunction()); 2722 if (I) { 2723 for (; *I; ++I) { 2724 if (ARM::GPRRegClass.contains(*I)) 2725 RetOps.push_back(DAG.getRegister(*I, MVT::i32)); 2726 else if (ARM::DPRRegClass.contains(*I)) 2727 RetOps.push_back(DAG.getRegister(*I, MVT::getFloatingPointVT(64))); 2728 else 2729 llvm_unreachable("Unexpected register class in CSRsViaCopy!"); 2730 } 2731 } 2732 2733 // Update chain and glue. 2734 RetOps[0] = Chain; 2735 if (Flag.getNode()) 2736 RetOps.push_back(Flag); 2737 2738 // CPUs which aren't M-class use a special sequence to return from 2739 // exceptions (roughly, any instruction setting pc and cpsr simultaneously, 2740 // though we use "subs pc, lr, #N"). 2741 // 2742 // M-class CPUs actually use a normal return sequence with a special 2743 // (hardware-provided) value in LR, so the normal code path works. 2744 if (DAG.getMachineFunction().getFunction().hasFnAttribute("interrupt") && 2745 !Subtarget->isMClass()) { 2746 if (Subtarget->isThumb1Only()) 2747 report_fatal_error("interrupt attribute is not supported in Thumb1"); 2748 return LowerInterruptReturn(RetOps, dl, DAG); 2749 } 2750 2751 return DAG.getNode(ARMISD::RET_FLAG, dl, MVT::Other, RetOps); 2752 } 2753 2754 bool ARMTargetLowering::isUsedByReturnOnly(SDNode *N, SDValue &Chain) const { 2755 if (N->getNumValues() != 1) 2756 return false; 2757 if (!N->hasNUsesOfValue(1, 0)) 2758 return false; 2759 2760 SDValue TCChain = Chain; 2761 SDNode *Copy = *N->use_begin(); 2762 if (Copy->getOpcode() == ISD::CopyToReg) { 2763 // If the copy has a glue operand, we conservatively assume it isn't safe to 2764 // perform a tail call. 2765 if (Copy->getOperand(Copy->getNumOperands()-1).getValueType() == MVT::Glue) 2766 return false; 2767 TCChain = Copy->getOperand(0); 2768 } else if (Copy->getOpcode() == ARMISD::VMOVRRD) { 2769 SDNode *VMov = Copy; 2770 // f64 returned in a pair of GPRs. 2771 SmallPtrSet<SDNode*, 2> Copies; 2772 for (SDNode::use_iterator UI = VMov->use_begin(), UE = VMov->use_end(); 2773 UI != UE; ++UI) { 2774 if (UI->getOpcode() != ISD::CopyToReg) 2775 return false; 2776 Copies.insert(*UI); 2777 } 2778 if (Copies.size() > 2) 2779 return false; 2780 2781 for (SDNode::use_iterator UI = VMov->use_begin(), UE = VMov->use_end(); 2782 UI != UE; ++UI) { 2783 SDValue UseChain = UI->getOperand(0); 2784 if (Copies.count(UseChain.getNode())) 2785 // Second CopyToReg 2786 Copy = *UI; 2787 else { 2788 // We are at the top of this chain. 2789 // If the copy has a glue operand, we conservatively assume it 2790 // isn't safe to perform a tail call. 2791 if (UI->getOperand(UI->getNumOperands()-1).getValueType() == MVT::Glue) 2792 return false; 2793 // First CopyToReg 2794 TCChain = UseChain; 2795 } 2796 } 2797 } else if (Copy->getOpcode() == ISD::BITCAST) { 2798 // f32 returned in a single GPR. 2799 if (!Copy->hasOneUse()) 2800 return false; 2801 Copy = *Copy->use_begin(); 2802 if (Copy->getOpcode() != ISD::CopyToReg || !Copy->hasNUsesOfValue(1, 0)) 2803 return false; 2804 // If the copy has a glue operand, we conservatively assume it isn't safe to 2805 // perform a tail call. 2806 if (Copy->getOperand(Copy->getNumOperands()-1).getValueType() == MVT::Glue) 2807 return false; 2808 TCChain = Copy->getOperand(0); 2809 } else { 2810 return false; 2811 } 2812 2813 bool HasRet = false; 2814 for (SDNode::use_iterator UI = Copy->use_begin(), UE = Copy->use_end(); 2815 UI != UE; ++UI) { 2816 if (UI->getOpcode() != ARMISD::RET_FLAG && 2817 UI->getOpcode() != ARMISD::INTRET_FLAG) 2818 return false; 2819 HasRet = true; 2820 } 2821 2822 if (!HasRet) 2823 return false; 2824 2825 Chain = TCChain; 2826 return true; 2827 } 2828 2829 bool ARMTargetLowering::mayBeEmittedAsTailCall(const CallInst *CI) const { 2830 if (!Subtarget->supportsTailCall()) 2831 return false; 2832 2833 auto Attr = 2834 CI->getParent()->getParent()->getFnAttribute("disable-tail-calls"); 2835 if (!CI->isTailCall() || Attr.getValueAsString() == "true") 2836 return false; 2837 2838 return true; 2839 } 2840 2841 // Trying to write a 64 bit value so need to split into two 32 bit values first, 2842 // and pass the lower and high parts through. 2843 static SDValue LowerWRITE_REGISTER(SDValue Op, SelectionDAG &DAG) { 2844 SDLoc DL(Op); 2845 SDValue WriteValue = Op->getOperand(2); 2846 2847 // This function is only supposed to be called for i64 type argument. 2848 assert(WriteValue.getValueType() == MVT::i64 2849 && "LowerWRITE_REGISTER called for non-i64 type argument."); 2850 2851 SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, WriteValue, 2852 DAG.getConstant(0, DL, MVT::i32)); 2853 SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, WriteValue, 2854 DAG.getConstant(1, DL, MVT::i32)); 2855 SDValue Ops[] = { Op->getOperand(0), Op->getOperand(1), Lo, Hi }; 2856 return DAG.getNode(ISD::WRITE_REGISTER, DL, MVT::Other, Ops); 2857 } 2858 2859 // ConstantPool, JumpTable, GlobalAddress, and ExternalSymbol are lowered as 2860 // their target counterpart wrapped in the ARMISD::Wrapper node. Suppose N is 2861 // one of the above mentioned nodes. It has to be wrapped because otherwise 2862 // Select(N) returns N. So the raw TargetGlobalAddress nodes, etc. can only 2863 // be used to form addressing mode. These wrapped nodes will be selected 2864 // into MOVi. 2865 SDValue ARMTargetLowering::LowerConstantPool(SDValue Op, 2866 SelectionDAG &DAG) const { 2867 EVT PtrVT = Op.getValueType(); 2868 // FIXME there is no actual debug info here 2869 SDLoc dl(Op); 2870 ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op); 2871 SDValue Res; 2872 2873 // When generating execute-only code Constant Pools must be promoted to the 2874 // global data section. It's a bit ugly that we can't share them across basic 2875 // blocks, but this way we guarantee that execute-only behaves correct with 2876 // position-independent addressing modes. 2877 if (Subtarget->genExecuteOnly()) { 2878 auto AFI = DAG.getMachineFunction().getInfo<ARMFunctionInfo>(); 2879 auto T = const_cast<Type*>(CP->getType()); 2880 auto C = const_cast<Constant*>(CP->getConstVal()); 2881 auto M = const_cast<Module*>(DAG.getMachineFunction(). 2882 getFunction().getParent()); 2883 auto GV = new GlobalVariable( 2884 *M, T, /*isConst=*/true, GlobalVariable::InternalLinkage, C, 2885 Twine(DAG.getDataLayout().getPrivateGlobalPrefix()) + "CP" + 2886 Twine(DAG.getMachineFunction().getFunctionNumber()) + "_" + 2887 Twine(AFI->createPICLabelUId()) 2888 ); 2889 SDValue GA = DAG.getTargetGlobalAddress(dyn_cast<GlobalValue>(GV), 2890 dl, PtrVT); 2891 return LowerGlobalAddress(GA, DAG); 2892 } 2893 2894 if (CP->isMachineConstantPoolEntry()) 2895 Res = DAG.getTargetConstantPool(CP->getMachineCPVal(), PtrVT, 2896 CP->getAlignment()); 2897 else 2898 Res = DAG.getTargetConstantPool(CP->getConstVal(), PtrVT, 2899 CP->getAlignment()); 2900 return DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Res); 2901 } 2902 2903 unsigned ARMTargetLowering::getJumpTableEncoding() const { 2904 return MachineJumpTableInfo::EK_Inline; 2905 } 2906 2907 SDValue ARMTargetLowering::LowerBlockAddress(SDValue Op, 2908 SelectionDAG &DAG) const { 2909 MachineFunction &MF = DAG.getMachineFunction(); 2910 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>(); 2911 unsigned ARMPCLabelIndex = 0; 2912 SDLoc DL(Op); 2913 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 2914 const BlockAddress *BA = cast<BlockAddressSDNode>(Op)->getBlockAddress(); 2915 SDValue CPAddr; 2916 bool IsPositionIndependent = isPositionIndependent() || Subtarget->isROPI(); 2917 if (!IsPositionIndependent) { 2918 CPAddr = DAG.getTargetConstantPool(BA, PtrVT, 4); 2919 } else { 2920 unsigned PCAdj = Subtarget->isThumb() ? 4 : 8; 2921 ARMPCLabelIndex = AFI->createPICLabelUId(); 2922 ARMConstantPoolValue *CPV = 2923 ARMConstantPoolConstant::Create(BA, ARMPCLabelIndex, 2924 ARMCP::CPBlockAddress, PCAdj); 2925 CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4); 2926 } 2927 CPAddr = DAG.getNode(ARMISD::Wrapper, DL, PtrVT, CPAddr); 2928 SDValue Result = DAG.getLoad( 2929 PtrVT, DL, DAG.getEntryNode(), CPAddr, 2930 MachinePointerInfo::getConstantPool(DAG.getMachineFunction())); 2931 if (!IsPositionIndependent) 2932 return Result; 2933 SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, DL, MVT::i32); 2934 return DAG.getNode(ARMISD::PIC_ADD, DL, PtrVT, Result, PICLabel); 2935 } 2936 2937 /// Convert a TLS address reference into the correct sequence of loads 2938 /// and calls to compute the variable's address for Darwin, and return an 2939 /// SDValue containing the final node. 2940 2941 /// Darwin only has one TLS scheme which must be capable of dealing with the 2942 /// fully general situation, in the worst case. This means: 2943 /// + "extern __thread" declaration. 2944 /// + Defined in a possibly unknown dynamic library. 2945 /// 2946 /// The general system is that each __thread variable has a [3 x i32] descriptor 2947 /// which contains information used by the runtime to calculate the address. The 2948 /// only part of this the compiler needs to know about is the first word, which 2949 /// contains a function pointer that must be called with the address of the 2950 /// entire descriptor in "r0". 2951 /// 2952 /// Since this descriptor may be in a different unit, in general access must 2953 /// proceed along the usual ARM rules. A common sequence to produce is: 2954 /// 2955 /// movw rT1, :lower16:_var$non_lazy_ptr 2956 /// movt rT1, :upper16:_var$non_lazy_ptr 2957 /// ldr r0, [rT1] 2958 /// ldr rT2, [r0] 2959 /// blx rT2 2960 /// [...address now in r0...] 2961 SDValue 2962 ARMTargetLowering::LowerGlobalTLSAddressDarwin(SDValue Op, 2963 SelectionDAG &DAG) const { 2964 assert(Subtarget->isTargetDarwin() && 2965 "This function expects a Darwin target"); 2966 SDLoc DL(Op); 2967 2968 // First step is to get the address of the actua global symbol. This is where 2969 // the TLS descriptor lives. 2970 SDValue DescAddr = LowerGlobalAddressDarwin(Op, DAG); 2971 2972 // The first entry in the descriptor is a function pointer that we must call 2973 // to obtain the address of the variable. 2974 SDValue Chain = DAG.getEntryNode(); 2975 SDValue FuncTLVGet = DAG.getLoad( 2976 MVT::i32, DL, Chain, DescAddr, 2977 MachinePointerInfo::getGOT(DAG.getMachineFunction()), 2978 /* Alignment = */ 4, 2979 MachineMemOperand::MONonTemporal | MachineMemOperand::MODereferenceable | 2980 MachineMemOperand::MOInvariant); 2981 Chain = FuncTLVGet.getValue(1); 2982 2983 MachineFunction &F = DAG.getMachineFunction(); 2984 MachineFrameInfo &MFI = F.getFrameInfo(); 2985 MFI.setAdjustsStack(true); 2986 2987 // TLS calls preserve all registers except those that absolutely must be 2988 // trashed: R0 (it takes an argument), LR (it's a call) and CPSR (let's not be 2989 // silly). 2990 auto TRI = 2991 getTargetMachine().getSubtargetImpl(F.getFunction())->getRegisterInfo(); 2992 auto ARI = static_cast<const ARMRegisterInfo *>(TRI); 2993 const uint32_t *Mask = ARI->getTLSCallPreservedMask(DAG.getMachineFunction()); 2994 2995 // Finally, we can make the call. This is just a degenerate version of a 2996 // normal AArch64 call node: r0 takes the address of the descriptor, and 2997 // returns the address of the variable in this thread. 2998 Chain = DAG.getCopyToReg(Chain, DL, ARM::R0, DescAddr, SDValue()); 2999 Chain = 3000 DAG.getNode(ARMISD::CALL, DL, DAG.getVTList(MVT::Other, MVT::Glue), 3001 Chain, FuncTLVGet, DAG.getRegister(ARM::R0, MVT::i32), 3002 DAG.getRegisterMask(Mask), Chain.getValue(1)); 3003 return DAG.getCopyFromReg(Chain, DL, ARM::R0, MVT::i32, Chain.getValue(1)); 3004 } 3005 3006 SDValue 3007 ARMTargetLowering::LowerGlobalTLSAddressWindows(SDValue Op, 3008 SelectionDAG &DAG) const { 3009 assert(Subtarget->isTargetWindows() && "Windows specific TLS lowering"); 3010 3011 SDValue Chain = DAG.getEntryNode(); 3012 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 3013 SDLoc DL(Op); 3014 3015 // Load the current TEB (thread environment block) 3016 SDValue Ops[] = {Chain, 3017 DAG.getConstant(Intrinsic::arm_mrc, DL, MVT::i32), 3018 DAG.getConstant(15, DL, MVT::i32), 3019 DAG.getConstant(0, DL, MVT::i32), 3020 DAG.getConstant(13, DL, MVT::i32), 3021 DAG.getConstant(0, DL, MVT::i32), 3022 DAG.getConstant(2, DL, MVT::i32)}; 3023 SDValue CurrentTEB = DAG.getNode(ISD::INTRINSIC_W_CHAIN, DL, 3024 DAG.getVTList(MVT::i32, MVT::Other), Ops); 3025 3026 SDValue TEB = CurrentTEB.getValue(0); 3027 Chain = CurrentTEB.getValue(1); 3028 3029 // Load the ThreadLocalStoragePointer from the TEB 3030 // A pointer to the TLS array is located at offset 0x2c from the TEB. 3031 SDValue TLSArray = 3032 DAG.getNode(ISD::ADD, DL, PtrVT, TEB, DAG.getIntPtrConstant(0x2c, DL)); 3033 TLSArray = DAG.getLoad(PtrVT, DL, Chain, TLSArray, MachinePointerInfo()); 3034 3035 // The pointer to the thread's TLS data area is at the TLS Index scaled by 4 3036 // offset into the TLSArray. 3037 3038 // Load the TLS index from the C runtime 3039 SDValue TLSIndex = 3040 DAG.getTargetExternalSymbol("_tls_index", PtrVT, ARMII::MO_NO_FLAG); 3041 TLSIndex = DAG.getNode(ARMISD::Wrapper, DL, PtrVT, TLSIndex); 3042 TLSIndex = DAG.getLoad(PtrVT, DL, Chain, TLSIndex, MachinePointerInfo()); 3043 3044 SDValue Slot = DAG.getNode(ISD::SHL, DL, PtrVT, TLSIndex, 3045 DAG.getConstant(2, DL, MVT::i32)); 3046 SDValue TLS = DAG.getLoad(PtrVT, DL, Chain, 3047 DAG.getNode(ISD::ADD, DL, PtrVT, TLSArray, Slot), 3048 MachinePointerInfo()); 3049 3050 // Get the offset of the start of the .tls section (section base) 3051 const auto *GA = cast<GlobalAddressSDNode>(Op); 3052 auto *CPV = ARMConstantPoolConstant::Create(GA->getGlobal(), ARMCP::SECREL); 3053 SDValue Offset = DAG.getLoad( 3054 PtrVT, DL, Chain, DAG.getNode(ARMISD::Wrapper, DL, MVT::i32, 3055 DAG.getTargetConstantPool(CPV, PtrVT, 4)), 3056 MachinePointerInfo::getConstantPool(DAG.getMachineFunction())); 3057 3058 return DAG.getNode(ISD::ADD, DL, PtrVT, TLS, Offset); 3059 } 3060 3061 // Lower ISD::GlobalTLSAddress using the "general dynamic" model 3062 SDValue 3063 ARMTargetLowering::LowerToTLSGeneralDynamicModel(GlobalAddressSDNode *GA, 3064 SelectionDAG &DAG) const { 3065 SDLoc dl(GA); 3066 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 3067 unsigned char PCAdj = Subtarget->isThumb() ? 4 : 8; 3068 MachineFunction &MF = DAG.getMachineFunction(); 3069 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>(); 3070 unsigned ARMPCLabelIndex = AFI->createPICLabelUId(); 3071 ARMConstantPoolValue *CPV = 3072 ARMConstantPoolConstant::Create(GA->getGlobal(), ARMPCLabelIndex, 3073 ARMCP::CPValue, PCAdj, ARMCP::TLSGD, true); 3074 SDValue Argument = DAG.getTargetConstantPool(CPV, PtrVT, 4); 3075 Argument = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Argument); 3076 Argument = DAG.getLoad( 3077 PtrVT, dl, DAG.getEntryNode(), Argument, 3078 MachinePointerInfo::getConstantPool(DAG.getMachineFunction())); 3079 SDValue Chain = Argument.getValue(1); 3080 3081 SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, dl, MVT::i32); 3082 Argument = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Argument, PICLabel); 3083 3084 // call __tls_get_addr. 3085 ArgListTy Args; 3086 ArgListEntry Entry; 3087 Entry.Node = Argument; 3088 Entry.Ty = (Type *) Type::getInt32Ty(*DAG.getContext()); 3089 Args.push_back(Entry); 3090 3091 // FIXME: is there useful debug info available here? 3092 TargetLowering::CallLoweringInfo CLI(DAG); 3093 CLI.setDebugLoc(dl).setChain(Chain).setLibCallee( 3094 CallingConv::C, Type::getInt32Ty(*DAG.getContext()), 3095 DAG.getExternalSymbol("__tls_get_addr", PtrVT), std::move(Args)); 3096 3097 std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI); 3098 return CallResult.first; 3099 } 3100 3101 // Lower ISD::GlobalTLSAddress using the "initial exec" or 3102 // "local exec" model. 3103 SDValue 3104 ARMTargetLowering::LowerToTLSExecModels(GlobalAddressSDNode *GA, 3105 SelectionDAG &DAG, 3106 TLSModel::Model model) const { 3107 const GlobalValue *GV = GA->getGlobal(); 3108 SDLoc dl(GA); 3109 SDValue Offset; 3110 SDValue Chain = DAG.getEntryNode(); 3111 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 3112 // Get the Thread Pointer 3113 SDValue ThreadPointer = DAG.getNode(ARMISD::THREAD_POINTER, dl, PtrVT); 3114 3115 if (model == TLSModel::InitialExec) { 3116 MachineFunction &MF = DAG.getMachineFunction(); 3117 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>(); 3118 unsigned ARMPCLabelIndex = AFI->createPICLabelUId(); 3119 // Initial exec model. 3120 unsigned char PCAdj = Subtarget->isThumb() ? 4 : 8; 3121 ARMConstantPoolValue *CPV = 3122 ARMConstantPoolConstant::Create(GA->getGlobal(), ARMPCLabelIndex, 3123 ARMCP::CPValue, PCAdj, ARMCP::GOTTPOFF, 3124 true); 3125 Offset = DAG.getTargetConstantPool(CPV, PtrVT, 4); 3126 Offset = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Offset); 3127 Offset = DAG.getLoad( 3128 PtrVT, dl, Chain, Offset, 3129 MachinePointerInfo::getConstantPool(DAG.getMachineFunction())); 3130 Chain = Offset.getValue(1); 3131 3132 SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, dl, MVT::i32); 3133 Offset = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Offset, PICLabel); 3134 3135 Offset = DAG.getLoad( 3136 PtrVT, dl, Chain, Offset, 3137 MachinePointerInfo::getConstantPool(DAG.getMachineFunction())); 3138 } else { 3139 // local exec model 3140 assert(model == TLSModel::LocalExec); 3141 ARMConstantPoolValue *CPV = 3142 ARMConstantPoolConstant::Create(GV, ARMCP::TPOFF); 3143 Offset = DAG.getTargetConstantPool(CPV, PtrVT, 4); 3144 Offset = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Offset); 3145 Offset = DAG.getLoad( 3146 PtrVT, dl, Chain, Offset, 3147 MachinePointerInfo::getConstantPool(DAG.getMachineFunction())); 3148 } 3149 3150 // The address of the thread local variable is the add of the thread 3151 // pointer with the offset of the variable. 3152 return DAG.getNode(ISD::ADD, dl, PtrVT, ThreadPointer, Offset); 3153 } 3154 3155 SDValue 3156 ARMTargetLowering::LowerGlobalTLSAddress(SDValue Op, SelectionDAG &DAG) const { 3157 GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op); 3158 if (DAG.getTarget().useEmulatedTLS()) 3159 return LowerToTLSEmulatedModel(GA, DAG); 3160 3161 if (Subtarget->isTargetDarwin()) 3162 return LowerGlobalTLSAddressDarwin(Op, DAG); 3163 3164 if (Subtarget->isTargetWindows()) 3165 return LowerGlobalTLSAddressWindows(Op, DAG); 3166 3167 // TODO: implement the "local dynamic" model 3168 assert(Subtarget->isTargetELF() && "Only ELF implemented here"); 3169 TLSModel::Model model = getTargetMachine().getTLSModel(GA->getGlobal()); 3170 3171 switch (model) { 3172 case TLSModel::GeneralDynamic: 3173 case TLSModel::LocalDynamic: 3174 return LowerToTLSGeneralDynamicModel(GA, DAG); 3175 case TLSModel::InitialExec: 3176 case TLSModel::LocalExec: 3177 return LowerToTLSExecModels(GA, DAG, model); 3178 } 3179 llvm_unreachable("bogus TLS model"); 3180 } 3181 3182 /// Return true if all users of V are within function F, looking through 3183 /// ConstantExprs. 3184 static bool allUsersAreInFunction(const Value *V, const Function *F) { 3185 SmallVector<const User*,4> Worklist; 3186 for (auto *U : V->users()) 3187 Worklist.push_back(U); 3188 while (!Worklist.empty()) { 3189 auto *U = Worklist.pop_back_val(); 3190 if (isa<ConstantExpr>(U)) { 3191 for (auto *UU : U->users()) 3192 Worklist.push_back(UU); 3193 continue; 3194 } 3195 3196 auto *I = dyn_cast<Instruction>(U); 3197 if (!I || I->getParent()->getParent() != F) 3198 return false; 3199 } 3200 return true; 3201 } 3202 3203 static SDValue promoteToConstantPool(const ARMTargetLowering *TLI, 3204 const GlobalValue *GV, SelectionDAG &DAG, 3205 EVT PtrVT, const SDLoc &dl) { 3206 // If we're creating a pool entry for a constant global with unnamed address, 3207 // and the global is small enough, we can emit it inline into the constant pool 3208 // to save ourselves an indirection. 3209 // 3210 // This is a win if the constant is only used in one function (so it doesn't 3211 // need to be duplicated) or duplicating the constant wouldn't increase code 3212 // size (implying the constant is no larger than 4 bytes). 3213 const Function &F = DAG.getMachineFunction().getFunction(); 3214 3215 // We rely on this decision to inline being idemopotent and unrelated to the 3216 // use-site. We know that if we inline a variable at one use site, we'll 3217 // inline it elsewhere too (and reuse the constant pool entry). Fast-isel 3218 // doesn't know about this optimization, so bail out if it's enabled else 3219 // we could decide to inline here (and thus never emit the GV) but require 3220 // the GV from fast-isel generated code. 3221 if (!EnableConstpoolPromotion || 3222 DAG.getMachineFunction().getTarget().Options.EnableFastISel) 3223 return SDValue(); 3224 3225 auto *GVar = dyn_cast<GlobalVariable>(GV); 3226 if (!GVar || !GVar->hasInitializer() || 3227 !GVar->isConstant() || !GVar->hasGlobalUnnamedAddr() || 3228 !GVar->hasLocalLinkage()) 3229 return SDValue(); 3230 3231 // If we inline a value that contains relocations, we move the relocations 3232 // from .data to .text. This is not allowed in position-independent code. 3233 auto *Init = GVar->getInitializer(); 3234 if ((TLI->isPositionIndependent() || TLI->getSubtarget()->isROPI()) && 3235 Init->needsRelocation()) 3236 return SDValue(); 3237 3238 // The constant islands pass can only really deal with alignment requests 3239 // <= 4 bytes and cannot pad constants itself. Therefore we cannot promote 3240 // any type wanting greater alignment requirements than 4 bytes. We also 3241 // can only promote constants that are multiples of 4 bytes in size or 3242 // are paddable to a multiple of 4. Currently we only try and pad constants 3243 // that are strings for simplicity. 3244 auto *CDAInit = dyn_cast<ConstantDataArray>(Init); 3245 unsigned Size = DAG.getDataLayout().getTypeAllocSize(Init->getType()); 3246 unsigned Align = DAG.getDataLayout().getPreferredAlignment(GVar); 3247 unsigned RequiredPadding = 4 - (Size % 4); 3248 bool PaddingPossible = 3249 RequiredPadding == 4 || (CDAInit && CDAInit->isString()); 3250 if (!PaddingPossible || Align > 4 || Size > ConstpoolPromotionMaxSize || 3251 Size == 0) 3252 return SDValue(); 3253 3254 unsigned PaddedSize = Size + ((RequiredPadding == 4) ? 0 : RequiredPadding); 3255 MachineFunction &MF = DAG.getMachineFunction(); 3256 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>(); 3257 3258 // We can't bloat the constant pool too much, else the ConstantIslands pass 3259 // may fail to converge. If we haven't promoted this global yet (it may have 3260 // multiple uses), and promoting it would increase the constant pool size (Sz 3261 // > 4), ensure we have space to do so up to MaxTotal. 3262 if (!AFI->getGlobalsPromotedToConstantPool().count(GVar) && Size > 4) 3263 if (AFI->getPromotedConstpoolIncrease() + PaddedSize - 4 >= 3264 ConstpoolPromotionMaxTotal) 3265 return SDValue(); 3266 3267 // This is only valid if all users are in a single function; we can't clone 3268 // the constant in general. The LLVM IR unnamed_addr allows merging 3269 // constants, but not cloning them. 3270 // 3271 // We could potentially allow cloning if we could prove all uses of the 3272 // constant in the current function don't care about the address, like 3273 // printf format strings. But that isn't implemented for now. 3274 if (!allUsersAreInFunction(GVar, &F)) 3275 return SDValue(); 3276 3277 // We're going to inline this global. Pad it out if needed. 3278 if (RequiredPadding != 4) { 3279 StringRef S = CDAInit->getAsString(); 3280 3281 SmallVector<uint8_t,16> V(S.size()); 3282 std::copy(S.bytes_begin(), S.bytes_end(), V.begin()); 3283 while (RequiredPadding--) 3284 V.push_back(0); 3285 Init = ConstantDataArray::get(*DAG.getContext(), V); 3286 } 3287 3288 auto CPVal = ARMConstantPoolConstant::Create(GVar, Init); 3289 SDValue CPAddr = 3290 DAG.getTargetConstantPool(CPVal, PtrVT, /*Align=*/4); 3291 if (!AFI->getGlobalsPromotedToConstantPool().count(GVar)) { 3292 AFI->markGlobalAsPromotedToConstantPool(GVar); 3293 AFI->setPromotedConstpoolIncrease(AFI->getPromotedConstpoolIncrease() + 3294 PaddedSize - 4); 3295 } 3296 ++NumConstpoolPromoted; 3297 return DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr); 3298 } 3299 3300 bool ARMTargetLowering::isReadOnly(const GlobalValue *GV) const { 3301 if (const GlobalAlias *GA = dyn_cast<GlobalAlias>(GV)) 3302 if (!(GV = GA->getBaseObject())) 3303 return false; 3304 if (const auto *V = dyn_cast<GlobalVariable>(GV)) 3305 return V->isConstant(); 3306 return isa<Function>(GV); 3307 } 3308 3309 SDValue ARMTargetLowering::LowerGlobalAddress(SDValue Op, 3310 SelectionDAG &DAG) const { 3311 switch (Subtarget->getTargetTriple().getObjectFormat()) { 3312 default: llvm_unreachable("unknown object format"); 3313 case Triple::COFF: 3314 return LowerGlobalAddressWindows(Op, DAG); 3315 case Triple::ELF: 3316 return LowerGlobalAddressELF(Op, DAG); 3317 case Triple::MachO: 3318 return LowerGlobalAddressDarwin(Op, DAG); 3319 } 3320 } 3321 3322 SDValue ARMTargetLowering::LowerGlobalAddressELF(SDValue Op, 3323 SelectionDAG &DAG) const { 3324 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 3325 SDLoc dl(Op); 3326 const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal(); 3327 const TargetMachine &TM = getTargetMachine(); 3328 bool IsRO = isReadOnly(GV); 3329 3330 // promoteToConstantPool only if not generating XO text section 3331 if (TM.shouldAssumeDSOLocal(*GV->getParent(), GV) && !Subtarget->genExecuteOnly()) 3332 if (SDValue V = promoteToConstantPool(this, GV, DAG, PtrVT, dl)) 3333 return V; 3334 3335 if (isPositionIndependent()) { 3336 bool UseGOT_PREL = !TM.shouldAssumeDSOLocal(*GV->getParent(), GV); 3337 SDValue G = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, 3338 UseGOT_PREL ? ARMII::MO_GOT : 0); 3339 SDValue Result = DAG.getNode(ARMISD::WrapperPIC, dl, PtrVT, G); 3340 if (UseGOT_PREL) 3341 Result = 3342 DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Result, 3343 MachinePointerInfo::getGOT(DAG.getMachineFunction())); 3344 return Result; 3345 } else if (Subtarget->isROPI() && IsRO) { 3346 // PC-relative. 3347 SDValue G = DAG.getTargetGlobalAddress(GV, dl, PtrVT); 3348 SDValue Result = DAG.getNode(ARMISD::WrapperPIC, dl, PtrVT, G); 3349 return Result; 3350 } else if (Subtarget->isRWPI() && !IsRO) { 3351 // SB-relative. 3352 SDValue RelAddr; 3353 if (Subtarget->useMovt()) { 3354 ++NumMovwMovt; 3355 SDValue G = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, ARMII::MO_SBREL); 3356 RelAddr = DAG.getNode(ARMISD::Wrapper, dl, PtrVT, G); 3357 } else { // use literal pool for address constant 3358 ARMConstantPoolValue *CPV = 3359 ARMConstantPoolConstant::Create(GV, ARMCP::SBREL); 3360 SDValue CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4); 3361 CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr); 3362 RelAddr = DAG.getLoad( 3363 PtrVT, dl, DAG.getEntryNode(), CPAddr, 3364 MachinePointerInfo::getConstantPool(DAG.getMachineFunction())); 3365 } 3366 SDValue SB = DAG.getCopyFromReg(DAG.getEntryNode(), dl, ARM::R9, PtrVT); 3367 SDValue Result = DAG.getNode(ISD::ADD, dl, PtrVT, SB, RelAddr); 3368 return Result; 3369 } 3370 3371 // If we have T2 ops, we can materialize the address directly via movt/movw 3372 // pair. This is always cheaper. 3373 if (Subtarget->useMovt()) { 3374 ++NumMovwMovt; 3375 // FIXME: Once remat is capable of dealing with instructions with register 3376 // operands, expand this into two nodes. 3377 return DAG.getNode(ARMISD::Wrapper, dl, PtrVT, 3378 DAG.getTargetGlobalAddress(GV, dl, PtrVT)); 3379 } else { 3380 SDValue CPAddr = DAG.getTargetConstantPool(GV, PtrVT, 4); 3381 CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr); 3382 return DAG.getLoad( 3383 PtrVT, dl, DAG.getEntryNode(), CPAddr, 3384 MachinePointerInfo::getConstantPool(DAG.getMachineFunction())); 3385 } 3386 } 3387 3388 SDValue ARMTargetLowering::LowerGlobalAddressDarwin(SDValue Op, 3389 SelectionDAG &DAG) const { 3390 assert(!Subtarget->isROPI() && !Subtarget->isRWPI() && 3391 "ROPI/RWPI not currently supported for Darwin"); 3392 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 3393 SDLoc dl(Op); 3394 const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal(); 3395 3396 if (Subtarget->useMovt()) 3397 ++NumMovwMovt; 3398 3399 // FIXME: Once remat is capable of dealing with instructions with register 3400 // operands, expand this into multiple nodes 3401 unsigned Wrapper = 3402 isPositionIndependent() ? ARMISD::WrapperPIC : ARMISD::Wrapper; 3403 3404 SDValue G = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, ARMII::MO_NONLAZY); 3405 SDValue Result = DAG.getNode(Wrapper, dl, PtrVT, G); 3406 3407 if (Subtarget->isGVIndirectSymbol(GV)) 3408 Result = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Result, 3409 MachinePointerInfo::getGOT(DAG.getMachineFunction())); 3410 return Result; 3411 } 3412 3413 SDValue ARMTargetLowering::LowerGlobalAddressWindows(SDValue Op, 3414 SelectionDAG &DAG) const { 3415 assert(Subtarget->isTargetWindows() && "non-Windows COFF is not supported"); 3416 assert(Subtarget->useMovt() && 3417 "Windows on ARM expects to use movw/movt"); 3418 assert(!Subtarget->isROPI() && !Subtarget->isRWPI() && 3419 "ROPI/RWPI not currently supported for Windows"); 3420 3421 const TargetMachine &TM = getTargetMachine(); 3422 const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal(); 3423 ARMII::TOF TargetFlags = ARMII::MO_NO_FLAG; 3424 if (GV->hasDLLImportStorageClass()) 3425 TargetFlags = ARMII::MO_DLLIMPORT; 3426 else if (!TM.shouldAssumeDSOLocal(*GV->getParent(), GV)) 3427 TargetFlags = ARMII::MO_COFFSTUB; 3428 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 3429 SDValue Result; 3430 SDLoc DL(Op); 3431 3432 ++NumMovwMovt; 3433 3434 // FIXME: Once remat is capable of dealing with instructions with register 3435 // operands, expand this into two nodes. 3436 Result = DAG.getNode(ARMISD::Wrapper, DL, PtrVT, 3437 DAG.getTargetGlobalAddress(GV, DL, PtrVT, /*Offset=*/0, 3438 TargetFlags)); 3439 if (TargetFlags & (ARMII::MO_DLLIMPORT | ARMII::MO_COFFSTUB)) 3440 Result = DAG.getLoad(PtrVT, DL, DAG.getEntryNode(), Result, 3441 MachinePointerInfo::getGOT(DAG.getMachineFunction())); 3442 return Result; 3443 } 3444 3445 SDValue 3446 ARMTargetLowering::LowerEH_SJLJ_SETJMP(SDValue Op, SelectionDAG &DAG) const { 3447 SDLoc dl(Op); 3448 SDValue Val = DAG.getConstant(0, dl, MVT::i32); 3449 return DAG.getNode(ARMISD::EH_SJLJ_SETJMP, dl, 3450 DAG.getVTList(MVT::i32, MVT::Other), Op.getOperand(0), 3451 Op.getOperand(1), Val); 3452 } 3453 3454 SDValue 3455 ARMTargetLowering::LowerEH_SJLJ_LONGJMP(SDValue Op, SelectionDAG &DAG) const { 3456 SDLoc dl(Op); 3457 return DAG.getNode(ARMISD::EH_SJLJ_LONGJMP, dl, MVT::Other, Op.getOperand(0), 3458 Op.getOperand(1), DAG.getConstant(0, dl, MVT::i32)); 3459 } 3460 3461 SDValue ARMTargetLowering::LowerEH_SJLJ_SETUP_DISPATCH(SDValue Op, 3462 SelectionDAG &DAG) const { 3463 SDLoc dl(Op); 3464 return DAG.getNode(ARMISD::EH_SJLJ_SETUP_DISPATCH, dl, MVT::Other, 3465 Op.getOperand(0)); 3466 } 3467 3468 SDValue 3469 ARMTargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op, SelectionDAG &DAG, 3470 const ARMSubtarget *Subtarget) const { 3471 unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue(); 3472 SDLoc dl(Op); 3473 switch (IntNo) { 3474 default: return SDValue(); // Don't custom lower most intrinsics. 3475 case Intrinsic::thread_pointer: { 3476 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 3477 return DAG.getNode(ARMISD::THREAD_POINTER, dl, PtrVT); 3478 } 3479 case Intrinsic::eh_sjlj_lsda: { 3480 MachineFunction &MF = DAG.getMachineFunction(); 3481 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>(); 3482 unsigned ARMPCLabelIndex = AFI->createPICLabelUId(); 3483 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 3484 SDValue CPAddr; 3485 bool IsPositionIndependent = isPositionIndependent(); 3486 unsigned PCAdj = IsPositionIndependent ? (Subtarget->isThumb() ? 4 : 8) : 0; 3487 ARMConstantPoolValue *CPV = 3488 ARMConstantPoolConstant::Create(&MF.getFunction(), ARMPCLabelIndex, 3489 ARMCP::CPLSDA, PCAdj); 3490 CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4); 3491 CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr); 3492 SDValue Result = DAG.getLoad( 3493 PtrVT, dl, DAG.getEntryNode(), CPAddr, 3494 MachinePointerInfo::getConstantPool(DAG.getMachineFunction())); 3495 3496 if (IsPositionIndependent) { 3497 SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, dl, MVT::i32); 3498 Result = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Result, PICLabel); 3499 } 3500 return Result; 3501 } 3502 case Intrinsic::arm_neon_vabs: 3503 return DAG.getNode(ISD::ABS, SDLoc(Op), Op.getValueType(), 3504 Op.getOperand(1)); 3505 case Intrinsic::arm_neon_vmulls: 3506 case Intrinsic::arm_neon_vmullu: { 3507 unsigned NewOpc = (IntNo == Intrinsic::arm_neon_vmulls) 3508 ? ARMISD::VMULLs : ARMISD::VMULLu; 3509 return DAG.getNode(NewOpc, SDLoc(Op), Op.getValueType(), 3510 Op.getOperand(1), Op.getOperand(2)); 3511 } 3512 case Intrinsic::arm_neon_vminnm: 3513 case Intrinsic::arm_neon_vmaxnm: { 3514 unsigned NewOpc = (IntNo == Intrinsic::arm_neon_vminnm) 3515 ? ISD::FMINNUM : ISD::FMAXNUM; 3516 return DAG.getNode(NewOpc, SDLoc(Op), Op.getValueType(), 3517 Op.getOperand(1), Op.getOperand(2)); 3518 } 3519 case Intrinsic::arm_neon_vminu: 3520 case Intrinsic::arm_neon_vmaxu: { 3521 if (Op.getValueType().isFloatingPoint()) 3522 return SDValue(); 3523 unsigned NewOpc = (IntNo == Intrinsic::arm_neon_vminu) 3524 ? ISD::UMIN : ISD::UMAX; 3525 return DAG.getNode(NewOpc, SDLoc(Op), Op.getValueType(), 3526 Op.getOperand(1), Op.getOperand(2)); 3527 } 3528 case Intrinsic::arm_neon_vmins: 3529 case Intrinsic::arm_neon_vmaxs: { 3530 // v{min,max}s is overloaded between signed integers and floats. 3531 if (!Op.getValueType().isFloatingPoint()) { 3532 unsigned NewOpc = (IntNo == Intrinsic::arm_neon_vmins) 3533 ? ISD::SMIN : ISD::SMAX; 3534 return DAG.getNode(NewOpc, SDLoc(Op), Op.getValueType(), 3535 Op.getOperand(1), Op.getOperand(2)); 3536 } 3537 unsigned NewOpc = (IntNo == Intrinsic::arm_neon_vmins) 3538 ? ISD::FMINIMUM : ISD::FMAXIMUM; 3539 return DAG.getNode(NewOpc, SDLoc(Op), Op.getValueType(), 3540 Op.getOperand(1), Op.getOperand(2)); 3541 } 3542 case Intrinsic::arm_neon_vtbl1: 3543 return DAG.getNode(ARMISD::VTBL1, SDLoc(Op), Op.getValueType(), 3544 Op.getOperand(1), Op.getOperand(2)); 3545 case Intrinsic::arm_neon_vtbl2: 3546 return DAG.getNode(ARMISD::VTBL2, SDLoc(Op), Op.getValueType(), 3547 Op.getOperand(1), Op.getOperand(2), Op.getOperand(3)); 3548 } 3549 } 3550 3551 static SDValue LowerATOMIC_FENCE(SDValue Op, SelectionDAG &DAG, 3552 const ARMSubtarget *Subtarget) { 3553 SDLoc dl(Op); 3554 ConstantSDNode *SSIDNode = cast<ConstantSDNode>(Op.getOperand(2)); 3555 auto SSID = static_cast<SyncScope::ID>(SSIDNode->getZExtValue()); 3556 if (SSID == SyncScope::SingleThread) 3557 return Op; 3558 3559 if (!Subtarget->hasDataBarrier()) { 3560 // Some ARMv6 cpus can support data barriers with an mcr instruction. 3561 // Thumb1 and pre-v6 ARM mode use a libcall instead and should never get 3562 // here. 3563 assert(Subtarget->hasV6Ops() && !Subtarget->isThumb() && 3564 "Unexpected ISD::ATOMIC_FENCE encountered. Should be libcall!"); 3565 return DAG.getNode(ARMISD::MEMBARRIER_MCR, dl, MVT::Other, Op.getOperand(0), 3566 DAG.getConstant(0, dl, MVT::i32)); 3567 } 3568 3569 ConstantSDNode *OrdN = cast<ConstantSDNode>(Op.getOperand(1)); 3570 AtomicOrdering Ord = static_cast<AtomicOrdering>(OrdN->getZExtValue()); 3571 ARM_MB::MemBOpt Domain = ARM_MB::ISH; 3572 if (Subtarget->isMClass()) { 3573 // Only a full system barrier exists in the M-class architectures. 3574 Domain = ARM_MB::SY; 3575 } else if (Subtarget->preferISHSTBarriers() && 3576 Ord == AtomicOrdering::Release) { 3577 // Swift happens to implement ISHST barriers in a way that's compatible with 3578 // Release semantics but weaker than ISH so we'd be fools not to use 3579 // it. Beware: other processors probably don't! 3580 Domain = ARM_MB::ISHST; 3581 } 3582 3583 return DAG.getNode(ISD::INTRINSIC_VOID, dl, MVT::Other, Op.getOperand(0), 3584 DAG.getConstant(Intrinsic::arm_dmb, dl, MVT::i32), 3585 DAG.getConstant(Domain, dl, MVT::i32)); 3586 } 3587 3588 static SDValue LowerPREFETCH(SDValue Op, SelectionDAG &DAG, 3589 const ARMSubtarget *Subtarget) { 3590 // ARM pre v5TE and Thumb1 does not have preload instructions. 3591 if (!(Subtarget->isThumb2() || 3592 (!Subtarget->isThumb1Only() && Subtarget->hasV5TEOps()))) 3593 // Just preserve the chain. 3594 return Op.getOperand(0); 3595 3596 SDLoc dl(Op); 3597 unsigned isRead = ~cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue() & 1; 3598 if (!isRead && 3599 (!Subtarget->hasV7Ops() || !Subtarget->hasMPExtension())) 3600 // ARMv7 with MP extension has PLDW. 3601 return Op.getOperand(0); 3602 3603 unsigned isData = cast<ConstantSDNode>(Op.getOperand(4))->getZExtValue(); 3604 if (Subtarget->isThumb()) { 3605 // Invert the bits. 3606 isRead = ~isRead & 1; 3607 isData = ~isData & 1; 3608 } 3609 3610 return DAG.getNode(ARMISD::PRELOAD, dl, MVT::Other, Op.getOperand(0), 3611 Op.getOperand(1), DAG.getConstant(isRead, dl, MVT::i32), 3612 DAG.getConstant(isData, dl, MVT::i32)); 3613 } 3614 3615 static SDValue LowerVASTART(SDValue Op, SelectionDAG &DAG) { 3616 MachineFunction &MF = DAG.getMachineFunction(); 3617 ARMFunctionInfo *FuncInfo = MF.getInfo<ARMFunctionInfo>(); 3618 3619 // vastart just stores the address of the VarArgsFrameIndex slot into the 3620 // memory location argument. 3621 SDLoc dl(Op); 3622 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout()); 3623 SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT); 3624 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue(); 3625 return DAG.getStore(Op.getOperand(0), dl, FR, Op.getOperand(1), 3626 MachinePointerInfo(SV)); 3627 } 3628 3629 SDValue ARMTargetLowering::GetF64FormalArgument(CCValAssign &VA, 3630 CCValAssign &NextVA, 3631 SDValue &Root, 3632 SelectionDAG &DAG, 3633 const SDLoc &dl) const { 3634 MachineFunction &MF = DAG.getMachineFunction(); 3635 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>(); 3636 3637 const TargetRegisterClass *RC; 3638 if (AFI->isThumb1OnlyFunction()) 3639 RC = &ARM::tGPRRegClass; 3640 else 3641 RC = &ARM::GPRRegClass; 3642 3643 // Transform the arguments stored in physical registers into virtual ones. 3644 unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC); 3645 SDValue ArgValue = DAG.getCopyFromReg(Root, dl, Reg, MVT::i32); 3646 3647 SDValue ArgValue2; 3648 if (NextVA.isMemLoc()) { 3649 MachineFrameInfo &MFI = MF.getFrameInfo(); 3650 int FI = MFI.CreateFixedObject(4, NextVA.getLocMemOffset(), true); 3651 3652 // Create load node to retrieve arguments from the stack. 3653 SDValue FIN = DAG.getFrameIndex(FI, getPointerTy(DAG.getDataLayout())); 3654 ArgValue2 = DAG.getLoad( 3655 MVT::i32, dl, Root, FIN, 3656 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI)); 3657 } else { 3658 Reg = MF.addLiveIn(NextVA.getLocReg(), RC); 3659 ArgValue2 = DAG.getCopyFromReg(Root, dl, Reg, MVT::i32); 3660 } 3661 if (!Subtarget->isLittle()) 3662 std::swap (ArgValue, ArgValue2); 3663 return DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, ArgValue, ArgValue2); 3664 } 3665 3666 // The remaining GPRs hold either the beginning of variable-argument 3667 // data, or the beginning of an aggregate passed by value (usually 3668 // byval). Either way, we allocate stack slots adjacent to the data 3669 // provided by our caller, and store the unallocated registers there. 3670 // If this is a variadic function, the va_list pointer will begin with 3671 // these values; otherwise, this reassembles a (byval) structure that 3672 // was split between registers and memory. 3673 // Return: The frame index registers were stored into. 3674 int ARMTargetLowering::StoreByValRegs(CCState &CCInfo, SelectionDAG &DAG, 3675 const SDLoc &dl, SDValue &Chain, 3676 const Value *OrigArg, 3677 unsigned InRegsParamRecordIdx, 3678 int ArgOffset, unsigned ArgSize) const { 3679 // Currently, two use-cases possible: 3680 // Case #1. Non-var-args function, and we meet first byval parameter. 3681 // Setup first unallocated register as first byval register; 3682 // eat all remained registers 3683 // (these two actions are performed by HandleByVal method). 3684 // Then, here, we initialize stack frame with 3685 // "store-reg" instructions. 3686 // Case #2. Var-args function, that doesn't contain byval parameters. 3687 // The same: eat all remained unallocated registers, 3688 // initialize stack frame. 3689 3690 MachineFunction &MF = DAG.getMachineFunction(); 3691 MachineFrameInfo &MFI = MF.getFrameInfo(); 3692 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>(); 3693 unsigned RBegin, REnd; 3694 if (InRegsParamRecordIdx < CCInfo.getInRegsParamsCount()) { 3695 CCInfo.getInRegsParamInfo(InRegsParamRecordIdx, RBegin, REnd); 3696 } else { 3697 unsigned RBeginIdx = CCInfo.getFirstUnallocated(GPRArgRegs); 3698 RBegin = RBeginIdx == 4 ? (unsigned)ARM::R4 : GPRArgRegs[RBeginIdx]; 3699 REnd = ARM::R4; 3700 } 3701 3702 if (REnd != RBegin) 3703 ArgOffset = -4 * (ARM::R4 - RBegin); 3704 3705 auto PtrVT = getPointerTy(DAG.getDataLayout()); 3706 int FrameIndex = MFI.CreateFixedObject(ArgSize, ArgOffset, false); 3707 SDValue FIN = DAG.getFrameIndex(FrameIndex, PtrVT); 3708 3709 SmallVector<SDValue, 4> MemOps; 3710 const TargetRegisterClass *RC = 3711 AFI->isThumb1OnlyFunction() ? &ARM::tGPRRegClass : &ARM::GPRRegClass; 3712 3713 for (unsigned Reg = RBegin, i = 0; Reg < REnd; ++Reg, ++i) { 3714 unsigned VReg = MF.addLiveIn(Reg, RC); 3715 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i32); 3716 SDValue Store = DAG.getStore(Val.getValue(1), dl, Val, FIN, 3717 MachinePointerInfo(OrigArg, 4 * i)); 3718 MemOps.push_back(Store); 3719 FIN = DAG.getNode(ISD::ADD, dl, PtrVT, FIN, DAG.getConstant(4, dl, PtrVT)); 3720 } 3721 3722 if (!MemOps.empty()) 3723 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOps); 3724 return FrameIndex; 3725 } 3726 3727 // Setup stack frame, the va_list pointer will start from. 3728 void ARMTargetLowering::VarArgStyleRegisters(CCState &CCInfo, SelectionDAG &DAG, 3729 const SDLoc &dl, SDValue &Chain, 3730 unsigned ArgOffset, 3731 unsigned TotalArgRegsSaveSize, 3732 bool ForceMutable) const { 3733 MachineFunction &MF = DAG.getMachineFunction(); 3734 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>(); 3735 3736 // Try to store any remaining integer argument regs 3737 // to their spots on the stack so that they may be loaded by dereferencing 3738 // the result of va_next. 3739 // If there is no regs to be stored, just point address after last 3740 // argument passed via stack. 3741 int FrameIndex = StoreByValRegs(CCInfo, DAG, dl, Chain, nullptr, 3742 CCInfo.getInRegsParamsCount(), 3743 CCInfo.getNextStackOffset(), 3744 std::max(4U, TotalArgRegsSaveSize)); 3745 AFI->setVarArgsFrameIndex(FrameIndex); 3746 } 3747 3748 SDValue ARMTargetLowering::LowerFormalArguments( 3749 SDValue Chain, CallingConv::ID CallConv, bool isVarArg, 3750 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl, 3751 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const { 3752 MachineFunction &MF = DAG.getMachineFunction(); 3753 MachineFrameInfo &MFI = MF.getFrameInfo(); 3754 3755 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>(); 3756 3757 // Assign locations to all of the incoming arguments. 3758 SmallVector<CCValAssign, 16> ArgLocs; 3759 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), ArgLocs, 3760 *DAG.getContext()); 3761 CCInfo.AnalyzeFormalArguments(Ins, CCAssignFnForCall(CallConv, isVarArg)); 3762 3763 SmallVector<SDValue, 16> ArgValues; 3764 SDValue ArgValue; 3765 Function::const_arg_iterator CurOrigArg = MF.getFunction().arg_begin(); 3766 unsigned CurArgIdx = 0; 3767 3768 // Initially ArgRegsSaveSize is zero. 3769 // Then we increase this value each time we meet byval parameter. 3770 // We also increase this value in case of varargs function. 3771 AFI->setArgRegsSaveSize(0); 3772 3773 // Calculate the amount of stack space that we need to allocate to store 3774 // byval and variadic arguments that are passed in registers. 3775 // We need to know this before we allocate the first byval or variadic 3776 // argument, as they will be allocated a stack slot below the CFA (Canonical 3777 // Frame Address, the stack pointer at entry to the function). 3778 unsigned ArgRegBegin = ARM::R4; 3779 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) { 3780 if (CCInfo.getInRegsParamsProcessed() >= CCInfo.getInRegsParamsCount()) 3781 break; 3782 3783 CCValAssign &VA = ArgLocs[i]; 3784 unsigned Index = VA.getValNo(); 3785 ISD::ArgFlagsTy Flags = Ins[Index].Flags; 3786 if (!Flags.isByVal()) 3787 continue; 3788 3789 assert(VA.isMemLoc() && "unexpected byval pointer in reg"); 3790 unsigned RBegin, REnd; 3791 CCInfo.getInRegsParamInfo(CCInfo.getInRegsParamsProcessed(), RBegin, REnd); 3792 ArgRegBegin = std::min(ArgRegBegin, RBegin); 3793 3794 CCInfo.nextInRegsParam(); 3795 } 3796 CCInfo.rewindByValRegsInfo(); 3797 3798 int lastInsIndex = -1; 3799 if (isVarArg && MFI.hasVAStart()) { 3800 unsigned RegIdx = CCInfo.getFirstUnallocated(GPRArgRegs); 3801 if (RegIdx != array_lengthof(GPRArgRegs)) 3802 ArgRegBegin = std::min(ArgRegBegin, (unsigned)GPRArgRegs[RegIdx]); 3803 } 3804 3805 unsigned TotalArgRegsSaveSize = 4 * (ARM::R4 - ArgRegBegin); 3806 AFI->setArgRegsSaveSize(TotalArgRegsSaveSize); 3807 auto PtrVT = getPointerTy(DAG.getDataLayout()); 3808 3809 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) { 3810 CCValAssign &VA = ArgLocs[i]; 3811 if (Ins[VA.getValNo()].isOrigArg()) { 3812 std::advance(CurOrigArg, 3813 Ins[VA.getValNo()].getOrigArgIndex() - CurArgIdx); 3814 CurArgIdx = Ins[VA.getValNo()].getOrigArgIndex(); 3815 } 3816 // Arguments stored in registers. 3817 if (VA.isRegLoc()) { 3818 EVT RegVT = VA.getLocVT(); 3819 3820 if (VA.needsCustom()) { 3821 // f64 and vector types are split up into multiple registers or 3822 // combinations of registers and stack slots. 3823 if (VA.getLocVT() == MVT::v2f64) { 3824 SDValue ArgValue1 = GetF64FormalArgument(VA, ArgLocs[++i], 3825 Chain, DAG, dl); 3826 VA = ArgLocs[++i]; // skip ahead to next loc 3827 SDValue ArgValue2; 3828 if (VA.isMemLoc()) { 3829 int FI = MFI.CreateFixedObject(8, VA.getLocMemOffset(), true); 3830 SDValue FIN = DAG.getFrameIndex(FI, PtrVT); 3831 ArgValue2 = DAG.getLoad(MVT::f64, dl, Chain, FIN, 3832 MachinePointerInfo::getFixedStack( 3833 DAG.getMachineFunction(), FI)); 3834 } else { 3835 ArgValue2 = GetF64FormalArgument(VA, ArgLocs[++i], 3836 Chain, DAG, dl); 3837 } 3838 ArgValue = DAG.getNode(ISD::UNDEF, dl, MVT::v2f64); 3839 ArgValue = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, 3840 ArgValue, ArgValue1, 3841 DAG.getIntPtrConstant(0, dl)); 3842 ArgValue = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, 3843 ArgValue, ArgValue2, 3844 DAG.getIntPtrConstant(1, dl)); 3845 } else 3846 ArgValue = GetF64FormalArgument(VA, ArgLocs[++i], Chain, DAG, dl); 3847 } else { 3848 const TargetRegisterClass *RC; 3849 3850 3851 if (RegVT == MVT::f16) 3852 RC = &ARM::HPRRegClass; 3853 else if (RegVT == MVT::f32) 3854 RC = &ARM::SPRRegClass; 3855 else if (RegVT == MVT::f64 || RegVT == MVT::v4f16) 3856 RC = &ARM::DPRRegClass; 3857 else if (RegVT == MVT::v2f64 || RegVT == MVT::v8f16) 3858 RC = &ARM::QPRRegClass; 3859 else if (RegVT == MVT::i32) 3860 RC = AFI->isThumb1OnlyFunction() ? &ARM::tGPRRegClass 3861 : &ARM::GPRRegClass; 3862 else 3863 llvm_unreachable("RegVT not supported by FORMAL_ARGUMENTS Lowering"); 3864 3865 // Transform the arguments in physical registers into virtual ones. 3866 unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC); 3867 ArgValue = DAG.getCopyFromReg(Chain, dl, Reg, RegVT); 3868 } 3869 3870 // If this is an 8 or 16-bit value, it is really passed promoted 3871 // to 32 bits. Insert an assert[sz]ext to capture this, then 3872 // truncate to the right size. 3873 switch (VA.getLocInfo()) { 3874 default: llvm_unreachable("Unknown loc info!"); 3875 case CCValAssign::Full: break; 3876 case CCValAssign::BCvt: 3877 ArgValue = DAG.getNode(ISD::BITCAST, dl, VA.getValVT(), ArgValue); 3878 break; 3879 case CCValAssign::SExt: 3880 ArgValue = DAG.getNode(ISD::AssertSext, dl, RegVT, ArgValue, 3881 DAG.getValueType(VA.getValVT())); 3882 ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue); 3883 break; 3884 case CCValAssign::ZExt: 3885 ArgValue = DAG.getNode(ISD::AssertZext, dl, RegVT, ArgValue, 3886 DAG.getValueType(VA.getValVT())); 3887 ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue); 3888 break; 3889 } 3890 3891 InVals.push_back(ArgValue); 3892 } else { // VA.isRegLoc() 3893 // sanity check 3894 assert(VA.isMemLoc()); 3895 assert(VA.getValVT() != MVT::i64 && "i64 should already be lowered"); 3896 3897 int index = VA.getValNo(); 3898 3899 // Some Ins[] entries become multiple ArgLoc[] entries. 3900 // Process them only once. 3901 if (index != lastInsIndex) 3902 { 3903 ISD::ArgFlagsTy Flags = Ins[index].Flags; 3904 // FIXME: For now, all byval parameter objects are marked mutable. 3905 // This can be changed with more analysis. 3906 // In case of tail call optimization mark all arguments mutable. 3907 // Since they could be overwritten by lowering of arguments in case of 3908 // a tail call. 3909 if (Flags.isByVal()) { 3910 assert(Ins[index].isOrigArg() && 3911 "Byval arguments cannot be implicit"); 3912 unsigned CurByValIndex = CCInfo.getInRegsParamsProcessed(); 3913 3914 int FrameIndex = StoreByValRegs( 3915 CCInfo, DAG, dl, Chain, &*CurOrigArg, CurByValIndex, 3916 VA.getLocMemOffset(), Flags.getByValSize()); 3917 InVals.push_back(DAG.getFrameIndex(FrameIndex, PtrVT)); 3918 CCInfo.nextInRegsParam(); 3919 } else { 3920 unsigned FIOffset = VA.getLocMemOffset(); 3921 int FI = MFI.CreateFixedObject(VA.getLocVT().getSizeInBits()/8, 3922 FIOffset, true); 3923 3924 // Create load nodes to retrieve arguments from the stack. 3925 SDValue FIN = DAG.getFrameIndex(FI, PtrVT); 3926 InVals.push_back(DAG.getLoad(VA.getValVT(), dl, Chain, FIN, 3927 MachinePointerInfo::getFixedStack( 3928 DAG.getMachineFunction(), FI))); 3929 } 3930 lastInsIndex = index; 3931 } 3932 } 3933 } 3934 3935 // varargs 3936 if (isVarArg && MFI.hasVAStart()) 3937 VarArgStyleRegisters(CCInfo, DAG, dl, Chain, 3938 CCInfo.getNextStackOffset(), 3939 TotalArgRegsSaveSize); 3940 3941 AFI->setArgumentStackSize(CCInfo.getNextStackOffset()); 3942 3943 return Chain; 3944 } 3945 3946 /// isFloatingPointZero - Return true if this is +0.0. 3947 static bool isFloatingPointZero(SDValue Op) { 3948 if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Op)) 3949 return CFP->getValueAPF().isPosZero(); 3950 else if (ISD::isEXTLoad(Op.getNode()) || ISD::isNON_EXTLoad(Op.getNode())) { 3951 // Maybe this has already been legalized into the constant pool? 3952 if (Op.getOperand(1).getOpcode() == ARMISD::Wrapper) { 3953 SDValue WrapperOp = Op.getOperand(1).getOperand(0); 3954 if (ConstantPoolSDNode *CP = dyn_cast<ConstantPoolSDNode>(WrapperOp)) 3955 if (const ConstantFP *CFP = dyn_cast<ConstantFP>(CP->getConstVal())) 3956 return CFP->getValueAPF().isPosZero(); 3957 } 3958 } else if (Op->getOpcode() == ISD::BITCAST && 3959 Op->getValueType(0) == MVT::f64) { 3960 // Handle (ISD::BITCAST (ARMISD::VMOVIMM (ISD::TargetConstant 0)) MVT::f64) 3961 // created by LowerConstantFP(). 3962 SDValue BitcastOp = Op->getOperand(0); 3963 if (BitcastOp->getOpcode() == ARMISD::VMOVIMM && 3964 isNullConstant(BitcastOp->getOperand(0))) 3965 return true; 3966 } 3967 return false; 3968 } 3969 3970 /// Returns appropriate ARM CMP (cmp) and corresponding condition code for 3971 /// the given operands. 3972 SDValue ARMTargetLowering::getARMCmp(SDValue LHS, SDValue RHS, ISD::CondCode CC, 3973 SDValue &ARMcc, SelectionDAG &DAG, 3974 const SDLoc &dl) const { 3975 if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS.getNode())) { 3976 unsigned C = RHSC->getZExtValue(); 3977 if (!isLegalICmpImmediate((int32_t)C)) { 3978 // Constant does not fit, try adjusting it by one. 3979 switch (CC) { 3980 default: break; 3981 case ISD::SETLT: 3982 case ISD::SETGE: 3983 if (C != 0x80000000 && isLegalICmpImmediate(C-1)) { 3984 CC = (CC == ISD::SETLT) ? ISD::SETLE : ISD::SETGT; 3985 RHS = DAG.getConstant(C - 1, dl, MVT::i32); 3986 } 3987 break; 3988 case ISD::SETULT: 3989 case ISD::SETUGE: 3990 if (C != 0 && isLegalICmpImmediate(C-1)) { 3991 CC = (CC == ISD::SETULT) ? ISD::SETULE : ISD::SETUGT; 3992 RHS = DAG.getConstant(C - 1, dl, MVT::i32); 3993 } 3994 break; 3995 case ISD::SETLE: 3996 case ISD::SETGT: 3997 if (C != 0x7fffffff && isLegalICmpImmediate(C+1)) { 3998 CC = (CC == ISD::SETLE) ? ISD::SETLT : ISD::SETGE; 3999 RHS = DAG.getConstant(C + 1, dl, MVT::i32); 4000 } 4001 break; 4002 case ISD::SETULE: 4003 case ISD::SETUGT: 4004 if (C != 0xffffffff && isLegalICmpImmediate(C+1)) { 4005 CC = (CC == ISD::SETULE) ? ISD::SETULT : ISD::SETUGE; 4006 RHS = DAG.getConstant(C + 1, dl, MVT::i32); 4007 } 4008 break; 4009 } 4010 } 4011 } else if ((ARM_AM::getShiftOpcForNode(LHS.getOpcode()) != ARM_AM::no_shift) && 4012 (ARM_AM::getShiftOpcForNode(RHS.getOpcode()) == ARM_AM::no_shift)) { 4013 // In ARM and Thumb-2, the compare instructions can shift their second 4014 // operand. 4015 CC = ISD::getSetCCSwappedOperands(CC); 4016 std::swap(LHS, RHS); 4017 } 4018 4019 ARMCC::CondCodes CondCode = IntCCToARMCC(CC); 4020 ARMISD::NodeType CompareType; 4021 switch (CondCode) { 4022 default: 4023 CompareType = ARMISD::CMP; 4024 break; 4025 case ARMCC::EQ: 4026 case ARMCC::NE: 4027 // Uses only Z Flag 4028 CompareType = ARMISD::CMPZ; 4029 break; 4030 } 4031 ARMcc = DAG.getConstant(CondCode, dl, MVT::i32); 4032 return DAG.getNode(CompareType, dl, MVT::Glue, LHS, RHS); 4033 } 4034 4035 /// Returns a appropriate VFP CMP (fcmp{s|d}+fmstat) for the given operands. 4036 SDValue ARMTargetLowering::getVFPCmp(SDValue LHS, SDValue RHS, 4037 SelectionDAG &DAG, const SDLoc &dl, 4038 bool InvalidOnQNaN) const { 4039 assert(Subtarget->hasFP64() || RHS.getValueType() != MVT::f64); 4040 SDValue Cmp; 4041 SDValue C = DAG.getConstant(InvalidOnQNaN, dl, MVT::i32); 4042 if (!isFloatingPointZero(RHS)) 4043 Cmp = DAG.getNode(ARMISD::CMPFP, dl, MVT::Glue, LHS, RHS, C); 4044 else 4045 Cmp = DAG.getNode(ARMISD::CMPFPw0, dl, MVT::Glue, LHS, C); 4046 return DAG.getNode(ARMISD::FMSTAT, dl, MVT::Glue, Cmp); 4047 } 4048 4049 /// duplicateCmp - Glue values can have only one use, so this function 4050 /// duplicates a comparison node. 4051 SDValue 4052 ARMTargetLowering::duplicateCmp(SDValue Cmp, SelectionDAG &DAG) const { 4053 unsigned Opc = Cmp.getOpcode(); 4054 SDLoc DL(Cmp); 4055 if (Opc == ARMISD::CMP || Opc == ARMISD::CMPZ) 4056 return DAG.getNode(Opc, DL, MVT::Glue, Cmp.getOperand(0),Cmp.getOperand(1)); 4057 4058 assert(Opc == ARMISD::FMSTAT && "unexpected comparison operation"); 4059 Cmp = Cmp.getOperand(0); 4060 Opc = Cmp.getOpcode(); 4061 if (Opc == ARMISD::CMPFP) 4062 Cmp = DAG.getNode(Opc, DL, MVT::Glue, Cmp.getOperand(0), 4063 Cmp.getOperand(1), Cmp.getOperand(2)); 4064 else { 4065 assert(Opc == ARMISD::CMPFPw0 && "unexpected operand of FMSTAT"); 4066 Cmp = DAG.getNode(Opc, DL, MVT::Glue, Cmp.getOperand(0), 4067 Cmp.getOperand(1)); 4068 } 4069 return DAG.getNode(ARMISD::FMSTAT, DL, MVT::Glue, Cmp); 4070 } 4071 4072 // This function returns three things: the arithmetic computation itself 4073 // (Value), a comparison (OverflowCmp), and a condition code (ARMcc). The 4074 // comparison and the condition code define the case in which the arithmetic 4075 // computation *does not* overflow. 4076 std::pair<SDValue, SDValue> 4077 ARMTargetLowering::getARMXALUOOp(SDValue Op, SelectionDAG &DAG, 4078 SDValue &ARMcc) const { 4079 assert(Op.getValueType() == MVT::i32 && "Unsupported value type"); 4080 4081 SDValue Value, OverflowCmp; 4082 SDValue LHS = Op.getOperand(0); 4083 SDValue RHS = Op.getOperand(1); 4084 SDLoc dl(Op); 4085 4086 // FIXME: We are currently always generating CMPs because we don't support 4087 // generating CMN through the backend. This is not as good as the natural 4088 // CMP case because it causes a register dependency and cannot be folded 4089 // later. 4090 4091 switch (Op.getOpcode()) { 4092 default: 4093 llvm_unreachable("Unknown overflow instruction!"); 4094 case ISD::SADDO: 4095 ARMcc = DAG.getConstant(ARMCC::VC, dl, MVT::i32); 4096 Value = DAG.getNode(ISD::ADD, dl, Op.getValueType(), LHS, RHS); 4097 OverflowCmp = DAG.getNode(ARMISD::CMP, dl, MVT::Glue, Value, LHS); 4098 break; 4099 case ISD::UADDO: 4100 ARMcc = DAG.getConstant(ARMCC::HS, dl, MVT::i32); 4101 // We use ADDC here to correspond to its use in LowerUnsignedALUO. 4102 // We do not use it in the USUBO case as Value may not be used. 4103 Value = DAG.getNode(ARMISD::ADDC, dl, 4104 DAG.getVTList(Op.getValueType(), MVT::i32), LHS, RHS) 4105 .getValue(0); 4106 OverflowCmp = DAG.getNode(ARMISD::CMP, dl, MVT::Glue, Value, LHS); 4107 break; 4108 case ISD::SSUBO: 4109 ARMcc = DAG.getConstant(ARMCC::VC, dl, MVT::i32); 4110 Value = DAG.getNode(ISD::SUB, dl, Op.getValueType(), LHS, RHS); 4111 OverflowCmp = DAG.getNode(ARMISD::CMP, dl, MVT::Glue, LHS, RHS); 4112 break; 4113 case ISD::USUBO: 4114 ARMcc = DAG.getConstant(ARMCC::HS, dl, MVT::i32); 4115 Value = DAG.getNode(ISD::SUB, dl, Op.getValueType(), LHS, RHS); 4116 OverflowCmp = DAG.getNode(ARMISD::CMP, dl, MVT::Glue, LHS, RHS); 4117 break; 4118 case ISD::UMULO: 4119 // We generate a UMUL_LOHI and then check if the high word is 0. 4120 ARMcc = DAG.getConstant(ARMCC::EQ, dl, MVT::i32); 4121 Value = DAG.getNode(ISD::UMUL_LOHI, dl, 4122 DAG.getVTList(Op.getValueType(), Op.getValueType()), 4123 LHS, RHS); 4124 OverflowCmp = DAG.getNode(ARMISD::CMP, dl, MVT::Glue, Value.getValue(1), 4125 DAG.getConstant(0, dl, MVT::i32)); 4126 Value = Value.getValue(0); // We only want the low 32 bits for the result. 4127 break; 4128 case ISD::SMULO: 4129 // We generate a SMUL_LOHI and then check if all the bits of the high word 4130 // are the same as the sign bit of the low word. 4131 ARMcc = DAG.getConstant(ARMCC::EQ, dl, MVT::i32); 4132 Value = DAG.getNode(ISD::SMUL_LOHI, dl, 4133 DAG.getVTList(Op.getValueType(), Op.getValueType()), 4134 LHS, RHS); 4135 OverflowCmp = DAG.getNode(ARMISD::CMP, dl, MVT::Glue, Value.getValue(1), 4136 DAG.getNode(ISD::SRA, dl, Op.getValueType(), 4137 Value.getValue(0), 4138 DAG.getConstant(31, dl, MVT::i32))); 4139 Value = Value.getValue(0); // We only want the low 32 bits for the result. 4140 break; 4141 } // switch (...) 4142 4143 return std::make_pair(Value, OverflowCmp); 4144 } 4145 4146 SDValue 4147 ARMTargetLowering::LowerSignedALUO(SDValue Op, SelectionDAG &DAG) const { 4148 // Let legalize expand this if it isn't a legal type yet. 4149 if (!DAG.getTargetLoweringInfo().isTypeLegal(Op.getValueType())) 4150 return SDValue(); 4151 4152 SDValue Value, OverflowCmp; 4153 SDValue ARMcc; 4154 std::tie(Value, OverflowCmp) = getARMXALUOOp(Op, DAG, ARMcc); 4155 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32); 4156 SDLoc dl(Op); 4157 // We use 0 and 1 as false and true values. 4158 SDValue TVal = DAG.getConstant(1, dl, MVT::i32); 4159 SDValue FVal = DAG.getConstant(0, dl, MVT::i32); 4160 EVT VT = Op.getValueType(); 4161 4162 SDValue Overflow = DAG.getNode(ARMISD::CMOV, dl, VT, TVal, FVal, 4163 ARMcc, CCR, OverflowCmp); 4164 4165 SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32); 4166 return DAG.getNode(ISD::MERGE_VALUES, dl, VTs, Value, Overflow); 4167 } 4168 4169 static SDValue ConvertBooleanCarryToCarryFlag(SDValue BoolCarry, 4170 SelectionDAG &DAG) { 4171 SDLoc DL(BoolCarry); 4172 EVT CarryVT = BoolCarry.getValueType(); 4173 4174 // This converts the boolean value carry into the carry flag by doing 4175 // ARMISD::SUBC Carry, 1 4176 SDValue Carry = DAG.getNode(ARMISD::SUBC, DL, 4177 DAG.getVTList(CarryVT, MVT::i32), 4178 BoolCarry, DAG.getConstant(1, DL, CarryVT)); 4179 return Carry.getValue(1); 4180 } 4181 4182 static SDValue ConvertCarryFlagToBooleanCarry(SDValue Flags, EVT VT, 4183 SelectionDAG &DAG) { 4184 SDLoc DL(Flags); 4185 4186 // Now convert the carry flag into a boolean carry. We do this 4187 // using ARMISD:ADDE 0, 0, Carry 4188 return DAG.getNode(ARMISD::ADDE, DL, DAG.getVTList(VT, MVT::i32), 4189 DAG.getConstant(0, DL, MVT::i32), 4190 DAG.getConstant(0, DL, MVT::i32), Flags); 4191 } 4192 4193 SDValue ARMTargetLowering::LowerUnsignedALUO(SDValue Op, 4194 SelectionDAG &DAG) const { 4195 // Let legalize expand this if it isn't a legal type yet. 4196 if (!DAG.getTargetLoweringInfo().isTypeLegal(Op.getValueType())) 4197 return SDValue(); 4198 4199 SDValue LHS = Op.getOperand(0); 4200 SDValue RHS = Op.getOperand(1); 4201 SDLoc dl(Op); 4202 4203 EVT VT = Op.getValueType(); 4204 SDVTList VTs = DAG.getVTList(VT, MVT::i32); 4205 SDValue Value; 4206 SDValue Overflow; 4207 switch (Op.getOpcode()) { 4208 default: 4209 llvm_unreachable("Unknown overflow instruction!"); 4210 case ISD::UADDO: 4211 Value = DAG.getNode(ARMISD::ADDC, dl, VTs, LHS, RHS); 4212 // Convert the carry flag into a boolean value. 4213 Overflow = ConvertCarryFlagToBooleanCarry(Value.getValue(1), VT, DAG); 4214 break; 4215 case ISD::USUBO: { 4216 Value = DAG.getNode(ARMISD::SUBC, dl, VTs, LHS, RHS); 4217 // Convert the carry flag into a boolean value. 4218 Overflow = ConvertCarryFlagToBooleanCarry(Value.getValue(1), VT, DAG); 4219 // ARMISD::SUBC returns 0 when we have to borrow, so make it an overflow 4220 // value. So compute 1 - C. 4221 Overflow = DAG.getNode(ISD::SUB, dl, MVT::i32, 4222 DAG.getConstant(1, dl, MVT::i32), Overflow); 4223 break; 4224 } 4225 } 4226 4227 return DAG.getNode(ISD::MERGE_VALUES, dl, VTs, Value, Overflow); 4228 } 4229 4230 SDValue ARMTargetLowering::LowerSELECT(SDValue Op, SelectionDAG &DAG) const { 4231 SDValue Cond = Op.getOperand(0); 4232 SDValue SelectTrue = Op.getOperand(1); 4233 SDValue SelectFalse = Op.getOperand(2); 4234 SDLoc dl(Op); 4235 unsigned Opc = Cond.getOpcode(); 4236 4237 if (Cond.getResNo() == 1 && 4238 (Opc == ISD::SADDO || Opc == ISD::UADDO || Opc == ISD::SSUBO || 4239 Opc == ISD::USUBO)) { 4240 if (!DAG.getTargetLoweringInfo().isTypeLegal(Cond->getValueType(0))) 4241 return SDValue(); 4242 4243 SDValue Value, OverflowCmp; 4244 SDValue ARMcc; 4245 std::tie(Value, OverflowCmp) = getARMXALUOOp(Cond, DAG, ARMcc); 4246 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32); 4247 EVT VT = Op.getValueType(); 4248 4249 return getCMOV(dl, VT, SelectTrue, SelectFalse, ARMcc, CCR, 4250 OverflowCmp, DAG); 4251 } 4252 4253 // Convert: 4254 // 4255 // (select (cmov 1, 0, cond), t, f) -> (cmov t, f, cond) 4256 // (select (cmov 0, 1, cond), t, f) -> (cmov f, t, cond) 4257 // 4258 if (Cond.getOpcode() == ARMISD::CMOV && Cond.hasOneUse()) { 4259 const ConstantSDNode *CMOVTrue = 4260 dyn_cast<ConstantSDNode>(Cond.getOperand(0)); 4261 const ConstantSDNode *CMOVFalse = 4262 dyn_cast<ConstantSDNode>(Cond.getOperand(1)); 4263 4264 if (CMOVTrue && CMOVFalse) { 4265 unsigned CMOVTrueVal = CMOVTrue->getZExtValue(); 4266 unsigned CMOVFalseVal = CMOVFalse->getZExtValue(); 4267 4268 SDValue True; 4269 SDValue False; 4270 if (CMOVTrueVal == 1 && CMOVFalseVal == 0) { 4271 True = SelectTrue; 4272 False = SelectFalse; 4273 } else if (CMOVTrueVal == 0 && CMOVFalseVal == 1) { 4274 True = SelectFalse; 4275 False = SelectTrue; 4276 } 4277 4278 if (True.getNode() && False.getNode()) { 4279 EVT VT = Op.getValueType(); 4280 SDValue ARMcc = Cond.getOperand(2); 4281 SDValue CCR = Cond.getOperand(3); 4282 SDValue Cmp = duplicateCmp(Cond.getOperand(4), DAG); 4283 assert(True.getValueType() == VT); 4284 return getCMOV(dl, VT, True, False, ARMcc, CCR, Cmp, DAG); 4285 } 4286 } 4287 } 4288 4289 // ARM's BooleanContents value is UndefinedBooleanContent. Mask out the 4290 // undefined bits before doing a full-word comparison with zero. 4291 Cond = DAG.getNode(ISD::AND, dl, Cond.getValueType(), Cond, 4292 DAG.getConstant(1, dl, Cond.getValueType())); 4293 4294 return DAG.getSelectCC(dl, Cond, 4295 DAG.getConstant(0, dl, Cond.getValueType()), 4296 SelectTrue, SelectFalse, ISD::SETNE); 4297 } 4298 4299 static void checkVSELConstraints(ISD::CondCode CC, ARMCC::CondCodes &CondCode, 4300 bool &swpCmpOps, bool &swpVselOps) { 4301 // Start by selecting the GE condition code for opcodes that return true for 4302 // 'equality' 4303 if (CC == ISD::SETUGE || CC == ISD::SETOGE || CC == ISD::SETOLE || 4304 CC == ISD::SETULE || CC == ISD::SETGE || CC == ISD::SETLE) 4305 CondCode = ARMCC::GE; 4306 4307 // and GT for opcodes that return false for 'equality'. 4308 else if (CC == ISD::SETUGT || CC == ISD::SETOGT || CC == ISD::SETOLT || 4309 CC == ISD::SETULT || CC == ISD::SETGT || CC == ISD::SETLT) 4310 CondCode = ARMCC::GT; 4311 4312 // Since we are constrained to GE/GT, if the opcode contains 'less', we need 4313 // to swap the compare operands. 4314 if (CC == ISD::SETOLE || CC == ISD::SETULE || CC == ISD::SETOLT || 4315 CC == ISD::SETULT || CC == ISD::SETLE || CC == ISD::SETLT) 4316 swpCmpOps = true; 4317 4318 // Both GT and GE are ordered comparisons, and return false for 'unordered'. 4319 // If we have an unordered opcode, we need to swap the operands to the VSEL 4320 // instruction (effectively negating the condition). 4321 // 4322 // This also has the effect of swapping which one of 'less' or 'greater' 4323 // returns true, so we also swap the compare operands. It also switches 4324 // whether we return true for 'equality', so we compensate by picking the 4325 // opposite condition code to our original choice. 4326 if (CC == ISD::SETULE || CC == ISD::SETULT || CC == ISD::SETUGE || 4327 CC == ISD::SETUGT) { 4328 swpCmpOps = !swpCmpOps; 4329 swpVselOps = !swpVselOps; 4330 CondCode = CondCode == ARMCC::GT ? ARMCC::GE : ARMCC::GT; 4331 } 4332 4333 // 'ordered' is 'anything but unordered', so use the VS condition code and 4334 // swap the VSEL operands. 4335 if (CC == ISD::SETO) { 4336 CondCode = ARMCC::VS; 4337 swpVselOps = true; 4338 } 4339 4340 // 'unordered or not equal' is 'anything but equal', so use the EQ condition 4341 // code and swap the VSEL operands. Also do this if we don't care about the 4342 // unordered case. 4343 if (CC == ISD::SETUNE || CC == ISD::SETNE) { 4344 CondCode = ARMCC::EQ; 4345 swpVselOps = true; 4346 } 4347 } 4348 4349 SDValue ARMTargetLowering::getCMOV(const SDLoc &dl, EVT VT, SDValue FalseVal, 4350 SDValue TrueVal, SDValue ARMcc, SDValue CCR, 4351 SDValue Cmp, SelectionDAG &DAG) const { 4352 if (!Subtarget->hasFP64() && VT == MVT::f64) { 4353 FalseVal = DAG.getNode(ARMISD::VMOVRRD, dl, 4354 DAG.getVTList(MVT::i32, MVT::i32), FalseVal); 4355 TrueVal = DAG.getNode(ARMISD::VMOVRRD, dl, 4356 DAG.getVTList(MVT::i32, MVT::i32), TrueVal); 4357 4358 SDValue TrueLow = TrueVal.getValue(0); 4359 SDValue TrueHigh = TrueVal.getValue(1); 4360 SDValue FalseLow = FalseVal.getValue(0); 4361 SDValue FalseHigh = FalseVal.getValue(1); 4362 4363 SDValue Low = DAG.getNode(ARMISD::CMOV, dl, MVT::i32, FalseLow, TrueLow, 4364 ARMcc, CCR, Cmp); 4365 SDValue High = DAG.getNode(ARMISD::CMOV, dl, MVT::i32, FalseHigh, TrueHigh, 4366 ARMcc, CCR, duplicateCmp(Cmp, DAG)); 4367 4368 return DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Low, High); 4369 } else { 4370 return DAG.getNode(ARMISD::CMOV, dl, VT, FalseVal, TrueVal, ARMcc, CCR, 4371 Cmp); 4372 } 4373 } 4374 4375 static bool isGTorGE(ISD::CondCode CC) { 4376 return CC == ISD::SETGT || CC == ISD::SETGE; 4377 } 4378 4379 static bool isLTorLE(ISD::CondCode CC) { 4380 return CC == ISD::SETLT || CC == ISD::SETLE; 4381 } 4382 4383 // See if a conditional (LHS CC RHS ? TrueVal : FalseVal) is lower-saturating. 4384 // All of these conditions (and their <= and >= counterparts) will do: 4385 // x < k ? k : x 4386 // x > k ? x : k 4387 // k < x ? x : k 4388 // k > x ? k : x 4389 static bool isLowerSaturate(const SDValue LHS, const SDValue RHS, 4390 const SDValue TrueVal, const SDValue FalseVal, 4391 const ISD::CondCode CC, const SDValue K) { 4392 return (isGTorGE(CC) && 4393 ((K == LHS && K == TrueVal) || (K == RHS && K == FalseVal))) || 4394 (isLTorLE(CC) && 4395 ((K == RHS && K == TrueVal) || (K == LHS && K == FalseVal))); 4396 } 4397 4398 // Similar to isLowerSaturate(), but checks for upper-saturating conditions. 4399 static bool isUpperSaturate(const SDValue LHS, const SDValue RHS, 4400 const SDValue TrueVal, const SDValue FalseVal, 4401 const ISD::CondCode CC, const SDValue K) { 4402 return (isGTorGE(CC) && 4403 ((K == RHS && K == TrueVal) || (K == LHS && K == FalseVal))) || 4404 (isLTorLE(CC) && 4405 ((K == LHS && K == TrueVal) || (K == RHS && K == FalseVal))); 4406 } 4407 4408 // Check if two chained conditionals could be converted into SSAT or USAT. 4409 // 4410 // SSAT can replace a set of two conditional selectors that bound a number to an 4411 // interval of type [k, ~k] when k + 1 is a power of 2. Here are some examples: 4412 // 4413 // x < -k ? -k : (x > k ? k : x) 4414 // x < -k ? -k : (x < k ? x : k) 4415 // x > -k ? (x > k ? k : x) : -k 4416 // x < k ? (x < -k ? -k : x) : k 4417 // etc. 4418 // 4419 // USAT works similarily to SSAT but bounds on the interval [0, k] where k + 1 is 4420 // a power of 2. 4421 // 4422 // It returns true if the conversion can be done, false otherwise. 4423 // Additionally, the variable is returned in parameter V, the constant in K and 4424 // usat is set to true if the conditional represents an unsigned saturation 4425 static bool isSaturatingConditional(const SDValue &Op, SDValue &V, 4426 uint64_t &K, bool &usat) { 4427 SDValue LHS1 = Op.getOperand(0); 4428 SDValue RHS1 = Op.getOperand(1); 4429 SDValue TrueVal1 = Op.getOperand(2); 4430 SDValue FalseVal1 = Op.getOperand(3); 4431 ISD::CondCode CC1 = cast<CondCodeSDNode>(Op.getOperand(4))->get(); 4432 4433 const SDValue Op2 = isa<ConstantSDNode>(TrueVal1) ? FalseVal1 : TrueVal1; 4434 if (Op2.getOpcode() != ISD::SELECT_CC) 4435 return false; 4436 4437 SDValue LHS2 = Op2.getOperand(0); 4438 SDValue RHS2 = Op2.getOperand(1); 4439 SDValue TrueVal2 = Op2.getOperand(2); 4440 SDValue FalseVal2 = Op2.getOperand(3); 4441 ISD::CondCode CC2 = cast<CondCodeSDNode>(Op2.getOperand(4))->get(); 4442 4443 // Find out which are the constants and which are the variables 4444 // in each conditional 4445 SDValue *K1 = isa<ConstantSDNode>(LHS1) ? &LHS1 : isa<ConstantSDNode>(RHS1) 4446 ? &RHS1 4447 : nullptr; 4448 SDValue *K2 = isa<ConstantSDNode>(LHS2) ? &LHS2 : isa<ConstantSDNode>(RHS2) 4449 ? &RHS2 4450 : nullptr; 4451 SDValue K2Tmp = isa<ConstantSDNode>(TrueVal2) ? TrueVal2 : FalseVal2; 4452 SDValue V1Tmp = (K1 && *K1 == LHS1) ? RHS1 : LHS1; 4453 SDValue V2Tmp = (K2 && *K2 == LHS2) ? RHS2 : LHS2; 4454 SDValue V2 = (K2Tmp == TrueVal2) ? FalseVal2 : TrueVal2; 4455 4456 // We must detect cases where the original operations worked with 16- or 4457 // 8-bit values. In such case, V2Tmp != V2 because the comparison operations 4458 // must work with sign-extended values but the select operations return 4459 // the original non-extended value. 4460 SDValue V2TmpReg = V2Tmp; 4461 if (V2Tmp->getOpcode() == ISD::SIGN_EXTEND_INREG) 4462 V2TmpReg = V2Tmp->getOperand(0); 4463 4464 // Check that the registers and the constants have the correct values 4465 // in both conditionals 4466 if (!K1 || !K2 || *K1 == Op2 || *K2 != K2Tmp || V1Tmp != V2Tmp || 4467 V2TmpReg != V2) 4468 return false; 4469 4470 // Figure out which conditional is saturating the lower/upper bound. 4471 const SDValue *LowerCheckOp = 4472 isLowerSaturate(LHS1, RHS1, TrueVal1, FalseVal1, CC1, *K1) 4473 ? &Op 4474 : isLowerSaturate(LHS2, RHS2, TrueVal2, FalseVal2, CC2, *K2) 4475 ? &Op2 4476 : nullptr; 4477 const SDValue *UpperCheckOp = 4478 isUpperSaturate(LHS1, RHS1, TrueVal1, FalseVal1, CC1, *K1) 4479 ? &Op 4480 : isUpperSaturate(LHS2, RHS2, TrueVal2, FalseVal2, CC2, *K2) 4481 ? &Op2 4482 : nullptr; 4483 4484 if (!UpperCheckOp || !LowerCheckOp || LowerCheckOp == UpperCheckOp) 4485 return false; 4486 4487 // Check that the constant in the lower-bound check is 4488 // the opposite of the constant in the upper-bound check 4489 // in 1's complement. 4490 int64_t Val1 = cast<ConstantSDNode>(*K1)->getSExtValue(); 4491 int64_t Val2 = cast<ConstantSDNode>(*K2)->getSExtValue(); 4492 int64_t PosVal = std::max(Val1, Val2); 4493 int64_t NegVal = std::min(Val1, Val2); 4494 4495 if (((Val1 > Val2 && UpperCheckOp == &Op) || 4496 (Val1 < Val2 && UpperCheckOp == &Op2)) && 4497 isPowerOf2_64(PosVal + 1)) { 4498 4499 // Handle the difference between USAT (unsigned) and SSAT (signed) saturation 4500 if (Val1 == ~Val2) 4501 usat = false; 4502 else if (NegVal == 0) 4503 usat = true; 4504 else 4505 return false; 4506 4507 V = V2; 4508 K = (uint64_t)PosVal; // At this point, PosVal is guaranteed to be positive 4509 4510 return true; 4511 } 4512 4513 return false; 4514 } 4515 4516 // Check if a condition of the type x < k ? k : x can be converted into a 4517 // bit operation instead of conditional moves. 4518 // Currently this is allowed given: 4519 // - The conditions and values match up 4520 // - k is 0 or -1 (all ones) 4521 // This function will not check the last condition, thats up to the caller 4522 // It returns true if the transformation can be made, and in such case 4523 // returns x in V, and k in SatK. 4524 static bool isLowerSaturatingConditional(const SDValue &Op, SDValue &V, 4525 SDValue &SatK) 4526 { 4527 SDValue LHS = Op.getOperand(0); 4528 SDValue RHS = Op.getOperand(1); 4529 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(4))->get(); 4530 SDValue TrueVal = Op.getOperand(2); 4531 SDValue FalseVal = Op.getOperand(3); 4532 4533 SDValue *K = isa<ConstantSDNode>(LHS) ? &LHS : isa<ConstantSDNode>(RHS) 4534 ? &RHS 4535 : nullptr; 4536 4537 // No constant operation in comparison, early out 4538 if (!K) 4539 return false; 4540 4541 SDValue KTmp = isa<ConstantSDNode>(TrueVal) ? TrueVal : FalseVal; 4542 V = (KTmp == TrueVal) ? FalseVal : TrueVal; 4543 SDValue VTmp = (K && *K == LHS) ? RHS : LHS; 4544 4545 // If the constant on left and right side, or variable on left and right, 4546 // does not match, early out 4547 if (*K != KTmp || V != VTmp) 4548 return false; 4549 4550 if (isLowerSaturate(LHS, RHS, TrueVal, FalseVal, CC, *K)) { 4551 SatK = *K; 4552 return true; 4553 } 4554 4555 return false; 4556 } 4557 4558 bool ARMTargetLowering::isUnsupportedFloatingType(EVT VT) const { 4559 if (VT == MVT::f32) 4560 return !Subtarget->hasVFP2Base(); 4561 if (VT == MVT::f64) 4562 return !Subtarget->hasFP64(); 4563 if (VT == MVT::f16) 4564 return !Subtarget->hasFullFP16(); 4565 return false; 4566 } 4567 4568 SDValue ARMTargetLowering::LowerSELECT_CC(SDValue Op, SelectionDAG &DAG) const { 4569 EVT VT = Op.getValueType(); 4570 SDLoc dl(Op); 4571 4572 // Try to convert two saturating conditional selects into a single SSAT 4573 SDValue SatValue; 4574 uint64_t SatConstant; 4575 bool SatUSat; 4576 if (((!Subtarget->isThumb() && Subtarget->hasV6Ops()) || Subtarget->isThumb2()) && 4577 isSaturatingConditional(Op, SatValue, SatConstant, SatUSat)) { 4578 if (SatUSat) 4579 return DAG.getNode(ARMISD::USAT, dl, VT, SatValue, 4580 DAG.getConstant(countTrailingOnes(SatConstant), dl, VT)); 4581 else 4582 return DAG.getNode(ARMISD::SSAT, dl, VT, SatValue, 4583 DAG.getConstant(countTrailingOnes(SatConstant), dl, VT)); 4584 } 4585 4586 // Try to convert expressions of the form x < k ? k : x (and similar forms) 4587 // into more efficient bit operations, which is possible when k is 0 or -1 4588 // On ARM and Thumb-2 which have flexible operand 2 this will result in 4589 // single instructions. On Thumb the shift and the bit operation will be two 4590 // instructions. 4591 // Only allow this transformation on full-width (32-bit) operations 4592 SDValue LowerSatConstant; 4593 if (VT == MVT::i32 && 4594 isLowerSaturatingConditional(Op, SatValue, LowerSatConstant)) { 4595 SDValue ShiftV = DAG.getNode(ISD::SRA, dl, VT, SatValue, 4596 DAG.getConstant(31, dl, VT)); 4597 if (isNullConstant(LowerSatConstant)) { 4598 SDValue NotShiftV = DAG.getNode(ISD::XOR, dl, VT, ShiftV, 4599 DAG.getAllOnesConstant(dl, VT)); 4600 return DAG.getNode(ISD::AND, dl, VT, SatValue, NotShiftV); 4601 } else if (isAllOnesConstant(LowerSatConstant)) 4602 return DAG.getNode(ISD::OR, dl, VT, SatValue, ShiftV); 4603 } 4604 4605 SDValue LHS = Op.getOperand(0); 4606 SDValue RHS = Op.getOperand(1); 4607 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(4))->get(); 4608 SDValue TrueVal = Op.getOperand(2); 4609 SDValue FalseVal = Op.getOperand(3); 4610 4611 if (isUnsupportedFloatingType(LHS.getValueType())) { 4612 DAG.getTargetLoweringInfo().softenSetCCOperands( 4613 DAG, LHS.getValueType(), LHS, RHS, CC, dl); 4614 4615 // If softenSetCCOperands only returned one value, we should compare it to 4616 // zero. 4617 if (!RHS.getNode()) { 4618 RHS = DAG.getConstant(0, dl, LHS.getValueType()); 4619 CC = ISD::SETNE; 4620 } 4621 } 4622 4623 if (LHS.getValueType() == MVT::i32) { 4624 // Try to generate VSEL on ARMv8. 4625 // The VSEL instruction can't use all the usual ARM condition 4626 // codes: it only has two bits to select the condition code, so it's 4627 // constrained to use only GE, GT, VS and EQ. 4628 // 4629 // To implement all the various ISD::SETXXX opcodes, we sometimes need to 4630 // swap the operands of the previous compare instruction (effectively 4631 // inverting the compare condition, swapping 'less' and 'greater') and 4632 // sometimes need to swap the operands to the VSEL (which inverts the 4633 // condition in the sense of firing whenever the previous condition didn't) 4634 if (Subtarget->hasFPARMv8Base() && (TrueVal.getValueType() == MVT::f16 || 4635 TrueVal.getValueType() == MVT::f32 || 4636 TrueVal.getValueType() == MVT::f64)) { 4637 ARMCC::CondCodes CondCode = IntCCToARMCC(CC); 4638 if (CondCode == ARMCC::LT || CondCode == ARMCC::LE || 4639 CondCode == ARMCC::VC || CondCode == ARMCC::NE) { 4640 CC = ISD::getSetCCInverse(CC, true); 4641 std::swap(TrueVal, FalseVal); 4642 } 4643 } 4644 4645 SDValue ARMcc; 4646 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32); 4647 SDValue Cmp = getARMCmp(LHS, RHS, CC, ARMcc, DAG, dl); 4648 return getCMOV(dl, VT, FalseVal, TrueVal, ARMcc, CCR, Cmp, DAG); 4649 } 4650 4651 ARMCC::CondCodes CondCode, CondCode2; 4652 bool InvalidOnQNaN; 4653 FPCCToARMCC(CC, CondCode, CondCode2, InvalidOnQNaN); 4654 4655 // Normalize the fp compare. If RHS is zero we prefer to keep it there so we 4656 // match CMPFPw0 instead of CMPFP, though we don't do this for f16 because we 4657 // must use VSEL (limited condition codes), due to not having conditional f16 4658 // moves. 4659 if (Subtarget->hasFPARMv8Base() && 4660 !(isFloatingPointZero(RHS) && TrueVal.getValueType() != MVT::f16) && 4661 (TrueVal.getValueType() == MVT::f16 || 4662 TrueVal.getValueType() == MVT::f32 || 4663 TrueVal.getValueType() == MVT::f64)) { 4664 bool swpCmpOps = false; 4665 bool swpVselOps = false; 4666 checkVSELConstraints(CC, CondCode, swpCmpOps, swpVselOps); 4667 4668 if (CondCode == ARMCC::GT || CondCode == ARMCC::GE || 4669 CondCode == ARMCC::VS || CondCode == ARMCC::EQ) { 4670 if (swpCmpOps) 4671 std::swap(LHS, RHS); 4672 if (swpVselOps) 4673 std::swap(TrueVal, FalseVal); 4674 } 4675 } 4676 4677 SDValue ARMcc = DAG.getConstant(CondCode, dl, MVT::i32); 4678 SDValue Cmp = getVFPCmp(LHS, RHS, DAG, dl, InvalidOnQNaN); 4679 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32); 4680 SDValue Result = getCMOV(dl, VT, FalseVal, TrueVal, ARMcc, CCR, Cmp, DAG); 4681 if (CondCode2 != ARMCC::AL) { 4682 SDValue ARMcc2 = DAG.getConstant(CondCode2, dl, MVT::i32); 4683 // FIXME: Needs another CMP because flag can have but one use. 4684 SDValue Cmp2 = getVFPCmp(LHS, RHS, DAG, dl, InvalidOnQNaN); 4685 Result = getCMOV(dl, VT, Result, TrueVal, ARMcc2, CCR, Cmp2, DAG); 4686 } 4687 return Result; 4688 } 4689 4690 /// canChangeToInt - Given the fp compare operand, return true if it is suitable 4691 /// to morph to an integer compare sequence. 4692 static bool canChangeToInt(SDValue Op, bool &SeenZero, 4693 const ARMSubtarget *Subtarget) { 4694 SDNode *N = Op.getNode(); 4695 if (!N->hasOneUse()) 4696 // Otherwise it requires moving the value from fp to integer registers. 4697 return false; 4698 if (!N->getNumValues()) 4699 return false; 4700 EVT VT = Op.getValueType(); 4701 if (VT != MVT::f32 && !Subtarget->isFPBrccSlow()) 4702 // f32 case is generally profitable. f64 case only makes sense when vcmpe + 4703 // vmrs are very slow, e.g. cortex-a8. 4704 return false; 4705 4706 if (isFloatingPointZero(Op)) { 4707 SeenZero = true; 4708 return true; 4709 } 4710 return ISD::isNormalLoad(N); 4711 } 4712 4713 static SDValue bitcastf32Toi32(SDValue Op, SelectionDAG &DAG) { 4714 if (isFloatingPointZero(Op)) 4715 return DAG.getConstant(0, SDLoc(Op), MVT::i32); 4716 4717 if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Op)) 4718 return DAG.getLoad(MVT::i32, SDLoc(Op), Ld->getChain(), Ld->getBasePtr(), 4719 Ld->getPointerInfo(), Ld->getAlignment(), 4720 Ld->getMemOperand()->getFlags()); 4721 4722 llvm_unreachable("Unknown VFP cmp argument!"); 4723 } 4724 4725 static void expandf64Toi32(SDValue Op, SelectionDAG &DAG, 4726 SDValue &RetVal1, SDValue &RetVal2) { 4727 SDLoc dl(Op); 4728 4729 if (isFloatingPointZero(Op)) { 4730 RetVal1 = DAG.getConstant(0, dl, MVT::i32); 4731 RetVal2 = DAG.getConstant(0, dl, MVT::i32); 4732 return; 4733 } 4734 4735 if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Op)) { 4736 SDValue Ptr = Ld->getBasePtr(); 4737 RetVal1 = 4738 DAG.getLoad(MVT::i32, dl, Ld->getChain(), Ptr, Ld->getPointerInfo(), 4739 Ld->getAlignment(), Ld->getMemOperand()->getFlags()); 4740 4741 EVT PtrType = Ptr.getValueType(); 4742 unsigned NewAlign = MinAlign(Ld->getAlignment(), 4); 4743 SDValue NewPtr = DAG.getNode(ISD::ADD, dl, 4744 PtrType, Ptr, DAG.getConstant(4, dl, PtrType)); 4745 RetVal2 = DAG.getLoad(MVT::i32, dl, Ld->getChain(), NewPtr, 4746 Ld->getPointerInfo().getWithOffset(4), NewAlign, 4747 Ld->getMemOperand()->getFlags()); 4748 return; 4749 } 4750 4751 llvm_unreachable("Unknown VFP cmp argument!"); 4752 } 4753 4754 /// OptimizeVFPBrcond - With -enable-unsafe-fp-math, it's legal to optimize some 4755 /// f32 and even f64 comparisons to integer ones. 4756 SDValue 4757 ARMTargetLowering::OptimizeVFPBrcond(SDValue Op, SelectionDAG &DAG) const { 4758 SDValue Chain = Op.getOperand(0); 4759 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(1))->get(); 4760 SDValue LHS = Op.getOperand(2); 4761 SDValue RHS = Op.getOperand(3); 4762 SDValue Dest = Op.getOperand(4); 4763 SDLoc dl(Op); 4764 4765 bool LHSSeenZero = false; 4766 bool LHSOk = canChangeToInt(LHS, LHSSeenZero, Subtarget); 4767 bool RHSSeenZero = false; 4768 bool RHSOk = canChangeToInt(RHS, RHSSeenZero, Subtarget); 4769 if (LHSOk && RHSOk && (LHSSeenZero || RHSSeenZero)) { 4770 // If unsafe fp math optimization is enabled and there are no other uses of 4771 // the CMP operands, and the condition code is EQ or NE, we can optimize it 4772 // to an integer comparison. 4773 if (CC == ISD::SETOEQ) 4774 CC = ISD::SETEQ; 4775 else if (CC == ISD::SETUNE) 4776 CC = ISD::SETNE; 4777 4778 SDValue Mask = DAG.getConstant(0x7fffffff, dl, MVT::i32); 4779 SDValue ARMcc; 4780 if (LHS.getValueType() == MVT::f32) { 4781 LHS = DAG.getNode(ISD::AND, dl, MVT::i32, 4782 bitcastf32Toi32(LHS, DAG), Mask); 4783 RHS = DAG.getNode(ISD::AND, dl, MVT::i32, 4784 bitcastf32Toi32(RHS, DAG), Mask); 4785 SDValue Cmp = getARMCmp(LHS, RHS, CC, ARMcc, DAG, dl); 4786 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32); 4787 return DAG.getNode(ARMISD::BRCOND, dl, MVT::Other, 4788 Chain, Dest, ARMcc, CCR, Cmp); 4789 } 4790 4791 SDValue LHS1, LHS2; 4792 SDValue RHS1, RHS2; 4793 expandf64Toi32(LHS, DAG, LHS1, LHS2); 4794 expandf64Toi32(RHS, DAG, RHS1, RHS2); 4795 LHS2 = DAG.getNode(ISD::AND, dl, MVT::i32, LHS2, Mask); 4796 RHS2 = DAG.getNode(ISD::AND, dl, MVT::i32, RHS2, Mask); 4797 ARMCC::CondCodes CondCode = IntCCToARMCC(CC); 4798 ARMcc = DAG.getConstant(CondCode, dl, MVT::i32); 4799 SDVTList VTList = DAG.getVTList(MVT::Other, MVT::Glue); 4800 SDValue Ops[] = { Chain, ARMcc, LHS1, LHS2, RHS1, RHS2, Dest }; 4801 return DAG.getNode(ARMISD::BCC_i64, dl, VTList, Ops); 4802 } 4803 4804 return SDValue(); 4805 } 4806 4807 SDValue ARMTargetLowering::LowerBRCOND(SDValue Op, SelectionDAG &DAG) const { 4808 SDValue Chain = Op.getOperand(0); 4809 SDValue Cond = Op.getOperand(1); 4810 SDValue Dest = Op.getOperand(2); 4811 SDLoc dl(Op); 4812 4813 // Optimize {s|u}{add|sub|mul}.with.overflow feeding into a branch 4814 // instruction. 4815 unsigned Opc = Cond.getOpcode(); 4816 bool OptimizeMul = (Opc == ISD::SMULO || Opc == ISD::UMULO) && 4817 !Subtarget->isThumb1Only(); 4818 if (Cond.getResNo() == 1 && 4819 (Opc == ISD::SADDO || Opc == ISD::UADDO || Opc == ISD::SSUBO || 4820 Opc == ISD::USUBO || OptimizeMul)) { 4821 // Only lower legal XALUO ops. 4822 if (!DAG.getTargetLoweringInfo().isTypeLegal(Cond->getValueType(0))) 4823 return SDValue(); 4824 4825 // The actual operation with overflow check. 4826 SDValue Value, OverflowCmp; 4827 SDValue ARMcc; 4828 std::tie(Value, OverflowCmp) = getARMXALUOOp(Cond, DAG, ARMcc); 4829 4830 // Reverse the condition code. 4831 ARMCC::CondCodes CondCode = 4832 (ARMCC::CondCodes)cast<const ConstantSDNode>(ARMcc)->getZExtValue(); 4833 CondCode = ARMCC::getOppositeCondition(CondCode); 4834 ARMcc = DAG.getConstant(CondCode, SDLoc(ARMcc), MVT::i32); 4835 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32); 4836 4837 return DAG.getNode(ARMISD::BRCOND, dl, MVT::Other, Chain, Dest, ARMcc, CCR, 4838 OverflowCmp); 4839 } 4840 4841 return SDValue(); 4842 } 4843 4844 SDValue ARMTargetLowering::LowerBR_CC(SDValue Op, SelectionDAG &DAG) const { 4845 SDValue Chain = Op.getOperand(0); 4846 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(1))->get(); 4847 SDValue LHS = Op.getOperand(2); 4848 SDValue RHS = Op.getOperand(3); 4849 SDValue Dest = Op.getOperand(4); 4850 SDLoc dl(Op); 4851 4852 if (isUnsupportedFloatingType(LHS.getValueType())) { 4853 DAG.getTargetLoweringInfo().softenSetCCOperands( 4854 DAG, LHS.getValueType(), LHS, RHS, CC, dl); 4855 4856 // If softenSetCCOperands only returned one value, we should compare it to 4857 // zero. 4858 if (!RHS.getNode()) { 4859 RHS = DAG.getConstant(0, dl, LHS.getValueType()); 4860 CC = ISD::SETNE; 4861 } 4862 } 4863 4864 // Optimize {s|u}{add|sub|mul}.with.overflow feeding into a branch 4865 // instruction. 4866 unsigned Opc = LHS.getOpcode(); 4867 bool OptimizeMul = (Opc == ISD::SMULO || Opc == ISD::UMULO) && 4868 !Subtarget->isThumb1Only(); 4869 if (LHS.getResNo() == 1 && (isOneConstant(RHS) || isNullConstant(RHS)) && 4870 (Opc == ISD::SADDO || Opc == ISD::UADDO || Opc == ISD::SSUBO || 4871 Opc == ISD::USUBO || OptimizeMul) && 4872 (CC == ISD::SETEQ || CC == ISD::SETNE)) { 4873 // Only lower legal XALUO ops. 4874 if (!DAG.getTargetLoweringInfo().isTypeLegal(LHS->getValueType(0))) 4875 return SDValue(); 4876 4877 // The actual operation with overflow check. 4878 SDValue Value, OverflowCmp; 4879 SDValue ARMcc; 4880 std::tie(Value, OverflowCmp) = getARMXALUOOp(LHS.getValue(0), DAG, ARMcc); 4881 4882 if ((CC == ISD::SETNE) != isOneConstant(RHS)) { 4883 // Reverse the condition code. 4884 ARMCC::CondCodes CondCode = 4885 (ARMCC::CondCodes)cast<const ConstantSDNode>(ARMcc)->getZExtValue(); 4886 CondCode = ARMCC::getOppositeCondition(CondCode); 4887 ARMcc = DAG.getConstant(CondCode, SDLoc(ARMcc), MVT::i32); 4888 } 4889 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32); 4890 4891 return DAG.getNode(ARMISD::BRCOND, dl, MVT::Other, Chain, Dest, ARMcc, CCR, 4892 OverflowCmp); 4893 } 4894 4895 if (LHS.getValueType() == MVT::i32) { 4896 SDValue ARMcc; 4897 SDValue Cmp = getARMCmp(LHS, RHS, CC, ARMcc, DAG, dl); 4898 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32); 4899 return DAG.getNode(ARMISD::BRCOND, dl, MVT::Other, 4900 Chain, Dest, ARMcc, CCR, Cmp); 4901 } 4902 4903 if (getTargetMachine().Options.UnsafeFPMath && 4904 (CC == ISD::SETEQ || CC == ISD::SETOEQ || 4905 CC == ISD::SETNE || CC == ISD::SETUNE)) { 4906 if (SDValue Result = OptimizeVFPBrcond(Op, DAG)) 4907 return Result; 4908 } 4909 4910 ARMCC::CondCodes CondCode, CondCode2; 4911 bool InvalidOnQNaN; 4912 FPCCToARMCC(CC, CondCode, CondCode2, InvalidOnQNaN); 4913 4914 SDValue ARMcc = DAG.getConstant(CondCode, dl, MVT::i32); 4915 SDValue Cmp = getVFPCmp(LHS, RHS, DAG, dl, InvalidOnQNaN); 4916 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32); 4917 SDVTList VTList = DAG.getVTList(MVT::Other, MVT::Glue); 4918 SDValue Ops[] = { Chain, Dest, ARMcc, CCR, Cmp }; 4919 SDValue Res = DAG.getNode(ARMISD::BRCOND, dl, VTList, Ops); 4920 if (CondCode2 != ARMCC::AL) { 4921 ARMcc = DAG.getConstant(CondCode2, dl, MVT::i32); 4922 SDValue Ops[] = { Res, Dest, ARMcc, CCR, Res.getValue(1) }; 4923 Res = DAG.getNode(ARMISD::BRCOND, dl, VTList, Ops); 4924 } 4925 return Res; 4926 } 4927 4928 SDValue ARMTargetLowering::LowerBR_JT(SDValue Op, SelectionDAG &DAG) const { 4929 SDValue Chain = Op.getOperand(0); 4930 SDValue Table = Op.getOperand(1); 4931 SDValue Index = Op.getOperand(2); 4932 SDLoc dl(Op); 4933 4934 EVT PTy = getPointerTy(DAG.getDataLayout()); 4935 JumpTableSDNode *JT = cast<JumpTableSDNode>(Table); 4936 SDValue JTI = DAG.getTargetJumpTable(JT->getIndex(), PTy); 4937 Table = DAG.getNode(ARMISD::WrapperJT, dl, MVT::i32, JTI); 4938 Index = DAG.getNode(ISD::MUL, dl, PTy, Index, DAG.getConstant(4, dl, PTy)); 4939 SDValue Addr = DAG.getNode(ISD::ADD, dl, PTy, Table, Index); 4940 if (Subtarget->isThumb2() || (Subtarget->hasV8MBaselineOps() && Subtarget->isThumb())) { 4941 // Thumb2 and ARMv8-M use a two-level jump. That is, it jumps into the jump table 4942 // which does another jump to the destination. This also makes it easier 4943 // to translate it to TBB / TBH later (Thumb2 only). 4944 // FIXME: This might not work if the function is extremely large. 4945 return DAG.getNode(ARMISD::BR2_JT, dl, MVT::Other, Chain, 4946 Addr, Op.getOperand(2), JTI); 4947 } 4948 if (isPositionIndependent() || Subtarget->isROPI()) { 4949 Addr = 4950 DAG.getLoad((EVT)MVT::i32, dl, Chain, Addr, 4951 MachinePointerInfo::getJumpTable(DAG.getMachineFunction())); 4952 Chain = Addr.getValue(1); 4953 Addr = DAG.getNode(ISD::ADD, dl, PTy, Table, Addr); 4954 return DAG.getNode(ARMISD::BR_JT, dl, MVT::Other, Chain, Addr, JTI); 4955 } else { 4956 Addr = 4957 DAG.getLoad(PTy, dl, Chain, Addr, 4958 MachinePointerInfo::getJumpTable(DAG.getMachineFunction())); 4959 Chain = Addr.getValue(1); 4960 return DAG.getNode(ARMISD::BR_JT, dl, MVT::Other, Chain, Addr, JTI); 4961 } 4962 } 4963 4964 static SDValue LowerVectorFP_TO_INT(SDValue Op, SelectionDAG &DAG) { 4965 EVT VT = Op.getValueType(); 4966 SDLoc dl(Op); 4967 4968 if (Op.getValueType().getVectorElementType() == MVT::i32) { 4969 if (Op.getOperand(0).getValueType().getVectorElementType() == MVT::f32) 4970 return Op; 4971 return DAG.UnrollVectorOp(Op.getNode()); 4972 } 4973 4974 const bool HasFullFP16 = 4975 static_cast<const ARMSubtarget&>(DAG.getSubtarget()).hasFullFP16(); 4976 4977 EVT NewTy; 4978 const EVT OpTy = Op.getOperand(0).getValueType(); 4979 if (OpTy == MVT::v4f32) 4980 NewTy = MVT::v4i32; 4981 else if (OpTy == MVT::v4f16 && HasFullFP16) 4982 NewTy = MVT::v4i16; 4983 else if (OpTy == MVT::v8f16 && HasFullFP16) 4984 NewTy = MVT::v8i16; 4985 else 4986 llvm_unreachable("Invalid type for custom lowering!"); 4987 4988 if (VT != MVT::v4i16 && VT != MVT::v8i16) 4989 return DAG.UnrollVectorOp(Op.getNode()); 4990 4991 Op = DAG.getNode(Op.getOpcode(), dl, NewTy, Op.getOperand(0)); 4992 return DAG.getNode(ISD::TRUNCATE, dl, VT, Op); 4993 } 4994 4995 SDValue ARMTargetLowering::LowerFP_TO_INT(SDValue Op, SelectionDAG &DAG) const { 4996 EVT VT = Op.getValueType(); 4997 if (VT.isVector()) 4998 return LowerVectorFP_TO_INT(Op, DAG); 4999 if (isUnsupportedFloatingType(Op.getOperand(0).getValueType())) { 5000 RTLIB::Libcall LC; 5001 if (Op.getOpcode() == ISD::FP_TO_SINT) 5002 LC = RTLIB::getFPTOSINT(Op.getOperand(0).getValueType(), 5003 Op.getValueType()); 5004 else 5005 LC = RTLIB::getFPTOUINT(Op.getOperand(0).getValueType(), 5006 Op.getValueType()); 5007 return makeLibCall(DAG, LC, Op.getValueType(), Op.getOperand(0), 5008 /*isSigned*/ false, SDLoc(Op)).first; 5009 } 5010 5011 return Op; 5012 } 5013 5014 static SDValue LowerVectorINT_TO_FP(SDValue Op, SelectionDAG &DAG) { 5015 EVT VT = Op.getValueType(); 5016 SDLoc dl(Op); 5017 5018 if (Op.getOperand(0).getValueType().getVectorElementType() == MVT::i32) { 5019 if (VT.getVectorElementType() == MVT::f32) 5020 return Op; 5021 return DAG.UnrollVectorOp(Op.getNode()); 5022 } 5023 5024 assert((Op.getOperand(0).getValueType() == MVT::v4i16 || 5025 Op.getOperand(0).getValueType() == MVT::v8i16) && 5026 "Invalid type for custom lowering!"); 5027 5028 const bool HasFullFP16 = 5029 static_cast<const ARMSubtarget&>(DAG.getSubtarget()).hasFullFP16(); 5030 5031 EVT DestVecType; 5032 if (VT == MVT::v4f32) 5033 DestVecType = MVT::v4i32; 5034 else if (VT == MVT::v4f16 && HasFullFP16) 5035 DestVecType = MVT::v4i16; 5036 else if (VT == MVT::v8f16 && HasFullFP16) 5037 DestVecType = MVT::v8i16; 5038 else 5039 return DAG.UnrollVectorOp(Op.getNode()); 5040 5041 unsigned CastOpc; 5042 unsigned Opc; 5043 switch (Op.getOpcode()) { 5044 default: llvm_unreachable("Invalid opcode!"); 5045 case ISD::SINT_TO_FP: 5046 CastOpc = ISD::SIGN_EXTEND; 5047 Opc = ISD::SINT_TO_FP; 5048 break; 5049 case ISD::UINT_TO_FP: 5050 CastOpc = ISD::ZERO_EXTEND; 5051 Opc = ISD::UINT_TO_FP; 5052 break; 5053 } 5054 5055 Op = DAG.getNode(CastOpc, dl, DestVecType, Op.getOperand(0)); 5056 return DAG.getNode(Opc, dl, VT, Op); 5057 } 5058 5059 SDValue ARMTargetLowering::LowerINT_TO_FP(SDValue Op, SelectionDAG &DAG) const { 5060 EVT VT = Op.getValueType(); 5061 if (VT.isVector()) 5062 return LowerVectorINT_TO_FP(Op, DAG); 5063 if (isUnsupportedFloatingType(VT)) { 5064 RTLIB::Libcall LC; 5065 if (Op.getOpcode() == ISD::SINT_TO_FP) 5066 LC = RTLIB::getSINTTOFP(Op.getOperand(0).getValueType(), 5067 Op.getValueType()); 5068 else 5069 LC = RTLIB::getUINTTOFP(Op.getOperand(0).getValueType(), 5070 Op.getValueType()); 5071 return makeLibCall(DAG, LC, Op.getValueType(), Op.getOperand(0), 5072 /*isSigned*/ false, SDLoc(Op)).first; 5073 } 5074 5075 return Op; 5076 } 5077 5078 SDValue ARMTargetLowering::LowerFCOPYSIGN(SDValue Op, SelectionDAG &DAG) const { 5079 // Implement fcopysign with a fabs and a conditional fneg. 5080 SDValue Tmp0 = Op.getOperand(0); 5081 SDValue Tmp1 = Op.getOperand(1); 5082 SDLoc dl(Op); 5083 EVT VT = Op.getValueType(); 5084 EVT SrcVT = Tmp1.getValueType(); 5085 bool InGPR = Tmp0.getOpcode() == ISD::BITCAST || 5086 Tmp0.getOpcode() == ARMISD::VMOVDRR; 5087 bool UseNEON = !InGPR && Subtarget->hasNEON(); 5088 5089 if (UseNEON) { 5090 // Use VBSL to copy the sign bit. 5091 unsigned EncodedVal = ARM_AM::createNEONModImm(0x6, 0x80); 5092 SDValue Mask = DAG.getNode(ARMISD::VMOVIMM, dl, MVT::v2i32, 5093 DAG.getTargetConstant(EncodedVal, dl, MVT::i32)); 5094 EVT OpVT = (VT == MVT::f32) ? MVT::v2i32 : MVT::v1i64; 5095 if (VT == MVT::f64) 5096 Mask = DAG.getNode(ARMISD::VSHL, dl, OpVT, 5097 DAG.getNode(ISD::BITCAST, dl, OpVT, Mask), 5098 DAG.getConstant(32, dl, MVT::i32)); 5099 else /*if (VT == MVT::f32)*/ 5100 Tmp0 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f32, Tmp0); 5101 if (SrcVT == MVT::f32) { 5102 Tmp1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f32, Tmp1); 5103 if (VT == MVT::f64) 5104 Tmp1 = DAG.getNode(ARMISD::VSHL, dl, OpVT, 5105 DAG.getNode(ISD::BITCAST, dl, OpVT, Tmp1), 5106 DAG.getConstant(32, dl, MVT::i32)); 5107 } else if (VT == MVT::f32) 5108 Tmp1 = DAG.getNode(ARMISD::VSHRu, dl, MVT::v1i64, 5109 DAG.getNode(ISD::BITCAST, dl, MVT::v1i64, Tmp1), 5110 DAG.getConstant(32, dl, MVT::i32)); 5111 Tmp0 = DAG.getNode(ISD::BITCAST, dl, OpVT, Tmp0); 5112 Tmp1 = DAG.getNode(ISD::BITCAST, dl, OpVT, Tmp1); 5113 5114 SDValue AllOnes = DAG.getTargetConstant(ARM_AM::createNEONModImm(0xe, 0xff), 5115 dl, MVT::i32); 5116 AllOnes = DAG.getNode(ARMISD::VMOVIMM, dl, MVT::v8i8, AllOnes); 5117 SDValue MaskNot = DAG.getNode(ISD::XOR, dl, OpVT, Mask, 5118 DAG.getNode(ISD::BITCAST, dl, OpVT, AllOnes)); 5119 5120 SDValue Res = DAG.getNode(ISD::OR, dl, OpVT, 5121 DAG.getNode(ISD::AND, dl, OpVT, Tmp1, Mask), 5122 DAG.getNode(ISD::AND, dl, OpVT, Tmp0, MaskNot)); 5123 if (VT == MVT::f32) { 5124 Res = DAG.getNode(ISD::BITCAST, dl, MVT::v2f32, Res); 5125 Res = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f32, Res, 5126 DAG.getConstant(0, dl, MVT::i32)); 5127 } else { 5128 Res = DAG.getNode(ISD::BITCAST, dl, MVT::f64, Res); 5129 } 5130 5131 return Res; 5132 } 5133 5134 // Bitcast operand 1 to i32. 5135 if (SrcVT == MVT::f64) 5136 Tmp1 = DAG.getNode(ARMISD::VMOVRRD, dl, DAG.getVTList(MVT::i32, MVT::i32), 5137 Tmp1).getValue(1); 5138 Tmp1 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Tmp1); 5139 5140 // Or in the signbit with integer operations. 5141 SDValue Mask1 = DAG.getConstant(0x80000000, dl, MVT::i32); 5142 SDValue Mask2 = DAG.getConstant(0x7fffffff, dl, MVT::i32); 5143 Tmp1 = DAG.getNode(ISD::AND, dl, MVT::i32, Tmp1, Mask1); 5144 if (VT == MVT::f32) { 5145 Tmp0 = DAG.getNode(ISD::AND, dl, MVT::i32, 5146 DAG.getNode(ISD::BITCAST, dl, MVT::i32, Tmp0), Mask2); 5147 return DAG.getNode(ISD::BITCAST, dl, MVT::f32, 5148 DAG.getNode(ISD::OR, dl, MVT::i32, Tmp0, Tmp1)); 5149 } 5150 5151 // f64: Or the high part with signbit and then combine two parts. 5152 Tmp0 = DAG.getNode(ARMISD::VMOVRRD, dl, DAG.getVTList(MVT::i32, MVT::i32), 5153 Tmp0); 5154 SDValue Lo = Tmp0.getValue(0); 5155 SDValue Hi = DAG.getNode(ISD::AND, dl, MVT::i32, Tmp0.getValue(1), Mask2); 5156 Hi = DAG.getNode(ISD::OR, dl, MVT::i32, Hi, Tmp1); 5157 return DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi); 5158 } 5159 5160 SDValue ARMTargetLowering::LowerRETURNADDR(SDValue Op, SelectionDAG &DAG) const{ 5161 MachineFunction &MF = DAG.getMachineFunction(); 5162 MachineFrameInfo &MFI = MF.getFrameInfo(); 5163 MFI.setReturnAddressIsTaken(true); 5164 5165 if (verifyReturnAddressArgumentIsConstant(Op, DAG)) 5166 return SDValue(); 5167 5168 EVT VT = Op.getValueType(); 5169 SDLoc dl(Op); 5170 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue(); 5171 if (Depth) { 5172 SDValue FrameAddr = LowerFRAMEADDR(Op, DAG); 5173 SDValue Offset = DAG.getConstant(4, dl, MVT::i32); 5174 return DAG.getLoad(VT, dl, DAG.getEntryNode(), 5175 DAG.getNode(ISD::ADD, dl, VT, FrameAddr, Offset), 5176 MachinePointerInfo()); 5177 } 5178 5179 // Return LR, which contains the return address. Mark it an implicit live-in. 5180 unsigned Reg = MF.addLiveIn(ARM::LR, getRegClassFor(MVT::i32)); 5181 return DAG.getCopyFromReg(DAG.getEntryNode(), dl, Reg, VT); 5182 } 5183 5184 SDValue ARMTargetLowering::LowerFRAMEADDR(SDValue Op, SelectionDAG &DAG) const { 5185 const ARMBaseRegisterInfo &ARI = 5186 *static_cast<const ARMBaseRegisterInfo*>(RegInfo); 5187 MachineFunction &MF = DAG.getMachineFunction(); 5188 MachineFrameInfo &MFI = MF.getFrameInfo(); 5189 MFI.setFrameAddressIsTaken(true); 5190 5191 EVT VT = Op.getValueType(); 5192 SDLoc dl(Op); // FIXME probably not meaningful 5193 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue(); 5194 unsigned FrameReg = ARI.getFrameRegister(MF); 5195 SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, VT); 5196 while (Depth--) 5197 FrameAddr = DAG.getLoad(VT, dl, DAG.getEntryNode(), FrameAddr, 5198 MachinePointerInfo()); 5199 return FrameAddr; 5200 } 5201 5202 // FIXME? Maybe this could be a TableGen attribute on some registers and 5203 // this table could be generated automatically from RegInfo. 5204 unsigned ARMTargetLowering::getRegisterByName(const char* RegName, EVT VT, 5205 SelectionDAG &DAG) const { 5206 unsigned Reg = StringSwitch<unsigned>(RegName) 5207 .Case("sp", ARM::SP) 5208 .Default(0); 5209 if (Reg) 5210 return Reg; 5211 report_fatal_error(Twine("Invalid register name \"" 5212 + StringRef(RegName) + "\".")); 5213 } 5214 5215 // Result is 64 bit value so split into two 32 bit values and return as a 5216 // pair of values. 5217 static void ExpandREAD_REGISTER(SDNode *N, SmallVectorImpl<SDValue> &Results, 5218 SelectionDAG &DAG) { 5219 SDLoc DL(N); 5220 5221 // This function is only supposed to be called for i64 type destination. 5222 assert(N->getValueType(0) == MVT::i64 5223 && "ExpandREAD_REGISTER called for non-i64 type result."); 5224 5225 SDValue Read = DAG.getNode(ISD::READ_REGISTER, DL, 5226 DAG.getVTList(MVT::i32, MVT::i32, MVT::Other), 5227 N->getOperand(0), 5228 N->getOperand(1)); 5229 5230 Results.push_back(DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, Read.getValue(0), 5231 Read.getValue(1))); 5232 Results.push_back(Read.getOperand(0)); 5233 } 5234 5235 /// \p BC is a bitcast that is about to be turned into a VMOVDRR. 5236 /// When \p DstVT, the destination type of \p BC, is on the vector 5237 /// register bank and the source of bitcast, \p Op, operates on the same bank, 5238 /// it might be possible to combine them, such that everything stays on the 5239 /// vector register bank. 5240 /// \p return The node that would replace \p BT, if the combine 5241 /// is possible. 5242 static SDValue CombineVMOVDRRCandidateWithVecOp(const SDNode *BC, 5243 SelectionDAG &DAG) { 5244 SDValue Op = BC->getOperand(0); 5245 EVT DstVT = BC->getValueType(0); 5246 5247 // The only vector instruction that can produce a scalar (remember, 5248 // since the bitcast was about to be turned into VMOVDRR, the source 5249 // type is i64) from a vector is EXTRACT_VECTOR_ELT. 5250 // Moreover, we can do this combine only if there is one use. 5251 // Finally, if the destination type is not a vector, there is not 5252 // much point on forcing everything on the vector bank. 5253 if (!DstVT.isVector() || Op.getOpcode() != ISD::EXTRACT_VECTOR_ELT || 5254 !Op.hasOneUse()) 5255 return SDValue(); 5256 5257 // If the index is not constant, we will introduce an additional 5258 // multiply that will stick. 5259 // Give up in that case. 5260 ConstantSDNode *Index = dyn_cast<ConstantSDNode>(Op.getOperand(1)); 5261 if (!Index) 5262 return SDValue(); 5263 unsigned DstNumElt = DstVT.getVectorNumElements(); 5264 5265 // Compute the new index. 5266 const APInt &APIntIndex = Index->getAPIntValue(); 5267 APInt NewIndex(APIntIndex.getBitWidth(), DstNumElt); 5268 NewIndex *= APIntIndex; 5269 // Check if the new constant index fits into i32. 5270 if (NewIndex.getBitWidth() > 32) 5271 return SDValue(); 5272 5273 // vMTy bitcast(i64 extractelt vNi64 src, i32 index) -> 5274 // vMTy extractsubvector vNxMTy (bitcast vNi64 src), i32 index*M) 5275 SDLoc dl(Op); 5276 SDValue ExtractSrc = Op.getOperand(0); 5277 EVT VecVT = EVT::getVectorVT( 5278 *DAG.getContext(), DstVT.getScalarType(), 5279 ExtractSrc.getValueType().getVectorNumElements() * DstNumElt); 5280 SDValue BitCast = DAG.getNode(ISD::BITCAST, dl, VecVT, ExtractSrc); 5281 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DstVT, BitCast, 5282 DAG.getConstant(NewIndex.getZExtValue(), dl, MVT::i32)); 5283 } 5284 5285 /// ExpandBITCAST - If the target supports VFP, this function is called to 5286 /// expand a bit convert where either the source or destination type is i64 to 5287 /// use a VMOVDRR or VMOVRRD node. This should not be done when the non-i64 5288 /// operand type is illegal (e.g., v2f32 for a target that doesn't support 5289 /// vectors), since the legalizer won't know what to do with that. 5290 static SDValue ExpandBITCAST(SDNode *N, SelectionDAG &DAG, 5291 const ARMSubtarget *Subtarget) { 5292 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 5293 SDLoc dl(N); 5294 SDValue Op = N->getOperand(0); 5295 5296 // This function is only supposed to be called for i64 types, either as the 5297 // source or destination of the bit convert. 5298 EVT SrcVT = Op.getValueType(); 5299 EVT DstVT = N->getValueType(0); 5300 const bool HasFullFP16 = Subtarget->hasFullFP16(); 5301 5302 if (SrcVT == MVT::f32 && DstVT == MVT::i32) { 5303 // FullFP16: half values are passed in S-registers, and we don't 5304 // need any of the bitcast and moves: 5305 // 5306 // t2: f32,ch = CopyFromReg t0, Register:f32 %0 5307 // t5: i32 = bitcast t2 5308 // t18: f16 = ARMISD::VMOVhr t5 5309 if (Op.getOpcode() != ISD::CopyFromReg || 5310 Op.getValueType() != MVT::f32) 5311 return SDValue(); 5312 5313 auto Move = N->use_begin(); 5314 if (Move->getOpcode() != ARMISD::VMOVhr) 5315 return SDValue(); 5316 5317 SDValue Ops[] = { Op.getOperand(0), Op.getOperand(1) }; 5318 SDValue Copy = DAG.getNode(ISD::CopyFromReg, SDLoc(Op), MVT::f16, Ops); 5319 DAG.ReplaceAllUsesWith(*Move, &Copy); 5320 return Copy; 5321 } 5322 5323 if (SrcVT == MVT::i16 && DstVT == MVT::f16) { 5324 if (!HasFullFP16) 5325 return SDValue(); 5326 // SoftFP: read half-precision arguments: 5327 // 5328 // t2: i32,ch = ... 5329 // t7: i16 = truncate t2 <~~~~ Op 5330 // t8: f16 = bitcast t7 <~~~~ N 5331 // 5332 if (Op.getOperand(0).getValueType() == MVT::i32) 5333 return DAG.getNode(ARMISD::VMOVhr, SDLoc(Op), 5334 MVT::f16, Op.getOperand(0)); 5335 5336 return SDValue(); 5337 } 5338 5339 // Half-precision return values 5340 if (SrcVT == MVT::f16 && DstVT == MVT::i16) { 5341 if (!HasFullFP16) 5342 return SDValue(); 5343 // 5344 // t11: f16 = fadd t8, t10 5345 // t12: i16 = bitcast t11 <~~~ SDNode N 5346 // t13: i32 = zero_extend t12 5347 // t16: ch,glue = CopyToReg t0, Register:i32 %r0, t13 5348 // t17: ch = ARMISD::RET_FLAG t16, Register:i32 %r0, t16:1 5349 // 5350 // transform this into: 5351 // 5352 // t20: i32 = ARMISD::VMOVrh t11 5353 // t16: ch,glue = CopyToReg t0, Register:i32 %r0, t20 5354 // 5355 auto ZeroExtend = N->use_begin(); 5356 if (N->use_size() != 1 || ZeroExtend->getOpcode() != ISD::ZERO_EXTEND || 5357 ZeroExtend->getValueType(0) != MVT::i32) 5358 return SDValue(); 5359 5360 auto Copy = ZeroExtend->use_begin(); 5361 if (Copy->getOpcode() == ISD::CopyToReg && 5362 Copy->use_begin()->getOpcode() == ARMISD::RET_FLAG) { 5363 SDValue Cvt = DAG.getNode(ARMISD::VMOVrh, SDLoc(Op), MVT::i32, Op); 5364 DAG.ReplaceAllUsesWith(*ZeroExtend, &Cvt); 5365 return Cvt; 5366 } 5367 return SDValue(); 5368 } 5369 5370 if (!(SrcVT == MVT::i64 || DstVT == MVT::i64)) 5371 return SDValue(); 5372 5373 // Turn i64->f64 into VMOVDRR. 5374 if (SrcVT == MVT::i64 && TLI.isTypeLegal(DstVT)) { 5375 // Do not force values to GPRs (this is what VMOVDRR does for the inputs) 5376 // if we can combine the bitcast with its source. 5377 if (SDValue Val = CombineVMOVDRRCandidateWithVecOp(N, DAG)) 5378 return Val; 5379 5380 SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, Op, 5381 DAG.getConstant(0, dl, MVT::i32)); 5382 SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, Op, 5383 DAG.getConstant(1, dl, MVT::i32)); 5384 return DAG.getNode(ISD::BITCAST, dl, DstVT, 5385 DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi)); 5386 } 5387 5388 // Turn f64->i64 into VMOVRRD. 5389 if (DstVT == MVT::i64 && TLI.isTypeLegal(SrcVT)) { 5390 SDValue Cvt; 5391 if (DAG.getDataLayout().isBigEndian() && SrcVT.isVector() && 5392 SrcVT.getVectorNumElements() > 1) 5393 Cvt = DAG.getNode(ARMISD::VMOVRRD, dl, 5394 DAG.getVTList(MVT::i32, MVT::i32), 5395 DAG.getNode(ARMISD::VREV64, dl, SrcVT, Op)); 5396 else 5397 Cvt = DAG.getNode(ARMISD::VMOVRRD, dl, 5398 DAG.getVTList(MVT::i32, MVT::i32), Op); 5399 // Merge the pieces into a single i64 value. 5400 return DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Cvt, Cvt.getValue(1)); 5401 } 5402 5403 return SDValue(); 5404 } 5405 5406 /// getZeroVector - Returns a vector of specified type with all zero elements. 5407 /// Zero vectors are used to represent vector negation and in those cases 5408 /// will be implemented with the NEON VNEG instruction. However, VNEG does 5409 /// not support i64 elements, so sometimes the zero vectors will need to be 5410 /// explicitly constructed. Regardless, use a canonical VMOV to create the 5411 /// zero vector. 5412 static SDValue getZeroVector(EVT VT, SelectionDAG &DAG, const SDLoc &dl) { 5413 assert(VT.isVector() && "Expected a vector type"); 5414 // The canonical modified immediate encoding of a zero vector is....0! 5415 SDValue EncodedVal = DAG.getTargetConstant(0, dl, MVT::i32); 5416 EVT VmovVT = VT.is128BitVector() ? MVT::v4i32 : MVT::v2i32; 5417 SDValue Vmov = DAG.getNode(ARMISD::VMOVIMM, dl, VmovVT, EncodedVal); 5418 return DAG.getNode(ISD::BITCAST, dl, VT, Vmov); 5419 } 5420 5421 /// LowerShiftRightParts - Lower SRA_PARTS, which returns two 5422 /// i32 values and take a 2 x i32 value to shift plus a shift amount. 5423 SDValue ARMTargetLowering::LowerShiftRightParts(SDValue Op, 5424 SelectionDAG &DAG) const { 5425 assert(Op.getNumOperands() == 3 && "Not a double-shift!"); 5426 EVT VT = Op.getValueType(); 5427 unsigned VTBits = VT.getSizeInBits(); 5428 SDLoc dl(Op); 5429 SDValue ShOpLo = Op.getOperand(0); 5430 SDValue ShOpHi = Op.getOperand(1); 5431 SDValue ShAmt = Op.getOperand(2); 5432 SDValue ARMcc; 5433 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32); 5434 unsigned Opc = (Op.getOpcode() == ISD::SRA_PARTS) ? ISD::SRA : ISD::SRL; 5435 5436 assert(Op.getOpcode() == ISD::SRA_PARTS || Op.getOpcode() == ISD::SRL_PARTS); 5437 5438 SDValue RevShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32, 5439 DAG.getConstant(VTBits, dl, MVT::i32), ShAmt); 5440 SDValue Tmp1 = DAG.getNode(ISD::SRL, dl, VT, ShOpLo, ShAmt); 5441 SDValue ExtraShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32, ShAmt, 5442 DAG.getConstant(VTBits, dl, MVT::i32)); 5443 SDValue Tmp2 = DAG.getNode(ISD::SHL, dl, VT, ShOpHi, RevShAmt); 5444 SDValue LoSmallShift = DAG.getNode(ISD::OR, dl, VT, Tmp1, Tmp2); 5445 SDValue LoBigShift = DAG.getNode(Opc, dl, VT, ShOpHi, ExtraShAmt); 5446 SDValue CmpLo = getARMCmp(ExtraShAmt, DAG.getConstant(0, dl, MVT::i32), 5447 ISD::SETGE, ARMcc, DAG, dl); 5448 SDValue Lo = DAG.getNode(ARMISD::CMOV, dl, VT, LoSmallShift, LoBigShift, 5449 ARMcc, CCR, CmpLo); 5450 5451 SDValue HiSmallShift = DAG.getNode(Opc, dl, VT, ShOpHi, ShAmt); 5452 SDValue HiBigShift = Opc == ISD::SRA 5453 ? DAG.getNode(Opc, dl, VT, ShOpHi, 5454 DAG.getConstant(VTBits - 1, dl, VT)) 5455 : DAG.getConstant(0, dl, VT); 5456 SDValue CmpHi = getARMCmp(ExtraShAmt, DAG.getConstant(0, dl, MVT::i32), 5457 ISD::SETGE, ARMcc, DAG, dl); 5458 SDValue Hi = DAG.getNode(ARMISD::CMOV, dl, VT, HiSmallShift, HiBigShift, 5459 ARMcc, CCR, CmpHi); 5460 5461 SDValue Ops[2] = { Lo, Hi }; 5462 return DAG.getMergeValues(Ops, dl); 5463 } 5464 5465 /// LowerShiftLeftParts - Lower SHL_PARTS, which returns two 5466 /// i32 values and take a 2 x i32 value to shift plus a shift amount. 5467 SDValue ARMTargetLowering::LowerShiftLeftParts(SDValue Op, 5468 SelectionDAG &DAG) const { 5469 assert(Op.getNumOperands() == 3 && "Not a double-shift!"); 5470 EVT VT = Op.getValueType(); 5471 unsigned VTBits = VT.getSizeInBits(); 5472 SDLoc dl(Op); 5473 SDValue ShOpLo = Op.getOperand(0); 5474 SDValue ShOpHi = Op.getOperand(1); 5475 SDValue ShAmt = Op.getOperand(2); 5476 SDValue ARMcc; 5477 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32); 5478 5479 assert(Op.getOpcode() == ISD::SHL_PARTS); 5480 SDValue RevShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32, 5481 DAG.getConstant(VTBits, dl, MVT::i32), ShAmt); 5482 SDValue Tmp1 = DAG.getNode(ISD::SRL, dl, VT, ShOpLo, RevShAmt); 5483 SDValue Tmp2 = DAG.getNode(ISD::SHL, dl, VT, ShOpHi, ShAmt); 5484 SDValue HiSmallShift = DAG.getNode(ISD::OR, dl, VT, Tmp1, Tmp2); 5485 5486 SDValue ExtraShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32, ShAmt, 5487 DAG.getConstant(VTBits, dl, MVT::i32)); 5488 SDValue HiBigShift = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ExtraShAmt); 5489 SDValue CmpHi = getARMCmp(ExtraShAmt, DAG.getConstant(0, dl, MVT::i32), 5490 ISD::SETGE, ARMcc, DAG, dl); 5491 SDValue Hi = DAG.getNode(ARMISD::CMOV, dl, VT, HiSmallShift, HiBigShift, 5492 ARMcc, CCR, CmpHi); 5493 5494 SDValue CmpLo = getARMCmp(ExtraShAmt, DAG.getConstant(0, dl, MVT::i32), 5495 ISD::SETGE, ARMcc, DAG, dl); 5496 SDValue LoSmallShift = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ShAmt); 5497 SDValue Lo = DAG.getNode(ARMISD::CMOV, dl, VT, LoSmallShift, 5498 DAG.getConstant(0, dl, VT), ARMcc, CCR, CmpLo); 5499 5500 SDValue Ops[2] = { Lo, Hi }; 5501 return DAG.getMergeValues(Ops, dl); 5502 } 5503 5504 SDValue ARMTargetLowering::LowerFLT_ROUNDS_(SDValue Op, 5505 SelectionDAG &DAG) const { 5506 // The rounding mode is in bits 23:22 of the FPSCR. 5507 // The ARM rounding mode value to FLT_ROUNDS mapping is 0->1, 1->2, 2->3, 3->0 5508 // The formula we use to implement this is (((FPSCR + 1 << 22) >> 22) & 3) 5509 // so that the shift + and get folded into a bitfield extract. 5510 SDLoc dl(Op); 5511 SDValue Ops[] = { DAG.getEntryNode(), 5512 DAG.getConstant(Intrinsic::arm_get_fpscr, dl, MVT::i32) }; 5513 5514 SDValue FPSCR = DAG.getNode(ISD::INTRINSIC_W_CHAIN, dl, MVT::i32, Ops); 5515 SDValue FltRounds = DAG.getNode(ISD::ADD, dl, MVT::i32, FPSCR, 5516 DAG.getConstant(1U << 22, dl, MVT::i32)); 5517 SDValue RMODE = DAG.getNode(ISD::SRL, dl, MVT::i32, FltRounds, 5518 DAG.getConstant(22, dl, MVT::i32)); 5519 return DAG.getNode(ISD::AND, dl, MVT::i32, RMODE, 5520 DAG.getConstant(3, dl, MVT::i32)); 5521 } 5522 5523 static SDValue LowerCTTZ(SDNode *N, SelectionDAG &DAG, 5524 const ARMSubtarget *ST) { 5525 SDLoc dl(N); 5526 EVT VT = N->getValueType(0); 5527 if (VT.isVector()) { 5528 assert(ST->hasNEON()); 5529 5530 // Compute the least significant set bit: LSB = X & -X 5531 SDValue X = N->getOperand(0); 5532 SDValue NX = DAG.getNode(ISD::SUB, dl, VT, getZeroVector(VT, DAG, dl), X); 5533 SDValue LSB = DAG.getNode(ISD::AND, dl, VT, X, NX); 5534 5535 EVT ElemTy = VT.getVectorElementType(); 5536 5537 if (ElemTy == MVT::i8) { 5538 // Compute with: cttz(x) = ctpop(lsb - 1) 5539 SDValue One = DAG.getNode(ARMISD::VMOVIMM, dl, VT, 5540 DAG.getTargetConstant(1, dl, ElemTy)); 5541 SDValue Bits = DAG.getNode(ISD::SUB, dl, VT, LSB, One); 5542 return DAG.getNode(ISD::CTPOP, dl, VT, Bits); 5543 } 5544 5545 if ((ElemTy == MVT::i16 || ElemTy == MVT::i32) && 5546 (N->getOpcode() == ISD::CTTZ_ZERO_UNDEF)) { 5547 // Compute with: cttz(x) = (width - 1) - ctlz(lsb), if x != 0 5548 unsigned NumBits = ElemTy.getSizeInBits(); 5549 SDValue WidthMinus1 = 5550 DAG.getNode(ARMISD::VMOVIMM, dl, VT, 5551 DAG.getTargetConstant(NumBits - 1, dl, ElemTy)); 5552 SDValue CTLZ = DAG.getNode(ISD::CTLZ, dl, VT, LSB); 5553 return DAG.getNode(ISD::SUB, dl, VT, WidthMinus1, CTLZ); 5554 } 5555 5556 // Compute with: cttz(x) = ctpop(lsb - 1) 5557 5558 // Compute LSB - 1. 5559 SDValue Bits; 5560 if (ElemTy == MVT::i64) { 5561 // Load constant 0xffff'ffff'ffff'ffff to register. 5562 SDValue FF = DAG.getNode(ARMISD::VMOVIMM, dl, VT, 5563 DAG.getTargetConstant(0x1eff, dl, MVT::i32)); 5564 Bits = DAG.getNode(ISD::ADD, dl, VT, LSB, FF); 5565 } else { 5566 SDValue One = DAG.getNode(ARMISD::VMOVIMM, dl, VT, 5567 DAG.getTargetConstant(1, dl, ElemTy)); 5568 Bits = DAG.getNode(ISD::SUB, dl, VT, LSB, One); 5569 } 5570 return DAG.getNode(ISD::CTPOP, dl, VT, Bits); 5571 } 5572 5573 if (!ST->hasV6T2Ops()) 5574 return SDValue(); 5575 5576 SDValue rbit = DAG.getNode(ISD::BITREVERSE, dl, VT, N->getOperand(0)); 5577 return DAG.getNode(ISD::CTLZ, dl, VT, rbit); 5578 } 5579 5580 static SDValue LowerCTPOP(SDNode *N, SelectionDAG &DAG, 5581 const ARMSubtarget *ST) { 5582 EVT VT = N->getValueType(0); 5583 SDLoc DL(N); 5584 5585 assert(ST->hasNEON() && "Custom ctpop lowering requires NEON."); 5586 assert((VT == MVT::v1i64 || VT == MVT::v2i64 || VT == MVT::v2i32 || 5587 VT == MVT::v4i32 || VT == MVT::v4i16 || VT == MVT::v8i16) && 5588 "Unexpected type for custom ctpop lowering"); 5589 5590 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 5591 EVT VT8Bit = VT.is64BitVector() ? MVT::v8i8 : MVT::v16i8; 5592 SDValue Res = DAG.getBitcast(VT8Bit, N->getOperand(0)); 5593 Res = DAG.getNode(ISD::CTPOP, DL, VT8Bit, Res); 5594 5595 // Widen v8i8/v16i8 CTPOP result to VT by repeatedly widening pairwise adds. 5596 unsigned EltSize = 8; 5597 unsigned NumElts = VT.is64BitVector() ? 8 : 16; 5598 while (EltSize != VT.getScalarSizeInBits()) { 5599 SmallVector<SDValue, 8> Ops; 5600 Ops.push_back(DAG.getConstant(Intrinsic::arm_neon_vpaddlu, DL, 5601 TLI.getPointerTy(DAG.getDataLayout()))); 5602 Ops.push_back(Res); 5603 5604 EltSize *= 2; 5605 NumElts /= 2; 5606 MVT WidenVT = MVT::getVectorVT(MVT::getIntegerVT(EltSize), NumElts); 5607 Res = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, WidenVT, Ops); 5608 } 5609 5610 return Res; 5611 } 5612 5613 static SDValue LowerShift(SDNode *N, SelectionDAG &DAG, 5614 const ARMSubtarget *ST) { 5615 EVT VT = N->getValueType(0); 5616 SDLoc dl(N); 5617 5618 if (!VT.isVector()) 5619 return SDValue(); 5620 5621 // Lower vector shifts on NEON to use VSHL. 5622 assert(ST->hasNEON() && "unexpected vector shift"); 5623 5624 // Left shifts translate directly to the vshiftu intrinsic. 5625 if (N->getOpcode() == ISD::SHL) 5626 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT, 5627 DAG.getConstant(Intrinsic::arm_neon_vshiftu, dl, 5628 MVT::i32), 5629 N->getOperand(0), N->getOperand(1)); 5630 5631 assert((N->getOpcode() == ISD::SRA || 5632 N->getOpcode() == ISD::SRL) && "unexpected vector shift opcode"); 5633 5634 // NEON uses the same intrinsics for both left and right shifts. For 5635 // right shifts, the shift amounts are negative, so negate the vector of 5636 // shift amounts. 5637 EVT ShiftVT = N->getOperand(1).getValueType(); 5638 SDValue NegatedCount = DAG.getNode(ISD::SUB, dl, ShiftVT, 5639 getZeroVector(ShiftVT, DAG, dl), 5640 N->getOperand(1)); 5641 Intrinsic::ID vshiftInt = (N->getOpcode() == ISD::SRA ? 5642 Intrinsic::arm_neon_vshifts : 5643 Intrinsic::arm_neon_vshiftu); 5644 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT, 5645 DAG.getConstant(vshiftInt, dl, MVT::i32), 5646 N->getOperand(0), NegatedCount); 5647 } 5648 5649 static SDValue Expand64BitShift(SDNode *N, SelectionDAG &DAG, 5650 const ARMSubtarget *ST) { 5651 EVT VT = N->getValueType(0); 5652 SDLoc dl(N); 5653 5654 // We can get here for a node like i32 = ISD::SHL i32, i64 5655 if (VT != MVT::i64) 5656 return SDValue(); 5657 5658 assert((N->getOpcode() == ISD::SRL || N->getOpcode() == ISD::SRA || 5659 N->getOpcode() == ISD::SHL) && 5660 "Unknown shift to lower!"); 5661 5662 unsigned ShOpc = N->getOpcode(); 5663 if (ST->hasMVEIntegerOps()) { 5664 SDValue ShAmt = N->getOperand(1); 5665 unsigned ShPartsOpc = ARMISD::LSLL; 5666 ConstantSDNode *Con = dyn_cast<ConstantSDNode>(ShAmt); 5667 5668 // If the shift amount is greater than 32 then do the default optimisation 5669 if (Con && Con->getZExtValue() > 32) 5670 return SDValue(); 5671 5672 // Extract the lower 32 bits of the shift amount if it's an i64 5673 if (ShAmt->getValueType(0) == MVT::i64) 5674 ShAmt = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, ShAmt, 5675 DAG.getConstant(0, dl, MVT::i32)); 5676 5677 if (ShOpc == ISD::SRL) { 5678 if (!Con) 5679 // There is no t2LSRLr instruction so negate and perform an lsll if the 5680 // shift amount is in a register, emulating a right shift. 5681 ShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32, 5682 DAG.getConstant(0, dl, MVT::i32), ShAmt); 5683 else 5684 // Else generate an lsrl on the immediate shift amount 5685 ShPartsOpc = ARMISD::LSRL; 5686 } else if (ShOpc == ISD::SRA) 5687 ShPartsOpc = ARMISD::ASRL; 5688 5689 // Lower 32 bits of the destination/source 5690 SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(0), 5691 DAG.getConstant(0, dl, MVT::i32)); 5692 // Upper 32 bits of the destination/source 5693 SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(0), 5694 DAG.getConstant(1, dl, MVT::i32)); 5695 5696 // Generate the shift operation as computed above 5697 Lo = DAG.getNode(ShPartsOpc, dl, DAG.getVTList(MVT::i32, MVT::i32), Lo, Hi, 5698 ShAmt); 5699 // The upper 32 bits come from the second return value of lsll 5700 Hi = SDValue(Lo.getNode(), 1); 5701 return DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Lo, Hi); 5702 } 5703 5704 // We only lower SRA, SRL of 1 here, all others use generic lowering. 5705 if (!isOneConstant(N->getOperand(1)) || N->getOpcode() == ISD::SHL) 5706 return SDValue(); 5707 5708 // If we are in thumb mode, we don't have RRX. 5709 if (ST->isThumb1Only()) 5710 return SDValue(); 5711 5712 // Okay, we have a 64-bit SRA or SRL of 1. Lower this to an RRX expr. 5713 SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(0), 5714 DAG.getConstant(0, dl, MVT::i32)); 5715 SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(0), 5716 DAG.getConstant(1, dl, MVT::i32)); 5717 5718 // First, build a SRA_FLAG/SRL_FLAG op, which shifts the top part by one and 5719 // captures the result into a carry flag. 5720 unsigned Opc = N->getOpcode() == ISD::SRL ? ARMISD::SRL_FLAG:ARMISD::SRA_FLAG; 5721 Hi = DAG.getNode(Opc, dl, DAG.getVTList(MVT::i32, MVT::Glue), Hi); 5722 5723 // The low part is an ARMISD::RRX operand, which shifts the carry in. 5724 Lo = DAG.getNode(ARMISD::RRX, dl, MVT::i32, Lo, Hi.getValue(1)); 5725 5726 // Merge the pieces into a single i64 value. 5727 return DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Lo, Hi); 5728 } 5729 5730 static SDValue LowerVSETCC(SDValue Op, SelectionDAG &DAG) { 5731 SDValue TmpOp0, TmpOp1; 5732 bool Invert = false; 5733 bool Swap = false; 5734 unsigned Opc = 0; 5735 5736 SDValue Op0 = Op.getOperand(0); 5737 SDValue Op1 = Op.getOperand(1); 5738 SDValue CC = Op.getOperand(2); 5739 EVT CmpVT = Op0.getValueType().changeVectorElementTypeToInteger(); 5740 EVT VT = Op.getValueType(); 5741 ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get(); 5742 SDLoc dl(Op); 5743 5744 if (Op0.getValueType().getVectorElementType() == MVT::i64 && 5745 (SetCCOpcode == ISD::SETEQ || SetCCOpcode == ISD::SETNE)) { 5746 // Special-case integer 64-bit equality comparisons. They aren't legal, 5747 // but they can be lowered with a few vector instructions. 5748 unsigned CmpElements = CmpVT.getVectorNumElements() * 2; 5749 EVT SplitVT = EVT::getVectorVT(*DAG.getContext(), MVT::i32, CmpElements); 5750 SDValue CastOp0 = DAG.getNode(ISD::BITCAST, dl, SplitVT, Op0); 5751 SDValue CastOp1 = DAG.getNode(ISD::BITCAST, dl, SplitVT, Op1); 5752 SDValue Cmp = DAG.getNode(ISD::SETCC, dl, SplitVT, CastOp0, CastOp1, 5753 DAG.getCondCode(ISD::SETEQ)); 5754 SDValue Reversed = DAG.getNode(ARMISD::VREV64, dl, SplitVT, Cmp); 5755 SDValue Merged = DAG.getNode(ISD::AND, dl, SplitVT, Cmp, Reversed); 5756 Merged = DAG.getNode(ISD::BITCAST, dl, CmpVT, Merged); 5757 if (SetCCOpcode == ISD::SETNE) 5758 Merged = DAG.getNOT(dl, Merged, CmpVT); 5759 Merged = DAG.getSExtOrTrunc(Merged, dl, VT); 5760 return Merged; 5761 } 5762 5763 if (CmpVT.getVectorElementType() == MVT::i64) 5764 // 64-bit comparisons are not legal in general. 5765 return SDValue(); 5766 5767 if (Op1.getValueType().isFloatingPoint()) { 5768 switch (SetCCOpcode) { 5769 default: llvm_unreachable("Illegal FP comparison"); 5770 case ISD::SETUNE: 5771 case ISD::SETNE: Invert = true; LLVM_FALLTHROUGH; 5772 case ISD::SETOEQ: 5773 case ISD::SETEQ: Opc = ARMISD::VCEQ; break; 5774 case ISD::SETOLT: 5775 case ISD::SETLT: Swap = true; LLVM_FALLTHROUGH; 5776 case ISD::SETOGT: 5777 case ISD::SETGT: Opc = ARMISD::VCGT; break; 5778 case ISD::SETOLE: 5779 case ISD::SETLE: Swap = true; LLVM_FALLTHROUGH; 5780 case ISD::SETOGE: 5781 case ISD::SETGE: Opc = ARMISD::VCGE; break; 5782 case ISD::SETUGE: Swap = true; LLVM_FALLTHROUGH; 5783 case ISD::SETULE: Invert = true; Opc = ARMISD::VCGT; break; 5784 case ISD::SETUGT: Swap = true; LLVM_FALLTHROUGH; 5785 case ISD::SETULT: Invert = true; Opc = ARMISD::VCGE; break; 5786 case ISD::SETUEQ: Invert = true; LLVM_FALLTHROUGH; 5787 case ISD::SETONE: 5788 // Expand this to (OLT | OGT). 5789 TmpOp0 = Op0; 5790 TmpOp1 = Op1; 5791 Opc = ISD::OR; 5792 Op0 = DAG.getNode(ARMISD::VCGT, dl, CmpVT, TmpOp1, TmpOp0); 5793 Op1 = DAG.getNode(ARMISD::VCGT, dl, CmpVT, TmpOp0, TmpOp1); 5794 break; 5795 case ISD::SETUO: 5796 Invert = true; 5797 LLVM_FALLTHROUGH; 5798 case ISD::SETO: 5799 // Expand this to (OLT | OGE). 5800 TmpOp0 = Op0; 5801 TmpOp1 = Op1; 5802 Opc = ISD::OR; 5803 Op0 = DAG.getNode(ARMISD::VCGT, dl, CmpVT, TmpOp1, TmpOp0); 5804 Op1 = DAG.getNode(ARMISD::VCGE, dl, CmpVT, TmpOp0, TmpOp1); 5805 break; 5806 } 5807 } else { 5808 // Integer comparisons. 5809 switch (SetCCOpcode) { 5810 default: llvm_unreachable("Illegal integer comparison"); 5811 case ISD::SETNE: Invert = true; LLVM_FALLTHROUGH; 5812 case ISD::SETEQ: Opc = ARMISD::VCEQ; break; 5813 case ISD::SETLT: Swap = true; LLVM_FALLTHROUGH; 5814 case ISD::SETGT: Opc = ARMISD::VCGT; break; 5815 case ISD::SETLE: Swap = true; LLVM_FALLTHROUGH; 5816 case ISD::SETGE: Opc = ARMISD::VCGE; break; 5817 case ISD::SETULT: Swap = true; LLVM_FALLTHROUGH; 5818 case ISD::SETUGT: Opc = ARMISD::VCGTU; break; 5819 case ISD::SETULE: Swap = true; LLVM_FALLTHROUGH; 5820 case ISD::SETUGE: Opc = ARMISD::VCGEU; break; 5821 } 5822 5823 // Detect VTST (Vector Test Bits) = icmp ne (and (op0, op1), zero). 5824 if (Opc == ARMISD::VCEQ) { 5825 SDValue AndOp; 5826 if (ISD::isBuildVectorAllZeros(Op1.getNode())) 5827 AndOp = Op0; 5828 else if (ISD::isBuildVectorAllZeros(Op0.getNode())) 5829 AndOp = Op1; 5830 5831 // Ignore bitconvert. 5832 if (AndOp.getNode() && AndOp.getOpcode() == ISD::BITCAST) 5833 AndOp = AndOp.getOperand(0); 5834 5835 if (AndOp.getNode() && AndOp.getOpcode() == ISD::AND) { 5836 Opc = ARMISD::VTST; 5837 Op0 = DAG.getNode(ISD::BITCAST, dl, CmpVT, AndOp.getOperand(0)); 5838 Op1 = DAG.getNode(ISD::BITCAST, dl, CmpVT, AndOp.getOperand(1)); 5839 Invert = !Invert; 5840 } 5841 } 5842 } 5843 5844 if (Swap) 5845 std::swap(Op0, Op1); 5846 5847 // If one of the operands is a constant vector zero, attempt to fold the 5848 // comparison to a specialized compare-against-zero form. 5849 SDValue SingleOp; 5850 if (ISD::isBuildVectorAllZeros(Op1.getNode())) 5851 SingleOp = Op0; 5852 else if (ISD::isBuildVectorAllZeros(Op0.getNode())) { 5853 if (Opc == ARMISD::VCGE) 5854 Opc = ARMISD::VCLEZ; 5855 else if (Opc == ARMISD::VCGT) 5856 Opc = ARMISD::VCLTZ; 5857 SingleOp = Op1; 5858 } 5859 5860 SDValue Result; 5861 if (SingleOp.getNode()) { 5862 switch (Opc) { 5863 case ARMISD::VCEQ: 5864 Result = DAG.getNode(ARMISD::VCEQZ, dl, CmpVT, SingleOp); break; 5865 case ARMISD::VCGE: 5866 Result = DAG.getNode(ARMISD::VCGEZ, dl, CmpVT, SingleOp); break; 5867 case ARMISD::VCLEZ: 5868 Result = DAG.getNode(ARMISD::VCLEZ, dl, CmpVT, SingleOp); break; 5869 case ARMISD::VCGT: 5870 Result = DAG.getNode(ARMISD::VCGTZ, dl, CmpVT, SingleOp); break; 5871 case ARMISD::VCLTZ: 5872 Result = DAG.getNode(ARMISD::VCLTZ, dl, CmpVT, SingleOp); break; 5873 default: 5874 Result = DAG.getNode(Opc, dl, CmpVT, Op0, Op1); 5875 } 5876 } else { 5877 Result = DAG.getNode(Opc, dl, CmpVT, Op0, Op1); 5878 } 5879 5880 Result = DAG.getSExtOrTrunc(Result, dl, VT); 5881 5882 if (Invert) 5883 Result = DAG.getNOT(dl, Result, VT); 5884 5885 return Result; 5886 } 5887 5888 static SDValue LowerSETCCCARRY(SDValue Op, SelectionDAG &DAG) { 5889 SDValue LHS = Op.getOperand(0); 5890 SDValue RHS = Op.getOperand(1); 5891 SDValue Carry = Op.getOperand(2); 5892 SDValue Cond = Op.getOperand(3); 5893 SDLoc DL(Op); 5894 5895 assert(LHS.getSimpleValueType().isInteger() && "SETCCCARRY is integer only."); 5896 5897 // ARMISD::SUBE expects a carry not a borrow like ISD::SUBCARRY so we 5898 // have to invert the carry first. 5899 Carry = DAG.getNode(ISD::SUB, DL, MVT::i32, 5900 DAG.getConstant(1, DL, MVT::i32), Carry); 5901 // This converts the boolean value carry into the carry flag. 5902 Carry = ConvertBooleanCarryToCarryFlag(Carry, DAG); 5903 5904 SDVTList VTs = DAG.getVTList(LHS.getValueType(), MVT::i32); 5905 SDValue Cmp = DAG.getNode(ARMISD::SUBE, DL, VTs, LHS, RHS, Carry); 5906 5907 SDValue FVal = DAG.getConstant(0, DL, MVT::i32); 5908 SDValue TVal = DAG.getConstant(1, DL, MVT::i32); 5909 SDValue ARMcc = DAG.getConstant( 5910 IntCCToARMCC(cast<CondCodeSDNode>(Cond)->get()), DL, MVT::i32); 5911 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32); 5912 SDValue Chain = DAG.getCopyToReg(DAG.getEntryNode(), DL, ARM::CPSR, 5913 Cmp.getValue(1), SDValue()); 5914 return DAG.getNode(ARMISD::CMOV, DL, Op.getValueType(), FVal, TVal, ARMcc, 5915 CCR, Chain.getValue(1)); 5916 } 5917 5918 /// isNEONModifiedImm - Check if the specified splat value corresponds to a 5919 /// valid vector constant for a NEON instruction with a "modified immediate" 5920 /// operand (e.g., VMOV). If so, return the encoded value. 5921 static SDValue isNEONModifiedImm(uint64_t SplatBits, uint64_t SplatUndef, 5922 unsigned SplatBitSize, SelectionDAG &DAG, 5923 const SDLoc &dl, EVT &VT, bool is128Bits, 5924 NEONModImmType type) { 5925 unsigned OpCmode, Imm; 5926 5927 // SplatBitSize is set to the smallest size that splats the vector, so a 5928 // zero vector will always have SplatBitSize == 8. However, NEON modified 5929 // immediate instructions others than VMOV do not support the 8-bit encoding 5930 // of a zero vector, and the default encoding of zero is supposed to be the 5931 // 32-bit version. 5932 if (SplatBits == 0) 5933 SplatBitSize = 32; 5934 5935 switch (SplatBitSize) { 5936 case 8: 5937 if (type != VMOVModImm) 5938 return SDValue(); 5939 // Any 1-byte value is OK. Op=0, Cmode=1110. 5940 assert((SplatBits & ~0xff) == 0 && "one byte splat value is too big"); 5941 OpCmode = 0xe; 5942 Imm = SplatBits; 5943 VT = is128Bits ? MVT::v16i8 : MVT::v8i8; 5944 break; 5945 5946 case 16: 5947 // NEON's 16-bit VMOV supports splat values where only one byte is nonzero. 5948 VT = is128Bits ? MVT::v8i16 : MVT::v4i16; 5949 if ((SplatBits & ~0xff) == 0) { 5950 // Value = 0x00nn: Op=x, Cmode=100x. 5951 OpCmode = 0x8; 5952 Imm = SplatBits; 5953 break; 5954 } 5955 if ((SplatBits & ~0xff00) == 0) { 5956 // Value = 0xnn00: Op=x, Cmode=101x. 5957 OpCmode = 0xa; 5958 Imm = SplatBits >> 8; 5959 break; 5960 } 5961 return SDValue(); 5962 5963 case 32: 5964 // NEON's 32-bit VMOV supports splat values where: 5965 // * only one byte is nonzero, or 5966 // * the least significant byte is 0xff and the second byte is nonzero, or 5967 // * the least significant 2 bytes are 0xff and the third is nonzero. 5968 VT = is128Bits ? MVT::v4i32 : MVT::v2i32; 5969 if ((SplatBits & ~0xff) == 0) { 5970 // Value = 0x000000nn: Op=x, Cmode=000x. 5971 OpCmode = 0; 5972 Imm = SplatBits; 5973 break; 5974 } 5975 if ((SplatBits & ~0xff00) == 0) { 5976 // Value = 0x0000nn00: Op=x, Cmode=001x. 5977 OpCmode = 0x2; 5978 Imm = SplatBits >> 8; 5979 break; 5980 } 5981 if ((SplatBits & ~0xff0000) == 0) { 5982 // Value = 0x00nn0000: Op=x, Cmode=010x. 5983 OpCmode = 0x4; 5984 Imm = SplatBits >> 16; 5985 break; 5986 } 5987 if ((SplatBits & ~0xff000000) == 0) { 5988 // Value = 0xnn000000: Op=x, Cmode=011x. 5989 OpCmode = 0x6; 5990 Imm = SplatBits >> 24; 5991 break; 5992 } 5993 5994 // cmode == 0b1100 and cmode == 0b1101 are not supported for VORR or VBIC 5995 if (type == OtherModImm) return SDValue(); 5996 5997 if ((SplatBits & ~0xffff) == 0 && 5998 ((SplatBits | SplatUndef) & 0xff) == 0xff) { 5999 // Value = 0x0000nnff: Op=x, Cmode=1100. 6000 OpCmode = 0xc; 6001 Imm = SplatBits >> 8; 6002 break; 6003 } 6004 6005 if ((SplatBits & ~0xffffff) == 0 && 6006 ((SplatBits | SplatUndef) & 0xffff) == 0xffff) { 6007 // Value = 0x00nnffff: Op=x, Cmode=1101. 6008 OpCmode = 0xd; 6009 Imm = SplatBits >> 16; 6010 break; 6011 } 6012 6013 // Note: there are a few 32-bit splat values (specifically: 00ffff00, 6014 // ff000000, ff0000ff, and ffff00ff) that are valid for VMOV.I64 but not 6015 // VMOV.I32. A (very) minor optimization would be to replicate the value 6016 // and fall through here to test for a valid 64-bit splat. But, then the 6017 // caller would also need to check and handle the change in size. 6018 return SDValue(); 6019 6020 case 64: { 6021 if (type != VMOVModImm) 6022 return SDValue(); 6023 // NEON has a 64-bit VMOV splat where each byte is either 0 or 0xff. 6024 uint64_t BitMask = 0xff; 6025 uint64_t Val = 0; 6026 unsigned ImmMask = 1; 6027 Imm = 0; 6028 for (int ByteNum = 0; ByteNum < 8; ++ByteNum) { 6029 if (((SplatBits | SplatUndef) & BitMask) == BitMask) { 6030 Val |= BitMask; 6031 Imm |= ImmMask; 6032 } else if ((SplatBits & BitMask) != 0) { 6033 return SDValue(); 6034 } 6035 BitMask <<= 8; 6036 ImmMask <<= 1; 6037 } 6038 6039 if (DAG.getDataLayout().isBigEndian()) 6040 // swap higher and lower 32 bit word 6041 Imm = ((Imm & 0xf) << 4) | ((Imm & 0xf0) >> 4); 6042 6043 // Op=1, Cmode=1110. 6044 OpCmode = 0x1e; 6045 VT = is128Bits ? MVT::v2i64 : MVT::v1i64; 6046 break; 6047 } 6048 6049 default: 6050 llvm_unreachable("unexpected size for isNEONModifiedImm"); 6051 } 6052 6053 unsigned EncodedVal = ARM_AM::createNEONModImm(OpCmode, Imm); 6054 return DAG.getTargetConstant(EncodedVal, dl, MVT::i32); 6055 } 6056 6057 SDValue ARMTargetLowering::LowerConstantFP(SDValue Op, SelectionDAG &DAG, 6058 const ARMSubtarget *ST) const { 6059 EVT VT = Op.getValueType(); 6060 bool IsDouble = (VT == MVT::f64); 6061 ConstantFPSDNode *CFP = cast<ConstantFPSDNode>(Op); 6062 const APFloat &FPVal = CFP->getValueAPF(); 6063 6064 // Prevent floating-point constants from using literal loads 6065 // when execute-only is enabled. 6066 if (ST->genExecuteOnly()) { 6067 // If we can represent the constant as an immediate, don't lower it 6068 if (isFPImmLegal(FPVal, VT)) 6069 return Op; 6070 // Otherwise, construct as integer, and move to float register 6071 APInt INTVal = FPVal.bitcastToAPInt(); 6072 SDLoc DL(CFP); 6073 switch (VT.getSimpleVT().SimpleTy) { 6074 default: 6075 llvm_unreachable("Unknown floating point type!"); 6076 break; 6077 case MVT::f64: { 6078 SDValue Lo = DAG.getConstant(INTVal.trunc(32), DL, MVT::i32); 6079 SDValue Hi = DAG.getConstant(INTVal.lshr(32).trunc(32), DL, MVT::i32); 6080 if (!ST->isLittle()) 6081 std::swap(Lo, Hi); 6082 return DAG.getNode(ARMISD::VMOVDRR, DL, MVT::f64, Lo, Hi); 6083 } 6084 case MVT::f32: 6085 return DAG.getNode(ARMISD::VMOVSR, DL, VT, 6086 DAG.getConstant(INTVal, DL, MVT::i32)); 6087 } 6088 } 6089 6090 if (!ST->hasVFP3Base()) 6091 return SDValue(); 6092 6093 // Use the default (constant pool) lowering for double constants when we have 6094 // an SP-only FPU 6095 if (IsDouble && !Subtarget->hasFP64()) 6096 return SDValue(); 6097 6098 // Try splatting with a VMOV.f32... 6099 int ImmVal = IsDouble ? ARM_AM::getFP64Imm(FPVal) : ARM_AM::getFP32Imm(FPVal); 6100 6101 if (ImmVal != -1) { 6102 if (IsDouble || !ST->useNEONForSinglePrecisionFP()) { 6103 // We have code in place to select a valid ConstantFP already, no need to 6104 // do any mangling. 6105 return Op; 6106 } 6107 6108 // It's a float and we are trying to use NEON operations where 6109 // possible. Lower it to a splat followed by an extract. 6110 SDLoc DL(Op); 6111 SDValue NewVal = DAG.getTargetConstant(ImmVal, DL, MVT::i32); 6112 SDValue VecConstant = DAG.getNode(ARMISD::VMOVFPIMM, DL, MVT::v2f32, 6113 NewVal); 6114 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32, VecConstant, 6115 DAG.getConstant(0, DL, MVT::i32)); 6116 } 6117 6118 // The rest of our options are NEON only, make sure that's allowed before 6119 // proceeding.. 6120 if (!ST->hasNEON() || (!IsDouble && !ST->useNEONForSinglePrecisionFP())) 6121 return SDValue(); 6122 6123 EVT VMovVT; 6124 uint64_t iVal = FPVal.bitcastToAPInt().getZExtValue(); 6125 6126 // It wouldn't really be worth bothering for doubles except for one very 6127 // important value, which does happen to match: 0.0. So make sure we don't do 6128 // anything stupid. 6129 if (IsDouble && (iVal & 0xffffffff) != (iVal >> 32)) 6130 return SDValue(); 6131 6132 // Try a VMOV.i32 (FIXME: i8, i16, or i64 could work too). 6133 SDValue NewVal = isNEONModifiedImm(iVal & 0xffffffffU, 0, 32, DAG, SDLoc(Op), 6134 VMovVT, false, VMOVModImm); 6135 if (NewVal != SDValue()) { 6136 SDLoc DL(Op); 6137 SDValue VecConstant = DAG.getNode(ARMISD::VMOVIMM, DL, VMovVT, 6138 NewVal); 6139 if (IsDouble) 6140 return DAG.getNode(ISD::BITCAST, DL, MVT::f64, VecConstant); 6141 6142 // It's a float: cast and extract a vector element. 6143 SDValue VecFConstant = DAG.getNode(ISD::BITCAST, DL, MVT::v2f32, 6144 VecConstant); 6145 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32, VecFConstant, 6146 DAG.getConstant(0, DL, MVT::i32)); 6147 } 6148 6149 // Finally, try a VMVN.i32 6150 NewVal = isNEONModifiedImm(~iVal & 0xffffffffU, 0, 32, DAG, SDLoc(Op), VMovVT, 6151 false, VMVNModImm); 6152 if (NewVal != SDValue()) { 6153 SDLoc DL(Op); 6154 SDValue VecConstant = DAG.getNode(ARMISD::VMVNIMM, DL, VMovVT, NewVal); 6155 6156 if (IsDouble) 6157 return DAG.getNode(ISD::BITCAST, DL, MVT::f64, VecConstant); 6158 6159 // It's a float: cast and extract a vector element. 6160 SDValue VecFConstant = DAG.getNode(ISD::BITCAST, DL, MVT::v2f32, 6161 VecConstant); 6162 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32, VecFConstant, 6163 DAG.getConstant(0, DL, MVT::i32)); 6164 } 6165 6166 return SDValue(); 6167 } 6168 6169 // check if an VEXT instruction can handle the shuffle mask when the 6170 // vector sources of the shuffle are the same. 6171 static bool isSingletonVEXTMask(ArrayRef<int> M, EVT VT, unsigned &Imm) { 6172 unsigned NumElts = VT.getVectorNumElements(); 6173 6174 // Assume that the first shuffle index is not UNDEF. Fail if it is. 6175 if (M[0] < 0) 6176 return false; 6177 6178 Imm = M[0]; 6179 6180 // If this is a VEXT shuffle, the immediate value is the index of the first 6181 // element. The other shuffle indices must be the successive elements after 6182 // the first one. 6183 unsigned ExpectedElt = Imm; 6184 for (unsigned i = 1; i < NumElts; ++i) { 6185 // Increment the expected index. If it wraps around, just follow it 6186 // back to index zero and keep going. 6187 ++ExpectedElt; 6188 if (ExpectedElt == NumElts) 6189 ExpectedElt = 0; 6190 6191 if (M[i] < 0) continue; // ignore UNDEF indices 6192 if (ExpectedElt != static_cast<unsigned>(M[i])) 6193 return false; 6194 } 6195 6196 return true; 6197 } 6198 6199 static bool isVEXTMask(ArrayRef<int> M, EVT VT, 6200 bool &ReverseVEXT, unsigned &Imm) { 6201 unsigned NumElts = VT.getVectorNumElements(); 6202 ReverseVEXT = false; 6203 6204 // Assume that the first shuffle index is not UNDEF. Fail if it is. 6205 if (M[0] < 0) 6206 return false; 6207 6208 Imm = M[0]; 6209 6210 // If this is a VEXT shuffle, the immediate value is the index of the first 6211 // element. The other shuffle indices must be the successive elements after 6212 // the first one. 6213 unsigned ExpectedElt = Imm; 6214 for (unsigned i = 1; i < NumElts; ++i) { 6215 // Increment the expected index. If it wraps around, it may still be 6216 // a VEXT but the source vectors must be swapped. 6217 ExpectedElt += 1; 6218 if (ExpectedElt == NumElts * 2) { 6219 ExpectedElt = 0; 6220 ReverseVEXT = true; 6221 } 6222 6223 if (M[i] < 0) continue; // ignore UNDEF indices 6224 if (ExpectedElt != static_cast<unsigned>(M[i])) 6225 return false; 6226 } 6227 6228 // Adjust the index value if the source operands will be swapped. 6229 if (ReverseVEXT) 6230 Imm -= NumElts; 6231 6232 return true; 6233 } 6234 6235 /// isVREVMask - Check if a vector shuffle corresponds to a VREV 6236 /// instruction with the specified blocksize. (The order of the elements 6237 /// within each block of the vector is reversed.) 6238 static bool isVREVMask(ArrayRef<int> M, EVT VT, unsigned BlockSize) { 6239 assert((BlockSize==16 || BlockSize==32 || BlockSize==64) && 6240 "Only possible block sizes for VREV are: 16, 32, 64"); 6241 6242 unsigned EltSz = VT.getScalarSizeInBits(); 6243 if (EltSz == 64) 6244 return false; 6245 6246 unsigned NumElts = VT.getVectorNumElements(); 6247 unsigned BlockElts = M[0] + 1; 6248 // If the first shuffle index is UNDEF, be optimistic. 6249 if (M[0] < 0) 6250 BlockElts = BlockSize / EltSz; 6251 6252 if (BlockSize <= EltSz || BlockSize != BlockElts * EltSz) 6253 return false; 6254 6255 for (unsigned i = 0; i < NumElts; ++i) { 6256 if (M[i] < 0) continue; // ignore UNDEF indices 6257 if ((unsigned) M[i] != (i - i%BlockElts) + (BlockElts - 1 - i%BlockElts)) 6258 return false; 6259 } 6260 6261 return true; 6262 } 6263 6264 static bool isVTBLMask(ArrayRef<int> M, EVT VT) { 6265 // We can handle <8 x i8> vector shuffles. If the index in the mask is out of 6266 // range, then 0 is placed into the resulting vector. So pretty much any mask 6267 // of 8 elements can work here. 6268 return VT == MVT::v8i8 && M.size() == 8; 6269 } 6270 6271 static unsigned SelectPairHalf(unsigned Elements, ArrayRef<int> Mask, 6272 unsigned Index) { 6273 if (Mask.size() == Elements * 2) 6274 return Index / Elements; 6275 return Mask[Index] == 0 ? 0 : 1; 6276 } 6277 6278 // Checks whether the shuffle mask represents a vector transpose (VTRN) by 6279 // checking that pairs of elements in the shuffle mask represent the same index 6280 // in each vector, incrementing the expected index by 2 at each step. 6281 // e.g. For v1,v2 of type v4i32 a valid shuffle mask is: [0, 4, 2, 6] 6282 // v1={a,b,c,d} => x=shufflevector v1, v2 shufflemask => x={a,e,c,g} 6283 // v2={e,f,g,h} 6284 // WhichResult gives the offset for each element in the mask based on which 6285 // of the two results it belongs to. 6286 // 6287 // The transpose can be represented either as: 6288 // result1 = shufflevector v1, v2, result1_shuffle_mask 6289 // result2 = shufflevector v1, v2, result2_shuffle_mask 6290 // where v1/v2 and the shuffle masks have the same number of elements 6291 // (here WhichResult (see below) indicates which result is being checked) 6292 // 6293 // or as: 6294 // results = shufflevector v1, v2, shuffle_mask 6295 // where both results are returned in one vector and the shuffle mask has twice 6296 // as many elements as v1/v2 (here WhichResult will always be 0 if true) here we 6297 // want to check the low half and high half of the shuffle mask as if it were 6298 // the other case 6299 static bool isVTRNMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) { 6300 unsigned EltSz = VT.getScalarSizeInBits(); 6301 if (EltSz == 64) 6302 return false; 6303 6304 unsigned NumElts = VT.getVectorNumElements(); 6305 if (M.size() != NumElts && M.size() != NumElts*2) 6306 return false; 6307 6308 // If the mask is twice as long as the input vector then we need to check the 6309 // upper and lower parts of the mask with a matching value for WhichResult 6310 // FIXME: A mask with only even values will be rejected in case the first 6311 // element is undefined, e.g. [-1, 4, 2, 6] will be rejected, because only 6312 // M[0] is used to determine WhichResult 6313 for (unsigned i = 0; i < M.size(); i += NumElts) { 6314 WhichResult = SelectPairHalf(NumElts, M, i); 6315 for (unsigned j = 0; j < NumElts; j += 2) { 6316 if ((M[i+j] >= 0 && (unsigned) M[i+j] != j + WhichResult) || 6317 (M[i+j+1] >= 0 && (unsigned) M[i+j+1] != j + NumElts + WhichResult)) 6318 return false; 6319 } 6320 } 6321 6322 if (M.size() == NumElts*2) 6323 WhichResult = 0; 6324 6325 return true; 6326 } 6327 6328 /// isVTRN_v_undef_Mask - Special case of isVTRNMask for canonical form of 6329 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef". 6330 /// Mask is e.g., <0, 0, 2, 2> instead of <0, 4, 2, 6>. 6331 static bool isVTRN_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult){ 6332 unsigned EltSz = VT.getScalarSizeInBits(); 6333 if (EltSz == 64) 6334 return false; 6335 6336 unsigned NumElts = VT.getVectorNumElements(); 6337 if (M.size() != NumElts && M.size() != NumElts*2) 6338 return false; 6339 6340 for (unsigned i = 0; i < M.size(); i += NumElts) { 6341 WhichResult = SelectPairHalf(NumElts, M, i); 6342 for (unsigned j = 0; j < NumElts; j += 2) { 6343 if ((M[i+j] >= 0 && (unsigned) M[i+j] != j + WhichResult) || 6344 (M[i+j+1] >= 0 && (unsigned) M[i+j+1] != j + WhichResult)) 6345 return false; 6346 } 6347 } 6348 6349 if (M.size() == NumElts*2) 6350 WhichResult = 0; 6351 6352 return true; 6353 } 6354 6355 // Checks whether the shuffle mask represents a vector unzip (VUZP) by checking 6356 // that the mask elements are either all even and in steps of size 2 or all odd 6357 // and in steps of size 2. 6358 // e.g. For v1,v2 of type v4i32 a valid shuffle mask is: [0, 2, 4, 6] 6359 // v1={a,b,c,d} => x=shufflevector v1, v2 shufflemask => x={a,c,e,g} 6360 // v2={e,f,g,h} 6361 // Requires similar checks to that of isVTRNMask with 6362 // respect the how results are returned. 6363 static bool isVUZPMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) { 6364 unsigned EltSz = VT.getScalarSizeInBits(); 6365 if (EltSz == 64) 6366 return false; 6367 6368 unsigned NumElts = VT.getVectorNumElements(); 6369 if (M.size() != NumElts && M.size() != NumElts*2) 6370 return false; 6371 6372 for (unsigned i = 0; i < M.size(); i += NumElts) { 6373 WhichResult = SelectPairHalf(NumElts, M, i); 6374 for (unsigned j = 0; j < NumElts; ++j) { 6375 if (M[i+j] >= 0 && (unsigned) M[i+j] != 2 * j + WhichResult) 6376 return false; 6377 } 6378 } 6379 6380 if (M.size() == NumElts*2) 6381 WhichResult = 0; 6382 6383 // VUZP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32. 6384 if (VT.is64BitVector() && EltSz == 32) 6385 return false; 6386 6387 return true; 6388 } 6389 6390 /// isVUZP_v_undef_Mask - Special case of isVUZPMask for canonical form of 6391 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef". 6392 /// Mask is e.g., <0, 2, 0, 2> instead of <0, 2, 4, 6>, 6393 static bool isVUZP_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult){ 6394 unsigned EltSz = VT.getScalarSizeInBits(); 6395 if (EltSz == 64) 6396 return false; 6397 6398 unsigned NumElts = VT.getVectorNumElements(); 6399 if (M.size() != NumElts && M.size() != NumElts*2) 6400 return false; 6401 6402 unsigned Half = NumElts / 2; 6403 for (unsigned i = 0; i < M.size(); i += NumElts) { 6404 WhichResult = SelectPairHalf(NumElts, M, i); 6405 for (unsigned j = 0; j < NumElts; j += Half) { 6406 unsigned Idx = WhichResult; 6407 for (unsigned k = 0; k < Half; ++k) { 6408 int MIdx = M[i + j + k]; 6409 if (MIdx >= 0 && (unsigned) MIdx != Idx) 6410 return false; 6411 Idx += 2; 6412 } 6413 } 6414 } 6415 6416 if (M.size() == NumElts*2) 6417 WhichResult = 0; 6418 6419 // VUZP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32. 6420 if (VT.is64BitVector() && EltSz == 32) 6421 return false; 6422 6423 return true; 6424 } 6425 6426 // Checks whether the shuffle mask represents a vector zip (VZIP) by checking 6427 // that pairs of elements of the shufflemask represent the same index in each 6428 // vector incrementing sequentially through the vectors. 6429 // e.g. For v1,v2 of type v4i32 a valid shuffle mask is: [0, 4, 1, 5] 6430 // v1={a,b,c,d} => x=shufflevector v1, v2 shufflemask => x={a,e,b,f} 6431 // v2={e,f,g,h} 6432 // Requires similar checks to that of isVTRNMask with respect the how results 6433 // are returned. 6434 static bool isVZIPMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) { 6435 unsigned EltSz = VT.getScalarSizeInBits(); 6436 if (EltSz == 64) 6437 return false; 6438 6439 unsigned NumElts = VT.getVectorNumElements(); 6440 if (M.size() != NumElts && M.size() != NumElts*2) 6441 return false; 6442 6443 for (unsigned i = 0; i < M.size(); i += NumElts) { 6444 WhichResult = SelectPairHalf(NumElts, M, i); 6445 unsigned Idx = WhichResult * NumElts / 2; 6446 for (unsigned j = 0; j < NumElts; j += 2) { 6447 if ((M[i+j] >= 0 && (unsigned) M[i+j] != Idx) || 6448 (M[i+j+1] >= 0 && (unsigned) M[i+j+1] != Idx + NumElts)) 6449 return false; 6450 Idx += 1; 6451 } 6452 } 6453 6454 if (M.size() == NumElts*2) 6455 WhichResult = 0; 6456 6457 // VZIP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32. 6458 if (VT.is64BitVector() && EltSz == 32) 6459 return false; 6460 6461 return true; 6462 } 6463 6464 /// isVZIP_v_undef_Mask - Special case of isVZIPMask for canonical form of 6465 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef". 6466 /// Mask is e.g., <0, 0, 1, 1> instead of <0, 4, 1, 5>. 6467 static bool isVZIP_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult){ 6468 unsigned EltSz = VT.getScalarSizeInBits(); 6469 if (EltSz == 64) 6470 return false; 6471 6472 unsigned NumElts = VT.getVectorNumElements(); 6473 if (M.size() != NumElts && M.size() != NumElts*2) 6474 return false; 6475 6476 for (unsigned i = 0; i < M.size(); i += NumElts) { 6477 WhichResult = SelectPairHalf(NumElts, M, i); 6478 unsigned Idx = WhichResult * NumElts / 2; 6479 for (unsigned j = 0; j < NumElts; j += 2) { 6480 if ((M[i+j] >= 0 && (unsigned) M[i+j] != Idx) || 6481 (M[i+j+1] >= 0 && (unsigned) M[i+j+1] != Idx)) 6482 return false; 6483 Idx += 1; 6484 } 6485 } 6486 6487 if (M.size() == NumElts*2) 6488 WhichResult = 0; 6489 6490 // VZIP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32. 6491 if (VT.is64BitVector() && EltSz == 32) 6492 return false; 6493 6494 return true; 6495 } 6496 6497 /// Check if \p ShuffleMask is a NEON two-result shuffle (VZIP, VUZP, VTRN), 6498 /// and return the corresponding ARMISD opcode if it is, or 0 if it isn't. 6499 static unsigned isNEONTwoResultShuffleMask(ArrayRef<int> ShuffleMask, EVT VT, 6500 unsigned &WhichResult, 6501 bool &isV_UNDEF) { 6502 isV_UNDEF = false; 6503 if (isVTRNMask(ShuffleMask, VT, WhichResult)) 6504 return ARMISD::VTRN; 6505 if (isVUZPMask(ShuffleMask, VT, WhichResult)) 6506 return ARMISD::VUZP; 6507 if (isVZIPMask(ShuffleMask, VT, WhichResult)) 6508 return ARMISD::VZIP; 6509 6510 isV_UNDEF = true; 6511 if (isVTRN_v_undef_Mask(ShuffleMask, VT, WhichResult)) 6512 return ARMISD::VTRN; 6513 if (isVUZP_v_undef_Mask(ShuffleMask, VT, WhichResult)) 6514 return ARMISD::VUZP; 6515 if (isVZIP_v_undef_Mask(ShuffleMask, VT, WhichResult)) 6516 return ARMISD::VZIP; 6517 6518 return 0; 6519 } 6520 6521 /// \return true if this is a reverse operation on an vector. 6522 static bool isReverseMask(ArrayRef<int> M, EVT VT) { 6523 unsigned NumElts = VT.getVectorNumElements(); 6524 // Make sure the mask has the right size. 6525 if (NumElts != M.size()) 6526 return false; 6527 6528 // Look for <15, ..., 3, -1, 1, 0>. 6529 for (unsigned i = 0; i != NumElts; ++i) 6530 if (M[i] >= 0 && M[i] != (int) (NumElts - 1 - i)) 6531 return false; 6532 6533 return true; 6534 } 6535 6536 // If N is an integer constant that can be moved into a register in one 6537 // instruction, return an SDValue of such a constant (will become a MOV 6538 // instruction). Otherwise return null. 6539 static SDValue IsSingleInstrConstant(SDValue N, SelectionDAG &DAG, 6540 const ARMSubtarget *ST, const SDLoc &dl) { 6541 uint64_t Val; 6542 if (!isa<ConstantSDNode>(N)) 6543 return SDValue(); 6544 Val = cast<ConstantSDNode>(N)->getZExtValue(); 6545 6546 if (ST->isThumb1Only()) { 6547 if (Val <= 255 || ~Val <= 255) 6548 return DAG.getConstant(Val, dl, MVT::i32); 6549 } else { 6550 if (ARM_AM::getSOImmVal(Val) != -1 || ARM_AM::getSOImmVal(~Val) != -1) 6551 return DAG.getConstant(Val, dl, MVT::i32); 6552 } 6553 return SDValue(); 6554 } 6555 6556 // If this is a case we can't handle, return null and let the default 6557 // expansion code take care of it. 6558 SDValue ARMTargetLowering::LowerBUILD_VECTOR(SDValue Op, SelectionDAG &DAG, 6559 const ARMSubtarget *ST) const { 6560 BuildVectorSDNode *BVN = cast<BuildVectorSDNode>(Op.getNode()); 6561 SDLoc dl(Op); 6562 EVT VT = Op.getValueType(); 6563 6564 APInt SplatBits, SplatUndef; 6565 unsigned SplatBitSize; 6566 bool HasAnyUndefs; 6567 if (BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs)) { 6568 if (SplatUndef.isAllOnesValue()) 6569 return DAG.getUNDEF(VT); 6570 6571 if (ST->hasNEON() && SplatBitSize <= 64) { 6572 // Check if an immediate VMOV works. 6573 EVT VmovVT; 6574 SDValue Val = isNEONModifiedImm(SplatBits.getZExtValue(), 6575 SplatUndef.getZExtValue(), SplatBitSize, 6576 DAG, dl, VmovVT, VT.is128BitVector(), 6577 VMOVModImm); 6578 if (Val.getNode()) { 6579 SDValue Vmov = DAG.getNode(ARMISD::VMOVIMM, dl, VmovVT, Val); 6580 return DAG.getNode(ISD::BITCAST, dl, VT, Vmov); 6581 } 6582 6583 // Try an immediate VMVN. 6584 uint64_t NegatedImm = (~SplatBits).getZExtValue(); 6585 Val = isNEONModifiedImm(NegatedImm, 6586 SplatUndef.getZExtValue(), SplatBitSize, 6587 DAG, dl, VmovVT, VT.is128BitVector(), 6588 VMVNModImm); 6589 if (Val.getNode()) { 6590 SDValue Vmov = DAG.getNode(ARMISD::VMVNIMM, dl, VmovVT, Val); 6591 return DAG.getNode(ISD::BITCAST, dl, VT, Vmov); 6592 } 6593 6594 // Use vmov.f32 to materialize other v2f32 and v4f32 splats. 6595 if ((VT == MVT::v2f32 || VT == MVT::v4f32) && SplatBitSize == 32) { 6596 int ImmVal = ARM_AM::getFP32Imm(SplatBits); 6597 if (ImmVal != -1) { 6598 SDValue Val = DAG.getTargetConstant(ImmVal, dl, MVT::i32); 6599 return DAG.getNode(ARMISD::VMOVFPIMM, dl, VT, Val); 6600 } 6601 } 6602 } 6603 } 6604 6605 // Scan through the operands to see if only one value is used. 6606 // 6607 // As an optimisation, even if more than one value is used it may be more 6608 // profitable to splat with one value then change some lanes. 6609 // 6610 // Heuristically we decide to do this if the vector has a "dominant" value, 6611 // defined as splatted to more than half of the lanes. 6612 unsigned NumElts = VT.getVectorNumElements(); 6613 bool isOnlyLowElement = true; 6614 bool usesOnlyOneValue = true; 6615 bool hasDominantValue = false; 6616 bool isConstant = true; 6617 6618 // Map of the number of times a particular SDValue appears in the 6619 // element list. 6620 DenseMap<SDValue, unsigned> ValueCounts; 6621 SDValue Value; 6622 for (unsigned i = 0; i < NumElts; ++i) { 6623 SDValue V = Op.getOperand(i); 6624 if (V.isUndef()) 6625 continue; 6626 if (i > 0) 6627 isOnlyLowElement = false; 6628 if (!isa<ConstantFPSDNode>(V) && !isa<ConstantSDNode>(V)) 6629 isConstant = false; 6630 6631 ValueCounts.insert(std::make_pair(V, 0)); 6632 unsigned &Count = ValueCounts[V]; 6633 6634 // Is this value dominant? (takes up more than half of the lanes) 6635 if (++Count > (NumElts / 2)) { 6636 hasDominantValue = true; 6637 Value = V; 6638 } 6639 } 6640 if (ValueCounts.size() != 1) 6641 usesOnlyOneValue = false; 6642 if (!Value.getNode() && !ValueCounts.empty()) 6643 Value = ValueCounts.begin()->first; 6644 6645 if (ValueCounts.empty()) 6646 return DAG.getUNDEF(VT); 6647 6648 // Loads are better lowered with insert_vector_elt/ARMISD::BUILD_VECTOR. 6649 // Keep going if we are hitting this case. 6650 if (isOnlyLowElement && !ISD::isNormalLoad(Value.getNode())) 6651 return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Value); 6652 6653 unsigned EltSize = VT.getScalarSizeInBits(); 6654 6655 // Use VDUP for non-constant splats. For f32 constant splats, reduce to 6656 // i32 and try again. 6657 if (hasDominantValue && EltSize <= 32) { 6658 if (!isConstant) { 6659 SDValue N; 6660 6661 // If we are VDUPing a value that comes directly from a vector, that will 6662 // cause an unnecessary move to and from a GPR, where instead we could 6663 // just use VDUPLANE. We can only do this if the lane being extracted 6664 // is at a constant index, as the VDUP from lane instructions only have 6665 // constant-index forms. 6666 ConstantSDNode *constIndex; 6667 if (Value->getOpcode() == ISD::EXTRACT_VECTOR_ELT && 6668 (constIndex = dyn_cast<ConstantSDNode>(Value->getOperand(1)))) { 6669 // We need to create a new undef vector to use for the VDUPLANE if the 6670 // size of the vector from which we get the value is different than the 6671 // size of the vector that we need to create. We will insert the element 6672 // such that the register coalescer will remove unnecessary copies. 6673 if (VT != Value->getOperand(0).getValueType()) { 6674 unsigned index = constIndex->getAPIntValue().getLimitedValue() % 6675 VT.getVectorNumElements(); 6676 N = DAG.getNode(ARMISD::VDUPLANE, dl, VT, 6677 DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, DAG.getUNDEF(VT), 6678 Value, DAG.getConstant(index, dl, MVT::i32)), 6679 DAG.getConstant(index, dl, MVT::i32)); 6680 } else 6681 N = DAG.getNode(ARMISD::VDUPLANE, dl, VT, 6682 Value->getOperand(0), Value->getOperand(1)); 6683 } else 6684 N = DAG.getNode(ARMISD::VDUP, dl, VT, Value); 6685 6686 if (!usesOnlyOneValue) { 6687 // The dominant value was splatted as 'N', but we now have to insert 6688 // all differing elements. 6689 for (unsigned I = 0; I < NumElts; ++I) { 6690 if (Op.getOperand(I) == Value) 6691 continue; 6692 SmallVector<SDValue, 3> Ops; 6693 Ops.push_back(N); 6694 Ops.push_back(Op.getOperand(I)); 6695 Ops.push_back(DAG.getConstant(I, dl, MVT::i32)); 6696 N = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Ops); 6697 } 6698 } 6699 return N; 6700 } 6701 if (VT.getVectorElementType().isFloatingPoint()) { 6702 SmallVector<SDValue, 8> Ops; 6703 MVT FVT = VT.getVectorElementType().getSimpleVT(); 6704 assert(FVT == MVT::f32 || FVT == MVT::f16); 6705 MVT IVT = (FVT == MVT::f32) ? MVT::i32 : MVT::i16; 6706 for (unsigned i = 0; i < NumElts; ++i) 6707 Ops.push_back(DAG.getNode(ISD::BITCAST, dl, IVT, 6708 Op.getOperand(i))); 6709 EVT VecVT = EVT::getVectorVT(*DAG.getContext(), IVT, NumElts); 6710 SDValue Val = DAG.getBuildVector(VecVT, dl, Ops); 6711 Val = LowerBUILD_VECTOR(Val, DAG, ST); 6712 if (Val.getNode()) 6713 return DAG.getNode(ISD::BITCAST, dl, VT, Val); 6714 } 6715 if (usesOnlyOneValue) { 6716 SDValue Val = IsSingleInstrConstant(Value, DAG, ST, dl); 6717 if (isConstant && Val.getNode()) 6718 return DAG.getNode(ARMISD::VDUP, dl, VT, Val); 6719 } 6720 } 6721 6722 // If all elements are constants and the case above didn't get hit, fall back 6723 // to the default expansion, which will generate a load from the constant 6724 // pool. 6725 if (isConstant) 6726 return SDValue(); 6727 6728 // Empirical tests suggest this is rarely worth it for vectors of length <= 2. 6729 if (NumElts >= 4) { 6730 SDValue shuffle = ReconstructShuffle(Op, DAG); 6731 if (shuffle != SDValue()) 6732 return shuffle; 6733 } 6734 6735 if (ST->hasNEON() && VT.is128BitVector() && VT != MVT::v2f64 && VT != MVT::v4f32) { 6736 // If we haven't found an efficient lowering, try splitting a 128-bit vector 6737 // into two 64-bit vectors; we might discover a better way to lower it. 6738 SmallVector<SDValue, 64> Ops(Op->op_begin(), Op->op_begin() + NumElts); 6739 EVT ExtVT = VT.getVectorElementType(); 6740 EVT HVT = EVT::getVectorVT(*DAG.getContext(), ExtVT, NumElts / 2); 6741 SDValue Lower = 6742 DAG.getBuildVector(HVT, dl, makeArrayRef(&Ops[0], NumElts / 2)); 6743 if (Lower.getOpcode() == ISD::BUILD_VECTOR) 6744 Lower = LowerBUILD_VECTOR(Lower, DAG, ST); 6745 SDValue Upper = DAG.getBuildVector( 6746 HVT, dl, makeArrayRef(&Ops[NumElts / 2], NumElts / 2)); 6747 if (Upper.getOpcode() == ISD::BUILD_VECTOR) 6748 Upper = LowerBUILD_VECTOR(Upper, DAG, ST); 6749 if (Lower && Upper) 6750 return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, Lower, Upper); 6751 } 6752 6753 // Vectors with 32- or 64-bit elements can be built by directly assigning 6754 // the subregisters. Lower it to an ARMISD::BUILD_VECTOR so the operands 6755 // will be legalized. 6756 if (EltSize >= 32) { 6757 // Do the expansion with floating-point types, since that is what the VFP 6758 // registers are defined to use, and since i64 is not legal. 6759 EVT EltVT = EVT::getFloatingPointVT(EltSize); 6760 EVT VecVT = EVT::getVectorVT(*DAG.getContext(), EltVT, NumElts); 6761 SmallVector<SDValue, 8> Ops; 6762 for (unsigned i = 0; i < NumElts; ++i) 6763 Ops.push_back(DAG.getNode(ISD::BITCAST, dl, EltVT, Op.getOperand(i))); 6764 SDValue Val = DAG.getNode(ARMISD::BUILD_VECTOR, dl, VecVT, Ops); 6765 return DAG.getNode(ISD::BITCAST, dl, VT, Val); 6766 } 6767 6768 // If all else fails, just use a sequence of INSERT_VECTOR_ELT when we 6769 // know the default expansion would otherwise fall back on something even 6770 // worse. For a vector with one or two non-undef values, that's 6771 // scalar_to_vector for the elements followed by a shuffle (provided the 6772 // shuffle is valid for the target) and materialization element by element 6773 // on the stack followed by a load for everything else. 6774 if (!isConstant && !usesOnlyOneValue) { 6775 SDValue Vec = DAG.getUNDEF(VT); 6776 for (unsigned i = 0 ; i < NumElts; ++i) { 6777 SDValue V = Op.getOperand(i); 6778 if (V.isUndef()) 6779 continue; 6780 SDValue LaneIdx = DAG.getConstant(i, dl, MVT::i32); 6781 Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Vec, V, LaneIdx); 6782 } 6783 return Vec; 6784 } 6785 6786 return SDValue(); 6787 } 6788 6789 // Gather data to see if the operation can be modelled as a 6790 // shuffle in combination with VEXTs. 6791 SDValue ARMTargetLowering::ReconstructShuffle(SDValue Op, 6792 SelectionDAG &DAG) const { 6793 assert(Op.getOpcode() == ISD::BUILD_VECTOR && "Unknown opcode!"); 6794 SDLoc dl(Op); 6795 EVT VT = Op.getValueType(); 6796 unsigned NumElts = VT.getVectorNumElements(); 6797 6798 struct ShuffleSourceInfo { 6799 SDValue Vec; 6800 unsigned MinElt = std::numeric_limits<unsigned>::max(); 6801 unsigned MaxElt = 0; 6802 6803 // We may insert some combination of BITCASTs and VEXT nodes to force Vec to 6804 // be compatible with the shuffle we intend to construct. As a result 6805 // ShuffleVec will be some sliding window into the original Vec. 6806 SDValue ShuffleVec; 6807 6808 // Code should guarantee that element i in Vec starts at element "WindowBase 6809 // + i * WindowScale in ShuffleVec". 6810 int WindowBase = 0; 6811 int WindowScale = 1; 6812 6813 ShuffleSourceInfo(SDValue Vec) : Vec(Vec), ShuffleVec(Vec) {} 6814 6815 bool operator ==(SDValue OtherVec) { return Vec == OtherVec; } 6816 }; 6817 6818 // First gather all vectors used as an immediate source for this BUILD_VECTOR 6819 // node. 6820 SmallVector<ShuffleSourceInfo, 2> Sources; 6821 for (unsigned i = 0; i < NumElts; ++i) { 6822 SDValue V = Op.getOperand(i); 6823 if (V.isUndef()) 6824 continue; 6825 else if (V.getOpcode() != ISD::EXTRACT_VECTOR_ELT) { 6826 // A shuffle can only come from building a vector from various 6827 // elements of other vectors. 6828 return SDValue(); 6829 } else if (!isa<ConstantSDNode>(V.getOperand(1))) { 6830 // Furthermore, shuffles require a constant mask, whereas extractelts 6831 // accept variable indices. 6832 return SDValue(); 6833 } 6834 6835 // Add this element source to the list if it's not already there. 6836 SDValue SourceVec = V.getOperand(0); 6837 auto Source = llvm::find(Sources, SourceVec); 6838 if (Source == Sources.end()) 6839 Source = Sources.insert(Sources.end(), ShuffleSourceInfo(SourceVec)); 6840 6841 // Update the minimum and maximum lane number seen. 6842 unsigned EltNo = cast<ConstantSDNode>(V.getOperand(1))->getZExtValue(); 6843 Source->MinElt = std::min(Source->MinElt, EltNo); 6844 Source->MaxElt = std::max(Source->MaxElt, EltNo); 6845 } 6846 6847 // Currently only do something sane when at most two source vectors 6848 // are involved. 6849 if (Sources.size() > 2) 6850 return SDValue(); 6851 6852 // Find out the smallest element size among result and two sources, and use 6853 // it as element size to build the shuffle_vector. 6854 EVT SmallestEltTy = VT.getVectorElementType(); 6855 for (auto &Source : Sources) { 6856 EVT SrcEltTy = Source.Vec.getValueType().getVectorElementType(); 6857 if (SrcEltTy.bitsLT(SmallestEltTy)) 6858 SmallestEltTy = SrcEltTy; 6859 } 6860 unsigned ResMultiplier = 6861 VT.getScalarSizeInBits() / SmallestEltTy.getSizeInBits(); 6862 NumElts = VT.getSizeInBits() / SmallestEltTy.getSizeInBits(); 6863 EVT ShuffleVT = EVT::getVectorVT(*DAG.getContext(), SmallestEltTy, NumElts); 6864 6865 // If the source vector is too wide or too narrow, we may nevertheless be able 6866 // to construct a compatible shuffle either by concatenating it with UNDEF or 6867 // extracting a suitable range of elements. 6868 for (auto &Src : Sources) { 6869 EVT SrcVT = Src.ShuffleVec.getValueType(); 6870 6871 if (SrcVT.getSizeInBits() == VT.getSizeInBits()) 6872 continue; 6873 6874 // This stage of the search produces a source with the same element type as 6875 // the original, but with a total width matching the BUILD_VECTOR output. 6876 EVT EltVT = SrcVT.getVectorElementType(); 6877 unsigned NumSrcElts = VT.getSizeInBits() / EltVT.getSizeInBits(); 6878 EVT DestVT = EVT::getVectorVT(*DAG.getContext(), EltVT, NumSrcElts); 6879 6880 if (SrcVT.getSizeInBits() < VT.getSizeInBits()) { 6881 if (2 * SrcVT.getSizeInBits() != VT.getSizeInBits()) 6882 return SDValue(); 6883 // We can pad out the smaller vector for free, so if it's part of a 6884 // shuffle... 6885 Src.ShuffleVec = 6886 DAG.getNode(ISD::CONCAT_VECTORS, dl, DestVT, Src.ShuffleVec, 6887 DAG.getUNDEF(Src.ShuffleVec.getValueType())); 6888 continue; 6889 } 6890 6891 if (SrcVT.getSizeInBits() != 2 * VT.getSizeInBits()) 6892 return SDValue(); 6893 6894 if (Src.MaxElt - Src.MinElt >= NumSrcElts) { 6895 // Span too large for a VEXT to cope 6896 return SDValue(); 6897 } 6898 6899 if (Src.MinElt >= NumSrcElts) { 6900 // The extraction can just take the second half 6901 Src.ShuffleVec = 6902 DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DestVT, Src.ShuffleVec, 6903 DAG.getConstant(NumSrcElts, dl, MVT::i32)); 6904 Src.WindowBase = -NumSrcElts; 6905 } else if (Src.MaxElt < NumSrcElts) { 6906 // The extraction can just take the first half 6907 Src.ShuffleVec = 6908 DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DestVT, Src.ShuffleVec, 6909 DAG.getConstant(0, dl, MVT::i32)); 6910 } else { 6911 // An actual VEXT is needed 6912 SDValue VEXTSrc1 = 6913 DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DestVT, Src.ShuffleVec, 6914 DAG.getConstant(0, dl, MVT::i32)); 6915 SDValue VEXTSrc2 = 6916 DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DestVT, Src.ShuffleVec, 6917 DAG.getConstant(NumSrcElts, dl, MVT::i32)); 6918 6919 Src.ShuffleVec = DAG.getNode(ARMISD::VEXT, dl, DestVT, VEXTSrc1, 6920 VEXTSrc2, 6921 DAG.getConstant(Src.MinElt, dl, MVT::i32)); 6922 Src.WindowBase = -Src.MinElt; 6923 } 6924 } 6925 6926 // Another possible incompatibility occurs from the vector element types. We 6927 // can fix this by bitcasting the source vectors to the same type we intend 6928 // for the shuffle. 6929 for (auto &Src : Sources) { 6930 EVT SrcEltTy = Src.ShuffleVec.getValueType().getVectorElementType(); 6931 if (SrcEltTy == SmallestEltTy) 6932 continue; 6933 assert(ShuffleVT.getVectorElementType() == SmallestEltTy); 6934 Src.ShuffleVec = DAG.getNode(ISD::BITCAST, dl, ShuffleVT, Src.ShuffleVec); 6935 Src.WindowScale = SrcEltTy.getSizeInBits() / SmallestEltTy.getSizeInBits(); 6936 Src.WindowBase *= Src.WindowScale; 6937 } 6938 6939 // Final sanity check before we try to actually produce a shuffle. 6940 LLVM_DEBUG(for (auto Src 6941 : Sources) 6942 assert(Src.ShuffleVec.getValueType() == ShuffleVT);); 6943 6944 // The stars all align, our next step is to produce the mask for the shuffle. 6945 SmallVector<int, 8> Mask(ShuffleVT.getVectorNumElements(), -1); 6946 int BitsPerShuffleLane = ShuffleVT.getScalarSizeInBits(); 6947 for (unsigned i = 0; i < VT.getVectorNumElements(); ++i) { 6948 SDValue Entry = Op.getOperand(i); 6949 if (Entry.isUndef()) 6950 continue; 6951 6952 auto Src = llvm::find(Sources, Entry.getOperand(0)); 6953 int EltNo = cast<ConstantSDNode>(Entry.getOperand(1))->getSExtValue(); 6954 6955 // EXTRACT_VECTOR_ELT performs an implicit any_ext; BUILD_VECTOR an implicit 6956 // trunc. So only std::min(SrcBits, DestBits) actually get defined in this 6957 // segment. 6958 EVT OrigEltTy = Entry.getOperand(0).getValueType().getVectorElementType(); 6959 int BitsDefined = std::min(OrigEltTy.getSizeInBits(), 6960 VT.getScalarSizeInBits()); 6961 int LanesDefined = BitsDefined / BitsPerShuffleLane; 6962 6963 // This source is expected to fill ResMultiplier lanes of the final shuffle, 6964 // starting at the appropriate offset. 6965 int *LaneMask = &Mask[i * ResMultiplier]; 6966 6967 int ExtractBase = EltNo * Src->WindowScale + Src->WindowBase; 6968 ExtractBase += NumElts * (Src - Sources.begin()); 6969 for (int j = 0; j < LanesDefined; ++j) 6970 LaneMask[j] = ExtractBase + j; 6971 } 6972 6973 // Final check before we try to produce nonsense... 6974 if (!isShuffleMaskLegal(Mask, ShuffleVT)) 6975 return SDValue(); 6976 6977 // We can't handle more than two sources. This should have already 6978 // been checked before this point. 6979 assert(Sources.size() <= 2 && "Too many sources!"); 6980 6981 SDValue ShuffleOps[] = { DAG.getUNDEF(ShuffleVT), DAG.getUNDEF(ShuffleVT) }; 6982 for (unsigned i = 0; i < Sources.size(); ++i) 6983 ShuffleOps[i] = Sources[i].ShuffleVec; 6984 6985 SDValue Shuffle = DAG.getVectorShuffle(ShuffleVT, dl, ShuffleOps[0], 6986 ShuffleOps[1], Mask); 6987 return DAG.getNode(ISD::BITCAST, dl, VT, Shuffle); 6988 } 6989 6990 enum ShuffleOpCodes { 6991 OP_COPY = 0, // Copy, used for things like <u,u,u,3> to say it is <0,1,2,3> 6992 OP_VREV, 6993 OP_VDUP0, 6994 OP_VDUP1, 6995 OP_VDUP2, 6996 OP_VDUP3, 6997 OP_VEXT1, 6998 OP_VEXT2, 6999 OP_VEXT3, 7000 OP_VUZPL, // VUZP, left result 7001 OP_VUZPR, // VUZP, right result 7002 OP_VZIPL, // VZIP, left result 7003 OP_VZIPR, // VZIP, right result 7004 OP_VTRNL, // VTRN, left result 7005 OP_VTRNR // VTRN, right result 7006 }; 7007 7008 static bool isLegalMVEShuffleOp(unsigned PFEntry) { 7009 unsigned OpNum = (PFEntry >> 26) & 0x0F; 7010 switch (OpNum) { 7011 case OP_COPY: 7012 case OP_VREV: 7013 case OP_VDUP0: 7014 case OP_VDUP1: 7015 case OP_VDUP2: 7016 case OP_VDUP3: 7017 return true; 7018 } 7019 return false; 7020 } 7021 7022 /// isShuffleMaskLegal - Targets can use this to indicate that they only 7023 /// support *some* VECTOR_SHUFFLE operations, those with specific masks. 7024 /// By default, if a target supports the VECTOR_SHUFFLE node, all mask values 7025 /// are assumed to be legal. 7026 bool ARMTargetLowering::isShuffleMaskLegal(ArrayRef<int> M, EVT VT) const { 7027 if (VT.getVectorNumElements() == 4 && 7028 (VT.is128BitVector() || VT.is64BitVector())) { 7029 unsigned PFIndexes[4]; 7030 for (unsigned i = 0; i != 4; ++i) { 7031 if (M[i] < 0) 7032 PFIndexes[i] = 8; 7033 else 7034 PFIndexes[i] = M[i]; 7035 } 7036 7037 // Compute the index in the perfect shuffle table. 7038 unsigned PFTableIndex = 7039 PFIndexes[0]*9*9*9+PFIndexes[1]*9*9+PFIndexes[2]*9+PFIndexes[3]; 7040 unsigned PFEntry = PerfectShuffleTable[PFTableIndex]; 7041 unsigned Cost = (PFEntry >> 30); 7042 7043 if (Cost <= 4 && (Subtarget->hasNEON() || isLegalMVEShuffleOp(PFEntry))) 7044 return true; 7045 } 7046 7047 bool ReverseVEXT, isV_UNDEF; 7048 unsigned Imm, WhichResult; 7049 7050 unsigned EltSize = VT.getScalarSizeInBits(); 7051 if (EltSize >= 32 || 7052 ShuffleVectorSDNode::isSplatMask(&M[0], VT) || 7053 isVREVMask(M, VT, 64) || 7054 isVREVMask(M, VT, 32) || 7055 isVREVMask(M, VT, 16)) 7056 return true; 7057 else if (Subtarget->hasNEON() && 7058 (isVEXTMask(M, VT, ReverseVEXT, Imm) || 7059 isVTBLMask(M, VT) || 7060 isNEONTwoResultShuffleMask(M, VT, WhichResult, isV_UNDEF))) 7061 return true; 7062 else if (Subtarget->hasNEON() && (VT == MVT::v8i16 || VT == MVT::v16i8) && 7063 isReverseMask(M, VT)) 7064 return true; 7065 else 7066 return false; 7067 } 7068 7069 /// GeneratePerfectShuffle - Given an entry in the perfect-shuffle table, emit 7070 /// the specified operations to build the shuffle. 7071 static SDValue GeneratePerfectShuffle(unsigned PFEntry, SDValue LHS, 7072 SDValue RHS, SelectionDAG &DAG, 7073 const SDLoc &dl) { 7074 unsigned OpNum = (PFEntry >> 26) & 0x0F; 7075 unsigned LHSID = (PFEntry >> 13) & ((1 << 13)-1); 7076 unsigned RHSID = (PFEntry >> 0) & ((1 << 13)-1); 7077 7078 if (OpNum == OP_COPY) { 7079 if (LHSID == (1*9+2)*9+3) return LHS; 7080 assert(LHSID == ((4*9+5)*9+6)*9+7 && "Illegal OP_COPY!"); 7081 return RHS; 7082 } 7083 7084 SDValue OpLHS, OpRHS; 7085 OpLHS = GeneratePerfectShuffle(PerfectShuffleTable[LHSID], LHS, RHS, DAG, dl); 7086 OpRHS = GeneratePerfectShuffle(PerfectShuffleTable[RHSID], LHS, RHS, DAG, dl); 7087 EVT VT = OpLHS.getValueType(); 7088 7089 switch (OpNum) { 7090 default: llvm_unreachable("Unknown shuffle opcode!"); 7091 case OP_VREV: 7092 // VREV divides the vector in half and swaps within the half. 7093 if (VT.getVectorElementType() == MVT::i32 || 7094 VT.getVectorElementType() == MVT::f32) 7095 return DAG.getNode(ARMISD::VREV64, dl, VT, OpLHS); 7096 // vrev <4 x i16> -> VREV32 7097 if (VT.getVectorElementType() == MVT::i16) 7098 return DAG.getNode(ARMISD::VREV32, dl, VT, OpLHS); 7099 // vrev <4 x i8> -> VREV16 7100 assert(VT.getVectorElementType() == MVT::i8); 7101 return DAG.getNode(ARMISD::VREV16, dl, VT, OpLHS); 7102 case OP_VDUP0: 7103 case OP_VDUP1: 7104 case OP_VDUP2: 7105 case OP_VDUP3: 7106 return DAG.getNode(ARMISD::VDUPLANE, dl, VT, 7107 OpLHS, DAG.getConstant(OpNum-OP_VDUP0, dl, MVT::i32)); 7108 case OP_VEXT1: 7109 case OP_VEXT2: 7110 case OP_VEXT3: 7111 return DAG.getNode(ARMISD::VEXT, dl, VT, 7112 OpLHS, OpRHS, 7113 DAG.getConstant(OpNum - OP_VEXT1 + 1, dl, MVT::i32)); 7114 case OP_VUZPL: 7115 case OP_VUZPR: 7116 return DAG.getNode(ARMISD::VUZP, dl, DAG.getVTList(VT, VT), 7117 OpLHS, OpRHS).getValue(OpNum-OP_VUZPL); 7118 case OP_VZIPL: 7119 case OP_VZIPR: 7120 return DAG.getNode(ARMISD::VZIP, dl, DAG.getVTList(VT, VT), 7121 OpLHS, OpRHS).getValue(OpNum-OP_VZIPL); 7122 case OP_VTRNL: 7123 case OP_VTRNR: 7124 return DAG.getNode(ARMISD::VTRN, dl, DAG.getVTList(VT, VT), 7125 OpLHS, OpRHS).getValue(OpNum-OP_VTRNL); 7126 } 7127 } 7128 7129 static SDValue LowerVECTOR_SHUFFLEv8i8(SDValue Op, 7130 ArrayRef<int> ShuffleMask, 7131 SelectionDAG &DAG) { 7132 // Check to see if we can use the VTBL instruction. 7133 SDValue V1 = Op.getOperand(0); 7134 SDValue V2 = Op.getOperand(1); 7135 SDLoc DL(Op); 7136 7137 SmallVector<SDValue, 8> VTBLMask; 7138 for (ArrayRef<int>::iterator 7139 I = ShuffleMask.begin(), E = ShuffleMask.end(); I != E; ++I) 7140 VTBLMask.push_back(DAG.getConstant(*I, DL, MVT::i32)); 7141 7142 if (V2.getNode()->isUndef()) 7143 return DAG.getNode(ARMISD::VTBL1, DL, MVT::v8i8, V1, 7144 DAG.getBuildVector(MVT::v8i8, DL, VTBLMask)); 7145 7146 return DAG.getNode(ARMISD::VTBL2, DL, MVT::v8i8, V1, V2, 7147 DAG.getBuildVector(MVT::v8i8, DL, VTBLMask)); 7148 } 7149 7150 static SDValue LowerReverse_VECTOR_SHUFFLEv16i8_v8i16(SDValue Op, 7151 SelectionDAG &DAG) { 7152 SDLoc DL(Op); 7153 SDValue OpLHS = Op.getOperand(0); 7154 EVT VT = OpLHS.getValueType(); 7155 7156 assert((VT == MVT::v8i16 || VT == MVT::v16i8) && 7157 "Expect an v8i16/v16i8 type"); 7158 OpLHS = DAG.getNode(ARMISD::VREV64, DL, VT, OpLHS); 7159 // For a v16i8 type: After the VREV, we have got <8, ...15, 8, ..., 0>. Now, 7160 // extract the first 8 bytes into the top double word and the last 8 bytes 7161 // into the bottom double word. The v8i16 case is similar. 7162 unsigned ExtractNum = (VT == MVT::v16i8) ? 8 : 4; 7163 return DAG.getNode(ARMISD::VEXT, DL, VT, OpLHS, OpLHS, 7164 DAG.getConstant(ExtractNum, DL, MVT::i32)); 7165 } 7166 7167 static SDValue LowerVECTOR_SHUFFLE(SDValue Op, SelectionDAG &DAG, 7168 const ARMSubtarget *ST) { 7169 SDValue V1 = Op.getOperand(0); 7170 SDValue V2 = Op.getOperand(1); 7171 SDLoc dl(Op); 7172 EVT VT = Op.getValueType(); 7173 ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(Op.getNode()); 7174 7175 // Convert shuffles that are directly supported on NEON to target-specific 7176 // DAG nodes, instead of keeping them as shuffles and matching them again 7177 // during code selection. This is more efficient and avoids the possibility 7178 // of inconsistencies between legalization and selection. 7179 // FIXME: floating-point vectors should be canonicalized to integer vectors 7180 // of the same time so that they get CSEd properly. 7181 ArrayRef<int> ShuffleMask = SVN->getMask(); 7182 7183 unsigned EltSize = VT.getScalarSizeInBits(); 7184 if (EltSize <= 32) { 7185 if (SVN->isSplat()) { 7186 int Lane = SVN->getSplatIndex(); 7187 // If this is undef splat, generate it via "just" vdup, if possible. 7188 if (Lane == -1) Lane = 0; 7189 7190 // Test if V1 is a SCALAR_TO_VECTOR. 7191 if (Lane == 0 && V1.getOpcode() == ISD::SCALAR_TO_VECTOR) { 7192 return DAG.getNode(ARMISD::VDUP, dl, VT, V1.getOperand(0)); 7193 } 7194 // Test if V1 is a BUILD_VECTOR which is equivalent to a SCALAR_TO_VECTOR 7195 // (and probably will turn into a SCALAR_TO_VECTOR once legalization 7196 // reaches it). 7197 if (Lane == 0 && V1.getOpcode() == ISD::BUILD_VECTOR && 7198 !isa<ConstantSDNode>(V1.getOperand(0))) { 7199 bool IsScalarToVector = true; 7200 for (unsigned i = 1, e = V1.getNumOperands(); i != e; ++i) 7201 if (!V1.getOperand(i).isUndef()) { 7202 IsScalarToVector = false; 7203 break; 7204 } 7205 if (IsScalarToVector) 7206 return DAG.getNode(ARMISD::VDUP, dl, VT, V1.getOperand(0)); 7207 } 7208 return DAG.getNode(ARMISD::VDUPLANE, dl, VT, V1, 7209 DAG.getConstant(Lane, dl, MVT::i32)); 7210 } 7211 7212 bool ReverseVEXT = false; 7213 unsigned Imm = 0; 7214 if (ST->hasNEON() && isVEXTMask(ShuffleMask, VT, ReverseVEXT, Imm)) { 7215 if (ReverseVEXT) 7216 std::swap(V1, V2); 7217 return DAG.getNode(ARMISD::VEXT, dl, VT, V1, V2, 7218 DAG.getConstant(Imm, dl, MVT::i32)); 7219 } 7220 7221 if (isVREVMask(ShuffleMask, VT, 64)) 7222 return DAG.getNode(ARMISD::VREV64, dl, VT, V1); 7223 if (isVREVMask(ShuffleMask, VT, 32)) 7224 return DAG.getNode(ARMISD::VREV32, dl, VT, V1); 7225 if (isVREVMask(ShuffleMask, VT, 16)) 7226 return DAG.getNode(ARMISD::VREV16, dl, VT, V1); 7227 7228 if (ST->hasNEON() && V2->isUndef() && isSingletonVEXTMask(ShuffleMask, VT, Imm)) { 7229 return DAG.getNode(ARMISD::VEXT, dl, VT, V1, V1, 7230 DAG.getConstant(Imm, dl, MVT::i32)); 7231 } 7232 7233 // Check for Neon shuffles that modify both input vectors in place. 7234 // If both results are used, i.e., if there are two shuffles with the same 7235 // source operands and with masks corresponding to both results of one of 7236 // these operations, DAG memoization will ensure that a single node is 7237 // used for both shuffles. 7238 unsigned WhichResult = 0; 7239 bool isV_UNDEF = false; 7240 if (ST->hasNEON()) { 7241 if (unsigned ShuffleOpc = isNEONTwoResultShuffleMask( 7242 ShuffleMask, VT, WhichResult, isV_UNDEF)) { 7243 if (isV_UNDEF) 7244 V2 = V1; 7245 return DAG.getNode(ShuffleOpc, dl, DAG.getVTList(VT, VT), V1, V2) 7246 .getValue(WhichResult); 7247 } 7248 } 7249 7250 // Also check for these shuffles through CONCAT_VECTORS: we canonicalize 7251 // shuffles that produce a result larger than their operands with: 7252 // shuffle(concat(v1, undef), concat(v2, undef)) 7253 // -> 7254 // shuffle(concat(v1, v2), undef) 7255 // because we can access quad vectors (see PerformVECTOR_SHUFFLECombine). 7256 // 7257 // This is useful in the general case, but there are special cases where 7258 // native shuffles produce larger results: the two-result ops. 7259 // 7260 // Look through the concat when lowering them: 7261 // shuffle(concat(v1, v2), undef) 7262 // -> 7263 // concat(VZIP(v1, v2):0, :1) 7264 // 7265 if (ST->hasNEON() && V1->getOpcode() == ISD::CONCAT_VECTORS && V2->isUndef()) { 7266 SDValue SubV1 = V1->getOperand(0); 7267 SDValue SubV2 = V1->getOperand(1); 7268 EVT SubVT = SubV1.getValueType(); 7269 7270 // We expect these to have been canonicalized to -1. 7271 assert(llvm::all_of(ShuffleMask, [&](int i) { 7272 return i < (int)VT.getVectorNumElements(); 7273 }) && "Unexpected shuffle index into UNDEF operand!"); 7274 7275 if (unsigned ShuffleOpc = isNEONTwoResultShuffleMask( 7276 ShuffleMask, SubVT, WhichResult, isV_UNDEF)) { 7277 if (isV_UNDEF) 7278 SubV2 = SubV1; 7279 assert((WhichResult == 0) && 7280 "In-place shuffle of concat can only have one result!"); 7281 SDValue Res = DAG.getNode(ShuffleOpc, dl, DAG.getVTList(SubVT, SubVT), 7282 SubV1, SubV2); 7283 return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, Res.getValue(0), 7284 Res.getValue(1)); 7285 } 7286 } 7287 } 7288 7289 // If the shuffle is not directly supported and it has 4 elements, use 7290 // the PerfectShuffle-generated table to synthesize it from other shuffles. 7291 unsigned NumElts = VT.getVectorNumElements(); 7292 if (NumElts == 4) { 7293 unsigned PFIndexes[4]; 7294 for (unsigned i = 0; i != 4; ++i) { 7295 if (ShuffleMask[i] < 0) 7296 PFIndexes[i] = 8; 7297 else 7298 PFIndexes[i] = ShuffleMask[i]; 7299 } 7300 7301 // Compute the index in the perfect shuffle table. 7302 unsigned PFTableIndex = 7303 PFIndexes[0]*9*9*9+PFIndexes[1]*9*9+PFIndexes[2]*9+PFIndexes[3]; 7304 unsigned PFEntry = PerfectShuffleTable[PFTableIndex]; 7305 unsigned Cost = (PFEntry >> 30); 7306 7307 if (Cost <= 4) { 7308 if (ST->hasNEON()) 7309 return GeneratePerfectShuffle(PFEntry, V1, V2, DAG, dl); 7310 else if (isLegalMVEShuffleOp(PFEntry)) { 7311 unsigned LHSID = (PFEntry >> 13) & ((1 << 13)-1); 7312 unsigned RHSID = (PFEntry >> 0) & ((1 << 13)-1); 7313 unsigned PFEntryLHS = PerfectShuffleTable[LHSID]; 7314 unsigned PFEntryRHS = PerfectShuffleTable[RHSID]; 7315 if (isLegalMVEShuffleOp(PFEntryLHS) && isLegalMVEShuffleOp(PFEntryRHS)) 7316 return GeneratePerfectShuffle(PFEntry, V1, V2, DAG, dl); 7317 } 7318 } 7319 } 7320 7321 // Implement shuffles with 32- or 64-bit elements as ARMISD::BUILD_VECTORs. 7322 if (EltSize >= 32) { 7323 // Do the expansion with floating-point types, since that is what the VFP 7324 // registers are defined to use, and since i64 is not legal. 7325 EVT EltVT = EVT::getFloatingPointVT(EltSize); 7326 EVT VecVT = EVT::getVectorVT(*DAG.getContext(), EltVT, NumElts); 7327 V1 = DAG.getNode(ISD::BITCAST, dl, VecVT, V1); 7328 V2 = DAG.getNode(ISD::BITCAST, dl, VecVT, V2); 7329 SmallVector<SDValue, 8> Ops; 7330 for (unsigned i = 0; i < NumElts; ++i) { 7331 if (ShuffleMask[i] < 0) 7332 Ops.push_back(DAG.getUNDEF(EltVT)); 7333 else 7334 Ops.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, EltVT, 7335 ShuffleMask[i] < (int)NumElts ? V1 : V2, 7336 DAG.getConstant(ShuffleMask[i] & (NumElts-1), 7337 dl, MVT::i32))); 7338 } 7339 SDValue Val = DAG.getNode(ARMISD::BUILD_VECTOR, dl, VecVT, Ops); 7340 return DAG.getNode(ISD::BITCAST, dl, VT, Val); 7341 } 7342 7343 if (ST->hasNEON() && (VT == MVT::v8i16 || VT == MVT::v16i8) && isReverseMask(ShuffleMask, VT)) 7344 return LowerReverse_VECTOR_SHUFFLEv16i8_v8i16(Op, DAG); 7345 7346 if (ST->hasNEON() && VT == MVT::v8i8) 7347 if (SDValue NewOp = LowerVECTOR_SHUFFLEv8i8(Op, ShuffleMask, DAG)) 7348 return NewOp; 7349 7350 return SDValue(); 7351 } 7352 7353 SDValue ARMTargetLowering:: 7354 LowerINSERT_VECTOR_ELT(SDValue Op, SelectionDAG &DAG) const { 7355 // INSERT_VECTOR_ELT is legal only for immediate indexes. 7356 SDValue Lane = Op.getOperand(2); 7357 if (!isa<ConstantSDNode>(Lane)) 7358 return SDValue(); 7359 7360 SDValue Elt = Op.getOperand(1); 7361 EVT EltVT = Elt.getValueType(); 7362 if (getTypeAction(*DAG.getContext(), EltVT) == 7363 TargetLowering::TypePromoteFloat) { 7364 // INSERT_VECTOR_ELT doesn't want f16 operands promoting to f32, 7365 // but the type system will try to do that if we don't intervene. 7366 // Reinterpret any such vector-element insertion as one with the 7367 // corresponding integer types. 7368 7369 SDLoc dl(Op); 7370 7371 EVT IEltVT = MVT::getIntegerVT(EltVT.getScalarSizeInBits()); 7372 assert(getTypeAction(*DAG.getContext(), IEltVT) != 7373 TargetLowering::TypePromoteFloat); 7374 7375 SDValue VecIn = Op.getOperand(0); 7376 EVT VecVT = VecIn.getValueType(); 7377 EVT IVecVT = EVT::getVectorVT(*DAG.getContext(), IEltVT, 7378 VecVT.getVectorNumElements()); 7379 7380 SDValue IElt = DAG.getNode(ISD::BITCAST, dl, IEltVT, Elt); 7381 SDValue IVecIn = DAG.getNode(ISD::BITCAST, dl, IVecVT, VecIn); 7382 SDValue IVecOut = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, IVecVT, 7383 IVecIn, IElt, Lane); 7384 return DAG.getNode(ISD::BITCAST, dl, VecVT, IVecOut); 7385 } 7386 7387 return Op; 7388 } 7389 7390 static SDValue LowerEXTRACT_VECTOR_ELT(SDValue Op, SelectionDAG &DAG) { 7391 // EXTRACT_VECTOR_ELT is legal only for immediate indexes. 7392 SDValue Lane = Op.getOperand(1); 7393 if (!isa<ConstantSDNode>(Lane)) 7394 return SDValue(); 7395 7396 SDValue Vec = Op.getOperand(0); 7397 if (Op.getValueType() == MVT::i32 && Vec.getScalarValueSizeInBits() < 32) { 7398 SDLoc dl(Op); 7399 return DAG.getNode(ARMISD::VGETLANEu, dl, MVT::i32, Vec, Lane); 7400 } 7401 7402 return Op; 7403 } 7404 7405 static SDValue LowerCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG) { 7406 // The only time a CONCAT_VECTORS operation can have legal types is when 7407 // two 64-bit vectors are concatenated to a 128-bit vector. 7408 assert(Op.getValueType().is128BitVector() && Op.getNumOperands() == 2 && 7409 "unexpected CONCAT_VECTORS"); 7410 SDLoc dl(Op); 7411 SDValue Val = DAG.getUNDEF(MVT::v2f64); 7412 SDValue Op0 = Op.getOperand(0); 7413 SDValue Op1 = Op.getOperand(1); 7414 if (!Op0.isUndef()) 7415 Val = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Val, 7416 DAG.getNode(ISD::BITCAST, dl, MVT::f64, Op0), 7417 DAG.getIntPtrConstant(0, dl)); 7418 if (!Op1.isUndef()) 7419 Val = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Val, 7420 DAG.getNode(ISD::BITCAST, dl, MVT::f64, Op1), 7421 DAG.getIntPtrConstant(1, dl)); 7422 return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Val); 7423 } 7424 7425 /// isExtendedBUILD_VECTOR - Check if N is a constant BUILD_VECTOR where each 7426 /// element has been zero/sign-extended, depending on the isSigned parameter, 7427 /// from an integer type half its size. 7428 static bool isExtendedBUILD_VECTOR(SDNode *N, SelectionDAG &DAG, 7429 bool isSigned) { 7430 // A v2i64 BUILD_VECTOR will have been legalized to a BITCAST from v4i32. 7431 EVT VT = N->getValueType(0); 7432 if (VT == MVT::v2i64 && N->getOpcode() == ISD::BITCAST) { 7433 SDNode *BVN = N->getOperand(0).getNode(); 7434 if (BVN->getValueType(0) != MVT::v4i32 || 7435 BVN->getOpcode() != ISD::BUILD_VECTOR) 7436 return false; 7437 unsigned LoElt = DAG.getDataLayout().isBigEndian() ? 1 : 0; 7438 unsigned HiElt = 1 - LoElt; 7439 ConstantSDNode *Lo0 = dyn_cast<ConstantSDNode>(BVN->getOperand(LoElt)); 7440 ConstantSDNode *Hi0 = dyn_cast<ConstantSDNode>(BVN->getOperand(HiElt)); 7441 ConstantSDNode *Lo1 = dyn_cast<ConstantSDNode>(BVN->getOperand(LoElt+2)); 7442 ConstantSDNode *Hi1 = dyn_cast<ConstantSDNode>(BVN->getOperand(HiElt+2)); 7443 if (!Lo0 || !Hi0 || !Lo1 || !Hi1) 7444 return false; 7445 if (isSigned) { 7446 if (Hi0->getSExtValue() == Lo0->getSExtValue() >> 32 && 7447 Hi1->getSExtValue() == Lo1->getSExtValue() >> 32) 7448 return true; 7449 } else { 7450 if (Hi0->isNullValue() && Hi1->isNullValue()) 7451 return true; 7452 } 7453 return false; 7454 } 7455 7456 if (N->getOpcode() != ISD::BUILD_VECTOR) 7457 return false; 7458 7459 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) { 7460 SDNode *Elt = N->getOperand(i).getNode(); 7461 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Elt)) { 7462 unsigned EltSize = VT.getScalarSizeInBits(); 7463 unsigned HalfSize = EltSize / 2; 7464 if (isSigned) { 7465 if (!isIntN(HalfSize, C->getSExtValue())) 7466 return false; 7467 } else { 7468 if (!isUIntN(HalfSize, C->getZExtValue())) 7469 return false; 7470 } 7471 continue; 7472 } 7473 return false; 7474 } 7475 7476 return true; 7477 } 7478 7479 /// isSignExtended - Check if a node is a vector value that is sign-extended 7480 /// or a constant BUILD_VECTOR with sign-extended elements. 7481 static bool isSignExtended(SDNode *N, SelectionDAG &DAG) { 7482 if (N->getOpcode() == ISD::SIGN_EXTEND || ISD::isSEXTLoad(N)) 7483 return true; 7484 if (isExtendedBUILD_VECTOR(N, DAG, true)) 7485 return true; 7486 return false; 7487 } 7488 7489 /// isZeroExtended - Check if a node is a vector value that is zero-extended 7490 /// or a constant BUILD_VECTOR with zero-extended elements. 7491 static bool isZeroExtended(SDNode *N, SelectionDAG &DAG) { 7492 if (N->getOpcode() == ISD::ZERO_EXTEND || ISD::isZEXTLoad(N)) 7493 return true; 7494 if (isExtendedBUILD_VECTOR(N, DAG, false)) 7495 return true; 7496 return false; 7497 } 7498 7499 static EVT getExtensionTo64Bits(const EVT &OrigVT) { 7500 if (OrigVT.getSizeInBits() >= 64) 7501 return OrigVT; 7502 7503 assert(OrigVT.isSimple() && "Expecting a simple value type"); 7504 7505 MVT::SimpleValueType OrigSimpleTy = OrigVT.getSimpleVT().SimpleTy; 7506 switch (OrigSimpleTy) { 7507 default: llvm_unreachable("Unexpected Vector Type"); 7508 case MVT::v2i8: 7509 case MVT::v2i16: 7510 return MVT::v2i32; 7511 case MVT::v4i8: 7512 return MVT::v4i16; 7513 } 7514 } 7515 7516 /// AddRequiredExtensionForVMULL - Add a sign/zero extension to extend the total 7517 /// value size to 64 bits. We need a 64-bit D register as an operand to VMULL. 7518 /// We insert the required extension here to get the vector to fill a D register. 7519 static SDValue AddRequiredExtensionForVMULL(SDValue N, SelectionDAG &DAG, 7520 const EVT &OrigTy, 7521 const EVT &ExtTy, 7522 unsigned ExtOpcode) { 7523 // The vector originally had a size of OrigTy. It was then extended to ExtTy. 7524 // We expect the ExtTy to be 128-bits total. If the OrigTy is less than 7525 // 64-bits we need to insert a new extension so that it will be 64-bits. 7526 assert(ExtTy.is128BitVector() && "Unexpected extension size"); 7527 if (OrigTy.getSizeInBits() >= 64) 7528 return N; 7529 7530 // Must extend size to at least 64 bits to be used as an operand for VMULL. 7531 EVT NewVT = getExtensionTo64Bits(OrigTy); 7532 7533 return DAG.getNode(ExtOpcode, SDLoc(N), NewVT, N); 7534 } 7535 7536 /// SkipLoadExtensionForVMULL - return a load of the original vector size that 7537 /// does not do any sign/zero extension. If the original vector is less 7538 /// than 64 bits, an appropriate extension will be added after the load to 7539 /// reach a total size of 64 bits. We have to add the extension separately 7540 /// because ARM does not have a sign/zero extending load for vectors. 7541 static SDValue SkipLoadExtensionForVMULL(LoadSDNode *LD, SelectionDAG& DAG) { 7542 EVT ExtendedTy = getExtensionTo64Bits(LD->getMemoryVT()); 7543 7544 // The load already has the right type. 7545 if (ExtendedTy == LD->getMemoryVT()) 7546 return DAG.getLoad(LD->getMemoryVT(), SDLoc(LD), LD->getChain(), 7547 LD->getBasePtr(), LD->getPointerInfo(), 7548 LD->getAlignment(), LD->getMemOperand()->getFlags()); 7549 7550 // We need to create a zextload/sextload. We cannot just create a load 7551 // followed by a zext/zext node because LowerMUL is also run during normal 7552 // operation legalization where we can't create illegal types. 7553 return DAG.getExtLoad(LD->getExtensionType(), SDLoc(LD), ExtendedTy, 7554 LD->getChain(), LD->getBasePtr(), LD->getPointerInfo(), 7555 LD->getMemoryVT(), LD->getAlignment(), 7556 LD->getMemOperand()->getFlags()); 7557 } 7558 7559 /// SkipExtensionForVMULL - For a node that is a SIGN_EXTEND, ZERO_EXTEND, 7560 /// extending load, or BUILD_VECTOR with extended elements, return the 7561 /// unextended value. The unextended vector should be 64 bits so that it can 7562 /// be used as an operand to a VMULL instruction. If the original vector size 7563 /// before extension is less than 64 bits we add a an extension to resize 7564 /// the vector to 64 bits. 7565 static SDValue SkipExtensionForVMULL(SDNode *N, SelectionDAG &DAG) { 7566 if (N->getOpcode() == ISD::SIGN_EXTEND || N->getOpcode() == ISD::ZERO_EXTEND) 7567 return AddRequiredExtensionForVMULL(N->getOperand(0), DAG, 7568 N->getOperand(0)->getValueType(0), 7569 N->getValueType(0), 7570 N->getOpcode()); 7571 7572 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) { 7573 assert((ISD::isSEXTLoad(LD) || ISD::isZEXTLoad(LD)) && 7574 "Expected extending load"); 7575 7576 SDValue newLoad = SkipLoadExtensionForVMULL(LD, DAG); 7577 DAG.ReplaceAllUsesOfValueWith(SDValue(LD, 1), newLoad.getValue(1)); 7578 unsigned Opcode = ISD::isSEXTLoad(LD) ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND; 7579 SDValue extLoad = 7580 DAG.getNode(Opcode, SDLoc(newLoad), LD->getValueType(0), newLoad); 7581 DAG.ReplaceAllUsesOfValueWith(SDValue(LD, 0), extLoad); 7582 7583 return newLoad; 7584 } 7585 7586 // Otherwise, the value must be a BUILD_VECTOR. For v2i64, it will 7587 // have been legalized as a BITCAST from v4i32. 7588 if (N->getOpcode() == ISD::BITCAST) { 7589 SDNode *BVN = N->getOperand(0).getNode(); 7590 assert(BVN->getOpcode() == ISD::BUILD_VECTOR && 7591 BVN->getValueType(0) == MVT::v4i32 && "expected v4i32 BUILD_VECTOR"); 7592 unsigned LowElt = DAG.getDataLayout().isBigEndian() ? 1 : 0; 7593 return DAG.getBuildVector( 7594 MVT::v2i32, SDLoc(N), 7595 {BVN->getOperand(LowElt), BVN->getOperand(LowElt + 2)}); 7596 } 7597 // Construct a new BUILD_VECTOR with elements truncated to half the size. 7598 assert(N->getOpcode() == ISD::BUILD_VECTOR && "expected BUILD_VECTOR"); 7599 EVT VT = N->getValueType(0); 7600 unsigned EltSize = VT.getScalarSizeInBits() / 2; 7601 unsigned NumElts = VT.getVectorNumElements(); 7602 MVT TruncVT = MVT::getIntegerVT(EltSize); 7603 SmallVector<SDValue, 8> Ops; 7604 SDLoc dl(N); 7605 for (unsigned i = 0; i != NumElts; ++i) { 7606 ConstantSDNode *C = cast<ConstantSDNode>(N->getOperand(i)); 7607 const APInt &CInt = C->getAPIntValue(); 7608 // Element types smaller than 32 bits are not legal, so use i32 elements. 7609 // The values are implicitly truncated so sext vs. zext doesn't matter. 7610 Ops.push_back(DAG.getConstant(CInt.zextOrTrunc(32), dl, MVT::i32)); 7611 } 7612 return DAG.getBuildVector(MVT::getVectorVT(TruncVT, NumElts), dl, Ops); 7613 } 7614 7615 static bool isAddSubSExt(SDNode *N, SelectionDAG &DAG) { 7616 unsigned Opcode = N->getOpcode(); 7617 if (Opcode == ISD::ADD || Opcode == ISD::SUB) { 7618 SDNode *N0 = N->getOperand(0).getNode(); 7619 SDNode *N1 = N->getOperand(1).getNode(); 7620 return N0->hasOneUse() && N1->hasOneUse() && 7621 isSignExtended(N0, DAG) && isSignExtended(N1, DAG); 7622 } 7623 return false; 7624 } 7625 7626 static bool isAddSubZExt(SDNode *N, SelectionDAG &DAG) { 7627 unsigned Opcode = N->getOpcode(); 7628 if (Opcode == ISD::ADD || Opcode == ISD::SUB) { 7629 SDNode *N0 = N->getOperand(0).getNode(); 7630 SDNode *N1 = N->getOperand(1).getNode(); 7631 return N0->hasOneUse() && N1->hasOneUse() && 7632 isZeroExtended(N0, DAG) && isZeroExtended(N1, DAG); 7633 } 7634 return false; 7635 } 7636 7637 static SDValue LowerMUL(SDValue Op, SelectionDAG &DAG) { 7638 // Multiplications are only custom-lowered for 128-bit vectors so that 7639 // VMULL can be detected. Otherwise v2i64 multiplications are not legal. 7640 EVT VT = Op.getValueType(); 7641 assert(VT.is128BitVector() && VT.isInteger() && 7642 "unexpected type for custom-lowering ISD::MUL"); 7643 SDNode *N0 = Op.getOperand(0).getNode(); 7644 SDNode *N1 = Op.getOperand(1).getNode(); 7645 unsigned NewOpc = 0; 7646 bool isMLA = false; 7647 bool isN0SExt = isSignExtended(N0, DAG); 7648 bool isN1SExt = isSignExtended(N1, DAG); 7649 if (isN0SExt && isN1SExt) 7650 NewOpc = ARMISD::VMULLs; 7651 else { 7652 bool isN0ZExt = isZeroExtended(N0, DAG); 7653 bool isN1ZExt = isZeroExtended(N1, DAG); 7654 if (isN0ZExt && isN1ZExt) 7655 NewOpc = ARMISD::VMULLu; 7656 else if (isN1SExt || isN1ZExt) { 7657 // Look for (s/zext A + s/zext B) * (s/zext C). We want to turn these 7658 // into (s/zext A * s/zext C) + (s/zext B * s/zext C) 7659 if (isN1SExt && isAddSubSExt(N0, DAG)) { 7660 NewOpc = ARMISD::VMULLs; 7661 isMLA = true; 7662 } else if (isN1ZExt && isAddSubZExt(N0, DAG)) { 7663 NewOpc = ARMISD::VMULLu; 7664 isMLA = true; 7665 } else if (isN0ZExt && isAddSubZExt(N1, DAG)) { 7666 std::swap(N0, N1); 7667 NewOpc = ARMISD::VMULLu; 7668 isMLA = true; 7669 } 7670 } 7671 7672 if (!NewOpc) { 7673 if (VT == MVT::v2i64) 7674 // Fall through to expand this. It is not legal. 7675 return SDValue(); 7676 else 7677 // Other vector multiplications are legal. 7678 return Op; 7679 } 7680 } 7681 7682 // Legalize to a VMULL instruction. 7683 SDLoc DL(Op); 7684 SDValue Op0; 7685 SDValue Op1 = SkipExtensionForVMULL(N1, DAG); 7686 if (!isMLA) { 7687 Op0 = SkipExtensionForVMULL(N0, DAG); 7688 assert(Op0.getValueType().is64BitVector() && 7689 Op1.getValueType().is64BitVector() && 7690 "unexpected types for extended operands to VMULL"); 7691 return DAG.getNode(NewOpc, DL, VT, Op0, Op1); 7692 } 7693 7694 // Optimizing (zext A + zext B) * C, to (VMULL A, C) + (VMULL B, C) during 7695 // isel lowering to take advantage of no-stall back to back vmul + vmla. 7696 // vmull q0, d4, d6 7697 // vmlal q0, d5, d6 7698 // is faster than 7699 // vaddl q0, d4, d5 7700 // vmovl q1, d6 7701 // vmul q0, q0, q1 7702 SDValue N00 = SkipExtensionForVMULL(N0->getOperand(0).getNode(), DAG); 7703 SDValue N01 = SkipExtensionForVMULL(N0->getOperand(1).getNode(), DAG); 7704 EVT Op1VT = Op1.getValueType(); 7705 return DAG.getNode(N0->getOpcode(), DL, VT, 7706 DAG.getNode(NewOpc, DL, VT, 7707 DAG.getNode(ISD::BITCAST, DL, Op1VT, N00), Op1), 7708 DAG.getNode(NewOpc, DL, VT, 7709 DAG.getNode(ISD::BITCAST, DL, Op1VT, N01), Op1)); 7710 } 7711 7712 static SDValue LowerSDIV_v4i8(SDValue X, SDValue Y, const SDLoc &dl, 7713 SelectionDAG &DAG) { 7714 // TODO: Should this propagate fast-math-flags? 7715 7716 // Convert to float 7717 // float4 xf = vcvt_f32_s32(vmovl_s16(a.lo)); 7718 // float4 yf = vcvt_f32_s32(vmovl_s16(b.lo)); 7719 X = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, X); 7720 Y = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, Y); 7721 X = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, X); 7722 Y = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, Y); 7723 // Get reciprocal estimate. 7724 // float4 recip = vrecpeq_f32(yf); 7725 Y = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32, 7726 DAG.getConstant(Intrinsic::arm_neon_vrecpe, dl, MVT::i32), 7727 Y); 7728 // Because char has a smaller range than uchar, we can actually get away 7729 // without any newton steps. This requires that we use a weird bias 7730 // of 0xb000, however (again, this has been exhaustively tested). 7731 // float4 result = as_float4(as_int4(xf*recip) + 0xb000); 7732 X = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, X, Y); 7733 X = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, X); 7734 Y = DAG.getConstant(0xb000, dl, MVT::v4i32); 7735 X = DAG.getNode(ISD::ADD, dl, MVT::v4i32, X, Y); 7736 X = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, X); 7737 // Convert back to short. 7738 X = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::v4i32, X); 7739 X = DAG.getNode(ISD::TRUNCATE, dl, MVT::v4i16, X); 7740 return X; 7741 } 7742 7743 static SDValue LowerSDIV_v4i16(SDValue N0, SDValue N1, const SDLoc &dl, 7744 SelectionDAG &DAG) { 7745 // TODO: Should this propagate fast-math-flags? 7746 7747 SDValue N2; 7748 // Convert to float. 7749 // float4 yf = vcvt_f32_s32(vmovl_s16(y)); 7750 // float4 xf = vcvt_f32_s32(vmovl_s16(x)); 7751 N0 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, N0); 7752 N1 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, N1); 7753 N0 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N0); 7754 N1 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N1); 7755 7756 // Use reciprocal estimate and one refinement step. 7757 // float4 recip = vrecpeq_f32(yf); 7758 // recip *= vrecpsq_f32(yf, recip); 7759 N2 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32, 7760 DAG.getConstant(Intrinsic::arm_neon_vrecpe, dl, MVT::i32), 7761 N1); 7762 N1 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32, 7763 DAG.getConstant(Intrinsic::arm_neon_vrecps, dl, MVT::i32), 7764 N1, N2); 7765 N2 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N1, N2); 7766 // Because short has a smaller range than ushort, we can actually get away 7767 // with only a single newton step. This requires that we use a weird bias 7768 // of 89, however (again, this has been exhaustively tested). 7769 // float4 result = as_float4(as_int4(xf*recip) + 0x89); 7770 N0 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N0, N2); 7771 N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, N0); 7772 N1 = DAG.getConstant(0x89, dl, MVT::v4i32); 7773 N0 = DAG.getNode(ISD::ADD, dl, MVT::v4i32, N0, N1); 7774 N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, N0); 7775 // Convert back to integer and return. 7776 // return vmovn_s32(vcvt_s32_f32(result)); 7777 N0 = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::v4i32, N0); 7778 N0 = DAG.getNode(ISD::TRUNCATE, dl, MVT::v4i16, N0); 7779 return N0; 7780 } 7781 7782 static SDValue LowerSDIV(SDValue Op, SelectionDAG &DAG) { 7783 EVT VT = Op.getValueType(); 7784 assert((VT == MVT::v4i16 || VT == MVT::v8i8) && 7785 "unexpected type for custom-lowering ISD::SDIV"); 7786 7787 SDLoc dl(Op); 7788 SDValue N0 = Op.getOperand(0); 7789 SDValue N1 = Op.getOperand(1); 7790 SDValue N2, N3; 7791 7792 if (VT == MVT::v8i8) { 7793 N0 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v8i16, N0); 7794 N1 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v8i16, N1); 7795 7796 N2 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0, 7797 DAG.getIntPtrConstant(4, dl)); 7798 N3 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1, 7799 DAG.getIntPtrConstant(4, dl)); 7800 N0 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0, 7801 DAG.getIntPtrConstant(0, dl)); 7802 N1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1, 7803 DAG.getIntPtrConstant(0, dl)); 7804 7805 N0 = LowerSDIV_v4i8(N0, N1, dl, DAG); // v4i16 7806 N2 = LowerSDIV_v4i8(N2, N3, dl, DAG); // v4i16 7807 7808 N0 = DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v8i16, N0, N2); 7809 N0 = LowerCONCAT_VECTORS(N0, DAG); 7810 7811 N0 = DAG.getNode(ISD::TRUNCATE, dl, MVT::v8i8, N0); 7812 return N0; 7813 } 7814 return LowerSDIV_v4i16(N0, N1, dl, DAG); 7815 } 7816 7817 static SDValue LowerUDIV(SDValue Op, SelectionDAG &DAG) { 7818 // TODO: Should this propagate fast-math-flags? 7819 EVT VT = Op.getValueType(); 7820 assert((VT == MVT::v4i16 || VT == MVT::v8i8) && 7821 "unexpected type for custom-lowering ISD::UDIV"); 7822 7823 SDLoc dl(Op); 7824 SDValue N0 = Op.getOperand(0); 7825 SDValue N1 = Op.getOperand(1); 7826 SDValue N2, N3; 7827 7828 if (VT == MVT::v8i8) { 7829 N0 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v8i16, N0); 7830 N1 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v8i16, N1); 7831 7832 N2 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0, 7833 DAG.getIntPtrConstant(4, dl)); 7834 N3 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1, 7835 DAG.getIntPtrConstant(4, dl)); 7836 N0 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0, 7837 DAG.getIntPtrConstant(0, dl)); 7838 N1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1, 7839 DAG.getIntPtrConstant(0, dl)); 7840 7841 N0 = LowerSDIV_v4i16(N0, N1, dl, DAG); // v4i16 7842 N2 = LowerSDIV_v4i16(N2, N3, dl, DAG); // v4i16 7843 7844 N0 = DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v8i16, N0, N2); 7845 N0 = LowerCONCAT_VECTORS(N0, DAG); 7846 7847 N0 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v8i8, 7848 DAG.getConstant(Intrinsic::arm_neon_vqmovnsu, dl, 7849 MVT::i32), 7850 N0); 7851 return N0; 7852 } 7853 7854 // v4i16 sdiv ... Convert to float. 7855 // float4 yf = vcvt_f32_s32(vmovl_u16(y)); 7856 // float4 xf = vcvt_f32_s32(vmovl_u16(x)); 7857 N0 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v4i32, N0); 7858 N1 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v4i32, N1); 7859 N0 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N0); 7860 SDValue BN1 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N1); 7861 7862 // Use reciprocal estimate and two refinement steps. 7863 // float4 recip = vrecpeq_f32(yf); 7864 // recip *= vrecpsq_f32(yf, recip); 7865 // recip *= vrecpsq_f32(yf, recip); 7866 N2 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32, 7867 DAG.getConstant(Intrinsic::arm_neon_vrecpe, dl, MVT::i32), 7868 BN1); 7869 N1 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32, 7870 DAG.getConstant(Intrinsic::arm_neon_vrecps, dl, MVT::i32), 7871 BN1, N2); 7872 N2 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N1, N2); 7873 N1 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32, 7874 DAG.getConstant(Intrinsic::arm_neon_vrecps, dl, MVT::i32), 7875 BN1, N2); 7876 N2 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N1, N2); 7877 // Simply multiplying by the reciprocal estimate can leave us a few ulps 7878 // too low, so we add 2 ulps (exhaustive testing shows that this is enough, 7879 // and that it will never cause us to return an answer too large). 7880 // float4 result = as_float4(as_int4(xf*recip) + 2); 7881 N0 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N0, N2); 7882 N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, N0); 7883 N1 = DAG.getConstant(2, dl, MVT::v4i32); 7884 N0 = DAG.getNode(ISD::ADD, dl, MVT::v4i32, N0, N1); 7885 N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, N0); 7886 // Convert back to integer and return. 7887 // return vmovn_u32(vcvt_s32_f32(result)); 7888 N0 = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::v4i32, N0); 7889 N0 = DAG.getNode(ISD::TRUNCATE, dl, MVT::v4i16, N0); 7890 return N0; 7891 } 7892 7893 static SDValue LowerADDSUBCARRY(SDValue Op, SelectionDAG &DAG) { 7894 SDNode *N = Op.getNode(); 7895 EVT VT = N->getValueType(0); 7896 SDVTList VTs = DAG.getVTList(VT, MVT::i32); 7897 7898 SDValue Carry = Op.getOperand(2); 7899 7900 SDLoc DL(Op); 7901 7902 SDValue Result; 7903 if (Op.getOpcode() == ISD::ADDCARRY) { 7904 // This converts the boolean value carry into the carry flag. 7905 Carry = ConvertBooleanCarryToCarryFlag(Carry, DAG); 7906 7907 // Do the addition proper using the carry flag we wanted. 7908 Result = DAG.getNode(ARMISD::ADDE, DL, VTs, Op.getOperand(0), 7909 Op.getOperand(1), Carry); 7910 7911 // Now convert the carry flag into a boolean value. 7912 Carry = ConvertCarryFlagToBooleanCarry(Result.getValue(1), VT, DAG); 7913 } else { 7914 // ARMISD::SUBE expects a carry not a borrow like ISD::SUBCARRY so we 7915 // have to invert the carry first. 7916 Carry = DAG.getNode(ISD::SUB, DL, MVT::i32, 7917 DAG.getConstant(1, DL, MVT::i32), Carry); 7918 // This converts the boolean value carry into the carry flag. 7919 Carry = ConvertBooleanCarryToCarryFlag(Carry, DAG); 7920 7921 // Do the subtraction proper using the carry flag we wanted. 7922 Result = DAG.getNode(ARMISD::SUBE, DL, VTs, Op.getOperand(0), 7923 Op.getOperand(1), Carry); 7924 7925 // Now convert the carry flag into a boolean value. 7926 Carry = ConvertCarryFlagToBooleanCarry(Result.getValue(1), VT, DAG); 7927 // But the carry returned by ARMISD::SUBE is not a borrow as expected 7928 // by ISD::SUBCARRY, so compute 1 - C. 7929 Carry = DAG.getNode(ISD::SUB, DL, MVT::i32, 7930 DAG.getConstant(1, DL, MVT::i32), Carry); 7931 } 7932 7933 // Return both values. 7934 return DAG.getNode(ISD::MERGE_VALUES, DL, N->getVTList(), Result, Carry); 7935 } 7936 7937 SDValue ARMTargetLowering::LowerFSINCOS(SDValue Op, SelectionDAG &DAG) const { 7938 assert(Subtarget->isTargetDarwin()); 7939 7940 // For iOS, we want to call an alternative entry point: __sincos_stret, 7941 // return values are passed via sret. 7942 SDLoc dl(Op); 7943 SDValue Arg = Op.getOperand(0); 7944 EVT ArgVT = Arg.getValueType(); 7945 Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext()); 7946 auto PtrVT = getPointerTy(DAG.getDataLayout()); 7947 7948 MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo(); 7949 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 7950 7951 // Pair of floats / doubles used to pass the result. 7952 Type *RetTy = StructType::get(ArgTy, ArgTy); 7953 auto &DL = DAG.getDataLayout(); 7954 7955 ArgListTy Args; 7956 bool ShouldUseSRet = Subtarget->isAPCS_ABI(); 7957 SDValue SRet; 7958 if (ShouldUseSRet) { 7959 // Create stack object for sret. 7960 const uint64_t ByteSize = DL.getTypeAllocSize(RetTy); 7961 const unsigned StackAlign = DL.getPrefTypeAlignment(RetTy); 7962 int FrameIdx = MFI.CreateStackObject(ByteSize, StackAlign, false); 7963 SRet = DAG.getFrameIndex(FrameIdx, TLI.getPointerTy(DL)); 7964 7965 ArgListEntry Entry; 7966 Entry.Node = SRet; 7967 Entry.Ty = RetTy->getPointerTo(); 7968 Entry.IsSExt = false; 7969 Entry.IsZExt = false; 7970 Entry.IsSRet = true; 7971 Args.push_back(Entry); 7972 RetTy = Type::getVoidTy(*DAG.getContext()); 7973 } 7974 7975 ArgListEntry Entry; 7976 Entry.Node = Arg; 7977 Entry.Ty = ArgTy; 7978 Entry.IsSExt = false; 7979 Entry.IsZExt = false; 7980 Args.push_back(Entry); 7981 7982 RTLIB::Libcall LC = 7983 (ArgVT == MVT::f64) ? RTLIB::SINCOS_STRET_F64 : RTLIB::SINCOS_STRET_F32; 7984 const char *LibcallName = getLibcallName(LC); 7985 CallingConv::ID CC = getLibcallCallingConv(LC); 7986 SDValue Callee = DAG.getExternalSymbol(LibcallName, getPointerTy(DL)); 7987 7988 TargetLowering::CallLoweringInfo CLI(DAG); 7989 CLI.setDebugLoc(dl) 7990 .setChain(DAG.getEntryNode()) 7991 .setCallee(CC, RetTy, Callee, std::move(Args)) 7992 .setDiscardResult(ShouldUseSRet); 7993 std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI); 7994 7995 if (!ShouldUseSRet) 7996 return CallResult.first; 7997 7998 SDValue LoadSin = 7999 DAG.getLoad(ArgVT, dl, CallResult.second, SRet, MachinePointerInfo()); 8000 8001 // Address of cos field. 8002 SDValue Add = DAG.getNode(ISD::ADD, dl, PtrVT, SRet, 8003 DAG.getIntPtrConstant(ArgVT.getStoreSize(), dl)); 8004 SDValue LoadCos = 8005 DAG.getLoad(ArgVT, dl, LoadSin.getValue(1), Add, MachinePointerInfo()); 8006 8007 SDVTList Tys = DAG.getVTList(ArgVT, ArgVT); 8008 return DAG.getNode(ISD::MERGE_VALUES, dl, Tys, 8009 LoadSin.getValue(0), LoadCos.getValue(0)); 8010 } 8011 8012 SDValue ARMTargetLowering::LowerWindowsDIVLibCall(SDValue Op, SelectionDAG &DAG, 8013 bool Signed, 8014 SDValue &Chain) const { 8015 EVT VT = Op.getValueType(); 8016 assert((VT == MVT::i32 || VT == MVT::i64) && 8017 "unexpected type for custom lowering DIV"); 8018 SDLoc dl(Op); 8019 8020 const auto &DL = DAG.getDataLayout(); 8021 const auto &TLI = DAG.getTargetLoweringInfo(); 8022 8023 const char *Name = nullptr; 8024 if (Signed) 8025 Name = (VT == MVT::i32) ? "__rt_sdiv" : "__rt_sdiv64"; 8026 else 8027 Name = (VT == MVT::i32) ? "__rt_udiv" : "__rt_udiv64"; 8028 8029 SDValue ES = DAG.getExternalSymbol(Name, TLI.getPointerTy(DL)); 8030 8031 ARMTargetLowering::ArgListTy Args; 8032 8033 for (auto AI : {1, 0}) { 8034 ArgListEntry Arg; 8035 Arg.Node = Op.getOperand(AI); 8036 Arg.Ty = Arg.Node.getValueType().getTypeForEVT(*DAG.getContext()); 8037 Args.push_back(Arg); 8038 } 8039 8040 CallLoweringInfo CLI(DAG); 8041 CLI.setDebugLoc(dl) 8042 .setChain(Chain) 8043 .setCallee(CallingConv::ARM_AAPCS_VFP, VT.getTypeForEVT(*DAG.getContext()), 8044 ES, std::move(Args)); 8045 8046 return LowerCallTo(CLI).first; 8047 } 8048 8049 // This is a code size optimisation: return the original SDIV node to 8050 // DAGCombiner when we don't want to expand SDIV into a sequence of 8051 // instructions, and an empty node otherwise which will cause the 8052 // SDIV to be expanded in DAGCombine. 8053 SDValue 8054 ARMTargetLowering::BuildSDIVPow2(SDNode *N, const APInt &Divisor, 8055 SelectionDAG &DAG, 8056 SmallVectorImpl<SDNode *> &Created) const { 8057 // TODO: Support SREM 8058 if (N->getOpcode() != ISD::SDIV) 8059 return SDValue(); 8060 8061 const auto &ST = static_cast<const ARMSubtarget&>(DAG.getSubtarget()); 8062 const bool MinSize = ST.hasMinSize(); 8063 const bool HasDivide = ST.isThumb() ? ST.hasDivideInThumbMode() 8064 : ST.hasDivideInARMMode(); 8065 8066 // Don't touch vector types; rewriting this may lead to scalarizing 8067 // the int divs. 8068 if (N->getOperand(0).getValueType().isVector()) 8069 return SDValue(); 8070 8071 // Bail if MinSize is not set, and also for both ARM and Thumb mode we need 8072 // hwdiv support for this to be really profitable. 8073 if (!(MinSize && HasDivide)) 8074 return SDValue(); 8075 8076 // ARM mode is a bit simpler than Thumb: we can handle large power 8077 // of 2 immediates with 1 mov instruction; no further checks required, 8078 // just return the sdiv node. 8079 if (!ST.isThumb()) 8080 return SDValue(N, 0); 8081 8082 // In Thumb mode, immediates larger than 128 need a wide 4-byte MOV, 8083 // and thus lose the code size benefits of a MOVS that requires only 2. 8084 // TargetTransformInfo and 'getIntImmCodeSizeCost' could be helpful here, 8085 // but as it's doing exactly this, it's not worth the trouble to get TTI. 8086 if (Divisor.sgt(128)) 8087 return SDValue(); 8088 8089 return SDValue(N, 0); 8090 } 8091 8092 SDValue ARMTargetLowering::LowerDIV_Windows(SDValue Op, SelectionDAG &DAG, 8093 bool Signed) const { 8094 assert(Op.getValueType() == MVT::i32 && 8095 "unexpected type for custom lowering DIV"); 8096 SDLoc dl(Op); 8097 8098 SDValue DBZCHK = DAG.getNode(ARMISD::WIN__DBZCHK, dl, MVT::Other, 8099 DAG.getEntryNode(), Op.getOperand(1)); 8100 8101 return LowerWindowsDIVLibCall(Op, DAG, Signed, DBZCHK); 8102 } 8103 8104 static SDValue WinDBZCheckDenominator(SelectionDAG &DAG, SDNode *N, SDValue InChain) { 8105 SDLoc DL(N); 8106 SDValue Op = N->getOperand(1); 8107 if (N->getValueType(0) == MVT::i32) 8108 return DAG.getNode(ARMISD::WIN__DBZCHK, DL, MVT::Other, InChain, Op); 8109 SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, Op, 8110 DAG.getConstant(0, DL, MVT::i32)); 8111 SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, Op, 8112 DAG.getConstant(1, DL, MVT::i32)); 8113 return DAG.getNode(ARMISD::WIN__DBZCHK, DL, MVT::Other, InChain, 8114 DAG.getNode(ISD::OR, DL, MVT::i32, Lo, Hi)); 8115 } 8116 8117 void ARMTargetLowering::ExpandDIV_Windows( 8118 SDValue Op, SelectionDAG &DAG, bool Signed, 8119 SmallVectorImpl<SDValue> &Results) const { 8120 const auto &DL = DAG.getDataLayout(); 8121 const auto &TLI = DAG.getTargetLoweringInfo(); 8122 8123 assert(Op.getValueType() == MVT::i64 && 8124 "unexpected type for custom lowering DIV"); 8125 SDLoc dl(Op); 8126 8127 SDValue DBZCHK = WinDBZCheckDenominator(DAG, Op.getNode(), DAG.getEntryNode()); 8128 8129 SDValue Result = LowerWindowsDIVLibCall(Op, DAG, Signed, DBZCHK); 8130 8131 SDValue Lower = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, Result); 8132 SDValue Upper = DAG.getNode(ISD::SRL, dl, MVT::i64, Result, 8133 DAG.getConstant(32, dl, TLI.getPointerTy(DL))); 8134 Upper = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, Upper); 8135 8136 Results.push_back(Lower); 8137 Results.push_back(Upper); 8138 } 8139 8140 static SDValue LowerAtomicLoadStore(SDValue Op, SelectionDAG &DAG) { 8141 if (isStrongerThanMonotonic(cast<AtomicSDNode>(Op)->getOrdering())) 8142 // Acquire/Release load/store is not legal for targets without a dmb or 8143 // equivalent available. 8144 return SDValue(); 8145 8146 // Monotonic load/store is legal for all targets. 8147 return Op; 8148 } 8149 8150 static void ReplaceREADCYCLECOUNTER(SDNode *N, 8151 SmallVectorImpl<SDValue> &Results, 8152 SelectionDAG &DAG, 8153 const ARMSubtarget *Subtarget) { 8154 SDLoc DL(N); 8155 // Under Power Management extensions, the cycle-count is: 8156 // mrc p15, #0, <Rt>, c9, c13, #0 8157 SDValue Ops[] = { N->getOperand(0), // Chain 8158 DAG.getConstant(Intrinsic::arm_mrc, DL, MVT::i32), 8159 DAG.getConstant(15, DL, MVT::i32), 8160 DAG.getConstant(0, DL, MVT::i32), 8161 DAG.getConstant(9, DL, MVT::i32), 8162 DAG.getConstant(13, DL, MVT::i32), 8163 DAG.getConstant(0, DL, MVT::i32) 8164 }; 8165 8166 SDValue Cycles32 = DAG.getNode(ISD::INTRINSIC_W_CHAIN, DL, 8167 DAG.getVTList(MVT::i32, MVT::Other), Ops); 8168 Results.push_back(DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, Cycles32, 8169 DAG.getConstant(0, DL, MVT::i32))); 8170 Results.push_back(Cycles32.getValue(1)); 8171 } 8172 8173 static SDValue createGPRPairNode(SelectionDAG &DAG, SDValue V) { 8174 SDLoc dl(V.getNode()); 8175 SDValue VLo = DAG.getAnyExtOrTrunc(V, dl, MVT::i32); 8176 SDValue VHi = DAG.getAnyExtOrTrunc( 8177 DAG.getNode(ISD::SRL, dl, MVT::i64, V, DAG.getConstant(32, dl, MVT::i32)), 8178 dl, MVT::i32); 8179 bool isBigEndian = DAG.getDataLayout().isBigEndian(); 8180 if (isBigEndian) 8181 std::swap (VLo, VHi); 8182 SDValue RegClass = 8183 DAG.getTargetConstant(ARM::GPRPairRegClassID, dl, MVT::i32); 8184 SDValue SubReg0 = DAG.getTargetConstant(ARM::gsub_0, dl, MVT::i32); 8185 SDValue SubReg1 = DAG.getTargetConstant(ARM::gsub_1, dl, MVT::i32); 8186 const SDValue Ops[] = { RegClass, VLo, SubReg0, VHi, SubReg1 }; 8187 return SDValue( 8188 DAG.getMachineNode(TargetOpcode::REG_SEQUENCE, dl, MVT::Untyped, Ops), 0); 8189 } 8190 8191 static void ReplaceCMP_SWAP_64Results(SDNode *N, 8192 SmallVectorImpl<SDValue> & Results, 8193 SelectionDAG &DAG) { 8194 assert(N->getValueType(0) == MVT::i64 && 8195 "AtomicCmpSwap on types less than 64 should be legal"); 8196 SDValue Ops[] = {N->getOperand(1), 8197 createGPRPairNode(DAG, N->getOperand(2)), 8198 createGPRPairNode(DAG, N->getOperand(3)), 8199 N->getOperand(0)}; 8200 SDNode *CmpSwap = DAG.getMachineNode( 8201 ARM::CMP_SWAP_64, SDLoc(N), 8202 DAG.getVTList(MVT::Untyped, MVT::i32, MVT::Other), Ops); 8203 8204 MachineMemOperand *MemOp = cast<MemSDNode>(N)->getMemOperand(); 8205 DAG.setNodeMemRefs(cast<MachineSDNode>(CmpSwap), {MemOp}); 8206 8207 bool isBigEndian = DAG.getDataLayout().isBigEndian(); 8208 8209 Results.push_back( 8210 DAG.getTargetExtractSubreg(isBigEndian ? ARM::gsub_1 : ARM::gsub_0, 8211 SDLoc(N), MVT::i32, SDValue(CmpSwap, 0))); 8212 Results.push_back( 8213 DAG.getTargetExtractSubreg(isBigEndian ? ARM::gsub_0 : ARM::gsub_1, 8214 SDLoc(N), MVT::i32, SDValue(CmpSwap, 0))); 8215 Results.push_back(SDValue(CmpSwap, 2)); 8216 } 8217 8218 static SDValue LowerFPOWI(SDValue Op, const ARMSubtarget &Subtarget, 8219 SelectionDAG &DAG) { 8220 const auto &TLI = DAG.getTargetLoweringInfo(); 8221 8222 assert(Subtarget.getTargetTriple().isOSMSVCRT() && 8223 "Custom lowering is MSVCRT specific!"); 8224 8225 SDLoc dl(Op); 8226 SDValue Val = Op.getOperand(0); 8227 MVT Ty = Val->getSimpleValueType(0); 8228 SDValue Exponent = DAG.getNode(ISD::SINT_TO_FP, dl, Ty, Op.getOperand(1)); 8229 SDValue Callee = DAG.getExternalSymbol(Ty == MVT::f32 ? "powf" : "pow", 8230 TLI.getPointerTy(DAG.getDataLayout())); 8231 8232 TargetLowering::ArgListTy Args; 8233 TargetLowering::ArgListEntry Entry; 8234 8235 Entry.Node = Val; 8236 Entry.Ty = Val.getValueType().getTypeForEVT(*DAG.getContext()); 8237 Entry.IsZExt = true; 8238 Args.push_back(Entry); 8239 8240 Entry.Node = Exponent; 8241 Entry.Ty = Exponent.getValueType().getTypeForEVT(*DAG.getContext()); 8242 Entry.IsZExt = true; 8243 Args.push_back(Entry); 8244 8245 Type *LCRTy = Val.getValueType().getTypeForEVT(*DAG.getContext()); 8246 8247 // In the in-chain to the call is the entry node If we are emitting a 8248 // tailcall, the chain will be mutated if the node has a non-entry input 8249 // chain. 8250 SDValue InChain = DAG.getEntryNode(); 8251 SDValue TCChain = InChain; 8252 8253 const Function &F = DAG.getMachineFunction().getFunction(); 8254 bool IsTC = TLI.isInTailCallPosition(DAG, Op.getNode(), TCChain) && 8255 F.getReturnType() == LCRTy; 8256 if (IsTC) 8257 InChain = TCChain; 8258 8259 TargetLowering::CallLoweringInfo CLI(DAG); 8260 CLI.setDebugLoc(dl) 8261 .setChain(InChain) 8262 .setCallee(CallingConv::ARM_AAPCS_VFP, LCRTy, Callee, std::move(Args)) 8263 .setTailCall(IsTC); 8264 std::pair<SDValue, SDValue> CI = TLI.LowerCallTo(CLI); 8265 8266 // Return the chain (the DAG root) if it is a tail call 8267 return !CI.second.getNode() ? DAG.getRoot() : CI.first; 8268 } 8269 8270 SDValue ARMTargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const { 8271 LLVM_DEBUG(dbgs() << "Lowering node: "; Op.dump()); 8272 switch (Op.getOpcode()) { 8273 default: llvm_unreachable("Don't know how to custom lower this!"); 8274 case ISD::WRITE_REGISTER: return LowerWRITE_REGISTER(Op, DAG); 8275 case ISD::ConstantPool: return LowerConstantPool(Op, DAG); 8276 case ISD::BlockAddress: return LowerBlockAddress(Op, DAG); 8277 case ISD::GlobalAddress: return LowerGlobalAddress(Op, DAG); 8278 case ISD::GlobalTLSAddress: return LowerGlobalTLSAddress(Op, DAG); 8279 case ISD::SELECT: return LowerSELECT(Op, DAG); 8280 case ISD::SELECT_CC: return LowerSELECT_CC(Op, DAG); 8281 case ISD::BRCOND: return LowerBRCOND(Op, DAG); 8282 case ISD::BR_CC: return LowerBR_CC(Op, DAG); 8283 case ISD::BR_JT: return LowerBR_JT(Op, DAG); 8284 case ISD::VASTART: return LowerVASTART(Op, DAG); 8285 case ISD::ATOMIC_FENCE: return LowerATOMIC_FENCE(Op, DAG, Subtarget); 8286 case ISD::PREFETCH: return LowerPREFETCH(Op, DAG, Subtarget); 8287 case ISD::SINT_TO_FP: 8288 case ISD::UINT_TO_FP: return LowerINT_TO_FP(Op, DAG); 8289 case ISD::FP_TO_SINT: 8290 case ISD::FP_TO_UINT: return LowerFP_TO_INT(Op, DAG); 8291 case ISD::FCOPYSIGN: return LowerFCOPYSIGN(Op, DAG); 8292 case ISD::RETURNADDR: return LowerRETURNADDR(Op, DAG); 8293 case ISD::FRAMEADDR: return LowerFRAMEADDR(Op, DAG); 8294 case ISD::EH_SJLJ_SETJMP: return LowerEH_SJLJ_SETJMP(Op, DAG); 8295 case ISD::EH_SJLJ_LONGJMP: return LowerEH_SJLJ_LONGJMP(Op, DAG); 8296 case ISD::EH_SJLJ_SETUP_DISPATCH: return LowerEH_SJLJ_SETUP_DISPATCH(Op, DAG); 8297 case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG, 8298 Subtarget); 8299 case ISD::BITCAST: return ExpandBITCAST(Op.getNode(), DAG, Subtarget); 8300 case ISD::SHL: 8301 case ISD::SRL: 8302 case ISD::SRA: return LowerShift(Op.getNode(), DAG, Subtarget); 8303 case ISD::SREM: return LowerREM(Op.getNode(), DAG); 8304 case ISD::UREM: return LowerREM(Op.getNode(), DAG); 8305 case ISD::SHL_PARTS: return LowerShiftLeftParts(Op, DAG); 8306 case ISD::SRL_PARTS: 8307 case ISD::SRA_PARTS: return LowerShiftRightParts(Op, DAG); 8308 case ISD::CTTZ: 8309 case ISD::CTTZ_ZERO_UNDEF: return LowerCTTZ(Op.getNode(), DAG, Subtarget); 8310 case ISD::CTPOP: return LowerCTPOP(Op.getNode(), DAG, Subtarget); 8311 case ISD::SETCC: return LowerVSETCC(Op, DAG); 8312 case ISD::SETCCCARRY: return LowerSETCCCARRY(Op, DAG); 8313 case ISD::ConstantFP: return LowerConstantFP(Op, DAG, Subtarget); 8314 case ISD::BUILD_VECTOR: return LowerBUILD_VECTOR(Op, DAG, Subtarget); 8315 case ISD::VECTOR_SHUFFLE: return LowerVECTOR_SHUFFLE(Op, DAG, Subtarget); 8316 case ISD::INSERT_VECTOR_ELT: return LowerINSERT_VECTOR_ELT(Op, DAG); 8317 case ISD::EXTRACT_VECTOR_ELT: return LowerEXTRACT_VECTOR_ELT(Op, DAG); 8318 case ISD::CONCAT_VECTORS: return LowerCONCAT_VECTORS(Op, DAG); 8319 case ISD::FLT_ROUNDS_: return LowerFLT_ROUNDS_(Op, DAG); 8320 case ISD::MUL: return LowerMUL(Op, DAG); 8321 case ISD::SDIV: 8322 if (Subtarget->isTargetWindows() && !Op.getValueType().isVector()) 8323 return LowerDIV_Windows(Op, DAG, /* Signed */ true); 8324 return LowerSDIV(Op, DAG); 8325 case ISD::UDIV: 8326 if (Subtarget->isTargetWindows() && !Op.getValueType().isVector()) 8327 return LowerDIV_Windows(Op, DAG, /* Signed */ false); 8328 return LowerUDIV(Op, DAG); 8329 case ISD::ADDCARRY: 8330 case ISD::SUBCARRY: return LowerADDSUBCARRY(Op, DAG); 8331 case ISD::SADDO: 8332 case ISD::SSUBO: 8333 return LowerSignedALUO(Op, DAG); 8334 case ISD::UADDO: 8335 case ISD::USUBO: 8336 return LowerUnsignedALUO(Op, DAG); 8337 case ISD::ATOMIC_LOAD: 8338 case ISD::ATOMIC_STORE: return LowerAtomicLoadStore(Op, DAG); 8339 case ISD::FSINCOS: return LowerFSINCOS(Op, DAG); 8340 case ISD::SDIVREM: 8341 case ISD::UDIVREM: return LowerDivRem(Op, DAG); 8342 case ISD::DYNAMIC_STACKALLOC: 8343 if (Subtarget->isTargetWindows()) 8344 return LowerDYNAMIC_STACKALLOC(Op, DAG); 8345 llvm_unreachable("Don't know how to custom lower this!"); 8346 case ISD::FP_ROUND: return LowerFP_ROUND(Op, DAG); 8347 case ISD::FP_EXTEND: return LowerFP_EXTEND(Op, DAG); 8348 case ISD::FPOWI: return LowerFPOWI(Op, *Subtarget, DAG); 8349 case ARMISD::WIN__DBZCHK: return SDValue(); 8350 } 8351 } 8352 8353 static void ReplaceLongIntrinsic(SDNode *N, SmallVectorImpl<SDValue> &Results, 8354 SelectionDAG &DAG) { 8355 unsigned IntNo = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue(); 8356 unsigned Opc = 0; 8357 if (IntNo == Intrinsic::arm_smlald) 8358 Opc = ARMISD::SMLALD; 8359 else if (IntNo == Intrinsic::arm_smlaldx) 8360 Opc = ARMISD::SMLALDX; 8361 else if (IntNo == Intrinsic::arm_smlsld) 8362 Opc = ARMISD::SMLSLD; 8363 else if (IntNo == Intrinsic::arm_smlsldx) 8364 Opc = ARMISD::SMLSLDX; 8365 else 8366 return; 8367 8368 SDLoc dl(N); 8369 SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, 8370 N->getOperand(3), 8371 DAG.getConstant(0, dl, MVT::i32)); 8372 SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, 8373 N->getOperand(3), 8374 DAG.getConstant(1, dl, MVT::i32)); 8375 8376 SDValue LongMul = DAG.getNode(Opc, dl, 8377 DAG.getVTList(MVT::i32, MVT::i32), 8378 N->getOperand(1), N->getOperand(2), 8379 Lo, Hi); 8380 Results.push_back(LongMul.getValue(0)); 8381 Results.push_back(LongMul.getValue(1)); 8382 } 8383 8384 /// ReplaceNodeResults - Replace the results of node with an illegal result 8385 /// type with new values built out of custom code. 8386 void ARMTargetLowering::ReplaceNodeResults(SDNode *N, 8387 SmallVectorImpl<SDValue> &Results, 8388 SelectionDAG &DAG) const { 8389 SDValue Res; 8390 switch (N->getOpcode()) { 8391 default: 8392 llvm_unreachable("Don't know how to custom expand this!"); 8393 case ISD::READ_REGISTER: 8394 ExpandREAD_REGISTER(N, Results, DAG); 8395 break; 8396 case ISD::BITCAST: 8397 Res = ExpandBITCAST(N, DAG, Subtarget); 8398 break; 8399 case ISD::SRL: 8400 case ISD::SRA: 8401 case ISD::SHL: 8402 Res = Expand64BitShift(N, DAG, Subtarget); 8403 break; 8404 case ISD::SREM: 8405 case ISD::UREM: 8406 Res = LowerREM(N, DAG); 8407 break; 8408 case ISD::SDIVREM: 8409 case ISD::UDIVREM: 8410 Res = LowerDivRem(SDValue(N, 0), DAG); 8411 assert(Res.getNumOperands() == 2 && "DivRem needs two values"); 8412 Results.push_back(Res.getValue(0)); 8413 Results.push_back(Res.getValue(1)); 8414 return; 8415 case ISD::READCYCLECOUNTER: 8416 ReplaceREADCYCLECOUNTER(N, Results, DAG, Subtarget); 8417 return; 8418 case ISD::UDIV: 8419 case ISD::SDIV: 8420 assert(Subtarget->isTargetWindows() && "can only expand DIV on Windows"); 8421 return ExpandDIV_Windows(SDValue(N, 0), DAG, N->getOpcode() == ISD::SDIV, 8422 Results); 8423 case ISD::ATOMIC_CMP_SWAP: 8424 ReplaceCMP_SWAP_64Results(N, Results, DAG); 8425 return; 8426 case ISD::INTRINSIC_WO_CHAIN: 8427 return ReplaceLongIntrinsic(N, Results, DAG); 8428 case ISD::ABS: 8429 lowerABS(N, Results, DAG); 8430 return ; 8431 8432 } 8433 if (Res.getNode()) 8434 Results.push_back(Res); 8435 } 8436 8437 //===----------------------------------------------------------------------===// 8438 // ARM Scheduler Hooks 8439 //===----------------------------------------------------------------------===// 8440 8441 /// SetupEntryBlockForSjLj - Insert code into the entry block that creates and 8442 /// registers the function context. 8443 void ARMTargetLowering::SetupEntryBlockForSjLj(MachineInstr &MI, 8444 MachineBasicBlock *MBB, 8445 MachineBasicBlock *DispatchBB, 8446 int FI) const { 8447 assert(!Subtarget->isROPI() && !Subtarget->isRWPI() && 8448 "ROPI/RWPI not currently supported with SjLj"); 8449 const TargetInstrInfo *TII = Subtarget->getInstrInfo(); 8450 DebugLoc dl = MI.getDebugLoc(); 8451 MachineFunction *MF = MBB->getParent(); 8452 MachineRegisterInfo *MRI = &MF->getRegInfo(); 8453 MachineConstantPool *MCP = MF->getConstantPool(); 8454 ARMFunctionInfo *AFI = MF->getInfo<ARMFunctionInfo>(); 8455 const Function &F = MF->getFunction(); 8456 8457 bool isThumb = Subtarget->isThumb(); 8458 bool isThumb2 = Subtarget->isThumb2(); 8459 8460 unsigned PCLabelId = AFI->createPICLabelUId(); 8461 unsigned PCAdj = (isThumb || isThumb2) ? 4 : 8; 8462 ARMConstantPoolValue *CPV = 8463 ARMConstantPoolMBB::Create(F.getContext(), DispatchBB, PCLabelId, PCAdj); 8464 unsigned CPI = MCP->getConstantPoolIndex(CPV, 4); 8465 8466 const TargetRegisterClass *TRC = isThumb ? &ARM::tGPRRegClass 8467 : &ARM::GPRRegClass; 8468 8469 // Grab constant pool and fixed stack memory operands. 8470 MachineMemOperand *CPMMO = 8471 MF->getMachineMemOperand(MachinePointerInfo::getConstantPool(*MF), 8472 MachineMemOperand::MOLoad, 4, 4); 8473 8474 MachineMemOperand *FIMMOSt = 8475 MF->getMachineMemOperand(MachinePointerInfo::getFixedStack(*MF, FI), 8476 MachineMemOperand::MOStore, 4, 4); 8477 8478 // Load the address of the dispatch MBB into the jump buffer. 8479 if (isThumb2) { 8480 // Incoming value: jbuf 8481 // ldr.n r5, LCPI1_1 8482 // orr r5, r5, #1 8483 // add r5, pc 8484 // str r5, [$jbuf, #+4] ; &jbuf[1] 8485 unsigned NewVReg1 = MRI->createVirtualRegister(TRC); 8486 BuildMI(*MBB, MI, dl, TII->get(ARM::t2LDRpci), NewVReg1) 8487 .addConstantPoolIndex(CPI) 8488 .addMemOperand(CPMMO) 8489 .add(predOps(ARMCC::AL)); 8490 // Set the low bit because of thumb mode. 8491 unsigned NewVReg2 = MRI->createVirtualRegister(TRC); 8492 BuildMI(*MBB, MI, dl, TII->get(ARM::t2ORRri), NewVReg2) 8493 .addReg(NewVReg1, RegState::Kill) 8494 .addImm(0x01) 8495 .add(predOps(ARMCC::AL)) 8496 .add(condCodeOp()); 8497 unsigned NewVReg3 = MRI->createVirtualRegister(TRC); 8498 BuildMI(*MBB, MI, dl, TII->get(ARM::tPICADD), NewVReg3) 8499 .addReg(NewVReg2, RegState::Kill) 8500 .addImm(PCLabelId); 8501 BuildMI(*MBB, MI, dl, TII->get(ARM::t2STRi12)) 8502 .addReg(NewVReg3, RegState::Kill) 8503 .addFrameIndex(FI) 8504 .addImm(36) // &jbuf[1] :: pc 8505 .addMemOperand(FIMMOSt) 8506 .add(predOps(ARMCC::AL)); 8507 } else if (isThumb) { 8508 // Incoming value: jbuf 8509 // ldr.n r1, LCPI1_4 8510 // add r1, pc 8511 // mov r2, #1 8512 // orrs r1, r2 8513 // add r2, $jbuf, #+4 ; &jbuf[1] 8514 // str r1, [r2] 8515 unsigned NewVReg1 = MRI->createVirtualRegister(TRC); 8516 BuildMI(*MBB, MI, dl, TII->get(ARM::tLDRpci), NewVReg1) 8517 .addConstantPoolIndex(CPI) 8518 .addMemOperand(CPMMO) 8519 .add(predOps(ARMCC::AL)); 8520 unsigned NewVReg2 = MRI->createVirtualRegister(TRC); 8521 BuildMI(*MBB, MI, dl, TII->get(ARM::tPICADD), NewVReg2) 8522 .addReg(NewVReg1, RegState::Kill) 8523 .addImm(PCLabelId); 8524 // Set the low bit because of thumb mode. 8525 unsigned NewVReg3 = MRI->createVirtualRegister(TRC); 8526 BuildMI(*MBB, MI, dl, TII->get(ARM::tMOVi8), NewVReg3) 8527 .addReg(ARM::CPSR, RegState::Define) 8528 .addImm(1) 8529 .add(predOps(ARMCC::AL)); 8530 unsigned NewVReg4 = MRI->createVirtualRegister(TRC); 8531 BuildMI(*MBB, MI, dl, TII->get(ARM::tORR), NewVReg4) 8532 .addReg(ARM::CPSR, RegState::Define) 8533 .addReg(NewVReg2, RegState::Kill) 8534 .addReg(NewVReg3, RegState::Kill) 8535 .add(predOps(ARMCC::AL)); 8536 unsigned NewVReg5 = MRI->createVirtualRegister(TRC); 8537 BuildMI(*MBB, MI, dl, TII->get(ARM::tADDframe), NewVReg5) 8538 .addFrameIndex(FI) 8539 .addImm(36); // &jbuf[1] :: pc 8540 BuildMI(*MBB, MI, dl, TII->get(ARM::tSTRi)) 8541 .addReg(NewVReg4, RegState::Kill) 8542 .addReg(NewVReg5, RegState::Kill) 8543 .addImm(0) 8544 .addMemOperand(FIMMOSt) 8545 .add(predOps(ARMCC::AL)); 8546 } else { 8547 // Incoming value: jbuf 8548 // ldr r1, LCPI1_1 8549 // add r1, pc, r1 8550 // str r1, [$jbuf, #+4] ; &jbuf[1] 8551 unsigned NewVReg1 = MRI->createVirtualRegister(TRC); 8552 BuildMI(*MBB, MI, dl, TII->get(ARM::LDRi12), NewVReg1) 8553 .addConstantPoolIndex(CPI) 8554 .addImm(0) 8555 .addMemOperand(CPMMO) 8556 .add(predOps(ARMCC::AL)); 8557 unsigned NewVReg2 = MRI->createVirtualRegister(TRC); 8558 BuildMI(*MBB, MI, dl, TII->get(ARM::PICADD), NewVReg2) 8559 .addReg(NewVReg1, RegState::Kill) 8560 .addImm(PCLabelId) 8561 .add(predOps(ARMCC::AL)); 8562 BuildMI(*MBB, MI, dl, TII->get(ARM::STRi12)) 8563 .addReg(NewVReg2, RegState::Kill) 8564 .addFrameIndex(FI) 8565 .addImm(36) // &jbuf[1] :: pc 8566 .addMemOperand(FIMMOSt) 8567 .add(predOps(ARMCC::AL)); 8568 } 8569 } 8570 8571 void ARMTargetLowering::EmitSjLjDispatchBlock(MachineInstr &MI, 8572 MachineBasicBlock *MBB) const { 8573 const TargetInstrInfo *TII = Subtarget->getInstrInfo(); 8574 DebugLoc dl = MI.getDebugLoc(); 8575 MachineFunction *MF = MBB->getParent(); 8576 MachineRegisterInfo *MRI = &MF->getRegInfo(); 8577 MachineFrameInfo &MFI = MF->getFrameInfo(); 8578 int FI = MFI.getFunctionContextIndex(); 8579 8580 const TargetRegisterClass *TRC = Subtarget->isThumb() ? &ARM::tGPRRegClass 8581 : &ARM::GPRnopcRegClass; 8582 8583 // Get a mapping of the call site numbers to all of the landing pads they're 8584 // associated with. 8585 DenseMap<unsigned, SmallVector<MachineBasicBlock*, 2>> CallSiteNumToLPad; 8586 unsigned MaxCSNum = 0; 8587 for (MachineFunction::iterator BB = MF->begin(), E = MF->end(); BB != E; 8588 ++BB) { 8589 if (!BB->isEHPad()) continue; 8590 8591 // FIXME: We should assert that the EH_LABEL is the first MI in the landing 8592 // pad. 8593 for (MachineBasicBlock::iterator 8594 II = BB->begin(), IE = BB->end(); II != IE; ++II) { 8595 if (!II->isEHLabel()) continue; 8596 8597 MCSymbol *Sym = II->getOperand(0).getMCSymbol(); 8598 if (!MF->hasCallSiteLandingPad(Sym)) continue; 8599 8600 SmallVectorImpl<unsigned> &CallSiteIdxs = MF->getCallSiteLandingPad(Sym); 8601 for (SmallVectorImpl<unsigned>::iterator 8602 CSI = CallSiteIdxs.begin(), CSE = CallSiteIdxs.end(); 8603 CSI != CSE; ++CSI) { 8604 CallSiteNumToLPad[*CSI].push_back(&*BB); 8605 MaxCSNum = std::max(MaxCSNum, *CSI); 8606 } 8607 break; 8608 } 8609 } 8610 8611 // Get an ordered list of the machine basic blocks for the jump table. 8612 std::vector<MachineBasicBlock*> LPadList; 8613 SmallPtrSet<MachineBasicBlock*, 32> InvokeBBs; 8614 LPadList.reserve(CallSiteNumToLPad.size()); 8615 for (unsigned I = 1; I <= MaxCSNum; ++I) { 8616 SmallVectorImpl<MachineBasicBlock*> &MBBList = CallSiteNumToLPad[I]; 8617 for (SmallVectorImpl<MachineBasicBlock*>::iterator 8618 II = MBBList.begin(), IE = MBBList.end(); II != IE; ++II) { 8619 LPadList.push_back(*II); 8620 InvokeBBs.insert((*II)->pred_begin(), (*II)->pred_end()); 8621 } 8622 } 8623 8624 assert(!LPadList.empty() && 8625 "No landing pad destinations for the dispatch jump table!"); 8626 8627 // Create the jump table and associated information. 8628 MachineJumpTableInfo *JTI = 8629 MF->getOrCreateJumpTableInfo(MachineJumpTableInfo::EK_Inline); 8630 unsigned MJTI = JTI->createJumpTableIndex(LPadList); 8631 8632 // Create the MBBs for the dispatch code. 8633 8634 // Shove the dispatch's address into the return slot in the function context. 8635 MachineBasicBlock *DispatchBB = MF->CreateMachineBasicBlock(); 8636 DispatchBB->setIsEHPad(); 8637 8638 MachineBasicBlock *TrapBB = MF->CreateMachineBasicBlock(); 8639 unsigned trap_opcode; 8640 if (Subtarget->isThumb()) 8641 trap_opcode = ARM::tTRAP; 8642 else 8643 trap_opcode = Subtarget->useNaClTrap() ? ARM::TRAPNaCl : ARM::TRAP; 8644 8645 BuildMI(TrapBB, dl, TII->get(trap_opcode)); 8646 DispatchBB->addSuccessor(TrapBB); 8647 8648 MachineBasicBlock *DispContBB = MF->CreateMachineBasicBlock(); 8649 DispatchBB->addSuccessor(DispContBB); 8650 8651 // Insert and MBBs. 8652 MF->insert(MF->end(), DispatchBB); 8653 MF->insert(MF->end(), DispContBB); 8654 MF->insert(MF->end(), TrapBB); 8655 8656 // Insert code into the entry block that creates and registers the function 8657 // context. 8658 SetupEntryBlockForSjLj(MI, MBB, DispatchBB, FI); 8659 8660 MachineMemOperand *FIMMOLd = MF->getMachineMemOperand( 8661 MachinePointerInfo::getFixedStack(*MF, FI), 8662 MachineMemOperand::MOLoad | MachineMemOperand::MOVolatile, 4, 4); 8663 8664 MachineInstrBuilder MIB; 8665 MIB = BuildMI(DispatchBB, dl, TII->get(ARM::Int_eh_sjlj_dispatchsetup)); 8666 8667 const ARMBaseInstrInfo *AII = static_cast<const ARMBaseInstrInfo*>(TII); 8668 const ARMBaseRegisterInfo &RI = AII->getRegisterInfo(); 8669 8670 // Add a register mask with no preserved registers. This results in all 8671 // registers being marked as clobbered. This can't work if the dispatch block 8672 // is in a Thumb1 function and is linked with ARM code which uses the FP 8673 // registers, as there is no way to preserve the FP registers in Thumb1 mode. 8674 MIB.addRegMask(RI.getSjLjDispatchPreservedMask(*MF)); 8675 8676 bool IsPositionIndependent = isPositionIndependent(); 8677 unsigned NumLPads = LPadList.size(); 8678 if (Subtarget->isThumb2()) { 8679 unsigned NewVReg1 = MRI->createVirtualRegister(TRC); 8680 BuildMI(DispatchBB, dl, TII->get(ARM::t2LDRi12), NewVReg1) 8681 .addFrameIndex(FI) 8682 .addImm(4) 8683 .addMemOperand(FIMMOLd) 8684 .add(predOps(ARMCC::AL)); 8685 8686 if (NumLPads < 256) { 8687 BuildMI(DispatchBB, dl, TII->get(ARM::t2CMPri)) 8688 .addReg(NewVReg1) 8689 .addImm(LPadList.size()) 8690 .add(predOps(ARMCC::AL)); 8691 } else { 8692 unsigned VReg1 = MRI->createVirtualRegister(TRC); 8693 BuildMI(DispatchBB, dl, TII->get(ARM::t2MOVi16), VReg1) 8694 .addImm(NumLPads & 0xFFFF) 8695 .add(predOps(ARMCC::AL)); 8696 8697 unsigned VReg2 = VReg1; 8698 if ((NumLPads & 0xFFFF0000) != 0) { 8699 VReg2 = MRI->createVirtualRegister(TRC); 8700 BuildMI(DispatchBB, dl, TII->get(ARM::t2MOVTi16), VReg2) 8701 .addReg(VReg1) 8702 .addImm(NumLPads >> 16) 8703 .add(predOps(ARMCC::AL)); 8704 } 8705 8706 BuildMI(DispatchBB, dl, TII->get(ARM::t2CMPrr)) 8707 .addReg(NewVReg1) 8708 .addReg(VReg2) 8709 .add(predOps(ARMCC::AL)); 8710 } 8711 8712 BuildMI(DispatchBB, dl, TII->get(ARM::t2Bcc)) 8713 .addMBB(TrapBB) 8714 .addImm(ARMCC::HI) 8715 .addReg(ARM::CPSR); 8716 8717 unsigned NewVReg3 = MRI->createVirtualRegister(TRC); 8718 BuildMI(DispContBB, dl, TII->get(ARM::t2LEApcrelJT), NewVReg3) 8719 .addJumpTableIndex(MJTI) 8720 .add(predOps(ARMCC::AL)); 8721 8722 unsigned NewVReg4 = MRI->createVirtualRegister(TRC); 8723 BuildMI(DispContBB, dl, TII->get(ARM::t2ADDrs), NewVReg4) 8724 .addReg(NewVReg3, RegState::Kill) 8725 .addReg(NewVReg1) 8726 .addImm(ARM_AM::getSORegOpc(ARM_AM::lsl, 2)) 8727 .add(predOps(ARMCC::AL)) 8728 .add(condCodeOp()); 8729 8730 BuildMI(DispContBB, dl, TII->get(ARM::t2BR_JT)) 8731 .addReg(NewVReg4, RegState::Kill) 8732 .addReg(NewVReg1) 8733 .addJumpTableIndex(MJTI); 8734 } else if (Subtarget->isThumb()) { 8735 unsigned NewVReg1 = MRI->createVirtualRegister(TRC); 8736 BuildMI(DispatchBB, dl, TII->get(ARM::tLDRspi), NewVReg1) 8737 .addFrameIndex(FI) 8738 .addImm(1) 8739 .addMemOperand(FIMMOLd) 8740 .add(predOps(ARMCC::AL)); 8741 8742 if (NumLPads < 256) { 8743 BuildMI(DispatchBB, dl, TII->get(ARM::tCMPi8)) 8744 .addReg(NewVReg1) 8745 .addImm(NumLPads) 8746 .add(predOps(ARMCC::AL)); 8747 } else { 8748 MachineConstantPool *ConstantPool = MF->getConstantPool(); 8749 Type *Int32Ty = Type::getInt32Ty(MF->getFunction().getContext()); 8750 const Constant *C = ConstantInt::get(Int32Ty, NumLPads); 8751 8752 // MachineConstantPool wants an explicit alignment. 8753 unsigned Align = MF->getDataLayout().getPrefTypeAlignment(Int32Ty); 8754 if (Align == 0) 8755 Align = MF->getDataLayout().getTypeAllocSize(C->getType()); 8756 unsigned Idx = ConstantPool->getConstantPoolIndex(C, Align); 8757 8758 unsigned VReg1 = MRI->createVirtualRegister(TRC); 8759 BuildMI(DispatchBB, dl, TII->get(ARM::tLDRpci)) 8760 .addReg(VReg1, RegState::Define) 8761 .addConstantPoolIndex(Idx) 8762 .add(predOps(ARMCC::AL)); 8763 BuildMI(DispatchBB, dl, TII->get(ARM::tCMPr)) 8764 .addReg(NewVReg1) 8765 .addReg(VReg1) 8766 .add(predOps(ARMCC::AL)); 8767 } 8768 8769 BuildMI(DispatchBB, dl, TII->get(ARM::tBcc)) 8770 .addMBB(TrapBB) 8771 .addImm(ARMCC::HI) 8772 .addReg(ARM::CPSR); 8773 8774 unsigned NewVReg2 = MRI->createVirtualRegister(TRC); 8775 BuildMI(DispContBB, dl, TII->get(ARM::tLSLri), NewVReg2) 8776 .addReg(ARM::CPSR, RegState::Define) 8777 .addReg(NewVReg1) 8778 .addImm(2) 8779 .add(predOps(ARMCC::AL)); 8780 8781 unsigned NewVReg3 = MRI->createVirtualRegister(TRC); 8782 BuildMI(DispContBB, dl, TII->get(ARM::tLEApcrelJT), NewVReg3) 8783 .addJumpTableIndex(MJTI) 8784 .add(predOps(ARMCC::AL)); 8785 8786 unsigned NewVReg4 = MRI->createVirtualRegister(TRC); 8787 BuildMI(DispContBB, dl, TII->get(ARM::tADDrr), NewVReg4) 8788 .addReg(ARM::CPSR, RegState::Define) 8789 .addReg(NewVReg2, RegState::Kill) 8790 .addReg(NewVReg3) 8791 .add(predOps(ARMCC::AL)); 8792 8793 MachineMemOperand *JTMMOLd = MF->getMachineMemOperand( 8794 MachinePointerInfo::getJumpTable(*MF), MachineMemOperand::MOLoad, 4, 4); 8795 8796 unsigned NewVReg5 = MRI->createVirtualRegister(TRC); 8797 BuildMI(DispContBB, dl, TII->get(ARM::tLDRi), NewVReg5) 8798 .addReg(NewVReg4, RegState::Kill) 8799 .addImm(0) 8800 .addMemOperand(JTMMOLd) 8801 .add(predOps(ARMCC::AL)); 8802 8803 unsigned NewVReg6 = NewVReg5; 8804 if (IsPositionIndependent) { 8805 NewVReg6 = MRI->createVirtualRegister(TRC); 8806 BuildMI(DispContBB, dl, TII->get(ARM::tADDrr), NewVReg6) 8807 .addReg(ARM::CPSR, RegState::Define) 8808 .addReg(NewVReg5, RegState::Kill) 8809 .addReg(NewVReg3) 8810 .add(predOps(ARMCC::AL)); 8811 } 8812 8813 BuildMI(DispContBB, dl, TII->get(ARM::tBR_JTr)) 8814 .addReg(NewVReg6, RegState::Kill) 8815 .addJumpTableIndex(MJTI); 8816 } else { 8817 unsigned NewVReg1 = MRI->createVirtualRegister(TRC); 8818 BuildMI(DispatchBB, dl, TII->get(ARM::LDRi12), NewVReg1) 8819 .addFrameIndex(FI) 8820 .addImm(4) 8821 .addMemOperand(FIMMOLd) 8822 .add(predOps(ARMCC::AL)); 8823 8824 if (NumLPads < 256) { 8825 BuildMI(DispatchBB, dl, TII->get(ARM::CMPri)) 8826 .addReg(NewVReg1) 8827 .addImm(NumLPads) 8828 .add(predOps(ARMCC::AL)); 8829 } else if (Subtarget->hasV6T2Ops() && isUInt<16>(NumLPads)) { 8830 unsigned VReg1 = MRI->createVirtualRegister(TRC); 8831 BuildMI(DispatchBB, dl, TII->get(ARM::MOVi16), VReg1) 8832 .addImm(NumLPads & 0xFFFF) 8833 .add(predOps(ARMCC::AL)); 8834 8835 unsigned VReg2 = VReg1; 8836 if ((NumLPads & 0xFFFF0000) != 0) { 8837 VReg2 = MRI->createVirtualRegister(TRC); 8838 BuildMI(DispatchBB, dl, TII->get(ARM::MOVTi16), VReg2) 8839 .addReg(VReg1) 8840 .addImm(NumLPads >> 16) 8841 .add(predOps(ARMCC::AL)); 8842 } 8843 8844 BuildMI(DispatchBB, dl, TII->get(ARM::CMPrr)) 8845 .addReg(NewVReg1) 8846 .addReg(VReg2) 8847 .add(predOps(ARMCC::AL)); 8848 } else { 8849 MachineConstantPool *ConstantPool = MF->getConstantPool(); 8850 Type *Int32Ty = Type::getInt32Ty(MF->getFunction().getContext()); 8851 const Constant *C = ConstantInt::get(Int32Ty, NumLPads); 8852 8853 // MachineConstantPool wants an explicit alignment. 8854 unsigned Align = MF->getDataLayout().getPrefTypeAlignment(Int32Ty); 8855 if (Align == 0) 8856 Align = MF->getDataLayout().getTypeAllocSize(C->getType()); 8857 unsigned Idx = ConstantPool->getConstantPoolIndex(C, Align); 8858 8859 unsigned VReg1 = MRI->createVirtualRegister(TRC); 8860 BuildMI(DispatchBB, dl, TII->get(ARM::LDRcp)) 8861 .addReg(VReg1, RegState::Define) 8862 .addConstantPoolIndex(Idx) 8863 .addImm(0) 8864 .add(predOps(ARMCC::AL)); 8865 BuildMI(DispatchBB, dl, TII->get(ARM::CMPrr)) 8866 .addReg(NewVReg1) 8867 .addReg(VReg1, RegState::Kill) 8868 .add(predOps(ARMCC::AL)); 8869 } 8870 8871 BuildMI(DispatchBB, dl, TII->get(ARM::Bcc)) 8872 .addMBB(TrapBB) 8873 .addImm(ARMCC::HI) 8874 .addReg(ARM::CPSR); 8875 8876 unsigned NewVReg3 = MRI->createVirtualRegister(TRC); 8877 BuildMI(DispContBB, dl, TII->get(ARM::MOVsi), NewVReg3) 8878 .addReg(NewVReg1) 8879 .addImm(ARM_AM::getSORegOpc(ARM_AM::lsl, 2)) 8880 .add(predOps(ARMCC::AL)) 8881 .add(condCodeOp()); 8882 unsigned NewVReg4 = MRI->createVirtualRegister(TRC); 8883 BuildMI(DispContBB, dl, TII->get(ARM::LEApcrelJT), NewVReg4) 8884 .addJumpTableIndex(MJTI) 8885 .add(predOps(ARMCC::AL)); 8886 8887 MachineMemOperand *JTMMOLd = MF->getMachineMemOperand( 8888 MachinePointerInfo::getJumpTable(*MF), MachineMemOperand::MOLoad, 4, 4); 8889 unsigned NewVReg5 = MRI->createVirtualRegister(TRC); 8890 BuildMI(DispContBB, dl, TII->get(ARM::LDRrs), NewVReg5) 8891 .addReg(NewVReg3, RegState::Kill) 8892 .addReg(NewVReg4) 8893 .addImm(0) 8894 .addMemOperand(JTMMOLd) 8895 .add(predOps(ARMCC::AL)); 8896 8897 if (IsPositionIndependent) { 8898 BuildMI(DispContBB, dl, TII->get(ARM::BR_JTadd)) 8899 .addReg(NewVReg5, RegState::Kill) 8900 .addReg(NewVReg4) 8901 .addJumpTableIndex(MJTI); 8902 } else { 8903 BuildMI(DispContBB, dl, TII->get(ARM::BR_JTr)) 8904 .addReg(NewVReg5, RegState::Kill) 8905 .addJumpTableIndex(MJTI); 8906 } 8907 } 8908 8909 // Add the jump table entries as successors to the MBB. 8910 SmallPtrSet<MachineBasicBlock*, 8> SeenMBBs; 8911 for (std::vector<MachineBasicBlock*>::iterator 8912 I = LPadList.begin(), E = LPadList.end(); I != E; ++I) { 8913 MachineBasicBlock *CurMBB = *I; 8914 if (SeenMBBs.insert(CurMBB).second) 8915 DispContBB->addSuccessor(CurMBB); 8916 } 8917 8918 // N.B. the order the invoke BBs are processed in doesn't matter here. 8919 const MCPhysReg *SavedRegs = RI.getCalleeSavedRegs(MF); 8920 SmallVector<MachineBasicBlock*, 64> MBBLPads; 8921 for (MachineBasicBlock *BB : InvokeBBs) { 8922 8923 // Remove the landing pad successor from the invoke block and replace it 8924 // with the new dispatch block. 8925 SmallVector<MachineBasicBlock*, 4> Successors(BB->succ_begin(), 8926 BB->succ_end()); 8927 while (!Successors.empty()) { 8928 MachineBasicBlock *SMBB = Successors.pop_back_val(); 8929 if (SMBB->isEHPad()) { 8930 BB->removeSuccessor(SMBB); 8931 MBBLPads.push_back(SMBB); 8932 } 8933 } 8934 8935 BB->addSuccessor(DispatchBB, BranchProbability::getZero()); 8936 BB->normalizeSuccProbs(); 8937 8938 // Find the invoke call and mark all of the callee-saved registers as 8939 // 'implicit defined' so that they're spilled. This prevents code from 8940 // moving instructions to before the EH block, where they will never be 8941 // executed. 8942 for (MachineBasicBlock::reverse_iterator 8943 II = BB->rbegin(), IE = BB->rend(); II != IE; ++II) { 8944 if (!II->isCall()) continue; 8945 8946 DenseMap<unsigned, bool> DefRegs; 8947 for (MachineInstr::mop_iterator 8948 OI = II->operands_begin(), OE = II->operands_end(); 8949 OI != OE; ++OI) { 8950 if (!OI->isReg()) continue; 8951 DefRegs[OI->getReg()] = true; 8952 } 8953 8954 MachineInstrBuilder MIB(*MF, &*II); 8955 8956 for (unsigned i = 0; SavedRegs[i] != 0; ++i) { 8957 unsigned Reg = SavedRegs[i]; 8958 if (Subtarget->isThumb2() && 8959 !ARM::tGPRRegClass.contains(Reg) && 8960 !ARM::hGPRRegClass.contains(Reg)) 8961 continue; 8962 if (Subtarget->isThumb1Only() && !ARM::tGPRRegClass.contains(Reg)) 8963 continue; 8964 if (!Subtarget->isThumb() && !ARM::GPRRegClass.contains(Reg)) 8965 continue; 8966 if (!DefRegs[Reg]) 8967 MIB.addReg(Reg, RegState::ImplicitDefine | RegState::Dead); 8968 } 8969 8970 break; 8971 } 8972 } 8973 8974 // Mark all former landing pads as non-landing pads. The dispatch is the only 8975 // landing pad now. 8976 for (SmallVectorImpl<MachineBasicBlock*>::iterator 8977 I = MBBLPads.begin(), E = MBBLPads.end(); I != E; ++I) 8978 (*I)->setIsEHPad(false); 8979 8980 // The instruction is gone now. 8981 MI.eraseFromParent(); 8982 } 8983 8984 static 8985 MachineBasicBlock *OtherSucc(MachineBasicBlock *MBB, MachineBasicBlock *Succ) { 8986 for (MachineBasicBlock::succ_iterator I = MBB->succ_begin(), 8987 E = MBB->succ_end(); I != E; ++I) 8988 if (*I != Succ) 8989 return *I; 8990 llvm_unreachable("Expecting a BB with two successors!"); 8991 } 8992 8993 /// Return the load opcode for a given load size. If load size >= 8, 8994 /// neon opcode will be returned. 8995 static unsigned getLdOpcode(unsigned LdSize, bool IsThumb1, bool IsThumb2) { 8996 if (LdSize >= 8) 8997 return LdSize == 16 ? ARM::VLD1q32wb_fixed 8998 : LdSize == 8 ? ARM::VLD1d32wb_fixed : 0; 8999 if (IsThumb1) 9000 return LdSize == 4 ? ARM::tLDRi 9001 : LdSize == 2 ? ARM::tLDRHi 9002 : LdSize == 1 ? ARM::tLDRBi : 0; 9003 if (IsThumb2) 9004 return LdSize == 4 ? ARM::t2LDR_POST 9005 : LdSize == 2 ? ARM::t2LDRH_POST 9006 : LdSize == 1 ? ARM::t2LDRB_POST : 0; 9007 return LdSize == 4 ? ARM::LDR_POST_IMM 9008 : LdSize == 2 ? ARM::LDRH_POST 9009 : LdSize == 1 ? ARM::LDRB_POST_IMM : 0; 9010 } 9011 9012 /// Return the store opcode for a given store size. If store size >= 8, 9013 /// neon opcode will be returned. 9014 static unsigned getStOpcode(unsigned StSize, bool IsThumb1, bool IsThumb2) { 9015 if (StSize >= 8) 9016 return StSize == 16 ? ARM::VST1q32wb_fixed 9017 : StSize == 8 ? ARM::VST1d32wb_fixed : 0; 9018 if (IsThumb1) 9019 return StSize == 4 ? ARM::tSTRi 9020 : StSize == 2 ? ARM::tSTRHi 9021 : StSize == 1 ? ARM::tSTRBi : 0; 9022 if (IsThumb2) 9023 return StSize == 4 ? ARM::t2STR_POST 9024 : StSize == 2 ? ARM::t2STRH_POST 9025 : StSize == 1 ? ARM::t2STRB_POST : 0; 9026 return StSize == 4 ? ARM::STR_POST_IMM 9027 : StSize == 2 ? ARM::STRH_POST 9028 : StSize == 1 ? ARM::STRB_POST_IMM : 0; 9029 } 9030 9031 /// Emit a post-increment load operation with given size. The instructions 9032 /// will be added to BB at Pos. 9033 static void emitPostLd(MachineBasicBlock *BB, MachineBasicBlock::iterator Pos, 9034 const TargetInstrInfo *TII, const DebugLoc &dl, 9035 unsigned LdSize, unsigned Data, unsigned AddrIn, 9036 unsigned AddrOut, bool IsThumb1, bool IsThumb2) { 9037 unsigned LdOpc = getLdOpcode(LdSize, IsThumb1, IsThumb2); 9038 assert(LdOpc != 0 && "Should have a load opcode"); 9039 if (LdSize >= 8) { 9040 BuildMI(*BB, Pos, dl, TII->get(LdOpc), Data) 9041 .addReg(AddrOut, RegState::Define) 9042 .addReg(AddrIn) 9043 .addImm(0) 9044 .add(predOps(ARMCC::AL)); 9045 } else if (IsThumb1) { 9046 // load + update AddrIn 9047 BuildMI(*BB, Pos, dl, TII->get(LdOpc), Data) 9048 .addReg(AddrIn) 9049 .addImm(0) 9050 .add(predOps(ARMCC::AL)); 9051 BuildMI(*BB, Pos, dl, TII->get(ARM::tADDi8), AddrOut) 9052 .add(t1CondCodeOp()) 9053 .addReg(AddrIn) 9054 .addImm(LdSize) 9055 .add(predOps(ARMCC::AL)); 9056 } else if (IsThumb2) { 9057 BuildMI(*BB, Pos, dl, TII->get(LdOpc), Data) 9058 .addReg(AddrOut, RegState::Define) 9059 .addReg(AddrIn) 9060 .addImm(LdSize) 9061 .add(predOps(ARMCC::AL)); 9062 } else { // arm 9063 BuildMI(*BB, Pos, dl, TII->get(LdOpc), Data) 9064 .addReg(AddrOut, RegState::Define) 9065 .addReg(AddrIn) 9066 .addReg(0) 9067 .addImm(LdSize) 9068 .add(predOps(ARMCC::AL)); 9069 } 9070 } 9071 9072 /// Emit a post-increment store operation with given size. The instructions 9073 /// will be added to BB at Pos. 9074 static void emitPostSt(MachineBasicBlock *BB, MachineBasicBlock::iterator Pos, 9075 const TargetInstrInfo *TII, const DebugLoc &dl, 9076 unsigned StSize, unsigned Data, unsigned AddrIn, 9077 unsigned AddrOut, bool IsThumb1, bool IsThumb2) { 9078 unsigned StOpc = getStOpcode(StSize, IsThumb1, IsThumb2); 9079 assert(StOpc != 0 && "Should have a store opcode"); 9080 if (StSize >= 8) { 9081 BuildMI(*BB, Pos, dl, TII->get(StOpc), AddrOut) 9082 .addReg(AddrIn) 9083 .addImm(0) 9084 .addReg(Data) 9085 .add(predOps(ARMCC::AL)); 9086 } else if (IsThumb1) { 9087 // store + update AddrIn 9088 BuildMI(*BB, Pos, dl, TII->get(StOpc)) 9089 .addReg(Data) 9090 .addReg(AddrIn) 9091 .addImm(0) 9092 .add(predOps(ARMCC::AL)); 9093 BuildMI(*BB, Pos, dl, TII->get(ARM::tADDi8), AddrOut) 9094 .add(t1CondCodeOp()) 9095 .addReg(AddrIn) 9096 .addImm(StSize) 9097 .add(predOps(ARMCC::AL)); 9098 } else if (IsThumb2) { 9099 BuildMI(*BB, Pos, dl, TII->get(StOpc), AddrOut) 9100 .addReg(Data) 9101 .addReg(AddrIn) 9102 .addImm(StSize) 9103 .add(predOps(ARMCC::AL)); 9104 } else { // arm 9105 BuildMI(*BB, Pos, dl, TII->get(StOpc), AddrOut) 9106 .addReg(Data) 9107 .addReg(AddrIn) 9108 .addReg(0) 9109 .addImm(StSize) 9110 .add(predOps(ARMCC::AL)); 9111 } 9112 } 9113 9114 MachineBasicBlock * 9115 ARMTargetLowering::EmitStructByval(MachineInstr &MI, 9116 MachineBasicBlock *BB) const { 9117 // This pseudo instruction has 3 operands: dst, src, size 9118 // We expand it to a loop if size > Subtarget->getMaxInlineSizeThreshold(). 9119 // Otherwise, we will generate unrolled scalar copies. 9120 const TargetInstrInfo *TII = Subtarget->getInstrInfo(); 9121 const BasicBlock *LLVM_BB = BB->getBasicBlock(); 9122 MachineFunction::iterator It = ++BB->getIterator(); 9123 9124 unsigned dest = MI.getOperand(0).getReg(); 9125 unsigned src = MI.getOperand(1).getReg(); 9126 unsigned SizeVal = MI.getOperand(2).getImm(); 9127 unsigned Align = MI.getOperand(3).getImm(); 9128 DebugLoc dl = MI.getDebugLoc(); 9129 9130 MachineFunction *MF = BB->getParent(); 9131 MachineRegisterInfo &MRI = MF->getRegInfo(); 9132 unsigned UnitSize = 0; 9133 const TargetRegisterClass *TRC = nullptr; 9134 const TargetRegisterClass *VecTRC = nullptr; 9135 9136 bool IsThumb1 = Subtarget->isThumb1Only(); 9137 bool IsThumb2 = Subtarget->isThumb2(); 9138 bool IsThumb = Subtarget->isThumb(); 9139 9140 if (Align & 1) { 9141 UnitSize = 1; 9142 } else if (Align & 2) { 9143 UnitSize = 2; 9144 } else { 9145 // Check whether we can use NEON instructions. 9146 if (!MF->getFunction().hasFnAttribute(Attribute::NoImplicitFloat) && 9147 Subtarget->hasNEON()) { 9148 if ((Align % 16 == 0) && SizeVal >= 16) 9149 UnitSize = 16; 9150 else if ((Align % 8 == 0) && SizeVal >= 8) 9151 UnitSize = 8; 9152 } 9153 // Can't use NEON instructions. 9154 if (UnitSize == 0) 9155 UnitSize = 4; 9156 } 9157 9158 // Select the correct opcode and register class for unit size load/store 9159 bool IsNeon = UnitSize >= 8; 9160 TRC = IsThumb ? &ARM::tGPRRegClass : &ARM::GPRRegClass; 9161 if (IsNeon) 9162 VecTRC = UnitSize == 16 ? &ARM::DPairRegClass 9163 : UnitSize == 8 ? &ARM::DPRRegClass 9164 : nullptr; 9165 9166 unsigned BytesLeft = SizeVal % UnitSize; 9167 unsigned LoopSize = SizeVal - BytesLeft; 9168 9169 if (SizeVal <= Subtarget->getMaxInlineSizeThreshold()) { 9170 // Use LDR and STR to copy. 9171 // [scratch, srcOut] = LDR_POST(srcIn, UnitSize) 9172 // [destOut] = STR_POST(scratch, destIn, UnitSize) 9173 unsigned srcIn = src; 9174 unsigned destIn = dest; 9175 for (unsigned i = 0; i < LoopSize; i+=UnitSize) { 9176 unsigned srcOut = MRI.createVirtualRegister(TRC); 9177 unsigned destOut = MRI.createVirtualRegister(TRC); 9178 unsigned scratch = MRI.createVirtualRegister(IsNeon ? VecTRC : TRC); 9179 emitPostLd(BB, MI, TII, dl, UnitSize, scratch, srcIn, srcOut, 9180 IsThumb1, IsThumb2); 9181 emitPostSt(BB, MI, TII, dl, UnitSize, scratch, destIn, destOut, 9182 IsThumb1, IsThumb2); 9183 srcIn = srcOut; 9184 destIn = destOut; 9185 } 9186 9187 // Handle the leftover bytes with LDRB and STRB. 9188 // [scratch, srcOut] = LDRB_POST(srcIn, 1) 9189 // [destOut] = STRB_POST(scratch, destIn, 1) 9190 for (unsigned i = 0; i < BytesLeft; i++) { 9191 unsigned srcOut = MRI.createVirtualRegister(TRC); 9192 unsigned destOut = MRI.createVirtualRegister(TRC); 9193 unsigned scratch = MRI.createVirtualRegister(TRC); 9194 emitPostLd(BB, MI, TII, dl, 1, scratch, srcIn, srcOut, 9195 IsThumb1, IsThumb2); 9196 emitPostSt(BB, MI, TII, dl, 1, scratch, destIn, destOut, 9197 IsThumb1, IsThumb2); 9198 srcIn = srcOut; 9199 destIn = destOut; 9200 } 9201 MI.eraseFromParent(); // The instruction is gone now. 9202 return BB; 9203 } 9204 9205 // Expand the pseudo op to a loop. 9206 // thisMBB: 9207 // ... 9208 // movw varEnd, # --> with thumb2 9209 // movt varEnd, # 9210 // ldrcp varEnd, idx --> without thumb2 9211 // fallthrough --> loopMBB 9212 // loopMBB: 9213 // PHI varPhi, varEnd, varLoop 9214 // PHI srcPhi, src, srcLoop 9215 // PHI destPhi, dst, destLoop 9216 // [scratch, srcLoop] = LDR_POST(srcPhi, UnitSize) 9217 // [destLoop] = STR_POST(scratch, destPhi, UnitSize) 9218 // subs varLoop, varPhi, #UnitSize 9219 // bne loopMBB 9220 // fallthrough --> exitMBB 9221 // exitMBB: 9222 // epilogue to handle left-over bytes 9223 // [scratch, srcOut] = LDRB_POST(srcLoop, 1) 9224 // [destOut] = STRB_POST(scratch, destLoop, 1) 9225 MachineBasicBlock *loopMBB = MF->CreateMachineBasicBlock(LLVM_BB); 9226 MachineBasicBlock *exitMBB = MF->CreateMachineBasicBlock(LLVM_BB); 9227 MF->insert(It, loopMBB); 9228 MF->insert(It, exitMBB); 9229 9230 // Transfer the remainder of BB and its successor edges to exitMBB. 9231 exitMBB->splice(exitMBB->begin(), BB, 9232 std::next(MachineBasicBlock::iterator(MI)), BB->end()); 9233 exitMBB->transferSuccessorsAndUpdatePHIs(BB); 9234 9235 // Load an immediate to varEnd. 9236 unsigned varEnd = MRI.createVirtualRegister(TRC); 9237 if (Subtarget->useMovt()) { 9238 unsigned Vtmp = varEnd; 9239 if ((LoopSize & 0xFFFF0000) != 0) 9240 Vtmp = MRI.createVirtualRegister(TRC); 9241 BuildMI(BB, dl, TII->get(IsThumb ? ARM::t2MOVi16 : ARM::MOVi16), Vtmp) 9242 .addImm(LoopSize & 0xFFFF) 9243 .add(predOps(ARMCC::AL)); 9244 9245 if ((LoopSize & 0xFFFF0000) != 0) 9246 BuildMI(BB, dl, TII->get(IsThumb ? ARM::t2MOVTi16 : ARM::MOVTi16), varEnd) 9247 .addReg(Vtmp) 9248 .addImm(LoopSize >> 16) 9249 .add(predOps(ARMCC::AL)); 9250 } else { 9251 MachineConstantPool *ConstantPool = MF->getConstantPool(); 9252 Type *Int32Ty = Type::getInt32Ty(MF->getFunction().getContext()); 9253 const Constant *C = ConstantInt::get(Int32Ty, LoopSize); 9254 9255 // MachineConstantPool wants an explicit alignment. 9256 unsigned Align = MF->getDataLayout().getPrefTypeAlignment(Int32Ty); 9257 if (Align == 0) 9258 Align = MF->getDataLayout().getTypeAllocSize(C->getType()); 9259 unsigned Idx = ConstantPool->getConstantPoolIndex(C, Align); 9260 MachineMemOperand *CPMMO = 9261 MF->getMachineMemOperand(MachinePointerInfo::getConstantPool(*MF), 9262 MachineMemOperand::MOLoad, 4, 4); 9263 9264 if (IsThumb) 9265 BuildMI(*BB, MI, dl, TII->get(ARM::tLDRpci)) 9266 .addReg(varEnd, RegState::Define) 9267 .addConstantPoolIndex(Idx) 9268 .add(predOps(ARMCC::AL)) 9269 .addMemOperand(CPMMO); 9270 else 9271 BuildMI(*BB, MI, dl, TII->get(ARM::LDRcp)) 9272 .addReg(varEnd, RegState::Define) 9273 .addConstantPoolIndex(Idx) 9274 .addImm(0) 9275 .add(predOps(ARMCC::AL)) 9276 .addMemOperand(CPMMO); 9277 } 9278 BB->addSuccessor(loopMBB); 9279 9280 // Generate the loop body: 9281 // varPhi = PHI(varLoop, varEnd) 9282 // srcPhi = PHI(srcLoop, src) 9283 // destPhi = PHI(destLoop, dst) 9284 MachineBasicBlock *entryBB = BB; 9285 BB = loopMBB; 9286 unsigned varLoop = MRI.createVirtualRegister(TRC); 9287 unsigned varPhi = MRI.createVirtualRegister(TRC); 9288 unsigned srcLoop = MRI.createVirtualRegister(TRC); 9289 unsigned srcPhi = MRI.createVirtualRegister(TRC); 9290 unsigned destLoop = MRI.createVirtualRegister(TRC); 9291 unsigned destPhi = MRI.createVirtualRegister(TRC); 9292 9293 BuildMI(*BB, BB->begin(), dl, TII->get(ARM::PHI), varPhi) 9294 .addReg(varLoop).addMBB(loopMBB) 9295 .addReg(varEnd).addMBB(entryBB); 9296 BuildMI(BB, dl, TII->get(ARM::PHI), srcPhi) 9297 .addReg(srcLoop).addMBB(loopMBB) 9298 .addReg(src).addMBB(entryBB); 9299 BuildMI(BB, dl, TII->get(ARM::PHI), destPhi) 9300 .addReg(destLoop).addMBB(loopMBB) 9301 .addReg(dest).addMBB(entryBB); 9302 9303 // [scratch, srcLoop] = LDR_POST(srcPhi, UnitSize) 9304 // [destLoop] = STR_POST(scratch, destPhi, UnitSiz) 9305 unsigned scratch = MRI.createVirtualRegister(IsNeon ? VecTRC : TRC); 9306 emitPostLd(BB, BB->end(), TII, dl, UnitSize, scratch, srcPhi, srcLoop, 9307 IsThumb1, IsThumb2); 9308 emitPostSt(BB, BB->end(), TII, dl, UnitSize, scratch, destPhi, destLoop, 9309 IsThumb1, IsThumb2); 9310 9311 // Decrement loop variable by UnitSize. 9312 if (IsThumb1) { 9313 BuildMI(*BB, BB->end(), dl, TII->get(ARM::tSUBi8), varLoop) 9314 .add(t1CondCodeOp()) 9315 .addReg(varPhi) 9316 .addImm(UnitSize) 9317 .add(predOps(ARMCC::AL)); 9318 } else { 9319 MachineInstrBuilder MIB = 9320 BuildMI(*BB, BB->end(), dl, 9321 TII->get(IsThumb2 ? ARM::t2SUBri : ARM::SUBri), varLoop); 9322 MIB.addReg(varPhi) 9323 .addImm(UnitSize) 9324 .add(predOps(ARMCC::AL)) 9325 .add(condCodeOp()); 9326 MIB->getOperand(5).setReg(ARM::CPSR); 9327 MIB->getOperand(5).setIsDef(true); 9328 } 9329 BuildMI(*BB, BB->end(), dl, 9330 TII->get(IsThumb1 ? ARM::tBcc : IsThumb2 ? ARM::t2Bcc : ARM::Bcc)) 9331 .addMBB(loopMBB).addImm(ARMCC::NE).addReg(ARM::CPSR); 9332 9333 // loopMBB can loop back to loopMBB or fall through to exitMBB. 9334 BB->addSuccessor(loopMBB); 9335 BB->addSuccessor(exitMBB); 9336 9337 // Add epilogue to handle BytesLeft. 9338 BB = exitMBB; 9339 auto StartOfExit = exitMBB->begin(); 9340 9341 // [scratch, srcOut] = LDRB_POST(srcLoop, 1) 9342 // [destOut] = STRB_POST(scratch, destLoop, 1) 9343 unsigned srcIn = srcLoop; 9344 unsigned destIn = destLoop; 9345 for (unsigned i = 0; i < BytesLeft; i++) { 9346 unsigned srcOut = MRI.createVirtualRegister(TRC); 9347 unsigned destOut = MRI.createVirtualRegister(TRC); 9348 unsigned scratch = MRI.createVirtualRegister(TRC); 9349 emitPostLd(BB, StartOfExit, TII, dl, 1, scratch, srcIn, srcOut, 9350 IsThumb1, IsThumb2); 9351 emitPostSt(BB, StartOfExit, TII, dl, 1, scratch, destIn, destOut, 9352 IsThumb1, IsThumb2); 9353 srcIn = srcOut; 9354 destIn = destOut; 9355 } 9356 9357 MI.eraseFromParent(); // The instruction is gone now. 9358 return BB; 9359 } 9360 9361 MachineBasicBlock * 9362 ARMTargetLowering::EmitLowered__chkstk(MachineInstr &MI, 9363 MachineBasicBlock *MBB) const { 9364 const TargetMachine &TM = getTargetMachine(); 9365 const TargetInstrInfo &TII = *Subtarget->getInstrInfo(); 9366 DebugLoc DL = MI.getDebugLoc(); 9367 9368 assert(Subtarget->isTargetWindows() && 9369 "__chkstk is only supported on Windows"); 9370 assert(Subtarget->isThumb2() && "Windows on ARM requires Thumb-2 mode"); 9371 9372 // __chkstk takes the number of words to allocate on the stack in R4, and 9373 // returns the stack adjustment in number of bytes in R4. This will not 9374 // clober any other registers (other than the obvious lr). 9375 // 9376 // Although, technically, IP should be considered a register which may be 9377 // clobbered, the call itself will not touch it. Windows on ARM is a pure 9378 // thumb-2 environment, so there is no interworking required. As a result, we 9379 // do not expect a veneer to be emitted by the linker, clobbering IP. 9380 // 9381 // Each module receives its own copy of __chkstk, so no import thunk is 9382 // required, again, ensuring that IP is not clobbered. 9383 // 9384 // Finally, although some linkers may theoretically provide a trampoline for 9385 // out of range calls (which is quite common due to a 32M range limitation of 9386 // branches for Thumb), we can generate the long-call version via 9387 // -mcmodel=large, alleviating the need for the trampoline which may clobber 9388 // IP. 9389 9390 switch (TM.getCodeModel()) { 9391 case CodeModel::Tiny: 9392 llvm_unreachable("Tiny code model not available on ARM."); 9393 case CodeModel::Small: 9394 case CodeModel::Medium: 9395 case CodeModel::Kernel: 9396 BuildMI(*MBB, MI, DL, TII.get(ARM::tBL)) 9397 .add(predOps(ARMCC::AL)) 9398 .addExternalSymbol("__chkstk") 9399 .addReg(ARM::R4, RegState::Implicit | RegState::Kill) 9400 .addReg(ARM::R4, RegState::Implicit | RegState::Define) 9401 .addReg(ARM::R12, 9402 RegState::Implicit | RegState::Define | RegState::Dead) 9403 .addReg(ARM::CPSR, 9404 RegState::Implicit | RegState::Define | RegState::Dead); 9405 break; 9406 case CodeModel::Large: { 9407 MachineRegisterInfo &MRI = MBB->getParent()->getRegInfo(); 9408 unsigned Reg = MRI.createVirtualRegister(&ARM::rGPRRegClass); 9409 9410 BuildMI(*MBB, MI, DL, TII.get(ARM::t2MOVi32imm), Reg) 9411 .addExternalSymbol("__chkstk"); 9412 BuildMI(*MBB, MI, DL, TII.get(ARM::tBLXr)) 9413 .add(predOps(ARMCC::AL)) 9414 .addReg(Reg, RegState::Kill) 9415 .addReg(ARM::R4, RegState::Implicit | RegState::Kill) 9416 .addReg(ARM::R4, RegState::Implicit | RegState::Define) 9417 .addReg(ARM::R12, 9418 RegState::Implicit | RegState::Define | RegState::Dead) 9419 .addReg(ARM::CPSR, 9420 RegState::Implicit | RegState::Define | RegState::Dead); 9421 break; 9422 } 9423 } 9424 9425 BuildMI(*MBB, MI, DL, TII.get(ARM::t2SUBrr), ARM::SP) 9426 .addReg(ARM::SP, RegState::Kill) 9427 .addReg(ARM::R4, RegState::Kill) 9428 .setMIFlags(MachineInstr::FrameSetup) 9429 .add(predOps(ARMCC::AL)) 9430 .add(condCodeOp()); 9431 9432 MI.eraseFromParent(); 9433 return MBB; 9434 } 9435 9436 MachineBasicBlock * 9437 ARMTargetLowering::EmitLowered__dbzchk(MachineInstr &MI, 9438 MachineBasicBlock *MBB) const { 9439 DebugLoc DL = MI.getDebugLoc(); 9440 MachineFunction *MF = MBB->getParent(); 9441 const TargetInstrInfo *TII = Subtarget->getInstrInfo(); 9442 9443 MachineBasicBlock *ContBB = MF->CreateMachineBasicBlock(); 9444 MF->insert(++MBB->getIterator(), ContBB); 9445 ContBB->splice(ContBB->begin(), MBB, 9446 std::next(MachineBasicBlock::iterator(MI)), MBB->end()); 9447 ContBB->transferSuccessorsAndUpdatePHIs(MBB); 9448 MBB->addSuccessor(ContBB); 9449 9450 MachineBasicBlock *TrapBB = MF->CreateMachineBasicBlock(); 9451 BuildMI(TrapBB, DL, TII->get(ARM::t__brkdiv0)); 9452 MF->push_back(TrapBB); 9453 MBB->addSuccessor(TrapBB); 9454 9455 BuildMI(*MBB, MI, DL, TII->get(ARM::tCMPi8)) 9456 .addReg(MI.getOperand(0).getReg()) 9457 .addImm(0) 9458 .add(predOps(ARMCC::AL)); 9459 BuildMI(*MBB, MI, DL, TII->get(ARM::t2Bcc)) 9460 .addMBB(TrapBB) 9461 .addImm(ARMCC::EQ) 9462 .addReg(ARM::CPSR); 9463 9464 MI.eraseFromParent(); 9465 return ContBB; 9466 } 9467 9468 // The CPSR operand of SelectItr might be missing a kill marker 9469 // because there were multiple uses of CPSR, and ISel didn't know 9470 // which to mark. Figure out whether SelectItr should have had a 9471 // kill marker, and set it if it should. Returns the correct kill 9472 // marker value. 9473 static bool checkAndUpdateCPSRKill(MachineBasicBlock::iterator SelectItr, 9474 MachineBasicBlock* BB, 9475 const TargetRegisterInfo* TRI) { 9476 // Scan forward through BB for a use/def of CPSR. 9477 MachineBasicBlock::iterator miI(std::next(SelectItr)); 9478 for (MachineBasicBlock::iterator miE = BB->end(); miI != miE; ++miI) { 9479 const MachineInstr& mi = *miI; 9480 if (mi.readsRegister(ARM::CPSR)) 9481 return false; 9482 if (mi.definesRegister(ARM::CPSR)) 9483 break; // Should have kill-flag - update below. 9484 } 9485 9486 // If we hit the end of the block, check whether CPSR is live into a 9487 // successor. 9488 if (miI == BB->end()) { 9489 for (MachineBasicBlock::succ_iterator sItr = BB->succ_begin(), 9490 sEnd = BB->succ_end(); 9491 sItr != sEnd; ++sItr) { 9492 MachineBasicBlock* succ = *sItr; 9493 if (succ->isLiveIn(ARM::CPSR)) 9494 return false; 9495 } 9496 } 9497 9498 // We found a def, or hit the end of the basic block and CPSR wasn't live 9499 // out. SelectMI should have a kill flag on CPSR. 9500 SelectItr->addRegisterKilled(ARM::CPSR, TRI); 9501 return true; 9502 } 9503 9504 MachineBasicBlock * 9505 ARMTargetLowering::EmitInstrWithCustomInserter(MachineInstr &MI, 9506 MachineBasicBlock *BB) const { 9507 const TargetInstrInfo *TII = Subtarget->getInstrInfo(); 9508 DebugLoc dl = MI.getDebugLoc(); 9509 bool isThumb2 = Subtarget->isThumb2(); 9510 switch (MI.getOpcode()) { 9511 default: { 9512 MI.print(errs()); 9513 llvm_unreachable("Unexpected instr type to insert"); 9514 } 9515 9516 // Thumb1 post-indexed loads are really just single-register LDMs. 9517 case ARM::tLDR_postidx: { 9518 MachineOperand Def(MI.getOperand(1)); 9519 BuildMI(*BB, MI, dl, TII->get(ARM::tLDMIA_UPD)) 9520 .add(Def) // Rn_wb 9521 .add(MI.getOperand(2)) // Rn 9522 .add(MI.getOperand(3)) // PredImm 9523 .add(MI.getOperand(4)) // PredReg 9524 .add(MI.getOperand(0)) // Rt 9525 .cloneMemRefs(MI); 9526 MI.eraseFromParent(); 9527 return BB; 9528 } 9529 9530 // The Thumb2 pre-indexed stores have the same MI operands, they just 9531 // define them differently in the .td files from the isel patterns, so 9532 // they need pseudos. 9533 case ARM::t2STR_preidx: 9534 MI.setDesc(TII->get(ARM::t2STR_PRE)); 9535 return BB; 9536 case ARM::t2STRB_preidx: 9537 MI.setDesc(TII->get(ARM::t2STRB_PRE)); 9538 return BB; 9539 case ARM::t2STRH_preidx: 9540 MI.setDesc(TII->get(ARM::t2STRH_PRE)); 9541 return BB; 9542 9543 case ARM::STRi_preidx: 9544 case ARM::STRBi_preidx: { 9545 unsigned NewOpc = MI.getOpcode() == ARM::STRi_preidx ? ARM::STR_PRE_IMM 9546 : ARM::STRB_PRE_IMM; 9547 // Decode the offset. 9548 unsigned Offset = MI.getOperand(4).getImm(); 9549 bool isSub = ARM_AM::getAM2Op(Offset) == ARM_AM::sub; 9550 Offset = ARM_AM::getAM2Offset(Offset); 9551 if (isSub) 9552 Offset = -Offset; 9553 9554 MachineMemOperand *MMO = *MI.memoperands_begin(); 9555 BuildMI(*BB, MI, dl, TII->get(NewOpc)) 9556 .add(MI.getOperand(0)) // Rn_wb 9557 .add(MI.getOperand(1)) // Rt 9558 .add(MI.getOperand(2)) // Rn 9559 .addImm(Offset) // offset (skip GPR==zero_reg) 9560 .add(MI.getOperand(5)) // pred 9561 .add(MI.getOperand(6)) 9562 .addMemOperand(MMO); 9563 MI.eraseFromParent(); 9564 return BB; 9565 } 9566 case ARM::STRr_preidx: 9567 case ARM::STRBr_preidx: 9568 case ARM::STRH_preidx: { 9569 unsigned NewOpc; 9570 switch (MI.getOpcode()) { 9571 default: llvm_unreachable("unexpected opcode!"); 9572 case ARM::STRr_preidx: NewOpc = ARM::STR_PRE_REG; break; 9573 case ARM::STRBr_preidx: NewOpc = ARM::STRB_PRE_REG; break; 9574 case ARM::STRH_preidx: NewOpc = ARM::STRH_PRE; break; 9575 } 9576 MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(NewOpc)); 9577 for (unsigned i = 0; i < MI.getNumOperands(); ++i) 9578 MIB.add(MI.getOperand(i)); 9579 MI.eraseFromParent(); 9580 return BB; 9581 } 9582 9583 case ARM::tMOVCCr_pseudo: { 9584 // To "insert" a SELECT_CC instruction, we actually have to insert the 9585 // diamond control-flow pattern. The incoming instruction knows the 9586 // destination vreg to set, the condition code register to branch on, the 9587 // true/false values to select between, and a branch opcode to use. 9588 const BasicBlock *LLVM_BB = BB->getBasicBlock(); 9589 MachineFunction::iterator It = ++BB->getIterator(); 9590 9591 // thisMBB: 9592 // ... 9593 // TrueVal = ... 9594 // cmpTY ccX, r1, r2 9595 // bCC copy1MBB 9596 // fallthrough --> copy0MBB 9597 MachineBasicBlock *thisMBB = BB; 9598 MachineFunction *F = BB->getParent(); 9599 MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB); 9600 MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB); 9601 F->insert(It, copy0MBB); 9602 F->insert(It, sinkMBB); 9603 9604 // Check whether CPSR is live past the tMOVCCr_pseudo. 9605 const TargetRegisterInfo *TRI = Subtarget->getRegisterInfo(); 9606 if (!MI.killsRegister(ARM::CPSR) && 9607 !checkAndUpdateCPSRKill(MI, thisMBB, TRI)) { 9608 copy0MBB->addLiveIn(ARM::CPSR); 9609 sinkMBB->addLiveIn(ARM::CPSR); 9610 } 9611 9612 // Transfer the remainder of BB and its successor edges to sinkMBB. 9613 sinkMBB->splice(sinkMBB->begin(), BB, 9614 std::next(MachineBasicBlock::iterator(MI)), BB->end()); 9615 sinkMBB->transferSuccessorsAndUpdatePHIs(BB); 9616 9617 BB->addSuccessor(copy0MBB); 9618 BB->addSuccessor(sinkMBB); 9619 9620 BuildMI(BB, dl, TII->get(ARM::tBcc)) 9621 .addMBB(sinkMBB) 9622 .addImm(MI.getOperand(3).getImm()) 9623 .addReg(MI.getOperand(4).getReg()); 9624 9625 // copy0MBB: 9626 // %FalseValue = ... 9627 // # fallthrough to sinkMBB 9628 BB = copy0MBB; 9629 9630 // Update machine-CFG edges 9631 BB->addSuccessor(sinkMBB); 9632 9633 // sinkMBB: 9634 // %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ] 9635 // ... 9636 BB = sinkMBB; 9637 BuildMI(*BB, BB->begin(), dl, TII->get(ARM::PHI), MI.getOperand(0).getReg()) 9638 .addReg(MI.getOperand(1).getReg()) 9639 .addMBB(copy0MBB) 9640 .addReg(MI.getOperand(2).getReg()) 9641 .addMBB(thisMBB); 9642 9643 MI.eraseFromParent(); // The pseudo instruction is gone now. 9644 return BB; 9645 } 9646 9647 case ARM::BCCi64: 9648 case ARM::BCCZi64: { 9649 // If there is an unconditional branch to the other successor, remove it. 9650 BB->erase(std::next(MachineBasicBlock::iterator(MI)), BB->end()); 9651 9652 // Compare both parts that make up the double comparison separately for 9653 // equality. 9654 bool RHSisZero = MI.getOpcode() == ARM::BCCZi64; 9655 9656 unsigned LHS1 = MI.getOperand(1).getReg(); 9657 unsigned LHS2 = MI.getOperand(2).getReg(); 9658 if (RHSisZero) { 9659 BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri)) 9660 .addReg(LHS1) 9661 .addImm(0) 9662 .add(predOps(ARMCC::AL)); 9663 BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri)) 9664 .addReg(LHS2).addImm(0) 9665 .addImm(ARMCC::EQ).addReg(ARM::CPSR); 9666 } else { 9667 unsigned RHS1 = MI.getOperand(3).getReg(); 9668 unsigned RHS2 = MI.getOperand(4).getReg(); 9669 BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPrr : ARM::CMPrr)) 9670 .addReg(LHS1) 9671 .addReg(RHS1) 9672 .add(predOps(ARMCC::AL)); 9673 BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPrr : ARM::CMPrr)) 9674 .addReg(LHS2).addReg(RHS2) 9675 .addImm(ARMCC::EQ).addReg(ARM::CPSR); 9676 } 9677 9678 MachineBasicBlock *destMBB = MI.getOperand(RHSisZero ? 3 : 5).getMBB(); 9679 MachineBasicBlock *exitMBB = OtherSucc(BB, destMBB); 9680 if (MI.getOperand(0).getImm() == ARMCC::NE) 9681 std::swap(destMBB, exitMBB); 9682 9683 BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc)) 9684 .addMBB(destMBB).addImm(ARMCC::EQ).addReg(ARM::CPSR); 9685 if (isThumb2) 9686 BuildMI(BB, dl, TII->get(ARM::t2B)) 9687 .addMBB(exitMBB) 9688 .add(predOps(ARMCC::AL)); 9689 else 9690 BuildMI(BB, dl, TII->get(ARM::B)) .addMBB(exitMBB); 9691 9692 MI.eraseFromParent(); // The pseudo instruction is gone now. 9693 return BB; 9694 } 9695 9696 case ARM::Int_eh_sjlj_setjmp: 9697 case ARM::Int_eh_sjlj_setjmp_nofp: 9698 case ARM::tInt_eh_sjlj_setjmp: 9699 case ARM::t2Int_eh_sjlj_setjmp: 9700 case ARM::t2Int_eh_sjlj_setjmp_nofp: 9701 return BB; 9702 9703 case ARM::Int_eh_sjlj_setup_dispatch: 9704 EmitSjLjDispatchBlock(MI, BB); 9705 return BB; 9706 9707 case ARM::ABS: 9708 case ARM::t2ABS: { 9709 // To insert an ABS instruction, we have to insert the 9710 // diamond control-flow pattern. The incoming instruction knows the 9711 // source vreg to test against 0, the destination vreg to set, 9712 // the condition code register to branch on, the 9713 // true/false values to select between, and a branch opcode to use. 9714 // It transforms 9715 // V1 = ABS V0 9716 // into 9717 // V2 = MOVS V0 9718 // BCC (branch to SinkBB if V0 >= 0) 9719 // RSBBB: V3 = RSBri V2, 0 (compute ABS if V2 < 0) 9720 // SinkBB: V1 = PHI(V2, V3) 9721 const BasicBlock *LLVM_BB = BB->getBasicBlock(); 9722 MachineFunction::iterator BBI = ++BB->getIterator(); 9723 MachineFunction *Fn = BB->getParent(); 9724 MachineBasicBlock *RSBBB = Fn->CreateMachineBasicBlock(LLVM_BB); 9725 MachineBasicBlock *SinkBB = Fn->CreateMachineBasicBlock(LLVM_BB); 9726 Fn->insert(BBI, RSBBB); 9727 Fn->insert(BBI, SinkBB); 9728 9729 unsigned int ABSSrcReg = MI.getOperand(1).getReg(); 9730 unsigned int ABSDstReg = MI.getOperand(0).getReg(); 9731 bool ABSSrcKIll = MI.getOperand(1).isKill(); 9732 bool isThumb2 = Subtarget->isThumb2(); 9733 MachineRegisterInfo &MRI = Fn->getRegInfo(); 9734 // In Thumb mode S must not be specified if source register is the SP or 9735 // PC and if destination register is the SP, so restrict register class 9736 unsigned NewRsbDstReg = 9737 MRI.createVirtualRegister(isThumb2 ? &ARM::rGPRRegClass : &ARM::GPRRegClass); 9738 9739 // Transfer the remainder of BB and its successor edges to sinkMBB. 9740 SinkBB->splice(SinkBB->begin(), BB, 9741 std::next(MachineBasicBlock::iterator(MI)), BB->end()); 9742 SinkBB->transferSuccessorsAndUpdatePHIs(BB); 9743 9744 BB->addSuccessor(RSBBB); 9745 BB->addSuccessor(SinkBB); 9746 9747 // fall through to SinkMBB 9748 RSBBB->addSuccessor(SinkBB); 9749 9750 // insert a cmp at the end of BB 9751 BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri)) 9752 .addReg(ABSSrcReg) 9753 .addImm(0) 9754 .add(predOps(ARMCC::AL)); 9755 9756 // insert a bcc with opposite CC to ARMCC::MI at the end of BB 9757 BuildMI(BB, dl, 9758 TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc)).addMBB(SinkBB) 9759 .addImm(ARMCC::getOppositeCondition(ARMCC::MI)).addReg(ARM::CPSR); 9760 9761 // insert rsbri in RSBBB 9762 // Note: BCC and rsbri will be converted into predicated rsbmi 9763 // by if-conversion pass 9764 BuildMI(*RSBBB, RSBBB->begin(), dl, 9765 TII->get(isThumb2 ? ARM::t2RSBri : ARM::RSBri), NewRsbDstReg) 9766 .addReg(ABSSrcReg, ABSSrcKIll ? RegState::Kill : 0) 9767 .addImm(0) 9768 .add(predOps(ARMCC::AL)) 9769 .add(condCodeOp()); 9770 9771 // insert PHI in SinkBB, 9772 // reuse ABSDstReg to not change uses of ABS instruction 9773 BuildMI(*SinkBB, SinkBB->begin(), dl, 9774 TII->get(ARM::PHI), ABSDstReg) 9775 .addReg(NewRsbDstReg).addMBB(RSBBB) 9776 .addReg(ABSSrcReg).addMBB(BB); 9777 9778 // remove ABS instruction 9779 MI.eraseFromParent(); 9780 9781 // return last added BB 9782 return SinkBB; 9783 } 9784 case ARM::COPY_STRUCT_BYVAL_I32: 9785 ++NumLoopByVals; 9786 return EmitStructByval(MI, BB); 9787 case ARM::WIN__CHKSTK: 9788 return EmitLowered__chkstk(MI, BB); 9789 case ARM::WIN__DBZCHK: 9790 return EmitLowered__dbzchk(MI, BB); 9791 } 9792 } 9793 9794 /// Attaches vregs to MEMCPY that it will use as scratch registers 9795 /// when it is expanded into LDM/STM. This is done as a post-isel lowering 9796 /// instead of as a custom inserter because we need the use list from the SDNode. 9797 static void attachMEMCPYScratchRegs(const ARMSubtarget *Subtarget, 9798 MachineInstr &MI, const SDNode *Node) { 9799 bool isThumb1 = Subtarget->isThumb1Only(); 9800 9801 DebugLoc DL = MI.getDebugLoc(); 9802 MachineFunction *MF = MI.getParent()->getParent(); 9803 MachineRegisterInfo &MRI = MF->getRegInfo(); 9804 MachineInstrBuilder MIB(*MF, MI); 9805 9806 // If the new dst/src is unused mark it as dead. 9807 if (!Node->hasAnyUseOfValue(0)) { 9808 MI.getOperand(0).setIsDead(true); 9809 } 9810 if (!Node->hasAnyUseOfValue(1)) { 9811 MI.getOperand(1).setIsDead(true); 9812 } 9813 9814 // The MEMCPY both defines and kills the scratch registers. 9815 for (unsigned I = 0; I != MI.getOperand(4).getImm(); ++I) { 9816 unsigned TmpReg = MRI.createVirtualRegister(isThumb1 ? &ARM::tGPRRegClass 9817 : &ARM::GPRRegClass); 9818 MIB.addReg(TmpReg, RegState::Define|RegState::Dead); 9819 } 9820 } 9821 9822 void ARMTargetLowering::AdjustInstrPostInstrSelection(MachineInstr &MI, 9823 SDNode *Node) const { 9824 if (MI.getOpcode() == ARM::MEMCPY) { 9825 attachMEMCPYScratchRegs(Subtarget, MI, Node); 9826 return; 9827 } 9828 9829 const MCInstrDesc *MCID = &MI.getDesc(); 9830 // Adjust potentially 's' setting instructions after isel, i.e. ADC, SBC, RSB, 9831 // RSC. Coming out of isel, they have an implicit CPSR def, but the optional 9832 // operand is still set to noreg. If needed, set the optional operand's 9833 // register to CPSR, and remove the redundant implicit def. 9834 // 9835 // e.g. ADCS (..., implicit-def CPSR) -> ADC (... opt:def CPSR). 9836 9837 // Rename pseudo opcodes. 9838 unsigned NewOpc = convertAddSubFlagsOpcode(MI.getOpcode()); 9839 unsigned ccOutIdx; 9840 if (NewOpc) { 9841 const ARMBaseInstrInfo *TII = Subtarget->getInstrInfo(); 9842 MCID = &TII->get(NewOpc); 9843 9844 assert(MCID->getNumOperands() == 9845 MI.getDesc().getNumOperands() + 5 - MI.getDesc().getSize() 9846 && "converted opcode should be the same except for cc_out" 9847 " (and, on Thumb1, pred)"); 9848 9849 MI.setDesc(*MCID); 9850 9851 // Add the optional cc_out operand 9852 MI.addOperand(MachineOperand::CreateReg(0, /*isDef=*/true)); 9853 9854 // On Thumb1, move all input operands to the end, then add the predicate 9855 if (Subtarget->isThumb1Only()) { 9856 for (unsigned c = MCID->getNumOperands() - 4; c--;) { 9857 MI.addOperand(MI.getOperand(1)); 9858 MI.RemoveOperand(1); 9859 } 9860 9861 // Restore the ties 9862 for (unsigned i = MI.getNumOperands(); i--;) { 9863 const MachineOperand& op = MI.getOperand(i); 9864 if (op.isReg() && op.isUse()) { 9865 int DefIdx = MCID->getOperandConstraint(i, MCOI::TIED_TO); 9866 if (DefIdx != -1) 9867 MI.tieOperands(DefIdx, i); 9868 } 9869 } 9870 9871 MI.addOperand(MachineOperand::CreateImm(ARMCC::AL)); 9872 MI.addOperand(MachineOperand::CreateReg(0, /*isDef=*/false)); 9873 ccOutIdx = 1; 9874 } else 9875 ccOutIdx = MCID->getNumOperands() - 1; 9876 } else 9877 ccOutIdx = MCID->getNumOperands() - 1; 9878 9879 // Any ARM instruction that sets the 's' bit should specify an optional 9880 // "cc_out" operand in the last operand position. 9881 if (!MI.hasOptionalDef() || !MCID->OpInfo[ccOutIdx].isOptionalDef()) { 9882 assert(!NewOpc && "Optional cc_out operand required"); 9883 return; 9884 } 9885 // Look for an implicit def of CPSR added by MachineInstr ctor. Remove it 9886 // since we already have an optional CPSR def. 9887 bool definesCPSR = false; 9888 bool deadCPSR = false; 9889 for (unsigned i = MCID->getNumOperands(), e = MI.getNumOperands(); i != e; 9890 ++i) { 9891 const MachineOperand &MO = MI.getOperand(i); 9892 if (MO.isReg() && MO.isDef() && MO.getReg() == ARM::CPSR) { 9893 definesCPSR = true; 9894 if (MO.isDead()) 9895 deadCPSR = true; 9896 MI.RemoveOperand(i); 9897 break; 9898 } 9899 } 9900 if (!definesCPSR) { 9901 assert(!NewOpc && "Optional cc_out operand required"); 9902 return; 9903 } 9904 assert(deadCPSR == !Node->hasAnyUseOfValue(1) && "inconsistent dead flag"); 9905 if (deadCPSR) { 9906 assert(!MI.getOperand(ccOutIdx).getReg() && 9907 "expect uninitialized optional cc_out operand"); 9908 // Thumb1 instructions must have the S bit even if the CPSR is dead. 9909 if (!Subtarget->isThumb1Only()) 9910 return; 9911 } 9912 9913 // If this instruction was defined with an optional CPSR def and its dag node 9914 // had a live implicit CPSR def, then activate the optional CPSR def. 9915 MachineOperand &MO = MI.getOperand(ccOutIdx); 9916 MO.setReg(ARM::CPSR); 9917 MO.setIsDef(true); 9918 } 9919 9920 //===----------------------------------------------------------------------===// 9921 // ARM Optimization Hooks 9922 //===----------------------------------------------------------------------===// 9923 9924 // Helper function that checks if N is a null or all ones constant. 9925 static inline bool isZeroOrAllOnes(SDValue N, bool AllOnes) { 9926 return AllOnes ? isAllOnesConstant(N) : isNullConstant(N); 9927 } 9928 9929 // Return true if N is conditionally 0 or all ones. 9930 // Detects these expressions where cc is an i1 value: 9931 // 9932 // (select cc 0, y) [AllOnes=0] 9933 // (select cc y, 0) [AllOnes=0] 9934 // (zext cc) [AllOnes=0] 9935 // (sext cc) [AllOnes=0/1] 9936 // (select cc -1, y) [AllOnes=1] 9937 // (select cc y, -1) [AllOnes=1] 9938 // 9939 // Invert is set when N is the null/all ones constant when CC is false. 9940 // OtherOp is set to the alternative value of N. 9941 static bool isConditionalZeroOrAllOnes(SDNode *N, bool AllOnes, 9942 SDValue &CC, bool &Invert, 9943 SDValue &OtherOp, 9944 SelectionDAG &DAG) { 9945 switch (N->getOpcode()) { 9946 default: return false; 9947 case ISD::SELECT: { 9948 CC = N->getOperand(0); 9949 SDValue N1 = N->getOperand(1); 9950 SDValue N2 = N->getOperand(2); 9951 if (isZeroOrAllOnes(N1, AllOnes)) { 9952 Invert = false; 9953 OtherOp = N2; 9954 return true; 9955 } 9956 if (isZeroOrAllOnes(N2, AllOnes)) { 9957 Invert = true; 9958 OtherOp = N1; 9959 return true; 9960 } 9961 return false; 9962 } 9963 case ISD::ZERO_EXTEND: 9964 // (zext cc) can never be the all ones value. 9965 if (AllOnes) 9966 return false; 9967 LLVM_FALLTHROUGH; 9968 case ISD::SIGN_EXTEND: { 9969 SDLoc dl(N); 9970 EVT VT = N->getValueType(0); 9971 CC = N->getOperand(0); 9972 if (CC.getValueType() != MVT::i1 || CC.getOpcode() != ISD::SETCC) 9973 return false; 9974 Invert = !AllOnes; 9975 if (AllOnes) 9976 // When looking for an AllOnes constant, N is an sext, and the 'other' 9977 // value is 0. 9978 OtherOp = DAG.getConstant(0, dl, VT); 9979 else if (N->getOpcode() == ISD::ZERO_EXTEND) 9980 // When looking for a 0 constant, N can be zext or sext. 9981 OtherOp = DAG.getConstant(1, dl, VT); 9982 else 9983 OtherOp = DAG.getConstant(APInt::getAllOnesValue(VT.getSizeInBits()), dl, 9984 VT); 9985 return true; 9986 } 9987 } 9988 } 9989 9990 // Combine a constant select operand into its use: 9991 // 9992 // (add (select cc, 0, c), x) -> (select cc, x, (add, x, c)) 9993 // (sub x, (select cc, 0, c)) -> (select cc, x, (sub, x, c)) 9994 // (and (select cc, -1, c), x) -> (select cc, x, (and, x, c)) [AllOnes=1] 9995 // (or (select cc, 0, c), x) -> (select cc, x, (or, x, c)) 9996 // (xor (select cc, 0, c), x) -> (select cc, x, (xor, x, c)) 9997 // 9998 // The transform is rejected if the select doesn't have a constant operand that 9999 // is null, or all ones when AllOnes is set. 10000 // 10001 // Also recognize sext/zext from i1: 10002 // 10003 // (add (zext cc), x) -> (select cc (add x, 1), x) 10004 // (add (sext cc), x) -> (select cc (add x, -1), x) 10005 // 10006 // These transformations eventually create predicated instructions. 10007 // 10008 // @param N The node to transform. 10009 // @param Slct The N operand that is a select. 10010 // @param OtherOp The other N operand (x above). 10011 // @param DCI Context. 10012 // @param AllOnes Require the select constant to be all ones instead of null. 10013 // @returns The new node, or SDValue() on failure. 10014 static 10015 SDValue combineSelectAndUse(SDNode *N, SDValue Slct, SDValue OtherOp, 10016 TargetLowering::DAGCombinerInfo &DCI, 10017 bool AllOnes = false) { 10018 SelectionDAG &DAG = DCI.DAG; 10019 EVT VT = N->getValueType(0); 10020 SDValue NonConstantVal; 10021 SDValue CCOp; 10022 bool SwapSelectOps; 10023 if (!isConditionalZeroOrAllOnes(Slct.getNode(), AllOnes, CCOp, SwapSelectOps, 10024 NonConstantVal, DAG)) 10025 return SDValue(); 10026 10027 // Slct is now know to be the desired identity constant when CC is true. 10028 SDValue TrueVal = OtherOp; 10029 SDValue FalseVal = DAG.getNode(N->getOpcode(), SDLoc(N), VT, 10030 OtherOp, NonConstantVal); 10031 // Unless SwapSelectOps says CC should be false. 10032 if (SwapSelectOps) 10033 std::swap(TrueVal, FalseVal); 10034 10035 return DAG.getNode(ISD::SELECT, SDLoc(N), VT, 10036 CCOp, TrueVal, FalseVal); 10037 } 10038 10039 // Attempt combineSelectAndUse on each operand of a commutative operator N. 10040 static 10041 SDValue combineSelectAndUseCommutative(SDNode *N, bool AllOnes, 10042 TargetLowering::DAGCombinerInfo &DCI) { 10043 SDValue N0 = N->getOperand(0); 10044 SDValue N1 = N->getOperand(1); 10045 if (N0.getNode()->hasOneUse()) 10046 if (SDValue Result = combineSelectAndUse(N, N0, N1, DCI, AllOnes)) 10047 return Result; 10048 if (N1.getNode()->hasOneUse()) 10049 if (SDValue Result = combineSelectAndUse(N, N1, N0, DCI, AllOnes)) 10050 return Result; 10051 return SDValue(); 10052 } 10053 10054 static bool IsVUZPShuffleNode(SDNode *N) { 10055 // VUZP shuffle node. 10056 if (N->getOpcode() == ARMISD::VUZP) 10057 return true; 10058 10059 // "VUZP" on i32 is an alias for VTRN. 10060 if (N->getOpcode() == ARMISD::VTRN && N->getValueType(0) == MVT::v2i32) 10061 return true; 10062 10063 return false; 10064 } 10065 10066 static SDValue AddCombineToVPADD(SDNode *N, SDValue N0, SDValue N1, 10067 TargetLowering::DAGCombinerInfo &DCI, 10068 const ARMSubtarget *Subtarget) { 10069 // Look for ADD(VUZP.0, VUZP.1). 10070 if (!IsVUZPShuffleNode(N0.getNode()) || N0.getNode() != N1.getNode() || 10071 N0 == N1) 10072 return SDValue(); 10073 10074 // Make sure the ADD is a 64-bit add; there is no 128-bit VPADD. 10075 if (!N->getValueType(0).is64BitVector()) 10076 return SDValue(); 10077 10078 // Generate vpadd. 10079 SelectionDAG &DAG = DCI.DAG; 10080 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 10081 SDLoc dl(N); 10082 SDNode *Unzip = N0.getNode(); 10083 EVT VT = N->getValueType(0); 10084 10085 SmallVector<SDValue, 8> Ops; 10086 Ops.push_back(DAG.getConstant(Intrinsic::arm_neon_vpadd, dl, 10087 TLI.getPointerTy(DAG.getDataLayout()))); 10088 Ops.push_back(Unzip->getOperand(0)); 10089 Ops.push_back(Unzip->getOperand(1)); 10090 10091 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT, Ops); 10092 } 10093 10094 static SDValue AddCombineVUZPToVPADDL(SDNode *N, SDValue N0, SDValue N1, 10095 TargetLowering::DAGCombinerInfo &DCI, 10096 const ARMSubtarget *Subtarget) { 10097 // Check for two extended operands. 10098 if (!(N0.getOpcode() == ISD::SIGN_EXTEND && 10099 N1.getOpcode() == ISD::SIGN_EXTEND) && 10100 !(N0.getOpcode() == ISD::ZERO_EXTEND && 10101 N1.getOpcode() == ISD::ZERO_EXTEND)) 10102 return SDValue(); 10103 10104 SDValue N00 = N0.getOperand(0); 10105 SDValue N10 = N1.getOperand(0); 10106 10107 // Look for ADD(SEXT(VUZP.0), SEXT(VUZP.1)) 10108 if (!IsVUZPShuffleNode(N00.getNode()) || N00.getNode() != N10.getNode() || 10109 N00 == N10) 10110 return SDValue(); 10111 10112 // We only recognize Q register paddl here; this can't be reached until 10113 // after type legalization. 10114 if (!N00.getValueType().is64BitVector() || 10115 !N0.getValueType().is128BitVector()) 10116 return SDValue(); 10117 10118 // Generate vpaddl. 10119 SelectionDAG &DAG = DCI.DAG; 10120 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 10121 SDLoc dl(N); 10122 EVT VT = N->getValueType(0); 10123 10124 SmallVector<SDValue, 8> Ops; 10125 // Form vpaddl.sN or vpaddl.uN depending on the kind of extension. 10126 unsigned Opcode; 10127 if (N0.getOpcode() == ISD::SIGN_EXTEND) 10128 Opcode = Intrinsic::arm_neon_vpaddls; 10129 else 10130 Opcode = Intrinsic::arm_neon_vpaddlu; 10131 Ops.push_back(DAG.getConstant(Opcode, dl, 10132 TLI.getPointerTy(DAG.getDataLayout()))); 10133 EVT ElemTy = N00.getValueType().getVectorElementType(); 10134 unsigned NumElts = VT.getVectorNumElements(); 10135 EVT ConcatVT = EVT::getVectorVT(*DAG.getContext(), ElemTy, NumElts * 2); 10136 SDValue Concat = DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), ConcatVT, 10137 N00.getOperand(0), N00.getOperand(1)); 10138 Ops.push_back(Concat); 10139 10140 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT, Ops); 10141 } 10142 10143 // FIXME: This function shouldn't be necessary; if we lower BUILD_VECTOR in 10144 // an appropriate manner, we end up with ADD(VUZP(ZEXT(N))), which is 10145 // much easier to match. 10146 static SDValue 10147 AddCombineBUILD_VECTORToVPADDL(SDNode *N, SDValue N0, SDValue N1, 10148 TargetLowering::DAGCombinerInfo &DCI, 10149 const ARMSubtarget *Subtarget) { 10150 // Only perform optimization if after legalize, and if NEON is available. We 10151 // also expected both operands to be BUILD_VECTORs. 10152 if (DCI.isBeforeLegalize() || !Subtarget->hasNEON() 10153 || N0.getOpcode() != ISD::BUILD_VECTOR 10154 || N1.getOpcode() != ISD::BUILD_VECTOR) 10155 return SDValue(); 10156 10157 // Check output type since VPADDL operand elements can only be 8, 16, or 32. 10158 EVT VT = N->getValueType(0); 10159 if (!VT.isInteger() || VT.getVectorElementType() == MVT::i64) 10160 return SDValue(); 10161 10162 // Check that the vector operands are of the right form. 10163 // N0 and N1 are BUILD_VECTOR nodes with N number of EXTRACT_VECTOR 10164 // operands, where N is the size of the formed vector. 10165 // Each EXTRACT_VECTOR should have the same input vector and odd or even 10166 // index such that we have a pair wise add pattern. 10167 10168 // Grab the vector that all EXTRACT_VECTOR nodes should be referencing. 10169 if (N0->getOperand(0)->getOpcode() != ISD::EXTRACT_VECTOR_ELT) 10170 return SDValue(); 10171 SDValue Vec = N0->getOperand(0)->getOperand(0); 10172 SDNode *V = Vec.getNode(); 10173 unsigned nextIndex = 0; 10174 10175 // For each operands to the ADD which are BUILD_VECTORs, 10176 // check to see if each of their operands are an EXTRACT_VECTOR with 10177 // the same vector and appropriate index. 10178 for (unsigned i = 0, e = N0->getNumOperands(); i != e; ++i) { 10179 if (N0->getOperand(i)->getOpcode() == ISD::EXTRACT_VECTOR_ELT 10180 && N1->getOperand(i)->getOpcode() == ISD::EXTRACT_VECTOR_ELT) { 10181 10182 SDValue ExtVec0 = N0->getOperand(i); 10183 SDValue ExtVec1 = N1->getOperand(i); 10184 10185 // First operand is the vector, verify its the same. 10186 if (V != ExtVec0->getOperand(0).getNode() || 10187 V != ExtVec1->getOperand(0).getNode()) 10188 return SDValue(); 10189 10190 // Second is the constant, verify its correct. 10191 ConstantSDNode *C0 = dyn_cast<ConstantSDNode>(ExtVec0->getOperand(1)); 10192 ConstantSDNode *C1 = dyn_cast<ConstantSDNode>(ExtVec1->getOperand(1)); 10193 10194 // For the constant, we want to see all the even or all the odd. 10195 if (!C0 || !C1 || C0->getZExtValue() != nextIndex 10196 || C1->getZExtValue() != nextIndex+1) 10197 return SDValue(); 10198 10199 // Increment index. 10200 nextIndex+=2; 10201 } else 10202 return SDValue(); 10203 } 10204 10205 // Don't generate vpaddl+vmovn; we'll match it to vpadd later. Also make sure 10206 // we're using the entire input vector, otherwise there's a size/legality 10207 // mismatch somewhere. 10208 if (nextIndex != Vec.getValueType().getVectorNumElements() || 10209 Vec.getValueType().getVectorElementType() == VT.getVectorElementType()) 10210 return SDValue(); 10211 10212 // Create VPADDL node. 10213 SelectionDAG &DAG = DCI.DAG; 10214 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 10215 10216 SDLoc dl(N); 10217 10218 // Build operand list. 10219 SmallVector<SDValue, 8> Ops; 10220 Ops.push_back(DAG.getConstant(Intrinsic::arm_neon_vpaddls, dl, 10221 TLI.getPointerTy(DAG.getDataLayout()))); 10222 10223 // Input is the vector. 10224 Ops.push_back(Vec); 10225 10226 // Get widened type and narrowed type. 10227 MVT widenType; 10228 unsigned numElem = VT.getVectorNumElements(); 10229 10230 EVT inputLaneType = Vec.getValueType().getVectorElementType(); 10231 switch (inputLaneType.getSimpleVT().SimpleTy) { 10232 case MVT::i8: widenType = MVT::getVectorVT(MVT::i16, numElem); break; 10233 case MVT::i16: widenType = MVT::getVectorVT(MVT::i32, numElem); break; 10234 case MVT::i32: widenType = MVT::getVectorVT(MVT::i64, numElem); break; 10235 default: 10236 llvm_unreachable("Invalid vector element type for padd optimization."); 10237 } 10238 10239 SDValue tmp = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, widenType, Ops); 10240 unsigned ExtOp = VT.bitsGT(tmp.getValueType()) ? ISD::ANY_EXTEND : ISD::TRUNCATE; 10241 return DAG.getNode(ExtOp, dl, VT, tmp); 10242 } 10243 10244 static SDValue findMUL_LOHI(SDValue V) { 10245 if (V->getOpcode() == ISD::UMUL_LOHI || 10246 V->getOpcode() == ISD::SMUL_LOHI) 10247 return V; 10248 return SDValue(); 10249 } 10250 10251 static SDValue AddCombineTo64BitSMLAL16(SDNode *AddcNode, SDNode *AddeNode, 10252 TargetLowering::DAGCombinerInfo &DCI, 10253 const ARMSubtarget *Subtarget) { 10254 if (Subtarget->isThumb()) { 10255 if (!Subtarget->hasDSP()) 10256 return SDValue(); 10257 } else if (!Subtarget->hasV5TEOps()) 10258 return SDValue(); 10259 10260 // SMLALBB, SMLALBT, SMLALTB, SMLALTT multiply two 16-bit values and 10261 // accumulates the product into a 64-bit value. The 16-bit values will 10262 // be sign extended somehow or SRA'd into 32-bit values 10263 // (addc (adde (mul 16bit, 16bit), lo), hi) 10264 SDValue Mul = AddcNode->getOperand(0); 10265 SDValue Lo = AddcNode->getOperand(1); 10266 if (Mul.getOpcode() != ISD::MUL) { 10267 Lo = AddcNode->getOperand(0); 10268 Mul = AddcNode->getOperand(1); 10269 if (Mul.getOpcode() != ISD::MUL) 10270 return SDValue(); 10271 } 10272 10273 SDValue SRA = AddeNode->getOperand(0); 10274 SDValue Hi = AddeNode->getOperand(1); 10275 if (SRA.getOpcode() != ISD::SRA) { 10276 SRA = AddeNode->getOperand(1); 10277 Hi = AddeNode->getOperand(0); 10278 if (SRA.getOpcode() != ISD::SRA) 10279 return SDValue(); 10280 } 10281 if (auto Const = dyn_cast<ConstantSDNode>(SRA.getOperand(1))) { 10282 if (Const->getZExtValue() != 31) 10283 return SDValue(); 10284 } else 10285 return SDValue(); 10286 10287 if (SRA.getOperand(0) != Mul) 10288 return SDValue(); 10289 10290 SelectionDAG &DAG = DCI.DAG; 10291 SDLoc dl(AddcNode); 10292 unsigned Opcode = 0; 10293 SDValue Op0; 10294 SDValue Op1; 10295 10296 if (isS16(Mul.getOperand(0), DAG) && isS16(Mul.getOperand(1), DAG)) { 10297 Opcode = ARMISD::SMLALBB; 10298 Op0 = Mul.getOperand(0); 10299 Op1 = Mul.getOperand(1); 10300 } else if (isS16(Mul.getOperand(0), DAG) && isSRA16(Mul.getOperand(1))) { 10301 Opcode = ARMISD::SMLALBT; 10302 Op0 = Mul.getOperand(0); 10303 Op1 = Mul.getOperand(1).getOperand(0); 10304 } else if (isSRA16(Mul.getOperand(0)) && isS16(Mul.getOperand(1), DAG)) { 10305 Opcode = ARMISD::SMLALTB; 10306 Op0 = Mul.getOperand(0).getOperand(0); 10307 Op1 = Mul.getOperand(1); 10308 } else if (isSRA16(Mul.getOperand(0)) && isSRA16(Mul.getOperand(1))) { 10309 Opcode = ARMISD::SMLALTT; 10310 Op0 = Mul->getOperand(0).getOperand(0); 10311 Op1 = Mul->getOperand(1).getOperand(0); 10312 } 10313 10314 if (!Op0 || !Op1) 10315 return SDValue(); 10316 10317 SDValue SMLAL = DAG.getNode(Opcode, dl, DAG.getVTList(MVT::i32, MVT::i32), 10318 Op0, Op1, Lo, Hi); 10319 // Replace the ADDs' nodes uses by the MLA node's values. 10320 SDValue HiMLALResult(SMLAL.getNode(), 1); 10321 SDValue LoMLALResult(SMLAL.getNode(), 0); 10322 10323 DAG.ReplaceAllUsesOfValueWith(SDValue(AddcNode, 0), LoMLALResult); 10324 DAG.ReplaceAllUsesOfValueWith(SDValue(AddeNode, 0), HiMLALResult); 10325 10326 // Return original node to notify the driver to stop replacing. 10327 SDValue resNode(AddcNode, 0); 10328 return resNode; 10329 } 10330 10331 static SDValue AddCombineTo64bitMLAL(SDNode *AddeSubeNode, 10332 TargetLowering::DAGCombinerInfo &DCI, 10333 const ARMSubtarget *Subtarget) { 10334 // Look for multiply add opportunities. 10335 // The pattern is a ISD::UMUL_LOHI followed by two add nodes, where 10336 // each add nodes consumes a value from ISD::UMUL_LOHI and there is 10337 // a glue link from the first add to the second add. 10338 // If we find this pattern, we can replace the U/SMUL_LOHI, ADDC, and ADDE by 10339 // a S/UMLAL instruction. 10340 // UMUL_LOHI 10341 // / :lo \ :hi 10342 // V \ [no multiline comment] 10343 // loAdd -> ADDC | 10344 // \ :carry / 10345 // V V 10346 // ADDE <- hiAdd 10347 // 10348 // In the special case where only the higher part of a signed result is used 10349 // and the add to the low part of the result of ISD::UMUL_LOHI adds or subtracts 10350 // a constant with the exact value of 0x80000000, we recognize we are dealing 10351 // with a "rounded multiply and add" (or subtract) and transform it into 10352 // either a ARMISD::SMMLAR or ARMISD::SMMLSR respectively. 10353 10354 assert((AddeSubeNode->getOpcode() == ARMISD::ADDE || 10355 AddeSubeNode->getOpcode() == ARMISD::SUBE) && 10356 "Expect an ADDE or SUBE"); 10357 10358 assert(AddeSubeNode->getNumOperands() == 3 && 10359 AddeSubeNode->getOperand(2).getValueType() == MVT::i32 && 10360 "ADDE node has the wrong inputs"); 10361 10362 // Check that we are chained to the right ADDC or SUBC node. 10363 SDNode *AddcSubcNode = AddeSubeNode->getOperand(2).getNode(); 10364 if ((AddeSubeNode->getOpcode() == ARMISD::ADDE && 10365 AddcSubcNode->getOpcode() != ARMISD::ADDC) || 10366 (AddeSubeNode->getOpcode() == ARMISD::SUBE && 10367 AddcSubcNode->getOpcode() != ARMISD::SUBC)) 10368 return SDValue(); 10369 10370 SDValue AddcSubcOp0 = AddcSubcNode->getOperand(0); 10371 SDValue AddcSubcOp1 = AddcSubcNode->getOperand(1); 10372 10373 // Check if the two operands are from the same mul_lohi node. 10374 if (AddcSubcOp0.getNode() == AddcSubcOp1.getNode()) 10375 return SDValue(); 10376 10377 assert(AddcSubcNode->getNumValues() == 2 && 10378 AddcSubcNode->getValueType(0) == MVT::i32 && 10379 "Expect ADDC with two result values. First: i32"); 10380 10381 // Check that the ADDC adds the low result of the S/UMUL_LOHI. If not, it 10382 // maybe a SMLAL which multiplies two 16-bit values. 10383 if (AddeSubeNode->getOpcode() == ARMISD::ADDE && 10384 AddcSubcOp0->getOpcode() != ISD::UMUL_LOHI && 10385 AddcSubcOp0->getOpcode() != ISD::SMUL_LOHI && 10386 AddcSubcOp1->getOpcode() != ISD::UMUL_LOHI && 10387 AddcSubcOp1->getOpcode() != ISD::SMUL_LOHI) 10388 return AddCombineTo64BitSMLAL16(AddcSubcNode, AddeSubeNode, DCI, Subtarget); 10389 10390 // Check for the triangle shape. 10391 SDValue AddeSubeOp0 = AddeSubeNode->getOperand(0); 10392 SDValue AddeSubeOp1 = AddeSubeNode->getOperand(1); 10393 10394 // Make sure that the ADDE/SUBE operands are not coming from the same node. 10395 if (AddeSubeOp0.getNode() == AddeSubeOp1.getNode()) 10396 return SDValue(); 10397 10398 // Find the MUL_LOHI node walking up ADDE/SUBE's operands. 10399 bool IsLeftOperandMUL = false; 10400 SDValue MULOp = findMUL_LOHI(AddeSubeOp0); 10401 if (MULOp == SDValue()) 10402 MULOp = findMUL_LOHI(AddeSubeOp1); 10403 else 10404 IsLeftOperandMUL = true; 10405 if (MULOp == SDValue()) 10406 return SDValue(); 10407 10408 // Figure out the right opcode. 10409 unsigned Opc = MULOp->getOpcode(); 10410 unsigned FinalOpc = (Opc == ISD::SMUL_LOHI) ? ARMISD::SMLAL : ARMISD::UMLAL; 10411 10412 // Figure out the high and low input values to the MLAL node. 10413 SDValue *HiAddSub = nullptr; 10414 SDValue *LoMul = nullptr; 10415 SDValue *LowAddSub = nullptr; 10416 10417 // Ensure that ADDE/SUBE is from high result of ISD::xMUL_LOHI. 10418 if ((AddeSubeOp0 != MULOp.getValue(1)) && (AddeSubeOp1 != MULOp.getValue(1))) 10419 return SDValue(); 10420 10421 if (IsLeftOperandMUL) 10422 HiAddSub = &AddeSubeOp1; 10423 else 10424 HiAddSub = &AddeSubeOp0; 10425 10426 // Ensure that LoMul and LowAddSub are taken from correct ISD::SMUL_LOHI node 10427 // whose low result is fed to the ADDC/SUBC we are checking. 10428 10429 if (AddcSubcOp0 == MULOp.getValue(0)) { 10430 LoMul = &AddcSubcOp0; 10431 LowAddSub = &AddcSubcOp1; 10432 } 10433 if (AddcSubcOp1 == MULOp.getValue(0)) { 10434 LoMul = &AddcSubcOp1; 10435 LowAddSub = &AddcSubcOp0; 10436 } 10437 10438 if (!LoMul) 10439 return SDValue(); 10440 10441 // If HiAddSub is the same node as ADDC/SUBC or is a predecessor of ADDC/SUBC 10442 // the replacement below will create a cycle. 10443 if (AddcSubcNode == HiAddSub->getNode() || 10444 AddcSubcNode->isPredecessorOf(HiAddSub->getNode())) 10445 return SDValue(); 10446 10447 // Create the merged node. 10448 SelectionDAG &DAG = DCI.DAG; 10449 10450 // Start building operand list. 10451 SmallVector<SDValue, 8> Ops; 10452 Ops.push_back(LoMul->getOperand(0)); 10453 Ops.push_back(LoMul->getOperand(1)); 10454 10455 // Check whether we can use SMMLAR, SMMLSR or SMMULR instead. For this to be 10456 // the case, we must be doing signed multiplication and only use the higher 10457 // part of the result of the MLAL, furthermore the LowAddSub must be a constant 10458 // addition or subtraction with the value of 0x800000. 10459 if (Subtarget->hasV6Ops() && Subtarget->hasDSP() && Subtarget->useMulOps() && 10460 FinalOpc == ARMISD::SMLAL && !AddeSubeNode->hasAnyUseOfValue(1) && 10461 LowAddSub->getNode()->getOpcode() == ISD::Constant && 10462 static_cast<ConstantSDNode *>(LowAddSub->getNode())->getZExtValue() == 10463 0x80000000) { 10464 Ops.push_back(*HiAddSub); 10465 if (AddcSubcNode->getOpcode() == ARMISD::SUBC) { 10466 FinalOpc = ARMISD::SMMLSR; 10467 } else { 10468 FinalOpc = ARMISD::SMMLAR; 10469 } 10470 SDValue NewNode = DAG.getNode(FinalOpc, SDLoc(AddcSubcNode), MVT::i32, Ops); 10471 DAG.ReplaceAllUsesOfValueWith(SDValue(AddeSubeNode, 0), NewNode); 10472 10473 return SDValue(AddeSubeNode, 0); 10474 } else if (AddcSubcNode->getOpcode() == ARMISD::SUBC) 10475 // SMMLS is generated during instruction selection and the rest of this 10476 // function can not handle the case where AddcSubcNode is a SUBC. 10477 return SDValue(); 10478 10479 // Finish building the operand list for {U/S}MLAL 10480 Ops.push_back(*LowAddSub); 10481 Ops.push_back(*HiAddSub); 10482 10483 SDValue MLALNode = DAG.getNode(FinalOpc, SDLoc(AddcSubcNode), 10484 DAG.getVTList(MVT::i32, MVT::i32), Ops); 10485 10486 // Replace the ADDs' nodes uses by the MLA node's values. 10487 SDValue HiMLALResult(MLALNode.getNode(), 1); 10488 DAG.ReplaceAllUsesOfValueWith(SDValue(AddeSubeNode, 0), HiMLALResult); 10489 10490 SDValue LoMLALResult(MLALNode.getNode(), 0); 10491 DAG.ReplaceAllUsesOfValueWith(SDValue(AddcSubcNode, 0), LoMLALResult); 10492 10493 // Return original node to notify the driver to stop replacing. 10494 return SDValue(AddeSubeNode, 0); 10495 } 10496 10497 static SDValue AddCombineTo64bitUMAAL(SDNode *AddeNode, 10498 TargetLowering::DAGCombinerInfo &DCI, 10499 const ARMSubtarget *Subtarget) { 10500 // UMAAL is similar to UMLAL except that it adds two unsigned values. 10501 // While trying to combine for the other MLAL nodes, first search for the 10502 // chance to use UMAAL. Check if Addc uses a node which has already 10503 // been combined into a UMLAL. The other pattern is UMLAL using Addc/Adde 10504 // as the addend, and it's handled in PerformUMLALCombine. 10505 10506 if (!Subtarget->hasV6Ops() || !Subtarget->hasDSP()) 10507 return AddCombineTo64bitMLAL(AddeNode, DCI, Subtarget); 10508 10509 // Check that we have a glued ADDC node. 10510 SDNode* AddcNode = AddeNode->getOperand(2).getNode(); 10511 if (AddcNode->getOpcode() != ARMISD::ADDC) 10512 return SDValue(); 10513 10514 // Find the converted UMAAL or quit if it doesn't exist. 10515 SDNode *UmlalNode = nullptr; 10516 SDValue AddHi; 10517 if (AddcNode->getOperand(0).getOpcode() == ARMISD::UMLAL) { 10518 UmlalNode = AddcNode->getOperand(0).getNode(); 10519 AddHi = AddcNode->getOperand(1); 10520 } else if (AddcNode->getOperand(1).getOpcode() == ARMISD::UMLAL) { 10521 UmlalNode = AddcNode->getOperand(1).getNode(); 10522 AddHi = AddcNode->getOperand(0); 10523 } else { 10524 return AddCombineTo64bitMLAL(AddeNode, DCI, Subtarget); 10525 } 10526 10527 // The ADDC should be glued to an ADDE node, which uses the same UMLAL as 10528 // the ADDC as well as Zero. 10529 if (!isNullConstant(UmlalNode->getOperand(3))) 10530 return SDValue(); 10531 10532 if ((isNullConstant(AddeNode->getOperand(0)) && 10533 AddeNode->getOperand(1).getNode() == UmlalNode) || 10534 (AddeNode->getOperand(0).getNode() == UmlalNode && 10535 isNullConstant(AddeNode->getOperand(1)))) { 10536 SelectionDAG &DAG = DCI.DAG; 10537 SDValue Ops[] = { UmlalNode->getOperand(0), UmlalNode->getOperand(1), 10538 UmlalNode->getOperand(2), AddHi }; 10539 SDValue UMAAL = DAG.getNode(ARMISD::UMAAL, SDLoc(AddcNode), 10540 DAG.getVTList(MVT::i32, MVT::i32), Ops); 10541 10542 // Replace the ADDs' nodes uses by the UMAAL node's values. 10543 DAG.ReplaceAllUsesOfValueWith(SDValue(AddeNode, 0), SDValue(UMAAL.getNode(), 1)); 10544 DAG.ReplaceAllUsesOfValueWith(SDValue(AddcNode, 0), SDValue(UMAAL.getNode(), 0)); 10545 10546 // Return original node to notify the driver to stop replacing. 10547 return SDValue(AddeNode, 0); 10548 } 10549 return SDValue(); 10550 } 10551 10552 static SDValue PerformUMLALCombine(SDNode *N, SelectionDAG &DAG, 10553 const ARMSubtarget *Subtarget) { 10554 if (!Subtarget->hasV6Ops() || !Subtarget->hasDSP()) 10555 return SDValue(); 10556 10557 // Check that we have a pair of ADDC and ADDE as operands. 10558 // Both addends of the ADDE must be zero. 10559 SDNode* AddcNode = N->getOperand(2).getNode(); 10560 SDNode* AddeNode = N->getOperand(3).getNode(); 10561 if ((AddcNode->getOpcode() == ARMISD::ADDC) && 10562 (AddeNode->getOpcode() == ARMISD::ADDE) && 10563 isNullConstant(AddeNode->getOperand(0)) && 10564 isNullConstant(AddeNode->getOperand(1)) && 10565 (AddeNode->getOperand(2).getNode() == AddcNode)) 10566 return DAG.getNode(ARMISD::UMAAL, SDLoc(N), 10567 DAG.getVTList(MVT::i32, MVT::i32), 10568 {N->getOperand(0), N->getOperand(1), 10569 AddcNode->getOperand(0), AddcNode->getOperand(1)}); 10570 else 10571 return SDValue(); 10572 } 10573 10574 static SDValue PerformAddcSubcCombine(SDNode *N, 10575 TargetLowering::DAGCombinerInfo &DCI, 10576 const ARMSubtarget *Subtarget) { 10577 SelectionDAG &DAG(DCI.DAG); 10578 10579 if (N->getOpcode() == ARMISD::SUBC) { 10580 // (SUBC (ADDE 0, 0, C), 1) -> C 10581 SDValue LHS = N->getOperand(0); 10582 SDValue RHS = N->getOperand(1); 10583 if (LHS->getOpcode() == ARMISD::ADDE && 10584 isNullConstant(LHS->getOperand(0)) && 10585 isNullConstant(LHS->getOperand(1)) && isOneConstant(RHS)) { 10586 return DCI.CombineTo(N, SDValue(N, 0), LHS->getOperand(2)); 10587 } 10588 } 10589 10590 if (Subtarget->isThumb1Only()) { 10591 SDValue RHS = N->getOperand(1); 10592 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS)) { 10593 int32_t imm = C->getSExtValue(); 10594 if (imm < 0 && imm > std::numeric_limits<int>::min()) { 10595 SDLoc DL(N); 10596 RHS = DAG.getConstant(-imm, DL, MVT::i32); 10597 unsigned Opcode = (N->getOpcode() == ARMISD::ADDC) ? ARMISD::SUBC 10598 : ARMISD::ADDC; 10599 return DAG.getNode(Opcode, DL, N->getVTList(), N->getOperand(0), RHS); 10600 } 10601 } 10602 } 10603 10604 return SDValue(); 10605 } 10606 10607 static SDValue PerformAddeSubeCombine(SDNode *N, 10608 TargetLowering::DAGCombinerInfo &DCI, 10609 const ARMSubtarget *Subtarget) { 10610 if (Subtarget->isThumb1Only()) { 10611 SelectionDAG &DAG = DCI.DAG; 10612 SDValue RHS = N->getOperand(1); 10613 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS)) { 10614 int64_t imm = C->getSExtValue(); 10615 if (imm < 0) { 10616 SDLoc DL(N); 10617 10618 // The with-carry-in form matches bitwise not instead of the negation. 10619 // Effectively, the inverse interpretation of the carry flag already 10620 // accounts for part of the negation. 10621 RHS = DAG.getConstant(~imm, DL, MVT::i32); 10622 10623 unsigned Opcode = (N->getOpcode() == ARMISD::ADDE) ? ARMISD::SUBE 10624 : ARMISD::ADDE; 10625 return DAG.getNode(Opcode, DL, N->getVTList(), 10626 N->getOperand(0), RHS, N->getOperand(2)); 10627 } 10628 } 10629 } else if (N->getOperand(1)->getOpcode() == ISD::SMUL_LOHI) { 10630 return AddCombineTo64bitMLAL(N, DCI, Subtarget); 10631 } 10632 return SDValue(); 10633 } 10634 10635 static SDValue PerformABSCombine(SDNode *N, 10636 TargetLowering::DAGCombinerInfo &DCI, 10637 const ARMSubtarget *Subtarget) { 10638 SDValue res; 10639 SelectionDAG &DAG = DCI.DAG; 10640 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 10641 10642 if (TLI.isOperationLegal(N->getOpcode(), N->getValueType(0))) 10643 return SDValue(); 10644 10645 if (!TLI.expandABS(N, res, DAG)) 10646 return SDValue(); 10647 10648 return res; 10649 } 10650 10651 /// PerformADDECombine - Target-specific dag combine transform from 10652 /// ARMISD::ADDC, ARMISD::ADDE, and ISD::MUL_LOHI to MLAL or 10653 /// ARMISD::ADDC, ARMISD::ADDE and ARMISD::UMLAL to ARMISD::UMAAL 10654 static SDValue PerformADDECombine(SDNode *N, 10655 TargetLowering::DAGCombinerInfo &DCI, 10656 const ARMSubtarget *Subtarget) { 10657 // Only ARM and Thumb2 support UMLAL/SMLAL. 10658 if (Subtarget->isThumb1Only()) 10659 return PerformAddeSubeCombine(N, DCI, Subtarget); 10660 10661 // Only perform the checks after legalize when the pattern is available. 10662 if (DCI.isBeforeLegalize()) return SDValue(); 10663 10664 return AddCombineTo64bitUMAAL(N, DCI, Subtarget); 10665 } 10666 10667 /// PerformADDCombineWithOperands - Try DAG combinations for an ADD with 10668 /// operands N0 and N1. This is a helper for PerformADDCombine that is 10669 /// called with the default operands, and if that fails, with commuted 10670 /// operands. 10671 static SDValue PerformADDCombineWithOperands(SDNode *N, SDValue N0, SDValue N1, 10672 TargetLowering::DAGCombinerInfo &DCI, 10673 const ARMSubtarget *Subtarget){ 10674 // Attempt to create vpadd for this add. 10675 if (SDValue Result = AddCombineToVPADD(N, N0, N1, DCI, Subtarget)) 10676 return Result; 10677 10678 // Attempt to create vpaddl for this add. 10679 if (SDValue Result = AddCombineVUZPToVPADDL(N, N0, N1, DCI, Subtarget)) 10680 return Result; 10681 if (SDValue Result = AddCombineBUILD_VECTORToVPADDL(N, N0, N1, DCI, 10682 Subtarget)) 10683 return Result; 10684 10685 // fold (add (select cc, 0, c), x) -> (select cc, x, (add, x, c)) 10686 if (N0.getNode()->hasOneUse()) 10687 if (SDValue Result = combineSelectAndUse(N, N0, N1, DCI)) 10688 return Result; 10689 return SDValue(); 10690 } 10691 10692 bool 10693 ARMTargetLowering::isDesirableToCommuteWithShift(const SDNode *N, 10694 CombineLevel Level) const { 10695 if (Level == BeforeLegalizeTypes) 10696 return true; 10697 10698 if (N->getOpcode() != ISD::SHL) 10699 return true; 10700 10701 if (Subtarget->isThumb1Only()) { 10702 // Avoid making expensive immediates by commuting shifts. (This logic 10703 // only applies to Thumb1 because ARM and Thumb2 immediates can be shifted 10704 // for free.) 10705 if (N->getOpcode() != ISD::SHL) 10706 return true; 10707 SDValue N1 = N->getOperand(0); 10708 if (N1->getOpcode() != ISD::ADD && N1->getOpcode() != ISD::AND && 10709 N1->getOpcode() != ISD::OR && N1->getOpcode() != ISD::XOR) 10710 return true; 10711 if (auto *Const = dyn_cast<ConstantSDNode>(N1->getOperand(1))) { 10712 if (Const->getAPIntValue().ult(256)) 10713 return false; 10714 if (N1->getOpcode() == ISD::ADD && Const->getAPIntValue().slt(0) && 10715 Const->getAPIntValue().sgt(-256)) 10716 return false; 10717 } 10718 return true; 10719 } 10720 10721 // Turn off commute-with-shift transform after legalization, so it doesn't 10722 // conflict with PerformSHLSimplify. (We could try to detect when 10723 // PerformSHLSimplify would trigger more precisely, but it isn't 10724 // really necessary.) 10725 return false; 10726 } 10727 10728 bool ARMTargetLowering::shouldFoldConstantShiftPairToMask( 10729 const SDNode *N, CombineLevel Level) const { 10730 if (!Subtarget->isThumb1Only()) 10731 return true; 10732 10733 if (Level == BeforeLegalizeTypes) 10734 return true; 10735 10736 return false; 10737 } 10738 10739 bool ARMTargetLowering::preferIncOfAddToSubOfNot(EVT VT) const { 10740 if (!Subtarget->hasNEON()) { 10741 if (Subtarget->isThumb1Only()) 10742 return VT.getScalarSizeInBits() <= 32; 10743 return true; 10744 } 10745 return VT.isScalarInteger(); 10746 } 10747 10748 static SDValue PerformSHLSimplify(SDNode *N, 10749 TargetLowering::DAGCombinerInfo &DCI, 10750 const ARMSubtarget *ST) { 10751 // Allow the generic combiner to identify potential bswaps. 10752 if (DCI.isBeforeLegalize()) 10753 return SDValue(); 10754 10755 // DAG combiner will fold: 10756 // (shl (add x, c1), c2) -> (add (shl x, c2), c1 << c2) 10757 // (shl (or x, c1), c2) -> (or (shl x, c2), c1 << c2 10758 // Other code patterns that can be also be modified have the following form: 10759 // b + ((a << 1) | 510) 10760 // b + ((a << 1) & 510) 10761 // b + ((a << 1) ^ 510) 10762 // b + ((a << 1) + 510) 10763 10764 // Many instructions can perform the shift for free, but it requires both 10765 // the operands to be registers. If c1 << c2 is too large, a mov immediate 10766 // instruction will needed. So, unfold back to the original pattern if: 10767 // - if c1 and c2 are small enough that they don't require mov imms. 10768 // - the user(s) of the node can perform an shl 10769 10770 // No shifted operands for 16-bit instructions. 10771 if (ST->isThumb() && ST->isThumb1Only()) 10772 return SDValue(); 10773 10774 // Check that all the users could perform the shl themselves. 10775 for (auto U : N->uses()) { 10776 switch(U->getOpcode()) { 10777 default: 10778 return SDValue(); 10779 case ISD::SUB: 10780 case ISD::ADD: 10781 case ISD::AND: 10782 case ISD::OR: 10783 case ISD::XOR: 10784 case ISD::SETCC: 10785 case ARMISD::CMP: 10786 // Check that the user isn't already using a constant because there 10787 // aren't any instructions that support an immediate operand and a 10788 // shifted operand. 10789 if (isa<ConstantSDNode>(U->getOperand(0)) || 10790 isa<ConstantSDNode>(U->getOperand(1))) 10791 return SDValue(); 10792 10793 // Check that it's not already using a shift. 10794 if (U->getOperand(0).getOpcode() == ISD::SHL || 10795 U->getOperand(1).getOpcode() == ISD::SHL) 10796 return SDValue(); 10797 break; 10798 } 10799 } 10800 10801 if (N->getOpcode() != ISD::ADD && N->getOpcode() != ISD::OR && 10802 N->getOpcode() != ISD::XOR && N->getOpcode() != ISD::AND) 10803 return SDValue(); 10804 10805 if (N->getOperand(0).getOpcode() != ISD::SHL) 10806 return SDValue(); 10807 10808 SDValue SHL = N->getOperand(0); 10809 10810 auto *C1ShlC2 = dyn_cast<ConstantSDNode>(N->getOperand(1)); 10811 auto *C2 = dyn_cast<ConstantSDNode>(SHL.getOperand(1)); 10812 if (!C1ShlC2 || !C2) 10813 return SDValue(); 10814 10815 APInt C2Int = C2->getAPIntValue(); 10816 APInt C1Int = C1ShlC2->getAPIntValue(); 10817 10818 // Check that performing a lshr will not lose any information. 10819 APInt Mask = APInt::getHighBitsSet(C2Int.getBitWidth(), 10820 C2Int.getBitWidth() - C2->getZExtValue()); 10821 if ((C1Int & Mask) != C1Int) 10822 return SDValue(); 10823 10824 // Shift the first constant. 10825 C1Int.lshrInPlace(C2Int); 10826 10827 // The immediates are encoded as an 8-bit value that can be rotated. 10828 auto LargeImm = [](const APInt &Imm) { 10829 unsigned Zeros = Imm.countLeadingZeros() + Imm.countTrailingZeros(); 10830 return Imm.getBitWidth() - Zeros > 8; 10831 }; 10832 10833 if (LargeImm(C1Int) || LargeImm(C2Int)) 10834 return SDValue(); 10835 10836 SelectionDAG &DAG = DCI.DAG; 10837 SDLoc dl(N); 10838 SDValue X = SHL.getOperand(0); 10839 SDValue BinOp = DAG.getNode(N->getOpcode(), dl, MVT::i32, X, 10840 DAG.getConstant(C1Int, dl, MVT::i32)); 10841 // Shift left to compensate for the lshr of C1Int. 10842 SDValue Res = DAG.getNode(ISD::SHL, dl, MVT::i32, BinOp, SHL.getOperand(1)); 10843 10844 LLVM_DEBUG(dbgs() << "Simplify shl use:\n"; SHL.getOperand(0).dump(); 10845 SHL.dump(); N->dump()); 10846 LLVM_DEBUG(dbgs() << "Into:\n"; X.dump(); BinOp.dump(); Res.dump()); 10847 return Res; 10848 } 10849 10850 10851 /// PerformADDCombine - Target-specific dag combine xforms for ISD::ADD. 10852 /// 10853 static SDValue PerformADDCombine(SDNode *N, 10854 TargetLowering::DAGCombinerInfo &DCI, 10855 const ARMSubtarget *Subtarget) { 10856 SDValue N0 = N->getOperand(0); 10857 SDValue N1 = N->getOperand(1); 10858 10859 // Only works one way, because it needs an immediate operand. 10860 if (SDValue Result = PerformSHLSimplify(N, DCI, Subtarget)) 10861 return Result; 10862 10863 // First try with the default operand order. 10864 if (SDValue Result = PerformADDCombineWithOperands(N, N0, N1, DCI, Subtarget)) 10865 return Result; 10866 10867 // If that didn't work, try again with the operands commuted. 10868 return PerformADDCombineWithOperands(N, N1, N0, DCI, Subtarget); 10869 } 10870 10871 /// PerformSUBCombine - Target-specific dag combine xforms for ISD::SUB. 10872 /// 10873 static SDValue PerformSUBCombine(SDNode *N, 10874 TargetLowering::DAGCombinerInfo &DCI) { 10875 SDValue N0 = N->getOperand(0); 10876 SDValue N1 = N->getOperand(1); 10877 10878 // fold (sub x, (select cc, 0, c)) -> (select cc, x, (sub, x, c)) 10879 if (N1.getNode()->hasOneUse()) 10880 if (SDValue Result = combineSelectAndUse(N, N1, N0, DCI)) 10881 return Result; 10882 10883 return SDValue(); 10884 } 10885 10886 /// PerformVMULCombine 10887 /// Distribute (A + B) * C to (A * C) + (B * C) to take advantage of the 10888 /// special multiplier accumulator forwarding. 10889 /// vmul d3, d0, d2 10890 /// vmla d3, d1, d2 10891 /// is faster than 10892 /// vadd d3, d0, d1 10893 /// vmul d3, d3, d2 10894 // However, for (A + B) * (A + B), 10895 // vadd d2, d0, d1 10896 // vmul d3, d0, d2 10897 // vmla d3, d1, d2 10898 // is slower than 10899 // vadd d2, d0, d1 10900 // vmul d3, d2, d2 10901 static SDValue PerformVMULCombine(SDNode *N, 10902 TargetLowering::DAGCombinerInfo &DCI, 10903 const ARMSubtarget *Subtarget) { 10904 if (!Subtarget->hasVMLxForwarding()) 10905 return SDValue(); 10906 10907 SelectionDAG &DAG = DCI.DAG; 10908 SDValue N0 = N->getOperand(0); 10909 SDValue N1 = N->getOperand(1); 10910 unsigned Opcode = N0.getOpcode(); 10911 if (Opcode != ISD::ADD && Opcode != ISD::SUB && 10912 Opcode != ISD::FADD && Opcode != ISD::FSUB) { 10913 Opcode = N1.getOpcode(); 10914 if (Opcode != ISD::ADD && Opcode != ISD::SUB && 10915 Opcode != ISD::FADD && Opcode != ISD::FSUB) 10916 return SDValue(); 10917 std::swap(N0, N1); 10918 } 10919 10920 if (N0 == N1) 10921 return SDValue(); 10922 10923 EVT VT = N->getValueType(0); 10924 SDLoc DL(N); 10925 SDValue N00 = N0->getOperand(0); 10926 SDValue N01 = N0->getOperand(1); 10927 return DAG.getNode(Opcode, DL, VT, 10928 DAG.getNode(ISD::MUL, DL, VT, N00, N1), 10929 DAG.getNode(ISD::MUL, DL, VT, N01, N1)); 10930 } 10931 10932 static SDValue PerformMULCombine(SDNode *N, 10933 TargetLowering::DAGCombinerInfo &DCI, 10934 const ARMSubtarget *Subtarget) { 10935 SelectionDAG &DAG = DCI.DAG; 10936 10937 if (Subtarget->isThumb1Only()) 10938 return SDValue(); 10939 10940 if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer()) 10941 return SDValue(); 10942 10943 EVT VT = N->getValueType(0); 10944 if (VT.is64BitVector() || VT.is128BitVector()) 10945 return PerformVMULCombine(N, DCI, Subtarget); 10946 if (VT != MVT::i32) 10947 return SDValue(); 10948 10949 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(1)); 10950 if (!C) 10951 return SDValue(); 10952 10953 int64_t MulAmt = C->getSExtValue(); 10954 unsigned ShiftAmt = countTrailingZeros<uint64_t>(MulAmt); 10955 10956 ShiftAmt = ShiftAmt & (32 - 1); 10957 SDValue V = N->getOperand(0); 10958 SDLoc DL(N); 10959 10960 SDValue Res; 10961 MulAmt >>= ShiftAmt; 10962 10963 if (MulAmt >= 0) { 10964 if (isPowerOf2_32(MulAmt - 1)) { 10965 // (mul x, 2^N + 1) => (add (shl x, N), x) 10966 Res = DAG.getNode(ISD::ADD, DL, VT, 10967 V, 10968 DAG.getNode(ISD::SHL, DL, VT, 10969 V, 10970 DAG.getConstant(Log2_32(MulAmt - 1), DL, 10971 MVT::i32))); 10972 } else if (isPowerOf2_32(MulAmt + 1)) { 10973 // (mul x, 2^N - 1) => (sub (shl x, N), x) 10974 Res = DAG.getNode(ISD::SUB, DL, VT, 10975 DAG.getNode(ISD::SHL, DL, VT, 10976 V, 10977 DAG.getConstant(Log2_32(MulAmt + 1), DL, 10978 MVT::i32)), 10979 V); 10980 } else 10981 return SDValue(); 10982 } else { 10983 uint64_t MulAmtAbs = -MulAmt; 10984 if (isPowerOf2_32(MulAmtAbs + 1)) { 10985 // (mul x, -(2^N - 1)) => (sub x, (shl x, N)) 10986 Res = DAG.getNode(ISD::SUB, DL, VT, 10987 V, 10988 DAG.getNode(ISD::SHL, DL, VT, 10989 V, 10990 DAG.getConstant(Log2_32(MulAmtAbs + 1), DL, 10991 MVT::i32))); 10992 } else if (isPowerOf2_32(MulAmtAbs - 1)) { 10993 // (mul x, -(2^N + 1)) => - (add (shl x, N), x) 10994 Res = DAG.getNode(ISD::ADD, DL, VT, 10995 V, 10996 DAG.getNode(ISD::SHL, DL, VT, 10997 V, 10998 DAG.getConstant(Log2_32(MulAmtAbs - 1), DL, 10999 MVT::i32))); 11000 Res = DAG.getNode(ISD::SUB, DL, VT, 11001 DAG.getConstant(0, DL, MVT::i32), Res); 11002 } else 11003 return SDValue(); 11004 } 11005 11006 if (ShiftAmt != 0) 11007 Res = DAG.getNode(ISD::SHL, DL, VT, 11008 Res, DAG.getConstant(ShiftAmt, DL, MVT::i32)); 11009 11010 // Do not add new nodes to DAG combiner worklist. 11011 DCI.CombineTo(N, Res, false); 11012 return SDValue(); 11013 } 11014 11015 static SDValue CombineANDShift(SDNode *N, 11016 TargetLowering::DAGCombinerInfo &DCI, 11017 const ARMSubtarget *Subtarget) { 11018 // Allow DAGCombine to pattern-match before we touch the canonical form. 11019 if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer()) 11020 return SDValue(); 11021 11022 if (N->getValueType(0) != MVT::i32) 11023 return SDValue(); 11024 11025 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N->getOperand(1)); 11026 if (!N1C) 11027 return SDValue(); 11028 11029 uint32_t C1 = (uint32_t)N1C->getZExtValue(); 11030 // Don't transform uxtb/uxth. 11031 if (C1 == 255 || C1 == 65535) 11032 return SDValue(); 11033 11034 SDNode *N0 = N->getOperand(0).getNode(); 11035 if (!N0->hasOneUse()) 11036 return SDValue(); 11037 11038 if (N0->getOpcode() != ISD::SHL && N0->getOpcode() != ISD::SRL) 11039 return SDValue(); 11040 11041 bool LeftShift = N0->getOpcode() == ISD::SHL; 11042 11043 ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N0->getOperand(1)); 11044 if (!N01C) 11045 return SDValue(); 11046 11047 uint32_t C2 = (uint32_t)N01C->getZExtValue(); 11048 if (!C2 || C2 >= 32) 11049 return SDValue(); 11050 11051 // Clear irrelevant bits in the mask. 11052 if (LeftShift) 11053 C1 &= (-1U << C2); 11054 else 11055 C1 &= (-1U >> C2); 11056 11057 SelectionDAG &DAG = DCI.DAG; 11058 SDLoc DL(N); 11059 11060 // We have a pattern of the form "(and (shl x, c2) c1)" or 11061 // "(and (srl x, c2) c1)", where c1 is a shifted mask. Try to 11062 // transform to a pair of shifts, to save materializing c1. 11063 11064 // First pattern: right shift, then mask off leading bits. 11065 // FIXME: Use demanded bits? 11066 if (!LeftShift && isMask_32(C1)) { 11067 uint32_t C3 = countLeadingZeros(C1); 11068 if (C2 < C3) { 11069 SDValue SHL = DAG.getNode(ISD::SHL, DL, MVT::i32, N0->getOperand(0), 11070 DAG.getConstant(C3 - C2, DL, MVT::i32)); 11071 return DAG.getNode(ISD::SRL, DL, MVT::i32, SHL, 11072 DAG.getConstant(C3, DL, MVT::i32)); 11073 } 11074 } 11075 11076 // First pattern, reversed: left shift, then mask off trailing bits. 11077 if (LeftShift && isMask_32(~C1)) { 11078 uint32_t C3 = countTrailingZeros(C1); 11079 if (C2 < C3) { 11080 SDValue SHL = DAG.getNode(ISD::SRL, DL, MVT::i32, N0->getOperand(0), 11081 DAG.getConstant(C3 - C2, DL, MVT::i32)); 11082 return DAG.getNode(ISD::SHL, DL, MVT::i32, SHL, 11083 DAG.getConstant(C3, DL, MVT::i32)); 11084 } 11085 } 11086 11087 // Second pattern: left shift, then mask off leading bits. 11088 // FIXME: Use demanded bits? 11089 if (LeftShift && isShiftedMask_32(C1)) { 11090 uint32_t Trailing = countTrailingZeros(C1); 11091 uint32_t C3 = countLeadingZeros(C1); 11092 if (Trailing == C2 && C2 + C3 < 32) { 11093 SDValue SHL = DAG.getNode(ISD::SHL, DL, MVT::i32, N0->getOperand(0), 11094 DAG.getConstant(C2 + C3, DL, MVT::i32)); 11095 return DAG.getNode(ISD::SRL, DL, MVT::i32, SHL, 11096 DAG.getConstant(C3, DL, MVT::i32)); 11097 } 11098 } 11099 11100 // Second pattern, reversed: right shift, then mask off trailing bits. 11101 // FIXME: Handle other patterns of known/demanded bits. 11102 if (!LeftShift && isShiftedMask_32(C1)) { 11103 uint32_t Leading = countLeadingZeros(C1); 11104 uint32_t C3 = countTrailingZeros(C1); 11105 if (Leading == C2 && C2 + C3 < 32) { 11106 SDValue SHL = DAG.getNode(ISD::SRL, DL, MVT::i32, N0->getOperand(0), 11107 DAG.getConstant(C2 + C3, DL, MVT::i32)); 11108 return DAG.getNode(ISD::SHL, DL, MVT::i32, SHL, 11109 DAG.getConstant(C3, DL, MVT::i32)); 11110 } 11111 } 11112 11113 // FIXME: Transform "(and (shl x, c2) c1)" -> 11114 // "(shl (and x, c1>>c2), c2)" if "c1 >> c2" is a cheaper immediate than 11115 // c1. 11116 return SDValue(); 11117 } 11118 11119 static SDValue PerformANDCombine(SDNode *N, 11120 TargetLowering::DAGCombinerInfo &DCI, 11121 const ARMSubtarget *Subtarget) { 11122 // Attempt to use immediate-form VBIC 11123 BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(N->getOperand(1)); 11124 SDLoc dl(N); 11125 EVT VT = N->getValueType(0); 11126 SelectionDAG &DAG = DCI.DAG; 11127 11128 if(!DAG.getTargetLoweringInfo().isTypeLegal(VT)) 11129 return SDValue(); 11130 11131 APInt SplatBits, SplatUndef; 11132 unsigned SplatBitSize; 11133 bool HasAnyUndefs; 11134 if (BVN && 11135 BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs)) { 11136 if (SplatBitSize <= 64) { 11137 EVT VbicVT; 11138 SDValue Val = isNEONModifiedImm((~SplatBits).getZExtValue(), 11139 SplatUndef.getZExtValue(), SplatBitSize, 11140 DAG, dl, VbicVT, VT.is128BitVector(), 11141 OtherModImm); 11142 if (Val.getNode()) { 11143 SDValue Input = 11144 DAG.getNode(ISD::BITCAST, dl, VbicVT, N->getOperand(0)); 11145 SDValue Vbic = DAG.getNode(ARMISD::VBICIMM, dl, VbicVT, Input, Val); 11146 return DAG.getNode(ISD::BITCAST, dl, VT, Vbic); 11147 } 11148 } 11149 } 11150 11151 if (!Subtarget->isThumb1Only()) { 11152 // fold (and (select cc, -1, c), x) -> (select cc, x, (and, x, c)) 11153 if (SDValue Result = combineSelectAndUseCommutative(N, true, DCI)) 11154 return Result; 11155 11156 if (SDValue Result = PerformSHLSimplify(N, DCI, Subtarget)) 11157 return Result; 11158 } 11159 11160 if (Subtarget->isThumb1Only()) 11161 if (SDValue Result = CombineANDShift(N, DCI, Subtarget)) 11162 return Result; 11163 11164 return SDValue(); 11165 } 11166 11167 // Try combining OR nodes to SMULWB, SMULWT. 11168 static SDValue PerformORCombineToSMULWBT(SDNode *OR, 11169 TargetLowering::DAGCombinerInfo &DCI, 11170 const ARMSubtarget *Subtarget) { 11171 if (!Subtarget->hasV6Ops() || 11172 (Subtarget->isThumb() && 11173 (!Subtarget->hasThumb2() || !Subtarget->hasDSP()))) 11174 return SDValue(); 11175 11176 SDValue SRL = OR->getOperand(0); 11177 SDValue SHL = OR->getOperand(1); 11178 11179 if (SRL.getOpcode() != ISD::SRL || SHL.getOpcode() != ISD::SHL) { 11180 SRL = OR->getOperand(1); 11181 SHL = OR->getOperand(0); 11182 } 11183 if (!isSRL16(SRL) || !isSHL16(SHL)) 11184 return SDValue(); 11185 11186 // The first operands to the shifts need to be the two results from the 11187 // same smul_lohi node. 11188 if ((SRL.getOperand(0).getNode() != SHL.getOperand(0).getNode()) || 11189 SRL.getOperand(0).getOpcode() != ISD::SMUL_LOHI) 11190 return SDValue(); 11191 11192 SDNode *SMULLOHI = SRL.getOperand(0).getNode(); 11193 if (SRL.getOperand(0) != SDValue(SMULLOHI, 0) || 11194 SHL.getOperand(0) != SDValue(SMULLOHI, 1)) 11195 return SDValue(); 11196 11197 // Now we have: 11198 // (or (srl (smul_lohi ?, ?), 16), (shl (smul_lohi ?, ?), 16))) 11199 // For SMUL[B|T] smul_lohi will take a 32-bit and a 16-bit arguments. 11200 // For SMUWB the 16-bit value will signed extended somehow. 11201 // For SMULWT only the SRA is required. 11202 // Check both sides of SMUL_LOHI 11203 SDValue OpS16 = SMULLOHI->getOperand(0); 11204 SDValue OpS32 = SMULLOHI->getOperand(1); 11205 11206 SelectionDAG &DAG = DCI.DAG; 11207 if (!isS16(OpS16, DAG) && !isSRA16(OpS16)) { 11208 OpS16 = OpS32; 11209 OpS32 = SMULLOHI->getOperand(0); 11210 } 11211 11212 SDLoc dl(OR); 11213 unsigned Opcode = 0; 11214 if (isS16(OpS16, DAG)) 11215 Opcode = ARMISD::SMULWB; 11216 else if (isSRA16(OpS16)) { 11217 Opcode = ARMISD::SMULWT; 11218 OpS16 = OpS16->getOperand(0); 11219 } 11220 else 11221 return SDValue(); 11222 11223 SDValue Res = DAG.getNode(Opcode, dl, MVT::i32, OpS32, OpS16); 11224 DAG.ReplaceAllUsesOfValueWith(SDValue(OR, 0), Res); 11225 return SDValue(OR, 0); 11226 } 11227 11228 static SDValue PerformORCombineToBFI(SDNode *N, 11229 TargetLowering::DAGCombinerInfo &DCI, 11230 const ARMSubtarget *Subtarget) { 11231 // BFI is only available on V6T2+ 11232 if (Subtarget->isThumb1Only() || !Subtarget->hasV6T2Ops()) 11233 return SDValue(); 11234 11235 EVT VT = N->getValueType(0); 11236 SDValue N0 = N->getOperand(0); 11237 SDValue N1 = N->getOperand(1); 11238 SelectionDAG &DAG = DCI.DAG; 11239 SDLoc DL(N); 11240 // 1) or (and A, mask), val => ARMbfi A, val, mask 11241 // iff (val & mask) == val 11242 // 11243 // 2) or (and A, mask), (and B, mask2) => ARMbfi A, (lsr B, amt), mask 11244 // 2a) iff isBitFieldInvertedMask(mask) && isBitFieldInvertedMask(~mask2) 11245 // && mask == ~mask2 11246 // 2b) iff isBitFieldInvertedMask(~mask) && isBitFieldInvertedMask(mask2) 11247 // && ~mask == mask2 11248 // (i.e., copy a bitfield value into another bitfield of the same width) 11249 11250 if (VT != MVT::i32) 11251 return SDValue(); 11252 11253 SDValue N00 = N0.getOperand(0); 11254 11255 // The value and the mask need to be constants so we can verify this is 11256 // actually a bitfield set. If the mask is 0xffff, we can do better 11257 // via a movt instruction, so don't use BFI in that case. 11258 SDValue MaskOp = N0.getOperand(1); 11259 ConstantSDNode *MaskC = dyn_cast<ConstantSDNode>(MaskOp); 11260 if (!MaskC) 11261 return SDValue(); 11262 unsigned Mask = MaskC->getZExtValue(); 11263 if (Mask == 0xffff) 11264 return SDValue(); 11265 SDValue Res; 11266 // Case (1): or (and A, mask), val => ARMbfi A, val, mask 11267 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1); 11268 if (N1C) { 11269 unsigned Val = N1C->getZExtValue(); 11270 if ((Val & ~Mask) != Val) 11271 return SDValue(); 11272 11273 if (ARM::isBitFieldInvertedMask(Mask)) { 11274 Val >>= countTrailingZeros(~Mask); 11275 11276 Res = DAG.getNode(ARMISD::BFI, DL, VT, N00, 11277 DAG.getConstant(Val, DL, MVT::i32), 11278 DAG.getConstant(Mask, DL, MVT::i32)); 11279 11280 DCI.CombineTo(N, Res, false); 11281 // Return value from the original node to inform the combiner than N is 11282 // now dead. 11283 return SDValue(N, 0); 11284 } 11285 } else if (N1.getOpcode() == ISD::AND) { 11286 // case (2) or (and A, mask), (and B, mask2) => ARMbfi A, (lsr B, amt), mask 11287 ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1)); 11288 if (!N11C) 11289 return SDValue(); 11290 unsigned Mask2 = N11C->getZExtValue(); 11291 11292 // Mask and ~Mask2 (or reverse) must be equivalent for the BFI pattern 11293 // as is to match. 11294 if (ARM::isBitFieldInvertedMask(Mask) && 11295 (Mask == ~Mask2)) { 11296 // The pack halfword instruction works better for masks that fit it, 11297 // so use that when it's available. 11298 if (Subtarget->hasDSP() && 11299 (Mask == 0xffff || Mask == 0xffff0000)) 11300 return SDValue(); 11301 // 2a 11302 unsigned amt = countTrailingZeros(Mask2); 11303 Res = DAG.getNode(ISD::SRL, DL, VT, N1.getOperand(0), 11304 DAG.getConstant(amt, DL, MVT::i32)); 11305 Res = DAG.getNode(ARMISD::BFI, DL, VT, N00, Res, 11306 DAG.getConstant(Mask, DL, MVT::i32)); 11307 DCI.CombineTo(N, Res, false); 11308 // Return value from the original node to inform the combiner than N is 11309 // now dead. 11310 return SDValue(N, 0); 11311 } else if (ARM::isBitFieldInvertedMask(~Mask) && 11312 (~Mask == Mask2)) { 11313 // The pack halfword instruction works better for masks that fit it, 11314 // so use that when it's available. 11315 if (Subtarget->hasDSP() && 11316 (Mask2 == 0xffff || Mask2 == 0xffff0000)) 11317 return SDValue(); 11318 // 2b 11319 unsigned lsb = countTrailingZeros(Mask); 11320 Res = DAG.getNode(ISD::SRL, DL, VT, N00, 11321 DAG.getConstant(lsb, DL, MVT::i32)); 11322 Res = DAG.getNode(ARMISD::BFI, DL, VT, N1.getOperand(0), Res, 11323 DAG.getConstant(Mask2, DL, MVT::i32)); 11324 DCI.CombineTo(N, Res, false); 11325 // Return value from the original node to inform the combiner than N is 11326 // now dead. 11327 return SDValue(N, 0); 11328 } 11329 } 11330 11331 if (DAG.MaskedValueIsZero(N1, MaskC->getAPIntValue()) && 11332 N00.getOpcode() == ISD::SHL && isa<ConstantSDNode>(N00.getOperand(1)) && 11333 ARM::isBitFieldInvertedMask(~Mask)) { 11334 // Case (3): or (and (shl A, #shamt), mask), B => ARMbfi B, A, ~mask 11335 // where lsb(mask) == #shamt and masked bits of B are known zero. 11336 SDValue ShAmt = N00.getOperand(1); 11337 unsigned ShAmtC = cast<ConstantSDNode>(ShAmt)->getZExtValue(); 11338 unsigned LSB = countTrailingZeros(Mask); 11339 if (ShAmtC != LSB) 11340 return SDValue(); 11341 11342 Res = DAG.getNode(ARMISD::BFI, DL, VT, N1, N00.getOperand(0), 11343 DAG.getConstant(~Mask, DL, MVT::i32)); 11344 11345 DCI.CombineTo(N, Res, false); 11346 // Return value from the original node to inform the combiner than N is 11347 // now dead. 11348 return SDValue(N, 0); 11349 } 11350 11351 return SDValue(); 11352 } 11353 11354 /// PerformORCombine - Target-specific dag combine xforms for ISD::OR 11355 static SDValue PerformORCombine(SDNode *N, 11356 TargetLowering::DAGCombinerInfo &DCI, 11357 const ARMSubtarget *Subtarget) { 11358 // Attempt to use immediate-form VORR 11359 BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(N->getOperand(1)); 11360 SDLoc dl(N); 11361 EVT VT = N->getValueType(0); 11362 SelectionDAG &DAG = DCI.DAG; 11363 11364 if(!DAG.getTargetLoweringInfo().isTypeLegal(VT)) 11365 return SDValue(); 11366 11367 APInt SplatBits, SplatUndef; 11368 unsigned SplatBitSize; 11369 bool HasAnyUndefs; 11370 if (BVN && Subtarget->hasNEON() && 11371 BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs)) { 11372 if (SplatBitSize <= 64) { 11373 EVT VorrVT; 11374 SDValue Val = isNEONModifiedImm(SplatBits.getZExtValue(), 11375 SplatUndef.getZExtValue(), SplatBitSize, 11376 DAG, dl, VorrVT, VT.is128BitVector(), 11377 OtherModImm); 11378 if (Val.getNode()) { 11379 SDValue Input = 11380 DAG.getNode(ISD::BITCAST, dl, VorrVT, N->getOperand(0)); 11381 SDValue Vorr = DAG.getNode(ARMISD::VORRIMM, dl, VorrVT, Input, Val); 11382 return DAG.getNode(ISD::BITCAST, dl, VT, Vorr); 11383 } 11384 } 11385 } 11386 11387 if (!Subtarget->isThumb1Only()) { 11388 // fold (or (select cc, 0, c), x) -> (select cc, x, (or, x, c)) 11389 if (SDValue Result = combineSelectAndUseCommutative(N, false, DCI)) 11390 return Result; 11391 if (SDValue Result = PerformORCombineToSMULWBT(N, DCI, Subtarget)) 11392 return Result; 11393 } 11394 11395 SDValue N0 = N->getOperand(0); 11396 SDValue N1 = N->getOperand(1); 11397 11398 // (or (and B, A), (and C, ~A)) => (VBSL A, B, C) when A is a constant. 11399 if (Subtarget->hasNEON() && N1.getOpcode() == ISD::AND && VT.isVector() && 11400 DAG.getTargetLoweringInfo().isTypeLegal(VT)) { 11401 11402 // The code below optimizes (or (and X, Y), Z). 11403 // The AND operand needs to have a single user to make these optimizations 11404 // profitable. 11405 if (N0.getOpcode() != ISD::AND || !N0.hasOneUse()) 11406 return SDValue(); 11407 11408 APInt SplatUndef; 11409 unsigned SplatBitSize; 11410 bool HasAnyUndefs; 11411 11412 APInt SplatBits0, SplatBits1; 11413 BuildVectorSDNode *BVN0 = dyn_cast<BuildVectorSDNode>(N0->getOperand(1)); 11414 BuildVectorSDNode *BVN1 = dyn_cast<BuildVectorSDNode>(N1->getOperand(1)); 11415 // Ensure that the second operand of both ands are constants 11416 if (BVN0 && BVN0->isConstantSplat(SplatBits0, SplatUndef, SplatBitSize, 11417 HasAnyUndefs) && !HasAnyUndefs) { 11418 if (BVN1 && BVN1->isConstantSplat(SplatBits1, SplatUndef, SplatBitSize, 11419 HasAnyUndefs) && !HasAnyUndefs) { 11420 // Ensure that the bit width of the constants are the same and that 11421 // the splat arguments are logical inverses as per the pattern we 11422 // are trying to simplify. 11423 if (SplatBits0.getBitWidth() == SplatBits1.getBitWidth() && 11424 SplatBits0 == ~SplatBits1) { 11425 // Canonicalize the vector type to make instruction selection 11426 // simpler. 11427 EVT CanonicalVT = VT.is128BitVector() ? MVT::v4i32 : MVT::v2i32; 11428 SDValue Result = DAG.getNode(ARMISD::VBSL, dl, CanonicalVT, 11429 N0->getOperand(1), 11430 N0->getOperand(0), 11431 N1->getOperand(0)); 11432 return DAG.getNode(ISD::BITCAST, dl, VT, Result); 11433 } 11434 } 11435 } 11436 } 11437 11438 // Try to use the ARM/Thumb2 BFI (bitfield insert) instruction when 11439 // reasonable. 11440 if (N0.getOpcode() == ISD::AND && N0.hasOneUse()) { 11441 if (SDValue Res = PerformORCombineToBFI(N, DCI, Subtarget)) 11442 return Res; 11443 } 11444 11445 if (SDValue Result = PerformSHLSimplify(N, DCI, Subtarget)) 11446 return Result; 11447 11448 return SDValue(); 11449 } 11450 11451 static SDValue PerformXORCombine(SDNode *N, 11452 TargetLowering::DAGCombinerInfo &DCI, 11453 const ARMSubtarget *Subtarget) { 11454 EVT VT = N->getValueType(0); 11455 SelectionDAG &DAG = DCI.DAG; 11456 11457 if(!DAG.getTargetLoweringInfo().isTypeLegal(VT)) 11458 return SDValue(); 11459 11460 if (!Subtarget->isThumb1Only()) { 11461 // fold (xor (select cc, 0, c), x) -> (select cc, x, (xor, x, c)) 11462 if (SDValue Result = combineSelectAndUseCommutative(N, false, DCI)) 11463 return Result; 11464 11465 if (SDValue Result = PerformSHLSimplify(N, DCI, Subtarget)) 11466 return Result; 11467 } 11468 11469 return SDValue(); 11470 } 11471 11472 // ParseBFI - given a BFI instruction in N, extract the "from" value (Rn) and return it, 11473 // and fill in FromMask and ToMask with (consecutive) bits in "from" to be extracted and 11474 // their position in "to" (Rd). 11475 static SDValue ParseBFI(SDNode *N, APInt &ToMask, APInt &FromMask) { 11476 assert(N->getOpcode() == ARMISD::BFI); 11477 11478 SDValue From = N->getOperand(1); 11479 ToMask = ~cast<ConstantSDNode>(N->getOperand(2))->getAPIntValue(); 11480 FromMask = APInt::getLowBitsSet(ToMask.getBitWidth(), ToMask.countPopulation()); 11481 11482 // If the Base came from a SHR #C, we can deduce that it is really testing bit 11483 // #C in the base of the SHR. 11484 if (From->getOpcode() == ISD::SRL && 11485 isa<ConstantSDNode>(From->getOperand(1))) { 11486 APInt Shift = cast<ConstantSDNode>(From->getOperand(1))->getAPIntValue(); 11487 assert(Shift.getLimitedValue() < 32 && "Shift too large!"); 11488 FromMask <<= Shift.getLimitedValue(31); 11489 From = From->getOperand(0); 11490 } 11491 11492 return From; 11493 } 11494 11495 // If A and B contain one contiguous set of bits, does A | B == A . B? 11496 // 11497 // Neither A nor B must be zero. 11498 static bool BitsProperlyConcatenate(const APInt &A, const APInt &B) { 11499 unsigned LastActiveBitInA = A.countTrailingZeros(); 11500 unsigned FirstActiveBitInB = B.getBitWidth() - B.countLeadingZeros() - 1; 11501 return LastActiveBitInA - 1 == FirstActiveBitInB; 11502 } 11503 11504 static SDValue FindBFIToCombineWith(SDNode *N) { 11505 // We have a BFI in N. Follow a possible chain of BFIs and find a BFI it can combine with, 11506 // if one exists. 11507 APInt ToMask, FromMask; 11508 SDValue From = ParseBFI(N, ToMask, FromMask); 11509 SDValue To = N->getOperand(0); 11510 11511 // Now check for a compatible BFI to merge with. We can pass through BFIs that 11512 // aren't compatible, but not if they set the same bit in their destination as 11513 // we do (or that of any BFI we're going to combine with). 11514 SDValue V = To; 11515 APInt CombinedToMask = ToMask; 11516 while (V.getOpcode() == ARMISD::BFI) { 11517 APInt NewToMask, NewFromMask; 11518 SDValue NewFrom = ParseBFI(V.getNode(), NewToMask, NewFromMask); 11519 if (NewFrom != From) { 11520 // This BFI has a different base. Keep going. 11521 CombinedToMask |= NewToMask; 11522 V = V.getOperand(0); 11523 continue; 11524 } 11525 11526 // Do the written bits conflict with any we've seen so far? 11527 if ((NewToMask & CombinedToMask).getBoolValue()) 11528 // Conflicting bits - bail out because going further is unsafe. 11529 return SDValue(); 11530 11531 // Are the new bits contiguous when combined with the old bits? 11532 if (BitsProperlyConcatenate(ToMask, NewToMask) && 11533 BitsProperlyConcatenate(FromMask, NewFromMask)) 11534 return V; 11535 if (BitsProperlyConcatenate(NewToMask, ToMask) && 11536 BitsProperlyConcatenate(NewFromMask, FromMask)) 11537 return V; 11538 11539 // We've seen a write to some bits, so track it. 11540 CombinedToMask |= NewToMask; 11541 // Keep going... 11542 V = V.getOperand(0); 11543 } 11544 11545 return SDValue(); 11546 } 11547 11548 static SDValue PerformBFICombine(SDNode *N, 11549 TargetLowering::DAGCombinerInfo &DCI) { 11550 SDValue N1 = N->getOperand(1); 11551 if (N1.getOpcode() == ISD::AND) { 11552 // (bfi A, (and B, Mask1), Mask2) -> (bfi A, B, Mask2) iff 11553 // the bits being cleared by the AND are not demanded by the BFI. 11554 ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1)); 11555 if (!N11C) 11556 return SDValue(); 11557 unsigned InvMask = cast<ConstantSDNode>(N->getOperand(2))->getZExtValue(); 11558 unsigned LSB = countTrailingZeros(~InvMask); 11559 unsigned Width = (32 - countLeadingZeros(~InvMask)) - LSB; 11560 assert(Width < 11561 static_cast<unsigned>(std::numeric_limits<unsigned>::digits) && 11562 "undefined behavior"); 11563 unsigned Mask = (1u << Width) - 1; 11564 unsigned Mask2 = N11C->getZExtValue(); 11565 if ((Mask & (~Mask2)) == 0) 11566 return DCI.DAG.getNode(ARMISD::BFI, SDLoc(N), N->getValueType(0), 11567 N->getOperand(0), N1.getOperand(0), 11568 N->getOperand(2)); 11569 } else if (N->getOperand(0).getOpcode() == ARMISD::BFI) { 11570 // We have a BFI of a BFI. Walk up the BFI chain to see how long it goes. 11571 // Keep track of any consecutive bits set that all come from the same base 11572 // value. We can combine these together into a single BFI. 11573 SDValue CombineBFI = FindBFIToCombineWith(N); 11574 if (CombineBFI == SDValue()) 11575 return SDValue(); 11576 11577 // We've found a BFI. 11578 APInt ToMask1, FromMask1; 11579 SDValue From1 = ParseBFI(N, ToMask1, FromMask1); 11580 11581 APInt ToMask2, FromMask2; 11582 SDValue From2 = ParseBFI(CombineBFI.getNode(), ToMask2, FromMask2); 11583 assert(From1 == From2); 11584 (void)From2; 11585 11586 // First, unlink CombineBFI. 11587 DCI.DAG.ReplaceAllUsesWith(CombineBFI, CombineBFI.getOperand(0)); 11588 // Then create a new BFI, combining the two together. 11589 APInt NewFromMask = FromMask1 | FromMask2; 11590 APInt NewToMask = ToMask1 | ToMask2; 11591 11592 EVT VT = N->getValueType(0); 11593 SDLoc dl(N); 11594 11595 if (NewFromMask[0] == 0) 11596 From1 = DCI.DAG.getNode( 11597 ISD::SRL, dl, VT, From1, 11598 DCI.DAG.getConstant(NewFromMask.countTrailingZeros(), dl, VT)); 11599 return DCI.DAG.getNode(ARMISD::BFI, dl, VT, N->getOperand(0), From1, 11600 DCI.DAG.getConstant(~NewToMask, dl, VT)); 11601 } 11602 return SDValue(); 11603 } 11604 11605 /// PerformVMOVRRDCombine - Target-specific dag combine xforms for 11606 /// ARMISD::VMOVRRD. 11607 static SDValue PerformVMOVRRDCombine(SDNode *N, 11608 TargetLowering::DAGCombinerInfo &DCI, 11609 const ARMSubtarget *Subtarget) { 11610 // vmovrrd(vmovdrr x, y) -> x,y 11611 SDValue InDouble = N->getOperand(0); 11612 if (InDouble.getOpcode() == ARMISD::VMOVDRR && Subtarget->hasFP64()) 11613 return DCI.CombineTo(N, InDouble.getOperand(0), InDouble.getOperand(1)); 11614 11615 // vmovrrd(load f64) -> (load i32), (load i32) 11616 SDNode *InNode = InDouble.getNode(); 11617 if (ISD::isNormalLoad(InNode) && InNode->hasOneUse() && 11618 InNode->getValueType(0) == MVT::f64 && 11619 InNode->getOperand(1).getOpcode() == ISD::FrameIndex && 11620 !cast<LoadSDNode>(InNode)->isVolatile()) { 11621 // TODO: Should this be done for non-FrameIndex operands? 11622 LoadSDNode *LD = cast<LoadSDNode>(InNode); 11623 11624 SelectionDAG &DAG = DCI.DAG; 11625 SDLoc DL(LD); 11626 SDValue BasePtr = LD->getBasePtr(); 11627 SDValue NewLD1 = 11628 DAG.getLoad(MVT::i32, DL, LD->getChain(), BasePtr, LD->getPointerInfo(), 11629 LD->getAlignment(), LD->getMemOperand()->getFlags()); 11630 11631 SDValue OffsetPtr = DAG.getNode(ISD::ADD, DL, MVT::i32, BasePtr, 11632 DAG.getConstant(4, DL, MVT::i32)); 11633 SDValue NewLD2 = DAG.getLoad( 11634 MVT::i32, DL, NewLD1.getValue(1), OffsetPtr, LD->getPointerInfo(), 11635 std::min(4U, LD->getAlignment() / 2), LD->getMemOperand()->getFlags()); 11636 11637 DAG.ReplaceAllUsesOfValueWith(SDValue(LD, 1), NewLD2.getValue(1)); 11638 if (DCI.DAG.getDataLayout().isBigEndian()) 11639 std::swap (NewLD1, NewLD2); 11640 SDValue Result = DCI.CombineTo(N, NewLD1, NewLD2); 11641 return Result; 11642 } 11643 11644 return SDValue(); 11645 } 11646 11647 /// PerformVMOVDRRCombine - Target-specific dag combine xforms for 11648 /// ARMISD::VMOVDRR. This is also used for BUILD_VECTORs with 2 operands. 11649 static SDValue PerformVMOVDRRCombine(SDNode *N, SelectionDAG &DAG) { 11650 // N=vmovrrd(X); vmovdrr(N:0, N:1) -> bit_convert(X) 11651 SDValue Op0 = N->getOperand(0); 11652 SDValue Op1 = N->getOperand(1); 11653 if (Op0.getOpcode() == ISD::BITCAST) 11654 Op0 = Op0.getOperand(0); 11655 if (Op1.getOpcode() == ISD::BITCAST) 11656 Op1 = Op1.getOperand(0); 11657 if (Op0.getOpcode() == ARMISD::VMOVRRD && 11658 Op0.getNode() == Op1.getNode() && 11659 Op0.getResNo() == 0 && Op1.getResNo() == 1) 11660 return DAG.getNode(ISD::BITCAST, SDLoc(N), 11661 N->getValueType(0), Op0.getOperand(0)); 11662 return SDValue(); 11663 } 11664 11665 /// hasNormalLoadOperand - Check if any of the operands of a BUILD_VECTOR node 11666 /// are normal, non-volatile loads. If so, it is profitable to bitcast an 11667 /// i64 vector to have f64 elements, since the value can then be loaded 11668 /// directly into a VFP register. 11669 static bool hasNormalLoadOperand(SDNode *N) { 11670 unsigned NumElts = N->getValueType(0).getVectorNumElements(); 11671 for (unsigned i = 0; i < NumElts; ++i) { 11672 SDNode *Elt = N->getOperand(i).getNode(); 11673 if (ISD::isNormalLoad(Elt) && !cast<LoadSDNode>(Elt)->isVolatile()) 11674 return true; 11675 } 11676 return false; 11677 } 11678 11679 /// PerformBUILD_VECTORCombine - Target-specific dag combine xforms for 11680 /// ISD::BUILD_VECTOR. 11681 static SDValue PerformBUILD_VECTORCombine(SDNode *N, 11682 TargetLowering::DAGCombinerInfo &DCI, 11683 const ARMSubtarget *Subtarget) { 11684 // build_vector(N=ARMISD::VMOVRRD(X), N:1) -> bit_convert(X): 11685 // VMOVRRD is introduced when legalizing i64 types. It forces the i64 value 11686 // into a pair of GPRs, which is fine when the value is used as a scalar, 11687 // but if the i64 value is converted to a vector, we need to undo the VMOVRRD. 11688 SelectionDAG &DAG = DCI.DAG; 11689 if (N->getNumOperands() == 2) 11690 if (SDValue RV = PerformVMOVDRRCombine(N, DAG)) 11691 return RV; 11692 11693 // Load i64 elements as f64 values so that type legalization does not split 11694 // them up into i32 values. 11695 EVT VT = N->getValueType(0); 11696 if (VT.getVectorElementType() != MVT::i64 || !hasNormalLoadOperand(N)) 11697 return SDValue(); 11698 SDLoc dl(N); 11699 SmallVector<SDValue, 8> Ops; 11700 unsigned NumElts = VT.getVectorNumElements(); 11701 for (unsigned i = 0; i < NumElts; ++i) { 11702 SDValue V = DAG.getNode(ISD::BITCAST, dl, MVT::f64, N->getOperand(i)); 11703 Ops.push_back(V); 11704 // Make the DAGCombiner fold the bitcast. 11705 DCI.AddToWorklist(V.getNode()); 11706 } 11707 EVT FloatVT = EVT::getVectorVT(*DAG.getContext(), MVT::f64, NumElts); 11708 SDValue BV = DAG.getBuildVector(FloatVT, dl, Ops); 11709 return DAG.getNode(ISD::BITCAST, dl, VT, BV); 11710 } 11711 11712 /// Target-specific dag combine xforms for ARMISD::BUILD_VECTOR. 11713 static SDValue 11714 PerformARMBUILD_VECTORCombine(SDNode *N, TargetLowering::DAGCombinerInfo &DCI) { 11715 // ARMISD::BUILD_VECTOR is introduced when legalizing ISD::BUILD_VECTOR. 11716 // At that time, we may have inserted bitcasts from integer to float. 11717 // If these bitcasts have survived DAGCombine, change the lowering of this 11718 // BUILD_VECTOR in something more vector friendly, i.e., that does not 11719 // force to use floating point types. 11720 11721 // Make sure we can change the type of the vector. 11722 // This is possible iff: 11723 // 1. The vector is only used in a bitcast to a integer type. I.e., 11724 // 1.1. Vector is used only once. 11725 // 1.2. Use is a bit convert to an integer type. 11726 // 2. The size of its operands are 32-bits (64-bits are not legal). 11727 EVT VT = N->getValueType(0); 11728 EVT EltVT = VT.getVectorElementType(); 11729 11730 // Check 1.1. and 2. 11731 if (EltVT.getSizeInBits() != 32 || !N->hasOneUse()) 11732 return SDValue(); 11733 11734 // By construction, the input type must be float. 11735 assert(EltVT == MVT::f32 && "Unexpected type!"); 11736 11737 // Check 1.2. 11738 SDNode *Use = *N->use_begin(); 11739 if (Use->getOpcode() != ISD::BITCAST || 11740 Use->getValueType(0).isFloatingPoint()) 11741 return SDValue(); 11742 11743 // Check profitability. 11744 // Model is, if more than half of the relevant operands are bitcast from 11745 // i32, turn the build_vector into a sequence of insert_vector_elt. 11746 // Relevant operands are everything that is not statically 11747 // (i.e., at compile time) bitcasted. 11748 unsigned NumOfBitCastedElts = 0; 11749 unsigned NumElts = VT.getVectorNumElements(); 11750 unsigned NumOfRelevantElts = NumElts; 11751 for (unsigned Idx = 0; Idx < NumElts; ++Idx) { 11752 SDValue Elt = N->getOperand(Idx); 11753 if (Elt->getOpcode() == ISD::BITCAST) { 11754 // Assume only bit cast to i32 will go away. 11755 if (Elt->getOperand(0).getValueType() == MVT::i32) 11756 ++NumOfBitCastedElts; 11757 } else if (Elt.isUndef() || isa<ConstantSDNode>(Elt)) 11758 // Constants are statically casted, thus do not count them as 11759 // relevant operands. 11760 --NumOfRelevantElts; 11761 } 11762 11763 // Check if more than half of the elements require a non-free bitcast. 11764 if (NumOfBitCastedElts <= NumOfRelevantElts / 2) 11765 return SDValue(); 11766 11767 SelectionDAG &DAG = DCI.DAG; 11768 // Create the new vector type. 11769 EVT VecVT = EVT::getVectorVT(*DAG.getContext(), MVT::i32, NumElts); 11770 // Check if the type is legal. 11771 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 11772 if (!TLI.isTypeLegal(VecVT)) 11773 return SDValue(); 11774 11775 // Combine: 11776 // ARMISD::BUILD_VECTOR E1, E2, ..., EN. 11777 // => BITCAST INSERT_VECTOR_ELT 11778 // (INSERT_VECTOR_ELT (...), (BITCAST EN-1), N-1), 11779 // (BITCAST EN), N. 11780 SDValue Vec = DAG.getUNDEF(VecVT); 11781 SDLoc dl(N); 11782 for (unsigned Idx = 0 ; Idx < NumElts; ++Idx) { 11783 SDValue V = N->getOperand(Idx); 11784 if (V.isUndef()) 11785 continue; 11786 if (V.getOpcode() == ISD::BITCAST && 11787 V->getOperand(0).getValueType() == MVT::i32) 11788 // Fold obvious case. 11789 V = V.getOperand(0); 11790 else { 11791 V = DAG.getNode(ISD::BITCAST, SDLoc(V), MVT::i32, V); 11792 // Make the DAGCombiner fold the bitcasts. 11793 DCI.AddToWorklist(V.getNode()); 11794 } 11795 SDValue LaneIdx = DAG.getConstant(Idx, dl, MVT::i32); 11796 Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VecVT, Vec, V, LaneIdx); 11797 } 11798 Vec = DAG.getNode(ISD::BITCAST, dl, VT, Vec); 11799 // Make the DAGCombiner fold the bitcasts. 11800 DCI.AddToWorklist(Vec.getNode()); 11801 return Vec; 11802 } 11803 11804 /// PerformInsertEltCombine - Target-specific dag combine xforms for 11805 /// ISD::INSERT_VECTOR_ELT. 11806 static SDValue PerformInsertEltCombine(SDNode *N, 11807 TargetLowering::DAGCombinerInfo &DCI) { 11808 // Bitcast an i64 load inserted into a vector to f64. 11809 // Otherwise, the i64 value will be legalized to a pair of i32 values. 11810 EVT VT = N->getValueType(0); 11811 SDNode *Elt = N->getOperand(1).getNode(); 11812 if (VT.getVectorElementType() != MVT::i64 || 11813 !ISD::isNormalLoad(Elt) || cast<LoadSDNode>(Elt)->isVolatile()) 11814 return SDValue(); 11815 11816 SelectionDAG &DAG = DCI.DAG; 11817 SDLoc dl(N); 11818 EVT FloatVT = EVT::getVectorVT(*DAG.getContext(), MVT::f64, 11819 VT.getVectorNumElements()); 11820 SDValue Vec = DAG.getNode(ISD::BITCAST, dl, FloatVT, N->getOperand(0)); 11821 SDValue V = DAG.getNode(ISD::BITCAST, dl, MVT::f64, N->getOperand(1)); 11822 // Make the DAGCombiner fold the bitcasts. 11823 DCI.AddToWorklist(Vec.getNode()); 11824 DCI.AddToWorklist(V.getNode()); 11825 SDValue InsElt = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, FloatVT, 11826 Vec, V, N->getOperand(2)); 11827 return DAG.getNode(ISD::BITCAST, dl, VT, InsElt); 11828 } 11829 11830 /// PerformVECTOR_SHUFFLECombine - Target-specific dag combine xforms for 11831 /// ISD::VECTOR_SHUFFLE. 11832 static SDValue PerformVECTOR_SHUFFLECombine(SDNode *N, SelectionDAG &DAG) { 11833 // The LLVM shufflevector instruction does not require the shuffle mask 11834 // length to match the operand vector length, but ISD::VECTOR_SHUFFLE does 11835 // have that requirement. When translating to ISD::VECTOR_SHUFFLE, if the 11836 // operands do not match the mask length, they are extended by concatenating 11837 // them with undef vectors. That is probably the right thing for other 11838 // targets, but for NEON it is better to concatenate two double-register 11839 // size vector operands into a single quad-register size vector. Do that 11840 // transformation here: 11841 // shuffle(concat(v1, undef), concat(v2, undef)) -> 11842 // shuffle(concat(v1, v2), undef) 11843 SDValue Op0 = N->getOperand(0); 11844 SDValue Op1 = N->getOperand(1); 11845 if (Op0.getOpcode() != ISD::CONCAT_VECTORS || 11846 Op1.getOpcode() != ISD::CONCAT_VECTORS || 11847 Op0.getNumOperands() != 2 || 11848 Op1.getNumOperands() != 2) 11849 return SDValue(); 11850 SDValue Concat0Op1 = Op0.getOperand(1); 11851 SDValue Concat1Op1 = Op1.getOperand(1); 11852 if (!Concat0Op1.isUndef() || !Concat1Op1.isUndef()) 11853 return SDValue(); 11854 // Skip the transformation if any of the types are illegal. 11855 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 11856 EVT VT = N->getValueType(0); 11857 if (!TLI.isTypeLegal(VT) || 11858 !TLI.isTypeLegal(Concat0Op1.getValueType()) || 11859 !TLI.isTypeLegal(Concat1Op1.getValueType())) 11860 return SDValue(); 11861 11862 SDValue NewConcat = DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT, 11863 Op0.getOperand(0), Op1.getOperand(0)); 11864 // Translate the shuffle mask. 11865 SmallVector<int, 16> NewMask; 11866 unsigned NumElts = VT.getVectorNumElements(); 11867 unsigned HalfElts = NumElts/2; 11868 ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N); 11869 for (unsigned n = 0; n < NumElts; ++n) { 11870 int MaskElt = SVN->getMaskElt(n); 11871 int NewElt = -1; 11872 if (MaskElt < (int)HalfElts) 11873 NewElt = MaskElt; 11874 else if (MaskElt >= (int)NumElts && MaskElt < (int)(NumElts + HalfElts)) 11875 NewElt = HalfElts + MaskElt - NumElts; 11876 NewMask.push_back(NewElt); 11877 } 11878 return DAG.getVectorShuffle(VT, SDLoc(N), NewConcat, 11879 DAG.getUNDEF(VT), NewMask); 11880 } 11881 11882 /// CombineBaseUpdate - Target-specific DAG combine function for VLDDUP, 11883 /// NEON load/store intrinsics, and generic vector load/stores, to merge 11884 /// base address updates. 11885 /// For generic load/stores, the memory type is assumed to be a vector. 11886 /// The caller is assumed to have checked legality. 11887 static SDValue CombineBaseUpdate(SDNode *N, 11888 TargetLowering::DAGCombinerInfo &DCI) { 11889 SelectionDAG &DAG = DCI.DAG; 11890 const bool isIntrinsic = (N->getOpcode() == ISD::INTRINSIC_VOID || 11891 N->getOpcode() == ISD::INTRINSIC_W_CHAIN); 11892 const bool isStore = N->getOpcode() == ISD::STORE; 11893 const unsigned AddrOpIdx = ((isIntrinsic || isStore) ? 2 : 1); 11894 SDValue Addr = N->getOperand(AddrOpIdx); 11895 MemSDNode *MemN = cast<MemSDNode>(N); 11896 SDLoc dl(N); 11897 11898 // Search for a use of the address operand that is an increment. 11899 for (SDNode::use_iterator UI = Addr.getNode()->use_begin(), 11900 UE = Addr.getNode()->use_end(); UI != UE; ++UI) { 11901 SDNode *User = *UI; 11902 if (User->getOpcode() != ISD::ADD || 11903 UI.getUse().getResNo() != Addr.getResNo()) 11904 continue; 11905 11906 // Check that the add is independent of the load/store. Otherwise, folding 11907 // it would create a cycle. We can avoid searching through Addr as it's a 11908 // predecessor to both. 11909 SmallPtrSet<const SDNode *, 32> Visited; 11910 SmallVector<const SDNode *, 16> Worklist; 11911 Visited.insert(Addr.getNode()); 11912 Worklist.push_back(N); 11913 Worklist.push_back(User); 11914 if (SDNode::hasPredecessorHelper(N, Visited, Worklist) || 11915 SDNode::hasPredecessorHelper(User, Visited, Worklist)) 11916 continue; 11917 11918 // Find the new opcode for the updating load/store. 11919 bool isLoadOp = true; 11920 bool isLaneOp = false; 11921 unsigned NewOpc = 0; 11922 unsigned NumVecs = 0; 11923 if (isIntrinsic) { 11924 unsigned IntNo = cast<ConstantSDNode>(N->getOperand(1))->getZExtValue(); 11925 switch (IntNo) { 11926 default: llvm_unreachable("unexpected intrinsic for Neon base update"); 11927 case Intrinsic::arm_neon_vld1: NewOpc = ARMISD::VLD1_UPD; 11928 NumVecs = 1; break; 11929 case Intrinsic::arm_neon_vld2: NewOpc = ARMISD::VLD2_UPD; 11930 NumVecs = 2; break; 11931 case Intrinsic::arm_neon_vld3: NewOpc = ARMISD::VLD3_UPD; 11932 NumVecs = 3; break; 11933 case Intrinsic::arm_neon_vld4: NewOpc = ARMISD::VLD4_UPD; 11934 NumVecs = 4; break; 11935 case Intrinsic::arm_neon_vld2dup: 11936 case Intrinsic::arm_neon_vld3dup: 11937 case Intrinsic::arm_neon_vld4dup: 11938 // TODO: Support updating VLDxDUP nodes. For now, we just skip 11939 // combining base updates for such intrinsics. 11940 continue; 11941 case Intrinsic::arm_neon_vld2lane: NewOpc = ARMISD::VLD2LN_UPD; 11942 NumVecs = 2; isLaneOp = true; break; 11943 case Intrinsic::arm_neon_vld3lane: NewOpc = ARMISD::VLD3LN_UPD; 11944 NumVecs = 3; isLaneOp = true; break; 11945 case Intrinsic::arm_neon_vld4lane: NewOpc = ARMISD::VLD4LN_UPD; 11946 NumVecs = 4; isLaneOp = true; break; 11947 case Intrinsic::arm_neon_vst1: NewOpc = ARMISD::VST1_UPD; 11948 NumVecs = 1; isLoadOp = false; break; 11949 case Intrinsic::arm_neon_vst2: NewOpc = ARMISD::VST2_UPD; 11950 NumVecs = 2; isLoadOp = false; break; 11951 case Intrinsic::arm_neon_vst3: NewOpc = ARMISD::VST3_UPD; 11952 NumVecs = 3; isLoadOp = false; break; 11953 case Intrinsic::arm_neon_vst4: NewOpc = ARMISD::VST4_UPD; 11954 NumVecs = 4; isLoadOp = false; break; 11955 case Intrinsic::arm_neon_vst2lane: NewOpc = ARMISD::VST2LN_UPD; 11956 NumVecs = 2; isLoadOp = false; isLaneOp = true; break; 11957 case Intrinsic::arm_neon_vst3lane: NewOpc = ARMISD::VST3LN_UPD; 11958 NumVecs = 3; isLoadOp = false; isLaneOp = true; break; 11959 case Intrinsic::arm_neon_vst4lane: NewOpc = ARMISD::VST4LN_UPD; 11960 NumVecs = 4; isLoadOp = false; isLaneOp = true; break; 11961 } 11962 } else { 11963 isLaneOp = true; 11964 switch (N->getOpcode()) { 11965 default: llvm_unreachable("unexpected opcode for Neon base update"); 11966 case ARMISD::VLD1DUP: NewOpc = ARMISD::VLD1DUP_UPD; NumVecs = 1; break; 11967 case ARMISD::VLD2DUP: NewOpc = ARMISD::VLD2DUP_UPD; NumVecs = 2; break; 11968 case ARMISD::VLD3DUP: NewOpc = ARMISD::VLD3DUP_UPD; NumVecs = 3; break; 11969 case ARMISD::VLD4DUP: NewOpc = ARMISD::VLD4DUP_UPD; NumVecs = 4; break; 11970 case ISD::LOAD: NewOpc = ARMISD::VLD1_UPD; 11971 NumVecs = 1; isLaneOp = false; break; 11972 case ISD::STORE: NewOpc = ARMISD::VST1_UPD; 11973 NumVecs = 1; isLaneOp = false; isLoadOp = false; break; 11974 } 11975 } 11976 11977 // Find the size of memory referenced by the load/store. 11978 EVT VecTy; 11979 if (isLoadOp) { 11980 VecTy = N->getValueType(0); 11981 } else if (isIntrinsic) { 11982 VecTy = N->getOperand(AddrOpIdx+1).getValueType(); 11983 } else { 11984 assert(isStore && "Node has to be a load, a store, or an intrinsic!"); 11985 VecTy = N->getOperand(1).getValueType(); 11986 } 11987 11988 unsigned NumBytes = NumVecs * VecTy.getSizeInBits() / 8; 11989 if (isLaneOp) 11990 NumBytes /= VecTy.getVectorNumElements(); 11991 11992 // If the increment is a constant, it must match the memory ref size. 11993 SDValue Inc = User->getOperand(User->getOperand(0) == Addr ? 1 : 0); 11994 ConstantSDNode *CInc = dyn_cast<ConstantSDNode>(Inc.getNode()); 11995 if (NumBytes >= 3 * 16 && (!CInc || CInc->getZExtValue() != NumBytes)) { 11996 // VLD3/4 and VST3/4 for 128-bit vectors are implemented with two 11997 // separate instructions that make it harder to use a non-constant update. 11998 continue; 11999 } 12000 12001 // OK, we found an ADD we can fold into the base update. 12002 // Now, create a _UPD node, taking care of not breaking alignment. 12003 12004 EVT AlignedVecTy = VecTy; 12005 unsigned Alignment = MemN->getAlignment(); 12006 12007 // If this is a less-than-standard-aligned load/store, change the type to 12008 // match the standard alignment. 12009 // The alignment is overlooked when selecting _UPD variants; and it's 12010 // easier to introduce bitcasts here than fix that. 12011 // There are 3 ways to get to this base-update combine: 12012 // - intrinsics: they are assumed to be properly aligned (to the standard 12013 // alignment of the memory type), so we don't need to do anything. 12014 // - ARMISD::VLDx nodes: they are only generated from the aforementioned 12015 // intrinsics, so, likewise, there's nothing to do. 12016 // - generic load/store instructions: the alignment is specified as an 12017 // explicit operand, rather than implicitly as the standard alignment 12018 // of the memory type (like the intrisics). We need to change the 12019 // memory type to match the explicit alignment. That way, we don't 12020 // generate non-standard-aligned ARMISD::VLDx nodes. 12021 if (isa<LSBaseSDNode>(N)) { 12022 if (Alignment == 0) 12023 Alignment = 1; 12024 if (Alignment < VecTy.getScalarSizeInBits() / 8) { 12025 MVT EltTy = MVT::getIntegerVT(Alignment * 8); 12026 assert(NumVecs == 1 && "Unexpected multi-element generic load/store."); 12027 assert(!isLaneOp && "Unexpected generic load/store lane."); 12028 unsigned NumElts = NumBytes / (EltTy.getSizeInBits() / 8); 12029 AlignedVecTy = MVT::getVectorVT(EltTy, NumElts); 12030 } 12031 // Don't set an explicit alignment on regular load/stores that we want 12032 // to transform to VLD/VST 1_UPD nodes. 12033 // This matches the behavior of regular load/stores, which only get an 12034 // explicit alignment if the MMO alignment is larger than the standard 12035 // alignment of the memory type. 12036 // Intrinsics, however, always get an explicit alignment, set to the 12037 // alignment of the MMO. 12038 Alignment = 1; 12039 } 12040 12041 // Create the new updating load/store node. 12042 // First, create an SDVTList for the new updating node's results. 12043 EVT Tys[6]; 12044 unsigned NumResultVecs = (isLoadOp ? NumVecs : 0); 12045 unsigned n; 12046 for (n = 0; n < NumResultVecs; ++n) 12047 Tys[n] = AlignedVecTy; 12048 Tys[n++] = MVT::i32; 12049 Tys[n] = MVT::Other; 12050 SDVTList SDTys = DAG.getVTList(makeArrayRef(Tys, NumResultVecs+2)); 12051 12052 // Then, gather the new node's operands. 12053 SmallVector<SDValue, 8> Ops; 12054 Ops.push_back(N->getOperand(0)); // incoming chain 12055 Ops.push_back(N->getOperand(AddrOpIdx)); 12056 Ops.push_back(Inc); 12057 12058 if (StoreSDNode *StN = dyn_cast<StoreSDNode>(N)) { 12059 // Try to match the intrinsic's signature 12060 Ops.push_back(StN->getValue()); 12061 } else { 12062 // Loads (and of course intrinsics) match the intrinsics' signature, 12063 // so just add all but the alignment operand. 12064 for (unsigned i = AddrOpIdx + 1; i < N->getNumOperands() - 1; ++i) 12065 Ops.push_back(N->getOperand(i)); 12066 } 12067 12068 // For all node types, the alignment operand is always the last one. 12069 Ops.push_back(DAG.getConstant(Alignment, dl, MVT::i32)); 12070 12071 // If this is a non-standard-aligned STORE, the penultimate operand is the 12072 // stored value. Bitcast it to the aligned type. 12073 if (AlignedVecTy != VecTy && N->getOpcode() == ISD::STORE) { 12074 SDValue &StVal = Ops[Ops.size()-2]; 12075 StVal = DAG.getNode(ISD::BITCAST, dl, AlignedVecTy, StVal); 12076 } 12077 12078 EVT LoadVT = isLaneOp ? VecTy.getVectorElementType() : AlignedVecTy; 12079 SDValue UpdN = DAG.getMemIntrinsicNode(NewOpc, dl, SDTys, Ops, LoadVT, 12080 MemN->getMemOperand()); 12081 12082 // Update the uses. 12083 SmallVector<SDValue, 5> NewResults; 12084 for (unsigned i = 0; i < NumResultVecs; ++i) 12085 NewResults.push_back(SDValue(UpdN.getNode(), i)); 12086 12087 // If this is an non-standard-aligned LOAD, the first result is the loaded 12088 // value. Bitcast it to the expected result type. 12089 if (AlignedVecTy != VecTy && N->getOpcode() == ISD::LOAD) { 12090 SDValue &LdVal = NewResults[0]; 12091 LdVal = DAG.getNode(ISD::BITCAST, dl, VecTy, LdVal); 12092 } 12093 12094 NewResults.push_back(SDValue(UpdN.getNode(), NumResultVecs+1)); // chain 12095 DCI.CombineTo(N, NewResults); 12096 DCI.CombineTo(User, SDValue(UpdN.getNode(), NumResultVecs)); 12097 12098 break; 12099 } 12100 return SDValue(); 12101 } 12102 12103 static SDValue PerformVLDCombine(SDNode *N, 12104 TargetLowering::DAGCombinerInfo &DCI) { 12105 if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer()) 12106 return SDValue(); 12107 12108 return CombineBaseUpdate(N, DCI); 12109 } 12110 12111 /// CombineVLDDUP - For a VDUPLANE node N, check if its source operand is a 12112 /// vldN-lane (N > 1) intrinsic, and if all the other uses of that intrinsic 12113 /// are also VDUPLANEs. If so, combine them to a vldN-dup operation and 12114 /// return true. 12115 static bool CombineVLDDUP(SDNode *N, TargetLowering::DAGCombinerInfo &DCI) { 12116 SelectionDAG &DAG = DCI.DAG; 12117 EVT VT = N->getValueType(0); 12118 // vldN-dup instructions only support 64-bit vectors for N > 1. 12119 if (!VT.is64BitVector()) 12120 return false; 12121 12122 // Check if the VDUPLANE operand is a vldN-dup intrinsic. 12123 SDNode *VLD = N->getOperand(0).getNode(); 12124 if (VLD->getOpcode() != ISD::INTRINSIC_W_CHAIN) 12125 return false; 12126 unsigned NumVecs = 0; 12127 unsigned NewOpc = 0; 12128 unsigned IntNo = cast<ConstantSDNode>(VLD->getOperand(1))->getZExtValue(); 12129 if (IntNo == Intrinsic::arm_neon_vld2lane) { 12130 NumVecs = 2; 12131 NewOpc = ARMISD::VLD2DUP; 12132 } else if (IntNo == Intrinsic::arm_neon_vld3lane) { 12133 NumVecs = 3; 12134 NewOpc = ARMISD::VLD3DUP; 12135 } else if (IntNo == Intrinsic::arm_neon_vld4lane) { 12136 NumVecs = 4; 12137 NewOpc = ARMISD::VLD4DUP; 12138 } else { 12139 return false; 12140 } 12141 12142 // First check that all the vldN-lane uses are VDUPLANEs and that the lane 12143 // numbers match the load. 12144 unsigned VLDLaneNo = 12145 cast<ConstantSDNode>(VLD->getOperand(NumVecs+3))->getZExtValue(); 12146 for (SDNode::use_iterator UI = VLD->use_begin(), UE = VLD->use_end(); 12147 UI != UE; ++UI) { 12148 // Ignore uses of the chain result. 12149 if (UI.getUse().getResNo() == NumVecs) 12150 continue; 12151 SDNode *User = *UI; 12152 if (User->getOpcode() != ARMISD::VDUPLANE || 12153 VLDLaneNo != cast<ConstantSDNode>(User->getOperand(1))->getZExtValue()) 12154 return false; 12155 } 12156 12157 // Create the vldN-dup node. 12158 EVT Tys[5]; 12159 unsigned n; 12160 for (n = 0; n < NumVecs; ++n) 12161 Tys[n] = VT; 12162 Tys[n] = MVT::Other; 12163 SDVTList SDTys = DAG.getVTList(makeArrayRef(Tys, NumVecs+1)); 12164 SDValue Ops[] = { VLD->getOperand(0), VLD->getOperand(2) }; 12165 MemIntrinsicSDNode *VLDMemInt = cast<MemIntrinsicSDNode>(VLD); 12166 SDValue VLDDup = DAG.getMemIntrinsicNode(NewOpc, SDLoc(VLD), SDTys, 12167 Ops, VLDMemInt->getMemoryVT(), 12168 VLDMemInt->getMemOperand()); 12169 12170 // Update the uses. 12171 for (SDNode::use_iterator UI = VLD->use_begin(), UE = VLD->use_end(); 12172 UI != UE; ++UI) { 12173 unsigned ResNo = UI.getUse().getResNo(); 12174 // Ignore uses of the chain result. 12175 if (ResNo == NumVecs) 12176 continue; 12177 SDNode *User = *UI; 12178 DCI.CombineTo(User, SDValue(VLDDup.getNode(), ResNo)); 12179 } 12180 12181 // Now the vldN-lane intrinsic is dead except for its chain result. 12182 // Update uses of the chain. 12183 std::vector<SDValue> VLDDupResults; 12184 for (unsigned n = 0; n < NumVecs; ++n) 12185 VLDDupResults.push_back(SDValue(VLDDup.getNode(), n)); 12186 VLDDupResults.push_back(SDValue(VLDDup.getNode(), NumVecs)); 12187 DCI.CombineTo(VLD, VLDDupResults); 12188 12189 return true; 12190 } 12191 12192 /// PerformVDUPLANECombine - Target-specific dag combine xforms for 12193 /// ARMISD::VDUPLANE. 12194 static SDValue PerformVDUPLANECombine(SDNode *N, 12195 TargetLowering::DAGCombinerInfo &DCI) { 12196 SDValue Op = N->getOperand(0); 12197 12198 // If the source is a vldN-lane (N > 1) intrinsic, and all the other uses 12199 // of that intrinsic are also VDUPLANEs, combine them to a vldN-dup operation. 12200 if (CombineVLDDUP(N, DCI)) 12201 return SDValue(N, 0); 12202 12203 // If the source is already a VMOVIMM or VMVNIMM splat, the VDUPLANE is 12204 // redundant. Ignore bit_converts for now; element sizes are checked below. 12205 while (Op.getOpcode() == ISD::BITCAST) 12206 Op = Op.getOperand(0); 12207 if (Op.getOpcode() != ARMISD::VMOVIMM && Op.getOpcode() != ARMISD::VMVNIMM) 12208 return SDValue(); 12209 12210 // Make sure the VMOV element size is not bigger than the VDUPLANE elements. 12211 unsigned EltSize = Op.getScalarValueSizeInBits(); 12212 // The canonical VMOV for a zero vector uses a 32-bit element size. 12213 unsigned Imm = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue(); 12214 unsigned EltBits; 12215 if (ARM_AM::decodeNEONModImm(Imm, EltBits) == 0) 12216 EltSize = 8; 12217 EVT VT = N->getValueType(0); 12218 if (EltSize > VT.getScalarSizeInBits()) 12219 return SDValue(); 12220 12221 return DCI.DAG.getNode(ISD::BITCAST, SDLoc(N), VT, Op); 12222 } 12223 12224 /// PerformVDUPCombine - Target-specific dag combine xforms for ARMISD::VDUP. 12225 static SDValue PerformVDUPCombine(SDNode *N, 12226 TargetLowering::DAGCombinerInfo &DCI, 12227 const ARMSubtarget *Subtarget) { 12228 SelectionDAG &DAG = DCI.DAG; 12229 SDValue Op = N->getOperand(0); 12230 12231 if (!Subtarget->hasNEON()) 12232 return SDValue(); 12233 12234 // Match VDUP(LOAD) -> VLD1DUP. 12235 // We match this pattern here rather than waiting for isel because the 12236 // transform is only legal for unindexed loads. 12237 LoadSDNode *LD = dyn_cast<LoadSDNode>(Op.getNode()); 12238 if (LD && Op.hasOneUse() && LD->isUnindexed() && 12239 LD->getMemoryVT() == N->getValueType(0).getVectorElementType()) { 12240 SDValue Ops[] = { LD->getOperand(0), LD->getOperand(1), 12241 DAG.getConstant(LD->getAlignment(), SDLoc(N), MVT::i32) }; 12242 SDVTList SDTys = DAG.getVTList(N->getValueType(0), MVT::Other); 12243 SDValue VLDDup = DAG.getMemIntrinsicNode(ARMISD::VLD1DUP, SDLoc(N), SDTys, 12244 Ops, LD->getMemoryVT(), 12245 LD->getMemOperand()); 12246 DAG.ReplaceAllUsesOfValueWith(SDValue(LD, 1), VLDDup.getValue(1)); 12247 return VLDDup; 12248 } 12249 12250 return SDValue(); 12251 } 12252 12253 static SDValue PerformLOADCombine(SDNode *N, 12254 TargetLowering::DAGCombinerInfo &DCI) { 12255 EVT VT = N->getValueType(0); 12256 12257 // If this is a legal vector load, try to combine it into a VLD1_UPD. 12258 if (ISD::isNormalLoad(N) && VT.isVector() && 12259 DCI.DAG.getTargetLoweringInfo().isTypeLegal(VT)) 12260 return CombineBaseUpdate(N, DCI); 12261 12262 return SDValue(); 12263 } 12264 12265 /// PerformSTORECombine - Target-specific dag combine xforms for 12266 /// ISD::STORE. 12267 static SDValue PerformSTORECombine(SDNode *N, 12268 TargetLowering::DAGCombinerInfo &DCI) { 12269 StoreSDNode *St = cast<StoreSDNode>(N); 12270 if (St->isVolatile()) 12271 return SDValue(); 12272 12273 // Optimize trunc store (of multiple scalars) to shuffle and store. First, 12274 // pack all of the elements in one place. Next, store to memory in fewer 12275 // chunks. 12276 SDValue StVal = St->getValue(); 12277 EVT VT = StVal.getValueType(); 12278 if (St->isTruncatingStore() && VT.isVector()) { 12279 SelectionDAG &DAG = DCI.DAG; 12280 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 12281 EVT StVT = St->getMemoryVT(); 12282 unsigned NumElems = VT.getVectorNumElements(); 12283 assert(StVT != VT && "Cannot truncate to the same type"); 12284 unsigned FromEltSz = VT.getScalarSizeInBits(); 12285 unsigned ToEltSz = StVT.getScalarSizeInBits(); 12286 12287 // From, To sizes and ElemCount must be pow of two 12288 if (!isPowerOf2_32(NumElems * FromEltSz * ToEltSz)) return SDValue(); 12289 12290 // We are going to use the original vector elt for storing. 12291 // Accumulated smaller vector elements must be a multiple of the store size. 12292 if (0 != (NumElems * FromEltSz) % ToEltSz) return SDValue(); 12293 12294 unsigned SizeRatio = FromEltSz / ToEltSz; 12295 assert(SizeRatio * NumElems * ToEltSz == VT.getSizeInBits()); 12296 12297 // Create a type on which we perform the shuffle. 12298 EVT WideVecVT = EVT::getVectorVT(*DAG.getContext(), StVT.getScalarType(), 12299 NumElems*SizeRatio); 12300 assert(WideVecVT.getSizeInBits() == VT.getSizeInBits()); 12301 12302 SDLoc DL(St); 12303 SDValue WideVec = DAG.getNode(ISD::BITCAST, DL, WideVecVT, StVal); 12304 SmallVector<int, 8> ShuffleVec(NumElems * SizeRatio, -1); 12305 for (unsigned i = 0; i < NumElems; ++i) 12306 ShuffleVec[i] = DAG.getDataLayout().isBigEndian() 12307 ? (i + 1) * SizeRatio - 1 12308 : i * SizeRatio; 12309 12310 // Can't shuffle using an illegal type. 12311 if (!TLI.isTypeLegal(WideVecVT)) return SDValue(); 12312 12313 SDValue Shuff = DAG.getVectorShuffle(WideVecVT, DL, WideVec, 12314 DAG.getUNDEF(WideVec.getValueType()), 12315 ShuffleVec); 12316 // At this point all of the data is stored at the bottom of the 12317 // register. We now need to save it to mem. 12318 12319 // Find the largest store unit 12320 MVT StoreType = MVT::i8; 12321 for (MVT Tp : MVT::integer_valuetypes()) { 12322 if (TLI.isTypeLegal(Tp) && Tp.getSizeInBits() <= NumElems * ToEltSz) 12323 StoreType = Tp; 12324 } 12325 // Didn't find a legal store type. 12326 if (!TLI.isTypeLegal(StoreType)) 12327 return SDValue(); 12328 12329 // Bitcast the original vector into a vector of store-size units 12330 EVT StoreVecVT = EVT::getVectorVT(*DAG.getContext(), 12331 StoreType, VT.getSizeInBits()/EVT(StoreType).getSizeInBits()); 12332 assert(StoreVecVT.getSizeInBits() == VT.getSizeInBits()); 12333 SDValue ShuffWide = DAG.getNode(ISD::BITCAST, DL, StoreVecVT, Shuff); 12334 SmallVector<SDValue, 8> Chains; 12335 SDValue Increment = DAG.getConstant(StoreType.getSizeInBits() / 8, DL, 12336 TLI.getPointerTy(DAG.getDataLayout())); 12337 SDValue BasePtr = St->getBasePtr(); 12338 12339 // Perform one or more big stores into memory. 12340 unsigned E = (ToEltSz*NumElems)/StoreType.getSizeInBits(); 12341 for (unsigned I = 0; I < E; I++) { 12342 SDValue SubVec = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, 12343 StoreType, ShuffWide, 12344 DAG.getIntPtrConstant(I, DL)); 12345 SDValue Ch = DAG.getStore(St->getChain(), DL, SubVec, BasePtr, 12346 St->getPointerInfo(), St->getAlignment(), 12347 St->getMemOperand()->getFlags()); 12348 BasePtr = DAG.getNode(ISD::ADD, DL, BasePtr.getValueType(), BasePtr, 12349 Increment); 12350 Chains.push_back(Ch); 12351 } 12352 return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Chains); 12353 } 12354 12355 if (!ISD::isNormalStore(St)) 12356 return SDValue(); 12357 12358 // Split a store of a VMOVDRR into two integer stores to avoid mixing NEON and 12359 // ARM stores of arguments in the same cache line. 12360 if (StVal.getNode()->getOpcode() == ARMISD::VMOVDRR && 12361 StVal.getNode()->hasOneUse()) { 12362 SelectionDAG &DAG = DCI.DAG; 12363 bool isBigEndian = DAG.getDataLayout().isBigEndian(); 12364 SDLoc DL(St); 12365 SDValue BasePtr = St->getBasePtr(); 12366 SDValue NewST1 = DAG.getStore( 12367 St->getChain(), DL, StVal.getNode()->getOperand(isBigEndian ? 1 : 0), 12368 BasePtr, St->getPointerInfo(), St->getAlignment(), 12369 St->getMemOperand()->getFlags()); 12370 12371 SDValue OffsetPtr = DAG.getNode(ISD::ADD, DL, MVT::i32, BasePtr, 12372 DAG.getConstant(4, DL, MVT::i32)); 12373 return DAG.getStore(NewST1.getValue(0), DL, 12374 StVal.getNode()->getOperand(isBigEndian ? 0 : 1), 12375 OffsetPtr, St->getPointerInfo(), 12376 std::min(4U, St->getAlignment() / 2), 12377 St->getMemOperand()->getFlags()); 12378 } 12379 12380 if (StVal.getValueType() == MVT::i64 && 12381 StVal.getNode()->getOpcode() == ISD::EXTRACT_VECTOR_ELT) { 12382 12383 // Bitcast an i64 store extracted from a vector to f64. 12384 // Otherwise, the i64 value will be legalized to a pair of i32 values. 12385 SelectionDAG &DAG = DCI.DAG; 12386 SDLoc dl(StVal); 12387 SDValue IntVec = StVal.getOperand(0); 12388 EVT FloatVT = EVT::getVectorVT(*DAG.getContext(), MVT::f64, 12389 IntVec.getValueType().getVectorNumElements()); 12390 SDValue Vec = DAG.getNode(ISD::BITCAST, dl, FloatVT, IntVec); 12391 SDValue ExtElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, 12392 Vec, StVal.getOperand(1)); 12393 dl = SDLoc(N); 12394 SDValue V = DAG.getNode(ISD::BITCAST, dl, MVT::i64, ExtElt); 12395 // Make the DAGCombiner fold the bitcasts. 12396 DCI.AddToWorklist(Vec.getNode()); 12397 DCI.AddToWorklist(ExtElt.getNode()); 12398 DCI.AddToWorklist(V.getNode()); 12399 return DAG.getStore(St->getChain(), dl, V, St->getBasePtr(), 12400 St->getPointerInfo(), St->getAlignment(), 12401 St->getMemOperand()->getFlags(), St->getAAInfo()); 12402 } 12403 12404 // If this is a legal vector store, try to combine it into a VST1_UPD. 12405 if (ISD::isNormalStore(N) && VT.isVector() && 12406 DCI.DAG.getTargetLoweringInfo().isTypeLegal(VT)) 12407 return CombineBaseUpdate(N, DCI); 12408 12409 return SDValue(); 12410 } 12411 12412 /// PerformVCVTCombine - VCVT (floating-point to fixed-point, Advanced SIMD) 12413 /// can replace combinations of VMUL and VCVT (floating-point to integer) 12414 /// when the VMUL has a constant operand that is a power of 2. 12415 /// 12416 /// Example (assume d17 = <float 8.000000e+00, float 8.000000e+00>): 12417 /// vmul.f32 d16, d17, d16 12418 /// vcvt.s32.f32 d16, d16 12419 /// becomes: 12420 /// vcvt.s32.f32 d16, d16, #3 12421 static SDValue PerformVCVTCombine(SDNode *N, SelectionDAG &DAG, 12422 const ARMSubtarget *Subtarget) { 12423 if (!Subtarget->hasNEON()) 12424 return SDValue(); 12425 12426 SDValue Op = N->getOperand(0); 12427 if (!Op.getValueType().isVector() || !Op.getValueType().isSimple() || 12428 Op.getOpcode() != ISD::FMUL) 12429 return SDValue(); 12430 12431 SDValue ConstVec = Op->getOperand(1); 12432 if (!isa<BuildVectorSDNode>(ConstVec)) 12433 return SDValue(); 12434 12435 MVT FloatTy = Op.getSimpleValueType().getVectorElementType(); 12436 uint32_t FloatBits = FloatTy.getSizeInBits(); 12437 MVT IntTy = N->getSimpleValueType(0).getVectorElementType(); 12438 uint32_t IntBits = IntTy.getSizeInBits(); 12439 unsigned NumLanes = Op.getValueType().getVectorNumElements(); 12440 if (FloatBits != 32 || IntBits > 32 || (NumLanes != 4 && NumLanes != 2)) { 12441 // These instructions only exist converting from f32 to i32. We can handle 12442 // smaller integers by generating an extra truncate, but larger ones would 12443 // be lossy. We also can't handle anything other than 2 or 4 lanes, since 12444 // these intructions only support v2i32/v4i32 types. 12445 return SDValue(); 12446 } 12447 12448 BitVector UndefElements; 12449 BuildVectorSDNode *BV = cast<BuildVectorSDNode>(ConstVec); 12450 int32_t C = BV->getConstantFPSplatPow2ToLog2Int(&UndefElements, 33); 12451 if (C == -1 || C == 0 || C > 32) 12452 return SDValue(); 12453 12454 SDLoc dl(N); 12455 bool isSigned = N->getOpcode() == ISD::FP_TO_SINT; 12456 unsigned IntrinsicOpcode = isSigned ? Intrinsic::arm_neon_vcvtfp2fxs : 12457 Intrinsic::arm_neon_vcvtfp2fxu; 12458 SDValue FixConv = DAG.getNode( 12459 ISD::INTRINSIC_WO_CHAIN, dl, NumLanes == 2 ? MVT::v2i32 : MVT::v4i32, 12460 DAG.getConstant(IntrinsicOpcode, dl, MVT::i32), Op->getOperand(0), 12461 DAG.getConstant(C, dl, MVT::i32)); 12462 12463 if (IntBits < FloatBits) 12464 FixConv = DAG.getNode(ISD::TRUNCATE, dl, N->getValueType(0), FixConv); 12465 12466 return FixConv; 12467 } 12468 12469 /// PerformVDIVCombine - VCVT (fixed-point to floating-point, Advanced SIMD) 12470 /// can replace combinations of VCVT (integer to floating-point) and VDIV 12471 /// when the VDIV has a constant operand that is a power of 2. 12472 /// 12473 /// Example (assume d17 = <float 8.000000e+00, float 8.000000e+00>): 12474 /// vcvt.f32.s32 d16, d16 12475 /// vdiv.f32 d16, d17, d16 12476 /// becomes: 12477 /// vcvt.f32.s32 d16, d16, #3 12478 static SDValue PerformVDIVCombine(SDNode *N, SelectionDAG &DAG, 12479 const ARMSubtarget *Subtarget) { 12480 if (!Subtarget->hasNEON()) 12481 return SDValue(); 12482 12483 SDValue Op = N->getOperand(0); 12484 unsigned OpOpcode = Op.getNode()->getOpcode(); 12485 if (!N->getValueType(0).isVector() || !N->getValueType(0).isSimple() || 12486 (OpOpcode != ISD::SINT_TO_FP && OpOpcode != ISD::UINT_TO_FP)) 12487 return SDValue(); 12488 12489 SDValue ConstVec = N->getOperand(1); 12490 if (!isa<BuildVectorSDNode>(ConstVec)) 12491 return SDValue(); 12492 12493 MVT FloatTy = N->getSimpleValueType(0).getVectorElementType(); 12494 uint32_t FloatBits = FloatTy.getSizeInBits(); 12495 MVT IntTy = Op.getOperand(0).getSimpleValueType().getVectorElementType(); 12496 uint32_t IntBits = IntTy.getSizeInBits(); 12497 unsigned NumLanes = Op.getValueType().getVectorNumElements(); 12498 if (FloatBits != 32 || IntBits > 32 || (NumLanes != 4 && NumLanes != 2)) { 12499 // These instructions only exist converting from i32 to f32. We can handle 12500 // smaller integers by generating an extra extend, but larger ones would 12501 // be lossy. We also can't handle anything other than 2 or 4 lanes, since 12502 // these intructions only support v2i32/v4i32 types. 12503 return SDValue(); 12504 } 12505 12506 BitVector UndefElements; 12507 BuildVectorSDNode *BV = cast<BuildVectorSDNode>(ConstVec); 12508 int32_t C = BV->getConstantFPSplatPow2ToLog2Int(&UndefElements, 33); 12509 if (C == -1 || C == 0 || C > 32) 12510 return SDValue(); 12511 12512 SDLoc dl(N); 12513 bool isSigned = OpOpcode == ISD::SINT_TO_FP; 12514 SDValue ConvInput = Op.getOperand(0); 12515 if (IntBits < FloatBits) 12516 ConvInput = DAG.getNode(isSigned ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND, 12517 dl, NumLanes == 2 ? MVT::v2i32 : MVT::v4i32, 12518 ConvInput); 12519 12520 unsigned IntrinsicOpcode = isSigned ? Intrinsic::arm_neon_vcvtfxs2fp : 12521 Intrinsic::arm_neon_vcvtfxu2fp; 12522 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, 12523 Op.getValueType(), 12524 DAG.getConstant(IntrinsicOpcode, dl, MVT::i32), 12525 ConvInput, DAG.getConstant(C, dl, MVT::i32)); 12526 } 12527 12528 /// Getvshiftimm - Check if this is a valid build_vector for the immediate 12529 /// operand of a vector shift operation, where all the elements of the 12530 /// build_vector must have the same constant integer value. 12531 static bool getVShiftImm(SDValue Op, unsigned ElementBits, int64_t &Cnt) { 12532 // Ignore bit_converts. 12533 while (Op.getOpcode() == ISD::BITCAST) 12534 Op = Op.getOperand(0); 12535 BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(Op.getNode()); 12536 APInt SplatBits, SplatUndef; 12537 unsigned SplatBitSize; 12538 bool HasAnyUndefs; 12539 if (! BVN || ! BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, 12540 HasAnyUndefs, ElementBits) || 12541 SplatBitSize > ElementBits) 12542 return false; 12543 Cnt = SplatBits.getSExtValue(); 12544 return true; 12545 } 12546 12547 /// isVShiftLImm - Check if this is a valid build_vector for the immediate 12548 /// operand of a vector shift left operation. That value must be in the range: 12549 /// 0 <= Value < ElementBits for a left shift; or 12550 /// 0 <= Value <= ElementBits for a long left shift. 12551 static bool isVShiftLImm(SDValue Op, EVT VT, bool isLong, int64_t &Cnt) { 12552 assert(VT.isVector() && "vector shift count is not a vector type"); 12553 int64_t ElementBits = VT.getScalarSizeInBits(); 12554 if (! getVShiftImm(Op, ElementBits, Cnt)) 12555 return false; 12556 return (Cnt >= 0 && (isLong ? Cnt-1 : Cnt) < ElementBits); 12557 } 12558 12559 /// isVShiftRImm - Check if this is a valid build_vector for the immediate 12560 /// operand of a vector shift right operation. For a shift opcode, the value 12561 /// is positive, but for an intrinsic the value count must be negative. The 12562 /// absolute value must be in the range: 12563 /// 1 <= |Value| <= ElementBits for a right shift; or 12564 /// 1 <= |Value| <= ElementBits/2 for a narrow right shift. 12565 static bool isVShiftRImm(SDValue Op, EVT VT, bool isNarrow, bool isIntrinsic, 12566 int64_t &Cnt) { 12567 assert(VT.isVector() && "vector shift count is not a vector type"); 12568 int64_t ElementBits = VT.getScalarSizeInBits(); 12569 if (! getVShiftImm(Op, ElementBits, Cnt)) 12570 return false; 12571 if (!isIntrinsic) 12572 return (Cnt >= 1 && Cnt <= (isNarrow ? ElementBits/2 : ElementBits)); 12573 if (Cnt >= -(isNarrow ? ElementBits/2 : ElementBits) && Cnt <= -1) { 12574 Cnt = -Cnt; 12575 return true; 12576 } 12577 return false; 12578 } 12579 12580 /// PerformIntrinsicCombine - ARM-specific DAG combining for intrinsics. 12581 static SDValue PerformIntrinsicCombine(SDNode *N, SelectionDAG &DAG) { 12582 unsigned IntNo = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue(); 12583 switch (IntNo) { 12584 default: 12585 // Don't do anything for most intrinsics. 12586 break; 12587 12588 // Vector shifts: check for immediate versions and lower them. 12589 // Note: This is done during DAG combining instead of DAG legalizing because 12590 // the build_vectors for 64-bit vector element shift counts are generally 12591 // not legal, and it is hard to see their values after they get legalized to 12592 // loads from a constant pool. 12593 case Intrinsic::arm_neon_vshifts: 12594 case Intrinsic::arm_neon_vshiftu: 12595 case Intrinsic::arm_neon_vrshifts: 12596 case Intrinsic::arm_neon_vrshiftu: 12597 case Intrinsic::arm_neon_vrshiftn: 12598 case Intrinsic::arm_neon_vqshifts: 12599 case Intrinsic::arm_neon_vqshiftu: 12600 case Intrinsic::arm_neon_vqshiftsu: 12601 case Intrinsic::arm_neon_vqshiftns: 12602 case Intrinsic::arm_neon_vqshiftnu: 12603 case Intrinsic::arm_neon_vqshiftnsu: 12604 case Intrinsic::arm_neon_vqrshiftns: 12605 case Intrinsic::arm_neon_vqrshiftnu: 12606 case Intrinsic::arm_neon_vqrshiftnsu: { 12607 EVT VT = N->getOperand(1).getValueType(); 12608 int64_t Cnt; 12609 unsigned VShiftOpc = 0; 12610 12611 switch (IntNo) { 12612 case Intrinsic::arm_neon_vshifts: 12613 case Intrinsic::arm_neon_vshiftu: 12614 if (isVShiftLImm(N->getOperand(2), VT, false, Cnt)) { 12615 VShiftOpc = ARMISD::VSHL; 12616 break; 12617 } 12618 if (isVShiftRImm(N->getOperand(2), VT, false, true, Cnt)) { 12619 VShiftOpc = (IntNo == Intrinsic::arm_neon_vshifts ? 12620 ARMISD::VSHRs : ARMISD::VSHRu); 12621 break; 12622 } 12623 return SDValue(); 12624 12625 case Intrinsic::arm_neon_vrshifts: 12626 case Intrinsic::arm_neon_vrshiftu: 12627 if (isVShiftRImm(N->getOperand(2), VT, false, true, Cnt)) 12628 break; 12629 return SDValue(); 12630 12631 case Intrinsic::arm_neon_vqshifts: 12632 case Intrinsic::arm_neon_vqshiftu: 12633 if (isVShiftLImm(N->getOperand(2), VT, false, Cnt)) 12634 break; 12635 return SDValue(); 12636 12637 case Intrinsic::arm_neon_vqshiftsu: 12638 if (isVShiftLImm(N->getOperand(2), VT, false, Cnt)) 12639 break; 12640 llvm_unreachable("invalid shift count for vqshlu intrinsic"); 12641 12642 case Intrinsic::arm_neon_vrshiftn: 12643 case Intrinsic::arm_neon_vqshiftns: 12644 case Intrinsic::arm_neon_vqshiftnu: 12645 case Intrinsic::arm_neon_vqshiftnsu: 12646 case Intrinsic::arm_neon_vqrshiftns: 12647 case Intrinsic::arm_neon_vqrshiftnu: 12648 case Intrinsic::arm_neon_vqrshiftnsu: 12649 // Narrowing shifts require an immediate right shift. 12650 if (isVShiftRImm(N->getOperand(2), VT, true, true, Cnt)) 12651 break; 12652 llvm_unreachable("invalid shift count for narrowing vector shift " 12653 "intrinsic"); 12654 12655 default: 12656 llvm_unreachable("unhandled vector shift"); 12657 } 12658 12659 switch (IntNo) { 12660 case Intrinsic::arm_neon_vshifts: 12661 case Intrinsic::arm_neon_vshiftu: 12662 // Opcode already set above. 12663 break; 12664 case Intrinsic::arm_neon_vrshifts: 12665 VShiftOpc = ARMISD::VRSHRs; break; 12666 case Intrinsic::arm_neon_vrshiftu: 12667 VShiftOpc = ARMISD::VRSHRu; break; 12668 case Intrinsic::arm_neon_vrshiftn: 12669 VShiftOpc = ARMISD::VRSHRN; break; 12670 case Intrinsic::arm_neon_vqshifts: 12671 VShiftOpc = ARMISD::VQSHLs; break; 12672 case Intrinsic::arm_neon_vqshiftu: 12673 VShiftOpc = ARMISD::VQSHLu; break; 12674 case Intrinsic::arm_neon_vqshiftsu: 12675 VShiftOpc = ARMISD::VQSHLsu; break; 12676 case Intrinsic::arm_neon_vqshiftns: 12677 VShiftOpc = ARMISD::VQSHRNs; break; 12678 case Intrinsic::arm_neon_vqshiftnu: 12679 VShiftOpc = ARMISD::VQSHRNu; break; 12680 case Intrinsic::arm_neon_vqshiftnsu: 12681 VShiftOpc = ARMISD::VQSHRNsu; break; 12682 case Intrinsic::arm_neon_vqrshiftns: 12683 VShiftOpc = ARMISD::VQRSHRNs; break; 12684 case Intrinsic::arm_neon_vqrshiftnu: 12685 VShiftOpc = ARMISD::VQRSHRNu; break; 12686 case Intrinsic::arm_neon_vqrshiftnsu: 12687 VShiftOpc = ARMISD::VQRSHRNsu; break; 12688 } 12689 12690 SDLoc dl(N); 12691 return DAG.getNode(VShiftOpc, dl, N->getValueType(0), 12692 N->getOperand(1), DAG.getConstant(Cnt, dl, MVT::i32)); 12693 } 12694 12695 case Intrinsic::arm_neon_vshiftins: { 12696 EVT VT = N->getOperand(1).getValueType(); 12697 int64_t Cnt; 12698 unsigned VShiftOpc = 0; 12699 12700 if (isVShiftLImm(N->getOperand(3), VT, false, Cnt)) 12701 VShiftOpc = ARMISD::VSLI; 12702 else if (isVShiftRImm(N->getOperand(3), VT, false, true, Cnt)) 12703 VShiftOpc = ARMISD::VSRI; 12704 else { 12705 llvm_unreachable("invalid shift count for vsli/vsri intrinsic"); 12706 } 12707 12708 SDLoc dl(N); 12709 return DAG.getNode(VShiftOpc, dl, N->getValueType(0), 12710 N->getOperand(1), N->getOperand(2), 12711 DAG.getConstant(Cnt, dl, MVT::i32)); 12712 } 12713 12714 case Intrinsic::arm_neon_vqrshifts: 12715 case Intrinsic::arm_neon_vqrshiftu: 12716 // No immediate versions of these to check for. 12717 break; 12718 } 12719 12720 return SDValue(); 12721 } 12722 12723 /// PerformShiftCombine - Checks for immediate versions of vector shifts and 12724 /// lowers them. As with the vector shift intrinsics, this is done during DAG 12725 /// combining instead of DAG legalizing because the build_vectors for 64-bit 12726 /// vector element shift counts are generally not legal, and it is hard to see 12727 /// their values after they get legalized to loads from a constant pool. 12728 static SDValue PerformShiftCombine(SDNode *N, 12729 TargetLowering::DAGCombinerInfo &DCI, 12730 const ARMSubtarget *ST) { 12731 SelectionDAG &DAG = DCI.DAG; 12732 EVT VT = N->getValueType(0); 12733 if (N->getOpcode() == ISD::SRL && VT == MVT::i32 && ST->hasV6Ops()) { 12734 // Canonicalize (srl (bswap x), 16) to (rotr (bswap x), 16) if the high 12735 // 16-bits of x is zero. This optimizes rev + lsr 16 to rev16. 12736 SDValue N1 = N->getOperand(1); 12737 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(N1)) { 12738 SDValue N0 = N->getOperand(0); 12739 if (C->getZExtValue() == 16 && N0.getOpcode() == ISD::BSWAP && 12740 DAG.MaskedValueIsZero(N0.getOperand(0), 12741 APInt::getHighBitsSet(32, 16))) 12742 return DAG.getNode(ISD::ROTR, SDLoc(N), VT, N0, N1); 12743 } 12744 } 12745 12746 if (ST->isThumb1Only() && N->getOpcode() == ISD::SHL && VT == MVT::i32 && 12747 N->getOperand(0)->getOpcode() == ISD::AND && 12748 N->getOperand(0)->hasOneUse()) { 12749 if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer()) 12750 return SDValue(); 12751 // Look for the pattern (shl (and x, AndMask), ShiftAmt). This doesn't 12752 // usually show up because instcombine prefers to canonicalize it to 12753 // (and (shl x, ShiftAmt) (shl AndMask, ShiftAmt)), but the shift can come 12754 // out of GEP lowering in some cases. 12755 SDValue N0 = N->getOperand(0); 12756 ConstantSDNode *ShiftAmtNode = dyn_cast<ConstantSDNode>(N->getOperand(1)); 12757 if (!ShiftAmtNode) 12758 return SDValue(); 12759 uint32_t ShiftAmt = static_cast<uint32_t>(ShiftAmtNode->getZExtValue()); 12760 ConstantSDNode *AndMaskNode = dyn_cast<ConstantSDNode>(N0->getOperand(1)); 12761 if (!AndMaskNode) 12762 return SDValue(); 12763 uint32_t AndMask = static_cast<uint32_t>(AndMaskNode->getZExtValue()); 12764 // Don't transform uxtb/uxth. 12765 if (AndMask == 255 || AndMask == 65535) 12766 return SDValue(); 12767 if (isMask_32(AndMask)) { 12768 uint32_t MaskedBits = countLeadingZeros(AndMask); 12769 if (MaskedBits > ShiftAmt) { 12770 SDLoc DL(N); 12771 SDValue SHL = DAG.getNode(ISD::SHL, DL, MVT::i32, N0->getOperand(0), 12772 DAG.getConstant(MaskedBits, DL, MVT::i32)); 12773 return DAG.getNode( 12774 ISD::SRL, DL, MVT::i32, SHL, 12775 DAG.getConstant(MaskedBits - ShiftAmt, DL, MVT::i32)); 12776 } 12777 } 12778 } 12779 12780 // Nothing to be done for scalar shifts. 12781 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 12782 if (!VT.isVector() || !TLI.isTypeLegal(VT)) 12783 return SDValue(); 12784 12785 assert(ST->hasNEON() && "unexpected vector shift"); 12786 int64_t Cnt; 12787 12788 switch (N->getOpcode()) { 12789 default: llvm_unreachable("unexpected shift opcode"); 12790 12791 case ISD::SHL: 12792 if (isVShiftLImm(N->getOperand(1), VT, false, Cnt)) { 12793 SDLoc dl(N); 12794 return DAG.getNode(ARMISD::VSHL, dl, VT, N->getOperand(0), 12795 DAG.getConstant(Cnt, dl, MVT::i32)); 12796 } 12797 break; 12798 12799 case ISD::SRA: 12800 case ISD::SRL: 12801 if (isVShiftRImm(N->getOperand(1), VT, false, false, Cnt)) { 12802 unsigned VShiftOpc = (N->getOpcode() == ISD::SRA ? 12803 ARMISD::VSHRs : ARMISD::VSHRu); 12804 SDLoc dl(N); 12805 return DAG.getNode(VShiftOpc, dl, VT, N->getOperand(0), 12806 DAG.getConstant(Cnt, dl, MVT::i32)); 12807 } 12808 } 12809 return SDValue(); 12810 } 12811 12812 /// PerformExtendCombine - Target-specific DAG combining for ISD::SIGN_EXTEND, 12813 /// ISD::ZERO_EXTEND, and ISD::ANY_EXTEND. 12814 static SDValue PerformExtendCombine(SDNode *N, SelectionDAG &DAG, 12815 const ARMSubtarget *ST) { 12816 SDValue N0 = N->getOperand(0); 12817 12818 // Check for sign- and zero-extensions of vector extract operations of 8- 12819 // and 16-bit vector elements. NEON supports these directly. They are 12820 // handled during DAG combining because type legalization will promote them 12821 // to 32-bit types and it is messy to recognize the operations after that. 12822 if (ST->hasNEON() && N0.getOpcode() == ISD::EXTRACT_VECTOR_ELT) { 12823 SDValue Vec = N0.getOperand(0); 12824 SDValue Lane = N0.getOperand(1); 12825 EVT VT = N->getValueType(0); 12826 EVT EltVT = N0.getValueType(); 12827 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 12828 12829 if (VT == MVT::i32 && 12830 (EltVT == MVT::i8 || EltVT == MVT::i16) && 12831 TLI.isTypeLegal(Vec.getValueType()) && 12832 isa<ConstantSDNode>(Lane)) { 12833 12834 unsigned Opc = 0; 12835 switch (N->getOpcode()) { 12836 default: llvm_unreachable("unexpected opcode"); 12837 case ISD::SIGN_EXTEND: 12838 Opc = ARMISD::VGETLANEs; 12839 break; 12840 case ISD::ZERO_EXTEND: 12841 case ISD::ANY_EXTEND: 12842 Opc = ARMISD::VGETLANEu; 12843 break; 12844 } 12845 return DAG.getNode(Opc, SDLoc(N), VT, Vec, Lane); 12846 } 12847 } 12848 12849 return SDValue(); 12850 } 12851 12852 static const APInt *isPowerOf2Constant(SDValue V) { 12853 ConstantSDNode *C = dyn_cast<ConstantSDNode>(V); 12854 if (!C) 12855 return nullptr; 12856 const APInt *CV = &C->getAPIntValue(); 12857 return CV->isPowerOf2() ? CV : nullptr; 12858 } 12859 12860 SDValue ARMTargetLowering::PerformCMOVToBFICombine(SDNode *CMOV, SelectionDAG &DAG) const { 12861 // If we have a CMOV, OR and AND combination such as: 12862 // if (x & CN) 12863 // y |= CM; 12864 // 12865 // And: 12866 // * CN is a single bit; 12867 // * All bits covered by CM are known zero in y 12868 // 12869 // Then we can convert this into a sequence of BFI instructions. This will 12870 // always be a win if CM is a single bit, will always be no worse than the 12871 // TST&OR sequence if CM is two bits, and for thumb will be no worse if CM is 12872 // three bits (due to the extra IT instruction). 12873 12874 SDValue Op0 = CMOV->getOperand(0); 12875 SDValue Op1 = CMOV->getOperand(1); 12876 auto CCNode = cast<ConstantSDNode>(CMOV->getOperand(2)); 12877 auto CC = CCNode->getAPIntValue().getLimitedValue(); 12878 SDValue CmpZ = CMOV->getOperand(4); 12879 12880 // The compare must be against zero. 12881 if (!isNullConstant(CmpZ->getOperand(1))) 12882 return SDValue(); 12883 12884 assert(CmpZ->getOpcode() == ARMISD::CMPZ); 12885 SDValue And = CmpZ->getOperand(0); 12886 if (And->getOpcode() != ISD::AND) 12887 return SDValue(); 12888 const APInt *AndC = isPowerOf2Constant(And->getOperand(1)); 12889 if (!AndC) 12890 return SDValue(); 12891 SDValue X = And->getOperand(0); 12892 12893 if (CC == ARMCC::EQ) { 12894 // We're performing an "equal to zero" compare. Swap the operands so we 12895 // canonicalize on a "not equal to zero" compare. 12896 std::swap(Op0, Op1); 12897 } else { 12898 assert(CC == ARMCC::NE && "How can a CMPZ node not be EQ or NE?"); 12899 } 12900 12901 if (Op1->getOpcode() != ISD::OR) 12902 return SDValue(); 12903 12904 ConstantSDNode *OrC = dyn_cast<ConstantSDNode>(Op1->getOperand(1)); 12905 if (!OrC) 12906 return SDValue(); 12907 SDValue Y = Op1->getOperand(0); 12908 12909 if (Op0 != Y) 12910 return SDValue(); 12911 12912 // Now, is it profitable to continue? 12913 APInt OrCI = OrC->getAPIntValue(); 12914 unsigned Heuristic = Subtarget->isThumb() ? 3 : 2; 12915 if (OrCI.countPopulation() > Heuristic) 12916 return SDValue(); 12917 12918 // Lastly, can we determine that the bits defined by OrCI 12919 // are zero in Y? 12920 KnownBits Known = DAG.computeKnownBits(Y); 12921 if ((OrCI & Known.Zero) != OrCI) 12922 return SDValue(); 12923 12924 // OK, we can do the combine. 12925 SDValue V = Y; 12926 SDLoc dl(X); 12927 EVT VT = X.getValueType(); 12928 unsigned BitInX = AndC->logBase2(); 12929 12930 if (BitInX != 0) { 12931 // We must shift X first. 12932 X = DAG.getNode(ISD::SRL, dl, VT, X, 12933 DAG.getConstant(BitInX, dl, VT)); 12934 } 12935 12936 for (unsigned BitInY = 0, NumActiveBits = OrCI.getActiveBits(); 12937 BitInY < NumActiveBits; ++BitInY) { 12938 if (OrCI[BitInY] == 0) 12939 continue; 12940 APInt Mask(VT.getSizeInBits(), 0); 12941 Mask.setBit(BitInY); 12942 V = DAG.getNode(ARMISD::BFI, dl, VT, V, X, 12943 // Confusingly, the operand is an *inverted* mask. 12944 DAG.getConstant(~Mask, dl, VT)); 12945 } 12946 12947 return V; 12948 } 12949 12950 static SDValue PerformHWLoopCombine(SDNode *N, 12951 TargetLowering::DAGCombinerInfo &DCI, 12952 const ARMSubtarget *ST) { 12953 // Look for (brcond (xor test.set.loop.iterations, -1) 12954 SDValue CC = N->getOperand(1); 12955 12956 if (CC->getOpcode() != ISD::XOR && CC->getOpcode() != ISD::SETCC) 12957 return SDValue(); 12958 12959 if (CC->getOperand(0)->getOpcode() != ISD::INTRINSIC_W_CHAIN) 12960 return SDValue(); 12961 12962 SDValue Int = CC->getOperand(0); 12963 unsigned IntOp = cast<ConstantSDNode>(Int.getOperand(1))->getZExtValue(); 12964 if (IntOp != Intrinsic::test_set_loop_iterations) 12965 return SDValue(); 12966 12967 assert((isa<ConstantSDNode>(CC->getOperand(1)) && 12968 cast<ConstantSDNode>(CC->getOperand(1))->isOne()) && 12969 "Expected to compare against 1"); 12970 12971 SDLoc dl(Int); 12972 SDValue Chain = N->getOperand(0); 12973 SDValue Elements = Int.getOperand(2); 12974 SDValue ExitBlock = N->getOperand(2); 12975 12976 // TODO: Once we start supporting tail predication, we can add another 12977 // operand to WLS for the number of elements processed in a vector loop. 12978 12979 SDValue Ops[] = { Chain, Elements, ExitBlock }; 12980 SDValue Res = DCI.DAG.getNode(ARMISD::WLS, dl, MVT::Other, Ops); 12981 DCI.DAG.ReplaceAllUsesOfValueWith(Int.getValue(1), Int.getOperand(0)); 12982 return Res; 12983 } 12984 12985 /// PerformBRCONDCombine - Target-specific DAG combining for ARMISD::BRCOND. 12986 SDValue 12987 ARMTargetLowering::PerformBRCONDCombine(SDNode *N, SelectionDAG &DAG) const { 12988 SDValue Cmp = N->getOperand(4); 12989 if (Cmp.getOpcode() != ARMISD::CMPZ) 12990 // Only looking at NE cases. 12991 return SDValue(); 12992 12993 EVT VT = N->getValueType(0); 12994 SDLoc dl(N); 12995 SDValue LHS = Cmp.getOperand(0); 12996 SDValue RHS = Cmp.getOperand(1); 12997 SDValue Chain = N->getOperand(0); 12998 SDValue BB = N->getOperand(1); 12999 SDValue ARMcc = N->getOperand(2); 13000 ARMCC::CondCodes CC = 13001 (ARMCC::CondCodes)cast<ConstantSDNode>(ARMcc)->getZExtValue(); 13002 13003 // (brcond Chain BB ne CPSR (cmpz (and (cmov 0 1 CC CPSR Cmp) 1) 0)) 13004 // -> (brcond Chain BB CC CPSR Cmp) 13005 if (CC == ARMCC::NE && LHS.getOpcode() == ISD::AND && LHS->hasOneUse() && 13006 LHS->getOperand(0)->getOpcode() == ARMISD::CMOV && 13007 LHS->getOperand(0)->hasOneUse()) { 13008 auto *LHS00C = dyn_cast<ConstantSDNode>(LHS->getOperand(0)->getOperand(0)); 13009 auto *LHS01C = dyn_cast<ConstantSDNode>(LHS->getOperand(0)->getOperand(1)); 13010 auto *LHS1C = dyn_cast<ConstantSDNode>(LHS->getOperand(1)); 13011 auto *RHSC = dyn_cast<ConstantSDNode>(RHS); 13012 if ((LHS00C && LHS00C->getZExtValue() == 0) && 13013 (LHS01C && LHS01C->getZExtValue() == 1) && 13014 (LHS1C && LHS1C->getZExtValue() == 1) && 13015 (RHSC && RHSC->getZExtValue() == 0)) { 13016 return DAG.getNode( 13017 ARMISD::BRCOND, dl, VT, Chain, BB, LHS->getOperand(0)->getOperand(2), 13018 LHS->getOperand(0)->getOperand(3), LHS->getOperand(0)->getOperand(4)); 13019 } 13020 } 13021 13022 return SDValue(); 13023 } 13024 13025 /// PerformCMOVCombine - Target-specific DAG combining for ARMISD::CMOV. 13026 SDValue 13027 ARMTargetLowering::PerformCMOVCombine(SDNode *N, SelectionDAG &DAG) const { 13028 SDValue Cmp = N->getOperand(4); 13029 if (Cmp.getOpcode() != ARMISD::CMPZ) 13030 // Only looking at EQ and NE cases. 13031 return SDValue(); 13032 13033 EVT VT = N->getValueType(0); 13034 SDLoc dl(N); 13035 SDValue LHS = Cmp.getOperand(0); 13036 SDValue RHS = Cmp.getOperand(1); 13037 SDValue FalseVal = N->getOperand(0); 13038 SDValue TrueVal = N->getOperand(1); 13039 SDValue ARMcc = N->getOperand(2); 13040 ARMCC::CondCodes CC = 13041 (ARMCC::CondCodes)cast<ConstantSDNode>(ARMcc)->getZExtValue(); 13042 13043 // BFI is only available on V6T2+. 13044 if (!Subtarget->isThumb1Only() && Subtarget->hasV6T2Ops()) { 13045 SDValue R = PerformCMOVToBFICombine(N, DAG); 13046 if (R) 13047 return R; 13048 } 13049 13050 // Simplify 13051 // mov r1, r0 13052 // cmp r1, x 13053 // mov r0, y 13054 // moveq r0, x 13055 // to 13056 // cmp r0, x 13057 // movne r0, y 13058 // 13059 // mov r1, r0 13060 // cmp r1, x 13061 // mov r0, x 13062 // movne r0, y 13063 // to 13064 // cmp r0, x 13065 // movne r0, y 13066 /// FIXME: Turn this into a target neutral optimization? 13067 SDValue Res; 13068 if (CC == ARMCC::NE && FalseVal == RHS && FalseVal != LHS) { 13069 Res = DAG.getNode(ARMISD::CMOV, dl, VT, LHS, TrueVal, ARMcc, 13070 N->getOperand(3), Cmp); 13071 } else if (CC == ARMCC::EQ && TrueVal == RHS) { 13072 SDValue ARMcc; 13073 SDValue NewCmp = getARMCmp(LHS, RHS, ISD::SETNE, ARMcc, DAG, dl); 13074 Res = DAG.getNode(ARMISD::CMOV, dl, VT, LHS, FalseVal, ARMcc, 13075 N->getOperand(3), NewCmp); 13076 } 13077 13078 // (cmov F T ne CPSR (cmpz (cmov 0 1 CC CPSR Cmp) 0)) 13079 // -> (cmov F T CC CPSR Cmp) 13080 if (CC == ARMCC::NE && LHS.getOpcode() == ARMISD::CMOV && LHS->hasOneUse()) { 13081 auto *LHS0C = dyn_cast<ConstantSDNode>(LHS->getOperand(0)); 13082 auto *LHS1C = dyn_cast<ConstantSDNode>(LHS->getOperand(1)); 13083 auto *RHSC = dyn_cast<ConstantSDNode>(RHS); 13084 if ((LHS0C && LHS0C->getZExtValue() == 0) && 13085 (LHS1C && LHS1C->getZExtValue() == 1) && 13086 (RHSC && RHSC->getZExtValue() == 0)) { 13087 return DAG.getNode(ARMISD::CMOV, dl, VT, FalseVal, TrueVal, 13088 LHS->getOperand(2), LHS->getOperand(3), 13089 LHS->getOperand(4)); 13090 } 13091 } 13092 13093 if (!VT.isInteger()) 13094 return SDValue(); 13095 13096 // Materialize a boolean comparison for integers so we can avoid branching. 13097 if (isNullConstant(FalseVal)) { 13098 if (CC == ARMCC::EQ && isOneConstant(TrueVal)) { 13099 if (!Subtarget->isThumb1Only() && Subtarget->hasV5TOps()) { 13100 // If x == y then x - y == 0 and ARM's CLZ will return 32, shifting it 13101 // right 5 bits will make that 32 be 1, otherwise it will be 0. 13102 // CMOV 0, 1, ==, (CMPZ x, y) -> SRL (CTLZ (SUB x, y)), 5 13103 SDValue Sub = DAG.getNode(ISD::SUB, dl, VT, LHS, RHS); 13104 Res = DAG.getNode(ISD::SRL, dl, VT, DAG.getNode(ISD::CTLZ, dl, VT, Sub), 13105 DAG.getConstant(5, dl, MVT::i32)); 13106 } else { 13107 // CMOV 0, 1, ==, (CMPZ x, y) -> 13108 // (ADDCARRY (SUB x, y), t:0, t:1) 13109 // where t = (SUBCARRY 0, (SUB x, y), 0) 13110 // 13111 // The SUBCARRY computes 0 - (x - y) and this will give a borrow when 13112 // x != y. In other words, a carry C == 1 when x == y, C == 0 13113 // otherwise. 13114 // The final ADDCARRY computes 13115 // x - y + (0 - (x - y)) + C == C 13116 SDValue Sub = DAG.getNode(ISD::SUB, dl, VT, LHS, RHS); 13117 SDVTList VTs = DAG.getVTList(VT, MVT::i32); 13118 SDValue Neg = DAG.getNode(ISD::USUBO, dl, VTs, FalseVal, Sub); 13119 // ISD::SUBCARRY returns a borrow but we want the carry here 13120 // actually. 13121 SDValue Carry = 13122 DAG.getNode(ISD::SUB, dl, MVT::i32, 13123 DAG.getConstant(1, dl, MVT::i32), Neg.getValue(1)); 13124 Res = DAG.getNode(ISD::ADDCARRY, dl, VTs, Sub, Neg, Carry); 13125 } 13126 } else if (CC == ARMCC::NE && !isNullConstant(RHS) && 13127 (!Subtarget->isThumb1Only() || isPowerOf2Constant(TrueVal))) { 13128 // This seems pointless but will allow us to combine it further below. 13129 // CMOV 0, z, !=, (CMPZ x, y) -> CMOV (SUBS x, y), z, !=, (SUBS x, y):1 13130 SDValue Sub = 13131 DAG.getNode(ARMISD::SUBS, dl, DAG.getVTList(VT, MVT::i32), LHS, RHS); 13132 SDValue CPSRGlue = DAG.getCopyToReg(DAG.getEntryNode(), dl, ARM::CPSR, 13133 Sub.getValue(1), SDValue()); 13134 Res = DAG.getNode(ARMISD::CMOV, dl, VT, Sub, TrueVal, ARMcc, 13135 N->getOperand(3), CPSRGlue.getValue(1)); 13136 FalseVal = Sub; 13137 } 13138 } else if (isNullConstant(TrueVal)) { 13139 if (CC == ARMCC::EQ && !isNullConstant(RHS) && 13140 (!Subtarget->isThumb1Only() || isPowerOf2Constant(FalseVal))) { 13141 // This seems pointless but will allow us to combine it further below 13142 // Note that we change == for != as this is the dual for the case above. 13143 // CMOV z, 0, ==, (CMPZ x, y) -> CMOV (SUBS x, y), z, !=, (SUBS x, y):1 13144 SDValue Sub = 13145 DAG.getNode(ARMISD::SUBS, dl, DAG.getVTList(VT, MVT::i32), LHS, RHS); 13146 SDValue CPSRGlue = DAG.getCopyToReg(DAG.getEntryNode(), dl, ARM::CPSR, 13147 Sub.getValue(1), SDValue()); 13148 Res = DAG.getNode(ARMISD::CMOV, dl, VT, Sub, FalseVal, 13149 DAG.getConstant(ARMCC::NE, dl, MVT::i32), 13150 N->getOperand(3), CPSRGlue.getValue(1)); 13151 FalseVal = Sub; 13152 } 13153 } 13154 13155 // On Thumb1, the DAG above may be further combined if z is a power of 2 13156 // (z == 2 ^ K). 13157 // CMOV (SUBS x, y), z, !=, (SUBS x, y):1 -> 13158 // t1 = (USUBO (SUB x, y), 1) 13159 // t2 = (SUBCARRY (SUB x, y), t1:0, t1:1) 13160 // Result = if K != 0 then (SHL t2:0, K) else t2:0 13161 // 13162 // This also handles the special case of comparing against zero; it's 13163 // essentially, the same pattern, except there's no SUBS: 13164 // CMOV x, z, !=, (CMPZ x, 0) -> 13165 // t1 = (USUBO x, 1) 13166 // t2 = (SUBCARRY x, t1:0, t1:1) 13167 // Result = if K != 0 then (SHL t2:0, K) else t2:0 13168 const APInt *TrueConst; 13169 if (Subtarget->isThumb1Only() && CC == ARMCC::NE && 13170 ((FalseVal.getOpcode() == ARMISD::SUBS && 13171 FalseVal.getOperand(0) == LHS && FalseVal.getOperand(1) == RHS) || 13172 (FalseVal == LHS && isNullConstant(RHS))) && 13173 (TrueConst = isPowerOf2Constant(TrueVal))) { 13174 SDVTList VTs = DAG.getVTList(VT, MVT::i32); 13175 unsigned ShiftAmount = TrueConst->logBase2(); 13176 if (ShiftAmount) 13177 TrueVal = DAG.getConstant(1, dl, VT); 13178 SDValue Subc = DAG.getNode(ISD::USUBO, dl, VTs, FalseVal, TrueVal); 13179 Res = DAG.getNode(ISD::SUBCARRY, dl, VTs, FalseVal, Subc, Subc.getValue(1)); 13180 13181 if (ShiftAmount) 13182 Res = DAG.getNode(ISD::SHL, dl, VT, Res, 13183 DAG.getConstant(ShiftAmount, dl, MVT::i32)); 13184 } 13185 13186 if (Res.getNode()) { 13187 KnownBits Known = DAG.computeKnownBits(SDValue(N,0)); 13188 // Capture demanded bits information that would be otherwise lost. 13189 if (Known.Zero == 0xfffffffe) 13190 Res = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Res, 13191 DAG.getValueType(MVT::i1)); 13192 else if (Known.Zero == 0xffffff00) 13193 Res = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Res, 13194 DAG.getValueType(MVT::i8)); 13195 else if (Known.Zero == 0xffff0000) 13196 Res = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Res, 13197 DAG.getValueType(MVT::i16)); 13198 } 13199 13200 return Res; 13201 } 13202 13203 SDValue ARMTargetLowering::PerformDAGCombine(SDNode *N, 13204 DAGCombinerInfo &DCI) const { 13205 switch (N->getOpcode()) { 13206 default: break; 13207 case ISD::ABS: return PerformABSCombine(N, DCI, Subtarget); 13208 case ARMISD::ADDE: return PerformADDECombine(N, DCI, Subtarget); 13209 case ARMISD::UMLAL: return PerformUMLALCombine(N, DCI.DAG, Subtarget); 13210 case ISD::ADD: return PerformADDCombine(N, DCI, Subtarget); 13211 case ISD::SUB: return PerformSUBCombine(N, DCI); 13212 case ISD::MUL: return PerformMULCombine(N, DCI, Subtarget); 13213 case ISD::OR: return PerformORCombine(N, DCI, Subtarget); 13214 case ISD::XOR: return PerformXORCombine(N, DCI, Subtarget); 13215 case ISD::AND: return PerformANDCombine(N, DCI, Subtarget); 13216 case ISD::BRCOND: return PerformHWLoopCombine(N, DCI, Subtarget); 13217 case ARMISD::ADDC: 13218 case ARMISD::SUBC: return PerformAddcSubcCombine(N, DCI, Subtarget); 13219 case ARMISD::SUBE: return PerformAddeSubeCombine(N, DCI, Subtarget); 13220 case ARMISD::BFI: return PerformBFICombine(N, DCI); 13221 case ARMISD::VMOVRRD: return PerformVMOVRRDCombine(N, DCI, Subtarget); 13222 case ARMISD::VMOVDRR: return PerformVMOVDRRCombine(N, DCI.DAG); 13223 case ISD::STORE: return PerformSTORECombine(N, DCI); 13224 case ISD::BUILD_VECTOR: return PerformBUILD_VECTORCombine(N, DCI, Subtarget); 13225 case ISD::INSERT_VECTOR_ELT: return PerformInsertEltCombine(N, DCI); 13226 case ISD::VECTOR_SHUFFLE: return PerformVECTOR_SHUFFLECombine(N, DCI.DAG); 13227 case ARMISD::VDUPLANE: return PerformVDUPLANECombine(N, DCI); 13228 case ARMISD::VDUP: return PerformVDUPCombine(N, DCI, Subtarget); 13229 case ISD::FP_TO_SINT: 13230 case ISD::FP_TO_UINT: 13231 return PerformVCVTCombine(N, DCI.DAG, Subtarget); 13232 case ISD::FDIV: 13233 return PerformVDIVCombine(N, DCI.DAG, Subtarget); 13234 case ISD::INTRINSIC_WO_CHAIN: return PerformIntrinsicCombine(N, DCI.DAG); 13235 case ISD::SHL: 13236 case ISD::SRA: 13237 case ISD::SRL: 13238 return PerformShiftCombine(N, DCI, Subtarget); 13239 case ISD::SIGN_EXTEND: 13240 case ISD::ZERO_EXTEND: 13241 case ISD::ANY_EXTEND: return PerformExtendCombine(N, DCI.DAG, Subtarget); 13242 case ARMISD::CMOV: return PerformCMOVCombine(N, DCI.DAG); 13243 case ARMISD::BRCOND: return PerformBRCONDCombine(N, DCI.DAG); 13244 case ISD::LOAD: return PerformLOADCombine(N, DCI); 13245 case ARMISD::VLD1DUP: 13246 case ARMISD::VLD2DUP: 13247 case ARMISD::VLD3DUP: 13248 case ARMISD::VLD4DUP: 13249 return PerformVLDCombine(N, DCI); 13250 case ARMISD::BUILD_VECTOR: 13251 return PerformARMBUILD_VECTORCombine(N, DCI); 13252 case ARMISD::SMULWB: { 13253 unsigned BitWidth = N->getValueType(0).getSizeInBits(); 13254 APInt DemandedMask = APInt::getLowBitsSet(BitWidth, 16); 13255 if (SimplifyDemandedBits(N->getOperand(1), DemandedMask, DCI)) 13256 return SDValue(); 13257 break; 13258 } 13259 case ARMISD::SMULWT: { 13260 unsigned BitWidth = N->getValueType(0).getSizeInBits(); 13261 APInt DemandedMask = APInt::getHighBitsSet(BitWidth, 16); 13262 if (SimplifyDemandedBits(N->getOperand(1), DemandedMask, DCI)) 13263 return SDValue(); 13264 break; 13265 } 13266 case ARMISD::SMLALBB: { 13267 unsigned BitWidth = N->getValueType(0).getSizeInBits(); 13268 APInt DemandedMask = APInt::getLowBitsSet(BitWidth, 16); 13269 if ((SimplifyDemandedBits(N->getOperand(0), DemandedMask, DCI)) || 13270 (SimplifyDemandedBits(N->getOperand(1), DemandedMask, DCI))) 13271 return SDValue(); 13272 break; 13273 } 13274 case ARMISD::SMLALBT: { 13275 unsigned LowWidth = N->getOperand(0).getValueType().getSizeInBits(); 13276 APInt LowMask = APInt::getLowBitsSet(LowWidth, 16); 13277 unsigned HighWidth = N->getOperand(1).getValueType().getSizeInBits(); 13278 APInt HighMask = APInt::getHighBitsSet(HighWidth, 16); 13279 if ((SimplifyDemandedBits(N->getOperand(0), LowMask, DCI)) || 13280 (SimplifyDemandedBits(N->getOperand(1), HighMask, DCI))) 13281 return SDValue(); 13282 break; 13283 } 13284 case ARMISD::SMLALTB: { 13285 unsigned HighWidth = N->getOperand(0).getValueType().getSizeInBits(); 13286 APInt HighMask = APInt::getHighBitsSet(HighWidth, 16); 13287 unsigned LowWidth = N->getOperand(1).getValueType().getSizeInBits(); 13288 APInt LowMask = APInt::getLowBitsSet(LowWidth, 16); 13289 if ((SimplifyDemandedBits(N->getOperand(0), HighMask, DCI)) || 13290 (SimplifyDemandedBits(N->getOperand(1), LowMask, DCI))) 13291 return SDValue(); 13292 break; 13293 } 13294 case ARMISD::SMLALTT: { 13295 unsigned BitWidth = N->getValueType(0).getSizeInBits(); 13296 APInt DemandedMask = APInt::getHighBitsSet(BitWidth, 16); 13297 if ((SimplifyDemandedBits(N->getOperand(0), DemandedMask, DCI)) || 13298 (SimplifyDemandedBits(N->getOperand(1), DemandedMask, DCI))) 13299 return SDValue(); 13300 break; 13301 } 13302 case ISD::INTRINSIC_VOID: 13303 case ISD::INTRINSIC_W_CHAIN: 13304 switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) { 13305 case Intrinsic::arm_neon_vld1: 13306 case Intrinsic::arm_neon_vld1x2: 13307 case Intrinsic::arm_neon_vld1x3: 13308 case Intrinsic::arm_neon_vld1x4: 13309 case Intrinsic::arm_neon_vld2: 13310 case Intrinsic::arm_neon_vld3: 13311 case Intrinsic::arm_neon_vld4: 13312 case Intrinsic::arm_neon_vld2lane: 13313 case Intrinsic::arm_neon_vld3lane: 13314 case Intrinsic::arm_neon_vld4lane: 13315 case Intrinsic::arm_neon_vld2dup: 13316 case Intrinsic::arm_neon_vld3dup: 13317 case Intrinsic::arm_neon_vld4dup: 13318 case Intrinsic::arm_neon_vst1: 13319 case Intrinsic::arm_neon_vst1x2: 13320 case Intrinsic::arm_neon_vst1x3: 13321 case Intrinsic::arm_neon_vst1x4: 13322 case Intrinsic::arm_neon_vst2: 13323 case Intrinsic::arm_neon_vst3: 13324 case Intrinsic::arm_neon_vst4: 13325 case Intrinsic::arm_neon_vst2lane: 13326 case Intrinsic::arm_neon_vst3lane: 13327 case Intrinsic::arm_neon_vst4lane: 13328 return PerformVLDCombine(N, DCI); 13329 default: break; 13330 } 13331 break; 13332 } 13333 return SDValue(); 13334 } 13335 13336 bool ARMTargetLowering::isDesirableToTransformToIntegerOp(unsigned Opc, 13337 EVT VT) const { 13338 return (VT == MVT::f32) && (Opc == ISD::LOAD || Opc == ISD::STORE); 13339 } 13340 13341 bool ARMTargetLowering::allowsMisalignedMemoryAccesses(EVT VT, unsigned, 13342 unsigned Alignment, 13343 MachineMemOperand::Flags, 13344 bool *Fast) const { 13345 // Depends what it gets converted into if the type is weird. 13346 if (!VT.isSimple()) 13347 return false; 13348 13349 // The AllowsUnaliged flag models the SCTLR.A setting in ARM cpus 13350 bool AllowsUnaligned = Subtarget->allowsUnalignedMem(); 13351 auto Ty = VT.getSimpleVT().SimpleTy; 13352 13353 if (Ty == MVT::i8 || Ty == MVT::i16 || Ty == MVT::i32) { 13354 // Unaligned access can use (for example) LRDB, LRDH, LDR 13355 if (AllowsUnaligned) { 13356 if (Fast) 13357 *Fast = Subtarget->hasV7Ops(); 13358 return true; 13359 } 13360 } 13361 13362 if (Ty == MVT::f64 || Ty == MVT::v2f64) { 13363 // For any little-endian targets with neon, we can support unaligned ld/st 13364 // of D and Q (e.g. {D0,D1}) registers by using vld1.i8/vst1.i8. 13365 // A big-endian target may also explicitly support unaligned accesses 13366 if (Subtarget->hasNEON() && (AllowsUnaligned || Subtarget->isLittle())) { 13367 if (Fast) 13368 *Fast = true; 13369 return true; 13370 } 13371 } 13372 13373 if (!Subtarget->hasMVEIntegerOps()) 13374 return false; 13375 if (Ty != MVT::v16i8 && Ty != MVT::v8i16 && Ty != MVT::v8f16 && 13376 Ty != MVT::v4i32 && Ty != MVT::v4f32 && Ty != MVT::v2i64 && 13377 Ty != MVT::v2f64 && 13378 // These are for truncated stores 13379 Ty != MVT::v4i8 && Ty != MVT::v8i8 && Ty != MVT::v4i16) 13380 return false; 13381 13382 if (Subtarget->isLittle()) { 13383 // In little-endian MVE, the store instructions VSTRB.U8, 13384 // VSTRH.U16 and VSTRW.U32 all store the vector register in 13385 // exactly the same format, and differ only in the range of 13386 // their immediate offset field and the required alignment. 13387 // 13388 // In particular, VSTRB.U8 can store a vector at byte alignment. 13389 // So at this stage we can simply say that loads/stores of all 13390 // 128-bit wide vector types are permitted at any alignment, 13391 // because we know at least _one_ instruction can manage that. 13392 // 13393 // Later on we might find that some of those loads are better 13394 // generated as VLDRW.U32 if alignment permits, to take 13395 // advantage of the larger immediate range. But for the moment, 13396 // all that matters is that if we don't lower the load then 13397 // _some_ instruction can handle it. 13398 if (Fast) 13399 *Fast = true; 13400 return true; 13401 } else { 13402 // In big-endian MVE, those instructions aren't so similar 13403 // after all, because they reorder the bytes of the vector 13404 // differently. So this time we can only store a particular 13405 // kind of vector if its alignment is at least the element 13406 // type. And we can't store vectors of i64 or f64 at all 13407 // without having to do some postprocessing, because there's 13408 // no VSTRD.U64. 13409 if (Ty == MVT::v16i8 || 13410 ((Ty == MVT::v8i16 || Ty == MVT::v8f16) && Alignment >= 2) || 13411 ((Ty == MVT::v4i32 || Ty == MVT::v4f32) && Alignment >= 4)) { 13412 if (Fast) 13413 *Fast = true; 13414 return true; 13415 } 13416 } 13417 13418 return false; 13419 } 13420 13421 static bool memOpAlign(unsigned DstAlign, unsigned SrcAlign, 13422 unsigned AlignCheck) { 13423 return ((SrcAlign == 0 || SrcAlign % AlignCheck == 0) && 13424 (DstAlign == 0 || DstAlign % AlignCheck == 0)); 13425 } 13426 13427 EVT ARMTargetLowering::getOptimalMemOpType( 13428 uint64_t Size, unsigned DstAlign, unsigned SrcAlign, bool IsMemset, 13429 bool ZeroMemset, bool MemcpyStrSrc, 13430 const AttributeList &FuncAttributes) const { 13431 // See if we can use NEON instructions for this... 13432 if ((!IsMemset || ZeroMemset) && Subtarget->hasNEON() && 13433 !FuncAttributes.hasFnAttribute(Attribute::NoImplicitFloat)) { 13434 bool Fast; 13435 if (Size >= 16 && 13436 (memOpAlign(SrcAlign, DstAlign, 16) || 13437 (allowsMisalignedMemoryAccesses(MVT::v2f64, 0, 1, 13438 MachineMemOperand::MONone, &Fast) && 13439 Fast))) { 13440 return MVT::v2f64; 13441 } else if (Size >= 8 && 13442 (memOpAlign(SrcAlign, DstAlign, 8) || 13443 (allowsMisalignedMemoryAccesses( 13444 MVT::f64, 0, 1, MachineMemOperand::MONone, &Fast) && 13445 Fast))) { 13446 return MVT::f64; 13447 } 13448 } 13449 13450 // Let the target-independent logic figure it out. 13451 return MVT::Other; 13452 } 13453 13454 // 64-bit integers are split into their high and low parts and held in two 13455 // different registers, so the trunc is free since the low register can just 13456 // be used. 13457 bool ARMTargetLowering::isTruncateFree(Type *SrcTy, Type *DstTy) const { 13458 if (!SrcTy->isIntegerTy() || !DstTy->isIntegerTy()) 13459 return false; 13460 unsigned SrcBits = SrcTy->getPrimitiveSizeInBits(); 13461 unsigned DestBits = DstTy->getPrimitiveSizeInBits(); 13462 return (SrcBits == 64 && DestBits == 32); 13463 } 13464 13465 bool ARMTargetLowering::isTruncateFree(EVT SrcVT, EVT DstVT) const { 13466 if (SrcVT.isVector() || DstVT.isVector() || !SrcVT.isInteger() || 13467 !DstVT.isInteger()) 13468 return false; 13469 unsigned SrcBits = SrcVT.getSizeInBits(); 13470 unsigned DestBits = DstVT.getSizeInBits(); 13471 return (SrcBits == 64 && DestBits == 32); 13472 } 13473 13474 bool ARMTargetLowering::isZExtFree(SDValue Val, EVT VT2) const { 13475 if (Val.getOpcode() != ISD::LOAD) 13476 return false; 13477 13478 EVT VT1 = Val.getValueType(); 13479 if (!VT1.isSimple() || !VT1.isInteger() || 13480 !VT2.isSimple() || !VT2.isInteger()) 13481 return false; 13482 13483 switch (VT1.getSimpleVT().SimpleTy) { 13484 default: break; 13485 case MVT::i1: 13486 case MVT::i8: 13487 case MVT::i16: 13488 // 8-bit and 16-bit loads implicitly zero-extend to 32-bits. 13489 return true; 13490 } 13491 13492 return false; 13493 } 13494 13495 bool ARMTargetLowering::isFNegFree(EVT VT) const { 13496 if (!VT.isSimple()) 13497 return false; 13498 13499 // There are quite a few FP16 instructions (e.g. VNMLA, VNMLS, etc.) that 13500 // negate values directly (fneg is free). So, we don't want to let the DAG 13501 // combiner rewrite fneg into xors and some other instructions. For f16 and 13502 // FullFP16 argument passing, some bitcast nodes may be introduced, 13503 // triggering this DAG combine rewrite, so we are avoiding that with this. 13504 switch (VT.getSimpleVT().SimpleTy) { 13505 default: break; 13506 case MVT::f16: 13507 return Subtarget->hasFullFP16(); 13508 } 13509 13510 return false; 13511 } 13512 13513 /// Check if Ext1 and Ext2 are extends of the same type, doubling the bitwidth 13514 /// of the vector elements. 13515 static bool areExtractExts(Value *Ext1, Value *Ext2) { 13516 auto areExtDoubled = [](Instruction *Ext) { 13517 return Ext->getType()->getScalarSizeInBits() == 13518 2 * Ext->getOperand(0)->getType()->getScalarSizeInBits(); 13519 }; 13520 13521 if (!match(Ext1, m_ZExtOrSExt(m_Value())) || 13522 !match(Ext2, m_ZExtOrSExt(m_Value())) || 13523 !areExtDoubled(cast<Instruction>(Ext1)) || 13524 !areExtDoubled(cast<Instruction>(Ext2))) 13525 return false; 13526 13527 return true; 13528 } 13529 13530 /// Check if sinking \p I's operands to I's basic block is profitable, because 13531 /// the operands can be folded into a target instruction, e.g. 13532 /// sext/zext can be folded into vsubl. 13533 bool ARMTargetLowering::shouldSinkOperands(Instruction *I, 13534 SmallVectorImpl<Use *> &Ops) const { 13535 if (!Subtarget->hasNEON() || !I->getType()->isVectorTy()) 13536 return false; 13537 13538 switch (I->getOpcode()) { 13539 case Instruction::Sub: 13540 case Instruction::Add: { 13541 if (!areExtractExts(I->getOperand(0), I->getOperand(1))) 13542 return false; 13543 Ops.push_back(&I->getOperandUse(0)); 13544 Ops.push_back(&I->getOperandUse(1)); 13545 return true; 13546 } 13547 default: 13548 return false; 13549 } 13550 return false; 13551 } 13552 13553 bool ARMTargetLowering::isVectorLoadExtDesirable(SDValue ExtVal) const { 13554 EVT VT = ExtVal.getValueType(); 13555 13556 if (!isTypeLegal(VT)) 13557 return false; 13558 13559 // Don't create a loadext if we can fold the extension into a wide/long 13560 // instruction. 13561 // If there's more than one user instruction, the loadext is desirable no 13562 // matter what. There can be two uses by the same instruction. 13563 if (ExtVal->use_empty() || 13564 !ExtVal->use_begin()->isOnlyUserOf(ExtVal.getNode())) 13565 return true; 13566 13567 SDNode *U = *ExtVal->use_begin(); 13568 if ((U->getOpcode() == ISD::ADD || U->getOpcode() == ISD::SUB || 13569 U->getOpcode() == ISD::SHL || U->getOpcode() == ARMISD::VSHL)) 13570 return false; 13571 13572 return true; 13573 } 13574 13575 bool ARMTargetLowering::allowTruncateForTailCall(Type *Ty1, Type *Ty2) const { 13576 if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy()) 13577 return false; 13578 13579 if (!isTypeLegal(EVT::getEVT(Ty1))) 13580 return false; 13581 13582 assert(Ty1->getPrimitiveSizeInBits() <= 64 && "i128 is probably not a noop"); 13583 13584 // Assuming the caller doesn't have a zeroext or signext return parameter, 13585 // truncation all the way down to i1 is valid. 13586 return true; 13587 } 13588 13589 int ARMTargetLowering::getScalingFactorCost(const DataLayout &DL, 13590 const AddrMode &AM, Type *Ty, 13591 unsigned AS) const { 13592 if (isLegalAddressingMode(DL, AM, Ty, AS)) { 13593 if (Subtarget->hasFPAO()) 13594 return AM.Scale < 0 ? 1 : 0; // positive offsets execute faster 13595 return 0; 13596 } 13597 return -1; 13598 } 13599 13600 static bool isLegalT1AddressImmediate(int64_t V, EVT VT) { 13601 if (V < 0) 13602 return false; 13603 13604 unsigned Scale = 1; 13605 switch (VT.getSimpleVT().SimpleTy) { 13606 case MVT::i1: 13607 case MVT::i8: 13608 // Scale == 1; 13609 break; 13610 case MVT::i16: 13611 // Scale == 2; 13612 Scale = 2; 13613 break; 13614 default: 13615 // On thumb1 we load most things (i32, i64, floats, etc) with a LDR 13616 // Scale == 4; 13617 Scale = 4; 13618 break; 13619 } 13620 13621 if ((V & (Scale - 1)) != 0) 13622 return false; 13623 return isUInt<5>(V / Scale); 13624 } 13625 13626 static bool isLegalT2AddressImmediate(int64_t V, EVT VT, 13627 const ARMSubtarget *Subtarget) { 13628 if (!VT.isInteger() && !VT.isFloatingPoint()) 13629 return false; 13630 if (VT.isVector() && Subtarget->hasNEON()) 13631 return false; 13632 if (VT.isVector() && VT.isFloatingPoint() && Subtarget->hasMVEIntegerOps() && 13633 !Subtarget->hasMVEFloatOps()) 13634 return false; 13635 13636 bool IsNeg = false; 13637 if (V < 0) { 13638 IsNeg = true; 13639 V = -V; 13640 } 13641 13642 unsigned NumBytes = std::max(VT.getSizeInBits() / 8, 1U); 13643 13644 // MVE: size * imm7 13645 if (VT.isVector() && Subtarget->hasMVEIntegerOps()) { 13646 switch (VT.getSimpleVT().getVectorElementType().SimpleTy) { 13647 case MVT::i32: 13648 case MVT::f32: 13649 return isShiftedUInt<7,2>(V); 13650 case MVT::i16: 13651 case MVT::f16: 13652 return isShiftedUInt<7,1>(V); 13653 case MVT::i8: 13654 return isUInt<7>(V); 13655 default: 13656 return false; 13657 } 13658 } 13659 13660 // half VLDR: 2 * imm8 13661 if (VT.isFloatingPoint() && NumBytes == 2 && Subtarget->hasFPRegs16()) 13662 return isShiftedUInt<8, 1>(V); 13663 // VLDR and LDRD: 4 * imm8 13664 if ((VT.isFloatingPoint() && Subtarget->hasVFP2Base()) || NumBytes == 8) 13665 return isShiftedUInt<8, 2>(V); 13666 13667 if (NumBytes == 1 || NumBytes == 2 || NumBytes == 4) { 13668 // + imm12 or - imm8 13669 if (IsNeg) 13670 return isUInt<8>(V); 13671 return isUInt<12>(V); 13672 } 13673 13674 return false; 13675 } 13676 13677 /// isLegalAddressImmediate - Return true if the integer value can be used 13678 /// as the offset of the target addressing mode for load / store of the 13679 /// given type. 13680 static bool isLegalAddressImmediate(int64_t V, EVT VT, 13681 const ARMSubtarget *Subtarget) { 13682 if (V == 0) 13683 return true; 13684 13685 if (!VT.isSimple()) 13686 return false; 13687 13688 if (Subtarget->isThumb1Only()) 13689 return isLegalT1AddressImmediate(V, VT); 13690 else if (Subtarget->isThumb2()) 13691 return isLegalT2AddressImmediate(V, VT, Subtarget); 13692 13693 // ARM mode. 13694 if (V < 0) 13695 V = - V; 13696 switch (VT.getSimpleVT().SimpleTy) { 13697 default: return false; 13698 case MVT::i1: 13699 case MVT::i8: 13700 case MVT::i32: 13701 // +- imm12 13702 return isUInt<12>(V); 13703 case MVT::i16: 13704 // +- imm8 13705 return isUInt<8>(V); 13706 case MVT::f32: 13707 case MVT::f64: 13708 if (!Subtarget->hasVFP2Base()) // FIXME: NEON? 13709 return false; 13710 return isShiftedUInt<8, 2>(V); 13711 } 13712 } 13713 13714 bool ARMTargetLowering::isLegalT2ScaledAddressingMode(const AddrMode &AM, 13715 EVT VT) const { 13716 int Scale = AM.Scale; 13717 if (Scale < 0) 13718 return false; 13719 13720 switch (VT.getSimpleVT().SimpleTy) { 13721 default: return false; 13722 case MVT::i1: 13723 case MVT::i8: 13724 case MVT::i16: 13725 case MVT::i32: 13726 if (Scale == 1) 13727 return true; 13728 // r + r << imm 13729 Scale = Scale & ~1; 13730 return Scale == 2 || Scale == 4 || Scale == 8; 13731 case MVT::i64: 13732 // FIXME: What are we trying to model here? ldrd doesn't have an r + r 13733 // version in Thumb mode. 13734 // r + r 13735 if (Scale == 1) 13736 return true; 13737 // r * 2 (this can be lowered to r + r). 13738 if (!AM.HasBaseReg && Scale == 2) 13739 return true; 13740 return false; 13741 case MVT::isVoid: 13742 // Note, we allow "void" uses (basically, uses that aren't loads or 13743 // stores), because arm allows folding a scale into many arithmetic 13744 // operations. This should be made more precise and revisited later. 13745 13746 // Allow r << imm, but the imm has to be a multiple of two. 13747 if (Scale & 1) return false; 13748 return isPowerOf2_32(Scale); 13749 } 13750 } 13751 13752 bool ARMTargetLowering::isLegalT1ScaledAddressingMode(const AddrMode &AM, 13753 EVT VT) const { 13754 const int Scale = AM.Scale; 13755 13756 // Negative scales are not supported in Thumb1. 13757 if (Scale < 0) 13758 return false; 13759 13760 // Thumb1 addressing modes do not support register scaling excepting the 13761 // following cases: 13762 // 1. Scale == 1 means no scaling. 13763 // 2. Scale == 2 this can be lowered to r + r if there is no base register. 13764 return (Scale == 1) || (!AM.HasBaseReg && Scale == 2); 13765 } 13766 13767 /// isLegalAddressingMode - Return true if the addressing mode represented 13768 /// by AM is legal for this target, for a load/store of the specified type. 13769 bool ARMTargetLowering::isLegalAddressingMode(const DataLayout &DL, 13770 const AddrMode &AM, Type *Ty, 13771 unsigned AS, Instruction *I) const { 13772 EVT VT = getValueType(DL, Ty, true); 13773 if (!isLegalAddressImmediate(AM.BaseOffs, VT, Subtarget)) 13774 return false; 13775 13776 // Can never fold addr of global into load/store. 13777 if (AM.BaseGV) 13778 return false; 13779 13780 switch (AM.Scale) { 13781 case 0: // no scale reg, must be "r+i" or "r", or "i". 13782 break; 13783 default: 13784 // ARM doesn't support any R+R*scale+imm addr modes. 13785 if (AM.BaseOffs) 13786 return false; 13787 13788 if (!VT.isSimple()) 13789 return false; 13790 13791 if (Subtarget->isThumb1Only()) 13792 return isLegalT1ScaledAddressingMode(AM, VT); 13793 13794 if (Subtarget->isThumb2()) 13795 return isLegalT2ScaledAddressingMode(AM, VT); 13796 13797 int Scale = AM.Scale; 13798 switch (VT.getSimpleVT().SimpleTy) { 13799 default: return false; 13800 case MVT::i1: 13801 case MVT::i8: 13802 case MVT::i32: 13803 if (Scale < 0) Scale = -Scale; 13804 if (Scale == 1) 13805 return true; 13806 // r + r << imm 13807 return isPowerOf2_32(Scale & ~1); 13808 case MVT::i16: 13809 case MVT::i64: 13810 // r +/- r 13811 if (Scale == 1 || (AM.HasBaseReg && Scale == -1)) 13812 return true; 13813 // r * 2 (this can be lowered to r + r). 13814 if (!AM.HasBaseReg && Scale == 2) 13815 return true; 13816 return false; 13817 13818 case MVT::isVoid: 13819 // Note, we allow "void" uses (basically, uses that aren't loads or 13820 // stores), because arm allows folding a scale into many arithmetic 13821 // operations. This should be made more precise and revisited later. 13822 13823 // Allow r << imm, but the imm has to be a multiple of two. 13824 if (Scale & 1) return false; 13825 return isPowerOf2_32(Scale); 13826 } 13827 } 13828 return true; 13829 } 13830 13831 /// isLegalICmpImmediate - Return true if the specified immediate is legal 13832 /// icmp immediate, that is the target has icmp instructions which can compare 13833 /// a register against the immediate without having to materialize the 13834 /// immediate into a register. 13835 bool ARMTargetLowering::isLegalICmpImmediate(int64_t Imm) const { 13836 // Thumb2 and ARM modes can use cmn for negative immediates. 13837 if (!Subtarget->isThumb()) 13838 return ARM_AM::getSOImmVal((uint32_t)Imm) != -1 || 13839 ARM_AM::getSOImmVal(-(uint32_t)Imm) != -1; 13840 if (Subtarget->isThumb2()) 13841 return ARM_AM::getT2SOImmVal((uint32_t)Imm) != -1 || 13842 ARM_AM::getT2SOImmVal(-(uint32_t)Imm) != -1; 13843 // Thumb1 doesn't have cmn, and only 8-bit immediates. 13844 return Imm >= 0 && Imm <= 255; 13845 } 13846 13847 /// isLegalAddImmediate - Return true if the specified immediate is a legal add 13848 /// *or sub* immediate, that is the target has add or sub instructions which can 13849 /// add a register with the immediate without having to materialize the 13850 /// immediate into a register. 13851 bool ARMTargetLowering::isLegalAddImmediate(int64_t Imm) const { 13852 // Same encoding for add/sub, just flip the sign. 13853 int64_t AbsImm = std::abs(Imm); 13854 if (!Subtarget->isThumb()) 13855 return ARM_AM::getSOImmVal(AbsImm) != -1; 13856 if (Subtarget->isThumb2()) 13857 return ARM_AM::getT2SOImmVal(AbsImm) != -1; 13858 // Thumb1 only has 8-bit unsigned immediate. 13859 return AbsImm >= 0 && AbsImm <= 255; 13860 } 13861 13862 static bool getARMIndexedAddressParts(SDNode *Ptr, EVT VT, 13863 bool isSEXTLoad, SDValue &Base, 13864 SDValue &Offset, bool &isInc, 13865 SelectionDAG &DAG) { 13866 if (Ptr->getOpcode() != ISD::ADD && Ptr->getOpcode() != ISD::SUB) 13867 return false; 13868 13869 if (VT == MVT::i16 || ((VT == MVT::i8 || VT == MVT::i1) && isSEXTLoad)) { 13870 // AddressingMode 3 13871 Base = Ptr->getOperand(0); 13872 if (ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(Ptr->getOperand(1))) { 13873 int RHSC = (int)RHS->getZExtValue(); 13874 if (RHSC < 0 && RHSC > -256) { 13875 assert(Ptr->getOpcode() == ISD::ADD); 13876 isInc = false; 13877 Offset = DAG.getConstant(-RHSC, SDLoc(Ptr), RHS->getValueType(0)); 13878 return true; 13879 } 13880 } 13881 isInc = (Ptr->getOpcode() == ISD::ADD); 13882 Offset = Ptr->getOperand(1); 13883 return true; 13884 } else if (VT == MVT::i32 || VT == MVT::i8 || VT == MVT::i1) { 13885 // AddressingMode 2 13886 if (ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(Ptr->getOperand(1))) { 13887 int RHSC = (int)RHS->getZExtValue(); 13888 if (RHSC < 0 && RHSC > -0x1000) { 13889 assert(Ptr->getOpcode() == ISD::ADD); 13890 isInc = false; 13891 Offset = DAG.getConstant(-RHSC, SDLoc(Ptr), RHS->getValueType(0)); 13892 Base = Ptr->getOperand(0); 13893 return true; 13894 } 13895 } 13896 13897 if (Ptr->getOpcode() == ISD::ADD) { 13898 isInc = true; 13899 ARM_AM::ShiftOpc ShOpcVal= 13900 ARM_AM::getShiftOpcForNode(Ptr->getOperand(0).getOpcode()); 13901 if (ShOpcVal != ARM_AM::no_shift) { 13902 Base = Ptr->getOperand(1); 13903 Offset = Ptr->getOperand(0); 13904 } else { 13905 Base = Ptr->getOperand(0); 13906 Offset = Ptr->getOperand(1); 13907 } 13908 return true; 13909 } 13910 13911 isInc = (Ptr->getOpcode() == ISD::ADD); 13912 Base = Ptr->getOperand(0); 13913 Offset = Ptr->getOperand(1); 13914 return true; 13915 } 13916 13917 // FIXME: Use VLDM / VSTM to emulate indexed FP load / store. 13918 return false; 13919 } 13920 13921 static bool getT2IndexedAddressParts(SDNode *Ptr, EVT VT, 13922 bool isSEXTLoad, SDValue &Base, 13923 SDValue &Offset, bool &isInc, 13924 SelectionDAG &DAG) { 13925 if (Ptr->getOpcode() != ISD::ADD && Ptr->getOpcode() != ISD::SUB) 13926 return false; 13927 13928 Base = Ptr->getOperand(0); 13929 if (ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(Ptr->getOperand(1))) { 13930 int RHSC = (int)RHS->getZExtValue(); 13931 if (RHSC < 0 && RHSC > -0x100) { // 8 bits. 13932 assert(Ptr->getOpcode() == ISD::ADD); 13933 isInc = false; 13934 Offset = DAG.getConstant(-RHSC, SDLoc(Ptr), RHS->getValueType(0)); 13935 return true; 13936 } else if (RHSC > 0 && RHSC < 0x100) { // 8 bit, no zero. 13937 isInc = Ptr->getOpcode() == ISD::ADD; 13938 Offset = DAG.getConstant(RHSC, SDLoc(Ptr), RHS->getValueType(0)); 13939 return true; 13940 } 13941 } 13942 13943 return false; 13944 } 13945 13946 /// getPreIndexedAddressParts - returns true by value, base pointer and 13947 /// offset pointer and addressing mode by reference if the node's address 13948 /// can be legally represented as pre-indexed load / store address. 13949 bool 13950 ARMTargetLowering::getPreIndexedAddressParts(SDNode *N, SDValue &Base, 13951 SDValue &Offset, 13952 ISD::MemIndexedMode &AM, 13953 SelectionDAG &DAG) const { 13954 if (Subtarget->isThumb1Only()) 13955 return false; 13956 13957 EVT VT; 13958 SDValue Ptr; 13959 bool isSEXTLoad = false; 13960 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) { 13961 Ptr = LD->getBasePtr(); 13962 VT = LD->getMemoryVT(); 13963 isSEXTLoad = LD->getExtensionType() == ISD::SEXTLOAD; 13964 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) { 13965 Ptr = ST->getBasePtr(); 13966 VT = ST->getMemoryVT(); 13967 } else 13968 return false; 13969 13970 bool isInc; 13971 bool isLegal = false; 13972 if (Subtarget->isThumb2()) 13973 isLegal = getT2IndexedAddressParts(Ptr.getNode(), VT, isSEXTLoad, Base, 13974 Offset, isInc, DAG); 13975 else 13976 isLegal = getARMIndexedAddressParts(Ptr.getNode(), VT, isSEXTLoad, Base, 13977 Offset, isInc, DAG); 13978 if (!isLegal) 13979 return false; 13980 13981 AM = isInc ? ISD::PRE_INC : ISD::PRE_DEC; 13982 return true; 13983 } 13984 13985 /// getPostIndexedAddressParts - returns true by value, base pointer and 13986 /// offset pointer and addressing mode by reference if this node can be 13987 /// combined with a load / store to form a post-indexed load / store. 13988 bool ARMTargetLowering::getPostIndexedAddressParts(SDNode *N, SDNode *Op, 13989 SDValue &Base, 13990 SDValue &Offset, 13991 ISD::MemIndexedMode &AM, 13992 SelectionDAG &DAG) const { 13993 EVT VT; 13994 SDValue Ptr; 13995 bool isSEXTLoad = false, isNonExt; 13996 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) { 13997 VT = LD->getMemoryVT(); 13998 Ptr = LD->getBasePtr(); 13999 isSEXTLoad = LD->getExtensionType() == ISD::SEXTLOAD; 14000 isNonExt = LD->getExtensionType() == ISD::NON_EXTLOAD; 14001 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) { 14002 VT = ST->getMemoryVT(); 14003 Ptr = ST->getBasePtr(); 14004 isNonExt = !ST->isTruncatingStore(); 14005 } else 14006 return false; 14007 14008 if (Subtarget->isThumb1Only()) { 14009 // Thumb-1 can do a limited post-inc load or store as an updating LDM. It 14010 // must be non-extending/truncating, i32, with an offset of 4. 14011 assert(Op->getValueType(0) == MVT::i32 && "Non-i32 post-inc op?!"); 14012 if (Op->getOpcode() != ISD::ADD || !isNonExt) 14013 return false; 14014 auto *RHS = dyn_cast<ConstantSDNode>(Op->getOperand(1)); 14015 if (!RHS || RHS->getZExtValue() != 4) 14016 return false; 14017 14018 Offset = Op->getOperand(1); 14019 Base = Op->getOperand(0); 14020 AM = ISD::POST_INC; 14021 return true; 14022 } 14023 14024 bool isInc; 14025 bool isLegal = false; 14026 if (Subtarget->isThumb2()) 14027 isLegal = getT2IndexedAddressParts(Op, VT, isSEXTLoad, Base, Offset, 14028 isInc, DAG); 14029 else 14030 isLegal = getARMIndexedAddressParts(Op, VT, isSEXTLoad, Base, Offset, 14031 isInc, DAG); 14032 if (!isLegal) 14033 return false; 14034 14035 if (Ptr != Base) { 14036 // Swap base ptr and offset to catch more post-index load / store when 14037 // it's legal. In Thumb2 mode, offset must be an immediate. 14038 if (Ptr == Offset && Op->getOpcode() == ISD::ADD && 14039 !Subtarget->isThumb2()) 14040 std::swap(Base, Offset); 14041 14042 // Post-indexed load / store update the base pointer. 14043 if (Ptr != Base) 14044 return false; 14045 } 14046 14047 AM = isInc ? ISD::POST_INC : ISD::POST_DEC; 14048 return true; 14049 } 14050 14051 void ARMTargetLowering::computeKnownBitsForTargetNode(const SDValue Op, 14052 KnownBits &Known, 14053 const APInt &DemandedElts, 14054 const SelectionDAG &DAG, 14055 unsigned Depth) const { 14056 unsigned BitWidth = Known.getBitWidth(); 14057 Known.resetAll(); 14058 switch (Op.getOpcode()) { 14059 default: break; 14060 case ARMISD::ADDC: 14061 case ARMISD::ADDE: 14062 case ARMISD::SUBC: 14063 case ARMISD::SUBE: 14064 // Special cases when we convert a carry to a boolean. 14065 if (Op.getResNo() == 0) { 14066 SDValue LHS = Op.getOperand(0); 14067 SDValue RHS = Op.getOperand(1); 14068 // (ADDE 0, 0, C) will give us a single bit. 14069 if (Op->getOpcode() == ARMISD::ADDE && isNullConstant(LHS) && 14070 isNullConstant(RHS)) { 14071 Known.Zero |= APInt::getHighBitsSet(BitWidth, BitWidth - 1); 14072 return; 14073 } 14074 } 14075 break; 14076 case ARMISD::CMOV: { 14077 // Bits are known zero/one if known on the LHS and RHS. 14078 Known = DAG.computeKnownBits(Op.getOperand(0), Depth+1); 14079 if (Known.isUnknown()) 14080 return; 14081 14082 KnownBits KnownRHS = DAG.computeKnownBits(Op.getOperand(1), Depth+1); 14083 Known.Zero &= KnownRHS.Zero; 14084 Known.One &= KnownRHS.One; 14085 return; 14086 } 14087 case ISD::INTRINSIC_W_CHAIN: { 14088 ConstantSDNode *CN = cast<ConstantSDNode>(Op->getOperand(1)); 14089 Intrinsic::ID IntID = static_cast<Intrinsic::ID>(CN->getZExtValue()); 14090 switch (IntID) { 14091 default: return; 14092 case Intrinsic::arm_ldaex: 14093 case Intrinsic::arm_ldrex: { 14094 EVT VT = cast<MemIntrinsicSDNode>(Op)->getMemoryVT(); 14095 unsigned MemBits = VT.getScalarSizeInBits(); 14096 Known.Zero |= APInt::getHighBitsSet(BitWidth, BitWidth - MemBits); 14097 return; 14098 } 14099 } 14100 } 14101 case ARMISD::BFI: { 14102 // Conservatively, we can recurse down the first operand 14103 // and just mask out all affected bits. 14104 Known = DAG.computeKnownBits(Op.getOperand(0), Depth + 1); 14105 14106 // The operand to BFI is already a mask suitable for removing the bits it 14107 // sets. 14108 ConstantSDNode *CI = cast<ConstantSDNode>(Op.getOperand(2)); 14109 const APInt &Mask = CI->getAPIntValue(); 14110 Known.Zero &= Mask; 14111 Known.One &= Mask; 14112 return; 14113 } 14114 case ARMISD::VGETLANEs: 14115 case ARMISD::VGETLANEu: { 14116 const SDValue &SrcSV = Op.getOperand(0); 14117 EVT VecVT = SrcSV.getValueType(); 14118 assert(VecVT.isVector() && "VGETLANE expected a vector type"); 14119 const unsigned NumSrcElts = VecVT.getVectorNumElements(); 14120 ConstantSDNode *Pos = cast<ConstantSDNode>(Op.getOperand(1).getNode()); 14121 assert(Pos->getAPIntValue().ult(NumSrcElts) && 14122 "VGETLANE index out of bounds"); 14123 unsigned Idx = Pos->getZExtValue(); 14124 APInt DemandedElt = APInt::getOneBitSet(NumSrcElts, Idx); 14125 Known = DAG.computeKnownBits(SrcSV, DemandedElt, Depth + 1); 14126 14127 EVT VT = Op.getValueType(); 14128 const unsigned DstSz = VT.getScalarSizeInBits(); 14129 const unsigned SrcSz = VecVT.getVectorElementType().getSizeInBits(); 14130 (void)SrcSz; 14131 assert(SrcSz == Known.getBitWidth()); 14132 assert(DstSz > SrcSz); 14133 if (Op.getOpcode() == ARMISD::VGETLANEs) 14134 Known = Known.sext(DstSz); 14135 else { 14136 Known = Known.zext(DstSz, true /* extended bits are known zero */); 14137 } 14138 assert(DstSz == Known.getBitWidth()); 14139 break; 14140 } 14141 } 14142 } 14143 14144 bool 14145 ARMTargetLowering::targetShrinkDemandedConstant(SDValue Op, 14146 const APInt &DemandedAPInt, 14147 TargetLoweringOpt &TLO) const { 14148 // Delay optimization, so we don't have to deal with illegal types, or block 14149 // optimizations. 14150 if (!TLO.LegalOps) 14151 return false; 14152 14153 // Only optimize AND for now. 14154 if (Op.getOpcode() != ISD::AND) 14155 return false; 14156 14157 EVT VT = Op.getValueType(); 14158 14159 // Ignore vectors. 14160 if (VT.isVector()) 14161 return false; 14162 14163 assert(VT == MVT::i32 && "Unexpected integer type"); 14164 14165 // Make sure the RHS really is a constant. 14166 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1)); 14167 if (!C) 14168 return false; 14169 14170 unsigned Mask = C->getZExtValue(); 14171 14172 unsigned Demanded = DemandedAPInt.getZExtValue(); 14173 unsigned ShrunkMask = Mask & Demanded; 14174 unsigned ExpandedMask = Mask | ~Demanded; 14175 14176 // If the mask is all zeros, let the target-independent code replace the 14177 // result with zero. 14178 if (ShrunkMask == 0) 14179 return false; 14180 14181 // If the mask is all ones, erase the AND. (Currently, the target-independent 14182 // code won't do this, so we have to do it explicitly to avoid an infinite 14183 // loop in obscure cases.) 14184 if (ExpandedMask == ~0U) 14185 return TLO.CombineTo(Op, Op.getOperand(0)); 14186 14187 auto IsLegalMask = [ShrunkMask, ExpandedMask](unsigned Mask) -> bool { 14188 return (ShrunkMask & Mask) == ShrunkMask && (~ExpandedMask & Mask) == 0; 14189 }; 14190 auto UseMask = [Mask, Op, VT, &TLO](unsigned NewMask) -> bool { 14191 if (NewMask == Mask) 14192 return true; 14193 SDLoc DL(Op); 14194 SDValue NewC = TLO.DAG.getConstant(NewMask, DL, VT); 14195 SDValue NewOp = TLO.DAG.getNode(ISD::AND, DL, VT, Op.getOperand(0), NewC); 14196 return TLO.CombineTo(Op, NewOp); 14197 }; 14198 14199 // Prefer uxtb mask. 14200 if (IsLegalMask(0xFF)) 14201 return UseMask(0xFF); 14202 14203 // Prefer uxth mask. 14204 if (IsLegalMask(0xFFFF)) 14205 return UseMask(0xFFFF); 14206 14207 // [1, 255] is Thumb1 movs+ands, legal immediate for ARM/Thumb2. 14208 // FIXME: Prefer a contiguous sequence of bits for other optimizations. 14209 if (ShrunkMask < 256) 14210 return UseMask(ShrunkMask); 14211 14212 // [-256, -2] is Thumb1 movs+bics, legal immediate for ARM/Thumb2. 14213 // FIXME: Prefer a contiguous sequence of bits for other optimizations. 14214 if ((int)ExpandedMask <= -2 && (int)ExpandedMask >= -256) 14215 return UseMask(ExpandedMask); 14216 14217 // Potential improvements: 14218 // 14219 // We could try to recognize lsls+lsrs or lsrs+lsls pairs here. 14220 // We could try to prefer Thumb1 immediates which can be lowered to a 14221 // two-instruction sequence. 14222 // We could try to recognize more legal ARM/Thumb2 immediates here. 14223 14224 return false; 14225 } 14226 14227 14228 //===----------------------------------------------------------------------===// 14229 // ARM Inline Assembly Support 14230 //===----------------------------------------------------------------------===// 14231 14232 bool ARMTargetLowering::ExpandInlineAsm(CallInst *CI) const { 14233 // Looking for "rev" which is V6+. 14234 if (!Subtarget->hasV6Ops()) 14235 return false; 14236 14237 InlineAsm *IA = cast<InlineAsm>(CI->getCalledValue()); 14238 std::string AsmStr = IA->getAsmString(); 14239 SmallVector<StringRef, 4> AsmPieces; 14240 SplitString(AsmStr, AsmPieces, ";\n"); 14241 14242 switch (AsmPieces.size()) { 14243 default: return false; 14244 case 1: 14245 AsmStr = AsmPieces[0]; 14246 AsmPieces.clear(); 14247 SplitString(AsmStr, AsmPieces, " \t,"); 14248 14249 // rev $0, $1 14250 if (AsmPieces.size() == 3 && 14251 AsmPieces[0] == "rev" && AsmPieces[1] == "$0" && AsmPieces[2] == "$1" && 14252 IA->getConstraintString().compare(0, 4, "=l,l") == 0) { 14253 IntegerType *Ty = dyn_cast<IntegerType>(CI->getType()); 14254 if (Ty && Ty->getBitWidth() == 32) 14255 return IntrinsicLowering::LowerToByteSwap(CI); 14256 } 14257 break; 14258 } 14259 14260 return false; 14261 } 14262 14263 const char *ARMTargetLowering::LowerXConstraint(EVT ConstraintVT) const { 14264 // At this point, we have to lower this constraint to something else, so we 14265 // lower it to an "r" or "w". However, by doing this we will force the result 14266 // to be in register, while the X constraint is much more permissive. 14267 // 14268 // Although we are correct (we are free to emit anything, without 14269 // constraints), we might break use cases that would expect us to be more 14270 // efficient and emit something else. 14271 if (!Subtarget->hasVFP2Base()) 14272 return "r"; 14273 if (ConstraintVT.isFloatingPoint()) 14274 return "w"; 14275 if (ConstraintVT.isVector() && Subtarget->hasNEON() && 14276 (ConstraintVT.getSizeInBits() == 64 || 14277 ConstraintVT.getSizeInBits() == 128)) 14278 return "w"; 14279 14280 return "r"; 14281 } 14282 14283 /// getConstraintType - Given a constraint letter, return the type of 14284 /// constraint it is for this target. 14285 ARMTargetLowering::ConstraintType 14286 ARMTargetLowering::getConstraintType(StringRef Constraint) const { 14287 if (Constraint.size() == 1) { 14288 switch (Constraint[0]) { 14289 default: break; 14290 case 'l': return C_RegisterClass; 14291 case 'w': return C_RegisterClass; 14292 case 'h': return C_RegisterClass; 14293 case 'x': return C_RegisterClass; 14294 case 't': return C_RegisterClass; 14295 case 'j': return C_Other; // Constant for movw. 14296 // An address with a single base register. Due to the way we 14297 // currently handle addresses it is the same as an 'r' memory constraint. 14298 case 'Q': return C_Memory; 14299 } 14300 } else if (Constraint.size() == 2) { 14301 switch (Constraint[0]) { 14302 default: break; 14303 case 'T': return C_RegisterClass; 14304 // All 'U+' constraints are addresses. 14305 case 'U': return C_Memory; 14306 } 14307 } 14308 return TargetLowering::getConstraintType(Constraint); 14309 } 14310 14311 /// Examine constraint type and operand type and determine a weight value. 14312 /// This object must already have been set up with the operand type 14313 /// and the current alternative constraint selected. 14314 TargetLowering::ConstraintWeight 14315 ARMTargetLowering::getSingleConstraintMatchWeight( 14316 AsmOperandInfo &info, const char *constraint) const { 14317 ConstraintWeight weight = CW_Invalid; 14318 Value *CallOperandVal = info.CallOperandVal; 14319 // If we don't have a value, we can't do a match, 14320 // but allow it at the lowest weight. 14321 if (!CallOperandVal) 14322 return CW_Default; 14323 Type *type = CallOperandVal->getType(); 14324 // Look at the constraint type. 14325 switch (*constraint) { 14326 default: 14327 weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint); 14328 break; 14329 case 'l': 14330 if (type->isIntegerTy()) { 14331 if (Subtarget->isThumb()) 14332 weight = CW_SpecificReg; 14333 else 14334 weight = CW_Register; 14335 } 14336 break; 14337 case 'w': 14338 if (type->isFloatingPointTy()) 14339 weight = CW_Register; 14340 break; 14341 } 14342 return weight; 14343 } 14344 14345 using RCPair = std::pair<unsigned, const TargetRegisterClass *>; 14346 14347 RCPair ARMTargetLowering::getRegForInlineAsmConstraint( 14348 const TargetRegisterInfo *TRI, StringRef Constraint, MVT VT) const { 14349 switch (Constraint.size()) { 14350 case 1: 14351 // GCC ARM Constraint Letters 14352 switch (Constraint[0]) { 14353 case 'l': // Low regs or general regs. 14354 if (Subtarget->isThumb()) 14355 return RCPair(0U, &ARM::tGPRRegClass); 14356 return RCPair(0U, &ARM::GPRRegClass); 14357 case 'h': // High regs or no regs. 14358 if (Subtarget->isThumb()) 14359 return RCPair(0U, &ARM::hGPRRegClass); 14360 break; 14361 case 'r': 14362 if (Subtarget->isThumb1Only()) 14363 return RCPair(0U, &ARM::tGPRRegClass); 14364 return RCPair(0U, &ARM::GPRRegClass); 14365 case 'w': 14366 if (VT == MVT::Other) 14367 break; 14368 if (VT == MVT::f32) 14369 return RCPair(0U, &ARM::SPRRegClass); 14370 if (VT.getSizeInBits() == 64) 14371 return RCPair(0U, &ARM::DPRRegClass); 14372 if (VT.getSizeInBits() == 128) 14373 return RCPair(0U, &ARM::QPRRegClass); 14374 break; 14375 case 'x': 14376 if (VT == MVT::Other) 14377 break; 14378 if (VT == MVT::f32) 14379 return RCPair(0U, &ARM::SPR_8RegClass); 14380 if (VT.getSizeInBits() == 64) 14381 return RCPair(0U, &ARM::DPR_8RegClass); 14382 if (VT.getSizeInBits() == 128) 14383 return RCPair(0U, &ARM::QPR_8RegClass); 14384 break; 14385 case 't': 14386 if (VT == MVT::Other) 14387 break; 14388 if (VT == MVT::f32 || VT == MVT::i32) 14389 return RCPair(0U, &ARM::SPRRegClass); 14390 if (VT.getSizeInBits() == 64) 14391 return RCPair(0U, &ARM::DPR_VFP2RegClass); 14392 if (VT.getSizeInBits() == 128) 14393 return RCPair(0U, &ARM::QPR_VFP2RegClass); 14394 break; 14395 } 14396 break; 14397 14398 case 2: 14399 if (Constraint[0] == 'T') { 14400 switch (Constraint[1]) { 14401 default: 14402 break; 14403 case 'e': 14404 return RCPair(0U, &ARM::tGPREvenRegClass); 14405 case 'o': 14406 return RCPair(0U, &ARM::tGPROddRegClass); 14407 } 14408 } 14409 break; 14410 14411 default: 14412 break; 14413 } 14414 14415 if (StringRef("{cc}").equals_lower(Constraint)) 14416 return std::make_pair(unsigned(ARM::CPSR), &ARM::CCRRegClass); 14417 14418 return TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT); 14419 } 14420 14421 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops 14422 /// vector. If it is invalid, don't add anything to Ops. 14423 void ARMTargetLowering::LowerAsmOperandForConstraint(SDValue Op, 14424 std::string &Constraint, 14425 std::vector<SDValue>&Ops, 14426 SelectionDAG &DAG) const { 14427 SDValue Result; 14428 14429 // Currently only support length 1 constraints. 14430 if (Constraint.length() != 1) return; 14431 14432 char ConstraintLetter = Constraint[0]; 14433 switch (ConstraintLetter) { 14434 default: break; 14435 case 'j': 14436 case 'I': case 'J': case 'K': case 'L': 14437 case 'M': case 'N': case 'O': 14438 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op); 14439 if (!C) 14440 return; 14441 14442 int64_t CVal64 = C->getSExtValue(); 14443 int CVal = (int) CVal64; 14444 // None of these constraints allow values larger than 32 bits. Check 14445 // that the value fits in an int. 14446 if (CVal != CVal64) 14447 return; 14448 14449 switch (ConstraintLetter) { 14450 case 'j': 14451 // Constant suitable for movw, must be between 0 and 14452 // 65535. 14453 if (Subtarget->hasV6T2Ops()) 14454 if (CVal >= 0 && CVal <= 65535) 14455 break; 14456 return; 14457 case 'I': 14458 if (Subtarget->isThumb1Only()) { 14459 // This must be a constant between 0 and 255, for ADD 14460 // immediates. 14461 if (CVal >= 0 && CVal <= 255) 14462 break; 14463 } else if (Subtarget->isThumb2()) { 14464 // A constant that can be used as an immediate value in a 14465 // data-processing instruction. 14466 if (ARM_AM::getT2SOImmVal(CVal) != -1) 14467 break; 14468 } else { 14469 // A constant that can be used as an immediate value in a 14470 // data-processing instruction. 14471 if (ARM_AM::getSOImmVal(CVal) != -1) 14472 break; 14473 } 14474 return; 14475 14476 case 'J': 14477 if (Subtarget->isThumb1Only()) { 14478 // This must be a constant between -255 and -1, for negated ADD 14479 // immediates. This can be used in GCC with an "n" modifier that 14480 // prints the negated value, for use with SUB instructions. It is 14481 // not useful otherwise but is implemented for compatibility. 14482 if (CVal >= -255 && CVal <= -1) 14483 break; 14484 } else { 14485 // This must be a constant between -4095 and 4095. It is not clear 14486 // what this constraint is intended for. Implemented for 14487 // compatibility with GCC. 14488 if (CVal >= -4095 && CVal <= 4095) 14489 break; 14490 } 14491 return; 14492 14493 case 'K': 14494 if (Subtarget->isThumb1Only()) { 14495 // A 32-bit value where only one byte has a nonzero value. Exclude 14496 // zero to match GCC. This constraint is used by GCC internally for 14497 // constants that can be loaded with a move/shift combination. 14498 // It is not useful otherwise but is implemented for compatibility. 14499 if (CVal != 0 && ARM_AM::isThumbImmShiftedVal(CVal)) 14500 break; 14501 } else if (Subtarget->isThumb2()) { 14502 // A constant whose bitwise inverse can be used as an immediate 14503 // value in a data-processing instruction. This can be used in GCC 14504 // with a "B" modifier that prints the inverted value, for use with 14505 // BIC and MVN instructions. It is not useful otherwise but is 14506 // implemented for compatibility. 14507 if (ARM_AM::getT2SOImmVal(~CVal) != -1) 14508 break; 14509 } else { 14510 // A constant whose bitwise inverse can be used as an immediate 14511 // value in a data-processing instruction. This can be used in GCC 14512 // with a "B" modifier that prints the inverted value, for use with 14513 // BIC and MVN instructions. It is not useful otherwise but is 14514 // implemented for compatibility. 14515 if (ARM_AM::getSOImmVal(~CVal) != -1) 14516 break; 14517 } 14518 return; 14519 14520 case 'L': 14521 if (Subtarget->isThumb1Only()) { 14522 // This must be a constant between -7 and 7, 14523 // for 3-operand ADD/SUB immediate instructions. 14524 if (CVal >= -7 && CVal < 7) 14525 break; 14526 } else if (Subtarget->isThumb2()) { 14527 // A constant whose negation can be used as an immediate value in a 14528 // data-processing instruction. This can be used in GCC with an "n" 14529 // modifier that prints the negated value, for use with SUB 14530 // instructions. It is not useful otherwise but is implemented for 14531 // compatibility. 14532 if (ARM_AM::getT2SOImmVal(-CVal) != -1) 14533 break; 14534 } else { 14535 // A constant whose negation can be used as an immediate value in a 14536 // data-processing instruction. This can be used in GCC with an "n" 14537 // modifier that prints the negated value, for use with SUB 14538 // instructions. It is not useful otherwise but is implemented for 14539 // compatibility. 14540 if (ARM_AM::getSOImmVal(-CVal) != -1) 14541 break; 14542 } 14543 return; 14544 14545 case 'M': 14546 if (Subtarget->isThumb1Only()) { 14547 // This must be a multiple of 4 between 0 and 1020, for 14548 // ADD sp + immediate. 14549 if ((CVal >= 0 && CVal <= 1020) && ((CVal & 3) == 0)) 14550 break; 14551 } else { 14552 // A power of two or a constant between 0 and 32. This is used in 14553 // GCC for the shift amount on shifted register operands, but it is 14554 // useful in general for any shift amounts. 14555 if ((CVal >= 0 && CVal <= 32) || ((CVal & (CVal - 1)) == 0)) 14556 break; 14557 } 14558 return; 14559 14560 case 'N': 14561 if (Subtarget->isThumb()) { // FIXME thumb2 14562 // This must be a constant between 0 and 31, for shift amounts. 14563 if (CVal >= 0 && CVal <= 31) 14564 break; 14565 } 14566 return; 14567 14568 case 'O': 14569 if (Subtarget->isThumb()) { // FIXME thumb2 14570 // This must be a multiple of 4 between -508 and 508, for 14571 // ADD/SUB sp = sp + immediate. 14572 if ((CVal >= -508 && CVal <= 508) && ((CVal & 3) == 0)) 14573 break; 14574 } 14575 return; 14576 } 14577 Result = DAG.getTargetConstant(CVal, SDLoc(Op), Op.getValueType()); 14578 break; 14579 } 14580 14581 if (Result.getNode()) { 14582 Ops.push_back(Result); 14583 return; 14584 } 14585 return TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG); 14586 } 14587 14588 static RTLIB::Libcall getDivRemLibcall( 14589 const SDNode *N, MVT::SimpleValueType SVT) { 14590 assert((N->getOpcode() == ISD::SDIVREM || N->getOpcode() == ISD::UDIVREM || 14591 N->getOpcode() == ISD::SREM || N->getOpcode() == ISD::UREM) && 14592 "Unhandled Opcode in getDivRemLibcall"); 14593 bool isSigned = N->getOpcode() == ISD::SDIVREM || 14594 N->getOpcode() == ISD::SREM; 14595 RTLIB::Libcall LC; 14596 switch (SVT) { 14597 default: llvm_unreachable("Unexpected request for libcall!"); 14598 case MVT::i8: LC = isSigned ? RTLIB::SDIVREM_I8 : RTLIB::UDIVREM_I8; break; 14599 case MVT::i16: LC = isSigned ? RTLIB::SDIVREM_I16 : RTLIB::UDIVREM_I16; break; 14600 case MVT::i32: LC = isSigned ? RTLIB::SDIVREM_I32 : RTLIB::UDIVREM_I32; break; 14601 case MVT::i64: LC = isSigned ? RTLIB::SDIVREM_I64 : RTLIB::UDIVREM_I64; break; 14602 } 14603 return LC; 14604 } 14605 14606 static TargetLowering::ArgListTy getDivRemArgList( 14607 const SDNode *N, LLVMContext *Context, const ARMSubtarget *Subtarget) { 14608 assert((N->getOpcode() == ISD::SDIVREM || N->getOpcode() == ISD::UDIVREM || 14609 N->getOpcode() == ISD::SREM || N->getOpcode() == ISD::UREM) && 14610 "Unhandled Opcode in getDivRemArgList"); 14611 bool isSigned = N->getOpcode() == ISD::SDIVREM || 14612 N->getOpcode() == ISD::SREM; 14613 TargetLowering::ArgListTy Args; 14614 TargetLowering::ArgListEntry Entry; 14615 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) { 14616 EVT ArgVT = N->getOperand(i).getValueType(); 14617 Type *ArgTy = ArgVT.getTypeForEVT(*Context); 14618 Entry.Node = N->getOperand(i); 14619 Entry.Ty = ArgTy; 14620 Entry.IsSExt = isSigned; 14621 Entry.IsZExt = !isSigned; 14622 Args.push_back(Entry); 14623 } 14624 if (Subtarget->isTargetWindows() && Args.size() >= 2) 14625 std::swap(Args[0], Args[1]); 14626 return Args; 14627 } 14628 14629 SDValue ARMTargetLowering::LowerDivRem(SDValue Op, SelectionDAG &DAG) const { 14630 assert((Subtarget->isTargetAEABI() || Subtarget->isTargetAndroid() || 14631 Subtarget->isTargetGNUAEABI() || Subtarget->isTargetMuslAEABI() || 14632 Subtarget->isTargetWindows()) && 14633 "Register-based DivRem lowering only"); 14634 unsigned Opcode = Op->getOpcode(); 14635 assert((Opcode == ISD::SDIVREM || Opcode == ISD::UDIVREM) && 14636 "Invalid opcode for Div/Rem lowering"); 14637 bool isSigned = (Opcode == ISD::SDIVREM); 14638 EVT VT = Op->getValueType(0); 14639 Type *Ty = VT.getTypeForEVT(*DAG.getContext()); 14640 SDLoc dl(Op); 14641 14642 // If the target has hardware divide, use divide + multiply + subtract: 14643 // div = a / b 14644 // rem = a - b * div 14645 // return {div, rem} 14646 // This should be lowered into UDIV/SDIV + MLS later on. 14647 bool hasDivide = Subtarget->isThumb() ? Subtarget->hasDivideInThumbMode() 14648 : Subtarget->hasDivideInARMMode(); 14649 if (hasDivide && Op->getValueType(0).isSimple() && 14650 Op->getSimpleValueType(0) == MVT::i32) { 14651 unsigned DivOpcode = isSigned ? ISD::SDIV : ISD::UDIV; 14652 const SDValue Dividend = Op->getOperand(0); 14653 const SDValue Divisor = Op->getOperand(1); 14654 SDValue Div = DAG.getNode(DivOpcode, dl, VT, Dividend, Divisor); 14655 SDValue Mul = DAG.getNode(ISD::MUL, dl, VT, Div, Divisor); 14656 SDValue Rem = DAG.getNode(ISD::SUB, dl, VT, Dividend, Mul); 14657 14658 SDValue Values[2] = {Div, Rem}; 14659 return DAG.getNode(ISD::MERGE_VALUES, dl, DAG.getVTList(VT, VT), Values); 14660 } 14661 14662 RTLIB::Libcall LC = getDivRemLibcall(Op.getNode(), 14663 VT.getSimpleVT().SimpleTy); 14664 SDValue InChain = DAG.getEntryNode(); 14665 14666 TargetLowering::ArgListTy Args = getDivRemArgList(Op.getNode(), 14667 DAG.getContext(), 14668 Subtarget); 14669 14670 SDValue Callee = DAG.getExternalSymbol(getLibcallName(LC), 14671 getPointerTy(DAG.getDataLayout())); 14672 14673 Type *RetTy = StructType::get(Ty, Ty); 14674 14675 if (Subtarget->isTargetWindows()) 14676 InChain = WinDBZCheckDenominator(DAG, Op.getNode(), InChain); 14677 14678 TargetLowering::CallLoweringInfo CLI(DAG); 14679 CLI.setDebugLoc(dl).setChain(InChain) 14680 .setCallee(getLibcallCallingConv(LC), RetTy, Callee, std::move(Args)) 14681 .setInRegister().setSExtResult(isSigned).setZExtResult(!isSigned); 14682 14683 std::pair<SDValue, SDValue> CallInfo = LowerCallTo(CLI); 14684 return CallInfo.first; 14685 } 14686 14687 // Lowers REM using divmod helpers 14688 // see RTABI section 4.2/4.3 14689 SDValue ARMTargetLowering::LowerREM(SDNode *N, SelectionDAG &DAG) const { 14690 // Build return types (div and rem) 14691 std::vector<Type*> RetTyParams; 14692 Type *RetTyElement; 14693 14694 switch (N->getValueType(0).getSimpleVT().SimpleTy) { 14695 default: llvm_unreachable("Unexpected request for libcall!"); 14696 case MVT::i8: RetTyElement = Type::getInt8Ty(*DAG.getContext()); break; 14697 case MVT::i16: RetTyElement = Type::getInt16Ty(*DAG.getContext()); break; 14698 case MVT::i32: RetTyElement = Type::getInt32Ty(*DAG.getContext()); break; 14699 case MVT::i64: RetTyElement = Type::getInt64Ty(*DAG.getContext()); break; 14700 } 14701 14702 RetTyParams.push_back(RetTyElement); 14703 RetTyParams.push_back(RetTyElement); 14704 ArrayRef<Type*> ret = ArrayRef<Type*>(RetTyParams); 14705 Type *RetTy = StructType::get(*DAG.getContext(), ret); 14706 14707 RTLIB::Libcall LC = getDivRemLibcall(N, N->getValueType(0).getSimpleVT(). 14708 SimpleTy); 14709 SDValue InChain = DAG.getEntryNode(); 14710 TargetLowering::ArgListTy Args = getDivRemArgList(N, DAG.getContext(), 14711 Subtarget); 14712 bool isSigned = N->getOpcode() == ISD::SREM; 14713 SDValue Callee = DAG.getExternalSymbol(getLibcallName(LC), 14714 getPointerTy(DAG.getDataLayout())); 14715 14716 if (Subtarget->isTargetWindows()) 14717 InChain = WinDBZCheckDenominator(DAG, N, InChain); 14718 14719 // Lower call 14720 CallLoweringInfo CLI(DAG); 14721 CLI.setChain(InChain) 14722 .setCallee(CallingConv::ARM_AAPCS, RetTy, Callee, std::move(Args)) 14723 .setSExtResult(isSigned).setZExtResult(!isSigned).setDebugLoc(SDLoc(N)); 14724 std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI); 14725 14726 // Return second (rem) result operand (first contains div) 14727 SDNode *ResNode = CallResult.first.getNode(); 14728 assert(ResNode->getNumOperands() == 2 && "divmod should return two operands"); 14729 return ResNode->getOperand(1); 14730 } 14731 14732 SDValue 14733 ARMTargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op, SelectionDAG &DAG) const { 14734 assert(Subtarget->isTargetWindows() && "unsupported target platform"); 14735 SDLoc DL(Op); 14736 14737 // Get the inputs. 14738 SDValue Chain = Op.getOperand(0); 14739 SDValue Size = Op.getOperand(1); 14740 14741 if (DAG.getMachineFunction().getFunction().hasFnAttribute( 14742 "no-stack-arg-probe")) { 14743 unsigned Align = cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue(); 14744 SDValue SP = DAG.getCopyFromReg(Chain, DL, ARM::SP, MVT::i32); 14745 Chain = SP.getValue(1); 14746 SP = DAG.getNode(ISD::SUB, DL, MVT::i32, SP, Size); 14747 if (Align) 14748 SP = DAG.getNode(ISD::AND, DL, MVT::i32, SP.getValue(0), 14749 DAG.getConstant(-(uint64_t)Align, DL, MVT::i32)); 14750 Chain = DAG.getCopyToReg(Chain, DL, ARM::SP, SP); 14751 SDValue Ops[2] = { SP, Chain }; 14752 return DAG.getMergeValues(Ops, DL); 14753 } 14754 14755 SDValue Words = DAG.getNode(ISD::SRL, DL, MVT::i32, Size, 14756 DAG.getConstant(2, DL, MVT::i32)); 14757 14758 SDValue Flag; 14759 Chain = DAG.getCopyToReg(Chain, DL, ARM::R4, Words, Flag); 14760 Flag = Chain.getValue(1); 14761 14762 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue); 14763 Chain = DAG.getNode(ARMISD::WIN__CHKSTK, DL, NodeTys, Chain, Flag); 14764 14765 SDValue NewSP = DAG.getCopyFromReg(Chain, DL, ARM::SP, MVT::i32); 14766 Chain = NewSP.getValue(1); 14767 14768 SDValue Ops[2] = { NewSP, Chain }; 14769 return DAG.getMergeValues(Ops, DL); 14770 } 14771 14772 SDValue ARMTargetLowering::LowerFP_EXTEND(SDValue Op, SelectionDAG &DAG) const { 14773 SDValue SrcVal = Op.getOperand(0); 14774 const unsigned DstSz = Op.getValueType().getSizeInBits(); 14775 const unsigned SrcSz = SrcVal.getValueType().getSizeInBits(); 14776 assert(DstSz > SrcSz && DstSz <= 64 && SrcSz >= 16 && 14777 "Unexpected type for custom-lowering FP_EXTEND"); 14778 14779 assert((!Subtarget->hasFP64() || !Subtarget->hasFPARMv8Base()) && 14780 "With both FP DP and 16, any FP conversion is legal!"); 14781 14782 assert(!(DstSz == 32 && Subtarget->hasFP16()) && 14783 "With FP16, 16 to 32 conversion is legal!"); 14784 14785 // Either we are converting from 16 -> 64, without FP16 and/or 14786 // FP.double-precision or without Armv8-fp. So we must do it in two 14787 // steps. 14788 // Or we are converting from 32 -> 64 without fp.double-precision or 16 -> 32 14789 // without FP16. So we must do a function call. 14790 SDLoc Loc(Op); 14791 RTLIB::Libcall LC; 14792 if (SrcSz == 16) { 14793 // Instruction from 16 -> 32 14794 if (Subtarget->hasFP16()) 14795 SrcVal = DAG.getNode(ISD::FP_EXTEND, Loc, MVT::f32, SrcVal); 14796 // Lib call from 16 -> 32 14797 else { 14798 LC = RTLIB::getFPEXT(MVT::f16, MVT::f32); 14799 assert(LC != RTLIB::UNKNOWN_LIBCALL && 14800 "Unexpected type for custom-lowering FP_EXTEND"); 14801 SrcVal = 14802 makeLibCall(DAG, LC, MVT::f32, SrcVal, /*isSigned*/ false, Loc).first; 14803 } 14804 } 14805 14806 if (DstSz != 64) 14807 return SrcVal; 14808 // For sure now SrcVal is 32 bits 14809 if (Subtarget->hasFP64()) // Instruction from 32 -> 64 14810 return DAG.getNode(ISD::FP_EXTEND, Loc, MVT::f64, SrcVal); 14811 14812 LC = RTLIB::getFPEXT(MVT::f32, MVT::f64); 14813 assert(LC != RTLIB::UNKNOWN_LIBCALL && 14814 "Unexpected type for custom-lowering FP_EXTEND"); 14815 return makeLibCall(DAG, LC, MVT::f64, SrcVal, /*isSigned*/ false, Loc).first; 14816 } 14817 14818 SDValue ARMTargetLowering::LowerFP_ROUND(SDValue Op, SelectionDAG &DAG) const { 14819 SDValue SrcVal = Op.getOperand(0); 14820 EVT SrcVT = SrcVal.getValueType(); 14821 EVT DstVT = Op.getValueType(); 14822 const unsigned DstSz = Op.getValueType().getSizeInBits(); 14823 const unsigned SrcSz = SrcVT.getSizeInBits(); 14824 (void)DstSz; 14825 assert(DstSz < SrcSz && SrcSz <= 64 && DstSz >= 16 && 14826 "Unexpected type for custom-lowering FP_ROUND"); 14827 14828 assert((!Subtarget->hasFP64() || !Subtarget->hasFPARMv8Base()) && 14829 "With both FP DP and 16, any FP conversion is legal!"); 14830 14831 SDLoc Loc(Op); 14832 14833 // Instruction from 32 -> 16 if hasFP16 is valid 14834 if (SrcSz == 32 && Subtarget->hasFP16()) 14835 return Op; 14836 14837 // Lib call from 32 -> 16 / 64 -> [32, 16] 14838 RTLIB::Libcall LC = RTLIB::getFPROUND(SrcVT, DstVT); 14839 assert(LC != RTLIB::UNKNOWN_LIBCALL && 14840 "Unexpected type for custom-lowering FP_ROUND"); 14841 return makeLibCall(DAG, LC, DstVT, SrcVal, /*isSigned*/ false, Loc).first; 14842 } 14843 14844 void ARMTargetLowering::lowerABS(SDNode *N, SmallVectorImpl<SDValue> &Results, 14845 SelectionDAG &DAG) const { 14846 assert(N->getValueType(0) == MVT::i64 && "Unexpected type (!= i64) on ABS."); 14847 MVT HalfT = MVT::i32; 14848 SDLoc dl(N); 14849 SDValue Hi, Lo, Tmp; 14850 14851 if (!isOperationLegalOrCustom(ISD::ADDCARRY, HalfT) || 14852 !isOperationLegalOrCustom(ISD::UADDO, HalfT)) 14853 return ; 14854 14855 unsigned OpTypeBits = HalfT.getScalarSizeInBits(); 14856 SDVTList VTList = DAG.getVTList(HalfT, MVT::i1); 14857 14858 Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(0), 14859 DAG.getConstant(0, dl, HalfT)); 14860 Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(0), 14861 DAG.getConstant(1, dl, HalfT)); 14862 14863 Tmp = DAG.getNode(ISD::SRA, dl, HalfT, Hi, 14864 DAG.getConstant(OpTypeBits - 1, dl, 14865 getShiftAmountTy(HalfT, DAG.getDataLayout()))); 14866 Lo = DAG.getNode(ISD::UADDO, dl, VTList, Tmp, Lo); 14867 Hi = DAG.getNode(ISD::ADDCARRY, dl, VTList, Tmp, Hi, 14868 SDValue(Lo.getNode(), 1)); 14869 Hi = DAG.getNode(ISD::XOR, dl, HalfT, Tmp, Hi); 14870 Lo = DAG.getNode(ISD::XOR, dl, HalfT, Tmp, Lo); 14871 14872 Results.push_back(Lo); 14873 Results.push_back(Hi); 14874 } 14875 14876 bool 14877 ARMTargetLowering::isOffsetFoldingLegal(const GlobalAddressSDNode *GA) const { 14878 // The ARM target isn't yet aware of offsets. 14879 return false; 14880 } 14881 14882 bool ARM::isBitFieldInvertedMask(unsigned v) { 14883 if (v == 0xffffffff) 14884 return false; 14885 14886 // there can be 1's on either or both "outsides", all the "inside" 14887 // bits must be 0's 14888 return isShiftedMask_32(~v); 14889 } 14890 14891 /// isFPImmLegal - Returns true if the target can instruction select the 14892 /// specified FP immediate natively. If false, the legalizer will 14893 /// materialize the FP immediate as a load from a constant pool. 14894 bool ARMTargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT, 14895 bool ForCodeSize) const { 14896 if (!Subtarget->hasVFP3Base()) 14897 return false; 14898 if (VT == MVT::f16 && Subtarget->hasFullFP16()) 14899 return ARM_AM::getFP16Imm(Imm) != -1; 14900 if (VT == MVT::f32) 14901 return ARM_AM::getFP32Imm(Imm) != -1; 14902 if (VT == MVT::f64 && Subtarget->hasFP64()) 14903 return ARM_AM::getFP64Imm(Imm) != -1; 14904 return false; 14905 } 14906 14907 /// getTgtMemIntrinsic - Represent NEON load and store intrinsics as 14908 /// MemIntrinsicNodes. The associated MachineMemOperands record the alignment 14909 /// specified in the intrinsic calls. 14910 bool ARMTargetLowering::getTgtMemIntrinsic(IntrinsicInfo &Info, 14911 const CallInst &I, 14912 MachineFunction &MF, 14913 unsigned Intrinsic) const { 14914 switch (Intrinsic) { 14915 case Intrinsic::arm_neon_vld1: 14916 case Intrinsic::arm_neon_vld2: 14917 case Intrinsic::arm_neon_vld3: 14918 case Intrinsic::arm_neon_vld4: 14919 case Intrinsic::arm_neon_vld2lane: 14920 case Intrinsic::arm_neon_vld3lane: 14921 case Intrinsic::arm_neon_vld4lane: 14922 case Intrinsic::arm_neon_vld2dup: 14923 case Intrinsic::arm_neon_vld3dup: 14924 case Intrinsic::arm_neon_vld4dup: { 14925 Info.opc = ISD::INTRINSIC_W_CHAIN; 14926 // Conservatively set memVT to the entire set of vectors loaded. 14927 auto &DL = I.getCalledFunction()->getParent()->getDataLayout(); 14928 uint64_t NumElts = DL.getTypeSizeInBits(I.getType()) / 64; 14929 Info.memVT = EVT::getVectorVT(I.getType()->getContext(), MVT::i64, NumElts); 14930 Info.ptrVal = I.getArgOperand(0); 14931 Info.offset = 0; 14932 Value *AlignArg = I.getArgOperand(I.getNumArgOperands() - 1); 14933 Info.align = cast<ConstantInt>(AlignArg)->getZExtValue(); 14934 // volatile loads with NEON intrinsics not supported 14935 Info.flags = MachineMemOperand::MOLoad; 14936 return true; 14937 } 14938 case Intrinsic::arm_neon_vld1x2: 14939 case Intrinsic::arm_neon_vld1x3: 14940 case Intrinsic::arm_neon_vld1x4: { 14941 Info.opc = ISD::INTRINSIC_W_CHAIN; 14942 // Conservatively set memVT to the entire set of vectors loaded. 14943 auto &DL = I.getCalledFunction()->getParent()->getDataLayout(); 14944 uint64_t NumElts = DL.getTypeSizeInBits(I.getType()) / 64; 14945 Info.memVT = EVT::getVectorVT(I.getType()->getContext(), MVT::i64, NumElts); 14946 Info.ptrVal = I.getArgOperand(I.getNumArgOperands() - 1); 14947 Info.offset = 0; 14948 Info.align = 0; 14949 // volatile loads with NEON intrinsics not supported 14950 Info.flags = MachineMemOperand::MOLoad; 14951 return true; 14952 } 14953 case Intrinsic::arm_neon_vst1: 14954 case Intrinsic::arm_neon_vst2: 14955 case Intrinsic::arm_neon_vst3: 14956 case Intrinsic::arm_neon_vst4: 14957 case Intrinsic::arm_neon_vst2lane: 14958 case Intrinsic::arm_neon_vst3lane: 14959 case Intrinsic::arm_neon_vst4lane: { 14960 Info.opc = ISD::INTRINSIC_VOID; 14961 // Conservatively set memVT to the entire set of vectors stored. 14962 auto &DL = I.getCalledFunction()->getParent()->getDataLayout(); 14963 unsigned NumElts = 0; 14964 for (unsigned ArgI = 1, ArgE = I.getNumArgOperands(); ArgI < ArgE; ++ArgI) { 14965 Type *ArgTy = I.getArgOperand(ArgI)->getType(); 14966 if (!ArgTy->isVectorTy()) 14967 break; 14968 NumElts += DL.getTypeSizeInBits(ArgTy) / 64; 14969 } 14970 Info.memVT = EVT::getVectorVT(I.getType()->getContext(), MVT::i64, NumElts); 14971 Info.ptrVal = I.getArgOperand(0); 14972 Info.offset = 0; 14973 Value *AlignArg = I.getArgOperand(I.getNumArgOperands() - 1); 14974 Info.align = cast<ConstantInt>(AlignArg)->getZExtValue(); 14975 // volatile stores with NEON intrinsics not supported 14976 Info.flags = MachineMemOperand::MOStore; 14977 return true; 14978 } 14979 case Intrinsic::arm_neon_vst1x2: 14980 case Intrinsic::arm_neon_vst1x3: 14981 case Intrinsic::arm_neon_vst1x4: { 14982 Info.opc = ISD::INTRINSIC_VOID; 14983 // Conservatively set memVT to the entire set of vectors stored. 14984 auto &DL = I.getCalledFunction()->getParent()->getDataLayout(); 14985 unsigned NumElts = 0; 14986 for (unsigned ArgI = 1, ArgE = I.getNumArgOperands(); ArgI < ArgE; ++ArgI) { 14987 Type *ArgTy = I.getArgOperand(ArgI)->getType(); 14988 if (!ArgTy->isVectorTy()) 14989 break; 14990 NumElts += DL.getTypeSizeInBits(ArgTy) / 64; 14991 } 14992 Info.memVT = EVT::getVectorVT(I.getType()->getContext(), MVT::i64, NumElts); 14993 Info.ptrVal = I.getArgOperand(0); 14994 Info.offset = 0; 14995 Info.align = 0; 14996 // volatile stores with NEON intrinsics not supported 14997 Info.flags = MachineMemOperand::MOStore; 14998 return true; 14999 } 15000 case Intrinsic::arm_ldaex: 15001 case Intrinsic::arm_ldrex: { 15002 auto &DL = I.getCalledFunction()->getParent()->getDataLayout(); 15003 PointerType *PtrTy = cast<PointerType>(I.getArgOperand(0)->getType()); 15004 Info.opc = ISD::INTRINSIC_W_CHAIN; 15005 Info.memVT = MVT::getVT(PtrTy->getElementType()); 15006 Info.ptrVal = I.getArgOperand(0); 15007 Info.offset = 0; 15008 Info.align = DL.getABITypeAlignment(PtrTy->getElementType()); 15009 Info.flags = MachineMemOperand::MOLoad | MachineMemOperand::MOVolatile; 15010 return true; 15011 } 15012 case Intrinsic::arm_stlex: 15013 case Intrinsic::arm_strex: { 15014 auto &DL = I.getCalledFunction()->getParent()->getDataLayout(); 15015 PointerType *PtrTy = cast<PointerType>(I.getArgOperand(1)->getType()); 15016 Info.opc = ISD::INTRINSIC_W_CHAIN; 15017 Info.memVT = MVT::getVT(PtrTy->getElementType()); 15018 Info.ptrVal = I.getArgOperand(1); 15019 Info.offset = 0; 15020 Info.align = DL.getABITypeAlignment(PtrTy->getElementType()); 15021 Info.flags = MachineMemOperand::MOStore | MachineMemOperand::MOVolatile; 15022 return true; 15023 } 15024 case Intrinsic::arm_stlexd: 15025 case Intrinsic::arm_strexd: 15026 Info.opc = ISD::INTRINSIC_W_CHAIN; 15027 Info.memVT = MVT::i64; 15028 Info.ptrVal = I.getArgOperand(2); 15029 Info.offset = 0; 15030 Info.align = 8; 15031 Info.flags = MachineMemOperand::MOStore | MachineMemOperand::MOVolatile; 15032 return true; 15033 15034 case Intrinsic::arm_ldaexd: 15035 case Intrinsic::arm_ldrexd: 15036 Info.opc = ISD::INTRINSIC_W_CHAIN; 15037 Info.memVT = MVT::i64; 15038 Info.ptrVal = I.getArgOperand(0); 15039 Info.offset = 0; 15040 Info.align = 8; 15041 Info.flags = MachineMemOperand::MOLoad | MachineMemOperand::MOVolatile; 15042 return true; 15043 15044 default: 15045 break; 15046 } 15047 15048 return false; 15049 } 15050 15051 /// Returns true if it is beneficial to convert a load of a constant 15052 /// to just the constant itself. 15053 bool ARMTargetLowering::shouldConvertConstantLoadToIntImm(const APInt &Imm, 15054 Type *Ty) const { 15055 assert(Ty->isIntegerTy()); 15056 15057 unsigned Bits = Ty->getPrimitiveSizeInBits(); 15058 if (Bits == 0 || Bits > 32) 15059 return false; 15060 return true; 15061 } 15062 15063 bool ARMTargetLowering::isExtractSubvectorCheap(EVT ResVT, EVT SrcVT, 15064 unsigned Index) const { 15065 if (!isOperationLegalOrCustom(ISD::EXTRACT_SUBVECTOR, ResVT)) 15066 return false; 15067 15068 return (Index == 0 || Index == ResVT.getVectorNumElements()); 15069 } 15070 15071 Instruction* ARMTargetLowering::makeDMB(IRBuilder<> &Builder, 15072 ARM_MB::MemBOpt Domain) const { 15073 Module *M = Builder.GetInsertBlock()->getParent()->getParent(); 15074 15075 // First, if the target has no DMB, see what fallback we can use. 15076 if (!Subtarget->hasDataBarrier()) { 15077 // Some ARMv6 cpus can support data barriers with an mcr instruction. 15078 // Thumb1 and pre-v6 ARM mode use a libcall instead and should never get 15079 // here. 15080 if (Subtarget->hasV6Ops() && !Subtarget->isThumb()) { 15081 Function *MCR = Intrinsic::getDeclaration(M, Intrinsic::arm_mcr); 15082 Value* args[6] = {Builder.getInt32(15), Builder.getInt32(0), 15083 Builder.getInt32(0), Builder.getInt32(7), 15084 Builder.getInt32(10), Builder.getInt32(5)}; 15085 return Builder.CreateCall(MCR, args); 15086 } else { 15087 // Instead of using barriers, atomic accesses on these subtargets use 15088 // libcalls. 15089 llvm_unreachable("makeDMB on a target so old that it has no barriers"); 15090 } 15091 } else { 15092 Function *DMB = Intrinsic::getDeclaration(M, Intrinsic::arm_dmb); 15093 // Only a full system barrier exists in the M-class architectures. 15094 Domain = Subtarget->isMClass() ? ARM_MB::SY : Domain; 15095 Constant *CDomain = Builder.getInt32(Domain); 15096 return Builder.CreateCall(DMB, CDomain); 15097 } 15098 } 15099 15100 // Based on http://www.cl.cam.ac.uk/~pes20/cpp/cpp0xmappings.html 15101 Instruction *ARMTargetLowering::emitLeadingFence(IRBuilder<> &Builder, 15102 Instruction *Inst, 15103 AtomicOrdering Ord) const { 15104 switch (Ord) { 15105 case AtomicOrdering::NotAtomic: 15106 case AtomicOrdering::Unordered: 15107 llvm_unreachable("Invalid fence: unordered/non-atomic"); 15108 case AtomicOrdering::Monotonic: 15109 case AtomicOrdering::Acquire: 15110 return nullptr; // Nothing to do 15111 case AtomicOrdering::SequentiallyConsistent: 15112 if (!Inst->hasAtomicStore()) 15113 return nullptr; // Nothing to do 15114 LLVM_FALLTHROUGH; 15115 case AtomicOrdering::Release: 15116 case AtomicOrdering::AcquireRelease: 15117 if (Subtarget->preferISHSTBarriers()) 15118 return makeDMB(Builder, ARM_MB::ISHST); 15119 // FIXME: add a comment with a link to documentation justifying this. 15120 else 15121 return makeDMB(Builder, ARM_MB::ISH); 15122 } 15123 llvm_unreachable("Unknown fence ordering in emitLeadingFence"); 15124 } 15125 15126 Instruction *ARMTargetLowering::emitTrailingFence(IRBuilder<> &Builder, 15127 Instruction *Inst, 15128 AtomicOrdering Ord) const { 15129 switch (Ord) { 15130 case AtomicOrdering::NotAtomic: 15131 case AtomicOrdering::Unordered: 15132 llvm_unreachable("Invalid fence: unordered/not-atomic"); 15133 case AtomicOrdering::Monotonic: 15134 case AtomicOrdering::Release: 15135 return nullptr; // Nothing to do 15136 case AtomicOrdering::Acquire: 15137 case AtomicOrdering::AcquireRelease: 15138 case AtomicOrdering::SequentiallyConsistent: 15139 return makeDMB(Builder, ARM_MB::ISH); 15140 } 15141 llvm_unreachable("Unknown fence ordering in emitTrailingFence"); 15142 } 15143 15144 // Loads and stores less than 64-bits are already atomic; ones above that 15145 // are doomed anyway, so defer to the default libcall and blame the OS when 15146 // things go wrong. Cortex M doesn't have ldrexd/strexd though, so don't emit 15147 // anything for those. 15148 bool ARMTargetLowering::shouldExpandAtomicStoreInIR(StoreInst *SI) const { 15149 unsigned Size = SI->getValueOperand()->getType()->getPrimitiveSizeInBits(); 15150 return (Size == 64) && !Subtarget->isMClass(); 15151 } 15152 15153 // Loads and stores less than 64-bits are already atomic; ones above that 15154 // are doomed anyway, so defer to the default libcall and blame the OS when 15155 // things go wrong. Cortex M doesn't have ldrexd/strexd though, so don't emit 15156 // anything for those. 15157 // FIXME: ldrd and strd are atomic if the CPU has LPAE (e.g. A15 has that 15158 // guarantee, see DDI0406C ARM architecture reference manual, 15159 // sections A8.8.72-74 LDRD) 15160 TargetLowering::AtomicExpansionKind 15161 ARMTargetLowering::shouldExpandAtomicLoadInIR(LoadInst *LI) const { 15162 unsigned Size = LI->getType()->getPrimitiveSizeInBits(); 15163 return ((Size == 64) && !Subtarget->isMClass()) ? AtomicExpansionKind::LLOnly 15164 : AtomicExpansionKind::None; 15165 } 15166 15167 // For the real atomic operations, we have ldrex/strex up to 32 bits, 15168 // and up to 64 bits on the non-M profiles 15169 TargetLowering::AtomicExpansionKind 15170 ARMTargetLowering::shouldExpandAtomicRMWInIR(AtomicRMWInst *AI) const { 15171 if (AI->isFloatingPointOperation()) 15172 return AtomicExpansionKind::CmpXChg; 15173 15174 unsigned Size = AI->getType()->getPrimitiveSizeInBits(); 15175 bool hasAtomicRMW = !Subtarget->isThumb() || Subtarget->hasV8MBaselineOps(); 15176 return (Size <= (Subtarget->isMClass() ? 32U : 64U) && hasAtomicRMW) 15177 ? AtomicExpansionKind::LLSC 15178 : AtomicExpansionKind::None; 15179 } 15180 15181 TargetLowering::AtomicExpansionKind 15182 ARMTargetLowering::shouldExpandAtomicCmpXchgInIR(AtomicCmpXchgInst *AI) const { 15183 // At -O0, fast-regalloc cannot cope with the live vregs necessary to 15184 // implement cmpxchg without spilling. If the address being exchanged is also 15185 // on the stack and close enough to the spill slot, this can lead to a 15186 // situation where the monitor always gets cleared and the atomic operation 15187 // can never succeed. So at -O0 we need a late-expanded pseudo-inst instead. 15188 bool HasAtomicCmpXchg = 15189 !Subtarget->isThumb() || Subtarget->hasV8MBaselineOps(); 15190 if (getTargetMachine().getOptLevel() != 0 && HasAtomicCmpXchg) 15191 return AtomicExpansionKind::LLSC; 15192 return AtomicExpansionKind::None; 15193 } 15194 15195 bool ARMTargetLowering::shouldInsertFencesForAtomic( 15196 const Instruction *I) const { 15197 return InsertFencesForAtomic; 15198 } 15199 15200 // This has so far only been implemented for MachO. 15201 bool ARMTargetLowering::useLoadStackGuardNode() const { 15202 return Subtarget->isTargetMachO(); 15203 } 15204 15205 bool ARMTargetLowering::canCombineStoreAndExtract(Type *VectorTy, Value *Idx, 15206 unsigned &Cost) const { 15207 // If we do not have NEON, vector types are not natively supported. 15208 if (!Subtarget->hasNEON()) 15209 return false; 15210 15211 // Floating point values and vector values map to the same register file. 15212 // Therefore, although we could do a store extract of a vector type, this is 15213 // better to leave at float as we have more freedom in the addressing mode for 15214 // those. 15215 if (VectorTy->isFPOrFPVectorTy()) 15216 return false; 15217 15218 // If the index is unknown at compile time, this is very expensive to lower 15219 // and it is not possible to combine the store with the extract. 15220 if (!isa<ConstantInt>(Idx)) 15221 return false; 15222 15223 assert(VectorTy->isVectorTy() && "VectorTy is not a vector type"); 15224 unsigned BitWidth = cast<VectorType>(VectorTy)->getBitWidth(); 15225 // We can do a store + vector extract on any vector that fits perfectly in a D 15226 // or Q register. 15227 if (BitWidth == 64 || BitWidth == 128) { 15228 Cost = 0; 15229 return true; 15230 } 15231 return false; 15232 } 15233 15234 bool ARMTargetLowering::isCheapToSpeculateCttz() const { 15235 return Subtarget->hasV6T2Ops(); 15236 } 15237 15238 bool ARMTargetLowering::isCheapToSpeculateCtlz() const { 15239 return Subtarget->hasV6T2Ops(); 15240 } 15241 15242 bool ARMTargetLowering::shouldExpandShift(SelectionDAG &DAG, SDNode *N) const { 15243 return !Subtarget->hasMinSize(); 15244 } 15245 15246 Value *ARMTargetLowering::emitLoadLinked(IRBuilder<> &Builder, Value *Addr, 15247 AtomicOrdering Ord) const { 15248 Module *M = Builder.GetInsertBlock()->getParent()->getParent(); 15249 Type *ValTy = cast<PointerType>(Addr->getType())->getElementType(); 15250 bool IsAcquire = isAcquireOrStronger(Ord); 15251 15252 // Since i64 isn't legal and intrinsics don't get type-lowered, the ldrexd 15253 // intrinsic must return {i32, i32} and we have to recombine them into a 15254 // single i64 here. 15255 if (ValTy->getPrimitiveSizeInBits() == 64) { 15256 Intrinsic::ID Int = 15257 IsAcquire ? Intrinsic::arm_ldaexd : Intrinsic::arm_ldrexd; 15258 Function *Ldrex = Intrinsic::getDeclaration(M, Int); 15259 15260 Addr = Builder.CreateBitCast(Addr, Type::getInt8PtrTy(M->getContext())); 15261 Value *LoHi = Builder.CreateCall(Ldrex, Addr, "lohi"); 15262 15263 Value *Lo = Builder.CreateExtractValue(LoHi, 0, "lo"); 15264 Value *Hi = Builder.CreateExtractValue(LoHi, 1, "hi"); 15265 if (!Subtarget->isLittle()) 15266 std::swap (Lo, Hi); 15267 Lo = Builder.CreateZExt(Lo, ValTy, "lo64"); 15268 Hi = Builder.CreateZExt(Hi, ValTy, "hi64"); 15269 return Builder.CreateOr( 15270 Lo, Builder.CreateShl(Hi, ConstantInt::get(ValTy, 32)), "val64"); 15271 } 15272 15273 Type *Tys[] = { Addr->getType() }; 15274 Intrinsic::ID Int = IsAcquire ? Intrinsic::arm_ldaex : Intrinsic::arm_ldrex; 15275 Function *Ldrex = Intrinsic::getDeclaration(M, Int, Tys); 15276 15277 return Builder.CreateTruncOrBitCast( 15278 Builder.CreateCall(Ldrex, Addr), 15279 cast<PointerType>(Addr->getType())->getElementType()); 15280 } 15281 15282 void ARMTargetLowering::emitAtomicCmpXchgNoStoreLLBalance( 15283 IRBuilder<> &Builder) const { 15284 if (!Subtarget->hasV7Ops()) 15285 return; 15286 Module *M = Builder.GetInsertBlock()->getParent()->getParent(); 15287 Builder.CreateCall(Intrinsic::getDeclaration(M, Intrinsic::arm_clrex)); 15288 } 15289 15290 Value *ARMTargetLowering::emitStoreConditional(IRBuilder<> &Builder, Value *Val, 15291 Value *Addr, 15292 AtomicOrdering Ord) const { 15293 Module *M = Builder.GetInsertBlock()->getParent()->getParent(); 15294 bool IsRelease = isReleaseOrStronger(Ord); 15295 15296 // Since the intrinsics must have legal type, the i64 intrinsics take two 15297 // parameters: "i32, i32". We must marshal Val into the appropriate form 15298 // before the call. 15299 if (Val->getType()->getPrimitiveSizeInBits() == 64) { 15300 Intrinsic::ID Int = 15301 IsRelease ? Intrinsic::arm_stlexd : Intrinsic::arm_strexd; 15302 Function *Strex = Intrinsic::getDeclaration(M, Int); 15303 Type *Int32Ty = Type::getInt32Ty(M->getContext()); 15304 15305 Value *Lo = Builder.CreateTrunc(Val, Int32Ty, "lo"); 15306 Value *Hi = Builder.CreateTrunc(Builder.CreateLShr(Val, 32), Int32Ty, "hi"); 15307 if (!Subtarget->isLittle()) 15308 std::swap(Lo, Hi); 15309 Addr = Builder.CreateBitCast(Addr, Type::getInt8PtrTy(M->getContext())); 15310 return Builder.CreateCall(Strex, {Lo, Hi, Addr}); 15311 } 15312 15313 Intrinsic::ID Int = IsRelease ? Intrinsic::arm_stlex : Intrinsic::arm_strex; 15314 Type *Tys[] = { Addr->getType() }; 15315 Function *Strex = Intrinsic::getDeclaration(M, Int, Tys); 15316 15317 return Builder.CreateCall( 15318 Strex, {Builder.CreateZExtOrBitCast( 15319 Val, Strex->getFunctionType()->getParamType(0)), 15320 Addr}); 15321 } 15322 15323 15324 bool ARMTargetLowering::alignLoopsWithOptSize() const { 15325 return Subtarget->isMClass(); 15326 } 15327 15328 /// A helper function for determining the number of interleaved accesses we 15329 /// will generate when lowering accesses of the given type. 15330 unsigned 15331 ARMTargetLowering::getNumInterleavedAccesses(VectorType *VecTy, 15332 const DataLayout &DL) const { 15333 return (DL.getTypeSizeInBits(VecTy) + 127) / 128; 15334 } 15335 15336 bool ARMTargetLowering::isLegalInterleavedAccessType( 15337 VectorType *VecTy, const DataLayout &DL) const { 15338 15339 unsigned VecSize = DL.getTypeSizeInBits(VecTy); 15340 unsigned ElSize = DL.getTypeSizeInBits(VecTy->getElementType()); 15341 15342 // Ensure the vector doesn't have f16 elements. Even though we could do an 15343 // i16 vldN, we can't hold the f16 vectors and will end up converting via 15344 // f32. 15345 if (VecTy->getElementType()->isHalfTy()) 15346 return false; 15347 15348 // Ensure the number of vector elements is greater than 1. 15349 if (VecTy->getNumElements() < 2) 15350 return false; 15351 15352 // Ensure the element type is legal. 15353 if (ElSize != 8 && ElSize != 16 && ElSize != 32) 15354 return false; 15355 15356 // Ensure the total vector size is 64 or a multiple of 128. Types larger than 15357 // 128 will be split into multiple interleaved accesses. 15358 return VecSize == 64 || VecSize % 128 == 0; 15359 } 15360 15361 /// Lower an interleaved load into a vldN intrinsic. 15362 /// 15363 /// E.g. Lower an interleaved load (Factor = 2): 15364 /// %wide.vec = load <8 x i32>, <8 x i32>* %ptr, align 4 15365 /// %v0 = shuffle %wide.vec, undef, <0, 2, 4, 6> ; Extract even elements 15366 /// %v1 = shuffle %wide.vec, undef, <1, 3, 5, 7> ; Extract odd elements 15367 /// 15368 /// Into: 15369 /// %vld2 = { <4 x i32>, <4 x i32> } call llvm.arm.neon.vld2(%ptr, 4) 15370 /// %vec0 = extractelement { <4 x i32>, <4 x i32> } %vld2, i32 0 15371 /// %vec1 = extractelement { <4 x i32>, <4 x i32> } %vld2, i32 1 15372 bool ARMTargetLowering::lowerInterleavedLoad( 15373 LoadInst *LI, ArrayRef<ShuffleVectorInst *> Shuffles, 15374 ArrayRef<unsigned> Indices, unsigned Factor) const { 15375 assert(Factor >= 2 && Factor <= getMaxSupportedInterleaveFactor() && 15376 "Invalid interleave factor"); 15377 assert(!Shuffles.empty() && "Empty shufflevector input"); 15378 assert(Shuffles.size() == Indices.size() && 15379 "Unmatched number of shufflevectors and indices"); 15380 15381 VectorType *VecTy = Shuffles[0]->getType(); 15382 Type *EltTy = VecTy->getVectorElementType(); 15383 15384 const DataLayout &DL = LI->getModule()->getDataLayout(); 15385 15386 // Skip if we do not have NEON and skip illegal vector types. We can 15387 // "legalize" wide vector types into multiple interleaved accesses as long as 15388 // the vector types are divisible by 128. 15389 if (!Subtarget->hasNEON() || !isLegalInterleavedAccessType(VecTy, DL)) 15390 return false; 15391 15392 unsigned NumLoads = getNumInterleavedAccesses(VecTy, DL); 15393 15394 // A pointer vector can not be the return type of the ldN intrinsics. Need to 15395 // load integer vectors first and then convert to pointer vectors. 15396 if (EltTy->isPointerTy()) 15397 VecTy = 15398 VectorType::get(DL.getIntPtrType(EltTy), VecTy->getVectorNumElements()); 15399 15400 IRBuilder<> Builder(LI); 15401 15402 // The base address of the load. 15403 Value *BaseAddr = LI->getPointerOperand(); 15404 15405 if (NumLoads > 1) { 15406 // If we're going to generate more than one load, reset the sub-vector type 15407 // to something legal. 15408 VecTy = VectorType::get(VecTy->getVectorElementType(), 15409 VecTy->getVectorNumElements() / NumLoads); 15410 15411 // We will compute the pointer operand of each load from the original base 15412 // address using GEPs. Cast the base address to a pointer to the scalar 15413 // element type. 15414 BaseAddr = Builder.CreateBitCast( 15415 BaseAddr, VecTy->getVectorElementType()->getPointerTo( 15416 LI->getPointerAddressSpace())); 15417 } 15418 15419 assert(isTypeLegal(EVT::getEVT(VecTy)) && "Illegal vldN vector type!"); 15420 15421 Type *Int8Ptr = Builder.getInt8PtrTy(LI->getPointerAddressSpace()); 15422 Type *Tys[] = {VecTy, Int8Ptr}; 15423 static const Intrinsic::ID LoadInts[3] = {Intrinsic::arm_neon_vld2, 15424 Intrinsic::arm_neon_vld3, 15425 Intrinsic::arm_neon_vld4}; 15426 Function *VldnFunc = 15427 Intrinsic::getDeclaration(LI->getModule(), LoadInts[Factor - 2], Tys); 15428 15429 // Holds sub-vectors extracted from the load intrinsic return values. The 15430 // sub-vectors are associated with the shufflevector instructions they will 15431 // replace. 15432 DenseMap<ShuffleVectorInst *, SmallVector<Value *, 4>> SubVecs; 15433 15434 for (unsigned LoadCount = 0; LoadCount < NumLoads; ++LoadCount) { 15435 // If we're generating more than one load, compute the base address of 15436 // subsequent loads as an offset from the previous. 15437 if (LoadCount > 0) 15438 BaseAddr = 15439 Builder.CreateConstGEP1_32(VecTy->getVectorElementType(), BaseAddr, 15440 VecTy->getVectorNumElements() * Factor); 15441 15442 SmallVector<Value *, 2> Ops; 15443 Ops.push_back(Builder.CreateBitCast(BaseAddr, Int8Ptr)); 15444 Ops.push_back(Builder.getInt32(LI->getAlignment())); 15445 15446 CallInst *VldN = Builder.CreateCall(VldnFunc, Ops, "vldN"); 15447 15448 // Replace uses of each shufflevector with the corresponding vector loaded 15449 // by ldN. 15450 for (unsigned i = 0; i < Shuffles.size(); i++) { 15451 ShuffleVectorInst *SV = Shuffles[i]; 15452 unsigned Index = Indices[i]; 15453 15454 Value *SubVec = Builder.CreateExtractValue(VldN, Index); 15455 15456 // Convert the integer vector to pointer vector if the element is pointer. 15457 if (EltTy->isPointerTy()) 15458 SubVec = Builder.CreateIntToPtr( 15459 SubVec, VectorType::get(SV->getType()->getVectorElementType(), 15460 VecTy->getVectorNumElements())); 15461 15462 SubVecs[SV].push_back(SubVec); 15463 } 15464 } 15465 15466 // Replace uses of the shufflevector instructions with the sub-vectors 15467 // returned by the load intrinsic. If a shufflevector instruction is 15468 // associated with more than one sub-vector, those sub-vectors will be 15469 // concatenated into a single wide vector. 15470 for (ShuffleVectorInst *SVI : Shuffles) { 15471 auto &SubVec = SubVecs[SVI]; 15472 auto *WideVec = 15473 SubVec.size() > 1 ? concatenateVectors(Builder, SubVec) : SubVec[0]; 15474 SVI->replaceAllUsesWith(WideVec); 15475 } 15476 15477 return true; 15478 } 15479 15480 /// Lower an interleaved store into a vstN intrinsic. 15481 /// 15482 /// E.g. Lower an interleaved store (Factor = 3): 15483 /// %i.vec = shuffle <8 x i32> %v0, <8 x i32> %v1, 15484 /// <0, 4, 8, 1, 5, 9, 2, 6, 10, 3, 7, 11> 15485 /// store <12 x i32> %i.vec, <12 x i32>* %ptr, align 4 15486 /// 15487 /// Into: 15488 /// %sub.v0 = shuffle <8 x i32> %v0, <8 x i32> v1, <0, 1, 2, 3> 15489 /// %sub.v1 = shuffle <8 x i32> %v0, <8 x i32> v1, <4, 5, 6, 7> 15490 /// %sub.v2 = shuffle <8 x i32> %v0, <8 x i32> v1, <8, 9, 10, 11> 15491 /// call void llvm.arm.neon.vst3(%ptr, %sub.v0, %sub.v1, %sub.v2, 4) 15492 /// 15493 /// Note that the new shufflevectors will be removed and we'll only generate one 15494 /// vst3 instruction in CodeGen. 15495 /// 15496 /// Example for a more general valid mask (Factor 3). Lower: 15497 /// %i.vec = shuffle <32 x i32> %v0, <32 x i32> %v1, 15498 /// <4, 32, 16, 5, 33, 17, 6, 34, 18, 7, 35, 19> 15499 /// store <12 x i32> %i.vec, <12 x i32>* %ptr 15500 /// 15501 /// Into: 15502 /// %sub.v0 = shuffle <32 x i32> %v0, <32 x i32> v1, <4, 5, 6, 7> 15503 /// %sub.v1 = shuffle <32 x i32> %v0, <32 x i32> v1, <32, 33, 34, 35> 15504 /// %sub.v2 = shuffle <32 x i32> %v0, <32 x i32> v1, <16, 17, 18, 19> 15505 /// call void llvm.arm.neon.vst3(%ptr, %sub.v0, %sub.v1, %sub.v2, 4) 15506 bool ARMTargetLowering::lowerInterleavedStore(StoreInst *SI, 15507 ShuffleVectorInst *SVI, 15508 unsigned Factor) const { 15509 assert(Factor >= 2 && Factor <= getMaxSupportedInterleaveFactor() && 15510 "Invalid interleave factor"); 15511 15512 VectorType *VecTy = SVI->getType(); 15513 assert(VecTy->getVectorNumElements() % Factor == 0 && 15514 "Invalid interleaved store"); 15515 15516 unsigned LaneLen = VecTy->getVectorNumElements() / Factor; 15517 Type *EltTy = VecTy->getVectorElementType(); 15518 VectorType *SubVecTy = VectorType::get(EltTy, LaneLen); 15519 15520 const DataLayout &DL = SI->getModule()->getDataLayout(); 15521 15522 // Skip if we do not have NEON and skip illegal vector types. We can 15523 // "legalize" wide vector types into multiple interleaved accesses as long as 15524 // the vector types are divisible by 128. 15525 if (!Subtarget->hasNEON() || !isLegalInterleavedAccessType(SubVecTy, DL)) 15526 return false; 15527 15528 unsigned NumStores = getNumInterleavedAccesses(SubVecTy, DL); 15529 15530 Value *Op0 = SVI->getOperand(0); 15531 Value *Op1 = SVI->getOperand(1); 15532 IRBuilder<> Builder(SI); 15533 15534 // StN intrinsics don't support pointer vectors as arguments. Convert pointer 15535 // vectors to integer vectors. 15536 if (EltTy->isPointerTy()) { 15537 Type *IntTy = DL.getIntPtrType(EltTy); 15538 15539 // Convert to the corresponding integer vector. 15540 Type *IntVecTy = 15541 VectorType::get(IntTy, Op0->getType()->getVectorNumElements()); 15542 Op0 = Builder.CreatePtrToInt(Op0, IntVecTy); 15543 Op1 = Builder.CreatePtrToInt(Op1, IntVecTy); 15544 15545 SubVecTy = VectorType::get(IntTy, LaneLen); 15546 } 15547 15548 // The base address of the store. 15549 Value *BaseAddr = SI->getPointerOperand(); 15550 15551 if (NumStores > 1) { 15552 // If we're going to generate more than one store, reset the lane length 15553 // and sub-vector type to something legal. 15554 LaneLen /= NumStores; 15555 SubVecTy = VectorType::get(SubVecTy->getVectorElementType(), LaneLen); 15556 15557 // We will compute the pointer operand of each store from the original base 15558 // address using GEPs. Cast the base address to a pointer to the scalar 15559 // element type. 15560 BaseAddr = Builder.CreateBitCast( 15561 BaseAddr, SubVecTy->getVectorElementType()->getPointerTo( 15562 SI->getPointerAddressSpace())); 15563 } 15564 15565 assert(isTypeLegal(EVT::getEVT(SubVecTy)) && "Illegal vstN vector type!"); 15566 15567 auto Mask = SVI->getShuffleMask(); 15568 15569 Type *Int8Ptr = Builder.getInt8PtrTy(SI->getPointerAddressSpace()); 15570 Type *Tys[] = {Int8Ptr, SubVecTy}; 15571 static const Intrinsic::ID StoreInts[3] = {Intrinsic::arm_neon_vst2, 15572 Intrinsic::arm_neon_vst3, 15573 Intrinsic::arm_neon_vst4}; 15574 15575 for (unsigned StoreCount = 0; StoreCount < NumStores; ++StoreCount) { 15576 // If we generating more than one store, we compute the base address of 15577 // subsequent stores as an offset from the previous. 15578 if (StoreCount > 0) 15579 BaseAddr = Builder.CreateConstGEP1_32(SubVecTy->getVectorElementType(), 15580 BaseAddr, LaneLen * Factor); 15581 15582 SmallVector<Value *, 6> Ops; 15583 Ops.push_back(Builder.CreateBitCast(BaseAddr, Int8Ptr)); 15584 15585 Function *VstNFunc = 15586 Intrinsic::getDeclaration(SI->getModule(), StoreInts[Factor - 2], Tys); 15587 15588 // Split the shufflevector operands into sub vectors for the new vstN call. 15589 for (unsigned i = 0; i < Factor; i++) { 15590 unsigned IdxI = StoreCount * LaneLen * Factor + i; 15591 if (Mask[IdxI] >= 0) { 15592 Ops.push_back(Builder.CreateShuffleVector( 15593 Op0, Op1, createSequentialMask(Builder, Mask[IdxI], LaneLen, 0))); 15594 } else { 15595 unsigned StartMask = 0; 15596 for (unsigned j = 1; j < LaneLen; j++) { 15597 unsigned IdxJ = StoreCount * LaneLen * Factor + j; 15598 if (Mask[IdxJ * Factor + IdxI] >= 0) { 15599 StartMask = Mask[IdxJ * Factor + IdxI] - IdxJ; 15600 break; 15601 } 15602 } 15603 // Note: If all elements in a chunk are undefs, StartMask=0! 15604 // Note: Filling undef gaps with random elements is ok, since 15605 // those elements were being written anyway (with undefs). 15606 // In the case of all undefs we're defaulting to using elems from 0 15607 // Note: StartMask cannot be negative, it's checked in 15608 // isReInterleaveMask 15609 Ops.push_back(Builder.CreateShuffleVector( 15610 Op0, Op1, createSequentialMask(Builder, StartMask, LaneLen, 0))); 15611 } 15612 } 15613 15614 Ops.push_back(Builder.getInt32(SI->getAlignment())); 15615 Builder.CreateCall(VstNFunc, Ops); 15616 } 15617 return true; 15618 } 15619 15620 enum HABaseType { 15621 HA_UNKNOWN = 0, 15622 HA_FLOAT, 15623 HA_DOUBLE, 15624 HA_VECT64, 15625 HA_VECT128 15626 }; 15627 15628 static bool isHomogeneousAggregate(Type *Ty, HABaseType &Base, 15629 uint64_t &Members) { 15630 if (auto *ST = dyn_cast<StructType>(Ty)) { 15631 for (unsigned i = 0; i < ST->getNumElements(); ++i) { 15632 uint64_t SubMembers = 0; 15633 if (!isHomogeneousAggregate(ST->getElementType(i), Base, SubMembers)) 15634 return false; 15635 Members += SubMembers; 15636 } 15637 } else if (auto *AT = dyn_cast<ArrayType>(Ty)) { 15638 uint64_t SubMembers = 0; 15639 if (!isHomogeneousAggregate(AT->getElementType(), Base, SubMembers)) 15640 return false; 15641 Members += SubMembers * AT->getNumElements(); 15642 } else if (Ty->isFloatTy()) { 15643 if (Base != HA_UNKNOWN && Base != HA_FLOAT) 15644 return false; 15645 Members = 1; 15646 Base = HA_FLOAT; 15647 } else if (Ty->isDoubleTy()) { 15648 if (Base != HA_UNKNOWN && Base != HA_DOUBLE) 15649 return false; 15650 Members = 1; 15651 Base = HA_DOUBLE; 15652 } else if (auto *VT = dyn_cast<VectorType>(Ty)) { 15653 Members = 1; 15654 switch (Base) { 15655 case HA_FLOAT: 15656 case HA_DOUBLE: 15657 return false; 15658 case HA_VECT64: 15659 return VT->getBitWidth() == 64; 15660 case HA_VECT128: 15661 return VT->getBitWidth() == 128; 15662 case HA_UNKNOWN: 15663 switch (VT->getBitWidth()) { 15664 case 64: 15665 Base = HA_VECT64; 15666 return true; 15667 case 128: 15668 Base = HA_VECT128; 15669 return true; 15670 default: 15671 return false; 15672 } 15673 } 15674 } 15675 15676 return (Members > 0 && Members <= 4); 15677 } 15678 15679 /// Return the correct alignment for the current calling convention. 15680 unsigned 15681 ARMTargetLowering::getABIAlignmentForCallingConv(Type *ArgTy, 15682 DataLayout DL) const { 15683 if (!ArgTy->isVectorTy()) 15684 return DL.getABITypeAlignment(ArgTy); 15685 15686 // Avoid over-aligning vector parameters. It would require realigning the 15687 // stack and waste space for no real benefit. 15688 return std::min(DL.getABITypeAlignment(ArgTy), DL.getStackAlignment()); 15689 } 15690 15691 /// Return true if a type is an AAPCS-VFP homogeneous aggregate or one of 15692 /// [N x i32] or [N x i64]. This allows front-ends to skip emitting padding when 15693 /// passing according to AAPCS rules. 15694 bool ARMTargetLowering::functionArgumentNeedsConsecutiveRegisters( 15695 Type *Ty, CallingConv::ID CallConv, bool isVarArg) const { 15696 if (getEffectiveCallingConv(CallConv, isVarArg) != 15697 CallingConv::ARM_AAPCS_VFP) 15698 return false; 15699 15700 HABaseType Base = HA_UNKNOWN; 15701 uint64_t Members = 0; 15702 bool IsHA = isHomogeneousAggregate(Ty, Base, Members); 15703 LLVM_DEBUG(dbgs() << "isHA: " << IsHA << " "; Ty->dump()); 15704 15705 bool IsIntArray = Ty->isArrayTy() && Ty->getArrayElementType()->isIntegerTy(); 15706 return IsHA || IsIntArray; 15707 } 15708 15709 unsigned ARMTargetLowering::getExceptionPointerRegister( 15710 const Constant *PersonalityFn) const { 15711 // Platforms which do not use SjLj EH may return values in these registers 15712 // via the personality function. 15713 return Subtarget->useSjLjEH() ? ARM::NoRegister : ARM::R0; 15714 } 15715 15716 unsigned ARMTargetLowering::getExceptionSelectorRegister( 15717 const Constant *PersonalityFn) const { 15718 // Platforms which do not use SjLj EH may return values in these registers 15719 // via the personality function. 15720 return Subtarget->useSjLjEH() ? ARM::NoRegister : ARM::R1; 15721 } 15722 15723 void ARMTargetLowering::initializeSplitCSR(MachineBasicBlock *Entry) const { 15724 // Update IsSplitCSR in ARMFunctionInfo. 15725 ARMFunctionInfo *AFI = Entry->getParent()->getInfo<ARMFunctionInfo>(); 15726 AFI->setIsSplitCSR(true); 15727 } 15728 15729 void ARMTargetLowering::insertCopiesSplitCSR( 15730 MachineBasicBlock *Entry, 15731 const SmallVectorImpl<MachineBasicBlock *> &Exits) const { 15732 const ARMBaseRegisterInfo *TRI = Subtarget->getRegisterInfo(); 15733 const MCPhysReg *IStart = TRI->getCalleeSavedRegsViaCopy(Entry->getParent()); 15734 if (!IStart) 15735 return; 15736 15737 const TargetInstrInfo *TII = Subtarget->getInstrInfo(); 15738 MachineRegisterInfo *MRI = &Entry->getParent()->getRegInfo(); 15739 MachineBasicBlock::iterator MBBI = Entry->begin(); 15740 for (const MCPhysReg *I = IStart; *I; ++I) { 15741 const TargetRegisterClass *RC = nullptr; 15742 if (ARM::GPRRegClass.contains(*I)) 15743 RC = &ARM::GPRRegClass; 15744 else if (ARM::DPRRegClass.contains(*I)) 15745 RC = &ARM::DPRRegClass; 15746 else 15747 llvm_unreachable("Unexpected register class in CSRsViaCopy!"); 15748 15749 unsigned NewVR = MRI->createVirtualRegister(RC); 15750 // Create copy from CSR to a virtual register. 15751 // FIXME: this currently does not emit CFI pseudo-instructions, it works 15752 // fine for CXX_FAST_TLS since the C++-style TLS access functions should be 15753 // nounwind. If we want to generalize this later, we may need to emit 15754 // CFI pseudo-instructions. 15755 assert(Entry->getParent()->getFunction().hasFnAttribute( 15756 Attribute::NoUnwind) && 15757 "Function should be nounwind in insertCopiesSplitCSR!"); 15758 Entry->addLiveIn(*I); 15759 BuildMI(*Entry, MBBI, DebugLoc(), TII->get(TargetOpcode::COPY), NewVR) 15760 .addReg(*I); 15761 15762 // Insert the copy-back instructions right before the terminator. 15763 for (auto *Exit : Exits) 15764 BuildMI(*Exit, Exit->getFirstTerminator(), DebugLoc(), 15765 TII->get(TargetOpcode::COPY), *I) 15766 .addReg(NewVR); 15767 } 15768 } 15769 15770 void ARMTargetLowering::finalizeLowering(MachineFunction &MF) const { 15771 MF.getFrameInfo().computeMaxCallFrameSize(MF); 15772 TargetLoweringBase::finalizeLowering(MF); 15773 } 15774