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/VectorUtils.h" 33 #include "llvm/CodeGen/CallingConvLower.h" 34 #include "llvm/CodeGen/MachineBasicBlock.h" 35 #include "llvm/CodeGen/MachineFrameInfo.h" 36 #include "llvm/CodeGen/MachineFunction.h" 37 #include "llvm/CodeGen/MachineInstr.h" 38 #include "llvm/CodeGen/MachineInstrBuilder.h" 39 #include "llvm/CodeGen/MachineMemOperand.h" 40 #include "llvm/CodeGen/MachineRegisterInfo.h" 41 #include "llvm/CodeGen/RuntimeLibcalls.h" 42 #include "llvm/CodeGen/SelectionDAG.h" 43 #include "llvm/CodeGen/SelectionDAGNodes.h" 44 #include "llvm/CodeGen/TargetCallingConv.h" 45 #include "llvm/CodeGen/TargetInstrInfo.h" 46 #include "llvm/CodeGen/ValueTypes.h" 47 #include "llvm/IR/Attributes.h" 48 #include "llvm/IR/Constants.h" 49 #include "llvm/IR/DataLayout.h" 50 #include "llvm/IR/DebugLoc.h" 51 #include "llvm/IR/DerivedTypes.h" 52 #include "llvm/IR/Function.h" 53 #include "llvm/IR/GetElementPtrTypeIterator.h" 54 #include "llvm/IR/GlobalValue.h" 55 #include "llvm/IR/IRBuilder.h" 56 #include "llvm/IR/Instruction.h" 57 #include "llvm/IR/Instructions.h" 58 #include "llvm/IR/IntrinsicInst.h" 59 #include "llvm/IR/Intrinsics.h" 60 #include "llvm/IR/IntrinsicsAArch64.h" 61 #include "llvm/IR/Module.h" 62 #include "llvm/IR/OperandTraits.h" 63 #include "llvm/IR/PatternMatch.h" 64 #include "llvm/IR/Type.h" 65 #include "llvm/IR/Use.h" 66 #include "llvm/IR/Value.h" 67 #include "llvm/MC/MCRegisterInfo.h" 68 #include "llvm/Support/Casting.h" 69 #include "llvm/Support/CodeGen.h" 70 #include "llvm/Support/CommandLine.h" 71 #include "llvm/Support/Compiler.h" 72 #include "llvm/Support/Debug.h" 73 #include "llvm/Support/ErrorHandling.h" 74 #include "llvm/Support/KnownBits.h" 75 #include "llvm/Support/MachineValueType.h" 76 #include "llvm/Support/MathExtras.h" 77 #include "llvm/Support/raw_ostream.h" 78 #include "llvm/Target/TargetMachine.h" 79 #include "llvm/Target/TargetOptions.h" 80 #include <algorithm> 81 #include <bitset> 82 #include <cassert> 83 #include <cctype> 84 #include <cstdint> 85 #include <cstdlib> 86 #include <iterator> 87 #include <limits> 88 #include <tuple> 89 #include <utility> 90 #include <vector> 91 92 using namespace llvm; 93 using namespace llvm::PatternMatch; 94 95 #define DEBUG_TYPE "aarch64-lower" 96 97 STATISTIC(NumTailCalls, "Number of tail calls"); 98 STATISTIC(NumShiftInserts, "Number of vector shift inserts"); 99 STATISTIC(NumOptimizedImms, "Number of times immediates were optimized"); 100 101 // FIXME: The necessary dtprel relocations don't seem to be supported 102 // well in the GNU bfd and gold linkers at the moment. Therefore, by 103 // default, for now, fall back to GeneralDynamic code generation. 104 cl::opt<bool> EnableAArch64ELFLocalDynamicTLSGeneration( 105 "aarch64-elf-ldtls-generation", cl::Hidden, 106 cl::desc("Allow AArch64 Local Dynamic TLS code generation"), 107 cl::init(false)); 108 109 static cl::opt<bool> 110 EnableOptimizeLogicalImm("aarch64-enable-logical-imm", cl::Hidden, 111 cl::desc("Enable AArch64 logical imm instruction " 112 "optimization"), 113 cl::init(true)); 114 115 // Temporary option added for the purpose of testing functionality added 116 // to DAGCombiner.cpp in D92230. It is expected that this can be removed 117 // in future when both implementations will be based off MGATHER rather 118 // than the GLD1 nodes added for the SVE gather load intrinsics. 119 static cl::opt<bool> 120 EnableCombineMGatherIntrinsics("aarch64-enable-mgather-combine", cl::Hidden, 121 cl::desc("Combine extends of AArch64 masked " 122 "gather intrinsics"), 123 cl::init(true)); 124 125 /// Value type used for condition codes. 126 static const MVT MVT_CC = MVT::i32; 127 128 static inline EVT getPackedSVEVectorVT(EVT VT) { 129 switch (VT.getSimpleVT().SimpleTy) { 130 default: 131 llvm_unreachable("unexpected element type for vector"); 132 case MVT::i8: 133 return MVT::nxv16i8; 134 case MVT::i16: 135 return MVT::nxv8i16; 136 case MVT::i32: 137 return MVT::nxv4i32; 138 case MVT::i64: 139 return MVT::nxv2i64; 140 case MVT::f16: 141 return MVT::nxv8f16; 142 case MVT::f32: 143 return MVT::nxv4f32; 144 case MVT::f64: 145 return MVT::nxv2f64; 146 case MVT::bf16: 147 return MVT::nxv8bf16; 148 } 149 } 150 151 // NOTE: Currently there's only a need to return integer vector types. If this 152 // changes then just add an extra "type" parameter. 153 static inline EVT getPackedSVEVectorVT(ElementCount EC) { 154 switch (EC.getKnownMinValue()) { 155 default: 156 llvm_unreachable("unexpected element count for vector"); 157 case 16: 158 return MVT::nxv16i8; 159 case 8: 160 return MVT::nxv8i16; 161 case 4: 162 return MVT::nxv4i32; 163 case 2: 164 return MVT::nxv2i64; 165 } 166 } 167 168 static inline EVT getPromotedVTForPredicate(EVT VT) { 169 assert(VT.isScalableVector() && (VT.getVectorElementType() == MVT::i1) && 170 "Expected scalable predicate vector type!"); 171 switch (VT.getVectorMinNumElements()) { 172 default: 173 llvm_unreachable("unexpected element count for vector"); 174 case 2: 175 return MVT::nxv2i64; 176 case 4: 177 return MVT::nxv4i32; 178 case 8: 179 return MVT::nxv8i16; 180 case 16: 181 return MVT::nxv16i8; 182 } 183 } 184 185 /// Returns true if VT's elements occupy the lowest bit positions of its 186 /// associated register class without any intervening space. 187 /// 188 /// For example, nxv2f16, nxv4f16 and nxv8f16 are legal types that belong to the 189 /// same register class, but only nxv8f16 can be treated as a packed vector. 190 static inline bool isPackedVectorType(EVT VT, SelectionDAG &DAG) { 191 assert(VT.isVector() && DAG.getTargetLoweringInfo().isTypeLegal(VT) && 192 "Expected legal vector type!"); 193 return VT.isFixedLengthVector() || 194 VT.getSizeInBits().getKnownMinSize() == AArch64::SVEBitsPerBlock; 195 } 196 197 // Returns true for ####_MERGE_PASSTHRU opcodes, whose operands have a leading 198 // predicate and end with a passthru value matching the result type. 199 static bool isMergePassthruOpcode(unsigned Opc) { 200 switch (Opc) { 201 default: 202 return false; 203 case AArch64ISD::BITREVERSE_MERGE_PASSTHRU: 204 case AArch64ISD::BSWAP_MERGE_PASSTHRU: 205 case AArch64ISD::CTLZ_MERGE_PASSTHRU: 206 case AArch64ISD::CTPOP_MERGE_PASSTHRU: 207 case AArch64ISD::DUP_MERGE_PASSTHRU: 208 case AArch64ISD::ABS_MERGE_PASSTHRU: 209 case AArch64ISD::NEG_MERGE_PASSTHRU: 210 case AArch64ISD::FNEG_MERGE_PASSTHRU: 211 case AArch64ISD::SIGN_EXTEND_INREG_MERGE_PASSTHRU: 212 case AArch64ISD::ZERO_EXTEND_INREG_MERGE_PASSTHRU: 213 case AArch64ISD::FCEIL_MERGE_PASSTHRU: 214 case AArch64ISD::FFLOOR_MERGE_PASSTHRU: 215 case AArch64ISD::FNEARBYINT_MERGE_PASSTHRU: 216 case AArch64ISD::FRINT_MERGE_PASSTHRU: 217 case AArch64ISD::FROUND_MERGE_PASSTHRU: 218 case AArch64ISD::FROUNDEVEN_MERGE_PASSTHRU: 219 case AArch64ISD::FTRUNC_MERGE_PASSTHRU: 220 case AArch64ISD::FP_ROUND_MERGE_PASSTHRU: 221 case AArch64ISD::FP_EXTEND_MERGE_PASSTHRU: 222 case AArch64ISD::SINT_TO_FP_MERGE_PASSTHRU: 223 case AArch64ISD::UINT_TO_FP_MERGE_PASSTHRU: 224 case AArch64ISD::FCVTZU_MERGE_PASSTHRU: 225 case AArch64ISD::FCVTZS_MERGE_PASSTHRU: 226 case AArch64ISD::FSQRT_MERGE_PASSTHRU: 227 case AArch64ISD::FRECPX_MERGE_PASSTHRU: 228 case AArch64ISD::FABS_MERGE_PASSTHRU: 229 return true; 230 } 231 } 232 233 AArch64TargetLowering::AArch64TargetLowering(const TargetMachine &TM, 234 const AArch64Subtarget &STI) 235 : TargetLowering(TM), Subtarget(&STI) { 236 // AArch64 doesn't have comparisons which set GPRs or setcc instructions, so 237 // we have to make something up. Arbitrarily, choose ZeroOrOne. 238 setBooleanContents(ZeroOrOneBooleanContent); 239 // When comparing vectors the result sets the different elements in the 240 // vector to all-one or all-zero. 241 setBooleanVectorContents(ZeroOrNegativeOneBooleanContent); 242 243 // Set up the register classes. 244 addRegisterClass(MVT::i32, &AArch64::GPR32allRegClass); 245 addRegisterClass(MVT::i64, &AArch64::GPR64allRegClass); 246 247 if (Subtarget->hasFPARMv8()) { 248 addRegisterClass(MVT::f16, &AArch64::FPR16RegClass); 249 addRegisterClass(MVT::bf16, &AArch64::FPR16RegClass); 250 addRegisterClass(MVT::f32, &AArch64::FPR32RegClass); 251 addRegisterClass(MVT::f64, &AArch64::FPR64RegClass); 252 addRegisterClass(MVT::f128, &AArch64::FPR128RegClass); 253 } 254 255 if (Subtarget->hasNEON()) { 256 addRegisterClass(MVT::v16i8, &AArch64::FPR8RegClass); 257 addRegisterClass(MVT::v8i16, &AArch64::FPR16RegClass); 258 // Someone set us up the NEON. 259 addDRTypeForNEON(MVT::v2f32); 260 addDRTypeForNEON(MVT::v8i8); 261 addDRTypeForNEON(MVT::v4i16); 262 addDRTypeForNEON(MVT::v2i32); 263 addDRTypeForNEON(MVT::v1i64); 264 addDRTypeForNEON(MVT::v1f64); 265 addDRTypeForNEON(MVT::v4f16); 266 if (Subtarget->hasBF16()) 267 addDRTypeForNEON(MVT::v4bf16); 268 269 addQRTypeForNEON(MVT::v4f32); 270 addQRTypeForNEON(MVT::v2f64); 271 addQRTypeForNEON(MVT::v16i8); 272 addQRTypeForNEON(MVT::v8i16); 273 addQRTypeForNEON(MVT::v4i32); 274 addQRTypeForNEON(MVT::v2i64); 275 addQRTypeForNEON(MVT::v8f16); 276 if (Subtarget->hasBF16()) 277 addQRTypeForNEON(MVT::v8bf16); 278 } 279 280 if (Subtarget->hasSVE()) { 281 // Add legal sve predicate types 282 addRegisterClass(MVT::nxv2i1, &AArch64::PPRRegClass); 283 addRegisterClass(MVT::nxv4i1, &AArch64::PPRRegClass); 284 addRegisterClass(MVT::nxv8i1, &AArch64::PPRRegClass); 285 addRegisterClass(MVT::nxv16i1, &AArch64::PPRRegClass); 286 287 // Add legal sve data types 288 addRegisterClass(MVT::nxv16i8, &AArch64::ZPRRegClass); 289 addRegisterClass(MVT::nxv8i16, &AArch64::ZPRRegClass); 290 addRegisterClass(MVT::nxv4i32, &AArch64::ZPRRegClass); 291 addRegisterClass(MVT::nxv2i64, &AArch64::ZPRRegClass); 292 293 addRegisterClass(MVT::nxv2f16, &AArch64::ZPRRegClass); 294 addRegisterClass(MVT::nxv4f16, &AArch64::ZPRRegClass); 295 addRegisterClass(MVT::nxv8f16, &AArch64::ZPRRegClass); 296 addRegisterClass(MVT::nxv2f32, &AArch64::ZPRRegClass); 297 addRegisterClass(MVT::nxv4f32, &AArch64::ZPRRegClass); 298 addRegisterClass(MVT::nxv2f64, &AArch64::ZPRRegClass); 299 300 if (Subtarget->hasBF16()) { 301 addRegisterClass(MVT::nxv2bf16, &AArch64::ZPRRegClass); 302 addRegisterClass(MVT::nxv4bf16, &AArch64::ZPRRegClass); 303 addRegisterClass(MVT::nxv8bf16, &AArch64::ZPRRegClass); 304 } 305 306 if (Subtarget->useSVEForFixedLengthVectors()) { 307 for (MVT VT : MVT::integer_fixedlen_vector_valuetypes()) 308 if (useSVEForFixedLengthVectorVT(VT)) 309 addRegisterClass(VT, &AArch64::ZPRRegClass); 310 311 for (MVT VT : MVT::fp_fixedlen_vector_valuetypes()) 312 if (useSVEForFixedLengthVectorVT(VT)) 313 addRegisterClass(VT, &AArch64::ZPRRegClass); 314 } 315 316 for (auto VT : { MVT::nxv16i8, MVT::nxv8i16, MVT::nxv4i32, MVT::nxv2i64 }) { 317 setOperationAction(ISD::SADDSAT, VT, Legal); 318 setOperationAction(ISD::UADDSAT, VT, Legal); 319 setOperationAction(ISD::SSUBSAT, VT, Legal); 320 setOperationAction(ISD::USUBSAT, VT, Legal); 321 setOperationAction(ISD::UREM, VT, Expand); 322 setOperationAction(ISD::SREM, VT, Expand); 323 setOperationAction(ISD::SDIVREM, VT, Expand); 324 setOperationAction(ISD::UDIVREM, VT, Expand); 325 } 326 327 for (auto VT : 328 { MVT::nxv2i8, MVT::nxv2i16, MVT::nxv2i32, MVT::nxv2i64, MVT::nxv4i8, 329 MVT::nxv4i16, MVT::nxv4i32, MVT::nxv8i8, MVT::nxv8i16 }) 330 setOperationAction(ISD::SIGN_EXTEND_INREG, VT, Legal); 331 332 for (auto VT : 333 { MVT::nxv2f16, MVT::nxv4f16, MVT::nxv8f16, MVT::nxv2f32, MVT::nxv4f32, 334 MVT::nxv2f64 }) { 335 setCondCodeAction(ISD::SETO, VT, Expand); 336 setCondCodeAction(ISD::SETOLT, VT, Expand); 337 setCondCodeAction(ISD::SETLT, VT, Expand); 338 setCondCodeAction(ISD::SETOLE, VT, Expand); 339 setCondCodeAction(ISD::SETLE, VT, Expand); 340 setCondCodeAction(ISD::SETULT, VT, Expand); 341 setCondCodeAction(ISD::SETULE, VT, Expand); 342 setCondCodeAction(ISD::SETUGE, VT, Expand); 343 setCondCodeAction(ISD::SETUGT, VT, Expand); 344 setCondCodeAction(ISD::SETUEQ, VT, Expand); 345 setCondCodeAction(ISD::SETUNE, VT, Expand); 346 } 347 } 348 349 // Compute derived properties from the register classes 350 computeRegisterProperties(Subtarget->getRegisterInfo()); 351 352 // Provide all sorts of operation actions 353 setOperationAction(ISD::GlobalAddress, MVT::i64, Custom); 354 setOperationAction(ISD::GlobalTLSAddress, MVT::i64, Custom); 355 setOperationAction(ISD::SETCC, MVT::i32, Custom); 356 setOperationAction(ISD::SETCC, MVT::i64, Custom); 357 setOperationAction(ISD::SETCC, MVT::f16, Custom); 358 setOperationAction(ISD::SETCC, MVT::f32, Custom); 359 setOperationAction(ISD::SETCC, MVT::f64, Custom); 360 setOperationAction(ISD::STRICT_FSETCC, MVT::f16, Custom); 361 setOperationAction(ISD::STRICT_FSETCC, MVT::f32, Custom); 362 setOperationAction(ISD::STRICT_FSETCC, MVT::f64, Custom); 363 setOperationAction(ISD::STRICT_FSETCCS, MVT::f16, Custom); 364 setOperationAction(ISD::STRICT_FSETCCS, MVT::f32, Custom); 365 setOperationAction(ISD::STRICT_FSETCCS, MVT::f64, Custom); 366 setOperationAction(ISD::BITREVERSE, MVT::i32, Legal); 367 setOperationAction(ISD::BITREVERSE, MVT::i64, Legal); 368 setOperationAction(ISD::BRCOND, MVT::Other, Expand); 369 setOperationAction(ISD::BR_CC, MVT::i32, Custom); 370 setOperationAction(ISD::BR_CC, MVT::i64, Custom); 371 setOperationAction(ISD::BR_CC, MVT::f16, Custom); 372 setOperationAction(ISD::BR_CC, MVT::f32, Custom); 373 setOperationAction(ISD::BR_CC, MVT::f64, Custom); 374 setOperationAction(ISD::SELECT, MVT::i32, Custom); 375 setOperationAction(ISD::SELECT, MVT::i64, Custom); 376 setOperationAction(ISD::SELECT, MVT::f16, Custom); 377 setOperationAction(ISD::SELECT, MVT::f32, Custom); 378 setOperationAction(ISD::SELECT, MVT::f64, Custom); 379 setOperationAction(ISD::SELECT_CC, MVT::i32, Custom); 380 setOperationAction(ISD::SELECT_CC, MVT::i64, Custom); 381 setOperationAction(ISD::SELECT_CC, MVT::f16, Custom); 382 setOperationAction(ISD::SELECT_CC, MVT::f32, Custom); 383 setOperationAction(ISD::SELECT_CC, MVT::f64, Custom); 384 setOperationAction(ISD::BR_JT, MVT::Other, Custom); 385 setOperationAction(ISD::JumpTable, MVT::i64, Custom); 386 387 setOperationAction(ISD::SHL_PARTS, MVT::i64, Custom); 388 setOperationAction(ISD::SRA_PARTS, MVT::i64, Custom); 389 setOperationAction(ISD::SRL_PARTS, MVT::i64, Custom); 390 391 setOperationAction(ISD::FREM, MVT::f32, Expand); 392 setOperationAction(ISD::FREM, MVT::f64, Expand); 393 setOperationAction(ISD::FREM, MVT::f80, Expand); 394 395 setOperationAction(ISD::BUILD_PAIR, MVT::i64, Expand); 396 397 // Custom lowering hooks are needed for XOR 398 // to fold it into CSINC/CSINV. 399 setOperationAction(ISD::XOR, MVT::i32, Custom); 400 setOperationAction(ISD::XOR, MVT::i64, Custom); 401 402 // Virtually no operation on f128 is legal, but LLVM can't expand them when 403 // there's a valid register class, so we need custom operations in most cases. 404 setOperationAction(ISD::FABS, MVT::f128, Expand); 405 setOperationAction(ISD::FADD, MVT::f128, LibCall); 406 setOperationAction(ISD::FCOPYSIGN, MVT::f128, Expand); 407 setOperationAction(ISD::FCOS, MVT::f128, Expand); 408 setOperationAction(ISD::FDIV, MVT::f128, LibCall); 409 setOperationAction(ISD::FMA, MVT::f128, Expand); 410 setOperationAction(ISD::FMUL, MVT::f128, LibCall); 411 setOperationAction(ISD::FNEG, MVT::f128, Expand); 412 setOperationAction(ISD::FPOW, MVT::f128, Expand); 413 setOperationAction(ISD::FREM, MVT::f128, Expand); 414 setOperationAction(ISD::FRINT, MVT::f128, Expand); 415 setOperationAction(ISD::FSIN, MVT::f128, Expand); 416 setOperationAction(ISD::FSINCOS, MVT::f128, Expand); 417 setOperationAction(ISD::FSQRT, MVT::f128, Expand); 418 setOperationAction(ISD::FSUB, MVT::f128, LibCall); 419 setOperationAction(ISD::FTRUNC, MVT::f128, Expand); 420 setOperationAction(ISD::SETCC, MVT::f128, Custom); 421 setOperationAction(ISD::STRICT_FSETCC, MVT::f128, Custom); 422 setOperationAction(ISD::STRICT_FSETCCS, MVT::f128, Custom); 423 setOperationAction(ISD::BR_CC, MVT::f128, Custom); 424 setOperationAction(ISD::SELECT, MVT::f128, Custom); 425 setOperationAction(ISD::SELECT_CC, MVT::f128, Custom); 426 setOperationAction(ISD::FP_EXTEND, MVT::f128, Custom); 427 428 // Lowering for many of the conversions is actually specified by the non-f128 429 // type. The LowerXXX function will be trivial when f128 isn't involved. 430 setOperationAction(ISD::FP_TO_SINT, MVT::i32, Custom); 431 setOperationAction(ISD::FP_TO_SINT, MVT::i64, Custom); 432 setOperationAction(ISD::FP_TO_SINT, MVT::i128, Custom); 433 setOperationAction(ISD::STRICT_FP_TO_SINT, MVT::i32, Custom); 434 setOperationAction(ISD::STRICT_FP_TO_SINT, MVT::i64, Custom); 435 setOperationAction(ISD::STRICT_FP_TO_SINT, MVT::i128, Custom); 436 setOperationAction(ISD::FP_TO_UINT, MVT::i32, Custom); 437 setOperationAction(ISD::FP_TO_UINT, MVT::i64, Custom); 438 setOperationAction(ISD::FP_TO_UINT, MVT::i128, Custom); 439 setOperationAction(ISD::STRICT_FP_TO_UINT, MVT::i32, Custom); 440 setOperationAction(ISD::STRICT_FP_TO_UINT, MVT::i64, Custom); 441 setOperationAction(ISD::STRICT_FP_TO_UINT, MVT::i128, Custom); 442 setOperationAction(ISD::SINT_TO_FP, MVT::i32, Custom); 443 setOperationAction(ISD::SINT_TO_FP, MVT::i64, Custom); 444 setOperationAction(ISD::SINT_TO_FP, MVT::i128, Custom); 445 setOperationAction(ISD::STRICT_SINT_TO_FP, MVT::i32, Custom); 446 setOperationAction(ISD::STRICT_SINT_TO_FP, MVT::i64, Custom); 447 setOperationAction(ISD::STRICT_SINT_TO_FP, MVT::i128, Custom); 448 setOperationAction(ISD::UINT_TO_FP, MVT::i32, Custom); 449 setOperationAction(ISD::UINT_TO_FP, MVT::i64, Custom); 450 setOperationAction(ISD::UINT_TO_FP, MVT::i128, Custom); 451 setOperationAction(ISD::STRICT_UINT_TO_FP, MVT::i32, Custom); 452 setOperationAction(ISD::STRICT_UINT_TO_FP, MVT::i64, Custom); 453 setOperationAction(ISD::STRICT_UINT_TO_FP, MVT::i128, Custom); 454 setOperationAction(ISD::FP_ROUND, MVT::f16, Custom); 455 setOperationAction(ISD::FP_ROUND, MVT::f32, Custom); 456 setOperationAction(ISD::FP_ROUND, MVT::f64, Custom); 457 setOperationAction(ISD::STRICT_FP_ROUND, MVT::f16, Custom); 458 setOperationAction(ISD::STRICT_FP_ROUND, MVT::f32, Custom); 459 setOperationAction(ISD::STRICT_FP_ROUND, MVT::f64, Custom); 460 461 // Variable arguments. 462 setOperationAction(ISD::VASTART, MVT::Other, Custom); 463 setOperationAction(ISD::VAARG, MVT::Other, Custom); 464 setOperationAction(ISD::VACOPY, MVT::Other, Custom); 465 setOperationAction(ISD::VAEND, MVT::Other, Expand); 466 467 // Variable-sized objects. 468 setOperationAction(ISD::STACKSAVE, MVT::Other, Expand); 469 setOperationAction(ISD::STACKRESTORE, MVT::Other, Expand); 470 471 if (Subtarget->isTargetWindows()) 472 setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i64, Custom); 473 else 474 setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i64, Expand); 475 476 // Constant pool entries 477 setOperationAction(ISD::ConstantPool, MVT::i64, Custom); 478 479 // BlockAddress 480 setOperationAction(ISD::BlockAddress, MVT::i64, Custom); 481 482 // Add/Sub overflow ops with MVT::Glues are lowered to NZCV dependences. 483 setOperationAction(ISD::ADDC, MVT::i32, Custom); 484 setOperationAction(ISD::ADDE, MVT::i32, Custom); 485 setOperationAction(ISD::SUBC, MVT::i32, Custom); 486 setOperationAction(ISD::SUBE, MVT::i32, Custom); 487 setOperationAction(ISD::ADDC, MVT::i64, Custom); 488 setOperationAction(ISD::ADDE, MVT::i64, Custom); 489 setOperationAction(ISD::SUBC, MVT::i64, Custom); 490 setOperationAction(ISD::SUBE, MVT::i64, Custom); 491 492 // AArch64 lacks both left-rotate and popcount instructions. 493 setOperationAction(ISD::ROTL, MVT::i32, Expand); 494 setOperationAction(ISD::ROTL, MVT::i64, Expand); 495 for (MVT VT : MVT::fixedlen_vector_valuetypes()) { 496 setOperationAction(ISD::ROTL, VT, Expand); 497 setOperationAction(ISD::ROTR, VT, Expand); 498 } 499 500 // AArch64 doesn't have i32 MULH{S|U}. 501 setOperationAction(ISD::MULHU, MVT::i32, Expand); 502 setOperationAction(ISD::MULHS, MVT::i32, Expand); 503 504 // AArch64 doesn't have {U|S}MUL_LOHI. 505 setOperationAction(ISD::UMUL_LOHI, MVT::i64, Expand); 506 setOperationAction(ISD::SMUL_LOHI, MVT::i64, Expand); 507 508 setOperationAction(ISD::CTPOP, MVT::i32, Custom); 509 setOperationAction(ISD::CTPOP, MVT::i64, Custom); 510 setOperationAction(ISD::CTPOP, MVT::i128, Custom); 511 512 setOperationAction(ISD::ABS, MVT::i32, Custom); 513 setOperationAction(ISD::ABS, MVT::i64, Custom); 514 515 setOperationAction(ISD::SDIVREM, MVT::i32, Expand); 516 setOperationAction(ISD::SDIVREM, MVT::i64, Expand); 517 for (MVT VT : MVT::fixedlen_vector_valuetypes()) { 518 setOperationAction(ISD::SDIVREM, VT, Expand); 519 setOperationAction(ISD::UDIVREM, VT, Expand); 520 } 521 setOperationAction(ISD::SREM, MVT::i32, Expand); 522 setOperationAction(ISD::SREM, MVT::i64, Expand); 523 setOperationAction(ISD::UDIVREM, MVT::i32, Expand); 524 setOperationAction(ISD::UDIVREM, MVT::i64, Expand); 525 setOperationAction(ISD::UREM, MVT::i32, Expand); 526 setOperationAction(ISD::UREM, MVT::i64, Expand); 527 528 // Custom lower Add/Sub/Mul with overflow. 529 setOperationAction(ISD::SADDO, MVT::i32, Custom); 530 setOperationAction(ISD::SADDO, MVT::i64, Custom); 531 setOperationAction(ISD::UADDO, MVT::i32, Custom); 532 setOperationAction(ISD::UADDO, MVT::i64, Custom); 533 setOperationAction(ISD::SSUBO, MVT::i32, Custom); 534 setOperationAction(ISD::SSUBO, MVT::i64, Custom); 535 setOperationAction(ISD::USUBO, MVT::i32, Custom); 536 setOperationAction(ISD::USUBO, MVT::i64, Custom); 537 setOperationAction(ISD::SMULO, MVT::i32, Custom); 538 setOperationAction(ISD::SMULO, MVT::i64, Custom); 539 setOperationAction(ISD::UMULO, MVT::i32, Custom); 540 setOperationAction(ISD::UMULO, MVT::i64, Custom); 541 542 setOperationAction(ISD::FSIN, MVT::f32, Expand); 543 setOperationAction(ISD::FSIN, MVT::f64, Expand); 544 setOperationAction(ISD::FCOS, MVT::f32, Expand); 545 setOperationAction(ISD::FCOS, MVT::f64, Expand); 546 setOperationAction(ISD::FPOW, MVT::f32, Expand); 547 setOperationAction(ISD::FPOW, MVT::f64, Expand); 548 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Custom); 549 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom); 550 if (Subtarget->hasFullFP16()) 551 setOperationAction(ISD::FCOPYSIGN, MVT::f16, Custom); 552 else 553 setOperationAction(ISD::FCOPYSIGN, MVT::f16, Promote); 554 555 setOperationAction(ISD::FREM, MVT::f16, Promote); 556 setOperationAction(ISD::FREM, MVT::v4f16, Expand); 557 setOperationAction(ISD::FREM, MVT::v8f16, Expand); 558 setOperationAction(ISD::FPOW, MVT::f16, Promote); 559 setOperationAction(ISD::FPOW, MVT::v4f16, Expand); 560 setOperationAction(ISD::FPOW, MVT::v8f16, Expand); 561 setOperationAction(ISD::FPOWI, MVT::f16, Promote); 562 setOperationAction(ISD::FPOWI, MVT::v4f16, Expand); 563 setOperationAction(ISD::FPOWI, MVT::v8f16, Expand); 564 setOperationAction(ISD::FCOS, MVT::f16, Promote); 565 setOperationAction(ISD::FCOS, MVT::v4f16, Expand); 566 setOperationAction(ISD::FCOS, MVT::v8f16, Expand); 567 setOperationAction(ISD::FSIN, MVT::f16, Promote); 568 setOperationAction(ISD::FSIN, MVT::v4f16, Expand); 569 setOperationAction(ISD::FSIN, MVT::v8f16, Expand); 570 setOperationAction(ISD::FSINCOS, MVT::f16, Promote); 571 setOperationAction(ISD::FSINCOS, MVT::v4f16, Expand); 572 setOperationAction(ISD::FSINCOS, MVT::v8f16, Expand); 573 setOperationAction(ISD::FEXP, MVT::f16, Promote); 574 setOperationAction(ISD::FEXP, MVT::v4f16, Expand); 575 setOperationAction(ISD::FEXP, MVT::v8f16, Expand); 576 setOperationAction(ISD::FEXP2, MVT::f16, Promote); 577 setOperationAction(ISD::FEXP2, MVT::v4f16, Expand); 578 setOperationAction(ISD::FEXP2, MVT::v8f16, Expand); 579 setOperationAction(ISD::FLOG, MVT::f16, Promote); 580 setOperationAction(ISD::FLOG, MVT::v4f16, Expand); 581 setOperationAction(ISD::FLOG, MVT::v8f16, Expand); 582 setOperationAction(ISD::FLOG2, MVT::f16, Promote); 583 setOperationAction(ISD::FLOG2, MVT::v4f16, Expand); 584 setOperationAction(ISD::FLOG2, MVT::v8f16, Expand); 585 setOperationAction(ISD::FLOG10, MVT::f16, Promote); 586 setOperationAction(ISD::FLOG10, MVT::v4f16, Expand); 587 setOperationAction(ISD::FLOG10, MVT::v8f16, Expand); 588 589 if (!Subtarget->hasFullFP16()) { 590 setOperationAction(ISD::SELECT, MVT::f16, Promote); 591 setOperationAction(ISD::SELECT_CC, MVT::f16, Promote); 592 setOperationAction(ISD::SETCC, MVT::f16, Promote); 593 setOperationAction(ISD::BR_CC, MVT::f16, Promote); 594 setOperationAction(ISD::FADD, MVT::f16, Promote); 595 setOperationAction(ISD::FSUB, MVT::f16, Promote); 596 setOperationAction(ISD::FMUL, MVT::f16, Promote); 597 setOperationAction(ISD::FDIV, MVT::f16, Promote); 598 setOperationAction(ISD::FMA, MVT::f16, Promote); 599 setOperationAction(ISD::FNEG, MVT::f16, Promote); 600 setOperationAction(ISD::FABS, MVT::f16, Promote); 601 setOperationAction(ISD::FCEIL, MVT::f16, Promote); 602 setOperationAction(ISD::FSQRT, MVT::f16, Promote); 603 setOperationAction(ISD::FFLOOR, MVT::f16, Promote); 604 setOperationAction(ISD::FNEARBYINT, MVT::f16, Promote); 605 setOperationAction(ISD::FRINT, MVT::f16, Promote); 606 setOperationAction(ISD::FROUND, MVT::f16, Promote); 607 setOperationAction(ISD::FTRUNC, MVT::f16, Promote); 608 setOperationAction(ISD::FMINNUM, MVT::f16, Promote); 609 setOperationAction(ISD::FMAXNUM, MVT::f16, Promote); 610 setOperationAction(ISD::FMINIMUM, MVT::f16, Promote); 611 setOperationAction(ISD::FMAXIMUM, MVT::f16, Promote); 612 613 // promote v4f16 to v4f32 when that is known to be safe. 614 setOperationAction(ISD::FADD, MVT::v4f16, Promote); 615 setOperationAction(ISD::FSUB, MVT::v4f16, Promote); 616 setOperationAction(ISD::FMUL, MVT::v4f16, Promote); 617 setOperationAction(ISD::FDIV, MVT::v4f16, Promote); 618 AddPromotedToType(ISD::FADD, MVT::v4f16, MVT::v4f32); 619 AddPromotedToType(ISD::FSUB, MVT::v4f16, MVT::v4f32); 620 AddPromotedToType(ISD::FMUL, MVT::v4f16, MVT::v4f32); 621 AddPromotedToType(ISD::FDIV, MVT::v4f16, MVT::v4f32); 622 623 setOperationAction(ISD::FABS, MVT::v4f16, Expand); 624 setOperationAction(ISD::FNEG, MVT::v4f16, Expand); 625 setOperationAction(ISD::FROUND, MVT::v4f16, Expand); 626 setOperationAction(ISD::FMA, MVT::v4f16, Expand); 627 setOperationAction(ISD::SETCC, MVT::v4f16, Expand); 628 setOperationAction(ISD::BR_CC, MVT::v4f16, Expand); 629 setOperationAction(ISD::SELECT, MVT::v4f16, Expand); 630 setOperationAction(ISD::SELECT_CC, MVT::v4f16, Expand); 631 setOperationAction(ISD::FTRUNC, MVT::v4f16, Expand); 632 setOperationAction(ISD::FCOPYSIGN, MVT::v4f16, Expand); 633 setOperationAction(ISD::FFLOOR, MVT::v4f16, Expand); 634 setOperationAction(ISD::FCEIL, MVT::v4f16, Expand); 635 setOperationAction(ISD::FRINT, MVT::v4f16, Expand); 636 setOperationAction(ISD::FNEARBYINT, MVT::v4f16, Expand); 637 setOperationAction(ISD::FSQRT, MVT::v4f16, Expand); 638 639 setOperationAction(ISD::FABS, MVT::v8f16, Expand); 640 setOperationAction(ISD::FADD, MVT::v8f16, Expand); 641 setOperationAction(ISD::FCEIL, MVT::v8f16, Expand); 642 setOperationAction(ISD::FCOPYSIGN, MVT::v8f16, Expand); 643 setOperationAction(ISD::FDIV, MVT::v8f16, Expand); 644 setOperationAction(ISD::FFLOOR, MVT::v8f16, Expand); 645 setOperationAction(ISD::FMA, MVT::v8f16, Expand); 646 setOperationAction(ISD::FMUL, MVT::v8f16, Expand); 647 setOperationAction(ISD::FNEARBYINT, MVT::v8f16, Expand); 648 setOperationAction(ISD::FNEG, MVT::v8f16, Expand); 649 setOperationAction(ISD::FROUND, MVT::v8f16, Expand); 650 setOperationAction(ISD::FRINT, MVT::v8f16, Expand); 651 setOperationAction(ISD::FSQRT, MVT::v8f16, Expand); 652 setOperationAction(ISD::FSUB, MVT::v8f16, Expand); 653 setOperationAction(ISD::FTRUNC, MVT::v8f16, Expand); 654 setOperationAction(ISD::SETCC, MVT::v8f16, Expand); 655 setOperationAction(ISD::BR_CC, MVT::v8f16, Expand); 656 setOperationAction(ISD::SELECT, MVT::v8f16, Expand); 657 setOperationAction(ISD::SELECT_CC, MVT::v8f16, Expand); 658 setOperationAction(ISD::FP_EXTEND, MVT::v8f16, Expand); 659 } 660 661 // AArch64 has implementations of a lot of rounding-like FP operations. 662 for (MVT Ty : {MVT::f32, MVT::f64}) { 663 setOperationAction(ISD::FFLOOR, Ty, Legal); 664 setOperationAction(ISD::FNEARBYINT, Ty, Legal); 665 setOperationAction(ISD::FCEIL, Ty, Legal); 666 setOperationAction(ISD::FRINT, Ty, Legal); 667 setOperationAction(ISD::FTRUNC, Ty, Legal); 668 setOperationAction(ISD::FROUND, Ty, Legal); 669 setOperationAction(ISD::FMINNUM, Ty, Legal); 670 setOperationAction(ISD::FMAXNUM, Ty, Legal); 671 setOperationAction(ISD::FMINIMUM, Ty, Legal); 672 setOperationAction(ISD::FMAXIMUM, Ty, Legal); 673 setOperationAction(ISD::LROUND, Ty, Legal); 674 setOperationAction(ISD::LLROUND, Ty, Legal); 675 setOperationAction(ISD::LRINT, Ty, Legal); 676 setOperationAction(ISD::LLRINT, Ty, Legal); 677 } 678 679 if (Subtarget->hasFullFP16()) { 680 setOperationAction(ISD::FNEARBYINT, MVT::f16, Legal); 681 setOperationAction(ISD::FFLOOR, MVT::f16, Legal); 682 setOperationAction(ISD::FCEIL, MVT::f16, Legal); 683 setOperationAction(ISD::FRINT, MVT::f16, Legal); 684 setOperationAction(ISD::FTRUNC, MVT::f16, Legal); 685 setOperationAction(ISD::FROUND, MVT::f16, Legal); 686 setOperationAction(ISD::FMINNUM, MVT::f16, Legal); 687 setOperationAction(ISD::FMAXNUM, MVT::f16, Legal); 688 setOperationAction(ISD::FMINIMUM, MVT::f16, Legal); 689 setOperationAction(ISD::FMAXIMUM, MVT::f16, Legal); 690 } 691 692 setOperationAction(ISD::PREFETCH, MVT::Other, Custom); 693 694 setOperationAction(ISD::FLT_ROUNDS_, MVT::i32, Custom); 695 696 setOperationAction(ISD::ATOMIC_CMP_SWAP, MVT::i128, Custom); 697 setOperationAction(ISD::ATOMIC_LOAD_SUB, MVT::i32, Custom); 698 setOperationAction(ISD::ATOMIC_LOAD_SUB, MVT::i64, Custom); 699 setOperationAction(ISD::ATOMIC_LOAD_AND, MVT::i32, Custom); 700 setOperationAction(ISD::ATOMIC_LOAD_AND, MVT::i64, Custom); 701 702 // Generate outline atomics library calls only if LSE was not specified for 703 // subtarget 704 if (Subtarget->outlineAtomics() && !Subtarget->hasLSE()) { 705 setOperationAction(ISD::ATOMIC_CMP_SWAP, MVT::i8, LibCall); 706 setOperationAction(ISD::ATOMIC_CMP_SWAP, MVT::i16, LibCall); 707 setOperationAction(ISD::ATOMIC_CMP_SWAP, MVT::i32, LibCall); 708 setOperationAction(ISD::ATOMIC_CMP_SWAP, MVT::i64, LibCall); 709 setOperationAction(ISD::ATOMIC_CMP_SWAP, MVT::i128, LibCall); 710 setOperationAction(ISD::ATOMIC_SWAP, MVT::i8, LibCall); 711 setOperationAction(ISD::ATOMIC_SWAP, MVT::i16, LibCall); 712 setOperationAction(ISD::ATOMIC_SWAP, MVT::i32, LibCall); 713 setOperationAction(ISD::ATOMIC_SWAP, MVT::i64, LibCall); 714 setOperationAction(ISD::ATOMIC_LOAD_ADD, MVT::i8, LibCall); 715 setOperationAction(ISD::ATOMIC_LOAD_ADD, MVT::i16, LibCall); 716 setOperationAction(ISD::ATOMIC_LOAD_ADD, MVT::i32, LibCall); 717 setOperationAction(ISD::ATOMIC_LOAD_ADD, MVT::i64, LibCall); 718 setOperationAction(ISD::ATOMIC_LOAD_OR, MVT::i8, LibCall); 719 setOperationAction(ISD::ATOMIC_LOAD_OR, MVT::i16, LibCall); 720 setOperationAction(ISD::ATOMIC_LOAD_OR, MVT::i32, LibCall); 721 setOperationAction(ISD::ATOMIC_LOAD_OR, MVT::i64, LibCall); 722 setOperationAction(ISD::ATOMIC_LOAD_CLR, MVT::i8, LibCall); 723 setOperationAction(ISD::ATOMIC_LOAD_CLR, MVT::i16, LibCall); 724 setOperationAction(ISD::ATOMIC_LOAD_CLR, MVT::i32, LibCall); 725 setOperationAction(ISD::ATOMIC_LOAD_CLR, MVT::i64, LibCall); 726 setOperationAction(ISD::ATOMIC_LOAD_XOR, MVT::i8, LibCall); 727 setOperationAction(ISD::ATOMIC_LOAD_XOR, MVT::i16, LibCall); 728 setOperationAction(ISD::ATOMIC_LOAD_XOR, MVT::i32, LibCall); 729 setOperationAction(ISD::ATOMIC_LOAD_XOR, MVT::i64, LibCall); 730 #define LCALLNAMES(A, B, N) \ 731 setLibcallName(A##N##_RELAX, #B #N "_relax"); \ 732 setLibcallName(A##N##_ACQ, #B #N "_acq"); \ 733 setLibcallName(A##N##_REL, #B #N "_rel"); \ 734 setLibcallName(A##N##_ACQ_REL, #B #N "_acq_rel"); 735 #define LCALLNAME4(A, B) \ 736 LCALLNAMES(A, B, 1) \ 737 LCALLNAMES(A, B, 2) LCALLNAMES(A, B, 4) LCALLNAMES(A, B, 8) 738 #define LCALLNAME5(A, B) \ 739 LCALLNAMES(A, B, 1) \ 740 LCALLNAMES(A, B, 2) \ 741 LCALLNAMES(A, B, 4) LCALLNAMES(A, B, 8) LCALLNAMES(A, B, 16) 742 LCALLNAME5(RTLIB::OUTLINE_ATOMIC_CAS, __aarch64_cas) 743 LCALLNAME4(RTLIB::OUTLINE_ATOMIC_SWP, __aarch64_swp) 744 LCALLNAME4(RTLIB::OUTLINE_ATOMIC_LDADD, __aarch64_ldadd) 745 LCALLNAME4(RTLIB::OUTLINE_ATOMIC_LDSET, __aarch64_ldset) 746 LCALLNAME4(RTLIB::OUTLINE_ATOMIC_LDCLR, __aarch64_ldclr) 747 LCALLNAME4(RTLIB::OUTLINE_ATOMIC_LDEOR, __aarch64_ldeor) 748 #undef LCALLNAMES 749 #undef LCALLNAME4 750 #undef LCALLNAME5 751 } 752 753 // 128-bit loads and stores can be done without expanding 754 setOperationAction(ISD::LOAD, MVT::i128, Custom); 755 setOperationAction(ISD::STORE, MVT::i128, Custom); 756 757 // 256 bit non-temporal stores can be lowered to STNP. Do this as part of the 758 // custom lowering, as there are no un-paired non-temporal stores and 759 // legalization will break up 256 bit inputs. 760 setOperationAction(ISD::STORE, MVT::v32i8, Custom); 761 setOperationAction(ISD::STORE, MVT::v16i16, Custom); 762 setOperationAction(ISD::STORE, MVT::v16f16, Custom); 763 setOperationAction(ISD::STORE, MVT::v8i32, Custom); 764 setOperationAction(ISD::STORE, MVT::v8f32, Custom); 765 setOperationAction(ISD::STORE, MVT::v4f64, Custom); 766 setOperationAction(ISD::STORE, MVT::v4i64, Custom); 767 768 // Lower READCYCLECOUNTER using an mrs from PMCCNTR_EL0. 769 // This requires the Performance Monitors extension. 770 if (Subtarget->hasPerfMon()) 771 setOperationAction(ISD::READCYCLECOUNTER, MVT::i64, Legal); 772 773 if (getLibcallName(RTLIB::SINCOS_STRET_F32) != nullptr && 774 getLibcallName(RTLIB::SINCOS_STRET_F64) != nullptr) { 775 // Issue __sincos_stret if available. 776 setOperationAction(ISD::FSINCOS, MVT::f64, Custom); 777 setOperationAction(ISD::FSINCOS, MVT::f32, Custom); 778 } else { 779 setOperationAction(ISD::FSINCOS, MVT::f64, Expand); 780 setOperationAction(ISD::FSINCOS, MVT::f32, Expand); 781 } 782 783 if (Subtarget->getTargetTriple().isOSMSVCRT()) { 784 // MSVCRT doesn't have powi; fall back to pow 785 setLibcallName(RTLIB::POWI_F32, nullptr); 786 setLibcallName(RTLIB::POWI_F64, nullptr); 787 } 788 789 // Make floating-point constants legal for the large code model, so they don't 790 // become loads from the constant pool. 791 if (Subtarget->isTargetMachO() && TM.getCodeModel() == CodeModel::Large) { 792 setOperationAction(ISD::ConstantFP, MVT::f32, Legal); 793 setOperationAction(ISD::ConstantFP, MVT::f64, Legal); 794 } 795 796 // AArch64 does not have floating-point extending loads, i1 sign-extending 797 // load, floating-point truncating stores, or v2i32->v2i16 truncating store. 798 for (MVT VT : MVT::fp_valuetypes()) { 799 setLoadExtAction(ISD::EXTLOAD, VT, MVT::f16, Expand); 800 setLoadExtAction(ISD::EXTLOAD, VT, MVT::f32, Expand); 801 setLoadExtAction(ISD::EXTLOAD, VT, MVT::f64, Expand); 802 setLoadExtAction(ISD::EXTLOAD, VT, MVT::f80, Expand); 803 } 804 for (MVT VT : MVT::integer_valuetypes()) 805 setLoadExtAction(ISD::SEXTLOAD, VT, MVT::i1, Expand); 806 807 setTruncStoreAction(MVT::f32, MVT::f16, Expand); 808 setTruncStoreAction(MVT::f64, MVT::f32, Expand); 809 setTruncStoreAction(MVT::f64, MVT::f16, Expand); 810 setTruncStoreAction(MVT::f128, MVT::f80, Expand); 811 setTruncStoreAction(MVT::f128, MVT::f64, Expand); 812 setTruncStoreAction(MVT::f128, MVT::f32, Expand); 813 setTruncStoreAction(MVT::f128, MVT::f16, Expand); 814 815 setOperationAction(ISD::BITCAST, MVT::i16, Custom); 816 setOperationAction(ISD::BITCAST, MVT::f16, Custom); 817 setOperationAction(ISD::BITCAST, MVT::bf16, Custom); 818 819 // Indexed loads and stores are supported. 820 for (unsigned im = (unsigned)ISD::PRE_INC; 821 im != (unsigned)ISD::LAST_INDEXED_MODE; ++im) { 822 setIndexedLoadAction(im, MVT::i8, Legal); 823 setIndexedLoadAction(im, MVT::i16, Legal); 824 setIndexedLoadAction(im, MVT::i32, Legal); 825 setIndexedLoadAction(im, MVT::i64, Legal); 826 setIndexedLoadAction(im, MVT::f64, Legal); 827 setIndexedLoadAction(im, MVT::f32, Legal); 828 setIndexedLoadAction(im, MVT::f16, Legal); 829 setIndexedLoadAction(im, MVT::bf16, Legal); 830 setIndexedStoreAction(im, MVT::i8, Legal); 831 setIndexedStoreAction(im, MVT::i16, Legal); 832 setIndexedStoreAction(im, MVT::i32, Legal); 833 setIndexedStoreAction(im, MVT::i64, Legal); 834 setIndexedStoreAction(im, MVT::f64, Legal); 835 setIndexedStoreAction(im, MVT::f32, Legal); 836 setIndexedStoreAction(im, MVT::f16, Legal); 837 setIndexedStoreAction(im, MVT::bf16, Legal); 838 } 839 840 // Trap. 841 setOperationAction(ISD::TRAP, MVT::Other, Legal); 842 setOperationAction(ISD::DEBUGTRAP, MVT::Other, Legal); 843 setOperationAction(ISD::UBSANTRAP, MVT::Other, Legal); 844 845 // We combine OR nodes for bitfield operations. 846 setTargetDAGCombine(ISD::OR); 847 // Try to create BICs for vector ANDs. 848 setTargetDAGCombine(ISD::AND); 849 850 // Vector add and sub nodes may conceal a high-half opportunity. 851 // Also, try to fold ADD into CSINC/CSINV.. 852 setTargetDAGCombine(ISD::ADD); 853 setTargetDAGCombine(ISD::ABS); 854 setTargetDAGCombine(ISD::SUB); 855 setTargetDAGCombine(ISD::SRL); 856 setTargetDAGCombine(ISD::XOR); 857 setTargetDAGCombine(ISD::SINT_TO_FP); 858 setTargetDAGCombine(ISD::UINT_TO_FP); 859 860 setTargetDAGCombine(ISD::FP_TO_SINT); 861 setTargetDAGCombine(ISD::FP_TO_UINT); 862 setTargetDAGCombine(ISD::FDIV); 863 864 setTargetDAGCombine(ISD::INTRINSIC_WO_CHAIN); 865 866 setTargetDAGCombine(ISD::ANY_EXTEND); 867 setTargetDAGCombine(ISD::ZERO_EXTEND); 868 setTargetDAGCombine(ISD::SIGN_EXTEND); 869 setTargetDAGCombine(ISD::SIGN_EXTEND_INREG); 870 setTargetDAGCombine(ISD::TRUNCATE); 871 setTargetDAGCombine(ISD::CONCAT_VECTORS); 872 setTargetDAGCombine(ISD::STORE); 873 if (Subtarget->supportsAddressTopByteIgnored()) 874 setTargetDAGCombine(ISD::LOAD); 875 876 setTargetDAGCombine(ISD::MUL); 877 878 setTargetDAGCombine(ISD::SELECT); 879 setTargetDAGCombine(ISD::VSELECT); 880 881 setTargetDAGCombine(ISD::INTRINSIC_VOID); 882 setTargetDAGCombine(ISD::INTRINSIC_W_CHAIN); 883 setTargetDAGCombine(ISD::INSERT_VECTOR_ELT); 884 setTargetDAGCombine(ISD::EXTRACT_VECTOR_ELT); 885 setTargetDAGCombine(ISD::VECREDUCE_ADD); 886 887 setTargetDAGCombine(ISD::GlobalAddress); 888 889 // In case of strict alignment, avoid an excessive number of byte wide stores. 890 MaxStoresPerMemsetOptSize = 8; 891 MaxStoresPerMemset = Subtarget->requiresStrictAlign() 892 ? MaxStoresPerMemsetOptSize : 32; 893 894 MaxGluedStoresPerMemcpy = 4; 895 MaxStoresPerMemcpyOptSize = 4; 896 MaxStoresPerMemcpy = Subtarget->requiresStrictAlign() 897 ? MaxStoresPerMemcpyOptSize : 16; 898 899 MaxStoresPerMemmoveOptSize = MaxStoresPerMemmove = 4; 900 901 MaxLoadsPerMemcmpOptSize = 4; 902 MaxLoadsPerMemcmp = Subtarget->requiresStrictAlign() 903 ? MaxLoadsPerMemcmpOptSize : 8; 904 905 setStackPointerRegisterToSaveRestore(AArch64::SP); 906 907 setSchedulingPreference(Sched::Hybrid); 908 909 EnableExtLdPromotion = true; 910 911 // Set required alignment. 912 setMinFunctionAlignment(Align(4)); 913 // Set preferred alignments. 914 setPrefLoopAlignment(Align(1ULL << STI.getPrefLoopLogAlignment())); 915 setPrefFunctionAlignment(Align(1ULL << STI.getPrefFunctionLogAlignment())); 916 917 // Only change the limit for entries in a jump table if specified by 918 // the sub target, but not at the command line. 919 unsigned MaxJT = STI.getMaximumJumpTableSize(); 920 if (MaxJT && getMaximumJumpTableSize() == UINT_MAX) 921 setMaximumJumpTableSize(MaxJT); 922 923 setHasExtractBitsInsn(true); 924 925 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom); 926 927 if (Subtarget->hasNEON()) { 928 // FIXME: v1f64 shouldn't be legal if we can avoid it, because it leads to 929 // silliness like this: 930 setOperationAction(ISD::FABS, MVT::v1f64, Expand); 931 setOperationAction(ISD::FADD, MVT::v1f64, Expand); 932 setOperationAction(ISD::FCEIL, MVT::v1f64, Expand); 933 setOperationAction(ISD::FCOPYSIGN, MVT::v1f64, Expand); 934 setOperationAction(ISD::FCOS, MVT::v1f64, Expand); 935 setOperationAction(ISD::FDIV, MVT::v1f64, Expand); 936 setOperationAction(ISD::FFLOOR, MVT::v1f64, Expand); 937 setOperationAction(ISD::FMA, MVT::v1f64, Expand); 938 setOperationAction(ISD::FMUL, MVT::v1f64, Expand); 939 setOperationAction(ISD::FNEARBYINT, MVT::v1f64, Expand); 940 setOperationAction(ISD::FNEG, MVT::v1f64, Expand); 941 setOperationAction(ISD::FPOW, MVT::v1f64, Expand); 942 setOperationAction(ISD::FREM, MVT::v1f64, Expand); 943 setOperationAction(ISD::FROUND, MVT::v1f64, Expand); 944 setOperationAction(ISD::FRINT, MVT::v1f64, Expand); 945 setOperationAction(ISD::FSIN, MVT::v1f64, Expand); 946 setOperationAction(ISD::FSINCOS, MVT::v1f64, Expand); 947 setOperationAction(ISD::FSQRT, MVT::v1f64, Expand); 948 setOperationAction(ISD::FSUB, MVT::v1f64, Expand); 949 setOperationAction(ISD::FTRUNC, MVT::v1f64, Expand); 950 setOperationAction(ISD::SETCC, MVT::v1f64, Expand); 951 setOperationAction(ISD::BR_CC, MVT::v1f64, Expand); 952 setOperationAction(ISD::SELECT, MVT::v1f64, Expand); 953 setOperationAction(ISD::SELECT_CC, MVT::v1f64, Expand); 954 setOperationAction(ISD::FP_EXTEND, MVT::v1f64, Expand); 955 956 setOperationAction(ISD::FP_TO_SINT, MVT::v1i64, Expand); 957 setOperationAction(ISD::FP_TO_UINT, MVT::v1i64, Expand); 958 setOperationAction(ISD::SINT_TO_FP, MVT::v1i64, Expand); 959 setOperationAction(ISD::UINT_TO_FP, MVT::v1i64, Expand); 960 setOperationAction(ISD::FP_ROUND, MVT::v1f64, Expand); 961 962 setOperationAction(ISD::MUL, MVT::v1i64, Expand); 963 964 // AArch64 doesn't have a direct vector ->f32 conversion instructions for 965 // elements smaller than i32, so promote the input to i32 first. 966 setOperationPromotedToType(ISD::UINT_TO_FP, MVT::v4i8, MVT::v4i32); 967 setOperationPromotedToType(ISD::SINT_TO_FP, MVT::v4i8, MVT::v4i32); 968 // i8 vector elements also need promotion to i32 for v8i8 969 setOperationPromotedToType(ISD::SINT_TO_FP, MVT::v8i8, MVT::v8i32); 970 setOperationPromotedToType(ISD::UINT_TO_FP, MVT::v8i8, MVT::v8i32); 971 // Similarly, there is no direct i32 -> f64 vector conversion instruction. 972 setOperationAction(ISD::SINT_TO_FP, MVT::v2i32, Custom); 973 setOperationAction(ISD::UINT_TO_FP, MVT::v2i32, Custom); 974 setOperationAction(ISD::SINT_TO_FP, MVT::v2i64, Custom); 975 setOperationAction(ISD::UINT_TO_FP, MVT::v2i64, Custom); 976 // Or, direct i32 -> f16 vector conversion. Set it so custom, so the 977 // conversion happens in two steps: v4i32 -> v4f32 -> v4f16 978 setOperationAction(ISD::SINT_TO_FP, MVT::v4i32, Custom); 979 setOperationAction(ISD::UINT_TO_FP, MVT::v4i32, Custom); 980 981 if (Subtarget->hasFullFP16()) { 982 setOperationAction(ISD::SINT_TO_FP, MVT::v4i16, Custom); 983 setOperationAction(ISD::UINT_TO_FP, MVT::v4i16, Custom); 984 setOperationAction(ISD::SINT_TO_FP, MVT::v8i16, Custom); 985 setOperationAction(ISD::UINT_TO_FP, MVT::v8i16, Custom); 986 } else { 987 // when AArch64 doesn't have fullfp16 support, promote the input 988 // to i32 first. 989 setOperationPromotedToType(ISD::UINT_TO_FP, MVT::v4i16, MVT::v4i32); 990 setOperationPromotedToType(ISD::SINT_TO_FP, MVT::v4i16, MVT::v4i32); 991 setOperationPromotedToType(ISD::SINT_TO_FP, MVT::v8i16, MVT::v8i32); 992 setOperationPromotedToType(ISD::UINT_TO_FP, MVT::v8i16, MVT::v8i32); 993 } 994 995 setOperationAction(ISD::CTLZ, MVT::v1i64, Expand); 996 setOperationAction(ISD::CTLZ, MVT::v2i64, Expand); 997 998 // AArch64 doesn't have MUL.2d: 999 setOperationAction(ISD::MUL, MVT::v2i64, Expand); 1000 // Custom handling for some quad-vector types to detect MULL. 1001 setOperationAction(ISD::MUL, MVT::v8i16, Custom); 1002 setOperationAction(ISD::MUL, MVT::v4i32, Custom); 1003 setOperationAction(ISD::MUL, MVT::v2i64, Custom); 1004 1005 // Saturates 1006 for (MVT VT : { MVT::v8i8, MVT::v4i16, MVT::v2i32, 1007 MVT::v16i8, MVT::v8i16, MVT::v4i32, MVT::v2i64 }) { 1008 setOperationAction(ISD::SADDSAT, VT, Legal); 1009 setOperationAction(ISD::UADDSAT, VT, Legal); 1010 setOperationAction(ISD::SSUBSAT, VT, Legal); 1011 setOperationAction(ISD::USUBSAT, VT, Legal); 1012 } 1013 1014 // Vector reductions 1015 for (MVT VT : { MVT::v4f16, MVT::v2f32, 1016 MVT::v8f16, MVT::v4f32, MVT::v2f64 }) { 1017 setOperationAction(ISD::VECREDUCE_FMAX, VT, Custom); 1018 setOperationAction(ISD::VECREDUCE_FMIN, VT, Custom); 1019 1020 if (VT.getVectorElementType() != MVT::f16 || Subtarget->hasFullFP16()) 1021 setOperationAction(ISD::VECREDUCE_FADD, VT, Legal); 1022 } 1023 for (MVT VT : { MVT::v8i8, MVT::v4i16, MVT::v2i32, 1024 MVT::v16i8, MVT::v8i16, MVT::v4i32 }) { 1025 setOperationAction(ISD::VECREDUCE_ADD, VT, Custom); 1026 setOperationAction(ISD::VECREDUCE_SMAX, VT, Custom); 1027 setOperationAction(ISD::VECREDUCE_SMIN, VT, Custom); 1028 setOperationAction(ISD::VECREDUCE_UMAX, VT, Custom); 1029 setOperationAction(ISD::VECREDUCE_UMIN, VT, Custom); 1030 } 1031 setOperationAction(ISD::VECREDUCE_ADD, MVT::v2i64, Custom); 1032 1033 setOperationAction(ISD::ANY_EXTEND, MVT::v4i32, Legal); 1034 setTruncStoreAction(MVT::v2i32, MVT::v2i16, Expand); 1035 // Likewise, narrowing and extending vector loads/stores aren't handled 1036 // directly. 1037 for (MVT VT : MVT::fixedlen_vector_valuetypes()) { 1038 setOperationAction(ISD::SIGN_EXTEND_INREG, VT, Expand); 1039 1040 if (VT == MVT::v16i8 || VT == MVT::v8i16 || VT == MVT::v4i32) { 1041 setOperationAction(ISD::MULHS, VT, Legal); 1042 setOperationAction(ISD::MULHU, VT, Legal); 1043 } else { 1044 setOperationAction(ISD::MULHS, VT, Expand); 1045 setOperationAction(ISD::MULHU, VT, Expand); 1046 } 1047 setOperationAction(ISD::SMUL_LOHI, VT, Expand); 1048 setOperationAction(ISD::UMUL_LOHI, VT, Expand); 1049 1050 setOperationAction(ISD::BSWAP, VT, Expand); 1051 setOperationAction(ISD::CTTZ, VT, Expand); 1052 1053 for (MVT InnerVT : MVT::fixedlen_vector_valuetypes()) { 1054 setTruncStoreAction(VT, InnerVT, Expand); 1055 setLoadExtAction(ISD::SEXTLOAD, VT, InnerVT, Expand); 1056 setLoadExtAction(ISD::ZEXTLOAD, VT, InnerVT, Expand); 1057 setLoadExtAction(ISD::EXTLOAD, VT, InnerVT, Expand); 1058 } 1059 } 1060 1061 // AArch64 has implementations of a lot of rounding-like FP operations. 1062 for (MVT Ty : {MVT::v2f32, MVT::v4f32, MVT::v2f64}) { 1063 setOperationAction(ISD::FFLOOR, Ty, Legal); 1064 setOperationAction(ISD::FNEARBYINT, Ty, Legal); 1065 setOperationAction(ISD::FCEIL, Ty, Legal); 1066 setOperationAction(ISD::FRINT, Ty, Legal); 1067 setOperationAction(ISD::FTRUNC, Ty, Legal); 1068 setOperationAction(ISD::FROUND, Ty, Legal); 1069 } 1070 1071 if (Subtarget->hasFullFP16()) { 1072 for (MVT Ty : {MVT::v4f16, MVT::v8f16}) { 1073 setOperationAction(ISD::FFLOOR, Ty, Legal); 1074 setOperationAction(ISD::FNEARBYINT, Ty, Legal); 1075 setOperationAction(ISD::FCEIL, Ty, Legal); 1076 setOperationAction(ISD::FRINT, Ty, Legal); 1077 setOperationAction(ISD::FTRUNC, Ty, Legal); 1078 setOperationAction(ISD::FROUND, Ty, Legal); 1079 } 1080 } 1081 1082 if (Subtarget->hasSVE()) 1083 setOperationAction(ISD::VSCALE, MVT::i32, Custom); 1084 1085 setTruncStoreAction(MVT::v4i16, MVT::v4i8, Custom); 1086 } 1087 1088 if (Subtarget->hasSVE()) { 1089 // FIXME: Add custom lowering of MLOAD to handle different passthrus (not a 1090 // splat of 0 or undef) once vector selects supported in SVE codegen. See 1091 // D68877 for more details. 1092 for (auto VT : {MVT::nxv16i8, MVT::nxv8i16, MVT::nxv4i32, MVT::nxv2i64}) { 1093 setOperationAction(ISD::BITREVERSE, VT, Custom); 1094 setOperationAction(ISD::BSWAP, VT, Custom); 1095 setOperationAction(ISD::CTLZ, VT, Custom); 1096 setOperationAction(ISD::CTPOP, VT, Custom); 1097 setOperationAction(ISD::CTTZ, VT, Custom); 1098 setOperationAction(ISD::INSERT_SUBVECTOR, VT, Custom); 1099 setOperationAction(ISD::UINT_TO_FP, VT, Custom); 1100 setOperationAction(ISD::SINT_TO_FP, VT, Custom); 1101 setOperationAction(ISD::FP_TO_UINT, VT, Custom); 1102 setOperationAction(ISD::FP_TO_SINT, VT, Custom); 1103 setOperationAction(ISD::MGATHER, VT, Custom); 1104 setOperationAction(ISD::MSCATTER, VT, Custom); 1105 setOperationAction(ISD::MUL, VT, Custom); 1106 setOperationAction(ISD::SPLAT_VECTOR, VT, Custom); 1107 setOperationAction(ISD::SELECT, VT, Custom); 1108 setOperationAction(ISD::SDIV, VT, Custom); 1109 setOperationAction(ISD::UDIV, VT, Custom); 1110 setOperationAction(ISD::SMIN, VT, Custom); 1111 setOperationAction(ISD::UMIN, VT, Custom); 1112 setOperationAction(ISD::SMAX, VT, Custom); 1113 setOperationAction(ISD::UMAX, VT, Custom); 1114 setOperationAction(ISD::SHL, VT, Custom); 1115 setOperationAction(ISD::SRL, VT, Custom); 1116 setOperationAction(ISD::SRA, VT, Custom); 1117 setOperationAction(ISD::ABS, VT, Custom); 1118 setOperationAction(ISD::VECREDUCE_ADD, VT, Custom); 1119 setOperationAction(ISD::VECREDUCE_AND, VT, Custom); 1120 setOperationAction(ISD::VECREDUCE_OR, VT, Custom); 1121 setOperationAction(ISD::VECREDUCE_XOR, VT, Custom); 1122 setOperationAction(ISD::VECREDUCE_UMIN, VT, Custom); 1123 setOperationAction(ISD::VECREDUCE_UMAX, VT, Custom); 1124 setOperationAction(ISD::VECREDUCE_SMIN, VT, Custom); 1125 setOperationAction(ISD::VECREDUCE_SMAX, VT, Custom); 1126 } 1127 1128 // Illegal unpacked integer vector types. 1129 for (auto VT : {MVT::nxv8i8, MVT::nxv4i16, MVT::nxv2i32}) { 1130 setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Custom); 1131 setOperationAction(ISD::INSERT_SUBVECTOR, VT, Custom); 1132 } 1133 1134 for (auto VT : {MVT::nxv16i1, MVT::nxv8i1, MVT::nxv4i1, MVT::nxv2i1}) { 1135 setOperationAction(ISD::CONCAT_VECTORS, VT, Custom); 1136 setOperationAction(ISD::SELECT, VT, Custom); 1137 setOperationAction(ISD::SETCC, VT, Custom); 1138 setOperationAction(ISD::SPLAT_VECTOR, VT, Custom); 1139 setOperationAction(ISD::TRUNCATE, VT, Custom); 1140 setOperationAction(ISD::VECREDUCE_AND, VT, Custom); 1141 setOperationAction(ISD::VECREDUCE_OR, VT, Custom); 1142 setOperationAction(ISD::VECREDUCE_XOR, VT, Custom); 1143 1144 // There are no legal MVT::nxv16f## based types. 1145 if (VT != MVT::nxv16i1) { 1146 setOperationAction(ISD::SINT_TO_FP, VT, Custom); 1147 setOperationAction(ISD::UINT_TO_FP, VT, Custom); 1148 } 1149 } 1150 1151 for (auto VT : {MVT::nxv2f16, MVT::nxv4f16, MVT::nxv8f16, MVT::nxv2f32, 1152 MVT::nxv4f32, MVT::nxv2f64}) { 1153 setOperationAction(ISD::CONCAT_VECTORS, VT, Custom); 1154 setOperationAction(ISD::INSERT_SUBVECTOR, VT, Custom); 1155 setOperationAction(ISD::MGATHER, VT, Custom); 1156 setOperationAction(ISD::MSCATTER, VT, Custom); 1157 setOperationAction(ISD::SPLAT_VECTOR, VT, Custom); 1158 setOperationAction(ISD::SELECT, VT, Custom); 1159 setOperationAction(ISD::FADD, VT, Custom); 1160 setOperationAction(ISD::FDIV, VT, Custom); 1161 setOperationAction(ISD::FMA, VT, Custom); 1162 setOperationAction(ISD::FMAXNUM, VT, Custom); 1163 setOperationAction(ISD::FMINNUM, VT, Custom); 1164 setOperationAction(ISD::FMUL, VT, Custom); 1165 setOperationAction(ISD::FNEG, VT, Custom); 1166 setOperationAction(ISD::FSUB, VT, Custom); 1167 setOperationAction(ISD::FCEIL, VT, Custom); 1168 setOperationAction(ISD::FFLOOR, VT, Custom); 1169 setOperationAction(ISD::FNEARBYINT, VT, Custom); 1170 setOperationAction(ISD::FRINT, VT, Custom); 1171 setOperationAction(ISD::FROUND, VT, Custom); 1172 setOperationAction(ISD::FROUNDEVEN, VT, Custom); 1173 setOperationAction(ISD::FTRUNC, VT, Custom); 1174 setOperationAction(ISD::FSQRT, VT, Custom); 1175 setOperationAction(ISD::FABS, VT, Custom); 1176 setOperationAction(ISD::FP_EXTEND, VT, Custom); 1177 setOperationAction(ISD::FP_ROUND, VT, Custom); 1178 setOperationAction(ISD::VECREDUCE_FADD, VT, Custom); 1179 setOperationAction(ISD::VECREDUCE_FMAX, VT, Custom); 1180 setOperationAction(ISD::VECREDUCE_FMIN, VT, Custom); 1181 setOperationAction(ISD::VECREDUCE_SEQ_FADD, VT, Custom); 1182 } 1183 1184 for (auto VT : {MVT::nxv2bf16, MVT::nxv4bf16, MVT::nxv8bf16}) { 1185 setOperationAction(ISD::CONCAT_VECTORS, VT, Custom); 1186 setOperationAction(ISD::MGATHER, VT, Custom); 1187 setOperationAction(ISD::MSCATTER, VT, Custom); 1188 } 1189 1190 setOperationAction(ISD::SPLAT_VECTOR, MVT::nxv8bf16, Custom); 1191 1192 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::i8, Custom); 1193 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::i16, Custom); 1194 1195 // NOTE: Currently this has to happen after computeRegisterProperties rather 1196 // than the preferred option of combining it with the addRegisterClass call. 1197 if (Subtarget->useSVEForFixedLengthVectors()) { 1198 for (MVT VT : MVT::integer_fixedlen_vector_valuetypes()) 1199 if (useSVEForFixedLengthVectorVT(VT)) 1200 addTypeForFixedLengthSVE(VT); 1201 for (MVT VT : MVT::fp_fixedlen_vector_valuetypes()) 1202 if (useSVEForFixedLengthVectorVT(VT)) 1203 addTypeForFixedLengthSVE(VT); 1204 1205 // 64bit results can mean a bigger than NEON input. 1206 for (auto VT : {MVT::v8i8, MVT::v4i16}) 1207 setOperationAction(ISD::TRUNCATE, VT, Custom); 1208 setOperationAction(ISD::FP_ROUND, MVT::v4f16, Custom); 1209 1210 // 128bit results imply a bigger than NEON input. 1211 for (auto VT : {MVT::v16i8, MVT::v8i16, MVT::v4i32}) 1212 setOperationAction(ISD::TRUNCATE, VT, Custom); 1213 for (auto VT : {MVT::v8f16, MVT::v4f32}) 1214 setOperationAction(ISD::FP_ROUND, VT, Expand); 1215 1216 // These operations are not supported on NEON but SVE can do them. 1217 setOperationAction(ISD::BITREVERSE, MVT::v1i64, Custom); 1218 setOperationAction(ISD::CTLZ, MVT::v1i64, Custom); 1219 setOperationAction(ISD::CTLZ, MVT::v2i64, Custom); 1220 setOperationAction(ISD::CTTZ, MVT::v1i64, Custom); 1221 setOperationAction(ISD::MUL, MVT::v1i64, Custom); 1222 setOperationAction(ISD::MUL, MVT::v2i64, Custom); 1223 setOperationAction(ISD::SDIV, MVT::v8i8, Custom); 1224 setOperationAction(ISD::SDIV, MVT::v16i8, Custom); 1225 setOperationAction(ISD::SDIV, MVT::v4i16, Custom); 1226 setOperationAction(ISD::SDIV, MVT::v8i16, Custom); 1227 setOperationAction(ISD::SDIV, MVT::v2i32, Custom); 1228 setOperationAction(ISD::SDIV, MVT::v4i32, Custom); 1229 setOperationAction(ISD::SDIV, MVT::v1i64, Custom); 1230 setOperationAction(ISD::SDIV, MVT::v2i64, Custom); 1231 setOperationAction(ISD::SMAX, MVT::v1i64, Custom); 1232 setOperationAction(ISD::SMAX, MVT::v2i64, Custom); 1233 setOperationAction(ISD::SMIN, MVT::v1i64, Custom); 1234 setOperationAction(ISD::SMIN, MVT::v2i64, Custom); 1235 setOperationAction(ISD::UDIV, MVT::v8i8, Custom); 1236 setOperationAction(ISD::UDIV, MVT::v16i8, Custom); 1237 setOperationAction(ISD::UDIV, MVT::v4i16, Custom); 1238 setOperationAction(ISD::UDIV, MVT::v8i16, Custom); 1239 setOperationAction(ISD::UDIV, MVT::v2i32, Custom); 1240 setOperationAction(ISD::UDIV, MVT::v4i32, Custom); 1241 setOperationAction(ISD::UDIV, MVT::v1i64, Custom); 1242 setOperationAction(ISD::UDIV, MVT::v2i64, Custom); 1243 setOperationAction(ISD::UMAX, MVT::v1i64, Custom); 1244 setOperationAction(ISD::UMAX, MVT::v2i64, Custom); 1245 setOperationAction(ISD::UMIN, MVT::v1i64, Custom); 1246 setOperationAction(ISD::UMIN, MVT::v2i64, Custom); 1247 setOperationAction(ISD::VECREDUCE_SMAX, MVT::v2i64, Custom); 1248 setOperationAction(ISD::VECREDUCE_SMIN, MVT::v2i64, Custom); 1249 setOperationAction(ISD::VECREDUCE_UMAX, MVT::v2i64, Custom); 1250 setOperationAction(ISD::VECREDUCE_UMIN, MVT::v2i64, Custom); 1251 1252 // Int operations with no NEON support. 1253 for (auto VT : {MVT::v8i8, MVT::v16i8, MVT::v4i16, MVT::v8i16, 1254 MVT::v2i32, MVT::v4i32, MVT::v2i64}) { 1255 setOperationAction(ISD::BITREVERSE, VT, Custom); 1256 setOperationAction(ISD::CTTZ, VT, Custom); 1257 setOperationAction(ISD::VECREDUCE_AND, VT, Custom); 1258 setOperationAction(ISD::VECREDUCE_OR, VT, Custom); 1259 setOperationAction(ISD::VECREDUCE_XOR, VT, Custom); 1260 } 1261 1262 // FP operations with no NEON support. 1263 for (auto VT : {MVT::v4f16, MVT::v8f16, MVT::v2f32, MVT::v4f32, 1264 MVT::v1f64, MVT::v2f64}) 1265 setOperationAction(ISD::VECREDUCE_SEQ_FADD, VT, Custom); 1266 1267 // Use SVE for vectors with more than 2 elements. 1268 for (auto VT : {MVT::v4f16, MVT::v8f16, MVT::v4f32}) 1269 setOperationAction(ISD::VECREDUCE_FADD, VT, Custom); 1270 } 1271 } 1272 1273 PredictableSelectIsExpensive = Subtarget->predictableSelectIsExpensive(); 1274 } 1275 1276 void AArch64TargetLowering::addTypeForNEON(MVT VT, MVT PromotedBitwiseVT) { 1277 assert(VT.isVector() && "VT should be a vector type"); 1278 1279 if (VT.isFloatingPoint()) { 1280 MVT PromoteTo = EVT(VT).changeVectorElementTypeToInteger().getSimpleVT(); 1281 setOperationPromotedToType(ISD::LOAD, VT, PromoteTo); 1282 setOperationPromotedToType(ISD::STORE, VT, PromoteTo); 1283 } 1284 1285 // Mark vector float intrinsics as expand. 1286 if (VT == MVT::v2f32 || VT == MVT::v4f32 || VT == MVT::v2f64) { 1287 setOperationAction(ISD::FSIN, VT, Expand); 1288 setOperationAction(ISD::FCOS, VT, Expand); 1289 setOperationAction(ISD::FPOW, VT, Expand); 1290 setOperationAction(ISD::FLOG, VT, Expand); 1291 setOperationAction(ISD::FLOG2, VT, Expand); 1292 setOperationAction(ISD::FLOG10, VT, Expand); 1293 setOperationAction(ISD::FEXP, VT, Expand); 1294 setOperationAction(ISD::FEXP2, VT, Expand); 1295 1296 // But we do support custom-lowering for FCOPYSIGN. 1297 setOperationAction(ISD::FCOPYSIGN, VT, Custom); 1298 } 1299 1300 setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom); 1301 setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Custom); 1302 setOperationAction(ISD::BUILD_VECTOR, VT, Custom); 1303 setOperationAction(ISD::VECTOR_SHUFFLE, VT, Custom); 1304 setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Custom); 1305 setOperationAction(ISD::SRA, VT, Custom); 1306 setOperationAction(ISD::SRL, VT, Custom); 1307 setOperationAction(ISD::SHL, VT, Custom); 1308 setOperationAction(ISD::OR, VT, Custom); 1309 setOperationAction(ISD::SETCC, VT, Custom); 1310 setOperationAction(ISD::CONCAT_VECTORS, VT, Legal); 1311 1312 setOperationAction(ISD::SELECT, VT, Expand); 1313 setOperationAction(ISD::SELECT_CC, VT, Expand); 1314 setOperationAction(ISD::VSELECT, VT, Expand); 1315 for (MVT InnerVT : MVT::all_valuetypes()) 1316 setLoadExtAction(ISD::EXTLOAD, InnerVT, VT, Expand); 1317 1318 // CNT supports only B element sizes, then use UADDLP to widen. 1319 if (VT != MVT::v8i8 && VT != MVT::v16i8) 1320 setOperationAction(ISD::CTPOP, VT, Custom); 1321 1322 setOperationAction(ISD::UDIV, VT, Expand); 1323 setOperationAction(ISD::SDIV, VT, Expand); 1324 setOperationAction(ISD::UREM, VT, Expand); 1325 setOperationAction(ISD::SREM, VT, Expand); 1326 setOperationAction(ISD::FREM, VT, Expand); 1327 1328 setOperationAction(ISD::FP_TO_SINT, VT, Custom); 1329 setOperationAction(ISD::FP_TO_UINT, VT, Custom); 1330 1331 if (!VT.isFloatingPoint()) 1332 setOperationAction(ISD::ABS, VT, Legal); 1333 1334 // [SU][MIN|MAX] are available for all NEON types apart from i64. 1335 if (!VT.isFloatingPoint() && VT != MVT::v2i64 && VT != MVT::v1i64) 1336 for (unsigned Opcode : {ISD::SMIN, ISD::SMAX, ISD::UMIN, ISD::UMAX}) 1337 setOperationAction(Opcode, VT, Legal); 1338 1339 // F[MIN|MAX][NUM|NAN] are available for all FP NEON types. 1340 if (VT.isFloatingPoint() && 1341 VT.getVectorElementType() != MVT::bf16 && 1342 (VT.getVectorElementType() != MVT::f16 || Subtarget->hasFullFP16())) 1343 for (unsigned Opcode : 1344 {ISD::FMINIMUM, ISD::FMAXIMUM, ISD::FMINNUM, ISD::FMAXNUM}) 1345 setOperationAction(Opcode, VT, Legal); 1346 1347 if (Subtarget->isLittleEndian()) { 1348 for (unsigned im = (unsigned)ISD::PRE_INC; 1349 im != (unsigned)ISD::LAST_INDEXED_MODE; ++im) { 1350 setIndexedLoadAction(im, VT, Legal); 1351 setIndexedStoreAction(im, VT, Legal); 1352 } 1353 } 1354 } 1355 1356 void AArch64TargetLowering::addTypeForFixedLengthSVE(MVT VT) { 1357 assert(VT.isFixedLengthVector() && "Expected fixed length vector type!"); 1358 1359 // By default everything must be expanded. 1360 for (unsigned Op = 0; Op < ISD::BUILTIN_OP_END; ++Op) 1361 setOperationAction(Op, VT, Expand); 1362 1363 // We use EXTRACT_SUBVECTOR to "cast" a scalable vector to a fixed length one. 1364 setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Custom); 1365 1366 // Lower fixed length vector operations to scalable equivalents. 1367 setOperationAction(ISD::ABS, VT, Custom); 1368 setOperationAction(ISD::ADD, VT, Custom); 1369 setOperationAction(ISD::AND, VT, Custom); 1370 setOperationAction(ISD::ANY_EXTEND, VT, Custom); 1371 setOperationAction(ISD::BITREVERSE, VT, Custom); 1372 setOperationAction(ISD::BSWAP, VT, Custom); 1373 setOperationAction(ISD::CTLZ, VT, Custom); 1374 setOperationAction(ISD::CTPOP, VT, Custom); 1375 setOperationAction(ISD::CTTZ, VT, Custom); 1376 setOperationAction(ISD::FADD, VT, Custom); 1377 setOperationAction(ISD::FCEIL, VT, Custom); 1378 setOperationAction(ISD::FDIV, VT, Custom); 1379 setOperationAction(ISD::FFLOOR, VT, Custom); 1380 setOperationAction(ISD::FMA, VT, Custom); 1381 setOperationAction(ISD::FMAXNUM, VT, Custom); 1382 setOperationAction(ISD::FMINNUM, VT, Custom); 1383 setOperationAction(ISD::FMUL, VT, Custom); 1384 setOperationAction(ISD::FNEARBYINT, VT, Custom); 1385 setOperationAction(ISD::FNEG, VT, Custom); 1386 setOperationAction(ISD::FRINT, VT, Custom); 1387 setOperationAction(ISD::FROUND, VT, Custom); 1388 setOperationAction(ISD::FSQRT, VT, Custom); 1389 setOperationAction(ISD::FSUB, VT, Custom); 1390 setOperationAction(ISD::FTRUNC, VT, Custom); 1391 setOperationAction(ISD::LOAD, VT, Custom); 1392 setOperationAction(ISD::MUL, VT, Custom); 1393 setOperationAction(ISD::OR, VT, Custom); 1394 setOperationAction(ISD::SDIV, VT, Custom); 1395 setOperationAction(ISD::SETCC, VT, Custom); 1396 setOperationAction(ISD::SHL, VT, Custom); 1397 setOperationAction(ISD::SIGN_EXTEND, VT, Custom); 1398 setOperationAction(ISD::SIGN_EXTEND_INREG, VT, Custom); 1399 setOperationAction(ISD::SMAX, VT, Custom); 1400 setOperationAction(ISD::SMIN, VT, Custom); 1401 setOperationAction(ISD::SPLAT_VECTOR, VT, Custom); 1402 setOperationAction(ISD::SRA, VT, Custom); 1403 setOperationAction(ISD::SRL, VT, Custom); 1404 setOperationAction(ISD::STORE, VT, Custom); 1405 setOperationAction(ISD::SUB, VT, Custom); 1406 setOperationAction(ISD::TRUNCATE, VT, Custom); 1407 setOperationAction(ISD::UDIV, VT, Custom); 1408 setOperationAction(ISD::UMAX, VT, Custom); 1409 setOperationAction(ISD::UMIN, VT, Custom); 1410 setOperationAction(ISD::VECREDUCE_ADD, VT, Custom); 1411 setOperationAction(ISD::VECREDUCE_AND, VT, Custom); 1412 setOperationAction(ISD::VECREDUCE_FADD, VT, Custom); 1413 setOperationAction(ISD::VECREDUCE_SEQ_FADD, VT, Custom); 1414 setOperationAction(ISD::VECREDUCE_FMAX, VT, Custom); 1415 setOperationAction(ISD::VECREDUCE_FMIN, VT, Custom); 1416 setOperationAction(ISD::VECREDUCE_OR, VT, Custom); 1417 setOperationAction(ISD::VECREDUCE_SMAX, VT, Custom); 1418 setOperationAction(ISD::VECREDUCE_SMIN, VT, Custom); 1419 setOperationAction(ISD::VECREDUCE_UMAX, VT, Custom); 1420 setOperationAction(ISD::VECREDUCE_UMIN, VT, Custom); 1421 setOperationAction(ISD::VECREDUCE_XOR, VT, Custom); 1422 setOperationAction(ISD::VSELECT, VT, Custom); 1423 setOperationAction(ISD::XOR, VT, Custom); 1424 setOperationAction(ISD::ZERO_EXTEND, VT, Custom); 1425 } 1426 1427 void AArch64TargetLowering::addDRTypeForNEON(MVT VT) { 1428 addRegisterClass(VT, &AArch64::FPR64RegClass); 1429 addTypeForNEON(VT, MVT::v2i32); 1430 } 1431 1432 void AArch64TargetLowering::addQRTypeForNEON(MVT VT) { 1433 addRegisterClass(VT, &AArch64::FPR128RegClass); 1434 addTypeForNEON(VT, MVT::v4i32); 1435 } 1436 1437 EVT AArch64TargetLowering::getSetCCResultType(const DataLayout &, 1438 LLVMContext &C, EVT VT) const { 1439 if (!VT.isVector()) 1440 return MVT::i32; 1441 if (VT.isScalableVector()) 1442 return EVT::getVectorVT(C, MVT::i1, VT.getVectorElementCount()); 1443 return VT.changeVectorElementTypeToInteger(); 1444 } 1445 1446 static bool optimizeLogicalImm(SDValue Op, unsigned Size, uint64_t Imm, 1447 const APInt &Demanded, 1448 TargetLowering::TargetLoweringOpt &TLO, 1449 unsigned NewOpc) { 1450 uint64_t OldImm = Imm, NewImm, Enc; 1451 uint64_t Mask = ((uint64_t)(-1LL) >> (64 - Size)), OrigMask = Mask; 1452 1453 // Return if the immediate is already all zeros, all ones, a bimm32 or a 1454 // bimm64. 1455 if (Imm == 0 || Imm == Mask || 1456 AArch64_AM::isLogicalImmediate(Imm & Mask, Size)) 1457 return false; 1458 1459 unsigned EltSize = Size; 1460 uint64_t DemandedBits = Demanded.getZExtValue(); 1461 1462 // Clear bits that are not demanded. 1463 Imm &= DemandedBits; 1464 1465 while (true) { 1466 // The goal here is to set the non-demanded bits in a way that minimizes 1467 // the number of switching between 0 and 1. In order to achieve this goal, 1468 // we set the non-demanded bits to the value of the preceding demanded bits. 1469 // For example, if we have an immediate 0bx10xx0x1 ('x' indicates a 1470 // non-demanded bit), we copy bit0 (1) to the least significant 'x', 1471 // bit2 (0) to 'xx', and bit6 (1) to the most significant 'x'. 1472 // The final result is 0b11000011. 1473 uint64_t NonDemandedBits = ~DemandedBits; 1474 uint64_t InvertedImm = ~Imm & DemandedBits; 1475 uint64_t RotatedImm = 1476 ((InvertedImm << 1) | (InvertedImm >> (EltSize - 1) & 1)) & 1477 NonDemandedBits; 1478 uint64_t Sum = RotatedImm + NonDemandedBits; 1479 bool Carry = NonDemandedBits & ~Sum & (1ULL << (EltSize - 1)); 1480 uint64_t Ones = (Sum + Carry) & NonDemandedBits; 1481 NewImm = (Imm | Ones) & Mask; 1482 1483 // If NewImm or its bitwise NOT is a shifted mask, it is a bitmask immediate 1484 // or all-ones or all-zeros, in which case we can stop searching. Otherwise, 1485 // we halve the element size and continue the search. 1486 if (isShiftedMask_64(NewImm) || isShiftedMask_64(~(NewImm | ~Mask))) 1487 break; 1488 1489 // We cannot shrink the element size any further if it is 2-bits. 1490 if (EltSize == 2) 1491 return false; 1492 1493 EltSize /= 2; 1494 Mask >>= EltSize; 1495 uint64_t Hi = Imm >> EltSize, DemandedBitsHi = DemandedBits >> EltSize; 1496 1497 // Return if there is mismatch in any of the demanded bits of Imm and Hi. 1498 if (((Imm ^ Hi) & (DemandedBits & DemandedBitsHi) & Mask) != 0) 1499 return false; 1500 1501 // Merge the upper and lower halves of Imm and DemandedBits. 1502 Imm |= Hi; 1503 DemandedBits |= DemandedBitsHi; 1504 } 1505 1506 ++NumOptimizedImms; 1507 1508 // Replicate the element across the register width. 1509 while (EltSize < Size) { 1510 NewImm |= NewImm << EltSize; 1511 EltSize *= 2; 1512 } 1513 1514 (void)OldImm; 1515 assert(((OldImm ^ NewImm) & Demanded.getZExtValue()) == 0 && 1516 "demanded bits should never be altered"); 1517 assert(OldImm != NewImm && "the new imm shouldn't be equal to the old imm"); 1518 1519 // Create the new constant immediate node. 1520 EVT VT = Op.getValueType(); 1521 SDLoc DL(Op); 1522 SDValue New; 1523 1524 // If the new constant immediate is all-zeros or all-ones, let the target 1525 // independent DAG combine optimize this node. 1526 if (NewImm == 0 || NewImm == OrigMask) { 1527 New = TLO.DAG.getNode(Op.getOpcode(), DL, VT, Op.getOperand(0), 1528 TLO.DAG.getConstant(NewImm, DL, VT)); 1529 // Otherwise, create a machine node so that target independent DAG combine 1530 // doesn't undo this optimization. 1531 } else { 1532 Enc = AArch64_AM::encodeLogicalImmediate(NewImm, Size); 1533 SDValue EncConst = TLO.DAG.getTargetConstant(Enc, DL, VT); 1534 New = SDValue( 1535 TLO.DAG.getMachineNode(NewOpc, DL, VT, Op.getOperand(0), EncConst), 0); 1536 } 1537 1538 return TLO.CombineTo(Op, New); 1539 } 1540 1541 bool AArch64TargetLowering::targetShrinkDemandedConstant( 1542 SDValue Op, const APInt &DemandedBits, const APInt &DemandedElts, 1543 TargetLoweringOpt &TLO) const { 1544 // Delay this optimization to as late as possible. 1545 if (!TLO.LegalOps) 1546 return false; 1547 1548 if (!EnableOptimizeLogicalImm) 1549 return false; 1550 1551 EVT VT = Op.getValueType(); 1552 if (VT.isVector()) 1553 return false; 1554 1555 unsigned Size = VT.getSizeInBits(); 1556 assert((Size == 32 || Size == 64) && 1557 "i32 or i64 is expected after legalization."); 1558 1559 // Exit early if we demand all bits. 1560 if (DemandedBits.countPopulation() == Size) 1561 return false; 1562 1563 unsigned NewOpc; 1564 switch (Op.getOpcode()) { 1565 default: 1566 return false; 1567 case ISD::AND: 1568 NewOpc = Size == 32 ? AArch64::ANDWri : AArch64::ANDXri; 1569 break; 1570 case ISD::OR: 1571 NewOpc = Size == 32 ? AArch64::ORRWri : AArch64::ORRXri; 1572 break; 1573 case ISD::XOR: 1574 NewOpc = Size == 32 ? AArch64::EORWri : AArch64::EORXri; 1575 break; 1576 } 1577 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1)); 1578 if (!C) 1579 return false; 1580 uint64_t Imm = C->getZExtValue(); 1581 return optimizeLogicalImm(Op, Size, Imm, DemandedBits, TLO, NewOpc); 1582 } 1583 1584 /// computeKnownBitsForTargetNode - Determine which of the bits specified in 1585 /// Mask are known to be either zero or one and return them Known. 1586 void AArch64TargetLowering::computeKnownBitsForTargetNode( 1587 const SDValue Op, KnownBits &Known, 1588 const APInt &DemandedElts, const SelectionDAG &DAG, unsigned Depth) const { 1589 switch (Op.getOpcode()) { 1590 default: 1591 break; 1592 case AArch64ISD::CSEL: { 1593 KnownBits Known2; 1594 Known = DAG.computeKnownBits(Op->getOperand(0), Depth + 1); 1595 Known2 = DAG.computeKnownBits(Op->getOperand(1), Depth + 1); 1596 Known = KnownBits::commonBits(Known, Known2); 1597 break; 1598 } 1599 case AArch64ISD::LOADgot: 1600 case AArch64ISD::ADDlow: { 1601 if (!Subtarget->isTargetILP32()) 1602 break; 1603 // In ILP32 mode all valid pointers are in the low 4GB of the address-space. 1604 Known.Zero = APInt::getHighBitsSet(64, 32); 1605 break; 1606 } 1607 case ISD::INTRINSIC_W_CHAIN: { 1608 ConstantSDNode *CN = cast<ConstantSDNode>(Op->getOperand(1)); 1609 Intrinsic::ID IntID = static_cast<Intrinsic::ID>(CN->getZExtValue()); 1610 switch (IntID) { 1611 default: return; 1612 case Intrinsic::aarch64_ldaxr: 1613 case Intrinsic::aarch64_ldxr: { 1614 unsigned BitWidth = Known.getBitWidth(); 1615 EVT VT = cast<MemIntrinsicSDNode>(Op)->getMemoryVT(); 1616 unsigned MemBits = VT.getScalarSizeInBits(); 1617 Known.Zero |= APInt::getHighBitsSet(BitWidth, BitWidth - MemBits); 1618 return; 1619 } 1620 } 1621 break; 1622 } 1623 case ISD::INTRINSIC_WO_CHAIN: 1624 case ISD::INTRINSIC_VOID: { 1625 unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue(); 1626 switch (IntNo) { 1627 default: 1628 break; 1629 case Intrinsic::aarch64_neon_umaxv: 1630 case Intrinsic::aarch64_neon_uminv: { 1631 // Figure out the datatype of the vector operand. The UMINV instruction 1632 // will zero extend the result, so we can mark as known zero all the 1633 // bits larger than the element datatype. 32-bit or larget doesn't need 1634 // this as those are legal types and will be handled by isel directly. 1635 MVT VT = Op.getOperand(1).getValueType().getSimpleVT(); 1636 unsigned BitWidth = Known.getBitWidth(); 1637 if (VT == MVT::v8i8 || VT == MVT::v16i8) { 1638 assert(BitWidth >= 8 && "Unexpected width!"); 1639 APInt Mask = APInt::getHighBitsSet(BitWidth, BitWidth - 8); 1640 Known.Zero |= Mask; 1641 } else if (VT == MVT::v4i16 || VT == MVT::v8i16) { 1642 assert(BitWidth >= 16 && "Unexpected width!"); 1643 APInt Mask = APInt::getHighBitsSet(BitWidth, BitWidth - 16); 1644 Known.Zero |= Mask; 1645 } 1646 break; 1647 } break; 1648 } 1649 } 1650 } 1651 } 1652 1653 MVT AArch64TargetLowering::getScalarShiftAmountTy(const DataLayout &DL, 1654 EVT) const { 1655 return MVT::i64; 1656 } 1657 1658 bool AArch64TargetLowering::allowsMisalignedMemoryAccesses( 1659 EVT VT, unsigned AddrSpace, Align Alignment, MachineMemOperand::Flags Flags, 1660 bool *Fast) const { 1661 if (Subtarget->requiresStrictAlign()) 1662 return false; 1663 1664 if (Fast) { 1665 // Some CPUs are fine with unaligned stores except for 128-bit ones. 1666 *Fast = !Subtarget->isMisaligned128StoreSlow() || VT.getStoreSize() != 16 || 1667 // See comments in performSTORECombine() for more details about 1668 // these conditions. 1669 1670 // Code that uses clang vector extensions can mark that it 1671 // wants unaligned accesses to be treated as fast by 1672 // underspecifying alignment to be 1 or 2. 1673 Alignment <= 2 || 1674 1675 // Disregard v2i64. Memcpy lowering produces those and splitting 1676 // them regresses performance on micro-benchmarks and olden/bh. 1677 VT == MVT::v2i64; 1678 } 1679 return true; 1680 } 1681 1682 // Same as above but handling LLTs instead. 1683 bool AArch64TargetLowering::allowsMisalignedMemoryAccesses( 1684 LLT Ty, unsigned AddrSpace, Align Alignment, MachineMemOperand::Flags Flags, 1685 bool *Fast) const { 1686 if (Subtarget->requiresStrictAlign()) 1687 return false; 1688 1689 if (Fast) { 1690 // Some CPUs are fine with unaligned stores except for 128-bit ones. 1691 *Fast = !Subtarget->isMisaligned128StoreSlow() || 1692 Ty.getSizeInBytes() != 16 || 1693 // See comments in performSTORECombine() for more details about 1694 // these conditions. 1695 1696 // Code that uses clang vector extensions can mark that it 1697 // wants unaligned accesses to be treated as fast by 1698 // underspecifying alignment to be 1 or 2. 1699 Alignment <= 2 || 1700 1701 // Disregard v2i64. Memcpy lowering produces those and splitting 1702 // them regresses performance on micro-benchmarks and olden/bh. 1703 Ty == LLT::vector(2, 64); 1704 } 1705 return true; 1706 } 1707 1708 FastISel * 1709 AArch64TargetLowering::createFastISel(FunctionLoweringInfo &funcInfo, 1710 const TargetLibraryInfo *libInfo) const { 1711 return AArch64::createFastISel(funcInfo, libInfo); 1712 } 1713 1714 const char *AArch64TargetLowering::getTargetNodeName(unsigned Opcode) const { 1715 #define MAKE_CASE(V) \ 1716 case V: \ 1717 return #V; 1718 switch ((AArch64ISD::NodeType)Opcode) { 1719 case AArch64ISD::FIRST_NUMBER: 1720 break; 1721 MAKE_CASE(AArch64ISD::CALL) 1722 MAKE_CASE(AArch64ISD::ADRP) 1723 MAKE_CASE(AArch64ISD::ADR) 1724 MAKE_CASE(AArch64ISD::ADDlow) 1725 MAKE_CASE(AArch64ISD::LOADgot) 1726 MAKE_CASE(AArch64ISD::RET_FLAG) 1727 MAKE_CASE(AArch64ISD::BRCOND) 1728 MAKE_CASE(AArch64ISD::CSEL) 1729 MAKE_CASE(AArch64ISD::FCSEL) 1730 MAKE_CASE(AArch64ISD::CSINV) 1731 MAKE_CASE(AArch64ISD::CSNEG) 1732 MAKE_CASE(AArch64ISD::CSINC) 1733 MAKE_CASE(AArch64ISD::THREAD_POINTER) 1734 MAKE_CASE(AArch64ISD::TLSDESC_CALLSEQ) 1735 MAKE_CASE(AArch64ISD::ADD_PRED) 1736 MAKE_CASE(AArch64ISD::MUL_PRED) 1737 MAKE_CASE(AArch64ISD::SDIV_PRED) 1738 MAKE_CASE(AArch64ISD::SHL_PRED) 1739 MAKE_CASE(AArch64ISD::SMAX_PRED) 1740 MAKE_CASE(AArch64ISD::SMIN_PRED) 1741 MAKE_CASE(AArch64ISD::SRA_PRED) 1742 MAKE_CASE(AArch64ISD::SRL_PRED) 1743 MAKE_CASE(AArch64ISD::SUB_PRED) 1744 MAKE_CASE(AArch64ISD::UDIV_PRED) 1745 MAKE_CASE(AArch64ISD::UMAX_PRED) 1746 MAKE_CASE(AArch64ISD::UMIN_PRED) 1747 MAKE_CASE(AArch64ISD::FNEG_MERGE_PASSTHRU) 1748 MAKE_CASE(AArch64ISD::SIGN_EXTEND_INREG_MERGE_PASSTHRU) 1749 MAKE_CASE(AArch64ISD::ZERO_EXTEND_INREG_MERGE_PASSTHRU) 1750 MAKE_CASE(AArch64ISD::FCEIL_MERGE_PASSTHRU) 1751 MAKE_CASE(AArch64ISD::FFLOOR_MERGE_PASSTHRU) 1752 MAKE_CASE(AArch64ISD::FNEARBYINT_MERGE_PASSTHRU) 1753 MAKE_CASE(AArch64ISD::FRINT_MERGE_PASSTHRU) 1754 MAKE_CASE(AArch64ISD::FROUND_MERGE_PASSTHRU) 1755 MAKE_CASE(AArch64ISD::FROUNDEVEN_MERGE_PASSTHRU) 1756 MAKE_CASE(AArch64ISD::FTRUNC_MERGE_PASSTHRU) 1757 MAKE_CASE(AArch64ISD::FP_ROUND_MERGE_PASSTHRU) 1758 MAKE_CASE(AArch64ISD::FP_EXTEND_MERGE_PASSTHRU) 1759 MAKE_CASE(AArch64ISD::SINT_TO_FP_MERGE_PASSTHRU) 1760 MAKE_CASE(AArch64ISD::UINT_TO_FP_MERGE_PASSTHRU) 1761 MAKE_CASE(AArch64ISD::FCVTZU_MERGE_PASSTHRU) 1762 MAKE_CASE(AArch64ISD::FCVTZS_MERGE_PASSTHRU) 1763 MAKE_CASE(AArch64ISD::FSQRT_MERGE_PASSTHRU) 1764 MAKE_CASE(AArch64ISD::FRECPX_MERGE_PASSTHRU) 1765 MAKE_CASE(AArch64ISD::FABS_MERGE_PASSTHRU) 1766 MAKE_CASE(AArch64ISD::ABS_MERGE_PASSTHRU) 1767 MAKE_CASE(AArch64ISD::NEG_MERGE_PASSTHRU) 1768 MAKE_CASE(AArch64ISD::SETCC_MERGE_ZERO) 1769 MAKE_CASE(AArch64ISD::ADC) 1770 MAKE_CASE(AArch64ISD::SBC) 1771 MAKE_CASE(AArch64ISD::ADDS) 1772 MAKE_CASE(AArch64ISD::SUBS) 1773 MAKE_CASE(AArch64ISD::ADCS) 1774 MAKE_CASE(AArch64ISD::SBCS) 1775 MAKE_CASE(AArch64ISD::ANDS) 1776 MAKE_CASE(AArch64ISD::CCMP) 1777 MAKE_CASE(AArch64ISD::CCMN) 1778 MAKE_CASE(AArch64ISD::FCCMP) 1779 MAKE_CASE(AArch64ISD::FCMP) 1780 MAKE_CASE(AArch64ISD::STRICT_FCMP) 1781 MAKE_CASE(AArch64ISD::STRICT_FCMPE) 1782 MAKE_CASE(AArch64ISD::DUP) 1783 MAKE_CASE(AArch64ISD::DUPLANE8) 1784 MAKE_CASE(AArch64ISD::DUPLANE16) 1785 MAKE_CASE(AArch64ISD::DUPLANE32) 1786 MAKE_CASE(AArch64ISD::DUPLANE64) 1787 MAKE_CASE(AArch64ISD::MOVI) 1788 MAKE_CASE(AArch64ISD::MOVIshift) 1789 MAKE_CASE(AArch64ISD::MOVIedit) 1790 MAKE_CASE(AArch64ISD::MOVImsl) 1791 MAKE_CASE(AArch64ISD::FMOV) 1792 MAKE_CASE(AArch64ISD::MVNIshift) 1793 MAKE_CASE(AArch64ISD::MVNImsl) 1794 MAKE_CASE(AArch64ISD::BICi) 1795 MAKE_CASE(AArch64ISD::ORRi) 1796 MAKE_CASE(AArch64ISD::BSP) 1797 MAKE_CASE(AArch64ISD::NEG) 1798 MAKE_CASE(AArch64ISD::EXTR) 1799 MAKE_CASE(AArch64ISD::ZIP1) 1800 MAKE_CASE(AArch64ISD::ZIP2) 1801 MAKE_CASE(AArch64ISD::UZP1) 1802 MAKE_CASE(AArch64ISD::UZP2) 1803 MAKE_CASE(AArch64ISD::TRN1) 1804 MAKE_CASE(AArch64ISD::TRN2) 1805 MAKE_CASE(AArch64ISD::REV16) 1806 MAKE_CASE(AArch64ISD::REV32) 1807 MAKE_CASE(AArch64ISD::REV64) 1808 MAKE_CASE(AArch64ISD::EXT) 1809 MAKE_CASE(AArch64ISD::VSHL) 1810 MAKE_CASE(AArch64ISD::VLSHR) 1811 MAKE_CASE(AArch64ISD::VASHR) 1812 MAKE_CASE(AArch64ISD::VSLI) 1813 MAKE_CASE(AArch64ISD::VSRI) 1814 MAKE_CASE(AArch64ISD::CMEQ) 1815 MAKE_CASE(AArch64ISD::CMGE) 1816 MAKE_CASE(AArch64ISD::CMGT) 1817 MAKE_CASE(AArch64ISD::CMHI) 1818 MAKE_CASE(AArch64ISD::CMHS) 1819 MAKE_CASE(AArch64ISD::FCMEQ) 1820 MAKE_CASE(AArch64ISD::FCMGE) 1821 MAKE_CASE(AArch64ISD::FCMGT) 1822 MAKE_CASE(AArch64ISD::CMEQz) 1823 MAKE_CASE(AArch64ISD::CMGEz) 1824 MAKE_CASE(AArch64ISD::CMGTz) 1825 MAKE_CASE(AArch64ISD::CMLEz) 1826 MAKE_CASE(AArch64ISD::CMLTz) 1827 MAKE_CASE(AArch64ISD::FCMEQz) 1828 MAKE_CASE(AArch64ISD::FCMGEz) 1829 MAKE_CASE(AArch64ISD::FCMGTz) 1830 MAKE_CASE(AArch64ISD::FCMLEz) 1831 MAKE_CASE(AArch64ISD::FCMLTz) 1832 MAKE_CASE(AArch64ISD::SADDV) 1833 MAKE_CASE(AArch64ISD::UADDV) 1834 MAKE_CASE(AArch64ISD::SRHADD) 1835 MAKE_CASE(AArch64ISD::URHADD) 1836 MAKE_CASE(AArch64ISD::SHADD) 1837 MAKE_CASE(AArch64ISD::UHADD) 1838 MAKE_CASE(AArch64ISD::SMINV) 1839 MAKE_CASE(AArch64ISD::UMINV) 1840 MAKE_CASE(AArch64ISD::SMAXV) 1841 MAKE_CASE(AArch64ISD::UMAXV) 1842 MAKE_CASE(AArch64ISD::SADDV_PRED) 1843 MAKE_CASE(AArch64ISD::UADDV_PRED) 1844 MAKE_CASE(AArch64ISD::SMAXV_PRED) 1845 MAKE_CASE(AArch64ISD::UMAXV_PRED) 1846 MAKE_CASE(AArch64ISD::SMINV_PRED) 1847 MAKE_CASE(AArch64ISD::UMINV_PRED) 1848 MAKE_CASE(AArch64ISD::ORV_PRED) 1849 MAKE_CASE(AArch64ISD::EORV_PRED) 1850 MAKE_CASE(AArch64ISD::ANDV_PRED) 1851 MAKE_CASE(AArch64ISD::CLASTA_N) 1852 MAKE_CASE(AArch64ISD::CLASTB_N) 1853 MAKE_CASE(AArch64ISD::LASTA) 1854 MAKE_CASE(AArch64ISD::LASTB) 1855 MAKE_CASE(AArch64ISD::REV) 1856 MAKE_CASE(AArch64ISD::REINTERPRET_CAST) 1857 MAKE_CASE(AArch64ISD::TBL) 1858 MAKE_CASE(AArch64ISD::FADD_PRED) 1859 MAKE_CASE(AArch64ISD::FADDA_PRED) 1860 MAKE_CASE(AArch64ISD::FADDV_PRED) 1861 MAKE_CASE(AArch64ISD::FDIV_PRED) 1862 MAKE_CASE(AArch64ISD::FMA_PRED) 1863 MAKE_CASE(AArch64ISD::FMAXV_PRED) 1864 MAKE_CASE(AArch64ISD::FMAXNM_PRED) 1865 MAKE_CASE(AArch64ISD::FMAXNMV_PRED) 1866 MAKE_CASE(AArch64ISD::FMINV_PRED) 1867 MAKE_CASE(AArch64ISD::FMINNM_PRED) 1868 MAKE_CASE(AArch64ISD::FMINNMV_PRED) 1869 MAKE_CASE(AArch64ISD::FMUL_PRED) 1870 MAKE_CASE(AArch64ISD::FSUB_PRED) 1871 MAKE_CASE(AArch64ISD::BIT) 1872 MAKE_CASE(AArch64ISD::CBZ) 1873 MAKE_CASE(AArch64ISD::CBNZ) 1874 MAKE_CASE(AArch64ISD::TBZ) 1875 MAKE_CASE(AArch64ISD::TBNZ) 1876 MAKE_CASE(AArch64ISD::TC_RETURN) 1877 MAKE_CASE(AArch64ISD::PREFETCH) 1878 MAKE_CASE(AArch64ISD::SITOF) 1879 MAKE_CASE(AArch64ISD::UITOF) 1880 MAKE_CASE(AArch64ISD::NVCAST) 1881 MAKE_CASE(AArch64ISD::SQSHL_I) 1882 MAKE_CASE(AArch64ISD::UQSHL_I) 1883 MAKE_CASE(AArch64ISD::SRSHR_I) 1884 MAKE_CASE(AArch64ISD::URSHR_I) 1885 MAKE_CASE(AArch64ISD::SQSHLU_I) 1886 MAKE_CASE(AArch64ISD::WrapperLarge) 1887 MAKE_CASE(AArch64ISD::LD2post) 1888 MAKE_CASE(AArch64ISD::LD3post) 1889 MAKE_CASE(AArch64ISD::LD4post) 1890 MAKE_CASE(AArch64ISD::ST2post) 1891 MAKE_CASE(AArch64ISD::ST3post) 1892 MAKE_CASE(AArch64ISD::ST4post) 1893 MAKE_CASE(AArch64ISD::LD1x2post) 1894 MAKE_CASE(AArch64ISD::LD1x3post) 1895 MAKE_CASE(AArch64ISD::LD1x4post) 1896 MAKE_CASE(AArch64ISD::ST1x2post) 1897 MAKE_CASE(AArch64ISD::ST1x3post) 1898 MAKE_CASE(AArch64ISD::ST1x4post) 1899 MAKE_CASE(AArch64ISD::LD1DUPpost) 1900 MAKE_CASE(AArch64ISD::LD2DUPpost) 1901 MAKE_CASE(AArch64ISD::LD3DUPpost) 1902 MAKE_CASE(AArch64ISD::LD4DUPpost) 1903 MAKE_CASE(AArch64ISD::LD1LANEpost) 1904 MAKE_CASE(AArch64ISD::LD2LANEpost) 1905 MAKE_CASE(AArch64ISD::LD3LANEpost) 1906 MAKE_CASE(AArch64ISD::LD4LANEpost) 1907 MAKE_CASE(AArch64ISD::ST2LANEpost) 1908 MAKE_CASE(AArch64ISD::ST3LANEpost) 1909 MAKE_CASE(AArch64ISD::ST4LANEpost) 1910 MAKE_CASE(AArch64ISD::SMULL) 1911 MAKE_CASE(AArch64ISD::UMULL) 1912 MAKE_CASE(AArch64ISD::FRECPE) 1913 MAKE_CASE(AArch64ISD::FRECPS) 1914 MAKE_CASE(AArch64ISD::FRSQRTE) 1915 MAKE_CASE(AArch64ISD::FRSQRTS) 1916 MAKE_CASE(AArch64ISD::STG) 1917 MAKE_CASE(AArch64ISD::STZG) 1918 MAKE_CASE(AArch64ISD::ST2G) 1919 MAKE_CASE(AArch64ISD::STZ2G) 1920 MAKE_CASE(AArch64ISD::SUNPKHI) 1921 MAKE_CASE(AArch64ISD::SUNPKLO) 1922 MAKE_CASE(AArch64ISD::UUNPKHI) 1923 MAKE_CASE(AArch64ISD::UUNPKLO) 1924 MAKE_CASE(AArch64ISD::INSR) 1925 MAKE_CASE(AArch64ISD::PTEST) 1926 MAKE_CASE(AArch64ISD::PTRUE) 1927 MAKE_CASE(AArch64ISD::LD1_MERGE_ZERO) 1928 MAKE_CASE(AArch64ISD::LD1S_MERGE_ZERO) 1929 MAKE_CASE(AArch64ISD::LDNF1_MERGE_ZERO) 1930 MAKE_CASE(AArch64ISD::LDNF1S_MERGE_ZERO) 1931 MAKE_CASE(AArch64ISD::LDFF1_MERGE_ZERO) 1932 MAKE_CASE(AArch64ISD::LDFF1S_MERGE_ZERO) 1933 MAKE_CASE(AArch64ISD::LD1RQ_MERGE_ZERO) 1934 MAKE_CASE(AArch64ISD::LD1RO_MERGE_ZERO) 1935 MAKE_CASE(AArch64ISD::SVE_LD2_MERGE_ZERO) 1936 MAKE_CASE(AArch64ISD::SVE_LD3_MERGE_ZERO) 1937 MAKE_CASE(AArch64ISD::SVE_LD4_MERGE_ZERO) 1938 MAKE_CASE(AArch64ISD::GLD1_MERGE_ZERO) 1939 MAKE_CASE(AArch64ISD::GLD1_SCALED_MERGE_ZERO) 1940 MAKE_CASE(AArch64ISD::GLD1_SXTW_MERGE_ZERO) 1941 MAKE_CASE(AArch64ISD::GLD1_UXTW_MERGE_ZERO) 1942 MAKE_CASE(AArch64ISD::GLD1_SXTW_SCALED_MERGE_ZERO) 1943 MAKE_CASE(AArch64ISD::GLD1_UXTW_SCALED_MERGE_ZERO) 1944 MAKE_CASE(AArch64ISD::GLD1_IMM_MERGE_ZERO) 1945 MAKE_CASE(AArch64ISD::GLD1S_MERGE_ZERO) 1946 MAKE_CASE(AArch64ISD::GLD1S_SCALED_MERGE_ZERO) 1947 MAKE_CASE(AArch64ISD::GLD1S_SXTW_MERGE_ZERO) 1948 MAKE_CASE(AArch64ISD::GLD1S_UXTW_MERGE_ZERO) 1949 MAKE_CASE(AArch64ISD::GLD1S_SXTW_SCALED_MERGE_ZERO) 1950 MAKE_CASE(AArch64ISD::GLD1S_UXTW_SCALED_MERGE_ZERO) 1951 MAKE_CASE(AArch64ISD::GLD1S_IMM_MERGE_ZERO) 1952 MAKE_CASE(AArch64ISD::GLDFF1_MERGE_ZERO) 1953 MAKE_CASE(AArch64ISD::GLDFF1_SCALED_MERGE_ZERO) 1954 MAKE_CASE(AArch64ISD::GLDFF1_SXTW_MERGE_ZERO) 1955 MAKE_CASE(AArch64ISD::GLDFF1_UXTW_MERGE_ZERO) 1956 MAKE_CASE(AArch64ISD::GLDFF1_SXTW_SCALED_MERGE_ZERO) 1957 MAKE_CASE(AArch64ISD::GLDFF1_UXTW_SCALED_MERGE_ZERO) 1958 MAKE_CASE(AArch64ISD::GLDFF1_IMM_MERGE_ZERO) 1959 MAKE_CASE(AArch64ISD::GLDFF1S_MERGE_ZERO) 1960 MAKE_CASE(AArch64ISD::GLDFF1S_SCALED_MERGE_ZERO) 1961 MAKE_CASE(AArch64ISD::GLDFF1S_SXTW_MERGE_ZERO) 1962 MAKE_CASE(AArch64ISD::GLDFF1S_UXTW_MERGE_ZERO) 1963 MAKE_CASE(AArch64ISD::GLDFF1S_SXTW_SCALED_MERGE_ZERO) 1964 MAKE_CASE(AArch64ISD::GLDFF1S_UXTW_SCALED_MERGE_ZERO) 1965 MAKE_CASE(AArch64ISD::GLDFF1S_IMM_MERGE_ZERO) 1966 MAKE_CASE(AArch64ISD::GLDNT1_MERGE_ZERO) 1967 MAKE_CASE(AArch64ISD::GLDNT1_INDEX_MERGE_ZERO) 1968 MAKE_CASE(AArch64ISD::GLDNT1S_MERGE_ZERO) 1969 MAKE_CASE(AArch64ISD::ST1_PRED) 1970 MAKE_CASE(AArch64ISD::SST1_PRED) 1971 MAKE_CASE(AArch64ISD::SST1_SCALED_PRED) 1972 MAKE_CASE(AArch64ISD::SST1_SXTW_PRED) 1973 MAKE_CASE(AArch64ISD::SST1_UXTW_PRED) 1974 MAKE_CASE(AArch64ISD::SST1_SXTW_SCALED_PRED) 1975 MAKE_CASE(AArch64ISD::SST1_UXTW_SCALED_PRED) 1976 MAKE_CASE(AArch64ISD::SST1_IMM_PRED) 1977 MAKE_CASE(AArch64ISD::SSTNT1_PRED) 1978 MAKE_CASE(AArch64ISD::SSTNT1_INDEX_PRED) 1979 MAKE_CASE(AArch64ISD::LDP) 1980 MAKE_CASE(AArch64ISD::STP) 1981 MAKE_CASE(AArch64ISD::STNP) 1982 MAKE_CASE(AArch64ISD::BITREVERSE_MERGE_PASSTHRU) 1983 MAKE_CASE(AArch64ISD::BSWAP_MERGE_PASSTHRU) 1984 MAKE_CASE(AArch64ISD::CTLZ_MERGE_PASSTHRU) 1985 MAKE_CASE(AArch64ISD::CTPOP_MERGE_PASSTHRU) 1986 MAKE_CASE(AArch64ISD::DUP_MERGE_PASSTHRU) 1987 MAKE_CASE(AArch64ISD::INDEX_VECTOR) 1988 MAKE_CASE(AArch64ISD::UABD) 1989 MAKE_CASE(AArch64ISD::SABD) 1990 MAKE_CASE(AArch64ISD::CALL_RVMARKER) 1991 } 1992 #undef MAKE_CASE 1993 return nullptr; 1994 } 1995 1996 MachineBasicBlock * 1997 AArch64TargetLowering::EmitF128CSEL(MachineInstr &MI, 1998 MachineBasicBlock *MBB) const { 1999 // We materialise the F128CSEL pseudo-instruction as some control flow and a 2000 // phi node: 2001 2002 // OrigBB: 2003 // [... previous instrs leading to comparison ...] 2004 // b.ne TrueBB 2005 // b EndBB 2006 // TrueBB: 2007 // ; Fallthrough 2008 // EndBB: 2009 // Dest = PHI [IfTrue, TrueBB], [IfFalse, OrigBB] 2010 2011 MachineFunction *MF = MBB->getParent(); 2012 const TargetInstrInfo *TII = Subtarget->getInstrInfo(); 2013 const BasicBlock *LLVM_BB = MBB->getBasicBlock(); 2014 DebugLoc DL = MI.getDebugLoc(); 2015 MachineFunction::iterator It = ++MBB->getIterator(); 2016 2017 Register DestReg = MI.getOperand(0).getReg(); 2018 Register IfTrueReg = MI.getOperand(1).getReg(); 2019 Register IfFalseReg = MI.getOperand(2).getReg(); 2020 unsigned CondCode = MI.getOperand(3).getImm(); 2021 bool NZCVKilled = MI.getOperand(4).isKill(); 2022 2023 MachineBasicBlock *TrueBB = MF->CreateMachineBasicBlock(LLVM_BB); 2024 MachineBasicBlock *EndBB = MF->CreateMachineBasicBlock(LLVM_BB); 2025 MF->insert(It, TrueBB); 2026 MF->insert(It, EndBB); 2027 2028 // Transfer rest of current basic-block to EndBB 2029 EndBB->splice(EndBB->begin(), MBB, std::next(MachineBasicBlock::iterator(MI)), 2030 MBB->end()); 2031 EndBB->transferSuccessorsAndUpdatePHIs(MBB); 2032 2033 BuildMI(MBB, DL, TII->get(AArch64::Bcc)).addImm(CondCode).addMBB(TrueBB); 2034 BuildMI(MBB, DL, TII->get(AArch64::B)).addMBB(EndBB); 2035 MBB->addSuccessor(TrueBB); 2036 MBB->addSuccessor(EndBB); 2037 2038 // TrueBB falls through to the end. 2039 TrueBB->addSuccessor(EndBB); 2040 2041 if (!NZCVKilled) { 2042 TrueBB->addLiveIn(AArch64::NZCV); 2043 EndBB->addLiveIn(AArch64::NZCV); 2044 } 2045 2046 BuildMI(*EndBB, EndBB->begin(), DL, TII->get(AArch64::PHI), DestReg) 2047 .addReg(IfTrueReg) 2048 .addMBB(TrueBB) 2049 .addReg(IfFalseReg) 2050 .addMBB(MBB); 2051 2052 MI.eraseFromParent(); 2053 return EndBB; 2054 } 2055 2056 MachineBasicBlock *AArch64TargetLowering::EmitLoweredCatchRet( 2057 MachineInstr &MI, MachineBasicBlock *BB) const { 2058 assert(!isAsynchronousEHPersonality(classifyEHPersonality( 2059 BB->getParent()->getFunction().getPersonalityFn())) && 2060 "SEH does not use catchret!"); 2061 return BB; 2062 } 2063 2064 MachineBasicBlock *AArch64TargetLowering::EmitInstrWithCustomInserter( 2065 MachineInstr &MI, MachineBasicBlock *BB) const { 2066 switch (MI.getOpcode()) { 2067 default: 2068 #ifndef NDEBUG 2069 MI.dump(); 2070 #endif 2071 llvm_unreachable("Unexpected instruction for custom inserter!"); 2072 2073 case AArch64::F128CSEL: 2074 return EmitF128CSEL(MI, BB); 2075 2076 case TargetOpcode::STACKMAP: 2077 case TargetOpcode::PATCHPOINT: 2078 case TargetOpcode::STATEPOINT: 2079 return emitPatchPoint(MI, BB); 2080 2081 case AArch64::CATCHRET: 2082 return EmitLoweredCatchRet(MI, BB); 2083 } 2084 } 2085 2086 //===----------------------------------------------------------------------===// 2087 // AArch64 Lowering private implementation. 2088 //===----------------------------------------------------------------------===// 2089 2090 //===----------------------------------------------------------------------===// 2091 // Lowering Code 2092 //===----------------------------------------------------------------------===// 2093 2094 /// changeIntCCToAArch64CC - Convert a DAG integer condition code to an AArch64 2095 /// CC 2096 static AArch64CC::CondCode changeIntCCToAArch64CC(ISD::CondCode CC) { 2097 switch (CC) { 2098 default: 2099 llvm_unreachable("Unknown condition code!"); 2100 case ISD::SETNE: 2101 return AArch64CC::NE; 2102 case ISD::SETEQ: 2103 return AArch64CC::EQ; 2104 case ISD::SETGT: 2105 return AArch64CC::GT; 2106 case ISD::SETGE: 2107 return AArch64CC::GE; 2108 case ISD::SETLT: 2109 return AArch64CC::LT; 2110 case ISD::SETLE: 2111 return AArch64CC::LE; 2112 case ISD::SETUGT: 2113 return AArch64CC::HI; 2114 case ISD::SETUGE: 2115 return AArch64CC::HS; 2116 case ISD::SETULT: 2117 return AArch64CC::LO; 2118 case ISD::SETULE: 2119 return AArch64CC::LS; 2120 } 2121 } 2122 2123 /// changeFPCCToAArch64CC - Convert a DAG fp condition code to an AArch64 CC. 2124 static void changeFPCCToAArch64CC(ISD::CondCode CC, 2125 AArch64CC::CondCode &CondCode, 2126 AArch64CC::CondCode &CondCode2) { 2127 CondCode2 = AArch64CC::AL; 2128 switch (CC) { 2129 default: 2130 llvm_unreachable("Unknown FP condition!"); 2131 case ISD::SETEQ: 2132 case ISD::SETOEQ: 2133 CondCode = AArch64CC::EQ; 2134 break; 2135 case ISD::SETGT: 2136 case ISD::SETOGT: 2137 CondCode = AArch64CC::GT; 2138 break; 2139 case ISD::SETGE: 2140 case ISD::SETOGE: 2141 CondCode = AArch64CC::GE; 2142 break; 2143 case ISD::SETOLT: 2144 CondCode = AArch64CC::MI; 2145 break; 2146 case ISD::SETOLE: 2147 CondCode = AArch64CC::LS; 2148 break; 2149 case ISD::SETONE: 2150 CondCode = AArch64CC::MI; 2151 CondCode2 = AArch64CC::GT; 2152 break; 2153 case ISD::SETO: 2154 CondCode = AArch64CC::VC; 2155 break; 2156 case ISD::SETUO: 2157 CondCode = AArch64CC::VS; 2158 break; 2159 case ISD::SETUEQ: 2160 CondCode = AArch64CC::EQ; 2161 CondCode2 = AArch64CC::VS; 2162 break; 2163 case ISD::SETUGT: 2164 CondCode = AArch64CC::HI; 2165 break; 2166 case ISD::SETUGE: 2167 CondCode = AArch64CC::PL; 2168 break; 2169 case ISD::SETLT: 2170 case ISD::SETULT: 2171 CondCode = AArch64CC::LT; 2172 break; 2173 case ISD::SETLE: 2174 case ISD::SETULE: 2175 CondCode = AArch64CC::LE; 2176 break; 2177 case ISD::SETNE: 2178 case ISD::SETUNE: 2179 CondCode = AArch64CC::NE; 2180 break; 2181 } 2182 } 2183 2184 /// Convert a DAG fp condition code to an AArch64 CC. 2185 /// This differs from changeFPCCToAArch64CC in that it returns cond codes that 2186 /// should be AND'ed instead of OR'ed. 2187 static void changeFPCCToANDAArch64CC(ISD::CondCode CC, 2188 AArch64CC::CondCode &CondCode, 2189 AArch64CC::CondCode &CondCode2) { 2190 CondCode2 = AArch64CC::AL; 2191 switch (CC) { 2192 default: 2193 changeFPCCToAArch64CC(CC, CondCode, CondCode2); 2194 assert(CondCode2 == AArch64CC::AL); 2195 break; 2196 case ISD::SETONE: 2197 // (a one b) 2198 // == ((a olt b) || (a ogt b)) 2199 // == ((a ord b) && (a une b)) 2200 CondCode = AArch64CC::VC; 2201 CondCode2 = AArch64CC::NE; 2202 break; 2203 case ISD::SETUEQ: 2204 // (a ueq b) 2205 // == ((a uno b) || (a oeq b)) 2206 // == ((a ule b) && (a uge b)) 2207 CondCode = AArch64CC::PL; 2208 CondCode2 = AArch64CC::LE; 2209 break; 2210 } 2211 } 2212 2213 /// changeVectorFPCCToAArch64CC - Convert a DAG fp condition code to an AArch64 2214 /// CC usable with the vector instructions. Fewer operations are available 2215 /// without a real NZCV register, so we have to use less efficient combinations 2216 /// to get the same effect. 2217 static void changeVectorFPCCToAArch64CC(ISD::CondCode CC, 2218 AArch64CC::CondCode &CondCode, 2219 AArch64CC::CondCode &CondCode2, 2220 bool &Invert) { 2221 Invert = false; 2222 switch (CC) { 2223 default: 2224 // Mostly the scalar mappings work fine. 2225 changeFPCCToAArch64CC(CC, CondCode, CondCode2); 2226 break; 2227 case ISD::SETUO: 2228 Invert = true; 2229 LLVM_FALLTHROUGH; 2230 case ISD::SETO: 2231 CondCode = AArch64CC::MI; 2232 CondCode2 = AArch64CC::GE; 2233 break; 2234 case ISD::SETUEQ: 2235 case ISD::SETULT: 2236 case ISD::SETULE: 2237 case ISD::SETUGT: 2238 case ISD::SETUGE: 2239 // All of the compare-mask comparisons are ordered, but we can switch 2240 // between the two by a double inversion. E.g. ULE == !OGT. 2241 Invert = true; 2242 changeFPCCToAArch64CC(getSetCCInverse(CC, /* FP inverse */ MVT::f32), 2243 CondCode, CondCode2); 2244 break; 2245 } 2246 } 2247 2248 static bool isLegalArithImmed(uint64_t C) { 2249 // Matches AArch64DAGToDAGISel::SelectArithImmed(). 2250 bool IsLegal = (C >> 12 == 0) || ((C & 0xFFFULL) == 0 && C >> 24 == 0); 2251 LLVM_DEBUG(dbgs() << "Is imm " << C 2252 << " legal: " << (IsLegal ? "yes\n" : "no\n")); 2253 return IsLegal; 2254 } 2255 2256 // Can a (CMP op1, (sub 0, op2) be turned into a CMN instruction on 2257 // the grounds that "op1 - (-op2) == op1 + op2" ? Not always, the C and V flags 2258 // can be set differently by this operation. It comes down to whether 2259 // "SInt(~op2)+1 == SInt(~op2+1)" (and the same for UInt). If they are then 2260 // everything is fine. If not then the optimization is wrong. Thus general 2261 // comparisons are only valid if op2 != 0. 2262 // 2263 // So, finally, the only LLVM-native comparisons that don't mention C and V 2264 // are SETEQ and SETNE. They're the only ones we can safely use CMN for in 2265 // the absence of information about op2. 2266 static bool isCMN(SDValue Op, ISD::CondCode CC) { 2267 return Op.getOpcode() == ISD::SUB && isNullConstant(Op.getOperand(0)) && 2268 (CC == ISD::SETEQ || CC == ISD::SETNE); 2269 } 2270 2271 static SDValue emitStrictFPComparison(SDValue LHS, SDValue RHS, const SDLoc &dl, 2272 SelectionDAG &DAG, SDValue Chain, 2273 bool IsSignaling) { 2274 EVT VT = LHS.getValueType(); 2275 assert(VT != MVT::f128); 2276 assert(VT != MVT::f16 && "Lowering of strict fp16 not yet implemented"); 2277 unsigned Opcode = 2278 IsSignaling ? AArch64ISD::STRICT_FCMPE : AArch64ISD::STRICT_FCMP; 2279 return DAG.getNode(Opcode, dl, {VT, MVT::Other}, {Chain, LHS, RHS}); 2280 } 2281 2282 static SDValue emitComparison(SDValue LHS, SDValue RHS, ISD::CondCode CC, 2283 const SDLoc &dl, SelectionDAG &DAG) { 2284 EVT VT = LHS.getValueType(); 2285 const bool FullFP16 = 2286 static_cast<const AArch64Subtarget &>(DAG.getSubtarget()).hasFullFP16(); 2287 2288 if (VT.isFloatingPoint()) { 2289 assert(VT != MVT::f128); 2290 if (VT == MVT::f16 && !FullFP16) { 2291 LHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f32, LHS); 2292 RHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f32, RHS); 2293 VT = MVT::f32; 2294 } 2295 return DAG.getNode(AArch64ISD::FCMP, dl, VT, LHS, RHS); 2296 } 2297 2298 // The CMP instruction is just an alias for SUBS, and representing it as 2299 // SUBS means that it's possible to get CSE with subtract operations. 2300 // A later phase can perform the optimization of setting the destination 2301 // register to WZR/XZR if it ends up being unused. 2302 unsigned Opcode = AArch64ISD::SUBS; 2303 2304 if (isCMN(RHS, CC)) { 2305 // Can we combine a (CMP op1, (sub 0, op2) into a CMN instruction ? 2306 Opcode = AArch64ISD::ADDS; 2307 RHS = RHS.getOperand(1); 2308 } else if (isCMN(LHS, CC)) { 2309 // As we are looking for EQ/NE compares, the operands can be commuted ; can 2310 // we combine a (CMP (sub 0, op1), op2) into a CMN instruction ? 2311 Opcode = AArch64ISD::ADDS; 2312 LHS = LHS.getOperand(1); 2313 } else if (isNullConstant(RHS) && !isUnsignedIntSetCC(CC)) { 2314 if (LHS.getOpcode() == ISD::AND) { 2315 // Similarly, (CMP (and X, Y), 0) can be implemented with a TST 2316 // (a.k.a. ANDS) except that the flags are only guaranteed to work for one 2317 // of the signed comparisons. 2318 const SDValue ANDSNode = DAG.getNode(AArch64ISD::ANDS, dl, 2319 DAG.getVTList(VT, MVT_CC), 2320 LHS.getOperand(0), 2321 LHS.getOperand(1)); 2322 // Replace all users of (and X, Y) with newly generated (ands X, Y) 2323 DAG.ReplaceAllUsesWith(LHS, ANDSNode); 2324 return ANDSNode.getValue(1); 2325 } else if (LHS.getOpcode() == AArch64ISD::ANDS) { 2326 // Use result of ANDS 2327 return LHS.getValue(1); 2328 } 2329 } 2330 2331 return DAG.getNode(Opcode, dl, DAG.getVTList(VT, MVT_CC), LHS, RHS) 2332 .getValue(1); 2333 } 2334 2335 /// \defgroup AArch64CCMP CMP;CCMP matching 2336 /// 2337 /// These functions deal with the formation of CMP;CCMP;... sequences. 2338 /// The CCMP/CCMN/FCCMP/FCCMPE instructions allow the conditional execution of 2339 /// a comparison. They set the NZCV flags to a predefined value if their 2340 /// predicate is false. This allows to express arbitrary conjunctions, for 2341 /// example "cmp 0 (and (setCA (cmp A)) (setCB (cmp B)))" 2342 /// expressed as: 2343 /// cmp A 2344 /// ccmp B, inv(CB), CA 2345 /// check for CB flags 2346 /// 2347 /// This naturally lets us implement chains of AND operations with SETCC 2348 /// operands. And we can even implement some other situations by transforming 2349 /// them: 2350 /// - We can implement (NEG SETCC) i.e. negating a single comparison by 2351 /// negating the flags used in a CCMP/FCCMP operations. 2352 /// - We can negate the result of a whole chain of CMP/CCMP/FCCMP operations 2353 /// by negating the flags we test for afterwards. i.e. 2354 /// NEG (CMP CCMP CCCMP ...) can be implemented. 2355 /// - Note that we can only ever negate all previously processed results. 2356 /// What we can not implement by flipping the flags to test is a negation 2357 /// of two sub-trees (because the negation affects all sub-trees emitted so 2358 /// far, so the 2nd sub-tree we emit would also affect the first). 2359 /// With those tools we can implement some OR operations: 2360 /// - (OR (SETCC A) (SETCC B)) can be implemented via: 2361 /// NEG (AND (NEG (SETCC A)) (NEG (SETCC B))) 2362 /// - After transforming OR to NEG/AND combinations we may be able to use NEG 2363 /// elimination rules from earlier to implement the whole thing as a 2364 /// CCMP/FCCMP chain. 2365 /// 2366 /// As complete example: 2367 /// or (or (setCA (cmp A)) (setCB (cmp B))) 2368 /// (and (setCC (cmp C)) (setCD (cmp D)))" 2369 /// can be reassociated to: 2370 /// or (and (setCC (cmp C)) setCD (cmp D)) 2371 // (or (setCA (cmp A)) (setCB (cmp B))) 2372 /// can be transformed to: 2373 /// not (and (not (and (setCC (cmp C)) (setCD (cmp D)))) 2374 /// (and (not (setCA (cmp A)) (not (setCB (cmp B))))))" 2375 /// which can be implemented as: 2376 /// cmp C 2377 /// ccmp D, inv(CD), CC 2378 /// ccmp A, CA, inv(CD) 2379 /// ccmp B, CB, inv(CA) 2380 /// check for CB flags 2381 /// 2382 /// A counterexample is "or (and A B) (and C D)" which translates to 2383 /// not (and (not (and (not A) (not B))) (not (and (not C) (not D)))), we 2384 /// can only implement 1 of the inner (not) operations, but not both! 2385 /// @{ 2386 2387 /// Create a conditional comparison; Use CCMP, CCMN or FCCMP as appropriate. 2388 static SDValue emitConditionalComparison(SDValue LHS, SDValue RHS, 2389 ISD::CondCode CC, SDValue CCOp, 2390 AArch64CC::CondCode Predicate, 2391 AArch64CC::CondCode OutCC, 2392 const SDLoc &DL, SelectionDAG &DAG) { 2393 unsigned Opcode = 0; 2394 const bool FullFP16 = 2395 static_cast<const AArch64Subtarget &>(DAG.getSubtarget()).hasFullFP16(); 2396 2397 if (LHS.getValueType().isFloatingPoint()) { 2398 assert(LHS.getValueType() != MVT::f128); 2399 if (LHS.getValueType() == MVT::f16 && !FullFP16) { 2400 LHS = DAG.getNode(ISD::FP_EXTEND, DL, MVT::f32, LHS); 2401 RHS = DAG.getNode(ISD::FP_EXTEND, DL, MVT::f32, RHS); 2402 } 2403 Opcode = AArch64ISD::FCCMP; 2404 } else if (RHS.getOpcode() == ISD::SUB) { 2405 SDValue SubOp0 = RHS.getOperand(0); 2406 if (isNullConstant(SubOp0) && (CC == ISD::SETEQ || CC == ISD::SETNE)) { 2407 // See emitComparison() on why we can only do this for SETEQ and SETNE. 2408 Opcode = AArch64ISD::CCMN; 2409 RHS = RHS.getOperand(1); 2410 } 2411 } 2412 if (Opcode == 0) 2413 Opcode = AArch64ISD::CCMP; 2414 2415 SDValue Condition = DAG.getConstant(Predicate, DL, MVT_CC); 2416 AArch64CC::CondCode InvOutCC = AArch64CC::getInvertedCondCode(OutCC); 2417 unsigned NZCV = AArch64CC::getNZCVToSatisfyCondCode(InvOutCC); 2418 SDValue NZCVOp = DAG.getConstant(NZCV, DL, MVT::i32); 2419 return DAG.getNode(Opcode, DL, MVT_CC, LHS, RHS, NZCVOp, Condition, CCOp); 2420 } 2421 2422 /// Returns true if @p Val is a tree of AND/OR/SETCC operations that can be 2423 /// expressed as a conjunction. See \ref AArch64CCMP. 2424 /// \param CanNegate Set to true if we can negate the whole sub-tree just by 2425 /// changing the conditions on the SETCC tests. 2426 /// (this means we can call emitConjunctionRec() with 2427 /// Negate==true on this sub-tree) 2428 /// \param MustBeFirst Set to true if this subtree needs to be negated and we 2429 /// cannot do the negation naturally. We are required to 2430 /// emit the subtree first in this case. 2431 /// \param WillNegate Is true if are called when the result of this 2432 /// subexpression must be negated. This happens when the 2433 /// outer expression is an OR. We can use this fact to know 2434 /// that we have a double negation (or (or ...) ...) that 2435 /// can be implemented for free. 2436 static bool canEmitConjunction(const SDValue Val, bool &CanNegate, 2437 bool &MustBeFirst, bool WillNegate, 2438 unsigned Depth = 0) { 2439 if (!Val.hasOneUse()) 2440 return false; 2441 unsigned Opcode = Val->getOpcode(); 2442 if (Opcode == ISD::SETCC) { 2443 if (Val->getOperand(0).getValueType() == MVT::f128) 2444 return false; 2445 CanNegate = true; 2446 MustBeFirst = false; 2447 return true; 2448 } 2449 // Protect against exponential runtime and stack overflow. 2450 if (Depth > 6) 2451 return false; 2452 if (Opcode == ISD::AND || Opcode == ISD::OR) { 2453 bool IsOR = Opcode == ISD::OR; 2454 SDValue O0 = Val->getOperand(0); 2455 SDValue O1 = Val->getOperand(1); 2456 bool CanNegateL; 2457 bool MustBeFirstL; 2458 if (!canEmitConjunction(O0, CanNegateL, MustBeFirstL, IsOR, Depth+1)) 2459 return false; 2460 bool CanNegateR; 2461 bool MustBeFirstR; 2462 if (!canEmitConjunction(O1, CanNegateR, MustBeFirstR, IsOR, Depth+1)) 2463 return false; 2464 2465 if (MustBeFirstL && MustBeFirstR) 2466 return false; 2467 2468 if (IsOR) { 2469 // For an OR expression we need to be able to naturally negate at least 2470 // one side or we cannot do the transformation at all. 2471 if (!CanNegateL && !CanNegateR) 2472 return false; 2473 // If we the result of the OR will be negated and we can naturally negate 2474 // the leafs, then this sub-tree as a whole negates naturally. 2475 CanNegate = WillNegate && CanNegateL && CanNegateR; 2476 // If we cannot naturally negate the whole sub-tree, then this must be 2477 // emitted first. 2478 MustBeFirst = !CanNegate; 2479 } else { 2480 assert(Opcode == ISD::AND && "Must be OR or AND"); 2481 // We cannot naturally negate an AND operation. 2482 CanNegate = false; 2483 MustBeFirst = MustBeFirstL || MustBeFirstR; 2484 } 2485 return true; 2486 } 2487 return false; 2488 } 2489 2490 /// Emit conjunction or disjunction tree with the CMP/FCMP followed by a chain 2491 /// of CCMP/CFCMP ops. See @ref AArch64CCMP. 2492 /// Tries to transform the given i1 producing node @p Val to a series compare 2493 /// and conditional compare operations. @returns an NZCV flags producing node 2494 /// and sets @p OutCC to the flags that should be tested or returns SDValue() if 2495 /// transformation was not possible. 2496 /// \p Negate is true if we want this sub-tree being negated just by changing 2497 /// SETCC conditions. 2498 static SDValue emitConjunctionRec(SelectionDAG &DAG, SDValue Val, 2499 AArch64CC::CondCode &OutCC, bool Negate, SDValue CCOp, 2500 AArch64CC::CondCode Predicate) { 2501 // We're at a tree leaf, produce a conditional comparison operation. 2502 unsigned Opcode = Val->getOpcode(); 2503 if (Opcode == ISD::SETCC) { 2504 SDValue LHS = Val->getOperand(0); 2505 SDValue RHS = Val->getOperand(1); 2506 ISD::CondCode CC = cast<CondCodeSDNode>(Val->getOperand(2))->get(); 2507 bool isInteger = LHS.getValueType().isInteger(); 2508 if (Negate) 2509 CC = getSetCCInverse(CC, LHS.getValueType()); 2510 SDLoc DL(Val); 2511 // Determine OutCC and handle FP special case. 2512 if (isInteger) { 2513 OutCC = changeIntCCToAArch64CC(CC); 2514 } else { 2515 assert(LHS.getValueType().isFloatingPoint()); 2516 AArch64CC::CondCode ExtraCC; 2517 changeFPCCToANDAArch64CC(CC, OutCC, ExtraCC); 2518 // Some floating point conditions can't be tested with a single condition 2519 // code. Construct an additional comparison in this case. 2520 if (ExtraCC != AArch64CC::AL) { 2521 SDValue ExtraCmp; 2522 if (!CCOp.getNode()) 2523 ExtraCmp = emitComparison(LHS, RHS, CC, DL, DAG); 2524 else 2525 ExtraCmp = emitConditionalComparison(LHS, RHS, CC, CCOp, Predicate, 2526 ExtraCC, DL, DAG); 2527 CCOp = ExtraCmp; 2528 Predicate = ExtraCC; 2529 } 2530 } 2531 2532 // Produce a normal comparison if we are first in the chain 2533 if (!CCOp) 2534 return emitComparison(LHS, RHS, CC, DL, DAG); 2535 // Otherwise produce a ccmp. 2536 return emitConditionalComparison(LHS, RHS, CC, CCOp, Predicate, OutCC, DL, 2537 DAG); 2538 } 2539 assert(Val->hasOneUse() && "Valid conjunction/disjunction tree"); 2540 2541 bool IsOR = Opcode == ISD::OR; 2542 2543 SDValue LHS = Val->getOperand(0); 2544 bool CanNegateL; 2545 bool MustBeFirstL; 2546 bool ValidL = canEmitConjunction(LHS, CanNegateL, MustBeFirstL, IsOR); 2547 assert(ValidL && "Valid conjunction/disjunction tree"); 2548 (void)ValidL; 2549 2550 SDValue RHS = Val->getOperand(1); 2551 bool CanNegateR; 2552 bool MustBeFirstR; 2553 bool ValidR = canEmitConjunction(RHS, CanNegateR, MustBeFirstR, IsOR); 2554 assert(ValidR && "Valid conjunction/disjunction tree"); 2555 (void)ValidR; 2556 2557 // Swap sub-tree that must come first to the right side. 2558 if (MustBeFirstL) { 2559 assert(!MustBeFirstR && "Valid conjunction/disjunction tree"); 2560 std::swap(LHS, RHS); 2561 std::swap(CanNegateL, CanNegateR); 2562 std::swap(MustBeFirstL, MustBeFirstR); 2563 } 2564 2565 bool NegateR; 2566 bool NegateAfterR; 2567 bool NegateL; 2568 bool NegateAfterAll; 2569 if (Opcode == ISD::OR) { 2570 // Swap the sub-tree that we can negate naturally to the left. 2571 if (!CanNegateL) { 2572 assert(CanNegateR && "at least one side must be negatable"); 2573 assert(!MustBeFirstR && "invalid conjunction/disjunction tree"); 2574 assert(!Negate); 2575 std::swap(LHS, RHS); 2576 NegateR = false; 2577 NegateAfterR = true; 2578 } else { 2579 // Negate the left sub-tree if possible, otherwise negate the result. 2580 NegateR = CanNegateR; 2581 NegateAfterR = !CanNegateR; 2582 } 2583 NegateL = true; 2584 NegateAfterAll = !Negate; 2585 } else { 2586 assert(Opcode == ISD::AND && "Valid conjunction/disjunction tree"); 2587 assert(!Negate && "Valid conjunction/disjunction tree"); 2588 2589 NegateL = false; 2590 NegateR = false; 2591 NegateAfterR = false; 2592 NegateAfterAll = false; 2593 } 2594 2595 // Emit sub-trees. 2596 AArch64CC::CondCode RHSCC; 2597 SDValue CmpR = emitConjunctionRec(DAG, RHS, RHSCC, NegateR, CCOp, Predicate); 2598 if (NegateAfterR) 2599 RHSCC = AArch64CC::getInvertedCondCode(RHSCC); 2600 SDValue CmpL = emitConjunctionRec(DAG, LHS, OutCC, NegateL, CmpR, RHSCC); 2601 if (NegateAfterAll) 2602 OutCC = AArch64CC::getInvertedCondCode(OutCC); 2603 return CmpL; 2604 } 2605 2606 /// Emit expression as a conjunction (a series of CCMP/CFCMP ops). 2607 /// In some cases this is even possible with OR operations in the expression. 2608 /// See \ref AArch64CCMP. 2609 /// \see emitConjunctionRec(). 2610 static SDValue emitConjunction(SelectionDAG &DAG, SDValue Val, 2611 AArch64CC::CondCode &OutCC) { 2612 bool DummyCanNegate; 2613 bool DummyMustBeFirst; 2614 if (!canEmitConjunction(Val, DummyCanNegate, DummyMustBeFirst, false)) 2615 return SDValue(); 2616 2617 return emitConjunctionRec(DAG, Val, OutCC, false, SDValue(), AArch64CC::AL); 2618 } 2619 2620 /// @} 2621 2622 /// Returns how profitable it is to fold a comparison's operand's shift and/or 2623 /// extension operations. 2624 static unsigned getCmpOperandFoldingProfit(SDValue Op) { 2625 auto isSupportedExtend = [&](SDValue V) { 2626 if (V.getOpcode() == ISD::SIGN_EXTEND_INREG) 2627 return true; 2628 2629 if (V.getOpcode() == ISD::AND) 2630 if (ConstantSDNode *MaskCst = dyn_cast<ConstantSDNode>(V.getOperand(1))) { 2631 uint64_t Mask = MaskCst->getZExtValue(); 2632 return (Mask == 0xFF || Mask == 0xFFFF || Mask == 0xFFFFFFFF); 2633 } 2634 2635 return false; 2636 }; 2637 2638 if (!Op.hasOneUse()) 2639 return 0; 2640 2641 if (isSupportedExtend(Op)) 2642 return 1; 2643 2644 unsigned Opc = Op.getOpcode(); 2645 if (Opc == ISD::SHL || Opc == ISD::SRL || Opc == ISD::SRA) 2646 if (ConstantSDNode *ShiftCst = dyn_cast<ConstantSDNode>(Op.getOperand(1))) { 2647 uint64_t Shift = ShiftCst->getZExtValue(); 2648 if (isSupportedExtend(Op.getOperand(0))) 2649 return (Shift <= 4) ? 2 : 1; 2650 EVT VT = Op.getValueType(); 2651 if ((VT == MVT::i32 && Shift <= 31) || (VT == MVT::i64 && Shift <= 63)) 2652 return 1; 2653 } 2654 2655 return 0; 2656 } 2657 2658 static SDValue getAArch64Cmp(SDValue LHS, SDValue RHS, ISD::CondCode CC, 2659 SDValue &AArch64cc, SelectionDAG &DAG, 2660 const SDLoc &dl) { 2661 if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS.getNode())) { 2662 EVT VT = RHS.getValueType(); 2663 uint64_t C = RHSC->getZExtValue(); 2664 if (!isLegalArithImmed(C)) { 2665 // Constant does not fit, try adjusting it by one? 2666 switch (CC) { 2667 default: 2668 break; 2669 case ISD::SETLT: 2670 case ISD::SETGE: 2671 if ((VT == MVT::i32 && C != 0x80000000 && 2672 isLegalArithImmed((uint32_t)(C - 1))) || 2673 (VT == MVT::i64 && C != 0x80000000ULL && 2674 isLegalArithImmed(C - 1ULL))) { 2675 CC = (CC == ISD::SETLT) ? ISD::SETLE : ISD::SETGT; 2676 C = (VT == MVT::i32) ? (uint32_t)(C - 1) : C - 1; 2677 RHS = DAG.getConstant(C, dl, VT); 2678 } 2679 break; 2680 case ISD::SETULT: 2681 case ISD::SETUGE: 2682 if ((VT == MVT::i32 && C != 0 && 2683 isLegalArithImmed((uint32_t)(C - 1))) || 2684 (VT == MVT::i64 && C != 0ULL && isLegalArithImmed(C - 1ULL))) { 2685 CC = (CC == ISD::SETULT) ? ISD::SETULE : ISD::SETUGT; 2686 C = (VT == MVT::i32) ? (uint32_t)(C - 1) : C - 1; 2687 RHS = DAG.getConstant(C, dl, VT); 2688 } 2689 break; 2690 case ISD::SETLE: 2691 case ISD::SETGT: 2692 if ((VT == MVT::i32 && C != INT32_MAX && 2693 isLegalArithImmed((uint32_t)(C + 1))) || 2694 (VT == MVT::i64 && C != INT64_MAX && 2695 isLegalArithImmed(C + 1ULL))) { 2696 CC = (CC == ISD::SETLE) ? ISD::SETLT : ISD::SETGE; 2697 C = (VT == MVT::i32) ? (uint32_t)(C + 1) : C + 1; 2698 RHS = DAG.getConstant(C, dl, VT); 2699 } 2700 break; 2701 case ISD::SETULE: 2702 case ISD::SETUGT: 2703 if ((VT == MVT::i32 && C != UINT32_MAX && 2704 isLegalArithImmed((uint32_t)(C + 1))) || 2705 (VT == MVT::i64 && C != UINT64_MAX && 2706 isLegalArithImmed(C + 1ULL))) { 2707 CC = (CC == ISD::SETULE) ? ISD::SETULT : ISD::SETUGE; 2708 C = (VT == MVT::i32) ? (uint32_t)(C + 1) : C + 1; 2709 RHS = DAG.getConstant(C, dl, VT); 2710 } 2711 break; 2712 } 2713 } 2714 } 2715 2716 // Comparisons are canonicalized so that the RHS operand is simpler than the 2717 // LHS one, the extreme case being when RHS is an immediate. However, AArch64 2718 // can fold some shift+extend operations on the RHS operand, so swap the 2719 // operands if that can be done. 2720 // 2721 // For example: 2722 // lsl w13, w11, #1 2723 // cmp w13, w12 2724 // can be turned into: 2725 // cmp w12, w11, lsl #1 2726 if (!isa<ConstantSDNode>(RHS) || 2727 !isLegalArithImmed(cast<ConstantSDNode>(RHS)->getZExtValue())) { 2728 SDValue TheLHS = isCMN(LHS, CC) ? LHS.getOperand(1) : LHS; 2729 2730 if (getCmpOperandFoldingProfit(TheLHS) > getCmpOperandFoldingProfit(RHS)) { 2731 std::swap(LHS, RHS); 2732 CC = ISD::getSetCCSwappedOperands(CC); 2733 } 2734 } 2735 2736 SDValue Cmp; 2737 AArch64CC::CondCode AArch64CC; 2738 if ((CC == ISD::SETEQ || CC == ISD::SETNE) && isa<ConstantSDNode>(RHS)) { 2739 const ConstantSDNode *RHSC = cast<ConstantSDNode>(RHS); 2740 2741 // The imm operand of ADDS is an unsigned immediate, in the range 0 to 4095. 2742 // For the i8 operand, the largest immediate is 255, so this can be easily 2743 // encoded in the compare instruction. For the i16 operand, however, the 2744 // largest immediate cannot be encoded in the compare. 2745 // Therefore, use a sign extending load and cmn to avoid materializing the 2746 // -1 constant. For example, 2747 // movz w1, #65535 2748 // ldrh w0, [x0, #0] 2749 // cmp w0, w1 2750 // > 2751 // ldrsh w0, [x0, #0] 2752 // cmn w0, #1 2753 // Fundamental, we're relying on the property that (zext LHS) == (zext RHS) 2754 // if and only if (sext LHS) == (sext RHS). The checks are in place to 2755 // ensure both the LHS and RHS are truly zero extended and to make sure the 2756 // transformation is profitable. 2757 if ((RHSC->getZExtValue() >> 16 == 0) && isa<LoadSDNode>(LHS) && 2758 cast<LoadSDNode>(LHS)->getExtensionType() == ISD::ZEXTLOAD && 2759 cast<LoadSDNode>(LHS)->getMemoryVT() == MVT::i16 && 2760 LHS.getNode()->hasNUsesOfValue(1, 0)) { 2761 int16_t ValueofRHS = cast<ConstantSDNode>(RHS)->getZExtValue(); 2762 if (ValueofRHS < 0 && isLegalArithImmed(-ValueofRHS)) { 2763 SDValue SExt = 2764 DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, LHS.getValueType(), LHS, 2765 DAG.getValueType(MVT::i16)); 2766 Cmp = emitComparison(SExt, DAG.getConstant(ValueofRHS, dl, 2767 RHS.getValueType()), 2768 CC, dl, DAG); 2769 AArch64CC = changeIntCCToAArch64CC(CC); 2770 } 2771 } 2772 2773 if (!Cmp && (RHSC->isNullValue() || RHSC->isOne())) { 2774 if ((Cmp = emitConjunction(DAG, LHS, AArch64CC))) { 2775 if ((CC == ISD::SETNE) ^ RHSC->isNullValue()) 2776 AArch64CC = AArch64CC::getInvertedCondCode(AArch64CC); 2777 } 2778 } 2779 } 2780 2781 if (!Cmp) { 2782 Cmp = emitComparison(LHS, RHS, CC, dl, DAG); 2783 AArch64CC = changeIntCCToAArch64CC(CC); 2784 } 2785 AArch64cc = DAG.getConstant(AArch64CC, dl, MVT_CC); 2786 return Cmp; 2787 } 2788 2789 static std::pair<SDValue, SDValue> 2790 getAArch64XALUOOp(AArch64CC::CondCode &CC, SDValue Op, SelectionDAG &DAG) { 2791 assert((Op.getValueType() == MVT::i32 || Op.getValueType() == MVT::i64) && 2792 "Unsupported value type"); 2793 SDValue Value, Overflow; 2794 SDLoc DL(Op); 2795 SDValue LHS = Op.getOperand(0); 2796 SDValue RHS = Op.getOperand(1); 2797 unsigned Opc = 0; 2798 switch (Op.getOpcode()) { 2799 default: 2800 llvm_unreachable("Unknown overflow instruction!"); 2801 case ISD::SADDO: 2802 Opc = AArch64ISD::ADDS; 2803 CC = AArch64CC::VS; 2804 break; 2805 case ISD::UADDO: 2806 Opc = AArch64ISD::ADDS; 2807 CC = AArch64CC::HS; 2808 break; 2809 case ISD::SSUBO: 2810 Opc = AArch64ISD::SUBS; 2811 CC = AArch64CC::VS; 2812 break; 2813 case ISD::USUBO: 2814 Opc = AArch64ISD::SUBS; 2815 CC = AArch64CC::LO; 2816 break; 2817 // Multiply needs a little bit extra work. 2818 case ISD::SMULO: 2819 case ISD::UMULO: { 2820 CC = AArch64CC::NE; 2821 bool IsSigned = Op.getOpcode() == ISD::SMULO; 2822 if (Op.getValueType() == MVT::i32) { 2823 unsigned ExtendOpc = IsSigned ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND; 2824 // For a 32 bit multiply with overflow check we want the instruction 2825 // selector to generate a widening multiply (SMADDL/UMADDL). For that we 2826 // need to generate the following pattern: 2827 // (i64 add 0, (i64 mul (i64 sext|zext i32 %a), (i64 sext|zext i32 %b)) 2828 LHS = DAG.getNode(ExtendOpc, DL, MVT::i64, LHS); 2829 RHS = DAG.getNode(ExtendOpc, DL, MVT::i64, RHS); 2830 SDValue Mul = DAG.getNode(ISD::MUL, DL, MVT::i64, LHS, RHS); 2831 SDValue Add = DAG.getNode(ISD::ADD, DL, MVT::i64, Mul, 2832 DAG.getConstant(0, DL, MVT::i64)); 2833 // On AArch64 the upper 32 bits are always zero extended for a 32 bit 2834 // operation. We need to clear out the upper 32 bits, because we used a 2835 // widening multiply that wrote all 64 bits. In the end this should be a 2836 // noop. 2837 Value = DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Add); 2838 if (IsSigned) { 2839 // The signed overflow check requires more than just a simple check for 2840 // any bit set in the upper 32 bits of the result. These bits could be 2841 // just the sign bits of a negative number. To perform the overflow 2842 // check we have to arithmetic shift right the 32nd bit of the result by 2843 // 31 bits. Then we compare the result to the upper 32 bits. 2844 SDValue UpperBits = DAG.getNode(ISD::SRL, DL, MVT::i64, Add, 2845 DAG.getConstant(32, DL, MVT::i64)); 2846 UpperBits = DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, UpperBits); 2847 SDValue LowerBits = DAG.getNode(ISD::SRA, DL, MVT::i32, Value, 2848 DAG.getConstant(31, DL, MVT::i64)); 2849 // It is important that LowerBits is last, otherwise the arithmetic 2850 // shift will not be folded into the compare (SUBS). 2851 SDVTList VTs = DAG.getVTList(MVT::i32, MVT::i32); 2852 Overflow = DAG.getNode(AArch64ISD::SUBS, DL, VTs, UpperBits, LowerBits) 2853 .getValue(1); 2854 } else { 2855 // The overflow check for unsigned multiply is easy. We only need to 2856 // check if any of the upper 32 bits are set. This can be done with a 2857 // CMP (shifted register). For that we need to generate the following 2858 // pattern: 2859 // (i64 AArch64ISD::SUBS i64 0, (i64 srl i64 %Mul, i64 32) 2860 SDValue UpperBits = DAG.getNode(ISD::SRL, DL, MVT::i64, Mul, 2861 DAG.getConstant(32, DL, MVT::i64)); 2862 SDVTList VTs = DAG.getVTList(MVT::i64, MVT::i32); 2863 Overflow = 2864 DAG.getNode(AArch64ISD::SUBS, DL, VTs, 2865 DAG.getConstant(0, DL, MVT::i64), 2866 UpperBits).getValue(1); 2867 } 2868 break; 2869 } 2870 assert(Op.getValueType() == MVT::i64 && "Expected an i64 value type"); 2871 // For the 64 bit multiply 2872 Value = DAG.getNode(ISD::MUL, DL, MVT::i64, LHS, RHS); 2873 if (IsSigned) { 2874 SDValue UpperBits = DAG.getNode(ISD::MULHS, DL, MVT::i64, LHS, RHS); 2875 SDValue LowerBits = DAG.getNode(ISD::SRA, DL, MVT::i64, Value, 2876 DAG.getConstant(63, DL, MVT::i64)); 2877 // It is important that LowerBits is last, otherwise the arithmetic 2878 // shift will not be folded into the compare (SUBS). 2879 SDVTList VTs = DAG.getVTList(MVT::i64, MVT::i32); 2880 Overflow = DAG.getNode(AArch64ISD::SUBS, DL, VTs, UpperBits, LowerBits) 2881 .getValue(1); 2882 } else { 2883 SDValue UpperBits = DAG.getNode(ISD::MULHU, DL, MVT::i64, LHS, RHS); 2884 SDVTList VTs = DAG.getVTList(MVT::i64, MVT::i32); 2885 Overflow = 2886 DAG.getNode(AArch64ISD::SUBS, DL, VTs, 2887 DAG.getConstant(0, DL, MVT::i64), 2888 UpperBits).getValue(1); 2889 } 2890 break; 2891 } 2892 } // switch (...) 2893 2894 if (Opc) { 2895 SDVTList VTs = DAG.getVTList(Op->getValueType(0), MVT::i32); 2896 2897 // Emit the AArch64 operation with overflow check. 2898 Value = DAG.getNode(Opc, DL, VTs, LHS, RHS); 2899 Overflow = Value.getValue(1); 2900 } 2901 return std::make_pair(Value, Overflow); 2902 } 2903 2904 SDValue AArch64TargetLowering::LowerXOR(SDValue Op, SelectionDAG &DAG) const { 2905 if (useSVEForFixedLengthVectorVT(Op.getValueType())) 2906 return LowerToScalableOp(Op, DAG); 2907 2908 SDValue Sel = Op.getOperand(0); 2909 SDValue Other = Op.getOperand(1); 2910 SDLoc dl(Sel); 2911 2912 // If the operand is an overflow checking operation, invert the condition 2913 // code and kill the Not operation. I.e., transform: 2914 // (xor (overflow_op_bool, 1)) 2915 // --> 2916 // (csel 1, 0, invert(cc), overflow_op_bool) 2917 // ... which later gets transformed to just a cset instruction with an 2918 // inverted condition code, rather than a cset + eor sequence. 2919 if (isOneConstant(Other) && ISD::isOverflowIntrOpRes(Sel)) { 2920 // Only lower legal XALUO ops. 2921 if (!DAG.getTargetLoweringInfo().isTypeLegal(Sel->getValueType(0))) 2922 return SDValue(); 2923 2924 SDValue TVal = DAG.getConstant(1, dl, MVT::i32); 2925 SDValue FVal = DAG.getConstant(0, dl, MVT::i32); 2926 AArch64CC::CondCode CC; 2927 SDValue Value, Overflow; 2928 std::tie(Value, Overflow) = getAArch64XALUOOp(CC, Sel.getValue(0), DAG); 2929 SDValue CCVal = DAG.getConstant(getInvertedCondCode(CC), dl, MVT::i32); 2930 return DAG.getNode(AArch64ISD::CSEL, dl, Op.getValueType(), TVal, FVal, 2931 CCVal, Overflow); 2932 } 2933 // If neither operand is a SELECT_CC, give up. 2934 if (Sel.getOpcode() != ISD::SELECT_CC) 2935 std::swap(Sel, Other); 2936 if (Sel.getOpcode() != ISD::SELECT_CC) 2937 return Op; 2938 2939 // The folding we want to perform is: 2940 // (xor x, (select_cc a, b, cc, 0, -1) ) 2941 // --> 2942 // (csel x, (xor x, -1), cc ...) 2943 // 2944 // The latter will get matched to a CSINV instruction. 2945 2946 ISD::CondCode CC = cast<CondCodeSDNode>(Sel.getOperand(4))->get(); 2947 SDValue LHS = Sel.getOperand(0); 2948 SDValue RHS = Sel.getOperand(1); 2949 SDValue TVal = Sel.getOperand(2); 2950 SDValue FVal = Sel.getOperand(3); 2951 2952 // FIXME: This could be generalized to non-integer comparisons. 2953 if (LHS.getValueType() != MVT::i32 && LHS.getValueType() != MVT::i64) 2954 return Op; 2955 2956 ConstantSDNode *CFVal = dyn_cast<ConstantSDNode>(FVal); 2957 ConstantSDNode *CTVal = dyn_cast<ConstantSDNode>(TVal); 2958 2959 // The values aren't constants, this isn't the pattern we're looking for. 2960 if (!CFVal || !CTVal) 2961 return Op; 2962 2963 // We can commute the SELECT_CC by inverting the condition. This 2964 // might be needed to make this fit into a CSINV pattern. 2965 if (CTVal->isAllOnesValue() && CFVal->isNullValue()) { 2966 std::swap(TVal, FVal); 2967 std::swap(CTVal, CFVal); 2968 CC = ISD::getSetCCInverse(CC, LHS.getValueType()); 2969 } 2970 2971 // If the constants line up, perform the transform! 2972 if (CTVal->isNullValue() && CFVal->isAllOnesValue()) { 2973 SDValue CCVal; 2974 SDValue Cmp = getAArch64Cmp(LHS, RHS, CC, CCVal, DAG, dl); 2975 2976 FVal = Other; 2977 TVal = DAG.getNode(ISD::XOR, dl, Other.getValueType(), Other, 2978 DAG.getConstant(-1ULL, dl, Other.getValueType())); 2979 2980 return DAG.getNode(AArch64ISD::CSEL, dl, Sel.getValueType(), FVal, TVal, 2981 CCVal, Cmp); 2982 } 2983 2984 return Op; 2985 } 2986 2987 static SDValue LowerADDC_ADDE_SUBC_SUBE(SDValue Op, SelectionDAG &DAG) { 2988 EVT VT = Op.getValueType(); 2989 2990 // Let legalize expand this if it isn't a legal type yet. 2991 if (!DAG.getTargetLoweringInfo().isTypeLegal(VT)) 2992 return SDValue(); 2993 2994 SDVTList VTs = DAG.getVTList(VT, MVT::i32); 2995 2996 unsigned Opc; 2997 bool ExtraOp = false; 2998 switch (Op.getOpcode()) { 2999 default: 3000 llvm_unreachable("Invalid code"); 3001 case ISD::ADDC: 3002 Opc = AArch64ISD::ADDS; 3003 break; 3004 case ISD::SUBC: 3005 Opc = AArch64ISD::SUBS; 3006 break; 3007 case ISD::ADDE: 3008 Opc = AArch64ISD::ADCS; 3009 ExtraOp = true; 3010 break; 3011 case ISD::SUBE: 3012 Opc = AArch64ISD::SBCS; 3013 ExtraOp = true; 3014 break; 3015 } 3016 3017 if (!ExtraOp) 3018 return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0), Op.getOperand(1)); 3019 return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0), Op.getOperand(1), 3020 Op.getOperand(2)); 3021 } 3022 3023 static SDValue LowerXALUO(SDValue Op, SelectionDAG &DAG) { 3024 // Let legalize expand this if it isn't a legal type yet. 3025 if (!DAG.getTargetLoweringInfo().isTypeLegal(Op.getValueType())) 3026 return SDValue(); 3027 3028 SDLoc dl(Op); 3029 AArch64CC::CondCode CC; 3030 // The actual operation that sets the overflow or carry flag. 3031 SDValue Value, Overflow; 3032 std::tie(Value, Overflow) = getAArch64XALUOOp(CC, Op, DAG); 3033 3034 // We use 0 and 1 as false and true values. 3035 SDValue TVal = DAG.getConstant(1, dl, MVT::i32); 3036 SDValue FVal = DAG.getConstant(0, dl, MVT::i32); 3037 3038 // We use an inverted condition, because the conditional select is inverted 3039 // too. This will allow it to be selected to a single instruction: 3040 // CSINC Wd, WZR, WZR, invert(cond). 3041 SDValue CCVal = DAG.getConstant(getInvertedCondCode(CC), dl, MVT::i32); 3042 Overflow = DAG.getNode(AArch64ISD::CSEL, dl, MVT::i32, FVal, TVal, 3043 CCVal, Overflow); 3044 3045 SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32); 3046 return DAG.getNode(ISD::MERGE_VALUES, dl, VTs, Value, Overflow); 3047 } 3048 3049 // Prefetch operands are: 3050 // 1: Address to prefetch 3051 // 2: bool isWrite 3052 // 3: int locality (0 = no locality ... 3 = extreme locality) 3053 // 4: bool isDataCache 3054 static SDValue LowerPREFETCH(SDValue Op, SelectionDAG &DAG) { 3055 SDLoc DL(Op); 3056 unsigned IsWrite = cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue(); 3057 unsigned Locality = cast<ConstantSDNode>(Op.getOperand(3))->getZExtValue(); 3058 unsigned IsData = cast<ConstantSDNode>(Op.getOperand(4))->getZExtValue(); 3059 3060 bool IsStream = !Locality; 3061 // When the locality number is set 3062 if (Locality) { 3063 // The front-end should have filtered out the out-of-range values 3064 assert(Locality <= 3 && "Prefetch locality out-of-range"); 3065 // The locality degree is the opposite of the cache speed. 3066 // Put the number the other way around. 3067 // The encoding starts at 0 for level 1 3068 Locality = 3 - Locality; 3069 } 3070 3071 // built the mask value encoding the expected behavior. 3072 unsigned PrfOp = (IsWrite << 4) | // Load/Store bit 3073 (!IsData << 3) | // IsDataCache bit 3074 (Locality << 1) | // Cache level bits 3075 (unsigned)IsStream; // Stream bit 3076 return DAG.getNode(AArch64ISD::PREFETCH, DL, MVT::Other, Op.getOperand(0), 3077 DAG.getConstant(PrfOp, DL, MVT::i32), Op.getOperand(1)); 3078 } 3079 3080 SDValue AArch64TargetLowering::LowerFP_EXTEND(SDValue Op, 3081 SelectionDAG &DAG) const { 3082 if (Op.getValueType().isScalableVector()) 3083 return LowerToPredicatedOp(Op, DAG, AArch64ISD::FP_EXTEND_MERGE_PASSTHRU); 3084 3085 assert(Op.getValueType() == MVT::f128 && "Unexpected lowering"); 3086 return SDValue(); 3087 } 3088 3089 SDValue AArch64TargetLowering::LowerFP_ROUND(SDValue Op, 3090 SelectionDAG &DAG) const { 3091 if (Op.getValueType().isScalableVector()) 3092 return LowerToPredicatedOp(Op, DAG, AArch64ISD::FP_ROUND_MERGE_PASSTHRU); 3093 3094 bool IsStrict = Op->isStrictFPOpcode(); 3095 SDValue SrcVal = Op.getOperand(IsStrict ? 1 : 0); 3096 EVT SrcVT = SrcVal.getValueType(); 3097 3098 if (SrcVT != MVT::f128) { 3099 // Expand cases where the input is a vector bigger than NEON. 3100 if (useSVEForFixedLengthVectorVT(SrcVT)) 3101 return SDValue(); 3102 3103 // It's legal except when f128 is involved 3104 return Op; 3105 } 3106 3107 return SDValue(); 3108 } 3109 3110 SDValue AArch64TargetLowering::LowerVectorFP_TO_INT(SDValue Op, 3111 SelectionDAG &DAG) const { 3112 // Warning: We maintain cost tables in AArch64TargetTransformInfo.cpp. 3113 // Any additional optimization in this function should be recorded 3114 // in the cost tables. 3115 EVT InVT = Op.getOperand(0).getValueType(); 3116 EVT VT = Op.getValueType(); 3117 3118 if (VT.isScalableVector()) { 3119 unsigned Opcode = Op.getOpcode() == ISD::FP_TO_UINT 3120 ? AArch64ISD::FCVTZU_MERGE_PASSTHRU 3121 : AArch64ISD::FCVTZS_MERGE_PASSTHRU; 3122 return LowerToPredicatedOp(Op, DAG, Opcode); 3123 } 3124 3125 unsigned NumElts = InVT.getVectorNumElements(); 3126 3127 // f16 conversions are promoted to f32 when full fp16 is not supported. 3128 if (InVT.getVectorElementType() == MVT::f16 && 3129 !Subtarget->hasFullFP16()) { 3130 MVT NewVT = MVT::getVectorVT(MVT::f32, NumElts); 3131 SDLoc dl(Op); 3132 return DAG.getNode( 3133 Op.getOpcode(), dl, Op.getValueType(), 3134 DAG.getNode(ISD::FP_EXTEND, dl, NewVT, Op.getOperand(0))); 3135 } 3136 3137 uint64_t VTSize = VT.getFixedSizeInBits(); 3138 uint64_t InVTSize = InVT.getFixedSizeInBits(); 3139 if (VTSize < InVTSize) { 3140 SDLoc dl(Op); 3141 SDValue Cv = 3142 DAG.getNode(Op.getOpcode(), dl, InVT.changeVectorElementTypeToInteger(), 3143 Op.getOperand(0)); 3144 return DAG.getNode(ISD::TRUNCATE, dl, VT, Cv); 3145 } 3146 3147 if (VTSize > InVTSize) { 3148 SDLoc dl(Op); 3149 MVT ExtVT = 3150 MVT::getVectorVT(MVT::getFloatingPointVT(VT.getScalarSizeInBits()), 3151 VT.getVectorNumElements()); 3152 SDValue Ext = DAG.getNode(ISD::FP_EXTEND, dl, ExtVT, Op.getOperand(0)); 3153 return DAG.getNode(Op.getOpcode(), dl, VT, Ext); 3154 } 3155 3156 // Type changing conversions are illegal. 3157 return Op; 3158 } 3159 3160 SDValue AArch64TargetLowering::LowerFP_TO_INT(SDValue Op, 3161 SelectionDAG &DAG) const { 3162 bool IsStrict = Op->isStrictFPOpcode(); 3163 SDValue SrcVal = Op.getOperand(IsStrict ? 1 : 0); 3164 3165 if (SrcVal.getValueType().isVector()) 3166 return LowerVectorFP_TO_INT(Op, DAG); 3167 3168 // f16 conversions are promoted to f32 when full fp16 is not supported. 3169 if (SrcVal.getValueType() == MVT::f16 && !Subtarget->hasFullFP16()) { 3170 assert(!IsStrict && "Lowering of strict fp16 not yet implemented"); 3171 SDLoc dl(Op); 3172 return DAG.getNode( 3173 Op.getOpcode(), dl, Op.getValueType(), 3174 DAG.getNode(ISD::FP_EXTEND, dl, MVT::f32, SrcVal)); 3175 } 3176 3177 if (SrcVal.getValueType() != MVT::f128) { 3178 // It's legal except when f128 is involved 3179 return Op; 3180 } 3181 3182 return SDValue(); 3183 } 3184 3185 SDValue AArch64TargetLowering::LowerVectorINT_TO_FP(SDValue Op, 3186 SelectionDAG &DAG) const { 3187 // Warning: We maintain cost tables in AArch64TargetTransformInfo.cpp. 3188 // Any additional optimization in this function should be recorded 3189 // in the cost tables. 3190 EVT VT = Op.getValueType(); 3191 SDLoc dl(Op); 3192 SDValue In = Op.getOperand(0); 3193 EVT InVT = In.getValueType(); 3194 unsigned Opc = Op.getOpcode(); 3195 bool IsSigned = Opc == ISD::SINT_TO_FP || Opc == ISD::STRICT_SINT_TO_FP; 3196 3197 if (VT.isScalableVector()) { 3198 if (InVT.getVectorElementType() == MVT::i1) { 3199 // We can't directly extend an SVE predicate; extend it first. 3200 unsigned CastOpc = IsSigned ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND; 3201 EVT CastVT = getPromotedVTForPredicate(InVT); 3202 In = DAG.getNode(CastOpc, dl, CastVT, In); 3203 return DAG.getNode(Opc, dl, VT, In); 3204 } 3205 3206 unsigned Opcode = IsSigned ? AArch64ISD::SINT_TO_FP_MERGE_PASSTHRU 3207 : AArch64ISD::UINT_TO_FP_MERGE_PASSTHRU; 3208 return LowerToPredicatedOp(Op, DAG, Opcode); 3209 } 3210 3211 uint64_t VTSize = VT.getFixedSizeInBits(); 3212 uint64_t InVTSize = InVT.getFixedSizeInBits(); 3213 if (VTSize < InVTSize) { 3214 MVT CastVT = 3215 MVT::getVectorVT(MVT::getFloatingPointVT(InVT.getScalarSizeInBits()), 3216 InVT.getVectorNumElements()); 3217 In = DAG.getNode(Opc, dl, CastVT, In); 3218 return DAG.getNode(ISD::FP_ROUND, dl, VT, In, DAG.getIntPtrConstant(0, dl)); 3219 } 3220 3221 if (VTSize > InVTSize) { 3222 unsigned CastOpc = IsSigned ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND; 3223 EVT CastVT = VT.changeVectorElementTypeToInteger(); 3224 In = DAG.getNode(CastOpc, dl, CastVT, In); 3225 return DAG.getNode(Opc, dl, VT, In); 3226 } 3227 3228 return Op; 3229 } 3230 3231 SDValue AArch64TargetLowering::LowerINT_TO_FP(SDValue Op, 3232 SelectionDAG &DAG) const { 3233 if (Op.getValueType().isVector()) 3234 return LowerVectorINT_TO_FP(Op, DAG); 3235 3236 bool IsStrict = Op->isStrictFPOpcode(); 3237 SDValue SrcVal = Op.getOperand(IsStrict ? 1 : 0); 3238 3239 // f16 conversions are promoted to f32 when full fp16 is not supported. 3240 if (Op.getValueType() == MVT::f16 && 3241 !Subtarget->hasFullFP16()) { 3242 assert(!IsStrict && "Lowering of strict fp16 not yet implemented"); 3243 SDLoc dl(Op); 3244 return DAG.getNode( 3245 ISD::FP_ROUND, dl, MVT::f16, 3246 DAG.getNode(Op.getOpcode(), dl, MVT::f32, SrcVal), 3247 DAG.getIntPtrConstant(0, dl)); 3248 } 3249 3250 // i128 conversions are libcalls. 3251 if (SrcVal.getValueType() == MVT::i128) 3252 return SDValue(); 3253 3254 // Other conversions are legal, unless it's to the completely software-based 3255 // fp128. 3256 if (Op.getValueType() != MVT::f128) 3257 return Op; 3258 return SDValue(); 3259 } 3260 3261 SDValue AArch64TargetLowering::LowerFSINCOS(SDValue Op, 3262 SelectionDAG &DAG) const { 3263 // For iOS, we want to call an alternative entry point: __sincos_stret, 3264 // which returns the values in two S / D registers. 3265 SDLoc dl(Op); 3266 SDValue Arg = Op.getOperand(0); 3267 EVT ArgVT = Arg.getValueType(); 3268 Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext()); 3269 3270 ArgListTy Args; 3271 ArgListEntry Entry; 3272 3273 Entry.Node = Arg; 3274 Entry.Ty = ArgTy; 3275 Entry.IsSExt = false; 3276 Entry.IsZExt = false; 3277 Args.push_back(Entry); 3278 3279 RTLIB::Libcall LC = ArgVT == MVT::f64 ? RTLIB::SINCOS_STRET_F64 3280 : RTLIB::SINCOS_STRET_F32; 3281 const char *LibcallName = getLibcallName(LC); 3282 SDValue Callee = 3283 DAG.getExternalSymbol(LibcallName, getPointerTy(DAG.getDataLayout())); 3284 3285 StructType *RetTy = StructType::get(ArgTy, ArgTy); 3286 TargetLowering::CallLoweringInfo CLI(DAG); 3287 CLI.setDebugLoc(dl) 3288 .setChain(DAG.getEntryNode()) 3289 .setLibCallee(CallingConv::Fast, RetTy, Callee, std::move(Args)); 3290 3291 std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI); 3292 return CallResult.first; 3293 } 3294 3295 static SDValue LowerBITCAST(SDValue Op, SelectionDAG &DAG) { 3296 EVT OpVT = Op.getValueType(); 3297 if (OpVT != MVT::f16 && OpVT != MVT::bf16) 3298 return SDValue(); 3299 3300 assert(Op.getOperand(0).getValueType() == MVT::i16); 3301 SDLoc DL(Op); 3302 3303 Op = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i32, Op.getOperand(0)); 3304 Op = DAG.getNode(ISD::BITCAST, DL, MVT::f32, Op); 3305 return SDValue( 3306 DAG.getMachineNode(TargetOpcode::EXTRACT_SUBREG, DL, OpVT, Op, 3307 DAG.getTargetConstant(AArch64::hsub, DL, MVT::i32)), 3308 0); 3309 } 3310 3311 static EVT getExtensionTo64Bits(const EVT &OrigVT) { 3312 if (OrigVT.getSizeInBits() >= 64) 3313 return OrigVT; 3314 3315 assert(OrigVT.isSimple() && "Expecting a simple value type"); 3316 3317 MVT::SimpleValueType OrigSimpleTy = OrigVT.getSimpleVT().SimpleTy; 3318 switch (OrigSimpleTy) { 3319 default: llvm_unreachable("Unexpected Vector Type"); 3320 case MVT::v2i8: 3321 case MVT::v2i16: 3322 return MVT::v2i32; 3323 case MVT::v4i8: 3324 return MVT::v4i16; 3325 } 3326 } 3327 3328 static SDValue addRequiredExtensionForVectorMULL(SDValue N, SelectionDAG &DAG, 3329 const EVT &OrigTy, 3330 const EVT &ExtTy, 3331 unsigned ExtOpcode) { 3332 // The vector originally had a size of OrigTy. It was then extended to ExtTy. 3333 // We expect the ExtTy to be 128-bits total. If the OrigTy is less than 3334 // 64-bits we need to insert a new extension so that it will be 64-bits. 3335 assert(ExtTy.is128BitVector() && "Unexpected extension size"); 3336 if (OrigTy.getSizeInBits() >= 64) 3337 return N; 3338 3339 // Must extend size to at least 64 bits to be used as an operand for VMULL. 3340 EVT NewVT = getExtensionTo64Bits(OrigTy); 3341 3342 return DAG.getNode(ExtOpcode, SDLoc(N), NewVT, N); 3343 } 3344 3345 static bool isExtendedBUILD_VECTOR(SDNode *N, SelectionDAG &DAG, 3346 bool isSigned) { 3347 EVT VT = N->getValueType(0); 3348 3349 if (N->getOpcode() != ISD::BUILD_VECTOR) 3350 return false; 3351 3352 for (const SDValue &Elt : N->op_values()) { 3353 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Elt)) { 3354 unsigned EltSize = VT.getScalarSizeInBits(); 3355 unsigned HalfSize = EltSize / 2; 3356 if (isSigned) { 3357 if (!isIntN(HalfSize, C->getSExtValue())) 3358 return false; 3359 } else { 3360 if (!isUIntN(HalfSize, C->getZExtValue())) 3361 return false; 3362 } 3363 continue; 3364 } 3365 return false; 3366 } 3367 3368 return true; 3369 } 3370 3371 static SDValue skipExtensionForVectorMULL(SDNode *N, SelectionDAG &DAG) { 3372 if (N->getOpcode() == ISD::SIGN_EXTEND || 3373 N->getOpcode() == ISD::ZERO_EXTEND || N->getOpcode() == ISD::ANY_EXTEND) 3374 return addRequiredExtensionForVectorMULL(N->getOperand(0), DAG, 3375 N->getOperand(0)->getValueType(0), 3376 N->getValueType(0), 3377 N->getOpcode()); 3378 3379 assert(N->getOpcode() == ISD::BUILD_VECTOR && "expected BUILD_VECTOR"); 3380 EVT VT = N->getValueType(0); 3381 SDLoc dl(N); 3382 unsigned EltSize = VT.getScalarSizeInBits() / 2; 3383 unsigned NumElts = VT.getVectorNumElements(); 3384 MVT TruncVT = MVT::getIntegerVT(EltSize); 3385 SmallVector<SDValue, 8> Ops; 3386 for (unsigned i = 0; i != NumElts; ++i) { 3387 ConstantSDNode *C = cast<ConstantSDNode>(N->getOperand(i)); 3388 const APInt &CInt = C->getAPIntValue(); 3389 // Element types smaller than 32 bits are not legal, so use i32 elements. 3390 // The values are implicitly truncated so sext vs. zext doesn't matter. 3391 Ops.push_back(DAG.getConstant(CInt.zextOrTrunc(32), dl, MVT::i32)); 3392 } 3393 return DAG.getBuildVector(MVT::getVectorVT(TruncVT, NumElts), dl, Ops); 3394 } 3395 3396 static bool isSignExtended(SDNode *N, SelectionDAG &DAG) { 3397 return N->getOpcode() == ISD::SIGN_EXTEND || 3398 N->getOpcode() == ISD::ANY_EXTEND || 3399 isExtendedBUILD_VECTOR(N, DAG, true); 3400 } 3401 3402 static bool isZeroExtended(SDNode *N, SelectionDAG &DAG) { 3403 return N->getOpcode() == ISD::ZERO_EXTEND || 3404 N->getOpcode() == ISD::ANY_EXTEND || 3405 isExtendedBUILD_VECTOR(N, DAG, false); 3406 } 3407 3408 static bool isAddSubSExt(SDNode *N, SelectionDAG &DAG) { 3409 unsigned Opcode = N->getOpcode(); 3410 if (Opcode == ISD::ADD || Opcode == ISD::SUB) { 3411 SDNode *N0 = N->getOperand(0).getNode(); 3412 SDNode *N1 = N->getOperand(1).getNode(); 3413 return N0->hasOneUse() && N1->hasOneUse() && 3414 isSignExtended(N0, DAG) && isSignExtended(N1, DAG); 3415 } 3416 return false; 3417 } 3418 3419 static bool isAddSubZExt(SDNode *N, SelectionDAG &DAG) { 3420 unsigned Opcode = N->getOpcode(); 3421 if (Opcode == ISD::ADD || Opcode == ISD::SUB) { 3422 SDNode *N0 = N->getOperand(0).getNode(); 3423 SDNode *N1 = N->getOperand(1).getNode(); 3424 return N0->hasOneUse() && N1->hasOneUse() && 3425 isZeroExtended(N0, DAG) && isZeroExtended(N1, DAG); 3426 } 3427 return false; 3428 } 3429 3430 SDValue AArch64TargetLowering::LowerFLT_ROUNDS_(SDValue Op, 3431 SelectionDAG &DAG) const { 3432 // The rounding mode is in bits 23:22 of the FPSCR. 3433 // The ARM rounding mode value to FLT_ROUNDS mapping is 0->1, 1->2, 2->3, 3->0 3434 // The formula we use to implement this is (((FPSCR + 1 << 22) >> 22) & 3) 3435 // so that the shift + and get folded into a bitfield extract. 3436 SDLoc dl(Op); 3437 3438 SDValue Chain = Op.getOperand(0); 3439 SDValue FPCR_64 = DAG.getNode( 3440 ISD::INTRINSIC_W_CHAIN, dl, {MVT::i64, MVT::Other}, 3441 {Chain, DAG.getConstant(Intrinsic::aarch64_get_fpcr, dl, MVT::i64)}); 3442 Chain = FPCR_64.getValue(1); 3443 SDValue FPCR_32 = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, FPCR_64); 3444 SDValue FltRounds = DAG.getNode(ISD::ADD, dl, MVT::i32, FPCR_32, 3445 DAG.getConstant(1U << 22, dl, MVT::i32)); 3446 SDValue RMODE = DAG.getNode(ISD::SRL, dl, MVT::i32, FltRounds, 3447 DAG.getConstant(22, dl, MVT::i32)); 3448 SDValue AND = DAG.getNode(ISD::AND, dl, MVT::i32, RMODE, 3449 DAG.getConstant(3, dl, MVT::i32)); 3450 return DAG.getMergeValues({AND, Chain}, dl); 3451 } 3452 3453 SDValue AArch64TargetLowering::LowerMUL(SDValue Op, SelectionDAG &DAG) const { 3454 EVT VT = Op.getValueType(); 3455 3456 // If SVE is available then i64 vector multiplications can also be made legal. 3457 bool OverrideNEON = VT == MVT::v2i64 || VT == MVT::v1i64; 3458 3459 if (VT.isScalableVector() || useSVEForFixedLengthVectorVT(VT, OverrideNEON)) 3460 return LowerToPredicatedOp(Op, DAG, AArch64ISD::MUL_PRED, OverrideNEON); 3461 3462 // Multiplications are only custom-lowered for 128-bit vectors so that 3463 // VMULL can be detected. Otherwise v2i64 multiplications are not legal. 3464 assert(VT.is128BitVector() && VT.isInteger() && 3465 "unexpected type for custom-lowering ISD::MUL"); 3466 SDNode *N0 = Op.getOperand(0).getNode(); 3467 SDNode *N1 = Op.getOperand(1).getNode(); 3468 unsigned NewOpc = 0; 3469 bool isMLA = false; 3470 bool isN0SExt = isSignExtended(N0, DAG); 3471 bool isN1SExt = isSignExtended(N1, DAG); 3472 if (isN0SExt && isN1SExt) 3473 NewOpc = AArch64ISD::SMULL; 3474 else { 3475 bool isN0ZExt = isZeroExtended(N0, DAG); 3476 bool isN1ZExt = isZeroExtended(N1, DAG); 3477 if (isN0ZExt && isN1ZExt) 3478 NewOpc = AArch64ISD::UMULL; 3479 else if (isN1SExt || isN1ZExt) { 3480 // Look for (s/zext A + s/zext B) * (s/zext C). We want to turn these 3481 // into (s/zext A * s/zext C) + (s/zext B * s/zext C) 3482 if (isN1SExt && isAddSubSExt(N0, DAG)) { 3483 NewOpc = AArch64ISD::SMULL; 3484 isMLA = true; 3485 } else if (isN1ZExt && isAddSubZExt(N0, DAG)) { 3486 NewOpc = AArch64ISD::UMULL; 3487 isMLA = true; 3488 } else if (isN0ZExt && isAddSubZExt(N1, DAG)) { 3489 std::swap(N0, N1); 3490 NewOpc = AArch64ISD::UMULL; 3491 isMLA = true; 3492 } 3493 } 3494 3495 if (!NewOpc) { 3496 if (VT == MVT::v2i64) 3497 // Fall through to expand this. It is not legal. 3498 return SDValue(); 3499 else 3500 // Other vector multiplications are legal. 3501 return Op; 3502 } 3503 } 3504 3505 // Legalize to a S/UMULL instruction 3506 SDLoc DL(Op); 3507 SDValue Op0; 3508 SDValue Op1 = skipExtensionForVectorMULL(N1, DAG); 3509 if (!isMLA) { 3510 Op0 = skipExtensionForVectorMULL(N0, DAG); 3511 assert(Op0.getValueType().is64BitVector() && 3512 Op1.getValueType().is64BitVector() && 3513 "unexpected types for extended operands to VMULL"); 3514 return DAG.getNode(NewOpc, DL, VT, Op0, Op1); 3515 } 3516 // Optimizing (zext A + zext B) * C, to (S/UMULL A, C) + (S/UMULL B, C) during 3517 // isel lowering to take advantage of no-stall back to back s/umul + s/umla. 3518 // This is true for CPUs with accumulate forwarding such as Cortex-A53/A57 3519 SDValue N00 = skipExtensionForVectorMULL(N0->getOperand(0).getNode(), DAG); 3520 SDValue N01 = skipExtensionForVectorMULL(N0->getOperand(1).getNode(), DAG); 3521 EVT Op1VT = Op1.getValueType(); 3522 return DAG.getNode(N0->getOpcode(), DL, VT, 3523 DAG.getNode(NewOpc, DL, VT, 3524 DAG.getNode(ISD::BITCAST, DL, Op1VT, N00), Op1), 3525 DAG.getNode(NewOpc, DL, VT, 3526 DAG.getNode(ISD::BITCAST, DL, Op1VT, N01), Op1)); 3527 } 3528 3529 static inline SDValue getPTrue(SelectionDAG &DAG, SDLoc DL, EVT VT, 3530 int Pattern) { 3531 return DAG.getNode(AArch64ISD::PTRUE, DL, VT, 3532 DAG.getTargetConstant(Pattern, DL, MVT::i32)); 3533 } 3534 3535 SDValue AArch64TargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op, 3536 SelectionDAG &DAG) const { 3537 unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue(); 3538 SDLoc dl(Op); 3539 switch (IntNo) { 3540 default: return SDValue(); // Don't custom lower most intrinsics. 3541 case Intrinsic::thread_pointer: { 3542 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 3543 return DAG.getNode(AArch64ISD::THREAD_POINTER, dl, PtrVT); 3544 } 3545 case Intrinsic::aarch64_neon_abs: { 3546 EVT Ty = Op.getValueType(); 3547 if (Ty == MVT::i64) { 3548 SDValue Result = DAG.getNode(ISD::BITCAST, dl, MVT::v1i64, 3549 Op.getOperand(1)); 3550 Result = DAG.getNode(ISD::ABS, dl, MVT::v1i64, Result); 3551 return DAG.getNode(ISD::BITCAST, dl, MVT::i64, Result); 3552 } else if (Ty.isVector() && Ty.isInteger() && isTypeLegal(Ty)) { 3553 return DAG.getNode(ISD::ABS, dl, Ty, Op.getOperand(1)); 3554 } else { 3555 report_fatal_error("Unexpected type for AArch64 NEON intrinic"); 3556 } 3557 } 3558 case Intrinsic::aarch64_neon_smax: 3559 return DAG.getNode(ISD::SMAX, dl, Op.getValueType(), 3560 Op.getOperand(1), Op.getOperand(2)); 3561 case Intrinsic::aarch64_neon_umax: 3562 return DAG.getNode(ISD::UMAX, dl, Op.getValueType(), 3563 Op.getOperand(1), Op.getOperand(2)); 3564 case Intrinsic::aarch64_neon_smin: 3565 return DAG.getNode(ISD::SMIN, dl, Op.getValueType(), 3566 Op.getOperand(1), Op.getOperand(2)); 3567 case Intrinsic::aarch64_neon_umin: 3568 return DAG.getNode(ISD::UMIN, dl, Op.getValueType(), 3569 Op.getOperand(1), Op.getOperand(2)); 3570 3571 case Intrinsic::aarch64_sve_sunpkhi: 3572 return DAG.getNode(AArch64ISD::SUNPKHI, dl, Op.getValueType(), 3573 Op.getOperand(1)); 3574 case Intrinsic::aarch64_sve_sunpklo: 3575 return DAG.getNode(AArch64ISD::SUNPKLO, dl, Op.getValueType(), 3576 Op.getOperand(1)); 3577 case Intrinsic::aarch64_sve_uunpkhi: 3578 return DAG.getNode(AArch64ISD::UUNPKHI, dl, Op.getValueType(), 3579 Op.getOperand(1)); 3580 case Intrinsic::aarch64_sve_uunpklo: 3581 return DAG.getNode(AArch64ISD::UUNPKLO, dl, Op.getValueType(), 3582 Op.getOperand(1)); 3583 case Intrinsic::aarch64_sve_clasta_n: 3584 return DAG.getNode(AArch64ISD::CLASTA_N, dl, Op.getValueType(), 3585 Op.getOperand(1), Op.getOperand(2), Op.getOperand(3)); 3586 case Intrinsic::aarch64_sve_clastb_n: 3587 return DAG.getNode(AArch64ISD::CLASTB_N, dl, Op.getValueType(), 3588 Op.getOperand(1), Op.getOperand(2), Op.getOperand(3)); 3589 case Intrinsic::aarch64_sve_lasta: 3590 return DAG.getNode(AArch64ISD::LASTA, dl, Op.getValueType(), 3591 Op.getOperand(1), Op.getOperand(2)); 3592 case Intrinsic::aarch64_sve_lastb: 3593 return DAG.getNode(AArch64ISD::LASTB, dl, Op.getValueType(), 3594 Op.getOperand(1), Op.getOperand(2)); 3595 case Intrinsic::aarch64_sve_rev: 3596 return DAG.getNode(AArch64ISD::REV, dl, Op.getValueType(), 3597 Op.getOperand(1)); 3598 case Intrinsic::aarch64_sve_tbl: 3599 return DAG.getNode(AArch64ISD::TBL, dl, Op.getValueType(), 3600 Op.getOperand(1), Op.getOperand(2)); 3601 case Intrinsic::aarch64_sve_trn1: 3602 return DAG.getNode(AArch64ISD::TRN1, dl, Op.getValueType(), 3603 Op.getOperand(1), Op.getOperand(2)); 3604 case Intrinsic::aarch64_sve_trn2: 3605 return DAG.getNode(AArch64ISD::TRN2, dl, Op.getValueType(), 3606 Op.getOperand(1), Op.getOperand(2)); 3607 case Intrinsic::aarch64_sve_uzp1: 3608 return DAG.getNode(AArch64ISD::UZP1, dl, Op.getValueType(), 3609 Op.getOperand(1), Op.getOperand(2)); 3610 case Intrinsic::aarch64_sve_uzp2: 3611 return DAG.getNode(AArch64ISD::UZP2, dl, Op.getValueType(), 3612 Op.getOperand(1), Op.getOperand(2)); 3613 case Intrinsic::aarch64_sve_zip1: 3614 return DAG.getNode(AArch64ISD::ZIP1, dl, Op.getValueType(), 3615 Op.getOperand(1), Op.getOperand(2)); 3616 case Intrinsic::aarch64_sve_zip2: 3617 return DAG.getNode(AArch64ISD::ZIP2, dl, Op.getValueType(), 3618 Op.getOperand(1), Op.getOperand(2)); 3619 case Intrinsic::aarch64_sve_ptrue: 3620 return DAG.getNode(AArch64ISD::PTRUE, dl, Op.getValueType(), 3621 Op.getOperand(1)); 3622 case Intrinsic::aarch64_sve_clz: 3623 return DAG.getNode(AArch64ISD::CTLZ_MERGE_PASSTHRU, dl, Op.getValueType(), 3624 Op.getOperand(2), Op.getOperand(3), Op.getOperand(1)); 3625 case Intrinsic::aarch64_sve_cnt: { 3626 SDValue Data = Op.getOperand(3); 3627 // CTPOP only supports integer operands. 3628 if (Data.getValueType().isFloatingPoint()) 3629 Data = DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Data); 3630 return DAG.getNode(AArch64ISD::CTPOP_MERGE_PASSTHRU, dl, Op.getValueType(), 3631 Op.getOperand(2), Data, Op.getOperand(1)); 3632 } 3633 case Intrinsic::aarch64_sve_dupq_lane: 3634 return LowerDUPQLane(Op, DAG); 3635 case Intrinsic::aarch64_sve_convert_from_svbool: 3636 return DAG.getNode(AArch64ISD::REINTERPRET_CAST, dl, Op.getValueType(), 3637 Op.getOperand(1)); 3638 case Intrinsic::aarch64_sve_fneg: 3639 return DAG.getNode(AArch64ISD::FNEG_MERGE_PASSTHRU, dl, Op.getValueType(), 3640 Op.getOperand(2), Op.getOperand(3), Op.getOperand(1)); 3641 case Intrinsic::aarch64_sve_frintp: 3642 return DAG.getNode(AArch64ISD::FCEIL_MERGE_PASSTHRU, dl, Op.getValueType(), 3643 Op.getOperand(2), Op.getOperand(3), Op.getOperand(1)); 3644 case Intrinsic::aarch64_sve_frintm: 3645 return DAG.getNode(AArch64ISD::FFLOOR_MERGE_PASSTHRU, dl, Op.getValueType(), 3646 Op.getOperand(2), Op.getOperand(3), Op.getOperand(1)); 3647 case Intrinsic::aarch64_sve_frinti: 3648 return DAG.getNode(AArch64ISD::FNEARBYINT_MERGE_PASSTHRU, dl, Op.getValueType(), 3649 Op.getOperand(2), Op.getOperand(3), Op.getOperand(1)); 3650 case Intrinsic::aarch64_sve_frintx: 3651 return DAG.getNode(AArch64ISD::FRINT_MERGE_PASSTHRU, dl, Op.getValueType(), 3652 Op.getOperand(2), Op.getOperand(3), Op.getOperand(1)); 3653 case Intrinsic::aarch64_sve_frinta: 3654 return DAG.getNode(AArch64ISD::FROUND_MERGE_PASSTHRU, dl, Op.getValueType(), 3655 Op.getOperand(2), Op.getOperand(3), Op.getOperand(1)); 3656 case Intrinsic::aarch64_sve_frintn: 3657 return DAG.getNode(AArch64ISD::FROUNDEVEN_MERGE_PASSTHRU, dl, Op.getValueType(), 3658 Op.getOperand(2), Op.getOperand(3), Op.getOperand(1)); 3659 case Intrinsic::aarch64_sve_frintz: 3660 return DAG.getNode(AArch64ISD::FTRUNC_MERGE_PASSTHRU, dl, Op.getValueType(), 3661 Op.getOperand(2), Op.getOperand(3), Op.getOperand(1)); 3662 case Intrinsic::aarch64_sve_ucvtf: 3663 return DAG.getNode(AArch64ISD::UINT_TO_FP_MERGE_PASSTHRU, dl, 3664 Op.getValueType(), Op.getOperand(2), Op.getOperand(3), 3665 Op.getOperand(1)); 3666 case Intrinsic::aarch64_sve_scvtf: 3667 return DAG.getNode(AArch64ISD::SINT_TO_FP_MERGE_PASSTHRU, dl, 3668 Op.getValueType(), Op.getOperand(2), Op.getOperand(3), 3669 Op.getOperand(1)); 3670 case Intrinsic::aarch64_sve_fcvtzu: 3671 return DAG.getNode(AArch64ISD::FCVTZU_MERGE_PASSTHRU, dl, 3672 Op.getValueType(), Op.getOperand(2), Op.getOperand(3), 3673 Op.getOperand(1)); 3674 case Intrinsic::aarch64_sve_fcvtzs: 3675 return DAG.getNode(AArch64ISD::FCVTZS_MERGE_PASSTHRU, dl, 3676 Op.getValueType(), Op.getOperand(2), Op.getOperand(3), 3677 Op.getOperand(1)); 3678 case Intrinsic::aarch64_sve_fsqrt: 3679 return DAG.getNode(AArch64ISD::FSQRT_MERGE_PASSTHRU, dl, Op.getValueType(), 3680 Op.getOperand(2), Op.getOperand(3), Op.getOperand(1)); 3681 case Intrinsic::aarch64_sve_frecpx: 3682 return DAG.getNode(AArch64ISD::FRECPX_MERGE_PASSTHRU, dl, Op.getValueType(), 3683 Op.getOperand(2), Op.getOperand(3), Op.getOperand(1)); 3684 case Intrinsic::aarch64_sve_fabs: 3685 return DAG.getNode(AArch64ISD::FABS_MERGE_PASSTHRU, dl, Op.getValueType(), 3686 Op.getOperand(2), Op.getOperand(3), Op.getOperand(1)); 3687 case Intrinsic::aarch64_sve_abs: 3688 return DAG.getNode(AArch64ISD::ABS_MERGE_PASSTHRU, dl, Op.getValueType(), 3689 Op.getOperand(2), Op.getOperand(3), Op.getOperand(1)); 3690 case Intrinsic::aarch64_sve_neg: 3691 return DAG.getNode(AArch64ISD::NEG_MERGE_PASSTHRU, dl, Op.getValueType(), 3692 Op.getOperand(2), Op.getOperand(3), Op.getOperand(1)); 3693 case Intrinsic::aarch64_sve_convert_to_svbool: { 3694 EVT OutVT = Op.getValueType(); 3695 EVT InVT = Op.getOperand(1).getValueType(); 3696 // Return the operand if the cast isn't changing type, 3697 // i.e. <n x 16 x i1> -> <n x 16 x i1> 3698 if (InVT == OutVT) 3699 return Op.getOperand(1); 3700 // Otherwise, zero the newly introduced lanes. 3701 SDValue Reinterpret = 3702 DAG.getNode(AArch64ISD::REINTERPRET_CAST, dl, OutVT, Op.getOperand(1)); 3703 SDValue Mask = getPTrue(DAG, dl, InVT, AArch64SVEPredPattern::all); 3704 SDValue MaskReinterpret = 3705 DAG.getNode(AArch64ISD::REINTERPRET_CAST, dl, OutVT, Mask); 3706 return DAG.getNode(ISD::AND, dl, OutVT, Reinterpret, MaskReinterpret); 3707 } 3708 3709 case Intrinsic::aarch64_sve_insr: { 3710 SDValue Scalar = Op.getOperand(2); 3711 EVT ScalarTy = Scalar.getValueType(); 3712 if ((ScalarTy == MVT::i8) || (ScalarTy == MVT::i16)) 3713 Scalar = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, Scalar); 3714 3715 return DAG.getNode(AArch64ISD::INSR, dl, Op.getValueType(), 3716 Op.getOperand(1), Scalar); 3717 } 3718 case Intrinsic::aarch64_sve_rbit: 3719 return DAG.getNode(AArch64ISD::BITREVERSE_MERGE_PASSTHRU, dl, 3720 Op.getValueType(), Op.getOperand(2), Op.getOperand(3), 3721 Op.getOperand(1)); 3722 case Intrinsic::aarch64_sve_revb: 3723 return DAG.getNode(AArch64ISD::BSWAP_MERGE_PASSTHRU, dl, Op.getValueType(), 3724 Op.getOperand(2), Op.getOperand(3), Op.getOperand(1)); 3725 case Intrinsic::aarch64_sve_sxtb: 3726 return DAG.getNode( 3727 AArch64ISD::SIGN_EXTEND_INREG_MERGE_PASSTHRU, dl, Op.getValueType(), 3728 Op.getOperand(2), Op.getOperand(3), 3729 DAG.getValueType(Op.getValueType().changeVectorElementType(MVT::i8)), 3730 Op.getOperand(1)); 3731 case Intrinsic::aarch64_sve_sxth: 3732 return DAG.getNode( 3733 AArch64ISD::SIGN_EXTEND_INREG_MERGE_PASSTHRU, dl, Op.getValueType(), 3734 Op.getOperand(2), Op.getOperand(3), 3735 DAG.getValueType(Op.getValueType().changeVectorElementType(MVT::i16)), 3736 Op.getOperand(1)); 3737 case Intrinsic::aarch64_sve_sxtw: 3738 return DAG.getNode( 3739 AArch64ISD::SIGN_EXTEND_INREG_MERGE_PASSTHRU, dl, Op.getValueType(), 3740 Op.getOperand(2), Op.getOperand(3), 3741 DAG.getValueType(Op.getValueType().changeVectorElementType(MVT::i32)), 3742 Op.getOperand(1)); 3743 case Intrinsic::aarch64_sve_uxtb: 3744 return DAG.getNode( 3745 AArch64ISD::ZERO_EXTEND_INREG_MERGE_PASSTHRU, dl, Op.getValueType(), 3746 Op.getOperand(2), Op.getOperand(3), 3747 DAG.getValueType(Op.getValueType().changeVectorElementType(MVT::i8)), 3748 Op.getOperand(1)); 3749 case Intrinsic::aarch64_sve_uxth: 3750 return DAG.getNode( 3751 AArch64ISD::ZERO_EXTEND_INREG_MERGE_PASSTHRU, dl, Op.getValueType(), 3752 Op.getOperand(2), Op.getOperand(3), 3753 DAG.getValueType(Op.getValueType().changeVectorElementType(MVT::i16)), 3754 Op.getOperand(1)); 3755 case Intrinsic::aarch64_sve_uxtw: 3756 return DAG.getNode( 3757 AArch64ISD::ZERO_EXTEND_INREG_MERGE_PASSTHRU, dl, Op.getValueType(), 3758 Op.getOperand(2), Op.getOperand(3), 3759 DAG.getValueType(Op.getValueType().changeVectorElementType(MVT::i32)), 3760 Op.getOperand(1)); 3761 3762 case Intrinsic::localaddress: { 3763 const auto &MF = DAG.getMachineFunction(); 3764 const auto *RegInfo = Subtarget->getRegisterInfo(); 3765 unsigned Reg = RegInfo->getLocalAddressRegister(MF); 3766 return DAG.getCopyFromReg(DAG.getEntryNode(), dl, Reg, 3767 Op.getSimpleValueType()); 3768 } 3769 3770 case Intrinsic::eh_recoverfp: { 3771 // FIXME: This needs to be implemented to correctly handle highly aligned 3772 // stack objects. For now we simply return the incoming FP. Refer D53541 3773 // for more details. 3774 SDValue FnOp = Op.getOperand(1); 3775 SDValue IncomingFPOp = Op.getOperand(2); 3776 GlobalAddressSDNode *GSD = dyn_cast<GlobalAddressSDNode>(FnOp); 3777 auto *Fn = dyn_cast_or_null<Function>(GSD ? GSD->getGlobal() : nullptr); 3778 if (!Fn) 3779 report_fatal_error( 3780 "llvm.eh.recoverfp must take a function as the first argument"); 3781 return IncomingFPOp; 3782 } 3783 3784 case Intrinsic::aarch64_neon_vsri: 3785 case Intrinsic::aarch64_neon_vsli: { 3786 EVT Ty = Op.getValueType(); 3787 3788 if (!Ty.isVector()) 3789 report_fatal_error("Unexpected type for aarch64_neon_vsli"); 3790 3791 assert(Op.getConstantOperandVal(3) <= Ty.getScalarSizeInBits()); 3792 3793 bool IsShiftRight = IntNo == Intrinsic::aarch64_neon_vsri; 3794 unsigned Opcode = IsShiftRight ? AArch64ISD::VSRI : AArch64ISD::VSLI; 3795 return DAG.getNode(Opcode, dl, Ty, Op.getOperand(1), Op.getOperand(2), 3796 Op.getOperand(3)); 3797 } 3798 3799 case Intrinsic::aarch64_neon_srhadd: 3800 case Intrinsic::aarch64_neon_urhadd: 3801 case Intrinsic::aarch64_neon_shadd: 3802 case Intrinsic::aarch64_neon_uhadd: { 3803 bool IsSignedAdd = (IntNo == Intrinsic::aarch64_neon_srhadd || 3804 IntNo == Intrinsic::aarch64_neon_shadd); 3805 bool IsRoundingAdd = (IntNo == Intrinsic::aarch64_neon_srhadd || 3806 IntNo == Intrinsic::aarch64_neon_urhadd); 3807 unsigned Opcode = 3808 IsSignedAdd ? (IsRoundingAdd ? AArch64ISD::SRHADD : AArch64ISD::SHADD) 3809 : (IsRoundingAdd ? AArch64ISD::URHADD : AArch64ISD::UHADD); 3810 return DAG.getNode(Opcode, dl, Op.getValueType(), Op.getOperand(1), 3811 Op.getOperand(2)); 3812 } 3813 3814 case Intrinsic::aarch64_neon_uabd: { 3815 return DAG.getNode(AArch64ISD::UABD, dl, Op.getValueType(), 3816 Op.getOperand(1), Op.getOperand(2)); 3817 } 3818 case Intrinsic::aarch64_neon_sabd: { 3819 return DAG.getNode(AArch64ISD::SABD, dl, Op.getValueType(), 3820 Op.getOperand(1), Op.getOperand(2)); 3821 } 3822 } 3823 } 3824 3825 bool AArch64TargetLowering::shouldExtendGSIndex(EVT VT, EVT &EltTy) const { 3826 if (VT.getVectorElementType() == MVT::i8 || 3827 VT.getVectorElementType() == MVT::i16) { 3828 EltTy = MVT::i32; 3829 return true; 3830 } 3831 return false; 3832 } 3833 3834 bool AArch64TargetLowering::shouldRemoveExtendFromGSIndex(EVT VT) const { 3835 if (VT.getVectorElementType() == MVT::i32 && 3836 VT.getVectorElementCount().getKnownMinValue() >= 4) 3837 return true; 3838 3839 return false; 3840 } 3841 3842 bool AArch64TargetLowering::isVectorLoadExtDesirable(SDValue ExtVal) const { 3843 return ExtVal.getValueType().isScalableVector(); 3844 } 3845 3846 unsigned getGatherVecOpcode(bool IsScaled, bool IsSigned, bool NeedsExtend) { 3847 std::map<std::tuple<bool, bool, bool>, unsigned> AddrModes = { 3848 {std::make_tuple(/*Scaled*/ false, /*Signed*/ false, /*Extend*/ false), 3849 AArch64ISD::GLD1_MERGE_ZERO}, 3850 {std::make_tuple(/*Scaled*/ false, /*Signed*/ false, /*Extend*/ true), 3851 AArch64ISD::GLD1_UXTW_MERGE_ZERO}, 3852 {std::make_tuple(/*Scaled*/ false, /*Signed*/ true, /*Extend*/ false), 3853 AArch64ISD::GLD1_MERGE_ZERO}, 3854 {std::make_tuple(/*Scaled*/ false, /*Signed*/ true, /*Extend*/ true), 3855 AArch64ISD::GLD1_SXTW_MERGE_ZERO}, 3856 {std::make_tuple(/*Scaled*/ true, /*Signed*/ false, /*Extend*/ false), 3857 AArch64ISD::GLD1_SCALED_MERGE_ZERO}, 3858 {std::make_tuple(/*Scaled*/ true, /*Signed*/ false, /*Extend*/ true), 3859 AArch64ISD::GLD1_UXTW_SCALED_MERGE_ZERO}, 3860 {std::make_tuple(/*Scaled*/ true, /*Signed*/ true, /*Extend*/ false), 3861 AArch64ISD::GLD1_SCALED_MERGE_ZERO}, 3862 {std::make_tuple(/*Scaled*/ true, /*Signed*/ true, /*Extend*/ true), 3863 AArch64ISD::GLD1_SXTW_SCALED_MERGE_ZERO}, 3864 }; 3865 auto Key = std::make_tuple(IsScaled, IsSigned, NeedsExtend); 3866 return AddrModes.find(Key)->second; 3867 } 3868 3869 unsigned getScatterVecOpcode(bool IsScaled, bool IsSigned, bool NeedsExtend) { 3870 std::map<std::tuple<bool, bool, bool>, unsigned> AddrModes = { 3871 {std::make_tuple(/*Scaled*/ false, /*Signed*/ false, /*Extend*/ false), 3872 AArch64ISD::SST1_PRED}, 3873 {std::make_tuple(/*Scaled*/ false, /*Signed*/ false, /*Extend*/ true), 3874 AArch64ISD::SST1_UXTW_PRED}, 3875 {std::make_tuple(/*Scaled*/ false, /*Signed*/ true, /*Extend*/ false), 3876 AArch64ISD::SST1_PRED}, 3877 {std::make_tuple(/*Scaled*/ false, /*Signed*/ true, /*Extend*/ true), 3878 AArch64ISD::SST1_SXTW_PRED}, 3879 {std::make_tuple(/*Scaled*/ true, /*Signed*/ false, /*Extend*/ false), 3880 AArch64ISD::SST1_SCALED_PRED}, 3881 {std::make_tuple(/*Scaled*/ true, /*Signed*/ false, /*Extend*/ true), 3882 AArch64ISD::SST1_UXTW_SCALED_PRED}, 3883 {std::make_tuple(/*Scaled*/ true, /*Signed*/ true, /*Extend*/ false), 3884 AArch64ISD::SST1_SCALED_PRED}, 3885 {std::make_tuple(/*Scaled*/ true, /*Signed*/ true, /*Extend*/ true), 3886 AArch64ISD::SST1_SXTW_SCALED_PRED}, 3887 }; 3888 auto Key = std::make_tuple(IsScaled, IsSigned, NeedsExtend); 3889 return AddrModes.find(Key)->second; 3890 } 3891 3892 unsigned getSignExtendedGatherOpcode(unsigned Opcode) { 3893 switch (Opcode) { 3894 default: 3895 llvm_unreachable("unimplemented opcode"); 3896 return Opcode; 3897 case AArch64ISD::GLD1_MERGE_ZERO: 3898 return AArch64ISD::GLD1S_MERGE_ZERO; 3899 case AArch64ISD::GLD1_IMM_MERGE_ZERO: 3900 return AArch64ISD::GLD1S_IMM_MERGE_ZERO; 3901 case AArch64ISD::GLD1_UXTW_MERGE_ZERO: 3902 return AArch64ISD::GLD1S_UXTW_MERGE_ZERO; 3903 case AArch64ISD::GLD1_SXTW_MERGE_ZERO: 3904 return AArch64ISD::GLD1S_SXTW_MERGE_ZERO; 3905 case AArch64ISD::GLD1_SCALED_MERGE_ZERO: 3906 return AArch64ISD::GLD1S_SCALED_MERGE_ZERO; 3907 case AArch64ISD::GLD1_UXTW_SCALED_MERGE_ZERO: 3908 return AArch64ISD::GLD1S_UXTW_SCALED_MERGE_ZERO; 3909 case AArch64ISD::GLD1_SXTW_SCALED_MERGE_ZERO: 3910 return AArch64ISD::GLD1S_SXTW_SCALED_MERGE_ZERO; 3911 } 3912 } 3913 3914 bool getGatherScatterIndexIsExtended(SDValue Index) { 3915 unsigned Opcode = Index.getOpcode(); 3916 if (Opcode == ISD::SIGN_EXTEND_INREG) 3917 return true; 3918 3919 if (Opcode == ISD::AND) { 3920 SDValue Splat = Index.getOperand(1); 3921 if (Splat.getOpcode() != ISD::SPLAT_VECTOR) 3922 return false; 3923 ConstantSDNode *Mask = dyn_cast<ConstantSDNode>(Splat.getOperand(0)); 3924 if (!Mask || Mask->getZExtValue() != 0xFFFFFFFF) 3925 return false; 3926 return true; 3927 } 3928 3929 return false; 3930 } 3931 3932 // If the base pointer of a masked gather or scatter is null, we 3933 // may be able to swap BasePtr & Index and use the vector + register 3934 // or vector + immediate addressing mode, e.g. 3935 // VECTOR + REGISTER: 3936 // getelementptr nullptr, <vscale x N x T> (splat(%offset)) + %indices) 3937 // -> getelementptr %offset, <vscale x N x T> %indices 3938 // VECTOR + IMMEDIATE: 3939 // getelementptr nullptr, <vscale x N x T> (splat(#x)) + %indices) 3940 // -> getelementptr #x, <vscale x N x T> %indices 3941 void selectGatherScatterAddrMode(SDValue &BasePtr, SDValue &Index, EVT MemVT, 3942 unsigned &Opcode, bool IsGather, 3943 SelectionDAG &DAG) { 3944 if (!isNullConstant(BasePtr)) 3945 return; 3946 3947 ConstantSDNode *Offset = nullptr; 3948 if (Index.getOpcode() == ISD::ADD) 3949 if (auto SplatVal = DAG.getSplatValue(Index.getOperand(1))) { 3950 if (isa<ConstantSDNode>(SplatVal)) 3951 Offset = cast<ConstantSDNode>(SplatVal); 3952 else { 3953 BasePtr = SplatVal; 3954 Index = Index->getOperand(0); 3955 return; 3956 } 3957 } 3958 3959 unsigned NewOp = 3960 IsGather ? AArch64ISD::GLD1_IMM_MERGE_ZERO : AArch64ISD::SST1_IMM_PRED; 3961 3962 if (!Offset) { 3963 std::swap(BasePtr, Index); 3964 Opcode = NewOp; 3965 return; 3966 } 3967 3968 uint64_t OffsetVal = Offset->getZExtValue(); 3969 unsigned ScalarSizeInBytes = MemVT.getScalarSizeInBits() / 8; 3970 auto ConstOffset = DAG.getConstant(OffsetVal, SDLoc(Index), MVT::i64); 3971 3972 if (OffsetVal % ScalarSizeInBytes || OffsetVal / ScalarSizeInBytes > 31) { 3973 // Index is out of range for the immediate addressing mode 3974 BasePtr = ConstOffset; 3975 Index = Index->getOperand(0); 3976 return; 3977 } 3978 3979 // Immediate is in range 3980 Opcode = NewOp; 3981 BasePtr = Index->getOperand(0); 3982 Index = ConstOffset; 3983 } 3984 3985 SDValue AArch64TargetLowering::LowerMGATHER(SDValue Op, 3986 SelectionDAG &DAG) const { 3987 SDLoc DL(Op); 3988 MaskedGatherSDNode *MGT = cast<MaskedGatherSDNode>(Op); 3989 assert(MGT && "Can only custom lower gather load nodes"); 3990 3991 SDValue Index = MGT->getIndex(); 3992 SDValue Chain = MGT->getChain(); 3993 SDValue PassThru = MGT->getPassThru(); 3994 SDValue Mask = MGT->getMask(); 3995 SDValue BasePtr = MGT->getBasePtr(); 3996 ISD::LoadExtType ExtTy = MGT->getExtensionType(); 3997 3998 ISD::MemIndexType IndexType = MGT->getIndexType(); 3999 bool IsScaled = 4000 IndexType == ISD::SIGNED_SCALED || IndexType == ISD::UNSIGNED_SCALED; 4001 bool IsSigned = 4002 IndexType == ISD::SIGNED_SCALED || IndexType == ISD::SIGNED_UNSCALED; 4003 bool IdxNeedsExtend = 4004 getGatherScatterIndexIsExtended(Index) || 4005 Index.getSimpleValueType().getVectorElementType() == MVT::i32; 4006 bool ResNeedsSignExtend = ExtTy == ISD::EXTLOAD || ExtTy == ISD::SEXTLOAD; 4007 4008 EVT VT = PassThru.getSimpleValueType(); 4009 EVT MemVT = MGT->getMemoryVT(); 4010 SDValue InputVT = DAG.getValueType(MemVT); 4011 4012 if (VT.getVectorElementType() == MVT::bf16 && 4013 !static_cast<const AArch64Subtarget &>(DAG.getSubtarget()).hasBF16()) 4014 return SDValue(); 4015 4016 // Handle FP data by using an integer gather and casting the result. 4017 if (VT.isFloatingPoint()) { 4018 EVT PassThruVT = getPackedSVEVectorVT(VT.getVectorElementCount()); 4019 PassThru = getSVESafeBitCast(PassThruVT, PassThru, DAG); 4020 InputVT = DAG.getValueType(MemVT.changeVectorElementTypeToInteger()); 4021 } 4022 4023 SDVTList VTs = DAG.getVTList(PassThru.getSimpleValueType(), MVT::Other); 4024 4025 if (getGatherScatterIndexIsExtended(Index)) 4026 Index = Index.getOperand(0); 4027 4028 unsigned Opcode = getGatherVecOpcode(IsScaled, IsSigned, IdxNeedsExtend); 4029 selectGatherScatterAddrMode(BasePtr, Index, MemVT, Opcode, 4030 /*isGather=*/true, DAG); 4031 4032 if (ResNeedsSignExtend) 4033 Opcode = getSignExtendedGatherOpcode(Opcode); 4034 4035 SDValue Ops[] = {Chain, Mask, BasePtr, Index, InputVT, PassThru}; 4036 SDValue Gather = DAG.getNode(Opcode, DL, VTs, Ops); 4037 4038 if (VT.isFloatingPoint()) { 4039 SDValue Cast = getSVESafeBitCast(VT, Gather, DAG); 4040 return DAG.getMergeValues({Cast, Gather}, DL); 4041 } 4042 4043 return Gather; 4044 } 4045 4046 SDValue AArch64TargetLowering::LowerMSCATTER(SDValue Op, 4047 SelectionDAG &DAG) const { 4048 SDLoc DL(Op); 4049 MaskedScatterSDNode *MSC = cast<MaskedScatterSDNode>(Op); 4050 assert(MSC && "Can only custom lower scatter store nodes"); 4051 4052 SDValue Index = MSC->getIndex(); 4053 SDValue Chain = MSC->getChain(); 4054 SDValue StoreVal = MSC->getValue(); 4055 SDValue Mask = MSC->getMask(); 4056 SDValue BasePtr = MSC->getBasePtr(); 4057 4058 ISD::MemIndexType IndexType = MSC->getIndexType(); 4059 bool IsScaled = 4060 IndexType == ISD::SIGNED_SCALED || IndexType == ISD::UNSIGNED_SCALED; 4061 bool IsSigned = 4062 IndexType == ISD::SIGNED_SCALED || IndexType == ISD::SIGNED_UNSCALED; 4063 bool NeedsExtend = 4064 getGatherScatterIndexIsExtended(Index) || 4065 Index.getSimpleValueType().getVectorElementType() == MVT::i32; 4066 4067 EVT VT = StoreVal.getSimpleValueType(); 4068 SDVTList VTs = DAG.getVTList(MVT::Other); 4069 EVT MemVT = MSC->getMemoryVT(); 4070 SDValue InputVT = DAG.getValueType(MemVT); 4071 4072 if (VT.getVectorElementType() == MVT::bf16 && 4073 !static_cast<const AArch64Subtarget &>(DAG.getSubtarget()).hasBF16()) 4074 return SDValue(); 4075 4076 // Handle FP data by casting the data so an integer scatter can be used. 4077 if (VT.isFloatingPoint()) { 4078 EVT StoreValVT = getPackedSVEVectorVT(VT.getVectorElementCount()); 4079 StoreVal = getSVESafeBitCast(StoreValVT, StoreVal, DAG); 4080 InputVT = DAG.getValueType(MemVT.changeVectorElementTypeToInteger()); 4081 } 4082 4083 if (getGatherScatterIndexIsExtended(Index)) 4084 Index = Index.getOperand(0); 4085 4086 unsigned Opcode = getScatterVecOpcode(IsScaled, IsSigned, NeedsExtend); 4087 selectGatherScatterAddrMode(BasePtr, Index, MemVT, Opcode, 4088 /*isGather=*/false, DAG); 4089 4090 SDValue Ops[] = {Chain, StoreVal, Mask, BasePtr, Index, InputVT}; 4091 return DAG.getNode(Opcode, DL, VTs, Ops); 4092 } 4093 4094 // Custom lower trunc store for v4i8 vectors, since it is promoted to v4i16. 4095 static SDValue LowerTruncateVectorStore(SDLoc DL, StoreSDNode *ST, 4096 EVT VT, EVT MemVT, 4097 SelectionDAG &DAG) { 4098 assert(VT.isVector() && "VT should be a vector type"); 4099 assert(MemVT == MVT::v4i8 && VT == MVT::v4i16); 4100 4101 SDValue Value = ST->getValue(); 4102 4103 // It first extend the promoted v4i16 to v8i16, truncate to v8i8, and extract 4104 // the word lane which represent the v4i8 subvector. It optimizes the store 4105 // to: 4106 // 4107 // xtn v0.8b, v0.8h 4108 // str s0, [x0] 4109 4110 SDValue Undef = DAG.getUNDEF(MVT::i16); 4111 SDValue UndefVec = DAG.getBuildVector(MVT::v4i16, DL, 4112 {Undef, Undef, Undef, Undef}); 4113 4114 SDValue TruncExt = DAG.getNode(ISD::CONCAT_VECTORS, DL, MVT::v8i16, 4115 Value, UndefVec); 4116 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, DL, MVT::v8i8, TruncExt); 4117 4118 Trunc = DAG.getNode(ISD::BITCAST, DL, MVT::v2i32, Trunc); 4119 SDValue ExtractTrunc = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32, 4120 Trunc, DAG.getConstant(0, DL, MVT::i64)); 4121 4122 return DAG.getStore(ST->getChain(), DL, ExtractTrunc, 4123 ST->getBasePtr(), ST->getMemOperand()); 4124 } 4125 4126 // Custom lowering for any store, vector or scalar and/or default or with 4127 // a truncate operations. Currently only custom lower truncate operation 4128 // from vector v4i16 to v4i8 or volatile stores of i128. 4129 SDValue AArch64TargetLowering::LowerSTORE(SDValue Op, 4130 SelectionDAG &DAG) const { 4131 SDLoc Dl(Op); 4132 StoreSDNode *StoreNode = cast<StoreSDNode>(Op); 4133 assert (StoreNode && "Can only custom lower store nodes"); 4134 4135 SDValue Value = StoreNode->getValue(); 4136 4137 EVT VT = Value.getValueType(); 4138 EVT MemVT = StoreNode->getMemoryVT(); 4139 4140 if (VT.isVector()) { 4141 if (useSVEForFixedLengthVectorVT(VT)) 4142 return LowerFixedLengthVectorStoreToSVE(Op, DAG); 4143 4144 unsigned AS = StoreNode->getAddressSpace(); 4145 Align Alignment = StoreNode->getAlign(); 4146 if (Alignment < MemVT.getStoreSize() && 4147 !allowsMisalignedMemoryAccesses(MemVT, AS, Alignment, 4148 StoreNode->getMemOperand()->getFlags(), 4149 nullptr)) { 4150 return scalarizeVectorStore(StoreNode, DAG); 4151 } 4152 4153 if (StoreNode->isTruncatingStore()) { 4154 return LowerTruncateVectorStore(Dl, StoreNode, VT, MemVT, DAG); 4155 } 4156 // 256 bit non-temporal stores can be lowered to STNP. Do this as part of 4157 // the custom lowering, as there are no un-paired non-temporal stores and 4158 // legalization will break up 256 bit inputs. 4159 ElementCount EC = MemVT.getVectorElementCount(); 4160 if (StoreNode->isNonTemporal() && MemVT.getSizeInBits() == 256u && 4161 EC.isKnownEven() && 4162 ((MemVT.getScalarSizeInBits() == 8u || 4163 MemVT.getScalarSizeInBits() == 16u || 4164 MemVT.getScalarSizeInBits() == 32u || 4165 MemVT.getScalarSizeInBits() == 64u))) { 4166 SDValue Lo = 4167 DAG.getNode(ISD::EXTRACT_SUBVECTOR, Dl, 4168 MemVT.getHalfNumVectorElementsVT(*DAG.getContext()), 4169 StoreNode->getValue(), DAG.getConstant(0, Dl, MVT::i64)); 4170 SDValue Hi = 4171 DAG.getNode(ISD::EXTRACT_SUBVECTOR, Dl, 4172 MemVT.getHalfNumVectorElementsVT(*DAG.getContext()), 4173 StoreNode->getValue(), 4174 DAG.getConstant(EC.getKnownMinValue() / 2, Dl, MVT::i64)); 4175 SDValue Result = DAG.getMemIntrinsicNode( 4176 AArch64ISD::STNP, Dl, DAG.getVTList(MVT::Other), 4177 {StoreNode->getChain(), Lo, Hi, StoreNode->getBasePtr()}, 4178 StoreNode->getMemoryVT(), StoreNode->getMemOperand()); 4179 return Result; 4180 } 4181 } else if (MemVT == MVT::i128 && StoreNode->isVolatile()) { 4182 assert(StoreNode->getValue()->getValueType(0) == MVT::i128); 4183 SDValue Lo = 4184 DAG.getNode(ISD::EXTRACT_ELEMENT, Dl, MVT::i64, StoreNode->getValue(), 4185 DAG.getConstant(0, Dl, MVT::i64)); 4186 SDValue Hi = 4187 DAG.getNode(ISD::EXTRACT_ELEMENT, Dl, MVT::i64, StoreNode->getValue(), 4188 DAG.getConstant(1, Dl, MVT::i64)); 4189 SDValue Result = DAG.getMemIntrinsicNode( 4190 AArch64ISD::STP, Dl, DAG.getVTList(MVT::Other), 4191 {StoreNode->getChain(), Lo, Hi, StoreNode->getBasePtr()}, 4192 StoreNode->getMemoryVT(), StoreNode->getMemOperand()); 4193 return Result; 4194 } 4195 4196 return SDValue(); 4197 } 4198 4199 // Generate SUBS and CSEL for integer abs. 4200 SDValue AArch64TargetLowering::LowerABS(SDValue Op, SelectionDAG &DAG) const { 4201 MVT VT = Op.getSimpleValueType(); 4202 4203 if (VT.isVector()) 4204 return LowerToPredicatedOp(Op, DAG, AArch64ISD::ABS_MERGE_PASSTHRU); 4205 4206 SDLoc DL(Op); 4207 SDValue Neg = DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, VT), 4208 Op.getOperand(0)); 4209 // Generate SUBS & CSEL. 4210 SDValue Cmp = 4211 DAG.getNode(AArch64ISD::SUBS, DL, DAG.getVTList(VT, MVT::i32), 4212 Op.getOperand(0), DAG.getConstant(0, DL, VT)); 4213 return DAG.getNode(AArch64ISD::CSEL, DL, VT, Op.getOperand(0), Neg, 4214 DAG.getConstant(AArch64CC::PL, DL, MVT::i32), 4215 Cmp.getValue(1)); 4216 } 4217 4218 SDValue AArch64TargetLowering::LowerOperation(SDValue Op, 4219 SelectionDAG &DAG) const { 4220 LLVM_DEBUG(dbgs() << "Custom lowering: "); 4221 LLVM_DEBUG(Op.dump()); 4222 4223 switch (Op.getOpcode()) { 4224 default: 4225 llvm_unreachable("unimplemented operand"); 4226 return SDValue(); 4227 case ISD::BITCAST: 4228 return LowerBITCAST(Op, DAG); 4229 case ISD::GlobalAddress: 4230 return LowerGlobalAddress(Op, DAG); 4231 case ISD::GlobalTLSAddress: 4232 return LowerGlobalTLSAddress(Op, DAG); 4233 case ISD::SETCC: 4234 case ISD::STRICT_FSETCC: 4235 case ISD::STRICT_FSETCCS: 4236 return LowerSETCC(Op, DAG); 4237 case ISD::BR_CC: 4238 return LowerBR_CC(Op, DAG); 4239 case ISD::SELECT: 4240 return LowerSELECT(Op, DAG); 4241 case ISD::SELECT_CC: 4242 return LowerSELECT_CC(Op, DAG); 4243 case ISD::JumpTable: 4244 return LowerJumpTable(Op, DAG); 4245 case ISD::BR_JT: 4246 return LowerBR_JT(Op, DAG); 4247 case ISD::ConstantPool: 4248 return LowerConstantPool(Op, DAG); 4249 case ISD::BlockAddress: 4250 return LowerBlockAddress(Op, DAG); 4251 case ISD::VASTART: 4252 return LowerVASTART(Op, DAG); 4253 case ISD::VACOPY: 4254 return LowerVACOPY(Op, DAG); 4255 case ISD::VAARG: 4256 return LowerVAARG(Op, DAG); 4257 case ISD::ADDC: 4258 case ISD::ADDE: 4259 case ISD::SUBC: 4260 case ISD::SUBE: 4261 return LowerADDC_ADDE_SUBC_SUBE(Op, DAG); 4262 case ISD::SADDO: 4263 case ISD::UADDO: 4264 case ISD::SSUBO: 4265 case ISD::USUBO: 4266 case ISD::SMULO: 4267 case ISD::UMULO: 4268 return LowerXALUO(Op, DAG); 4269 case ISD::FADD: 4270 return LowerToPredicatedOp(Op, DAG, AArch64ISD::FADD_PRED); 4271 case ISD::FSUB: 4272 return LowerToPredicatedOp(Op, DAG, AArch64ISD::FSUB_PRED); 4273 case ISD::FMUL: 4274 return LowerToPredicatedOp(Op, DAG, AArch64ISD::FMUL_PRED); 4275 case ISD::FMA: 4276 return LowerToPredicatedOp(Op, DAG, AArch64ISD::FMA_PRED); 4277 case ISD::FDIV: 4278 return LowerToPredicatedOp(Op, DAG, AArch64ISD::FDIV_PRED); 4279 case ISD::FNEG: 4280 return LowerToPredicatedOp(Op, DAG, AArch64ISD::FNEG_MERGE_PASSTHRU); 4281 case ISD::FCEIL: 4282 return LowerToPredicatedOp(Op, DAG, AArch64ISD::FCEIL_MERGE_PASSTHRU); 4283 case ISD::FFLOOR: 4284 return LowerToPredicatedOp(Op, DAG, AArch64ISD::FFLOOR_MERGE_PASSTHRU); 4285 case ISD::FNEARBYINT: 4286 return LowerToPredicatedOp(Op, DAG, AArch64ISD::FNEARBYINT_MERGE_PASSTHRU); 4287 case ISD::FRINT: 4288 return LowerToPredicatedOp(Op, DAG, AArch64ISD::FRINT_MERGE_PASSTHRU); 4289 case ISD::FROUND: 4290 return LowerToPredicatedOp(Op, DAG, AArch64ISD::FROUND_MERGE_PASSTHRU); 4291 case ISD::FROUNDEVEN: 4292 return LowerToPredicatedOp(Op, DAG, AArch64ISD::FROUNDEVEN_MERGE_PASSTHRU); 4293 case ISD::FTRUNC: 4294 return LowerToPredicatedOp(Op, DAG, AArch64ISD::FTRUNC_MERGE_PASSTHRU); 4295 case ISD::FSQRT: 4296 return LowerToPredicatedOp(Op, DAG, AArch64ISD::FSQRT_MERGE_PASSTHRU); 4297 case ISD::FABS: 4298 return LowerToPredicatedOp(Op, DAG, AArch64ISD::FABS_MERGE_PASSTHRU); 4299 case ISD::FP_ROUND: 4300 case ISD::STRICT_FP_ROUND: 4301 return LowerFP_ROUND(Op, DAG); 4302 case ISD::FP_EXTEND: 4303 return LowerFP_EXTEND(Op, DAG); 4304 case ISD::FRAMEADDR: 4305 return LowerFRAMEADDR(Op, DAG); 4306 case ISD::SPONENTRY: 4307 return LowerSPONENTRY(Op, DAG); 4308 case ISD::RETURNADDR: 4309 return LowerRETURNADDR(Op, DAG); 4310 case ISD::ADDROFRETURNADDR: 4311 return LowerADDROFRETURNADDR(Op, DAG); 4312 case ISD::CONCAT_VECTORS: 4313 return LowerCONCAT_VECTORS(Op, DAG); 4314 case ISD::INSERT_VECTOR_ELT: 4315 return LowerINSERT_VECTOR_ELT(Op, DAG); 4316 case ISD::EXTRACT_VECTOR_ELT: 4317 return LowerEXTRACT_VECTOR_ELT(Op, DAG); 4318 case ISD::BUILD_VECTOR: 4319 return LowerBUILD_VECTOR(Op, DAG); 4320 case ISD::VECTOR_SHUFFLE: 4321 return LowerVECTOR_SHUFFLE(Op, DAG); 4322 case ISD::SPLAT_VECTOR: 4323 return LowerSPLAT_VECTOR(Op, DAG); 4324 case ISD::EXTRACT_SUBVECTOR: 4325 return LowerEXTRACT_SUBVECTOR(Op, DAG); 4326 case ISD::INSERT_SUBVECTOR: 4327 return LowerINSERT_SUBVECTOR(Op, DAG); 4328 case ISD::SDIV: 4329 case ISD::UDIV: 4330 return LowerDIV(Op, DAG); 4331 case ISD::SMIN: 4332 return LowerToPredicatedOp(Op, DAG, AArch64ISD::SMIN_PRED, 4333 /*OverrideNEON=*/true); 4334 case ISD::UMIN: 4335 return LowerToPredicatedOp(Op, DAG, AArch64ISD::UMIN_PRED, 4336 /*OverrideNEON=*/true); 4337 case ISD::SMAX: 4338 return LowerToPredicatedOp(Op, DAG, AArch64ISD::SMAX_PRED, 4339 /*OverrideNEON=*/true); 4340 case ISD::UMAX: 4341 return LowerToPredicatedOp(Op, DAG, AArch64ISD::UMAX_PRED, 4342 /*OverrideNEON=*/true); 4343 case ISD::SRA: 4344 case ISD::SRL: 4345 case ISD::SHL: 4346 return LowerVectorSRA_SRL_SHL(Op, DAG); 4347 case ISD::SHL_PARTS: 4348 return LowerShiftLeftParts(Op, DAG); 4349 case ISD::SRL_PARTS: 4350 case ISD::SRA_PARTS: 4351 return LowerShiftRightParts(Op, DAG); 4352 case ISD::CTPOP: 4353 return LowerCTPOP(Op, DAG); 4354 case ISD::FCOPYSIGN: 4355 return LowerFCOPYSIGN(Op, DAG); 4356 case ISD::OR: 4357 return LowerVectorOR(Op, DAG); 4358 case ISD::XOR: 4359 return LowerXOR(Op, DAG); 4360 case ISD::PREFETCH: 4361 return LowerPREFETCH(Op, DAG); 4362 case ISD::SINT_TO_FP: 4363 case ISD::UINT_TO_FP: 4364 case ISD::STRICT_SINT_TO_FP: 4365 case ISD::STRICT_UINT_TO_FP: 4366 return LowerINT_TO_FP(Op, DAG); 4367 case ISD::FP_TO_SINT: 4368 case ISD::FP_TO_UINT: 4369 case ISD::STRICT_FP_TO_SINT: 4370 case ISD::STRICT_FP_TO_UINT: 4371 return LowerFP_TO_INT(Op, DAG); 4372 case ISD::FSINCOS: 4373 return LowerFSINCOS(Op, DAG); 4374 case ISD::FLT_ROUNDS_: 4375 return LowerFLT_ROUNDS_(Op, DAG); 4376 case ISD::MUL: 4377 return LowerMUL(Op, DAG); 4378 case ISD::INTRINSIC_WO_CHAIN: 4379 return LowerINTRINSIC_WO_CHAIN(Op, DAG); 4380 case ISD::STORE: 4381 return LowerSTORE(Op, DAG); 4382 case ISD::MGATHER: 4383 return LowerMGATHER(Op, DAG); 4384 case ISD::MSCATTER: 4385 return LowerMSCATTER(Op, DAG); 4386 case ISD::VECREDUCE_SEQ_FADD: 4387 return LowerVECREDUCE_SEQ_FADD(Op, DAG); 4388 case ISD::VECREDUCE_ADD: 4389 case ISD::VECREDUCE_AND: 4390 case ISD::VECREDUCE_OR: 4391 case ISD::VECREDUCE_XOR: 4392 case ISD::VECREDUCE_SMAX: 4393 case ISD::VECREDUCE_SMIN: 4394 case ISD::VECREDUCE_UMAX: 4395 case ISD::VECREDUCE_UMIN: 4396 case ISD::VECREDUCE_FADD: 4397 case ISD::VECREDUCE_FMAX: 4398 case ISD::VECREDUCE_FMIN: 4399 return LowerVECREDUCE(Op, DAG); 4400 case ISD::ATOMIC_LOAD_SUB: 4401 return LowerATOMIC_LOAD_SUB(Op, DAG); 4402 case ISD::ATOMIC_LOAD_AND: 4403 return LowerATOMIC_LOAD_AND(Op, DAG); 4404 case ISD::DYNAMIC_STACKALLOC: 4405 return LowerDYNAMIC_STACKALLOC(Op, DAG); 4406 case ISD::VSCALE: 4407 return LowerVSCALE(Op, DAG); 4408 case ISD::ANY_EXTEND: 4409 case ISD::SIGN_EXTEND: 4410 case ISD::ZERO_EXTEND: 4411 return LowerFixedLengthVectorIntExtendToSVE(Op, DAG); 4412 case ISD::SIGN_EXTEND_INREG: { 4413 // Only custom lower when ExtraVT has a legal byte based element type. 4414 EVT ExtraVT = cast<VTSDNode>(Op.getOperand(1))->getVT(); 4415 EVT ExtraEltVT = ExtraVT.getVectorElementType(); 4416 if ((ExtraEltVT != MVT::i8) && (ExtraEltVT != MVT::i16) && 4417 (ExtraEltVT != MVT::i32) && (ExtraEltVT != MVT::i64)) 4418 return SDValue(); 4419 4420 return LowerToPredicatedOp(Op, DAG, 4421 AArch64ISD::SIGN_EXTEND_INREG_MERGE_PASSTHRU); 4422 } 4423 case ISD::TRUNCATE: 4424 return LowerTRUNCATE(Op, DAG); 4425 case ISD::LOAD: 4426 if (useSVEForFixedLengthVectorVT(Op.getValueType())) 4427 return LowerFixedLengthVectorLoadToSVE(Op, DAG); 4428 llvm_unreachable("Unexpected request to lower ISD::LOAD"); 4429 case ISD::ADD: 4430 return LowerToPredicatedOp(Op, DAG, AArch64ISD::ADD_PRED); 4431 case ISD::AND: 4432 return LowerToScalableOp(Op, DAG); 4433 case ISD::SUB: 4434 return LowerToPredicatedOp(Op, DAG, AArch64ISD::SUB_PRED); 4435 case ISD::FMAXNUM: 4436 return LowerToPredicatedOp(Op, DAG, AArch64ISD::FMAXNM_PRED); 4437 case ISD::FMINNUM: 4438 return LowerToPredicatedOp(Op, DAG, AArch64ISD::FMINNM_PRED); 4439 case ISD::VSELECT: 4440 return LowerFixedLengthVectorSelectToSVE(Op, DAG); 4441 case ISD::ABS: 4442 return LowerABS(Op, DAG); 4443 case ISD::BITREVERSE: 4444 return LowerToPredicatedOp(Op, DAG, AArch64ISD::BITREVERSE_MERGE_PASSTHRU, 4445 /*OverrideNEON=*/true); 4446 case ISD::BSWAP: 4447 return LowerToPredicatedOp(Op, DAG, AArch64ISD::BSWAP_MERGE_PASSTHRU); 4448 case ISD::CTLZ: 4449 return LowerToPredicatedOp(Op, DAG, AArch64ISD::CTLZ_MERGE_PASSTHRU, 4450 /*OverrideNEON=*/true); 4451 case ISD::CTTZ: 4452 return LowerCTTZ(Op, DAG); 4453 } 4454 } 4455 4456 bool AArch64TargetLowering::mergeStoresAfterLegalization(EVT VT) const { 4457 return !Subtarget->useSVEForFixedLengthVectors(); 4458 } 4459 4460 bool AArch64TargetLowering::useSVEForFixedLengthVectorVT( 4461 EVT VT, bool OverrideNEON) const { 4462 if (!Subtarget->useSVEForFixedLengthVectors()) 4463 return false; 4464 4465 if (!VT.isFixedLengthVector()) 4466 return false; 4467 4468 // Don't use SVE for vectors we cannot scalarize if required. 4469 switch (VT.getVectorElementType().getSimpleVT().SimpleTy) { 4470 // Fixed length predicates should be promoted to i8. 4471 // NOTE: This is consistent with how NEON (and thus 64/128bit vectors) work. 4472 case MVT::i1: 4473 default: 4474 return false; 4475 case MVT::i8: 4476 case MVT::i16: 4477 case MVT::i32: 4478 case MVT::i64: 4479 case MVT::f16: 4480 case MVT::f32: 4481 case MVT::f64: 4482 break; 4483 } 4484 4485 // All SVE implementations support NEON sized vectors. 4486 if (OverrideNEON && (VT.is128BitVector() || VT.is64BitVector())) 4487 return true; 4488 4489 // Ensure NEON MVTs only belong to a single register class. 4490 if (VT.getFixedSizeInBits() <= 128) 4491 return false; 4492 4493 // Don't use SVE for types that don't fit. 4494 if (VT.getFixedSizeInBits() > Subtarget->getMinSVEVectorSizeInBits()) 4495 return false; 4496 4497 // TODO: Perhaps an artificial restriction, but worth having whilst getting 4498 // the base fixed length SVE support in place. 4499 if (!VT.isPow2VectorType()) 4500 return false; 4501 4502 return true; 4503 } 4504 4505 //===----------------------------------------------------------------------===// 4506 // Calling Convention Implementation 4507 //===----------------------------------------------------------------------===// 4508 4509 /// Selects the correct CCAssignFn for a given CallingConvention value. 4510 CCAssignFn *AArch64TargetLowering::CCAssignFnForCall(CallingConv::ID CC, 4511 bool IsVarArg) const { 4512 switch (CC) { 4513 default: 4514 report_fatal_error("Unsupported calling convention."); 4515 case CallingConv::WebKit_JS: 4516 return CC_AArch64_WebKit_JS; 4517 case CallingConv::GHC: 4518 return CC_AArch64_GHC; 4519 case CallingConv::C: 4520 case CallingConv::Fast: 4521 case CallingConv::PreserveMost: 4522 case CallingConv::CXX_FAST_TLS: 4523 case CallingConv::Swift: 4524 if (Subtarget->isTargetWindows() && IsVarArg) 4525 return CC_AArch64_Win64_VarArg; 4526 if (!Subtarget->isTargetDarwin()) 4527 return CC_AArch64_AAPCS; 4528 if (!IsVarArg) 4529 return CC_AArch64_DarwinPCS; 4530 return Subtarget->isTargetILP32() ? CC_AArch64_DarwinPCS_ILP32_VarArg 4531 : CC_AArch64_DarwinPCS_VarArg; 4532 case CallingConv::Win64: 4533 return IsVarArg ? CC_AArch64_Win64_VarArg : CC_AArch64_AAPCS; 4534 case CallingConv::CFGuard_Check: 4535 return CC_AArch64_Win64_CFGuard_Check; 4536 case CallingConv::AArch64_VectorCall: 4537 case CallingConv::AArch64_SVE_VectorCall: 4538 return CC_AArch64_AAPCS; 4539 } 4540 } 4541 4542 CCAssignFn * 4543 AArch64TargetLowering::CCAssignFnForReturn(CallingConv::ID CC) const { 4544 return CC == CallingConv::WebKit_JS ? RetCC_AArch64_WebKit_JS 4545 : RetCC_AArch64_AAPCS; 4546 } 4547 4548 SDValue AArch64TargetLowering::LowerFormalArguments( 4549 SDValue Chain, CallingConv::ID CallConv, bool isVarArg, 4550 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &DL, 4551 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const { 4552 MachineFunction &MF = DAG.getMachineFunction(); 4553 MachineFrameInfo &MFI = MF.getFrameInfo(); 4554 bool IsWin64 = Subtarget->isCallingConvWin64(MF.getFunction().getCallingConv()); 4555 4556 // Assign locations to all of the incoming arguments. 4557 SmallVector<CCValAssign, 16> ArgLocs; 4558 DenseMap<unsigned, SDValue> CopiedRegs; 4559 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), ArgLocs, 4560 *DAG.getContext()); 4561 4562 // At this point, Ins[].VT may already be promoted to i32. To correctly 4563 // handle passing i8 as i8 instead of i32 on stack, we pass in both i32 and 4564 // i8 to CC_AArch64_AAPCS with i32 being ValVT and i8 being LocVT. 4565 // Since AnalyzeFormalArguments uses Ins[].VT for both ValVT and LocVT, here 4566 // we use a special version of AnalyzeFormalArguments to pass in ValVT and 4567 // LocVT. 4568 unsigned NumArgs = Ins.size(); 4569 Function::const_arg_iterator CurOrigArg = MF.getFunction().arg_begin(); 4570 unsigned CurArgIdx = 0; 4571 for (unsigned i = 0; i != NumArgs; ++i) { 4572 MVT ValVT = Ins[i].VT; 4573 if (Ins[i].isOrigArg()) { 4574 std::advance(CurOrigArg, Ins[i].getOrigArgIndex() - CurArgIdx); 4575 CurArgIdx = Ins[i].getOrigArgIndex(); 4576 4577 // Get type of the original argument. 4578 EVT ActualVT = getValueType(DAG.getDataLayout(), CurOrigArg->getType(), 4579 /*AllowUnknown*/ true); 4580 MVT ActualMVT = ActualVT.isSimple() ? ActualVT.getSimpleVT() : MVT::Other; 4581 // If ActualMVT is i1/i8/i16, we should set LocVT to i8/i8/i16. 4582 if (ActualMVT == MVT::i1 || ActualMVT == MVT::i8) 4583 ValVT = MVT::i8; 4584 else if (ActualMVT == MVT::i16) 4585 ValVT = MVT::i16; 4586 } 4587 CCAssignFn *AssignFn = CCAssignFnForCall(CallConv, /*IsVarArg=*/false); 4588 bool Res = 4589 AssignFn(i, ValVT, ValVT, CCValAssign::Full, Ins[i].Flags, CCInfo); 4590 assert(!Res && "Call operand has unhandled type"); 4591 (void)Res; 4592 } 4593 SmallVector<SDValue, 16> ArgValues; 4594 unsigned ExtraArgLocs = 0; 4595 for (unsigned i = 0, e = Ins.size(); i != e; ++i) { 4596 CCValAssign &VA = ArgLocs[i - ExtraArgLocs]; 4597 4598 if (Ins[i].Flags.isByVal()) { 4599 // Byval is used for HFAs in the PCS, but the system should work in a 4600 // non-compliant manner for larger structs. 4601 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 4602 int Size = Ins[i].Flags.getByValSize(); 4603 unsigned NumRegs = (Size + 7) / 8; 4604 4605 // FIXME: This works on big-endian for composite byvals, which are the common 4606 // case. It should also work for fundamental types too. 4607 unsigned FrameIdx = 4608 MFI.CreateFixedObject(8 * NumRegs, VA.getLocMemOffset(), false); 4609 SDValue FrameIdxN = DAG.getFrameIndex(FrameIdx, PtrVT); 4610 InVals.push_back(FrameIdxN); 4611 4612 continue; 4613 } 4614 4615 SDValue ArgValue; 4616 if (VA.isRegLoc()) { 4617 // Arguments stored in registers. 4618 EVT RegVT = VA.getLocVT(); 4619 const TargetRegisterClass *RC; 4620 4621 if (RegVT == MVT::i32) 4622 RC = &AArch64::GPR32RegClass; 4623 else if (RegVT == MVT::i64) 4624 RC = &AArch64::GPR64RegClass; 4625 else if (RegVT == MVT::f16 || RegVT == MVT::bf16) 4626 RC = &AArch64::FPR16RegClass; 4627 else if (RegVT == MVT::f32) 4628 RC = &AArch64::FPR32RegClass; 4629 else if (RegVT == MVT::f64 || RegVT.is64BitVector()) 4630 RC = &AArch64::FPR64RegClass; 4631 else if (RegVT == MVT::f128 || RegVT.is128BitVector()) 4632 RC = &AArch64::FPR128RegClass; 4633 else if (RegVT.isScalableVector() && 4634 RegVT.getVectorElementType() == MVT::i1) 4635 RC = &AArch64::PPRRegClass; 4636 else if (RegVT.isScalableVector()) 4637 RC = &AArch64::ZPRRegClass; 4638 else 4639 llvm_unreachable("RegVT not supported by FORMAL_ARGUMENTS Lowering"); 4640 4641 // Transform the arguments in physical registers into virtual ones. 4642 unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC); 4643 ArgValue = DAG.getCopyFromReg(Chain, DL, Reg, RegVT); 4644 4645 // If this is an 8, 16 or 32-bit value, it is really passed promoted 4646 // to 64 bits. Insert an assert[sz]ext to capture this, then 4647 // truncate to the right size. 4648 switch (VA.getLocInfo()) { 4649 default: 4650 llvm_unreachable("Unknown loc info!"); 4651 case CCValAssign::Full: 4652 break; 4653 case CCValAssign::Indirect: 4654 assert(VA.getValVT().isScalableVector() && 4655 "Only scalable vectors can be passed indirectly"); 4656 break; 4657 case CCValAssign::BCvt: 4658 ArgValue = DAG.getNode(ISD::BITCAST, DL, VA.getValVT(), ArgValue); 4659 break; 4660 case CCValAssign::AExt: 4661 case CCValAssign::SExt: 4662 case CCValAssign::ZExt: 4663 break; 4664 case CCValAssign::AExtUpper: 4665 ArgValue = DAG.getNode(ISD::SRL, DL, RegVT, ArgValue, 4666 DAG.getConstant(32, DL, RegVT)); 4667 ArgValue = DAG.getZExtOrTrunc(ArgValue, DL, VA.getValVT()); 4668 break; 4669 } 4670 } else { // VA.isRegLoc() 4671 assert(VA.isMemLoc() && "CCValAssign is neither reg nor mem"); 4672 unsigned ArgOffset = VA.getLocMemOffset(); 4673 unsigned ArgSize = (VA.getLocInfo() == CCValAssign::Indirect 4674 ? VA.getLocVT().getSizeInBits() 4675 : VA.getValVT().getSizeInBits()) / 8; 4676 4677 uint32_t BEAlign = 0; 4678 if (!Subtarget->isLittleEndian() && ArgSize < 8 && 4679 !Ins[i].Flags.isInConsecutiveRegs()) 4680 BEAlign = 8 - ArgSize; 4681 4682 int FI = MFI.CreateFixedObject(ArgSize, ArgOffset + BEAlign, true); 4683 4684 // Create load nodes to retrieve arguments from the stack. 4685 SDValue FIN = DAG.getFrameIndex(FI, getPointerTy(DAG.getDataLayout())); 4686 4687 // For NON_EXTLOAD, generic code in getLoad assert(ValVT == MemVT) 4688 ISD::LoadExtType ExtType = ISD::NON_EXTLOAD; 4689 MVT MemVT = VA.getValVT(); 4690 4691 switch (VA.getLocInfo()) { 4692 default: 4693 break; 4694 case CCValAssign::Trunc: 4695 case CCValAssign::BCvt: 4696 MemVT = VA.getLocVT(); 4697 break; 4698 case CCValAssign::Indirect: 4699 assert(VA.getValVT().isScalableVector() && 4700 "Only scalable vectors can be passed indirectly"); 4701 MemVT = VA.getLocVT(); 4702 break; 4703 case CCValAssign::SExt: 4704 ExtType = ISD::SEXTLOAD; 4705 break; 4706 case CCValAssign::ZExt: 4707 ExtType = ISD::ZEXTLOAD; 4708 break; 4709 case CCValAssign::AExt: 4710 ExtType = ISD::EXTLOAD; 4711 break; 4712 } 4713 4714 ArgValue = DAG.getExtLoad( 4715 ExtType, DL, VA.getLocVT(), Chain, FIN, 4716 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI), 4717 MemVT); 4718 4719 } 4720 4721 if (VA.getLocInfo() == CCValAssign::Indirect) { 4722 assert(VA.getValVT().isScalableVector() && 4723 "Only scalable vectors can be passed indirectly"); 4724 4725 uint64_t PartSize = VA.getValVT().getStoreSize().getKnownMinSize(); 4726 unsigned NumParts = 1; 4727 if (Ins[i].Flags.isInConsecutiveRegs()) { 4728 assert(!Ins[i].Flags.isInConsecutiveRegsLast()); 4729 while (!Ins[i + NumParts - 1].Flags.isInConsecutiveRegsLast()) 4730 ++NumParts; 4731 } 4732 4733 MVT PartLoad = VA.getValVT(); 4734 SDValue Ptr = ArgValue; 4735 4736 // Ensure we generate all loads for each tuple part, whilst updating the 4737 // pointer after each load correctly using vscale. 4738 while (NumParts > 0) { 4739 ArgValue = DAG.getLoad(PartLoad, DL, Chain, Ptr, MachinePointerInfo()); 4740 InVals.push_back(ArgValue); 4741 NumParts--; 4742 if (NumParts > 0) { 4743 SDValue BytesIncrement = DAG.getVScale( 4744 DL, Ptr.getValueType(), 4745 APInt(Ptr.getValueSizeInBits().getFixedSize(), PartSize)); 4746 SDNodeFlags Flags; 4747 Flags.setNoUnsignedWrap(true); 4748 Ptr = DAG.getNode(ISD::ADD, DL, Ptr.getValueType(), Ptr, 4749 BytesIncrement, Flags); 4750 ExtraArgLocs++; 4751 i++; 4752 } 4753 } 4754 } else { 4755 if (Subtarget->isTargetILP32() && Ins[i].Flags.isPointer()) 4756 ArgValue = DAG.getNode(ISD::AssertZext, DL, ArgValue.getValueType(), 4757 ArgValue, DAG.getValueType(MVT::i32)); 4758 InVals.push_back(ArgValue); 4759 } 4760 } 4761 assert((ArgLocs.size() + ExtraArgLocs) == Ins.size()); 4762 4763 // varargs 4764 AArch64FunctionInfo *FuncInfo = MF.getInfo<AArch64FunctionInfo>(); 4765 if (isVarArg) { 4766 if (!Subtarget->isTargetDarwin() || IsWin64) { 4767 // The AAPCS variadic function ABI is identical to the non-variadic 4768 // one. As a result there may be more arguments in registers and we should 4769 // save them for future reference. 4770 // Win64 variadic functions also pass arguments in registers, but all float 4771 // arguments are passed in integer registers. 4772 saveVarArgRegisters(CCInfo, DAG, DL, Chain); 4773 } 4774 4775 // This will point to the next argument passed via stack. 4776 unsigned StackOffset = CCInfo.getNextStackOffset(); 4777 // We currently pass all varargs at 8-byte alignment, or 4 for ILP32 4778 StackOffset = alignTo(StackOffset, Subtarget->isTargetILP32() ? 4 : 8); 4779 FuncInfo->setVarArgsStackIndex(MFI.CreateFixedObject(4, StackOffset, true)); 4780 4781 if (MFI.hasMustTailInVarArgFunc()) { 4782 SmallVector<MVT, 2> RegParmTypes; 4783 RegParmTypes.push_back(MVT::i64); 4784 RegParmTypes.push_back(MVT::f128); 4785 // Compute the set of forwarded registers. The rest are scratch. 4786 SmallVectorImpl<ForwardedRegister> &Forwards = 4787 FuncInfo->getForwardedMustTailRegParms(); 4788 CCInfo.analyzeMustTailForwardedRegisters(Forwards, RegParmTypes, 4789 CC_AArch64_AAPCS); 4790 4791 // Conservatively forward X8, since it might be used for aggregate return. 4792 if (!CCInfo.isAllocated(AArch64::X8)) { 4793 unsigned X8VReg = MF.addLiveIn(AArch64::X8, &AArch64::GPR64RegClass); 4794 Forwards.push_back(ForwardedRegister(X8VReg, AArch64::X8, MVT::i64)); 4795 } 4796 } 4797 } 4798 4799 // On Windows, InReg pointers must be returned, so record the pointer in a 4800 // virtual register at the start of the function so it can be returned in the 4801 // epilogue. 4802 if (IsWin64) { 4803 for (unsigned I = 0, E = Ins.size(); I != E; ++I) { 4804 if (Ins[I].Flags.isInReg()) { 4805 assert(!FuncInfo->getSRetReturnReg()); 4806 4807 MVT PtrTy = getPointerTy(DAG.getDataLayout()); 4808 Register Reg = 4809 MF.getRegInfo().createVirtualRegister(getRegClassFor(PtrTy)); 4810 FuncInfo->setSRetReturnReg(Reg); 4811 4812 SDValue Copy = DAG.getCopyToReg(DAG.getEntryNode(), DL, Reg, InVals[I]); 4813 Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Copy, Chain); 4814 break; 4815 } 4816 } 4817 } 4818 4819 unsigned StackArgSize = CCInfo.getNextStackOffset(); 4820 bool TailCallOpt = MF.getTarget().Options.GuaranteedTailCallOpt; 4821 if (DoesCalleeRestoreStack(CallConv, TailCallOpt)) { 4822 // This is a non-standard ABI so by fiat I say we're allowed to make full 4823 // use of the stack area to be popped, which must be aligned to 16 bytes in 4824 // any case: 4825 StackArgSize = alignTo(StackArgSize, 16); 4826 4827 // If we're expected to restore the stack (e.g. fastcc) then we'll be adding 4828 // a multiple of 16. 4829 FuncInfo->setArgumentStackToRestore(StackArgSize); 4830 4831 // This realignment carries over to the available bytes below. Our own 4832 // callers will guarantee the space is free by giving an aligned value to 4833 // CALLSEQ_START. 4834 } 4835 // Even if we're not expected to free up the space, it's useful to know how 4836 // much is there while considering tail calls (because we can reuse it). 4837 FuncInfo->setBytesInStackArgArea(StackArgSize); 4838 4839 if (Subtarget->hasCustomCallingConv()) 4840 Subtarget->getRegisterInfo()->UpdateCustomCalleeSavedRegs(MF); 4841 4842 return Chain; 4843 } 4844 4845 void AArch64TargetLowering::saveVarArgRegisters(CCState &CCInfo, 4846 SelectionDAG &DAG, 4847 const SDLoc &DL, 4848 SDValue &Chain) const { 4849 MachineFunction &MF = DAG.getMachineFunction(); 4850 MachineFrameInfo &MFI = MF.getFrameInfo(); 4851 AArch64FunctionInfo *FuncInfo = MF.getInfo<AArch64FunctionInfo>(); 4852 auto PtrVT = getPointerTy(DAG.getDataLayout()); 4853 bool IsWin64 = Subtarget->isCallingConvWin64(MF.getFunction().getCallingConv()); 4854 4855 SmallVector<SDValue, 8> MemOps; 4856 4857 static const MCPhysReg GPRArgRegs[] = { AArch64::X0, AArch64::X1, AArch64::X2, 4858 AArch64::X3, AArch64::X4, AArch64::X5, 4859 AArch64::X6, AArch64::X7 }; 4860 static const unsigned NumGPRArgRegs = array_lengthof(GPRArgRegs); 4861 unsigned FirstVariadicGPR = CCInfo.getFirstUnallocated(GPRArgRegs); 4862 4863 unsigned GPRSaveSize = 8 * (NumGPRArgRegs - FirstVariadicGPR); 4864 int GPRIdx = 0; 4865 if (GPRSaveSize != 0) { 4866 if (IsWin64) { 4867 GPRIdx = MFI.CreateFixedObject(GPRSaveSize, -(int)GPRSaveSize, false); 4868 if (GPRSaveSize & 15) 4869 // The extra size here, if triggered, will always be 8. 4870 MFI.CreateFixedObject(16 - (GPRSaveSize & 15), -(int)alignTo(GPRSaveSize, 16), false); 4871 } else 4872 GPRIdx = MFI.CreateStackObject(GPRSaveSize, Align(8), false); 4873 4874 SDValue FIN = DAG.getFrameIndex(GPRIdx, PtrVT); 4875 4876 for (unsigned i = FirstVariadicGPR; i < NumGPRArgRegs; ++i) { 4877 unsigned VReg = MF.addLiveIn(GPRArgRegs[i], &AArch64::GPR64RegClass); 4878 SDValue Val = DAG.getCopyFromReg(Chain, DL, VReg, MVT::i64); 4879 SDValue Store = DAG.getStore( 4880 Val.getValue(1), DL, Val, FIN, 4881 IsWin64 4882 ? MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), 4883 GPRIdx, 4884 (i - FirstVariadicGPR) * 8) 4885 : MachinePointerInfo::getStack(DAG.getMachineFunction(), i * 8)); 4886 MemOps.push_back(Store); 4887 FIN = 4888 DAG.getNode(ISD::ADD, DL, PtrVT, FIN, DAG.getConstant(8, DL, PtrVT)); 4889 } 4890 } 4891 FuncInfo->setVarArgsGPRIndex(GPRIdx); 4892 FuncInfo->setVarArgsGPRSize(GPRSaveSize); 4893 4894 if (Subtarget->hasFPARMv8() && !IsWin64) { 4895 static const MCPhysReg FPRArgRegs[] = { 4896 AArch64::Q0, AArch64::Q1, AArch64::Q2, AArch64::Q3, 4897 AArch64::Q4, AArch64::Q5, AArch64::Q6, AArch64::Q7}; 4898 static const unsigned NumFPRArgRegs = array_lengthof(FPRArgRegs); 4899 unsigned FirstVariadicFPR = CCInfo.getFirstUnallocated(FPRArgRegs); 4900 4901 unsigned FPRSaveSize = 16 * (NumFPRArgRegs - FirstVariadicFPR); 4902 int FPRIdx = 0; 4903 if (FPRSaveSize != 0) { 4904 FPRIdx = MFI.CreateStackObject(FPRSaveSize, Align(16), false); 4905 4906 SDValue FIN = DAG.getFrameIndex(FPRIdx, PtrVT); 4907 4908 for (unsigned i = FirstVariadicFPR; i < NumFPRArgRegs; ++i) { 4909 unsigned VReg = MF.addLiveIn(FPRArgRegs[i], &AArch64::FPR128RegClass); 4910 SDValue Val = DAG.getCopyFromReg(Chain, DL, VReg, MVT::f128); 4911 4912 SDValue Store = DAG.getStore( 4913 Val.getValue(1), DL, Val, FIN, 4914 MachinePointerInfo::getStack(DAG.getMachineFunction(), i * 16)); 4915 MemOps.push_back(Store); 4916 FIN = DAG.getNode(ISD::ADD, DL, PtrVT, FIN, 4917 DAG.getConstant(16, DL, PtrVT)); 4918 } 4919 } 4920 FuncInfo->setVarArgsFPRIndex(FPRIdx); 4921 FuncInfo->setVarArgsFPRSize(FPRSaveSize); 4922 } 4923 4924 if (!MemOps.empty()) { 4925 Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, MemOps); 4926 } 4927 } 4928 4929 /// LowerCallResult - Lower the result values of a call into the 4930 /// appropriate copies out of appropriate physical registers. 4931 SDValue AArch64TargetLowering::LowerCallResult( 4932 SDValue Chain, SDValue InFlag, CallingConv::ID CallConv, bool isVarArg, 4933 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &DL, 4934 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals, bool isThisReturn, 4935 SDValue ThisVal) const { 4936 CCAssignFn *RetCC = CCAssignFnForReturn(CallConv); 4937 // Assign locations to each value returned by this call. 4938 SmallVector<CCValAssign, 16> RVLocs; 4939 DenseMap<unsigned, SDValue> CopiedRegs; 4940 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs, 4941 *DAG.getContext()); 4942 CCInfo.AnalyzeCallResult(Ins, RetCC); 4943 4944 // Copy all of the result registers out of their specified physreg. 4945 for (unsigned i = 0; i != RVLocs.size(); ++i) { 4946 CCValAssign VA = RVLocs[i]; 4947 4948 // Pass 'this' value directly from the argument to return value, to avoid 4949 // reg unit interference 4950 if (i == 0 && isThisReturn) { 4951 assert(!VA.needsCustom() && VA.getLocVT() == MVT::i64 && 4952 "unexpected return calling convention register assignment"); 4953 InVals.push_back(ThisVal); 4954 continue; 4955 } 4956 4957 // Avoid copying a physreg twice since RegAllocFast is incompetent and only 4958 // allows one use of a physreg per block. 4959 SDValue Val = CopiedRegs.lookup(VA.getLocReg()); 4960 if (!Val) { 4961 Val = 4962 DAG.getCopyFromReg(Chain, DL, VA.getLocReg(), VA.getLocVT(), InFlag); 4963 Chain = Val.getValue(1); 4964 InFlag = Val.getValue(2); 4965 CopiedRegs[VA.getLocReg()] = Val; 4966 } 4967 4968 switch (VA.getLocInfo()) { 4969 default: 4970 llvm_unreachable("Unknown loc info!"); 4971 case CCValAssign::Full: 4972 break; 4973 case CCValAssign::BCvt: 4974 Val = DAG.getNode(ISD::BITCAST, DL, VA.getValVT(), Val); 4975 break; 4976 case CCValAssign::AExtUpper: 4977 Val = DAG.getNode(ISD::SRL, DL, VA.getLocVT(), Val, 4978 DAG.getConstant(32, DL, VA.getLocVT())); 4979 LLVM_FALLTHROUGH; 4980 case CCValAssign::AExt: 4981 LLVM_FALLTHROUGH; 4982 case CCValAssign::ZExt: 4983 Val = DAG.getZExtOrTrunc(Val, DL, VA.getValVT()); 4984 break; 4985 } 4986 4987 InVals.push_back(Val); 4988 } 4989 4990 return Chain; 4991 } 4992 4993 /// Return true if the calling convention is one that we can guarantee TCO for. 4994 static bool canGuaranteeTCO(CallingConv::ID CC) { 4995 return CC == CallingConv::Fast; 4996 } 4997 4998 /// Return true if we might ever do TCO for calls with this calling convention. 4999 static bool mayTailCallThisCC(CallingConv::ID CC) { 5000 switch (CC) { 5001 case CallingConv::C: 5002 case CallingConv::AArch64_SVE_VectorCall: 5003 case CallingConv::PreserveMost: 5004 case CallingConv::Swift: 5005 return true; 5006 default: 5007 return canGuaranteeTCO(CC); 5008 } 5009 } 5010 5011 bool AArch64TargetLowering::isEligibleForTailCallOptimization( 5012 SDValue Callee, CallingConv::ID CalleeCC, bool isVarArg, 5013 const SmallVectorImpl<ISD::OutputArg> &Outs, 5014 const SmallVectorImpl<SDValue> &OutVals, 5015 const SmallVectorImpl<ISD::InputArg> &Ins, SelectionDAG &DAG) const { 5016 if (!mayTailCallThisCC(CalleeCC)) 5017 return false; 5018 5019 MachineFunction &MF = DAG.getMachineFunction(); 5020 const Function &CallerF = MF.getFunction(); 5021 CallingConv::ID CallerCC = CallerF.getCallingConv(); 5022 5023 // If this function uses the C calling convention but has an SVE signature, 5024 // then it preserves more registers and should assume the SVE_VectorCall CC. 5025 // The check for matching callee-saved regs will determine whether it is 5026 // eligible for TCO. 5027 if (CallerCC == CallingConv::C && 5028 AArch64RegisterInfo::hasSVEArgsOrReturn(&MF)) 5029 CallerCC = CallingConv::AArch64_SVE_VectorCall; 5030 5031 bool CCMatch = CallerCC == CalleeCC; 5032 5033 // When using the Windows calling convention on a non-windows OS, we want 5034 // to back up and restore X18 in such functions; we can't do a tail call 5035 // from those functions. 5036 if (CallerCC == CallingConv::Win64 && !Subtarget->isTargetWindows() && 5037 CalleeCC != CallingConv::Win64) 5038 return false; 5039 5040 // Byval parameters hand the function a pointer directly into the stack area 5041 // we want to reuse during a tail call. Working around this *is* possible (see 5042 // X86) but less efficient and uglier in LowerCall. 5043 for (Function::const_arg_iterator i = CallerF.arg_begin(), 5044 e = CallerF.arg_end(); 5045 i != e; ++i) { 5046 if (i->hasByValAttr()) 5047 return false; 5048 5049 // On Windows, "inreg" attributes signify non-aggregate indirect returns. 5050 // In this case, it is necessary to save/restore X0 in the callee. Tail 5051 // call opt interferes with this. So we disable tail call opt when the 5052 // caller has an argument with "inreg" attribute. 5053 5054 // FIXME: Check whether the callee also has an "inreg" argument. 5055 if (i->hasInRegAttr()) 5056 return false; 5057 } 5058 5059 if (getTargetMachine().Options.GuaranteedTailCallOpt) 5060 return canGuaranteeTCO(CalleeCC) && CCMatch; 5061 5062 // Externally-defined functions with weak linkage should not be 5063 // tail-called on AArch64 when the OS does not support dynamic 5064 // pre-emption of symbols, as the AAELF spec requires normal calls 5065 // to undefined weak functions to be replaced with a NOP or jump to the 5066 // next instruction. The behaviour of branch instructions in this 5067 // situation (as used for tail calls) is implementation-defined, so we 5068 // cannot rely on the linker replacing the tail call with a return. 5069 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) { 5070 const GlobalValue *GV = G->getGlobal(); 5071 const Triple &TT = getTargetMachine().getTargetTriple(); 5072 if (GV->hasExternalWeakLinkage() && 5073 (!TT.isOSWindows() || TT.isOSBinFormatELF() || TT.isOSBinFormatMachO())) 5074 return false; 5075 } 5076 5077 // Now we search for cases where we can use a tail call without changing the 5078 // ABI. Sibcall is used in some places (particularly gcc) to refer to this 5079 // concept. 5080 5081 // I want anyone implementing a new calling convention to think long and hard 5082 // about this assert. 5083 assert((!isVarArg || CalleeCC == CallingConv::C) && 5084 "Unexpected variadic calling convention"); 5085 5086 LLVMContext &C = *DAG.getContext(); 5087 if (isVarArg && !Outs.empty()) { 5088 // At least two cases here: if caller is fastcc then we can't have any 5089 // memory arguments (we'd be expected to clean up the stack afterwards). If 5090 // caller is C then we could potentially use its argument area. 5091 5092 // FIXME: for now we take the most conservative of these in both cases: 5093 // disallow all variadic memory operands. 5094 SmallVector<CCValAssign, 16> ArgLocs; 5095 CCState CCInfo(CalleeCC, isVarArg, MF, ArgLocs, C); 5096 5097 CCInfo.AnalyzeCallOperands(Outs, CCAssignFnForCall(CalleeCC, true)); 5098 for (const CCValAssign &ArgLoc : ArgLocs) 5099 if (!ArgLoc.isRegLoc()) 5100 return false; 5101 } 5102 5103 // Check that the call results are passed in the same way. 5104 if (!CCState::resultsCompatible(CalleeCC, CallerCC, MF, C, Ins, 5105 CCAssignFnForCall(CalleeCC, isVarArg), 5106 CCAssignFnForCall(CallerCC, isVarArg))) 5107 return false; 5108 // The callee has to preserve all registers the caller needs to preserve. 5109 const AArch64RegisterInfo *TRI = Subtarget->getRegisterInfo(); 5110 const uint32_t *CallerPreserved = TRI->getCallPreservedMask(MF, CallerCC); 5111 if (!CCMatch) { 5112 const uint32_t *CalleePreserved = TRI->getCallPreservedMask(MF, CalleeCC); 5113 if (Subtarget->hasCustomCallingConv()) { 5114 TRI->UpdateCustomCallPreservedMask(MF, &CallerPreserved); 5115 TRI->UpdateCustomCallPreservedMask(MF, &CalleePreserved); 5116 } 5117 if (!TRI->regmaskSubsetEqual(CallerPreserved, CalleePreserved)) 5118 return false; 5119 } 5120 5121 // Nothing more to check if the callee is taking no arguments 5122 if (Outs.empty()) 5123 return true; 5124 5125 SmallVector<CCValAssign, 16> ArgLocs; 5126 CCState CCInfo(CalleeCC, isVarArg, MF, ArgLocs, C); 5127 5128 CCInfo.AnalyzeCallOperands(Outs, CCAssignFnForCall(CalleeCC, isVarArg)); 5129 5130 const AArch64FunctionInfo *FuncInfo = MF.getInfo<AArch64FunctionInfo>(); 5131 5132 // If any of the arguments is passed indirectly, it must be SVE, so the 5133 // 'getBytesInStackArgArea' is not sufficient to determine whether we need to 5134 // allocate space on the stack. That is why we determine this explicitly here 5135 // the call cannot be a tailcall. 5136 if (llvm::any_of(ArgLocs, [](CCValAssign &A) { 5137 assert((A.getLocInfo() != CCValAssign::Indirect || 5138 A.getValVT().isScalableVector()) && 5139 "Expected value to be scalable"); 5140 return A.getLocInfo() == CCValAssign::Indirect; 5141 })) 5142 return false; 5143 5144 // If the stack arguments for this call do not fit into our own save area then 5145 // the call cannot be made tail. 5146 if (CCInfo.getNextStackOffset() > FuncInfo->getBytesInStackArgArea()) 5147 return false; 5148 5149 const MachineRegisterInfo &MRI = MF.getRegInfo(); 5150 if (!parametersInCSRMatch(MRI, CallerPreserved, ArgLocs, OutVals)) 5151 return false; 5152 5153 return true; 5154 } 5155 5156 SDValue AArch64TargetLowering::addTokenForArgument(SDValue Chain, 5157 SelectionDAG &DAG, 5158 MachineFrameInfo &MFI, 5159 int ClobberedFI) const { 5160 SmallVector<SDValue, 8> ArgChains; 5161 int64_t FirstByte = MFI.getObjectOffset(ClobberedFI); 5162 int64_t LastByte = FirstByte + MFI.getObjectSize(ClobberedFI) - 1; 5163 5164 // Include the original chain at the beginning of the list. When this is 5165 // used by target LowerCall hooks, this helps legalize find the 5166 // CALLSEQ_BEGIN node. 5167 ArgChains.push_back(Chain); 5168 5169 // Add a chain value for each stack argument corresponding 5170 for (SDNode::use_iterator U = DAG.getEntryNode().getNode()->use_begin(), 5171 UE = DAG.getEntryNode().getNode()->use_end(); 5172 U != UE; ++U) 5173 if (LoadSDNode *L = dyn_cast<LoadSDNode>(*U)) 5174 if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(L->getBasePtr())) 5175 if (FI->getIndex() < 0) { 5176 int64_t InFirstByte = MFI.getObjectOffset(FI->getIndex()); 5177 int64_t InLastByte = InFirstByte; 5178 InLastByte += MFI.getObjectSize(FI->getIndex()) - 1; 5179 5180 if ((InFirstByte <= FirstByte && FirstByte <= InLastByte) || 5181 (FirstByte <= InFirstByte && InFirstByte <= LastByte)) 5182 ArgChains.push_back(SDValue(L, 1)); 5183 } 5184 5185 // Build a tokenfactor for all the chains. 5186 return DAG.getNode(ISD::TokenFactor, SDLoc(Chain), MVT::Other, ArgChains); 5187 } 5188 5189 bool AArch64TargetLowering::DoesCalleeRestoreStack(CallingConv::ID CallCC, 5190 bool TailCallOpt) const { 5191 return CallCC == CallingConv::Fast && TailCallOpt; 5192 } 5193 5194 /// LowerCall - Lower a call to a callseq_start + CALL + callseq_end chain, 5195 /// and add input and output parameter nodes. 5196 SDValue 5197 AArch64TargetLowering::LowerCall(CallLoweringInfo &CLI, 5198 SmallVectorImpl<SDValue> &InVals) const { 5199 SelectionDAG &DAG = CLI.DAG; 5200 SDLoc &DL = CLI.DL; 5201 SmallVector<ISD::OutputArg, 32> &Outs = CLI.Outs; 5202 SmallVector<SDValue, 32> &OutVals = CLI.OutVals; 5203 SmallVector<ISD::InputArg, 32> &Ins = CLI.Ins; 5204 SDValue Chain = CLI.Chain; 5205 SDValue Callee = CLI.Callee; 5206 bool &IsTailCall = CLI.IsTailCall; 5207 CallingConv::ID CallConv = CLI.CallConv; 5208 bool IsVarArg = CLI.IsVarArg; 5209 5210 MachineFunction &MF = DAG.getMachineFunction(); 5211 MachineFunction::CallSiteInfo CSInfo; 5212 bool IsThisReturn = false; 5213 5214 AArch64FunctionInfo *FuncInfo = MF.getInfo<AArch64FunctionInfo>(); 5215 bool TailCallOpt = MF.getTarget().Options.GuaranteedTailCallOpt; 5216 bool IsSibCall = false; 5217 5218 // Check callee args/returns for SVE registers and set calling convention 5219 // accordingly. 5220 if (CallConv == CallingConv::C) { 5221 bool CalleeOutSVE = any_of(Outs, [](ISD::OutputArg &Out){ 5222 return Out.VT.isScalableVector(); 5223 }); 5224 bool CalleeInSVE = any_of(Ins, [](ISD::InputArg &In){ 5225 return In.VT.isScalableVector(); 5226 }); 5227 5228 if (CalleeInSVE || CalleeOutSVE) 5229 CallConv = CallingConv::AArch64_SVE_VectorCall; 5230 } 5231 5232 if (IsTailCall) { 5233 // Check if it's really possible to do a tail call. 5234 IsTailCall = isEligibleForTailCallOptimization( 5235 Callee, CallConv, IsVarArg, Outs, OutVals, Ins, DAG); 5236 if (!IsTailCall && CLI.CB && CLI.CB->isMustTailCall()) 5237 report_fatal_error("failed to perform tail call elimination on a call " 5238 "site marked musttail"); 5239 5240 // A sibling call is one where we're under the usual C ABI and not planning 5241 // to change that but can still do a tail call: 5242 if (!TailCallOpt && IsTailCall) 5243 IsSibCall = true; 5244 5245 if (IsTailCall) 5246 ++NumTailCalls; 5247 } 5248 5249 // Analyze operands of the call, assigning locations to each operand. 5250 SmallVector<CCValAssign, 16> ArgLocs; 5251 CCState CCInfo(CallConv, IsVarArg, DAG.getMachineFunction(), ArgLocs, 5252 *DAG.getContext()); 5253 5254 if (IsVarArg) { 5255 // Handle fixed and variable vector arguments differently. 5256 // Variable vector arguments always go into memory. 5257 unsigned NumArgs = Outs.size(); 5258 5259 for (unsigned i = 0; i != NumArgs; ++i) { 5260 MVT ArgVT = Outs[i].VT; 5261 if (!Outs[i].IsFixed && ArgVT.isScalableVector()) 5262 report_fatal_error("Passing SVE types to variadic functions is " 5263 "currently not supported"); 5264 5265 ISD::ArgFlagsTy ArgFlags = Outs[i].Flags; 5266 CCAssignFn *AssignFn = CCAssignFnForCall(CallConv, 5267 /*IsVarArg=*/ !Outs[i].IsFixed); 5268 bool Res = AssignFn(i, ArgVT, ArgVT, CCValAssign::Full, ArgFlags, CCInfo); 5269 assert(!Res && "Call operand has unhandled type"); 5270 (void)Res; 5271 } 5272 } else { 5273 // At this point, Outs[].VT may already be promoted to i32. To correctly 5274 // handle passing i8 as i8 instead of i32 on stack, we pass in both i32 and 5275 // i8 to CC_AArch64_AAPCS with i32 being ValVT and i8 being LocVT. 5276 // Since AnalyzeCallOperands uses Ins[].VT for both ValVT and LocVT, here 5277 // we use a special version of AnalyzeCallOperands to pass in ValVT and 5278 // LocVT. 5279 unsigned NumArgs = Outs.size(); 5280 for (unsigned i = 0; i != NumArgs; ++i) { 5281 MVT ValVT = Outs[i].VT; 5282 // Get type of the original argument. 5283 EVT ActualVT = getValueType(DAG.getDataLayout(), 5284 CLI.getArgs()[Outs[i].OrigArgIndex].Ty, 5285 /*AllowUnknown*/ true); 5286 MVT ActualMVT = ActualVT.isSimple() ? ActualVT.getSimpleVT() : ValVT; 5287 ISD::ArgFlagsTy ArgFlags = Outs[i].Flags; 5288 // If ActualMVT is i1/i8/i16, we should set LocVT to i8/i8/i16. 5289 if (ActualMVT == MVT::i1 || ActualMVT == MVT::i8) 5290 ValVT = MVT::i8; 5291 else if (ActualMVT == MVT::i16) 5292 ValVT = MVT::i16; 5293 5294 CCAssignFn *AssignFn = CCAssignFnForCall(CallConv, /*IsVarArg=*/false); 5295 bool Res = AssignFn(i, ValVT, ValVT, CCValAssign::Full, ArgFlags, CCInfo); 5296 assert(!Res && "Call operand has unhandled type"); 5297 (void)Res; 5298 } 5299 } 5300 5301 // Get a count of how many bytes are to be pushed on the stack. 5302 unsigned NumBytes = CCInfo.getNextStackOffset(); 5303 5304 if (IsSibCall) { 5305 // Since we're not changing the ABI to make this a tail call, the memory 5306 // operands are already available in the caller's incoming argument space. 5307 NumBytes = 0; 5308 } 5309 5310 // FPDiff is the byte offset of the call's argument area from the callee's. 5311 // Stores to callee stack arguments will be placed in FixedStackSlots offset 5312 // by this amount for a tail call. In a sibling call it must be 0 because the 5313 // caller will deallocate the entire stack and the callee still expects its 5314 // arguments to begin at SP+0. Completely unused for non-tail calls. 5315 int FPDiff = 0; 5316 5317 if (IsTailCall && !IsSibCall) { 5318 unsigned NumReusableBytes = FuncInfo->getBytesInStackArgArea(); 5319 5320 // Since callee will pop argument stack as a tail call, we must keep the 5321 // popped size 16-byte aligned. 5322 NumBytes = alignTo(NumBytes, 16); 5323 5324 // FPDiff will be negative if this tail call requires more space than we 5325 // would automatically have in our incoming argument space. Positive if we 5326 // can actually shrink the stack. 5327 FPDiff = NumReusableBytes - NumBytes; 5328 5329 // The stack pointer must be 16-byte aligned at all times it's used for a 5330 // memory operation, which in practice means at *all* times and in 5331 // particular across call boundaries. Therefore our own arguments started at 5332 // a 16-byte aligned SP and the delta applied for the tail call should 5333 // satisfy the same constraint. 5334 assert(FPDiff % 16 == 0 && "unaligned stack on tail call"); 5335 } 5336 5337 // Adjust the stack pointer for the new arguments... 5338 // These operations are automatically eliminated by the prolog/epilog pass 5339 if (!IsSibCall) 5340 Chain = DAG.getCALLSEQ_START(Chain, NumBytes, 0, DL); 5341 5342 SDValue StackPtr = DAG.getCopyFromReg(Chain, DL, AArch64::SP, 5343 getPointerTy(DAG.getDataLayout())); 5344 5345 SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass; 5346 SmallSet<unsigned, 8> RegsUsed; 5347 SmallVector<SDValue, 8> MemOpChains; 5348 auto PtrVT = getPointerTy(DAG.getDataLayout()); 5349 5350 if (IsVarArg && CLI.CB && CLI.CB->isMustTailCall()) { 5351 const auto &Forwards = FuncInfo->getForwardedMustTailRegParms(); 5352 for (const auto &F : Forwards) { 5353 SDValue Val = DAG.getCopyFromReg(Chain, DL, F.VReg, F.VT); 5354 RegsToPass.emplace_back(F.PReg, Val); 5355 } 5356 } 5357 5358 // Walk the register/memloc assignments, inserting copies/loads. 5359 unsigned ExtraArgLocs = 0; 5360 for (unsigned i = 0, e = Outs.size(); i != e; ++i) { 5361 CCValAssign &VA = ArgLocs[i - ExtraArgLocs]; 5362 SDValue Arg = OutVals[i]; 5363 ISD::ArgFlagsTy Flags = Outs[i].Flags; 5364 5365 // Promote the value if needed. 5366 switch (VA.getLocInfo()) { 5367 default: 5368 llvm_unreachable("Unknown loc info!"); 5369 case CCValAssign::Full: 5370 break; 5371 case CCValAssign::SExt: 5372 Arg = DAG.getNode(ISD::SIGN_EXTEND, DL, VA.getLocVT(), Arg); 5373 break; 5374 case CCValAssign::ZExt: 5375 Arg = DAG.getNode(ISD::ZERO_EXTEND, DL, VA.getLocVT(), Arg); 5376 break; 5377 case CCValAssign::AExt: 5378 if (Outs[i].ArgVT == MVT::i1) { 5379 // AAPCS requires i1 to be zero-extended to 8-bits by the caller. 5380 Arg = DAG.getNode(ISD::TRUNCATE, DL, MVT::i1, Arg); 5381 Arg = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i8, Arg); 5382 } 5383 Arg = DAG.getNode(ISD::ANY_EXTEND, DL, VA.getLocVT(), Arg); 5384 break; 5385 case CCValAssign::AExtUpper: 5386 assert(VA.getValVT() == MVT::i32 && "only expect 32 -> 64 upper bits"); 5387 Arg = DAG.getNode(ISD::ANY_EXTEND, DL, VA.getLocVT(), Arg); 5388 Arg = DAG.getNode(ISD::SHL, DL, VA.getLocVT(), Arg, 5389 DAG.getConstant(32, DL, VA.getLocVT())); 5390 break; 5391 case CCValAssign::BCvt: 5392 Arg = DAG.getBitcast(VA.getLocVT(), Arg); 5393 break; 5394 case CCValAssign::Trunc: 5395 Arg = DAG.getZExtOrTrunc(Arg, DL, VA.getLocVT()); 5396 break; 5397 case CCValAssign::FPExt: 5398 Arg = DAG.getNode(ISD::FP_EXTEND, DL, VA.getLocVT(), Arg); 5399 break; 5400 case CCValAssign::Indirect: 5401 assert(VA.getValVT().isScalableVector() && 5402 "Only scalable vectors can be passed indirectly"); 5403 5404 uint64_t StoreSize = VA.getValVT().getStoreSize().getKnownMinSize(); 5405 uint64_t PartSize = StoreSize; 5406 unsigned NumParts = 1; 5407 if (Outs[i].Flags.isInConsecutiveRegs()) { 5408 assert(!Outs[i].Flags.isInConsecutiveRegsLast()); 5409 while (!Outs[i + NumParts - 1].Flags.isInConsecutiveRegsLast()) 5410 ++NumParts; 5411 StoreSize *= NumParts; 5412 } 5413 5414 MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo(); 5415 Type *Ty = EVT(VA.getValVT()).getTypeForEVT(*DAG.getContext()); 5416 Align Alignment = DAG.getDataLayout().getPrefTypeAlign(Ty); 5417 int FI = MFI.CreateStackObject(StoreSize, Alignment, false); 5418 MFI.setStackID(FI, TargetStackID::ScalableVector); 5419 5420 MachinePointerInfo MPI = 5421 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI); 5422 SDValue Ptr = DAG.getFrameIndex( 5423 FI, DAG.getTargetLoweringInfo().getFrameIndexTy(DAG.getDataLayout())); 5424 SDValue SpillSlot = Ptr; 5425 5426 // Ensure we generate all stores for each tuple part, whilst updating the 5427 // pointer after each store correctly using vscale. 5428 while (NumParts) { 5429 Chain = DAG.getStore(Chain, DL, OutVals[i], Ptr, MPI); 5430 NumParts--; 5431 if (NumParts > 0) { 5432 SDValue BytesIncrement = DAG.getVScale( 5433 DL, Ptr.getValueType(), 5434 APInt(Ptr.getValueSizeInBits().getFixedSize(), PartSize)); 5435 SDNodeFlags Flags; 5436 Flags.setNoUnsignedWrap(true); 5437 5438 MPI = MachinePointerInfo(MPI.getAddrSpace()); 5439 Ptr = DAG.getNode(ISD::ADD, DL, Ptr.getValueType(), Ptr, 5440 BytesIncrement, Flags); 5441 ExtraArgLocs++; 5442 i++; 5443 } 5444 } 5445 5446 Arg = SpillSlot; 5447 break; 5448 } 5449 5450 if (VA.isRegLoc()) { 5451 if (i == 0 && Flags.isReturned() && !Flags.isSwiftSelf() && 5452 Outs[0].VT == MVT::i64) { 5453 assert(VA.getLocVT() == MVT::i64 && 5454 "unexpected calling convention register assignment"); 5455 assert(!Ins.empty() && Ins[0].VT == MVT::i64 && 5456 "unexpected use of 'returned'"); 5457 IsThisReturn = true; 5458 } 5459 if (RegsUsed.count(VA.getLocReg())) { 5460 // If this register has already been used then we're trying to pack 5461 // parts of an [N x i32] into an X-register. The extension type will 5462 // take care of putting the two halves in the right place but we have to 5463 // combine them. 5464 SDValue &Bits = 5465 llvm::find_if(RegsToPass, 5466 [=](const std::pair<unsigned, SDValue> &Elt) { 5467 return Elt.first == VA.getLocReg(); 5468 }) 5469 ->second; 5470 Bits = DAG.getNode(ISD::OR, DL, Bits.getValueType(), Bits, Arg); 5471 // Call site info is used for function's parameter entry value 5472 // tracking. For now we track only simple cases when parameter 5473 // is transferred through whole register. 5474 llvm::erase_if(CSInfo, [&VA](MachineFunction::ArgRegPair ArgReg) { 5475 return ArgReg.Reg == VA.getLocReg(); 5476 }); 5477 } else { 5478 RegsToPass.emplace_back(VA.getLocReg(), Arg); 5479 RegsUsed.insert(VA.getLocReg()); 5480 const TargetOptions &Options = DAG.getTarget().Options; 5481 if (Options.EmitCallSiteInfo) 5482 CSInfo.emplace_back(VA.getLocReg(), i); 5483 } 5484 } else { 5485 assert(VA.isMemLoc()); 5486 5487 SDValue DstAddr; 5488 MachinePointerInfo DstInfo; 5489 5490 // FIXME: This works on big-endian for composite byvals, which are the 5491 // common case. It should also work for fundamental types too. 5492 uint32_t BEAlign = 0; 5493 unsigned OpSize; 5494 if (VA.getLocInfo() == CCValAssign::Indirect) 5495 OpSize = VA.getLocVT().getFixedSizeInBits(); 5496 else 5497 OpSize = Flags.isByVal() ? Flags.getByValSize() * 8 5498 : VA.getValVT().getSizeInBits(); 5499 OpSize = (OpSize + 7) / 8; 5500 if (!Subtarget->isLittleEndian() && !Flags.isByVal() && 5501 !Flags.isInConsecutiveRegs()) { 5502 if (OpSize < 8) 5503 BEAlign = 8 - OpSize; 5504 } 5505 unsigned LocMemOffset = VA.getLocMemOffset(); 5506 int32_t Offset = LocMemOffset + BEAlign; 5507 SDValue PtrOff = DAG.getIntPtrConstant(Offset, DL); 5508 PtrOff = DAG.getNode(ISD::ADD, DL, PtrVT, StackPtr, PtrOff); 5509 5510 if (IsTailCall) { 5511 Offset = Offset + FPDiff; 5512 int FI = MF.getFrameInfo().CreateFixedObject(OpSize, Offset, true); 5513 5514 DstAddr = DAG.getFrameIndex(FI, PtrVT); 5515 DstInfo = 5516 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI); 5517 5518 // Make sure any stack arguments overlapping with where we're storing 5519 // are loaded before this eventual operation. Otherwise they'll be 5520 // clobbered. 5521 Chain = addTokenForArgument(Chain, DAG, MF.getFrameInfo(), FI); 5522 } else { 5523 SDValue PtrOff = DAG.getIntPtrConstant(Offset, DL); 5524 5525 DstAddr = DAG.getNode(ISD::ADD, DL, PtrVT, StackPtr, PtrOff); 5526 DstInfo = MachinePointerInfo::getStack(DAG.getMachineFunction(), 5527 LocMemOffset); 5528 } 5529 5530 if (Outs[i].Flags.isByVal()) { 5531 SDValue SizeNode = 5532 DAG.getConstant(Outs[i].Flags.getByValSize(), DL, MVT::i64); 5533 SDValue Cpy = DAG.getMemcpy( 5534 Chain, DL, DstAddr, Arg, SizeNode, 5535 Outs[i].Flags.getNonZeroByValAlign(), 5536 /*isVol = */ false, /*AlwaysInline = */ false, 5537 /*isTailCall = */ false, DstInfo, MachinePointerInfo()); 5538 5539 MemOpChains.push_back(Cpy); 5540 } else { 5541 // Since we pass i1/i8/i16 as i1/i8/i16 on stack and Arg is already 5542 // promoted to a legal register type i32, we should truncate Arg back to 5543 // i1/i8/i16. 5544 if (VA.getValVT() == MVT::i1 || VA.getValVT() == MVT::i8 || 5545 VA.getValVT() == MVT::i16) 5546 Arg = DAG.getNode(ISD::TRUNCATE, DL, VA.getValVT(), Arg); 5547 5548 SDValue Store = DAG.getStore(Chain, DL, Arg, DstAddr, DstInfo); 5549 MemOpChains.push_back(Store); 5550 } 5551 } 5552 } 5553 5554 if (!MemOpChains.empty()) 5555 Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, MemOpChains); 5556 5557 // Build a sequence of copy-to-reg nodes chained together with token chain 5558 // and flag operands which copy the outgoing args into the appropriate regs. 5559 SDValue InFlag; 5560 for (auto &RegToPass : RegsToPass) { 5561 Chain = DAG.getCopyToReg(Chain, DL, RegToPass.first, 5562 RegToPass.second, InFlag); 5563 InFlag = Chain.getValue(1); 5564 } 5565 5566 // If the callee is a GlobalAddress/ExternalSymbol node (quite common, every 5567 // direct call is) turn it into a TargetGlobalAddress/TargetExternalSymbol 5568 // node so that legalize doesn't hack it. 5569 if (auto *G = dyn_cast<GlobalAddressSDNode>(Callee)) { 5570 auto GV = G->getGlobal(); 5571 unsigned OpFlags = 5572 Subtarget->classifyGlobalFunctionReference(GV, getTargetMachine()); 5573 if (OpFlags & AArch64II::MO_GOT) { 5574 Callee = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, OpFlags); 5575 Callee = DAG.getNode(AArch64ISD::LOADgot, DL, PtrVT, Callee); 5576 } else { 5577 const GlobalValue *GV = G->getGlobal(); 5578 Callee = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, 0); 5579 } 5580 } else if (auto *S = dyn_cast<ExternalSymbolSDNode>(Callee)) { 5581 if (getTargetMachine().getCodeModel() == CodeModel::Large && 5582 Subtarget->isTargetMachO()) { 5583 const char *Sym = S->getSymbol(); 5584 Callee = DAG.getTargetExternalSymbol(Sym, PtrVT, AArch64II::MO_GOT); 5585 Callee = DAG.getNode(AArch64ISD::LOADgot, DL, PtrVT, Callee); 5586 } else { 5587 const char *Sym = S->getSymbol(); 5588 Callee = DAG.getTargetExternalSymbol(Sym, PtrVT, 0); 5589 } 5590 } 5591 5592 // We don't usually want to end the call-sequence here because we would tidy 5593 // the frame up *after* the call, however in the ABI-changing tail-call case 5594 // we've carefully laid out the parameters so that when sp is reset they'll be 5595 // in the correct location. 5596 if (IsTailCall && !IsSibCall) { 5597 Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, DL, true), 5598 DAG.getIntPtrConstant(0, DL, true), InFlag, DL); 5599 InFlag = Chain.getValue(1); 5600 } 5601 5602 std::vector<SDValue> Ops; 5603 Ops.push_back(Chain); 5604 Ops.push_back(Callee); 5605 5606 if (IsTailCall) { 5607 // Each tail call may have to adjust the stack by a different amount, so 5608 // this information must travel along with the operation for eventual 5609 // consumption by emitEpilogue. 5610 Ops.push_back(DAG.getTargetConstant(FPDiff, DL, MVT::i32)); 5611 } 5612 5613 // Add argument registers to the end of the list so that they are known live 5614 // into the call. 5615 for (auto &RegToPass : RegsToPass) 5616 Ops.push_back(DAG.getRegister(RegToPass.first, 5617 RegToPass.second.getValueType())); 5618 5619 // Add a register mask operand representing the call-preserved registers. 5620 const uint32_t *Mask; 5621 const AArch64RegisterInfo *TRI = Subtarget->getRegisterInfo(); 5622 if (IsThisReturn) { 5623 // For 'this' returns, use the X0-preserving mask if applicable 5624 Mask = TRI->getThisReturnPreservedMask(MF, CallConv); 5625 if (!Mask) { 5626 IsThisReturn = false; 5627 Mask = TRI->getCallPreservedMask(MF, CallConv); 5628 } 5629 } else 5630 Mask = TRI->getCallPreservedMask(MF, CallConv); 5631 5632 if (Subtarget->hasCustomCallingConv()) 5633 TRI->UpdateCustomCallPreservedMask(MF, &Mask); 5634 5635 if (TRI->isAnyArgRegReserved(MF)) 5636 TRI->emitReservedArgRegCallError(MF); 5637 5638 assert(Mask && "Missing call preserved mask for calling convention"); 5639 Ops.push_back(DAG.getRegisterMask(Mask)); 5640 5641 if (InFlag.getNode()) 5642 Ops.push_back(InFlag); 5643 5644 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue); 5645 5646 // If we're doing a tall call, use a TC_RETURN here rather than an 5647 // actual call instruction. 5648 if (IsTailCall) { 5649 MF.getFrameInfo().setHasTailCall(); 5650 SDValue Ret = DAG.getNode(AArch64ISD::TC_RETURN, DL, NodeTys, Ops); 5651 DAG.addCallSiteInfo(Ret.getNode(), std::move(CSInfo)); 5652 return Ret; 5653 } 5654 5655 unsigned CallOpc = AArch64ISD::CALL; 5656 // Calls marked with "rv_marker" are special. They should be expanded to the 5657 // call, directly followed by a special marker sequence. Use the CALL_RVMARKER 5658 // to do that. 5659 if (CLI.CB && CLI.CB->hasRetAttr("rv_marker")) { 5660 assert(!IsTailCall && "tail calls cannot be marked with rv_marker"); 5661 CallOpc = AArch64ISD::CALL_RVMARKER; 5662 } 5663 5664 // Returns a chain and a flag for retval copy to use. 5665 Chain = DAG.getNode(CallOpc, DL, NodeTys, Ops); 5666 DAG.addNoMergeSiteInfo(Chain.getNode(), CLI.NoMerge); 5667 InFlag = Chain.getValue(1); 5668 DAG.addCallSiteInfo(Chain.getNode(), std::move(CSInfo)); 5669 5670 uint64_t CalleePopBytes = 5671 DoesCalleeRestoreStack(CallConv, TailCallOpt) ? alignTo(NumBytes, 16) : 0; 5672 5673 Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, DL, true), 5674 DAG.getIntPtrConstant(CalleePopBytes, DL, true), 5675 InFlag, DL); 5676 if (!Ins.empty()) 5677 InFlag = Chain.getValue(1); 5678 5679 // Handle result values, copying them out of physregs into vregs that we 5680 // return. 5681 return LowerCallResult(Chain, InFlag, CallConv, IsVarArg, Ins, DL, DAG, 5682 InVals, IsThisReturn, 5683 IsThisReturn ? OutVals[0] : SDValue()); 5684 } 5685 5686 bool AArch64TargetLowering::CanLowerReturn( 5687 CallingConv::ID CallConv, MachineFunction &MF, bool isVarArg, 5688 const SmallVectorImpl<ISD::OutputArg> &Outs, LLVMContext &Context) const { 5689 CCAssignFn *RetCC = CCAssignFnForReturn(CallConv); 5690 SmallVector<CCValAssign, 16> RVLocs; 5691 CCState CCInfo(CallConv, isVarArg, MF, RVLocs, Context); 5692 return CCInfo.CheckReturn(Outs, RetCC); 5693 } 5694 5695 SDValue 5696 AArch64TargetLowering::LowerReturn(SDValue Chain, CallingConv::ID CallConv, 5697 bool isVarArg, 5698 const SmallVectorImpl<ISD::OutputArg> &Outs, 5699 const SmallVectorImpl<SDValue> &OutVals, 5700 const SDLoc &DL, SelectionDAG &DAG) const { 5701 auto &MF = DAG.getMachineFunction(); 5702 auto *FuncInfo = MF.getInfo<AArch64FunctionInfo>(); 5703 5704 CCAssignFn *RetCC = CCAssignFnForReturn(CallConv); 5705 SmallVector<CCValAssign, 16> RVLocs; 5706 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs, 5707 *DAG.getContext()); 5708 CCInfo.AnalyzeReturn(Outs, RetCC); 5709 5710 // Copy the result values into the output registers. 5711 SDValue Flag; 5712 SmallVector<std::pair<unsigned, SDValue>, 4> RetVals; 5713 SmallSet<unsigned, 4> RegsUsed; 5714 for (unsigned i = 0, realRVLocIdx = 0; i != RVLocs.size(); 5715 ++i, ++realRVLocIdx) { 5716 CCValAssign &VA = RVLocs[i]; 5717 assert(VA.isRegLoc() && "Can only return in registers!"); 5718 SDValue Arg = OutVals[realRVLocIdx]; 5719 5720 switch (VA.getLocInfo()) { 5721 default: 5722 llvm_unreachable("Unknown loc info!"); 5723 case CCValAssign::Full: 5724 if (Outs[i].ArgVT == MVT::i1) { 5725 // AAPCS requires i1 to be zero-extended to i8 by the producer of the 5726 // value. This is strictly redundant on Darwin (which uses "zeroext 5727 // i1"), but will be optimised out before ISel. 5728 Arg = DAG.getNode(ISD::TRUNCATE, DL, MVT::i1, Arg); 5729 Arg = DAG.getNode(ISD::ZERO_EXTEND, DL, VA.getLocVT(), Arg); 5730 } 5731 break; 5732 case CCValAssign::BCvt: 5733 Arg = DAG.getNode(ISD::BITCAST, DL, VA.getLocVT(), Arg); 5734 break; 5735 case CCValAssign::AExt: 5736 case CCValAssign::ZExt: 5737 Arg = DAG.getZExtOrTrunc(Arg, DL, VA.getLocVT()); 5738 break; 5739 case CCValAssign::AExtUpper: 5740 assert(VA.getValVT() == MVT::i32 && "only expect 32 -> 64 upper bits"); 5741 Arg = DAG.getZExtOrTrunc(Arg, DL, VA.getLocVT()); 5742 Arg = DAG.getNode(ISD::SHL, DL, VA.getLocVT(), Arg, 5743 DAG.getConstant(32, DL, VA.getLocVT())); 5744 break; 5745 } 5746 5747 if (RegsUsed.count(VA.getLocReg())) { 5748 SDValue &Bits = 5749 llvm::find_if(RetVals, [=](const std::pair<unsigned, SDValue> &Elt) { 5750 return Elt.first == VA.getLocReg(); 5751 })->second; 5752 Bits = DAG.getNode(ISD::OR, DL, Bits.getValueType(), Bits, Arg); 5753 } else { 5754 RetVals.emplace_back(VA.getLocReg(), Arg); 5755 RegsUsed.insert(VA.getLocReg()); 5756 } 5757 } 5758 5759 SmallVector<SDValue, 4> RetOps(1, Chain); 5760 for (auto &RetVal : RetVals) { 5761 Chain = DAG.getCopyToReg(Chain, DL, RetVal.first, RetVal.second, Flag); 5762 Flag = Chain.getValue(1); 5763 RetOps.push_back( 5764 DAG.getRegister(RetVal.first, RetVal.second.getValueType())); 5765 } 5766 5767 // Windows AArch64 ABIs require that for returning structs by value we copy 5768 // the sret argument into X0 for the return. 5769 // We saved the argument into a virtual register in the entry block, 5770 // so now we copy the value out and into X0. 5771 if (unsigned SRetReg = FuncInfo->getSRetReturnReg()) { 5772 SDValue Val = DAG.getCopyFromReg(RetOps[0], DL, SRetReg, 5773 getPointerTy(MF.getDataLayout())); 5774 5775 unsigned RetValReg = AArch64::X0; 5776 Chain = DAG.getCopyToReg(Chain, DL, RetValReg, Val, Flag); 5777 Flag = Chain.getValue(1); 5778 5779 RetOps.push_back( 5780 DAG.getRegister(RetValReg, getPointerTy(DAG.getDataLayout()))); 5781 } 5782 5783 const AArch64RegisterInfo *TRI = Subtarget->getRegisterInfo(); 5784 const MCPhysReg *I = 5785 TRI->getCalleeSavedRegsViaCopy(&DAG.getMachineFunction()); 5786 if (I) { 5787 for (; *I; ++I) { 5788 if (AArch64::GPR64RegClass.contains(*I)) 5789 RetOps.push_back(DAG.getRegister(*I, MVT::i64)); 5790 else if (AArch64::FPR64RegClass.contains(*I)) 5791 RetOps.push_back(DAG.getRegister(*I, MVT::getFloatingPointVT(64))); 5792 else 5793 llvm_unreachable("Unexpected register class in CSRsViaCopy!"); 5794 } 5795 } 5796 5797 RetOps[0] = Chain; // Update chain. 5798 5799 // Add the flag if we have it. 5800 if (Flag.getNode()) 5801 RetOps.push_back(Flag); 5802 5803 return DAG.getNode(AArch64ISD::RET_FLAG, DL, MVT::Other, RetOps); 5804 } 5805 5806 //===----------------------------------------------------------------------===// 5807 // Other Lowering Code 5808 //===----------------------------------------------------------------------===// 5809 5810 SDValue AArch64TargetLowering::getTargetNode(GlobalAddressSDNode *N, EVT Ty, 5811 SelectionDAG &DAG, 5812 unsigned Flag) const { 5813 return DAG.getTargetGlobalAddress(N->getGlobal(), SDLoc(N), Ty, 5814 N->getOffset(), Flag); 5815 } 5816 5817 SDValue AArch64TargetLowering::getTargetNode(JumpTableSDNode *N, EVT Ty, 5818 SelectionDAG &DAG, 5819 unsigned Flag) const { 5820 return DAG.getTargetJumpTable(N->getIndex(), Ty, Flag); 5821 } 5822 5823 SDValue AArch64TargetLowering::getTargetNode(ConstantPoolSDNode *N, EVT Ty, 5824 SelectionDAG &DAG, 5825 unsigned Flag) const { 5826 return DAG.getTargetConstantPool(N->getConstVal(), Ty, N->getAlign(), 5827 N->getOffset(), Flag); 5828 } 5829 5830 SDValue AArch64TargetLowering::getTargetNode(BlockAddressSDNode* N, EVT Ty, 5831 SelectionDAG &DAG, 5832 unsigned Flag) const { 5833 return DAG.getTargetBlockAddress(N->getBlockAddress(), Ty, 0, Flag); 5834 } 5835 5836 // (loadGOT sym) 5837 template <class NodeTy> 5838 SDValue AArch64TargetLowering::getGOT(NodeTy *N, SelectionDAG &DAG, 5839 unsigned Flags) const { 5840 LLVM_DEBUG(dbgs() << "AArch64TargetLowering::getGOT\n"); 5841 SDLoc DL(N); 5842 EVT Ty = getPointerTy(DAG.getDataLayout()); 5843 SDValue GotAddr = getTargetNode(N, Ty, DAG, AArch64II::MO_GOT | Flags); 5844 // FIXME: Once remat is capable of dealing with instructions with register 5845 // operands, expand this into two nodes instead of using a wrapper node. 5846 return DAG.getNode(AArch64ISD::LOADgot, DL, Ty, GotAddr); 5847 } 5848 5849 // (wrapper %highest(sym), %higher(sym), %hi(sym), %lo(sym)) 5850 template <class NodeTy> 5851 SDValue AArch64TargetLowering::getAddrLarge(NodeTy *N, SelectionDAG &DAG, 5852 unsigned Flags) const { 5853 LLVM_DEBUG(dbgs() << "AArch64TargetLowering::getAddrLarge\n"); 5854 SDLoc DL(N); 5855 EVT Ty = getPointerTy(DAG.getDataLayout()); 5856 const unsigned char MO_NC = AArch64II::MO_NC; 5857 return DAG.getNode( 5858 AArch64ISD::WrapperLarge, DL, Ty, 5859 getTargetNode(N, Ty, DAG, AArch64II::MO_G3 | Flags), 5860 getTargetNode(N, Ty, DAG, AArch64II::MO_G2 | MO_NC | Flags), 5861 getTargetNode(N, Ty, DAG, AArch64II::MO_G1 | MO_NC | Flags), 5862 getTargetNode(N, Ty, DAG, AArch64II::MO_G0 | MO_NC | Flags)); 5863 } 5864 5865 // (addlow (adrp %hi(sym)) %lo(sym)) 5866 template <class NodeTy> 5867 SDValue AArch64TargetLowering::getAddr(NodeTy *N, SelectionDAG &DAG, 5868 unsigned Flags) const { 5869 LLVM_DEBUG(dbgs() << "AArch64TargetLowering::getAddr\n"); 5870 SDLoc DL(N); 5871 EVT Ty = getPointerTy(DAG.getDataLayout()); 5872 SDValue Hi = getTargetNode(N, Ty, DAG, AArch64II::MO_PAGE | Flags); 5873 SDValue Lo = getTargetNode(N, Ty, DAG, 5874 AArch64II::MO_PAGEOFF | AArch64II::MO_NC | Flags); 5875 SDValue ADRP = DAG.getNode(AArch64ISD::ADRP, DL, Ty, Hi); 5876 return DAG.getNode(AArch64ISD::ADDlow, DL, Ty, ADRP, Lo); 5877 } 5878 5879 // (adr sym) 5880 template <class NodeTy> 5881 SDValue AArch64TargetLowering::getAddrTiny(NodeTy *N, SelectionDAG &DAG, 5882 unsigned Flags) const { 5883 LLVM_DEBUG(dbgs() << "AArch64TargetLowering::getAddrTiny\n"); 5884 SDLoc DL(N); 5885 EVT Ty = getPointerTy(DAG.getDataLayout()); 5886 SDValue Sym = getTargetNode(N, Ty, DAG, Flags); 5887 return DAG.getNode(AArch64ISD::ADR, DL, Ty, Sym); 5888 } 5889 5890 SDValue AArch64TargetLowering::LowerGlobalAddress(SDValue Op, 5891 SelectionDAG &DAG) const { 5892 GlobalAddressSDNode *GN = cast<GlobalAddressSDNode>(Op); 5893 const GlobalValue *GV = GN->getGlobal(); 5894 unsigned OpFlags = Subtarget->ClassifyGlobalReference(GV, getTargetMachine()); 5895 5896 if (OpFlags != AArch64II::MO_NO_FLAG) 5897 assert(cast<GlobalAddressSDNode>(Op)->getOffset() == 0 && 5898 "unexpected offset in global node"); 5899 5900 // This also catches the large code model case for Darwin, and tiny code 5901 // model with got relocations. 5902 if ((OpFlags & AArch64II::MO_GOT) != 0) { 5903 return getGOT(GN, DAG, OpFlags); 5904 } 5905 5906 SDValue Result; 5907 if (getTargetMachine().getCodeModel() == CodeModel::Large) { 5908 Result = getAddrLarge(GN, DAG, OpFlags); 5909 } else if (getTargetMachine().getCodeModel() == CodeModel::Tiny) { 5910 Result = getAddrTiny(GN, DAG, OpFlags); 5911 } else { 5912 Result = getAddr(GN, DAG, OpFlags); 5913 } 5914 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 5915 SDLoc DL(GN); 5916 if (OpFlags & (AArch64II::MO_DLLIMPORT | AArch64II::MO_COFFSTUB)) 5917 Result = DAG.getLoad(PtrVT, DL, DAG.getEntryNode(), Result, 5918 MachinePointerInfo::getGOT(DAG.getMachineFunction())); 5919 return Result; 5920 } 5921 5922 /// Convert a TLS address reference into the correct sequence of loads 5923 /// and calls to compute the variable's address (for Darwin, currently) and 5924 /// return an SDValue containing the final node. 5925 5926 /// Darwin only has one TLS scheme which must be capable of dealing with the 5927 /// fully general situation, in the worst case. This means: 5928 /// + "extern __thread" declaration. 5929 /// + Defined in a possibly unknown dynamic library. 5930 /// 5931 /// The general system is that each __thread variable has a [3 x i64] descriptor 5932 /// which contains information used by the runtime to calculate the address. The 5933 /// only part of this the compiler needs to know about is the first xword, which 5934 /// contains a function pointer that must be called with the address of the 5935 /// entire descriptor in "x0". 5936 /// 5937 /// Since this descriptor may be in a different unit, in general even the 5938 /// descriptor must be accessed via an indirect load. The "ideal" code sequence 5939 /// is: 5940 /// adrp x0, _var@TLVPPAGE 5941 /// ldr x0, [x0, _var@TLVPPAGEOFF] ; x0 now contains address of descriptor 5942 /// ldr x1, [x0] ; x1 contains 1st entry of descriptor, 5943 /// ; the function pointer 5944 /// blr x1 ; Uses descriptor address in x0 5945 /// ; Address of _var is now in x0. 5946 /// 5947 /// If the address of _var's descriptor *is* known to the linker, then it can 5948 /// change the first "ldr" instruction to an appropriate "add x0, x0, #imm" for 5949 /// a slight efficiency gain. 5950 SDValue 5951 AArch64TargetLowering::LowerDarwinGlobalTLSAddress(SDValue Op, 5952 SelectionDAG &DAG) const { 5953 assert(Subtarget->isTargetDarwin() && 5954 "This function expects a Darwin target"); 5955 5956 SDLoc DL(Op); 5957 MVT PtrVT = getPointerTy(DAG.getDataLayout()); 5958 MVT PtrMemVT = getPointerMemTy(DAG.getDataLayout()); 5959 const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal(); 5960 5961 SDValue TLVPAddr = 5962 DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, AArch64II::MO_TLS); 5963 SDValue DescAddr = DAG.getNode(AArch64ISD::LOADgot, DL, PtrVT, TLVPAddr); 5964 5965 // The first entry in the descriptor is a function pointer that we must call 5966 // to obtain the address of the variable. 5967 SDValue Chain = DAG.getEntryNode(); 5968 SDValue FuncTLVGet = DAG.getLoad( 5969 PtrMemVT, DL, Chain, DescAddr, 5970 MachinePointerInfo::getGOT(DAG.getMachineFunction()), 5971 Align(PtrMemVT.getSizeInBits() / 8), 5972 MachineMemOperand::MOInvariant | MachineMemOperand::MODereferenceable); 5973 Chain = FuncTLVGet.getValue(1); 5974 5975 // Extend loaded pointer if necessary (i.e. if ILP32) to DAG pointer. 5976 FuncTLVGet = DAG.getZExtOrTrunc(FuncTLVGet, DL, PtrVT); 5977 5978 MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo(); 5979 MFI.setAdjustsStack(true); 5980 5981 // TLS calls preserve all registers except those that absolutely must be 5982 // trashed: X0 (it takes an argument), LR (it's a call) and NZCV (let's not be 5983 // silly). 5984 const AArch64RegisterInfo *TRI = Subtarget->getRegisterInfo(); 5985 const uint32_t *Mask = TRI->getTLSCallPreservedMask(); 5986 if (Subtarget->hasCustomCallingConv()) 5987 TRI->UpdateCustomCallPreservedMask(DAG.getMachineFunction(), &Mask); 5988 5989 // Finally, we can make the call. This is just a degenerate version of a 5990 // normal AArch64 call node: x0 takes the address of the descriptor, and 5991 // returns the address of the variable in this thread. 5992 Chain = DAG.getCopyToReg(Chain, DL, AArch64::X0, DescAddr, SDValue()); 5993 Chain = 5994 DAG.getNode(AArch64ISD::CALL, DL, DAG.getVTList(MVT::Other, MVT::Glue), 5995 Chain, FuncTLVGet, DAG.getRegister(AArch64::X0, MVT::i64), 5996 DAG.getRegisterMask(Mask), Chain.getValue(1)); 5997 return DAG.getCopyFromReg(Chain, DL, AArch64::X0, PtrVT, Chain.getValue(1)); 5998 } 5999 6000 /// Convert a thread-local variable reference into a sequence of instructions to 6001 /// compute the variable's address for the local exec TLS model of ELF targets. 6002 /// The sequence depends on the maximum TLS area size. 6003 SDValue AArch64TargetLowering::LowerELFTLSLocalExec(const GlobalValue *GV, 6004 SDValue ThreadBase, 6005 const SDLoc &DL, 6006 SelectionDAG &DAG) const { 6007 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 6008 SDValue TPOff, Addr; 6009 6010 switch (DAG.getTarget().Options.TLSSize) { 6011 default: 6012 llvm_unreachable("Unexpected TLS size"); 6013 6014 case 12: { 6015 // mrs x0, TPIDR_EL0 6016 // add x0, x0, :tprel_lo12:a 6017 SDValue Var = DAG.getTargetGlobalAddress( 6018 GV, DL, PtrVT, 0, AArch64II::MO_TLS | AArch64II::MO_PAGEOFF); 6019 return SDValue(DAG.getMachineNode(AArch64::ADDXri, DL, PtrVT, ThreadBase, 6020 Var, 6021 DAG.getTargetConstant(0, DL, MVT::i32)), 6022 0); 6023 } 6024 6025 case 24: { 6026 // mrs x0, TPIDR_EL0 6027 // add x0, x0, :tprel_hi12:a 6028 // add x0, x0, :tprel_lo12_nc:a 6029 SDValue HiVar = DAG.getTargetGlobalAddress( 6030 GV, DL, PtrVT, 0, AArch64II::MO_TLS | AArch64II::MO_HI12); 6031 SDValue LoVar = DAG.getTargetGlobalAddress( 6032 GV, DL, PtrVT, 0, 6033 AArch64II::MO_TLS | AArch64II::MO_PAGEOFF | AArch64II::MO_NC); 6034 Addr = SDValue(DAG.getMachineNode(AArch64::ADDXri, DL, PtrVT, ThreadBase, 6035 HiVar, 6036 DAG.getTargetConstant(0, DL, MVT::i32)), 6037 0); 6038 return SDValue(DAG.getMachineNode(AArch64::ADDXri, DL, PtrVT, Addr, 6039 LoVar, 6040 DAG.getTargetConstant(0, DL, MVT::i32)), 6041 0); 6042 } 6043 6044 case 32: { 6045 // mrs x1, TPIDR_EL0 6046 // movz x0, #:tprel_g1:a 6047 // movk x0, #:tprel_g0_nc:a 6048 // add x0, x1, x0 6049 SDValue HiVar = DAG.getTargetGlobalAddress( 6050 GV, DL, PtrVT, 0, AArch64II::MO_TLS | AArch64II::MO_G1); 6051 SDValue LoVar = DAG.getTargetGlobalAddress( 6052 GV, DL, PtrVT, 0, 6053 AArch64II::MO_TLS | AArch64II::MO_G0 | AArch64II::MO_NC); 6054 TPOff = SDValue(DAG.getMachineNode(AArch64::MOVZXi, DL, PtrVT, HiVar, 6055 DAG.getTargetConstant(16, DL, MVT::i32)), 6056 0); 6057 TPOff = SDValue(DAG.getMachineNode(AArch64::MOVKXi, DL, PtrVT, TPOff, LoVar, 6058 DAG.getTargetConstant(0, DL, MVT::i32)), 6059 0); 6060 return DAG.getNode(ISD::ADD, DL, PtrVT, ThreadBase, TPOff); 6061 } 6062 6063 case 48: { 6064 // mrs x1, TPIDR_EL0 6065 // movz x0, #:tprel_g2:a 6066 // movk x0, #:tprel_g1_nc:a 6067 // movk x0, #:tprel_g0_nc:a 6068 // add x0, x1, x0 6069 SDValue HiVar = DAG.getTargetGlobalAddress( 6070 GV, DL, PtrVT, 0, AArch64II::MO_TLS | AArch64II::MO_G2); 6071 SDValue MiVar = DAG.getTargetGlobalAddress( 6072 GV, DL, PtrVT, 0, 6073 AArch64II::MO_TLS | AArch64II::MO_G1 | AArch64II::MO_NC); 6074 SDValue LoVar = DAG.getTargetGlobalAddress( 6075 GV, DL, PtrVT, 0, 6076 AArch64II::MO_TLS | AArch64II::MO_G0 | AArch64II::MO_NC); 6077 TPOff = SDValue(DAG.getMachineNode(AArch64::MOVZXi, DL, PtrVT, HiVar, 6078 DAG.getTargetConstant(32, DL, MVT::i32)), 6079 0); 6080 TPOff = SDValue(DAG.getMachineNode(AArch64::MOVKXi, DL, PtrVT, TPOff, MiVar, 6081 DAG.getTargetConstant(16, DL, MVT::i32)), 6082 0); 6083 TPOff = SDValue(DAG.getMachineNode(AArch64::MOVKXi, DL, PtrVT, TPOff, LoVar, 6084 DAG.getTargetConstant(0, DL, MVT::i32)), 6085 0); 6086 return DAG.getNode(ISD::ADD, DL, PtrVT, ThreadBase, TPOff); 6087 } 6088 } 6089 } 6090 6091 /// When accessing thread-local variables under either the general-dynamic or 6092 /// local-dynamic system, we make a "TLS-descriptor" call. The variable will 6093 /// have a descriptor, accessible via a PC-relative ADRP, and whose first entry 6094 /// is a function pointer to carry out the resolution. 6095 /// 6096 /// The sequence is: 6097 /// adrp x0, :tlsdesc:var 6098 /// ldr x1, [x0, #:tlsdesc_lo12:var] 6099 /// add x0, x0, #:tlsdesc_lo12:var 6100 /// .tlsdesccall var 6101 /// blr x1 6102 /// (TPIDR_EL0 offset now in x0) 6103 /// 6104 /// The above sequence must be produced unscheduled, to enable the linker to 6105 /// optimize/relax this sequence. 6106 /// Therefore, a pseudo-instruction (TLSDESC_CALLSEQ) is used to represent the 6107 /// above sequence, and expanded really late in the compilation flow, to ensure 6108 /// the sequence is produced as per above. 6109 SDValue AArch64TargetLowering::LowerELFTLSDescCallSeq(SDValue SymAddr, 6110 const SDLoc &DL, 6111 SelectionDAG &DAG) const { 6112 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 6113 6114 SDValue Chain = DAG.getEntryNode(); 6115 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue); 6116 6117 Chain = 6118 DAG.getNode(AArch64ISD::TLSDESC_CALLSEQ, DL, NodeTys, {Chain, SymAddr}); 6119 SDValue Glue = Chain.getValue(1); 6120 6121 return DAG.getCopyFromReg(Chain, DL, AArch64::X0, PtrVT, Glue); 6122 } 6123 6124 SDValue 6125 AArch64TargetLowering::LowerELFGlobalTLSAddress(SDValue Op, 6126 SelectionDAG &DAG) const { 6127 assert(Subtarget->isTargetELF() && "This function expects an ELF target"); 6128 6129 const GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op); 6130 6131 TLSModel::Model Model = getTargetMachine().getTLSModel(GA->getGlobal()); 6132 6133 if (!EnableAArch64ELFLocalDynamicTLSGeneration) { 6134 if (Model == TLSModel::LocalDynamic) 6135 Model = TLSModel::GeneralDynamic; 6136 } 6137 6138 if (getTargetMachine().getCodeModel() == CodeModel::Large && 6139 Model != TLSModel::LocalExec) 6140 report_fatal_error("ELF TLS only supported in small memory model or " 6141 "in local exec TLS model"); 6142 // Different choices can be made for the maximum size of the TLS area for a 6143 // module. For the small address model, the default TLS size is 16MiB and the 6144 // maximum TLS size is 4GiB. 6145 // FIXME: add tiny and large code model support for TLS access models other 6146 // than local exec. We currently generate the same code as small for tiny, 6147 // which may be larger than needed. 6148 6149 SDValue TPOff; 6150 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 6151 SDLoc DL(Op); 6152 const GlobalValue *GV = GA->getGlobal(); 6153 6154 SDValue ThreadBase = DAG.getNode(AArch64ISD::THREAD_POINTER, DL, PtrVT); 6155 6156 if (Model == TLSModel::LocalExec) { 6157 return LowerELFTLSLocalExec(GV, ThreadBase, DL, DAG); 6158 } else if (Model == TLSModel::InitialExec) { 6159 TPOff = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, AArch64II::MO_TLS); 6160 TPOff = DAG.getNode(AArch64ISD::LOADgot, DL, PtrVT, TPOff); 6161 } else if (Model == TLSModel::LocalDynamic) { 6162 // Local-dynamic accesses proceed in two phases. A general-dynamic TLS 6163 // descriptor call against the special symbol _TLS_MODULE_BASE_ to calculate 6164 // the beginning of the module's TLS region, followed by a DTPREL offset 6165 // calculation. 6166 6167 // These accesses will need deduplicating if there's more than one. 6168 AArch64FunctionInfo *MFI = 6169 DAG.getMachineFunction().getInfo<AArch64FunctionInfo>(); 6170 MFI->incNumLocalDynamicTLSAccesses(); 6171 6172 // The call needs a relocation too for linker relaxation. It doesn't make 6173 // sense to call it MO_PAGE or MO_PAGEOFF though so we need another copy of 6174 // the address. 6175 SDValue SymAddr = DAG.getTargetExternalSymbol("_TLS_MODULE_BASE_", PtrVT, 6176 AArch64II::MO_TLS); 6177 6178 // Now we can calculate the offset from TPIDR_EL0 to this module's 6179 // thread-local area. 6180 TPOff = LowerELFTLSDescCallSeq(SymAddr, DL, DAG); 6181 6182 // Now use :dtprel_whatever: operations to calculate this variable's offset 6183 // in its thread-storage area. 6184 SDValue HiVar = DAG.getTargetGlobalAddress( 6185 GV, DL, MVT::i64, 0, AArch64II::MO_TLS | AArch64II::MO_HI12); 6186 SDValue LoVar = DAG.getTargetGlobalAddress( 6187 GV, DL, MVT::i64, 0, 6188 AArch64II::MO_TLS | AArch64II::MO_PAGEOFF | AArch64II::MO_NC); 6189 6190 TPOff = SDValue(DAG.getMachineNode(AArch64::ADDXri, DL, PtrVT, TPOff, HiVar, 6191 DAG.getTargetConstant(0, DL, MVT::i32)), 6192 0); 6193 TPOff = SDValue(DAG.getMachineNode(AArch64::ADDXri, DL, PtrVT, TPOff, LoVar, 6194 DAG.getTargetConstant(0, DL, MVT::i32)), 6195 0); 6196 } else if (Model == TLSModel::GeneralDynamic) { 6197 // The call needs a relocation too for linker relaxation. It doesn't make 6198 // sense to call it MO_PAGE or MO_PAGEOFF though so we need another copy of 6199 // the address. 6200 SDValue SymAddr = 6201 DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, AArch64II::MO_TLS); 6202 6203 // Finally we can make a call to calculate the offset from tpidr_el0. 6204 TPOff = LowerELFTLSDescCallSeq(SymAddr, DL, DAG); 6205 } else 6206 llvm_unreachable("Unsupported ELF TLS access model"); 6207 6208 return DAG.getNode(ISD::ADD, DL, PtrVT, ThreadBase, TPOff); 6209 } 6210 6211 SDValue 6212 AArch64TargetLowering::LowerWindowsGlobalTLSAddress(SDValue Op, 6213 SelectionDAG &DAG) const { 6214 assert(Subtarget->isTargetWindows() && "Windows specific TLS lowering"); 6215 6216 SDValue Chain = DAG.getEntryNode(); 6217 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 6218 SDLoc DL(Op); 6219 6220 SDValue TEB = DAG.getRegister(AArch64::X18, MVT::i64); 6221 6222 // Load the ThreadLocalStoragePointer from the TEB 6223 // A pointer to the TLS array is located at offset 0x58 from the TEB. 6224 SDValue TLSArray = 6225 DAG.getNode(ISD::ADD, DL, PtrVT, TEB, DAG.getIntPtrConstant(0x58, DL)); 6226 TLSArray = DAG.getLoad(PtrVT, DL, Chain, TLSArray, MachinePointerInfo()); 6227 Chain = TLSArray.getValue(1); 6228 6229 // Load the TLS index from the C runtime; 6230 // This does the same as getAddr(), but without having a GlobalAddressSDNode. 6231 // This also does the same as LOADgot, but using a generic i32 load, 6232 // while LOADgot only loads i64. 6233 SDValue TLSIndexHi = 6234 DAG.getTargetExternalSymbol("_tls_index", PtrVT, AArch64II::MO_PAGE); 6235 SDValue TLSIndexLo = DAG.getTargetExternalSymbol( 6236 "_tls_index", PtrVT, AArch64II::MO_PAGEOFF | AArch64II::MO_NC); 6237 SDValue ADRP = DAG.getNode(AArch64ISD::ADRP, DL, PtrVT, TLSIndexHi); 6238 SDValue TLSIndex = 6239 DAG.getNode(AArch64ISD::ADDlow, DL, PtrVT, ADRP, TLSIndexLo); 6240 TLSIndex = DAG.getLoad(MVT::i32, DL, Chain, TLSIndex, MachinePointerInfo()); 6241 Chain = TLSIndex.getValue(1); 6242 6243 // The pointer to the thread's TLS data area is at the TLS Index scaled by 8 6244 // offset into the TLSArray. 6245 TLSIndex = DAG.getNode(ISD::ZERO_EXTEND, DL, PtrVT, TLSIndex); 6246 SDValue Slot = DAG.getNode(ISD::SHL, DL, PtrVT, TLSIndex, 6247 DAG.getConstant(3, DL, PtrVT)); 6248 SDValue TLS = DAG.getLoad(PtrVT, DL, Chain, 6249 DAG.getNode(ISD::ADD, DL, PtrVT, TLSArray, Slot), 6250 MachinePointerInfo()); 6251 Chain = TLS.getValue(1); 6252 6253 const GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op); 6254 const GlobalValue *GV = GA->getGlobal(); 6255 SDValue TGAHi = DAG.getTargetGlobalAddress( 6256 GV, DL, PtrVT, 0, AArch64II::MO_TLS | AArch64II::MO_HI12); 6257 SDValue TGALo = DAG.getTargetGlobalAddress( 6258 GV, DL, PtrVT, 0, 6259 AArch64II::MO_TLS | AArch64II::MO_PAGEOFF | AArch64II::MO_NC); 6260 6261 // Add the offset from the start of the .tls section (section base). 6262 SDValue Addr = 6263 SDValue(DAG.getMachineNode(AArch64::ADDXri, DL, PtrVT, TLS, TGAHi, 6264 DAG.getTargetConstant(0, DL, MVT::i32)), 6265 0); 6266 Addr = DAG.getNode(AArch64ISD::ADDlow, DL, PtrVT, Addr, TGALo); 6267 return Addr; 6268 } 6269 6270 SDValue AArch64TargetLowering::LowerGlobalTLSAddress(SDValue Op, 6271 SelectionDAG &DAG) const { 6272 const GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op); 6273 if (DAG.getTarget().useEmulatedTLS()) 6274 return LowerToTLSEmulatedModel(GA, DAG); 6275 6276 if (Subtarget->isTargetDarwin()) 6277 return LowerDarwinGlobalTLSAddress(Op, DAG); 6278 if (Subtarget->isTargetELF()) 6279 return LowerELFGlobalTLSAddress(Op, DAG); 6280 if (Subtarget->isTargetWindows()) 6281 return LowerWindowsGlobalTLSAddress(Op, DAG); 6282 6283 llvm_unreachable("Unexpected platform trying to use TLS"); 6284 } 6285 6286 // Looks through \param Val to determine the bit that can be used to 6287 // check the sign of the value. It returns the unextended value and 6288 // the sign bit position. 6289 std::pair<SDValue, uint64_t> lookThroughSignExtension(SDValue Val) { 6290 if (Val.getOpcode() == ISD::SIGN_EXTEND_INREG) 6291 return {Val.getOperand(0), 6292 cast<VTSDNode>(Val.getOperand(1))->getVT().getFixedSizeInBits() - 6293 1}; 6294 6295 if (Val.getOpcode() == ISD::SIGN_EXTEND) 6296 return {Val.getOperand(0), 6297 Val.getOperand(0)->getValueType(0).getFixedSizeInBits() - 1}; 6298 6299 return {Val, Val.getValueSizeInBits() - 1}; 6300 } 6301 6302 SDValue AArch64TargetLowering::LowerBR_CC(SDValue Op, SelectionDAG &DAG) const { 6303 SDValue Chain = Op.getOperand(0); 6304 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(1))->get(); 6305 SDValue LHS = Op.getOperand(2); 6306 SDValue RHS = Op.getOperand(3); 6307 SDValue Dest = Op.getOperand(4); 6308 SDLoc dl(Op); 6309 6310 MachineFunction &MF = DAG.getMachineFunction(); 6311 // Speculation tracking/SLH assumes that optimized TB(N)Z/CB(N)Z instructions 6312 // will not be produced, as they are conditional branch instructions that do 6313 // not set flags. 6314 bool ProduceNonFlagSettingCondBr = 6315 !MF.getFunction().hasFnAttribute(Attribute::SpeculativeLoadHardening); 6316 6317 // Handle f128 first, since lowering it will result in comparing the return 6318 // value of a libcall against zero, which is just what the rest of LowerBR_CC 6319 // is expecting to deal with. 6320 if (LHS.getValueType() == MVT::f128) { 6321 softenSetCCOperands(DAG, MVT::f128, LHS, RHS, CC, dl, LHS, RHS); 6322 6323 // If softenSetCCOperands returned a scalar, we need to compare the result 6324 // against zero to select between true and false values. 6325 if (!RHS.getNode()) { 6326 RHS = DAG.getConstant(0, dl, LHS.getValueType()); 6327 CC = ISD::SETNE; 6328 } 6329 } 6330 6331 // Optimize {s|u}{add|sub|mul}.with.overflow feeding into a branch 6332 // instruction. 6333 if (ISD::isOverflowIntrOpRes(LHS) && isOneConstant(RHS) && 6334 (CC == ISD::SETEQ || CC == ISD::SETNE)) { 6335 // Only lower legal XALUO ops. 6336 if (!DAG.getTargetLoweringInfo().isTypeLegal(LHS->getValueType(0))) 6337 return SDValue(); 6338 6339 // The actual operation with overflow check. 6340 AArch64CC::CondCode OFCC; 6341 SDValue Value, Overflow; 6342 std::tie(Value, Overflow) = getAArch64XALUOOp(OFCC, LHS.getValue(0), DAG); 6343 6344 if (CC == ISD::SETNE) 6345 OFCC = getInvertedCondCode(OFCC); 6346 SDValue CCVal = DAG.getConstant(OFCC, dl, MVT::i32); 6347 6348 return DAG.getNode(AArch64ISD::BRCOND, dl, MVT::Other, Chain, Dest, CCVal, 6349 Overflow); 6350 } 6351 6352 if (LHS.getValueType().isInteger()) { 6353 assert((LHS.getValueType() == RHS.getValueType()) && 6354 (LHS.getValueType() == MVT::i32 || LHS.getValueType() == MVT::i64)); 6355 6356 // If the RHS of the comparison is zero, we can potentially fold this 6357 // to a specialized branch. 6358 const ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS); 6359 if (RHSC && RHSC->getZExtValue() == 0 && ProduceNonFlagSettingCondBr) { 6360 if (CC == ISD::SETEQ) { 6361 // See if we can use a TBZ to fold in an AND as well. 6362 // TBZ has a smaller branch displacement than CBZ. If the offset is 6363 // out of bounds, a late MI-layer pass rewrites branches. 6364 // 403.gcc is an example that hits this case. 6365 if (LHS.getOpcode() == ISD::AND && 6366 isa<ConstantSDNode>(LHS.getOperand(1)) && 6367 isPowerOf2_64(LHS.getConstantOperandVal(1))) { 6368 SDValue Test = LHS.getOperand(0); 6369 uint64_t Mask = LHS.getConstantOperandVal(1); 6370 return DAG.getNode(AArch64ISD::TBZ, dl, MVT::Other, Chain, Test, 6371 DAG.getConstant(Log2_64(Mask), dl, MVT::i64), 6372 Dest); 6373 } 6374 6375 return DAG.getNode(AArch64ISD::CBZ, dl, MVT::Other, Chain, LHS, Dest); 6376 } else if (CC == ISD::SETNE) { 6377 // See if we can use a TBZ to fold in an AND as well. 6378 // TBZ has a smaller branch displacement than CBZ. If the offset is 6379 // out of bounds, a late MI-layer pass rewrites branches. 6380 // 403.gcc is an example that hits this case. 6381 if (LHS.getOpcode() == ISD::AND && 6382 isa<ConstantSDNode>(LHS.getOperand(1)) && 6383 isPowerOf2_64(LHS.getConstantOperandVal(1))) { 6384 SDValue Test = LHS.getOperand(0); 6385 uint64_t Mask = LHS.getConstantOperandVal(1); 6386 return DAG.getNode(AArch64ISD::TBNZ, dl, MVT::Other, Chain, Test, 6387 DAG.getConstant(Log2_64(Mask), dl, MVT::i64), 6388 Dest); 6389 } 6390 6391 return DAG.getNode(AArch64ISD::CBNZ, dl, MVT::Other, Chain, LHS, Dest); 6392 } else if (CC == ISD::SETLT && LHS.getOpcode() != ISD::AND) { 6393 // Don't combine AND since emitComparison converts the AND to an ANDS 6394 // (a.k.a. TST) and the test in the test bit and branch instruction 6395 // becomes redundant. This would also increase register pressure. 6396 uint64_t SignBitPos; 6397 std::tie(LHS, SignBitPos) = lookThroughSignExtension(LHS); 6398 return DAG.getNode(AArch64ISD::TBNZ, dl, MVT::Other, Chain, LHS, 6399 DAG.getConstant(SignBitPos, dl, MVT::i64), Dest); 6400 } 6401 } 6402 if (RHSC && RHSC->getSExtValue() == -1 && CC == ISD::SETGT && 6403 LHS.getOpcode() != ISD::AND && ProduceNonFlagSettingCondBr) { 6404 // Don't combine AND since emitComparison converts the AND to an ANDS 6405 // (a.k.a. TST) and the test in the test bit and branch instruction 6406 // becomes redundant. This would also increase register pressure. 6407 uint64_t SignBitPos; 6408 std::tie(LHS, SignBitPos) = lookThroughSignExtension(LHS); 6409 return DAG.getNode(AArch64ISD::TBZ, dl, MVT::Other, Chain, LHS, 6410 DAG.getConstant(SignBitPos, dl, MVT::i64), Dest); 6411 } 6412 6413 SDValue CCVal; 6414 SDValue Cmp = getAArch64Cmp(LHS, RHS, CC, CCVal, DAG, dl); 6415 return DAG.getNode(AArch64ISD::BRCOND, dl, MVT::Other, Chain, Dest, CCVal, 6416 Cmp); 6417 } 6418 6419 assert(LHS.getValueType() == MVT::f16 || LHS.getValueType() == MVT::bf16 || 6420 LHS.getValueType() == MVT::f32 || LHS.getValueType() == MVT::f64); 6421 6422 // Unfortunately, the mapping of LLVM FP CC's onto AArch64 CC's isn't totally 6423 // clean. Some of them require two branches to implement. 6424 SDValue Cmp = emitComparison(LHS, RHS, CC, dl, DAG); 6425 AArch64CC::CondCode CC1, CC2; 6426 changeFPCCToAArch64CC(CC, CC1, CC2); 6427 SDValue CC1Val = DAG.getConstant(CC1, dl, MVT::i32); 6428 SDValue BR1 = 6429 DAG.getNode(AArch64ISD::BRCOND, dl, MVT::Other, Chain, Dest, CC1Val, Cmp); 6430 if (CC2 != AArch64CC::AL) { 6431 SDValue CC2Val = DAG.getConstant(CC2, dl, MVT::i32); 6432 return DAG.getNode(AArch64ISD::BRCOND, dl, MVT::Other, BR1, Dest, CC2Val, 6433 Cmp); 6434 } 6435 6436 return BR1; 6437 } 6438 6439 SDValue AArch64TargetLowering::LowerFCOPYSIGN(SDValue Op, 6440 SelectionDAG &DAG) const { 6441 EVT VT = Op.getValueType(); 6442 SDLoc DL(Op); 6443 6444 SDValue In1 = Op.getOperand(0); 6445 SDValue In2 = Op.getOperand(1); 6446 EVT SrcVT = In2.getValueType(); 6447 6448 if (SrcVT.bitsLT(VT)) 6449 In2 = DAG.getNode(ISD::FP_EXTEND, DL, VT, In2); 6450 else if (SrcVT.bitsGT(VT)) 6451 In2 = DAG.getNode(ISD::FP_ROUND, DL, VT, In2, DAG.getIntPtrConstant(0, DL)); 6452 6453 EVT VecVT; 6454 uint64_t EltMask; 6455 SDValue VecVal1, VecVal2; 6456 6457 auto setVecVal = [&] (int Idx) { 6458 if (!VT.isVector()) { 6459 VecVal1 = DAG.getTargetInsertSubreg(Idx, DL, VecVT, 6460 DAG.getUNDEF(VecVT), In1); 6461 VecVal2 = DAG.getTargetInsertSubreg(Idx, DL, VecVT, 6462 DAG.getUNDEF(VecVT), In2); 6463 } else { 6464 VecVal1 = DAG.getNode(ISD::BITCAST, DL, VecVT, In1); 6465 VecVal2 = DAG.getNode(ISD::BITCAST, DL, VecVT, In2); 6466 } 6467 }; 6468 6469 if (VT == MVT::f32 || VT == MVT::v2f32 || VT == MVT::v4f32) { 6470 VecVT = (VT == MVT::v2f32 ? MVT::v2i32 : MVT::v4i32); 6471 EltMask = 0x80000000ULL; 6472 setVecVal(AArch64::ssub); 6473 } else if (VT == MVT::f64 || VT == MVT::v2f64) { 6474 VecVT = MVT::v2i64; 6475 6476 // We want to materialize a mask with the high bit set, but the AdvSIMD 6477 // immediate moves cannot materialize that in a single instruction for 6478 // 64-bit elements. Instead, materialize zero and then negate it. 6479 EltMask = 0; 6480 6481 setVecVal(AArch64::dsub); 6482 } else if (VT == MVT::f16 || VT == MVT::v4f16 || VT == MVT::v8f16) { 6483 VecVT = (VT == MVT::v4f16 ? MVT::v4i16 : MVT::v8i16); 6484 EltMask = 0x8000ULL; 6485 setVecVal(AArch64::hsub); 6486 } else { 6487 llvm_unreachable("Invalid type for copysign!"); 6488 } 6489 6490 SDValue BuildVec = DAG.getConstant(EltMask, DL, VecVT); 6491 6492 // If we couldn't materialize the mask above, then the mask vector will be 6493 // the zero vector, and we need to negate it here. 6494 if (VT == MVT::f64 || VT == MVT::v2f64) { 6495 BuildVec = DAG.getNode(ISD::BITCAST, DL, MVT::v2f64, BuildVec); 6496 BuildVec = DAG.getNode(ISD::FNEG, DL, MVT::v2f64, BuildVec); 6497 BuildVec = DAG.getNode(ISD::BITCAST, DL, MVT::v2i64, BuildVec); 6498 } 6499 6500 SDValue Sel = 6501 DAG.getNode(AArch64ISD::BIT, DL, VecVT, VecVal1, VecVal2, BuildVec); 6502 6503 if (VT == MVT::f16) 6504 return DAG.getTargetExtractSubreg(AArch64::hsub, DL, VT, Sel); 6505 if (VT == MVT::f32) 6506 return DAG.getTargetExtractSubreg(AArch64::ssub, DL, VT, Sel); 6507 else if (VT == MVT::f64) 6508 return DAG.getTargetExtractSubreg(AArch64::dsub, DL, VT, Sel); 6509 else 6510 return DAG.getNode(ISD::BITCAST, DL, VT, Sel); 6511 } 6512 6513 SDValue AArch64TargetLowering::LowerCTPOP(SDValue Op, SelectionDAG &DAG) const { 6514 if (DAG.getMachineFunction().getFunction().hasFnAttribute( 6515 Attribute::NoImplicitFloat)) 6516 return SDValue(); 6517 6518 if (!Subtarget->hasNEON()) 6519 return SDValue(); 6520 6521 // While there is no integer popcount instruction, it can 6522 // be more efficiently lowered to the following sequence that uses 6523 // AdvSIMD registers/instructions as long as the copies to/from 6524 // the AdvSIMD registers are cheap. 6525 // FMOV D0, X0 // copy 64-bit int to vector, high bits zero'd 6526 // CNT V0.8B, V0.8B // 8xbyte pop-counts 6527 // ADDV B0, V0.8B // sum 8xbyte pop-counts 6528 // UMOV X0, V0.B[0] // copy byte result back to integer reg 6529 SDValue Val = Op.getOperand(0); 6530 SDLoc DL(Op); 6531 EVT VT = Op.getValueType(); 6532 6533 if (VT == MVT::i32 || VT == MVT::i64) { 6534 if (VT == MVT::i32) 6535 Val = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i64, Val); 6536 Val = DAG.getNode(ISD::BITCAST, DL, MVT::v8i8, Val); 6537 6538 SDValue CtPop = DAG.getNode(ISD::CTPOP, DL, MVT::v8i8, Val); 6539 SDValue UaddLV = DAG.getNode( 6540 ISD::INTRINSIC_WO_CHAIN, DL, MVT::i32, 6541 DAG.getConstant(Intrinsic::aarch64_neon_uaddlv, DL, MVT::i32), CtPop); 6542 6543 if (VT == MVT::i64) 6544 UaddLV = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i64, UaddLV); 6545 return UaddLV; 6546 } else if (VT == MVT::i128) { 6547 Val = DAG.getNode(ISD::BITCAST, DL, MVT::v16i8, Val); 6548 6549 SDValue CtPop = DAG.getNode(ISD::CTPOP, DL, MVT::v16i8, Val); 6550 SDValue UaddLV = DAG.getNode( 6551 ISD::INTRINSIC_WO_CHAIN, DL, MVT::i32, 6552 DAG.getConstant(Intrinsic::aarch64_neon_uaddlv, DL, MVT::i32), CtPop); 6553 6554 return DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i128, UaddLV); 6555 } 6556 6557 if (VT.isScalableVector() || useSVEForFixedLengthVectorVT(VT)) 6558 return LowerToPredicatedOp(Op, DAG, AArch64ISD::CTPOP_MERGE_PASSTHRU); 6559 6560 assert((VT == MVT::v1i64 || VT == MVT::v2i64 || VT == MVT::v2i32 || 6561 VT == MVT::v4i32 || VT == MVT::v4i16 || VT == MVT::v8i16) && 6562 "Unexpected type for custom ctpop lowering"); 6563 6564 EVT VT8Bit = VT.is64BitVector() ? MVT::v8i8 : MVT::v16i8; 6565 Val = DAG.getBitcast(VT8Bit, Val); 6566 Val = DAG.getNode(ISD::CTPOP, DL, VT8Bit, Val); 6567 6568 // Widen v8i8/v16i8 CTPOP result to VT by repeatedly widening pairwise adds. 6569 unsigned EltSize = 8; 6570 unsigned NumElts = VT.is64BitVector() ? 8 : 16; 6571 while (EltSize != VT.getScalarSizeInBits()) { 6572 EltSize *= 2; 6573 NumElts /= 2; 6574 MVT WidenVT = MVT::getVectorVT(MVT::getIntegerVT(EltSize), NumElts); 6575 Val = DAG.getNode( 6576 ISD::INTRINSIC_WO_CHAIN, DL, WidenVT, 6577 DAG.getConstant(Intrinsic::aarch64_neon_uaddlp, DL, MVT::i32), Val); 6578 } 6579 6580 return Val; 6581 } 6582 6583 SDValue AArch64TargetLowering::LowerCTTZ(SDValue Op, SelectionDAG &DAG) const { 6584 EVT VT = Op.getValueType(); 6585 assert(VT.isScalableVector() || 6586 useSVEForFixedLengthVectorVT(VT, /*OverrideNEON=*/true)); 6587 6588 SDLoc DL(Op); 6589 SDValue RBIT = DAG.getNode(ISD::BITREVERSE, DL, VT, Op.getOperand(0)); 6590 return DAG.getNode(ISD::CTLZ, DL, VT, RBIT); 6591 } 6592 6593 SDValue AArch64TargetLowering::LowerSETCC(SDValue Op, SelectionDAG &DAG) const { 6594 6595 if (Op.getValueType().isVector()) 6596 return LowerVSETCC(Op, DAG); 6597 6598 bool IsStrict = Op->isStrictFPOpcode(); 6599 bool IsSignaling = Op.getOpcode() == ISD::STRICT_FSETCCS; 6600 unsigned OpNo = IsStrict ? 1 : 0; 6601 SDValue Chain; 6602 if (IsStrict) 6603 Chain = Op.getOperand(0); 6604 SDValue LHS = Op.getOperand(OpNo + 0); 6605 SDValue RHS = Op.getOperand(OpNo + 1); 6606 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(OpNo + 2))->get(); 6607 SDLoc dl(Op); 6608 6609 // We chose ZeroOrOneBooleanContents, so use zero and one. 6610 EVT VT = Op.getValueType(); 6611 SDValue TVal = DAG.getConstant(1, dl, VT); 6612 SDValue FVal = DAG.getConstant(0, dl, VT); 6613 6614 // Handle f128 first, since one possible outcome is a normal integer 6615 // comparison which gets picked up by the next if statement. 6616 if (LHS.getValueType() == MVT::f128) { 6617 softenSetCCOperands(DAG, MVT::f128, LHS, RHS, CC, dl, LHS, RHS, Chain, 6618 IsSignaling); 6619 6620 // If softenSetCCOperands returned a scalar, use it. 6621 if (!RHS.getNode()) { 6622 assert(LHS.getValueType() == Op.getValueType() && 6623 "Unexpected setcc expansion!"); 6624 return IsStrict ? DAG.getMergeValues({LHS, Chain}, dl) : LHS; 6625 } 6626 } 6627 6628 if (LHS.getValueType().isInteger()) { 6629 SDValue CCVal; 6630 SDValue Cmp = getAArch64Cmp( 6631 LHS, RHS, ISD::getSetCCInverse(CC, LHS.getValueType()), CCVal, DAG, dl); 6632 6633 // Note that we inverted the condition above, so we reverse the order of 6634 // the true and false operands here. This will allow the setcc to be 6635 // matched to a single CSINC instruction. 6636 SDValue Res = DAG.getNode(AArch64ISD::CSEL, dl, VT, FVal, TVal, CCVal, Cmp); 6637 return IsStrict ? DAG.getMergeValues({Res, Chain}, dl) : Res; 6638 } 6639 6640 // Now we know we're dealing with FP values. 6641 assert(LHS.getValueType() == MVT::f16 || LHS.getValueType() == MVT::f32 || 6642 LHS.getValueType() == MVT::f64); 6643 6644 // If that fails, we'll need to perform an FCMP + CSEL sequence. Go ahead 6645 // and do the comparison. 6646 SDValue Cmp; 6647 if (IsStrict) 6648 Cmp = emitStrictFPComparison(LHS, RHS, dl, DAG, Chain, IsSignaling); 6649 else 6650 Cmp = emitComparison(LHS, RHS, CC, dl, DAG); 6651 6652 AArch64CC::CondCode CC1, CC2; 6653 changeFPCCToAArch64CC(CC, CC1, CC2); 6654 SDValue Res; 6655 if (CC2 == AArch64CC::AL) { 6656 changeFPCCToAArch64CC(ISD::getSetCCInverse(CC, LHS.getValueType()), CC1, 6657 CC2); 6658 SDValue CC1Val = DAG.getConstant(CC1, dl, MVT::i32); 6659 6660 // Note that we inverted the condition above, so we reverse the order of 6661 // the true and false operands here. This will allow the setcc to be 6662 // matched to a single CSINC instruction. 6663 Res = DAG.getNode(AArch64ISD::CSEL, dl, VT, FVal, TVal, CC1Val, Cmp); 6664 } else { 6665 // Unfortunately, the mapping of LLVM FP CC's onto AArch64 CC's isn't 6666 // totally clean. Some of them require two CSELs to implement. As is in 6667 // this case, we emit the first CSEL and then emit a second using the output 6668 // of the first as the RHS. We're effectively OR'ing the two CC's together. 6669 6670 // FIXME: It would be nice if we could match the two CSELs to two CSINCs. 6671 SDValue CC1Val = DAG.getConstant(CC1, dl, MVT::i32); 6672 SDValue CS1 = 6673 DAG.getNode(AArch64ISD::CSEL, dl, VT, TVal, FVal, CC1Val, Cmp); 6674 6675 SDValue CC2Val = DAG.getConstant(CC2, dl, MVT::i32); 6676 Res = DAG.getNode(AArch64ISD::CSEL, dl, VT, TVal, CS1, CC2Val, Cmp); 6677 } 6678 return IsStrict ? DAG.getMergeValues({Res, Cmp.getValue(1)}, dl) : Res; 6679 } 6680 6681 SDValue AArch64TargetLowering::LowerSELECT_CC(ISD::CondCode CC, SDValue LHS, 6682 SDValue RHS, SDValue TVal, 6683 SDValue FVal, const SDLoc &dl, 6684 SelectionDAG &DAG) const { 6685 // Handle f128 first, because it will result in a comparison of some RTLIB 6686 // call result against zero. 6687 if (LHS.getValueType() == MVT::f128) { 6688 softenSetCCOperands(DAG, MVT::f128, LHS, RHS, CC, dl, LHS, RHS); 6689 6690 // If softenSetCCOperands returned a scalar, we need to compare the result 6691 // against zero to select between true and false values. 6692 if (!RHS.getNode()) { 6693 RHS = DAG.getConstant(0, dl, LHS.getValueType()); 6694 CC = ISD::SETNE; 6695 } 6696 } 6697 6698 // Also handle f16, for which we need to do a f32 comparison. 6699 if (LHS.getValueType() == MVT::f16 && !Subtarget->hasFullFP16()) { 6700 LHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f32, LHS); 6701 RHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f32, RHS); 6702 } 6703 6704 // Next, handle integers. 6705 if (LHS.getValueType().isInteger()) { 6706 assert((LHS.getValueType() == RHS.getValueType()) && 6707 (LHS.getValueType() == MVT::i32 || LHS.getValueType() == MVT::i64)); 6708 6709 unsigned Opcode = AArch64ISD::CSEL; 6710 6711 // If both the TVal and the FVal are constants, see if we can swap them in 6712 // order to for a CSINV or CSINC out of them. 6713 ConstantSDNode *CFVal = dyn_cast<ConstantSDNode>(FVal); 6714 ConstantSDNode *CTVal = dyn_cast<ConstantSDNode>(TVal); 6715 6716 if (CTVal && CFVal && CTVal->isAllOnesValue() && CFVal->isNullValue()) { 6717 std::swap(TVal, FVal); 6718 std::swap(CTVal, CFVal); 6719 CC = ISD::getSetCCInverse(CC, LHS.getValueType()); 6720 } else if (CTVal && CFVal && CTVal->isOne() && CFVal->isNullValue()) { 6721 std::swap(TVal, FVal); 6722 std::swap(CTVal, CFVal); 6723 CC = ISD::getSetCCInverse(CC, LHS.getValueType()); 6724 } else if (TVal.getOpcode() == ISD::XOR) { 6725 // If TVal is a NOT we want to swap TVal and FVal so that we can match 6726 // with a CSINV rather than a CSEL. 6727 if (isAllOnesConstant(TVal.getOperand(1))) { 6728 std::swap(TVal, FVal); 6729 std::swap(CTVal, CFVal); 6730 CC = ISD::getSetCCInverse(CC, LHS.getValueType()); 6731 } 6732 } else if (TVal.getOpcode() == ISD::SUB) { 6733 // If TVal is a negation (SUB from 0) we want to swap TVal and FVal so 6734 // that we can match with a CSNEG rather than a CSEL. 6735 if (isNullConstant(TVal.getOperand(0))) { 6736 std::swap(TVal, FVal); 6737 std::swap(CTVal, CFVal); 6738 CC = ISD::getSetCCInverse(CC, LHS.getValueType()); 6739 } 6740 } else if (CTVal && CFVal) { 6741 const int64_t TrueVal = CTVal->getSExtValue(); 6742 const int64_t FalseVal = CFVal->getSExtValue(); 6743 bool Swap = false; 6744 6745 // If both TVal and FVal are constants, see if FVal is the 6746 // inverse/negation/increment of TVal and generate a CSINV/CSNEG/CSINC 6747 // instead of a CSEL in that case. 6748 if (TrueVal == ~FalseVal) { 6749 Opcode = AArch64ISD::CSINV; 6750 } else if (FalseVal > std::numeric_limits<int64_t>::min() && 6751 TrueVal == -FalseVal) { 6752 Opcode = AArch64ISD::CSNEG; 6753 } else if (TVal.getValueType() == MVT::i32) { 6754 // If our operands are only 32-bit wide, make sure we use 32-bit 6755 // arithmetic for the check whether we can use CSINC. This ensures that 6756 // the addition in the check will wrap around properly in case there is 6757 // an overflow (which would not be the case if we do the check with 6758 // 64-bit arithmetic). 6759 const uint32_t TrueVal32 = CTVal->getZExtValue(); 6760 const uint32_t FalseVal32 = CFVal->getZExtValue(); 6761 6762 if ((TrueVal32 == FalseVal32 + 1) || (TrueVal32 + 1 == FalseVal32)) { 6763 Opcode = AArch64ISD::CSINC; 6764 6765 if (TrueVal32 > FalseVal32) { 6766 Swap = true; 6767 } 6768 } 6769 // 64-bit check whether we can use CSINC. 6770 } else if ((TrueVal == FalseVal + 1) || (TrueVal + 1 == FalseVal)) { 6771 Opcode = AArch64ISD::CSINC; 6772 6773 if (TrueVal > FalseVal) { 6774 Swap = true; 6775 } 6776 } 6777 6778 // Swap TVal and FVal if necessary. 6779 if (Swap) { 6780 std::swap(TVal, FVal); 6781 std::swap(CTVal, CFVal); 6782 CC = ISD::getSetCCInverse(CC, LHS.getValueType()); 6783 } 6784 6785 if (Opcode != AArch64ISD::CSEL) { 6786 // Drop FVal since we can get its value by simply inverting/negating 6787 // TVal. 6788 FVal = TVal; 6789 } 6790 } 6791 6792 // Avoid materializing a constant when possible by reusing a known value in 6793 // a register. However, don't perform this optimization if the known value 6794 // is one, zero or negative one in the case of a CSEL. We can always 6795 // materialize these values using CSINC, CSEL and CSINV with wzr/xzr as the 6796 // FVal, respectively. 6797 ConstantSDNode *RHSVal = dyn_cast<ConstantSDNode>(RHS); 6798 if (Opcode == AArch64ISD::CSEL && RHSVal && !RHSVal->isOne() && 6799 !RHSVal->isNullValue() && !RHSVal->isAllOnesValue()) { 6800 AArch64CC::CondCode AArch64CC = changeIntCCToAArch64CC(CC); 6801 // Transform "a == C ? C : x" to "a == C ? a : x" and "a != C ? x : C" to 6802 // "a != C ? x : a" to avoid materializing C. 6803 if (CTVal && CTVal == RHSVal && AArch64CC == AArch64CC::EQ) 6804 TVal = LHS; 6805 else if (CFVal && CFVal == RHSVal && AArch64CC == AArch64CC::NE) 6806 FVal = LHS; 6807 } else if (Opcode == AArch64ISD::CSNEG && RHSVal && RHSVal->isOne()) { 6808 assert (CTVal && CFVal && "Expected constant operands for CSNEG."); 6809 // Use a CSINV to transform "a == C ? 1 : -1" to "a == C ? a : -1" to 6810 // avoid materializing C. 6811 AArch64CC::CondCode AArch64CC = changeIntCCToAArch64CC(CC); 6812 if (CTVal == RHSVal && AArch64CC == AArch64CC::EQ) { 6813 Opcode = AArch64ISD::CSINV; 6814 TVal = LHS; 6815 FVal = DAG.getConstant(0, dl, FVal.getValueType()); 6816 } 6817 } 6818 6819 SDValue CCVal; 6820 SDValue Cmp = getAArch64Cmp(LHS, RHS, CC, CCVal, DAG, dl); 6821 EVT VT = TVal.getValueType(); 6822 return DAG.getNode(Opcode, dl, VT, TVal, FVal, CCVal, Cmp); 6823 } 6824 6825 // Now we know we're dealing with FP values. 6826 assert(LHS.getValueType() == MVT::f16 || LHS.getValueType() == MVT::f32 || 6827 LHS.getValueType() == MVT::f64); 6828 assert(LHS.getValueType() == RHS.getValueType()); 6829 EVT VT = TVal.getValueType(); 6830 SDValue Cmp = emitComparison(LHS, RHS, CC, dl, DAG); 6831 6832 // Unfortunately, the mapping of LLVM FP CC's onto AArch64 CC's isn't totally 6833 // clean. Some of them require two CSELs to implement. 6834 AArch64CC::CondCode CC1, CC2; 6835 changeFPCCToAArch64CC(CC, CC1, CC2); 6836 6837 if (DAG.getTarget().Options.UnsafeFPMath) { 6838 // Transform "a == 0.0 ? 0.0 : x" to "a == 0.0 ? a : x" and 6839 // "a != 0.0 ? x : 0.0" to "a != 0.0 ? x : a" to avoid materializing 0.0. 6840 ConstantFPSDNode *RHSVal = dyn_cast<ConstantFPSDNode>(RHS); 6841 if (RHSVal && RHSVal->isZero()) { 6842 ConstantFPSDNode *CFVal = dyn_cast<ConstantFPSDNode>(FVal); 6843 ConstantFPSDNode *CTVal = dyn_cast<ConstantFPSDNode>(TVal); 6844 6845 if ((CC == ISD::SETEQ || CC == ISD::SETOEQ || CC == ISD::SETUEQ) && 6846 CTVal && CTVal->isZero() && TVal.getValueType() == LHS.getValueType()) 6847 TVal = LHS; 6848 else if ((CC == ISD::SETNE || CC == ISD::SETONE || CC == ISD::SETUNE) && 6849 CFVal && CFVal->isZero() && 6850 FVal.getValueType() == LHS.getValueType()) 6851 FVal = LHS; 6852 } 6853 } 6854 6855 // Emit first, and possibly only, CSEL. 6856 SDValue CC1Val = DAG.getConstant(CC1, dl, MVT::i32); 6857 SDValue CS1 = DAG.getNode(AArch64ISD::CSEL, dl, VT, TVal, FVal, CC1Val, Cmp); 6858 6859 // If we need a second CSEL, emit it, using the output of the first as the 6860 // RHS. We're effectively OR'ing the two CC's together. 6861 if (CC2 != AArch64CC::AL) { 6862 SDValue CC2Val = DAG.getConstant(CC2, dl, MVT::i32); 6863 return DAG.getNode(AArch64ISD::CSEL, dl, VT, TVal, CS1, CC2Val, Cmp); 6864 } 6865 6866 // Otherwise, return the output of the first CSEL. 6867 return CS1; 6868 } 6869 6870 SDValue AArch64TargetLowering::LowerSELECT_CC(SDValue Op, 6871 SelectionDAG &DAG) const { 6872 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(4))->get(); 6873 SDValue LHS = Op.getOperand(0); 6874 SDValue RHS = Op.getOperand(1); 6875 SDValue TVal = Op.getOperand(2); 6876 SDValue FVal = Op.getOperand(3); 6877 SDLoc DL(Op); 6878 return LowerSELECT_CC(CC, LHS, RHS, TVal, FVal, DL, DAG); 6879 } 6880 6881 SDValue AArch64TargetLowering::LowerSELECT(SDValue Op, 6882 SelectionDAG &DAG) const { 6883 SDValue CCVal = Op->getOperand(0); 6884 SDValue TVal = Op->getOperand(1); 6885 SDValue FVal = Op->getOperand(2); 6886 SDLoc DL(Op); 6887 6888 EVT Ty = Op.getValueType(); 6889 if (Ty.isScalableVector()) { 6890 SDValue TruncCC = DAG.getNode(ISD::TRUNCATE, DL, MVT::i1, CCVal); 6891 MVT PredVT = MVT::getVectorVT(MVT::i1, Ty.getVectorElementCount()); 6892 SDValue SplatPred = DAG.getNode(ISD::SPLAT_VECTOR, DL, PredVT, TruncCC); 6893 return DAG.getNode(ISD::VSELECT, DL, Ty, SplatPred, TVal, FVal); 6894 } 6895 6896 // Optimize {s|u}{add|sub|mul}.with.overflow feeding into a select 6897 // instruction. 6898 if (ISD::isOverflowIntrOpRes(CCVal)) { 6899 // Only lower legal XALUO ops. 6900 if (!DAG.getTargetLoweringInfo().isTypeLegal(CCVal->getValueType(0))) 6901 return SDValue(); 6902 6903 AArch64CC::CondCode OFCC; 6904 SDValue Value, Overflow; 6905 std::tie(Value, Overflow) = getAArch64XALUOOp(OFCC, CCVal.getValue(0), DAG); 6906 SDValue CCVal = DAG.getConstant(OFCC, DL, MVT::i32); 6907 6908 return DAG.getNode(AArch64ISD::CSEL, DL, Op.getValueType(), TVal, FVal, 6909 CCVal, Overflow); 6910 } 6911 6912 // Lower it the same way as we would lower a SELECT_CC node. 6913 ISD::CondCode CC; 6914 SDValue LHS, RHS; 6915 if (CCVal.getOpcode() == ISD::SETCC) { 6916 LHS = CCVal.getOperand(0); 6917 RHS = CCVal.getOperand(1); 6918 CC = cast<CondCodeSDNode>(CCVal->getOperand(2))->get(); 6919 } else { 6920 LHS = CCVal; 6921 RHS = DAG.getConstant(0, DL, CCVal.getValueType()); 6922 CC = ISD::SETNE; 6923 } 6924 return LowerSELECT_CC(CC, LHS, RHS, TVal, FVal, DL, DAG); 6925 } 6926 6927 SDValue AArch64TargetLowering::LowerJumpTable(SDValue Op, 6928 SelectionDAG &DAG) const { 6929 // Jump table entries as PC relative offsets. No additional tweaking 6930 // is necessary here. Just get the address of the jump table. 6931 JumpTableSDNode *JT = cast<JumpTableSDNode>(Op); 6932 6933 if (getTargetMachine().getCodeModel() == CodeModel::Large && 6934 !Subtarget->isTargetMachO()) { 6935 return getAddrLarge(JT, DAG); 6936 } else if (getTargetMachine().getCodeModel() == CodeModel::Tiny) { 6937 return getAddrTiny(JT, DAG); 6938 } 6939 return getAddr(JT, DAG); 6940 } 6941 6942 SDValue AArch64TargetLowering::LowerBR_JT(SDValue Op, 6943 SelectionDAG &DAG) const { 6944 // Jump table entries as PC relative offsets. No additional tweaking 6945 // is necessary here. Just get the address of the jump table. 6946 SDLoc DL(Op); 6947 SDValue JT = Op.getOperand(1); 6948 SDValue Entry = Op.getOperand(2); 6949 int JTI = cast<JumpTableSDNode>(JT.getNode())->getIndex(); 6950 6951 auto *AFI = DAG.getMachineFunction().getInfo<AArch64FunctionInfo>(); 6952 AFI->setJumpTableEntryInfo(JTI, 4, nullptr); 6953 6954 SDNode *Dest = 6955 DAG.getMachineNode(AArch64::JumpTableDest32, DL, MVT::i64, MVT::i64, JT, 6956 Entry, DAG.getTargetJumpTable(JTI, MVT::i32)); 6957 return DAG.getNode(ISD::BRIND, DL, MVT::Other, Op.getOperand(0), 6958 SDValue(Dest, 0)); 6959 } 6960 6961 SDValue AArch64TargetLowering::LowerConstantPool(SDValue Op, 6962 SelectionDAG &DAG) const { 6963 ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op); 6964 6965 if (getTargetMachine().getCodeModel() == CodeModel::Large) { 6966 // Use the GOT for the large code model on iOS. 6967 if (Subtarget->isTargetMachO()) { 6968 return getGOT(CP, DAG); 6969 } 6970 return getAddrLarge(CP, DAG); 6971 } else if (getTargetMachine().getCodeModel() == CodeModel::Tiny) { 6972 return getAddrTiny(CP, DAG); 6973 } else { 6974 return getAddr(CP, DAG); 6975 } 6976 } 6977 6978 SDValue AArch64TargetLowering::LowerBlockAddress(SDValue Op, 6979 SelectionDAG &DAG) const { 6980 BlockAddressSDNode *BA = cast<BlockAddressSDNode>(Op); 6981 if (getTargetMachine().getCodeModel() == CodeModel::Large && 6982 !Subtarget->isTargetMachO()) { 6983 return getAddrLarge(BA, DAG); 6984 } else if (getTargetMachine().getCodeModel() == CodeModel::Tiny) { 6985 return getAddrTiny(BA, DAG); 6986 } 6987 return getAddr(BA, DAG); 6988 } 6989 6990 SDValue AArch64TargetLowering::LowerDarwin_VASTART(SDValue Op, 6991 SelectionDAG &DAG) const { 6992 AArch64FunctionInfo *FuncInfo = 6993 DAG.getMachineFunction().getInfo<AArch64FunctionInfo>(); 6994 6995 SDLoc DL(Op); 6996 SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsStackIndex(), 6997 getPointerTy(DAG.getDataLayout())); 6998 FR = DAG.getZExtOrTrunc(FR, DL, getPointerMemTy(DAG.getDataLayout())); 6999 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue(); 7000 return DAG.getStore(Op.getOperand(0), DL, FR, Op.getOperand(1), 7001 MachinePointerInfo(SV)); 7002 } 7003 7004 SDValue AArch64TargetLowering::LowerWin64_VASTART(SDValue Op, 7005 SelectionDAG &DAG) const { 7006 AArch64FunctionInfo *FuncInfo = 7007 DAG.getMachineFunction().getInfo<AArch64FunctionInfo>(); 7008 7009 SDLoc DL(Op); 7010 SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsGPRSize() > 0 7011 ? FuncInfo->getVarArgsGPRIndex() 7012 : FuncInfo->getVarArgsStackIndex(), 7013 getPointerTy(DAG.getDataLayout())); 7014 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue(); 7015 return DAG.getStore(Op.getOperand(0), DL, FR, Op.getOperand(1), 7016 MachinePointerInfo(SV)); 7017 } 7018 7019 SDValue AArch64TargetLowering::LowerAAPCS_VASTART(SDValue Op, 7020 SelectionDAG &DAG) const { 7021 // The layout of the va_list struct is specified in the AArch64 Procedure Call 7022 // Standard, section B.3. 7023 MachineFunction &MF = DAG.getMachineFunction(); 7024 AArch64FunctionInfo *FuncInfo = MF.getInfo<AArch64FunctionInfo>(); 7025 unsigned PtrSize = Subtarget->isTargetILP32() ? 4 : 8; 7026 auto PtrMemVT = getPointerMemTy(DAG.getDataLayout()); 7027 auto PtrVT = getPointerTy(DAG.getDataLayout()); 7028 SDLoc DL(Op); 7029 7030 SDValue Chain = Op.getOperand(0); 7031 SDValue VAList = Op.getOperand(1); 7032 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue(); 7033 SmallVector<SDValue, 4> MemOps; 7034 7035 // void *__stack at offset 0 7036 unsigned Offset = 0; 7037 SDValue Stack = DAG.getFrameIndex(FuncInfo->getVarArgsStackIndex(), PtrVT); 7038 Stack = DAG.getZExtOrTrunc(Stack, DL, PtrMemVT); 7039 MemOps.push_back(DAG.getStore(Chain, DL, Stack, VAList, 7040 MachinePointerInfo(SV), Align(PtrSize))); 7041 7042 // void *__gr_top at offset 8 (4 on ILP32) 7043 Offset += PtrSize; 7044 int GPRSize = FuncInfo->getVarArgsGPRSize(); 7045 if (GPRSize > 0) { 7046 SDValue GRTop, GRTopAddr; 7047 7048 GRTopAddr = DAG.getNode(ISD::ADD, DL, PtrVT, VAList, 7049 DAG.getConstant(Offset, DL, PtrVT)); 7050 7051 GRTop = DAG.getFrameIndex(FuncInfo->getVarArgsGPRIndex(), PtrVT); 7052 GRTop = DAG.getNode(ISD::ADD, DL, PtrVT, GRTop, 7053 DAG.getConstant(GPRSize, DL, PtrVT)); 7054 GRTop = DAG.getZExtOrTrunc(GRTop, DL, PtrMemVT); 7055 7056 MemOps.push_back(DAG.getStore(Chain, DL, GRTop, GRTopAddr, 7057 MachinePointerInfo(SV, Offset), 7058 Align(PtrSize))); 7059 } 7060 7061 // void *__vr_top at offset 16 (8 on ILP32) 7062 Offset += PtrSize; 7063 int FPRSize = FuncInfo->getVarArgsFPRSize(); 7064 if (FPRSize > 0) { 7065 SDValue VRTop, VRTopAddr; 7066 VRTopAddr = DAG.getNode(ISD::ADD, DL, PtrVT, VAList, 7067 DAG.getConstant(Offset, DL, PtrVT)); 7068 7069 VRTop = DAG.getFrameIndex(FuncInfo->getVarArgsFPRIndex(), PtrVT); 7070 VRTop = DAG.getNode(ISD::ADD, DL, PtrVT, VRTop, 7071 DAG.getConstant(FPRSize, DL, PtrVT)); 7072 VRTop = DAG.getZExtOrTrunc(VRTop, DL, PtrMemVT); 7073 7074 MemOps.push_back(DAG.getStore(Chain, DL, VRTop, VRTopAddr, 7075 MachinePointerInfo(SV, Offset), 7076 Align(PtrSize))); 7077 } 7078 7079 // int __gr_offs at offset 24 (12 on ILP32) 7080 Offset += PtrSize; 7081 SDValue GROffsAddr = DAG.getNode(ISD::ADD, DL, PtrVT, VAList, 7082 DAG.getConstant(Offset, DL, PtrVT)); 7083 MemOps.push_back( 7084 DAG.getStore(Chain, DL, DAG.getConstant(-GPRSize, DL, MVT::i32), 7085 GROffsAddr, MachinePointerInfo(SV, Offset), Align(4))); 7086 7087 // int __vr_offs at offset 28 (16 on ILP32) 7088 Offset += 4; 7089 SDValue VROffsAddr = DAG.getNode(ISD::ADD, DL, PtrVT, VAList, 7090 DAG.getConstant(Offset, DL, PtrVT)); 7091 MemOps.push_back( 7092 DAG.getStore(Chain, DL, DAG.getConstant(-FPRSize, DL, MVT::i32), 7093 VROffsAddr, MachinePointerInfo(SV, Offset), Align(4))); 7094 7095 return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, MemOps); 7096 } 7097 7098 SDValue AArch64TargetLowering::LowerVASTART(SDValue Op, 7099 SelectionDAG &DAG) const { 7100 MachineFunction &MF = DAG.getMachineFunction(); 7101 7102 if (Subtarget->isCallingConvWin64(MF.getFunction().getCallingConv())) 7103 return LowerWin64_VASTART(Op, DAG); 7104 else if (Subtarget->isTargetDarwin()) 7105 return LowerDarwin_VASTART(Op, DAG); 7106 else 7107 return LowerAAPCS_VASTART(Op, DAG); 7108 } 7109 7110 SDValue AArch64TargetLowering::LowerVACOPY(SDValue Op, 7111 SelectionDAG &DAG) const { 7112 // AAPCS has three pointers and two ints (= 32 bytes), Darwin has single 7113 // pointer. 7114 SDLoc DL(Op); 7115 unsigned PtrSize = Subtarget->isTargetILP32() ? 4 : 8; 7116 unsigned VaListSize = 7117 (Subtarget->isTargetDarwin() || Subtarget->isTargetWindows()) 7118 ? PtrSize 7119 : Subtarget->isTargetILP32() ? 20 : 32; 7120 const Value *DestSV = cast<SrcValueSDNode>(Op.getOperand(3))->getValue(); 7121 const Value *SrcSV = cast<SrcValueSDNode>(Op.getOperand(4))->getValue(); 7122 7123 return DAG.getMemcpy(Op.getOperand(0), DL, Op.getOperand(1), Op.getOperand(2), 7124 DAG.getConstant(VaListSize, DL, MVT::i32), 7125 Align(PtrSize), false, false, false, 7126 MachinePointerInfo(DestSV), MachinePointerInfo(SrcSV)); 7127 } 7128 7129 SDValue AArch64TargetLowering::LowerVAARG(SDValue Op, SelectionDAG &DAG) const { 7130 assert(Subtarget->isTargetDarwin() && 7131 "automatic va_arg instruction only works on Darwin"); 7132 7133 const Value *V = cast<SrcValueSDNode>(Op.getOperand(2))->getValue(); 7134 EVT VT = Op.getValueType(); 7135 SDLoc DL(Op); 7136 SDValue Chain = Op.getOperand(0); 7137 SDValue Addr = Op.getOperand(1); 7138 MaybeAlign Align(Op.getConstantOperandVal(3)); 7139 unsigned MinSlotSize = Subtarget->isTargetILP32() ? 4 : 8; 7140 auto PtrVT = getPointerTy(DAG.getDataLayout()); 7141 auto PtrMemVT = getPointerMemTy(DAG.getDataLayout()); 7142 SDValue VAList = 7143 DAG.getLoad(PtrMemVT, DL, Chain, Addr, MachinePointerInfo(V)); 7144 Chain = VAList.getValue(1); 7145 VAList = DAG.getZExtOrTrunc(VAList, DL, PtrVT); 7146 7147 if (VT.isScalableVector()) 7148 report_fatal_error("Passing SVE types to variadic functions is " 7149 "currently not supported"); 7150 7151 if (Align && *Align > MinSlotSize) { 7152 VAList = DAG.getNode(ISD::ADD, DL, PtrVT, VAList, 7153 DAG.getConstant(Align->value() - 1, DL, PtrVT)); 7154 VAList = DAG.getNode(ISD::AND, DL, PtrVT, VAList, 7155 DAG.getConstant(-(int64_t)Align->value(), DL, PtrVT)); 7156 } 7157 7158 Type *ArgTy = VT.getTypeForEVT(*DAG.getContext()); 7159 unsigned ArgSize = DAG.getDataLayout().getTypeAllocSize(ArgTy); 7160 7161 // Scalar integer and FP values smaller than 64 bits are implicitly extended 7162 // up to 64 bits. At the very least, we have to increase the striding of the 7163 // vaargs list to match this, and for FP values we need to introduce 7164 // FP_ROUND nodes as well. 7165 if (VT.isInteger() && !VT.isVector()) 7166 ArgSize = std::max(ArgSize, MinSlotSize); 7167 bool NeedFPTrunc = false; 7168 if (VT.isFloatingPoint() && !VT.isVector() && VT != MVT::f64) { 7169 ArgSize = 8; 7170 NeedFPTrunc = true; 7171 } 7172 7173 // Increment the pointer, VAList, to the next vaarg 7174 SDValue VANext = DAG.getNode(ISD::ADD, DL, PtrVT, VAList, 7175 DAG.getConstant(ArgSize, DL, PtrVT)); 7176 VANext = DAG.getZExtOrTrunc(VANext, DL, PtrMemVT); 7177 7178 // Store the incremented VAList to the legalized pointer 7179 SDValue APStore = 7180 DAG.getStore(Chain, DL, VANext, Addr, MachinePointerInfo(V)); 7181 7182 // Load the actual argument out of the pointer VAList 7183 if (NeedFPTrunc) { 7184 // Load the value as an f64. 7185 SDValue WideFP = 7186 DAG.getLoad(MVT::f64, DL, APStore, VAList, MachinePointerInfo()); 7187 // Round the value down to an f32. 7188 SDValue NarrowFP = DAG.getNode(ISD::FP_ROUND, DL, VT, WideFP.getValue(0), 7189 DAG.getIntPtrConstant(1, DL)); 7190 SDValue Ops[] = { NarrowFP, WideFP.getValue(1) }; 7191 // Merge the rounded value with the chain output of the load. 7192 return DAG.getMergeValues(Ops, DL); 7193 } 7194 7195 return DAG.getLoad(VT, DL, APStore, VAList, MachinePointerInfo()); 7196 } 7197 7198 SDValue AArch64TargetLowering::LowerFRAMEADDR(SDValue Op, 7199 SelectionDAG &DAG) const { 7200 MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo(); 7201 MFI.setFrameAddressIsTaken(true); 7202 7203 EVT VT = Op.getValueType(); 7204 SDLoc DL(Op); 7205 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue(); 7206 SDValue FrameAddr = 7207 DAG.getCopyFromReg(DAG.getEntryNode(), DL, AArch64::FP, MVT::i64); 7208 while (Depth--) 7209 FrameAddr = DAG.getLoad(VT, DL, DAG.getEntryNode(), FrameAddr, 7210 MachinePointerInfo()); 7211 7212 if (Subtarget->isTargetILP32()) 7213 FrameAddr = DAG.getNode(ISD::AssertZext, DL, MVT::i64, FrameAddr, 7214 DAG.getValueType(VT)); 7215 7216 return FrameAddr; 7217 } 7218 7219 SDValue AArch64TargetLowering::LowerSPONENTRY(SDValue Op, 7220 SelectionDAG &DAG) const { 7221 MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo(); 7222 7223 EVT VT = getPointerTy(DAG.getDataLayout()); 7224 SDLoc DL(Op); 7225 int FI = MFI.CreateFixedObject(4, 0, false); 7226 return DAG.getFrameIndex(FI, VT); 7227 } 7228 7229 #define GET_REGISTER_MATCHER 7230 #include "AArch64GenAsmMatcher.inc" 7231 7232 // FIXME? Maybe this could be a TableGen attribute on some registers and 7233 // this table could be generated automatically from RegInfo. 7234 Register AArch64TargetLowering:: 7235 getRegisterByName(const char* RegName, LLT VT, const MachineFunction &MF) const { 7236 Register Reg = MatchRegisterName(RegName); 7237 if (AArch64::X1 <= Reg && Reg <= AArch64::X28) { 7238 const MCRegisterInfo *MRI = Subtarget->getRegisterInfo(); 7239 unsigned DwarfRegNum = MRI->getDwarfRegNum(Reg, false); 7240 if (!Subtarget->isXRegisterReserved(DwarfRegNum)) 7241 Reg = 0; 7242 } 7243 if (Reg) 7244 return Reg; 7245 report_fatal_error(Twine("Invalid register name \"" 7246 + StringRef(RegName) + "\".")); 7247 } 7248 7249 SDValue AArch64TargetLowering::LowerADDROFRETURNADDR(SDValue Op, 7250 SelectionDAG &DAG) const { 7251 DAG.getMachineFunction().getFrameInfo().setFrameAddressIsTaken(true); 7252 7253 EVT VT = Op.getValueType(); 7254 SDLoc DL(Op); 7255 7256 SDValue FrameAddr = 7257 DAG.getCopyFromReg(DAG.getEntryNode(), DL, AArch64::FP, VT); 7258 SDValue Offset = DAG.getConstant(8, DL, getPointerTy(DAG.getDataLayout())); 7259 7260 return DAG.getNode(ISD::ADD, DL, VT, FrameAddr, Offset); 7261 } 7262 7263 SDValue AArch64TargetLowering::LowerRETURNADDR(SDValue Op, 7264 SelectionDAG &DAG) const { 7265 MachineFunction &MF = DAG.getMachineFunction(); 7266 MachineFrameInfo &MFI = MF.getFrameInfo(); 7267 MFI.setReturnAddressIsTaken(true); 7268 7269 EVT VT = Op.getValueType(); 7270 SDLoc DL(Op); 7271 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue(); 7272 SDValue ReturnAddress; 7273 if (Depth) { 7274 SDValue FrameAddr = LowerFRAMEADDR(Op, DAG); 7275 SDValue Offset = DAG.getConstant(8, DL, getPointerTy(DAG.getDataLayout())); 7276 ReturnAddress = DAG.getLoad( 7277 VT, DL, DAG.getEntryNode(), 7278 DAG.getNode(ISD::ADD, DL, VT, FrameAddr, Offset), MachinePointerInfo()); 7279 } else { 7280 // Return LR, which contains the return address. Mark it an implicit 7281 // live-in. 7282 unsigned Reg = MF.addLiveIn(AArch64::LR, &AArch64::GPR64RegClass); 7283 ReturnAddress = DAG.getCopyFromReg(DAG.getEntryNode(), DL, Reg, VT); 7284 } 7285 7286 // The XPACLRI instruction assembles to a hint-space instruction before 7287 // Armv8.3-A therefore this instruction can be safely used for any pre 7288 // Armv8.3-A architectures. On Armv8.3-A and onwards XPACI is available so use 7289 // that instead. 7290 SDNode *St; 7291 if (Subtarget->hasPAuth()) { 7292 St = DAG.getMachineNode(AArch64::XPACI, DL, VT, ReturnAddress); 7293 } else { 7294 // XPACLRI operates on LR therefore we must move the operand accordingly. 7295 SDValue Chain = 7296 DAG.getCopyToReg(DAG.getEntryNode(), DL, AArch64::LR, ReturnAddress); 7297 St = DAG.getMachineNode(AArch64::XPACLRI, DL, VT, Chain); 7298 } 7299 return SDValue(St, 0); 7300 } 7301 7302 /// LowerShiftRightParts - Lower SRA_PARTS, which returns two 7303 /// i64 values and take a 2 x i64 value to shift plus a shift amount. 7304 SDValue AArch64TargetLowering::LowerShiftRightParts(SDValue Op, 7305 SelectionDAG &DAG) const { 7306 assert(Op.getNumOperands() == 3 && "Not a double-shift!"); 7307 EVT VT = Op.getValueType(); 7308 unsigned VTBits = VT.getSizeInBits(); 7309 SDLoc dl(Op); 7310 SDValue ShOpLo = Op.getOperand(0); 7311 SDValue ShOpHi = Op.getOperand(1); 7312 SDValue ShAmt = Op.getOperand(2); 7313 unsigned Opc = (Op.getOpcode() == ISD::SRA_PARTS) ? ISD::SRA : ISD::SRL; 7314 7315 assert(Op.getOpcode() == ISD::SRA_PARTS || Op.getOpcode() == ISD::SRL_PARTS); 7316 7317 SDValue RevShAmt = DAG.getNode(ISD::SUB, dl, MVT::i64, 7318 DAG.getConstant(VTBits, dl, MVT::i64), ShAmt); 7319 SDValue HiBitsForLo = DAG.getNode(ISD::SHL, dl, VT, ShOpHi, RevShAmt); 7320 7321 // Unfortunately, if ShAmt == 0, we just calculated "(SHL ShOpHi, 64)" which 7322 // is "undef". We wanted 0, so CSEL it directly. 7323 SDValue Cmp = emitComparison(ShAmt, DAG.getConstant(0, dl, MVT::i64), 7324 ISD::SETEQ, dl, DAG); 7325 SDValue CCVal = DAG.getConstant(AArch64CC::EQ, dl, MVT::i32); 7326 HiBitsForLo = 7327 DAG.getNode(AArch64ISD::CSEL, dl, VT, DAG.getConstant(0, dl, MVT::i64), 7328 HiBitsForLo, CCVal, Cmp); 7329 7330 SDValue ExtraShAmt = DAG.getNode(ISD::SUB, dl, MVT::i64, ShAmt, 7331 DAG.getConstant(VTBits, dl, MVT::i64)); 7332 7333 SDValue LoBitsForLo = DAG.getNode(ISD::SRL, dl, VT, ShOpLo, ShAmt); 7334 SDValue LoForNormalShift = 7335 DAG.getNode(ISD::OR, dl, VT, LoBitsForLo, HiBitsForLo); 7336 7337 Cmp = emitComparison(ExtraShAmt, DAG.getConstant(0, dl, MVT::i64), ISD::SETGE, 7338 dl, DAG); 7339 CCVal = DAG.getConstant(AArch64CC::GE, dl, MVT::i32); 7340 SDValue LoForBigShift = DAG.getNode(Opc, dl, VT, ShOpHi, ExtraShAmt); 7341 SDValue Lo = DAG.getNode(AArch64ISD::CSEL, dl, VT, LoForBigShift, 7342 LoForNormalShift, CCVal, Cmp); 7343 7344 // AArch64 shifts larger than the register width are wrapped rather than 7345 // clamped, so we can't just emit "hi >> x". 7346 SDValue HiForNormalShift = DAG.getNode(Opc, dl, VT, ShOpHi, ShAmt); 7347 SDValue HiForBigShift = 7348 Opc == ISD::SRA 7349 ? DAG.getNode(Opc, dl, VT, ShOpHi, 7350 DAG.getConstant(VTBits - 1, dl, MVT::i64)) 7351 : DAG.getConstant(0, dl, VT); 7352 SDValue Hi = DAG.getNode(AArch64ISD::CSEL, dl, VT, HiForBigShift, 7353 HiForNormalShift, CCVal, Cmp); 7354 7355 SDValue Ops[2] = { Lo, Hi }; 7356 return DAG.getMergeValues(Ops, dl); 7357 } 7358 7359 /// LowerShiftLeftParts - Lower SHL_PARTS, which returns two 7360 /// i64 values and take a 2 x i64 value to shift plus a shift amount. 7361 SDValue AArch64TargetLowering::LowerShiftLeftParts(SDValue Op, 7362 SelectionDAG &DAG) const { 7363 assert(Op.getNumOperands() == 3 && "Not a double-shift!"); 7364 EVT VT = Op.getValueType(); 7365 unsigned VTBits = VT.getSizeInBits(); 7366 SDLoc dl(Op); 7367 SDValue ShOpLo = Op.getOperand(0); 7368 SDValue ShOpHi = Op.getOperand(1); 7369 SDValue ShAmt = Op.getOperand(2); 7370 7371 assert(Op.getOpcode() == ISD::SHL_PARTS); 7372 SDValue RevShAmt = DAG.getNode(ISD::SUB, dl, MVT::i64, 7373 DAG.getConstant(VTBits, dl, MVT::i64), ShAmt); 7374 SDValue LoBitsForHi = DAG.getNode(ISD::SRL, dl, VT, ShOpLo, RevShAmt); 7375 7376 // Unfortunately, if ShAmt == 0, we just calculated "(SRL ShOpLo, 64)" which 7377 // is "undef". We wanted 0, so CSEL it directly. 7378 SDValue Cmp = emitComparison(ShAmt, DAG.getConstant(0, dl, MVT::i64), 7379 ISD::SETEQ, dl, DAG); 7380 SDValue CCVal = DAG.getConstant(AArch64CC::EQ, dl, MVT::i32); 7381 LoBitsForHi = 7382 DAG.getNode(AArch64ISD::CSEL, dl, VT, DAG.getConstant(0, dl, MVT::i64), 7383 LoBitsForHi, CCVal, Cmp); 7384 7385 SDValue ExtraShAmt = DAG.getNode(ISD::SUB, dl, MVT::i64, ShAmt, 7386 DAG.getConstant(VTBits, dl, MVT::i64)); 7387 SDValue HiBitsForHi = DAG.getNode(ISD::SHL, dl, VT, ShOpHi, ShAmt); 7388 SDValue HiForNormalShift = 7389 DAG.getNode(ISD::OR, dl, VT, LoBitsForHi, HiBitsForHi); 7390 7391 SDValue HiForBigShift = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ExtraShAmt); 7392 7393 Cmp = emitComparison(ExtraShAmt, DAG.getConstant(0, dl, MVT::i64), ISD::SETGE, 7394 dl, DAG); 7395 CCVal = DAG.getConstant(AArch64CC::GE, dl, MVT::i32); 7396 SDValue Hi = DAG.getNode(AArch64ISD::CSEL, dl, VT, HiForBigShift, 7397 HiForNormalShift, CCVal, Cmp); 7398 7399 // AArch64 shifts of larger than register sizes are wrapped rather than 7400 // clamped, so we can't just emit "lo << a" if a is too big. 7401 SDValue LoForBigShift = DAG.getConstant(0, dl, VT); 7402 SDValue LoForNormalShift = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ShAmt); 7403 SDValue Lo = DAG.getNode(AArch64ISD::CSEL, dl, VT, LoForBigShift, 7404 LoForNormalShift, CCVal, Cmp); 7405 7406 SDValue Ops[2] = { Lo, Hi }; 7407 return DAG.getMergeValues(Ops, dl); 7408 } 7409 7410 bool AArch64TargetLowering::isOffsetFoldingLegal( 7411 const GlobalAddressSDNode *GA) const { 7412 // Offsets are folded in the DAG combine rather than here so that we can 7413 // intelligently choose an offset based on the uses. 7414 return false; 7415 } 7416 7417 bool AArch64TargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT, 7418 bool OptForSize) const { 7419 bool IsLegal = false; 7420 // We can materialize #0.0 as fmov $Rd, XZR for 64-bit, 32-bit cases, and 7421 // 16-bit case when target has full fp16 support. 7422 // FIXME: We should be able to handle f128 as well with a clever lowering. 7423 const APInt ImmInt = Imm.bitcastToAPInt(); 7424 if (VT == MVT::f64) 7425 IsLegal = AArch64_AM::getFP64Imm(ImmInt) != -1 || Imm.isPosZero(); 7426 else if (VT == MVT::f32) 7427 IsLegal = AArch64_AM::getFP32Imm(ImmInt) != -1 || Imm.isPosZero(); 7428 else if (VT == MVT::f16 && Subtarget->hasFullFP16()) 7429 IsLegal = AArch64_AM::getFP16Imm(ImmInt) != -1 || Imm.isPosZero(); 7430 // TODO: fmov h0, w0 is also legal, however on't have an isel pattern to 7431 // generate that fmov. 7432 7433 // If we can not materialize in immediate field for fmov, check if the 7434 // value can be encoded as the immediate operand of a logical instruction. 7435 // The immediate value will be created with either MOVZ, MOVN, or ORR. 7436 if (!IsLegal && (VT == MVT::f64 || VT == MVT::f32)) { 7437 // The cost is actually exactly the same for mov+fmov vs. adrp+ldr; 7438 // however the mov+fmov sequence is always better because of the reduced 7439 // cache pressure. The timings are still the same if you consider 7440 // movw+movk+fmov vs. adrp+ldr (it's one instruction longer, but the 7441 // movw+movk is fused). So we limit up to 2 instrdduction at most. 7442 SmallVector<AArch64_IMM::ImmInsnModel, 4> Insn; 7443 AArch64_IMM::expandMOVImm(ImmInt.getZExtValue(), VT.getSizeInBits(), 7444 Insn); 7445 unsigned Limit = (OptForSize ? 1 : (Subtarget->hasFuseLiterals() ? 5 : 2)); 7446 IsLegal = Insn.size() <= Limit; 7447 } 7448 7449 LLVM_DEBUG(dbgs() << (IsLegal ? "Legal " : "Illegal ") << VT.getEVTString() 7450 << " imm value: "; Imm.dump();); 7451 return IsLegal; 7452 } 7453 7454 //===----------------------------------------------------------------------===// 7455 // AArch64 Optimization Hooks 7456 //===----------------------------------------------------------------------===// 7457 7458 static SDValue getEstimate(const AArch64Subtarget *ST, unsigned Opcode, 7459 SDValue Operand, SelectionDAG &DAG, 7460 int &ExtraSteps) { 7461 EVT VT = Operand.getValueType(); 7462 if (ST->hasNEON() && 7463 (VT == MVT::f64 || VT == MVT::v1f64 || VT == MVT::v2f64 || 7464 VT == MVT::f32 || VT == MVT::v1f32 || 7465 VT == MVT::v2f32 || VT == MVT::v4f32)) { 7466 if (ExtraSteps == TargetLoweringBase::ReciprocalEstimate::Unspecified) 7467 // For the reciprocal estimates, convergence is quadratic, so the number 7468 // of digits is doubled after each iteration. In ARMv8, the accuracy of 7469 // the initial estimate is 2^-8. Thus the number of extra steps to refine 7470 // the result for float (23 mantissa bits) is 2 and for double (52 7471 // mantissa bits) is 3. 7472 ExtraSteps = VT.getScalarType() == MVT::f64 ? 3 : 2; 7473 7474 return DAG.getNode(Opcode, SDLoc(Operand), VT, Operand); 7475 } 7476 7477 return SDValue(); 7478 } 7479 7480 SDValue 7481 AArch64TargetLowering::getSqrtInputTest(SDValue Op, SelectionDAG &DAG, 7482 const DenormalMode &Mode) const { 7483 SDLoc DL(Op); 7484 EVT VT = Op.getValueType(); 7485 EVT CCVT = getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT); 7486 SDValue FPZero = DAG.getConstantFP(0.0, DL, VT); 7487 return DAG.getSetCC(DL, CCVT, Op, FPZero, ISD::SETEQ); 7488 } 7489 7490 SDValue 7491 AArch64TargetLowering::getSqrtResultForDenormInput(SDValue Op, 7492 SelectionDAG &DAG) const { 7493 return Op; 7494 } 7495 7496 SDValue AArch64TargetLowering::getSqrtEstimate(SDValue Operand, 7497 SelectionDAG &DAG, int Enabled, 7498 int &ExtraSteps, 7499 bool &UseOneConst, 7500 bool Reciprocal) const { 7501 if (Enabled == ReciprocalEstimate::Enabled || 7502 (Enabled == ReciprocalEstimate::Unspecified && Subtarget->useRSqrt())) 7503 if (SDValue Estimate = getEstimate(Subtarget, AArch64ISD::FRSQRTE, Operand, 7504 DAG, ExtraSteps)) { 7505 SDLoc DL(Operand); 7506 EVT VT = Operand.getValueType(); 7507 7508 SDNodeFlags Flags; 7509 Flags.setAllowReassociation(true); 7510 7511 // Newton reciprocal square root iteration: E * 0.5 * (3 - X * E^2) 7512 // AArch64 reciprocal square root iteration instruction: 0.5 * (3 - M * N) 7513 for (int i = ExtraSteps; i > 0; --i) { 7514 SDValue Step = DAG.getNode(ISD::FMUL, DL, VT, Estimate, Estimate, 7515 Flags); 7516 Step = DAG.getNode(AArch64ISD::FRSQRTS, DL, VT, Operand, Step, Flags); 7517 Estimate = DAG.getNode(ISD::FMUL, DL, VT, Estimate, Step, Flags); 7518 } 7519 if (!Reciprocal) 7520 Estimate = DAG.getNode(ISD::FMUL, DL, VT, Operand, Estimate, Flags); 7521 7522 ExtraSteps = 0; 7523 return Estimate; 7524 } 7525 7526 return SDValue(); 7527 } 7528 7529 SDValue AArch64TargetLowering::getRecipEstimate(SDValue Operand, 7530 SelectionDAG &DAG, int Enabled, 7531 int &ExtraSteps) const { 7532 if (Enabled == ReciprocalEstimate::Enabled) 7533 if (SDValue Estimate = getEstimate(Subtarget, AArch64ISD::FRECPE, Operand, 7534 DAG, ExtraSteps)) { 7535 SDLoc DL(Operand); 7536 EVT VT = Operand.getValueType(); 7537 7538 SDNodeFlags Flags; 7539 Flags.setAllowReassociation(true); 7540 7541 // Newton reciprocal iteration: E * (2 - X * E) 7542 // AArch64 reciprocal iteration instruction: (2 - M * N) 7543 for (int i = ExtraSteps; i > 0; --i) { 7544 SDValue Step = DAG.getNode(AArch64ISD::FRECPS, DL, VT, Operand, 7545 Estimate, Flags); 7546 Estimate = DAG.getNode(ISD::FMUL, DL, VT, Estimate, Step, Flags); 7547 } 7548 7549 ExtraSteps = 0; 7550 return Estimate; 7551 } 7552 7553 return SDValue(); 7554 } 7555 7556 //===----------------------------------------------------------------------===// 7557 // AArch64 Inline Assembly Support 7558 //===----------------------------------------------------------------------===// 7559 7560 // Table of Constraints 7561 // TODO: This is the current set of constraints supported by ARM for the 7562 // compiler, not all of them may make sense. 7563 // 7564 // r - A general register 7565 // w - An FP/SIMD register of some size in the range v0-v31 7566 // x - An FP/SIMD register of some size in the range v0-v15 7567 // I - Constant that can be used with an ADD instruction 7568 // J - Constant that can be used with a SUB instruction 7569 // K - Constant that can be used with a 32-bit logical instruction 7570 // L - Constant that can be used with a 64-bit logical instruction 7571 // M - Constant that can be used as a 32-bit MOV immediate 7572 // N - Constant that can be used as a 64-bit MOV immediate 7573 // Q - A memory reference with base register and no offset 7574 // S - A symbolic address 7575 // Y - Floating point constant zero 7576 // Z - Integer constant zero 7577 // 7578 // Note that general register operands will be output using their 64-bit x 7579 // register name, whatever the size of the variable, unless the asm operand 7580 // is prefixed by the %w modifier. Floating-point and SIMD register operands 7581 // will be output with the v prefix unless prefixed by the %b, %h, %s, %d or 7582 // %q modifier. 7583 const char *AArch64TargetLowering::LowerXConstraint(EVT ConstraintVT) const { 7584 // At this point, we have to lower this constraint to something else, so we 7585 // lower it to an "r" or "w". However, by doing this we will force the result 7586 // to be in register, while the X constraint is much more permissive. 7587 // 7588 // Although we are correct (we are free to emit anything, without 7589 // constraints), we might break use cases that would expect us to be more 7590 // efficient and emit something else. 7591 if (!Subtarget->hasFPARMv8()) 7592 return "r"; 7593 7594 if (ConstraintVT.isFloatingPoint()) 7595 return "w"; 7596 7597 if (ConstraintVT.isVector() && 7598 (ConstraintVT.getSizeInBits() == 64 || 7599 ConstraintVT.getSizeInBits() == 128)) 7600 return "w"; 7601 7602 return "r"; 7603 } 7604 7605 enum PredicateConstraint { 7606 Upl, 7607 Upa, 7608 Invalid 7609 }; 7610 7611 static PredicateConstraint parsePredicateConstraint(StringRef Constraint) { 7612 PredicateConstraint P = PredicateConstraint::Invalid; 7613 if (Constraint == "Upa") 7614 P = PredicateConstraint::Upa; 7615 if (Constraint == "Upl") 7616 P = PredicateConstraint::Upl; 7617 return P; 7618 } 7619 7620 /// getConstraintType - Given a constraint letter, return the type of 7621 /// constraint it is for this target. 7622 AArch64TargetLowering::ConstraintType 7623 AArch64TargetLowering::getConstraintType(StringRef Constraint) const { 7624 if (Constraint.size() == 1) { 7625 switch (Constraint[0]) { 7626 default: 7627 break; 7628 case 'x': 7629 case 'w': 7630 case 'y': 7631 return C_RegisterClass; 7632 // An address with a single base register. Due to the way we 7633 // currently handle addresses it is the same as 'r'. 7634 case 'Q': 7635 return C_Memory; 7636 case 'I': 7637 case 'J': 7638 case 'K': 7639 case 'L': 7640 case 'M': 7641 case 'N': 7642 case 'Y': 7643 case 'Z': 7644 return C_Immediate; 7645 case 'z': 7646 case 'S': // A symbolic address 7647 return C_Other; 7648 } 7649 } else if (parsePredicateConstraint(Constraint) != 7650 PredicateConstraint::Invalid) 7651 return C_RegisterClass; 7652 return TargetLowering::getConstraintType(Constraint); 7653 } 7654 7655 /// Examine constraint type and operand type and determine a weight value. 7656 /// This object must already have been set up with the operand type 7657 /// and the current alternative constraint selected. 7658 TargetLowering::ConstraintWeight 7659 AArch64TargetLowering::getSingleConstraintMatchWeight( 7660 AsmOperandInfo &info, const char *constraint) const { 7661 ConstraintWeight weight = CW_Invalid; 7662 Value *CallOperandVal = info.CallOperandVal; 7663 // If we don't have a value, we can't do a match, 7664 // but allow it at the lowest weight. 7665 if (!CallOperandVal) 7666 return CW_Default; 7667 Type *type = CallOperandVal->getType(); 7668 // Look at the constraint type. 7669 switch (*constraint) { 7670 default: 7671 weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint); 7672 break; 7673 case 'x': 7674 case 'w': 7675 case 'y': 7676 if (type->isFloatingPointTy() || type->isVectorTy()) 7677 weight = CW_Register; 7678 break; 7679 case 'z': 7680 weight = CW_Constant; 7681 break; 7682 case 'U': 7683 if (parsePredicateConstraint(constraint) != PredicateConstraint::Invalid) 7684 weight = CW_Register; 7685 break; 7686 } 7687 return weight; 7688 } 7689 7690 std::pair<unsigned, const TargetRegisterClass *> 7691 AArch64TargetLowering::getRegForInlineAsmConstraint( 7692 const TargetRegisterInfo *TRI, StringRef Constraint, MVT VT) const { 7693 if (Constraint.size() == 1) { 7694 switch (Constraint[0]) { 7695 case 'r': 7696 if (VT.isScalableVector()) 7697 return std::make_pair(0U, nullptr); 7698 if (VT.getFixedSizeInBits() == 64) 7699 return std::make_pair(0U, &AArch64::GPR64commonRegClass); 7700 return std::make_pair(0U, &AArch64::GPR32commonRegClass); 7701 case 'w': { 7702 if (!Subtarget->hasFPARMv8()) 7703 break; 7704 if (VT.isScalableVector()) { 7705 if (VT.getVectorElementType() != MVT::i1) 7706 return std::make_pair(0U, &AArch64::ZPRRegClass); 7707 return std::make_pair(0U, nullptr); 7708 } 7709 uint64_t VTSize = VT.getFixedSizeInBits(); 7710 if (VTSize == 16) 7711 return std::make_pair(0U, &AArch64::FPR16RegClass); 7712 if (VTSize == 32) 7713 return std::make_pair(0U, &AArch64::FPR32RegClass); 7714 if (VTSize == 64) 7715 return std::make_pair(0U, &AArch64::FPR64RegClass); 7716 if (VTSize == 128) 7717 return std::make_pair(0U, &AArch64::FPR128RegClass); 7718 break; 7719 } 7720 // The instructions that this constraint is designed for can 7721 // only take 128-bit registers so just use that regclass. 7722 case 'x': 7723 if (!Subtarget->hasFPARMv8()) 7724 break; 7725 if (VT.isScalableVector()) 7726 return std::make_pair(0U, &AArch64::ZPR_4bRegClass); 7727 if (VT.getSizeInBits() == 128) 7728 return std::make_pair(0U, &AArch64::FPR128_loRegClass); 7729 break; 7730 case 'y': 7731 if (!Subtarget->hasFPARMv8()) 7732 break; 7733 if (VT.isScalableVector()) 7734 return std::make_pair(0U, &AArch64::ZPR_3bRegClass); 7735 break; 7736 } 7737 } else { 7738 PredicateConstraint PC = parsePredicateConstraint(Constraint); 7739 if (PC != PredicateConstraint::Invalid) { 7740 if (!VT.isScalableVector() || VT.getVectorElementType() != MVT::i1) 7741 return std::make_pair(0U, nullptr); 7742 bool restricted = (PC == PredicateConstraint::Upl); 7743 return restricted ? std::make_pair(0U, &AArch64::PPR_3bRegClass) 7744 : std::make_pair(0U, &AArch64::PPRRegClass); 7745 } 7746 } 7747 if (StringRef("{cc}").equals_lower(Constraint)) 7748 return std::make_pair(unsigned(AArch64::NZCV), &AArch64::CCRRegClass); 7749 7750 // Use the default implementation in TargetLowering to convert the register 7751 // constraint into a member of a register class. 7752 std::pair<unsigned, const TargetRegisterClass *> Res; 7753 Res = TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT); 7754 7755 // Not found as a standard register? 7756 if (!Res.second) { 7757 unsigned Size = Constraint.size(); 7758 if ((Size == 4 || Size == 5) && Constraint[0] == '{' && 7759 tolower(Constraint[1]) == 'v' && Constraint[Size - 1] == '}') { 7760 int RegNo; 7761 bool Failed = Constraint.slice(2, Size - 1).getAsInteger(10, RegNo); 7762 if (!Failed && RegNo >= 0 && RegNo <= 31) { 7763 // v0 - v31 are aliases of q0 - q31 or d0 - d31 depending on size. 7764 // By default we'll emit v0-v31 for this unless there's a modifier where 7765 // we'll emit the correct register as well. 7766 if (VT != MVT::Other && VT.getSizeInBits() == 64) { 7767 Res.first = AArch64::FPR64RegClass.getRegister(RegNo); 7768 Res.second = &AArch64::FPR64RegClass; 7769 } else { 7770 Res.first = AArch64::FPR128RegClass.getRegister(RegNo); 7771 Res.second = &AArch64::FPR128RegClass; 7772 } 7773 } 7774 } 7775 } 7776 7777 if (Res.second && !Subtarget->hasFPARMv8() && 7778 !AArch64::GPR32allRegClass.hasSubClassEq(Res.second) && 7779 !AArch64::GPR64allRegClass.hasSubClassEq(Res.second)) 7780 return std::make_pair(0U, nullptr); 7781 7782 return Res; 7783 } 7784 7785 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops 7786 /// vector. If it is invalid, don't add anything to Ops. 7787 void AArch64TargetLowering::LowerAsmOperandForConstraint( 7788 SDValue Op, std::string &Constraint, std::vector<SDValue> &Ops, 7789 SelectionDAG &DAG) const { 7790 SDValue Result; 7791 7792 // Currently only support length 1 constraints. 7793 if (Constraint.length() != 1) 7794 return; 7795 7796 char ConstraintLetter = Constraint[0]; 7797 switch (ConstraintLetter) { 7798 default: 7799 break; 7800 7801 // This set of constraints deal with valid constants for various instructions. 7802 // Validate and return a target constant for them if we can. 7803 case 'z': { 7804 // 'z' maps to xzr or wzr so it needs an input of 0. 7805 if (!isNullConstant(Op)) 7806 return; 7807 7808 if (Op.getValueType() == MVT::i64) 7809 Result = DAG.getRegister(AArch64::XZR, MVT::i64); 7810 else 7811 Result = DAG.getRegister(AArch64::WZR, MVT::i32); 7812 break; 7813 } 7814 case 'S': { 7815 // An absolute symbolic address or label reference. 7816 if (const GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(Op)) { 7817 Result = DAG.getTargetGlobalAddress(GA->getGlobal(), SDLoc(Op), 7818 GA->getValueType(0)); 7819 } else if (const BlockAddressSDNode *BA = 7820 dyn_cast<BlockAddressSDNode>(Op)) { 7821 Result = 7822 DAG.getTargetBlockAddress(BA->getBlockAddress(), BA->getValueType(0)); 7823 } else if (const ExternalSymbolSDNode *ES = 7824 dyn_cast<ExternalSymbolSDNode>(Op)) { 7825 Result = 7826 DAG.getTargetExternalSymbol(ES->getSymbol(), ES->getValueType(0)); 7827 } else 7828 return; 7829 break; 7830 } 7831 7832 case 'I': 7833 case 'J': 7834 case 'K': 7835 case 'L': 7836 case 'M': 7837 case 'N': 7838 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op); 7839 if (!C) 7840 return; 7841 7842 // Grab the value and do some validation. 7843 uint64_t CVal = C->getZExtValue(); 7844 switch (ConstraintLetter) { 7845 // The I constraint applies only to simple ADD or SUB immediate operands: 7846 // i.e. 0 to 4095 with optional shift by 12 7847 // The J constraint applies only to ADD or SUB immediates that would be 7848 // valid when negated, i.e. if [an add pattern] were to be output as a SUB 7849 // instruction [or vice versa], in other words -1 to -4095 with optional 7850 // left shift by 12. 7851 case 'I': 7852 if (isUInt<12>(CVal) || isShiftedUInt<12, 12>(CVal)) 7853 break; 7854 return; 7855 case 'J': { 7856 uint64_t NVal = -C->getSExtValue(); 7857 if (isUInt<12>(NVal) || isShiftedUInt<12, 12>(NVal)) { 7858 CVal = C->getSExtValue(); 7859 break; 7860 } 7861 return; 7862 } 7863 // The K and L constraints apply *only* to logical immediates, including 7864 // what used to be the MOVI alias for ORR (though the MOVI alias has now 7865 // been removed and MOV should be used). So these constraints have to 7866 // distinguish between bit patterns that are valid 32-bit or 64-bit 7867 // "bitmask immediates": for example 0xaaaaaaaa is a valid bimm32 (K), but 7868 // not a valid bimm64 (L) where 0xaaaaaaaaaaaaaaaa would be valid, and vice 7869 // versa. 7870 case 'K': 7871 if (AArch64_AM::isLogicalImmediate(CVal, 32)) 7872 break; 7873 return; 7874 case 'L': 7875 if (AArch64_AM::isLogicalImmediate(CVal, 64)) 7876 break; 7877 return; 7878 // The M and N constraints are a superset of K and L respectively, for use 7879 // with the MOV (immediate) alias. As well as the logical immediates they 7880 // also match 32 or 64-bit immediates that can be loaded either using a 7881 // *single* MOVZ or MOVN , such as 32-bit 0x12340000, 0x00001234, 0xffffedca 7882 // (M) or 64-bit 0x1234000000000000 (N) etc. 7883 // As a note some of this code is liberally stolen from the asm parser. 7884 case 'M': { 7885 if (!isUInt<32>(CVal)) 7886 return; 7887 if (AArch64_AM::isLogicalImmediate(CVal, 32)) 7888 break; 7889 if ((CVal & 0xFFFF) == CVal) 7890 break; 7891 if ((CVal & 0xFFFF0000ULL) == CVal) 7892 break; 7893 uint64_t NCVal = ~(uint32_t)CVal; 7894 if ((NCVal & 0xFFFFULL) == NCVal) 7895 break; 7896 if ((NCVal & 0xFFFF0000ULL) == NCVal) 7897 break; 7898 return; 7899 } 7900 case 'N': { 7901 if (AArch64_AM::isLogicalImmediate(CVal, 64)) 7902 break; 7903 if ((CVal & 0xFFFFULL) == CVal) 7904 break; 7905 if ((CVal & 0xFFFF0000ULL) == CVal) 7906 break; 7907 if ((CVal & 0xFFFF00000000ULL) == CVal) 7908 break; 7909 if ((CVal & 0xFFFF000000000000ULL) == CVal) 7910 break; 7911 uint64_t NCVal = ~CVal; 7912 if ((NCVal & 0xFFFFULL) == NCVal) 7913 break; 7914 if ((NCVal & 0xFFFF0000ULL) == NCVal) 7915 break; 7916 if ((NCVal & 0xFFFF00000000ULL) == NCVal) 7917 break; 7918 if ((NCVal & 0xFFFF000000000000ULL) == NCVal) 7919 break; 7920 return; 7921 } 7922 default: 7923 return; 7924 } 7925 7926 // All assembler immediates are 64-bit integers. 7927 Result = DAG.getTargetConstant(CVal, SDLoc(Op), MVT::i64); 7928 break; 7929 } 7930 7931 if (Result.getNode()) { 7932 Ops.push_back(Result); 7933 return; 7934 } 7935 7936 return TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG); 7937 } 7938 7939 //===----------------------------------------------------------------------===// 7940 // AArch64 Advanced SIMD Support 7941 //===----------------------------------------------------------------------===// 7942 7943 /// WidenVector - Given a value in the V64 register class, produce the 7944 /// equivalent value in the V128 register class. 7945 static SDValue WidenVector(SDValue V64Reg, SelectionDAG &DAG) { 7946 EVT VT = V64Reg.getValueType(); 7947 unsigned NarrowSize = VT.getVectorNumElements(); 7948 MVT EltTy = VT.getVectorElementType().getSimpleVT(); 7949 MVT WideTy = MVT::getVectorVT(EltTy, 2 * NarrowSize); 7950 SDLoc DL(V64Reg); 7951 7952 return DAG.getNode(ISD::INSERT_SUBVECTOR, DL, WideTy, DAG.getUNDEF(WideTy), 7953 V64Reg, DAG.getConstant(0, DL, MVT::i32)); 7954 } 7955 7956 /// getExtFactor - Determine the adjustment factor for the position when 7957 /// generating an "extract from vector registers" instruction. 7958 static unsigned getExtFactor(SDValue &V) { 7959 EVT EltType = V.getValueType().getVectorElementType(); 7960 return EltType.getSizeInBits() / 8; 7961 } 7962 7963 /// NarrowVector - Given a value in the V128 register class, produce the 7964 /// equivalent value in the V64 register class. 7965 static SDValue NarrowVector(SDValue V128Reg, SelectionDAG &DAG) { 7966 EVT VT = V128Reg.getValueType(); 7967 unsigned WideSize = VT.getVectorNumElements(); 7968 MVT EltTy = VT.getVectorElementType().getSimpleVT(); 7969 MVT NarrowTy = MVT::getVectorVT(EltTy, WideSize / 2); 7970 SDLoc DL(V128Reg); 7971 7972 return DAG.getTargetExtractSubreg(AArch64::dsub, DL, NarrowTy, V128Reg); 7973 } 7974 7975 // Gather data to see if the operation can be modelled as a 7976 // shuffle in combination with VEXTs. 7977 SDValue AArch64TargetLowering::ReconstructShuffle(SDValue Op, 7978 SelectionDAG &DAG) const { 7979 assert(Op.getOpcode() == ISD::BUILD_VECTOR && "Unknown opcode!"); 7980 LLVM_DEBUG(dbgs() << "AArch64TargetLowering::ReconstructShuffle\n"); 7981 SDLoc dl(Op); 7982 EVT VT = Op.getValueType(); 7983 assert(!VT.isScalableVector() && 7984 "Scalable vectors cannot be used with ISD::BUILD_VECTOR"); 7985 unsigned NumElts = VT.getVectorNumElements(); 7986 7987 struct ShuffleSourceInfo { 7988 SDValue Vec; 7989 unsigned MinElt; 7990 unsigned MaxElt; 7991 7992 // We may insert some combination of BITCASTs and VEXT nodes to force Vec to 7993 // be compatible with the shuffle we intend to construct. As a result 7994 // ShuffleVec will be some sliding window into the original Vec. 7995 SDValue ShuffleVec; 7996 7997 // Code should guarantee that element i in Vec starts at element "WindowBase 7998 // + i * WindowScale in ShuffleVec". 7999 int WindowBase; 8000 int WindowScale; 8001 8002 ShuffleSourceInfo(SDValue Vec) 8003 : Vec(Vec), MinElt(std::numeric_limits<unsigned>::max()), MaxElt(0), 8004 ShuffleVec(Vec), WindowBase(0), WindowScale(1) {} 8005 8006 bool operator ==(SDValue OtherVec) { return Vec == OtherVec; } 8007 }; 8008 8009 // First gather all vectors used as an immediate source for this BUILD_VECTOR 8010 // node. 8011 SmallVector<ShuffleSourceInfo, 2> Sources; 8012 for (unsigned i = 0; i < NumElts; ++i) { 8013 SDValue V = Op.getOperand(i); 8014 if (V.isUndef()) 8015 continue; 8016 else if (V.getOpcode() != ISD::EXTRACT_VECTOR_ELT || 8017 !isa<ConstantSDNode>(V.getOperand(1))) { 8018 LLVM_DEBUG( 8019 dbgs() << "Reshuffle failed: " 8020 "a shuffle can only come from building a vector from " 8021 "various elements of other vectors, provided their " 8022 "indices are constant\n"); 8023 return SDValue(); 8024 } 8025 8026 // Add this element source to the list if it's not already there. 8027 SDValue SourceVec = V.getOperand(0); 8028 auto Source = find(Sources, SourceVec); 8029 if (Source == Sources.end()) 8030 Source = Sources.insert(Sources.end(), ShuffleSourceInfo(SourceVec)); 8031 8032 // Update the minimum and maximum lane number seen. 8033 unsigned EltNo = cast<ConstantSDNode>(V.getOperand(1))->getZExtValue(); 8034 Source->MinElt = std::min(Source->MinElt, EltNo); 8035 Source->MaxElt = std::max(Source->MaxElt, EltNo); 8036 } 8037 8038 if (Sources.size() > 2) { 8039 LLVM_DEBUG( 8040 dbgs() << "Reshuffle failed: currently only do something sane when at " 8041 "most two source vectors are involved\n"); 8042 return SDValue(); 8043 } 8044 8045 // Find out the smallest element size among result and two sources, and use 8046 // it as element size to build the shuffle_vector. 8047 EVT SmallestEltTy = VT.getVectorElementType(); 8048 for (auto &Source : Sources) { 8049 EVT SrcEltTy = Source.Vec.getValueType().getVectorElementType(); 8050 if (SrcEltTy.bitsLT(SmallestEltTy)) { 8051 SmallestEltTy = SrcEltTy; 8052 } 8053 } 8054 unsigned ResMultiplier = 8055 VT.getScalarSizeInBits() / SmallestEltTy.getFixedSizeInBits(); 8056 uint64_t VTSize = VT.getFixedSizeInBits(); 8057 NumElts = VTSize / SmallestEltTy.getFixedSizeInBits(); 8058 EVT ShuffleVT = EVT::getVectorVT(*DAG.getContext(), SmallestEltTy, NumElts); 8059 8060 // If the source vector is too wide or too narrow, we may nevertheless be able 8061 // to construct a compatible shuffle either by concatenating it with UNDEF or 8062 // extracting a suitable range of elements. 8063 for (auto &Src : Sources) { 8064 EVT SrcVT = Src.ShuffleVec.getValueType(); 8065 8066 uint64_t SrcVTSize = SrcVT.getFixedSizeInBits(); 8067 if (SrcVTSize == VTSize) 8068 continue; 8069 8070 // This stage of the search produces a source with the same element type as 8071 // the original, but with a total width matching the BUILD_VECTOR output. 8072 EVT EltVT = SrcVT.getVectorElementType(); 8073 unsigned NumSrcElts = VTSize / EltVT.getFixedSizeInBits(); 8074 EVT DestVT = EVT::getVectorVT(*DAG.getContext(), EltVT, NumSrcElts); 8075 8076 if (SrcVTSize < VTSize) { 8077 assert(2 * SrcVTSize == VTSize); 8078 // We can pad out the smaller vector for free, so if it's part of a 8079 // shuffle... 8080 Src.ShuffleVec = 8081 DAG.getNode(ISD::CONCAT_VECTORS, dl, DestVT, Src.ShuffleVec, 8082 DAG.getUNDEF(Src.ShuffleVec.getValueType())); 8083 continue; 8084 } 8085 8086 if (SrcVTSize != 2 * VTSize) { 8087 LLVM_DEBUG( 8088 dbgs() << "Reshuffle failed: result vector too small to extract\n"); 8089 return SDValue(); 8090 } 8091 8092 if (Src.MaxElt - Src.MinElt >= NumSrcElts) { 8093 LLVM_DEBUG( 8094 dbgs() << "Reshuffle failed: span too large for a VEXT to cope\n"); 8095 return SDValue(); 8096 } 8097 8098 if (Src.MinElt >= NumSrcElts) { 8099 // The extraction can just take the second half 8100 Src.ShuffleVec = 8101 DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DestVT, Src.ShuffleVec, 8102 DAG.getConstant(NumSrcElts, dl, MVT::i64)); 8103 Src.WindowBase = -NumSrcElts; 8104 } else if (Src.MaxElt < NumSrcElts) { 8105 // The extraction can just take the first half 8106 Src.ShuffleVec = 8107 DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DestVT, Src.ShuffleVec, 8108 DAG.getConstant(0, dl, MVT::i64)); 8109 } else { 8110 // An actual VEXT is needed 8111 SDValue VEXTSrc1 = 8112 DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DestVT, Src.ShuffleVec, 8113 DAG.getConstant(0, dl, MVT::i64)); 8114 SDValue VEXTSrc2 = 8115 DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DestVT, Src.ShuffleVec, 8116 DAG.getConstant(NumSrcElts, dl, MVT::i64)); 8117 unsigned Imm = Src.MinElt * getExtFactor(VEXTSrc1); 8118 8119 if (!SrcVT.is64BitVector()) { 8120 LLVM_DEBUG( 8121 dbgs() << "Reshuffle failed: don't know how to lower AArch64ISD::EXT " 8122 "for SVE vectors."); 8123 return SDValue(); 8124 } 8125 8126 Src.ShuffleVec = DAG.getNode(AArch64ISD::EXT, dl, DestVT, VEXTSrc1, 8127 VEXTSrc2, 8128 DAG.getConstant(Imm, dl, MVT::i32)); 8129 Src.WindowBase = -Src.MinElt; 8130 } 8131 } 8132 8133 // Another possible incompatibility occurs from the vector element types. We 8134 // can fix this by bitcasting the source vectors to the same type we intend 8135 // for the shuffle. 8136 for (auto &Src : Sources) { 8137 EVT SrcEltTy = Src.ShuffleVec.getValueType().getVectorElementType(); 8138 if (SrcEltTy == SmallestEltTy) 8139 continue; 8140 assert(ShuffleVT.getVectorElementType() == SmallestEltTy); 8141 Src.ShuffleVec = DAG.getNode(ISD::BITCAST, dl, ShuffleVT, Src.ShuffleVec); 8142 Src.WindowScale = 8143 SrcEltTy.getFixedSizeInBits() / SmallestEltTy.getFixedSizeInBits(); 8144 Src.WindowBase *= Src.WindowScale; 8145 } 8146 8147 // Final sanity check before we try to actually produce a shuffle. 8148 LLVM_DEBUG(for (auto Src 8149 : Sources) 8150 assert(Src.ShuffleVec.getValueType() == ShuffleVT);); 8151 8152 // The stars all align, our next step is to produce the mask for the shuffle. 8153 SmallVector<int, 8> Mask(ShuffleVT.getVectorNumElements(), -1); 8154 int BitsPerShuffleLane = ShuffleVT.getScalarSizeInBits(); 8155 for (unsigned i = 0; i < VT.getVectorNumElements(); ++i) { 8156 SDValue Entry = Op.getOperand(i); 8157 if (Entry.isUndef()) 8158 continue; 8159 8160 auto Src = find(Sources, Entry.getOperand(0)); 8161 int EltNo = cast<ConstantSDNode>(Entry.getOperand(1))->getSExtValue(); 8162 8163 // EXTRACT_VECTOR_ELT performs an implicit any_ext; BUILD_VECTOR an implicit 8164 // trunc. So only std::min(SrcBits, DestBits) actually get defined in this 8165 // segment. 8166 EVT OrigEltTy = Entry.getOperand(0).getValueType().getVectorElementType(); 8167 int BitsDefined = std::min(OrigEltTy.getScalarSizeInBits(), 8168 VT.getScalarSizeInBits()); 8169 int LanesDefined = BitsDefined / BitsPerShuffleLane; 8170 8171 // This source is expected to fill ResMultiplier lanes of the final shuffle, 8172 // starting at the appropriate offset. 8173 int *LaneMask = &Mask[i * ResMultiplier]; 8174 8175 int ExtractBase = EltNo * Src->WindowScale + Src->WindowBase; 8176 ExtractBase += NumElts * (Src - Sources.begin()); 8177 for (int j = 0; j < LanesDefined; ++j) 8178 LaneMask[j] = ExtractBase + j; 8179 } 8180 8181 // Final check before we try to produce nonsense... 8182 if (!isShuffleMaskLegal(Mask, ShuffleVT)) { 8183 LLVM_DEBUG(dbgs() << "Reshuffle failed: illegal shuffle mask\n"); 8184 return SDValue(); 8185 } 8186 8187 SDValue ShuffleOps[] = { DAG.getUNDEF(ShuffleVT), DAG.getUNDEF(ShuffleVT) }; 8188 for (unsigned i = 0; i < Sources.size(); ++i) 8189 ShuffleOps[i] = Sources[i].ShuffleVec; 8190 8191 SDValue Shuffle = DAG.getVectorShuffle(ShuffleVT, dl, ShuffleOps[0], 8192 ShuffleOps[1], Mask); 8193 SDValue V = DAG.getNode(ISD::BITCAST, dl, VT, Shuffle); 8194 8195 LLVM_DEBUG(dbgs() << "Reshuffle, creating node: "; Shuffle.dump(); 8196 dbgs() << "Reshuffle, creating node: "; V.dump();); 8197 8198 return V; 8199 } 8200 8201 // check if an EXT instruction can handle the shuffle mask when the 8202 // vector sources of the shuffle are the same. 8203 static bool isSingletonEXTMask(ArrayRef<int> M, EVT VT, unsigned &Imm) { 8204 unsigned NumElts = VT.getVectorNumElements(); 8205 8206 // Assume that the first shuffle index is not UNDEF. Fail if it is. 8207 if (M[0] < 0) 8208 return false; 8209 8210 Imm = M[0]; 8211 8212 // If this is a VEXT shuffle, the immediate value is the index of the first 8213 // element. The other shuffle indices must be the successive elements after 8214 // the first one. 8215 unsigned ExpectedElt = Imm; 8216 for (unsigned i = 1; i < NumElts; ++i) { 8217 // Increment the expected index. If it wraps around, just follow it 8218 // back to index zero and keep going. 8219 ++ExpectedElt; 8220 if (ExpectedElt == NumElts) 8221 ExpectedElt = 0; 8222 8223 if (M[i] < 0) 8224 continue; // ignore UNDEF indices 8225 if (ExpectedElt != static_cast<unsigned>(M[i])) 8226 return false; 8227 } 8228 8229 return true; 8230 } 8231 8232 /// Check if a vector shuffle corresponds to a DUP instructions with a larger 8233 /// element width than the vector lane type. If that is the case the function 8234 /// returns true and writes the value of the DUP instruction lane operand into 8235 /// DupLaneOp 8236 static bool isWideDUPMask(ArrayRef<int> M, EVT VT, unsigned BlockSize, 8237 unsigned &DupLaneOp) { 8238 assert((BlockSize == 16 || BlockSize == 32 || BlockSize == 64) && 8239 "Only possible block sizes for wide DUP are: 16, 32, 64"); 8240 8241 if (BlockSize <= VT.getScalarSizeInBits()) 8242 return false; 8243 if (BlockSize % VT.getScalarSizeInBits() != 0) 8244 return false; 8245 if (VT.getSizeInBits() % BlockSize != 0) 8246 return false; 8247 8248 size_t SingleVecNumElements = VT.getVectorNumElements(); 8249 size_t NumEltsPerBlock = BlockSize / VT.getScalarSizeInBits(); 8250 size_t NumBlocks = VT.getSizeInBits() / BlockSize; 8251 8252 // We are looking for masks like 8253 // [0, 1, 0, 1] or [2, 3, 2, 3] or [4, 5, 6, 7, 4, 5, 6, 7] where any element 8254 // might be replaced by 'undefined'. BlockIndices will eventually contain 8255 // lane indices of the duplicated block (i.e. [0, 1], [2, 3] and [4, 5, 6, 7] 8256 // for the above examples) 8257 SmallVector<int, 8> BlockElts(NumEltsPerBlock, -1); 8258 for (size_t BlockIndex = 0; BlockIndex < NumBlocks; BlockIndex++) 8259 for (size_t I = 0; I < NumEltsPerBlock; I++) { 8260 int Elt = M[BlockIndex * NumEltsPerBlock + I]; 8261 if (Elt < 0) 8262 continue; 8263 // For now we don't support shuffles that use the second operand 8264 if ((unsigned)Elt >= SingleVecNumElements) 8265 return false; 8266 if (BlockElts[I] < 0) 8267 BlockElts[I] = Elt; 8268 else if (BlockElts[I] != Elt) 8269 return false; 8270 } 8271 8272 // We found a candidate block (possibly with some undefs). It must be a 8273 // sequence of consecutive integers starting with a value divisible by 8274 // NumEltsPerBlock with some values possibly replaced by undef-s. 8275 8276 // Find first non-undef element 8277 auto FirstRealEltIter = find_if(BlockElts, [](int Elt) { return Elt >= 0; }); 8278 assert(FirstRealEltIter != BlockElts.end() && 8279 "Shuffle with all-undefs must have been caught by previous cases, " 8280 "e.g. isSplat()"); 8281 if (FirstRealEltIter == BlockElts.end()) { 8282 DupLaneOp = 0; 8283 return true; 8284 } 8285 8286 // Index of FirstRealElt in BlockElts 8287 size_t FirstRealIndex = FirstRealEltIter - BlockElts.begin(); 8288 8289 if ((unsigned)*FirstRealEltIter < FirstRealIndex) 8290 return false; 8291 // BlockElts[0] must have the following value if it isn't undef: 8292 size_t Elt0 = *FirstRealEltIter - FirstRealIndex; 8293 8294 // Check the first element 8295 if (Elt0 % NumEltsPerBlock != 0) 8296 return false; 8297 // Check that the sequence indeed consists of consecutive integers (modulo 8298 // undefs) 8299 for (size_t I = 0; I < NumEltsPerBlock; I++) 8300 if (BlockElts[I] >= 0 && (unsigned)BlockElts[I] != Elt0 + I) 8301 return false; 8302 8303 DupLaneOp = Elt0 / NumEltsPerBlock; 8304 return true; 8305 } 8306 8307 // check if an EXT instruction can handle the shuffle mask when the 8308 // vector sources of the shuffle are different. 8309 static bool isEXTMask(ArrayRef<int> M, EVT VT, bool &ReverseEXT, 8310 unsigned &Imm) { 8311 // Look for the first non-undef element. 8312 const int *FirstRealElt = find_if(M, [](int Elt) { return Elt >= 0; }); 8313 8314 // Benefit form APInt to handle overflow when calculating expected element. 8315 unsigned NumElts = VT.getVectorNumElements(); 8316 unsigned MaskBits = APInt(32, NumElts * 2).logBase2(); 8317 APInt ExpectedElt = APInt(MaskBits, *FirstRealElt + 1); 8318 // The following shuffle indices must be the successive elements after the 8319 // first real element. 8320 const int *FirstWrongElt = std::find_if(FirstRealElt + 1, M.end(), 8321 [&](int Elt) {return Elt != ExpectedElt++ && Elt != -1;}); 8322 if (FirstWrongElt != M.end()) 8323 return false; 8324 8325 // The index of an EXT is the first element if it is not UNDEF. 8326 // Watch out for the beginning UNDEFs. The EXT index should be the expected 8327 // value of the first element. E.g. 8328 // <-1, -1, 3, ...> is treated as <1, 2, 3, ...>. 8329 // <-1, -1, 0, 1, ...> is treated as <2*NumElts-2, 2*NumElts-1, 0, 1, ...>. 8330 // ExpectedElt is the last mask index plus 1. 8331 Imm = ExpectedElt.getZExtValue(); 8332 8333 // There are two difference cases requiring to reverse input vectors. 8334 // For example, for vector <4 x i32> we have the following cases, 8335 // Case 1: shufflevector(<4 x i32>,<4 x i32>,<-1, -1, -1, 0>) 8336 // Case 2: shufflevector(<4 x i32>,<4 x i32>,<-1, -1, 7, 0>) 8337 // For both cases, we finally use mask <5, 6, 7, 0>, which requires 8338 // to reverse two input vectors. 8339 if (Imm < NumElts) 8340 ReverseEXT = true; 8341 else 8342 Imm -= NumElts; 8343 8344 return true; 8345 } 8346 8347 /// isREVMask - Check if a vector shuffle corresponds to a REV 8348 /// instruction with the specified blocksize. (The order of the elements 8349 /// within each block of the vector is reversed.) 8350 static bool isREVMask(ArrayRef<int> M, EVT VT, unsigned BlockSize) { 8351 assert((BlockSize == 16 || BlockSize == 32 || BlockSize == 64) && 8352 "Only possible block sizes for REV are: 16, 32, 64"); 8353 8354 unsigned EltSz = VT.getScalarSizeInBits(); 8355 if (EltSz == 64) 8356 return false; 8357 8358 unsigned NumElts = VT.getVectorNumElements(); 8359 unsigned BlockElts = M[0] + 1; 8360 // If the first shuffle index is UNDEF, be optimistic. 8361 if (M[0] < 0) 8362 BlockElts = BlockSize / EltSz; 8363 8364 if (BlockSize <= EltSz || BlockSize != BlockElts * EltSz) 8365 return false; 8366 8367 for (unsigned i = 0; i < NumElts; ++i) { 8368 if (M[i] < 0) 8369 continue; // ignore UNDEF indices 8370 if ((unsigned)M[i] != (i - i % BlockElts) + (BlockElts - 1 - i % BlockElts)) 8371 return false; 8372 } 8373 8374 return true; 8375 } 8376 8377 static bool isZIPMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) { 8378 unsigned NumElts = VT.getVectorNumElements(); 8379 if (NumElts % 2 != 0) 8380 return false; 8381 WhichResult = (M[0] == 0 ? 0 : 1); 8382 unsigned Idx = WhichResult * NumElts / 2; 8383 for (unsigned i = 0; i != NumElts; i += 2) { 8384 if ((M[i] >= 0 && (unsigned)M[i] != Idx) || 8385 (M[i + 1] >= 0 && (unsigned)M[i + 1] != Idx + NumElts)) 8386 return false; 8387 Idx += 1; 8388 } 8389 8390 return true; 8391 } 8392 8393 static bool isUZPMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) { 8394 unsigned NumElts = VT.getVectorNumElements(); 8395 WhichResult = (M[0] == 0 ? 0 : 1); 8396 for (unsigned i = 0; i != NumElts; ++i) { 8397 if (M[i] < 0) 8398 continue; // ignore UNDEF indices 8399 if ((unsigned)M[i] != 2 * i + WhichResult) 8400 return false; 8401 } 8402 8403 return true; 8404 } 8405 8406 static bool isTRNMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) { 8407 unsigned NumElts = VT.getVectorNumElements(); 8408 if (NumElts % 2 != 0) 8409 return false; 8410 WhichResult = (M[0] == 0 ? 0 : 1); 8411 for (unsigned i = 0; i < NumElts; i += 2) { 8412 if ((M[i] >= 0 && (unsigned)M[i] != i + WhichResult) || 8413 (M[i + 1] >= 0 && (unsigned)M[i + 1] != i + NumElts + WhichResult)) 8414 return false; 8415 } 8416 return true; 8417 } 8418 8419 /// isZIP_v_undef_Mask - Special case of isZIPMask for canonical form of 8420 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef". 8421 /// Mask is e.g., <0, 0, 1, 1> instead of <0, 4, 1, 5>. 8422 static bool isZIP_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) { 8423 unsigned NumElts = VT.getVectorNumElements(); 8424 if (NumElts % 2 != 0) 8425 return false; 8426 WhichResult = (M[0] == 0 ? 0 : 1); 8427 unsigned Idx = WhichResult * NumElts / 2; 8428 for (unsigned i = 0; i != NumElts; i += 2) { 8429 if ((M[i] >= 0 && (unsigned)M[i] != Idx) || 8430 (M[i + 1] >= 0 && (unsigned)M[i + 1] != Idx)) 8431 return false; 8432 Idx += 1; 8433 } 8434 8435 return true; 8436 } 8437 8438 /// isUZP_v_undef_Mask - Special case of isUZPMask for canonical form of 8439 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef". 8440 /// Mask is e.g., <0, 2, 0, 2> instead of <0, 2, 4, 6>, 8441 static bool isUZP_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) { 8442 unsigned Half = VT.getVectorNumElements() / 2; 8443 WhichResult = (M[0] == 0 ? 0 : 1); 8444 for (unsigned j = 0; j != 2; ++j) { 8445 unsigned Idx = WhichResult; 8446 for (unsigned i = 0; i != Half; ++i) { 8447 int MIdx = M[i + j * Half]; 8448 if (MIdx >= 0 && (unsigned)MIdx != Idx) 8449 return false; 8450 Idx += 2; 8451 } 8452 } 8453 8454 return true; 8455 } 8456 8457 /// isTRN_v_undef_Mask - Special case of isTRNMask for canonical form of 8458 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef". 8459 /// Mask is e.g., <0, 0, 2, 2> instead of <0, 4, 2, 6>. 8460 static bool isTRN_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) { 8461 unsigned NumElts = VT.getVectorNumElements(); 8462 if (NumElts % 2 != 0) 8463 return false; 8464 WhichResult = (M[0] == 0 ? 0 : 1); 8465 for (unsigned i = 0; i < NumElts; i += 2) { 8466 if ((M[i] >= 0 && (unsigned)M[i] != i + WhichResult) || 8467 (M[i + 1] >= 0 && (unsigned)M[i + 1] != i + WhichResult)) 8468 return false; 8469 } 8470 return true; 8471 } 8472 8473 static bool isINSMask(ArrayRef<int> M, int NumInputElements, 8474 bool &DstIsLeft, int &Anomaly) { 8475 if (M.size() != static_cast<size_t>(NumInputElements)) 8476 return false; 8477 8478 int NumLHSMatch = 0, NumRHSMatch = 0; 8479 int LastLHSMismatch = -1, LastRHSMismatch = -1; 8480 8481 for (int i = 0; i < NumInputElements; ++i) { 8482 if (M[i] == -1) { 8483 ++NumLHSMatch; 8484 ++NumRHSMatch; 8485 continue; 8486 } 8487 8488 if (M[i] == i) 8489 ++NumLHSMatch; 8490 else 8491 LastLHSMismatch = i; 8492 8493 if (M[i] == i + NumInputElements) 8494 ++NumRHSMatch; 8495 else 8496 LastRHSMismatch = i; 8497 } 8498 8499 if (NumLHSMatch == NumInputElements - 1) { 8500 DstIsLeft = true; 8501 Anomaly = LastLHSMismatch; 8502 return true; 8503 } else if (NumRHSMatch == NumInputElements - 1) { 8504 DstIsLeft = false; 8505 Anomaly = LastRHSMismatch; 8506 return true; 8507 } 8508 8509 return false; 8510 } 8511 8512 static bool isConcatMask(ArrayRef<int> Mask, EVT VT, bool SplitLHS) { 8513 if (VT.getSizeInBits() != 128) 8514 return false; 8515 8516 unsigned NumElts = VT.getVectorNumElements(); 8517 8518 for (int I = 0, E = NumElts / 2; I != E; I++) { 8519 if (Mask[I] != I) 8520 return false; 8521 } 8522 8523 int Offset = NumElts / 2; 8524 for (int I = NumElts / 2, E = NumElts; I != E; I++) { 8525 if (Mask[I] != I + SplitLHS * Offset) 8526 return false; 8527 } 8528 8529 return true; 8530 } 8531 8532 static SDValue tryFormConcatFromShuffle(SDValue Op, SelectionDAG &DAG) { 8533 SDLoc DL(Op); 8534 EVT VT = Op.getValueType(); 8535 SDValue V0 = Op.getOperand(0); 8536 SDValue V1 = Op.getOperand(1); 8537 ArrayRef<int> Mask = cast<ShuffleVectorSDNode>(Op)->getMask(); 8538 8539 if (VT.getVectorElementType() != V0.getValueType().getVectorElementType() || 8540 VT.getVectorElementType() != V1.getValueType().getVectorElementType()) 8541 return SDValue(); 8542 8543 bool SplitV0 = V0.getValueSizeInBits() == 128; 8544 8545 if (!isConcatMask(Mask, VT, SplitV0)) 8546 return SDValue(); 8547 8548 EVT CastVT = VT.getHalfNumVectorElementsVT(*DAG.getContext()); 8549 if (SplitV0) { 8550 V0 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, CastVT, V0, 8551 DAG.getConstant(0, DL, MVT::i64)); 8552 } 8553 if (V1.getValueSizeInBits() == 128) { 8554 V1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, CastVT, V1, 8555 DAG.getConstant(0, DL, MVT::i64)); 8556 } 8557 return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, V0, V1); 8558 } 8559 8560 /// GeneratePerfectShuffle - Given an entry in the perfect-shuffle table, emit 8561 /// the specified operations to build the shuffle. 8562 static SDValue GeneratePerfectShuffle(unsigned PFEntry, SDValue LHS, 8563 SDValue RHS, SelectionDAG &DAG, 8564 const SDLoc &dl) { 8565 unsigned OpNum = (PFEntry >> 26) & 0x0F; 8566 unsigned LHSID = (PFEntry >> 13) & ((1 << 13) - 1); 8567 unsigned RHSID = (PFEntry >> 0) & ((1 << 13) - 1); 8568 8569 enum { 8570 OP_COPY = 0, // Copy, used for things like <u,u,u,3> to say it is <0,1,2,3> 8571 OP_VREV, 8572 OP_VDUP0, 8573 OP_VDUP1, 8574 OP_VDUP2, 8575 OP_VDUP3, 8576 OP_VEXT1, 8577 OP_VEXT2, 8578 OP_VEXT3, 8579 OP_VUZPL, // VUZP, left result 8580 OP_VUZPR, // VUZP, right result 8581 OP_VZIPL, // VZIP, left result 8582 OP_VZIPR, // VZIP, right result 8583 OP_VTRNL, // VTRN, left result 8584 OP_VTRNR // VTRN, right result 8585 }; 8586 8587 if (OpNum == OP_COPY) { 8588 if (LHSID == (1 * 9 + 2) * 9 + 3) 8589 return LHS; 8590 assert(LHSID == ((4 * 9 + 5) * 9 + 6) * 9 + 7 && "Illegal OP_COPY!"); 8591 return RHS; 8592 } 8593 8594 SDValue OpLHS, OpRHS; 8595 OpLHS = GeneratePerfectShuffle(PerfectShuffleTable[LHSID], LHS, RHS, DAG, dl); 8596 OpRHS = GeneratePerfectShuffle(PerfectShuffleTable[RHSID], LHS, RHS, DAG, dl); 8597 EVT VT = OpLHS.getValueType(); 8598 8599 switch (OpNum) { 8600 default: 8601 llvm_unreachable("Unknown shuffle opcode!"); 8602 case OP_VREV: 8603 // VREV divides the vector in half and swaps within the half. 8604 if (VT.getVectorElementType() == MVT::i32 || 8605 VT.getVectorElementType() == MVT::f32) 8606 return DAG.getNode(AArch64ISD::REV64, dl, VT, OpLHS); 8607 // vrev <4 x i16> -> REV32 8608 if (VT.getVectorElementType() == MVT::i16 || 8609 VT.getVectorElementType() == MVT::f16 || 8610 VT.getVectorElementType() == MVT::bf16) 8611 return DAG.getNode(AArch64ISD::REV32, dl, VT, OpLHS); 8612 // vrev <4 x i8> -> REV16 8613 assert(VT.getVectorElementType() == MVT::i8); 8614 return DAG.getNode(AArch64ISD::REV16, dl, VT, OpLHS); 8615 case OP_VDUP0: 8616 case OP_VDUP1: 8617 case OP_VDUP2: 8618 case OP_VDUP3: { 8619 EVT EltTy = VT.getVectorElementType(); 8620 unsigned Opcode; 8621 if (EltTy == MVT::i8) 8622 Opcode = AArch64ISD::DUPLANE8; 8623 else if (EltTy == MVT::i16 || EltTy == MVT::f16 || EltTy == MVT::bf16) 8624 Opcode = AArch64ISD::DUPLANE16; 8625 else if (EltTy == MVT::i32 || EltTy == MVT::f32) 8626 Opcode = AArch64ISD::DUPLANE32; 8627 else if (EltTy == MVT::i64 || EltTy == MVT::f64) 8628 Opcode = AArch64ISD::DUPLANE64; 8629 else 8630 llvm_unreachable("Invalid vector element type?"); 8631 8632 if (VT.getSizeInBits() == 64) 8633 OpLHS = WidenVector(OpLHS, DAG); 8634 SDValue Lane = DAG.getConstant(OpNum - OP_VDUP0, dl, MVT::i64); 8635 return DAG.getNode(Opcode, dl, VT, OpLHS, Lane); 8636 } 8637 case OP_VEXT1: 8638 case OP_VEXT2: 8639 case OP_VEXT3: { 8640 unsigned Imm = (OpNum - OP_VEXT1 + 1) * getExtFactor(OpLHS); 8641 return DAG.getNode(AArch64ISD::EXT, dl, VT, OpLHS, OpRHS, 8642 DAG.getConstant(Imm, dl, MVT::i32)); 8643 } 8644 case OP_VUZPL: 8645 return DAG.getNode(AArch64ISD::UZP1, dl, DAG.getVTList(VT, VT), OpLHS, 8646 OpRHS); 8647 case OP_VUZPR: 8648 return DAG.getNode(AArch64ISD::UZP2, dl, DAG.getVTList(VT, VT), OpLHS, 8649 OpRHS); 8650 case OP_VZIPL: 8651 return DAG.getNode(AArch64ISD::ZIP1, dl, DAG.getVTList(VT, VT), OpLHS, 8652 OpRHS); 8653 case OP_VZIPR: 8654 return DAG.getNode(AArch64ISD::ZIP2, dl, DAG.getVTList(VT, VT), OpLHS, 8655 OpRHS); 8656 case OP_VTRNL: 8657 return DAG.getNode(AArch64ISD::TRN1, dl, DAG.getVTList(VT, VT), OpLHS, 8658 OpRHS); 8659 case OP_VTRNR: 8660 return DAG.getNode(AArch64ISD::TRN2, dl, DAG.getVTList(VT, VT), OpLHS, 8661 OpRHS); 8662 } 8663 } 8664 8665 static SDValue GenerateTBL(SDValue Op, ArrayRef<int> ShuffleMask, 8666 SelectionDAG &DAG) { 8667 // Check to see if we can use the TBL instruction. 8668 SDValue V1 = Op.getOperand(0); 8669 SDValue V2 = Op.getOperand(1); 8670 SDLoc DL(Op); 8671 8672 EVT EltVT = Op.getValueType().getVectorElementType(); 8673 unsigned BytesPerElt = EltVT.getSizeInBits() / 8; 8674 8675 SmallVector<SDValue, 8> TBLMask; 8676 for (int Val : ShuffleMask) { 8677 for (unsigned Byte = 0; Byte < BytesPerElt; ++Byte) { 8678 unsigned Offset = Byte + Val * BytesPerElt; 8679 TBLMask.push_back(DAG.getConstant(Offset, DL, MVT::i32)); 8680 } 8681 } 8682 8683 MVT IndexVT = MVT::v8i8; 8684 unsigned IndexLen = 8; 8685 if (Op.getValueSizeInBits() == 128) { 8686 IndexVT = MVT::v16i8; 8687 IndexLen = 16; 8688 } 8689 8690 SDValue V1Cst = DAG.getNode(ISD::BITCAST, DL, IndexVT, V1); 8691 SDValue V2Cst = DAG.getNode(ISD::BITCAST, DL, IndexVT, V2); 8692 8693 SDValue Shuffle; 8694 if (V2.getNode()->isUndef()) { 8695 if (IndexLen == 8) 8696 V1Cst = DAG.getNode(ISD::CONCAT_VECTORS, DL, MVT::v16i8, V1Cst, V1Cst); 8697 Shuffle = DAG.getNode( 8698 ISD::INTRINSIC_WO_CHAIN, DL, IndexVT, 8699 DAG.getConstant(Intrinsic::aarch64_neon_tbl1, DL, MVT::i32), V1Cst, 8700 DAG.getBuildVector(IndexVT, DL, 8701 makeArrayRef(TBLMask.data(), IndexLen))); 8702 } else { 8703 if (IndexLen == 8) { 8704 V1Cst = DAG.getNode(ISD::CONCAT_VECTORS, DL, MVT::v16i8, V1Cst, V2Cst); 8705 Shuffle = DAG.getNode( 8706 ISD::INTRINSIC_WO_CHAIN, DL, IndexVT, 8707 DAG.getConstant(Intrinsic::aarch64_neon_tbl1, DL, MVT::i32), V1Cst, 8708 DAG.getBuildVector(IndexVT, DL, 8709 makeArrayRef(TBLMask.data(), IndexLen))); 8710 } else { 8711 // FIXME: We cannot, for the moment, emit a TBL2 instruction because we 8712 // cannot currently represent the register constraints on the input 8713 // table registers. 8714 // Shuffle = DAG.getNode(AArch64ISD::TBL2, DL, IndexVT, V1Cst, V2Cst, 8715 // DAG.getBuildVector(IndexVT, DL, &TBLMask[0], 8716 // IndexLen)); 8717 Shuffle = DAG.getNode( 8718 ISD::INTRINSIC_WO_CHAIN, DL, IndexVT, 8719 DAG.getConstant(Intrinsic::aarch64_neon_tbl2, DL, MVT::i32), V1Cst, 8720 V2Cst, DAG.getBuildVector(IndexVT, DL, 8721 makeArrayRef(TBLMask.data(), IndexLen))); 8722 } 8723 } 8724 return DAG.getNode(ISD::BITCAST, DL, Op.getValueType(), Shuffle); 8725 } 8726 8727 static unsigned getDUPLANEOp(EVT EltType) { 8728 if (EltType == MVT::i8) 8729 return AArch64ISD::DUPLANE8; 8730 if (EltType == MVT::i16 || EltType == MVT::f16 || EltType == MVT::bf16) 8731 return AArch64ISD::DUPLANE16; 8732 if (EltType == MVT::i32 || EltType == MVT::f32) 8733 return AArch64ISD::DUPLANE32; 8734 if (EltType == MVT::i64 || EltType == MVT::f64) 8735 return AArch64ISD::DUPLANE64; 8736 8737 llvm_unreachable("Invalid vector element type?"); 8738 } 8739 8740 static SDValue constructDup(SDValue V, int Lane, SDLoc dl, EVT VT, 8741 unsigned Opcode, SelectionDAG &DAG) { 8742 // Try to eliminate a bitcasted extract subvector before a DUPLANE. 8743 auto getScaledOffsetDup = [](SDValue BitCast, int &LaneC, MVT &CastVT) { 8744 // Match: dup (bitcast (extract_subv X, C)), LaneC 8745 if (BitCast.getOpcode() != ISD::BITCAST || 8746 BitCast.getOperand(0).getOpcode() != ISD::EXTRACT_SUBVECTOR) 8747 return false; 8748 8749 // The extract index must align in the destination type. That may not 8750 // happen if the bitcast is from narrow to wide type. 8751 SDValue Extract = BitCast.getOperand(0); 8752 unsigned ExtIdx = Extract.getConstantOperandVal(1); 8753 unsigned SrcEltBitWidth = Extract.getScalarValueSizeInBits(); 8754 unsigned ExtIdxInBits = ExtIdx * SrcEltBitWidth; 8755 unsigned CastedEltBitWidth = BitCast.getScalarValueSizeInBits(); 8756 if (ExtIdxInBits % CastedEltBitWidth != 0) 8757 return false; 8758 8759 // Update the lane value by offsetting with the scaled extract index. 8760 LaneC += ExtIdxInBits / CastedEltBitWidth; 8761 8762 // Determine the casted vector type of the wide vector input. 8763 // dup (bitcast (extract_subv X, C)), LaneC --> dup (bitcast X), LaneC' 8764 // Examples: 8765 // dup (bitcast (extract_subv v2f64 X, 1) to v2f32), 1 --> dup v4f32 X, 3 8766 // dup (bitcast (extract_subv v16i8 X, 8) to v4i16), 1 --> dup v8i16 X, 5 8767 unsigned SrcVecNumElts = 8768 Extract.getOperand(0).getValueSizeInBits() / CastedEltBitWidth; 8769 CastVT = MVT::getVectorVT(BitCast.getSimpleValueType().getScalarType(), 8770 SrcVecNumElts); 8771 return true; 8772 }; 8773 MVT CastVT; 8774 if (getScaledOffsetDup(V, Lane, CastVT)) { 8775 V = DAG.getBitcast(CastVT, V.getOperand(0).getOperand(0)); 8776 } else if (V.getOpcode() == ISD::EXTRACT_SUBVECTOR) { 8777 // The lane is incremented by the index of the extract. 8778 // Example: dup v2f32 (extract v4f32 X, 2), 1 --> dup v4f32 X, 3 8779 Lane += V.getConstantOperandVal(1); 8780 V = V.getOperand(0); 8781 } else if (V.getOpcode() == ISD::CONCAT_VECTORS) { 8782 // The lane is decremented if we are splatting from the 2nd operand. 8783 // Example: dup v4i32 (concat v2i32 X, v2i32 Y), 3 --> dup v4i32 Y, 1 8784 unsigned Idx = Lane >= (int)VT.getVectorNumElements() / 2; 8785 Lane -= Idx * VT.getVectorNumElements() / 2; 8786 V = WidenVector(V.getOperand(Idx), DAG); 8787 } else if (VT.getSizeInBits() == 64) { 8788 // Widen the operand to 128-bit register with undef. 8789 V = WidenVector(V, DAG); 8790 } 8791 return DAG.getNode(Opcode, dl, VT, V, DAG.getConstant(Lane, dl, MVT::i64)); 8792 } 8793 8794 SDValue AArch64TargetLowering::LowerVECTOR_SHUFFLE(SDValue Op, 8795 SelectionDAG &DAG) const { 8796 SDLoc dl(Op); 8797 EVT VT = Op.getValueType(); 8798 8799 ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(Op.getNode()); 8800 8801 // Convert shuffles that are directly supported on NEON to target-specific 8802 // DAG nodes, instead of keeping them as shuffles and matching them again 8803 // during code selection. This is more efficient and avoids the possibility 8804 // of inconsistencies between legalization and selection. 8805 ArrayRef<int> ShuffleMask = SVN->getMask(); 8806 8807 SDValue V1 = Op.getOperand(0); 8808 SDValue V2 = Op.getOperand(1); 8809 8810 if (SVN->isSplat()) { 8811 int Lane = SVN->getSplatIndex(); 8812 // If this is undef splat, generate it via "just" vdup, if possible. 8813 if (Lane == -1) 8814 Lane = 0; 8815 8816 if (Lane == 0 && V1.getOpcode() == ISD::SCALAR_TO_VECTOR) 8817 return DAG.getNode(AArch64ISD::DUP, dl, V1.getValueType(), 8818 V1.getOperand(0)); 8819 // Test if V1 is a BUILD_VECTOR and the lane being referenced is a non- 8820 // constant. If so, we can just reference the lane's definition directly. 8821 if (V1.getOpcode() == ISD::BUILD_VECTOR && 8822 !isa<ConstantSDNode>(V1.getOperand(Lane))) 8823 return DAG.getNode(AArch64ISD::DUP, dl, VT, V1.getOperand(Lane)); 8824 8825 // Otherwise, duplicate from the lane of the input vector. 8826 unsigned Opcode = getDUPLANEOp(V1.getValueType().getVectorElementType()); 8827 return constructDup(V1, Lane, dl, VT, Opcode, DAG); 8828 } 8829 8830 // Check if the mask matches a DUP for a wider element 8831 for (unsigned LaneSize : {64U, 32U, 16U}) { 8832 unsigned Lane = 0; 8833 if (isWideDUPMask(ShuffleMask, VT, LaneSize, Lane)) { 8834 unsigned Opcode = LaneSize == 64 ? AArch64ISD::DUPLANE64 8835 : LaneSize == 32 ? AArch64ISD::DUPLANE32 8836 : AArch64ISD::DUPLANE16; 8837 // Cast V1 to an integer vector with required lane size 8838 MVT NewEltTy = MVT::getIntegerVT(LaneSize); 8839 unsigned NewEltCount = VT.getSizeInBits() / LaneSize; 8840 MVT NewVecTy = MVT::getVectorVT(NewEltTy, NewEltCount); 8841 V1 = DAG.getBitcast(NewVecTy, V1); 8842 // Constuct the DUP instruction 8843 V1 = constructDup(V1, Lane, dl, NewVecTy, Opcode, DAG); 8844 // Cast back to the original type 8845 return DAG.getBitcast(VT, V1); 8846 } 8847 } 8848 8849 if (isREVMask(ShuffleMask, VT, 64)) 8850 return DAG.getNode(AArch64ISD::REV64, dl, V1.getValueType(), V1, V2); 8851 if (isREVMask(ShuffleMask, VT, 32)) 8852 return DAG.getNode(AArch64ISD::REV32, dl, V1.getValueType(), V1, V2); 8853 if (isREVMask(ShuffleMask, VT, 16)) 8854 return DAG.getNode(AArch64ISD::REV16, dl, V1.getValueType(), V1, V2); 8855 8856 bool ReverseEXT = false; 8857 unsigned Imm; 8858 if (isEXTMask(ShuffleMask, VT, ReverseEXT, Imm)) { 8859 if (ReverseEXT) 8860 std::swap(V1, V2); 8861 Imm *= getExtFactor(V1); 8862 return DAG.getNode(AArch64ISD::EXT, dl, V1.getValueType(), V1, V2, 8863 DAG.getConstant(Imm, dl, MVT::i32)); 8864 } else if (V2->isUndef() && isSingletonEXTMask(ShuffleMask, VT, Imm)) { 8865 Imm *= getExtFactor(V1); 8866 return DAG.getNode(AArch64ISD::EXT, dl, V1.getValueType(), V1, V1, 8867 DAG.getConstant(Imm, dl, MVT::i32)); 8868 } 8869 8870 unsigned WhichResult; 8871 if (isZIPMask(ShuffleMask, VT, WhichResult)) { 8872 unsigned Opc = (WhichResult == 0) ? AArch64ISD::ZIP1 : AArch64ISD::ZIP2; 8873 return DAG.getNode(Opc, dl, V1.getValueType(), V1, V2); 8874 } 8875 if (isUZPMask(ShuffleMask, VT, WhichResult)) { 8876 unsigned Opc = (WhichResult == 0) ? AArch64ISD::UZP1 : AArch64ISD::UZP2; 8877 return DAG.getNode(Opc, dl, V1.getValueType(), V1, V2); 8878 } 8879 if (isTRNMask(ShuffleMask, VT, WhichResult)) { 8880 unsigned Opc = (WhichResult == 0) ? AArch64ISD::TRN1 : AArch64ISD::TRN2; 8881 return DAG.getNode(Opc, dl, V1.getValueType(), V1, V2); 8882 } 8883 8884 if (isZIP_v_undef_Mask(ShuffleMask, VT, WhichResult)) { 8885 unsigned Opc = (WhichResult == 0) ? AArch64ISD::ZIP1 : AArch64ISD::ZIP2; 8886 return DAG.getNode(Opc, dl, V1.getValueType(), V1, V1); 8887 } 8888 if (isUZP_v_undef_Mask(ShuffleMask, VT, WhichResult)) { 8889 unsigned Opc = (WhichResult == 0) ? AArch64ISD::UZP1 : AArch64ISD::UZP2; 8890 return DAG.getNode(Opc, dl, V1.getValueType(), V1, V1); 8891 } 8892 if (isTRN_v_undef_Mask(ShuffleMask, VT, WhichResult)) { 8893 unsigned Opc = (WhichResult == 0) ? AArch64ISD::TRN1 : AArch64ISD::TRN2; 8894 return DAG.getNode(Opc, dl, V1.getValueType(), V1, V1); 8895 } 8896 8897 if (SDValue Concat = tryFormConcatFromShuffle(Op, DAG)) 8898 return Concat; 8899 8900 bool DstIsLeft; 8901 int Anomaly; 8902 int NumInputElements = V1.getValueType().getVectorNumElements(); 8903 if (isINSMask(ShuffleMask, NumInputElements, DstIsLeft, Anomaly)) { 8904 SDValue DstVec = DstIsLeft ? V1 : V2; 8905 SDValue DstLaneV = DAG.getConstant(Anomaly, dl, MVT::i64); 8906 8907 SDValue SrcVec = V1; 8908 int SrcLane = ShuffleMask[Anomaly]; 8909 if (SrcLane >= NumInputElements) { 8910 SrcVec = V2; 8911 SrcLane -= VT.getVectorNumElements(); 8912 } 8913 SDValue SrcLaneV = DAG.getConstant(SrcLane, dl, MVT::i64); 8914 8915 EVT ScalarVT = VT.getVectorElementType(); 8916 8917 if (ScalarVT.getFixedSizeInBits() < 32 && ScalarVT.isInteger()) 8918 ScalarVT = MVT::i32; 8919 8920 return DAG.getNode( 8921 ISD::INSERT_VECTOR_ELT, dl, VT, DstVec, 8922 DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, ScalarVT, SrcVec, SrcLaneV), 8923 DstLaneV); 8924 } 8925 8926 // If the shuffle is not directly supported and it has 4 elements, use 8927 // the PerfectShuffle-generated table to synthesize it from other shuffles. 8928 unsigned NumElts = VT.getVectorNumElements(); 8929 if (NumElts == 4) { 8930 unsigned PFIndexes[4]; 8931 for (unsigned i = 0; i != 4; ++i) { 8932 if (ShuffleMask[i] < 0) 8933 PFIndexes[i] = 8; 8934 else 8935 PFIndexes[i] = ShuffleMask[i]; 8936 } 8937 8938 // Compute the index in the perfect shuffle table. 8939 unsigned PFTableIndex = PFIndexes[0] * 9 * 9 * 9 + PFIndexes[1] * 9 * 9 + 8940 PFIndexes[2] * 9 + PFIndexes[3]; 8941 unsigned PFEntry = PerfectShuffleTable[PFTableIndex]; 8942 unsigned Cost = (PFEntry >> 30); 8943 8944 if (Cost <= 4) 8945 return GeneratePerfectShuffle(PFEntry, V1, V2, DAG, dl); 8946 } 8947 8948 return GenerateTBL(Op, ShuffleMask, DAG); 8949 } 8950 8951 SDValue AArch64TargetLowering::LowerSPLAT_VECTOR(SDValue Op, 8952 SelectionDAG &DAG) const { 8953 SDLoc dl(Op); 8954 EVT VT = Op.getValueType(); 8955 EVT ElemVT = VT.getScalarType(); 8956 SDValue SplatVal = Op.getOperand(0); 8957 8958 if (useSVEForFixedLengthVectorVT(VT)) 8959 return LowerToScalableOp(Op, DAG); 8960 8961 // Extend input splat value where needed to fit into a GPR (32b or 64b only) 8962 // FPRs don't have this restriction. 8963 switch (ElemVT.getSimpleVT().SimpleTy) { 8964 case MVT::i1: { 8965 // The only legal i1 vectors are SVE vectors, so we can use SVE-specific 8966 // lowering code. 8967 if (auto *ConstVal = dyn_cast<ConstantSDNode>(SplatVal)) { 8968 if (ConstVal->isOne()) 8969 return getPTrue(DAG, dl, VT, AArch64SVEPredPattern::all); 8970 // TODO: Add special case for constant false 8971 } 8972 // The general case of i1. There isn't any natural way to do this, 8973 // so we use some trickery with whilelo. 8974 SplatVal = DAG.getAnyExtOrTrunc(SplatVal, dl, MVT::i64); 8975 SplatVal = DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, MVT::i64, SplatVal, 8976 DAG.getValueType(MVT::i1)); 8977 SDValue ID = DAG.getTargetConstant(Intrinsic::aarch64_sve_whilelo, dl, 8978 MVT::i64); 8979 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT, ID, 8980 DAG.getConstant(0, dl, MVT::i64), SplatVal); 8981 } 8982 case MVT::i8: 8983 case MVT::i16: 8984 case MVT::i32: 8985 SplatVal = DAG.getAnyExtOrTrunc(SplatVal, dl, MVT::i32); 8986 break; 8987 case MVT::i64: 8988 SplatVal = DAG.getAnyExtOrTrunc(SplatVal, dl, MVT::i64); 8989 break; 8990 case MVT::f16: 8991 case MVT::bf16: 8992 case MVT::f32: 8993 case MVT::f64: 8994 // Fine as is 8995 break; 8996 default: 8997 report_fatal_error("Unsupported SPLAT_VECTOR input operand type"); 8998 } 8999 9000 return DAG.getNode(AArch64ISD::DUP, dl, VT, SplatVal); 9001 } 9002 9003 SDValue AArch64TargetLowering::LowerDUPQLane(SDValue Op, 9004 SelectionDAG &DAG) const { 9005 SDLoc DL(Op); 9006 9007 EVT VT = Op.getValueType(); 9008 if (!isTypeLegal(VT) || !VT.isScalableVector()) 9009 return SDValue(); 9010 9011 // Current lowering only supports the SVE-ACLE types. 9012 if (VT.getSizeInBits().getKnownMinSize() != AArch64::SVEBitsPerBlock) 9013 return SDValue(); 9014 9015 // The DUPQ operation is indepedent of element type so normalise to i64s. 9016 SDValue V = DAG.getNode(ISD::BITCAST, DL, MVT::nxv2i64, Op.getOperand(1)); 9017 SDValue Idx128 = Op.getOperand(2); 9018 9019 // DUPQ can be used when idx is in range. 9020 auto *CIdx = dyn_cast<ConstantSDNode>(Idx128); 9021 if (CIdx && (CIdx->getZExtValue() <= 3)) { 9022 SDValue CI = DAG.getTargetConstant(CIdx->getZExtValue(), DL, MVT::i64); 9023 SDNode *DUPQ = 9024 DAG.getMachineNode(AArch64::DUP_ZZI_Q, DL, MVT::nxv2i64, V, CI); 9025 return DAG.getNode(ISD::BITCAST, DL, VT, SDValue(DUPQ, 0)); 9026 } 9027 9028 // The ACLE says this must produce the same result as: 9029 // svtbl(data, svadd_x(svptrue_b64(), 9030 // svand_x(svptrue_b64(), svindex_u64(0, 1), 1), 9031 // index * 2)) 9032 SDValue One = DAG.getConstant(1, DL, MVT::i64); 9033 SDValue SplatOne = DAG.getNode(ISD::SPLAT_VECTOR, DL, MVT::nxv2i64, One); 9034 9035 // create the vector 0,1,0,1,... 9036 SDValue Zero = DAG.getConstant(0, DL, MVT::i64); 9037 SDValue SV = DAG.getNode(AArch64ISD::INDEX_VECTOR, 9038 DL, MVT::nxv2i64, Zero, One); 9039 SV = DAG.getNode(ISD::AND, DL, MVT::nxv2i64, SV, SplatOne); 9040 9041 // create the vector idx64,idx64+1,idx64,idx64+1,... 9042 SDValue Idx64 = DAG.getNode(ISD::ADD, DL, MVT::i64, Idx128, Idx128); 9043 SDValue SplatIdx64 = DAG.getNode(ISD::SPLAT_VECTOR, DL, MVT::nxv2i64, Idx64); 9044 SDValue ShuffleMask = DAG.getNode(ISD::ADD, DL, MVT::nxv2i64, SV, SplatIdx64); 9045 9046 // create the vector Val[idx64],Val[idx64+1],Val[idx64],Val[idx64+1],... 9047 SDValue TBL = DAG.getNode(AArch64ISD::TBL, DL, MVT::nxv2i64, V, ShuffleMask); 9048 return DAG.getNode(ISD::BITCAST, DL, VT, TBL); 9049 } 9050 9051 9052 static bool resolveBuildVector(BuildVectorSDNode *BVN, APInt &CnstBits, 9053 APInt &UndefBits) { 9054 EVT VT = BVN->getValueType(0); 9055 APInt SplatBits, SplatUndef; 9056 unsigned SplatBitSize; 9057 bool HasAnyUndefs; 9058 if (BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs)) { 9059 unsigned NumSplats = VT.getSizeInBits() / SplatBitSize; 9060 9061 for (unsigned i = 0; i < NumSplats; ++i) { 9062 CnstBits <<= SplatBitSize; 9063 UndefBits <<= SplatBitSize; 9064 CnstBits |= SplatBits.zextOrTrunc(VT.getSizeInBits()); 9065 UndefBits |= (SplatBits ^ SplatUndef).zextOrTrunc(VT.getSizeInBits()); 9066 } 9067 9068 return true; 9069 } 9070 9071 return false; 9072 } 9073 9074 // Try 64-bit splatted SIMD immediate. 9075 static SDValue tryAdvSIMDModImm64(unsigned NewOp, SDValue Op, SelectionDAG &DAG, 9076 const APInt &Bits) { 9077 if (Bits.getHiBits(64) == Bits.getLoBits(64)) { 9078 uint64_t Value = Bits.zextOrTrunc(64).getZExtValue(); 9079 EVT VT = Op.getValueType(); 9080 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v2i64 : MVT::f64; 9081 9082 if (AArch64_AM::isAdvSIMDModImmType10(Value)) { 9083 Value = AArch64_AM::encodeAdvSIMDModImmType10(Value); 9084 9085 SDLoc dl(Op); 9086 SDValue Mov = DAG.getNode(NewOp, dl, MovTy, 9087 DAG.getConstant(Value, dl, MVT::i32)); 9088 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov); 9089 } 9090 } 9091 9092 return SDValue(); 9093 } 9094 9095 // Try 32-bit splatted SIMD immediate. 9096 static SDValue tryAdvSIMDModImm32(unsigned NewOp, SDValue Op, SelectionDAG &DAG, 9097 const APInt &Bits, 9098 const SDValue *LHS = nullptr) { 9099 if (Bits.getHiBits(64) == Bits.getLoBits(64)) { 9100 uint64_t Value = Bits.zextOrTrunc(64).getZExtValue(); 9101 EVT VT = Op.getValueType(); 9102 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32; 9103 bool isAdvSIMDModImm = false; 9104 uint64_t Shift; 9105 9106 if ((isAdvSIMDModImm = AArch64_AM::isAdvSIMDModImmType1(Value))) { 9107 Value = AArch64_AM::encodeAdvSIMDModImmType1(Value); 9108 Shift = 0; 9109 } 9110 else if ((isAdvSIMDModImm = AArch64_AM::isAdvSIMDModImmType2(Value))) { 9111 Value = AArch64_AM::encodeAdvSIMDModImmType2(Value); 9112 Shift = 8; 9113 } 9114 else if ((isAdvSIMDModImm = AArch64_AM::isAdvSIMDModImmType3(Value))) { 9115 Value = AArch64_AM::encodeAdvSIMDModImmType3(Value); 9116 Shift = 16; 9117 } 9118 else if ((isAdvSIMDModImm = AArch64_AM::isAdvSIMDModImmType4(Value))) { 9119 Value = AArch64_AM::encodeAdvSIMDModImmType4(Value); 9120 Shift = 24; 9121 } 9122 9123 if (isAdvSIMDModImm) { 9124 SDLoc dl(Op); 9125 SDValue Mov; 9126 9127 if (LHS) 9128 Mov = DAG.getNode(NewOp, dl, MovTy, *LHS, 9129 DAG.getConstant(Value, dl, MVT::i32), 9130 DAG.getConstant(Shift, dl, MVT::i32)); 9131 else 9132 Mov = DAG.getNode(NewOp, dl, MovTy, 9133 DAG.getConstant(Value, dl, MVT::i32), 9134 DAG.getConstant(Shift, dl, MVT::i32)); 9135 9136 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov); 9137 } 9138 } 9139 9140 return SDValue(); 9141 } 9142 9143 // Try 16-bit splatted SIMD immediate. 9144 static SDValue tryAdvSIMDModImm16(unsigned NewOp, SDValue Op, SelectionDAG &DAG, 9145 const APInt &Bits, 9146 const SDValue *LHS = nullptr) { 9147 if (Bits.getHiBits(64) == Bits.getLoBits(64)) { 9148 uint64_t Value = Bits.zextOrTrunc(64).getZExtValue(); 9149 EVT VT = Op.getValueType(); 9150 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v8i16 : MVT::v4i16; 9151 bool isAdvSIMDModImm = false; 9152 uint64_t Shift; 9153 9154 if ((isAdvSIMDModImm = AArch64_AM::isAdvSIMDModImmType5(Value))) { 9155 Value = AArch64_AM::encodeAdvSIMDModImmType5(Value); 9156 Shift = 0; 9157 } 9158 else if ((isAdvSIMDModImm = AArch64_AM::isAdvSIMDModImmType6(Value))) { 9159 Value = AArch64_AM::encodeAdvSIMDModImmType6(Value); 9160 Shift = 8; 9161 } 9162 9163 if (isAdvSIMDModImm) { 9164 SDLoc dl(Op); 9165 SDValue Mov; 9166 9167 if (LHS) 9168 Mov = DAG.getNode(NewOp, dl, MovTy, *LHS, 9169 DAG.getConstant(Value, dl, MVT::i32), 9170 DAG.getConstant(Shift, dl, MVT::i32)); 9171 else 9172 Mov = DAG.getNode(NewOp, dl, MovTy, 9173 DAG.getConstant(Value, dl, MVT::i32), 9174 DAG.getConstant(Shift, dl, MVT::i32)); 9175 9176 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov); 9177 } 9178 } 9179 9180 return SDValue(); 9181 } 9182 9183 // Try 32-bit splatted SIMD immediate with shifted ones. 9184 static SDValue tryAdvSIMDModImm321s(unsigned NewOp, SDValue Op, 9185 SelectionDAG &DAG, const APInt &Bits) { 9186 if (Bits.getHiBits(64) == Bits.getLoBits(64)) { 9187 uint64_t Value = Bits.zextOrTrunc(64).getZExtValue(); 9188 EVT VT = Op.getValueType(); 9189 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32; 9190 bool isAdvSIMDModImm = false; 9191 uint64_t Shift; 9192 9193 if ((isAdvSIMDModImm = AArch64_AM::isAdvSIMDModImmType7(Value))) { 9194 Value = AArch64_AM::encodeAdvSIMDModImmType7(Value); 9195 Shift = 264; 9196 } 9197 else if ((isAdvSIMDModImm = AArch64_AM::isAdvSIMDModImmType8(Value))) { 9198 Value = AArch64_AM::encodeAdvSIMDModImmType8(Value); 9199 Shift = 272; 9200 } 9201 9202 if (isAdvSIMDModImm) { 9203 SDLoc dl(Op); 9204 SDValue Mov = DAG.getNode(NewOp, dl, MovTy, 9205 DAG.getConstant(Value, dl, MVT::i32), 9206 DAG.getConstant(Shift, dl, MVT::i32)); 9207 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov); 9208 } 9209 } 9210 9211 return SDValue(); 9212 } 9213 9214 // Try 8-bit splatted SIMD immediate. 9215 static SDValue tryAdvSIMDModImm8(unsigned NewOp, SDValue Op, SelectionDAG &DAG, 9216 const APInt &Bits) { 9217 if (Bits.getHiBits(64) == Bits.getLoBits(64)) { 9218 uint64_t Value = Bits.zextOrTrunc(64).getZExtValue(); 9219 EVT VT = Op.getValueType(); 9220 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v16i8 : MVT::v8i8; 9221 9222 if (AArch64_AM::isAdvSIMDModImmType9(Value)) { 9223 Value = AArch64_AM::encodeAdvSIMDModImmType9(Value); 9224 9225 SDLoc dl(Op); 9226 SDValue Mov = DAG.getNode(NewOp, dl, MovTy, 9227 DAG.getConstant(Value, dl, MVT::i32)); 9228 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov); 9229 } 9230 } 9231 9232 return SDValue(); 9233 } 9234 9235 // Try FP splatted SIMD immediate. 9236 static SDValue tryAdvSIMDModImmFP(unsigned NewOp, SDValue Op, SelectionDAG &DAG, 9237 const APInt &Bits) { 9238 if (Bits.getHiBits(64) == Bits.getLoBits(64)) { 9239 uint64_t Value = Bits.zextOrTrunc(64).getZExtValue(); 9240 EVT VT = Op.getValueType(); 9241 bool isWide = (VT.getSizeInBits() == 128); 9242 MVT MovTy; 9243 bool isAdvSIMDModImm = false; 9244 9245 if ((isAdvSIMDModImm = AArch64_AM::isAdvSIMDModImmType11(Value))) { 9246 Value = AArch64_AM::encodeAdvSIMDModImmType11(Value); 9247 MovTy = isWide ? MVT::v4f32 : MVT::v2f32; 9248 } 9249 else if (isWide && 9250 (isAdvSIMDModImm = AArch64_AM::isAdvSIMDModImmType12(Value))) { 9251 Value = AArch64_AM::encodeAdvSIMDModImmType12(Value); 9252 MovTy = MVT::v2f64; 9253 } 9254 9255 if (isAdvSIMDModImm) { 9256 SDLoc dl(Op); 9257 SDValue Mov = DAG.getNode(NewOp, dl, MovTy, 9258 DAG.getConstant(Value, dl, MVT::i32)); 9259 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov); 9260 } 9261 } 9262 9263 return SDValue(); 9264 } 9265 9266 // Specialized code to quickly find if PotentialBVec is a BuildVector that 9267 // consists of only the same constant int value, returned in reference arg 9268 // ConstVal 9269 static bool isAllConstantBuildVector(const SDValue &PotentialBVec, 9270 uint64_t &ConstVal) { 9271 BuildVectorSDNode *Bvec = dyn_cast<BuildVectorSDNode>(PotentialBVec); 9272 if (!Bvec) 9273 return false; 9274 ConstantSDNode *FirstElt = dyn_cast<ConstantSDNode>(Bvec->getOperand(0)); 9275 if (!FirstElt) 9276 return false; 9277 EVT VT = Bvec->getValueType(0); 9278 unsigned NumElts = VT.getVectorNumElements(); 9279 for (unsigned i = 1; i < NumElts; ++i) 9280 if (dyn_cast<ConstantSDNode>(Bvec->getOperand(i)) != FirstElt) 9281 return false; 9282 ConstVal = FirstElt->getZExtValue(); 9283 return true; 9284 } 9285 9286 static unsigned getIntrinsicID(const SDNode *N) { 9287 unsigned Opcode = N->getOpcode(); 9288 switch (Opcode) { 9289 default: 9290 return Intrinsic::not_intrinsic; 9291 case ISD::INTRINSIC_WO_CHAIN: { 9292 unsigned IID = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue(); 9293 if (IID < Intrinsic::num_intrinsics) 9294 return IID; 9295 return Intrinsic::not_intrinsic; 9296 } 9297 } 9298 } 9299 9300 // Attempt to form a vector S[LR]I from (or (and X, BvecC1), (lsl Y, C2)), 9301 // to (SLI X, Y, C2), where X and Y have matching vector types, BvecC1 is a 9302 // BUILD_VECTORs with constant element C1, C2 is a constant, and: 9303 // - for the SLI case: C1 == ~(Ones(ElemSizeInBits) << C2) 9304 // - for the SRI case: C1 == ~(Ones(ElemSizeInBits) >> C2) 9305 // The (or (lsl Y, C2), (and X, BvecC1)) case is also handled. 9306 static SDValue tryLowerToSLI(SDNode *N, SelectionDAG &DAG) { 9307 EVT VT = N->getValueType(0); 9308 9309 if (!VT.isVector()) 9310 return SDValue(); 9311 9312 SDLoc DL(N); 9313 9314 SDValue And; 9315 SDValue Shift; 9316 9317 SDValue FirstOp = N->getOperand(0); 9318 unsigned FirstOpc = FirstOp.getOpcode(); 9319 SDValue SecondOp = N->getOperand(1); 9320 unsigned SecondOpc = SecondOp.getOpcode(); 9321 9322 // Is one of the operands an AND or a BICi? The AND may have been optimised to 9323 // a BICi in order to use an immediate instead of a register. 9324 // Is the other operand an shl or lshr? This will have been turned into: 9325 // AArch64ISD::VSHL vector, #shift or AArch64ISD::VLSHR vector, #shift. 9326 if ((FirstOpc == ISD::AND || FirstOpc == AArch64ISD::BICi) && 9327 (SecondOpc == AArch64ISD::VSHL || SecondOpc == AArch64ISD::VLSHR)) { 9328 And = FirstOp; 9329 Shift = SecondOp; 9330 9331 } else if ((SecondOpc == ISD::AND || SecondOpc == AArch64ISD::BICi) && 9332 (FirstOpc == AArch64ISD::VSHL || FirstOpc == AArch64ISD::VLSHR)) { 9333 And = SecondOp; 9334 Shift = FirstOp; 9335 } else 9336 return SDValue(); 9337 9338 bool IsAnd = And.getOpcode() == ISD::AND; 9339 bool IsShiftRight = Shift.getOpcode() == AArch64ISD::VLSHR; 9340 9341 // Is the shift amount constant? 9342 ConstantSDNode *C2node = dyn_cast<ConstantSDNode>(Shift.getOperand(1)); 9343 if (!C2node) 9344 return SDValue(); 9345 9346 uint64_t C1; 9347 if (IsAnd) { 9348 // Is the and mask vector all constant? 9349 if (!isAllConstantBuildVector(And.getOperand(1), C1)) 9350 return SDValue(); 9351 } else { 9352 // Reconstruct the corresponding AND immediate from the two BICi immediates. 9353 ConstantSDNode *C1nodeImm = dyn_cast<ConstantSDNode>(And.getOperand(1)); 9354 ConstantSDNode *C1nodeShift = dyn_cast<ConstantSDNode>(And.getOperand(2)); 9355 assert(C1nodeImm && C1nodeShift); 9356 C1 = ~(C1nodeImm->getZExtValue() << C1nodeShift->getZExtValue()); 9357 } 9358 9359 // Is C1 == ~(Ones(ElemSizeInBits) << C2) or 9360 // C1 == ~(Ones(ElemSizeInBits) >> C2), taking into account 9361 // how much one can shift elements of a particular size? 9362 uint64_t C2 = C2node->getZExtValue(); 9363 unsigned ElemSizeInBits = VT.getScalarSizeInBits(); 9364 if (C2 > ElemSizeInBits) 9365 return SDValue(); 9366 9367 APInt C1AsAPInt(ElemSizeInBits, C1); 9368 APInt RequiredC1 = IsShiftRight ? APInt::getHighBitsSet(ElemSizeInBits, C2) 9369 : APInt::getLowBitsSet(ElemSizeInBits, C2); 9370 if (C1AsAPInt != RequiredC1) 9371 return SDValue(); 9372 9373 SDValue X = And.getOperand(0); 9374 SDValue Y = Shift.getOperand(0); 9375 9376 unsigned Inst = IsShiftRight ? AArch64ISD::VSRI : AArch64ISD::VSLI; 9377 SDValue ResultSLI = DAG.getNode(Inst, DL, VT, X, Y, Shift.getOperand(1)); 9378 9379 LLVM_DEBUG(dbgs() << "aarch64-lower: transformed: \n"); 9380 LLVM_DEBUG(N->dump(&DAG)); 9381 LLVM_DEBUG(dbgs() << "into: \n"); 9382 LLVM_DEBUG(ResultSLI->dump(&DAG)); 9383 9384 ++NumShiftInserts; 9385 return ResultSLI; 9386 } 9387 9388 SDValue AArch64TargetLowering::LowerVectorOR(SDValue Op, 9389 SelectionDAG &DAG) const { 9390 if (useSVEForFixedLengthVectorVT(Op.getValueType())) 9391 return LowerToScalableOp(Op, DAG); 9392 9393 // Attempt to form a vector S[LR]I from (or (and X, C1), (lsl Y, C2)) 9394 if (SDValue Res = tryLowerToSLI(Op.getNode(), DAG)) 9395 return Res; 9396 9397 EVT VT = Op.getValueType(); 9398 9399 SDValue LHS = Op.getOperand(0); 9400 BuildVectorSDNode *BVN = 9401 dyn_cast<BuildVectorSDNode>(Op.getOperand(1).getNode()); 9402 if (!BVN) { 9403 // OR commutes, so try swapping the operands. 9404 LHS = Op.getOperand(1); 9405 BVN = dyn_cast<BuildVectorSDNode>(Op.getOperand(0).getNode()); 9406 } 9407 if (!BVN) 9408 return Op; 9409 9410 APInt DefBits(VT.getSizeInBits(), 0); 9411 APInt UndefBits(VT.getSizeInBits(), 0); 9412 if (resolveBuildVector(BVN, DefBits, UndefBits)) { 9413 SDValue NewOp; 9414 9415 if ((NewOp = tryAdvSIMDModImm32(AArch64ISD::ORRi, Op, DAG, 9416 DefBits, &LHS)) || 9417 (NewOp = tryAdvSIMDModImm16(AArch64ISD::ORRi, Op, DAG, 9418 DefBits, &LHS))) 9419 return NewOp; 9420 9421 if ((NewOp = tryAdvSIMDModImm32(AArch64ISD::ORRi, Op, DAG, 9422 UndefBits, &LHS)) || 9423 (NewOp = tryAdvSIMDModImm16(AArch64ISD::ORRi, Op, DAG, 9424 UndefBits, &LHS))) 9425 return NewOp; 9426 } 9427 9428 // We can always fall back to a non-immediate OR. 9429 return Op; 9430 } 9431 9432 // Normalize the operands of BUILD_VECTOR. The value of constant operands will 9433 // be truncated to fit element width. 9434 static SDValue NormalizeBuildVector(SDValue Op, 9435 SelectionDAG &DAG) { 9436 assert(Op.getOpcode() == ISD::BUILD_VECTOR && "Unknown opcode!"); 9437 SDLoc dl(Op); 9438 EVT VT = Op.getValueType(); 9439 EVT EltTy= VT.getVectorElementType(); 9440 9441 if (EltTy.isFloatingPoint() || EltTy.getSizeInBits() > 16) 9442 return Op; 9443 9444 SmallVector<SDValue, 16> Ops; 9445 for (SDValue Lane : Op->ops()) { 9446 // For integer vectors, type legalization would have promoted the 9447 // operands already. Otherwise, if Op is a floating-point splat 9448 // (with operands cast to integers), then the only possibilities 9449 // are constants and UNDEFs. 9450 if (auto *CstLane = dyn_cast<ConstantSDNode>(Lane)) { 9451 APInt LowBits(EltTy.getSizeInBits(), 9452 CstLane->getZExtValue()); 9453 Lane = DAG.getConstant(LowBits.getZExtValue(), dl, MVT::i32); 9454 } else if (Lane.getNode()->isUndef()) { 9455 Lane = DAG.getUNDEF(MVT::i32); 9456 } else { 9457 assert(Lane.getValueType() == MVT::i32 && 9458 "Unexpected BUILD_VECTOR operand type"); 9459 } 9460 Ops.push_back(Lane); 9461 } 9462 return DAG.getBuildVector(VT, dl, Ops); 9463 } 9464 9465 static SDValue ConstantBuildVector(SDValue Op, SelectionDAG &DAG) { 9466 EVT VT = Op.getValueType(); 9467 9468 APInt DefBits(VT.getSizeInBits(), 0); 9469 APInt UndefBits(VT.getSizeInBits(), 0); 9470 BuildVectorSDNode *BVN = cast<BuildVectorSDNode>(Op.getNode()); 9471 if (resolveBuildVector(BVN, DefBits, UndefBits)) { 9472 SDValue NewOp; 9473 if ((NewOp = tryAdvSIMDModImm64(AArch64ISD::MOVIedit, Op, DAG, DefBits)) || 9474 (NewOp = tryAdvSIMDModImm32(AArch64ISD::MOVIshift, Op, DAG, DefBits)) || 9475 (NewOp = tryAdvSIMDModImm321s(AArch64ISD::MOVImsl, Op, DAG, DefBits)) || 9476 (NewOp = tryAdvSIMDModImm16(AArch64ISD::MOVIshift, Op, DAG, DefBits)) || 9477 (NewOp = tryAdvSIMDModImm8(AArch64ISD::MOVI, Op, DAG, DefBits)) || 9478 (NewOp = tryAdvSIMDModImmFP(AArch64ISD::FMOV, Op, DAG, DefBits))) 9479 return NewOp; 9480 9481 DefBits = ~DefBits; 9482 if ((NewOp = tryAdvSIMDModImm32(AArch64ISD::MVNIshift, Op, DAG, DefBits)) || 9483 (NewOp = tryAdvSIMDModImm321s(AArch64ISD::MVNImsl, Op, DAG, DefBits)) || 9484 (NewOp = tryAdvSIMDModImm16(AArch64ISD::MVNIshift, Op, DAG, DefBits))) 9485 return NewOp; 9486 9487 DefBits = UndefBits; 9488 if ((NewOp = tryAdvSIMDModImm64(AArch64ISD::MOVIedit, Op, DAG, DefBits)) || 9489 (NewOp = tryAdvSIMDModImm32(AArch64ISD::MOVIshift, Op, DAG, DefBits)) || 9490 (NewOp = tryAdvSIMDModImm321s(AArch64ISD::MOVImsl, Op, DAG, DefBits)) || 9491 (NewOp = tryAdvSIMDModImm16(AArch64ISD::MOVIshift, Op, DAG, DefBits)) || 9492 (NewOp = tryAdvSIMDModImm8(AArch64ISD::MOVI, Op, DAG, DefBits)) || 9493 (NewOp = tryAdvSIMDModImmFP(AArch64ISD::FMOV, Op, DAG, DefBits))) 9494 return NewOp; 9495 9496 DefBits = ~UndefBits; 9497 if ((NewOp = tryAdvSIMDModImm32(AArch64ISD::MVNIshift, Op, DAG, DefBits)) || 9498 (NewOp = tryAdvSIMDModImm321s(AArch64ISD::MVNImsl, Op, DAG, DefBits)) || 9499 (NewOp = tryAdvSIMDModImm16(AArch64ISD::MVNIshift, Op, DAG, DefBits))) 9500 return NewOp; 9501 } 9502 9503 return SDValue(); 9504 } 9505 9506 SDValue AArch64TargetLowering::LowerBUILD_VECTOR(SDValue Op, 9507 SelectionDAG &DAG) const { 9508 EVT VT = Op.getValueType(); 9509 9510 // Try to build a simple constant vector. 9511 Op = NormalizeBuildVector(Op, DAG); 9512 if (VT.isInteger()) { 9513 // Certain vector constants, used to express things like logical NOT and 9514 // arithmetic NEG, are passed through unmodified. This allows special 9515 // patterns for these operations to match, which will lower these constants 9516 // to whatever is proven necessary. 9517 BuildVectorSDNode *BVN = cast<BuildVectorSDNode>(Op.getNode()); 9518 if (BVN->isConstant()) 9519 if (ConstantSDNode *Const = BVN->getConstantSplatNode()) { 9520 unsigned BitSize = VT.getVectorElementType().getSizeInBits(); 9521 APInt Val(BitSize, 9522 Const->getAPIntValue().zextOrTrunc(BitSize).getZExtValue()); 9523 if (Val.isNullValue() || Val.isAllOnesValue()) 9524 return Op; 9525 } 9526 } 9527 9528 if (SDValue V = ConstantBuildVector(Op, DAG)) 9529 return V; 9530 9531 // Scan through the operands to find some interesting properties we can 9532 // exploit: 9533 // 1) If only one value is used, we can use a DUP, or 9534 // 2) if only the low element is not undef, we can just insert that, or 9535 // 3) if only one constant value is used (w/ some non-constant lanes), 9536 // we can splat the constant value into the whole vector then fill 9537 // in the non-constant lanes. 9538 // 4) FIXME: If different constant values are used, but we can intelligently 9539 // select the values we'll be overwriting for the non-constant 9540 // lanes such that we can directly materialize the vector 9541 // some other way (MOVI, e.g.), we can be sneaky. 9542 // 5) if all operands are EXTRACT_VECTOR_ELT, check for VUZP. 9543 SDLoc dl(Op); 9544 unsigned NumElts = VT.getVectorNumElements(); 9545 bool isOnlyLowElement = true; 9546 bool usesOnlyOneValue = true; 9547 bool usesOnlyOneConstantValue = true; 9548 bool isConstant = true; 9549 bool AllLanesExtractElt = true; 9550 unsigned NumConstantLanes = 0; 9551 unsigned NumDifferentLanes = 0; 9552 unsigned NumUndefLanes = 0; 9553 SDValue Value; 9554 SDValue ConstantValue; 9555 for (unsigned i = 0; i < NumElts; ++i) { 9556 SDValue V = Op.getOperand(i); 9557 if (V.getOpcode() != ISD::EXTRACT_VECTOR_ELT) 9558 AllLanesExtractElt = false; 9559 if (V.isUndef()) { 9560 ++NumUndefLanes; 9561 continue; 9562 } 9563 if (i > 0) 9564 isOnlyLowElement = false; 9565 if (!isa<ConstantFPSDNode>(V) && !isa<ConstantSDNode>(V)) 9566 isConstant = false; 9567 9568 if (isa<ConstantSDNode>(V) || isa<ConstantFPSDNode>(V)) { 9569 ++NumConstantLanes; 9570 if (!ConstantValue.getNode()) 9571 ConstantValue = V; 9572 else if (ConstantValue != V) 9573 usesOnlyOneConstantValue = false; 9574 } 9575 9576 if (!Value.getNode()) 9577 Value = V; 9578 else if (V != Value) { 9579 usesOnlyOneValue = false; 9580 ++NumDifferentLanes; 9581 } 9582 } 9583 9584 if (!Value.getNode()) { 9585 LLVM_DEBUG( 9586 dbgs() << "LowerBUILD_VECTOR: value undefined, creating undef node\n"); 9587 return DAG.getUNDEF(VT); 9588 } 9589 9590 // Convert BUILD_VECTOR where all elements but the lowest are undef into 9591 // SCALAR_TO_VECTOR, except for when we have a single-element constant vector 9592 // as SimplifyDemandedBits will just turn that back into BUILD_VECTOR. 9593 if (isOnlyLowElement && !(NumElts == 1 && isa<ConstantSDNode>(Value))) { 9594 LLVM_DEBUG(dbgs() << "LowerBUILD_VECTOR: only low element used, creating 1 " 9595 "SCALAR_TO_VECTOR node\n"); 9596 return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Value); 9597 } 9598 9599 if (AllLanesExtractElt) { 9600 SDNode *Vector = nullptr; 9601 bool Even = false; 9602 bool Odd = false; 9603 // Check whether the extract elements match the Even pattern <0,2,4,...> or 9604 // the Odd pattern <1,3,5,...>. 9605 for (unsigned i = 0; i < NumElts; ++i) { 9606 SDValue V = Op.getOperand(i); 9607 const SDNode *N = V.getNode(); 9608 if (!isa<ConstantSDNode>(N->getOperand(1))) 9609 break; 9610 SDValue N0 = N->getOperand(0); 9611 9612 // All elements are extracted from the same vector. 9613 if (!Vector) { 9614 Vector = N0.getNode(); 9615 // Check that the type of EXTRACT_VECTOR_ELT matches the type of 9616 // BUILD_VECTOR. 9617 if (VT.getVectorElementType() != 9618 N0.getValueType().getVectorElementType()) 9619 break; 9620 } else if (Vector != N0.getNode()) { 9621 Odd = false; 9622 Even = false; 9623 break; 9624 } 9625 9626 // Extracted values are either at Even indices <0,2,4,...> or at Odd 9627 // indices <1,3,5,...>. 9628 uint64_t Val = N->getConstantOperandVal(1); 9629 if (Val == 2 * i) { 9630 Even = true; 9631 continue; 9632 } 9633 if (Val - 1 == 2 * i) { 9634 Odd = true; 9635 continue; 9636 } 9637 9638 // Something does not match: abort. 9639 Odd = false; 9640 Even = false; 9641 break; 9642 } 9643 if (Even || Odd) { 9644 SDValue LHS = 9645 DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT, SDValue(Vector, 0), 9646 DAG.getConstant(0, dl, MVT::i64)); 9647 SDValue RHS = 9648 DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT, SDValue(Vector, 0), 9649 DAG.getConstant(NumElts, dl, MVT::i64)); 9650 9651 if (Even && !Odd) 9652 return DAG.getNode(AArch64ISD::UZP1, dl, DAG.getVTList(VT, VT), LHS, 9653 RHS); 9654 if (Odd && !Even) 9655 return DAG.getNode(AArch64ISD::UZP2, dl, DAG.getVTList(VT, VT), LHS, 9656 RHS); 9657 } 9658 } 9659 9660 // Use DUP for non-constant splats. For f32 constant splats, reduce to 9661 // i32 and try again. 9662 if (usesOnlyOneValue) { 9663 if (!isConstant) { 9664 if (Value.getOpcode() != ISD::EXTRACT_VECTOR_ELT || 9665 Value.getValueType() != VT) { 9666 LLVM_DEBUG( 9667 dbgs() << "LowerBUILD_VECTOR: use DUP for non-constant splats\n"); 9668 return DAG.getNode(AArch64ISD::DUP, dl, VT, Value); 9669 } 9670 9671 // This is actually a DUPLANExx operation, which keeps everything vectory. 9672 9673 SDValue Lane = Value.getOperand(1); 9674 Value = Value.getOperand(0); 9675 if (Value.getValueSizeInBits() == 64) { 9676 LLVM_DEBUG( 9677 dbgs() << "LowerBUILD_VECTOR: DUPLANE works on 128-bit vectors, " 9678 "widening it\n"); 9679 Value = WidenVector(Value, DAG); 9680 } 9681 9682 unsigned Opcode = getDUPLANEOp(VT.getVectorElementType()); 9683 return DAG.getNode(Opcode, dl, VT, Value, Lane); 9684 } 9685 9686 if (VT.getVectorElementType().isFloatingPoint()) { 9687 SmallVector<SDValue, 8> Ops; 9688 EVT EltTy = VT.getVectorElementType(); 9689 assert ((EltTy == MVT::f16 || EltTy == MVT::bf16 || EltTy == MVT::f32 || 9690 EltTy == MVT::f64) && "Unsupported floating-point vector type"); 9691 LLVM_DEBUG( 9692 dbgs() << "LowerBUILD_VECTOR: float constant splats, creating int " 9693 "BITCASTS, and try again\n"); 9694 MVT NewType = MVT::getIntegerVT(EltTy.getSizeInBits()); 9695 for (unsigned i = 0; i < NumElts; ++i) 9696 Ops.push_back(DAG.getNode(ISD::BITCAST, dl, NewType, Op.getOperand(i))); 9697 EVT VecVT = EVT::getVectorVT(*DAG.getContext(), NewType, NumElts); 9698 SDValue Val = DAG.getBuildVector(VecVT, dl, Ops); 9699 LLVM_DEBUG(dbgs() << "LowerBUILD_VECTOR: trying to lower new vector: "; 9700 Val.dump();); 9701 Val = LowerBUILD_VECTOR(Val, DAG); 9702 if (Val.getNode()) 9703 return DAG.getNode(ISD::BITCAST, dl, VT, Val); 9704 } 9705 } 9706 9707 // If we need to insert a small number of different non-constant elements and 9708 // the vector width is sufficiently large, prefer using DUP with the common 9709 // value and INSERT_VECTOR_ELT for the different lanes. If DUP is preferred, 9710 // skip the constant lane handling below. 9711 bool PreferDUPAndInsert = 9712 !isConstant && NumDifferentLanes >= 1 && 9713 NumDifferentLanes < ((NumElts - NumUndefLanes) / 2) && 9714 NumDifferentLanes >= NumConstantLanes; 9715 9716 // If there was only one constant value used and for more than one lane, 9717 // start by splatting that value, then replace the non-constant lanes. This 9718 // is better than the default, which will perform a separate initialization 9719 // for each lane. 9720 if (!PreferDUPAndInsert && NumConstantLanes > 0 && usesOnlyOneConstantValue) { 9721 // Firstly, try to materialize the splat constant. 9722 SDValue Vec = DAG.getSplatBuildVector(VT, dl, ConstantValue), 9723 Val = ConstantBuildVector(Vec, DAG); 9724 if (!Val) { 9725 // Otherwise, materialize the constant and splat it. 9726 Val = DAG.getNode(AArch64ISD::DUP, dl, VT, ConstantValue); 9727 DAG.ReplaceAllUsesWith(Vec.getNode(), &Val); 9728 } 9729 9730 // Now insert the non-constant lanes. 9731 for (unsigned i = 0; i < NumElts; ++i) { 9732 SDValue V = Op.getOperand(i); 9733 SDValue LaneIdx = DAG.getConstant(i, dl, MVT::i64); 9734 if (!isa<ConstantSDNode>(V) && !isa<ConstantFPSDNode>(V)) 9735 // Note that type legalization likely mucked about with the VT of the 9736 // source operand, so we may have to convert it here before inserting. 9737 Val = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Val, V, LaneIdx); 9738 } 9739 return Val; 9740 } 9741 9742 // This will generate a load from the constant pool. 9743 if (isConstant) { 9744 LLVM_DEBUG( 9745 dbgs() << "LowerBUILD_VECTOR: all elements are constant, use default " 9746 "expansion\n"); 9747 return SDValue(); 9748 } 9749 9750 // Empirical tests suggest this is rarely worth it for vectors of length <= 2. 9751 if (NumElts >= 4) { 9752 if (SDValue shuffle = ReconstructShuffle(Op, DAG)) 9753 return shuffle; 9754 } 9755 9756 if (PreferDUPAndInsert) { 9757 // First, build a constant vector with the common element. 9758 SmallVector<SDValue, 8> Ops(NumElts, Value); 9759 SDValue NewVector = LowerBUILD_VECTOR(DAG.getBuildVector(VT, dl, Ops), DAG); 9760 // Next, insert the elements that do not match the common value. 9761 for (unsigned I = 0; I < NumElts; ++I) 9762 if (Op.getOperand(I) != Value) 9763 NewVector = 9764 DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, NewVector, 9765 Op.getOperand(I), DAG.getConstant(I, dl, MVT::i64)); 9766 9767 return NewVector; 9768 } 9769 9770 // If all else fails, just use a sequence of INSERT_VECTOR_ELT when we 9771 // know the default expansion would otherwise fall back on something even 9772 // worse. For a vector with one or two non-undef values, that's 9773 // scalar_to_vector for the elements followed by a shuffle (provided the 9774 // shuffle is valid for the target) and materialization element by element 9775 // on the stack followed by a load for everything else. 9776 if (!isConstant && !usesOnlyOneValue) { 9777 LLVM_DEBUG( 9778 dbgs() << "LowerBUILD_VECTOR: alternatives failed, creating sequence " 9779 "of INSERT_VECTOR_ELT\n"); 9780 9781 SDValue Vec = DAG.getUNDEF(VT); 9782 SDValue Op0 = Op.getOperand(0); 9783 unsigned i = 0; 9784 9785 // Use SCALAR_TO_VECTOR for lane zero to 9786 // a) Avoid a RMW dependency on the full vector register, and 9787 // b) Allow the register coalescer to fold away the copy if the 9788 // value is already in an S or D register, and we're forced to emit an 9789 // INSERT_SUBREG that we can't fold anywhere. 9790 // 9791 // We also allow types like i8 and i16 which are illegal scalar but legal 9792 // vector element types. After type-legalization the inserted value is 9793 // extended (i32) and it is safe to cast them to the vector type by ignoring 9794 // the upper bits of the lowest lane (e.g. v8i8, v4i16). 9795 if (!Op0.isUndef()) { 9796 LLVM_DEBUG(dbgs() << "Creating node for op0, it is not undefined:\n"); 9797 Vec = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op0); 9798 ++i; 9799 } 9800 LLVM_DEBUG(if (i < NumElts) dbgs() 9801 << "Creating nodes for the other vector elements:\n";); 9802 for (; i < NumElts; ++i) { 9803 SDValue V = Op.getOperand(i); 9804 if (V.isUndef()) 9805 continue; 9806 SDValue LaneIdx = DAG.getConstant(i, dl, MVT::i64); 9807 Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Vec, V, LaneIdx); 9808 } 9809 return Vec; 9810 } 9811 9812 LLVM_DEBUG( 9813 dbgs() << "LowerBUILD_VECTOR: use default expansion, failed to find " 9814 "better alternative\n"); 9815 return SDValue(); 9816 } 9817 9818 SDValue AArch64TargetLowering::LowerCONCAT_VECTORS(SDValue Op, 9819 SelectionDAG &DAG) const { 9820 assert(Op.getValueType().isScalableVector() && 9821 isTypeLegal(Op.getValueType()) && 9822 "Expected legal scalable vector type!"); 9823 9824 if (isTypeLegal(Op.getOperand(0).getValueType()) && Op.getNumOperands() == 2) 9825 return Op; 9826 9827 return SDValue(); 9828 } 9829 9830 SDValue AArch64TargetLowering::LowerINSERT_VECTOR_ELT(SDValue Op, 9831 SelectionDAG &DAG) const { 9832 assert(Op.getOpcode() == ISD::INSERT_VECTOR_ELT && "Unknown opcode!"); 9833 9834 // Check for non-constant or out of range lane. 9835 EVT VT = Op.getOperand(0).getValueType(); 9836 ConstantSDNode *CI = dyn_cast<ConstantSDNode>(Op.getOperand(2)); 9837 if (!CI || CI->getZExtValue() >= VT.getVectorNumElements()) 9838 return SDValue(); 9839 9840 9841 // Insertion/extraction are legal for V128 types. 9842 if (VT == MVT::v16i8 || VT == MVT::v8i16 || VT == MVT::v4i32 || 9843 VT == MVT::v2i64 || VT == MVT::v4f32 || VT == MVT::v2f64 || 9844 VT == MVT::v8f16 || VT == MVT::v8bf16) 9845 return Op; 9846 9847 if (VT != MVT::v8i8 && VT != MVT::v4i16 && VT != MVT::v2i32 && 9848 VT != MVT::v1i64 && VT != MVT::v2f32 && VT != MVT::v4f16 && 9849 VT != MVT::v4bf16) 9850 return SDValue(); 9851 9852 // For V64 types, we perform insertion by expanding the value 9853 // to a V128 type and perform the insertion on that. 9854 SDLoc DL(Op); 9855 SDValue WideVec = WidenVector(Op.getOperand(0), DAG); 9856 EVT WideTy = WideVec.getValueType(); 9857 9858 SDValue Node = DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, WideTy, WideVec, 9859 Op.getOperand(1), Op.getOperand(2)); 9860 // Re-narrow the resultant vector. 9861 return NarrowVector(Node, DAG); 9862 } 9863 9864 SDValue 9865 AArch64TargetLowering::LowerEXTRACT_VECTOR_ELT(SDValue Op, 9866 SelectionDAG &DAG) const { 9867 assert(Op.getOpcode() == ISD::EXTRACT_VECTOR_ELT && "Unknown opcode!"); 9868 9869 // Check for non-constant or out of range lane. 9870 EVT VT = Op.getOperand(0).getValueType(); 9871 ConstantSDNode *CI = dyn_cast<ConstantSDNode>(Op.getOperand(1)); 9872 if (!CI || CI->getZExtValue() >= VT.getVectorNumElements()) 9873 return SDValue(); 9874 9875 9876 // Insertion/extraction are legal for V128 types. 9877 if (VT == MVT::v16i8 || VT == MVT::v8i16 || VT == MVT::v4i32 || 9878 VT == MVT::v2i64 || VT == MVT::v4f32 || VT == MVT::v2f64 || 9879 VT == MVT::v8f16 || VT == MVT::v8bf16) 9880 return Op; 9881 9882 if (VT != MVT::v8i8 && VT != MVT::v4i16 && VT != MVT::v2i32 && 9883 VT != MVT::v1i64 && VT != MVT::v2f32 && VT != MVT::v4f16 && 9884 VT != MVT::v4bf16) 9885 return SDValue(); 9886 9887 // For V64 types, we perform extraction by expanding the value 9888 // to a V128 type and perform the extraction on that. 9889 SDLoc DL(Op); 9890 SDValue WideVec = WidenVector(Op.getOperand(0), DAG); 9891 EVT WideTy = WideVec.getValueType(); 9892 9893 EVT ExtrTy = WideTy.getVectorElementType(); 9894 if (ExtrTy == MVT::i16 || ExtrTy == MVT::i8) 9895 ExtrTy = MVT::i32; 9896 9897 // For extractions, we just return the result directly. 9898 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, ExtrTy, WideVec, 9899 Op.getOperand(1)); 9900 } 9901 9902 SDValue AArch64TargetLowering::LowerEXTRACT_SUBVECTOR(SDValue Op, 9903 SelectionDAG &DAG) const { 9904 assert(Op.getValueType().isFixedLengthVector() && 9905 "Only cases that extract a fixed length vector are supported!"); 9906 9907 EVT InVT = Op.getOperand(0).getValueType(); 9908 unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue(); 9909 unsigned Size = Op.getValueSizeInBits(); 9910 9911 if (InVT.isScalableVector()) { 9912 // This will be matched by custom code during ISelDAGToDAG. 9913 if (Idx == 0 && isPackedVectorType(InVT, DAG)) 9914 return Op; 9915 9916 return SDValue(); 9917 } 9918 9919 // This will get lowered to an appropriate EXTRACT_SUBREG in ISel. 9920 if (Idx == 0 && InVT.getSizeInBits() <= 128) 9921 return Op; 9922 9923 // If this is extracting the upper 64-bits of a 128-bit vector, we match 9924 // that directly. 9925 if (Size == 64 && Idx * InVT.getScalarSizeInBits() == 64 && 9926 InVT.getSizeInBits() == 128) 9927 return Op; 9928 9929 return SDValue(); 9930 } 9931 9932 SDValue AArch64TargetLowering::LowerINSERT_SUBVECTOR(SDValue Op, 9933 SelectionDAG &DAG) const { 9934 assert(Op.getValueType().isScalableVector() && 9935 "Only expect to lower inserts into scalable vectors!"); 9936 9937 EVT InVT = Op.getOperand(1).getValueType(); 9938 unsigned Idx = cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue(); 9939 9940 if (InVT.isScalableVector()) { 9941 SDLoc DL(Op); 9942 EVT VT = Op.getValueType(); 9943 9944 if (!isTypeLegal(VT) || !VT.isInteger()) 9945 return SDValue(); 9946 9947 SDValue Vec0 = Op.getOperand(0); 9948 SDValue Vec1 = Op.getOperand(1); 9949 9950 // Ensure the subvector is half the size of the main vector. 9951 if (VT.getVectorElementCount() != (InVT.getVectorElementCount() * 2)) 9952 return SDValue(); 9953 9954 // Extend elements of smaller vector... 9955 EVT WideVT = InVT.widenIntegerVectorElementType(*(DAG.getContext())); 9956 SDValue ExtVec = DAG.getNode(ISD::ANY_EXTEND, DL, WideVT, Vec1); 9957 9958 if (Idx == 0) { 9959 SDValue HiVec0 = DAG.getNode(AArch64ISD::UUNPKHI, DL, WideVT, Vec0); 9960 return DAG.getNode(AArch64ISD::UZP1, DL, VT, ExtVec, HiVec0); 9961 } else if (Idx == InVT.getVectorMinNumElements()) { 9962 SDValue LoVec0 = DAG.getNode(AArch64ISD::UUNPKLO, DL, WideVT, Vec0); 9963 return DAG.getNode(AArch64ISD::UZP1, DL, VT, LoVec0, ExtVec); 9964 } 9965 9966 return SDValue(); 9967 } 9968 9969 // This will be matched by custom code during ISelDAGToDAG. 9970 if (Idx == 0 && isPackedVectorType(InVT, DAG) && Op.getOperand(0).isUndef()) 9971 return Op; 9972 9973 return SDValue(); 9974 } 9975 9976 SDValue AArch64TargetLowering::LowerDIV(SDValue Op, SelectionDAG &DAG) const { 9977 EVT VT = Op.getValueType(); 9978 9979 if (useSVEForFixedLengthVectorVT(VT, /*OverrideNEON=*/true)) 9980 return LowerFixedLengthVectorIntDivideToSVE(Op, DAG); 9981 9982 assert(VT.isScalableVector() && "Expected a scalable vector."); 9983 9984 bool Signed = Op.getOpcode() == ISD::SDIV; 9985 unsigned PredOpcode = Signed ? AArch64ISD::SDIV_PRED : AArch64ISD::UDIV_PRED; 9986 9987 if (VT == MVT::nxv4i32 || VT == MVT::nxv2i64) 9988 return LowerToPredicatedOp(Op, DAG, PredOpcode); 9989 9990 // SVE doesn't have i8 and i16 DIV operations; widen them to 32-bit 9991 // operations, and truncate the result. 9992 EVT WidenedVT; 9993 if (VT == MVT::nxv16i8) 9994 WidenedVT = MVT::nxv8i16; 9995 else if (VT == MVT::nxv8i16) 9996 WidenedVT = MVT::nxv4i32; 9997 else 9998 llvm_unreachable("Unexpected Custom DIV operation"); 9999 10000 SDLoc dl(Op); 10001 unsigned UnpkLo = Signed ? AArch64ISD::SUNPKLO : AArch64ISD::UUNPKLO; 10002 unsigned UnpkHi = Signed ? AArch64ISD::SUNPKHI : AArch64ISD::UUNPKHI; 10003 SDValue Op0Lo = DAG.getNode(UnpkLo, dl, WidenedVT, Op.getOperand(0)); 10004 SDValue Op1Lo = DAG.getNode(UnpkLo, dl, WidenedVT, Op.getOperand(1)); 10005 SDValue Op0Hi = DAG.getNode(UnpkHi, dl, WidenedVT, Op.getOperand(0)); 10006 SDValue Op1Hi = DAG.getNode(UnpkHi, dl, WidenedVT, Op.getOperand(1)); 10007 SDValue ResultLo = DAG.getNode(Op.getOpcode(), dl, WidenedVT, Op0Lo, Op1Lo); 10008 SDValue ResultHi = DAG.getNode(Op.getOpcode(), dl, WidenedVT, Op0Hi, Op1Hi); 10009 return DAG.getNode(AArch64ISD::UZP1, dl, VT, ResultLo, ResultHi); 10010 } 10011 10012 bool AArch64TargetLowering::isShuffleMaskLegal(ArrayRef<int> M, EVT VT) const { 10013 // Currently no fixed length shuffles that require SVE are legal. 10014 if (useSVEForFixedLengthVectorVT(VT)) 10015 return false; 10016 10017 if (VT.getVectorNumElements() == 4 && 10018 (VT.is128BitVector() || VT.is64BitVector())) { 10019 unsigned PFIndexes[4]; 10020 for (unsigned i = 0; i != 4; ++i) { 10021 if (M[i] < 0) 10022 PFIndexes[i] = 8; 10023 else 10024 PFIndexes[i] = M[i]; 10025 } 10026 10027 // Compute the index in the perfect shuffle table. 10028 unsigned PFTableIndex = PFIndexes[0] * 9 * 9 * 9 + PFIndexes[1] * 9 * 9 + 10029 PFIndexes[2] * 9 + PFIndexes[3]; 10030 unsigned PFEntry = PerfectShuffleTable[PFTableIndex]; 10031 unsigned Cost = (PFEntry >> 30); 10032 10033 if (Cost <= 4) 10034 return true; 10035 } 10036 10037 bool DummyBool; 10038 int DummyInt; 10039 unsigned DummyUnsigned; 10040 10041 return (ShuffleVectorSDNode::isSplatMask(&M[0], VT) || isREVMask(M, VT, 64) || 10042 isREVMask(M, VT, 32) || isREVMask(M, VT, 16) || 10043 isEXTMask(M, VT, DummyBool, DummyUnsigned) || 10044 // isTBLMask(M, VT) || // FIXME: Port TBL support from ARM. 10045 isTRNMask(M, VT, DummyUnsigned) || isUZPMask(M, VT, DummyUnsigned) || 10046 isZIPMask(M, VT, DummyUnsigned) || 10047 isTRN_v_undef_Mask(M, VT, DummyUnsigned) || 10048 isUZP_v_undef_Mask(M, VT, DummyUnsigned) || 10049 isZIP_v_undef_Mask(M, VT, DummyUnsigned) || 10050 isINSMask(M, VT.getVectorNumElements(), DummyBool, DummyInt) || 10051 isConcatMask(M, VT, VT.getSizeInBits() == 128)); 10052 } 10053 10054 /// getVShiftImm - Check if this is a valid build_vector for the immediate 10055 /// operand of a vector shift operation, where all the elements of the 10056 /// build_vector must have the same constant integer value. 10057 static bool getVShiftImm(SDValue Op, unsigned ElementBits, int64_t &Cnt) { 10058 // Ignore bit_converts. 10059 while (Op.getOpcode() == ISD::BITCAST) 10060 Op = Op.getOperand(0); 10061 BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(Op.getNode()); 10062 APInt SplatBits, SplatUndef; 10063 unsigned SplatBitSize; 10064 bool HasAnyUndefs; 10065 if (!BVN || !BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, 10066 HasAnyUndefs, ElementBits) || 10067 SplatBitSize > ElementBits) 10068 return false; 10069 Cnt = SplatBits.getSExtValue(); 10070 return true; 10071 } 10072 10073 /// isVShiftLImm - Check if this is a valid build_vector for the immediate 10074 /// operand of a vector shift left operation. That value must be in the range: 10075 /// 0 <= Value < ElementBits for a left shift; or 10076 /// 0 <= Value <= ElementBits for a long left shift. 10077 static bool isVShiftLImm(SDValue Op, EVT VT, bool isLong, int64_t &Cnt) { 10078 assert(VT.isVector() && "vector shift count is not a vector type"); 10079 int64_t ElementBits = VT.getScalarSizeInBits(); 10080 if (!getVShiftImm(Op, ElementBits, Cnt)) 10081 return false; 10082 return (Cnt >= 0 && (isLong ? Cnt - 1 : Cnt) < ElementBits); 10083 } 10084 10085 /// isVShiftRImm - Check if this is a valid build_vector for the immediate 10086 /// operand of a vector shift right operation. The value must be in the range: 10087 /// 1 <= Value <= ElementBits for a right shift; or 10088 static bool isVShiftRImm(SDValue Op, EVT VT, bool isNarrow, int64_t &Cnt) { 10089 assert(VT.isVector() && "vector shift count is not a vector type"); 10090 int64_t ElementBits = VT.getScalarSizeInBits(); 10091 if (!getVShiftImm(Op, ElementBits, Cnt)) 10092 return false; 10093 return (Cnt >= 1 && Cnt <= (isNarrow ? ElementBits / 2 : ElementBits)); 10094 } 10095 10096 SDValue AArch64TargetLowering::LowerTRUNCATE(SDValue Op, 10097 SelectionDAG &DAG) const { 10098 EVT VT = Op.getValueType(); 10099 10100 if (VT.getScalarType() == MVT::i1) { 10101 // Lower i1 truncate to `(x & 1) != 0`. 10102 SDLoc dl(Op); 10103 EVT OpVT = Op.getOperand(0).getValueType(); 10104 SDValue Zero = DAG.getConstant(0, dl, OpVT); 10105 SDValue One = DAG.getConstant(1, dl, OpVT); 10106 SDValue And = DAG.getNode(ISD::AND, dl, OpVT, Op.getOperand(0), One); 10107 return DAG.getSetCC(dl, VT, And, Zero, ISD::SETNE); 10108 } 10109 10110 if (!VT.isVector() || VT.isScalableVector()) 10111 return SDValue(); 10112 10113 if (useSVEForFixedLengthVectorVT(Op.getOperand(0).getValueType())) 10114 return LowerFixedLengthVectorTruncateToSVE(Op, DAG); 10115 10116 return SDValue(); 10117 } 10118 10119 SDValue AArch64TargetLowering::LowerVectorSRA_SRL_SHL(SDValue Op, 10120 SelectionDAG &DAG) const { 10121 EVT VT = Op.getValueType(); 10122 SDLoc DL(Op); 10123 int64_t Cnt; 10124 10125 if (!Op.getOperand(1).getValueType().isVector()) 10126 return Op; 10127 unsigned EltSize = VT.getScalarSizeInBits(); 10128 10129 switch (Op.getOpcode()) { 10130 default: 10131 llvm_unreachable("unexpected shift opcode"); 10132 10133 case ISD::SHL: 10134 if (VT.isScalableVector() || useSVEForFixedLengthVectorVT(VT)) 10135 return LowerToPredicatedOp(Op, DAG, AArch64ISD::SHL_PRED); 10136 10137 if (isVShiftLImm(Op.getOperand(1), VT, false, Cnt) && Cnt < EltSize) 10138 return DAG.getNode(AArch64ISD::VSHL, DL, VT, Op.getOperand(0), 10139 DAG.getConstant(Cnt, DL, MVT::i32)); 10140 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT, 10141 DAG.getConstant(Intrinsic::aarch64_neon_ushl, DL, 10142 MVT::i32), 10143 Op.getOperand(0), Op.getOperand(1)); 10144 case ISD::SRA: 10145 case ISD::SRL: 10146 if (VT.isScalableVector() || useSVEForFixedLengthVectorVT(VT)) { 10147 unsigned Opc = Op.getOpcode() == ISD::SRA ? AArch64ISD::SRA_PRED 10148 : AArch64ISD::SRL_PRED; 10149 return LowerToPredicatedOp(Op, DAG, Opc); 10150 } 10151 10152 // Right shift immediate 10153 if (isVShiftRImm(Op.getOperand(1), VT, false, Cnt) && Cnt < EltSize) { 10154 unsigned Opc = 10155 (Op.getOpcode() == ISD::SRA) ? AArch64ISD::VASHR : AArch64ISD::VLSHR; 10156 return DAG.getNode(Opc, DL, VT, Op.getOperand(0), 10157 DAG.getConstant(Cnt, DL, MVT::i32)); 10158 } 10159 10160 // Right shift register. Note, there is not a shift right register 10161 // instruction, but the shift left register instruction takes a signed 10162 // value, where negative numbers specify a right shift. 10163 unsigned Opc = (Op.getOpcode() == ISD::SRA) ? Intrinsic::aarch64_neon_sshl 10164 : Intrinsic::aarch64_neon_ushl; 10165 // negate the shift amount 10166 SDValue NegShift = DAG.getNode(AArch64ISD::NEG, DL, VT, Op.getOperand(1)); 10167 SDValue NegShiftLeft = 10168 DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT, 10169 DAG.getConstant(Opc, DL, MVT::i32), Op.getOperand(0), 10170 NegShift); 10171 return NegShiftLeft; 10172 } 10173 10174 return SDValue(); 10175 } 10176 10177 static SDValue EmitVectorComparison(SDValue LHS, SDValue RHS, 10178 AArch64CC::CondCode CC, bool NoNans, EVT VT, 10179 const SDLoc &dl, SelectionDAG &DAG) { 10180 EVT SrcVT = LHS.getValueType(); 10181 assert(VT.getSizeInBits() == SrcVT.getSizeInBits() && 10182 "function only supposed to emit natural comparisons"); 10183 10184 BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(RHS.getNode()); 10185 APInt CnstBits(VT.getSizeInBits(), 0); 10186 APInt UndefBits(VT.getSizeInBits(), 0); 10187 bool IsCnst = BVN && resolveBuildVector(BVN, CnstBits, UndefBits); 10188 bool IsZero = IsCnst && (CnstBits == 0); 10189 10190 if (SrcVT.getVectorElementType().isFloatingPoint()) { 10191 switch (CC) { 10192 default: 10193 return SDValue(); 10194 case AArch64CC::NE: { 10195 SDValue Fcmeq; 10196 if (IsZero) 10197 Fcmeq = DAG.getNode(AArch64ISD::FCMEQz, dl, VT, LHS); 10198 else 10199 Fcmeq = DAG.getNode(AArch64ISD::FCMEQ, dl, VT, LHS, RHS); 10200 return DAG.getNOT(dl, Fcmeq, VT); 10201 } 10202 case AArch64CC::EQ: 10203 if (IsZero) 10204 return DAG.getNode(AArch64ISD::FCMEQz, dl, VT, LHS); 10205 return DAG.getNode(AArch64ISD::FCMEQ, dl, VT, LHS, RHS); 10206 case AArch64CC::GE: 10207 if (IsZero) 10208 return DAG.getNode(AArch64ISD::FCMGEz, dl, VT, LHS); 10209 return DAG.getNode(AArch64ISD::FCMGE, dl, VT, LHS, RHS); 10210 case AArch64CC::GT: 10211 if (IsZero) 10212 return DAG.getNode(AArch64ISD::FCMGTz, dl, VT, LHS); 10213 return DAG.getNode(AArch64ISD::FCMGT, dl, VT, LHS, RHS); 10214 case AArch64CC::LS: 10215 if (IsZero) 10216 return DAG.getNode(AArch64ISD::FCMLEz, dl, VT, LHS); 10217 return DAG.getNode(AArch64ISD::FCMGE, dl, VT, RHS, LHS); 10218 case AArch64CC::LT: 10219 if (!NoNans) 10220 return SDValue(); 10221 // If we ignore NaNs then we can use to the MI implementation. 10222 LLVM_FALLTHROUGH; 10223 case AArch64CC::MI: 10224 if (IsZero) 10225 return DAG.getNode(AArch64ISD::FCMLTz, dl, VT, LHS); 10226 return DAG.getNode(AArch64ISD::FCMGT, dl, VT, RHS, LHS); 10227 } 10228 } 10229 10230 switch (CC) { 10231 default: 10232 return SDValue(); 10233 case AArch64CC::NE: { 10234 SDValue Cmeq; 10235 if (IsZero) 10236 Cmeq = DAG.getNode(AArch64ISD::CMEQz, dl, VT, LHS); 10237 else 10238 Cmeq = DAG.getNode(AArch64ISD::CMEQ, dl, VT, LHS, RHS); 10239 return DAG.getNOT(dl, Cmeq, VT); 10240 } 10241 case AArch64CC::EQ: 10242 if (IsZero) 10243 return DAG.getNode(AArch64ISD::CMEQz, dl, VT, LHS); 10244 return DAG.getNode(AArch64ISD::CMEQ, dl, VT, LHS, RHS); 10245 case AArch64CC::GE: 10246 if (IsZero) 10247 return DAG.getNode(AArch64ISD::CMGEz, dl, VT, LHS); 10248 return DAG.getNode(AArch64ISD::CMGE, dl, VT, LHS, RHS); 10249 case AArch64CC::GT: 10250 if (IsZero) 10251 return DAG.getNode(AArch64ISD::CMGTz, dl, VT, LHS); 10252 return DAG.getNode(AArch64ISD::CMGT, dl, VT, LHS, RHS); 10253 case AArch64CC::LE: 10254 if (IsZero) 10255 return DAG.getNode(AArch64ISD::CMLEz, dl, VT, LHS); 10256 return DAG.getNode(AArch64ISD::CMGE, dl, VT, RHS, LHS); 10257 case AArch64CC::LS: 10258 return DAG.getNode(AArch64ISD::CMHS, dl, VT, RHS, LHS); 10259 case AArch64CC::LO: 10260 return DAG.getNode(AArch64ISD::CMHI, dl, VT, RHS, LHS); 10261 case AArch64CC::LT: 10262 if (IsZero) 10263 return DAG.getNode(AArch64ISD::CMLTz, dl, VT, LHS); 10264 return DAG.getNode(AArch64ISD::CMGT, dl, VT, RHS, LHS); 10265 case AArch64CC::HI: 10266 return DAG.getNode(AArch64ISD::CMHI, dl, VT, LHS, RHS); 10267 case AArch64CC::HS: 10268 return DAG.getNode(AArch64ISD::CMHS, dl, VT, LHS, RHS); 10269 } 10270 } 10271 10272 SDValue AArch64TargetLowering::LowerVSETCC(SDValue Op, 10273 SelectionDAG &DAG) const { 10274 if (Op.getValueType().isScalableVector()) { 10275 if (Op.getOperand(0).getValueType().isFloatingPoint()) 10276 return Op; 10277 return LowerToPredicatedOp(Op, DAG, AArch64ISD::SETCC_MERGE_ZERO); 10278 } 10279 10280 if (useSVEForFixedLengthVectorVT(Op.getOperand(0).getValueType())) 10281 return LowerFixedLengthVectorSetccToSVE(Op, DAG); 10282 10283 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get(); 10284 SDValue LHS = Op.getOperand(0); 10285 SDValue RHS = Op.getOperand(1); 10286 EVT CmpVT = LHS.getValueType().changeVectorElementTypeToInteger(); 10287 SDLoc dl(Op); 10288 10289 if (LHS.getValueType().getVectorElementType().isInteger()) { 10290 assert(LHS.getValueType() == RHS.getValueType()); 10291 AArch64CC::CondCode AArch64CC = changeIntCCToAArch64CC(CC); 10292 SDValue Cmp = 10293 EmitVectorComparison(LHS, RHS, AArch64CC, false, CmpVT, dl, DAG); 10294 return DAG.getSExtOrTrunc(Cmp, dl, Op.getValueType()); 10295 } 10296 10297 const bool FullFP16 = 10298 static_cast<const AArch64Subtarget &>(DAG.getSubtarget()).hasFullFP16(); 10299 10300 // Make v4f16 (only) fcmp operations utilise vector instructions 10301 // v8f16 support will be a litle more complicated 10302 if (!FullFP16 && LHS.getValueType().getVectorElementType() == MVT::f16) { 10303 if (LHS.getValueType().getVectorNumElements() == 4) { 10304 LHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::v4f32, LHS); 10305 RHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::v4f32, RHS); 10306 SDValue NewSetcc = DAG.getSetCC(dl, MVT::v4i16, LHS, RHS, CC); 10307 DAG.ReplaceAllUsesWith(Op, NewSetcc); 10308 CmpVT = MVT::v4i32; 10309 } else 10310 return SDValue(); 10311 } 10312 10313 assert((!FullFP16 && LHS.getValueType().getVectorElementType() != MVT::f16) || 10314 LHS.getValueType().getVectorElementType() != MVT::f128); 10315 10316 // Unfortunately, the mapping of LLVM FP CC's onto AArch64 CC's isn't totally 10317 // clean. Some of them require two branches to implement. 10318 AArch64CC::CondCode CC1, CC2; 10319 bool ShouldInvert; 10320 changeVectorFPCCToAArch64CC(CC, CC1, CC2, ShouldInvert); 10321 10322 bool NoNaNs = getTargetMachine().Options.NoNaNsFPMath; 10323 SDValue Cmp = 10324 EmitVectorComparison(LHS, RHS, CC1, NoNaNs, CmpVT, dl, DAG); 10325 if (!Cmp.getNode()) 10326 return SDValue(); 10327 10328 if (CC2 != AArch64CC::AL) { 10329 SDValue Cmp2 = 10330 EmitVectorComparison(LHS, RHS, CC2, NoNaNs, CmpVT, dl, DAG); 10331 if (!Cmp2.getNode()) 10332 return SDValue(); 10333 10334 Cmp = DAG.getNode(ISD::OR, dl, CmpVT, Cmp, Cmp2); 10335 } 10336 10337 Cmp = DAG.getSExtOrTrunc(Cmp, dl, Op.getValueType()); 10338 10339 if (ShouldInvert) 10340 Cmp = DAG.getNOT(dl, Cmp, Cmp.getValueType()); 10341 10342 return Cmp; 10343 } 10344 10345 static SDValue getReductionSDNode(unsigned Op, SDLoc DL, SDValue ScalarOp, 10346 SelectionDAG &DAG) { 10347 SDValue VecOp = ScalarOp.getOperand(0); 10348 auto Rdx = DAG.getNode(Op, DL, VecOp.getSimpleValueType(), VecOp); 10349 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, ScalarOp.getValueType(), Rdx, 10350 DAG.getConstant(0, DL, MVT::i64)); 10351 } 10352 10353 SDValue AArch64TargetLowering::LowerVECREDUCE(SDValue Op, 10354 SelectionDAG &DAG) const { 10355 SDValue Src = Op.getOperand(0); 10356 10357 // Try to lower fixed length reductions to SVE. 10358 EVT SrcVT = Src.getValueType(); 10359 bool OverrideNEON = Op.getOpcode() == ISD::VECREDUCE_AND || 10360 Op.getOpcode() == ISD::VECREDUCE_OR || 10361 Op.getOpcode() == ISD::VECREDUCE_XOR || 10362 Op.getOpcode() == ISD::VECREDUCE_FADD || 10363 (Op.getOpcode() != ISD::VECREDUCE_ADD && 10364 SrcVT.getVectorElementType() == MVT::i64); 10365 if (SrcVT.isScalableVector() || 10366 useSVEForFixedLengthVectorVT(SrcVT, OverrideNEON)) { 10367 10368 if (SrcVT.getVectorElementType() == MVT::i1) 10369 return LowerPredReductionToSVE(Op, DAG); 10370 10371 switch (Op.getOpcode()) { 10372 case ISD::VECREDUCE_ADD: 10373 return LowerReductionToSVE(AArch64ISD::UADDV_PRED, Op, DAG); 10374 case ISD::VECREDUCE_AND: 10375 return LowerReductionToSVE(AArch64ISD::ANDV_PRED, Op, DAG); 10376 case ISD::VECREDUCE_OR: 10377 return LowerReductionToSVE(AArch64ISD::ORV_PRED, Op, DAG); 10378 case ISD::VECREDUCE_SMAX: 10379 return LowerReductionToSVE(AArch64ISD::SMAXV_PRED, Op, DAG); 10380 case ISD::VECREDUCE_SMIN: 10381 return LowerReductionToSVE(AArch64ISD::SMINV_PRED, Op, DAG); 10382 case ISD::VECREDUCE_UMAX: 10383 return LowerReductionToSVE(AArch64ISD::UMAXV_PRED, Op, DAG); 10384 case ISD::VECREDUCE_UMIN: 10385 return LowerReductionToSVE(AArch64ISD::UMINV_PRED, Op, DAG); 10386 case ISD::VECREDUCE_XOR: 10387 return LowerReductionToSVE(AArch64ISD::EORV_PRED, Op, DAG); 10388 case ISD::VECREDUCE_FADD: 10389 return LowerReductionToSVE(AArch64ISD::FADDV_PRED, Op, DAG); 10390 case ISD::VECREDUCE_FMAX: 10391 return LowerReductionToSVE(AArch64ISD::FMAXNMV_PRED, Op, DAG); 10392 case ISD::VECREDUCE_FMIN: 10393 return LowerReductionToSVE(AArch64ISD::FMINNMV_PRED, Op, DAG); 10394 default: 10395 llvm_unreachable("Unhandled fixed length reduction"); 10396 } 10397 } 10398 10399 // Lower NEON reductions. 10400 SDLoc dl(Op); 10401 switch (Op.getOpcode()) { 10402 case ISD::VECREDUCE_ADD: 10403 return getReductionSDNode(AArch64ISD::UADDV, dl, Op, DAG); 10404 case ISD::VECREDUCE_SMAX: 10405 return getReductionSDNode(AArch64ISD::SMAXV, dl, Op, DAG); 10406 case ISD::VECREDUCE_SMIN: 10407 return getReductionSDNode(AArch64ISD::SMINV, dl, Op, DAG); 10408 case ISD::VECREDUCE_UMAX: 10409 return getReductionSDNode(AArch64ISD::UMAXV, dl, Op, DAG); 10410 case ISD::VECREDUCE_UMIN: 10411 return getReductionSDNode(AArch64ISD::UMINV, dl, Op, DAG); 10412 case ISD::VECREDUCE_FMAX: { 10413 return DAG.getNode( 10414 ISD::INTRINSIC_WO_CHAIN, dl, Op.getValueType(), 10415 DAG.getConstant(Intrinsic::aarch64_neon_fmaxnmv, dl, MVT::i32), 10416 Src); 10417 } 10418 case ISD::VECREDUCE_FMIN: { 10419 return DAG.getNode( 10420 ISD::INTRINSIC_WO_CHAIN, dl, Op.getValueType(), 10421 DAG.getConstant(Intrinsic::aarch64_neon_fminnmv, dl, MVT::i32), 10422 Src); 10423 } 10424 default: 10425 llvm_unreachable("Unhandled reduction"); 10426 } 10427 } 10428 10429 SDValue AArch64TargetLowering::LowerATOMIC_LOAD_SUB(SDValue Op, 10430 SelectionDAG &DAG) const { 10431 auto &Subtarget = static_cast<const AArch64Subtarget &>(DAG.getSubtarget()); 10432 if (!Subtarget.hasLSE() && !Subtarget.outlineAtomics()) 10433 return SDValue(); 10434 10435 // LSE has an atomic load-add instruction, but not a load-sub. 10436 SDLoc dl(Op); 10437 MVT VT = Op.getSimpleValueType(); 10438 SDValue RHS = Op.getOperand(2); 10439 AtomicSDNode *AN = cast<AtomicSDNode>(Op.getNode()); 10440 RHS = DAG.getNode(ISD::SUB, dl, VT, DAG.getConstant(0, dl, VT), RHS); 10441 return DAG.getAtomic(ISD::ATOMIC_LOAD_ADD, dl, AN->getMemoryVT(), 10442 Op.getOperand(0), Op.getOperand(1), RHS, 10443 AN->getMemOperand()); 10444 } 10445 10446 SDValue AArch64TargetLowering::LowerATOMIC_LOAD_AND(SDValue Op, 10447 SelectionDAG &DAG) const { 10448 auto &Subtarget = static_cast<const AArch64Subtarget &>(DAG.getSubtarget()); 10449 if (!Subtarget.hasLSE() && !Subtarget.outlineAtomics()) 10450 return SDValue(); 10451 10452 // LSE has an atomic load-clear instruction, but not a load-and. 10453 SDLoc dl(Op); 10454 MVT VT = Op.getSimpleValueType(); 10455 SDValue RHS = Op.getOperand(2); 10456 AtomicSDNode *AN = cast<AtomicSDNode>(Op.getNode()); 10457 RHS = DAG.getNode(ISD::XOR, dl, VT, DAG.getConstant(-1ULL, dl, VT), RHS); 10458 return DAG.getAtomic(ISD::ATOMIC_LOAD_CLR, dl, AN->getMemoryVT(), 10459 Op.getOperand(0), Op.getOperand(1), RHS, 10460 AN->getMemOperand()); 10461 } 10462 10463 SDValue AArch64TargetLowering::LowerWindowsDYNAMIC_STACKALLOC( 10464 SDValue Op, SDValue Chain, SDValue &Size, SelectionDAG &DAG) const { 10465 SDLoc dl(Op); 10466 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 10467 SDValue Callee = DAG.getTargetExternalSymbol("__chkstk", PtrVT, 0); 10468 10469 const AArch64RegisterInfo *TRI = Subtarget->getRegisterInfo(); 10470 const uint32_t *Mask = TRI->getWindowsStackProbePreservedMask(); 10471 if (Subtarget->hasCustomCallingConv()) 10472 TRI->UpdateCustomCallPreservedMask(DAG.getMachineFunction(), &Mask); 10473 10474 Size = DAG.getNode(ISD::SRL, dl, MVT::i64, Size, 10475 DAG.getConstant(4, dl, MVT::i64)); 10476 Chain = DAG.getCopyToReg(Chain, dl, AArch64::X15, Size, SDValue()); 10477 Chain = 10478 DAG.getNode(AArch64ISD::CALL, dl, DAG.getVTList(MVT::Other, MVT::Glue), 10479 Chain, Callee, DAG.getRegister(AArch64::X15, MVT::i64), 10480 DAG.getRegisterMask(Mask), Chain.getValue(1)); 10481 // To match the actual intent better, we should read the output from X15 here 10482 // again (instead of potentially spilling it to the stack), but rereading Size 10483 // from X15 here doesn't work at -O0, since it thinks that X15 is undefined 10484 // here. 10485 10486 Size = DAG.getNode(ISD::SHL, dl, MVT::i64, Size, 10487 DAG.getConstant(4, dl, MVT::i64)); 10488 return Chain; 10489 } 10490 10491 SDValue 10492 AArch64TargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op, 10493 SelectionDAG &DAG) const { 10494 assert(Subtarget->isTargetWindows() && 10495 "Only Windows alloca probing supported"); 10496 SDLoc dl(Op); 10497 // Get the inputs. 10498 SDNode *Node = Op.getNode(); 10499 SDValue Chain = Op.getOperand(0); 10500 SDValue Size = Op.getOperand(1); 10501 MaybeAlign Align = 10502 cast<ConstantSDNode>(Op.getOperand(2))->getMaybeAlignValue(); 10503 EVT VT = Node->getValueType(0); 10504 10505 if (DAG.getMachineFunction().getFunction().hasFnAttribute( 10506 "no-stack-arg-probe")) { 10507 SDValue SP = DAG.getCopyFromReg(Chain, dl, AArch64::SP, MVT::i64); 10508 Chain = SP.getValue(1); 10509 SP = DAG.getNode(ISD::SUB, dl, MVT::i64, SP, Size); 10510 if (Align) 10511 SP = DAG.getNode(ISD::AND, dl, VT, SP.getValue(0), 10512 DAG.getConstant(-(uint64_t)Align->value(), dl, VT)); 10513 Chain = DAG.getCopyToReg(Chain, dl, AArch64::SP, SP); 10514 SDValue Ops[2] = {SP, Chain}; 10515 return DAG.getMergeValues(Ops, dl); 10516 } 10517 10518 Chain = DAG.getCALLSEQ_START(Chain, 0, 0, dl); 10519 10520 Chain = LowerWindowsDYNAMIC_STACKALLOC(Op, Chain, Size, DAG); 10521 10522 SDValue SP = DAG.getCopyFromReg(Chain, dl, AArch64::SP, MVT::i64); 10523 Chain = SP.getValue(1); 10524 SP = DAG.getNode(ISD::SUB, dl, MVT::i64, SP, Size); 10525 if (Align) 10526 SP = DAG.getNode(ISD::AND, dl, VT, SP.getValue(0), 10527 DAG.getConstant(-(uint64_t)Align->value(), dl, VT)); 10528 Chain = DAG.getCopyToReg(Chain, dl, AArch64::SP, SP); 10529 10530 Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(0, dl, true), 10531 DAG.getIntPtrConstant(0, dl, true), SDValue(), dl); 10532 10533 SDValue Ops[2] = {SP, Chain}; 10534 return DAG.getMergeValues(Ops, dl); 10535 } 10536 10537 SDValue AArch64TargetLowering::LowerVSCALE(SDValue Op, 10538 SelectionDAG &DAG) const { 10539 EVT VT = Op.getValueType(); 10540 assert(VT != MVT::i64 && "Expected illegal VSCALE node"); 10541 10542 SDLoc DL(Op); 10543 APInt MulImm = cast<ConstantSDNode>(Op.getOperand(0))->getAPIntValue(); 10544 return DAG.getZExtOrTrunc(DAG.getVScale(DL, MVT::i64, MulImm.sextOrSelf(64)), 10545 DL, VT); 10546 } 10547 10548 /// Set the IntrinsicInfo for the `aarch64_sve_st<N>` intrinsics. 10549 template <unsigned NumVecs> 10550 static bool 10551 setInfoSVEStN(const AArch64TargetLowering &TLI, const DataLayout &DL, 10552 AArch64TargetLowering::IntrinsicInfo &Info, const CallInst &CI) { 10553 Info.opc = ISD::INTRINSIC_VOID; 10554 // Retrieve EC from first vector argument. 10555 const EVT VT = TLI.getMemValueType(DL, CI.getArgOperand(0)->getType()); 10556 ElementCount EC = VT.getVectorElementCount(); 10557 #ifndef NDEBUG 10558 // Check the assumption that all input vectors are the same type. 10559 for (unsigned I = 0; I < NumVecs; ++I) 10560 assert(VT == TLI.getMemValueType(DL, CI.getArgOperand(I)->getType()) && 10561 "Invalid type."); 10562 #endif 10563 // memVT is `NumVecs * VT`. 10564 Info.memVT = EVT::getVectorVT(CI.getType()->getContext(), VT.getScalarType(), 10565 EC * NumVecs); 10566 Info.ptrVal = CI.getArgOperand(CI.getNumArgOperands() - 1); 10567 Info.offset = 0; 10568 Info.align.reset(); 10569 Info.flags = MachineMemOperand::MOStore; 10570 return true; 10571 } 10572 10573 /// getTgtMemIntrinsic - Represent NEON load and store intrinsics as 10574 /// MemIntrinsicNodes. The associated MachineMemOperands record the alignment 10575 /// specified in the intrinsic calls. 10576 bool AArch64TargetLowering::getTgtMemIntrinsic(IntrinsicInfo &Info, 10577 const CallInst &I, 10578 MachineFunction &MF, 10579 unsigned Intrinsic) const { 10580 auto &DL = I.getModule()->getDataLayout(); 10581 switch (Intrinsic) { 10582 case Intrinsic::aarch64_sve_st2: 10583 return setInfoSVEStN<2>(*this, DL, Info, I); 10584 case Intrinsic::aarch64_sve_st3: 10585 return setInfoSVEStN<3>(*this, DL, Info, I); 10586 case Intrinsic::aarch64_sve_st4: 10587 return setInfoSVEStN<4>(*this, DL, Info, I); 10588 case Intrinsic::aarch64_neon_ld2: 10589 case Intrinsic::aarch64_neon_ld3: 10590 case Intrinsic::aarch64_neon_ld4: 10591 case Intrinsic::aarch64_neon_ld1x2: 10592 case Intrinsic::aarch64_neon_ld1x3: 10593 case Intrinsic::aarch64_neon_ld1x4: 10594 case Intrinsic::aarch64_neon_ld2lane: 10595 case Intrinsic::aarch64_neon_ld3lane: 10596 case Intrinsic::aarch64_neon_ld4lane: 10597 case Intrinsic::aarch64_neon_ld2r: 10598 case Intrinsic::aarch64_neon_ld3r: 10599 case Intrinsic::aarch64_neon_ld4r: { 10600 Info.opc = ISD::INTRINSIC_W_CHAIN; 10601 // Conservatively set memVT to the entire set of vectors loaded. 10602 uint64_t NumElts = DL.getTypeSizeInBits(I.getType()) / 64; 10603 Info.memVT = EVT::getVectorVT(I.getType()->getContext(), MVT::i64, NumElts); 10604 Info.ptrVal = I.getArgOperand(I.getNumArgOperands() - 1); 10605 Info.offset = 0; 10606 Info.align.reset(); 10607 // volatile loads with NEON intrinsics not supported 10608 Info.flags = MachineMemOperand::MOLoad; 10609 return true; 10610 } 10611 case Intrinsic::aarch64_neon_st2: 10612 case Intrinsic::aarch64_neon_st3: 10613 case Intrinsic::aarch64_neon_st4: 10614 case Intrinsic::aarch64_neon_st1x2: 10615 case Intrinsic::aarch64_neon_st1x3: 10616 case Intrinsic::aarch64_neon_st1x4: 10617 case Intrinsic::aarch64_neon_st2lane: 10618 case Intrinsic::aarch64_neon_st3lane: 10619 case Intrinsic::aarch64_neon_st4lane: { 10620 Info.opc = ISD::INTRINSIC_VOID; 10621 // Conservatively set memVT to the entire set of vectors stored. 10622 unsigned NumElts = 0; 10623 for (unsigned ArgI = 0, ArgE = I.getNumArgOperands(); ArgI < ArgE; ++ArgI) { 10624 Type *ArgTy = I.getArgOperand(ArgI)->getType(); 10625 if (!ArgTy->isVectorTy()) 10626 break; 10627 NumElts += DL.getTypeSizeInBits(ArgTy) / 64; 10628 } 10629 Info.memVT = EVT::getVectorVT(I.getType()->getContext(), MVT::i64, NumElts); 10630 Info.ptrVal = I.getArgOperand(I.getNumArgOperands() - 1); 10631 Info.offset = 0; 10632 Info.align.reset(); 10633 // volatile stores with NEON intrinsics not supported 10634 Info.flags = MachineMemOperand::MOStore; 10635 return true; 10636 } 10637 case Intrinsic::aarch64_ldaxr: 10638 case Intrinsic::aarch64_ldxr: { 10639 PointerType *PtrTy = cast<PointerType>(I.getArgOperand(0)->getType()); 10640 Info.opc = ISD::INTRINSIC_W_CHAIN; 10641 Info.memVT = MVT::getVT(PtrTy->getElementType()); 10642 Info.ptrVal = I.getArgOperand(0); 10643 Info.offset = 0; 10644 Info.align = DL.getABITypeAlign(PtrTy->getElementType()); 10645 Info.flags = MachineMemOperand::MOLoad | MachineMemOperand::MOVolatile; 10646 return true; 10647 } 10648 case Intrinsic::aarch64_stlxr: 10649 case Intrinsic::aarch64_stxr: { 10650 PointerType *PtrTy = cast<PointerType>(I.getArgOperand(1)->getType()); 10651 Info.opc = ISD::INTRINSIC_W_CHAIN; 10652 Info.memVT = MVT::getVT(PtrTy->getElementType()); 10653 Info.ptrVal = I.getArgOperand(1); 10654 Info.offset = 0; 10655 Info.align = DL.getABITypeAlign(PtrTy->getElementType()); 10656 Info.flags = MachineMemOperand::MOStore | MachineMemOperand::MOVolatile; 10657 return true; 10658 } 10659 case Intrinsic::aarch64_ldaxp: 10660 case Intrinsic::aarch64_ldxp: 10661 Info.opc = ISD::INTRINSIC_W_CHAIN; 10662 Info.memVT = MVT::i128; 10663 Info.ptrVal = I.getArgOperand(0); 10664 Info.offset = 0; 10665 Info.align = Align(16); 10666 Info.flags = MachineMemOperand::MOLoad | MachineMemOperand::MOVolatile; 10667 return true; 10668 case Intrinsic::aarch64_stlxp: 10669 case Intrinsic::aarch64_stxp: 10670 Info.opc = ISD::INTRINSIC_W_CHAIN; 10671 Info.memVT = MVT::i128; 10672 Info.ptrVal = I.getArgOperand(2); 10673 Info.offset = 0; 10674 Info.align = Align(16); 10675 Info.flags = MachineMemOperand::MOStore | MachineMemOperand::MOVolatile; 10676 return true; 10677 case Intrinsic::aarch64_sve_ldnt1: { 10678 PointerType *PtrTy = cast<PointerType>(I.getArgOperand(1)->getType()); 10679 Info.opc = ISD::INTRINSIC_W_CHAIN; 10680 Info.memVT = MVT::getVT(I.getType()); 10681 Info.ptrVal = I.getArgOperand(1); 10682 Info.offset = 0; 10683 Info.align = DL.getABITypeAlign(PtrTy->getElementType()); 10684 Info.flags = MachineMemOperand::MOLoad; 10685 if (Intrinsic == Intrinsic::aarch64_sve_ldnt1) 10686 Info.flags |= MachineMemOperand::MONonTemporal; 10687 return true; 10688 } 10689 case Intrinsic::aarch64_sve_stnt1: { 10690 PointerType *PtrTy = cast<PointerType>(I.getArgOperand(2)->getType()); 10691 Info.opc = ISD::INTRINSIC_W_CHAIN; 10692 Info.memVT = MVT::getVT(I.getOperand(0)->getType()); 10693 Info.ptrVal = I.getArgOperand(2); 10694 Info.offset = 0; 10695 Info.align = DL.getABITypeAlign(PtrTy->getElementType()); 10696 Info.flags = MachineMemOperand::MOStore; 10697 if (Intrinsic == Intrinsic::aarch64_sve_stnt1) 10698 Info.flags |= MachineMemOperand::MONonTemporal; 10699 return true; 10700 } 10701 default: 10702 break; 10703 } 10704 10705 return false; 10706 } 10707 10708 bool AArch64TargetLowering::shouldReduceLoadWidth(SDNode *Load, 10709 ISD::LoadExtType ExtTy, 10710 EVT NewVT) const { 10711 // TODO: This may be worth removing. Check regression tests for diffs. 10712 if (!TargetLoweringBase::shouldReduceLoadWidth(Load, ExtTy, NewVT)) 10713 return false; 10714 10715 // If we're reducing the load width in order to avoid having to use an extra 10716 // instruction to do extension then it's probably a good idea. 10717 if (ExtTy != ISD::NON_EXTLOAD) 10718 return true; 10719 // Don't reduce load width if it would prevent us from combining a shift into 10720 // the offset. 10721 MemSDNode *Mem = dyn_cast<MemSDNode>(Load); 10722 assert(Mem); 10723 const SDValue &Base = Mem->getBasePtr(); 10724 if (Base.getOpcode() == ISD::ADD && 10725 Base.getOperand(1).getOpcode() == ISD::SHL && 10726 Base.getOperand(1).hasOneUse() && 10727 Base.getOperand(1).getOperand(1).getOpcode() == ISD::Constant) { 10728 // The shift can be combined if it matches the size of the value being 10729 // loaded (and so reducing the width would make it not match). 10730 uint64_t ShiftAmount = Base.getOperand(1).getConstantOperandVal(1); 10731 uint64_t LoadBytes = Mem->getMemoryVT().getSizeInBits()/8; 10732 if (ShiftAmount == Log2_32(LoadBytes)) 10733 return false; 10734 } 10735 // We have no reason to disallow reducing the load width, so allow it. 10736 return true; 10737 } 10738 10739 // Truncations from 64-bit GPR to 32-bit GPR is free. 10740 bool AArch64TargetLowering::isTruncateFree(Type *Ty1, Type *Ty2) const { 10741 if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy()) 10742 return false; 10743 uint64_t NumBits1 = Ty1->getPrimitiveSizeInBits().getFixedSize(); 10744 uint64_t NumBits2 = Ty2->getPrimitiveSizeInBits().getFixedSize(); 10745 return NumBits1 > NumBits2; 10746 } 10747 bool AArch64TargetLowering::isTruncateFree(EVT VT1, EVT VT2) const { 10748 if (VT1.isVector() || VT2.isVector() || !VT1.isInteger() || !VT2.isInteger()) 10749 return false; 10750 uint64_t NumBits1 = VT1.getFixedSizeInBits(); 10751 uint64_t NumBits2 = VT2.getFixedSizeInBits(); 10752 return NumBits1 > NumBits2; 10753 } 10754 10755 /// Check if it is profitable to hoist instruction in then/else to if. 10756 /// Not profitable if I and it's user can form a FMA instruction 10757 /// because we prefer FMSUB/FMADD. 10758 bool AArch64TargetLowering::isProfitableToHoist(Instruction *I) const { 10759 if (I->getOpcode() != Instruction::FMul) 10760 return true; 10761 10762 if (!I->hasOneUse()) 10763 return true; 10764 10765 Instruction *User = I->user_back(); 10766 10767 if (User && 10768 !(User->getOpcode() == Instruction::FSub || 10769 User->getOpcode() == Instruction::FAdd)) 10770 return true; 10771 10772 const TargetOptions &Options = getTargetMachine().Options; 10773 const Function *F = I->getFunction(); 10774 const DataLayout &DL = F->getParent()->getDataLayout(); 10775 Type *Ty = User->getOperand(0)->getType(); 10776 10777 return !(isFMAFasterThanFMulAndFAdd(*F, Ty) && 10778 isOperationLegalOrCustom(ISD::FMA, getValueType(DL, Ty)) && 10779 (Options.AllowFPOpFusion == FPOpFusion::Fast || 10780 Options.UnsafeFPMath)); 10781 } 10782 10783 // All 32-bit GPR operations implicitly zero the high-half of the corresponding 10784 // 64-bit GPR. 10785 bool AArch64TargetLowering::isZExtFree(Type *Ty1, Type *Ty2) const { 10786 if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy()) 10787 return false; 10788 unsigned NumBits1 = Ty1->getPrimitiveSizeInBits(); 10789 unsigned NumBits2 = Ty2->getPrimitiveSizeInBits(); 10790 return NumBits1 == 32 && NumBits2 == 64; 10791 } 10792 bool AArch64TargetLowering::isZExtFree(EVT VT1, EVT VT2) const { 10793 if (VT1.isVector() || VT2.isVector() || !VT1.isInteger() || !VT2.isInteger()) 10794 return false; 10795 unsigned NumBits1 = VT1.getSizeInBits(); 10796 unsigned NumBits2 = VT2.getSizeInBits(); 10797 return NumBits1 == 32 && NumBits2 == 64; 10798 } 10799 10800 bool AArch64TargetLowering::isZExtFree(SDValue Val, EVT VT2) const { 10801 EVT VT1 = Val.getValueType(); 10802 if (isZExtFree(VT1, VT2)) { 10803 return true; 10804 } 10805 10806 if (Val.getOpcode() != ISD::LOAD) 10807 return false; 10808 10809 // 8-, 16-, and 32-bit integer loads all implicitly zero-extend. 10810 return (VT1.isSimple() && !VT1.isVector() && VT1.isInteger() && 10811 VT2.isSimple() && !VT2.isVector() && VT2.isInteger() && 10812 VT1.getSizeInBits() <= 32); 10813 } 10814 10815 bool AArch64TargetLowering::isExtFreeImpl(const Instruction *Ext) const { 10816 if (isa<FPExtInst>(Ext)) 10817 return false; 10818 10819 // Vector types are not free. 10820 if (Ext->getType()->isVectorTy()) 10821 return false; 10822 10823 for (const Use &U : Ext->uses()) { 10824 // The extension is free if we can fold it with a left shift in an 10825 // addressing mode or an arithmetic operation: add, sub, and cmp. 10826 10827 // Is there a shift? 10828 const Instruction *Instr = cast<Instruction>(U.getUser()); 10829 10830 // Is this a constant shift? 10831 switch (Instr->getOpcode()) { 10832 case Instruction::Shl: 10833 if (!isa<ConstantInt>(Instr->getOperand(1))) 10834 return false; 10835 break; 10836 case Instruction::GetElementPtr: { 10837 gep_type_iterator GTI = gep_type_begin(Instr); 10838 auto &DL = Ext->getModule()->getDataLayout(); 10839 std::advance(GTI, U.getOperandNo()-1); 10840 Type *IdxTy = GTI.getIndexedType(); 10841 // This extension will end up with a shift because of the scaling factor. 10842 // 8-bit sized types have a scaling factor of 1, thus a shift amount of 0. 10843 // Get the shift amount based on the scaling factor: 10844 // log2(sizeof(IdxTy)) - log2(8). 10845 uint64_t ShiftAmt = 10846 countTrailingZeros(DL.getTypeStoreSizeInBits(IdxTy).getFixedSize()) - 3; 10847 // Is the constant foldable in the shift of the addressing mode? 10848 // I.e., shift amount is between 1 and 4 inclusive. 10849 if (ShiftAmt == 0 || ShiftAmt > 4) 10850 return false; 10851 break; 10852 } 10853 case Instruction::Trunc: 10854 // Check if this is a noop. 10855 // trunc(sext ty1 to ty2) to ty1. 10856 if (Instr->getType() == Ext->getOperand(0)->getType()) 10857 continue; 10858 LLVM_FALLTHROUGH; 10859 default: 10860 return false; 10861 } 10862 10863 // At this point we can use the bfm family, so this extension is free 10864 // for that use. 10865 } 10866 return true; 10867 } 10868 10869 /// Check if both Op1 and Op2 are shufflevector extracts of either the lower 10870 /// or upper half of the vector elements. 10871 static bool areExtractShuffleVectors(Value *Op1, Value *Op2) { 10872 auto areTypesHalfed = [](Value *FullV, Value *HalfV) { 10873 auto *FullTy = FullV->getType(); 10874 auto *HalfTy = HalfV->getType(); 10875 return FullTy->getPrimitiveSizeInBits().getFixedSize() == 10876 2 * HalfTy->getPrimitiveSizeInBits().getFixedSize(); 10877 }; 10878 10879 auto extractHalf = [](Value *FullV, Value *HalfV) { 10880 auto *FullVT = cast<FixedVectorType>(FullV->getType()); 10881 auto *HalfVT = cast<FixedVectorType>(HalfV->getType()); 10882 return FullVT->getNumElements() == 2 * HalfVT->getNumElements(); 10883 }; 10884 10885 ArrayRef<int> M1, M2; 10886 Value *S1Op1, *S2Op1; 10887 if (!match(Op1, m_Shuffle(m_Value(S1Op1), m_Undef(), m_Mask(M1))) || 10888 !match(Op2, m_Shuffle(m_Value(S2Op1), m_Undef(), m_Mask(M2)))) 10889 return false; 10890 10891 // Check that the operands are half as wide as the result and we extract 10892 // half of the elements of the input vectors. 10893 if (!areTypesHalfed(S1Op1, Op1) || !areTypesHalfed(S2Op1, Op2) || 10894 !extractHalf(S1Op1, Op1) || !extractHalf(S2Op1, Op2)) 10895 return false; 10896 10897 // Check the mask extracts either the lower or upper half of vector 10898 // elements. 10899 int M1Start = -1; 10900 int M2Start = -1; 10901 int NumElements = cast<FixedVectorType>(Op1->getType())->getNumElements() * 2; 10902 if (!ShuffleVectorInst::isExtractSubvectorMask(M1, NumElements, M1Start) || 10903 !ShuffleVectorInst::isExtractSubvectorMask(M2, NumElements, M2Start) || 10904 M1Start != M2Start || (M1Start != 0 && M2Start != (NumElements / 2))) 10905 return false; 10906 10907 return true; 10908 } 10909 10910 /// Check if Ext1 and Ext2 are extends of the same type, doubling the bitwidth 10911 /// of the vector elements. 10912 static bool areExtractExts(Value *Ext1, Value *Ext2) { 10913 auto areExtDoubled = [](Instruction *Ext) { 10914 return Ext->getType()->getScalarSizeInBits() == 10915 2 * Ext->getOperand(0)->getType()->getScalarSizeInBits(); 10916 }; 10917 10918 if (!match(Ext1, m_ZExtOrSExt(m_Value())) || 10919 !match(Ext2, m_ZExtOrSExt(m_Value())) || 10920 !areExtDoubled(cast<Instruction>(Ext1)) || 10921 !areExtDoubled(cast<Instruction>(Ext2))) 10922 return false; 10923 10924 return true; 10925 } 10926 10927 /// Check if Op could be used with vmull_high_p64 intrinsic. 10928 static bool isOperandOfVmullHighP64(Value *Op) { 10929 Value *VectorOperand = nullptr; 10930 ConstantInt *ElementIndex = nullptr; 10931 return match(Op, m_ExtractElt(m_Value(VectorOperand), 10932 m_ConstantInt(ElementIndex))) && 10933 ElementIndex->getValue() == 1 && 10934 isa<FixedVectorType>(VectorOperand->getType()) && 10935 cast<FixedVectorType>(VectorOperand->getType())->getNumElements() == 2; 10936 } 10937 10938 /// Check if Op1 and Op2 could be used with vmull_high_p64 intrinsic. 10939 static bool areOperandsOfVmullHighP64(Value *Op1, Value *Op2) { 10940 return isOperandOfVmullHighP64(Op1) && isOperandOfVmullHighP64(Op2); 10941 } 10942 10943 /// Check if sinking \p I's operands to I's basic block is profitable, because 10944 /// the operands can be folded into a target instruction, e.g. 10945 /// shufflevectors extracts and/or sext/zext can be folded into (u,s)subl(2). 10946 bool AArch64TargetLowering::shouldSinkOperands( 10947 Instruction *I, SmallVectorImpl<Use *> &Ops) const { 10948 if (!I->getType()->isVectorTy()) 10949 return false; 10950 10951 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(I)) { 10952 switch (II->getIntrinsicID()) { 10953 case Intrinsic::aarch64_neon_umull: 10954 if (!areExtractShuffleVectors(II->getOperand(0), II->getOperand(1))) 10955 return false; 10956 Ops.push_back(&II->getOperandUse(0)); 10957 Ops.push_back(&II->getOperandUse(1)); 10958 return true; 10959 10960 case Intrinsic::aarch64_neon_pmull64: 10961 if (!areOperandsOfVmullHighP64(II->getArgOperand(0), 10962 II->getArgOperand(1))) 10963 return false; 10964 Ops.push_back(&II->getArgOperandUse(0)); 10965 Ops.push_back(&II->getArgOperandUse(1)); 10966 return true; 10967 10968 default: 10969 return false; 10970 } 10971 } 10972 10973 switch (I->getOpcode()) { 10974 case Instruction::Sub: 10975 case Instruction::Add: { 10976 if (!areExtractExts(I->getOperand(0), I->getOperand(1))) 10977 return false; 10978 10979 // If the exts' operands extract either the lower or upper elements, we 10980 // can sink them too. 10981 auto Ext1 = cast<Instruction>(I->getOperand(0)); 10982 auto Ext2 = cast<Instruction>(I->getOperand(1)); 10983 if (areExtractShuffleVectors(Ext1, Ext2)) { 10984 Ops.push_back(&Ext1->getOperandUse(0)); 10985 Ops.push_back(&Ext2->getOperandUse(0)); 10986 } 10987 10988 Ops.push_back(&I->getOperandUse(0)); 10989 Ops.push_back(&I->getOperandUse(1)); 10990 10991 return true; 10992 } 10993 case Instruction::Mul: { 10994 bool IsProfitable = false; 10995 for (auto &Op : I->operands()) { 10996 // Make sure we are not already sinking this operand 10997 if (any_of(Ops, [&](Use *U) { return U->get() == Op; })) 10998 continue; 10999 11000 ShuffleVectorInst *Shuffle = dyn_cast<ShuffleVectorInst>(Op); 11001 if (!Shuffle || !Shuffle->isZeroEltSplat()) 11002 continue; 11003 11004 Value *ShuffleOperand = Shuffle->getOperand(0); 11005 InsertElementInst *Insert = dyn_cast<InsertElementInst>(ShuffleOperand); 11006 if (!Insert) 11007 continue; 11008 11009 Instruction *OperandInstr = dyn_cast<Instruction>(Insert->getOperand(1)); 11010 if (!OperandInstr) 11011 continue; 11012 11013 ConstantInt *ElementConstant = 11014 dyn_cast<ConstantInt>(Insert->getOperand(2)); 11015 // Check that the insertelement is inserting into element 0 11016 if (!ElementConstant || ElementConstant->getZExtValue() != 0) 11017 continue; 11018 11019 unsigned Opcode = OperandInstr->getOpcode(); 11020 if (Opcode != Instruction::SExt && Opcode != Instruction::ZExt) 11021 continue; 11022 11023 Ops.push_back(&Shuffle->getOperandUse(0)); 11024 Ops.push_back(&Op); 11025 IsProfitable = true; 11026 } 11027 11028 return IsProfitable; 11029 } 11030 default: 11031 return false; 11032 } 11033 return false; 11034 } 11035 11036 bool AArch64TargetLowering::hasPairedLoad(EVT LoadedType, 11037 Align &RequiredAligment) const { 11038 if (!LoadedType.isSimple() || 11039 (!LoadedType.isInteger() && !LoadedType.isFloatingPoint())) 11040 return false; 11041 // Cyclone supports unaligned accesses. 11042 RequiredAligment = Align(1); 11043 unsigned NumBits = LoadedType.getSizeInBits(); 11044 return NumBits == 32 || NumBits == 64; 11045 } 11046 11047 /// A helper function for determining the number of interleaved accesses we 11048 /// will generate when lowering accesses of the given type. 11049 unsigned 11050 AArch64TargetLowering::getNumInterleavedAccesses(VectorType *VecTy, 11051 const DataLayout &DL) const { 11052 return (DL.getTypeSizeInBits(VecTy) + 127) / 128; 11053 } 11054 11055 MachineMemOperand::Flags 11056 AArch64TargetLowering::getTargetMMOFlags(const Instruction &I) const { 11057 if (Subtarget->getProcFamily() == AArch64Subtarget::Falkor && 11058 I.getMetadata(FALKOR_STRIDED_ACCESS_MD) != nullptr) 11059 return MOStridedAccess; 11060 return MachineMemOperand::MONone; 11061 } 11062 11063 bool AArch64TargetLowering::isLegalInterleavedAccessType( 11064 VectorType *VecTy, const DataLayout &DL) const { 11065 11066 unsigned VecSize = DL.getTypeSizeInBits(VecTy); 11067 unsigned ElSize = DL.getTypeSizeInBits(VecTy->getElementType()); 11068 11069 // Ensure the number of vector elements is greater than 1. 11070 if (cast<FixedVectorType>(VecTy)->getNumElements() < 2) 11071 return false; 11072 11073 // Ensure the element type is legal. 11074 if (ElSize != 8 && ElSize != 16 && ElSize != 32 && ElSize != 64) 11075 return false; 11076 11077 // Ensure the total vector size is 64 or a multiple of 128. Types larger than 11078 // 128 will be split into multiple interleaved accesses. 11079 return VecSize == 64 || VecSize % 128 == 0; 11080 } 11081 11082 /// Lower an interleaved load into a ldN intrinsic. 11083 /// 11084 /// E.g. Lower an interleaved load (Factor = 2): 11085 /// %wide.vec = load <8 x i32>, <8 x i32>* %ptr 11086 /// %v0 = shuffle %wide.vec, undef, <0, 2, 4, 6> ; Extract even elements 11087 /// %v1 = shuffle %wide.vec, undef, <1, 3, 5, 7> ; Extract odd elements 11088 /// 11089 /// Into: 11090 /// %ld2 = { <4 x i32>, <4 x i32> } call llvm.aarch64.neon.ld2(%ptr) 11091 /// %vec0 = extractelement { <4 x i32>, <4 x i32> } %ld2, i32 0 11092 /// %vec1 = extractelement { <4 x i32>, <4 x i32> } %ld2, i32 1 11093 bool AArch64TargetLowering::lowerInterleavedLoad( 11094 LoadInst *LI, ArrayRef<ShuffleVectorInst *> Shuffles, 11095 ArrayRef<unsigned> Indices, unsigned Factor) const { 11096 assert(Factor >= 2 && Factor <= getMaxSupportedInterleaveFactor() && 11097 "Invalid interleave factor"); 11098 assert(!Shuffles.empty() && "Empty shufflevector input"); 11099 assert(Shuffles.size() == Indices.size() && 11100 "Unmatched number of shufflevectors and indices"); 11101 11102 const DataLayout &DL = LI->getModule()->getDataLayout(); 11103 11104 VectorType *VTy = Shuffles[0]->getType(); 11105 11106 // Skip if we do not have NEON and skip illegal vector types. We can 11107 // "legalize" wide vector types into multiple interleaved accesses as long as 11108 // the vector types are divisible by 128. 11109 if (!Subtarget->hasNEON() || !isLegalInterleavedAccessType(VTy, DL)) 11110 return false; 11111 11112 unsigned NumLoads = getNumInterleavedAccesses(VTy, DL); 11113 11114 auto *FVTy = cast<FixedVectorType>(VTy); 11115 11116 // A pointer vector can not be the return type of the ldN intrinsics. Need to 11117 // load integer vectors first and then convert to pointer vectors. 11118 Type *EltTy = FVTy->getElementType(); 11119 if (EltTy->isPointerTy()) 11120 FVTy = 11121 FixedVectorType::get(DL.getIntPtrType(EltTy), FVTy->getNumElements()); 11122 11123 IRBuilder<> Builder(LI); 11124 11125 // The base address of the load. 11126 Value *BaseAddr = LI->getPointerOperand(); 11127 11128 if (NumLoads > 1) { 11129 // If we're going to generate more than one load, reset the sub-vector type 11130 // to something legal. 11131 FVTy = FixedVectorType::get(FVTy->getElementType(), 11132 FVTy->getNumElements() / NumLoads); 11133 11134 // We will compute the pointer operand of each load from the original base 11135 // address using GEPs. Cast the base address to a pointer to the scalar 11136 // element type. 11137 BaseAddr = Builder.CreateBitCast( 11138 BaseAddr, 11139 FVTy->getElementType()->getPointerTo(LI->getPointerAddressSpace())); 11140 } 11141 11142 Type *PtrTy = FVTy->getPointerTo(LI->getPointerAddressSpace()); 11143 Type *Tys[2] = {FVTy, PtrTy}; 11144 static const Intrinsic::ID LoadInts[3] = {Intrinsic::aarch64_neon_ld2, 11145 Intrinsic::aarch64_neon_ld3, 11146 Intrinsic::aarch64_neon_ld4}; 11147 Function *LdNFunc = 11148 Intrinsic::getDeclaration(LI->getModule(), LoadInts[Factor - 2], Tys); 11149 11150 // Holds sub-vectors extracted from the load intrinsic return values. The 11151 // sub-vectors are associated with the shufflevector instructions they will 11152 // replace. 11153 DenseMap<ShuffleVectorInst *, SmallVector<Value *, 4>> SubVecs; 11154 11155 for (unsigned LoadCount = 0; LoadCount < NumLoads; ++LoadCount) { 11156 11157 // If we're generating more than one load, compute the base address of 11158 // subsequent loads as an offset from the previous. 11159 if (LoadCount > 0) 11160 BaseAddr = Builder.CreateConstGEP1_32(FVTy->getElementType(), BaseAddr, 11161 FVTy->getNumElements() * Factor); 11162 11163 CallInst *LdN = Builder.CreateCall( 11164 LdNFunc, Builder.CreateBitCast(BaseAddr, PtrTy), "ldN"); 11165 11166 // Extract and store the sub-vectors returned by the load intrinsic. 11167 for (unsigned i = 0; i < Shuffles.size(); i++) { 11168 ShuffleVectorInst *SVI = Shuffles[i]; 11169 unsigned Index = Indices[i]; 11170 11171 Value *SubVec = Builder.CreateExtractValue(LdN, Index); 11172 11173 // Convert the integer vector to pointer vector if the element is pointer. 11174 if (EltTy->isPointerTy()) 11175 SubVec = Builder.CreateIntToPtr( 11176 SubVec, FixedVectorType::get(SVI->getType()->getElementType(), 11177 FVTy->getNumElements())); 11178 SubVecs[SVI].push_back(SubVec); 11179 } 11180 } 11181 11182 // Replace uses of the shufflevector instructions with the sub-vectors 11183 // returned by the load intrinsic. If a shufflevector instruction is 11184 // associated with more than one sub-vector, those sub-vectors will be 11185 // concatenated into a single wide vector. 11186 for (ShuffleVectorInst *SVI : Shuffles) { 11187 auto &SubVec = SubVecs[SVI]; 11188 auto *WideVec = 11189 SubVec.size() > 1 ? concatenateVectors(Builder, SubVec) : SubVec[0]; 11190 SVI->replaceAllUsesWith(WideVec); 11191 } 11192 11193 return true; 11194 } 11195 11196 /// Lower an interleaved store into a stN intrinsic. 11197 /// 11198 /// E.g. Lower an interleaved store (Factor = 3): 11199 /// %i.vec = shuffle <8 x i32> %v0, <8 x i32> %v1, 11200 /// <0, 4, 8, 1, 5, 9, 2, 6, 10, 3, 7, 11> 11201 /// store <12 x i32> %i.vec, <12 x i32>* %ptr 11202 /// 11203 /// Into: 11204 /// %sub.v0 = shuffle <8 x i32> %v0, <8 x i32> v1, <0, 1, 2, 3> 11205 /// %sub.v1 = shuffle <8 x i32> %v0, <8 x i32> v1, <4, 5, 6, 7> 11206 /// %sub.v2 = shuffle <8 x i32> %v0, <8 x i32> v1, <8, 9, 10, 11> 11207 /// call void llvm.aarch64.neon.st3(%sub.v0, %sub.v1, %sub.v2, %ptr) 11208 /// 11209 /// Note that the new shufflevectors will be removed and we'll only generate one 11210 /// st3 instruction in CodeGen. 11211 /// 11212 /// Example for a more general valid mask (Factor 3). Lower: 11213 /// %i.vec = shuffle <32 x i32> %v0, <32 x i32> %v1, 11214 /// <4, 32, 16, 5, 33, 17, 6, 34, 18, 7, 35, 19> 11215 /// store <12 x i32> %i.vec, <12 x i32>* %ptr 11216 /// 11217 /// Into: 11218 /// %sub.v0 = shuffle <32 x i32> %v0, <32 x i32> v1, <4, 5, 6, 7> 11219 /// %sub.v1 = shuffle <32 x i32> %v0, <32 x i32> v1, <32, 33, 34, 35> 11220 /// %sub.v2 = shuffle <32 x i32> %v0, <32 x i32> v1, <16, 17, 18, 19> 11221 /// call void llvm.aarch64.neon.st3(%sub.v0, %sub.v1, %sub.v2, %ptr) 11222 bool AArch64TargetLowering::lowerInterleavedStore(StoreInst *SI, 11223 ShuffleVectorInst *SVI, 11224 unsigned Factor) const { 11225 assert(Factor >= 2 && Factor <= getMaxSupportedInterleaveFactor() && 11226 "Invalid interleave factor"); 11227 11228 auto *VecTy = cast<FixedVectorType>(SVI->getType()); 11229 assert(VecTy->getNumElements() % Factor == 0 && "Invalid interleaved store"); 11230 11231 unsigned LaneLen = VecTy->getNumElements() / Factor; 11232 Type *EltTy = VecTy->getElementType(); 11233 auto *SubVecTy = FixedVectorType::get(EltTy, LaneLen); 11234 11235 const DataLayout &DL = SI->getModule()->getDataLayout(); 11236 11237 // Skip if we do not have NEON and skip illegal vector types. We can 11238 // "legalize" wide vector types into multiple interleaved accesses as long as 11239 // the vector types are divisible by 128. 11240 if (!Subtarget->hasNEON() || !isLegalInterleavedAccessType(SubVecTy, DL)) 11241 return false; 11242 11243 unsigned NumStores = getNumInterleavedAccesses(SubVecTy, DL); 11244 11245 Value *Op0 = SVI->getOperand(0); 11246 Value *Op1 = SVI->getOperand(1); 11247 IRBuilder<> Builder(SI); 11248 11249 // StN intrinsics don't support pointer vectors as arguments. Convert pointer 11250 // vectors to integer vectors. 11251 if (EltTy->isPointerTy()) { 11252 Type *IntTy = DL.getIntPtrType(EltTy); 11253 unsigned NumOpElts = 11254 cast<FixedVectorType>(Op0->getType())->getNumElements(); 11255 11256 // Convert to the corresponding integer vector. 11257 auto *IntVecTy = FixedVectorType::get(IntTy, NumOpElts); 11258 Op0 = Builder.CreatePtrToInt(Op0, IntVecTy); 11259 Op1 = Builder.CreatePtrToInt(Op1, IntVecTy); 11260 11261 SubVecTy = FixedVectorType::get(IntTy, LaneLen); 11262 } 11263 11264 // The base address of the store. 11265 Value *BaseAddr = SI->getPointerOperand(); 11266 11267 if (NumStores > 1) { 11268 // If we're going to generate more than one store, reset the lane length 11269 // and sub-vector type to something legal. 11270 LaneLen /= NumStores; 11271 SubVecTy = FixedVectorType::get(SubVecTy->getElementType(), LaneLen); 11272 11273 // We will compute the pointer operand of each store from the original base 11274 // address using GEPs. Cast the base address to a pointer to the scalar 11275 // element type. 11276 BaseAddr = Builder.CreateBitCast( 11277 BaseAddr, 11278 SubVecTy->getElementType()->getPointerTo(SI->getPointerAddressSpace())); 11279 } 11280 11281 auto Mask = SVI->getShuffleMask(); 11282 11283 Type *PtrTy = SubVecTy->getPointerTo(SI->getPointerAddressSpace()); 11284 Type *Tys[2] = {SubVecTy, PtrTy}; 11285 static const Intrinsic::ID StoreInts[3] = {Intrinsic::aarch64_neon_st2, 11286 Intrinsic::aarch64_neon_st3, 11287 Intrinsic::aarch64_neon_st4}; 11288 Function *StNFunc = 11289 Intrinsic::getDeclaration(SI->getModule(), StoreInts[Factor - 2], Tys); 11290 11291 for (unsigned StoreCount = 0; StoreCount < NumStores; ++StoreCount) { 11292 11293 SmallVector<Value *, 5> Ops; 11294 11295 // Split the shufflevector operands into sub vectors for the new stN call. 11296 for (unsigned i = 0; i < Factor; i++) { 11297 unsigned IdxI = StoreCount * LaneLen * Factor + i; 11298 if (Mask[IdxI] >= 0) { 11299 Ops.push_back(Builder.CreateShuffleVector( 11300 Op0, Op1, createSequentialMask(Mask[IdxI], LaneLen, 0))); 11301 } else { 11302 unsigned StartMask = 0; 11303 for (unsigned j = 1; j < LaneLen; j++) { 11304 unsigned IdxJ = StoreCount * LaneLen * Factor + j; 11305 if (Mask[IdxJ * Factor + IdxI] >= 0) { 11306 StartMask = Mask[IdxJ * Factor + IdxI] - IdxJ; 11307 break; 11308 } 11309 } 11310 // Note: Filling undef gaps with random elements is ok, since 11311 // those elements were being written anyway (with undefs). 11312 // In the case of all undefs we're defaulting to using elems from 0 11313 // Note: StartMask cannot be negative, it's checked in 11314 // isReInterleaveMask 11315 Ops.push_back(Builder.CreateShuffleVector( 11316 Op0, Op1, createSequentialMask(StartMask, LaneLen, 0))); 11317 } 11318 } 11319 11320 // If we generating more than one store, we compute the base address of 11321 // subsequent stores as an offset from the previous. 11322 if (StoreCount > 0) 11323 BaseAddr = Builder.CreateConstGEP1_32(SubVecTy->getElementType(), 11324 BaseAddr, LaneLen * Factor); 11325 11326 Ops.push_back(Builder.CreateBitCast(BaseAddr, PtrTy)); 11327 Builder.CreateCall(StNFunc, Ops); 11328 } 11329 return true; 11330 } 11331 11332 // Lower an SVE structured load intrinsic returning a tuple type to target 11333 // specific intrinsic taking the same input but returning a multi-result value 11334 // of the split tuple type. 11335 // 11336 // E.g. Lowering an LD3: 11337 // 11338 // call <vscale x 12 x i32> @llvm.aarch64.sve.ld3.nxv12i32( 11339 // <vscale x 4 x i1> %pred, 11340 // <vscale x 4 x i32>* %addr) 11341 // 11342 // Output DAG: 11343 // 11344 // t0: ch = EntryToken 11345 // t2: nxv4i1,ch = CopyFromReg t0, Register:nxv4i1 %0 11346 // t4: i64,ch = CopyFromReg t0, Register:i64 %1 11347 // t5: nxv4i32,nxv4i32,nxv4i32,ch = AArch64ISD::SVE_LD3 t0, t2, t4 11348 // t6: nxv12i32 = concat_vectors t5, t5:1, t5:2 11349 // 11350 // This is called pre-legalization to avoid widening/splitting issues with 11351 // non-power-of-2 tuple types used for LD3, such as nxv12i32. 11352 SDValue AArch64TargetLowering::LowerSVEStructLoad(unsigned Intrinsic, 11353 ArrayRef<SDValue> LoadOps, 11354 EVT VT, SelectionDAG &DAG, 11355 const SDLoc &DL) const { 11356 assert(VT.isScalableVector() && "Can only lower scalable vectors"); 11357 11358 unsigned N, Opcode; 11359 static std::map<unsigned, std::pair<unsigned, unsigned>> IntrinsicMap = { 11360 {Intrinsic::aarch64_sve_ld2, {2, AArch64ISD::SVE_LD2_MERGE_ZERO}}, 11361 {Intrinsic::aarch64_sve_ld3, {3, AArch64ISD::SVE_LD3_MERGE_ZERO}}, 11362 {Intrinsic::aarch64_sve_ld4, {4, AArch64ISD::SVE_LD4_MERGE_ZERO}}}; 11363 11364 std::tie(N, Opcode) = IntrinsicMap[Intrinsic]; 11365 assert(VT.getVectorElementCount().getKnownMinValue() % N == 0 && 11366 "invalid tuple vector type!"); 11367 11368 EVT SplitVT = 11369 EVT::getVectorVT(*DAG.getContext(), VT.getVectorElementType(), 11370 VT.getVectorElementCount().divideCoefficientBy(N)); 11371 assert(isTypeLegal(SplitVT)); 11372 11373 SmallVector<EVT, 5> VTs(N, SplitVT); 11374 VTs.push_back(MVT::Other); // Chain 11375 SDVTList NodeTys = DAG.getVTList(VTs); 11376 11377 SDValue PseudoLoad = DAG.getNode(Opcode, DL, NodeTys, LoadOps); 11378 SmallVector<SDValue, 4> PseudoLoadOps; 11379 for (unsigned I = 0; I < N; ++I) 11380 PseudoLoadOps.push_back(SDValue(PseudoLoad.getNode(), I)); 11381 return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, PseudoLoadOps); 11382 } 11383 11384 EVT AArch64TargetLowering::getOptimalMemOpType( 11385 const MemOp &Op, const AttributeList &FuncAttributes) const { 11386 bool CanImplicitFloat = 11387 !FuncAttributes.hasFnAttribute(Attribute::NoImplicitFloat); 11388 bool CanUseNEON = Subtarget->hasNEON() && CanImplicitFloat; 11389 bool CanUseFP = Subtarget->hasFPARMv8() && CanImplicitFloat; 11390 // Only use AdvSIMD to implement memset of 32-byte and above. It would have 11391 // taken one instruction to materialize the v2i64 zero and one store (with 11392 // restrictive addressing mode). Just do i64 stores. 11393 bool IsSmallMemset = Op.isMemset() && Op.size() < 32; 11394 auto AlignmentIsAcceptable = [&](EVT VT, Align AlignCheck) { 11395 if (Op.isAligned(AlignCheck)) 11396 return true; 11397 bool Fast; 11398 return allowsMisalignedMemoryAccesses(VT, 0, Align(1), 11399 MachineMemOperand::MONone, &Fast) && 11400 Fast; 11401 }; 11402 11403 if (CanUseNEON && Op.isMemset() && !IsSmallMemset && 11404 AlignmentIsAcceptable(MVT::v2i64, Align(16))) 11405 return MVT::v2i64; 11406 if (CanUseFP && !IsSmallMemset && AlignmentIsAcceptable(MVT::f128, Align(16))) 11407 return MVT::f128; 11408 if (Op.size() >= 8 && AlignmentIsAcceptable(MVT::i64, Align(8))) 11409 return MVT::i64; 11410 if (Op.size() >= 4 && AlignmentIsAcceptable(MVT::i32, Align(4))) 11411 return MVT::i32; 11412 return MVT::Other; 11413 } 11414 11415 LLT AArch64TargetLowering::getOptimalMemOpLLT( 11416 const MemOp &Op, const AttributeList &FuncAttributes) const { 11417 bool CanImplicitFloat = 11418 !FuncAttributes.hasFnAttribute(Attribute::NoImplicitFloat); 11419 bool CanUseNEON = Subtarget->hasNEON() && CanImplicitFloat; 11420 bool CanUseFP = Subtarget->hasFPARMv8() && CanImplicitFloat; 11421 // Only use AdvSIMD to implement memset of 32-byte and above. It would have 11422 // taken one instruction to materialize the v2i64 zero and one store (with 11423 // restrictive addressing mode). Just do i64 stores. 11424 bool IsSmallMemset = Op.isMemset() && Op.size() < 32; 11425 auto AlignmentIsAcceptable = [&](EVT VT, Align AlignCheck) { 11426 if (Op.isAligned(AlignCheck)) 11427 return true; 11428 bool Fast; 11429 return allowsMisalignedMemoryAccesses(VT, 0, Align(1), 11430 MachineMemOperand::MONone, &Fast) && 11431 Fast; 11432 }; 11433 11434 if (CanUseNEON && Op.isMemset() && !IsSmallMemset && 11435 AlignmentIsAcceptable(MVT::v2i64, Align(16))) 11436 return LLT::vector(2, 64); 11437 if (CanUseFP && !IsSmallMemset && AlignmentIsAcceptable(MVT::f128, Align(16))) 11438 return LLT::scalar(128); 11439 if (Op.size() >= 8 && AlignmentIsAcceptable(MVT::i64, Align(8))) 11440 return LLT::scalar(64); 11441 if (Op.size() >= 4 && AlignmentIsAcceptable(MVT::i32, Align(4))) 11442 return LLT::scalar(32); 11443 return LLT(); 11444 } 11445 11446 // 12-bit optionally shifted immediates are legal for adds. 11447 bool AArch64TargetLowering::isLegalAddImmediate(int64_t Immed) const { 11448 if (Immed == std::numeric_limits<int64_t>::min()) { 11449 LLVM_DEBUG(dbgs() << "Illegal add imm " << Immed 11450 << ": avoid UB for INT64_MIN\n"); 11451 return false; 11452 } 11453 // Same encoding for add/sub, just flip the sign. 11454 Immed = std::abs(Immed); 11455 bool IsLegal = ((Immed >> 12) == 0 || 11456 ((Immed & 0xfff) == 0 && Immed >> 24 == 0)); 11457 LLVM_DEBUG(dbgs() << "Is " << Immed 11458 << " legal add imm: " << (IsLegal ? "yes" : "no") << "\n"); 11459 return IsLegal; 11460 } 11461 11462 // Integer comparisons are implemented with ADDS/SUBS, so the range of valid 11463 // immediates is the same as for an add or a sub. 11464 bool AArch64TargetLowering::isLegalICmpImmediate(int64_t Immed) const { 11465 return isLegalAddImmediate(Immed); 11466 } 11467 11468 /// isLegalAddressingMode - Return true if the addressing mode represented 11469 /// by AM is legal for this target, for a load/store of the specified type. 11470 bool AArch64TargetLowering::isLegalAddressingMode(const DataLayout &DL, 11471 const AddrMode &AM, Type *Ty, 11472 unsigned AS, Instruction *I) const { 11473 // AArch64 has five basic addressing modes: 11474 // reg 11475 // reg + 9-bit signed offset 11476 // reg + SIZE_IN_BYTES * 12-bit unsigned offset 11477 // reg1 + reg2 11478 // reg + SIZE_IN_BYTES * reg 11479 11480 // No global is ever allowed as a base. 11481 if (AM.BaseGV) 11482 return false; 11483 11484 // No reg+reg+imm addressing. 11485 if (AM.HasBaseReg && AM.BaseOffs && AM.Scale) 11486 return false; 11487 11488 // FIXME: Update this method to support scalable addressing modes. 11489 if (isa<ScalableVectorType>(Ty)) 11490 return AM.HasBaseReg && !AM.BaseOffs && !AM.Scale; 11491 11492 // check reg + imm case: 11493 // i.e., reg + 0, reg + imm9, reg + SIZE_IN_BYTES * uimm12 11494 uint64_t NumBytes = 0; 11495 if (Ty->isSized()) { 11496 uint64_t NumBits = DL.getTypeSizeInBits(Ty); 11497 NumBytes = NumBits / 8; 11498 if (!isPowerOf2_64(NumBits)) 11499 NumBytes = 0; 11500 } 11501 11502 if (!AM.Scale) { 11503 int64_t Offset = AM.BaseOffs; 11504 11505 // 9-bit signed offset 11506 if (isInt<9>(Offset)) 11507 return true; 11508 11509 // 12-bit unsigned offset 11510 unsigned shift = Log2_64(NumBytes); 11511 if (NumBytes && Offset > 0 && (Offset / NumBytes) <= (1LL << 12) - 1 && 11512 // Must be a multiple of NumBytes (NumBytes is a power of 2) 11513 (Offset >> shift) << shift == Offset) 11514 return true; 11515 return false; 11516 } 11517 11518 // Check reg1 + SIZE_IN_BYTES * reg2 and reg1 + reg2 11519 11520 return AM.Scale == 1 || (AM.Scale > 0 && (uint64_t)AM.Scale == NumBytes); 11521 } 11522 11523 bool AArch64TargetLowering::shouldConsiderGEPOffsetSplit() const { 11524 // Consider splitting large offset of struct or array. 11525 return true; 11526 } 11527 11528 int AArch64TargetLowering::getScalingFactorCost(const DataLayout &DL, 11529 const AddrMode &AM, Type *Ty, 11530 unsigned AS) const { 11531 // Scaling factors are not free at all. 11532 // Operands | Rt Latency 11533 // ------------------------------------------- 11534 // Rt, [Xn, Xm] | 4 11535 // ------------------------------------------- 11536 // Rt, [Xn, Xm, lsl #imm] | Rn: 4 Rm: 5 11537 // Rt, [Xn, Wm, <extend> #imm] | 11538 if (isLegalAddressingMode(DL, AM, Ty, AS)) 11539 // Scale represents reg2 * scale, thus account for 1 if 11540 // it is not equal to 0 or 1. 11541 return AM.Scale != 0 && AM.Scale != 1; 11542 return -1; 11543 } 11544 11545 bool AArch64TargetLowering::isFMAFasterThanFMulAndFAdd( 11546 const MachineFunction &MF, EVT VT) const { 11547 VT = VT.getScalarType(); 11548 11549 if (!VT.isSimple()) 11550 return false; 11551 11552 switch (VT.getSimpleVT().SimpleTy) { 11553 case MVT::f32: 11554 case MVT::f64: 11555 return true; 11556 default: 11557 break; 11558 } 11559 11560 return false; 11561 } 11562 11563 bool AArch64TargetLowering::isFMAFasterThanFMulAndFAdd(const Function &F, 11564 Type *Ty) const { 11565 switch (Ty->getScalarType()->getTypeID()) { 11566 case Type::FloatTyID: 11567 case Type::DoubleTyID: 11568 return true; 11569 default: 11570 return false; 11571 } 11572 } 11573 11574 const MCPhysReg * 11575 AArch64TargetLowering::getScratchRegisters(CallingConv::ID) const { 11576 // LR is a callee-save register, but we must treat it as clobbered by any call 11577 // site. Hence we include LR in the scratch registers, which are in turn added 11578 // as implicit-defs for stackmaps and patchpoints. 11579 static const MCPhysReg ScratchRegs[] = { 11580 AArch64::X16, AArch64::X17, AArch64::LR, 0 11581 }; 11582 return ScratchRegs; 11583 } 11584 11585 bool 11586 AArch64TargetLowering::isDesirableToCommuteWithShift(const SDNode *N, 11587 CombineLevel Level) const { 11588 N = N->getOperand(0).getNode(); 11589 EVT VT = N->getValueType(0); 11590 // If N is unsigned bit extraction: ((x >> C) & mask), then do not combine 11591 // it with shift to let it be lowered to UBFX. 11592 if (N->getOpcode() == ISD::AND && (VT == MVT::i32 || VT == MVT::i64) && 11593 isa<ConstantSDNode>(N->getOperand(1))) { 11594 uint64_t TruncMask = N->getConstantOperandVal(1); 11595 if (isMask_64(TruncMask) && 11596 N->getOperand(0).getOpcode() == ISD::SRL && 11597 isa<ConstantSDNode>(N->getOperand(0)->getOperand(1))) 11598 return false; 11599 } 11600 return true; 11601 } 11602 11603 bool AArch64TargetLowering::shouldConvertConstantLoadToIntImm(const APInt &Imm, 11604 Type *Ty) const { 11605 assert(Ty->isIntegerTy()); 11606 11607 unsigned BitSize = Ty->getPrimitiveSizeInBits(); 11608 if (BitSize == 0) 11609 return false; 11610 11611 int64_t Val = Imm.getSExtValue(); 11612 if (Val == 0 || AArch64_AM::isLogicalImmediate(Val, BitSize)) 11613 return true; 11614 11615 if ((int64_t)Val < 0) 11616 Val = ~Val; 11617 if (BitSize == 32) 11618 Val &= (1LL << 32) - 1; 11619 11620 unsigned LZ = countLeadingZeros((uint64_t)Val); 11621 unsigned Shift = (63 - LZ) / 16; 11622 // MOVZ is free so return true for one or fewer MOVK. 11623 return Shift < 3; 11624 } 11625 11626 bool AArch64TargetLowering::isExtractSubvectorCheap(EVT ResVT, EVT SrcVT, 11627 unsigned Index) const { 11628 if (!isOperationLegalOrCustom(ISD::EXTRACT_SUBVECTOR, ResVT)) 11629 return false; 11630 11631 return (Index == 0 || Index == ResVT.getVectorNumElements()); 11632 } 11633 11634 /// Turn vector tests of the signbit in the form of: 11635 /// xor (sra X, elt_size(X)-1), -1 11636 /// into: 11637 /// cmge X, X, #0 11638 static SDValue foldVectorXorShiftIntoCmp(SDNode *N, SelectionDAG &DAG, 11639 const AArch64Subtarget *Subtarget) { 11640 EVT VT = N->getValueType(0); 11641 if (!Subtarget->hasNEON() || !VT.isVector()) 11642 return SDValue(); 11643 11644 // There must be a shift right algebraic before the xor, and the xor must be a 11645 // 'not' operation. 11646 SDValue Shift = N->getOperand(0); 11647 SDValue Ones = N->getOperand(1); 11648 if (Shift.getOpcode() != AArch64ISD::VASHR || !Shift.hasOneUse() || 11649 !ISD::isBuildVectorAllOnes(Ones.getNode())) 11650 return SDValue(); 11651 11652 // The shift should be smearing the sign bit across each vector element. 11653 auto *ShiftAmt = dyn_cast<ConstantSDNode>(Shift.getOperand(1)); 11654 EVT ShiftEltTy = Shift.getValueType().getVectorElementType(); 11655 if (!ShiftAmt || ShiftAmt->getZExtValue() != ShiftEltTy.getSizeInBits() - 1) 11656 return SDValue(); 11657 11658 return DAG.getNode(AArch64ISD::CMGEz, SDLoc(N), VT, Shift.getOperand(0)); 11659 } 11660 11661 // VECREDUCE_ADD( EXTEND(v16i8_type) ) to 11662 // VECREDUCE_ADD( DOTv16i8(v16i8_type) ) 11663 static SDValue performVecReduceAddCombine(SDNode *N, SelectionDAG &DAG, 11664 const AArch64Subtarget *ST) { 11665 SDValue Op0 = N->getOperand(0); 11666 if (!ST->hasDotProd() || N->getValueType(0) != MVT::i32) 11667 return SDValue(); 11668 11669 if (Op0.getValueType().getVectorElementType() != MVT::i32) 11670 return SDValue(); 11671 11672 unsigned ExtOpcode = Op0.getOpcode(); 11673 if (ExtOpcode != ISD::ZERO_EXTEND && ExtOpcode != ISD::SIGN_EXTEND) 11674 return SDValue(); 11675 11676 EVT Op0VT = Op0.getOperand(0).getValueType(); 11677 if (Op0VT != MVT::v16i8) 11678 return SDValue(); 11679 11680 SDLoc DL(Op0); 11681 SDValue Ones = DAG.getConstant(1, DL, Op0VT); 11682 SDValue Zeros = DAG.getConstant(0, DL, MVT::v4i32); 11683 auto DotIntrisic = (ExtOpcode == ISD::ZERO_EXTEND) 11684 ? Intrinsic::aarch64_neon_udot 11685 : Intrinsic::aarch64_neon_sdot; 11686 SDValue Dot = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, Zeros.getValueType(), 11687 DAG.getConstant(DotIntrisic, DL, MVT::i32), Zeros, 11688 Ones, Op0.getOperand(0)); 11689 return DAG.getNode(ISD::VECREDUCE_ADD, DL, N->getValueType(0), Dot); 11690 } 11691 11692 // Given a ABS node, detect the following pattern: 11693 // (ABS (SUB (EXTEND a), (EXTEND b))). 11694 // Generates UABD/SABD instruction. 11695 static SDValue performABSCombine(SDNode *N, SelectionDAG &DAG, 11696 TargetLowering::DAGCombinerInfo &DCI, 11697 const AArch64Subtarget *Subtarget) { 11698 SDValue AbsOp1 = N->getOperand(0); 11699 SDValue Op0, Op1; 11700 11701 if (AbsOp1.getOpcode() != ISD::SUB) 11702 return SDValue(); 11703 11704 Op0 = AbsOp1.getOperand(0); 11705 Op1 = AbsOp1.getOperand(1); 11706 11707 unsigned Opc0 = Op0.getOpcode(); 11708 // Check if the operands of the sub are (zero|sign)-extended. 11709 if (Opc0 != Op1.getOpcode() || 11710 (Opc0 != ISD::ZERO_EXTEND && Opc0 != ISD::SIGN_EXTEND)) 11711 return SDValue(); 11712 11713 EVT VectorT1 = Op0.getOperand(0).getValueType(); 11714 EVT VectorT2 = Op1.getOperand(0).getValueType(); 11715 // Check if vectors are of same type and valid size. 11716 uint64_t Size = VectorT1.getFixedSizeInBits(); 11717 if (VectorT1 != VectorT2 || (Size != 64 && Size != 128)) 11718 return SDValue(); 11719 11720 // Check if vector element types are valid. 11721 EVT VT1 = VectorT1.getVectorElementType(); 11722 if (VT1 != MVT::i8 && VT1 != MVT::i16 && VT1 != MVT::i32) 11723 return SDValue(); 11724 11725 Op0 = Op0.getOperand(0); 11726 Op1 = Op1.getOperand(0); 11727 unsigned ABDOpcode = 11728 (Opc0 == ISD::SIGN_EXTEND) ? AArch64ISD::SABD : AArch64ISD::UABD; 11729 SDValue ABD = 11730 DAG.getNode(ABDOpcode, SDLoc(N), Op0->getValueType(0), Op0, Op1); 11731 return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), N->getValueType(0), ABD); 11732 } 11733 11734 static SDValue performXorCombine(SDNode *N, SelectionDAG &DAG, 11735 TargetLowering::DAGCombinerInfo &DCI, 11736 const AArch64Subtarget *Subtarget) { 11737 if (DCI.isBeforeLegalizeOps()) 11738 return SDValue(); 11739 11740 return foldVectorXorShiftIntoCmp(N, DAG, Subtarget); 11741 } 11742 11743 SDValue 11744 AArch64TargetLowering::BuildSDIVPow2(SDNode *N, const APInt &Divisor, 11745 SelectionDAG &DAG, 11746 SmallVectorImpl<SDNode *> &Created) const { 11747 AttributeList Attr = DAG.getMachineFunction().getFunction().getAttributes(); 11748 if (isIntDivCheap(N->getValueType(0), Attr)) 11749 return SDValue(N,0); // Lower SDIV as SDIV 11750 11751 // fold (sdiv X, pow2) 11752 EVT VT = N->getValueType(0); 11753 if ((VT != MVT::i32 && VT != MVT::i64) || 11754 !(Divisor.isPowerOf2() || (-Divisor).isPowerOf2())) 11755 return SDValue(); 11756 11757 SDLoc DL(N); 11758 SDValue N0 = N->getOperand(0); 11759 unsigned Lg2 = Divisor.countTrailingZeros(); 11760 SDValue Zero = DAG.getConstant(0, DL, VT); 11761 SDValue Pow2MinusOne = DAG.getConstant((1ULL << Lg2) - 1, DL, VT); 11762 11763 // Add (N0 < 0) ? Pow2 - 1 : 0; 11764 SDValue CCVal; 11765 SDValue Cmp = getAArch64Cmp(N0, Zero, ISD::SETLT, CCVal, DAG, DL); 11766 SDValue Add = DAG.getNode(ISD::ADD, DL, VT, N0, Pow2MinusOne); 11767 SDValue CSel = DAG.getNode(AArch64ISD::CSEL, DL, VT, Add, N0, CCVal, Cmp); 11768 11769 Created.push_back(Cmp.getNode()); 11770 Created.push_back(Add.getNode()); 11771 Created.push_back(CSel.getNode()); 11772 11773 // Divide by pow2. 11774 SDValue SRA = 11775 DAG.getNode(ISD::SRA, DL, VT, CSel, DAG.getConstant(Lg2, DL, MVT::i64)); 11776 11777 // If we're dividing by a positive value, we're done. Otherwise, we must 11778 // negate the result. 11779 if (Divisor.isNonNegative()) 11780 return SRA; 11781 11782 Created.push_back(SRA.getNode()); 11783 return DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, VT), SRA); 11784 } 11785 11786 static bool IsSVECntIntrinsic(SDValue S) { 11787 switch(getIntrinsicID(S.getNode())) { 11788 default: 11789 break; 11790 case Intrinsic::aarch64_sve_cntb: 11791 case Intrinsic::aarch64_sve_cnth: 11792 case Intrinsic::aarch64_sve_cntw: 11793 case Intrinsic::aarch64_sve_cntd: 11794 return true; 11795 } 11796 return false; 11797 } 11798 11799 /// Calculates what the pre-extend type is, based on the extension 11800 /// operation node provided by \p Extend. 11801 /// 11802 /// In the case that \p Extend is a SIGN_EXTEND or a ZERO_EXTEND, the 11803 /// pre-extend type is pulled directly from the operand, while other extend 11804 /// operations need a bit more inspection to get this information. 11805 /// 11806 /// \param Extend The SDNode from the DAG that represents the extend operation 11807 /// \param DAG The SelectionDAG hosting the \p Extend node 11808 /// 11809 /// \returns The type representing the \p Extend source type, or \p MVT::Other 11810 /// if no valid type can be determined 11811 static EVT calculatePreExtendType(SDValue Extend, SelectionDAG &DAG) { 11812 switch (Extend.getOpcode()) { 11813 case ISD::SIGN_EXTEND: 11814 case ISD::ZERO_EXTEND: 11815 return Extend.getOperand(0).getValueType(); 11816 case ISD::AssertSext: 11817 case ISD::AssertZext: 11818 case ISD::SIGN_EXTEND_INREG: { 11819 VTSDNode *TypeNode = dyn_cast<VTSDNode>(Extend.getOperand(1)); 11820 if (!TypeNode) 11821 return MVT::Other; 11822 return TypeNode->getVT(); 11823 } 11824 case ISD::AND: { 11825 ConstantSDNode *Constant = 11826 dyn_cast<ConstantSDNode>(Extend.getOperand(1).getNode()); 11827 if (!Constant) 11828 return MVT::Other; 11829 11830 uint32_t Mask = Constant->getZExtValue(); 11831 11832 if (Mask == UCHAR_MAX) 11833 return MVT::i8; 11834 else if (Mask == USHRT_MAX) 11835 return MVT::i16; 11836 else if (Mask == UINT_MAX) 11837 return MVT::i32; 11838 11839 return MVT::Other; 11840 } 11841 default: 11842 return MVT::Other; 11843 } 11844 11845 llvm_unreachable("Code path unhandled in calculatePreExtendType!"); 11846 } 11847 11848 /// Combines a dup(sext/zext) node pattern into sext/zext(dup) 11849 /// making use of the vector SExt/ZExt rather than the scalar SExt/ZExt 11850 static SDValue performCommonVectorExtendCombine(SDValue VectorShuffle, 11851 SelectionDAG &DAG) { 11852 11853 ShuffleVectorSDNode *ShuffleNode = 11854 dyn_cast<ShuffleVectorSDNode>(VectorShuffle.getNode()); 11855 if (!ShuffleNode) 11856 return SDValue(); 11857 11858 // Ensuring the mask is zero before continuing 11859 if (!ShuffleNode->isSplat() || ShuffleNode->getSplatIndex() != 0) 11860 return SDValue(); 11861 11862 SDValue InsertVectorElt = VectorShuffle.getOperand(0); 11863 11864 if (InsertVectorElt.getOpcode() != ISD::INSERT_VECTOR_ELT) 11865 return SDValue(); 11866 11867 SDValue InsertLane = InsertVectorElt.getOperand(2); 11868 ConstantSDNode *Constant = dyn_cast<ConstantSDNode>(InsertLane.getNode()); 11869 // Ensures the insert is inserting into lane 0 11870 if (!Constant || Constant->getZExtValue() != 0) 11871 return SDValue(); 11872 11873 SDValue Extend = InsertVectorElt.getOperand(1); 11874 unsigned ExtendOpcode = Extend.getOpcode(); 11875 11876 bool IsSExt = ExtendOpcode == ISD::SIGN_EXTEND || 11877 ExtendOpcode == ISD::SIGN_EXTEND_INREG || 11878 ExtendOpcode == ISD::AssertSext; 11879 if (!IsSExt && ExtendOpcode != ISD::ZERO_EXTEND && 11880 ExtendOpcode != ISD::AssertZext && ExtendOpcode != ISD::AND) 11881 return SDValue(); 11882 11883 EVT TargetType = VectorShuffle.getValueType(); 11884 EVT PreExtendType = calculatePreExtendType(Extend, DAG); 11885 11886 if ((TargetType != MVT::v8i16 && TargetType != MVT::v4i32 && 11887 TargetType != MVT::v2i64) || 11888 (PreExtendType == MVT::Other)) 11889 return SDValue(); 11890 11891 // Restrict valid pre-extend data type 11892 if (PreExtendType != MVT::i8 && PreExtendType != MVT::i16 && 11893 PreExtendType != MVT::i32) 11894 return SDValue(); 11895 11896 EVT PreExtendVT = TargetType.changeVectorElementType(PreExtendType); 11897 11898 if (PreExtendVT.getVectorElementCount() != TargetType.getVectorElementCount()) 11899 return SDValue(); 11900 11901 if (TargetType.getScalarSizeInBits() != PreExtendVT.getScalarSizeInBits() * 2) 11902 return SDValue(); 11903 11904 SDLoc DL(VectorShuffle); 11905 11906 SDValue InsertVectorNode = DAG.getNode( 11907 InsertVectorElt.getOpcode(), DL, PreExtendVT, DAG.getUNDEF(PreExtendVT), 11908 DAG.getAnyExtOrTrunc(Extend.getOperand(0), DL, PreExtendType), 11909 DAG.getConstant(0, DL, MVT::i64)); 11910 11911 std::vector<int> ShuffleMask(TargetType.getVectorElementCount().getValue()); 11912 11913 SDValue VectorShuffleNode = 11914 DAG.getVectorShuffle(PreExtendVT, DL, InsertVectorNode, 11915 DAG.getUNDEF(PreExtendVT), ShuffleMask); 11916 11917 SDValue ExtendNode = DAG.getNode(IsSExt ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND, 11918 DL, TargetType, VectorShuffleNode); 11919 11920 return ExtendNode; 11921 } 11922 11923 /// Combines a mul(dup(sext/zext)) node pattern into mul(sext/zext(dup)) 11924 /// making use of the vector SExt/ZExt rather than the scalar SExt/ZExt 11925 static SDValue performMulVectorExtendCombine(SDNode *Mul, SelectionDAG &DAG) { 11926 // If the value type isn't a vector, none of the operands are going to be dups 11927 if (!Mul->getValueType(0).isVector()) 11928 return SDValue(); 11929 11930 SDValue Op0 = performCommonVectorExtendCombine(Mul->getOperand(0), DAG); 11931 SDValue Op1 = performCommonVectorExtendCombine(Mul->getOperand(1), DAG); 11932 11933 // Neither operands have been changed, don't make any further changes 11934 if (!Op0 && !Op1) 11935 return SDValue(); 11936 11937 SDLoc DL(Mul); 11938 return DAG.getNode(Mul->getOpcode(), DL, Mul->getValueType(0), 11939 Op0 ? Op0 : Mul->getOperand(0), 11940 Op1 ? Op1 : Mul->getOperand(1)); 11941 } 11942 11943 static SDValue performMulCombine(SDNode *N, SelectionDAG &DAG, 11944 TargetLowering::DAGCombinerInfo &DCI, 11945 const AArch64Subtarget *Subtarget) { 11946 11947 if (SDValue Ext = performMulVectorExtendCombine(N, DAG)) 11948 return Ext; 11949 11950 if (DCI.isBeforeLegalizeOps()) 11951 return SDValue(); 11952 11953 // The below optimizations require a constant RHS. 11954 if (!isa<ConstantSDNode>(N->getOperand(1))) 11955 return SDValue(); 11956 11957 SDValue N0 = N->getOperand(0); 11958 ConstantSDNode *C = cast<ConstantSDNode>(N->getOperand(1)); 11959 const APInt &ConstValue = C->getAPIntValue(); 11960 11961 // Allow the scaling to be folded into the `cnt` instruction by preventing 11962 // the scaling to be obscured here. This makes it easier to pattern match. 11963 if (IsSVECntIntrinsic(N0) || 11964 (N0->getOpcode() == ISD::TRUNCATE && 11965 (IsSVECntIntrinsic(N0->getOperand(0))))) 11966 if (ConstValue.sge(1) && ConstValue.sle(16)) 11967 return SDValue(); 11968 11969 // Multiplication of a power of two plus/minus one can be done more 11970 // cheaply as as shift+add/sub. For now, this is true unilaterally. If 11971 // future CPUs have a cheaper MADD instruction, this may need to be 11972 // gated on a subtarget feature. For Cyclone, 32-bit MADD is 4 cycles and 11973 // 64-bit is 5 cycles, so this is always a win. 11974 // More aggressively, some multiplications N0 * C can be lowered to 11975 // shift+add+shift if the constant C = A * B where A = 2^N + 1 and B = 2^M, 11976 // e.g. 6=3*2=(2+1)*2. 11977 // TODO: consider lowering more cases, e.g. C = 14, -6, -14 or even 45 11978 // which equals to (1+2)*16-(1+2). 11979 // TrailingZeroes is used to test if the mul can be lowered to 11980 // shift+add+shift. 11981 unsigned TrailingZeroes = ConstValue.countTrailingZeros(); 11982 if (TrailingZeroes) { 11983 // Conservatively do not lower to shift+add+shift if the mul might be 11984 // folded into smul or umul. 11985 if (N0->hasOneUse() && (isSignExtended(N0.getNode(), DAG) || 11986 isZeroExtended(N0.getNode(), DAG))) 11987 return SDValue(); 11988 // Conservatively do not lower to shift+add+shift if the mul might be 11989 // folded into madd or msub. 11990 if (N->hasOneUse() && (N->use_begin()->getOpcode() == ISD::ADD || 11991 N->use_begin()->getOpcode() == ISD::SUB)) 11992 return SDValue(); 11993 } 11994 // Use ShiftedConstValue instead of ConstValue to support both shift+add/sub 11995 // and shift+add+shift. 11996 APInt ShiftedConstValue = ConstValue.ashr(TrailingZeroes); 11997 11998 unsigned ShiftAmt, AddSubOpc; 11999 // Is the shifted value the LHS operand of the add/sub? 12000 bool ShiftValUseIsN0 = true; 12001 // Do we need to negate the result? 12002 bool NegateResult = false; 12003 12004 if (ConstValue.isNonNegative()) { 12005 // (mul x, 2^N + 1) => (add (shl x, N), x) 12006 // (mul x, 2^N - 1) => (sub (shl x, N), x) 12007 // (mul x, (2^N + 1) * 2^M) => (shl (add (shl x, N), x), M) 12008 APInt SCVMinus1 = ShiftedConstValue - 1; 12009 APInt CVPlus1 = ConstValue + 1; 12010 if (SCVMinus1.isPowerOf2()) { 12011 ShiftAmt = SCVMinus1.logBase2(); 12012 AddSubOpc = ISD::ADD; 12013 } else if (CVPlus1.isPowerOf2()) { 12014 ShiftAmt = CVPlus1.logBase2(); 12015 AddSubOpc = ISD::SUB; 12016 } else 12017 return SDValue(); 12018 } else { 12019 // (mul x, -(2^N - 1)) => (sub x, (shl x, N)) 12020 // (mul x, -(2^N + 1)) => - (add (shl x, N), x) 12021 APInt CVNegPlus1 = -ConstValue + 1; 12022 APInt CVNegMinus1 = -ConstValue - 1; 12023 if (CVNegPlus1.isPowerOf2()) { 12024 ShiftAmt = CVNegPlus1.logBase2(); 12025 AddSubOpc = ISD::SUB; 12026 ShiftValUseIsN0 = false; 12027 } else if (CVNegMinus1.isPowerOf2()) { 12028 ShiftAmt = CVNegMinus1.logBase2(); 12029 AddSubOpc = ISD::ADD; 12030 NegateResult = true; 12031 } else 12032 return SDValue(); 12033 } 12034 12035 SDLoc DL(N); 12036 EVT VT = N->getValueType(0); 12037 SDValue ShiftedVal = DAG.getNode(ISD::SHL, DL, VT, N0, 12038 DAG.getConstant(ShiftAmt, DL, MVT::i64)); 12039 12040 SDValue AddSubN0 = ShiftValUseIsN0 ? ShiftedVal : N0; 12041 SDValue AddSubN1 = ShiftValUseIsN0 ? N0 : ShiftedVal; 12042 SDValue Res = DAG.getNode(AddSubOpc, DL, VT, AddSubN0, AddSubN1); 12043 assert(!(NegateResult && TrailingZeroes) && 12044 "NegateResult and TrailingZeroes cannot both be true for now."); 12045 // Negate the result. 12046 if (NegateResult) 12047 return DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, VT), Res); 12048 // Shift the result. 12049 if (TrailingZeroes) 12050 return DAG.getNode(ISD::SHL, DL, VT, Res, 12051 DAG.getConstant(TrailingZeroes, DL, MVT::i64)); 12052 return Res; 12053 } 12054 12055 static SDValue performVectorCompareAndMaskUnaryOpCombine(SDNode *N, 12056 SelectionDAG &DAG) { 12057 // Take advantage of vector comparisons producing 0 or -1 in each lane to 12058 // optimize away operation when it's from a constant. 12059 // 12060 // The general transformation is: 12061 // UNARYOP(AND(VECTOR_CMP(x,y), constant)) --> 12062 // AND(VECTOR_CMP(x,y), constant2) 12063 // constant2 = UNARYOP(constant) 12064 12065 // Early exit if this isn't a vector operation, the operand of the 12066 // unary operation isn't a bitwise AND, or if the sizes of the operations 12067 // aren't the same. 12068 EVT VT = N->getValueType(0); 12069 if (!VT.isVector() || N->getOperand(0)->getOpcode() != ISD::AND || 12070 N->getOperand(0)->getOperand(0)->getOpcode() != ISD::SETCC || 12071 VT.getSizeInBits() != N->getOperand(0)->getValueType(0).getSizeInBits()) 12072 return SDValue(); 12073 12074 // Now check that the other operand of the AND is a constant. We could 12075 // make the transformation for non-constant splats as well, but it's unclear 12076 // that would be a benefit as it would not eliminate any operations, just 12077 // perform one more step in scalar code before moving to the vector unit. 12078 if (BuildVectorSDNode *BV = 12079 dyn_cast<BuildVectorSDNode>(N->getOperand(0)->getOperand(1))) { 12080 // Bail out if the vector isn't a constant. 12081 if (!BV->isConstant()) 12082 return SDValue(); 12083 12084 // Everything checks out. Build up the new and improved node. 12085 SDLoc DL(N); 12086 EVT IntVT = BV->getValueType(0); 12087 // Create a new constant of the appropriate type for the transformed 12088 // DAG. 12089 SDValue SourceConst = DAG.getNode(N->getOpcode(), DL, VT, SDValue(BV, 0)); 12090 // The AND node needs bitcasts to/from an integer vector type around it. 12091 SDValue MaskConst = DAG.getNode(ISD::BITCAST, DL, IntVT, SourceConst); 12092 SDValue NewAnd = DAG.getNode(ISD::AND, DL, IntVT, 12093 N->getOperand(0)->getOperand(0), MaskConst); 12094 SDValue Res = DAG.getNode(ISD::BITCAST, DL, VT, NewAnd); 12095 return Res; 12096 } 12097 12098 return SDValue(); 12099 } 12100 12101 static SDValue performIntToFpCombine(SDNode *N, SelectionDAG &DAG, 12102 const AArch64Subtarget *Subtarget) { 12103 // First try to optimize away the conversion when it's conditionally from 12104 // a constant. Vectors only. 12105 if (SDValue Res = performVectorCompareAndMaskUnaryOpCombine(N, DAG)) 12106 return Res; 12107 12108 EVT VT = N->getValueType(0); 12109 if (VT != MVT::f32 && VT != MVT::f64) 12110 return SDValue(); 12111 12112 // Only optimize when the source and destination types have the same width. 12113 if (VT.getSizeInBits() != N->getOperand(0).getValueSizeInBits()) 12114 return SDValue(); 12115 12116 // If the result of an integer load is only used by an integer-to-float 12117 // conversion, use a fp load instead and a AdvSIMD scalar {S|U}CVTF instead. 12118 // This eliminates an "integer-to-vector-move" UOP and improves throughput. 12119 SDValue N0 = N->getOperand(0); 12120 if (Subtarget->hasNEON() && ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() && 12121 // Do not change the width of a volatile load. 12122 !cast<LoadSDNode>(N0)->isVolatile()) { 12123 LoadSDNode *LN0 = cast<LoadSDNode>(N0); 12124 SDValue Load = DAG.getLoad(VT, SDLoc(N), LN0->getChain(), LN0->getBasePtr(), 12125 LN0->getPointerInfo(), LN0->getAlignment(), 12126 LN0->getMemOperand()->getFlags()); 12127 12128 // Make sure successors of the original load stay after it by updating them 12129 // to use the new Chain. 12130 DAG.ReplaceAllUsesOfValueWith(SDValue(LN0, 1), Load.getValue(1)); 12131 12132 unsigned Opcode = 12133 (N->getOpcode() == ISD::SINT_TO_FP) ? AArch64ISD::SITOF : AArch64ISD::UITOF; 12134 return DAG.getNode(Opcode, SDLoc(N), VT, Load); 12135 } 12136 12137 return SDValue(); 12138 } 12139 12140 /// Fold a floating-point multiply by power of two into floating-point to 12141 /// fixed-point conversion. 12142 static SDValue performFpToIntCombine(SDNode *N, SelectionDAG &DAG, 12143 TargetLowering::DAGCombinerInfo &DCI, 12144 const AArch64Subtarget *Subtarget) { 12145 if (!Subtarget->hasNEON()) 12146 return SDValue(); 12147 12148 if (!N->getValueType(0).isSimple()) 12149 return SDValue(); 12150 12151 SDValue Op = N->getOperand(0); 12152 if (!Op.getValueType().isVector() || !Op.getValueType().isSimple() || 12153 Op.getOpcode() != ISD::FMUL) 12154 return SDValue(); 12155 12156 SDValue ConstVec = Op->getOperand(1); 12157 if (!isa<BuildVectorSDNode>(ConstVec)) 12158 return SDValue(); 12159 12160 MVT FloatTy = Op.getSimpleValueType().getVectorElementType(); 12161 uint32_t FloatBits = FloatTy.getSizeInBits(); 12162 if (FloatBits != 32 && FloatBits != 64) 12163 return SDValue(); 12164 12165 MVT IntTy = N->getSimpleValueType(0).getVectorElementType(); 12166 uint32_t IntBits = IntTy.getSizeInBits(); 12167 if (IntBits != 16 && IntBits != 32 && IntBits != 64) 12168 return SDValue(); 12169 12170 // Avoid conversions where iN is larger than the float (e.g., float -> i64). 12171 if (IntBits > FloatBits) 12172 return SDValue(); 12173 12174 BitVector UndefElements; 12175 BuildVectorSDNode *BV = cast<BuildVectorSDNode>(ConstVec); 12176 int32_t Bits = IntBits == 64 ? 64 : 32; 12177 int32_t C = BV->getConstantFPSplatPow2ToLog2Int(&UndefElements, Bits + 1); 12178 if (C == -1 || C == 0 || C > Bits) 12179 return SDValue(); 12180 12181 MVT ResTy; 12182 unsigned NumLanes = Op.getValueType().getVectorNumElements(); 12183 switch (NumLanes) { 12184 default: 12185 return SDValue(); 12186 case 2: 12187 ResTy = FloatBits == 32 ? MVT::v2i32 : MVT::v2i64; 12188 break; 12189 case 4: 12190 ResTy = FloatBits == 32 ? MVT::v4i32 : MVT::v4i64; 12191 break; 12192 } 12193 12194 if (ResTy == MVT::v4i64 && DCI.isBeforeLegalizeOps()) 12195 return SDValue(); 12196 12197 assert((ResTy != MVT::v4i64 || DCI.isBeforeLegalizeOps()) && 12198 "Illegal vector type after legalization"); 12199 12200 SDLoc DL(N); 12201 bool IsSigned = N->getOpcode() == ISD::FP_TO_SINT; 12202 unsigned IntrinsicOpcode = IsSigned ? Intrinsic::aarch64_neon_vcvtfp2fxs 12203 : Intrinsic::aarch64_neon_vcvtfp2fxu; 12204 SDValue FixConv = 12205 DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, ResTy, 12206 DAG.getConstant(IntrinsicOpcode, DL, MVT::i32), 12207 Op->getOperand(0), DAG.getConstant(C, DL, MVT::i32)); 12208 // We can handle smaller integers by generating an extra trunc. 12209 if (IntBits < FloatBits) 12210 FixConv = DAG.getNode(ISD::TRUNCATE, DL, N->getValueType(0), FixConv); 12211 12212 return FixConv; 12213 } 12214 12215 /// Fold a floating-point divide by power of two into fixed-point to 12216 /// floating-point conversion. 12217 static SDValue performFDivCombine(SDNode *N, SelectionDAG &DAG, 12218 TargetLowering::DAGCombinerInfo &DCI, 12219 const AArch64Subtarget *Subtarget) { 12220 if (!Subtarget->hasNEON()) 12221 return SDValue(); 12222 12223 SDValue Op = N->getOperand(0); 12224 unsigned Opc = Op->getOpcode(); 12225 if (!Op.getValueType().isVector() || !Op.getValueType().isSimple() || 12226 !Op.getOperand(0).getValueType().isSimple() || 12227 (Opc != ISD::SINT_TO_FP && Opc != ISD::UINT_TO_FP)) 12228 return SDValue(); 12229 12230 SDValue ConstVec = N->getOperand(1); 12231 if (!isa<BuildVectorSDNode>(ConstVec)) 12232 return SDValue(); 12233 12234 MVT IntTy = Op.getOperand(0).getSimpleValueType().getVectorElementType(); 12235 int32_t IntBits = IntTy.getSizeInBits(); 12236 if (IntBits != 16 && IntBits != 32 && IntBits != 64) 12237 return SDValue(); 12238 12239 MVT FloatTy = N->getSimpleValueType(0).getVectorElementType(); 12240 int32_t FloatBits = FloatTy.getSizeInBits(); 12241 if (FloatBits != 32 && FloatBits != 64) 12242 return SDValue(); 12243 12244 // Avoid conversions where iN is larger than the float (e.g., i64 -> float). 12245 if (IntBits > FloatBits) 12246 return SDValue(); 12247 12248 BitVector UndefElements; 12249 BuildVectorSDNode *BV = cast<BuildVectorSDNode>(ConstVec); 12250 int32_t C = BV->getConstantFPSplatPow2ToLog2Int(&UndefElements, FloatBits + 1); 12251 if (C == -1 || C == 0 || C > FloatBits) 12252 return SDValue(); 12253 12254 MVT ResTy; 12255 unsigned NumLanes = Op.getValueType().getVectorNumElements(); 12256 switch (NumLanes) { 12257 default: 12258 return SDValue(); 12259 case 2: 12260 ResTy = FloatBits == 32 ? MVT::v2i32 : MVT::v2i64; 12261 break; 12262 case 4: 12263 ResTy = FloatBits == 32 ? MVT::v4i32 : MVT::v4i64; 12264 break; 12265 } 12266 12267 if (ResTy == MVT::v4i64 && DCI.isBeforeLegalizeOps()) 12268 return SDValue(); 12269 12270 SDLoc DL(N); 12271 SDValue ConvInput = Op.getOperand(0); 12272 bool IsSigned = Opc == ISD::SINT_TO_FP; 12273 if (IntBits < FloatBits) 12274 ConvInput = DAG.getNode(IsSigned ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND, DL, 12275 ResTy, ConvInput); 12276 12277 unsigned IntrinsicOpcode = IsSigned ? Intrinsic::aarch64_neon_vcvtfxs2fp 12278 : Intrinsic::aarch64_neon_vcvtfxu2fp; 12279 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, Op.getValueType(), 12280 DAG.getConstant(IntrinsicOpcode, DL, MVT::i32), ConvInput, 12281 DAG.getConstant(C, DL, MVT::i32)); 12282 } 12283 12284 /// An EXTR instruction is made up of two shifts, ORed together. This helper 12285 /// searches for and classifies those shifts. 12286 static bool findEXTRHalf(SDValue N, SDValue &Src, uint32_t &ShiftAmount, 12287 bool &FromHi) { 12288 if (N.getOpcode() == ISD::SHL) 12289 FromHi = false; 12290 else if (N.getOpcode() == ISD::SRL) 12291 FromHi = true; 12292 else 12293 return false; 12294 12295 if (!isa<ConstantSDNode>(N.getOperand(1))) 12296 return false; 12297 12298 ShiftAmount = N->getConstantOperandVal(1); 12299 Src = N->getOperand(0); 12300 return true; 12301 } 12302 12303 /// EXTR instruction extracts a contiguous chunk of bits from two existing 12304 /// registers viewed as a high/low pair. This function looks for the pattern: 12305 /// <tt>(or (shl VAL1, \#N), (srl VAL2, \#RegWidth-N))</tt> and replaces it 12306 /// with an EXTR. Can't quite be done in TableGen because the two immediates 12307 /// aren't independent. 12308 static SDValue tryCombineToEXTR(SDNode *N, 12309 TargetLowering::DAGCombinerInfo &DCI) { 12310 SelectionDAG &DAG = DCI.DAG; 12311 SDLoc DL(N); 12312 EVT VT = N->getValueType(0); 12313 12314 assert(N->getOpcode() == ISD::OR && "Unexpected root"); 12315 12316 if (VT != MVT::i32 && VT != MVT::i64) 12317 return SDValue(); 12318 12319 SDValue LHS; 12320 uint32_t ShiftLHS = 0; 12321 bool LHSFromHi = false; 12322 if (!findEXTRHalf(N->getOperand(0), LHS, ShiftLHS, LHSFromHi)) 12323 return SDValue(); 12324 12325 SDValue RHS; 12326 uint32_t ShiftRHS = 0; 12327 bool RHSFromHi = false; 12328 if (!findEXTRHalf(N->getOperand(1), RHS, ShiftRHS, RHSFromHi)) 12329 return SDValue(); 12330 12331 // If they're both trying to come from the high part of the register, they're 12332 // not really an EXTR. 12333 if (LHSFromHi == RHSFromHi) 12334 return SDValue(); 12335 12336 if (ShiftLHS + ShiftRHS != VT.getSizeInBits()) 12337 return SDValue(); 12338 12339 if (LHSFromHi) { 12340 std::swap(LHS, RHS); 12341 std::swap(ShiftLHS, ShiftRHS); 12342 } 12343 12344 return DAG.getNode(AArch64ISD::EXTR, DL, VT, LHS, RHS, 12345 DAG.getConstant(ShiftRHS, DL, MVT::i64)); 12346 } 12347 12348 static SDValue tryCombineToBSL(SDNode *N, 12349 TargetLowering::DAGCombinerInfo &DCI) { 12350 EVT VT = N->getValueType(0); 12351 SelectionDAG &DAG = DCI.DAG; 12352 SDLoc DL(N); 12353 12354 if (!VT.isVector()) 12355 return SDValue(); 12356 12357 SDValue N0 = N->getOperand(0); 12358 if (N0.getOpcode() != ISD::AND) 12359 return SDValue(); 12360 12361 SDValue N1 = N->getOperand(1); 12362 if (N1.getOpcode() != ISD::AND) 12363 return SDValue(); 12364 12365 // We only have to look for constant vectors here since the general, variable 12366 // case can be handled in TableGen. 12367 unsigned Bits = VT.getScalarSizeInBits(); 12368 uint64_t BitMask = Bits == 64 ? -1ULL : ((1ULL << Bits) - 1); 12369 for (int i = 1; i >= 0; --i) 12370 for (int j = 1; j >= 0; --j) { 12371 BuildVectorSDNode *BVN0 = dyn_cast<BuildVectorSDNode>(N0->getOperand(i)); 12372 BuildVectorSDNode *BVN1 = dyn_cast<BuildVectorSDNode>(N1->getOperand(j)); 12373 if (!BVN0 || !BVN1) 12374 continue; 12375 12376 bool FoundMatch = true; 12377 for (unsigned k = 0; k < VT.getVectorNumElements(); ++k) { 12378 ConstantSDNode *CN0 = dyn_cast<ConstantSDNode>(BVN0->getOperand(k)); 12379 ConstantSDNode *CN1 = dyn_cast<ConstantSDNode>(BVN1->getOperand(k)); 12380 if (!CN0 || !CN1 || 12381 CN0->getZExtValue() != (BitMask & ~CN1->getZExtValue())) { 12382 FoundMatch = false; 12383 break; 12384 } 12385 } 12386 12387 if (FoundMatch) 12388 return DAG.getNode(AArch64ISD::BSP, DL, VT, SDValue(BVN0, 0), 12389 N0->getOperand(1 - i), N1->getOperand(1 - j)); 12390 } 12391 12392 return SDValue(); 12393 } 12394 12395 static SDValue performORCombine(SDNode *N, TargetLowering::DAGCombinerInfo &DCI, 12396 const AArch64Subtarget *Subtarget) { 12397 // Attempt to form an EXTR from (or (shl VAL1, #N), (srl VAL2, #RegWidth-N)) 12398 SelectionDAG &DAG = DCI.DAG; 12399 EVT VT = N->getValueType(0); 12400 12401 if (!DAG.getTargetLoweringInfo().isTypeLegal(VT)) 12402 return SDValue(); 12403 12404 if (SDValue Res = tryCombineToEXTR(N, DCI)) 12405 return Res; 12406 12407 if (SDValue Res = tryCombineToBSL(N, DCI)) 12408 return Res; 12409 12410 return SDValue(); 12411 } 12412 12413 static bool isConstantSplatVectorMaskForType(SDNode *N, EVT MemVT) { 12414 if (!MemVT.getVectorElementType().isSimple()) 12415 return false; 12416 12417 uint64_t MaskForTy = 0ull; 12418 switch (MemVT.getVectorElementType().getSimpleVT().SimpleTy) { 12419 case MVT::i8: 12420 MaskForTy = 0xffull; 12421 break; 12422 case MVT::i16: 12423 MaskForTy = 0xffffull; 12424 break; 12425 case MVT::i32: 12426 MaskForTy = 0xffffffffull; 12427 break; 12428 default: 12429 return false; 12430 break; 12431 } 12432 12433 if (N->getOpcode() == AArch64ISD::DUP || N->getOpcode() == ISD::SPLAT_VECTOR) 12434 if (auto *Op0 = dyn_cast<ConstantSDNode>(N->getOperand(0))) 12435 return Op0->getAPIntValue().getLimitedValue() == MaskForTy; 12436 12437 return false; 12438 } 12439 12440 static SDValue performSVEAndCombine(SDNode *N, 12441 TargetLowering::DAGCombinerInfo &DCI) { 12442 if (DCI.isBeforeLegalizeOps()) 12443 return SDValue(); 12444 12445 SelectionDAG &DAG = DCI.DAG; 12446 SDValue Src = N->getOperand(0); 12447 unsigned Opc = Src->getOpcode(); 12448 12449 // Zero/any extend of an unsigned unpack 12450 if (Opc == AArch64ISD::UUNPKHI || Opc == AArch64ISD::UUNPKLO) { 12451 SDValue UnpkOp = Src->getOperand(0); 12452 SDValue Dup = N->getOperand(1); 12453 12454 if (Dup.getOpcode() != AArch64ISD::DUP) 12455 return SDValue(); 12456 12457 SDLoc DL(N); 12458 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Dup->getOperand(0)); 12459 uint64_t ExtVal = C->getZExtValue(); 12460 12461 // If the mask is fully covered by the unpack, we don't need to push 12462 // a new AND onto the operand 12463 EVT EltTy = UnpkOp->getValueType(0).getVectorElementType(); 12464 if ((ExtVal == 0xFF && EltTy == MVT::i8) || 12465 (ExtVal == 0xFFFF && EltTy == MVT::i16) || 12466 (ExtVal == 0xFFFFFFFF && EltTy == MVT::i32)) 12467 return Src; 12468 12469 // Truncate to prevent a DUP with an over wide constant 12470 APInt Mask = C->getAPIntValue().trunc(EltTy.getSizeInBits()); 12471 12472 // Otherwise, make sure we propagate the AND to the operand 12473 // of the unpack 12474 Dup = DAG.getNode(AArch64ISD::DUP, DL, 12475 UnpkOp->getValueType(0), 12476 DAG.getConstant(Mask.zextOrTrunc(32), DL, MVT::i32)); 12477 12478 SDValue And = DAG.getNode(ISD::AND, DL, 12479 UnpkOp->getValueType(0), UnpkOp, Dup); 12480 12481 return DAG.getNode(Opc, DL, N->getValueType(0), And); 12482 } 12483 12484 if (!EnableCombineMGatherIntrinsics) 12485 return SDValue(); 12486 12487 SDValue Mask = N->getOperand(1); 12488 12489 if (!Src.hasOneUse()) 12490 return SDValue(); 12491 12492 EVT MemVT; 12493 12494 // SVE load instructions perform an implicit zero-extend, which makes them 12495 // perfect candidates for combining. 12496 switch (Opc) { 12497 case AArch64ISD::LD1_MERGE_ZERO: 12498 case AArch64ISD::LDNF1_MERGE_ZERO: 12499 case AArch64ISD::LDFF1_MERGE_ZERO: 12500 MemVT = cast<VTSDNode>(Src->getOperand(3))->getVT(); 12501 break; 12502 case AArch64ISD::GLD1_MERGE_ZERO: 12503 case AArch64ISD::GLD1_SCALED_MERGE_ZERO: 12504 case AArch64ISD::GLD1_SXTW_MERGE_ZERO: 12505 case AArch64ISD::GLD1_SXTW_SCALED_MERGE_ZERO: 12506 case AArch64ISD::GLD1_UXTW_MERGE_ZERO: 12507 case AArch64ISD::GLD1_UXTW_SCALED_MERGE_ZERO: 12508 case AArch64ISD::GLD1_IMM_MERGE_ZERO: 12509 case AArch64ISD::GLDFF1_MERGE_ZERO: 12510 case AArch64ISD::GLDFF1_SCALED_MERGE_ZERO: 12511 case AArch64ISD::GLDFF1_SXTW_MERGE_ZERO: 12512 case AArch64ISD::GLDFF1_SXTW_SCALED_MERGE_ZERO: 12513 case AArch64ISD::GLDFF1_UXTW_MERGE_ZERO: 12514 case AArch64ISD::GLDFF1_UXTW_SCALED_MERGE_ZERO: 12515 case AArch64ISD::GLDFF1_IMM_MERGE_ZERO: 12516 case AArch64ISD::GLDNT1_MERGE_ZERO: 12517 MemVT = cast<VTSDNode>(Src->getOperand(4))->getVT(); 12518 break; 12519 default: 12520 return SDValue(); 12521 } 12522 12523 if (isConstantSplatVectorMaskForType(Mask.getNode(), MemVT)) 12524 return Src; 12525 12526 return SDValue(); 12527 } 12528 12529 static SDValue performANDCombine(SDNode *N, 12530 TargetLowering::DAGCombinerInfo &DCI) { 12531 SelectionDAG &DAG = DCI.DAG; 12532 SDValue LHS = N->getOperand(0); 12533 EVT VT = N->getValueType(0); 12534 if (!VT.isVector() || !DAG.getTargetLoweringInfo().isTypeLegal(VT)) 12535 return SDValue(); 12536 12537 if (VT.isScalableVector()) 12538 return performSVEAndCombine(N, DCI); 12539 12540 // The combining code below works only for NEON vectors. In particular, it 12541 // does not work for SVE when dealing with vectors wider than 128 bits. 12542 if (!(VT.is64BitVector() || VT.is128BitVector())) 12543 return SDValue(); 12544 12545 BuildVectorSDNode *BVN = 12546 dyn_cast<BuildVectorSDNode>(N->getOperand(1).getNode()); 12547 if (!BVN) 12548 return SDValue(); 12549 12550 // AND does not accept an immediate, so check if we can use a BIC immediate 12551 // instruction instead. We do this here instead of using a (and x, (mvni imm)) 12552 // pattern in isel, because some immediates may be lowered to the preferred 12553 // (and x, (movi imm)) form, even though an mvni representation also exists. 12554 APInt DefBits(VT.getSizeInBits(), 0); 12555 APInt UndefBits(VT.getSizeInBits(), 0); 12556 if (resolveBuildVector(BVN, DefBits, UndefBits)) { 12557 SDValue NewOp; 12558 12559 DefBits = ~DefBits; 12560 if ((NewOp = tryAdvSIMDModImm32(AArch64ISD::BICi, SDValue(N, 0), DAG, 12561 DefBits, &LHS)) || 12562 (NewOp = tryAdvSIMDModImm16(AArch64ISD::BICi, SDValue(N, 0), DAG, 12563 DefBits, &LHS))) 12564 return NewOp; 12565 12566 UndefBits = ~UndefBits; 12567 if ((NewOp = tryAdvSIMDModImm32(AArch64ISD::BICi, SDValue(N, 0), DAG, 12568 UndefBits, &LHS)) || 12569 (NewOp = tryAdvSIMDModImm16(AArch64ISD::BICi, SDValue(N, 0), DAG, 12570 UndefBits, &LHS))) 12571 return NewOp; 12572 } 12573 12574 return SDValue(); 12575 } 12576 12577 static SDValue performSRLCombine(SDNode *N, 12578 TargetLowering::DAGCombinerInfo &DCI) { 12579 SelectionDAG &DAG = DCI.DAG; 12580 EVT VT = N->getValueType(0); 12581 if (VT != MVT::i32 && VT != MVT::i64) 12582 return SDValue(); 12583 12584 // Canonicalize (srl (bswap i32 x), 16) to (rotr (bswap i32 x), 16), if the 12585 // high 16-bits of x are zero. Similarly, canonicalize (srl (bswap i64 x), 32) 12586 // to (rotr (bswap i64 x), 32), if the high 32-bits of x are zero. 12587 SDValue N0 = N->getOperand(0); 12588 if (N0.getOpcode() == ISD::BSWAP) { 12589 SDLoc DL(N); 12590 SDValue N1 = N->getOperand(1); 12591 SDValue N00 = N0.getOperand(0); 12592 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(N1)) { 12593 uint64_t ShiftAmt = C->getZExtValue(); 12594 if (VT == MVT::i32 && ShiftAmt == 16 && 12595 DAG.MaskedValueIsZero(N00, APInt::getHighBitsSet(32, 16))) 12596 return DAG.getNode(ISD::ROTR, DL, VT, N0, N1); 12597 if (VT == MVT::i64 && ShiftAmt == 32 && 12598 DAG.MaskedValueIsZero(N00, APInt::getHighBitsSet(64, 32))) 12599 return DAG.getNode(ISD::ROTR, DL, VT, N0, N1); 12600 } 12601 } 12602 return SDValue(); 12603 } 12604 12605 // Attempt to form urhadd(OpA, OpB) from 12606 // truncate(vlshr(sub(zext(OpB), xor(zext(OpA), Ones(ElemSizeInBits))), 1)) 12607 // or uhadd(OpA, OpB) from truncate(vlshr(add(zext(OpA), zext(OpB)), 1)). 12608 // The original form of the first expression is 12609 // truncate(srl(add(zext(OpB), add(zext(OpA), 1)), 1)) and the 12610 // (OpA + OpB + 1) subexpression will have been changed to (OpB - (~OpA)). 12611 // Before this function is called the srl will have been lowered to 12612 // AArch64ISD::VLSHR. 12613 // This pass can also recognize signed variants of the patterns that use sign 12614 // extension instead of zero extension and form a srhadd(OpA, OpB) or a 12615 // shadd(OpA, OpB) from them. 12616 static SDValue 12617 performVectorTruncateCombine(SDNode *N, TargetLowering::DAGCombinerInfo &DCI, 12618 SelectionDAG &DAG) { 12619 EVT VT = N->getValueType(0); 12620 12621 // Since we are looking for a right shift by a constant value of 1 and we are 12622 // operating on types at least 16 bits in length (sign/zero extended OpA and 12623 // OpB, which are at least 8 bits), it follows that the truncate will always 12624 // discard the shifted-in bit and therefore the right shift will be logical 12625 // regardless of the signedness of OpA and OpB. 12626 SDValue Shift = N->getOperand(0); 12627 if (Shift.getOpcode() != AArch64ISD::VLSHR) 12628 return SDValue(); 12629 12630 // Is the right shift using an immediate value of 1? 12631 uint64_t ShiftAmount = Shift.getConstantOperandVal(1); 12632 if (ShiftAmount != 1) 12633 return SDValue(); 12634 12635 SDValue ExtendOpA, ExtendOpB; 12636 SDValue ShiftOp0 = Shift.getOperand(0); 12637 unsigned ShiftOp0Opc = ShiftOp0.getOpcode(); 12638 if (ShiftOp0Opc == ISD::SUB) { 12639 12640 SDValue Xor = ShiftOp0.getOperand(1); 12641 if (Xor.getOpcode() != ISD::XOR) 12642 return SDValue(); 12643 12644 // Is the XOR using a constant amount of all ones in the right hand side? 12645 uint64_t C; 12646 if (!isAllConstantBuildVector(Xor.getOperand(1), C)) 12647 return SDValue(); 12648 12649 unsigned ElemSizeInBits = VT.getScalarSizeInBits(); 12650 APInt CAsAPInt(ElemSizeInBits, C); 12651 if (CAsAPInt != APInt::getAllOnesValue(ElemSizeInBits)) 12652 return SDValue(); 12653 12654 ExtendOpA = Xor.getOperand(0); 12655 ExtendOpB = ShiftOp0.getOperand(0); 12656 } else if (ShiftOp0Opc == ISD::ADD) { 12657 ExtendOpA = ShiftOp0.getOperand(0); 12658 ExtendOpB = ShiftOp0.getOperand(1); 12659 } else 12660 return SDValue(); 12661 12662 unsigned ExtendOpAOpc = ExtendOpA.getOpcode(); 12663 unsigned ExtendOpBOpc = ExtendOpB.getOpcode(); 12664 if (!(ExtendOpAOpc == ExtendOpBOpc && 12665 (ExtendOpAOpc == ISD::ZERO_EXTEND || ExtendOpAOpc == ISD::SIGN_EXTEND))) 12666 return SDValue(); 12667 12668 // Is the result of the right shift being truncated to the same value type as 12669 // the original operands, OpA and OpB? 12670 SDValue OpA = ExtendOpA.getOperand(0); 12671 SDValue OpB = ExtendOpB.getOperand(0); 12672 EVT OpAVT = OpA.getValueType(); 12673 assert(ExtendOpA.getValueType() == ExtendOpB.getValueType()); 12674 if (!(VT == OpAVT && OpAVT == OpB.getValueType())) 12675 return SDValue(); 12676 12677 SDLoc DL(N); 12678 bool IsSignExtend = ExtendOpAOpc == ISD::SIGN_EXTEND; 12679 bool IsRHADD = ShiftOp0Opc == ISD::SUB; 12680 unsigned HADDOpc = IsSignExtend 12681 ? (IsRHADD ? AArch64ISD::SRHADD : AArch64ISD::SHADD) 12682 : (IsRHADD ? AArch64ISD::URHADD : AArch64ISD::UHADD); 12683 SDValue ResultHADD = DAG.getNode(HADDOpc, DL, VT, OpA, OpB); 12684 12685 return ResultHADD; 12686 } 12687 12688 static bool hasPairwiseAdd(unsigned Opcode, EVT VT, bool FullFP16) { 12689 switch (Opcode) { 12690 case ISD::FADD: 12691 return (FullFP16 && VT == MVT::f16) || VT == MVT::f32 || VT == MVT::f64; 12692 case ISD::ADD: 12693 return VT == MVT::i64; 12694 default: 12695 return false; 12696 } 12697 } 12698 12699 static SDValue performExtractVectorEltCombine(SDNode *N, SelectionDAG &DAG) { 12700 SDValue N0 = N->getOperand(0), N1 = N->getOperand(1); 12701 ConstantSDNode *ConstantN1 = dyn_cast<ConstantSDNode>(N1); 12702 12703 EVT VT = N->getValueType(0); 12704 const bool FullFP16 = 12705 static_cast<const AArch64Subtarget &>(DAG.getSubtarget()).hasFullFP16(); 12706 12707 // Rewrite for pairwise fadd pattern 12708 // (f32 (extract_vector_elt 12709 // (fadd (vXf32 Other) 12710 // (vector_shuffle (vXf32 Other) undef <1,X,...> )) 0)) 12711 // -> 12712 // (f32 (fadd (extract_vector_elt (vXf32 Other) 0) 12713 // (extract_vector_elt (vXf32 Other) 1)) 12714 if (ConstantN1 && ConstantN1->getZExtValue() == 0 && 12715 hasPairwiseAdd(N0->getOpcode(), VT, FullFP16)) { 12716 SDLoc DL(N0); 12717 SDValue N00 = N0->getOperand(0); 12718 SDValue N01 = N0->getOperand(1); 12719 12720 ShuffleVectorSDNode *Shuffle = dyn_cast<ShuffleVectorSDNode>(N01); 12721 SDValue Other = N00; 12722 12723 // And handle the commutative case. 12724 if (!Shuffle) { 12725 Shuffle = dyn_cast<ShuffleVectorSDNode>(N00); 12726 Other = N01; 12727 } 12728 12729 if (Shuffle && Shuffle->getMaskElt(0) == 1 && 12730 Other == Shuffle->getOperand(0)) { 12731 return DAG.getNode(N0->getOpcode(), DL, VT, 12732 DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, VT, Other, 12733 DAG.getConstant(0, DL, MVT::i64)), 12734 DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, VT, Other, 12735 DAG.getConstant(1, DL, MVT::i64))); 12736 } 12737 } 12738 12739 return SDValue(); 12740 } 12741 12742 static SDValue performConcatVectorsCombine(SDNode *N, 12743 TargetLowering::DAGCombinerInfo &DCI, 12744 SelectionDAG &DAG) { 12745 SDLoc dl(N); 12746 EVT VT = N->getValueType(0); 12747 SDValue N0 = N->getOperand(0), N1 = N->getOperand(1); 12748 unsigned N0Opc = N0->getOpcode(), N1Opc = N1->getOpcode(); 12749 12750 // Optimize concat_vectors of truncated vectors, where the intermediate 12751 // type is illegal, to avoid said illegality, e.g., 12752 // (v4i16 (concat_vectors (v2i16 (truncate (v2i64))), 12753 // (v2i16 (truncate (v2i64))))) 12754 // -> 12755 // (v4i16 (truncate (vector_shuffle (v4i32 (bitcast (v2i64))), 12756 // (v4i32 (bitcast (v2i64))), 12757 // <0, 2, 4, 6>))) 12758 // This isn't really target-specific, but ISD::TRUNCATE legality isn't keyed 12759 // on both input and result type, so we might generate worse code. 12760 // On AArch64 we know it's fine for v2i64->v4i16 and v4i32->v8i8. 12761 if (N->getNumOperands() == 2 && N0Opc == ISD::TRUNCATE && 12762 N1Opc == ISD::TRUNCATE) { 12763 SDValue N00 = N0->getOperand(0); 12764 SDValue N10 = N1->getOperand(0); 12765 EVT N00VT = N00.getValueType(); 12766 12767 if (N00VT == N10.getValueType() && 12768 (N00VT == MVT::v2i64 || N00VT == MVT::v4i32) && 12769 N00VT.getScalarSizeInBits() == 4 * VT.getScalarSizeInBits()) { 12770 MVT MidVT = (N00VT == MVT::v2i64 ? MVT::v4i32 : MVT::v8i16); 12771 SmallVector<int, 8> Mask(MidVT.getVectorNumElements()); 12772 for (size_t i = 0; i < Mask.size(); ++i) 12773 Mask[i] = i * 2; 12774 return DAG.getNode(ISD::TRUNCATE, dl, VT, 12775 DAG.getVectorShuffle( 12776 MidVT, dl, 12777 DAG.getNode(ISD::BITCAST, dl, MidVT, N00), 12778 DAG.getNode(ISD::BITCAST, dl, MidVT, N10), Mask)); 12779 } 12780 } 12781 12782 // Wait 'til after everything is legalized to try this. That way we have 12783 // legal vector types and such. 12784 if (DCI.isBeforeLegalizeOps()) 12785 return SDValue(); 12786 12787 // Optimise concat_vectors of two [us]rhadds or [us]hadds that use extracted 12788 // subvectors from the same original vectors. Combine these into a single 12789 // [us]rhadd or [us]hadd that operates on the two original vectors. Example: 12790 // (v16i8 (concat_vectors (v8i8 (urhadd (extract_subvector (v16i8 OpA, <0>), 12791 // extract_subvector (v16i8 OpB, 12792 // <0>))), 12793 // (v8i8 (urhadd (extract_subvector (v16i8 OpA, <8>), 12794 // extract_subvector (v16i8 OpB, 12795 // <8>))))) 12796 // -> 12797 // (v16i8(urhadd(v16i8 OpA, v16i8 OpB))) 12798 if (N->getNumOperands() == 2 && N0Opc == N1Opc && 12799 (N0Opc == AArch64ISD::URHADD || N0Opc == AArch64ISD::SRHADD || 12800 N0Opc == AArch64ISD::UHADD || N0Opc == AArch64ISD::SHADD)) { 12801 SDValue N00 = N0->getOperand(0); 12802 SDValue N01 = N0->getOperand(1); 12803 SDValue N10 = N1->getOperand(0); 12804 SDValue N11 = N1->getOperand(1); 12805 12806 EVT N00VT = N00.getValueType(); 12807 EVT N10VT = N10.getValueType(); 12808 12809 if (N00->getOpcode() == ISD::EXTRACT_SUBVECTOR && 12810 N01->getOpcode() == ISD::EXTRACT_SUBVECTOR && 12811 N10->getOpcode() == ISD::EXTRACT_SUBVECTOR && 12812 N11->getOpcode() == ISD::EXTRACT_SUBVECTOR && N00VT == N10VT) { 12813 SDValue N00Source = N00->getOperand(0); 12814 SDValue N01Source = N01->getOperand(0); 12815 SDValue N10Source = N10->getOperand(0); 12816 SDValue N11Source = N11->getOperand(0); 12817 12818 if (N00Source == N10Source && N01Source == N11Source && 12819 N00Source.getValueType() == VT && N01Source.getValueType() == VT) { 12820 assert(N0.getValueType() == N1.getValueType()); 12821 12822 uint64_t N00Index = N00.getConstantOperandVal(1); 12823 uint64_t N01Index = N01.getConstantOperandVal(1); 12824 uint64_t N10Index = N10.getConstantOperandVal(1); 12825 uint64_t N11Index = N11.getConstantOperandVal(1); 12826 12827 if (N00Index == N01Index && N10Index == N11Index && N00Index == 0 && 12828 N10Index == N00VT.getVectorNumElements()) 12829 return DAG.getNode(N0Opc, dl, VT, N00Source, N01Source); 12830 } 12831 } 12832 } 12833 12834 // If we see a (concat_vectors (v1x64 A), (v1x64 A)) it's really a vector 12835 // splat. The indexed instructions are going to be expecting a DUPLANE64, so 12836 // canonicalise to that. 12837 if (N0 == N1 && VT.getVectorNumElements() == 2) { 12838 assert(VT.getScalarSizeInBits() == 64); 12839 return DAG.getNode(AArch64ISD::DUPLANE64, dl, VT, WidenVector(N0, DAG), 12840 DAG.getConstant(0, dl, MVT::i64)); 12841 } 12842 12843 // Canonicalise concat_vectors so that the right-hand vector has as few 12844 // bit-casts as possible before its real operation. The primary matching 12845 // destination for these operations will be the narrowing "2" instructions, 12846 // which depend on the operation being performed on this right-hand vector. 12847 // For example, 12848 // (concat_vectors LHS, (v1i64 (bitconvert (v4i16 RHS)))) 12849 // becomes 12850 // (bitconvert (concat_vectors (v4i16 (bitconvert LHS)), RHS)) 12851 12852 if (N1Opc != ISD::BITCAST) 12853 return SDValue(); 12854 SDValue RHS = N1->getOperand(0); 12855 MVT RHSTy = RHS.getValueType().getSimpleVT(); 12856 // If the RHS is not a vector, this is not the pattern we're looking for. 12857 if (!RHSTy.isVector()) 12858 return SDValue(); 12859 12860 LLVM_DEBUG( 12861 dbgs() << "aarch64-lower: concat_vectors bitcast simplification\n"); 12862 12863 MVT ConcatTy = MVT::getVectorVT(RHSTy.getVectorElementType(), 12864 RHSTy.getVectorNumElements() * 2); 12865 return DAG.getNode(ISD::BITCAST, dl, VT, 12866 DAG.getNode(ISD::CONCAT_VECTORS, dl, ConcatTy, 12867 DAG.getNode(ISD::BITCAST, dl, RHSTy, N0), 12868 RHS)); 12869 } 12870 12871 static SDValue tryCombineFixedPointConvert(SDNode *N, 12872 TargetLowering::DAGCombinerInfo &DCI, 12873 SelectionDAG &DAG) { 12874 // Wait until after everything is legalized to try this. That way we have 12875 // legal vector types and such. 12876 if (DCI.isBeforeLegalizeOps()) 12877 return SDValue(); 12878 // Transform a scalar conversion of a value from a lane extract into a 12879 // lane extract of a vector conversion. E.g., from foo1 to foo2: 12880 // double foo1(int64x2_t a) { return vcvtd_n_f64_s64(a[1], 9); } 12881 // double foo2(int64x2_t a) { return vcvtq_n_f64_s64(a, 9)[1]; } 12882 // 12883 // The second form interacts better with instruction selection and the 12884 // register allocator to avoid cross-class register copies that aren't 12885 // coalescable due to a lane reference. 12886 12887 // Check the operand and see if it originates from a lane extract. 12888 SDValue Op1 = N->getOperand(1); 12889 if (Op1.getOpcode() == ISD::EXTRACT_VECTOR_ELT) { 12890 // Yep, no additional predication needed. Perform the transform. 12891 SDValue IID = N->getOperand(0); 12892 SDValue Shift = N->getOperand(2); 12893 SDValue Vec = Op1.getOperand(0); 12894 SDValue Lane = Op1.getOperand(1); 12895 EVT ResTy = N->getValueType(0); 12896 EVT VecResTy; 12897 SDLoc DL(N); 12898 12899 // The vector width should be 128 bits by the time we get here, even 12900 // if it started as 64 bits (the extract_vector handling will have 12901 // done so). 12902 assert(Vec.getValueSizeInBits() == 128 && 12903 "unexpected vector size on extract_vector_elt!"); 12904 if (Vec.getValueType() == MVT::v4i32) 12905 VecResTy = MVT::v4f32; 12906 else if (Vec.getValueType() == MVT::v2i64) 12907 VecResTy = MVT::v2f64; 12908 else 12909 llvm_unreachable("unexpected vector type!"); 12910 12911 SDValue Convert = 12912 DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VecResTy, IID, Vec, Shift); 12913 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, ResTy, Convert, Lane); 12914 } 12915 return SDValue(); 12916 } 12917 12918 // AArch64 high-vector "long" operations are formed by performing the non-high 12919 // version on an extract_subvector of each operand which gets the high half: 12920 // 12921 // (longop2 LHS, RHS) == (longop (extract_high LHS), (extract_high RHS)) 12922 // 12923 // However, there are cases which don't have an extract_high explicitly, but 12924 // have another operation that can be made compatible with one for free. For 12925 // example: 12926 // 12927 // (dupv64 scalar) --> (extract_high (dup128 scalar)) 12928 // 12929 // This routine does the actual conversion of such DUPs, once outer routines 12930 // have determined that everything else is in order. 12931 // It also supports immediate DUP-like nodes (MOVI/MVNi), which we can fold 12932 // similarly here. 12933 static SDValue tryExtendDUPToExtractHigh(SDValue N, SelectionDAG &DAG) { 12934 switch (N.getOpcode()) { 12935 case AArch64ISD::DUP: 12936 case AArch64ISD::DUPLANE8: 12937 case AArch64ISD::DUPLANE16: 12938 case AArch64ISD::DUPLANE32: 12939 case AArch64ISD::DUPLANE64: 12940 case AArch64ISD::MOVI: 12941 case AArch64ISD::MOVIshift: 12942 case AArch64ISD::MOVIedit: 12943 case AArch64ISD::MOVImsl: 12944 case AArch64ISD::MVNIshift: 12945 case AArch64ISD::MVNImsl: 12946 break; 12947 default: 12948 // FMOV could be supported, but isn't very useful, as it would only occur 12949 // if you passed a bitcast' floating point immediate to an eligible long 12950 // integer op (addl, smull, ...). 12951 return SDValue(); 12952 } 12953 12954 MVT NarrowTy = N.getSimpleValueType(); 12955 if (!NarrowTy.is64BitVector()) 12956 return SDValue(); 12957 12958 MVT ElementTy = NarrowTy.getVectorElementType(); 12959 unsigned NumElems = NarrowTy.getVectorNumElements(); 12960 MVT NewVT = MVT::getVectorVT(ElementTy, NumElems * 2); 12961 12962 SDLoc dl(N); 12963 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, NarrowTy, 12964 DAG.getNode(N->getOpcode(), dl, NewVT, N->ops()), 12965 DAG.getConstant(NumElems, dl, MVT::i64)); 12966 } 12967 12968 static bool isEssentiallyExtractHighSubvector(SDValue N) { 12969 if (N.getOpcode() == ISD::BITCAST) 12970 N = N.getOperand(0); 12971 if (N.getOpcode() != ISD::EXTRACT_SUBVECTOR) 12972 return false; 12973 return cast<ConstantSDNode>(N.getOperand(1))->getAPIntValue() == 12974 N.getOperand(0).getValueType().getVectorNumElements() / 2; 12975 } 12976 12977 /// Helper structure to keep track of ISD::SET_CC operands. 12978 struct GenericSetCCInfo { 12979 const SDValue *Opnd0; 12980 const SDValue *Opnd1; 12981 ISD::CondCode CC; 12982 }; 12983 12984 /// Helper structure to keep track of a SET_CC lowered into AArch64 code. 12985 struct AArch64SetCCInfo { 12986 const SDValue *Cmp; 12987 AArch64CC::CondCode CC; 12988 }; 12989 12990 /// Helper structure to keep track of SetCC information. 12991 union SetCCInfo { 12992 GenericSetCCInfo Generic; 12993 AArch64SetCCInfo AArch64; 12994 }; 12995 12996 /// Helper structure to be able to read SetCC information. If set to 12997 /// true, IsAArch64 field, Info is a AArch64SetCCInfo, otherwise Info is a 12998 /// GenericSetCCInfo. 12999 struct SetCCInfoAndKind { 13000 SetCCInfo Info; 13001 bool IsAArch64; 13002 }; 13003 13004 /// Check whether or not \p Op is a SET_CC operation, either a generic or 13005 /// an 13006 /// AArch64 lowered one. 13007 /// \p SetCCInfo is filled accordingly. 13008 /// \post SetCCInfo is meanginfull only when this function returns true. 13009 /// \return True when Op is a kind of SET_CC operation. 13010 static bool isSetCC(SDValue Op, SetCCInfoAndKind &SetCCInfo) { 13011 // If this is a setcc, this is straight forward. 13012 if (Op.getOpcode() == ISD::SETCC) { 13013 SetCCInfo.Info.Generic.Opnd0 = &Op.getOperand(0); 13014 SetCCInfo.Info.Generic.Opnd1 = &Op.getOperand(1); 13015 SetCCInfo.Info.Generic.CC = cast<CondCodeSDNode>(Op.getOperand(2))->get(); 13016 SetCCInfo.IsAArch64 = false; 13017 return true; 13018 } 13019 // Otherwise, check if this is a matching csel instruction. 13020 // In other words: 13021 // - csel 1, 0, cc 13022 // - csel 0, 1, !cc 13023 if (Op.getOpcode() != AArch64ISD::CSEL) 13024 return false; 13025 // Set the information about the operands. 13026 // TODO: we want the operands of the Cmp not the csel 13027 SetCCInfo.Info.AArch64.Cmp = &Op.getOperand(3); 13028 SetCCInfo.IsAArch64 = true; 13029 SetCCInfo.Info.AArch64.CC = static_cast<AArch64CC::CondCode>( 13030 cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue()); 13031 13032 // Check that the operands matches the constraints: 13033 // (1) Both operands must be constants. 13034 // (2) One must be 1 and the other must be 0. 13035 ConstantSDNode *TValue = dyn_cast<ConstantSDNode>(Op.getOperand(0)); 13036 ConstantSDNode *FValue = dyn_cast<ConstantSDNode>(Op.getOperand(1)); 13037 13038 // Check (1). 13039 if (!TValue || !FValue) 13040 return false; 13041 13042 // Check (2). 13043 if (!TValue->isOne()) { 13044 // Update the comparison when we are interested in !cc. 13045 std::swap(TValue, FValue); 13046 SetCCInfo.Info.AArch64.CC = 13047 AArch64CC::getInvertedCondCode(SetCCInfo.Info.AArch64.CC); 13048 } 13049 return TValue->isOne() && FValue->isNullValue(); 13050 } 13051 13052 // Returns true if Op is setcc or zext of setcc. 13053 static bool isSetCCOrZExtSetCC(const SDValue& Op, SetCCInfoAndKind &Info) { 13054 if (isSetCC(Op, Info)) 13055 return true; 13056 return ((Op.getOpcode() == ISD::ZERO_EXTEND) && 13057 isSetCC(Op->getOperand(0), Info)); 13058 } 13059 13060 // The folding we want to perform is: 13061 // (add x, [zext] (setcc cc ...) ) 13062 // --> 13063 // (csel x, (add x, 1), !cc ...) 13064 // 13065 // The latter will get matched to a CSINC instruction. 13066 static SDValue performSetccAddFolding(SDNode *Op, SelectionDAG &DAG) { 13067 assert(Op && Op->getOpcode() == ISD::ADD && "Unexpected operation!"); 13068 SDValue LHS = Op->getOperand(0); 13069 SDValue RHS = Op->getOperand(1); 13070 SetCCInfoAndKind InfoAndKind; 13071 13072 // If neither operand is a SET_CC, give up. 13073 if (!isSetCCOrZExtSetCC(LHS, InfoAndKind)) { 13074 std::swap(LHS, RHS); 13075 if (!isSetCCOrZExtSetCC(LHS, InfoAndKind)) 13076 return SDValue(); 13077 } 13078 13079 // FIXME: This could be generatized to work for FP comparisons. 13080 EVT CmpVT = InfoAndKind.IsAArch64 13081 ? InfoAndKind.Info.AArch64.Cmp->getOperand(0).getValueType() 13082 : InfoAndKind.Info.Generic.Opnd0->getValueType(); 13083 if (CmpVT != MVT::i32 && CmpVT != MVT::i64) 13084 return SDValue(); 13085 13086 SDValue CCVal; 13087 SDValue Cmp; 13088 SDLoc dl(Op); 13089 if (InfoAndKind.IsAArch64) { 13090 CCVal = DAG.getConstant( 13091 AArch64CC::getInvertedCondCode(InfoAndKind.Info.AArch64.CC), dl, 13092 MVT::i32); 13093 Cmp = *InfoAndKind.Info.AArch64.Cmp; 13094 } else 13095 Cmp = getAArch64Cmp( 13096 *InfoAndKind.Info.Generic.Opnd0, *InfoAndKind.Info.Generic.Opnd1, 13097 ISD::getSetCCInverse(InfoAndKind.Info.Generic.CC, CmpVT), CCVal, DAG, 13098 dl); 13099 13100 EVT VT = Op->getValueType(0); 13101 LHS = DAG.getNode(ISD::ADD, dl, VT, RHS, DAG.getConstant(1, dl, VT)); 13102 return DAG.getNode(AArch64ISD::CSEL, dl, VT, RHS, LHS, CCVal, Cmp); 13103 } 13104 13105 // ADD(UADDV a, UADDV b) --> UADDV(ADD a, b) 13106 static SDValue performUADDVCombine(SDNode *N, SelectionDAG &DAG) { 13107 EVT VT = N->getValueType(0); 13108 // Only scalar integer and vector types. 13109 if (N->getOpcode() != ISD::ADD || !VT.isScalarInteger()) 13110 return SDValue(); 13111 13112 SDValue LHS = N->getOperand(0); 13113 SDValue RHS = N->getOperand(1); 13114 if (LHS.getOpcode() != ISD::EXTRACT_VECTOR_ELT || 13115 RHS.getOpcode() != ISD::EXTRACT_VECTOR_ELT || LHS.getValueType() != VT) 13116 return SDValue(); 13117 13118 auto *LHSN1 = dyn_cast<ConstantSDNode>(LHS->getOperand(1)); 13119 auto *RHSN1 = dyn_cast<ConstantSDNode>(RHS->getOperand(1)); 13120 if (!LHSN1 || LHSN1 != RHSN1 || !RHSN1->isNullValue()) 13121 return SDValue(); 13122 13123 SDValue Op1 = LHS->getOperand(0); 13124 SDValue Op2 = RHS->getOperand(0); 13125 EVT OpVT1 = Op1.getValueType(); 13126 EVT OpVT2 = Op2.getValueType(); 13127 if (Op1.getOpcode() != AArch64ISD::UADDV || OpVT1 != OpVT2 || 13128 Op2.getOpcode() != AArch64ISD::UADDV || 13129 OpVT1.getVectorElementType() != VT) 13130 return SDValue(); 13131 13132 SDValue Val1 = Op1.getOperand(0); 13133 SDValue Val2 = Op2.getOperand(0); 13134 EVT ValVT = Val1->getValueType(0); 13135 SDLoc DL(N); 13136 SDValue AddVal = DAG.getNode(ISD::ADD, DL, ValVT, Val1, Val2); 13137 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, VT, 13138 DAG.getNode(AArch64ISD::UADDV, DL, ValVT, AddVal), 13139 DAG.getConstant(0, DL, MVT::i64)); 13140 } 13141 13142 // The basic add/sub long vector instructions have variants with "2" on the end 13143 // which act on the high-half of their inputs. They are normally matched by 13144 // patterns like: 13145 // 13146 // (add (zeroext (extract_high LHS)), 13147 // (zeroext (extract_high RHS))) 13148 // -> uaddl2 vD, vN, vM 13149 // 13150 // However, if one of the extracts is something like a duplicate, this 13151 // instruction can still be used profitably. This function puts the DAG into a 13152 // more appropriate form for those patterns to trigger. 13153 static SDValue performAddSubLongCombine(SDNode *N, 13154 TargetLowering::DAGCombinerInfo &DCI, 13155 SelectionDAG &DAG) { 13156 if (DCI.isBeforeLegalizeOps()) 13157 return SDValue(); 13158 13159 MVT VT = N->getSimpleValueType(0); 13160 if (!VT.is128BitVector()) { 13161 if (N->getOpcode() == ISD::ADD) 13162 return performSetccAddFolding(N, DAG); 13163 return SDValue(); 13164 } 13165 13166 // Make sure both branches are extended in the same way. 13167 SDValue LHS = N->getOperand(0); 13168 SDValue RHS = N->getOperand(1); 13169 if ((LHS.getOpcode() != ISD::ZERO_EXTEND && 13170 LHS.getOpcode() != ISD::SIGN_EXTEND) || 13171 LHS.getOpcode() != RHS.getOpcode()) 13172 return SDValue(); 13173 13174 unsigned ExtType = LHS.getOpcode(); 13175 13176 // It's not worth doing if at least one of the inputs isn't already an 13177 // extract, but we don't know which it'll be so we have to try both. 13178 if (isEssentiallyExtractHighSubvector(LHS.getOperand(0))) { 13179 RHS = tryExtendDUPToExtractHigh(RHS.getOperand(0), DAG); 13180 if (!RHS.getNode()) 13181 return SDValue(); 13182 13183 RHS = DAG.getNode(ExtType, SDLoc(N), VT, RHS); 13184 } else if (isEssentiallyExtractHighSubvector(RHS.getOperand(0))) { 13185 LHS = tryExtendDUPToExtractHigh(LHS.getOperand(0), DAG); 13186 if (!LHS.getNode()) 13187 return SDValue(); 13188 13189 LHS = DAG.getNode(ExtType, SDLoc(N), VT, LHS); 13190 } 13191 13192 return DAG.getNode(N->getOpcode(), SDLoc(N), VT, LHS, RHS); 13193 } 13194 13195 static SDValue performAddSubCombine(SDNode *N, 13196 TargetLowering::DAGCombinerInfo &DCI, 13197 SelectionDAG &DAG) { 13198 // Try to change sum of two reductions. 13199 if (SDValue Val = performUADDVCombine(N, DAG)) 13200 return Val; 13201 13202 return performAddSubLongCombine(N, DCI, DAG); 13203 } 13204 13205 // Massage DAGs which we can use the high-half "long" operations on into 13206 // something isel will recognize better. E.g. 13207 // 13208 // (aarch64_neon_umull (extract_high vec) (dupv64 scalar)) --> 13209 // (aarch64_neon_umull (extract_high (v2i64 vec))) 13210 // (extract_high (v2i64 (dup128 scalar))))) 13211 // 13212 static SDValue tryCombineLongOpWithDup(unsigned IID, SDNode *N, 13213 TargetLowering::DAGCombinerInfo &DCI, 13214 SelectionDAG &DAG) { 13215 if (DCI.isBeforeLegalizeOps()) 13216 return SDValue(); 13217 13218 SDValue LHS = N->getOperand((IID == Intrinsic::not_intrinsic) ? 0 : 1); 13219 SDValue RHS = N->getOperand((IID == Intrinsic::not_intrinsic) ? 1 : 2); 13220 assert(LHS.getValueType().is64BitVector() && 13221 RHS.getValueType().is64BitVector() && 13222 "unexpected shape for long operation"); 13223 13224 // Either node could be a DUP, but it's not worth doing both of them (you'd 13225 // just as well use the non-high version) so look for a corresponding extract 13226 // operation on the other "wing". 13227 if (isEssentiallyExtractHighSubvector(LHS)) { 13228 RHS = tryExtendDUPToExtractHigh(RHS, DAG); 13229 if (!RHS.getNode()) 13230 return SDValue(); 13231 } else if (isEssentiallyExtractHighSubvector(RHS)) { 13232 LHS = tryExtendDUPToExtractHigh(LHS, DAG); 13233 if (!LHS.getNode()) 13234 return SDValue(); 13235 } 13236 13237 if (IID == Intrinsic::not_intrinsic) 13238 return DAG.getNode(N->getOpcode(), SDLoc(N), N->getValueType(0), LHS, RHS); 13239 13240 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, SDLoc(N), N->getValueType(0), 13241 N->getOperand(0), LHS, RHS); 13242 } 13243 13244 static SDValue tryCombineShiftImm(unsigned IID, SDNode *N, SelectionDAG &DAG) { 13245 MVT ElemTy = N->getSimpleValueType(0).getScalarType(); 13246 unsigned ElemBits = ElemTy.getSizeInBits(); 13247 13248 int64_t ShiftAmount; 13249 if (BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(N->getOperand(2))) { 13250 APInt SplatValue, SplatUndef; 13251 unsigned SplatBitSize; 13252 bool HasAnyUndefs; 13253 if (!BVN->isConstantSplat(SplatValue, SplatUndef, SplatBitSize, 13254 HasAnyUndefs, ElemBits) || 13255 SplatBitSize != ElemBits) 13256 return SDValue(); 13257 13258 ShiftAmount = SplatValue.getSExtValue(); 13259 } else if (ConstantSDNode *CVN = dyn_cast<ConstantSDNode>(N->getOperand(2))) { 13260 ShiftAmount = CVN->getSExtValue(); 13261 } else 13262 return SDValue(); 13263 13264 unsigned Opcode; 13265 bool IsRightShift; 13266 switch (IID) { 13267 default: 13268 llvm_unreachable("Unknown shift intrinsic"); 13269 case Intrinsic::aarch64_neon_sqshl: 13270 Opcode = AArch64ISD::SQSHL_I; 13271 IsRightShift = false; 13272 break; 13273 case Intrinsic::aarch64_neon_uqshl: 13274 Opcode = AArch64ISD::UQSHL_I; 13275 IsRightShift = false; 13276 break; 13277 case Intrinsic::aarch64_neon_srshl: 13278 Opcode = AArch64ISD::SRSHR_I; 13279 IsRightShift = true; 13280 break; 13281 case Intrinsic::aarch64_neon_urshl: 13282 Opcode = AArch64ISD::URSHR_I; 13283 IsRightShift = true; 13284 break; 13285 case Intrinsic::aarch64_neon_sqshlu: 13286 Opcode = AArch64ISD::SQSHLU_I; 13287 IsRightShift = false; 13288 break; 13289 case Intrinsic::aarch64_neon_sshl: 13290 case Intrinsic::aarch64_neon_ushl: 13291 // For positive shift amounts we can use SHL, as ushl/sshl perform a regular 13292 // left shift for positive shift amounts. Below, we only replace the current 13293 // node with VSHL, if this condition is met. 13294 Opcode = AArch64ISD::VSHL; 13295 IsRightShift = false; 13296 break; 13297 } 13298 13299 if (IsRightShift && ShiftAmount <= -1 && ShiftAmount >= -(int)ElemBits) { 13300 SDLoc dl(N); 13301 return DAG.getNode(Opcode, dl, N->getValueType(0), N->getOperand(1), 13302 DAG.getConstant(-ShiftAmount, dl, MVT::i32)); 13303 } else if (!IsRightShift && ShiftAmount >= 0 && ShiftAmount < ElemBits) { 13304 SDLoc dl(N); 13305 return DAG.getNode(Opcode, dl, N->getValueType(0), N->getOperand(1), 13306 DAG.getConstant(ShiftAmount, dl, MVT::i32)); 13307 } 13308 13309 return SDValue(); 13310 } 13311 13312 // The CRC32[BH] instructions ignore the high bits of their data operand. Since 13313 // the intrinsics must be legal and take an i32, this means there's almost 13314 // certainly going to be a zext in the DAG which we can eliminate. 13315 static SDValue tryCombineCRC32(unsigned Mask, SDNode *N, SelectionDAG &DAG) { 13316 SDValue AndN = N->getOperand(2); 13317 if (AndN.getOpcode() != ISD::AND) 13318 return SDValue(); 13319 13320 ConstantSDNode *CMask = dyn_cast<ConstantSDNode>(AndN.getOperand(1)); 13321 if (!CMask || CMask->getZExtValue() != Mask) 13322 return SDValue(); 13323 13324 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, SDLoc(N), MVT::i32, 13325 N->getOperand(0), N->getOperand(1), AndN.getOperand(0)); 13326 } 13327 13328 static SDValue combineAcrossLanesIntrinsic(unsigned Opc, SDNode *N, 13329 SelectionDAG &DAG) { 13330 SDLoc dl(N); 13331 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, N->getValueType(0), 13332 DAG.getNode(Opc, dl, 13333 N->getOperand(1).getSimpleValueType(), 13334 N->getOperand(1)), 13335 DAG.getConstant(0, dl, MVT::i64)); 13336 } 13337 13338 static SDValue LowerSVEIntrinsicIndex(SDNode *N, SelectionDAG &DAG) { 13339 SDLoc DL(N); 13340 SDValue Op1 = N->getOperand(1); 13341 SDValue Op2 = N->getOperand(2); 13342 EVT ScalarTy = Op1.getValueType(); 13343 13344 if ((ScalarTy == MVT::i8) || (ScalarTy == MVT::i16)) { 13345 Op1 = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i32, Op1); 13346 Op2 = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i32, Op2); 13347 } 13348 13349 return DAG.getNode(AArch64ISD::INDEX_VECTOR, DL, N->getValueType(0), 13350 Op1, Op2); 13351 } 13352 13353 static SDValue LowerSVEIntrinsicDUP(SDNode *N, SelectionDAG &DAG) { 13354 SDLoc dl(N); 13355 SDValue Scalar = N->getOperand(3); 13356 EVT ScalarTy = Scalar.getValueType(); 13357 13358 if ((ScalarTy == MVT::i8) || (ScalarTy == MVT::i16)) 13359 Scalar = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, Scalar); 13360 13361 SDValue Passthru = N->getOperand(1); 13362 SDValue Pred = N->getOperand(2); 13363 return DAG.getNode(AArch64ISD::DUP_MERGE_PASSTHRU, dl, N->getValueType(0), 13364 Pred, Scalar, Passthru); 13365 } 13366 13367 static SDValue LowerSVEIntrinsicEXT(SDNode *N, SelectionDAG &DAG) { 13368 SDLoc dl(N); 13369 LLVMContext &Ctx = *DAG.getContext(); 13370 EVT VT = N->getValueType(0); 13371 13372 assert(VT.isScalableVector() && "Expected a scalable vector."); 13373 13374 // Current lowering only supports the SVE-ACLE types. 13375 if (VT.getSizeInBits().getKnownMinSize() != AArch64::SVEBitsPerBlock) 13376 return SDValue(); 13377 13378 unsigned ElemSize = VT.getVectorElementType().getSizeInBits() / 8; 13379 unsigned ByteSize = VT.getSizeInBits().getKnownMinSize() / 8; 13380 EVT ByteVT = 13381 EVT::getVectorVT(Ctx, MVT::i8, ElementCount::getScalable(ByteSize)); 13382 13383 // Convert everything to the domain of EXT (i.e bytes). 13384 SDValue Op0 = DAG.getNode(ISD::BITCAST, dl, ByteVT, N->getOperand(1)); 13385 SDValue Op1 = DAG.getNode(ISD::BITCAST, dl, ByteVT, N->getOperand(2)); 13386 SDValue Op2 = DAG.getNode(ISD::MUL, dl, MVT::i32, N->getOperand(3), 13387 DAG.getConstant(ElemSize, dl, MVT::i32)); 13388 13389 SDValue EXT = DAG.getNode(AArch64ISD::EXT, dl, ByteVT, Op0, Op1, Op2); 13390 return DAG.getNode(ISD::BITCAST, dl, VT, EXT); 13391 } 13392 13393 static SDValue tryConvertSVEWideCompare(SDNode *N, ISD::CondCode CC, 13394 TargetLowering::DAGCombinerInfo &DCI, 13395 SelectionDAG &DAG) { 13396 if (DCI.isBeforeLegalize()) 13397 return SDValue(); 13398 13399 SDValue Comparator = N->getOperand(3); 13400 if (Comparator.getOpcode() == AArch64ISD::DUP || 13401 Comparator.getOpcode() == ISD::SPLAT_VECTOR) { 13402 unsigned IID = getIntrinsicID(N); 13403 EVT VT = N->getValueType(0); 13404 EVT CmpVT = N->getOperand(2).getValueType(); 13405 SDValue Pred = N->getOperand(1); 13406 SDValue Imm; 13407 SDLoc DL(N); 13408 13409 switch (IID) { 13410 default: 13411 llvm_unreachable("Called with wrong intrinsic!"); 13412 break; 13413 13414 // Signed comparisons 13415 case Intrinsic::aarch64_sve_cmpeq_wide: 13416 case Intrinsic::aarch64_sve_cmpne_wide: 13417 case Intrinsic::aarch64_sve_cmpge_wide: 13418 case Intrinsic::aarch64_sve_cmpgt_wide: 13419 case Intrinsic::aarch64_sve_cmplt_wide: 13420 case Intrinsic::aarch64_sve_cmple_wide: { 13421 if (auto *CN = dyn_cast<ConstantSDNode>(Comparator.getOperand(0))) { 13422 int64_t ImmVal = CN->getSExtValue(); 13423 if (ImmVal >= -16 && ImmVal <= 15) 13424 Imm = DAG.getConstant(ImmVal, DL, MVT::i32); 13425 else 13426 return SDValue(); 13427 } 13428 break; 13429 } 13430 // Unsigned comparisons 13431 case Intrinsic::aarch64_sve_cmphs_wide: 13432 case Intrinsic::aarch64_sve_cmphi_wide: 13433 case Intrinsic::aarch64_sve_cmplo_wide: 13434 case Intrinsic::aarch64_sve_cmpls_wide: { 13435 if (auto *CN = dyn_cast<ConstantSDNode>(Comparator.getOperand(0))) { 13436 uint64_t ImmVal = CN->getZExtValue(); 13437 if (ImmVal <= 127) 13438 Imm = DAG.getConstant(ImmVal, DL, MVT::i32); 13439 else 13440 return SDValue(); 13441 } 13442 break; 13443 } 13444 } 13445 13446 if (!Imm) 13447 return SDValue(); 13448 13449 SDValue Splat = DAG.getNode(ISD::SPLAT_VECTOR, DL, CmpVT, Imm); 13450 return DAG.getNode(AArch64ISD::SETCC_MERGE_ZERO, DL, VT, Pred, 13451 N->getOperand(2), Splat, DAG.getCondCode(CC)); 13452 } 13453 13454 return SDValue(); 13455 } 13456 13457 static SDValue getPTest(SelectionDAG &DAG, EVT VT, SDValue Pg, SDValue Op, 13458 AArch64CC::CondCode Cond) { 13459 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 13460 13461 SDLoc DL(Op); 13462 assert(Op.getValueType().isScalableVector() && 13463 TLI.isTypeLegal(Op.getValueType()) && 13464 "Expected legal scalable vector type!"); 13465 13466 // Ensure target specific opcodes are using legal type. 13467 EVT OutVT = TLI.getTypeToTransformTo(*DAG.getContext(), VT); 13468 SDValue TVal = DAG.getConstant(1, DL, OutVT); 13469 SDValue FVal = DAG.getConstant(0, DL, OutVT); 13470 13471 // Set condition code (CC) flags. 13472 SDValue Test = DAG.getNode(AArch64ISD::PTEST, DL, MVT::Other, Pg, Op); 13473 13474 // Convert CC to integer based on requested condition. 13475 // NOTE: Cond is inverted to promote CSEL's removal when it feeds a compare. 13476 SDValue CC = DAG.getConstant(getInvertedCondCode(Cond), DL, MVT::i32); 13477 SDValue Res = DAG.getNode(AArch64ISD::CSEL, DL, OutVT, FVal, TVal, CC, Test); 13478 return DAG.getZExtOrTrunc(Res, DL, VT); 13479 } 13480 13481 static SDValue combineSVEReductionInt(SDNode *N, unsigned Opc, 13482 SelectionDAG &DAG) { 13483 SDLoc DL(N); 13484 13485 SDValue Pred = N->getOperand(1); 13486 SDValue VecToReduce = N->getOperand(2); 13487 13488 // NOTE: The integer reduction's result type is not always linked to the 13489 // operand's element type so we construct it from the intrinsic's result type. 13490 EVT ReduceVT = getPackedSVEVectorVT(N->getValueType(0)); 13491 SDValue Reduce = DAG.getNode(Opc, DL, ReduceVT, Pred, VecToReduce); 13492 13493 // SVE reductions set the whole vector register with the first element 13494 // containing the reduction result, which we'll now extract. 13495 SDValue Zero = DAG.getConstant(0, DL, MVT::i64); 13496 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, N->getValueType(0), Reduce, 13497 Zero); 13498 } 13499 13500 static SDValue combineSVEReductionFP(SDNode *N, unsigned Opc, 13501 SelectionDAG &DAG) { 13502 SDLoc DL(N); 13503 13504 SDValue Pred = N->getOperand(1); 13505 SDValue VecToReduce = N->getOperand(2); 13506 13507 EVT ReduceVT = VecToReduce.getValueType(); 13508 SDValue Reduce = DAG.getNode(Opc, DL, ReduceVT, Pred, VecToReduce); 13509 13510 // SVE reductions set the whole vector register with the first element 13511 // containing the reduction result, which we'll now extract. 13512 SDValue Zero = DAG.getConstant(0, DL, MVT::i64); 13513 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, N->getValueType(0), Reduce, 13514 Zero); 13515 } 13516 13517 static SDValue combineSVEReductionOrderedFP(SDNode *N, unsigned Opc, 13518 SelectionDAG &DAG) { 13519 SDLoc DL(N); 13520 13521 SDValue Pred = N->getOperand(1); 13522 SDValue InitVal = N->getOperand(2); 13523 SDValue VecToReduce = N->getOperand(3); 13524 EVT ReduceVT = VecToReduce.getValueType(); 13525 13526 // Ordered reductions use the first lane of the result vector as the 13527 // reduction's initial value. 13528 SDValue Zero = DAG.getConstant(0, DL, MVT::i64); 13529 InitVal = DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, ReduceVT, 13530 DAG.getUNDEF(ReduceVT), InitVal, Zero); 13531 13532 SDValue Reduce = DAG.getNode(Opc, DL, ReduceVT, Pred, InitVal, VecToReduce); 13533 13534 // SVE reductions set the whole vector register with the first element 13535 // containing the reduction result, which we'll now extract. 13536 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, N->getValueType(0), Reduce, 13537 Zero); 13538 } 13539 13540 // If a merged operation has no inactive lanes we can relax it to a predicated 13541 // or unpredicated operation, which potentially allows better isel (perhaps 13542 // using immediate forms) or relaxing register reuse requirements. 13543 static SDValue convertMergedOpToPredOp(SDNode *N, unsigned PredOpc, 13544 SelectionDAG &DAG) { 13545 assert(N->getOpcode() == ISD::INTRINSIC_WO_CHAIN && "Expected intrinsic!"); 13546 assert(N->getNumOperands() == 4 && "Expected 3 operand intrinsic!"); 13547 SDValue Pg = N->getOperand(1); 13548 13549 // ISD way to specify an all active predicate. 13550 if ((Pg.getOpcode() == AArch64ISD::PTRUE) && 13551 (Pg.getConstantOperandVal(0) == AArch64SVEPredPattern::all)) 13552 return DAG.getNode(PredOpc, SDLoc(N), N->getValueType(0), Pg, 13553 N->getOperand(2), N->getOperand(3)); 13554 13555 // FUTURE: SplatVector(true) 13556 return SDValue(); 13557 } 13558 13559 static SDValue performIntrinsicCombine(SDNode *N, 13560 TargetLowering::DAGCombinerInfo &DCI, 13561 const AArch64Subtarget *Subtarget) { 13562 SelectionDAG &DAG = DCI.DAG; 13563 unsigned IID = getIntrinsicID(N); 13564 switch (IID) { 13565 default: 13566 break; 13567 case Intrinsic::aarch64_neon_vcvtfxs2fp: 13568 case Intrinsic::aarch64_neon_vcvtfxu2fp: 13569 return tryCombineFixedPointConvert(N, DCI, DAG); 13570 case Intrinsic::aarch64_neon_saddv: 13571 return combineAcrossLanesIntrinsic(AArch64ISD::SADDV, N, DAG); 13572 case Intrinsic::aarch64_neon_uaddv: 13573 return combineAcrossLanesIntrinsic(AArch64ISD::UADDV, N, DAG); 13574 case Intrinsic::aarch64_neon_sminv: 13575 return combineAcrossLanesIntrinsic(AArch64ISD::SMINV, N, DAG); 13576 case Intrinsic::aarch64_neon_uminv: 13577 return combineAcrossLanesIntrinsic(AArch64ISD::UMINV, N, DAG); 13578 case Intrinsic::aarch64_neon_smaxv: 13579 return combineAcrossLanesIntrinsic(AArch64ISD::SMAXV, N, DAG); 13580 case Intrinsic::aarch64_neon_umaxv: 13581 return combineAcrossLanesIntrinsic(AArch64ISD::UMAXV, N, DAG); 13582 case Intrinsic::aarch64_neon_fmax: 13583 return DAG.getNode(ISD::FMAXIMUM, SDLoc(N), N->getValueType(0), 13584 N->getOperand(1), N->getOperand(2)); 13585 case Intrinsic::aarch64_neon_fmin: 13586 return DAG.getNode(ISD::FMINIMUM, SDLoc(N), N->getValueType(0), 13587 N->getOperand(1), N->getOperand(2)); 13588 case Intrinsic::aarch64_neon_fmaxnm: 13589 return DAG.getNode(ISD::FMAXNUM, SDLoc(N), N->getValueType(0), 13590 N->getOperand(1), N->getOperand(2)); 13591 case Intrinsic::aarch64_neon_fminnm: 13592 return DAG.getNode(ISD::FMINNUM, SDLoc(N), N->getValueType(0), 13593 N->getOperand(1), N->getOperand(2)); 13594 case Intrinsic::aarch64_neon_smull: 13595 case Intrinsic::aarch64_neon_umull: 13596 case Intrinsic::aarch64_neon_pmull: 13597 case Intrinsic::aarch64_neon_sqdmull: 13598 return tryCombineLongOpWithDup(IID, N, DCI, DAG); 13599 case Intrinsic::aarch64_neon_sqshl: 13600 case Intrinsic::aarch64_neon_uqshl: 13601 case Intrinsic::aarch64_neon_sqshlu: 13602 case Intrinsic::aarch64_neon_srshl: 13603 case Intrinsic::aarch64_neon_urshl: 13604 case Intrinsic::aarch64_neon_sshl: 13605 case Intrinsic::aarch64_neon_ushl: 13606 return tryCombineShiftImm(IID, N, DAG); 13607 case Intrinsic::aarch64_crc32b: 13608 case Intrinsic::aarch64_crc32cb: 13609 return tryCombineCRC32(0xff, N, DAG); 13610 case Intrinsic::aarch64_crc32h: 13611 case Intrinsic::aarch64_crc32ch: 13612 return tryCombineCRC32(0xffff, N, DAG); 13613 case Intrinsic::aarch64_sve_saddv: 13614 // There is no i64 version of SADDV because the sign is irrelevant. 13615 if (N->getOperand(2)->getValueType(0).getVectorElementType() == MVT::i64) 13616 return combineSVEReductionInt(N, AArch64ISD::UADDV_PRED, DAG); 13617 else 13618 return combineSVEReductionInt(N, AArch64ISD::SADDV_PRED, DAG); 13619 case Intrinsic::aarch64_sve_uaddv: 13620 return combineSVEReductionInt(N, AArch64ISD::UADDV_PRED, DAG); 13621 case Intrinsic::aarch64_sve_smaxv: 13622 return combineSVEReductionInt(N, AArch64ISD::SMAXV_PRED, DAG); 13623 case Intrinsic::aarch64_sve_umaxv: 13624 return combineSVEReductionInt(N, AArch64ISD::UMAXV_PRED, DAG); 13625 case Intrinsic::aarch64_sve_sminv: 13626 return combineSVEReductionInt(N, AArch64ISD::SMINV_PRED, DAG); 13627 case Intrinsic::aarch64_sve_uminv: 13628 return combineSVEReductionInt(N, AArch64ISD::UMINV_PRED, DAG); 13629 case Intrinsic::aarch64_sve_orv: 13630 return combineSVEReductionInt(N, AArch64ISD::ORV_PRED, DAG); 13631 case Intrinsic::aarch64_sve_eorv: 13632 return combineSVEReductionInt(N, AArch64ISD::EORV_PRED, DAG); 13633 case Intrinsic::aarch64_sve_andv: 13634 return combineSVEReductionInt(N, AArch64ISD::ANDV_PRED, DAG); 13635 case Intrinsic::aarch64_sve_index: 13636 return LowerSVEIntrinsicIndex(N, DAG); 13637 case Intrinsic::aarch64_sve_dup: 13638 return LowerSVEIntrinsicDUP(N, DAG); 13639 case Intrinsic::aarch64_sve_dup_x: 13640 return DAG.getNode(ISD::SPLAT_VECTOR, SDLoc(N), N->getValueType(0), 13641 N->getOperand(1)); 13642 case Intrinsic::aarch64_sve_ext: 13643 return LowerSVEIntrinsicEXT(N, DAG); 13644 case Intrinsic::aarch64_sve_smin: 13645 return convertMergedOpToPredOp(N, AArch64ISD::SMIN_PRED, DAG); 13646 case Intrinsic::aarch64_sve_umin: 13647 return convertMergedOpToPredOp(N, AArch64ISD::UMIN_PRED, DAG); 13648 case Intrinsic::aarch64_sve_smax: 13649 return convertMergedOpToPredOp(N, AArch64ISD::SMAX_PRED, DAG); 13650 case Intrinsic::aarch64_sve_umax: 13651 return convertMergedOpToPredOp(N, AArch64ISD::UMAX_PRED, DAG); 13652 case Intrinsic::aarch64_sve_lsl: 13653 return convertMergedOpToPredOp(N, AArch64ISD::SHL_PRED, DAG); 13654 case Intrinsic::aarch64_sve_lsr: 13655 return convertMergedOpToPredOp(N, AArch64ISD::SRL_PRED, DAG); 13656 case Intrinsic::aarch64_sve_asr: 13657 return convertMergedOpToPredOp(N, AArch64ISD::SRA_PRED, DAG); 13658 case Intrinsic::aarch64_sve_cmphs: 13659 if (!N->getOperand(2).getValueType().isFloatingPoint()) 13660 return DAG.getNode(AArch64ISD::SETCC_MERGE_ZERO, SDLoc(N), 13661 N->getValueType(0), N->getOperand(1), N->getOperand(2), 13662 N->getOperand(3), DAG.getCondCode(ISD::SETUGE)); 13663 break; 13664 case Intrinsic::aarch64_sve_cmphi: 13665 if (!N->getOperand(2).getValueType().isFloatingPoint()) 13666 return DAG.getNode(AArch64ISD::SETCC_MERGE_ZERO, SDLoc(N), 13667 N->getValueType(0), N->getOperand(1), N->getOperand(2), 13668 N->getOperand(3), DAG.getCondCode(ISD::SETUGT)); 13669 break; 13670 case Intrinsic::aarch64_sve_cmpge: 13671 if (!N->getOperand(2).getValueType().isFloatingPoint()) 13672 return DAG.getNode(AArch64ISD::SETCC_MERGE_ZERO, SDLoc(N), 13673 N->getValueType(0), N->getOperand(1), N->getOperand(2), 13674 N->getOperand(3), DAG.getCondCode(ISD::SETGE)); 13675 break; 13676 case Intrinsic::aarch64_sve_cmpgt: 13677 if (!N->getOperand(2).getValueType().isFloatingPoint()) 13678 return DAG.getNode(AArch64ISD::SETCC_MERGE_ZERO, SDLoc(N), 13679 N->getValueType(0), N->getOperand(1), N->getOperand(2), 13680 N->getOperand(3), DAG.getCondCode(ISD::SETGT)); 13681 break; 13682 case Intrinsic::aarch64_sve_cmpeq: 13683 if (!N->getOperand(2).getValueType().isFloatingPoint()) 13684 return DAG.getNode(AArch64ISD::SETCC_MERGE_ZERO, SDLoc(N), 13685 N->getValueType(0), N->getOperand(1), N->getOperand(2), 13686 N->getOperand(3), DAG.getCondCode(ISD::SETEQ)); 13687 break; 13688 case Intrinsic::aarch64_sve_cmpne: 13689 if (!N->getOperand(2).getValueType().isFloatingPoint()) 13690 return DAG.getNode(AArch64ISD::SETCC_MERGE_ZERO, SDLoc(N), 13691 N->getValueType(0), N->getOperand(1), N->getOperand(2), 13692 N->getOperand(3), DAG.getCondCode(ISD::SETNE)); 13693 break; 13694 case Intrinsic::aarch64_sve_fadda: 13695 return combineSVEReductionOrderedFP(N, AArch64ISD::FADDA_PRED, DAG); 13696 case Intrinsic::aarch64_sve_faddv: 13697 return combineSVEReductionFP(N, AArch64ISD::FADDV_PRED, DAG); 13698 case Intrinsic::aarch64_sve_fmaxnmv: 13699 return combineSVEReductionFP(N, AArch64ISD::FMAXNMV_PRED, DAG); 13700 case Intrinsic::aarch64_sve_fmaxv: 13701 return combineSVEReductionFP(N, AArch64ISD::FMAXV_PRED, DAG); 13702 case Intrinsic::aarch64_sve_fminnmv: 13703 return combineSVEReductionFP(N, AArch64ISD::FMINNMV_PRED, DAG); 13704 case Intrinsic::aarch64_sve_fminv: 13705 return combineSVEReductionFP(N, AArch64ISD::FMINV_PRED, DAG); 13706 case Intrinsic::aarch64_sve_sel: 13707 return DAG.getNode(ISD::VSELECT, SDLoc(N), N->getValueType(0), 13708 N->getOperand(1), N->getOperand(2), N->getOperand(3)); 13709 case Intrinsic::aarch64_sve_cmpeq_wide: 13710 return tryConvertSVEWideCompare(N, ISD::SETEQ, DCI, DAG); 13711 case Intrinsic::aarch64_sve_cmpne_wide: 13712 return tryConvertSVEWideCompare(N, ISD::SETNE, DCI, DAG); 13713 case Intrinsic::aarch64_sve_cmpge_wide: 13714 return tryConvertSVEWideCompare(N, ISD::SETGE, DCI, DAG); 13715 case Intrinsic::aarch64_sve_cmpgt_wide: 13716 return tryConvertSVEWideCompare(N, ISD::SETGT, DCI, DAG); 13717 case Intrinsic::aarch64_sve_cmplt_wide: 13718 return tryConvertSVEWideCompare(N, ISD::SETLT, DCI, DAG); 13719 case Intrinsic::aarch64_sve_cmple_wide: 13720 return tryConvertSVEWideCompare(N, ISD::SETLE, DCI, DAG); 13721 case Intrinsic::aarch64_sve_cmphs_wide: 13722 return tryConvertSVEWideCompare(N, ISD::SETUGE, DCI, DAG); 13723 case Intrinsic::aarch64_sve_cmphi_wide: 13724 return tryConvertSVEWideCompare(N, ISD::SETUGT, DCI, DAG); 13725 case Intrinsic::aarch64_sve_cmplo_wide: 13726 return tryConvertSVEWideCompare(N, ISD::SETULT, DCI, DAG); 13727 case Intrinsic::aarch64_sve_cmpls_wide: 13728 return tryConvertSVEWideCompare(N, ISD::SETULE, DCI, DAG); 13729 case Intrinsic::aarch64_sve_ptest_any: 13730 return getPTest(DAG, N->getValueType(0), N->getOperand(1), N->getOperand(2), 13731 AArch64CC::ANY_ACTIVE); 13732 case Intrinsic::aarch64_sve_ptest_first: 13733 return getPTest(DAG, N->getValueType(0), N->getOperand(1), N->getOperand(2), 13734 AArch64CC::FIRST_ACTIVE); 13735 case Intrinsic::aarch64_sve_ptest_last: 13736 return getPTest(DAG, N->getValueType(0), N->getOperand(1), N->getOperand(2), 13737 AArch64CC::LAST_ACTIVE); 13738 } 13739 return SDValue(); 13740 } 13741 13742 static SDValue performExtendCombine(SDNode *N, 13743 TargetLowering::DAGCombinerInfo &DCI, 13744 SelectionDAG &DAG) { 13745 // If we see something like (zext (sabd (extract_high ...), (DUP ...))) then 13746 // we can convert that DUP into another extract_high (of a bigger DUP), which 13747 // helps the backend to decide that an sabdl2 would be useful, saving a real 13748 // extract_high operation. 13749 if (!DCI.isBeforeLegalizeOps() && N->getOpcode() == ISD::ZERO_EXTEND && 13750 (N->getOperand(0).getOpcode() == AArch64ISD::UABD || 13751 N->getOperand(0).getOpcode() == AArch64ISD::SABD)) { 13752 SDNode *ABDNode = N->getOperand(0).getNode(); 13753 SDValue NewABD = 13754 tryCombineLongOpWithDup(Intrinsic::not_intrinsic, ABDNode, DCI, DAG); 13755 if (!NewABD.getNode()) 13756 return SDValue(); 13757 13758 return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), N->getValueType(0), NewABD); 13759 } 13760 13761 // This is effectively a custom type legalization for AArch64. 13762 // 13763 // Type legalization will split an extend of a small, legal, type to a larger 13764 // illegal type by first splitting the destination type, often creating 13765 // illegal source types, which then get legalized in isel-confusing ways, 13766 // leading to really terrible codegen. E.g., 13767 // %result = v8i32 sext v8i8 %value 13768 // becomes 13769 // %losrc = extract_subreg %value, ... 13770 // %hisrc = extract_subreg %value, ... 13771 // %lo = v4i32 sext v4i8 %losrc 13772 // %hi = v4i32 sext v4i8 %hisrc 13773 // Things go rapidly downhill from there. 13774 // 13775 // For AArch64, the [sz]ext vector instructions can only go up one element 13776 // size, so we can, e.g., extend from i8 to i16, but to go from i8 to i32 13777 // take two instructions. 13778 // 13779 // This implies that the most efficient way to do the extend from v8i8 13780 // to two v4i32 values is to first extend the v8i8 to v8i16, then do 13781 // the normal splitting to happen for the v8i16->v8i32. 13782 13783 // This is pre-legalization to catch some cases where the default 13784 // type legalization will create ill-tempered code. 13785 if (!DCI.isBeforeLegalizeOps()) 13786 return SDValue(); 13787 13788 // We're only interested in cleaning things up for non-legal vector types 13789 // here. If both the source and destination are legal, things will just 13790 // work naturally without any fiddling. 13791 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 13792 EVT ResVT = N->getValueType(0); 13793 if (!ResVT.isVector() || TLI.isTypeLegal(ResVT)) 13794 return SDValue(); 13795 // If the vector type isn't a simple VT, it's beyond the scope of what 13796 // we're worried about here. Let legalization do its thing and hope for 13797 // the best. 13798 SDValue Src = N->getOperand(0); 13799 EVT SrcVT = Src->getValueType(0); 13800 if (!ResVT.isSimple() || !SrcVT.isSimple()) 13801 return SDValue(); 13802 13803 // If the source VT is a 64-bit fixed or scalable vector, we can play games 13804 // and get the better results we want. 13805 if (SrcVT.getSizeInBits().getKnownMinSize() != 64) 13806 return SDValue(); 13807 13808 unsigned SrcEltSize = SrcVT.getScalarSizeInBits(); 13809 ElementCount SrcEC = SrcVT.getVectorElementCount(); 13810 SrcVT = MVT::getVectorVT(MVT::getIntegerVT(SrcEltSize * 2), SrcEC); 13811 SDLoc DL(N); 13812 Src = DAG.getNode(N->getOpcode(), DL, SrcVT, Src); 13813 13814 // Now split the rest of the operation into two halves, each with a 64 13815 // bit source. 13816 EVT LoVT, HiVT; 13817 SDValue Lo, Hi; 13818 LoVT = HiVT = ResVT.getHalfNumVectorElementsVT(*DAG.getContext()); 13819 13820 EVT InNVT = EVT::getVectorVT(*DAG.getContext(), SrcVT.getVectorElementType(), 13821 LoVT.getVectorElementCount()); 13822 Lo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, InNVT, Src, 13823 DAG.getConstant(0, DL, MVT::i64)); 13824 Hi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, InNVT, Src, 13825 DAG.getConstant(InNVT.getVectorMinNumElements(), DL, MVT::i64)); 13826 Lo = DAG.getNode(N->getOpcode(), DL, LoVT, Lo); 13827 Hi = DAG.getNode(N->getOpcode(), DL, HiVT, Hi); 13828 13829 // Now combine the parts back together so we still have a single result 13830 // like the combiner expects. 13831 return DAG.getNode(ISD::CONCAT_VECTORS, DL, ResVT, Lo, Hi); 13832 } 13833 13834 static SDValue splitStoreSplat(SelectionDAG &DAG, StoreSDNode &St, 13835 SDValue SplatVal, unsigned NumVecElts) { 13836 assert(!St.isTruncatingStore() && "cannot split truncating vector store"); 13837 unsigned OrigAlignment = St.getAlignment(); 13838 unsigned EltOffset = SplatVal.getValueType().getSizeInBits() / 8; 13839 13840 // Create scalar stores. This is at least as good as the code sequence for a 13841 // split unaligned store which is a dup.s, ext.b, and two stores. 13842 // Most of the time the three stores should be replaced by store pair 13843 // instructions (stp). 13844 SDLoc DL(&St); 13845 SDValue BasePtr = St.getBasePtr(); 13846 uint64_t BaseOffset = 0; 13847 13848 const MachinePointerInfo &PtrInfo = St.getPointerInfo(); 13849 SDValue NewST1 = 13850 DAG.getStore(St.getChain(), DL, SplatVal, BasePtr, PtrInfo, 13851 OrigAlignment, St.getMemOperand()->getFlags()); 13852 13853 // As this in ISel, we will not merge this add which may degrade results. 13854 if (BasePtr->getOpcode() == ISD::ADD && 13855 isa<ConstantSDNode>(BasePtr->getOperand(1))) { 13856 BaseOffset = cast<ConstantSDNode>(BasePtr->getOperand(1))->getSExtValue(); 13857 BasePtr = BasePtr->getOperand(0); 13858 } 13859 13860 unsigned Offset = EltOffset; 13861 while (--NumVecElts) { 13862 unsigned Alignment = MinAlign(OrigAlignment, Offset); 13863 SDValue OffsetPtr = 13864 DAG.getNode(ISD::ADD, DL, MVT::i64, BasePtr, 13865 DAG.getConstant(BaseOffset + Offset, DL, MVT::i64)); 13866 NewST1 = DAG.getStore(NewST1.getValue(0), DL, SplatVal, OffsetPtr, 13867 PtrInfo.getWithOffset(Offset), Alignment, 13868 St.getMemOperand()->getFlags()); 13869 Offset += EltOffset; 13870 } 13871 return NewST1; 13872 } 13873 13874 // Returns an SVE type that ContentTy can be trivially sign or zero extended 13875 // into. 13876 static MVT getSVEContainerType(EVT ContentTy) { 13877 assert(ContentTy.isSimple() && "No SVE containers for extended types"); 13878 13879 switch (ContentTy.getSimpleVT().SimpleTy) { 13880 default: 13881 llvm_unreachable("No known SVE container for this MVT type"); 13882 case MVT::nxv2i8: 13883 case MVT::nxv2i16: 13884 case MVT::nxv2i32: 13885 case MVT::nxv2i64: 13886 case MVT::nxv2f32: 13887 case MVT::nxv2f64: 13888 return MVT::nxv2i64; 13889 case MVT::nxv4i8: 13890 case MVT::nxv4i16: 13891 case MVT::nxv4i32: 13892 case MVT::nxv4f32: 13893 return MVT::nxv4i32; 13894 case MVT::nxv8i8: 13895 case MVT::nxv8i16: 13896 case MVT::nxv8f16: 13897 case MVT::nxv8bf16: 13898 return MVT::nxv8i16; 13899 case MVT::nxv16i8: 13900 return MVT::nxv16i8; 13901 } 13902 } 13903 13904 static SDValue performLD1Combine(SDNode *N, SelectionDAG &DAG, unsigned Opc) { 13905 SDLoc DL(N); 13906 EVT VT = N->getValueType(0); 13907 13908 if (VT.getSizeInBits().getKnownMinSize() > AArch64::SVEBitsPerBlock) 13909 return SDValue(); 13910 13911 EVT ContainerVT = VT; 13912 if (ContainerVT.isInteger()) 13913 ContainerVT = getSVEContainerType(ContainerVT); 13914 13915 SDVTList VTs = DAG.getVTList(ContainerVT, MVT::Other); 13916 SDValue Ops[] = { N->getOperand(0), // Chain 13917 N->getOperand(2), // Pg 13918 N->getOperand(3), // Base 13919 DAG.getValueType(VT) }; 13920 13921 SDValue Load = DAG.getNode(Opc, DL, VTs, Ops); 13922 SDValue LoadChain = SDValue(Load.getNode(), 1); 13923 13924 if (ContainerVT.isInteger() && (VT != ContainerVT)) 13925 Load = DAG.getNode(ISD::TRUNCATE, DL, VT, Load.getValue(0)); 13926 13927 return DAG.getMergeValues({ Load, LoadChain }, DL); 13928 } 13929 13930 static SDValue performLDNT1Combine(SDNode *N, SelectionDAG &DAG) { 13931 SDLoc DL(N); 13932 EVT VT = N->getValueType(0); 13933 EVT PtrTy = N->getOperand(3).getValueType(); 13934 13935 if (VT == MVT::nxv8bf16 && 13936 !static_cast<const AArch64Subtarget &>(DAG.getSubtarget()).hasBF16()) 13937 return SDValue(); 13938 13939 EVT LoadVT = VT; 13940 if (VT.isFloatingPoint()) 13941 LoadVT = VT.changeTypeToInteger(); 13942 13943 auto *MINode = cast<MemIntrinsicSDNode>(N); 13944 SDValue PassThru = DAG.getConstant(0, DL, LoadVT); 13945 SDValue L = DAG.getMaskedLoad(LoadVT, DL, MINode->getChain(), 13946 MINode->getOperand(3), DAG.getUNDEF(PtrTy), 13947 MINode->getOperand(2), PassThru, 13948 MINode->getMemoryVT(), MINode->getMemOperand(), 13949 ISD::UNINDEXED, ISD::NON_EXTLOAD, false); 13950 13951 if (VT.isFloatingPoint()) { 13952 SDValue Ops[] = { DAG.getNode(ISD::BITCAST, DL, VT, L), L.getValue(1) }; 13953 return DAG.getMergeValues(Ops, DL); 13954 } 13955 13956 return L; 13957 } 13958 13959 template <unsigned Opcode> 13960 static SDValue performLD1ReplicateCombine(SDNode *N, SelectionDAG &DAG) { 13961 static_assert(Opcode == AArch64ISD::LD1RQ_MERGE_ZERO || 13962 Opcode == AArch64ISD::LD1RO_MERGE_ZERO, 13963 "Unsupported opcode."); 13964 SDLoc DL(N); 13965 EVT VT = N->getValueType(0); 13966 if (VT == MVT::nxv8bf16 && 13967 !static_cast<const AArch64Subtarget &>(DAG.getSubtarget()).hasBF16()) 13968 return SDValue(); 13969 13970 EVT LoadVT = VT; 13971 if (VT.isFloatingPoint()) 13972 LoadVT = VT.changeTypeToInteger(); 13973 13974 SDValue Ops[] = {N->getOperand(0), N->getOperand(2), N->getOperand(3)}; 13975 SDValue Load = DAG.getNode(Opcode, DL, {LoadVT, MVT::Other}, Ops); 13976 SDValue LoadChain = SDValue(Load.getNode(), 1); 13977 13978 if (VT.isFloatingPoint()) 13979 Load = DAG.getNode(ISD::BITCAST, DL, VT, Load.getValue(0)); 13980 13981 return DAG.getMergeValues({Load, LoadChain}, DL); 13982 } 13983 13984 static SDValue performST1Combine(SDNode *N, SelectionDAG &DAG) { 13985 SDLoc DL(N); 13986 SDValue Data = N->getOperand(2); 13987 EVT DataVT = Data.getValueType(); 13988 EVT HwSrcVt = getSVEContainerType(DataVT); 13989 SDValue InputVT = DAG.getValueType(DataVT); 13990 13991 if (DataVT == MVT::nxv8bf16 && 13992 !static_cast<const AArch64Subtarget &>(DAG.getSubtarget()).hasBF16()) 13993 return SDValue(); 13994 13995 if (DataVT.isFloatingPoint()) 13996 InputVT = DAG.getValueType(HwSrcVt); 13997 13998 SDValue SrcNew; 13999 if (Data.getValueType().isFloatingPoint()) 14000 SrcNew = DAG.getNode(ISD::BITCAST, DL, HwSrcVt, Data); 14001 else 14002 SrcNew = DAG.getNode(ISD::ANY_EXTEND, DL, HwSrcVt, Data); 14003 14004 SDValue Ops[] = { N->getOperand(0), // Chain 14005 SrcNew, 14006 N->getOperand(4), // Base 14007 N->getOperand(3), // Pg 14008 InputVT 14009 }; 14010 14011 return DAG.getNode(AArch64ISD::ST1_PRED, DL, N->getValueType(0), Ops); 14012 } 14013 14014 static SDValue performSTNT1Combine(SDNode *N, SelectionDAG &DAG) { 14015 SDLoc DL(N); 14016 14017 SDValue Data = N->getOperand(2); 14018 EVT DataVT = Data.getValueType(); 14019 EVT PtrTy = N->getOperand(4).getValueType(); 14020 14021 if (DataVT == MVT::nxv8bf16 && 14022 !static_cast<const AArch64Subtarget &>(DAG.getSubtarget()).hasBF16()) 14023 return SDValue(); 14024 14025 if (DataVT.isFloatingPoint()) 14026 Data = DAG.getNode(ISD::BITCAST, DL, DataVT.changeTypeToInteger(), Data); 14027 14028 auto *MINode = cast<MemIntrinsicSDNode>(N); 14029 return DAG.getMaskedStore(MINode->getChain(), DL, Data, MINode->getOperand(4), 14030 DAG.getUNDEF(PtrTy), MINode->getOperand(3), 14031 MINode->getMemoryVT(), MINode->getMemOperand(), 14032 ISD::UNINDEXED, false, false); 14033 } 14034 14035 /// Replace a splat of zeros to a vector store by scalar stores of WZR/XZR. The 14036 /// load store optimizer pass will merge them to store pair stores. This should 14037 /// be better than a movi to create the vector zero followed by a vector store 14038 /// if the zero constant is not re-used, since one instructions and one register 14039 /// live range will be removed. 14040 /// 14041 /// For example, the final generated code should be: 14042 /// 14043 /// stp xzr, xzr, [x0] 14044 /// 14045 /// instead of: 14046 /// 14047 /// movi v0.2d, #0 14048 /// str q0, [x0] 14049 /// 14050 static SDValue replaceZeroVectorStore(SelectionDAG &DAG, StoreSDNode &St) { 14051 SDValue StVal = St.getValue(); 14052 EVT VT = StVal.getValueType(); 14053 14054 // Avoid scalarizing zero splat stores for scalable vectors. 14055 if (VT.isScalableVector()) 14056 return SDValue(); 14057 14058 // It is beneficial to scalarize a zero splat store for 2 or 3 i64 elements or 14059 // 2, 3 or 4 i32 elements. 14060 int NumVecElts = VT.getVectorNumElements(); 14061 if (!(((NumVecElts == 2 || NumVecElts == 3) && 14062 VT.getVectorElementType().getSizeInBits() == 64) || 14063 ((NumVecElts == 2 || NumVecElts == 3 || NumVecElts == 4) && 14064 VT.getVectorElementType().getSizeInBits() == 32))) 14065 return SDValue(); 14066 14067 if (StVal.getOpcode() != ISD::BUILD_VECTOR) 14068 return SDValue(); 14069 14070 // If the zero constant has more than one use then the vector store could be 14071 // better since the constant mov will be amortized and stp q instructions 14072 // should be able to be formed. 14073 if (!StVal.hasOneUse()) 14074 return SDValue(); 14075 14076 // If the store is truncating then it's going down to i16 or smaller, which 14077 // means it can be implemented in a single store anyway. 14078 if (St.isTruncatingStore()) 14079 return SDValue(); 14080 14081 // If the immediate offset of the address operand is too large for the stp 14082 // instruction, then bail out. 14083 if (DAG.isBaseWithConstantOffset(St.getBasePtr())) { 14084 int64_t Offset = St.getBasePtr()->getConstantOperandVal(1); 14085 if (Offset < -512 || Offset > 504) 14086 return SDValue(); 14087 } 14088 14089 for (int I = 0; I < NumVecElts; ++I) { 14090 SDValue EltVal = StVal.getOperand(I); 14091 if (!isNullConstant(EltVal) && !isNullFPConstant(EltVal)) 14092 return SDValue(); 14093 } 14094 14095 // Use a CopyFromReg WZR/XZR here to prevent 14096 // DAGCombiner::MergeConsecutiveStores from undoing this transformation. 14097 SDLoc DL(&St); 14098 unsigned ZeroReg; 14099 EVT ZeroVT; 14100 if (VT.getVectorElementType().getSizeInBits() == 32) { 14101 ZeroReg = AArch64::WZR; 14102 ZeroVT = MVT::i32; 14103 } else { 14104 ZeroReg = AArch64::XZR; 14105 ZeroVT = MVT::i64; 14106 } 14107 SDValue SplatVal = 14108 DAG.getCopyFromReg(DAG.getEntryNode(), DL, ZeroReg, ZeroVT); 14109 return splitStoreSplat(DAG, St, SplatVal, NumVecElts); 14110 } 14111 14112 /// Replace a splat of a scalar to a vector store by scalar stores of the scalar 14113 /// value. The load store optimizer pass will merge them to store pair stores. 14114 /// This has better performance than a splat of the scalar followed by a split 14115 /// vector store. Even if the stores are not merged it is four stores vs a dup, 14116 /// followed by an ext.b and two stores. 14117 static SDValue replaceSplatVectorStore(SelectionDAG &DAG, StoreSDNode &St) { 14118 SDValue StVal = St.getValue(); 14119 EVT VT = StVal.getValueType(); 14120 14121 // Don't replace floating point stores, they possibly won't be transformed to 14122 // stp because of the store pair suppress pass. 14123 if (VT.isFloatingPoint()) 14124 return SDValue(); 14125 14126 // We can express a splat as store pair(s) for 2 or 4 elements. 14127 unsigned NumVecElts = VT.getVectorNumElements(); 14128 if (NumVecElts != 4 && NumVecElts != 2) 14129 return SDValue(); 14130 14131 // If the store is truncating then it's going down to i16 or smaller, which 14132 // means it can be implemented in a single store anyway. 14133 if (St.isTruncatingStore()) 14134 return SDValue(); 14135 14136 // Check that this is a splat. 14137 // Make sure that each of the relevant vector element locations are inserted 14138 // to, i.e. 0 and 1 for v2i64 and 0, 1, 2, 3 for v4i32. 14139 std::bitset<4> IndexNotInserted((1 << NumVecElts) - 1); 14140 SDValue SplatVal; 14141 for (unsigned I = 0; I < NumVecElts; ++I) { 14142 // Check for insert vector elements. 14143 if (StVal.getOpcode() != ISD::INSERT_VECTOR_ELT) 14144 return SDValue(); 14145 14146 // Check that same value is inserted at each vector element. 14147 if (I == 0) 14148 SplatVal = StVal.getOperand(1); 14149 else if (StVal.getOperand(1) != SplatVal) 14150 return SDValue(); 14151 14152 // Check insert element index. 14153 ConstantSDNode *CIndex = dyn_cast<ConstantSDNode>(StVal.getOperand(2)); 14154 if (!CIndex) 14155 return SDValue(); 14156 uint64_t IndexVal = CIndex->getZExtValue(); 14157 if (IndexVal >= NumVecElts) 14158 return SDValue(); 14159 IndexNotInserted.reset(IndexVal); 14160 14161 StVal = StVal.getOperand(0); 14162 } 14163 // Check that all vector element locations were inserted to. 14164 if (IndexNotInserted.any()) 14165 return SDValue(); 14166 14167 return splitStoreSplat(DAG, St, SplatVal, NumVecElts); 14168 } 14169 14170 static SDValue splitStores(SDNode *N, TargetLowering::DAGCombinerInfo &DCI, 14171 SelectionDAG &DAG, 14172 const AArch64Subtarget *Subtarget) { 14173 14174 StoreSDNode *S = cast<StoreSDNode>(N); 14175 if (S->isVolatile() || S->isIndexed()) 14176 return SDValue(); 14177 14178 SDValue StVal = S->getValue(); 14179 EVT VT = StVal.getValueType(); 14180 14181 if (!VT.isFixedLengthVector()) 14182 return SDValue(); 14183 14184 // If we get a splat of zeros, convert this vector store to a store of 14185 // scalars. They will be merged into store pairs of xzr thereby removing one 14186 // instruction and one register. 14187 if (SDValue ReplacedZeroSplat = replaceZeroVectorStore(DAG, *S)) 14188 return ReplacedZeroSplat; 14189 14190 // FIXME: The logic for deciding if an unaligned store should be split should 14191 // be included in TLI.allowsMisalignedMemoryAccesses(), and there should be 14192 // a call to that function here. 14193 14194 if (!Subtarget->isMisaligned128StoreSlow()) 14195 return SDValue(); 14196 14197 // Don't split at -Oz. 14198 if (DAG.getMachineFunction().getFunction().hasMinSize()) 14199 return SDValue(); 14200 14201 // Don't split v2i64 vectors. Memcpy lowering produces those and splitting 14202 // those up regresses performance on micro-benchmarks and olden/bh. 14203 if (VT.getVectorNumElements() < 2 || VT == MVT::v2i64) 14204 return SDValue(); 14205 14206 // Split unaligned 16B stores. They are terrible for performance. 14207 // Don't split stores with alignment of 1 or 2. Code that uses clang vector 14208 // extensions can use this to mark that it does not want splitting to happen 14209 // (by underspecifying alignment to be 1 or 2). Furthermore, the chance of 14210 // eliminating alignment hazards is only 1 in 8 for alignment of 2. 14211 if (VT.getSizeInBits() != 128 || S->getAlignment() >= 16 || 14212 S->getAlignment() <= 2) 14213 return SDValue(); 14214 14215 // If we get a splat of a scalar convert this vector store to a store of 14216 // scalars. They will be merged into store pairs thereby removing two 14217 // instructions. 14218 if (SDValue ReplacedSplat = replaceSplatVectorStore(DAG, *S)) 14219 return ReplacedSplat; 14220 14221 SDLoc DL(S); 14222 14223 // Split VT into two. 14224 EVT HalfVT = VT.getHalfNumVectorElementsVT(*DAG.getContext()); 14225 unsigned NumElts = HalfVT.getVectorNumElements(); 14226 SDValue SubVector0 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, HalfVT, StVal, 14227 DAG.getConstant(0, DL, MVT::i64)); 14228 SDValue SubVector1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, HalfVT, StVal, 14229 DAG.getConstant(NumElts, DL, MVT::i64)); 14230 SDValue BasePtr = S->getBasePtr(); 14231 SDValue NewST1 = 14232 DAG.getStore(S->getChain(), DL, SubVector0, BasePtr, S->getPointerInfo(), 14233 S->getAlignment(), S->getMemOperand()->getFlags()); 14234 SDValue OffsetPtr = DAG.getNode(ISD::ADD, DL, MVT::i64, BasePtr, 14235 DAG.getConstant(8, DL, MVT::i64)); 14236 return DAG.getStore(NewST1.getValue(0), DL, SubVector1, OffsetPtr, 14237 S->getPointerInfo(), S->getAlignment(), 14238 S->getMemOperand()->getFlags()); 14239 } 14240 14241 static SDValue performUzpCombine(SDNode *N, SelectionDAG &DAG) { 14242 SDLoc DL(N); 14243 SDValue Op0 = N->getOperand(0); 14244 SDValue Op1 = N->getOperand(1); 14245 EVT ResVT = N->getValueType(0); 14246 14247 // uzp1(unpklo(uzp1(x, y)), z) => uzp1(x, z) 14248 if (Op0.getOpcode() == AArch64ISD::UUNPKLO) { 14249 if (Op0.getOperand(0).getOpcode() == AArch64ISD::UZP1) { 14250 SDValue X = Op0.getOperand(0).getOperand(0); 14251 return DAG.getNode(AArch64ISD::UZP1, DL, ResVT, X, Op1); 14252 } 14253 } 14254 14255 // uzp1(x, unpkhi(uzp1(y, z))) => uzp1(x, z) 14256 if (Op1.getOpcode() == AArch64ISD::UUNPKHI) { 14257 if (Op1.getOperand(0).getOpcode() == AArch64ISD::UZP1) { 14258 SDValue Z = Op1.getOperand(0).getOperand(1); 14259 return DAG.getNode(AArch64ISD::UZP1, DL, ResVT, Op0, Z); 14260 } 14261 } 14262 14263 return SDValue(); 14264 } 14265 14266 /// Target-specific DAG combine function for post-increment LD1 (lane) and 14267 /// post-increment LD1R. 14268 static SDValue performPostLD1Combine(SDNode *N, 14269 TargetLowering::DAGCombinerInfo &DCI, 14270 bool IsLaneOp) { 14271 if (DCI.isBeforeLegalizeOps()) 14272 return SDValue(); 14273 14274 SelectionDAG &DAG = DCI.DAG; 14275 EVT VT = N->getValueType(0); 14276 14277 if (VT.isScalableVector()) 14278 return SDValue(); 14279 14280 unsigned LoadIdx = IsLaneOp ? 1 : 0; 14281 SDNode *LD = N->getOperand(LoadIdx).getNode(); 14282 // If it is not LOAD, can not do such combine. 14283 if (LD->getOpcode() != ISD::LOAD) 14284 return SDValue(); 14285 14286 // The vector lane must be a constant in the LD1LANE opcode. 14287 SDValue Lane; 14288 if (IsLaneOp) { 14289 Lane = N->getOperand(2); 14290 auto *LaneC = dyn_cast<ConstantSDNode>(Lane); 14291 if (!LaneC || LaneC->getZExtValue() >= VT.getVectorNumElements()) 14292 return SDValue(); 14293 } 14294 14295 LoadSDNode *LoadSDN = cast<LoadSDNode>(LD); 14296 EVT MemVT = LoadSDN->getMemoryVT(); 14297 // Check if memory operand is the same type as the vector element. 14298 if (MemVT != VT.getVectorElementType()) 14299 return SDValue(); 14300 14301 // Check if there are other uses. If so, do not combine as it will introduce 14302 // an extra load. 14303 for (SDNode::use_iterator UI = LD->use_begin(), UE = LD->use_end(); UI != UE; 14304 ++UI) { 14305 if (UI.getUse().getResNo() == 1) // Ignore uses of the chain result. 14306 continue; 14307 if (*UI != N) 14308 return SDValue(); 14309 } 14310 14311 SDValue Addr = LD->getOperand(1); 14312 SDValue Vector = N->getOperand(0); 14313 // Search for a use of the address operand that is an increment. 14314 for (SDNode::use_iterator UI = Addr.getNode()->use_begin(), UE = 14315 Addr.getNode()->use_end(); UI != UE; ++UI) { 14316 SDNode *User = *UI; 14317 if (User->getOpcode() != ISD::ADD 14318 || UI.getUse().getResNo() != Addr.getResNo()) 14319 continue; 14320 14321 // If the increment is a constant, it must match the memory ref size. 14322 SDValue Inc = User->getOperand(User->getOperand(0) == Addr ? 1 : 0); 14323 if (ConstantSDNode *CInc = dyn_cast<ConstantSDNode>(Inc.getNode())) { 14324 uint32_t IncVal = CInc->getZExtValue(); 14325 unsigned NumBytes = VT.getScalarSizeInBits() / 8; 14326 if (IncVal != NumBytes) 14327 continue; 14328 Inc = DAG.getRegister(AArch64::XZR, MVT::i64); 14329 } 14330 14331 // To avoid cycle construction make sure that neither the load nor the add 14332 // are predecessors to each other or the Vector. 14333 SmallPtrSet<const SDNode *, 32> Visited; 14334 SmallVector<const SDNode *, 16> Worklist; 14335 Visited.insert(Addr.getNode()); 14336 Worklist.push_back(User); 14337 Worklist.push_back(LD); 14338 Worklist.push_back(Vector.getNode()); 14339 if (SDNode::hasPredecessorHelper(LD, Visited, Worklist) || 14340 SDNode::hasPredecessorHelper(User, Visited, Worklist)) 14341 continue; 14342 14343 SmallVector<SDValue, 8> Ops; 14344 Ops.push_back(LD->getOperand(0)); // Chain 14345 if (IsLaneOp) { 14346 Ops.push_back(Vector); // The vector to be inserted 14347 Ops.push_back(Lane); // The lane to be inserted in the vector 14348 } 14349 Ops.push_back(Addr); 14350 Ops.push_back(Inc); 14351 14352 EVT Tys[3] = { VT, MVT::i64, MVT::Other }; 14353 SDVTList SDTys = DAG.getVTList(Tys); 14354 unsigned NewOp = IsLaneOp ? AArch64ISD::LD1LANEpost : AArch64ISD::LD1DUPpost; 14355 SDValue UpdN = DAG.getMemIntrinsicNode(NewOp, SDLoc(N), SDTys, Ops, 14356 MemVT, 14357 LoadSDN->getMemOperand()); 14358 14359 // Update the uses. 14360 SDValue NewResults[] = { 14361 SDValue(LD, 0), // The result of load 14362 SDValue(UpdN.getNode(), 2) // Chain 14363 }; 14364 DCI.CombineTo(LD, NewResults); 14365 DCI.CombineTo(N, SDValue(UpdN.getNode(), 0)); // Dup/Inserted Result 14366 DCI.CombineTo(User, SDValue(UpdN.getNode(), 1)); // Write back register 14367 14368 break; 14369 } 14370 return SDValue(); 14371 } 14372 14373 /// Simplify ``Addr`` given that the top byte of it is ignored by HW during 14374 /// address translation. 14375 static bool performTBISimplification(SDValue Addr, 14376 TargetLowering::DAGCombinerInfo &DCI, 14377 SelectionDAG &DAG) { 14378 APInt DemandedMask = APInt::getLowBitsSet(64, 56); 14379 KnownBits Known; 14380 TargetLowering::TargetLoweringOpt TLO(DAG, !DCI.isBeforeLegalize(), 14381 !DCI.isBeforeLegalizeOps()); 14382 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 14383 if (TLI.SimplifyDemandedBits(Addr, DemandedMask, Known, TLO)) { 14384 DCI.CommitTargetLoweringOpt(TLO); 14385 return true; 14386 } 14387 return false; 14388 } 14389 14390 static SDValue performSTORECombine(SDNode *N, 14391 TargetLowering::DAGCombinerInfo &DCI, 14392 SelectionDAG &DAG, 14393 const AArch64Subtarget *Subtarget) { 14394 if (SDValue Split = splitStores(N, DCI, DAG, Subtarget)) 14395 return Split; 14396 14397 if (Subtarget->supportsAddressTopByteIgnored() && 14398 performTBISimplification(N->getOperand(2), DCI, DAG)) 14399 return SDValue(N, 0); 14400 14401 return SDValue(); 14402 } 14403 14404 /// Target-specific DAG combine function for NEON load/store intrinsics 14405 /// to merge base address updates. 14406 static SDValue performNEONPostLDSTCombine(SDNode *N, 14407 TargetLowering::DAGCombinerInfo &DCI, 14408 SelectionDAG &DAG) { 14409 if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer()) 14410 return SDValue(); 14411 14412 unsigned AddrOpIdx = N->getNumOperands() - 1; 14413 SDValue Addr = N->getOperand(AddrOpIdx); 14414 14415 // Search for a use of the address operand that is an increment. 14416 for (SDNode::use_iterator UI = Addr.getNode()->use_begin(), 14417 UE = Addr.getNode()->use_end(); UI != UE; ++UI) { 14418 SDNode *User = *UI; 14419 if (User->getOpcode() != ISD::ADD || 14420 UI.getUse().getResNo() != Addr.getResNo()) 14421 continue; 14422 14423 // Check that the add is independent of the load/store. Otherwise, folding 14424 // it would create a cycle. 14425 SmallPtrSet<const SDNode *, 32> Visited; 14426 SmallVector<const SDNode *, 16> Worklist; 14427 Visited.insert(Addr.getNode()); 14428 Worklist.push_back(N); 14429 Worklist.push_back(User); 14430 if (SDNode::hasPredecessorHelper(N, Visited, Worklist) || 14431 SDNode::hasPredecessorHelper(User, Visited, Worklist)) 14432 continue; 14433 14434 // Find the new opcode for the updating load/store. 14435 bool IsStore = false; 14436 bool IsLaneOp = false; 14437 bool IsDupOp = false; 14438 unsigned NewOpc = 0; 14439 unsigned NumVecs = 0; 14440 unsigned IntNo = cast<ConstantSDNode>(N->getOperand(1))->getZExtValue(); 14441 switch (IntNo) { 14442 default: llvm_unreachable("unexpected intrinsic for Neon base update"); 14443 case Intrinsic::aarch64_neon_ld2: NewOpc = AArch64ISD::LD2post; 14444 NumVecs = 2; break; 14445 case Intrinsic::aarch64_neon_ld3: NewOpc = AArch64ISD::LD3post; 14446 NumVecs = 3; break; 14447 case Intrinsic::aarch64_neon_ld4: NewOpc = AArch64ISD::LD4post; 14448 NumVecs = 4; break; 14449 case Intrinsic::aarch64_neon_st2: NewOpc = AArch64ISD::ST2post; 14450 NumVecs = 2; IsStore = true; break; 14451 case Intrinsic::aarch64_neon_st3: NewOpc = AArch64ISD::ST3post; 14452 NumVecs = 3; IsStore = true; break; 14453 case Intrinsic::aarch64_neon_st4: NewOpc = AArch64ISD::ST4post; 14454 NumVecs = 4; IsStore = true; break; 14455 case Intrinsic::aarch64_neon_ld1x2: NewOpc = AArch64ISD::LD1x2post; 14456 NumVecs = 2; break; 14457 case Intrinsic::aarch64_neon_ld1x3: NewOpc = AArch64ISD::LD1x3post; 14458 NumVecs = 3; break; 14459 case Intrinsic::aarch64_neon_ld1x4: NewOpc = AArch64ISD::LD1x4post; 14460 NumVecs = 4; break; 14461 case Intrinsic::aarch64_neon_st1x2: NewOpc = AArch64ISD::ST1x2post; 14462 NumVecs = 2; IsStore = true; break; 14463 case Intrinsic::aarch64_neon_st1x3: NewOpc = AArch64ISD::ST1x3post; 14464 NumVecs = 3; IsStore = true; break; 14465 case Intrinsic::aarch64_neon_st1x4: NewOpc = AArch64ISD::ST1x4post; 14466 NumVecs = 4; IsStore = true; break; 14467 case Intrinsic::aarch64_neon_ld2r: NewOpc = AArch64ISD::LD2DUPpost; 14468 NumVecs = 2; IsDupOp = true; break; 14469 case Intrinsic::aarch64_neon_ld3r: NewOpc = AArch64ISD::LD3DUPpost; 14470 NumVecs = 3; IsDupOp = true; break; 14471 case Intrinsic::aarch64_neon_ld4r: NewOpc = AArch64ISD::LD4DUPpost; 14472 NumVecs = 4; IsDupOp = true; break; 14473 case Intrinsic::aarch64_neon_ld2lane: NewOpc = AArch64ISD::LD2LANEpost; 14474 NumVecs = 2; IsLaneOp = true; break; 14475 case Intrinsic::aarch64_neon_ld3lane: NewOpc = AArch64ISD::LD3LANEpost; 14476 NumVecs = 3; IsLaneOp = true; break; 14477 case Intrinsic::aarch64_neon_ld4lane: NewOpc = AArch64ISD::LD4LANEpost; 14478 NumVecs = 4; IsLaneOp = true; break; 14479 case Intrinsic::aarch64_neon_st2lane: NewOpc = AArch64ISD::ST2LANEpost; 14480 NumVecs = 2; IsStore = true; IsLaneOp = true; break; 14481 case Intrinsic::aarch64_neon_st3lane: NewOpc = AArch64ISD::ST3LANEpost; 14482 NumVecs = 3; IsStore = true; IsLaneOp = true; break; 14483 case Intrinsic::aarch64_neon_st4lane: NewOpc = AArch64ISD::ST4LANEpost; 14484 NumVecs = 4; IsStore = true; IsLaneOp = true; break; 14485 } 14486 14487 EVT VecTy; 14488 if (IsStore) 14489 VecTy = N->getOperand(2).getValueType(); 14490 else 14491 VecTy = N->getValueType(0); 14492 14493 // If the increment is a constant, it must match the memory ref size. 14494 SDValue Inc = User->getOperand(User->getOperand(0) == Addr ? 1 : 0); 14495 if (ConstantSDNode *CInc = dyn_cast<ConstantSDNode>(Inc.getNode())) { 14496 uint32_t IncVal = CInc->getZExtValue(); 14497 unsigned NumBytes = NumVecs * VecTy.getSizeInBits() / 8; 14498 if (IsLaneOp || IsDupOp) 14499 NumBytes /= VecTy.getVectorNumElements(); 14500 if (IncVal != NumBytes) 14501 continue; 14502 Inc = DAG.getRegister(AArch64::XZR, MVT::i64); 14503 } 14504 SmallVector<SDValue, 8> Ops; 14505 Ops.push_back(N->getOperand(0)); // Incoming chain 14506 // Load lane and store have vector list as input. 14507 if (IsLaneOp || IsStore) 14508 for (unsigned i = 2; i < AddrOpIdx; ++i) 14509 Ops.push_back(N->getOperand(i)); 14510 Ops.push_back(Addr); // Base register 14511 Ops.push_back(Inc); 14512 14513 // Return Types. 14514 EVT Tys[6]; 14515 unsigned NumResultVecs = (IsStore ? 0 : NumVecs); 14516 unsigned n; 14517 for (n = 0; n < NumResultVecs; ++n) 14518 Tys[n] = VecTy; 14519 Tys[n++] = MVT::i64; // Type of write back register 14520 Tys[n] = MVT::Other; // Type of the chain 14521 SDVTList SDTys = DAG.getVTList(makeArrayRef(Tys, NumResultVecs + 2)); 14522 14523 MemIntrinsicSDNode *MemInt = cast<MemIntrinsicSDNode>(N); 14524 SDValue UpdN = DAG.getMemIntrinsicNode(NewOpc, SDLoc(N), SDTys, Ops, 14525 MemInt->getMemoryVT(), 14526 MemInt->getMemOperand()); 14527 14528 // Update the uses. 14529 std::vector<SDValue> NewResults; 14530 for (unsigned i = 0; i < NumResultVecs; ++i) { 14531 NewResults.push_back(SDValue(UpdN.getNode(), i)); 14532 } 14533 NewResults.push_back(SDValue(UpdN.getNode(), NumResultVecs + 1)); 14534 DCI.CombineTo(N, NewResults); 14535 DCI.CombineTo(User, SDValue(UpdN.getNode(), NumResultVecs)); 14536 14537 break; 14538 } 14539 return SDValue(); 14540 } 14541 14542 // Checks to see if the value is the prescribed width and returns information 14543 // about its extension mode. 14544 static 14545 bool checkValueWidth(SDValue V, unsigned width, ISD::LoadExtType &ExtType) { 14546 ExtType = ISD::NON_EXTLOAD; 14547 switch(V.getNode()->getOpcode()) { 14548 default: 14549 return false; 14550 case ISD::LOAD: { 14551 LoadSDNode *LoadNode = cast<LoadSDNode>(V.getNode()); 14552 if ((LoadNode->getMemoryVT() == MVT::i8 && width == 8) 14553 || (LoadNode->getMemoryVT() == MVT::i16 && width == 16)) { 14554 ExtType = LoadNode->getExtensionType(); 14555 return true; 14556 } 14557 return false; 14558 } 14559 case ISD::AssertSext: { 14560 VTSDNode *TypeNode = cast<VTSDNode>(V.getNode()->getOperand(1)); 14561 if ((TypeNode->getVT() == MVT::i8 && width == 8) 14562 || (TypeNode->getVT() == MVT::i16 && width == 16)) { 14563 ExtType = ISD::SEXTLOAD; 14564 return true; 14565 } 14566 return false; 14567 } 14568 case ISD::AssertZext: { 14569 VTSDNode *TypeNode = cast<VTSDNode>(V.getNode()->getOperand(1)); 14570 if ((TypeNode->getVT() == MVT::i8 && width == 8) 14571 || (TypeNode->getVT() == MVT::i16 && width == 16)) { 14572 ExtType = ISD::ZEXTLOAD; 14573 return true; 14574 } 14575 return false; 14576 } 14577 case ISD::Constant: 14578 case ISD::TargetConstant: { 14579 return std::abs(cast<ConstantSDNode>(V.getNode())->getSExtValue()) < 14580 1LL << (width - 1); 14581 } 14582 } 14583 14584 return true; 14585 } 14586 14587 // This function does a whole lot of voodoo to determine if the tests are 14588 // equivalent without and with a mask. Essentially what happens is that given a 14589 // DAG resembling: 14590 // 14591 // +-------------+ +-------------+ +-------------+ +-------------+ 14592 // | Input | | AddConstant | | CompConstant| | CC | 14593 // +-------------+ +-------------+ +-------------+ +-------------+ 14594 // | | | | 14595 // V V | +----------+ 14596 // +-------------+ +----+ | | 14597 // | ADD | |0xff| | | 14598 // +-------------+ +----+ | | 14599 // | | | | 14600 // V V | | 14601 // +-------------+ | | 14602 // | AND | | | 14603 // +-------------+ | | 14604 // | | | 14605 // +-----+ | | 14606 // | | | 14607 // V V V 14608 // +-------------+ 14609 // | CMP | 14610 // +-------------+ 14611 // 14612 // The AND node may be safely removed for some combinations of inputs. In 14613 // particular we need to take into account the extension type of the Input, 14614 // the exact values of AddConstant, CompConstant, and CC, along with the nominal 14615 // width of the input (this can work for any width inputs, the above graph is 14616 // specific to 8 bits. 14617 // 14618 // The specific equations were worked out by generating output tables for each 14619 // AArch64CC value in terms of and AddConstant (w1), CompConstant(w2). The 14620 // problem was simplified by working with 4 bit inputs, which means we only 14621 // needed to reason about 24 distinct bit patterns: 8 patterns unique to zero 14622 // extension (8,15), 8 patterns unique to sign extensions (-8,-1), and 8 14623 // patterns present in both extensions (0,7). For every distinct set of 14624 // AddConstant and CompConstants bit patterns we can consider the masked and 14625 // unmasked versions to be equivalent if the result of this function is true for 14626 // all 16 distinct bit patterns of for the current extension type of Input (w0). 14627 // 14628 // sub w8, w0, w1 14629 // and w10, w8, #0x0f 14630 // cmp w8, w2 14631 // cset w9, AArch64CC 14632 // cmp w10, w2 14633 // cset w11, AArch64CC 14634 // cmp w9, w11 14635 // cset w0, eq 14636 // ret 14637 // 14638 // Since the above function shows when the outputs are equivalent it defines 14639 // when it is safe to remove the AND. Unfortunately it only runs on AArch64 and 14640 // would be expensive to run during compiles. The equations below were written 14641 // in a test harness that confirmed they gave equivalent outputs to the above 14642 // for all inputs function, so they can be used determine if the removal is 14643 // legal instead. 14644 // 14645 // isEquivalentMaskless() is the code for testing if the AND can be removed 14646 // factored out of the DAG recognition as the DAG can take several forms. 14647 14648 static bool isEquivalentMaskless(unsigned CC, unsigned width, 14649 ISD::LoadExtType ExtType, int AddConstant, 14650 int CompConstant) { 14651 // By being careful about our equations and only writing the in term 14652 // symbolic values and well known constants (0, 1, -1, MaxUInt) we can 14653 // make them generally applicable to all bit widths. 14654 int MaxUInt = (1 << width); 14655 14656 // For the purposes of these comparisons sign extending the type is 14657 // equivalent to zero extending the add and displacing it by half the integer 14658 // width. Provided we are careful and make sure our equations are valid over 14659 // the whole range we can just adjust the input and avoid writing equations 14660 // for sign extended inputs. 14661 if (ExtType == ISD::SEXTLOAD) 14662 AddConstant -= (1 << (width-1)); 14663 14664 switch(CC) { 14665 case AArch64CC::LE: 14666 case AArch64CC::GT: 14667 if ((AddConstant == 0) || 14668 (CompConstant == MaxUInt - 1 && AddConstant < 0) || 14669 (AddConstant >= 0 && CompConstant < 0) || 14670 (AddConstant <= 0 && CompConstant <= 0 && CompConstant < AddConstant)) 14671 return true; 14672 break; 14673 case AArch64CC::LT: 14674 case AArch64CC::GE: 14675 if ((AddConstant == 0) || 14676 (AddConstant >= 0 && CompConstant <= 0) || 14677 (AddConstant <= 0 && CompConstant <= 0 && CompConstant <= AddConstant)) 14678 return true; 14679 break; 14680 case AArch64CC::HI: 14681 case AArch64CC::LS: 14682 if ((AddConstant >= 0 && CompConstant < 0) || 14683 (AddConstant <= 0 && CompConstant >= -1 && 14684 CompConstant < AddConstant + MaxUInt)) 14685 return true; 14686 break; 14687 case AArch64CC::PL: 14688 case AArch64CC::MI: 14689 if ((AddConstant == 0) || 14690 (AddConstant > 0 && CompConstant <= 0) || 14691 (AddConstant < 0 && CompConstant <= AddConstant)) 14692 return true; 14693 break; 14694 case AArch64CC::LO: 14695 case AArch64CC::HS: 14696 if ((AddConstant >= 0 && CompConstant <= 0) || 14697 (AddConstant <= 0 && CompConstant >= 0 && 14698 CompConstant <= AddConstant + MaxUInt)) 14699 return true; 14700 break; 14701 case AArch64CC::EQ: 14702 case AArch64CC::NE: 14703 if ((AddConstant > 0 && CompConstant < 0) || 14704 (AddConstant < 0 && CompConstant >= 0 && 14705 CompConstant < AddConstant + MaxUInt) || 14706 (AddConstant >= 0 && CompConstant >= 0 && 14707 CompConstant >= AddConstant) || 14708 (AddConstant <= 0 && CompConstant < 0 && CompConstant < AddConstant)) 14709 return true; 14710 break; 14711 case AArch64CC::VS: 14712 case AArch64CC::VC: 14713 case AArch64CC::AL: 14714 case AArch64CC::NV: 14715 return true; 14716 case AArch64CC::Invalid: 14717 break; 14718 } 14719 14720 return false; 14721 } 14722 14723 static 14724 SDValue performCONDCombine(SDNode *N, 14725 TargetLowering::DAGCombinerInfo &DCI, 14726 SelectionDAG &DAG, unsigned CCIndex, 14727 unsigned CmpIndex) { 14728 unsigned CC = cast<ConstantSDNode>(N->getOperand(CCIndex))->getSExtValue(); 14729 SDNode *SubsNode = N->getOperand(CmpIndex).getNode(); 14730 unsigned CondOpcode = SubsNode->getOpcode(); 14731 14732 if (CondOpcode != AArch64ISD::SUBS) 14733 return SDValue(); 14734 14735 // There is a SUBS feeding this condition. Is it fed by a mask we can 14736 // use? 14737 14738 SDNode *AndNode = SubsNode->getOperand(0).getNode(); 14739 unsigned MaskBits = 0; 14740 14741 if (AndNode->getOpcode() != ISD::AND) 14742 return SDValue(); 14743 14744 if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(AndNode->getOperand(1))) { 14745 uint32_t CNV = CN->getZExtValue(); 14746 if (CNV == 255) 14747 MaskBits = 8; 14748 else if (CNV == 65535) 14749 MaskBits = 16; 14750 } 14751 14752 if (!MaskBits) 14753 return SDValue(); 14754 14755 SDValue AddValue = AndNode->getOperand(0); 14756 14757 if (AddValue.getOpcode() != ISD::ADD) 14758 return SDValue(); 14759 14760 // The basic dag structure is correct, grab the inputs and validate them. 14761 14762 SDValue AddInputValue1 = AddValue.getNode()->getOperand(0); 14763 SDValue AddInputValue2 = AddValue.getNode()->getOperand(1); 14764 SDValue SubsInputValue = SubsNode->getOperand(1); 14765 14766 // The mask is present and the provenance of all the values is a smaller type, 14767 // lets see if the mask is superfluous. 14768 14769 if (!isa<ConstantSDNode>(AddInputValue2.getNode()) || 14770 !isa<ConstantSDNode>(SubsInputValue.getNode())) 14771 return SDValue(); 14772 14773 ISD::LoadExtType ExtType; 14774 14775 if (!checkValueWidth(SubsInputValue, MaskBits, ExtType) || 14776 !checkValueWidth(AddInputValue2, MaskBits, ExtType) || 14777 !checkValueWidth(AddInputValue1, MaskBits, ExtType) ) 14778 return SDValue(); 14779 14780 if(!isEquivalentMaskless(CC, MaskBits, ExtType, 14781 cast<ConstantSDNode>(AddInputValue2.getNode())->getSExtValue(), 14782 cast<ConstantSDNode>(SubsInputValue.getNode())->getSExtValue())) 14783 return SDValue(); 14784 14785 // The AND is not necessary, remove it. 14786 14787 SDVTList VTs = DAG.getVTList(SubsNode->getValueType(0), 14788 SubsNode->getValueType(1)); 14789 SDValue Ops[] = { AddValue, SubsNode->getOperand(1) }; 14790 14791 SDValue NewValue = DAG.getNode(CondOpcode, SDLoc(SubsNode), VTs, Ops); 14792 DAG.ReplaceAllUsesWith(SubsNode, NewValue.getNode()); 14793 14794 return SDValue(N, 0); 14795 } 14796 14797 // Optimize compare with zero and branch. 14798 static SDValue performBRCONDCombine(SDNode *N, 14799 TargetLowering::DAGCombinerInfo &DCI, 14800 SelectionDAG &DAG) { 14801 MachineFunction &MF = DAG.getMachineFunction(); 14802 // Speculation tracking/SLH assumes that optimized TB(N)Z/CB(N)Z instructions 14803 // will not be produced, as they are conditional branch instructions that do 14804 // not set flags. 14805 if (MF.getFunction().hasFnAttribute(Attribute::SpeculativeLoadHardening)) 14806 return SDValue(); 14807 14808 if (SDValue NV = performCONDCombine(N, DCI, DAG, 2, 3)) 14809 N = NV.getNode(); 14810 SDValue Chain = N->getOperand(0); 14811 SDValue Dest = N->getOperand(1); 14812 SDValue CCVal = N->getOperand(2); 14813 SDValue Cmp = N->getOperand(3); 14814 14815 assert(isa<ConstantSDNode>(CCVal) && "Expected a ConstantSDNode here!"); 14816 unsigned CC = cast<ConstantSDNode>(CCVal)->getZExtValue(); 14817 if (CC != AArch64CC::EQ && CC != AArch64CC::NE) 14818 return SDValue(); 14819 14820 unsigned CmpOpc = Cmp.getOpcode(); 14821 if (CmpOpc != AArch64ISD::ADDS && CmpOpc != AArch64ISD::SUBS) 14822 return SDValue(); 14823 14824 // Only attempt folding if there is only one use of the flag and no use of the 14825 // value. 14826 if (!Cmp->hasNUsesOfValue(0, 0) || !Cmp->hasNUsesOfValue(1, 1)) 14827 return SDValue(); 14828 14829 SDValue LHS = Cmp.getOperand(0); 14830 SDValue RHS = Cmp.getOperand(1); 14831 14832 assert(LHS.getValueType() == RHS.getValueType() && 14833 "Expected the value type to be the same for both operands!"); 14834 if (LHS.getValueType() != MVT::i32 && LHS.getValueType() != MVT::i64) 14835 return SDValue(); 14836 14837 if (isNullConstant(LHS)) 14838 std::swap(LHS, RHS); 14839 14840 if (!isNullConstant(RHS)) 14841 return SDValue(); 14842 14843 if (LHS.getOpcode() == ISD::SHL || LHS.getOpcode() == ISD::SRA || 14844 LHS.getOpcode() == ISD::SRL) 14845 return SDValue(); 14846 14847 // Fold the compare into the branch instruction. 14848 SDValue BR; 14849 if (CC == AArch64CC::EQ) 14850 BR = DAG.getNode(AArch64ISD::CBZ, SDLoc(N), MVT::Other, Chain, LHS, Dest); 14851 else 14852 BR = DAG.getNode(AArch64ISD::CBNZ, SDLoc(N), MVT::Other, Chain, LHS, Dest); 14853 14854 // Do not add new nodes to DAG combiner worklist. 14855 DCI.CombineTo(N, BR, false); 14856 14857 return SDValue(); 14858 } 14859 14860 // Optimize some simple tbz/tbnz cases. Returns the new operand and bit to test 14861 // as well as whether the test should be inverted. This code is required to 14862 // catch these cases (as opposed to standard dag combines) because 14863 // AArch64ISD::TBZ is matched during legalization. 14864 static SDValue getTestBitOperand(SDValue Op, unsigned &Bit, bool &Invert, 14865 SelectionDAG &DAG) { 14866 14867 if (!Op->hasOneUse()) 14868 return Op; 14869 14870 // We don't handle undef/constant-fold cases below, as they should have 14871 // already been taken care of (e.g. and of 0, test of undefined shifted bits, 14872 // etc.) 14873 14874 // (tbz (trunc x), b) -> (tbz x, b) 14875 // This case is just here to enable more of the below cases to be caught. 14876 if (Op->getOpcode() == ISD::TRUNCATE && 14877 Bit < Op->getValueType(0).getSizeInBits()) { 14878 return getTestBitOperand(Op->getOperand(0), Bit, Invert, DAG); 14879 } 14880 14881 // (tbz (any_ext x), b) -> (tbz x, b) if we don't use the extended bits. 14882 if (Op->getOpcode() == ISD::ANY_EXTEND && 14883 Bit < Op->getOperand(0).getValueSizeInBits()) { 14884 return getTestBitOperand(Op->getOperand(0), Bit, Invert, DAG); 14885 } 14886 14887 if (Op->getNumOperands() != 2) 14888 return Op; 14889 14890 auto *C = dyn_cast<ConstantSDNode>(Op->getOperand(1)); 14891 if (!C) 14892 return Op; 14893 14894 switch (Op->getOpcode()) { 14895 default: 14896 return Op; 14897 14898 // (tbz (and x, m), b) -> (tbz x, b) 14899 case ISD::AND: 14900 if ((C->getZExtValue() >> Bit) & 1) 14901 return getTestBitOperand(Op->getOperand(0), Bit, Invert, DAG); 14902 return Op; 14903 14904 // (tbz (shl x, c), b) -> (tbz x, b-c) 14905 case ISD::SHL: 14906 if (C->getZExtValue() <= Bit && 14907 (Bit - C->getZExtValue()) < Op->getValueType(0).getSizeInBits()) { 14908 Bit = Bit - C->getZExtValue(); 14909 return getTestBitOperand(Op->getOperand(0), Bit, Invert, DAG); 14910 } 14911 return Op; 14912 14913 // (tbz (sra x, c), b) -> (tbz x, b+c) or (tbz x, msb) if b+c is > # bits in x 14914 case ISD::SRA: 14915 Bit = Bit + C->getZExtValue(); 14916 if (Bit >= Op->getValueType(0).getSizeInBits()) 14917 Bit = Op->getValueType(0).getSizeInBits() - 1; 14918 return getTestBitOperand(Op->getOperand(0), Bit, Invert, DAG); 14919 14920 // (tbz (srl x, c), b) -> (tbz x, b+c) 14921 case ISD::SRL: 14922 if ((Bit + C->getZExtValue()) < Op->getValueType(0).getSizeInBits()) { 14923 Bit = Bit + C->getZExtValue(); 14924 return getTestBitOperand(Op->getOperand(0), Bit, Invert, DAG); 14925 } 14926 return Op; 14927 14928 // (tbz (xor x, -1), b) -> (tbnz x, b) 14929 case ISD::XOR: 14930 if ((C->getZExtValue() >> Bit) & 1) 14931 Invert = !Invert; 14932 return getTestBitOperand(Op->getOperand(0), Bit, Invert, DAG); 14933 } 14934 } 14935 14936 // Optimize test single bit zero/non-zero and branch. 14937 static SDValue performTBZCombine(SDNode *N, 14938 TargetLowering::DAGCombinerInfo &DCI, 14939 SelectionDAG &DAG) { 14940 unsigned Bit = cast<ConstantSDNode>(N->getOperand(2))->getZExtValue(); 14941 bool Invert = false; 14942 SDValue TestSrc = N->getOperand(1); 14943 SDValue NewTestSrc = getTestBitOperand(TestSrc, Bit, Invert, DAG); 14944 14945 if (TestSrc == NewTestSrc) 14946 return SDValue(); 14947 14948 unsigned NewOpc = N->getOpcode(); 14949 if (Invert) { 14950 if (NewOpc == AArch64ISD::TBZ) 14951 NewOpc = AArch64ISD::TBNZ; 14952 else { 14953 assert(NewOpc == AArch64ISD::TBNZ); 14954 NewOpc = AArch64ISD::TBZ; 14955 } 14956 } 14957 14958 SDLoc DL(N); 14959 return DAG.getNode(NewOpc, DL, MVT::Other, N->getOperand(0), NewTestSrc, 14960 DAG.getConstant(Bit, DL, MVT::i64), N->getOperand(3)); 14961 } 14962 14963 // vselect (v1i1 setcc) -> 14964 // vselect (v1iXX setcc) (XX is the size of the compared operand type) 14965 // FIXME: Currently the type legalizer can't handle VSELECT having v1i1 as 14966 // condition. If it can legalize "VSELECT v1i1" correctly, no need to combine 14967 // such VSELECT. 14968 static SDValue performVSelectCombine(SDNode *N, SelectionDAG &DAG) { 14969 SDValue N0 = N->getOperand(0); 14970 EVT CCVT = N0.getValueType(); 14971 14972 if (N0.getOpcode() != ISD::SETCC || CCVT.getVectorNumElements() != 1 || 14973 CCVT.getVectorElementType() != MVT::i1) 14974 return SDValue(); 14975 14976 EVT ResVT = N->getValueType(0); 14977 EVT CmpVT = N0.getOperand(0).getValueType(); 14978 // Only combine when the result type is of the same size as the compared 14979 // operands. 14980 if (ResVT.getSizeInBits() != CmpVT.getSizeInBits()) 14981 return SDValue(); 14982 14983 SDValue IfTrue = N->getOperand(1); 14984 SDValue IfFalse = N->getOperand(2); 14985 SDValue SetCC = 14986 DAG.getSetCC(SDLoc(N), CmpVT.changeVectorElementTypeToInteger(), 14987 N0.getOperand(0), N0.getOperand(1), 14988 cast<CondCodeSDNode>(N0.getOperand(2))->get()); 14989 return DAG.getNode(ISD::VSELECT, SDLoc(N), ResVT, SetCC, 14990 IfTrue, IfFalse); 14991 } 14992 14993 /// A vector select: "(select vL, vR, (setcc LHS, RHS))" is best performed with 14994 /// the compare-mask instructions rather than going via NZCV, even if LHS and 14995 /// RHS are really scalar. This replaces any scalar setcc in the above pattern 14996 /// with a vector one followed by a DUP shuffle on the result. 14997 static SDValue performSelectCombine(SDNode *N, 14998 TargetLowering::DAGCombinerInfo &DCI) { 14999 SelectionDAG &DAG = DCI.DAG; 15000 SDValue N0 = N->getOperand(0); 15001 EVT ResVT = N->getValueType(0); 15002 15003 if (N0.getOpcode() != ISD::SETCC) 15004 return SDValue(); 15005 15006 // Make sure the SETCC result is either i1 (initial DAG), or i32, the lowered 15007 // scalar SetCCResultType. We also don't expect vectors, because we assume 15008 // that selects fed by vector SETCCs are canonicalized to VSELECT. 15009 assert((N0.getValueType() == MVT::i1 || N0.getValueType() == MVT::i32) && 15010 "Scalar-SETCC feeding SELECT has unexpected result type!"); 15011 15012 // If NumMaskElts == 0, the comparison is larger than select result. The 15013 // largest real NEON comparison is 64-bits per lane, which means the result is 15014 // at most 32-bits and an illegal vector. Just bail out for now. 15015 EVT SrcVT = N0.getOperand(0).getValueType(); 15016 15017 // Don't try to do this optimization when the setcc itself has i1 operands. 15018 // There are no legal vectors of i1, so this would be pointless. 15019 if (SrcVT == MVT::i1) 15020 return SDValue(); 15021 15022 int NumMaskElts = ResVT.getSizeInBits() / SrcVT.getSizeInBits(); 15023 if (!ResVT.isVector() || NumMaskElts == 0) 15024 return SDValue(); 15025 15026 SrcVT = EVT::getVectorVT(*DAG.getContext(), SrcVT, NumMaskElts); 15027 EVT CCVT = SrcVT.changeVectorElementTypeToInteger(); 15028 15029 // Also bail out if the vector CCVT isn't the same size as ResVT. 15030 // This can happen if the SETCC operand size doesn't divide the ResVT size 15031 // (e.g., f64 vs v3f32). 15032 if (CCVT.getSizeInBits() != ResVT.getSizeInBits()) 15033 return SDValue(); 15034 15035 // Make sure we didn't create illegal types, if we're not supposed to. 15036 assert(DCI.isBeforeLegalize() || 15037 DAG.getTargetLoweringInfo().isTypeLegal(SrcVT)); 15038 15039 // First perform a vector comparison, where lane 0 is the one we're interested 15040 // in. 15041 SDLoc DL(N0); 15042 SDValue LHS = 15043 DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, SrcVT, N0.getOperand(0)); 15044 SDValue RHS = 15045 DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, SrcVT, N0.getOperand(1)); 15046 SDValue SetCC = DAG.getNode(ISD::SETCC, DL, CCVT, LHS, RHS, N0.getOperand(2)); 15047 15048 // Now duplicate the comparison mask we want across all other lanes. 15049 SmallVector<int, 8> DUPMask(CCVT.getVectorNumElements(), 0); 15050 SDValue Mask = DAG.getVectorShuffle(CCVT, DL, SetCC, SetCC, DUPMask); 15051 Mask = DAG.getNode(ISD::BITCAST, DL, 15052 ResVT.changeVectorElementTypeToInteger(), Mask); 15053 15054 return DAG.getSelect(DL, ResVT, Mask, N->getOperand(1), N->getOperand(2)); 15055 } 15056 15057 /// Get rid of unnecessary NVCASTs (that don't change the type). 15058 static SDValue performNVCASTCombine(SDNode *N) { 15059 if (N->getValueType(0) == N->getOperand(0).getValueType()) 15060 return N->getOperand(0); 15061 15062 return SDValue(); 15063 } 15064 15065 // If all users of the globaladdr are of the form (globaladdr + constant), find 15066 // the smallest constant, fold it into the globaladdr's offset and rewrite the 15067 // globaladdr as (globaladdr + constant) - constant. 15068 static SDValue performGlobalAddressCombine(SDNode *N, SelectionDAG &DAG, 15069 const AArch64Subtarget *Subtarget, 15070 const TargetMachine &TM) { 15071 auto *GN = cast<GlobalAddressSDNode>(N); 15072 if (Subtarget->ClassifyGlobalReference(GN->getGlobal(), TM) != 15073 AArch64II::MO_NO_FLAG) 15074 return SDValue(); 15075 15076 uint64_t MinOffset = -1ull; 15077 for (SDNode *N : GN->uses()) { 15078 if (N->getOpcode() != ISD::ADD) 15079 return SDValue(); 15080 auto *C = dyn_cast<ConstantSDNode>(N->getOperand(0)); 15081 if (!C) 15082 C = dyn_cast<ConstantSDNode>(N->getOperand(1)); 15083 if (!C) 15084 return SDValue(); 15085 MinOffset = std::min(MinOffset, C->getZExtValue()); 15086 } 15087 uint64_t Offset = MinOffset + GN->getOffset(); 15088 15089 // Require that the new offset is larger than the existing one. Otherwise, we 15090 // can end up oscillating between two possible DAGs, for example, 15091 // (add (add globaladdr + 10, -1), 1) and (add globaladdr + 9, 1). 15092 if (Offset <= uint64_t(GN->getOffset())) 15093 return SDValue(); 15094 15095 // Check whether folding this offset is legal. It must not go out of bounds of 15096 // the referenced object to avoid violating the code model, and must be 15097 // smaller than 2^21 because this is the largest offset expressible in all 15098 // object formats. 15099 // 15100 // This check also prevents us from folding negative offsets, which will end 15101 // up being treated in the same way as large positive ones. They could also 15102 // cause code model violations, and aren't really common enough to matter. 15103 if (Offset >= (1 << 21)) 15104 return SDValue(); 15105 15106 const GlobalValue *GV = GN->getGlobal(); 15107 Type *T = GV->getValueType(); 15108 if (!T->isSized() || 15109 Offset > GV->getParent()->getDataLayout().getTypeAllocSize(T)) 15110 return SDValue(); 15111 15112 SDLoc DL(GN); 15113 SDValue Result = DAG.getGlobalAddress(GV, DL, MVT::i64, Offset); 15114 return DAG.getNode(ISD::SUB, DL, MVT::i64, Result, 15115 DAG.getConstant(MinOffset, DL, MVT::i64)); 15116 } 15117 15118 // Turns the vector of indices into a vector of byte offstes by scaling Offset 15119 // by (BitWidth / 8). 15120 static SDValue getScaledOffsetForBitWidth(SelectionDAG &DAG, SDValue Offset, 15121 SDLoc DL, unsigned BitWidth) { 15122 assert(Offset.getValueType().isScalableVector() && 15123 "This method is only for scalable vectors of offsets"); 15124 15125 SDValue Shift = DAG.getConstant(Log2_32(BitWidth / 8), DL, MVT::i64); 15126 SDValue SplatShift = DAG.getNode(ISD::SPLAT_VECTOR, DL, MVT::nxv2i64, Shift); 15127 15128 return DAG.getNode(ISD::SHL, DL, MVT::nxv2i64, Offset, SplatShift); 15129 } 15130 15131 /// Check if the value of \p OffsetInBytes can be used as an immediate for 15132 /// the gather load/prefetch and scatter store instructions with vector base and 15133 /// immediate offset addressing mode: 15134 /// 15135 /// [<Zn>.[S|D]{, #<imm>}] 15136 /// 15137 /// where <imm> = sizeof(<T>) * k, for k = 0, 1, ..., 31. 15138 15139 inline static bool isValidImmForSVEVecImmAddrMode(unsigned OffsetInBytes, 15140 unsigned ScalarSizeInBytes) { 15141 // The immediate is not a multiple of the scalar size. 15142 if (OffsetInBytes % ScalarSizeInBytes) 15143 return false; 15144 15145 // The immediate is out of range. 15146 if (OffsetInBytes / ScalarSizeInBytes > 31) 15147 return false; 15148 15149 return true; 15150 } 15151 15152 /// Check if the value of \p Offset represents a valid immediate for the SVE 15153 /// gather load/prefetch and scatter store instructiona with vector base and 15154 /// immediate offset addressing mode: 15155 /// 15156 /// [<Zn>.[S|D]{, #<imm>}] 15157 /// 15158 /// where <imm> = sizeof(<T>) * k, for k = 0, 1, ..., 31. 15159 static bool isValidImmForSVEVecImmAddrMode(SDValue Offset, 15160 unsigned ScalarSizeInBytes) { 15161 ConstantSDNode *OffsetConst = dyn_cast<ConstantSDNode>(Offset.getNode()); 15162 return OffsetConst && isValidImmForSVEVecImmAddrMode( 15163 OffsetConst->getZExtValue(), ScalarSizeInBytes); 15164 } 15165 15166 static SDValue performScatterStoreCombine(SDNode *N, SelectionDAG &DAG, 15167 unsigned Opcode, 15168 bool OnlyPackedOffsets = true) { 15169 const SDValue Src = N->getOperand(2); 15170 const EVT SrcVT = Src->getValueType(0); 15171 assert(SrcVT.isScalableVector() && 15172 "Scatter stores are only possible for SVE vectors"); 15173 15174 SDLoc DL(N); 15175 MVT SrcElVT = SrcVT.getVectorElementType().getSimpleVT(); 15176 15177 // Make sure that source data will fit into an SVE register 15178 if (SrcVT.getSizeInBits().getKnownMinSize() > AArch64::SVEBitsPerBlock) 15179 return SDValue(); 15180 15181 // For FPs, ACLE only supports _packed_ single and double precision types. 15182 if (SrcElVT.isFloatingPoint()) 15183 if ((SrcVT != MVT::nxv4f32) && (SrcVT != MVT::nxv2f64)) 15184 return SDValue(); 15185 15186 // Depending on the addressing mode, this is either a pointer or a vector of 15187 // pointers (that fits into one register) 15188 SDValue Base = N->getOperand(4); 15189 // Depending on the addressing mode, this is either a single offset or a 15190 // vector of offsets (that fits into one register) 15191 SDValue Offset = N->getOperand(5); 15192 15193 // For "scalar + vector of indices", just scale the indices. This only 15194 // applies to non-temporal scatters because there's no instruction that takes 15195 // indicies. 15196 if (Opcode == AArch64ISD::SSTNT1_INDEX_PRED) { 15197 Offset = 15198 getScaledOffsetForBitWidth(DAG, Offset, DL, SrcElVT.getSizeInBits()); 15199 Opcode = AArch64ISD::SSTNT1_PRED; 15200 } 15201 15202 // In the case of non-temporal gather loads there's only one SVE instruction 15203 // per data-size: "scalar + vector", i.e. 15204 // * stnt1{b|h|w|d} { z0.s }, p0/z, [z0.s, x0] 15205 // Since we do have intrinsics that allow the arguments to be in a different 15206 // order, we may need to swap them to match the spec. 15207 if (Opcode == AArch64ISD::SSTNT1_PRED && Offset.getValueType().isVector()) 15208 std::swap(Base, Offset); 15209 15210 // SST1_IMM requires that the offset is an immediate that is: 15211 // * a multiple of #SizeInBytes, 15212 // * in the range [0, 31 x #SizeInBytes], 15213 // where #SizeInBytes is the size in bytes of the stored items. For 15214 // immediates outside that range and non-immediate scalar offsets use SST1 or 15215 // SST1_UXTW instead. 15216 if (Opcode == AArch64ISD::SST1_IMM_PRED) { 15217 if (!isValidImmForSVEVecImmAddrMode(Offset, 15218 SrcVT.getScalarSizeInBits() / 8)) { 15219 if (MVT::nxv4i32 == Base.getValueType().getSimpleVT().SimpleTy) 15220 Opcode = AArch64ISD::SST1_UXTW_PRED; 15221 else 15222 Opcode = AArch64ISD::SST1_PRED; 15223 15224 std::swap(Base, Offset); 15225 } 15226 } 15227 15228 auto &TLI = DAG.getTargetLoweringInfo(); 15229 if (!TLI.isTypeLegal(Base.getValueType())) 15230 return SDValue(); 15231 15232 // Some scatter store variants allow unpacked offsets, but only as nxv2i32 15233 // vectors. These are implicitly sign (sxtw) or zero (zxtw) extend to 15234 // nxv2i64. Legalize accordingly. 15235 if (!OnlyPackedOffsets && 15236 Offset.getValueType().getSimpleVT().SimpleTy == MVT::nxv2i32) 15237 Offset = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::nxv2i64, Offset).getValue(0); 15238 15239 if (!TLI.isTypeLegal(Offset.getValueType())) 15240 return SDValue(); 15241 15242 // Source value type that is representable in hardware 15243 EVT HwSrcVt = getSVEContainerType(SrcVT); 15244 15245 // Keep the original type of the input data to store - this is needed to be 15246 // able to select the correct instruction, e.g. ST1B, ST1H, ST1W and ST1D. For 15247 // FP values we want the integer equivalent, so just use HwSrcVt. 15248 SDValue InputVT = DAG.getValueType(SrcVT); 15249 if (SrcVT.isFloatingPoint()) 15250 InputVT = DAG.getValueType(HwSrcVt); 15251 15252 SDVTList VTs = DAG.getVTList(MVT::Other); 15253 SDValue SrcNew; 15254 15255 if (Src.getValueType().isFloatingPoint()) 15256 SrcNew = DAG.getNode(ISD::BITCAST, DL, HwSrcVt, Src); 15257 else 15258 SrcNew = DAG.getNode(ISD::ANY_EXTEND, DL, HwSrcVt, Src); 15259 15260 SDValue Ops[] = {N->getOperand(0), // Chain 15261 SrcNew, 15262 N->getOperand(3), // Pg 15263 Base, 15264 Offset, 15265 InputVT}; 15266 15267 return DAG.getNode(Opcode, DL, VTs, Ops); 15268 } 15269 15270 static SDValue performGatherLoadCombine(SDNode *N, SelectionDAG &DAG, 15271 unsigned Opcode, 15272 bool OnlyPackedOffsets = true) { 15273 const EVT RetVT = N->getValueType(0); 15274 assert(RetVT.isScalableVector() && 15275 "Gather loads are only possible for SVE vectors"); 15276 15277 SDLoc DL(N); 15278 15279 // Make sure that the loaded data will fit into an SVE register 15280 if (RetVT.getSizeInBits().getKnownMinSize() > AArch64::SVEBitsPerBlock) 15281 return SDValue(); 15282 15283 // Depending on the addressing mode, this is either a pointer or a vector of 15284 // pointers (that fits into one register) 15285 SDValue Base = N->getOperand(3); 15286 // Depending on the addressing mode, this is either a single offset or a 15287 // vector of offsets (that fits into one register) 15288 SDValue Offset = N->getOperand(4); 15289 15290 // For "scalar + vector of indices", just scale the indices. This only 15291 // applies to non-temporal gathers because there's no instruction that takes 15292 // indicies. 15293 if (Opcode == AArch64ISD::GLDNT1_INDEX_MERGE_ZERO) { 15294 Offset = getScaledOffsetForBitWidth(DAG, Offset, DL, 15295 RetVT.getScalarSizeInBits()); 15296 Opcode = AArch64ISD::GLDNT1_MERGE_ZERO; 15297 } 15298 15299 // In the case of non-temporal gather loads there's only one SVE instruction 15300 // per data-size: "scalar + vector", i.e. 15301 // * ldnt1{b|h|w|d} { z0.s }, p0/z, [z0.s, x0] 15302 // Since we do have intrinsics that allow the arguments to be in a different 15303 // order, we may need to swap them to match the spec. 15304 if (Opcode == AArch64ISD::GLDNT1_MERGE_ZERO && 15305 Offset.getValueType().isVector()) 15306 std::swap(Base, Offset); 15307 15308 // GLD{FF}1_IMM requires that the offset is an immediate that is: 15309 // * a multiple of #SizeInBytes, 15310 // * in the range [0, 31 x #SizeInBytes], 15311 // where #SizeInBytes is the size in bytes of the loaded items. For 15312 // immediates outside that range and non-immediate scalar offsets use 15313 // GLD1_MERGE_ZERO or GLD1_UXTW_MERGE_ZERO instead. 15314 if (Opcode == AArch64ISD::GLD1_IMM_MERGE_ZERO || 15315 Opcode == AArch64ISD::GLDFF1_IMM_MERGE_ZERO) { 15316 if (!isValidImmForSVEVecImmAddrMode(Offset, 15317 RetVT.getScalarSizeInBits() / 8)) { 15318 if (MVT::nxv4i32 == Base.getValueType().getSimpleVT().SimpleTy) 15319 Opcode = (Opcode == AArch64ISD::GLD1_IMM_MERGE_ZERO) 15320 ? AArch64ISD::GLD1_UXTW_MERGE_ZERO 15321 : AArch64ISD::GLDFF1_UXTW_MERGE_ZERO; 15322 else 15323 Opcode = (Opcode == AArch64ISD::GLD1_IMM_MERGE_ZERO) 15324 ? AArch64ISD::GLD1_MERGE_ZERO 15325 : AArch64ISD::GLDFF1_MERGE_ZERO; 15326 15327 std::swap(Base, Offset); 15328 } 15329 } 15330 15331 auto &TLI = DAG.getTargetLoweringInfo(); 15332 if (!TLI.isTypeLegal(Base.getValueType())) 15333 return SDValue(); 15334 15335 // Some gather load variants allow unpacked offsets, but only as nxv2i32 15336 // vectors. These are implicitly sign (sxtw) or zero (zxtw) extend to 15337 // nxv2i64. Legalize accordingly. 15338 if (!OnlyPackedOffsets && 15339 Offset.getValueType().getSimpleVT().SimpleTy == MVT::nxv2i32) 15340 Offset = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::nxv2i64, Offset).getValue(0); 15341 15342 // Return value type that is representable in hardware 15343 EVT HwRetVt = getSVEContainerType(RetVT); 15344 15345 // Keep the original output value type around - this is needed to be able to 15346 // select the correct instruction, e.g. LD1B, LD1H, LD1W and LD1D. For FP 15347 // values we want the integer equivalent, so just use HwRetVT. 15348 SDValue OutVT = DAG.getValueType(RetVT); 15349 if (RetVT.isFloatingPoint()) 15350 OutVT = DAG.getValueType(HwRetVt); 15351 15352 SDVTList VTs = DAG.getVTList(HwRetVt, MVT::Other); 15353 SDValue Ops[] = {N->getOperand(0), // Chain 15354 N->getOperand(2), // Pg 15355 Base, Offset, OutVT}; 15356 15357 SDValue Load = DAG.getNode(Opcode, DL, VTs, Ops); 15358 SDValue LoadChain = SDValue(Load.getNode(), 1); 15359 15360 if (RetVT.isInteger() && (RetVT != HwRetVt)) 15361 Load = DAG.getNode(ISD::TRUNCATE, DL, RetVT, Load.getValue(0)); 15362 15363 // If the original return value was FP, bitcast accordingly. Doing it here 15364 // means that we can avoid adding TableGen patterns for FPs. 15365 if (RetVT.isFloatingPoint()) 15366 Load = DAG.getNode(ISD::BITCAST, DL, RetVT, Load.getValue(0)); 15367 15368 return DAG.getMergeValues({Load, LoadChain}, DL); 15369 } 15370 15371 static SDValue 15372 performSignExtendInRegCombine(SDNode *N, TargetLowering::DAGCombinerInfo &DCI, 15373 SelectionDAG &DAG) { 15374 SDLoc DL(N); 15375 SDValue Src = N->getOperand(0); 15376 unsigned Opc = Src->getOpcode(); 15377 15378 // Sign extend of an unsigned unpack -> signed unpack 15379 if (Opc == AArch64ISD::UUNPKHI || Opc == AArch64ISD::UUNPKLO) { 15380 15381 unsigned SOpc = Opc == AArch64ISD::UUNPKHI ? AArch64ISD::SUNPKHI 15382 : AArch64ISD::SUNPKLO; 15383 15384 // Push the sign extend to the operand of the unpack 15385 // This is necessary where, for example, the operand of the unpack 15386 // is another unpack: 15387 // 4i32 sign_extend_inreg (4i32 uunpklo(8i16 uunpklo (16i8 opnd)), from 4i8) 15388 // -> 15389 // 4i32 sunpklo (8i16 sign_extend_inreg(8i16 uunpklo (16i8 opnd), from 8i8) 15390 // -> 15391 // 4i32 sunpklo(8i16 sunpklo(16i8 opnd)) 15392 SDValue ExtOp = Src->getOperand(0); 15393 auto VT = cast<VTSDNode>(N->getOperand(1))->getVT(); 15394 EVT EltTy = VT.getVectorElementType(); 15395 (void)EltTy; 15396 15397 assert((EltTy == MVT::i8 || EltTy == MVT::i16 || EltTy == MVT::i32) && 15398 "Sign extending from an invalid type"); 15399 15400 EVT ExtVT = VT.getDoubleNumVectorElementsVT(*DAG.getContext()); 15401 15402 SDValue Ext = DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, ExtOp.getValueType(), 15403 ExtOp, DAG.getValueType(ExtVT)); 15404 15405 return DAG.getNode(SOpc, DL, N->getValueType(0), Ext); 15406 } 15407 15408 if (DCI.isBeforeLegalizeOps()) 15409 return SDValue(); 15410 15411 if (!EnableCombineMGatherIntrinsics) 15412 return SDValue(); 15413 15414 // SVE load nodes (e.g. AArch64ISD::GLD1) are straightforward candidates 15415 // for DAG Combine with SIGN_EXTEND_INREG. Bail out for all other nodes. 15416 unsigned NewOpc; 15417 unsigned MemVTOpNum = 4; 15418 switch (Opc) { 15419 case AArch64ISD::LD1_MERGE_ZERO: 15420 NewOpc = AArch64ISD::LD1S_MERGE_ZERO; 15421 MemVTOpNum = 3; 15422 break; 15423 case AArch64ISD::LDNF1_MERGE_ZERO: 15424 NewOpc = AArch64ISD::LDNF1S_MERGE_ZERO; 15425 MemVTOpNum = 3; 15426 break; 15427 case AArch64ISD::LDFF1_MERGE_ZERO: 15428 NewOpc = AArch64ISD::LDFF1S_MERGE_ZERO; 15429 MemVTOpNum = 3; 15430 break; 15431 case AArch64ISD::GLD1_MERGE_ZERO: 15432 NewOpc = AArch64ISD::GLD1S_MERGE_ZERO; 15433 break; 15434 case AArch64ISD::GLD1_SCALED_MERGE_ZERO: 15435 NewOpc = AArch64ISD::GLD1S_SCALED_MERGE_ZERO; 15436 break; 15437 case AArch64ISD::GLD1_SXTW_MERGE_ZERO: 15438 NewOpc = AArch64ISD::GLD1S_SXTW_MERGE_ZERO; 15439 break; 15440 case AArch64ISD::GLD1_SXTW_SCALED_MERGE_ZERO: 15441 NewOpc = AArch64ISD::GLD1S_SXTW_SCALED_MERGE_ZERO; 15442 break; 15443 case AArch64ISD::GLD1_UXTW_MERGE_ZERO: 15444 NewOpc = AArch64ISD::GLD1S_UXTW_MERGE_ZERO; 15445 break; 15446 case AArch64ISD::GLD1_UXTW_SCALED_MERGE_ZERO: 15447 NewOpc = AArch64ISD::GLD1S_UXTW_SCALED_MERGE_ZERO; 15448 break; 15449 case AArch64ISD::GLD1_IMM_MERGE_ZERO: 15450 NewOpc = AArch64ISD::GLD1S_IMM_MERGE_ZERO; 15451 break; 15452 case AArch64ISD::GLDFF1_MERGE_ZERO: 15453 NewOpc = AArch64ISD::GLDFF1S_MERGE_ZERO; 15454 break; 15455 case AArch64ISD::GLDFF1_SCALED_MERGE_ZERO: 15456 NewOpc = AArch64ISD::GLDFF1S_SCALED_MERGE_ZERO; 15457 break; 15458 case AArch64ISD::GLDFF1_SXTW_MERGE_ZERO: 15459 NewOpc = AArch64ISD::GLDFF1S_SXTW_MERGE_ZERO; 15460 break; 15461 case AArch64ISD::GLDFF1_SXTW_SCALED_MERGE_ZERO: 15462 NewOpc = AArch64ISD::GLDFF1S_SXTW_SCALED_MERGE_ZERO; 15463 break; 15464 case AArch64ISD::GLDFF1_UXTW_MERGE_ZERO: 15465 NewOpc = AArch64ISD::GLDFF1S_UXTW_MERGE_ZERO; 15466 break; 15467 case AArch64ISD::GLDFF1_UXTW_SCALED_MERGE_ZERO: 15468 NewOpc = AArch64ISD::GLDFF1S_UXTW_SCALED_MERGE_ZERO; 15469 break; 15470 case AArch64ISD::GLDFF1_IMM_MERGE_ZERO: 15471 NewOpc = AArch64ISD::GLDFF1S_IMM_MERGE_ZERO; 15472 break; 15473 case AArch64ISD::GLDNT1_MERGE_ZERO: 15474 NewOpc = AArch64ISD::GLDNT1S_MERGE_ZERO; 15475 break; 15476 default: 15477 return SDValue(); 15478 } 15479 15480 EVT SignExtSrcVT = cast<VTSDNode>(N->getOperand(1))->getVT(); 15481 EVT SrcMemVT = cast<VTSDNode>(Src->getOperand(MemVTOpNum))->getVT(); 15482 15483 if ((SignExtSrcVT != SrcMemVT) || !Src.hasOneUse()) 15484 return SDValue(); 15485 15486 EVT DstVT = N->getValueType(0); 15487 SDVTList VTs = DAG.getVTList(DstVT, MVT::Other); 15488 15489 SmallVector<SDValue, 5> Ops; 15490 for (unsigned I = 0; I < Src->getNumOperands(); ++I) 15491 Ops.push_back(Src->getOperand(I)); 15492 15493 SDValue ExtLoad = DAG.getNode(NewOpc, SDLoc(N), VTs, Ops); 15494 DCI.CombineTo(N, ExtLoad); 15495 DCI.CombineTo(Src.getNode(), ExtLoad, ExtLoad.getValue(1)); 15496 15497 // Return N so it doesn't get rechecked 15498 return SDValue(N, 0); 15499 } 15500 15501 /// Legalize the gather prefetch (scalar + vector addressing mode) when the 15502 /// offset vector is an unpacked 32-bit scalable vector. The other cases (Offset 15503 /// != nxv2i32) do not need legalization. 15504 static SDValue legalizeSVEGatherPrefetchOffsVec(SDNode *N, SelectionDAG &DAG) { 15505 const unsigned OffsetPos = 4; 15506 SDValue Offset = N->getOperand(OffsetPos); 15507 15508 // Not an unpacked vector, bail out. 15509 if (Offset.getValueType().getSimpleVT().SimpleTy != MVT::nxv2i32) 15510 return SDValue(); 15511 15512 // Extend the unpacked offset vector to 64-bit lanes. 15513 SDLoc DL(N); 15514 Offset = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::nxv2i64, Offset); 15515 SmallVector<SDValue, 5> Ops(N->op_begin(), N->op_end()); 15516 // Replace the offset operand with the 64-bit one. 15517 Ops[OffsetPos] = Offset; 15518 15519 return DAG.getNode(N->getOpcode(), DL, DAG.getVTList(MVT::Other), Ops); 15520 } 15521 15522 /// Combines a node carrying the intrinsic 15523 /// `aarch64_sve_prf<T>_gather_scalar_offset` into a node that uses 15524 /// `aarch64_sve_prfb_gather_uxtw_index` when the scalar offset passed to 15525 /// `aarch64_sve_prf<T>_gather_scalar_offset` is not a valid immediate for the 15526 /// sve gather prefetch instruction with vector plus immediate addressing mode. 15527 static SDValue combineSVEPrefetchVecBaseImmOff(SDNode *N, SelectionDAG &DAG, 15528 unsigned ScalarSizeInBytes) { 15529 const unsigned ImmPos = 4, OffsetPos = 3; 15530 // No need to combine the node if the immediate is valid... 15531 if (isValidImmForSVEVecImmAddrMode(N->getOperand(ImmPos), ScalarSizeInBytes)) 15532 return SDValue(); 15533 15534 // ...otherwise swap the offset base with the offset... 15535 SmallVector<SDValue, 5> Ops(N->op_begin(), N->op_end()); 15536 std::swap(Ops[ImmPos], Ops[OffsetPos]); 15537 // ...and remap the intrinsic `aarch64_sve_prf<T>_gather_scalar_offset` to 15538 // `aarch64_sve_prfb_gather_uxtw_index`. 15539 SDLoc DL(N); 15540 Ops[1] = DAG.getConstant(Intrinsic::aarch64_sve_prfb_gather_uxtw_index, DL, 15541 MVT::i64); 15542 15543 return DAG.getNode(N->getOpcode(), DL, DAG.getVTList(MVT::Other), Ops); 15544 } 15545 15546 SDValue AArch64TargetLowering::PerformDAGCombine(SDNode *N, 15547 DAGCombinerInfo &DCI) const { 15548 SelectionDAG &DAG = DCI.DAG; 15549 switch (N->getOpcode()) { 15550 default: 15551 LLVM_DEBUG(dbgs() << "Custom combining: skipping\n"); 15552 break; 15553 case ISD::ABS: 15554 return performABSCombine(N, DAG, DCI, Subtarget); 15555 case ISD::ADD: 15556 case ISD::SUB: 15557 return performAddSubCombine(N, DCI, DAG); 15558 case ISD::XOR: 15559 return performXorCombine(N, DAG, DCI, Subtarget); 15560 case ISD::MUL: 15561 return performMulCombine(N, DAG, DCI, Subtarget); 15562 case ISD::SINT_TO_FP: 15563 case ISD::UINT_TO_FP: 15564 return performIntToFpCombine(N, DAG, Subtarget); 15565 case ISD::FP_TO_SINT: 15566 case ISD::FP_TO_UINT: 15567 return performFpToIntCombine(N, DAG, DCI, Subtarget); 15568 case ISD::FDIV: 15569 return performFDivCombine(N, DAG, DCI, Subtarget); 15570 case ISD::OR: 15571 return performORCombine(N, DCI, Subtarget); 15572 case ISD::AND: 15573 return performANDCombine(N, DCI); 15574 case ISD::SRL: 15575 return performSRLCombine(N, DCI); 15576 case ISD::INTRINSIC_WO_CHAIN: 15577 return performIntrinsicCombine(N, DCI, Subtarget); 15578 case ISD::ANY_EXTEND: 15579 case ISD::ZERO_EXTEND: 15580 case ISD::SIGN_EXTEND: 15581 return performExtendCombine(N, DCI, DAG); 15582 case ISD::SIGN_EXTEND_INREG: 15583 return performSignExtendInRegCombine(N, DCI, DAG); 15584 case ISD::TRUNCATE: 15585 return performVectorTruncateCombine(N, DCI, DAG); 15586 case ISD::CONCAT_VECTORS: 15587 return performConcatVectorsCombine(N, DCI, DAG); 15588 case ISD::SELECT: 15589 return performSelectCombine(N, DCI); 15590 case ISD::VSELECT: 15591 return performVSelectCombine(N, DCI.DAG); 15592 case ISD::LOAD: 15593 if (performTBISimplification(N->getOperand(1), DCI, DAG)) 15594 return SDValue(N, 0); 15595 break; 15596 case ISD::STORE: 15597 return performSTORECombine(N, DCI, DAG, Subtarget); 15598 case AArch64ISD::BRCOND: 15599 return performBRCONDCombine(N, DCI, DAG); 15600 case AArch64ISD::TBNZ: 15601 case AArch64ISD::TBZ: 15602 return performTBZCombine(N, DCI, DAG); 15603 case AArch64ISD::CSEL: 15604 return performCONDCombine(N, DCI, DAG, 2, 3); 15605 case AArch64ISD::DUP: 15606 return performPostLD1Combine(N, DCI, false); 15607 case AArch64ISD::NVCAST: 15608 return performNVCASTCombine(N); 15609 case AArch64ISD::UZP1: 15610 return performUzpCombine(N, DAG); 15611 case ISD::INSERT_VECTOR_ELT: 15612 return performPostLD1Combine(N, DCI, true); 15613 case ISD::EXTRACT_VECTOR_ELT: 15614 return performExtractVectorEltCombine(N, DAG); 15615 case ISD::VECREDUCE_ADD: 15616 return performVecReduceAddCombine(N, DCI.DAG, Subtarget); 15617 case ISD::INTRINSIC_VOID: 15618 case ISD::INTRINSIC_W_CHAIN: 15619 switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) { 15620 case Intrinsic::aarch64_sve_prfb_gather_scalar_offset: 15621 return combineSVEPrefetchVecBaseImmOff(N, DAG, 1 /*=ScalarSizeInBytes*/); 15622 case Intrinsic::aarch64_sve_prfh_gather_scalar_offset: 15623 return combineSVEPrefetchVecBaseImmOff(N, DAG, 2 /*=ScalarSizeInBytes*/); 15624 case Intrinsic::aarch64_sve_prfw_gather_scalar_offset: 15625 return combineSVEPrefetchVecBaseImmOff(N, DAG, 4 /*=ScalarSizeInBytes*/); 15626 case Intrinsic::aarch64_sve_prfd_gather_scalar_offset: 15627 return combineSVEPrefetchVecBaseImmOff(N, DAG, 8 /*=ScalarSizeInBytes*/); 15628 case Intrinsic::aarch64_sve_prfb_gather_uxtw_index: 15629 case Intrinsic::aarch64_sve_prfb_gather_sxtw_index: 15630 case Intrinsic::aarch64_sve_prfh_gather_uxtw_index: 15631 case Intrinsic::aarch64_sve_prfh_gather_sxtw_index: 15632 case Intrinsic::aarch64_sve_prfw_gather_uxtw_index: 15633 case Intrinsic::aarch64_sve_prfw_gather_sxtw_index: 15634 case Intrinsic::aarch64_sve_prfd_gather_uxtw_index: 15635 case Intrinsic::aarch64_sve_prfd_gather_sxtw_index: 15636 return legalizeSVEGatherPrefetchOffsVec(N, DAG); 15637 case Intrinsic::aarch64_neon_ld2: 15638 case Intrinsic::aarch64_neon_ld3: 15639 case Intrinsic::aarch64_neon_ld4: 15640 case Intrinsic::aarch64_neon_ld1x2: 15641 case Intrinsic::aarch64_neon_ld1x3: 15642 case Intrinsic::aarch64_neon_ld1x4: 15643 case Intrinsic::aarch64_neon_ld2lane: 15644 case Intrinsic::aarch64_neon_ld3lane: 15645 case Intrinsic::aarch64_neon_ld4lane: 15646 case Intrinsic::aarch64_neon_ld2r: 15647 case Intrinsic::aarch64_neon_ld3r: 15648 case Intrinsic::aarch64_neon_ld4r: 15649 case Intrinsic::aarch64_neon_st2: 15650 case Intrinsic::aarch64_neon_st3: 15651 case Intrinsic::aarch64_neon_st4: 15652 case Intrinsic::aarch64_neon_st1x2: 15653 case Intrinsic::aarch64_neon_st1x3: 15654 case Intrinsic::aarch64_neon_st1x4: 15655 case Intrinsic::aarch64_neon_st2lane: 15656 case Intrinsic::aarch64_neon_st3lane: 15657 case Intrinsic::aarch64_neon_st4lane: 15658 return performNEONPostLDSTCombine(N, DCI, DAG); 15659 case Intrinsic::aarch64_sve_ldnt1: 15660 return performLDNT1Combine(N, DAG); 15661 case Intrinsic::aarch64_sve_ld1rq: 15662 return performLD1ReplicateCombine<AArch64ISD::LD1RQ_MERGE_ZERO>(N, DAG); 15663 case Intrinsic::aarch64_sve_ld1ro: 15664 return performLD1ReplicateCombine<AArch64ISD::LD1RO_MERGE_ZERO>(N, DAG); 15665 case Intrinsic::aarch64_sve_ldnt1_gather_scalar_offset: 15666 return performGatherLoadCombine(N, DAG, AArch64ISD::GLDNT1_MERGE_ZERO); 15667 case Intrinsic::aarch64_sve_ldnt1_gather: 15668 return performGatherLoadCombine(N, DAG, AArch64ISD::GLDNT1_MERGE_ZERO); 15669 case Intrinsic::aarch64_sve_ldnt1_gather_index: 15670 return performGatherLoadCombine(N, DAG, 15671 AArch64ISD::GLDNT1_INDEX_MERGE_ZERO); 15672 case Intrinsic::aarch64_sve_ldnt1_gather_uxtw: 15673 return performGatherLoadCombine(N, DAG, AArch64ISD::GLDNT1_MERGE_ZERO); 15674 case Intrinsic::aarch64_sve_ld1: 15675 return performLD1Combine(N, DAG, AArch64ISD::LD1_MERGE_ZERO); 15676 case Intrinsic::aarch64_sve_ldnf1: 15677 return performLD1Combine(N, DAG, AArch64ISD::LDNF1_MERGE_ZERO); 15678 case Intrinsic::aarch64_sve_ldff1: 15679 return performLD1Combine(N, DAG, AArch64ISD::LDFF1_MERGE_ZERO); 15680 case Intrinsic::aarch64_sve_st1: 15681 return performST1Combine(N, DAG); 15682 case Intrinsic::aarch64_sve_stnt1: 15683 return performSTNT1Combine(N, DAG); 15684 case Intrinsic::aarch64_sve_stnt1_scatter_scalar_offset: 15685 return performScatterStoreCombine(N, DAG, AArch64ISD::SSTNT1_PRED); 15686 case Intrinsic::aarch64_sve_stnt1_scatter_uxtw: 15687 return performScatterStoreCombine(N, DAG, AArch64ISD::SSTNT1_PRED); 15688 case Intrinsic::aarch64_sve_stnt1_scatter: 15689 return performScatterStoreCombine(N, DAG, AArch64ISD::SSTNT1_PRED); 15690 case Intrinsic::aarch64_sve_stnt1_scatter_index: 15691 return performScatterStoreCombine(N, DAG, AArch64ISD::SSTNT1_INDEX_PRED); 15692 case Intrinsic::aarch64_sve_ld1_gather: 15693 return performGatherLoadCombine(N, DAG, AArch64ISD::GLD1_MERGE_ZERO); 15694 case Intrinsic::aarch64_sve_ld1_gather_index: 15695 return performGatherLoadCombine(N, DAG, 15696 AArch64ISD::GLD1_SCALED_MERGE_ZERO); 15697 case Intrinsic::aarch64_sve_ld1_gather_sxtw: 15698 return performGatherLoadCombine(N, DAG, AArch64ISD::GLD1_SXTW_MERGE_ZERO, 15699 /*OnlyPackedOffsets=*/false); 15700 case Intrinsic::aarch64_sve_ld1_gather_uxtw: 15701 return performGatherLoadCombine(N, DAG, AArch64ISD::GLD1_UXTW_MERGE_ZERO, 15702 /*OnlyPackedOffsets=*/false); 15703 case Intrinsic::aarch64_sve_ld1_gather_sxtw_index: 15704 return performGatherLoadCombine(N, DAG, 15705 AArch64ISD::GLD1_SXTW_SCALED_MERGE_ZERO, 15706 /*OnlyPackedOffsets=*/false); 15707 case Intrinsic::aarch64_sve_ld1_gather_uxtw_index: 15708 return performGatherLoadCombine(N, DAG, 15709 AArch64ISD::GLD1_UXTW_SCALED_MERGE_ZERO, 15710 /*OnlyPackedOffsets=*/false); 15711 case Intrinsic::aarch64_sve_ld1_gather_scalar_offset: 15712 return performGatherLoadCombine(N, DAG, AArch64ISD::GLD1_IMM_MERGE_ZERO); 15713 case Intrinsic::aarch64_sve_ldff1_gather: 15714 return performGatherLoadCombine(N, DAG, AArch64ISD::GLDFF1_MERGE_ZERO); 15715 case Intrinsic::aarch64_sve_ldff1_gather_index: 15716 return performGatherLoadCombine(N, DAG, 15717 AArch64ISD::GLDFF1_SCALED_MERGE_ZERO); 15718 case Intrinsic::aarch64_sve_ldff1_gather_sxtw: 15719 return performGatherLoadCombine(N, DAG, 15720 AArch64ISD::GLDFF1_SXTW_MERGE_ZERO, 15721 /*OnlyPackedOffsets=*/false); 15722 case Intrinsic::aarch64_sve_ldff1_gather_uxtw: 15723 return performGatherLoadCombine(N, DAG, 15724 AArch64ISD::GLDFF1_UXTW_MERGE_ZERO, 15725 /*OnlyPackedOffsets=*/false); 15726 case Intrinsic::aarch64_sve_ldff1_gather_sxtw_index: 15727 return performGatherLoadCombine(N, DAG, 15728 AArch64ISD::GLDFF1_SXTW_SCALED_MERGE_ZERO, 15729 /*OnlyPackedOffsets=*/false); 15730 case Intrinsic::aarch64_sve_ldff1_gather_uxtw_index: 15731 return performGatherLoadCombine(N, DAG, 15732 AArch64ISD::GLDFF1_UXTW_SCALED_MERGE_ZERO, 15733 /*OnlyPackedOffsets=*/false); 15734 case Intrinsic::aarch64_sve_ldff1_gather_scalar_offset: 15735 return performGatherLoadCombine(N, DAG, 15736 AArch64ISD::GLDFF1_IMM_MERGE_ZERO); 15737 case Intrinsic::aarch64_sve_st1_scatter: 15738 return performScatterStoreCombine(N, DAG, AArch64ISD::SST1_PRED); 15739 case Intrinsic::aarch64_sve_st1_scatter_index: 15740 return performScatterStoreCombine(N, DAG, AArch64ISD::SST1_SCALED_PRED); 15741 case Intrinsic::aarch64_sve_st1_scatter_sxtw: 15742 return performScatterStoreCombine(N, DAG, AArch64ISD::SST1_SXTW_PRED, 15743 /*OnlyPackedOffsets=*/false); 15744 case Intrinsic::aarch64_sve_st1_scatter_uxtw: 15745 return performScatterStoreCombine(N, DAG, AArch64ISD::SST1_UXTW_PRED, 15746 /*OnlyPackedOffsets=*/false); 15747 case Intrinsic::aarch64_sve_st1_scatter_sxtw_index: 15748 return performScatterStoreCombine(N, DAG, 15749 AArch64ISD::SST1_SXTW_SCALED_PRED, 15750 /*OnlyPackedOffsets=*/false); 15751 case Intrinsic::aarch64_sve_st1_scatter_uxtw_index: 15752 return performScatterStoreCombine(N, DAG, 15753 AArch64ISD::SST1_UXTW_SCALED_PRED, 15754 /*OnlyPackedOffsets=*/false); 15755 case Intrinsic::aarch64_sve_st1_scatter_scalar_offset: 15756 return performScatterStoreCombine(N, DAG, AArch64ISD::SST1_IMM_PRED); 15757 case Intrinsic::aarch64_sve_tuple_get: { 15758 SDLoc DL(N); 15759 SDValue Chain = N->getOperand(0); 15760 SDValue Src1 = N->getOperand(2); 15761 SDValue Idx = N->getOperand(3); 15762 15763 uint64_t IdxConst = cast<ConstantSDNode>(Idx)->getZExtValue(); 15764 EVT ResVT = N->getValueType(0); 15765 uint64_t NumLanes = ResVT.getVectorElementCount().getKnownMinValue(); 15766 SDValue ExtIdx = DAG.getVectorIdxConstant(IdxConst * NumLanes, DL); 15767 SDValue Val = 15768 DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, ResVT, Src1, ExtIdx); 15769 return DAG.getMergeValues({Val, Chain}, DL); 15770 } 15771 case Intrinsic::aarch64_sve_tuple_set: { 15772 SDLoc DL(N); 15773 SDValue Chain = N->getOperand(0); 15774 SDValue Tuple = N->getOperand(2); 15775 SDValue Idx = N->getOperand(3); 15776 SDValue Vec = N->getOperand(4); 15777 15778 EVT TupleVT = Tuple.getValueType(); 15779 uint64_t TupleLanes = TupleVT.getVectorElementCount().getKnownMinValue(); 15780 15781 uint64_t IdxConst = cast<ConstantSDNode>(Idx)->getZExtValue(); 15782 uint64_t NumLanes = 15783 Vec.getValueType().getVectorElementCount().getKnownMinValue(); 15784 15785 if ((TupleLanes % NumLanes) != 0) 15786 report_fatal_error("invalid tuple vector!"); 15787 15788 uint64_t NumVecs = TupleLanes / NumLanes; 15789 15790 SmallVector<SDValue, 4> Opnds; 15791 for (unsigned I = 0; I < NumVecs; ++I) { 15792 if (I == IdxConst) 15793 Opnds.push_back(Vec); 15794 else { 15795 SDValue ExtIdx = DAG.getVectorIdxConstant(I * NumLanes, DL); 15796 Opnds.push_back(DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, 15797 Vec.getValueType(), Tuple, ExtIdx)); 15798 } 15799 } 15800 SDValue Concat = 15801 DAG.getNode(ISD::CONCAT_VECTORS, DL, Tuple.getValueType(), Opnds); 15802 return DAG.getMergeValues({Concat, Chain}, DL); 15803 } 15804 case Intrinsic::aarch64_sve_tuple_create2: 15805 case Intrinsic::aarch64_sve_tuple_create3: 15806 case Intrinsic::aarch64_sve_tuple_create4: { 15807 SDLoc DL(N); 15808 SDValue Chain = N->getOperand(0); 15809 15810 SmallVector<SDValue, 4> Opnds; 15811 for (unsigned I = 2; I < N->getNumOperands(); ++I) 15812 Opnds.push_back(N->getOperand(I)); 15813 15814 EVT VT = Opnds[0].getValueType(); 15815 EVT EltVT = VT.getVectorElementType(); 15816 EVT DestVT = EVT::getVectorVT(*DAG.getContext(), EltVT, 15817 VT.getVectorElementCount() * 15818 (N->getNumOperands() - 2)); 15819 SDValue Concat = DAG.getNode(ISD::CONCAT_VECTORS, DL, DestVT, Opnds); 15820 return DAG.getMergeValues({Concat, Chain}, DL); 15821 } 15822 case Intrinsic::aarch64_sve_ld2: 15823 case Intrinsic::aarch64_sve_ld3: 15824 case Intrinsic::aarch64_sve_ld4: { 15825 SDLoc DL(N); 15826 SDValue Chain = N->getOperand(0); 15827 SDValue Mask = N->getOperand(2); 15828 SDValue BasePtr = N->getOperand(3); 15829 SDValue LoadOps[] = {Chain, Mask, BasePtr}; 15830 unsigned IntrinsicID = 15831 cast<ConstantSDNode>(N->getOperand(1))->getZExtValue(); 15832 SDValue Result = 15833 LowerSVEStructLoad(IntrinsicID, LoadOps, N->getValueType(0), DAG, DL); 15834 return DAG.getMergeValues({Result, Chain}, DL); 15835 } 15836 default: 15837 break; 15838 } 15839 break; 15840 case ISD::GlobalAddress: 15841 return performGlobalAddressCombine(N, DAG, Subtarget, getTargetMachine()); 15842 } 15843 return SDValue(); 15844 } 15845 15846 // Check if the return value is used as only a return value, as otherwise 15847 // we can't perform a tail-call. In particular, we need to check for 15848 // target ISD nodes that are returns and any other "odd" constructs 15849 // that the generic analysis code won't necessarily catch. 15850 bool AArch64TargetLowering::isUsedByReturnOnly(SDNode *N, 15851 SDValue &Chain) const { 15852 if (N->getNumValues() != 1) 15853 return false; 15854 if (!N->hasNUsesOfValue(1, 0)) 15855 return false; 15856 15857 SDValue TCChain = Chain; 15858 SDNode *Copy = *N->use_begin(); 15859 if (Copy->getOpcode() == ISD::CopyToReg) { 15860 // If the copy has a glue operand, we conservatively assume it isn't safe to 15861 // perform a tail call. 15862 if (Copy->getOperand(Copy->getNumOperands() - 1).getValueType() == 15863 MVT::Glue) 15864 return false; 15865 TCChain = Copy->getOperand(0); 15866 } else if (Copy->getOpcode() != ISD::FP_EXTEND) 15867 return false; 15868 15869 bool HasRet = false; 15870 for (SDNode *Node : Copy->uses()) { 15871 if (Node->getOpcode() != AArch64ISD::RET_FLAG) 15872 return false; 15873 HasRet = true; 15874 } 15875 15876 if (!HasRet) 15877 return false; 15878 15879 Chain = TCChain; 15880 return true; 15881 } 15882 15883 // Return whether the an instruction can potentially be optimized to a tail 15884 // call. This will cause the optimizers to attempt to move, or duplicate, 15885 // return instructions to help enable tail call optimizations for this 15886 // instruction. 15887 bool AArch64TargetLowering::mayBeEmittedAsTailCall(const CallInst *CI) const { 15888 return CI->isTailCall(); 15889 } 15890 15891 bool AArch64TargetLowering::getIndexedAddressParts(SDNode *Op, SDValue &Base, 15892 SDValue &Offset, 15893 ISD::MemIndexedMode &AM, 15894 bool &IsInc, 15895 SelectionDAG &DAG) const { 15896 if (Op->getOpcode() != ISD::ADD && Op->getOpcode() != ISD::SUB) 15897 return false; 15898 15899 Base = Op->getOperand(0); 15900 // All of the indexed addressing mode instructions take a signed 15901 // 9 bit immediate offset. 15902 if (ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(Op->getOperand(1))) { 15903 int64_t RHSC = RHS->getSExtValue(); 15904 if (Op->getOpcode() == ISD::SUB) 15905 RHSC = -(uint64_t)RHSC; 15906 if (!isInt<9>(RHSC)) 15907 return false; 15908 IsInc = (Op->getOpcode() == ISD::ADD); 15909 Offset = Op->getOperand(1); 15910 return true; 15911 } 15912 return false; 15913 } 15914 15915 bool AArch64TargetLowering::getPreIndexedAddressParts(SDNode *N, SDValue &Base, 15916 SDValue &Offset, 15917 ISD::MemIndexedMode &AM, 15918 SelectionDAG &DAG) const { 15919 EVT VT; 15920 SDValue Ptr; 15921 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) { 15922 VT = LD->getMemoryVT(); 15923 Ptr = LD->getBasePtr(); 15924 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) { 15925 VT = ST->getMemoryVT(); 15926 Ptr = ST->getBasePtr(); 15927 } else 15928 return false; 15929 15930 bool IsInc; 15931 if (!getIndexedAddressParts(Ptr.getNode(), Base, Offset, AM, IsInc, DAG)) 15932 return false; 15933 AM = IsInc ? ISD::PRE_INC : ISD::PRE_DEC; 15934 return true; 15935 } 15936 15937 bool AArch64TargetLowering::getPostIndexedAddressParts( 15938 SDNode *N, SDNode *Op, SDValue &Base, SDValue &Offset, 15939 ISD::MemIndexedMode &AM, SelectionDAG &DAG) const { 15940 EVT VT; 15941 SDValue Ptr; 15942 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) { 15943 VT = LD->getMemoryVT(); 15944 Ptr = LD->getBasePtr(); 15945 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) { 15946 VT = ST->getMemoryVT(); 15947 Ptr = ST->getBasePtr(); 15948 } else 15949 return false; 15950 15951 bool IsInc; 15952 if (!getIndexedAddressParts(Op, Base, Offset, AM, IsInc, DAG)) 15953 return false; 15954 // Post-indexing updates the base, so it's not a valid transform 15955 // if that's not the same as the load's pointer. 15956 if (Ptr != Base) 15957 return false; 15958 AM = IsInc ? ISD::POST_INC : ISD::POST_DEC; 15959 return true; 15960 } 15961 15962 static void ReplaceBITCASTResults(SDNode *N, SmallVectorImpl<SDValue> &Results, 15963 SelectionDAG &DAG) { 15964 SDLoc DL(N); 15965 SDValue Op = N->getOperand(0); 15966 15967 if (N->getValueType(0) != MVT::i16 || 15968 (Op.getValueType() != MVT::f16 && Op.getValueType() != MVT::bf16)) 15969 return; 15970 15971 Op = SDValue( 15972 DAG.getMachineNode(TargetOpcode::INSERT_SUBREG, DL, MVT::f32, 15973 DAG.getUNDEF(MVT::i32), Op, 15974 DAG.getTargetConstant(AArch64::hsub, DL, MVT::i32)), 15975 0); 15976 Op = DAG.getNode(ISD::BITCAST, DL, MVT::i32, Op); 15977 Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i16, Op)); 15978 } 15979 15980 static void ReplaceReductionResults(SDNode *N, 15981 SmallVectorImpl<SDValue> &Results, 15982 SelectionDAG &DAG, unsigned InterOp, 15983 unsigned AcrossOp) { 15984 EVT LoVT, HiVT; 15985 SDValue Lo, Hi; 15986 SDLoc dl(N); 15987 std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(N->getValueType(0)); 15988 std::tie(Lo, Hi) = DAG.SplitVectorOperand(N, 0); 15989 SDValue InterVal = DAG.getNode(InterOp, dl, LoVT, Lo, Hi); 15990 SDValue SplitVal = DAG.getNode(AcrossOp, dl, LoVT, InterVal); 15991 Results.push_back(SplitVal); 15992 } 15993 15994 static std::pair<SDValue, SDValue> splitInt128(SDValue N, SelectionDAG &DAG) { 15995 SDLoc DL(N); 15996 SDValue Lo = DAG.getNode(ISD::TRUNCATE, DL, MVT::i64, N); 15997 SDValue Hi = DAG.getNode(ISD::TRUNCATE, DL, MVT::i64, 15998 DAG.getNode(ISD::SRL, DL, MVT::i128, N, 15999 DAG.getConstant(64, DL, MVT::i64))); 16000 return std::make_pair(Lo, Hi); 16001 } 16002 16003 void AArch64TargetLowering::ReplaceExtractSubVectorResults( 16004 SDNode *N, SmallVectorImpl<SDValue> &Results, SelectionDAG &DAG) const { 16005 SDValue In = N->getOperand(0); 16006 EVT InVT = In.getValueType(); 16007 16008 // Common code will handle these just fine. 16009 if (!InVT.isScalableVector() || !InVT.isInteger()) 16010 return; 16011 16012 SDLoc DL(N); 16013 EVT VT = N->getValueType(0); 16014 16015 // The following checks bail if this is not a halving operation. 16016 16017 ElementCount ResEC = VT.getVectorElementCount(); 16018 16019 if (InVT.getVectorElementCount() != (ResEC * 2)) 16020 return; 16021 16022 auto *CIndex = dyn_cast<ConstantSDNode>(N->getOperand(1)); 16023 if (!CIndex) 16024 return; 16025 16026 unsigned Index = CIndex->getZExtValue(); 16027 if ((Index != 0) && (Index != ResEC.getKnownMinValue())) 16028 return; 16029 16030 unsigned Opcode = (Index == 0) ? AArch64ISD::UUNPKLO : AArch64ISD::UUNPKHI; 16031 EVT ExtendedHalfVT = VT.widenIntegerVectorElementType(*DAG.getContext()); 16032 16033 SDValue Half = DAG.getNode(Opcode, DL, ExtendedHalfVT, N->getOperand(0)); 16034 Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, VT, Half)); 16035 } 16036 16037 // Create an even/odd pair of X registers holding integer value V. 16038 static SDValue createGPRPairNode(SelectionDAG &DAG, SDValue V) { 16039 SDLoc dl(V.getNode()); 16040 SDValue VLo = DAG.getAnyExtOrTrunc(V, dl, MVT::i64); 16041 SDValue VHi = DAG.getAnyExtOrTrunc( 16042 DAG.getNode(ISD::SRL, dl, MVT::i128, V, DAG.getConstant(64, dl, MVT::i64)), 16043 dl, MVT::i64); 16044 if (DAG.getDataLayout().isBigEndian()) 16045 std::swap (VLo, VHi); 16046 SDValue RegClass = 16047 DAG.getTargetConstant(AArch64::XSeqPairsClassRegClassID, dl, MVT::i32); 16048 SDValue SubReg0 = DAG.getTargetConstant(AArch64::sube64, dl, MVT::i32); 16049 SDValue SubReg1 = DAG.getTargetConstant(AArch64::subo64, dl, MVT::i32); 16050 const SDValue Ops[] = { RegClass, VLo, SubReg0, VHi, SubReg1 }; 16051 return SDValue( 16052 DAG.getMachineNode(TargetOpcode::REG_SEQUENCE, dl, MVT::Untyped, Ops), 0); 16053 } 16054 16055 static void ReplaceCMP_SWAP_128Results(SDNode *N, 16056 SmallVectorImpl<SDValue> &Results, 16057 SelectionDAG &DAG, 16058 const AArch64Subtarget *Subtarget) { 16059 assert(N->getValueType(0) == MVT::i128 && 16060 "AtomicCmpSwap on types less than 128 should be legal"); 16061 16062 if (Subtarget->hasLSE() || Subtarget->outlineAtomics()) { 16063 // LSE has a 128-bit compare and swap (CASP), but i128 is not a legal type, 16064 // so lower it here, wrapped in REG_SEQUENCE and EXTRACT_SUBREG. 16065 SDValue Ops[] = { 16066 createGPRPairNode(DAG, N->getOperand(2)), // Compare value 16067 createGPRPairNode(DAG, N->getOperand(3)), // Store value 16068 N->getOperand(1), // Ptr 16069 N->getOperand(0), // Chain in 16070 }; 16071 16072 MachineMemOperand *MemOp = cast<MemSDNode>(N)->getMemOperand(); 16073 16074 unsigned Opcode; 16075 switch (MemOp->getOrdering()) { 16076 case AtomicOrdering::Monotonic: 16077 Opcode = AArch64::CASPX; 16078 break; 16079 case AtomicOrdering::Acquire: 16080 Opcode = AArch64::CASPAX; 16081 break; 16082 case AtomicOrdering::Release: 16083 Opcode = AArch64::CASPLX; 16084 break; 16085 case AtomicOrdering::AcquireRelease: 16086 case AtomicOrdering::SequentiallyConsistent: 16087 Opcode = AArch64::CASPALX; 16088 break; 16089 default: 16090 llvm_unreachable("Unexpected ordering!"); 16091 } 16092 16093 MachineSDNode *CmpSwap = DAG.getMachineNode( 16094 Opcode, SDLoc(N), DAG.getVTList(MVT::Untyped, MVT::Other), Ops); 16095 DAG.setNodeMemRefs(CmpSwap, {MemOp}); 16096 16097 unsigned SubReg1 = AArch64::sube64, SubReg2 = AArch64::subo64; 16098 if (DAG.getDataLayout().isBigEndian()) 16099 std::swap(SubReg1, SubReg2); 16100 SDValue Lo = DAG.getTargetExtractSubreg(SubReg1, SDLoc(N), MVT::i64, 16101 SDValue(CmpSwap, 0)); 16102 SDValue Hi = DAG.getTargetExtractSubreg(SubReg2, SDLoc(N), MVT::i64, 16103 SDValue(CmpSwap, 0)); 16104 Results.push_back( 16105 DAG.getNode(ISD::BUILD_PAIR, SDLoc(N), MVT::i128, Lo, Hi)); 16106 Results.push_back(SDValue(CmpSwap, 1)); // Chain out 16107 return; 16108 } 16109 16110 auto Desired = splitInt128(N->getOperand(2), DAG); 16111 auto New = splitInt128(N->getOperand(3), DAG); 16112 SDValue Ops[] = {N->getOperand(1), Desired.first, Desired.second, 16113 New.first, New.second, N->getOperand(0)}; 16114 SDNode *CmpSwap = DAG.getMachineNode( 16115 AArch64::CMP_SWAP_128, SDLoc(N), 16116 DAG.getVTList(MVT::i64, MVT::i64, MVT::i32, MVT::Other), Ops); 16117 16118 MachineMemOperand *MemOp = cast<MemSDNode>(N)->getMemOperand(); 16119 DAG.setNodeMemRefs(cast<MachineSDNode>(CmpSwap), {MemOp}); 16120 16121 Results.push_back(DAG.getNode(ISD::BUILD_PAIR, SDLoc(N), MVT::i128, 16122 SDValue(CmpSwap, 0), SDValue(CmpSwap, 1))); 16123 Results.push_back(SDValue(CmpSwap, 3)); 16124 } 16125 16126 void AArch64TargetLowering::ReplaceNodeResults( 16127 SDNode *N, SmallVectorImpl<SDValue> &Results, SelectionDAG &DAG) const { 16128 switch (N->getOpcode()) { 16129 default: 16130 llvm_unreachable("Don't know how to custom expand this"); 16131 case ISD::BITCAST: 16132 ReplaceBITCASTResults(N, Results, DAG); 16133 return; 16134 case ISD::VECREDUCE_ADD: 16135 case ISD::VECREDUCE_SMAX: 16136 case ISD::VECREDUCE_SMIN: 16137 case ISD::VECREDUCE_UMAX: 16138 case ISD::VECREDUCE_UMIN: 16139 Results.push_back(LowerVECREDUCE(SDValue(N, 0), DAG)); 16140 return; 16141 16142 case ISD::CTPOP: 16143 if (SDValue Result = LowerCTPOP(SDValue(N, 0), DAG)) 16144 Results.push_back(Result); 16145 return; 16146 case AArch64ISD::SADDV: 16147 ReplaceReductionResults(N, Results, DAG, ISD::ADD, AArch64ISD::SADDV); 16148 return; 16149 case AArch64ISD::UADDV: 16150 ReplaceReductionResults(N, Results, DAG, ISD::ADD, AArch64ISD::UADDV); 16151 return; 16152 case AArch64ISD::SMINV: 16153 ReplaceReductionResults(N, Results, DAG, ISD::SMIN, AArch64ISD::SMINV); 16154 return; 16155 case AArch64ISD::UMINV: 16156 ReplaceReductionResults(N, Results, DAG, ISD::UMIN, AArch64ISD::UMINV); 16157 return; 16158 case AArch64ISD::SMAXV: 16159 ReplaceReductionResults(N, Results, DAG, ISD::SMAX, AArch64ISD::SMAXV); 16160 return; 16161 case AArch64ISD::UMAXV: 16162 ReplaceReductionResults(N, Results, DAG, ISD::UMAX, AArch64ISD::UMAXV); 16163 return; 16164 case ISD::FP_TO_UINT: 16165 case ISD::FP_TO_SINT: 16166 assert(N->getValueType(0) == MVT::i128 && "unexpected illegal conversion"); 16167 // Let normal code take care of it by not adding anything to Results. 16168 return; 16169 case ISD::ATOMIC_CMP_SWAP: 16170 ReplaceCMP_SWAP_128Results(N, Results, DAG, Subtarget); 16171 return; 16172 case ISD::LOAD: { 16173 assert(SDValue(N, 0).getValueType() == MVT::i128 && 16174 "unexpected load's value type"); 16175 LoadSDNode *LoadNode = cast<LoadSDNode>(N); 16176 if (!LoadNode->isVolatile() || LoadNode->getMemoryVT() != MVT::i128) { 16177 // Non-volatile loads are optimized later in AArch64's load/store 16178 // optimizer. 16179 return; 16180 } 16181 16182 SDValue Result = DAG.getMemIntrinsicNode( 16183 AArch64ISD::LDP, SDLoc(N), 16184 DAG.getVTList({MVT::i64, MVT::i64, MVT::Other}), 16185 {LoadNode->getChain(), LoadNode->getBasePtr()}, LoadNode->getMemoryVT(), 16186 LoadNode->getMemOperand()); 16187 16188 SDValue Pair = DAG.getNode(ISD::BUILD_PAIR, SDLoc(N), MVT::i128, 16189 Result.getValue(0), Result.getValue(1)); 16190 Results.append({Pair, Result.getValue(2) /* Chain */}); 16191 return; 16192 } 16193 case ISD::EXTRACT_SUBVECTOR: 16194 ReplaceExtractSubVectorResults(N, Results, DAG); 16195 return; 16196 case ISD::INTRINSIC_WO_CHAIN: { 16197 EVT VT = N->getValueType(0); 16198 assert((VT == MVT::i8 || VT == MVT::i16) && 16199 "custom lowering for unexpected type"); 16200 16201 ConstantSDNode *CN = cast<ConstantSDNode>(N->getOperand(0)); 16202 Intrinsic::ID IntID = static_cast<Intrinsic::ID>(CN->getZExtValue()); 16203 switch (IntID) { 16204 default: 16205 return; 16206 case Intrinsic::aarch64_sve_clasta_n: { 16207 SDLoc DL(N); 16208 auto Op2 = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i32, N->getOperand(2)); 16209 auto V = DAG.getNode(AArch64ISD::CLASTA_N, DL, MVT::i32, 16210 N->getOperand(1), Op2, N->getOperand(3)); 16211 Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, VT, V)); 16212 return; 16213 } 16214 case Intrinsic::aarch64_sve_clastb_n: { 16215 SDLoc DL(N); 16216 auto Op2 = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i32, N->getOperand(2)); 16217 auto V = DAG.getNode(AArch64ISD::CLASTB_N, DL, MVT::i32, 16218 N->getOperand(1), Op2, N->getOperand(3)); 16219 Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, VT, V)); 16220 return; 16221 } 16222 case Intrinsic::aarch64_sve_lasta: { 16223 SDLoc DL(N); 16224 auto V = DAG.getNode(AArch64ISD::LASTA, DL, MVT::i32, 16225 N->getOperand(1), N->getOperand(2)); 16226 Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, VT, V)); 16227 return; 16228 } 16229 case Intrinsic::aarch64_sve_lastb: { 16230 SDLoc DL(N); 16231 auto V = DAG.getNode(AArch64ISD::LASTB, DL, MVT::i32, 16232 N->getOperand(1), N->getOperand(2)); 16233 Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, VT, V)); 16234 return; 16235 } 16236 } 16237 } 16238 } 16239 } 16240 16241 bool AArch64TargetLowering::useLoadStackGuardNode() const { 16242 if (Subtarget->isTargetAndroid() || Subtarget->isTargetFuchsia()) 16243 return TargetLowering::useLoadStackGuardNode(); 16244 return true; 16245 } 16246 16247 unsigned AArch64TargetLowering::combineRepeatedFPDivisors() const { 16248 // Combine multiple FDIVs with the same divisor into multiple FMULs by the 16249 // reciprocal if there are three or more FDIVs. 16250 return 3; 16251 } 16252 16253 TargetLoweringBase::LegalizeTypeAction 16254 AArch64TargetLowering::getPreferredVectorAction(MVT VT) const { 16255 // During type legalization, we prefer to widen v1i8, v1i16, v1i32 to v8i8, 16256 // v4i16, v2i32 instead of to promote. 16257 if (VT == MVT::v1i8 || VT == MVT::v1i16 || VT == MVT::v1i32 || 16258 VT == MVT::v1f32) 16259 return TypeWidenVector; 16260 16261 return TargetLoweringBase::getPreferredVectorAction(VT); 16262 } 16263 16264 // Loads and stores less than 128-bits are already atomic; ones above that 16265 // are doomed anyway, so defer to the default libcall and blame the OS when 16266 // things go wrong. 16267 bool AArch64TargetLowering::shouldExpandAtomicStoreInIR(StoreInst *SI) const { 16268 unsigned Size = SI->getValueOperand()->getType()->getPrimitiveSizeInBits(); 16269 return Size == 128; 16270 } 16271 16272 // Loads and stores less than 128-bits are already atomic; ones above that 16273 // are doomed anyway, so defer to the default libcall and blame the OS when 16274 // things go wrong. 16275 TargetLowering::AtomicExpansionKind 16276 AArch64TargetLowering::shouldExpandAtomicLoadInIR(LoadInst *LI) const { 16277 unsigned Size = LI->getType()->getPrimitiveSizeInBits(); 16278 return Size == 128 ? AtomicExpansionKind::LLSC : AtomicExpansionKind::None; 16279 } 16280 16281 // For the real atomic operations, we have ldxr/stxr up to 128 bits, 16282 TargetLowering::AtomicExpansionKind 16283 AArch64TargetLowering::shouldExpandAtomicRMWInIR(AtomicRMWInst *AI) const { 16284 if (AI->isFloatingPointOperation()) 16285 return AtomicExpansionKind::CmpXChg; 16286 16287 unsigned Size = AI->getType()->getPrimitiveSizeInBits(); 16288 if (Size > 128) return AtomicExpansionKind::None; 16289 // Nand not supported in LSE. 16290 if (AI->getOperation() == AtomicRMWInst::Nand) return AtomicExpansionKind::LLSC; 16291 // Leave 128 bits to LLSC. 16292 if (Subtarget->hasLSE() && Size < 128) 16293 return AtomicExpansionKind::None; 16294 if (Subtarget->outlineAtomics() && Size < 128) { 16295 // [U]Min/[U]Max RWM atomics are used in __sync_fetch_ libcalls so far. 16296 // Don't outline them unless 16297 // (1) high level <atomic> support approved: 16298 // http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2020/p0493r1.pdf 16299 // (2) low level libgcc and compiler-rt support implemented by: 16300 // min/max outline atomics helpers 16301 if (AI->getOperation() != AtomicRMWInst::Min && 16302 AI->getOperation() != AtomicRMWInst::Max && 16303 AI->getOperation() != AtomicRMWInst::UMin && 16304 AI->getOperation() != AtomicRMWInst::UMax) { 16305 return AtomicExpansionKind::None; 16306 } 16307 } 16308 return AtomicExpansionKind::LLSC; 16309 } 16310 16311 TargetLowering::AtomicExpansionKind 16312 AArch64TargetLowering::shouldExpandAtomicCmpXchgInIR( 16313 AtomicCmpXchgInst *AI) const { 16314 // If subtarget has LSE, leave cmpxchg intact for codegen. 16315 if (Subtarget->hasLSE() || Subtarget->outlineAtomics()) 16316 return AtomicExpansionKind::None; 16317 // At -O0, fast-regalloc cannot cope with the live vregs necessary to 16318 // implement cmpxchg without spilling. If the address being exchanged is also 16319 // on the stack and close enough to the spill slot, this can lead to a 16320 // situation where the monitor always gets cleared and the atomic operation 16321 // can never succeed. So at -O0 we need a late-expanded pseudo-inst instead. 16322 if (getTargetMachine().getOptLevel() == CodeGenOpt::None) 16323 return AtomicExpansionKind::None; 16324 return AtomicExpansionKind::LLSC; 16325 } 16326 16327 Value *AArch64TargetLowering::emitLoadLinked(IRBuilder<> &Builder, Value *Addr, 16328 AtomicOrdering Ord) const { 16329 Module *M = Builder.GetInsertBlock()->getParent()->getParent(); 16330 Type *ValTy = cast<PointerType>(Addr->getType())->getElementType(); 16331 bool IsAcquire = isAcquireOrStronger(Ord); 16332 16333 // Since i128 isn't legal and intrinsics don't get type-lowered, the ldrexd 16334 // intrinsic must return {i64, i64} and we have to recombine them into a 16335 // single i128 here. 16336 if (ValTy->getPrimitiveSizeInBits() == 128) { 16337 Intrinsic::ID Int = 16338 IsAcquire ? Intrinsic::aarch64_ldaxp : Intrinsic::aarch64_ldxp; 16339 Function *Ldxr = Intrinsic::getDeclaration(M, Int); 16340 16341 Addr = Builder.CreateBitCast(Addr, Type::getInt8PtrTy(M->getContext())); 16342 Value *LoHi = Builder.CreateCall(Ldxr, Addr, "lohi"); 16343 16344 Value *Lo = Builder.CreateExtractValue(LoHi, 0, "lo"); 16345 Value *Hi = Builder.CreateExtractValue(LoHi, 1, "hi"); 16346 Lo = Builder.CreateZExt(Lo, ValTy, "lo64"); 16347 Hi = Builder.CreateZExt(Hi, ValTy, "hi64"); 16348 return Builder.CreateOr( 16349 Lo, Builder.CreateShl(Hi, ConstantInt::get(ValTy, 64)), "val64"); 16350 } 16351 16352 Type *Tys[] = { Addr->getType() }; 16353 Intrinsic::ID Int = 16354 IsAcquire ? Intrinsic::aarch64_ldaxr : Intrinsic::aarch64_ldxr; 16355 Function *Ldxr = Intrinsic::getDeclaration(M, Int, Tys); 16356 16357 Type *EltTy = cast<PointerType>(Addr->getType())->getElementType(); 16358 16359 const DataLayout &DL = M->getDataLayout(); 16360 IntegerType *IntEltTy = Builder.getIntNTy(DL.getTypeSizeInBits(EltTy)); 16361 Value *Trunc = Builder.CreateTrunc(Builder.CreateCall(Ldxr, Addr), IntEltTy); 16362 16363 return Builder.CreateBitCast(Trunc, EltTy); 16364 } 16365 16366 void AArch64TargetLowering::emitAtomicCmpXchgNoStoreLLBalance( 16367 IRBuilder<> &Builder) const { 16368 Module *M = Builder.GetInsertBlock()->getParent()->getParent(); 16369 Builder.CreateCall(Intrinsic::getDeclaration(M, Intrinsic::aarch64_clrex)); 16370 } 16371 16372 Value *AArch64TargetLowering::emitStoreConditional(IRBuilder<> &Builder, 16373 Value *Val, Value *Addr, 16374 AtomicOrdering Ord) const { 16375 Module *M = Builder.GetInsertBlock()->getParent()->getParent(); 16376 bool IsRelease = isReleaseOrStronger(Ord); 16377 16378 // Since the intrinsics must have legal type, the i128 intrinsics take two 16379 // parameters: "i64, i64". We must marshal Val into the appropriate form 16380 // before the call. 16381 if (Val->getType()->getPrimitiveSizeInBits() == 128) { 16382 Intrinsic::ID Int = 16383 IsRelease ? Intrinsic::aarch64_stlxp : Intrinsic::aarch64_stxp; 16384 Function *Stxr = Intrinsic::getDeclaration(M, Int); 16385 Type *Int64Ty = Type::getInt64Ty(M->getContext()); 16386 16387 Value *Lo = Builder.CreateTrunc(Val, Int64Ty, "lo"); 16388 Value *Hi = Builder.CreateTrunc(Builder.CreateLShr(Val, 64), Int64Ty, "hi"); 16389 Addr = Builder.CreateBitCast(Addr, Type::getInt8PtrTy(M->getContext())); 16390 return Builder.CreateCall(Stxr, {Lo, Hi, Addr}); 16391 } 16392 16393 Intrinsic::ID Int = 16394 IsRelease ? Intrinsic::aarch64_stlxr : Intrinsic::aarch64_stxr; 16395 Type *Tys[] = { Addr->getType() }; 16396 Function *Stxr = Intrinsic::getDeclaration(M, Int, Tys); 16397 16398 const DataLayout &DL = M->getDataLayout(); 16399 IntegerType *IntValTy = Builder.getIntNTy(DL.getTypeSizeInBits(Val->getType())); 16400 Val = Builder.CreateBitCast(Val, IntValTy); 16401 16402 return Builder.CreateCall(Stxr, 16403 {Builder.CreateZExtOrBitCast( 16404 Val, Stxr->getFunctionType()->getParamType(0)), 16405 Addr}); 16406 } 16407 16408 bool AArch64TargetLowering::functionArgumentNeedsConsecutiveRegisters( 16409 Type *Ty, CallingConv::ID CallConv, bool isVarArg) const { 16410 if (Ty->isArrayTy()) 16411 return true; 16412 16413 const TypeSize &TySize = Ty->getPrimitiveSizeInBits(); 16414 if (TySize.isScalable() && TySize.getKnownMinSize() > 128) 16415 return true; 16416 16417 return false; 16418 } 16419 16420 bool AArch64TargetLowering::shouldNormalizeToSelectSequence(LLVMContext &, 16421 EVT) const { 16422 return false; 16423 } 16424 16425 static Value *UseTlsOffset(IRBuilder<> &IRB, unsigned Offset) { 16426 Module *M = IRB.GetInsertBlock()->getParent()->getParent(); 16427 Function *ThreadPointerFunc = 16428 Intrinsic::getDeclaration(M, Intrinsic::thread_pointer); 16429 return IRB.CreatePointerCast( 16430 IRB.CreateConstGEP1_32(IRB.getInt8Ty(), IRB.CreateCall(ThreadPointerFunc), 16431 Offset), 16432 IRB.getInt8PtrTy()->getPointerTo(0)); 16433 } 16434 16435 Value *AArch64TargetLowering::getIRStackGuard(IRBuilder<> &IRB) const { 16436 // Android provides a fixed TLS slot for the stack cookie. See the definition 16437 // of TLS_SLOT_STACK_GUARD in 16438 // https://android.googlesource.com/platform/bionic/+/master/libc/private/bionic_tls.h 16439 if (Subtarget->isTargetAndroid()) 16440 return UseTlsOffset(IRB, 0x28); 16441 16442 // Fuchsia is similar. 16443 // <zircon/tls.h> defines ZX_TLS_STACK_GUARD_OFFSET with this value. 16444 if (Subtarget->isTargetFuchsia()) 16445 return UseTlsOffset(IRB, -0x10); 16446 16447 return TargetLowering::getIRStackGuard(IRB); 16448 } 16449 16450 void AArch64TargetLowering::insertSSPDeclarations(Module &M) const { 16451 // MSVC CRT provides functionalities for stack protection. 16452 if (Subtarget->getTargetTriple().isWindowsMSVCEnvironment()) { 16453 // MSVC CRT has a global variable holding security cookie. 16454 M.getOrInsertGlobal("__security_cookie", 16455 Type::getInt8PtrTy(M.getContext())); 16456 16457 // MSVC CRT has a function to validate security cookie. 16458 FunctionCallee SecurityCheckCookie = M.getOrInsertFunction( 16459 "__security_check_cookie", Type::getVoidTy(M.getContext()), 16460 Type::getInt8PtrTy(M.getContext())); 16461 if (Function *F = dyn_cast<Function>(SecurityCheckCookie.getCallee())) { 16462 F->setCallingConv(CallingConv::Win64); 16463 F->addAttribute(1, Attribute::AttrKind::InReg); 16464 } 16465 return; 16466 } 16467 TargetLowering::insertSSPDeclarations(M); 16468 } 16469 16470 Value *AArch64TargetLowering::getSDagStackGuard(const Module &M) const { 16471 // MSVC CRT has a global variable holding security cookie. 16472 if (Subtarget->getTargetTriple().isWindowsMSVCEnvironment()) 16473 return M.getGlobalVariable("__security_cookie"); 16474 return TargetLowering::getSDagStackGuard(M); 16475 } 16476 16477 Function *AArch64TargetLowering::getSSPStackGuardCheck(const Module &M) const { 16478 // MSVC CRT has a function to validate security cookie. 16479 if (Subtarget->getTargetTriple().isWindowsMSVCEnvironment()) 16480 return M.getFunction("__security_check_cookie"); 16481 return TargetLowering::getSSPStackGuardCheck(M); 16482 } 16483 16484 Value *AArch64TargetLowering::getSafeStackPointerLocation(IRBuilder<> &IRB) const { 16485 // Android provides a fixed TLS slot for the SafeStack pointer. See the 16486 // definition of TLS_SLOT_SAFESTACK in 16487 // https://android.googlesource.com/platform/bionic/+/master/libc/private/bionic_tls.h 16488 if (Subtarget->isTargetAndroid()) 16489 return UseTlsOffset(IRB, 0x48); 16490 16491 // Fuchsia is similar. 16492 // <zircon/tls.h> defines ZX_TLS_UNSAFE_SP_OFFSET with this value. 16493 if (Subtarget->isTargetFuchsia()) 16494 return UseTlsOffset(IRB, -0x8); 16495 16496 return TargetLowering::getSafeStackPointerLocation(IRB); 16497 } 16498 16499 bool AArch64TargetLowering::isMaskAndCmp0FoldingBeneficial( 16500 const Instruction &AndI) const { 16501 // Only sink 'and' mask to cmp use block if it is masking a single bit, since 16502 // this is likely to be fold the and/cmp/br into a single tbz instruction. It 16503 // may be beneficial to sink in other cases, but we would have to check that 16504 // the cmp would not get folded into the br to form a cbz for these to be 16505 // beneficial. 16506 ConstantInt* Mask = dyn_cast<ConstantInt>(AndI.getOperand(1)); 16507 if (!Mask) 16508 return false; 16509 return Mask->getValue().isPowerOf2(); 16510 } 16511 16512 bool AArch64TargetLowering:: 16513 shouldProduceAndByConstByHoistingConstFromShiftsLHSOfAnd( 16514 SDValue X, ConstantSDNode *XC, ConstantSDNode *CC, SDValue Y, 16515 unsigned OldShiftOpcode, unsigned NewShiftOpcode, 16516 SelectionDAG &DAG) const { 16517 // Does baseline recommend not to perform the fold by default? 16518 if (!TargetLowering::shouldProduceAndByConstByHoistingConstFromShiftsLHSOfAnd( 16519 X, XC, CC, Y, OldShiftOpcode, NewShiftOpcode, DAG)) 16520 return false; 16521 // Else, if this is a vector shift, prefer 'shl'. 16522 return X.getValueType().isScalarInteger() || NewShiftOpcode == ISD::SHL; 16523 } 16524 16525 bool AArch64TargetLowering::shouldExpandShift(SelectionDAG &DAG, 16526 SDNode *N) const { 16527 if (DAG.getMachineFunction().getFunction().hasMinSize() && 16528 !Subtarget->isTargetWindows() && !Subtarget->isTargetDarwin()) 16529 return false; 16530 return true; 16531 } 16532 16533 void AArch64TargetLowering::initializeSplitCSR(MachineBasicBlock *Entry) const { 16534 // Update IsSplitCSR in AArch64unctionInfo. 16535 AArch64FunctionInfo *AFI = Entry->getParent()->getInfo<AArch64FunctionInfo>(); 16536 AFI->setIsSplitCSR(true); 16537 } 16538 16539 void AArch64TargetLowering::insertCopiesSplitCSR( 16540 MachineBasicBlock *Entry, 16541 const SmallVectorImpl<MachineBasicBlock *> &Exits) const { 16542 const AArch64RegisterInfo *TRI = Subtarget->getRegisterInfo(); 16543 const MCPhysReg *IStart = TRI->getCalleeSavedRegsViaCopy(Entry->getParent()); 16544 if (!IStart) 16545 return; 16546 16547 const TargetInstrInfo *TII = Subtarget->getInstrInfo(); 16548 MachineRegisterInfo *MRI = &Entry->getParent()->getRegInfo(); 16549 MachineBasicBlock::iterator MBBI = Entry->begin(); 16550 for (const MCPhysReg *I = IStart; *I; ++I) { 16551 const TargetRegisterClass *RC = nullptr; 16552 if (AArch64::GPR64RegClass.contains(*I)) 16553 RC = &AArch64::GPR64RegClass; 16554 else if (AArch64::FPR64RegClass.contains(*I)) 16555 RC = &AArch64::FPR64RegClass; 16556 else 16557 llvm_unreachable("Unexpected register class in CSRsViaCopy!"); 16558 16559 Register NewVR = MRI->createVirtualRegister(RC); 16560 // Create copy from CSR to a virtual register. 16561 // FIXME: this currently does not emit CFI pseudo-instructions, it works 16562 // fine for CXX_FAST_TLS since the C++-style TLS access functions should be 16563 // nounwind. If we want to generalize this later, we may need to emit 16564 // CFI pseudo-instructions. 16565 assert(Entry->getParent()->getFunction().hasFnAttribute( 16566 Attribute::NoUnwind) && 16567 "Function should be nounwind in insertCopiesSplitCSR!"); 16568 Entry->addLiveIn(*I); 16569 BuildMI(*Entry, MBBI, DebugLoc(), TII->get(TargetOpcode::COPY), NewVR) 16570 .addReg(*I); 16571 16572 // Insert the copy-back instructions right before the terminator. 16573 for (auto *Exit : Exits) 16574 BuildMI(*Exit, Exit->getFirstTerminator(), DebugLoc(), 16575 TII->get(TargetOpcode::COPY), *I) 16576 .addReg(NewVR); 16577 } 16578 } 16579 16580 bool AArch64TargetLowering::isIntDivCheap(EVT VT, AttributeList Attr) const { 16581 // Integer division on AArch64 is expensive. However, when aggressively 16582 // optimizing for code size, we prefer to use a div instruction, as it is 16583 // usually smaller than the alternative sequence. 16584 // The exception to this is vector division. Since AArch64 doesn't have vector 16585 // integer division, leaving the division as-is is a loss even in terms of 16586 // size, because it will have to be scalarized, while the alternative code 16587 // sequence can be performed in vector form. 16588 bool OptSize = Attr.hasFnAttribute(Attribute::MinSize); 16589 return OptSize && !VT.isVector(); 16590 } 16591 16592 bool AArch64TargetLowering::preferIncOfAddToSubOfNot(EVT VT) const { 16593 // We want inc-of-add for scalars and sub-of-not for vectors. 16594 return VT.isScalarInteger(); 16595 } 16596 16597 bool AArch64TargetLowering::enableAggressiveFMAFusion(EVT VT) const { 16598 return Subtarget->hasAggressiveFMA() && VT.isFloatingPoint(); 16599 } 16600 16601 unsigned 16602 AArch64TargetLowering::getVaListSizeInBits(const DataLayout &DL) const { 16603 if (Subtarget->isTargetDarwin() || Subtarget->isTargetWindows()) 16604 return getPointerTy(DL).getSizeInBits(); 16605 16606 return 3 * getPointerTy(DL).getSizeInBits() + 2 * 32; 16607 } 16608 16609 void AArch64TargetLowering::finalizeLowering(MachineFunction &MF) const { 16610 MF.getFrameInfo().computeMaxCallFrameSize(MF); 16611 TargetLoweringBase::finalizeLowering(MF); 16612 } 16613 16614 // Unlike X86, we let frame lowering assign offsets to all catch objects. 16615 bool AArch64TargetLowering::needsFixedCatchObjects() const { 16616 return false; 16617 } 16618 16619 bool AArch64TargetLowering::shouldLocalize( 16620 const MachineInstr &MI, const TargetTransformInfo *TTI) const { 16621 switch (MI.getOpcode()) { 16622 case TargetOpcode::G_GLOBAL_VALUE: { 16623 // On Darwin, TLS global vars get selected into function calls, which 16624 // we don't want localized, as they can get moved into the middle of a 16625 // another call sequence. 16626 const GlobalValue &GV = *MI.getOperand(1).getGlobal(); 16627 if (GV.isThreadLocal() && Subtarget->isTargetMachO()) 16628 return false; 16629 break; 16630 } 16631 // If we legalized G_GLOBAL_VALUE into ADRP + G_ADD_LOW, mark both as being 16632 // localizable. 16633 case AArch64::ADRP: 16634 case AArch64::G_ADD_LOW: 16635 return true; 16636 default: 16637 break; 16638 } 16639 return TargetLoweringBase::shouldLocalize(MI, TTI); 16640 } 16641 16642 bool AArch64TargetLowering::fallBackToDAGISel(const Instruction &Inst) const { 16643 if (isa<ScalableVectorType>(Inst.getType())) 16644 return true; 16645 16646 for (unsigned i = 0; i < Inst.getNumOperands(); ++i) 16647 if (isa<ScalableVectorType>(Inst.getOperand(i)->getType())) 16648 return true; 16649 16650 if (const AllocaInst *AI = dyn_cast<AllocaInst>(&Inst)) { 16651 if (isa<ScalableVectorType>(AI->getAllocatedType())) 16652 return true; 16653 } 16654 16655 return false; 16656 } 16657 16658 // Return the largest legal scalable vector type that matches VT's element type. 16659 static EVT getContainerForFixedLengthVector(SelectionDAG &DAG, EVT VT) { 16660 assert(VT.isFixedLengthVector() && 16661 DAG.getTargetLoweringInfo().isTypeLegal(VT) && 16662 "Expected legal fixed length vector!"); 16663 switch (VT.getVectorElementType().getSimpleVT().SimpleTy) { 16664 default: 16665 llvm_unreachable("unexpected element type for SVE container"); 16666 case MVT::i8: 16667 return EVT(MVT::nxv16i8); 16668 case MVT::i16: 16669 return EVT(MVT::nxv8i16); 16670 case MVT::i32: 16671 return EVT(MVT::nxv4i32); 16672 case MVT::i64: 16673 return EVT(MVT::nxv2i64); 16674 case MVT::f16: 16675 return EVT(MVT::nxv8f16); 16676 case MVT::f32: 16677 return EVT(MVT::nxv4f32); 16678 case MVT::f64: 16679 return EVT(MVT::nxv2f64); 16680 } 16681 } 16682 16683 // Return a PTRUE with active lanes corresponding to the extent of VT. 16684 static SDValue getPredicateForFixedLengthVector(SelectionDAG &DAG, SDLoc &DL, 16685 EVT VT) { 16686 assert(VT.isFixedLengthVector() && 16687 DAG.getTargetLoweringInfo().isTypeLegal(VT) && 16688 "Expected legal fixed length vector!"); 16689 16690 int PgPattern; 16691 switch (VT.getVectorNumElements()) { 16692 default: 16693 llvm_unreachable("unexpected element count for SVE predicate"); 16694 case 1: 16695 PgPattern = AArch64SVEPredPattern::vl1; 16696 break; 16697 case 2: 16698 PgPattern = AArch64SVEPredPattern::vl2; 16699 break; 16700 case 4: 16701 PgPattern = AArch64SVEPredPattern::vl4; 16702 break; 16703 case 8: 16704 PgPattern = AArch64SVEPredPattern::vl8; 16705 break; 16706 case 16: 16707 PgPattern = AArch64SVEPredPattern::vl16; 16708 break; 16709 case 32: 16710 PgPattern = AArch64SVEPredPattern::vl32; 16711 break; 16712 case 64: 16713 PgPattern = AArch64SVEPredPattern::vl64; 16714 break; 16715 case 128: 16716 PgPattern = AArch64SVEPredPattern::vl128; 16717 break; 16718 case 256: 16719 PgPattern = AArch64SVEPredPattern::vl256; 16720 break; 16721 } 16722 16723 // TODO: For vectors that are exactly getMaxSVEVectorSizeInBits big, we can 16724 // use AArch64SVEPredPattern::all, which can enable the use of unpredicated 16725 // variants of instructions when available. 16726 16727 MVT MaskVT; 16728 switch (VT.getVectorElementType().getSimpleVT().SimpleTy) { 16729 default: 16730 llvm_unreachable("unexpected element type for SVE predicate"); 16731 case MVT::i8: 16732 MaskVT = MVT::nxv16i1; 16733 break; 16734 case MVT::i16: 16735 case MVT::f16: 16736 MaskVT = MVT::nxv8i1; 16737 break; 16738 case MVT::i32: 16739 case MVT::f32: 16740 MaskVT = MVT::nxv4i1; 16741 break; 16742 case MVT::i64: 16743 case MVT::f64: 16744 MaskVT = MVT::nxv2i1; 16745 break; 16746 } 16747 16748 return DAG.getNode(AArch64ISD::PTRUE, DL, MaskVT, 16749 DAG.getTargetConstant(PgPattern, DL, MVT::i64)); 16750 } 16751 16752 static SDValue getPredicateForScalableVector(SelectionDAG &DAG, SDLoc &DL, 16753 EVT VT) { 16754 assert(VT.isScalableVector() && DAG.getTargetLoweringInfo().isTypeLegal(VT) && 16755 "Expected legal scalable vector!"); 16756 auto PredTy = VT.changeVectorElementType(MVT::i1); 16757 return getPTrue(DAG, DL, PredTy, AArch64SVEPredPattern::all); 16758 } 16759 16760 static SDValue getPredicateForVector(SelectionDAG &DAG, SDLoc &DL, EVT VT) { 16761 if (VT.isFixedLengthVector()) 16762 return getPredicateForFixedLengthVector(DAG, DL, VT); 16763 16764 return getPredicateForScalableVector(DAG, DL, VT); 16765 } 16766 16767 // Grow V to consume an entire SVE register. 16768 static SDValue convertToScalableVector(SelectionDAG &DAG, EVT VT, SDValue V) { 16769 assert(VT.isScalableVector() && 16770 "Expected to convert into a scalable vector!"); 16771 assert(V.getValueType().isFixedLengthVector() && 16772 "Expected a fixed length vector operand!"); 16773 SDLoc DL(V); 16774 SDValue Zero = DAG.getConstant(0, DL, MVT::i64); 16775 return DAG.getNode(ISD::INSERT_SUBVECTOR, DL, VT, DAG.getUNDEF(VT), V, Zero); 16776 } 16777 16778 // Shrink V so it's just big enough to maintain a VT's worth of data. 16779 static SDValue convertFromScalableVector(SelectionDAG &DAG, EVT VT, SDValue V) { 16780 assert(VT.isFixedLengthVector() && 16781 "Expected to convert into a fixed length vector!"); 16782 assert(V.getValueType().isScalableVector() && 16783 "Expected a scalable vector operand!"); 16784 SDLoc DL(V); 16785 SDValue Zero = DAG.getConstant(0, DL, MVT::i64); 16786 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, V, Zero); 16787 } 16788 16789 // Convert all fixed length vector loads larger than NEON to masked_loads. 16790 SDValue AArch64TargetLowering::LowerFixedLengthVectorLoadToSVE( 16791 SDValue Op, SelectionDAG &DAG) const { 16792 auto Load = cast<LoadSDNode>(Op); 16793 16794 SDLoc DL(Op); 16795 EVT VT = Op.getValueType(); 16796 EVT ContainerVT = getContainerForFixedLengthVector(DAG, VT); 16797 16798 auto NewLoad = DAG.getMaskedLoad( 16799 ContainerVT, DL, Load->getChain(), Load->getBasePtr(), Load->getOffset(), 16800 getPredicateForFixedLengthVector(DAG, DL, VT), DAG.getUNDEF(ContainerVT), 16801 Load->getMemoryVT(), Load->getMemOperand(), Load->getAddressingMode(), 16802 Load->getExtensionType()); 16803 16804 auto Result = convertFromScalableVector(DAG, VT, NewLoad); 16805 SDValue MergedValues[2] = {Result, Load->getChain()}; 16806 return DAG.getMergeValues(MergedValues, DL); 16807 } 16808 16809 // Convert all fixed length vector stores larger than NEON to masked_stores. 16810 SDValue AArch64TargetLowering::LowerFixedLengthVectorStoreToSVE( 16811 SDValue Op, SelectionDAG &DAG) const { 16812 auto Store = cast<StoreSDNode>(Op); 16813 16814 SDLoc DL(Op); 16815 EVT VT = Store->getValue().getValueType(); 16816 EVT ContainerVT = getContainerForFixedLengthVector(DAG, VT); 16817 16818 auto NewValue = convertToScalableVector(DAG, ContainerVT, Store->getValue()); 16819 return DAG.getMaskedStore( 16820 Store->getChain(), DL, NewValue, Store->getBasePtr(), Store->getOffset(), 16821 getPredicateForFixedLengthVector(DAG, DL, VT), Store->getMemoryVT(), 16822 Store->getMemOperand(), Store->getAddressingMode(), 16823 Store->isTruncatingStore()); 16824 } 16825 16826 SDValue AArch64TargetLowering::LowerFixedLengthVectorIntDivideToSVE( 16827 SDValue Op, SelectionDAG &DAG) const { 16828 SDLoc dl(Op); 16829 EVT VT = Op.getValueType(); 16830 EVT EltVT = VT.getVectorElementType(); 16831 16832 bool Signed = Op.getOpcode() == ISD::SDIV; 16833 unsigned PredOpcode = Signed ? AArch64ISD::SDIV_PRED : AArch64ISD::UDIV_PRED; 16834 16835 // Scalable vector i32/i64 DIV is supported. 16836 if (EltVT == MVT::i32 || EltVT == MVT::i64) 16837 return LowerToPredicatedOp(Op, DAG, PredOpcode, /*OverrideNEON=*/true); 16838 16839 // Scalable vector i8/i16 DIV is not supported. Promote it to i32. 16840 EVT ContainerVT = getContainerForFixedLengthVector(DAG, VT); 16841 EVT HalfVT = VT.getHalfNumVectorElementsVT(*DAG.getContext()); 16842 EVT FixedWidenedVT = HalfVT.widenIntegerVectorElementType(*DAG.getContext()); 16843 EVT ScalableWidenedVT = getContainerForFixedLengthVector(DAG, FixedWidenedVT); 16844 16845 // Convert the operands to scalable vectors. 16846 SDValue Op0 = convertToScalableVector(DAG, ContainerVT, Op.getOperand(0)); 16847 SDValue Op1 = convertToScalableVector(DAG, ContainerVT, Op.getOperand(1)); 16848 16849 // Extend the scalable operands. 16850 unsigned UnpkLo = Signed ? AArch64ISD::SUNPKLO : AArch64ISD::UUNPKLO; 16851 unsigned UnpkHi = Signed ? AArch64ISD::SUNPKHI : AArch64ISD::UUNPKHI; 16852 SDValue Op0Lo = DAG.getNode(UnpkLo, dl, ScalableWidenedVT, Op0); 16853 SDValue Op1Lo = DAG.getNode(UnpkLo, dl, ScalableWidenedVT, Op1); 16854 SDValue Op0Hi = DAG.getNode(UnpkHi, dl, ScalableWidenedVT, Op0); 16855 SDValue Op1Hi = DAG.getNode(UnpkHi, dl, ScalableWidenedVT, Op1); 16856 16857 // Convert back to fixed vectors so the DIV can be further lowered. 16858 Op0Lo = convertFromScalableVector(DAG, FixedWidenedVT, Op0Lo); 16859 Op1Lo = convertFromScalableVector(DAG, FixedWidenedVT, Op1Lo); 16860 Op0Hi = convertFromScalableVector(DAG, FixedWidenedVT, Op0Hi); 16861 Op1Hi = convertFromScalableVector(DAG, FixedWidenedVT, Op1Hi); 16862 SDValue ResultLo = DAG.getNode(Op.getOpcode(), dl, FixedWidenedVT, 16863 Op0Lo, Op1Lo); 16864 SDValue ResultHi = DAG.getNode(Op.getOpcode(), dl, FixedWidenedVT, 16865 Op0Hi, Op1Hi); 16866 16867 // Convert again to scalable vectors to truncate. 16868 ResultLo = convertToScalableVector(DAG, ScalableWidenedVT, ResultLo); 16869 ResultHi = convertToScalableVector(DAG, ScalableWidenedVT, ResultHi); 16870 SDValue ScalableResult = DAG.getNode(AArch64ISD::UZP1, dl, ContainerVT, 16871 ResultLo, ResultHi); 16872 16873 return convertFromScalableVector(DAG, VT, ScalableResult); 16874 } 16875 16876 SDValue AArch64TargetLowering::LowerFixedLengthVectorIntExtendToSVE( 16877 SDValue Op, SelectionDAG &DAG) const { 16878 EVT VT = Op.getValueType(); 16879 assert(VT.isFixedLengthVector() && "Expected fixed length vector type!"); 16880 16881 SDLoc DL(Op); 16882 SDValue Val = Op.getOperand(0); 16883 EVT ContainerVT = getContainerForFixedLengthVector(DAG, Val.getValueType()); 16884 Val = convertToScalableVector(DAG, ContainerVT, Val); 16885 16886 bool Signed = Op.getOpcode() == ISD::SIGN_EXTEND; 16887 unsigned ExtendOpc = Signed ? AArch64ISD::SUNPKLO : AArch64ISD::UUNPKLO; 16888 16889 // Repeatedly unpack Val until the result is of the desired element type. 16890 switch (ContainerVT.getSimpleVT().SimpleTy) { 16891 default: 16892 llvm_unreachable("unimplemented container type"); 16893 case MVT::nxv16i8: 16894 Val = DAG.getNode(ExtendOpc, DL, MVT::nxv8i16, Val); 16895 if (VT.getVectorElementType() == MVT::i16) 16896 break; 16897 LLVM_FALLTHROUGH; 16898 case MVT::nxv8i16: 16899 Val = DAG.getNode(ExtendOpc, DL, MVT::nxv4i32, Val); 16900 if (VT.getVectorElementType() == MVT::i32) 16901 break; 16902 LLVM_FALLTHROUGH; 16903 case MVT::nxv4i32: 16904 Val = DAG.getNode(ExtendOpc, DL, MVT::nxv2i64, Val); 16905 assert(VT.getVectorElementType() == MVT::i64 && "Unexpected element type!"); 16906 break; 16907 } 16908 16909 return convertFromScalableVector(DAG, VT, Val); 16910 } 16911 16912 SDValue AArch64TargetLowering::LowerFixedLengthVectorTruncateToSVE( 16913 SDValue Op, SelectionDAG &DAG) const { 16914 EVT VT = Op.getValueType(); 16915 assert(VT.isFixedLengthVector() && "Expected fixed length vector type!"); 16916 16917 SDLoc DL(Op); 16918 SDValue Val = Op.getOperand(0); 16919 EVT ContainerVT = getContainerForFixedLengthVector(DAG, Val.getValueType()); 16920 Val = convertToScalableVector(DAG, ContainerVT, Val); 16921 16922 // Repeatedly truncate Val until the result is of the desired element type. 16923 switch (ContainerVT.getSimpleVT().SimpleTy) { 16924 default: 16925 llvm_unreachable("unimplemented container type"); 16926 case MVT::nxv2i64: 16927 Val = DAG.getNode(ISD::BITCAST, DL, MVT::nxv4i32, Val); 16928 Val = DAG.getNode(AArch64ISD::UZP1, DL, MVT::nxv4i32, Val, Val); 16929 if (VT.getVectorElementType() == MVT::i32) 16930 break; 16931 LLVM_FALLTHROUGH; 16932 case MVT::nxv4i32: 16933 Val = DAG.getNode(ISD::BITCAST, DL, MVT::nxv8i16, Val); 16934 Val = DAG.getNode(AArch64ISD::UZP1, DL, MVT::nxv8i16, Val, Val); 16935 if (VT.getVectorElementType() == MVT::i16) 16936 break; 16937 LLVM_FALLTHROUGH; 16938 case MVT::nxv8i16: 16939 Val = DAG.getNode(ISD::BITCAST, DL, MVT::nxv16i8, Val); 16940 Val = DAG.getNode(AArch64ISD::UZP1, DL, MVT::nxv16i8, Val, Val); 16941 assert(VT.getVectorElementType() == MVT::i8 && "Unexpected element type!"); 16942 break; 16943 } 16944 16945 return convertFromScalableVector(DAG, VT, Val); 16946 } 16947 16948 // Convert vector operation 'Op' to an equivalent predicated operation whereby 16949 // the original operation's type is used to construct a suitable predicate. 16950 // NOTE: The results for inactive lanes are undefined. 16951 SDValue AArch64TargetLowering::LowerToPredicatedOp(SDValue Op, 16952 SelectionDAG &DAG, 16953 unsigned NewOp, 16954 bool OverrideNEON) const { 16955 EVT VT = Op.getValueType(); 16956 SDLoc DL(Op); 16957 auto Pg = getPredicateForVector(DAG, DL, VT); 16958 16959 if (useSVEForFixedLengthVectorVT(VT, OverrideNEON)) { 16960 EVT ContainerVT = getContainerForFixedLengthVector(DAG, VT); 16961 16962 // Create list of operands by converting existing ones to scalable types. 16963 SmallVector<SDValue, 4> Operands = {Pg}; 16964 for (const SDValue &V : Op->op_values()) { 16965 if (isa<CondCodeSDNode>(V)) { 16966 Operands.push_back(V); 16967 continue; 16968 } 16969 16970 if (const VTSDNode *VTNode = dyn_cast<VTSDNode>(V)) { 16971 EVT VTArg = VTNode->getVT().getVectorElementType(); 16972 EVT NewVTArg = ContainerVT.changeVectorElementType(VTArg); 16973 Operands.push_back(DAG.getValueType(NewVTArg)); 16974 continue; 16975 } 16976 16977 assert(useSVEForFixedLengthVectorVT(V.getValueType(), OverrideNEON) && 16978 "Only fixed length vectors are supported!"); 16979 Operands.push_back(convertToScalableVector(DAG, ContainerVT, V)); 16980 } 16981 16982 if (isMergePassthruOpcode(NewOp)) 16983 Operands.push_back(DAG.getUNDEF(ContainerVT)); 16984 16985 auto ScalableRes = DAG.getNode(NewOp, DL, ContainerVT, Operands); 16986 return convertFromScalableVector(DAG, VT, ScalableRes); 16987 } 16988 16989 assert(VT.isScalableVector() && "Only expect to lower scalable vector op!"); 16990 16991 SmallVector<SDValue, 4> Operands = {Pg}; 16992 for (const SDValue &V : Op->op_values()) { 16993 assert((!V.getValueType().isVector() || 16994 V.getValueType().isScalableVector()) && 16995 "Only scalable vectors are supported!"); 16996 Operands.push_back(V); 16997 } 16998 16999 if (isMergePassthruOpcode(NewOp)) 17000 Operands.push_back(DAG.getUNDEF(VT)); 17001 17002 return DAG.getNode(NewOp, DL, VT, Operands); 17003 } 17004 17005 // If a fixed length vector operation has no side effects when applied to 17006 // undefined elements, we can safely use scalable vectors to perform the same 17007 // operation without needing to worry about predication. 17008 SDValue AArch64TargetLowering::LowerToScalableOp(SDValue Op, 17009 SelectionDAG &DAG) const { 17010 EVT VT = Op.getValueType(); 17011 assert(useSVEForFixedLengthVectorVT(VT) && 17012 "Only expected to lower fixed length vector operation!"); 17013 EVT ContainerVT = getContainerForFixedLengthVector(DAG, VT); 17014 17015 // Create list of operands by converting existing ones to scalable types. 17016 SmallVector<SDValue, 4> Ops; 17017 for (const SDValue &V : Op->op_values()) { 17018 assert(!isa<VTSDNode>(V) && "Unexpected VTSDNode node!"); 17019 17020 // Pass through non-vector operands. 17021 if (!V.getValueType().isVector()) { 17022 Ops.push_back(V); 17023 continue; 17024 } 17025 17026 // "cast" fixed length vector to a scalable vector. 17027 assert(useSVEForFixedLengthVectorVT(V.getValueType()) && 17028 "Only fixed length vectors are supported!"); 17029 Ops.push_back(convertToScalableVector(DAG, ContainerVT, V)); 17030 } 17031 17032 auto ScalableRes = DAG.getNode(Op.getOpcode(), SDLoc(Op), ContainerVT, Ops); 17033 return convertFromScalableVector(DAG, VT, ScalableRes); 17034 } 17035 17036 SDValue AArch64TargetLowering::LowerVECREDUCE_SEQ_FADD(SDValue ScalarOp, 17037 SelectionDAG &DAG) const { 17038 SDLoc DL(ScalarOp); 17039 SDValue AccOp = ScalarOp.getOperand(0); 17040 SDValue VecOp = ScalarOp.getOperand(1); 17041 EVT SrcVT = VecOp.getValueType(); 17042 EVT ResVT = SrcVT.getVectorElementType(); 17043 17044 EVT ContainerVT = SrcVT; 17045 if (SrcVT.isFixedLengthVector()) { 17046 ContainerVT = getContainerForFixedLengthVector(DAG, SrcVT); 17047 VecOp = convertToScalableVector(DAG, ContainerVT, VecOp); 17048 } 17049 17050 SDValue Pg = getPredicateForVector(DAG, DL, SrcVT); 17051 SDValue Zero = DAG.getConstant(0, DL, MVT::i64); 17052 17053 // Convert operands to Scalable. 17054 AccOp = DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, ContainerVT, 17055 DAG.getUNDEF(ContainerVT), AccOp, Zero); 17056 17057 // Perform reduction. 17058 SDValue Rdx = DAG.getNode(AArch64ISD::FADDA_PRED, DL, ContainerVT, 17059 Pg, AccOp, VecOp); 17060 17061 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, ResVT, Rdx, Zero); 17062 } 17063 17064 SDValue AArch64TargetLowering::LowerPredReductionToSVE(SDValue ReduceOp, 17065 SelectionDAG &DAG) const { 17066 SDLoc DL(ReduceOp); 17067 SDValue Op = ReduceOp.getOperand(0); 17068 EVT OpVT = Op.getValueType(); 17069 EVT VT = ReduceOp.getValueType(); 17070 17071 if (!OpVT.isScalableVector() || OpVT.getVectorElementType() != MVT::i1) 17072 return SDValue(); 17073 17074 SDValue Pg = getPredicateForVector(DAG, DL, OpVT); 17075 17076 switch (ReduceOp.getOpcode()) { 17077 default: 17078 return SDValue(); 17079 case ISD::VECREDUCE_OR: 17080 return getPTest(DAG, VT, Pg, Op, AArch64CC::ANY_ACTIVE); 17081 case ISD::VECREDUCE_AND: { 17082 Op = DAG.getNode(ISD::XOR, DL, OpVT, Op, Pg); 17083 return getPTest(DAG, VT, Pg, Op, AArch64CC::NONE_ACTIVE); 17084 } 17085 case ISD::VECREDUCE_XOR: { 17086 SDValue ID = 17087 DAG.getTargetConstant(Intrinsic::aarch64_sve_cntp, DL, MVT::i64); 17088 SDValue Cntp = 17089 DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, MVT::i64, ID, Pg, Op); 17090 return DAG.getAnyExtOrTrunc(Cntp, DL, VT); 17091 } 17092 } 17093 17094 return SDValue(); 17095 } 17096 17097 SDValue AArch64TargetLowering::LowerReductionToSVE(unsigned Opcode, 17098 SDValue ScalarOp, 17099 SelectionDAG &DAG) const { 17100 SDLoc DL(ScalarOp); 17101 SDValue VecOp = ScalarOp.getOperand(0); 17102 EVT SrcVT = VecOp.getValueType(); 17103 17104 if (useSVEForFixedLengthVectorVT(SrcVT, true)) { 17105 EVT ContainerVT = getContainerForFixedLengthVector(DAG, SrcVT); 17106 VecOp = convertToScalableVector(DAG, ContainerVT, VecOp); 17107 } 17108 17109 // UADDV always returns an i64 result. 17110 EVT ResVT = (Opcode == AArch64ISD::UADDV_PRED) ? MVT::i64 : 17111 SrcVT.getVectorElementType(); 17112 EVT RdxVT = SrcVT; 17113 if (SrcVT.isFixedLengthVector() || Opcode == AArch64ISD::UADDV_PRED) 17114 RdxVT = getPackedSVEVectorVT(ResVT); 17115 17116 SDValue Pg = getPredicateForVector(DAG, DL, SrcVT); 17117 SDValue Rdx = DAG.getNode(Opcode, DL, RdxVT, Pg, VecOp); 17118 SDValue Res = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, ResVT, 17119 Rdx, DAG.getConstant(0, DL, MVT::i64)); 17120 17121 // The VEC_REDUCE nodes expect an element size result. 17122 if (ResVT != ScalarOp.getValueType()) 17123 Res = DAG.getAnyExtOrTrunc(Res, DL, ScalarOp.getValueType()); 17124 17125 return Res; 17126 } 17127 17128 SDValue 17129 AArch64TargetLowering::LowerFixedLengthVectorSelectToSVE(SDValue Op, 17130 SelectionDAG &DAG) const { 17131 EVT VT = Op.getValueType(); 17132 SDLoc DL(Op); 17133 17134 EVT InVT = Op.getOperand(1).getValueType(); 17135 EVT ContainerVT = getContainerForFixedLengthVector(DAG, InVT); 17136 SDValue Op1 = convertToScalableVector(DAG, ContainerVT, Op->getOperand(1)); 17137 SDValue Op2 = convertToScalableVector(DAG, ContainerVT, Op->getOperand(2)); 17138 17139 // Convert the mask to a predicated (NOTE: We don't need to worry about 17140 // inactive lanes since VSELECT is safe when given undefined elements). 17141 EVT MaskVT = Op.getOperand(0).getValueType(); 17142 EVT MaskContainerVT = getContainerForFixedLengthVector(DAG, MaskVT); 17143 auto Mask = convertToScalableVector(DAG, MaskContainerVT, Op.getOperand(0)); 17144 Mask = DAG.getNode(ISD::TRUNCATE, DL, 17145 MaskContainerVT.changeVectorElementType(MVT::i1), Mask); 17146 17147 auto ScalableRes = DAG.getNode(ISD::VSELECT, DL, ContainerVT, 17148 Mask, Op1, Op2); 17149 17150 return convertFromScalableVector(DAG, VT, ScalableRes); 17151 } 17152 17153 SDValue AArch64TargetLowering::LowerFixedLengthVectorSetccToSVE( 17154 SDValue Op, SelectionDAG &DAG) const { 17155 SDLoc DL(Op); 17156 EVT InVT = Op.getOperand(0).getValueType(); 17157 EVT ContainerVT = getContainerForFixedLengthVector(DAG, InVT); 17158 17159 assert(useSVEForFixedLengthVectorVT(InVT) && 17160 "Only expected to lower fixed length vector operation!"); 17161 assert(Op.getValueType() == InVT.changeTypeToInteger() && 17162 "Expected integer result of the same bit length as the inputs!"); 17163 17164 // Expand floating point vector comparisons. 17165 if (InVT.isFloatingPoint()) 17166 return SDValue(); 17167 17168 auto Op1 = convertToScalableVector(DAG, ContainerVT, Op.getOperand(0)); 17169 auto Op2 = convertToScalableVector(DAG, ContainerVT, Op.getOperand(1)); 17170 auto Pg = getPredicateForFixedLengthVector(DAG, DL, InVT); 17171 17172 EVT CmpVT = Pg.getValueType(); 17173 auto Cmp = DAG.getNode(AArch64ISD::SETCC_MERGE_ZERO, DL, CmpVT, 17174 {Pg, Op1, Op2, Op.getOperand(2)}); 17175 17176 EVT PromoteVT = ContainerVT.changeTypeToInteger(); 17177 auto Promote = DAG.getBoolExtOrTrunc(Cmp, DL, PromoteVT, InVT); 17178 return convertFromScalableVector(DAG, Op.getValueType(), Promote); 17179 } 17180 17181 SDValue AArch64TargetLowering::getSVESafeBitCast(EVT VT, SDValue Op, 17182 SelectionDAG &DAG) const { 17183 SDLoc DL(Op); 17184 EVT InVT = Op.getValueType(); 17185 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 17186 (void)TLI; 17187 17188 assert(VT.isScalableVector() && TLI.isTypeLegal(VT) && 17189 InVT.isScalableVector() && TLI.isTypeLegal(InVT) && 17190 "Only expect to cast between legal scalable vector types!"); 17191 assert((VT.getVectorElementType() == MVT::i1) == 17192 (InVT.getVectorElementType() == MVT::i1) && 17193 "Cannot cast between data and predicate scalable vector types!"); 17194 17195 if (InVT == VT) 17196 return Op; 17197 17198 if (VT.getVectorElementType() == MVT::i1) 17199 return DAG.getNode(AArch64ISD::REINTERPRET_CAST, DL, VT, Op); 17200 17201 EVT PackedVT = getPackedSVEVectorVT(VT.getVectorElementType()); 17202 EVT PackedInVT = getPackedSVEVectorVT(InVT.getVectorElementType()); 17203 assert((VT == PackedVT || InVT == PackedInVT) && 17204 "Cannot cast between unpacked scalable vector types!"); 17205 17206 // Pack input if required. 17207 if (InVT != PackedInVT) 17208 Op = DAG.getNode(AArch64ISD::REINTERPRET_CAST, DL, PackedInVT, Op); 17209 17210 Op = DAG.getNode(ISD::BITCAST, DL, PackedVT, Op); 17211 17212 // Unpack result if required. 17213 if (VT != PackedVT) 17214 Op = DAG.getNode(AArch64ISD::REINTERPRET_CAST, DL, VT, Op); 17215 17216 return Op; 17217 } 17218