1 //===-- AArch64ISelLowering.cpp - AArch64 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 implements the AArch64TargetLowering class. 10 // 11 //===----------------------------------------------------------------------===// 12 13 #include "AArch64ISelLowering.h" 14 #include "AArch64CallingConvention.h" 15 #include "AArch64ExpandImm.h" 16 #include "AArch64MachineFunctionInfo.h" 17 #include "AArch64PerfectShuffle.h" 18 #include "AArch64RegisterInfo.h" 19 #include "AArch64Subtarget.h" 20 #include "MCTargetDesc/AArch64AddressingModes.h" 21 #include "Utils/AArch64BaseInfo.h" 22 #include "llvm/ADT/APFloat.h" 23 #include "llvm/ADT/APInt.h" 24 #include "llvm/ADT/ArrayRef.h" 25 #include "llvm/ADT/STLExtras.h" 26 #include "llvm/ADT/SmallSet.h" 27 #include "llvm/ADT/SmallVector.h" 28 #include "llvm/ADT/Statistic.h" 29 #include "llvm/ADT/StringRef.h" 30 #include "llvm/ADT/Triple.h" 31 #include "llvm/ADT/Twine.h" 32 #include "llvm/Analysis/ObjCARCUtil.h" 33 #include "llvm/Analysis/VectorUtils.h" 34 #include "llvm/CodeGen/CallingConvLower.h" 35 #include "llvm/CodeGen/MachineBasicBlock.h" 36 #include "llvm/CodeGen/MachineFrameInfo.h" 37 #include "llvm/CodeGen/MachineFunction.h" 38 #include "llvm/CodeGen/MachineInstr.h" 39 #include "llvm/CodeGen/MachineInstrBuilder.h" 40 #include "llvm/CodeGen/MachineMemOperand.h" 41 #include "llvm/CodeGen/MachineRegisterInfo.h" 42 #include "llvm/CodeGen/RuntimeLibcalls.h" 43 #include "llvm/CodeGen/SelectionDAG.h" 44 #include "llvm/CodeGen/SelectionDAGNodes.h" 45 #include "llvm/CodeGen/TargetCallingConv.h" 46 #include "llvm/CodeGen/TargetInstrInfo.h" 47 #include "llvm/CodeGen/ValueTypes.h" 48 #include "llvm/IR/Attributes.h" 49 #include "llvm/IR/Constants.h" 50 #include "llvm/IR/DataLayout.h" 51 #include "llvm/IR/DebugLoc.h" 52 #include "llvm/IR/DerivedTypes.h" 53 #include "llvm/IR/Function.h" 54 #include "llvm/IR/GetElementPtrTypeIterator.h" 55 #include "llvm/IR/GlobalValue.h" 56 #include "llvm/IR/IRBuilder.h" 57 #include "llvm/IR/Instruction.h" 58 #include "llvm/IR/Instructions.h" 59 #include "llvm/IR/IntrinsicInst.h" 60 #include "llvm/IR/Intrinsics.h" 61 #include "llvm/IR/IntrinsicsAArch64.h" 62 #include "llvm/IR/Module.h" 63 #include "llvm/IR/OperandTraits.h" 64 #include "llvm/IR/PatternMatch.h" 65 #include "llvm/IR/Type.h" 66 #include "llvm/IR/Use.h" 67 #include "llvm/IR/Value.h" 68 #include "llvm/MC/MCRegisterInfo.h" 69 #include "llvm/Support/Casting.h" 70 #include "llvm/Support/CodeGen.h" 71 #include "llvm/Support/CommandLine.h" 72 #include "llvm/Support/Compiler.h" 73 #include "llvm/Support/Debug.h" 74 #include "llvm/Support/ErrorHandling.h" 75 #include "llvm/Support/KnownBits.h" 76 #include "llvm/Support/MachineValueType.h" 77 #include "llvm/Support/MathExtras.h" 78 #include "llvm/Support/raw_ostream.h" 79 #include "llvm/Target/TargetMachine.h" 80 #include "llvm/Target/TargetOptions.h" 81 #include <algorithm> 82 #include <bitset> 83 #include <cassert> 84 #include <cctype> 85 #include <cstdint> 86 #include <cstdlib> 87 #include <iterator> 88 #include <limits> 89 #include <tuple> 90 #include <utility> 91 #include <vector> 92 93 using namespace llvm; 94 using namespace llvm::PatternMatch; 95 96 #define DEBUG_TYPE "aarch64-lower" 97 98 STATISTIC(NumTailCalls, "Number of tail calls"); 99 STATISTIC(NumShiftInserts, "Number of vector shift inserts"); 100 STATISTIC(NumOptimizedImms, "Number of times immediates were optimized"); 101 102 // FIXME: The necessary dtprel relocations don't seem to be supported 103 // well in the GNU bfd and gold linkers at the moment. Therefore, by 104 // default, for now, fall back to GeneralDynamic code generation. 105 cl::opt<bool> EnableAArch64ELFLocalDynamicTLSGeneration( 106 "aarch64-elf-ldtls-generation", cl::Hidden, 107 cl::desc("Allow AArch64 Local Dynamic TLS code generation"), 108 cl::init(false)); 109 110 static cl::opt<bool> 111 EnableOptimizeLogicalImm("aarch64-enable-logical-imm", cl::Hidden, 112 cl::desc("Enable AArch64 logical imm instruction " 113 "optimization"), 114 cl::init(true)); 115 116 // Temporary option added for the purpose of testing functionality added 117 // to DAGCombiner.cpp in D92230. It is expected that this can be removed 118 // in future when both implementations will be based off MGATHER rather 119 // than the GLD1 nodes added for the SVE gather load intrinsics. 120 static cl::opt<bool> 121 EnableCombineMGatherIntrinsics("aarch64-enable-mgather-combine", cl::Hidden, 122 cl::desc("Combine extends of AArch64 masked " 123 "gather intrinsics"), 124 cl::init(true)); 125 126 /// Value type used for condition codes. 127 static const MVT MVT_CC = MVT::i32; 128 129 static inline EVT getPackedSVEVectorVT(EVT VT) { 130 switch (VT.getSimpleVT().SimpleTy) { 131 default: 132 llvm_unreachable("unexpected element type for vector"); 133 case MVT::i8: 134 return MVT::nxv16i8; 135 case MVT::i16: 136 return MVT::nxv8i16; 137 case MVT::i32: 138 return MVT::nxv4i32; 139 case MVT::i64: 140 return MVT::nxv2i64; 141 case MVT::f16: 142 return MVT::nxv8f16; 143 case MVT::f32: 144 return MVT::nxv4f32; 145 case MVT::f64: 146 return MVT::nxv2f64; 147 case MVT::bf16: 148 return MVT::nxv8bf16; 149 } 150 } 151 152 // NOTE: Currently there's only a need to return integer vector types. If this 153 // changes then just add an extra "type" parameter. 154 static inline EVT getPackedSVEVectorVT(ElementCount EC) { 155 switch (EC.getKnownMinValue()) { 156 default: 157 llvm_unreachable("unexpected element count for vector"); 158 case 16: 159 return MVT::nxv16i8; 160 case 8: 161 return MVT::nxv8i16; 162 case 4: 163 return MVT::nxv4i32; 164 case 2: 165 return MVT::nxv2i64; 166 } 167 } 168 169 static inline EVT getPromotedVTForPredicate(EVT VT) { 170 assert(VT.isScalableVector() && (VT.getVectorElementType() == MVT::i1) && 171 "Expected scalable predicate vector type!"); 172 switch (VT.getVectorMinNumElements()) { 173 default: 174 llvm_unreachable("unexpected element count for vector"); 175 case 2: 176 return MVT::nxv2i64; 177 case 4: 178 return MVT::nxv4i32; 179 case 8: 180 return MVT::nxv8i16; 181 case 16: 182 return MVT::nxv16i8; 183 } 184 } 185 186 /// Returns true if VT's elements occupy the lowest bit positions of its 187 /// associated register class without any intervening space. 188 /// 189 /// For example, nxv2f16, nxv4f16 and nxv8f16 are legal types that belong to the 190 /// same register class, but only nxv8f16 can be treated as a packed vector. 191 static inline bool isPackedVectorType(EVT VT, SelectionDAG &DAG) { 192 assert(VT.isVector() && DAG.getTargetLoweringInfo().isTypeLegal(VT) && 193 "Expected legal vector type!"); 194 return VT.isFixedLengthVector() || 195 VT.getSizeInBits().getKnownMinSize() == AArch64::SVEBitsPerBlock; 196 } 197 198 // Returns true for ####_MERGE_PASSTHRU opcodes, whose operands have a leading 199 // predicate and end with a passthru value matching the result type. 200 static bool isMergePassthruOpcode(unsigned Opc) { 201 switch (Opc) { 202 default: 203 return false; 204 case AArch64ISD::BITREVERSE_MERGE_PASSTHRU: 205 case AArch64ISD::BSWAP_MERGE_PASSTHRU: 206 case AArch64ISD::CTLZ_MERGE_PASSTHRU: 207 case AArch64ISD::CTPOP_MERGE_PASSTHRU: 208 case AArch64ISD::DUP_MERGE_PASSTHRU: 209 case AArch64ISD::ABS_MERGE_PASSTHRU: 210 case AArch64ISD::NEG_MERGE_PASSTHRU: 211 case AArch64ISD::FNEG_MERGE_PASSTHRU: 212 case AArch64ISD::SIGN_EXTEND_INREG_MERGE_PASSTHRU: 213 case AArch64ISD::ZERO_EXTEND_INREG_MERGE_PASSTHRU: 214 case AArch64ISD::FCEIL_MERGE_PASSTHRU: 215 case AArch64ISD::FFLOOR_MERGE_PASSTHRU: 216 case AArch64ISD::FNEARBYINT_MERGE_PASSTHRU: 217 case AArch64ISD::FRINT_MERGE_PASSTHRU: 218 case AArch64ISD::FROUND_MERGE_PASSTHRU: 219 case AArch64ISD::FROUNDEVEN_MERGE_PASSTHRU: 220 case AArch64ISD::FTRUNC_MERGE_PASSTHRU: 221 case AArch64ISD::FP_ROUND_MERGE_PASSTHRU: 222 case AArch64ISD::FP_EXTEND_MERGE_PASSTHRU: 223 case AArch64ISD::SINT_TO_FP_MERGE_PASSTHRU: 224 case AArch64ISD::UINT_TO_FP_MERGE_PASSTHRU: 225 case AArch64ISD::FCVTZU_MERGE_PASSTHRU: 226 case AArch64ISD::FCVTZS_MERGE_PASSTHRU: 227 case AArch64ISD::FSQRT_MERGE_PASSTHRU: 228 case AArch64ISD::FRECPX_MERGE_PASSTHRU: 229 case AArch64ISD::FABS_MERGE_PASSTHRU: 230 return true; 231 } 232 } 233 234 AArch64TargetLowering::AArch64TargetLowering(const TargetMachine &TM, 235 const AArch64Subtarget &STI) 236 : TargetLowering(TM), Subtarget(&STI) { 237 // AArch64 doesn't have comparisons which set GPRs or setcc instructions, so 238 // we have to make something up. Arbitrarily, choose ZeroOrOne. 239 setBooleanContents(ZeroOrOneBooleanContent); 240 // When comparing vectors the result sets the different elements in the 241 // vector to all-one or all-zero. 242 setBooleanVectorContents(ZeroOrNegativeOneBooleanContent); 243 244 // Set up the register classes. 245 addRegisterClass(MVT::i32, &AArch64::GPR32allRegClass); 246 addRegisterClass(MVT::i64, &AArch64::GPR64allRegClass); 247 248 if (Subtarget->hasFPARMv8()) { 249 addRegisterClass(MVT::f16, &AArch64::FPR16RegClass); 250 addRegisterClass(MVT::bf16, &AArch64::FPR16RegClass); 251 addRegisterClass(MVT::f32, &AArch64::FPR32RegClass); 252 addRegisterClass(MVT::f64, &AArch64::FPR64RegClass); 253 addRegisterClass(MVT::f128, &AArch64::FPR128RegClass); 254 } 255 256 if (Subtarget->hasNEON()) { 257 addRegisterClass(MVT::v16i8, &AArch64::FPR8RegClass); 258 addRegisterClass(MVT::v8i16, &AArch64::FPR16RegClass); 259 // Someone set us up the NEON. 260 addDRTypeForNEON(MVT::v2f32); 261 addDRTypeForNEON(MVT::v8i8); 262 addDRTypeForNEON(MVT::v4i16); 263 addDRTypeForNEON(MVT::v2i32); 264 addDRTypeForNEON(MVT::v1i64); 265 addDRTypeForNEON(MVT::v1f64); 266 addDRTypeForNEON(MVT::v4f16); 267 if (Subtarget->hasBF16()) 268 addDRTypeForNEON(MVT::v4bf16); 269 270 addQRTypeForNEON(MVT::v4f32); 271 addQRTypeForNEON(MVT::v2f64); 272 addQRTypeForNEON(MVT::v16i8); 273 addQRTypeForNEON(MVT::v8i16); 274 addQRTypeForNEON(MVT::v4i32); 275 addQRTypeForNEON(MVT::v2i64); 276 addQRTypeForNEON(MVT::v8f16); 277 if (Subtarget->hasBF16()) 278 addQRTypeForNEON(MVT::v8bf16); 279 } 280 281 if (Subtarget->hasSVE()) { 282 // Add legal sve predicate types 283 addRegisterClass(MVT::nxv2i1, &AArch64::PPRRegClass); 284 addRegisterClass(MVT::nxv4i1, &AArch64::PPRRegClass); 285 addRegisterClass(MVT::nxv8i1, &AArch64::PPRRegClass); 286 addRegisterClass(MVT::nxv16i1, &AArch64::PPRRegClass); 287 288 // Add legal sve data types 289 addRegisterClass(MVT::nxv16i8, &AArch64::ZPRRegClass); 290 addRegisterClass(MVT::nxv8i16, &AArch64::ZPRRegClass); 291 addRegisterClass(MVT::nxv4i32, &AArch64::ZPRRegClass); 292 addRegisterClass(MVT::nxv2i64, &AArch64::ZPRRegClass); 293 294 addRegisterClass(MVT::nxv2f16, &AArch64::ZPRRegClass); 295 addRegisterClass(MVT::nxv4f16, &AArch64::ZPRRegClass); 296 addRegisterClass(MVT::nxv8f16, &AArch64::ZPRRegClass); 297 addRegisterClass(MVT::nxv2f32, &AArch64::ZPRRegClass); 298 addRegisterClass(MVT::nxv4f32, &AArch64::ZPRRegClass); 299 addRegisterClass(MVT::nxv2f64, &AArch64::ZPRRegClass); 300 301 if (Subtarget->hasBF16()) { 302 addRegisterClass(MVT::nxv2bf16, &AArch64::ZPRRegClass); 303 addRegisterClass(MVT::nxv4bf16, &AArch64::ZPRRegClass); 304 addRegisterClass(MVT::nxv8bf16, &AArch64::ZPRRegClass); 305 } 306 307 if (Subtarget->useSVEForFixedLengthVectors()) { 308 for (MVT VT : MVT::integer_fixedlen_vector_valuetypes()) 309 if (useSVEForFixedLengthVectorVT(VT)) 310 addRegisterClass(VT, &AArch64::ZPRRegClass); 311 312 for (MVT VT : MVT::fp_fixedlen_vector_valuetypes()) 313 if (useSVEForFixedLengthVectorVT(VT)) 314 addRegisterClass(VT, &AArch64::ZPRRegClass); 315 } 316 317 for (auto VT : { MVT::nxv16i8, MVT::nxv8i16, MVT::nxv4i32, MVT::nxv2i64 }) { 318 setOperationAction(ISD::SADDSAT, VT, Legal); 319 setOperationAction(ISD::UADDSAT, VT, Legal); 320 setOperationAction(ISD::SSUBSAT, VT, Legal); 321 setOperationAction(ISD::USUBSAT, VT, Legal); 322 setOperationAction(ISD::UREM, VT, Expand); 323 setOperationAction(ISD::SREM, VT, Expand); 324 setOperationAction(ISD::SDIVREM, VT, Expand); 325 setOperationAction(ISD::UDIVREM, VT, Expand); 326 } 327 328 for (auto VT : 329 { MVT::nxv2i8, MVT::nxv2i16, MVT::nxv2i32, MVT::nxv2i64, MVT::nxv4i8, 330 MVT::nxv4i16, MVT::nxv4i32, MVT::nxv8i8, MVT::nxv8i16 }) 331 setOperationAction(ISD::SIGN_EXTEND_INREG, VT, Legal); 332 333 for (auto VT : 334 { MVT::nxv2f16, MVT::nxv4f16, MVT::nxv8f16, MVT::nxv2f32, MVT::nxv4f32, 335 MVT::nxv2f64 }) { 336 setCondCodeAction(ISD::SETO, VT, Expand); 337 setCondCodeAction(ISD::SETOLT, VT, Expand); 338 setCondCodeAction(ISD::SETLT, VT, Expand); 339 setCondCodeAction(ISD::SETOLE, VT, Expand); 340 setCondCodeAction(ISD::SETLE, VT, Expand); 341 setCondCodeAction(ISD::SETULT, VT, Expand); 342 setCondCodeAction(ISD::SETULE, VT, Expand); 343 setCondCodeAction(ISD::SETUGE, VT, Expand); 344 setCondCodeAction(ISD::SETUGT, VT, Expand); 345 setCondCodeAction(ISD::SETUEQ, VT, Expand); 346 setCondCodeAction(ISD::SETUNE, VT, Expand); 347 348 setOperationAction(ISD::FREM, VT, Expand); 349 setOperationAction(ISD::FPOW, VT, Expand); 350 setOperationAction(ISD::FPOWI, VT, Expand); 351 setOperationAction(ISD::FCOS, VT, Expand); 352 setOperationAction(ISD::FSIN, VT, Expand); 353 setOperationAction(ISD::FSINCOS, VT, Expand); 354 setOperationAction(ISD::FEXP, VT, Expand); 355 setOperationAction(ISD::FEXP2, VT, Expand); 356 setOperationAction(ISD::FLOG, VT, Expand); 357 setOperationAction(ISD::FLOG2, VT, Expand); 358 setOperationAction(ISD::FLOG10, VT, Expand); 359 } 360 } 361 362 // Compute derived properties from the register classes 363 computeRegisterProperties(Subtarget->getRegisterInfo()); 364 365 // Provide all sorts of operation actions 366 setOperationAction(ISD::GlobalAddress, MVT::i64, Custom); 367 setOperationAction(ISD::GlobalTLSAddress, MVT::i64, Custom); 368 setOperationAction(ISD::SETCC, MVT::i32, Custom); 369 setOperationAction(ISD::SETCC, MVT::i64, Custom); 370 setOperationAction(ISD::SETCC, MVT::f16, Custom); 371 setOperationAction(ISD::SETCC, MVT::f32, Custom); 372 setOperationAction(ISD::SETCC, MVT::f64, Custom); 373 setOperationAction(ISD::STRICT_FSETCC, MVT::f16, Custom); 374 setOperationAction(ISD::STRICT_FSETCC, MVT::f32, Custom); 375 setOperationAction(ISD::STRICT_FSETCC, MVT::f64, Custom); 376 setOperationAction(ISD::STRICT_FSETCCS, MVT::f16, Custom); 377 setOperationAction(ISD::STRICT_FSETCCS, MVT::f32, Custom); 378 setOperationAction(ISD::STRICT_FSETCCS, MVT::f64, Custom); 379 setOperationAction(ISD::BITREVERSE, MVT::i32, Legal); 380 setOperationAction(ISD::BITREVERSE, MVT::i64, Legal); 381 setOperationAction(ISD::BRCOND, MVT::Other, Expand); 382 setOperationAction(ISD::BR_CC, MVT::i32, Custom); 383 setOperationAction(ISD::BR_CC, MVT::i64, Custom); 384 setOperationAction(ISD::BR_CC, MVT::f16, Custom); 385 setOperationAction(ISD::BR_CC, MVT::f32, Custom); 386 setOperationAction(ISD::BR_CC, MVT::f64, Custom); 387 setOperationAction(ISD::SELECT, MVT::i32, Custom); 388 setOperationAction(ISD::SELECT, MVT::i64, Custom); 389 setOperationAction(ISD::SELECT, MVT::f16, Custom); 390 setOperationAction(ISD::SELECT, MVT::f32, Custom); 391 setOperationAction(ISD::SELECT, MVT::f64, Custom); 392 setOperationAction(ISD::SELECT_CC, MVT::i32, Custom); 393 setOperationAction(ISD::SELECT_CC, MVT::i64, Custom); 394 setOperationAction(ISD::SELECT_CC, MVT::f16, Custom); 395 setOperationAction(ISD::SELECT_CC, MVT::f32, Custom); 396 setOperationAction(ISD::SELECT_CC, MVT::f64, Custom); 397 setOperationAction(ISD::BR_JT, MVT::Other, Custom); 398 setOperationAction(ISD::JumpTable, MVT::i64, Custom); 399 400 setOperationAction(ISD::SHL_PARTS, MVT::i64, Custom); 401 setOperationAction(ISD::SRA_PARTS, MVT::i64, Custom); 402 setOperationAction(ISD::SRL_PARTS, MVT::i64, Custom); 403 404 setOperationAction(ISD::FREM, MVT::f32, Expand); 405 setOperationAction(ISD::FREM, MVT::f64, Expand); 406 setOperationAction(ISD::FREM, MVT::f80, Expand); 407 408 setOperationAction(ISD::BUILD_PAIR, MVT::i64, Expand); 409 410 // Custom lowering hooks are needed for XOR 411 // to fold it into CSINC/CSINV. 412 setOperationAction(ISD::XOR, MVT::i32, Custom); 413 setOperationAction(ISD::XOR, MVT::i64, Custom); 414 415 // Virtually no operation on f128 is legal, but LLVM can't expand them when 416 // there's a valid register class, so we need custom operations in most cases. 417 setOperationAction(ISD::FABS, MVT::f128, Expand); 418 setOperationAction(ISD::FADD, MVT::f128, LibCall); 419 setOperationAction(ISD::FCOPYSIGN, MVT::f128, Expand); 420 setOperationAction(ISD::FCOS, MVT::f128, Expand); 421 setOperationAction(ISD::FDIV, MVT::f128, LibCall); 422 setOperationAction(ISD::FMA, MVT::f128, Expand); 423 setOperationAction(ISD::FMUL, MVT::f128, LibCall); 424 setOperationAction(ISD::FNEG, MVT::f128, Expand); 425 setOperationAction(ISD::FPOW, MVT::f128, Expand); 426 setOperationAction(ISD::FREM, MVT::f128, Expand); 427 setOperationAction(ISD::FRINT, MVT::f128, Expand); 428 setOperationAction(ISD::FSIN, MVT::f128, Expand); 429 setOperationAction(ISD::FSINCOS, MVT::f128, Expand); 430 setOperationAction(ISD::FSQRT, MVT::f128, Expand); 431 setOperationAction(ISD::FSUB, MVT::f128, LibCall); 432 setOperationAction(ISD::FTRUNC, MVT::f128, Expand); 433 setOperationAction(ISD::SETCC, MVT::f128, Custom); 434 setOperationAction(ISD::STRICT_FSETCC, MVT::f128, Custom); 435 setOperationAction(ISD::STRICT_FSETCCS, MVT::f128, Custom); 436 setOperationAction(ISD::BR_CC, MVT::f128, Custom); 437 setOperationAction(ISD::SELECT, MVT::f128, Custom); 438 setOperationAction(ISD::SELECT_CC, MVT::f128, Custom); 439 setOperationAction(ISD::FP_EXTEND, MVT::f128, Custom); 440 441 // Lowering for many of the conversions is actually specified by the non-f128 442 // type. The LowerXXX function will be trivial when f128 isn't involved. 443 setOperationAction(ISD::FP_TO_SINT, MVT::i32, Custom); 444 setOperationAction(ISD::FP_TO_SINT, MVT::i64, Custom); 445 setOperationAction(ISD::FP_TO_SINT, MVT::i128, Custom); 446 setOperationAction(ISD::STRICT_FP_TO_SINT, MVT::i32, Custom); 447 setOperationAction(ISD::STRICT_FP_TO_SINT, MVT::i64, Custom); 448 setOperationAction(ISD::STRICT_FP_TO_SINT, MVT::i128, Custom); 449 setOperationAction(ISD::FP_TO_UINT, MVT::i32, Custom); 450 setOperationAction(ISD::FP_TO_UINT, MVT::i64, Custom); 451 setOperationAction(ISD::FP_TO_UINT, MVT::i128, Custom); 452 setOperationAction(ISD::STRICT_FP_TO_UINT, MVT::i32, Custom); 453 setOperationAction(ISD::STRICT_FP_TO_UINT, MVT::i64, Custom); 454 setOperationAction(ISD::STRICT_FP_TO_UINT, MVT::i128, Custom); 455 setOperationAction(ISD::SINT_TO_FP, MVT::i32, Custom); 456 setOperationAction(ISD::SINT_TO_FP, MVT::i64, Custom); 457 setOperationAction(ISD::SINT_TO_FP, MVT::i128, Custom); 458 setOperationAction(ISD::STRICT_SINT_TO_FP, MVT::i32, Custom); 459 setOperationAction(ISD::STRICT_SINT_TO_FP, MVT::i64, Custom); 460 setOperationAction(ISD::STRICT_SINT_TO_FP, MVT::i128, Custom); 461 setOperationAction(ISD::UINT_TO_FP, MVT::i32, Custom); 462 setOperationAction(ISD::UINT_TO_FP, MVT::i64, Custom); 463 setOperationAction(ISD::UINT_TO_FP, MVT::i128, Custom); 464 setOperationAction(ISD::STRICT_UINT_TO_FP, MVT::i32, Custom); 465 setOperationAction(ISD::STRICT_UINT_TO_FP, MVT::i64, Custom); 466 setOperationAction(ISD::STRICT_UINT_TO_FP, MVT::i128, Custom); 467 setOperationAction(ISD::FP_ROUND, MVT::f16, Custom); 468 setOperationAction(ISD::FP_ROUND, MVT::f32, Custom); 469 setOperationAction(ISD::FP_ROUND, MVT::f64, Custom); 470 setOperationAction(ISD::STRICT_FP_ROUND, MVT::f16, Custom); 471 setOperationAction(ISD::STRICT_FP_ROUND, MVT::f32, Custom); 472 setOperationAction(ISD::STRICT_FP_ROUND, MVT::f64, Custom); 473 474 // Variable arguments. 475 setOperationAction(ISD::VASTART, MVT::Other, Custom); 476 setOperationAction(ISD::VAARG, MVT::Other, Custom); 477 setOperationAction(ISD::VACOPY, MVT::Other, Custom); 478 setOperationAction(ISD::VAEND, MVT::Other, Expand); 479 480 // Variable-sized objects. 481 setOperationAction(ISD::STACKSAVE, MVT::Other, Expand); 482 setOperationAction(ISD::STACKRESTORE, MVT::Other, Expand); 483 484 if (Subtarget->isTargetWindows()) 485 setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i64, Custom); 486 else 487 setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i64, Expand); 488 489 // Constant pool entries 490 setOperationAction(ISD::ConstantPool, MVT::i64, Custom); 491 492 // BlockAddress 493 setOperationAction(ISD::BlockAddress, MVT::i64, Custom); 494 495 // Add/Sub overflow ops with MVT::Glues are lowered to NZCV dependences. 496 setOperationAction(ISD::ADDC, MVT::i32, Custom); 497 setOperationAction(ISD::ADDE, MVT::i32, Custom); 498 setOperationAction(ISD::SUBC, MVT::i32, Custom); 499 setOperationAction(ISD::SUBE, MVT::i32, Custom); 500 setOperationAction(ISD::ADDC, MVT::i64, Custom); 501 setOperationAction(ISD::ADDE, MVT::i64, Custom); 502 setOperationAction(ISD::SUBC, MVT::i64, Custom); 503 setOperationAction(ISD::SUBE, MVT::i64, Custom); 504 505 // AArch64 lacks both left-rotate and popcount instructions. 506 setOperationAction(ISD::ROTL, MVT::i32, Expand); 507 setOperationAction(ISD::ROTL, MVT::i64, Expand); 508 for (MVT VT : MVT::fixedlen_vector_valuetypes()) { 509 setOperationAction(ISD::ROTL, VT, Expand); 510 setOperationAction(ISD::ROTR, VT, Expand); 511 } 512 513 // AArch64 doesn't have i32 MULH{S|U}. 514 setOperationAction(ISD::MULHU, MVT::i32, Expand); 515 setOperationAction(ISD::MULHS, MVT::i32, Expand); 516 517 // AArch64 doesn't have {U|S}MUL_LOHI. 518 setOperationAction(ISD::UMUL_LOHI, MVT::i64, Expand); 519 setOperationAction(ISD::SMUL_LOHI, MVT::i64, Expand); 520 521 setOperationAction(ISD::CTPOP, MVT::i32, Custom); 522 setOperationAction(ISD::CTPOP, MVT::i64, Custom); 523 setOperationAction(ISD::CTPOP, MVT::i128, Custom); 524 525 setOperationAction(ISD::ABS, MVT::i32, Custom); 526 setOperationAction(ISD::ABS, MVT::i64, Custom); 527 528 setOperationAction(ISD::SDIVREM, MVT::i32, Expand); 529 setOperationAction(ISD::SDIVREM, MVT::i64, Expand); 530 for (MVT VT : MVT::fixedlen_vector_valuetypes()) { 531 setOperationAction(ISD::SDIVREM, VT, Expand); 532 setOperationAction(ISD::UDIVREM, VT, Expand); 533 } 534 setOperationAction(ISD::SREM, MVT::i32, Expand); 535 setOperationAction(ISD::SREM, MVT::i64, Expand); 536 setOperationAction(ISD::UDIVREM, MVT::i32, Expand); 537 setOperationAction(ISD::UDIVREM, MVT::i64, Expand); 538 setOperationAction(ISD::UREM, MVT::i32, Expand); 539 setOperationAction(ISD::UREM, MVT::i64, Expand); 540 541 // Custom lower Add/Sub/Mul with overflow. 542 setOperationAction(ISD::SADDO, MVT::i32, Custom); 543 setOperationAction(ISD::SADDO, MVT::i64, Custom); 544 setOperationAction(ISD::UADDO, MVT::i32, Custom); 545 setOperationAction(ISD::UADDO, MVT::i64, Custom); 546 setOperationAction(ISD::SSUBO, MVT::i32, Custom); 547 setOperationAction(ISD::SSUBO, MVT::i64, Custom); 548 setOperationAction(ISD::USUBO, MVT::i32, Custom); 549 setOperationAction(ISD::USUBO, MVT::i64, Custom); 550 setOperationAction(ISD::SMULO, MVT::i32, Custom); 551 setOperationAction(ISD::SMULO, MVT::i64, Custom); 552 setOperationAction(ISD::UMULO, MVT::i32, Custom); 553 setOperationAction(ISD::UMULO, MVT::i64, Custom); 554 555 setOperationAction(ISD::FSIN, MVT::f32, Expand); 556 setOperationAction(ISD::FSIN, MVT::f64, Expand); 557 setOperationAction(ISD::FCOS, MVT::f32, Expand); 558 setOperationAction(ISD::FCOS, MVT::f64, Expand); 559 setOperationAction(ISD::FPOW, MVT::f32, Expand); 560 setOperationAction(ISD::FPOW, MVT::f64, Expand); 561 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Custom); 562 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom); 563 if (Subtarget->hasFullFP16()) 564 setOperationAction(ISD::FCOPYSIGN, MVT::f16, Custom); 565 else 566 setOperationAction(ISD::FCOPYSIGN, MVT::f16, Promote); 567 568 setOperationAction(ISD::FREM, MVT::f16, Promote); 569 setOperationAction(ISD::FREM, MVT::v4f16, Expand); 570 setOperationAction(ISD::FREM, MVT::v8f16, Expand); 571 setOperationAction(ISD::FPOW, MVT::f16, Promote); 572 setOperationAction(ISD::FPOW, MVT::v4f16, Expand); 573 setOperationAction(ISD::FPOW, MVT::v8f16, Expand); 574 setOperationAction(ISD::FPOWI, MVT::f16, Promote); 575 setOperationAction(ISD::FPOWI, MVT::v4f16, Expand); 576 setOperationAction(ISD::FPOWI, MVT::v8f16, Expand); 577 setOperationAction(ISD::FCOS, MVT::f16, Promote); 578 setOperationAction(ISD::FCOS, MVT::v4f16, Expand); 579 setOperationAction(ISD::FCOS, MVT::v8f16, Expand); 580 setOperationAction(ISD::FSIN, MVT::f16, Promote); 581 setOperationAction(ISD::FSIN, MVT::v4f16, Expand); 582 setOperationAction(ISD::FSIN, MVT::v8f16, Expand); 583 setOperationAction(ISD::FSINCOS, MVT::f16, Promote); 584 setOperationAction(ISD::FSINCOS, MVT::v4f16, Expand); 585 setOperationAction(ISD::FSINCOS, MVT::v8f16, Expand); 586 setOperationAction(ISD::FEXP, MVT::f16, Promote); 587 setOperationAction(ISD::FEXP, MVT::v4f16, Expand); 588 setOperationAction(ISD::FEXP, MVT::v8f16, Expand); 589 setOperationAction(ISD::FEXP2, MVT::f16, Promote); 590 setOperationAction(ISD::FEXP2, MVT::v4f16, Expand); 591 setOperationAction(ISD::FEXP2, MVT::v8f16, Expand); 592 setOperationAction(ISD::FLOG, MVT::f16, Promote); 593 setOperationAction(ISD::FLOG, MVT::v4f16, Expand); 594 setOperationAction(ISD::FLOG, MVT::v8f16, Expand); 595 setOperationAction(ISD::FLOG2, MVT::f16, Promote); 596 setOperationAction(ISD::FLOG2, MVT::v4f16, Expand); 597 setOperationAction(ISD::FLOG2, MVT::v8f16, Expand); 598 setOperationAction(ISD::FLOG10, MVT::f16, Promote); 599 setOperationAction(ISD::FLOG10, MVT::v4f16, Expand); 600 setOperationAction(ISD::FLOG10, MVT::v8f16, Expand); 601 602 if (!Subtarget->hasFullFP16()) { 603 setOperationAction(ISD::SELECT, MVT::f16, Promote); 604 setOperationAction(ISD::SELECT_CC, MVT::f16, Promote); 605 setOperationAction(ISD::SETCC, MVT::f16, Promote); 606 setOperationAction(ISD::BR_CC, MVT::f16, Promote); 607 setOperationAction(ISD::FADD, MVT::f16, Promote); 608 setOperationAction(ISD::FSUB, MVT::f16, Promote); 609 setOperationAction(ISD::FMUL, MVT::f16, Promote); 610 setOperationAction(ISD::FDIV, MVT::f16, Promote); 611 setOperationAction(ISD::FMA, MVT::f16, Promote); 612 setOperationAction(ISD::FNEG, MVT::f16, Promote); 613 setOperationAction(ISD::FABS, MVT::f16, Promote); 614 setOperationAction(ISD::FCEIL, MVT::f16, Promote); 615 setOperationAction(ISD::FSQRT, MVT::f16, Promote); 616 setOperationAction(ISD::FFLOOR, MVT::f16, Promote); 617 setOperationAction(ISD::FNEARBYINT, MVT::f16, Promote); 618 setOperationAction(ISD::FRINT, MVT::f16, Promote); 619 setOperationAction(ISD::FROUND, MVT::f16, Promote); 620 setOperationAction(ISD::FROUNDEVEN, MVT::f16, Promote); 621 setOperationAction(ISD::FTRUNC, MVT::f16, Promote); 622 setOperationAction(ISD::FMINNUM, MVT::f16, Promote); 623 setOperationAction(ISD::FMAXNUM, MVT::f16, Promote); 624 setOperationAction(ISD::FMINIMUM, MVT::f16, Promote); 625 setOperationAction(ISD::FMAXIMUM, MVT::f16, Promote); 626 627 // promote v4f16 to v4f32 when that is known to be safe. 628 setOperationAction(ISD::FADD, MVT::v4f16, Promote); 629 setOperationAction(ISD::FSUB, MVT::v4f16, Promote); 630 setOperationAction(ISD::FMUL, MVT::v4f16, Promote); 631 setOperationAction(ISD::FDIV, MVT::v4f16, Promote); 632 AddPromotedToType(ISD::FADD, MVT::v4f16, MVT::v4f32); 633 AddPromotedToType(ISD::FSUB, MVT::v4f16, MVT::v4f32); 634 AddPromotedToType(ISD::FMUL, MVT::v4f16, MVT::v4f32); 635 AddPromotedToType(ISD::FDIV, MVT::v4f16, MVT::v4f32); 636 637 setOperationAction(ISD::FABS, MVT::v4f16, Expand); 638 setOperationAction(ISD::FNEG, MVT::v4f16, Expand); 639 setOperationAction(ISD::FROUND, MVT::v4f16, Expand); 640 setOperationAction(ISD::FROUNDEVEN, MVT::v4f16, Expand); 641 setOperationAction(ISD::FMA, MVT::v4f16, Expand); 642 setOperationAction(ISD::SETCC, MVT::v4f16, Expand); 643 setOperationAction(ISD::BR_CC, MVT::v4f16, Expand); 644 setOperationAction(ISD::SELECT, MVT::v4f16, Expand); 645 setOperationAction(ISD::SELECT_CC, MVT::v4f16, Expand); 646 setOperationAction(ISD::FTRUNC, MVT::v4f16, Expand); 647 setOperationAction(ISD::FCOPYSIGN, MVT::v4f16, Expand); 648 setOperationAction(ISD::FFLOOR, MVT::v4f16, Expand); 649 setOperationAction(ISD::FCEIL, MVT::v4f16, Expand); 650 setOperationAction(ISD::FRINT, MVT::v4f16, Expand); 651 setOperationAction(ISD::FNEARBYINT, MVT::v4f16, Expand); 652 setOperationAction(ISD::FSQRT, MVT::v4f16, Expand); 653 654 setOperationAction(ISD::FABS, MVT::v8f16, Expand); 655 setOperationAction(ISD::FADD, MVT::v8f16, Expand); 656 setOperationAction(ISD::FCEIL, MVT::v8f16, Expand); 657 setOperationAction(ISD::FCOPYSIGN, MVT::v8f16, Expand); 658 setOperationAction(ISD::FDIV, MVT::v8f16, Expand); 659 setOperationAction(ISD::FFLOOR, MVT::v8f16, Expand); 660 setOperationAction(ISD::FMA, MVT::v8f16, Expand); 661 setOperationAction(ISD::FMUL, MVT::v8f16, Expand); 662 setOperationAction(ISD::FNEARBYINT, MVT::v8f16, Expand); 663 setOperationAction(ISD::FNEG, MVT::v8f16, Expand); 664 setOperationAction(ISD::FROUND, MVT::v8f16, Expand); 665 setOperationAction(ISD::FROUNDEVEN, MVT::v8f16, Expand); 666 setOperationAction(ISD::FRINT, MVT::v8f16, Expand); 667 setOperationAction(ISD::FSQRT, MVT::v8f16, Expand); 668 setOperationAction(ISD::FSUB, MVT::v8f16, Expand); 669 setOperationAction(ISD::FTRUNC, MVT::v8f16, Expand); 670 setOperationAction(ISD::SETCC, MVT::v8f16, Expand); 671 setOperationAction(ISD::BR_CC, MVT::v8f16, Expand); 672 setOperationAction(ISD::SELECT, MVT::v8f16, Expand); 673 setOperationAction(ISD::SELECT_CC, MVT::v8f16, Expand); 674 setOperationAction(ISD::FP_EXTEND, MVT::v8f16, Expand); 675 } 676 677 // AArch64 has implementations of a lot of rounding-like FP operations. 678 for (MVT Ty : {MVT::f32, MVT::f64}) { 679 setOperationAction(ISD::FFLOOR, Ty, Legal); 680 setOperationAction(ISD::FNEARBYINT, Ty, Legal); 681 setOperationAction(ISD::FCEIL, Ty, Legal); 682 setOperationAction(ISD::FRINT, Ty, Legal); 683 setOperationAction(ISD::FTRUNC, Ty, Legal); 684 setOperationAction(ISD::FROUND, Ty, Legal); 685 setOperationAction(ISD::FROUNDEVEN, Ty, Legal); 686 setOperationAction(ISD::FMINNUM, Ty, Legal); 687 setOperationAction(ISD::FMAXNUM, Ty, Legal); 688 setOperationAction(ISD::FMINIMUM, Ty, Legal); 689 setOperationAction(ISD::FMAXIMUM, Ty, Legal); 690 setOperationAction(ISD::LROUND, Ty, Legal); 691 setOperationAction(ISD::LLROUND, Ty, Legal); 692 setOperationAction(ISD::LRINT, Ty, Legal); 693 setOperationAction(ISD::LLRINT, Ty, Legal); 694 } 695 696 if (Subtarget->hasFullFP16()) { 697 setOperationAction(ISD::FNEARBYINT, MVT::f16, Legal); 698 setOperationAction(ISD::FFLOOR, MVT::f16, Legal); 699 setOperationAction(ISD::FCEIL, MVT::f16, Legal); 700 setOperationAction(ISD::FRINT, MVT::f16, Legal); 701 setOperationAction(ISD::FTRUNC, MVT::f16, Legal); 702 setOperationAction(ISD::FROUND, MVT::f16, Legal); 703 setOperationAction(ISD::FROUNDEVEN, MVT::f16, Legal); 704 setOperationAction(ISD::FMINNUM, MVT::f16, Legal); 705 setOperationAction(ISD::FMAXNUM, MVT::f16, Legal); 706 setOperationAction(ISD::FMINIMUM, MVT::f16, Legal); 707 setOperationAction(ISD::FMAXIMUM, MVT::f16, Legal); 708 } 709 710 setOperationAction(ISD::PREFETCH, MVT::Other, Custom); 711 712 setOperationAction(ISD::FLT_ROUNDS_, MVT::i32, Custom); 713 setOperationAction(ISD::SET_ROUNDING, MVT::Other, Custom); 714 715 setOperationAction(ISD::ATOMIC_CMP_SWAP, MVT::i128, Custom); 716 setOperationAction(ISD::ATOMIC_LOAD_SUB, MVT::i32, Custom); 717 setOperationAction(ISD::ATOMIC_LOAD_SUB, MVT::i64, Custom); 718 setOperationAction(ISD::ATOMIC_LOAD_AND, MVT::i32, Custom); 719 setOperationAction(ISD::ATOMIC_LOAD_AND, MVT::i64, Custom); 720 721 // Generate outline atomics library calls only if LSE was not specified for 722 // subtarget 723 if (Subtarget->outlineAtomics() && !Subtarget->hasLSE()) { 724 setOperationAction(ISD::ATOMIC_CMP_SWAP, MVT::i8, LibCall); 725 setOperationAction(ISD::ATOMIC_CMP_SWAP, MVT::i16, LibCall); 726 setOperationAction(ISD::ATOMIC_CMP_SWAP, MVT::i32, LibCall); 727 setOperationAction(ISD::ATOMIC_CMP_SWAP, MVT::i64, LibCall); 728 setOperationAction(ISD::ATOMIC_CMP_SWAP, MVT::i128, LibCall); 729 setOperationAction(ISD::ATOMIC_SWAP, MVT::i8, LibCall); 730 setOperationAction(ISD::ATOMIC_SWAP, MVT::i16, LibCall); 731 setOperationAction(ISD::ATOMIC_SWAP, MVT::i32, LibCall); 732 setOperationAction(ISD::ATOMIC_SWAP, MVT::i64, LibCall); 733 setOperationAction(ISD::ATOMIC_LOAD_ADD, MVT::i8, LibCall); 734 setOperationAction(ISD::ATOMIC_LOAD_ADD, MVT::i16, LibCall); 735 setOperationAction(ISD::ATOMIC_LOAD_ADD, MVT::i32, LibCall); 736 setOperationAction(ISD::ATOMIC_LOAD_ADD, MVT::i64, LibCall); 737 setOperationAction(ISD::ATOMIC_LOAD_OR, MVT::i8, LibCall); 738 setOperationAction(ISD::ATOMIC_LOAD_OR, MVT::i16, LibCall); 739 setOperationAction(ISD::ATOMIC_LOAD_OR, MVT::i32, LibCall); 740 setOperationAction(ISD::ATOMIC_LOAD_OR, MVT::i64, LibCall); 741 setOperationAction(ISD::ATOMIC_LOAD_CLR, MVT::i8, LibCall); 742 setOperationAction(ISD::ATOMIC_LOAD_CLR, MVT::i16, LibCall); 743 setOperationAction(ISD::ATOMIC_LOAD_CLR, MVT::i32, LibCall); 744 setOperationAction(ISD::ATOMIC_LOAD_CLR, MVT::i64, LibCall); 745 setOperationAction(ISD::ATOMIC_LOAD_XOR, MVT::i8, LibCall); 746 setOperationAction(ISD::ATOMIC_LOAD_XOR, MVT::i16, LibCall); 747 setOperationAction(ISD::ATOMIC_LOAD_XOR, MVT::i32, LibCall); 748 setOperationAction(ISD::ATOMIC_LOAD_XOR, MVT::i64, LibCall); 749 #define LCALLNAMES(A, B, N) \ 750 setLibcallName(A##N##_RELAX, #B #N "_relax"); \ 751 setLibcallName(A##N##_ACQ, #B #N "_acq"); \ 752 setLibcallName(A##N##_REL, #B #N "_rel"); \ 753 setLibcallName(A##N##_ACQ_REL, #B #N "_acq_rel"); 754 #define LCALLNAME4(A, B) \ 755 LCALLNAMES(A, B, 1) \ 756 LCALLNAMES(A, B, 2) LCALLNAMES(A, B, 4) LCALLNAMES(A, B, 8) 757 #define LCALLNAME5(A, B) \ 758 LCALLNAMES(A, B, 1) \ 759 LCALLNAMES(A, B, 2) \ 760 LCALLNAMES(A, B, 4) LCALLNAMES(A, B, 8) LCALLNAMES(A, B, 16) 761 LCALLNAME5(RTLIB::OUTLINE_ATOMIC_CAS, __aarch64_cas) 762 LCALLNAME4(RTLIB::OUTLINE_ATOMIC_SWP, __aarch64_swp) 763 LCALLNAME4(RTLIB::OUTLINE_ATOMIC_LDADD, __aarch64_ldadd) 764 LCALLNAME4(RTLIB::OUTLINE_ATOMIC_LDSET, __aarch64_ldset) 765 LCALLNAME4(RTLIB::OUTLINE_ATOMIC_LDCLR, __aarch64_ldclr) 766 LCALLNAME4(RTLIB::OUTLINE_ATOMIC_LDEOR, __aarch64_ldeor) 767 #undef LCALLNAMES 768 #undef LCALLNAME4 769 #undef LCALLNAME5 770 } 771 772 // 128-bit loads and stores can be done without expanding 773 setOperationAction(ISD::LOAD, MVT::i128, Custom); 774 setOperationAction(ISD::STORE, MVT::i128, Custom); 775 776 // 256 bit non-temporal stores can be lowered to STNP. Do this as part of the 777 // custom lowering, as there are no un-paired non-temporal stores and 778 // legalization will break up 256 bit inputs. 779 setOperationAction(ISD::STORE, MVT::v32i8, Custom); 780 setOperationAction(ISD::STORE, MVT::v16i16, Custom); 781 setOperationAction(ISD::STORE, MVT::v16f16, Custom); 782 setOperationAction(ISD::STORE, MVT::v8i32, Custom); 783 setOperationAction(ISD::STORE, MVT::v8f32, Custom); 784 setOperationAction(ISD::STORE, MVT::v4f64, Custom); 785 setOperationAction(ISD::STORE, MVT::v4i64, Custom); 786 787 // Lower READCYCLECOUNTER using an mrs from PMCCNTR_EL0. 788 // This requires the Performance Monitors extension. 789 if (Subtarget->hasPerfMon()) 790 setOperationAction(ISD::READCYCLECOUNTER, MVT::i64, Legal); 791 792 if (getLibcallName(RTLIB::SINCOS_STRET_F32) != nullptr && 793 getLibcallName(RTLIB::SINCOS_STRET_F64) != nullptr) { 794 // Issue __sincos_stret if available. 795 setOperationAction(ISD::FSINCOS, MVT::f64, Custom); 796 setOperationAction(ISD::FSINCOS, MVT::f32, Custom); 797 } else { 798 setOperationAction(ISD::FSINCOS, MVT::f64, Expand); 799 setOperationAction(ISD::FSINCOS, MVT::f32, Expand); 800 } 801 802 if (Subtarget->getTargetTriple().isOSMSVCRT()) { 803 // MSVCRT doesn't have powi; fall back to pow 804 setLibcallName(RTLIB::POWI_F32, nullptr); 805 setLibcallName(RTLIB::POWI_F64, nullptr); 806 } 807 808 // Make floating-point constants legal for the large code model, so they don't 809 // become loads from the constant pool. 810 if (Subtarget->isTargetMachO() && TM.getCodeModel() == CodeModel::Large) { 811 setOperationAction(ISD::ConstantFP, MVT::f32, Legal); 812 setOperationAction(ISD::ConstantFP, MVT::f64, Legal); 813 } 814 815 // AArch64 does not have floating-point extending loads, i1 sign-extending 816 // load, floating-point truncating stores, or v2i32->v2i16 truncating store. 817 for (MVT VT : MVT::fp_valuetypes()) { 818 setLoadExtAction(ISD::EXTLOAD, VT, MVT::f16, Expand); 819 setLoadExtAction(ISD::EXTLOAD, VT, MVT::f32, Expand); 820 setLoadExtAction(ISD::EXTLOAD, VT, MVT::f64, Expand); 821 setLoadExtAction(ISD::EXTLOAD, VT, MVT::f80, Expand); 822 } 823 for (MVT VT : MVT::integer_valuetypes()) 824 setLoadExtAction(ISD::SEXTLOAD, VT, MVT::i1, Expand); 825 826 setTruncStoreAction(MVT::f32, MVT::f16, Expand); 827 setTruncStoreAction(MVT::f64, MVT::f32, Expand); 828 setTruncStoreAction(MVT::f64, MVT::f16, Expand); 829 setTruncStoreAction(MVT::f128, MVT::f80, Expand); 830 setTruncStoreAction(MVT::f128, MVT::f64, Expand); 831 setTruncStoreAction(MVT::f128, MVT::f32, Expand); 832 setTruncStoreAction(MVT::f128, MVT::f16, Expand); 833 834 setOperationAction(ISD::BITCAST, MVT::i16, Custom); 835 setOperationAction(ISD::BITCAST, MVT::f16, Custom); 836 setOperationAction(ISD::BITCAST, MVT::bf16, Custom); 837 838 // Indexed loads and stores are supported. 839 for (unsigned im = (unsigned)ISD::PRE_INC; 840 im != (unsigned)ISD::LAST_INDEXED_MODE; ++im) { 841 setIndexedLoadAction(im, MVT::i8, Legal); 842 setIndexedLoadAction(im, MVT::i16, Legal); 843 setIndexedLoadAction(im, MVT::i32, Legal); 844 setIndexedLoadAction(im, MVT::i64, Legal); 845 setIndexedLoadAction(im, MVT::f64, Legal); 846 setIndexedLoadAction(im, MVT::f32, Legal); 847 setIndexedLoadAction(im, MVT::f16, Legal); 848 setIndexedLoadAction(im, MVT::bf16, Legal); 849 setIndexedStoreAction(im, MVT::i8, Legal); 850 setIndexedStoreAction(im, MVT::i16, Legal); 851 setIndexedStoreAction(im, MVT::i32, Legal); 852 setIndexedStoreAction(im, MVT::i64, Legal); 853 setIndexedStoreAction(im, MVT::f64, Legal); 854 setIndexedStoreAction(im, MVT::f32, Legal); 855 setIndexedStoreAction(im, MVT::f16, Legal); 856 setIndexedStoreAction(im, MVT::bf16, Legal); 857 } 858 859 // Trap. 860 setOperationAction(ISD::TRAP, MVT::Other, Legal); 861 setOperationAction(ISD::DEBUGTRAP, MVT::Other, Legal); 862 setOperationAction(ISD::UBSANTRAP, MVT::Other, Legal); 863 864 // We combine OR nodes for bitfield operations. 865 setTargetDAGCombine(ISD::OR); 866 // Try to create BICs for vector ANDs. 867 setTargetDAGCombine(ISD::AND); 868 869 // Vector add and sub nodes may conceal a high-half opportunity. 870 // Also, try to fold ADD into CSINC/CSINV.. 871 setTargetDAGCombine(ISD::ADD); 872 setTargetDAGCombine(ISD::ABS); 873 setTargetDAGCombine(ISD::SUB); 874 setTargetDAGCombine(ISD::SRL); 875 setTargetDAGCombine(ISD::XOR); 876 setTargetDAGCombine(ISD::SINT_TO_FP); 877 setTargetDAGCombine(ISD::UINT_TO_FP); 878 879 setTargetDAGCombine(ISD::FP_TO_SINT); 880 setTargetDAGCombine(ISD::FP_TO_UINT); 881 setTargetDAGCombine(ISD::FDIV); 882 883 setTargetDAGCombine(ISD::INTRINSIC_WO_CHAIN); 884 885 setTargetDAGCombine(ISD::ANY_EXTEND); 886 setTargetDAGCombine(ISD::ZERO_EXTEND); 887 setTargetDAGCombine(ISD::SIGN_EXTEND); 888 setTargetDAGCombine(ISD::SIGN_EXTEND_INREG); 889 setTargetDAGCombine(ISD::TRUNCATE); 890 setTargetDAGCombine(ISD::CONCAT_VECTORS); 891 setTargetDAGCombine(ISD::STORE); 892 if (Subtarget->supportsAddressTopByteIgnored()) 893 setTargetDAGCombine(ISD::LOAD); 894 895 setTargetDAGCombine(ISD::MUL); 896 897 setTargetDAGCombine(ISD::SELECT); 898 setTargetDAGCombine(ISD::VSELECT); 899 900 setTargetDAGCombine(ISD::INTRINSIC_VOID); 901 setTargetDAGCombine(ISD::INTRINSIC_W_CHAIN); 902 setTargetDAGCombine(ISD::INSERT_VECTOR_ELT); 903 setTargetDAGCombine(ISD::EXTRACT_VECTOR_ELT); 904 setTargetDAGCombine(ISD::VECREDUCE_ADD); 905 906 setTargetDAGCombine(ISD::GlobalAddress); 907 908 // In case of strict alignment, avoid an excessive number of byte wide stores. 909 MaxStoresPerMemsetOptSize = 8; 910 MaxStoresPerMemset = Subtarget->requiresStrictAlign() 911 ? MaxStoresPerMemsetOptSize : 32; 912 913 MaxGluedStoresPerMemcpy = 4; 914 MaxStoresPerMemcpyOptSize = 4; 915 MaxStoresPerMemcpy = Subtarget->requiresStrictAlign() 916 ? MaxStoresPerMemcpyOptSize : 16; 917 918 MaxStoresPerMemmoveOptSize = MaxStoresPerMemmove = 4; 919 920 MaxLoadsPerMemcmpOptSize = 4; 921 MaxLoadsPerMemcmp = Subtarget->requiresStrictAlign() 922 ? MaxLoadsPerMemcmpOptSize : 8; 923 924 setStackPointerRegisterToSaveRestore(AArch64::SP); 925 926 setSchedulingPreference(Sched::Hybrid); 927 928 EnableExtLdPromotion = true; 929 930 // Set required alignment. 931 setMinFunctionAlignment(Align(4)); 932 // Set preferred alignments. 933 setPrefLoopAlignment(Align(1ULL << STI.getPrefLoopLogAlignment())); 934 setPrefFunctionAlignment(Align(1ULL << STI.getPrefFunctionLogAlignment())); 935 936 // Only change the limit for entries in a jump table if specified by 937 // the sub target, but not at the command line. 938 unsigned MaxJT = STI.getMaximumJumpTableSize(); 939 if (MaxJT && getMaximumJumpTableSize() == UINT_MAX) 940 setMaximumJumpTableSize(MaxJT); 941 942 setHasExtractBitsInsn(true); 943 944 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom); 945 946 if (Subtarget->hasNEON()) { 947 // FIXME: v1f64 shouldn't be legal if we can avoid it, because it leads to 948 // silliness like this: 949 setOperationAction(ISD::FABS, MVT::v1f64, Expand); 950 setOperationAction(ISD::FADD, MVT::v1f64, Expand); 951 setOperationAction(ISD::FCEIL, MVT::v1f64, Expand); 952 setOperationAction(ISD::FCOPYSIGN, MVT::v1f64, Expand); 953 setOperationAction(ISD::FCOS, MVT::v1f64, Expand); 954 setOperationAction(ISD::FDIV, MVT::v1f64, Expand); 955 setOperationAction(ISD::FFLOOR, MVT::v1f64, Expand); 956 setOperationAction(ISD::FMA, MVT::v1f64, Expand); 957 setOperationAction(ISD::FMUL, MVT::v1f64, Expand); 958 setOperationAction(ISD::FNEARBYINT, MVT::v1f64, Expand); 959 setOperationAction(ISD::FNEG, MVT::v1f64, Expand); 960 setOperationAction(ISD::FPOW, MVT::v1f64, Expand); 961 setOperationAction(ISD::FREM, MVT::v1f64, Expand); 962 setOperationAction(ISD::FROUND, MVT::v1f64, Expand); 963 setOperationAction(ISD::FROUNDEVEN, MVT::v1f64, Expand); 964 setOperationAction(ISD::FRINT, MVT::v1f64, Expand); 965 setOperationAction(ISD::FSIN, MVT::v1f64, Expand); 966 setOperationAction(ISD::FSINCOS, MVT::v1f64, Expand); 967 setOperationAction(ISD::FSQRT, MVT::v1f64, Expand); 968 setOperationAction(ISD::FSUB, MVT::v1f64, Expand); 969 setOperationAction(ISD::FTRUNC, MVT::v1f64, Expand); 970 setOperationAction(ISD::SETCC, MVT::v1f64, Expand); 971 setOperationAction(ISD::BR_CC, MVT::v1f64, Expand); 972 setOperationAction(ISD::SELECT, MVT::v1f64, Expand); 973 setOperationAction(ISD::SELECT_CC, MVT::v1f64, Expand); 974 setOperationAction(ISD::FP_EXTEND, MVT::v1f64, Expand); 975 976 setOperationAction(ISD::FP_TO_SINT, MVT::v1i64, Expand); 977 setOperationAction(ISD::FP_TO_UINT, MVT::v1i64, Expand); 978 setOperationAction(ISD::SINT_TO_FP, MVT::v1i64, Expand); 979 setOperationAction(ISD::UINT_TO_FP, MVT::v1i64, Expand); 980 setOperationAction(ISD::FP_ROUND, MVT::v1f64, Expand); 981 982 setOperationAction(ISD::MUL, MVT::v1i64, Expand); 983 984 // AArch64 doesn't have a direct vector ->f32 conversion instructions for 985 // elements smaller than i32, so promote the input to i32 first. 986 setOperationPromotedToType(ISD::UINT_TO_FP, MVT::v4i8, MVT::v4i32); 987 setOperationPromotedToType(ISD::SINT_TO_FP, MVT::v4i8, MVT::v4i32); 988 // i8 vector elements also need promotion to i32 for v8i8 989 setOperationPromotedToType(ISD::SINT_TO_FP, MVT::v8i8, MVT::v8i32); 990 setOperationPromotedToType(ISD::UINT_TO_FP, MVT::v8i8, MVT::v8i32); 991 // Similarly, there is no direct i32 -> f64 vector conversion instruction. 992 setOperationAction(ISD::SINT_TO_FP, MVT::v2i32, Custom); 993 setOperationAction(ISD::UINT_TO_FP, MVT::v2i32, Custom); 994 setOperationAction(ISD::SINT_TO_FP, MVT::v2i64, Custom); 995 setOperationAction(ISD::UINT_TO_FP, MVT::v2i64, Custom); 996 // Or, direct i32 -> f16 vector conversion. Set it so custom, so the 997 // conversion happens in two steps: v4i32 -> v4f32 -> v4f16 998 setOperationAction(ISD::SINT_TO_FP, MVT::v4i32, Custom); 999 setOperationAction(ISD::UINT_TO_FP, MVT::v4i32, Custom); 1000 1001 if (Subtarget->hasFullFP16()) { 1002 setOperationAction(ISD::SINT_TO_FP, MVT::v4i16, Custom); 1003 setOperationAction(ISD::UINT_TO_FP, MVT::v4i16, Custom); 1004 setOperationAction(ISD::SINT_TO_FP, MVT::v8i16, Custom); 1005 setOperationAction(ISD::UINT_TO_FP, MVT::v8i16, Custom); 1006 } else { 1007 // when AArch64 doesn't have fullfp16 support, promote the input 1008 // to i32 first. 1009 setOperationPromotedToType(ISD::UINT_TO_FP, MVT::v4i16, MVT::v4i32); 1010 setOperationPromotedToType(ISD::SINT_TO_FP, MVT::v4i16, MVT::v4i32); 1011 setOperationPromotedToType(ISD::SINT_TO_FP, MVT::v8i16, MVT::v8i32); 1012 setOperationPromotedToType(ISD::UINT_TO_FP, MVT::v8i16, MVT::v8i32); 1013 } 1014 1015 setOperationAction(ISD::CTLZ, MVT::v1i64, Expand); 1016 setOperationAction(ISD::CTLZ, MVT::v2i64, Expand); 1017 1018 // AArch64 doesn't have MUL.2d: 1019 setOperationAction(ISD::MUL, MVT::v2i64, Expand); 1020 // Custom handling for some quad-vector types to detect MULL. 1021 setOperationAction(ISD::MUL, MVT::v8i16, Custom); 1022 setOperationAction(ISD::MUL, MVT::v4i32, Custom); 1023 setOperationAction(ISD::MUL, MVT::v2i64, Custom); 1024 1025 // Saturates 1026 for (MVT VT : { MVT::v8i8, MVT::v4i16, MVT::v2i32, 1027 MVT::v16i8, MVT::v8i16, MVT::v4i32, MVT::v2i64 }) { 1028 setOperationAction(ISD::SADDSAT, VT, Legal); 1029 setOperationAction(ISD::UADDSAT, VT, Legal); 1030 setOperationAction(ISD::SSUBSAT, VT, Legal); 1031 setOperationAction(ISD::USUBSAT, VT, Legal); 1032 } 1033 1034 // Vector reductions 1035 for (MVT VT : { MVT::v4f16, MVT::v2f32, 1036 MVT::v8f16, MVT::v4f32, MVT::v2f64 }) { 1037 if (VT.getVectorElementType() != MVT::f16 || Subtarget->hasFullFP16()) { 1038 setOperationAction(ISD::VECREDUCE_FMAX, VT, Custom); 1039 setOperationAction(ISD::VECREDUCE_FMIN, VT, Custom); 1040 1041 setOperationAction(ISD::VECREDUCE_FADD, VT, Legal); 1042 } 1043 } 1044 for (MVT VT : { MVT::v8i8, MVT::v4i16, MVT::v2i32, 1045 MVT::v16i8, MVT::v8i16, MVT::v4i32 }) { 1046 setOperationAction(ISD::VECREDUCE_ADD, VT, Custom); 1047 setOperationAction(ISD::VECREDUCE_SMAX, VT, Custom); 1048 setOperationAction(ISD::VECREDUCE_SMIN, VT, Custom); 1049 setOperationAction(ISD::VECREDUCE_UMAX, VT, Custom); 1050 setOperationAction(ISD::VECREDUCE_UMIN, VT, Custom); 1051 } 1052 setOperationAction(ISD::VECREDUCE_ADD, MVT::v2i64, Custom); 1053 1054 setOperationAction(ISD::ANY_EXTEND, MVT::v4i32, Legal); 1055 setTruncStoreAction(MVT::v2i32, MVT::v2i16, Expand); 1056 // Likewise, narrowing and extending vector loads/stores aren't handled 1057 // directly. 1058 for (MVT VT : MVT::fixedlen_vector_valuetypes()) { 1059 setOperationAction(ISD::SIGN_EXTEND_INREG, VT, Expand); 1060 1061 if (VT == MVT::v16i8 || VT == MVT::v8i16 || VT == MVT::v4i32) { 1062 setOperationAction(ISD::MULHS, VT, Legal); 1063 setOperationAction(ISD::MULHU, VT, Legal); 1064 } else { 1065 setOperationAction(ISD::MULHS, VT, Expand); 1066 setOperationAction(ISD::MULHU, VT, Expand); 1067 } 1068 setOperationAction(ISD::SMUL_LOHI, VT, Expand); 1069 setOperationAction(ISD::UMUL_LOHI, VT, Expand); 1070 1071 setOperationAction(ISD::BSWAP, VT, Expand); 1072 setOperationAction(ISD::CTTZ, VT, Expand); 1073 1074 for (MVT InnerVT : MVT::fixedlen_vector_valuetypes()) { 1075 setTruncStoreAction(VT, InnerVT, Expand); 1076 setLoadExtAction(ISD::SEXTLOAD, VT, InnerVT, Expand); 1077 setLoadExtAction(ISD::ZEXTLOAD, VT, InnerVT, Expand); 1078 setLoadExtAction(ISD::EXTLOAD, VT, InnerVT, Expand); 1079 } 1080 } 1081 1082 // AArch64 has implementations of a lot of rounding-like FP operations. 1083 for (MVT Ty : {MVT::v2f32, MVT::v4f32, MVT::v2f64}) { 1084 setOperationAction(ISD::FFLOOR, Ty, Legal); 1085 setOperationAction(ISD::FNEARBYINT, Ty, Legal); 1086 setOperationAction(ISD::FCEIL, Ty, Legal); 1087 setOperationAction(ISD::FRINT, Ty, Legal); 1088 setOperationAction(ISD::FTRUNC, Ty, Legal); 1089 setOperationAction(ISD::FROUND, Ty, Legal); 1090 setOperationAction(ISD::FROUNDEVEN, Ty, Legal); 1091 } 1092 1093 if (Subtarget->hasFullFP16()) { 1094 for (MVT Ty : {MVT::v4f16, MVT::v8f16}) { 1095 setOperationAction(ISD::FFLOOR, Ty, Legal); 1096 setOperationAction(ISD::FNEARBYINT, Ty, Legal); 1097 setOperationAction(ISD::FCEIL, Ty, Legal); 1098 setOperationAction(ISD::FRINT, Ty, Legal); 1099 setOperationAction(ISD::FTRUNC, Ty, Legal); 1100 setOperationAction(ISD::FROUND, Ty, Legal); 1101 setOperationAction(ISD::FROUNDEVEN, Ty, Legal); 1102 } 1103 } 1104 1105 if (Subtarget->hasSVE()) 1106 setOperationAction(ISD::VSCALE, MVT::i32, Custom); 1107 1108 setTruncStoreAction(MVT::v4i16, MVT::v4i8, Custom); 1109 } 1110 1111 if (Subtarget->hasSVE()) { 1112 // FIXME: Add custom lowering of MLOAD to handle different passthrus (not a 1113 // splat of 0 or undef) once vector selects supported in SVE codegen. See 1114 // D68877 for more details. 1115 for (auto VT : {MVT::nxv16i8, MVT::nxv8i16, MVT::nxv4i32, MVT::nxv2i64}) { 1116 setOperationAction(ISD::BITREVERSE, VT, Custom); 1117 setOperationAction(ISD::BSWAP, VT, Custom); 1118 setOperationAction(ISD::CTLZ, VT, Custom); 1119 setOperationAction(ISD::CTPOP, VT, Custom); 1120 setOperationAction(ISD::CTTZ, VT, Custom); 1121 setOperationAction(ISD::INSERT_SUBVECTOR, VT, Custom); 1122 setOperationAction(ISD::UINT_TO_FP, VT, Custom); 1123 setOperationAction(ISD::SINT_TO_FP, VT, Custom); 1124 setOperationAction(ISD::FP_TO_UINT, VT, Custom); 1125 setOperationAction(ISD::FP_TO_SINT, VT, Custom); 1126 setOperationAction(ISD::MGATHER, VT, Custom); 1127 setOperationAction(ISD::MSCATTER, VT, Custom); 1128 setOperationAction(ISD::MUL, VT, Custom); 1129 setOperationAction(ISD::SPLAT_VECTOR, VT, Custom); 1130 setOperationAction(ISD::SELECT, VT, Custom); 1131 setOperationAction(ISD::SETCC, VT, Custom); 1132 setOperationAction(ISD::SDIV, VT, Custom); 1133 setOperationAction(ISD::UDIV, VT, Custom); 1134 setOperationAction(ISD::SMIN, VT, Custom); 1135 setOperationAction(ISD::UMIN, VT, Custom); 1136 setOperationAction(ISD::SMAX, VT, Custom); 1137 setOperationAction(ISD::UMAX, VT, Custom); 1138 setOperationAction(ISD::SHL, VT, Custom); 1139 setOperationAction(ISD::SRL, VT, Custom); 1140 setOperationAction(ISD::SRA, VT, Custom); 1141 setOperationAction(ISD::ABS, VT, Custom); 1142 setOperationAction(ISD::VECREDUCE_ADD, VT, Custom); 1143 setOperationAction(ISD::VECREDUCE_AND, VT, Custom); 1144 setOperationAction(ISD::VECREDUCE_OR, VT, Custom); 1145 setOperationAction(ISD::VECREDUCE_XOR, VT, Custom); 1146 setOperationAction(ISD::VECREDUCE_UMIN, VT, Custom); 1147 setOperationAction(ISD::VECREDUCE_UMAX, VT, Custom); 1148 setOperationAction(ISD::VECREDUCE_SMIN, VT, Custom); 1149 setOperationAction(ISD::VECREDUCE_SMAX, VT, Custom); 1150 setOperationAction(ISD::STEP_VECTOR, VT, Custom); 1151 1152 setOperationAction(ISD::MULHU, VT, Expand); 1153 setOperationAction(ISD::MULHS, VT, Expand); 1154 setOperationAction(ISD::UMUL_LOHI, VT, Expand); 1155 setOperationAction(ISD::SMUL_LOHI, VT, Expand); 1156 } 1157 1158 // Illegal unpacked integer vector types. 1159 for (auto VT : {MVT::nxv8i8, MVT::nxv4i16, MVT::nxv2i32}) { 1160 setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Custom); 1161 setOperationAction(ISD::INSERT_SUBVECTOR, VT, Custom); 1162 } 1163 1164 for (auto VT : {MVT::nxv16i1, MVT::nxv8i1, MVT::nxv4i1, MVT::nxv2i1}) { 1165 setOperationAction(ISD::CONCAT_VECTORS, VT, Custom); 1166 setOperationAction(ISD::SELECT, VT, Custom); 1167 setOperationAction(ISD::SETCC, VT, Custom); 1168 setOperationAction(ISD::SPLAT_VECTOR, VT, Custom); 1169 setOperationAction(ISD::TRUNCATE, VT, Custom); 1170 setOperationAction(ISD::VECREDUCE_AND, VT, Custom); 1171 setOperationAction(ISD::VECREDUCE_OR, VT, Custom); 1172 setOperationAction(ISD::VECREDUCE_XOR, VT, Custom); 1173 1174 // There are no legal MVT::nxv16f## based types. 1175 if (VT != MVT::nxv16i1) { 1176 setOperationAction(ISD::SINT_TO_FP, VT, Custom); 1177 setOperationAction(ISD::UINT_TO_FP, VT, Custom); 1178 } 1179 } 1180 1181 for (auto VT : {MVT::nxv2f16, MVT::nxv4f16, MVT::nxv8f16, MVT::nxv2f32, 1182 MVT::nxv4f32, MVT::nxv2f64}) { 1183 for (auto InnerVT : {MVT::nxv2f16, MVT::nxv4f16, MVT::nxv8f16, 1184 MVT::nxv2f32, MVT::nxv4f32, MVT::nxv2f64}) { 1185 // Avoid marking truncating FP stores as legal to prevent the 1186 // DAGCombiner from creating unsupported truncating stores. 1187 setTruncStoreAction(VT, InnerVT, Expand); 1188 } 1189 1190 setOperationAction(ISD::CONCAT_VECTORS, VT, Custom); 1191 setOperationAction(ISD::INSERT_SUBVECTOR, VT, Custom); 1192 setOperationAction(ISD::MGATHER, VT, Custom); 1193 setOperationAction(ISD::MSCATTER, VT, Custom); 1194 setOperationAction(ISD::SPLAT_VECTOR, VT, Custom); 1195 setOperationAction(ISD::SELECT, VT, Custom); 1196 setOperationAction(ISD::FADD, VT, Custom); 1197 setOperationAction(ISD::FDIV, VT, Custom); 1198 setOperationAction(ISD::FMA, VT, Custom); 1199 setOperationAction(ISD::FMAXIMUM, VT, Custom); 1200 setOperationAction(ISD::FMAXNUM, VT, Custom); 1201 setOperationAction(ISD::FMINIMUM, VT, Custom); 1202 setOperationAction(ISD::FMINNUM, VT, Custom); 1203 setOperationAction(ISD::FMUL, VT, Custom); 1204 setOperationAction(ISD::FNEG, VT, Custom); 1205 setOperationAction(ISD::FSUB, VT, Custom); 1206 setOperationAction(ISD::FCEIL, VT, Custom); 1207 setOperationAction(ISD::FFLOOR, VT, Custom); 1208 setOperationAction(ISD::FNEARBYINT, VT, Custom); 1209 setOperationAction(ISD::FRINT, VT, Custom); 1210 setOperationAction(ISD::FROUND, VT, Custom); 1211 setOperationAction(ISD::FROUNDEVEN, VT, Custom); 1212 setOperationAction(ISD::FTRUNC, VT, Custom); 1213 setOperationAction(ISD::FSQRT, VT, Custom); 1214 setOperationAction(ISD::FABS, VT, Custom); 1215 setOperationAction(ISD::FP_EXTEND, VT, Custom); 1216 setOperationAction(ISD::FP_ROUND, VT, Custom); 1217 setOperationAction(ISD::VECREDUCE_FADD, VT, Custom); 1218 setOperationAction(ISD::VECREDUCE_FMAX, VT, Custom); 1219 setOperationAction(ISD::VECREDUCE_FMIN, VT, Custom); 1220 setOperationAction(ISD::VECREDUCE_SEQ_FADD, VT, Custom); 1221 } 1222 1223 for (auto VT : {MVT::nxv2bf16, MVT::nxv4bf16, MVT::nxv8bf16}) { 1224 setOperationAction(ISD::CONCAT_VECTORS, VT, Custom); 1225 setOperationAction(ISD::MGATHER, VT, Custom); 1226 setOperationAction(ISD::MSCATTER, VT, Custom); 1227 } 1228 1229 setOperationAction(ISD::SPLAT_VECTOR, MVT::nxv8bf16, Custom); 1230 1231 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::i8, Custom); 1232 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::i16, Custom); 1233 1234 // NOTE: Currently this has to happen after computeRegisterProperties rather 1235 // than the preferred option of combining it with the addRegisterClass call. 1236 if (Subtarget->useSVEForFixedLengthVectors()) { 1237 for (MVT VT : MVT::integer_fixedlen_vector_valuetypes()) 1238 if (useSVEForFixedLengthVectorVT(VT)) 1239 addTypeForFixedLengthSVE(VT); 1240 for (MVT VT : MVT::fp_fixedlen_vector_valuetypes()) 1241 if (useSVEForFixedLengthVectorVT(VT)) 1242 addTypeForFixedLengthSVE(VT); 1243 1244 // 64bit results can mean a bigger than NEON input. 1245 for (auto VT : {MVT::v8i8, MVT::v4i16}) 1246 setOperationAction(ISD::TRUNCATE, VT, Custom); 1247 setOperationAction(ISD::FP_ROUND, MVT::v4f16, Custom); 1248 1249 // 128bit results imply a bigger than NEON input. 1250 for (auto VT : {MVT::v16i8, MVT::v8i16, MVT::v4i32}) 1251 setOperationAction(ISD::TRUNCATE, VT, Custom); 1252 for (auto VT : {MVT::v8f16, MVT::v4f32}) 1253 setOperationAction(ISD::FP_ROUND, VT, Expand); 1254 1255 // These operations are not supported on NEON but SVE can do them. 1256 setOperationAction(ISD::BITREVERSE, MVT::v1i64, Custom); 1257 setOperationAction(ISD::CTLZ, MVT::v1i64, Custom); 1258 setOperationAction(ISD::CTLZ, MVT::v2i64, Custom); 1259 setOperationAction(ISD::CTTZ, MVT::v1i64, Custom); 1260 setOperationAction(ISD::MUL, MVT::v1i64, Custom); 1261 setOperationAction(ISD::MUL, MVT::v2i64, Custom); 1262 setOperationAction(ISD::SDIV, MVT::v8i8, Custom); 1263 setOperationAction(ISD::SDIV, MVT::v16i8, Custom); 1264 setOperationAction(ISD::SDIV, MVT::v4i16, Custom); 1265 setOperationAction(ISD::SDIV, MVT::v8i16, Custom); 1266 setOperationAction(ISD::SDIV, MVT::v2i32, Custom); 1267 setOperationAction(ISD::SDIV, MVT::v4i32, Custom); 1268 setOperationAction(ISD::SDIV, MVT::v1i64, Custom); 1269 setOperationAction(ISD::SDIV, MVT::v2i64, Custom); 1270 setOperationAction(ISD::SMAX, MVT::v1i64, Custom); 1271 setOperationAction(ISD::SMAX, MVT::v2i64, Custom); 1272 setOperationAction(ISD::SMIN, MVT::v1i64, Custom); 1273 setOperationAction(ISD::SMIN, MVT::v2i64, Custom); 1274 setOperationAction(ISD::UDIV, MVT::v8i8, Custom); 1275 setOperationAction(ISD::UDIV, MVT::v16i8, Custom); 1276 setOperationAction(ISD::UDIV, MVT::v4i16, Custom); 1277 setOperationAction(ISD::UDIV, MVT::v8i16, Custom); 1278 setOperationAction(ISD::UDIV, MVT::v2i32, Custom); 1279 setOperationAction(ISD::UDIV, MVT::v4i32, Custom); 1280 setOperationAction(ISD::UDIV, MVT::v1i64, Custom); 1281 setOperationAction(ISD::UDIV, MVT::v2i64, Custom); 1282 setOperationAction(ISD::UMAX, MVT::v1i64, Custom); 1283 setOperationAction(ISD::UMAX, MVT::v2i64, Custom); 1284 setOperationAction(ISD::UMIN, MVT::v1i64, Custom); 1285 setOperationAction(ISD::UMIN, MVT::v2i64, Custom); 1286 setOperationAction(ISD::VECREDUCE_SMAX, MVT::v2i64, Custom); 1287 setOperationAction(ISD::VECREDUCE_SMIN, MVT::v2i64, Custom); 1288 setOperationAction(ISD::VECREDUCE_UMAX, MVT::v2i64, Custom); 1289 setOperationAction(ISD::VECREDUCE_UMIN, MVT::v2i64, Custom); 1290 1291 // Int operations with no NEON support. 1292 for (auto VT : {MVT::v8i8, MVT::v16i8, MVT::v4i16, MVT::v8i16, 1293 MVT::v2i32, MVT::v4i32, MVT::v2i64}) { 1294 setOperationAction(ISD::BITREVERSE, VT, Custom); 1295 setOperationAction(ISD::CTTZ, VT, Custom); 1296 setOperationAction(ISD::VECREDUCE_AND, VT, Custom); 1297 setOperationAction(ISD::VECREDUCE_OR, VT, Custom); 1298 setOperationAction(ISD::VECREDUCE_XOR, VT, Custom); 1299 } 1300 1301 // FP operations with no NEON support. 1302 for (auto VT : {MVT::v4f16, MVT::v8f16, MVT::v2f32, MVT::v4f32, 1303 MVT::v1f64, MVT::v2f64}) 1304 setOperationAction(ISD::VECREDUCE_SEQ_FADD, VT, Custom); 1305 1306 // Use SVE for vectors with more than 2 elements. 1307 for (auto VT : {MVT::v4f16, MVT::v8f16, MVT::v4f32}) 1308 setOperationAction(ISD::VECREDUCE_FADD, VT, Custom); 1309 } 1310 1311 setOperationPromotedToType(ISD::VECTOR_SPLICE, MVT::nxv2i1, MVT::nxv2i64); 1312 setOperationPromotedToType(ISD::VECTOR_SPLICE, MVT::nxv4i1, MVT::nxv4i32); 1313 setOperationPromotedToType(ISD::VECTOR_SPLICE, MVT::nxv8i1, MVT::nxv8i16); 1314 setOperationPromotedToType(ISD::VECTOR_SPLICE, MVT::nxv16i1, MVT::nxv16i8); 1315 } 1316 1317 PredictableSelectIsExpensive = Subtarget->predictableSelectIsExpensive(); 1318 } 1319 1320 void AArch64TargetLowering::addTypeForNEON(MVT VT, MVT PromotedBitwiseVT) { 1321 assert(VT.isVector() && "VT should be a vector type"); 1322 1323 if (VT.isFloatingPoint()) { 1324 MVT PromoteTo = EVT(VT).changeVectorElementTypeToInteger().getSimpleVT(); 1325 setOperationPromotedToType(ISD::LOAD, VT, PromoteTo); 1326 setOperationPromotedToType(ISD::STORE, VT, PromoteTo); 1327 } 1328 1329 // Mark vector float intrinsics as expand. 1330 if (VT == MVT::v2f32 || VT == MVT::v4f32 || VT == MVT::v2f64) { 1331 setOperationAction(ISD::FSIN, VT, Expand); 1332 setOperationAction(ISD::FCOS, VT, Expand); 1333 setOperationAction(ISD::FPOW, VT, Expand); 1334 setOperationAction(ISD::FLOG, VT, Expand); 1335 setOperationAction(ISD::FLOG2, VT, Expand); 1336 setOperationAction(ISD::FLOG10, VT, Expand); 1337 setOperationAction(ISD::FEXP, VT, Expand); 1338 setOperationAction(ISD::FEXP2, VT, Expand); 1339 1340 // But we do support custom-lowering for FCOPYSIGN. 1341 setOperationAction(ISD::FCOPYSIGN, VT, Custom); 1342 } 1343 1344 setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom); 1345 setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Custom); 1346 setOperationAction(ISD::BUILD_VECTOR, VT, Custom); 1347 setOperationAction(ISD::VECTOR_SHUFFLE, VT, Custom); 1348 setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Custom); 1349 setOperationAction(ISD::SRA, VT, Custom); 1350 setOperationAction(ISD::SRL, VT, Custom); 1351 setOperationAction(ISD::SHL, VT, Custom); 1352 setOperationAction(ISD::OR, VT, Custom); 1353 setOperationAction(ISD::SETCC, VT, Custom); 1354 setOperationAction(ISD::CONCAT_VECTORS, VT, Legal); 1355 1356 setOperationAction(ISD::SELECT, VT, Expand); 1357 setOperationAction(ISD::SELECT_CC, VT, Expand); 1358 setOperationAction(ISD::VSELECT, VT, Expand); 1359 for (MVT InnerVT : MVT::all_valuetypes()) 1360 setLoadExtAction(ISD::EXTLOAD, InnerVT, VT, Expand); 1361 1362 // CNT supports only B element sizes, then use UADDLP to widen. 1363 if (VT != MVT::v8i8 && VT != MVT::v16i8) 1364 setOperationAction(ISD::CTPOP, VT, Custom); 1365 1366 setOperationAction(ISD::UDIV, VT, Expand); 1367 setOperationAction(ISD::SDIV, VT, Expand); 1368 setOperationAction(ISD::UREM, VT, Expand); 1369 setOperationAction(ISD::SREM, VT, Expand); 1370 setOperationAction(ISD::FREM, VT, Expand); 1371 1372 setOperationAction(ISD::FP_TO_SINT, VT, Custom); 1373 setOperationAction(ISD::FP_TO_UINT, VT, Custom); 1374 1375 if (!VT.isFloatingPoint()) 1376 setOperationAction(ISD::ABS, VT, Legal); 1377 1378 // [SU][MIN|MAX] are available for all NEON types apart from i64. 1379 if (!VT.isFloatingPoint() && VT != MVT::v2i64 && VT != MVT::v1i64) 1380 for (unsigned Opcode : {ISD::SMIN, ISD::SMAX, ISD::UMIN, ISD::UMAX}) 1381 setOperationAction(Opcode, VT, Legal); 1382 1383 // F[MIN|MAX][NUM|NAN] are available for all FP NEON types. 1384 if (VT.isFloatingPoint() && 1385 VT.getVectorElementType() != MVT::bf16 && 1386 (VT.getVectorElementType() != MVT::f16 || Subtarget->hasFullFP16())) 1387 for (unsigned Opcode : 1388 {ISD::FMINIMUM, ISD::FMAXIMUM, ISD::FMINNUM, ISD::FMAXNUM}) 1389 setOperationAction(Opcode, VT, Legal); 1390 1391 if (Subtarget->isLittleEndian()) { 1392 for (unsigned im = (unsigned)ISD::PRE_INC; 1393 im != (unsigned)ISD::LAST_INDEXED_MODE; ++im) { 1394 setIndexedLoadAction(im, VT, Legal); 1395 setIndexedStoreAction(im, VT, Legal); 1396 } 1397 } 1398 } 1399 1400 void AArch64TargetLowering::addTypeForFixedLengthSVE(MVT VT) { 1401 assert(VT.isFixedLengthVector() && "Expected fixed length vector type!"); 1402 1403 // By default everything must be expanded. 1404 for (unsigned Op = 0; Op < ISD::BUILTIN_OP_END; ++Op) 1405 setOperationAction(Op, VT, Expand); 1406 1407 // We use EXTRACT_SUBVECTOR to "cast" a scalable vector to a fixed length one. 1408 setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Custom); 1409 1410 if (VT.isFloatingPoint()) { 1411 setCondCodeAction(ISD::SETO, VT, Expand); 1412 setCondCodeAction(ISD::SETOLT, VT, Expand); 1413 setCondCodeAction(ISD::SETLT, VT, Expand); 1414 setCondCodeAction(ISD::SETOLE, VT, Expand); 1415 setCondCodeAction(ISD::SETLE, VT, Expand); 1416 setCondCodeAction(ISD::SETULT, VT, Expand); 1417 setCondCodeAction(ISD::SETULE, VT, Expand); 1418 setCondCodeAction(ISD::SETUGE, VT, Expand); 1419 setCondCodeAction(ISD::SETUGT, VT, Expand); 1420 setCondCodeAction(ISD::SETUEQ, VT, Expand); 1421 setCondCodeAction(ISD::SETUNE, VT, Expand); 1422 } 1423 1424 // Lower fixed length vector operations to scalable equivalents. 1425 setOperationAction(ISD::ABS, VT, Custom); 1426 setOperationAction(ISD::ADD, VT, Custom); 1427 setOperationAction(ISD::AND, VT, Custom); 1428 setOperationAction(ISD::ANY_EXTEND, VT, Custom); 1429 setOperationAction(ISD::BITREVERSE, VT, Custom); 1430 setOperationAction(ISD::BSWAP, VT, Custom); 1431 setOperationAction(ISD::CTLZ, VT, Custom); 1432 setOperationAction(ISD::CTPOP, VT, Custom); 1433 setOperationAction(ISD::CTTZ, VT, Custom); 1434 setOperationAction(ISD::FABS, VT, Custom); 1435 setOperationAction(ISD::FADD, VT, Custom); 1436 setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom); 1437 setOperationAction(ISD::FCEIL, VT, Custom); 1438 setOperationAction(ISD::FDIV, VT, Custom); 1439 setOperationAction(ISD::FFLOOR, VT, Custom); 1440 setOperationAction(ISD::FMA, VT, Custom); 1441 setOperationAction(ISD::FMAXIMUM, VT, Custom); 1442 setOperationAction(ISD::FMAXNUM, VT, Custom); 1443 setOperationAction(ISD::FMINIMUM, VT, Custom); 1444 setOperationAction(ISD::FMINNUM, VT, Custom); 1445 setOperationAction(ISD::FMUL, VT, Custom); 1446 setOperationAction(ISD::FNEARBYINT, VT, Custom); 1447 setOperationAction(ISD::FNEG, VT, Custom); 1448 setOperationAction(ISD::FRINT, VT, Custom); 1449 setOperationAction(ISD::FROUND, VT, Custom); 1450 setOperationAction(ISD::FROUNDEVEN, VT, Custom); 1451 setOperationAction(ISD::FSQRT, VT, Custom); 1452 setOperationAction(ISD::FSUB, VT, Custom); 1453 setOperationAction(ISD::FTRUNC, VT, Custom); 1454 setOperationAction(ISD::LOAD, VT, Custom); 1455 setOperationAction(ISD::MUL, VT, Custom); 1456 setOperationAction(ISD::OR, VT, Custom); 1457 setOperationAction(ISD::SDIV, VT, Custom); 1458 setOperationAction(ISD::SELECT, VT, Custom); 1459 setOperationAction(ISD::SETCC, VT, Custom); 1460 setOperationAction(ISD::SHL, VT, Custom); 1461 setOperationAction(ISD::SIGN_EXTEND, VT, Custom); 1462 setOperationAction(ISD::SIGN_EXTEND_INREG, VT, Custom); 1463 setOperationAction(ISD::SMAX, VT, Custom); 1464 setOperationAction(ISD::SMIN, VT, Custom); 1465 setOperationAction(ISD::SPLAT_VECTOR, VT, Custom); 1466 setOperationAction(ISD::SRA, VT, Custom); 1467 setOperationAction(ISD::SRL, VT, Custom); 1468 setOperationAction(ISD::STORE, VT, Custom); 1469 setOperationAction(ISD::SUB, VT, Custom); 1470 setOperationAction(ISD::TRUNCATE, VT, Custom); 1471 setOperationAction(ISD::UDIV, VT, Custom); 1472 setOperationAction(ISD::UMAX, VT, Custom); 1473 setOperationAction(ISD::UMIN, VT, Custom); 1474 setOperationAction(ISD::VECREDUCE_ADD, VT, Custom); 1475 setOperationAction(ISD::VECREDUCE_AND, VT, Custom); 1476 setOperationAction(ISD::VECREDUCE_FADD, VT, Custom); 1477 setOperationAction(ISD::VECREDUCE_SEQ_FADD, VT, Custom); 1478 setOperationAction(ISD::VECREDUCE_FMAX, VT, Custom); 1479 setOperationAction(ISD::VECREDUCE_FMIN, VT, Custom); 1480 setOperationAction(ISD::VECREDUCE_OR, VT, Custom); 1481 setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Custom); 1482 setOperationAction(ISD::VECREDUCE_SMAX, VT, Custom); 1483 setOperationAction(ISD::VECREDUCE_SMIN, VT, Custom); 1484 setOperationAction(ISD::VECREDUCE_UMAX, VT, Custom); 1485 setOperationAction(ISD::VECREDUCE_UMIN, VT, Custom); 1486 setOperationAction(ISD::VECREDUCE_XOR, VT, Custom); 1487 setOperationAction(ISD::VSELECT, VT, Custom); 1488 setOperationAction(ISD::XOR, VT, Custom); 1489 setOperationAction(ISD::ZERO_EXTEND, VT, Custom); 1490 } 1491 1492 void AArch64TargetLowering::addDRTypeForNEON(MVT VT) { 1493 addRegisterClass(VT, &AArch64::FPR64RegClass); 1494 addTypeForNEON(VT, MVT::v2i32); 1495 } 1496 1497 void AArch64TargetLowering::addQRTypeForNEON(MVT VT) { 1498 addRegisterClass(VT, &AArch64::FPR128RegClass); 1499 addTypeForNEON(VT, MVT::v4i32); 1500 } 1501 1502 EVT AArch64TargetLowering::getSetCCResultType(const DataLayout &, 1503 LLVMContext &C, EVT VT) const { 1504 if (!VT.isVector()) 1505 return MVT::i32; 1506 if (VT.isScalableVector()) 1507 return EVT::getVectorVT(C, MVT::i1, VT.getVectorElementCount()); 1508 return VT.changeVectorElementTypeToInteger(); 1509 } 1510 1511 static bool optimizeLogicalImm(SDValue Op, unsigned Size, uint64_t Imm, 1512 const APInt &Demanded, 1513 TargetLowering::TargetLoweringOpt &TLO, 1514 unsigned NewOpc) { 1515 uint64_t OldImm = Imm, NewImm, Enc; 1516 uint64_t Mask = ((uint64_t)(-1LL) >> (64 - Size)), OrigMask = Mask; 1517 1518 // Return if the immediate is already all zeros, all ones, a bimm32 or a 1519 // bimm64. 1520 if (Imm == 0 || Imm == Mask || 1521 AArch64_AM::isLogicalImmediate(Imm & Mask, Size)) 1522 return false; 1523 1524 unsigned EltSize = Size; 1525 uint64_t DemandedBits = Demanded.getZExtValue(); 1526 1527 // Clear bits that are not demanded. 1528 Imm &= DemandedBits; 1529 1530 while (true) { 1531 // The goal here is to set the non-demanded bits in a way that minimizes 1532 // the number of switching between 0 and 1. In order to achieve this goal, 1533 // we set the non-demanded bits to the value of the preceding demanded bits. 1534 // For example, if we have an immediate 0bx10xx0x1 ('x' indicates a 1535 // non-demanded bit), we copy bit0 (1) to the least significant 'x', 1536 // bit2 (0) to 'xx', and bit6 (1) to the most significant 'x'. 1537 // The final result is 0b11000011. 1538 uint64_t NonDemandedBits = ~DemandedBits; 1539 uint64_t InvertedImm = ~Imm & DemandedBits; 1540 uint64_t RotatedImm = 1541 ((InvertedImm << 1) | (InvertedImm >> (EltSize - 1) & 1)) & 1542 NonDemandedBits; 1543 uint64_t Sum = RotatedImm + NonDemandedBits; 1544 bool Carry = NonDemandedBits & ~Sum & (1ULL << (EltSize - 1)); 1545 uint64_t Ones = (Sum + Carry) & NonDemandedBits; 1546 NewImm = (Imm | Ones) & Mask; 1547 1548 // If NewImm or its bitwise NOT is a shifted mask, it is a bitmask immediate 1549 // or all-ones or all-zeros, in which case we can stop searching. Otherwise, 1550 // we halve the element size and continue the search. 1551 if (isShiftedMask_64(NewImm) || isShiftedMask_64(~(NewImm | ~Mask))) 1552 break; 1553 1554 // We cannot shrink the element size any further if it is 2-bits. 1555 if (EltSize == 2) 1556 return false; 1557 1558 EltSize /= 2; 1559 Mask >>= EltSize; 1560 uint64_t Hi = Imm >> EltSize, DemandedBitsHi = DemandedBits >> EltSize; 1561 1562 // Return if there is mismatch in any of the demanded bits of Imm and Hi. 1563 if (((Imm ^ Hi) & (DemandedBits & DemandedBitsHi) & Mask) != 0) 1564 return false; 1565 1566 // Merge the upper and lower halves of Imm and DemandedBits. 1567 Imm |= Hi; 1568 DemandedBits |= DemandedBitsHi; 1569 } 1570 1571 ++NumOptimizedImms; 1572 1573 // Replicate the element across the register width. 1574 while (EltSize < Size) { 1575 NewImm |= NewImm << EltSize; 1576 EltSize *= 2; 1577 } 1578 1579 (void)OldImm; 1580 assert(((OldImm ^ NewImm) & Demanded.getZExtValue()) == 0 && 1581 "demanded bits should never be altered"); 1582 assert(OldImm != NewImm && "the new imm shouldn't be equal to the old imm"); 1583 1584 // Create the new constant immediate node. 1585 EVT VT = Op.getValueType(); 1586 SDLoc DL(Op); 1587 SDValue New; 1588 1589 // If the new constant immediate is all-zeros or all-ones, let the target 1590 // independent DAG combine optimize this node. 1591 if (NewImm == 0 || NewImm == OrigMask) { 1592 New = TLO.DAG.getNode(Op.getOpcode(), DL, VT, Op.getOperand(0), 1593 TLO.DAG.getConstant(NewImm, DL, VT)); 1594 // Otherwise, create a machine node so that target independent DAG combine 1595 // doesn't undo this optimization. 1596 } else { 1597 Enc = AArch64_AM::encodeLogicalImmediate(NewImm, Size); 1598 SDValue EncConst = TLO.DAG.getTargetConstant(Enc, DL, VT); 1599 New = SDValue( 1600 TLO.DAG.getMachineNode(NewOpc, DL, VT, Op.getOperand(0), EncConst), 0); 1601 } 1602 1603 return TLO.CombineTo(Op, New); 1604 } 1605 1606 bool AArch64TargetLowering::targetShrinkDemandedConstant( 1607 SDValue Op, const APInt &DemandedBits, const APInt &DemandedElts, 1608 TargetLoweringOpt &TLO) const { 1609 // Delay this optimization to as late as possible. 1610 if (!TLO.LegalOps) 1611 return false; 1612 1613 if (!EnableOptimizeLogicalImm) 1614 return false; 1615 1616 EVT VT = Op.getValueType(); 1617 if (VT.isVector()) 1618 return false; 1619 1620 unsigned Size = VT.getSizeInBits(); 1621 assert((Size == 32 || Size == 64) && 1622 "i32 or i64 is expected after legalization."); 1623 1624 // Exit early if we demand all bits. 1625 if (DemandedBits.countPopulation() == Size) 1626 return false; 1627 1628 unsigned NewOpc; 1629 switch (Op.getOpcode()) { 1630 default: 1631 return false; 1632 case ISD::AND: 1633 NewOpc = Size == 32 ? AArch64::ANDWri : AArch64::ANDXri; 1634 break; 1635 case ISD::OR: 1636 NewOpc = Size == 32 ? AArch64::ORRWri : AArch64::ORRXri; 1637 break; 1638 case ISD::XOR: 1639 NewOpc = Size == 32 ? AArch64::EORWri : AArch64::EORXri; 1640 break; 1641 } 1642 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1)); 1643 if (!C) 1644 return false; 1645 uint64_t Imm = C->getZExtValue(); 1646 return optimizeLogicalImm(Op, Size, Imm, DemandedBits, TLO, NewOpc); 1647 } 1648 1649 /// computeKnownBitsForTargetNode - Determine which of the bits specified in 1650 /// Mask are known to be either zero or one and return them Known. 1651 void AArch64TargetLowering::computeKnownBitsForTargetNode( 1652 const SDValue Op, KnownBits &Known, 1653 const APInt &DemandedElts, const SelectionDAG &DAG, unsigned Depth) const { 1654 switch (Op.getOpcode()) { 1655 default: 1656 break; 1657 case AArch64ISD::CSEL: { 1658 KnownBits Known2; 1659 Known = DAG.computeKnownBits(Op->getOperand(0), Depth + 1); 1660 Known2 = DAG.computeKnownBits(Op->getOperand(1), Depth + 1); 1661 Known = KnownBits::commonBits(Known, Known2); 1662 break; 1663 } 1664 case AArch64ISD::LOADgot: 1665 case AArch64ISD::ADDlow: { 1666 if (!Subtarget->isTargetILP32()) 1667 break; 1668 // In ILP32 mode all valid pointers are in the low 4GB of the address-space. 1669 Known.Zero = APInt::getHighBitsSet(64, 32); 1670 break; 1671 } 1672 case ISD::INTRINSIC_W_CHAIN: { 1673 ConstantSDNode *CN = cast<ConstantSDNode>(Op->getOperand(1)); 1674 Intrinsic::ID IntID = static_cast<Intrinsic::ID>(CN->getZExtValue()); 1675 switch (IntID) { 1676 default: return; 1677 case Intrinsic::aarch64_ldaxr: 1678 case Intrinsic::aarch64_ldxr: { 1679 unsigned BitWidth = Known.getBitWidth(); 1680 EVT VT = cast<MemIntrinsicSDNode>(Op)->getMemoryVT(); 1681 unsigned MemBits = VT.getScalarSizeInBits(); 1682 Known.Zero |= APInt::getHighBitsSet(BitWidth, BitWidth - MemBits); 1683 return; 1684 } 1685 } 1686 break; 1687 } 1688 case ISD::INTRINSIC_WO_CHAIN: 1689 case ISD::INTRINSIC_VOID: { 1690 unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue(); 1691 switch (IntNo) { 1692 default: 1693 break; 1694 case Intrinsic::aarch64_neon_umaxv: 1695 case Intrinsic::aarch64_neon_uminv: { 1696 // Figure out the datatype of the vector operand. The UMINV instruction 1697 // will zero extend the result, so we can mark as known zero all the 1698 // bits larger than the element datatype. 32-bit or larget doesn't need 1699 // this as those are legal types and will be handled by isel directly. 1700 MVT VT = Op.getOperand(1).getValueType().getSimpleVT(); 1701 unsigned BitWidth = Known.getBitWidth(); 1702 if (VT == MVT::v8i8 || VT == MVT::v16i8) { 1703 assert(BitWidth >= 8 && "Unexpected width!"); 1704 APInt Mask = APInt::getHighBitsSet(BitWidth, BitWidth - 8); 1705 Known.Zero |= Mask; 1706 } else if (VT == MVT::v4i16 || VT == MVT::v8i16) { 1707 assert(BitWidth >= 16 && "Unexpected width!"); 1708 APInt Mask = APInt::getHighBitsSet(BitWidth, BitWidth - 16); 1709 Known.Zero |= Mask; 1710 } 1711 break; 1712 } break; 1713 } 1714 } 1715 } 1716 } 1717 1718 MVT AArch64TargetLowering::getScalarShiftAmountTy(const DataLayout &DL, 1719 EVT) const { 1720 return MVT::i64; 1721 } 1722 1723 bool AArch64TargetLowering::allowsMisalignedMemoryAccesses( 1724 EVT VT, unsigned AddrSpace, Align Alignment, MachineMemOperand::Flags Flags, 1725 bool *Fast) const { 1726 if (Subtarget->requiresStrictAlign()) 1727 return false; 1728 1729 if (Fast) { 1730 // Some CPUs are fine with unaligned stores except for 128-bit ones. 1731 *Fast = !Subtarget->isMisaligned128StoreSlow() || VT.getStoreSize() != 16 || 1732 // See comments in performSTORECombine() for more details about 1733 // these conditions. 1734 1735 // Code that uses clang vector extensions can mark that it 1736 // wants unaligned accesses to be treated as fast by 1737 // underspecifying alignment to be 1 or 2. 1738 Alignment <= 2 || 1739 1740 // Disregard v2i64. Memcpy lowering produces those and splitting 1741 // them regresses performance on micro-benchmarks and olden/bh. 1742 VT == MVT::v2i64; 1743 } 1744 return true; 1745 } 1746 1747 // Same as above but handling LLTs instead. 1748 bool AArch64TargetLowering::allowsMisalignedMemoryAccesses( 1749 LLT Ty, unsigned AddrSpace, Align Alignment, MachineMemOperand::Flags Flags, 1750 bool *Fast) const { 1751 if (Subtarget->requiresStrictAlign()) 1752 return false; 1753 1754 if (Fast) { 1755 // Some CPUs are fine with unaligned stores except for 128-bit ones. 1756 *Fast = !Subtarget->isMisaligned128StoreSlow() || 1757 Ty.getSizeInBytes() != 16 || 1758 // See comments in performSTORECombine() for more details about 1759 // these conditions. 1760 1761 // Code that uses clang vector extensions can mark that it 1762 // wants unaligned accesses to be treated as fast by 1763 // underspecifying alignment to be 1 or 2. 1764 Alignment <= 2 || 1765 1766 // Disregard v2i64. Memcpy lowering produces those and splitting 1767 // them regresses performance on micro-benchmarks and olden/bh. 1768 Ty == LLT::vector(2, 64); 1769 } 1770 return true; 1771 } 1772 1773 FastISel * 1774 AArch64TargetLowering::createFastISel(FunctionLoweringInfo &funcInfo, 1775 const TargetLibraryInfo *libInfo) const { 1776 return AArch64::createFastISel(funcInfo, libInfo); 1777 } 1778 1779 const char *AArch64TargetLowering::getTargetNodeName(unsigned Opcode) const { 1780 #define MAKE_CASE(V) \ 1781 case V: \ 1782 return #V; 1783 switch ((AArch64ISD::NodeType)Opcode) { 1784 case AArch64ISD::FIRST_NUMBER: 1785 break; 1786 MAKE_CASE(AArch64ISD::CALL) 1787 MAKE_CASE(AArch64ISD::ADRP) 1788 MAKE_CASE(AArch64ISD::ADR) 1789 MAKE_CASE(AArch64ISD::ADDlow) 1790 MAKE_CASE(AArch64ISD::LOADgot) 1791 MAKE_CASE(AArch64ISD::RET_FLAG) 1792 MAKE_CASE(AArch64ISD::BRCOND) 1793 MAKE_CASE(AArch64ISD::CSEL) 1794 MAKE_CASE(AArch64ISD::FCSEL) 1795 MAKE_CASE(AArch64ISD::CSINV) 1796 MAKE_CASE(AArch64ISD::CSNEG) 1797 MAKE_CASE(AArch64ISD::CSINC) 1798 MAKE_CASE(AArch64ISD::THREAD_POINTER) 1799 MAKE_CASE(AArch64ISD::TLSDESC_CALLSEQ) 1800 MAKE_CASE(AArch64ISD::ADD_PRED) 1801 MAKE_CASE(AArch64ISD::MUL_PRED) 1802 MAKE_CASE(AArch64ISD::SDIV_PRED) 1803 MAKE_CASE(AArch64ISD::SHL_PRED) 1804 MAKE_CASE(AArch64ISD::SMAX_PRED) 1805 MAKE_CASE(AArch64ISD::SMIN_PRED) 1806 MAKE_CASE(AArch64ISD::SRA_PRED) 1807 MAKE_CASE(AArch64ISD::SRL_PRED) 1808 MAKE_CASE(AArch64ISD::SUB_PRED) 1809 MAKE_CASE(AArch64ISD::UDIV_PRED) 1810 MAKE_CASE(AArch64ISD::UMAX_PRED) 1811 MAKE_CASE(AArch64ISD::UMIN_PRED) 1812 MAKE_CASE(AArch64ISD::FNEG_MERGE_PASSTHRU) 1813 MAKE_CASE(AArch64ISD::SIGN_EXTEND_INREG_MERGE_PASSTHRU) 1814 MAKE_CASE(AArch64ISD::ZERO_EXTEND_INREG_MERGE_PASSTHRU) 1815 MAKE_CASE(AArch64ISD::FCEIL_MERGE_PASSTHRU) 1816 MAKE_CASE(AArch64ISD::FFLOOR_MERGE_PASSTHRU) 1817 MAKE_CASE(AArch64ISD::FNEARBYINT_MERGE_PASSTHRU) 1818 MAKE_CASE(AArch64ISD::FRINT_MERGE_PASSTHRU) 1819 MAKE_CASE(AArch64ISD::FROUND_MERGE_PASSTHRU) 1820 MAKE_CASE(AArch64ISD::FROUNDEVEN_MERGE_PASSTHRU) 1821 MAKE_CASE(AArch64ISD::FTRUNC_MERGE_PASSTHRU) 1822 MAKE_CASE(AArch64ISD::FP_ROUND_MERGE_PASSTHRU) 1823 MAKE_CASE(AArch64ISD::FP_EXTEND_MERGE_PASSTHRU) 1824 MAKE_CASE(AArch64ISD::SINT_TO_FP_MERGE_PASSTHRU) 1825 MAKE_CASE(AArch64ISD::UINT_TO_FP_MERGE_PASSTHRU) 1826 MAKE_CASE(AArch64ISD::FCVTZU_MERGE_PASSTHRU) 1827 MAKE_CASE(AArch64ISD::FCVTZS_MERGE_PASSTHRU) 1828 MAKE_CASE(AArch64ISD::FSQRT_MERGE_PASSTHRU) 1829 MAKE_CASE(AArch64ISD::FRECPX_MERGE_PASSTHRU) 1830 MAKE_CASE(AArch64ISD::FABS_MERGE_PASSTHRU) 1831 MAKE_CASE(AArch64ISD::ABS_MERGE_PASSTHRU) 1832 MAKE_CASE(AArch64ISD::NEG_MERGE_PASSTHRU) 1833 MAKE_CASE(AArch64ISD::SETCC_MERGE_ZERO) 1834 MAKE_CASE(AArch64ISD::ADC) 1835 MAKE_CASE(AArch64ISD::SBC) 1836 MAKE_CASE(AArch64ISD::ADDS) 1837 MAKE_CASE(AArch64ISD::SUBS) 1838 MAKE_CASE(AArch64ISD::ADCS) 1839 MAKE_CASE(AArch64ISD::SBCS) 1840 MAKE_CASE(AArch64ISD::ANDS) 1841 MAKE_CASE(AArch64ISD::CCMP) 1842 MAKE_CASE(AArch64ISD::CCMN) 1843 MAKE_CASE(AArch64ISD::FCCMP) 1844 MAKE_CASE(AArch64ISD::FCMP) 1845 MAKE_CASE(AArch64ISD::STRICT_FCMP) 1846 MAKE_CASE(AArch64ISD::STRICT_FCMPE) 1847 MAKE_CASE(AArch64ISD::DUP) 1848 MAKE_CASE(AArch64ISD::DUPLANE8) 1849 MAKE_CASE(AArch64ISD::DUPLANE16) 1850 MAKE_CASE(AArch64ISD::DUPLANE32) 1851 MAKE_CASE(AArch64ISD::DUPLANE64) 1852 MAKE_CASE(AArch64ISD::MOVI) 1853 MAKE_CASE(AArch64ISD::MOVIshift) 1854 MAKE_CASE(AArch64ISD::MOVIedit) 1855 MAKE_CASE(AArch64ISD::MOVImsl) 1856 MAKE_CASE(AArch64ISD::FMOV) 1857 MAKE_CASE(AArch64ISD::MVNIshift) 1858 MAKE_CASE(AArch64ISD::MVNImsl) 1859 MAKE_CASE(AArch64ISD::BICi) 1860 MAKE_CASE(AArch64ISD::ORRi) 1861 MAKE_CASE(AArch64ISD::BSP) 1862 MAKE_CASE(AArch64ISD::NEG) 1863 MAKE_CASE(AArch64ISD::EXTR) 1864 MAKE_CASE(AArch64ISD::ZIP1) 1865 MAKE_CASE(AArch64ISD::ZIP2) 1866 MAKE_CASE(AArch64ISD::UZP1) 1867 MAKE_CASE(AArch64ISD::UZP2) 1868 MAKE_CASE(AArch64ISD::TRN1) 1869 MAKE_CASE(AArch64ISD::TRN2) 1870 MAKE_CASE(AArch64ISD::REV16) 1871 MAKE_CASE(AArch64ISD::REV32) 1872 MAKE_CASE(AArch64ISD::REV64) 1873 MAKE_CASE(AArch64ISD::EXT) 1874 MAKE_CASE(AArch64ISD::VSHL) 1875 MAKE_CASE(AArch64ISD::VLSHR) 1876 MAKE_CASE(AArch64ISD::VASHR) 1877 MAKE_CASE(AArch64ISD::VSLI) 1878 MAKE_CASE(AArch64ISD::VSRI) 1879 MAKE_CASE(AArch64ISD::CMEQ) 1880 MAKE_CASE(AArch64ISD::CMGE) 1881 MAKE_CASE(AArch64ISD::CMGT) 1882 MAKE_CASE(AArch64ISD::CMHI) 1883 MAKE_CASE(AArch64ISD::CMHS) 1884 MAKE_CASE(AArch64ISD::FCMEQ) 1885 MAKE_CASE(AArch64ISD::FCMGE) 1886 MAKE_CASE(AArch64ISD::FCMGT) 1887 MAKE_CASE(AArch64ISD::CMEQz) 1888 MAKE_CASE(AArch64ISD::CMGEz) 1889 MAKE_CASE(AArch64ISD::CMGTz) 1890 MAKE_CASE(AArch64ISD::CMLEz) 1891 MAKE_CASE(AArch64ISD::CMLTz) 1892 MAKE_CASE(AArch64ISD::FCMEQz) 1893 MAKE_CASE(AArch64ISD::FCMGEz) 1894 MAKE_CASE(AArch64ISD::FCMGTz) 1895 MAKE_CASE(AArch64ISD::FCMLEz) 1896 MAKE_CASE(AArch64ISD::FCMLTz) 1897 MAKE_CASE(AArch64ISD::SADDV) 1898 MAKE_CASE(AArch64ISD::UADDV) 1899 MAKE_CASE(AArch64ISD::SRHADD) 1900 MAKE_CASE(AArch64ISD::URHADD) 1901 MAKE_CASE(AArch64ISD::SHADD) 1902 MAKE_CASE(AArch64ISD::UHADD) 1903 MAKE_CASE(AArch64ISD::SDOT) 1904 MAKE_CASE(AArch64ISD::UDOT) 1905 MAKE_CASE(AArch64ISD::SMINV) 1906 MAKE_CASE(AArch64ISD::UMINV) 1907 MAKE_CASE(AArch64ISD::SMAXV) 1908 MAKE_CASE(AArch64ISD::UMAXV) 1909 MAKE_CASE(AArch64ISD::SADDV_PRED) 1910 MAKE_CASE(AArch64ISD::UADDV_PRED) 1911 MAKE_CASE(AArch64ISD::SMAXV_PRED) 1912 MAKE_CASE(AArch64ISD::UMAXV_PRED) 1913 MAKE_CASE(AArch64ISD::SMINV_PRED) 1914 MAKE_CASE(AArch64ISD::UMINV_PRED) 1915 MAKE_CASE(AArch64ISD::ORV_PRED) 1916 MAKE_CASE(AArch64ISD::EORV_PRED) 1917 MAKE_CASE(AArch64ISD::ANDV_PRED) 1918 MAKE_CASE(AArch64ISD::CLASTA_N) 1919 MAKE_CASE(AArch64ISD::CLASTB_N) 1920 MAKE_CASE(AArch64ISD::LASTA) 1921 MAKE_CASE(AArch64ISD::LASTB) 1922 MAKE_CASE(AArch64ISD::REINTERPRET_CAST) 1923 MAKE_CASE(AArch64ISD::TBL) 1924 MAKE_CASE(AArch64ISD::FADD_PRED) 1925 MAKE_CASE(AArch64ISD::FADDA_PRED) 1926 MAKE_CASE(AArch64ISD::FADDV_PRED) 1927 MAKE_CASE(AArch64ISD::FDIV_PRED) 1928 MAKE_CASE(AArch64ISD::FMA_PRED) 1929 MAKE_CASE(AArch64ISD::FMAX_PRED) 1930 MAKE_CASE(AArch64ISD::FMAXV_PRED) 1931 MAKE_CASE(AArch64ISD::FMAXNM_PRED) 1932 MAKE_CASE(AArch64ISD::FMAXNMV_PRED) 1933 MAKE_CASE(AArch64ISD::FMIN_PRED) 1934 MAKE_CASE(AArch64ISD::FMINV_PRED) 1935 MAKE_CASE(AArch64ISD::FMINNM_PRED) 1936 MAKE_CASE(AArch64ISD::FMINNMV_PRED) 1937 MAKE_CASE(AArch64ISD::FMUL_PRED) 1938 MAKE_CASE(AArch64ISD::FSUB_PRED) 1939 MAKE_CASE(AArch64ISD::BIT) 1940 MAKE_CASE(AArch64ISD::CBZ) 1941 MAKE_CASE(AArch64ISD::CBNZ) 1942 MAKE_CASE(AArch64ISD::TBZ) 1943 MAKE_CASE(AArch64ISD::TBNZ) 1944 MAKE_CASE(AArch64ISD::TC_RETURN) 1945 MAKE_CASE(AArch64ISD::PREFETCH) 1946 MAKE_CASE(AArch64ISD::SITOF) 1947 MAKE_CASE(AArch64ISD::UITOF) 1948 MAKE_CASE(AArch64ISD::NVCAST) 1949 MAKE_CASE(AArch64ISD::MRS) 1950 MAKE_CASE(AArch64ISD::SQSHL_I) 1951 MAKE_CASE(AArch64ISD::UQSHL_I) 1952 MAKE_CASE(AArch64ISD::SRSHR_I) 1953 MAKE_CASE(AArch64ISD::URSHR_I) 1954 MAKE_CASE(AArch64ISD::SQSHLU_I) 1955 MAKE_CASE(AArch64ISD::WrapperLarge) 1956 MAKE_CASE(AArch64ISD::LD2post) 1957 MAKE_CASE(AArch64ISD::LD3post) 1958 MAKE_CASE(AArch64ISD::LD4post) 1959 MAKE_CASE(AArch64ISD::ST2post) 1960 MAKE_CASE(AArch64ISD::ST3post) 1961 MAKE_CASE(AArch64ISD::ST4post) 1962 MAKE_CASE(AArch64ISD::LD1x2post) 1963 MAKE_CASE(AArch64ISD::LD1x3post) 1964 MAKE_CASE(AArch64ISD::LD1x4post) 1965 MAKE_CASE(AArch64ISD::ST1x2post) 1966 MAKE_CASE(AArch64ISD::ST1x3post) 1967 MAKE_CASE(AArch64ISD::ST1x4post) 1968 MAKE_CASE(AArch64ISD::LD1DUPpost) 1969 MAKE_CASE(AArch64ISD::LD2DUPpost) 1970 MAKE_CASE(AArch64ISD::LD3DUPpost) 1971 MAKE_CASE(AArch64ISD::LD4DUPpost) 1972 MAKE_CASE(AArch64ISD::LD1LANEpost) 1973 MAKE_CASE(AArch64ISD::LD2LANEpost) 1974 MAKE_CASE(AArch64ISD::LD3LANEpost) 1975 MAKE_CASE(AArch64ISD::LD4LANEpost) 1976 MAKE_CASE(AArch64ISD::ST2LANEpost) 1977 MAKE_CASE(AArch64ISD::ST3LANEpost) 1978 MAKE_CASE(AArch64ISD::ST4LANEpost) 1979 MAKE_CASE(AArch64ISD::SMULL) 1980 MAKE_CASE(AArch64ISD::UMULL) 1981 MAKE_CASE(AArch64ISD::FRECPE) 1982 MAKE_CASE(AArch64ISD::FRECPS) 1983 MAKE_CASE(AArch64ISD::FRSQRTE) 1984 MAKE_CASE(AArch64ISD::FRSQRTS) 1985 MAKE_CASE(AArch64ISD::STG) 1986 MAKE_CASE(AArch64ISD::STZG) 1987 MAKE_CASE(AArch64ISD::ST2G) 1988 MAKE_CASE(AArch64ISD::STZ2G) 1989 MAKE_CASE(AArch64ISD::SUNPKHI) 1990 MAKE_CASE(AArch64ISD::SUNPKLO) 1991 MAKE_CASE(AArch64ISD::UUNPKHI) 1992 MAKE_CASE(AArch64ISD::UUNPKLO) 1993 MAKE_CASE(AArch64ISD::INSR) 1994 MAKE_CASE(AArch64ISD::PTEST) 1995 MAKE_CASE(AArch64ISD::PTRUE) 1996 MAKE_CASE(AArch64ISD::LD1_MERGE_ZERO) 1997 MAKE_CASE(AArch64ISD::LD1S_MERGE_ZERO) 1998 MAKE_CASE(AArch64ISD::LDNF1_MERGE_ZERO) 1999 MAKE_CASE(AArch64ISD::LDNF1S_MERGE_ZERO) 2000 MAKE_CASE(AArch64ISD::LDFF1_MERGE_ZERO) 2001 MAKE_CASE(AArch64ISD::LDFF1S_MERGE_ZERO) 2002 MAKE_CASE(AArch64ISD::LD1RQ_MERGE_ZERO) 2003 MAKE_CASE(AArch64ISD::LD1RO_MERGE_ZERO) 2004 MAKE_CASE(AArch64ISD::SVE_LD2_MERGE_ZERO) 2005 MAKE_CASE(AArch64ISD::SVE_LD3_MERGE_ZERO) 2006 MAKE_CASE(AArch64ISD::SVE_LD4_MERGE_ZERO) 2007 MAKE_CASE(AArch64ISD::GLD1_MERGE_ZERO) 2008 MAKE_CASE(AArch64ISD::GLD1_SCALED_MERGE_ZERO) 2009 MAKE_CASE(AArch64ISD::GLD1_SXTW_MERGE_ZERO) 2010 MAKE_CASE(AArch64ISD::GLD1_UXTW_MERGE_ZERO) 2011 MAKE_CASE(AArch64ISD::GLD1_SXTW_SCALED_MERGE_ZERO) 2012 MAKE_CASE(AArch64ISD::GLD1_UXTW_SCALED_MERGE_ZERO) 2013 MAKE_CASE(AArch64ISD::GLD1_IMM_MERGE_ZERO) 2014 MAKE_CASE(AArch64ISD::GLD1S_MERGE_ZERO) 2015 MAKE_CASE(AArch64ISD::GLD1S_SCALED_MERGE_ZERO) 2016 MAKE_CASE(AArch64ISD::GLD1S_SXTW_MERGE_ZERO) 2017 MAKE_CASE(AArch64ISD::GLD1S_UXTW_MERGE_ZERO) 2018 MAKE_CASE(AArch64ISD::GLD1S_SXTW_SCALED_MERGE_ZERO) 2019 MAKE_CASE(AArch64ISD::GLD1S_UXTW_SCALED_MERGE_ZERO) 2020 MAKE_CASE(AArch64ISD::GLD1S_IMM_MERGE_ZERO) 2021 MAKE_CASE(AArch64ISD::GLDFF1_MERGE_ZERO) 2022 MAKE_CASE(AArch64ISD::GLDFF1_SCALED_MERGE_ZERO) 2023 MAKE_CASE(AArch64ISD::GLDFF1_SXTW_MERGE_ZERO) 2024 MAKE_CASE(AArch64ISD::GLDFF1_UXTW_MERGE_ZERO) 2025 MAKE_CASE(AArch64ISD::GLDFF1_SXTW_SCALED_MERGE_ZERO) 2026 MAKE_CASE(AArch64ISD::GLDFF1_UXTW_SCALED_MERGE_ZERO) 2027 MAKE_CASE(AArch64ISD::GLDFF1_IMM_MERGE_ZERO) 2028 MAKE_CASE(AArch64ISD::GLDFF1S_MERGE_ZERO) 2029 MAKE_CASE(AArch64ISD::GLDFF1S_SCALED_MERGE_ZERO) 2030 MAKE_CASE(AArch64ISD::GLDFF1S_SXTW_MERGE_ZERO) 2031 MAKE_CASE(AArch64ISD::GLDFF1S_UXTW_MERGE_ZERO) 2032 MAKE_CASE(AArch64ISD::GLDFF1S_SXTW_SCALED_MERGE_ZERO) 2033 MAKE_CASE(AArch64ISD::GLDFF1S_UXTW_SCALED_MERGE_ZERO) 2034 MAKE_CASE(AArch64ISD::GLDFF1S_IMM_MERGE_ZERO) 2035 MAKE_CASE(AArch64ISD::GLDNT1_MERGE_ZERO) 2036 MAKE_CASE(AArch64ISD::GLDNT1_INDEX_MERGE_ZERO) 2037 MAKE_CASE(AArch64ISD::GLDNT1S_MERGE_ZERO) 2038 MAKE_CASE(AArch64ISD::ST1_PRED) 2039 MAKE_CASE(AArch64ISD::SST1_PRED) 2040 MAKE_CASE(AArch64ISD::SST1_SCALED_PRED) 2041 MAKE_CASE(AArch64ISD::SST1_SXTW_PRED) 2042 MAKE_CASE(AArch64ISD::SST1_UXTW_PRED) 2043 MAKE_CASE(AArch64ISD::SST1_SXTW_SCALED_PRED) 2044 MAKE_CASE(AArch64ISD::SST1_UXTW_SCALED_PRED) 2045 MAKE_CASE(AArch64ISD::SST1_IMM_PRED) 2046 MAKE_CASE(AArch64ISD::SSTNT1_PRED) 2047 MAKE_CASE(AArch64ISD::SSTNT1_INDEX_PRED) 2048 MAKE_CASE(AArch64ISD::LDP) 2049 MAKE_CASE(AArch64ISD::STP) 2050 MAKE_CASE(AArch64ISD::STNP) 2051 MAKE_CASE(AArch64ISD::BITREVERSE_MERGE_PASSTHRU) 2052 MAKE_CASE(AArch64ISD::BSWAP_MERGE_PASSTHRU) 2053 MAKE_CASE(AArch64ISD::CTLZ_MERGE_PASSTHRU) 2054 MAKE_CASE(AArch64ISD::CTPOP_MERGE_PASSTHRU) 2055 MAKE_CASE(AArch64ISD::DUP_MERGE_PASSTHRU) 2056 MAKE_CASE(AArch64ISD::INDEX_VECTOR) 2057 MAKE_CASE(AArch64ISD::UABD) 2058 MAKE_CASE(AArch64ISD::SABD) 2059 MAKE_CASE(AArch64ISD::CALL_RVMARKER) 2060 } 2061 #undef MAKE_CASE 2062 return nullptr; 2063 } 2064 2065 MachineBasicBlock * 2066 AArch64TargetLowering::EmitF128CSEL(MachineInstr &MI, 2067 MachineBasicBlock *MBB) const { 2068 // We materialise the F128CSEL pseudo-instruction as some control flow and a 2069 // phi node: 2070 2071 // OrigBB: 2072 // [... previous instrs leading to comparison ...] 2073 // b.ne TrueBB 2074 // b EndBB 2075 // TrueBB: 2076 // ; Fallthrough 2077 // EndBB: 2078 // Dest = PHI [IfTrue, TrueBB], [IfFalse, OrigBB] 2079 2080 MachineFunction *MF = MBB->getParent(); 2081 const TargetInstrInfo *TII = Subtarget->getInstrInfo(); 2082 const BasicBlock *LLVM_BB = MBB->getBasicBlock(); 2083 DebugLoc DL = MI.getDebugLoc(); 2084 MachineFunction::iterator It = ++MBB->getIterator(); 2085 2086 Register DestReg = MI.getOperand(0).getReg(); 2087 Register IfTrueReg = MI.getOperand(1).getReg(); 2088 Register IfFalseReg = MI.getOperand(2).getReg(); 2089 unsigned CondCode = MI.getOperand(3).getImm(); 2090 bool NZCVKilled = MI.getOperand(4).isKill(); 2091 2092 MachineBasicBlock *TrueBB = MF->CreateMachineBasicBlock(LLVM_BB); 2093 MachineBasicBlock *EndBB = MF->CreateMachineBasicBlock(LLVM_BB); 2094 MF->insert(It, TrueBB); 2095 MF->insert(It, EndBB); 2096 2097 // Transfer rest of current basic-block to EndBB 2098 EndBB->splice(EndBB->begin(), MBB, std::next(MachineBasicBlock::iterator(MI)), 2099 MBB->end()); 2100 EndBB->transferSuccessorsAndUpdatePHIs(MBB); 2101 2102 BuildMI(MBB, DL, TII->get(AArch64::Bcc)).addImm(CondCode).addMBB(TrueBB); 2103 BuildMI(MBB, DL, TII->get(AArch64::B)).addMBB(EndBB); 2104 MBB->addSuccessor(TrueBB); 2105 MBB->addSuccessor(EndBB); 2106 2107 // TrueBB falls through to the end. 2108 TrueBB->addSuccessor(EndBB); 2109 2110 if (!NZCVKilled) { 2111 TrueBB->addLiveIn(AArch64::NZCV); 2112 EndBB->addLiveIn(AArch64::NZCV); 2113 } 2114 2115 BuildMI(*EndBB, EndBB->begin(), DL, TII->get(AArch64::PHI), DestReg) 2116 .addReg(IfTrueReg) 2117 .addMBB(TrueBB) 2118 .addReg(IfFalseReg) 2119 .addMBB(MBB); 2120 2121 MI.eraseFromParent(); 2122 return EndBB; 2123 } 2124 2125 MachineBasicBlock *AArch64TargetLowering::EmitLoweredCatchRet( 2126 MachineInstr &MI, MachineBasicBlock *BB) const { 2127 assert(!isAsynchronousEHPersonality(classifyEHPersonality( 2128 BB->getParent()->getFunction().getPersonalityFn())) && 2129 "SEH does not use catchret!"); 2130 return BB; 2131 } 2132 2133 MachineBasicBlock *AArch64TargetLowering::EmitInstrWithCustomInserter( 2134 MachineInstr &MI, MachineBasicBlock *BB) const { 2135 switch (MI.getOpcode()) { 2136 default: 2137 #ifndef NDEBUG 2138 MI.dump(); 2139 #endif 2140 llvm_unreachable("Unexpected instruction for custom inserter!"); 2141 2142 case AArch64::F128CSEL: 2143 return EmitF128CSEL(MI, BB); 2144 2145 case TargetOpcode::STACKMAP: 2146 case TargetOpcode::PATCHPOINT: 2147 case TargetOpcode::STATEPOINT: 2148 return emitPatchPoint(MI, BB); 2149 2150 case AArch64::CATCHRET: 2151 return EmitLoweredCatchRet(MI, BB); 2152 } 2153 } 2154 2155 //===----------------------------------------------------------------------===// 2156 // AArch64 Lowering private implementation. 2157 //===----------------------------------------------------------------------===// 2158 2159 //===----------------------------------------------------------------------===// 2160 // Lowering Code 2161 //===----------------------------------------------------------------------===// 2162 2163 /// isZerosVector - Check whether SDNode N is a zero-filled vector. 2164 static bool isZerosVector(const SDNode *N) { 2165 // Look through a bit convert. 2166 while (N->getOpcode() == ISD::BITCAST) 2167 N = N->getOperand(0).getNode(); 2168 2169 if (ISD::isConstantSplatVectorAllZeros(N)) 2170 return true; 2171 2172 if (N->getOpcode() != AArch64ISD::DUP) 2173 return false; 2174 2175 auto Opnd0 = N->getOperand(0); 2176 auto *CINT = dyn_cast<ConstantSDNode>(Opnd0); 2177 auto *CFP = dyn_cast<ConstantFPSDNode>(Opnd0); 2178 return (CINT && CINT->isNullValue()) || (CFP && CFP->isZero()); 2179 } 2180 2181 /// changeIntCCToAArch64CC - Convert a DAG integer condition code to an AArch64 2182 /// CC 2183 static AArch64CC::CondCode changeIntCCToAArch64CC(ISD::CondCode CC) { 2184 switch (CC) { 2185 default: 2186 llvm_unreachable("Unknown condition code!"); 2187 case ISD::SETNE: 2188 return AArch64CC::NE; 2189 case ISD::SETEQ: 2190 return AArch64CC::EQ; 2191 case ISD::SETGT: 2192 return AArch64CC::GT; 2193 case ISD::SETGE: 2194 return AArch64CC::GE; 2195 case ISD::SETLT: 2196 return AArch64CC::LT; 2197 case ISD::SETLE: 2198 return AArch64CC::LE; 2199 case ISD::SETUGT: 2200 return AArch64CC::HI; 2201 case ISD::SETUGE: 2202 return AArch64CC::HS; 2203 case ISD::SETULT: 2204 return AArch64CC::LO; 2205 case ISD::SETULE: 2206 return AArch64CC::LS; 2207 } 2208 } 2209 2210 /// changeFPCCToAArch64CC - Convert a DAG fp condition code to an AArch64 CC. 2211 static void changeFPCCToAArch64CC(ISD::CondCode CC, 2212 AArch64CC::CondCode &CondCode, 2213 AArch64CC::CondCode &CondCode2) { 2214 CondCode2 = AArch64CC::AL; 2215 switch (CC) { 2216 default: 2217 llvm_unreachable("Unknown FP condition!"); 2218 case ISD::SETEQ: 2219 case ISD::SETOEQ: 2220 CondCode = AArch64CC::EQ; 2221 break; 2222 case ISD::SETGT: 2223 case ISD::SETOGT: 2224 CondCode = AArch64CC::GT; 2225 break; 2226 case ISD::SETGE: 2227 case ISD::SETOGE: 2228 CondCode = AArch64CC::GE; 2229 break; 2230 case ISD::SETOLT: 2231 CondCode = AArch64CC::MI; 2232 break; 2233 case ISD::SETOLE: 2234 CondCode = AArch64CC::LS; 2235 break; 2236 case ISD::SETONE: 2237 CondCode = AArch64CC::MI; 2238 CondCode2 = AArch64CC::GT; 2239 break; 2240 case ISD::SETO: 2241 CondCode = AArch64CC::VC; 2242 break; 2243 case ISD::SETUO: 2244 CondCode = AArch64CC::VS; 2245 break; 2246 case ISD::SETUEQ: 2247 CondCode = AArch64CC::EQ; 2248 CondCode2 = AArch64CC::VS; 2249 break; 2250 case ISD::SETUGT: 2251 CondCode = AArch64CC::HI; 2252 break; 2253 case ISD::SETUGE: 2254 CondCode = AArch64CC::PL; 2255 break; 2256 case ISD::SETLT: 2257 case ISD::SETULT: 2258 CondCode = AArch64CC::LT; 2259 break; 2260 case ISD::SETLE: 2261 case ISD::SETULE: 2262 CondCode = AArch64CC::LE; 2263 break; 2264 case ISD::SETNE: 2265 case ISD::SETUNE: 2266 CondCode = AArch64CC::NE; 2267 break; 2268 } 2269 } 2270 2271 /// Convert a DAG fp condition code to an AArch64 CC. 2272 /// This differs from changeFPCCToAArch64CC in that it returns cond codes that 2273 /// should be AND'ed instead of OR'ed. 2274 static void changeFPCCToANDAArch64CC(ISD::CondCode CC, 2275 AArch64CC::CondCode &CondCode, 2276 AArch64CC::CondCode &CondCode2) { 2277 CondCode2 = AArch64CC::AL; 2278 switch (CC) { 2279 default: 2280 changeFPCCToAArch64CC(CC, CondCode, CondCode2); 2281 assert(CondCode2 == AArch64CC::AL); 2282 break; 2283 case ISD::SETONE: 2284 // (a one b) 2285 // == ((a olt b) || (a ogt b)) 2286 // == ((a ord b) && (a une b)) 2287 CondCode = AArch64CC::VC; 2288 CondCode2 = AArch64CC::NE; 2289 break; 2290 case ISD::SETUEQ: 2291 // (a ueq b) 2292 // == ((a uno b) || (a oeq b)) 2293 // == ((a ule b) && (a uge b)) 2294 CondCode = AArch64CC::PL; 2295 CondCode2 = AArch64CC::LE; 2296 break; 2297 } 2298 } 2299 2300 /// changeVectorFPCCToAArch64CC - Convert a DAG fp condition code to an AArch64 2301 /// CC usable with the vector instructions. Fewer operations are available 2302 /// without a real NZCV register, so we have to use less efficient combinations 2303 /// to get the same effect. 2304 static void changeVectorFPCCToAArch64CC(ISD::CondCode CC, 2305 AArch64CC::CondCode &CondCode, 2306 AArch64CC::CondCode &CondCode2, 2307 bool &Invert) { 2308 Invert = false; 2309 switch (CC) { 2310 default: 2311 // Mostly the scalar mappings work fine. 2312 changeFPCCToAArch64CC(CC, CondCode, CondCode2); 2313 break; 2314 case ISD::SETUO: 2315 Invert = true; 2316 LLVM_FALLTHROUGH; 2317 case ISD::SETO: 2318 CondCode = AArch64CC::MI; 2319 CondCode2 = AArch64CC::GE; 2320 break; 2321 case ISD::SETUEQ: 2322 case ISD::SETULT: 2323 case ISD::SETULE: 2324 case ISD::SETUGT: 2325 case ISD::SETUGE: 2326 // All of the compare-mask comparisons are ordered, but we can switch 2327 // between the two by a double inversion. E.g. ULE == !OGT. 2328 Invert = true; 2329 changeFPCCToAArch64CC(getSetCCInverse(CC, /* FP inverse */ MVT::f32), 2330 CondCode, CondCode2); 2331 break; 2332 } 2333 } 2334 2335 static bool isLegalArithImmed(uint64_t C) { 2336 // Matches AArch64DAGToDAGISel::SelectArithImmed(). 2337 bool IsLegal = (C >> 12 == 0) || ((C & 0xFFFULL) == 0 && C >> 24 == 0); 2338 LLVM_DEBUG(dbgs() << "Is imm " << C 2339 << " legal: " << (IsLegal ? "yes\n" : "no\n")); 2340 return IsLegal; 2341 } 2342 2343 // Can a (CMP op1, (sub 0, op2) be turned into a CMN instruction on 2344 // the grounds that "op1 - (-op2) == op1 + op2" ? Not always, the C and V flags 2345 // can be set differently by this operation. It comes down to whether 2346 // "SInt(~op2)+1 == SInt(~op2+1)" (and the same for UInt). If they are then 2347 // everything is fine. If not then the optimization is wrong. Thus general 2348 // comparisons are only valid if op2 != 0. 2349 // 2350 // So, finally, the only LLVM-native comparisons that don't mention C and V 2351 // are SETEQ and SETNE. They're the only ones we can safely use CMN for in 2352 // the absence of information about op2. 2353 static bool isCMN(SDValue Op, ISD::CondCode CC) { 2354 return Op.getOpcode() == ISD::SUB && isNullConstant(Op.getOperand(0)) && 2355 (CC == ISD::SETEQ || CC == ISD::SETNE); 2356 } 2357 2358 static SDValue emitStrictFPComparison(SDValue LHS, SDValue RHS, const SDLoc &dl, 2359 SelectionDAG &DAG, SDValue Chain, 2360 bool IsSignaling) { 2361 EVT VT = LHS.getValueType(); 2362 assert(VT != MVT::f128); 2363 assert(VT != MVT::f16 && "Lowering of strict fp16 not yet implemented"); 2364 unsigned Opcode = 2365 IsSignaling ? AArch64ISD::STRICT_FCMPE : AArch64ISD::STRICT_FCMP; 2366 return DAG.getNode(Opcode, dl, {VT, MVT::Other}, {Chain, LHS, RHS}); 2367 } 2368 2369 static SDValue emitComparison(SDValue LHS, SDValue RHS, ISD::CondCode CC, 2370 const SDLoc &dl, SelectionDAG &DAG) { 2371 EVT VT = LHS.getValueType(); 2372 const bool FullFP16 = 2373 static_cast<const AArch64Subtarget &>(DAG.getSubtarget()).hasFullFP16(); 2374 2375 if (VT.isFloatingPoint()) { 2376 assert(VT != MVT::f128); 2377 if (VT == MVT::f16 && !FullFP16) { 2378 LHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f32, LHS); 2379 RHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f32, RHS); 2380 VT = MVT::f32; 2381 } 2382 return DAG.getNode(AArch64ISD::FCMP, dl, VT, LHS, RHS); 2383 } 2384 2385 // The CMP instruction is just an alias for SUBS, and representing it as 2386 // SUBS means that it's possible to get CSE with subtract operations. 2387 // A later phase can perform the optimization of setting the destination 2388 // register to WZR/XZR if it ends up being unused. 2389 unsigned Opcode = AArch64ISD::SUBS; 2390 2391 if (isCMN(RHS, CC)) { 2392 // Can we combine a (CMP op1, (sub 0, op2) into a CMN instruction ? 2393 Opcode = AArch64ISD::ADDS; 2394 RHS = RHS.getOperand(1); 2395 } else if (isCMN(LHS, CC)) { 2396 // As we are looking for EQ/NE compares, the operands can be commuted ; can 2397 // we combine a (CMP (sub 0, op1), op2) into a CMN instruction ? 2398 Opcode = AArch64ISD::ADDS; 2399 LHS = LHS.getOperand(1); 2400 } else if (isNullConstant(RHS) && !isUnsignedIntSetCC(CC)) { 2401 if (LHS.getOpcode() == ISD::AND) { 2402 // Similarly, (CMP (and X, Y), 0) can be implemented with a TST 2403 // (a.k.a. ANDS) except that the flags are only guaranteed to work for one 2404 // of the signed comparisons. 2405 const SDValue ANDSNode = DAG.getNode(AArch64ISD::ANDS, dl, 2406 DAG.getVTList(VT, MVT_CC), 2407 LHS.getOperand(0), 2408 LHS.getOperand(1)); 2409 // Replace all users of (and X, Y) with newly generated (ands X, Y) 2410 DAG.ReplaceAllUsesWith(LHS, ANDSNode); 2411 return ANDSNode.getValue(1); 2412 } else if (LHS.getOpcode() == AArch64ISD::ANDS) { 2413 // Use result of ANDS 2414 return LHS.getValue(1); 2415 } 2416 } 2417 2418 return DAG.getNode(Opcode, dl, DAG.getVTList(VT, MVT_CC), LHS, RHS) 2419 .getValue(1); 2420 } 2421 2422 /// \defgroup AArch64CCMP CMP;CCMP matching 2423 /// 2424 /// These functions deal with the formation of CMP;CCMP;... sequences. 2425 /// The CCMP/CCMN/FCCMP/FCCMPE instructions allow the conditional execution of 2426 /// a comparison. They set the NZCV flags to a predefined value if their 2427 /// predicate is false. This allows to express arbitrary conjunctions, for 2428 /// example "cmp 0 (and (setCA (cmp A)) (setCB (cmp B)))" 2429 /// expressed as: 2430 /// cmp A 2431 /// ccmp B, inv(CB), CA 2432 /// check for CB flags 2433 /// 2434 /// This naturally lets us implement chains of AND operations with SETCC 2435 /// operands. And we can even implement some other situations by transforming 2436 /// them: 2437 /// - We can implement (NEG SETCC) i.e. negating a single comparison by 2438 /// negating the flags used in a CCMP/FCCMP operations. 2439 /// - We can negate the result of a whole chain of CMP/CCMP/FCCMP operations 2440 /// by negating the flags we test for afterwards. i.e. 2441 /// NEG (CMP CCMP CCCMP ...) can be implemented. 2442 /// - Note that we can only ever negate all previously processed results. 2443 /// What we can not implement by flipping the flags to test is a negation 2444 /// of two sub-trees (because the negation affects all sub-trees emitted so 2445 /// far, so the 2nd sub-tree we emit would also affect the first). 2446 /// With those tools we can implement some OR operations: 2447 /// - (OR (SETCC A) (SETCC B)) can be implemented via: 2448 /// NEG (AND (NEG (SETCC A)) (NEG (SETCC B))) 2449 /// - After transforming OR to NEG/AND combinations we may be able to use NEG 2450 /// elimination rules from earlier to implement the whole thing as a 2451 /// CCMP/FCCMP chain. 2452 /// 2453 /// As complete example: 2454 /// or (or (setCA (cmp A)) (setCB (cmp B))) 2455 /// (and (setCC (cmp C)) (setCD (cmp D)))" 2456 /// can be reassociated to: 2457 /// or (and (setCC (cmp C)) setCD (cmp D)) 2458 // (or (setCA (cmp A)) (setCB (cmp B))) 2459 /// can be transformed to: 2460 /// not (and (not (and (setCC (cmp C)) (setCD (cmp D)))) 2461 /// (and (not (setCA (cmp A)) (not (setCB (cmp B))))))" 2462 /// which can be implemented as: 2463 /// cmp C 2464 /// ccmp D, inv(CD), CC 2465 /// ccmp A, CA, inv(CD) 2466 /// ccmp B, CB, inv(CA) 2467 /// check for CB flags 2468 /// 2469 /// A counterexample is "or (and A B) (and C D)" which translates to 2470 /// not (and (not (and (not A) (not B))) (not (and (not C) (not D)))), we 2471 /// can only implement 1 of the inner (not) operations, but not both! 2472 /// @{ 2473 2474 /// Create a conditional comparison; Use CCMP, CCMN or FCCMP as appropriate. 2475 static SDValue emitConditionalComparison(SDValue LHS, SDValue RHS, 2476 ISD::CondCode CC, SDValue CCOp, 2477 AArch64CC::CondCode Predicate, 2478 AArch64CC::CondCode OutCC, 2479 const SDLoc &DL, SelectionDAG &DAG) { 2480 unsigned Opcode = 0; 2481 const bool FullFP16 = 2482 static_cast<const AArch64Subtarget &>(DAG.getSubtarget()).hasFullFP16(); 2483 2484 if (LHS.getValueType().isFloatingPoint()) { 2485 assert(LHS.getValueType() != MVT::f128); 2486 if (LHS.getValueType() == MVT::f16 && !FullFP16) { 2487 LHS = DAG.getNode(ISD::FP_EXTEND, DL, MVT::f32, LHS); 2488 RHS = DAG.getNode(ISD::FP_EXTEND, DL, MVT::f32, RHS); 2489 } 2490 Opcode = AArch64ISD::FCCMP; 2491 } else if (RHS.getOpcode() == ISD::SUB) { 2492 SDValue SubOp0 = RHS.getOperand(0); 2493 if (isNullConstant(SubOp0) && (CC == ISD::SETEQ || CC == ISD::SETNE)) { 2494 // See emitComparison() on why we can only do this for SETEQ and SETNE. 2495 Opcode = AArch64ISD::CCMN; 2496 RHS = RHS.getOperand(1); 2497 } 2498 } 2499 if (Opcode == 0) 2500 Opcode = AArch64ISD::CCMP; 2501 2502 SDValue Condition = DAG.getConstant(Predicate, DL, MVT_CC); 2503 AArch64CC::CondCode InvOutCC = AArch64CC::getInvertedCondCode(OutCC); 2504 unsigned NZCV = AArch64CC::getNZCVToSatisfyCondCode(InvOutCC); 2505 SDValue NZCVOp = DAG.getConstant(NZCV, DL, MVT::i32); 2506 return DAG.getNode(Opcode, DL, MVT_CC, LHS, RHS, NZCVOp, Condition, CCOp); 2507 } 2508 2509 /// Returns true if @p Val is a tree of AND/OR/SETCC operations that can be 2510 /// expressed as a conjunction. See \ref AArch64CCMP. 2511 /// \param CanNegate Set to true if we can negate the whole sub-tree just by 2512 /// changing the conditions on the SETCC tests. 2513 /// (this means we can call emitConjunctionRec() with 2514 /// Negate==true on this sub-tree) 2515 /// \param MustBeFirst Set to true if this subtree needs to be negated and we 2516 /// cannot do the negation naturally. We are required to 2517 /// emit the subtree first in this case. 2518 /// \param WillNegate Is true if are called when the result of this 2519 /// subexpression must be negated. This happens when the 2520 /// outer expression is an OR. We can use this fact to know 2521 /// that we have a double negation (or (or ...) ...) that 2522 /// can be implemented for free. 2523 static bool canEmitConjunction(const SDValue Val, bool &CanNegate, 2524 bool &MustBeFirst, bool WillNegate, 2525 unsigned Depth = 0) { 2526 if (!Val.hasOneUse()) 2527 return false; 2528 unsigned Opcode = Val->getOpcode(); 2529 if (Opcode == ISD::SETCC) { 2530 if (Val->getOperand(0).getValueType() == MVT::f128) 2531 return false; 2532 CanNegate = true; 2533 MustBeFirst = false; 2534 return true; 2535 } 2536 // Protect against exponential runtime and stack overflow. 2537 if (Depth > 6) 2538 return false; 2539 if (Opcode == ISD::AND || Opcode == ISD::OR) { 2540 bool IsOR = Opcode == ISD::OR; 2541 SDValue O0 = Val->getOperand(0); 2542 SDValue O1 = Val->getOperand(1); 2543 bool CanNegateL; 2544 bool MustBeFirstL; 2545 if (!canEmitConjunction(O0, CanNegateL, MustBeFirstL, IsOR, Depth+1)) 2546 return false; 2547 bool CanNegateR; 2548 bool MustBeFirstR; 2549 if (!canEmitConjunction(O1, CanNegateR, MustBeFirstR, IsOR, Depth+1)) 2550 return false; 2551 2552 if (MustBeFirstL && MustBeFirstR) 2553 return false; 2554 2555 if (IsOR) { 2556 // For an OR expression we need to be able to naturally negate at least 2557 // one side or we cannot do the transformation at all. 2558 if (!CanNegateL && !CanNegateR) 2559 return false; 2560 // If we the result of the OR will be negated and we can naturally negate 2561 // the leafs, then this sub-tree as a whole negates naturally. 2562 CanNegate = WillNegate && CanNegateL && CanNegateR; 2563 // If we cannot naturally negate the whole sub-tree, then this must be 2564 // emitted first. 2565 MustBeFirst = !CanNegate; 2566 } else { 2567 assert(Opcode == ISD::AND && "Must be OR or AND"); 2568 // We cannot naturally negate an AND operation. 2569 CanNegate = false; 2570 MustBeFirst = MustBeFirstL || MustBeFirstR; 2571 } 2572 return true; 2573 } 2574 return false; 2575 } 2576 2577 /// Emit conjunction or disjunction tree with the CMP/FCMP followed by a chain 2578 /// of CCMP/CFCMP ops. See @ref AArch64CCMP. 2579 /// Tries to transform the given i1 producing node @p Val to a series compare 2580 /// and conditional compare operations. @returns an NZCV flags producing node 2581 /// and sets @p OutCC to the flags that should be tested or returns SDValue() if 2582 /// transformation was not possible. 2583 /// \p Negate is true if we want this sub-tree being negated just by changing 2584 /// SETCC conditions. 2585 static SDValue emitConjunctionRec(SelectionDAG &DAG, SDValue Val, 2586 AArch64CC::CondCode &OutCC, bool Negate, SDValue CCOp, 2587 AArch64CC::CondCode Predicate) { 2588 // We're at a tree leaf, produce a conditional comparison operation. 2589 unsigned Opcode = Val->getOpcode(); 2590 if (Opcode == ISD::SETCC) { 2591 SDValue LHS = Val->getOperand(0); 2592 SDValue RHS = Val->getOperand(1); 2593 ISD::CondCode CC = cast<CondCodeSDNode>(Val->getOperand(2))->get(); 2594 bool isInteger = LHS.getValueType().isInteger(); 2595 if (Negate) 2596 CC = getSetCCInverse(CC, LHS.getValueType()); 2597 SDLoc DL(Val); 2598 // Determine OutCC and handle FP special case. 2599 if (isInteger) { 2600 OutCC = changeIntCCToAArch64CC(CC); 2601 } else { 2602 assert(LHS.getValueType().isFloatingPoint()); 2603 AArch64CC::CondCode ExtraCC; 2604 changeFPCCToANDAArch64CC(CC, OutCC, ExtraCC); 2605 // Some floating point conditions can't be tested with a single condition 2606 // code. Construct an additional comparison in this case. 2607 if (ExtraCC != AArch64CC::AL) { 2608 SDValue ExtraCmp; 2609 if (!CCOp.getNode()) 2610 ExtraCmp = emitComparison(LHS, RHS, CC, DL, DAG); 2611 else 2612 ExtraCmp = emitConditionalComparison(LHS, RHS, CC, CCOp, Predicate, 2613 ExtraCC, DL, DAG); 2614 CCOp = ExtraCmp; 2615 Predicate = ExtraCC; 2616 } 2617 } 2618 2619 // Produce a normal comparison if we are first in the chain 2620 if (!CCOp) 2621 return emitComparison(LHS, RHS, CC, DL, DAG); 2622 // Otherwise produce a ccmp. 2623 return emitConditionalComparison(LHS, RHS, CC, CCOp, Predicate, OutCC, DL, 2624 DAG); 2625 } 2626 assert(Val->hasOneUse() && "Valid conjunction/disjunction tree"); 2627 2628 bool IsOR = Opcode == ISD::OR; 2629 2630 SDValue LHS = Val->getOperand(0); 2631 bool CanNegateL; 2632 bool MustBeFirstL; 2633 bool ValidL = canEmitConjunction(LHS, CanNegateL, MustBeFirstL, IsOR); 2634 assert(ValidL && "Valid conjunction/disjunction tree"); 2635 (void)ValidL; 2636 2637 SDValue RHS = Val->getOperand(1); 2638 bool CanNegateR; 2639 bool MustBeFirstR; 2640 bool ValidR = canEmitConjunction(RHS, CanNegateR, MustBeFirstR, IsOR); 2641 assert(ValidR && "Valid conjunction/disjunction tree"); 2642 (void)ValidR; 2643 2644 // Swap sub-tree that must come first to the right side. 2645 if (MustBeFirstL) { 2646 assert(!MustBeFirstR && "Valid conjunction/disjunction tree"); 2647 std::swap(LHS, RHS); 2648 std::swap(CanNegateL, CanNegateR); 2649 std::swap(MustBeFirstL, MustBeFirstR); 2650 } 2651 2652 bool NegateR; 2653 bool NegateAfterR; 2654 bool NegateL; 2655 bool NegateAfterAll; 2656 if (Opcode == ISD::OR) { 2657 // Swap the sub-tree that we can negate naturally to the left. 2658 if (!CanNegateL) { 2659 assert(CanNegateR && "at least one side must be negatable"); 2660 assert(!MustBeFirstR && "invalid conjunction/disjunction tree"); 2661 assert(!Negate); 2662 std::swap(LHS, RHS); 2663 NegateR = false; 2664 NegateAfterR = true; 2665 } else { 2666 // Negate the left sub-tree if possible, otherwise negate the result. 2667 NegateR = CanNegateR; 2668 NegateAfterR = !CanNegateR; 2669 } 2670 NegateL = true; 2671 NegateAfterAll = !Negate; 2672 } else { 2673 assert(Opcode == ISD::AND && "Valid conjunction/disjunction tree"); 2674 assert(!Negate && "Valid conjunction/disjunction tree"); 2675 2676 NegateL = false; 2677 NegateR = false; 2678 NegateAfterR = false; 2679 NegateAfterAll = false; 2680 } 2681 2682 // Emit sub-trees. 2683 AArch64CC::CondCode RHSCC; 2684 SDValue CmpR = emitConjunctionRec(DAG, RHS, RHSCC, NegateR, CCOp, Predicate); 2685 if (NegateAfterR) 2686 RHSCC = AArch64CC::getInvertedCondCode(RHSCC); 2687 SDValue CmpL = emitConjunctionRec(DAG, LHS, OutCC, NegateL, CmpR, RHSCC); 2688 if (NegateAfterAll) 2689 OutCC = AArch64CC::getInvertedCondCode(OutCC); 2690 return CmpL; 2691 } 2692 2693 /// Emit expression as a conjunction (a series of CCMP/CFCMP ops). 2694 /// In some cases this is even possible with OR operations in the expression. 2695 /// See \ref AArch64CCMP. 2696 /// \see emitConjunctionRec(). 2697 static SDValue emitConjunction(SelectionDAG &DAG, SDValue Val, 2698 AArch64CC::CondCode &OutCC) { 2699 bool DummyCanNegate; 2700 bool DummyMustBeFirst; 2701 if (!canEmitConjunction(Val, DummyCanNegate, DummyMustBeFirst, false)) 2702 return SDValue(); 2703 2704 return emitConjunctionRec(DAG, Val, OutCC, false, SDValue(), AArch64CC::AL); 2705 } 2706 2707 /// @} 2708 2709 /// Returns how profitable it is to fold a comparison's operand's shift and/or 2710 /// extension operations. 2711 static unsigned getCmpOperandFoldingProfit(SDValue Op) { 2712 auto isSupportedExtend = [&](SDValue V) { 2713 if (V.getOpcode() == ISD::SIGN_EXTEND_INREG) 2714 return true; 2715 2716 if (V.getOpcode() == ISD::AND) 2717 if (ConstantSDNode *MaskCst = dyn_cast<ConstantSDNode>(V.getOperand(1))) { 2718 uint64_t Mask = MaskCst->getZExtValue(); 2719 return (Mask == 0xFF || Mask == 0xFFFF || Mask == 0xFFFFFFFF); 2720 } 2721 2722 return false; 2723 }; 2724 2725 if (!Op.hasOneUse()) 2726 return 0; 2727 2728 if (isSupportedExtend(Op)) 2729 return 1; 2730 2731 unsigned Opc = Op.getOpcode(); 2732 if (Opc == ISD::SHL || Opc == ISD::SRL || Opc == ISD::SRA) 2733 if (ConstantSDNode *ShiftCst = dyn_cast<ConstantSDNode>(Op.getOperand(1))) { 2734 uint64_t Shift = ShiftCst->getZExtValue(); 2735 if (isSupportedExtend(Op.getOperand(0))) 2736 return (Shift <= 4) ? 2 : 1; 2737 EVT VT = Op.getValueType(); 2738 if ((VT == MVT::i32 && Shift <= 31) || (VT == MVT::i64 && Shift <= 63)) 2739 return 1; 2740 } 2741 2742 return 0; 2743 } 2744 2745 static SDValue getAArch64Cmp(SDValue LHS, SDValue RHS, ISD::CondCode CC, 2746 SDValue &AArch64cc, SelectionDAG &DAG, 2747 const SDLoc &dl) { 2748 if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS.getNode())) { 2749 EVT VT = RHS.getValueType(); 2750 uint64_t C = RHSC->getZExtValue(); 2751 if (!isLegalArithImmed(C)) { 2752 // Constant does not fit, try adjusting it by one? 2753 switch (CC) { 2754 default: 2755 break; 2756 case ISD::SETLT: 2757 case ISD::SETGE: 2758 if ((VT == MVT::i32 && C != 0x80000000 && 2759 isLegalArithImmed((uint32_t)(C - 1))) || 2760 (VT == MVT::i64 && C != 0x80000000ULL && 2761 isLegalArithImmed(C - 1ULL))) { 2762 CC = (CC == ISD::SETLT) ? ISD::SETLE : ISD::SETGT; 2763 C = (VT == MVT::i32) ? (uint32_t)(C - 1) : C - 1; 2764 RHS = DAG.getConstant(C, dl, VT); 2765 } 2766 break; 2767 case ISD::SETULT: 2768 case ISD::SETUGE: 2769 if ((VT == MVT::i32 && C != 0 && 2770 isLegalArithImmed((uint32_t)(C - 1))) || 2771 (VT == MVT::i64 && C != 0ULL && isLegalArithImmed(C - 1ULL))) { 2772 CC = (CC == ISD::SETULT) ? ISD::SETULE : ISD::SETUGT; 2773 C = (VT == MVT::i32) ? (uint32_t)(C - 1) : C - 1; 2774 RHS = DAG.getConstant(C, dl, VT); 2775 } 2776 break; 2777 case ISD::SETLE: 2778 case ISD::SETGT: 2779 if ((VT == MVT::i32 && C != INT32_MAX && 2780 isLegalArithImmed((uint32_t)(C + 1))) || 2781 (VT == MVT::i64 && C != INT64_MAX && 2782 isLegalArithImmed(C + 1ULL))) { 2783 CC = (CC == ISD::SETLE) ? ISD::SETLT : ISD::SETGE; 2784 C = (VT == MVT::i32) ? (uint32_t)(C + 1) : C + 1; 2785 RHS = DAG.getConstant(C, dl, VT); 2786 } 2787 break; 2788 case ISD::SETULE: 2789 case ISD::SETUGT: 2790 if ((VT == MVT::i32 && C != UINT32_MAX && 2791 isLegalArithImmed((uint32_t)(C + 1))) || 2792 (VT == MVT::i64 && C != UINT64_MAX && 2793 isLegalArithImmed(C + 1ULL))) { 2794 CC = (CC == ISD::SETULE) ? ISD::SETULT : ISD::SETUGE; 2795 C = (VT == MVT::i32) ? (uint32_t)(C + 1) : C + 1; 2796 RHS = DAG.getConstant(C, dl, VT); 2797 } 2798 break; 2799 } 2800 } 2801 } 2802 2803 // Comparisons are canonicalized so that the RHS operand is simpler than the 2804 // LHS one, the extreme case being when RHS is an immediate. However, AArch64 2805 // can fold some shift+extend operations on the RHS operand, so swap the 2806 // operands if that can be done. 2807 // 2808 // For example: 2809 // lsl w13, w11, #1 2810 // cmp w13, w12 2811 // can be turned into: 2812 // cmp w12, w11, lsl #1 2813 if (!isa<ConstantSDNode>(RHS) || 2814 !isLegalArithImmed(cast<ConstantSDNode>(RHS)->getZExtValue())) { 2815 SDValue TheLHS = isCMN(LHS, CC) ? LHS.getOperand(1) : LHS; 2816 2817 if (getCmpOperandFoldingProfit(TheLHS) > getCmpOperandFoldingProfit(RHS)) { 2818 std::swap(LHS, RHS); 2819 CC = ISD::getSetCCSwappedOperands(CC); 2820 } 2821 } 2822 2823 SDValue Cmp; 2824 AArch64CC::CondCode AArch64CC; 2825 if ((CC == ISD::SETEQ || CC == ISD::SETNE) && isa<ConstantSDNode>(RHS)) { 2826 const ConstantSDNode *RHSC = cast<ConstantSDNode>(RHS); 2827 2828 // The imm operand of ADDS is an unsigned immediate, in the range 0 to 4095. 2829 // For the i8 operand, the largest immediate is 255, so this can be easily 2830 // encoded in the compare instruction. For the i16 operand, however, the 2831 // largest immediate cannot be encoded in the compare. 2832 // Therefore, use a sign extending load and cmn to avoid materializing the 2833 // -1 constant. For example, 2834 // movz w1, #65535 2835 // ldrh w0, [x0, #0] 2836 // cmp w0, w1 2837 // > 2838 // ldrsh w0, [x0, #0] 2839 // cmn w0, #1 2840 // Fundamental, we're relying on the property that (zext LHS) == (zext RHS) 2841 // if and only if (sext LHS) == (sext RHS). The checks are in place to 2842 // ensure both the LHS and RHS are truly zero extended and to make sure the 2843 // transformation is profitable. 2844 if ((RHSC->getZExtValue() >> 16 == 0) && isa<LoadSDNode>(LHS) && 2845 cast<LoadSDNode>(LHS)->getExtensionType() == ISD::ZEXTLOAD && 2846 cast<LoadSDNode>(LHS)->getMemoryVT() == MVT::i16 && 2847 LHS.getNode()->hasNUsesOfValue(1, 0)) { 2848 int16_t ValueofRHS = cast<ConstantSDNode>(RHS)->getZExtValue(); 2849 if (ValueofRHS < 0 && isLegalArithImmed(-ValueofRHS)) { 2850 SDValue SExt = 2851 DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, LHS.getValueType(), LHS, 2852 DAG.getValueType(MVT::i16)); 2853 Cmp = emitComparison(SExt, DAG.getConstant(ValueofRHS, dl, 2854 RHS.getValueType()), 2855 CC, dl, DAG); 2856 AArch64CC = changeIntCCToAArch64CC(CC); 2857 } 2858 } 2859 2860 if (!Cmp && (RHSC->isNullValue() || RHSC->isOne())) { 2861 if ((Cmp = emitConjunction(DAG, LHS, AArch64CC))) { 2862 if ((CC == ISD::SETNE) ^ RHSC->isNullValue()) 2863 AArch64CC = AArch64CC::getInvertedCondCode(AArch64CC); 2864 } 2865 } 2866 } 2867 2868 if (!Cmp) { 2869 Cmp = emitComparison(LHS, RHS, CC, dl, DAG); 2870 AArch64CC = changeIntCCToAArch64CC(CC); 2871 } 2872 AArch64cc = DAG.getConstant(AArch64CC, dl, MVT_CC); 2873 return Cmp; 2874 } 2875 2876 static std::pair<SDValue, SDValue> 2877 getAArch64XALUOOp(AArch64CC::CondCode &CC, SDValue Op, SelectionDAG &DAG) { 2878 assert((Op.getValueType() == MVT::i32 || Op.getValueType() == MVT::i64) && 2879 "Unsupported value type"); 2880 SDValue Value, Overflow; 2881 SDLoc DL(Op); 2882 SDValue LHS = Op.getOperand(0); 2883 SDValue RHS = Op.getOperand(1); 2884 unsigned Opc = 0; 2885 switch (Op.getOpcode()) { 2886 default: 2887 llvm_unreachable("Unknown overflow instruction!"); 2888 case ISD::SADDO: 2889 Opc = AArch64ISD::ADDS; 2890 CC = AArch64CC::VS; 2891 break; 2892 case ISD::UADDO: 2893 Opc = AArch64ISD::ADDS; 2894 CC = AArch64CC::HS; 2895 break; 2896 case ISD::SSUBO: 2897 Opc = AArch64ISD::SUBS; 2898 CC = AArch64CC::VS; 2899 break; 2900 case ISD::USUBO: 2901 Opc = AArch64ISD::SUBS; 2902 CC = AArch64CC::LO; 2903 break; 2904 // Multiply needs a little bit extra work. 2905 case ISD::SMULO: 2906 case ISD::UMULO: { 2907 CC = AArch64CC::NE; 2908 bool IsSigned = Op.getOpcode() == ISD::SMULO; 2909 if (Op.getValueType() == MVT::i32) { 2910 unsigned ExtendOpc = IsSigned ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND; 2911 // For a 32 bit multiply with overflow check we want the instruction 2912 // selector to generate a widening multiply (SMADDL/UMADDL). For that we 2913 // need to generate the following pattern: 2914 // (i64 add 0, (i64 mul (i64 sext|zext i32 %a), (i64 sext|zext i32 %b)) 2915 LHS = DAG.getNode(ExtendOpc, DL, MVT::i64, LHS); 2916 RHS = DAG.getNode(ExtendOpc, DL, MVT::i64, RHS); 2917 SDValue Mul = DAG.getNode(ISD::MUL, DL, MVT::i64, LHS, RHS); 2918 SDValue Add = DAG.getNode(ISD::ADD, DL, MVT::i64, Mul, 2919 DAG.getConstant(0, DL, MVT::i64)); 2920 // On AArch64 the upper 32 bits are always zero extended for a 32 bit 2921 // operation. We need to clear out the upper 32 bits, because we used a 2922 // widening multiply that wrote all 64 bits. In the end this should be a 2923 // noop. 2924 Value = DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Add); 2925 if (IsSigned) { 2926 // The signed overflow check requires more than just a simple check for 2927 // any bit set in the upper 32 bits of the result. These bits could be 2928 // just the sign bits of a negative number. To perform the overflow 2929 // check we have to arithmetic shift right the 32nd bit of the result by 2930 // 31 bits. Then we compare the result to the upper 32 bits. 2931 SDValue UpperBits = DAG.getNode(ISD::SRL, DL, MVT::i64, Add, 2932 DAG.getConstant(32, DL, MVT::i64)); 2933 UpperBits = DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, UpperBits); 2934 SDValue LowerBits = DAG.getNode(ISD::SRA, DL, MVT::i32, Value, 2935 DAG.getConstant(31, DL, MVT::i64)); 2936 // It is important that LowerBits is last, otherwise the arithmetic 2937 // shift will not be folded into the compare (SUBS). 2938 SDVTList VTs = DAG.getVTList(MVT::i32, MVT::i32); 2939 Overflow = DAG.getNode(AArch64ISD::SUBS, DL, VTs, UpperBits, LowerBits) 2940 .getValue(1); 2941 } else { 2942 // The overflow check for unsigned multiply is easy. We only need to 2943 // check if any of the upper 32 bits are set. This can be done with a 2944 // CMP (shifted register). For that we need to generate the following 2945 // pattern: 2946 // (i64 AArch64ISD::SUBS i64 0, (i64 srl i64 %Mul, i64 32) 2947 SDValue UpperBits = DAG.getNode(ISD::SRL, DL, MVT::i64, Mul, 2948 DAG.getConstant(32, DL, MVT::i64)); 2949 SDVTList VTs = DAG.getVTList(MVT::i64, MVT::i32); 2950 Overflow = 2951 DAG.getNode(AArch64ISD::SUBS, DL, VTs, 2952 DAG.getConstant(0, DL, MVT::i64), 2953 UpperBits).getValue(1); 2954 } 2955 break; 2956 } 2957 assert(Op.getValueType() == MVT::i64 && "Expected an i64 value type"); 2958 // For the 64 bit multiply 2959 Value = DAG.getNode(ISD::MUL, DL, MVT::i64, LHS, RHS); 2960 if (IsSigned) { 2961 SDValue UpperBits = DAG.getNode(ISD::MULHS, DL, MVT::i64, LHS, RHS); 2962 SDValue LowerBits = DAG.getNode(ISD::SRA, DL, MVT::i64, Value, 2963 DAG.getConstant(63, DL, MVT::i64)); 2964 // It is important that LowerBits is last, otherwise the arithmetic 2965 // shift will not be folded into the compare (SUBS). 2966 SDVTList VTs = DAG.getVTList(MVT::i64, MVT::i32); 2967 Overflow = DAG.getNode(AArch64ISD::SUBS, DL, VTs, UpperBits, LowerBits) 2968 .getValue(1); 2969 } else { 2970 SDValue UpperBits = DAG.getNode(ISD::MULHU, DL, MVT::i64, LHS, RHS); 2971 SDVTList VTs = DAG.getVTList(MVT::i64, MVT::i32); 2972 Overflow = 2973 DAG.getNode(AArch64ISD::SUBS, DL, VTs, 2974 DAG.getConstant(0, DL, MVT::i64), 2975 UpperBits).getValue(1); 2976 } 2977 break; 2978 } 2979 } // switch (...) 2980 2981 if (Opc) { 2982 SDVTList VTs = DAG.getVTList(Op->getValueType(0), MVT::i32); 2983 2984 // Emit the AArch64 operation with overflow check. 2985 Value = DAG.getNode(Opc, DL, VTs, LHS, RHS); 2986 Overflow = Value.getValue(1); 2987 } 2988 return std::make_pair(Value, Overflow); 2989 } 2990 2991 SDValue AArch64TargetLowering::LowerXOR(SDValue Op, SelectionDAG &DAG) const { 2992 if (useSVEForFixedLengthVectorVT(Op.getValueType())) 2993 return LowerToScalableOp(Op, DAG); 2994 2995 SDValue Sel = Op.getOperand(0); 2996 SDValue Other = Op.getOperand(1); 2997 SDLoc dl(Sel); 2998 2999 // If the operand is an overflow checking operation, invert the condition 3000 // code and kill the Not operation. I.e., transform: 3001 // (xor (overflow_op_bool, 1)) 3002 // --> 3003 // (csel 1, 0, invert(cc), overflow_op_bool) 3004 // ... which later gets transformed to just a cset instruction with an 3005 // inverted condition code, rather than a cset + eor sequence. 3006 if (isOneConstant(Other) && ISD::isOverflowIntrOpRes(Sel)) { 3007 // Only lower legal XALUO ops. 3008 if (!DAG.getTargetLoweringInfo().isTypeLegal(Sel->getValueType(0))) 3009 return SDValue(); 3010 3011 SDValue TVal = DAG.getConstant(1, dl, MVT::i32); 3012 SDValue FVal = DAG.getConstant(0, dl, MVT::i32); 3013 AArch64CC::CondCode CC; 3014 SDValue Value, Overflow; 3015 std::tie(Value, Overflow) = getAArch64XALUOOp(CC, Sel.getValue(0), DAG); 3016 SDValue CCVal = DAG.getConstant(getInvertedCondCode(CC), dl, MVT::i32); 3017 return DAG.getNode(AArch64ISD::CSEL, dl, Op.getValueType(), TVal, FVal, 3018 CCVal, Overflow); 3019 } 3020 // If neither operand is a SELECT_CC, give up. 3021 if (Sel.getOpcode() != ISD::SELECT_CC) 3022 std::swap(Sel, Other); 3023 if (Sel.getOpcode() != ISD::SELECT_CC) 3024 return Op; 3025 3026 // The folding we want to perform is: 3027 // (xor x, (select_cc a, b, cc, 0, -1) ) 3028 // --> 3029 // (csel x, (xor x, -1), cc ...) 3030 // 3031 // The latter will get matched to a CSINV instruction. 3032 3033 ISD::CondCode CC = cast<CondCodeSDNode>(Sel.getOperand(4))->get(); 3034 SDValue LHS = Sel.getOperand(0); 3035 SDValue RHS = Sel.getOperand(1); 3036 SDValue TVal = Sel.getOperand(2); 3037 SDValue FVal = Sel.getOperand(3); 3038 3039 // FIXME: This could be generalized to non-integer comparisons. 3040 if (LHS.getValueType() != MVT::i32 && LHS.getValueType() != MVT::i64) 3041 return Op; 3042 3043 ConstantSDNode *CFVal = dyn_cast<ConstantSDNode>(FVal); 3044 ConstantSDNode *CTVal = dyn_cast<ConstantSDNode>(TVal); 3045 3046 // The values aren't constants, this isn't the pattern we're looking for. 3047 if (!CFVal || !CTVal) 3048 return Op; 3049 3050 // We can commute the SELECT_CC by inverting the condition. This 3051 // might be needed to make this fit into a CSINV pattern. 3052 if (CTVal->isAllOnesValue() && CFVal->isNullValue()) { 3053 std::swap(TVal, FVal); 3054 std::swap(CTVal, CFVal); 3055 CC = ISD::getSetCCInverse(CC, LHS.getValueType()); 3056 } 3057 3058 // If the constants line up, perform the transform! 3059 if (CTVal->isNullValue() && CFVal->isAllOnesValue()) { 3060 SDValue CCVal; 3061 SDValue Cmp = getAArch64Cmp(LHS, RHS, CC, CCVal, DAG, dl); 3062 3063 FVal = Other; 3064 TVal = DAG.getNode(ISD::XOR, dl, Other.getValueType(), Other, 3065 DAG.getConstant(-1ULL, dl, Other.getValueType())); 3066 3067 return DAG.getNode(AArch64ISD::CSEL, dl, Sel.getValueType(), FVal, TVal, 3068 CCVal, Cmp); 3069 } 3070 3071 return Op; 3072 } 3073 3074 static SDValue LowerADDC_ADDE_SUBC_SUBE(SDValue Op, SelectionDAG &DAG) { 3075 EVT VT = Op.getValueType(); 3076 3077 // Let legalize expand this if it isn't a legal type yet. 3078 if (!DAG.getTargetLoweringInfo().isTypeLegal(VT)) 3079 return SDValue(); 3080 3081 SDVTList VTs = DAG.getVTList(VT, MVT::i32); 3082 3083 unsigned Opc; 3084 bool ExtraOp = false; 3085 switch (Op.getOpcode()) { 3086 default: 3087 llvm_unreachable("Invalid code"); 3088 case ISD::ADDC: 3089 Opc = AArch64ISD::ADDS; 3090 break; 3091 case ISD::SUBC: 3092 Opc = AArch64ISD::SUBS; 3093 break; 3094 case ISD::ADDE: 3095 Opc = AArch64ISD::ADCS; 3096 ExtraOp = true; 3097 break; 3098 case ISD::SUBE: 3099 Opc = AArch64ISD::SBCS; 3100 ExtraOp = true; 3101 break; 3102 } 3103 3104 if (!ExtraOp) 3105 return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0), Op.getOperand(1)); 3106 return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0), Op.getOperand(1), 3107 Op.getOperand(2)); 3108 } 3109 3110 static SDValue LowerXALUO(SDValue Op, SelectionDAG &DAG) { 3111 // Let legalize expand this if it isn't a legal type yet. 3112 if (!DAG.getTargetLoweringInfo().isTypeLegal(Op.getValueType())) 3113 return SDValue(); 3114 3115 SDLoc dl(Op); 3116 AArch64CC::CondCode CC; 3117 // The actual operation that sets the overflow or carry flag. 3118 SDValue Value, Overflow; 3119 std::tie(Value, Overflow) = getAArch64XALUOOp(CC, Op, DAG); 3120 3121 // We use 0 and 1 as false and true values. 3122 SDValue TVal = DAG.getConstant(1, dl, MVT::i32); 3123 SDValue FVal = DAG.getConstant(0, dl, MVT::i32); 3124 3125 // We use an inverted condition, because the conditional select is inverted 3126 // too. This will allow it to be selected to a single instruction: 3127 // CSINC Wd, WZR, WZR, invert(cond). 3128 SDValue CCVal = DAG.getConstant(getInvertedCondCode(CC), dl, MVT::i32); 3129 Overflow = DAG.getNode(AArch64ISD::CSEL, dl, MVT::i32, FVal, TVal, 3130 CCVal, Overflow); 3131 3132 SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32); 3133 return DAG.getNode(ISD::MERGE_VALUES, dl, VTs, Value, Overflow); 3134 } 3135 3136 // Prefetch operands are: 3137 // 1: Address to prefetch 3138 // 2: bool isWrite 3139 // 3: int locality (0 = no locality ... 3 = extreme locality) 3140 // 4: bool isDataCache 3141 static SDValue LowerPREFETCH(SDValue Op, SelectionDAG &DAG) { 3142 SDLoc DL(Op); 3143 unsigned IsWrite = cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue(); 3144 unsigned Locality = cast<ConstantSDNode>(Op.getOperand(3))->getZExtValue(); 3145 unsigned IsData = cast<ConstantSDNode>(Op.getOperand(4))->getZExtValue(); 3146 3147 bool IsStream = !Locality; 3148 // When the locality number is set 3149 if (Locality) { 3150 // The front-end should have filtered out the out-of-range values 3151 assert(Locality <= 3 && "Prefetch locality out-of-range"); 3152 // The locality degree is the opposite of the cache speed. 3153 // Put the number the other way around. 3154 // The encoding starts at 0 for level 1 3155 Locality = 3 - Locality; 3156 } 3157 3158 // built the mask value encoding the expected behavior. 3159 unsigned PrfOp = (IsWrite << 4) | // Load/Store bit 3160 (!IsData << 3) | // IsDataCache bit 3161 (Locality << 1) | // Cache level bits 3162 (unsigned)IsStream; // Stream bit 3163 return DAG.getNode(AArch64ISD::PREFETCH, DL, MVT::Other, Op.getOperand(0), 3164 DAG.getConstant(PrfOp, DL, MVT::i32), Op.getOperand(1)); 3165 } 3166 3167 SDValue AArch64TargetLowering::LowerFP_EXTEND(SDValue Op, 3168 SelectionDAG &DAG) const { 3169 if (Op.getValueType().isScalableVector()) 3170 return LowerToPredicatedOp(Op, DAG, AArch64ISD::FP_EXTEND_MERGE_PASSTHRU); 3171 3172 assert(Op.getValueType() == MVT::f128 && "Unexpected lowering"); 3173 return SDValue(); 3174 } 3175 3176 SDValue AArch64TargetLowering::LowerFP_ROUND(SDValue Op, 3177 SelectionDAG &DAG) const { 3178 if (Op.getValueType().isScalableVector()) 3179 return LowerToPredicatedOp(Op, DAG, AArch64ISD::FP_ROUND_MERGE_PASSTHRU); 3180 3181 bool IsStrict = Op->isStrictFPOpcode(); 3182 SDValue SrcVal = Op.getOperand(IsStrict ? 1 : 0); 3183 EVT SrcVT = SrcVal.getValueType(); 3184 3185 if (SrcVT != MVT::f128) { 3186 // Expand cases where the input is a vector bigger than NEON. 3187 if (useSVEForFixedLengthVectorVT(SrcVT)) 3188 return SDValue(); 3189 3190 // It's legal except when f128 is involved 3191 return Op; 3192 } 3193 3194 return SDValue(); 3195 } 3196 3197 SDValue AArch64TargetLowering::LowerVectorFP_TO_INT(SDValue Op, 3198 SelectionDAG &DAG) const { 3199 // Warning: We maintain cost tables in AArch64TargetTransformInfo.cpp. 3200 // Any additional optimization in this function should be recorded 3201 // in the cost tables. 3202 EVT InVT = Op.getOperand(0).getValueType(); 3203 EVT VT = Op.getValueType(); 3204 3205 if (VT.isScalableVector()) { 3206 unsigned Opcode = Op.getOpcode() == ISD::FP_TO_UINT 3207 ? AArch64ISD::FCVTZU_MERGE_PASSTHRU 3208 : AArch64ISD::FCVTZS_MERGE_PASSTHRU; 3209 return LowerToPredicatedOp(Op, DAG, Opcode); 3210 } 3211 3212 unsigned NumElts = InVT.getVectorNumElements(); 3213 3214 // f16 conversions are promoted to f32 when full fp16 is not supported. 3215 if (InVT.getVectorElementType() == MVT::f16 && 3216 !Subtarget->hasFullFP16()) { 3217 MVT NewVT = MVT::getVectorVT(MVT::f32, NumElts); 3218 SDLoc dl(Op); 3219 return DAG.getNode( 3220 Op.getOpcode(), dl, Op.getValueType(), 3221 DAG.getNode(ISD::FP_EXTEND, dl, NewVT, Op.getOperand(0))); 3222 } 3223 3224 uint64_t VTSize = VT.getFixedSizeInBits(); 3225 uint64_t InVTSize = InVT.getFixedSizeInBits(); 3226 if (VTSize < InVTSize) { 3227 SDLoc dl(Op); 3228 SDValue Cv = 3229 DAG.getNode(Op.getOpcode(), dl, InVT.changeVectorElementTypeToInteger(), 3230 Op.getOperand(0)); 3231 return DAG.getNode(ISD::TRUNCATE, dl, VT, Cv); 3232 } 3233 3234 if (VTSize > InVTSize) { 3235 SDLoc dl(Op); 3236 MVT ExtVT = 3237 MVT::getVectorVT(MVT::getFloatingPointVT(VT.getScalarSizeInBits()), 3238 VT.getVectorNumElements()); 3239 SDValue Ext = DAG.getNode(ISD::FP_EXTEND, dl, ExtVT, Op.getOperand(0)); 3240 return DAG.getNode(Op.getOpcode(), dl, VT, Ext); 3241 } 3242 3243 // Type changing conversions are illegal. 3244 return Op; 3245 } 3246 3247 SDValue AArch64TargetLowering::LowerFP_TO_INT(SDValue Op, 3248 SelectionDAG &DAG) const { 3249 bool IsStrict = Op->isStrictFPOpcode(); 3250 SDValue SrcVal = Op.getOperand(IsStrict ? 1 : 0); 3251 3252 if (SrcVal.getValueType().isVector()) 3253 return LowerVectorFP_TO_INT(Op, DAG); 3254 3255 // f16 conversions are promoted to f32 when full fp16 is not supported. 3256 if (SrcVal.getValueType() == MVT::f16 && !Subtarget->hasFullFP16()) { 3257 assert(!IsStrict && "Lowering of strict fp16 not yet implemented"); 3258 SDLoc dl(Op); 3259 return DAG.getNode( 3260 Op.getOpcode(), dl, Op.getValueType(), 3261 DAG.getNode(ISD::FP_EXTEND, dl, MVT::f32, SrcVal)); 3262 } 3263 3264 if (SrcVal.getValueType() != MVT::f128) { 3265 // It's legal except when f128 is involved 3266 return Op; 3267 } 3268 3269 return SDValue(); 3270 } 3271 3272 SDValue AArch64TargetLowering::LowerVectorINT_TO_FP(SDValue Op, 3273 SelectionDAG &DAG) const { 3274 // Warning: We maintain cost tables in AArch64TargetTransformInfo.cpp. 3275 // Any additional optimization in this function should be recorded 3276 // in the cost tables. 3277 EVT VT = Op.getValueType(); 3278 SDLoc dl(Op); 3279 SDValue In = Op.getOperand(0); 3280 EVT InVT = In.getValueType(); 3281 unsigned Opc = Op.getOpcode(); 3282 bool IsSigned = Opc == ISD::SINT_TO_FP || Opc == ISD::STRICT_SINT_TO_FP; 3283 3284 if (VT.isScalableVector()) { 3285 if (InVT.getVectorElementType() == MVT::i1) { 3286 // We can't directly extend an SVE predicate; extend it first. 3287 unsigned CastOpc = IsSigned ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND; 3288 EVT CastVT = getPromotedVTForPredicate(InVT); 3289 In = DAG.getNode(CastOpc, dl, CastVT, In); 3290 return DAG.getNode(Opc, dl, VT, In); 3291 } 3292 3293 unsigned Opcode = IsSigned ? AArch64ISD::SINT_TO_FP_MERGE_PASSTHRU 3294 : AArch64ISD::UINT_TO_FP_MERGE_PASSTHRU; 3295 return LowerToPredicatedOp(Op, DAG, Opcode); 3296 } 3297 3298 uint64_t VTSize = VT.getFixedSizeInBits(); 3299 uint64_t InVTSize = InVT.getFixedSizeInBits(); 3300 if (VTSize < InVTSize) { 3301 MVT CastVT = 3302 MVT::getVectorVT(MVT::getFloatingPointVT(InVT.getScalarSizeInBits()), 3303 InVT.getVectorNumElements()); 3304 In = DAG.getNode(Opc, dl, CastVT, In); 3305 return DAG.getNode(ISD::FP_ROUND, dl, VT, In, DAG.getIntPtrConstant(0, dl)); 3306 } 3307 3308 if (VTSize > InVTSize) { 3309 unsigned CastOpc = IsSigned ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND; 3310 EVT CastVT = VT.changeVectorElementTypeToInteger(); 3311 In = DAG.getNode(CastOpc, dl, CastVT, In); 3312 return DAG.getNode(Opc, dl, VT, In); 3313 } 3314 3315 return Op; 3316 } 3317 3318 SDValue AArch64TargetLowering::LowerINT_TO_FP(SDValue Op, 3319 SelectionDAG &DAG) const { 3320 if (Op.getValueType().isVector()) 3321 return LowerVectorINT_TO_FP(Op, DAG); 3322 3323 bool IsStrict = Op->isStrictFPOpcode(); 3324 SDValue SrcVal = Op.getOperand(IsStrict ? 1 : 0); 3325 3326 // f16 conversions are promoted to f32 when full fp16 is not supported. 3327 if (Op.getValueType() == MVT::f16 && 3328 !Subtarget->hasFullFP16()) { 3329 assert(!IsStrict && "Lowering of strict fp16 not yet implemented"); 3330 SDLoc dl(Op); 3331 return DAG.getNode( 3332 ISD::FP_ROUND, dl, MVT::f16, 3333 DAG.getNode(Op.getOpcode(), dl, MVT::f32, SrcVal), 3334 DAG.getIntPtrConstant(0, dl)); 3335 } 3336 3337 // i128 conversions are libcalls. 3338 if (SrcVal.getValueType() == MVT::i128) 3339 return SDValue(); 3340 3341 // Other conversions are legal, unless it's to the completely software-based 3342 // fp128. 3343 if (Op.getValueType() != MVT::f128) 3344 return Op; 3345 return SDValue(); 3346 } 3347 3348 SDValue AArch64TargetLowering::LowerFSINCOS(SDValue Op, 3349 SelectionDAG &DAG) const { 3350 // For iOS, we want to call an alternative entry point: __sincos_stret, 3351 // which returns the values in two S / D registers. 3352 SDLoc dl(Op); 3353 SDValue Arg = Op.getOperand(0); 3354 EVT ArgVT = Arg.getValueType(); 3355 Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext()); 3356 3357 ArgListTy Args; 3358 ArgListEntry Entry; 3359 3360 Entry.Node = Arg; 3361 Entry.Ty = ArgTy; 3362 Entry.IsSExt = false; 3363 Entry.IsZExt = false; 3364 Args.push_back(Entry); 3365 3366 RTLIB::Libcall LC = ArgVT == MVT::f64 ? RTLIB::SINCOS_STRET_F64 3367 : RTLIB::SINCOS_STRET_F32; 3368 const char *LibcallName = getLibcallName(LC); 3369 SDValue Callee = 3370 DAG.getExternalSymbol(LibcallName, getPointerTy(DAG.getDataLayout())); 3371 3372 StructType *RetTy = StructType::get(ArgTy, ArgTy); 3373 TargetLowering::CallLoweringInfo CLI(DAG); 3374 CLI.setDebugLoc(dl) 3375 .setChain(DAG.getEntryNode()) 3376 .setLibCallee(CallingConv::Fast, RetTy, Callee, std::move(Args)); 3377 3378 std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI); 3379 return CallResult.first; 3380 } 3381 3382 static SDValue LowerBITCAST(SDValue Op, SelectionDAG &DAG) { 3383 EVT OpVT = Op.getValueType(); 3384 if (OpVT != MVT::f16 && OpVT != MVT::bf16) 3385 return SDValue(); 3386 3387 assert(Op.getOperand(0).getValueType() == MVT::i16); 3388 SDLoc DL(Op); 3389 3390 Op = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i32, Op.getOperand(0)); 3391 Op = DAG.getNode(ISD::BITCAST, DL, MVT::f32, Op); 3392 return SDValue( 3393 DAG.getMachineNode(TargetOpcode::EXTRACT_SUBREG, DL, OpVT, Op, 3394 DAG.getTargetConstant(AArch64::hsub, DL, MVT::i32)), 3395 0); 3396 } 3397 3398 static EVT getExtensionTo64Bits(const EVT &OrigVT) { 3399 if (OrigVT.getSizeInBits() >= 64) 3400 return OrigVT; 3401 3402 assert(OrigVT.isSimple() && "Expecting a simple value type"); 3403 3404 MVT::SimpleValueType OrigSimpleTy = OrigVT.getSimpleVT().SimpleTy; 3405 switch (OrigSimpleTy) { 3406 default: llvm_unreachable("Unexpected Vector Type"); 3407 case MVT::v2i8: 3408 case MVT::v2i16: 3409 return MVT::v2i32; 3410 case MVT::v4i8: 3411 return MVT::v4i16; 3412 } 3413 } 3414 3415 static SDValue addRequiredExtensionForVectorMULL(SDValue N, SelectionDAG &DAG, 3416 const EVT &OrigTy, 3417 const EVT &ExtTy, 3418 unsigned ExtOpcode) { 3419 // The vector originally had a size of OrigTy. It was then extended to ExtTy. 3420 // We expect the ExtTy to be 128-bits total. If the OrigTy is less than 3421 // 64-bits we need to insert a new extension so that it will be 64-bits. 3422 assert(ExtTy.is128BitVector() && "Unexpected extension size"); 3423 if (OrigTy.getSizeInBits() >= 64) 3424 return N; 3425 3426 // Must extend size to at least 64 bits to be used as an operand for VMULL. 3427 EVT NewVT = getExtensionTo64Bits(OrigTy); 3428 3429 return DAG.getNode(ExtOpcode, SDLoc(N), NewVT, N); 3430 } 3431 3432 static bool isExtendedBUILD_VECTOR(SDNode *N, SelectionDAG &DAG, 3433 bool isSigned) { 3434 EVT VT = N->getValueType(0); 3435 3436 if (N->getOpcode() != ISD::BUILD_VECTOR) 3437 return false; 3438 3439 for (const SDValue &Elt : N->op_values()) { 3440 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Elt)) { 3441 unsigned EltSize = VT.getScalarSizeInBits(); 3442 unsigned HalfSize = EltSize / 2; 3443 if (isSigned) { 3444 if (!isIntN(HalfSize, C->getSExtValue())) 3445 return false; 3446 } else { 3447 if (!isUIntN(HalfSize, C->getZExtValue())) 3448 return false; 3449 } 3450 continue; 3451 } 3452 return false; 3453 } 3454 3455 return true; 3456 } 3457 3458 static SDValue skipExtensionForVectorMULL(SDNode *N, SelectionDAG &DAG) { 3459 if (N->getOpcode() == ISD::SIGN_EXTEND || 3460 N->getOpcode() == ISD::ZERO_EXTEND || N->getOpcode() == ISD::ANY_EXTEND) 3461 return addRequiredExtensionForVectorMULL(N->getOperand(0), DAG, 3462 N->getOperand(0)->getValueType(0), 3463 N->getValueType(0), 3464 N->getOpcode()); 3465 3466 assert(N->getOpcode() == ISD::BUILD_VECTOR && "expected BUILD_VECTOR"); 3467 EVT VT = N->getValueType(0); 3468 SDLoc dl(N); 3469 unsigned EltSize = VT.getScalarSizeInBits() / 2; 3470 unsigned NumElts = VT.getVectorNumElements(); 3471 MVT TruncVT = MVT::getIntegerVT(EltSize); 3472 SmallVector<SDValue, 8> Ops; 3473 for (unsigned i = 0; i != NumElts; ++i) { 3474 ConstantSDNode *C = cast<ConstantSDNode>(N->getOperand(i)); 3475 const APInt &CInt = C->getAPIntValue(); 3476 // Element types smaller than 32 bits are not legal, so use i32 elements. 3477 // The values are implicitly truncated so sext vs. zext doesn't matter. 3478 Ops.push_back(DAG.getConstant(CInt.zextOrTrunc(32), dl, MVT::i32)); 3479 } 3480 return DAG.getBuildVector(MVT::getVectorVT(TruncVT, NumElts), dl, Ops); 3481 } 3482 3483 static bool isSignExtended(SDNode *N, SelectionDAG &DAG) { 3484 return N->getOpcode() == ISD::SIGN_EXTEND || 3485 N->getOpcode() == ISD::ANY_EXTEND || 3486 isExtendedBUILD_VECTOR(N, DAG, true); 3487 } 3488 3489 static bool isZeroExtended(SDNode *N, SelectionDAG &DAG) { 3490 return N->getOpcode() == ISD::ZERO_EXTEND || 3491 N->getOpcode() == ISD::ANY_EXTEND || 3492 isExtendedBUILD_VECTOR(N, DAG, false); 3493 } 3494 3495 static bool isAddSubSExt(SDNode *N, SelectionDAG &DAG) { 3496 unsigned Opcode = N->getOpcode(); 3497 if (Opcode == ISD::ADD || Opcode == ISD::SUB) { 3498 SDNode *N0 = N->getOperand(0).getNode(); 3499 SDNode *N1 = N->getOperand(1).getNode(); 3500 return N0->hasOneUse() && N1->hasOneUse() && 3501 isSignExtended(N0, DAG) && isSignExtended(N1, DAG); 3502 } 3503 return false; 3504 } 3505 3506 static bool isAddSubZExt(SDNode *N, SelectionDAG &DAG) { 3507 unsigned Opcode = N->getOpcode(); 3508 if (Opcode == ISD::ADD || Opcode == ISD::SUB) { 3509 SDNode *N0 = N->getOperand(0).getNode(); 3510 SDNode *N1 = N->getOperand(1).getNode(); 3511 return N0->hasOneUse() && N1->hasOneUse() && 3512 isZeroExtended(N0, DAG) && isZeroExtended(N1, DAG); 3513 } 3514 return false; 3515 } 3516 3517 SDValue AArch64TargetLowering::LowerFLT_ROUNDS_(SDValue Op, 3518 SelectionDAG &DAG) const { 3519 // The rounding mode is in bits 23:22 of the FPSCR. 3520 // The ARM rounding mode value to FLT_ROUNDS mapping is 0->1, 1->2, 2->3, 3->0 3521 // The formula we use to implement this is (((FPSCR + 1 << 22) >> 22) & 3) 3522 // so that the shift + and get folded into a bitfield extract. 3523 SDLoc dl(Op); 3524 3525 SDValue Chain = Op.getOperand(0); 3526 SDValue FPCR_64 = DAG.getNode( 3527 ISD::INTRINSIC_W_CHAIN, dl, {MVT::i64, MVT::Other}, 3528 {Chain, DAG.getConstant(Intrinsic::aarch64_get_fpcr, dl, MVT::i64)}); 3529 Chain = FPCR_64.getValue(1); 3530 SDValue FPCR_32 = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, FPCR_64); 3531 SDValue FltRounds = DAG.getNode(ISD::ADD, dl, MVT::i32, FPCR_32, 3532 DAG.getConstant(1U << 22, dl, MVT::i32)); 3533 SDValue RMODE = DAG.getNode(ISD::SRL, dl, MVT::i32, FltRounds, 3534 DAG.getConstant(22, dl, MVT::i32)); 3535 SDValue AND = DAG.getNode(ISD::AND, dl, MVT::i32, RMODE, 3536 DAG.getConstant(3, dl, MVT::i32)); 3537 return DAG.getMergeValues({AND, Chain}, dl); 3538 } 3539 3540 SDValue AArch64TargetLowering::LowerSET_ROUNDING(SDValue Op, 3541 SelectionDAG &DAG) const { 3542 SDLoc DL(Op); 3543 SDValue Chain = Op->getOperand(0); 3544 SDValue RMValue = Op->getOperand(1); 3545 3546 // The rounding mode is in bits 23:22 of the FPCR. 3547 // The llvm.set.rounding argument value to the rounding mode in FPCR mapping 3548 // is 0->3, 1->0, 2->1, 3->2. The formula we use to implement this is 3549 // ((arg - 1) & 3) << 22). 3550 // 3551 // The argument of llvm.set.rounding must be within the segment [0, 3], so 3552 // NearestTiesToAway (4) is not handled here. It is responsibility of the code 3553 // generated llvm.set.rounding to ensure this condition. 3554 3555 // Calculate new value of FPCR[23:22]. 3556 RMValue = DAG.getNode(ISD::SUB, DL, MVT::i32, RMValue, 3557 DAG.getConstant(1, DL, MVT::i32)); 3558 RMValue = DAG.getNode(ISD::AND, DL, MVT::i32, RMValue, 3559 DAG.getConstant(0x3, DL, MVT::i32)); 3560 RMValue = 3561 DAG.getNode(ISD::SHL, DL, MVT::i32, RMValue, 3562 DAG.getConstant(AArch64::RoundingBitsPos, DL, MVT::i32)); 3563 RMValue = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i64, RMValue); 3564 3565 // Get current value of FPCR. 3566 SDValue Ops[] = { 3567 Chain, DAG.getTargetConstant(Intrinsic::aarch64_get_fpcr, DL, MVT::i64)}; 3568 SDValue FPCR = 3569 DAG.getNode(ISD::INTRINSIC_W_CHAIN, DL, {MVT::i64, MVT::Other}, Ops); 3570 Chain = FPCR.getValue(1); 3571 FPCR = FPCR.getValue(0); 3572 3573 // Put new rounding mode into FPSCR[23:22]. 3574 const int RMMask = ~(AArch64::Rounding::rmMask << AArch64::RoundingBitsPos); 3575 FPCR = DAG.getNode(ISD::AND, DL, MVT::i64, FPCR, 3576 DAG.getConstant(RMMask, DL, MVT::i64)); 3577 FPCR = DAG.getNode(ISD::OR, DL, MVT::i64, FPCR, RMValue); 3578 SDValue Ops2[] = { 3579 Chain, DAG.getTargetConstant(Intrinsic::aarch64_set_fpcr, DL, MVT::i64), 3580 FPCR}; 3581 return DAG.getNode(ISD::INTRINSIC_VOID, DL, MVT::Other, Ops2); 3582 } 3583 3584 SDValue AArch64TargetLowering::LowerMUL(SDValue Op, SelectionDAG &DAG) const { 3585 EVT VT = Op.getValueType(); 3586 3587 // If SVE is available then i64 vector multiplications can also be made legal. 3588 bool OverrideNEON = VT == MVT::v2i64 || VT == MVT::v1i64; 3589 3590 if (VT.isScalableVector() || useSVEForFixedLengthVectorVT(VT, OverrideNEON)) 3591 return LowerToPredicatedOp(Op, DAG, AArch64ISD::MUL_PRED, OverrideNEON); 3592 3593 // Multiplications are only custom-lowered for 128-bit vectors so that 3594 // VMULL can be detected. Otherwise v2i64 multiplications are not legal. 3595 assert(VT.is128BitVector() && VT.isInteger() && 3596 "unexpected type for custom-lowering ISD::MUL"); 3597 SDNode *N0 = Op.getOperand(0).getNode(); 3598 SDNode *N1 = Op.getOperand(1).getNode(); 3599 unsigned NewOpc = 0; 3600 bool isMLA = false; 3601 bool isN0SExt = isSignExtended(N0, DAG); 3602 bool isN1SExt = isSignExtended(N1, DAG); 3603 if (isN0SExt && isN1SExt) 3604 NewOpc = AArch64ISD::SMULL; 3605 else { 3606 bool isN0ZExt = isZeroExtended(N0, DAG); 3607 bool isN1ZExt = isZeroExtended(N1, DAG); 3608 if (isN0ZExt && isN1ZExt) 3609 NewOpc = AArch64ISD::UMULL; 3610 else if (isN1SExt || isN1ZExt) { 3611 // Look for (s/zext A + s/zext B) * (s/zext C). We want to turn these 3612 // into (s/zext A * s/zext C) + (s/zext B * s/zext C) 3613 if (isN1SExt && isAddSubSExt(N0, DAG)) { 3614 NewOpc = AArch64ISD::SMULL; 3615 isMLA = true; 3616 } else if (isN1ZExt && isAddSubZExt(N0, DAG)) { 3617 NewOpc = AArch64ISD::UMULL; 3618 isMLA = true; 3619 } else if (isN0ZExt && isAddSubZExt(N1, DAG)) { 3620 std::swap(N0, N1); 3621 NewOpc = AArch64ISD::UMULL; 3622 isMLA = true; 3623 } 3624 } 3625 3626 if (!NewOpc) { 3627 if (VT == MVT::v2i64) 3628 // Fall through to expand this. It is not legal. 3629 return SDValue(); 3630 else 3631 // Other vector multiplications are legal. 3632 return Op; 3633 } 3634 } 3635 3636 // Legalize to a S/UMULL instruction 3637 SDLoc DL(Op); 3638 SDValue Op0; 3639 SDValue Op1 = skipExtensionForVectorMULL(N1, DAG); 3640 if (!isMLA) { 3641 Op0 = skipExtensionForVectorMULL(N0, DAG); 3642 assert(Op0.getValueType().is64BitVector() && 3643 Op1.getValueType().is64BitVector() && 3644 "unexpected types for extended operands to VMULL"); 3645 return DAG.getNode(NewOpc, DL, VT, Op0, Op1); 3646 } 3647 // Optimizing (zext A + zext B) * C, to (S/UMULL A, C) + (S/UMULL B, C) during 3648 // isel lowering to take advantage of no-stall back to back s/umul + s/umla. 3649 // This is true for CPUs with accumulate forwarding such as Cortex-A53/A57 3650 SDValue N00 = skipExtensionForVectorMULL(N0->getOperand(0).getNode(), DAG); 3651 SDValue N01 = skipExtensionForVectorMULL(N0->getOperand(1).getNode(), DAG); 3652 EVT Op1VT = Op1.getValueType(); 3653 return DAG.getNode(N0->getOpcode(), DL, VT, 3654 DAG.getNode(NewOpc, DL, VT, 3655 DAG.getNode(ISD::BITCAST, DL, Op1VT, N00), Op1), 3656 DAG.getNode(NewOpc, DL, VT, 3657 DAG.getNode(ISD::BITCAST, DL, Op1VT, N01), Op1)); 3658 } 3659 3660 static inline SDValue getPTrue(SelectionDAG &DAG, SDLoc DL, EVT VT, 3661 int Pattern) { 3662 return DAG.getNode(AArch64ISD::PTRUE, DL, VT, 3663 DAG.getTargetConstant(Pattern, DL, MVT::i32)); 3664 } 3665 3666 SDValue AArch64TargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op, 3667 SelectionDAG &DAG) const { 3668 unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue(); 3669 SDLoc dl(Op); 3670 switch (IntNo) { 3671 default: return SDValue(); // Don't custom lower most intrinsics. 3672 case Intrinsic::thread_pointer: { 3673 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 3674 return DAG.getNode(AArch64ISD::THREAD_POINTER, dl, PtrVT); 3675 } 3676 case Intrinsic::aarch64_neon_abs: { 3677 EVT Ty = Op.getValueType(); 3678 if (Ty == MVT::i64) { 3679 SDValue Result = DAG.getNode(ISD::BITCAST, dl, MVT::v1i64, 3680 Op.getOperand(1)); 3681 Result = DAG.getNode(ISD::ABS, dl, MVT::v1i64, Result); 3682 return DAG.getNode(ISD::BITCAST, dl, MVT::i64, Result); 3683 } else if (Ty.isVector() && Ty.isInteger() && isTypeLegal(Ty)) { 3684 return DAG.getNode(ISD::ABS, dl, Ty, Op.getOperand(1)); 3685 } else { 3686 report_fatal_error("Unexpected type for AArch64 NEON intrinic"); 3687 } 3688 } 3689 case Intrinsic::aarch64_neon_smax: 3690 return DAG.getNode(ISD::SMAX, dl, Op.getValueType(), 3691 Op.getOperand(1), Op.getOperand(2)); 3692 case Intrinsic::aarch64_neon_umax: 3693 return DAG.getNode(ISD::UMAX, dl, Op.getValueType(), 3694 Op.getOperand(1), Op.getOperand(2)); 3695 case Intrinsic::aarch64_neon_smin: 3696 return DAG.getNode(ISD::SMIN, dl, Op.getValueType(), 3697 Op.getOperand(1), Op.getOperand(2)); 3698 case Intrinsic::aarch64_neon_umin: 3699 return DAG.getNode(ISD::UMIN, dl, Op.getValueType(), 3700 Op.getOperand(1), Op.getOperand(2)); 3701 3702 case Intrinsic::aarch64_sve_sunpkhi: 3703 return DAG.getNode(AArch64ISD::SUNPKHI, dl, Op.getValueType(), 3704 Op.getOperand(1)); 3705 case Intrinsic::aarch64_sve_sunpklo: 3706 return DAG.getNode(AArch64ISD::SUNPKLO, dl, Op.getValueType(), 3707 Op.getOperand(1)); 3708 case Intrinsic::aarch64_sve_uunpkhi: 3709 return DAG.getNode(AArch64ISD::UUNPKHI, dl, Op.getValueType(), 3710 Op.getOperand(1)); 3711 case Intrinsic::aarch64_sve_uunpklo: 3712 return DAG.getNode(AArch64ISD::UUNPKLO, dl, Op.getValueType(), 3713 Op.getOperand(1)); 3714 case Intrinsic::aarch64_sve_clasta_n: 3715 return DAG.getNode(AArch64ISD::CLASTA_N, dl, Op.getValueType(), 3716 Op.getOperand(1), Op.getOperand(2), Op.getOperand(3)); 3717 case Intrinsic::aarch64_sve_clastb_n: 3718 return DAG.getNode(AArch64ISD::CLASTB_N, dl, Op.getValueType(), 3719 Op.getOperand(1), Op.getOperand(2), Op.getOperand(3)); 3720 case Intrinsic::aarch64_sve_lasta: 3721 return DAG.getNode(AArch64ISD::LASTA, dl, Op.getValueType(), 3722 Op.getOperand(1), Op.getOperand(2)); 3723 case Intrinsic::aarch64_sve_lastb: 3724 return DAG.getNode(AArch64ISD::LASTB, dl, Op.getValueType(), 3725 Op.getOperand(1), Op.getOperand(2)); 3726 case Intrinsic::aarch64_sve_rev: 3727 return DAG.getNode(ISD::VECTOR_REVERSE, dl, Op.getValueType(), 3728 Op.getOperand(1)); 3729 case Intrinsic::aarch64_sve_tbl: 3730 return DAG.getNode(AArch64ISD::TBL, dl, Op.getValueType(), 3731 Op.getOperand(1), Op.getOperand(2)); 3732 case Intrinsic::aarch64_sve_trn1: 3733 return DAG.getNode(AArch64ISD::TRN1, dl, Op.getValueType(), 3734 Op.getOperand(1), Op.getOperand(2)); 3735 case Intrinsic::aarch64_sve_trn2: 3736 return DAG.getNode(AArch64ISD::TRN2, dl, Op.getValueType(), 3737 Op.getOperand(1), Op.getOperand(2)); 3738 case Intrinsic::aarch64_sve_uzp1: 3739 return DAG.getNode(AArch64ISD::UZP1, dl, Op.getValueType(), 3740 Op.getOperand(1), Op.getOperand(2)); 3741 case Intrinsic::aarch64_sve_uzp2: 3742 return DAG.getNode(AArch64ISD::UZP2, dl, Op.getValueType(), 3743 Op.getOperand(1), Op.getOperand(2)); 3744 case Intrinsic::aarch64_sve_zip1: 3745 return DAG.getNode(AArch64ISD::ZIP1, dl, Op.getValueType(), 3746 Op.getOperand(1), Op.getOperand(2)); 3747 case Intrinsic::aarch64_sve_zip2: 3748 return DAG.getNode(AArch64ISD::ZIP2, dl, Op.getValueType(), 3749 Op.getOperand(1), Op.getOperand(2)); 3750 case Intrinsic::aarch64_sve_ptrue: 3751 return DAG.getNode(AArch64ISD::PTRUE, dl, Op.getValueType(), 3752 Op.getOperand(1)); 3753 case Intrinsic::aarch64_sve_clz: 3754 return DAG.getNode(AArch64ISD::CTLZ_MERGE_PASSTHRU, dl, Op.getValueType(), 3755 Op.getOperand(2), Op.getOperand(3), Op.getOperand(1)); 3756 case Intrinsic::aarch64_sve_cnt: { 3757 SDValue Data = Op.getOperand(3); 3758 // CTPOP only supports integer operands. 3759 if (Data.getValueType().isFloatingPoint()) 3760 Data = DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Data); 3761 return DAG.getNode(AArch64ISD::CTPOP_MERGE_PASSTHRU, dl, Op.getValueType(), 3762 Op.getOperand(2), Data, Op.getOperand(1)); 3763 } 3764 case Intrinsic::aarch64_sve_dupq_lane: 3765 return LowerDUPQLane(Op, DAG); 3766 case Intrinsic::aarch64_sve_convert_from_svbool: 3767 return DAG.getNode(AArch64ISD::REINTERPRET_CAST, dl, Op.getValueType(), 3768 Op.getOperand(1)); 3769 case Intrinsic::aarch64_sve_fneg: 3770 return DAG.getNode(AArch64ISD::FNEG_MERGE_PASSTHRU, dl, Op.getValueType(), 3771 Op.getOperand(2), Op.getOperand(3), Op.getOperand(1)); 3772 case Intrinsic::aarch64_sve_frintp: 3773 return DAG.getNode(AArch64ISD::FCEIL_MERGE_PASSTHRU, dl, Op.getValueType(), 3774 Op.getOperand(2), Op.getOperand(3), Op.getOperand(1)); 3775 case Intrinsic::aarch64_sve_frintm: 3776 return DAG.getNode(AArch64ISD::FFLOOR_MERGE_PASSTHRU, dl, Op.getValueType(), 3777 Op.getOperand(2), Op.getOperand(3), Op.getOperand(1)); 3778 case Intrinsic::aarch64_sve_frinti: 3779 return DAG.getNode(AArch64ISD::FNEARBYINT_MERGE_PASSTHRU, dl, Op.getValueType(), 3780 Op.getOperand(2), Op.getOperand(3), Op.getOperand(1)); 3781 case Intrinsic::aarch64_sve_frintx: 3782 return DAG.getNode(AArch64ISD::FRINT_MERGE_PASSTHRU, dl, Op.getValueType(), 3783 Op.getOperand(2), Op.getOperand(3), Op.getOperand(1)); 3784 case Intrinsic::aarch64_sve_frinta: 3785 return DAG.getNode(AArch64ISD::FROUND_MERGE_PASSTHRU, dl, Op.getValueType(), 3786 Op.getOperand(2), Op.getOperand(3), Op.getOperand(1)); 3787 case Intrinsic::aarch64_sve_frintn: 3788 return DAG.getNode(AArch64ISD::FROUNDEVEN_MERGE_PASSTHRU, dl, Op.getValueType(), 3789 Op.getOperand(2), Op.getOperand(3), Op.getOperand(1)); 3790 case Intrinsic::aarch64_sve_frintz: 3791 return DAG.getNode(AArch64ISD::FTRUNC_MERGE_PASSTHRU, dl, Op.getValueType(), 3792 Op.getOperand(2), Op.getOperand(3), Op.getOperand(1)); 3793 case Intrinsic::aarch64_sve_ucvtf: 3794 return DAG.getNode(AArch64ISD::UINT_TO_FP_MERGE_PASSTHRU, dl, 3795 Op.getValueType(), Op.getOperand(2), Op.getOperand(3), 3796 Op.getOperand(1)); 3797 case Intrinsic::aarch64_sve_scvtf: 3798 return DAG.getNode(AArch64ISD::SINT_TO_FP_MERGE_PASSTHRU, dl, 3799 Op.getValueType(), Op.getOperand(2), Op.getOperand(3), 3800 Op.getOperand(1)); 3801 case Intrinsic::aarch64_sve_fcvtzu: 3802 return DAG.getNode(AArch64ISD::FCVTZU_MERGE_PASSTHRU, dl, 3803 Op.getValueType(), Op.getOperand(2), Op.getOperand(3), 3804 Op.getOperand(1)); 3805 case Intrinsic::aarch64_sve_fcvtzs: 3806 return DAG.getNode(AArch64ISD::FCVTZS_MERGE_PASSTHRU, dl, 3807 Op.getValueType(), Op.getOperand(2), Op.getOperand(3), 3808 Op.getOperand(1)); 3809 case Intrinsic::aarch64_sve_fsqrt: 3810 return DAG.getNode(AArch64ISD::FSQRT_MERGE_PASSTHRU, dl, Op.getValueType(), 3811 Op.getOperand(2), Op.getOperand(3), Op.getOperand(1)); 3812 case Intrinsic::aarch64_sve_frecpx: 3813 return DAG.getNode(AArch64ISD::FRECPX_MERGE_PASSTHRU, dl, Op.getValueType(), 3814 Op.getOperand(2), Op.getOperand(3), Op.getOperand(1)); 3815 case Intrinsic::aarch64_sve_fabs: 3816 return DAG.getNode(AArch64ISD::FABS_MERGE_PASSTHRU, dl, Op.getValueType(), 3817 Op.getOperand(2), Op.getOperand(3), Op.getOperand(1)); 3818 case Intrinsic::aarch64_sve_abs: 3819 return DAG.getNode(AArch64ISD::ABS_MERGE_PASSTHRU, dl, Op.getValueType(), 3820 Op.getOperand(2), Op.getOperand(3), Op.getOperand(1)); 3821 case Intrinsic::aarch64_sve_neg: 3822 return DAG.getNode(AArch64ISD::NEG_MERGE_PASSTHRU, dl, Op.getValueType(), 3823 Op.getOperand(2), Op.getOperand(3), Op.getOperand(1)); 3824 case Intrinsic::aarch64_sve_convert_to_svbool: { 3825 EVT OutVT = Op.getValueType(); 3826 EVT InVT = Op.getOperand(1).getValueType(); 3827 // Return the operand if the cast isn't changing type, 3828 // i.e. <n x 16 x i1> -> <n x 16 x i1> 3829 if (InVT == OutVT) 3830 return Op.getOperand(1); 3831 // Otherwise, zero the newly introduced lanes. 3832 SDValue Reinterpret = 3833 DAG.getNode(AArch64ISD::REINTERPRET_CAST, dl, OutVT, Op.getOperand(1)); 3834 SDValue Mask = getPTrue(DAG, dl, InVT, AArch64SVEPredPattern::all); 3835 SDValue MaskReinterpret = 3836 DAG.getNode(AArch64ISD::REINTERPRET_CAST, dl, OutVT, Mask); 3837 return DAG.getNode(ISD::AND, dl, OutVT, Reinterpret, MaskReinterpret); 3838 } 3839 3840 case Intrinsic::aarch64_sve_insr: { 3841 SDValue Scalar = Op.getOperand(2); 3842 EVT ScalarTy = Scalar.getValueType(); 3843 if ((ScalarTy == MVT::i8) || (ScalarTy == MVT::i16)) 3844 Scalar = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, Scalar); 3845 3846 return DAG.getNode(AArch64ISD::INSR, dl, Op.getValueType(), 3847 Op.getOperand(1), Scalar); 3848 } 3849 case Intrinsic::aarch64_sve_rbit: 3850 return DAG.getNode(AArch64ISD::BITREVERSE_MERGE_PASSTHRU, dl, 3851 Op.getValueType(), Op.getOperand(2), Op.getOperand(3), 3852 Op.getOperand(1)); 3853 case Intrinsic::aarch64_sve_revb: 3854 return DAG.getNode(AArch64ISD::BSWAP_MERGE_PASSTHRU, dl, Op.getValueType(), 3855 Op.getOperand(2), Op.getOperand(3), Op.getOperand(1)); 3856 case Intrinsic::aarch64_sve_sxtb: 3857 return DAG.getNode( 3858 AArch64ISD::SIGN_EXTEND_INREG_MERGE_PASSTHRU, dl, Op.getValueType(), 3859 Op.getOperand(2), Op.getOperand(3), 3860 DAG.getValueType(Op.getValueType().changeVectorElementType(MVT::i8)), 3861 Op.getOperand(1)); 3862 case Intrinsic::aarch64_sve_sxth: 3863 return DAG.getNode( 3864 AArch64ISD::SIGN_EXTEND_INREG_MERGE_PASSTHRU, dl, Op.getValueType(), 3865 Op.getOperand(2), Op.getOperand(3), 3866 DAG.getValueType(Op.getValueType().changeVectorElementType(MVT::i16)), 3867 Op.getOperand(1)); 3868 case Intrinsic::aarch64_sve_sxtw: 3869 return DAG.getNode( 3870 AArch64ISD::SIGN_EXTEND_INREG_MERGE_PASSTHRU, dl, Op.getValueType(), 3871 Op.getOperand(2), Op.getOperand(3), 3872 DAG.getValueType(Op.getValueType().changeVectorElementType(MVT::i32)), 3873 Op.getOperand(1)); 3874 case Intrinsic::aarch64_sve_uxtb: 3875 return DAG.getNode( 3876 AArch64ISD::ZERO_EXTEND_INREG_MERGE_PASSTHRU, dl, Op.getValueType(), 3877 Op.getOperand(2), Op.getOperand(3), 3878 DAG.getValueType(Op.getValueType().changeVectorElementType(MVT::i8)), 3879 Op.getOperand(1)); 3880 case Intrinsic::aarch64_sve_uxth: 3881 return DAG.getNode( 3882 AArch64ISD::ZERO_EXTEND_INREG_MERGE_PASSTHRU, dl, Op.getValueType(), 3883 Op.getOperand(2), Op.getOperand(3), 3884 DAG.getValueType(Op.getValueType().changeVectorElementType(MVT::i16)), 3885 Op.getOperand(1)); 3886 case Intrinsic::aarch64_sve_uxtw: 3887 return DAG.getNode( 3888 AArch64ISD::ZERO_EXTEND_INREG_MERGE_PASSTHRU, dl, Op.getValueType(), 3889 Op.getOperand(2), Op.getOperand(3), 3890 DAG.getValueType(Op.getValueType().changeVectorElementType(MVT::i32)), 3891 Op.getOperand(1)); 3892 3893 case Intrinsic::localaddress: { 3894 const auto &MF = DAG.getMachineFunction(); 3895 const auto *RegInfo = Subtarget->getRegisterInfo(); 3896 unsigned Reg = RegInfo->getLocalAddressRegister(MF); 3897 return DAG.getCopyFromReg(DAG.getEntryNode(), dl, Reg, 3898 Op.getSimpleValueType()); 3899 } 3900 3901 case Intrinsic::eh_recoverfp: { 3902 // FIXME: This needs to be implemented to correctly handle highly aligned 3903 // stack objects. For now we simply return the incoming FP. Refer D53541 3904 // for more details. 3905 SDValue FnOp = Op.getOperand(1); 3906 SDValue IncomingFPOp = Op.getOperand(2); 3907 GlobalAddressSDNode *GSD = dyn_cast<GlobalAddressSDNode>(FnOp); 3908 auto *Fn = dyn_cast_or_null<Function>(GSD ? GSD->getGlobal() : nullptr); 3909 if (!Fn) 3910 report_fatal_error( 3911 "llvm.eh.recoverfp must take a function as the first argument"); 3912 return IncomingFPOp; 3913 } 3914 3915 case Intrinsic::aarch64_neon_vsri: 3916 case Intrinsic::aarch64_neon_vsli: { 3917 EVT Ty = Op.getValueType(); 3918 3919 if (!Ty.isVector()) 3920 report_fatal_error("Unexpected type for aarch64_neon_vsli"); 3921 3922 assert(Op.getConstantOperandVal(3) <= Ty.getScalarSizeInBits()); 3923 3924 bool IsShiftRight = IntNo == Intrinsic::aarch64_neon_vsri; 3925 unsigned Opcode = IsShiftRight ? AArch64ISD::VSRI : AArch64ISD::VSLI; 3926 return DAG.getNode(Opcode, dl, Ty, Op.getOperand(1), Op.getOperand(2), 3927 Op.getOperand(3)); 3928 } 3929 3930 case Intrinsic::aarch64_neon_srhadd: 3931 case Intrinsic::aarch64_neon_urhadd: 3932 case Intrinsic::aarch64_neon_shadd: 3933 case Intrinsic::aarch64_neon_uhadd: { 3934 bool IsSignedAdd = (IntNo == Intrinsic::aarch64_neon_srhadd || 3935 IntNo == Intrinsic::aarch64_neon_shadd); 3936 bool IsRoundingAdd = (IntNo == Intrinsic::aarch64_neon_srhadd || 3937 IntNo == Intrinsic::aarch64_neon_urhadd); 3938 unsigned Opcode = 3939 IsSignedAdd ? (IsRoundingAdd ? AArch64ISD::SRHADD : AArch64ISD::SHADD) 3940 : (IsRoundingAdd ? AArch64ISD::URHADD : AArch64ISD::UHADD); 3941 return DAG.getNode(Opcode, dl, Op.getValueType(), Op.getOperand(1), 3942 Op.getOperand(2)); 3943 } 3944 case Intrinsic::aarch64_neon_sabd: 3945 case Intrinsic::aarch64_neon_uabd: { 3946 unsigned Opcode = IntNo == Intrinsic::aarch64_neon_uabd ? AArch64ISD::UABD 3947 : AArch64ISD::SABD; 3948 return DAG.getNode(Opcode, dl, Op.getValueType(), Op.getOperand(1), 3949 Op.getOperand(2)); 3950 } 3951 case Intrinsic::aarch64_neon_sdot: 3952 case Intrinsic::aarch64_neon_udot: 3953 case Intrinsic::aarch64_sve_sdot: 3954 case Intrinsic::aarch64_sve_udot: { 3955 unsigned Opcode = (IntNo == Intrinsic::aarch64_neon_udot || 3956 IntNo == Intrinsic::aarch64_sve_udot) 3957 ? AArch64ISD::UDOT 3958 : AArch64ISD::SDOT; 3959 return DAG.getNode(Opcode, dl, Op.getValueType(), Op.getOperand(1), 3960 Op.getOperand(2), Op.getOperand(3)); 3961 } 3962 } 3963 } 3964 3965 bool AArch64TargetLowering::shouldExtendGSIndex(EVT VT, EVT &EltTy) const { 3966 if (VT.getVectorElementType() == MVT::i8 || 3967 VT.getVectorElementType() == MVT::i16) { 3968 EltTy = MVT::i32; 3969 return true; 3970 } 3971 return false; 3972 } 3973 3974 bool AArch64TargetLowering::shouldRemoveExtendFromGSIndex(EVT VT) const { 3975 if (VT.getVectorElementType() == MVT::i32 && 3976 VT.getVectorElementCount().getKnownMinValue() >= 4) 3977 return true; 3978 3979 return false; 3980 } 3981 3982 bool AArch64TargetLowering::isVectorLoadExtDesirable(SDValue ExtVal) const { 3983 return ExtVal.getValueType().isScalableVector(); 3984 } 3985 3986 unsigned getGatherVecOpcode(bool IsScaled, bool IsSigned, bool NeedsExtend) { 3987 std::map<std::tuple<bool, bool, bool>, unsigned> AddrModes = { 3988 {std::make_tuple(/*Scaled*/ false, /*Signed*/ false, /*Extend*/ false), 3989 AArch64ISD::GLD1_MERGE_ZERO}, 3990 {std::make_tuple(/*Scaled*/ false, /*Signed*/ false, /*Extend*/ true), 3991 AArch64ISD::GLD1_UXTW_MERGE_ZERO}, 3992 {std::make_tuple(/*Scaled*/ false, /*Signed*/ true, /*Extend*/ false), 3993 AArch64ISD::GLD1_MERGE_ZERO}, 3994 {std::make_tuple(/*Scaled*/ false, /*Signed*/ true, /*Extend*/ true), 3995 AArch64ISD::GLD1_SXTW_MERGE_ZERO}, 3996 {std::make_tuple(/*Scaled*/ true, /*Signed*/ false, /*Extend*/ false), 3997 AArch64ISD::GLD1_SCALED_MERGE_ZERO}, 3998 {std::make_tuple(/*Scaled*/ true, /*Signed*/ false, /*Extend*/ true), 3999 AArch64ISD::GLD1_UXTW_SCALED_MERGE_ZERO}, 4000 {std::make_tuple(/*Scaled*/ true, /*Signed*/ true, /*Extend*/ false), 4001 AArch64ISD::GLD1_SCALED_MERGE_ZERO}, 4002 {std::make_tuple(/*Scaled*/ true, /*Signed*/ true, /*Extend*/ true), 4003 AArch64ISD::GLD1_SXTW_SCALED_MERGE_ZERO}, 4004 }; 4005 auto Key = std::make_tuple(IsScaled, IsSigned, NeedsExtend); 4006 return AddrModes.find(Key)->second; 4007 } 4008 4009 unsigned getScatterVecOpcode(bool IsScaled, bool IsSigned, bool NeedsExtend) { 4010 std::map<std::tuple<bool, bool, bool>, unsigned> AddrModes = { 4011 {std::make_tuple(/*Scaled*/ false, /*Signed*/ false, /*Extend*/ false), 4012 AArch64ISD::SST1_PRED}, 4013 {std::make_tuple(/*Scaled*/ false, /*Signed*/ false, /*Extend*/ true), 4014 AArch64ISD::SST1_UXTW_PRED}, 4015 {std::make_tuple(/*Scaled*/ false, /*Signed*/ true, /*Extend*/ false), 4016 AArch64ISD::SST1_PRED}, 4017 {std::make_tuple(/*Scaled*/ false, /*Signed*/ true, /*Extend*/ true), 4018 AArch64ISD::SST1_SXTW_PRED}, 4019 {std::make_tuple(/*Scaled*/ true, /*Signed*/ false, /*Extend*/ false), 4020 AArch64ISD::SST1_SCALED_PRED}, 4021 {std::make_tuple(/*Scaled*/ true, /*Signed*/ false, /*Extend*/ true), 4022 AArch64ISD::SST1_UXTW_SCALED_PRED}, 4023 {std::make_tuple(/*Scaled*/ true, /*Signed*/ true, /*Extend*/ false), 4024 AArch64ISD::SST1_SCALED_PRED}, 4025 {std::make_tuple(/*Scaled*/ true, /*Signed*/ true, /*Extend*/ true), 4026 AArch64ISD::SST1_SXTW_SCALED_PRED}, 4027 }; 4028 auto Key = std::make_tuple(IsScaled, IsSigned, NeedsExtend); 4029 return AddrModes.find(Key)->second; 4030 } 4031 4032 unsigned getSignExtendedGatherOpcode(unsigned Opcode) { 4033 switch (Opcode) { 4034 default: 4035 llvm_unreachable("unimplemented opcode"); 4036 return Opcode; 4037 case AArch64ISD::GLD1_MERGE_ZERO: 4038 return AArch64ISD::GLD1S_MERGE_ZERO; 4039 case AArch64ISD::GLD1_IMM_MERGE_ZERO: 4040 return AArch64ISD::GLD1S_IMM_MERGE_ZERO; 4041 case AArch64ISD::GLD1_UXTW_MERGE_ZERO: 4042 return AArch64ISD::GLD1S_UXTW_MERGE_ZERO; 4043 case AArch64ISD::GLD1_SXTW_MERGE_ZERO: 4044 return AArch64ISD::GLD1S_SXTW_MERGE_ZERO; 4045 case AArch64ISD::GLD1_SCALED_MERGE_ZERO: 4046 return AArch64ISD::GLD1S_SCALED_MERGE_ZERO; 4047 case AArch64ISD::GLD1_UXTW_SCALED_MERGE_ZERO: 4048 return AArch64ISD::GLD1S_UXTW_SCALED_MERGE_ZERO; 4049 case AArch64ISD::GLD1_SXTW_SCALED_MERGE_ZERO: 4050 return AArch64ISD::GLD1S_SXTW_SCALED_MERGE_ZERO; 4051 } 4052 } 4053 4054 bool getGatherScatterIndexIsExtended(SDValue Index) { 4055 unsigned Opcode = Index.getOpcode(); 4056 if (Opcode == ISD::SIGN_EXTEND_INREG) 4057 return true; 4058 4059 if (Opcode == ISD::AND) { 4060 SDValue Splat = Index.getOperand(1); 4061 if (Splat.getOpcode() != ISD::SPLAT_VECTOR) 4062 return false; 4063 ConstantSDNode *Mask = dyn_cast<ConstantSDNode>(Splat.getOperand(0)); 4064 if (!Mask || Mask->getZExtValue() != 0xFFFFFFFF) 4065 return false; 4066 return true; 4067 } 4068 4069 return false; 4070 } 4071 4072 // If the base pointer of a masked gather or scatter is null, we 4073 // may be able to swap BasePtr & Index and use the vector + register 4074 // or vector + immediate addressing mode, e.g. 4075 // VECTOR + REGISTER: 4076 // getelementptr nullptr, <vscale x N x T> (splat(%offset)) + %indices) 4077 // -> getelementptr %offset, <vscale x N x T> %indices 4078 // VECTOR + IMMEDIATE: 4079 // getelementptr nullptr, <vscale x N x T> (splat(#x)) + %indices) 4080 // -> getelementptr #x, <vscale x N x T> %indices 4081 void selectGatherScatterAddrMode(SDValue &BasePtr, SDValue &Index, EVT MemVT, 4082 unsigned &Opcode, bool IsGather, 4083 SelectionDAG &DAG) { 4084 if (!isNullConstant(BasePtr)) 4085 return; 4086 4087 ConstantSDNode *Offset = nullptr; 4088 if (Index.getOpcode() == ISD::ADD) 4089 if (auto SplatVal = DAG.getSplatValue(Index.getOperand(1))) { 4090 if (isa<ConstantSDNode>(SplatVal)) 4091 Offset = cast<ConstantSDNode>(SplatVal); 4092 else { 4093 BasePtr = SplatVal; 4094 Index = Index->getOperand(0); 4095 return; 4096 } 4097 } 4098 4099 unsigned NewOp = 4100 IsGather ? AArch64ISD::GLD1_IMM_MERGE_ZERO : AArch64ISD::SST1_IMM_PRED; 4101 4102 if (!Offset) { 4103 std::swap(BasePtr, Index); 4104 Opcode = NewOp; 4105 return; 4106 } 4107 4108 uint64_t OffsetVal = Offset->getZExtValue(); 4109 unsigned ScalarSizeInBytes = MemVT.getScalarSizeInBits() / 8; 4110 auto ConstOffset = DAG.getConstant(OffsetVal, SDLoc(Index), MVT::i64); 4111 4112 if (OffsetVal % ScalarSizeInBytes || OffsetVal / ScalarSizeInBytes > 31) { 4113 // Index is out of range for the immediate addressing mode 4114 BasePtr = ConstOffset; 4115 Index = Index->getOperand(0); 4116 return; 4117 } 4118 4119 // Immediate is in range 4120 Opcode = NewOp; 4121 BasePtr = Index->getOperand(0); 4122 Index = ConstOffset; 4123 } 4124 4125 SDValue AArch64TargetLowering::LowerMGATHER(SDValue Op, 4126 SelectionDAG &DAG) const { 4127 SDLoc DL(Op); 4128 MaskedGatherSDNode *MGT = cast<MaskedGatherSDNode>(Op); 4129 assert(MGT && "Can only custom lower gather load nodes"); 4130 4131 SDValue Index = MGT->getIndex(); 4132 SDValue Chain = MGT->getChain(); 4133 SDValue PassThru = MGT->getPassThru(); 4134 SDValue Mask = MGT->getMask(); 4135 SDValue BasePtr = MGT->getBasePtr(); 4136 ISD::LoadExtType ExtTy = MGT->getExtensionType(); 4137 4138 ISD::MemIndexType IndexType = MGT->getIndexType(); 4139 bool IsScaled = 4140 IndexType == ISD::SIGNED_SCALED || IndexType == ISD::UNSIGNED_SCALED; 4141 bool IsSigned = 4142 IndexType == ISD::SIGNED_SCALED || IndexType == ISD::SIGNED_UNSCALED; 4143 bool IdxNeedsExtend = 4144 getGatherScatterIndexIsExtended(Index) || 4145 Index.getSimpleValueType().getVectorElementType() == MVT::i32; 4146 bool ResNeedsSignExtend = ExtTy == ISD::EXTLOAD || ExtTy == ISD::SEXTLOAD; 4147 4148 EVT VT = PassThru.getSimpleValueType(); 4149 EVT MemVT = MGT->getMemoryVT(); 4150 SDValue InputVT = DAG.getValueType(MemVT); 4151 4152 if (VT.getVectorElementType() == MVT::bf16 && 4153 !static_cast<const AArch64Subtarget &>(DAG.getSubtarget()).hasBF16()) 4154 return SDValue(); 4155 4156 // Handle FP data by using an integer gather and casting the result. 4157 if (VT.isFloatingPoint()) { 4158 EVT PassThruVT = getPackedSVEVectorVT(VT.getVectorElementCount()); 4159 PassThru = getSVESafeBitCast(PassThruVT, PassThru, DAG); 4160 InputVT = DAG.getValueType(MemVT.changeVectorElementTypeToInteger()); 4161 } 4162 4163 SDVTList VTs = DAG.getVTList(PassThru.getSimpleValueType(), MVT::Other); 4164 4165 if (getGatherScatterIndexIsExtended(Index)) 4166 Index = Index.getOperand(0); 4167 4168 unsigned Opcode = getGatherVecOpcode(IsScaled, IsSigned, IdxNeedsExtend); 4169 selectGatherScatterAddrMode(BasePtr, Index, MemVT, Opcode, 4170 /*isGather=*/true, DAG); 4171 4172 if (ResNeedsSignExtend) 4173 Opcode = getSignExtendedGatherOpcode(Opcode); 4174 4175 SDValue Ops[] = {Chain, Mask, BasePtr, Index, InputVT, PassThru}; 4176 SDValue Gather = DAG.getNode(Opcode, DL, VTs, Ops); 4177 4178 if (VT.isFloatingPoint()) { 4179 SDValue Cast = getSVESafeBitCast(VT, Gather, DAG); 4180 return DAG.getMergeValues({Cast, Gather.getValue(1)}, DL); 4181 } 4182 4183 return Gather; 4184 } 4185 4186 SDValue AArch64TargetLowering::LowerMSCATTER(SDValue Op, 4187 SelectionDAG &DAG) const { 4188 SDLoc DL(Op); 4189 MaskedScatterSDNode *MSC = cast<MaskedScatterSDNode>(Op); 4190 assert(MSC && "Can only custom lower scatter store nodes"); 4191 4192 SDValue Index = MSC->getIndex(); 4193 SDValue Chain = MSC->getChain(); 4194 SDValue StoreVal = MSC->getValue(); 4195 SDValue Mask = MSC->getMask(); 4196 SDValue BasePtr = MSC->getBasePtr(); 4197 4198 ISD::MemIndexType IndexType = MSC->getIndexType(); 4199 bool IsScaled = 4200 IndexType == ISD::SIGNED_SCALED || IndexType == ISD::UNSIGNED_SCALED; 4201 bool IsSigned = 4202 IndexType == ISD::SIGNED_SCALED || IndexType == ISD::SIGNED_UNSCALED; 4203 bool NeedsExtend = 4204 getGatherScatterIndexIsExtended(Index) || 4205 Index.getSimpleValueType().getVectorElementType() == MVT::i32; 4206 4207 EVT VT = StoreVal.getSimpleValueType(); 4208 SDVTList VTs = DAG.getVTList(MVT::Other); 4209 EVT MemVT = MSC->getMemoryVT(); 4210 SDValue InputVT = DAG.getValueType(MemVT); 4211 4212 if (VT.getVectorElementType() == MVT::bf16 && 4213 !static_cast<const AArch64Subtarget &>(DAG.getSubtarget()).hasBF16()) 4214 return SDValue(); 4215 4216 // Handle FP data by casting the data so an integer scatter can be used. 4217 if (VT.isFloatingPoint()) { 4218 EVT StoreValVT = getPackedSVEVectorVT(VT.getVectorElementCount()); 4219 StoreVal = getSVESafeBitCast(StoreValVT, StoreVal, DAG); 4220 InputVT = DAG.getValueType(MemVT.changeVectorElementTypeToInteger()); 4221 } 4222 4223 if (getGatherScatterIndexIsExtended(Index)) 4224 Index = Index.getOperand(0); 4225 4226 unsigned Opcode = getScatterVecOpcode(IsScaled, IsSigned, NeedsExtend); 4227 selectGatherScatterAddrMode(BasePtr, Index, MemVT, Opcode, 4228 /*isGather=*/false, DAG); 4229 4230 SDValue Ops[] = {Chain, StoreVal, Mask, BasePtr, Index, InputVT}; 4231 return DAG.getNode(Opcode, DL, VTs, Ops); 4232 } 4233 4234 // Custom lower trunc store for v4i8 vectors, since it is promoted to v4i16. 4235 static SDValue LowerTruncateVectorStore(SDLoc DL, StoreSDNode *ST, 4236 EVT VT, EVT MemVT, 4237 SelectionDAG &DAG) { 4238 assert(VT.isVector() && "VT should be a vector type"); 4239 assert(MemVT == MVT::v4i8 && VT == MVT::v4i16); 4240 4241 SDValue Value = ST->getValue(); 4242 4243 // It first extend the promoted v4i16 to v8i16, truncate to v8i8, and extract 4244 // the word lane which represent the v4i8 subvector. It optimizes the store 4245 // to: 4246 // 4247 // xtn v0.8b, v0.8h 4248 // str s0, [x0] 4249 4250 SDValue Undef = DAG.getUNDEF(MVT::i16); 4251 SDValue UndefVec = DAG.getBuildVector(MVT::v4i16, DL, 4252 {Undef, Undef, Undef, Undef}); 4253 4254 SDValue TruncExt = DAG.getNode(ISD::CONCAT_VECTORS, DL, MVT::v8i16, 4255 Value, UndefVec); 4256 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, DL, MVT::v8i8, TruncExt); 4257 4258 Trunc = DAG.getNode(ISD::BITCAST, DL, MVT::v2i32, Trunc); 4259 SDValue ExtractTrunc = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32, 4260 Trunc, DAG.getConstant(0, DL, MVT::i64)); 4261 4262 return DAG.getStore(ST->getChain(), DL, ExtractTrunc, 4263 ST->getBasePtr(), ST->getMemOperand()); 4264 } 4265 4266 // Custom lowering for any store, vector or scalar and/or default or with 4267 // a truncate operations. Currently only custom lower truncate operation 4268 // from vector v4i16 to v4i8 or volatile stores of i128. 4269 SDValue AArch64TargetLowering::LowerSTORE(SDValue Op, 4270 SelectionDAG &DAG) const { 4271 SDLoc Dl(Op); 4272 StoreSDNode *StoreNode = cast<StoreSDNode>(Op); 4273 assert (StoreNode && "Can only custom lower store nodes"); 4274 4275 SDValue Value = StoreNode->getValue(); 4276 4277 EVT VT = Value.getValueType(); 4278 EVT MemVT = StoreNode->getMemoryVT(); 4279 4280 if (VT.isVector()) { 4281 if (useSVEForFixedLengthVectorVT(VT)) 4282 return LowerFixedLengthVectorStoreToSVE(Op, DAG); 4283 4284 unsigned AS = StoreNode->getAddressSpace(); 4285 Align Alignment = StoreNode->getAlign(); 4286 if (Alignment < MemVT.getStoreSize() && 4287 !allowsMisalignedMemoryAccesses(MemVT, AS, Alignment, 4288 StoreNode->getMemOperand()->getFlags(), 4289 nullptr)) { 4290 return scalarizeVectorStore(StoreNode, DAG); 4291 } 4292 4293 if (StoreNode->isTruncatingStore()) { 4294 return LowerTruncateVectorStore(Dl, StoreNode, VT, MemVT, DAG); 4295 } 4296 // 256 bit non-temporal stores can be lowered to STNP. Do this as part of 4297 // the custom lowering, as there are no un-paired non-temporal stores and 4298 // legalization will break up 256 bit inputs. 4299 ElementCount EC = MemVT.getVectorElementCount(); 4300 if (StoreNode->isNonTemporal() && MemVT.getSizeInBits() == 256u && 4301 EC.isKnownEven() && 4302 ((MemVT.getScalarSizeInBits() == 8u || 4303 MemVT.getScalarSizeInBits() == 16u || 4304 MemVT.getScalarSizeInBits() == 32u || 4305 MemVT.getScalarSizeInBits() == 64u))) { 4306 SDValue Lo = 4307 DAG.getNode(ISD::EXTRACT_SUBVECTOR, Dl, 4308 MemVT.getHalfNumVectorElementsVT(*DAG.getContext()), 4309 StoreNode->getValue(), DAG.getConstant(0, Dl, MVT::i64)); 4310 SDValue Hi = 4311 DAG.getNode(ISD::EXTRACT_SUBVECTOR, Dl, 4312 MemVT.getHalfNumVectorElementsVT(*DAG.getContext()), 4313 StoreNode->getValue(), 4314 DAG.getConstant(EC.getKnownMinValue() / 2, Dl, MVT::i64)); 4315 SDValue Result = DAG.getMemIntrinsicNode( 4316 AArch64ISD::STNP, Dl, DAG.getVTList(MVT::Other), 4317 {StoreNode->getChain(), Lo, Hi, StoreNode->getBasePtr()}, 4318 StoreNode->getMemoryVT(), StoreNode->getMemOperand()); 4319 return Result; 4320 } 4321 } else if (MemVT == MVT::i128 && StoreNode->isVolatile()) { 4322 assert(StoreNode->getValue()->getValueType(0) == MVT::i128); 4323 SDValue Lo = 4324 DAG.getNode(ISD::EXTRACT_ELEMENT, Dl, MVT::i64, StoreNode->getValue(), 4325 DAG.getConstant(0, Dl, MVT::i64)); 4326 SDValue Hi = 4327 DAG.getNode(ISD::EXTRACT_ELEMENT, Dl, MVT::i64, StoreNode->getValue(), 4328 DAG.getConstant(1, Dl, MVT::i64)); 4329 SDValue Result = DAG.getMemIntrinsicNode( 4330 AArch64ISD::STP, Dl, DAG.getVTList(MVT::Other), 4331 {StoreNode->getChain(), Lo, Hi, StoreNode->getBasePtr()}, 4332 StoreNode->getMemoryVT(), StoreNode->getMemOperand()); 4333 return Result; 4334 } 4335 4336 return SDValue(); 4337 } 4338 4339 // Generate SUBS and CSEL for integer abs. 4340 SDValue AArch64TargetLowering::LowerABS(SDValue Op, SelectionDAG &DAG) const { 4341 MVT VT = Op.getSimpleValueType(); 4342 4343 if (VT.isVector()) 4344 return LowerToPredicatedOp(Op, DAG, AArch64ISD::ABS_MERGE_PASSTHRU); 4345 4346 SDLoc DL(Op); 4347 SDValue Neg = DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, VT), 4348 Op.getOperand(0)); 4349 // Generate SUBS & CSEL. 4350 SDValue Cmp = 4351 DAG.getNode(AArch64ISD::SUBS, DL, DAG.getVTList(VT, MVT::i32), 4352 Op.getOperand(0), DAG.getConstant(0, DL, VT)); 4353 return DAG.getNode(AArch64ISD::CSEL, DL, VT, Op.getOperand(0), Neg, 4354 DAG.getConstant(AArch64CC::PL, DL, MVT::i32), 4355 Cmp.getValue(1)); 4356 } 4357 4358 SDValue AArch64TargetLowering::LowerOperation(SDValue Op, 4359 SelectionDAG &DAG) const { 4360 LLVM_DEBUG(dbgs() << "Custom lowering: "); 4361 LLVM_DEBUG(Op.dump()); 4362 4363 switch (Op.getOpcode()) { 4364 default: 4365 llvm_unreachable("unimplemented operand"); 4366 return SDValue(); 4367 case ISD::BITCAST: 4368 return LowerBITCAST(Op, DAG); 4369 case ISD::GlobalAddress: 4370 return LowerGlobalAddress(Op, DAG); 4371 case ISD::GlobalTLSAddress: 4372 return LowerGlobalTLSAddress(Op, DAG); 4373 case ISD::SETCC: 4374 case ISD::STRICT_FSETCC: 4375 case ISD::STRICT_FSETCCS: 4376 return LowerSETCC(Op, DAG); 4377 case ISD::BR_CC: 4378 return LowerBR_CC(Op, DAG); 4379 case ISD::SELECT: 4380 return LowerSELECT(Op, DAG); 4381 case ISD::SELECT_CC: 4382 return LowerSELECT_CC(Op, DAG); 4383 case ISD::JumpTable: 4384 return LowerJumpTable(Op, DAG); 4385 case ISD::BR_JT: 4386 return LowerBR_JT(Op, DAG); 4387 case ISD::ConstantPool: 4388 return LowerConstantPool(Op, DAG); 4389 case ISD::BlockAddress: 4390 return LowerBlockAddress(Op, DAG); 4391 case ISD::VASTART: 4392 return LowerVASTART(Op, DAG); 4393 case ISD::VACOPY: 4394 return LowerVACOPY(Op, DAG); 4395 case ISD::VAARG: 4396 return LowerVAARG(Op, DAG); 4397 case ISD::ADDC: 4398 case ISD::ADDE: 4399 case ISD::SUBC: 4400 case ISD::SUBE: 4401 return LowerADDC_ADDE_SUBC_SUBE(Op, DAG); 4402 case ISD::SADDO: 4403 case ISD::UADDO: 4404 case ISD::SSUBO: 4405 case ISD::USUBO: 4406 case ISD::SMULO: 4407 case ISD::UMULO: 4408 return LowerXALUO(Op, DAG); 4409 case ISD::FADD: 4410 return LowerToPredicatedOp(Op, DAG, AArch64ISD::FADD_PRED); 4411 case ISD::FSUB: 4412 return LowerToPredicatedOp(Op, DAG, AArch64ISD::FSUB_PRED); 4413 case ISD::FMUL: 4414 return LowerToPredicatedOp(Op, DAG, AArch64ISD::FMUL_PRED); 4415 case ISD::FMA: 4416 return LowerToPredicatedOp(Op, DAG, AArch64ISD::FMA_PRED); 4417 case ISD::FDIV: 4418 return LowerToPredicatedOp(Op, DAG, AArch64ISD::FDIV_PRED); 4419 case ISD::FNEG: 4420 return LowerToPredicatedOp(Op, DAG, AArch64ISD::FNEG_MERGE_PASSTHRU); 4421 case ISD::FCEIL: 4422 return LowerToPredicatedOp(Op, DAG, AArch64ISD::FCEIL_MERGE_PASSTHRU); 4423 case ISD::FFLOOR: 4424 return LowerToPredicatedOp(Op, DAG, AArch64ISD::FFLOOR_MERGE_PASSTHRU); 4425 case ISD::FNEARBYINT: 4426 return LowerToPredicatedOp(Op, DAG, AArch64ISD::FNEARBYINT_MERGE_PASSTHRU); 4427 case ISD::FRINT: 4428 return LowerToPredicatedOp(Op, DAG, AArch64ISD::FRINT_MERGE_PASSTHRU); 4429 case ISD::FROUND: 4430 return LowerToPredicatedOp(Op, DAG, AArch64ISD::FROUND_MERGE_PASSTHRU); 4431 case ISD::FROUNDEVEN: 4432 return LowerToPredicatedOp(Op, DAG, AArch64ISD::FROUNDEVEN_MERGE_PASSTHRU); 4433 case ISD::FTRUNC: 4434 return LowerToPredicatedOp(Op, DAG, AArch64ISD::FTRUNC_MERGE_PASSTHRU); 4435 case ISD::FSQRT: 4436 return LowerToPredicatedOp(Op, DAG, AArch64ISD::FSQRT_MERGE_PASSTHRU); 4437 case ISD::FABS: 4438 return LowerToPredicatedOp(Op, DAG, AArch64ISD::FABS_MERGE_PASSTHRU); 4439 case ISD::FP_ROUND: 4440 case ISD::STRICT_FP_ROUND: 4441 return LowerFP_ROUND(Op, DAG); 4442 case ISD::FP_EXTEND: 4443 return LowerFP_EXTEND(Op, DAG); 4444 case ISD::FRAMEADDR: 4445 return LowerFRAMEADDR(Op, DAG); 4446 case ISD::SPONENTRY: 4447 return LowerSPONENTRY(Op, DAG); 4448 case ISD::RETURNADDR: 4449 return LowerRETURNADDR(Op, DAG); 4450 case ISD::ADDROFRETURNADDR: 4451 return LowerADDROFRETURNADDR(Op, DAG); 4452 case ISD::CONCAT_VECTORS: 4453 return LowerCONCAT_VECTORS(Op, DAG); 4454 case ISD::INSERT_VECTOR_ELT: 4455 return LowerINSERT_VECTOR_ELT(Op, DAG); 4456 case ISD::EXTRACT_VECTOR_ELT: 4457 return LowerEXTRACT_VECTOR_ELT(Op, DAG); 4458 case ISD::BUILD_VECTOR: 4459 return LowerBUILD_VECTOR(Op, DAG); 4460 case ISD::VECTOR_SHUFFLE: 4461 return LowerVECTOR_SHUFFLE(Op, DAG); 4462 case ISD::SPLAT_VECTOR: 4463 return LowerSPLAT_VECTOR(Op, DAG); 4464 case ISD::STEP_VECTOR: 4465 return LowerSTEP_VECTOR(Op, DAG); 4466 case ISD::EXTRACT_SUBVECTOR: 4467 return LowerEXTRACT_SUBVECTOR(Op, DAG); 4468 case ISD::INSERT_SUBVECTOR: 4469 return LowerINSERT_SUBVECTOR(Op, DAG); 4470 case ISD::SDIV: 4471 case ISD::UDIV: 4472 return LowerDIV(Op, DAG); 4473 case ISD::SMIN: 4474 return LowerToPredicatedOp(Op, DAG, AArch64ISD::SMIN_PRED, 4475 /*OverrideNEON=*/true); 4476 case ISD::UMIN: 4477 return LowerToPredicatedOp(Op, DAG, AArch64ISD::UMIN_PRED, 4478 /*OverrideNEON=*/true); 4479 case ISD::SMAX: 4480 return LowerToPredicatedOp(Op, DAG, AArch64ISD::SMAX_PRED, 4481 /*OverrideNEON=*/true); 4482 case ISD::UMAX: 4483 return LowerToPredicatedOp(Op, DAG, AArch64ISD::UMAX_PRED, 4484 /*OverrideNEON=*/true); 4485 case ISD::SRA: 4486 case ISD::SRL: 4487 case ISD::SHL: 4488 return LowerVectorSRA_SRL_SHL(Op, DAG); 4489 case ISD::SHL_PARTS: 4490 return LowerShiftLeftParts(Op, DAG); 4491 case ISD::SRL_PARTS: 4492 case ISD::SRA_PARTS: 4493 return LowerShiftRightParts(Op, DAG); 4494 case ISD::CTPOP: 4495 return LowerCTPOP(Op, DAG); 4496 case ISD::FCOPYSIGN: 4497 return LowerFCOPYSIGN(Op, DAG); 4498 case ISD::OR: 4499 return LowerVectorOR(Op, DAG); 4500 case ISD::XOR: 4501 return LowerXOR(Op, DAG); 4502 case ISD::PREFETCH: 4503 return LowerPREFETCH(Op, DAG); 4504 case ISD::SINT_TO_FP: 4505 case ISD::UINT_TO_FP: 4506 case ISD::STRICT_SINT_TO_FP: 4507 case ISD::STRICT_UINT_TO_FP: 4508 return LowerINT_TO_FP(Op, DAG); 4509 case ISD::FP_TO_SINT: 4510 case ISD::FP_TO_UINT: 4511 case ISD::STRICT_FP_TO_SINT: 4512 case ISD::STRICT_FP_TO_UINT: 4513 return LowerFP_TO_INT(Op, DAG); 4514 case ISD::FSINCOS: 4515 return LowerFSINCOS(Op, DAG); 4516 case ISD::FLT_ROUNDS_: 4517 return LowerFLT_ROUNDS_(Op, DAG); 4518 case ISD::SET_ROUNDING: 4519 return LowerSET_ROUNDING(Op, DAG); 4520 case ISD::MUL: 4521 return LowerMUL(Op, DAG); 4522 case ISD::INTRINSIC_WO_CHAIN: 4523 return LowerINTRINSIC_WO_CHAIN(Op, DAG); 4524 case ISD::STORE: 4525 return LowerSTORE(Op, DAG); 4526 case ISD::MGATHER: 4527 return LowerMGATHER(Op, DAG); 4528 case ISD::MSCATTER: 4529 return LowerMSCATTER(Op, DAG); 4530 case ISD::VECREDUCE_SEQ_FADD: 4531 return LowerVECREDUCE_SEQ_FADD(Op, DAG); 4532 case ISD::VECREDUCE_ADD: 4533 case ISD::VECREDUCE_AND: 4534 case ISD::VECREDUCE_OR: 4535 case ISD::VECREDUCE_XOR: 4536 case ISD::VECREDUCE_SMAX: 4537 case ISD::VECREDUCE_SMIN: 4538 case ISD::VECREDUCE_UMAX: 4539 case ISD::VECREDUCE_UMIN: 4540 case ISD::VECREDUCE_FADD: 4541 case ISD::VECREDUCE_FMAX: 4542 case ISD::VECREDUCE_FMIN: 4543 return LowerVECREDUCE(Op, DAG); 4544 case ISD::ATOMIC_LOAD_SUB: 4545 return LowerATOMIC_LOAD_SUB(Op, DAG); 4546 case ISD::ATOMIC_LOAD_AND: 4547 return LowerATOMIC_LOAD_AND(Op, DAG); 4548 case ISD::DYNAMIC_STACKALLOC: 4549 return LowerDYNAMIC_STACKALLOC(Op, DAG); 4550 case ISD::VSCALE: 4551 return LowerVSCALE(Op, DAG); 4552 case ISD::ANY_EXTEND: 4553 case ISD::SIGN_EXTEND: 4554 case ISD::ZERO_EXTEND: 4555 return LowerFixedLengthVectorIntExtendToSVE(Op, DAG); 4556 case ISD::SIGN_EXTEND_INREG: { 4557 // Only custom lower when ExtraVT has a legal byte based element type. 4558 EVT ExtraVT = cast<VTSDNode>(Op.getOperand(1))->getVT(); 4559 EVT ExtraEltVT = ExtraVT.getVectorElementType(); 4560 if ((ExtraEltVT != MVT::i8) && (ExtraEltVT != MVT::i16) && 4561 (ExtraEltVT != MVT::i32) && (ExtraEltVT != MVT::i64)) 4562 return SDValue(); 4563 4564 return LowerToPredicatedOp(Op, DAG, 4565 AArch64ISD::SIGN_EXTEND_INREG_MERGE_PASSTHRU); 4566 } 4567 case ISD::TRUNCATE: 4568 return LowerTRUNCATE(Op, DAG); 4569 case ISD::LOAD: 4570 if (useSVEForFixedLengthVectorVT(Op.getValueType())) 4571 return LowerFixedLengthVectorLoadToSVE(Op, DAG); 4572 llvm_unreachable("Unexpected request to lower ISD::LOAD"); 4573 case ISD::ADD: 4574 return LowerToPredicatedOp(Op, DAG, AArch64ISD::ADD_PRED); 4575 case ISD::AND: 4576 return LowerToScalableOp(Op, DAG); 4577 case ISD::SUB: 4578 return LowerToPredicatedOp(Op, DAG, AArch64ISD::SUB_PRED); 4579 case ISD::FMAXIMUM: 4580 return LowerToPredicatedOp(Op, DAG, AArch64ISD::FMAX_PRED); 4581 case ISD::FMAXNUM: 4582 return LowerToPredicatedOp(Op, DAG, AArch64ISD::FMAXNM_PRED); 4583 case ISD::FMINIMUM: 4584 return LowerToPredicatedOp(Op, DAG, AArch64ISD::FMIN_PRED); 4585 case ISD::FMINNUM: 4586 return LowerToPredicatedOp(Op, DAG, AArch64ISD::FMINNM_PRED); 4587 case ISD::VSELECT: 4588 return LowerFixedLengthVectorSelectToSVE(Op, DAG); 4589 case ISD::ABS: 4590 return LowerABS(Op, DAG); 4591 case ISD::BITREVERSE: 4592 return LowerToPredicatedOp(Op, DAG, AArch64ISD::BITREVERSE_MERGE_PASSTHRU, 4593 /*OverrideNEON=*/true); 4594 case ISD::BSWAP: 4595 return LowerToPredicatedOp(Op, DAG, AArch64ISD::BSWAP_MERGE_PASSTHRU); 4596 case ISD::CTLZ: 4597 return LowerToPredicatedOp(Op, DAG, AArch64ISD::CTLZ_MERGE_PASSTHRU, 4598 /*OverrideNEON=*/true); 4599 case ISD::CTTZ: 4600 return LowerCTTZ(Op, DAG); 4601 } 4602 } 4603 4604 bool AArch64TargetLowering::mergeStoresAfterLegalization(EVT VT) const { 4605 return !Subtarget->useSVEForFixedLengthVectors(); 4606 } 4607 4608 bool AArch64TargetLowering::useSVEForFixedLengthVectorVT( 4609 EVT VT, bool OverrideNEON) const { 4610 if (!Subtarget->useSVEForFixedLengthVectors()) 4611 return false; 4612 4613 if (!VT.isFixedLengthVector()) 4614 return false; 4615 4616 // Don't use SVE for vectors we cannot scalarize if required. 4617 switch (VT.getVectorElementType().getSimpleVT().SimpleTy) { 4618 // Fixed length predicates should be promoted to i8. 4619 // NOTE: This is consistent with how NEON (and thus 64/128bit vectors) work. 4620 case MVT::i1: 4621 default: 4622 return false; 4623 case MVT::i8: 4624 case MVT::i16: 4625 case MVT::i32: 4626 case MVT::i64: 4627 case MVT::f16: 4628 case MVT::f32: 4629 case MVT::f64: 4630 break; 4631 } 4632 4633 // All SVE implementations support NEON sized vectors. 4634 if (OverrideNEON && (VT.is128BitVector() || VT.is64BitVector())) 4635 return true; 4636 4637 // Ensure NEON MVTs only belong to a single register class. 4638 if (VT.getFixedSizeInBits() <= 128) 4639 return false; 4640 4641 // Don't use SVE for types that don't fit. 4642 if (VT.getFixedSizeInBits() > Subtarget->getMinSVEVectorSizeInBits()) 4643 return false; 4644 4645 // TODO: Perhaps an artificial restriction, but worth having whilst getting 4646 // the base fixed length SVE support in place. 4647 if (!VT.isPow2VectorType()) 4648 return false; 4649 4650 return true; 4651 } 4652 4653 //===----------------------------------------------------------------------===// 4654 // Calling Convention Implementation 4655 //===----------------------------------------------------------------------===// 4656 4657 /// Selects the correct CCAssignFn for a given CallingConvention value. 4658 CCAssignFn *AArch64TargetLowering::CCAssignFnForCall(CallingConv::ID CC, 4659 bool IsVarArg) const { 4660 switch (CC) { 4661 default: 4662 report_fatal_error("Unsupported calling convention."); 4663 case CallingConv::WebKit_JS: 4664 return CC_AArch64_WebKit_JS; 4665 case CallingConv::GHC: 4666 return CC_AArch64_GHC; 4667 case CallingConv::C: 4668 case CallingConv::Fast: 4669 case CallingConv::PreserveMost: 4670 case CallingConv::CXX_FAST_TLS: 4671 case CallingConv::Swift: 4672 if (Subtarget->isTargetWindows() && IsVarArg) 4673 return CC_AArch64_Win64_VarArg; 4674 if (!Subtarget->isTargetDarwin()) 4675 return CC_AArch64_AAPCS; 4676 if (!IsVarArg) 4677 return CC_AArch64_DarwinPCS; 4678 return Subtarget->isTargetILP32() ? CC_AArch64_DarwinPCS_ILP32_VarArg 4679 : CC_AArch64_DarwinPCS_VarArg; 4680 case CallingConv::Win64: 4681 return IsVarArg ? CC_AArch64_Win64_VarArg : CC_AArch64_AAPCS; 4682 case CallingConv::CFGuard_Check: 4683 return CC_AArch64_Win64_CFGuard_Check; 4684 case CallingConv::AArch64_VectorCall: 4685 case CallingConv::AArch64_SVE_VectorCall: 4686 return CC_AArch64_AAPCS; 4687 } 4688 } 4689 4690 CCAssignFn * 4691 AArch64TargetLowering::CCAssignFnForReturn(CallingConv::ID CC) const { 4692 return CC == CallingConv::WebKit_JS ? RetCC_AArch64_WebKit_JS 4693 : RetCC_AArch64_AAPCS; 4694 } 4695 4696 SDValue AArch64TargetLowering::LowerFormalArguments( 4697 SDValue Chain, CallingConv::ID CallConv, bool isVarArg, 4698 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &DL, 4699 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const { 4700 MachineFunction &MF = DAG.getMachineFunction(); 4701 MachineFrameInfo &MFI = MF.getFrameInfo(); 4702 bool IsWin64 = Subtarget->isCallingConvWin64(MF.getFunction().getCallingConv()); 4703 4704 // Assign locations to all of the incoming arguments. 4705 SmallVector<CCValAssign, 16> ArgLocs; 4706 DenseMap<unsigned, SDValue> CopiedRegs; 4707 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), ArgLocs, 4708 *DAG.getContext()); 4709 4710 // At this point, Ins[].VT may already be promoted to i32. To correctly 4711 // handle passing i8 as i8 instead of i32 on stack, we pass in both i32 and 4712 // i8 to CC_AArch64_AAPCS with i32 being ValVT and i8 being LocVT. 4713 // Since AnalyzeFormalArguments uses Ins[].VT for both ValVT and LocVT, here 4714 // we use a special version of AnalyzeFormalArguments to pass in ValVT and 4715 // LocVT. 4716 unsigned NumArgs = Ins.size(); 4717 Function::const_arg_iterator CurOrigArg = MF.getFunction().arg_begin(); 4718 unsigned CurArgIdx = 0; 4719 for (unsigned i = 0; i != NumArgs; ++i) { 4720 MVT ValVT = Ins[i].VT; 4721 if (Ins[i].isOrigArg()) { 4722 std::advance(CurOrigArg, Ins[i].getOrigArgIndex() - CurArgIdx); 4723 CurArgIdx = Ins[i].getOrigArgIndex(); 4724 4725 // Get type of the original argument. 4726 EVT ActualVT = getValueType(DAG.getDataLayout(), CurOrigArg->getType(), 4727 /*AllowUnknown*/ true); 4728 MVT ActualMVT = ActualVT.isSimple() ? ActualVT.getSimpleVT() : MVT::Other; 4729 // If ActualMVT is i1/i8/i16, we should set LocVT to i8/i8/i16. 4730 if (ActualMVT == MVT::i1 || ActualMVT == MVT::i8) 4731 ValVT = MVT::i8; 4732 else if (ActualMVT == MVT::i16) 4733 ValVT = MVT::i16; 4734 } 4735 CCAssignFn *AssignFn = CCAssignFnForCall(CallConv, /*IsVarArg=*/false); 4736 bool Res = 4737 AssignFn(i, ValVT, ValVT, CCValAssign::Full, Ins[i].Flags, CCInfo); 4738 assert(!Res && "Call operand has unhandled type"); 4739 (void)Res; 4740 } 4741 SmallVector<SDValue, 16> ArgValues; 4742 unsigned ExtraArgLocs = 0; 4743 for (unsigned i = 0, e = Ins.size(); i != e; ++i) { 4744 CCValAssign &VA = ArgLocs[i - ExtraArgLocs]; 4745 4746 if (Ins[i].Flags.isByVal()) { 4747 // Byval is used for HFAs in the PCS, but the system should work in a 4748 // non-compliant manner for larger structs. 4749 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 4750 int Size = Ins[i].Flags.getByValSize(); 4751 unsigned NumRegs = (Size + 7) / 8; 4752 4753 // FIXME: This works on big-endian for composite byvals, which are the common 4754 // case. It should also work for fundamental types too. 4755 unsigned FrameIdx = 4756 MFI.CreateFixedObject(8 * NumRegs, VA.getLocMemOffset(), false); 4757 SDValue FrameIdxN = DAG.getFrameIndex(FrameIdx, PtrVT); 4758 InVals.push_back(FrameIdxN); 4759 4760 continue; 4761 } 4762 4763 SDValue ArgValue; 4764 if (VA.isRegLoc()) { 4765 // Arguments stored in registers. 4766 EVT RegVT = VA.getLocVT(); 4767 const TargetRegisterClass *RC; 4768 4769 if (RegVT == MVT::i32) 4770 RC = &AArch64::GPR32RegClass; 4771 else if (RegVT == MVT::i64) 4772 RC = &AArch64::GPR64RegClass; 4773 else if (RegVT == MVT::f16 || RegVT == MVT::bf16) 4774 RC = &AArch64::FPR16RegClass; 4775 else if (RegVT == MVT::f32) 4776 RC = &AArch64::FPR32RegClass; 4777 else if (RegVT == MVT::f64 || RegVT.is64BitVector()) 4778 RC = &AArch64::FPR64RegClass; 4779 else if (RegVT == MVT::f128 || RegVT.is128BitVector()) 4780 RC = &AArch64::FPR128RegClass; 4781 else if (RegVT.isScalableVector() && 4782 RegVT.getVectorElementType() == MVT::i1) 4783 RC = &AArch64::PPRRegClass; 4784 else if (RegVT.isScalableVector()) 4785 RC = &AArch64::ZPRRegClass; 4786 else 4787 llvm_unreachable("RegVT not supported by FORMAL_ARGUMENTS Lowering"); 4788 4789 // Transform the arguments in physical registers into virtual ones. 4790 unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC); 4791 ArgValue = DAG.getCopyFromReg(Chain, DL, Reg, RegVT); 4792 4793 // If this is an 8, 16 or 32-bit value, it is really passed promoted 4794 // to 64 bits. Insert an assert[sz]ext to capture this, then 4795 // truncate to the right size. 4796 switch (VA.getLocInfo()) { 4797 default: 4798 llvm_unreachable("Unknown loc info!"); 4799 case CCValAssign::Full: 4800 break; 4801 case CCValAssign::Indirect: 4802 assert(VA.getValVT().isScalableVector() && 4803 "Only scalable vectors can be passed indirectly"); 4804 break; 4805 case CCValAssign::BCvt: 4806 ArgValue = DAG.getNode(ISD::BITCAST, DL, VA.getValVT(), ArgValue); 4807 break; 4808 case CCValAssign::AExt: 4809 case CCValAssign::SExt: 4810 case CCValAssign::ZExt: 4811 break; 4812 case CCValAssign::AExtUpper: 4813 ArgValue = DAG.getNode(ISD::SRL, DL, RegVT, ArgValue, 4814 DAG.getConstant(32, DL, RegVT)); 4815 ArgValue = DAG.getZExtOrTrunc(ArgValue, DL, VA.getValVT()); 4816 break; 4817 } 4818 } else { // VA.isRegLoc() 4819 assert(VA.isMemLoc() && "CCValAssign is neither reg nor mem"); 4820 unsigned ArgOffset = VA.getLocMemOffset(); 4821 unsigned ArgSize = (VA.getLocInfo() == CCValAssign::Indirect 4822 ? VA.getLocVT().getSizeInBits() 4823 : VA.getValVT().getSizeInBits()) / 8; 4824 4825 uint32_t BEAlign = 0; 4826 if (!Subtarget->isLittleEndian() && ArgSize < 8 && 4827 !Ins[i].Flags.isInConsecutiveRegs()) 4828 BEAlign = 8 - ArgSize; 4829 4830 int FI = MFI.CreateFixedObject(ArgSize, ArgOffset + BEAlign, true); 4831 4832 // Create load nodes to retrieve arguments from the stack. 4833 SDValue FIN = DAG.getFrameIndex(FI, getPointerTy(DAG.getDataLayout())); 4834 4835 // For NON_EXTLOAD, generic code in getLoad assert(ValVT == MemVT) 4836 ISD::LoadExtType ExtType = ISD::NON_EXTLOAD; 4837 MVT MemVT = VA.getValVT(); 4838 4839 switch (VA.getLocInfo()) { 4840 default: 4841 break; 4842 case CCValAssign::Trunc: 4843 case CCValAssign::BCvt: 4844 MemVT = VA.getLocVT(); 4845 break; 4846 case CCValAssign::Indirect: 4847 assert(VA.getValVT().isScalableVector() && 4848 "Only scalable vectors can be passed indirectly"); 4849 MemVT = VA.getLocVT(); 4850 break; 4851 case CCValAssign::SExt: 4852 ExtType = ISD::SEXTLOAD; 4853 break; 4854 case CCValAssign::ZExt: 4855 ExtType = ISD::ZEXTLOAD; 4856 break; 4857 case CCValAssign::AExt: 4858 ExtType = ISD::EXTLOAD; 4859 break; 4860 } 4861 4862 ArgValue = DAG.getExtLoad( 4863 ExtType, DL, VA.getLocVT(), Chain, FIN, 4864 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI), 4865 MemVT); 4866 4867 } 4868 4869 if (VA.getLocInfo() == CCValAssign::Indirect) { 4870 assert(VA.getValVT().isScalableVector() && 4871 "Only scalable vectors can be passed indirectly"); 4872 4873 uint64_t PartSize = VA.getValVT().getStoreSize().getKnownMinSize(); 4874 unsigned NumParts = 1; 4875 if (Ins[i].Flags.isInConsecutiveRegs()) { 4876 assert(!Ins[i].Flags.isInConsecutiveRegsLast()); 4877 while (!Ins[i + NumParts - 1].Flags.isInConsecutiveRegsLast()) 4878 ++NumParts; 4879 } 4880 4881 MVT PartLoad = VA.getValVT(); 4882 SDValue Ptr = ArgValue; 4883 4884 // Ensure we generate all loads for each tuple part, whilst updating the 4885 // pointer after each load correctly using vscale. 4886 while (NumParts > 0) { 4887 ArgValue = DAG.getLoad(PartLoad, DL, Chain, Ptr, MachinePointerInfo()); 4888 InVals.push_back(ArgValue); 4889 NumParts--; 4890 if (NumParts > 0) { 4891 SDValue BytesIncrement = DAG.getVScale( 4892 DL, Ptr.getValueType(), 4893 APInt(Ptr.getValueSizeInBits().getFixedSize(), PartSize)); 4894 SDNodeFlags Flags; 4895 Flags.setNoUnsignedWrap(true); 4896 Ptr = DAG.getNode(ISD::ADD, DL, Ptr.getValueType(), Ptr, 4897 BytesIncrement, Flags); 4898 ExtraArgLocs++; 4899 i++; 4900 } 4901 } 4902 } else { 4903 if (Subtarget->isTargetILP32() && Ins[i].Flags.isPointer()) 4904 ArgValue = DAG.getNode(ISD::AssertZext, DL, ArgValue.getValueType(), 4905 ArgValue, DAG.getValueType(MVT::i32)); 4906 InVals.push_back(ArgValue); 4907 } 4908 } 4909 assert((ArgLocs.size() + ExtraArgLocs) == Ins.size()); 4910 4911 // varargs 4912 AArch64FunctionInfo *FuncInfo = MF.getInfo<AArch64FunctionInfo>(); 4913 if (isVarArg) { 4914 if (!Subtarget->isTargetDarwin() || IsWin64) { 4915 // The AAPCS variadic function ABI is identical to the non-variadic 4916 // one. As a result there may be more arguments in registers and we should 4917 // save them for future reference. 4918 // Win64 variadic functions also pass arguments in registers, but all float 4919 // arguments are passed in integer registers. 4920 saveVarArgRegisters(CCInfo, DAG, DL, Chain); 4921 } 4922 4923 // This will point to the next argument passed via stack. 4924 unsigned StackOffset = CCInfo.getNextStackOffset(); 4925 // We currently pass all varargs at 8-byte alignment, or 4 for ILP32 4926 StackOffset = alignTo(StackOffset, Subtarget->isTargetILP32() ? 4 : 8); 4927 FuncInfo->setVarArgsStackIndex(MFI.CreateFixedObject(4, StackOffset, true)); 4928 4929 if (MFI.hasMustTailInVarArgFunc()) { 4930 SmallVector<MVT, 2> RegParmTypes; 4931 RegParmTypes.push_back(MVT::i64); 4932 RegParmTypes.push_back(MVT::f128); 4933 // Compute the set of forwarded registers. The rest are scratch. 4934 SmallVectorImpl<ForwardedRegister> &Forwards = 4935 FuncInfo->getForwardedMustTailRegParms(); 4936 CCInfo.analyzeMustTailForwardedRegisters(Forwards, RegParmTypes, 4937 CC_AArch64_AAPCS); 4938 4939 // Conservatively forward X8, since it might be used for aggregate return. 4940 if (!CCInfo.isAllocated(AArch64::X8)) { 4941 unsigned X8VReg = MF.addLiveIn(AArch64::X8, &AArch64::GPR64RegClass); 4942 Forwards.push_back(ForwardedRegister(X8VReg, AArch64::X8, MVT::i64)); 4943 } 4944 } 4945 } 4946 4947 // On Windows, InReg pointers must be returned, so record the pointer in a 4948 // virtual register at the start of the function so it can be returned in the 4949 // epilogue. 4950 if (IsWin64) { 4951 for (unsigned I = 0, E = Ins.size(); I != E; ++I) { 4952 if (Ins[I].Flags.isInReg()) { 4953 assert(!FuncInfo->getSRetReturnReg()); 4954 4955 MVT PtrTy = getPointerTy(DAG.getDataLayout()); 4956 Register Reg = 4957 MF.getRegInfo().createVirtualRegister(getRegClassFor(PtrTy)); 4958 FuncInfo->setSRetReturnReg(Reg); 4959 4960 SDValue Copy = DAG.getCopyToReg(DAG.getEntryNode(), DL, Reg, InVals[I]); 4961 Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Copy, Chain); 4962 break; 4963 } 4964 } 4965 } 4966 4967 unsigned StackArgSize = CCInfo.getNextStackOffset(); 4968 bool TailCallOpt = MF.getTarget().Options.GuaranteedTailCallOpt; 4969 if (DoesCalleeRestoreStack(CallConv, TailCallOpt)) { 4970 // This is a non-standard ABI so by fiat I say we're allowed to make full 4971 // use of the stack area to be popped, which must be aligned to 16 bytes in 4972 // any case: 4973 StackArgSize = alignTo(StackArgSize, 16); 4974 4975 // If we're expected to restore the stack (e.g. fastcc) then we'll be adding 4976 // a multiple of 16. 4977 FuncInfo->setArgumentStackToRestore(StackArgSize); 4978 4979 // This realignment carries over to the available bytes below. Our own 4980 // callers will guarantee the space is free by giving an aligned value to 4981 // CALLSEQ_START. 4982 } 4983 // Even if we're not expected to free up the space, it's useful to know how 4984 // much is there while considering tail calls (because we can reuse it). 4985 FuncInfo->setBytesInStackArgArea(StackArgSize); 4986 4987 if (Subtarget->hasCustomCallingConv()) 4988 Subtarget->getRegisterInfo()->UpdateCustomCalleeSavedRegs(MF); 4989 4990 return Chain; 4991 } 4992 4993 void AArch64TargetLowering::saveVarArgRegisters(CCState &CCInfo, 4994 SelectionDAG &DAG, 4995 const SDLoc &DL, 4996 SDValue &Chain) const { 4997 MachineFunction &MF = DAG.getMachineFunction(); 4998 MachineFrameInfo &MFI = MF.getFrameInfo(); 4999 AArch64FunctionInfo *FuncInfo = MF.getInfo<AArch64FunctionInfo>(); 5000 auto PtrVT = getPointerTy(DAG.getDataLayout()); 5001 bool IsWin64 = Subtarget->isCallingConvWin64(MF.getFunction().getCallingConv()); 5002 5003 SmallVector<SDValue, 8> MemOps; 5004 5005 static const MCPhysReg GPRArgRegs[] = { AArch64::X0, AArch64::X1, AArch64::X2, 5006 AArch64::X3, AArch64::X4, AArch64::X5, 5007 AArch64::X6, AArch64::X7 }; 5008 static const unsigned NumGPRArgRegs = array_lengthof(GPRArgRegs); 5009 unsigned FirstVariadicGPR = CCInfo.getFirstUnallocated(GPRArgRegs); 5010 5011 unsigned GPRSaveSize = 8 * (NumGPRArgRegs - FirstVariadicGPR); 5012 int GPRIdx = 0; 5013 if (GPRSaveSize != 0) { 5014 if (IsWin64) { 5015 GPRIdx = MFI.CreateFixedObject(GPRSaveSize, -(int)GPRSaveSize, false); 5016 if (GPRSaveSize & 15) 5017 // The extra size here, if triggered, will always be 8. 5018 MFI.CreateFixedObject(16 - (GPRSaveSize & 15), -(int)alignTo(GPRSaveSize, 16), false); 5019 } else 5020 GPRIdx = MFI.CreateStackObject(GPRSaveSize, Align(8), false); 5021 5022 SDValue FIN = DAG.getFrameIndex(GPRIdx, PtrVT); 5023 5024 for (unsigned i = FirstVariadicGPR; i < NumGPRArgRegs; ++i) { 5025 unsigned VReg = MF.addLiveIn(GPRArgRegs[i], &AArch64::GPR64RegClass); 5026 SDValue Val = DAG.getCopyFromReg(Chain, DL, VReg, MVT::i64); 5027 SDValue Store = DAG.getStore( 5028 Val.getValue(1), DL, Val, FIN, 5029 IsWin64 5030 ? MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), 5031 GPRIdx, 5032 (i - FirstVariadicGPR) * 8) 5033 : MachinePointerInfo::getStack(DAG.getMachineFunction(), i * 8)); 5034 MemOps.push_back(Store); 5035 FIN = 5036 DAG.getNode(ISD::ADD, DL, PtrVT, FIN, DAG.getConstant(8, DL, PtrVT)); 5037 } 5038 } 5039 FuncInfo->setVarArgsGPRIndex(GPRIdx); 5040 FuncInfo->setVarArgsGPRSize(GPRSaveSize); 5041 5042 if (Subtarget->hasFPARMv8() && !IsWin64) { 5043 static const MCPhysReg FPRArgRegs[] = { 5044 AArch64::Q0, AArch64::Q1, AArch64::Q2, AArch64::Q3, 5045 AArch64::Q4, AArch64::Q5, AArch64::Q6, AArch64::Q7}; 5046 static const unsigned NumFPRArgRegs = array_lengthof(FPRArgRegs); 5047 unsigned FirstVariadicFPR = CCInfo.getFirstUnallocated(FPRArgRegs); 5048 5049 unsigned FPRSaveSize = 16 * (NumFPRArgRegs - FirstVariadicFPR); 5050 int FPRIdx = 0; 5051 if (FPRSaveSize != 0) { 5052 FPRIdx = MFI.CreateStackObject(FPRSaveSize, Align(16), false); 5053 5054 SDValue FIN = DAG.getFrameIndex(FPRIdx, PtrVT); 5055 5056 for (unsigned i = FirstVariadicFPR; i < NumFPRArgRegs; ++i) { 5057 unsigned VReg = MF.addLiveIn(FPRArgRegs[i], &AArch64::FPR128RegClass); 5058 SDValue Val = DAG.getCopyFromReg(Chain, DL, VReg, MVT::f128); 5059 5060 SDValue Store = DAG.getStore( 5061 Val.getValue(1), DL, Val, FIN, 5062 MachinePointerInfo::getStack(DAG.getMachineFunction(), i * 16)); 5063 MemOps.push_back(Store); 5064 FIN = DAG.getNode(ISD::ADD, DL, PtrVT, FIN, 5065 DAG.getConstant(16, DL, PtrVT)); 5066 } 5067 } 5068 FuncInfo->setVarArgsFPRIndex(FPRIdx); 5069 FuncInfo->setVarArgsFPRSize(FPRSaveSize); 5070 } 5071 5072 if (!MemOps.empty()) { 5073 Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, MemOps); 5074 } 5075 } 5076 5077 /// LowerCallResult - Lower the result values of a call into the 5078 /// appropriate copies out of appropriate physical registers. 5079 SDValue AArch64TargetLowering::LowerCallResult( 5080 SDValue Chain, SDValue InFlag, CallingConv::ID CallConv, bool isVarArg, 5081 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &DL, 5082 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals, bool isThisReturn, 5083 SDValue ThisVal) const { 5084 CCAssignFn *RetCC = CCAssignFnForReturn(CallConv); 5085 // Assign locations to each value returned by this call. 5086 SmallVector<CCValAssign, 16> RVLocs; 5087 DenseMap<unsigned, SDValue> CopiedRegs; 5088 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs, 5089 *DAG.getContext()); 5090 CCInfo.AnalyzeCallResult(Ins, RetCC); 5091 5092 // Copy all of the result registers out of their specified physreg. 5093 for (unsigned i = 0; i != RVLocs.size(); ++i) { 5094 CCValAssign VA = RVLocs[i]; 5095 5096 // Pass 'this' value directly from the argument to return value, to avoid 5097 // reg unit interference 5098 if (i == 0 && isThisReturn) { 5099 assert(!VA.needsCustom() && VA.getLocVT() == MVT::i64 && 5100 "unexpected return calling convention register assignment"); 5101 InVals.push_back(ThisVal); 5102 continue; 5103 } 5104 5105 // Avoid copying a physreg twice since RegAllocFast is incompetent and only 5106 // allows one use of a physreg per block. 5107 SDValue Val = CopiedRegs.lookup(VA.getLocReg()); 5108 if (!Val) { 5109 Val = 5110 DAG.getCopyFromReg(Chain, DL, VA.getLocReg(), VA.getLocVT(), InFlag); 5111 Chain = Val.getValue(1); 5112 InFlag = Val.getValue(2); 5113 CopiedRegs[VA.getLocReg()] = Val; 5114 } 5115 5116 switch (VA.getLocInfo()) { 5117 default: 5118 llvm_unreachable("Unknown loc info!"); 5119 case CCValAssign::Full: 5120 break; 5121 case CCValAssign::BCvt: 5122 Val = DAG.getNode(ISD::BITCAST, DL, VA.getValVT(), Val); 5123 break; 5124 case CCValAssign::AExtUpper: 5125 Val = DAG.getNode(ISD::SRL, DL, VA.getLocVT(), Val, 5126 DAG.getConstant(32, DL, VA.getLocVT())); 5127 LLVM_FALLTHROUGH; 5128 case CCValAssign::AExt: 5129 LLVM_FALLTHROUGH; 5130 case CCValAssign::ZExt: 5131 Val = DAG.getZExtOrTrunc(Val, DL, VA.getValVT()); 5132 break; 5133 } 5134 5135 InVals.push_back(Val); 5136 } 5137 5138 return Chain; 5139 } 5140 5141 /// Return true if the calling convention is one that we can guarantee TCO for. 5142 static bool canGuaranteeTCO(CallingConv::ID CC) { 5143 return CC == CallingConv::Fast; 5144 } 5145 5146 /// Return true if we might ever do TCO for calls with this calling convention. 5147 static bool mayTailCallThisCC(CallingConv::ID CC) { 5148 switch (CC) { 5149 case CallingConv::C: 5150 case CallingConv::AArch64_SVE_VectorCall: 5151 case CallingConv::PreserveMost: 5152 case CallingConv::Swift: 5153 return true; 5154 default: 5155 return canGuaranteeTCO(CC); 5156 } 5157 } 5158 5159 bool AArch64TargetLowering::isEligibleForTailCallOptimization( 5160 SDValue Callee, CallingConv::ID CalleeCC, bool isVarArg, 5161 const SmallVectorImpl<ISD::OutputArg> &Outs, 5162 const SmallVectorImpl<SDValue> &OutVals, 5163 const SmallVectorImpl<ISD::InputArg> &Ins, SelectionDAG &DAG) const { 5164 if (!mayTailCallThisCC(CalleeCC)) 5165 return false; 5166 5167 MachineFunction &MF = DAG.getMachineFunction(); 5168 const Function &CallerF = MF.getFunction(); 5169 CallingConv::ID CallerCC = CallerF.getCallingConv(); 5170 5171 // Functions using the C or Fast calling convention that have an SVE signature 5172 // preserve more registers and should assume the SVE_VectorCall CC. 5173 // The check for matching callee-saved regs will determine whether it is 5174 // eligible for TCO. 5175 if ((CallerCC == CallingConv::C || CallerCC == CallingConv::Fast) && 5176 AArch64RegisterInfo::hasSVEArgsOrReturn(&MF)) 5177 CallerCC = CallingConv::AArch64_SVE_VectorCall; 5178 5179 bool CCMatch = CallerCC == CalleeCC; 5180 5181 // When using the Windows calling convention on a non-windows OS, we want 5182 // to back up and restore X18 in such functions; we can't do a tail call 5183 // from those functions. 5184 if (CallerCC == CallingConv::Win64 && !Subtarget->isTargetWindows() && 5185 CalleeCC != CallingConv::Win64) 5186 return false; 5187 5188 // Byval parameters hand the function a pointer directly into the stack area 5189 // we want to reuse during a tail call. Working around this *is* possible (see 5190 // X86) but less efficient and uglier in LowerCall. 5191 for (Function::const_arg_iterator i = CallerF.arg_begin(), 5192 e = CallerF.arg_end(); 5193 i != e; ++i) { 5194 if (i->hasByValAttr()) 5195 return false; 5196 5197 // On Windows, "inreg" attributes signify non-aggregate indirect returns. 5198 // In this case, it is necessary to save/restore X0 in the callee. Tail 5199 // call opt interferes with this. So we disable tail call opt when the 5200 // caller has an argument with "inreg" attribute. 5201 5202 // FIXME: Check whether the callee also has an "inreg" argument. 5203 if (i->hasInRegAttr()) 5204 return false; 5205 } 5206 5207 if (getTargetMachine().Options.GuaranteedTailCallOpt) 5208 return canGuaranteeTCO(CalleeCC) && CCMatch; 5209 5210 // Externally-defined functions with weak linkage should not be 5211 // tail-called on AArch64 when the OS does not support dynamic 5212 // pre-emption of symbols, as the AAELF spec requires normal calls 5213 // to undefined weak functions to be replaced with a NOP or jump to the 5214 // next instruction. The behaviour of branch instructions in this 5215 // situation (as used for tail calls) is implementation-defined, so we 5216 // cannot rely on the linker replacing the tail call with a return. 5217 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) { 5218 const GlobalValue *GV = G->getGlobal(); 5219 const Triple &TT = getTargetMachine().getTargetTriple(); 5220 if (GV->hasExternalWeakLinkage() && 5221 (!TT.isOSWindows() || TT.isOSBinFormatELF() || TT.isOSBinFormatMachO())) 5222 return false; 5223 } 5224 5225 // Now we search for cases where we can use a tail call without changing the 5226 // ABI. Sibcall is used in some places (particularly gcc) to refer to this 5227 // concept. 5228 5229 // I want anyone implementing a new calling convention to think long and hard 5230 // about this assert. 5231 assert((!isVarArg || CalleeCC == CallingConv::C) && 5232 "Unexpected variadic calling convention"); 5233 5234 LLVMContext &C = *DAG.getContext(); 5235 if (isVarArg && !Outs.empty()) { 5236 // At least two cases here: if caller is fastcc then we can't have any 5237 // memory arguments (we'd be expected to clean up the stack afterwards). If 5238 // caller is C then we could potentially use its argument area. 5239 5240 // FIXME: for now we take the most conservative of these in both cases: 5241 // disallow all variadic memory operands. 5242 SmallVector<CCValAssign, 16> ArgLocs; 5243 CCState CCInfo(CalleeCC, isVarArg, MF, ArgLocs, C); 5244 5245 CCInfo.AnalyzeCallOperands(Outs, CCAssignFnForCall(CalleeCC, true)); 5246 for (const CCValAssign &ArgLoc : ArgLocs) 5247 if (!ArgLoc.isRegLoc()) 5248 return false; 5249 } 5250 5251 // Check that the call results are passed in the same way. 5252 if (!CCState::resultsCompatible(CalleeCC, CallerCC, MF, C, Ins, 5253 CCAssignFnForCall(CalleeCC, isVarArg), 5254 CCAssignFnForCall(CallerCC, isVarArg))) 5255 return false; 5256 // The callee has to preserve all registers the caller needs to preserve. 5257 const AArch64RegisterInfo *TRI = Subtarget->getRegisterInfo(); 5258 const uint32_t *CallerPreserved = TRI->getCallPreservedMask(MF, CallerCC); 5259 if (!CCMatch) { 5260 const uint32_t *CalleePreserved = TRI->getCallPreservedMask(MF, CalleeCC); 5261 if (Subtarget->hasCustomCallingConv()) { 5262 TRI->UpdateCustomCallPreservedMask(MF, &CallerPreserved); 5263 TRI->UpdateCustomCallPreservedMask(MF, &CalleePreserved); 5264 } 5265 if (!TRI->regmaskSubsetEqual(CallerPreserved, CalleePreserved)) 5266 return false; 5267 } 5268 5269 // Nothing more to check if the callee is taking no arguments 5270 if (Outs.empty()) 5271 return true; 5272 5273 SmallVector<CCValAssign, 16> ArgLocs; 5274 CCState CCInfo(CalleeCC, isVarArg, MF, ArgLocs, C); 5275 5276 CCInfo.AnalyzeCallOperands(Outs, CCAssignFnForCall(CalleeCC, isVarArg)); 5277 5278 const AArch64FunctionInfo *FuncInfo = MF.getInfo<AArch64FunctionInfo>(); 5279 5280 // If any of the arguments is passed indirectly, it must be SVE, so the 5281 // 'getBytesInStackArgArea' is not sufficient to determine whether we need to 5282 // allocate space on the stack. That is why we determine this explicitly here 5283 // the call cannot be a tailcall. 5284 if (llvm::any_of(ArgLocs, [](CCValAssign &A) { 5285 assert((A.getLocInfo() != CCValAssign::Indirect || 5286 A.getValVT().isScalableVector()) && 5287 "Expected value to be scalable"); 5288 return A.getLocInfo() == CCValAssign::Indirect; 5289 })) 5290 return false; 5291 5292 // If the stack arguments for this call do not fit into our own save area then 5293 // the call cannot be made tail. 5294 if (CCInfo.getNextStackOffset() > FuncInfo->getBytesInStackArgArea()) 5295 return false; 5296 5297 const MachineRegisterInfo &MRI = MF.getRegInfo(); 5298 if (!parametersInCSRMatch(MRI, CallerPreserved, ArgLocs, OutVals)) 5299 return false; 5300 5301 return true; 5302 } 5303 5304 SDValue AArch64TargetLowering::addTokenForArgument(SDValue Chain, 5305 SelectionDAG &DAG, 5306 MachineFrameInfo &MFI, 5307 int ClobberedFI) const { 5308 SmallVector<SDValue, 8> ArgChains; 5309 int64_t FirstByte = MFI.getObjectOffset(ClobberedFI); 5310 int64_t LastByte = FirstByte + MFI.getObjectSize(ClobberedFI) - 1; 5311 5312 // Include the original chain at the beginning of the list. When this is 5313 // used by target LowerCall hooks, this helps legalize find the 5314 // CALLSEQ_BEGIN node. 5315 ArgChains.push_back(Chain); 5316 5317 // Add a chain value for each stack argument corresponding 5318 for (SDNode::use_iterator U = DAG.getEntryNode().getNode()->use_begin(), 5319 UE = DAG.getEntryNode().getNode()->use_end(); 5320 U != UE; ++U) 5321 if (LoadSDNode *L = dyn_cast<LoadSDNode>(*U)) 5322 if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(L->getBasePtr())) 5323 if (FI->getIndex() < 0) { 5324 int64_t InFirstByte = MFI.getObjectOffset(FI->getIndex()); 5325 int64_t InLastByte = InFirstByte; 5326 InLastByte += MFI.getObjectSize(FI->getIndex()) - 1; 5327 5328 if ((InFirstByte <= FirstByte && FirstByte <= InLastByte) || 5329 (FirstByte <= InFirstByte && InFirstByte <= LastByte)) 5330 ArgChains.push_back(SDValue(L, 1)); 5331 } 5332 5333 // Build a tokenfactor for all the chains. 5334 return DAG.getNode(ISD::TokenFactor, SDLoc(Chain), MVT::Other, ArgChains); 5335 } 5336 5337 bool AArch64TargetLowering::DoesCalleeRestoreStack(CallingConv::ID CallCC, 5338 bool TailCallOpt) const { 5339 return CallCC == CallingConv::Fast && TailCallOpt; 5340 } 5341 5342 /// LowerCall - Lower a call to a callseq_start + CALL + callseq_end chain, 5343 /// and add input and output parameter nodes. 5344 SDValue 5345 AArch64TargetLowering::LowerCall(CallLoweringInfo &CLI, 5346 SmallVectorImpl<SDValue> &InVals) const { 5347 SelectionDAG &DAG = CLI.DAG; 5348 SDLoc &DL = CLI.DL; 5349 SmallVector<ISD::OutputArg, 32> &Outs = CLI.Outs; 5350 SmallVector<SDValue, 32> &OutVals = CLI.OutVals; 5351 SmallVector<ISD::InputArg, 32> &Ins = CLI.Ins; 5352 SDValue Chain = CLI.Chain; 5353 SDValue Callee = CLI.Callee; 5354 bool &IsTailCall = CLI.IsTailCall; 5355 CallingConv::ID CallConv = CLI.CallConv; 5356 bool IsVarArg = CLI.IsVarArg; 5357 5358 MachineFunction &MF = DAG.getMachineFunction(); 5359 MachineFunction::CallSiteInfo CSInfo; 5360 bool IsThisReturn = false; 5361 5362 AArch64FunctionInfo *FuncInfo = MF.getInfo<AArch64FunctionInfo>(); 5363 bool TailCallOpt = MF.getTarget().Options.GuaranteedTailCallOpt; 5364 bool IsSibCall = false; 5365 5366 // Check callee args/returns for SVE registers and set calling convention 5367 // accordingly. 5368 if (CallConv == CallingConv::C || CallConv == CallingConv::Fast) { 5369 bool CalleeOutSVE = any_of(Outs, [](ISD::OutputArg &Out){ 5370 return Out.VT.isScalableVector(); 5371 }); 5372 bool CalleeInSVE = any_of(Ins, [](ISD::InputArg &In){ 5373 return In.VT.isScalableVector(); 5374 }); 5375 5376 if (CalleeInSVE || CalleeOutSVE) 5377 CallConv = CallingConv::AArch64_SVE_VectorCall; 5378 } 5379 5380 if (IsTailCall) { 5381 // Check if it's really possible to do a tail call. 5382 IsTailCall = isEligibleForTailCallOptimization( 5383 Callee, CallConv, IsVarArg, Outs, OutVals, Ins, DAG); 5384 if (!IsTailCall && CLI.CB && CLI.CB->isMustTailCall()) 5385 report_fatal_error("failed to perform tail call elimination on a call " 5386 "site marked musttail"); 5387 5388 // A sibling call is one where we're under the usual C ABI and not planning 5389 // to change that but can still do a tail call: 5390 if (!TailCallOpt && IsTailCall) 5391 IsSibCall = true; 5392 5393 if (IsTailCall) 5394 ++NumTailCalls; 5395 } 5396 5397 // Analyze operands of the call, assigning locations to each operand. 5398 SmallVector<CCValAssign, 16> ArgLocs; 5399 CCState CCInfo(CallConv, IsVarArg, DAG.getMachineFunction(), ArgLocs, 5400 *DAG.getContext()); 5401 5402 if (IsVarArg) { 5403 // Handle fixed and variable vector arguments differently. 5404 // Variable vector arguments always go into memory. 5405 unsigned NumArgs = Outs.size(); 5406 5407 for (unsigned i = 0; i != NumArgs; ++i) { 5408 MVT ArgVT = Outs[i].VT; 5409 if (!Outs[i].IsFixed && ArgVT.isScalableVector()) 5410 report_fatal_error("Passing SVE types to variadic functions is " 5411 "currently not supported"); 5412 5413 ISD::ArgFlagsTy ArgFlags = Outs[i].Flags; 5414 CCAssignFn *AssignFn = CCAssignFnForCall(CallConv, 5415 /*IsVarArg=*/ !Outs[i].IsFixed); 5416 bool Res = AssignFn(i, ArgVT, ArgVT, CCValAssign::Full, ArgFlags, CCInfo); 5417 assert(!Res && "Call operand has unhandled type"); 5418 (void)Res; 5419 } 5420 } else { 5421 // At this point, Outs[].VT may already be promoted to i32. To correctly 5422 // handle passing i8 as i8 instead of i32 on stack, we pass in both i32 and 5423 // i8 to CC_AArch64_AAPCS with i32 being ValVT and i8 being LocVT. 5424 // Since AnalyzeCallOperands uses Ins[].VT for both ValVT and LocVT, here 5425 // we use a special version of AnalyzeCallOperands to pass in ValVT and 5426 // LocVT. 5427 unsigned NumArgs = Outs.size(); 5428 for (unsigned i = 0; i != NumArgs; ++i) { 5429 MVT ValVT = Outs[i].VT; 5430 // Get type of the original argument. 5431 EVT ActualVT = getValueType(DAG.getDataLayout(), 5432 CLI.getArgs()[Outs[i].OrigArgIndex].Ty, 5433 /*AllowUnknown*/ true); 5434 MVT ActualMVT = ActualVT.isSimple() ? ActualVT.getSimpleVT() : ValVT; 5435 ISD::ArgFlagsTy ArgFlags = Outs[i].Flags; 5436 // If ActualMVT is i1/i8/i16, we should set LocVT to i8/i8/i16. 5437 if (ActualMVT == MVT::i1 || ActualMVT == MVT::i8) 5438 ValVT = MVT::i8; 5439 else if (ActualMVT == MVT::i16) 5440 ValVT = MVT::i16; 5441 5442 CCAssignFn *AssignFn = CCAssignFnForCall(CallConv, /*IsVarArg=*/false); 5443 bool Res = AssignFn(i, ValVT, ValVT, CCValAssign::Full, ArgFlags, CCInfo); 5444 assert(!Res && "Call operand has unhandled type"); 5445 (void)Res; 5446 } 5447 } 5448 5449 // Get a count of how many bytes are to be pushed on the stack. 5450 unsigned NumBytes = CCInfo.getNextStackOffset(); 5451 5452 if (IsSibCall) { 5453 // Since we're not changing the ABI to make this a tail call, the memory 5454 // operands are already available in the caller's incoming argument space. 5455 NumBytes = 0; 5456 } 5457 5458 // FPDiff is the byte offset of the call's argument area from the callee's. 5459 // Stores to callee stack arguments will be placed in FixedStackSlots offset 5460 // by this amount for a tail call. In a sibling call it must be 0 because the 5461 // caller will deallocate the entire stack and the callee still expects its 5462 // arguments to begin at SP+0. Completely unused for non-tail calls. 5463 int FPDiff = 0; 5464 5465 if (IsTailCall && !IsSibCall) { 5466 unsigned NumReusableBytes = FuncInfo->getBytesInStackArgArea(); 5467 5468 // Since callee will pop argument stack as a tail call, we must keep the 5469 // popped size 16-byte aligned. 5470 NumBytes = alignTo(NumBytes, 16); 5471 5472 // FPDiff will be negative if this tail call requires more space than we 5473 // would automatically have in our incoming argument space. Positive if we 5474 // can actually shrink the stack. 5475 FPDiff = NumReusableBytes - NumBytes; 5476 5477 // The stack pointer must be 16-byte aligned at all times it's used for a 5478 // memory operation, which in practice means at *all* times and in 5479 // particular across call boundaries. Therefore our own arguments started at 5480 // a 16-byte aligned SP and the delta applied for the tail call should 5481 // satisfy the same constraint. 5482 assert(FPDiff % 16 == 0 && "unaligned stack on tail call"); 5483 } 5484 5485 // Adjust the stack pointer for the new arguments... 5486 // These operations are automatically eliminated by the prolog/epilog pass 5487 if (!IsSibCall) 5488 Chain = DAG.getCALLSEQ_START(Chain, NumBytes, 0, DL); 5489 5490 SDValue StackPtr = DAG.getCopyFromReg(Chain, DL, AArch64::SP, 5491 getPointerTy(DAG.getDataLayout())); 5492 5493 SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass; 5494 SmallSet<unsigned, 8> RegsUsed; 5495 SmallVector<SDValue, 8> MemOpChains; 5496 auto PtrVT = getPointerTy(DAG.getDataLayout()); 5497 5498 if (IsVarArg && CLI.CB && CLI.CB->isMustTailCall()) { 5499 const auto &Forwards = FuncInfo->getForwardedMustTailRegParms(); 5500 for (const auto &F : Forwards) { 5501 SDValue Val = DAG.getCopyFromReg(Chain, DL, F.VReg, F.VT); 5502 RegsToPass.emplace_back(F.PReg, Val); 5503 } 5504 } 5505 5506 // Walk the register/memloc assignments, inserting copies/loads. 5507 unsigned ExtraArgLocs = 0; 5508 for (unsigned i = 0, e = Outs.size(); i != e; ++i) { 5509 CCValAssign &VA = ArgLocs[i - ExtraArgLocs]; 5510 SDValue Arg = OutVals[i]; 5511 ISD::ArgFlagsTy Flags = Outs[i].Flags; 5512 5513 // Promote the value if needed. 5514 switch (VA.getLocInfo()) { 5515 default: 5516 llvm_unreachable("Unknown loc info!"); 5517 case CCValAssign::Full: 5518 break; 5519 case CCValAssign::SExt: 5520 Arg = DAG.getNode(ISD::SIGN_EXTEND, DL, VA.getLocVT(), Arg); 5521 break; 5522 case CCValAssign::ZExt: 5523 Arg = DAG.getNode(ISD::ZERO_EXTEND, DL, VA.getLocVT(), Arg); 5524 break; 5525 case CCValAssign::AExt: 5526 if (Outs[i].ArgVT == MVT::i1) { 5527 // AAPCS requires i1 to be zero-extended to 8-bits by the caller. 5528 Arg = DAG.getNode(ISD::TRUNCATE, DL, MVT::i1, Arg); 5529 Arg = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i8, Arg); 5530 } 5531 Arg = DAG.getNode(ISD::ANY_EXTEND, DL, VA.getLocVT(), Arg); 5532 break; 5533 case CCValAssign::AExtUpper: 5534 assert(VA.getValVT() == MVT::i32 && "only expect 32 -> 64 upper bits"); 5535 Arg = DAG.getNode(ISD::ANY_EXTEND, DL, VA.getLocVT(), Arg); 5536 Arg = DAG.getNode(ISD::SHL, DL, VA.getLocVT(), Arg, 5537 DAG.getConstant(32, DL, VA.getLocVT())); 5538 break; 5539 case CCValAssign::BCvt: 5540 Arg = DAG.getBitcast(VA.getLocVT(), Arg); 5541 break; 5542 case CCValAssign::Trunc: 5543 Arg = DAG.getZExtOrTrunc(Arg, DL, VA.getLocVT()); 5544 break; 5545 case CCValAssign::FPExt: 5546 Arg = DAG.getNode(ISD::FP_EXTEND, DL, VA.getLocVT(), Arg); 5547 break; 5548 case CCValAssign::Indirect: 5549 assert(VA.getValVT().isScalableVector() && 5550 "Only scalable vectors can be passed indirectly"); 5551 5552 uint64_t StoreSize = VA.getValVT().getStoreSize().getKnownMinSize(); 5553 uint64_t PartSize = StoreSize; 5554 unsigned NumParts = 1; 5555 if (Outs[i].Flags.isInConsecutiveRegs()) { 5556 assert(!Outs[i].Flags.isInConsecutiveRegsLast()); 5557 while (!Outs[i + NumParts - 1].Flags.isInConsecutiveRegsLast()) 5558 ++NumParts; 5559 StoreSize *= NumParts; 5560 } 5561 5562 MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo(); 5563 Type *Ty = EVT(VA.getValVT()).getTypeForEVT(*DAG.getContext()); 5564 Align Alignment = DAG.getDataLayout().getPrefTypeAlign(Ty); 5565 int FI = MFI.CreateStackObject(StoreSize, Alignment, false); 5566 MFI.setStackID(FI, TargetStackID::ScalableVector); 5567 5568 MachinePointerInfo MPI = 5569 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI); 5570 SDValue Ptr = DAG.getFrameIndex( 5571 FI, DAG.getTargetLoweringInfo().getFrameIndexTy(DAG.getDataLayout())); 5572 SDValue SpillSlot = Ptr; 5573 5574 // Ensure we generate all stores for each tuple part, whilst updating the 5575 // pointer after each store correctly using vscale. 5576 while (NumParts) { 5577 Chain = DAG.getStore(Chain, DL, OutVals[i], Ptr, MPI); 5578 NumParts--; 5579 if (NumParts > 0) { 5580 SDValue BytesIncrement = DAG.getVScale( 5581 DL, Ptr.getValueType(), 5582 APInt(Ptr.getValueSizeInBits().getFixedSize(), PartSize)); 5583 SDNodeFlags Flags; 5584 Flags.setNoUnsignedWrap(true); 5585 5586 MPI = MachinePointerInfo(MPI.getAddrSpace()); 5587 Ptr = DAG.getNode(ISD::ADD, DL, Ptr.getValueType(), Ptr, 5588 BytesIncrement, Flags); 5589 ExtraArgLocs++; 5590 i++; 5591 } 5592 } 5593 5594 Arg = SpillSlot; 5595 break; 5596 } 5597 5598 if (VA.isRegLoc()) { 5599 if (i == 0 && Flags.isReturned() && !Flags.isSwiftSelf() && 5600 Outs[0].VT == MVT::i64) { 5601 assert(VA.getLocVT() == MVT::i64 && 5602 "unexpected calling convention register assignment"); 5603 assert(!Ins.empty() && Ins[0].VT == MVT::i64 && 5604 "unexpected use of 'returned'"); 5605 IsThisReturn = true; 5606 } 5607 if (RegsUsed.count(VA.getLocReg())) { 5608 // If this register has already been used then we're trying to pack 5609 // parts of an [N x i32] into an X-register. The extension type will 5610 // take care of putting the two halves in the right place but we have to 5611 // combine them. 5612 SDValue &Bits = 5613 llvm::find_if(RegsToPass, 5614 [=](const std::pair<unsigned, SDValue> &Elt) { 5615 return Elt.first == VA.getLocReg(); 5616 }) 5617 ->second; 5618 Bits = DAG.getNode(ISD::OR, DL, Bits.getValueType(), Bits, Arg); 5619 // Call site info is used for function's parameter entry value 5620 // tracking. For now we track only simple cases when parameter 5621 // is transferred through whole register. 5622 llvm::erase_if(CSInfo, [&VA](MachineFunction::ArgRegPair ArgReg) { 5623 return ArgReg.Reg == VA.getLocReg(); 5624 }); 5625 } else { 5626 RegsToPass.emplace_back(VA.getLocReg(), Arg); 5627 RegsUsed.insert(VA.getLocReg()); 5628 const TargetOptions &Options = DAG.getTarget().Options; 5629 if (Options.EmitCallSiteInfo) 5630 CSInfo.emplace_back(VA.getLocReg(), i); 5631 } 5632 } else { 5633 assert(VA.isMemLoc()); 5634 5635 SDValue DstAddr; 5636 MachinePointerInfo DstInfo; 5637 5638 // FIXME: This works on big-endian for composite byvals, which are the 5639 // common case. It should also work for fundamental types too. 5640 uint32_t BEAlign = 0; 5641 unsigned OpSize; 5642 if (VA.getLocInfo() == CCValAssign::Indirect) 5643 OpSize = VA.getLocVT().getFixedSizeInBits(); 5644 else 5645 OpSize = Flags.isByVal() ? Flags.getByValSize() * 8 5646 : VA.getValVT().getSizeInBits(); 5647 OpSize = (OpSize + 7) / 8; 5648 if (!Subtarget->isLittleEndian() && !Flags.isByVal() && 5649 !Flags.isInConsecutiveRegs()) { 5650 if (OpSize < 8) 5651 BEAlign = 8 - OpSize; 5652 } 5653 unsigned LocMemOffset = VA.getLocMemOffset(); 5654 int32_t Offset = LocMemOffset + BEAlign; 5655 SDValue PtrOff = DAG.getIntPtrConstant(Offset, DL); 5656 PtrOff = DAG.getNode(ISD::ADD, DL, PtrVT, StackPtr, PtrOff); 5657 5658 if (IsTailCall) { 5659 Offset = Offset + FPDiff; 5660 int FI = MF.getFrameInfo().CreateFixedObject(OpSize, Offset, true); 5661 5662 DstAddr = DAG.getFrameIndex(FI, PtrVT); 5663 DstInfo = 5664 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI); 5665 5666 // Make sure any stack arguments overlapping with where we're storing 5667 // are loaded before this eventual operation. Otherwise they'll be 5668 // clobbered. 5669 Chain = addTokenForArgument(Chain, DAG, MF.getFrameInfo(), FI); 5670 } else { 5671 SDValue PtrOff = DAG.getIntPtrConstant(Offset, DL); 5672 5673 DstAddr = DAG.getNode(ISD::ADD, DL, PtrVT, StackPtr, PtrOff); 5674 DstInfo = MachinePointerInfo::getStack(DAG.getMachineFunction(), 5675 LocMemOffset); 5676 } 5677 5678 if (Outs[i].Flags.isByVal()) { 5679 SDValue SizeNode = 5680 DAG.getConstant(Outs[i].Flags.getByValSize(), DL, MVT::i64); 5681 SDValue Cpy = DAG.getMemcpy( 5682 Chain, DL, DstAddr, Arg, SizeNode, 5683 Outs[i].Flags.getNonZeroByValAlign(), 5684 /*isVol = */ false, /*AlwaysInline = */ false, 5685 /*isTailCall = */ false, DstInfo, MachinePointerInfo()); 5686 5687 MemOpChains.push_back(Cpy); 5688 } else { 5689 // Since we pass i1/i8/i16 as i1/i8/i16 on stack and Arg is already 5690 // promoted to a legal register type i32, we should truncate Arg back to 5691 // i1/i8/i16. 5692 if (VA.getValVT() == MVT::i1 || VA.getValVT() == MVT::i8 || 5693 VA.getValVT() == MVT::i16) 5694 Arg = DAG.getNode(ISD::TRUNCATE, DL, VA.getValVT(), Arg); 5695 5696 SDValue Store = DAG.getStore(Chain, DL, Arg, DstAddr, DstInfo); 5697 MemOpChains.push_back(Store); 5698 } 5699 } 5700 } 5701 5702 if (!MemOpChains.empty()) 5703 Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, MemOpChains); 5704 5705 // Build a sequence of copy-to-reg nodes chained together with token chain 5706 // and flag operands which copy the outgoing args into the appropriate regs. 5707 SDValue InFlag; 5708 for (auto &RegToPass : RegsToPass) { 5709 Chain = DAG.getCopyToReg(Chain, DL, RegToPass.first, 5710 RegToPass.second, InFlag); 5711 InFlag = Chain.getValue(1); 5712 } 5713 5714 // If the callee is a GlobalAddress/ExternalSymbol node (quite common, every 5715 // direct call is) turn it into a TargetGlobalAddress/TargetExternalSymbol 5716 // node so that legalize doesn't hack it. 5717 if (auto *G = dyn_cast<GlobalAddressSDNode>(Callee)) { 5718 auto GV = G->getGlobal(); 5719 unsigned OpFlags = 5720 Subtarget->classifyGlobalFunctionReference(GV, getTargetMachine()); 5721 if (OpFlags & AArch64II::MO_GOT) { 5722 Callee = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, OpFlags); 5723 Callee = DAG.getNode(AArch64ISD::LOADgot, DL, PtrVT, Callee); 5724 } else { 5725 const GlobalValue *GV = G->getGlobal(); 5726 Callee = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, 0); 5727 } 5728 } else if (auto *S = dyn_cast<ExternalSymbolSDNode>(Callee)) { 5729 if (getTargetMachine().getCodeModel() == CodeModel::Large && 5730 Subtarget->isTargetMachO()) { 5731 const char *Sym = S->getSymbol(); 5732 Callee = DAG.getTargetExternalSymbol(Sym, PtrVT, AArch64II::MO_GOT); 5733 Callee = DAG.getNode(AArch64ISD::LOADgot, DL, PtrVT, Callee); 5734 } else { 5735 const char *Sym = S->getSymbol(); 5736 Callee = DAG.getTargetExternalSymbol(Sym, PtrVT, 0); 5737 } 5738 } 5739 5740 // We don't usually want to end the call-sequence here because we would tidy 5741 // the frame up *after* the call, however in the ABI-changing tail-call case 5742 // we've carefully laid out the parameters so that when sp is reset they'll be 5743 // in the correct location. 5744 if (IsTailCall && !IsSibCall) { 5745 Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, DL, true), 5746 DAG.getIntPtrConstant(0, DL, true), InFlag, DL); 5747 InFlag = Chain.getValue(1); 5748 } 5749 5750 std::vector<SDValue> Ops; 5751 Ops.push_back(Chain); 5752 Ops.push_back(Callee); 5753 5754 if (IsTailCall) { 5755 // Each tail call may have to adjust the stack by a different amount, so 5756 // this information must travel along with the operation for eventual 5757 // consumption by emitEpilogue. 5758 Ops.push_back(DAG.getTargetConstant(FPDiff, DL, MVT::i32)); 5759 } 5760 5761 // Add argument registers to the end of the list so that they are known live 5762 // into the call. 5763 for (auto &RegToPass : RegsToPass) 5764 Ops.push_back(DAG.getRegister(RegToPass.first, 5765 RegToPass.second.getValueType())); 5766 5767 // Add a register mask operand representing the call-preserved registers. 5768 const uint32_t *Mask; 5769 const AArch64RegisterInfo *TRI = Subtarget->getRegisterInfo(); 5770 if (IsThisReturn) { 5771 // For 'this' returns, use the X0-preserving mask if applicable 5772 Mask = TRI->getThisReturnPreservedMask(MF, CallConv); 5773 if (!Mask) { 5774 IsThisReturn = false; 5775 Mask = TRI->getCallPreservedMask(MF, CallConv); 5776 } 5777 } else 5778 Mask = TRI->getCallPreservedMask(MF, CallConv); 5779 5780 if (Subtarget->hasCustomCallingConv()) 5781 TRI->UpdateCustomCallPreservedMask(MF, &Mask); 5782 5783 if (TRI->isAnyArgRegReserved(MF)) 5784 TRI->emitReservedArgRegCallError(MF); 5785 5786 assert(Mask && "Missing call preserved mask for calling convention"); 5787 Ops.push_back(DAG.getRegisterMask(Mask)); 5788 5789 if (InFlag.getNode()) 5790 Ops.push_back(InFlag); 5791 5792 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue); 5793 5794 // If we're doing a tall call, use a TC_RETURN here rather than an 5795 // actual call instruction. 5796 if (IsTailCall) { 5797 MF.getFrameInfo().setHasTailCall(); 5798 SDValue Ret = DAG.getNode(AArch64ISD::TC_RETURN, DL, NodeTys, Ops); 5799 DAG.addCallSiteInfo(Ret.getNode(), std::move(CSInfo)); 5800 return Ret; 5801 } 5802 5803 unsigned CallOpc = AArch64ISD::CALL; 5804 // Calls with operand bundle "clang.arc.attachedcall" are special. They should 5805 // be expanded to the call, directly followed by a special marker sequence. 5806 // Use the CALL_RVMARKER to do that. 5807 if (CLI.CB && objcarc::hasAttachedCallOpBundle(CLI.CB)) { 5808 assert(!IsTailCall && 5809 "tail calls cannot be marked with clang.arc.attachedcall"); 5810 CallOpc = AArch64ISD::CALL_RVMARKER; 5811 } 5812 5813 // Returns a chain and a flag for retval copy to use. 5814 Chain = DAG.getNode(CallOpc, DL, NodeTys, Ops); 5815 DAG.addNoMergeSiteInfo(Chain.getNode(), CLI.NoMerge); 5816 InFlag = Chain.getValue(1); 5817 DAG.addCallSiteInfo(Chain.getNode(), std::move(CSInfo)); 5818 5819 uint64_t CalleePopBytes = 5820 DoesCalleeRestoreStack(CallConv, TailCallOpt) ? alignTo(NumBytes, 16) : 0; 5821 5822 Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, DL, true), 5823 DAG.getIntPtrConstant(CalleePopBytes, DL, true), 5824 InFlag, DL); 5825 if (!Ins.empty()) 5826 InFlag = Chain.getValue(1); 5827 5828 // Handle result values, copying them out of physregs into vregs that we 5829 // return. 5830 return LowerCallResult(Chain, InFlag, CallConv, IsVarArg, Ins, DL, DAG, 5831 InVals, IsThisReturn, 5832 IsThisReturn ? OutVals[0] : SDValue()); 5833 } 5834 5835 bool AArch64TargetLowering::CanLowerReturn( 5836 CallingConv::ID CallConv, MachineFunction &MF, bool isVarArg, 5837 const SmallVectorImpl<ISD::OutputArg> &Outs, LLVMContext &Context) const { 5838 CCAssignFn *RetCC = CCAssignFnForReturn(CallConv); 5839 SmallVector<CCValAssign, 16> RVLocs; 5840 CCState CCInfo(CallConv, isVarArg, MF, RVLocs, Context); 5841 return CCInfo.CheckReturn(Outs, RetCC); 5842 } 5843 5844 SDValue 5845 AArch64TargetLowering::LowerReturn(SDValue Chain, CallingConv::ID CallConv, 5846 bool isVarArg, 5847 const SmallVectorImpl<ISD::OutputArg> &Outs, 5848 const SmallVectorImpl<SDValue> &OutVals, 5849 const SDLoc &DL, SelectionDAG &DAG) const { 5850 auto &MF = DAG.getMachineFunction(); 5851 auto *FuncInfo = MF.getInfo<AArch64FunctionInfo>(); 5852 5853 CCAssignFn *RetCC = CCAssignFnForReturn(CallConv); 5854 SmallVector<CCValAssign, 16> RVLocs; 5855 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs, 5856 *DAG.getContext()); 5857 CCInfo.AnalyzeReturn(Outs, RetCC); 5858 5859 // Copy the result values into the output registers. 5860 SDValue Flag; 5861 SmallVector<std::pair<unsigned, SDValue>, 4> RetVals; 5862 SmallSet<unsigned, 4> RegsUsed; 5863 for (unsigned i = 0, realRVLocIdx = 0; i != RVLocs.size(); 5864 ++i, ++realRVLocIdx) { 5865 CCValAssign &VA = RVLocs[i]; 5866 assert(VA.isRegLoc() && "Can only return in registers!"); 5867 SDValue Arg = OutVals[realRVLocIdx]; 5868 5869 switch (VA.getLocInfo()) { 5870 default: 5871 llvm_unreachable("Unknown loc info!"); 5872 case CCValAssign::Full: 5873 if (Outs[i].ArgVT == MVT::i1) { 5874 // AAPCS requires i1 to be zero-extended to i8 by the producer of the 5875 // value. This is strictly redundant on Darwin (which uses "zeroext 5876 // i1"), but will be optimised out before ISel. 5877 Arg = DAG.getNode(ISD::TRUNCATE, DL, MVT::i1, Arg); 5878 Arg = DAG.getNode(ISD::ZERO_EXTEND, DL, VA.getLocVT(), Arg); 5879 } 5880 break; 5881 case CCValAssign::BCvt: 5882 Arg = DAG.getNode(ISD::BITCAST, DL, VA.getLocVT(), Arg); 5883 break; 5884 case CCValAssign::AExt: 5885 case CCValAssign::ZExt: 5886 Arg = DAG.getZExtOrTrunc(Arg, DL, VA.getLocVT()); 5887 break; 5888 case CCValAssign::AExtUpper: 5889 assert(VA.getValVT() == MVT::i32 && "only expect 32 -> 64 upper bits"); 5890 Arg = DAG.getZExtOrTrunc(Arg, DL, VA.getLocVT()); 5891 Arg = DAG.getNode(ISD::SHL, DL, VA.getLocVT(), Arg, 5892 DAG.getConstant(32, DL, VA.getLocVT())); 5893 break; 5894 } 5895 5896 if (RegsUsed.count(VA.getLocReg())) { 5897 SDValue &Bits = 5898 llvm::find_if(RetVals, [=](const std::pair<unsigned, SDValue> &Elt) { 5899 return Elt.first == VA.getLocReg(); 5900 })->second; 5901 Bits = DAG.getNode(ISD::OR, DL, Bits.getValueType(), Bits, Arg); 5902 } else { 5903 RetVals.emplace_back(VA.getLocReg(), Arg); 5904 RegsUsed.insert(VA.getLocReg()); 5905 } 5906 } 5907 5908 SmallVector<SDValue, 4> RetOps(1, Chain); 5909 for (auto &RetVal : RetVals) { 5910 Chain = DAG.getCopyToReg(Chain, DL, RetVal.first, RetVal.second, Flag); 5911 Flag = Chain.getValue(1); 5912 RetOps.push_back( 5913 DAG.getRegister(RetVal.first, RetVal.second.getValueType())); 5914 } 5915 5916 // Windows AArch64 ABIs require that for returning structs by value we copy 5917 // the sret argument into X0 for the return. 5918 // We saved the argument into a virtual register in the entry block, 5919 // so now we copy the value out and into X0. 5920 if (unsigned SRetReg = FuncInfo->getSRetReturnReg()) { 5921 SDValue Val = DAG.getCopyFromReg(RetOps[0], DL, SRetReg, 5922 getPointerTy(MF.getDataLayout())); 5923 5924 unsigned RetValReg = AArch64::X0; 5925 Chain = DAG.getCopyToReg(Chain, DL, RetValReg, Val, Flag); 5926 Flag = Chain.getValue(1); 5927 5928 RetOps.push_back( 5929 DAG.getRegister(RetValReg, getPointerTy(DAG.getDataLayout()))); 5930 } 5931 5932 const AArch64RegisterInfo *TRI = Subtarget->getRegisterInfo(); 5933 const MCPhysReg *I = 5934 TRI->getCalleeSavedRegsViaCopy(&DAG.getMachineFunction()); 5935 if (I) { 5936 for (; *I; ++I) { 5937 if (AArch64::GPR64RegClass.contains(*I)) 5938 RetOps.push_back(DAG.getRegister(*I, MVT::i64)); 5939 else if (AArch64::FPR64RegClass.contains(*I)) 5940 RetOps.push_back(DAG.getRegister(*I, MVT::getFloatingPointVT(64))); 5941 else 5942 llvm_unreachable("Unexpected register class in CSRsViaCopy!"); 5943 } 5944 } 5945 5946 RetOps[0] = Chain; // Update chain. 5947 5948 // Add the flag if we have it. 5949 if (Flag.getNode()) 5950 RetOps.push_back(Flag); 5951 5952 return DAG.getNode(AArch64ISD::RET_FLAG, DL, MVT::Other, RetOps); 5953 } 5954 5955 //===----------------------------------------------------------------------===// 5956 // Other Lowering Code 5957 //===----------------------------------------------------------------------===// 5958 5959 SDValue AArch64TargetLowering::getTargetNode(GlobalAddressSDNode *N, EVT Ty, 5960 SelectionDAG &DAG, 5961 unsigned Flag) const { 5962 return DAG.getTargetGlobalAddress(N->getGlobal(), SDLoc(N), Ty, 5963 N->getOffset(), Flag); 5964 } 5965 5966 SDValue AArch64TargetLowering::getTargetNode(JumpTableSDNode *N, EVT Ty, 5967 SelectionDAG &DAG, 5968 unsigned Flag) const { 5969 return DAG.getTargetJumpTable(N->getIndex(), Ty, Flag); 5970 } 5971 5972 SDValue AArch64TargetLowering::getTargetNode(ConstantPoolSDNode *N, EVT Ty, 5973 SelectionDAG &DAG, 5974 unsigned Flag) const { 5975 return DAG.getTargetConstantPool(N->getConstVal(), Ty, N->getAlign(), 5976 N->getOffset(), Flag); 5977 } 5978 5979 SDValue AArch64TargetLowering::getTargetNode(BlockAddressSDNode* N, EVT Ty, 5980 SelectionDAG &DAG, 5981 unsigned Flag) const { 5982 return DAG.getTargetBlockAddress(N->getBlockAddress(), Ty, 0, Flag); 5983 } 5984 5985 // (loadGOT sym) 5986 template <class NodeTy> 5987 SDValue AArch64TargetLowering::getGOT(NodeTy *N, SelectionDAG &DAG, 5988 unsigned Flags) const { 5989 LLVM_DEBUG(dbgs() << "AArch64TargetLowering::getGOT\n"); 5990 SDLoc DL(N); 5991 EVT Ty = getPointerTy(DAG.getDataLayout()); 5992 SDValue GotAddr = getTargetNode(N, Ty, DAG, AArch64II::MO_GOT | Flags); 5993 // FIXME: Once remat is capable of dealing with instructions with register 5994 // operands, expand this into two nodes instead of using a wrapper node. 5995 return DAG.getNode(AArch64ISD::LOADgot, DL, Ty, GotAddr); 5996 } 5997 5998 // (wrapper %highest(sym), %higher(sym), %hi(sym), %lo(sym)) 5999 template <class NodeTy> 6000 SDValue AArch64TargetLowering::getAddrLarge(NodeTy *N, SelectionDAG &DAG, 6001 unsigned Flags) const { 6002 LLVM_DEBUG(dbgs() << "AArch64TargetLowering::getAddrLarge\n"); 6003 SDLoc DL(N); 6004 EVT Ty = getPointerTy(DAG.getDataLayout()); 6005 const unsigned char MO_NC = AArch64II::MO_NC; 6006 return DAG.getNode( 6007 AArch64ISD::WrapperLarge, DL, Ty, 6008 getTargetNode(N, Ty, DAG, AArch64II::MO_G3 | Flags), 6009 getTargetNode(N, Ty, DAG, AArch64II::MO_G2 | MO_NC | Flags), 6010 getTargetNode(N, Ty, DAG, AArch64II::MO_G1 | MO_NC | Flags), 6011 getTargetNode(N, Ty, DAG, AArch64II::MO_G0 | MO_NC | Flags)); 6012 } 6013 6014 // (addlow (adrp %hi(sym)) %lo(sym)) 6015 template <class NodeTy> 6016 SDValue AArch64TargetLowering::getAddr(NodeTy *N, SelectionDAG &DAG, 6017 unsigned Flags) const { 6018 LLVM_DEBUG(dbgs() << "AArch64TargetLowering::getAddr\n"); 6019 SDLoc DL(N); 6020 EVT Ty = getPointerTy(DAG.getDataLayout()); 6021 SDValue Hi = getTargetNode(N, Ty, DAG, AArch64II::MO_PAGE | Flags); 6022 SDValue Lo = getTargetNode(N, Ty, DAG, 6023 AArch64II::MO_PAGEOFF | AArch64II::MO_NC | Flags); 6024 SDValue ADRP = DAG.getNode(AArch64ISD::ADRP, DL, Ty, Hi); 6025 return DAG.getNode(AArch64ISD::ADDlow, DL, Ty, ADRP, Lo); 6026 } 6027 6028 // (adr sym) 6029 template <class NodeTy> 6030 SDValue AArch64TargetLowering::getAddrTiny(NodeTy *N, SelectionDAG &DAG, 6031 unsigned Flags) const { 6032 LLVM_DEBUG(dbgs() << "AArch64TargetLowering::getAddrTiny\n"); 6033 SDLoc DL(N); 6034 EVT Ty = getPointerTy(DAG.getDataLayout()); 6035 SDValue Sym = getTargetNode(N, Ty, DAG, Flags); 6036 return DAG.getNode(AArch64ISD::ADR, DL, Ty, Sym); 6037 } 6038 6039 SDValue AArch64TargetLowering::LowerGlobalAddress(SDValue Op, 6040 SelectionDAG &DAG) const { 6041 GlobalAddressSDNode *GN = cast<GlobalAddressSDNode>(Op); 6042 const GlobalValue *GV = GN->getGlobal(); 6043 unsigned OpFlags = Subtarget->ClassifyGlobalReference(GV, getTargetMachine()); 6044 6045 if (OpFlags != AArch64II::MO_NO_FLAG) 6046 assert(cast<GlobalAddressSDNode>(Op)->getOffset() == 0 && 6047 "unexpected offset in global node"); 6048 6049 // This also catches the large code model case for Darwin, and tiny code 6050 // model with got relocations. 6051 if ((OpFlags & AArch64II::MO_GOT) != 0) { 6052 return getGOT(GN, DAG, OpFlags); 6053 } 6054 6055 SDValue Result; 6056 if (getTargetMachine().getCodeModel() == CodeModel::Large) { 6057 Result = getAddrLarge(GN, DAG, OpFlags); 6058 } else if (getTargetMachine().getCodeModel() == CodeModel::Tiny) { 6059 Result = getAddrTiny(GN, DAG, OpFlags); 6060 } else { 6061 Result = getAddr(GN, DAG, OpFlags); 6062 } 6063 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 6064 SDLoc DL(GN); 6065 if (OpFlags & (AArch64II::MO_DLLIMPORT | AArch64II::MO_COFFSTUB)) 6066 Result = DAG.getLoad(PtrVT, DL, DAG.getEntryNode(), Result, 6067 MachinePointerInfo::getGOT(DAG.getMachineFunction())); 6068 return Result; 6069 } 6070 6071 /// Convert a TLS address reference into the correct sequence of loads 6072 /// and calls to compute the variable's address (for Darwin, currently) and 6073 /// return an SDValue containing the final node. 6074 6075 /// Darwin only has one TLS scheme which must be capable of dealing with the 6076 /// fully general situation, in the worst case. This means: 6077 /// + "extern __thread" declaration. 6078 /// + Defined in a possibly unknown dynamic library. 6079 /// 6080 /// The general system is that each __thread variable has a [3 x i64] descriptor 6081 /// which contains information used by the runtime to calculate the address. The 6082 /// only part of this the compiler needs to know about is the first xword, which 6083 /// contains a function pointer that must be called with the address of the 6084 /// entire descriptor in "x0". 6085 /// 6086 /// Since this descriptor may be in a different unit, in general even the 6087 /// descriptor must be accessed via an indirect load. The "ideal" code sequence 6088 /// is: 6089 /// adrp x0, _var@TLVPPAGE 6090 /// ldr x0, [x0, _var@TLVPPAGEOFF] ; x0 now contains address of descriptor 6091 /// ldr x1, [x0] ; x1 contains 1st entry of descriptor, 6092 /// ; the function pointer 6093 /// blr x1 ; Uses descriptor address in x0 6094 /// ; Address of _var is now in x0. 6095 /// 6096 /// If the address of _var's descriptor *is* known to the linker, then it can 6097 /// change the first "ldr" instruction to an appropriate "add x0, x0, #imm" for 6098 /// a slight efficiency gain. 6099 SDValue 6100 AArch64TargetLowering::LowerDarwinGlobalTLSAddress(SDValue Op, 6101 SelectionDAG &DAG) const { 6102 assert(Subtarget->isTargetDarwin() && 6103 "This function expects a Darwin target"); 6104 6105 SDLoc DL(Op); 6106 MVT PtrVT = getPointerTy(DAG.getDataLayout()); 6107 MVT PtrMemVT = getPointerMemTy(DAG.getDataLayout()); 6108 const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal(); 6109 6110 SDValue TLVPAddr = 6111 DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, AArch64II::MO_TLS); 6112 SDValue DescAddr = DAG.getNode(AArch64ISD::LOADgot, DL, PtrVT, TLVPAddr); 6113 6114 // The first entry in the descriptor is a function pointer that we must call 6115 // to obtain the address of the variable. 6116 SDValue Chain = DAG.getEntryNode(); 6117 SDValue FuncTLVGet = DAG.getLoad( 6118 PtrMemVT, DL, Chain, DescAddr, 6119 MachinePointerInfo::getGOT(DAG.getMachineFunction()), 6120 Align(PtrMemVT.getSizeInBits() / 8), 6121 MachineMemOperand::MOInvariant | MachineMemOperand::MODereferenceable); 6122 Chain = FuncTLVGet.getValue(1); 6123 6124 // Extend loaded pointer if necessary (i.e. if ILP32) to DAG pointer. 6125 FuncTLVGet = DAG.getZExtOrTrunc(FuncTLVGet, DL, PtrVT); 6126 6127 MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo(); 6128 MFI.setAdjustsStack(true); 6129 6130 // TLS calls preserve all registers except those that absolutely must be 6131 // trashed: X0 (it takes an argument), LR (it's a call) and NZCV (let's not be 6132 // silly). 6133 const AArch64RegisterInfo *TRI = Subtarget->getRegisterInfo(); 6134 const uint32_t *Mask = TRI->getTLSCallPreservedMask(); 6135 if (Subtarget->hasCustomCallingConv()) 6136 TRI->UpdateCustomCallPreservedMask(DAG.getMachineFunction(), &Mask); 6137 6138 // Finally, we can make the call. This is just a degenerate version of a 6139 // normal AArch64 call node: x0 takes the address of the descriptor, and 6140 // returns the address of the variable in this thread. 6141 Chain = DAG.getCopyToReg(Chain, DL, AArch64::X0, DescAddr, SDValue()); 6142 Chain = 6143 DAG.getNode(AArch64ISD::CALL, DL, DAG.getVTList(MVT::Other, MVT::Glue), 6144 Chain, FuncTLVGet, DAG.getRegister(AArch64::X0, MVT::i64), 6145 DAG.getRegisterMask(Mask), Chain.getValue(1)); 6146 return DAG.getCopyFromReg(Chain, DL, AArch64::X0, PtrVT, Chain.getValue(1)); 6147 } 6148 6149 /// Convert a thread-local variable reference into a sequence of instructions to 6150 /// compute the variable's address for the local exec TLS model of ELF targets. 6151 /// The sequence depends on the maximum TLS area size. 6152 SDValue AArch64TargetLowering::LowerELFTLSLocalExec(const GlobalValue *GV, 6153 SDValue ThreadBase, 6154 const SDLoc &DL, 6155 SelectionDAG &DAG) const { 6156 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 6157 SDValue TPOff, Addr; 6158 6159 switch (DAG.getTarget().Options.TLSSize) { 6160 default: 6161 llvm_unreachable("Unexpected TLS size"); 6162 6163 case 12: { 6164 // mrs x0, TPIDR_EL0 6165 // add x0, x0, :tprel_lo12:a 6166 SDValue Var = DAG.getTargetGlobalAddress( 6167 GV, DL, PtrVT, 0, AArch64II::MO_TLS | AArch64II::MO_PAGEOFF); 6168 return SDValue(DAG.getMachineNode(AArch64::ADDXri, DL, PtrVT, ThreadBase, 6169 Var, 6170 DAG.getTargetConstant(0, DL, MVT::i32)), 6171 0); 6172 } 6173 6174 case 24: { 6175 // mrs x0, TPIDR_EL0 6176 // add x0, x0, :tprel_hi12:a 6177 // add x0, x0, :tprel_lo12_nc:a 6178 SDValue HiVar = DAG.getTargetGlobalAddress( 6179 GV, DL, PtrVT, 0, AArch64II::MO_TLS | AArch64II::MO_HI12); 6180 SDValue LoVar = DAG.getTargetGlobalAddress( 6181 GV, DL, PtrVT, 0, 6182 AArch64II::MO_TLS | AArch64II::MO_PAGEOFF | AArch64II::MO_NC); 6183 Addr = SDValue(DAG.getMachineNode(AArch64::ADDXri, DL, PtrVT, ThreadBase, 6184 HiVar, 6185 DAG.getTargetConstant(0, DL, MVT::i32)), 6186 0); 6187 return SDValue(DAG.getMachineNode(AArch64::ADDXri, DL, PtrVT, Addr, 6188 LoVar, 6189 DAG.getTargetConstant(0, DL, MVT::i32)), 6190 0); 6191 } 6192 6193 case 32: { 6194 // mrs x1, TPIDR_EL0 6195 // movz x0, #:tprel_g1:a 6196 // movk x0, #:tprel_g0_nc:a 6197 // add x0, x1, x0 6198 SDValue HiVar = DAG.getTargetGlobalAddress( 6199 GV, DL, PtrVT, 0, AArch64II::MO_TLS | AArch64II::MO_G1); 6200 SDValue LoVar = DAG.getTargetGlobalAddress( 6201 GV, DL, PtrVT, 0, 6202 AArch64II::MO_TLS | AArch64II::MO_G0 | AArch64II::MO_NC); 6203 TPOff = SDValue(DAG.getMachineNode(AArch64::MOVZXi, DL, PtrVT, HiVar, 6204 DAG.getTargetConstant(16, DL, MVT::i32)), 6205 0); 6206 TPOff = SDValue(DAG.getMachineNode(AArch64::MOVKXi, DL, PtrVT, TPOff, LoVar, 6207 DAG.getTargetConstant(0, DL, MVT::i32)), 6208 0); 6209 return DAG.getNode(ISD::ADD, DL, PtrVT, ThreadBase, TPOff); 6210 } 6211 6212 case 48: { 6213 // mrs x1, TPIDR_EL0 6214 // movz x0, #:tprel_g2:a 6215 // movk x0, #:tprel_g1_nc:a 6216 // movk x0, #:tprel_g0_nc:a 6217 // add x0, x1, x0 6218 SDValue HiVar = DAG.getTargetGlobalAddress( 6219 GV, DL, PtrVT, 0, AArch64II::MO_TLS | AArch64II::MO_G2); 6220 SDValue MiVar = DAG.getTargetGlobalAddress( 6221 GV, DL, PtrVT, 0, 6222 AArch64II::MO_TLS | AArch64II::MO_G1 | AArch64II::MO_NC); 6223 SDValue LoVar = DAG.getTargetGlobalAddress( 6224 GV, DL, PtrVT, 0, 6225 AArch64II::MO_TLS | AArch64II::MO_G0 | AArch64II::MO_NC); 6226 TPOff = SDValue(DAG.getMachineNode(AArch64::MOVZXi, DL, PtrVT, HiVar, 6227 DAG.getTargetConstant(32, DL, MVT::i32)), 6228 0); 6229 TPOff = SDValue(DAG.getMachineNode(AArch64::MOVKXi, DL, PtrVT, TPOff, MiVar, 6230 DAG.getTargetConstant(16, DL, MVT::i32)), 6231 0); 6232 TPOff = SDValue(DAG.getMachineNode(AArch64::MOVKXi, DL, PtrVT, TPOff, LoVar, 6233 DAG.getTargetConstant(0, DL, MVT::i32)), 6234 0); 6235 return DAG.getNode(ISD::ADD, DL, PtrVT, ThreadBase, TPOff); 6236 } 6237 } 6238 } 6239 6240 /// When accessing thread-local variables under either the general-dynamic or 6241 /// local-dynamic system, we make a "TLS-descriptor" call. The variable will 6242 /// have a descriptor, accessible via a PC-relative ADRP, and whose first entry 6243 /// is a function pointer to carry out the resolution. 6244 /// 6245 /// The sequence is: 6246 /// adrp x0, :tlsdesc:var 6247 /// ldr x1, [x0, #:tlsdesc_lo12:var] 6248 /// add x0, x0, #:tlsdesc_lo12:var 6249 /// .tlsdesccall var 6250 /// blr x1 6251 /// (TPIDR_EL0 offset now in x0) 6252 /// 6253 /// The above sequence must be produced unscheduled, to enable the linker to 6254 /// optimize/relax this sequence. 6255 /// Therefore, a pseudo-instruction (TLSDESC_CALLSEQ) is used to represent the 6256 /// above sequence, and expanded really late in the compilation flow, to ensure 6257 /// the sequence is produced as per above. 6258 SDValue AArch64TargetLowering::LowerELFTLSDescCallSeq(SDValue SymAddr, 6259 const SDLoc &DL, 6260 SelectionDAG &DAG) const { 6261 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 6262 6263 SDValue Chain = DAG.getEntryNode(); 6264 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue); 6265 6266 Chain = 6267 DAG.getNode(AArch64ISD::TLSDESC_CALLSEQ, DL, NodeTys, {Chain, SymAddr}); 6268 SDValue Glue = Chain.getValue(1); 6269 6270 return DAG.getCopyFromReg(Chain, DL, AArch64::X0, PtrVT, Glue); 6271 } 6272 6273 SDValue 6274 AArch64TargetLowering::LowerELFGlobalTLSAddress(SDValue Op, 6275 SelectionDAG &DAG) const { 6276 assert(Subtarget->isTargetELF() && "This function expects an ELF target"); 6277 6278 const GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op); 6279 6280 TLSModel::Model Model = getTargetMachine().getTLSModel(GA->getGlobal()); 6281 6282 if (!EnableAArch64ELFLocalDynamicTLSGeneration) { 6283 if (Model == TLSModel::LocalDynamic) 6284 Model = TLSModel::GeneralDynamic; 6285 } 6286 6287 if (getTargetMachine().getCodeModel() == CodeModel::Large && 6288 Model != TLSModel::LocalExec) 6289 report_fatal_error("ELF TLS only supported in small memory model or " 6290 "in local exec TLS model"); 6291 // Different choices can be made for the maximum size of the TLS area for a 6292 // module. For the small address model, the default TLS size is 16MiB and the 6293 // maximum TLS size is 4GiB. 6294 // FIXME: add tiny and large code model support for TLS access models other 6295 // than local exec. We currently generate the same code as small for tiny, 6296 // which may be larger than needed. 6297 6298 SDValue TPOff; 6299 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 6300 SDLoc DL(Op); 6301 const GlobalValue *GV = GA->getGlobal(); 6302 6303 SDValue ThreadBase = DAG.getNode(AArch64ISD::THREAD_POINTER, DL, PtrVT); 6304 6305 if (Model == TLSModel::LocalExec) { 6306 return LowerELFTLSLocalExec(GV, ThreadBase, DL, DAG); 6307 } else if (Model == TLSModel::InitialExec) { 6308 TPOff = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, AArch64II::MO_TLS); 6309 TPOff = DAG.getNode(AArch64ISD::LOADgot, DL, PtrVT, TPOff); 6310 } else if (Model == TLSModel::LocalDynamic) { 6311 // Local-dynamic accesses proceed in two phases. A general-dynamic TLS 6312 // descriptor call against the special symbol _TLS_MODULE_BASE_ to calculate 6313 // the beginning of the module's TLS region, followed by a DTPREL offset 6314 // calculation. 6315 6316 // These accesses will need deduplicating if there's more than one. 6317 AArch64FunctionInfo *MFI = 6318 DAG.getMachineFunction().getInfo<AArch64FunctionInfo>(); 6319 MFI->incNumLocalDynamicTLSAccesses(); 6320 6321 // The call needs a relocation too for linker relaxation. It doesn't make 6322 // sense to call it MO_PAGE or MO_PAGEOFF though so we need another copy of 6323 // the address. 6324 SDValue SymAddr = DAG.getTargetExternalSymbol("_TLS_MODULE_BASE_", PtrVT, 6325 AArch64II::MO_TLS); 6326 6327 // Now we can calculate the offset from TPIDR_EL0 to this module's 6328 // thread-local area. 6329 TPOff = LowerELFTLSDescCallSeq(SymAddr, DL, DAG); 6330 6331 // Now use :dtprel_whatever: operations to calculate this variable's offset 6332 // in its thread-storage area. 6333 SDValue HiVar = DAG.getTargetGlobalAddress( 6334 GV, DL, MVT::i64, 0, AArch64II::MO_TLS | AArch64II::MO_HI12); 6335 SDValue LoVar = DAG.getTargetGlobalAddress( 6336 GV, DL, MVT::i64, 0, 6337 AArch64II::MO_TLS | AArch64II::MO_PAGEOFF | AArch64II::MO_NC); 6338 6339 TPOff = SDValue(DAG.getMachineNode(AArch64::ADDXri, DL, PtrVT, TPOff, HiVar, 6340 DAG.getTargetConstant(0, DL, MVT::i32)), 6341 0); 6342 TPOff = SDValue(DAG.getMachineNode(AArch64::ADDXri, DL, PtrVT, TPOff, LoVar, 6343 DAG.getTargetConstant(0, DL, MVT::i32)), 6344 0); 6345 } else if (Model == TLSModel::GeneralDynamic) { 6346 // The call needs a relocation too for linker relaxation. It doesn't make 6347 // sense to call it MO_PAGE or MO_PAGEOFF though so we need another copy of 6348 // the address. 6349 SDValue SymAddr = 6350 DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, AArch64II::MO_TLS); 6351 6352 // Finally we can make a call to calculate the offset from tpidr_el0. 6353 TPOff = LowerELFTLSDescCallSeq(SymAddr, DL, DAG); 6354 } else 6355 llvm_unreachable("Unsupported ELF TLS access model"); 6356 6357 return DAG.getNode(ISD::ADD, DL, PtrVT, ThreadBase, TPOff); 6358 } 6359 6360 SDValue 6361 AArch64TargetLowering::LowerWindowsGlobalTLSAddress(SDValue Op, 6362 SelectionDAG &DAG) const { 6363 assert(Subtarget->isTargetWindows() && "Windows specific TLS lowering"); 6364 6365 SDValue Chain = DAG.getEntryNode(); 6366 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 6367 SDLoc DL(Op); 6368 6369 SDValue TEB = DAG.getRegister(AArch64::X18, MVT::i64); 6370 6371 // Load the ThreadLocalStoragePointer from the TEB 6372 // A pointer to the TLS array is located at offset 0x58 from the TEB. 6373 SDValue TLSArray = 6374 DAG.getNode(ISD::ADD, DL, PtrVT, TEB, DAG.getIntPtrConstant(0x58, DL)); 6375 TLSArray = DAG.getLoad(PtrVT, DL, Chain, TLSArray, MachinePointerInfo()); 6376 Chain = TLSArray.getValue(1); 6377 6378 // Load the TLS index from the C runtime; 6379 // This does the same as getAddr(), but without having a GlobalAddressSDNode. 6380 // This also does the same as LOADgot, but using a generic i32 load, 6381 // while LOADgot only loads i64. 6382 SDValue TLSIndexHi = 6383 DAG.getTargetExternalSymbol("_tls_index", PtrVT, AArch64II::MO_PAGE); 6384 SDValue TLSIndexLo = DAG.getTargetExternalSymbol( 6385 "_tls_index", PtrVT, AArch64II::MO_PAGEOFF | AArch64II::MO_NC); 6386 SDValue ADRP = DAG.getNode(AArch64ISD::ADRP, DL, PtrVT, TLSIndexHi); 6387 SDValue TLSIndex = 6388 DAG.getNode(AArch64ISD::ADDlow, DL, PtrVT, ADRP, TLSIndexLo); 6389 TLSIndex = DAG.getLoad(MVT::i32, DL, Chain, TLSIndex, MachinePointerInfo()); 6390 Chain = TLSIndex.getValue(1); 6391 6392 // The pointer to the thread's TLS data area is at the TLS Index scaled by 8 6393 // offset into the TLSArray. 6394 TLSIndex = DAG.getNode(ISD::ZERO_EXTEND, DL, PtrVT, TLSIndex); 6395 SDValue Slot = DAG.getNode(ISD::SHL, DL, PtrVT, TLSIndex, 6396 DAG.getConstant(3, DL, PtrVT)); 6397 SDValue TLS = DAG.getLoad(PtrVT, DL, Chain, 6398 DAG.getNode(ISD::ADD, DL, PtrVT, TLSArray, Slot), 6399 MachinePointerInfo()); 6400 Chain = TLS.getValue(1); 6401 6402 const GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op); 6403 const GlobalValue *GV = GA->getGlobal(); 6404 SDValue TGAHi = DAG.getTargetGlobalAddress( 6405 GV, DL, PtrVT, 0, AArch64II::MO_TLS | AArch64II::MO_HI12); 6406 SDValue TGALo = DAG.getTargetGlobalAddress( 6407 GV, DL, PtrVT, 0, 6408 AArch64II::MO_TLS | AArch64II::MO_PAGEOFF | AArch64II::MO_NC); 6409 6410 // Add the offset from the start of the .tls section (section base). 6411 SDValue Addr = 6412 SDValue(DAG.getMachineNode(AArch64::ADDXri, DL, PtrVT, TLS, TGAHi, 6413 DAG.getTargetConstant(0, DL, MVT::i32)), 6414 0); 6415 Addr = DAG.getNode(AArch64ISD::ADDlow, DL, PtrVT, Addr, TGALo); 6416 return Addr; 6417 } 6418 6419 SDValue AArch64TargetLowering::LowerGlobalTLSAddress(SDValue Op, 6420 SelectionDAG &DAG) const { 6421 const GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op); 6422 if (DAG.getTarget().useEmulatedTLS()) 6423 return LowerToTLSEmulatedModel(GA, DAG); 6424 6425 if (Subtarget->isTargetDarwin()) 6426 return LowerDarwinGlobalTLSAddress(Op, DAG); 6427 if (Subtarget->isTargetELF()) 6428 return LowerELFGlobalTLSAddress(Op, DAG); 6429 if (Subtarget->isTargetWindows()) 6430 return LowerWindowsGlobalTLSAddress(Op, DAG); 6431 6432 llvm_unreachable("Unexpected platform trying to use TLS"); 6433 } 6434 6435 // Looks through \param Val to determine the bit that can be used to 6436 // check the sign of the value. It returns the unextended value and 6437 // the sign bit position. 6438 std::pair<SDValue, uint64_t> lookThroughSignExtension(SDValue Val) { 6439 if (Val.getOpcode() == ISD::SIGN_EXTEND_INREG) 6440 return {Val.getOperand(0), 6441 cast<VTSDNode>(Val.getOperand(1))->getVT().getFixedSizeInBits() - 6442 1}; 6443 6444 if (Val.getOpcode() == ISD::SIGN_EXTEND) 6445 return {Val.getOperand(0), 6446 Val.getOperand(0)->getValueType(0).getFixedSizeInBits() - 1}; 6447 6448 return {Val, Val.getValueSizeInBits() - 1}; 6449 } 6450 6451 SDValue AArch64TargetLowering::LowerBR_CC(SDValue Op, SelectionDAG &DAG) const { 6452 SDValue Chain = Op.getOperand(0); 6453 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(1))->get(); 6454 SDValue LHS = Op.getOperand(2); 6455 SDValue RHS = Op.getOperand(3); 6456 SDValue Dest = Op.getOperand(4); 6457 SDLoc dl(Op); 6458 6459 MachineFunction &MF = DAG.getMachineFunction(); 6460 // Speculation tracking/SLH assumes that optimized TB(N)Z/CB(N)Z instructions 6461 // will not be produced, as they are conditional branch instructions that do 6462 // not set flags. 6463 bool ProduceNonFlagSettingCondBr = 6464 !MF.getFunction().hasFnAttribute(Attribute::SpeculativeLoadHardening); 6465 6466 // Handle f128 first, since lowering it will result in comparing the return 6467 // value of a libcall against zero, which is just what the rest of LowerBR_CC 6468 // is expecting to deal with. 6469 if (LHS.getValueType() == MVT::f128) { 6470 softenSetCCOperands(DAG, MVT::f128, LHS, RHS, CC, dl, LHS, RHS); 6471 6472 // If softenSetCCOperands returned a scalar, we need to compare the result 6473 // against zero to select between true and false values. 6474 if (!RHS.getNode()) { 6475 RHS = DAG.getConstant(0, dl, LHS.getValueType()); 6476 CC = ISD::SETNE; 6477 } 6478 } 6479 6480 // Optimize {s|u}{add|sub|mul}.with.overflow feeding into a branch 6481 // instruction. 6482 if (ISD::isOverflowIntrOpRes(LHS) && isOneConstant(RHS) && 6483 (CC == ISD::SETEQ || CC == ISD::SETNE)) { 6484 // Only lower legal XALUO ops. 6485 if (!DAG.getTargetLoweringInfo().isTypeLegal(LHS->getValueType(0))) 6486 return SDValue(); 6487 6488 // The actual operation with overflow check. 6489 AArch64CC::CondCode OFCC; 6490 SDValue Value, Overflow; 6491 std::tie(Value, Overflow) = getAArch64XALUOOp(OFCC, LHS.getValue(0), DAG); 6492 6493 if (CC == ISD::SETNE) 6494 OFCC = getInvertedCondCode(OFCC); 6495 SDValue CCVal = DAG.getConstant(OFCC, dl, MVT::i32); 6496 6497 return DAG.getNode(AArch64ISD::BRCOND, dl, MVT::Other, Chain, Dest, CCVal, 6498 Overflow); 6499 } 6500 6501 if (LHS.getValueType().isInteger()) { 6502 assert((LHS.getValueType() == RHS.getValueType()) && 6503 (LHS.getValueType() == MVT::i32 || LHS.getValueType() == MVT::i64)); 6504 6505 // If the RHS of the comparison is zero, we can potentially fold this 6506 // to a specialized branch. 6507 const ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS); 6508 if (RHSC && RHSC->getZExtValue() == 0 && ProduceNonFlagSettingCondBr) { 6509 if (CC == ISD::SETEQ) { 6510 // See if we can use a TBZ to fold in an AND as well. 6511 // TBZ has a smaller branch displacement than CBZ. If the offset is 6512 // out of bounds, a late MI-layer pass rewrites branches. 6513 // 403.gcc is an example that hits this case. 6514 if (LHS.getOpcode() == ISD::AND && 6515 isa<ConstantSDNode>(LHS.getOperand(1)) && 6516 isPowerOf2_64(LHS.getConstantOperandVal(1))) { 6517 SDValue Test = LHS.getOperand(0); 6518 uint64_t Mask = LHS.getConstantOperandVal(1); 6519 return DAG.getNode(AArch64ISD::TBZ, dl, MVT::Other, Chain, Test, 6520 DAG.getConstant(Log2_64(Mask), dl, MVT::i64), 6521 Dest); 6522 } 6523 6524 return DAG.getNode(AArch64ISD::CBZ, dl, MVT::Other, Chain, LHS, Dest); 6525 } else if (CC == ISD::SETNE) { 6526 // See if we can use a TBZ to fold in an AND as well. 6527 // TBZ has a smaller branch displacement than CBZ. If the offset is 6528 // out of bounds, a late MI-layer pass rewrites branches. 6529 // 403.gcc is an example that hits this case. 6530 if (LHS.getOpcode() == ISD::AND && 6531 isa<ConstantSDNode>(LHS.getOperand(1)) && 6532 isPowerOf2_64(LHS.getConstantOperandVal(1))) { 6533 SDValue Test = LHS.getOperand(0); 6534 uint64_t Mask = LHS.getConstantOperandVal(1); 6535 return DAG.getNode(AArch64ISD::TBNZ, dl, MVT::Other, Chain, Test, 6536 DAG.getConstant(Log2_64(Mask), dl, MVT::i64), 6537 Dest); 6538 } 6539 6540 return DAG.getNode(AArch64ISD::CBNZ, dl, MVT::Other, Chain, LHS, Dest); 6541 } else if (CC == ISD::SETLT && LHS.getOpcode() != ISD::AND) { 6542 // Don't combine AND since emitComparison converts the AND to an ANDS 6543 // (a.k.a. TST) and the test in the test bit and branch instruction 6544 // becomes redundant. This would also increase register pressure. 6545 uint64_t SignBitPos; 6546 std::tie(LHS, SignBitPos) = lookThroughSignExtension(LHS); 6547 return DAG.getNode(AArch64ISD::TBNZ, dl, MVT::Other, Chain, LHS, 6548 DAG.getConstant(SignBitPos, dl, MVT::i64), Dest); 6549 } 6550 } 6551 if (RHSC && RHSC->getSExtValue() == -1 && CC == ISD::SETGT && 6552 LHS.getOpcode() != ISD::AND && ProduceNonFlagSettingCondBr) { 6553 // Don't combine AND since emitComparison converts the AND to an ANDS 6554 // (a.k.a. TST) and the test in the test bit and branch instruction 6555 // becomes redundant. This would also increase register pressure. 6556 uint64_t SignBitPos; 6557 std::tie(LHS, SignBitPos) = lookThroughSignExtension(LHS); 6558 return DAG.getNode(AArch64ISD::TBZ, dl, MVT::Other, Chain, LHS, 6559 DAG.getConstant(SignBitPos, dl, MVT::i64), Dest); 6560 } 6561 6562 SDValue CCVal; 6563 SDValue Cmp = getAArch64Cmp(LHS, RHS, CC, CCVal, DAG, dl); 6564 return DAG.getNode(AArch64ISD::BRCOND, dl, MVT::Other, Chain, Dest, CCVal, 6565 Cmp); 6566 } 6567 6568 assert(LHS.getValueType() == MVT::f16 || LHS.getValueType() == MVT::bf16 || 6569 LHS.getValueType() == MVT::f32 || LHS.getValueType() == MVT::f64); 6570 6571 // Unfortunately, the mapping of LLVM FP CC's onto AArch64 CC's isn't totally 6572 // clean. Some of them require two branches to implement. 6573 SDValue Cmp = emitComparison(LHS, RHS, CC, dl, DAG); 6574 AArch64CC::CondCode CC1, CC2; 6575 changeFPCCToAArch64CC(CC, CC1, CC2); 6576 SDValue CC1Val = DAG.getConstant(CC1, dl, MVT::i32); 6577 SDValue BR1 = 6578 DAG.getNode(AArch64ISD::BRCOND, dl, MVT::Other, Chain, Dest, CC1Val, Cmp); 6579 if (CC2 != AArch64CC::AL) { 6580 SDValue CC2Val = DAG.getConstant(CC2, dl, MVT::i32); 6581 return DAG.getNode(AArch64ISD::BRCOND, dl, MVT::Other, BR1, Dest, CC2Val, 6582 Cmp); 6583 } 6584 6585 return BR1; 6586 } 6587 6588 SDValue AArch64TargetLowering::LowerFCOPYSIGN(SDValue Op, 6589 SelectionDAG &DAG) const { 6590 EVT VT = Op.getValueType(); 6591 SDLoc DL(Op); 6592 6593 SDValue In1 = Op.getOperand(0); 6594 SDValue In2 = Op.getOperand(1); 6595 EVT SrcVT = In2.getValueType(); 6596 6597 if (SrcVT.bitsLT(VT)) 6598 In2 = DAG.getNode(ISD::FP_EXTEND, DL, VT, In2); 6599 else if (SrcVT.bitsGT(VT)) 6600 In2 = DAG.getNode(ISD::FP_ROUND, DL, VT, In2, DAG.getIntPtrConstant(0, DL)); 6601 6602 EVT VecVT; 6603 uint64_t EltMask; 6604 SDValue VecVal1, VecVal2; 6605 6606 auto setVecVal = [&] (int Idx) { 6607 if (!VT.isVector()) { 6608 VecVal1 = DAG.getTargetInsertSubreg(Idx, DL, VecVT, 6609 DAG.getUNDEF(VecVT), In1); 6610 VecVal2 = DAG.getTargetInsertSubreg(Idx, DL, VecVT, 6611 DAG.getUNDEF(VecVT), In2); 6612 } else { 6613 VecVal1 = DAG.getNode(ISD::BITCAST, DL, VecVT, In1); 6614 VecVal2 = DAG.getNode(ISD::BITCAST, DL, VecVT, In2); 6615 } 6616 }; 6617 6618 if (VT == MVT::f32 || VT == MVT::v2f32 || VT == MVT::v4f32) { 6619 VecVT = (VT == MVT::v2f32 ? MVT::v2i32 : MVT::v4i32); 6620 EltMask = 0x80000000ULL; 6621 setVecVal(AArch64::ssub); 6622 } else if (VT == MVT::f64 || VT == MVT::v2f64) { 6623 VecVT = MVT::v2i64; 6624 6625 // We want to materialize a mask with the high bit set, but the AdvSIMD 6626 // immediate moves cannot materialize that in a single instruction for 6627 // 64-bit elements. Instead, materialize zero and then negate it. 6628 EltMask = 0; 6629 6630 setVecVal(AArch64::dsub); 6631 } else if (VT == MVT::f16 || VT == MVT::v4f16 || VT == MVT::v8f16) { 6632 VecVT = (VT == MVT::v4f16 ? MVT::v4i16 : MVT::v8i16); 6633 EltMask = 0x8000ULL; 6634 setVecVal(AArch64::hsub); 6635 } else { 6636 llvm_unreachable("Invalid type for copysign!"); 6637 } 6638 6639 SDValue BuildVec = DAG.getConstant(EltMask, DL, VecVT); 6640 6641 // If we couldn't materialize the mask above, then the mask vector will be 6642 // the zero vector, and we need to negate it here. 6643 if (VT == MVT::f64 || VT == MVT::v2f64) { 6644 BuildVec = DAG.getNode(ISD::BITCAST, DL, MVT::v2f64, BuildVec); 6645 BuildVec = DAG.getNode(ISD::FNEG, DL, MVT::v2f64, BuildVec); 6646 BuildVec = DAG.getNode(ISD::BITCAST, DL, MVT::v2i64, BuildVec); 6647 } 6648 6649 SDValue Sel = 6650 DAG.getNode(AArch64ISD::BIT, DL, VecVT, VecVal1, VecVal2, BuildVec); 6651 6652 if (VT == MVT::f16) 6653 return DAG.getTargetExtractSubreg(AArch64::hsub, DL, VT, Sel); 6654 if (VT == MVT::f32) 6655 return DAG.getTargetExtractSubreg(AArch64::ssub, DL, VT, Sel); 6656 else if (VT == MVT::f64) 6657 return DAG.getTargetExtractSubreg(AArch64::dsub, DL, VT, Sel); 6658 else 6659 return DAG.getNode(ISD::BITCAST, DL, VT, Sel); 6660 } 6661 6662 SDValue AArch64TargetLowering::LowerCTPOP(SDValue Op, SelectionDAG &DAG) const { 6663 if (DAG.getMachineFunction().getFunction().hasFnAttribute( 6664 Attribute::NoImplicitFloat)) 6665 return SDValue(); 6666 6667 if (!Subtarget->hasNEON()) 6668 return SDValue(); 6669 6670 // While there is no integer popcount instruction, it can 6671 // be more efficiently lowered to the following sequence that uses 6672 // AdvSIMD registers/instructions as long as the copies to/from 6673 // the AdvSIMD registers are cheap. 6674 // FMOV D0, X0 // copy 64-bit int to vector, high bits zero'd 6675 // CNT V0.8B, V0.8B // 8xbyte pop-counts 6676 // ADDV B0, V0.8B // sum 8xbyte pop-counts 6677 // UMOV X0, V0.B[0] // copy byte result back to integer reg 6678 SDValue Val = Op.getOperand(0); 6679 SDLoc DL(Op); 6680 EVT VT = Op.getValueType(); 6681 6682 if (VT == MVT::i32 || VT == MVT::i64) { 6683 if (VT == MVT::i32) 6684 Val = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i64, Val); 6685 Val = DAG.getNode(ISD::BITCAST, DL, MVT::v8i8, Val); 6686 6687 SDValue CtPop = DAG.getNode(ISD::CTPOP, DL, MVT::v8i8, Val); 6688 SDValue UaddLV = DAG.getNode( 6689 ISD::INTRINSIC_WO_CHAIN, DL, MVT::i32, 6690 DAG.getConstant(Intrinsic::aarch64_neon_uaddlv, DL, MVT::i32), CtPop); 6691 6692 if (VT == MVT::i64) 6693 UaddLV = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i64, UaddLV); 6694 return UaddLV; 6695 } else if (VT == MVT::i128) { 6696 Val = DAG.getNode(ISD::BITCAST, DL, MVT::v16i8, Val); 6697 6698 SDValue CtPop = DAG.getNode(ISD::CTPOP, DL, MVT::v16i8, Val); 6699 SDValue UaddLV = DAG.getNode( 6700 ISD::INTRINSIC_WO_CHAIN, DL, MVT::i32, 6701 DAG.getConstant(Intrinsic::aarch64_neon_uaddlv, DL, MVT::i32), CtPop); 6702 6703 return DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i128, UaddLV); 6704 } 6705 6706 if (VT.isScalableVector() || useSVEForFixedLengthVectorVT(VT)) 6707 return LowerToPredicatedOp(Op, DAG, AArch64ISD::CTPOP_MERGE_PASSTHRU); 6708 6709 assert((VT == MVT::v1i64 || VT == MVT::v2i64 || VT == MVT::v2i32 || 6710 VT == MVT::v4i32 || VT == MVT::v4i16 || VT == MVT::v8i16) && 6711 "Unexpected type for custom ctpop lowering"); 6712 6713 EVT VT8Bit = VT.is64BitVector() ? MVT::v8i8 : MVT::v16i8; 6714 Val = DAG.getBitcast(VT8Bit, Val); 6715 Val = DAG.getNode(ISD::CTPOP, DL, VT8Bit, Val); 6716 6717 // Widen v8i8/v16i8 CTPOP result to VT by repeatedly widening pairwise adds. 6718 unsigned EltSize = 8; 6719 unsigned NumElts = VT.is64BitVector() ? 8 : 16; 6720 while (EltSize != VT.getScalarSizeInBits()) { 6721 EltSize *= 2; 6722 NumElts /= 2; 6723 MVT WidenVT = MVT::getVectorVT(MVT::getIntegerVT(EltSize), NumElts); 6724 Val = DAG.getNode( 6725 ISD::INTRINSIC_WO_CHAIN, DL, WidenVT, 6726 DAG.getConstant(Intrinsic::aarch64_neon_uaddlp, DL, MVT::i32), Val); 6727 } 6728 6729 return Val; 6730 } 6731 6732 SDValue AArch64TargetLowering::LowerCTTZ(SDValue Op, SelectionDAG &DAG) const { 6733 EVT VT = Op.getValueType(); 6734 assert(VT.isScalableVector() || 6735 useSVEForFixedLengthVectorVT(VT, /*OverrideNEON=*/true)); 6736 6737 SDLoc DL(Op); 6738 SDValue RBIT = DAG.getNode(ISD::BITREVERSE, DL, VT, Op.getOperand(0)); 6739 return DAG.getNode(ISD::CTLZ, DL, VT, RBIT); 6740 } 6741 6742 SDValue AArch64TargetLowering::LowerSETCC(SDValue Op, SelectionDAG &DAG) const { 6743 6744 if (Op.getValueType().isVector()) 6745 return LowerVSETCC(Op, DAG); 6746 6747 bool IsStrict = Op->isStrictFPOpcode(); 6748 bool IsSignaling = Op.getOpcode() == ISD::STRICT_FSETCCS; 6749 unsigned OpNo = IsStrict ? 1 : 0; 6750 SDValue Chain; 6751 if (IsStrict) 6752 Chain = Op.getOperand(0); 6753 SDValue LHS = Op.getOperand(OpNo + 0); 6754 SDValue RHS = Op.getOperand(OpNo + 1); 6755 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(OpNo + 2))->get(); 6756 SDLoc dl(Op); 6757 6758 // We chose ZeroOrOneBooleanContents, so use zero and one. 6759 EVT VT = Op.getValueType(); 6760 SDValue TVal = DAG.getConstant(1, dl, VT); 6761 SDValue FVal = DAG.getConstant(0, dl, VT); 6762 6763 // Handle f128 first, since one possible outcome is a normal integer 6764 // comparison which gets picked up by the next if statement. 6765 if (LHS.getValueType() == MVT::f128) { 6766 softenSetCCOperands(DAG, MVT::f128, LHS, RHS, CC, dl, LHS, RHS, Chain, 6767 IsSignaling); 6768 6769 // If softenSetCCOperands returned a scalar, use it. 6770 if (!RHS.getNode()) { 6771 assert(LHS.getValueType() == Op.getValueType() && 6772 "Unexpected setcc expansion!"); 6773 return IsStrict ? DAG.getMergeValues({LHS, Chain}, dl) : LHS; 6774 } 6775 } 6776 6777 if (LHS.getValueType().isInteger()) { 6778 SDValue CCVal; 6779 SDValue Cmp = getAArch64Cmp( 6780 LHS, RHS, ISD::getSetCCInverse(CC, LHS.getValueType()), CCVal, DAG, dl); 6781 6782 // Note that we inverted the condition above, so we reverse the order of 6783 // the true and false operands here. This will allow the setcc to be 6784 // matched to a single CSINC instruction. 6785 SDValue Res = DAG.getNode(AArch64ISD::CSEL, dl, VT, FVal, TVal, CCVal, Cmp); 6786 return IsStrict ? DAG.getMergeValues({Res, Chain}, dl) : Res; 6787 } 6788 6789 // Now we know we're dealing with FP values. 6790 assert(LHS.getValueType() == MVT::f16 || LHS.getValueType() == MVT::f32 || 6791 LHS.getValueType() == MVT::f64); 6792 6793 // If that fails, we'll need to perform an FCMP + CSEL sequence. Go ahead 6794 // and do the comparison. 6795 SDValue Cmp; 6796 if (IsStrict) 6797 Cmp = emitStrictFPComparison(LHS, RHS, dl, DAG, Chain, IsSignaling); 6798 else 6799 Cmp = emitComparison(LHS, RHS, CC, dl, DAG); 6800 6801 AArch64CC::CondCode CC1, CC2; 6802 changeFPCCToAArch64CC(CC, CC1, CC2); 6803 SDValue Res; 6804 if (CC2 == AArch64CC::AL) { 6805 changeFPCCToAArch64CC(ISD::getSetCCInverse(CC, LHS.getValueType()), CC1, 6806 CC2); 6807 SDValue CC1Val = DAG.getConstant(CC1, dl, MVT::i32); 6808 6809 // Note that we inverted the condition above, so we reverse the order of 6810 // the true and false operands here. This will allow the setcc to be 6811 // matched to a single CSINC instruction. 6812 Res = DAG.getNode(AArch64ISD::CSEL, dl, VT, FVal, TVal, CC1Val, Cmp); 6813 } else { 6814 // Unfortunately, the mapping of LLVM FP CC's onto AArch64 CC's isn't 6815 // totally clean. Some of them require two CSELs to implement. As is in 6816 // this case, we emit the first CSEL and then emit a second using the output 6817 // of the first as the RHS. We're effectively OR'ing the two CC's together. 6818 6819 // FIXME: It would be nice if we could match the two CSELs to two CSINCs. 6820 SDValue CC1Val = DAG.getConstant(CC1, dl, MVT::i32); 6821 SDValue CS1 = 6822 DAG.getNode(AArch64ISD::CSEL, dl, VT, TVal, FVal, CC1Val, Cmp); 6823 6824 SDValue CC2Val = DAG.getConstant(CC2, dl, MVT::i32); 6825 Res = DAG.getNode(AArch64ISD::CSEL, dl, VT, TVal, CS1, CC2Val, Cmp); 6826 } 6827 return IsStrict ? DAG.getMergeValues({Res, Cmp.getValue(1)}, dl) : Res; 6828 } 6829 6830 SDValue AArch64TargetLowering::LowerSELECT_CC(ISD::CondCode CC, SDValue LHS, 6831 SDValue RHS, SDValue TVal, 6832 SDValue FVal, const SDLoc &dl, 6833 SelectionDAG &DAG) const { 6834 // Handle f128 first, because it will result in a comparison of some RTLIB 6835 // call result against zero. 6836 if (LHS.getValueType() == MVT::f128) { 6837 softenSetCCOperands(DAG, MVT::f128, LHS, RHS, CC, dl, LHS, RHS); 6838 6839 // If softenSetCCOperands returned a scalar, we need to compare the result 6840 // against zero to select between true and false values. 6841 if (!RHS.getNode()) { 6842 RHS = DAG.getConstant(0, dl, LHS.getValueType()); 6843 CC = ISD::SETNE; 6844 } 6845 } 6846 6847 // Also handle f16, for which we need to do a f32 comparison. 6848 if (LHS.getValueType() == MVT::f16 && !Subtarget->hasFullFP16()) { 6849 LHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f32, LHS); 6850 RHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f32, RHS); 6851 } 6852 6853 // Next, handle integers. 6854 if (LHS.getValueType().isInteger()) { 6855 assert((LHS.getValueType() == RHS.getValueType()) && 6856 (LHS.getValueType() == MVT::i32 || LHS.getValueType() == MVT::i64)); 6857 6858 ConstantSDNode *CFVal = dyn_cast<ConstantSDNode>(FVal); 6859 ConstantSDNode *CTVal = dyn_cast<ConstantSDNode>(TVal); 6860 ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS); 6861 // Check for sign pattern (SELECT_CC setgt, iN lhs, -1, 1, -1) and transform 6862 // into (OR (ASR lhs, N-1), 1), which requires less instructions for the 6863 // supported types. 6864 if (CC == ISD::SETGT && RHSC && RHSC->isAllOnesValue() && CTVal && CFVal && 6865 CTVal->isOne() && CFVal->isAllOnesValue() && 6866 LHS.getValueType() == TVal.getValueType()) { 6867 EVT VT = LHS.getValueType(); 6868 SDValue Shift = 6869 DAG.getNode(ISD::SRA, dl, VT, LHS, 6870 DAG.getConstant(VT.getSizeInBits() - 1, dl, VT)); 6871 return DAG.getNode(ISD::OR, dl, VT, Shift, DAG.getConstant(1, dl, VT)); 6872 } 6873 6874 unsigned Opcode = AArch64ISD::CSEL; 6875 6876 // If both the TVal and the FVal are constants, see if we can swap them in 6877 // order to for a CSINV or CSINC out of them. 6878 if (CTVal && CFVal && CTVal->isAllOnesValue() && CFVal->isNullValue()) { 6879 std::swap(TVal, FVal); 6880 std::swap(CTVal, CFVal); 6881 CC = ISD::getSetCCInverse(CC, LHS.getValueType()); 6882 } else if (CTVal && CFVal && CTVal->isOne() && CFVal->isNullValue()) { 6883 std::swap(TVal, FVal); 6884 std::swap(CTVal, CFVal); 6885 CC = ISD::getSetCCInverse(CC, LHS.getValueType()); 6886 } else if (TVal.getOpcode() == ISD::XOR) { 6887 // If TVal is a NOT we want to swap TVal and FVal so that we can match 6888 // with a CSINV rather than a CSEL. 6889 if (isAllOnesConstant(TVal.getOperand(1))) { 6890 std::swap(TVal, FVal); 6891 std::swap(CTVal, CFVal); 6892 CC = ISD::getSetCCInverse(CC, LHS.getValueType()); 6893 } 6894 } else if (TVal.getOpcode() == ISD::SUB) { 6895 // If TVal is a negation (SUB from 0) we want to swap TVal and FVal so 6896 // that we can match with a CSNEG rather than a CSEL. 6897 if (isNullConstant(TVal.getOperand(0))) { 6898 std::swap(TVal, FVal); 6899 std::swap(CTVal, CFVal); 6900 CC = ISD::getSetCCInverse(CC, LHS.getValueType()); 6901 } 6902 } else if (CTVal && CFVal) { 6903 const int64_t TrueVal = CTVal->getSExtValue(); 6904 const int64_t FalseVal = CFVal->getSExtValue(); 6905 bool Swap = false; 6906 6907 // If both TVal and FVal are constants, see if FVal is the 6908 // inverse/negation/increment of TVal and generate a CSINV/CSNEG/CSINC 6909 // instead of a CSEL in that case. 6910 if (TrueVal == ~FalseVal) { 6911 Opcode = AArch64ISD::CSINV; 6912 } else if (FalseVal > std::numeric_limits<int64_t>::min() && 6913 TrueVal == -FalseVal) { 6914 Opcode = AArch64ISD::CSNEG; 6915 } else if (TVal.getValueType() == MVT::i32) { 6916 // If our operands are only 32-bit wide, make sure we use 32-bit 6917 // arithmetic for the check whether we can use CSINC. This ensures that 6918 // the addition in the check will wrap around properly in case there is 6919 // an overflow (which would not be the case if we do the check with 6920 // 64-bit arithmetic). 6921 const uint32_t TrueVal32 = CTVal->getZExtValue(); 6922 const uint32_t FalseVal32 = CFVal->getZExtValue(); 6923 6924 if ((TrueVal32 == FalseVal32 + 1) || (TrueVal32 + 1 == FalseVal32)) { 6925 Opcode = AArch64ISD::CSINC; 6926 6927 if (TrueVal32 > FalseVal32) { 6928 Swap = true; 6929 } 6930 } 6931 // 64-bit check whether we can use CSINC. 6932 } else if ((TrueVal == FalseVal + 1) || (TrueVal + 1 == FalseVal)) { 6933 Opcode = AArch64ISD::CSINC; 6934 6935 if (TrueVal > FalseVal) { 6936 Swap = true; 6937 } 6938 } 6939 6940 // Swap TVal and FVal if necessary. 6941 if (Swap) { 6942 std::swap(TVal, FVal); 6943 std::swap(CTVal, CFVal); 6944 CC = ISD::getSetCCInverse(CC, LHS.getValueType()); 6945 } 6946 6947 if (Opcode != AArch64ISD::CSEL) { 6948 // Drop FVal since we can get its value by simply inverting/negating 6949 // TVal. 6950 FVal = TVal; 6951 } 6952 } 6953 6954 // Avoid materializing a constant when possible by reusing a known value in 6955 // a register. However, don't perform this optimization if the known value 6956 // is one, zero or negative one in the case of a CSEL. We can always 6957 // materialize these values using CSINC, CSEL and CSINV with wzr/xzr as the 6958 // FVal, respectively. 6959 ConstantSDNode *RHSVal = dyn_cast<ConstantSDNode>(RHS); 6960 if (Opcode == AArch64ISD::CSEL && RHSVal && !RHSVal->isOne() && 6961 !RHSVal->isNullValue() && !RHSVal->isAllOnesValue()) { 6962 AArch64CC::CondCode AArch64CC = changeIntCCToAArch64CC(CC); 6963 // Transform "a == C ? C : x" to "a == C ? a : x" and "a != C ? x : C" to 6964 // "a != C ? x : a" to avoid materializing C. 6965 if (CTVal && CTVal == RHSVal && AArch64CC == AArch64CC::EQ) 6966 TVal = LHS; 6967 else if (CFVal && CFVal == RHSVal && AArch64CC == AArch64CC::NE) 6968 FVal = LHS; 6969 } else if (Opcode == AArch64ISD::CSNEG && RHSVal && RHSVal->isOne()) { 6970 assert (CTVal && CFVal && "Expected constant operands for CSNEG."); 6971 // Use a CSINV to transform "a == C ? 1 : -1" to "a == C ? a : -1" to 6972 // avoid materializing C. 6973 AArch64CC::CondCode AArch64CC = changeIntCCToAArch64CC(CC); 6974 if (CTVal == RHSVal && AArch64CC == AArch64CC::EQ) { 6975 Opcode = AArch64ISD::CSINV; 6976 TVal = LHS; 6977 FVal = DAG.getConstant(0, dl, FVal.getValueType()); 6978 } 6979 } 6980 6981 SDValue CCVal; 6982 SDValue Cmp = getAArch64Cmp(LHS, RHS, CC, CCVal, DAG, dl); 6983 EVT VT = TVal.getValueType(); 6984 return DAG.getNode(Opcode, dl, VT, TVal, FVal, CCVal, Cmp); 6985 } 6986 6987 // Now we know we're dealing with FP values. 6988 assert(LHS.getValueType() == MVT::f16 || LHS.getValueType() == MVT::f32 || 6989 LHS.getValueType() == MVT::f64); 6990 assert(LHS.getValueType() == RHS.getValueType()); 6991 EVT VT = TVal.getValueType(); 6992 SDValue Cmp = emitComparison(LHS, RHS, CC, dl, DAG); 6993 6994 // Unfortunately, the mapping of LLVM FP CC's onto AArch64 CC's isn't totally 6995 // clean. Some of them require two CSELs to implement. 6996 AArch64CC::CondCode CC1, CC2; 6997 changeFPCCToAArch64CC(CC, CC1, CC2); 6998 6999 if (DAG.getTarget().Options.UnsafeFPMath) { 7000 // Transform "a == 0.0 ? 0.0 : x" to "a == 0.0 ? a : x" and 7001 // "a != 0.0 ? x : 0.0" to "a != 0.0 ? x : a" to avoid materializing 0.0. 7002 ConstantFPSDNode *RHSVal = dyn_cast<ConstantFPSDNode>(RHS); 7003 if (RHSVal && RHSVal->isZero()) { 7004 ConstantFPSDNode *CFVal = dyn_cast<ConstantFPSDNode>(FVal); 7005 ConstantFPSDNode *CTVal = dyn_cast<ConstantFPSDNode>(TVal); 7006 7007 if ((CC == ISD::SETEQ || CC == ISD::SETOEQ || CC == ISD::SETUEQ) && 7008 CTVal && CTVal->isZero() && TVal.getValueType() == LHS.getValueType()) 7009 TVal = LHS; 7010 else if ((CC == ISD::SETNE || CC == ISD::SETONE || CC == ISD::SETUNE) && 7011 CFVal && CFVal->isZero() && 7012 FVal.getValueType() == LHS.getValueType()) 7013 FVal = LHS; 7014 } 7015 } 7016 7017 // Emit first, and possibly only, CSEL. 7018 SDValue CC1Val = DAG.getConstant(CC1, dl, MVT::i32); 7019 SDValue CS1 = DAG.getNode(AArch64ISD::CSEL, dl, VT, TVal, FVal, CC1Val, Cmp); 7020 7021 // If we need a second CSEL, emit it, using the output of the first as the 7022 // RHS. We're effectively OR'ing the two CC's together. 7023 if (CC2 != AArch64CC::AL) { 7024 SDValue CC2Val = DAG.getConstant(CC2, dl, MVT::i32); 7025 return DAG.getNode(AArch64ISD::CSEL, dl, VT, TVal, CS1, CC2Val, Cmp); 7026 } 7027 7028 // Otherwise, return the output of the first CSEL. 7029 return CS1; 7030 } 7031 7032 SDValue AArch64TargetLowering::LowerSELECT_CC(SDValue Op, 7033 SelectionDAG &DAG) const { 7034 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(4))->get(); 7035 SDValue LHS = Op.getOperand(0); 7036 SDValue RHS = Op.getOperand(1); 7037 SDValue TVal = Op.getOperand(2); 7038 SDValue FVal = Op.getOperand(3); 7039 SDLoc DL(Op); 7040 return LowerSELECT_CC(CC, LHS, RHS, TVal, FVal, DL, DAG); 7041 } 7042 7043 SDValue AArch64TargetLowering::LowerSELECT(SDValue Op, 7044 SelectionDAG &DAG) const { 7045 SDValue CCVal = Op->getOperand(0); 7046 SDValue TVal = Op->getOperand(1); 7047 SDValue FVal = Op->getOperand(2); 7048 SDLoc DL(Op); 7049 7050 EVT Ty = Op.getValueType(); 7051 if (Ty.isScalableVector()) { 7052 SDValue TruncCC = DAG.getNode(ISD::TRUNCATE, DL, MVT::i1, CCVal); 7053 MVT PredVT = MVT::getVectorVT(MVT::i1, Ty.getVectorElementCount()); 7054 SDValue SplatPred = DAG.getNode(ISD::SPLAT_VECTOR, DL, PredVT, TruncCC); 7055 return DAG.getNode(ISD::VSELECT, DL, Ty, SplatPred, TVal, FVal); 7056 } 7057 7058 if (useSVEForFixedLengthVectorVT(Ty)) { 7059 // FIXME: Ideally this would be the same as above using i1 types, however 7060 // for the moment we can't deal with fixed i1 vector types properly, so 7061 // instead extend the predicate to a result type sized integer vector. 7062 MVT SplatValVT = MVT::getIntegerVT(Ty.getScalarSizeInBits()); 7063 MVT PredVT = MVT::getVectorVT(SplatValVT, Ty.getVectorElementCount()); 7064 SDValue SplatVal = DAG.getSExtOrTrunc(CCVal, DL, SplatValVT); 7065 SDValue SplatPred = DAG.getNode(ISD::SPLAT_VECTOR, DL, PredVT, SplatVal); 7066 return DAG.getNode(ISD::VSELECT, DL, Ty, SplatPred, TVal, FVal); 7067 } 7068 7069 // Optimize {s|u}{add|sub|mul}.with.overflow feeding into a select 7070 // instruction. 7071 if (ISD::isOverflowIntrOpRes(CCVal)) { 7072 // Only lower legal XALUO ops. 7073 if (!DAG.getTargetLoweringInfo().isTypeLegal(CCVal->getValueType(0))) 7074 return SDValue(); 7075 7076 AArch64CC::CondCode OFCC; 7077 SDValue Value, Overflow; 7078 std::tie(Value, Overflow) = getAArch64XALUOOp(OFCC, CCVal.getValue(0), DAG); 7079 SDValue CCVal = DAG.getConstant(OFCC, DL, MVT::i32); 7080 7081 return DAG.getNode(AArch64ISD::CSEL, DL, Op.getValueType(), TVal, FVal, 7082 CCVal, Overflow); 7083 } 7084 7085 // Lower it the same way as we would lower a SELECT_CC node. 7086 ISD::CondCode CC; 7087 SDValue LHS, RHS; 7088 if (CCVal.getOpcode() == ISD::SETCC) { 7089 LHS = CCVal.getOperand(0); 7090 RHS = CCVal.getOperand(1); 7091 CC = cast<CondCodeSDNode>(CCVal.getOperand(2))->get(); 7092 } else { 7093 LHS = CCVal; 7094 RHS = DAG.getConstant(0, DL, CCVal.getValueType()); 7095 CC = ISD::SETNE; 7096 } 7097 return LowerSELECT_CC(CC, LHS, RHS, TVal, FVal, DL, DAG); 7098 } 7099 7100 SDValue AArch64TargetLowering::LowerJumpTable(SDValue Op, 7101 SelectionDAG &DAG) const { 7102 // Jump table entries as PC relative offsets. No additional tweaking 7103 // is necessary here. Just get the address of the jump table. 7104 JumpTableSDNode *JT = cast<JumpTableSDNode>(Op); 7105 7106 if (getTargetMachine().getCodeModel() == CodeModel::Large && 7107 !Subtarget->isTargetMachO()) { 7108 return getAddrLarge(JT, DAG); 7109 } else if (getTargetMachine().getCodeModel() == CodeModel::Tiny) { 7110 return getAddrTiny(JT, DAG); 7111 } 7112 return getAddr(JT, DAG); 7113 } 7114 7115 SDValue AArch64TargetLowering::LowerBR_JT(SDValue Op, 7116 SelectionDAG &DAG) const { 7117 // Jump table entries as PC relative offsets. No additional tweaking 7118 // is necessary here. Just get the address of the jump table. 7119 SDLoc DL(Op); 7120 SDValue JT = Op.getOperand(1); 7121 SDValue Entry = Op.getOperand(2); 7122 int JTI = cast<JumpTableSDNode>(JT.getNode())->getIndex(); 7123 7124 auto *AFI = DAG.getMachineFunction().getInfo<AArch64FunctionInfo>(); 7125 AFI->setJumpTableEntryInfo(JTI, 4, nullptr); 7126 7127 SDNode *Dest = 7128 DAG.getMachineNode(AArch64::JumpTableDest32, DL, MVT::i64, MVT::i64, JT, 7129 Entry, DAG.getTargetJumpTable(JTI, MVT::i32)); 7130 return DAG.getNode(ISD::BRIND, DL, MVT::Other, Op.getOperand(0), 7131 SDValue(Dest, 0)); 7132 } 7133 7134 SDValue AArch64TargetLowering::LowerConstantPool(SDValue Op, 7135 SelectionDAG &DAG) const { 7136 ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op); 7137 7138 if (getTargetMachine().getCodeModel() == CodeModel::Large) { 7139 // Use the GOT for the large code model on iOS. 7140 if (Subtarget->isTargetMachO()) { 7141 return getGOT(CP, DAG); 7142 } 7143 return getAddrLarge(CP, DAG); 7144 } else if (getTargetMachine().getCodeModel() == CodeModel::Tiny) { 7145 return getAddrTiny(CP, DAG); 7146 } else { 7147 return getAddr(CP, DAG); 7148 } 7149 } 7150 7151 SDValue AArch64TargetLowering::LowerBlockAddress(SDValue Op, 7152 SelectionDAG &DAG) const { 7153 BlockAddressSDNode *BA = cast<BlockAddressSDNode>(Op); 7154 if (getTargetMachine().getCodeModel() == CodeModel::Large && 7155 !Subtarget->isTargetMachO()) { 7156 return getAddrLarge(BA, DAG); 7157 } else if (getTargetMachine().getCodeModel() == CodeModel::Tiny) { 7158 return getAddrTiny(BA, DAG); 7159 } 7160 return getAddr(BA, DAG); 7161 } 7162 7163 SDValue AArch64TargetLowering::LowerDarwin_VASTART(SDValue Op, 7164 SelectionDAG &DAG) const { 7165 AArch64FunctionInfo *FuncInfo = 7166 DAG.getMachineFunction().getInfo<AArch64FunctionInfo>(); 7167 7168 SDLoc DL(Op); 7169 SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsStackIndex(), 7170 getPointerTy(DAG.getDataLayout())); 7171 FR = DAG.getZExtOrTrunc(FR, DL, getPointerMemTy(DAG.getDataLayout())); 7172 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue(); 7173 return DAG.getStore(Op.getOperand(0), DL, FR, Op.getOperand(1), 7174 MachinePointerInfo(SV)); 7175 } 7176 7177 SDValue AArch64TargetLowering::LowerWin64_VASTART(SDValue Op, 7178 SelectionDAG &DAG) const { 7179 AArch64FunctionInfo *FuncInfo = 7180 DAG.getMachineFunction().getInfo<AArch64FunctionInfo>(); 7181 7182 SDLoc DL(Op); 7183 SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsGPRSize() > 0 7184 ? FuncInfo->getVarArgsGPRIndex() 7185 : FuncInfo->getVarArgsStackIndex(), 7186 getPointerTy(DAG.getDataLayout())); 7187 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue(); 7188 return DAG.getStore(Op.getOperand(0), DL, FR, Op.getOperand(1), 7189 MachinePointerInfo(SV)); 7190 } 7191 7192 SDValue AArch64TargetLowering::LowerAAPCS_VASTART(SDValue Op, 7193 SelectionDAG &DAG) const { 7194 // The layout of the va_list struct is specified in the AArch64 Procedure Call 7195 // Standard, section B.3. 7196 MachineFunction &MF = DAG.getMachineFunction(); 7197 AArch64FunctionInfo *FuncInfo = MF.getInfo<AArch64FunctionInfo>(); 7198 unsigned PtrSize = Subtarget->isTargetILP32() ? 4 : 8; 7199 auto PtrMemVT = getPointerMemTy(DAG.getDataLayout()); 7200 auto PtrVT = getPointerTy(DAG.getDataLayout()); 7201 SDLoc DL(Op); 7202 7203 SDValue Chain = Op.getOperand(0); 7204 SDValue VAList = Op.getOperand(1); 7205 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue(); 7206 SmallVector<SDValue, 4> MemOps; 7207 7208 // void *__stack at offset 0 7209 unsigned Offset = 0; 7210 SDValue Stack = DAG.getFrameIndex(FuncInfo->getVarArgsStackIndex(), PtrVT); 7211 Stack = DAG.getZExtOrTrunc(Stack, DL, PtrMemVT); 7212 MemOps.push_back(DAG.getStore(Chain, DL, Stack, VAList, 7213 MachinePointerInfo(SV), Align(PtrSize))); 7214 7215 // void *__gr_top at offset 8 (4 on ILP32) 7216 Offset += PtrSize; 7217 int GPRSize = FuncInfo->getVarArgsGPRSize(); 7218 if (GPRSize > 0) { 7219 SDValue GRTop, GRTopAddr; 7220 7221 GRTopAddr = DAG.getNode(ISD::ADD, DL, PtrVT, VAList, 7222 DAG.getConstant(Offset, DL, PtrVT)); 7223 7224 GRTop = DAG.getFrameIndex(FuncInfo->getVarArgsGPRIndex(), PtrVT); 7225 GRTop = DAG.getNode(ISD::ADD, DL, PtrVT, GRTop, 7226 DAG.getConstant(GPRSize, DL, PtrVT)); 7227 GRTop = DAG.getZExtOrTrunc(GRTop, DL, PtrMemVT); 7228 7229 MemOps.push_back(DAG.getStore(Chain, DL, GRTop, GRTopAddr, 7230 MachinePointerInfo(SV, Offset), 7231 Align(PtrSize))); 7232 } 7233 7234 // void *__vr_top at offset 16 (8 on ILP32) 7235 Offset += PtrSize; 7236 int FPRSize = FuncInfo->getVarArgsFPRSize(); 7237 if (FPRSize > 0) { 7238 SDValue VRTop, VRTopAddr; 7239 VRTopAddr = DAG.getNode(ISD::ADD, DL, PtrVT, VAList, 7240 DAG.getConstant(Offset, DL, PtrVT)); 7241 7242 VRTop = DAG.getFrameIndex(FuncInfo->getVarArgsFPRIndex(), PtrVT); 7243 VRTop = DAG.getNode(ISD::ADD, DL, PtrVT, VRTop, 7244 DAG.getConstant(FPRSize, DL, PtrVT)); 7245 VRTop = DAG.getZExtOrTrunc(VRTop, DL, PtrMemVT); 7246 7247 MemOps.push_back(DAG.getStore(Chain, DL, VRTop, VRTopAddr, 7248 MachinePointerInfo(SV, Offset), 7249 Align(PtrSize))); 7250 } 7251 7252 // int __gr_offs at offset 24 (12 on ILP32) 7253 Offset += PtrSize; 7254 SDValue GROffsAddr = DAG.getNode(ISD::ADD, DL, PtrVT, VAList, 7255 DAG.getConstant(Offset, DL, PtrVT)); 7256 MemOps.push_back( 7257 DAG.getStore(Chain, DL, DAG.getConstant(-GPRSize, DL, MVT::i32), 7258 GROffsAddr, MachinePointerInfo(SV, Offset), Align(4))); 7259 7260 // int __vr_offs at offset 28 (16 on ILP32) 7261 Offset += 4; 7262 SDValue VROffsAddr = DAG.getNode(ISD::ADD, DL, PtrVT, VAList, 7263 DAG.getConstant(Offset, DL, PtrVT)); 7264 MemOps.push_back( 7265 DAG.getStore(Chain, DL, DAG.getConstant(-FPRSize, DL, MVT::i32), 7266 VROffsAddr, MachinePointerInfo(SV, Offset), Align(4))); 7267 7268 return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, MemOps); 7269 } 7270 7271 SDValue AArch64TargetLowering::LowerVASTART(SDValue Op, 7272 SelectionDAG &DAG) const { 7273 MachineFunction &MF = DAG.getMachineFunction(); 7274 7275 if (Subtarget->isCallingConvWin64(MF.getFunction().getCallingConv())) 7276 return LowerWin64_VASTART(Op, DAG); 7277 else if (Subtarget->isTargetDarwin()) 7278 return LowerDarwin_VASTART(Op, DAG); 7279 else 7280 return LowerAAPCS_VASTART(Op, DAG); 7281 } 7282 7283 SDValue AArch64TargetLowering::LowerVACOPY(SDValue Op, 7284 SelectionDAG &DAG) const { 7285 // AAPCS has three pointers and two ints (= 32 bytes), Darwin has single 7286 // pointer. 7287 SDLoc DL(Op); 7288 unsigned PtrSize = Subtarget->isTargetILP32() ? 4 : 8; 7289 unsigned VaListSize = 7290 (Subtarget->isTargetDarwin() || Subtarget->isTargetWindows()) 7291 ? PtrSize 7292 : Subtarget->isTargetILP32() ? 20 : 32; 7293 const Value *DestSV = cast<SrcValueSDNode>(Op.getOperand(3))->getValue(); 7294 const Value *SrcSV = cast<SrcValueSDNode>(Op.getOperand(4))->getValue(); 7295 7296 return DAG.getMemcpy(Op.getOperand(0), DL, Op.getOperand(1), Op.getOperand(2), 7297 DAG.getConstant(VaListSize, DL, MVT::i32), 7298 Align(PtrSize), false, false, false, 7299 MachinePointerInfo(DestSV), MachinePointerInfo(SrcSV)); 7300 } 7301 7302 SDValue AArch64TargetLowering::LowerVAARG(SDValue Op, SelectionDAG &DAG) const { 7303 assert(Subtarget->isTargetDarwin() && 7304 "automatic va_arg instruction only works on Darwin"); 7305 7306 const Value *V = cast<SrcValueSDNode>(Op.getOperand(2))->getValue(); 7307 EVT VT = Op.getValueType(); 7308 SDLoc DL(Op); 7309 SDValue Chain = Op.getOperand(0); 7310 SDValue Addr = Op.getOperand(1); 7311 MaybeAlign Align(Op.getConstantOperandVal(3)); 7312 unsigned MinSlotSize = Subtarget->isTargetILP32() ? 4 : 8; 7313 auto PtrVT = getPointerTy(DAG.getDataLayout()); 7314 auto PtrMemVT = getPointerMemTy(DAG.getDataLayout()); 7315 SDValue VAList = 7316 DAG.getLoad(PtrMemVT, DL, Chain, Addr, MachinePointerInfo(V)); 7317 Chain = VAList.getValue(1); 7318 VAList = DAG.getZExtOrTrunc(VAList, DL, PtrVT); 7319 7320 if (VT.isScalableVector()) 7321 report_fatal_error("Passing SVE types to variadic functions is " 7322 "currently not supported"); 7323 7324 if (Align && *Align > MinSlotSize) { 7325 VAList = DAG.getNode(ISD::ADD, DL, PtrVT, VAList, 7326 DAG.getConstant(Align->value() - 1, DL, PtrVT)); 7327 VAList = DAG.getNode(ISD::AND, DL, PtrVT, VAList, 7328 DAG.getConstant(-(int64_t)Align->value(), DL, PtrVT)); 7329 } 7330 7331 Type *ArgTy = VT.getTypeForEVT(*DAG.getContext()); 7332 unsigned ArgSize = DAG.getDataLayout().getTypeAllocSize(ArgTy); 7333 7334 // Scalar integer and FP values smaller than 64 bits are implicitly extended 7335 // up to 64 bits. At the very least, we have to increase the striding of the 7336 // vaargs list to match this, and for FP values we need to introduce 7337 // FP_ROUND nodes as well. 7338 if (VT.isInteger() && !VT.isVector()) 7339 ArgSize = std::max(ArgSize, MinSlotSize); 7340 bool NeedFPTrunc = false; 7341 if (VT.isFloatingPoint() && !VT.isVector() && VT != MVT::f64) { 7342 ArgSize = 8; 7343 NeedFPTrunc = true; 7344 } 7345 7346 // Increment the pointer, VAList, to the next vaarg 7347 SDValue VANext = DAG.getNode(ISD::ADD, DL, PtrVT, VAList, 7348 DAG.getConstant(ArgSize, DL, PtrVT)); 7349 VANext = DAG.getZExtOrTrunc(VANext, DL, PtrMemVT); 7350 7351 // Store the incremented VAList to the legalized pointer 7352 SDValue APStore = 7353 DAG.getStore(Chain, DL, VANext, Addr, MachinePointerInfo(V)); 7354 7355 // Load the actual argument out of the pointer VAList 7356 if (NeedFPTrunc) { 7357 // Load the value as an f64. 7358 SDValue WideFP = 7359 DAG.getLoad(MVT::f64, DL, APStore, VAList, MachinePointerInfo()); 7360 // Round the value down to an f32. 7361 SDValue NarrowFP = DAG.getNode(ISD::FP_ROUND, DL, VT, WideFP.getValue(0), 7362 DAG.getIntPtrConstant(1, DL)); 7363 SDValue Ops[] = { NarrowFP, WideFP.getValue(1) }; 7364 // Merge the rounded value with the chain output of the load. 7365 return DAG.getMergeValues(Ops, DL); 7366 } 7367 7368 return DAG.getLoad(VT, DL, APStore, VAList, MachinePointerInfo()); 7369 } 7370 7371 SDValue AArch64TargetLowering::LowerFRAMEADDR(SDValue Op, 7372 SelectionDAG &DAG) const { 7373 MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo(); 7374 MFI.setFrameAddressIsTaken(true); 7375 7376 EVT VT = Op.getValueType(); 7377 SDLoc DL(Op); 7378 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue(); 7379 SDValue FrameAddr = 7380 DAG.getCopyFromReg(DAG.getEntryNode(), DL, AArch64::FP, MVT::i64); 7381 while (Depth--) 7382 FrameAddr = DAG.getLoad(VT, DL, DAG.getEntryNode(), FrameAddr, 7383 MachinePointerInfo()); 7384 7385 if (Subtarget->isTargetILP32()) 7386 FrameAddr = DAG.getNode(ISD::AssertZext, DL, MVT::i64, FrameAddr, 7387 DAG.getValueType(VT)); 7388 7389 return FrameAddr; 7390 } 7391 7392 SDValue AArch64TargetLowering::LowerSPONENTRY(SDValue Op, 7393 SelectionDAG &DAG) const { 7394 MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo(); 7395 7396 EVT VT = getPointerTy(DAG.getDataLayout()); 7397 SDLoc DL(Op); 7398 int FI = MFI.CreateFixedObject(4, 0, false); 7399 return DAG.getFrameIndex(FI, VT); 7400 } 7401 7402 #define GET_REGISTER_MATCHER 7403 #include "AArch64GenAsmMatcher.inc" 7404 7405 // FIXME? Maybe this could be a TableGen attribute on some registers and 7406 // this table could be generated automatically from RegInfo. 7407 Register AArch64TargetLowering:: 7408 getRegisterByName(const char* RegName, LLT VT, const MachineFunction &MF) const { 7409 Register Reg = MatchRegisterName(RegName); 7410 if (AArch64::X1 <= Reg && Reg <= AArch64::X28) { 7411 const MCRegisterInfo *MRI = Subtarget->getRegisterInfo(); 7412 unsigned DwarfRegNum = MRI->getDwarfRegNum(Reg, false); 7413 if (!Subtarget->isXRegisterReserved(DwarfRegNum)) 7414 Reg = 0; 7415 } 7416 if (Reg) 7417 return Reg; 7418 report_fatal_error(Twine("Invalid register name \"" 7419 + StringRef(RegName) + "\".")); 7420 } 7421 7422 SDValue AArch64TargetLowering::LowerADDROFRETURNADDR(SDValue Op, 7423 SelectionDAG &DAG) const { 7424 DAG.getMachineFunction().getFrameInfo().setFrameAddressIsTaken(true); 7425 7426 EVT VT = Op.getValueType(); 7427 SDLoc DL(Op); 7428 7429 SDValue FrameAddr = 7430 DAG.getCopyFromReg(DAG.getEntryNode(), DL, AArch64::FP, VT); 7431 SDValue Offset = DAG.getConstant(8, DL, getPointerTy(DAG.getDataLayout())); 7432 7433 return DAG.getNode(ISD::ADD, DL, VT, FrameAddr, Offset); 7434 } 7435 7436 SDValue AArch64TargetLowering::LowerRETURNADDR(SDValue Op, 7437 SelectionDAG &DAG) const { 7438 MachineFunction &MF = DAG.getMachineFunction(); 7439 MachineFrameInfo &MFI = MF.getFrameInfo(); 7440 MFI.setReturnAddressIsTaken(true); 7441 7442 EVT VT = Op.getValueType(); 7443 SDLoc DL(Op); 7444 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue(); 7445 SDValue ReturnAddress; 7446 if (Depth) { 7447 SDValue FrameAddr = LowerFRAMEADDR(Op, DAG); 7448 SDValue Offset = DAG.getConstant(8, DL, getPointerTy(DAG.getDataLayout())); 7449 ReturnAddress = DAG.getLoad( 7450 VT, DL, DAG.getEntryNode(), 7451 DAG.getNode(ISD::ADD, DL, VT, FrameAddr, Offset), MachinePointerInfo()); 7452 } else { 7453 // Return LR, which contains the return address. Mark it an implicit 7454 // live-in. 7455 unsigned Reg = MF.addLiveIn(AArch64::LR, &AArch64::GPR64RegClass); 7456 ReturnAddress = DAG.getCopyFromReg(DAG.getEntryNode(), DL, Reg, VT); 7457 } 7458 7459 // The XPACLRI instruction assembles to a hint-space instruction before 7460 // Armv8.3-A therefore this instruction can be safely used for any pre 7461 // Armv8.3-A architectures. On Armv8.3-A and onwards XPACI is available so use 7462 // that instead. 7463 SDNode *St; 7464 if (Subtarget->hasPAuth()) { 7465 St = DAG.getMachineNode(AArch64::XPACI, DL, VT, ReturnAddress); 7466 } else { 7467 // XPACLRI operates on LR therefore we must move the operand accordingly. 7468 SDValue Chain = 7469 DAG.getCopyToReg(DAG.getEntryNode(), DL, AArch64::LR, ReturnAddress); 7470 St = DAG.getMachineNode(AArch64::XPACLRI, DL, VT, Chain); 7471 } 7472 return SDValue(St, 0); 7473 } 7474 7475 /// LowerShiftRightParts - Lower SRA_PARTS, which returns two 7476 /// i64 values and take a 2 x i64 value to shift plus a shift amount. 7477 SDValue AArch64TargetLowering::LowerShiftRightParts(SDValue Op, 7478 SelectionDAG &DAG) const { 7479 assert(Op.getNumOperands() == 3 && "Not a double-shift!"); 7480 EVT VT = Op.getValueType(); 7481 unsigned VTBits = VT.getSizeInBits(); 7482 SDLoc dl(Op); 7483 SDValue ShOpLo = Op.getOperand(0); 7484 SDValue ShOpHi = Op.getOperand(1); 7485 SDValue ShAmt = Op.getOperand(2); 7486 unsigned Opc = (Op.getOpcode() == ISD::SRA_PARTS) ? ISD::SRA : ISD::SRL; 7487 7488 assert(Op.getOpcode() == ISD::SRA_PARTS || Op.getOpcode() == ISD::SRL_PARTS); 7489 7490 SDValue RevShAmt = DAG.getNode(ISD::SUB, dl, MVT::i64, 7491 DAG.getConstant(VTBits, dl, MVT::i64), ShAmt); 7492 SDValue HiBitsForLo = DAG.getNode(ISD::SHL, dl, VT, ShOpHi, RevShAmt); 7493 7494 // Unfortunately, if ShAmt == 0, we just calculated "(SHL ShOpHi, 64)" which 7495 // is "undef". We wanted 0, so CSEL it directly. 7496 SDValue Cmp = emitComparison(ShAmt, DAG.getConstant(0, dl, MVT::i64), 7497 ISD::SETEQ, dl, DAG); 7498 SDValue CCVal = DAG.getConstant(AArch64CC::EQ, dl, MVT::i32); 7499 HiBitsForLo = 7500 DAG.getNode(AArch64ISD::CSEL, dl, VT, DAG.getConstant(0, dl, MVT::i64), 7501 HiBitsForLo, CCVal, Cmp); 7502 7503 SDValue ExtraShAmt = DAG.getNode(ISD::SUB, dl, MVT::i64, ShAmt, 7504 DAG.getConstant(VTBits, dl, MVT::i64)); 7505 7506 SDValue LoBitsForLo = DAG.getNode(ISD::SRL, dl, VT, ShOpLo, ShAmt); 7507 SDValue LoForNormalShift = 7508 DAG.getNode(ISD::OR, dl, VT, LoBitsForLo, HiBitsForLo); 7509 7510 Cmp = emitComparison(ExtraShAmt, DAG.getConstant(0, dl, MVT::i64), ISD::SETGE, 7511 dl, DAG); 7512 CCVal = DAG.getConstant(AArch64CC::GE, dl, MVT::i32); 7513 SDValue LoForBigShift = DAG.getNode(Opc, dl, VT, ShOpHi, ExtraShAmt); 7514 SDValue Lo = DAG.getNode(AArch64ISD::CSEL, dl, VT, LoForBigShift, 7515 LoForNormalShift, CCVal, Cmp); 7516 7517 // AArch64 shifts larger than the register width are wrapped rather than 7518 // clamped, so we can't just emit "hi >> x". 7519 SDValue HiForNormalShift = DAG.getNode(Opc, dl, VT, ShOpHi, ShAmt); 7520 SDValue HiForBigShift = 7521 Opc == ISD::SRA 7522 ? DAG.getNode(Opc, dl, VT, ShOpHi, 7523 DAG.getConstant(VTBits - 1, dl, MVT::i64)) 7524 : DAG.getConstant(0, dl, VT); 7525 SDValue Hi = DAG.getNode(AArch64ISD::CSEL, dl, VT, HiForBigShift, 7526 HiForNormalShift, CCVal, Cmp); 7527 7528 SDValue Ops[2] = { Lo, Hi }; 7529 return DAG.getMergeValues(Ops, dl); 7530 } 7531 7532 /// LowerShiftLeftParts - Lower SHL_PARTS, which returns two 7533 /// i64 values and take a 2 x i64 value to shift plus a shift amount. 7534 SDValue AArch64TargetLowering::LowerShiftLeftParts(SDValue Op, 7535 SelectionDAG &DAG) const { 7536 assert(Op.getNumOperands() == 3 && "Not a double-shift!"); 7537 EVT VT = Op.getValueType(); 7538 unsigned VTBits = VT.getSizeInBits(); 7539 SDLoc dl(Op); 7540 SDValue ShOpLo = Op.getOperand(0); 7541 SDValue ShOpHi = Op.getOperand(1); 7542 SDValue ShAmt = Op.getOperand(2); 7543 7544 assert(Op.getOpcode() == ISD::SHL_PARTS); 7545 SDValue RevShAmt = DAG.getNode(ISD::SUB, dl, MVT::i64, 7546 DAG.getConstant(VTBits, dl, MVT::i64), ShAmt); 7547 SDValue LoBitsForHi = DAG.getNode(ISD::SRL, dl, VT, ShOpLo, RevShAmt); 7548 7549 // Unfortunately, if ShAmt == 0, we just calculated "(SRL ShOpLo, 64)" which 7550 // is "undef". We wanted 0, so CSEL it directly. 7551 SDValue Cmp = emitComparison(ShAmt, DAG.getConstant(0, dl, MVT::i64), 7552 ISD::SETEQ, dl, DAG); 7553 SDValue CCVal = DAG.getConstant(AArch64CC::EQ, dl, MVT::i32); 7554 LoBitsForHi = 7555 DAG.getNode(AArch64ISD::CSEL, dl, VT, DAG.getConstant(0, dl, MVT::i64), 7556 LoBitsForHi, CCVal, Cmp); 7557 7558 SDValue ExtraShAmt = DAG.getNode(ISD::SUB, dl, MVT::i64, ShAmt, 7559 DAG.getConstant(VTBits, dl, MVT::i64)); 7560 SDValue HiBitsForHi = DAG.getNode(ISD::SHL, dl, VT, ShOpHi, ShAmt); 7561 SDValue HiForNormalShift = 7562 DAG.getNode(ISD::OR, dl, VT, LoBitsForHi, HiBitsForHi); 7563 7564 SDValue HiForBigShift = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ExtraShAmt); 7565 7566 Cmp = emitComparison(ExtraShAmt, DAG.getConstant(0, dl, MVT::i64), ISD::SETGE, 7567 dl, DAG); 7568 CCVal = DAG.getConstant(AArch64CC::GE, dl, MVT::i32); 7569 SDValue Hi = DAG.getNode(AArch64ISD::CSEL, dl, VT, HiForBigShift, 7570 HiForNormalShift, CCVal, Cmp); 7571 7572 // AArch64 shifts of larger than register sizes are wrapped rather than 7573 // clamped, so we can't just emit "lo << a" if a is too big. 7574 SDValue LoForBigShift = DAG.getConstant(0, dl, VT); 7575 SDValue LoForNormalShift = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ShAmt); 7576 SDValue Lo = DAG.getNode(AArch64ISD::CSEL, dl, VT, LoForBigShift, 7577 LoForNormalShift, CCVal, Cmp); 7578 7579 SDValue Ops[2] = { Lo, Hi }; 7580 return DAG.getMergeValues(Ops, dl); 7581 } 7582 7583 bool AArch64TargetLowering::isOffsetFoldingLegal( 7584 const GlobalAddressSDNode *GA) const { 7585 // Offsets are folded in the DAG combine rather than here so that we can 7586 // intelligently choose an offset based on the uses. 7587 return false; 7588 } 7589 7590 bool AArch64TargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT, 7591 bool OptForSize) const { 7592 bool IsLegal = false; 7593 // We can materialize #0.0 as fmov $Rd, XZR for 64-bit, 32-bit cases, and 7594 // 16-bit case when target has full fp16 support. 7595 // FIXME: We should be able to handle f128 as well with a clever lowering. 7596 const APInt ImmInt = Imm.bitcastToAPInt(); 7597 if (VT == MVT::f64) 7598 IsLegal = AArch64_AM::getFP64Imm(ImmInt) != -1 || Imm.isPosZero(); 7599 else if (VT == MVT::f32) 7600 IsLegal = AArch64_AM::getFP32Imm(ImmInt) != -1 || Imm.isPosZero(); 7601 else if (VT == MVT::f16 && Subtarget->hasFullFP16()) 7602 IsLegal = AArch64_AM::getFP16Imm(ImmInt) != -1 || Imm.isPosZero(); 7603 // TODO: fmov h0, w0 is also legal, however on't have an isel pattern to 7604 // generate that fmov. 7605 7606 // If we can not materialize in immediate field for fmov, check if the 7607 // value can be encoded as the immediate operand of a logical instruction. 7608 // The immediate value will be created with either MOVZ, MOVN, or ORR. 7609 if (!IsLegal && (VT == MVT::f64 || VT == MVT::f32)) { 7610 // The cost is actually exactly the same for mov+fmov vs. adrp+ldr; 7611 // however the mov+fmov sequence is always better because of the reduced 7612 // cache pressure. The timings are still the same if you consider 7613 // movw+movk+fmov vs. adrp+ldr (it's one instruction longer, but the 7614 // movw+movk is fused). So we limit up to 2 instrdduction at most. 7615 SmallVector<AArch64_IMM::ImmInsnModel, 4> Insn; 7616 AArch64_IMM::expandMOVImm(ImmInt.getZExtValue(), VT.getSizeInBits(), 7617 Insn); 7618 unsigned Limit = (OptForSize ? 1 : (Subtarget->hasFuseLiterals() ? 5 : 2)); 7619 IsLegal = Insn.size() <= Limit; 7620 } 7621 7622 LLVM_DEBUG(dbgs() << (IsLegal ? "Legal " : "Illegal ") << VT.getEVTString() 7623 << " imm value: "; Imm.dump();); 7624 return IsLegal; 7625 } 7626 7627 //===----------------------------------------------------------------------===// 7628 // AArch64 Optimization Hooks 7629 //===----------------------------------------------------------------------===// 7630 7631 static SDValue getEstimate(const AArch64Subtarget *ST, unsigned Opcode, 7632 SDValue Operand, SelectionDAG &DAG, 7633 int &ExtraSteps) { 7634 EVT VT = Operand.getValueType(); 7635 if (ST->hasNEON() && 7636 (VT == MVT::f64 || VT == MVT::v1f64 || VT == MVT::v2f64 || 7637 VT == MVT::f32 || VT == MVT::v1f32 || 7638 VT == MVT::v2f32 || VT == MVT::v4f32)) { 7639 if (ExtraSteps == TargetLoweringBase::ReciprocalEstimate::Unspecified) 7640 // For the reciprocal estimates, convergence is quadratic, so the number 7641 // of digits is doubled after each iteration. In ARMv8, the accuracy of 7642 // the initial estimate is 2^-8. Thus the number of extra steps to refine 7643 // the result for float (23 mantissa bits) is 2 and for double (52 7644 // mantissa bits) is 3. 7645 ExtraSteps = VT.getScalarType() == MVT::f64 ? 3 : 2; 7646 7647 return DAG.getNode(Opcode, SDLoc(Operand), VT, Operand); 7648 } 7649 7650 return SDValue(); 7651 } 7652 7653 SDValue 7654 AArch64TargetLowering::getSqrtInputTest(SDValue Op, SelectionDAG &DAG, 7655 const DenormalMode &Mode) const { 7656 SDLoc DL(Op); 7657 EVT VT = Op.getValueType(); 7658 EVT CCVT = getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT); 7659 SDValue FPZero = DAG.getConstantFP(0.0, DL, VT); 7660 return DAG.getSetCC(DL, CCVT, Op, FPZero, ISD::SETEQ); 7661 } 7662 7663 SDValue 7664 AArch64TargetLowering::getSqrtResultForDenormInput(SDValue Op, 7665 SelectionDAG &DAG) const { 7666 return Op; 7667 } 7668 7669 SDValue AArch64TargetLowering::getSqrtEstimate(SDValue Operand, 7670 SelectionDAG &DAG, int Enabled, 7671 int &ExtraSteps, 7672 bool &UseOneConst, 7673 bool Reciprocal) const { 7674 if (Enabled == ReciprocalEstimate::Enabled || 7675 (Enabled == ReciprocalEstimate::Unspecified && Subtarget->useRSqrt())) 7676 if (SDValue Estimate = getEstimate(Subtarget, AArch64ISD::FRSQRTE, Operand, 7677 DAG, ExtraSteps)) { 7678 SDLoc DL(Operand); 7679 EVT VT = Operand.getValueType(); 7680 7681 SDNodeFlags Flags; 7682 Flags.setAllowReassociation(true); 7683 7684 // Newton reciprocal square root iteration: E * 0.5 * (3 - X * E^2) 7685 // AArch64 reciprocal square root iteration instruction: 0.5 * (3 - M * N) 7686 for (int i = ExtraSteps; i > 0; --i) { 7687 SDValue Step = DAG.getNode(ISD::FMUL, DL, VT, Estimate, Estimate, 7688 Flags); 7689 Step = DAG.getNode(AArch64ISD::FRSQRTS, DL, VT, Operand, Step, Flags); 7690 Estimate = DAG.getNode(ISD::FMUL, DL, VT, Estimate, Step, Flags); 7691 } 7692 if (!Reciprocal) 7693 Estimate = DAG.getNode(ISD::FMUL, DL, VT, Operand, Estimate, Flags); 7694 7695 ExtraSteps = 0; 7696 return Estimate; 7697 } 7698 7699 return SDValue(); 7700 } 7701 7702 SDValue AArch64TargetLowering::getRecipEstimate(SDValue Operand, 7703 SelectionDAG &DAG, int Enabled, 7704 int &ExtraSteps) const { 7705 if (Enabled == ReciprocalEstimate::Enabled) 7706 if (SDValue Estimate = getEstimate(Subtarget, AArch64ISD::FRECPE, Operand, 7707 DAG, ExtraSteps)) { 7708 SDLoc DL(Operand); 7709 EVT VT = Operand.getValueType(); 7710 7711 SDNodeFlags Flags; 7712 Flags.setAllowReassociation(true); 7713 7714 // Newton reciprocal iteration: E * (2 - X * E) 7715 // AArch64 reciprocal iteration instruction: (2 - M * N) 7716 for (int i = ExtraSteps; i > 0; --i) { 7717 SDValue Step = DAG.getNode(AArch64ISD::FRECPS, DL, VT, Operand, 7718 Estimate, Flags); 7719 Estimate = DAG.getNode(ISD::FMUL, DL, VT, Estimate, Step, Flags); 7720 } 7721 7722 ExtraSteps = 0; 7723 return Estimate; 7724 } 7725 7726 return SDValue(); 7727 } 7728 7729 //===----------------------------------------------------------------------===// 7730 // AArch64 Inline Assembly Support 7731 //===----------------------------------------------------------------------===// 7732 7733 // Table of Constraints 7734 // TODO: This is the current set of constraints supported by ARM for the 7735 // compiler, not all of them may make sense. 7736 // 7737 // r - A general register 7738 // w - An FP/SIMD register of some size in the range v0-v31 7739 // x - An FP/SIMD register of some size in the range v0-v15 7740 // I - Constant that can be used with an ADD instruction 7741 // J - Constant that can be used with a SUB instruction 7742 // K - Constant that can be used with a 32-bit logical instruction 7743 // L - Constant that can be used with a 64-bit logical instruction 7744 // M - Constant that can be used as a 32-bit MOV immediate 7745 // N - Constant that can be used as a 64-bit MOV immediate 7746 // Q - A memory reference with base register and no offset 7747 // S - A symbolic address 7748 // Y - Floating point constant zero 7749 // Z - Integer constant zero 7750 // 7751 // Note that general register operands will be output using their 64-bit x 7752 // register name, whatever the size of the variable, unless the asm operand 7753 // is prefixed by the %w modifier. Floating-point and SIMD register operands 7754 // will be output with the v prefix unless prefixed by the %b, %h, %s, %d or 7755 // %q modifier. 7756 const char *AArch64TargetLowering::LowerXConstraint(EVT ConstraintVT) const { 7757 // At this point, we have to lower this constraint to something else, so we 7758 // lower it to an "r" or "w". However, by doing this we will force the result 7759 // to be in register, while the X constraint is much more permissive. 7760 // 7761 // Although we are correct (we are free to emit anything, without 7762 // constraints), we might break use cases that would expect us to be more 7763 // efficient and emit something else. 7764 if (!Subtarget->hasFPARMv8()) 7765 return "r"; 7766 7767 if (ConstraintVT.isFloatingPoint()) 7768 return "w"; 7769 7770 if (ConstraintVT.isVector() && 7771 (ConstraintVT.getSizeInBits() == 64 || 7772 ConstraintVT.getSizeInBits() == 128)) 7773 return "w"; 7774 7775 return "r"; 7776 } 7777 7778 enum PredicateConstraint { 7779 Upl, 7780 Upa, 7781 Invalid 7782 }; 7783 7784 static PredicateConstraint parsePredicateConstraint(StringRef Constraint) { 7785 PredicateConstraint P = PredicateConstraint::Invalid; 7786 if (Constraint == "Upa") 7787 P = PredicateConstraint::Upa; 7788 if (Constraint == "Upl") 7789 P = PredicateConstraint::Upl; 7790 return P; 7791 } 7792 7793 /// getConstraintType - Given a constraint letter, return the type of 7794 /// constraint it is for this target. 7795 AArch64TargetLowering::ConstraintType 7796 AArch64TargetLowering::getConstraintType(StringRef Constraint) const { 7797 if (Constraint.size() == 1) { 7798 switch (Constraint[0]) { 7799 default: 7800 break; 7801 case 'x': 7802 case 'w': 7803 case 'y': 7804 return C_RegisterClass; 7805 // An address with a single base register. Due to the way we 7806 // currently handle addresses it is the same as 'r'. 7807 case 'Q': 7808 return C_Memory; 7809 case 'I': 7810 case 'J': 7811 case 'K': 7812 case 'L': 7813 case 'M': 7814 case 'N': 7815 case 'Y': 7816 case 'Z': 7817 return C_Immediate; 7818 case 'z': 7819 case 'S': // A symbolic address 7820 return C_Other; 7821 } 7822 } else if (parsePredicateConstraint(Constraint) != 7823 PredicateConstraint::Invalid) 7824 return C_RegisterClass; 7825 return TargetLowering::getConstraintType(Constraint); 7826 } 7827 7828 /// Examine constraint type and operand type and determine a weight value. 7829 /// This object must already have been set up with the operand type 7830 /// and the current alternative constraint selected. 7831 TargetLowering::ConstraintWeight 7832 AArch64TargetLowering::getSingleConstraintMatchWeight( 7833 AsmOperandInfo &info, const char *constraint) const { 7834 ConstraintWeight weight = CW_Invalid; 7835 Value *CallOperandVal = info.CallOperandVal; 7836 // If we don't have a value, we can't do a match, 7837 // but allow it at the lowest weight. 7838 if (!CallOperandVal) 7839 return CW_Default; 7840 Type *type = CallOperandVal->getType(); 7841 // Look at the constraint type. 7842 switch (*constraint) { 7843 default: 7844 weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint); 7845 break; 7846 case 'x': 7847 case 'w': 7848 case 'y': 7849 if (type->isFloatingPointTy() || type->isVectorTy()) 7850 weight = CW_Register; 7851 break; 7852 case 'z': 7853 weight = CW_Constant; 7854 break; 7855 case 'U': 7856 if (parsePredicateConstraint(constraint) != PredicateConstraint::Invalid) 7857 weight = CW_Register; 7858 break; 7859 } 7860 return weight; 7861 } 7862 7863 std::pair<unsigned, const TargetRegisterClass *> 7864 AArch64TargetLowering::getRegForInlineAsmConstraint( 7865 const TargetRegisterInfo *TRI, StringRef Constraint, MVT VT) const { 7866 if (Constraint.size() == 1) { 7867 switch (Constraint[0]) { 7868 case 'r': 7869 if (VT.isScalableVector()) 7870 return std::make_pair(0U, nullptr); 7871 if (VT.getFixedSizeInBits() == 64) 7872 return std::make_pair(0U, &AArch64::GPR64commonRegClass); 7873 return std::make_pair(0U, &AArch64::GPR32commonRegClass); 7874 case 'w': { 7875 if (!Subtarget->hasFPARMv8()) 7876 break; 7877 if (VT.isScalableVector()) { 7878 if (VT.getVectorElementType() != MVT::i1) 7879 return std::make_pair(0U, &AArch64::ZPRRegClass); 7880 return std::make_pair(0U, nullptr); 7881 } 7882 uint64_t VTSize = VT.getFixedSizeInBits(); 7883 if (VTSize == 16) 7884 return std::make_pair(0U, &AArch64::FPR16RegClass); 7885 if (VTSize == 32) 7886 return std::make_pair(0U, &AArch64::FPR32RegClass); 7887 if (VTSize == 64) 7888 return std::make_pair(0U, &AArch64::FPR64RegClass); 7889 if (VTSize == 128) 7890 return std::make_pair(0U, &AArch64::FPR128RegClass); 7891 break; 7892 } 7893 // The instructions that this constraint is designed for can 7894 // only take 128-bit registers so just use that regclass. 7895 case 'x': 7896 if (!Subtarget->hasFPARMv8()) 7897 break; 7898 if (VT.isScalableVector()) 7899 return std::make_pair(0U, &AArch64::ZPR_4bRegClass); 7900 if (VT.getSizeInBits() == 128) 7901 return std::make_pair(0U, &AArch64::FPR128_loRegClass); 7902 break; 7903 case 'y': 7904 if (!Subtarget->hasFPARMv8()) 7905 break; 7906 if (VT.isScalableVector()) 7907 return std::make_pair(0U, &AArch64::ZPR_3bRegClass); 7908 break; 7909 } 7910 } else { 7911 PredicateConstraint PC = parsePredicateConstraint(Constraint); 7912 if (PC != PredicateConstraint::Invalid) { 7913 if (!VT.isScalableVector() || VT.getVectorElementType() != MVT::i1) 7914 return std::make_pair(0U, nullptr); 7915 bool restricted = (PC == PredicateConstraint::Upl); 7916 return restricted ? std::make_pair(0U, &AArch64::PPR_3bRegClass) 7917 : std::make_pair(0U, &AArch64::PPRRegClass); 7918 } 7919 } 7920 if (StringRef("{cc}").equals_lower(Constraint)) 7921 return std::make_pair(unsigned(AArch64::NZCV), &AArch64::CCRRegClass); 7922 7923 // Use the default implementation in TargetLowering to convert the register 7924 // constraint into a member of a register class. 7925 std::pair<unsigned, const TargetRegisterClass *> Res; 7926 Res = TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT); 7927 7928 // Not found as a standard register? 7929 if (!Res.second) { 7930 unsigned Size = Constraint.size(); 7931 if ((Size == 4 || Size == 5) && Constraint[0] == '{' && 7932 tolower(Constraint[1]) == 'v' && Constraint[Size - 1] == '}') { 7933 int RegNo; 7934 bool Failed = Constraint.slice(2, Size - 1).getAsInteger(10, RegNo); 7935 if (!Failed && RegNo >= 0 && RegNo <= 31) { 7936 // v0 - v31 are aliases of q0 - q31 or d0 - d31 depending on size. 7937 // By default we'll emit v0-v31 for this unless there's a modifier where 7938 // we'll emit the correct register as well. 7939 if (VT != MVT::Other && VT.getSizeInBits() == 64) { 7940 Res.first = AArch64::FPR64RegClass.getRegister(RegNo); 7941 Res.second = &AArch64::FPR64RegClass; 7942 } else { 7943 Res.first = AArch64::FPR128RegClass.getRegister(RegNo); 7944 Res.second = &AArch64::FPR128RegClass; 7945 } 7946 } 7947 } 7948 } 7949 7950 if (Res.second && !Subtarget->hasFPARMv8() && 7951 !AArch64::GPR32allRegClass.hasSubClassEq(Res.second) && 7952 !AArch64::GPR64allRegClass.hasSubClassEq(Res.second)) 7953 return std::make_pair(0U, nullptr); 7954 7955 return Res; 7956 } 7957 7958 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops 7959 /// vector. If it is invalid, don't add anything to Ops. 7960 void AArch64TargetLowering::LowerAsmOperandForConstraint( 7961 SDValue Op, std::string &Constraint, std::vector<SDValue> &Ops, 7962 SelectionDAG &DAG) const { 7963 SDValue Result; 7964 7965 // Currently only support length 1 constraints. 7966 if (Constraint.length() != 1) 7967 return; 7968 7969 char ConstraintLetter = Constraint[0]; 7970 switch (ConstraintLetter) { 7971 default: 7972 break; 7973 7974 // This set of constraints deal with valid constants for various instructions. 7975 // Validate and return a target constant for them if we can. 7976 case 'z': { 7977 // 'z' maps to xzr or wzr so it needs an input of 0. 7978 if (!isNullConstant(Op)) 7979 return; 7980 7981 if (Op.getValueType() == MVT::i64) 7982 Result = DAG.getRegister(AArch64::XZR, MVT::i64); 7983 else 7984 Result = DAG.getRegister(AArch64::WZR, MVT::i32); 7985 break; 7986 } 7987 case 'S': { 7988 // An absolute symbolic address or label reference. 7989 if (const GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(Op)) { 7990 Result = DAG.getTargetGlobalAddress(GA->getGlobal(), SDLoc(Op), 7991 GA->getValueType(0)); 7992 } else if (const BlockAddressSDNode *BA = 7993 dyn_cast<BlockAddressSDNode>(Op)) { 7994 Result = 7995 DAG.getTargetBlockAddress(BA->getBlockAddress(), BA->getValueType(0)); 7996 } else if (const ExternalSymbolSDNode *ES = 7997 dyn_cast<ExternalSymbolSDNode>(Op)) { 7998 Result = 7999 DAG.getTargetExternalSymbol(ES->getSymbol(), ES->getValueType(0)); 8000 } else 8001 return; 8002 break; 8003 } 8004 8005 case 'I': 8006 case 'J': 8007 case 'K': 8008 case 'L': 8009 case 'M': 8010 case 'N': 8011 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op); 8012 if (!C) 8013 return; 8014 8015 // Grab the value and do some validation. 8016 uint64_t CVal = C->getZExtValue(); 8017 switch (ConstraintLetter) { 8018 // The I constraint applies only to simple ADD or SUB immediate operands: 8019 // i.e. 0 to 4095 with optional shift by 12 8020 // The J constraint applies only to ADD or SUB immediates that would be 8021 // valid when negated, i.e. if [an add pattern] were to be output as a SUB 8022 // instruction [or vice versa], in other words -1 to -4095 with optional 8023 // left shift by 12. 8024 case 'I': 8025 if (isUInt<12>(CVal) || isShiftedUInt<12, 12>(CVal)) 8026 break; 8027 return; 8028 case 'J': { 8029 uint64_t NVal = -C->getSExtValue(); 8030 if (isUInt<12>(NVal) || isShiftedUInt<12, 12>(NVal)) { 8031 CVal = C->getSExtValue(); 8032 break; 8033 } 8034 return; 8035 } 8036 // The K and L constraints apply *only* to logical immediates, including 8037 // what used to be the MOVI alias for ORR (though the MOVI alias has now 8038 // been removed and MOV should be used). So these constraints have to 8039 // distinguish between bit patterns that are valid 32-bit or 64-bit 8040 // "bitmask immediates": for example 0xaaaaaaaa is a valid bimm32 (K), but 8041 // not a valid bimm64 (L) where 0xaaaaaaaaaaaaaaaa would be valid, and vice 8042 // versa. 8043 case 'K': 8044 if (AArch64_AM::isLogicalImmediate(CVal, 32)) 8045 break; 8046 return; 8047 case 'L': 8048 if (AArch64_AM::isLogicalImmediate(CVal, 64)) 8049 break; 8050 return; 8051 // The M and N constraints are a superset of K and L respectively, for use 8052 // with the MOV (immediate) alias. As well as the logical immediates they 8053 // also match 32 or 64-bit immediates that can be loaded either using a 8054 // *single* MOVZ or MOVN , such as 32-bit 0x12340000, 0x00001234, 0xffffedca 8055 // (M) or 64-bit 0x1234000000000000 (N) etc. 8056 // As a note some of this code is liberally stolen from the asm parser. 8057 case 'M': { 8058 if (!isUInt<32>(CVal)) 8059 return; 8060 if (AArch64_AM::isLogicalImmediate(CVal, 32)) 8061 break; 8062 if ((CVal & 0xFFFF) == CVal) 8063 break; 8064 if ((CVal & 0xFFFF0000ULL) == CVal) 8065 break; 8066 uint64_t NCVal = ~(uint32_t)CVal; 8067 if ((NCVal & 0xFFFFULL) == NCVal) 8068 break; 8069 if ((NCVal & 0xFFFF0000ULL) == NCVal) 8070 break; 8071 return; 8072 } 8073 case 'N': { 8074 if (AArch64_AM::isLogicalImmediate(CVal, 64)) 8075 break; 8076 if ((CVal & 0xFFFFULL) == CVal) 8077 break; 8078 if ((CVal & 0xFFFF0000ULL) == CVal) 8079 break; 8080 if ((CVal & 0xFFFF00000000ULL) == CVal) 8081 break; 8082 if ((CVal & 0xFFFF000000000000ULL) == CVal) 8083 break; 8084 uint64_t NCVal = ~CVal; 8085 if ((NCVal & 0xFFFFULL) == NCVal) 8086 break; 8087 if ((NCVal & 0xFFFF0000ULL) == NCVal) 8088 break; 8089 if ((NCVal & 0xFFFF00000000ULL) == NCVal) 8090 break; 8091 if ((NCVal & 0xFFFF000000000000ULL) == NCVal) 8092 break; 8093 return; 8094 } 8095 default: 8096 return; 8097 } 8098 8099 // All assembler immediates are 64-bit integers. 8100 Result = DAG.getTargetConstant(CVal, SDLoc(Op), MVT::i64); 8101 break; 8102 } 8103 8104 if (Result.getNode()) { 8105 Ops.push_back(Result); 8106 return; 8107 } 8108 8109 return TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG); 8110 } 8111 8112 //===----------------------------------------------------------------------===// 8113 // AArch64 Advanced SIMD Support 8114 //===----------------------------------------------------------------------===// 8115 8116 /// WidenVector - Given a value in the V64 register class, produce the 8117 /// equivalent value in the V128 register class. 8118 static SDValue WidenVector(SDValue V64Reg, SelectionDAG &DAG) { 8119 EVT VT = V64Reg.getValueType(); 8120 unsigned NarrowSize = VT.getVectorNumElements(); 8121 MVT EltTy = VT.getVectorElementType().getSimpleVT(); 8122 MVT WideTy = MVT::getVectorVT(EltTy, 2 * NarrowSize); 8123 SDLoc DL(V64Reg); 8124 8125 return DAG.getNode(ISD::INSERT_SUBVECTOR, DL, WideTy, DAG.getUNDEF(WideTy), 8126 V64Reg, DAG.getConstant(0, DL, MVT::i64)); 8127 } 8128 8129 /// getExtFactor - Determine the adjustment factor for the position when 8130 /// generating an "extract from vector registers" instruction. 8131 static unsigned getExtFactor(SDValue &V) { 8132 EVT EltType = V.getValueType().getVectorElementType(); 8133 return EltType.getSizeInBits() / 8; 8134 } 8135 8136 /// NarrowVector - Given a value in the V128 register class, produce the 8137 /// equivalent value in the V64 register class. 8138 static SDValue NarrowVector(SDValue V128Reg, SelectionDAG &DAG) { 8139 EVT VT = V128Reg.getValueType(); 8140 unsigned WideSize = VT.getVectorNumElements(); 8141 MVT EltTy = VT.getVectorElementType().getSimpleVT(); 8142 MVT NarrowTy = MVT::getVectorVT(EltTy, WideSize / 2); 8143 SDLoc DL(V128Reg); 8144 8145 return DAG.getTargetExtractSubreg(AArch64::dsub, DL, NarrowTy, V128Reg); 8146 } 8147 8148 // Gather data to see if the operation can be modelled as a 8149 // shuffle in combination with VEXTs. 8150 SDValue AArch64TargetLowering::ReconstructShuffle(SDValue Op, 8151 SelectionDAG &DAG) const { 8152 assert(Op.getOpcode() == ISD::BUILD_VECTOR && "Unknown opcode!"); 8153 LLVM_DEBUG(dbgs() << "AArch64TargetLowering::ReconstructShuffle\n"); 8154 SDLoc dl(Op); 8155 EVT VT = Op.getValueType(); 8156 assert(!VT.isScalableVector() && 8157 "Scalable vectors cannot be used with ISD::BUILD_VECTOR"); 8158 unsigned NumElts = VT.getVectorNumElements(); 8159 8160 struct ShuffleSourceInfo { 8161 SDValue Vec; 8162 unsigned MinElt; 8163 unsigned MaxElt; 8164 8165 // We may insert some combination of BITCASTs and VEXT nodes to force Vec to 8166 // be compatible with the shuffle we intend to construct. As a result 8167 // ShuffleVec will be some sliding window into the original Vec. 8168 SDValue ShuffleVec; 8169 8170 // Code should guarantee that element i in Vec starts at element "WindowBase 8171 // + i * WindowScale in ShuffleVec". 8172 int WindowBase; 8173 int WindowScale; 8174 8175 ShuffleSourceInfo(SDValue Vec) 8176 : Vec(Vec), MinElt(std::numeric_limits<unsigned>::max()), MaxElt(0), 8177 ShuffleVec(Vec), WindowBase(0), WindowScale(1) {} 8178 8179 bool operator ==(SDValue OtherVec) { return Vec == OtherVec; } 8180 }; 8181 8182 // First gather all vectors used as an immediate source for this BUILD_VECTOR 8183 // node. 8184 SmallVector<ShuffleSourceInfo, 2> Sources; 8185 for (unsigned i = 0; i < NumElts; ++i) { 8186 SDValue V = Op.getOperand(i); 8187 if (V.isUndef()) 8188 continue; 8189 else if (V.getOpcode() != ISD::EXTRACT_VECTOR_ELT || 8190 !isa<ConstantSDNode>(V.getOperand(1))) { 8191 LLVM_DEBUG( 8192 dbgs() << "Reshuffle failed: " 8193 "a shuffle can only come from building a vector from " 8194 "various elements of other vectors, provided their " 8195 "indices are constant\n"); 8196 return SDValue(); 8197 } 8198 8199 // Add this element source to the list if it's not already there. 8200 SDValue SourceVec = V.getOperand(0); 8201 auto Source = find(Sources, SourceVec); 8202 if (Source == Sources.end()) 8203 Source = Sources.insert(Sources.end(), ShuffleSourceInfo(SourceVec)); 8204 8205 // Update the minimum and maximum lane number seen. 8206 unsigned EltNo = cast<ConstantSDNode>(V.getOperand(1))->getZExtValue(); 8207 Source->MinElt = std::min(Source->MinElt, EltNo); 8208 Source->MaxElt = std::max(Source->MaxElt, EltNo); 8209 } 8210 8211 if (Sources.size() > 2) { 8212 LLVM_DEBUG( 8213 dbgs() << "Reshuffle failed: currently only do something sane when at " 8214 "most two source vectors are involved\n"); 8215 return SDValue(); 8216 } 8217 8218 // Find out the smallest element size among result and two sources, and use 8219 // it as element size to build the shuffle_vector. 8220 EVT SmallestEltTy = VT.getVectorElementType(); 8221 for (auto &Source : Sources) { 8222 EVT SrcEltTy = Source.Vec.getValueType().getVectorElementType(); 8223 if (SrcEltTy.bitsLT(SmallestEltTy)) { 8224 SmallestEltTy = SrcEltTy; 8225 } 8226 } 8227 unsigned ResMultiplier = 8228 VT.getScalarSizeInBits() / SmallestEltTy.getFixedSizeInBits(); 8229 uint64_t VTSize = VT.getFixedSizeInBits(); 8230 NumElts = VTSize / SmallestEltTy.getFixedSizeInBits(); 8231 EVT ShuffleVT = EVT::getVectorVT(*DAG.getContext(), SmallestEltTy, NumElts); 8232 8233 // If the source vector is too wide or too narrow, we may nevertheless be able 8234 // to construct a compatible shuffle either by concatenating it with UNDEF or 8235 // extracting a suitable range of elements. 8236 for (auto &Src : Sources) { 8237 EVT SrcVT = Src.ShuffleVec.getValueType(); 8238 8239 uint64_t SrcVTSize = SrcVT.getFixedSizeInBits(); 8240 if (SrcVTSize == VTSize) 8241 continue; 8242 8243 // This stage of the search produces a source with the same element type as 8244 // the original, but with a total width matching the BUILD_VECTOR output. 8245 EVT EltVT = SrcVT.getVectorElementType(); 8246 unsigned NumSrcElts = VTSize / EltVT.getFixedSizeInBits(); 8247 EVT DestVT = EVT::getVectorVT(*DAG.getContext(), EltVT, NumSrcElts); 8248 8249 if (SrcVTSize < VTSize) { 8250 assert(2 * SrcVTSize == VTSize); 8251 // We can pad out the smaller vector for free, so if it's part of a 8252 // shuffle... 8253 Src.ShuffleVec = 8254 DAG.getNode(ISD::CONCAT_VECTORS, dl, DestVT, Src.ShuffleVec, 8255 DAG.getUNDEF(Src.ShuffleVec.getValueType())); 8256 continue; 8257 } 8258 8259 if (SrcVTSize != 2 * VTSize) { 8260 LLVM_DEBUG( 8261 dbgs() << "Reshuffle failed: result vector too small to extract\n"); 8262 return SDValue(); 8263 } 8264 8265 if (Src.MaxElt - Src.MinElt >= NumSrcElts) { 8266 LLVM_DEBUG( 8267 dbgs() << "Reshuffle failed: span too large for a VEXT to cope\n"); 8268 return SDValue(); 8269 } 8270 8271 if (Src.MinElt >= NumSrcElts) { 8272 // The extraction can just take the second half 8273 Src.ShuffleVec = 8274 DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DestVT, Src.ShuffleVec, 8275 DAG.getConstant(NumSrcElts, dl, MVT::i64)); 8276 Src.WindowBase = -NumSrcElts; 8277 } else if (Src.MaxElt < NumSrcElts) { 8278 // The extraction can just take the first half 8279 Src.ShuffleVec = 8280 DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DestVT, Src.ShuffleVec, 8281 DAG.getConstant(0, dl, MVT::i64)); 8282 } else { 8283 // An actual VEXT is needed 8284 SDValue VEXTSrc1 = 8285 DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DestVT, Src.ShuffleVec, 8286 DAG.getConstant(0, dl, MVT::i64)); 8287 SDValue VEXTSrc2 = 8288 DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DestVT, Src.ShuffleVec, 8289 DAG.getConstant(NumSrcElts, dl, MVT::i64)); 8290 unsigned Imm = Src.MinElt * getExtFactor(VEXTSrc1); 8291 8292 if (!SrcVT.is64BitVector()) { 8293 LLVM_DEBUG( 8294 dbgs() << "Reshuffle failed: don't know how to lower AArch64ISD::EXT " 8295 "for SVE vectors."); 8296 return SDValue(); 8297 } 8298 8299 Src.ShuffleVec = DAG.getNode(AArch64ISD::EXT, dl, DestVT, VEXTSrc1, 8300 VEXTSrc2, 8301 DAG.getConstant(Imm, dl, MVT::i32)); 8302 Src.WindowBase = -Src.MinElt; 8303 } 8304 } 8305 8306 // Another possible incompatibility occurs from the vector element types. We 8307 // can fix this by bitcasting the source vectors to the same type we intend 8308 // for the shuffle. 8309 for (auto &Src : Sources) { 8310 EVT SrcEltTy = Src.ShuffleVec.getValueType().getVectorElementType(); 8311 if (SrcEltTy == SmallestEltTy) 8312 continue; 8313 assert(ShuffleVT.getVectorElementType() == SmallestEltTy); 8314 Src.ShuffleVec = DAG.getNode(ISD::BITCAST, dl, ShuffleVT, Src.ShuffleVec); 8315 Src.WindowScale = 8316 SrcEltTy.getFixedSizeInBits() / SmallestEltTy.getFixedSizeInBits(); 8317 Src.WindowBase *= Src.WindowScale; 8318 } 8319 8320 // Final sanity check before we try to actually produce a shuffle. 8321 LLVM_DEBUG(for (auto Src 8322 : Sources) 8323 assert(Src.ShuffleVec.getValueType() == ShuffleVT);); 8324 8325 // The stars all align, our next step is to produce the mask for the shuffle. 8326 SmallVector<int, 8> Mask(ShuffleVT.getVectorNumElements(), -1); 8327 int BitsPerShuffleLane = ShuffleVT.getScalarSizeInBits(); 8328 for (unsigned i = 0; i < VT.getVectorNumElements(); ++i) { 8329 SDValue Entry = Op.getOperand(i); 8330 if (Entry.isUndef()) 8331 continue; 8332 8333 auto Src = find(Sources, Entry.getOperand(0)); 8334 int EltNo = cast<ConstantSDNode>(Entry.getOperand(1))->getSExtValue(); 8335 8336 // EXTRACT_VECTOR_ELT performs an implicit any_ext; BUILD_VECTOR an implicit 8337 // trunc. So only std::min(SrcBits, DestBits) actually get defined in this 8338 // segment. 8339 EVT OrigEltTy = Entry.getOperand(0).getValueType().getVectorElementType(); 8340 int BitsDefined = std::min(OrigEltTy.getScalarSizeInBits(), 8341 VT.getScalarSizeInBits()); 8342 int LanesDefined = BitsDefined / BitsPerShuffleLane; 8343 8344 // This source is expected to fill ResMultiplier lanes of the final shuffle, 8345 // starting at the appropriate offset. 8346 int *LaneMask = &Mask[i * ResMultiplier]; 8347 8348 int ExtractBase = EltNo * Src->WindowScale + Src->WindowBase; 8349 ExtractBase += NumElts * (Src - Sources.begin()); 8350 for (int j = 0; j < LanesDefined; ++j) 8351 LaneMask[j] = ExtractBase + j; 8352 } 8353 8354 // Final check before we try to produce nonsense... 8355 if (!isShuffleMaskLegal(Mask, ShuffleVT)) { 8356 LLVM_DEBUG(dbgs() << "Reshuffle failed: illegal shuffle mask\n"); 8357 return SDValue(); 8358 } 8359 8360 SDValue ShuffleOps[] = { DAG.getUNDEF(ShuffleVT), DAG.getUNDEF(ShuffleVT) }; 8361 for (unsigned i = 0; i < Sources.size(); ++i) 8362 ShuffleOps[i] = Sources[i].ShuffleVec; 8363 8364 SDValue Shuffle = DAG.getVectorShuffle(ShuffleVT, dl, ShuffleOps[0], 8365 ShuffleOps[1], Mask); 8366 SDValue V = DAG.getNode(ISD::BITCAST, dl, VT, Shuffle); 8367 8368 LLVM_DEBUG(dbgs() << "Reshuffle, creating node: "; Shuffle.dump(); 8369 dbgs() << "Reshuffle, creating node: "; V.dump();); 8370 8371 return V; 8372 } 8373 8374 // check if an EXT instruction can handle the shuffle mask when the 8375 // vector sources of the shuffle are the same. 8376 static bool isSingletonEXTMask(ArrayRef<int> M, EVT VT, unsigned &Imm) { 8377 unsigned NumElts = VT.getVectorNumElements(); 8378 8379 // Assume that the first shuffle index is not UNDEF. Fail if it is. 8380 if (M[0] < 0) 8381 return false; 8382 8383 Imm = M[0]; 8384 8385 // If this is a VEXT shuffle, the immediate value is the index of the first 8386 // element. The other shuffle indices must be the successive elements after 8387 // the first one. 8388 unsigned ExpectedElt = Imm; 8389 for (unsigned i = 1; i < NumElts; ++i) { 8390 // Increment the expected index. If it wraps around, just follow it 8391 // back to index zero and keep going. 8392 ++ExpectedElt; 8393 if (ExpectedElt == NumElts) 8394 ExpectedElt = 0; 8395 8396 if (M[i] < 0) 8397 continue; // ignore UNDEF indices 8398 if (ExpectedElt != static_cast<unsigned>(M[i])) 8399 return false; 8400 } 8401 8402 return true; 8403 } 8404 8405 /// Check if a vector shuffle corresponds to a DUP instructions with a larger 8406 /// element width than the vector lane type. If that is the case the function 8407 /// returns true and writes the value of the DUP instruction lane operand into 8408 /// DupLaneOp 8409 static bool isWideDUPMask(ArrayRef<int> M, EVT VT, unsigned BlockSize, 8410 unsigned &DupLaneOp) { 8411 assert((BlockSize == 16 || BlockSize == 32 || BlockSize == 64) && 8412 "Only possible block sizes for wide DUP are: 16, 32, 64"); 8413 8414 if (BlockSize <= VT.getScalarSizeInBits()) 8415 return false; 8416 if (BlockSize % VT.getScalarSizeInBits() != 0) 8417 return false; 8418 if (VT.getSizeInBits() % BlockSize != 0) 8419 return false; 8420 8421 size_t SingleVecNumElements = VT.getVectorNumElements(); 8422 size_t NumEltsPerBlock = BlockSize / VT.getScalarSizeInBits(); 8423 size_t NumBlocks = VT.getSizeInBits() / BlockSize; 8424 8425 // We are looking for masks like 8426 // [0, 1, 0, 1] or [2, 3, 2, 3] or [4, 5, 6, 7, 4, 5, 6, 7] where any element 8427 // might be replaced by 'undefined'. BlockIndices will eventually contain 8428 // lane indices of the duplicated block (i.e. [0, 1], [2, 3] and [4, 5, 6, 7] 8429 // for the above examples) 8430 SmallVector<int, 8> BlockElts(NumEltsPerBlock, -1); 8431 for (size_t BlockIndex = 0; BlockIndex < NumBlocks; BlockIndex++) 8432 for (size_t I = 0; I < NumEltsPerBlock; I++) { 8433 int Elt = M[BlockIndex * NumEltsPerBlock + I]; 8434 if (Elt < 0) 8435 continue; 8436 // For now we don't support shuffles that use the second operand 8437 if ((unsigned)Elt >= SingleVecNumElements) 8438 return false; 8439 if (BlockElts[I] < 0) 8440 BlockElts[I] = Elt; 8441 else if (BlockElts[I] != Elt) 8442 return false; 8443 } 8444 8445 // We found a candidate block (possibly with some undefs). It must be a 8446 // sequence of consecutive integers starting with a value divisible by 8447 // NumEltsPerBlock with some values possibly replaced by undef-s. 8448 8449 // Find first non-undef element 8450 auto FirstRealEltIter = find_if(BlockElts, [](int Elt) { return Elt >= 0; }); 8451 assert(FirstRealEltIter != BlockElts.end() && 8452 "Shuffle with all-undefs must have been caught by previous cases, " 8453 "e.g. isSplat()"); 8454 if (FirstRealEltIter == BlockElts.end()) { 8455 DupLaneOp = 0; 8456 return true; 8457 } 8458 8459 // Index of FirstRealElt in BlockElts 8460 size_t FirstRealIndex = FirstRealEltIter - BlockElts.begin(); 8461 8462 if ((unsigned)*FirstRealEltIter < FirstRealIndex) 8463 return false; 8464 // BlockElts[0] must have the following value if it isn't undef: 8465 size_t Elt0 = *FirstRealEltIter - FirstRealIndex; 8466 8467 // Check the first element 8468 if (Elt0 % NumEltsPerBlock != 0) 8469 return false; 8470 // Check that the sequence indeed consists of consecutive integers (modulo 8471 // undefs) 8472 for (size_t I = 0; I < NumEltsPerBlock; I++) 8473 if (BlockElts[I] >= 0 && (unsigned)BlockElts[I] != Elt0 + I) 8474 return false; 8475 8476 DupLaneOp = Elt0 / NumEltsPerBlock; 8477 return true; 8478 } 8479 8480 // check if an EXT instruction can handle the shuffle mask when the 8481 // vector sources of the shuffle are different. 8482 static bool isEXTMask(ArrayRef<int> M, EVT VT, bool &ReverseEXT, 8483 unsigned &Imm) { 8484 // Look for the first non-undef element. 8485 const int *FirstRealElt = find_if(M, [](int Elt) { return Elt >= 0; }); 8486 8487 // Benefit form APInt to handle overflow when calculating expected element. 8488 unsigned NumElts = VT.getVectorNumElements(); 8489 unsigned MaskBits = APInt(32, NumElts * 2).logBase2(); 8490 APInt ExpectedElt = APInt(MaskBits, *FirstRealElt + 1); 8491 // The following shuffle indices must be the successive elements after the 8492 // first real element. 8493 const int *FirstWrongElt = std::find_if(FirstRealElt + 1, M.end(), 8494 [&](int Elt) {return Elt != ExpectedElt++ && Elt != -1;}); 8495 if (FirstWrongElt != M.end()) 8496 return false; 8497 8498 // The index of an EXT is the first element if it is not UNDEF. 8499 // Watch out for the beginning UNDEFs. The EXT index should be the expected 8500 // value of the first element. E.g. 8501 // <-1, -1, 3, ...> is treated as <1, 2, 3, ...>. 8502 // <-1, -1, 0, 1, ...> is treated as <2*NumElts-2, 2*NumElts-1, 0, 1, ...>. 8503 // ExpectedElt is the last mask index plus 1. 8504 Imm = ExpectedElt.getZExtValue(); 8505 8506 // There are two difference cases requiring to reverse input vectors. 8507 // For example, for vector <4 x i32> we have the following cases, 8508 // Case 1: shufflevector(<4 x i32>,<4 x i32>,<-1, -1, -1, 0>) 8509 // Case 2: shufflevector(<4 x i32>,<4 x i32>,<-1, -1, 7, 0>) 8510 // For both cases, we finally use mask <5, 6, 7, 0>, which requires 8511 // to reverse two input vectors. 8512 if (Imm < NumElts) 8513 ReverseEXT = true; 8514 else 8515 Imm -= NumElts; 8516 8517 return true; 8518 } 8519 8520 /// isREVMask - Check if a vector shuffle corresponds to a REV 8521 /// instruction with the specified blocksize. (The order of the elements 8522 /// within each block of the vector is reversed.) 8523 static bool isREVMask(ArrayRef<int> M, EVT VT, unsigned BlockSize) { 8524 assert((BlockSize == 16 || BlockSize == 32 || BlockSize == 64) && 8525 "Only possible block sizes for REV are: 16, 32, 64"); 8526 8527 unsigned EltSz = VT.getScalarSizeInBits(); 8528 if (EltSz == 64) 8529 return false; 8530 8531 unsigned NumElts = VT.getVectorNumElements(); 8532 unsigned BlockElts = M[0] + 1; 8533 // If the first shuffle index is UNDEF, be optimistic. 8534 if (M[0] < 0) 8535 BlockElts = BlockSize / EltSz; 8536 8537 if (BlockSize <= EltSz || BlockSize != BlockElts * EltSz) 8538 return false; 8539 8540 for (unsigned i = 0; i < NumElts; ++i) { 8541 if (M[i] < 0) 8542 continue; // ignore UNDEF indices 8543 if ((unsigned)M[i] != (i - i % BlockElts) + (BlockElts - 1 - i % BlockElts)) 8544 return false; 8545 } 8546 8547 return true; 8548 } 8549 8550 static bool isZIPMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) { 8551 unsigned NumElts = VT.getVectorNumElements(); 8552 if (NumElts % 2 != 0) 8553 return false; 8554 WhichResult = (M[0] == 0 ? 0 : 1); 8555 unsigned Idx = WhichResult * NumElts / 2; 8556 for (unsigned i = 0; i != NumElts; i += 2) { 8557 if ((M[i] >= 0 && (unsigned)M[i] != Idx) || 8558 (M[i + 1] >= 0 && (unsigned)M[i + 1] != Idx + NumElts)) 8559 return false; 8560 Idx += 1; 8561 } 8562 8563 return true; 8564 } 8565 8566 static bool isUZPMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) { 8567 unsigned NumElts = VT.getVectorNumElements(); 8568 WhichResult = (M[0] == 0 ? 0 : 1); 8569 for (unsigned i = 0; i != NumElts; ++i) { 8570 if (M[i] < 0) 8571 continue; // ignore UNDEF indices 8572 if ((unsigned)M[i] != 2 * i + WhichResult) 8573 return false; 8574 } 8575 8576 return true; 8577 } 8578 8579 static bool isTRNMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) { 8580 unsigned NumElts = VT.getVectorNumElements(); 8581 if (NumElts % 2 != 0) 8582 return false; 8583 WhichResult = (M[0] == 0 ? 0 : 1); 8584 for (unsigned i = 0; i < NumElts; i += 2) { 8585 if ((M[i] >= 0 && (unsigned)M[i] != i + WhichResult) || 8586 (M[i + 1] >= 0 && (unsigned)M[i + 1] != i + NumElts + WhichResult)) 8587 return false; 8588 } 8589 return true; 8590 } 8591 8592 /// isZIP_v_undef_Mask - Special case of isZIPMask for canonical form of 8593 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef". 8594 /// Mask is e.g., <0, 0, 1, 1> instead of <0, 4, 1, 5>. 8595 static bool isZIP_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) { 8596 unsigned NumElts = VT.getVectorNumElements(); 8597 if (NumElts % 2 != 0) 8598 return false; 8599 WhichResult = (M[0] == 0 ? 0 : 1); 8600 unsigned Idx = WhichResult * NumElts / 2; 8601 for (unsigned i = 0; i != NumElts; i += 2) { 8602 if ((M[i] >= 0 && (unsigned)M[i] != Idx) || 8603 (M[i + 1] >= 0 && (unsigned)M[i + 1] != Idx)) 8604 return false; 8605 Idx += 1; 8606 } 8607 8608 return true; 8609 } 8610 8611 /// isUZP_v_undef_Mask - Special case of isUZPMask for canonical form of 8612 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef". 8613 /// Mask is e.g., <0, 2, 0, 2> instead of <0, 2, 4, 6>, 8614 static bool isUZP_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) { 8615 unsigned Half = VT.getVectorNumElements() / 2; 8616 WhichResult = (M[0] == 0 ? 0 : 1); 8617 for (unsigned j = 0; j != 2; ++j) { 8618 unsigned Idx = WhichResult; 8619 for (unsigned i = 0; i != Half; ++i) { 8620 int MIdx = M[i + j * Half]; 8621 if (MIdx >= 0 && (unsigned)MIdx != Idx) 8622 return false; 8623 Idx += 2; 8624 } 8625 } 8626 8627 return true; 8628 } 8629 8630 /// isTRN_v_undef_Mask - Special case of isTRNMask for canonical form of 8631 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef". 8632 /// Mask is e.g., <0, 0, 2, 2> instead of <0, 4, 2, 6>. 8633 static bool isTRN_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) { 8634 unsigned NumElts = VT.getVectorNumElements(); 8635 if (NumElts % 2 != 0) 8636 return false; 8637 WhichResult = (M[0] == 0 ? 0 : 1); 8638 for (unsigned i = 0; i < NumElts; i += 2) { 8639 if ((M[i] >= 0 && (unsigned)M[i] != i + WhichResult) || 8640 (M[i + 1] >= 0 && (unsigned)M[i + 1] != i + WhichResult)) 8641 return false; 8642 } 8643 return true; 8644 } 8645 8646 static bool isINSMask(ArrayRef<int> M, int NumInputElements, 8647 bool &DstIsLeft, int &Anomaly) { 8648 if (M.size() != static_cast<size_t>(NumInputElements)) 8649 return false; 8650 8651 int NumLHSMatch = 0, NumRHSMatch = 0; 8652 int LastLHSMismatch = -1, LastRHSMismatch = -1; 8653 8654 for (int i = 0; i < NumInputElements; ++i) { 8655 if (M[i] == -1) { 8656 ++NumLHSMatch; 8657 ++NumRHSMatch; 8658 continue; 8659 } 8660 8661 if (M[i] == i) 8662 ++NumLHSMatch; 8663 else 8664 LastLHSMismatch = i; 8665 8666 if (M[i] == i + NumInputElements) 8667 ++NumRHSMatch; 8668 else 8669 LastRHSMismatch = i; 8670 } 8671 8672 if (NumLHSMatch == NumInputElements - 1) { 8673 DstIsLeft = true; 8674 Anomaly = LastLHSMismatch; 8675 return true; 8676 } else if (NumRHSMatch == NumInputElements - 1) { 8677 DstIsLeft = false; 8678 Anomaly = LastRHSMismatch; 8679 return true; 8680 } 8681 8682 return false; 8683 } 8684 8685 static bool isConcatMask(ArrayRef<int> Mask, EVT VT, bool SplitLHS) { 8686 if (VT.getSizeInBits() != 128) 8687 return false; 8688 8689 unsigned NumElts = VT.getVectorNumElements(); 8690 8691 for (int I = 0, E = NumElts / 2; I != E; I++) { 8692 if (Mask[I] != I) 8693 return false; 8694 } 8695 8696 int Offset = NumElts / 2; 8697 for (int I = NumElts / 2, E = NumElts; I != E; I++) { 8698 if (Mask[I] != I + SplitLHS * Offset) 8699 return false; 8700 } 8701 8702 return true; 8703 } 8704 8705 static SDValue tryFormConcatFromShuffle(SDValue Op, SelectionDAG &DAG) { 8706 SDLoc DL(Op); 8707 EVT VT = Op.getValueType(); 8708 SDValue V0 = Op.getOperand(0); 8709 SDValue V1 = Op.getOperand(1); 8710 ArrayRef<int> Mask = cast<ShuffleVectorSDNode>(Op)->getMask(); 8711 8712 if (VT.getVectorElementType() != V0.getValueType().getVectorElementType() || 8713 VT.getVectorElementType() != V1.getValueType().getVectorElementType()) 8714 return SDValue(); 8715 8716 bool SplitV0 = V0.getValueSizeInBits() == 128; 8717 8718 if (!isConcatMask(Mask, VT, SplitV0)) 8719 return SDValue(); 8720 8721 EVT CastVT = VT.getHalfNumVectorElementsVT(*DAG.getContext()); 8722 if (SplitV0) { 8723 V0 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, CastVT, V0, 8724 DAG.getConstant(0, DL, MVT::i64)); 8725 } 8726 if (V1.getValueSizeInBits() == 128) { 8727 V1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, CastVT, V1, 8728 DAG.getConstant(0, DL, MVT::i64)); 8729 } 8730 return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, V0, V1); 8731 } 8732 8733 /// GeneratePerfectShuffle - Given an entry in the perfect-shuffle table, emit 8734 /// the specified operations to build the shuffle. 8735 static SDValue GeneratePerfectShuffle(unsigned PFEntry, SDValue LHS, 8736 SDValue RHS, SelectionDAG &DAG, 8737 const SDLoc &dl) { 8738 unsigned OpNum = (PFEntry >> 26) & 0x0F; 8739 unsigned LHSID = (PFEntry >> 13) & ((1 << 13) - 1); 8740 unsigned RHSID = (PFEntry >> 0) & ((1 << 13) - 1); 8741 8742 enum { 8743 OP_COPY = 0, // Copy, used for things like <u,u,u,3> to say it is <0,1,2,3> 8744 OP_VREV, 8745 OP_VDUP0, 8746 OP_VDUP1, 8747 OP_VDUP2, 8748 OP_VDUP3, 8749 OP_VEXT1, 8750 OP_VEXT2, 8751 OP_VEXT3, 8752 OP_VUZPL, // VUZP, left result 8753 OP_VUZPR, // VUZP, right result 8754 OP_VZIPL, // VZIP, left result 8755 OP_VZIPR, // VZIP, right result 8756 OP_VTRNL, // VTRN, left result 8757 OP_VTRNR // VTRN, right result 8758 }; 8759 8760 if (OpNum == OP_COPY) { 8761 if (LHSID == (1 * 9 + 2) * 9 + 3) 8762 return LHS; 8763 assert(LHSID == ((4 * 9 + 5) * 9 + 6) * 9 + 7 && "Illegal OP_COPY!"); 8764 return RHS; 8765 } 8766 8767 SDValue OpLHS, OpRHS; 8768 OpLHS = GeneratePerfectShuffle(PerfectShuffleTable[LHSID], LHS, RHS, DAG, dl); 8769 OpRHS = GeneratePerfectShuffle(PerfectShuffleTable[RHSID], LHS, RHS, DAG, dl); 8770 EVT VT = OpLHS.getValueType(); 8771 8772 switch (OpNum) { 8773 default: 8774 llvm_unreachable("Unknown shuffle opcode!"); 8775 case OP_VREV: 8776 // VREV divides the vector in half and swaps within the half. 8777 if (VT.getVectorElementType() == MVT::i32 || 8778 VT.getVectorElementType() == MVT::f32) 8779 return DAG.getNode(AArch64ISD::REV64, dl, VT, OpLHS); 8780 // vrev <4 x i16> -> REV32 8781 if (VT.getVectorElementType() == MVT::i16 || 8782 VT.getVectorElementType() == MVT::f16 || 8783 VT.getVectorElementType() == MVT::bf16) 8784 return DAG.getNode(AArch64ISD::REV32, dl, VT, OpLHS); 8785 // vrev <4 x i8> -> REV16 8786 assert(VT.getVectorElementType() == MVT::i8); 8787 return DAG.getNode(AArch64ISD::REV16, dl, VT, OpLHS); 8788 case OP_VDUP0: 8789 case OP_VDUP1: 8790 case OP_VDUP2: 8791 case OP_VDUP3: { 8792 EVT EltTy = VT.getVectorElementType(); 8793 unsigned Opcode; 8794 if (EltTy == MVT::i8) 8795 Opcode = AArch64ISD::DUPLANE8; 8796 else if (EltTy == MVT::i16 || EltTy == MVT::f16 || EltTy == MVT::bf16) 8797 Opcode = AArch64ISD::DUPLANE16; 8798 else if (EltTy == MVT::i32 || EltTy == MVT::f32) 8799 Opcode = AArch64ISD::DUPLANE32; 8800 else if (EltTy == MVT::i64 || EltTy == MVT::f64) 8801 Opcode = AArch64ISD::DUPLANE64; 8802 else 8803 llvm_unreachable("Invalid vector element type?"); 8804 8805 if (VT.getSizeInBits() == 64) 8806 OpLHS = WidenVector(OpLHS, DAG); 8807 SDValue Lane = DAG.getConstant(OpNum - OP_VDUP0, dl, MVT::i64); 8808 return DAG.getNode(Opcode, dl, VT, OpLHS, Lane); 8809 } 8810 case OP_VEXT1: 8811 case OP_VEXT2: 8812 case OP_VEXT3: { 8813 unsigned Imm = (OpNum - OP_VEXT1 + 1) * getExtFactor(OpLHS); 8814 return DAG.getNode(AArch64ISD::EXT, dl, VT, OpLHS, OpRHS, 8815 DAG.getConstant(Imm, dl, MVT::i32)); 8816 } 8817 case OP_VUZPL: 8818 return DAG.getNode(AArch64ISD::UZP1, dl, DAG.getVTList(VT, VT), OpLHS, 8819 OpRHS); 8820 case OP_VUZPR: 8821 return DAG.getNode(AArch64ISD::UZP2, dl, DAG.getVTList(VT, VT), OpLHS, 8822 OpRHS); 8823 case OP_VZIPL: 8824 return DAG.getNode(AArch64ISD::ZIP1, dl, DAG.getVTList(VT, VT), OpLHS, 8825 OpRHS); 8826 case OP_VZIPR: 8827 return DAG.getNode(AArch64ISD::ZIP2, dl, DAG.getVTList(VT, VT), OpLHS, 8828 OpRHS); 8829 case OP_VTRNL: 8830 return DAG.getNode(AArch64ISD::TRN1, dl, DAG.getVTList(VT, VT), OpLHS, 8831 OpRHS); 8832 case OP_VTRNR: 8833 return DAG.getNode(AArch64ISD::TRN2, dl, DAG.getVTList(VT, VT), OpLHS, 8834 OpRHS); 8835 } 8836 } 8837 8838 static SDValue GenerateTBL(SDValue Op, ArrayRef<int> ShuffleMask, 8839 SelectionDAG &DAG) { 8840 // Check to see if we can use the TBL instruction. 8841 SDValue V1 = Op.getOperand(0); 8842 SDValue V2 = Op.getOperand(1); 8843 SDLoc DL(Op); 8844 8845 EVT EltVT = Op.getValueType().getVectorElementType(); 8846 unsigned BytesPerElt = EltVT.getSizeInBits() / 8; 8847 8848 SmallVector<SDValue, 8> TBLMask; 8849 for (int Val : ShuffleMask) { 8850 for (unsigned Byte = 0; Byte < BytesPerElt; ++Byte) { 8851 unsigned Offset = Byte + Val * BytesPerElt; 8852 TBLMask.push_back(DAG.getConstant(Offset, DL, MVT::i32)); 8853 } 8854 } 8855 8856 MVT IndexVT = MVT::v8i8; 8857 unsigned IndexLen = 8; 8858 if (Op.getValueSizeInBits() == 128) { 8859 IndexVT = MVT::v16i8; 8860 IndexLen = 16; 8861 } 8862 8863 SDValue V1Cst = DAG.getNode(ISD::BITCAST, DL, IndexVT, V1); 8864 SDValue V2Cst = DAG.getNode(ISD::BITCAST, DL, IndexVT, V2); 8865 8866 SDValue Shuffle; 8867 if (V2.getNode()->isUndef()) { 8868 if (IndexLen == 8) 8869 V1Cst = DAG.getNode(ISD::CONCAT_VECTORS, DL, MVT::v16i8, V1Cst, V1Cst); 8870 Shuffle = DAG.getNode( 8871 ISD::INTRINSIC_WO_CHAIN, DL, IndexVT, 8872 DAG.getConstant(Intrinsic::aarch64_neon_tbl1, DL, MVT::i32), V1Cst, 8873 DAG.getBuildVector(IndexVT, DL, 8874 makeArrayRef(TBLMask.data(), IndexLen))); 8875 } else { 8876 if (IndexLen == 8) { 8877 V1Cst = DAG.getNode(ISD::CONCAT_VECTORS, DL, MVT::v16i8, V1Cst, V2Cst); 8878 Shuffle = DAG.getNode( 8879 ISD::INTRINSIC_WO_CHAIN, DL, IndexVT, 8880 DAG.getConstant(Intrinsic::aarch64_neon_tbl1, DL, MVT::i32), V1Cst, 8881 DAG.getBuildVector(IndexVT, DL, 8882 makeArrayRef(TBLMask.data(), IndexLen))); 8883 } else { 8884 // FIXME: We cannot, for the moment, emit a TBL2 instruction because we 8885 // cannot currently represent the register constraints on the input 8886 // table registers. 8887 // Shuffle = DAG.getNode(AArch64ISD::TBL2, DL, IndexVT, V1Cst, V2Cst, 8888 // DAG.getBuildVector(IndexVT, DL, &TBLMask[0], 8889 // IndexLen)); 8890 Shuffle = DAG.getNode( 8891 ISD::INTRINSIC_WO_CHAIN, DL, IndexVT, 8892 DAG.getConstant(Intrinsic::aarch64_neon_tbl2, DL, MVT::i32), V1Cst, 8893 V2Cst, DAG.getBuildVector(IndexVT, DL, 8894 makeArrayRef(TBLMask.data(), IndexLen))); 8895 } 8896 } 8897 return DAG.getNode(ISD::BITCAST, DL, Op.getValueType(), Shuffle); 8898 } 8899 8900 static unsigned getDUPLANEOp(EVT EltType) { 8901 if (EltType == MVT::i8) 8902 return AArch64ISD::DUPLANE8; 8903 if (EltType == MVT::i16 || EltType == MVT::f16 || EltType == MVT::bf16) 8904 return AArch64ISD::DUPLANE16; 8905 if (EltType == MVT::i32 || EltType == MVT::f32) 8906 return AArch64ISD::DUPLANE32; 8907 if (EltType == MVT::i64 || EltType == MVT::f64) 8908 return AArch64ISD::DUPLANE64; 8909 8910 llvm_unreachable("Invalid vector element type?"); 8911 } 8912 8913 static SDValue constructDup(SDValue V, int Lane, SDLoc dl, EVT VT, 8914 unsigned Opcode, SelectionDAG &DAG) { 8915 // Try to eliminate a bitcasted extract subvector before a DUPLANE. 8916 auto getScaledOffsetDup = [](SDValue BitCast, int &LaneC, MVT &CastVT) { 8917 // Match: dup (bitcast (extract_subv X, C)), LaneC 8918 if (BitCast.getOpcode() != ISD::BITCAST || 8919 BitCast.getOperand(0).getOpcode() != ISD::EXTRACT_SUBVECTOR) 8920 return false; 8921 8922 // The extract index must align in the destination type. That may not 8923 // happen if the bitcast is from narrow to wide type. 8924 SDValue Extract = BitCast.getOperand(0); 8925 unsigned ExtIdx = Extract.getConstantOperandVal(1); 8926 unsigned SrcEltBitWidth = Extract.getScalarValueSizeInBits(); 8927 unsigned ExtIdxInBits = ExtIdx * SrcEltBitWidth; 8928 unsigned CastedEltBitWidth = BitCast.getScalarValueSizeInBits(); 8929 if (ExtIdxInBits % CastedEltBitWidth != 0) 8930 return false; 8931 8932 // Update the lane value by offsetting with the scaled extract index. 8933 LaneC += ExtIdxInBits / CastedEltBitWidth; 8934 8935 // Determine the casted vector type of the wide vector input. 8936 // dup (bitcast (extract_subv X, C)), LaneC --> dup (bitcast X), LaneC' 8937 // Examples: 8938 // dup (bitcast (extract_subv v2f64 X, 1) to v2f32), 1 --> dup v4f32 X, 3 8939 // dup (bitcast (extract_subv v16i8 X, 8) to v4i16), 1 --> dup v8i16 X, 5 8940 unsigned SrcVecNumElts = 8941 Extract.getOperand(0).getValueSizeInBits() / CastedEltBitWidth; 8942 CastVT = MVT::getVectorVT(BitCast.getSimpleValueType().getScalarType(), 8943 SrcVecNumElts); 8944 return true; 8945 }; 8946 MVT CastVT; 8947 if (getScaledOffsetDup(V, Lane, CastVT)) { 8948 V = DAG.getBitcast(CastVT, V.getOperand(0).getOperand(0)); 8949 } else if (V.getOpcode() == ISD::EXTRACT_SUBVECTOR) { 8950 // The lane is incremented by the index of the extract. 8951 // Example: dup v2f32 (extract v4f32 X, 2), 1 --> dup v4f32 X, 3 8952 Lane += V.getConstantOperandVal(1); 8953 V = V.getOperand(0); 8954 } else if (V.getOpcode() == ISD::CONCAT_VECTORS) { 8955 // The lane is decremented if we are splatting from the 2nd operand. 8956 // Example: dup v4i32 (concat v2i32 X, v2i32 Y), 3 --> dup v4i32 Y, 1 8957 unsigned Idx = Lane >= (int)VT.getVectorNumElements() / 2; 8958 Lane -= Idx * VT.getVectorNumElements() / 2; 8959 V = WidenVector(V.getOperand(Idx), DAG); 8960 } else if (VT.getSizeInBits() == 64) { 8961 // Widen the operand to 128-bit register with undef. 8962 V = WidenVector(V, DAG); 8963 } 8964 return DAG.getNode(Opcode, dl, VT, V, DAG.getConstant(Lane, dl, MVT::i64)); 8965 } 8966 8967 SDValue AArch64TargetLowering::LowerVECTOR_SHUFFLE(SDValue Op, 8968 SelectionDAG &DAG) const { 8969 SDLoc dl(Op); 8970 EVT VT = Op.getValueType(); 8971 8972 ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(Op.getNode()); 8973 8974 // Convert shuffles that are directly supported on NEON to target-specific 8975 // DAG nodes, instead of keeping them as shuffles and matching them again 8976 // during code selection. This is more efficient and avoids the possibility 8977 // of inconsistencies between legalization and selection. 8978 ArrayRef<int> ShuffleMask = SVN->getMask(); 8979 8980 SDValue V1 = Op.getOperand(0); 8981 SDValue V2 = Op.getOperand(1); 8982 8983 if (SVN->isSplat()) { 8984 int Lane = SVN->getSplatIndex(); 8985 // If this is undef splat, generate it via "just" vdup, if possible. 8986 if (Lane == -1) 8987 Lane = 0; 8988 8989 if (Lane == 0 && V1.getOpcode() == ISD::SCALAR_TO_VECTOR) 8990 return DAG.getNode(AArch64ISD::DUP, dl, V1.getValueType(), 8991 V1.getOperand(0)); 8992 // Test if V1 is a BUILD_VECTOR and the lane being referenced is a non- 8993 // constant. If so, we can just reference the lane's definition directly. 8994 if (V1.getOpcode() == ISD::BUILD_VECTOR && 8995 !isa<ConstantSDNode>(V1.getOperand(Lane))) 8996 return DAG.getNode(AArch64ISD::DUP, dl, VT, V1.getOperand(Lane)); 8997 8998 // Otherwise, duplicate from the lane of the input vector. 8999 unsigned Opcode = getDUPLANEOp(V1.getValueType().getVectorElementType()); 9000 return constructDup(V1, Lane, dl, VT, Opcode, DAG); 9001 } 9002 9003 // Check if the mask matches a DUP for a wider element 9004 for (unsigned LaneSize : {64U, 32U, 16U}) { 9005 unsigned Lane = 0; 9006 if (isWideDUPMask(ShuffleMask, VT, LaneSize, Lane)) { 9007 unsigned Opcode = LaneSize == 64 ? AArch64ISD::DUPLANE64 9008 : LaneSize == 32 ? AArch64ISD::DUPLANE32 9009 : AArch64ISD::DUPLANE16; 9010 // Cast V1 to an integer vector with required lane size 9011 MVT NewEltTy = MVT::getIntegerVT(LaneSize); 9012 unsigned NewEltCount = VT.getSizeInBits() / LaneSize; 9013 MVT NewVecTy = MVT::getVectorVT(NewEltTy, NewEltCount); 9014 V1 = DAG.getBitcast(NewVecTy, V1); 9015 // Constuct the DUP instruction 9016 V1 = constructDup(V1, Lane, dl, NewVecTy, Opcode, DAG); 9017 // Cast back to the original type 9018 return DAG.getBitcast(VT, V1); 9019 } 9020 } 9021 9022 if (isREVMask(ShuffleMask, VT, 64)) 9023 return DAG.getNode(AArch64ISD::REV64, dl, V1.getValueType(), V1, V2); 9024 if (isREVMask(ShuffleMask, VT, 32)) 9025 return DAG.getNode(AArch64ISD::REV32, dl, V1.getValueType(), V1, V2); 9026 if (isREVMask(ShuffleMask, VT, 16)) 9027 return DAG.getNode(AArch64ISD::REV16, dl, V1.getValueType(), V1, V2); 9028 9029 bool ReverseEXT = false; 9030 unsigned Imm; 9031 if (isEXTMask(ShuffleMask, VT, ReverseEXT, Imm)) { 9032 if (ReverseEXT) 9033 std::swap(V1, V2); 9034 Imm *= getExtFactor(V1); 9035 return DAG.getNode(AArch64ISD::EXT, dl, V1.getValueType(), V1, V2, 9036 DAG.getConstant(Imm, dl, MVT::i32)); 9037 } else if (V2->isUndef() && isSingletonEXTMask(ShuffleMask, VT, Imm)) { 9038 Imm *= getExtFactor(V1); 9039 return DAG.getNode(AArch64ISD::EXT, dl, V1.getValueType(), V1, V1, 9040 DAG.getConstant(Imm, dl, MVT::i32)); 9041 } 9042 9043 unsigned WhichResult; 9044 if (isZIPMask(ShuffleMask, VT, WhichResult)) { 9045 unsigned Opc = (WhichResult == 0) ? AArch64ISD::ZIP1 : AArch64ISD::ZIP2; 9046 return DAG.getNode(Opc, dl, V1.getValueType(), V1, V2); 9047 } 9048 if (isUZPMask(ShuffleMask, VT, WhichResult)) { 9049 unsigned Opc = (WhichResult == 0) ? AArch64ISD::UZP1 : AArch64ISD::UZP2; 9050 return DAG.getNode(Opc, dl, V1.getValueType(), V1, V2); 9051 } 9052 if (isTRNMask(ShuffleMask, VT, WhichResult)) { 9053 unsigned Opc = (WhichResult == 0) ? AArch64ISD::TRN1 : AArch64ISD::TRN2; 9054 return DAG.getNode(Opc, dl, V1.getValueType(), V1, V2); 9055 } 9056 9057 if (isZIP_v_undef_Mask(ShuffleMask, VT, WhichResult)) { 9058 unsigned Opc = (WhichResult == 0) ? AArch64ISD::ZIP1 : AArch64ISD::ZIP2; 9059 return DAG.getNode(Opc, dl, V1.getValueType(), V1, V1); 9060 } 9061 if (isUZP_v_undef_Mask(ShuffleMask, VT, WhichResult)) { 9062 unsigned Opc = (WhichResult == 0) ? AArch64ISD::UZP1 : AArch64ISD::UZP2; 9063 return DAG.getNode(Opc, dl, V1.getValueType(), V1, V1); 9064 } 9065 if (isTRN_v_undef_Mask(ShuffleMask, VT, WhichResult)) { 9066 unsigned Opc = (WhichResult == 0) ? AArch64ISD::TRN1 : AArch64ISD::TRN2; 9067 return DAG.getNode(Opc, dl, V1.getValueType(), V1, V1); 9068 } 9069 9070 if (SDValue Concat = tryFormConcatFromShuffle(Op, DAG)) 9071 return Concat; 9072 9073 bool DstIsLeft; 9074 int Anomaly; 9075 int NumInputElements = V1.getValueType().getVectorNumElements(); 9076 if (isINSMask(ShuffleMask, NumInputElements, DstIsLeft, Anomaly)) { 9077 SDValue DstVec = DstIsLeft ? V1 : V2; 9078 SDValue DstLaneV = DAG.getConstant(Anomaly, dl, MVT::i64); 9079 9080 SDValue SrcVec = V1; 9081 int SrcLane = ShuffleMask[Anomaly]; 9082 if (SrcLane >= NumInputElements) { 9083 SrcVec = V2; 9084 SrcLane -= VT.getVectorNumElements(); 9085 } 9086 SDValue SrcLaneV = DAG.getConstant(SrcLane, dl, MVT::i64); 9087 9088 EVT ScalarVT = VT.getVectorElementType(); 9089 9090 if (ScalarVT.getFixedSizeInBits() < 32 && ScalarVT.isInteger()) 9091 ScalarVT = MVT::i32; 9092 9093 return DAG.getNode( 9094 ISD::INSERT_VECTOR_ELT, dl, VT, DstVec, 9095 DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, ScalarVT, SrcVec, SrcLaneV), 9096 DstLaneV); 9097 } 9098 9099 // If the shuffle is not directly supported and it has 4 elements, use 9100 // the PerfectShuffle-generated table to synthesize it from other shuffles. 9101 unsigned NumElts = VT.getVectorNumElements(); 9102 if (NumElts == 4) { 9103 unsigned PFIndexes[4]; 9104 for (unsigned i = 0; i != 4; ++i) { 9105 if (ShuffleMask[i] < 0) 9106 PFIndexes[i] = 8; 9107 else 9108 PFIndexes[i] = ShuffleMask[i]; 9109 } 9110 9111 // Compute the index in the perfect shuffle table. 9112 unsigned PFTableIndex = PFIndexes[0] * 9 * 9 * 9 + PFIndexes[1] * 9 * 9 + 9113 PFIndexes[2] * 9 + PFIndexes[3]; 9114 unsigned PFEntry = PerfectShuffleTable[PFTableIndex]; 9115 unsigned Cost = (PFEntry >> 30); 9116 9117 if (Cost <= 4) 9118 return GeneratePerfectShuffle(PFEntry, V1, V2, DAG, dl); 9119 } 9120 9121 return GenerateTBL(Op, ShuffleMask, DAG); 9122 } 9123 9124 SDValue AArch64TargetLowering::LowerSTEP_VECTOR(SDValue Op, 9125 SelectionDAG &DAG) const { 9126 SDLoc dl(Op); 9127 EVT VT = Op.getValueType(); 9128 assert(VT.isScalableVector() && 9129 "Only expect scalable vectors for STEP_VECTOR"); 9130 assert(VT.getScalarType() != MVT::i1 && 9131 "Vectors of i1 types not supported for STEP_VECTOR"); 9132 9133 SDValue StepVal = Op.getOperand(0); 9134 SDValue Zero = DAG.getConstant(0, dl, StepVal.getValueType()); 9135 return DAG.getNode(AArch64ISD::INDEX_VECTOR, dl, VT, Zero, StepVal); 9136 } 9137 9138 SDValue AArch64TargetLowering::LowerSPLAT_VECTOR(SDValue Op, 9139 SelectionDAG &DAG) const { 9140 SDLoc dl(Op); 9141 EVT VT = Op.getValueType(); 9142 EVT ElemVT = VT.getScalarType(); 9143 SDValue SplatVal = Op.getOperand(0); 9144 9145 if (useSVEForFixedLengthVectorVT(VT)) 9146 return LowerToScalableOp(Op, DAG); 9147 9148 // Extend input splat value where needed to fit into a GPR (32b or 64b only) 9149 // FPRs don't have this restriction. 9150 switch (ElemVT.getSimpleVT().SimpleTy) { 9151 case MVT::i1: { 9152 // The only legal i1 vectors are SVE vectors, so we can use SVE-specific 9153 // lowering code. 9154 if (auto *ConstVal = dyn_cast<ConstantSDNode>(SplatVal)) { 9155 if (ConstVal->isOne()) 9156 return getPTrue(DAG, dl, VT, AArch64SVEPredPattern::all); 9157 // TODO: Add special case for constant false 9158 } 9159 // The general case of i1. There isn't any natural way to do this, 9160 // so we use some trickery with whilelo. 9161 SplatVal = DAG.getAnyExtOrTrunc(SplatVal, dl, MVT::i64); 9162 SplatVal = DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, MVT::i64, SplatVal, 9163 DAG.getValueType(MVT::i1)); 9164 SDValue ID = DAG.getTargetConstant(Intrinsic::aarch64_sve_whilelo, dl, 9165 MVT::i64); 9166 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT, ID, 9167 DAG.getConstant(0, dl, MVT::i64), SplatVal); 9168 } 9169 case MVT::i8: 9170 case MVT::i16: 9171 case MVT::i32: 9172 SplatVal = DAG.getAnyExtOrTrunc(SplatVal, dl, MVT::i32); 9173 break; 9174 case MVT::i64: 9175 SplatVal = DAG.getAnyExtOrTrunc(SplatVal, dl, MVT::i64); 9176 break; 9177 case MVT::f16: 9178 case MVT::bf16: 9179 case MVT::f32: 9180 case MVT::f64: 9181 // Fine as is 9182 break; 9183 default: 9184 report_fatal_error("Unsupported SPLAT_VECTOR input operand type"); 9185 } 9186 9187 return DAG.getNode(AArch64ISD::DUP, dl, VT, SplatVal); 9188 } 9189 9190 SDValue AArch64TargetLowering::LowerDUPQLane(SDValue Op, 9191 SelectionDAG &DAG) const { 9192 SDLoc DL(Op); 9193 9194 EVT VT = Op.getValueType(); 9195 if (!isTypeLegal(VT) || !VT.isScalableVector()) 9196 return SDValue(); 9197 9198 // Current lowering only supports the SVE-ACLE types. 9199 if (VT.getSizeInBits().getKnownMinSize() != AArch64::SVEBitsPerBlock) 9200 return SDValue(); 9201 9202 // The DUPQ operation is indepedent of element type so normalise to i64s. 9203 SDValue V = DAG.getNode(ISD::BITCAST, DL, MVT::nxv2i64, Op.getOperand(1)); 9204 SDValue Idx128 = Op.getOperand(2); 9205 9206 // DUPQ can be used when idx is in range. 9207 auto *CIdx = dyn_cast<ConstantSDNode>(Idx128); 9208 if (CIdx && (CIdx->getZExtValue() <= 3)) { 9209 SDValue CI = DAG.getTargetConstant(CIdx->getZExtValue(), DL, MVT::i64); 9210 SDNode *DUPQ = 9211 DAG.getMachineNode(AArch64::DUP_ZZI_Q, DL, MVT::nxv2i64, V, CI); 9212 return DAG.getNode(ISD::BITCAST, DL, VT, SDValue(DUPQ, 0)); 9213 } 9214 9215 // The ACLE says this must produce the same result as: 9216 // svtbl(data, svadd_x(svptrue_b64(), 9217 // svand_x(svptrue_b64(), svindex_u64(0, 1), 1), 9218 // index * 2)) 9219 SDValue One = DAG.getConstant(1, DL, MVT::i64); 9220 SDValue SplatOne = DAG.getNode(ISD::SPLAT_VECTOR, DL, MVT::nxv2i64, One); 9221 9222 // create the vector 0,1,0,1,... 9223 SDValue Zero = DAG.getConstant(0, DL, MVT::i64); 9224 SDValue SV = DAG.getNode(AArch64ISD::INDEX_VECTOR, 9225 DL, MVT::nxv2i64, Zero, One); 9226 SV = DAG.getNode(ISD::AND, DL, MVT::nxv2i64, SV, SplatOne); 9227 9228 // create the vector idx64,idx64+1,idx64,idx64+1,... 9229 SDValue Idx64 = DAG.getNode(ISD::ADD, DL, MVT::i64, Idx128, Idx128); 9230 SDValue SplatIdx64 = DAG.getNode(ISD::SPLAT_VECTOR, DL, MVT::nxv2i64, Idx64); 9231 SDValue ShuffleMask = DAG.getNode(ISD::ADD, DL, MVT::nxv2i64, SV, SplatIdx64); 9232 9233 // create the vector Val[idx64],Val[idx64+1],Val[idx64],Val[idx64+1],... 9234 SDValue TBL = DAG.getNode(AArch64ISD::TBL, DL, MVT::nxv2i64, V, ShuffleMask); 9235 return DAG.getNode(ISD::BITCAST, DL, VT, TBL); 9236 } 9237 9238 9239 static bool resolveBuildVector(BuildVectorSDNode *BVN, APInt &CnstBits, 9240 APInt &UndefBits) { 9241 EVT VT = BVN->getValueType(0); 9242 APInt SplatBits, SplatUndef; 9243 unsigned SplatBitSize; 9244 bool HasAnyUndefs; 9245 if (BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs)) { 9246 unsigned NumSplats = VT.getSizeInBits() / SplatBitSize; 9247 9248 for (unsigned i = 0; i < NumSplats; ++i) { 9249 CnstBits <<= SplatBitSize; 9250 UndefBits <<= SplatBitSize; 9251 CnstBits |= SplatBits.zextOrTrunc(VT.getSizeInBits()); 9252 UndefBits |= (SplatBits ^ SplatUndef).zextOrTrunc(VT.getSizeInBits()); 9253 } 9254 9255 return true; 9256 } 9257 9258 return false; 9259 } 9260 9261 // Try 64-bit splatted SIMD immediate. 9262 static SDValue tryAdvSIMDModImm64(unsigned NewOp, SDValue Op, SelectionDAG &DAG, 9263 const APInt &Bits) { 9264 if (Bits.getHiBits(64) == Bits.getLoBits(64)) { 9265 uint64_t Value = Bits.zextOrTrunc(64).getZExtValue(); 9266 EVT VT = Op.getValueType(); 9267 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v2i64 : MVT::f64; 9268 9269 if (AArch64_AM::isAdvSIMDModImmType10(Value)) { 9270 Value = AArch64_AM::encodeAdvSIMDModImmType10(Value); 9271 9272 SDLoc dl(Op); 9273 SDValue Mov = DAG.getNode(NewOp, dl, MovTy, 9274 DAG.getConstant(Value, dl, MVT::i32)); 9275 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov); 9276 } 9277 } 9278 9279 return SDValue(); 9280 } 9281 9282 // Try 32-bit splatted SIMD immediate. 9283 static SDValue tryAdvSIMDModImm32(unsigned NewOp, SDValue Op, SelectionDAG &DAG, 9284 const APInt &Bits, 9285 const SDValue *LHS = nullptr) { 9286 if (Bits.getHiBits(64) == Bits.getLoBits(64)) { 9287 uint64_t Value = Bits.zextOrTrunc(64).getZExtValue(); 9288 EVT VT = Op.getValueType(); 9289 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32; 9290 bool isAdvSIMDModImm = false; 9291 uint64_t Shift; 9292 9293 if ((isAdvSIMDModImm = AArch64_AM::isAdvSIMDModImmType1(Value))) { 9294 Value = AArch64_AM::encodeAdvSIMDModImmType1(Value); 9295 Shift = 0; 9296 } 9297 else if ((isAdvSIMDModImm = AArch64_AM::isAdvSIMDModImmType2(Value))) { 9298 Value = AArch64_AM::encodeAdvSIMDModImmType2(Value); 9299 Shift = 8; 9300 } 9301 else if ((isAdvSIMDModImm = AArch64_AM::isAdvSIMDModImmType3(Value))) { 9302 Value = AArch64_AM::encodeAdvSIMDModImmType3(Value); 9303 Shift = 16; 9304 } 9305 else if ((isAdvSIMDModImm = AArch64_AM::isAdvSIMDModImmType4(Value))) { 9306 Value = AArch64_AM::encodeAdvSIMDModImmType4(Value); 9307 Shift = 24; 9308 } 9309 9310 if (isAdvSIMDModImm) { 9311 SDLoc dl(Op); 9312 SDValue Mov; 9313 9314 if (LHS) 9315 Mov = DAG.getNode(NewOp, dl, MovTy, *LHS, 9316 DAG.getConstant(Value, dl, MVT::i32), 9317 DAG.getConstant(Shift, dl, MVT::i32)); 9318 else 9319 Mov = DAG.getNode(NewOp, dl, MovTy, 9320 DAG.getConstant(Value, dl, MVT::i32), 9321 DAG.getConstant(Shift, dl, MVT::i32)); 9322 9323 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov); 9324 } 9325 } 9326 9327 return SDValue(); 9328 } 9329 9330 // Try 16-bit splatted SIMD immediate. 9331 static SDValue tryAdvSIMDModImm16(unsigned NewOp, SDValue Op, SelectionDAG &DAG, 9332 const APInt &Bits, 9333 const SDValue *LHS = nullptr) { 9334 if (Bits.getHiBits(64) == Bits.getLoBits(64)) { 9335 uint64_t Value = Bits.zextOrTrunc(64).getZExtValue(); 9336 EVT VT = Op.getValueType(); 9337 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v8i16 : MVT::v4i16; 9338 bool isAdvSIMDModImm = false; 9339 uint64_t Shift; 9340 9341 if ((isAdvSIMDModImm = AArch64_AM::isAdvSIMDModImmType5(Value))) { 9342 Value = AArch64_AM::encodeAdvSIMDModImmType5(Value); 9343 Shift = 0; 9344 } 9345 else if ((isAdvSIMDModImm = AArch64_AM::isAdvSIMDModImmType6(Value))) { 9346 Value = AArch64_AM::encodeAdvSIMDModImmType6(Value); 9347 Shift = 8; 9348 } 9349 9350 if (isAdvSIMDModImm) { 9351 SDLoc dl(Op); 9352 SDValue Mov; 9353 9354 if (LHS) 9355 Mov = DAG.getNode(NewOp, dl, MovTy, *LHS, 9356 DAG.getConstant(Value, dl, MVT::i32), 9357 DAG.getConstant(Shift, dl, MVT::i32)); 9358 else 9359 Mov = DAG.getNode(NewOp, dl, MovTy, 9360 DAG.getConstant(Value, dl, MVT::i32), 9361 DAG.getConstant(Shift, dl, MVT::i32)); 9362 9363 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov); 9364 } 9365 } 9366 9367 return SDValue(); 9368 } 9369 9370 // Try 32-bit splatted SIMD immediate with shifted ones. 9371 static SDValue tryAdvSIMDModImm321s(unsigned NewOp, SDValue Op, 9372 SelectionDAG &DAG, const APInt &Bits) { 9373 if (Bits.getHiBits(64) == Bits.getLoBits(64)) { 9374 uint64_t Value = Bits.zextOrTrunc(64).getZExtValue(); 9375 EVT VT = Op.getValueType(); 9376 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32; 9377 bool isAdvSIMDModImm = false; 9378 uint64_t Shift; 9379 9380 if ((isAdvSIMDModImm = AArch64_AM::isAdvSIMDModImmType7(Value))) { 9381 Value = AArch64_AM::encodeAdvSIMDModImmType7(Value); 9382 Shift = 264; 9383 } 9384 else if ((isAdvSIMDModImm = AArch64_AM::isAdvSIMDModImmType8(Value))) { 9385 Value = AArch64_AM::encodeAdvSIMDModImmType8(Value); 9386 Shift = 272; 9387 } 9388 9389 if (isAdvSIMDModImm) { 9390 SDLoc dl(Op); 9391 SDValue Mov = DAG.getNode(NewOp, dl, MovTy, 9392 DAG.getConstant(Value, dl, MVT::i32), 9393 DAG.getConstant(Shift, dl, MVT::i32)); 9394 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov); 9395 } 9396 } 9397 9398 return SDValue(); 9399 } 9400 9401 // Try 8-bit splatted SIMD immediate. 9402 static SDValue tryAdvSIMDModImm8(unsigned NewOp, SDValue Op, SelectionDAG &DAG, 9403 const APInt &Bits) { 9404 if (Bits.getHiBits(64) == Bits.getLoBits(64)) { 9405 uint64_t Value = Bits.zextOrTrunc(64).getZExtValue(); 9406 EVT VT = Op.getValueType(); 9407 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v16i8 : MVT::v8i8; 9408 9409 if (AArch64_AM::isAdvSIMDModImmType9(Value)) { 9410 Value = AArch64_AM::encodeAdvSIMDModImmType9(Value); 9411 9412 SDLoc dl(Op); 9413 SDValue Mov = DAG.getNode(NewOp, dl, MovTy, 9414 DAG.getConstant(Value, dl, MVT::i32)); 9415 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov); 9416 } 9417 } 9418 9419 return SDValue(); 9420 } 9421 9422 // Try FP splatted SIMD immediate. 9423 static SDValue tryAdvSIMDModImmFP(unsigned NewOp, SDValue Op, SelectionDAG &DAG, 9424 const APInt &Bits) { 9425 if (Bits.getHiBits(64) == Bits.getLoBits(64)) { 9426 uint64_t Value = Bits.zextOrTrunc(64).getZExtValue(); 9427 EVT VT = Op.getValueType(); 9428 bool isWide = (VT.getSizeInBits() == 128); 9429 MVT MovTy; 9430 bool isAdvSIMDModImm = false; 9431 9432 if ((isAdvSIMDModImm = AArch64_AM::isAdvSIMDModImmType11(Value))) { 9433 Value = AArch64_AM::encodeAdvSIMDModImmType11(Value); 9434 MovTy = isWide ? MVT::v4f32 : MVT::v2f32; 9435 } 9436 else if (isWide && 9437 (isAdvSIMDModImm = AArch64_AM::isAdvSIMDModImmType12(Value))) { 9438 Value = AArch64_AM::encodeAdvSIMDModImmType12(Value); 9439 MovTy = MVT::v2f64; 9440 } 9441 9442 if (isAdvSIMDModImm) { 9443 SDLoc dl(Op); 9444 SDValue Mov = DAG.getNode(NewOp, dl, MovTy, 9445 DAG.getConstant(Value, dl, MVT::i32)); 9446 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov); 9447 } 9448 } 9449 9450 return SDValue(); 9451 } 9452 9453 // Specialized code to quickly find if PotentialBVec is a BuildVector that 9454 // consists of only the same constant int value, returned in reference arg 9455 // ConstVal 9456 static bool isAllConstantBuildVector(const SDValue &PotentialBVec, 9457 uint64_t &ConstVal) { 9458 BuildVectorSDNode *Bvec = dyn_cast<BuildVectorSDNode>(PotentialBVec); 9459 if (!Bvec) 9460 return false; 9461 ConstantSDNode *FirstElt = dyn_cast<ConstantSDNode>(Bvec->getOperand(0)); 9462 if (!FirstElt) 9463 return false; 9464 EVT VT = Bvec->getValueType(0); 9465 unsigned NumElts = VT.getVectorNumElements(); 9466 for (unsigned i = 1; i < NumElts; ++i) 9467 if (dyn_cast<ConstantSDNode>(Bvec->getOperand(i)) != FirstElt) 9468 return false; 9469 ConstVal = FirstElt->getZExtValue(); 9470 return true; 9471 } 9472 9473 static unsigned getIntrinsicID(const SDNode *N) { 9474 unsigned Opcode = N->getOpcode(); 9475 switch (Opcode) { 9476 default: 9477 return Intrinsic::not_intrinsic; 9478 case ISD::INTRINSIC_WO_CHAIN: { 9479 unsigned IID = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue(); 9480 if (IID < Intrinsic::num_intrinsics) 9481 return IID; 9482 return Intrinsic::not_intrinsic; 9483 } 9484 } 9485 } 9486 9487 // Attempt to form a vector S[LR]I from (or (and X, BvecC1), (lsl Y, C2)), 9488 // to (SLI X, Y, C2), where X and Y have matching vector types, BvecC1 is a 9489 // BUILD_VECTORs with constant element C1, C2 is a constant, and: 9490 // - for the SLI case: C1 == ~(Ones(ElemSizeInBits) << C2) 9491 // - for the SRI case: C1 == ~(Ones(ElemSizeInBits) >> C2) 9492 // The (or (lsl Y, C2), (and X, BvecC1)) case is also handled. 9493 static SDValue tryLowerToSLI(SDNode *N, SelectionDAG &DAG) { 9494 EVT VT = N->getValueType(0); 9495 9496 if (!VT.isVector()) 9497 return SDValue(); 9498 9499 SDLoc DL(N); 9500 9501 SDValue And; 9502 SDValue Shift; 9503 9504 SDValue FirstOp = N->getOperand(0); 9505 unsigned FirstOpc = FirstOp.getOpcode(); 9506 SDValue SecondOp = N->getOperand(1); 9507 unsigned SecondOpc = SecondOp.getOpcode(); 9508 9509 // Is one of the operands an AND or a BICi? The AND may have been optimised to 9510 // a BICi in order to use an immediate instead of a register. 9511 // Is the other operand an shl or lshr? This will have been turned into: 9512 // AArch64ISD::VSHL vector, #shift or AArch64ISD::VLSHR vector, #shift. 9513 if ((FirstOpc == ISD::AND || FirstOpc == AArch64ISD::BICi) && 9514 (SecondOpc == AArch64ISD::VSHL || SecondOpc == AArch64ISD::VLSHR)) { 9515 And = FirstOp; 9516 Shift = SecondOp; 9517 9518 } else if ((SecondOpc == ISD::AND || SecondOpc == AArch64ISD::BICi) && 9519 (FirstOpc == AArch64ISD::VSHL || FirstOpc == AArch64ISD::VLSHR)) { 9520 And = SecondOp; 9521 Shift = FirstOp; 9522 } else 9523 return SDValue(); 9524 9525 bool IsAnd = And.getOpcode() == ISD::AND; 9526 bool IsShiftRight = Shift.getOpcode() == AArch64ISD::VLSHR; 9527 9528 // Is the shift amount constant? 9529 ConstantSDNode *C2node = dyn_cast<ConstantSDNode>(Shift.getOperand(1)); 9530 if (!C2node) 9531 return SDValue(); 9532 9533 uint64_t C1; 9534 if (IsAnd) { 9535 // Is the and mask vector all constant? 9536 if (!isAllConstantBuildVector(And.getOperand(1), C1)) 9537 return SDValue(); 9538 } else { 9539 // Reconstruct the corresponding AND immediate from the two BICi immediates. 9540 ConstantSDNode *C1nodeImm = dyn_cast<ConstantSDNode>(And.getOperand(1)); 9541 ConstantSDNode *C1nodeShift = dyn_cast<ConstantSDNode>(And.getOperand(2)); 9542 assert(C1nodeImm && C1nodeShift); 9543 C1 = ~(C1nodeImm->getZExtValue() << C1nodeShift->getZExtValue()); 9544 } 9545 9546 // Is C1 == ~(Ones(ElemSizeInBits) << C2) or 9547 // C1 == ~(Ones(ElemSizeInBits) >> C2), taking into account 9548 // how much one can shift elements of a particular size? 9549 uint64_t C2 = C2node->getZExtValue(); 9550 unsigned ElemSizeInBits = VT.getScalarSizeInBits(); 9551 if (C2 > ElemSizeInBits) 9552 return SDValue(); 9553 9554 APInt C1AsAPInt(ElemSizeInBits, C1); 9555 APInt RequiredC1 = IsShiftRight ? APInt::getHighBitsSet(ElemSizeInBits, C2) 9556 : APInt::getLowBitsSet(ElemSizeInBits, C2); 9557 if (C1AsAPInt != RequiredC1) 9558 return SDValue(); 9559 9560 SDValue X = And.getOperand(0); 9561 SDValue Y = Shift.getOperand(0); 9562 9563 unsigned Inst = IsShiftRight ? AArch64ISD::VSRI : AArch64ISD::VSLI; 9564 SDValue ResultSLI = DAG.getNode(Inst, DL, VT, X, Y, Shift.getOperand(1)); 9565 9566 LLVM_DEBUG(dbgs() << "aarch64-lower: transformed: \n"); 9567 LLVM_DEBUG(N->dump(&DAG)); 9568 LLVM_DEBUG(dbgs() << "into: \n"); 9569 LLVM_DEBUG(ResultSLI->dump(&DAG)); 9570 9571 ++NumShiftInserts; 9572 return ResultSLI; 9573 } 9574 9575 SDValue AArch64TargetLowering::LowerVectorOR(SDValue Op, 9576 SelectionDAG &DAG) const { 9577 if (useSVEForFixedLengthVectorVT(Op.getValueType())) 9578 return LowerToScalableOp(Op, DAG); 9579 9580 // Attempt to form a vector S[LR]I from (or (and X, C1), (lsl Y, C2)) 9581 if (SDValue Res = tryLowerToSLI(Op.getNode(), DAG)) 9582 return Res; 9583 9584 EVT VT = Op.getValueType(); 9585 9586 SDValue LHS = Op.getOperand(0); 9587 BuildVectorSDNode *BVN = 9588 dyn_cast<BuildVectorSDNode>(Op.getOperand(1).getNode()); 9589 if (!BVN) { 9590 // OR commutes, so try swapping the operands. 9591 LHS = Op.getOperand(1); 9592 BVN = dyn_cast<BuildVectorSDNode>(Op.getOperand(0).getNode()); 9593 } 9594 if (!BVN) 9595 return Op; 9596 9597 APInt DefBits(VT.getSizeInBits(), 0); 9598 APInt UndefBits(VT.getSizeInBits(), 0); 9599 if (resolveBuildVector(BVN, DefBits, UndefBits)) { 9600 SDValue NewOp; 9601 9602 if ((NewOp = tryAdvSIMDModImm32(AArch64ISD::ORRi, Op, DAG, 9603 DefBits, &LHS)) || 9604 (NewOp = tryAdvSIMDModImm16(AArch64ISD::ORRi, Op, DAG, 9605 DefBits, &LHS))) 9606 return NewOp; 9607 9608 if ((NewOp = tryAdvSIMDModImm32(AArch64ISD::ORRi, Op, DAG, 9609 UndefBits, &LHS)) || 9610 (NewOp = tryAdvSIMDModImm16(AArch64ISD::ORRi, Op, DAG, 9611 UndefBits, &LHS))) 9612 return NewOp; 9613 } 9614 9615 // We can always fall back to a non-immediate OR. 9616 return Op; 9617 } 9618 9619 // Normalize the operands of BUILD_VECTOR. The value of constant operands will 9620 // be truncated to fit element width. 9621 static SDValue NormalizeBuildVector(SDValue Op, 9622 SelectionDAG &DAG) { 9623 assert(Op.getOpcode() == ISD::BUILD_VECTOR && "Unknown opcode!"); 9624 SDLoc dl(Op); 9625 EVT VT = Op.getValueType(); 9626 EVT EltTy= VT.getVectorElementType(); 9627 9628 if (EltTy.isFloatingPoint() || EltTy.getSizeInBits() > 16) 9629 return Op; 9630 9631 SmallVector<SDValue, 16> Ops; 9632 for (SDValue Lane : Op->ops()) { 9633 // For integer vectors, type legalization would have promoted the 9634 // operands already. Otherwise, if Op is a floating-point splat 9635 // (with operands cast to integers), then the only possibilities 9636 // are constants and UNDEFs. 9637 if (auto *CstLane = dyn_cast<ConstantSDNode>(Lane)) { 9638 APInt LowBits(EltTy.getSizeInBits(), 9639 CstLane->getZExtValue()); 9640 Lane = DAG.getConstant(LowBits.getZExtValue(), dl, MVT::i32); 9641 } else if (Lane.getNode()->isUndef()) { 9642 Lane = DAG.getUNDEF(MVT::i32); 9643 } else { 9644 assert(Lane.getValueType() == MVT::i32 && 9645 "Unexpected BUILD_VECTOR operand type"); 9646 } 9647 Ops.push_back(Lane); 9648 } 9649 return DAG.getBuildVector(VT, dl, Ops); 9650 } 9651 9652 static SDValue ConstantBuildVector(SDValue Op, SelectionDAG &DAG) { 9653 EVT VT = Op.getValueType(); 9654 9655 APInt DefBits(VT.getSizeInBits(), 0); 9656 APInt UndefBits(VT.getSizeInBits(), 0); 9657 BuildVectorSDNode *BVN = cast<BuildVectorSDNode>(Op.getNode()); 9658 if (resolveBuildVector(BVN, DefBits, UndefBits)) { 9659 SDValue NewOp; 9660 if ((NewOp = tryAdvSIMDModImm64(AArch64ISD::MOVIedit, Op, DAG, DefBits)) || 9661 (NewOp = tryAdvSIMDModImm32(AArch64ISD::MOVIshift, Op, DAG, DefBits)) || 9662 (NewOp = tryAdvSIMDModImm321s(AArch64ISD::MOVImsl, Op, DAG, DefBits)) || 9663 (NewOp = tryAdvSIMDModImm16(AArch64ISD::MOVIshift, Op, DAG, DefBits)) || 9664 (NewOp = tryAdvSIMDModImm8(AArch64ISD::MOVI, Op, DAG, DefBits)) || 9665 (NewOp = tryAdvSIMDModImmFP(AArch64ISD::FMOV, Op, DAG, DefBits))) 9666 return NewOp; 9667 9668 DefBits = ~DefBits; 9669 if ((NewOp = tryAdvSIMDModImm32(AArch64ISD::MVNIshift, Op, DAG, DefBits)) || 9670 (NewOp = tryAdvSIMDModImm321s(AArch64ISD::MVNImsl, Op, DAG, DefBits)) || 9671 (NewOp = tryAdvSIMDModImm16(AArch64ISD::MVNIshift, Op, DAG, DefBits))) 9672 return NewOp; 9673 9674 DefBits = UndefBits; 9675 if ((NewOp = tryAdvSIMDModImm64(AArch64ISD::MOVIedit, Op, DAG, DefBits)) || 9676 (NewOp = tryAdvSIMDModImm32(AArch64ISD::MOVIshift, Op, DAG, DefBits)) || 9677 (NewOp = tryAdvSIMDModImm321s(AArch64ISD::MOVImsl, Op, DAG, DefBits)) || 9678 (NewOp = tryAdvSIMDModImm16(AArch64ISD::MOVIshift, Op, DAG, DefBits)) || 9679 (NewOp = tryAdvSIMDModImm8(AArch64ISD::MOVI, Op, DAG, DefBits)) || 9680 (NewOp = tryAdvSIMDModImmFP(AArch64ISD::FMOV, Op, DAG, DefBits))) 9681 return NewOp; 9682 9683 DefBits = ~UndefBits; 9684 if ((NewOp = tryAdvSIMDModImm32(AArch64ISD::MVNIshift, Op, DAG, DefBits)) || 9685 (NewOp = tryAdvSIMDModImm321s(AArch64ISD::MVNImsl, Op, DAG, DefBits)) || 9686 (NewOp = tryAdvSIMDModImm16(AArch64ISD::MVNIshift, Op, DAG, DefBits))) 9687 return NewOp; 9688 } 9689 9690 return SDValue(); 9691 } 9692 9693 SDValue AArch64TargetLowering::LowerBUILD_VECTOR(SDValue Op, 9694 SelectionDAG &DAG) const { 9695 EVT VT = Op.getValueType(); 9696 9697 // Try to build a simple constant vector. 9698 Op = NormalizeBuildVector(Op, DAG); 9699 if (VT.isInteger()) { 9700 // Certain vector constants, used to express things like logical NOT and 9701 // arithmetic NEG, are passed through unmodified. This allows special 9702 // patterns for these operations to match, which will lower these constants 9703 // to whatever is proven necessary. 9704 BuildVectorSDNode *BVN = cast<BuildVectorSDNode>(Op.getNode()); 9705 if (BVN->isConstant()) 9706 if (ConstantSDNode *Const = BVN->getConstantSplatNode()) { 9707 unsigned BitSize = VT.getVectorElementType().getSizeInBits(); 9708 APInt Val(BitSize, 9709 Const->getAPIntValue().zextOrTrunc(BitSize).getZExtValue()); 9710 if (Val.isNullValue() || Val.isAllOnesValue()) 9711 return Op; 9712 } 9713 } 9714 9715 if (SDValue V = ConstantBuildVector(Op, DAG)) 9716 return V; 9717 9718 // Scan through the operands to find some interesting properties we can 9719 // exploit: 9720 // 1) If only one value is used, we can use a DUP, or 9721 // 2) if only the low element is not undef, we can just insert that, or 9722 // 3) if only one constant value is used (w/ some non-constant lanes), 9723 // we can splat the constant value into the whole vector then fill 9724 // in the non-constant lanes. 9725 // 4) FIXME: If different constant values are used, but we can intelligently 9726 // select the values we'll be overwriting for the non-constant 9727 // lanes such that we can directly materialize the vector 9728 // some other way (MOVI, e.g.), we can be sneaky. 9729 // 5) if all operands are EXTRACT_VECTOR_ELT, check for VUZP. 9730 SDLoc dl(Op); 9731 unsigned NumElts = VT.getVectorNumElements(); 9732 bool isOnlyLowElement = true; 9733 bool usesOnlyOneValue = true; 9734 bool usesOnlyOneConstantValue = true; 9735 bool isConstant = true; 9736 bool AllLanesExtractElt = true; 9737 unsigned NumConstantLanes = 0; 9738 unsigned NumDifferentLanes = 0; 9739 unsigned NumUndefLanes = 0; 9740 SDValue Value; 9741 SDValue ConstantValue; 9742 for (unsigned i = 0; i < NumElts; ++i) { 9743 SDValue V = Op.getOperand(i); 9744 if (V.getOpcode() != ISD::EXTRACT_VECTOR_ELT) 9745 AllLanesExtractElt = false; 9746 if (V.isUndef()) { 9747 ++NumUndefLanes; 9748 continue; 9749 } 9750 if (i > 0) 9751 isOnlyLowElement = false; 9752 if (!isIntOrFPConstant(V)) 9753 isConstant = false; 9754 9755 if (isIntOrFPConstant(V)) { 9756 ++NumConstantLanes; 9757 if (!ConstantValue.getNode()) 9758 ConstantValue = V; 9759 else if (ConstantValue != V) 9760 usesOnlyOneConstantValue = false; 9761 } 9762 9763 if (!Value.getNode()) 9764 Value = V; 9765 else if (V != Value) { 9766 usesOnlyOneValue = false; 9767 ++NumDifferentLanes; 9768 } 9769 } 9770 9771 if (!Value.getNode()) { 9772 LLVM_DEBUG( 9773 dbgs() << "LowerBUILD_VECTOR: value undefined, creating undef node\n"); 9774 return DAG.getUNDEF(VT); 9775 } 9776 9777 // Convert BUILD_VECTOR where all elements but the lowest are undef into 9778 // SCALAR_TO_VECTOR, except for when we have a single-element constant vector 9779 // as SimplifyDemandedBits will just turn that back into BUILD_VECTOR. 9780 if (isOnlyLowElement && !(NumElts == 1 && isIntOrFPConstant(Value))) { 9781 LLVM_DEBUG(dbgs() << "LowerBUILD_VECTOR: only low element used, creating 1 " 9782 "SCALAR_TO_VECTOR node\n"); 9783 return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Value); 9784 } 9785 9786 if (AllLanesExtractElt) { 9787 SDNode *Vector = nullptr; 9788 bool Even = false; 9789 bool Odd = false; 9790 // Check whether the extract elements match the Even pattern <0,2,4,...> or 9791 // the Odd pattern <1,3,5,...>. 9792 for (unsigned i = 0; i < NumElts; ++i) { 9793 SDValue V = Op.getOperand(i); 9794 const SDNode *N = V.getNode(); 9795 if (!isa<ConstantSDNode>(N->getOperand(1))) 9796 break; 9797 SDValue N0 = N->getOperand(0); 9798 9799 // All elements are extracted from the same vector. 9800 if (!Vector) { 9801 Vector = N0.getNode(); 9802 // Check that the type of EXTRACT_VECTOR_ELT matches the type of 9803 // BUILD_VECTOR. 9804 if (VT.getVectorElementType() != 9805 N0.getValueType().getVectorElementType()) 9806 break; 9807 } else if (Vector != N0.getNode()) { 9808 Odd = false; 9809 Even = false; 9810 break; 9811 } 9812 9813 // Extracted values are either at Even indices <0,2,4,...> or at Odd 9814 // indices <1,3,5,...>. 9815 uint64_t Val = N->getConstantOperandVal(1); 9816 if (Val == 2 * i) { 9817 Even = true; 9818 continue; 9819 } 9820 if (Val - 1 == 2 * i) { 9821 Odd = true; 9822 continue; 9823 } 9824 9825 // Something does not match: abort. 9826 Odd = false; 9827 Even = false; 9828 break; 9829 } 9830 if (Even || Odd) { 9831 SDValue LHS = 9832 DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT, SDValue(Vector, 0), 9833 DAG.getConstant(0, dl, MVT::i64)); 9834 SDValue RHS = 9835 DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT, SDValue(Vector, 0), 9836 DAG.getConstant(NumElts, dl, MVT::i64)); 9837 9838 if (Even && !Odd) 9839 return DAG.getNode(AArch64ISD::UZP1, dl, DAG.getVTList(VT, VT), LHS, 9840 RHS); 9841 if (Odd && !Even) 9842 return DAG.getNode(AArch64ISD::UZP2, dl, DAG.getVTList(VT, VT), LHS, 9843 RHS); 9844 } 9845 } 9846 9847 // Use DUP for non-constant splats. For f32 constant splats, reduce to 9848 // i32 and try again. 9849 if (usesOnlyOneValue) { 9850 if (!isConstant) { 9851 if (Value.getOpcode() != ISD::EXTRACT_VECTOR_ELT || 9852 Value.getValueType() != VT) { 9853 LLVM_DEBUG( 9854 dbgs() << "LowerBUILD_VECTOR: use DUP for non-constant splats\n"); 9855 return DAG.getNode(AArch64ISD::DUP, dl, VT, Value); 9856 } 9857 9858 // This is actually a DUPLANExx operation, which keeps everything vectory. 9859 9860 SDValue Lane = Value.getOperand(1); 9861 Value = Value.getOperand(0); 9862 if (Value.getValueSizeInBits() == 64) { 9863 LLVM_DEBUG( 9864 dbgs() << "LowerBUILD_VECTOR: DUPLANE works on 128-bit vectors, " 9865 "widening it\n"); 9866 Value = WidenVector(Value, DAG); 9867 } 9868 9869 unsigned Opcode = getDUPLANEOp(VT.getVectorElementType()); 9870 return DAG.getNode(Opcode, dl, VT, Value, Lane); 9871 } 9872 9873 if (VT.getVectorElementType().isFloatingPoint()) { 9874 SmallVector<SDValue, 8> Ops; 9875 EVT EltTy = VT.getVectorElementType(); 9876 assert ((EltTy == MVT::f16 || EltTy == MVT::bf16 || EltTy == MVT::f32 || 9877 EltTy == MVT::f64) && "Unsupported floating-point vector type"); 9878 LLVM_DEBUG( 9879 dbgs() << "LowerBUILD_VECTOR: float constant splats, creating int " 9880 "BITCASTS, and try again\n"); 9881 MVT NewType = MVT::getIntegerVT(EltTy.getSizeInBits()); 9882 for (unsigned i = 0; i < NumElts; ++i) 9883 Ops.push_back(DAG.getNode(ISD::BITCAST, dl, NewType, Op.getOperand(i))); 9884 EVT VecVT = EVT::getVectorVT(*DAG.getContext(), NewType, NumElts); 9885 SDValue Val = DAG.getBuildVector(VecVT, dl, Ops); 9886 LLVM_DEBUG(dbgs() << "LowerBUILD_VECTOR: trying to lower new vector: "; 9887 Val.dump();); 9888 Val = LowerBUILD_VECTOR(Val, DAG); 9889 if (Val.getNode()) 9890 return DAG.getNode(ISD::BITCAST, dl, VT, Val); 9891 } 9892 } 9893 9894 // If we need to insert a small number of different non-constant elements and 9895 // the vector width is sufficiently large, prefer using DUP with the common 9896 // value and INSERT_VECTOR_ELT for the different lanes. If DUP is preferred, 9897 // skip the constant lane handling below. 9898 bool PreferDUPAndInsert = 9899 !isConstant && NumDifferentLanes >= 1 && 9900 NumDifferentLanes < ((NumElts - NumUndefLanes) / 2) && 9901 NumDifferentLanes >= NumConstantLanes; 9902 9903 // If there was only one constant value used and for more than one lane, 9904 // start by splatting that value, then replace the non-constant lanes. This 9905 // is better than the default, which will perform a separate initialization 9906 // for each lane. 9907 if (!PreferDUPAndInsert && NumConstantLanes > 0 && usesOnlyOneConstantValue) { 9908 // Firstly, try to materialize the splat constant. 9909 SDValue Vec = DAG.getSplatBuildVector(VT, dl, ConstantValue), 9910 Val = ConstantBuildVector(Vec, DAG); 9911 if (!Val) { 9912 // Otherwise, materialize the constant and splat it. 9913 Val = DAG.getNode(AArch64ISD::DUP, dl, VT, ConstantValue); 9914 DAG.ReplaceAllUsesWith(Vec.getNode(), &Val); 9915 } 9916 9917 // Now insert the non-constant lanes. 9918 for (unsigned i = 0; i < NumElts; ++i) { 9919 SDValue V = Op.getOperand(i); 9920 SDValue LaneIdx = DAG.getConstant(i, dl, MVT::i64); 9921 if (!isIntOrFPConstant(V)) 9922 // Note that type legalization likely mucked about with the VT of the 9923 // source operand, so we may have to convert it here before inserting. 9924 Val = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Val, V, LaneIdx); 9925 } 9926 return Val; 9927 } 9928 9929 // This will generate a load from the constant pool. 9930 if (isConstant) { 9931 LLVM_DEBUG( 9932 dbgs() << "LowerBUILD_VECTOR: all elements are constant, use default " 9933 "expansion\n"); 9934 return SDValue(); 9935 } 9936 9937 // Empirical tests suggest this is rarely worth it for vectors of length <= 2. 9938 if (NumElts >= 4) { 9939 if (SDValue shuffle = ReconstructShuffle(Op, DAG)) 9940 return shuffle; 9941 } 9942 9943 if (PreferDUPAndInsert) { 9944 // First, build a constant vector with the common element. 9945 SmallVector<SDValue, 8> Ops(NumElts, Value); 9946 SDValue NewVector = LowerBUILD_VECTOR(DAG.getBuildVector(VT, dl, Ops), DAG); 9947 // Next, insert the elements that do not match the common value. 9948 for (unsigned I = 0; I < NumElts; ++I) 9949 if (Op.getOperand(I) != Value) 9950 NewVector = 9951 DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, NewVector, 9952 Op.getOperand(I), DAG.getConstant(I, dl, MVT::i64)); 9953 9954 return NewVector; 9955 } 9956 9957 // If all else fails, just use a sequence of INSERT_VECTOR_ELT when we 9958 // know the default expansion would otherwise fall back on something even 9959 // worse. For a vector with one or two non-undef values, that's 9960 // scalar_to_vector for the elements followed by a shuffle (provided the 9961 // shuffle is valid for the target) and materialization element by element 9962 // on the stack followed by a load for everything else. 9963 if (!isConstant && !usesOnlyOneValue) { 9964 LLVM_DEBUG( 9965 dbgs() << "LowerBUILD_VECTOR: alternatives failed, creating sequence " 9966 "of INSERT_VECTOR_ELT\n"); 9967 9968 SDValue Vec = DAG.getUNDEF(VT); 9969 SDValue Op0 = Op.getOperand(0); 9970 unsigned i = 0; 9971 9972 // Use SCALAR_TO_VECTOR for lane zero to 9973 // a) Avoid a RMW dependency on the full vector register, and 9974 // b) Allow the register coalescer to fold away the copy if the 9975 // value is already in an S or D register, and we're forced to emit an 9976 // INSERT_SUBREG that we can't fold anywhere. 9977 // 9978 // We also allow types like i8 and i16 which are illegal scalar but legal 9979 // vector element types. After type-legalization the inserted value is 9980 // extended (i32) and it is safe to cast them to the vector type by ignoring 9981 // the upper bits of the lowest lane (e.g. v8i8, v4i16). 9982 if (!Op0.isUndef()) { 9983 LLVM_DEBUG(dbgs() << "Creating node for op0, it is not undefined:\n"); 9984 Vec = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op0); 9985 ++i; 9986 } 9987 LLVM_DEBUG(if (i < NumElts) dbgs() 9988 << "Creating nodes for the other vector elements:\n";); 9989 for (; i < NumElts; ++i) { 9990 SDValue V = Op.getOperand(i); 9991 if (V.isUndef()) 9992 continue; 9993 SDValue LaneIdx = DAG.getConstant(i, dl, MVT::i64); 9994 Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Vec, V, LaneIdx); 9995 } 9996 return Vec; 9997 } 9998 9999 LLVM_DEBUG( 10000 dbgs() << "LowerBUILD_VECTOR: use default expansion, failed to find " 10001 "better alternative\n"); 10002 return SDValue(); 10003 } 10004 10005 SDValue AArch64TargetLowering::LowerCONCAT_VECTORS(SDValue Op, 10006 SelectionDAG &DAG) const { 10007 assert(Op.getValueType().isScalableVector() && 10008 isTypeLegal(Op.getValueType()) && 10009 "Expected legal scalable vector type!"); 10010 10011 if (isTypeLegal(Op.getOperand(0).getValueType()) && Op.getNumOperands() == 2) 10012 return Op; 10013 10014 return SDValue(); 10015 } 10016 10017 SDValue AArch64TargetLowering::LowerINSERT_VECTOR_ELT(SDValue Op, 10018 SelectionDAG &DAG) const { 10019 assert(Op.getOpcode() == ISD::INSERT_VECTOR_ELT && "Unknown opcode!"); 10020 10021 if (useSVEForFixedLengthVectorVT(Op.getValueType())) 10022 return LowerFixedLengthInsertVectorElt(Op, DAG); 10023 10024 // Check for non-constant or out of range lane. 10025 EVT VT = Op.getOperand(0).getValueType(); 10026 ConstantSDNode *CI = dyn_cast<ConstantSDNode>(Op.getOperand(2)); 10027 if (!CI || CI->getZExtValue() >= VT.getVectorNumElements()) 10028 return SDValue(); 10029 10030 10031 // Insertion/extraction are legal for V128 types. 10032 if (VT == MVT::v16i8 || VT == MVT::v8i16 || VT == MVT::v4i32 || 10033 VT == MVT::v2i64 || VT == MVT::v4f32 || VT == MVT::v2f64 || 10034 VT == MVT::v8f16 || VT == MVT::v8bf16) 10035 return Op; 10036 10037 if (VT != MVT::v8i8 && VT != MVT::v4i16 && VT != MVT::v2i32 && 10038 VT != MVT::v1i64 && VT != MVT::v2f32 && VT != MVT::v4f16 && 10039 VT != MVT::v4bf16) 10040 return SDValue(); 10041 10042 // For V64 types, we perform insertion by expanding the value 10043 // to a V128 type and perform the insertion on that. 10044 SDLoc DL(Op); 10045 SDValue WideVec = WidenVector(Op.getOperand(0), DAG); 10046 EVT WideTy = WideVec.getValueType(); 10047 10048 SDValue Node = DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, WideTy, WideVec, 10049 Op.getOperand(1), Op.getOperand(2)); 10050 // Re-narrow the resultant vector. 10051 return NarrowVector(Node, DAG); 10052 } 10053 10054 SDValue 10055 AArch64TargetLowering::LowerEXTRACT_VECTOR_ELT(SDValue Op, 10056 SelectionDAG &DAG) const { 10057 assert(Op.getOpcode() == ISD::EXTRACT_VECTOR_ELT && "Unknown opcode!"); 10058 10059 EVT VT = Op.getOperand(0).getValueType(); 10060 if (useSVEForFixedLengthVectorVT(VT)) 10061 return LowerFixedLengthExtractVectorElt(Op, DAG); 10062 10063 // Check for non-constant or out of range lane. 10064 ConstantSDNode *CI = dyn_cast<ConstantSDNode>(Op.getOperand(1)); 10065 if (!CI || CI->getZExtValue() >= VT.getVectorNumElements()) 10066 return SDValue(); 10067 10068 10069 // Insertion/extraction are legal for V128 types. 10070 if (VT == MVT::v16i8 || VT == MVT::v8i16 || VT == MVT::v4i32 || 10071 VT == MVT::v2i64 || VT == MVT::v4f32 || VT == MVT::v2f64 || 10072 VT == MVT::v8f16 || VT == MVT::v8bf16) 10073 return Op; 10074 10075 if (VT != MVT::v8i8 && VT != MVT::v4i16 && VT != MVT::v2i32 && 10076 VT != MVT::v1i64 && VT != MVT::v2f32 && VT != MVT::v4f16 && 10077 VT != MVT::v4bf16) 10078 return SDValue(); 10079 10080 // For V64 types, we perform extraction by expanding the value 10081 // to a V128 type and perform the extraction on that. 10082 SDLoc DL(Op); 10083 SDValue WideVec = WidenVector(Op.getOperand(0), DAG); 10084 EVT WideTy = WideVec.getValueType(); 10085 10086 EVT ExtrTy = WideTy.getVectorElementType(); 10087 if (ExtrTy == MVT::i16 || ExtrTy == MVT::i8) 10088 ExtrTy = MVT::i32; 10089 10090 // For extractions, we just return the result directly. 10091 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, ExtrTy, WideVec, 10092 Op.getOperand(1)); 10093 } 10094 10095 SDValue AArch64TargetLowering::LowerEXTRACT_SUBVECTOR(SDValue Op, 10096 SelectionDAG &DAG) const { 10097 assert(Op.getValueType().isFixedLengthVector() && 10098 "Only cases that extract a fixed length vector are supported!"); 10099 10100 EVT InVT = Op.getOperand(0).getValueType(); 10101 unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue(); 10102 unsigned Size = Op.getValueSizeInBits(); 10103 10104 if (InVT.isScalableVector()) { 10105 // This will be matched by custom code during ISelDAGToDAG. 10106 if (Idx == 0 && isPackedVectorType(InVT, DAG)) 10107 return Op; 10108 10109 return SDValue(); 10110 } 10111 10112 // This will get lowered to an appropriate EXTRACT_SUBREG in ISel. 10113 if (Idx == 0 && InVT.getSizeInBits() <= 128) 10114 return Op; 10115 10116 // If this is extracting the upper 64-bits of a 128-bit vector, we match 10117 // that directly. 10118 if (Size == 64 && Idx * InVT.getScalarSizeInBits() == 64 && 10119 InVT.getSizeInBits() == 128) 10120 return Op; 10121 10122 return SDValue(); 10123 } 10124 10125 SDValue AArch64TargetLowering::LowerINSERT_SUBVECTOR(SDValue Op, 10126 SelectionDAG &DAG) const { 10127 assert(Op.getValueType().isScalableVector() && 10128 "Only expect to lower inserts into scalable vectors!"); 10129 10130 EVT InVT = Op.getOperand(1).getValueType(); 10131 unsigned Idx = cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue(); 10132 10133 if (InVT.isScalableVector()) { 10134 SDLoc DL(Op); 10135 EVT VT = Op.getValueType(); 10136 10137 if (!isTypeLegal(VT) || !VT.isInteger()) 10138 return SDValue(); 10139 10140 SDValue Vec0 = Op.getOperand(0); 10141 SDValue Vec1 = Op.getOperand(1); 10142 10143 // Ensure the subvector is half the size of the main vector. 10144 if (VT.getVectorElementCount() != (InVT.getVectorElementCount() * 2)) 10145 return SDValue(); 10146 10147 // Extend elements of smaller vector... 10148 EVT WideVT = InVT.widenIntegerVectorElementType(*(DAG.getContext())); 10149 SDValue ExtVec = DAG.getNode(ISD::ANY_EXTEND, DL, WideVT, Vec1); 10150 10151 if (Idx == 0) { 10152 SDValue HiVec0 = DAG.getNode(AArch64ISD::UUNPKHI, DL, WideVT, Vec0); 10153 return DAG.getNode(AArch64ISD::UZP1, DL, VT, ExtVec, HiVec0); 10154 } else if (Idx == InVT.getVectorMinNumElements()) { 10155 SDValue LoVec0 = DAG.getNode(AArch64ISD::UUNPKLO, DL, WideVT, Vec0); 10156 return DAG.getNode(AArch64ISD::UZP1, DL, VT, LoVec0, ExtVec); 10157 } 10158 10159 return SDValue(); 10160 } 10161 10162 // This will be matched by custom code during ISelDAGToDAG. 10163 if (Idx == 0 && isPackedVectorType(InVT, DAG) && Op.getOperand(0).isUndef()) 10164 return Op; 10165 10166 return SDValue(); 10167 } 10168 10169 SDValue AArch64TargetLowering::LowerDIV(SDValue Op, SelectionDAG &DAG) const { 10170 EVT VT = Op.getValueType(); 10171 10172 if (useSVEForFixedLengthVectorVT(VT, /*OverrideNEON=*/true)) 10173 return LowerFixedLengthVectorIntDivideToSVE(Op, DAG); 10174 10175 assert(VT.isScalableVector() && "Expected a scalable vector."); 10176 10177 bool Signed = Op.getOpcode() == ISD::SDIV; 10178 unsigned PredOpcode = Signed ? AArch64ISD::SDIV_PRED : AArch64ISD::UDIV_PRED; 10179 10180 if (VT == MVT::nxv4i32 || VT == MVT::nxv2i64) 10181 return LowerToPredicatedOp(Op, DAG, PredOpcode); 10182 10183 // SVE doesn't have i8 and i16 DIV operations; widen them to 32-bit 10184 // operations, and truncate the result. 10185 EVT WidenedVT; 10186 if (VT == MVT::nxv16i8) 10187 WidenedVT = MVT::nxv8i16; 10188 else if (VT == MVT::nxv8i16) 10189 WidenedVT = MVT::nxv4i32; 10190 else 10191 llvm_unreachable("Unexpected Custom DIV operation"); 10192 10193 SDLoc dl(Op); 10194 unsigned UnpkLo = Signed ? AArch64ISD::SUNPKLO : AArch64ISD::UUNPKLO; 10195 unsigned UnpkHi = Signed ? AArch64ISD::SUNPKHI : AArch64ISD::UUNPKHI; 10196 SDValue Op0Lo = DAG.getNode(UnpkLo, dl, WidenedVT, Op.getOperand(0)); 10197 SDValue Op1Lo = DAG.getNode(UnpkLo, dl, WidenedVT, Op.getOperand(1)); 10198 SDValue Op0Hi = DAG.getNode(UnpkHi, dl, WidenedVT, Op.getOperand(0)); 10199 SDValue Op1Hi = DAG.getNode(UnpkHi, dl, WidenedVT, Op.getOperand(1)); 10200 SDValue ResultLo = DAG.getNode(Op.getOpcode(), dl, WidenedVT, Op0Lo, Op1Lo); 10201 SDValue ResultHi = DAG.getNode(Op.getOpcode(), dl, WidenedVT, Op0Hi, Op1Hi); 10202 return DAG.getNode(AArch64ISD::UZP1, dl, VT, ResultLo, ResultHi); 10203 } 10204 10205 bool AArch64TargetLowering::isShuffleMaskLegal(ArrayRef<int> M, EVT VT) const { 10206 // Currently no fixed length shuffles that require SVE are legal. 10207 if (useSVEForFixedLengthVectorVT(VT)) 10208 return false; 10209 10210 if (VT.getVectorNumElements() == 4 && 10211 (VT.is128BitVector() || VT.is64BitVector())) { 10212 unsigned PFIndexes[4]; 10213 for (unsigned i = 0; i != 4; ++i) { 10214 if (M[i] < 0) 10215 PFIndexes[i] = 8; 10216 else 10217 PFIndexes[i] = M[i]; 10218 } 10219 10220 // Compute the index in the perfect shuffle table. 10221 unsigned PFTableIndex = PFIndexes[0] * 9 * 9 * 9 + PFIndexes[1] * 9 * 9 + 10222 PFIndexes[2] * 9 + PFIndexes[3]; 10223 unsigned PFEntry = PerfectShuffleTable[PFTableIndex]; 10224 unsigned Cost = (PFEntry >> 30); 10225 10226 if (Cost <= 4) 10227 return true; 10228 } 10229 10230 bool DummyBool; 10231 int DummyInt; 10232 unsigned DummyUnsigned; 10233 10234 return (ShuffleVectorSDNode::isSplatMask(&M[0], VT) || isREVMask(M, VT, 64) || 10235 isREVMask(M, VT, 32) || isREVMask(M, VT, 16) || 10236 isEXTMask(M, VT, DummyBool, DummyUnsigned) || 10237 // isTBLMask(M, VT) || // FIXME: Port TBL support from ARM. 10238 isTRNMask(M, VT, DummyUnsigned) || isUZPMask(M, VT, DummyUnsigned) || 10239 isZIPMask(M, VT, DummyUnsigned) || 10240 isTRN_v_undef_Mask(M, VT, DummyUnsigned) || 10241 isUZP_v_undef_Mask(M, VT, DummyUnsigned) || 10242 isZIP_v_undef_Mask(M, VT, DummyUnsigned) || 10243 isINSMask(M, VT.getVectorNumElements(), DummyBool, DummyInt) || 10244 isConcatMask(M, VT, VT.getSizeInBits() == 128)); 10245 } 10246 10247 /// getVShiftImm - Check if this is a valid build_vector for the immediate 10248 /// operand of a vector shift operation, where all the elements of the 10249 /// build_vector must have the same constant integer value. 10250 static bool getVShiftImm(SDValue Op, unsigned ElementBits, int64_t &Cnt) { 10251 // Ignore bit_converts. 10252 while (Op.getOpcode() == ISD::BITCAST) 10253 Op = Op.getOperand(0); 10254 BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(Op.getNode()); 10255 APInt SplatBits, SplatUndef; 10256 unsigned SplatBitSize; 10257 bool HasAnyUndefs; 10258 if (!BVN || !BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, 10259 HasAnyUndefs, ElementBits) || 10260 SplatBitSize > ElementBits) 10261 return false; 10262 Cnt = SplatBits.getSExtValue(); 10263 return true; 10264 } 10265 10266 /// isVShiftLImm - Check if this is a valid build_vector for the immediate 10267 /// operand of a vector shift left operation. That value must be in the range: 10268 /// 0 <= Value < ElementBits for a left shift; or 10269 /// 0 <= Value <= ElementBits for a long left shift. 10270 static bool isVShiftLImm(SDValue Op, EVT VT, bool isLong, int64_t &Cnt) { 10271 assert(VT.isVector() && "vector shift count is not a vector type"); 10272 int64_t ElementBits = VT.getScalarSizeInBits(); 10273 if (!getVShiftImm(Op, ElementBits, Cnt)) 10274 return false; 10275 return (Cnt >= 0 && (isLong ? Cnt - 1 : Cnt) < ElementBits); 10276 } 10277 10278 /// isVShiftRImm - Check if this is a valid build_vector for the immediate 10279 /// operand of a vector shift right operation. The value must be in the range: 10280 /// 1 <= Value <= ElementBits for a right shift; or 10281 static bool isVShiftRImm(SDValue Op, EVT VT, bool isNarrow, int64_t &Cnt) { 10282 assert(VT.isVector() && "vector shift count is not a vector type"); 10283 int64_t ElementBits = VT.getScalarSizeInBits(); 10284 if (!getVShiftImm(Op, ElementBits, Cnt)) 10285 return false; 10286 return (Cnt >= 1 && Cnt <= (isNarrow ? ElementBits / 2 : ElementBits)); 10287 } 10288 10289 SDValue AArch64TargetLowering::LowerTRUNCATE(SDValue Op, 10290 SelectionDAG &DAG) const { 10291 EVT VT = Op.getValueType(); 10292 10293 if (VT.getScalarType() == MVT::i1) { 10294 // Lower i1 truncate to `(x & 1) != 0`. 10295 SDLoc dl(Op); 10296 EVT OpVT = Op.getOperand(0).getValueType(); 10297 SDValue Zero = DAG.getConstant(0, dl, OpVT); 10298 SDValue One = DAG.getConstant(1, dl, OpVT); 10299 SDValue And = DAG.getNode(ISD::AND, dl, OpVT, Op.getOperand(0), One); 10300 return DAG.getSetCC(dl, VT, And, Zero, ISD::SETNE); 10301 } 10302 10303 if (!VT.isVector() || VT.isScalableVector()) 10304 return SDValue(); 10305 10306 if (useSVEForFixedLengthVectorVT(Op.getOperand(0).getValueType())) 10307 return LowerFixedLengthVectorTruncateToSVE(Op, DAG); 10308 10309 return SDValue(); 10310 } 10311 10312 SDValue AArch64TargetLowering::LowerVectorSRA_SRL_SHL(SDValue Op, 10313 SelectionDAG &DAG) const { 10314 EVT VT = Op.getValueType(); 10315 SDLoc DL(Op); 10316 int64_t Cnt; 10317 10318 if (!Op.getOperand(1).getValueType().isVector()) 10319 return Op; 10320 unsigned EltSize = VT.getScalarSizeInBits(); 10321 10322 switch (Op.getOpcode()) { 10323 default: 10324 llvm_unreachable("unexpected shift opcode"); 10325 10326 case ISD::SHL: 10327 if (VT.isScalableVector() || useSVEForFixedLengthVectorVT(VT)) 10328 return LowerToPredicatedOp(Op, DAG, AArch64ISD::SHL_PRED); 10329 10330 if (isVShiftLImm(Op.getOperand(1), VT, false, Cnt) && Cnt < EltSize) 10331 return DAG.getNode(AArch64ISD::VSHL, DL, VT, Op.getOperand(0), 10332 DAG.getConstant(Cnt, DL, MVT::i32)); 10333 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT, 10334 DAG.getConstant(Intrinsic::aarch64_neon_ushl, DL, 10335 MVT::i32), 10336 Op.getOperand(0), Op.getOperand(1)); 10337 case ISD::SRA: 10338 case ISD::SRL: 10339 if (VT.isScalableVector() || useSVEForFixedLengthVectorVT(VT)) { 10340 unsigned Opc = Op.getOpcode() == ISD::SRA ? AArch64ISD::SRA_PRED 10341 : AArch64ISD::SRL_PRED; 10342 return LowerToPredicatedOp(Op, DAG, Opc); 10343 } 10344 10345 // Right shift immediate 10346 if (isVShiftRImm(Op.getOperand(1), VT, false, Cnt) && Cnt < EltSize) { 10347 unsigned Opc = 10348 (Op.getOpcode() == ISD::SRA) ? AArch64ISD::VASHR : AArch64ISD::VLSHR; 10349 return DAG.getNode(Opc, DL, VT, Op.getOperand(0), 10350 DAG.getConstant(Cnt, DL, MVT::i32)); 10351 } 10352 10353 // Right shift register. Note, there is not a shift right register 10354 // instruction, but the shift left register instruction takes a signed 10355 // value, where negative numbers specify a right shift. 10356 unsigned Opc = (Op.getOpcode() == ISD::SRA) ? Intrinsic::aarch64_neon_sshl 10357 : Intrinsic::aarch64_neon_ushl; 10358 // negate the shift amount 10359 SDValue NegShift = DAG.getNode(AArch64ISD::NEG, DL, VT, Op.getOperand(1)); 10360 SDValue NegShiftLeft = 10361 DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT, 10362 DAG.getConstant(Opc, DL, MVT::i32), Op.getOperand(0), 10363 NegShift); 10364 return NegShiftLeft; 10365 } 10366 10367 return SDValue(); 10368 } 10369 10370 static SDValue EmitVectorComparison(SDValue LHS, SDValue RHS, 10371 AArch64CC::CondCode CC, bool NoNans, EVT VT, 10372 const SDLoc &dl, SelectionDAG &DAG) { 10373 EVT SrcVT = LHS.getValueType(); 10374 assert(VT.getSizeInBits() == SrcVT.getSizeInBits() && 10375 "function only supposed to emit natural comparisons"); 10376 10377 BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(RHS.getNode()); 10378 APInt CnstBits(VT.getSizeInBits(), 0); 10379 APInt UndefBits(VT.getSizeInBits(), 0); 10380 bool IsCnst = BVN && resolveBuildVector(BVN, CnstBits, UndefBits); 10381 bool IsZero = IsCnst && (CnstBits == 0); 10382 10383 if (SrcVT.getVectorElementType().isFloatingPoint()) { 10384 switch (CC) { 10385 default: 10386 return SDValue(); 10387 case AArch64CC::NE: { 10388 SDValue Fcmeq; 10389 if (IsZero) 10390 Fcmeq = DAG.getNode(AArch64ISD::FCMEQz, dl, VT, LHS); 10391 else 10392 Fcmeq = DAG.getNode(AArch64ISD::FCMEQ, dl, VT, LHS, RHS); 10393 return DAG.getNOT(dl, Fcmeq, VT); 10394 } 10395 case AArch64CC::EQ: 10396 if (IsZero) 10397 return DAG.getNode(AArch64ISD::FCMEQz, dl, VT, LHS); 10398 return DAG.getNode(AArch64ISD::FCMEQ, dl, VT, LHS, RHS); 10399 case AArch64CC::GE: 10400 if (IsZero) 10401 return DAG.getNode(AArch64ISD::FCMGEz, dl, VT, LHS); 10402 return DAG.getNode(AArch64ISD::FCMGE, dl, VT, LHS, RHS); 10403 case AArch64CC::GT: 10404 if (IsZero) 10405 return DAG.getNode(AArch64ISD::FCMGTz, dl, VT, LHS); 10406 return DAG.getNode(AArch64ISD::FCMGT, dl, VT, LHS, RHS); 10407 case AArch64CC::LS: 10408 if (IsZero) 10409 return DAG.getNode(AArch64ISD::FCMLEz, dl, VT, LHS); 10410 return DAG.getNode(AArch64ISD::FCMGE, dl, VT, RHS, LHS); 10411 case AArch64CC::LT: 10412 if (!NoNans) 10413 return SDValue(); 10414 // If we ignore NaNs then we can use to the MI implementation. 10415 LLVM_FALLTHROUGH; 10416 case AArch64CC::MI: 10417 if (IsZero) 10418 return DAG.getNode(AArch64ISD::FCMLTz, dl, VT, LHS); 10419 return DAG.getNode(AArch64ISD::FCMGT, dl, VT, RHS, LHS); 10420 } 10421 } 10422 10423 switch (CC) { 10424 default: 10425 return SDValue(); 10426 case AArch64CC::NE: { 10427 SDValue Cmeq; 10428 if (IsZero) 10429 Cmeq = DAG.getNode(AArch64ISD::CMEQz, dl, VT, LHS); 10430 else 10431 Cmeq = DAG.getNode(AArch64ISD::CMEQ, dl, VT, LHS, RHS); 10432 return DAG.getNOT(dl, Cmeq, VT); 10433 } 10434 case AArch64CC::EQ: 10435 if (IsZero) 10436 return DAG.getNode(AArch64ISD::CMEQz, dl, VT, LHS); 10437 return DAG.getNode(AArch64ISD::CMEQ, dl, VT, LHS, RHS); 10438 case AArch64CC::GE: 10439 if (IsZero) 10440 return DAG.getNode(AArch64ISD::CMGEz, dl, VT, LHS); 10441 return DAG.getNode(AArch64ISD::CMGE, dl, VT, LHS, RHS); 10442 case AArch64CC::GT: 10443 if (IsZero) 10444 return DAG.getNode(AArch64ISD::CMGTz, dl, VT, LHS); 10445 return DAG.getNode(AArch64ISD::CMGT, dl, VT, LHS, RHS); 10446 case AArch64CC::LE: 10447 if (IsZero) 10448 return DAG.getNode(AArch64ISD::CMLEz, dl, VT, LHS); 10449 return DAG.getNode(AArch64ISD::CMGE, dl, VT, RHS, LHS); 10450 case AArch64CC::LS: 10451 return DAG.getNode(AArch64ISD::CMHS, dl, VT, RHS, LHS); 10452 case AArch64CC::LO: 10453 return DAG.getNode(AArch64ISD::CMHI, dl, VT, RHS, LHS); 10454 case AArch64CC::LT: 10455 if (IsZero) 10456 return DAG.getNode(AArch64ISD::CMLTz, dl, VT, LHS); 10457 return DAG.getNode(AArch64ISD::CMGT, dl, VT, RHS, LHS); 10458 case AArch64CC::HI: 10459 return DAG.getNode(AArch64ISD::CMHI, dl, VT, LHS, RHS); 10460 case AArch64CC::HS: 10461 return DAG.getNode(AArch64ISD::CMHS, dl, VT, LHS, RHS); 10462 } 10463 } 10464 10465 SDValue AArch64TargetLowering::LowerVSETCC(SDValue Op, 10466 SelectionDAG &DAG) const { 10467 if (Op.getValueType().isScalableVector()) 10468 return LowerToPredicatedOp(Op, DAG, AArch64ISD::SETCC_MERGE_ZERO); 10469 10470 if (useSVEForFixedLengthVectorVT(Op.getOperand(0).getValueType())) 10471 return LowerFixedLengthVectorSetccToSVE(Op, DAG); 10472 10473 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get(); 10474 SDValue LHS = Op.getOperand(0); 10475 SDValue RHS = Op.getOperand(1); 10476 EVT CmpVT = LHS.getValueType().changeVectorElementTypeToInteger(); 10477 SDLoc dl(Op); 10478 10479 if (LHS.getValueType().getVectorElementType().isInteger()) { 10480 assert(LHS.getValueType() == RHS.getValueType()); 10481 AArch64CC::CondCode AArch64CC = changeIntCCToAArch64CC(CC); 10482 SDValue Cmp = 10483 EmitVectorComparison(LHS, RHS, AArch64CC, false, CmpVT, dl, DAG); 10484 return DAG.getSExtOrTrunc(Cmp, dl, Op.getValueType()); 10485 } 10486 10487 const bool FullFP16 = 10488 static_cast<const AArch64Subtarget &>(DAG.getSubtarget()).hasFullFP16(); 10489 10490 // Make v4f16 (only) fcmp operations utilise vector instructions 10491 // v8f16 support will be a litle more complicated 10492 if (!FullFP16 && LHS.getValueType().getVectorElementType() == MVT::f16) { 10493 if (LHS.getValueType().getVectorNumElements() == 4) { 10494 LHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::v4f32, LHS); 10495 RHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::v4f32, RHS); 10496 SDValue NewSetcc = DAG.getSetCC(dl, MVT::v4i16, LHS, RHS, CC); 10497 DAG.ReplaceAllUsesWith(Op, NewSetcc); 10498 CmpVT = MVT::v4i32; 10499 } else 10500 return SDValue(); 10501 } 10502 10503 assert((!FullFP16 && LHS.getValueType().getVectorElementType() != MVT::f16) || 10504 LHS.getValueType().getVectorElementType() != MVT::f128); 10505 10506 // Unfortunately, the mapping of LLVM FP CC's onto AArch64 CC's isn't totally 10507 // clean. Some of them require two branches to implement. 10508 AArch64CC::CondCode CC1, CC2; 10509 bool ShouldInvert; 10510 changeVectorFPCCToAArch64CC(CC, CC1, CC2, ShouldInvert); 10511 10512 bool NoNaNs = getTargetMachine().Options.NoNaNsFPMath; 10513 SDValue Cmp = 10514 EmitVectorComparison(LHS, RHS, CC1, NoNaNs, CmpVT, dl, DAG); 10515 if (!Cmp.getNode()) 10516 return SDValue(); 10517 10518 if (CC2 != AArch64CC::AL) { 10519 SDValue Cmp2 = 10520 EmitVectorComparison(LHS, RHS, CC2, NoNaNs, CmpVT, dl, DAG); 10521 if (!Cmp2.getNode()) 10522 return SDValue(); 10523 10524 Cmp = DAG.getNode(ISD::OR, dl, CmpVT, Cmp, Cmp2); 10525 } 10526 10527 Cmp = DAG.getSExtOrTrunc(Cmp, dl, Op.getValueType()); 10528 10529 if (ShouldInvert) 10530 Cmp = DAG.getNOT(dl, Cmp, Cmp.getValueType()); 10531 10532 return Cmp; 10533 } 10534 10535 static SDValue getReductionSDNode(unsigned Op, SDLoc DL, SDValue ScalarOp, 10536 SelectionDAG &DAG) { 10537 SDValue VecOp = ScalarOp.getOperand(0); 10538 auto Rdx = DAG.getNode(Op, DL, VecOp.getSimpleValueType(), VecOp); 10539 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, ScalarOp.getValueType(), Rdx, 10540 DAG.getConstant(0, DL, MVT::i64)); 10541 } 10542 10543 SDValue AArch64TargetLowering::LowerVECREDUCE(SDValue Op, 10544 SelectionDAG &DAG) const { 10545 SDValue Src = Op.getOperand(0); 10546 10547 // Try to lower fixed length reductions to SVE. 10548 EVT SrcVT = Src.getValueType(); 10549 bool OverrideNEON = Op.getOpcode() == ISD::VECREDUCE_AND || 10550 Op.getOpcode() == ISD::VECREDUCE_OR || 10551 Op.getOpcode() == ISD::VECREDUCE_XOR || 10552 Op.getOpcode() == ISD::VECREDUCE_FADD || 10553 (Op.getOpcode() != ISD::VECREDUCE_ADD && 10554 SrcVT.getVectorElementType() == MVT::i64); 10555 if (SrcVT.isScalableVector() || 10556 useSVEForFixedLengthVectorVT(SrcVT, OverrideNEON)) { 10557 10558 if (SrcVT.getVectorElementType() == MVT::i1) 10559 return LowerPredReductionToSVE(Op, DAG); 10560 10561 switch (Op.getOpcode()) { 10562 case ISD::VECREDUCE_ADD: 10563 return LowerReductionToSVE(AArch64ISD::UADDV_PRED, Op, DAG); 10564 case ISD::VECREDUCE_AND: 10565 return LowerReductionToSVE(AArch64ISD::ANDV_PRED, Op, DAG); 10566 case ISD::VECREDUCE_OR: 10567 return LowerReductionToSVE(AArch64ISD::ORV_PRED, Op, DAG); 10568 case ISD::VECREDUCE_SMAX: 10569 return LowerReductionToSVE(AArch64ISD::SMAXV_PRED, Op, DAG); 10570 case ISD::VECREDUCE_SMIN: 10571 return LowerReductionToSVE(AArch64ISD::SMINV_PRED, Op, DAG); 10572 case ISD::VECREDUCE_UMAX: 10573 return LowerReductionToSVE(AArch64ISD::UMAXV_PRED, Op, DAG); 10574 case ISD::VECREDUCE_UMIN: 10575 return LowerReductionToSVE(AArch64ISD::UMINV_PRED, Op, DAG); 10576 case ISD::VECREDUCE_XOR: 10577 return LowerReductionToSVE(AArch64ISD::EORV_PRED, Op, DAG); 10578 case ISD::VECREDUCE_FADD: 10579 return LowerReductionToSVE(AArch64ISD::FADDV_PRED, Op, DAG); 10580 case ISD::VECREDUCE_FMAX: 10581 return LowerReductionToSVE(AArch64ISD::FMAXNMV_PRED, Op, DAG); 10582 case ISD::VECREDUCE_FMIN: 10583 return LowerReductionToSVE(AArch64ISD::FMINNMV_PRED, Op, DAG); 10584 default: 10585 llvm_unreachable("Unhandled fixed length reduction"); 10586 } 10587 } 10588 10589 // Lower NEON reductions. 10590 SDLoc dl(Op); 10591 switch (Op.getOpcode()) { 10592 case ISD::VECREDUCE_ADD: 10593 return getReductionSDNode(AArch64ISD::UADDV, dl, Op, DAG); 10594 case ISD::VECREDUCE_SMAX: 10595 return getReductionSDNode(AArch64ISD::SMAXV, dl, Op, DAG); 10596 case ISD::VECREDUCE_SMIN: 10597 return getReductionSDNode(AArch64ISD::SMINV, dl, Op, DAG); 10598 case ISD::VECREDUCE_UMAX: 10599 return getReductionSDNode(AArch64ISD::UMAXV, dl, Op, DAG); 10600 case ISD::VECREDUCE_UMIN: 10601 return getReductionSDNode(AArch64ISD::UMINV, dl, Op, DAG); 10602 case ISD::VECREDUCE_FMAX: { 10603 return DAG.getNode( 10604 ISD::INTRINSIC_WO_CHAIN, dl, Op.getValueType(), 10605 DAG.getConstant(Intrinsic::aarch64_neon_fmaxnmv, dl, MVT::i32), 10606 Src); 10607 } 10608 case ISD::VECREDUCE_FMIN: { 10609 return DAG.getNode( 10610 ISD::INTRINSIC_WO_CHAIN, dl, Op.getValueType(), 10611 DAG.getConstant(Intrinsic::aarch64_neon_fminnmv, dl, MVT::i32), 10612 Src); 10613 } 10614 default: 10615 llvm_unreachable("Unhandled reduction"); 10616 } 10617 } 10618 10619 SDValue AArch64TargetLowering::LowerATOMIC_LOAD_SUB(SDValue Op, 10620 SelectionDAG &DAG) const { 10621 auto &Subtarget = static_cast<const AArch64Subtarget &>(DAG.getSubtarget()); 10622 if (!Subtarget.hasLSE() && !Subtarget.outlineAtomics()) 10623 return SDValue(); 10624 10625 // LSE has an atomic load-add instruction, but not a load-sub. 10626 SDLoc dl(Op); 10627 MVT VT = Op.getSimpleValueType(); 10628 SDValue RHS = Op.getOperand(2); 10629 AtomicSDNode *AN = cast<AtomicSDNode>(Op.getNode()); 10630 RHS = DAG.getNode(ISD::SUB, dl, VT, DAG.getConstant(0, dl, VT), RHS); 10631 return DAG.getAtomic(ISD::ATOMIC_LOAD_ADD, dl, AN->getMemoryVT(), 10632 Op.getOperand(0), Op.getOperand(1), RHS, 10633 AN->getMemOperand()); 10634 } 10635 10636 SDValue AArch64TargetLowering::LowerATOMIC_LOAD_AND(SDValue Op, 10637 SelectionDAG &DAG) const { 10638 auto &Subtarget = static_cast<const AArch64Subtarget &>(DAG.getSubtarget()); 10639 if (!Subtarget.hasLSE() && !Subtarget.outlineAtomics()) 10640 return SDValue(); 10641 10642 // LSE has an atomic load-clear instruction, but not a load-and. 10643 SDLoc dl(Op); 10644 MVT VT = Op.getSimpleValueType(); 10645 SDValue RHS = Op.getOperand(2); 10646 AtomicSDNode *AN = cast<AtomicSDNode>(Op.getNode()); 10647 RHS = DAG.getNode(ISD::XOR, dl, VT, DAG.getConstant(-1ULL, dl, VT), RHS); 10648 return DAG.getAtomic(ISD::ATOMIC_LOAD_CLR, dl, AN->getMemoryVT(), 10649 Op.getOperand(0), Op.getOperand(1), RHS, 10650 AN->getMemOperand()); 10651 } 10652 10653 SDValue AArch64TargetLowering::LowerWindowsDYNAMIC_STACKALLOC( 10654 SDValue Op, SDValue Chain, SDValue &Size, SelectionDAG &DAG) const { 10655 SDLoc dl(Op); 10656 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 10657 SDValue Callee = DAG.getTargetExternalSymbol("__chkstk", PtrVT, 0); 10658 10659 const AArch64RegisterInfo *TRI = Subtarget->getRegisterInfo(); 10660 const uint32_t *Mask = TRI->getWindowsStackProbePreservedMask(); 10661 if (Subtarget->hasCustomCallingConv()) 10662 TRI->UpdateCustomCallPreservedMask(DAG.getMachineFunction(), &Mask); 10663 10664 Size = DAG.getNode(ISD::SRL, dl, MVT::i64, Size, 10665 DAG.getConstant(4, dl, MVT::i64)); 10666 Chain = DAG.getCopyToReg(Chain, dl, AArch64::X15, Size, SDValue()); 10667 Chain = 10668 DAG.getNode(AArch64ISD::CALL, dl, DAG.getVTList(MVT::Other, MVT::Glue), 10669 Chain, Callee, DAG.getRegister(AArch64::X15, MVT::i64), 10670 DAG.getRegisterMask(Mask), Chain.getValue(1)); 10671 // To match the actual intent better, we should read the output from X15 here 10672 // again (instead of potentially spilling it to the stack), but rereading Size 10673 // from X15 here doesn't work at -O0, since it thinks that X15 is undefined 10674 // here. 10675 10676 Size = DAG.getNode(ISD::SHL, dl, MVT::i64, Size, 10677 DAG.getConstant(4, dl, MVT::i64)); 10678 return Chain; 10679 } 10680 10681 SDValue 10682 AArch64TargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op, 10683 SelectionDAG &DAG) const { 10684 assert(Subtarget->isTargetWindows() && 10685 "Only Windows alloca probing supported"); 10686 SDLoc dl(Op); 10687 // Get the inputs. 10688 SDNode *Node = Op.getNode(); 10689 SDValue Chain = Op.getOperand(0); 10690 SDValue Size = Op.getOperand(1); 10691 MaybeAlign Align = 10692 cast<ConstantSDNode>(Op.getOperand(2))->getMaybeAlignValue(); 10693 EVT VT = Node->getValueType(0); 10694 10695 if (DAG.getMachineFunction().getFunction().hasFnAttribute( 10696 "no-stack-arg-probe")) { 10697 SDValue SP = DAG.getCopyFromReg(Chain, dl, AArch64::SP, MVT::i64); 10698 Chain = SP.getValue(1); 10699 SP = DAG.getNode(ISD::SUB, dl, MVT::i64, SP, Size); 10700 if (Align) 10701 SP = DAG.getNode(ISD::AND, dl, VT, SP.getValue(0), 10702 DAG.getConstant(-(uint64_t)Align->value(), dl, VT)); 10703 Chain = DAG.getCopyToReg(Chain, dl, AArch64::SP, SP); 10704 SDValue Ops[2] = {SP, Chain}; 10705 return DAG.getMergeValues(Ops, dl); 10706 } 10707 10708 Chain = DAG.getCALLSEQ_START(Chain, 0, 0, dl); 10709 10710 Chain = LowerWindowsDYNAMIC_STACKALLOC(Op, Chain, Size, DAG); 10711 10712 SDValue SP = DAG.getCopyFromReg(Chain, dl, AArch64::SP, MVT::i64); 10713 Chain = SP.getValue(1); 10714 SP = DAG.getNode(ISD::SUB, dl, MVT::i64, SP, Size); 10715 if (Align) 10716 SP = DAG.getNode(ISD::AND, dl, VT, SP.getValue(0), 10717 DAG.getConstant(-(uint64_t)Align->value(), dl, VT)); 10718 Chain = DAG.getCopyToReg(Chain, dl, AArch64::SP, SP); 10719 10720 Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(0, dl, true), 10721 DAG.getIntPtrConstant(0, dl, true), SDValue(), dl); 10722 10723 SDValue Ops[2] = {SP, Chain}; 10724 return DAG.getMergeValues(Ops, dl); 10725 } 10726 10727 SDValue AArch64TargetLowering::LowerVSCALE(SDValue Op, 10728 SelectionDAG &DAG) const { 10729 EVT VT = Op.getValueType(); 10730 assert(VT != MVT::i64 && "Expected illegal VSCALE node"); 10731 10732 SDLoc DL(Op); 10733 APInt MulImm = cast<ConstantSDNode>(Op.getOperand(0))->getAPIntValue(); 10734 return DAG.getZExtOrTrunc(DAG.getVScale(DL, MVT::i64, MulImm.sextOrSelf(64)), 10735 DL, VT); 10736 } 10737 10738 /// Set the IntrinsicInfo for the `aarch64_sve_st<N>` intrinsics. 10739 template <unsigned NumVecs> 10740 static bool 10741 setInfoSVEStN(const AArch64TargetLowering &TLI, const DataLayout &DL, 10742 AArch64TargetLowering::IntrinsicInfo &Info, const CallInst &CI) { 10743 Info.opc = ISD::INTRINSIC_VOID; 10744 // Retrieve EC from first vector argument. 10745 const EVT VT = TLI.getMemValueType(DL, CI.getArgOperand(0)->getType()); 10746 ElementCount EC = VT.getVectorElementCount(); 10747 #ifndef NDEBUG 10748 // Check the assumption that all input vectors are the same type. 10749 for (unsigned I = 0; I < NumVecs; ++I) 10750 assert(VT == TLI.getMemValueType(DL, CI.getArgOperand(I)->getType()) && 10751 "Invalid type."); 10752 #endif 10753 // memVT is `NumVecs * VT`. 10754 Info.memVT = EVT::getVectorVT(CI.getType()->getContext(), VT.getScalarType(), 10755 EC * NumVecs); 10756 Info.ptrVal = CI.getArgOperand(CI.getNumArgOperands() - 1); 10757 Info.offset = 0; 10758 Info.align.reset(); 10759 Info.flags = MachineMemOperand::MOStore; 10760 return true; 10761 } 10762 10763 /// getTgtMemIntrinsic - Represent NEON load and store intrinsics as 10764 /// MemIntrinsicNodes. The associated MachineMemOperands record the alignment 10765 /// specified in the intrinsic calls. 10766 bool AArch64TargetLowering::getTgtMemIntrinsic(IntrinsicInfo &Info, 10767 const CallInst &I, 10768 MachineFunction &MF, 10769 unsigned Intrinsic) const { 10770 auto &DL = I.getModule()->getDataLayout(); 10771 switch (Intrinsic) { 10772 case Intrinsic::aarch64_sve_st2: 10773 return setInfoSVEStN<2>(*this, DL, Info, I); 10774 case Intrinsic::aarch64_sve_st3: 10775 return setInfoSVEStN<3>(*this, DL, Info, I); 10776 case Intrinsic::aarch64_sve_st4: 10777 return setInfoSVEStN<4>(*this, DL, Info, I); 10778 case Intrinsic::aarch64_neon_ld2: 10779 case Intrinsic::aarch64_neon_ld3: 10780 case Intrinsic::aarch64_neon_ld4: 10781 case Intrinsic::aarch64_neon_ld1x2: 10782 case Intrinsic::aarch64_neon_ld1x3: 10783 case Intrinsic::aarch64_neon_ld1x4: 10784 case Intrinsic::aarch64_neon_ld2lane: 10785 case Intrinsic::aarch64_neon_ld3lane: 10786 case Intrinsic::aarch64_neon_ld4lane: 10787 case Intrinsic::aarch64_neon_ld2r: 10788 case Intrinsic::aarch64_neon_ld3r: 10789 case Intrinsic::aarch64_neon_ld4r: { 10790 Info.opc = ISD::INTRINSIC_W_CHAIN; 10791 // Conservatively set memVT to the entire set of vectors loaded. 10792 uint64_t NumElts = DL.getTypeSizeInBits(I.getType()) / 64; 10793 Info.memVT = EVT::getVectorVT(I.getType()->getContext(), MVT::i64, NumElts); 10794 Info.ptrVal = I.getArgOperand(I.getNumArgOperands() - 1); 10795 Info.offset = 0; 10796 Info.align.reset(); 10797 // volatile loads with NEON intrinsics not supported 10798 Info.flags = MachineMemOperand::MOLoad; 10799 return true; 10800 } 10801 case Intrinsic::aarch64_neon_st2: 10802 case Intrinsic::aarch64_neon_st3: 10803 case Intrinsic::aarch64_neon_st4: 10804 case Intrinsic::aarch64_neon_st1x2: 10805 case Intrinsic::aarch64_neon_st1x3: 10806 case Intrinsic::aarch64_neon_st1x4: 10807 case Intrinsic::aarch64_neon_st2lane: 10808 case Intrinsic::aarch64_neon_st3lane: 10809 case Intrinsic::aarch64_neon_st4lane: { 10810 Info.opc = ISD::INTRINSIC_VOID; 10811 // Conservatively set memVT to the entire set of vectors stored. 10812 unsigned NumElts = 0; 10813 for (unsigned ArgI = 0, ArgE = I.getNumArgOperands(); ArgI < ArgE; ++ArgI) { 10814 Type *ArgTy = I.getArgOperand(ArgI)->getType(); 10815 if (!ArgTy->isVectorTy()) 10816 break; 10817 NumElts += DL.getTypeSizeInBits(ArgTy) / 64; 10818 } 10819 Info.memVT = EVT::getVectorVT(I.getType()->getContext(), MVT::i64, NumElts); 10820 Info.ptrVal = I.getArgOperand(I.getNumArgOperands() - 1); 10821 Info.offset = 0; 10822 Info.align.reset(); 10823 // volatile stores with NEON intrinsics not supported 10824 Info.flags = MachineMemOperand::MOStore; 10825 return true; 10826 } 10827 case Intrinsic::aarch64_ldaxr: 10828 case Intrinsic::aarch64_ldxr: { 10829 PointerType *PtrTy = cast<PointerType>(I.getArgOperand(0)->getType()); 10830 Info.opc = ISD::INTRINSIC_W_CHAIN; 10831 Info.memVT = MVT::getVT(PtrTy->getElementType()); 10832 Info.ptrVal = I.getArgOperand(0); 10833 Info.offset = 0; 10834 Info.align = DL.getABITypeAlign(PtrTy->getElementType()); 10835 Info.flags = MachineMemOperand::MOLoad | MachineMemOperand::MOVolatile; 10836 return true; 10837 } 10838 case Intrinsic::aarch64_stlxr: 10839 case Intrinsic::aarch64_stxr: { 10840 PointerType *PtrTy = cast<PointerType>(I.getArgOperand(1)->getType()); 10841 Info.opc = ISD::INTRINSIC_W_CHAIN; 10842 Info.memVT = MVT::getVT(PtrTy->getElementType()); 10843 Info.ptrVal = I.getArgOperand(1); 10844 Info.offset = 0; 10845 Info.align = DL.getABITypeAlign(PtrTy->getElementType()); 10846 Info.flags = MachineMemOperand::MOStore | MachineMemOperand::MOVolatile; 10847 return true; 10848 } 10849 case Intrinsic::aarch64_ldaxp: 10850 case Intrinsic::aarch64_ldxp: 10851 Info.opc = ISD::INTRINSIC_W_CHAIN; 10852 Info.memVT = MVT::i128; 10853 Info.ptrVal = I.getArgOperand(0); 10854 Info.offset = 0; 10855 Info.align = Align(16); 10856 Info.flags = MachineMemOperand::MOLoad | MachineMemOperand::MOVolatile; 10857 return true; 10858 case Intrinsic::aarch64_stlxp: 10859 case Intrinsic::aarch64_stxp: 10860 Info.opc = ISD::INTRINSIC_W_CHAIN; 10861 Info.memVT = MVT::i128; 10862 Info.ptrVal = I.getArgOperand(2); 10863 Info.offset = 0; 10864 Info.align = Align(16); 10865 Info.flags = MachineMemOperand::MOStore | MachineMemOperand::MOVolatile; 10866 return true; 10867 case Intrinsic::aarch64_sve_ldnt1: { 10868 PointerType *PtrTy = cast<PointerType>(I.getArgOperand(1)->getType()); 10869 Info.opc = ISD::INTRINSIC_W_CHAIN; 10870 Info.memVT = MVT::getVT(I.getType()); 10871 Info.ptrVal = I.getArgOperand(1); 10872 Info.offset = 0; 10873 Info.align = DL.getABITypeAlign(PtrTy->getElementType()); 10874 Info.flags = MachineMemOperand::MOLoad; 10875 if (Intrinsic == Intrinsic::aarch64_sve_ldnt1) 10876 Info.flags |= MachineMemOperand::MONonTemporal; 10877 return true; 10878 } 10879 case Intrinsic::aarch64_sve_stnt1: { 10880 PointerType *PtrTy = cast<PointerType>(I.getArgOperand(2)->getType()); 10881 Info.opc = ISD::INTRINSIC_W_CHAIN; 10882 Info.memVT = MVT::getVT(I.getOperand(0)->getType()); 10883 Info.ptrVal = I.getArgOperand(2); 10884 Info.offset = 0; 10885 Info.align = DL.getABITypeAlign(PtrTy->getElementType()); 10886 Info.flags = MachineMemOperand::MOStore; 10887 if (Intrinsic == Intrinsic::aarch64_sve_stnt1) 10888 Info.flags |= MachineMemOperand::MONonTemporal; 10889 return true; 10890 } 10891 default: 10892 break; 10893 } 10894 10895 return false; 10896 } 10897 10898 bool AArch64TargetLowering::shouldReduceLoadWidth(SDNode *Load, 10899 ISD::LoadExtType ExtTy, 10900 EVT NewVT) const { 10901 // TODO: This may be worth removing. Check regression tests for diffs. 10902 if (!TargetLoweringBase::shouldReduceLoadWidth(Load, ExtTy, NewVT)) 10903 return false; 10904 10905 // If we're reducing the load width in order to avoid having to use an extra 10906 // instruction to do extension then it's probably a good idea. 10907 if (ExtTy != ISD::NON_EXTLOAD) 10908 return true; 10909 // Don't reduce load width if it would prevent us from combining a shift into 10910 // the offset. 10911 MemSDNode *Mem = dyn_cast<MemSDNode>(Load); 10912 assert(Mem); 10913 const SDValue &Base = Mem->getBasePtr(); 10914 if (Base.getOpcode() == ISD::ADD && 10915 Base.getOperand(1).getOpcode() == ISD::SHL && 10916 Base.getOperand(1).hasOneUse() && 10917 Base.getOperand(1).getOperand(1).getOpcode() == ISD::Constant) { 10918 // The shift can be combined if it matches the size of the value being 10919 // loaded (and so reducing the width would make it not match). 10920 uint64_t ShiftAmount = Base.getOperand(1).getConstantOperandVal(1); 10921 uint64_t LoadBytes = Mem->getMemoryVT().getSizeInBits()/8; 10922 if (ShiftAmount == Log2_32(LoadBytes)) 10923 return false; 10924 } 10925 // We have no reason to disallow reducing the load width, so allow it. 10926 return true; 10927 } 10928 10929 // Truncations from 64-bit GPR to 32-bit GPR is free. 10930 bool AArch64TargetLowering::isTruncateFree(Type *Ty1, Type *Ty2) const { 10931 if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy()) 10932 return false; 10933 uint64_t NumBits1 = Ty1->getPrimitiveSizeInBits().getFixedSize(); 10934 uint64_t NumBits2 = Ty2->getPrimitiveSizeInBits().getFixedSize(); 10935 return NumBits1 > NumBits2; 10936 } 10937 bool AArch64TargetLowering::isTruncateFree(EVT VT1, EVT VT2) const { 10938 if (VT1.isVector() || VT2.isVector() || !VT1.isInteger() || !VT2.isInteger()) 10939 return false; 10940 uint64_t NumBits1 = VT1.getFixedSizeInBits(); 10941 uint64_t NumBits2 = VT2.getFixedSizeInBits(); 10942 return NumBits1 > NumBits2; 10943 } 10944 10945 /// Check if it is profitable to hoist instruction in then/else to if. 10946 /// Not profitable if I and it's user can form a FMA instruction 10947 /// because we prefer FMSUB/FMADD. 10948 bool AArch64TargetLowering::isProfitableToHoist(Instruction *I) const { 10949 if (I->getOpcode() != Instruction::FMul) 10950 return true; 10951 10952 if (!I->hasOneUse()) 10953 return true; 10954 10955 Instruction *User = I->user_back(); 10956 10957 if (User && 10958 !(User->getOpcode() == Instruction::FSub || 10959 User->getOpcode() == Instruction::FAdd)) 10960 return true; 10961 10962 const TargetOptions &Options = getTargetMachine().Options; 10963 const Function *F = I->getFunction(); 10964 const DataLayout &DL = F->getParent()->getDataLayout(); 10965 Type *Ty = User->getOperand(0)->getType(); 10966 10967 return !(isFMAFasterThanFMulAndFAdd(*F, Ty) && 10968 isOperationLegalOrCustom(ISD::FMA, getValueType(DL, Ty)) && 10969 (Options.AllowFPOpFusion == FPOpFusion::Fast || 10970 Options.UnsafeFPMath)); 10971 } 10972 10973 // All 32-bit GPR operations implicitly zero the high-half of the corresponding 10974 // 64-bit GPR. 10975 bool AArch64TargetLowering::isZExtFree(Type *Ty1, Type *Ty2) const { 10976 if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy()) 10977 return false; 10978 unsigned NumBits1 = Ty1->getPrimitiveSizeInBits(); 10979 unsigned NumBits2 = Ty2->getPrimitiveSizeInBits(); 10980 return NumBits1 == 32 && NumBits2 == 64; 10981 } 10982 bool AArch64TargetLowering::isZExtFree(EVT VT1, EVT VT2) const { 10983 if (VT1.isVector() || VT2.isVector() || !VT1.isInteger() || !VT2.isInteger()) 10984 return false; 10985 unsigned NumBits1 = VT1.getSizeInBits(); 10986 unsigned NumBits2 = VT2.getSizeInBits(); 10987 return NumBits1 == 32 && NumBits2 == 64; 10988 } 10989 10990 bool AArch64TargetLowering::isZExtFree(SDValue Val, EVT VT2) const { 10991 EVT VT1 = Val.getValueType(); 10992 if (isZExtFree(VT1, VT2)) { 10993 return true; 10994 } 10995 10996 if (Val.getOpcode() != ISD::LOAD) 10997 return false; 10998 10999 // 8-, 16-, and 32-bit integer loads all implicitly zero-extend. 11000 return (VT1.isSimple() && !VT1.isVector() && VT1.isInteger() && 11001 VT2.isSimple() && !VT2.isVector() && VT2.isInteger() && 11002 VT1.getSizeInBits() <= 32); 11003 } 11004 11005 bool AArch64TargetLowering::isExtFreeImpl(const Instruction *Ext) const { 11006 if (isa<FPExtInst>(Ext)) 11007 return false; 11008 11009 // Vector types are not free. 11010 if (Ext->getType()->isVectorTy()) 11011 return false; 11012 11013 for (const Use &U : Ext->uses()) { 11014 // The extension is free if we can fold it with a left shift in an 11015 // addressing mode or an arithmetic operation: add, sub, and cmp. 11016 11017 // Is there a shift? 11018 const Instruction *Instr = cast<Instruction>(U.getUser()); 11019 11020 // Is this a constant shift? 11021 switch (Instr->getOpcode()) { 11022 case Instruction::Shl: 11023 if (!isa<ConstantInt>(Instr->getOperand(1))) 11024 return false; 11025 break; 11026 case Instruction::GetElementPtr: { 11027 gep_type_iterator GTI = gep_type_begin(Instr); 11028 auto &DL = Ext->getModule()->getDataLayout(); 11029 std::advance(GTI, U.getOperandNo()-1); 11030 Type *IdxTy = GTI.getIndexedType(); 11031 // This extension will end up with a shift because of the scaling factor. 11032 // 8-bit sized types have a scaling factor of 1, thus a shift amount of 0. 11033 // Get the shift amount based on the scaling factor: 11034 // log2(sizeof(IdxTy)) - log2(8). 11035 uint64_t ShiftAmt = 11036 countTrailingZeros(DL.getTypeStoreSizeInBits(IdxTy).getFixedSize()) - 3; 11037 // Is the constant foldable in the shift of the addressing mode? 11038 // I.e., shift amount is between 1 and 4 inclusive. 11039 if (ShiftAmt == 0 || ShiftAmt > 4) 11040 return false; 11041 break; 11042 } 11043 case Instruction::Trunc: 11044 // Check if this is a noop. 11045 // trunc(sext ty1 to ty2) to ty1. 11046 if (Instr->getType() == Ext->getOperand(0)->getType()) 11047 continue; 11048 LLVM_FALLTHROUGH; 11049 default: 11050 return false; 11051 } 11052 11053 // At this point we can use the bfm family, so this extension is free 11054 // for that use. 11055 } 11056 return true; 11057 } 11058 11059 /// Check if both Op1 and Op2 are shufflevector extracts of either the lower 11060 /// or upper half of the vector elements. 11061 static bool areExtractShuffleVectors(Value *Op1, Value *Op2) { 11062 auto areTypesHalfed = [](Value *FullV, Value *HalfV) { 11063 auto *FullTy = FullV->getType(); 11064 auto *HalfTy = HalfV->getType(); 11065 return FullTy->getPrimitiveSizeInBits().getFixedSize() == 11066 2 * HalfTy->getPrimitiveSizeInBits().getFixedSize(); 11067 }; 11068 11069 auto extractHalf = [](Value *FullV, Value *HalfV) { 11070 auto *FullVT = cast<FixedVectorType>(FullV->getType()); 11071 auto *HalfVT = cast<FixedVectorType>(HalfV->getType()); 11072 return FullVT->getNumElements() == 2 * HalfVT->getNumElements(); 11073 }; 11074 11075 ArrayRef<int> M1, M2; 11076 Value *S1Op1, *S2Op1; 11077 if (!match(Op1, m_Shuffle(m_Value(S1Op1), m_Undef(), m_Mask(M1))) || 11078 !match(Op2, m_Shuffle(m_Value(S2Op1), m_Undef(), m_Mask(M2)))) 11079 return false; 11080 11081 // Check that the operands are half as wide as the result and we extract 11082 // half of the elements of the input vectors. 11083 if (!areTypesHalfed(S1Op1, Op1) || !areTypesHalfed(S2Op1, Op2) || 11084 !extractHalf(S1Op1, Op1) || !extractHalf(S2Op1, Op2)) 11085 return false; 11086 11087 // Check the mask extracts either the lower or upper half of vector 11088 // elements. 11089 int M1Start = -1; 11090 int M2Start = -1; 11091 int NumElements = cast<FixedVectorType>(Op1->getType())->getNumElements() * 2; 11092 if (!ShuffleVectorInst::isExtractSubvectorMask(M1, NumElements, M1Start) || 11093 !ShuffleVectorInst::isExtractSubvectorMask(M2, NumElements, M2Start) || 11094 M1Start != M2Start || (M1Start != 0 && M2Start != (NumElements / 2))) 11095 return false; 11096 11097 return true; 11098 } 11099 11100 /// Check if Ext1 and Ext2 are extends of the same type, doubling the bitwidth 11101 /// of the vector elements. 11102 static bool areExtractExts(Value *Ext1, Value *Ext2) { 11103 auto areExtDoubled = [](Instruction *Ext) { 11104 return Ext->getType()->getScalarSizeInBits() == 11105 2 * Ext->getOperand(0)->getType()->getScalarSizeInBits(); 11106 }; 11107 11108 if (!match(Ext1, m_ZExtOrSExt(m_Value())) || 11109 !match(Ext2, m_ZExtOrSExt(m_Value())) || 11110 !areExtDoubled(cast<Instruction>(Ext1)) || 11111 !areExtDoubled(cast<Instruction>(Ext2))) 11112 return false; 11113 11114 return true; 11115 } 11116 11117 /// Check if Op could be used with vmull_high_p64 intrinsic. 11118 static bool isOperandOfVmullHighP64(Value *Op) { 11119 Value *VectorOperand = nullptr; 11120 ConstantInt *ElementIndex = nullptr; 11121 return match(Op, m_ExtractElt(m_Value(VectorOperand), 11122 m_ConstantInt(ElementIndex))) && 11123 ElementIndex->getValue() == 1 && 11124 isa<FixedVectorType>(VectorOperand->getType()) && 11125 cast<FixedVectorType>(VectorOperand->getType())->getNumElements() == 2; 11126 } 11127 11128 /// Check if Op1 and Op2 could be used with vmull_high_p64 intrinsic. 11129 static bool areOperandsOfVmullHighP64(Value *Op1, Value *Op2) { 11130 return isOperandOfVmullHighP64(Op1) && isOperandOfVmullHighP64(Op2); 11131 } 11132 11133 /// Check if sinking \p I's operands to I's basic block is profitable, because 11134 /// the operands can be folded into a target instruction, e.g. 11135 /// shufflevectors extracts and/or sext/zext can be folded into (u,s)subl(2). 11136 bool AArch64TargetLowering::shouldSinkOperands( 11137 Instruction *I, SmallVectorImpl<Use *> &Ops) const { 11138 if (!I->getType()->isVectorTy()) 11139 return false; 11140 11141 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(I)) { 11142 switch (II->getIntrinsicID()) { 11143 case Intrinsic::aarch64_neon_umull: 11144 if (!areExtractShuffleVectors(II->getOperand(0), II->getOperand(1))) 11145 return false; 11146 Ops.push_back(&II->getOperandUse(0)); 11147 Ops.push_back(&II->getOperandUse(1)); 11148 return true; 11149 11150 case Intrinsic::aarch64_neon_pmull64: 11151 if (!areOperandsOfVmullHighP64(II->getArgOperand(0), 11152 II->getArgOperand(1))) 11153 return false; 11154 Ops.push_back(&II->getArgOperandUse(0)); 11155 Ops.push_back(&II->getArgOperandUse(1)); 11156 return true; 11157 11158 default: 11159 return false; 11160 } 11161 } 11162 11163 switch (I->getOpcode()) { 11164 case Instruction::Sub: 11165 case Instruction::Add: { 11166 if (!areExtractExts(I->getOperand(0), I->getOperand(1))) 11167 return false; 11168 11169 // If the exts' operands extract either the lower or upper elements, we 11170 // can sink them too. 11171 auto Ext1 = cast<Instruction>(I->getOperand(0)); 11172 auto Ext2 = cast<Instruction>(I->getOperand(1)); 11173 if (areExtractShuffleVectors(Ext1, Ext2)) { 11174 Ops.push_back(&Ext1->getOperandUse(0)); 11175 Ops.push_back(&Ext2->getOperandUse(0)); 11176 } 11177 11178 Ops.push_back(&I->getOperandUse(0)); 11179 Ops.push_back(&I->getOperandUse(1)); 11180 11181 return true; 11182 } 11183 case Instruction::Mul: { 11184 bool IsProfitable = false; 11185 for (auto &Op : I->operands()) { 11186 // Make sure we are not already sinking this operand 11187 if (any_of(Ops, [&](Use *U) { return U->get() == Op; })) 11188 continue; 11189 11190 ShuffleVectorInst *Shuffle = dyn_cast<ShuffleVectorInst>(Op); 11191 if (!Shuffle || !Shuffle->isZeroEltSplat()) 11192 continue; 11193 11194 Value *ShuffleOperand = Shuffle->getOperand(0); 11195 InsertElementInst *Insert = dyn_cast<InsertElementInst>(ShuffleOperand); 11196 if (!Insert) 11197 continue; 11198 11199 Instruction *OperandInstr = dyn_cast<Instruction>(Insert->getOperand(1)); 11200 if (!OperandInstr) 11201 continue; 11202 11203 ConstantInt *ElementConstant = 11204 dyn_cast<ConstantInt>(Insert->getOperand(2)); 11205 // Check that the insertelement is inserting into element 0 11206 if (!ElementConstant || ElementConstant->getZExtValue() != 0) 11207 continue; 11208 11209 unsigned Opcode = OperandInstr->getOpcode(); 11210 if (Opcode != Instruction::SExt && Opcode != Instruction::ZExt) 11211 continue; 11212 11213 Ops.push_back(&Shuffle->getOperandUse(0)); 11214 Ops.push_back(&Op); 11215 IsProfitable = true; 11216 } 11217 11218 return IsProfitable; 11219 } 11220 default: 11221 return false; 11222 } 11223 return false; 11224 } 11225 11226 bool AArch64TargetLowering::hasPairedLoad(EVT LoadedType, 11227 Align &RequiredAligment) const { 11228 if (!LoadedType.isSimple() || 11229 (!LoadedType.isInteger() && !LoadedType.isFloatingPoint())) 11230 return false; 11231 // Cyclone supports unaligned accesses. 11232 RequiredAligment = Align(1); 11233 unsigned NumBits = LoadedType.getSizeInBits(); 11234 return NumBits == 32 || NumBits == 64; 11235 } 11236 11237 /// A helper function for determining the number of interleaved accesses we 11238 /// will generate when lowering accesses of the given type. 11239 unsigned 11240 AArch64TargetLowering::getNumInterleavedAccesses(VectorType *VecTy, 11241 const DataLayout &DL) const { 11242 return (DL.getTypeSizeInBits(VecTy) + 127) / 128; 11243 } 11244 11245 MachineMemOperand::Flags 11246 AArch64TargetLowering::getTargetMMOFlags(const Instruction &I) const { 11247 if (Subtarget->getProcFamily() == AArch64Subtarget::Falkor && 11248 I.getMetadata(FALKOR_STRIDED_ACCESS_MD) != nullptr) 11249 return MOStridedAccess; 11250 return MachineMemOperand::MONone; 11251 } 11252 11253 bool AArch64TargetLowering::isLegalInterleavedAccessType( 11254 VectorType *VecTy, const DataLayout &DL) const { 11255 11256 unsigned VecSize = DL.getTypeSizeInBits(VecTy); 11257 unsigned ElSize = DL.getTypeSizeInBits(VecTy->getElementType()); 11258 11259 // Ensure the number of vector elements is greater than 1. 11260 if (cast<FixedVectorType>(VecTy)->getNumElements() < 2) 11261 return false; 11262 11263 // Ensure the element type is legal. 11264 if (ElSize != 8 && ElSize != 16 && ElSize != 32 && ElSize != 64) 11265 return false; 11266 11267 // Ensure the total vector size is 64 or a multiple of 128. Types larger than 11268 // 128 will be split into multiple interleaved accesses. 11269 return VecSize == 64 || VecSize % 128 == 0; 11270 } 11271 11272 /// Lower an interleaved load into a ldN intrinsic. 11273 /// 11274 /// E.g. Lower an interleaved load (Factor = 2): 11275 /// %wide.vec = load <8 x i32>, <8 x i32>* %ptr 11276 /// %v0 = shuffle %wide.vec, undef, <0, 2, 4, 6> ; Extract even elements 11277 /// %v1 = shuffle %wide.vec, undef, <1, 3, 5, 7> ; Extract odd elements 11278 /// 11279 /// Into: 11280 /// %ld2 = { <4 x i32>, <4 x i32> } call llvm.aarch64.neon.ld2(%ptr) 11281 /// %vec0 = extractelement { <4 x i32>, <4 x i32> } %ld2, i32 0 11282 /// %vec1 = extractelement { <4 x i32>, <4 x i32> } %ld2, i32 1 11283 bool AArch64TargetLowering::lowerInterleavedLoad( 11284 LoadInst *LI, ArrayRef<ShuffleVectorInst *> Shuffles, 11285 ArrayRef<unsigned> Indices, unsigned Factor) const { 11286 assert(Factor >= 2 && Factor <= getMaxSupportedInterleaveFactor() && 11287 "Invalid interleave factor"); 11288 assert(!Shuffles.empty() && "Empty shufflevector input"); 11289 assert(Shuffles.size() == Indices.size() && 11290 "Unmatched number of shufflevectors and indices"); 11291 11292 const DataLayout &DL = LI->getModule()->getDataLayout(); 11293 11294 VectorType *VTy = Shuffles[0]->getType(); 11295 11296 // Skip if we do not have NEON and skip illegal vector types. We can 11297 // "legalize" wide vector types into multiple interleaved accesses as long as 11298 // the vector types are divisible by 128. 11299 if (!Subtarget->hasNEON() || !isLegalInterleavedAccessType(VTy, DL)) 11300 return false; 11301 11302 unsigned NumLoads = getNumInterleavedAccesses(VTy, DL); 11303 11304 auto *FVTy = cast<FixedVectorType>(VTy); 11305 11306 // A pointer vector can not be the return type of the ldN intrinsics. Need to 11307 // load integer vectors first and then convert to pointer vectors. 11308 Type *EltTy = FVTy->getElementType(); 11309 if (EltTy->isPointerTy()) 11310 FVTy = 11311 FixedVectorType::get(DL.getIntPtrType(EltTy), FVTy->getNumElements()); 11312 11313 IRBuilder<> Builder(LI); 11314 11315 // The base address of the load. 11316 Value *BaseAddr = LI->getPointerOperand(); 11317 11318 if (NumLoads > 1) { 11319 // If we're going to generate more than one load, reset the sub-vector type 11320 // to something legal. 11321 FVTy = FixedVectorType::get(FVTy->getElementType(), 11322 FVTy->getNumElements() / NumLoads); 11323 11324 // We will compute the pointer operand of each load from the original base 11325 // address using GEPs. Cast the base address to a pointer to the scalar 11326 // element type. 11327 BaseAddr = Builder.CreateBitCast( 11328 BaseAddr, 11329 FVTy->getElementType()->getPointerTo(LI->getPointerAddressSpace())); 11330 } 11331 11332 Type *PtrTy = FVTy->getPointerTo(LI->getPointerAddressSpace()); 11333 Type *Tys[2] = {FVTy, PtrTy}; 11334 static const Intrinsic::ID LoadInts[3] = {Intrinsic::aarch64_neon_ld2, 11335 Intrinsic::aarch64_neon_ld3, 11336 Intrinsic::aarch64_neon_ld4}; 11337 Function *LdNFunc = 11338 Intrinsic::getDeclaration(LI->getModule(), LoadInts[Factor - 2], Tys); 11339 11340 // Holds sub-vectors extracted from the load intrinsic return values. The 11341 // sub-vectors are associated with the shufflevector instructions they will 11342 // replace. 11343 DenseMap<ShuffleVectorInst *, SmallVector<Value *, 4>> SubVecs; 11344 11345 for (unsigned LoadCount = 0; LoadCount < NumLoads; ++LoadCount) { 11346 11347 // If we're generating more than one load, compute the base address of 11348 // subsequent loads as an offset from the previous. 11349 if (LoadCount > 0) 11350 BaseAddr = Builder.CreateConstGEP1_32(FVTy->getElementType(), BaseAddr, 11351 FVTy->getNumElements() * Factor); 11352 11353 CallInst *LdN = Builder.CreateCall( 11354 LdNFunc, Builder.CreateBitCast(BaseAddr, PtrTy), "ldN"); 11355 11356 // Extract and store the sub-vectors returned by the load intrinsic. 11357 for (unsigned i = 0; i < Shuffles.size(); i++) { 11358 ShuffleVectorInst *SVI = Shuffles[i]; 11359 unsigned Index = Indices[i]; 11360 11361 Value *SubVec = Builder.CreateExtractValue(LdN, Index); 11362 11363 // Convert the integer vector to pointer vector if the element is pointer. 11364 if (EltTy->isPointerTy()) 11365 SubVec = Builder.CreateIntToPtr( 11366 SubVec, FixedVectorType::get(SVI->getType()->getElementType(), 11367 FVTy->getNumElements())); 11368 SubVecs[SVI].push_back(SubVec); 11369 } 11370 } 11371 11372 // Replace uses of the shufflevector instructions with the sub-vectors 11373 // returned by the load intrinsic. If a shufflevector instruction is 11374 // associated with more than one sub-vector, those sub-vectors will be 11375 // concatenated into a single wide vector. 11376 for (ShuffleVectorInst *SVI : Shuffles) { 11377 auto &SubVec = SubVecs[SVI]; 11378 auto *WideVec = 11379 SubVec.size() > 1 ? concatenateVectors(Builder, SubVec) : SubVec[0]; 11380 SVI->replaceAllUsesWith(WideVec); 11381 } 11382 11383 return true; 11384 } 11385 11386 /// Lower an interleaved store into a stN intrinsic. 11387 /// 11388 /// E.g. Lower an interleaved store (Factor = 3): 11389 /// %i.vec = shuffle <8 x i32> %v0, <8 x i32> %v1, 11390 /// <0, 4, 8, 1, 5, 9, 2, 6, 10, 3, 7, 11> 11391 /// store <12 x i32> %i.vec, <12 x i32>* %ptr 11392 /// 11393 /// Into: 11394 /// %sub.v0 = shuffle <8 x i32> %v0, <8 x i32> v1, <0, 1, 2, 3> 11395 /// %sub.v1 = shuffle <8 x i32> %v0, <8 x i32> v1, <4, 5, 6, 7> 11396 /// %sub.v2 = shuffle <8 x i32> %v0, <8 x i32> v1, <8, 9, 10, 11> 11397 /// call void llvm.aarch64.neon.st3(%sub.v0, %sub.v1, %sub.v2, %ptr) 11398 /// 11399 /// Note that the new shufflevectors will be removed and we'll only generate one 11400 /// st3 instruction in CodeGen. 11401 /// 11402 /// Example for a more general valid mask (Factor 3). Lower: 11403 /// %i.vec = shuffle <32 x i32> %v0, <32 x i32> %v1, 11404 /// <4, 32, 16, 5, 33, 17, 6, 34, 18, 7, 35, 19> 11405 /// store <12 x i32> %i.vec, <12 x i32>* %ptr 11406 /// 11407 /// Into: 11408 /// %sub.v0 = shuffle <32 x i32> %v0, <32 x i32> v1, <4, 5, 6, 7> 11409 /// %sub.v1 = shuffle <32 x i32> %v0, <32 x i32> v1, <32, 33, 34, 35> 11410 /// %sub.v2 = shuffle <32 x i32> %v0, <32 x i32> v1, <16, 17, 18, 19> 11411 /// call void llvm.aarch64.neon.st3(%sub.v0, %sub.v1, %sub.v2, %ptr) 11412 bool AArch64TargetLowering::lowerInterleavedStore(StoreInst *SI, 11413 ShuffleVectorInst *SVI, 11414 unsigned Factor) const { 11415 assert(Factor >= 2 && Factor <= getMaxSupportedInterleaveFactor() && 11416 "Invalid interleave factor"); 11417 11418 auto *VecTy = cast<FixedVectorType>(SVI->getType()); 11419 assert(VecTy->getNumElements() % Factor == 0 && "Invalid interleaved store"); 11420 11421 unsigned LaneLen = VecTy->getNumElements() / Factor; 11422 Type *EltTy = VecTy->getElementType(); 11423 auto *SubVecTy = FixedVectorType::get(EltTy, LaneLen); 11424 11425 const DataLayout &DL = SI->getModule()->getDataLayout(); 11426 11427 // Skip if we do not have NEON and skip illegal vector types. We can 11428 // "legalize" wide vector types into multiple interleaved accesses as long as 11429 // the vector types are divisible by 128. 11430 if (!Subtarget->hasNEON() || !isLegalInterleavedAccessType(SubVecTy, DL)) 11431 return false; 11432 11433 unsigned NumStores = getNumInterleavedAccesses(SubVecTy, DL); 11434 11435 Value *Op0 = SVI->getOperand(0); 11436 Value *Op1 = SVI->getOperand(1); 11437 IRBuilder<> Builder(SI); 11438 11439 // StN intrinsics don't support pointer vectors as arguments. Convert pointer 11440 // vectors to integer vectors. 11441 if (EltTy->isPointerTy()) { 11442 Type *IntTy = DL.getIntPtrType(EltTy); 11443 unsigned NumOpElts = 11444 cast<FixedVectorType>(Op0->getType())->getNumElements(); 11445 11446 // Convert to the corresponding integer vector. 11447 auto *IntVecTy = FixedVectorType::get(IntTy, NumOpElts); 11448 Op0 = Builder.CreatePtrToInt(Op0, IntVecTy); 11449 Op1 = Builder.CreatePtrToInt(Op1, IntVecTy); 11450 11451 SubVecTy = FixedVectorType::get(IntTy, LaneLen); 11452 } 11453 11454 // The base address of the store. 11455 Value *BaseAddr = SI->getPointerOperand(); 11456 11457 if (NumStores > 1) { 11458 // If we're going to generate more than one store, reset the lane length 11459 // and sub-vector type to something legal. 11460 LaneLen /= NumStores; 11461 SubVecTy = FixedVectorType::get(SubVecTy->getElementType(), LaneLen); 11462 11463 // We will compute the pointer operand of each store from the original base 11464 // address using GEPs. Cast the base address to a pointer to the scalar 11465 // element type. 11466 BaseAddr = Builder.CreateBitCast( 11467 BaseAddr, 11468 SubVecTy->getElementType()->getPointerTo(SI->getPointerAddressSpace())); 11469 } 11470 11471 auto Mask = SVI->getShuffleMask(); 11472 11473 Type *PtrTy = SubVecTy->getPointerTo(SI->getPointerAddressSpace()); 11474 Type *Tys[2] = {SubVecTy, PtrTy}; 11475 static const Intrinsic::ID StoreInts[3] = {Intrinsic::aarch64_neon_st2, 11476 Intrinsic::aarch64_neon_st3, 11477 Intrinsic::aarch64_neon_st4}; 11478 Function *StNFunc = 11479 Intrinsic::getDeclaration(SI->getModule(), StoreInts[Factor - 2], Tys); 11480 11481 for (unsigned StoreCount = 0; StoreCount < NumStores; ++StoreCount) { 11482 11483 SmallVector<Value *, 5> Ops; 11484 11485 // Split the shufflevector operands into sub vectors for the new stN call. 11486 for (unsigned i = 0; i < Factor; i++) { 11487 unsigned IdxI = StoreCount * LaneLen * Factor + i; 11488 if (Mask[IdxI] >= 0) { 11489 Ops.push_back(Builder.CreateShuffleVector( 11490 Op0, Op1, createSequentialMask(Mask[IdxI], LaneLen, 0))); 11491 } else { 11492 unsigned StartMask = 0; 11493 for (unsigned j = 1; j < LaneLen; j++) { 11494 unsigned IdxJ = StoreCount * LaneLen * Factor + j; 11495 if (Mask[IdxJ * Factor + IdxI] >= 0) { 11496 StartMask = Mask[IdxJ * Factor + IdxI] - IdxJ; 11497 break; 11498 } 11499 } 11500 // Note: Filling undef gaps with random elements is ok, since 11501 // those elements were being written anyway (with undefs). 11502 // In the case of all undefs we're defaulting to using elems from 0 11503 // Note: StartMask cannot be negative, it's checked in 11504 // isReInterleaveMask 11505 Ops.push_back(Builder.CreateShuffleVector( 11506 Op0, Op1, createSequentialMask(StartMask, LaneLen, 0))); 11507 } 11508 } 11509 11510 // If we generating more than one store, we compute the base address of 11511 // subsequent stores as an offset from the previous. 11512 if (StoreCount > 0) 11513 BaseAddr = Builder.CreateConstGEP1_32(SubVecTy->getElementType(), 11514 BaseAddr, LaneLen * Factor); 11515 11516 Ops.push_back(Builder.CreateBitCast(BaseAddr, PtrTy)); 11517 Builder.CreateCall(StNFunc, Ops); 11518 } 11519 return true; 11520 } 11521 11522 // Lower an SVE structured load intrinsic returning a tuple type to target 11523 // specific intrinsic taking the same input but returning a multi-result value 11524 // of the split tuple type. 11525 // 11526 // E.g. Lowering an LD3: 11527 // 11528 // call <vscale x 12 x i32> @llvm.aarch64.sve.ld3.nxv12i32( 11529 // <vscale x 4 x i1> %pred, 11530 // <vscale x 4 x i32>* %addr) 11531 // 11532 // Output DAG: 11533 // 11534 // t0: ch = EntryToken 11535 // t2: nxv4i1,ch = CopyFromReg t0, Register:nxv4i1 %0 11536 // t4: i64,ch = CopyFromReg t0, Register:i64 %1 11537 // t5: nxv4i32,nxv4i32,nxv4i32,ch = AArch64ISD::SVE_LD3 t0, t2, t4 11538 // t6: nxv12i32 = concat_vectors t5, t5:1, t5:2 11539 // 11540 // This is called pre-legalization to avoid widening/splitting issues with 11541 // non-power-of-2 tuple types used for LD3, such as nxv12i32. 11542 SDValue AArch64TargetLowering::LowerSVEStructLoad(unsigned Intrinsic, 11543 ArrayRef<SDValue> LoadOps, 11544 EVT VT, SelectionDAG &DAG, 11545 const SDLoc &DL) const { 11546 assert(VT.isScalableVector() && "Can only lower scalable vectors"); 11547 11548 unsigned N, Opcode; 11549 static std::map<unsigned, std::pair<unsigned, unsigned>> IntrinsicMap = { 11550 {Intrinsic::aarch64_sve_ld2, {2, AArch64ISD::SVE_LD2_MERGE_ZERO}}, 11551 {Intrinsic::aarch64_sve_ld3, {3, AArch64ISD::SVE_LD3_MERGE_ZERO}}, 11552 {Intrinsic::aarch64_sve_ld4, {4, AArch64ISD::SVE_LD4_MERGE_ZERO}}}; 11553 11554 std::tie(N, Opcode) = IntrinsicMap[Intrinsic]; 11555 assert(VT.getVectorElementCount().getKnownMinValue() % N == 0 && 11556 "invalid tuple vector type!"); 11557 11558 EVT SplitVT = 11559 EVT::getVectorVT(*DAG.getContext(), VT.getVectorElementType(), 11560 VT.getVectorElementCount().divideCoefficientBy(N)); 11561 assert(isTypeLegal(SplitVT)); 11562 11563 SmallVector<EVT, 5> VTs(N, SplitVT); 11564 VTs.push_back(MVT::Other); // Chain 11565 SDVTList NodeTys = DAG.getVTList(VTs); 11566 11567 SDValue PseudoLoad = DAG.getNode(Opcode, DL, NodeTys, LoadOps); 11568 SmallVector<SDValue, 4> PseudoLoadOps; 11569 for (unsigned I = 0; I < N; ++I) 11570 PseudoLoadOps.push_back(SDValue(PseudoLoad.getNode(), I)); 11571 return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, PseudoLoadOps); 11572 } 11573 11574 EVT AArch64TargetLowering::getOptimalMemOpType( 11575 const MemOp &Op, const AttributeList &FuncAttributes) const { 11576 bool CanImplicitFloat = 11577 !FuncAttributes.hasFnAttribute(Attribute::NoImplicitFloat); 11578 bool CanUseNEON = Subtarget->hasNEON() && CanImplicitFloat; 11579 bool CanUseFP = Subtarget->hasFPARMv8() && CanImplicitFloat; 11580 // Only use AdvSIMD to implement memset of 32-byte and above. It would have 11581 // taken one instruction to materialize the v2i64 zero and one store (with 11582 // restrictive addressing mode). Just do i64 stores. 11583 bool IsSmallMemset = Op.isMemset() && Op.size() < 32; 11584 auto AlignmentIsAcceptable = [&](EVT VT, Align AlignCheck) { 11585 if (Op.isAligned(AlignCheck)) 11586 return true; 11587 bool Fast; 11588 return allowsMisalignedMemoryAccesses(VT, 0, Align(1), 11589 MachineMemOperand::MONone, &Fast) && 11590 Fast; 11591 }; 11592 11593 if (CanUseNEON && Op.isMemset() && !IsSmallMemset && 11594 AlignmentIsAcceptable(MVT::v2i64, Align(16))) 11595 return MVT::v2i64; 11596 if (CanUseFP && !IsSmallMemset && AlignmentIsAcceptable(MVT::f128, Align(16))) 11597 return MVT::f128; 11598 if (Op.size() >= 8 && AlignmentIsAcceptable(MVT::i64, Align(8))) 11599 return MVT::i64; 11600 if (Op.size() >= 4 && AlignmentIsAcceptable(MVT::i32, Align(4))) 11601 return MVT::i32; 11602 return MVT::Other; 11603 } 11604 11605 LLT AArch64TargetLowering::getOptimalMemOpLLT( 11606 const MemOp &Op, const AttributeList &FuncAttributes) const { 11607 bool CanImplicitFloat = 11608 !FuncAttributes.hasFnAttribute(Attribute::NoImplicitFloat); 11609 bool CanUseNEON = Subtarget->hasNEON() && CanImplicitFloat; 11610 bool CanUseFP = Subtarget->hasFPARMv8() && CanImplicitFloat; 11611 // Only use AdvSIMD to implement memset of 32-byte and above. It would have 11612 // taken one instruction to materialize the v2i64 zero and one store (with 11613 // restrictive addressing mode). Just do i64 stores. 11614 bool IsSmallMemset = Op.isMemset() && Op.size() < 32; 11615 auto AlignmentIsAcceptable = [&](EVT VT, Align AlignCheck) { 11616 if (Op.isAligned(AlignCheck)) 11617 return true; 11618 bool Fast; 11619 return allowsMisalignedMemoryAccesses(VT, 0, Align(1), 11620 MachineMemOperand::MONone, &Fast) && 11621 Fast; 11622 }; 11623 11624 if (CanUseNEON && Op.isMemset() && !IsSmallMemset && 11625 AlignmentIsAcceptable(MVT::v2i64, Align(16))) 11626 return LLT::vector(2, 64); 11627 if (CanUseFP && !IsSmallMemset && AlignmentIsAcceptable(MVT::f128, Align(16))) 11628 return LLT::scalar(128); 11629 if (Op.size() >= 8 && AlignmentIsAcceptable(MVT::i64, Align(8))) 11630 return LLT::scalar(64); 11631 if (Op.size() >= 4 && AlignmentIsAcceptable(MVT::i32, Align(4))) 11632 return LLT::scalar(32); 11633 return LLT(); 11634 } 11635 11636 // 12-bit optionally shifted immediates are legal for adds. 11637 bool AArch64TargetLowering::isLegalAddImmediate(int64_t Immed) const { 11638 if (Immed == std::numeric_limits<int64_t>::min()) { 11639 LLVM_DEBUG(dbgs() << "Illegal add imm " << Immed 11640 << ": avoid UB for INT64_MIN\n"); 11641 return false; 11642 } 11643 // Same encoding for add/sub, just flip the sign. 11644 Immed = std::abs(Immed); 11645 bool IsLegal = ((Immed >> 12) == 0 || 11646 ((Immed & 0xfff) == 0 && Immed >> 24 == 0)); 11647 LLVM_DEBUG(dbgs() << "Is " << Immed 11648 << " legal add imm: " << (IsLegal ? "yes" : "no") << "\n"); 11649 return IsLegal; 11650 } 11651 11652 // Integer comparisons are implemented with ADDS/SUBS, so the range of valid 11653 // immediates is the same as for an add or a sub. 11654 bool AArch64TargetLowering::isLegalICmpImmediate(int64_t Immed) const { 11655 return isLegalAddImmediate(Immed); 11656 } 11657 11658 /// isLegalAddressingMode - Return true if the addressing mode represented 11659 /// by AM is legal for this target, for a load/store of the specified type. 11660 bool AArch64TargetLowering::isLegalAddressingMode(const DataLayout &DL, 11661 const AddrMode &AM, Type *Ty, 11662 unsigned AS, Instruction *I) const { 11663 // AArch64 has five basic addressing modes: 11664 // reg 11665 // reg + 9-bit signed offset 11666 // reg + SIZE_IN_BYTES * 12-bit unsigned offset 11667 // reg1 + reg2 11668 // reg + SIZE_IN_BYTES * reg 11669 11670 // No global is ever allowed as a base. 11671 if (AM.BaseGV) 11672 return false; 11673 11674 // No reg+reg+imm addressing. 11675 if (AM.HasBaseReg && AM.BaseOffs && AM.Scale) 11676 return false; 11677 11678 // FIXME: Update this method to support scalable addressing modes. 11679 if (isa<ScalableVectorType>(Ty)) 11680 return AM.HasBaseReg && !AM.BaseOffs && !AM.Scale; 11681 11682 // check reg + imm case: 11683 // i.e., reg + 0, reg + imm9, reg + SIZE_IN_BYTES * uimm12 11684 uint64_t NumBytes = 0; 11685 if (Ty->isSized()) { 11686 uint64_t NumBits = DL.getTypeSizeInBits(Ty); 11687 NumBytes = NumBits / 8; 11688 if (!isPowerOf2_64(NumBits)) 11689 NumBytes = 0; 11690 } 11691 11692 if (!AM.Scale) { 11693 int64_t Offset = AM.BaseOffs; 11694 11695 // 9-bit signed offset 11696 if (isInt<9>(Offset)) 11697 return true; 11698 11699 // 12-bit unsigned offset 11700 unsigned shift = Log2_64(NumBytes); 11701 if (NumBytes && Offset > 0 && (Offset / NumBytes) <= (1LL << 12) - 1 && 11702 // Must be a multiple of NumBytes (NumBytes is a power of 2) 11703 (Offset >> shift) << shift == Offset) 11704 return true; 11705 return false; 11706 } 11707 11708 // Check reg1 + SIZE_IN_BYTES * reg2 and reg1 + reg2 11709 11710 return AM.Scale == 1 || (AM.Scale > 0 && (uint64_t)AM.Scale == NumBytes); 11711 } 11712 11713 bool AArch64TargetLowering::shouldConsiderGEPOffsetSplit() const { 11714 // Consider splitting large offset of struct or array. 11715 return true; 11716 } 11717 11718 int AArch64TargetLowering::getScalingFactorCost(const DataLayout &DL, 11719 const AddrMode &AM, Type *Ty, 11720 unsigned AS) const { 11721 // Scaling factors are not free at all. 11722 // Operands | Rt Latency 11723 // ------------------------------------------- 11724 // Rt, [Xn, Xm] | 4 11725 // ------------------------------------------- 11726 // Rt, [Xn, Xm, lsl #imm] | Rn: 4 Rm: 5 11727 // Rt, [Xn, Wm, <extend> #imm] | 11728 if (isLegalAddressingMode(DL, AM, Ty, AS)) 11729 // Scale represents reg2 * scale, thus account for 1 if 11730 // it is not equal to 0 or 1. 11731 return AM.Scale != 0 && AM.Scale != 1; 11732 return -1; 11733 } 11734 11735 bool AArch64TargetLowering::isFMAFasterThanFMulAndFAdd( 11736 const MachineFunction &MF, EVT VT) const { 11737 VT = VT.getScalarType(); 11738 11739 if (!VT.isSimple()) 11740 return false; 11741 11742 switch (VT.getSimpleVT().SimpleTy) { 11743 case MVT::f16: 11744 return Subtarget->hasFullFP16(); 11745 case MVT::f32: 11746 case MVT::f64: 11747 return true; 11748 default: 11749 break; 11750 } 11751 11752 return false; 11753 } 11754 11755 bool AArch64TargetLowering::isFMAFasterThanFMulAndFAdd(const Function &F, 11756 Type *Ty) const { 11757 switch (Ty->getScalarType()->getTypeID()) { 11758 case Type::FloatTyID: 11759 case Type::DoubleTyID: 11760 return true; 11761 default: 11762 return false; 11763 } 11764 } 11765 11766 bool AArch64TargetLowering::generateFMAsInMachineCombiner( 11767 EVT VT, CodeGenOpt::Level OptLevel) const { 11768 return (OptLevel >= CodeGenOpt::Aggressive) && !VT.isScalableVector(); 11769 } 11770 11771 const MCPhysReg * 11772 AArch64TargetLowering::getScratchRegisters(CallingConv::ID) const { 11773 // LR is a callee-save register, but we must treat it as clobbered by any call 11774 // site. Hence we include LR in the scratch registers, which are in turn added 11775 // as implicit-defs for stackmaps and patchpoints. 11776 static const MCPhysReg ScratchRegs[] = { 11777 AArch64::X16, AArch64::X17, AArch64::LR, 0 11778 }; 11779 return ScratchRegs; 11780 } 11781 11782 bool 11783 AArch64TargetLowering::isDesirableToCommuteWithShift(const SDNode *N, 11784 CombineLevel Level) const { 11785 N = N->getOperand(0).getNode(); 11786 EVT VT = N->getValueType(0); 11787 // If N is unsigned bit extraction: ((x >> C) & mask), then do not combine 11788 // it with shift to let it be lowered to UBFX. 11789 if (N->getOpcode() == ISD::AND && (VT == MVT::i32 || VT == MVT::i64) && 11790 isa<ConstantSDNode>(N->getOperand(1))) { 11791 uint64_t TruncMask = N->getConstantOperandVal(1); 11792 if (isMask_64(TruncMask) && 11793 N->getOperand(0).getOpcode() == ISD::SRL && 11794 isa<ConstantSDNode>(N->getOperand(0)->getOperand(1))) 11795 return false; 11796 } 11797 return true; 11798 } 11799 11800 bool AArch64TargetLowering::shouldConvertConstantLoadToIntImm(const APInt &Imm, 11801 Type *Ty) const { 11802 assert(Ty->isIntegerTy()); 11803 11804 unsigned BitSize = Ty->getPrimitiveSizeInBits(); 11805 if (BitSize == 0) 11806 return false; 11807 11808 int64_t Val = Imm.getSExtValue(); 11809 if (Val == 0 || AArch64_AM::isLogicalImmediate(Val, BitSize)) 11810 return true; 11811 11812 if ((int64_t)Val < 0) 11813 Val = ~Val; 11814 if (BitSize == 32) 11815 Val &= (1LL << 32) - 1; 11816 11817 unsigned LZ = countLeadingZeros((uint64_t)Val); 11818 unsigned Shift = (63 - LZ) / 16; 11819 // MOVZ is free so return true for one or fewer MOVK. 11820 return Shift < 3; 11821 } 11822 11823 bool AArch64TargetLowering::isExtractSubvectorCheap(EVT ResVT, EVT SrcVT, 11824 unsigned Index) const { 11825 if (!isOperationLegalOrCustom(ISD::EXTRACT_SUBVECTOR, ResVT)) 11826 return false; 11827 11828 return (Index == 0 || Index == ResVT.getVectorNumElements()); 11829 } 11830 11831 /// Turn vector tests of the signbit in the form of: 11832 /// xor (sra X, elt_size(X)-1), -1 11833 /// into: 11834 /// cmge X, X, #0 11835 static SDValue foldVectorXorShiftIntoCmp(SDNode *N, SelectionDAG &DAG, 11836 const AArch64Subtarget *Subtarget) { 11837 EVT VT = N->getValueType(0); 11838 if (!Subtarget->hasNEON() || !VT.isVector()) 11839 return SDValue(); 11840 11841 // There must be a shift right algebraic before the xor, and the xor must be a 11842 // 'not' operation. 11843 SDValue Shift = N->getOperand(0); 11844 SDValue Ones = N->getOperand(1); 11845 if (Shift.getOpcode() != AArch64ISD::VASHR || !Shift.hasOneUse() || 11846 !ISD::isBuildVectorAllOnes(Ones.getNode())) 11847 return SDValue(); 11848 11849 // The shift should be smearing the sign bit across each vector element. 11850 auto *ShiftAmt = dyn_cast<ConstantSDNode>(Shift.getOperand(1)); 11851 EVT ShiftEltTy = Shift.getValueType().getVectorElementType(); 11852 if (!ShiftAmt || ShiftAmt->getZExtValue() != ShiftEltTy.getSizeInBits() - 1) 11853 return SDValue(); 11854 11855 return DAG.getNode(AArch64ISD::CMGEz, SDLoc(N), VT, Shift.getOperand(0)); 11856 } 11857 11858 // Turn a v8i8/v16i8 extended vecreduce into a udot/sdot and vecreduce 11859 // vecreduce.add(ext(A)) to vecreduce.add(DOT(zero, A, one)) 11860 // vecreduce.add(mul(ext(A), ext(B))) to vecreduce.add(DOT(zero, A, B)) 11861 static SDValue performVecReduceAddCombine(SDNode *N, SelectionDAG &DAG, 11862 const AArch64Subtarget *ST) { 11863 SDValue Op0 = N->getOperand(0); 11864 if (!ST->hasDotProd() || N->getValueType(0) != MVT::i32 || 11865 Op0.getValueType().getVectorElementType() != MVT::i32) 11866 return SDValue(); 11867 11868 unsigned ExtOpcode = Op0.getOpcode(); 11869 SDValue A = Op0; 11870 SDValue B; 11871 if (ExtOpcode == ISD::MUL) { 11872 A = Op0.getOperand(0); 11873 B = Op0.getOperand(1); 11874 if (A.getOpcode() != B.getOpcode() || 11875 A.getOperand(0).getValueType() != B.getOperand(0).getValueType()) 11876 return SDValue(); 11877 ExtOpcode = A.getOpcode(); 11878 } 11879 if (ExtOpcode != ISD::ZERO_EXTEND && ExtOpcode != ISD::SIGN_EXTEND) 11880 return SDValue(); 11881 11882 EVT Op0VT = A.getOperand(0).getValueType(); 11883 if (Op0VT != MVT::v8i8 && Op0VT != MVT::v16i8) 11884 return SDValue(); 11885 11886 SDLoc DL(Op0); 11887 // For non-mla reductions B can be set to 1. For MLA we take the operand of 11888 // the extend B. 11889 if (!B) 11890 B = DAG.getConstant(1, DL, Op0VT); 11891 else 11892 B = B.getOperand(0); 11893 11894 SDValue Zeros = 11895 DAG.getConstant(0, DL, Op0VT == MVT::v8i8 ? MVT::v2i32 : MVT::v4i32); 11896 auto DotOpcode = 11897 (ExtOpcode == ISD::ZERO_EXTEND) ? AArch64ISD::UDOT : AArch64ISD::SDOT; 11898 SDValue Dot = DAG.getNode(DotOpcode, DL, Zeros.getValueType(), Zeros, 11899 A.getOperand(0), B); 11900 return DAG.getNode(ISD::VECREDUCE_ADD, DL, N->getValueType(0), Dot); 11901 } 11902 11903 // Given a ABS node, detect the following pattern: 11904 // (ABS (SUB (EXTEND a), (EXTEND b))). 11905 // Generates UABD/SABD instruction. 11906 static SDValue performABSCombine(SDNode *N, SelectionDAG &DAG, 11907 TargetLowering::DAGCombinerInfo &DCI, 11908 const AArch64Subtarget *Subtarget) { 11909 SDValue AbsOp1 = N->getOperand(0); 11910 SDValue Op0, Op1; 11911 11912 if (AbsOp1.getOpcode() != ISD::SUB) 11913 return SDValue(); 11914 11915 Op0 = AbsOp1.getOperand(0); 11916 Op1 = AbsOp1.getOperand(1); 11917 11918 unsigned Opc0 = Op0.getOpcode(); 11919 // Check if the operands of the sub are (zero|sign)-extended. 11920 if (Opc0 != Op1.getOpcode() || 11921 (Opc0 != ISD::ZERO_EXTEND && Opc0 != ISD::SIGN_EXTEND)) 11922 return SDValue(); 11923 11924 EVT VectorT1 = Op0.getOperand(0).getValueType(); 11925 EVT VectorT2 = Op1.getOperand(0).getValueType(); 11926 // Check if vectors are of same type and valid size. 11927 uint64_t Size = VectorT1.getFixedSizeInBits(); 11928 if (VectorT1 != VectorT2 || (Size != 64 && Size != 128)) 11929 return SDValue(); 11930 11931 // Check if vector element types are valid. 11932 EVT VT1 = VectorT1.getVectorElementType(); 11933 if (VT1 != MVT::i8 && VT1 != MVT::i16 && VT1 != MVT::i32) 11934 return SDValue(); 11935 11936 Op0 = Op0.getOperand(0); 11937 Op1 = Op1.getOperand(0); 11938 unsigned ABDOpcode = 11939 (Opc0 == ISD::SIGN_EXTEND) ? AArch64ISD::SABD : AArch64ISD::UABD; 11940 SDValue ABD = 11941 DAG.getNode(ABDOpcode, SDLoc(N), Op0->getValueType(0), Op0, Op1); 11942 return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), N->getValueType(0), ABD); 11943 } 11944 11945 static SDValue performXorCombine(SDNode *N, SelectionDAG &DAG, 11946 TargetLowering::DAGCombinerInfo &DCI, 11947 const AArch64Subtarget *Subtarget) { 11948 if (DCI.isBeforeLegalizeOps()) 11949 return SDValue(); 11950 11951 return foldVectorXorShiftIntoCmp(N, DAG, Subtarget); 11952 } 11953 11954 SDValue 11955 AArch64TargetLowering::BuildSDIVPow2(SDNode *N, const APInt &Divisor, 11956 SelectionDAG &DAG, 11957 SmallVectorImpl<SDNode *> &Created) const { 11958 AttributeList Attr = DAG.getMachineFunction().getFunction().getAttributes(); 11959 if (isIntDivCheap(N->getValueType(0), Attr)) 11960 return SDValue(N,0); // Lower SDIV as SDIV 11961 11962 // fold (sdiv X, pow2) 11963 EVT VT = N->getValueType(0); 11964 if ((VT != MVT::i32 && VT != MVT::i64) || 11965 !(Divisor.isPowerOf2() || (-Divisor).isPowerOf2())) 11966 return SDValue(); 11967 11968 SDLoc DL(N); 11969 SDValue N0 = N->getOperand(0); 11970 unsigned Lg2 = Divisor.countTrailingZeros(); 11971 SDValue Zero = DAG.getConstant(0, DL, VT); 11972 SDValue Pow2MinusOne = DAG.getConstant((1ULL << Lg2) - 1, DL, VT); 11973 11974 // Add (N0 < 0) ? Pow2 - 1 : 0; 11975 SDValue CCVal; 11976 SDValue Cmp = getAArch64Cmp(N0, Zero, ISD::SETLT, CCVal, DAG, DL); 11977 SDValue Add = DAG.getNode(ISD::ADD, DL, VT, N0, Pow2MinusOne); 11978 SDValue CSel = DAG.getNode(AArch64ISD::CSEL, DL, VT, Add, N0, CCVal, Cmp); 11979 11980 Created.push_back(Cmp.getNode()); 11981 Created.push_back(Add.getNode()); 11982 Created.push_back(CSel.getNode()); 11983 11984 // Divide by pow2. 11985 SDValue SRA = 11986 DAG.getNode(ISD::SRA, DL, VT, CSel, DAG.getConstant(Lg2, DL, MVT::i64)); 11987 11988 // If we're dividing by a positive value, we're done. Otherwise, we must 11989 // negate the result. 11990 if (Divisor.isNonNegative()) 11991 return SRA; 11992 11993 Created.push_back(SRA.getNode()); 11994 return DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, VT), SRA); 11995 } 11996 11997 static bool IsSVECntIntrinsic(SDValue S) { 11998 switch(getIntrinsicID(S.getNode())) { 11999 default: 12000 break; 12001 case Intrinsic::aarch64_sve_cntb: 12002 case Intrinsic::aarch64_sve_cnth: 12003 case Intrinsic::aarch64_sve_cntw: 12004 case Intrinsic::aarch64_sve_cntd: 12005 return true; 12006 } 12007 return false; 12008 } 12009 12010 /// Calculates what the pre-extend type is, based on the extension 12011 /// operation node provided by \p Extend. 12012 /// 12013 /// In the case that \p Extend is a SIGN_EXTEND or a ZERO_EXTEND, the 12014 /// pre-extend type is pulled directly from the operand, while other extend 12015 /// operations need a bit more inspection to get this information. 12016 /// 12017 /// \param Extend The SDNode from the DAG that represents the extend operation 12018 /// \param DAG The SelectionDAG hosting the \p Extend node 12019 /// 12020 /// \returns The type representing the \p Extend source type, or \p MVT::Other 12021 /// if no valid type can be determined 12022 static EVT calculatePreExtendType(SDValue Extend, SelectionDAG &DAG) { 12023 switch (Extend.getOpcode()) { 12024 case ISD::SIGN_EXTEND: 12025 case ISD::ZERO_EXTEND: 12026 return Extend.getOperand(0).getValueType(); 12027 case ISD::AssertSext: 12028 case ISD::AssertZext: 12029 case ISD::SIGN_EXTEND_INREG: { 12030 VTSDNode *TypeNode = dyn_cast<VTSDNode>(Extend.getOperand(1)); 12031 if (!TypeNode) 12032 return MVT::Other; 12033 return TypeNode->getVT(); 12034 } 12035 case ISD::AND: { 12036 ConstantSDNode *Constant = 12037 dyn_cast<ConstantSDNode>(Extend.getOperand(1).getNode()); 12038 if (!Constant) 12039 return MVT::Other; 12040 12041 uint32_t Mask = Constant->getZExtValue(); 12042 12043 if (Mask == UCHAR_MAX) 12044 return MVT::i8; 12045 else if (Mask == USHRT_MAX) 12046 return MVT::i16; 12047 else if (Mask == UINT_MAX) 12048 return MVT::i32; 12049 12050 return MVT::Other; 12051 } 12052 default: 12053 return MVT::Other; 12054 } 12055 12056 llvm_unreachable("Code path unhandled in calculatePreExtendType!"); 12057 } 12058 12059 /// Combines a dup(sext/zext) node pattern into sext/zext(dup) 12060 /// making use of the vector SExt/ZExt rather than the scalar SExt/ZExt 12061 static SDValue performCommonVectorExtendCombine(SDValue VectorShuffle, 12062 SelectionDAG &DAG) { 12063 12064 ShuffleVectorSDNode *ShuffleNode = 12065 dyn_cast<ShuffleVectorSDNode>(VectorShuffle.getNode()); 12066 if (!ShuffleNode) 12067 return SDValue(); 12068 12069 // Ensuring the mask is zero before continuing 12070 if (!ShuffleNode->isSplat() || ShuffleNode->getSplatIndex() != 0) 12071 return SDValue(); 12072 12073 SDValue InsertVectorElt = VectorShuffle.getOperand(0); 12074 12075 if (InsertVectorElt.getOpcode() != ISD::INSERT_VECTOR_ELT) 12076 return SDValue(); 12077 12078 SDValue InsertLane = InsertVectorElt.getOperand(2); 12079 ConstantSDNode *Constant = dyn_cast<ConstantSDNode>(InsertLane.getNode()); 12080 // Ensures the insert is inserting into lane 0 12081 if (!Constant || Constant->getZExtValue() != 0) 12082 return SDValue(); 12083 12084 SDValue Extend = InsertVectorElt.getOperand(1); 12085 unsigned ExtendOpcode = Extend.getOpcode(); 12086 12087 bool IsSExt = ExtendOpcode == ISD::SIGN_EXTEND || 12088 ExtendOpcode == ISD::SIGN_EXTEND_INREG || 12089 ExtendOpcode == ISD::AssertSext; 12090 if (!IsSExt && ExtendOpcode != ISD::ZERO_EXTEND && 12091 ExtendOpcode != ISD::AssertZext && ExtendOpcode != ISD::AND) 12092 return SDValue(); 12093 12094 EVT TargetType = VectorShuffle.getValueType(); 12095 EVT PreExtendType = calculatePreExtendType(Extend, DAG); 12096 12097 if ((TargetType != MVT::v8i16 && TargetType != MVT::v4i32 && 12098 TargetType != MVT::v2i64) || 12099 (PreExtendType == MVT::Other)) 12100 return SDValue(); 12101 12102 // Restrict valid pre-extend data type 12103 if (PreExtendType != MVT::i8 && PreExtendType != MVT::i16 && 12104 PreExtendType != MVT::i32) 12105 return SDValue(); 12106 12107 EVT PreExtendVT = TargetType.changeVectorElementType(PreExtendType); 12108 12109 if (PreExtendVT.getVectorElementCount() != TargetType.getVectorElementCount()) 12110 return SDValue(); 12111 12112 if (TargetType.getScalarSizeInBits() != PreExtendVT.getScalarSizeInBits() * 2) 12113 return SDValue(); 12114 12115 SDLoc DL(VectorShuffle); 12116 12117 SDValue InsertVectorNode = DAG.getNode( 12118 InsertVectorElt.getOpcode(), DL, PreExtendVT, DAG.getUNDEF(PreExtendVT), 12119 DAG.getAnyExtOrTrunc(Extend.getOperand(0), DL, PreExtendType), 12120 DAG.getConstant(0, DL, MVT::i64)); 12121 12122 std::vector<int> ShuffleMask(TargetType.getVectorElementCount().getValue()); 12123 12124 SDValue VectorShuffleNode = 12125 DAG.getVectorShuffle(PreExtendVT, DL, InsertVectorNode, 12126 DAG.getUNDEF(PreExtendVT), ShuffleMask); 12127 12128 SDValue ExtendNode = DAG.getNode(IsSExt ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND, 12129 DL, TargetType, VectorShuffleNode); 12130 12131 return ExtendNode; 12132 } 12133 12134 /// Combines a mul(dup(sext/zext)) node pattern into mul(sext/zext(dup)) 12135 /// making use of the vector SExt/ZExt rather than the scalar SExt/ZExt 12136 static SDValue performMulVectorExtendCombine(SDNode *Mul, SelectionDAG &DAG) { 12137 // If the value type isn't a vector, none of the operands are going to be dups 12138 if (!Mul->getValueType(0).isVector()) 12139 return SDValue(); 12140 12141 SDValue Op0 = performCommonVectorExtendCombine(Mul->getOperand(0), DAG); 12142 SDValue Op1 = performCommonVectorExtendCombine(Mul->getOperand(1), DAG); 12143 12144 // Neither operands have been changed, don't make any further changes 12145 if (!Op0 && !Op1) 12146 return SDValue(); 12147 12148 SDLoc DL(Mul); 12149 return DAG.getNode(Mul->getOpcode(), DL, Mul->getValueType(0), 12150 Op0 ? Op0 : Mul->getOperand(0), 12151 Op1 ? Op1 : Mul->getOperand(1)); 12152 } 12153 12154 static SDValue performMulCombine(SDNode *N, SelectionDAG &DAG, 12155 TargetLowering::DAGCombinerInfo &DCI, 12156 const AArch64Subtarget *Subtarget) { 12157 12158 if (SDValue Ext = performMulVectorExtendCombine(N, DAG)) 12159 return Ext; 12160 12161 if (DCI.isBeforeLegalizeOps()) 12162 return SDValue(); 12163 12164 // The below optimizations require a constant RHS. 12165 if (!isa<ConstantSDNode>(N->getOperand(1))) 12166 return SDValue(); 12167 12168 SDValue N0 = N->getOperand(0); 12169 ConstantSDNode *C = cast<ConstantSDNode>(N->getOperand(1)); 12170 const APInt &ConstValue = C->getAPIntValue(); 12171 12172 // Allow the scaling to be folded into the `cnt` instruction by preventing 12173 // the scaling to be obscured here. This makes it easier to pattern match. 12174 if (IsSVECntIntrinsic(N0) || 12175 (N0->getOpcode() == ISD::TRUNCATE && 12176 (IsSVECntIntrinsic(N0->getOperand(0))))) 12177 if (ConstValue.sge(1) && ConstValue.sle(16)) 12178 return SDValue(); 12179 12180 // Multiplication of a power of two plus/minus one can be done more 12181 // cheaply as as shift+add/sub. For now, this is true unilaterally. If 12182 // future CPUs have a cheaper MADD instruction, this may need to be 12183 // gated on a subtarget feature. For Cyclone, 32-bit MADD is 4 cycles and 12184 // 64-bit is 5 cycles, so this is always a win. 12185 // More aggressively, some multiplications N0 * C can be lowered to 12186 // shift+add+shift if the constant C = A * B where A = 2^N + 1 and B = 2^M, 12187 // e.g. 6=3*2=(2+1)*2. 12188 // TODO: consider lowering more cases, e.g. C = 14, -6, -14 or even 45 12189 // which equals to (1+2)*16-(1+2). 12190 // TrailingZeroes is used to test if the mul can be lowered to 12191 // shift+add+shift. 12192 unsigned TrailingZeroes = ConstValue.countTrailingZeros(); 12193 if (TrailingZeroes) { 12194 // Conservatively do not lower to shift+add+shift if the mul might be 12195 // folded into smul or umul. 12196 if (N0->hasOneUse() && (isSignExtended(N0.getNode(), DAG) || 12197 isZeroExtended(N0.getNode(), DAG))) 12198 return SDValue(); 12199 // Conservatively do not lower to shift+add+shift if the mul might be 12200 // folded into madd or msub. 12201 if (N->hasOneUse() && (N->use_begin()->getOpcode() == ISD::ADD || 12202 N->use_begin()->getOpcode() == ISD::SUB)) 12203 return SDValue(); 12204 } 12205 // Use ShiftedConstValue instead of ConstValue to support both shift+add/sub 12206 // and shift+add+shift. 12207 APInt ShiftedConstValue = ConstValue.ashr(TrailingZeroes); 12208 12209 unsigned ShiftAmt, AddSubOpc; 12210 // Is the shifted value the LHS operand of the add/sub? 12211 bool ShiftValUseIsN0 = true; 12212 // Do we need to negate the result? 12213 bool NegateResult = false; 12214 12215 if (ConstValue.isNonNegative()) { 12216 // (mul x, 2^N + 1) => (add (shl x, N), x) 12217 // (mul x, 2^N - 1) => (sub (shl x, N), x) 12218 // (mul x, (2^N + 1) * 2^M) => (shl (add (shl x, N), x), M) 12219 APInt SCVMinus1 = ShiftedConstValue - 1; 12220 APInt CVPlus1 = ConstValue + 1; 12221 if (SCVMinus1.isPowerOf2()) { 12222 ShiftAmt = SCVMinus1.logBase2(); 12223 AddSubOpc = ISD::ADD; 12224 } else if (CVPlus1.isPowerOf2()) { 12225 ShiftAmt = CVPlus1.logBase2(); 12226 AddSubOpc = ISD::SUB; 12227 } else 12228 return SDValue(); 12229 } else { 12230 // (mul x, -(2^N - 1)) => (sub x, (shl x, N)) 12231 // (mul x, -(2^N + 1)) => - (add (shl x, N), x) 12232 APInt CVNegPlus1 = -ConstValue + 1; 12233 APInt CVNegMinus1 = -ConstValue - 1; 12234 if (CVNegPlus1.isPowerOf2()) { 12235 ShiftAmt = CVNegPlus1.logBase2(); 12236 AddSubOpc = ISD::SUB; 12237 ShiftValUseIsN0 = false; 12238 } else if (CVNegMinus1.isPowerOf2()) { 12239 ShiftAmt = CVNegMinus1.logBase2(); 12240 AddSubOpc = ISD::ADD; 12241 NegateResult = true; 12242 } else 12243 return SDValue(); 12244 } 12245 12246 SDLoc DL(N); 12247 EVT VT = N->getValueType(0); 12248 SDValue ShiftedVal = DAG.getNode(ISD::SHL, DL, VT, N0, 12249 DAG.getConstant(ShiftAmt, DL, MVT::i64)); 12250 12251 SDValue AddSubN0 = ShiftValUseIsN0 ? ShiftedVal : N0; 12252 SDValue AddSubN1 = ShiftValUseIsN0 ? N0 : ShiftedVal; 12253 SDValue Res = DAG.getNode(AddSubOpc, DL, VT, AddSubN0, AddSubN1); 12254 assert(!(NegateResult && TrailingZeroes) && 12255 "NegateResult and TrailingZeroes cannot both be true for now."); 12256 // Negate the result. 12257 if (NegateResult) 12258 return DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, VT), Res); 12259 // Shift the result. 12260 if (TrailingZeroes) 12261 return DAG.getNode(ISD::SHL, DL, VT, Res, 12262 DAG.getConstant(TrailingZeroes, DL, MVT::i64)); 12263 return Res; 12264 } 12265 12266 static SDValue performVectorCompareAndMaskUnaryOpCombine(SDNode *N, 12267 SelectionDAG &DAG) { 12268 // Take advantage of vector comparisons producing 0 or -1 in each lane to 12269 // optimize away operation when it's from a constant. 12270 // 12271 // The general transformation is: 12272 // UNARYOP(AND(VECTOR_CMP(x,y), constant)) --> 12273 // AND(VECTOR_CMP(x,y), constant2) 12274 // constant2 = UNARYOP(constant) 12275 12276 // Early exit if this isn't a vector operation, the operand of the 12277 // unary operation isn't a bitwise AND, or if the sizes of the operations 12278 // aren't the same. 12279 EVT VT = N->getValueType(0); 12280 if (!VT.isVector() || N->getOperand(0)->getOpcode() != ISD::AND || 12281 N->getOperand(0)->getOperand(0)->getOpcode() != ISD::SETCC || 12282 VT.getSizeInBits() != N->getOperand(0)->getValueType(0).getSizeInBits()) 12283 return SDValue(); 12284 12285 // Now check that the other operand of the AND is a constant. We could 12286 // make the transformation for non-constant splats as well, but it's unclear 12287 // that would be a benefit as it would not eliminate any operations, just 12288 // perform one more step in scalar code before moving to the vector unit. 12289 if (BuildVectorSDNode *BV = 12290 dyn_cast<BuildVectorSDNode>(N->getOperand(0)->getOperand(1))) { 12291 // Bail out if the vector isn't a constant. 12292 if (!BV->isConstant()) 12293 return SDValue(); 12294 12295 // Everything checks out. Build up the new and improved node. 12296 SDLoc DL(N); 12297 EVT IntVT = BV->getValueType(0); 12298 // Create a new constant of the appropriate type for the transformed 12299 // DAG. 12300 SDValue SourceConst = DAG.getNode(N->getOpcode(), DL, VT, SDValue(BV, 0)); 12301 // The AND node needs bitcasts to/from an integer vector type around it. 12302 SDValue MaskConst = DAG.getNode(ISD::BITCAST, DL, IntVT, SourceConst); 12303 SDValue NewAnd = DAG.getNode(ISD::AND, DL, IntVT, 12304 N->getOperand(0)->getOperand(0), MaskConst); 12305 SDValue Res = DAG.getNode(ISD::BITCAST, DL, VT, NewAnd); 12306 return Res; 12307 } 12308 12309 return SDValue(); 12310 } 12311 12312 static SDValue performIntToFpCombine(SDNode *N, SelectionDAG &DAG, 12313 const AArch64Subtarget *Subtarget) { 12314 // First try to optimize away the conversion when it's conditionally from 12315 // a constant. Vectors only. 12316 if (SDValue Res = performVectorCompareAndMaskUnaryOpCombine(N, DAG)) 12317 return Res; 12318 12319 EVT VT = N->getValueType(0); 12320 if (VT != MVT::f32 && VT != MVT::f64) 12321 return SDValue(); 12322 12323 // Only optimize when the source and destination types have the same width. 12324 if (VT.getSizeInBits() != N->getOperand(0).getValueSizeInBits()) 12325 return SDValue(); 12326 12327 // If the result of an integer load is only used by an integer-to-float 12328 // conversion, use a fp load instead and a AdvSIMD scalar {S|U}CVTF instead. 12329 // This eliminates an "integer-to-vector-move" UOP and improves throughput. 12330 SDValue N0 = N->getOperand(0); 12331 if (Subtarget->hasNEON() && ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() && 12332 // Do not change the width of a volatile load. 12333 !cast<LoadSDNode>(N0)->isVolatile()) { 12334 LoadSDNode *LN0 = cast<LoadSDNode>(N0); 12335 SDValue Load = DAG.getLoad(VT, SDLoc(N), LN0->getChain(), LN0->getBasePtr(), 12336 LN0->getPointerInfo(), LN0->getAlignment(), 12337 LN0->getMemOperand()->getFlags()); 12338 12339 // Make sure successors of the original load stay after it by updating them 12340 // to use the new Chain. 12341 DAG.ReplaceAllUsesOfValueWith(SDValue(LN0, 1), Load.getValue(1)); 12342 12343 unsigned Opcode = 12344 (N->getOpcode() == ISD::SINT_TO_FP) ? AArch64ISD::SITOF : AArch64ISD::UITOF; 12345 return DAG.getNode(Opcode, SDLoc(N), VT, Load); 12346 } 12347 12348 return SDValue(); 12349 } 12350 12351 /// Fold a floating-point multiply by power of two into floating-point to 12352 /// fixed-point conversion. 12353 static SDValue performFpToIntCombine(SDNode *N, SelectionDAG &DAG, 12354 TargetLowering::DAGCombinerInfo &DCI, 12355 const AArch64Subtarget *Subtarget) { 12356 if (!Subtarget->hasNEON()) 12357 return SDValue(); 12358 12359 if (!N->getValueType(0).isSimple()) 12360 return SDValue(); 12361 12362 SDValue Op = N->getOperand(0); 12363 if (!Op.getValueType().isVector() || !Op.getValueType().isSimple() || 12364 Op.getOpcode() != ISD::FMUL) 12365 return SDValue(); 12366 12367 SDValue ConstVec = Op->getOperand(1); 12368 if (!isa<BuildVectorSDNode>(ConstVec)) 12369 return SDValue(); 12370 12371 MVT FloatTy = Op.getSimpleValueType().getVectorElementType(); 12372 uint32_t FloatBits = FloatTy.getSizeInBits(); 12373 if (FloatBits != 32 && FloatBits != 64) 12374 return SDValue(); 12375 12376 MVT IntTy = N->getSimpleValueType(0).getVectorElementType(); 12377 uint32_t IntBits = IntTy.getSizeInBits(); 12378 if (IntBits != 16 && IntBits != 32 && IntBits != 64) 12379 return SDValue(); 12380 12381 // Avoid conversions where iN is larger than the float (e.g., float -> i64). 12382 if (IntBits > FloatBits) 12383 return SDValue(); 12384 12385 BitVector UndefElements; 12386 BuildVectorSDNode *BV = cast<BuildVectorSDNode>(ConstVec); 12387 int32_t Bits = IntBits == 64 ? 64 : 32; 12388 int32_t C = BV->getConstantFPSplatPow2ToLog2Int(&UndefElements, Bits + 1); 12389 if (C == -1 || C == 0 || C > Bits) 12390 return SDValue(); 12391 12392 MVT ResTy; 12393 unsigned NumLanes = Op.getValueType().getVectorNumElements(); 12394 switch (NumLanes) { 12395 default: 12396 return SDValue(); 12397 case 2: 12398 ResTy = FloatBits == 32 ? MVT::v2i32 : MVT::v2i64; 12399 break; 12400 case 4: 12401 ResTy = FloatBits == 32 ? MVT::v4i32 : MVT::v4i64; 12402 break; 12403 } 12404 12405 if (ResTy == MVT::v4i64 && DCI.isBeforeLegalizeOps()) 12406 return SDValue(); 12407 12408 assert((ResTy != MVT::v4i64 || DCI.isBeforeLegalizeOps()) && 12409 "Illegal vector type after legalization"); 12410 12411 SDLoc DL(N); 12412 bool IsSigned = N->getOpcode() == ISD::FP_TO_SINT; 12413 unsigned IntrinsicOpcode = IsSigned ? Intrinsic::aarch64_neon_vcvtfp2fxs 12414 : Intrinsic::aarch64_neon_vcvtfp2fxu; 12415 SDValue FixConv = 12416 DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, ResTy, 12417 DAG.getConstant(IntrinsicOpcode, DL, MVT::i32), 12418 Op->getOperand(0), DAG.getConstant(C, DL, MVT::i32)); 12419 // We can handle smaller integers by generating an extra trunc. 12420 if (IntBits < FloatBits) 12421 FixConv = DAG.getNode(ISD::TRUNCATE, DL, N->getValueType(0), FixConv); 12422 12423 return FixConv; 12424 } 12425 12426 /// Fold a floating-point divide by power of two into fixed-point to 12427 /// floating-point conversion. 12428 static SDValue performFDivCombine(SDNode *N, SelectionDAG &DAG, 12429 TargetLowering::DAGCombinerInfo &DCI, 12430 const AArch64Subtarget *Subtarget) { 12431 if (!Subtarget->hasNEON()) 12432 return SDValue(); 12433 12434 SDValue Op = N->getOperand(0); 12435 unsigned Opc = Op->getOpcode(); 12436 if (!Op.getValueType().isVector() || !Op.getValueType().isSimple() || 12437 !Op.getOperand(0).getValueType().isSimple() || 12438 (Opc != ISD::SINT_TO_FP && Opc != ISD::UINT_TO_FP)) 12439 return SDValue(); 12440 12441 SDValue ConstVec = N->getOperand(1); 12442 if (!isa<BuildVectorSDNode>(ConstVec)) 12443 return SDValue(); 12444 12445 MVT IntTy = Op.getOperand(0).getSimpleValueType().getVectorElementType(); 12446 int32_t IntBits = IntTy.getSizeInBits(); 12447 if (IntBits != 16 && IntBits != 32 && IntBits != 64) 12448 return SDValue(); 12449 12450 MVT FloatTy = N->getSimpleValueType(0).getVectorElementType(); 12451 int32_t FloatBits = FloatTy.getSizeInBits(); 12452 if (FloatBits != 32 && FloatBits != 64) 12453 return SDValue(); 12454 12455 // Avoid conversions where iN is larger than the float (e.g., i64 -> float). 12456 if (IntBits > FloatBits) 12457 return SDValue(); 12458 12459 BitVector UndefElements; 12460 BuildVectorSDNode *BV = cast<BuildVectorSDNode>(ConstVec); 12461 int32_t C = BV->getConstantFPSplatPow2ToLog2Int(&UndefElements, FloatBits + 1); 12462 if (C == -1 || C == 0 || C > FloatBits) 12463 return SDValue(); 12464 12465 MVT ResTy; 12466 unsigned NumLanes = Op.getValueType().getVectorNumElements(); 12467 switch (NumLanes) { 12468 default: 12469 return SDValue(); 12470 case 2: 12471 ResTy = FloatBits == 32 ? MVT::v2i32 : MVT::v2i64; 12472 break; 12473 case 4: 12474 ResTy = FloatBits == 32 ? MVT::v4i32 : MVT::v4i64; 12475 break; 12476 } 12477 12478 if (ResTy == MVT::v4i64 && DCI.isBeforeLegalizeOps()) 12479 return SDValue(); 12480 12481 SDLoc DL(N); 12482 SDValue ConvInput = Op.getOperand(0); 12483 bool IsSigned = Opc == ISD::SINT_TO_FP; 12484 if (IntBits < FloatBits) 12485 ConvInput = DAG.getNode(IsSigned ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND, DL, 12486 ResTy, ConvInput); 12487 12488 unsigned IntrinsicOpcode = IsSigned ? Intrinsic::aarch64_neon_vcvtfxs2fp 12489 : Intrinsic::aarch64_neon_vcvtfxu2fp; 12490 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, Op.getValueType(), 12491 DAG.getConstant(IntrinsicOpcode, DL, MVT::i32), ConvInput, 12492 DAG.getConstant(C, DL, MVT::i32)); 12493 } 12494 12495 /// An EXTR instruction is made up of two shifts, ORed together. This helper 12496 /// searches for and classifies those shifts. 12497 static bool findEXTRHalf(SDValue N, SDValue &Src, uint32_t &ShiftAmount, 12498 bool &FromHi) { 12499 if (N.getOpcode() == ISD::SHL) 12500 FromHi = false; 12501 else if (N.getOpcode() == ISD::SRL) 12502 FromHi = true; 12503 else 12504 return false; 12505 12506 if (!isa<ConstantSDNode>(N.getOperand(1))) 12507 return false; 12508 12509 ShiftAmount = N->getConstantOperandVal(1); 12510 Src = N->getOperand(0); 12511 return true; 12512 } 12513 12514 /// EXTR instruction extracts a contiguous chunk of bits from two existing 12515 /// registers viewed as a high/low pair. This function looks for the pattern: 12516 /// <tt>(or (shl VAL1, \#N), (srl VAL2, \#RegWidth-N))</tt> and replaces it 12517 /// with an EXTR. Can't quite be done in TableGen because the two immediates 12518 /// aren't independent. 12519 static SDValue tryCombineToEXTR(SDNode *N, 12520 TargetLowering::DAGCombinerInfo &DCI) { 12521 SelectionDAG &DAG = DCI.DAG; 12522 SDLoc DL(N); 12523 EVT VT = N->getValueType(0); 12524 12525 assert(N->getOpcode() == ISD::OR && "Unexpected root"); 12526 12527 if (VT != MVT::i32 && VT != MVT::i64) 12528 return SDValue(); 12529 12530 SDValue LHS; 12531 uint32_t ShiftLHS = 0; 12532 bool LHSFromHi = false; 12533 if (!findEXTRHalf(N->getOperand(0), LHS, ShiftLHS, LHSFromHi)) 12534 return SDValue(); 12535 12536 SDValue RHS; 12537 uint32_t ShiftRHS = 0; 12538 bool RHSFromHi = false; 12539 if (!findEXTRHalf(N->getOperand(1), RHS, ShiftRHS, RHSFromHi)) 12540 return SDValue(); 12541 12542 // If they're both trying to come from the high part of the register, they're 12543 // not really an EXTR. 12544 if (LHSFromHi == RHSFromHi) 12545 return SDValue(); 12546 12547 if (ShiftLHS + ShiftRHS != VT.getSizeInBits()) 12548 return SDValue(); 12549 12550 if (LHSFromHi) { 12551 std::swap(LHS, RHS); 12552 std::swap(ShiftLHS, ShiftRHS); 12553 } 12554 12555 return DAG.getNode(AArch64ISD::EXTR, DL, VT, LHS, RHS, 12556 DAG.getConstant(ShiftRHS, DL, MVT::i64)); 12557 } 12558 12559 static SDValue tryCombineToBSL(SDNode *N, 12560 TargetLowering::DAGCombinerInfo &DCI) { 12561 EVT VT = N->getValueType(0); 12562 SelectionDAG &DAG = DCI.DAG; 12563 SDLoc DL(N); 12564 12565 if (!VT.isVector()) 12566 return SDValue(); 12567 12568 SDValue N0 = N->getOperand(0); 12569 if (N0.getOpcode() != ISD::AND) 12570 return SDValue(); 12571 12572 SDValue N1 = N->getOperand(1); 12573 if (N1.getOpcode() != ISD::AND) 12574 return SDValue(); 12575 12576 // We only have to look for constant vectors here since the general, variable 12577 // case can be handled in TableGen. 12578 unsigned Bits = VT.getScalarSizeInBits(); 12579 uint64_t BitMask = Bits == 64 ? -1ULL : ((1ULL << Bits) - 1); 12580 for (int i = 1; i >= 0; --i) 12581 for (int j = 1; j >= 0; --j) { 12582 BuildVectorSDNode *BVN0 = dyn_cast<BuildVectorSDNode>(N0->getOperand(i)); 12583 BuildVectorSDNode *BVN1 = dyn_cast<BuildVectorSDNode>(N1->getOperand(j)); 12584 if (!BVN0 || !BVN1) 12585 continue; 12586 12587 bool FoundMatch = true; 12588 for (unsigned k = 0; k < VT.getVectorNumElements(); ++k) { 12589 ConstantSDNode *CN0 = dyn_cast<ConstantSDNode>(BVN0->getOperand(k)); 12590 ConstantSDNode *CN1 = dyn_cast<ConstantSDNode>(BVN1->getOperand(k)); 12591 if (!CN0 || !CN1 || 12592 CN0->getZExtValue() != (BitMask & ~CN1->getZExtValue())) { 12593 FoundMatch = false; 12594 break; 12595 } 12596 } 12597 12598 if (FoundMatch) 12599 return DAG.getNode(AArch64ISD::BSP, DL, VT, SDValue(BVN0, 0), 12600 N0->getOperand(1 - i), N1->getOperand(1 - j)); 12601 } 12602 12603 return SDValue(); 12604 } 12605 12606 static SDValue performORCombine(SDNode *N, TargetLowering::DAGCombinerInfo &DCI, 12607 const AArch64Subtarget *Subtarget) { 12608 // Attempt to form an EXTR from (or (shl VAL1, #N), (srl VAL2, #RegWidth-N)) 12609 SelectionDAG &DAG = DCI.DAG; 12610 EVT VT = N->getValueType(0); 12611 12612 if (!DAG.getTargetLoweringInfo().isTypeLegal(VT)) 12613 return SDValue(); 12614 12615 if (SDValue Res = tryCombineToEXTR(N, DCI)) 12616 return Res; 12617 12618 if (SDValue Res = tryCombineToBSL(N, DCI)) 12619 return Res; 12620 12621 return SDValue(); 12622 } 12623 12624 static bool isConstantSplatVectorMaskForType(SDNode *N, EVT MemVT) { 12625 if (!MemVT.getVectorElementType().isSimple()) 12626 return false; 12627 12628 uint64_t MaskForTy = 0ull; 12629 switch (MemVT.getVectorElementType().getSimpleVT().SimpleTy) { 12630 case MVT::i8: 12631 MaskForTy = 0xffull; 12632 break; 12633 case MVT::i16: 12634 MaskForTy = 0xffffull; 12635 break; 12636 case MVT::i32: 12637 MaskForTy = 0xffffffffull; 12638 break; 12639 default: 12640 return false; 12641 break; 12642 } 12643 12644 if (N->getOpcode() == AArch64ISD::DUP || N->getOpcode() == ISD::SPLAT_VECTOR) 12645 if (auto *Op0 = dyn_cast<ConstantSDNode>(N->getOperand(0))) 12646 return Op0->getAPIntValue().getLimitedValue() == MaskForTy; 12647 12648 return false; 12649 } 12650 12651 static SDValue performSVEAndCombine(SDNode *N, 12652 TargetLowering::DAGCombinerInfo &DCI) { 12653 if (DCI.isBeforeLegalizeOps()) 12654 return SDValue(); 12655 12656 SelectionDAG &DAG = DCI.DAG; 12657 SDValue Src = N->getOperand(0); 12658 unsigned Opc = Src->getOpcode(); 12659 12660 // Zero/any extend of an unsigned unpack 12661 if (Opc == AArch64ISD::UUNPKHI || Opc == AArch64ISD::UUNPKLO) { 12662 SDValue UnpkOp = Src->getOperand(0); 12663 SDValue Dup = N->getOperand(1); 12664 12665 if (Dup.getOpcode() != AArch64ISD::DUP) 12666 return SDValue(); 12667 12668 SDLoc DL(N); 12669 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Dup->getOperand(0)); 12670 uint64_t ExtVal = C->getZExtValue(); 12671 12672 // If the mask is fully covered by the unpack, we don't need to push 12673 // a new AND onto the operand 12674 EVT EltTy = UnpkOp->getValueType(0).getVectorElementType(); 12675 if ((ExtVal == 0xFF && EltTy == MVT::i8) || 12676 (ExtVal == 0xFFFF && EltTy == MVT::i16) || 12677 (ExtVal == 0xFFFFFFFF && EltTy == MVT::i32)) 12678 return Src; 12679 12680 // Truncate to prevent a DUP with an over wide constant 12681 APInt Mask = C->getAPIntValue().trunc(EltTy.getSizeInBits()); 12682 12683 // Otherwise, make sure we propagate the AND to the operand 12684 // of the unpack 12685 Dup = DAG.getNode(AArch64ISD::DUP, DL, 12686 UnpkOp->getValueType(0), 12687 DAG.getConstant(Mask.zextOrTrunc(32), DL, MVT::i32)); 12688 12689 SDValue And = DAG.getNode(ISD::AND, DL, 12690 UnpkOp->getValueType(0), UnpkOp, Dup); 12691 12692 return DAG.getNode(Opc, DL, N->getValueType(0), And); 12693 } 12694 12695 if (!EnableCombineMGatherIntrinsics) 12696 return SDValue(); 12697 12698 SDValue Mask = N->getOperand(1); 12699 12700 if (!Src.hasOneUse()) 12701 return SDValue(); 12702 12703 EVT MemVT; 12704 12705 // SVE load instructions perform an implicit zero-extend, which makes them 12706 // perfect candidates for combining. 12707 switch (Opc) { 12708 case AArch64ISD::LD1_MERGE_ZERO: 12709 case AArch64ISD::LDNF1_MERGE_ZERO: 12710 case AArch64ISD::LDFF1_MERGE_ZERO: 12711 MemVT = cast<VTSDNode>(Src->getOperand(3))->getVT(); 12712 break; 12713 case AArch64ISD::GLD1_MERGE_ZERO: 12714 case AArch64ISD::GLD1_SCALED_MERGE_ZERO: 12715 case AArch64ISD::GLD1_SXTW_MERGE_ZERO: 12716 case AArch64ISD::GLD1_SXTW_SCALED_MERGE_ZERO: 12717 case AArch64ISD::GLD1_UXTW_MERGE_ZERO: 12718 case AArch64ISD::GLD1_UXTW_SCALED_MERGE_ZERO: 12719 case AArch64ISD::GLD1_IMM_MERGE_ZERO: 12720 case AArch64ISD::GLDFF1_MERGE_ZERO: 12721 case AArch64ISD::GLDFF1_SCALED_MERGE_ZERO: 12722 case AArch64ISD::GLDFF1_SXTW_MERGE_ZERO: 12723 case AArch64ISD::GLDFF1_SXTW_SCALED_MERGE_ZERO: 12724 case AArch64ISD::GLDFF1_UXTW_MERGE_ZERO: 12725 case AArch64ISD::GLDFF1_UXTW_SCALED_MERGE_ZERO: 12726 case AArch64ISD::GLDFF1_IMM_MERGE_ZERO: 12727 case AArch64ISD::GLDNT1_MERGE_ZERO: 12728 MemVT = cast<VTSDNode>(Src->getOperand(4))->getVT(); 12729 break; 12730 default: 12731 return SDValue(); 12732 } 12733 12734 if (isConstantSplatVectorMaskForType(Mask.getNode(), MemVT)) 12735 return Src; 12736 12737 return SDValue(); 12738 } 12739 12740 static SDValue performANDCombine(SDNode *N, 12741 TargetLowering::DAGCombinerInfo &DCI) { 12742 SelectionDAG &DAG = DCI.DAG; 12743 SDValue LHS = N->getOperand(0); 12744 EVT VT = N->getValueType(0); 12745 if (!VT.isVector() || !DAG.getTargetLoweringInfo().isTypeLegal(VT)) 12746 return SDValue(); 12747 12748 if (VT.isScalableVector()) 12749 return performSVEAndCombine(N, DCI); 12750 12751 // The combining code below works only for NEON vectors. In particular, it 12752 // does not work for SVE when dealing with vectors wider than 128 bits. 12753 if (!(VT.is64BitVector() || VT.is128BitVector())) 12754 return SDValue(); 12755 12756 BuildVectorSDNode *BVN = 12757 dyn_cast<BuildVectorSDNode>(N->getOperand(1).getNode()); 12758 if (!BVN) 12759 return SDValue(); 12760 12761 // AND does not accept an immediate, so check if we can use a BIC immediate 12762 // instruction instead. We do this here instead of using a (and x, (mvni imm)) 12763 // pattern in isel, because some immediates may be lowered to the preferred 12764 // (and x, (movi imm)) form, even though an mvni representation also exists. 12765 APInt DefBits(VT.getSizeInBits(), 0); 12766 APInt UndefBits(VT.getSizeInBits(), 0); 12767 if (resolveBuildVector(BVN, DefBits, UndefBits)) { 12768 SDValue NewOp; 12769 12770 DefBits = ~DefBits; 12771 if ((NewOp = tryAdvSIMDModImm32(AArch64ISD::BICi, SDValue(N, 0), DAG, 12772 DefBits, &LHS)) || 12773 (NewOp = tryAdvSIMDModImm16(AArch64ISD::BICi, SDValue(N, 0), DAG, 12774 DefBits, &LHS))) 12775 return NewOp; 12776 12777 UndefBits = ~UndefBits; 12778 if ((NewOp = tryAdvSIMDModImm32(AArch64ISD::BICi, SDValue(N, 0), DAG, 12779 UndefBits, &LHS)) || 12780 (NewOp = tryAdvSIMDModImm16(AArch64ISD::BICi, SDValue(N, 0), DAG, 12781 UndefBits, &LHS))) 12782 return NewOp; 12783 } 12784 12785 return SDValue(); 12786 } 12787 12788 static SDValue performSRLCombine(SDNode *N, 12789 TargetLowering::DAGCombinerInfo &DCI) { 12790 SelectionDAG &DAG = DCI.DAG; 12791 EVT VT = N->getValueType(0); 12792 if (VT != MVT::i32 && VT != MVT::i64) 12793 return SDValue(); 12794 12795 // Canonicalize (srl (bswap i32 x), 16) to (rotr (bswap i32 x), 16), if the 12796 // high 16-bits of x are zero. Similarly, canonicalize (srl (bswap i64 x), 32) 12797 // to (rotr (bswap i64 x), 32), if the high 32-bits of x are zero. 12798 SDValue N0 = N->getOperand(0); 12799 if (N0.getOpcode() == ISD::BSWAP) { 12800 SDLoc DL(N); 12801 SDValue N1 = N->getOperand(1); 12802 SDValue N00 = N0.getOperand(0); 12803 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(N1)) { 12804 uint64_t ShiftAmt = C->getZExtValue(); 12805 if (VT == MVT::i32 && ShiftAmt == 16 && 12806 DAG.MaskedValueIsZero(N00, APInt::getHighBitsSet(32, 16))) 12807 return DAG.getNode(ISD::ROTR, DL, VT, N0, N1); 12808 if (VT == MVT::i64 && ShiftAmt == 32 && 12809 DAG.MaskedValueIsZero(N00, APInt::getHighBitsSet(64, 32))) 12810 return DAG.getNode(ISD::ROTR, DL, VT, N0, N1); 12811 } 12812 } 12813 return SDValue(); 12814 } 12815 12816 // Attempt to form urhadd(OpA, OpB) from 12817 // truncate(vlshr(sub(zext(OpB), xor(zext(OpA), Ones(ElemSizeInBits))), 1)) 12818 // or uhadd(OpA, OpB) from truncate(vlshr(add(zext(OpA), zext(OpB)), 1)). 12819 // The original form of the first expression is 12820 // truncate(srl(add(zext(OpB), add(zext(OpA), 1)), 1)) and the 12821 // (OpA + OpB + 1) subexpression will have been changed to (OpB - (~OpA)). 12822 // Before this function is called the srl will have been lowered to 12823 // AArch64ISD::VLSHR. 12824 // This pass can also recognize signed variants of the patterns that use sign 12825 // extension instead of zero extension and form a srhadd(OpA, OpB) or a 12826 // shadd(OpA, OpB) from them. 12827 static SDValue 12828 performVectorTruncateCombine(SDNode *N, TargetLowering::DAGCombinerInfo &DCI, 12829 SelectionDAG &DAG) { 12830 EVT VT = N->getValueType(0); 12831 12832 // Since we are looking for a right shift by a constant value of 1 and we are 12833 // operating on types at least 16 bits in length (sign/zero extended OpA and 12834 // OpB, which are at least 8 bits), it follows that the truncate will always 12835 // discard the shifted-in bit and therefore the right shift will be logical 12836 // regardless of the signedness of OpA and OpB. 12837 SDValue Shift = N->getOperand(0); 12838 if (Shift.getOpcode() != AArch64ISD::VLSHR) 12839 return SDValue(); 12840 12841 // Is the right shift using an immediate value of 1? 12842 uint64_t ShiftAmount = Shift.getConstantOperandVal(1); 12843 if (ShiftAmount != 1) 12844 return SDValue(); 12845 12846 SDValue ExtendOpA, ExtendOpB; 12847 SDValue ShiftOp0 = Shift.getOperand(0); 12848 unsigned ShiftOp0Opc = ShiftOp0.getOpcode(); 12849 if (ShiftOp0Opc == ISD::SUB) { 12850 12851 SDValue Xor = ShiftOp0.getOperand(1); 12852 if (Xor.getOpcode() != ISD::XOR) 12853 return SDValue(); 12854 12855 // Is the XOR using a constant amount of all ones in the right hand side? 12856 uint64_t C; 12857 if (!isAllConstantBuildVector(Xor.getOperand(1), C)) 12858 return SDValue(); 12859 12860 unsigned ElemSizeInBits = VT.getScalarSizeInBits(); 12861 APInt CAsAPInt(ElemSizeInBits, C); 12862 if (CAsAPInt != APInt::getAllOnesValue(ElemSizeInBits)) 12863 return SDValue(); 12864 12865 ExtendOpA = Xor.getOperand(0); 12866 ExtendOpB = ShiftOp0.getOperand(0); 12867 } else if (ShiftOp0Opc == ISD::ADD) { 12868 ExtendOpA = ShiftOp0.getOperand(0); 12869 ExtendOpB = ShiftOp0.getOperand(1); 12870 } else 12871 return SDValue(); 12872 12873 unsigned ExtendOpAOpc = ExtendOpA.getOpcode(); 12874 unsigned ExtendOpBOpc = ExtendOpB.getOpcode(); 12875 if (!(ExtendOpAOpc == ExtendOpBOpc && 12876 (ExtendOpAOpc == ISD::ZERO_EXTEND || ExtendOpAOpc == ISD::SIGN_EXTEND))) 12877 return SDValue(); 12878 12879 // Is the result of the right shift being truncated to the same value type as 12880 // the original operands, OpA and OpB? 12881 SDValue OpA = ExtendOpA.getOperand(0); 12882 SDValue OpB = ExtendOpB.getOperand(0); 12883 EVT OpAVT = OpA.getValueType(); 12884 assert(ExtendOpA.getValueType() == ExtendOpB.getValueType()); 12885 if (!(VT == OpAVT && OpAVT == OpB.getValueType())) 12886 return SDValue(); 12887 12888 SDLoc DL(N); 12889 bool IsSignExtend = ExtendOpAOpc == ISD::SIGN_EXTEND; 12890 bool IsRHADD = ShiftOp0Opc == ISD::SUB; 12891 unsigned HADDOpc = IsSignExtend 12892 ? (IsRHADD ? AArch64ISD::SRHADD : AArch64ISD::SHADD) 12893 : (IsRHADD ? AArch64ISD::URHADD : AArch64ISD::UHADD); 12894 SDValue ResultHADD = DAG.getNode(HADDOpc, DL, VT, OpA, OpB); 12895 12896 return ResultHADD; 12897 } 12898 12899 static bool hasPairwiseAdd(unsigned Opcode, EVT VT, bool FullFP16) { 12900 switch (Opcode) { 12901 case ISD::FADD: 12902 return (FullFP16 && VT == MVT::f16) || VT == MVT::f32 || VT == MVT::f64; 12903 case ISD::ADD: 12904 return VT == MVT::i64; 12905 default: 12906 return false; 12907 } 12908 } 12909 12910 static SDValue performExtractVectorEltCombine(SDNode *N, SelectionDAG &DAG) { 12911 SDValue N0 = N->getOperand(0), N1 = N->getOperand(1); 12912 ConstantSDNode *ConstantN1 = dyn_cast<ConstantSDNode>(N1); 12913 12914 EVT VT = N->getValueType(0); 12915 const bool FullFP16 = 12916 static_cast<const AArch64Subtarget &>(DAG.getSubtarget()).hasFullFP16(); 12917 12918 // Rewrite for pairwise fadd pattern 12919 // (f32 (extract_vector_elt 12920 // (fadd (vXf32 Other) 12921 // (vector_shuffle (vXf32 Other) undef <1,X,...> )) 0)) 12922 // -> 12923 // (f32 (fadd (extract_vector_elt (vXf32 Other) 0) 12924 // (extract_vector_elt (vXf32 Other) 1)) 12925 if (ConstantN1 && ConstantN1->getZExtValue() == 0 && 12926 hasPairwiseAdd(N0->getOpcode(), VT, FullFP16)) { 12927 SDLoc DL(N0); 12928 SDValue N00 = N0->getOperand(0); 12929 SDValue N01 = N0->getOperand(1); 12930 12931 ShuffleVectorSDNode *Shuffle = dyn_cast<ShuffleVectorSDNode>(N01); 12932 SDValue Other = N00; 12933 12934 // And handle the commutative case. 12935 if (!Shuffle) { 12936 Shuffle = dyn_cast<ShuffleVectorSDNode>(N00); 12937 Other = N01; 12938 } 12939 12940 if (Shuffle && Shuffle->getMaskElt(0) == 1 && 12941 Other == Shuffle->getOperand(0)) { 12942 return DAG.getNode(N0->getOpcode(), DL, VT, 12943 DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, VT, Other, 12944 DAG.getConstant(0, DL, MVT::i64)), 12945 DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, VT, Other, 12946 DAG.getConstant(1, DL, MVT::i64))); 12947 } 12948 } 12949 12950 return SDValue(); 12951 } 12952 12953 static SDValue performConcatVectorsCombine(SDNode *N, 12954 TargetLowering::DAGCombinerInfo &DCI, 12955 SelectionDAG &DAG) { 12956 SDLoc dl(N); 12957 EVT VT = N->getValueType(0); 12958 SDValue N0 = N->getOperand(0), N1 = N->getOperand(1); 12959 unsigned N0Opc = N0->getOpcode(), N1Opc = N1->getOpcode(); 12960 12961 // Optimize concat_vectors of truncated vectors, where the intermediate 12962 // type is illegal, to avoid said illegality, e.g., 12963 // (v4i16 (concat_vectors (v2i16 (truncate (v2i64))), 12964 // (v2i16 (truncate (v2i64))))) 12965 // -> 12966 // (v4i16 (truncate (vector_shuffle (v4i32 (bitcast (v2i64))), 12967 // (v4i32 (bitcast (v2i64))), 12968 // <0, 2, 4, 6>))) 12969 // This isn't really target-specific, but ISD::TRUNCATE legality isn't keyed 12970 // on both input and result type, so we might generate worse code. 12971 // On AArch64 we know it's fine for v2i64->v4i16 and v4i32->v8i8. 12972 if (N->getNumOperands() == 2 && N0Opc == ISD::TRUNCATE && 12973 N1Opc == ISD::TRUNCATE) { 12974 SDValue N00 = N0->getOperand(0); 12975 SDValue N10 = N1->getOperand(0); 12976 EVT N00VT = N00.getValueType(); 12977 12978 if (N00VT == N10.getValueType() && 12979 (N00VT == MVT::v2i64 || N00VT == MVT::v4i32) && 12980 N00VT.getScalarSizeInBits() == 4 * VT.getScalarSizeInBits()) { 12981 MVT MidVT = (N00VT == MVT::v2i64 ? MVT::v4i32 : MVT::v8i16); 12982 SmallVector<int, 8> Mask(MidVT.getVectorNumElements()); 12983 for (size_t i = 0; i < Mask.size(); ++i) 12984 Mask[i] = i * 2; 12985 return DAG.getNode(ISD::TRUNCATE, dl, VT, 12986 DAG.getVectorShuffle( 12987 MidVT, dl, 12988 DAG.getNode(ISD::BITCAST, dl, MidVT, N00), 12989 DAG.getNode(ISD::BITCAST, dl, MidVT, N10), Mask)); 12990 } 12991 } 12992 12993 // Wait 'til after everything is legalized to try this. That way we have 12994 // legal vector types and such. 12995 if (DCI.isBeforeLegalizeOps()) 12996 return SDValue(); 12997 12998 // Optimise concat_vectors of two [us]rhadds or [us]hadds that use extracted 12999 // subvectors from the same original vectors. Combine these into a single 13000 // [us]rhadd or [us]hadd that operates on the two original vectors. Example: 13001 // (v16i8 (concat_vectors (v8i8 (urhadd (extract_subvector (v16i8 OpA, <0>), 13002 // extract_subvector (v16i8 OpB, 13003 // <0>))), 13004 // (v8i8 (urhadd (extract_subvector (v16i8 OpA, <8>), 13005 // extract_subvector (v16i8 OpB, 13006 // <8>))))) 13007 // -> 13008 // (v16i8(urhadd(v16i8 OpA, v16i8 OpB))) 13009 if (N->getNumOperands() == 2 && N0Opc == N1Opc && 13010 (N0Opc == AArch64ISD::URHADD || N0Opc == AArch64ISD::SRHADD || 13011 N0Opc == AArch64ISD::UHADD || N0Opc == AArch64ISD::SHADD)) { 13012 SDValue N00 = N0->getOperand(0); 13013 SDValue N01 = N0->getOperand(1); 13014 SDValue N10 = N1->getOperand(0); 13015 SDValue N11 = N1->getOperand(1); 13016 13017 EVT N00VT = N00.getValueType(); 13018 EVT N10VT = N10.getValueType(); 13019 13020 if (N00->getOpcode() == ISD::EXTRACT_SUBVECTOR && 13021 N01->getOpcode() == ISD::EXTRACT_SUBVECTOR && 13022 N10->getOpcode() == ISD::EXTRACT_SUBVECTOR && 13023 N11->getOpcode() == ISD::EXTRACT_SUBVECTOR && N00VT == N10VT) { 13024 SDValue N00Source = N00->getOperand(0); 13025 SDValue N01Source = N01->getOperand(0); 13026 SDValue N10Source = N10->getOperand(0); 13027 SDValue N11Source = N11->getOperand(0); 13028 13029 if (N00Source == N10Source && N01Source == N11Source && 13030 N00Source.getValueType() == VT && N01Source.getValueType() == VT) { 13031 assert(N0.getValueType() == N1.getValueType()); 13032 13033 uint64_t N00Index = N00.getConstantOperandVal(1); 13034 uint64_t N01Index = N01.getConstantOperandVal(1); 13035 uint64_t N10Index = N10.getConstantOperandVal(1); 13036 uint64_t N11Index = N11.getConstantOperandVal(1); 13037 13038 if (N00Index == N01Index && N10Index == N11Index && N00Index == 0 && 13039 N10Index == N00VT.getVectorNumElements()) 13040 return DAG.getNode(N0Opc, dl, VT, N00Source, N01Source); 13041 } 13042 } 13043 } 13044 13045 // If we see a (concat_vectors (v1x64 A), (v1x64 A)) it's really a vector 13046 // splat. The indexed instructions are going to be expecting a DUPLANE64, so 13047 // canonicalise to that. 13048 if (N0 == N1 && VT.getVectorNumElements() == 2) { 13049 assert(VT.getScalarSizeInBits() == 64); 13050 return DAG.getNode(AArch64ISD::DUPLANE64, dl, VT, WidenVector(N0, DAG), 13051 DAG.getConstant(0, dl, MVT::i64)); 13052 } 13053 13054 // Canonicalise concat_vectors so that the right-hand vector has as few 13055 // bit-casts as possible before its real operation. The primary matching 13056 // destination for these operations will be the narrowing "2" instructions, 13057 // which depend on the operation being performed on this right-hand vector. 13058 // For example, 13059 // (concat_vectors LHS, (v1i64 (bitconvert (v4i16 RHS)))) 13060 // becomes 13061 // (bitconvert (concat_vectors (v4i16 (bitconvert LHS)), RHS)) 13062 13063 if (N1Opc != ISD::BITCAST) 13064 return SDValue(); 13065 SDValue RHS = N1->getOperand(0); 13066 MVT RHSTy = RHS.getValueType().getSimpleVT(); 13067 // If the RHS is not a vector, this is not the pattern we're looking for. 13068 if (!RHSTy.isVector()) 13069 return SDValue(); 13070 13071 LLVM_DEBUG( 13072 dbgs() << "aarch64-lower: concat_vectors bitcast simplification\n"); 13073 13074 MVT ConcatTy = MVT::getVectorVT(RHSTy.getVectorElementType(), 13075 RHSTy.getVectorNumElements() * 2); 13076 return DAG.getNode(ISD::BITCAST, dl, VT, 13077 DAG.getNode(ISD::CONCAT_VECTORS, dl, ConcatTy, 13078 DAG.getNode(ISD::BITCAST, dl, RHSTy, N0), 13079 RHS)); 13080 } 13081 13082 static SDValue tryCombineFixedPointConvert(SDNode *N, 13083 TargetLowering::DAGCombinerInfo &DCI, 13084 SelectionDAG &DAG) { 13085 // Wait until after everything is legalized to try this. That way we have 13086 // legal vector types and such. 13087 if (DCI.isBeforeLegalizeOps()) 13088 return SDValue(); 13089 // Transform a scalar conversion of a value from a lane extract into a 13090 // lane extract of a vector conversion. E.g., from foo1 to foo2: 13091 // double foo1(int64x2_t a) { return vcvtd_n_f64_s64(a[1], 9); } 13092 // double foo2(int64x2_t a) { return vcvtq_n_f64_s64(a, 9)[1]; } 13093 // 13094 // The second form interacts better with instruction selection and the 13095 // register allocator to avoid cross-class register copies that aren't 13096 // coalescable due to a lane reference. 13097 13098 // Check the operand and see if it originates from a lane extract. 13099 SDValue Op1 = N->getOperand(1); 13100 if (Op1.getOpcode() == ISD::EXTRACT_VECTOR_ELT) { 13101 // Yep, no additional predication needed. Perform the transform. 13102 SDValue IID = N->getOperand(0); 13103 SDValue Shift = N->getOperand(2); 13104 SDValue Vec = Op1.getOperand(0); 13105 SDValue Lane = Op1.getOperand(1); 13106 EVT ResTy = N->getValueType(0); 13107 EVT VecResTy; 13108 SDLoc DL(N); 13109 13110 // The vector width should be 128 bits by the time we get here, even 13111 // if it started as 64 bits (the extract_vector handling will have 13112 // done so). 13113 assert(Vec.getValueSizeInBits() == 128 && 13114 "unexpected vector size on extract_vector_elt!"); 13115 if (Vec.getValueType() == MVT::v4i32) 13116 VecResTy = MVT::v4f32; 13117 else if (Vec.getValueType() == MVT::v2i64) 13118 VecResTy = MVT::v2f64; 13119 else 13120 llvm_unreachable("unexpected vector type!"); 13121 13122 SDValue Convert = 13123 DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VecResTy, IID, Vec, Shift); 13124 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, ResTy, Convert, Lane); 13125 } 13126 return SDValue(); 13127 } 13128 13129 // AArch64 high-vector "long" operations are formed by performing the non-high 13130 // version on an extract_subvector of each operand which gets the high half: 13131 // 13132 // (longop2 LHS, RHS) == (longop (extract_high LHS), (extract_high RHS)) 13133 // 13134 // However, there are cases which don't have an extract_high explicitly, but 13135 // have another operation that can be made compatible with one for free. For 13136 // example: 13137 // 13138 // (dupv64 scalar) --> (extract_high (dup128 scalar)) 13139 // 13140 // This routine does the actual conversion of such DUPs, once outer routines 13141 // have determined that everything else is in order. 13142 // It also supports immediate DUP-like nodes (MOVI/MVNi), which we can fold 13143 // similarly here. 13144 static SDValue tryExtendDUPToExtractHigh(SDValue N, SelectionDAG &DAG) { 13145 switch (N.getOpcode()) { 13146 case AArch64ISD::DUP: 13147 case AArch64ISD::DUPLANE8: 13148 case AArch64ISD::DUPLANE16: 13149 case AArch64ISD::DUPLANE32: 13150 case AArch64ISD::DUPLANE64: 13151 case AArch64ISD::MOVI: 13152 case AArch64ISD::MOVIshift: 13153 case AArch64ISD::MOVIedit: 13154 case AArch64ISD::MOVImsl: 13155 case AArch64ISD::MVNIshift: 13156 case AArch64ISD::MVNImsl: 13157 break; 13158 default: 13159 // FMOV could be supported, but isn't very useful, as it would only occur 13160 // if you passed a bitcast' floating point immediate to an eligible long 13161 // integer op (addl, smull, ...). 13162 return SDValue(); 13163 } 13164 13165 MVT NarrowTy = N.getSimpleValueType(); 13166 if (!NarrowTy.is64BitVector()) 13167 return SDValue(); 13168 13169 MVT ElementTy = NarrowTy.getVectorElementType(); 13170 unsigned NumElems = NarrowTy.getVectorNumElements(); 13171 MVT NewVT = MVT::getVectorVT(ElementTy, NumElems * 2); 13172 13173 SDLoc dl(N); 13174 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, NarrowTy, 13175 DAG.getNode(N->getOpcode(), dl, NewVT, N->ops()), 13176 DAG.getConstant(NumElems, dl, MVT::i64)); 13177 } 13178 13179 static bool isEssentiallyExtractHighSubvector(SDValue N) { 13180 if (N.getOpcode() == ISD::BITCAST) 13181 N = N.getOperand(0); 13182 if (N.getOpcode() != ISD::EXTRACT_SUBVECTOR) 13183 return false; 13184 return cast<ConstantSDNode>(N.getOperand(1))->getAPIntValue() == 13185 N.getOperand(0).getValueType().getVectorNumElements() / 2; 13186 } 13187 13188 /// Helper structure to keep track of ISD::SET_CC operands. 13189 struct GenericSetCCInfo { 13190 const SDValue *Opnd0; 13191 const SDValue *Opnd1; 13192 ISD::CondCode CC; 13193 }; 13194 13195 /// Helper structure to keep track of a SET_CC lowered into AArch64 code. 13196 struct AArch64SetCCInfo { 13197 const SDValue *Cmp; 13198 AArch64CC::CondCode CC; 13199 }; 13200 13201 /// Helper structure to keep track of SetCC information. 13202 union SetCCInfo { 13203 GenericSetCCInfo Generic; 13204 AArch64SetCCInfo AArch64; 13205 }; 13206 13207 /// Helper structure to be able to read SetCC information. If set to 13208 /// true, IsAArch64 field, Info is a AArch64SetCCInfo, otherwise Info is a 13209 /// GenericSetCCInfo. 13210 struct SetCCInfoAndKind { 13211 SetCCInfo Info; 13212 bool IsAArch64; 13213 }; 13214 13215 /// Check whether or not \p Op is a SET_CC operation, either a generic or 13216 /// an 13217 /// AArch64 lowered one. 13218 /// \p SetCCInfo is filled accordingly. 13219 /// \post SetCCInfo is meanginfull only when this function returns true. 13220 /// \return True when Op is a kind of SET_CC operation. 13221 static bool isSetCC(SDValue Op, SetCCInfoAndKind &SetCCInfo) { 13222 // If this is a setcc, this is straight forward. 13223 if (Op.getOpcode() == ISD::SETCC) { 13224 SetCCInfo.Info.Generic.Opnd0 = &Op.getOperand(0); 13225 SetCCInfo.Info.Generic.Opnd1 = &Op.getOperand(1); 13226 SetCCInfo.Info.Generic.CC = cast<CondCodeSDNode>(Op.getOperand(2))->get(); 13227 SetCCInfo.IsAArch64 = false; 13228 return true; 13229 } 13230 // Otherwise, check if this is a matching csel instruction. 13231 // In other words: 13232 // - csel 1, 0, cc 13233 // - csel 0, 1, !cc 13234 if (Op.getOpcode() != AArch64ISD::CSEL) 13235 return false; 13236 // Set the information about the operands. 13237 // TODO: we want the operands of the Cmp not the csel 13238 SetCCInfo.Info.AArch64.Cmp = &Op.getOperand(3); 13239 SetCCInfo.IsAArch64 = true; 13240 SetCCInfo.Info.AArch64.CC = static_cast<AArch64CC::CondCode>( 13241 cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue()); 13242 13243 // Check that the operands matches the constraints: 13244 // (1) Both operands must be constants. 13245 // (2) One must be 1 and the other must be 0. 13246 ConstantSDNode *TValue = dyn_cast<ConstantSDNode>(Op.getOperand(0)); 13247 ConstantSDNode *FValue = dyn_cast<ConstantSDNode>(Op.getOperand(1)); 13248 13249 // Check (1). 13250 if (!TValue || !FValue) 13251 return false; 13252 13253 // Check (2). 13254 if (!TValue->isOne()) { 13255 // Update the comparison when we are interested in !cc. 13256 std::swap(TValue, FValue); 13257 SetCCInfo.Info.AArch64.CC = 13258 AArch64CC::getInvertedCondCode(SetCCInfo.Info.AArch64.CC); 13259 } 13260 return TValue->isOne() && FValue->isNullValue(); 13261 } 13262 13263 // Returns true if Op is setcc or zext of setcc. 13264 static bool isSetCCOrZExtSetCC(const SDValue& Op, SetCCInfoAndKind &Info) { 13265 if (isSetCC(Op, Info)) 13266 return true; 13267 return ((Op.getOpcode() == ISD::ZERO_EXTEND) && 13268 isSetCC(Op->getOperand(0), Info)); 13269 } 13270 13271 // The folding we want to perform is: 13272 // (add x, [zext] (setcc cc ...) ) 13273 // --> 13274 // (csel x, (add x, 1), !cc ...) 13275 // 13276 // The latter will get matched to a CSINC instruction. 13277 static SDValue performSetccAddFolding(SDNode *Op, SelectionDAG &DAG) { 13278 assert(Op && Op->getOpcode() == ISD::ADD && "Unexpected operation!"); 13279 SDValue LHS = Op->getOperand(0); 13280 SDValue RHS = Op->getOperand(1); 13281 SetCCInfoAndKind InfoAndKind; 13282 13283 // If both operands are a SET_CC, then we don't want to perform this 13284 // folding and create another csel as this results in more instructions 13285 // (and higher register usage). 13286 if (isSetCCOrZExtSetCC(LHS, InfoAndKind) && 13287 isSetCCOrZExtSetCC(RHS, InfoAndKind)) 13288 return SDValue(); 13289 13290 // If neither operand is a SET_CC, give up. 13291 if (!isSetCCOrZExtSetCC(LHS, InfoAndKind)) { 13292 std::swap(LHS, RHS); 13293 if (!isSetCCOrZExtSetCC(LHS, InfoAndKind)) 13294 return SDValue(); 13295 } 13296 13297 // FIXME: This could be generatized to work for FP comparisons. 13298 EVT CmpVT = InfoAndKind.IsAArch64 13299 ? InfoAndKind.Info.AArch64.Cmp->getOperand(0).getValueType() 13300 : InfoAndKind.Info.Generic.Opnd0->getValueType(); 13301 if (CmpVT != MVT::i32 && CmpVT != MVT::i64) 13302 return SDValue(); 13303 13304 SDValue CCVal; 13305 SDValue Cmp; 13306 SDLoc dl(Op); 13307 if (InfoAndKind.IsAArch64) { 13308 CCVal = DAG.getConstant( 13309 AArch64CC::getInvertedCondCode(InfoAndKind.Info.AArch64.CC), dl, 13310 MVT::i32); 13311 Cmp = *InfoAndKind.Info.AArch64.Cmp; 13312 } else 13313 Cmp = getAArch64Cmp( 13314 *InfoAndKind.Info.Generic.Opnd0, *InfoAndKind.Info.Generic.Opnd1, 13315 ISD::getSetCCInverse(InfoAndKind.Info.Generic.CC, CmpVT), CCVal, DAG, 13316 dl); 13317 13318 EVT VT = Op->getValueType(0); 13319 LHS = DAG.getNode(ISD::ADD, dl, VT, RHS, DAG.getConstant(1, dl, VT)); 13320 return DAG.getNode(AArch64ISD::CSEL, dl, VT, RHS, LHS, CCVal, Cmp); 13321 } 13322 13323 // ADD(UADDV a, UADDV b) --> UADDV(ADD a, b) 13324 static SDValue performUADDVCombine(SDNode *N, SelectionDAG &DAG) { 13325 EVT VT = N->getValueType(0); 13326 // Only scalar integer and vector types. 13327 if (N->getOpcode() != ISD::ADD || !VT.isScalarInteger()) 13328 return SDValue(); 13329 13330 SDValue LHS = N->getOperand(0); 13331 SDValue RHS = N->getOperand(1); 13332 if (LHS.getOpcode() != ISD::EXTRACT_VECTOR_ELT || 13333 RHS.getOpcode() != ISD::EXTRACT_VECTOR_ELT || LHS.getValueType() != VT) 13334 return SDValue(); 13335 13336 auto *LHSN1 = dyn_cast<ConstantSDNode>(LHS->getOperand(1)); 13337 auto *RHSN1 = dyn_cast<ConstantSDNode>(RHS->getOperand(1)); 13338 if (!LHSN1 || LHSN1 != RHSN1 || !RHSN1->isNullValue()) 13339 return SDValue(); 13340 13341 SDValue Op1 = LHS->getOperand(0); 13342 SDValue Op2 = RHS->getOperand(0); 13343 EVT OpVT1 = Op1.getValueType(); 13344 EVT OpVT2 = Op2.getValueType(); 13345 if (Op1.getOpcode() != AArch64ISD::UADDV || OpVT1 != OpVT2 || 13346 Op2.getOpcode() != AArch64ISD::UADDV || 13347 OpVT1.getVectorElementType() != VT) 13348 return SDValue(); 13349 13350 SDValue Val1 = Op1.getOperand(0); 13351 SDValue Val2 = Op2.getOperand(0); 13352 EVT ValVT = Val1->getValueType(0); 13353 SDLoc DL(N); 13354 SDValue AddVal = DAG.getNode(ISD::ADD, DL, ValVT, Val1, Val2); 13355 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, VT, 13356 DAG.getNode(AArch64ISD::UADDV, DL, ValVT, AddVal), 13357 DAG.getConstant(0, DL, MVT::i64)); 13358 } 13359 13360 // ADD(UDOT(zero, x, y), A) --> UDOT(A, x, y) 13361 static SDValue performAddDotCombine(SDNode *N, SelectionDAG &DAG) { 13362 EVT VT = N->getValueType(0); 13363 if (N->getOpcode() != ISD::ADD) 13364 return SDValue(); 13365 13366 SDValue Dot = N->getOperand(0); 13367 SDValue A = N->getOperand(1); 13368 // Handle commutivity 13369 auto isZeroDot = [](SDValue Dot) { 13370 return (Dot.getOpcode() == AArch64ISD::UDOT || 13371 Dot.getOpcode() == AArch64ISD::SDOT) && 13372 isZerosVector(Dot.getOperand(0).getNode()); 13373 }; 13374 if (!isZeroDot(Dot)) 13375 std::swap(Dot, A); 13376 if (!isZeroDot(Dot)) 13377 return SDValue(); 13378 13379 return DAG.getNode(Dot.getOpcode(), SDLoc(N), VT, A, Dot.getOperand(1), 13380 Dot.getOperand(2)); 13381 } 13382 13383 // The basic add/sub long vector instructions have variants with "2" on the end 13384 // which act on the high-half of their inputs. They are normally matched by 13385 // patterns like: 13386 // 13387 // (add (zeroext (extract_high LHS)), 13388 // (zeroext (extract_high RHS))) 13389 // -> uaddl2 vD, vN, vM 13390 // 13391 // However, if one of the extracts is something like a duplicate, this 13392 // instruction can still be used profitably. This function puts the DAG into a 13393 // more appropriate form for those patterns to trigger. 13394 static SDValue performAddSubLongCombine(SDNode *N, 13395 TargetLowering::DAGCombinerInfo &DCI, 13396 SelectionDAG &DAG) { 13397 if (DCI.isBeforeLegalizeOps()) 13398 return SDValue(); 13399 13400 MVT VT = N->getSimpleValueType(0); 13401 if (!VT.is128BitVector()) { 13402 if (N->getOpcode() == ISD::ADD) 13403 return performSetccAddFolding(N, DAG); 13404 return SDValue(); 13405 } 13406 13407 // Make sure both branches are extended in the same way. 13408 SDValue LHS = N->getOperand(0); 13409 SDValue RHS = N->getOperand(1); 13410 if ((LHS.getOpcode() != ISD::ZERO_EXTEND && 13411 LHS.getOpcode() != ISD::SIGN_EXTEND) || 13412 LHS.getOpcode() != RHS.getOpcode()) 13413 return SDValue(); 13414 13415 unsigned ExtType = LHS.getOpcode(); 13416 13417 // It's not worth doing if at least one of the inputs isn't already an 13418 // extract, but we don't know which it'll be so we have to try both. 13419 if (isEssentiallyExtractHighSubvector(LHS.getOperand(0))) { 13420 RHS = tryExtendDUPToExtractHigh(RHS.getOperand(0), DAG); 13421 if (!RHS.getNode()) 13422 return SDValue(); 13423 13424 RHS = DAG.getNode(ExtType, SDLoc(N), VT, RHS); 13425 } else if (isEssentiallyExtractHighSubvector(RHS.getOperand(0))) { 13426 LHS = tryExtendDUPToExtractHigh(LHS.getOperand(0), DAG); 13427 if (!LHS.getNode()) 13428 return SDValue(); 13429 13430 LHS = DAG.getNode(ExtType, SDLoc(N), VT, LHS); 13431 } 13432 13433 return DAG.getNode(N->getOpcode(), SDLoc(N), VT, LHS, RHS); 13434 } 13435 13436 static SDValue performAddSubCombine(SDNode *N, 13437 TargetLowering::DAGCombinerInfo &DCI, 13438 SelectionDAG &DAG) { 13439 // Try to change sum of two reductions. 13440 if (SDValue Val = performUADDVCombine(N, DAG)) 13441 return Val; 13442 if (SDValue Val = performAddDotCombine(N, DAG)) 13443 return Val; 13444 13445 return performAddSubLongCombine(N, DCI, DAG); 13446 } 13447 13448 // Massage DAGs which we can use the high-half "long" operations on into 13449 // something isel will recognize better. E.g. 13450 // 13451 // (aarch64_neon_umull (extract_high vec) (dupv64 scalar)) --> 13452 // (aarch64_neon_umull (extract_high (v2i64 vec))) 13453 // (extract_high (v2i64 (dup128 scalar))))) 13454 // 13455 static SDValue tryCombineLongOpWithDup(unsigned IID, SDNode *N, 13456 TargetLowering::DAGCombinerInfo &DCI, 13457 SelectionDAG &DAG) { 13458 if (DCI.isBeforeLegalizeOps()) 13459 return SDValue(); 13460 13461 SDValue LHS = N->getOperand((IID == Intrinsic::not_intrinsic) ? 0 : 1); 13462 SDValue RHS = N->getOperand((IID == Intrinsic::not_intrinsic) ? 1 : 2); 13463 assert(LHS.getValueType().is64BitVector() && 13464 RHS.getValueType().is64BitVector() && 13465 "unexpected shape for long operation"); 13466 13467 // Either node could be a DUP, but it's not worth doing both of them (you'd 13468 // just as well use the non-high version) so look for a corresponding extract 13469 // operation on the other "wing". 13470 if (isEssentiallyExtractHighSubvector(LHS)) { 13471 RHS = tryExtendDUPToExtractHigh(RHS, DAG); 13472 if (!RHS.getNode()) 13473 return SDValue(); 13474 } else if (isEssentiallyExtractHighSubvector(RHS)) { 13475 LHS = tryExtendDUPToExtractHigh(LHS, DAG); 13476 if (!LHS.getNode()) 13477 return SDValue(); 13478 } 13479 13480 if (IID == Intrinsic::not_intrinsic) 13481 return DAG.getNode(N->getOpcode(), SDLoc(N), N->getValueType(0), LHS, RHS); 13482 13483 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, SDLoc(N), N->getValueType(0), 13484 N->getOperand(0), LHS, RHS); 13485 } 13486 13487 static SDValue tryCombineShiftImm(unsigned IID, SDNode *N, SelectionDAG &DAG) { 13488 MVT ElemTy = N->getSimpleValueType(0).getScalarType(); 13489 unsigned ElemBits = ElemTy.getSizeInBits(); 13490 13491 int64_t ShiftAmount; 13492 if (BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(N->getOperand(2))) { 13493 APInt SplatValue, SplatUndef; 13494 unsigned SplatBitSize; 13495 bool HasAnyUndefs; 13496 if (!BVN->isConstantSplat(SplatValue, SplatUndef, SplatBitSize, 13497 HasAnyUndefs, ElemBits) || 13498 SplatBitSize != ElemBits) 13499 return SDValue(); 13500 13501 ShiftAmount = SplatValue.getSExtValue(); 13502 } else if (ConstantSDNode *CVN = dyn_cast<ConstantSDNode>(N->getOperand(2))) { 13503 ShiftAmount = CVN->getSExtValue(); 13504 } else 13505 return SDValue(); 13506 13507 unsigned Opcode; 13508 bool IsRightShift; 13509 switch (IID) { 13510 default: 13511 llvm_unreachable("Unknown shift intrinsic"); 13512 case Intrinsic::aarch64_neon_sqshl: 13513 Opcode = AArch64ISD::SQSHL_I; 13514 IsRightShift = false; 13515 break; 13516 case Intrinsic::aarch64_neon_uqshl: 13517 Opcode = AArch64ISD::UQSHL_I; 13518 IsRightShift = false; 13519 break; 13520 case Intrinsic::aarch64_neon_srshl: 13521 Opcode = AArch64ISD::SRSHR_I; 13522 IsRightShift = true; 13523 break; 13524 case Intrinsic::aarch64_neon_urshl: 13525 Opcode = AArch64ISD::URSHR_I; 13526 IsRightShift = true; 13527 break; 13528 case Intrinsic::aarch64_neon_sqshlu: 13529 Opcode = AArch64ISD::SQSHLU_I; 13530 IsRightShift = false; 13531 break; 13532 case Intrinsic::aarch64_neon_sshl: 13533 case Intrinsic::aarch64_neon_ushl: 13534 // For positive shift amounts we can use SHL, as ushl/sshl perform a regular 13535 // left shift for positive shift amounts. Below, we only replace the current 13536 // node with VSHL, if this condition is met. 13537 Opcode = AArch64ISD::VSHL; 13538 IsRightShift = false; 13539 break; 13540 } 13541 13542 if (IsRightShift && ShiftAmount <= -1 && ShiftAmount >= -(int)ElemBits) { 13543 SDLoc dl(N); 13544 return DAG.getNode(Opcode, dl, N->getValueType(0), N->getOperand(1), 13545 DAG.getConstant(-ShiftAmount, dl, MVT::i32)); 13546 } else if (!IsRightShift && ShiftAmount >= 0 && ShiftAmount < ElemBits) { 13547 SDLoc dl(N); 13548 return DAG.getNode(Opcode, dl, N->getValueType(0), N->getOperand(1), 13549 DAG.getConstant(ShiftAmount, dl, MVT::i32)); 13550 } 13551 13552 return SDValue(); 13553 } 13554 13555 // The CRC32[BH] instructions ignore the high bits of their data operand. Since 13556 // the intrinsics must be legal and take an i32, this means there's almost 13557 // certainly going to be a zext in the DAG which we can eliminate. 13558 static SDValue tryCombineCRC32(unsigned Mask, SDNode *N, SelectionDAG &DAG) { 13559 SDValue AndN = N->getOperand(2); 13560 if (AndN.getOpcode() != ISD::AND) 13561 return SDValue(); 13562 13563 ConstantSDNode *CMask = dyn_cast<ConstantSDNode>(AndN.getOperand(1)); 13564 if (!CMask || CMask->getZExtValue() != Mask) 13565 return SDValue(); 13566 13567 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, SDLoc(N), MVT::i32, 13568 N->getOperand(0), N->getOperand(1), AndN.getOperand(0)); 13569 } 13570 13571 static SDValue combineAcrossLanesIntrinsic(unsigned Opc, SDNode *N, 13572 SelectionDAG &DAG) { 13573 SDLoc dl(N); 13574 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, N->getValueType(0), 13575 DAG.getNode(Opc, dl, 13576 N->getOperand(1).getSimpleValueType(), 13577 N->getOperand(1)), 13578 DAG.getConstant(0, dl, MVT::i64)); 13579 } 13580 13581 static SDValue LowerSVEIntrinsicIndex(SDNode *N, SelectionDAG &DAG) { 13582 SDLoc DL(N); 13583 SDValue Op1 = N->getOperand(1); 13584 SDValue Op2 = N->getOperand(2); 13585 EVT ScalarTy = Op1.getValueType(); 13586 13587 if ((ScalarTy == MVT::i8) || (ScalarTy == MVT::i16)) { 13588 Op1 = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i32, Op1); 13589 Op2 = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i32, Op2); 13590 } 13591 13592 return DAG.getNode(AArch64ISD::INDEX_VECTOR, DL, N->getValueType(0), 13593 Op1, Op2); 13594 } 13595 13596 static SDValue LowerSVEIntrinsicDUP(SDNode *N, SelectionDAG &DAG) { 13597 SDLoc dl(N); 13598 SDValue Scalar = N->getOperand(3); 13599 EVT ScalarTy = Scalar.getValueType(); 13600 13601 if ((ScalarTy == MVT::i8) || (ScalarTy == MVT::i16)) 13602 Scalar = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, Scalar); 13603 13604 SDValue Passthru = N->getOperand(1); 13605 SDValue Pred = N->getOperand(2); 13606 return DAG.getNode(AArch64ISD::DUP_MERGE_PASSTHRU, dl, N->getValueType(0), 13607 Pred, Scalar, Passthru); 13608 } 13609 13610 static SDValue LowerSVEIntrinsicEXT(SDNode *N, SelectionDAG &DAG) { 13611 SDLoc dl(N); 13612 LLVMContext &Ctx = *DAG.getContext(); 13613 EVT VT = N->getValueType(0); 13614 13615 assert(VT.isScalableVector() && "Expected a scalable vector."); 13616 13617 // Current lowering only supports the SVE-ACLE types. 13618 if (VT.getSizeInBits().getKnownMinSize() != AArch64::SVEBitsPerBlock) 13619 return SDValue(); 13620 13621 unsigned ElemSize = VT.getVectorElementType().getSizeInBits() / 8; 13622 unsigned ByteSize = VT.getSizeInBits().getKnownMinSize() / 8; 13623 EVT ByteVT = 13624 EVT::getVectorVT(Ctx, MVT::i8, ElementCount::getScalable(ByteSize)); 13625 13626 // Convert everything to the domain of EXT (i.e bytes). 13627 SDValue Op0 = DAG.getNode(ISD::BITCAST, dl, ByteVT, N->getOperand(1)); 13628 SDValue Op1 = DAG.getNode(ISD::BITCAST, dl, ByteVT, N->getOperand(2)); 13629 SDValue Op2 = DAG.getNode(ISD::MUL, dl, MVT::i32, N->getOperand(3), 13630 DAG.getConstant(ElemSize, dl, MVT::i32)); 13631 13632 SDValue EXT = DAG.getNode(AArch64ISD::EXT, dl, ByteVT, Op0, Op1, Op2); 13633 return DAG.getNode(ISD::BITCAST, dl, VT, EXT); 13634 } 13635 13636 static SDValue tryConvertSVEWideCompare(SDNode *N, ISD::CondCode CC, 13637 TargetLowering::DAGCombinerInfo &DCI, 13638 SelectionDAG &DAG) { 13639 if (DCI.isBeforeLegalize()) 13640 return SDValue(); 13641 13642 SDValue Comparator = N->getOperand(3); 13643 if (Comparator.getOpcode() == AArch64ISD::DUP || 13644 Comparator.getOpcode() == ISD::SPLAT_VECTOR) { 13645 unsigned IID = getIntrinsicID(N); 13646 EVT VT = N->getValueType(0); 13647 EVT CmpVT = N->getOperand(2).getValueType(); 13648 SDValue Pred = N->getOperand(1); 13649 SDValue Imm; 13650 SDLoc DL(N); 13651 13652 switch (IID) { 13653 default: 13654 llvm_unreachable("Called with wrong intrinsic!"); 13655 break; 13656 13657 // Signed comparisons 13658 case Intrinsic::aarch64_sve_cmpeq_wide: 13659 case Intrinsic::aarch64_sve_cmpne_wide: 13660 case Intrinsic::aarch64_sve_cmpge_wide: 13661 case Intrinsic::aarch64_sve_cmpgt_wide: 13662 case Intrinsic::aarch64_sve_cmplt_wide: 13663 case Intrinsic::aarch64_sve_cmple_wide: { 13664 if (auto *CN = dyn_cast<ConstantSDNode>(Comparator.getOperand(0))) { 13665 int64_t ImmVal = CN->getSExtValue(); 13666 if (ImmVal >= -16 && ImmVal <= 15) 13667 Imm = DAG.getConstant(ImmVal, DL, MVT::i32); 13668 else 13669 return SDValue(); 13670 } 13671 break; 13672 } 13673 // Unsigned comparisons 13674 case Intrinsic::aarch64_sve_cmphs_wide: 13675 case Intrinsic::aarch64_sve_cmphi_wide: 13676 case Intrinsic::aarch64_sve_cmplo_wide: 13677 case Intrinsic::aarch64_sve_cmpls_wide: { 13678 if (auto *CN = dyn_cast<ConstantSDNode>(Comparator.getOperand(0))) { 13679 uint64_t ImmVal = CN->getZExtValue(); 13680 if (ImmVal <= 127) 13681 Imm = DAG.getConstant(ImmVal, DL, MVT::i32); 13682 else 13683 return SDValue(); 13684 } 13685 break; 13686 } 13687 } 13688 13689 if (!Imm) 13690 return SDValue(); 13691 13692 SDValue Splat = DAG.getNode(ISD::SPLAT_VECTOR, DL, CmpVT, Imm); 13693 return DAG.getNode(AArch64ISD::SETCC_MERGE_ZERO, DL, VT, Pred, 13694 N->getOperand(2), Splat, DAG.getCondCode(CC)); 13695 } 13696 13697 return SDValue(); 13698 } 13699 13700 static SDValue getPTest(SelectionDAG &DAG, EVT VT, SDValue Pg, SDValue Op, 13701 AArch64CC::CondCode Cond) { 13702 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 13703 13704 SDLoc DL(Op); 13705 assert(Op.getValueType().isScalableVector() && 13706 TLI.isTypeLegal(Op.getValueType()) && 13707 "Expected legal scalable vector type!"); 13708 13709 // Ensure target specific opcodes are using legal type. 13710 EVT OutVT = TLI.getTypeToTransformTo(*DAG.getContext(), VT); 13711 SDValue TVal = DAG.getConstant(1, DL, OutVT); 13712 SDValue FVal = DAG.getConstant(0, DL, OutVT); 13713 13714 // Set condition code (CC) flags. 13715 SDValue Test = DAG.getNode(AArch64ISD::PTEST, DL, MVT::Other, Pg, Op); 13716 13717 // Convert CC to integer based on requested condition. 13718 // NOTE: Cond is inverted to promote CSEL's removal when it feeds a compare. 13719 SDValue CC = DAG.getConstant(getInvertedCondCode(Cond), DL, MVT::i32); 13720 SDValue Res = DAG.getNode(AArch64ISD::CSEL, DL, OutVT, FVal, TVal, CC, Test); 13721 return DAG.getZExtOrTrunc(Res, DL, VT); 13722 } 13723 13724 static SDValue combineSVEReductionInt(SDNode *N, unsigned Opc, 13725 SelectionDAG &DAG) { 13726 SDLoc DL(N); 13727 13728 SDValue Pred = N->getOperand(1); 13729 SDValue VecToReduce = N->getOperand(2); 13730 13731 // NOTE: The integer reduction's result type is not always linked to the 13732 // operand's element type so we construct it from the intrinsic's result type. 13733 EVT ReduceVT = getPackedSVEVectorVT(N->getValueType(0)); 13734 SDValue Reduce = DAG.getNode(Opc, DL, ReduceVT, Pred, VecToReduce); 13735 13736 // SVE reductions set the whole vector register with the first element 13737 // containing the reduction result, which we'll now extract. 13738 SDValue Zero = DAG.getConstant(0, DL, MVT::i64); 13739 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, N->getValueType(0), Reduce, 13740 Zero); 13741 } 13742 13743 static SDValue combineSVEReductionFP(SDNode *N, unsigned Opc, 13744 SelectionDAG &DAG) { 13745 SDLoc DL(N); 13746 13747 SDValue Pred = N->getOperand(1); 13748 SDValue VecToReduce = N->getOperand(2); 13749 13750 EVT ReduceVT = VecToReduce.getValueType(); 13751 SDValue Reduce = DAG.getNode(Opc, DL, ReduceVT, Pred, VecToReduce); 13752 13753 // SVE reductions set the whole vector register with the first element 13754 // containing the reduction result, which we'll now extract. 13755 SDValue Zero = DAG.getConstant(0, DL, MVT::i64); 13756 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, N->getValueType(0), Reduce, 13757 Zero); 13758 } 13759 13760 static SDValue combineSVEReductionOrderedFP(SDNode *N, unsigned Opc, 13761 SelectionDAG &DAG) { 13762 SDLoc DL(N); 13763 13764 SDValue Pred = N->getOperand(1); 13765 SDValue InitVal = N->getOperand(2); 13766 SDValue VecToReduce = N->getOperand(3); 13767 EVT ReduceVT = VecToReduce.getValueType(); 13768 13769 // Ordered reductions use the first lane of the result vector as the 13770 // reduction's initial value. 13771 SDValue Zero = DAG.getConstant(0, DL, MVT::i64); 13772 InitVal = DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, ReduceVT, 13773 DAG.getUNDEF(ReduceVT), InitVal, Zero); 13774 13775 SDValue Reduce = DAG.getNode(Opc, DL, ReduceVT, Pred, InitVal, VecToReduce); 13776 13777 // SVE reductions set the whole vector register with the first element 13778 // containing the reduction result, which we'll now extract. 13779 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, N->getValueType(0), Reduce, 13780 Zero); 13781 } 13782 13783 // If a merged operation has no inactive lanes we can relax it to a predicated 13784 // or unpredicated operation, which potentially allows better isel (perhaps 13785 // using immediate forms) or relaxing register reuse requirements. 13786 static SDValue convertMergedOpToPredOp(SDNode *N, unsigned PredOpc, 13787 SelectionDAG &DAG) { 13788 assert(N->getOpcode() == ISD::INTRINSIC_WO_CHAIN && "Expected intrinsic!"); 13789 assert(N->getNumOperands() == 4 && "Expected 3 operand intrinsic!"); 13790 SDValue Pg = N->getOperand(1); 13791 13792 // ISD way to specify an all active predicate. 13793 if ((Pg.getOpcode() == AArch64ISD::PTRUE) && 13794 (Pg.getConstantOperandVal(0) == AArch64SVEPredPattern::all)) 13795 return DAG.getNode(PredOpc, SDLoc(N), N->getValueType(0), Pg, 13796 N->getOperand(2), N->getOperand(3)); 13797 13798 // FUTURE: SplatVector(true) 13799 return SDValue(); 13800 } 13801 13802 static SDValue performIntrinsicCombine(SDNode *N, 13803 TargetLowering::DAGCombinerInfo &DCI, 13804 const AArch64Subtarget *Subtarget) { 13805 SelectionDAG &DAG = DCI.DAG; 13806 unsigned IID = getIntrinsicID(N); 13807 switch (IID) { 13808 default: 13809 break; 13810 case Intrinsic::aarch64_neon_vcvtfxs2fp: 13811 case Intrinsic::aarch64_neon_vcvtfxu2fp: 13812 return tryCombineFixedPointConvert(N, DCI, DAG); 13813 case Intrinsic::aarch64_neon_saddv: 13814 return combineAcrossLanesIntrinsic(AArch64ISD::SADDV, N, DAG); 13815 case Intrinsic::aarch64_neon_uaddv: 13816 return combineAcrossLanesIntrinsic(AArch64ISD::UADDV, N, DAG); 13817 case Intrinsic::aarch64_neon_sminv: 13818 return combineAcrossLanesIntrinsic(AArch64ISD::SMINV, N, DAG); 13819 case Intrinsic::aarch64_neon_uminv: 13820 return combineAcrossLanesIntrinsic(AArch64ISD::UMINV, N, DAG); 13821 case Intrinsic::aarch64_neon_smaxv: 13822 return combineAcrossLanesIntrinsic(AArch64ISD::SMAXV, N, DAG); 13823 case Intrinsic::aarch64_neon_umaxv: 13824 return combineAcrossLanesIntrinsic(AArch64ISD::UMAXV, N, DAG); 13825 case Intrinsic::aarch64_neon_fmax: 13826 return DAG.getNode(ISD::FMAXIMUM, SDLoc(N), N->getValueType(0), 13827 N->getOperand(1), N->getOperand(2)); 13828 case Intrinsic::aarch64_neon_fmin: 13829 return DAG.getNode(ISD::FMINIMUM, SDLoc(N), N->getValueType(0), 13830 N->getOperand(1), N->getOperand(2)); 13831 case Intrinsic::aarch64_neon_fmaxnm: 13832 return DAG.getNode(ISD::FMAXNUM, SDLoc(N), N->getValueType(0), 13833 N->getOperand(1), N->getOperand(2)); 13834 case Intrinsic::aarch64_neon_fminnm: 13835 return DAG.getNode(ISD::FMINNUM, SDLoc(N), N->getValueType(0), 13836 N->getOperand(1), N->getOperand(2)); 13837 case Intrinsic::aarch64_neon_smull: 13838 case Intrinsic::aarch64_neon_umull: 13839 case Intrinsic::aarch64_neon_pmull: 13840 case Intrinsic::aarch64_neon_sqdmull: 13841 return tryCombineLongOpWithDup(IID, N, DCI, DAG); 13842 case Intrinsic::aarch64_neon_sqshl: 13843 case Intrinsic::aarch64_neon_uqshl: 13844 case Intrinsic::aarch64_neon_sqshlu: 13845 case Intrinsic::aarch64_neon_srshl: 13846 case Intrinsic::aarch64_neon_urshl: 13847 case Intrinsic::aarch64_neon_sshl: 13848 case Intrinsic::aarch64_neon_ushl: 13849 return tryCombineShiftImm(IID, N, DAG); 13850 case Intrinsic::aarch64_crc32b: 13851 case Intrinsic::aarch64_crc32cb: 13852 return tryCombineCRC32(0xff, N, DAG); 13853 case Intrinsic::aarch64_crc32h: 13854 case Intrinsic::aarch64_crc32ch: 13855 return tryCombineCRC32(0xffff, N, DAG); 13856 case Intrinsic::aarch64_sve_saddv: 13857 // There is no i64 version of SADDV because the sign is irrelevant. 13858 if (N->getOperand(2)->getValueType(0).getVectorElementType() == MVT::i64) 13859 return combineSVEReductionInt(N, AArch64ISD::UADDV_PRED, DAG); 13860 else 13861 return combineSVEReductionInt(N, AArch64ISD::SADDV_PRED, DAG); 13862 case Intrinsic::aarch64_sve_uaddv: 13863 return combineSVEReductionInt(N, AArch64ISD::UADDV_PRED, DAG); 13864 case Intrinsic::aarch64_sve_smaxv: 13865 return combineSVEReductionInt(N, AArch64ISD::SMAXV_PRED, DAG); 13866 case Intrinsic::aarch64_sve_umaxv: 13867 return combineSVEReductionInt(N, AArch64ISD::UMAXV_PRED, DAG); 13868 case Intrinsic::aarch64_sve_sminv: 13869 return combineSVEReductionInt(N, AArch64ISD::SMINV_PRED, DAG); 13870 case Intrinsic::aarch64_sve_uminv: 13871 return combineSVEReductionInt(N, AArch64ISD::UMINV_PRED, DAG); 13872 case Intrinsic::aarch64_sve_orv: 13873 return combineSVEReductionInt(N, AArch64ISD::ORV_PRED, DAG); 13874 case Intrinsic::aarch64_sve_eorv: 13875 return combineSVEReductionInt(N, AArch64ISD::EORV_PRED, DAG); 13876 case Intrinsic::aarch64_sve_andv: 13877 return combineSVEReductionInt(N, AArch64ISD::ANDV_PRED, DAG); 13878 case Intrinsic::aarch64_sve_index: 13879 return LowerSVEIntrinsicIndex(N, DAG); 13880 case Intrinsic::aarch64_sve_dup: 13881 return LowerSVEIntrinsicDUP(N, DAG); 13882 case Intrinsic::aarch64_sve_dup_x: 13883 return DAG.getNode(ISD::SPLAT_VECTOR, SDLoc(N), N->getValueType(0), 13884 N->getOperand(1)); 13885 case Intrinsic::aarch64_sve_ext: 13886 return LowerSVEIntrinsicEXT(N, DAG); 13887 case Intrinsic::aarch64_sve_smin: 13888 return convertMergedOpToPredOp(N, AArch64ISD::SMIN_PRED, DAG); 13889 case Intrinsic::aarch64_sve_umin: 13890 return convertMergedOpToPredOp(N, AArch64ISD::UMIN_PRED, DAG); 13891 case Intrinsic::aarch64_sve_smax: 13892 return convertMergedOpToPredOp(N, AArch64ISD::SMAX_PRED, DAG); 13893 case Intrinsic::aarch64_sve_umax: 13894 return convertMergedOpToPredOp(N, AArch64ISD::UMAX_PRED, DAG); 13895 case Intrinsic::aarch64_sve_lsl: 13896 return convertMergedOpToPredOp(N, AArch64ISD::SHL_PRED, DAG); 13897 case Intrinsic::aarch64_sve_lsr: 13898 return convertMergedOpToPredOp(N, AArch64ISD::SRL_PRED, DAG); 13899 case Intrinsic::aarch64_sve_asr: 13900 return convertMergedOpToPredOp(N, AArch64ISD::SRA_PRED, DAG); 13901 case Intrinsic::aarch64_sve_cmphs: 13902 if (!N->getOperand(2).getValueType().isFloatingPoint()) 13903 return DAG.getNode(AArch64ISD::SETCC_MERGE_ZERO, SDLoc(N), 13904 N->getValueType(0), N->getOperand(1), N->getOperand(2), 13905 N->getOperand(3), DAG.getCondCode(ISD::SETUGE)); 13906 break; 13907 case Intrinsic::aarch64_sve_cmphi: 13908 if (!N->getOperand(2).getValueType().isFloatingPoint()) 13909 return DAG.getNode(AArch64ISD::SETCC_MERGE_ZERO, SDLoc(N), 13910 N->getValueType(0), N->getOperand(1), N->getOperand(2), 13911 N->getOperand(3), DAG.getCondCode(ISD::SETUGT)); 13912 break; 13913 case Intrinsic::aarch64_sve_cmpge: 13914 if (!N->getOperand(2).getValueType().isFloatingPoint()) 13915 return DAG.getNode(AArch64ISD::SETCC_MERGE_ZERO, SDLoc(N), 13916 N->getValueType(0), N->getOperand(1), N->getOperand(2), 13917 N->getOperand(3), DAG.getCondCode(ISD::SETGE)); 13918 break; 13919 case Intrinsic::aarch64_sve_cmpgt: 13920 if (!N->getOperand(2).getValueType().isFloatingPoint()) 13921 return DAG.getNode(AArch64ISD::SETCC_MERGE_ZERO, SDLoc(N), 13922 N->getValueType(0), N->getOperand(1), N->getOperand(2), 13923 N->getOperand(3), DAG.getCondCode(ISD::SETGT)); 13924 break; 13925 case Intrinsic::aarch64_sve_cmpeq: 13926 if (!N->getOperand(2).getValueType().isFloatingPoint()) 13927 return DAG.getNode(AArch64ISD::SETCC_MERGE_ZERO, SDLoc(N), 13928 N->getValueType(0), N->getOperand(1), N->getOperand(2), 13929 N->getOperand(3), DAG.getCondCode(ISD::SETEQ)); 13930 break; 13931 case Intrinsic::aarch64_sve_cmpne: 13932 if (!N->getOperand(2).getValueType().isFloatingPoint()) 13933 return DAG.getNode(AArch64ISD::SETCC_MERGE_ZERO, SDLoc(N), 13934 N->getValueType(0), N->getOperand(1), N->getOperand(2), 13935 N->getOperand(3), DAG.getCondCode(ISD::SETNE)); 13936 break; 13937 case Intrinsic::aarch64_sve_fadda: 13938 return combineSVEReductionOrderedFP(N, AArch64ISD::FADDA_PRED, DAG); 13939 case Intrinsic::aarch64_sve_faddv: 13940 return combineSVEReductionFP(N, AArch64ISD::FADDV_PRED, DAG); 13941 case Intrinsic::aarch64_sve_fmaxnmv: 13942 return combineSVEReductionFP(N, AArch64ISD::FMAXNMV_PRED, DAG); 13943 case Intrinsic::aarch64_sve_fmaxv: 13944 return combineSVEReductionFP(N, AArch64ISD::FMAXV_PRED, DAG); 13945 case Intrinsic::aarch64_sve_fminnmv: 13946 return combineSVEReductionFP(N, AArch64ISD::FMINNMV_PRED, DAG); 13947 case Intrinsic::aarch64_sve_fminv: 13948 return combineSVEReductionFP(N, AArch64ISD::FMINV_PRED, DAG); 13949 case Intrinsic::aarch64_sve_sel: 13950 return DAG.getNode(ISD::VSELECT, SDLoc(N), N->getValueType(0), 13951 N->getOperand(1), N->getOperand(2), N->getOperand(3)); 13952 case Intrinsic::aarch64_sve_cmpeq_wide: 13953 return tryConvertSVEWideCompare(N, ISD::SETEQ, DCI, DAG); 13954 case Intrinsic::aarch64_sve_cmpne_wide: 13955 return tryConvertSVEWideCompare(N, ISD::SETNE, DCI, DAG); 13956 case Intrinsic::aarch64_sve_cmpge_wide: 13957 return tryConvertSVEWideCompare(N, ISD::SETGE, DCI, DAG); 13958 case Intrinsic::aarch64_sve_cmpgt_wide: 13959 return tryConvertSVEWideCompare(N, ISD::SETGT, DCI, DAG); 13960 case Intrinsic::aarch64_sve_cmplt_wide: 13961 return tryConvertSVEWideCompare(N, ISD::SETLT, DCI, DAG); 13962 case Intrinsic::aarch64_sve_cmple_wide: 13963 return tryConvertSVEWideCompare(N, ISD::SETLE, DCI, DAG); 13964 case Intrinsic::aarch64_sve_cmphs_wide: 13965 return tryConvertSVEWideCompare(N, ISD::SETUGE, DCI, DAG); 13966 case Intrinsic::aarch64_sve_cmphi_wide: 13967 return tryConvertSVEWideCompare(N, ISD::SETUGT, DCI, DAG); 13968 case Intrinsic::aarch64_sve_cmplo_wide: 13969 return tryConvertSVEWideCompare(N, ISD::SETULT, DCI, DAG); 13970 case Intrinsic::aarch64_sve_cmpls_wide: 13971 return tryConvertSVEWideCompare(N, ISD::SETULE, DCI, DAG); 13972 case Intrinsic::aarch64_sve_ptest_any: 13973 return getPTest(DAG, N->getValueType(0), N->getOperand(1), N->getOperand(2), 13974 AArch64CC::ANY_ACTIVE); 13975 case Intrinsic::aarch64_sve_ptest_first: 13976 return getPTest(DAG, N->getValueType(0), N->getOperand(1), N->getOperand(2), 13977 AArch64CC::FIRST_ACTIVE); 13978 case Intrinsic::aarch64_sve_ptest_last: 13979 return getPTest(DAG, N->getValueType(0), N->getOperand(1), N->getOperand(2), 13980 AArch64CC::LAST_ACTIVE); 13981 } 13982 return SDValue(); 13983 } 13984 13985 static SDValue performExtendCombine(SDNode *N, 13986 TargetLowering::DAGCombinerInfo &DCI, 13987 SelectionDAG &DAG) { 13988 // If we see something like (zext (sabd (extract_high ...), (DUP ...))) then 13989 // we can convert that DUP into another extract_high (of a bigger DUP), which 13990 // helps the backend to decide that an sabdl2 would be useful, saving a real 13991 // extract_high operation. 13992 if (!DCI.isBeforeLegalizeOps() && N->getOpcode() == ISD::ZERO_EXTEND && 13993 (N->getOperand(0).getOpcode() == AArch64ISD::UABD || 13994 N->getOperand(0).getOpcode() == AArch64ISD::SABD)) { 13995 SDNode *ABDNode = N->getOperand(0).getNode(); 13996 SDValue NewABD = 13997 tryCombineLongOpWithDup(Intrinsic::not_intrinsic, ABDNode, DCI, DAG); 13998 if (!NewABD.getNode()) 13999 return SDValue(); 14000 14001 return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), N->getValueType(0), NewABD); 14002 } 14003 return SDValue(); 14004 } 14005 14006 static SDValue splitStoreSplat(SelectionDAG &DAG, StoreSDNode &St, 14007 SDValue SplatVal, unsigned NumVecElts) { 14008 assert(!St.isTruncatingStore() && "cannot split truncating vector store"); 14009 unsigned OrigAlignment = St.getAlignment(); 14010 unsigned EltOffset = SplatVal.getValueType().getSizeInBits() / 8; 14011 14012 // Create scalar stores. This is at least as good as the code sequence for a 14013 // split unaligned store which is a dup.s, ext.b, and two stores. 14014 // Most of the time the three stores should be replaced by store pair 14015 // instructions (stp). 14016 SDLoc DL(&St); 14017 SDValue BasePtr = St.getBasePtr(); 14018 uint64_t BaseOffset = 0; 14019 14020 const MachinePointerInfo &PtrInfo = St.getPointerInfo(); 14021 SDValue NewST1 = 14022 DAG.getStore(St.getChain(), DL, SplatVal, BasePtr, PtrInfo, 14023 OrigAlignment, St.getMemOperand()->getFlags()); 14024 14025 // As this in ISel, we will not merge this add which may degrade results. 14026 if (BasePtr->getOpcode() == ISD::ADD && 14027 isa<ConstantSDNode>(BasePtr->getOperand(1))) { 14028 BaseOffset = cast<ConstantSDNode>(BasePtr->getOperand(1))->getSExtValue(); 14029 BasePtr = BasePtr->getOperand(0); 14030 } 14031 14032 unsigned Offset = EltOffset; 14033 while (--NumVecElts) { 14034 unsigned Alignment = MinAlign(OrigAlignment, Offset); 14035 SDValue OffsetPtr = 14036 DAG.getNode(ISD::ADD, DL, MVT::i64, BasePtr, 14037 DAG.getConstant(BaseOffset + Offset, DL, MVT::i64)); 14038 NewST1 = DAG.getStore(NewST1.getValue(0), DL, SplatVal, OffsetPtr, 14039 PtrInfo.getWithOffset(Offset), Alignment, 14040 St.getMemOperand()->getFlags()); 14041 Offset += EltOffset; 14042 } 14043 return NewST1; 14044 } 14045 14046 // Returns an SVE type that ContentTy can be trivially sign or zero extended 14047 // into. 14048 static MVT getSVEContainerType(EVT ContentTy) { 14049 assert(ContentTy.isSimple() && "No SVE containers for extended types"); 14050 14051 switch (ContentTy.getSimpleVT().SimpleTy) { 14052 default: 14053 llvm_unreachable("No known SVE container for this MVT type"); 14054 case MVT::nxv2i8: 14055 case MVT::nxv2i16: 14056 case MVT::nxv2i32: 14057 case MVT::nxv2i64: 14058 case MVT::nxv2f32: 14059 case MVT::nxv2f64: 14060 return MVT::nxv2i64; 14061 case MVT::nxv4i8: 14062 case MVT::nxv4i16: 14063 case MVT::nxv4i32: 14064 case MVT::nxv4f32: 14065 return MVT::nxv4i32; 14066 case MVT::nxv8i8: 14067 case MVT::nxv8i16: 14068 case MVT::nxv8f16: 14069 case MVT::nxv8bf16: 14070 return MVT::nxv8i16; 14071 case MVT::nxv16i8: 14072 return MVT::nxv16i8; 14073 } 14074 } 14075 14076 static SDValue performLD1Combine(SDNode *N, SelectionDAG &DAG, unsigned Opc) { 14077 SDLoc DL(N); 14078 EVT VT = N->getValueType(0); 14079 14080 if (VT.getSizeInBits().getKnownMinSize() > AArch64::SVEBitsPerBlock) 14081 return SDValue(); 14082 14083 EVT ContainerVT = VT; 14084 if (ContainerVT.isInteger()) 14085 ContainerVT = getSVEContainerType(ContainerVT); 14086 14087 SDVTList VTs = DAG.getVTList(ContainerVT, MVT::Other); 14088 SDValue Ops[] = { N->getOperand(0), // Chain 14089 N->getOperand(2), // Pg 14090 N->getOperand(3), // Base 14091 DAG.getValueType(VT) }; 14092 14093 SDValue Load = DAG.getNode(Opc, DL, VTs, Ops); 14094 SDValue LoadChain = SDValue(Load.getNode(), 1); 14095 14096 if (ContainerVT.isInteger() && (VT != ContainerVT)) 14097 Load = DAG.getNode(ISD::TRUNCATE, DL, VT, Load.getValue(0)); 14098 14099 return DAG.getMergeValues({ Load, LoadChain }, DL); 14100 } 14101 14102 static SDValue performLDNT1Combine(SDNode *N, SelectionDAG &DAG) { 14103 SDLoc DL(N); 14104 EVT VT = N->getValueType(0); 14105 EVT PtrTy = N->getOperand(3).getValueType(); 14106 14107 if (VT == MVT::nxv8bf16 && 14108 !static_cast<const AArch64Subtarget &>(DAG.getSubtarget()).hasBF16()) 14109 return SDValue(); 14110 14111 EVT LoadVT = VT; 14112 if (VT.isFloatingPoint()) 14113 LoadVT = VT.changeTypeToInteger(); 14114 14115 auto *MINode = cast<MemIntrinsicSDNode>(N); 14116 SDValue PassThru = DAG.getConstant(0, DL, LoadVT); 14117 SDValue L = DAG.getMaskedLoad(LoadVT, DL, MINode->getChain(), 14118 MINode->getOperand(3), DAG.getUNDEF(PtrTy), 14119 MINode->getOperand(2), PassThru, 14120 MINode->getMemoryVT(), MINode->getMemOperand(), 14121 ISD::UNINDEXED, ISD::NON_EXTLOAD, false); 14122 14123 if (VT.isFloatingPoint()) { 14124 SDValue Ops[] = { DAG.getNode(ISD::BITCAST, DL, VT, L), L.getValue(1) }; 14125 return DAG.getMergeValues(Ops, DL); 14126 } 14127 14128 return L; 14129 } 14130 14131 template <unsigned Opcode> 14132 static SDValue performLD1ReplicateCombine(SDNode *N, SelectionDAG &DAG) { 14133 static_assert(Opcode == AArch64ISD::LD1RQ_MERGE_ZERO || 14134 Opcode == AArch64ISD::LD1RO_MERGE_ZERO, 14135 "Unsupported opcode."); 14136 SDLoc DL(N); 14137 EVT VT = N->getValueType(0); 14138 if (VT == MVT::nxv8bf16 && 14139 !static_cast<const AArch64Subtarget &>(DAG.getSubtarget()).hasBF16()) 14140 return SDValue(); 14141 14142 EVT LoadVT = VT; 14143 if (VT.isFloatingPoint()) 14144 LoadVT = VT.changeTypeToInteger(); 14145 14146 SDValue Ops[] = {N->getOperand(0), N->getOperand(2), N->getOperand(3)}; 14147 SDValue Load = DAG.getNode(Opcode, DL, {LoadVT, MVT::Other}, Ops); 14148 SDValue LoadChain = SDValue(Load.getNode(), 1); 14149 14150 if (VT.isFloatingPoint()) 14151 Load = DAG.getNode(ISD::BITCAST, DL, VT, Load.getValue(0)); 14152 14153 return DAG.getMergeValues({Load, LoadChain}, DL); 14154 } 14155 14156 static SDValue performST1Combine(SDNode *N, SelectionDAG &DAG) { 14157 SDLoc DL(N); 14158 SDValue Data = N->getOperand(2); 14159 EVT DataVT = Data.getValueType(); 14160 EVT HwSrcVt = getSVEContainerType(DataVT); 14161 SDValue InputVT = DAG.getValueType(DataVT); 14162 14163 if (DataVT == MVT::nxv8bf16 && 14164 !static_cast<const AArch64Subtarget &>(DAG.getSubtarget()).hasBF16()) 14165 return SDValue(); 14166 14167 if (DataVT.isFloatingPoint()) 14168 InputVT = DAG.getValueType(HwSrcVt); 14169 14170 SDValue SrcNew; 14171 if (Data.getValueType().isFloatingPoint()) 14172 SrcNew = DAG.getNode(ISD::BITCAST, DL, HwSrcVt, Data); 14173 else 14174 SrcNew = DAG.getNode(ISD::ANY_EXTEND, DL, HwSrcVt, Data); 14175 14176 SDValue Ops[] = { N->getOperand(0), // Chain 14177 SrcNew, 14178 N->getOperand(4), // Base 14179 N->getOperand(3), // Pg 14180 InputVT 14181 }; 14182 14183 return DAG.getNode(AArch64ISD::ST1_PRED, DL, N->getValueType(0), Ops); 14184 } 14185 14186 static SDValue performSTNT1Combine(SDNode *N, SelectionDAG &DAG) { 14187 SDLoc DL(N); 14188 14189 SDValue Data = N->getOperand(2); 14190 EVT DataVT = Data.getValueType(); 14191 EVT PtrTy = N->getOperand(4).getValueType(); 14192 14193 if (DataVT == MVT::nxv8bf16 && 14194 !static_cast<const AArch64Subtarget &>(DAG.getSubtarget()).hasBF16()) 14195 return SDValue(); 14196 14197 if (DataVT.isFloatingPoint()) 14198 Data = DAG.getNode(ISD::BITCAST, DL, DataVT.changeTypeToInteger(), Data); 14199 14200 auto *MINode = cast<MemIntrinsicSDNode>(N); 14201 return DAG.getMaskedStore(MINode->getChain(), DL, Data, MINode->getOperand(4), 14202 DAG.getUNDEF(PtrTy), MINode->getOperand(3), 14203 MINode->getMemoryVT(), MINode->getMemOperand(), 14204 ISD::UNINDEXED, false, false); 14205 } 14206 14207 /// Replace a splat of zeros to a vector store by scalar stores of WZR/XZR. The 14208 /// load store optimizer pass will merge them to store pair stores. This should 14209 /// be better than a movi to create the vector zero followed by a vector store 14210 /// if the zero constant is not re-used, since one instructions and one register 14211 /// live range will be removed. 14212 /// 14213 /// For example, the final generated code should be: 14214 /// 14215 /// stp xzr, xzr, [x0] 14216 /// 14217 /// instead of: 14218 /// 14219 /// movi v0.2d, #0 14220 /// str q0, [x0] 14221 /// 14222 static SDValue replaceZeroVectorStore(SelectionDAG &DAG, StoreSDNode &St) { 14223 SDValue StVal = St.getValue(); 14224 EVT VT = StVal.getValueType(); 14225 14226 // Avoid scalarizing zero splat stores for scalable vectors. 14227 if (VT.isScalableVector()) 14228 return SDValue(); 14229 14230 // It is beneficial to scalarize a zero splat store for 2 or 3 i64 elements or 14231 // 2, 3 or 4 i32 elements. 14232 int NumVecElts = VT.getVectorNumElements(); 14233 if (!(((NumVecElts == 2 || NumVecElts == 3) && 14234 VT.getVectorElementType().getSizeInBits() == 64) || 14235 ((NumVecElts == 2 || NumVecElts == 3 || NumVecElts == 4) && 14236 VT.getVectorElementType().getSizeInBits() == 32))) 14237 return SDValue(); 14238 14239 if (StVal.getOpcode() != ISD::BUILD_VECTOR) 14240 return SDValue(); 14241 14242 // If the zero constant has more than one use then the vector store could be 14243 // better since the constant mov will be amortized and stp q instructions 14244 // should be able to be formed. 14245 if (!StVal.hasOneUse()) 14246 return SDValue(); 14247 14248 // If the store is truncating then it's going down to i16 or smaller, which 14249 // means it can be implemented in a single store anyway. 14250 if (St.isTruncatingStore()) 14251 return SDValue(); 14252 14253 // If the immediate offset of the address operand is too large for the stp 14254 // instruction, then bail out. 14255 if (DAG.isBaseWithConstantOffset(St.getBasePtr())) { 14256 int64_t Offset = St.getBasePtr()->getConstantOperandVal(1); 14257 if (Offset < -512 || Offset > 504) 14258 return SDValue(); 14259 } 14260 14261 for (int I = 0; I < NumVecElts; ++I) { 14262 SDValue EltVal = StVal.getOperand(I); 14263 if (!isNullConstant(EltVal) && !isNullFPConstant(EltVal)) 14264 return SDValue(); 14265 } 14266 14267 // Use a CopyFromReg WZR/XZR here to prevent 14268 // DAGCombiner::MergeConsecutiveStores from undoing this transformation. 14269 SDLoc DL(&St); 14270 unsigned ZeroReg; 14271 EVT ZeroVT; 14272 if (VT.getVectorElementType().getSizeInBits() == 32) { 14273 ZeroReg = AArch64::WZR; 14274 ZeroVT = MVT::i32; 14275 } else { 14276 ZeroReg = AArch64::XZR; 14277 ZeroVT = MVT::i64; 14278 } 14279 SDValue SplatVal = 14280 DAG.getCopyFromReg(DAG.getEntryNode(), DL, ZeroReg, ZeroVT); 14281 return splitStoreSplat(DAG, St, SplatVal, NumVecElts); 14282 } 14283 14284 /// Replace a splat of a scalar to a vector store by scalar stores of the scalar 14285 /// value. The load store optimizer pass will merge them to store pair stores. 14286 /// This has better performance than a splat of the scalar followed by a split 14287 /// vector store. Even if the stores are not merged it is four stores vs a dup, 14288 /// followed by an ext.b and two stores. 14289 static SDValue replaceSplatVectorStore(SelectionDAG &DAG, StoreSDNode &St) { 14290 SDValue StVal = St.getValue(); 14291 EVT VT = StVal.getValueType(); 14292 14293 // Don't replace floating point stores, they possibly won't be transformed to 14294 // stp because of the store pair suppress pass. 14295 if (VT.isFloatingPoint()) 14296 return SDValue(); 14297 14298 // We can express a splat as store pair(s) for 2 or 4 elements. 14299 unsigned NumVecElts = VT.getVectorNumElements(); 14300 if (NumVecElts != 4 && NumVecElts != 2) 14301 return SDValue(); 14302 14303 // If the store is truncating then it's going down to i16 or smaller, which 14304 // means it can be implemented in a single store anyway. 14305 if (St.isTruncatingStore()) 14306 return SDValue(); 14307 14308 // Check that this is a splat. 14309 // Make sure that each of the relevant vector element locations are inserted 14310 // to, i.e. 0 and 1 for v2i64 and 0, 1, 2, 3 for v4i32. 14311 std::bitset<4> IndexNotInserted((1 << NumVecElts) - 1); 14312 SDValue SplatVal; 14313 for (unsigned I = 0; I < NumVecElts; ++I) { 14314 // Check for insert vector elements. 14315 if (StVal.getOpcode() != ISD::INSERT_VECTOR_ELT) 14316 return SDValue(); 14317 14318 // Check that same value is inserted at each vector element. 14319 if (I == 0) 14320 SplatVal = StVal.getOperand(1); 14321 else if (StVal.getOperand(1) != SplatVal) 14322 return SDValue(); 14323 14324 // Check insert element index. 14325 ConstantSDNode *CIndex = dyn_cast<ConstantSDNode>(StVal.getOperand(2)); 14326 if (!CIndex) 14327 return SDValue(); 14328 uint64_t IndexVal = CIndex->getZExtValue(); 14329 if (IndexVal >= NumVecElts) 14330 return SDValue(); 14331 IndexNotInserted.reset(IndexVal); 14332 14333 StVal = StVal.getOperand(0); 14334 } 14335 // Check that all vector element locations were inserted to. 14336 if (IndexNotInserted.any()) 14337 return SDValue(); 14338 14339 return splitStoreSplat(DAG, St, SplatVal, NumVecElts); 14340 } 14341 14342 static SDValue splitStores(SDNode *N, TargetLowering::DAGCombinerInfo &DCI, 14343 SelectionDAG &DAG, 14344 const AArch64Subtarget *Subtarget) { 14345 14346 StoreSDNode *S = cast<StoreSDNode>(N); 14347 if (S->isVolatile() || S->isIndexed()) 14348 return SDValue(); 14349 14350 SDValue StVal = S->getValue(); 14351 EVT VT = StVal.getValueType(); 14352 14353 if (!VT.isFixedLengthVector()) 14354 return SDValue(); 14355 14356 // If we get a splat of zeros, convert this vector store to a store of 14357 // scalars. They will be merged into store pairs of xzr thereby removing one 14358 // instruction and one register. 14359 if (SDValue ReplacedZeroSplat = replaceZeroVectorStore(DAG, *S)) 14360 return ReplacedZeroSplat; 14361 14362 // FIXME: The logic for deciding if an unaligned store should be split should 14363 // be included in TLI.allowsMisalignedMemoryAccesses(), and there should be 14364 // a call to that function here. 14365 14366 if (!Subtarget->isMisaligned128StoreSlow()) 14367 return SDValue(); 14368 14369 // Don't split at -Oz. 14370 if (DAG.getMachineFunction().getFunction().hasMinSize()) 14371 return SDValue(); 14372 14373 // Don't split v2i64 vectors. Memcpy lowering produces those and splitting 14374 // those up regresses performance on micro-benchmarks and olden/bh. 14375 if (VT.getVectorNumElements() < 2 || VT == MVT::v2i64) 14376 return SDValue(); 14377 14378 // Split unaligned 16B stores. They are terrible for performance. 14379 // Don't split stores with alignment of 1 or 2. Code that uses clang vector 14380 // extensions can use this to mark that it does not want splitting to happen 14381 // (by underspecifying alignment to be 1 or 2). Furthermore, the chance of 14382 // eliminating alignment hazards is only 1 in 8 for alignment of 2. 14383 if (VT.getSizeInBits() != 128 || S->getAlignment() >= 16 || 14384 S->getAlignment() <= 2) 14385 return SDValue(); 14386 14387 // If we get a splat of a scalar convert this vector store to a store of 14388 // scalars. They will be merged into store pairs thereby removing two 14389 // instructions. 14390 if (SDValue ReplacedSplat = replaceSplatVectorStore(DAG, *S)) 14391 return ReplacedSplat; 14392 14393 SDLoc DL(S); 14394 14395 // Split VT into two. 14396 EVT HalfVT = VT.getHalfNumVectorElementsVT(*DAG.getContext()); 14397 unsigned NumElts = HalfVT.getVectorNumElements(); 14398 SDValue SubVector0 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, HalfVT, StVal, 14399 DAG.getConstant(0, DL, MVT::i64)); 14400 SDValue SubVector1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, HalfVT, StVal, 14401 DAG.getConstant(NumElts, DL, MVT::i64)); 14402 SDValue BasePtr = S->getBasePtr(); 14403 SDValue NewST1 = 14404 DAG.getStore(S->getChain(), DL, SubVector0, BasePtr, S->getPointerInfo(), 14405 S->getAlignment(), S->getMemOperand()->getFlags()); 14406 SDValue OffsetPtr = DAG.getNode(ISD::ADD, DL, MVT::i64, BasePtr, 14407 DAG.getConstant(8, DL, MVT::i64)); 14408 return DAG.getStore(NewST1.getValue(0), DL, SubVector1, OffsetPtr, 14409 S->getPointerInfo(), S->getAlignment(), 14410 S->getMemOperand()->getFlags()); 14411 } 14412 14413 static SDValue performUzpCombine(SDNode *N, SelectionDAG &DAG) { 14414 SDLoc DL(N); 14415 SDValue Op0 = N->getOperand(0); 14416 SDValue Op1 = N->getOperand(1); 14417 EVT ResVT = N->getValueType(0); 14418 14419 // uzp1(unpklo(uzp1(x, y)), z) => uzp1(x, z) 14420 if (Op0.getOpcode() == AArch64ISD::UUNPKLO) { 14421 if (Op0.getOperand(0).getOpcode() == AArch64ISD::UZP1) { 14422 SDValue X = Op0.getOperand(0).getOperand(0); 14423 return DAG.getNode(AArch64ISD::UZP1, DL, ResVT, X, Op1); 14424 } 14425 } 14426 14427 // uzp1(x, unpkhi(uzp1(y, z))) => uzp1(x, z) 14428 if (Op1.getOpcode() == AArch64ISD::UUNPKHI) { 14429 if (Op1.getOperand(0).getOpcode() == AArch64ISD::UZP1) { 14430 SDValue Z = Op1.getOperand(0).getOperand(1); 14431 return DAG.getNode(AArch64ISD::UZP1, DL, ResVT, Op0, Z); 14432 } 14433 } 14434 14435 return SDValue(); 14436 } 14437 14438 static SDValue performGLD1Combine(SDNode *N, SelectionDAG &DAG) { 14439 unsigned Opc = N->getOpcode(); 14440 14441 assert(((Opc >= AArch64ISD::GLD1_MERGE_ZERO && // unsigned gather loads 14442 Opc <= AArch64ISD::GLD1_IMM_MERGE_ZERO) || 14443 (Opc >= AArch64ISD::GLD1S_MERGE_ZERO && // signed gather loads 14444 Opc <= AArch64ISD::GLD1S_IMM_MERGE_ZERO)) && 14445 "Invalid opcode."); 14446 14447 const bool Scaled = Opc == AArch64ISD::GLD1_SCALED_MERGE_ZERO || 14448 Opc == AArch64ISD::GLD1S_SCALED_MERGE_ZERO; 14449 const bool Signed = Opc == AArch64ISD::GLD1S_MERGE_ZERO || 14450 Opc == AArch64ISD::GLD1S_SCALED_MERGE_ZERO; 14451 const bool Extended = Opc == AArch64ISD::GLD1_SXTW_MERGE_ZERO || 14452 Opc == AArch64ISD::GLD1_SXTW_SCALED_MERGE_ZERO || 14453 Opc == AArch64ISD::GLD1_UXTW_MERGE_ZERO || 14454 Opc == AArch64ISD::GLD1_UXTW_SCALED_MERGE_ZERO; 14455 14456 SDLoc DL(N); 14457 SDValue Chain = N->getOperand(0); 14458 SDValue Pg = N->getOperand(1); 14459 SDValue Base = N->getOperand(2); 14460 SDValue Offset = N->getOperand(3); 14461 SDValue Ty = N->getOperand(4); 14462 14463 EVT ResVT = N->getValueType(0); 14464 14465 const auto OffsetOpc = Offset.getOpcode(); 14466 const bool OffsetIsZExt = 14467 OffsetOpc == AArch64ISD::ZERO_EXTEND_INREG_MERGE_PASSTHRU; 14468 const bool OffsetIsSExt = 14469 OffsetOpc == AArch64ISD::SIGN_EXTEND_INREG_MERGE_PASSTHRU; 14470 14471 // Fold sign/zero extensions of vector offsets into GLD1 nodes where possible. 14472 if (!Extended && (OffsetIsSExt || OffsetIsZExt)) { 14473 SDValue ExtPg = Offset.getOperand(0); 14474 VTSDNode *ExtFrom = cast<VTSDNode>(Offset.getOperand(2).getNode()); 14475 EVT ExtFromEVT = ExtFrom->getVT().getVectorElementType(); 14476 14477 // If the predicate for the sign- or zero-extended offset is the 14478 // same as the predicate used for this load and the sign-/zero-extension 14479 // was from a 32-bits... 14480 if (ExtPg == Pg && ExtFromEVT == MVT::i32) { 14481 SDValue UnextendedOffset = Offset.getOperand(1); 14482 14483 unsigned NewOpc = getGatherVecOpcode(Scaled, OffsetIsSExt, true); 14484 if (Signed) 14485 NewOpc = getSignExtendedGatherOpcode(NewOpc); 14486 14487 return DAG.getNode(NewOpc, DL, {ResVT, MVT::Other}, 14488 {Chain, Pg, Base, UnextendedOffset, Ty}); 14489 } 14490 } 14491 14492 return SDValue(); 14493 } 14494 14495 /// Target-specific DAG combine function for post-increment LD1 (lane) and 14496 /// post-increment LD1R. 14497 static SDValue performPostLD1Combine(SDNode *N, 14498 TargetLowering::DAGCombinerInfo &DCI, 14499 bool IsLaneOp) { 14500 if (DCI.isBeforeLegalizeOps()) 14501 return SDValue(); 14502 14503 SelectionDAG &DAG = DCI.DAG; 14504 EVT VT = N->getValueType(0); 14505 14506 if (VT.isScalableVector()) 14507 return SDValue(); 14508 14509 unsigned LoadIdx = IsLaneOp ? 1 : 0; 14510 SDNode *LD = N->getOperand(LoadIdx).getNode(); 14511 // If it is not LOAD, can not do such combine. 14512 if (LD->getOpcode() != ISD::LOAD) 14513 return SDValue(); 14514 14515 // The vector lane must be a constant in the LD1LANE opcode. 14516 SDValue Lane; 14517 if (IsLaneOp) { 14518 Lane = N->getOperand(2); 14519 auto *LaneC = dyn_cast<ConstantSDNode>(Lane); 14520 if (!LaneC || LaneC->getZExtValue() >= VT.getVectorNumElements()) 14521 return SDValue(); 14522 } 14523 14524 LoadSDNode *LoadSDN = cast<LoadSDNode>(LD); 14525 EVT MemVT = LoadSDN->getMemoryVT(); 14526 // Check if memory operand is the same type as the vector element. 14527 if (MemVT != VT.getVectorElementType()) 14528 return SDValue(); 14529 14530 // Check if there are other uses. If so, do not combine as it will introduce 14531 // an extra load. 14532 for (SDNode::use_iterator UI = LD->use_begin(), UE = LD->use_end(); UI != UE; 14533 ++UI) { 14534 if (UI.getUse().getResNo() == 1) // Ignore uses of the chain result. 14535 continue; 14536 if (*UI != N) 14537 return SDValue(); 14538 } 14539 14540 SDValue Addr = LD->getOperand(1); 14541 SDValue Vector = N->getOperand(0); 14542 // Search for a use of the address operand that is an increment. 14543 for (SDNode::use_iterator UI = Addr.getNode()->use_begin(), UE = 14544 Addr.getNode()->use_end(); UI != UE; ++UI) { 14545 SDNode *User = *UI; 14546 if (User->getOpcode() != ISD::ADD 14547 || UI.getUse().getResNo() != Addr.getResNo()) 14548 continue; 14549 14550 // If the increment is a constant, it must match the memory ref size. 14551 SDValue Inc = User->getOperand(User->getOperand(0) == Addr ? 1 : 0); 14552 if (ConstantSDNode *CInc = dyn_cast<ConstantSDNode>(Inc.getNode())) { 14553 uint32_t IncVal = CInc->getZExtValue(); 14554 unsigned NumBytes = VT.getScalarSizeInBits() / 8; 14555 if (IncVal != NumBytes) 14556 continue; 14557 Inc = DAG.getRegister(AArch64::XZR, MVT::i64); 14558 } 14559 14560 // To avoid cycle construction make sure that neither the load nor the add 14561 // are predecessors to each other or the Vector. 14562 SmallPtrSet<const SDNode *, 32> Visited; 14563 SmallVector<const SDNode *, 16> Worklist; 14564 Visited.insert(Addr.getNode()); 14565 Worklist.push_back(User); 14566 Worklist.push_back(LD); 14567 Worklist.push_back(Vector.getNode()); 14568 if (SDNode::hasPredecessorHelper(LD, Visited, Worklist) || 14569 SDNode::hasPredecessorHelper(User, Visited, Worklist)) 14570 continue; 14571 14572 SmallVector<SDValue, 8> Ops; 14573 Ops.push_back(LD->getOperand(0)); // Chain 14574 if (IsLaneOp) { 14575 Ops.push_back(Vector); // The vector to be inserted 14576 Ops.push_back(Lane); // The lane to be inserted in the vector 14577 } 14578 Ops.push_back(Addr); 14579 Ops.push_back(Inc); 14580 14581 EVT Tys[3] = { VT, MVT::i64, MVT::Other }; 14582 SDVTList SDTys = DAG.getVTList(Tys); 14583 unsigned NewOp = IsLaneOp ? AArch64ISD::LD1LANEpost : AArch64ISD::LD1DUPpost; 14584 SDValue UpdN = DAG.getMemIntrinsicNode(NewOp, SDLoc(N), SDTys, Ops, 14585 MemVT, 14586 LoadSDN->getMemOperand()); 14587 14588 // Update the uses. 14589 SDValue NewResults[] = { 14590 SDValue(LD, 0), // The result of load 14591 SDValue(UpdN.getNode(), 2) // Chain 14592 }; 14593 DCI.CombineTo(LD, NewResults); 14594 DCI.CombineTo(N, SDValue(UpdN.getNode(), 0)); // Dup/Inserted Result 14595 DCI.CombineTo(User, SDValue(UpdN.getNode(), 1)); // Write back register 14596 14597 break; 14598 } 14599 return SDValue(); 14600 } 14601 14602 /// Simplify ``Addr`` given that the top byte of it is ignored by HW during 14603 /// address translation. 14604 static bool performTBISimplification(SDValue Addr, 14605 TargetLowering::DAGCombinerInfo &DCI, 14606 SelectionDAG &DAG) { 14607 APInt DemandedMask = APInt::getLowBitsSet(64, 56); 14608 KnownBits Known; 14609 TargetLowering::TargetLoweringOpt TLO(DAG, !DCI.isBeforeLegalize(), 14610 !DCI.isBeforeLegalizeOps()); 14611 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 14612 if (TLI.SimplifyDemandedBits(Addr, DemandedMask, Known, TLO)) { 14613 DCI.CommitTargetLoweringOpt(TLO); 14614 return true; 14615 } 14616 return false; 14617 } 14618 14619 static SDValue performSTORECombine(SDNode *N, 14620 TargetLowering::DAGCombinerInfo &DCI, 14621 SelectionDAG &DAG, 14622 const AArch64Subtarget *Subtarget) { 14623 if (SDValue Split = splitStores(N, DCI, DAG, Subtarget)) 14624 return Split; 14625 14626 if (Subtarget->supportsAddressTopByteIgnored() && 14627 performTBISimplification(N->getOperand(2), DCI, DAG)) 14628 return SDValue(N, 0); 14629 14630 return SDValue(); 14631 } 14632 14633 /// Target-specific DAG combine function for NEON load/store intrinsics 14634 /// to merge base address updates. 14635 static SDValue performNEONPostLDSTCombine(SDNode *N, 14636 TargetLowering::DAGCombinerInfo &DCI, 14637 SelectionDAG &DAG) { 14638 if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer()) 14639 return SDValue(); 14640 14641 unsigned AddrOpIdx = N->getNumOperands() - 1; 14642 SDValue Addr = N->getOperand(AddrOpIdx); 14643 14644 // Search for a use of the address operand that is an increment. 14645 for (SDNode::use_iterator UI = Addr.getNode()->use_begin(), 14646 UE = Addr.getNode()->use_end(); UI != UE; ++UI) { 14647 SDNode *User = *UI; 14648 if (User->getOpcode() != ISD::ADD || 14649 UI.getUse().getResNo() != Addr.getResNo()) 14650 continue; 14651 14652 // Check that the add is independent of the load/store. Otherwise, folding 14653 // it would create a cycle. 14654 SmallPtrSet<const SDNode *, 32> Visited; 14655 SmallVector<const SDNode *, 16> Worklist; 14656 Visited.insert(Addr.getNode()); 14657 Worklist.push_back(N); 14658 Worklist.push_back(User); 14659 if (SDNode::hasPredecessorHelper(N, Visited, Worklist) || 14660 SDNode::hasPredecessorHelper(User, Visited, Worklist)) 14661 continue; 14662 14663 // Find the new opcode for the updating load/store. 14664 bool IsStore = false; 14665 bool IsLaneOp = false; 14666 bool IsDupOp = false; 14667 unsigned NewOpc = 0; 14668 unsigned NumVecs = 0; 14669 unsigned IntNo = cast<ConstantSDNode>(N->getOperand(1))->getZExtValue(); 14670 switch (IntNo) { 14671 default: llvm_unreachable("unexpected intrinsic for Neon base update"); 14672 case Intrinsic::aarch64_neon_ld2: NewOpc = AArch64ISD::LD2post; 14673 NumVecs = 2; break; 14674 case Intrinsic::aarch64_neon_ld3: NewOpc = AArch64ISD::LD3post; 14675 NumVecs = 3; break; 14676 case Intrinsic::aarch64_neon_ld4: NewOpc = AArch64ISD::LD4post; 14677 NumVecs = 4; break; 14678 case Intrinsic::aarch64_neon_st2: NewOpc = AArch64ISD::ST2post; 14679 NumVecs = 2; IsStore = true; break; 14680 case Intrinsic::aarch64_neon_st3: NewOpc = AArch64ISD::ST3post; 14681 NumVecs = 3; IsStore = true; break; 14682 case Intrinsic::aarch64_neon_st4: NewOpc = AArch64ISD::ST4post; 14683 NumVecs = 4; IsStore = true; break; 14684 case Intrinsic::aarch64_neon_ld1x2: NewOpc = AArch64ISD::LD1x2post; 14685 NumVecs = 2; break; 14686 case Intrinsic::aarch64_neon_ld1x3: NewOpc = AArch64ISD::LD1x3post; 14687 NumVecs = 3; break; 14688 case Intrinsic::aarch64_neon_ld1x4: NewOpc = AArch64ISD::LD1x4post; 14689 NumVecs = 4; break; 14690 case Intrinsic::aarch64_neon_st1x2: NewOpc = AArch64ISD::ST1x2post; 14691 NumVecs = 2; IsStore = true; break; 14692 case Intrinsic::aarch64_neon_st1x3: NewOpc = AArch64ISD::ST1x3post; 14693 NumVecs = 3; IsStore = true; break; 14694 case Intrinsic::aarch64_neon_st1x4: NewOpc = AArch64ISD::ST1x4post; 14695 NumVecs = 4; IsStore = true; break; 14696 case Intrinsic::aarch64_neon_ld2r: NewOpc = AArch64ISD::LD2DUPpost; 14697 NumVecs = 2; IsDupOp = true; break; 14698 case Intrinsic::aarch64_neon_ld3r: NewOpc = AArch64ISD::LD3DUPpost; 14699 NumVecs = 3; IsDupOp = true; break; 14700 case Intrinsic::aarch64_neon_ld4r: NewOpc = AArch64ISD::LD4DUPpost; 14701 NumVecs = 4; IsDupOp = true; break; 14702 case Intrinsic::aarch64_neon_ld2lane: NewOpc = AArch64ISD::LD2LANEpost; 14703 NumVecs = 2; IsLaneOp = true; break; 14704 case Intrinsic::aarch64_neon_ld3lane: NewOpc = AArch64ISD::LD3LANEpost; 14705 NumVecs = 3; IsLaneOp = true; break; 14706 case Intrinsic::aarch64_neon_ld4lane: NewOpc = AArch64ISD::LD4LANEpost; 14707 NumVecs = 4; IsLaneOp = true; break; 14708 case Intrinsic::aarch64_neon_st2lane: NewOpc = AArch64ISD::ST2LANEpost; 14709 NumVecs = 2; IsStore = true; IsLaneOp = true; break; 14710 case Intrinsic::aarch64_neon_st3lane: NewOpc = AArch64ISD::ST3LANEpost; 14711 NumVecs = 3; IsStore = true; IsLaneOp = true; break; 14712 case Intrinsic::aarch64_neon_st4lane: NewOpc = AArch64ISD::ST4LANEpost; 14713 NumVecs = 4; IsStore = true; IsLaneOp = true; break; 14714 } 14715 14716 EVT VecTy; 14717 if (IsStore) 14718 VecTy = N->getOperand(2).getValueType(); 14719 else 14720 VecTy = N->getValueType(0); 14721 14722 // If the increment is a constant, it must match the memory ref size. 14723 SDValue Inc = User->getOperand(User->getOperand(0) == Addr ? 1 : 0); 14724 if (ConstantSDNode *CInc = dyn_cast<ConstantSDNode>(Inc.getNode())) { 14725 uint32_t IncVal = CInc->getZExtValue(); 14726 unsigned NumBytes = NumVecs * VecTy.getSizeInBits() / 8; 14727 if (IsLaneOp || IsDupOp) 14728 NumBytes /= VecTy.getVectorNumElements(); 14729 if (IncVal != NumBytes) 14730 continue; 14731 Inc = DAG.getRegister(AArch64::XZR, MVT::i64); 14732 } 14733 SmallVector<SDValue, 8> Ops; 14734 Ops.push_back(N->getOperand(0)); // Incoming chain 14735 // Load lane and store have vector list as input. 14736 if (IsLaneOp || IsStore) 14737 for (unsigned i = 2; i < AddrOpIdx; ++i) 14738 Ops.push_back(N->getOperand(i)); 14739 Ops.push_back(Addr); // Base register 14740 Ops.push_back(Inc); 14741 14742 // Return Types. 14743 EVT Tys[6]; 14744 unsigned NumResultVecs = (IsStore ? 0 : NumVecs); 14745 unsigned n; 14746 for (n = 0; n < NumResultVecs; ++n) 14747 Tys[n] = VecTy; 14748 Tys[n++] = MVT::i64; // Type of write back register 14749 Tys[n] = MVT::Other; // Type of the chain 14750 SDVTList SDTys = DAG.getVTList(makeArrayRef(Tys, NumResultVecs + 2)); 14751 14752 MemIntrinsicSDNode *MemInt = cast<MemIntrinsicSDNode>(N); 14753 SDValue UpdN = DAG.getMemIntrinsicNode(NewOpc, SDLoc(N), SDTys, Ops, 14754 MemInt->getMemoryVT(), 14755 MemInt->getMemOperand()); 14756 14757 // Update the uses. 14758 std::vector<SDValue> NewResults; 14759 for (unsigned i = 0; i < NumResultVecs; ++i) { 14760 NewResults.push_back(SDValue(UpdN.getNode(), i)); 14761 } 14762 NewResults.push_back(SDValue(UpdN.getNode(), NumResultVecs + 1)); 14763 DCI.CombineTo(N, NewResults); 14764 DCI.CombineTo(User, SDValue(UpdN.getNode(), NumResultVecs)); 14765 14766 break; 14767 } 14768 return SDValue(); 14769 } 14770 14771 // Checks to see if the value is the prescribed width and returns information 14772 // about its extension mode. 14773 static 14774 bool checkValueWidth(SDValue V, unsigned width, ISD::LoadExtType &ExtType) { 14775 ExtType = ISD::NON_EXTLOAD; 14776 switch(V.getNode()->getOpcode()) { 14777 default: 14778 return false; 14779 case ISD::LOAD: { 14780 LoadSDNode *LoadNode = cast<LoadSDNode>(V.getNode()); 14781 if ((LoadNode->getMemoryVT() == MVT::i8 && width == 8) 14782 || (LoadNode->getMemoryVT() == MVT::i16 && width == 16)) { 14783 ExtType = LoadNode->getExtensionType(); 14784 return true; 14785 } 14786 return false; 14787 } 14788 case ISD::AssertSext: { 14789 VTSDNode *TypeNode = cast<VTSDNode>(V.getNode()->getOperand(1)); 14790 if ((TypeNode->getVT() == MVT::i8 && width == 8) 14791 || (TypeNode->getVT() == MVT::i16 && width == 16)) { 14792 ExtType = ISD::SEXTLOAD; 14793 return true; 14794 } 14795 return false; 14796 } 14797 case ISD::AssertZext: { 14798 VTSDNode *TypeNode = cast<VTSDNode>(V.getNode()->getOperand(1)); 14799 if ((TypeNode->getVT() == MVT::i8 && width == 8) 14800 || (TypeNode->getVT() == MVT::i16 && width == 16)) { 14801 ExtType = ISD::ZEXTLOAD; 14802 return true; 14803 } 14804 return false; 14805 } 14806 case ISD::Constant: 14807 case ISD::TargetConstant: { 14808 return std::abs(cast<ConstantSDNode>(V.getNode())->getSExtValue()) < 14809 1LL << (width - 1); 14810 } 14811 } 14812 14813 return true; 14814 } 14815 14816 // This function does a whole lot of voodoo to determine if the tests are 14817 // equivalent without and with a mask. Essentially what happens is that given a 14818 // DAG resembling: 14819 // 14820 // +-------------+ +-------------+ +-------------+ +-------------+ 14821 // | Input | | AddConstant | | CompConstant| | CC | 14822 // +-------------+ +-------------+ +-------------+ +-------------+ 14823 // | | | | 14824 // V V | +----------+ 14825 // +-------------+ +----+ | | 14826 // | ADD | |0xff| | | 14827 // +-------------+ +----+ | | 14828 // | | | | 14829 // V V | | 14830 // +-------------+ | | 14831 // | AND | | | 14832 // +-------------+ | | 14833 // | | | 14834 // +-----+ | | 14835 // | | | 14836 // V V V 14837 // +-------------+ 14838 // | CMP | 14839 // +-------------+ 14840 // 14841 // The AND node may be safely removed for some combinations of inputs. In 14842 // particular we need to take into account the extension type of the Input, 14843 // the exact values of AddConstant, CompConstant, and CC, along with the nominal 14844 // width of the input (this can work for any width inputs, the above graph is 14845 // specific to 8 bits. 14846 // 14847 // The specific equations were worked out by generating output tables for each 14848 // AArch64CC value in terms of and AddConstant (w1), CompConstant(w2). The 14849 // problem was simplified by working with 4 bit inputs, which means we only 14850 // needed to reason about 24 distinct bit patterns: 8 patterns unique to zero 14851 // extension (8,15), 8 patterns unique to sign extensions (-8,-1), and 8 14852 // patterns present in both extensions (0,7). For every distinct set of 14853 // AddConstant and CompConstants bit patterns we can consider the masked and 14854 // unmasked versions to be equivalent if the result of this function is true for 14855 // all 16 distinct bit patterns of for the current extension type of Input (w0). 14856 // 14857 // sub w8, w0, w1 14858 // and w10, w8, #0x0f 14859 // cmp w8, w2 14860 // cset w9, AArch64CC 14861 // cmp w10, w2 14862 // cset w11, AArch64CC 14863 // cmp w9, w11 14864 // cset w0, eq 14865 // ret 14866 // 14867 // Since the above function shows when the outputs are equivalent it defines 14868 // when it is safe to remove the AND. Unfortunately it only runs on AArch64 and 14869 // would be expensive to run during compiles. The equations below were written 14870 // in a test harness that confirmed they gave equivalent outputs to the above 14871 // for all inputs function, so they can be used determine if the removal is 14872 // legal instead. 14873 // 14874 // isEquivalentMaskless() is the code for testing if the AND can be removed 14875 // factored out of the DAG recognition as the DAG can take several forms. 14876 14877 static bool isEquivalentMaskless(unsigned CC, unsigned width, 14878 ISD::LoadExtType ExtType, int AddConstant, 14879 int CompConstant) { 14880 // By being careful about our equations and only writing the in term 14881 // symbolic values and well known constants (0, 1, -1, MaxUInt) we can 14882 // make them generally applicable to all bit widths. 14883 int MaxUInt = (1 << width); 14884 14885 // For the purposes of these comparisons sign extending the type is 14886 // equivalent to zero extending the add and displacing it by half the integer 14887 // width. Provided we are careful and make sure our equations are valid over 14888 // the whole range we can just adjust the input and avoid writing equations 14889 // for sign extended inputs. 14890 if (ExtType == ISD::SEXTLOAD) 14891 AddConstant -= (1 << (width-1)); 14892 14893 switch(CC) { 14894 case AArch64CC::LE: 14895 case AArch64CC::GT: 14896 if ((AddConstant == 0) || 14897 (CompConstant == MaxUInt - 1 && AddConstant < 0) || 14898 (AddConstant >= 0 && CompConstant < 0) || 14899 (AddConstant <= 0 && CompConstant <= 0 && CompConstant < AddConstant)) 14900 return true; 14901 break; 14902 case AArch64CC::LT: 14903 case AArch64CC::GE: 14904 if ((AddConstant == 0) || 14905 (AddConstant >= 0 && CompConstant <= 0) || 14906 (AddConstant <= 0 && CompConstant <= 0 && CompConstant <= AddConstant)) 14907 return true; 14908 break; 14909 case AArch64CC::HI: 14910 case AArch64CC::LS: 14911 if ((AddConstant >= 0 && CompConstant < 0) || 14912 (AddConstant <= 0 && CompConstant >= -1 && 14913 CompConstant < AddConstant + MaxUInt)) 14914 return true; 14915 break; 14916 case AArch64CC::PL: 14917 case AArch64CC::MI: 14918 if ((AddConstant == 0) || 14919 (AddConstant > 0 && CompConstant <= 0) || 14920 (AddConstant < 0 && CompConstant <= AddConstant)) 14921 return true; 14922 break; 14923 case AArch64CC::LO: 14924 case AArch64CC::HS: 14925 if ((AddConstant >= 0 && CompConstant <= 0) || 14926 (AddConstant <= 0 && CompConstant >= 0 && 14927 CompConstant <= AddConstant + MaxUInt)) 14928 return true; 14929 break; 14930 case AArch64CC::EQ: 14931 case AArch64CC::NE: 14932 if ((AddConstant > 0 && CompConstant < 0) || 14933 (AddConstant < 0 && CompConstant >= 0 && 14934 CompConstant < AddConstant + MaxUInt) || 14935 (AddConstant >= 0 && CompConstant >= 0 && 14936 CompConstant >= AddConstant) || 14937 (AddConstant <= 0 && CompConstant < 0 && CompConstant < AddConstant)) 14938 return true; 14939 break; 14940 case AArch64CC::VS: 14941 case AArch64CC::VC: 14942 case AArch64CC::AL: 14943 case AArch64CC::NV: 14944 return true; 14945 case AArch64CC::Invalid: 14946 break; 14947 } 14948 14949 return false; 14950 } 14951 14952 static 14953 SDValue performCONDCombine(SDNode *N, 14954 TargetLowering::DAGCombinerInfo &DCI, 14955 SelectionDAG &DAG, unsigned CCIndex, 14956 unsigned CmpIndex) { 14957 unsigned CC = cast<ConstantSDNode>(N->getOperand(CCIndex))->getSExtValue(); 14958 SDNode *SubsNode = N->getOperand(CmpIndex).getNode(); 14959 unsigned CondOpcode = SubsNode->getOpcode(); 14960 14961 if (CondOpcode != AArch64ISD::SUBS) 14962 return SDValue(); 14963 14964 // There is a SUBS feeding this condition. Is it fed by a mask we can 14965 // use? 14966 14967 SDNode *AndNode = SubsNode->getOperand(0).getNode(); 14968 unsigned MaskBits = 0; 14969 14970 if (AndNode->getOpcode() != ISD::AND) 14971 return SDValue(); 14972 14973 if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(AndNode->getOperand(1))) { 14974 uint32_t CNV = CN->getZExtValue(); 14975 if (CNV == 255) 14976 MaskBits = 8; 14977 else if (CNV == 65535) 14978 MaskBits = 16; 14979 } 14980 14981 if (!MaskBits) 14982 return SDValue(); 14983 14984 SDValue AddValue = AndNode->getOperand(0); 14985 14986 if (AddValue.getOpcode() != ISD::ADD) 14987 return SDValue(); 14988 14989 // The basic dag structure is correct, grab the inputs and validate them. 14990 14991 SDValue AddInputValue1 = AddValue.getNode()->getOperand(0); 14992 SDValue AddInputValue2 = AddValue.getNode()->getOperand(1); 14993 SDValue SubsInputValue = SubsNode->getOperand(1); 14994 14995 // The mask is present and the provenance of all the values is a smaller type, 14996 // lets see if the mask is superfluous. 14997 14998 if (!isa<ConstantSDNode>(AddInputValue2.getNode()) || 14999 !isa<ConstantSDNode>(SubsInputValue.getNode())) 15000 return SDValue(); 15001 15002 ISD::LoadExtType ExtType; 15003 15004 if (!checkValueWidth(SubsInputValue, MaskBits, ExtType) || 15005 !checkValueWidth(AddInputValue2, MaskBits, ExtType) || 15006 !checkValueWidth(AddInputValue1, MaskBits, ExtType) ) 15007 return SDValue(); 15008 15009 if(!isEquivalentMaskless(CC, MaskBits, ExtType, 15010 cast<ConstantSDNode>(AddInputValue2.getNode())->getSExtValue(), 15011 cast<ConstantSDNode>(SubsInputValue.getNode())->getSExtValue())) 15012 return SDValue(); 15013 15014 // The AND is not necessary, remove it. 15015 15016 SDVTList VTs = DAG.getVTList(SubsNode->getValueType(0), 15017 SubsNode->getValueType(1)); 15018 SDValue Ops[] = { AddValue, SubsNode->getOperand(1) }; 15019 15020 SDValue NewValue = DAG.getNode(CondOpcode, SDLoc(SubsNode), VTs, Ops); 15021 DAG.ReplaceAllUsesWith(SubsNode, NewValue.getNode()); 15022 15023 return SDValue(N, 0); 15024 } 15025 15026 // Optimize compare with zero and branch. 15027 static SDValue performBRCONDCombine(SDNode *N, 15028 TargetLowering::DAGCombinerInfo &DCI, 15029 SelectionDAG &DAG) { 15030 MachineFunction &MF = DAG.getMachineFunction(); 15031 // Speculation tracking/SLH assumes that optimized TB(N)Z/CB(N)Z instructions 15032 // will not be produced, as they are conditional branch instructions that do 15033 // not set flags. 15034 if (MF.getFunction().hasFnAttribute(Attribute::SpeculativeLoadHardening)) 15035 return SDValue(); 15036 15037 if (SDValue NV = performCONDCombine(N, DCI, DAG, 2, 3)) 15038 N = NV.getNode(); 15039 SDValue Chain = N->getOperand(0); 15040 SDValue Dest = N->getOperand(1); 15041 SDValue CCVal = N->getOperand(2); 15042 SDValue Cmp = N->getOperand(3); 15043 15044 assert(isa<ConstantSDNode>(CCVal) && "Expected a ConstantSDNode here!"); 15045 unsigned CC = cast<ConstantSDNode>(CCVal)->getZExtValue(); 15046 if (CC != AArch64CC::EQ && CC != AArch64CC::NE) 15047 return SDValue(); 15048 15049 unsigned CmpOpc = Cmp.getOpcode(); 15050 if (CmpOpc != AArch64ISD::ADDS && CmpOpc != AArch64ISD::SUBS) 15051 return SDValue(); 15052 15053 // Only attempt folding if there is only one use of the flag and no use of the 15054 // value. 15055 if (!Cmp->hasNUsesOfValue(0, 0) || !Cmp->hasNUsesOfValue(1, 1)) 15056 return SDValue(); 15057 15058 SDValue LHS = Cmp.getOperand(0); 15059 SDValue RHS = Cmp.getOperand(1); 15060 15061 assert(LHS.getValueType() == RHS.getValueType() && 15062 "Expected the value type to be the same for both operands!"); 15063 if (LHS.getValueType() != MVT::i32 && LHS.getValueType() != MVT::i64) 15064 return SDValue(); 15065 15066 if (isNullConstant(LHS)) 15067 std::swap(LHS, RHS); 15068 15069 if (!isNullConstant(RHS)) 15070 return SDValue(); 15071 15072 if (LHS.getOpcode() == ISD::SHL || LHS.getOpcode() == ISD::SRA || 15073 LHS.getOpcode() == ISD::SRL) 15074 return SDValue(); 15075 15076 // Fold the compare into the branch instruction. 15077 SDValue BR; 15078 if (CC == AArch64CC::EQ) 15079 BR = DAG.getNode(AArch64ISD::CBZ, SDLoc(N), MVT::Other, Chain, LHS, Dest); 15080 else 15081 BR = DAG.getNode(AArch64ISD::CBNZ, SDLoc(N), MVT::Other, Chain, LHS, Dest); 15082 15083 // Do not add new nodes to DAG combiner worklist. 15084 DCI.CombineTo(N, BR, false); 15085 15086 return SDValue(); 15087 } 15088 15089 // Optimize some simple tbz/tbnz cases. Returns the new operand and bit to test 15090 // as well as whether the test should be inverted. This code is required to 15091 // catch these cases (as opposed to standard dag combines) because 15092 // AArch64ISD::TBZ is matched during legalization. 15093 static SDValue getTestBitOperand(SDValue Op, unsigned &Bit, bool &Invert, 15094 SelectionDAG &DAG) { 15095 15096 if (!Op->hasOneUse()) 15097 return Op; 15098 15099 // We don't handle undef/constant-fold cases below, as they should have 15100 // already been taken care of (e.g. and of 0, test of undefined shifted bits, 15101 // etc.) 15102 15103 // (tbz (trunc x), b) -> (tbz x, b) 15104 // This case is just here to enable more of the below cases to be caught. 15105 if (Op->getOpcode() == ISD::TRUNCATE && 15106 Bit < Op->getValueType(0).getSizeInBits()) { 15107 return getTestBitOperand(Op->getOperand(0), Bit, Invert, DAG); 15108 } 15109 15110 // (tbz (any_ext x), b) -> (tbz x, b) if we don't use the extended bits. 15111 if (Op->getOpcode() == ISD::ANY_EXTEND && 15112 Bit < Op->getOperand(0).getValueSizeInBits()) { 15113 return getTestBitOperand(Op->getOperand(0), Bit, Invert, DAG); 15114 } 15115 15116 if (Op->getNumOperands() != 2) 15117 return Op; 15118 15119 auto *C = dyn_cast<ConstantSDNode>(Op->getOperand(1)); 15120 if (!C) 15121 return Op; 15122 15123 switch (Op->getOpcode()) { 15124 default: 15125 return Op; 15126 15127 // (tbz (and x, m), b) -> (tbz x, b) 15128 case ISD::AND: 15129 if ((C->getZExtValue() >> Bit) & 1) 15130 return getTestBitOperand(Op->getOperand(0), Bit, Invert, DAG); 15131 return Op; 15132 15133 // (tbz (shl x, c), b) -> (tbz x, b-c) 15134 case ISD::SHL: 15135 if (C->getZExtValue() <= Bit && 15136 (Bit - C->getZExtValue()) < Op->getValueType(0).getSizeInBits()) { 15137 Bit = Bit - C->getZExtValue(); 15138 return getTestBitOperand(Op->getOperand(0), Bit, Invert, DAG); 15139 } 15140 return Op; 15141 15142 // (tbz (sra x, c), b) -> (tbz x, b+c) or (tbz x, msb) if b+c is > # bits in x 15143 case ISD::SRA: 15144 Bit = Bit + C->getZExtValue(); 15145 if (Bit >= Op->getValueType(0).getSizeInBits()) 15146 Bit = Op->getValueType(0).getSizeInBits() - 1; 15147 return getTestBitOperand(Op->getOperand(0), Bit, Invert, DAG); 15148 15149 // (tbz (srl x, c), b) -> (tbz x, b+c) 15150 case ISD::SRL: 15151 if ((Bit + C->getZExtValue()) < Op->getValueType(0).getSizeInBits()) { 15152 Bit = Bit + C->getZExtValue(); 15153 return getTestBitOperand(Op->getOperand(0), Bit, Invert, DAG); 15154 } 15155 return Op; 15156 15157 // (tbz (xor x, -1), b) -> (tbnz x, b) 15158 case ISD::XOR: 15159 if ((C->getZExtValue() >> Bit) & 1) 15160 Invert = !Invert; 15161 return getTestBitOperand(Op->getOperand(0), Bit, Invert, DAG); 15162 } 15163 } 15164 15165 // Optimize test single bit zero/non-zero and branch. 15166 static SDValue performTBZCombine(SDNode *N, 15167 TargetLowering::DAGCombinerInfo &DCI, 15168 SelectionDAG &DAG) { 15169 unsigned Bit = cast<ConstantSDNode>(N->getOperand(2))->getZExtValue(); 15170 bool Invert = false; 15171 SDValue TestSrc = N->getOperand(1); 15172 SDValue NewTestSrc = getTestBitOperand(TestSrc, Bit, Invert, DAG); 15173 15174 if (TestSrc == NewTestSrc) 15175 return SDValue(); 15176 15177 unsigned NewOpc = N->getOpcode(); 15178 if (Invert) { 15179 if (NewOpc == AArch64ISD::TBZ) 15180 NewOpc = AArch64ISD::TBNZ; 15181 else { 15182 assert(NewOpc == AArch64ISD::TBNZ); 15183 NewOpc = AArch64ISD::TBZ; 15184 } 15185 } 15186 15187 SDLoc DL(N); 15188 return DAG.getNode(NewOpc, DL, MVT::Other, N->getOperand(0), NewTestSrc, 15189 DAG.getConstant(Bit, DL, MVT::i64), N->getOperand(3)); 15190 } 15191 15192 // vselect (v1i1 setcc) -> 15193 // vselect (v1iXX setcc) (XX is the size of the compared operand type) 15194 // FIXME: Currently the type legalizer can't handle VSELECT having v1i1 as 15195 // condition. If it can legalize "VSELECT v1i1" correctly, no need to combine 15196 // such VSELECT. 15197 static SDValue performVSelectCombine(SDNode *N, SelectionDAG &DAG) { 15198 SDValue N0 = N->getOperand(0); 15199 EVT CCVT = N0.getValueType(); 15200 15201 // Check for sign pattern (VSELECT setgt, iN lhs, -1, 1, -1) and transform 15202 // into (OR (ASR lhs, N-1), 1), which requires less instructions for the 15203 // supported types. 15204 SDValue SetCC = N->getOperand(0); 15205 if (SetCC.getOpcode() == ISD::SETCC && 15206 SetCC.getOperand(2) == DAG.getCondCode(ISD::SETGT)) { 15207 SDValue CmpLHS = SetCC.getOperand(0); 15208 EVT VT = CmpLHS.getValueType(); 15209 SDNode *CmpRHS = SetCC.getOperand(1).getNode(); 15210 SDNode *SplatLHS = N->getOperand(1).getNode(); 15211 SDNode *SplatRHS = N->getOperand(2).getNode(); 15212 APInt SplatLHSVal; 15213 if (CmpLHS.getValueType() == N->getOperand(1).getValueType() && 15214 VT.isSimple() && 15215 is_contained( 15216 makeArrayRef({MVT::v8i8, MVT::v16i8, MVT::v4i16, MVT::v8i16, 15217 MVT::v2i32, MVT::v4i32, MVT::v2i64}), 15218 VT.getSimpleVT().SimpleTy) && 15219 ISD::isConstantSplatVector(SplatLHS, SplatLHSVal) && 15220 SplatLHSVal.isOneValue() && ISD::isConstantSplatVectorAllOnes(CmpRHS) && 15221 ISD::isConstantSplatVectorAllOnes(SplatRHS)) { 15222 unsigned NumElts = VT.getVectorNumElements(); 15223 SmallVector<SDValue, 8> Ops( 15224 NumElts, DAG.getConstant(VT.getScalarSizeInBits() - 1, SDLoc(N), 15225 VT.getScalarType())); 15226 SDValue Val = DAG.getBuildVector(VT, SDLoc(N), Ops); 15227 15228 auto Shift = DAG.getNode(ISD::SRA, SDLoc(N), VT, CmpLHS, Val); 15229 auto Or = DAG.getNode(ISD::OR, SDLoc(N), VT, Shift, N->getOperand(1)); 15230 return Or; 15231 } 15232 } 15233 15234 if (N0.getOpcode() != ISD::SETCC || 15235 CCVT.getVectorElementCount() != ElementCount::getFixed(1) || 15236 CCVT.getVectorElementType() != MVT::i1) 15237 return SDValue(); 15238 15239 EVT ResVT = N->getValueType(0); 15240 EVT CmpVT = N0.getOperand(0).getValueType(); 15241 // Only combine when the result type is of the same size as the compared 15242 // operands. 15243 if (ResVT.getSizeInBits() != CmpVT.getSizeInBits()) 15244 return SDValue(); 15245 15246 SDValue IfTrue = N->getOperand(1); 15247 SDValue IfFalse = N->getOperand(2); 15248 SetCC = DAG.getSetCC(SDLoc(N), CmpVT.changeVectorElementTypeToInteger(), 15249 N0.getOperand(0), N0.getOperand(1), 15250 cast<CondCodeSDNode>(N0.getOperand(2))->get()); 15251 return DAG.getNode(ISD::VSELECT, SDLoc(N), ResVT, SetCC, 15252 IfTrue, IfFalse); 15253 } 15254 15255 /// A vector select: "(select vL, vR, (setcc LHS, RHS))" is best performed with 15256 /// the compare-mask instructions rather than going via NZCV, even if LHS and 15257 /// RHS are really scalar. This replaces any scalar setcc in the above pattern 15258 /// with a vector one followed by a DUP shuffle on the result. 15259 static SDValue performSelectCombine(SDNode *N, 15260 TargetLowering::DAGCombinerInfo &DCI) { 15261 SelectionDAG &DAG = DCI.DAG; 15262 SDValue N0 = N->getOperand(0); 15263 EVT ResVT = N->getValueType(0); 15264 15265 if (N0.getOpcode() != ISD::SETCC) 15266 return SDValue(); 15267 15268 // Make sure the SETCC result is either i1 (initial DAG), or i32, the lowered 15269 // scalar SetCCResultType. We also don't expect vectors, because we assume 15270 // that selects fed by vector SETCCs are canonicalized to VSELECT. 15271 assert((N0.getValueType() == MVT::i1 || N0.getValueType() == MVT::i32) && 15272 "Scalar-SETCC feeding SELECT has unexpected result type!"); 15273 15274 // If NumMaskElts == 0, the comparison is larger than select result. The 15275 // largest real NEON comparison is 64-bits per lane, which means the result is 15276 // at most 32-bits and an illegal vector. Just bail out for now. 15277 EVT SrcVT = N0.getOperand(0).getValueType(); 15278 15279 // Don't try to do this optimization when the setcc itself has i1 operands. 15280 // There are no legal vectors of i1, so this would be pointless. 15281 if (SrcVT == MVT::i1) 15282 return SDValue(); 15283 15284 int NumMaskElts = ResVT.getSizeInBits() / SrcVT.getSizeInBits(); 15285 if (!ResVT.isVector() || NumMaskElts == 0) 15286 return SDValue(); 15287 15288 SrcVT = EVT::getVectorVT(*DAG.getContext(), SrcVT, NumMaskElts); 15289 EVT CCVT = SrcVT.changeVectorElementTypeToInteger(); 15290 15291 // Also bail out if the vector CCVT isn't the same size as ResVT. 15292 // This can happen if the SETCC operand size doesn't divide the ResVT size 15293 // (e.g., f64 vs v3f32). 15294 if (CCVT.getSizeInBits() != ResVT.getSizeInBits()) 15295 return SDValue(); 15296 15297 // Make sure we didn't create illegal types, if we're not supposed to. 15298 assert(DCI.isBeforeLegalize() || 15299 DAG.getTargetLoweringInfo().isTypeLegal(SrcVT)); 15300 15301 // First perform a vector comparison, where lane 0 is the one we're interested 15302 // in. 15303 SDLoc DL(N0); 15304 SDValue LHS = 15305 DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, SrcVT, N0.getOperand(0)); 15306 SDValue RHS = 15307 DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, SrcVT, N0.getOperand(1)); 15308 SDValue SetCC = DAG.getNode(ISD::SETCC, DL, CCVT, LHS, RHS, N0.getOperand(2)); 15309 15310 // Now duplicate the comparison mask we want across all other lanes. 15311 SmallVector<int, 8> DUPMask(CCVT.getVectorNumElements(), 0); 15312 SDValue Mask = DAG.getVectorShuffle(CCVT, DL, SetCC, SetCC, DUPMask); 15313 Mask = DAG.getNode(ISD::BITCAST, DL, 15314 ResVT.changeVectorElementTypeToInteger(), Mask); 15315 15316 return DAG.getSelect(DL, ResVT, Mask, N->getOperand(1), N->getOperand(2)); 15317 } 15318 15319 /// Get rid of unnecessary NVCASTs (that don't change the type). 15320 static SDValue performNVCASTCombine(SDNode *N) { 15321 if (N->getValueType(0) == N->getOperand(0).getValueType()) 15322 return N->getOperand(0); 15323 15324 return SDValue(); 15325 } 15326 15327 // If all users of the globaladdr are of the form (globaladdr + constant), find 15328 // the smallest constant, fold it into the globaladdr's offset and rewrite the 15329 // globaladdr as (globaladdr + constant) - constant. 15330 static SDValue performGlobalAddressCombine(SDNode *N, SelectionDAG &DAG, 15331 const AArch64Subtarget *Subtarget, 15332 const TargetMachine &TM) { 15333 auto *GN = cast<GlobalAddressSDNode>(N); 15334 if (Subtarget->ClassifyGlobalReference(GN->getGlobal(), TM) != 15335 AArch64II::MO_NO_FLAG) 15336 return SDValue(); 15337 15338 uint64_t MinOffset = -1ull; 15339 for (SDNode *N : GN->uses()) { 15340 if (N->getOpcode() != ISD::ADD) 15341 return SDValue(); 15342 auto *C = dyn_cast<ConstantSDNode>(N->getOperand(0)); 15343 if (!C) 15344 C = dyn_cast<ConstantSDNode>(N->getOperand(1)); 15345 if (!C) 15346 return SDValue(); 15347 MinOffset = std::min(MinOffset, C->getZExtValue()); 15348 } 15349 uint64_t Offset = MinOffset + GN->getOffset(); 15350 15351 // Require that the new offset is larger than the existing one. Otherwise, we 15352 // can end up oscillating between two possible DAGs, for example, 15353 // (add (add globaladdr + 10, -1), 1) and (add globaladdr + 9, 1). 15354 if (Offset <= uint64_t(GN->getOffset())) 15355 return SDValue(); 15356 15357 // Check whether folding this offset is legal. It must not go out of bounds of 15358 // the referenced object to avoid violating the code model, and must be 15359 // smaller than 2^21 because this is the largest offset expressible in all 15360 // object formats. 15361 // 15362 // This check also prevents us from folding negative offsets, which will end 15363 // up being treated in the same way as large positive ones. They could also 15364 // cause code model violations, and aren't really common enough to matter. 15365 if (Offset >= (1 << 21)) 15366 return SDValue(); 15367 15368 const GlobalValue *GV = GN->getGlobal(); 15369 Type *T = GV->getValueType(); 15370 if (!T->isSized() || 15371 Offset > GV->getParent()->getDataLayout().getTypeAllocSize(T)) 15372 return SDValue(); 15373 15374 SDLoc DL(GN); 15375 SDValue Result = DAG.getGlobalAddress(GV, DL, MVT::i64, Offset); 15376 return DAG.getNode(ISD::SUB, DL, MVT::i64, Result, 15377 DAG.getConstant(MinOffset, DL, MVT::i64)); 15378 } 15379 15380 // Turns the vector of indices into a vector of byte offstes by scaling Offset 15381 // by (BitWidth / 8). 15382 static SDValue getScaledOffsetForBitWidth(SelectionDAG &DAG, SDValue Offset, 15383 SDLoc DL, unsigned BitWidth) { 15384 assert(Offset.getValueType().isScalableVector() && 15385 "This method is only for scalable vectors of offsets"); 15386 15387 SDValue Shift = DAG.getConstant(Log2_32(BitWidth / 8), DL, MVT::i64); 15388 SDValue SplatShift = DAG.getNode(ISD::SPLAT_VECTOR, DL, MVT::nxv2i64, Shift); 15389 15390 return DAG.getNode(ISD::SHL, DL, MVT::nxv2i64, Offset, SplatShift); 15391 } 15392 15393 /// Check if the value of \p OffsetInBytes can be used as an immediate for 15394 /// the gather load/prefetch and scatter store instructions with vector base and 15395 /// immediate offset addressing mode: 15396 /// 15397 /// [<Zn>.[S|D]{, #<imm>}] 15398 /// 15399 /// where <imm> = sizeof(<T>) * k, for k = 0, 1, ..., 31. 15400 15401 inline static bool isValidImmForSVEVecImmAddrMode(unsigned OffsetInBytes, 15402 unsigned ScalarSizeInBytes) { 15403 // The immediate is not a multiple of the scalar size. 15404 if (OffsetInBytes % ScalarSizeInBytes) 15405 return false; 15406 15407 // The immediate is out of range. 15408 if (OffsetInBytes / ScalarSizeInBytes > 31) 15409 return false; 15410 15411 return true; 15412 } 15413 15414 /// Check if the value of \p Offset represents a valid immediate for the SVE 15415 /// gather load/prefetch and scatter store instructiona with vector base and 15416 /// immediate offset addressing mode: 15417 /// 15418 /// [<Zn>.[S|D]{, #<imm>}] 15419 /// 15420 /// where <imm> = sizeof(<T>) * k, for k = 0, 1, ..., 31. 15421 static bool isValidImmForSVEVecImmAddrMode(SDValue Offset, 15422 unsigned ScalarSizeInBytes) { 15423 ConstantSDNode *OffsetConst = dyn_cast<ConstantSDNode>(Offset.getNode()); 15424 return OffsetConst && isValidImmForSVEVecImmAddrMode( 15425 OffsetConst->getZExtValue(), ScalarSizeInBytes); 15426 } 15427 15428 static SDValue performScatterStoreCombine(SDNode *N, SelectionDAG &DAG, 15429 unsigned Opcode, 15430 bool OnlyPackedOffsets = true) { 15431 const SDValue Src = N->getOperand(2); 15432 const EVT SrcVT = Src->getValueType(0); 15433 assert(SrcVT.isScalableVector() && 15434 "Scatter stores are only possible for SVE vectors"); 15435 15436 SDLoc DL(N); 15437 MVT SrcElVT = SrcVT.getVectorElementType().getSimpleVT(); 15438 15439 // Make sure that source data will fit into an SVE register 15440 if (SrcVT.getSizeInBits().getKnownMinSize() > AArch64::SVEBitsPerBlock) 15441 return SDValue(); 15442 15443 // For FPs, ACLE only supports _packed_ single and double precision types. 15444 if (SrcElVT.isFloatingPoint()) 15445 if ((SrcVT != MVT::nxv4f32) && (SrcVT != MVT::nxv2f64)) 15446 return SDValue(); 15447 15448 // Depending on the addressing mode, this is either a pointer or a vector of 15449 // pointers (that fits into one register) 15450 SDValue Base = N->getOperand(4); 15451 // Depending on the addressing mode, this is either a single offset or a 15452 // vector of offsets (that fits into one register) 15453 SDValue Offset = N->getOperand(5); 15454 15455 // For "scalar + vector of indices", just scale the indices. This only 15456 // applies to non-temporal scatters because there's no instruction that takes 15457 // indicies. 15458 if (Opcode == AArch64ISD::SSTNT1_INDEX_PRED) { 15459 Offset = 15460 getScaledOffsetForBitWidth(DAG, Offset, DL, SrcElVT.getSizeInBits()); 15461 Opcode = AArch64ISD::SSTNT1_PRED; 15462 } 15463 15464 // In the case of non-temporal gather loads there's only one SVE instruction 15465 // per data-size: "scalar + vector", i.e. 15466 // * stnt1{b|h|w|d} { z0.s }, p0/z, [z0.s, x0] 15467 // Since we do have intrinsics that allow the arguments to be in a different 15468 // order, we may need to swap them to match the spec. 15469 if (Opcode == AArch64ISD::SSTNT1_PRED && Offset.getValueType().isVector()) 15470 std::swap(Base, Offset); 15471 15472 // SST1_IMM requires that the offset is an immediate that is: 15473 // * a multiple of #SizeInBytes, 15474 // * in the range [0, 31 x #SizeInBytes], 15475 // where #SizeInBytes is the size in bytes of the stored items. For 15476 // immediates outside that range and non-immediate scalar offsets use SST1 or 15477 // SST1_UXTW instead. 15478 if (Opcode == AArch64ISD::SST1_IMM_PRED) { 15479 if (!isValidImmForSVEVecImmAddrMode(Offset, 15480 SrcVT.getScalarSizeInBits() / 8)) { 15481 if (MVT::nxv4i32 == Base.getValueType().getSimpleVT().SimpleTy) 15482 Opcode = AArch64ISD::SST1_UXTW_PRED; 15483 else 15484 Opcode = AArch64ISD::SST1_PRED; 15485 15486 std::swap(Base, Offset); 15487 } 15488 } 15489 15490 auto &TLI = DAG.getTargetLoweringInfo(); 15491 if (!TLI.isTypeLegal(Base.getValueType())) 15492 return SDValue(); 15493 15494 // Some scatter store variants allow unpacked offsets, but only as nxv2i32 15495 // vectors. These are implicitly sign (sxtw) or zero (zxtw) extend to 15496 // nxv2i64. Legalize accordingly. 15497 if (!OnlyPackedOffsets && 15498 Offset.getValueType().getSimpleVT().SimpleTy == MVT::nxv2i32) 15499 Offset = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::nxv2i64, Offset).getValue(0); 15500 15501 if (!TLI.isTypeLegal(Offset.getValueType())) 15502 return SDValue(); 15503 15504 // Source value type that is representable in hardware 15505 EVT HwSrcVt = getSVEContainerType(SrcVT); 15506 15507 // Keep the original type of the input data to store - this is needed to be 15508 // able to select the correct instruction, e.g. ST1B, ST1H, ST1W and ST1D. For 15509 // FP values we want the integer equivalent, so just use HwSrcVt. 15510 SDValue InputVT = DAG.getValueType(SrcVT); 15511 if (SrcVT.isFloatingPoint()) 15512 InputVT = DAG.getValueType(HwSrcVt); 15513 15514 SDVTList VTs = DAG.getVTList(MVT::Other); 15515 SDValue SrcNew; 15516 15517 if (Src.getValueType().isFloatingPoint()) 15518 SrcNew = DAG.getNode(ISD::BITCAST, DL, HwSrcVt, Src); 15519 else 15520 SrcNew = DAG.getNode(ISD::ANY_EXTEND, DL, HwSrcVt, Src); 15521 15522 SDValue Ops[] = {N->getOperand(0), // Chain 15523 SrcNew, 15524 N->getOperand(3), // Pg 15525 Base, 15526 Offset, 15527 InputVT}; 15528 15529 return DAG.getNode(Opcode, DL, VTs, Ops); 15530 } 15531 15532 static SDValue performGatherLoadCombine(SDNode *N, SelectionDAG &DAG, 15533 unsigned Opcode, 15534 bool OnlyPackedOffsets = true) { 15535 const EVT RetVT = N->getValueType(0); 15536 assert(RetVT.isScalableVector() && 15537 "Gather loads are only possible for SVE vectors"); 15538 15539 SDLoc DL(N); 15540 15541 // Make sure that the loaded data will fit into an SVE register 15542 if (RetVT.getSizeInBits().getKnownMinSize() > AArch64::SVEBitsPerBlock) 15543 return SDValue(); 15544 15545 // Depending on the addressing mode, this is either a pointer or a vector of 15546 // pointers (that fits into one register) 15547 SDValue Base = N->getOperand(3); 15548 // Depending on the addressing mode, this is either a single offset or a 15549 // vector of offsets (that fits into one register) 15550 SDValue Offset = N->getOperand(4); 15551 15552 // For "scalar + vector of indices", just scale the indices. This only 15553 // applies to non-temporal gathers because there's no instruction that takes 15554 // indicies. 15555 if (Opcode == AArch64ISD::GLDNT1_INDEX_MERGE_ZERO) { 15556 Offset = getScaledOffsetForBitWidth(DAG, Offset, DL, 15557 RetVT.getScalarSizeInBits()); 15558 Opcode = AArch64ISD::GLDNT1_MERGE_ZERO; 15559 } 15560 15561 // In the case of non-temporal gather loads there's only one SVE instruction 15562 // per data-size: "scalar + vector", i.e. 15563 // * ldnt1{b|h|w|d} { z0.s }, p0/z, [z0.s, x0] 15564 // Since we do have intrinsics that allow the arguments to be in a different 15565 // order, we may need to swap them to match the spec. 15566 if (Opcode == AArch64ISD::GLDNT1_MERGE_ZERO && 15567 Offset.getValueType().isVector()) 15568 std::swap(Base, Offset); 15569 15570 // GLD{FF}1_IMM requires that the offset is an immediate that is: 15571 // * a multiple of #SizeInBytes, 15572 // * in the range [0, 31 x #SizeInBytes], 15573 // where #SizeInBytes is the size in bytes of the loaded items. For 15574 // immediates outside that range and non-immediate scalar offsets use 15575 // GLD1_MERGE_ZERO or GLD1_UXTW_MERGE_ZERO instead. 15576 if (Opcode == AArch64ISD::GLD1_IMM_MERGE_ZERO || 15577 Opcode == AArch64ISD::GLDFF1_IMM_MERGE_ZERO) { 15578 if (!isValidImmForSVEVecImmAddrMode(Offset, 15579 RetVT.getScalarSizeInBits() / 8)) { 15580 if (MVT::nxv4i32 == Base.getValueType().getSimpleVT().SimpleTy) 15581 Opcode = (Opcode == AArch64ISD::GLD1_IMM_MERGE_ZERO) 15582 ? AArch64ISD::GLD1_UXTW_MERGE_ZERO 15583 : AArch64ISD::GLDFF1_UXTW_MERGE_ZERO; 15584 else 15585 Opcode = (Opcode == AArch64ISD::GLD1_IMM_MERGE_ZERO) 15586 ? AArch64ISD::GLD1_MERGE_ZERO 15587 : AArch64ISD::GLDFF1_MERGE_ZERO; 15588 15589 std::swap(Base, Offset); 15590 } 15591 } 15592 15593 auto &TLI = DAG.getTargetLoweringInfo(); 15594 if (!TLI.isTypeLegal(Base.getValueType())) 15595 return SDValue(); 15596 15597 // Some gather load variants allow unpacked offsets, but only as nxv2i32 15598 // vectors. These are implicitly sign (sxtw) or zero (zxtw) extend to 15599 // nxv2i64. Legalize accordingly. 15600 if (!OnlyPackedOffsets && 15601 Offset.getValueType().getSimpleVT().SimpleTy == MVT::nxv2i32) 15602 Offset = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::nxv2i64, Offset).getValue(0); 15603 15604 // Return value type that is representable in hardware 15605 EVT HwRetVt = getSVEContainerType(RetVT); 15606 15607 // Keep the original output value type around - this is needed to be able to 15608 // select the correct instruction, e.g. LD1B, LD1H, LD1W and LD1D. For FP 15609 // values we want the integer equivalent, so just use HwRetVT. 15610 SDValue OutVT = DAG.getValueType(RetVT); 15611 if (RetVT.isFloatingPoint()) 15612 OutVT = DAG.getValueType(HwRetVt); 15613 15614 SDVTList VTs = DAG.getVTList(HwRetVt, MVT::Other); 15615 SDValue Ops[] = {N->getOperand(0), // Chain 15616 N->getOperand(2), // Pg 15617 Base, Offset, OutVT}; 15618 15619 SDValue Load = DAG.getNode(Opcode, DL, VTs, Ops); 15620 SDValue LoadChain = SDValue(Load.getNode(), 1); 15621 15622 if (RetVT.isInteger() && (RetVT != HwRetVt)) 15623 Load = DAG.getNode(ISD::TRUNCATE, DL, RetVT, Load.getValue(0)); 15624 15625 // If the original return value was FP, bitcast accordingly. Doing it here 15626 // means that we can avoid adding TableGen patterns for FPs. 15627 if (RetVT.isFloatingPoint()) 15628 Load = DAG.getNode(ISD::BITCAST, DL, RetVT, Load.getValue(0)); 15629 15630 return DAG.getMergeValues({Load, LoadChain}, DL); 15631 } 15632 15633 static SDValue 15634 performSignExtendInRegCombine(SDNode *N, TargetLowering::DAGCombinerInfo &DCI, 15635 SelectionDAG &DAG) { 15636 SDLoc DL(N); 15637 SDValue Src = N->getOperand(0); 15638 unsigned Opc = Src->getOpcode(); 15639 15640 // Sign extend of an unsigned unpack -> signed unpack 15641 if (Opc == AArch64ISD::UUNPKHI || Opc == AArch64ISD::UUNPKLO) { 15642 15643 unsigned SOpc = Opc == AArch64ISD::UUNPKHI ? AArch64ISD::SUNPKHI 15644 : AArch64ISD::SUNPKLO; 15645 15646 // Push the sign extend to the operand of the unpack 15647 // This is necessary where, for example, the operand of the unpack 15648 // is another unpack: 15649 // 4i32 sign_extend_inreg (4i32 uunpklo(8i16 uunpklo (16i8 opnd)), from 4i8) 15650 // -> 15651 // 4i32 sunpklo (8i16 sign_extend_inreg(8i16 uunpklo (16i8 opnd), from 8i8) 15652 // -> 15653 // 4i32 sunpklo(8i16 sunpklo(16i8 opnd)) 15654 SDValue ExtOp = Src->getOperand(0); 15655 auto VT = cast<VTSDNode>(N->getOperand(1))->getVT(); 15656 EVT EltTy = VT.getVectorElementType(); 15657 (void)EltTy; 15658 15659 assert((EltTy == MVT::i8 || EltTy == MVT::i16 || EltTy == MVT::i32) && 15660 "Sign extending from an invalid type"); 15661 15662 EVT ExtVT = VT.getDoubleNumVectorElementsVT(*DAG.getContext()); 15663 15664 SDValue Ext = DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, ExtOp.getValueType(), 15665 ExtOp, DAG.getValueType(ExtVT)); 15666 15667 return DAG.getNode(SOpc, DL, N->getValueType(0), Ext); 15668 } 15669 15670 if (DCI.isBeforeLegalizeOps()) 15671 return SDValue(); 15672 15673 if (!EnableCombineMGatherIntrinsics) 15674 return SDValue(); 15675 15676 // SVE load nodes (e.g. AArch64ISD::GLD1) are straightforward candidates 15677 // for DAG Combine with SIGN_EXTEND_INREG. Bail out for all other nodes. 15678 unsigned NewOpc; 15679 unsigned MemVTOpNum = 4; 15680 switch (Opc) { 15681 case AArch64ISD::LD1_MERGE_ZERO: 15682 NewOpc = AArch64ISD::LD1S_MERGE_ZERO; 15683 MemVTOpNum = 3; 15684 break; 15685 case AArch64ISD::LDNF1_MERGE_ZERO: 15686 NewOpc = AArch64ISD::LDNF1S_MERGE_ZERO; 15687 MemVTOpNum = 3; 15688 break; 15689 case AArch64ISD::LDFF1_MERGE_ZERO: 15690 NewOpc = AArch64ISD::LDFF1S_MERGE_ZERO; 15691 MemVTOpNum = 3; 15692 break; 15693 case AArch64ISD::GLD1_MERGE_ZERO: 15694 NewOpc = AArch64ISD::GLD1S_MERGE_ZERO; 15695 break; 15696 case AArch64ISD::GLD1_SCALED_MERGE_ZERO: 15697 NewOpc = AArch64ISD::GLD1S_SCALED_MERGE_ZERO; 15698 break; 15699 case AArch64ISD::GLD1_SXTW_MERGE_ZERO: 15700 NewOpc = AArch64ISD::GLD1S_SXTW_MERGE_ZERO; 15701 break; 15702 case AArch64ISD::GLD1_SXTW_SCALED_MERGE_ZERO: 15703 NewOpc = AArch64ISD::GLD1S_SXTW_SCALED_MERGE_ZERO; 15704 break; 15705 case AArch64ISD::GLD1_UXTW_MERGE_ZERO: 15706 NewOpc = AArch64ISD::GLD1S_UXTW_MERGE_ZERO; 15707 break; 15708 case AArch64ISD::GLD1_UXTW_SCALED_MERGE_ZERO: 15709 NewOpc = AArch64ISD::GLD1S_UXTW_SCALED_MERGE_ZERO; 15710 break; 15711 case AArch64ISD::GLD1_IMM_MERGE_ZERO: 15712 NewOpc = AArch64ISD::GLD1S_IMM_MERGE_ZERO; 15713 break; 15714 case AArch64ISD::GLDFF1_MERGE_ZERO: 15715 NewOpc = AArch64ISD::GLDFF1S_MERGE_ZERO; 15716 break; 15717 case AArch64ISD::GLDFF1_SCALED_MERGE_ZERO: 15718 NewOpc = AArch64ISD::GLDFF1S_SCALED_MERGE_ZERO; 15719 break; 15720 case AArch64ISD::GLDFF1_SXTW_MERGE_ZERO: 15721 NewOpc = AArch64ISD::GLDFF1S_SXTW_MERGE_ZERO; 15722 break; 15723 case AArch64ISD::GLDFF1_SXTW_SCALED_MERGE_ZERO: 15724 NewOpc = AArch64ISD::GLDFF1S_SXTW_SCALED_MERGE_ZERO; 15725 break; 15726 case AArch64ISD::GLDFF1_UXTW_MERGE_ZERO: 15727 NewOpc = AArch64ISD::GLDFF1S_UXTW_MERGE_ZERO; 15728 break; 15729 case AArch64ISD::GLDFF1_UXTW_SCALED_MERGE_ZERO: 15730 NewOpc = AArch64ISD::GLDFF1S_UXTW_SCALED_MERGE_ZERO; 15731 break; 15732 case AArch64ISD::GLDFF1_IMM_MERGE_ZERO: 15733 NewOpc = AArch64ISD::GLDFF1S_IMM_MERGE_ZERO; 15734 break; 15735 case AArch64ISD::GLDNT1_MERGE_ZERO: 15736 NewOpc = AArch64ISD::GLDNT1S_MERGE_ZERO; 15737 break; 15738 default: 15739 return SDValue(); 15740 } 15741 15742 EVT SignExtSrcVT = cast<VTSDNode>(N->getOperand(1))->getVT(); 15743 EVT SrcMemVT = cast<VTSDNode>(Src->getOperand(MemVTOpNum))->getVT(); 15744 15745 if ((SignExtSrcVT != SrcMemVT) || !Src.hasOneUse()) 15746 return SDValue(); 15747 15748 EVT DstVT = N->getValueType(0); 15749 SDVTList VTs = DAG.getVTList(DstVT, MVT::Other); 15750 15751 SmallVector<SDValue, 5> Ops; 15752 for (unsigned I = 0; I < Src->getNumOperands(); ++I) 15753 Ops.push_back(Src->getOperand(I)); 15754 15755 SDValue ExtLoad = DAG.getNode(NewOpc, SDLoc(N), VTs, Ops); 15756 DCI.CombineTo(N, ExtLoad); 15757 DCI.CombineTo(Src.getNode(), ExtLoad, ExtLoad.getValue(1)); 15758 15759 // Return N so it doesn't get rechecked 15760 return SDValue(N, 0); 15761 } 15762 15763 /// Legalize the gather prefetch (scalar + vector addressing mode) when the 15764 /// offset vector is an unpacked 32-bit scalable vector. The other cases (Offset 15765 /// != nxv2i32) do not need legalization. 15766 static SDValue legalizeSVEGatherPrefetchOffsVec(SDNode *N, SelectionDAG &DAG) { 15767 const unsigned OffsetPos = 4; 15768 SDValue Offset = N->getOperand(OffsetPos); 15769 15770 // Not an unpacked vector, bail out. 15771 if (Offset.getValueType().getSimpleVT().SimpleTy != MVT::nxv2i32) 15772 return SDValue(); 15773 15774 // Extend the unpacked offset vector to 64-bit lanes. 15775 SDLoc DL(N); 15776 Offset = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::nxv2i64, Offset); 15777 SmallVector<SDValue, 5> Ops(N->op_begin(), N->op_end()); 15778 // Replace the offset operand with the 64-bit one. 15779 Ops[OffsetPos] = Offset; 15780 15781 return DAG.getNode(N->getOpcode(), DL, DAG.getVTList(MVT::Other), Ops); 15782 } 15783 15784 /// Combines a node carrying the intrinsic 15785 /// `aarch64_sve_prf<T>_gather_scalar_offset` into a node that uses 15786 /// `aarch64_sve_prfb_gather_uxtw_index` when the scalar offset passed to 15787 /// `aarch64_sve_prf<T>_gather_scalar_offset` is not a valid immediate for the 15788 /// sve gather prefetch instruction with vector plus immediate addressing mode. 15789 static SDValue combineSVEPrefetchVecBaseImmOff(SDNode *N, SelectionDAG &DAG, 15790 unsigned ScalarSizeInBytes) { 15791 const unsigned ImmPos = 4, OffsetPos = 3; 15792 // No need to combine the node if the immediate is valid... 15793 if (isValidImmForSVEVecImmAddrMode(N->getOperand(ImmPos), ScalarSizeInBytes)) 15794 return SDValue(); 15795 15796 // ...otherwise swap the offset base with the offset... 15797 SmallVector<SDValue, 5> Ops(N->op_begin(), N->op_end()); 15798 std::swap(Ops[ImmPos], Ops[OffsetPos]); 15799 // ...and remap the intrinsic `aarch64_sve_prf<T>_gather_scalar_offset` to 15800 // `aarch64_sve_prfb_gather_uxtw_index`. 15801 SDLoc DL(N); 15802 Ops[1] = DAG.getConstant(Intrinsic::aarch64_sve_prfb_gather_uxtw_index, DL, 15803 MVT::i64); 15804 15805 return DAG.getNode(N->getOpcode(), DL, DAG.getVTList(MVT::Other), Ops); 15806 } 15807 15808 SDValue AArch64TargetLowering::PerformDAGCombine(SDNode *N, 15809 DAGCombinerInfo &DCI) const { 15810 SelectionDAG &DAG = DCI.DAG; 15811 switch (N->getOpcode()) { 15812 default: 15813 LLVM_DEBUG(dbgs() << "Custom combining: skipping\n"); 15814 break; 15815 case ISD::ABS: 15816 return performABSCombine(N, DAG, DCI, Subtarget); 15817 case ISD::ADD: 15818 case ISD::SUB: 15819 return performAddSubCombine(N, DCI, DAG); 15820 case ISD::XOR: 15821 return performXorCombine(N, DAG, DCI, Subtarget); 15822 case ISD::MUL: 15823 return performMulCombine(N, DAG, DCI, Subtarget); 15824 case ISD::SINT_TO_FP: 15825 case ISD::UINT_TO_FP: 15826 return performIntToFpCombine(N, DAG, Subtarget); 15827 case ISD::FP_TO_SINT: 15828 case ISD::FP_TO_UINT: 15829 return performFpToIntCombine(N, DAG, DCI, Subtarget); 15830 case ISD::FDIV: 15831 return performFDivCombine(N, DAG, DCI, Subtarget); 15832 case ISD::OR: 15833 return performORCombine(N, DCI, Subtarget); 15834 case ISD::AND: 15835 return performANDCombine(N, DCI); 15836 case ISD::SRL: 15837 return performSRLCombine(N, DCI); 15838 case ISD::INTRINSIC_WO_CHAIN: 15839 return performIntrinsicCombine(N, DCI, Subtarget); 15840 case ISD::ANY_EXTEND: 15841 case ISD::ZERO_EXTEND: 15842 case ISD::SIGN_EXTEND: 15843 return performExtendCombine(N, DCI, DAG); 15844 case ISD::SIGN_EXTEND_INREG: 15845 return performSignExtendInRegCombine(N, DCI, DAG); 15846 case ISD::TRUNCATE: 15847 return performVectorTruncateCombine(N, DCI, DAG); 15848 case ISD::CONCAT_VECTORS: 15849 return performConcatVectorsCombine(N, DCI, DAG); 15850 case ISD::SELECT: 15851 return performSelectCombine(N, DCI); 15852 case ISD::VSELECT: 15853 return performVSelectCombine(N, DCI.DAG); 15854 case ISD::LOAD: 15855 if (performTBISimplification(N->getOperand(1), DCI, DAG)) 15856 return SDValue(N, 0); 15857 break; 15858 case ISD::STORE: 15859 return performSTORECombine(N, DCI, DAG, Subtarget); 15860 case AArch64ISD::BRCOND: 15861 return performBRCONDCombine(N, DCI, DAG); 15862 case AArch64ISD::TBNZ: 15863 case AArch64ISD::TBZ: 15864 return performTBZCombine(N, DCI, DAG); 15865 case AArch64ISD::CSEL: 15866 return performCONDCombine(N, DCI, DAG, 2, 3); 15867 case AArch64ISD::DUP: 15868 return performPostLD1Combine(N, DCI, false); 15869 case AArch64ISD::NVCAST: 15870 return performNVCASTCombine(N); 15871 case AArch64ISD::UZP1: 15872 return performUzpCombine(N, DAG); 15873 case AArch64ISD::GLD1_MERGE_ZERO: 15874 case AArch64ISD::GLD1_SCALED_MERGE_ZERO: 15875 case AArch64ISD::GLD1_UXTW_MERGE_ZERO: 15876 case AArch64ISD::GLD1_SXTW_MERGE_ZERO: 15877 case AArch64ISD::GLD1_UXTW_SCALED_MERGE_ZERO: 15878 case AArch64ISD::GLD1_SXTW_SCALED_MERGE_ZERO: 15879 case AArch64ISD::GLD1_IMM_MERGE_ZERO: 15880 case AArch64ISD::GLD1S_MERGE_ZERO: 15881 case AArch64ISD::GLD1S_SCALED_MERGE_ZERO: 15882 case AArch64ISD::GLD1S_UXTW_MERGE_ZERO: 15883 case AArch64ISD::GLD1S_SXTW_MERGE_ZERO: 15884 case AArch64ISD::GLD1S_UXTW_SCALED_MERGE_ZERO: 15885 case AArch64ISD::GLD1S_SXTW_SCALED_MERGE_ZERO: 15886 case AArch64ISD::GLD1S_IMM_MERGE_ZERO: 15887 return performGLD1Combine(N, DAG); 15888 case ISD::INSERT_VECTOR_ELT: 15889 return performPostLD1Combine(N, DCI, true); 15890 case ISD::EXTRACT_VECTOR_ELT: 15891 return performExtractVectorEltCombine(N, DAG); 15892 case ISD::VECREDUCE_ADD: 15893 return performVecReduceAddCombine(N, DCI.DAG, Subtarget); 15894 case ISD::INTRINSIC_VOID: 15895 case ISD::INTRINSIC_W_CHAIN: 15896 switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) { 15897 case Intrinsic::aarch64_sve_prfb_gather_scalar_offset: 15898 return combineSVEPrefetchVecBaseImmOff(N, DAG, 1 /*=ScalarSizeInBytes*/); 15899 case Intrinsic::aarch64_sve_prfh_gather_scalar_offset: 15900 return combineSVEPrefetchVecBaseImmOff(N, DAG, 2 /*=ScalarSizeInBytes*/); 15901 case Intrinsic::aarch64_sve_prfw_gather_scalar_offset: 15902 return combineSVEPrefetchVecBaseImmOff(N, DAG, 4 /*=ScalarSizeInBytes*/); 15903 case Intrinsic::aarch64_sve_prfd_gather_scalar_offset: 15904 return combineSVEPrefetchVecBaseImmOff(N, DAG, 8 /*=ScalarSizeInBytes*/); 15905 case Intrinsic::aarch64_sve_prfb_gather_uxtw_index: 15906 case Intrinsic::aarch64_sve_prfb_gather_sxtw_index: 15907 case Intrinsic::aarch64_sve_prfh_gather_uxtw_index: 15908 case Intrinsic::aarch64_sve_prfh_gather_sxtw_index: 15909 case Intrinsic::aarch64_sve_prfw_gather_uxtw_index: 15910 case Intrinsic::aarch64_sve_prfw_gather_sxtw_index: 15911 case Intrinsic::aarch64_sve_prfd_gather_uxtw_index: 15912 case Intrinsic::aarch64_sve_prfd_gather_sxtw_index: 15913 return legalizeSVEGatherPrefetchOffsVec(N, DAG); 15914 case Intrinsic::aarch64_neon_ld2: 15915 case Intrinsic::aarch64_neon_ld3: 15916 case Intrinsic::aarch64_neon_ld4: 15917 case Intrinsic::aarch64_neon_ld1x2: 15918 case Intrinsic::aarch64_neon_ld1x3: 15919 case Intrinsic::aarch64_neon_ld1x4: 15920 case Intrinsic::aarch64_neon_ld2lane: 15921 case Intrinsic::aarch64_neon_ld3lane: 15922 case Intrinsic::aarch64_neon_ld4lane: 15923 case Intrinsic::aarch64_neon_ld2r: 15924 case Intrinsic::aarch64_neon_ld3r: 15925 case Intrinsic::aarch64_neon_ld4r: 15926 case Intrinsic::aarch64_neon_st2: 15927 case Intrinsic::aarch64_neon_st3: 15928 case Intrinsic::aarch64_neon_st4: 15929 case Intrinsic::aarch64_neon_st1x2: 15930 case Intrinsic::aarch64_neon_st1x3: 15931 case Intrinsic::aarch64_neon_st1x4: 15932 case Intrinsic::aarch64_neon_st2lane: 15933 case Intrinsic::aarch64_neon_st3lane: 15934 case Intrinsic::aarch64_neon_st4lane: 15935 return performNEONPostLDSTCombine(N, DCI, DAG); 15936 case Intrinsic::aarch64_sve_ldnt1: 15937 return performLDNT1Combine(N, DAG); 15938 case Intrinsic::aarch64_sve_ld1rq: 15939 return performLD1ReplicateCombine<AArch64ISD::LD1RQ_MERGE_ZERO>(N, DAG); 15940 case Intrinsic::aarch64_sve_ld1ro: 15941 return performLD1ReplicateCombine<AArch64ISD::LD1RO_MERGE_ZERO>(N, DAG); 15942 case Intrinsic::aarch64_sve_ldnt1_gather_scalar_offset: 15943 return performGatherLoadCombine(N, DAG, AArch64ISD::GLDNT1_MERGE_ZERO); 15944 case Intrinsic::aarch64_sve_ldnt1_gather: 15945 return performGatherLoadCombine(N, DAG, AArch64ISD::GLDNT1_MERGE_ZERO); 15946 case Intrinsic::aarch64_sve_ldnt1_gather_index: 15947 return performGatherLoadCombine(N, DAG, 15948 AArch64ISD::GLDNT1_INDEX_MERGE_ZERO); 15949 case Intrinsic::aarch64_sve_ldnt1_gather_uxtw: 15950 return performGatherLoadCombine(N, DAG, AArch64ISD::GLDNT1_MERGE_ZERO); 15951 case Intrinsic::aarch64_sve_ld1: 15952 return performLD1Combine(N, DAG, AArch64ISD::LD1_MERGE_ZERO); 15953 case Intrinsic::aarch64_sve_ldnf1: 15954 return performLD1Combine(N, DAG, AArch64ISD::LDNF1_MERGE_ZERO); 15955 case Intrinsic::aarch64_sve_ldff1: 15956 return performLD1Combine(N, DAG, AArch64ISD::LDFF1_MERGE_ZERO); 15957 case Intrinsic::aarch64_sve_st1: 15958 return performST1Combine(N, DAG); 15959 case Intrinsic::aarch64_sve_stnt1: 15960 return performSTNT1Combine(N, DAG); 15961 case Intrinsic::aarch64_sve_stnt1_scatter_scalar_offset: 15962 return performScatterStoreCombine(N, DAG, AArch64ISD::SSTNT1_PRED); 15963 case Intrinsic::aarch64_sve_stnt1_scatter_uxtw: 15964 return performScatterStoreCombine(N, DAG, AArch64ISD::SSTNT1_PRED); 15965 case Intrinsic::aarch64_sve_stnt1_scatter: 15966 return performScatterStoreCombine(N, DAG, AArch64ISD::SSTNT1_PRED); 15967 case Intrinsic::aarch64_sve_stnt1_scatter_index: 15968 return performScatterStoreCombine(N, DAG, AArch64ISD::SSTNT1_INDEX_PRED); 15969 case Intrinsic::aarch64_sve_ld1_gather: 15970 return performGatherLoadCombine(N, DAG, AArch64ISD::GLD1_MERGE_ZERO); 15971 case Intrinsic::aarch64_sve_ld1_gather_index: 15972 return performGatherLoadCombine(N, DAG, 15973 AArch64ISD::GLD1_SCALED_MERGE_ZERO); 15974 case Intrinsic::aarch64_sve_ld1_gather_sxtw: 15975 return performGatherLoadCombine(N, DAG, AArch64ISD::GLD1_SXTW_MERGE_ZERO, 15976 /*OnlyPackedOffsets=*/false); 15977 case Intrinsic::aarch64_sve_ld1_gather_uxtw: 15978 return performGatherLoadCombine(N, DAG, AArch64ISD::GLD1_UXTW_MERGE_ZERO, 15979 /*OnlyPackedOffsets=*/false); 15980 case Intrinsic::aarch64_sve_ld1_gather_sxtw_index: 15981 return performGatherLoadCombine(N, DAG, 15982 AArch64ISD::GLD1_SXTW_SCALED_MERGE_ZERO, 15983 /*OnlyPackedOffsets=*/false); 15984 case Intrinsic::aarch64_sve_ld1_gather_uxtw_index: 15985 return performGatherLoadCombine(N, DAG, 15986 AArch64ISD::GLD1_UXTW_SCALED_MERGE_ZERO, 15987 /*OnlyPackedOffsets=*/false); 15988 case Intrinsic::aarch64_sve_ld1_gather_scalar_offset: 15989 return performGatherLoadCombine(N, DAG, AArch64ISD::GLD1_IMM_MERGE_ZERO); 15990 case Intrinsic::aarch64_sve_ldff1_gather: 15991 return performGatherLoadCombine(N, DAG, AArch64ISD::GLDFF1_MERGE_ZERO); 15992 case Intrinsic::aarch64_sve_ldff1_gather_index: 15993 return performGatherLoadCombine(N, DAG, 15994 AArch64ISD::GLDFF1_SCALED_MERGE_ZERO); 15995 case Intrinsic::aarch64_sve_ldff1_gather_sxtw: 15996 return performGatherLoadCombine(N, DAG, 15997 AArch64ISD::GLDFF1_SXTW_MERGE_ZERO, 15998 /*OnlyPackedOffsets=*/false); 15999 case Intrinsic::aarch64_sve_ldff1_gather_uxtw: 16000 return performGatherLoadCombine(N, DAG, 16001 AArch64ISD::GLDFF1_UXTW_MERGE_ZERO, 16002 /*OnlyPackedOffsets=*/false); 16003 case Intrinsic::aarch64_sve_ldff1_gather_sxtw_index: 16004 return performGatherLoadCombine(N, DAG, 16005 AArch64ISD::GLDFF1_SXTW_SCALED_MERGE_ZERO, 16006 /*OnlyPackedOffsets=*/false); 16007 case Intrinsic::aarch64_sve_ldff1_gather_uxtw_index: 16008 return performGatherLoadCombine(N, DAG, 16009 AArch64ISD::GLDFF1_UXTW_SCALED_MERGE_ZERO, 16010 /*OnlyPackedOffsets=*/false); 16011 case Intrinsic::aarch64_sve_ldff1_gather_scalar_offset: 16012 return performGatherLoadCombine(N, DAG, 16013 AArch64ISD::GLDFF1_IMM_MERGE_ZERO); 16014 case Intrinsic::aarch64_sve_st1_scatter: 16015 return performScatterStoreCombine(N, DAG, AArch64ISD::SST1_PRED); 16016 case Intrinsic::aarch64_sve_st1_scatter_index: 16017 return performScatterStoreCombine(N, DAG, AArch64ISD::SST1_SCALED_PRED); 16018 case Intrinsic::aarch64_sve_st1_scatter_sxtw: 16019 return performScatterStoreCombine(N, DAG, AArch64ISD::SST1_SXTW_PRED, 16020 /*OnlyPackedOffsets=*/false); 16021 case Intrinsic::aarch64_sve_st1_scatter_uxtw: 16022 return performScatterStoreCombine(N, DAG, AArch64ISD::SST1_UXTW_PRED, 16023 /*OnlyPackedOffsets=*/false); 16024 case Intrinsic::aarch64_sve_st1_scatter_sxtw_index: 16025 return performScatterStoreCombine(N, DAG, 16026 AArch64ISD::SST1_SXTW_SCALED_PRED, 16027 /*OnlyPackedOffsets=*/false); 16028 case Intrinsic::aarch64_sve_st1_scatter_uxtw_index: 16029 return performScatterStoreCombine(N, DAG, 16030 AArch64ISD::SST1_UXTW_SCALED_PRED, 16031 /*OnlyPackedOffsets=*/false); 16032 case Intrinsic::aarch64_sve_st1_scatter_scalar_offset: 16033 return performScatterStoreCombine(N, DAG, AArch64ISD::SST1_IMM_PRED); 16034 case Intrinsic::aarch64_sve_tuple_get: { 16035 SDLoc DL(N); 16036 SDValue Chain = N->getOperand(0); 16037 SDValue Src1 = N->getOperand(2); 16038 SDValue Idx = N->getOperand(3); 16039 16040 uint64_t IdxConst = cast<ConstantSDNode>(Idx)->getZExtValue(); 16041 EVT ResVT = N->getValueType(0); 16042 uint64_t NumLanes = ResVT.getVectorElementCount().getKnownMinValue(); 16043 SDValue ExtIdx = DAG.getVectorIdxConstant(IdxConst * NumLanes, DL); 16044 SDValue Val = 16045 DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, ResVT, Src1, ExtIdx); 16046 return DAG.getMergeValues({Val, Chain}, DL); 16047 } 16048 case Intrinsic::aarch64_sve_tuple_set: { 16049 SDLoc DL(N); 16050 SDValue Chain = N->getOperand(0); 16051 SDValue Tuple = N->getOperand(2); 16052 SDValue Idx = N->getOperand(3); 16053 SDValue Vec = N->getOperand(4); 16054 16055 EVT TupleVT = Tuple.getValueType(); 16056 uint64_t TupleLanes = TupleVT.getVectorElementCount().getKnownMinValue(); 16057 16058 uint64_t IdxConst = cast<ConstantSDNode>(Idx)->getZExtValue(); 16059 uint64_t NumLanes = 16060 Vec.getValueType().getVectorElementCount().getKnownMinValue(); 16061 16062 if ((TupleLanes % NumLanes) != 0) 16063 report_fatal_error("invalid tuple vector!"); 16064 16065 uint64_t NumVecs = TupleLanes / NumLanes; 16066 16067 SmallVector<SDValue, 4> Opnds; 16068 for (unsigned I = 0; I < NumVecs; ++I) { 16069 if (I == IdxConst) 16070 Opnds.push_back(Vec); 16071 else { 16072 SDValue ExtIdx = DAG.getVectorIdxConstant(I * NumLanes, DL); 16073 Opnds.push_back(DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, 16074 Vec.getValueType(), Tuple, ExtIdx)); 16075 } 16076 } 16077 SDValue Concat = 16078 DAG.getNode(ISD::CONCAT_VECTORS, DL, Tuple.getValueType(), Opnds); 16079 return DAG.getMergeValues({Concat, Chain}, DL); 16080 } 16081 case Intrinsic::aarch64_sve_tuple_create2: 16082 case Intrinsic::aarch64_sve_tuple_create3: 16083 case Intrinsic::aarch64_sve_tuple_create4: { 16084 SDLoc DL(N); 16085 SDValue Chain = N->getOperand(0); 16086 16087 SmallVector<SDValue, 4> Opnds; 16088 for (unsigned I = 2; I < N->getNumOperands(); ++I) 16089 Opnds.push_back(N->getOperand(I)); 16090 16091 EVT VT = Opnds[0].getValueType(); 16092 EVT EltVT = VT.getVectorElementType(); 16093 EVT DestVT = EVT::getVectorVT(*DAG.getContext(), EltVT, 16094 VT.getVectorElementCount() * 16095 (N->getNumOperands() - 2)); 16096 SDValue Concat = DAG.getNode(ISD::CONCAT_VECTORS, DL, DestVT, Opnds); 16097 return DAG.getMergeValues({Concat, Chain}, DL); 16098 } 16099 case Intrinsic::aarch64_sve_ld2: 16100 case Intrinsic::aarch64_sve_ld3: 16101 case Intrinsic::aarch64_sve_ld4: { 16102 SDLoc DL(N); 16103 SDValue Chain = N->getOperand(0); 16104 SDValue Mask = N->getOperand(2); 16105 SDValue BasePtr = N->getOperand(3); 16106 SDValue LoadOps[] = {Chain, Mask, BasePtr}; 16107 unsigned IntrinsicID = 16108 cast<ConstantSDNode>(N->getOperand(1))->getZExtValue(); 16109 SDValue Result = 16110 LowerSVEStructLoad(IntrinsicID, LoadOps, N->getValueType(0), DAG, DL); 16111 return DAG.getMergeValues({Result, Chain}, DL); 16112 } 16113 case Intrinsic::aarch64_rndr: 16114 case Intrinsic::aarch64_rndrrs: { 16115 unsigned IntrinsicID = 16116 cast<ConstantSDNode>(N->getOperand(1))->getZExtValue(); 16117 auto Register = 16118 (IntrinsicID == Intrinsic::aarch64_rndr ? AArch64SysReg::RNDR 16119 : AArch64SysReg::RNDRRS); 16120 SDLoc DL(N); 16121 SDValue A = DAG.getNode( 16122 AArch64ISD::MRS, DL, DAG.getVTList(MVT::i64, MVT::Glue, MVT::Other), 16123 N->getOperand(0), DAG.getConstant(Register, DL, MVT::i64)); 16124 SDValue B = DAG.getNode( 16125 AArch64ISD::CSINC, DL, MVT::i32, DAG.getConstant(0, DL, MVT::i32), 16126 DAG.getConstant(0, DL, MVT::i32), 16127 DAG.getConstant(AArch64CC::NE, DL, MVT::i32), A.getValue(1)); 16128 return DAG.getMergeValues( 16129 {A, DAG.getZExtOrTrunc(B, DL, MVT::i1), A.getValue(2)}, DL); 16130 } 16131 default: 16132 break; 16133 } 16134 break; 16135 case ISD::GlobalAddress: 16136 return performGlobalAddressCombine(N, DAG, Subtarget, getTargetMachine()); 16137 } 16138 return SDValue(); 16139 } 16140 16141 // Check if the return value is used as only a return value, as otherwise 16142 // we can't perform a tail-call. In particular, we need to check for 16143 // target ISD nodes that are returns and any other "odd" constructs 16144 // that the generic analysis code won't necessarily catch. 16145 bool AArch64TargetLowering::isUsedByReturnOnly(SDNode *N, 16146 SDValue &Chain) const { 16147 if (N->getNumValues() != 1) 16148 return false; 16149 if (!N->hasNUsesOfValue(1, 0)) 16150 return false; 16151 16152 SDValue TCChain = Chain; 16153 SDNode *Copy = *N->use_begin(); 16154 if (Copy->getOpcode() == ISD::CopyToReg) { 16155 // If the copy has a glue operand, we conservatively assume it isn't safe to 16156 // perform a tail call. 16157 if (Copy->getOperand(Copy->getNumOperands() - 1).getValueType() == 16158 MVT::Glue) 16159 return false; 16160 TCChain = Copy->getOperand(0); 16161 } else if (Copy->getOpcode() != ISD::FP_EXTEND) 16162 return false; 16163 16164 bool HasRet = false; 16165 for (SDNode *Node : Copy->uses()) { 16166 if (Node->getOpcode() != AArch64ISD::RET_FLAG) 16167 return false; 16168 HasRet = true; 16169 } 16170 16171 if (!HasRet) 16172 return false; 16173 16174 Chain = TCChain; 16175 return true; 16176 } 16177 16178 // Return whether the an instruction can potentially be optimized to a tail 16179 // call. This will cause the optimizers to attempt to move, or duplicate, 16180 // return instructions to help enable tail call optimizations for this 16181 // instruction. 16182 bool AArch64TargetLowering::mayBeEmittedAsTailCall(const CallInst *CI) const { 16183 return CI->isTailCall(); 16184 } 16185 16186 bool AArch64TargetLowering::getIndexedAddressParts(SDNode *Op, SDValue &Base, 16187 SDValue &Offset, 16188 ISD::MemIndexedMode &AM, 16189 bool &IsInc, 16190 SelectionDAG &DAG) const { 16191 if (Op->getOpcode() != ISD::ADD && Op->getOpcode() != ISD::SUB) 16192 return false; 16193 16194 Base = Op->getOperand(0); 16195 // All of the indexed addressing mode instructions take a signed 16196 // 9 bit immediate offset. 16197 if (ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(Op->getOperand(1))) { 16198 int64_t RHSC = RHS->getSExtValue(); 16199 if (Op->getOpcode() == ISD::SUB) 16200 RHSC = -(uint64_t)RHSC; 16201 if (!isInt<9>(RHSC)) 16202 return false; 16203 IsInc = (Op->getOpcode() == ISD::ADD); 16204 Offset = Op->getOperand(1); 16205 return true; 16206 } 16207 return false; 16208 } 16209 16210 bool AArch64TargetLowering::getPreIndexedAddressParts(SDNode *N, SDValue &Base, 16211 SDValue &Offset, 16212 ISD::MemIndexedMode &AM, 16213 SelectionDAG &DAG) const { 16214 EVT VT; 16215 SDValue Ptr; 16216 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) { 16217 VT = LD->getMemoryVT(); 16218 Ptr = LD->getBasePtr(); 16219 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) { 16220 VT = ST->getMemoryVT(); 16221 Ptr = ST->getBasePtr(); 16222 } else 16223 return false; 16224 16225 bool IsInc; 16226 if (!getIndexedAddressParts(Ptr.getNode(), Base, Offset, AM, IsInc, DAG)) 16227 return false; 16228 AM = IsInc ? ISD::PRE_INC : ISD::PRE_DEC; 16229 return true; 16230 } 16231 16232 bool AArch64TargetLowering::getPostIndexedAddressParts( 16233 SDNode *N, SDNode *Op, SDValue &Base, SDValue &Offset, 16234 ISD::MemIndexedMode &AM, SelectionDAG &DAG) const { 16235 EVT VT; 16236 SDValue Ptr; 16237 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) { 16238 VT = LD->getMemoryVT(); 16239 Ptr = LD->getBasePtr(); 16240 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) { 16241 VT = ST->getMemoryVT(); 16242 Ptr = ST->getBasePtr(); 16243 } else 16244 return false; 16245 16246 bool IsInc; 16247 if (!getIndexedAddressParts(Op, Base, Offset, AM, IsInc, DAG)) 16248 return false; 16249 // Post-indexing updates the base, so it's not a valid transform 16250 // if that's not the same as the load's pointer. 16251 if (Ptr != Base) 16252 return false; 16253 AM = IsInc ? ISD::POST_INC : ISD::POST_DEC; 16254 return true; 16255 } 16256 16257 static void ReplaceBITCASTResults(SDNode *N, SmallVectorImpl<SDValue> &Results, 16258 SelectionDAG &DAG) { 16259 SDLoc DL(N); 16260 SDValue Op = N->getOperand(0); 16261 16262 if (N->getValueType(0) != MVT::i16 || 16263 (Op.getValueType() != MVT::f16 && Op.getValueType() != MVT::bf16)) 16264 return; 16265 16266 Op = SDValue( 16267 DAG.getMachineNode(TargetOpcode::INSERT_SUBREG, DL, MVT::f32, 16268 DAG.getUNDEF(MVT::i32), Op, 16269 DAG.getTargetConstant(AArch64::hsub, DL, MVT::i32)), 16270 0); 16271 Op = DAG.getNode(ISD::BITCAST, DL, MVT::i32, Op); 16272 Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i16, Op)); 16273 } 16274 16275 static void ReplaceReductionResults(SDNode *N, 16276 SmallVectorImpl<SDValue> &Results, 16277 SelectionDAG &DAG, unsigned InterOp, 16278 unsigned AcrossOp) { 16279 EVT LoVT, HiVT; 16280 SDValue Lo, Hi; 16281 SDLoc dl(N); 16282 std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(N->getValueType(0)); 16283 std::tie(Lo, Hi) = DAG.SplitVectorOperand(N, 0); 16284 SDValue InterVal = DAG.getNode(InterOp, dl, LoVT, Lo, Hi); 16285 SDValue SplitVal = DAG.getNode(AcrossOp, dl, LoVT, InterVal); 16286 Results.push_back(SplitVal); 16287 } 16288 16289 static std::pair<SDValue, SDValue> splitInt128(SDValue N, SelectionDAG &DAG) { 16290 SDLoc DL(N); 16291 SDValue Lo = DAG.getNode(ISD::TRUNCATE, DL, MVT::i64, N); 16292 SDValue Hi = DAG.getNode(ISD::TRUNCATE, DL, MVT::i64, 16293 DAG.getNode(ISD::SRL, DL, MVT::i128, N, 16294 DAG.getConstant(64, DL, MVT::i64))); 16295 return std::make_pair(Lo, Hi); 16296 } 16297 16298 void AArch64TargetLowering::ReplaceExtractSubVectorResults( 16299 SDNode *N, SmallVectorImpl<SDValue> &Results, SelectionDAG &DAG) const { 16300 SDValue In = N->getOperand(0); 16301 EVT InVT = In.getValueType(); 16302 16303 // Common code will handle these just fine. 16304 if (!InVT.isScalableVector() || !InVT.isInteger()) 16305 return; 16306 16307 SDLoc DL(N); 16308 EVT VT = N->getValueType(0); 16309 16310 // The following checks bail if this is not a halving operation. 16311 16312 ElementCount ResEC = VT.getVectorElementCount(); 16313 16314 if (InVT.getVectorElementCount() != (ResEC * 2)) 16315 return; 16316 16317 auto *CIndex = dyn_cast<ConstantSDNode>(N->getOperand(1)); 16318 if (!CIndex) 16319 return; 16320 16321 unsigned Index = CIndex->getZExtValue(); 16322 if ((Index != 0) && (Index != ResEC.getKnownMinValue())) 16323 return; 16324 16325 unsigned Opcode = (Index == 0) ? AArch64ISD::UUNPKLO : AArch64ISD::UUNPKHI; 16326 EVT ExtendedHalfVT = VT.widenIntegerVectorElementType(*DAG.getContext()); 16327 16328 SDValue Half = DAG.getNode(Opcode, DL, ExtendedHalfVT, N->getOperand(0)); 16329 Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, VT, Half)); 16330 } 16331 16332 // Create an even/odd pair of X registers holding integer value V. 16333 static SDValue createGPRPairNode(SelectionDAG &DAG, SDValue V) { 16334 SDLoc dl(V.getNode()); 16335 SDValue VLo = DAG.getAnyExtOrTrunc(V, dl, MVT::i64); 16336 SDValue VHi = DAG.getAnyExtOrTrunc( 16337 DAG.getNode(ISD::SRL, dl, MVT::i128, V, DAG.getConstant(64, dl, MVT::i64)), 16338 dl, MVT::i64); 16339 if (DAG.getDataLayout().isBigEndian()) 16340 std::swap (VLo, VHi); 16341 SDValue RegClass = 16342 DAG.getTargetConstant(AArch64::XSeqPairsClassRegClassID, dl, MVT::i32); 16343 SDValue SubReg0 = DAG.getTargetConstant(AArch64::sube64, dl, MVT::i32); 16344 SDValue SubReg1 = DAG.getTargetConstant(AArch64::subo64, dl, MVT::i32); 16345 const SDValue Ops[] = { RegClass, VLo, SubReg0, VHi, SubReg1 }; 16346 return SDValue( 16347 DAG.getMachineNode(TargetOpcode::REG_SEQUENCE, dl, MVT::Untyped, Ops), 0); 16348 } 16349 16350 static void ReplaceCMP_SWAP_128Results(SDNode *N, 16351 SmallVectorImpl<SDValue> &Results, 16352 SelectionDAG &DAG, 16353 const AArch64Subtarget *Subtarget) { 16354 assert(N->getValueType(0) == MVT::i128 && 16355 "AtomicCmpSwap on types less than 128 should be legal"); 16356 16357 if (Subtarget->hasLSE() || Subtarget->outlineAtomics()) { 16358 // LSE has a 128-bit compare and swap (CASP), but i128 is not a legal type, 16359 // so lower it here, wrapped in REG_SEQUENCE and EXTRACT_SUBREG. 16360 SDValue Ops[] = { 16361 createGPRPairNode(DAG, N->getOperand(2)), // Compare value 16362 createGPRPairNode(DAG, N->getOperand(3)), // Store value 16363 N->getOperand(1), // Ptr 16364 N->getOperand(0), // Chain in 16365 }; 16366 16367 MachineMemOperand *MemOp = cast<MemSDNode>(N)->getMemOperand(); 16368 16369 unsigned Opcode; 16370 switch (MemOp->getOrdering()) { 16371 case AtomicOrdering::Monotonic: 16372 Opcode = AArch64::CASPX; 16373 break; 16374 case AtomicOrdering::Acquire: 16375 Opcode = AArch64::CASPAX; 16376 break; 16377 case AtomicOrdering::Release: 16378 Opcode = AArch64::CASPLX; 16379 break; 16380 case AtomicOrdering::AcquireRelease: 16381 case AtomicOrdering::SequentiallyConsistent: 16382 Opcode = AArch64::CASPALX; 16383 break; 16384 default: 16385 llvm_unreachable("Unexpected ordering!"); 16386 } 16387 16388 MachineSDNode *CmpSwap = DAG.getMachineNode( 16389 Opcode, SDLoc(N), DAG.getVTList(MVT::Untyped, MVT::Other), Ops); 16390 DAG.setNodeMemRefs(CmpSwap, {MemOp}); 16391 16392 unsigned SubReg1 = AArch64::sube64, SubReg2 = AArch64::subo64; 16393 if (DAG.getDataLayout().isBigEndian()) 16394 std::swap(SubReg1, SubReg2); 16395 SDValue Lo = DAG.getTargetExtractSubreg(SubReg1, SDLoc(N), MVT::i64, 16396 SDValue(CmpSwap, 0)); 16397 SDValue Hi = DAG.getTargetExtractSubreg(SubReg2, SDLoc(N), MVT::i64, 16398 SDValue(CmpSwap, 0)); 16399 Results.push_back( 16400 DAG.getNode(ISD::BUILD_PAIR, SDLoc(N), MVT::i128, Lo, Hi)); 16401 Results.push_back(SDValue(CmpSwap, 1)); // Chain out 16402 return; 16403 } 16404 16405 auto Desired = splitInt128(N->getOperand(2), DAG); 16406 auto New = splitInt128(N->getOperand(3), DAG); 16407 SDValue Ops[] = {N->getOperand(1), Desired.first, Desired.second, 16408 New.first, New.second, N->getOperand(0)}; 16409 SDNode *CmpSwap = DAG.getMachineNode( 16410 AArch64::CMP_SWAP_128, SDLoc(N), 16411 DAG.getVTList(MVT::i64, MVT::i64, MVT::i32, MVT::Other), Ops); 16412 16413 MachineMemOperand *MemOp = cast<MemSDNode>(N)->getMemOperand(); 16414 DAG.setNodeMemRefs(cast<MachineSDNode>(CmpSwap), {MemOp}); 16415 16416 Results.push_back(DAG.getNode(ISD::BUILD_PAIR, SDLoc(N), MVT::i128, 16417 SDValue(CmpSwap, 0), SDValue(CmpSwap, 1))); 16418 Results.push_back(SDValue(CmpSwap, 3)); 16419 } 16420 16421 void AArch64TargetLowering::ReplaceNodeResults( 16422 SDNode *N, SmallVectorImpl<SDValue> &Results, SelectionDAG &DAG) const { 16423 switch (N->getOpcode()) { 16424 default: 16425 llvm_unreachable("Don't know how to custom expand this"); 16426 case ISD::BITCAST: 16427 ReplaceBITCASTResults(N, Results, DAG); 16428 return; 16429 case ISD::VECREDUCE_ADD: 16430 case ISD::VECREDUCE_SMAX: 16431 case ISD::VECREDUCE_SMIN: 16432 case ISD::VECREDUCE_UMAX: 16433 case ISD::VECREDUCE_UMIN: 16434 Results.push_back(LowerVECREDUCE(SDValue(N, 0), DAG)); 16435 return; 16436 16437 case ISD::CTPOP: 16438 if (SDValue Result = LowerCTPOP(SDValue(N, 0), DAG)) 16439 Results.push_back(Result); 16440 return; 16441 case AArch64ISD::SADDV: 16442 ReplaceReductionResults(N, Results, DAG, ISD::ADD, AArch64ISD::SADDV); 16443 return; 16444 case AArch64ISD::UADDV: 16445 ReplaceReductionResults(N, Results, DAG, ISD::ADD, AArch64ISD::UADDV); 16446 return; 16447 case AArch64ISD::SMINV: 16448 ReplaceReductionResults(N, Results, DAG, ISD::SMIN, AArch64ISD::SMINV); 16449 return; 16450 case AArch64ISD::UMINV: 16451 ReplaceReductionResults(N, Results, DAG, ISD::UMIN, AArch64ISD::UMINV); 16452 return; 16453 case AArch64ISD::SMAXV: 16454 ReplaceReductionResults(N, Results, DAG, ISD::SMAX, AArch64ISD::SMAXV); 16455 return; 16456 case AArch64ISD::UMAXV: 16457 ReplaceReductionResults(N, Results, DAG, ISD::UMAX, AArch64ISD::UMAXV); 16458 return; 16459 case ISD::FP_TO_UINT: 16460 case ISD::FP_TO_SINT: 16461 assert(N->getValueType(0) == MVT::i128 && "unexpected illegal conversion"); 16462 // Let normal code take care of it by not adding anything to Results. 16463 return; 16464 case ISD::ATOMIC_CMP_SWAP: 16465 ReplaceCMP_SWAP_128Results(N, Results, DAG, Subtarget); 16466 return; 16467 case ISD::LOAD: { 16468 assert(SDValue(N, 0).getValueType() == MVT::i128 && 16469 "unexpected load's value type"); 16470 LoadSDNode *LoadNode = cast<LoadSDNode>(N); 16471 if (!LoadNode->isVolatile() || LoadNode->getMemoryVT() != MVT::i128) { 16472 // Non-volatile loads are optimized later in AArch64's load/store 16473 // optimizer. 16474 return; 16475 } 16476 16477 SDValue Result = DAG.getMemIntrinsicNode( 16478 AArch64ISD::LDP, SDLoc(N), 16479 DAG.getVTList({MVT::i64, MVT::i64, MVT::Other}), 16480 {LoadNode->getChain(), LoadNode->getBasePtr()}, LoadNode->getMemoryVT(), 16481 LoadNode->getMemOperand()); 16482 16483 SDValue Pair = DAG.getNode(ISD::BUILD_PAIR, SDLoc(N), MVT::i128, 16484 Result.getValue(0), Result.getValue(1)); 16485 Results.append({Pair, Result.getValue(2) /* Chain */}); 16486 return; 16487 } 16488 case ISD::EXTRACT_SUBVECTOR: 16489 ReplaceExtractSubVectorResults(N, Results, DAG); 16490 return; 16491 case ISD::INTRINSIC_WO_CHAIN: { 16492 EVT VT = N->getValueType(0); 16493 assert((VT == MVT::i8 || VT == MVT::i16) && 16494 "custom lowering for unexpected type"); 16495 16496 ConstantSDNode *CN = cast<ConstantSDNode>(N->getOperand(0)); 16497 Intrinsic::ID IntID = static_cast<Intrinsic::ID>(CN->getZExtValue()); 16498 switch (IntID) { 16499 default: 16500 return; 16501 case Intrinsic::aarch64_sve_clasta_n: { 16502 SDLoc DL(N); 16503 auto Op2 = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i32, N->getOperand(2)); 16504 auto V = DAG.getNode(AArch64ISD::CLASTA_N, DL, MVT::i32, 16505 N->getOperand(1), Op2, N->getOperand(3)); 16506 Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, VT, V)); 16507 return; 16508 } 16509 case Intrinsic::aarch64_sve_clastb_n: { 16510 SDLoc DL(N); 16511 auto Op2 = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i32, N->getOperand(2)); 16512 auto V = DAG.getNode(AArch64ISD::CLASTB_N, DL, MVT::i32, 16513 N->getOperand(1), Op2, N->getOperand(3)); 16514 Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, VT, V)); 16515 return; 16516 } 16517 case Intrinsic::aarch64_sve_lasta: { 16518 SDLoc DL(N); 16519 auto V = DAG.getNode(AArch64ISD::LASTA, DL, MVT::i32, 16520 N->getOperand(1), N->getOperand(2)); 16521 Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, VT, V)); 16522 return; 16523 } 16524 case Intrinsic::aarch64_sve_lastb: { 16525 SDLoc DL(N); 16526 auto V = DAG.getNode(AArch64ISD::LASTB, DL, MVT::i32, 16527 N->getOperand(1), N->getOperand(2)); 16528 Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, VT, V)); 16529 return; 16530 } 16531 } 16532 } 16533 } 16534 } 16535 16536 bool AArch64TargetLowering::useLoadStackGuardNode() const { 16537 if (Subtarget->isTargetAndroid() || Subtarget->isTargetFuchsia()) 16538 return TargetLowering::useLoadStackGuardNode(); 16539 return true; 16540 } 16541 16542 unsigned AArch64TargetLowering::combineRepeatedFPDivisors() const { 16543 // Combine multiple FDIVs with the same divisor into multiple FMULs by the 16544 // reciprocal if there are three or more FDIVs. 16545 return 3; 16546 } 16547 16548 TargetLoweringBase::LegalizeTypeAction 16549 AArch64TargetLowering::getPreferredVectorAction(MVT VT) const { 16550 // During type legalization, we prefer to widen v1i8, v1i16, v1i32 to v8i8, 16551 // v4i16, v2i32 instead of to promote. 16552 if (VT == MVT::v1i8 || VT == MVT::v1i16 || VT == MVT::v1i32 || 16553 VT == MVT::v1f32) 16554 return TypeWidenVector; 16555 16556 return TargetLoweringBase::getPreferredVectorAction(VT); 16557 } 16558 16559 // Loads and stores less than 128-bits are already atomic; ones above that 16560 // are doomed anyway, so defer to the default libcall and blame the OS when 16561 // things go wrong. 16562 bool AArch64TargetLowering::shouldExpandAtomicStoreInIR(StoreInst *SI) const { 16563 unsigned Size = SI->getValueOperand()->getType()->getPrimitiveSizeInBits(); 16564 return Size == 128; 16565 } 16566 16567 // Loads and stores less than 128-bits are already atomic; ones above that 16568 // are doomed anyway, so defer to the default libcall and blame the OS when 16569 // things go wrong. 16570 TargetLowering::AtomicExpansionKind 16571 AArch64TargetLowering::shouldExpandAtomicLoadInIR(LoadInst *LI) const { 16572 unsigned Size = LI->getType()->getPrimitiveSizeInBits(); 16573 return Size == 128 ? AtomicExpansionKind::LLSC : AtomicExpansionKind::None; 16574 } 16575 16576 // For the real atomic operations, we have ldxr/stxr up to 128 bits, 16577 TargetLowering::AtomicExpansionKind 16578 AArch64TargetLowering::shouldExpandAtomicRMWInIR(AtomicRMWInst *AI) const { 16579 if (AI->isFloatingPointOperation()) 16580 return AtomicExpansionKind::CmpXChg; 16581 16582 unsigned Size = AI->getType()->getPrimitiveSizeInBits(); 16583 if (Size > 128) return AtomicExpansionKind::None; 16584 // Nand not supported in LSE. 16585 if (AI->getOperation() == AtomicRMWInst::Nand) return AtomicExpansionKind::LLSC; 16586 // Leave 128 bits to LLSC. 16587 if (Subtarget->hasLSE() && Size < 128) 16588 return AtomicExpansionKind::None; 16589 if (Subtarget->outlineAtomics() && Size < 128) { 16590 // [U]Min/[U]Max RWM atomics are used in __sync_fetch_ libcalls so far. 16591 // Don't outline them unless 16592 // (1) high level <atomic> support approved: 16593 // http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2020/p0493r1.pdf 16594 // (2) low level libgcc and compiler-rt support implemented by: 16595 // min/max outline atomics helpers 16596 if (AI->getOperation() != AtomicRMWInst::Min && 16597 AI->getOperation() != AtomicRMWInst::Max && 16598 AI->getOperation() != AtomicRMWInst::UMin && 16599 AI->getOperation() != AtomicRMWInst::UMax) { 16600 return AtomicExpansionKind::None; 16601 } 16602 } 16603 return AtomicExpansionKind::LLSC; 16604 } 16605 16606 TargetLowering::AtomicExpansionKind 16607 AArch64TargetLowering::shouldExpandAtomicCmpXchgInIR( 16608 AtomicCmpXchgInst *AI) const { 16609 // If subtarget has LSE, leave cmpxchg intact for codegen. 16610 if (Subtarget->hasLSE() || Subtarget->outlineAtomics()) 16611 return AtomicExpansionKind::None; 16612 // At -O0, fast-regalloc cannot cope with the live vregs necessary to 16613 // implement cmpxchg without spilling. If the address being exchanged is also 16614 // on the stack and close enough to the spill slot, this can lead to a 16615 // situation where the monitor always gets cleared and the atomic operation 16616 // can never succeed. So at -O0 we need a late-expanded pseudo-inst instead. 16617 if (getTargetMachine().getOptLevel() == CodeGenOpt::None) 16618 return AtomicExpansionKind::None; 16619 return AtomicExpansionKind::LLSC; 16620 } 16621 16622 Value *AArch64TargetLowering::emitLoadLinked(IRBuilder<> &Builder, Value *Addr, 16623 AtomicOrdering Ord) const { 16624 Module *M = Builder.GetInsertBlock()->getParent()->getParent(); 16625 Type *ValTy = cast<PointerType>(Addr->getType())->getElementType(); 16626 bool IsAcquire = isAcquireOrStronger(Ord); 16627 16628 // Since i128 isn't legal and intrinsics don't get type-lowered, the ldrexd 16629 // intrinsic must return {i64, i64} and we have to recombine them into a 16630 // single i128 here. 16631 if (ValTy->getPrimitiveSizeInBits() == 128) { 16632 Intrinsic::ID Int = 16633 IsAcquire ? Intrinsic::aarch64_ldaxp : Intrinsic::aarch64_ldxp; 16634 Function *Ldxr = Intrinsic::getDeclaration(M, Int); 16635 16636 Addr = Builder.CreateBitCast(Addr, Type::getInt8PtrTy(M->getContext())); 16637 Value *LoHi = Builder.CreateCall(Ldxr, Addr, "lohi"); 16638 16639 Value *Lo = Builder.CreateExtractValue(LoHi, 0, "lo"); 16640 Value *Hi = Builder.CreateExtractValue(LoHi, 1, "hi"); 16641 Lo = Builder.CreateZExt(Lo, ValTy, "lo64"); 16642 Hi = Builder.CreateZExt(Hi, ValTy, "hi64"); 16643 return Builder.CreateOr( 16644 Lo, Builder.CreateShl(Hi, ConstantInt::get(ValTy, 64)), "val64"); 16645 } 16646 16647 Type *Tys[] = { Addr->getType() }; 16648 Intrinsic::ID Int = 16649 IsAcquire ? Intrinsic::aarch64_ldaxr : Intrinsic::aarch64_ldxr; 16650 Function *Ldxr = Intrinsic::getDeclaration(M, Int, Tys); 16651 16652 Type *EltTy = cast<PointerType>(Addr->getType())->getElementType(); 16653 16654 const DataLayout &DL = M->getDataLayout(); 16655 IntegerType *IntEltTy = Builder.getIntNTy(DL.getTypeSizeInBits(EltTy)); 16656 Value *Trunc = Builder.CreateTrunc(Builder.CreateCall(Ldxr, Addr), IntEltTy); 16657 16658 return Builder.CreateBitCast(Trunc, EltTy); 16659 } 16660 16661 void AArch64TargetLowering::emitAtomicCmpXchgNoStoreLLBalance( 16662 IRBuilder<> &Builder) const { 16663 Module *M = Builder.GetInsertBlock()->getParent()->getParent(); 16664 Builder.CreateCall(Intrinsic::getDeclaration(M, Intrinsic::aarch64_clrex)); 16665 } 16666 16667 Value *AArch64TargetLowering::emitStoreConditional(IRBuilder<> &Builder, 16668 Value *Val, Value *Addr, 16669 AtomicOrdering Ord) const { 16670 Module *M = Builder.GetInsertBlock()->getParent()->getParent(); 16671 bool IsRelease = isReleaseOrStronger(Ord); 16672 16673 // Since the intrinsics must have legal type, the i128 intrinsics take two 16674 // parameters: "i64, i64". We must marshal Val into the appropriate form 16675 // before the call. 16676 if (Val->getType()->getPrimitiveSizeInBits() == 128) { 16677 Intrinsic::ID Int = 16678 IsRelease ? Intrinsic::aarch64_stlxp : Intrinsic::aarch64_stxp; 16679 Function *Stxr = Intrinsic::getDeclaration(M, Int); 16680 Type *Int64Ty = Type::getInt64Ty(M->getContext()); 16681 16682 Value *Lo = Builder.CreateTrunc(Val, Int64Ty, "lo"); 16683 Value *Hi = Builder.CreateTrunc(Builder.CreateLShr(Val, 64), Int64Ty, "hi"); 16684 Addr = Builder.CreateBitCast(Addr, Type::getInt8PtrTy(M->getContext())); 16685 return Builder.CreateCall(Stxr, {Lo, Hi, Addr}); 16686 } 16687 16688 Intrinsic::ID Int = 16689 IsRelease ? Intrinsic::aarch64_stlxr : Intrinsic::aarch64_stxr; 16690 Type *Tys[] = { Addr->getType() }; 16691 Function *Stxr = Intrinsic::getDeclaration(M, Int, Tys); 16692 16693 const DataLayout &DL = M->getDataLayout(); 16694 IntegerType *IntValTy = Builder.getIntNTy(DL.getTypeSizeInBits(Val->getType())); 16695 Val = Builder.CreateBitCast(Val, IntValTy); 16696 16697 return Builder.CreateCall(Stxr, 16698 {Builder.CreateZExtOrBitCast( 16699 Val, Stxr->getFunctionType()->getParamType(0)), 16700 Addr}); 16701 } 16702 16703 bool AArch64TargetLowering::functionArgumentNeedsConsecutiveRegisters( 16704 Type *Ty, CallingConv::ID CallConv, bool isVarArg) const { 16705 if (Ty->isArrayTy()) 16706 return true; 16707 16708 const TypeSize &TySize = Ty->getPrimitiveSizeInBits(); 16709 if (TySize.isScalable() && TySize.getKnownMinSize() > 128) 16710 return true; 16711 16712 return false; 16713 } 16714 16715 bool AArch64TargetLowering::shouldNormalizeToSelectSequence(LLVMContext &, 16716 EVT) const { 16717 return false; 16718 } 16719 16720 static Value *UseTlsOffset(IRBuilder<> &IRB, unsigned Offset) { 16721 Module *M = IRB.GetInsertBlock()->getParent()->getParent(); 16722 Function *ThreadPointerFunc = 16723 Intrinsic::getDeclaration(M, Intrinsic::thread_pointer); 16724 return IRB.CreatePointerCast( 16725 IRB.CreateConstGEP1_32(IRB.getInt8Ty(), IRB.CreateCall(ThreadPointerFunc), 16726 Offset), 16727 IRB.getInt8PtrTy()->getPointerTo(0)); 16728 } 16729 16730 Value *AArch64TargetLowering::getIRStackGuard(IRBuilder<> &IRB) const { 16731 // Android provides a fixed TLS slot for the stack cookie. See the definition 16732 // of TLS_SLOT_STACK_GUARD in 16733 // https://android.googlesource.com/platform/bionic/+/master/libc/private/bionic_tls.h 16734 if (Subtarget->isTargetAndroid()) 16735 return UseTlsOffset(IRB, 0x28); 16736 16737 // Fuchsia is similar. 16738 // <zircon/tls.h> defines ZX_TLS_STACK_GUARD_OFFSET with this value. 16739 if (Subtarget->isTargetFuchsia()) 16740 return UseTlsOffset(IRB, -0x10); 16741 16742 return TargetLowering::getIRStackGuard(IRB); 16743 } 16744 16745 void AArch64TargetLowering::insertSSPDeclarations(Module &M) const { 16746 // MSVC CRT provides functionalities for stack protection. 16747 if (Subtarget->getTargetTriple().isWindowsMSVCEnvironment()) { 16748 // MSVC CRT has a global variable holding security cookie. 16749 M.getOrInsertGlobal("__security_cookie", 16750 Type::getInt8PtrTy(M.getContext())); 16751 16752 // MSVC CRT has a function to validate security cookie. 16753 FunctionCallee SecurityCheckCookie = M.getOrInsertFunction( 16754 "__security_check_cookie", Type::getVoidTy(M.getContext()), 16755 Type::getInt8PtrTy(M.getContext())); 16756 if (Function *F = dyn_cast<Function>(SecurityCheckCookie.getCallee())) { 16757 F->setCallingConv(CallingConv::Win64); 16758 F->addAttribute(1, Attribute::AttrKind::InReg); 16759 } 16760 return; 16761 } 16762 TargetLowering::insertSSPDeclarations(M); 16763 } 16764 16765 Value *AArch64TargetLowering::getSDagStackGuard(const Module &M) const { 16766 // MSVC CRT has a global variable holding security cookie. 16767 if (Subtarget->getTargetTriple().isWindowsMSVCEnvironment()) 16768 return M.getGlobalVariable("__security_cookie"); 16769 return TargetLowering::getSDagStackGuard(M); 16770 } 16771 16772 Function *AArch64TargetLowering::getSSPStackGuardCheck(const Module &M) const { 16773 // MSVC CRT has a function to validate security cookie. 16774 if (Subtarget->getTargetTriple().isWindowsMSVCEnvironment()) 16775 return M.getFunction("__security_check_cookie"); 16776 return TargetLowering::getSSPStackGuardCheck(M); 16777 } 16778 16779 Value *AArch64TargetLowering::getSafeStackPointerLocation(IRBuilder<> &IRB) const { 16780 // Android provides a fixed TLS slot for the SafeStack pointer. See the 16781 // definition of TLS_SLOT_SAFESTACK in 16782 // https://android.googlesource.com/platform/bionic/+/master/libc/private/bionic_tls.h 16783 if (Subtarget->isTargetAndroid()) 16784 return UseTlsOffset(IRB, 0x48); 16785 16786 // Fuchsia is similar. 16787 // <zircon/tls.h> defines ZX_TLS_UNSAFE_SP_OFFSET with this value. 16788 if (Subtarget->isTargetFuchsia()) 16789 return UseTlsOffset(IRB, -0x8); 16790 16791 return TargetLowering::getSafeStackPointerLocation(IRB); 16792 } 16793 16794 bool AArch64TargetLowering::isMaskAndCmp0FoldingBeneficial( 16795 const Instruction &AndI) const { 16796 // Only sink 'and' mask to cmp use block if it is masking a single bit, since 16797 // this is likely to be fold the and/cmp/br into a single tbz instruction. It 16798 // may be beneficial to sink in other cases, but we would have to check that 16799 // the cmp would not get folded into the br to form a cbz for these to be 16800 // beneficial. 16801 ConstantInt* Mask = dyn_cast<ConstantInt>(AndI.getOperand(1)); 16802 if (!Mask) 16803 return false; 16804 return Mask->getValue().isPowerOf2(); 16805 } 16806 16807 bool AArch64TargetLowering:: 16808 shouldProduceAndByConstByHoistingConstFromShiftsLHSOfAnd( 16809 SDValue X, ConstantSDNode *XC, ConstantSDNode *CC, SDValue Y, 16810 unsigned OldShiftOpcode, unsigned NewShiftOpcode, 16811 SelectionDAG &DAG) const { 16812 // Does baseline recommend not to perform the fold by default? 16813 if (!TargetLowering::shouldProduceAndByConstByHoistingConstFromShiftsLHSOfAnd( 16814 X, XC, CC, Y, OldShiftOpcode, NewShiftOpcode, DAG)) 16815 return false; 16816 // Else, if this is a vector shift, prefer 'shl'. 16817 return X.getValueType().isScalarInteger() || NewShiftOpcode == ISD::SHL; 16818 } 16819 16820 bool AArch64TargetLowering::shouldExpandShift(SelectionDAG &DAG, 16821 SDNode *N) const { 16822 if (DAG.getMachineFunction().getFunction().hasMinSize() && 16823 !Subtarget->isTargetWindows() && !Subtarget->isTargetDarwin()) 16824 return false; 16825 return true; 16826 } 16827 16828 void AArch64TargetLowering::initializeSplitCSR(MachineBasicBlock *Entry) const { 16829 // Update IsSplitCSR in AArch64unctionInfo. 16830 AArch64FunctionInfo *AFI = Entry->getParent()->getInfo<AArch64FunctionInfo>(); 16831 AFI->setIsSplitCSR(true); 16832 } 16833 16834 void AArch64TargetLowering::insertCopiesSplitCSR( 16835 MachineBasicBlock *Entry, 16836 const SmallVectorImpl<MachineBasicBlock *> &Exits) const { 16837 const AArch64RegisterInfo *TRI = Subtarget->getRegisterInfo(); 16838 const MCPhysReg *IStart = TRI->getCalleeSavedRegsViaCopy(Entry->getParent()); 16839 if (!IStart) 16840 return; 16841 16842 const TargetInstrInfo *TII = Subtarget->getInstrInfo(); 16843 MachineRegisterInfo *MRI = &Entry->getParent()->getRegInfo(); 16844 MachineBasicBlock::iterator MBBI = Entry->begin(); 16845 for (const MCPhysReg *I = IStart; *I; ++I) { 16846 const TargetRegisterClass *RC = nullptr; 16847 if (AArch64::GPR64RegClass.contains(*I)) 16848 RC = &AArch64::GPR64RegClass; 16849 else if (AArch64::FPR64RegClass.contains(*I)) 16850 RC = &AArch64::FPR64RegClass; 16851 else 16852 llvm_unreachable("Unexpected register class in CSRsViaCopy!"); 16853 16854 Register NewVR = MRI->createVirtualRegister(RC); 16855 // Create copy from CSR to a virtual register. 16856 // FIXME: this currently does not emit CFI pseudo-instructions, it works 16857 // fine for CXX_FAST_TLS since the C++-style TLS access functions should be 16858 // nounwind. If we want to generalize this later, we may need to emit 16859 // CFI pseudo-instructions. 16860 assert(Entry->getParent()->getFunction().hasFnAttribute( 16861 Attribute::NoUnwind) && 16862 "Function should be nounwind in insertCopiesSplitCSR!"); 16863 Entry->addLiveIn(*I); 16864 BuildMI(*Entry, MBBI, DebugLoc(), TII->get(TargetOpcode::COPY), NewVR) 16865 .addReg(*I); 16866 16867 // Insert the copy-back instructions right before the terminator. 16868 for (auto *Exit : Exits) 16869 BuildMI(*Exit, Exit->getFirstTerminator(), DebugLoc(), 16870 TII->get(TargetOpcode::COPY), *I) 16871 .addReg(NewVR); 16872 } 16873 } 16874 16875 bool AArch64TargetLowering::isIntDivCheap(EVT VT, AttributeList Attr) const { 16876 // Integer division on AArch64 is expensive. However, when aggressively 16877 // optimizing for code size, we prefer to use a div instruction, as it is 16878 // usually smaller than the alternative sequence. 16879 // The exception to this is vector division. Since AArch64 doesn't have vector 16880 // integer division, leaving the division as-is is a loss even in terms of 16881 // size, because it will have to be scalarized, while the alternative code 16882 // sequence can be performed in vector form. 16883 bool OptSize = Attr.hasFnAttribute(Attribute::MinSize); 16884 return OptSize && !VT.isVector(); 16885 } 16886 16887 bool AArch64TargetLowering::preferIncOfAddToSubOfNot(EVT VT) const { 16888 // We want inc-of-add for scalars and sub-of-not for vectors. 16889 return VT.isScalarInteger(); 16890 } 16891 16892 bool AArch64TargetLowering::enableAggressiveFMAFusion(EVT VT) const { 16893 return Subtarget->hasAggressiveFMA() && VT.isFloatingPoint(); 16894 } 16895 16896 unsigned 16897 AArch64TargetLowering::getVaListSizeInBits(const DataLayout &DL) const { 16898 if (Subtarget->isTargetDarwin() || Subtarget->isTargetWindows()) 16899 return getPointerTy(DL).getSizeInBits(); 16900 16901 return 3 * getPointerTy(DL).getSizeInBits() + 2 * 32; 16902 } 16903 16904 void AArch64TargetLowering::finalizeLowering(MachineFunction &MF) const { 16905 MF.getFrameInfo().computeMaxCallFrameSize(MF); 16906 TargetLoweringBase::finalizeLowering(MF); 16907 } 16908 16909 // Unlike X86, we let frame lowering assign offsets to all catch objects. 16910 bool AArch64TargetLowering::needsFixedCatchObjects() const { 16911 return false; 16912 } 16913 16914 bool AArch64TargetLowering::shouldLocalize( 16915 const MachineInstr &MI, const TargetTransformInfo *TTI) const { 16916 switch (MI.getOpcode()) { 16917 case TargetOpcode::G_GLOBAL_VALUE: { 16918 // On Darwin, TLS global vars get selected into function calls, which 16919 // we don't want localized, as they can get moved into the middle of a 16920 // another call sequence. 16921 const GlobalValue &GV = *MI.getOperand(1).getGlobal(); 16922 if (GV.isThreadLocal() && Subtarget->isTargetMachO()) 16923 return false; 16924 break; 16925 } 16926 // If we legalized G_GLOBAL_VALUE into ADRP + G_ADD_LOW, mark both as being 16927 // localizable. 16928 case AArch64::ADRP: 16929 case AArch64::G_ADD_LOW: 16930 return true; 16931 default: 16932 break; 16933 } 16934 return TargetLoweringBase::shouldLocalize(MI, TTI); 16935 } 16936 16937 bool AArch64TargetLowering::fallBackToDAGISel(const Instruction &Inst) const { 16938 if (isa<ScalableVectorType>(Inst.getType())) 16939 return true; 16940 16941 for (unsigned i = 0; i < Inst.getNumOperands(); ++i) 16942 if (isa<ScalableVectorType>(Inst.getOperand(i)->getType())) 16943 return true; 16944 16945 if (const AllocaInst *AI = dyn_cast<AllocaInst>(&Inst)) { 16946 if (isa<ScalableVectorType>(AI->getAllocatedType())) 16947 return true; 16948 } 16949 16950 return false; 16951 } 16952 16953 // Return the largest legal scalable vector type that matches VT's element type. 16954 static EVT getContainerForFixedLengthVector(SelectionDAG &DAG, EVT VT) { 16955 assert(VT.isFixedLengthVector() && 16956 DAG.getTargetLoweringInfo().isTypeLegal(VT) && 16957 "Expected legal fixed length vector!"); 16958 switch (VT.getVectorElementType().getSimpleVT().SimpleTy) { 16959 default: 16960 llvm_unreachable("unexpected element type for SVE container"); 16961 case MVT::i8: 16962 return EVT(MVT::nxv16i8); 16963 case MVT::i16: 16964 return EVT(MVT::nxv8i16); 16965 case MVT::i32: 16966 return EVT(MVT::nxv4i32); 16967 case MVT::i64: 16968 return EVT(MVT::nxv2i64); 16969 case MVT::f16: 16970 return EVT(MVT::nxv8f16); 16971 case MVT::f32: 16972 return EVT(MVT::nxv4f32); 16973 case MVT::f64: 16974 return EVT(MVT::nxv2f64); 16975 } 16976 } 16977 16978 // Return a PTRUE with active lanes corresponding to the extent of VT. 16979 static SDValue getPredicateForFixedLengthVector(SelectionDAG &DAG, SDLoc &DL, 16980 EVT VT) { 16981 assert(VT.isFixedLengthVector() && 16982 DAG.getTargetLoweringInfo().isTypeLegal(VT) && 16983 "Expected legal fixed length vector!"); 16984 16985 int PgPattern; 16986 switch (VT.getVectorNumElements()) { 16987 default: 16988 llvm_unreachable("unexpected element count for SVE predicate"); 16989 case 1: 16990 PgPattern = AArch64SVEPredPattern::vl1; 16991 break; 16992 case 2: 16993 PgPattern = AArch64SVEPredPattern::vl2; 16994 break; 16995 case 4: 16996 PgPattern = AArch64SVEPredPattern::vl4; 16997 break; 16998 case 8: 16999 PgPattern = AArch64SVEPredPattern::vl8; 17000 break; 17001 case 16: 17002 PgPattern = AArch64SVEPredPattern::vl16; 17003 break; 17004 case 32: 17005 PgPattern = AArch64SVEPredPattern::vl32; 17006 break; 17007 case 64: 17008 PgPattern = AArch64SVEPredPattern::vl64; 17009 break; 17010 case 128: 17011 PgPattern = AArch64SVEPredPattern::vl128; 17012 break; 17013 case 256: 17014 PgPattern = AArch64SVEPredPattern::vl256; 17015 break; 17016 } 17017 17018 // TODO: For vectors that are exactly getMaxSVEVectorSizeInBits big, we can 17019 // use AArch64SVEPredPattern::all, which can enable the use of unpredicated 17020 // variants of instructions when available. 17021 17022 MVT MaskVT; 17023 switch (VT.getVectorElementType().getSimpleVT().SimpleTy) { 17024 default: 17025 llvm_unreachable("unexpected element type for SVE predicate"); 17026 case MVT::i8: 17027 MaskVT = MVT::nxv16i1; 17028 break; 17029 case MVT::i16: 17030 case MVT::f16: 17031 MaskVT = MVT::nxv8i1; 17032 break; 17033 case MVT::i32: 17034 case MVT::f32: 17035 MaskVT = MVT::nxv4i1; 17036 break; 17037 case MVT::i64: 17038 case MVT::f64: 17039 MaskVT = MVT::nxv2i1; 17040 break; 17041 } 17042 17043 return DAG.getNode(AArch64ISD::PTRUE, DL, MaskVT, 17044 DAG.getTargetConstant(PgPattern, DL, MVT::i64)); 17045 } 17046 17047 static SDValue getPredicateForScalableVector(SelectionDAG &DAG, SDLoc &DL, 17048 EVT VT) { 17049 assert(VT.isScalableVector() && DAG.getTargetLoweringInfo().isTypeLegal(VT) && 17050 "Expected legal scalable vector!"); 17051 auto PredTy = VT.changeVectorElementType(MVT::i1); 17052 return getPTrue(DAG, DL, PredTy, AArch64SVEPredPattern::all); 17053 } 17054 17055 static SDValue getPredicateForVector(SelectionDAG &DAG, SDLoc &DL, EVT VT) { 17056 if (VT.isFixedLengthVector()) 17057 return getPredicateForFixedLengthVector(DAG, DL, VT); 17058 17059 return getPredicateForScalableVector(DAG, DL, VT); 17060 } 17061 17062 // Grow V to consume an entire SVE register. 17063 static SDValue convertToScalableVector(SelectionDAG &DAG, EVT VT, SDValue V) { 17064 assert(VT.isScalableVector() && 17065 "Expected to convert into a scalable vector!"); 17066 assert(V.getValueType().isFixedLengthVector() && 17067 "Expected a fixed length vector operand!"); 17068 SDLoc DL(V); 17069 SDValue Zero = DAG.getConstant(0, DL, MVT::i64); 17070 return DAG.getNode(ISD::INSERT_SUBVECTOR, DL, VT, DAG.getUNDEF(VT), V, Zero); 17071 } 17072 17073 // Shrink V so it's just big enough to maintain a VT's worth of data. 17074 static SDValue convertFromScalableVector(SelectionDAG &DAG, EVT VT, SDValue V) { 17075 assert(VT.isFixedLengthVector() && 17076 "Expected to convert into a fixed length vector!"); 17077 assert(V.getValueType().isScalableVector() && 17078 "Expected a scalable vector operand!"); 17079 SDLoc DL(V); 17080 SDValue Zero = DAG.getConstant(0, DL, MVT::i64); 17081 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, V, Zero); 17082 } 17083 17084 // Convert all fixed length vector loads larger than NEON to masked_loads. 17085 SDValue AArch64TargetLowering::LowerFixedLengthVectorLoadToSVE( 17086 SDValue Op, SelectionDAG &DAG) const { 17087 auto Load = cast<LoadSDNode>(Op); 17088 17089 SDLoc DL(Op); 17090 EVT VT = Op.getValueType(); 17091 EVT ContainerVT = getContainerForFixedLengthVector(DAG, VT); 17092 17093 auto NewLoad = DAG.getMaskedLoad( 17094 ContainerVT, DL, Load->getChain(), Load->getBasePtr(), Load->getOffset(), 17095 getPredicateForFixedLengthVector(DAG, DL, VT), DAG.getUNDEF(ContainerVT), 17096 Load->getMemoryVT(), Load->getMemOperand(), Load->getAddressingMode(), 17097 Load->getExtensionType()); 17098 17099 auto Result = convertFromScalableVector(DAG, VT, NewLoad); 17100 SDValue MergedValues[2] = {Result, Load->getChain()}; 17101 return DAG.getMergeValues(MergedValues, DL); 17102 } 17103 17104 // Convert all fixed length vector stores larger than NEON to masked_stores. 17105 SDValue AArch64TargetLowering::LowerFixedLengthVectorStoreToSVE( 17106 SDValue Op, SelectionDAG &DAG) const { 17107 auto Store = cast<StoreSDNode>(Op); 17108 17109 SDLoc DL(Op); 17110 EVT VT = Store->getValue().getValueType(); 17111 EVT ContainerVT = getContainerForFixedLengthVector(DAG, VT); 17112 17113 auto NewValue = convertToScalableVector(DAG, ContainerVT, Store->getValue()); 17114 return DAG.getMaskedStore( 17115 Store->getChain(), DL, NewValue, Store->getBasePtr(), Store->getOffset(), 17116 getPredicateForFixedLengthVector(DAG, DL, VT), Store->getMemoryVT(), 17117 Store->getMemOperand(), Store->getAddressingMode(), 17118 Store->isTruncatingStore()); 17119 } 17120 17121 SDValue AArch64TargetLowering::LowerFixedLengthVectorIntDivideToSVE( 17122 SDValue Op, SelectionDAG &DAG) const { 17123 SDLoc dl(Op); 17124 EVT VT = Op.getValueType(); 17125 EVT EltVT = VT.getVectorElementType(); 17126 17127 bool Signed = Op.getOpcode() == ISD::SDIV; 17128 unsigned PredOpcode = Signed ? AArch64ISD::SDIV_PRED : AArch64ISD::UDIV_PRED; 17129 17130 // Scalable vector i32/i64 DIV is supported. 17131 if (EltVT == MVT::i32 || EltVT == MVT::i64) 17132 return LowerToPredicatedOp(Op, DAG, PredOpcode, /*OverrideNEON=*/true); 17133 17134 // Scalable vector i8/i16 DIV is not supported. Promote it to i32. 17135 EVT ContainerVT = getContainerForFixedLengthVector(DAG, VT); 17136 EVT HalfVT = VT.getHalfNumVectorElementsVT(*DAG.getContext()); 17137 EVT FixedWidenedVT = HalfVT.widenIntegerVectorElementType(*DAG.getContext()); 17138 EVT ScalableWidenedVT = getContainerForFixedLengthVector(DAG, FixedWidenedVT); 17139 17140 // Convert the operands to scalable vectors. 17141 SDValue Op0 = convertToScalableVector(DAG, ContainerVT, Op.getOperand(0)); 17142 SDValue Op1 = convertToScalableVector(DAG, ContainerVT, Op.getOperand(1)); 17143 17144 // Extend the scalable operands. 17145 unsigned UnpkLo = Signed ? AArch64ISD::SUNPKLO : AArch64ISD::UUNPKLO; 17146 unsigned UnpkHi = Signed ? AArch64ISD::SUNPKHI : AArch64ISD::UUNPKHI; 17147 SDValue Op0Lo = DAG.getNode(UnpkLo, dl, ScalableWidenedVT, Op0); 17148 SDValue Op1Lo = DAG.getNode(UnpkLo, dl, ScalableWidenedVT, Op1); 17149 SDValue Op0Hi = DAG.getNode(UnpkHi, dl, ScalableWidenedVT, Op0); 17150 SDValue Op1Hi = DAG.getNode(UnpkHi, dl, ScalableWidenedVT, Op1); 17151 17152 // Convert back to fixed vectors so the DIV can be further lowered. 17153 Op0Lo = convertFromScalableVector(DAG, FixedWidenedVT, Op0Lo); 17154 Op1Lo = convertFromScalableVector(DAG, FixedWidenedVT, Op1Lo); 17155 Op0Hi = convertFromScalableVector(DAG, FixedWidenedVT, Op0Hi); 17156 Op1Hi = convertFromScalableVector(DAG, FixedWidenedVT, Op1Hi); 17157 SDValue ResultLo = DAG.getNode(Op.getOpcode(), dl, FixedWidenedVT, 17158 Op0Lo, Op1Lo); 17159 SDValue ResultHi = DAG.getNode(Op.getOpcode(), dl, FixedWidenedVT, 17160 Op0Hi, Op1Hi); 17161 17162 // Convert again to scalable vectors to truncate. 17163 ResultLo = convertToScalableVector(DAG, ScalableWidenedVT, ResultLo); 17164 ResultHi = convertToScalableVector(DAG, ScalableWidenedVT, ResultHi); 17165 SDValue ScalableResult = DAG.getNode(AArch64ISD::UZP1, dl, ContainerVT, 17166 ResultLo, ResultHi); 17167 17168 return convertFromScalableVector(DAG, VT, ScalableResult); 17169 } 17170 17171 SDValue AArch64TargetLowering::LowerFixedLengthVectorIntExtendToSVE( 17172 SDValue Op, SelectionDAG &DAG) const { 17173 EVT VT = Op.getValueType(); 17174 assert(VT.isFixedLengthVector() && "Expected fixed length vector type!"); 17175 17176 SDLoc DL(Op); 17177 SDValue Val = Op.getOperand(0); 17178 EVT ContainerVT = getContainerForFixedLengthVector(DAG, Val.getValueType()); 17179 Val = convertToScalableVector(DAG, ContainerVT, Val); 17180 17181 bool Signed = Op.getOpcode() == ISD::SIGN_EXTEND; 17182 unsigned ExtendOpc = Signed ? AArch64ISD::SUNPKLO : AArch64ISD::UUNPKLO; 17183 17184 // Repeatedly unpack Val until the result is of the desired element type. 17185 switch (ContainerVT.getSimpleVT().SimpleTy) { 17186 default: 17187 llvm_unreachable("unimplemented container type"); 17188 case MVT::nxv16i8: 17189 Val = DAG.getNode(ExtendOpc, DL, MVT::nxv8i16, Val); 17190 if (VT.getVectorElementType() == MVT::i16) 17191 break; 17192 LLVM_FALLTHROUGH; 17193 case MVT::nxv8i16: 17194 Val = DAG.getNode(ExtendOpc, DL, MVT::nxv4i32, Val); 17195 if (VT.getVectorElementType() == MVT::i32) 17196 break; 17197 LLVM_FALLTHROUGH; 17198 case MVT::nxv4i32: 17199 Val = DAG.getNode(ExtendOpc, DL, MVT::nxv2i64, Val); 17200 assert(VT.getVectorElementType() == MVT::i64 && "Unexpected element type!"); 17201 break; 17202 } 17203 17204 return convertFromScalableVector(DAG, VT, Val); 17205 } 17206 17207 SDValue AArch64TargetLowering::LowerFixedLengthVectorTruncateToSVE( 17208 SDValue Op, SelectionDAG &DAG) const { 17209 EVT VT = Op.getValueType(); 17210 assert(VT.isFixedLengthVector() && "Expected fixed length vector type!"); 17211 17212 SDLoc DL(Op); 17213 SDValue Val = Op.getOperand(0); 17214 EVT ContainerVT = getContainerForFixedLengthVector(DAG, Val.getValueType()); 17215 Val = convertToScalableVector(DAG, ContainerVT, Val); 17216 17217 // Repeatedly truncate Val until the result is of the desired element type. 17218 switch (ContainerVT.getSimpleVT().SimpleTy) { 17219 default: 17220 llvm_unreachable("unimplemented container type"); 17221 case MVT::nxv2i64: 17222 Val = DAG.getNode(ISD::BITCAST, DL, MVT::nxv4i32, Val); 17223 Val = DAG.getNode(AArch64ISD::UZP1, DL, MVT::nxv4i32, Val, Val); 17224 if (VT.getVectorElementType() == MVT::i32) 17225 break; 17226 LLVM_FALLTHROUGH; 17227 case MVT::nxv4i32: 17228 Val = DAG.getNode(ISD::BITCAST, DL, MVT::nxv8i16, Val); 17229 Val = DAG.getNode(AArch64ISD::UZP1, DL, MVT::nxv8i16, Val, Val); 17230 if (VT.getVectorElementType() == MVT::i16) 17231 break; 17232 LLVM_FALLTHROUGH; 17233 case MVT::nxv8i16: 17234 Val = DAG.getNode(ISD::BITCAST, DL, MVT::nxv16i8, Val); 17235 Val = DAG.getNode(AArch64ISD::UZP1, DL, MVT::nxv16i8, Val, Val); 17236 assert(VT.getVectorElementType() == MVT::i8 && "Unexpected element type!"); 17237 break; 17238 } 17239 17240 return convertFromScalableVector(DAG, VT, Val); 17241 } 17242 17243 SDValue AArch64TargetLowering::LowerFixedLengthExtractVectorElt( 17244 SDValue Op, SelectionDAG &DAG) const { 17245 EVT VT = Op.getValueType(); 17246 EVT InVT = Op.getOperand(0).getValueType(); 17247 assert(InVT.isFixedLengthVector() && "Expected fixed length vector type!"); 17248 17249 SDLoc DL(Op); 17250 EVT ContainerVT = getContainerForFixedLengthVector(DAG, InVT); 17251 SDValue Op0 = convertToScalableVector(DAG, ContainerVT, Op->getOperand(0)); 17252 17253 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, VT, Op0, Op.getOperand(1)); 17254 } 17255 17256 SDValue AArch64TargetLowering::LowerFixedLengthInsertVectorElt( 17257 SDValue Op, SelectionDAG &DAG) const { 17258 EVT VT = Op.getValueType(); 17259 assert(VT.isFixedLengthVector() && "Expected fixed length vector type!"); 17260 17261 SDLoc DL(Op); 17262 EVT InVT = Op.getOperand(0).getValueType(); 17263 EVT ContainerVT = getContainerForFixedLengthVector(DAG, InVT); 17264 SDValue Op0 = convertToScalableVector(DAG, ContainerVT, Op->getOperand(0)); 17265 17266 auto ScalableRes = DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, ContainerVT, Op0, 17267 Op.getOperand(1), Op.getOperand(2)); 17268 17269 return convertFromScalableVector(DAG, VT, ScalableRes); 17270 } 17271 17272 // Convert vector operation 'Op' to an equivalent predicated operation whereby 17273 // the original operation's type is used to construct a suitable predicate. 17274 // NOTE: The results for inactive lanes are undefined. 17275 SDValue AArch64TargetLowering::LowerToPredicatedOp(SDValue Op, 17276 SelectionDAG &DAG, 17277 unsigned NewOp, 17278 bool OverrideNEON) const { 17279 EVT VT = Op.getValueType(); 17280 SDLoc DL(Op); 17281 auto Pg = getPredicateForVector(DAG, DL, VT); 17282 17283 if (useSVEForFixedLengthVectorVT(VT, OverrideNEON)) { 17284 EVT ContainerVT = getContainerForFixedLengthVector(DAG, VT); 17285 17286 // Create list of operands by converting existing ones to scalable types. 17287 SmallVector<SDValue, 4> Operands = {Pg}; 17288 for (const SDValue &V : Op->op_values()) { 17289 if (isa<CondCodeSDNode>(V)) { 17290 Operands.push_back(V); 17291 continue; 17292 } 17293 17294 if (const VTSDNode *VTNode = dyn_cast<VTSDNode>(V)) { 17295 EVT VTArg = VTNode->getVT().getVectorElementType(); 17296 EVT NewVTArg = ContainerVT.changeVectorElementType(VTArg); 17297 Operands.push_back(DAG.getValueType(NewVTArg)); 17298 continue; 17299 } 17300 17301 assert(useSVEForFixedLengthVectorVT(V.getValueType(), OverrideNEON) && 17302 "Only fixed length vectors are supported!"); 17303 Operands.push_back(convertToScalableVector(DAG, ContainerVT, V)); 17304 } 17305 17306 if (isMergePassthruOpcode(NewOp)) 17307 Operands.push_back(DAG.getUNDEF(ContainerVT)); 17308 17309 auto ScalableRes = DAG.getNode(NewOp, DL, ContainerVT, Operands); 17310 return convertFromScalableVector(DAG, VT, ScalableRes); 17311 } 17312 17313 assert(VT.isScalableVector() && "Only expect to lower scalable vector op!"); 17314 17315 SmallVector<SDValue, 4> Operands = {Pg}; 17316 for (const SDValue &V : Op->op_values()) { 17317 assert((!V.getValueType().isVector() || 17318 V.getValueType().isScalableVector()) && 17319 "Only scalable vectors are supported!"); 17320 Operands.push_back(V); 17321 } 17322 17323 if (isMergePassthruOpcode(NewOp)) 17324 Operands.push_back(DAG.getUNDEF(VT)); 17325 17326 return DAG.getNode(NewOp, DL, VT, Operands); 17327 } 17328 17329 // If a fixed length vector operation has no side effects when applied to 17330 // undefined elements, we can safely use scalable vectors to perform the same 17331 // operation without needing to worry about predication. 17332 SDValue AArch64TargetLowering::LowerToScalableOp(SDValue Op, 17333 SelectionDAG &DAG) const { 17334 EVT VT = Op.getValueType(); 17335 assert(useSVEForFixedLengthVectorVT(VT) && 17336 "Only expected to lower fixed length vector operation!"); 17337 EVT ContainerVT = getContainerForFixedLengthVector(DAG, VT); 17338 17339 // Create list of operands by converting existing ones to scalable types. 17340 SmallVector<SDValue, 4> Ops; 17341 for (const SDValue &V : Op->op_values()) { 17342 assert(!isa<VTSDNode>(V) && "Unexpected VTSDNode node!"); 17343 17344 // Pass through non-vector operands. 17345 if (!V.getValueType().isVector()) { 17346 Ops.push_back(V); 17347 continue; 17348 } 17349 17350 // "cast" fixed length vector to a scalable vector. 17351 assert(useSVEForFixedLengthVectorVT(V.getValueType()) && 17352 "Only fixed length vectors are supported!"); 17353 Ops.push_back(convertToScalableVector(DAG, ContainerVT, V)); 17354 } 17355 17356 auto ScalableRes = DAG.getNode(Op.getOpcode(), SDLoc(Op), ContainerVT, Ops); 17357 return convertFromScalableVector(DAG, VT, ScalableRes); 17358 } 17359 17360 SDValue AArch64TargetLowering::LowerVECREDUCE_SEQ_FADD(SDValue ScalarOp, 17361 SelectionDAG &DAG) const { 17362 SDLoc DL(ScalarOp); 17363 SDValue AccOp = ScalarOp.getOperand(0); 17364 SDValue VecOp = ScalarOp.getOperand(1); 17365 EVT SrcVT = VecOp.getValueType(); 17366 EVT ResVT = SrcVT.getVectorElementType(); 17367 17368 EVT ContainerVT = SrcVT; 17369 if (SrcVT.isFixedLengthVector()) { 17370 ContainerVT = getContainerForFixedLengthVector(DAG, SrcVT); 17371 VecOp = convertToScalableVector(DAG, ContainerVT, VecOp); 17372 } 17373 17374 SDValue Pg = getPredicateForVector(DAG, DL, SrcVT); 17375 SDValue Zero = DAG.getConstant(0, DL, MVT::i64); 17376 17377 // Convert operands to Scalable. 17378 AccOp = DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, ContainerVT, 17379 DAG.getUNDEF(ContainerVT), AccOp, Zero); 17380 17381 // Perform reduction. 17382 SDValue Rdx = DAG.getNode(AArch64ISD::FADDA_PRED, DL, ContainerVT, 17383 Pg, AccOp, VecOp); 17384 17385 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, ResVT, Rdx, Zero); 17386 } 17387 17388 SDValue AArch64TargetLowering::LowerPredReductionToSVE(SDValue ReduceOp, 17389 SelectionDAG &DAG) const { 17390 SDLoc DL(ReduceOp); 17391 SDValue Op = ReduceOp.getOperand(0); 17392 EVT OpVT = Op.getValueType(); 17393 EVT VT = ReduceOp.getValueType(); 17394 17395 if (!OpVT.isScalableVector() || OpVT.getVectorElementType() != MVT::i1) 17396 return SDValue(); 17397 17398 SDValue Pg = getPredicateForVector(DAG, DL, OpVT); 17399 17400 switch (ReduceOp.getOpcode()) { 17401 default: 17402 return SDValue(); 17403 case ISD::VECREDUCE_OR: 17404 return getPTest(DAG, VT, Pg, Op, AArch64CC::ANY_ACTIVE); 17405 case ISD::VECREDUCE_AND: { 17406 Op = DAG.getNode(ISD::XOR, DL, OpVT, Op, Pg); 17407 return getPTest(DAG, VT, Pg, Op, AArch64CC::NONE_ACTIVE); 17408 } 17409 case ISD::VECREDUCE_XOR: { 17410 SDValue ID = 17411 DAG.getTargetConstant(Intrinsic::aarch64_sve_cntp, DL, MVT::i64); 17412 SDValue Cntp = 17413 DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, MVT::i64, ID, Pg, Op); 17414 return DAG.getAnyExtOrTrunc(Cntp, DL, VT); 17415 } 17416 } 17417 17418 return SDValue(); 17419 } 17420 17421 SDValue AArch64TargetLowering::LowerReductionToSVE(unsigned Opcode, 17422 SDValue ScalarOp, 17423 SelectionDAG &DAG) const { 17424 SDLoc DL(ScalarOp); 17425 SDValue VecOp = ScalarOp.getOperand(0); 17426 EVT SrcVT = VecOp.getValueType(); 17427 17428 if (useSVEForFixedLengthVectorVT(SrcVT, true)) { 17429 EVT ContainerVT = getContainerForFixedLengthVector(DAG, SrcVT); 17430 VecOp = convertToScalableVector(DAG, ContainerVT, VecOp); 17431 } 17432 17433 // UADDV always returns an i64 result. 17434 EVT ResVT = (Opcode == AArch64ISD::UADDV_PRED) ? MVT::i64 : 17435 SrcVT.getVectorElementType(); 17436 EVT RdxVT = SrcVT; 17437 if (SrcVT.isFixedLengthVector() || Opcode == AArch64ISD::UADDV_PRED) 17438 RdxVT = getPackedSVEVectorVT(ResVT); 17439 17440 SDValue Pg = getPredicateForVector(DAG, DL, SrcVT); 17441 SDValue Rdx = DAG.getNode(Opcode, DL, RdxVT, Pg, VecOp); 17442 SDValue Res = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, ResVT, 17443 Rdx, DAG.getConstant(0, DL, MVT::i64)); 17444 17445 // The VEC_REDUCE nodes expect an element size result. 17446 if (ResVT != ScalarOp.getValueType()) 17447 Res = DAG.getAnyExtOrTrunc(Res, DL, ScalarOp.getValueType()); 17448 17449 return Res; 17450 } 17451 17452 SDValue 17453 AArch64TargetLowering::LowerFixedLengthVectorSelectToSVE(SDValue Op, 17454 SelectionDAG &DAG) const { 17455 EVT VT = Op.getValueType(); 17456 SDLoc DL(Op); 17457 17458 EVT InVT = Op.getOperand(1).getValueType(); 17459 EVT ContainerVT = getContainerForFixedLengthVector(DAG, InVT); 17460 SDValue Op1 = convertToScalableVector(DAG, ContainerVT, Op->getOperand(1)); 17461 SDValue Op2 = convertToScalableVector(DAG, ContainerVT, Op->getOperand(2)); 17462 17463 // Convert the mask to a predicated (NOTE: We don't need to worry about 17464 // inactive lanes since VSELECT is safe when given undefined elements). 17465 EVT MaskVT = Op.getOperand(0).getValueType(); 17466 EVT MaskContainerVT = getContainerForFixedLengthVector(DAG, MaskVT); 17467 auto Mask = convertToScalableVector(DAG, MaskContainerVT, Op.getOperand(0)); 17468 Mask = DAG.getNode(ISD::TRUNCATE, DL, 17469 MaskContainerVT.changeVectorElementType(MVT::i1), Mask); 17470 17471 auto ScalableRes = DAG.getNode(ISD::VSELECT, DL, ContainerVT, 17472 Mask, Op1, Op2); 17473 17474 return convertFromScalableVector(DAG, VT, ScalableRes); 17475 } 17476 17477 SDValue AArch64TargetLowering::LowerFixedLengthVectorSetccToSVE( 17478 SDValue Op, SelectionDAG &DAG) const { 17479 SDLoc DL(Op); 17480 EVT InVT = Op.getOperand(0).getValueType(); 17481 EVT ContainerVT = getContainerForFixedLengthVector(DAG, InVT); 17482 17483 assert(useSVEForFixedLengthVectorVT(InVT) && 17484 "Only expected to lower fixed length vector operation!"); 17485 assert(Op.getValueType() == InVT.changeTypeToInteger() && 17486 "Expected integer result of the same bit length as the inputs!"); 17487 17488 auto Op1 = convertToScalableVector(DAG, ContainerVT, Op.getOperand(0)); 17489 auto Op2 = convertToScalableVector(DAG, ContainerVT, Op.getOperand(1)); 17490 auto Pg = getPredicateForFixedLengthVector(DAG, DL, InVT); 17491 17492 EVT CmpVT = Pg.getValueType(); 17493 auto Cmp = DAG.getNode(AArch64ISD::SETCC_MERGE_ZERO, DL, CmpVT, 17494 {Pg, Op1, Op2, Op.getOperand(2)}); 17495 17496 EVT PromoteVT = ContainerVT.changeTypeToInteger(); 17497 auto Promote = DAG.getBoolExtOrTrunc(Cmp, DL, PromoteVT, InVT); 17498 return convertFromScalableVector(DAG, Op.getValueType(), Promote); 17499 } 17500 17501 SDValue AArch64TargetLowering::getSVESafeBitCast(EVT VT, SDValue Op, 17502 SelectionDAG &DAG) const { 17503 SDLoc DL(Op); 17504 EVT InVT = Op.getValueType(); 17505 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 17506 (void)TLI; 17507 17508 assert(VT.isScalableVector() && TLI.isTypeLegal(VT) && 17509 InVT.isScalableVector() && TLI.isTypeLegal(InVT) && 17510 "Only expect to cast between legal scalable vector types!"); 17511 assert((VT.getVectorElementType() == MVT::i1) == 17512 (InVT.getVectorElementType() == MVT::i1) && 17513 "Cannot cast between data and predicate scalable vector types!"); 17514 17515 if (InVT == VT) 17516 return Op; 17517 17518 if (VT.getVectorElementType() == MVT::i1) 17519 return DAG.getNode(AArch64ISD::REINTERPRET_CAST, DL, VT, Op); 17520 17521 EVT PackedVT = getPackedSVEVectorVT(VT.getVectorElementType()); 17522 EVT PackedInVT = getPackedSVEVectorVT(InVT.getVectorElementType()); 17523 assert((VT == PackedVT || InVT == PackedInVT) && 17524 "Cannot cast between unpacked scalable vector types!"); 17525 17526 // Pack input if required. 17527 if (InVT != PackedInVT) 17528 Op = DAG.getNode(AArch64ISD::REINTERPRET_CAST, DL, PackedInVT, Op); 17529 17530 Op = DAG.getNode(ISD::BITCAST, DL, PackedVT, Op); 17531 17532 // Unpack result if required. 17533 if (VT != PackedVT) 17534 Op = DAG.getNode(AArch64ISD::REINTERPRET_CAST, DL, VT, Op); 17535 17536 return Op; 17537 } 17538