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/StringSwitch.h" 31 #include "llvm/ADT/Triple.h" 32 #include "llvm/ADT/Twine.h" 33 #include "llvm/Analysis/VectorUtils.h" 34 #include "llvm/CodeGen/CallingConvLower.h" 35 #include "llvm/CodeGen/MachineBasicBlock.h" 36 #include "llvm/CodeGen/MachineFrameInfo.h" 37 #include "llvm/CodeGen/MachineFunction.h" 38 #include "llvm/CodeGen/MachineInstr.h" 39 #include "llvm/CodeGen/MachineInstrBuilder.h" 40 #include "llvm/CodeGen/MachineMemOperand.h" 41 #include "llvm/CodeGen/MachineRegisterInfo.h" 42 #include "llvm/CodeGen/RuntimeLibcalls.h" 43 #include "llvm/CodeGen/SelectionDAG.h" 44 #include "llvm/CodeGen/SelectionDAGNodes.h" 45 #include "llvm/CodeGen/TargetCallingConv.h" 46 #include "llvm/CodeGen/TargetInstrInfo.h" 47 #include "llvm/CodeGen/ValueTypes.h" 48 #include "llvm/IR/Attributes.h" 49 #include "llvm/IR/Constants.h" 50 #include "llvm/IR/DataLayout.h" 51 #include "llvm/IR/DebugLoc.h" 52 #include "llvm/IR/DerivedTypes.h" 53 #include "llvm/IR/Function.h" 54 #include "llvm/IR/GetElementPtrTypeIterator.h" 55 #include "llvm/IR/GlobalValue.h" 56 #include "llvm/IR/IRBuilder.h" 57 #include "llvm/IR/Instruction.h" 58 #include "llvm/IR/Instructions.h" 59 #include "llvm/IR/IntrinsicInst.h" 60 #include "llvm/IR/Intrinsics.h" 61 #include "llvm/IR/IntrinsicsAArch64.h" 62 #include "llvm/IR/Module.h" 63 #include "llvm/IR/OperandTraits.h" 64 #include "llvm/IR/PatternMatch.h" 65 #include "llvm/IR/Type.h" 66 #include "llvm/IR/Use.h" 67 #include "llvm/IR/Value.h" 68 #include "llvm/MC/MCRegisterInfo.h" 69 #include "llvm/Support/Casting.h" 70 #include "llvm/Support/CodeGen.h" 71 #include "llvm/Support/CommandLine.h" 72 #include "llvm/Support/Compiler.h" 73 #include "llvm/Support/Debug.h" 74 #include "llvm/Support/ErrorHandling.h" 75 #include "llvm/Support/KnownBits.h" 76 #include "llvm/Support/MachineValueType.h" 77 #include "llvm/Support/MathExtras.h" 78 #include "llvm/Support/raw_ostream.h" 79 #include "llvm/Target/TargetMachine.h" 80 #include "llvm/Target/TargetOptions.h" 81 #include <algorithm> 82 #include <bitset> 83 #include <cassert> 84 #include <cctype> 85 #include <cstdint> 86 #include <cstdlib> 87 #include <iterator> 88 #include <limits> 89 #include <tuple> 90 #include <utility> 91 #include <vector> 92 93 using namespace llvm; 94 using namespace llvm::PatternMatch; 95 96 #define DEBUG_TYPE "aarch64-lower" 97 98 STATISTIC(NumTailCalls, "Number of tail calls"); 99 STATISTIC(NumShiftInserts, "Number of vector shift inserts"); 100 STATISTIC(NumOptimizedImms, "Number of times immediates were optimized"); 101 102 // FIXME: The necessary dtprel relocations don't seem to be supported 103 // well in the GNU bfd and gold linkers at the moment. Therefore, by 104 // default, for now, fall back to GeneralDynamic code generation. 105 cl::opt<bool> EnableAArch64ELFLocalDynamicTLSGeneration( 106 "aarch64-elf-ldtls-generation", cl::Hidden, 107 cl::desc("Allow AArch64 Local Dynamic TLS code generation"), 108 cl::init(false)); 109 110 static cl::opt<bool> 111 EnableOptimizeLogicalImm("aarch64-enable-logical-imm", cl::Hidden, 112 cl::desc("Enable AArch64 logical imm instruction " 113 "optimization"), 114 cl::init(true)); 115 116 /// Value type used for condition codes. 117 static const MVT MVT_CC = MVT::i32; 118 119 AArch64TargetLowering::AArch64TargetLowering(const TargetMachine &TM, 120 const AArch64Subtarget &STI) 121 : TargetLowering(TM), Subtarget(&STI) { 122 // AArch64 doesn't have comparisons which set GPRs or setcc instructions, so 123 // we have to make something up. Arbitrarily, choose ZeroOrOne. 124 setBooleanContents(ZeroOrOneBooleanContent); 125 // When comparing vectors the result sets the different elements in the 126 // vector to all-one or all-zero. 127 setBooleanVectorContents(ZeroOrNegativeOneBooleanContent); 128 129 // Set up the register classes. 130 addRegisterClass(MVT::i32, &AArch64::GPR32allRegClass); 131 addRegisterClass(MVT::i64, &AArch64::GPR64allRegClass); 132 133 if (Subtarget->hasFPARMv8()) { 134 addRegisterClass(MVT::f16, &AArch64::FPR16RegClass); 135 addRegisterClass(MVT::bf16, &AArch64::FPR16RegClass); 136 addRegisterClass(MVT::f32, &AArch64::FPR32RegClass); 137 addRegisterClass(MVT::f64, &AArch64::FPR64RegClass); 138 addRegisterClass(MVT::f128, &AArch64::FPR128RegClass); 139 } 140 141 if (Subtarget->hasNEON()) { 142 addRegisterClass(MVT::v16i8, &AArch64::FPR8RegClass); 143 addRegisterClass(MVT::v8i16, &AArch64::FPR16RegClass); 144 // Someone set us up the NEON. 145 addDRTypeForNEON(MVT::v2f32); 146 addDRTypeForNEON(MVT::v8i8); 147 addDRTypeForNEON(MVT::v4i16); 148 addDRTypeForNEON(MVT::v2i32); 149 addDRTypeForNEON(MVT::v1i64); 150 addDRTypeForNEON(MVT::v1f64); 151 addDRTypeForNEON(MVT::v4f16); 152 addDRTypeForNEON(MVT::v4bf16); 153 154 addQRTypeForNEON(MVT::v4f32); 155 addQRTypeForNEON(MVT::v2f64); 156 addQRTypeForNEON(MVT::v16i8); 157 addQRTypeForNEON(MVT::v8i16); 158 addQRTypeForNEON(MVT::v4i32); 159 addQRTypeForNEON(MVT::v2i64); 160 addQRTypeForNEON(MVT::v8f16); 161 addQRTypeForNEON(MVT::v8bf16); 162 } 163 164 if (Subtarget->hasSVE()) { 165 // Add legal sve predicate types 166 addRegisterClass(MVT::nxv2i1, &AArch64::PPRRegClass); 167 addRegisterClass(MVT::nxv4i1, &AArch64::PPRRegClass); 168 addRegisterClass(MVT::nxv8i1, &AArch64::PPRRegClass); 169 addRegisterClass(MVT::nxv16i1, &AArch64::PPRRegClass); 170 171 // Add legal sve data types 172 addRegisterClass(MVT::nxv16i8, &AArch64::ZPRRegClass); 173 addRegisterClass(MVT::nxv8i16, &AArch64::ZPRRegClass); 174 addRegisterClass(MVT::nxv4i32, &AArch64::ZPRRegClass); 175 addRegisterClass(MVT::nxv2i64, &AArch64::ZPRRegClass); 176 177 addRegisterClass(MVT::nxv2f16, &AArch64::ZPRRegClass); 178 addRegisterClass(MVT::nxv4f16, &AArch64::ZPRRegClass); 179 addRegisterClass(MVT::nxv8f16, &AArch64::ZPRRegClass); 180 addRegisterClass(MVT::nxv2bf16, &AArch64::ZPRRegClass); 181 addRegisterClass(MVT::nxv4bf16, &AArch64::ZPRRegClass); 182 addRegisterClass(MVT::nxv8bf16, &AArch64::ZPRRegClass); 183 addRegisterClass(MVT::nxv2f32, &AArch64::ZPRRegClass); 184 addRegisterClass(MVT::nxv4f32, &AArch64::ZPRRegClass); 185 addRegisterClass(MVT::nxv2f64, &AArch64::ZPRRegClass); 186 187 for (auto VT : { MVT::nxv16i8, MVT::nxv8i16, MVT::nxv4i32, MVT::nxv2i64 }) { 188 setOperationAction(ISD::SADDSAT, VT, Legal); 189 setOperationAction(ISD::UADDSAT, VT, Legal); 190 setOperationAction(ISD::SSUBSAT, VT, Legal); 191 setOperationAction(ISD::USUBSAT, VT, Legal); 192 } 193 194 for (auto VT : 195 { MVT::nxv2i8, MVT::nxv2i16, MVT::nxv2i32, MVT::nxv2i64, MVT::nxv4i8, 196 MVT::nxv4i16, MVT::nxv4i32, MVT::nxv8i8, MVT::nxv8i16 }) 197 setOperationAction(ISD::SIGN_EXTEND_INREG, VT, Legal); 198 199 for (auto VT : 200 { MVT::nxv2f16, MVT::nxv4f16, MVT::nxv8f16, MVT::nxv2f32, MVT::nxv4f32, 201 MVT::nxv2f64 }) { 202 setCondCodeAction(ISD::SETO, VT, Expand); 203 setCondCodeAction(ISD::SETOLT, VT, Expand); 204 setCondCodeAction(ISD::SETOLE, VT, Expand); 205 setCondCodeAction(ISD::SETULT, VT, Expand); 206 setCondCodeAction(ISD::SETULE, VT, Expand); 207 setCondCodeAction(ISD::SETUGE, VT, Expand); 208 setCondCodeAction(ISD::SETUGT, VT, Expand); 209 setCondCodeAction(ISD::SETUEQ, VT, Expand); 210 setCondCodeAction(ISD::SETUNE, VT, Expand); 211 } 212 } 213 214 // Compute derived properties from the register classes 215 computeRegisterProperties(Subtarget->getRegisterInfo()); 216 217 // Provide all sorts of operation actions 218 setOperationAction(ISD::GlobalAddress, MVT::i64, Custom); 219 setOperationAction(ISD::GlobalTLSAddress, MVT::i64, Custom); 220 setOperationAction(ISD::SETCC, MVT::i32, Custom); 221 setOperationAction(ISD::SETCC, MVT::i64, Custom); 222 setOperationAction(ISD::SETCC, MVT::f16, Custom); 223 setOperationAction(ISD::SETCC, MVT::f32, Custom); 224 setOperationAction(ISD::SETCC, MVT::f64, Custom); 225 setOperationAction(ISD::STRICT_FSETCC, MVT::f16, Custom); 226 setOperationAction(ISD::STRICT_FSETCC, MVT::f32, Custom); 227 setOperationAction(ISD::STRICT_FSETCC, MVT::f64, Custom); 228 setOperationAction(ISD::STRICT_FSETCCS, MVT::f16, Custom); 229 setOperationAction(ISD::STRICT_FSETCCS, MVT::f32, Custom); 230 setOperationAction(ISD::STRICT_FSETCCS, MVT::f64, Custom); 231 setOperationAction(ISD::BITREVERSE, MVT::i32, Legal); 232 setOperationAction(ISD::BITREVERSE, MVT::i64, Legal); 233 setOperationAction(ISD::BRCOND, MVT::Other, Expand); 234 setOperationAction(ISD::BR_CC, MVT::i32, Custom); 235 setOperationAction(ISD::BR_CC, MVT::i64, Custom); 236 setOperationAction(ISD::BR_CC, MVT::f16, Custom); 237 setOperationAction(ISD::BR_CC, MVT::f32, Custom); 238 setOperationAction(ISD::BR_CC, MVT::f64, Custom); 239 setOperationAction(ISD::SELECT, MVT::i32, Custom); 240 setOperationAction(ISD::SELECT, MVT::i64, Custom); 241 setOperationAction(ISD::SELECT, MVT::f16, Custom); 242 setOperationAction(ISD::SELECT, MVT::f32, Custom); 243 setOperationAction(ISD::SELECT, MVT::f64, Custom); 244 setOperationAction(ISD::SELECT_CC, MVT::i32, Custom); 245 setOperationAction(ISD::SELECT_CC, MVT::i64, Custom); 246 setOperationAction(ISD::SELECT_CC, MVT::f16, Custom); 247 setOperationAction(ISD::SELECT_CC, MVT::f32, Custom); 248 setOperationAction(ISD::SELECT_CC, MVT::f64, Custom); 249 setOperationAction(ISD::BR_JT, MVT::Other, Custom); 250 setOperationAction(ISD::JumpTable, MVT::i64, Custom); 251 252 setOperationAction(ISD::SHL_PARTS, MVT::i64, Custom); 253 setOperationAction(ISD::SRA_PARTS, MVT::i64, Custom); 254 setOperationAction(ISD::SRL_PARTS, MVT::i64, Custom); 255 256 setOperationAction(ISD::FREM, MVT::f32, Expand); 257 setOperationAction(ISD::FREM, MVT::f64, Expand); 258 setOperationAction(ISD::FREM, MVT::f80, Expand); 259 260 setOperationAction(ISD::BUILD_PAIR, MVT::i64, Expand); 261 262 // Custom lowering hooks are needed for XOR 263 // to fold it into CSINC/CSINV. 264 setOperationAction(ISD::XOR, MVT::i32, Custom); 265 setOperationAction(ISD::XOR, MVT::i64, Custom); 266 267 // Virtually no operation on f128 is legal, but LLVM can't expand them when 268 // there's a valid register class, so we need custom operations in most cases. 269 setOperationAction(ISD::FABS, MVT::f128, Expand); 270 setOperationAction(ISD::FADD, MVT::f128, Custom); 271 setOperationAction(ISD::FCOPYSIGN, MVT::f128, Expand); 272 setOperationAction(ISD::FCOS, MVT::f128, Expand); 273 setOperationAction(ISD::FDIV, MVT::f128, Custom); 274 setOperationAction(ISD::FMA, MVT::f128, Expand); 275 setOperationAction(ISD::FMUL, MVT::f128, Custom); 276 setOperationAction(ISD::FNEG, MVT::f128, Expand); 277 setOperationAction(ISD::FPOW, MVT::f128, Expand); 278 setOperationAction(ISD::FREM, MVT::f128, Expand); 279 setOperationAction(ISD::FRINT, MVT::f128, Expand); 280 setOperationAction(ISD::FSIN, MVT::f128, Expand); 281 setOperationAction(ISD::FSINCOS, MVT::f128, Expand); 282 setOperationAction(ISD::FSQRT, MVT::f128, Expand); 283 setOperationAction(ISD::FSUB, MVT::f128, Custom); 284 setOperationAction(ISD::FTRUNC, MVT::f128, Expand); 285 setOperationAction(ISD::SETCC, MVT::f128, Custom); 286 setOperationAction(ISD::STRICT_FSETCC, MVT::f128, Custom); 287 setOperationAction(ISD::STRICT_FSETCCS, MVT::f128, Custom); 288 setOperationAction(ISD::BR_CC, MVT::f128, Custom); 289 setOperationAction(ISD::SELECT, MVT::f128, Custom); 290 setOperationAction(ISD::SELECT_CC, MVT::f128, Custom); 291 setOperationAction(ISD::FP_EXTEND, MVT::f128, Custom); 292 293 // Lowering for many of the conversions is actually specified by the non-f128 294 // type. The LowerXXX function will be trivial when f128 isn't involved. 295 setOperationAction(ISD::FP_TO_SINT, MVT::i32, Custom); 296 setOperationAction(ISD::FP_TO_SINT, MVT::i64, Custom); 297 setOperationAction(ISD::FP_TO_SINT, MVT::i128, Custom); 298 setOperationAction(ISD::STRICT_FP_TO_SINT, MVT::i32, Custom); 299 setOperationAction(ISD::STRICT_FP_TO_SINT, MVT::i64, Custom); 300 setOperationAction(ISD::STRICT_FP_TO_SINT, MVT::i128, Custom); 301 setOperationAction(ISD::FP_TO_UINT, MVT::i32, Custom); 302 setOperationAction(ISD::FP_TO_UINT, MVT::i64, Custom); 303 setOperationAction(ISD::FP_TO_UINT, MVT::i128, Custom); 304 setOperationAction(ISD::STRICT_FP_TO_UINT, MVT::i32, Custom); 305 setOperationAction(ISD::STRICT_FP_TO_UINT, MVT::i64, Custom); 306 setOperationAction(ISD::STRICT_FP_TO_UINT, MVT::i128, Custom); 307 setOperationAction(ISD::SINT_TO_FP, MVT::i32, Custom); 308 setOperationAction(ISD::SINT_TO_FP, MVT::i64, Custom); 309 setOperationAction(ISD::SINT_TO_FP, MVT::i128, Custom); 310 setOperationAction(ISD::STRICT_SINT_TO_FP, MVT::i32, Custom); 311 setOperationAction(ISD::STRICT_SINT_TO_FP, MVT::i64, Custom); 312 setOperationAction(ISD::STRICT_SINT_TO_FP, MVT::i128, Custom); 313 setOperationAction(ISD::UINT_TO_FP, MVT::i32, Custom); 314 setOperationAction(ISD::UINT_TO_FP, MVT::i64, Custom); 315 setOperationAction(ISD::UINT_TO_FP, MVT::i128, Custom); 316 setOperationAction(ISD::STRICT_UINT_TO_FP, MVT::i32, Custom); 317 setOperationAction(ISD::STRICT_UINT_TO_FP, MVT::i64, Custom); 318 setOperationAction(ISD::STRICT_UINT_TO_FP, MVT::i128, Custom); 319 setOperationAction(ISD::FP_ROUND, MVT::f32, Custom); 320 setOperationAction(ISD::FP_ROUND, MVT::f64, Custom); 321 setOperationAction(ISD::STRICT_FP_ROUND, MVT::f32, Custom); 322 setOperationAction(ISD::STRICT_FP_ROUND, MVT::f64, Custom); 323 324 // Variable arguments. 325 setOperationAction(ISD::VASTART, MVT::Other, Custom); 326 setOperationAction(ISD::VAARG, MVT::Other, Custom); 327 setOperationAction(ISD::VACOPY, MVT::Other, Custom); 328 setOperationAction(ISD::VAEND, MVT::Other, Expand); 329 330 // Variable-sized objects. 331 setOperationAction(ISD::STACKSAVE, MVT::Other, Expand); 332 setOperationAction(ISD::STACKRESTORE, MVT::Other, Expand); 333 334 if (Subtarget->isTargetWindows()) 335 setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i64, Custom); 336 else 337 setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i64, Expand); 338 339 // Constant pool entries 340 setOperationAction(ISD::ConstantPool, MVT::i64, Custom); 341 342 // BlockAddress 343 setOperationAction(ISD::BlockAddress, MVT::i64, Custom); 344 345 // Add/Sub overflow ops with MVT::Glues are lowered to NZCV dependences. 346 setOperationAction(ISD::ADDC, MVT::i32, Custom); 347 setOperationAction(ISD::ADDE, MVT::i32, Custom); 348 setOperationAction(ISD::SUBC, MVT::i32, Custom); 349 setOperationAction(ISD::SUBE, MVT::i32, Custom); 350 setOperationAction(ISD::ADDC, MVT::i64, Custom); 351 setOperationAction(ISD::ADDE, MVT::i64, Custom); 352 setOperationAction(ISD::SUBC, MVT::i64, Custom); 353 setOperationAction(ISD::SUBE, MVT::i64, Custom); 354 355 // AArch64 lacks both left-rotate and popcount instructions. 356 setOperationAction(ISD::ROTL, MVT::i32, Expand); 357 setOperationAction(ISD::ROTL, MVT::i64, Expand); 358 for (MVT VT : MVT::fixedlen_vector_valuetypes()) { 359 setOperationAction(ISD::ROTL, VT, Expand); 360 setOperationAction(ISD::ROTR, VT, Expand); 361 } 362 363 // AArch64 doesn't have i32 MULH{S|U}. 364 setOperationAction(ISD::MULHU, MVT::i32, Expand); 365 setOperationAction(ISD::MULHS, MVT::i32, Expand); 366 367 // AArch64 doesn't have {U|S}MUL_LOHI. 368 setOperationAction(ISD::UMUL_LOHI, MVT::i64, Expand); 369 setOperationAction(ISD::SMUL_LOHI, MVT::i64, Expand); 370 371 setOperationAction(ISD::CTPOP, MVT::i32, Custom); 372 setOperationAction(ISD::CTPOP, MVT::i64, Custom); 373 setOperationAction(ISD::CTPOP, MVT::i128, Custom); 374 375 setOperationAction(ISD::SDIVREM, MVT::i32, Expand); 376 setOperationAction(ISD::SDIVREM, MVT::i64, Expand); 377 for (MVT VT : MVT::fixedlen_vector_valuetypes()) { 378 setOperationAction(ISD::SDIVREM, VT, Expand); 379 setOperationAction(ISD::UDIVREM, VT, Expand); 380 } 381 setOperationAction(ISD::SREM, MVT::i32, Expand); 382 setOperationAction(ISD::SREM, MVT::i64, Expand); 383 setOperationAction(ISD::UDIVREM, MVT::i32, Expand); 384 setOperationAction(ISD::UDIVREM, MVT::i64, Expand); 385 setOperationAction(ISD::UREM, MVT::i32, Expand); 386 setOperationAction(ISD::UREM, MVT::i64, Expand); 387 388 // Custom lower Add/Sub/Mul with overflow. 389 setOperationAction(ISD::SADDO, MVT::i32, Custom); 390 setOperationAction(ISD::SADDO, MVT::i64, Custom); 391 setOperationAction(ISD::UADDO, MVT::i32, Custom); 392 setOperationAction(ISD::UADDO, MVT::i64, Custom); 393 setOperationAction(ISD::SSUBO, MVT::i32, Custom); 394 setOperationAction(ISD::SSUBO, MVT::i64, Custom); 395 setOperationAction(ISD::USUBO, MVT::i32, Custom); 396 setOperationAction(ISD::USUBO, MVT::i64, Custom); 397 setOperationAction(ISD::SMULO, MVT::i32, Custom); 398 setOperationAction(ISD::SMULO, MVT::i64, Custom); 399 setOperationAction(ISD::UMULO, MVT::i32, Custom); 400 setOperationAction(ISD::UMULO, MVT::i64, Custom); 401 402 setOperationAction(ISD::FSIN, MVT::f32, Expand); 403 setOperationAction(ISD::FSIN, MVT::f64, Expand); 404 setOperationAction(ISD::FCOS, MVT::f32, Expand); 405 setOperationAction(ISD::FCOS, MVT::f64, Expand); 406 setOperationAction(ISD::FPOW, MVT::f32, Expand); 407 setOperationAction(ISD::FPOW, MVT::f64, Expand); 408 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Custom); 409 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom); 410 if (Subtarget->hasFullFP16()) 411 setOperationAction(ISD::FCOPYSIGN, MVT::f16, Custom); 412 else 413 setOperationAction(ISD::FCOPYSIGN, MVT::f16, Promote); 414 415 setOperationAction(ISD::FREM, MVT::f16, Promote); 416 setOperationAction(ISD::FREM, MVT::v4f16, Expand); 417 setOperationAction(ISD::FREM, MVT::v8f16, Expand); 418 setOperationAction(ISD::FPOW, MVT::f16, Promote); 419 setOperationAction(ISD::FPOW, MVT::v4f16, Expand); 420 setOperationAction(ISD::FPOW, MVT::v8f16, Expand); 421 setOperationAction(ISD::FPOWI, MVT::f16, Promote); 422 setOperationAction(ISD::FPOWI, MVT::v4f16, Expand); 423 setOperationAction(ISD::FPOWI, MVT::v8f16, Expand); 424 setOperationAction(ISD::FCOS, MVT::f16, Promote); 425 setOperationAction(ISD::FCOS, MVT::v4f16, Expand); 426 setOperationAction(ISD::FCOS, MVT::v8f16, Expand); 427 setOperationAction(ISD::FSIN, MVT::f16, Promote); 428 setOperationAction(ISD::FSIN, MVT::v4f16, Expand); 429 setOperationAction(ISD::FSIN, MVT::v8f16, Expand); 430 setOperationAction(ISD::FSINCOS, MVT::f16, Promote); 431 setOperationAction(ISD::FSINCOS, MVT::v4f16, Expand); 432 setOperationAction(ISD::FSINCOS, MVT::v8f16, Expand); 433 setOperationAction(ISD::FEXP, MVT::f16, Promote); 434 setOperationAction(ISD::FEXP, MVT::v4f16, Expand); 435 setOperationAction(ISD::FEXP, MVT::v8f16, Expand); 436 setOperationAction(ISD::FEXP2, MVT::f16, Promote); 437 setOperationAction(ISD::FEXP2, MVT::v4f16, Expand); 438 setOperationAction(ISD::FEXP2, MVT::v8f16, Expand); 439 setOperationAction(ISD::FLOG, MVT::f16, Promote); 440 setOperationAction(ISD::FLOG, MVT::v4f16, Expand); 441 setOperationAction(ISD::FLOG, MVT::v8f16, Expand); 442 setOperationAction(ISD::FLOG2, MVT::f16, Promote); 443 setOperationAction(ISD::FLOG2, MVT::v4f16, Expand); 444 setOperationAction(ISD::FLOG2, MVT::v8f16, Expand); 445 setOperationAction(ISD::FLOG10, MVT::f16, Promote); 446 setOperationAction(ISD::FLOG10, MVT::v4f16, Expand); 447 setOperationAction(ISD::FLOG10, MVT::v8f16, Expand); 448 449 if (!Subtarget->hasFullFP16()) { 450 setOperationAction(ISD::SELECT, MVT::f16, Promote); 451 setOperationAction(ISD::SELECT_CC, MVT::f16, Promote); 452 setOperationAction(ISD::SETCC, MVT::f16, Promote); 453 setOperationAction(ISD::BR_CC, MVT::f16, Promote); 454 setOperationAction(ISD::FADD, MVT::f16, Promote); 455 setOperationAction(ISD::FSUB, MVT::f16, Promote); 456 setOperationAction(ISD::FMUL, MVT::f16, Promote); 457 setOperationAction(ISD::FDIV, MVT::f16, Promote); 458 setOperationAction(ISD::FMA, MVT::f16, Promote); 459 setOperationAction(ISD::FNEG, MVT::f16, Promote); 460 setOperationAction(ISD::FABS, MVT::f16, Promote); 461 setOperationAction(ISD::FCEIL, MVT::f16, Promote); 462 setOperationAction(ISD::FSQRT, MVT::f16, Promote); 463 setOperationAction(ISD::FFLOOR, MVT::f16, Promote); 464 setOperationAction(ISD::FNEARBYINT, MVT::f16, Promote); 465 setOperationAction(ISD::FRINT, MVT::f16, Promote); 466 setOperationAction(ISD::FROUND, MVT::f16, Promote); 467 setOperationAction(ISD::FTRUNC, MVT::f16, Promote); 468 setOperationAction(ISD::FMINNUM, MVT::f16, Promote); 469 setOperationAction(ISD::FMAXNUM, MVT::f16, Promote); 470 setOperationAction(ISD::FMINIMUM, MVT::f16, Promote); 471 setOperationAction(ISD::FMAXIMUM, MVT::f16, Promote); 472 473 // promote v4f16 to v4f32 when that is known to be safe. 474 setOperationAction(ISD::FADD, MVT::v4f16, Promote); 475 setOperationAction(ISD::FSUB, MVT::v4f16, Promote); 476 setOperationAction(ISD::FMUL, MVT::v4f16, Promote); 477 setOperationAction(ISD::FDIV, MVT::v4f16, Promote); 478 AddPromotedToType(ISD::FADD, MVT::v4f16, MVT::v4f32); 479 AddPromotedToType(ISD::FSUB, MVT::v4f16, MVT::v4f32); 480 AddPromotedToType(ISD::FMUL, MVT::v4f16, MVT::v4f32); 481 AddPromotedToType(ISD::FDIV, MVT::v4f16, MVT::v4f32); 482 483 setOperationAction(ISD::FABS, MVT::v4f16, Expand); 484 setOperationAction(ISD::FNEG, MVT::v4f16, Expand); 485 setOperationAction(ISD::FROUND, MVT::v4f16, Expand); 486 setOperationAction(ISD::FMA, MVT::v4f16, Expand); 487 setOperationAction(ISD::SETCC, MVT::v4f16, Expand); 488 setOperationAction(ISD::BR_CC, MVT::v4f16, Expand); 489 setOperationAction(ISD::SELECT, MVT::v4f16, Expand); 490 setOperationAction(ISD::SELECT_CC, MVT::v4f16, Expand); 491 setOperationAction(ISD::FTRUNC, MVT::v4f16, Expand); 492 setOperationAction(ISD::FCOPYSIGN, MVT::v4f16, Expand); 493 setOperationAction(ISD::FFLOOR, MVT::v4f16, Expand); 494 setOperationAction(ISD::FCEIL, MVT::v4f16, Expand); 495 setOperationAction(ISD::FRINT, MVT::v4f16, Expand); 496 setOperationAction(ISD::FNEARBYINT, MVT::v4f16, Expand); 497 setOperationAction(ISD::FSQRT, MVT::v4f16, Expand); 498 499 setOperationAction(ISD::FABS, MVT::v8f16, Expand); 500 setOperationAction(ISD::FADD, MVT::v8f16, Expand); 501 setOperationAction(ISD::FCEIL, MVT::v8f16, Expand); 502 setOperationAction(ISD::FCOPYSIGN, MVT::v8f16, Expand); 503 setOperationAction(ISD::FDIV, MVT::v8f16, Expand); 504 setOperationAction(ISD::FFLOOR, MVT::v8f16, Expand); 505 setOperationAction(ISD::FMA, MVT::v8f16, Expand); 506 setOperationAction(ISD::FMUL, MVT::v8f16, Expand); 507 setOperationAction(ISD::FNEARBYINT, MVT::v8f16, Expand); 508 setOperationAction(ISD::FNEG, MVT::v8f16, Expand); 509 setOperationAction(ISD::FROUND, MVT::v8f16, Expand); 510 setOperationAction(ISD::FRINT, MVT::v8f16, Expand); 511 setOperationAction(ISD::FSQRT, MVT::v8f16, Expand); 512 setOperationAction(ISD::FSUB, MVT::v8f16, Expand); 513 setOperationAction(ISD::FTRUNC, MVT::v8f16, Expand); 514 setOperationAction(ISD::SETCC, MVT::v8f16, Expand); 515 setOperationAction(ISD::BR_CC, MVT::v8f16, Expand); 516 setOperationAction(ISD::SELECT, MVT::v8f16, Expand); 517 setOperationAction(ISD::SELECT_CC, MVT::v8f16, Expand); 518 setOperationAction(ISD::FP_EXTEND, MVT::v8f16, Expand); 519 } 520 521 // AArch64 has implementations of a lot of rounding-like FP operations. 522 for (MVT Ty : {MVT::f32, MVT::f64}) { 523 setOperationAction(ISD::FFLOOR, Ty, Legal); 524 setOperationAction(ISD::FNEARBYINT, Ty, Legal); 525 setOperationAction(ISD::FCEIL, Ty, Legal); 526 setOperationAction(ISD::FRINT, Ty, Legal); 527 setOperationAction(ISD::FTRUNC, Ty, Legal); 528 setOperationAction(ISD::FROUND, Ty, Legal); 529 setOperationAction(ISD::FMINNUM, Ty, Legal); 530 setOperationAction(ISD::FMAXNUM, Ty, Legal); 531 setOperationAction(ISD::FMINIMUM, Ty, Legal); 532 setOperationAction(ISD::FMAXIMUM, Ty, Legal); 533 setOperationAction(ISD::LROUND, Ty, Legal); 534 setOperationAction(ISD::LLROUND, Ty, Legal); 535 setOperationAction(ISD::LRINT, Ty, Legal); 536 setOperationAction(ISD::LLRINT, Ty, Legal); 537 } 538 539 if (Subtarget->hasFullFP16()) { 540 setOperationAction(ISD::FNEARBYINT, MVT::f16, Legal); 541 setOperationAction(ISD::FFLOOR, MVT::f16, Legal); 542 setOperationAction(ISD::FCEIL, MVT::f16, Legal); 543 setOperationAction(ISD::FRINT, MVT::f16, Legal); 544 setOperationAction(ISD::FTRUNC, MVT::f16, Legal); 545 setOperationAction(ISD::FROUND, MVT::f16, Legal); 546 setOperationAction(ISD::FMINNUM, MVT::f16, Legal); 547 setOperationAction(ISD::FMAXNUM, MVT::f16, Legal); 548 setOperationAction(ISD::FMINIMUM, MVT::f16, Legal); 549 setOperationAction(ISD::FMAXIMUM, MVT::f16, Legal); 550 } 551 552 setOperationAction(ISD::PREFETCH, MVT::Other, Custom); 553 554 setOperationAction(ISD::FLT_ROUNDS_, MVT::i32, Custom); 555 556 setOperationAction(ISD::ATOMIC_CMP_SWAP, MVT::i128, Custom); 557 setOperationAction(ISD::ATOMIC_LOAD_SUB, MVT::i32, Custom); 558 setOperationAction(ISD::ATOMIC_LOAD_SUB, MVT::i64, Custom); 559 setOperationAction(ISD::ATOMIC_LOAD_AND, MVT::i32, Custom); 560 setOperationAction(ISD::ATOMIC_LOAD_AND, MVT::i64, Custom); 561 562 // 128-bit loads and stores can be done without expanding 563 setOperationAction(ISD::LOAD, MVT::i128, Custom); 564 setOperationAction(ISD::STORE, MVT::i128, Custom); 565 566 // 256 bit non-temporal stores can be lowered to STNP. Do this as part of the 567 // custom lowering, as there are no un-paired non-temporal stores and 568 // legalization will break up 256 bit inputs. 569 setOperationAction(ISD::STORE, MVT::v32i8, Custom); 570 setOperationAction(ISD::STORE, MVT::v16i16, Custom); 571 setOperationAction(ISD::STORE, MVT::v16f16, Custom); 572 setOperationAction(ISD::STORE, MVT::v8i32, Custom); 573 setOperationAction(ISD::STORE, MVT::v8f32, Custom); 574 setOperationAction(ISD::STORE, MVT::v4f64, Custom); 575 setOperationAction(ISD::STORE, MVT::v4i64, Custom); 576 577 // Lower READCYCLECOUNTER using an mrs from PMCCNTR_EL0. 578 // This requires the Performance Monitors extension. 579 if (Subtarget->hasPerfMon()) 580 setOperationAction(ISD::READCYCLECOUNTER, MVT::i64, Legal); 581 582 if (getLibcallName(RTLIB::SINCOS_STRET_F32) != nullptr && 583 getLibcallName(RTLIB::SINCOS_STRET_F64) != nullptr) { 584 // Issue __sincos_stret if available. 585 setOperationAction(ISD::FSINCOS, MVT::f64, Custom); 586 setOperationAction(ISD::FSINCOS, MVT::f32, Custom); 587 } else { 588 setOperationAction(ISD::FSINCOS, MVT::f64, Expand); 589 setOperationAction(ISD::FSINCOS, MVT::f32, Expand); 590 } 591 592 if (Subtarget->getTargetTriple().isOSMSVCRT()) { 593 // MSVCRT doesn't have powi; fall back to pow 594 setLibcallName(RTLIB::POWI_F32, nullptr); 595 setLibcallName(RTLIB::POWI_F64, nullptr); 596 } 597 598 // Make floating-point constants legal for the large code model, so they don't 599 // become loads from the constant pool. 600 if (Subtarget->isTargetMachO() && TM.getCodeModel() == CodeModel::Large) { 601 setOperationAction(ISD::ConstantFP, MVT::f32, Legal); 602 setOperationAction(ISD::ConstantFP, MVT::f64, Legal); 603 } 604 605 // AArch64 does not have floating-point extending loads, i1 sign-extending 606 // load, floating-point truncating stores, or v2i32->v2i16 truncating store. 607 for (MVT VT : MVT::fp_valuetypes()) { 608 setLoadExtAction(ISD::EXTLOAD, VT, MVT::f16, Expand); 609 setLoadExtAction(ISD::EXTLOAD, VT, MVT::f32, Expand); 610 setLoadExtAction(ISD::EXTLOAD, VT, MVT::f64, Expand); 611 setLoadExtAction(ISD::EXTLOAD, VT, MVT::f80, Expand); 612 } 613 for (MVT VT : MVT::integer_valuetypes()) 614 setLoadExtAction(ISD::SEXTLOAD, VT, MVT::i1, Expand); 615 616 setTruncStoreAction(MVT::f32, MVT::f16, Expand); 617 setTruncStoreAction(MVT::f64, MVT::f32, Expand); 618 setTruncStoreAction(MVT::f64, MVT::f16, Expand); 619 setTruncStoreAction(MVT::f128, MVT::f80, Expand); 620 setTruncStoreAction(MVT::f128, MVT::f64, Expand); 621 setTruncStoreAction(MVT::f128, MVT::f32, Expand); 622 setTruncStoreAction(MVT::f128, MVT::f16, Expand); 623 624 setOperationAction(ISD::BITCAST, MVT::i16, Custom); 625 setOperationAction(ISD::BITCAST, MVT::f16, Custom); 626 setOperationAction(ISD::BITCAST, MVT::bf16, Custom); 627 628 // Indexed loads and stores are supported. 629 for (unsigned im = (unsigned)ISD::PRE_INC; 630 im != (unsigned)ISD::LAST_INDEXED_MODE; ++im) { 631 setIndexedLoadAction(im, MVT::i8, Legal); 632 setIndexedLoadAction(im, MVT::i16, Legal); 633 setIndexedLoadAction(im, MVT::i32, Legal); 634 setIndexedLoadAction(im, MVT::i64, Legal); 635 setIndexedLoadAction(im, MVT::f64, Legal); 636 setIndexedLoadAction(im, MVT::f32, Legal); 637 setIndexedLoadAction(im, MVT::f16, Legal); 638 setIndexedLoadAction(im, MVT::bf16, Legal); 639 setIndexedStoreAction(im, MVT::i8, Legal); 640 setIndexedStoreAction(im, MVT::i16, Legal); 641 setIndexedStoreAction(im, MVT::i32, Legal); 642 setIndexedStoreAction(im, MVT::i64, Legal); 643 setIndexedStoreAction(im, MVT::f64, Legal); 644 setIndexedStoreAction(im, MVT::f32, Legal); 645 setIndexedStoreAction(im, MVT::f16, Legal); 646 setIndexedStoreAction(im, MVT::bf16, Legal); 647 } 648 649 // Trap. 650 setOperationAction(ISD::TRAP, MVT::Other, Legal); 651 if (Subtarget->isTargetWindows()) 652 setOperationAction(ISD::DEBUGTRAP, MVT::Other, Legal); 653 654 // We combine OR nodes for bitfield operations. 655 setTargetDAGCombine(ISD::OR); 656 // Try to create BICs for vector ANDs. 657 setTargetDAGCombine(ISD::AND); 658 659 // Vector add and sub nodes may conceal a high-half opportunity. 660 // Also, try to fold ADD into CSINC/CSINV.. 661 setTargetDAGCombine(ISD::ADD); 662 setTargetDAGCombine(ISD::SUB); 663 setTargetDAGCombine(ISD::SRL); 664 setTargetDAGCombine(ISD::XOR); 665 setTargetDAGCombine(ISD::SINT_TO_FP); 666 setTargetDAGCombine(ISD::UINT_TO_FP); 667 668 setTargetDAGCombine(ISD::FP_TO_SINT); 669 setTargetDAGCombine(ISD::FP_TO_UINT); 670 setTargetDAGCombine(ISD::FDIV); 671 672 setTargetDAGCombine(ISD::INTRINSIC_WO_CHAIN); 673 674 setTargetDAGCombine(ISD::ANY_EXTEND); 675 setTargetDAGCombine(ISD::ZERO_EXTEND); 676 setTargetDAGCombine(ISD::SIGN_EXTEND); 677 setTargetDAGCombine(ISD::SIGN_EXTEND_INREG); 678 setTargetDAGCombine(ISD::CONCAT_VECTORS); 679 setTargetDAGCombine(ISD::STORE); 680 if (Subtarget->supportsAddressTopByteIgnored()) 681 setTargetDAGCombine(ISD::LOAD); 682 683 setTargetDAGCombine(ISD::MUL); 684 685 setTargetDAGCombine(ISD::SELECT); 686 setTargetDAGCombine(ISD::VSELECT); 687 688 setTargetDAGCombine(ISD::INTRINSIC_VOID); 689 setTargetDAGCombine(ISD::INTRINSIC_W_CHAIN); 690 setTargetDAGCombine(ISD::INSERT_VECTOR_ELT); 691 692 setTargetDAGCombine(ISD::GlobalAddress); 693 694 // In case of strict alignment, avoid an excessive number of byte wide stores. 695 MaxStoresPerMemsetOptSize = 8; 696 MaxStoresPerMemset = Subtarget->requiresStrictAlign() 697 ? MaxStoresPerMemsetOptSize : 32; 698 699 MaxGluedStoresPerMemcpy = 4; 700 MaxStoresPerMemcpyOptSize = 4; 701 MaxStoresPerMemcpy = Subtarget->requiresStrictAlign() 702 ? MaxStoresPerMemcpyOptSize : 16; 703 704 MaxStoresPerMemmoveOptSize = MaxStoresPerMemmove = 4; 705 706 MaxLoadsPerMemcmpOptSize = 4; 707 MaxLoadsPerMemcmp = Subtarget->requiresStrictAlign() 708 ? MaxLoadsPerMemcmpOptSize : 8; 709 710 setStackPointerRegisterToSaveRestore(AArch64::SP); 711 712 setSchedulingPreference(Sched::Hybrid); 713 714 EnableExtLdPromotion = true; 715 716 // Set required alignment. 717 setMinFunctionAlignment(Align(4)); 718 // Set preferred alignments. 719 setPrefLoopAlignment(Align(1ULL << STI.getPrefLoopLogAlignment())); 720 setPrefFunctionAlignment(Align(1ULL << STI.getPrefFunctionLogAlignment())); 721 722 // Only change the limit for entries in a jump table if specified by 723 // the sub target, but not at the command line. 724 unsigned MaxJT = STI.getMaximumJumpTableSize(); 725 if (MaxJT && getMaximumJumpTableSize() == UINT_MAX) 726 setMaximumJumpTableSize(MaxJT); 727 728 setHasExtractBitsInsn(true); 729 730 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom); 731 732 if (Subtarget->hasNEON()) { 733 // FIXME: v1f64 shouldn't be legal if we can avoid it, because it leads to 734 // silliness like this: 735 setOperationAction(ISD::FABS, MVT::v1f64, Expand); 736 setOperationAction(ISD::FADD, MVT::v1f64, Expand); 737 setOperationAction(ISD::FCEIL, MVT::v1f64, Expand); 738 setOperationAction(ISD::FCOPYSIGN, MVT::v1f64, Expand); 739 setOperationAction(ISD::FCOS, MVT::v1f64, Expand); 740 setOperationAction(ISD::FDIV, MVT::v1f64, Expand); 741 setOperationAction(ISD::FFLOOR, MVT::v1f64, Expand); 742 setOperationAction(ISD::FMA, MVT::v1f64, Expand); 743 setOperationAction(ISD::FMUL, MVT::v1f64, Expand); 744 setOperationAction(ISD::FNEARBYINT, MVT::v1f64, Expand); 745 setOperationAction(ISD::FNEG, MVT::v1f64, Expand); 746 setOperationAction(ISD::FPOW, MVT::v1f64, Expand); 747 setOperationAction(ISD::FREM, MVT::v1f64, Expand); 748 setOperationAction(ISD::FROUND, MVT::v1f64, Expand); 749 setOperationAction(ISD::FRINT, MVT::v1f64, Expand); 750 setOperationAction(ISD::FSIN, MVT::v1f64, Expand); 751 setOperationAction(ISD::FSINCOS, MVT::v1f64, Expand); 752 setOperationAction(ISD::FSQRT, MVT::v1f64, Expand); 753 setOperationAction(ISD::FSUB, MVT::v1f64, Expand); 754 setOperationAction(ISD::FTRUNC, MVT::v1f64, Expand); 755 setOperationAction(ISD::SETCC, MVT::v1f64, Expand); 756 setOperationAction(ISD::BR_CC, MVT::v1f64, Expand); 757 setOperationAction(ISD::SELECT, MVT::v1f64, Expand); 758 setOperationAction(ISD::SELECT_CC, MVT::v1f64, Expand); 759 setOperationAction(ISD::FP_EXTEND, MVT::v1f64, Expand); 760 761 setOperationAction(ISD::FP_TO_SINT, MVT::v1i64, Expand); 762 setOperationAction(ISD::FP_TO_UINT, MVT::v1i64, Expand); 763 setOperationAction(ISD::SINT_TO_FP, MVT::v1i64, Expand); 764 setOperationAction(ISD::UINT_TO_FP, MVT::v1i64, Expand); 765 setOperationAction(ISD::FP_ROUND, MVT::v1f64, Expand); 766 767 setOperationAction(ISD::MUL, MVT::v1i64, Expand); 768 769 // AArch64 doesn't have a direct vector ->f32 conversion instructions for 770 // elements smaller than i32, so promote the input to i32 first. 771 setOperationPromotedToType(ISD::UINT_TO_FP, MVT::v4i8, MVT::v4i32); 772 setOperationPromotedToType(ISD::SINT_TO_FP, MVT::v4i8, MVT::v4i32); 773 // i8 vector elements also need promotion to i32 for v8i8 774 setOperationPromotedToType(ISD::SINT_TO_FP, MVT::v8i8, MVT::v8i32); 775 setOperationPromotedToType(ISD::UINT_TO_FP, MVT::v8i8, MVT::v8i32); 776 // Similarly, there is no direct i32 -> f64 vector conversion instruction. 777 setOperationAction(ISD::SINT_TO_FP, MVT::v2i32, Custom); 778 setOperationAction(ISD::UINT_TO_FP, MVT::v2i32, Custom); 779 setOperationAction(ISD::SINT_TO_FP, MVT::v2i64, Custom); 780 setOperationAction(ISD::UINT_TO_FP, MVT::v2i64, Custom); 781 // Or, direct i32 -> f16 vector conversion. Set it so custom, so the 782 // conversion happens in two steps: v4i32 -> v4f32 -> v4f16 783 setOperationAction(ISD::SINT_TO_FP, MVT::v4i32, Custom); 784 setOperationAction(ISD::UINT_TO_FP, MVT::v4i32, Custom); 785 786 if (Subtarget->hasFullFP16()) { 787 setOperationAction(ISD::SINT_TO_FP, MVT::v4i16, Custom); 788 setOperationAction(ISD::UINT_TO_FP, MVT::v4i16, Custom); 789 setOperationAction(ISD::SINT_TO_FP, MVT::v8i16, Custom); 790 setOperationAction(ISD::UINT_TO_FP, MVT::v8i16, Custom); 791 } else { 792 // when AArch64 doesn't have fullfp16 support, promote the input 793 // to i32 first. 794 setOperationPromotedToType(ISD::UINT_TO_FP, MVT::v4i16, MVT::v4i32); 795 setOperationPromotedToType(ISD::SINT_TO_FP, MVT::v4i16, MVT::v4i32); 796 setOperationPromotedToType(ISD::SINT_TO_FP, MVT::v8i16, MVT::v8i32); 797 setOperationPromotedToType(ISD::UINT_TO_FP, MVT::v8i16, MVT::v8i32); 798 } 799 800 setOperationAction(ISD::CTLZ, MVT::v1i64, Expand); 801 setOperationAction(ISD::CTLZ, MVT::v2i64, Expand); 802 803 // AArch64 doesn't have MUL.2d: 804 setOperationAction(ISD::MUL, MVT::v2i64, Expand); 805 // Custom handling for some quad-vector types to detect MULL. 806 setOperationAction(ISD::MUL, MVT::v8i16, Custom); 807 setOperationAction(ISD::MUL, MVT::v4i32, Custom); 808 setOperationAction(ISD::MUL, MVT::v2i64, Custom); 809 810 for (MVT VT : { MVT::v8i8, MVT::v4i16, MVT::v2i32, 811 MVT::v16i8, MVT::v8i16, MVT::v4i32, MVT::v2i64 }) { 812 // Vector reductions 813 setOperationAction(ISD::VECREDUCE_ADD, VT, Custom); 814 setOperationAction(ISD::VECREDUCE_SMAX, VT, Custom); 815 setOperationAction(ISD::VECREDUCE_SMIN, VT, Custom); 816 setOperationAction(ISD::VECREDUCE_UMAX, VT, Custom); 817 setOperationAction(ISD::VECREDUCE_UMIN, VT, Custom); 818 819 // Saturates 820 setOperationAction(ISD::SADDSAT, VT, Legal); 821 setOperationAction(ISD::UADDSAT, VT, Legal); 822 setOperationAction(ISD::SSUBSAT, VT, Legal); 823 setOperationAction(ISD::USUBSAT, VT, Legal); 824 } 825 for (MVT VT : { MVT::v4f16, MVT::v2f32, 826 MVT::v8f16, MVT::v4f32, MVT::v2f64 }) { 827 setOperationAction(ISD::VECREDUCE_FMAX, VT, Custom); 828 setOperationAction(ISD::VECREDUCE_FMIN, VT, Custom); 829 } 830 831 setOperationAction(ISD::ANY_EXTEND, MVT::v4i32, Legal); 832 setTruncStoreAction(MVT::v2i32, MVT::v2i16, Expand); 833 // Likewise, narrowing and extending vector loads/stores aren't handled 834 // directly. 835 for (MVT VT : MVT::fixedlen_vector_valuetypes()) { 836 setOperationAction(ISD::SIGN_EXTEND_INREG, VT, Expand); 837 838 if (VT == MVT::v16i8 || VT == MVT::v8i16 || VT == MVT::v4i32) { 839 setOperationAction(ISD::MULHS, VT, Legal); 840 setOperationAction(ISD::MULHU, VT, Legal); 841 } else { 842 setOperationAction(ISD::MULHS, VT, Expand); 843 setOperationAction(ISD::MULHU, VT, Expand); 844 } 845 setOperationAction(ISD::SMUL_LOHI, VT, Expand); 846 setOperationAction(ISD::UMUL_LOHI, VT, Expand); 847 848 setOperationAction(ISD::BSWAP, VT, Expand); 849 setOperationAction(ISD::CTTZ, VT, Expand); 850 851 for (MVT InnerVT : MVT::fixedlen_vector_valuetypes()) { 852 setTruncStoreAction(VT, InnerVT, Expand); 853 setLoadExtAction(ISD::SEXTLOAD, VT, InnerVT, Expand); 854 setLoadExtAction(ISD::ZEXTLOAD, VT, InnerVT, Expand); 855 setLoadExtAction(ISD::EXTLOAD, VT, InnerVT, Expand); 856 } 857 } 858 859 // AArch64 has implementations of a lot of rounding-like FP operations. 860 for (MVT Ty : {MVT::v2f32, MVT::v4f32, MVT::v2f64}) { 861 setOperationAction(ISD::FFLOOR, Ty, Legal); 862 setOperationAction(ISD::FNEARBYINT, Ty, Legal); 863 setOperationAction(ISD::FCEIL, Ty, Legal); 864 setOperationAction(ISD::FRINT, Ty, Legal); 865 setOperationAction(ISD::FTRUNC, Ty, Legal); 866 setOperationAction(ISD::FROUND, Ty, Legal); 867 } 868 869 if (Subtarget->hasFullFP16()) { 870 for (MVT Ty : {MVT::v4f16, MVT::v8f16}) { 871 setOperationAction(ISD::FFLOOR, Ty, Legal); 872 setOperationAction(ISD::FNEARBYINT, Ty, Legal); 873 setOperationAction(ISD::FCEIL, Ty, Legal); 874 setOperationAction(ISD::FRINT, Ty, Legal); 875 setOperationAction(ISD::FTRUNC, Ty, Legal); 876 setOperationAction(ISD::FROUND, Ty, Legal); 877 } 878 } 879 880 if (Subtarget->hasSVE()) 881 setOperationAction(ISD::VSCALE, MVT::i32, Custom); 882 883 setTruncStoreAction(MVT::v4i16, MVT::v4i8, Custom); 884 } 885 886 if (Subtarget->hasSVE()) { 887 // FIXME: Add custom lowering of MLOAD to handle different passthrus (not a 888 // splat of 0 or undef) once vector selects supported in SVE codegen. See 889 // D68877 for more details. 890 for (MVT VT : MVT::integer_scalable_vector_valuetypes()) { 891 if (isTypeLegal(VT)) { 892 setOperationAction(ISD::SPLAT_VECTOR, VT, Custom); 893 setOperationAction(ISD::SELECT, VT, Custom); 894 setOperationAction(ISD::SDIV, VT, Custom); 895 setOperationAction(ISD::UDIV, VT, Custom); 896 setOperationAction(ISD::SMIN, VT, Custom); 897 setOperationAction(ISD::UMIN, VT, Custom); 898 setOperationAction(ISD::SMAX, VT, Custom); 899 setOperationAction(ISD::UMAX, VT, Custom); 900 setOperationAction(ISD::SHL, VT, Custom); 901 setOperationAction(ISD::SRL, VT, Custom); 902 setOperationAction(ISD::SRA, VT, Custom); 903 if (VT.getScalarType() == MVT::i1) 904 setOperationAction(ISD::SETCC, VT, Custom); 905 } else { 906 for (auto VT : { MVT::nxv8i8, MVT::nxv4i16, MVT::nxv2i32 }) 907 setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Custom); 908 } 909 } 910 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::i8, Custom); 911 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::i16, Custom); 912 913 for (MVT VT : MVT::fp_scalable_vector_valuetypes()) { 914 if (isTypeLegal(VT)) { 915 setOperationAction(ISD::SPLAT_VECTOR, VT, Custom); 916 setOperationAction(ISD::SELECT, VT, Custom); 917 } 918 } 919 } 920 921 PredictableSelectIsExpensive = Subtarget->predictableSelectIsExpensive(); 922 } 923 924 void AArch64TargetLowering::addTypeForNEON(MVT VT, MVT PromotedBitwiseVT) { 925 assert(VT.isVector() && "VT should be a vector type"); 926 927 if (VT.isFloatingPoint()) { 928 MVT PromoteTo = EVT(VT).changeVectorElementTypeToInteger().getSimpleVT(); 929 setOperationPromotedToType(ISD::LOAD, VT, PromoteTo); 930 setOperationPromotedToType(ISD::STORE, VT, PromoteTo); 931 } 932 933 // Mark vector float intrinsics as expand. 934 if (VT == MVT::v2f32 || VT == MVT::v4f32 || VT == MVT::v2f64) { 935 setOperationAction(ISD::FSIN, VT, Expand); 936 setOperationAction(ISD::FCOS, VT, Expand); 937 setOperationAction(ISD::FPOW, VT, Expand); 938 setOperationAction(ISD::FLOG, VT, Expand); 939 setOperationAction(ISD::FLOG2, VT, Expand); 940 setOperationAction(ISD::FLOG10, VT, Expand); 941 setOperationAction(ISD::FEXP, VT, Expand); 942 setOperationAction(ISD::FEXP2, VT, Expand); 943 944 // But we do support custom-lowering for FCOPYSIGN. 945 setOperationAction(ISD::FCOPYSIGN, VT, Custom); 946 } 947 948 setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom); 949 setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Custom); 950 setOperationAction(ISD::BUILD_VECTOR, VT, Custom); 951 setOperationAction(ISD::VECTOR_SHUFFLE, VT, Custom); 952 setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Custom); 953 setOperationAction(ISD::SRA, VT, Custom); 954 setOperationAction(ISD::SRL, VT, Custom); 955 setOperationAction(ISD::SHL, VT, Custom); 956 setOperationAction(ISD::OR, VT, Custom); 957 setOperationAction(ISD::SETCC, VT, Custom); 958 setOperationAction(ISD::CONCAT_VECTORS, VT, Legal); 959 960 setOperationAction(ISD::SELECT, VT, Expand); 961 setOperationAction(ISD::SELECT_CC, VT, Expand); 962 setOperationAction(ISD::VSELECT, VT, Expand); 963 for (MVT InnerVT : MVT::all_valuetypes()) 964 setLoadExtAction(ISD::EXTLOAD, InnerVT, VT, Expand); 965 966 // CNT supports only B element sizes, then use UADDLP to widen. 967 if (VT != MVT::v8i8 && VT != MVT::v16i8) 968 setOperationAction(ISD::CTPOP, VT, Custom); 969 970 setOperationAction(ISD::UDIV, VT, Expand); 971 setOperationAction(ISD::SDIV, VT, Expand); 972 setOperationAction(ISD::UREM, VT, Expand); 973 setOperationAction(ISD::SREM, VT, Expand); 974 setOperationAction(ISD::FREM, VT, Expand); 975 976 setOperationAction(ISD::FP_TO_SINT, VT, Custom); 977 setOperationAction(ISD::FP_TO_UINT, VT, Custom); 978 979 if (!VT.isFloatingPoint()) 980 setOperationAction(ISD::ABS, VT, Legal); 981 982 // [SU][MIN|MAX] are available for all NEON types apart from i64. 983 if (!VT.isFloatingPoint() && VT != MVT::v2i64 && VT != MVT::v1i64) 984 for (unsigned Opcode : {ISD::SMIN, ISD::SMAX, ISD::UMIN, ISD::UMAX}) 985 setOperationAction(Opcode, VT, Legal); 986 987 // F[MIN|MAX][NUM|NAN] are available for all FP NEON types. 988 if (VT.isFloatingPoint() && 989 (VT.getVectorElementType() != MVT::f16 || Subtarget->hasFullFP16())) 990 for (unsigned Opcode : 991 {ISD::FMINIMUM, ISD::FMAXIMUM, ISD::FMINNUM, ISD::FMAXNUM}) 992 setOperationAction(Opcode, VT, Legal); 993 994 if (Subtarget->isLittleEndian()) { 995 for (unsigned im = (unsigned)ISD::PRE_INC; 996 im != (unsigned)ISD::LAST_INDEXED_MODE; ++im) { 997 setIndexedLoadAction(im, VT, Legal); 998 setIndexedStoreAction(im, VT, Legal); 999 } 1000 } 1001 } 1002 1003 void AArch64TargetLowering::addDRTypeForNEON(MVT VT) { 1004 addRegisterClass(VT, &AArch64::FPR64RegClass); 1005 addTypeForNEON(VT, MVT::v2i32); 1006 } 1007 1008 void AArch64TargetLowering::addQRTypeForNEON(MVT VT) { 1009 addRegisterClass(VT, &AArch64::FPR128RegClass); 1010 addTypeForNEON(VT, MVT::v4i32); 1011 } 1012 1013 EVT AArch64TargetLowering::getSetCCResultType(const DataLayout &, 1014 LLVMContext &C, EVT VT) const { 1015 if (!VT.isVector()) 1016 return MVT::i32; 1017 if (VT.isScalableVector()) 1018 return EVT::getVectorVT(C, MVT::i1, VT.getVectorElementCount()); 1019 return VT.changeVectorElementTypeToInteger(); 1020 } 1021 1022 static bool optimizeLogicalImm(SDValue Op, unsigned Size, uint64_t Imm, 1023 const APInt &Demanded, 1024 TargetLowering::TargetLoweringOpt &TLO, 1025 unsigned NewOpc) { 1026 uint64_t OldImm = Imm, NewImm, Enc; 1027 uint64_t Mask = ((uint64_t)(-1LL) >> (64 - Size)), OrigMask = Mask; 1028 1029 // Return if the immediate is already all zeros, all ones, a bimm32 or a 1030 // bimm64. 1031 if (Imm == 0 || Imm == Mask || 1032 AArch64_AM::isLogicalImmediate(Imm & Mask, Size)) 1033 return false; 1034 1035 unsigned EltSize = Size; 1036 uint64_t DemandedBits = Demanded.getZExtValue(); 1037 1038 // Clear bits that are not demanded. 1039 Imm &= DemandedBits; 1040 1041 while (true) { 1042 // The goal here is to set the non-demanded bits in a way that minimizes 1043 // the number of switching between 0 and 1. In order to achieve this goal, 1044 // we set the non-demanded bits to the value of the preceding demanded bits. 1045 // For example, if we have an immediate 0bx10xx0x1 ('x' indicates a 1046 // non-demanded bit), we copy bit0 (1) to the least significant 'x', 1047 // bit2 (0) to 'xx', and bit6 (1) to the most significant 'x'. 1048 // The final result is 0b11000011. 1049 uint64_t NonDemandedBits = ~DemandedBits; 1050 uint64_t InvertedImm = ~Imm & DemandedBits; 1051 uint64_t RotatedImm = 1052 ((InvertedImm << 1) | (InvertedImm >> (EltSize - 1) & 1)) & 1053 NonDemandedBits; 1054 uint64_t Sum = RotatedImm + NonDemandedBits; 1055 bool Carry = NonDemandedBits & ~Sum & (1ULL << (EltSize - 1)); 1056 uint64_t Ones = (Sum + Carry) & NonDemandedBits; 1057 NewImm = (Imm | Ones) & Mask; 1058 1059 // If NewImm or its bitwise NOT is a shifted mask, it is a bitmask immediate 1060 // or all-ones or all-zeros, in which case we can stop searching. Otherwise, 1061 // we halve the element size and continue the search. 1062 if (isShiftedMask_64(NewImm) || isShiftedMask_64(~(NewImm | ~Mask))) 1063 break; 1064 1065 // We cannot shrink the element size any further if it is 2-bits. 1066 if (EltSize == 2) 1067 return false; 1068 1069 EltSize /= 2; 1070 Mask >>= EltSize; 1071 uint64_t Hi = Imm >> EltSize, DemandedBitsHi = DemandedBits >> EltSize; 1072 1073 // Return if there is mismatch in any of the demanded bits of Imm and Hi. 1074 if (((Imm ^ Hi) & (DemandedBits & DemandedBitsHi) & Mask) != 0) 1075 return false; 1076 1077 // Merge the upper and lower halves of Imm and DemandedBits. 1078 Imm |= Hi; 1079 DemandedBits |= DemandedBitsHi; 1080 } 1081 1082 ++NumOptimizedImms; 1083 1084 // Replicate the element across the register width. 1085 while (EltSize < Size) { 1086 NewImm |= NewImm << EltSize; 1087 EltSize *= 2; 1088 } 1089 1090 (void)OldImm; 1091 assert(((OldImm ^ NewImm) & Demanded.getZExtValue()) == 0 && 1092 "demanded bits should never be altered"); 1093 assert(OldImm != NewImm && "the new imm shouldn't be equal to the old imm"); 1094 1095 // Create the new constant immediate node. 1096 EVT VT = Op.getValueType(); 1097 SDLoc DL(Op); 1098 SDValue New; 1099 1100 // If the new constant immediate is all-zeros or all-ones, let the target 1101 // independent DAG combine optimize this node. 1102 if (NewImm == 0 || NewImm == OrigMask) { 1103 New = TLO.DAG.getNode(Op.getOpcode(), DL, VT, Op.getOperand(0), 1104 TLO.DAG.getConstant(NewImm, DL, VT)); 1105 // Otherwise, create a machine node so that target independent DAG combine 1106 // doesn't undo this optimization. 1107 } else { 1108 Enc = AArch64_AM::encodeLogicalImmediate(NewImm, Size); 1109 SDValue EncConst = TLO.DAG.getTargetConstant(Enc, DL, VT); 1110 New = SDValue( 1111 TLO.DAG.getMachineNode(NewOpc, DL, VT, Op.getOperand(0), EncConst), 0); 1112 } 1113 1114 return TLO.CombineTo(Op, New); 1115 } 1116 1117 bool AArch64TargetLowering::targetShrinkDemandedConstant( 1118 SDValue Op, const APInt &Demanded, TargetLoweringOpt &TLO) const { 1119 // Delay this optimization to as late as possible. 1120 if (!TLO.LegalOps) 1121 return false; 1122 1123 if (!EnableOptimizeLogicalImm) 1124 return false; 1125 1126 EVT VT = Op.getValueType(); 1127 if (VT.isVector()) 1128 return false; 1129 1130 unsigned Size = VT.getSizeInBits(); 1131 assert((Size == 32 || Size == 64) && 1132 "i32 or i64 is expected after legalization."); 1133 1134 // Exit early if we demand all bits. 1135 if (Demanded.countPopulation() == Size) 1136 return false; 1137 1138 unsigned NewOpc; 1139 switch (Op.getOpcode()) { 1140 default: 1141 return false; 1142 case ISD::AND: 1143 NewOpc = Size == 32 ? AArch64::ANDWri : AArch64::ANDXri; 1144 break; 1145 case ISD::OR: 1146 NewOpc = Size == 32 ? AArch64::ORRWri : AArch64::ORRXri; 1147 break; 1148 case ISD::XOR: 1149 NewOpc = Size == 32 ? AArch64::EORWri : AArch64::EORXri; 1150 break; 1151 } 1152 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1)); 1153 if (!C) 1154 return false; 1155 uint64_t Imm = C->getZExtValue(); 1156 return optimizeLogicalImm(Op, Size, Imm, Demanded, TLO, NewOpc); 1157 } 1158 1159 /// computeKnownBitsForTargetNode - Determine which of the bits specified in 1160 /// Mask are known to be either zero or one and return them Known. 1161 void AArch64TargetLowering::computeKnownBitsForTargetNode( 1162 const SDValue Op, KnownBits &Known, 1163 const APInt &DemandedElts, const SelectionDAG &DAG, unsigned Depth) const { 1164 switch (Op.getOpcode()) { 1165 default: 1166 break; 1167 case AArch64ISD::CSEL: { 1168 KnownBits Known2; 1169 Known = DAG.computeKnownBits(Op->getOperand(0), Depth + 1); 1170 Known2 = DAG.computeKnownBits(Op->getOperand(1), Depth + 1); 1171 Known.Zero &= Known2.Zero; 1172 Known.One &= Known2.One; 1173 break; 1174 } 1175 case AArch64ISD::LOADgot: 1176 case AArch64ISD::ADDlow: { 1177 if (!Subtarget->isTargetILP32()) 1178 break; 1179 // In ILP32 mode all valid pointers are in the low 4GB of the address-space. 1180 Known.Zero = APInt::getHighBitsSet(64, 32); 1181 break; 1182 } 1183 case ISD::INTRINSIC_W_CHAIN: { 1184 ConstantSDNode *CN = cast<ConstantSDNode>(Op->getOperand(1)); 1185 Intrinsic::ID IntID = static_cast<Intrinsic::ID>(CN->getZExtValue()); 1186 switch (IntID) { 1187 default: return; 1188 case Intrinsic::aarch64_ldaxr: 1189 case Intrinsic::aarch64_ldxr: { 1190 unsigned BitWidth = Known.getBitWidth(); 1191 EVT VT = cast<MemIntrinsicSDNode>(Op)->getMemoryVT(); 1192 unsigned MemBits = VT.getScalarSizeInBits(); 1193 Known.Zero |= APInt::getHighBitsSet(BitWidth, BitWidth - MemBits); 1194 return; 1195 } 1196 } 1197 break; 1198 } 1199 case ISD::INTRINSIC_WO_CHAIN: 1200 case ISD::INTRINSIC_VOID: { 1201 unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue(); 1202 switch (IntNo) { 1203 default: 1204 break; 1205 case Intrinsic::aarch64_neon_umaxv: 1206 case Intrinsic::aarch64_neon_uminv: { 1207 // Figure out the datatype of the vector operand. The UMINV instruction 1208 // will zero extend the result, so we can mark as known zero all the 1209 // bits larger than the element datatype. 32-bit or larget doesn't need 1210 // this as those are legal types and will be handled by isel directly. 1211 MVT VT = Op.getOperand(1).getValueType().getSimpleVT(); 1212 unsigned BitWidth = Known.getBitWidth(); 1213 if (VT == MVT::v8i8 || VT == MVT::v16i8) { 1214 assert(BitWidth >= 8 && "Unexpected width!"); 1215 APInt Mask = APInt::getHighBitsSet(BitWidth, BitWidth - 8); 1216 Known.Zero |= Mask; 1217 } else if (VT == MVT::v4i16 || VT == MVT::v8i16) { 1218 assert(BitWidth >= 16 && "Unexpected width!"); 1219 APInt Mask = APInt::getHighBitsSet(BitWidth, BitWidth - 16); 1220 Known.Zero |= Mask; 1221 } 1222 break; 1223 } break; 1224 } 1225 } 1226 } 1227 } 1228 1229 MVT AArch64TargetLowering::getScalarShiftAmountTy(const DataLayout &DL, 1230 EVT) const { 1231 return MVT::i64; 1232 } 1233 1234 bool AArch64TargetLowering::allowsMisalignedMemoryAccesses( 1235 EVT VT, unsigned AddrSpace, unsigned Align, MachineMemOperand::Flags Flags, 1236 bool *Fast) const { 1237 if (Subtarget->requiresStrictAlign()) 1238 return false; 1239 1240 if (Fast) { 1241 // Some CPUs are fine with unaligned stores except for 128-bit ones. 1242 *Fast = !Subtarget->isMisaligned128StoreSlow() || VT.getStoreSize() != 16 || 1243 // See comments in performSTORECombine() for more details about 1244 // these conditions. 1245 1246 // Code that uses clang vector extensions can mark that it 1247 // wants unaligned accesses to be treated as fast by 1248 // underspecifying alignment to be 1 or 2. 1249 Align <= 2 || 1250 1251 // Disregard v2i64. Memcpy lowering produces those and splitting 1252 // them regresses performance on micro-benchmarks and olden/bh. 1253 VT == MVT::v2i64; 1254 } 1255 return true; 1256 } 1257 1258 // Same as above but handling LLTs instead. 1259 bool AArch64TargetLowering::allowsMisalignedMemoryAccesses( 1260 LLT Ty, unsigned AddrSpace, Align Alignment, MachineMemOperand::Flags Flags, 1261 bool *Fast) const { 1262 if (Subtarget->requiresStrictAlign()) 1263 return false; 1264 1265 if (Fast) { 1266 // Some CPUs are fine with unaligned stores except for 128-bit ones. 1267 *Fast = !Subtarget->isMisaligned128StoreSlow() || 1268 Ty.getSizeInBytes() != 16 || 1269 // See comments in performSTORECombine() for more details about 1270 // these conditions. 1271 1272 // Code that uses clang vector extensions can mark that it 1273 // wants unaligned accesses to be treated as fast by 1274 // underspecifying alignment to be 1 or 2. 1275 Alignment <= 2 || 1276 1277 // Disregard v2i64. Memcpy lowering produces those and splitting 1278 // them regresses performance on micro-benchmarks and olden/bh. 1279 Ty == LLT::vector(2, 64); 1280 } 1281 return true; 1282 } 1283 1284 FastISel * 1285 AArch64TargetLowering::createFastISel(FunctionLoweringInfo &funcInfo, 1286 const TargetLibraryInfo *libInfo) const { 1287 return AArch64::createFastISel(funcInfo, libInfo); 1288 } 1289 1290 const char *AArch64TargetLowering::getTargetNodeName(unsigned Opcode) const { 1291 switch ((AArch64ISD::NodeType)Opcode) { 1292 case AArch64ISD::FIRST_NUMBER: break; 1293 case AArch64ISD::CALL: return "AArch64ISD::CALL"; 1294 case AArch64ISD::ADRP: return "AArch64ISD::ADRP"; 1295 case AArch64ISD::ADR: return "AArch64ISD::ADR"; 1296 case AArch64ISD::ADDlow: return "AArch64ISD::ADDlow"; 1297 case AArch64ISD::LOADgot: return "AArch64ISD::LOADgot"; 1298 case AArch64ISD::RET_FLAG: return "AArch64ISD::RET_FLAG"; 1299 case AArch64ISD::BRCOND: return "AArch64ISD::BRCOND"; 1300 case AArch64ISD::CSEL: return "AArch64ISD::CSEL"; 1301 case AArch64ISD::FCSEL: return "AArch64ISD::FCSEL"; 1302 case AArch64ISD::CSINV: return "AArch64ISD::CSINV"; 1303 case AArch64ISD::CSNEG: return "AArch64ISD::CSNEG"; 1304 case AArch64ISD::CSINC: return "AArch64ISD::CSINC"; 1305 case AArch64ISD::THREAD_POINTER: return "AArch64ISD::THREAD_POINTER"; 1306 case AArch64ISD::TLSDESC_CALLSEQ: return "AArch64ISD::TLSDESC_CALLSEQ"; 1307 case AArch64ISD::SDIV_PRED: return "AArch64ISD::SDIV_PRED"; 1308 case AArch64ISD::UDIV_PRED: return "AArch64ISD::UDIV_PRED"; 1309 case AArch64ISD::SMIN_PRED: return "AArch64ISD::SMIN_PRED"; 1310 case AArch64ISD::UMIN_PRED: return "AArch64ISD::UMIN_PRED"; 1311 case AArch64ISD::SMAX_PRED: return "AArch64ISD::SMAX_PRED"; 1312 case AArch64ISD::UMAX_PRED: return "AArch64ISD::UMAX_PRED"; 1313 case AArch64ISD::SHL_PRED: return "AArch64ISD::SHL_PRED"; 1314 case AArch64ISD::SRL_PRED: return "AArch64ISD::SRL_PRED"; 1315 case AArch64ISD::SRA_PRED: return "AArch64ISD::SRA_PRED"; 1316 case AArch64ISD::SETCC_PRED: return "AArch64ISD::SETCC_PRED"; 1317 case AArch64ISD::ADC: return "AArch64ISD::ADC"; 1318 case AArch64ISD::SBC: return "AArch64ISD::SBC"; 1319 case AArch64ISD::ADDS: return "AArch64ISD::ADDS"; 1320 case AArch64ISD::SUBS: return "AArch64ISD::SUBS"; 1321 case AArch64ISD::ADCS: return "AArch64ISD::ADCS"; 1322 case AArch64ISD::SBCS: return "AArch64ISD::SBCS"; 1323 case AArch64ISD::ANDS: return "AArch64ISD::ANDS"; 1324 case AArch64ISD::CCMP: return "AArch64ISD::CCMP"; 1325 case AArch64ISD::CCMN: return "AArch64ISD::CCMN"; 1326 case AArch64ISD::FCCMP: return "AArch64ISD::FCCMP"; 1327 case AArch64ISD::FCMP: return "AArch64ISD::FCMP"; 1328 case AArch64ISD::STRICT_FCMP: return "AArch64ISD::STRICT_FCMP"; 1329 case AArch64ISD::STRICT_FCMPE: return "AArch64ISD::STRICT_FCMPE"; 1330 case AArch64ISD::DUP: return "AArch64ISD::DUP"; 1331 case AArch64ISD::DUPLANE8: return "AArch64ISD::DUPLANE8"; 1332 case AArch64ISD::DUPLANE16: return "AArch64ISD::DUPLANE16"; 1333 case AArch64ISD::DUPLANE32: return "AArch64ISD::DUPLANE32"; 1334 case AArch64ISD::DUPLANE64: return "AArch64ISD::DUPLANE64"; 1335 case AArch64ISD::MOVI: return "AArch64ISD::MOVI"; 1336 case AArch64ISD::MOVIshift: return "AArch64ISD::MOVIshift"; 1337 case AArch64ISD::MOVIedit: return "AArch64ISD::MOVIedit"; 1338 case AArch64ISD::MOVImsl: return "AArch64ISD::MOVImsl"; 1339 case AArch64ISD::FMOV: return "AArch64ISD::FMOV"; 1340 case AArch64ISD::MVNIshift: return "AArch64ISD::MVNIshift"; 1341 case AArch64ISD::MVNImsl: return "AArch64ISD::MVNImsl"; 1342 case AArch64ISD::BICi: return "AArch64ISD::BICi"; 1343 case AArch64ISD::ORRi: return "AArch64ISD::ORRi"; 1344 case AArch64ISD::BSP: return "AArch64ISD::BSP"; 1345 case AArch64ISD::NEG: return "AArch64ISD::NEG"; 1346 case AArch64ISD::EXTR: return "AArch64ISD::EXTR"; 1347 case AArch64ISD::ZIP1: return "AArch64ISD::ZIP1"; 1348 case AArch64ISD::ZIP2: return "AArch64ISD::ZIP2"; 1349 case AArch64ISD::UZP1: return "AArch64ISD::UZP1"; 1350 case AArch64ISD::UZP2: return "AArch64ISD::UZP2"; 1351 case AArch64ISD::TRN1: return "AArch64ISD::TRN1"; 1352 case AArch64ISD::TRN2: return "AArch64ISD::TRN2"; 1353 case AArch64ISD::REV16: return "AArch64ISD::REV16"; 1354 case AArch64ISD::REV32: return "AArch64ISD::REV32"; 1355 case AArch64ISD::REV64: return "AArch64ISD::REV64"; 1356 case AArch64ISD::EXT: return "AArch64ISD::EXT"; 1357 case AArch64ISD::VSHL: return "AArch64ISD::VSHL"; 1358 case AArch64ISD::VLSHR: return "AArch64ISD::VLSHR"; 1359 case AArch64ISD::VASHR: return "AArch64ISD::VASHR"; 1360 case AArch64ISD::VSLI: return "AArch64ISD::VSLI"; 1361 case AArch64ISD::VSRI: return "AArch64ISD::VSRI"; 1362 case AArch64ISD::CMEQ: return "AArch64ISD::CMEQ"; 1363 case AArch64ISD::CMGE: return "AArch64ISD::CMGE"; 1364 case AArch64ISD::CMGT: return "AArch64ISD::CMGT"; 1365 case AArch64ISD::CMHI: return "AArch64ISD::CMHI"; 1366 case AArch64ISD::CMHS: return "AArch64ISD::CMHS"; 1367 case AArch64ISD::FCMEQ: return "AArch64ISD::FCMEQ"; 1368 case AArch64ISD::FCMGE: return "AArch64ISD::FCMGE"; 1369 case AArch64ISD::FCMGT: return "AArch64ISD::FCMGT"; 1370 case AArch64ISD::CMEQz: return "AArch64ISD::CMEQz"; 1371 case AArch64ISD::CMGEz: return "AArch64ISD::CMGEz"; 1372 case AArch64ISD::CMGTz: return "AArch64ISD::CMGTz"; 1373 case AArch64ISD::CMLEz: return "AArch64ISD::CMLEz"; 1374 case AArch64ISD::CMLTz: return "AArch64ISD::CMLTz"; 1375 case AArch64ISD::FCMEQz: return "AArch64ISD::FCMEQz"; 1376 case AArch64ISD::FCMGEz: return "AArch64ISD::FCMGEz"; 1377 case AArch64ISD::FCMGTz: return "AArch64ISD::FCMGTz"; 1378 case AArch64ISD::FCMLEz: return "AArch64ISD::FCMLEz"; 1379 case AArch64ISD::FCMLTz: return "AArch64ISD::FCMLTz"; 1380 case AArch64ISD::SADDV: return "AArch64ISD::SADDV"; 1381 case AArch64ISD::UADDV: return "AArch64ISD::UADDV"; 1382 case AArch64ISD::SMINV: return "AArch64ISD::SMINV"; 1383 case AArch64ISD::UMINV: return "AArch64ISD::UMINV"; 1384 case AArch64ISD::SMAXV: return "AArch64ISD::SMAXV"; 1385 case AArch64ISD::UMAXV: return "AArch64ISD::UMAXV"; 1386 case AArch64ISD::SMAXV_PRED: return "AArch64ISD::SMAXV_PRED"; 1387 case AArch64ISD::UMAXV_PRED: return "AArch64ISD::UMAXV_PRED"; 1388 case AArch64ISD::SMINV_PRED: return "AArch64ISD::SMINV_PRED"; 1389 case AArch64ISD::UMINV_PRED: return "AArch64ISD::UMINV_PRED"; 1390 case AArch64ISD::ORV_PRED: return "AArch64ISD::ORV_PRED"; 1391 case AArch64ISD::EORV_PRED: return "AArch64ISD::EORV_PRED"; 1392 case AArch64ISD::ANDV_PRED: return "AArch64ISD::ANDV_PRED"; 1393 case AArch64ISD::CLASTA_N: return "AArch64ISD::CLASTA_N"; 1394 case AArch64ISD::CLASTB_N: return "AArch64ISD::CLASTB_N"; 1395 case AArch64ISD::LASTA: return "AArch64ISD::LASTA"; 1396 case AArch64ISD::LASTB: return "AArch64ISD::LASTB"; 1397 case AArch64ISD::REV: return "AArch64ISD::REV"; 1398 case AArch64ISD::REINTERPRET_CAST: return "AArch64ISD::REINTERPRET_CAST"; 1399 case AArch64ISD::TBL: return "AArch64ISD::TBL"; 1400 case AArch64ISD::FADDA_PRED: return "AArch64ISD::FADDA_PRED"; 1401 case AArch64ISD::FADDV_PRED: return "AArch64ISD::FADDV_PRED"; 1402 case AArch64ISD::FMAXV_PRED: return "AArch64ISD::FMAXV_PRED"; 1403 case AArch64ISD::FMAXNMV_PRED: return "AArch64ISD::FMAXNMV_PRED"; 1404 case AArch64ISD::FMINV_PRED: return "AArch64ISD::FMINV_PRED"; 1405 case AArch64ISD::FMINNMV_PRED: return "AArch64ISD::FMINNMV_PRED"; 1406 case AArch64ISD::NOT: return "AArch64ISD::NOT"; 1407 case AArch64ISD::BIT: return "AArch64ISD::BIT"; 1408 case AArch64ISD::CBZ: return "AArch64ISD::CBZ"; 1409 case AArch64ISD::CBNZ: return "AArch64ISD::CBNZ"; 1410 case AArch64ISD::TBZ: return "AArch64ISD::TBZ"; 1411 case AArch64ISD::TBNZ: return "AArch64ISD::TBNZ"; 1412 case AArch64ISD::TC_RETURN: return "AArch64ISD::TC_RETURN"; 1413 case AArch64ISD::PREFETCH: return "AArch64ISD::PREFETCH"; 1414 case AArch64ISD::SITOF: return "AArch64ISD::SITOF"; 1415 case AArch64ISD::UITOF: return "AArch64ISD::UITOF"; 1416 case AArch64ISD::NVCAST: return "AArch64ISD::NVCAST"; 1417 case AArch64ISD::SQSHL_I: return "AArch64ISD::SQSHL_I"; 1418 case AArch64ISD::UQSHL_I: return "AArch64ISD::UQSHL_I"; 1419 case AArch64ISD::SRSHR_I: return "AArch64ISD::SRSHR_I"; 1420 case AArch64ISD::URSHR_I: return "AArch64ISD::URSHR_I"; 1421 case AArch64ISD::SQSHLU_I: return "AArch64ISD::SQSHLU_I"; 1422 case AArch64ISD::WrapperLarge: return "AArch64ISD::WrapperLarge"; 1423 case AArch64ISD::LD2post: return "AArch64ISD::LD2post"; 1424 case AArch64ISD::LD3post: return "AArch64ISD::LD3post"; 1425 case AArch64ISD::LD4post: return "AArch64ISD::LD4post"; 1426 case AArch64ISD::ST2post: return "AArch64ISD::ST2post"; 1427 case AArch64ISD::ST3post: return "AArch64ISD::ST3post"; 1428 case AArch64ISD::ST4post: return "AArch64ISD::ST4post"; 1429 case AArch64ISD::LD1x2post: return "AArch64ISD::LD1x2post"; 1430 case AArch64ISD::LD1x3post: return "AArch64ISD::LD1x3post"; 1431 case AArch64ISD::LD1x4post: return "AArch64ISD::LD1x4post"; 1432 case AArch64ISD::ST1x2post: return "AArch64ISD::ST1x2post"; 1433 case AArch64ISD::ST1x3post: return "AArch64ISD::ST1x3post"; 1434 case AArch64ISD::ST1x4post: return "AArch64ISD::ST1x4post"; 1435 case AArch64ISD::LD1DUPpost: return "AArch64ISD::LD1DUPpost"; 1436 case AArch64ISD::LD2DUPpost: return "AArch64ISD::LD2DUPpost"; 1437 case AArch64ISD::LD3DUPpost: return "AArch64ISD::LD3DUPpost"; 1438 case AArch64ISD::LD4DUPpost: return "AArch64ISD::LD4DUPpost"; 1439 case AArch64ISD::LD1LANEpost: return "AArch64ISD::LD1LANEpost"; 1440 case AArch64ISD::LD2LANEpost: return "AArch64ISD::LD2LANEpost"; 1441 case AArch64ISD::LD3LANEpost: return "AArch64ISD::LD3LANEpost"; 1442 case AArch64ISD::LD4LANEpost: return "AArch64ISD::LD4LANEpost"; 1443 case AArch64ISD::ST2LANEpost: return "AArch64ISD::ST2LANEpost"; 1444 case AArch64ISD::ST3LANEpost: return "AArch64ISD::ST3LANEpost"; 1445 case AArch64ISD::ST4LANEpost: return "AArch64ISD::ST4LANEpost"; 1446 case AArch64ISD::SMULL: return "AArch64ISD::SMULL"; 1447 case AArch64ISD::UMULL: return "AArch64ISD::UMULL"; 1448 case AArch64ISD::FRECPE: return "AArch64ISD::FRECPE"; 1449 case AArch64ISD::FRECPS: return "AArch64ISD::FRECPS"; 1450 case AArch64ISD::FRSQRTE: return "AArch64ISD::FRSQRTE"; 1451 case AArch64ISD::FRSQRTS: return "AArch64ISD::FRSQRTS"; 1452 case AArch64ISD::STG: return "AArch64ISD::STG"; 1453 case AArch64ISD::STZG: return "AArch64ISD::STZG"; 1454 case AArch64ISD::ST2G: return "AArch64ISD::ST2G"; 1455 case AArch64ISD::STZ2G: return "AArch64ISD::STZ2G"; 1456 case AArch64ISD::SUNPKHI: return "AArch64ISD::SUNPKHI"; 1457 case AArch64ISD::SUNPKLO: return "AArch64ISD::SUNPKLO"; 1458 case AArch64ISD::UUNPKHI: return "AArch64ISD::UUNPKHI"; 1459 case AArch64ISD::UUNPKLO: return "AArch64ISD::UUNPKLO"; 1460 case AArch64ISD::INSR: return "AArch64ISD::INSR"; 1461 case AArch64ISD::PTEST: return "AArch64ISD::PTEST"; 1462 case AArch64ISD::PTRUE: return "AArch64ISD::PTRUE"; 1463 case AArch64ISD::LD1: return "AArch64ISD::LD1"; 1464 case AArch64ISD::LD1S: return "AArch64ISD::LD1S"; 1465 case AArch64ISD::LDNF1: return "AArch64ISD::LDNF1"; 1466 case AArch64ISD::LDNF1S: return "AArch64ISD::LDNF1S"; 1467 case AArch64ISD::LDFF1: return "AArch64ISD::LDFF1"; 1468 case AArch64ISD::LDFF1S: return "AArch64ISD::LDFF1S"; 1469 case AArch64ISD::LD1RQ: return "AArch64ISD::LD1RQ"; 1470 case AArch64ISD::LD1RO: return "AArch64ISD::LD1RO"; 1471 case AArch64ISD::SVE_LD2: return "AArch64ISD::SVE_LD2"; 1472 case AArch64ISD::SVE_LD3: return "AArch64ISD::SVE_LD3"; 1473 case AArch64ISD::SVE_LD4: return "AArch64ISD::SVE_LD4"; 1474 case AArch64ISD::GLD1: return "AArch64ISD::GLD1"; 1475 case AArch64ISD::GLD1_SCALED: return "AArch64ISD::GLD1_SCALED"; 1476 case AArch64ISD::GLD1_SXTW: return "AArch64ISD::GLD1_SXTW"; 1477 case AArch64ISD::GLD1_UXTW: return "AArch64ISD::GLD1_UXTW"; 1478 case AArch64ISD::GLD1_SXTW_SCALED: return "AArch64ISD::GLD1_SXTW_SCALED"; 1479 case AArch64ISD::GLD1_UXTW_SCALED: return "AArch64ISD::GLD1_UXTW_SCALED"; 1480 case AArch64ISD::GLD1_IMM: return "AArch64ISD::GLD1_IMM"; 1481 case AArch64ISD::GLD1S: return "AArch64ISD::GLD1S"; 1482 case AArch64ISD::GLD1S_SCALED: return "AArch64ISD::GLD1S_SCALED"; 1483 case AArch64ISD::GLD1S_SXTW: return "AArch64ISD::GLD1S_SXTW"; 1484 case AArch64ISD::GLD1S_UXTW: return "AArch64ISD::GLD1S_UXTW"; 1485 case AArch64ISD::GLD1S_SXTW_SCALED: return "AArch64ISD::GLD1S_SXTW_SCALED"; 1486 case AArch64ISD::GLD1S_UXTW_SCALED: return "AArch64ISD::GLD1S_UXTW_SCALED"; 1487 case AArch64ISD::GLD1S_IMM: return "AArch64ISD::GLD1S_IMM"; 1488 case AArch64ISD::GLDFF1: return "AArch64ISD::GLDFF1"; 1489 case AArch64ISD::GLDFF1_SCALED: return "AArch64ISD::GLDFF1_SCALED"; 1490 case AArch64ISD::GLDFF1_SXTW: return "AArch64ISD::GLDFF1_SXTW"; 1491 case AArch64ISD::GLDFF1_UXTW: return "AArch64ISD::GLDFF1_UXTW"; 1492 case AArch64ISD::GLDFF1_SXTW_SCALED:return "AArch64ISD::GLDFF1_SXTW_SCALED"; 1493 case AArch64ISD::GLDFF1_UXTW_SCALED:return "AArch64ISD::GLDFF1_UXTW_SCALED"; 1494 case AArch64ISD::GLDFF1_IMM: return "AArch64ISD::GLDFF1_IMM"; 1495 case AArch64ISD::GLDFF1S: return "AArch64ISD::GLDFF1S"; 1496 case AArch64ISD::GLDFF1S_SCALED: return "AArch64ISD::GLDFF1S_SCALED"; 1497 case AArch64ISD::GLDFF1S_SXTW: return "AArch64ISD::GLDFF1S_SXTW"; 1498 case AArch64ISD::GLDFF1S_UXTW: return "AArch64ISD::GLDFF1S_UXTW"; 1499 case AArch64ISD::GLDFF1S_SXTW_SCALED: 1500 return "AArch64ISD::GLDFF1S_SXTW_SCALED"; 1501 case AArch64ISD::GLDFF1S_UXTW_SCALED: 1502 return "AArch64ISD::GLDFF1S_UXTW_SCALED"; 1503 case AArch64ISD::GLDFF1S_IMM: return "AArch64ISD::GLDFF1S_IMM"; 1504 1505 case AArch64ISD::GLDNT1: return "AArch64ISD::GLDNT1"; 1506 case AArch64ISD::GLDNT1_INDEX: return "AArch64ISD::GLDNT1_INDEX"; 1507 case AArch64ISD::GLDNT1S: return "AArch64ISD::GLDNT1S"; 1508 1509 case AArch64ISD::ST1: return "AArch64ISD::ST1"; 1510 1511 case AArch64ISD::SST1: return "AArch64ISD::SST1"; 1512 case AArch64ISD::SST1_SCALED: return "AArch64ISD::SST1_SCALED"; 1513 case AArch64ISD::SST1_SXTW: return "AArch64ISD::SST1_SXTW"; 1514 case AArch64ISD::SST1_UXTW: return "AArch64ISD::SST1_UXTW"; 1515 case AArch64ISD::SST1_SXTW_SCALED: return "AArch64ISD::SST1_SXTW_SCALED"; 1516 case AArch64ISD::SST1_UXTW_SCALED: return "AArch64ISD::SST1_UXTW_SCALED"; 1517 case AArch64ISD::SST1_IMM: return "AArch64ISD::SST1_IMM"; 1518 1519 case AArch64ISD::SSTNT1: return "AArch64ISD::SSTNT1"; 1520 case AArch64ISD::SSTNT1_INDEX: return "AArch64ISD::SSTNT1_INDEX"; 1521 1522 case AArch64ISD::LDP: return "AArch64ISD::LDP"; 1523 case AArch64ISD::STP: return "AArch64ISD::STP"; 1524 case AArch64ISD::STNP: return "AArch64ISD::STNP"; 1525 case AArch64ISD::DUP_PRED: return "AArch64ISD::DUP_PRED"; 1526 case AArch64ISD::INDEX_VECTOR: return "AArch64ISD::INDEX_VECTOR"; 1527 } 1528 return nullptr; 1529 } 1530 1531 MachineBasicBlock * 1532 AArch64TargetLowering::EmitF128CSEL(MachineInstr &MI, 1533 MachineBasicBlock *MBB) const { 1534 // We materialise the F128CSEL pseudo-instruction as some control flow and a 1535 // phi node: 1536 1537 // OrigBB: 1538 // [... previous instrs leading to comparison ...] 1539 // b.ne TrueBB 1540 // b EndBB 1541 // TrueBB: 1542 // ; Fallthrough 1543 // EndBB: 1544 // Dest = PHI [IfTrue, TrueBB], [IfFalse, OrigBB] 1545 1546 MachineFunction *MF = MBB->getParent(); 1547 const TargetInstrInfo *TII = Subtarget->getInstrInfo(); 1548 const BasicBlock *LLVM_BB = MBB->getBasicBlock(); 1549 DebugLoc DL = MI.getDebugLoc(); 1550 MachineFunction::iterator It = ++MBB->getIterator(); 1551 1552 Register DestReg = MI.getOperand(0).getReg(); 1553 Register IfTrueReg = MI.getOperand(1).getReg(); 1554 Register IfFalseReg = MI.getOperand(2).getReg(); 1555 unsigned CondCode = MI.getOperand(3).getImm(); 1556 bool NZCVKilled = MI.getOperand(4).isKill(); 1557 1558 MachineBasicBlock *TrueBB = MF->CreateMachineBasicBlock(LLVM_BB); 1559 MachineBasicBlock *EndBB = MF->CreateMachineBasicBlock(LLVM_BB); 1560 MF->insert(It, TrueBB); 1561 MF->insert(It, EndBB); 1562 1563 // Transfer rest of current basic-block to EndBB 1564 EndBB->splice(EndBB->begin(), MBB, std::next(MachineBasicBlock::iterator(MI)), 1565 MBB->end()); 1566 EndBB->transferSuccessorsAndUpdatePHIs(MBB); 1567 1568 BuildMI(MBB, DL, TII->get(AArch64::Bcc)).addImm(CondCode).addMBB(TrueBB); 1569 BuildMI(MBB, DL, TII->get(AArch64::B)).addMBB(EndBB); 1570 MBB->addSuccessor(TrueBB); 1571 MBB->addSuccessor(EndBB); 1572 1573 // TrueBB falls through to the end. 1574 TrueBB->addSuccessor(EndBB); 1575 1576 if (!NZCVKilled) { 1577 TrueBB->addLiveIn(AArch64::NZCV); 1578 EndBB->addLiveIn(AArch64::NZCV); 1579 } 1580 1581 BuildMI(*EndBB, EndBB->begin(), DL, TII->get(AArch64::PHI), DestReg) 1582 .addReg(IfTrueReg) 1583 .addMBB(TrueBB) 1584 .addReg(IfFalseReg) 1585 .addMBB(MBB); 1586 1587 MI.eraseFromParent(); 1588 return EndBB; 1589 } 1590 1591 MachineBasicBlock *AArch64TargetLowering::EmitLoweredCatchRet( 1592 MachineInstr &MI, MachineBasicBlock *BB) const { 1593 assert(!isAsynchronousEHPersonality(classifyEHPersonality( 1594 BB->getParent()->getFunction().getPersonalityFn())) && 1595 "SEH does not use catchret!"); 1596 return BB; 1597 } 1598 1599 MachineBasicBlock *AArch64TargetLowering::EmitInstrWithCustomInserter( 1600 MachineInstr &MI, MachineBasicBlock *BB) const { 1601 switch (MI.getOpcode()) { 1602 default: 1603 #ifndef NDEBUG 1604 MI.dump(); 1605 #endif 1606 llvm_unreachable("Unexpected instruction for custom inserter!"); 1607 1608 case AArch64::F128CSEL: 1609 return EmitF128CSEL(MI, BB); 1610 1611 case TargetOpcode::STACKMAP: 1612 case TargetOpcode::PATCHPOINT: 1613 return emitPatchPoint(MI, BB); 1614 1615 case AArch64::CATCHRET: 1616 return EmitLoweredCatchRet(MI, BB); 1617 } 1618 } 1619 1620 //===----------------------------------------------------------------------===// 1621 // AArch64 Lowering private implementation. 1622 //===----------------------------------------------------------------------===// 1623 1624 //===----------------------------------------------------------------------===// 1625 // Lowering Code 1626 //===----------------------------------------------------------------------===// 1627 1628 /// changeIntCCToAArch64CC - Convert a DAG integer condition code to an AArch64 1629 /// CC 1630 static AArch64CC::CondCode changeIntCCToAArch64CC(ISD::CondCode CC) { 1631 switch (CC) { 1632 default: 1633 llvm_unreachable("Unknown condition code!"); 1634 case ISD::SETNE: 1635 return AArch64CC::NE; 1636 case ISD::SETEQ: 1637 return AArch64CC::EQ; 1638 case ISD::SETGT: 1639 return AArch64CC::GT; 1640 case ISD::SETGE: 1641 return AArch64CC::GE; 1642 case ISD::SETLT: 1643 return AArch64CC::LT; 1644 case ISD::SETLE: 1645 return AArch64CC::LE; 1646 case ISD::SETUGT: 1647 return AArch64CC::HI; 1648 case ISD::SETUGE: 1649 return AArch64CC::HS; 1650 case ISD::SETULT: 1651 return AArch64CC::LO; 1652 case ISD::SETULE: 1653 return AArch64CC::LS; 1654 } 1655 } 1656 1657 /// changeFPCCToAArch64CC - Convert a DAG fp condition code to an AArch64 CC. 1658 static void changeFPCCToAArch64CC(ISD::CondCode CC, 1659 AArch64CC::CondCode &CondCode, 1660 AArch64CC::CondCode &CondCode2) { 1661 CondCode2 = AArch64CC::AL; 1662 switch (CC) { 1663 default: 1664 llvm_unreachable("Unknown FP condition!"); 1665 case ISD::SETEQ: 1666 case ISD::SETOEQ: 1667 CondCode = AArch64CC::EQ; 1668 break; 1669 case ISD::SETGT: 1670 case ISD::SETOGT: 1671 CondCode = AArch64CC::GT; 1672 break; 1673 case ISD::SETGE: 1674 case ISD::SETOGE: 1675 CondCode = AArch64CC::GE; 1676 break; 1677 case ISD::SETOLT: 1678 CondCode = AArch64CC::MI; 1679 break; 1680 case ISD::SETOLE: 1681 CondCode = AArch64CC::LS; 1682 break; 1683 case ISD::SETONE: 1684 CondCode = AArch64CC::MI; 1685 CondCode2 = AArch64CC::GT; 1686 break; 1687 case ISD::SETO: 1688 CondCode = AArch64CC::VC; 1689 break; 1690 case ISD::SETUO: 1691 CondCode = AArch64CC::VS; 1692 break; 1693 case ISD::SETUEQ: 1694 CondCode = AArch64CC::EQ; 1695 CondCode2 = AArch64CC::VS; 1696 break; 1697 case ISD::SETUGT: 1698 CondCode = AArch64CC::HI; 1699 break; 1700 case ISD::SETUGE: 1701 CondCode = AArch64CC::PL; 1702 break; 1703 case ISD::SETLT: 1704 case ISD::SETULT: 1705 CondCode = AArch64CC::LT; 1706 break; 1707 case ISD::SETLE: 1708 case ISD::SETULE: 1709 CondCode = AArch64CC::LE; 1710 break; 1711 case ISD::SETNE: 1712 case ISD::SETUNE: 1713 CondCode = AArch64CC::NE; 1714 break; 1715 } 1716 } 1717 1718 /// Convert a DAG fp condition code to an AArch64 CC. 1719 /// This differs from changeFPCCToAArch64CC in that it returns cond codes that 1720 /// should be AND'ed instead of OR'ed. 1721 static void changeFPCCToANDAArch64CC(ISD::CondCode CC, 1722 AArch64CC::CondCode &CondCode, 1723 AArch64CC::CondCode &CondCode2) { 1724 CondCode2 = AArch64CC::AL; 1725 switch (CC) { 1726 default: 1727 changeFPCCToAArch64CC(CC, CondCode, CondCode2); 1728 assert(CondCode2 == AArch64CC::AL); 1729 break; 1730 case ISD::SETONE: 1731 // (a one b) 1732 // == ((a olt b) || (a ogt b)) 1733 // == ((a ord b) && (a une b)) 1734 CondCode = AArch64CC::VC; 1735 CondCode2 = AArch64CC::NE; 1736 break; 1737 case ISD::SETUEQ: 1738 // (a ueq b) 1739 // == ((a uno b) || (a oeq b)) 1740 // == ((a ule b) && (a uge b)) 1741 CondCode = AArch64CC::PL; 1742 CondCode2 = AArch64CC::LE; 1743 break; 1744 } 1745 } 1746 1747 /// changeVectorFPCCToAArch64CC - Convert a DAG fp condition code to an AArch64 1748 /// CC usable with the vector instructions. Fewer operations are available 1749 /// without a real NZCV register, so we have to use less efficient combinations 1750 /// to get the same effect. 1751 static void changeVectorFPCCToAArch64CC(ISD::CondCode CC, 1752 AArch64CC::CondCode &CondCode, 1753 AArch64CC::CondCode &CondCode2, 1754 bool &Invert) { 1755 Invert = false; 1756 switch (CC) { 1757 default: 1758 // Mostly the scalar mappings work fine. 1759 changeFPCCToAArch64CC(CC, CondCode, CondCode2); 1760 break; 1761 case ISD::SETUO: 1762 Invert = true; 1763 LLVM_FALLTHROUGH; 1764 case ISD::SETO: 1765 CondCode = AArch64CC::MI; 1766 CondCode2 = AArch64CC::GE; 1767 break; 1768 case ISD::SETUEQ: 1769 case ISD::SETULT: 1770 case ISD::SETULE: 1771 case ISD::SETUGT: 1772 case ISD::SETUGE: 1773 // All of the compare-mask comparisons are ordered, but we can switch 1774 // between the two by a double inversion. E.g. ULE == !OGT. 1775 Invert = true; 1776 changeFPCCToAArch64CC(getSetCCInverse(CC, /* FP inverse */ MVT::f32), 1777 CondCode, CondCode2); 1778 break; 1779 } 1780 } 1781 1782 static bool isLegalArithImmed(uint64_t C) { 1783 // Matches AArch64DAGToDAGISel::SelectArithImmed(). 1784 bool IsLegal = (C >> 12 == 0) || ((C & 0xFFFULL) == 0 && C >> 24 == 0); 1785 LLVM_DEBUG(dbgs() << "Is imm " << C 1786 << " legal: " << (IsLegal ? "yes\n" : "no\n")); 1787 return IsLegal; 1788 } 1789 1790 // Can a (CMP op1, (sub 0, op2) be turned into a CMN instruction on 1791 // the grounds that "op1 - (-op2) == op1 + op2" ? Not always, the C and V flags 1792 // can be set differently by this operation. It comes down to whether 1793 // "SInt(~op2)+1 == SInt(~op2+1)" (and the same for UInt). If they are then 1794 // everything is fine. If not then the optimization is wrong. Thus general 1795 // comparisons are only valid if op2 != 0. 1796 // 1797 // So, finally, the only LLVM-native comparisons that don't mention C and V 1798 // are SETEQ and SETNE. They're the only ones we can safely use CMN for in 1799 // the absence of information about op2. 1800 static bool isCMN(SDValue Op, ISD::CondCode CC) { 1801 return Op.getOpcode() == ISD::SUB && isNullConstant(Op.getOperand(0)) && 1802 (CC == ISD::SETEQ || CC == ISD::SETNE); 1803 } 1804 1805 static SDValue emitStrictFPComparison(SDValue LHS, SDValue RHS, const SDLoc &dl, 1806 SelectionDAG &DAG, SDValue Chain, 1807 bool IsSignaling) { 1808 EVT VT = LHS.getValueType(); 1809 assert(VT != MVT::f128); 1810 assert(VT != MVT::f16 && "Lowering of strict fp16 not yet implemented"); 1811 unsigned Opcode = 1812 IsSignaling ? AArch64ISD::STRICT_FCMPE : AArch64ISD::STRICT_FCMP; 1813 return DAG.getNode(Opcode, dl, {VT, MVT::Other}, {Chain, LHS, RHS}); 1814 } 1815 1816 static SDValue emitComparison(SDValue LHS, SDValue RHS, ISD::CondCode CC, 1817 const SDLoc &dl, SelectionDAG &DAG) { 1818 EVT VT = LHS.getValueType(); 1819 const bool FullFP16 = 1820 static_cast<const AArch64Subtarget &>(DAG.getSubtarget()).hasFullFP16(); 1821 1822 if (VT.isFloatingPoint()) { 1823 assert(VT != MVT::f128); 1824 if (VT == MVT::f16 && !FullFP16) { 1825 LHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f32, LHS); 1826 RHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f32, RHS); 1827 VT = MVT::f32; 1828 } 1829 return DAG.getNode(AArch64ISD::FCMP, dl, VT, LHS, RHS); 1830 } 1831 1832 // The CMP instruction is just an alias for SUBS, and representing it as 1833 // SUBS means that it's possible to get CSE with subtract operations. 1834 // A later phase can perform the optimization of setting the destination 1835 // register to WZR/XZR if it ends up being unused. 1836 unsigned Opcode = AArch64ISD::SUBS; 1837 1838 if (isCMN(RHS, CC)) { 1839 // Can we combine a (CMP op1, (sub 0, op2) into a CMN instruction ? 1840 Opcode = AArch64ISD::ADDS; 1841 RHS = RHS.getOperand(1); 1842 } else if (isCMN(LHS, CC)) { 1843 // As we are looking for EQ/NE compares, the operands can be commuted ; can 1844 // we combine a (CMP (sub 0, op1), op2) into a CMN instruction ? 1845 Opcode = AArch64ISD::ADDS; 1846 LHS = LHS.getOperand(1); 1847 } else if (isNullConstant(RHS) && !isUnsignedIntSetCC(CC)) { 1848 if (LHS.getOpcode() == ISD::AND) { 1849 // Similarly, (CMP (and X, Y), 0) can be implemented with a TST 1850 // (a.k.a. ANDS) except that the flags are only guaranteed to work for one 1851 // of the signed comparisons. 1852 const SDValue ANDSNode = DAG.getNode(AArch64ISD::ANDS, dl, 1853 DAG.getVTList(VT, MVT_CC), 1854 LHS.getOperand(0), 1855 LHS.getOperand(1)); 1856 // Replace all users of (and X, Y) with newly generated (ands X, Y) 1857 DAG.ReplaceAllUsesWith(LHS, ANDSNode); 1858 return ANDSNode.getValue(1); 1859 } else if (LHS.getOpcode() == AArch64ISD::ANDS) { 1860 // Use result of ANDS 1861 return LHS.getValue(1); 1862 } 1863 } 1864 1865 return DAG.getNode(Opcode, dl, DAG.getVTList(VT, MVT_CC), LHS, RHS) 1866 .getValue(1); 1867 } 1868 1869 /// \defgroup AArch64CCMP CMP;CCMP matching 1870 /// 1871 /// These functions deal with the formation of CMP;CCMP;... sequences. 1872 /// The CCMP/CCMN/FCCMP/FCCMPE instructions allow the conditional execution of 1873 /// a comparison. They set the NZCV flags to a predefined value if their 1874 /// predicate is false. This allows to express arbitrary conjunctions, for 1875 /// example "cmp 0 (and (setCA (cmp A)) (setCB (cmp B)))" 1876 /// expressed as: 1877 /// cmp A 1878 /// ccmp B, inv(CB), CA 1879 /// check for CB flags 1880 /// 1881 /// This naturally lets us implement chains of AND operations with SETCC 1882 /// operands. And we can even implement some other situations by transforming 1883 /// them: 1884 /// - We can implement (NEG SETCC) i.e. negating a single comparison by 1885 /// negating the flags used in a CCMP/FCCMP operations. 1886 /// - We can negate the result of a whole chain of CMP/CCMP/FCCMP operations 1887 /// by negating the flags we test for afterwards. i.e. 1888 /// NEG (CMP CCMP CCCMP ...) can be implemented. 1889 /// - Note that we can only ever negate all previously processed results. 1890 /// What we can not implement by flipping the flags to test is a negation 1891 /// of two sub-trees (because the negation affects all sub-trees emitted so 1892 /// far, so the 2nd sub-tree we emit would also affect the first). 1893 /// With those tools we can implement some OR operations: 1894 /// - (OR (SETCC A) (SETCC B)) can be implemented via: 1895 /// NEG (AND (NEG (SETCC A)) (NEG (SETCC B))) 1896 /// - After transforming OR to NEG/AND combinations we may be able to use NEG 1897 /// elimination rules from earlier to implement the whole thing as a 1898 /// CCMP/FCCMP chain. 1899 /// 1900 /// As complete example: 1901 /// or (or (setCA (cmp A)) (setCB (cmp B))) 1902 /// (and (setCC (cmp C)) (setCD (cmp D)))" 1903 /// can be reassociated to: 1904 /// or (and (setCC (cmp C)) setCD (cmp D)) 1905 // (or (setCA (cmp A)) (setCB (cmp B))) 1906 /// can be transformed to: 1907 /// not (and (not (and (setCC (cmp C)) (setCD (cmp D)))) 1908 /// (and (not (setCA (cmp A)) (not (setCB (cmp B))))))" 1909 /// which can be implemented as: 1910 /// cmp C 1911 /// ccmp D, inv(CD), CC 1912 /// ccmp A, CA, inv(CD) 1913 /// ccmp B, CB, inv(CA) 1914 /// check for CB flags 1915 /// 1916 /// A counterexample is "or (and A B) (and C D)" which translates to 1917 /// not (and (not (and (not A) (not B))) (not (and (not C) (not D)))), we 1918 /// can only implement 1 of the inner (not) operations, but not both! 1919 /// @{ 1920 1921 /// Create a conditional comparison; Use CCMP, CCMN or FCCMP as appropriate. 1922 static SDValue emitConditionalComparison(SDValue LHS, SDValue RHS, 1923 ISD::CondCode CC, SDValue CCOp, 1924 AArch64CC::CondCode Predicate, 1925 AArch64CC::CondCode OutCC, 1926 const SDLoc &DL, SelectionDAG &DAG) { 1927 unsigned Opcode = 0; 1928 const bool FullFP16 = 1929 static_cast<const AArch64Subtarget &>(DAG.getSubtarget()).hasFullFP16(); 1930 1931 if (LHS.getValueType().isFloatingPoint()) { 1932 assert(LHS.getValueType() != MVT::f128); 1933 if (LHS.getValueType() == MVT::f16 && !FullFP16) { 1934 LHS = DAG.getNode(ISD::FP_EXTEND, DL, MVT::f32, LHS); 1935 RHS = DAG.getNode(ISD::FP_EXTEND, DL, MVT::f32, RHS); 1936 } 1937 Opcode = AArch64ISD::FCCMP; 1938 } else if (RHS.getOpcode() == ISD::SUB) { 1939 SDValue SubOp0 = RHS.getOperand(0); 1940 if (isNullConstant(SubOp0) && (CC == ISD::SETEQ || CC == ISD::SETNE)) { 1941 // See emitComparison() on why we can only do this for SETEQ and SETNE. 1942 Opcode = AArch64ISD::CCMN; 1943 RHS = RHS.getOperand(1); 1944 } 1945 } 1946 if (Opcode == 0) 1947 Opcode = AArch64ISD::CCMP; 1948 1949 SDValue Condition = DAG.getConstant(Predicate, DL, MVT_CC); 1950 AArch64CC::CondCode InvOutCC = AArch64CC::getInvertedCondCode(OutCC); 1951 unsigned NZCV = AArch64CC::getNZCVToSatisfyCondCode(InvOutCC); 1952 SDValue NZCVOp = DAG.getConstant(NZCV, DL, MVT::i32); 1953 return DAG.getNode(Opcode, DL, MVT_CC, LHS, RHS, NZCVOp, Condition, CCOp); 1954 } 1955 1956 /// Returns true if @p Val is a tree of AND/OR/SETCC operations that can be 1957 /// expressed as a conjunction. See \ref AArch64CCMP. 1958 /// \param CanNegate Set to true if we can negate the whole sub-tree just by 1959 /// changing the conditions on the SETCC tests. 1960 /// (this means we can call emitConjunctionRec() with 1961 /// Negate==true on this sub-tree) 1962 /// \param MustBeFirst Set to true if this subtree needs to be negated and we 1963 /// cannot do the negation naturally. We are required to 1964 /// emit the subtree first in this case. 1965 /// \param WillNegate Is true if are called when the result of this 1966 /// subexpression must be negated. This happens when the 1967 /// outer expression is an OR. We can use this fact to know 1968 /// that we have a double negation (or (or ...) ...) that 1969 /// can be implemented for free. 1970 static bool canEmitConjunction(const SDValue Val, bool &CanNegate, 1971 bool &MustBeFirst, bool WillNegate, 1972 unsigned Depth = 0) { 1973 if (!Val.hasOneUse()) 1974 return false; 1975 unsigned Opcode = Val->getOpcode(); 1976 if (Opcode == ISD::SETCC) { 1977 if (Val->getOperand(0).getValueType() == MVT::f128) 1978 return false; 1979 CanNegate = true; 1980 MustBeFirst = false; 1981 return true; 1982 } 1983 // Protect against exponential runtime and stack overflow. 1984 if (Depth > 6) 1985 return false; 1986 if (Opcode == ISD::AND || Opcode == ISD::OR) { 1987 bool IsOR = Opcode == ISD::OR; 1988 SDValue O0 = Val->getOperand(0); 1989 SDValue O1 = Val->getOperand(1); 1990 bool CanNegateL; 1991 bool MustBeFirstL; 1992 if (!canEmitConjunction(O0, CanNegateL, MustBeFirstL, IsOR, Depth+1)) 1993 return false; 1994 bool CanNegateR; 1995 bool MustBeFirstR; 1996 if (!canEmitConjunction(O1, CanNegateR, MustBeFirstR, IsOR, Depth+1)) 1997 return false; 1998 1999 if (MustBeFirstL && MustBeFirstR) 2000 return false; 2001 2002 if (IsOR) { 2003 // For an OR expression we need to be able to naturally negate at least 2004 // one side or we cannot do the transformation at all. 2005 if (!CanNegateL && !CanNegateR) 2006 return false; 2007 // If we the result of the OR will be negated and we can naturally negate 2008 // the leafs, then this sub-tree as a whole negates naturally. 2009 CanNegate = WillNegate && CanNegateL && CanNegateR; 2010 // If we cannot naturally negate the whole sub-tree, then this must be 2011 // emitted first. 2012 MustBeFirst = !CanNegate; 2013 } else { 2014 assert(Opcode == ISD::AND && "Must be OR or AND"); 2015 // We cannot naturally negate an AND operation. 2016 CanNegate = false; 2017 MustBeFirst = MustBeFirstL || MustBeFirstR; 2018 } 2019 return true; 2020 } 2021 return false; 2022 } 2023 2024 /// Emit conjunction or disjunction tree with the CMP/FCMP followed by a chain 2025 /// of CCMP/CFCMP ops. See @ref AArch64CCMP. 2026 /// Tries to transform the given i1 producing node @p Val to a series compare 2027 /// and conditional compare operations. @returns an NZCV flags producing node 2028 /// and sets @p OutCC to the flags that should be tested or returns SDValue() if 2029 /// transformation was not possible. 2030 /// \p Negate is true if we want this sub-tree being negated just by changing 2031 /// SETCC conditions. 2032 static SDValue emitConjunctionRec(SelectionDAG &DAG, SDValue Val, 2033 AArch64CC::CondCode &OutCC, bool Negate, SDValue CCOp, 2034 AArch64CC::CondCode Predicate) { 2035 // We're at a tree leaf, produce a conditional comparison operation. 2036 unsigned Opcode = Val->getOpcode(); 2037 if (Opcode == ISD::SETCC) { 2038 SDValue LHS = Val->getOperand(0); 2039 SDValue RHS = Val->getOperand(1); 2040 ISD::CondCode CC = cast<CondCodeSDNode>(Val->getOperand(2))->get(); 2041 bool isInteger = LHS.getValueType().isInteger(); 2042 if (Negate) 2043 CC = getSetCCInverse(CC, LHS.getValueType()); 2044 SDLoc DL(Val); 2045 // Determine OutCC and handle FP special case. 2046 if (isInteger) { 2047 OutCC = changeIntCCToAArch64CC(CC); 2048 } else { 2049 assert(LHS.getValueType().isFloatingPoint()); 2050 AArch64CC::CondCode ExtraCC; 2051 changeFPCCToANDAArch64CC(CC, OutCC, ExtraCC); 2052 // Some floating point conditions can't be tested with a single condition 2053 // code. Construct an additional comparison in this case. 2054 if (ExtraCC != AArch64CC::AL) { 2055 SDValue ExtraCmp; 2056 if (!CCOp.getNode()) 2057 ExtraCmp = emitComparison(LHS, RHS, CC, DL, DAG); 2058 else 2059 ExtraCmp = emitConditionalComparison(LHS, RHS, CC, CCOp, Predicate, 2060 ExtraCC, DL, DAG); 2061 CCOp = ExtraCmp; 2062 Predicate = ExtraCC; 2063 } 2064 } 2065 2066 // Produce a normal comparison if we are first in the chain 2067 if (!CCOp) 2068 return emitComparison(LHS, RHS, CC, DL, DAG); 2069 // Otherwise produce a ccmp. 2070 return emitConditionalComparison(LHS, RHS, CC, CCOp, Predicate, OutCC, DL, 2071 DAG); 2072 } 2073 assert(Val->hasOneUse() && "Valid conjunction/disjunction tree"); 2074 2075 bool IsOR = Opcode == ISD::OR; 2076 2077 SDValue LHS = Val->getOperand(0); 2078 bool CanNegateL; 2079 bool MustBeFirstL; 2080 bool ValidL = canEmitConjunction(LHS, CanNegateL, MustBeFirstL, IsOR); 2081 assert(ValidL && "Valid conjunction/disjunction tree"); 2082 (void)ValidL; 2083 2084 SDValue RHS = Val->getOperand(1); 2085 bool CanNegateR; 2086 bool MustBeFirstR; 2087 bool ValidR = canEmitConjunction(RHS, CanNegateR, MustBeFirstR, IsOR); 2088 assert(ValidR && "Valid conjunction/disjunction tree"); 2089 (void)ValidR; 2090 2091 // Swap sub-tree that must come first to the right side. 2092 if (MustBeFirstL) { 2093 assert(!MustBeFirstR && "Valid conjunction/disjunction tree"); 2094 std::swap(LHS, RHS); 2095 std::swap(CanNegateL, CanNegateR); 2096 std::swap(MustBeFirstL, MustBeFirstR); 2097 } 2098 2099 bool NegateR; 2100 bool NegateAfterR; 2101 bool NegateL; 2102 bool NegateAfterAll; 2103 if (Opcode == ISD::OR) { 2104 // Swap the sub-tree that we can negate naturally to the left. 2105 if (!CanNegateL) { 2106 assert(CanNegateR && "at least one side must be negatable"); 2107 assert(!MustBeFirstR && "invalid conjunction/disjunction tree"); 2108 assert(!Negate); 2109 std::swap(LHS, RHS); 2110 NegateR = false; 2111 NegateAfterR = true; 2112 } else { 2113 // Negate the left sub-tree if possible, otherwise negate the result. 2114 NegateR = CanNegateR; 2115 NegateAfterR = !CanNegateR; 2116 } 2117 NegateL = true; 2118 NegateAfterAll = !Negate; 2119 } else { 2120 assert(Opcode == ISD::AND && "Valid conjunction/disjunction tree"); 2121 assert(!Negate && "Valid conjunction/disjunction tree"); 2122 2123 NegateL = false; 2124 NegateR = false; 2125 NegateAfterR = false; 2126 NegateAfterAll = false; 2127 } 2128 2129 // Emit sub-trees. 2130 AArch64CC::CondCode RHSCC; 2131 SDValue CmpR = emitConjunctionRec(DAG, RHS, RHSCC, NegateR, CCOp, Predicate); 2132 if (NegateAfterR) 2133 RHSCC = AArch64CC::getInvertedCondCode(RHSCC); 2134 SDValue CmpL = emitConjunctionRec(DAG, LHS, OutCC, NegateL, CmpR, RHSCC); 2135 if (NegateAfterAll) 2136 OutCC = AArch64CC::getInvertedCondCode(OutCC); 2137 return CmpL; 2138 } 2139 2140 /// Emit expression as a conjunction (a series of CCMP/CFCMP ops). 2141 /// In some cases this is even possible with OR operations in the expression. 2142 /// See \ref AArch64CCMP. 2143 /// \see emitConjunctionRec(). 2144 static SDValue emitConjunction(SelectionDAG &DAG, SDValue Val, 2145 AArch64CC::CondCode &OutCC) { 2146 bool DummyCanNegate; 2147 bool DummyMustBeFirst; 2148 if (!canEmitConjunction(Val, DummyCanNegate, DummyMustBeFirst, false)) 2149 return SDValue(); 2150 2151 return emitConjunctionRec(DAG, Val, OutCC, false, SDValue(), AArch64CC::AL); 2152 } 2153 2154 /// @} 2155 2156 /// Returns how profitable it is to fold a comparison's operand's shift and/or 2157 /// extension operations. 2158 static unsigned getCmpOperandFoldingProfit(SDValue Op) { 2159 auto isSupportedExtend = [&](SDValue V) { 2160 if (V.getOpcode() == ISD::SIGN_EXTEND_INREG) 2161 return true; 2162 2163 if (V.getOpcode() == ISD::AND) 2164 if (ConstantSDNode *MaskCst = dyn_cast<ConstantSDNode>(V.getOperand(1))) { 2165 uint64_t Mask = MaskCst->getZExtValue(); 2166 return (Mask == 0xFF || Mask == 0xFFFF || Mask == 0xFFFFFFFF); 2167 } 2168 2169 return false; 2170 }; 2171 2172 if (!Op.hasOneUse()) 2173 return 0; 2174 2175 if (isSupportedExtend(Op)) 2176 return 1; 2177 2178 unsigned Opc = Op.getOpcode(); 2179 if (Opc == ISD::SHL || Opc == ISD::SRL || Opc == ISD::SRA) 2180 if (ConstantSDNode *ShiftCst = dyn_cast<ConstantSDNode>(Op.getOperand(1))) { 2181 uint64_t Shift = ShiftCst->getZExtValue(); 2182 if (isSupportedExtend(Op.getOperand(0))) 2183 return (Shift <= 4) ? 2 : 1; 2184 EVT VT = Op.getValueType(); 2185 if ((VT == MVT::i32 && Shift <= 31) || (VT == MVT::i64 && Shift <= 63)) 2186 return 1; 2187 } 2188 2189 return 0; 2190 } 2191 2192 static SDValue getAArch64Cmp(SDValue LHS, SDValue RHS, ISD::CondCode CC, 2193 SDValue &AArch64cc, SelectionDAG &DAG, 2194 const SDLoc &dl) { 2195 if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS.getNode())) { 2196 EVT VT = RHS.getValueType(); 2197 uint64_t C = RHSC->getZExtValue(); 2198 if (!isLegalArithImmed(C)) { 2199 // Constant does not fit, try adjusting it by one? 2200 switch (CC) { 2201 default: 2202 break; 2203 case ISD::SETLT: 2204 case ISD::SETGE: 2205 if ((VT == MVT::i32 && C != 0x80000000 && 2206 isLegalArithImmed((uint32_t)(C - 1))) || 2207 (VT == MVT::i64 && C != 0x80000000ULL && 2208 isLegalArithImmed(C - 1ULL))) { 2209 CC = (CC == ISD::SETLT) ? ISD::SETLE : ISD::SETGT; 2210 C = (VT == MVT::i32) ? (uint32_t)(C - 1) : C - 1; 2211 RHS = DAG.getConstant(C, dl, VT); 2212 } 2213 break; 2214 case ISD::SETULT: 2215 case ISD::SETUGE: 2216 if ((VT == MVT::i32 && C != 0 && 2217 isLegalArithImmed((uint32_t)(C - 1))) || 2218 (VT == MVT::i64 && C != 0ULL && isLegalArithImmed(C - 1ULL))) { 2219 CC = (CC == ISD::SETULT) ? ISD::SETULE : ISD::SETUGT; 2220 C = (VT == MVT::i32) ? (uint32_t)(C - 1) : C - 1; 2221 RHS = DAG.getConstant(C, dl, VT); 2222 } 2223 break; 2224 case ISD::SETLE: 2225 case ISD::SETGT: 2226 if ((VT == MVT::i32 && C != INT32_MAX && 2227 isLegalArithImmed((uint32_t)(C + 1))) || 2228 (VT == MVT::i64 && C != INT64_MAX && 2229 isLegalArithImmed(C + 1ULL))) { 2230 CC = (CC == ISD::SETLE) ? ISD::SETLT : ISD::SETGE; 2231 C = (VT == MVT::i32) ? (uint32_t)(C + 1) : C + 1; 2232 RHS = DAG.getConstant(C, dl, VT); 2233 } 2234 break; 2235 case ISD::SETULE: 2236 case ISD::SETUGT: 2237 if ((VT == MVT::i32 && C != UINT32_MAX && 2238 isLegalArithImmed((uint32_t)(C + 1))) || 2239 (VT == MVT::i64 && C != UINT64_MAX && 2240 isLegalArithImmed(C + 1ULL))) { 2241 CC = (CC == ISD::SETULE) ? ISD::SETULT : ISD::SETUGE; 2242 C = (VT == MVT::i32) ? (uint32_t)(C + 1) : C + 1; 2243 RHS = DAG.getConstant(C, dl, VT); 2244 } 2245 break; 2246 } 2247 } 2248 } 2249 2250 // Comparisons are canonicalized so that the RHS operand is simpler than the 2251 // LHS one, the extreme case being when RHS is an immediate. However, AArch64 2252 // can fold some shift+extend operations on the RHS operand, so swap the 2253 // operands if that can be done. 2254 // 2255 // For example: 2256 // lsl w13, w11, #1 2257 // cmp w13, w12 2258 // can be turned into: 2259 // cmp w12, w11, lsl #1 2260 if (!isa<ConstantSDNode>(RHS) || 2261 !isLegalArithImmed(cast<ConstantSDNode>(RHS)->getZExtValue())) { 2262 SDValue TheLHS = isCMN(LHS, CC) ? LHS.getOperand(1) : LHS; 2263 2264 if (getCmpOperandFoldingProfit(TheLHS) > getCmpOperandFoldingProfit(RHS)) { 2265 std::swap(LHS, RHS); 2266 CC = ISD::getSetCCSwappedOperands(CC); 2267 } 2268 } 2269 2270 SDValue Cmp; 2271 AArch64CC::CondCode AArch64CC; 2272 if ((CC == ISD::SETEQ || CC == ISD::SETNE) && isa<ConstantSDNode>(RHS)) { 2273 const ConstantSDNode *RHSC = cast<ConstantSDNode>(RHS); 2274 2275 // The imm operand of ADDS is an unsigned immediate, in the range 0 to 4095. 2276 // For the i8 operand, the largest immediate is 255, so this can be easily 2277 // encoded in the compare instruction. For the i16 operand, however, the 2278 // largest immediate cannot be encoded in the compare. 2279 // Therefore, use a sign extending load and cmn to avoid materializing the 2280 // -1 constant. For example, 2281 // movz w1, #65535 2282 // ldrh w0, [x0, #0] 2283 // cmp w0, w1 2284 // > 2285 // ldrsh w0, [x0, #0] 2286 // cmn w0, #1 2287 // Fundamental, we're relying on the property that (zext LHS) == (zext RHS) 2288 // if and only if (sext LHS) == (sext RHS). The checks are in place to 2289 // ensure both the LHS and RHS are truly zero extended and to make sure the 2290 // transformation is profitable. 2291 if ((RHSC->getZExtValue() >> 16 == 0) && isa<LoadSDNode>(LHS) && 2292 cast<LoadSDNode>(LHS)->getExtensionType() == ISD::ZEXTLOAD && 2293 cast<LoadSDNode>(LHS)->getMemoryVT() == MVT::i16 && 2294 LHS.getNode()->hasNUsesOfValue(1, 0)) { 2295 int16_t ValueofRHS = cast<ConstantSDNode>(RHS)->getZExtValue(); 2296 if (ValueofRHS < 0 && isLegalArithImmed(-ValueofRHS)) { 2297 SDValue SExt = 2298 DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, LHS.getValueType(), LHS, 2299 DAG.getValueType(MVT::i16)); 2300 Cmp = emitComparison(SExt, DAG.getConstant(ValueofRHS, dl, 2301 RHS.getValueType()), 2302 CC, dl, DAG); 2303 AArch64CC = changeIntCCToAArch64CC(CC); 2304 } 2305 } 2306 2307 if (!Cmp && (RHSC->isNullValue() || RHSC->isOne())) { 2308 if ((Cmp = emitConjunction(DAG, LHS, AArch64CC))) { 2309 if ((CC == ISD::SETNE) ^ RHSC->isNullValue()) 2310 AArch64CC = AArch64CC::getInvertedCondCode(AArch64CC); 2311 } 2312 } 2313 } 2314 2315 if (!Cmp) { 2316 Cmp = emitComparison(LHS, RHS, CC, dl, DAG); 2317 AArch64CC = changeIntCCToAArch64CC(CC); 2318 } 2319 AArch64cc = DAG.getConstant(AArch64CC, dl, MVT_CC); 2320 return Cmp; 2321 } 2322 2323 static std::pair<SDValue, SDValue> 2324 getAArch64XALUOOp(AArch64CC::CondCode &CC, SDValue Op, SelectionDAG &DAG) { 2325 assert((Op.getValueType() == MVT::i32 || Op.getValueType() == MVT::i64) && 2326 "Unsupported value type"); 2327 SDValue Value, Overflow; 2328 SDLoc DL(Op); 2329 SDValue LHS = Op.getOperand(0); 2330 SDValue RHS = Op.getOperand(1); 2331 unsigned Opc = 0; 2332 switch (Op.getOpcode()) { 2333 default: 2334 llvm_unreachable("Unknown overflow instruction!"); 2335 case ISD::SADDO: 2336 Opc = AArch64ISD::ADDS; 2337 CC = AArch64CC::VS; 2338 break; 2339 case ISD::UADDO: 2340 Opc = AArch64ISD::ADDS; 2341 CC = AArch64CC::HS; 2342 break; 2343 case ISD::SSUBO: 2344 Opc = AArch64ISD::SUBS; 2345 CC = AArch64CC::VS; 2346 break; 2347 case ISD::USUBO: 2348 Opc = AArch64ISD::SUBS; 2349 CC = AArch64CC::LO; 2350 break; 2351 // Multiply needs a little bit extra work. 2352 case ISD::SMULO: 2353 case ISD::UMULO: { 2354 CC = AArch64CC::NE; 2355 bool IsSigned = Op.getOpcode() == ISD::SMULO; 2356 if (Op.getValueType() == MVT::i32) { 2357 unsigned ExtendOpc = IsSigned ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND; 2358 // For a 32 bit multiply with overflow check we want the instruction 2359 // selector to generate a widening multiply (SMADDL/UMADDL). For that we 2360 // need to generate the following pattern: 2361 // (i64 add 0, (i64 mul (i64 sext|zext i32 %a), (i64 sext|zext i32 %b)) 2362 LHS = DAG.getNode(ExtendOpc, DL, MVT::i64, LHS); 2363 RHS = DAG.getNode(ExtendOpc, DL, MVT::i64, RHS); 2364 SDValue Mul = DAG.getNode(ISD::MUL, DL, MVT::i64, LHS, RHS); 2365 SDValue Add = DAG.getNode(ISD::ADD, DL, MVT::i64, Mul, 2366 DAG.getConstant(0, DL, MVT::i64)); 2367 // On AArch64 the upper 32 bits are always zero extended for a 32 bit 2368 // operation. We need to clear out the upper 32 bits, because we used a 2369 // widening multiply that wrote all 64 bits. In the end this should be a 2370 // noop. 2371 Value = DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Add); 2372 if (IsSigned) { 2373 // The signed overflow check requires more than just a simple check for 2374 // any bit set in the upper 32 bits of the result. These bits could be 2375 // just the sign bits of a negative number. To perform the overflow 2376 // check we have to arithmetic shift right the 32nd bit of the result by 2377 // 31 bits. Then we compare the result to the upper 32 bits. 2378 SDValue UpperBits = DAG.getNode(ISD::SRL, DL, MVT::i64, Add, 2379 DAG.getConstant(32, DL, MVT::i64)); 2380 UpperBits = DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, UpperBits); 2381 SDValue LowerBits = DAG.getNode(ISD::SRA, DL, MVT::i32, Value, 2382 DAG.getConstant(31, DL, MVT::i64)); 2383 // It is important that LowerBits is last, otherwise the arithmetic 2384 // shift will not be folded into the compare (SUBS). 2385 SDVTList VTs = DAG.getVTList(MVT::i32, MVT::i32); 2386 Overflow = DAG.getNode(AArch64ISD::SUBS, DL, VTs, UpperBits, LowerBits) 2387 .getValue(1); 2388 } else { 2389 // The overflow check for unsigned multiply is easy. We only need to 2390 // check if any of the upper 32 bits are set. This can be done with a 2391 // CMP (shifted register). For that we need to generate the following 2392 // pattern: 2393 // (i64 AArch64ISD::SUBS i64 0, (i64 srl i64 %Mul, i64 32) 2394 SDValue UpperBits = DAG.getNode(ISD::SRL, DL, MVT::i64, Mul, 2395 DAG.getConstant(32, DL, MVT::i64)); 2396 SDVTList VTs = DAG.getVTList(MVT::i64, MVT::i32); 2397 Overflow = 2398 DAG.getNode(AArch64ISD::SUBS, DL, VTs, 2399 DAG.getConstant(0, DL, MVT::i64), 2400 UpperBits).getValue(1); 2401 } 2402 break; 2403 } 2404 assert(Op.getValueType() == MVT::i64 && "Expected an i64 value type"); 2405 // For the 64 bit multiply 2406 Value = DAG.getNode(ISD::MUL, DL, MVT::i64, LHS, RHS); 2407 if (IsSigned) { 2408 SDValue UpperBits = DAG.getNode(ISD::MULHS, DL, MVT::i64, LHS, RHS); 2409 SDValue LowerBits = DAG.getNode(ISD::SRA, DL, MVT::i64, Value, 2410 DAG.getConstant(63, DL, MVT::i64)); 2411 // It is important that LowerBits is last, otherwise the arithmetic 2412 // shift will not be folded into the compare (SUBS). 2413 SDVTList VTs = DAG.getVTList(MVT::i64, MVT::i32); 2414 Overflow = DAG.getNode(AArch64ISD::SUBS, DL, VTs, UpperBits, LowerBits) 2415 .getValue(1); 2416 } else { 2417 SDValue UpperBits = DAG.getNode(ISD::MULHU, DL, MVT::i64, LHS, RHS); 2418 SDVTList VTs = DAG.getVTList(MVT::i64, MVT::i32); 2419 Overflow = 2420 DAG.getNode(AArch64ISD::SUBS, DL, VTs, 2421 DAG.getConstant(0, DL, MVT::i64), 2422 UpperBits).getValue(1); 2423 } 2424 break; 2425 } 2426 } // switch (...) 2427 2428 if (Opc) { 2429 SDVTList VTs = DAG.getVTList(Op->getValueType(0), MVT::i32); 2430 2431 // Emit the AArch64 operation with overflow check. 2432 Value = DAG.getNode(Opc, DL, VTs, LHS, RHS); 2433 Overflow = Value.getValue(1); 2434 } 2435 return std::make_pair(Value, Overflow); 2436 } 2437 2438 SDValue AArch64TargetLowering::LowerF128Call(SDValue Op, SelectionDAG &DAG, 2439 RTLIB::Libcall Call) const { 2440 bool IsStrict = Op->isStrictFPOpcode(); 2441 unsigned Offset = IsStrict ? 1 : 0; 2442 SDValue Chain = IsStrict ? Op.getOperand(0) : SDValue(); 2443 SmallVector<SDValue, 2> Ops(Op->op_begin() + Offset, Op->op_end()); 2444 MakeLibCallOptions CallOptions; 2445 SDValue Result; 2446 SDLoc dl(Op); 2447 std::tie(Result, Chain) = makeLibCall(DAG, Call, Op.getValueType(), Ops, 2448 CallOptions, dl, Chain); 2449 return IsStrict ? DAG.getMergeValues({Result, Chain}, dl) : Result; 2450 } 2451 2452 static SDValue LowerXOR(SDValue Op, SelectionDAG &DAG) { 2453 SDValue Sel = Op.getOperand(0); 2454 SDValue Other = Op.getOperand(1); 2455 SDLoc dl(Sel); 2456 2457 // If the operand is an overflow checking operation, invert the condition 2458 // code and kill the Not operation. I.e., transform: 2459 // (xor (overflow_op_bool, 1)) 2460 // --> 2461 // (csel 1, 0, invert(cc), overflow_op_bool) 2462 // ... which later gets transformed to just a cset instruction with an 2463 // inverted condition code, rather than a cset + eor sequence. 2464 if (isOneConstant(Other) && ISD::isOverflowIntrOpRes(Sel)) { 2465 // Only lower legal XALUO ops. 2466 if (!DAG.getTargetLoweringInfo().isTypeLegal(Sel->getValueType(0))) 2467 return SDValue(); 2468 2469 SDValue TVal = DAG.getConstant(1, dl, MVT::i32); 2470 SDValue FVal = DAG.getConstant(0, dl, MVT::i32); 2471 AArch64CC::CondCode CC; 2472 SDValue Value, Overflow; 2473 std::tie(Value, Overflow) = getAArch64XALUOOp(CC, Sel.getValue(0), DAG); 2474 SDValue CCVal = DAG.getConstant(getInvertedCondCode(CC), dl, MVT::i32); 2475 return DAG.getNode(AArch64ISD::CSEL, dl, Op.getValueType(), TVal, FVal, 2476 CCVal, Overflow); 2477 } 2478 // If neither operand is a SELECT_CC, give up. 2479 if (Sel.getOpcode() != ISD::SELECT_CC) 2480 std::swap(Sel, Other); 2481 if (Sel.getOpcode() != ISD::SELECT_CC) 2482 return Op; 2483 2484 // The folding we want to perform is: 2485 // (xor x, (select_cc a, b, cc, 0, -1) ) 2486 // --> 2487 // (csel x, (xor x, -1), cc ...) 2488 // 2489 // The latter will get matched to a CSINV instruction. 2490 2491 ISD::CondCode CC = cast<CondCodeSDNode>(Sel.getOperand(4))->get(); 2492 SDValue LHS = Sel.getOperand(0); 2493 SDValue RHS = Sel.getOperand(1); 2494 SDValue TVal = Sel.getOperand(2); 2495 SDValue FVal = Sel.getOperand(3); 2496 2497 // FIXME: This could be generalized to non-integer comparisons. 2498 if (LHS.getValueType() != MVT::i32 && LHS.getValueType() != MVT::i64) 2499 return Op; 2500 2501 ConstantSDNode *CFVal = dyn_cast<ConstantSDNode>(FVal); 2502 ConstantSDNode *CTVal = dyn_cast<ConstantSDNode>(TVal); 2503 2504 // The values aren't constants, this isn't the pattern we're looking for. 2505 if (!CFVal || !CTVal) 2506 return Op; 2507 2508 // We can commute the SELECT_CC by inverting the condition. This 2509 // might be needed to make this fit into a CSINV pattern. 2510 if (CTVal->isAllOnesValue() && CFVal->isNullValue()) { 2511 std::swap(TVal, FVal); 2512 std::swap(CTVal, CFVal); 2513 CC = ISD::getSetCCInverse(CC, LHS.getValueType()); 2514 } 2515 2516 // If the constants line up, perform the transform! 2517 if (CTVal->isNullValue() && CFVal->isAllOnesValue()) { 2518 SDValue CCVal; 2519 SDValue Cmp = getAArch64Cmp(LHS, RHS, CC, CCVal, DAG, dl); 2520 2521 FVal = Other; 2522 TVal = DAG.getNode(ISD::XOR, dl, Other.getValueType(), Other, 2523 DAG.getConstant(-1ULL, dl, Other.getValueType())); 2524 2525 return DAG.getNode(AArch64ISD::CSEL, dl, Sel.getValueType(), FVal, TVal, 2526 CCVal, Cmp); 2527 } 2528 2529 return Op; 2530 } 2531 2532 static SDValue LowerADDC_ADDE_SUBC_SUBE(SDValue Op, SelectionDAG &DAG) { 2533 EVT VT = Op.getValueType(); 2534 2535 // Let legalize expand this if it isn't a legal type yet. 2536 if (!DAG.getTargetLoweringInfo().isTypeLegal(VT)) 2537 return SDValue(); 2538 2539 SDVTList VTs = DAG.getVTList(VT, MVT::i32); 2540 2541 unsigned Opc; 2542 bool ExtraOp = false; 2543 switch (Op.getOpcode()) { 2544 default: 2545 llvm_unreachable("Invalid code"); 2546 case ISD::ADDC: 2547 Opc = AArch64ISD::ADDS; 2548 break; 2549 case ISD::SUBC: 2550 Opc = AArch64ISD::SUBS; 2551 break; 2552 case ISD::ADDE: 2553 Opc = AArch64ISD::ADCS; 2554 ExtraOp = true; 2555 break; 2556 case ISD::SUBE: 2557 Opc = AArch64ISD::SBCS; 2558 ExtraOp = true; 2559 break; 2560 } 2561 2562 if (!ExtraOp) 2563 return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0), Op.getOperand(1)); 2564 return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0), Op.getOperand(1), 2565 Op.getOperand(2)); 2566 } 2567 2568 static SDValue LowerXALUO(SDValue Op, SelectionDAG &DAG) { 2569 // Let legalize expand this if it isn't a legal type yet. 2570 if (!DAG.getTargetLoweringInfo().isTypeLegal(Op.getValueType())) 2571 return SDValue(); 2572 2573 SDLoc dl(Op); 2574 AArch64CC::CondCode CC; 2575 // The actual operation that sets the overflow or carry flag. 2576 SDValue Value, Overflow; 2577 std::tie(Value, Overflow) = getAArch64XALUOOp(CC, Op, DAG); 2578 2579 // We use 0 and 1 as false and true values. 2580 SDValue TVal = DAG.getConstant(1, dl, MVT::i32); 2581 SDValue FVal = DAG.getConstant(0, dl, MVT::i32); 2582 2583 // We use an inverted condition, because the conditional select is inverted 2584 // too. This will allow it to be selected to a single instruction: 2585 // CSINC Wd, WZR, WZR, invert(cond). 2586 SDValue CCVal = DAG.getConstant(getInvertedCondCode(CC), dl, MVT::i32); 2587 Overflow = DAG.getNode(AArch64ISD::CSEL, dl, MVT::i32, FVal, TVal, 2588 CCVal, Overflow); 2589 2590 SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32); 2591 return DAG.getNode(ISD::MERGE_VALUES, dl, VTs, Value, Overflow); 2592 } 2593 2594 // Prefetch operands are: 2595 // 1: Address to prefetch 2596 // 2: bool isWrite 2597 // 3: int locality (0 = no locality ... 3 = extreme locality) 2598 // 4: bool isDataCache 2599 static SDValue LowerPREFETCH(SDValue Op, SelectionDAG &DAG) { 2600 SDLoc DL(Op); 2601 unsigned IsWrite = cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue(); 2602 unsigned Locality = cast<ConstantSDNode>(Op.getOperand(3))->getZExtValue(); 2603 unsigned IsData = cast<ConstantSDNode>(Op.getOperand(4))->getZExtValue(); 2604 2605 bool IsStream = !Locality; 2606 // When the locality number is set 2607 if (Locality) { 2608 // The front-end should have filtered out the out-of-range values 2609 assert(Locality <= 3 && "Prefetch locality out-of-range"); 2610 // The locality degree is the opposite of the cache speed. 2611 // Put the number the other way around. 2612 // The encoding starts at 0 for level 1 2613 Locality = 3 - Locality; 2614 } 2615 2616 // built the mask value encoding the expected behavior. 2617 unsigned PrfOp = (IsWrite << 4) | // Load/Store bit 2618 (!IsData << 3) | // IsDataCache bit 2619 (Locality << 1) | // Cache level bits 2620 (unsigned)IsStream; // Stream bit 2621 return DAG.getNode(AArch64ISD::PREFETCH, DL, MVT::Other, Op.getOperand(0), 2622 DAG.getConstant(PrfOp, DL, MVT::i32), Op.getOperand(1)); 2623 } 2624 2625 SDValue AArch64TargetLowering::LowerFP_EXTEND(SDValue Op, 2626 SelectionDAG &DAG) const { 2627 assert(Op.getValueType() == MVT::f128 && "Unexpected lowering"); 2628 2629 RTLIB::Libcall LC; 2630 LC = RTLIB::getFPEXT(Op.getOperand(0).getValueType(), Op.getValueType()); 2631 2632 return LowerF128Call(Op, DAG, LC); 2633 } 2634 2635 SDValue AArch64TargetLowering::LowerFP_ROUND(SDValue Op, 2636 SelectionDAG &DAG) const { 2637 bool IsStrict = Op->isStrictFPOpcode(); 2638 SDValue SrcVal = Op.getOperand(IsStrict ? 1 : 0); 2639 if (SrcVal.getValueType() != MVT::f128) { 2640 // It's legal except when f128 is involved 2641 return Op; 2642 } 2643 2644 RTLIB::Libcall LC; 2645 LC = RTLIB::getFPROUND(SrcVal.getValueType(), Op.getValueType()); 2646 2647 // FP_ROUND node has a second operand indicating whether it is known to be 2648 // precise. That doesn't take part in the LibCall so we can't directly use 2649 // LowerF128Call. 2650 MakeLibCallOptions CallOptions; 2651 SDValue Chain = IsStrict ? Op.getOperand(0) : SDValue(); 2652 SDValue Result; 2653 SDLoc dl(Op); 2654 std::tie(Result, Chain) = makeLibCall(DAG, LC, Op.getValueType(), SrcVal, 2655 CallOptions, dl, Chain); 2656 return IsStrict ? DAG.getMergeValues({Result, Chain}, dl) : Result; 2657 } 2658 2659 SDValue AArch64TargetLowering::LowerVectorFP_TO_INT(SDValue Op, 2660 SelectionDAG &DAG) const { 2661 // Warning: We maintain cost tables in AArch64TargetTransformInfo.cpp. 2662 // Any additional optimization in this function should be recorded 2663 // in the cost tables. 2664 EVT InVT = Op.getOperand(0).getValueType(); 2665 EVT VT = Op.getValueType(); 2666 unsigned NumElts = InVT.getVectorNumElements(); 2667 2668 // f16 conversions are promoted to f32 when full fp16 is not supported. 2669 if (InVT.getVectorElementType() == MVT::f16 && 2670 !Subtarget->hasFullFP16()) { 2671 MVT NewVT = MVT::getVectorVT(MVT::f32, NumElts); 2672 SDLoc dl(Op); 2673 return DAG.getNode( 2674 Op.getOpcode(), dl, Op.getValueType(), 2675 DAG.getNode(ISD::FP_EXTEND, dl, NewVT, Op.getOperand(0))); 2676 } 2677 2678 if (VT.getSizeInBits() < InVT.getSizeInBits()) { 2679 SDLoc dl(Op); 2680 SDValue Cv = 2681 DAG.getNode(Op.getOpcode(), dl, InVT.changeVectorElementTypeToInteger(), 2682 Op.getOperand(0)); 2683 return DAG.getNode(ISD::TRUNCATE, dl, VT, Cv); 2684 } 2685 2686 if (VT.getSizeInBits() > InVT.getSizeInBits()) { 2687 SDLoc dl(Op); 2688 MVT ExtVT = 2689 MVT::getVectorVT(MVT::getFloatingPointVT(VT.getScalarSizeInBits()), 2690 VT.getVectorNumElements()); 2691 SDValue Ext = DAG.getNode(ISD::FP_EXTEND, dl, ExtVT, Op.getOperand(0)); 2692 return DAG.getNode(Op.getOpcode(), dl, VT, Ext); 2693 } 2694 2695 // Type changing conversions are illegal. 2696 return Op; 2697 } 2698 2699 SDValue AArch64TargetLowering::LowerFP_TO_INT(SDValue Op, 2700 SelectionDAG &DAG) const { 2701 bool IsStrict = Op->isStrictFPOpcode(); 2702 SDValue SrcVal = Op.getOperand(IsStrict ? 1 : 0); 2703 2704 if (SrcVal.getValueType().isVector()) 2705 return LowerVectorFP_TO_INT(Op, DAG); 2706 2707 // f16 conversions are promoted to f32 when full fp16 is not supported. 2708 if (SrcVal.getValueType() == MVT::f16 && !Subtarget->hasFullFP16()) { 2709 assert(!IsStrict && "Lowering of strict fp16 not yet implemented"); 2710 SDLoc dl(Op); 2711 return DAG.getNode( 2712 Op.getOpcode(), dl, Op.getValueType(), 2713 DAG.getNode(ISD::FP_EXTEND, dl, MVT::f32, SrcVal)); 2714 } 2715 2716 if (SrcVal.getValueType() != MVT::f128) { 2717 // It's legal except when f128 is involved 2718 return Op; 2719 } 2720 2721 RTLIB::Libcall LC; 2722 if (Op.getOpcode() == ISD::FP_TO_SINT || 2723 Op.getOpcode() == ISD::STRICT_FP_TO_SINT) 2724 LC = RTLIB::getFPTOSINT(SrcVal.getValueType(), Op.getValueType()); 2725 else 2726 LC = RTLIB::getFPTOUINT(SrcVal.getValueType(), Op.getValueType()); 2727 2728 return LowerF128Call(Op, DAG, LC); 2729 } 2730 2731 static SDValue LowerVectorINT_TO_FP(SDValue Op, SelectionDAG &DAG) { 2732 // Warning: We maintain cost tables in AArch64TargetTransformInfo.cpp. 2733 // Any additional optimization in this function should be recorded 2734 // in the cost tables. 2735 EVT VT = Op.getValueType(); 2736 SDLoc dl(Op); 2737 SDValue In = Op.getOperand(0); 2738 EVT InVT = In.getValueType(); 2739 2740 if (VT.getSizeInBits() < InVT.getSizeInBits()) { 2741 MVT CastVT = 2742 MVT::getVectorVT(MVT::getFloatingPointVT(InVT.getScalarSizeInBits()), 2743 InVT.getVectorNumElements()); 2744 In = DAG.getNode(Op.getOpcode(), dl, CastVT, In); 2745 return DAG.getNode(ISD::FP_ROUND, dl, VT, In, DAG.getIntPtrConstant(0, dl)); 2746 } 2747 2748 if (VT.getSizeInBits() > InVT.getSizeInBits()) { 2749 unsigned CastOpc = 2750 Op.getOpcode() == ISD::SINT_TO_FP ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND; 2751 EVT CastVT = VT.changeVectorElementTypeToInteger(); 2752 In = DAG.getNode(CastOpc, dl, CastVT, In); 2753 return DAG.getNode(Op.getOpcode(), dl, VT, In); 2754 } 2755 2756 return Op; 2757 } 2758 2759 SDValue AArch64TargetLowering::LowerINT_TO_FP(SDValue Op, 2760 SelectionDAG &DAG) const { 2761 if (Op.getValueType().isVector()) 2762 return LowerVectorINT_TO_FP(Op, DAG); 2763 2764 bool IsStrict = Op->isStrictFPOpcode(); 2765 SDValue SrcVal = Op.getOperand(IsStrict ? 1 : 0); 2766 2767 // f16 conversions are promoted to f32 when full fp16 is not supported. 2768 if (Op.getValueType() == MVT::f16 && 2769 !Subtarget->hasFullFP16()) { 2770 assert(!IsStrict && "Lowering of strict fp16 not yet implemented"); 2771 SDLoc dl(Op); 2772 return DAG.getNode( 2773 ISD::FP_ROUND, dl, MVT::f16, 2774 DAG.getNode(Op.getOpcode(), dl, MVT::f32, SrcVal), 2775 DAG.getIntPtrConstant(0, dl)); 2776 } 2777 2778 // i128 conversions are libcalls. 2779 if (SrcVal.getValueType() == MVT::i128) 2780 return SDValue(); 2781 2782 // Other conversions are legal, unless it's to the completely software-based 2783 // fp128. 2784 if (Op.getValueType() != MVT::f128) 2785 return Op; 2786 2787 RTLIB::Libcall LC; 2788 if (Op.getOpcode() == ISD::SINT_TO_FP || 2789 Op.getOpcode() == ISD::STRICT_SINT_TO_FP) 2790 LC = RTLIB::getSINTTOFP(SrcVal.getValueType(), Op.getValueType()); 2791 else 2792 LC = RTLIB::getUINTTOFP(SrcVal.getValueType(), Op.getValueType()); 2793 2794 return LowerF128Call(Op, DAG, LC); 2795 } 2796 2797 SDValue AArch64TargetLowering::LowerFSINCOS(SDValue Op, 2798 SelectionDAG &DAG) const { 2799 // For iOS, we want to call an alternative entry point: __sincos_stret, 2800 // which returns the values in two S / D registers. 2801 SDLoc dl(Op); 2802 SDValue Arg = Op.getOperand(0); 2803 EVT ArgVT = Arg.getValueType(); 2804 Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext()); 2805 2806 ArgListTy Args; 2807 ArgListEntry Entry; 2808 2809 Entry.Node = Arg; 2810 Entry.Ty = ArgTy; 2811 Entry.IsSExt = false; 2812 Entry.IsZExt = false; 2813 Args.push_back(Entry); 2814 2815 RTLIB::Libcall LC = ArgVT == MVT::f64 ? RTLIB::SINCOS_STRET_F64 2816 : RTLIB::SINCOS_STRET_F32; 2817 const char *LibcallName = getLibcallName(LC); 2818 SDValue Callee = 2819 DAG.getExternalSymbol(LibcallName, getPointerTy(DAG.getDataLayout())); 2820 2821 StructType *RetTy = StructType::get(ArgTy, ArgTy); 2822 TargetLowering::CallLoweringInfo CLI(DAG); 2823 CLI.setDebugLoc(dl) 2824 .setChain(DAG.getEntryNode()) 2825 .setLibCallee(CallingConv::Fast, RetTy, Callee, std::move(Args)); 2826 2827 std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI); 2828 return CallResult.first; 2829 } 2830 2831 static SDValue LowerBITCAST(SDValue Op, SelectionDAG &DAG) { 2832 EVT OpVT = Op.getValueType(); 2833 if (OpVT != MVT::f16 && OpVT != MVT::bf16) 2834 return SDValue(); 2835 2836 assert(Op.getOperand(0).getValueType() == MVT::i16); 2837 SDLoc DL(Op); 2838 2839 Op = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i32, Op.getOperand(0)); 2840 Op = DAG.getNode(ISD::BITCAST, DL, MVT::f32, Op); 2841 return SDValue( 2842 DAG.getMachineNode(TargetOpcode::EXTRACT_SUBREG, DL, OpVT, Op, 2843 DAG.getTargetConstant(AArch64::hsub, DL, MVT::i32)), 2844 0); 2845 } 2846 2847 static EVT getExtensionTo64Bits(const EVT &OrigVT) { 2848 if (OrigVT.getSizeInBits() >= 64) 2849 return OrigVT; 2850 2851 assert(OrigVT.isSimple() && "Expecting a simple value type"); 2852 2853 MVT::SimpleValueType OrigSimpleTy = OrigVT.getSimpleVT().SimpleTy; 2854 switch (OrigSimpleTy) { 2855 default: llvm_unreachable("Unexpected Vector Type"); 2856 case MVT::v2i8: 2857 case MVT::v2i16: 2858 return MVT::v2i32; 2859 case MVT::v4i8: 2860 return MVT::v4i16; 2861 } 2862 } 2863 2864 static SDValue addRequiredExtensionForVectorMULL(SDValue N, SelectionDAG &DAG, 2865 const EVT &OrigTy, 2866 const EVT &ExtTy, 2867 unsigned ExtOpcode) { 2868 // The vector originally had a size of OrigTy. It was then extended to ExtTy. 2869 // We expect the ExtTy to be 128-bits total. If the OrigTy is less than 2870 // 64-bits we need to insert a new extension so that it will be 64-bits. 2871 assert(ExtTy.is128BitVector() && "Unexpected extension size"); 2872 if (OrigTy.getSizeInBits() >= 64) 2873 return N; 2874 2875 // Must extend size to at least 64 bits to be used as an operand for VMULL. 2876 EVT NewVT = getExtensionTo64Bits(OrigTy); 2877 2878 return DAG.getNode(ExtOpcode, SDLoc(N), NewVT, N); 2879 } 2880 2881 static bool isExtendedBUILD_VECTOR(SDNode *N, SelectionDAG &DAG, 2882 bool isSigned) { 2883 EVT VT = N->getValueType(0); 2884 2885 if (N->getOpcode() != ISD::BUILD_VECTOR) 2886 return false; 2887 2888 for (const SDValue &Elt : N->op_values()) { 2889 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Elt)) { 2890 unsigned EltSize = VT.getScalarSizeInBits(); 2891 unsigned HalfSize = EltSize / 2; 2892 if (isSigned) { 2893 if (!isIntN(HalfSize, C->getSExtValue())) 2894 return false; 2895 } else { 2896 if (!isUIntN(HalfSize, C->getZExtValue())) 2897 return false; 2898 } 2899 continue; 2900 } 2901 return false; 2902 } 2903 2904 return true; 2905 } 2906 2907 static SDValue skipExtensionForVectorMULL(SDNode *N, SelectionDAG &DAG) { 2908 if (N->getOpcode() == ISD::SIGN_EXTEND || N->getOpcode() == ISD::ZERO_EXTEND) 2909 return addRequiredExtensionForVectorMULL(N->getOperand(0), DAG, 2910 N->getOperand(0)->getValueType(0), 2911 N->getValueType(0), 2912 N->getOpcode()); 2913 2914 assert(N->getOpcode() == ISD::BUILD_VECTOR && "expected BUILD_VECTOR"); 2915 EVT VT = N->getValueType(0); 2916 SDLoc dl(N); 2917 unsigned EltSize = VT.getScalarSizeInBits() / 2; 2918 unsigned NumElts = VT.getVectorNumElements(); 2919 MVT TruncVT = MVT::getIntegerVT(EltSize); 2920 SmallVector<SDValue, 8> Ops; 2921 for (unsigned i = 0; i != NumElts; ++i) { 2922 ConstantSDNode *C = cast<ConstantSDNode>(N->getOperand(i)); 2923 const APInt &CInt = C->getAPIntValue(); 2924 // Element types smaller than 32 bits are not legal, so use i32 elements. 2925 // The values are implicitly truncated so sext vs. zext doesn't matter. 2926 Ops.push_back(DAG.getConstant(CInt.zextOrTrunc(32), dl, MVT::i32)); 2927 } 2928 return DAG.getBuildVector(MVT::getVectorVT(TruncVT, NumElts), dl, Ops); 2929 } 2930 2931 static bool isSignExtended(SDNode *N, SelectionDAG &DAG) { 2932 return N->getOpcode() == ISD::SIGN_EXTEND || 2933 isExtendedBUILD_VECTOR(N, DAG, true); 2934 } 2935 2936 static bool isZeroExtended(SDNode *N, SelectionDAG &DAG) { 2937 return N->getOpcode() == ISD::ZERO_EXTEND || 2938 isExtendedBUILD_VECTOR(N, DAG, false); 2939 } 2940 2941 static bool isAddSubSExt(SDNode *N, SelectionDAG &DAG) { 2942 unsigned Opcode = N->getOpcode(); 2943 if (Opcode == ISD::ADD || Opcode == ISD::SUB) { 2944 SDNode *N0 = N->getOperand(0).getNode(); 2945 SDNode *N1 = N->getOperand(1).getNode(); 2946 return N0->hasOneUse() && N1->hasOneUse() && 2947 isSignExtended(N0, DAG) && isSignExtended(N1, DAG); 2948 } 2949 return false; 2950 } 2951 2952 static bool isAddSubZExt(SDNode *N, SelectionDAG &DAG) { 2953 unsigned Opcode = N->getOpcode(); 2954 if (Opcode == ISD::ADD || Opcode == ISD::SUB) { 2955 SDNode *N0 = N->getOperand(0).getNode(); 2956 SDNode *N1 = N->getOperand(1).getNode(); 2957 return N0->hasOneUse() && N1->hasOneUse() && 2958 isZeroExtended(N0, DAG) && isZeroExtended(N1, DAG); 2959 } 2960 return false; 2961 } 2962 2963 SDValue AArch64TargetLowering::LowerFLT_ROUNDS_(SDValue Op, 2964 SelectionDAG &DAG) const { 2965 // The rounding mode is in bits 23:22 of the FPSCR. 2966 // The ARM rounding mode value to FLT_ROUNDS mapping is 0->1, 1->2, 2->3, 3->0 2967 // The formula we use to implement this is (((FPSCR + 1 << 22) >> 22) & 3) 2968 // so that the shift + and get folded into a bitfield extract. 2969 SDLoc dl(Op); 2970 2971 SDValue Chain = Op.getOperand(0); 2972 SDValue FPCR_64 = DAG.getNode( 2973 ISD::INTRINSIC_W_CHAIN, dl, {MVT::i64, MVT::Other}, 2974 {Chain, DAG.getConstant(Intrinsic::aarch64_get_fpcr, dl, MVT::i64)}); 2975 Chain = FPCR_64.getValue(1); 2976 SDValue FPCR_32 = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, FPCR_64); 2977 SDValue FltRounds = DAG.getNode(ISD::ADD, dl, MVT::i32, FPCR_32, 2978 DAG.getConstant(1U << 22, dl, MVT::i32)); 2979 SDValue RMODE = DAG.getNode(ISD::SRL, dl, MVT::i32, FltRounds, 2980 DAG.getConstant(22, dl, MVT::i32)); 2981 SDValue AND = DAG.getNode(ISD::AND, dl, MVT::i32, RMODE, 2982 DAG.getConstant(3, dl, MVT::i32)); 2983 return DAG.getMergeValues({AND, Chain}, dl); 2984 } 2985 2986 static SDValue LowerMUL(SDValue Op, SelectionDAG &DAG) { 2987 // Multiplications are only custom-lowered for 128-bit vectors so that 2988 // VMULL can be detected. Otherwise v2i64 multiplications are not legal. 2989 EVT VT = Op.getValueType(); 2990 assert(VT.is128BitVector() && VT.isInteger() && 2991 "unexpected type for custom-lowering ISD::MUL"); 2992 SDNode *N0 = Op.getOperand(0).getNode(); 2993 SDNode *N1 = Op.getOperand(1).getNode(); 2994 unsigned NewOpc = 0; 2995 bool isMLA = false; 2996 bool isN0SExt = isSignExtended(N0, DAG); 2997 bool isN1SExt = isSignExtended(N1, DAG); 2998 if (isN0SExt && isN1SExt) 2999 NewOpc = AArch64ISD::SMULL; 3000 else { 3001 bool isN0ZExt = isZeroExtended(N0, DAG); 3002 bool isN1ZExt = isZeroExtended(N1, DAG); 3003 if (isN0ZExt && isN1ZExt) 3004 NewOpc = AArch64ISD::UMULL; 3005 else if (isN1SExt || isN1ZExt) { 3006 // Look for (s/zext A + s/zext B) * (s/zext C). We want to turn these 3007 // into (s/zext A * s/zext C) + (s/zext B * s/zext C) 3008 if (isN1SExt && isAddSubSExt(N0, DAG)) { 3009 NewOpc = AArch64ISD::SMULL; 3010 isMLA = true; 3011 } else if (isN1ZExt && isAddSubZExt(N0, DAG)) { 3012 NewOpc = AArch64ISD::UMULL; 3013 isMLA = true; 3014 } else if (isN0ZExt && isAddSubZExt(N1, DAG)) { 3015 std::swap(N0, N1); 3016 NewOpc = AArch64ISD::UMULL; 3017 isMLA = true; 3018 } 3019 } 3020 3021 if (!NewOpc) { 3022 if (VT == MVT::v2i64) 3023 // Fall through to expand this. It is not legal. 3024 return SDValue(); 3025 else 3026 // Other vector multiplications are legal. 3027 return Op; 3028 } 3029 } 3030 3031 // Legalize to a S/UMULL instruction 3032 SDLoc DL(Op); 3033 SDValue Op0; 3034 SDValue Op1 = skipExtensionForVectorMULL(N1, DAG); 3035 if (!isMLA) { 3036 Op0 = skipExtensionForVectorMULL(N0, DAG); 3037 assert(Op0.getValueType().is64BitVector() && 3038 Op1.getValueType().is64BitVector() && 3039 "unexpected types for extended operands to VMULL"); 3040 return DAG.getNode(NewOpc, DL, VT, Op0, Op1); 3041 } 3042 // Optimizing (zext A + zext B) * C, to (S/UMULL A, C) + (S/UMULL B, C) during 3043 // isel lowering to take advantage of no-stall back to back s/umul + s/umla. 3044 // This is true for CPUs with accumulate forwarding such as Cortex-A53/A57 3045 SDValue N00 = skipExtensionForVectorMULL(N0->getOperand(0).getNode(), DAG); 3046 SDValue N01 = skipExtensionForVectorMULL(N0->getOperand(1).getNode(), DAG); 3047 EVT Op1VT = Op1.getValueType(); 3048 return DAG.getNode(N0->getOpcode(), DL, VT, 3049 DAG.getNode(NewOpc, DL, VT, 3050 DAG.getNode(ISD::BITCAST, DL, Op1VT, N00), Op1), 3051 DAG.getNode(NewOpc, DL, VT, 3052 DAG.getNode(ISD::BITCAST, DL, Op1VT, N01), Op1)); 3053 } 3054 3055 static inline SDValue getPTrue(SelectionDAG &DAG, SDLoc DL, EVT VT, 3056 int Pattern) { 3057 return DAG.getNode(AArch64ISD::PTRUE, DL, VT, 3058 DAG.getTargetConstant(Pattern, DL, MVT::i32)); 3059 } 3060 3061 SDValue AArch64TargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op, 3062 SelectionDAG &DAG) const { 3063 unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue(); 3064 SDLoc dl(Op); 3065 switch (IntNo) { 3066 default: return SDValue(); // Don't custom lower most intrinsics. 3067 case Intrinsic::thread_pointer: { 3068 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 3069 return DAG.getNode(AArch64ISD::THREAD_POINTER, dl, PtrVT); 3070 } 3071 case Intrinsic::aarch64_neon_abs: { 3072 EVT Ty = Op.getValueType(); 3073 if (Ty == MVT::i64) { 3074 SDValue Result = DAG.getNode(ISD::BITCAST, dl, MVT::v1i64, 3075 Op.getOperand(1)); 3076 Result = DAG.getNode(ISD::ABS, dl, MVT::v1i64, Result); 3077 return DAG.getNode(ISD::BITCAST, dl, MVT::i64, Result); 3078 } else if (Ty.isVector() && Ty.isInteger() && isTypeLegal(Ty)) { 3079 return DAG.getNode(ISD::ABS, dl, Ty, Op.getOperand(1)); 3080 } else { 3081 report_fatal_error("Unexpected type for AArch64 NEON intrinic"); 3082 } 3083 } 3084 case Intrinsic::aarch64_neon_smax: 3085 return DAG.getNode(ISD::SMAX, dl, Op.getValueType(), 3086 Op.getOperand(1), Op.getOperand(2)); 3087 case Intrinsic::aarch64_neon_umax: 3088 return DAG.getNode(ISD::UMAX, dl, Op.getValueType(), 3089 Op.getOperand(1), Op.getOperand(2)); 3090 case Intrinsic::aarch64_neon_smin: 3091 return DAG.getNode(ISD::SMIN, dl, Op.getValueType(), 3092 Op.getOperand(1), Op.getOperand(2)); 3093 case Intrinsic::aarch64_neon_umin: 3094 return DAG.getNode(ISD::UMIN, dl, Op.getValueType(), 3095 Op.getOperand(1), Op.getOperand(2)); 3096 3097 case Intrinsic::aarch64_sve_sunpkhi: 3098 return DAG.getNode(AArch64ISD::SUNPKHI, dl, Op.getValueType(), 3099 Op.getOperand(1)); 3100 case Intrinsic::aarch64_sve_sunpklo: 3101 return DAG.getNode(AArch64ISD::SUNPKLO, dl, Op.getValueType(), 3102 Op.getOperand(1)); 3103 case Intrinsic::aarch64_sve_uunpkhi: 3104 return DAG.getNode(AArch64ISD::UUNPKHI, dl, Op.getValueType(), 3105 Op.getOperand(1)); 3106 case Intrinsic::aarch64_sve_uunpklo: 3107 return DAG.getNode(AArch64ISD::UUNPKLO, dl, Op.getValueType(), 3108 Op.getOperand(1)); 3109 case Intrinsic::aarch64_sve_clasta_n: 3110 return DAG.getNode(AArch64ISD::CLASTA_N, dl, Op.getValueType(), 3111 Op.getOperand(1), Op.getOperand(2), Op.getOperand(3)); 3112 case Intrinsic::aarch64_sve_clastb_n: 3113 return DAG.getNode(AArch64ISD::CLASTB_N, dl, Op.getValueType(), 3114 Op.getOperand(1), Op.getOperand(2), Op.getOperand(3)); 3115 case Intrinsic::aarch64_sve_lasta: 3116 return DAG.getNode(AArch64ISD::LASTA, dl, Op.getValueType(), 3117 Op.getOperand(1), Op.getOperand(2)); 3118 case Intrinsic::aarch64_sve_lastb: 3119 return DAG.getNode(AArch64ISD::LASTB, dl, Op.getValueType(), 3120 Op.getOperand(1), Op.getOperand(2)); 3121 case Intrinsic::aarch64_sve_rev: 3122 return DAG.getNode(AArch64ISD::REV, dl, Op.getValueType(), 3123 Op.getOperand(1)); 3124 case Intrinsic::aarch64_sve_tbl: 3125 return DAG.getNode(AArch64ISD::TBL, dl, Op.getValueType(), 3126 Op.getOperand(1), Op.getOperand(2)); 3127 case Intrinsic::aarch64_sve_trn1: 3128 return DAG.getNode(AArch64ISD::TRN1, dl, Op.getValueType(), 3129 Op.getOperand(1), Op.getOperand(2)); 3130 case Intrinsic::aarch64_sve_trn2: 3131 return DAG.getNode(AArch64ISD::TRN2, dl, Op.getValueType(), 3132 Op.getOperand(1), Op.getOperand(2)); 3133 case Intrinsic::aarch64_sve_uzp1: 3134 return DAG.getNode(AArch64ISD::UZP1, dl, Op.getValueType(), 3135 Op.getOperand(1), Op.getOperand(2)); 3136 case Intrinsic::aarch64_sve_uzp2: 3137 return DAG.getNode(AArch64ISD::UZP2, dl, Op.getValueType(), 3138 Op.getOperand(1), Op.getOperand(2)); 3139 case Intrinsic::aarch64_sve_zip1: 3140 return DAG.getNode(AArch64ISD::ZIP1, dl, Op.getValueType(), 3141 Op.getOperand(1), Op.getOperand(2)); 3142 case Intrinsic::aarch64_sve_zip2: 3143 return DAG.getNode(AArch64ISD::ZIP2, dl, Op.getValueType(), 3144 Op.getOperand(1), Op.getOperand(2)); 3145 case Intrinsic::aarch64_sve_ptrue: 3146 return DAG.getNode(AArch64ISD::PTRUE, dl, Op.getValueType(), 3147 Op.getOperand(1)); 3148 case Intrinsic::aarch64_sve_dupq_lane: 3149 return LowerDUPQLane(Op, DAG); 3150 case Intrinsic::aarch64_sve_convert_from_svbool: 3151 return DAG.getNode(AArch64ISD::REINTERPRET_CAST, dl, Op.getValueType(), 3152 Op.getOperand(1)); 3153 case Intrinsic::aarch64_sve_convert_to_svbool: { 3154 EVT OutVT = Op.getValueType(); 3155 EVT InVT = Op.getOperand(1).getValueType(); 3156 // Return the operand if the cast isn't changing type, 3157 // i.e. <n x 16 x i1> -> <n x 16 x i1> 3158 if (InVT == OutVT) 3159 return Op.getOperand(1); 3160 // Otherwise, zero the newly introduced lanes. 3161 SDValue Reinterpret = 3162 DAG.getNode(AArch64ISD::REINTERPRET_CAST, dl, OutVT, Op.getOperand(1)); 3163 SDValue Mask = getPTrue(DAG, dl, InVT, AArch64SVEPredPattern::all); 3164 SDValue MaskReinterpret = 3165 DAG.getNode(AArch64ISD::REINTERPRET_CAST, dl, OutVT, Mask); 3166 return DAG.getNode(ISD::AND, dl, OutVT, Reinterpret, MaskReinterpret); 3167 } 3168 3169 case Intrinsic::aarch64_sve_insr: { 3170 SDValue Scalar = Op.getOperand(2); 3171 EVT ScalarTy = Scalar.getValueType(); 3172 if ((ScalarTy == MVT::i8) || (ScalarTy == MVT::i16)) 3173 Scalar = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, Scalar); 3174 3175 return DAG.getNode(AArch64ISD::INSR, dl, Op.getValueType(), 3176 Op.getOperand(1), Scalar); 3177 } 3178 3179 case Intrinsic::localaddress: { 3180 const auto &MF = DAG.getMachineFunction(); 3181 const auto *RegInfo = Subtarget->getRegisterInfo(); 3182 unsigned Reg = RegInfo->getLocalAddressRegister(MF); 3183 return DAG.getCopyFromReg(DAG.getEntryNode(), dl, Reg, 3184 Op.getSimpleValueType()); 3185 } 3186 3187 case Intrinsic::eh_recoverfp: { 3188 // FIXME: This needs to be implemented to correctly handle highly aligned 3189 // stack objects. For now we simply return the incoming FP. Refer D53541 3190 // for more details. 3191 SDValue FnOp = Op.getOperand(1); 3192 SDValue IncomingFPOp = Op.getOperand(2); 3193 GlobalAddressSDNode *GSD = dyn_cast<GlobalAddressSDNode>(FnOp); 3194 auto *Fn = dyn_cast_or_null<Function>(GSD ? GSD->getGlobal() : nullptr); 3195 if (!Fn) 3196 report_fatal_error( 3197 "llvm.eh.recoverfp must take a function as the first argument"); 3198 return IncomingFPOp; 3199 } 3200 3201 case Intrinsic::aarch64_neon_vsri: 3202 case Intrinsic::aarch64_neon_vsli: { 3203 EVT Ty = Op.getValueType(); 3204 3205 if (!Ty.isVector()) 3206 report_fatal_error("Unexpected type for aarch64_neon_vsli"); 3207 3208 assert(Op.getConstantOperandVal(3) <= Ty.getScalarSizeInBits()); 3209 3210 bool IsShiftRight = IntNo == Intrinsic::aarch64_neon_vsri; 3211 unsigned Opcode = IsShiftRight ? AArch64ISD::VSRI : AArch64ISD::VSLI; 3212 return DAG.getNode(Opcode, dl, Ty, Op.getOperand(1), Op.getOperand(2), 3213 Op.getOperand(3)); 3214 } 3215 } 3216 } 3217 3218 bool AArch64TargetLowering::isVectorLoadExtDesirable(SDValue ExtVal) const { 3219 return ExtVal.getValueType().isScalableVector(); 3220 } 3221 3222 // Custom lower trunc store for v4i8 vectors, since it is promoted to v4i16. 3223 static SDValue LowerTruncateVectorStore(SDLoc DL, StoreSDNode *ST, 3224 EVT VT, EVT MemVT, 3225 SelectionDAG &DAG) { 3226 assert(VT.isVector() && "VT should be a vector type"); 3227 assert(MemVT == MVT::v4i8 && VT == MVT::v4i16); 3228 3229 SDValue Value = ST->getValue(); 3230 3231 // It first extend the promoted v4i16 to v8i16, truncate to v8i8, and extract 3232 // the word lane which represent the v4i8 subvector. It optimizes the store 3233 // to: 3234 // 3235 // xtn v0.8b, v0.8h 3236 // str s0, [x0] 3237 3238 SDValue Undef = DAG.getUNDEF(MVT::i16); 3239 SDValue UndefVec = DAG.getBuildVector(MVT::v4i16, DL, 3240 {Undef, Undef, Undef, Undef}); 3241 3242 SDValue TruncExt = DAG.getNode(ISD::CONCAT_VECTORS, DL, MVT::v8i16, 3243 Value, UndefVec); 3244 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, DL, MVT::v8i8, TruncExt); 3245 3246 Trunc = DAG.getNode(ISD::BITCAST, DL, MVT::v2i32, Trunc); 3247 SDValue ExtractTrunc = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32, 3248 Trunc, DAG.getConstant(0, DL, MVT::i64)); 3249 3250 return DAG.getStore(ST->getChain(), DL, ExtractTrunc, 3251 ST->getBasePtr(), ST->getMemOperand()); 3252 } 3253 3254 // Custom lowering for any store, vector or scalar and/or default or with 3255 // a truncate operations. Currently only custom lower truncate operation 3256 // from vector v4i16 to v4i8 or volatile stores of i128. 3257 SDValue AArch64TargetLowering::LowerSTORE(SDValue Op, 3258 SelectionDAG &DAG) const { 3259 SDLoc Dl(Op); 3260 StoreSDNode *StoreNode = cast<StoreSDNode>(Op); 3261 assert (StoreNode && "Can only custom lower store nodes"); 3262 3263 SDValue Value = StoreNode->getValue(); 3264 3265 EVT VT = Value.getValueType(); 3266 EVT MemVT = StoreNode->getMemoryVT(); 3267 3268 if (VT.isVector()) { 3269 unsigned AS = StoreNode->getAddressSpace(); 3270 unsigned Align = StoreNode->getAlignment(); 3271 if (Align < MemVT.getStoreSize() && 3272 !allowsMisalignedMemoryAccesses(MemVT, AS, Align, 3273 StoreNode->getMemOperand()->getFlags(), 3274 nullptr)) { 3275 return scalarizeVectorStore(StoreNode, DAG); 3276 } 3277 3278 if (StoreNode->isTruncatingStore()) { 3279 return LowerTruncateVectorStore(Dl, StoreNode, VT, MemVT, DAG); 3280 } 3281 // 256 bit non-temporal stores can be lowered to STNP. Do this as part of 3282 // the custom lowering, as there are no un-paired non-temporal stores and 3283 // legalization will break up 256 bit inputs. 3284 if (StoreNode->isNonTemporal() && MemVT.getSizeInBits() == 256u && 3285 MemVT.getVectorElementCount().Min % 2u == 0 && 3286 ((MemVT.getScalarSizeInBits() == 8u || 3287 MemVT.getScalarSizeInBits() == 16u || 3288 MemVT.getScalarSizeInBits() == 32u || 3289 MemVT.getScalarSizeInBits() == 64u))) { 3290 SDValue Lo = 3291 DAG.getNode(ISD::EXTRACT_SUBVECTOR, Dl, 3292 MemVT.getHalfNumVectorElementsVT(*DAG.getContext()), 3293 StoreNode->getValue(), DAG.getConstant(0, Dl, MVT::i64)); 3294 SDValue Hi = DAG.getNode( 3295 ISD::EXTRACT_SUBVECTOR, Dl, 3296 MemVT.getHalfNumVectorElementsVT(*DAG.getContext()), 3297 StoreNode->getValue(), 3298 DAG.getConstant(MemVT.getVectorElementCount().Min / 2, Dl, MVT::i64)); 3299 SDValue Result = DAG.getMemIntrinsicNode( 3300 AArch64ISD::STNP, Dl, DAG.getVTList(MVT::Other), 3301 {StoreNode->getChain(), Lo, Hi, StoreNode->getBasePtr()}, 3302 StoreNode->getMemoryVT(), StoreNode->getMemOperand()); 3303 return Result; 3304 } 3305 } else if (MemVT == MVT::i128 && StoreNode->isVolatile()) { 3306 assert(StoreNode->getValue()->getValueType(0) == MVT::i128); 3307 SDValue Lo = 3308 DAG.getNode(ISD::EXTRACT_ELEMENT, Dl, MVT::i64, StoreNode->getValue(), 3309 DAG.getConstant(0, Dl, MVT::i64)); 3310 SDValue Hi = 3311 DAG.getNode(ISD::EXTRACT_ELEMENT, Dl, MVT::i64, StoreNode->getValue(), 3312 DAG.getConstant(1, Dl, MVT::i64)); 3313 SDValue Result = DAG.getMemIntrinsicNode( 3314 AArch64ISD::STP, Dl, DAG.getVTList(MVT::Other), 3315 {StoreNode->getChain(), Lo, Hi, StoreNode->getBasePtr()}, 3316 StoreNode->getMemoryVT(), StoreNode->getMemOperand()); 3317 return Result; 3318 } 3319 3320 return SDValue(); 3321 } 3322 3323 SDValue AArch64TargetLowering::LowerOperation(SDValue Op, 3324 SelectionDAG &DAG) const { 3325 LLVM_DEBUG(dbgs() << "Custom lowering: "); 3326 LLVM_DEBUG(Op.dump()); 3327 3328 switch (Op.getOpcode()) { 3329 default: 3330 llvm_unreachable("unimplemented operand"); 3331 return SDValue(); 3332 case ISD::BITCAST: 3333 return LowerBITCAST(Op, DAG); 3334 case ISD::GlobalAddress: 3335 return LowerGlobalAddress(Op, DAG); 3336 case ISD::GlobalTLSAddress: 3337 return LowerGlobalTLSAddress(Op, DAG); 3338 case ISD::SETCC: 3339 case ISD::STRICT_FSETCC: 3340 case ISD::STRICT_FSETCCS: 3341 return LowerSETCC(Op, DAG); 3342 case ISD::BR_CC: 3343 return LowerBR_CC(Op, DAG); 3344 case ISD::SELECT: 3345 return LowerSELECT(Op, DAG); 3346 case ISD::SELECT_CC: 3347 return LowerSELECT_CC(Op, DAG); 3348 case ISD::JumpTable: 3349 return LowerJumpTable(Op, DAG); 3350 case ISD::BR_JT: 3351 return LowerBR_JT(Op, DAG); 3352 case ISD::ConstantPool: 3353 return LowerConstantPool(Op, DAG); 3354 case ISD::BlockAddress: 3355 return LowerBlockAddress(Op, DAG); 3356 case ISD::VASTART: 3357 return LowerVASTART(Op, DAG); 3358 case ISD::VACOPY: 3359 return LowerVACOPY(Op, DAG); 3360 case ISD::VAARG: 3361 return LowerVAARG(Op, DAG); 3362 case ISD::ADDC: 3363 case ISD::ADDE: 3364 case ISD::SUBC: 3365 case ISD::SUBE: 3366 return LowerADDC_ADDE_SUBC_SUBE(Op, DAG); 3367 case ISD::SADDO: 3368 case ISD::UADDO: 3369 case ISD::SSUBO: 3370 case ISD::USUBO: 3371 case ISD::SMULO: 3372 case ISD::UMULO: 3373 return LowerXALUO(Op, DAG); 3374 case ISD::FADD: 3375 return LowerF128Call(Op, DAG, RTLIB::ADD_F128); 3376 case ISD::FSUB: 3377 return LowerF128Call(Op, DAG, RTLIB::SUB_F128); 3378 case ISD::FMUL: 3379 return LowerF128Call(Op, DAG, RTLIB::MUL_F128); 3380 case ISD::FDIV: 3381 return LowerF128Call(Op, DAG, RTLIB::DIV_F128); 3382 case ISD::FP_ROUND: 3383 case ISD::STRICT_FP_ROUND: 3384 return LowerFP_ROUND(Op, DAG); 3385 case ISD::FP_EXTEND: 3386 return LowerFP_EXTEND(Op, DAG); 3387 case ISD::FRAMEADDR: 3388 return LowerFRAMEADDR(Op, DAG); 3389 case ISD::SPONENTRY: 3390 return LowerSPONENTRY(Op, DAG); 3391 case ISD::RETURNADDR: 3392 return LowerRETURNADDR(Op, DAG); 3393 case ISD::ADDROFRETURNADDR: 3394 return LowerADDROFRETURNADDR(Op, DAG); 3395 case ISD::INSERT_VECTOR_ELT: 3396 return LowerINSERT_VECTOR_ELT(Op, DAG); 3397 case ISD::EXTRACT_VECTOR_ELT: 3398 return LowerEXTRACT_VECTOR_ELT(Op, DAG); 3399 case ISD::BUILD_VECTOR: 3400 return LowerBUILD_VECTOR(Op, DAG); 3401 case ISD::VECTOR_SHUFFLE: 3402 return LowerVECTOR_SHUFFLE(Op, DAG); 3403 case ISD::SPLAT_VECTOR: 3404 return LowerSPLAT_VECTOR(Op, DAG); 3405 case ISD::EXTRACT_SUBVECTOR: 3406 return LowerEXTRACT_SUBVECTOR(Op, DAG); 3407 case ISD::SDIV: 3408 return LowerToPredicatedOp(Op, DAG, AArch64ISD::SDIV_PRED); 3409 case ISD::UDIV: 3410 return LowerToPredicatedOp(Op, DAG, AArch64ISD::UDIV_PRED); 3411 case ISD::SMIN: 3412 return LowerToPredicatedOp(Op, DAG, AArch64ISD::SMIN_PRED); 3413 case ISD::UMIN: 3414 return LowerToPredicatedOp(Op, DAG, AArch64ISD::UMIN_PRED); 3415 case ISD::SMAX: 3416 return LowerToPredicatedOp(Op, DAG, AArch64ISD::SMAX_PRED); 3417 case ISD::UMAX: 3418 return LowerToPredicatedOp(Op, DAG, AArch64ISD::UMAX_PRED); 3419 case ISD::SRA: 3420 case ISD::SRL: 3421 case ISD::SHL: 3422 return LowerVectorSRA_SRL_SHL(Op, DAG); 3423 case ISD::SHL_PARTS: 3424 return LowerShiftLeftParts(Op, DAG); 3425 case ISD::SRL_PARTS: 3426 case ISD::SRA_PARTS: 3427 return LowerShiftRightParts(Op, DAG); 3428 case ISD::CTPOP: 3429 return LowerCTPOP(Op, DAG); 3430 case ISD::FCOPYSIGN: 3431 return LowerFCOPYSIGN(Op, DAG); 3432 case ISD::OR: 3433 return LowerVectorOR(Op, DAG); 3434 case ISD::XOR: 3435 return LowerXOR(Op, DAG); 3436 case ISD::PREFETCH: 3437 return LowerPREFETCH(Op, DAG); 3438 case ISD::SINT_TO_FP: 3439 case ISD::UINT_TO_FP: 3440 case ISD::STRICT_SINT_TO_FP: 3441 case ISD::STRICT_UINT_TO_FP: 3442 return LowerINT_TO_FP(Op, DAG); 3443 case ISD::FP_TO_SINT: 3444 case ISD::FP_TO_UINT: 3445 case ISD::STRICT_FP_TO_SINT: 3446 case ISD::STRICT_FP_TO_UINT: 3447 return LowerFP_TO_INT(Op, DAG); 3448 case ISD::FSINCOS: 3449 return LowerFSINCOS(Op, DAG); 3450 case ISD::FLT_ROUNDS_: 3451 return LowerFLT_ROUNDS_(Op, DAG); 3452 case ISD::MUL: 3453 return LowerMUL(Op, DAG); 3454 case ISD::INTRINSIC_WO_CHAIN: 3455 return LowerINTRINSIC_WO_CHAIN(Op, DAG); 3456 case ISD::STORE: 3457 return LowerSTORE(Op, DAG); 3458 case ISD::VECREDUCE_ADD: 3459 case ISD::VECREDUCE_SMAX: 3460 case ISD::VECREDUCE_SMIN: 3461 case ISD::VECREDUCE_UMAX: 3462 case ISD::VECREDUCE_UMIN: 3463 case ISD::VECREDUCE_FMAX: 3464 case ISD::VECREDUCE_FMIN: 3465 return LowerVECREDUCE(Op, DAG); 3466 case ISD::ATOMIC_LOAD_SUB: 3467 return LowerATOMIC_LOAD_SUB(Op, DAG); 3468 case ISD::ATOMIC_LOAD_AND: 3469 return LowerATOMIC_LOAD_AND(Op, DAG); 3470 case ISD::DYNAMIC_STACKALLOC: 3471 return LowerDYNAMIC_STACKALLOC(Op, DAG); 3472 case ISD::VSCALE: 3473 return LowerVSCALE(Op, DAG); 3474 } 3475 } 3476 3477 //===----------------------------------------------------------------------===// 3478 // Calling Convention Implementation 3479 //===----------------------------------------------------------------------===// 3480 3481 /// Selects the correct CCAssignFn for a given CallingConvention value. 3482 CCAssignFn *AArch64TargetLowering::CCAssignFnForCall(CallingConv::ID CC, 3483 bool IsVarArg) const { 3484 switch (CC) { 3485 default: 3486 report_fatal_error("Unsupported calling convention."); 3487 case CallingConv::WebKit_JS: 3488 return CC_AArch64_WebKit_JS; 3489 case CallingConv::GHC: 3490 return CC_AArch64_GHC; 3491 case CallingConv::C: 3492 case CallingConv::Fast: 3493 case CallingConv::PreserveMost: 3494 case CallingConv::CXX_FAST_TLS: 3495 case CallingConv::Swift: 3496 if (Subtarget->isTargetWindows() && IsVarArg) 3497 return CC_AArch64_Win64_VarArg; 3498 if (!Subtarget->isTargetDarwin()) 3499 return CC_AArch64_AAPCS; 3500 if (!IsVarArg) 3501 return CC_AArch64_DarwinPCS; 3502 return Subtarget->isTargetILP32() ? CC_AArch64_DarwinPCS_ILP32_VarArg 3503 : CC_AArch64_DarwinPCS_VarArg; 3504 case CallingConv::Win64: 3505 return IsVarArg ? CC_AArch64_Win64_VarArg : CC_AArch64_AAPCS; 3506 case CallingConv::CFGuard_Check: 3507 return CC_AArch64_Win64_CFGuard_Check; 3508 case CallingConv::AArch64_VectorCall: 3509 case CallingConv::AArch64_SVE_VectorCall: 3510 return CC_AArch64_AAPCS; 3511 } 3512 } 3513 3514 CCAssignFn * 3515 AArch64TargetLowering::CCAssignFnForReturn(CallingConv::ID CC) const { 3516 return CC == CallingConv::WebKit_JS ? RetCC_AArch64_WebKit_JS 3517 : RetCC_AArch64_AAPCS; 3518 } 3519 3520 SDValue AArch64TargetLowering::LowerFormalArguments( 3521 SDValue Chain, CallingConv::ID CallConv, bool isVarArg, 3522 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &DL, 3523 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const { 3524 MachineFunction &MF = DAG.getMachineFunction(); 3525 MachineFrameInfo &MFI = MF.getFrameInfo(); 3526 bool IsWin64 = Subtarget->isCallingConvWin64(MF.getFunction().getCallingConv()); 3527 3528 // Assign locations to all of the incoming arguments. 3529 SmallVector<CCValAssign, 16> ArgLocs; 3530 DenseMap<unsigned, SDValue> CopiedRegs; 3531 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), ArgLocs, 3532 *DAG.getContext()); 3533 3534 // At this point, Ins[].VT may already be promoted to i32. To correctly 3535 // handle passing i8 as i8 instead of i32 on stack, we pass in both i32 and 3536 // i8 to CC_AArch64_AAPCS with i32 being ValVT and i8 being LocVT. 3537 // Since AnalyzeFormalArguments uses Ins[].VT for both ValVT and LocVT, here 3538 // we use a special version of AnalyzeFormalArguments to pass in ValVT and 3539 // LocVT. 3540 unsigned NumArgs = Ins.size(); 3541 Function::const_arg_iterator CurOrigArg = MF.getFunction().arg_begin(); 3542 unsigned CurArgIdx = 0; 3543 for (unsigned i = 0; i != NumArgs; ++i) { 3544 MVT ValVT = Ins[i].VT; 3545 if (Ins[i].isOrigArg()) { 3546 std::advance(CurOrigArg, Ins[i].getOrigArgIndex() - CurArgIdx); 3547 CurArgIdx = Ins[i].getOrigArgIndex(); 3548 3549 // Get type of the original argument. 3550 EVT ActualVT = getValueType(DAG.getDataLayout(), CurOrigArg->getType(), 3551 /*AllowUnknown*/ true); 3552 MVT ActualMVT = ActualVT.isSimple() ? ActualVT.getSimpleVT() : MVT::Other; 3553 // If ActualMVT is i1/i8/i16, we should set LocVT to i8/i8/i16. 3554 if (ActualMVT == MVT::i1 || ActualMVT == MVT::i8) 3555 ValVT = MVT::i8; 3556 else if (ActualMVT == MVT::i16) 3557 ValVT = MVT::i16; 3558 } 3559 CCAssignFn *AssignFn = CCAssignFnForCall(CallConv, /*IsVarArg=*/false); 3560 bool Res = 3561 AssignFn(i, ValVT, ValVT, CCValAssign::Full, Ins[i].Flags, CCInfo); 3562 assert(!Res && "Call operand has unhandled type"); 3563 (void)Res; 3564 } 3565 assert(ArgLocs.size() == Ins.size()); 3566 SmallVector<SDValue, 16> ArgValues; 3567 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) { 3568 CCValAssign &VA = ArgLocs[i]; 3569 3570 if (Ins[i].Flags.isByVal()) { 3571 // Byval is used for HFAs in the PCS, but the system should work in a 3572 // non-compliant manner for larger structs. 3573 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 3574 int Size = Ins[i].Flags.getByValSize(); 3575 unsigned NumRegs = (Size + 7) / 8; 3576 3577 // FIXME: This works on big-endian for composite byvals, which are the common 3578 // case. It should also work for fundamental types too. 3579 unsigned FrameIdx = 3580 MFI.CreateFixedObject(8 * NumRegs, VA.getLocMemOffset(), false); 3581 SDValue FrameIdxN = DAG.getFrameIndex(FrameIdx, PtrVT); 3582 InVals.push_back(FrameIdxN); 3583 3584 continue; 3585 } 3586 3587 SDValue ArgValue; 3588 if (VA.isRegLoc()) { 3589 // Arguments stored in registers. 3590 EVT RegVT = VA.getLocVT(); 3591 const TargetRegisterClass *RC; 3592 3593 if (RegVT == MVT::i32) 3594 RC = &AArch64::GPR32RegClass; 3595 else if (RegVT == MVT::i64) 3596 RC = &AArch64::GPR64RegClass; 3597 else if (RegVT == MVT::f16 || RegVT == MVT::bf16) 3598 RC = &AArch64::FPR16RegClass; 3599 else if (RegVT == MVT::f32) 3600 RC = &AArch64::FPR32RegClass; 3601 else if (RegVT == MVT::f64 || RegVT.is64BitVector()) 3602 RC = &AArch64::FPR64RegClass; 3603 else if (RegVT == MVT::f128 || RegVT.is128BitVector()) 3604 RC = &AArch64::FPR128RegClass; 3605 else if (RegVT.isScalableVector() && 3606 RegVT.getVectorElementType() == MVT::i1) 3607 RC = &AArch64::PPRRegClass; 3608 else if (RegVT.isScalableVector()) 3609 RC = &AArch64::ZPRRegClass; 3610 else 3611 llvm_unreachable("RegVT not supported by FORMAL_ARGUMENTS Lowering"); 3612 3613 // Transform the arguments in physical registers into virtual ones. 3614 unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC); 3615 ArgValue = DAG.getCopyFromReg(Chain, DL, Reg, RegVT); 3616 3617 // If this is an 8, 16 or 32-bit value, it is really passed promoted 3618 // to 64 bits. Insert an assert[sz]ext to capture this, then 3619 // truncate to the right size. 3620 switch (VA.getLocInfo()) { 3621 default: 3622 llvm_unreachable("Unknown loc info!"); 3623 case CCValAssign::Full: 3624 break; 3625 case CCValAssign::Indirect: 3626 assert(VA.getValVT().isScalableVector() && 3627 "Only scalable vectors can be passed indirectly"); 3628 break; 3629 case CCValAssign::BCvt: 3630 ArgValue = DAG.getNode(ISD::BITCAST, DL, VA.getValVT(), ArgValue); 3631 break; 3632 case CCValAssign::AExt: 3633 case CCValAssign::SExt: 3634 case CCValAssign::ZExt: 3635 break; 3636 case CCValAssign::AExtUpper: 3637 ArgValue = DAG.getNode(ISD::SRL, DL, RegVT, ArgValue, 3638 DAG.getConstant(32, DL, RegVT)); 3639 ArgValue = DAG.getZExtOrTrunc(ArgValue, DL, VA.getValVT()); 3640 break; 3641 } 3642 } else { // VA.isRegLoc() 3643 assert(VA.isMemLoc() && "CCValAssign is neither reg nor mem"); 3644 unsigned ArgOffset = VA.getLocMemOffset(); 3645 unsigned ArgSize = (VA.getLocInfo() == CCValAssign::Indirect 3646 ? VA.getLocVT().getSizeInBits() 3647 : VA.getValVT().getSizeInBits()) / 8; 3648 3649 uint32_t BEAlign = 0; 3650 if (!Subtarget->isLittleEndian() && ArgSize < 8 && 3651 !Ins[i].Flags.isInConsecutiveRegs()) 3652 BEAlign = 8 - ArgSize; 3653 3654 int FI = MFI.CreateFixedObject(ArgSize, ArgOffset + BEAlign, true); 3655 3656 // Create load nodes to retrieve arguments from the stack. 3657 SDValue FIN = DAG.getFrameIndex(FI, getPointerTy(DAG.getDataLayout())); 3658 3659 // For NON_EXTLOAD, generic code in getLoad assert(ValVT == MemVT) 3660 ISD::LoadExtType ExtType = ISD::NON_EXTLOAD; 3661 MVT MemVT = VA.getValVT(); 3662 3663 switch (VA.getLocInfo()) { 3664 default: 3665 break; 3666 case CCValAssign::Trunc: 3667 case CCValAssign::BCvt: 3668 MemVT = VA.getLocVT(); 3669 break; 3670 case CCValAssign::Indirect: 3671 assert(VA.getValVT().isScalableVector() && 3672 "Only scalable vectors can be passed indirectly"); 3673 MemVT = VA.getLocVT(); 3674 break; 3675 case CCValAssign::SExt: 3676 ExtType = ISD::SEXTLOAD; 3677 break; 3678 case CCValAssign::ZExt: 3679 ExtType = ISD::ZEXTLOAD; 3680 break; 3681 case CCValAssign::AExt: 3682 ExtType = ISD::EXTLOAD; 3683 break; 3684 } 3685 3686 ArgValue = DAG.getExtLoad( 3687 ExtType, DL, VA.getLocVT(), Chain, FIN, 3688 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI), 3689 MemVT); 3690 3691 } 3692 3693 if (VA.getLocInfo() == CCValAssign::Indirect) { 3694 assert(VA.getValVT().isScalableVector() && 3695 "Only scalable vectors can be passed indirectly"); 3696 // If value is passed via pointer - do a load. 3697 ArgValue = 3698 DAG.getLoad(VA.getValVT(), DL, Chain, ArgValue, MachinePointerInfo()); 3699 } 3700 3701 if (Subtarget->isTargetILP32() && Ins[i].Flags.isPointer()) 3702 ArgValue = DAG.getNode(ISD::AssertZext, DL, ArgValue.getValueType(), 3703 ArgValue, DAG.getValueType(MVT::i32)); 3704 InVals.push_back(ArgValue); 3705 } 3706 3707 // varargs 3708 AArch64FunctionInfo *FuncInfo = MF.getInfo<AArch64FunctionInfo>(); 3709 if (isVarArg) { 3710 if (!Subtarget->isTargetDarwin() || IsWin64) { 3711 // The AAPCS variadic function ABI is identical to the non-variadic 3712 // one. As a result there may be more arguments in registers and we should 3713 // save them for future reference. 3714 // Win64 variadic functions also pass arguments in registers, but all float 3715 // arguments are passed in integer registers. 3716 saveVarArgRegisters(CCInfo, DAG, DL, Chain); 3717 } 3718 3719 // This will point to the next argument passed via stack. 3720 unsigned StackOffset = CCInfo.getNextStackOffset(); 3721 // We currently pass all varargs at 8-byte alignment, or 4 for ILP32 3722 StackOffset = alignTo(StackOffset, Subtarget->isTargetILP32() ? 4 : 8); 3723 FuncInfo->setVarArgsStackIndex(MFI.CreateFixedObject(4, StackOffset, true)); 3724 3725 if (MFI.hasMustTailInVarArgFunc()) { 3726 SmallVector<MVT, 2> RegParmTypes; 3727 RegParmTypes.push_back(MVT::i64); 3728 RegParmTypes.push_back(MVT::f128); 3729 // Compute the set of forwarded registers. The rest are scratch. 3730 SmallVectorImpl<ForwardedRegister> &Forwards = 3731 FuncInfo->getForwardedMustTailRegParms(); 3732 CCInfo.analyzeMustTailForwardedRegisters(Forwards, RegParmTypes, 3733 CC_AArch64_AAPCS); 3734 3735 // Conservatively forward X8, since it might be used for aggregate return. 3736 if (!CCInfo.isAllocated(AArch64::X8)) { 3737 unsigned X8VReg = MF.addLiveIn(AArch64::X8, &AArch64::GPR64RegClass); 3738 Forwards.push_back(ForwardedRegister(X8VReg, AArch64::X8, MVT::i64)); 3739 } 3740 } 3741 } 3742 3743 // On Windows, InReg pointers must be returned, so record the pointer in a 3744 // virtual register at the start of the function so it can be returned in the 3745 // epilogue. 3746 if (IsWin64) { 3747 for (unsigned I = 0, E = Ins.size(); I != E; ++I) { 3748 if (Ins[I].Flags.isInReg()) { 3749 assert(!FuncInfo->getSRetReturnReg()); 3750 3751 MVT PtrTy = getPointerTy(DAG.getDataLayout()); 3752 Register Reg = 3753 MF.getRegInfo().createVirtualRegister(getRegClassFor(PtrTy)); 3754 FuncInfo->setSRetReturnReg(Reg); 3755 3756 SDValue Copy = DAG.getCopyToReg(DAG.getEntryNode(), DL, Reg, InVals[I]); 3757 Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Copy, Chain); 3758 break; 3759 } 3760 } 3761 } 3762 3763 unsigned StackArgSize = CCInfo.getNextStackOffset(); 3764 bool TailCallOpt = MF.getTarget().Options.GuaranteedTailCallOpt; 3765 if (DoesCalleeRestoreStack(CallConv, TailCallOpt)) { 3766 // This is a non-standard ABI so by fiat I say we're allowed to make full 3767 // use of the stack area to be popped, which must be aligned to 16 bytes in 3768 // any case: 3769 StackArgSize = alignTo(StackArgSize, 16); 3770 3771 // If we're expected to restore the stack (e.g. fastcc) then we'll be adding 3772 // a multiple of 16. 3773 FuncInfo->setArgumentStackToRestore(StackArgSize); 3774 3775 // This realignment carries over to the available bytes below. Our own 3776 // callers will guarantee the space is free by giving an aligned value to 3777 // CALLSEQ_START. 3778 } 3779 // Even if we're not expected to free up the space, it's useful to know how 3780 // much is there while considering tail calls (because we can reuse it). 3781 FuncInfo->setBytesInStackArgArea(StackArgSize); 3782 3783 if (Subtarget->hasCustomCallingConv()) 3784 Subtarget->getRegisterInfo()->UpdateCustomCalleeSavedRegs(MF); 3785 3786 return Chain; 3787 } 3788 3789 void AArch64TargetLowering::saveVarArgRegisters(CCState &CCInfo, 3790 SelectionDAG &DAG, 3791 const SDLoc &DL, 3792 SDValue &Chain) const { 3793 MachineFunction &MF = DAG.getMachineFunction(); 3794 MachineFrameInfo &MFI = MF.getFrameInfo(); 3795 AArch64FunctionInfo *FuncInfo = MF.getInfo<AArch64FunctionInfo>(); 3796 auto PtrVT = getPointerTy(DAG.getDataLayout()); 3797 bool IsWin64 = Subtarget->isCallingConvWin64(MF.getFunction().getCallingConv()); 3798 3799 SmallVector<SDValue, 8> MemOps; 3800 3801 static const MCPhysReg GPRArgRegs[] = { AArch64::X0, AArch64::X1, AArch64::X2, 3802 AArch64::X3, AArch64::X4, AArch64::X5, 3803 AArch64::X6, AArch64::X7 }; 3804 static const unsigned NumGPRArgRegs = array_lengthof(GPRArgRegs); 3805 unsigned FirstVariadicGPR = CCInfo.getFirstUnallocated(GPRArgRegs); 3806 3807 unsigned GPRSaveSize = 8 * (NumGPRArgRegs - FirstVariadicGPR); 3808 int GPRIdx = 0; 3809 if (GPRSaveSize != 0) { 3810 if (IsWin64) { 3811 GPRIdx = MFI.CreateFixedObject(GPRSaveSize, -(int)GPRSaveSize, false); 3812 if (GPRSaveSize & 15) 3813 // The extra size here, if triggered, will always be 8. 3814 MFI.CreateFixedObject(16 - (GPRSaveSize & 15), -(int)alignTo(GPRSaveSize, 16), false); 3815 } else 3816 GPRIdx = MFI.CreateStackObject(GPRSaveSize, 8, false); 3817 3818 SDValue FIN = DAG.getFrameIndex(GPRIdx, PtrVT); 3819 3820 for (unsigned i = FirstVariadicGPR; i < NumGPRArgRegs; ++i) { 3821 unsigned VReg = MF.addLiveIn(GPRArgRegs[i], &AArch64::GPR64RegClass); 3822 SDValue Val = DAG.getCopyFromReg(Chain, DL, VReg, MVT::i64); 3823 SDValue Store = DAG.getStore( 3824 Val.getValue(1), DL, Val, FIN, 3825 IsWin64 3826 ? MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), 3827 GPRIdx, 3828 (i - FirstVariadicGPR) * 8) 3829 : MachinePointerInfo::getStack(DAG.getMachineFunction(), i * 8)); 3830 MemOps.push_back(Store); 3831 FIN = 3832 DAG.getNode(ISD::ADD, DL, PtrVT, FIN, DAG.getConstant(8, DL, PtrVT)); 3833 } 3834 } 3835 FuncInfo->setVarArgsGPRIndex(GPRIdx); 3836 FuncInfo->setVarArgsGPRSize(GPRSaveSize); 3837 3838 if (Subtarget->hasFPARMv8() && !IsWin64) { 3839 static const MCPhysReg FPRArgRegs[] = { 3840 AArch64::Q0, AArch64::Q1, AArch64::Q2, AArch64::Q3, 3841 AArch64::Q4, AArch64::Q5, AArch64::Q6, AArch64::Q7}; 3842 static const unsigned NumFPRArgRegs = array_lengthof(FPRArgRegs); 3843 unsigned FirstVariadicFPR = CCInfo.getFirstUnallocated(FPRArgRegs); 3844 3845 unsigned FPRSaveSize = 16 * (NumFPRArgRegs - FirstVariadicFPR); 3846 int FPRIdx = 0; 3847 if (FPRSaveSize != 0) { 3848 FPRIdx = MFI.CreateStackObject(FPRSaveSize, 16, false); 3849 3850 SDValue FIN = DAG.getFrameIndex(FPRIdx, PtrVT); 3851 3852 for (unsigned i = FirstVariadicFPR; i < NumFPRArgRegs; ++i) { 3853 unsigned VReg = MF.addLiveIn(FPRArgRegs[i], &AArch64::FPR128RegClass); 3854 SDValue Val = DAG.getCopyFromReg(Chain, DL, VReg, MVT::f128); 3855 3856 SDValue Store = DAG.getStore( 3857 Val.getValue(1), DL, Val, FIN, 3858 MachinePointerInfo::getStack(DAG.getMachineFunction(), i * 16)); 3859 MemOps.push_back(Store); 3860 FIN = DAG.getNode(ISD::ADD, DL, PtrVT, FIN, 3861 DAG.getConstant(16, DL, PtrVT)); 3862 } 3863 } 3864 FuncInfo->setVarArgsFPRIndex(FPRIdx); 3865 FuncInfo->setVarArgsFPRSize(FPRSaveSize); 3866 } 3867 3868 if (!MemOps.empty()) { 3869 Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, MemOps); 3870 } 3871 } 3872 3873 /// LowerCallResult - Lower the result values of a call into the 3874 /// appropriate copies out of appropriate physical registers. 3875 SDValue AArch64TargetLowering::LowerCallResult( 3876 SDValue Chain, SDValue InFlag, CallingConv::ID CallConv, bool isVarArg, 3877 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &DL, 3878 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals, bool isThisReturn, 3879 SDValue ThisVal) const { 3880 CCAssignFn *RetCC = CallConv == CallingConv::WebKit_JS 3881 ? RetCC_AArch64_WebKit_JS 3882 : RetCC_AArch64_AAPCS; 3883 // Assign locations to each value returned by this call. 3884 SmallVector<CCValAssign, 16> RVLocs; 3885 DenseMap<unsigned, SDValue> CopiedRegs; 3886 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs, 3887 *DAG.getContext()); 3888 CCInfo.AnalyzeCallResult(Ins, RetCC); 3889 3890 // Copy all of the result registers out of their specified physreg. 3891 for (unsigned i = 0; i != RVLocs.size(); ++i) { 3892 CCValAssign VA = RVLocs[i]; 3893 3894 // Pass 'this' value directly from the argument to return value, to avoid 3895 // reg unit interference 3896 if (i == 0 && isThisReturn) { 3897 assert(!VA.needsCustom() && VA.getLocVT() == MVT::i64 && 3898 "unexpected return calling convention register assignment"); 3899 InVals.push_back(ThisVal); 3900 continue; 3901 } 3902 3903 // Avoid copying a physreg twice since RegAllocFast is incompetent and only 3904 // allows one use of a physreg per block. 3905 SDValue Val = CopiedRegs.lookup(VA.getLocReg()); 3906 if (!Val) { 3907 Val = 3908 DAG.getCopyFromReg(Chain, DL, VA.getLocReg(), VA.getLocVT(), InFlag); 3909 Chain = Val.getValue(1); 3910 InFlag = Val.getValue(2); 3911 CopiedRegs[VA.getLocReg()] = Val; 3912 } 3913 3914 switch (VA.getLocInfo()) { 3915 default: 3916 llvm_unreachable("Unknown loc info!"); 3917 case CCValAssign::Full: 3918 break; 3919 case CCValAssign::BCvt: 3920 Val = DAG.getNode(ISD::BITCAST, DL, VA.getValVT(), Val); 3921 break; 3922 case CCValAssign::AExtUpper: 3923 Val = DAG.getNode(ISD::SRL, DL, VA.getLocVT(), Val, 3924 DAG.getConstant(32, DL, VA.getLocVT())); 3925 LLVM_FALLTHROUGH; 3926 case CCValAssign::AExt: 3927 LLVM_FALLTHROUGH; 3928 case CCValAssign::ZExt: 3929 Val = DAG.getZExtOrTrunc(Val, DL, VA.getValVT()); 3930 break; 3931 } 3932 3933 InVals.push_back(Val); 3934 } 3935 3936 return Chain; 3937 } 3938 3939 /// Return true if the calling convention is one that we can guarantee TCO for. 3940 static bool canGuaranteeTCO(CallingConv::ID CC) { 3941 return CC == CallingConv::Fast; 3942 } 3943 3944 /// Return true if we might ever do TCO for calls with this calling convention. 3945 static bool mayTailCallThisCC(CallingConv::ID CC) { 3946 switch (CC) { 3947 case CallingConv::C: 3948 case CallingConv::PreserveMost: 3949 case CallingConv::Swift: 3950 return true; 3951 default: 3952 return canGuaranteeTCO(CC); 3953 } 3954 } 3955 3956 bool AArch64TargetLowering::isEligibleForTailCallOptimization( 3957 SDValue Callee, CallingConv::ID CalleeCC, bool isVarArg, 3958 const SmallVectorImpl<ISD::OutputArg> &Outs, 3959 const SmallVectorImpl<SDValue> &OutVals, 3960 const SmallVectorImpl<ISD::InputArg> &Ins, SelectionDAG &DAG) const { 3961 if (!mayTailCallThisCC(CalleeCC)) 3962 return false; 3963 3964 MachineFunction &MF = DAG.getMachineFunction(); 3965 const Function &CallerF = MF.getFunction(); 3966 CallingConv::ID CallerCC = CallerF.getCallingConv(); 3967 bool CCMatch = CallerCC == CalleeCC; 3968 3969 // When using the Windows calling convention on a non-windows OS, we want 3970 // to back up and restore X18 in such functions; we can't do a tail call 3971 // from those functions. 3972 if (CallerCC == CallingConv::Win64 && !Subtarget->isTargetWindows() && 3973 CalleeCC != CallingConv::Win64) 3974 return false; 3975 3976 // Byval parameters hand the function a pointer directly into the stack area 3977 // we want to reuse during a tail call. Working around this *is* possible (see 3978 // X86) but less efficient and uglier in LowerCall. 3979 for (Function::const_arg_iterator i = CallerF.arg_begin(), 3980 e = CallerF.arg_end(); 3981 i != e; ++i) { 3982 if (i->hasByValAttr()) 3983 return false; 3984 3985 // On Windows, "inreg" attributes signify non-aggregate indirect returns. 3986 // In this case, it is necessary to save/restore X0 in the callee. Tail 3987 // call opt interferes with this. So we disable tail call opt when the 3988 // caller has an argument with "inreg" attribute. 3989 3990 // FIXME: Check whether the callee also has an "inreg" argument. 3991 if (i->hasInRegAttr()) 3992 return false; 3993 } 3994 3995 if (getTargetMachine().Options.GuaranteedTailCallOpt) 3996 return canGuaranteeTCO(CalleeCC) && CCMatch; 3997 3998 // Externally-defined functions with weak linkage should not be 3999 // tail-called on AArch64 when the OS does not support dynamic 4000 // pre-emption of symbols, as the AAELF spec requires normal calls 4001 // to undefined weak functions to be replaced with a NOP or jump to the 4002 // next instruction. The behaviour of branch instructions in this 4003 // situation (as used for tail calls) is implementation-defined, so we 4004 // cannot rely on the linker replacing the tail call with a return. 4005 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) { 4006 const GlobalValue *GV = G->getGlobal(); 4007 const Triple &TT = getTargetMachine().getTargetTriple(); 4008 if (GV->hasExternalWeakLinkage() && 4009 (!TT.isOSWindows() || TT.isOSBinFormatELF() || TT.isOSBinFormatMachO())) 4010 return false; 4011 } 4012 4013 // Now we search for cases where we can use a tail call without changing the 4014 // ABI. Sibcall is used in some places (particularly gcc) to refer to this 4015 // concept. 4016 4017 // I want anyone implementing a new calling convention to think long and hard 4018 // about this assert. 4019 assert((!isVarArg || CalleeCC == CallingConv::C) && 4020 "Unexpected variadic calling convention"); 4021 4022 LLVMContext &C = *DAG.getContext(); 4023 if (isVarArg && !Outs.empty()) { 4024 // At least two cases here: if caller is fastcc then we can't have any 4025 // memory arguments (we'd be expected to clean up the stack afterwards). If 4026 // caller is C then we could potentially use its argument area. 4027 4028 // FIXME: for now we take the most conservative of these in both cases: 4029 // disallow all variadic memory operands. 4030 SmallVector<CCValAssign, 16> ArgLocs; 4031 CCState CCInfo(CalleeCC, isVarArg, MF, ArgLocs, C); 4032 4033 CCInfo.AnalyzeCallOperands(Outs, CCAssignFnForCall(CalleeCC, true)); 4034 for (const CCValAssign &ArgLoc : ArgLocs) 4035 if (!ArgLoc.isRegLoc()) 4036 return false; 4037 } 4038 4039 // Check that the call results are passed in the same way. 4040 if (!CCState::resultsCompatible(CalleeCC, CallerCC, MF, C, Ins, 4041 CCAssignFnForCall(CalleeCC, isVarArg), 4042 CCAssignFnForCall(CallerCC, isVarArg))) 4043 return false; 4044 // The callee has to preserve all registers the caller needs to preserve. 4045 const AArch64RegisterInfo *TRI = Subtarget->getRegisterInfo(); 4046 const uint32_t *CallerPreserved = TRI->getCallPreservedMask(MF, CallerCC); 4047 if (!CCMatch) { 4048 const uint32_t *CalleePreserved = TRI->getCallPreservedMask(MF, CalleeCC); 4049 if (Subtarget->hasCustomCallingConv()) { 4050 TRI->UpdateCustomCallPreservedMask(MF, &CallerPreserved); 4051 TRI->UpdateCustomCallPreservedMask(MF, &CalleePreserved); 4052 } 4053 if (!TRI->regmaskSubsetEqual(CallerPreserved, CalleePreserved)) 4054 return false; 4055 } 4056 4057 // Nothing more to check if the callee is taking no arguments 4058 if (Outs.empty()) 4059 return true; 4060 4061 SmallVector<CCValAssign, 16> ArgLocs; 4062 CCState CCInfo(CalleeCC, isVarArg, MF, ArgLocs, C); 4063 4064 CCInfo.AnalyzeCallOperands(Outs, CCAssignFnForCall(CalleeCC, isVarArg)); 4065 4066 const AArch64FunctionInfo *FuncInfo = MF.getInfo<AArch64FunctionInfo>(); 4067 4068 // If any of the arguments is passed indirectly, it must be SVE, so the 4069 // 'getBytesInStackArgArea' is not sufficient to determine whether we need to 4070 // allocate space on the stack. That is why we determine this explicitly here 4071 // the call cannot be a tailcall. 4072 if (llvm::any_of(ArgLocs, [](CCValAssign &A) { 4073 assert((A.getLocInfo() != CCValAssign::Indirect || 4074 A.getValVT().isScalableVector()) && 4075 "Expected value to be scalable"); 4076 return A.getLocInfo() == CCValAssign::Indirect; 4077 })) 4078 return false; 4079 4080 // If the stack arguments for this call do not fit into our own save area then 4081 // the call cannot be made tail. 4082 if (CCInfo.getNextStackOffset() > FuncInfo->getBytesInStackArgArea()) 4083 return false; 4084 4085 const MachineRegisterInfo &MRI = MF.getRegInfo(); 4086 if (!parametersInCSRMatch(MRI, CallerPreserved, ArgLocs, OutVals)) 4087 return false; 4088 4089 return true; 4090 } 4091 4092 SDValue AArch64TargetLowering::addTokenForArgument(SDValue Chain, 4093 SelectionDAG &DAG, 4094 MachineFrameInfo &MFI, 4095 int ClobberedFI) const { 4096 SmallVector<SDValue, 8> ArgChains; 4097 int64_t FirstByte = MFI.getObjectOffset(ClobberedFI); 4098 int64_t LastByte = FirstByte + MFI.getObjectSize(ClobberedFI) - 1; 4099 4100 // Include the original chain at the beginning of the list. When this is 4101 // used by target LowerCall hooks, this helps legalize find the 4102 // CALLSEQ_BEGIN node. 4103 ArgChains.push_back(Chain); 4104 4105 // Add a chain value for each stack argument corresponding 4106 for (SDNode::use_iterator U = DAG.getEntryNode().getNode()->use_begin(), 4107 UE = DAG.getEntryNode().getNode()->use_end(); 4108 U != UE; ++U) 4109 if (LoadSDNode *L = dyn_cast<LoadSDNode>(*U)) 4110 if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(L->getBasePtr())) 4111 if (FI->getIndex() < 0) { 4112 int64_t InFirstByte = MFI.getObjectOffset(FI->getIndex()); 4113 int64_t InLastByte = InFirstByte; 4114 InLastByte += MFI.getObjectSize(FI->getIndex()) - 1; 4115 4116 if ((InFirstByte <= FirstByte && FirstByte <= InLastByte) || 4117 (FirstByte <= InFirstByte && InFirstByte <= LastByte)) 4118 ArgChains.push_back(SDValue(L, 1)); 4119 } 4120 4121 // Build a tokenfactor for all the chains. 4122 return DAG.getNode(ISD::TokenFactor, SDLoc(Chain), MVT::Other, ArgChains); 4123 } 4124 4125 bool AArch64TargetLowering::DoesCalleeRestoreStack(CallingConv::ID CallCC, 4126 bool TailCallOpt) const { 4127 return CallCC == CallingConv::Fast && TailCallOpt; 4128 } 4129 4130 /// LowerCall - Lower a call to a callseq_start + CALL + callseq_end chain, 4131 /// and add input and output parameter nodes. 4132 SDValue 4133 AArch64TargetLowering::LowerCall(CallLoweringInfo &CLI, 4134 SmallVectorImpl<SDValue> &InVals) const { 4135 SelectionDAG &DAG = CLI.DAG; 4136 SDLoc &DL = CLI.DL; 4137 SmallVector<ISD::OutputArg, 32> &Outs = CLI.Outs; 4138 SmallVector<SDValue, 32> &OutVals = CLI.OutVals; 4139 SmallVector<ISD::InputArg, 32> &Ins = CLI.Ins; 4140 SDValue Chain = CLI.Chain; 4141 SDValue Callee = CLI.Callee; 4142 bool &IsTailCall = CLI.IsTailCall; 4143 CallingConv::ID CallConv = CLI.CallConv; 4144 bool IsVarArg = CLI.IsVarArg; 4145 4146 MachineFunction &MF = DAG.getMachineFunction(); 4147 MachineFunction::CallSiteInfo CSInfo; 4148 bool IsThisReturn = false; 4149 4150 AArch64FunctionInfo *FuncInfo = MF.getInfo<AArch64FunctionInfo>(); 4151 bool TailCallOpt = MF.getTarget().Options.GuaranteedTailCallOpt; 4152 bool IsSibCall = false; 4153 4154 if (IsTailCall) { 4155 // Check if it's really possible to do a tail call. 4156 IsTailCall = isEligibleForTailCallOptimization( 4157 Callee, CallConv, IsVarArg, Outs, OutVals, Ins, DAG); 4158 if (!IsTailCall && CLI.CB && CLI.CB->isMustTailCall()) 4159 report_fatal_error("failed to perform tail call elimination on a call " 4160 "site marked musttail"); 4161 4162 // A sibling call is one where we're under the usual C ABI and not planning 4163 // to change that but can still do a tail call: 4164 if (!TailCallOpt && IsTailCall) 4165 IsSibCall = true; 4166 4167 if (IsTailCall) 4168 ++NumTailCalls; 4169 } 4170 4171 // Analyze operands of the call, assigning locations to each operand. 4172 SmallVector<CCValAssign, 16> ArgLocs; 4173 CCState CCInfo(CallConv, IsVarArg, DAG.getMachineFunction(), ArgLocs, 4174 *DAG.getContext()); 4175 4176 if (IsVarArg) { 4177 // Handle fixed and variable vector arguments differently. 4178 // Variable vector arguments always go into memory. 4179 unsigned NumArgs = Outs.size(); 4180 4181 for (unsigned i = 0; i != NumArgs; ++i) { 4182 MVT ArgVT = Outs[i].VT; 4183 ISD::ArgFlagsTy ArgFlags = Outs[i].Flags; 4184 CCAssignFn *AssignFn = CCAssignFnForCall(CallConv, 4185 /*IsVarArg=*/ !Outs[i].IsFixed); 4186 bool Res = AssignFn(i, ArgVT, ArgVT, CCValAssign::Full, ArgFlags, CCInfo); 4187 assert(!Res && "Call operand has unhandled type"); 4188 (void)Res; 4189 } 4190 } else { 4191 // At this point, Outs[].VT may already be promoted to i32. To correctly 4192 // handle passing i8 as i8 instead of i32 on stack, we pass in both i32 and 4193 // i8 to CC_AArch64_AAPCS with i32 being ValVT and i8 being LocVT. 4194 // Since AnalyzeCallOperands uses Ins[].VT for both ValVT and LocVT, here 4195 // we use a special version of AnalyzeCallOperands to pass in ValVT and 4196 // LocVT. 4197 unsigned NumArgs = Outs.size(); 4198 for (unsigned i = 0; i != NumArgs; ++i) { 4199 MVT ValVT = Outs[i].VT; 4200 // Get type of the original argument. 4201 EVT ActualVT = getValueType(DAG.getDataLayout(), 4202 CLI.getArgs()[Outs[i].OrigArgIndex].Ty, 4203 /*AllowUnknown*/ true); 4204 MVT ActualMVT = ActualVT.isSimple() ? ActualVT.getSimpleVT() : ValVT; 4205 ISD::ArgFlagsTy ArgFlags = Outs[i].Flags; 4206 // If ActualMVT is i1/i8/i16, we should set LocVT to i8/i8/i16. 4207 if (ActualMVT == MVT::i1 || ActualMVT == MVT::i8) 4208 ValVT = MVT::i8; 4209 else if (ActualMVT == MVT::i16) 4210 ValVT = MVT::i16; 4211 4212 CCAssignFn *AssignFn = CCAssignFnForCall(CallConv, /*IsVarArg=*/false); 4213 bool Res = AssignFn(i, ValVT, ValVT, CCValAssign::Full, ArgFlags, CCInfo); 4214 assert(!Res && "Call operand has unhandled type"); 4215 (void)Res; 4216 } 4217 } 4218 4219 // Get a count of how many bytes are to be pushed on the stack. 4220 unsigned NumBytes = CCInfo.getNextStackOffset(); 4221 4222 if (IsSibCall) { 4223 // Since we're not changing the ABI to make this a tail call, the memory 4224 // operands are already available in the caller's incoming argument space. 4225 NumBytes = 0; 4226 } 4227 4228 // FPDiff is the byte offset of the call's argument area from the callee's. 4229 // Stores to callee stack arguments will be placed in FixedStackSlots offset 4230 // by this amount for a tail call. In a sibling call it must be 0 because the 4231 // caller will deallocate the entire stack and the callee still expects its 4232 // arguments to begin at SP+0. Completely unused for non-tail calls. 4233 int FPDiff = 0; 4234 4235 if (IsTailCall && !IsSibCall) { 4236 unsigned NumReusableBytes = FuncInfo->getBytesInStackArgArea(); 4237 4238 // Since callee will pop argument stack as a tail call, we must keep the 4239 // popped size 16-byte aligned. 4240 NumBytes = alignTo(NumBytes, 16); 4241 4242 // FPDiff will be negative if this tail call requires more space than we 4243 // would automatically have in our incoming argument space. Positive if we 4244 // can actually shrink the stack. 4245 FPDiff = NumReusableBytes - NumBytes; 4246 4247 // The stack pointer must be 16-byte aligned at all times it's used for a 4248 // memory operation, which in practice means at *all* times and in 4249 // particular across call boundaries. Therefore our own arguments started at 4250 // a 16-byte aligned SP and the delta applied for the tail call should 4251 // satisfy the same constraint. 4252 assert(FPDiff % 16 == 0 && "unaligned stack on tail call"); 4253 } 4254 4255 // Adjust the stack pointer for the new arguments... 4256 // These operations are automatically eliminated by the prolog/epilog pass 4257 if (!IsSibCall) 4258 Chain = DAG.getCALLSEQ_START(Chain, NumBytes, 0, DL); 4259 4260 SDValue StackPtr = DAG.getCopyFromReg(Chain, DL, AArch64::SP, 4261 getPointerTy(DAG.getDataLayout())); 4262 4263 SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass; 4264 SmallSet<unsigned, 8> RegsUsed; 4265 SmallVector<SDValue, 8> MemOpChains; 4266 auto PtrVT = getPointerTy(DAG.getDataLayout()); 4267 4268 if (IsVarArg && CLI.CB && CLI.CB->isMustTailCall()) { 4269 const auto &Forwards = FuncInfo->getForwardedMustTailRegParms(); 4270 for (const auto &F : Forwards) { 4271 SDValue Val = DAG.getCopyFromReg(Chain, DL, F.VReg, F.VT); 4272 RegsToPass.emplace_back(F.PReg, Val); 4273 } 4274 } 4275 4276 // Walk the register/memloc assignments, inserting copies/loads. 4277 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) { 4278 CCValAssign &VA = ArgLocs[i]; 4279 SDValue Arg = OutVals[i]; 4280 ISD::ArgFlagsTy Flags = Outs[i].Flags; 4281 4282 // Promote the value if needed. 4283 switch (VA.getLocInfo()) { 4284 default: 4285 llvm_unreachable("Unknown loc info!"); 4286 case CCValAssign::Full: 4287 break; 4288 case CCValAssign::SExt: 4289 Arg = DAG.getNode(ISD::SIGN_EXTEND, DL, VA.getLocVT(), Arg); 4290 break; 4291 case CCValAssign::ZExt: 4292 Arg = DAG.getNode(ISD::ZERO_EXTEND, DL, VA.getLocVT(), Arg); 4293 break; 4294 case CCValAssign::AExt: 4295 if (Outs[i].ArgVT == MVT::i1) { 4296 // AAPCS requires i1 to be zero-extended to 8-bits by the caller. 4297 Arg = DAG.getNode(ISD::TRUNCATE, DL, MVT::i1, Arg); 4298 Arg = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i8, Arg); 4299 } 4300 Arg = DAG.getNode(ISD::ANY_EXTEND, DL, VA.getLocVT(), Arg); 4301 break; 4302 case CCValAssign::AExtUpper: 4303 assert(VA.getValVT() == MVT::i32 && "only expect 32 -> 64 upper bits"); 4304 Arg = DAG.getNode(ISD::ANY_EXTEND, DL, VA.getLocVT(), Arg); 4305 Arg = DAG.getNode(ISD::SHL, DL, VA.getLocVT(), Arg, 4306 DAG.getConstant(32, DL, VA.getLocVT())); 4307 break; 4308 case CCValAssign::BCvt: 4309 Arg = DAG.getBitcast(VA.getLocVT(), Arg); 4310 break; 4311 case CCValAssign::Trunc: 4312 Arg = DAG.getZExtOrTrunc(Arg, DL, VA.getLocVT()); 4313 break; 4314 case CCValAssign::FPExt: 4315 Arg = DAG.getNode(ISD::FP_EXTEND, DL, VA.getLocVT(), Arg); 4316 break; 4317 case CCValAssign::Indirect: 4318 assert(VA.getValVT().isScalableVector() && 4319 "Only scalable vectors can be passed indirectly"); 4320 MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo(); 4321 Type *Ty = EVT(VA.getValVT()).getTypeForEVT(*DAG.getContext()); 4322 unsigned Align = DAG.getDataLayout().getPrefTypeAlignment(Ty); 4323 int FI = MFI.CreateStackObject( 4324 VA.getValVT().getStoreSize().getKnownMinSize(), Align, false); 4325 MFI.setStackID(FI, TargetStackID::SVEVector); 4326 4327 SDValue SpillSlot = DAG.getFrameIndex( 4328 FI, DAG.getTargetLoweringInfo().getFrameIndexTy(DAG.getDataLayout())); 4329 Chain = DAG.getStore( 4330 Chain, DL, Arg, SpillSlot, 4331 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI)); 4332 Arg = SpillSlot; 4333 break; 4334 } 4335 4336 if (VA.isRegLoc()) { 4337 if (i == 0 && Flags.isReturned() && !Flags.isSwiftSelf() && 4338 Outs[0].VT == MVT::i64) { 4339 assert(VA.getLocVT() == MVT::i64 && 4340 "unexpected calling convention register assignment"); 4341 assert(!Ins.empty() && Ins[0].VT == MVT::i64 && 4342 "unexpected use of 'returned'"); 4343 IsThisReturn = true; 4344 } 4345 if (RegsUsed.count(VA.getLocReg())) { 4346 // If this register has already been used then we're trying to pack 4347 // parts of an [N x i32] into an X-register. The extension type will 4348 // take care of putting the two halves in the right place but we have to 4349 // combine them. 4350 SDValue &Bits = 4351 std::find_if(RegsToPass.begin(), RegsToPass.end(), 4352 [=](const std::pair<unsigned, SDValue> &Elt) { 4353 return Elt.first == VA.getLocReg(); 4354 }) 4355 ->second; 4356 Bits = DAG.getNode(ISD::OR, DL, Bits.getValueType(), Bits, Arg); 4357 // Call site info is used for function's parameter entry value 4358 // tracking. For now we track only simple cases when parameter 4359 // is transferred through whole register. 4360 CSInfo.erase(std::remove_if(CSInfo.begin(), CSInfo.end(), 4361 [&VA](MachineFunction::ArgRegPair ArgReg) { 4362 return ArgReg.Reg == VA.getLocReg(); 4363 }), 4364 CSInfo.end()); 4365 } else { 4366 RegsToPass.emplace_back(VA.getLocReg(), Arg); 4367 RegsUsed.insert(VA.getLocReg()); 4368 const TargetOptions &Options = DAG.getTarget().Options; 4369 if (Options.EmitCallSiteInfo) 4370 CSInfo.emplace_back(VA.getLocReg(), i); 4371 } 4372 } else { 4373 assert(VA.isMemLoc()); 4374 4375 SDValue DstAddr; 4376 MachinePointerInfo DstInfo; 4377 4378 // FIXME: This works on big-endian for composite byvals, which are the 4379 // common case. It should also work for fundamental types too. 4380 uint32_t BEAlign = 0; 4381 unsigned OpSize; 4382 if (VA.getLocInfo() == CCValAssign::Indirect) 4383 OpSize = VA.getLocVT().getSizeInBits(); 4384 else 4385 OpSize = Flags.isByVal() ? Flags.getByValSize() * 8 4386 : VA.getValVT().getSizeInBits(); 4387 OpSize = (OpSize + 7) / 8; 4388 if (!Subtarget->isLittleEndian() && !Flags.isByVal() && 4389 !Flags.isInConsecutiveRegs()) { 4390 if (OpSize < 8) 4391 BEAlign = 8 - OpSize; 4392 } 4393 unsigned LocMemOffset = VA.getLocMemOffset(); 4394 int32_t Offset = LocMemOffset + BEAlign; 4395 SDValue PtrOff = DAG.getIntPtrConstant(Offset, DL); 4396 PtrOff = DAG.getNode(ISD::ADD, DL, PtrVT, StackPtr, PtrOff); 4397 4398 if (IsTailCall) { 4399 Offset = Offset + FPDiff; 4400 int FI = MF.getFrameInfo().CreateFixedObject(OpSize, Offset, true); 4401 4402 DstAddr = DAG.getFrameIndex(FI, PtrVT); 4403 DstInfo = 4404 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI); 4405 4406 // Make sure any stack arguments overlapping with where we're storing 4407 // are loaded before this eventual operation. Otherwise they'll be 4408 // clobbered. 4409 Chain = addTokenForArgument(Chain, DAG, MF.getFrameInfo(), FI); 4410 } else { 4411 SDValue PtrOff = DAG.getIntPtrConstant(Offset, DL); 4412 4413 DstAddr = DAG.getNode(ISD::ADD, DL, PtrVT, StackPtr, PtrOff); 4414 DstInfo = MachinePointerInfo::getStack(DAG.getMachineFunction(), 4415 LocMemOffset); 4416 } 4417 4418 if (Outs[i].Flags.isByVal()) { 4419 SDValue SizeNode = 4420 DAG.getConstant(Outs[i].Flags.getByValSize(), DL, MVT::i64); 4421 SDValue Cpy = DAG.getMemcpy( 4422 Chain, DL, DstAddr, Arg, SizeNode, 4423 Outs[i].Flags.getNonZeroByValAlign(), 4424 /*isVol = */ false, /*AlwaysInline = */ false, 4425 /*isTailCall = */ false, DstInfo, MachinePointerInfo()); 4426 4427 MemOpChains.push_back(Cpy); 4428 } else { 4429 // Since we pass i1/i8/i16 as i1/i8/i16 on stack and Arg is already 4430 // promoted to a legal register type i32, we should truncate Arg back to 4431 // i1/i8/i16. 4432 if (VA.getValVT() == MVT::i1 || VA.getValVT() == MVT::i8 || 4433 VA.getValVT() == MVT::i16) 4434 Arg = DAG.getNode(ISD::TRUNCATE, DL, VA.getValVT(), Arg); 4435 4436 SDValue Store = DAG.getStore(Chain, DL, Arg, DstAddr, DstInfo); 4437 MemOpChains.push_back(Store); 4438 } 4439 } 4440 } 4441 4442 if (!MemOpChains.empty()) 4443 Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, MemOpChains); 4444 4445 // Build a sequence of copy-to-reg nodes chained together with token chain 4446 // and flag operands which copy the outgoing args into the appropriate regs. 4447 SDValue InFlag; 4448 for (auto &RegToPass : RegsToPass) { 4449 Chain = DAG.getCopyToReg(Chain, DL, RegToPass.first, 4450 RegToPass.second, InFlag); 4451 InFlag = Chain.getValue(1); 4452 } 4453 4454 // If the callee is a GlobalAddress/ExternalSymbol node (quite common, every 4455 // direct call is) turn it into a TargetGlobalAddress/TargetExternalSymbol 4456 // node so that legalize doesn't hack it. 4457 if (auto *G = dyn_cast<GlobalAddressSDNode>(Callee)) { 4458 auto GV = G->getGlobal(); 4459 unsigned OpFlags = 4460 Subtarget->classifyGlobalFunctionReference(GV, getTargetMachine()); 4461 if (OpFlags & AArch64II::MO_GOT) { 4462 Callee = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, OpFlags); 4463 Callee = DAG.getNode(AArch64ISD::LOADgot, DL, PtrVT, Callee); 4464 } else { 4465 const GlobalValue *GV = G->getGlobal(); 4466 Callee = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, 0); 4467 } 4468 } else if (auto *S = dyn_cast<ExternalSymbolSDNode>(Callee)) { 4469 if (getTargetMachine().getCodeModel() == CodeModel::Large && 4470 Subtarget->isTargetMachO()) { 4471 const char *Sym = S->getSymbol(); 4472 Callee = DAG.getTargetExternalSymbol(Sym, PtrVT, AArch64II::MO_GOT); 4473 Callee = DAG.getNode(AArch64ISD::LOADgot, DL, PtrVT, Callee); 4474 } else { 4475 const char *Sym = S->getSymbol(); 4476 Callee = DAG.getTargetExternalSymbol(Sym, PtrVT, 0); 4477 } 4478 } 4479 4480 // We don't usually want to end the call-sequence here because we would tidy 4481 // the frame up *after* the call, however in the ABI-changing tail-call case 4482 // we've carefully laid out the parameters so that when sp is reset they'll be 4483 // in the correct location. 4484 if (IsTailCall && !IsSibCall) { 4485 Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, DL, true), 4486 DAG.getIntPtrConstant(0, DL, true), InFlag, DL); 4487 InFlag = Chain.getValue(1); 4488 } 4489 4490 std::vector<SDValue> Ops; 4491 Ops.push_back(Chain); 4492 Ops.push_back(Callee); 4493 4494 if (IsTailCall) { 4495 // Each tail call may have to adjust the stack by a different amount, so 4496 // this information must travel along with the operation for eventual 4497 // consumption by emitEpilogue. 4498 Ops.push_back(DAG.getTargetConstant(FPDiff, DL, MVT::i32)); 4499 } 4500 4501 // Add argument registers to the end of the list so that they are known live 4502 // into the call. 4503 for (auto &RegToPass : RegsToPass) 4504 Ops.push_back(DAG.getRegister(RegToPass.first, 4505 RegToPass.second.getValueType())); 4506 4507 // Check callee args/returns for SVE registers and set calling convention 4508 // accordingly. 4509 if (CallConv == CallingConv::C) { 4510 bool CalleeOutSVE = any_of(Outs, [](ISD::OutputArg &Out){ 4511 return Out.VT.isScalableVector(); 4512 }); 4513 bool CalleeInSVE = any_of(Ins, [](ISD::InputArg &In){ 4514 return In.VT.isScalableVector(); 4515 }); 4516 4517 if (CalleeInSVE || CalleeOutSVE) 4518 CallConv = CallingConv::AArch64_SVE_VectorCall; 4519 } 4520 4521 // Add a register mask operand representing the call-preserved registers. 4522 const uint32_t *Mask; 4523 const AArch64RegisterInfo *TRI = Subtarget->getRegisterInfo(); 4524 if (IsThisReturn) { 4525 // For 'this' returns, use the X0-preserving mask if applicable 4526 Mask = TRI->getThisReturnPreservedMask(MF, CallConv); 4527 if (!Mask) { 4528 IsThisReturn = false; 4529 Mask = TRI->getCallPreservedMask(MF, CallConv); 4530 } 4531 } else 4532 Mask = TRI->getCallPreservedMask(MF, CallConv); 4533 4534 if (Subtarget->hasCustomCallingConv()) 4535 TRI->UpdateCustomCallPreservedMask(MF, &Mask); 4536 4537 if (TRI->isAnyArgRegReserved(MF)) 4538 TRI->emitReservedArgRegCallError(MF); 4539 4540 assert(Mask && "Missing call preserved mask for calling convention"); 4541 Ops.push_back(DAG.getRegisterMask(Mask)); 4542 4543 if (InFlag.getNode()) 4544 Ops.push_back(InFlag); 4545 4546 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue); 4547 4548 // If we're doing a tall call, use a TC_RETURN here rather than an 4549 // actual call instruction. 4550 if (IsTailCall) { 4551 MF.getFrameInfo().setHasTailCall(); 4552 SDValue Ret = DAG.getNode(AArch64ISD::TC_RETURN, DL, NodeTys, Ops); 4553 DAG.addCallSiteInfo(Ret.getNode(), std::move(CSInfo)); 4554 return Ret; 4555 } 4556 4557 // Returns a chain and a flag for retval copy to use. 4558 Chain = DAG.getNode(AArch64ISD::CALL, DL, NodeTys, Ops); 4559 DAG.addNoMergeSiteInfo(Chain.getNode(), CLI.NoMerge); 4560 InFlag = Chain.getValue(1); 4561 DAG.addCallSiteInfo(Chain.getNode(), std::move(CSInfo)); 4562 4563 uint64_t CalleePopBytes = 4564 DoesCalleeRestoreStack(CallConv, TailCallOpt) ? alignTo(NumBytes, 16) : 0; 4565 4566 Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, DL, true), 4567 DAG.getIntPtrConstant(CalleePopBytes, DL, true), 4568 InFlag, DL); 4569 if (!Ins.empty()) 4570 InFlag = Chain.getValue(1); 4571 4572 // Handle result values, copying them out of physregs into vregs that we 4573 // return. 4574 return LowerCallResult(Chain, InFlag, CallConv, IsVarArg, Ins, DL, DAG, 4575 InVals, IsThisReturn, 4576 IsThisReturn ? OutVals[0] : SDValue()); 4577 } 4578 4579 bool AArch64TargetLowering::CanLowerReturn( 4580 CallingConv::ID CallConv, MachineFunction &MF, bool isVarArg, 4581 const SmallVectorImpl<ISD::OutputArg> &Outs, LLVMContext &Context) const { 4582 CCAssignFn *RetCC = CallConv == CallingConv::WebKit_JS 4583 ? RetCC_AArch64_WebKit_JS 4584 : RetCC_AArch64_AAPCS; 4585 SmallVector<CCValAssign, 16> RVLocs; 4586 CCState CCInfo(CallConv, isVarArg, MF, RVLocs, Context); 4587 return CCInfo.CheckReturn(Outs, RetCC); 4588 } 4589 4590 SDValue 4591 AArch64TargetLowering::LowerReturn(SDValue Chain, CallingConv::ID CallConv, 4592 bool isVarArg, 4593 const SmallVectorImpl<ISD::OutputArg> &Outs, 4594 const SmallVectorImpl<SDValue> &OutVals, 4595 const SDLoc &DL, SelectionDAG &DAG) const { 4596 auto &MF = DAG.getMachineFunction(); 4597 auto *FuncInfo = MF.getInfo<AArch64FunctionInfo>(); 4598 4599 CCAssignFn *RetCC = CallConv == CallingConv::WebKit_JS 4600 ? RetCC_AArch64_WebKit_JS 4601 : RetCC_AArch64_AAPCS; 4602 SmallVector<CCValAssign, 16> RVLocs; 4603 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs, 4604 *DAG.getContext()); 4605 CCInfo.AnalyzeReturn(Outs, RetCC); 4606 4607 // Copy the result values into the output registers. 4608 SDValue Flag; 4609 SmallVector<std::pair<unsigned, SDValue>, 4> RetVals; 4610 SmallSet<unsigned, 4> RegsUsed; 4611 for (unsigned i = 0, realRVLocIdx = 0; i != RVLocs.size(); 4612 ++i, ++realRVLocIdx) { 4613 CCValAssign &VA = RVLocs[i]; 4614 assert(VA.isRegLoc() && "Can only return in registers!"); 4615 SDValue Arg = OutVals[realRVLocIdx]; 4616 4617 switch (VA.getLocInfo()) { 4618 default: 4619 llvm_unreachable("Unknown loc info!"); 4620 case CCValAssign::Full: 4621 if (Outs[i].ArgVT == MVT::i1) { 4622 // AAPCS requires i1 to be zero-extended to i8 by the producer of the 4623 // value. This is strictly redundant on Darwin (which uses "zeroext 4624 // i1"), but will be optimised out before ISel. 4625 Arg = DAG.getNode(ISD::TRUNCATE, DL, MVT::i1, Arg); 4626 Arg = DAG.getNode(ISD::ZERO_EXTEND, DL, VA.getLocVT(), Arg); 4627 } 4628 break; 4629 case CCValAssign::BCvt: 4630 Arg = DAG.getNode(ISD::BITCAST, DL, VA.getLocVT(), Arg); 4631 break; 4632 case CCValAssign::AExt: 4633 case CCValAssign::ZExt: 4634 Arg = DAG.getZExtOrTrunc(Arg, DL, VA.getLocVT()); 4635 break; 4636 case CCValAssign::AExtUpper: 4637 assert(VA.getValVT() == MVT::i32 && "only expect 32 -> 64 upper bits"); 4638 Arg = DAG.getZExtOrTrunc(Arg, DL, VA.getLocVT()); 4639 Arg = DAG.getNode(ISD::SHL, DL, VA.getLocVT(), Arg, 4640 DAG.getConstant(32, DL, VA.getLocVT())); 4641 break; 4642 } 4643 4644 if (RegsUsed.count(VA.getLocReg())) { 4645 SDValue &Bits = 4646 std::find_if(RetVals.begin(), RetVals.end(), 4647 [=](const std::pair<unsigned, SDValue> &Elt) { 4648 return Elt.first == VA.getLocReg(); 4649 }) 4650 ->second; 4651 Bits = DAG.getNode(ISD::OR, DL, Bits.getValueType(), Bits, Arg); 4652 } else { 4653 RetVals.emplace_back(VA.getLocReg(), Arg); 4654 RegsUsed.insert(VA.getLocReg()); 4655 } 4656 } 4657 4658 SmallVector<SDValue, 4> RetOps(1, Chain); 4659 for (auto &RetVal : RetVals) { 4660 Chain = DAG.getCopyToReg(Chain, DL, RetVal.first, RetVal.second, Flag); 4661 Flag = Chain.getValue(1); 4662 RetOps.push_back( 4663 DAG.getRegister(RetVal.first, RetVal.second.getValueType())); 4664 } 4665 4666 // Windows AArch64 ABIs require that for returning structs by value we copy 4667 // the sret argument into X0 for the return. 4668 // We saved the argument into a virtual register in the entry block, 4669 // so now we copy the value out and into X0. 4670 if (unsigned SRetReg = FuncInfo->getSRetReturnReg()) { 4671 SDValue Val = DAG.getCopyFromReg(RetOps[0], DL, SRetReg, 4672 getPointerTy(MF.getDataLayout())); 4673 4674 unsigned RetValReg = AArch64::X0; 4675 Chain = DAG.getCopyToReg(Chain, DL, RetValReg, Val, Flag); 4676 Flag = Chain.getValue(1); 4677 4678 RetOps.push_back( 4679 DAG.getRegister(RetValReg, getPointerTy(DAG.getDataLayout()))); 4680 } 4681 4682 const AArch64RegisterInfo *TRI = Subtarget->getRegisterInfo(); 4683 const MCPhysReg *I = 4684 TRI->getCalleeSavedRegsViaCopy(&DAG.getMachineFunction()); 4685 if (I) { 4686 for (; *I; ++I) { 4687 if (AArch64::GPR64RegClass.contains(*I)) 4688 RetOps.push_back(DAG.getRegister(*I, MVT::i64)); 4689 else if (AArch64::FPR64RegClass.contains(*I)) 4690 RetOps.push_back(DAG.getRegister(*I, MVT::getFloatingPointVT(64))); 4691 else 4692 llvm_unreachable("Unexpected register class in CSRsViaCopy!"); 4693 } 4694 } 4695 4696 RetOps[0] = Chain; // Update chain. 4697 4698 // Add the flag if we have it. 4699 if (Flag.getNode()) 4700 RetOps.push_back(Flag); 4701 4702 return DAG.getNode(AArch64ISD::RET_FLAG, DL, MVT::Other, RetOps); 4703 } 4704 4705 //===----------------------------------------------------------------------===// 4706 // Other Lowering Code 4707 //===----------------------------------------------------------------------===// 4708 4709 SDValue AArch64TargetLowering::getTargetNode(GlobalAddressSDNode *N, EVT Ty, 4710 SelectionDAG &DAG, 4711 unsigned Flag) const { 4712 return DAG.getTargetGlobalAddress(N->getGlobal(), SDLoc(N), Ty, 4713 N->getOffset(), Flag); 4714 } 4715 4716 SDValue AArch64TargetLowering::getTargetNode(JumpTableSDNode *N, EVT Ty, 4717 SelectionDAG &DAG, 4718 unsigned Flag) const { 4719 return DAG.getTargetJumpTable(N->getIndex(), Ty, Flag); 4720 } 4721 4722 SDValue AArch64TargetLowering::getTargetNode(ConstantPoolSDNode *N, EVT Ty, 4723 SelectionDAG &DAG, 4724 unsigned Flag) const { 4725 return DAG.getTargetConstantPool(N->getConstVal(), Ty, N->getAlign(), 4726 N->getOffset(), Flag); 4727 } 4728 4729 SDValue AArch64TargetLowering::getTargetNode(BlockAddressSDNode* N, EVT Ty, 4730 SelectionDAG &DAG, 4731 unsigned Flag) const { 4732 return DAG.getTargetBlockAddress(N->getBlockAddress(), Ty, 0, Flag); 4733 } 4734 4735 // (loadGOT sym) 4736 template <class NodeTy> 4737 SDValue AArch64TargetLowering::getGOT(NodeTy *N, SelectionDAG &DAG, 4738 unsigned Flags) const { 4739 LLVM_DEBUG(dbgs() << "AArch64TargetLowering::getGOT\n"); 4740 SDLoc DL(N); 4741 EVT Ty = getPointerTy(DAG.getDataLayout()); 4742 SDValue GotAddr = getTargetNode(N, Ty, DAG, AArch64II::MO_GOT | Flags); 4743 // FIXME: Once remat is capable of dealing with instructions with register 4744 // operands, expand this into two nodes instead of using a wrapper node. 4745 return DAG.getNode(AArch64ISD::LOADgot, DL, Ty, GotAddr); 4746 } 4747 4748 // (wrapper %highest(sym), %higher(sym), %hi(sym), %lo(sym)) 4749 template <class NodeTy> 4750 SDValue AArch64TargetLowering::getAddrLarge(NodeTy *N, SelectionDAG &DAG, 4751 unsigned Flags) const { 4752 LLVM_DEBUG(dbgs() << "AArch64TargetLowering::getAddrLarge\n"); 4753 SDLoc DL(N); 4754 EVT Ty = getPointerTy(DAG.getDataLayout()); 4755 const unsigned char MO_NC = AArch64II::MO_NC; 4756 return DAG.getNode( 4757 AArch64ISD::WrapperLarge, DL, Ty, 4758 getTargetNode(N, Ty, DAG, AArch64II::MO_G3 | Flags), 4759 getTargetNode(N, Ty, DAG, AArch64II::MO_G2 | MO_NC | Flags), 4760 getTargetNode(N, Ty, DAG, AArch64II::MO_G1 | MO_NC | Flags), 4761 getTargetNode(N, Ty, DAG, AArch64II::MO_G0 | MO_NC | Flags)); 4762 } 4763 4764 // (addlow (adrp %hi(sym)) %lo(sym)) 4765 template <class NodeTy> 4766 SDValue AArch64TargetLowering::getAddr(NodeTy *N, SelectionDAG &DAG, 4767 unsigned Flags) const { 4768 LLVM_DEBUG(dbgs() << "AArch64TargetLowering::getAddr\n"); 4769 SDLoc DL(N); 4770 EVT Ty = getPointerTy(DAG.getDataLayout()); 4771 SDValue Hi = getTargetNode(N, Ty, DAG, AArch64II::MO_PAGE | Flags); 4772 SDValue Lo = getTargetNode(N, Ty, DAG, 4773 AArch64II::MO_PAGEOFF | AArch64II::MO_NC | Flags); 4774 SDValue ADRP = DAG.getNode(AArch64ISD::ADRP, DL, Ty, Hi); 4775 return DAG.getNode(AArch64ISD::ADDlow, DL, Ty, ADRP, Lo); 4776 } 4777 4778 // (adr sym) 4779 template <class NodeTy> 4780 SDValue AArch64TargetLowering::getAddrTiny(NodeTy *N, SelectionDAG &DAG, 4781 unsigned Flags) const { 4782 LLVM_DEBUG(dbgs() << "AArch64TargetLowering::getAddrTiny\n"); 4783 SDLoc DL(N); 4784 EVT Ty = getPointerTy(DAG.getDataLayout()); 4785 SDValue Sym = getTargetNode(N, Ty, DAG, Flags); 4786 return DAG.getNode(AArch64ISD::ADR, DL, Ty, Sym); 4787 } 4788 4789 SDValue AArch64TargetLowering::LowerGlobalAddress(SDValue Op, 4790 SelectionDAG &DAG) const { 4791 GlobalAddressSDNode *GN = cast<GlobalAddressSDNode>(Op); 4792 const GlobalValue *GV = GN->getGlobal(); 4793 unsigned OpFlags = Subtarget->ClassifyGlobalReference(GV, getTargetMachine()); 4794 4795 if (OpFlags != AArch64II::MO_NO_FLAG) 4796 assert(cast<GlobalAddressSDNode>(Op)->getOffset() == 0 && 4797 "unexpected offset in global node"); 4798 4799 // This also catches the large code model case for Darwin, and tiny code 4800 // model with got relocations. 4801 if ((OpFlags & AArch64II::MO_GOT) != 0) { 4802 return getGOT(GN, DAG, OpFlags); 4803 } 4804 4805 SDValue Result; 4806 if (getTargetMachine().getCodeModel() == CodeModel::Large) { 4807 Result = getAddrLarge(GN, DAG, OpFlags); 4808 } else if (getTargetMachine().getCodeModel() == CodeModel::Tiny) { 4809 Result = getAddrTiny(GN, DAG, OpFlags); 4810 } else { 4811 Result = getAddr(GN, DAG, OpFlags); 4812 } 4813 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 4814 SDLoc DL(GN); 4815 if (OpFlags & (AArch64II::MO_DLLIMPORT | AArch64II::MO_COFFSTUB)) 4816 Result = DAG.getLoad(PtrVT, DL, DAG.getEntryNode(), Result, 4817 MachinePointerInfo::getGOT(DAG.getMachineFunction())); 4818 return Result; 4819 } 4820 4821 /// Convert a TLS address reference into the correct sequence of loads 4822 /// and calls to compute the variable's address (for Darwin, currently) and 4823 /// return an SDValue containing the final node. 4824 4825 /// Darwin only has one TLS scheme which must be capable of dealing with the 4826 /// fully general situation, in the worst case. This means: 4827 /// + "extern __thread" declaration. 4828 /// + Defined in a possibly unknown dynamic library. 4829 /// 4830 /// The general system is that each __thread variable has a [3 x i64] descriptor 4831 /// which contains information used by the runtime to calculate the address. The 4832 /// only part of this the compiler needs to know about is the first xword, which 4833 /// contains a function pointer that must be called with the address of the 4834 /// entire descriptor in "x0". 4835 /// 4836 /// Since this descriptor may be in a different unit, in general even the 4837 /// descriptor must be accessed via an indirect load. The "ideal" code sequence 4838 /// is: 4839 /// adrp x0, _var@TLVPPAGE 4840 /// ldr x0, [x0, _var@TLVPPAGEOFF] ; x0 now contains address of descriptor 4841 /// ldr x1, [x0] ; x1 contains 1st entry of descriptor, 4842 /// ; the function pointer 4843 /// blr x1 ; Uses descriptor address in x0 4844 /// ; Address of _var is now in x0. 4845 /// 4846 /// If the address of _var's descriptor *is* known to the linker, then it can 4847 /// change the first "ldr" instruction to an appropriate "add x0, x0, #imm" for 4848 /// a slight efficiency gain. 4849 SDValue 4850 AArch64TargetLowering::LowerDarwinGlobalTLSAddress(SDValue Op, 4851 SelectionDAG &DAG) const { 4852 assert(Subtarget->isTargetDarwin() && 4853 "This function expects a Darwin target"); 4854 4855 SDLoc DL(Op); 4856 MVT PtrVT = getPointerTy(DAG.getDataLayout()); 4857 MVT PtrMemVT = getPointerMemTy(DAG.getDataLayout()); 4858 const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal(); 4859 4860 SDValue TLVPAddr = 4861 DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, AArch64II::MO_TLS); 4862 SDValue DescAddr = DAG.getNode(AArch64ISD::LOADgot, DL, PtrVT, TLVPAddr); 4863 4864 // The first entry in the descriptor is a function pointer that we must call 4865 // to obtain the address of the variable. 4866 SDValue Chain = DAG.getEntryNode(); 4867 SDValue FuncTLVGet = DAG.getLoad( 4868 PtrMemVT, DL, Chain, DescAddr, 4869 MachinePointerInfo::getGOT(DAG.getMachineFunction()), 4870 /* Alignment = */ PtrMemVT.getSizeInBits() / 8, 4871 MachineMemOperand::MOInvariant | MachineMemOperand::MODereferenceable); 4872 Chain = FuncTLVGet.getValue(1); 4873 4874 // Extend loaded pointer if necessary (i.e. if ILP32) to DAG pointer. 4875 FuncTLVGet = DAG.getZExtOrTrunc(FuncTLVGet, DL, PtrVT); 4876 4877 MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo(); 4878 MFI.setAdjustsStack(true); 4879 4880 // TLS calls preserve all registers except those that absolutely must be 4881 // trashed: X0 (it takes an argument), LR (it's a call) and NZCV (let's not be 4882 // silly). 4883 const AArch64RegisterInfo *TRI = Subtarget->getRegisterInfo(); 4884 const uint32_t *Mask = TRI->getTLSCallPreservedMask(); 4885 if (Subtarget->hasCustomCallingConv()) 4886 TRI->UpdateCustomCallPreservedMask(DAG.getMachineFunction(), &Mask); 4887 4888 // Finally, we can make the call. This is just a degenerate version of a 4889 // normal AArch64 call node: x0 takes the address of the descriptor, and 4890 // returns the address of the variable in this thread. 4891 Chain = DAG.getCopyToReg(Chain, DL, AArch64::X0, DescAddr, SDValue()); 4892 Chain = 4893 DAG.getNode(AArch64ISD::CALL, DL, DAG.getVTList(MVT::Other, MVT::Glue), 4894 Chain, FuncTLVGet, DAG.getRegister(AArch64::X0, MVT::i64), 4895 DAG.getRegisterMask(Mask), Chain.getValue(1)); 4896 return DAG.getCopyFromReg(Chain, DL, AArch64::X0, PtrVT, Chain.getValue(1)); 4897 } 4898 4899 /// Convert a thread-local variable reference into a sequence of instructions to 4900 /// compute the variable's address for the local exec TLS model of ELF targets. 4901 /// The sequence depends on the maximum TLS area size. 4902 SDValue AArch64TargetLowering::LowerELFTLSLocalExec(const GlobalValue *GV, 4903 SDValue ThreadBase, 4904 const SDLoc &DL, 4905 SelectionDAG &DAG) const { 4906 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 4907 SDValue TPOff, Addr; 4908 4909 switch (DAG.getTarget().Options.TLSSize) { 4910 default: 4911 llvm_unreachable("Unexpected TLS size"); 4912 4913 case 12: { 4914 // mrs x0, TPIDR_EL0 4915 // add x0, x0, :tprel_lo12:a 4916 SDValue Var = DAG.getTargetGlobalAddress( 4917 GV, DL, PtrVT, 0, AArch64II::MO_TLS | AArch64II::MO_PAGEOFF); 4918 return SDValue(DAG.getMachineNode(AArch64::ADDXri, DL, PtrVT, ThreadBase, 4919 Var, 4920 DAG.getTargetConstant(0, DL, MVT::i32)), 4921 0); 4922 } 4923 4924 case 24: { 4925 // mrs x0, TPIDR_EL0 4926 // add x0, x0, :tprel_hi12:a 4927 // add x0, x0, :tprel_lo12_nc:a 4928 SDValue HiVar = DAG.getTargetGlobalAddress( 4929 GV, DL, PtrVT, 0, AArch64II::MO_TLS | AArch64II::MO_HI12); 4930 SDValue LoVar = DAG.getTargetGlobalAddress( 4931 GV, DL, PtrVT, 0, 4932 AArch64II::MO_TLS | AArch64II::MO_PAGEOFF | AArch64II::MO_NC); 4933 Addr = SDValue(DAG.getMachineNode(AArch64::ADDXri, DL, PtrVT, ThreadBase, 4934 HiVar, 4935 DAG.getTargetConstant(0, DL, MVT::i32)), 4936 0); 4937 return SDValue(DAG.getMachineNode(AArch64::ADDXri, DL, PtrVT, Addr, 4938 LoVar, 4939 DAG.getTargetConstant(0, DL, MVT::i32)), 4940 0); 4941 } 4942 4943 case 32: { 4944 // mrs x1, TPIDR_EL0 4945 // movz x0, #:tprel_g1:a 4946 // movk x0, #:tprel_g0_nc:a 4947 // add x0, x1, x0 4948 SDValue HiVar = DAG.getTargetGlobalAddress( 4949 GV, DL, PtrVT, 0, AArch64II::MO_TLS | AArch64II::MO_G1); 4950 SDValue LoVar = DAG.getTargetGlobalAddress( 4951 GV, DL, PtrVT, 0, 4952 AArch64II::MO_TLS | AArch64II::MO_G0 | AArch64II::MO_NC); 4953 TPOff = SDValue(DAG.getMachineNode(AArch64::MOVZXi, DL, PtrVT, HiVar, 4954 DAG.getTargetConstant(16, DL, MVT::i32)), 4955 0); 4956 TPOff = SDValue(DAG.getMachineNode(AArch64::MOVKXi, DL, PtrVT, TPOff, LoVar, 4957 DAG.getTargetConstant(0, DL, MVT::i32)), 4958 0); 4959 return DAG.getNode(ISD::ADD, DL, PtrVT, ThreadBase, TPOff); 4960 } 4961 4962 case 48: { 4963 // mrs x1, TPIDR_EL0 4964 // movz x0, #:tprel_g2:a 4965 // movk x0, #:tprel_g1_nc:a 4966 // movk x0, #:tprel_g0_nc:a 4967 // add x0, x1, x0 4968 SDValue HiVar = DAG.getTargetGlobalAddress( 4969 GV, DL, PtrVT, 0, AArch64II::MO_TLS | AArch64II::MO_G2); 4970 SDValue MiVar = DAG.getTargetGlobalAddress( 4971 GV, DL, PtrVT, 0, 4972 AArch64II::MO_TLS | AArch64II::MO_G1 | AArch64II::MO_NC); 4973 SDValue LoVar = DAG.getTargetGlobalAddress( 4974 GV, DL, PtrVT, 0, 4975 AArch64II::MO_TLS | AArch64II::MO_G0 | AArch64II::MO_NC); 4976 TPOff = SDValue(DAG.getMachineNode(AArch64::MOVZXi, DL, PtrVT, HiVar, 4977 DAG.getTargetConstant(32, DL, MVT::i32)), 4978 0); 4979 TPOff = SDValue(DAG.getMachineNode(AArch64::MOVKXi, DL, PtrVT, TPOff, MiVar, 4980 DAG.getTargetConstant(16, DL, MVT::i32)), 4981 0); 4982 TPOff = SDValue(DAG.getMachineNode(AArch64::MOVKXi, DL, PtrVT, TPOff, LoVar, 4983 DAG.getTargetConstant(0, DL, MVT::i32)), 4984 0); 4985 return DAG.getNode(ISD::ADD, DL, PtrVT, ThreadBase, TPOff); 4986 } 4987 } 4988 } 4989 4990 /// When accessing thread-local variables under either the general-dynamic or 4991 /// local-dynamic system, we make a "TLS-descriptor" call. The variable will 4992 /// have a descriptor, accessible via a PC-relative ADRP, and whose first entry 4993 /// is a function pointer to carry out the resolution. 4994 /// 4995 /// The sequence is: 4996 /// adrp x0, :tlsdesc:var 4997 /// ldr x1, [x0, #:tlsdesc_lo12:var] 4998 /// add x0, x0, #:tlsdesc_lo12:var 4999 /// .tlsdesccall var 5000 /// blr x1 5001 /// (TPIDR_EL0 offset now in x0) 5002 /// 5003 /// The above sequence must be produced unscheduled, to enable the linker to 5004 /// optimize/relax this sequence. 5005 /// Therefore, a pseudo-instruction (TLSDESC_CALLSEQ) is used to represent the 5006 /// above sequence, and expanded really late in the compilation flow, to ensure 5007 /// the sequence is produced as per above. 5008 SDValue AArch64TargetLowering::LowerELFTLSDescCallSeq(SDValue SymAddr, 5009 const SDLoc &DL, 5010 SelectionDAG &DAG) const { 5011 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 5012 5013 SDValue Chain = DAG.getEntryNode(); 5014 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue); 5015 5016 Chain = 5017 DAG.getNode(AArch64ISD::TLSDESC_CALLSEQ, DL, NodeTys, {Chain, SymAddr}); 5018 SDValue Glue = Chain.getValue(1); 5019 5020 return DAG.getCopyFromReg(Chain, DL, AArch64::X0, PtrVT, Glue); 5021 } 5022 5023 SDValue 5024 AArch64TargetLowering::LowerELFGlobalTLSAddress(SDValue Op, 5025 SelectionDAG &DAG) const { 5026 assert(Subtarget->isTargetELF() && "This function expects an ELF target"); 5027 5028 const GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op); 5029 5030 TLSModel::Model Model = getTargetMachine().getTLSModel(GA->getGlobal()); 5031 5032 if (!EnableAArch64ELFLocalDynamicTLSGeneration) { 5033 if (Model == TLSModel::LocalDynamic) 5034 Model = TLSModel::GeneralDynamic; 5035 } 5036 5037 if (getTargetMachine().getCodeModel() == CodeModel::Large && 5038 Model != TLSModel::LocalExec) 5039 report_fatal_error("ELF TLS only supported in small memory model or " 5040 "in local exec TLS model"); 5041 // Different choices can be made for the maximum size of the TLS area for a 5042 // module. For the small address model, the default TLS size is 16MiB and the 5043 // maximum TLS size is 4GiB. 5044 // FIXME: add tiny and large code model support for TLS access models other 5045 // than local exec. We currently generate the same code as small for tiny, 5046 // which may be larger than needed. 5047 5048 SDValue TPOff; 5049 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 5050 SDLoc DL(Op); 5051 const GlobalValue *GV = GA->getGlobal(); 5052 5053 SDValue ThreadBase = DAG.getNode(AArch64ISD::THREAD_POINTER, DL, PtrVT); 5054 5055 if (Model == TLSModel::LocalExec) { 5056 return LowerELFTLSLocalExec(GV, ThreadBase, DL, DAG); 5057 } else if (Model == TLSModel::InitialExec) { 5058 TPOff = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, AArch64II::MO_TLS); 5059 TPOff = DAG.getNode(AArch64ISD::LOADgot, DL, PtrVT, TPOff); 5060 } else if (Model == TLSModel::LocalDynamic) { 5061 // Local-dynamic accesses proceed in two phases. A general-dynamic TLS 5062 // descriptor call against the special symbol _TLS_MODULE_BASE_ to calculate 5063 // the beginning of the module's TLS region, followed by a DTPREL offset 5064 // calculation. 5065 5066 // These accesses will need deduplicating if there's more than one. 5067 AArch64FunctionInfo *MFI = 5068 DAG.getMachineFunction().getInfo<AArch64FunctionInfo>(); 5069 MFI->incNumLocalDynamicTLSAccesses(); 5070 5071 // The call needs a relocation too for linker relaxation. It doesn't make 5072 // sense to call it MO_PAGE or MO_PAGEOFF though so we need another copy of 5073 // the address. 5074 SDValue SymAddr = DAG.getTargetExternalSymbol("_TLS_MODULE_BASE_", PtrVT, 5075 AArch64II::MO_TLS); 5076 5077 // Now we can calculate the offset from TPIDR_EL0 to this module's 5078 // thread-local area. 5079 TPOff = LowerELFTLSDescCallSeq(SymAddr, DL, DAG); 5080 5081 // Now use :dtprel_whatever: operations to calculate this variable's offset 5082 // in its thread-storage area. 5083 SDValue HiVar = DAG.getTargetGlobalAddress( 5084 GV, DL, MVT::i64, 0, AArch64II::MO_TLS | AArch64II::MO_HI12); 5085 SDValue LoVar = DAG.getTargetGlobalAddress( 5086 GV, DL, MVT::i64, 0, 5087 AArch64II::MO_TLS | AArch64II::MO_PAGEOFF | AArch64II::MO_NC); 5088 5089 TPOff = SDValue(DAG.getMachineNode(AArch64::ADDXri, DL, PtrVT, TPOff, HiVar, 5090 DAG.getTargetConstant(0, DL, MVT::i32)), 5091 0); 5092 TPOff = SDValue(DAG.getMachineNode(AArch64::ADDXri, DL, PtrVT, TPOff, LoVar, 5093 DAG.getTargetConstant(0, DL, MVT::i32)), 5094 0); 5095 } else if (Model == TLSModel::GeneralDynamic) { 5096 // The call needs a relocation too for linker relaxation. It doesn't make 5097 // sense to call it MO_PAGE or MO_PAGEOFF though so we need another copy of 5098 // the address. 5099 SDValue SymAddr = 5100 DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, AArch64II::MO_TLS); 5101 5102 // Finally we can make a call to calculate the offset from tpidr_el0. 5103 TPOff = LowerELFTLSDescCallSeq(SymAddr, DL, DAG); 5104 } else 5105 llvm_unreachable("Unsupported ELF TLS access model"); 5106 5107 return DAG.getNode(ISD::ADD, DL, PtrVT, ThreadBase, TPOff); 5108 } 5109 5110 SDValue 5111 AArch64TargetLowering::LowerWindowsGlobalTLSAddress(SDValue Op, 5112 SelectionDAG &DAG) const { 5113 assert(Subtarget->isTargetWindows() && "Windows specific TLS lowering"); 5114 5115 SDValue Chain = DAG.getEntryNode(); 5116 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 5117 SDLoc DL(Op); 5118 5119 SDValue TEB = DAG.getRegister(AArch64::X18, MVT::i64); 5120 5121 // Load the ThreadLocalStoragePointer from the TEB 5122 // A pointer to the TLS array is located at offset 0x58 from the TEB. 5123 SDValue TLSArray = 5124 DAG.getNode(ISD::ADD, DL, PtrVT, TEB, DAG.getIntPtrConstant(0x58, DL)); 5125 TLSArray = DAG.getLoad(PtrVT, DL, Chain, TLSArray, MachinePointerInfo()); 5126 Chain = TLSArray.getValue(1); 5127 5128 // Load the TLS index from the C runtime; 5129 // This does the same as getAddr(), but without having a GlobalAddressSDNode. 5130 // This also does the same as LOADgot, but using a generic i32 load, 5131 // while LOADgot only loads i64. 5132 SDValue TLSIndexHi = 5133 DAG.getTargetExternalSymbol("_tls_index", PtrVT, AArch64II::MO_PAGE); 5134 SDValue TLSIndexLo = DAG.getTargetExternalSymbol( 5135 "_tls_index", PtrVT, AArch64II::MO_PAGEOFF | AArch64II::MO_NC); 5136 SDValue ADRP = DAG.getNode(AArch64ISD::ADRP, DL, PtrVT, TLSIndexHi); 5137 SDValue TLSIndex = 5138 DAG.getNode(AArch64ISD::ADDlow, DL, PtrVT, ADRP, TLSIndexLo); 5139 TLSIndex = DAG.getLoad(MVT::i32, DL, Chain, TLSIndex, MachinePointerInfo()); 5140 Chain = TLSIndex.getValue(1); 5141 5142 // The pointer to the thread's TLS data area is at the TLS Index scaled by 8 5143 // offset into the TLSArray. 5144 TLSIndex = DAG.getNode(ISD::ZERO_EXTEND, DL, PtrVT, TLSIndex); 5145 SDValue Slot = DAG.getNode(ISD::SHL, DL, PtrVT, TLSIndex, 5146 DAG.getConstant(3, DL, PtrVT)); 5147 SDValue TLS = DAG.getLoad(PtrVT, DL, Chain, 5148 DAG.getNode(ISD::ADD, DL, PtrVT, TLSArray, Slot), 5149 MachinePointerInfo()); 5150 Chain = TLS.getValue(1); 5151 5152 const GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op); 5153 const GlobalValue *GV = GA->getGlobal(); 5154 SDValue TGAHi = DAG.getTargetGlobalAddress( 5155 GV, DL, PtrVT, 0, AArch64II::MO_TLS | AArch64II::MO_HI12); 5156 SDValue TGALo = DAG.getTargetGlobalAddress( 5157 GV, DL, PtrVT, 0, 5158 AArch64II::MO_TLS | AArch64II::MO_PAGEOFF | AArch64II::MO_NC); 5159 5160 // Add the offset from the start of the .tls section (section base). 5161 SDValue Addr = 5162 SDValue(DAG.getMachineNode(AArch64::ADDXri, DL, PtrVT, TLS, TGAHi, 5163 DAG.getTargetConstant(0, DL, MVT::i32)), 5164 0); 5165 Addr = DAG.getNode(AArch64ISD::ADDlow, DL, PtrVT, Addr, TGALo); 5166 return Addr; 5167 } 5168 5169 SDValue AArch64TargetLowering::LowerGlobalTLSAddress(SDValue Op, 5170 SelectionDAG &DAG) const { 5171 const GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op); 5172 if (DAG.getTarget().useEmulatedTLS()) 5173 return LowerToTLSEmulatedModel(GA, DAG); 5174 5175 if (Subtarget->isTargetDarwin()) 5176 return LowerDarwinGlobalTLSAddress(Op, DAG); 5177 if (Subtarget->isTargetELF()) 5178 return LowerELFGlobalTLSAddress(Op, DAG); 5179 if (Subtarget->isTargetWindows()) 5180 return LowerWindowsGlobalTLSAddress(Op, DAG); 5181 5182 llvm_unreachable("Unexpected platform trying to use TLS"); 5183 } 5184 5185 SDValue AArch64TargetLowering::LowerBR_CC(SDValue Op, SelectionDAG &DAG) const { 5186 SDValue Chain = Op.getOperand(0); 5187 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(1))->get(); 5188 SDValue LHS = Op.getOperand(2); 5189 SDValue RHS = Op.getOperand(3); 5190 SDValue Dest = Op.getOperand(4); 5191 SDLoc dl(Op); 5192 5193 MachineFunction &MF = DAG.getMachineFunction(); 5194 // Speculation tracking/SLH assumes that optimized TB(N)Z/CB(N)Z instructions 5195 // will not be produced, as they are conditional branch instructions that do 5196 // not set flags. 5197 bool ProduceNonFlagSettingCondBr = 5198 !MF.getFunction().hasFnAttribute(Attribute::SpeculativeLoadHardening); 5199 5200 // Handle f128 first, since lowering it will result in comparing the return 5201 // value of a libcall against zero, which is just what the rest of LowerBR_CC 5202 // is expecting to deal with. 5203 if (LHS.getValueType() == MVT::f128) { 5204 softenSetCCOperands(DAG, MVT::f128, LHS, RHS, CC, dl, LHS, RHS); 5205 5206 // If softenSetCCOperands returned a scalar, we need to compare the result 5207 // against zero to select between true and false values. 5208 if (!RHS.getNode()) { 5209 RHS = DAG.getConstant(0, dl, LHS.getValueType()); 5210 CC = ISD::SETNE; 5211 } 5212 } 5213 5214 // Optimize {s|u}{add|sub|mul}.with.overflow feeding into a branch 5215 // instruction. 5216 if (ISD::isOverflowIntrOpRes(LHS) && isOneConstant(RHS) && 5217 (CC == ISD::SETEQ || CC == ISD::SETNE)) { 5218 // Only lower legal XALUO ops. 5219 if (!DAG.getTargetLoweringInfo().isTypeLegal(LHS->getValueType(0))) 5220 return SDValue(); 5221 5222 // The actual operation with overflow check. 5223 AArch64CC::CondCode OFCC; 5224 SDValue Value, Overflow; 5225 std::tie(Value, Overflow) = getAArch64XALUOOp(OFCC, LHS.getValue(0), DAG); 5226 5227 if (CC == ISD::SETNE) 5228 OFCC = getInvertedCondCode(OFCC); 5229 SDValue CCVal = DAG.getConstant(OFCC, dl, MVT::i32); 5230 5231 return DAG.getNode(AArch64ISD::BRCOND, dl, MVT::Other, Chain, Dest, CCVal, 5232 Overflow); 5233 } 5234 5235 if (LHS.getValueType().isInteger()) { 5236 assert((LHS.getValueType() == RHS.getValueType()) && 5237 (LHS.getValueType() == MVT::i32 || LHS.getValueType() == MVT::i64)); 5238 5239 // If the RHS of the comparison is zero, we can potentially fold this 5240 // to a specialized branch. 5241 const ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS); 5242 if (RHSC && RHSC->getZExtValue() == 0 && ProduceNonFlagSettingCondBr) { 5243 if (CC == ISD::SETEQ) { 5244 // See if we can use a TBZ to fold in an AND as well. 5245 // TBZ has a smaller branch displacement than CBZ. If the offset is 5246 // out of bounds, a late MI-layer pass rewrites branches. 5247 // 403.gcc is an example that hits this case. 5248 if (LHS.getOpcode() == ISD::AND && 5249 isa<ConstantSDNode>(LHS.getOperand(1)) && 5250 isPowerOf2_64(LHS.getConstantOperandVal(1))) { 5251 SDValue Test = LHS.getOperand(0); 5252 uint64_t Mask = LHS.getConstantOperandVal(1); 5253 return DAG.getNode(AArch64ISD::TBZ, dl, MVT::Other, Chain, Test, 5254 DAG.getConstant(Log2_64(Mask), dl, MVT::i64), 5255 Dest); 5256 } 5257 5258 return DAG.getNode(AArch64ISD::CBZ, dl, MVT::Other, Chain, LHS, Dest); 5259 } else if (CC == ISD::SETNE) { 5260 // See if we can use a TBZ to fold in an AND as well. 5261 // TBZ has a smaller branch displacement than CBZ. If the offset is 5262 // out of bounds, a late MI-layer pass rewrites branches. 5263 // 403.gcc is an example that hits this case. 5264 if (LHS.getOpcode() == ISD::AND && 5265 isa<ConstantSDNode>(LHS.getOperand(1)) && 5266 isPowerOf2_64(LHS.getConstantOperandVal(1))) { 5267 SDValue Test = LHS.getOperand(0); 5268 uint64_t Mask = LHS.getConstantOperandVal(1); 5269 return DAG.getNode(AArch64ISD::TBNZ, dl, MVT::Other, Chain, Test, 5270 DAG.getConstant(Log2_64(Mask), dl, MVT::i64), 5271 Dest); 5272 } 5273 5274 return DAG.getNode(AArch64ISD::CBNZ, dl, MVT::Other, Chain, LHS, Dest); 5275 } else if (CC == ISD::SETLT && LHS.getOpcode() != ISD::AND) { 5276 // Don't combine AND since emitComparison converts the AND to an ANDS 5277 // (a.k.a. TST) and the test in the test bit and branch instruction 5278 // becomes redundant. This would also increase register pressure. 5279 uint64_t Mask = LHS.getValueSizeInBits() - 1; 5280 return DAG.getNode(AArch64ISD::TBNZ, dl, MVT::Other, Chain, LHS, 5281 DAG.getConstant(Mask, dl, MVT::i64), Dest); 5282 } 5283 } 5284 if (RHSC && RHSC->getSExtValue() == -1 && CC == ISD::SETGT && 5285 LHS.getOpcode() != ISD::AND && ProduceNonFlagSettingCondBr) { 5286 // Don't combine AND since emitComparison converts the AND to an ANDS 5287 // (a.k.a. TST) and the test in the test bit and branch instruction 5288 // becomes redundant. This would also increase register pressure. 5289 uint64_t Mask = LHS.getValueSizeInBits() - 1; 5290 return DAG.getNode(AArch64ISD::TBZ, dl, MVT::Other, Chain, LHS, 5291 DAG.getConstant(Mask, dl, MVT::i64), Dest); 5292 } 5293 5294 SDValue CCVal; 5295 SDValue Cmp = getAArch64Cmp(LHS, RHS, CC, CCVal, DAG, dl); 5296 return DAG.getNode(AArch64ISD::BRCOND, dl, MVT::Other, Chain, Dest, CCVal, 5297 Cmp); 5298 } 5299 5300 assert(LHS.getValueType() == MVT::f16 || LHS.getValueType() == MVT::bf16 || 5301 LHS.getValueType() == MVT::f32 || LHS.getValueType() == MVT::f64); 5302 5303 // Unfortunately, the mapping of LLVM FP CC's onto AArch64 CC's isn't totally 5304 // clean. Some of them require two branches to implement. 5305 SDValue Cmp = emitComparison(LHS, RHS, CC, dl, DAG); 5306 AArch64CC::CondCode CC1, CC2; 5307 changeFPCCToAArch64CC(CC, CC1, CC2); 5308 SDValue CC1Val = DAG.getConstant(CC1, dl, MVT::i32); 5309 SDValue BR1 = 5310 DAG.getNode(AArch64ISD::BRCOND, dl, MVT::Other, Chain, Dest, CC1Val, Cmp); 5311 if (CC2 != AArch64CC::AL) { 5312 SDValue CC2Val = DAG.getConstant(CC2, dl, MVT::i32); 5313 return DAG.getNode(AArch64ISD::BRCOND, dl, MVT::Other, BR1, Dest, CC2Val, 5314 Cmp); 5315 } 5316 5317 return BR1; 5318 } 5319 5320 SDValue AArch64TargetLowering::LowerFCOPYSIGN(SDValue Op, 5321 SelectionDAG &DAG) const { 5322 EVT VT = Op.getValueType(); 5323 SDLoc DL(Op); 5324 5325 SDValue In1 = Op.getOperand(0); 5326 SDValue In2 = Op.getOperand(1); 5327 EVT SrcVT = In2.getValueType(); 5328 5329 if (SrcVT.bitsLT(VT)) 5330 In2 = DAG.getNode(ISD::FP_EXTEND, DL, VT, In2); 5331 else if (SrcVT.bitsGT(VT)) 5332 In2 = DAG.getNode(ISD::FP_ROUND, DL, VT, In2, DAG.getIntPtrConstant(0, DL)); 5333 5334 EVT VecVT; 5335 uint64_t EltMask; 5336 SDValue VecVal1, VecVal2; 5337 5338 auto setVecVal = [&] (int Idx) { 5339 if (!VT.isVector()) { 5340 VecVal1 = DAG.getTargetInsertSubreg(Idx, DL, VecVT, 5341 DAG.getUNDEF(VecVT), In1); 5342 VecVal2 = DAG.getTargetInsertSubreg(Idx, DL, VecVT, 5343 DAG.getUNDEF(VecVT), In2); 5344 } else { 5345 VecVal1 = DAG.getNode(ISD::BITCAST, DL, VecVT, In1); 5346 VecVal2 = DAG.getNode(ISD::BITCAST, DL, VecVT, In2); 5347 } 5348 }; 5349 5350 if (VT == MVT::f32 || VT == MVT::v2f32 || VT == MVT::v4f32) { 5351 VecVT = (VT == MVT::v2f32 ? MVT::v2i32 : MVT::v4i32); 5352 EltMask = 0x80000000ULL; 5353 setVecVal(AArch64::ssub); 5354 } else if (VT == MVT::f64 || VT == MVT::v2f64) { 5355 VecVT = MVT::v2i64; 5356 5357 // We want to materialize a mask with the high bit set, but the AdvSIMD 5358 // immediate moves cannot materialize that in a single instruction for 5359 // 64-bit elements. Instead, materialize zero and then negate it. 5360 EltMask = 0; 5361 5362 setVecVal(AArch64::dsub); 5363 } else if (VT == MVT::f16 || VT == MVT::v4f16 || VT == MVT::v8f16) { 5364 VecVT = (VT == MVT::v4f16 ? MVT::v4i16 : MVT::v8i16); 5365 EltMask = 0x8000ULL; 5366 setVecVal(AArch64::hsub); 5367 } else { 5368 llvm_unreachable("Invalid type for copysign!"); 5369 } 5370 5371 SDValue BuildVec = DAG.getConstant(EltMask, DL, VecVT); 5372 5373 // If we couldn't materialize the mask above, then the mask vector will be 5374 // the zero vector, and we need to negate it here. 5375 if (VT == MVT::f64 || VT == MVT::v2f64) { 5376 BuildVec = DAG.getNode(ISD::BITCAST, DL, MVT::v2f64, BuildVec); 5377 BuildVec = DAG.getNode(ISD::FNEG, DL, MVT::v2f64, BuildVec); 5378 BuildVec = DAG.getNode(ISD::BITCAST, DL, MVT::v2i64, BuildVec); 5379 } 5380 5381 SDValue Sel = 5382 DAG.getNode(AArch64ISD::BIT, DL, VecVT, VecVal1, VecVal2, BuildVec); 5383 5384 if (VT == MVT::f16) 5385 return DAG.getTargetExtractSubreg(AArch64::hsub, DL, VT, Sel); 5386 if (VT == MVT::f32) 5387 return DAG.getTargetExtractSubreg(AArch64::ssub, DL, VT, Sel); 5388 else if (VT == MVT::f64) 5389 return DAG.getTargetExtractSubreg(AArch64::dsub, DL, VT, Sel); 5390 else 5391 return DAG.getNode(ISD::BITCAST, DL, VT, Sel); 5392 } 5393 5394 SDValue AArch64TargetLowering::LowerCTPOP(SDValue Op, SelectionDAG &DAG) const { 5395 if (DAG.getMachineFunction().getFunction().hasFnAttribute( 5396 Attribute::NoImplicitFloat)) 5397 return SDValue(); 5398 5399 if (!Subtarget->hasNEON()) 5400 return SDValue(); 5401 5402 // While there is no integer popcount instruction, it can 5403 // be more efficiently lowered to the following sequence that uses 5404 // AdvSIMD registers/instructions as long as the copies to/from 5405 // the AdvSIMD registers are cheap. 5406 // FMOV D0, X0 // copy 64-bit int to vector, high bits zero'd 5407 // CNT V0.8B, V0.8B // 8xbyte pop-counts 5408 // ADDV B0, V0.8B // sum 8xbyte pop-counts 5409 // UMOV X0, V0.B[0] // copy byte result back to integer reg 5410 SDValue Val = Op.getOperand(0); 5411 SDLoc DL(Op); 5412 EVT VT = Op.getValueType(); 5413 5414 if (VT == MVT::i32 || VT == MVT::i64) { 5415 if (VT == MVT::i32) 5416 Val = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i64, Val); 5417 Val = DAG.getNode(ISD::BITCAST, DL, MVT::v8i8, Val); 5418 5419 SDValue CtPop = DAG.getNode(ISD::CTPOP, DL, MVT::v8i8, Val); 5420 SDValue UaddLV = DAG.getNode( 5421 ISD::INTRINSIC_WO_CHAIN, DL, MVT::i32, 5422 DAG.getConstant(Intrinsic::aarch64_neon_uaddlv, DL, MVT::i32), CtPop); 5423 5424 if (VT == MVT::i64) 5425 UaddLV = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i64, UaddLV); 5426 return UaddLV; 5427 } else if (VT == MVT::i128) { 5428 Val = DAG.getNode(ISD::BITCAST, DL, MVT::v16i8, Val); 5429 5430 SDValue CtPop = DAG.getNode(ISD::CTPOP, DL, MVT::v16i8, Val); 5431 SDValue UaddLV = DAG.getNode( 5432 ISD::INTRINSIC_WO_CHAIN, DL, MVT::i32, 5433 DAG.getConstant(Intrinsic::aarch64_neon_uaddlv, DL, MVT::i32), CtPop); 5434 5435 return DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i128, UaddLV); 5436 } 5437 5438 assert((VT == MVT::v1i64 || VT == MVT::v2i64 || VT == MVT::v2i32 || 5439 VT == MVT::v4i32 || VT == MVT::v4i16 || VT == MVT::v8i16) && 5440 "Unexpected type for custom ctpop lowering"); 5441 5442 EVT VT8Bit = VT.is64BitVector() ? MVT::v8i8 : MVT::v16i8; 5443 Val = DAG.getBitcast(VT8Bit, Val); 5444 Val = DAG.getNode(ISD::CTPOP, DL, VT8Bit, Val); 5445 5446 // Widen v8i8/v16i8 CTPOP result to VT by repeatedly widening pairwise adds. 5447 unsigned EltSize = 8; 5448 unsigned NumElts = VT.is64BitVector() ? 8 : 16; 5449 while (EltSize != VT.getScalarSizeInBits()) { 5450 EltSize *= 2; 5451 NumElts /= 2; 5452 MVT WidenVT = MVT::getVectorVT(MVT::getIntegerVT(EltSize), NumElts); 5453 Val = DAG.getNode( 5454 ISD::INTRINSIC_WO_CHAIN, DL, WidenVT, 5455 DAG.getConstant(Intrinsic::aarch64_neon_uaddlp, DL, MVT::i32), Val); 5456 } 5457 5458 return Val; 5459 } 5460 5461 SDValue AArch64TargetLowering::LowerSETCC(SDValue Op, SelectionDAG &DAG) const { 5462 5463 if (Op.getValueType().isVector()) 5464 return LowerVSETCC(Op, DAG); 5465 5466 bool IsStrict = Op->isStrictFPOpcode(); 5467 bool IsSignaling = Op.getOpcode() == ISD::STRICT_FSETCCS; 5468 unsigned OpNo = IsStrict ? 1 : 0; 5469 SDValue Chain; 5470 if (IsStrict) 5471 Chain = Op.getOperand(0); 5472 SDValue LHS = Op.getOperand(OpNo + 0); 5473 SDValue RHS = Op.getOperand(OpNo + 1); 5474 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(OpNo + 2))->get(); 5475 SDLoc dl(Op); 5476 5477 // We chose ZeroOrOneBooleanContents, so use zero and one. 5478 EVT VT = Op.getValueType(); 5479 SDValue TVal = DAG.getConstant(1, dl, VT); 5480 SDValue FVal = DAG.getConstant(0, dl, VT); 5481 5482 // Handle f128 first, since one possible outcome is a normal integer 5483 // comparison which gets picked up by the next if statement. 5484 if (LHS.getValueType() == MVT::f128) { 5485 softenSetCCOperands(DAG, MVT::f128, LHS, RHS, CC, dl, LHS, RHS, Chain, 5486 IsSignaling); 5487 5488 // If softenSetCCOperands returned a scalar, use it. 5489 if (!RHS.getNode()) { 5490 assert(LHS.getValueType() == Op.getValueType() && 5491 "Unexpected setcc expansion!"); 5492 return IsStrict ? DAG.getMergeValues({LHS, Chain}, dl) : LHS; 5493 } 5494 } 5495 5496 if (LHS.getValueType().isInteger()) { 5497 SDValue CCVal; 5498 SDValue Cmp = getAArch64Cmp( 5499 LHS, RHS, ISD::getSetCCInverse(CC, LHS.getValueType()), CCVal, DAG, dl); 5500 5501 // Note that we inverted the condition above, so we reverse the order of 5502 // the true and false operands here. This will allow the setcc to be 5503 // matched to a single CSINC instruction. 5504 SDValue Res = DAG.getNode(AArch64ISD::CSEL, dl, VT, FVal, TVal, CCVal, Cmp); 5505 return IsStrict ? DAG.getMergeValues({Res, Chain}, dl) : Res; 5506 } 5507 5508 // Now we know we're dealing with FP values. 5509 assert(LHS.getValueType() == MVT::f16 || LHS.getValueType() == MVT::f32 || 5510 LHS.getValueType() == MVT::f64); 5511 5512 // If that fails, we'll need to perform an FCMP + CSEL sequence. Go ahead 5513 // and do the comparison. 5514 SDValue Cmp; 5515 if (IsStrict) 5516 Cmp = emitStrictFPComparison(LHS, RHS, dl, DAG, Chain, IsSignaling); 5517 else 5518 Cmp = emitComparison(LHS, RHS, CC, dl, DAG); 5519 5520 AArch64CC::CondCode CC1, CC2; 5521 changeFPCCToAArch64CC(CC, CC1, CC2); 5522 SDValue Res; 5523 if (CC2 == AArch64CC::AL) { 5524 changeFPCCToAArch64CC(ISD::getSetCCInverse(CC, LHS.getValueType()), CC1, 5525 CC2); 5526 SDValue CC1Val = DAG.getConstant(CC1, dl, MVT::i32); 5527 5528 // Note that we inverted the condition above, so we reverse the order of 5529 // the true and false operands here. This will allow the setcc to be 5530 // matched to a single CSINC instruction. 5531 Res = DAG.getNode(AArch64ISD::CSEL, dl, VT, FVal, TVal, CC1Val, Cmp); 5532 } else { 5533 // Unfortunately, the mapping of LLVM FP CC's onto AArch64 CC's isn't 5534 // totally clean. Some of them require two CSELs to implement. As is in 5535 // this case, we emit the first CSEL and then emit a second using the output 5536 // of the first as the RHS. We're effectively OR'ing the two CC's together. 5537 5538 // FIXME: It would be nice if we could match the two CSELs to two CSINCs. 5539 SDValue CC1Val = DAG.getConstant(CC1, dl, MVT::i32); 5540 SDValue CS1 = 5541 DAG.getNode(AArch64ISD::CSEL, dl, VT, TVal, FVal, CC1Val, Cmp); 5542 5543 SDValue CC2Val = DAG.getConstant(CC2, dl, MVT::i32); 5544 Res = DAG.getNode(AArch64ISD::CSEL, dl, VT, TVal, CS1, CC2Val, Cmp); 5545 } 5546 return IsStrict ? DAG.getMergeValues({Res, Cmp.getValue(1)}, dl) : Res; 5547 } 5548 5549 SDValue AArch64TargetLowering::LowerSELECT_CC(ISD::CondCode CC, SDValue LHS, 5550 SDValue RHS, SDValue TVal, 5551 SDValue FVal, const SDLoc &dl, 5552 SelectionDAG &DAG) const { 5553 // Handle f128 first, because it will result in a comparison of some RTLIB 5554 // call result against zero. 5555 if (LHS.getValueType() == MVT::f128) { 5556 softenSetCCOperands(DAG, MVT::f128, LHS, RHS, CC, dl, LHS, RHS); 5557 5558 // If softenSetCCOperands returned a scalar, we need to compare the result 5559 // against zero to select between true and false values. 5560 if (!RHS.getNode()) { 5561 RHS = DAG.getConstant(0, dl, LHS.getValueType()); 5562 CC = ISD::SETNE; 5563 } 5564 } 5565 5566 // Also handle f16, for which we need to do a f32 comparison. 5567 if (LHS.getValueType() == MVT::f16 && !Subtarget->hasFullFP16()) { 5568 LHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f32, LHS); 5569 RHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f32, RHS); 5570 } 5571 5572 // Next, handle integers. 5573 if (LHS.getValueType().isInteger()) { 5574 assert((LHS.getValueType() == RHS.getValueType()) && 5575 (LHS.getValueType() == MVT::i32 || LHS.getValueType() == MVT::i64)); 5576 5577 unsigned Opcode = AArch64ISD::CSEL; 5578 5579 // If both the TVal and the FVal are constants, see if we can swap them in 5580 // order to for a CSINV or CSINC out of them. 5581 ConstantSDNode *CFVal = dyn_cast<ConstantSDNode>(FVal); 5582 ConstantSDNode *CTVal = dyn_cast<ConstantSDNode>(TVal); 5583 5584 if (CTVal && CFVal && CTVal->isAllOnesValue() && CFVal->isNullValue()) { 5585 std::swap(TVal, FVal); 5586 std::swap(CTVal, CFVal); 5587 CC = ISD::getSetCCInverse(CC, LHS.getValueType()); 5588 } else if (CTVal && CFVal && CTVal->isOne() && CFVal->isNullValue()) { 5589 std::swap(TVal, FVal); 5590 std::swap(CTVal, CFVal); 5591 CC = ISD::getSetCCInverse(CC, LHS.getValueType()); 5592 } else if (TVal.getOpcode() == ISD::XOR) { 5593 // If TVal is a NOT we want to swap TVal and FVal so that we can match 5594 // with a CSINV rather than a CSEL. 5595 if (isAllOnesConstant(TVal.getOperand(1))) { 5596 std::swap(TVal, FVal); 5597 std::swap(CTVal, CFVal); 5598 CC = ISD::getSetCCInverse(CC, LHS.getValueType()); 5599 } 5600 } else if (TVal.getOpcode() == ISD::SUB) { 5601 // If TVal is a negation (SUB from 0) we want to swap TVal and FVal so 5602 // that we can match with a CSNEG rather than a CSEL. 5603 if (isNullConstant(TVal.getOperand(0))) { 5604 std::swap(TVal, FVal); 5605 std::swap(CTVal, CFVal); 5606 CC = ISD::getSetCCInverse(CC, LHS.getValueType()); 5607 } 5608 } else if (CTVal && CFVal) { 5609 const int64_t TrueVal = CTVal->getSExtValue(); 5610 const int64_t FalseVal = CFVal->getSExtValue(); 5611 bool Swap = false; 5612 5613 // If both TVal and FVal are constants, see if FVal is the 5614 // inverse/negation/increment of TVal and generate a CSINV/CSNEG/CSINC 5615 // instead of a CSEL in that case. 5616 if (TrueVal == ~FalseVal) { 5617 Opcode = AArch64ISD::CSINV; 5618 } else if (TrueVal == -FalseVal) { 5619 Opcode = AArch64ISD::CSNEG; 5620 } else if (TVal.getValueType() == MVT::i32) { 5621 // If our operands are only 32-bit wide, make sure we use 32-bit 5622 // arithmetic for the check whether we can use CSINC. This ensures that 5623 // the addition in the check will wrap around properly in case there is 5624 // an overflow (which would not be the case if we do the check with 5625 // 64-bit arithmetic). 5626 const uint32_t TrueVal32 = CTVal->getZExtValue(); 5627 const uint32_t FalseVal32 = CFVal->getZExtValue(); 5628 5629 if ((TrueVal32 == FalseVal32 + 1) || (TrueVal32 + 1 == FalseVal32)) { 5630 Opcode = AArch64ISD::CSINC; 5631 5632 if (TrueVal32 > FalseVal32) { 5633 Swap = true; 5634 } 5635 } 5636 // 64-bit check whether we can use CSINC. 5637 } else if ((TrueVal == FalseVal + 1) || (TrueVal + 1 == FalseVal)) { 5638 Opcode = AArch64ISD::CSINC; 5639 5640 if (TrueVal > FalseVal) { 5641 Swap = true; 5642 } 5643 } 5644 5645 // Swap TVal and FVal if necessary. 5646 if (Swap) { 5647 std::swap(TVal, FVal); 5648 std::swap(CTVal, CFVal); 5649 CC = ISD::getSetCCInverse(CC, LHS.getValueType()); 5650 } 5651 5652 if (Opcode != AArch64ISD::CSEL) { 5653 // Drop FVal since we can get its value by simply inverting/negating 5654 // TVal. 5655 FVal = TVal; 5656 } 5657 } 5658 5659 // Avoid materializing a constant when possible by reusing a known value in 5660 // a register. However, don't perform this optimization if the known value 5661 // is one, zero or negative one in the case of a CSEL. We can always 5662 // materialize these values using CSINC, CSEL and CSINV with wzr/xzr as the 5663 // FVal, respectively. 5664 ConstantSDNode *RHSVal = dyn_cast<ConstantSDNode>(RHS); 5665 if (Opcode == AArch64ISD::CSEL && RHSVal && !RHSVal->isOne() && 5666 !RHSVal->isNullValue() && !RHSVal->isAllOnesValue()) { 5667 AArch64CC::CondCode AArch64CC = changeIntCCToAArch64CC(CC); 5668 // Transform "a == C ? C : x" to "a == C ? a : x" and "a != C ? x : C" to 5669 // "a != C ? x : a" to avoid materializing C. 5670 if (CTVal && CTVal == RHSVal && AArch64CC == AArch64CC::EQ) 5671 TVal = LHS; 5672 else if (CFVal && CFVal == RHSVal && AArch64CC == AArch64CC::NE) 5673 FVal = LHS; 5674 } else if (Opcode == AArch64ISD::CSNEG && RHSVal && RHSVal->isOne()) { 5675 assert (CTVal && CFVal && "Expected constant operands for CSNEG."); 5676 // Use a CSINV to transform "a == C ? 1 : -1" to "a == C ? a : -1" to 5677 // avoid materializing C. 5678 AArch64CC::CondCode AArch64CC = changeIntCCToAArch64CC(CC); 5679 if (CTVal == RHSVal && AArch64CC == AArch64CC::EQ) { 5680 Opcode = AArch64ISD::CSINV; 5681 TVal = LHS; 5682 FVal = DAG.getConstant(0, dl, FVal.getValueType()); 5683 } 5684 } 5685 5686 SDValue CCVal; 5687 SDValue Cmp = getAArch64Cmp(LHS, RHS, CC, CCVal, DAG, dl); 5688 EVT VT = TVal.getValueType(); 5689 return DAG.getNode(Opcode, dl, VT, TVal, FVal, CCVal, Cmp); 5690 } 5691 5692 // Now we know we're dealing with FP values. 5693 assert(LHS.getValueType() == MVT::f16 || LHS.getValueType() == MVT::f32 || 5694 LHS.getValueType() == MVT::f64); 5695 assert(LHS.getValueType() == RHS.getValueType()); 5696 EVT VT = TVal.getValueType(); 5697 SDValue Cmp = emitComparison(LHS, RHS, CC, dl, DAG); 5698 5699 // Unfortunately, the mapping of LLVM FP CC's onto AArch64 CC's isn't totally 5700 // clean. Some of them require two CSELs to implement. 5701 AArch64CC::CondCode CC1, CC2; 5702 changeFPCCToAArch64CC(CC, CC1, CC2); 5703 5704 if (DAG.getTarget().Options.UnsafeFPMath) { 5705 // Transform "a == 0.0 ? 0.0 : x" to "a == 0.0 ? a : x" and 5706 // "a != 0.0 ? x : 0.0" to "a != 0.0 ? x : a" to avoid materializing 0.0. 5707 ConstantFPSDNode *RHSVal = dyn_cast<ConstantFPSDNode>(RHS); 5708 if (RHSVal && RHSVal->isZero()) { 5709 ConstantFPSDNode *CFVal = dyn_cast<ConstantFPSDNode>(FVal); 5710 ConstantFPSDNode *CTVal = dyn_cast<ConstantFPSDNode>(TVal); 5711 5712 if ((CC == ISD::SETEQ || CC == ISD::SETOEQ || CC == ISD::SETUEQ) && 5713 CTVal && CTVal->isZero() && TVal.getValueType() == LHS.getValueType()) 5714 TVal = LHS; 5715 else if ((CC == ISD::SETNE || CC == ISD::SETONE || CC == ISD::SETUNE) && 5716 CFVal && CFVal->isZero() && 5717 FVal.getValueType() == LHS.getValueType()) 5718 FVal = LHS; 5719 } 5720 } 5721 5722 // Emit first, and possibly only, CSEL. 5723 SDValue CC1Val = DAG.getConstant(CC1, dl, MVT::i32); 5724 SDValue CS1 = DAG.getNode(AArch64ISD::CSEL, dl, VT, TVal, FVal, CC1Val, Cmp); 5725 5726 // If we need a second CSEL, emit it, using the output of the first as the 5727 // RHS. We're effectively OR'ing the two CC's together. 5728 if (CC2 != AArch64CC::AL) { 5729 SDValue CC2Val = DAG.getConstant(CC2, dl, MVT::i32); 5730 return DAG.getNode(AArch64ISD::CSEL, dl, VT, TVal, CS1, CC2Val, Cmp); 5731 } 5732 5733 // Otherwise, return the output of the first CSEL. 5734 return CS1; 5735 } 5736 5737 SDValue AArch64TargetLowering::LowerSELECT_CC(SDValue Op, 5738 SelectionDAG &DAG) const { 5739 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(4))->get(); 5740 SDValue LHS = Op.getOperand(0); 5741 SDValue RHS = Op.getOperand(1); 5742 SDValue TVal = Op.getOperand(2); 5743 SDValue FVal = Op.getOperand(3); 5744 SDLoc DL(Op); 5745 return LowerSELECT_CC(CC, LHS, RHS, TVal, FVal, DL, DAG); 5746 } 5747 5748 SDValue AArch64TargetLowering::LowerSELECT(SDValue Op, 5749 SelectionDAG &DAG) const { 5750 SDValue CCVal = Op->getOperand(0); 5751 SDValue TVal = Op->getOperand(1); 5752 SDValue FVal = Op->getOperand(2); 5753 SDLoc DL(Op); 5754 5755 EVT Ty = Op.getValueType(); 5756 if (Ty.isScalableVector()) { 5757 SDValue TruncCC = DAG.getNode(ISD::TRUNCATE, DL, MVT::i1, CCVal); 5758 MVT PredVT = MVT::getVectorVT(MVT::i1, Ty.getVectorElementCount()); 5759 SDValue SplatPred = DAG.getNode(ISD::SPLAT_VECTOR, DL, PredVT, TruncCC); 5760 return DAG.getNode(ISD::VSELECT, DL, Ty, SplatPred, TVal, FVal); 5761 } 5762 5763 // Optimize {s|u}{add|sub|mul}.with.overflow feeding into a select 5764 // instruction. 5765 if (ISD::isOverflowIntrOpRes(CCVal)) { 5766 // Only lower legal XALUO ops. 5767 if (!DAG.getTargetLoweringInfo().isTypeLegal(CCVal->getValueType(0))) 5768 return SDValue(); 5769 5770 AArch64CC::CondCode OFCC; 5771 SDValue Value, Overflow; 5772 std::tie(Value, Overflow) = getAArch64XALUOOp(OFCC, CCVal.getValue(0), DAG); 5773 SDValue CCVal = DAG.getConstant(OFCC, DL, MVT::i32); 5774 5775 return DAG.getNode(AArch64ISD::CSEL, DL, Op.getValueType(), TVal, FVal, 5776 CCVal, Overflow); 5777 } 5778 5779 // Lower it the same way as we would lower a SELECT_CC node. 5780 ISD::CondCode CC; 5781 SDValue LHS, RHS; 5782 if (CCVal.getOpcode() == ISD::SETCC) { 5783 LHS = CCVal.getOperand(0); 5784 RHS = CCVal.getOperand(1); 5785 CC = cast<CondCodeSDNode>(CCVal->getOperand(2))->get(); 5786 } else { 5787 LHS = CCVal; 5788 RHS = DAG.getConstant(0, DL, CCVal.getValueType()); 5789 CC = ISD::SETNE; 5790 } 5791 return LowerSELECT_CC(CC, LHS, RHS, TVal, FVal, DL, DAG); 5792 } 5793 5794 SDValue AArch64TargetLowering::LowerJumpTable(SDValue Op, 5795 SelectionDAG &DAG) const { 5796 // Jump table entries as PC relative offsets. No additional tweaking 5797 // is necessary here. Just get the address of the jump table. 5798 JumpTableSDNode *JT = cast<JumpTableSDNode>(Op); 5799 5800 if (getTargetMachine().getCodeModel() == CodeModel::Large && 5801 !Subtarget->isTargetMachO()) { 5802 return getAddrLarge(JT, DAG); 5803 } else if (getTargetMachine().getCodeModel() == CodeModel::Tiny) { 5804 return getAddrTiny(JT, DAG); 5805 } 5806 return getAddr(JT, DAG); 5807 } 5808 5809 SDValue AArch64TargetLowering::LowerBR_JT(SDValue Op, 5810 SelectionDAG &DAG) const { 5811 // Jump table entries as PC relative offsets. No additional tweaking 5812 // is necessary here. Just get the address of the jump table. 5813 SDLoc DL(Op); 5814 SDValue JT = Op.getOperand(1); 5815 SDValue Entry = Op.getOperand(2); 5816 int JTI = cast<JumpTableSDNode>(JT.getNode())->getIndex(); 5817 5818 SDNode *Dest = 5819 DAG.getMachineNode(AArch64::JumpTableDest32, DL, MVT::i64, MVT::i64, JT, 5820 Entry, DAG.getTargetJumpTable(JTI, MVT::i32)); 5821 return DAG.getNode(ISD::BRIND, DL, MVT::Other, Op.getOperand(0), 5822 SDValue(Dest, 0)); 5823 } 5824 5825 SDValue AArch64TargetLowering::LowerConstantPool(SDValue Op, 5826 SelectionDAG &DAG) const { 5827 ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op); 5828 5829 if (getTargetMachine().getCodeModel() == CodeModel::Large) { 5830 // Use the GOT for the large code model on iOS. 5831 if (Subtarget->isTargetMachO()) { 5832 return getGOT(CP, DAG); 5833 } 5834 return getAddrLarge(CP, DAG); 5835 } else if (getTargetMachine().getCodeModel() == CodeModel::Tiny) { 5836 return getAddrTiny(CP, DAG); 5837 } else { 5838 return getAddr(CP, DAG); 5839 } 5840 } 5841 5842 SDValue AArch64TargetLowering::LowerBlockAddress(SDValue Op, 5843 SelectionDAG &DAG) const { 5844 BlockAddressSDNode *BA = cast<BlockAddressSDNode>(Op); 5845 if (getTargetMachine().getCodeModel() == CodeModel::Large && 5846 !Subtarget->isTargetMachO()) { 5847 return getAddrLarge(BA, DAG); 5848 } else if (getTargetMachine().getCodeModel() == CodeModel::Tiny) { 5849 return getAddrTiny(BA, DAG); 5850 } 5851 return getAddr(BA, DAG); 5852 } 5853 5854 SDValue AArch64TargetLowering::LowerDarwin_VASTART(SDValue Op, 5855 SelectionDAG &DAG) const { 5856 AArch64FunctionInfo *FuncInfo = 5857 DAG.getMachineFunction().getInfo<AArch64FunctionInfo>(); 5858 5859 SDLoc DL(Op); 5860 SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsStackIndex(), 5861 getPointerTy(DAG.getDataLayout())); 5862 FR = DAG.getZExtOrTrunc(FR, DL, getPointerMemTy(DAG.getDataLayout())); 5863 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue(); 5864 return DAG.getStore(Op.getOperand(0), DL, FR, Op.getOperand(1), 5865 MachinePointerInfo(SV)); 5866 } 5867 5868 SDValue AArch64TargetLowering::LowerWin64_VASTART(SDValue Op, 5869 SelectionDAG &DAG) const { 5870 AArch64FunctionInfo *FuncInfo = 5871 DAG.getMachineFunction().getInfo<AArch64FunctionInfo>(); 5872 5873 SDLoc DL(Op); 5874 SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsGPRSize() > 0 5875 ? FuncInfo->getVarArgsGPRIndex() 5876 : FuncInfo->getVarArgsStackIndex(), 5877 getPointerTy(DAG.getDataLayout())); 5878 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue(); 5879 return DAG.getStore(Op.getOperand(0), DL, FR, Op.getOperand(1), 5880 MachinePointerInfo(SV)); 5881 } 5882 5883 SDValue AArch64TargetLowering::LowerAAPCS_VASTART(SDValue Op, 5884 SelectionDAG &DAG) const { 5885 // The layout of the va_list struct is specified in the AArch64 Procedure Call 5886 // Standard, section B.3. 5887 MachineFunction &MF = DAG.getMachineFunction(); 5888 AArch64FunctionInfo *FuncInfo = MF.getInfo<AArch64FunctionInfo>(); 5889 auto PtrVT = getPointerTy(DAG.getDataLayout()); 5890 SDLoc DL(Op); 5891 5892 SDValue Chain = Op.getOperand(0); 5893 SDValue VAList = Op.getOperand(1); 5894 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue(); 5895 SmallVector<SDValue, 4> MemOps; 5896 5897 // void *__stack at offset 0 5898 SDValue Stack = DAG.getFrameIndex(FuncInfo->getVarArgsStackIndex(), PtrVT); 5899 MemOps.push_back(DAG.getStore(Chain, DL, Stack, VAList, 5900 MachinePointerInfo(SV), /* Alignment = */ 8)); 5901 5902 // void *__gr_top at offset 8 5903 int GPRSize = FuncInfo->getVarArgsGPRSize(); 5904 if (GPRSize > 0) { 5905 SDValue GRTop, GRTopAddr; 5906 5907 GRTopAddr = 5908 DAG.getNode(ISD::ADD, DL, PtrVT, VAList, DAG.getConstant(8, DL, PtrVT)); 5909 5910 GRTop = DAG.getFrameIndex(FuncInfo->getVarArgsGPRIndex(), PtrVT); 5911 GRTop = DAG.getNode(ISD::ADD, DL, PtrVT, GRTop, 5912 DAG.getConstant(GPRSize, DL, PtrVT)); 5913 5914 MemOps.push_back(DAG.getStore(Chain, DL, GRTop, GRTopAddr, 5915 MachinePointerInfo(SV, 8), 5916 /* Alignment = */ 8)); 5917 } 5918 5919 // void *__vr_top at offset 16 5920 int FPRSize = FuncInfo->getVarArgsFPRSize(); 5921 if (FPRSize > 0) { 5922 SDValue VRTop, VRTopAddr; 5923 VRTopAddr = DAG.getNode(ISD::ADD, DL, PtrVT, VAList, 5924 DAG.getConstant(16, DL, PtrVT)); 5925 5926 VRTop = DAG.getFrameIndex(FuncInfo->getVarArgsFPRIndex(), PtrVT); 5927 VRTop = DAG.getNode(ISD::ADD, DL, PtrVT, VRTop, 5928 DAG.getConstant(FPRSize, DL, PtrVT)); 5929 5930 MemOps.push_back(DAG.getStore(Chain, DL, VRTop, VRTopAddr, 5931 MachinePointerInfo(SV, 16), 5932 /* Alignment = */ 8)); 5933 } 5934 5935 // int __gr_offs at offset 24 5936 SDValue GROffsAddr = 5937 DAG.getNode(ISD::ADD, DL, PtrVT, VAList, DAG.getConstant(24, DL, PtrVT)); 5938 MemOps.push_back(DAG.getStore( 5939 Chain, DL, DAG.getConstant(-GPRSize, DL, MVT::i32), GROffsAddr, 5940 MachinePointerInfo(SV, 24), /* Alignment = */ 4)); 5941 5942 // int __vr_offs at offset 28 5943 SDValue VROffsAddr = 5944 DAG.getNode(ISD::ADD, DL, PtrVT, VAList, DAG.getConstant(28, DL, PtrVT)); 5945 MemOps.push_back(DAG.getStore( 5946 Chain, DL, DAG.getConstant(-FPRSize, DL, MVT::i32), VROffsAddr, 5947 MachinePointerInfo(SV, 28), /* Alignment = */ 4)); 5948 5949 return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, MemOps); 5950 } 5951 5952 SDValue AArch64TargetLowering::LowerVASTART(SDValue Op, 5953 SelectionDAG &DAG) const { 5954 MachineFunction &MF = DAG.getMachineFunction(); 5955 5956 if (Subtarget->isCallingConvWin64(MF.getFunction().getCallingConv())) 5957 return LowerWin64_VASTART(Op, DAG); 5958 else if (Subtarget->isTargetDarwin()) 5959 return LowerDarwin_VASTART(Op, DAG); 5960 else 5961 return LowerAAPCS_VASTART(Op, DAG); 5962 } 5963 5964 SDValue AArch64TargetLowering::LowerVACOPY(SDValue Op, 5965 SelectionDAG &DAG) const { 5966 // AAPCS has three pointers and two ints (= 32 bytes), Darwin has single 5967 // pointer. 5968 SDLoc DL(Op); 5969 unsigned PtrSize = Subtarget->isTargetILP32() ? 4 : 8; 5970 unsigned VaListSize = (Subtarget->isTargetDarwin() || 5971 Subtarget->isTargetWindows()) ? PtrSize : 32; 5972 const Value *DestSV = cast<SrcValueSDNode>(Op.getOperand(3))->getValue(); 5973 const Value *SrcSV = cast<SrcValueSDNode>(Op.getOperand(4))->getValue(); 5974 5975 return DAG.getMemcpy(Op.getOperand(0), DL, Op.getOperand(1), Op.getOperand(2), 5976 DAG.getConstant(VaListSize, DL, MVT::i32), 5977 Align(PtrSize), false, false, false, 5978 MachinePointerInfo(DestSV), MachinePointerInfo(SrcSV)); 5979 } 5980 5981 SDValue AArch64TargetLowering::LowerVAARG(SDValue Op, SelectionDAG &DAG) const { 5982 assert(Subtarget->isTargetDarwin() && 5983 "automatic va_arg instruction only works on Darwin"); 5984 5985 const Value *V = cast<SrcValueSDNode>(Op.getOperand(2))->getValue(); 5986 EVT VT = Op.getValueType(); 5987 SDLoc DL(Op); 5988 SDValue Chain = Op.getOperand(0); 5989 SDValue Addr = Op.getOperand(1); 5990 unsigned Align = Op.getConstantOperandVal(3); 5991 unsigned MinSlotSize = Subtarget->isTargetILP32() ? 4 : 8; 5992 auto PtrVT = getPointerTy(DAG.getDataLayout()); 5993 auto PtrMemVT = getPointerMemTy(DAG.getDataLayout()); 5994 SDValue VAList = 5995 DAG.getLoad(PtrMemVT, DL, Chain, Addr, MachinePointerInfo(V)); 5996 Chain = VAList.getValue(1); 5997 VAList = DAG.getZExtOrTrunc(VAList, DL, PtrVT); 5998 5999 if (Align > MinSlotSize) { 6000 assert(((Align & (Align - 1)) == 0) && "Expected Align to be a power of 2"); 6001 VAList = DAG.getNode(ISD::ADD, DL, PtrVT, VAList, 6002 DAG.getConstant(Align - 1, DL, PtrVT)); 6003 VAList = DAG.getNode(ISD::AND, DL, PtrVT, VAList, 6004 DAG.getConstant(-(int64_t)Align, DL, PtrVT)); 6005 } 6006 6007 Type *ArgTy = VT.getTypeForEVT(*DAG.getContext()); 6008 unsigned ArgSize = DAG.getDataLayout().getTypeAllocSize(ArgTy); 6009 6010 // Scalar integer and FP values smaller than 64 bits are implicitly extended 6011 // up to 64 bits. At the very least, we have to increase the striding of the 6012 // vaargs list to match this, and for FP values we need to introduce 6013 // FP_ROUND nodes as well. 6014 if (VT.isInteger() && !VT.isVector()) 6015 ArgSize = std::max(ArgSize, MinSlotSize); 6016 bool NeedFPTrunc = false; 6017 if (VT.isFloatingPoint() && !VT.isVector() && VT != MVT::f64) { 6018 ArgSize = 8; 6019 NeedFPTrunc = true; 6020 } 6021 6022 // Increment the pointer, VAList, to the next vaarg 6023 SDValue VANext = DAG.getNode(ISD::ADD, DL, PtrVT, VAList, 6024 DAG.getConstant(ArgSize, DL, PtrVT)); 6025 VANext = DAG.getZExtOrTrunc(VANext, DL, PtrMemVT); 6026 6027 // Store the incremented VAList to the legalized pointer 6028 SDValue APStore = 6029 DAG.getStore(Chain, DL, VANext, Addr, MachinePointerInfo(V)); 6030 6031 // Load the actual argument out of the pointer VAList 6032 if (NeedFPTrunc) { 6033 // Load the value as an f64. 6034 SDValue WideFP = 6035 DAG.getLoad(MVT::f64, DL, APStore, VAList, MachinePointerInfo()); 6036 // Round the value down to an f32. 6037 SDValue NarrowFP = DAG.getNode(ISD::FP_ROUND, DL, VT, WideFP.getValue(0), 6038 DAG.getIntPtrConstant(1, DL)); 6039 SDValue Ops[] = { NarrowFP, WideFP.getValue(1) }; 6040 // Merge the rounded value with the chain output of the load. 6041 return DAG.getMergeValues(Ops, DL); 6042 } 6043 6044 return DAG.getLoad(VT, DL, APStore, VAList, MachinePointerInfo()); 6045 } 6046 6047 SDValue AArch64TargetLowering::LowerFRAMEADDR(SDValue Op, 6048 SelectionDAG &DAG) const { 6049 MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo(); 6050 MFI.setFrameAddressIsTaken(true); 6051 6052 EVT VT = Op.getValueType(); 6053 SDLoc DL(Op); 6054 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue(); 6055 SDValue FrameAddr = 6056 DAG.getCopyFromReg(DAG.getEntryNode(), DL, AArch64::FP, MVT::i64); 6057 while (Depth--) 6058 FrameAddr = DAG.getLoad(VT, DL, DAG.getEntryNode(), FrameAddr, 6059 MachinePointerInfo()); 6060 6061 if (Subtarget->isTargetILP32()) 6062 FrameAddr = DAG.getNode(ISD::AssertZext, DL, MVT::i64, FrameAddr, 6063 DAG.getValueType(VT)); 6064 6065 return FrameAddr; 6066 } 6067 6068 SDValue AArch64TargetLowering::LowerSPONENTRY(SDValue Op, 6069 SelectionDAG &DAG) const { 6070 MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo(); 6071 6072 EVT VT = getPointerTy(DAG.getDataLayout()); 6073 SDLoc DL(Op); 6074 int FI = MFI.CreateFixedObject(4, 0, false); 6075 return DAG.getFrameIndex(FI, VT); 6076 } 6077 6078 #define GET_REGISTER_MATCHER 6079 #include "AArch64GenAsmMatcher.inc" 6080 6081 // FIXME? Maybe this could be a TableGen attribute on some registers and 6082 // this table could be generated automatically from RegInfo. 6083 Register AArch64TargetLowering:: 6084 getRegisterByName(const char* RegName, LLT VT, const MachineFunction &MF) const { 6085 Register Reg = MatchRegisterName(RegName); 6086 if (AArch64::X1 <= Reg && Reg <= AArch64::X28) { 6087 const MCRegisterInfo *MRI = Subtarget->getRegisterInfo(); 6088 unsigned DwarfRegNum = MRI->getDwarfRegNum(Reg, false); 6089 if (!Subtarget->isXRegisterReserved(DwarfRegNum)) 6090 Reg = 0; 6091 } 6092 if (Reg) 6093 return Reg; 6094 report_fatal_error(Twine("Invalid register name \"" 6095 + StringRef(RegName) + "\".")); 6096 } 6097 6098 SDValue AArch64TargetLowering::LowerADDROFRETURNADDR(SDValue Op, 6099 SelectionDAG &DAG) const { 6100 DAG.getMachineFunction().getFrameInfo().setFrameAddressIsTaken(true); 6101 6102 EVT VT = Op.getValueType(); 6103 SDLoc DL(Op); 6104 6105 SDValue FrameAddr = 6106 DAG.getCopyFromReg(DAG.getEntryNode(), DL, AArch64::FP, VT); 6107 SDValue Offset = DAG.getConstant(8, DL, getPointerTy(DAG.getDataLayout())); 6108 6109 return DAG.getNode(ISD::ADD, DL, VT, FrameAddr, Offset); 6110 } 6111 6112 SDValue AArch64TargetLowering::LowerRETURNADDR(SDValue Op, 6113 SelectionDAG &DAG) const { 6114 MachineFunction &MF = DAG.getMachineFunction(); 6115 MachineFrameInfo &MFI = MF.getFrameInfo(); 6116 MFI.setReturnAddressIsTaken(true); 6117 6118 EVT VT = Op.getValueType(); 6119 SDLoc DL(Op); 6120 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue(); 6121 if (Depth) { 6122 SDValue FrameAddr = LowerFRAMEADDR(Op, DAG); 6123 SDValue Offset = DAG.getConstant(8, DL, getPointerTy(DAG.getDataLayout())); 6124 return DAG.getLoad(VT, DL, DAG.getEntryNode(), 6125 DAG.getNode(ISD::ADD, DL, VT, FrameAddr, Offset), 6126 MachinePointerInfo()); 6127 } 6128 6129 // Return LR, which contains the return address. Mark it an implicit live-in. 6130 unsigned Reg = MF.addLiveIn(AArch64::LR, &AArch64::GPR64RegClass); 6131 return DAG.getCopyFromReg(DAG.getEntryNode(), DL, Reg, VT); 6132 } 6133 6134 /// LowerShiftRightParts - Lower SRA_PARTS, which returns two 6135 /// i64 values and take a 2 x i64 value to shift plus a shift amount. 6136 SDValue AArch64TargetLowering::LowerShiftRightParts(SDValue Op, 6137 SelectionDAG &DAG) const { 6138 assert(Op.getNumOperands() == 3 && "Not a double-shift!"); 6139 EVT VT = Op.getValueType(); 6140 unsigned VTBits = VT.getSizeInBits(); 6141 SDLoc dl(Op); 6142 SDValue ShOpLo = Op.getOperand(0); 6143 SDValue ShOpHi = Op.getOperand(1); 6144 SDValue ShAmt = Op.getOperand(2); 6145 unsigned Opc = (Op.getOpcode() == ISD::SRA_PARTS) ? ISD::SRA : ISD::SRL; 6146 6147 assert(Op.getOpcode() == ISD::SRA_PARTS || Op.getOpcode() == ISD::SRL_PARTS); 6148 6149 SDValue RevShAmt = DAG.getNode(ISD::SUB, dl, MVT::i64, 6150 DAG.getConstant(VTBits, dl, MVT::i64), ShAmt); 6151 SDValue HiBitsForLo = DAG.getNode(ISD::SHL, dl, VT, ShOpHi, RevShAmt); 6152 6153 // Unfortunately, if ShAmt == 0, we just calculated "(SHL ShOpHi, 64)" which 6154 // is "undef". We wanted 0, so CSEL it directly. 6155 SDValue Cmp = emitComparison(ShAmt, DAG.getConstant(0, dl, MVT::i64), 6156 ISD::SETEQ, dl, DAG); 6157 SDValue CCVal = DAG.getConstant(AArch64CC::EQ, dl, MVT::i32); 6158 HiBitsForLo = 6159 DAG.getNode(AArch64ISD::CSEL, dl, VT, DAG.getConstant(0, dl, MVT::i64), 6160 HiBitsForLo, CCVal, Cmp); 6161 6162 SDValue ExtraShAmt = DAG.getNode(ISD::SUB, dl, MVT::i64, ShAmt, 6163 DAG.getConstant(VTBits, dl, MVT::i64)); 6164 6165 SDValue LoBitsForLo = DAG.getNode(ISD::SRL, dl, VT, ShOpLo, ShAmt); 6166 SDValue LoForNormalShift = 6167 DAG.getNode(ISD::OR, dl, VT, LoBitsForLo, HiBitsForLo); 6168 6169 Cmp = emitComparison(ExtraShAmt, DAG.getConstant(0, dl, MVT::i64), ISD::SETGE, 6170 dl, DAG); 6171 CCVal = DAG.getConstant(AArch64CC::GE, dl, MVT::i32); 6172 SDValue LoForBigShift = DAG.getNode(Opc, dl, VT, ShOpHi, ExtraShAmt); 6173 SDValue Lo = DAG.getNode(AArch64ISD::CSEL, dl, VT, LoForBigShift, 6174 LoForNormalShift, CCVal, Cmp); 6175 6176 // AArch64 shifts larger than the register width are wrapped rather than 6177 // clamped, so we can't just emit "hi >> x". 6178 SDValue HiForNormalShift = DAG.getNode(Opc, dl, VT, ShOpHi, ShAmt); 6179 SDValue HiForBigShift = 6180 Opc == ISD::SRA 6181 ? DAG.getNode(Opc, dl, VT, ShOpHi, 6182 DAG.getConstant(VTBits - 1, dl, MVT::i64)) 6183 : DAG.getConstant(0, dl, VT); 6184 SDValue Hi = DAG.getNode(AArch64ISD::CSEL, dl, VT, HiForBigShift, 6185 HiForNormalShift, CCVal, Cmp); 6186 6187 SDValue Ops[2] = { Lo, Hi }; 6188 return DAG.getMergeValues(Ops, dl); 6189 } 6190 6191 /// LowerShiftLeftParts - Lower SHL_PARTS, which returns two 6192 /// i64 values and take a 2 x i64 value to shift plus a shift amount. 6193 SDValue AArch64TargetLowering::LowerShiftLeftParts(SDValue Op, 6194 SelectionDAG &DAG) const { 6195 assert(Op.getNumOperands() == 3 && "Not a double-shift!"); 6196 EVT VT = Op.getValueType(); 6197 unsigned VTBits = VT.getSizeInBits(); 6198 SDLoc dl(Op); 6199 SDValue ShOpLo = Op.getOperand(0); 6200 SDValue ShOpHi = Op.getOperand(1); 6201 SDValue ShAmt = Op.getOperand(2); 6202 6203 assert(Op.getOpcode() == ISD::SHL_PARTS); 6204 SDValue RevShAmt = DAG.getNode(ISD::SUB, dl, MVT::i64, 6205 DAG.getConstant(VTBits, dl, MVT::i64), ShAmt); 6206 SDValue LoBitsForHi = DAG.getNode(ISD::SRL, dl, VT, ShOpLo, RevShAmt); 6207 6208 // Unfortunately, if ShAmt == 0, we just calculated "(SRL ShOpLo, 64)" which 6209 // is "undef". We wanted 0, so CSEL it directly. 6210 SDValue Cmp = emitComparison(ShAmt, DAG.getConstant(0, dl, MVT::i64), 6211 ISD::SETEQ, dl, DAG); 6212 SDValue CCVal = DAG.getConstant(AArch64CC::EQ, dl, MVT::i32); 6213 LoBitsForHi = 6214 DAG.getNode(AArch64ISD::CSEL, dl, VT, DAG.getConstant(0, dl, MVT::i64), 6215 LoBitsForHi, CCVal, Cmp); 6216 6217 SDValue ExtraShAmt = DAG.getNode(ISD::SUB, dl, MVT::i64, ShAmt, 6218 DAG.getConstant(VTBits, dl, MVT::i64)); 6219 SDValue HiBitsForHi = DAG.getNode(ISD::SHL, dl, VT, ShOpHi, ShAmt); 6220 SDValue HiForNormalShift = 6221 DAG.getNode(ISD::OR, dl, VT, LoBitsForHi, HiBitsForHi); 6222 6223 SDValue HiForBigShift = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ExtraShAmt); 6224 6225 Cmp = emitComparison(ExtraShAmt, DAG.getConstant(0, dl, MVT::i64), ISD::SETGE, 6226 dl, DAG); 6227 CCVal = DAG.getConstant(AArch64CC::GE, dl, MVT::i32); 6228 SDValue Hi = DAG.getNode(AArch64ISD::CSEL, dl, VT, HiForBigShift, 6229 HiForNormalShift, CCVal, Cmp); 6230 6231 // AArch64 shifts of larger than register sizes are wrapped rather than 6232 // clamped, so we can't just emit "lo << a" if a is too big. 6233 SDValue LoForBigShift = DAG.getConstant(0, dl, VT); 6234 SDValue LoForNormalShift = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ShAmt); 6235 SDValue Lo = DAG.getNode(AArch64ISD::CSEL, dl, VT, LoForBigShift, 6236 LoForNormalShift, CCVal, Cmp); 6237 6238 SDValue Ops[2] = { Lo, Hi }; 6239 return DAG.getMergeValues(Ops, dl); 6240 } 6241 6242 bool AArch64TargetLowering::isOffsetFoldingLegal( 6243 const GlobalAddressSDNode *GA) const { 6244 // Offsets are folded in the DAG combine rather than here so that we can 6245 // intelligently choose an offset based on the uses. 6246 return false; 6247 } 6248 6249 bool AArch64TargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT, 6250 bool OptForSize) const { 6251 bool IsLegal = false; 6252 // We can materialize #0.0 as fmov $Rd, XZR for 64-bit, 32-bit cases, and 6253 // 16-bit case when target has full fp16 support. 6254 // FIXME: We should be able to handle f128 as well with a clever lowering. 6255 const APInt ImmInt = Imm.bitcastToAPInt(); 6256 if (VT == MVT::f64) 6257 IsLegal = AArch64_AM::getFP64Imm(ImmInt) != -1 || Imm.isPosZero(); 6258 else if (VT == MVT::f32) 6259 IsLegal = AArch64_AM::getFP32Imm(ImmInt) != -1 || Imm.isPosZero(); 6260 else if (VT == MVT::f16 && Subtarget->hasFullFP16()) 6261 IsLegal = AArch64_AM::getFP16Imm(ImmInt) != -1 || Imm.isPosZero(); 6262 // TODO: fmov h0, w0 is also legal, however on't have an isel pattern to 6263 // generate that fmov. 6264 6265 // If we can not materialize in immediate field for fmov, check if the 6266 // value can be encoded as the immediate operand of a logical instruction. 6267 // The immediate value will be created with either MOVZ, MOVN, or ORR. 6268 if (!IsLegal && (VT == MVT::f64 || VT == MVT::f32)) { 6269 // The cost is actually exactly the same for mov+fmov vs. adrp+ldr; 6270 // however the mov+fmov sequence is always better because of the reduced 6271 // cache pressure. The timings are still the same if you consider 6272 // movw+movk+fmov vs. adrp+ldr (it's one instruction longer, but the 6273 // movw+movk is fused). So we limit up to 2 instrdduction at most. 6274 SmallVector<AArch64_IMM::ImmInsnModel, 4> Insn; 6275 AArch64_IMM::expandMOVImm(ImmInt.getZExtValue(), VT.getSizeInBits(), 6276 Insn); 6277 unsigned Limit = (OptForSize ? 1 : (Subtarget->hasFuseLiterals() ? 5 : 2)); 6278 IsLegal = Insn.size() <= Limit; 6279 } 6280 6281 LLVM_DEBUG(dbgs() << (IsLegal ? "Legal " : "Illegal ") << VT.getEVTString() 6282 << " imm value: "; Imm.dump();); 6283 return IsLegal; 6284 } 6285 6286 //===----------------------------------------------------------------------===// 6287 // AArch64 Optimization Hooks 6288 //===----------------------------------------------------------------------===// 6289 6290 static SDValue getEstimate(const AArch64Subtarget *ST, unsigned Opcode, 6291 SDValue Operand, SelectionDAG &DAG, 6292 int &ExtraSteps) { 6293 EVT VT = Operand.getValueType(); 6294 if (ST->hasNEON() && 6295 (VT == MVT::f64 || VT == MVT::v1f64 || VT == MVT::v2f64 || 6296 VT == MVT::f32 || VT == MVT::v1f32 || 6297 VT == MVT::v2f32 || VT == MVT::v4f32)) { 6298 if (ExtraSteps == TargetLoweringBase::ReciprocalEstimate::Unspecified) 6299 // For the reciprocal estimates, convergence is quadratic, so the number 6300 // of digits is doubled after each iteration. In ARMv8, the accuracy of 6301 // the initial estimate is 2^-8. Thus the number of extra steps to refine 6302 // the result for float (23 mantissa bits) is 2 and for double (52 6303 // mantissa bits) is 3. 6304 ExtraSteps = VT.getScalarType() == MVT::f64 ? 3 : 2; 6305 6306 return DAG.getNode(Opcode, SDLoc(Operand), VT, Operand); 6307 } 6308 6309 return SDValue(); 6310 } 6311 6312 SDValue AArch64TargetLowering::getSqrtEstimate(SDValue Operand, 6313 SelectionDAG &DAG, int Enabled, 6314 int &ExtraSteps, 6315 bool &UseOneConst, 6316 bool Reciprocal) const { 6317 if (Enabled == ReciprocalEstimate::Enabled || 6318 (Enabled == ReciprocalEstimate::Unspecified && Subtarget->useRSqrt())) 6319 if (SDValue Estimate = getEstimate(Subtarget, AArch64ISD::FRSQRTE, Operand, 6320 DAG, ExtraSteps)) { 6321 SDLoc DL(Operand); 6322 EVT VT = Operand.getValueType(); 6323 6324 SDNodeFlags Flags; 6325 Flags.setAllowReassociation(true); 6326 6327 // Newton reciprocal square root iteration: E * 0.5 * (3 - X * E^2) 6328 // AArch64 reciprocal square root iteration instruction: 0.5 * (3 - M * N) 6329 for (int i = ExtraSteps; i > 0; --i) { 6330 SDValue Step = DAG.getNode(ISD::FMUL, DL, VT, Estimate, Estimate, 6331 Flags); 6332 Step = DAG.getNode(AArch64ISD::FRSQRTS, DL, VT, Operand, Step, Flags); 6333 Estimate = DAG.getNode(ISD::FMUL, DL, VT, Estimate, Step, Flags); 6334 } 6335 if (!Reciprocal) { 6336 EVT CCVT = getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), 6337 VT); 6338 SDValue FPZero = DAG.getConstantFP(0.0, DL, VT); 6339 SDValue Eq = DAG.getSetCC(DL, CCVT, Operand, FPZero, ISD::SETEQ); 6340 6341 Estimate = DAG.getNode(ISD::FMUL, DL, VT, Operand, Estimate, Flags); 6342 // Correct the result if the operand is 0.0. 6343 Estimate = DAG.getNode(VT.isVector() ? ISD::VSELECT : ISD::SELECT, DL, 6344 VT, Eq, Operand, Estimate); 6345 } 6346 6347 ExtraSteps = 0; 6348 return Estimate; 6349 } 6350 6351 return SDValue(); 6352 } 6353 6354 SDValue AArch64TargetLowering::getRecipEstimate(SDValue Operand, 6355 SelectionDAG &DAG, int Enabled, 6356 int &ExtraSteps) const { 6357 if (Enabled == ReciprocalEstimate::Enabled) 6358 if (SDValue Estimate = getEstimate(Subtarget, AArch64ISD::FRECPE, Operand, 6359 DAG, ExtraSteps)) { 6360 SDLoc DL(Operand); 6361 EVT VT = Operand.getValueType(); 6362 6363 SDNodeFlags Flags; 6364 Flags.setAllowReassociation(true); 6365 6366 // Newton reciprocal iteration: E * (2 - X * E) 6367 // AArch64 reciprocal iteration instruction: (2 - M * N) 6368 for (int i = ExtraSteps; i > 0; --i) { 6369 SDValue Step = DAG.getNode(AArch64ISD::FRECPS, DL, VT, Operand, 6370 Estimate, Flags); 6371 Estimate = DAG.getNode(ISD::FMUL, DL, VT, Estimate, Step, Flags); 6372 } 6373 6374 ExtraSteps = 0; 6375 return Estimate; 6376 } 6377 6378 return SDValue(); 6379 } 6380 6381 //===----------------------------------------------------------------------===// 6382 // AArch64 Inline Assembly Support 6383 //===----------------------------------------------------------------------===// 6384 6385 // Table of Constraints 6386 // TODO: This is the current set of constraints supported by ARM for the 6387 // compiler, not all of them may make sense. 6388 // 6389 // r - A general register 6390 // w - An FP/SIMD register of some size in the range v0-v31 6391 // x - An FP/SIMD register of some size in the range v0-v15 6392 // I - Constant that can be used with an ADD instruction 6393 // J - Constant that can be used with a SUB instruction 6394 // K - Constant that can be used with a 32-bit logical instruction 6395 // L - Constant that can be used with a 64-bit logical instruction 6396 // M - Constant that can be used as a 32-bit MOV immediate 6397 // N - Constant that can be used as a 64-bit MOV immediate 6398 // Q - A memory reference with base register and no offset 6399 // S - A symbolic address 6400 // Y - Floating point constant zero 6401 // Z - Integer constant zero 6402 // 6403 // Note that general register operands will be output using their 64-bit x 6404 // register name, whatever the size of the variable, unless the asm operand 6405 // is prefixed by the %w modifier. Floating-point and SIMD register operands 6406 // will be output with the v prefix unless prefixed by the %b, %h, %s, %d or 6407 // %q modifier. 6408 const char *AArch64TargetLowering::LowerXConstraint(EVT ConstraintVT) const { 6409 // At this point, we have to lower this constraint to something else, so we 6410 // lower it to an "r" or "w". However, by doing this we will force the result 6411 // to be in register, while the X constraint is much more permissive. 6412 // 6413 // Although we are correct (we are free to emit anything, without 6414 // constraints), we might break use cases that would expect us to be more 6415 // efficient and emit something else. 6416 if (!Subtarget->hasFPARMv8()) 6417 return "r"; 6418 6419 if (ConstraintVT.isFloatingPoint()) 6420 return "w"; 6421 6422 if (ConstraintVT.isVector() && 6423 (ConstraintVT.getSizeInBits() == 64 || 6424 ConstraintVT.getSizeInBits() == 128)) 6425 return "w"; 6426 6427 return "r"; 6428 } 6429 6430 enum PredicateConstraint { 6431 Upl, 6432 Upa, 6433 Invalid 6434 }; 6435 6436 static PredicateConstraint parsePredicateConstraint(StringRef Constraint) { 6437 PredicateConstraint P = PredicateConstraint::Invalid; 6438 if (Constraint == "Upa") 6439 P = PredicateConstraint::Upa; 6440 if (Constraint == "Upl") 6441 P = PredicateConstraint::Upl; 6442 return P; 6443 } 6444 6445 /// getConstraintType - Given a constraint letter, return the type of 6446 /// constraint it is for this target. 6447 AArch64TargetLowering::ConstraintType 6448 AArch64TargetLowering::getConstraintType(StringRef Constraint) const { 6449 if (Constraint.size() == 1) { 6450 switch (Constraint[0]) { 6451 default: 6452 break; 6453 case 'x': 6454 case 'w': 6455 case 'y': 6456 return C_RegisterClass; 6457 // An address with a single base register. Due to the way we 6458 // currently handle addresses it is the same as 'r'. 6459 case 'Q': 6460 return C_Memory; 6461 case 'I': 6462 case 'J': 6463 case 'K': 6464 case 'L': 6465 case 'M': 6466 case 'N': 6467 case 'Y': 6468 case 'Z': 6469 return C_Immediate; 6470 case 'z': 6471 case 'S': // A symbolic address 6472 return C_Other; 6473 } 6474 } else if (parsePredicateConstraint(Constraint) != 6475 PredicateConstraint::Invalid) 6476 return C_RegisterClass; 6477 return TargetLowering::getConstraintType(Constraint); 6478 } 6479 6480 /// Examine constraint type and operand type and determine a weight value. 6481 /// This object must already have been set up with the operand type 6482 /// and the current alternative constraint selected. 6483 TargetLowering::ConstraintWeight 6484 AArch64TargetLowering::getSingleConstraintMatchWeight( 6485 AsmOperandInfo &info, const char *constraint) const { 6486 ConstraintWeight weight = CW_Invalid; 6487 Value *CallOperandVal = info.CallOperandVal; 6488 // If we don't have a value, we can't do a match, 6489 // but allow it at the lowest weight. 6490 if (!CallOperandVal) 6491 return CW_Default; 6492 Type *type = CallOperandVal->getType(); 6493 // Look at the constraint type. 6494 switch (*constraint) { 6495 default: 6496 weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint); 6497 break; 6498 case 'x': 6499 case 'w': 6500 case 'y': 6501 if (type->isFloatingPointTy() || type->isVectorTy()) 6502 weight = CW_Register; 6503 break; 6504 case 'z': 6505 weight = CW_Constant; 6506 break; 6507 case 'U': 6508 if (parsePredicateConstraint(constraint) != PredicateConstraint::Invalid) 6509 weight = CW_Register; 6510 break; 6511 } 6512 return weight; 6513 } 6514 6515 std::pair<unsigned, const TargetRegisterClass *> 6516 AArch64TargetLowering::getRegForInlineAsmConstraint( 6517 const TargetRegisterInfo *TRI, StringRef Constraint, MVT VT) const { 6518 if (Constraint.size() == 1) { 6519 switch (Constraint[0]) { 6520 case 'r': 6521 if (VT.getSizeInBits() == 64) 6522 return std::make_pair(0U, &AArch64::GPR64commonRegClass); 6523 return std::make_pair(0U, &AArch64::GPR32commonRegClass); 6524 case 'w': 6525 if (!Subtarget->hasFPARMv8()) 6526 break; 6527 if (VT.isScalableVector()) 6528 return std::make_pair(0U, &AArch64::ZPRRegClass); 6529 if (VT.getSizeInBits() == 16) 6530 return std::make_pair(0U, &AArch64::FPR16RegClass); 6531 if (VT.getSizeInBits() == 32) 6532 return std::make_pair(0U, &AArch64::FPR32RegClass); 6533 if (VT.getSizeInBits() == 64) 6534 return std::make_pair(0U, &AArch64::FPR64RegClass); 6535 if (VT.getSizeInBits() == 128) 6536 return std::make_pair(0U, &AArch64::FPR128RegClass); 6537 break; 6538 // The instructions that this constraint is designed for can 6539 // only take 128-bit registers so just use that regclass. 6540 case 'x': 6541 if (!Subtarget->hasFPARMv8()) 6542 break; 6543 if (VT.isScalableVector()) 6544 return std::make_pair(0U, &AArch64::ZPR_4bRegClass); 6545 if (VT.getSizeInBits() == 128) 6546 return std::make_pair(0U, &AArch64::FPR128_loRegClass); 6547 break; 6548 case 'y': 6549 if (!Subtarget->hasFPARMv8()) 6550 break; 6551 if (VT.isScalableVector()) 6552 return std::make_pair(0U, &AArch64::ZPR_3bRegClass); 6553 break; 6554 } 6555 } else { 6556 PredicateConstraint PC = parsePredicateConstraint(Constraint); 6557 if (PC != PredicateConstraint::Invalid) { 6558 assert(VT.isScalableVector()); 6559 bool restricted = (PC == PredicateConstraint::Upl); 6560 return restricted ? std::make_pair(0U, &AArch64::PPR_3bRegClass) 6561 : std::make_pair(0U, &AArch64::PPRRegClass); 6562 } 6563 } 6564 if (StringRef("{cc}").equals_lower(Constraint)) 6565 return std::make_pair(unsigned(AArch64::NZCV), &AArch64::CCRRegClass); 6566 6567 // Use the default implementation in TargetLowering to convert the register 6568 // constraint into a member of a register class. 6569 std::pair<unsigned, const TargetRegisterClass *> Res; 6570 Res = TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT); 6571 6572 // Not found as a standard register? 6573 if (!Res.second) { 6574 unsigned Size = Constraint.size(); 6575 if ((Size == 4 || Size == 5) && Constraint[0] == '{' && 6576 tolower(Constraint[1]) == 'v' && Constraint[Size - 1] == '}') { 6577 int RegNo; 6578 bool Failed = Constraint.slice(2, Size - 1).getAsInteger(10, RegNo); 6579 if (!Failed && RegNo >= 0 && RegNo <= 31) { 6580 // v0 - v31 are aliases of q0 - q31 or d0 - d31 depending on size. 6581 // By default we'll emit v0-v31 for this unless there's a modifier where 6582 // we'll emit the correct register as well. 6583 if (VT != MVT::Other && VT.getSizeInBits() == 64) { 6584 Res.first = AArch64::FPR64RegClass.getRegister(RegNo); 6585 Res.second = &AArch64::FPR64RegClass; 6586 } else { 6587 Res.first = AArch64::FPR128RegClass.getRegister(RegNo); 6588 Res.second = &AArch64::FPR128RegClass; 6589 } 6590 } 6591 } 6592 } 6593 6594 if (Res.second && !Subtarget->hasFPARMv8() && 6595 !AArch64::GPR32allRegClass.hasSubClassEq(Res.second) && 6596 !AArch64::GPR64allRegClass.hasSubClassEq(Res.second)) 6597 return std::make_pair(0U, nullptr); 6598 6599 return Res; 6600 } 6601 6602 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops 6603 /// vector. If it is invalid, don't add anything to Ops. 6604 void AArch64TargetLowering::LowerAsmOperandForConstraint( 6605 SDValue Op, std::string &Constraint, std::vector<SDValue> &Ops, 6606 SelectionDAG &DAG) const { 6607 SDValue Result; 6608 6609 // Currently only support length 1 constraints. 6610 if (Constraint.length() != 1) 6611 return; 6612 6613 char ConstraintLetter = Constraint[0]; 6614 switch (ConstraintLetter) { 6615 default: 6616 break; 6617 6618 // This set of constraints deal with valid constants for various instructions. 6619 // Validate and return a target constant for them if we can. 6620 case 'z': { 6621 // 'z' maps to xzr or wzr so it needs an input of 0. 6622 if (!isNullConstant(Op)) 6623 return; 6624 6625 if (Op.getValueType() == MVT::i64) 6626 Result = DAG.getRegister(AArch64::XZR, MVT::i64); 6627 else 6628 Result = DAG.getRegister(AArch64::WZR, MVT::i32); 6629 break; 6630 } 6631 case 'S': { 6632 // An absolute symbolic address or label reference. 6633 if (const GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(Op)) { 6634 Result = DAG.getTargetGlobalAddress(GA->getGlobal(), SDLoc(Op), 6635 GA->getValueType(0)); 6636 } else if (const BlockAddressSDNode *BA = 6637 dyn_cast<BlockAddressSDNode>(Op)) { 6638 Result = 6639 DAG.getTargetBlockAddress(BA->getBlockAddress(), BA->getValueType(0)); 6640 } else if (const ExternalSymbolSDNode *ES = 6641 dyn_cast<ExternalSymbolSDNode>(Op)) { 6642 Result = 6643 DAG.getTargetExternalSymbol(ES->getSymbol(), ES->getValueType(0)); 6644 } else 6645 return; 6646 break; 6647 } 6648 6649 case 'I': 6650 case 'J': 6651 case 'K': 6652 case 'L': 6653 case 'M': 6654 case 'N': 6655 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op); 6656 if (!C) 6657 return; 6658 6659 // Grab the value and do some validation. 6660 uint64_t CVal = C->getZExtValue(); 6661 switch (ConstraintLetter) { 6662 // The I constraint applies only to simple ADD or SUB immediate operands: 6663 // i.e. 0 to 4095 with optional shift by 12 6664 // The J constraint applies only to ADD or SUB immediates that would be 6665 // valid when negated, i.e. if [an add pattern] were to be output as a SUB 6666 // instruction [or vice versa], in other words -1 to -4095 with optional 6667 // left shift by 12. 6668 case 'I': 6669 if (isUInt<12>(CVal) || isShiftedUInt<12, 12>(CVal)) 6670 break; 6671 return; 6672 case 'J': { 6673 uint64_t NVal = -C->getSExtValue(); 6674 if (isUInt<12>(NVal) || isShiftedUInt<12, 12>(NVal)) { 6675 CVal = C->getSExtValue(); 6676 break; 6677 } 6678 return; 6679 } 6680 // The K and L constraints apply *only* to logical immediates, including 6681 // what used to be the MOVI alias for ORR (though the MOVI alias has now 6682 // been removed and MOV should be used). So these constraints have to 6683 // distinguish between bit patterns that are valid 32-bit or 64-bit 6684 // "bitmask immediates": for example 0xaaaaaaaa is a valid bimm32 (K), but 6685 // not a valid bimm64 (L) where 0xaaaaaaaaaaaaaaaa would be valid, and vice 6686 // versa. 6687 case 'K': 6688 if (AArch64_AM::isLogicalImmediate(CVal, 32)) 6689 break; 6690 return; 6691 case 'L': 6692 if (AArch64_AM::isLogicalImmediate(CVal, 64)) 6693 break; 6694 return; 6695 // The M and N constraints are a superset of K and L respectively, for use 6696 // with the MOV (immediate) alias. As well as the logical immediates they 6697 // also match 32 or 64-bit immediates that can be loaded either using a 6698 // *single* MOVZ or MOVN , such as 32-bit 0x12340000, 0x00001234, 0xffffedca 6699 // (M) or 64-bit 0x1234000000000000 (N) etc. 6700 // As a note some of this code is liberally stolen from the asm parser. 6701 case 'M': { 6702 if (!isUInt<32>(CVal)) 6703 return; 6704 if (AArch64_AM::isLogicalImmediate(CVal, 32)) 6705 break; 6706 if ((CVal & 0xFFFF) == CVal) 6707 break; 6708 if ((CVal & 0xFFFF0000ULL) == CVal) 6709 break; 6710 uint64_t NCVal = ~(uint32_t)CVal; 6711 if ((NCVal & 0xFFFFULL) == NCVal) 6712 break; 6713 if ((NCVal & 0xFFFF0000ULL) == NCVal) 6714 break; 6715 return; 6716 } 6717 case 'N': { 6718 if (AArch64_AM::isLogicalImmediate(CVal, 64)) 6719 break; 6720 if ((CVal & 0xFFFFULL) == CVal) 6721 break; 6722 if ((CVal & 0xFFFF0000ULL) == CVal) 6723 break; 6724 if ((CVal & 0xFFFF00000000ULL) == CVal) 6725 break; 6726 if ((CVal & 0xFFFF000000000000ULL) == CVal) 6727 break; 6728 uint64_t NCVal = ~CVal; 6729 if ((NCVal & 0xFFFFULL) == NCVal) 6730 break; 6731 if ((NCVal & 0xFFFF0000ULL) == NCVal) 6732 break; 6733 if ((NCVal & 0xFFFF00000000ULL) == NCVal) 6734 break; 6735 if ((NCVal & 0xFFFF000000000000ULL) == NCVal) 6736 break; 6737 return; 6738 } 6739 default: 6740 return; 6741 } 6742 6743 // All assembler immediates are 64-bit integers. 6744 Result = DAG.getTargetConstant(CVal, SDLoc(Op), MVT::i64); 6745 break; 6746 } 6747 6748 if (Result.getNode()) { 6749 Ops.push_back(Result); 6750 return; 6751 } 6752 6753 return TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG); 6754 } 6755 6756 //===----------------------------------------------------------------------===// 6757 // AArch64 Advanced SIMD Support 6758 //===----------------------------------------------------------------------===// 6759 6760 /// WidenVector - Given a value in the V64 register class, produce the 6761 /// equivalent value in the V128 register class. 6762 static SDValue WidenVector(SDValue V64Reg, SelectionDAG &DAG) { 6763 EVT VT = V64Reg.getValueType(); 6764 unsigned NarrowSize = VT.getVectorNumElements(); 6765 MVT EltTy = VT.getVectorElementType().getSimpleVT(); 6766 MVT WideTy = MVT::getVectorVT(EltTy, 2 * NarrowSize); 6767 SDLoc DL(V64Reg); 6768 6769 return DAG.getNode(ISD::INSERT_SUBVECTOR, DL, WideTy, DAG.getUNDEF(WideTy), 6770 V64Reg, DAG.getConstant(0, DL, MVT::i32)); 6771 } 6772 6773 /// getExtFactor - Determine the adjustment factor for the position when 6774 /// generating an "extract from vector registers" instruction. 6775 static unsigned getExtFactor(SDValue &V) { 6776 EVT EltType = V.getValueType().getVectorElementType(); 6777 return EltType.getSizeInBits() / 8; 6778 } 6779 6780 /// NarrowVector - Given a value in the V128 register class, produce the 6781 /// equivalent value in the V64 register class. 6782 static SDValue NarrowVector(SDValue V128Reg, SelectionDAG &DAG) { 6783 EVT VT = V128Reg.getValueType(); 6784 unsigned WideSize = VT.getVectorNumElements(); 6785 MVT EltTy = VT.getVectorElementType().getSimpleVT(); 6786 MVT NarrowTy = MVT::getVectorVT(EltTy, WideSize / 2); 6787 SDLoc DL(V128Reg); 6788 6789 return DAG.getTargetExtractSubreg(AArch64::dsub, DL, NarrowTy, V128Reg); 6790 } 6791 6792 // Gather data to see if the operation can be modelled as a 6793 // shuffle in combination with VEXTs. 6794 SDValue AArch64TargetLowering::ReconstructShuffle(SDValue Op, 6795 SelectionDAG &DAG) const { 6796 assert(Op.getOpcode() == ISD::BUILD_VECTOR && "Unknown opcode!"); 6797 LLVM_DEBUG(dbgs() << "AArch64TargetLowering::ReconstructShuffle\n"); 6798 SDLoc dl(Op); 6799 EVT VT = Op.getValueType(); 6800 unsigned NumElts = VT.getVectorNumElements(); 6801 6802 struct ShuffleSourceInfo { 6803 SDValue Vec; 6804 unsigned MinElt; 6805 unsigned MaxElt; 6806 6807 // We may insert some combination of BITCASTs and VEXT nodes to force Vec to 6808 // be compatible with the shuffle we intend to construct. As a result 6809 // ShuffleVec will be some sliding window into the original Vec. 6810 SDValue ShuffleVec; 6811 6812 // Code should guarantee that element i in Vec starts at element "WindowBase 6813 // + i * WindowScale in ShuffleVec". 6814 int WindowBase; 6815 int WindowScale; 6816 6817 ShuffleSourceInfo(SDValue Vec) 6818 : Vec(Vec), MinElt(std::numeric_limits<unsigned>::max()), MaxElt(0), 6819 ShuffleVec(Vec), WindowBase(0), WindowScale(1) {} 6820 6821 bool operator ==(SDValue OtherVec) { return Vec == OtherVec; } 6822 }; 6823 6824 // First gather all vectors used as an immediate source for this BUILD_VECTOR 6825 // node. 6826 SmallVector<ShuffleSourceInfo, 2> Sources; 6827 for (unsigned i = 0; i < NumElts; ++i) { 6828 SDValue V = Op.getOperand(i); 6829 if (V.isUndef()) 6830 continue; 6831 else if (V.getOpcode() != ISD::EXTRACT_VECTOR_ELT || 6832 !isa<ConstantSDNode>(V.getOperand(1))) { 6833 LLVM_DEBUG( 6834 dbgs() << "Reshuffle failed: " 6835 "a shuffle can only come from building a vector from " 6836 "various elements of other vectors, provided their " 6837 "indices are constant\n"); 6838 return SDValue(); 6839 } 6840 6841 // Add this element source to the list if it's not already there. 6842 SDValue SourceVec = V.getOperand(0); 6843 auto Source = find(Sources, SourceVec); 6844 if (Source == Sources.end()) 6845 Source = Sources.insert(Sources.end(), ShuffleSourceInfo(SourceVec)); 6846 6847 // Update the minimum and maximum lane number seen. 6848 unsigned EltNo = cast<ConstantSDNode>(V.getOperand(1))->getZExtValue(); 6849 Source->MinElt = std::min(Source->MinElt, EltNo); 6850 Source->MaxElt = std::max(Source->MaxElt, EltNo); 6851 } 6852 6853 if (Sources.size() > 2) { 6854 LLVM_DEBUG( 6855 dbgs() << "Reshuffle failed: currently only do something sane when at " 6856 "most two source vectors are involved\n"); 6857 return SDValue(); 6858 } 6859 6860 // Find out the smallest element size among result and two sources, and use 6861 // it as element size to build the shuffle_vector. 6862 EVT SmallestEltTy = VT.getVectorElementType(); 6863 for (auto &Source : Sources) { 6864 EVT SrcEltTy = Source.Vec.getValueType().getVectorElementType(); 6865 if (SrcEltTy.bitsLT(SmallestEltTy)) { 6866 SmallestEltTy = SrcEltTy; 6867 } 6868 } 6869 unsigned ResMultiplier = 6870 VT.getScalarSizeInBits() / SmallestEltTy.getSizeInBits(); 6871 NumElts = VT.getSizeInBits() / SmallestEltTy.getSizeInBits(); 6872 EVT ShuffleVT = EVT::getVectorVT(*DAG.getContext(), SmallestEltTy, NumElts); 6873 6874 // If the source vector is too wide or too narrow, we may nevertheless be able 6875 // to construct a compatible shuffle either by concatenating it with UNDEF or 6876 // extracting a suitable range of elements. 6877 for (auto &Src : Sources) { 6878 EVT SrcVT = Src.ShuffleVec.getValueType(); 6879 6880 if (SrcVT.getSizeInBits() == VT.getSizeInBits()) 6881 continue; 6882 6883 // This stage of the search produces a source with the same element type as 6884 // the original, but with a total width matching the BUILD_VECTOR output. 6885 EVT EltVT = SrcVT.getVectorElementType(); 6886 unsigned NumSrcElts = VT.getSizeInBits() / EltVT.getSizeInBits(); 6887 EVT DestVT = EVT::getVectorVT(*DAG.getContext(), EltVT, NumSrcElts); 6888 6889 if (SrcVT.getSizeInBits() < VT.getSizeInBits()) { 6890 assert(2 * SrcVT.getSizeInBits() == VT.getSizeInBits()); 6891 // We can pad out the smaller vector for free, so if it's part of a 6892 // shuffle... 6893 Src.ShuffleVec = 6894 DAG.getNode(ISD::CONCAT_VECTORS, dl, DestVT, Src.ShuffleVec, 6895 DAG.getUNDEF(Src.ShuffleVec.getValueType())); 6896 continue; 6897 } 6898 6899 assert(SrcVT.getSizeInBits() == 2 * VT.getSizeInBits()); 6900 6901 if (Src.MaxElt - Src.MinElt >= NumSrcElts) { 6902 LLVM_DEBUG( 6903 dbgs() << "Reshuffle failed: span too large for a VEXT to cope\n"); 6904 return SDValue(); 6905 } 6906 6907 if (Src.MinElt >= NumSrcElts) { 6908 // The extraction can just take the second half 6909 Src.ShuffleVec = 6910 DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DestVT, Src.ShuffleVec, 6911 DAG.getConstant(NumSrcElts, dl, MVT::i64)); 6912 Src.WindowBase = -NumSrcElts; 6913 } else if (Src.MaxElt < NumSrcElts) { 6914 // The extraction can just take the first half 6915 Src.ShuffleVec = 6916 DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DestVT, Src.ShuffleVec, 6917 DAG.getConstant(0, dl, MVT::i64)); 6918 } else { 6919 // An actual VEXT is needed 6920 SDValue VEXTSrc1 = 6921 DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DestVT, Src.ShuffleVec, 6922 DAG.getConstant(0, dl, MVT::i64)); 6923 SDValue VEXTSrc2 = 6924 DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DestVT, Src.ShuffleVec, 6925 DAG.getConstant(NumSrcElts, dl, MVT::i64)); 6926 unsigned Imm = Src.MinElt * getExtFactor(VEXTSrc1); 6927 6928 Src.ShuffleVec = DAG.getNode(AArch64ISD::EXT, dl, DestVT, VEXTSrc1, 6929 VEXTSrc2, 6930 DAG.getConstant(Imm, dl, MVT::i32)); 6931 Src.WindowBase = -Src.MinElt; 6932 } 6933 } 6934 6935 // Another possible incompatibility occurs from the vector element types. We 6936 // can fix this by bitcasting the source vectors to the same type we intend 6937 // for the shuffle. 6938 for (auto &Src : Sources) { 6939 EVT SrcEltTy = Src.ShuffleVec.getValueType().getVectorElementType(); 6940 if (SrcEltTy == SmallestEltTy) 6941 continue; 6942 assert(ShuffleVT.getVectorElementType() == SmallestEltTy); 6943 Src.ShuffleVec = DAG.getNode(ISD::BITCAST, dl, ShuffleVT, Src.ShuffleVec); 6944 Src.WindowScale = SrcEltTy.getSizeInBits() / SmallestEltTy.getSizeInBits(); 6945 Src.WindowBase *= Src.WindowScale; 6946 } 6947 6948 // Final sanity check before we try to actually produce a shuffle. 6949 LLVM_DEBUG(for (auto Src 6950 : Sources) 6951 assert(Src.ShuffleVec.getValueType() == ShuffleVT);); 6952 6953 // The stars all align, our next step is to produce the mask for the shuffle. 6954 SmallVector<int, 8> Mask(ShuffleVT.getVectorNumElements(), -1); 6955 int BitsPerShuffleLane = ShuffleVT.getScalarSizeInBits(); 6956 for (unsigned i = 0; i < VT.getVectorNumElements(); ++i) { 6957 SDValue Entry = Op.getOperand(i); 6958 if (Entry.isUndef()) 6959 continue; 6960 6961 auto Src = find(Sources, Entry.getOperand(0)); 6962 int EltNo = cast<ConstantSDNode>(Entry.getOperand(1))->getSExtValue(); 6963 6964 // EXTRACT_VECTOR_ELT performs an implicit any_ext; BUILD_VECTOR an implicit 6965 // trunc. So only std::min(SrcBits, DestBits) actually get defined in this 6966 // segment. 6967 EVT OrigEltTy = Entry.getOperand(0).getValueType().getVectorElementType(); 6968 int BitsDefined = 6969 std::min(OrigEltTy.getSizeInBits(), VT.getScalarSizeInBits()); 6970 int LanesDefined = BitsDefined / BitsPerShuffleLane; 6971 6972 // This source is expected to fill ResMultiplier lanes of the final shuffle, 6973 // starting at the appropriate offset. 6974 int *LaneMask = &Mask[i * ResMultiplier]; 6975 6976 int ExtractBase = EltNo * Src->WindowScale + Src->WindowBase; 6977 ExtractBase += NumElts * (Src - Sources.begin()); 6978 for (int j = 0; j < LanesDefined; ++j) 6979 LaneMask[j] = ExtractBase + j; 6980 } 6981 6982 // Final check before we try to produce nonsense... 6983 if (!isShuffleMaskLegal(Mask, ShuffleVT)) { 6984 LLVM_DEBUG(dbgs() << "Reshuffle failed: illegal shuffle mask\n"); 6985 return SDValue(); 6986 } 6987 6988 SDValue ShuffleOps[] = { DAG.getUNDEF(ShuffleVT), DAG.getUNDEF(ShuffleVT) }; 6989 for (unsigned i = 0; i < Sources.size(); ++i) 6990 ShuffleOps[i] = Sources[i].ShuffleVec; 6991 6992 SDValue Shuffle = DAG.getVectorShuffle(ShuffleVT, dl, ShuffleOps[0], 6993 ShuffleOps[1], Mask); 6994 SDValue V = DAG.getNode(ISD::BITCAST, dl, VT, Shuffle); 6995 6996 LLVM_DEBUG(dbgs() << "Reshuffle, creating node: "; Shuffle.dump(); 6997 dbgs() << "Reshuffle, creating node: "; V.dump();); 6998 6999 return V; 7000 } 7001 7002 // check if an EXT instruction can handle the shuffle mask when the 7003 // vector sources of the shuffle are the same. 7004 static bool isSingletonEXTMask(ArrayRef<int> M, EVT VT, unsigned &Imm) { 7005 unsigned NumElts = VT.getVectorNumElements(); 7006 7007 // Assume that the first shuffle index is not UNDEF. Fail if it is. 7008 if (M[0] < 0) 7009 return false; 7010 7011 Imm = M[0]; 7012 7013 // If this is a VEXT shuffle, the immediate value is the index of the first 7014 // element. The other shuffle indices must be the successive elements after 7015 // the first one. 7016 unsigned ExpectedElt = Imm; 7017 for (unsigned i = 1; i < NumElts; ++i) { 7018 // Increment the expected index. If it wraps around, just follow it 7019 // back to index zero and keep going. 7020 ++ExpectedElt; 7021 if (ExpectedElt == NumElts) 7022 ExpectedElt = 0; 7023 7024 if (M[i] < 0) 7025 continue; // ignore UNDEF indices 7026 if (ExpectedElt != static_cast<unsigned>(M[i])) 7027 return false; 7028 } 7029 7030 return true; 7031 } 7032 7033 // check if an EXT instruction can handle the shuffle mask when the 7034 // vector sources of the shuffle are different. 7035 static bool isEXTMask(ArrayRef<int> M, EVT VT, bool &ReverseEXT, 7036 unsigned &Imm) { 7037 // Look for the first non-undef element. 7038 const int *FirstRealElt = find_if(M, [](int Elt) { return Elt >= 0; }); 7039 7040 // Benefit form APInt to handle overflow when calculating expected element. 7041 unsigned NumElts = VT.getVectorNumElements(); 7042 unsigned MaskBits = APInt(32, NumElts * 2).logBase2(); 7043 APInt ExpectedElt = APInt(MaskBits, *FirstRealElt + 1); 7044 // The following shuffle indices must be the successive elements after the 7045 // first real element. 7046 const int *FirstWrongElt = std::find_if(FirstRealElt + 1, M.end(), 7047 [&](int Elt) {return Elt != ExpectedElt++ && Elt != -1;}); 7048 if (FirstWrongElt != M.end()) 7049 return false; 7050 7051 // The index of an EXT is the first element if it is not UNDEF. 7052 // Watch out for the beginning UNDEFs. The EXT index should be the expected 7053 // value of the first element. E.g. 7054 // <-1, -1, 3, ...> is treated as <1, 2, 3, ...>. 7055 // <-1, -1, 0, 1, ...> is treated as <2*NumElts-2, 2*NumElts-1, 0, 1, ...>. 7056 // ExpectedElt is the last mask index plus 1. 7057 Imm = ExpectedElt.getZExtValue(); 7058 7059 // There are two difference cases requiring to reverse input vectors. 7060 // For example, for vector <4 x i32> we have the following cases, 7061 // Case 1: shufflevector(<4 x i32>,<4 x i32>,<-1, -1, -1, 0>) 7062 // Case 2: shufflevector(<4 x i32>,<4 x i32>,<-1, -1, 7, 0>) 7063 // For both cases, we finally use mask <5, 6, 7, 0>, which requires 7064 // to reverse two input vectors. 7065 if (Imm < NumElts) 7066 ReverseEXT = true; 7067 else 7068 Imm -= NumElts; 7069 7070 return true; 7071 } 7072 7073 /// isREVMask - Check if a vector shuffle corresponds to a REV 7074 /// instruction with the specified blocksize. (The order of the elements 7075 /// within each block of the vector is reversed.) 7076 static bool isREVMask(ArrayRef<int> M, EVT VT, unsigned BlockSize) { 7077 assert((BlockSize == 16 || BlockSize == 32 || BlockSize == 64) && 7078 "Only possible block sizes for REV are: 16, 32, 64"); 7079 7080 unsigned EltSz = VT.getScalarSizeInBits(); 7081 if (EltSz == 64) 7082 return false; 7083 7084 unsigned NumElts = VT.getVectorNumElements(); 7085 unsigned BlockElts = M[0] + 1; 7086 // If the first shuffle index is UNDEF, be optimistic. 7087 if (M[0] < 0) 7088 BlockElts = BlockSize / EltSz; 7089 7090 if (BlockSize <= EltSz || BlockSize != BlockElts * EltSz) 7091 return false; 7092 7093 for (unsigned i = 0; i < NumElts; ++i) { 7094 if (M[i] < 0) 7095 continue; // ignore UNDEF indices 7096 if ((unsigned)M[i] != (i - i % BlockElts) + (BlockElts - 1 - i % BlockElts)) 7097 return false; 7098 } 7099 7100 return true; 7101 } 7102 7103 static bool isZIPMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) { 7104 unsigned NumElts = VT.getVectorNumElements(); 7105 if (NumElts % 2 != 0) 7106 return false; 7107 WhichResult = (M[0] == 0 ? 0 : 1); 7108 unsigned Idx = WhichResult * NumElts / 2; 7109 for (unsigned i = 0; i != NumElts; i += 2) { 7110 if ((M[i] >= 0 && (unsigned)M[i] != Idx) || 7111 (M[i + 1] >= 0 && (unsigned)M[i + 1] != Idx + NumElts)) 7112 return false; 7113 Idx += 1; 7114 } 7115 7116 return true; 7117 } 7118 7119 static bool isUZPMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) { 7120 unsigned NumElts = VT.getVectorNumElements(); 7121 WhichResult = (M[0] == 0 ? 0 : 1); 7122 for (unsigned i = 0; i != NumElts; ++i) { 7123 if (M[i] < 0) 7124 continue; // ignore UNDEF indices 7125 if ((unsigned)M[i] != 2 * i + WhichResult) 7126 return false; 7127 } 7128 7129 return true; 7130 } 7131 7132 static bool isTRNMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) { 7133 unsigned NumElts = VT.getVectorNumElements(); 7134 if (NumElts % 2 != 0) 7135 return false; 7136 WhichResult = (M[0] == 0 ? 0 : 1); 7137 for (unsigned i = 0; i < NumElts; i += 2) { 7138 if ((M[i] >= 0 && (unsigned)M[i] != i + WhichResult) || 7139 (M[i + 1] >= 0 && (unsigned)M[i + 1] != i + NumElts + WhichResult)) 7140 return false; 7141 } 7142 return true; 7143 } 7144 7145 /// isZIP_v_undef_Mask - Special case of isZIPMask for canonical form of 7146 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef". 7147 /// Mask is e.g., <0, 0, 1, 1> instead of <0, 4, 1, 5>. 7148 static bool isZIP_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) { 7149 unsigned NumElts = VT.getVectorNumElements(); 7150 if (NumElts % 2 != 0) 7151 return false; 7152 WhichResult = (M[0] == 0 ? 0 : 1); 7153 unsigned Idx = WhichResult * NumElts / 2; 7154 for (unsigned i = 0; i != NumElts; i += 2) { 7155 if ((M[i] >= 0 && (unsigned)M[i] != Idx) || 7156 (M[i + 1] >= 0 && (unsigned)M[i + 1] != Idx)) 7157 return false; 7158 Idx += 1; 7159 } 7160 7161 return true; 7162 } 7163 7164 /// isUZP_v_undef_Mask - Special case of isUZPMask for canonical form of 7165 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef". 7166 /// Mask is e.g., <0, 2, 0, 2> instead of <0, 2, 4, 6>, 7167 static bool isUZP_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) { 7168 unsigned Half = VT.getVectorNumElements() / 2; 7169 WhichResult = (M[0] == 0 ? 0 : 1); 7170 for (unsigned j = 0; j != 2; ++j) { 7171 unsigned Idx = WhichResult; 7172 for (unsigned i = 0; i != Half; ++i) { 7173 int MIdx = M[i + j * Half]; 7174 if (MIdx >= 0 && (unsigned)MIdx != Idx) 7175 return false; 7176 Idx += 2; 7177 } 7178 } 7179 7180 return true; 7181 } 7182 7183 /// isTRN_v_undef_Mask - Special case of isTRNMask for canonical form of 7184 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef". 7185 /// Mask is e.g., <0, 0, 2, 2> instead of <0, 4, 2, 6>. 7186 static bool isTRN_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) { 7187 unsigned NumElts = VT.getVectorNumElements(); 7188 if (NumElts % 2 != 0) 7189 return false; 7190 WhichResult = (M[0] == 0 ? 0 : 1); 7191 for (unsigned i = 0; i < NumElts; i += 2) { 7192 if ((M[i] >= 0 && (unsigned)M[i] != i + WhichResult) || 7193 (M[i + 1] >= 0 && (unsigned)M[i + 1] != i + WhichResult)) 7194 return false; 7195 } 7196 return true; 7197 } 7198 7199 static bool isINSMask(ArrayRef<int> M, int NumInputElements, 7200 bool &DstIsLeft, int &Anomaly) { 7201 if (M.size() != static_cast<size_t>(NumInputElements)) 7202 return false; 7203 7204 int NumLHSMatch = 0, NumRHSMatch = 0; 7205 int LastLHSMismatch = -1, LastRHSMismatch = -1; 7206 7207 for (int i = 0; i < NumInputElements; ++i) { 7208 if (M[i] == -1) { 7209 ++NumLHSMatch; 7210 ++NumRHSMatch; 7211 continue; 7212 } 7213 7214 if (M[i] == i) 7215 ++NumLHSMatch; 7216 else 7217 LastLHSMismatch = i; 7218 7219 if (M[i] == i + NumInputElements) 7220 ++NumRHSMatch; 7221 else 7222 LastRHSMismatch = i; 7223 } 7224 7225 if (NumLHSMatch == NumInputElements - 1) { 7226 DstIsLeft = true; 7227 Anomaly = LastLHSMismatch; 7228 return true; 7229 } else if (NumRHSMatch == NumInputElements - 1) { 7230 DstIsLeft = false; 7231 Anomaly = LastRHSMismatch; 7232 return true; 7233 } 7234 7235 return false; 7236 } 7237 7238 static bool isConcatMask(ArrayRef<int> Mask, EVT VT, bool SplitLHS) { 7239 if (VT.getSizeInBits() != 128) 7240 return false; 7241 7242 unsigned NumElts = VT.getVectorNumElements(); 7243 7244 for (int I = 0, E = NumElts / 2; I != E; I++) { 7245 if (Mask[I] != I) 7246 return false; 7247 } 7248 7249 int Offset = NumElts / 2; 7250 for (int I = NumElts / 2, E = NumElts; I != E; I++) { 7251 if (Mask[I] != I + SplitLHS * Offset) 7252 return false; 7253 } 7254 7255 return true; 7256 } 7257 7258 static SDValue tryFormConcatFromShuffle(SDValue Op, SelectionDAG &DAG) { 7259 SDLoc DL(Op); 7260 EVT VT = Op.getValueType(); 7261 SDValue V0 = Op.getOperand(0); 7262 SDValue V1 = Op.getOperand(1); 7263 ArrayRef<int> Mask = cast<ShuffleVectorSDNode>(Op)->getMask(); 7264 7265 if (VT.getVectorElementType() != V0.getValueType().getVectorElementType() || 7266 VT.getVectorElementType() != V1.getValueType().getVectorElementType()) 7267 return SDValue(); 7268 7269 bool SplitV0 = V0.getValueSizeInBits() == 128; 7270 7271 if (!isConcatMask(Mask, VT, SplitV0)) 7272 return SDValue(); 7273 7274 EVT CastVT = VT.getHalfNumVectorElementsVT(*DAG.getContext()); 7275 if (SplitV0) { 7276 V0 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, CastVT, V0, 7277 DAG.getConstant(0, DL, MVT::i64)); 7278 } 7279 if (V1.getValueSizeInBits() == 128) { 7280 V1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, CastVT, V1, 7281 DAG.getConstant(0, DL, MVT::i64)); 7282 } 7283 return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, V0, V1); 7284 } 7285 7286 /// GeneratePerfectShuffle - Given an entry in the perfect-shuffle table, emit 7287 /// the specified operations to build the shuffle. 7288 static SDValue GeneratePerfectShuffle(unsigned PFEntry, SDValue LHS, 7289 SDValue RHS, SelectionDAG &DAG, 7290 const SDLoc &dl) { 7291 unsigned OpNum = (PFEntry >> 26) & 0x0F; 7292 unsigned LHSID = (PFEntry >> 13) & ((1 << 13) - 1); 7293 unsigned RHSID = (PFEntry >> 0) & ((1 << 13) - 1); 7294 7295 enum { 7296 OP_COPY = 0, // Copy, used for things like <u,u,u,3> to say it is <0,1,2,3> 7297 OP_VREV, 7298 OP_VDUP0, 7299 OP_VDUP1, 7300 OP_VDUP2, 7301 OP_VDUP3, 7302 OP_VEXT1, 7303 OP_VEXT2, 7304 OP_VEXT3, 7305 OP_VUZPL, // VUZP, left result 7306 OP_VUZPR, // VUZP, right result 7307 OP_VZIPL, // VZIP, left result 7308 OP_VZIPR, // VZIP, right result 7309 OP_VTRNL, // VTRN, left result 7310 OP_VTRNR // VTRN, right result 7311 }; 7312 7313 if (OpNum == OP_COPY) { 7314 if (LHSID == (1 * 9 + 2) * 9 + 3) 7315 return LHS; 7316 assert(LHSID == ((4 * 9 + 5) * 9 + 6) * 9 + 7 && "Illegal OP_COPY!"); 7317 return RHS; 7318 } 7319 7320 SDValue OpLHS, OpRHS; 7321 OpLHS = GeneratePerfectShuffle(PerfectShuffleTable[LHSID], LHS, RHS, DAG, dl); 7322 OpRHS = GeneratePerfectShuffle(PerfectShuffleTable[RHSID], LHS, RHS, DAG, dl); 7323 EVT VT = OpLHS.getValueType(); 7324 7325 switch (OpNum) { 7326 default: 7327 llvm_unreachable("Unknown shuffle opcode!"); 7328 case OP_VREV: 7329 // VREV divides the vector in half and swaps within the half. 7330 if (VT.getVectorElementType() == MVT::i32 || 7331 VT.getVectorElementType() == MVT::f32) 7332 return DAG.getNode(AArch64ISD::REV64, dl, VT, OpLHS); 7333 // vrev <4 x i16> -> REV32 7334 if (VT.getVectorElementType() == MVT::i16 || 7335 VT.getVectorElementType() == MVT::f16 || 7336 VT.getVectorElementType() == MVT::bf16) 7337 return DAG.getNode(AArch64ISD::REV32, dl, VT, OpLHS); 7338 // vrev <4 x i8> -> REV16 7339 assert(VT.getVectorElementType() == MVT::i8); 7340 return DAG.getNode(AArch64ISD::REV16, dl, VT, OpLHS); 7341 case OP_VDUP0: 7342 case OP_VDUP1: 7343 case OP_VDUP2: 7344 case OP_VDUP3: { 7345 EVT EltTy = VT.getVectorElementType(); 7346 unsigned Opcode; 7347 if (EltTy == MVT::i8) 7348 Opcode = AArch64ISD::DUPLANE8; 7349 else if (EltTy == MVT::i16 || EltTy == MVT::f16 || EltTy == MVT::bf16) 7350 Opcode = AArch64ISD::DUPLANE16; 7351 else if (EltTy == MVT::i32 || EltTy == MVT::f32) 7352 Opcode = AArch64ISD::DUPLANE32; 7353 else if (EltTy == MVT::i64 || EltTy == MVT::f64) 7354 Opcode = AArch64ISD::DUPLANE64; 7355 else 7356 llvm_unreachable("Invalid vector element type?"); 7357 7358 if (VT.getSizeInBits() == 64) 7359 OpLHS = WidenVector(OpLHS, DAG); 7360 SDValue Lane = DAG.getConstant(OpNum - OP_VDUP0, dl, MVT::i64); 7361 return DAG.getNode(Opcode, dl, VT, OpLHS, Lane); 7362 } 7363 case OP_VEXT1: 7364 case OP_VEXT2: 7365 case OP_VEXT3: { 7366 unsigned Imm = (OpNum - OP_VEXT1 + 1) * getExtFactor(OpLHS); 7367 return DAG.getNode(AArch64ISD::EXT, dl, VT, OpLHS, OpRHS, 7368 DAG.getConstant(Imm, dl, MVT::i32)); 7369 } 7370 case OP_VUZPL: 7371 return DAG.getNode(AArch64ISD::UZP1, dl, DAG.getVTList(VT, VT), OpLHS, 7372 OpRHS); 7373 case OP_VUZPR: 7374 return DAG.getNode(AArch64ISD::UZP2, dl, DAG.getVTList(VT, VT), OpLHS, 7375 OpRHS); 7376 case OP_VZIPL: 7377 return DAG.getNode(AArch64ISD::ZIP1, dl, DAG.getVTList(VT, VT), OpLHS, 7378 OpRHS); 7379 case OP_VZIPR: 7380 return DAG.getNode(AArch64ISD::ZIP2, dl, DAG.getVTList(VT, VT), OpLHS, 7381 OpRHS); 7382 case OP_VTRNL: 7383 return DAG.getNode(AArch64ISD::TRN1, dl, DAG.getVTList(VT, VT), OpLHS, 7384 OpRHS); 7385 case OP_VTRNR: 7386 return DAG.getNode(AArch64ISD::TRN2, dl, DAG.getVTList(VT, VT), OpLHS, 7387 OpRHS); 7388 } 7389 } 7390 7391 static SDValue GenerateTBL(SDValue Op, ArrayRef<int> ShuffleMask, 7392 SelectionDAG &DAG) { 7393 // Check to see if we can use the TBL instruction. 7394 SDValue V1 = Op.getOperand(0); 7395 SDValue V2 = Op.getOperand(1); 7396 SDLoc DL(Op); 7397 7398 EVT EltVT = Op.getValueType().getVectorElementType(); 7399 unsigned BytesPerElt = EltVT.getSizeInBits() / 8; 7400 7401 SmallVector<SDValue, 8> TBLMask; 7402 for (int Val : ShuffleMask) { 7403 for (unsigned Byte = 0; Byte < BytesPerElt; ++Byte) { 7404 unsigned Offset = Byte + Val * BytesPerElt; 7405 TBLMask.push_back(DAG.getConstant(Offset, DL, MVT::i32)); 7406 } 7407 } 7408 7409 MVT IndexVT = MVT::v8i8; 7410 unsigned IndexLen = 8; 7411 if (Op.getValueSizeInBits() == 128) { 7412 IndexVT = MVT::v16i8; 7413 IndexLen = 16; 7414 } 7415 7416 SDValue V1Cst = DAG.getNode(ISD::BITCAST, DL, IndexVT, V1); 7417 SDValue V2Cst = DAG.getNode(ISD::BITCAST, DL, IndexVT, V2); 7418 7419 SDValue Shuffle; 7420 if (V2.getNode()->isUndef()) { 7421 if (IndexLen == 8) 7422 V1Cst = DAG.getNode(ISD::CONCAT_VECTORS, DL, MVT::v16i8, V1Cst, V1Cst); 7423 Shuffle = DAG.getNode( 7424 ISD::INTRINSIC_WO_CHAIN, DL, IndexVT, 7425 DAG.getConstant(Intrinsic::aarch64_neon_tbl1, DL, MVT::i32), V1Cst, 7426 DAG.getBuildVector(IndexVT, DL, 7427 makeArrayRef(TBLMask.data(), IndexLen))); 7428 } else { 7429 if (IndexLen == 8) { 7430 V1Cst = DAG.getNode(ISD::CONCAT_VECTORS, DL, MVT::v16i8, V1Cst, V2Cst); 7431 Shuffle = DAG.getNode( 7432 ISD::INTRINSIC_WO_CHAIN, DL, IndexVT, 7433 DAG.getConstant(Intrinsic::aarch64_neon_tbl1, DL, MVT::i32), V1Cst, 7434 DAG.getBuildVector(IndexVT, DL, 7435 makeArrayRef(TBLMask.data(), IndexLen))); 7436 } else { 7437 // FIXME: We cannot, for the moment, emit a TBL2 instruction because we 7438 // cannot currently represent the register constraints on the input 7439 // table registers. 7440 // Shuffle = DAG.getNode(AArch64ISD::TBL2, DL, IndexVT, V1Cst, V2Cst, 7441 // DAG.getBuildVector(IndexVT, DL, &TBLMask[0], 7442 // IndexLen)); 7443 Shuffle = DAG.getNode( 7444 ISD::INTRINSIC_WO_CHAIN, DL, IndexVT, 7445 DAG.getConstant(Intrinsic::aarch64_neon_tbl2, DL, MVT::i32), V1Cst, 7446 V2Cst, DAG.getBuildVector(IndexVT, DL, 7447 makeArrayRef(TBLMask.data(), IndexLen))); 7448 } 7449 } 7450 return DAG.getNode(ISD::BITCAST, DL, Op.getValueType(), Shuffle); 7451 } 7452 7453 static unsigned getDUPLANEOp(EVT EltType) { 7454 if (EltType == MVT::i8) 7455 return AArch64ISD::DUPLANE8; 7456 if (EltType == MVT::i16 || EltType == MVT::f16 || EltType == MVT::bf16) 7457 return AArch64ISD::DUPLANE16; 7458 if (EltType == MVT::i32 || EltType == MVT::f32) 7459 return AArch64ISD::DUPLANE32; 7460 if (EltType == MVT::i64 || EltType == MVT::f64) 7461 return AArch64ISD::DUPLANE64; 7462 7463 llvm_unreachable("Invalid vector element type?"); 7464 } 7465 7466 SDValue AArch64TargetLowering::LowerVECTOR_SHUFFLE(SDValue Op, 7467 SelectionDAG &DAG) const { 7468 SDLoc dl(Op); 7469 EVT VT = Op.getValueType(); 7470 7471 ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(Op.getNode()); 7472 7473 // Convert shuffles that are directly supported on NEON to target-specific 7474 // DAG nodes, instead of keeping them as shuffles and matching them again 7475 // during code selection. This is more efficient and avoids the possibility 7476 // of inconsistencies between legalization and selection. 7477 ArrayRef<int> ShuffleMask = SVN->getMask(); 7478 7479 SDValue V1 = Op.getOperand(0); 7480 SDValue V2 = Op.getOperand(1); 7481 7482 if (SVN->isSplat()) { 7483 int Lane = SVN->getSplatIndex(); 7484 // If this is undef splat, generate it via "just" vdup, if possible. 7485 if (Lane == -1) 7486 Lane = 0; 7487 7488 if (Lane == 0 && V1.getOpcode() == ISD::SCALAR_TO_VECTOR) 7489 return DAG.getNode(AArch64ISD::DUP, dl, V1.getValueType(), 7490 V1.getOperand(0)); 7491 // Test if V1 is a BUILD_VECTOR and the lane being referenced is a non- 7492 // constant. If so, we can just reference the lane's definition directly. 7493 if (V1.getOpcode() == ISD::BUILD_VECTOR && 7494 !isa<ConstantSDNode>(V1.getOperand(Lane))) 7495 return DAG.getNode(AArch64ISD::DUP, dl, VT, V1.getOperand(Lane)); 7496 7497 // Otherwise, duplicate from the lane of the input vector. 7498 unsigned Opcode = getDUPLANEOp(V1.getValueType().getVectorElementType()); 7499 7500 // Try to eliminate a bitcasted extract subvector before a DUPLANE. 7501 auto getScaledOffsetDup = [](SDValue BitCast, int &LaneC, MVT &CastVT) { 7502 // Match: dup (bitcast (extract_subv X, C)), LaneC 7503 if (BitCast.getOpcode() != ISD::BITCAST || 7504 BitCast.getOperand(0).getOpcode() != ISD::EXTRACT_SUBVECTOR) 7505 return false; 7506 7507 // The extract index must align in the destination type. That may not 7508 // happen if the bitcast is from narrow to wide type. 7509 SDValue Extract = BitCast.getOperand(0); 7510 unsigned ExtIdx = Extract.getConstantOperandVal(1); 7511 unsigned SrcEltBitWidth = Extract.getScalarValueSizeInBits(); 7512 unsigned ExtIdxInBits = ExtIdx * SrcEltBitWidth; 7513 unsigned CastedEltBitWidth = BitCast.getScalarValueSizeInBits(); 7514 if (ExtIdxInBits % CastedEltBitWidth != 0) 7515 return false; 7516 7517 // Update the lane value by offsetting with the scaled extract index. 7518 LaneC += ExtIdxInBits / CastedEltBitWidth; 7519 7520 // Determine the casted vector type of the wide vector input. 7521 // dup (bitcast (extract_subv X, C)), LaneC --> dup (bitcast X), LaneC' 7522 // Examples: 7523 // dup (bitcast (extract_subv v2f64 X, 1) to v2f32), 1 --> dup v4f32 X, 3 7524 // dup (bitcast (extract_subv v16i8 X, 8) to v4i16), 1 --> dup v8i16 X, 5 7525 unsigned SrcVecNumElts = 7526 Extract.getOperand(0).getValueSizeInBits() / CastedEltBitWidth; 7527 CastVT = MVT::getVectorVT(BitCast.getSimpleValueType().getScalarType(), 7528 SrcVecNumElts); 7529 return true; 7530 }; 7531 MVT CastVT; 7532 if (getScaledOffsetDup(V1, Lane, CastVT)) { 7533 V1 = DAG.getBitcast(CastVT, V1.getOperand(0).getOperand(0)); 7534 } else if (V1.getOpcode() == ISD::EXTRACT_SUBVECTOR) { 7535 // The lane is incremented by the index of the extract. 7536 // Example: dup v2f32 (extract v4f32 X, 2), 1 --> dup v4f32 X, 3 7537 Lane += V1.getConstantOperandVal(1); 7538 V1 = V1.getOperand(0); 7539 } else if (V1.getOpcode() == ISD::CONCAT_VECTORS) { 7540 // The lane is decremented if we are splatting from the 2nd operand. 7541 // Example: dup v4i32 (concat v2i32 X, v2i32 Y), 3 --> dup v4i32 Y, 1 7542 unsigned Idx = Lane >= (int)VT.getVectorNumElements() / 2; 7543 Lane -= Idx * VT.getVectorNumElements() / 2; 7544 V1 = WidenVector(V1.getOperand(Idx), DAG); 7545 } else if (VT.getSizeInBits() == 64) { 7546 // Widen the operand to 128-bit register with undef. 7547 V1 = WidenVector(V1, DAG); 7548 } 7549 return DAG.getNode(Opcode, dl, VT, V1, DAG.getConstant(Lane, dl, MVT::i64)); 7550 } 7551 7552 if (isREVMask(ShuffleMask, VT, 64)) 7553 return DAG.getNode(AArch64ISD::REV64, dl, V1.getValueType(), V1, V2); 7554 if (isREVMask(ShuffleMask, VT, 32)) 7555 return DAG.getNode(AArch64ISD::REV32, dl, V1.getValueType(), V1, V2); 7556 if (isREVMask(ShuffleMask, VT, 16)) 7557 return DAG.getNode(AArch64ISD::REV16, dl, V1.getValueType(), V1, V2); 7558 7559 bool ReverseEXT = false; 7560 unsigned Imm; 7561 if (isEXTMask(ShuffleMask, VT, ReverseEXT, Imm)) { 7562 if (ReverseEXT) 7563 std::swap(V1, V2); 7564 Imm *= getExtFactor(V1); 7565 return DAG.getNode(AArch64ISD::EXT, dl, V1.getValueType(), V1, V2, 7566 DAG.getConstant(Imm, dl, MVT::i32)); 7567 } else if (V2->isUndef() && isSingletonEXTMask(ShuffleMask, VT, Imm)) { 7568 Imm *= getExtFactor(V1); 7569 return DAG.getNode(AArch64ISD::EXT, dl, V1.getValueType(), V1, V1, 7570 DAG.getConstant(Imm, dl, MVT::i32)); 7571 } 7572 7573 unsigned WhichResult; 7574 if (isZIPMask(ShuffleMask, VT, WhichResult)) { 7575 unsigned Opc = (WhichResult == 0) ? AArch64ISD::ZIP1 : AArch64ISD::ZIP2; 7576 return DAG.getNode(Opc, dl, V1.getValueType(), V1, V2); 7577 } 7578 if (isUZPMask(ShuffleMask, VT, WhichResult)) { 7579 unsigned Opc = (WhichResult == 0) ? AArch64ISD::UZP1 : AArch64ISD::UZP2; 7580 return DAG.getNode(Opc, dl, V1.getValueType(), V1, V2); 7581 } 7582 if (isTRNMask(ShuffleMask, VT, WhichResult)) { 7583 unsigned Opc = (WhichResult == 0) ? AArch64ISD::TRN1 : AArch64ISD::TRN2; 7584 return DAG.getNode(Opc, dl, V1.getValueType(), V1, V2); 7585 } 7586 7587 if (isZIP_v_undef_Mask(ShuffleMask, VT, WhichResult)) { 7588 unsigned Opc = (WhichResult == 0) ? AArch64ISD::ZIP1 : AArch64ISD::ZIP2; 7589 return DAG.getNode(Opc, dl, V1.getValueType(), V1, V1); 7590 } 7591 if (isUZP_v_undef_Mask(ShuffleMask, VT, WhichResult)) { 7592 unsigned Opc = (WhichResult == 0) ? AArch64ISD::UZP1 : AArch64ISD::UZP2; 7593 return DAG.getNode(Opc, dl, V1.getValueType(), V1, V1); 7594 } 7595 if (isTRN_v_undef_Mask(ShuffleMask, VT, WhichResult)) { 7596 unsigned Opc = (WhichResult == 0) ? AArch64ISD::TRN1 : AArch64ISD::TRN2; 7597 return DAG.getNode(Opc, dl, V1.getValueType(), V1, V1); 7598 } 7599 7600 if (SDValue Concat = tryFormConcatFromShuffle(Op, DAG)) 7601 return Concat; 7602 7603 bool DstIsLeft; 7604 int Anomaly; 7605 int NumInputElements = V1.getValueType().getVectorNumElements(); 7606 if (isINSMask(ShuffleMask, NumInputElements, DstIsLeft, Anomaly)) { 7607 SDValue DstVec = DstIsLeft ? V1 : V2; 7608 SDValue DstLaneV = DAG.getConstant(Anomaly, dl, MVT::i64); 7609 7610 SDValue SrcVec = V1; 7611 int SrcLane = ShuffleMask[Anomaly]; 7612 if (SrcLane >= NumInputElements) { 7613 SrcVec = V2; 7614 SrcLane -= VT.getVectorNumElements(); 7615 } 7616 SDValue SrcLaneV = DAG.getConstant(SrcLane, dl, MVT::i64); 7617 7618 EVT ScalarVT = VT.getVectorElementType(); 7619 7620 if (ScalarVT.getSizeInBits() < 32 && ScalarVT.isInteger()) 7621 ScalarVT = MVT::i32; 7622 7623 return DAG.getNode( 7624 ISD::INSERT_VECTOR_ELT, dl, VT, DstVec, 7625 DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, ScalarVT, SrcVec, SrcLaneV), 7626 DstLaneV); 7627 } 7628 7629 // If the shuffle is not directly supported and it has 4 elements, use 7630 // the PerfectShuffle-generated table to synthesize it from other shuffles. 7631 unsigned NumElts = VT.getVectorNumElements(); 7632 if (NumElts == 4) { 7633 unsigned PFIndexes[4]; 7634 for (unsigned i = 0; i != 4; ++i) { 7635 if (ShuffleMask[i] < 0) 7636 PFIndexes[i] = 8; 7637 else 7638 PFIndexes[i] = ShuffleMask[i]; 7639 } 7640 7641 // Compute the index in the perfect shuffle table. 7642 unsigned PFTableIndex = PFIndexes[0] * 9 * 9 * 9 + PFIndexes[1] * 9 * 9 + 7643 PFIndexes[2] * 9 + PFIndexes[3]; 7644 unsigned PFEntry = PerfectShuffleTable[PFTableIndex]; 7645 unsigned Cost = (PFEntry >> 30); 7646 7647 if (Cost <= 4) 7648 return GeneratePerfectShuffle(PFEntry, V1, V2, DAG, dl); 7649 } 7650 7651 return GenerateTBL(Op, ShuffleMask, DAG); 7652 } 7653 7654 SDValue AArch64TargetLowering::LowerSPLAT_VECTOR(SDValue Op, 7655 SelectionDAG &DAG) const { 7656 SDLoc dl(Op); 7657 EVT VT = Op.getValueType(); 7658 EVT ElemVT = VT.getScalarType(); 7659 7660 SDValue SplatVal = Op.getOperand(0); 7661 7662 // Extend input splat value where needed to fit into a GPR (32b or 64b only) 7663 // FPRs don't have this restriction. 7664 switch (ElemVT.getSimpleVT().SimpleTy) { 7665 case MVT::i1: { 7666 // The only legal i1 vectors are SVE vectors, so we can use SVE-specific 7667 // lowering code. 7668 if (auto *ConstVal = dyn_cast<ConstantSDNode>(SplatVal)) { 7669 if (ConstVal->isOne()) 7670 return getPTrue(DAG, dl, VT, AArch64SVEPredPattern::all); 7671 // TODO: Add special case for constant false 7672 } 7673 // The general case of i1. There isn't any natural way to do this, 7674 // so we use some trickery with whilelo. 7675 SplatVal = DAG.getAnyExtOrTrunc(SplatVal, dl, MVT::i64); 7676 SplatVal = DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, MVT::i64, SplatVal, 7677 DAG.getValueType(MVT::i1)); 7678 SDValue ID = DAG.getTargetConstant(Intrinsic::aarch64_sve_whilelo, dl, 7679 MVT::i64); 7680 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT, ID, 7681 DAG.getConstant(0, dl, MVT::i64), SplatVal); 7682 } 7683 case MVT::i8: 7684 case MVT::i16: 7685 case MVT::i32: 7686 SplatVal = DAG.getAnyExtOrTrunc(SplatVal, dl, MVT::i32); 7687 break; 7688 case MVT::i64: 7689 SplatVal = DAG.getAnyExtOrTrunc(SplatVal, dl, MVT::i64); 7690 break; 7691 case MVT::f16: 7692 case MVT::bf16: 7693 case MVT::f32: 7694 case MVT::f64: 7695 // Fine as is 7696 break; 7697 default: 7698 report_fatal_error("Unsupported SPLAT_VECTOR input operand type"); 7699 } 7700 7701 return DAG.getNode(AArch64ISD::DUP, dl, VT, SplatVal); 7702 } 7703 7704 SDValue AArch64TargetLowering::LowerDUPQLane(SDValue Op, 7705 SelectionDAG &DAG) const { 7706 SDLoc DL(Op); 7707 7708 EVT VT = Op.getValueType(); 7709 if (!isTypeLegal(VT) || !VT.isScalableVector()) 7710 return SDValue(); 7711 7712 // Current lowering only supports the SVE-ACLE types. 7713 if (VT.getSizeInBits().getKnownMinSize() != AArch64::SVEBitsPerBlock) 7714 return SDValue(); 7715 7716 // The DUPQ operation is indepedent of element type so normalise to i64s. 7717 SDValue V = DAG.getNode(ISD::BITCAST, DL, MVT::nxv2i64, Op.getOperand(1)); 7718 SDValue Idx128 = Op.getOperand(2); 7719 7720 // DUPQ can be used when idx is in range. 7721 auto *CIdx = dyn_cast<ConstantSDNode>(Idx128); 7722 if (CIdx && (CIdx->getZExtValue() <= 3)) { 7723 SDValue CI = DAG.getTargetConstant(CIdx->getZExtValue(), DL, MVT::i64); 7724 SDNode *DUPQ = 7725 DAG.getMachineNode(AArch64::DUP_ZZI_Q, DL, MVT::nxv2i64, V, CI); 7726 return DAG.getNode(ISD::BITCAST, DL, VT, SDValue(DUPQ, 0)); 7727 } 7728 7729 // The ACLE says this must produce the same result as: 7730 // svtbl(data, svadd_x(svptrue_b64(), 7731 // svand_x(svptrue_b64(), svindex_u64(0, 1), 1), 7732 // index * 2)) 7733 SDValue One = DAG.getConstant(1, DL, MVT::i64); 7734 SDValue SplatOne = DAG.getNode(ISD::SPLAT_VECTOR, DL, MVT::nxv2i64, One); 7735 7736 // create the vector 0,1,0,1,... 7737 SDValue Zero = DAG.getConstant(0, DL, MVT::i64); 7738 SDValue SV = DAG.getNode(AArch64ISD::INDEX_VECTOR, 7739 DL, MVT::nxv2i64, Zero, One); 7740 SV = DAG.getNode(ISD::AND, DL, MVT::nxv2i64, SV, SplatOne); 7741 7742 // create the vector idx64,idx64+1,idx64,idx64+1,... 7743 SDValue Idx64 = DAG.getNode(ISD::ADD, DL, MVT::i64, Idx128, Idx128); 7744 SDValue SplatIdx64 = DAG.getNode(ISD::SPLAT_VECTOR, DL, MVT::nxv2i64, Idx64); 7745 SDValue ShuffleMask = DAG.getNode(ISD::ADD, DL, MVT::nxv2i64, SV, SplatIdx64); 7746 7747 // create the vector Val[idx64],Val[idx64+1],Val[idx64],Val[idx64+1],... 7748 SDValue TBL = DAG.getNode(AArch64ISD::TBL, DL, MVT::nxv2i64, V, ShuffleMask); 7749 return DAG.getNode(ISD::BITCAST, DL, VT, TBL); 7750 } 7751 7752 SDValue AArch64TargetLowering::LowerToPredicatedOp(SDValue Op, 7753 SelectionDAG &DAG, 7754 unsigned NewOp) const { 7755 EVT VT = Op.getValueType(); 7756 SDLoc DL(Op); 7757 7758 assert(Op.getOperand(0).getValueType().isScalableVector() && 7759 Op.getOperand(1).getValueType().isScalableVector() && 7760 "Only scalable vectors are supported"); 7761 7762 auto PredTy = 7763 VT.getVectorVT(*DAG.getContext(), MVT::i1, VT.getVectorElementCount()); 7764 SDValue Mask = getPTrue(DAG, DL, PredTy, AArch64SVEPredPattern::all); 7765 7766 SmallVector<SDValue, 4> Operands = {Mask}; 7767 Operands.append(Op->op_begin(), Op->op_end()); 7768 return DAG.getNode(NewOp, DL, VT, Operands); 7769 } 7770 7771 static bool resolveBuildVector(BuildVectorSDNode *BVN, APInt &CnstBits, 7772 APInt &UndefBits) { 7773 EVT VT = BVN->getValueType(0); 7774 APInt SplatBits, SplatUndef; 7775 unsigned SplatBitSize; 7776 bool HasAnyUndefs; 7777 if (BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs)) { 7778 unsigned NumSplats = VT.getSizeInBits() / SplatBitSize; 7779 7780 for (unsigned i = 0; i < NumSplats; ++i) { 7781 CnstBits <<= SplatBitSize; 7782 UndefBits <<= SplatBitSize; 7783 CnstBits |= SplatBits.zextOrTrunc(VT.getSizeInBits()); 7784 UndefBits |= (SplatBits ^ SplatUndef).zextOrTrunc(VT.getSizeInBits()); 7785 } 7786 7787 return true; 7788 } 7789 7790 return false; 7791 } 7792 7793 // Try 64-bit splatted SIMD immediate. 7794 static SDValue tryAdvSIMDModImm64(unsigned NewOp, SDValue Op, SelectionDAG &DAG, 7795 const APInt &Bits) { 7796 if (Bits.getHiBits(64) == Bits.getLoBits(64)) { 7797 uint64_t Value = Bits.zextOrTrunc(64).getZExtValue(); 7798 EVT VT = Op.getValueType(); 7799 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v2i64 : MVT::f64; 7800 7801 if (AArch64_AM::isAdvSIMDModImmType10(Value)) { 7802 Value = AArch64_AM::encodeAdvSIMDModImmType10(Value); 7803 7804 SDLoc dl(Op); 7805 SDValue Mov = DAG.getNode(NewOp, dl, MovTy, 7806 DAG.getConstant(Value, dl, MVT::i32)); 7807 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov); 7808 } 7809 } 7810 7811 return SDValue(); 7812 } 7813 7814 // Try 32-bit splatted SIMD immediate. 7815 static SDValue tryAdvSIMDModImm32(unsigned NewOp, SDValue Op, SelectionDAG &DAG, 7816 const APInt &Bits, 7817 const SDValue *LHS = nullptr) { 7818 if (Bits.getHiBits(64) == Bits.getLoBits(64)) { 7819 uint64_t Value = Bits.zextOrTrunc(64).getZExtValue(); 7820 EVT VT = Op.getValueType(); 7821 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32; 7822 bool isAdvSIMDModImm = false; 7823 uint64_t Shift; 7824 7825 if ((isAdvSIMDModImm = AArch64_AM::isAdvSIMDModImmType1(Value))) { 7826 Value = AArch64_AM::encodeAdvSIMDModImmType1(Value); 7827 Shift = 0; 7828 } 7829 else if ((isAdvSIMDModImm = AArch64_AM::isAdvSIMDModImmType2(Value))) { 7830 Value = AArch64_AM::encodeAdvSIMDModImmType2(Value); 7831 Shift = 8; 7832 } 7833 else if ((isAdvSIMDModImm = AArch64_AM::isAdvSIMDModImmType3(Value))) { 7834 Value = AArch64_AM::encodeAdvSIMDModImmType3(Value); 7835 Shift = 16; 7836 } 7837 else if ((isAdvSIMDModImm = AArch64_AM::isAdvSIMDModImmType4(Value))) { 7838 Value = AArch64_AM::encodeAdvSIMDModImmType4(Value); 7839 Shift = 24; 7840 } 7841 7842 if (isAdvSIMDModImm) { 7843 SDLoc dl(Op); 7844 SDValue Mov; 7845 7846 if (LHS) 7847 Mov = DAG.getNode(NewOp, dl, MovTy, *LHS, 7848 DAG.getConstant(Value, dl, MVT::i32), 7849 DAG.getConstant(Shift, dl, MVT::i32)); 7850 else 7851 Mov = DAG.getNode(NewOp, dl, MovTy, 7852 DAG.getConstant(Value, dl, MVT::i32), 7853 DAG.getConstant(Shift, dl, MVT::i32)); 7854 7855 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov); 7856 } 7857 } 7858 7859 return SDValue(); 7860 } 7861 7862 // Try 16-bit splatted SIMD immediate. 7863 static SDValue tryAdvSIMDModImm16(unsigned NewOp, SDValue Op, SelectionDAG &DAG, 7864 const APInt &Bits, 7865 const SDValue *LHS = nullptr) { 7866 if (Bits.getHiBits(64) == Bits.getLoBits(64)) { 7867 uint64_t Value = Bits.zextOrTrunc(64).getZExtValue(); 7868 EVT VT = Op.getValueType(); 7869 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v8i16 : MVT::v4i16; 7870 bool isAdvSIMDModImm = false; 7871 uint64_t Shift; 7872 7873 if ((isAdvSIMDModImm = AArch64_AM::isAdvSIMDModImmType5(Value))) { 7874 Value = AArch64_AM::encodeAdvSIMDModImmType5(Value); 7875 Shift = 0; 7876 } 7877 else if ((isAdvSIMDModImm = AArch64_AM::isAdvSIMDModImmType6(Value))) { 7878 Value = AArch64_AM::encodeAdvSIMDModImmType6(Value); 7879 Shift = 8; 7880 } 7881 7882 if (isAdvSIMDModImm) { 7883 SDLoc dl(Op); 7884 SDValue Mov; 7885 7886 if (LHS) 7887 Mov = DAG.getNode(NewOp, dl, MovTy, *LHS, 7888 DAG.getConstant(Value, dl, MVT::i32), 7889 DAG.getConstant(Shift, dl, MVT::i32)); 7890 else 7891 Mov = DAG.getNode(NewOp, dl, MovTy, 7892 DAG.getConstant(Value, dl, MVT::i32), 7893 DAG.getConstant(Shift, dl, MVT::i32)); 7894 7895 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov); 7896 } 7897 } 7898 7899 return SDValue(); 7900 } 7901 7902 // Try 32-bit splatted SIMD immediate with shifted ones. 7903 static SDValue tryAdvSIMDModImm321s(unsigned NewOp, SDValue Op, 7904 SelectionDAG &DAG, const APInt &Bits) { 7905 if (Bits.getHiBits(64) == Bits.getLoBits(64)) { 7906 uint64_t Value = Bits.zextOrTrunc(64).getZExtValue(); 7907 EVT VT = Op.getValueType(); 7908 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32; 7909 bool isAdvSIMDModImm = false; 7910 uint64_t Shift; 7911 7912 if ((isAdvSIMDModImm = AArch64_AM::isAdvSIMDModImmType7(Value))) { 7913 Value = AArch64_AM::encodeAdvSIMDModImmType7(Value); 7914 Shift = 264; 7915 } 7916 else if ((isAdvSIMDModImm = AArch64_AM::isAdvSIMDModImmType8(Value))) { 7917 Value = AArch64_AM::encodeAdvSIMDModImmType8(Value); 7918 Shift = 272; 7919 } 7920 7921 if (isAdvSIMDModImm) { 7922 SDLoc dl(Op); 7923 SDValue Mov = DAG.getNode(NewOp, dl, MovTy, 7924 DAG.getConstant(Value, dl, MVT::i32), 7925 DAG.getConstant(Shift, dl, MVT::i32)); 7926 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov); 7927 } 7928 } 7929 7930 return SDValue(); 7931 } 7932 7933 // Try 8-bit splatted SIMD immediate. 7934 static SDValue tryAdvSIMDModImm8(unsigned NewOp, SDValue Op, SelectionDAG &DAG, 7935 const APInt &Bits) { 7936 if (Bits.getHiBits(64) == Bits.getLoBits(64)) { 7937 uint64_t Value = Bits.zextOrTrunc(64).getZExtValue(); 7938 EVT VT = Op.getValueType(); 7939 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v16i8 : MVT::v8i8; 7940 7941 if (AArch64_AM::isAdvSIMDModImmType9(Value)) { 7942 Value = AArch64_AM::encodeAdvSIMDModImmType9(Value); 7943 7944 SDLoc dl(Op); 7945 SDValue Mov = DAG.getNode(NewOp, dl, MovTy, 7946 DAG.getConstant(Value, dl, MVT::i32)); 7947 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov); 7948 } 7949 } 7950 7951 return SDValue(); 7952 } 7953 7954 // Try FP splatted SIMD immediate. 7955 static SDValue tryAdvSIMDModImmFP(unsigned NewOp, SDValue Op, SelectionDAG &DAG, 7956 const APInt &Bits) { 7957 if (Bits.getHiBits(64) == Bits.getLoBits(64)) { 7958 uint64_t Value = Bits.zextOrTrunc(64).getZExtValue(); 7959 EVT VT = Op.getValueType(); 7960 bool isWide = (VT.getSizeInBits() == 128); 7961 MVT MovTy; 7962 bool isAdvSIMDModImm = false; 7963 7964 if ((isAdvSIMDModImm = AArch64_AM::isAdvSIMDModImmType11(Value))) { 7965 Value = AArch64_AM::encodeAdvSIMDModImmType11(Value); 7966 MovTy = isWide ? MVT::v4f32 : MVT::v2f32; 7967 } 7968 else if (isWide && 7969 (isAdvSIMDModImm = AArch64_AM::isAdvSIMDModImmType12(Value))) { 7970 Value = AArch64_AM::encodeAdvSIMDModImmType12(Value); 7971 MovTy = MVT::v2f64; 7972 } 7973 7974 if (isAdvSIMDModImm) { 7975 SDLoc dl(Op); 7976 SDValue Mov = DAG.getNode(NewOp, dl, MovTy, 7977 DAG.getConstant(Value, dl, MVT::i32)); 7978 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov); 7979 } 7980 } 7981 7982 return SDValue(); 7983 } 7984 7985 // Specialized code to quickly find if PotentialBVec is a BuildVector that 7986 // consists of only the same constant int value, returned in reference arg 7987 // ConstVal 7988 static bool isAllConstantBuildVector(const SDValue &PotentialBVec, 7989 uint64_t &ConstVal) { 7990 BuildVectorSDNode *Bvec = dyn_cast<BuildVectorSDNode>(PotentialBVec); 7991 if (!Bvec) 7992 return false; 7993 ConstantSDNode *FirstElt = dyn_cast<ConstantSDNode>(Bvec->getOperand(0)); 7994 if (!FirstElt) 7995 return false; 7996 EVT VT = Bvec->getValueType(0); 7997 unsigned NumElts = VT.getVectorNumElements(); 7998 for (unsigned i = 1; i < NumElts; ++i) 7999 if (dyn_cast<ConstantSDNode>(Bvec->getOperand(i)) != FirstElt) 8000 return false; 8001 ConstVal = FirstElt->getZExtValue(); 8002 return true; 8003 } 8004 8005 static unsigned getIntrinsicID(const SDNode *N) { 8006 unsigned Opcode = N->getOpcode(); 8007 switch (Opcode) { 8008 default: 8009 return Intrinsic::not_intrinsic; 8010 case ISD::INTRINSIC_WO_CHAIN: { 8011 unsigned IID = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue(); 8012 if (IID < Intrinsic::num_intrinsics) 8013 return IID; 8014 return Intrinsic::not_intrinsic; 8015 } 8016 } 8017 } 8018 8019 // Attempt to form a vector S[LR]I from (or (and X, BvecC1), (lsl Y, C2)), 8020 // to (SLI X, Y, C2), where X and Y have matching vector types, BvecC1 is a 8021 // BUILD_VECTORs with constant element C1, C2 is a constant, and: 8022 // - for the SLI case: C1 == ~(Ones(ElemSizeInBits) << C2) 8023 // - for the SRI case: C1 == ~(Ones(ElemSizeInBits) >> C2) 8024 // The (or (lsl Y, C2), (and X, BvecC1)) case is also handled. 8025 static SDValue tryLowerToSLI(SDNode *N, SelectionDAG &DAG) { 8026 EVT VT = N->getValueType(0); 8027 8028 if (!VT.isVector()) 8029 return SDValue(); 8030 8031 SDLoc DL(N); 8032 8033 SDValue And; 8034 SDValue Shift; 8035 8036 SDValue FirstOp = N->getOperand(0); 8037 unsigned FirstOpc = FirstOp.getOpcode(); 8038 SDValue SecondOp = N->getOperand(1); 8039 unsigned SecondOpc = SecondOp.getOpcode(); 8040 8041 // Is one of the operands an AND or a BICi? The AND may have been optimised to 8042 // a BICi in order to use an immediate instead of a register. 8043 // Is the other operand an shl or lshr? This will have been turned into: 8044 // AArch64ISD::VSHL vector, #shift or AArch64ISD::VLSHR vector, #shift. 8045 if ((FirstOpc == ISD::AND || FirstOpc == AArch64ISD::BICi) && 8046 (SecondOpc == AArch64ISD::VSHL || SecondOpc == AArch64ISD::VLSHR)) { 8047 And = FirstOp; 8048 Shift = SecondOp; 8049 8050 } else if ((SecondOpc == ISD::AND || SecondOpc == AArch64ISD::BICi) && 8051 (FirstOpc == AArch64ISD::VSHL || FirstOpc == AArch64ISD::VLSHR)) { 8052 And = SecondOp; 8053 Shift = FirstOp; 8054 } else 8055 return SDValue(); 8056 8057 bool IsAnd = And.getOpcode() == ISD::AND; 8058 bool IsShiftRight = Shift.getOpcode() == AArch64ISD::VLSHR; 8059 8060 // Is the shift amount constant? 8061 ConstantSDNode *C2node = dyn_cast<ConstantSDNode>(Shift.getOperand(1)); 8062 if (!C2node) 8063 return SDValue(); 8064 8065 uint64_t C1; 8066 if (IsAnd) { 8067 // Is the and mask vector all constant? 8068 if (!isAllConstantBuildVector(And.getOperand(1), C1)) 8069 return SDValue(); 8070 } else { 8071 // Reconstruct the corresponding AND immediate from the two BICi immediates. 8072 ConstantSDNode *C1nodeImm = dyn_cast<ConstantSDNode>(And.getOperand(1)); 8073 ConstantSDNode *C1nodeShift = dyn_cast<ConstantSDNode>(And.getOperand(2)); 8074 assert(C1nodeImm && C1nodeShift); 8075 C1 = ~(C1nodeImm->getZExtValue() << C1nodeShift->getZExtValue()); 8076 } 8077 8078 // Is C1 == ~(Ones(ElemSizeInBits) << C2) or 8079 // C1 == ~(Ones(ElemSizeInBits) >> C2), taking into account 8080 // how much one can shift elements of a particular size? 8081 uint64_t C2 = C2node->getZExtValue(); 8082 unsigned ElemSizeInBits = VT.getScalarSizeInBits(); 8083 if (C2 > ElemSizeInBits) 8084 return SDValue(); 8085 8086 APInt C1AsAPInt(ElemSizeInBits, C1); 8087 APInt RequiredC1 = IsShiftRight ? APInt::getHighBitsSet(ElemSizeInBits, C2) 8088 : APInt::getLowBitsSet(ElemSizeInBits, C2); 8089 if (C1AsAPInt != RequiredC1) 8090 return SDValue(); 8091 8092 SDValue X = And.getOperand(0); 8093 SDValue Y = Shift.getOperand(0); 8094 8095 unsigned Inst = IsShiftRight ? AArch64ISD::VSRI : AArch64ISD::VSLI; 8096 SDValue ResultSLI = DAG.getNode(Inst, DL, VT, X, Y, Shift.getOperand(1)); 8097 8098 LLVM_DEBUG(dbgs() << "aarch64-lower: transformed: \n"); 8099 LLVM_DEBUG(N->dump(&DAG)); 8100 LLVM_DEBUG(dbgs() << "into: \n"); 8101 LLVM_DEBUG(ResultSLI->dump(&DAG)); 8102 8103 ++NumShiftInserts; 8104 return ResultSLI; 8105 } 8106 8107 SDValue AArch64TargetLowering::LowerVectorOR(SDValue Op, 8108 SelectionDAG &DAG) const { 8109 // Attempt to form a vector S[LR]I from (or (and X, C1), (lsl Y, C2)) 8110 if (SDValue Res = tryLowerToSLI(Op.getNode(), DAG)) 8111 return Res; 8112 8113 EVT VT = Op.getValueType(); 8114 8115 SDValue LHS = Op.getOperand(0); 8116 BuildVectorSDNode *BVN = 8117 dyn_cast<BuildVectorSDNode>(Op.getOperand(1).getNode()); 8118 if (!BVN) { 8119 // OR commutes, so try swapping the operands. 8120 LHS = Op.getOperand(1); 8121 BVN = dyn_cast<BuildVectorSDNode>(Op.getOperand(0).getNode()); 8122 } 8123 if (!BVN) 8124 return Op; 8125 8126 APInt DefBits(VT.getSizeInBits(), 0); 8127 APInt UndefBits(VT.getSizeInBits(), 0); 8128 if (resolveBuildVector(BVN, DefBits, UndefBits)) { 8129 SDValue NewOp; 8130 8131 if ((NewOp = tryAdvSIMDModImm32(AArch64ISD::ORRi, Op, DAG, 8132 DefBits, &LHS)) || 8133 (NewOp = tryAdvSIMDModImm16(AArch64ISD::ORRi, Op, DAG, 8134 DefBits, &LHS))) 8135 return NewOp; 8136 8137 if ((NewOp = tryAdvSIMDModImm32(AArch64ISD::ORRi, Op, DAG, 8138 UndefBits, &LHS)) || 8139 (NewOp = tryAdvSIMDModImm16(AArch64ISD::ORRi, Op, DAG, 8140 UndefBits, &LHS))) 8141 return NewOp; 8142 } 8143 8144 // We can always fall back to a non-immediate OR. 8145 return Op; 8146 } 8147 8148 // Normalize the operands of BUILD_VECTOR. The value of constant operands will 8149 // be truncated to fit element width. 8150 static SDValue NormalizeBuildVector(SDValue Op, 8151 SelectionDAG &DAG) { 8152 assert(Op.getOpcode() == ISD::BUILD_VECTOR && "Unknown opcode!"); 8153 SDLoc dl(Op); 8154 EVT VT = Op.getValueType(); 8155 EVT EltTy= VT.getVectorElementType(); 8156 8157 if (EltTy.isFloatingPoint() || EltTy.getSizeInBits() > 16) 8158 return Op; 8159 8160 SmallVector<SDValue, 16> Ops; 8161 for (SDValue Lane : Op->ops()) { 8162 // For integer vectors, type legalization would have promoted the 8163 // operands already. Otherwise, if Op is a floating-point splat 8164 // (with operands cast to integers), then the only possibilities 8165 // are constants and UNDEFs. 8166 if (auto *CstLane = dyn_cast<ConstantSDNode>(Lane)) { 8167 APInt LowBits(EltTy.getSizeInBits(), 8168 CstLane->getZExtValue()); 8169 Lane = DAG.getConstant(LowBits.getZExtValue(), dl, MVT::i32); 8170 } else if (Lane.getNode()->isUndef()) { 8171 Lane = DAG.getUNDEF(MVT::i32); 8172 } else { 8173 assert(Lane.getValueType() == MVT::i32 && 8174 "Unexpected BUILD_VECTOR operand type"); 8175 } 8176 Ops.push_back(Lane); 8177 } 8178 return DAG.getBuildVector(VT, dl, Ops); 8179 } 8180 8181 static SDValue ConstantBuildVector(SDValue Op, SelectionDAG &DAG) { 8182 EVT VT = Op.getValueType(); 8183 8184 APInt DefBits(VT.getSizeInBits(), 0); 8185 APInt UndefBits(VT.getSizeInBits(), 0); 8186 BuildVectorSDNode *BVN = cast<BuildVectorSDNode>(Op.getNode()); 8187 if (resolveBuildVector(BVN, DefBits, UndefBits)) { 8188 SDValue NewOp; 8189 if ((NewOp = tryAdvSIMDModImm64(AArch64ISD::MOVIedit, Op, DAG, DefBits)) || 8190 (NewOp = tryAdvSIMDModImm32(AArch64ISD::MOVIshift, Op, DAG, DefBits)) || 8191 (NewOp = tryAdvSIMDModImm321s(AArch64ISD::MOVImsl, Op, DAG, DefBits)) || 8192 (NewOp = tryAdvSIMDModImm16(AArch64ISD::MOVIshift, Op, DAG, DefBits)) || 8193 (NewOp = tryAdvSIMDModImm8(AArch64ISD::MOVI, Op, DAG, DefBits)) || 8194 (NewOp = tryAdvSIMDModImmFP(AArch64ISD::FMOV, Op, DAG, DefBits))) 8195 return NewOp; 8196 8197 DefBits = ~DefBits; 8198 if ((NewOp = tryAdvSIMDModImm32(AArch64ISD::MVNIshift, Op, DAG, DefBits)) || 8199 (NewOp = tryAdvSIMDModImm321s(AArch64ISD::MVNImsl, Op, DAG, DefBits)) || 8200 (NewOp = tryAdvSIMDModImm16(AArch64ISD::MVNIshift, Op, DAG, DefBits))) 8201 return NewOp; 8202 8203 DefBits = UndefBits; 8204 if ((NewOp = tryAdvSIMDModImm64(AArch64ISD::MOVIedit, Op, DAG, DefBits)) || 8205 (NewOp = tryAdvSIMDModImm32(AArch64ISD::MOVIshift, Op, DAG, DefBits)) || 8206 (NewOp = tryAdvSIMDModImm321s(AArch64ISD::MOVImsl, Op, DAG, DefBits)) || 8207 (NewOp = tryAdvSIMDModImm16(AArch64ISD::MOVIshift, Op, DAG, DefBits)) || 8208 (NewOp = tryAdvSIMDModImm8(AArch64ISD::MOVI, Op, DAG, DefBits)) || 8209 (NewOp = tryAdvSIMDModImmFP(AArch64ISD::FMOV, Op, DAG, DefBits))) 8210 return NewOp; 8211 8212 DefBits = ~UndefBits; 8213 if ((NewOp = tryAdvSIMDModImm32(AArch64ISD::MVNIshift, Op, DAG, DefBits)) || 8214 (NewOp = tryAdvSIMDModImm321s(AArch64ISD::MVNImsl, Op, DAG, DefBits)) || 8215 (NewOp = tryAdvSIMDModImm16(AArch64ISD::MVNIshift, Op, DAG, DefBits))) 8216 return NewOp; 8217 } 8218 8219 return SDValue(); 8220 } 8221 8222 SDValue AArch64TargetLowering::LowerBUILD_VECTOR(SDValue Op, 8223 SelectionDAG &DAG) const { 8224 EVT VT = Op.getValueType(); 8225 8226 // Try to build a simple constant vector. 8227 Op = NormalizeBuildVector(Op, DAG); 8228 if (VT.isInteger()) { 8229 // Certain vector constants, used to express things like logical NOT and 8230 // arithmetic NEG, are passed through unmodified. This allows special 8231 // patterns for these operations to match, which will lower these constants 8232 // to whatever is proven necessary. 8233 BuildVectorSDNode *BVN = cast<BuildVectorSDNode>(Op.getNode()); 8234 if (BVN->isConstant()) 8235 if (ConstantSDNode *Const = BVN->getConstantSplatNode()) { 8236 unsigned BitSize = VT.getVectorElementType().getSizeInBits(); 8237 APInt Val(BitSize, 8238 Const->getAPIntValue().zextOrTrunc(BitSize).getZExtValue()); 8239 if (Val.isNullValue() || Val.isAllOnesValue()) 8240 return Op; 8241 } 8242 } 8243 8244 if (SDValue V = ConstantBuildVector(Op, DAG)) 8245 return V; 8246 8247 // Scan through the operands to find some interesting properties we can 8248 // exploit: 8249 // 1) If only one value is used, we can use a DUP, or 8250 // 2) if only the low element is not undef, we can just insert that, or 8251 // 3) if only one constant value is used (w/ some non-constant lanes), 8252 // we can splat the constant value into the whole vector then fill 8253 // in the non-constant lanes. 8254 // 4) FIXME: If different constant values are used, but we can intelligently 8255 // select the values we'll be overwriting for the non-constant 8256 // lanes such that we can directly materialize the vector 8257 // some other way (MOVI, e.g.), we can be sneaky. 8258 // 5) if all operands are EXTRACT_VECTOR_ELT, check for VUZP. 8259 SDLoc dl(Op); 8260 unsigned NumElts = VT.getVectorNumElements(); 8261 bool isOnlyLowElement = true; 8262 bool usesOnlyOneValue = true; 8263 bool usesOnlyOneConstantValue = true; 8264 bool isConstant = true; 8265 bool AllLanesExtractElt = true; 8266 unsigned NumConstantLanes = 0; 8267 SDValue Value; 8268 SDValue ConstantValue; 8269 for (unsigned i = 0; i < NumElts; ++i) { 8270 SDValue V = Op.getOperand(i); 8271 if (V.getOpcode() != ISD::EXTRACT_VECTOR_ELT) 8272 AllLanesExtractElt = false; 8273 if (V.isUndef()) 8274 continue; 8275 if (i > 0) 8276 isOnlyLowElement = false; 8277 if (!isa<ConstantFPSDNode>(V) && !isa<ConstantSDNode>(V)) 8278 isConstant = false; 8279 8280 if (isa<ConstantSDNode>(V) || isa<ConstantFPSDNode>(V)) { 8281 ++NumConstantLanes; 8282 if (!ConstantValue.getNode()) 8283 ConstantValue = V; 8284 else if (ConstantValue != V) 8285 usesOnlyOneConstantValue = false; 8286 } 8287 8288 if (!Value.getNode()) 8289 Value = V; 8290 else if (V != Value) 8291 usesOnlyOneValue = false; 8292 } 8293 8294 if (!Value.getNode()) { 8295 LLVM_DEBUG( 8296 dbgs() << "LowerBUILD_VECTOR: value undefined, creating undef node\n"); 8297 return DAG.getUNDEF(VT); 8298 } 8299 8300 // Convert BUILD_VECTOR where all elements but the lowest are undef into 8301 // SCALAR_TO_VECTOR, except for when we have a single-element constant vector 8302 // as SimplifyDemandedBits will just turn that back into BUILD_VECTOR. 8303 if (isOnlyLowElement && !(NumElts == 1 && isa<ConstantSDNode>(Value))) { 8304 LLVM_DEBUG(dbgs() << "LowerBUILD_VECTOR: only low element used, creating 1 " 8305 "SCALAR_TO_VECTOR node\n"); 8306 return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Value); 8307 } 8308 8309 if (AllLanesExtractElt) { 8310 SDNode *Vector = nullptr; 8311 bool Even = false; 8312 bool Odd = false; 8313 // Check whether the extract elements match the Even pattern <0,2,4,...> or 8314 // the Odd pattern <1,3,5,...>. 8315 for (unsigned i = 0; i < NumElts; ++i) { 8316 SDValue V = Op.getOperand(i); 8317 const SDNode *N = V.getNode(); 8318 if (!isa<ConstantSDNode>(N->getOperand(1))) 8319 break; 8320 SDValue N0 = N->getOperand(0); 8321 8322 // All elements are extracted from the same vector. 8323 if (!Vector) { 8324 Vector = N0.getNode(); 8325 // Check that the type of EXTRACT_VECTOR_ELT matches the type of 8326 // BUILD_VECTOR. 8327 if (VT.getVectorElementType() != 8328 N0.getValueType().getVectorElementType()) 8329 break; 8330 } else if (Vector != N0.getNode()) { 8331 Odd = false; 8332 Even = false; 8333 break; 8334 } 8335 8336 // Extracted values are either at Even indices <0,2,4,...> or at Odd 8337 // indices <1,3,5,...>. 8338 uint64_t Val = N->getConstantOperandVal(1); 8339 if (Val == 2 * i) { 8340 Even = true; 8341 continue; 8342 } 8343 if (Val - 1 == 2 * i) { 8344 Odd = true; 8345 continue; 8346 } 8347 8348 // Something does not match: abort. 8349 Odd = false; 8350 Even = false; 8351 break; 8352 } 8353 if (Even || Odd) { 8354 SDValue LHS = 8355 DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT, SDValue(Vector, 0), 8356 DAG.getConstant(0, dl, MVT::i64)); 8357 SDValue RHS = 8358 DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT, SDValue(Vector, 0), 8359 DAG.getConstant(NumElts, dl, MVT::i64)); 8360 8361 if (Even && !Odd) 8362 return DAG.getNode(AArch64ISD::UZP1, dl, DAG.getVTList(VT, VT), LHS, 8363 RHS); 8364 if (Odd && !Even) 8365 return DAG.getNode(AArch64ISD::UZP2, dl, DAG.getVTList(VT, VT), LHS, 8366 RHS); 8367 } 8368 } 8369 8370 // Use DUP for non-constant splats. For f32 constant splats, reduce to 8371 // i32 and try again. 8372 if (usesOnlyOneValue) { 8373 if (!isConstant) { 8374 if (Value.getOpcode() != ISD::EXTRACT_VECTOR_ELT || 8375 Value.getValueType() != VT) { 8376 LLVM_DEBUG( 8377 dbgs() << "LowerBUILD_VECTOR: use DUP for non-constant splats\n"); 8378 return DAG.getNode(AArch64ISD::DUP, dl, VT, Value); 8379 } 8380 8381 // This is actually a DUPLANExx operation, which keeps everything vectory. 8382 8383 SDValue Lane = Value.getOperand(1); 8384 Value = Value.getOperand(0); 8385 if (Value.getValueSizeInBits() == 64) { 8386 LLVM_DEBUG( 8387 dbgs() << "LowerBUILD_VECTOR: DUPLANE works on 128-bit vectors, " 8388 "widening it\n"); 8389 Value = WidenVector(Value, DAG); 8390 } 8391 8392 unsigned Opcode = getDUPLANEOp(VT.getVectorElementType()); 8393 return DAG.getNode(Opcode, dl, VT, Value, Lane); 8394 } 8395 8396 if (VT.getVectorElementType().isFloatingPoint()) { 8397 SmallVector<SDValue, 8> Ops; 8398 EVT EltTy = VT.getVectorElementType(); 8399 assert ((EltTy == MVT::f16 || EltTy == MVT::bf16 || EltTy == MVT::f32 || 8400 EltTy == MVT::f64) && "Unsupported floating-point vector type"); 8401 LLVM_DEBUG( 8402 dbgs() << "LowerBUILD_VECTOR: float constant splats, creating int " 8403 "BITCASTS, and try again\n"); 8404 MVT NewType = MVT::getIntegerVT(EltTy.getSizeInBits()); 8405 for (unsigned i = 0; i < NumElts; ++i) 8406 Ops.push_back(DAG.getNode(ISD::BITCAST, dl, NewType, Op.getOperand(i))); 8407 EVT VecVT = EVT::getVectorVT(*DAG.getContext(), NewType, NumElts); 8408 SDValue Val = DAG.getBuildVector(VecVT, dl, Ops); 8409 LLVM_DEBUG(dbgs() << "LowerBUILD_VECTOR: trying to lower new vector: "; 8410 Val.dump();); 8411 Val = LowerBUILD_VECTOR(Val, DAG); 8412 if (Val.getNode()) 8413 return DAG.getNode(ISD::BITCAST, dl, VT, Val); 8414 } 8415 } 8416 8417 // If there was only one constant value used and for more than one lane, 8418 // start by splatting that value, then replace the non-constant lanes. This 8419 // is better than the default, which will perform a separate initialization 8420 // for each lane. 8421 if (NumConstantLanes > 0 && usesOnlyOneConstantValue) { 8422 // Firstly, try to materialize the splat constant. 8423 SDValue Vec = DAG.getSplatBuildVector(VT, dl, ConstantValue), 8424 Val = ConstantBuildVector(Vec, DAG); 8425 if (!Val) { 8426 // Otherwise, materialize the constant and splat it. 8427 Val = DAG.getNode(AArch64ISD::DUP, dl, VT, ConstantValue); 8428 DAG.ReplaceAllUsesWith(Vec.getNode(), &Val); 8429 } 8430 8431 // Now insert the non-constant lanes. 8432 for (unsigned i = 0; i < NumElts; ++i) { 8433 SDValue V = Op.getOperand(i); 8434 SDValue LaneIdx = DAG.getConstant(i, dl, MVT::i64); 8435 if (!isa<ConstantSDNode>(V) && !isa<ConstantFPSDNode>(V)) 8436 // Note that type legalization likely mucked about with the VT of the 8437 // source operand, so we may have to convert it here before inserting. 8438 Val = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Val, V, LaneIdx); 8439 } 8440 return Val; 8441 } 8442 8443 // This will generate a load from the constant pool. 8444 if (isConstant) { 8445 LLVM_DEBUG( 8446 dbgs() << "LowerBUILD_VECTOR: all elements are constant, use default " 8447 "expansion\n"); 8448 return SDValue(); 8449 } 8450 8451 // Empirical tests suggest this is rarely worth it for vectors of length <= 2. 8452 if (NumElts >= 4) { 8453 if (SDValue shuffle = ReconstructShuffle(Op, DAG)) 8454 return shuffle; 8455 } 8456 8457 // If all else fails, just use a sequence of INSERT_VECTOR_ELT when we 8458 // know the default expansion would otherwise fall back on something even 8459 // worse. For a vector with one or two non-undef values, that's 8460 // scalar_to_vector for the elements followed by a shuffle (provided the 8461 // shuffle is valid for the target) and materialization element by element 8462 // on the stack followed by a load for everything else. 8463 if (!isConstant && !usesOnlyOneValue) { 8464 LLVM_DEBUG( 8465 dbgs() << "LowerBUILD_VECTOR: alternatives failed, creating sequence " 8466 "of INSERT_VECTOR_ELT\n"); 8467 8468 SDValue Vec = DAG.getUNDEF(VT); 8469 SDValue Op0 = Op.getOperand(0); 8470 unsigned i = 0; 8471 8472 // Use SCALAR_TO_VECTOR for lane zero to 8473 // a) Avoid a RMW dependency on the full vector register, and 8474 // b) Allow the register coalescer to fold away the copy if the 8475 // value is already in an S or D register, and we're forced to emit an 8476 // INSERT_SUBREG that we can't fold anywhere. 8477 // 8478 // We also allow types like i8 and i16 which are illegal scalar but legal 8479 // vector element types. After type-legalization the inserted value is 8480 // extended (i32) and it is safe to cast them to the vector type by ignoring 8481 // the upper bits of the lowest lane (e.g. v8i8, v4i16). 8482 if (!Op0.isUndef()) { 8483 LLVM_DEBUG(dbgs() << "Creating node for op0, it is not undefined:\n"); 8484 Vec = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op0); 8485 ++i; 8486 } 8487 LLVM_DEBUG(if (i < NumElts) dbgs() 8488 << "Creating nodes for the other vector elements:\n";); 8489 for (; i < NumElts; ++i) { 8490 SDValue V = Op.getOperand(i); 8491 if (V.isUndef()) 8492 continue; 8493 SDValue LaneIdx = DAG.getConstant(i, dl, MVT::i64); 8494 Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Vec, V, LaneIdx); 8495 } 8496 return Vec; 8497 } 8498 8499 LLVM_DEBUG( 8500 dbgs() << "LowerBUILD_VECTOR: use default expansion, failed to find " 8501 "better alternative\n"); 8502 return SDValue(); 8503 } 8504 8505 SDValue AArch64TargetLowering::LowerINSERT_VECTOR_ELT(SDValue Op, 8506 SelectionDAG &DAG) const { 8507 assert(Op.getOpcode() == ISD::INSERT_VECTOR_ELT && "Unknown opcode!"); 8508 8509 // Check for non-constant or out of range lane. 8510 EVT VT = Op.getOperand(0).getValueType(); 8511 ConstantSDNode *CI = dyn_cast<ConstantSDNode>(Op.getOperand(2)); 8512 if (!CI || CI->getZExtValue() >= VT.getVectorNumElements()) 8513 return SDValue(); 8514 8515 8516 // Insertion/extraction are legal for V128 types. 8517 if (VT == MVT::v16i8 || VT == MVT::v8i16 || VT == MVT::v4i32 || 8518 VT == MVT::v2i64 || VT == MVT::v4f32 || VT == MVT::v2f64 || 8519 VT == MVT::v8f16 || VT == MVT::v8bf16) 8520 return Op; 8521 8522 if (VT != MVT::v8i8 && VT != MVT::v4i16 && VT != MVT::v2i32 && 8523 VT != MVT::v1i64 && VT != MVT::v2f32 && VT != MVT::v4f16 && 8524 VT != MVT::v4bf16) 8525 return SDValue(); 8526 8527 // For V64 types, we perform insertion by expanding the value 8528 // to a V128 type and perform the insertion on that. 8529 SDLoc DL(Op); 8530 SDValue WideVec = WidenVector(Op.getOperand(0), DAG); 8531 EVT WideTy = WideVec.getValueType(); 8532 8533 SDValue Node = DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, WideTy, WideVec, 8534 Op.getOperand(1), Op.getOperand(2)); 8535 // Re-narrow the resultant vector. 8536 return NarrowVector(Node, DAG); 8537 } 8538 8539 SDValue 8540 AArch64TargetLowering::LowerEXTRACT_VECTOR_ELT(SDValue Op, 8541 SelectionDAG &DAG) const { 8542 assert(Op.getOpcode() == ISD::EXTRACT_VECTOR_ELT && "Unknown opcode!"); 8543 8544 // Check for non-constant or out of range lane. 8545 EVT VT = Op.getOperand(0).getValueType(); 8546 ConstantSDNode *CI = dyn_cast<ConstantSDNode>(Op.getOperand(1)); 8547 if (!CI || CI->getZExtValue() >= VT.getVectorNumElements()) 8548 return SDValue(); 8549 8550 8551 // Insertion/extraction are legal for V128 types. 8552 if (VT == MVT::v16i8 || VT == MVT::v8i16 || VT == MVT::v4i32 || 8553 VT == MVT::v2i64 || VT == MVT::v4f32 || VT == MVT::v2f64 || 8554 VT == MVT::v8f16 || VT == MVT::v8bf16) 8555 return Op; 8556 8557 if (VT != MVT::v8i8 && VT != MVT::v4i16 && VT != MVT::v2i32 && 8558 VT != MVT::v1i64 && VT != MVT::v2f32 && VT != MVT::v4f16 && 8559 VT != MVT::v4bf16) 8560 return SDValue(); 8561 8562 // For V64 types, we perform extraction by expanding the value 8563 // to a V128 type and perform the extraction on that. 8564 SDLoc DL(Op); 8565 SDValue WideVec = WidenVector(Op.getOperand(0), DAG); 8566 EVT WideTy = WideVec.getValueType(); 8567 8568 EVT ExtrTy = WideTy.getVectorElementType(); 8569 if (ExtrTy == MVT::i16 || ExtrTy == MVT::i8) 8570 ExtrTy = MVT::i32; 8571 8572 // For extractions, we just return the result directly. 8573 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, ExtrTy, WideVec, 8574 Op.getOperand(1)); 8575 } 8576 8577 SDValue AArch64TargetLowering::LowerEXTRACT_SUBVECTOR(SDValue Op, 8578 SelectionDAG &DAG) const { 8579 assert(!Op.getValueType().isScalableVector() && 8580 "Unexpected scalable type for custom lowering EXTRACT_SUBVECTOR"); 8581 8582 EVT VT = Op.getOperand(0).getValueType(); 8583 SDLoc dl(Op); 8584 // Just in case... 8585 if (!VT.isVector()) 8586 return SDValue(); 8587 8588 ConstantSDNode *Cst = dyn_cast<ConstantSDNode>(Op.getOperand(1)); 8589 if (!Cst) 8590 return SDValue(); 8591 unsigned Val = Cst->getZExtValue(); 8592 8593 unsigned Size = Op.getValueSizeInBits(); 8594 8595 // This will get lowered to an appropriate EXTRACT_SUBREG in ISel. 8596 if (Val == 0) 8597 return Op; 8598 8599 // If this is extracting the upper 64-bits of a 128-bit vector, we match 8600 // that directly. 8601 if (Size == 64 && Val * VT.getScalarSizeInBits() == 64) 8602 return Op; 8603 8604 return SDValue(); 8605 } 8606 8607 bool AArch64TargetLowering::isShuffleMaskLegal(ArrayRef<int> M, EVT VT) const { 8608 if (VT.getVectorNumElements() == 4 && 8609 (VT.is128BitVector() || VT.is64BitVector())) { 8610 unsigned PFIndexes[4]; 8611 for (unsigned i = 0; i != 4; ++i) { 8612 if (M[i] < 0) 8613 PFIndexes[i] = 8; 8614 else 8615 PFIndexes[i] = M[i]; 8616 } 8617 8618 // Compute the index in the perfect shuffle table. 8619 unsigned PFTableIndex = PFIndexes[0] * 9 * 9 * 9 + PFIndexes[1] * 9 * 9 + 8620 PFIndexes[2] * 9 + PFIndexes[3]; 8621 unsigned PFEntry = PerfectShuffleTable[PFTableIndex]; 8622 unsigned Cost = (PFEntry >> 30); 8623 8624 if (Cost <= 4) 8625 return true; 8626 } 8627 8628 bool DummyBool; 8629 int DummyInt; 8630 unsigned DummyUnsigned; 8631 8632 return (ShuffleVectorSDNode::isSplatMask(&M[0], VT) || isREVMask(M, VT, 64) || 8633 isREVMask(M, VT, 32) || isREVMask(M, VT, 16) || 8634 isEXTMask(M, VT, DummyBool, DummyUnsigned) || 8635 // isTBLMask(M, VT) || // FIXME: Port TBL support from ARM. 8636 isTRNMask(M, VT, DummyUnsigned) || isUZPMask(M, VT, DummyUnsigned) || 8637 isZIPMask(M, VT, DummyUnsigned) || 8638 isTRN_v_undef_Mask(M, VT, DummyUnsigned) || 8639 isUZP_v_undef_Mask(M, VT, DummyUnsigned) || 8640 isZIP_v_undef_Mask(M, VT, DummyUnsigned) || 8641 isINSMask(M, VT.getVectorNumElements(), DummyBool, DummyInt) || 8642 isConcatMask(M, VT, VT.getSizeInBits() == 128)); 8643 } 8644 8645 /// getVShiftImm - Check if this is a valid build_vector for the immediate 8646 /// operand of a vector shift operation, where all the elements of the 8647 /// build_vector must have the same constant integer value. 8648 static bool getVShiftImm(SDValue Op, unsigned ElementBits, int64_t &Cnt) { 8649 // Ignore bit_converts. 8650 while (Op.getOpcode() == ISD::BITCAST) 8651 Op = Op.getOperand(0); 8652 BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(Op.getNode()); 8653 APInt SplatBits, SplatUndef; 8654 unsigned SplatBitSize; 8655 bool HasAnyUndefs; 8656 if (!BVN || !BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, 8657 HasAnyUndefs, ElementBits) || 8658 SplatBitSize > ElementBits) 8659 return false; 8660 Cnt = SplatBits.getSExtValue(); 8661 return true; 8662 } 8663 8664 /// isVShiftLImm - Check if this is a valid build_vector for the immediate 8665 /// operand of a vector shift left operation. That value must be in the range: 8666 /// 0 <= Value < ElementBits for a left shift; or 8667 /// 0 <= Value <= ElementBits for a long left shift. 8668 static bool isVShiftLImm(SDValue Op, EVT VT, bool isLong, int64_t &Cnt) { 8669 assert(VT.isVector() && "vector shift count is not a vector type"); 8670 int64_t ElementBits = VT.getScalarSizeInBits(); 8671 if (!getVShiftImm(Op, ElementBits, Cnt)) 8672 return false; 8673 return (Cnt >= 0 && (isLong ? Cnt - 1 : Cnt) < ElementBits); 8674 } 8675 8676 /// isVShiftRImm - Check if this is a valid build_vector for the immediate 8677 /// operand of a vector shift right operation. The value must be in the range: 8678 /// 1 <= Value <= ElementBits for a right shift; or 8679 static bool isVShiftRImm(SDValue Op, EVT VT, bool isNarrow, int64_t &Cnt) { 8680 assert(VT.isVector() && "vector shift count is not a vector type"); 8681 int64_t ElementBits = VT.getScalarSizeInBits(); 8682 if (!getVShiftImm(Op, ElementBits, Cnt)) 8683 return false; 8684 return (Cnt >= 1 && Cnt <= (isNarrow ? ElementBits / 2 : ElementBits)); 8685 } 8686 8687 SDValue AArch64TargetLowering::LowerVectorSRA_SRL_SHL(SDValue Op, 8688 SelectionDAG &DAG) const { 8689 EVT VT = Op.getValueType(); 8690 SDLoc DL(Op); 8691 int64_t Cnt; 8692 8693 if (!Op.getOperand(1).getValueType().isVector()) 8694 return Op; 8695 unsigned EltSize = VT.getScalarSizeInBits(); 8696 8697 switch (Op.getOpcode()) { 8698 default: 8699 llvm_unreachable("unexpected shift opcode"); 8700 8701 case ISD::SHL: 8702 if (VT.isScalableVector()) 8703 return LowerToPredicatedOp(Op, DAG, AArch64ISD::SHL_PRED); 8704 8705 if (isVShiftLImm(Op.getOperand(1), VT, false, Cnt) && Cnt < EltSize) 8706 return DAG.getNode(AArch64ISD::VSHL, DL, VT, Op.getOperand(0), 8707 DAG.getConstant(Cnt, DL, MVT::i32)); 8708 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT, 8709 DAG.getConstant(Intrinsic::aarch64_neon_ushl, DL, 8710 MVT::i32), 8711 Op.getOperand(0), Op.getOperand(1)); 8712 case ISD::SRA: 8713 case ISD::SRL: 8714 if (VT.isScalableVector()) { 8715 unsigned Opc = Op.getOpcode() == ISD::SRA ? AArch64ISD::SRA_PRED 8716 : AArch64ISD::SRL_PRED; 8717 return LowerToPredicatedOp(Op, DAG, Opc); 8718 } 8719 8720 // Right shift immediate 8721 if (isVShiftRImm(Op.getOperand(1), VT, false, Cnt) && Cnt < EltSize) { 8722 unsigned Opc = 8723 (Op.getOpcode() == ISD::SRA) ? AArch64ISD::VASHR : AArch64ISD::VLSHR; 8724 return DAG.getNode(Opc, DL, VT, Op.getOperand(0), 8725 DAG.getConstant(Cnt, DL, MVT::i32)); 8726 } 8727 8728 // Right shift register. Note, there is not a shift right register 8729 // instruction, but the shift left register instruction takes a signed 8730 // value, where negative numbers specify a right shift. 8731 unsigned Opc = (Op.getOpcode() == ISD::SRA) ? Intrinsic::aarch64_neon_sshl 8732 : Intrinsic::aarch64_neon_ushl; 8733 // negate the shift amount 8734 SDValue NegShift = DAG.getNode(AArch64ISD::NEG, DL, VT, Op.getOperand(1)); 8735 SDValue NegShiftLeft = 8736 DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT, 8737 DAG.getConstant(Opc, DL, MVT::i32), Op.getOperand(0), 8738 NegShift); 8739 return NegShiftLeft; 8740 } 8741 8742 return SDValue(); 8743 } 8744 8745 static SDValue EmitVectorComparison(SDValue LHS, SDValue RHS, 8746 AArch64CC::CondCode CC, bool NoNans, EVT VT, 8747 const SDLoc &dl, SelectionDAG &DAG) { 8748 EVT SrcVT = LHS.getValueType(); 8749 assert(VT.getSizeInBits() == SrcVT.getSizeInBits() && 8750 "function only supposed to emit natural comparisons"); 8751 8752 BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(RHS.getNode()); 8753 APInt CnstBits(VT.getSizeInBits(), 0); 8754 APInt UndefBits(VT.getSizeInBits(), 0); 8755 bool IsCnst = BVN && resolveBuildVector(BVN, CnstBits, UndefBits); 8756 bool IsZero = IsCnst && (CnstBits == 0); 8757 8758 if (SrcVT.getVectorElementType().isFloatingPoint()) { 8759 switch (CC) { 8760 default: 8761 return SDValue(); 8762 case AArch64CC::NE: { 8763 SDValue Fcmeq; 8764 if (IsZero) 8765 Fcmeq = DAG.getNode(AArch64ISD::FCMEQz, dl, VT, LHS); 8766 else 8767 Fcmeq = DAG.getNode(AArch64ISD::FCMEQ, dl, VT, LHS, RHS); 8768 return DAG.getNode(AArch64ISD::NOT, dl, VT, Fcmeq); 8769 } 8770 case AArch64CC::EQ: 8771 if (IsZero) 8772 return DAG.getNode(AArch64ISD::FCMEQz, dl, VT, LHS); 8773 return DAG.getNode(AArch64ISD::FCMEQ, dl, VT, LHS, RHS); 8774 case AArch64CC::GE: 8775 if (IsZero) 8776 return DAG.getNode(AArch64ISD::FCMGEz, dl, VT, LHS); 8777 return DAG.getNode(AArch64ISD::FCMGE, dl, VT, LHS, RHS); 8778 case AArch64CC::GT: 8779 if (IsZero) 8780 return DAG.getNode(AArch64ISD::FCMGTz, dl, VT, LHS); 8781 return DAG.getNode(AArch64ISD::FCMGT, dl, VT, LHS, RHS); 8782 case AArch64CC::LS: 8783 if (IsZero) 8784 return DAG.getNode(AArch64ISD::FCMLEz, dl, VT, LHS); 8785 return DAG.getNode(AArch64ISD::FCMGE, dl, VT, RHS, LHS); 8786 case AArch64CC::LT: 8787 if (!NoNans) 8788 return SDValue(); 8789 // If we ignore NaNs then we can use to the MI implementation. 8790 LLVM_FALLTHROUGH; 8791 case AArch64CC::MI: 8792 if (IsZero) 8793 return DAG.getNode(AArch64ISD::FCMLTz, dl, VT, LHS); 8794 return DAG.getNode(AArch64ISD::FCMGT, dl, VT, RHS, LHS); 8795 } 8796 } 8797 8798 switch (CC) { 8799 default: 8800 return SDValue(); 8801 case AArch64CC::NE: { 8802 SDValue Cmeq; 8803 if (IsZero) 8804 Cmeq = DAG.getNode(AArch64ISD::CMEQz, dl, VT, LHS); 8805 else 8806 Cmeq = DAG.getNode(AArch64ISD::CMEQ, dl, VT, LHS, RHS); 8807 return DAG.getNode(AArch64ISD::NOT, dl, VT, Cmeq); 8808 } 8809 case AArch64CC::EQ: 8810 if (IsZero) 8811 return DAG.getNode(AArch64ISD::CMEQz, dl, VT, LHS); 8812 return DAG.getNode(AArch64ISD::CMEQ, dl, VT, LHS, RHS); 8813 case AArch64CC::GE: 8814 if (IsZero) 8815 return DAG.getNode(AArch64ISD::CMGEz, dl, VT, LHS); 8816 return DAG.getNode(AArch64ISD::CMGE, dl, VT, LHS, RHS); 8817 case AArch64CC::GT: 8818 if (IsZero) 8819 return DAG.getNode(AArch64ISD::CMGTz, dl, VT, LHS); 8820 return DAG.getNode(AArch64ISD::CMGT, dl, VT, LHS, RHS); 8821 case AArch64CC::LE: 8822 if (IsZero) 8823 return DAG.getNode(AArch64ISD::CMLEz, dl, VT, LHS); 8824 return DAG.getNode(AArch64ISD::CMGE, dl, VT, RHS, LHS); 8825 case AArch64CC::LS: 8826 return DAG.getNode(AArch64ISD::CMHS, dl, VT, RHS, LHS); 8827 case AArch64CC::LO: 8828 return DAG.getNode(AArch64ISD::CMHI, dl, VT, RHS, LHS); 8829 case AArch64CC::LT: 8830 if (IsZero) 8831 return DAG.getNode(AArch64ISD::CMLTz, dl, VT, LHS); 8832 return DAG.getNode(AArch64ISD::CMGT, dl, VT, RHS, LHS); 8833 case AArch64CC::HI: 8834 return DAG.getNode(AArch64ISD::CMHI, dl, VT, LHS, RHS); 8835 case AArch64CC::HS: 8836 return DAG.getNode(AArch64ISD::CMHS, dl, VT, LHS, RHS); 8837 } 8838 } 8839 8840 SDValue AArch64TargetLowering::LowerVSETCC(SDValue Op, 8841 SelectionDAG &DAG) const { 8842 if (Op.getValueType().isScalableVector()) { 8843 if (Op.getOperand(0).getValueType().isFloatingPoint()) 8844 return Op; 8845 return LowerToPredicatedOp(Op, DAG, AArch64ISD::SETCC_PRED); 8846 } 8847 8848 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get(); 8849 SDValue LHS = Op.getOperand(0); 8850 SDValue RHS = Op.getOperand(1); 8851 EVT CmpVT = LHS.getValueType().changeVectorElementTypeToInteger(); 8852 SDLoc dl(Op); 8853 8854 if (LHS.getValueType().getVectorElementType().isInteger()) { 8855 assert(LHS.getValueType() == RHS.getValueType()); 8856 AArch64CC::CondCode AArch64CC = changeIntCCToAArch64CC(CC); 8857 SDValue Cmp = 8858 EmitVectorComparison(LHS, RHS, AArch64CC, false, CmpVT, dl, DAG); 8859 return DAG.getSExtOrTrunc(Cmp, dl, Op.getValueType()); 8860 } 8861 8862 const bool FullFP16 = 8863 static_cast<const AArch64Subtarget &>(DAG.getSubtarget()).hasFullFP16(); 8864 8865 // Make v4f16 (only) fcmp operations utilise vector instructions 8866 // v8f16 support will be a litle more complicated 8867 if (!FullFP16 && LHS.getValueType().getVectorElementType() == MVT::f16) { 8868 if (LHS.getValueType().getVectorNumElements() == 4) { 8869 LHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::v4f32, LHS); 8870 RHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::v4f32, RHS); 8871 SDValue NewSetcc = DAG.getSetCC(dl, MVT::v4i16, LHS, RHS, CC); 8872 DAG.ReplaceAllUsesWith(Op, NewSetcc); 8873 CmpVT = MVT::v4i32; 8874 } else 8875 return SDValue(); 8876 } 8877 8878 assert((!FullFP16 && LHS.getValueType().getVectorElementType() != MVT::f16) || 8879 LHS.getValueType().getVectorElementType() != MVT::f128); 8880 8881 // Unfortunately, the mapping of LLVM FP CC's onto AArch64 CC's isn't totally 8882 // clean. Some of them require two branches to implement. 8883 AArch64CC::CondCode CC1, CC2; 8884 bool ShouldInvert; 8885 changeVectorFPCCToAArch64CC(CC, CC1, CC2, ShouldInvert); 8886 8887 bool NoNaNs = getTargetMachine().Options.NoNaNsFPMath; 8888 SDValue Cmp = 8889 EmitVectorComparison(LHS, RHS, CC1, NoNaNs, CmpVT, dl, DAG); 8890 if (!Cmp.getNode()) 8891 return SDValue(); 8892 8893 if (CC2 != AArch64CC::AL) { 8894 SDValue Cmp2 = 8895 EmitVectorComparison(LHS, RHS, CC2, NoNaNs, CmpVT, dl, DAG); 8896 if (!Cmp2.getNode()) 8897 return SDValue(); 8898 8899 Cmp = DAG.getNode(ISD::OR, dl, CmpVT, Cmp, Cmp2); 8900 } 8901 8902 Cmp = DAG.getSExtOrTrunc(Cmp, dl, Op.getValueType()); 8903 8904 if (ShouldInvert) 8905 Cmp = DAG.getNOT(dl, Cmp, Cmp.getValueType()); 8906 8907 return Cmp; 8908 } 8909 8910 static SDValue getReductionSDNode(unsigned Op, SDLoc DL, SDValue ScalarOp, 8911 SelectionDAG &DAG) { 8912 SDValue VecOp = ScalarOp.getOperand(0); 8913 auto Rdx = DAG.getNode(Op, DL, VecOp.getSimpleValueType(), VecOp); 8914 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, ScalarOp.getValueType(), Rdx, 8915 DAG.getConstant(0, DL, MVT::i64)); 8916 } 8917 8918 SDValue AArch64TargetLowering::LowerVECREDUCE(SDValue Op, 8919 SelectionDAG &DAG) const { 8920 SDLoc dl(Op); 8921 switch (Op.getOpcode()) { 8922 case ISD::VECREDUCE_ADD: 8923 return getReductionSDNode(AArch64ISD::UADDV, dl, Op, DAG); 8924 case ISD::VECREDUCE_SMAX: 8925 return getReductionSDNode(AArch64ISD::SMAXV, dl, Op, DAG); 8926 case ISD::VECREDUCE_SMIN: 8927 return getReductionSDNode(AArch64ISD::SMINV, dl, Op, DAG); 8928 case ISD::VECREDUCE_UMAX: 8929 return getReductionSDNode(AArch64ISD::UMAXV, dl, Op, DAG); 8930 case ISD::VECREDUCE_UMIN: 8931 return getReductionSDNode(AArch64ISD::UMINV, dl, Op, DAG); 8932 case ISD::VECREDUCE_FMAX: { 8933 assert(Op->getFlags().hasNoNaNs() && "fmax vector reduction needs NoNaN flag"); 8934 return DAG.getNode( 8935 ISD::INTRINSIC_WO_CHAIN, dl, Op.getValueType(), 8936 DAG.getConstant(Intrinsic::aarch64_neon_fmaxnmv, dl, MVT::i32), 8937 Op.getOperand(0)); 8938 } 8939 case ISD::VECREDUCE_FMIN: { 8940 assert(Op->getFlags().hasNoNaNs() && "fmin vector reduction needs NoNaN flag"); 8941 return DAG.getNode( 8942 ISD::INTRINSIC_WO_CHAIN, dl, Op.getValueType(), 8943 DAG.getConstant(Intrinsic::aarch64_neon_fminnmv, dl, MVT::i32), 8944 Op.getOperand(0)); 8945 } 8946 default: 8947 llvm_unreachable("Unhandled reduction"); 8948 } 8949 } 8950 8951 SDValue AArch64TargetLowering::LowerATOMIC_LOAD_SUB(SDValue Op, 8952 SelectionDAG &DAG) const { 8953 auto &Subtarget = static_cast<const AArch64Subtarget &>(DAG.getSubtarget()); 8954 if (!Subtarget.hasLSE()) 8955 return SDValue(); 8956 8957 // LSE has an atomic load-add instruction, but not a load-sub. 8958 SDLoc dl(Op); 8959 MVT VT = Op.getSimpleValueType(); 8960 SDValue RHS = Op.getOperand(2); 8961 AtomicSDNode *AN = cast<AtomicSDNode>(Op.getNode()); 8962 RHS = DAG.getNode(ISD::SUB, dl, VT, DAG.getConstant(0, dl, VT), RHS); 8963 return DAG.getAtomic(ISD::ATOMIC_LOAD_ADD, dl, AN->getMemoryVT(), 8964 Op.getOperand(0), Op.getOperand(1), RHS, 8965 AN->getMemOperand()); 8966 } 8967 8968 SDValue AArch64TargetLowering::LowerATOMIC_LOAD_AND(SDValue Op, 8969 SelectionDAG &DAG) const { 8970 auto &Subtarget = static_cast<const AArch64Subtarget &>(DAG.getSubtarget()); 8971 if (!Subtarget.hasLSE()) 8972 return SDValue(); 8973 8974 // LSE has an atomic load-clear instruction, but not a load-and. 8975 SDLoc dl(Op); 8976 MVT VT = Op.getSimpleValueType(); 8977 SDValue RHS = Op.getOperand(2); 8978 AtomicSDNode *AN = cast<AtomicSDNode>(Op.getNode()); 8979 RHS = DAG.getNode(ISD::XOR, dl, VT, DAG.getConstant(-1ULL, dl, VT), RHS); 8980 return DAG.getAtomic(ISD::ATOMIC_LOAD_CLR, dl, AN->getMemoryVT(), 8981 Op.getOperand(0), Op.getOperand(1), RHS, 8982 AN->getMemOperand()); 8983 } 8984 8985 SDValue AArch64TargetLowering::LowerWindowsDYNAMIC_STACKALLOC( 8986 SDValue Op, SDValue Chain, SDValue &Size, SelectionDAG &DAG) const { 8987 SDLoc dl(Op); 8988 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 8989 SDValue Callee = DAG.getTargetExternalSymbol("__chkstk", PtrVT, 0); 8990 8991 const AArch64RegisterInfo *TRI = Subtarget->getRegisterInfo(); 8992 const uint32_t *Mask = TRI->getWindowsStackProbePreservedMask(); 8993 if (Subtarget->hasCustomCallingConv()) 8994 TRI->UpdateCustomCallPreservedMask(DAG.getMachineFunction(), &Mask); 8995 8996 Size = DAG.getNode(ISD::SRL, dl, MVT::i64, Size, 8997 DAG.getConstant(4, dl, MVT::i64)); 8998 Chain = DAG.getCopyToReg(Chain, dl, AArch64::X15, Size, SDValue()); 8999 Chain = 9000 DAG.getNode(AArch64ISD::CALL, dl, DAG.getVTList(MVT::Other, MVT::Glue), 9001 Chain, Callee, DAG.getRegister(AArch64::X15, MVT::i64), 9002 DAG.getRegisterMask(Mask), Chain.getValue(1)); 9003 // To match the actual intent better, we should read the output from X15 here 9004 // again (instead of potentially spilling it to the stack), but rereading Size 9005 // from X15 here doesn't work at -O0, since it thinks that X15 is undefined 9006 // here. 9007 9008 Size = DAG.getNode(ISD::SHL, dl, MVT::i64, Size, 9009 DAG.getConstant(4, dl, MVT::i64)); 9010 return Chain; 9011 } 9012 9013 SDValue 9014 AArch64TargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op, 9015 SelectionDAG &DAG) const { 9016 assert(Subtarget->isTargetWindows() && 9017 "Only Windows alloca probing supported"); 9018 SDLoc dl(Op); 9019 // Get the inputs. 9020 SDNode *Node = Op.getNode(); 9021 SDValue Chain = Op.getOperand(0); 9022 SDValue Size = Op.getOperand(1); 9023 unsigned Align = cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue(); 9024 EVT VT = Node->getValueType(0); 9025 9026 if (DAG.getMachineFunction().getFunction().hasFnAttribute( 9027 "no-stack-arg-probe")) { 9028 SDValue SP = DAG.getCopyFromReg(Chain, dl, AArch64::SP, MVT::i64); 9029 Chain = SP.getValue(1); 9030 SP = DAG.getNode(ISD::SUB, dl, MVT::i64, SP, Size); 9031 if (Align) 9032 SP = DAG.getNode(ISD::AND, dl, VT, SP.getValue(0), 9033 DAG.getConstant(-(uint64_t)Align, dl, VT)); 9034 Chain = DAG.getCopyToReg(Chain, dl, AArch64::SP, SP); 9035 SDValue Ops[2] = {SP, Chain}; 9036 return DAG.getMergeValues(Ops, dl); 9037 } 9038 9039 Chain = DAG.getCALLSEQ_START(Chain, 0, 0, dl); 9040 9041 Chain = LowerWindowsDYNAMIC_STACKALLOC(Op, Chain, Size, DAG); 9042 9043 SDValue SP = DAG.getCopyFromReg(Chain, dl, AArch64::SP, MVT::i64); 9044 Chain = SP.getValue(1); 9045 SP = DAG.getNode(ISD::SUB, dl, MVT::i64, SP, Size); 9046 if (Align) 9047 SP = DAG.getNode(ISD::AND, dl, VT, SP.getValue(0), 9048 DAG.getConstant(-(uint64_t)Align, dl, VT)); 9049 Chain = DAG.getCopyToReg(Chain, dl, AArch64::SP, SP); 9050 9051 Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(0, dl, true), 9052 DAG.getIntPtrConstant(0, dl, true), SDValue(), dl); 9053 9054 SDValue Ops[2] = {SP, Chain}; 9055 return DAG.getMergeValues(Ops, dl); 9056 } 9057 9058 SDValue AArch64TargetLowering::LowerVSCALE(SDValue Op, 9059 SelectionDAG &DAG) const { 9060 EVT VT = Op.getValueType(); 9061 assert(VT != MVT::i64 && "Expected illegal VSCALE node"); 9062 9063 SDLoc DL(Op); 9064 APInt MulImm = cast<ConstantSDNode>(Op.getOperand(0))->getAPIntValue(); 9065 return DAG.getZExtOrTrunc(DAG.getVScale(DL, MVT::i64, MulImm.sextOrSelf(64)), 9066 DL, VT); 9067 } 9068 9069 /// Set the IntrinsicInfo for the `aarch64_sve_st<N>` intrinsics. 9070 template <unsigned NumVecs> 9071 static bool setInfoSVEStN(AArch64TargetLowering::IntrinsicInfo &Info, 9072 const CallInst &CI) { 9073 Info.opc = ISD::INTRINSIC_VOID; 9074 // Retrieve EC from first vector argument. 9075 const EVT VT = EVT::getEVT(CI.getArgOperand(0)->getType()); 9076 ElementCount EC = VT.getVectorElementCount(); 9077 #ifndef NDEBUG 9078 // Check the assumption that all input vectors are the same type. 9079 for (unsigned I = 0; I < NumVecs; ++I) 9080 assert(VT == EVT::getEVT(CI.getArgOperand(I)->getType()) && 9081 "Invalid type."); 9082 #endif 9083 // memVT is `NumVecs * VT`. 9084 Info.memVT = EVT::getVectorVT(CI.getType()->getContext(), VT.getScalarType(), 9085 EC * NumVecs); 9086 Info.ptrVal = CI.getArgOperand(CI.getNumArgOperands() - 1); 9087 Info.offset = 0; 9088 Info.align.reset(); 9089 Info.flags = MachineMemOperand::MOStore; 9090 return true; 9091 } 9092 9093 /// getTgtMemIntrinsic - Represent NEON load and store intrinsics as 9094 /// MemIntrinsicNodes. The associated MachineMemOperands record the alignment 9095 /// specified in the intrinsic calls. 9096 bool AArch64TargetLowering::getTgtMemIntrinsic(IntrinsicInfo &Info, 9097 const CallInst &I, 9098 MachineFunction &MF, 9099 unsigned Intrinsic) const { 9100 auto &DL = I.getModule()->getDataLayout(); 9101 switch (Intrinsic) { 9102 case Intrinsic::aarch64_sve_st2: 9103 return setInfoSVEStN<2>(Info, I); 9104 case Intrinsic::aarch64_sve_st3: 9105 return setInfoSVEStN<3>(Info, I); 9106 case Intrinsic::aarch64_sve_st4: 9107 return setInfoSVEStN<4>(Info, I); 9108 case Intrinsic::aarch64_neon_ld2: 9109 case Intrinsic::aarch64_neon_ld3: 9110 case Intrinsic::aarch64_neon_ld4: 9111 case Intrinsic::aarch64_neon_ld1x2: 9112 case Intrinsic::aarch64_neon_ld1x3: 9113 case Intrinsic::aarch64_neon_ld1x4: 9114 case Intrinsic::aarch64_neon_ld2lane: 9115 case Intrinsic::aarch64_neon_ld3lane: 9116 case Intrinsic::aarch64_neon_ld4lane: 9117 case Intrinsic::aarch64_neon_ld2r: 9118 case Intrinsic::aarch64_neon_ld3r: 9119 case Intrinsic::aarch64_neon_ld4r: { 9120 Info.opc = ISD::INTRINSIC_W_CHAIN; 9121 // Conservatively set memVT to the entire set of vectors loaded. 9122 uint64_t NumElts = DL.getTypeSizeInBits(I.getType()) / 64; 9123 Info.memVT = EVT::getVectorVT(I.getType()->getContext(), MVT::i64, NumElts); 9124 Info.ptrVal = I.getArgOperand(I.getNumArgOperands() - 1); 9125 Info.offset = 0; 9126 Info.align.reset(); 9127 // volatile loads with NEON intrinsics not supported 9128 Info.flags = MachineMemOperand::MOLoad; 9129 return true; 9130 } 9131 case Intrinsic::aarch64_neon_st2: 9132 case Intrinsic::aarch64_neon_st3: 9133 case Intrinsic::aarch64_neon_st4: 9134 case Intrinsic::aarch64_neon_st1x2: 9135 case Intrinsic::aarch64_neon_st1x3: 9136 case Intrinsic::aarch64_neon_st1x4: 9137 case Intrinsic::aarch64_neon_st2lane: 9138 case Intrinsic::aarch64_neon_st3lane: 9139 case Intrinsic::aarch64_neon_st4lane: { 9140 Info.opc = ISD::INTRINSIC_VOID; 9141 // Conservatively set memVT to the entire set of vectors stored. 9142 unsigned NumElts = 0; 9143 for (unsigned ArgI = 0, ArgE = I.getNumArgOperands(); ArgI < ArgE; ++ArgI) { 9144 Type *ArgTy = I.getArgOperand(ArgI)->getType(); 9145 if (!ArgTy->isVectorTy()) 9146 break; 9147 NumElts += DL.getTypeSizeInBits(ArgTy) / 64; 9148 } 9149 Info.memVT = EVT::getVectorVT(I.getType()->getContext(), MVT::i64, NumElts); 9150 Info.ptrVal = I.getArgOperand(I.getNumArgOperands() - 1); 9151 Info.offset = 0; 9152 Info.align.reset(); 9153 // volatile stores with NEON intrinsics not supported 9154 Info.flags = MachineMemOperand::MOStore; 9155 return true; 9156 } 9157 case Intrinsic::aarch64_ldaxr: 9158 case Intrinsic::aarch64_ldxr: { 9159 PointerType *PtrTy = cast<PointerType>(I.getArgOperand(0)->getType()); 9160 Info.opc = ISD::INTRINSIC_W_CHAIN; 9161 Info.memVT = MVT::getVT(PtrTy->getElementType()); 9162 Info.ptrVal = I.getArgOperand(0); 9163 Info.offset = 0; 9164 Info.align = MaybeAlign(DL.getABITypeAlignment(PtrTy->getElementType())); 9165 Info.flags = MachineMemOperand::MOLoad | MachineMemOperand::MOVolatile; 9166 return true; 9167 } 9168 case Intrinsic::aarch64_stlxr: 9169 case Intrinsic::aarch64_stxr: { 9170 PointerType *PtrTy = cast<PointerType>(I.getArgOperand(1)->getType()); 9171 Info.opc = ISD::INTRINSIC_W_CHAIN; 9172 Info.memVT = MVT::getVT(PtrTy->getElementType()); 9173 Info.ptrVal = I.getArgOperand(1); 9174 Info.offset = 0; 9175 Info.align = MaybeAlign(DL.getABITypeAlignment(PtrTy->getElementType())); 9176 Info.flags = MachineMemOperand::MOStore | MachineMemOperand::MOVolatile; 9177 return true; 9178 } 9179 case Intrinsic::aarch64_ldaxp: 9180 case Intrinsic::aarch64_ldxp: 9181 Info.opc = ISD::INTRINSIC_W_CHAIN; 9182 Info.memVT = MVT::i128; 9183 Info.ptrVal = I.getArgOperand(0); 9184 Info.offset = 0; 9185 Info.align = Align(16); 9186 Info.flags = MachineMemOperand::MOLoad | MachineMemOperand::MOVolatile; 9187 return true; 9188 case Intrinsic::aarch64_stlxp: 9189 case Intrinsic::aarch64_stxp: 9190 Info.opc = ISD::INTRINSIC_W_CHAIN; 9191 Info.memVT = MVT::i128; 9192 Info.ptrVal = I.getArgOperand(2); 9193 Info.offset = 0; 9194 Info.align = Align(16); 9195 Info.flags = MachineMemOperand::MOStore | MachineMemOperand::MOVolatile; 9196 return true; 9197 case Intrinsic::aarch64_sve_ldnt1: { 9198 PointerType *PtrTy = cast<PointerType>(I.getArgOperand(1)->getType()); 9199 Info.opc = ISD::INTRINSIC_W_CHAIN; 9200 Info.memVT = MVT::getVT(I.getType()); 9201 Info.ptrVal = I.getArgOperand(1); 9202 Info.offset = 0; 9203 Info.align = MaybeAlign(DL.getABITypeAlignment(PtrTy->getElementType())); 9204 Info.flags = MachineMemOperand::MOLoad; 9205 if (Intrinsic == Intrinsic::aarch64_sve_ldnt1) 9206 Info.flags |= MachineMemOperand::MONonTemporal; 9207 return true; 9208 } 9209 case Intrinsic::aarch64_sve_stnt1: { 9210 PointerType *PtrTy = cast<PointerType>(I.getArgOperand(2)->getType()); 9211 Info.opc = ISD::INTRINSIC_W_CHAIN; 9212 Info.memVT = MVT::getVT(I.getOperand(0)->getType()); 9213 Info.ptrVal = I.getArgOperand(2); 9214 Info.offset = 0; 9215 Info.align = MaybeAlign(DL.getABITypeAlignment(PtrTy->getElementType())); 9216 Info.flags = MachineMemOperand::MOStore; 9217 if (Intrinsic == Intrinsic::aarch64_sve_stnt1) 9218 Info.flags |= MachineMemOperand::MONonTemporal; 9219 return true; 9220 } 9221 default: 9222 break; 9223 } 9224 9225 return false; 9226 } 9227 9228 bool AArch64TargetLowering::shouldReduceLoadWidth(SDNode *Load, 9229 ISD::LoadExtType ExtTy, 9230 EVT NewVT) const { 9231 // TODO: This may be worth removing. Check regression tests for diffs. 9232 if (!TargetLoweringBase::shouldReduceLoadWidth(Load, ExtTy, NewVT)) 9233 return false; 9234 9235 // If we're reducing the load width in order to avoid having to use an extra 9236 // instruction to do extension then it's probably a good idea. 9237 if (ExtTy != ISD::NON_EXTLOAD) 9238 return true; 9239 // Don't reduce load width if it would prevent us from combining a shift into 9240 // the offset. 9241 MemSDNode *Mem = dyn_cast<MemSDNode>(Load); 9242 assert(Mem); 9243 const SDValue &Base = Mem->getBasePtr(); 9244 if (Base.getOpcode() == ISD::ADD && 9245 Base.getOperand(1).getOpcode() == ISD::SHL && 9246 Base.getOperand(1).hasOneUse() && 9247 Base.getOperand(1).getOperand(1).getOpcode() == ISD::Constant) { 9248 // The shift can be combined if it matches the size of the value being 9249 // loaded (and so reducing the width would make it not match). 9250 uint64_t ShiftAmount = Base.getOperand(1).getConstantOperandVal(1); 9251 uint64_t LoadBytes = Mem->getMemoryVT().getSizeInBits()/8; 9252 if (ShiftAmount == Log2_32(LoadBytes)) 9253 return false; 9254 } 9255 // We have no reason to disallow reducing the load width, so allow it. 9256 return true; 9257 } 9258 9259 // Truncations from 64-bit GPR to 32-bit GPR is free. 9260 bool AArch64TargetLowering::isTruncateFree(Type *Ty1, Type *Ty2) const { 9261 if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy()) 9262 return false; 9263 unsigned NumBits1 = Ty1->getPrimitiveSizeInBits(); 9264 unsigned NumBits2 = Ty2->getPrimitiveSizeInBits(); 9265 return NumBits1 > NumBits2; 9266 } 9267 bool AArch64TargetLowering::isTruncateFree(EVT VT1, EVT VT2) const { 9268 if (VT1.isVector() || VT2.isVector() || !VT1.isInteger() || !VT2.isInteger()) 9269 return false; 9270 unsigned NumBits1 = VT1.getSizeInBits(); 9271 unsigned NumBits2 = VT2.getSizeInBits(); 9272 return NumBits1 > NumBits2; 9273 } 9274 9275 /// Check if it is profitable to hoist instruction in then/else to if. 9276 /// Not profitable if I and it's user can form a FMA instruction 9277 /// because we prefer FMSUB/FMADD. 9278 bool AArch64TargetLowering::isProfitableToHoist(Instruction *I) const { 9279 if (I->getOpcode() != Instruction::FMul) 9280 return true; 9281 9282 if (!I->hasOneUse()) 9283 return true; 9284 9285 Instruction *User = I->user_back(); 9286 9287 if (User && 9288 !(User->getOpcode() == Instruction::FSub || 9289 User->getOpcode() == Instruction::FAdd)) 9290 return true; 9291 9292 const TargetOptions &Options = getTargetMachine().Options; 9293 const Function *F = I->getFunction(); 9294 const DataLayout &DL = F->getParent()->getDataLayout(); 9295 Type *Ty = User->getOperand(0)->getType(); 9296 9297 return !(isFMAFasterThanFMulAndFAdd(*F, Ty) && 9298 isOperationLegalOrCustom(ISD::FMA, getValueType(DL, Ty)) && 9299 (Options.AllowFPOpFusion == FPOpFusion::Fast || 9300 Options.UnsafeFPMath)); 9301 } 9302 9303 // All 32-bit GPR operations implicitly zero the high-half of the corresponding 9304 // 64-bit GPR. 9305 bool AArch64TargetLowering::isZExtFree(Type *Ty1, Type *Ty2) const { 9306 if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy()) 9307 return false; 9308 unsigned NumBits1 = Ty1->getPrimitiveSizeInBits(); 9309 unsigned NumBits2 = Ty2->getPrimitiveSizeInBits(); 9310 return NumBits1 == 32 && NumBits2 == 64; 9311 } 9312 bool AArch64TargetLowering::isZExtFree(EVT VT1, EVT VT2) const { 9313 if (VT1.isVector() || VT2.isVector() || !VT1.isInteger() || !VT2.isInteger()) 9314 return false; 9315 unsigned NumBits1 = VT1.getSizeInBits(); 9316 unsigned NumBits2 = VT2.getSizeInBits(); 9317 return NumBits1 == 32 && NumBits2 == 64; 9318 } 9319 9320 bool AArch64TargetLowering::isZExtFree(SDValue Val, EVT VT2) const { 9321 EVT VT1 = Val.getValueType(); 9322 if (isZExtFree(VT1, VT2)) { 9323 return true; 9324 } 9325 9326 if (Val.getOpcode() != ISD::LOAD) 9327 return false; 9328 9329 // 8-, 16-, and 32-bit integer loads all implicitly zero-extend. 9330 return (VT1.isSimple() && !VT1.isVector() && VT1.isInteger() && 9331 VT2.isSimple() && !VT2.isVector() && VT2.isInteger() && 9332 VT1.getSizeInBits() <= 32); 9333 } 9334 9335 bool AArch64TargetLowering::isExtFreeImpl(const Instruction *Ext) const { 9336 if (isa<FPExtInst>(Ext)) 9337 return false; 9338 9339 // Vector types are not free. 9340 if (Ext->getType()->isVectorTy()) 9341 return false; 9342 9343 for (const Use &U : Ext->uses()) { 9344 // The extension is free if we can fold it with a left shift in an 9345 // addressing mode or an arithmetic operation: add, sub, and cmp. 9346 9347 // Is there a shift? 9348 const Instruction *Instr = cast<Instruction>(U.getUser()); 9349 9350 // Is this a constant shift? 9351 switch (Instr->getOpcode()) { 9352 case Instruction::Shl: 9353 if (!isa<ConstantInt>(Instr->getOperand(1))) 9354 return false; 9355 break; 9356 case Instruction::GetElementPtr: { 9357 gep_type_iterator GTI = gep_type_begin(Instr); 9358 auto &DL = Ext->getModule()->getDataLayout(); 9359 std::advance(GTI, U.getOperandNo()-1); 9360 Type *IdxTy = GTI.getIndexedType(); 9361 // This extension will end up with a shift because of the scaling factor. 9362 // 8-bit sized types have a scaling factor of 1, thus a shift amount of 0. 9363 // Get the shift amount based on the scaling factor: 9364 // log2(sizeof(IdxTy)) - log2(8). 9365 uint64_t ShiftAmt = 9366 countTrailingZeros(DL.getTypeStoreSizeInBits(IdxTy).getFixedSize()) - 3; 9367 // Is the constant foldable in the shift of the addressing mode? 9368 // I.e., shift amount is between 1 and 4 inclusive. 9369 if (ShiftAmt == 0 || ShiftAmt > 4) 9370 return false; 9371 break; 9372 } 9373 case Instruction::Trunc: 9374 // Check if this is a noop. 9375 // trunc(sext ty1 to ty2) to ty1. 9376 if (Instr->getType() == Ext->getOperand(0)->getType()) 9377 continue; 9378 LLVM_FALLTHROUGH; 9379 default: 9380 return false; 9381 } 9382 9383 // At this point we can use the bfm family, so this extension is free 9384 // for that use. 9385 } 9386 return true; 9387 } 9388 9389 /// Check if both Op1 and Op2 are shufflevector extracts of either the lower 9390 /// or upper half of the vector elements. 9391 static bool areExtractShuffleVectors(Value *Op1, Value *Op2) { 9392 auto areTypesHalfed = [](Value *FullV, Value *HalfV) { 9393 auto *FullTy = FullV->getType(); 9394 auto *HalfTy = HalfV->getType(); 9395 return FullTy->getPrimitiveSizeInBits().getFixedSize() == 9396 2 * HalfTy->getPrimitiveSizeInBits().getFixedSize(); 9397 }; 9398 9399 auto extractHalf = [](Value *FullV, Value *HalfV) { 9400 auto *FullVT = cast<VectorType>(FullV->getType()); 9401 auto *HalfVT = cast<VectorType>(HalfV->getType()); 9402 return FullVT->getNumElements() == 2 * HalfVT->getNumElements(); 9403 }; 9404 9405 ArrayRef<int> M1, M2; 9406 Value *S1Op1, *S2Op1; 9407 if (!match(Op1, m_Shuffle(m_Value(S1Op1), m_Undef(), m_Mask(M1))) || 9408 !match(Op2, m_Shuffle(m_Value(S2Op1), m_Undef(), m_Mask(M2)))) 9409 return false; 9410 9411 // Check that the operands are half as wide as the result and we extract 9412 // half of the elements of the input vectors. 9413 if (!areTypesHalfed(S1Op1, Op1) || !areTypesHalfed(S2Op1, Op2) || 9414 !extractHalf(S1Op1, Op1) || !extractHalf(S2Op1, Op2)) 9415 return false; 9416 9417 // Check the mask extracts either the lower or upper half of vector 9418 // elements. 9419 int M1Start = -1; 9420 int M2Start = -1; 9421 int NumElements = cast<VectorType>(Op1->getType())->getNumElements() * 2; 9422 if (!ShuffleVectorInst::isExtractSubvectorMask(M1, NumElements, M1Start) || 9423 !ShuffleVectorInst::isExtractSubvectorMask(M2, NumElements, M2Start) || 9424 M1Start != M2Start || (M1Start != 0 && M2Start != (NumElements / 2))) 9425 return false; 9426 9427 return true; 9428 } 9429 9430 /// Check if Ext1 and Ext2 are extends of the same type, doubling the bitwidth 9431 /// of the vector elements. 9432 static bool areExtractExts(Value *Ext1, Value *Ext2) { 9433 auto areExtDoubled = [](Instruction *Ext) { 9434 return Ext->getType()->getScalarSizeInBits() == 9435 2 * Ext->getOperand(0)->getType()->getScalarSizeInBits(); 9436 }; 9437 9438 if (!match(Ext1, m_ZExtOrSExt(m_Value())) || 9439 !match(Ext2, m_ZExtOrSExt(m_Value())) || 9440 !areExtDoubled(cast<Instruction>(Ext1)) || 9441 !areExtDoubled(cast<Instruction>(Ext2))) 9442 return false; 9443 9444 return true; 9445 } 9446 9447 /// Check if Op could be used with vmull_high_p64 intrinsic. 9448 static bool isOperandOfVmullHighP64(Value *Op) { 9449 Value *VectorOperand = nullptr; 9450 ConstantInt *ElementIndex = nullptr; 9451 return match(Op, m_ExtractElt(m_Value(VectorOperand), 9452 m_ConstantInt(ElementIndex))) && 9453 ElementIndex->getValue() == 1 && 9454 isa<FixedVectorType>(VectorOperand->getType()) && 9455 cast<FixedVectorType>(VectorOperand->getType())->getNumElements() == 2; 9456 } 9457 9458 /// Check if Op1 and Op2 could be used with vmull_high_p64 intrinsic. 9459 static bool areOperandsOfVmullHighP64(Value *Op1, Value *Op2) { 9460 return isOperandOfVmullHighP64(Op1) && isOperandOfVmullHighP64(Op2); 9461 } 9462 9463 /// Check if sinking \p I's operands to I's basic block is profitable, because 9464 /// the operands can be folded into a target instruction, e.g. 9465 /// shufflevectors extracts and/or sext/zext can be folded into (u,s)subl(2). 9466 bool AArch64TargetLowering::shouldSinkOperands( 9467 Instruction *I, SmallVectorImpl<Use *> &Ops) const { 9468 if (!I->getType()->isVectorTy()) 9469 return false; 9470 9471 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(I)) { 9472 switch (II->getIntrinsicID()) { 9473 case Intrinsic::aarch64_neon_umull: 9474 if (!areExtractShuffleVectors(II->getOperand(0), II->getOperand(1))) 9475 return false; 9476 Ops.push_back(&II->getOperandUse(0)); 9477 Ops.push_back(&II->getOperandUse(1)); 9478 return true; 9479 9480 case Intrinsic::aarch64_neon_pmull64: 9481 if (!areOperandsOfVmullHighP64(II->getArgOperand(0), 9482 II->getArgOperand(1))) 9483 return false; 9484 Ops.push_back(&II->getArgOperandUse(0)); 9485 Ops.push_back(&II->getArgOperandUse(1)); 9486 return true; 9487 9488 default: 9489 return false; 9490 } 9491 } 9492 9493 switch (I->getOpcode()) { 9494 case Instruction::Sub: 9495 case Instruction::Add: { 9496 if (!areExtractExts(I->getOperand(0), I->getOperand(1))) 9497 return false; 9498 9499 // If the exts' operands extract either the lower or upper elements, we 9500 // can sink them too. 9501 auto Ext1 = cast<Instruction>(I->getOperand(0)); 9502 auto Ext2 = cast<Instruction>(I->getOperand(1)); 9503 if (areExtractShuffleVectors(Ext1, Ext2)) { 9504 Ops.push_back(&Ext1->getOperandUse(0)); 9505 Ops.push_back(&Ext2->getOperandUse(0)); 9506 } 9507 9508 Ops.push_back(&I->getOperandUse(0)); 9509 Ops.push_back(&I->getOperandUse(1)); 9510 9511 return true; 9512 } 9513 default: 9514 return false; 9515 } 9516 return false; 9517 } 9518 9519 bool AArch64TargetLowering::hasPairedLoad(EVT LoadedType, 9520 unsigned &RequiredAligment) const { 9521 if (!LoadedType.isSimple() || 9522 (!LoadedType.isInteger() && !LoadedType.isFloatingPoint())) 9523 return false; 9524 // Cyclone supports unaligned accesses. 9525 RequiredAligment = 0; 9526 unsigned NumBits = LoadedType.getSizeInBits(); 9527 return NumBits == 32 || NumBits == 64; 9528 } 9529 9530 /// A helper function for determining the number of interleaved accesses we 9531 /// will generate when lowering accesses of the given type. 9532 unsigned 9533 AArch64TargetLowering::getNumInterleavedAccesses(VectorType *VecTy, 9534 const DataLayout &DL) const { 9535 return (DL.getTypeSizeInBits(VecTy) + 127) / 128; 9536 } 9537 9538 MachineMemOperand::Flags 9539 AArch64TargetLowering::getTargetMMOFlags(const Instruction &I) const { 9540 if (Subtarget->getProcFamily() == AArch64Subtarget::Falkor && 9541 I.getMetadata(FALKOR_STRIDED_ACCESS_MD) != nullptr) 9542 return MOStridedAccess; 9543 return MachineMemOperand::MONone; 9544 } 9545 9546 bool AArch64TargetLowering::isLegalInterleavedAccessType( 9547 VectorType *VecTy, const DataLayout &DL) const { 9548 9549 unsigned VecSize = DL.getTypeSizeInBits(VecTy); 9550 unsigned ElSize = DL.getTypeSizeInBits(VecTy->getElementType()); 9551 9552 // Ensure the number of vector elements is greater than 1. 9553 if (VecTy->getNumElements() < 2) 9554 return false; 9555 9556 // Ensure the element type is legal. 9557 if (ElSize != 8 && ElSize != 16 && ElSize != 32 && ElSize != 64) 9558 return false; 9559 9560 // Ensure the total vector size is 64 or a multiple of 128. Types larger than 9561 // 128 will be split into multiple interleaved accesses. 9562 return VecSize == 64 || VecSize % 128 == 0; 9563 } 9564 9565 /// Lower an interleaved load into a ldN intrinsic. 9566 /// 9567 /// E.g. Lower an interleaved load (Factor = 2): 9568 /// %wide.vec = load <8 x i32>, <8 x i32>* %ptr 9569 /// %v0 = shuffle %wide.vec, undef, <0, 2, 4, 6> ; Extract even elements 9570 /// %v1 = shuffle %wide.vec, undef, <1, 3, 5, 7> ; Extract odd elements 9571 /// 9572 /// Into: 9573 /// %ld2 = { <4 x i32>, <4 x i32> } call llvm.aarch64.neon.ld2(%ptr) 9574 /// %vec0 = extractelement { <4 x i32>, <4 x i32> } %ld2, i32 0 9575 /// %vec1 = extractelement { <4 x i32>, <4 x i32> } %ld2, i32 1 9576 bool AArch64TargetLowering::lowerInterleavedLoad( 9577 LoadInst *LI, ArrayRef<ShuffleVectorInst *> Shuffles, 9578 ArrayRef<unsigned> Indices, unsigned Factor) const { 9579 assert(Factor >= 2 && Factor <= getMaxSupportedInterleaveFactor() && 9580 "Invalid interleave factor"); 9581 assert(!Shuffles.empty() && "Empty shufflevector input"); 9582 assert(Shuffles.size() == Indices.size() && 9583 "Unmatched number of shufflevectors and indices"); 9584 9585 const DataLayout &DL = LI->getModule()->getDataLayout(); 9586 9587 VectorType *VecTy = Shuffles[0]->getType(); 9588 9589 // Skip if we do not have NEON and skip illegal vector types. We can 9590 // "legalize" wide vector types into multiple interleaved accesses as long as 9591 // the vector types are divisible by 128. 9592 if (!Subtarget->hasNEON() || !isLegalInterleavedAccessType(VecTy, DL)) 9593 return false; 9594 9595 unsigned NumLoads = getNumInterleavedAccesses(VecTy, DL); 9596 9597 // A pointer vector can not be the return type of the ldN intrinsics. Need to 9598 // load integer vectors first and then convert to pointer vectors. 9599 Type *EltTy = VecTy->getElementType(); 9600 if (EltTy->isPointerTy()) 9601 VecTy = 9602 FixedVectorType::get(DL.getIntPtrType(EltTy), VecTy->getNumElements()); 9603 9604 IRBuilder<> Builder(LI); 9605 9606 // The base address of the load. 9607 Value *BaseAddr = LI->getPointerOperand(); 9608 9609 if (NumLoads > 1) { 9610 // If we're going to generate more than one load, reset the sub-vector type 9611 // to something legal. 9612 VecTy = FixedVectorType::get(VecTy->getElementType(), 9613 VecTy->getNumElements() / NumLoads); 9614 9615 // We will compute the pointer operand of each load from the original base 9616 // address using GEPs. Cast the base address to a pointer to the scalar 9617 // element type. 9618 BaseAddr = Builder.CreateBitCast( 9619 BaseAddr, 9620 VecTy->getElementType()->getPointerTo(LI->getPointerAddressSpace())); 9621 } 9622 9623 Type *PtrTy = VecTy->getPointerTo(LI->getPointerAddressSpace()); 9624 Type *Tys[2] = {VecTy, PtrTy}; 9625 static const Intrinsic::ID LoadInts[3] = {Intrinsic::aarch64_neon_ld2, 9626 Intrinsic::aarch64_neon_ld3, 9627 Intrinsic::aarch64_neon_ld4}; 9628 Function *LdNFunc = 9629 Intrinsic::getDeclaration(LI->getModule(), LoadInts[Factor - 2], Tys); 9630 9631 // Holds sub-vectors extracted from the load intrinsic return values. The 9632 // sub-vectors are associated with the shufflevector instructions they will 9633 // replace. 9634 DenseMap<ShuffleVectorInst *, SmallVector<Value *, 4>> SubVecs; 9635 9636 for (unsigned LoadCount = 0; LoadCount < NumLoads; ++LoadCount) { 9637 9638 // If we're generating more than one load, compute the base address of 9639 // subsequent loads as an offset from the previous. 9640 if (LoadCount > 0) 9641 BaseAddr = Builder.CreateConstGEP1_32(VecTy->getElementType(), BaseAddr, 9642 VecTy->getNumElements() * Factor); 9643 9644 CallInst *LdN = Builder.CreateCall( 9645 LdNFunc, Builder.CreateBitCast(BaseAddr, PtrTy), "ldN"); 9646 9647 // Extract and store the sub-vectors returned by the load intrinsic. 9648 for (unsigned i = 0; i < Shuffles.size(); i++) { 9649 ShuffleVectorInst *SVI = Shuffles[i]; 9650 unsigned Index = Indices[i]; 9651 9652 Value *SubVec = Builder.CreateExtractValue(LdN, Index); 9653 9654 // Convert the integer vector to pointer vector if the element is pointer. 9655 if (EltTy->isPointerTy()) 9656 SubVec = Builder.CreateIntToPtr( 9657 SubVec, FixedVectorType::get(SVI->getType()->getElementType(), 9658 VecTy->getNumElements())); 9659 SubVecs[SVI].push_back(SubVec); 9660 } 9661 } 9662 9663 // Replace uses of the shufflevector instructions with the sub-vectors 9664 // returned by the load intrinsic. If a shufflevector instruction is 9665 // associated with more than one sub-vector, those sub-vectors will be 9666 // concatenated into a single wide vector. 9667 for (ShuffleVectorInst *SVI : Shuffles) { 9668 auto &SubVec = SubVecs[SVI]; 9669 auto *WideVec = 9670 SubVec.size() > 1 ? concatenateVectors(Builder, SubVec) : SubVec[0]; 9671 SVI->replaceAllUsesWith(WideVec); 9672 } 9673 9674 return true; 9675 } 9676 9677 /// Lower an interleaved store into a stN intrinsic. 9678 /// 9679 /// E.g. Lower an interleaved store (Factor = 3): 9680 /// %i.vec = shuffle <8 x i32> %v0, <8 x i32> %v1, 9681 /// <0, 4, 8, 1, 5, 9, 2, 6, 10, 3, 7, 11> 9682 /// store <12 x i32> %i.vec, <12 x i32>* %ptr 9683 /// 9684 /// Into: 9685 /// %sub.v0 = shuffle <8 x i32> %v0, <8 x i32> v1, <0, 1, 2, 3> 9686 /// %sub.v1 = shuffle <8 x i32> %v0, <8 x i32> v1, <4, 5, 6, 7> 9687 /// %sub.v2 = shuffle <8 x i32> %v0, <8 x i32> v1, <8, 9, 10, 11> 9688 /// call void llvm.aarch64.neon.st3(%sub.v0, %sub.v1, %sub.v2, %ptr) 9689 /// 9690 /// Note that the new shufflevectors will be removed and we'll only generate one 9691 /// st3 instruction in CodeGen. 9692 /// 9693 /// Example for a more general valid mask (Factor 3). Lower: 9694 /// %i.vec = shuffle <32 x i32> %v0, <32 x i32> %v1, 9695 /// <4, 32, 16, 5, 33, 17, 6, 34, 18, 7, 35, 19> 9696 /// store <12 x i32> %i.vec, <12 x i32>* %ptr 9697 /// 9698 /// Into: 9699 /// %sub.v0 = shuffle <32 x i32> %v0, <32 x i32> v1, <4, 5, 6, 7> 9700 /// %sub.v1 = shuffle <32 x i32> %v0, <32 x i32> v1, <32, 33, 34, 35> 9701 /// %sub.v2 = shuffle <32 x i32> %v0, <32 x i32> v1, <16, 17, 18, 19> 9702 /// call void llvm.aarch64.neon.st3(%sub.v0, %sub.v1, %sub.v2, %ptr) 9703 bool AArch64TargetLowering::lowerInterleavedStore(StoreInst *SI, 9704 ShuffleVectorInst *SVI, 9705 unsigned Factor) const { 9706 assert(Factor >= 2 && Factor <= getMaxSupportedInterleaveFactor() && 9707 "Invalid interleave factor"); 9708 9709 VectorType *VecTy = SVI->getType(); 9710 assert(VecTy->getNumElements() % Factor == 0 && "Invalid interleaved store"); 9711 9712 unsigned LaneLen = VecTy->getNumElements() / Factor; 9713 Type *EltTy = VecTy->getElementType(); 9714 auto *SubVecTy = FixedVectorType::get(EltTy, LaneLen); 9715 9716 const DataLayout &DL = SI->getModule()->getDataLayout(); 9717 9718 // Skip if we do not have NEON and skip illegal vector types. We can 9719 // "legalize" wide vector types into multiple interleaved accesses as long as 9720 // the vector types are divisible by 128. 9721 if (!Subtarget->hasNEON() || !isLegalInterleavedAccessType(SubVecTy, DL)) 9722 return false; 9723 9724 unsigned NumStores = getNumInterleavedAccesses(SubVecTy, DL); 9725 9726 Value *Op0 = SVI->getOperand(0); 9727 Value *Op1 = SVI->getOperand(1); 9728 IRBuilder<> Builder(SI); 9729 9730 // StN intrinsics don't support pointer vectors as arguments. Convert pointer 9731 // vectors to integer vectors. 9732 if (EltTy->isPointerTy()) { 9733 Type *IntTy = DL.getIntPtrType(EltTy); 9734 unsigned NumOpElts = cast<VectorType>(Op0->getType())->getNumElements(); 9735 9736 // Convert to the corresponding integer vector. 9737 auto *IntVecTy = FixedVectorType::get(IntTy, NumOpElts); 9738 Op0 = Builder.CreatePtrToInt(Op0, IntVecTy); 9739 Op1 = Builder.CreatePtrToInt(Op1, IntVecTy); 9740 9741 SubVecTy = FixedVectorType::get(IntTy, LaneLen); 9742 } 9743 9744 // The base address of the store. 9745 Value *BaseAddr = SI->getPointerOperand(); 9746 9747 if (NumStores > 1) { 9748 // If we're going to generate more than one store, reset the lane length 9749 // and sub-vector type to something legal. 9750 LaneLen /= NumStores; 9751 SubVecTy = FixedVectorType::get(SubVecTy->getElementType(), LaneLen); 9752 9753 // We will compute the pointer operand of each store from the original base 9754 // address using GEPs. Cast the base address to a pointer to the scalar 9755 // element type. 9756 BaseAddr = Builder.CreateBitCast( 9757 BaseAddr, 9758 SubVecTy->getElementType()->getPointerTo(SI->getPointerAddressSpace())); 9759 } 9760 9761 auto Mask = SVI->getShuffleMask(); 9762 9763 Type *PtrTy = SubVecTy->getPointerTo(SI->getPointerAddressSpace()); 9764 Type *Tys[2] = {SubVecTy, PtrTy}; 9765 static const Intrinsic::ID StoreInts[3] = {Intrinsic::aarch64_neon_st2, 9766 Intrinsic::aarch64_neon_st3, 9767 Intrinsic::aarch64_neon_st4}; 9768 Function *StNFunc = 9769 Intrinsic::getDeclaration(SI->getModule(), StoreInts[Factor - 2], Tys); 9770 9771 for (unsigned StoreCount = 0; StoreCount < NumStores; ++StoreCount) { 9772 9773 SmallVector<Value *, 5> Ops; 9774 9775 // Split the shufflevector operands into sub vectors for the new stN call. 9776 for (unsigned i = 0; i < Factor; i++) { 9777 unsigned IdxI = StoreCount * LaneLen * Factor + i; 9778 if (Mask[IdxI] >= 0) { 9779 Ops.push_back(Builder.CreateShuffleVector( 9780 Op0, Op1, createSequentialMask(Mask[IdxI], LaneLen, 0))); 9781 } else { 9782 unsigned StartMask = 0; 9783 for (unsigned j = 1; j < LaneLen; j++) { 9784 unsigned IdxJ = StoreCount * LaneLen * Factor + j; 9785 if (Mask[IdxJ * Factor + IdxI] >= 0) { 9786 StartMask = Mask[IdxJ * Factor + IdxI] - IdxJ; 9787 break; 9788 } 9789 } 9790 // Note: Filling undef gaps with random elements is ok, since 9791 // those elements were being written anyway (with undefs). 9792 // In the case of all undefs we're defaulting to using elems from 0 9793 // Note: StartMask cannot be negative, it's checked in 9794 // isReInterleaveMask 9795 Ops.push_back(Builder.CreateShuffleVector( 9796 Op0, Op1, createSequentialMask(StartMask, LaneLen, 0))); 9797 } 9798 } 9799 9800 // If we generating more than one store, we compute the base address of 9801 // subsequent stores as an offset from the previous. 9802 if (StoreCount > 0) 9803 BaseAddr = Builder.CreateConstGEP1_32(SubVecTy->getElementType(), 9804 BaseAddr, LaneLen * Factor); 9805 9806 Ops.push_back(Builder.CreateBitCast(BaseAddr, PtrTy)); 9807 Builder.CreateCall(StNFunc, Ops); 9808 } 9809 return true; 9810 } 9811 9812 // Lower an SVE structured load intrinsic returning a tuple type to target 9813 // specific intrinsic taking the same input but returning a multi-result value 9814 // of the split tuple type. 9815 // 9816 // E.g. Lowering an LD3: 9817 // 9818 // call <vscale x 12 x i32> @llvm.aarch64.sve.ld3.nxv12i32( 9819 // <vscale x 4 x i1> %pred, 9820 // <vscale x 4 x i32>* %addr) 9821 // 9822 // Output DAG: 9823 // 9824 // t0: ch = EntryToken 9825 // t2: nxv4i1,ch = CopyFromReg t0, Register:nxv4i1 %0 9826 // t4: i64,ch = CopyFromReg t0, Register:i64 %1 9827 // t5: nxv4i32,nxv4i32,nxv4i32,ch = AArch64ISD::SVE_LD3 t0, t2, t4 9828 // t6: nxv12i32 = concat_vectors t5, t5:1, t5:2 9829 // 9830 // This is called pre-legalization to avoid widening/splitting issues with 9831 // non-power-of-2 tuple types used for LD3, such as nxv12i32. 9832 SDValue AArch64TargetLowering::LowerSVEStructLoad(unsigned Intrinsic, 9833 ArrayRef<SDValue> LoadOps, 9834 EVT VT, SelectionDAG &DAG, 9835 const SDLoc &DL) const { 9836 assert(VT.isScalableVector() && "Can only lower scalable vectors"); 9837 9838 unsigned N, Opcode; 9839 static std::map<unsigned, std::pair<unsigned, unsigned>> IntrinsicMap = { 9840 {Intrinsic::aarch64_sve_ld2, {2, AArch64ISD::SVE_LD2}}, 9841 {Intrinsic::aarch64_sve_ld3, {3, AArch64ISD::SVE_LD3}}, 9842 {Intrinsic::aarch64_sve_ld4, {4, AArch64ISD::SVE_LD4}}}; 9843 9844 std::tie(N, Opcode) = IntrinsicMap[Intrinsic]; 9845 assert(VT.getVectorElementCount().Min % N == 0 && 9846 "invalid tuple vector type!"); 9847 9848 EVT SplitVT = EVT::getVectorVT(*DAG.getContext(), VT.getVectorElementType(), 9849 VT.getVectorElementCount() / N); 9850 assert(isTypeLegal(SplitVT)); 9851 9852 SmallVector<EVT, 5> VTs(N, SplitVT); 9853 VTs.push_back(MVT::Other); // Chain 9854 SDVTList NodeTys = DAG.getVTList(VTs); 9855 9856 SDValue PseudoLoad = DAG.getNode(Opcode, DL, NodeTys, LoadOps); 9857 SmallVector<SDValue, 4> PseudoLoadOps; 9858 for (unsigned I = 0; I < N; ++I) 9859 PseudoLoadOps.push_back(SDValue(PseudoLoad.getNode(), I)); 9860 return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, PseudoLoadOps); 9861 } 9862 9863 EVT AArch64TargetLowering::getOptimalMemOpType( 9864 const MemOp &Op, const AttributeList &FuncAttributes) const { 9865 bool CanImplicitFloat = 9866 !FuncAttributes.hasFnAttribute(Attribute::NoImplicitFloat); 9867 bool CanUseNEON = Subtarget->hasNEON() && CanImplicitFloat; 9868 bool CanUseFP = Subtarget->hasFPARMv8() && CanImplicitFloat; 9869 // Only use AdvSIMD to implement memset of 32-byte and above. It would have 9870 // taken one instruction to materialize the v2i64 zero and one store (with 9871 // restrictive addressing mode). Just do i64 stores. 9872 bool IsSmallMemset = Op.isMemset() && Op.size() < 32; 9873 auto AlignmentIsAcceptable = [&](EVT VT, Align AlignCheck) { 9874 if (Op.isAligned(AlignCheck)) 9875 return true; 9876 bool Fast; 9877 return allowsMisalignedMemoryAccesses(VT, 0, 1, MachineMemOperand::MONone, 9878 &Fast) && 9879 Fast; 9880 }; 9881 9882 if (CanUseNEON && Op.isMemset() && !IsSmallMemset && 9883 AlignmentIsAcceptable(MVT::v2i64, Align(16))) 9884 return MVT::v2i64; 9885 if (CanUseFP && !IsSmallMemset && AlignmentIsAcceptable(MVT::f128, Align(16))) 9886 return MVT::f128; 9887 if (Op.size() >= 8 && AlignmentIsAcceptable(MVT::i64, Align(8))) 9888 return MVT::i64; 9889 if (Op.size() >= 4 && AlignmentIsAcceptable(MVT::i32, Align(4))) 9890 return MVT::i32; 9891 return MVT::Other; 9892 } 9893 9894 LLT AArch64TargetLowering::getOptimalMemOpLLT( 9895 const MemOp &Op, const AttributeList &FuncAttributes) const { 9896 bool CanImplicitFloat = 9897 !FuncAttributes.hasFnAttribute(Attribute::NoImplicitFloat); 9898 bool CanUseNEON = Subtarget->hasNEON() && CanImplicitFloat; 9899 bool CanUseFP = Subtarget->hasFPARMv8() && CanImplicitFloat; 9900 // Only use AdvSIMD to implement memset of 32-byte and above. It would have 9901 // taken one instruction to materialize the v2i64 zero and one store (with 9902 // restrictive addressing mode). Just do i64 stores. 9903 bool IsSmallMemset = Op.isMemset() && Op.size() < 32; 9904 auto AlignmentIsAcceptable = [&](EVT VT, Align AlignCheck) { 9905 if (Op.isAligned(AlignCheck)) 9906 return true; 9907 bool Fast; 9908 return allowsMisalignedMemoryAccesses(VT, 0, 1, MachineMemOperand::MONone, 9909 &Fast) && 9910 Fast; 9911 }; 9912 9913 if (CanUseNEON && Op.isMemset() && !IsSmallMemset && 9914 AlignmentIsAcceptable(MVT::v2i64, Align(16))) 9915 return LLT::vector(2, 64); 9916 if (CanUseFP && !IsSmallMemset && AlignmentIsAcceptable(MVT::f128, Align(16))) 9917 return LLT::scalar(128); 9918 if (Op.size() >= 8 && AlignmentIsAcceptable(MVT::i64, Align(8))) 9919 return LLT::scalar(64); 9920 if (Op.size() >= 4 && AlignmentIsAcceptable(MVT::i32, Align(4))) 9921 return LLT::scalar(32); 9922 return LLT(); 9923 } 9924 9925 // 12-bit optionally shifted immediates are legal for adds. 9926 bool AArch64TargetLowering::isLegalAddImmediate(int64_t Immed) const { 9927 if (Immed == std::numeric_limits<int64_t>::min()) { 9928 LLVM_DEBUG(dbgs() << "Illegal add imm " << Immed 9929 << ": avoid UB for INT64_MIN\n"); 9930 return false; 9931 } 9932 // Same encoding for add/sub, just flip the sign. 9933 Immed = std::abs(Immed); 9934 bool IsLegal = ((Immed >> 12) == 0 || 9935 ((Immed & 0xfff) == 0 && Immed >> 24 == 0)); 9936 LLVM_DEBUG(dbgs() << "Is " << Immed 9937 << " legal add imm: " << (IsLegal ? "yes" : "no") << "\n"); 9938 return IsLegal; 9939 } 9940 9941 // Integer comparisons are implemented with ADDS/SUBS, so the range of valid 9942 // immediates is the same as for an add or a sub. 9943 bool AArch64TargetLowering::isLegalICmpImmediate(int64_t Immed) const { 9944 return isLegalAddImmediate(Immed); 9945 } 9946 9947 /// isLegalAddressingMode - Return true if the addressing mode represented 9948 /// by AM is legal for this target, for a load/store of the specified type. 9949 bool AArch64TargetLowering::isLegalAddressingMode(const DataLayout &DL, 9950 const AddrMode &AM, Type *Ty, 9951 unsigned AS, Instruction *I) const { 9952 // AArch64 has five basic addressing modes: 9953 // reg 9954 // reg + 9-bit signed offset 9955 // reg + SIZE_IN_BYTES * 12-bit unsigned offset 9956 // reg1 + reg2 9957 // reg + SIZE_IN_BYTES * reg 9958 9959 // No global is ever allowed as a base. 9960 if (AM.BaseGV) 9961 return false; 9962 9963 // No reg+reg+imm addressing. 9964 if (AM.HasBaseReg && AM.BaseOffs && AM.Scale) 9965 return false; 9966 9967 // FIXME: Update this method to support scalable addressing modes. 9968 if (isa<ScalableVectorType>(Ty)) 9969 return AM.HasBaseReg && !AM.BaseOffs && !AM.Scale; 9970 9971 // check reg + imm case: 9972 // i.e., reg + 0, reg + imm9, reg + SIZE_IN_BYTES * uimm12 9973 uint64_t NumBytes = 0; 9974 if (Ty->isSized()) { 9975 uint64_t NumBits = DL.getTypeSizeInBits(Ty); 9976 NumBytes = NumBits / 8; 9977 if (!isPowerOf2_64(NumBits)) 9978 NumBytes = 0; 9979 } 9980 9981 if (!AM.Scale) { 9982 int64_t Offset = AM.BaseOffs; 9983 9984 // 9-bit signed offset 9985 if (isInt<9>(Offset)) 9986 return true; 9987 9988 // 12-bit unsigned offset 9989 unsigned shift = Log2_64(NumBytes); 9990 if (NumBytes && Offset > 0 && (Offset / NumBytes) <= (1LL << 12) - 1 && 9991 // Must be a multiple of NumBytes (NumBytes is a power of 2) 9992 (Offset >> shift) << shift == Offset) 9993 return true; 9994 return false; 9995 } 9996 9997 // Check reg1 + SIZE_IN_BYTES * reg2 and reg1 + reg2 9998 9999 return AM.Scale == 1 || (AM.Scale > 0 && (uint64_t)AM.Scale == NumBytes); 10000 } 10001 10002 bool AArch64TargetLowering::shouldConsiderGEPOffsetSplit() const { 10003 // Consider splitting large offset of struct or array. 10004 return true; 10005 } 10006 10007 int AArch64TargetLowering::getScalingFactorCost(const DataLayout &DL, 10008 const AddrMode &AM, Type *Ty, 10009 unsigned AS) const { 10010 // Scaling factors are not free at all. 10011 // Operands | Rt Latency 10012 // ------------------------------------------- 10013 // Rt, [Xn, Xm] | 4 10014 // ------------------------------------------- 10015 // Rt, [Xn, Xm, lsl #imm] | Rn: 4 Rm: 5 10016 // Rt, [Xn, Wm, <extend> #imm] | 10017 if (isLegalAddressingMode(DL, AM, Ty, AS)) 10018 // Scale represents reg2 * scale, thus account for 1 if 10019 // it is not equal to 0 or 1. 10020 return AM.Scale != 0 && AM.Scale != 1; 10021 return -1; 10022 } 10023 10024 bool AArch64TargetLowering::isFMAFasterThanFMulAndFAdd( 10025 const MachineFunction &MF, EVT VT) const { 10026 VT = VT.getScalarType(); 10027 10028 if (!VT.isSimple()) 10029 return false; 10030 10031 switch (VT.getSimpleVT().SimpleTy) { 10032 case MVT::f32: 10033 case MVT::f64: 10034 return true; 10035 default: 10036 break; 10037 } 10038 10039 return false; 10040 } 10041 10042 bool AArch64TargetLowering::isFMAFasterThanFMulAndFAdd(const Function &F, 10043 Type *Ty) const { 10044 switch (Ty->getScalarType()->getTypeID()) { 10045 case Type::FloatTyID: 10046 case Type::DoubleTyID: 10047 return true; 10048 default: 10049 return false; 10050 } 10051 } 10052 10053 const MCPhysReg * 10054 AArch64TargetLowering::getScratchRegisters(CallingConv::ID) const { 10055 // LR is a callee-save register, but we must treat it as clobbered by any call 10056 // site. Hence we include LR in the scratch registers, which are in turn added 10057 // as implicit-defs for stackmaps and patchpoints. 10058 static const MCPhysReg ScratchRegs[] = { 10059 AArch64::X16, AArch64::X17, AArch64::LR, 0 10060 }; 10061 return ScratchRegs; 10062 } 10063 10064 bool 10065 AArch64TargetLowering::isDesirableToCommuteWithShift(const SDNode *N, 10066 CombineLevel Level) const { 10067 N = N->getOperand(0).getNode(); 10068 EVT VT = N->getValueType(0); 10069 // If N is unsigned bit extraction: ((x >> C) & mask), then do not combine 10070 // it with shift to let it be lowered to UBFX. 10071 if (N->getOpcode() == ISD::AND && (VT == MVT::i32 || VT == MVT::i64) && 10072 isa<ConstantSDNode>(N->getOperand(1))) { 10073 uint64_t TruncMask = N->getConstantOperandVal(1); 10074 if (isMask_64(TruncMask) && 10075 N->getOperand(0).getOpcode() == ISD::SRL && 10076 isa<ConstantSDNode>(N->getOperand(0)->getOperand(1))) 10077 return false; 10078 } 10079 return true; 10080 } 10081 10082 bool AArch64TargetLowering::shouldConvertConstantLoadToIntImm(const APInt &Imm, 10083 Type *Ty) const { 10084 assert(Ty->isIntegerTy()); 10085 10086 unsigned BitSize = Ty->getPrimitiveSizeInBits(); 10087 if (BitSize == 0) 10088 return false; 10089 10090 int64_t Val = Imm.getSExtValue(); 10091 if (Val == 0 || AArch64_AM::isLogicalImmediate(Val, BitSize)) 10092 return true; 10093 10094 if ((int64_t)Val < 0) 10095 Val = ~Val; 10096 if (BitSize == 32) 10097 Val &= (1LL << 32) - 1; 10098 10099 unsigned LZ = countLeadingZeros((uint64_t)Val); 10100 unsigned Shift = (63 - LZ) / 16; 10101 // MOVZ is free so return true for one or fewer MOVK. 10102 return Shift < 3; 10103 } 10104 10105 bool AArch64TargetLowering::isExtractSubvectorCheap(EVT ResVT, EVT SrcVT, 10106 unsigned Index) const { 10107 if (!isOperationLegalOrCustom(ISD::EXTRACT_SUBVECTOR, ResVT)) 10108 return false; 10109 10110 return (Index == 0 || Index == ResVT.getVectorNumElements()); 10111 } 10112 10113 /// Turn vector tests of the signbit in the form of: 10114 /// xor (sra X, elt_size(X)-1), -1 10115 /// into: 10116 /// cmge X, X, #0 10117 static SDValue foldVectorXorShiftIntoCmp(SDNode *N, SelectionDAG &DAG, 10118 const AArch64Subtarget *Subtarget) { 10119 EVT VT = N->getValueType(0); 10120 if (!Subtarget->hasNEON() || !VT.isVector()) 10121 return SDValue(); 10122 10123 // There must be a shift right algebraic before the xor, and the xor must be a 10124 // 'not' operation. 10125 SDValue Shift = N->getOperand(0); 10126 SDValue Ones = N->getOperand(1); 10127 if (Shift.getOpcode() != AArch64ISD::VASHR || !Shift.hasOneUse() || 10128 !ISD::isBuildVectorAllOnes(Ones.getNode())) 10129 return SDValue(); 10130 10131 // The shift should be smearing the sign bit across each vector element. 10132 auto *ShiftAmt = dyn_cast<ConstantSDNode>(Shift.getOperand(1)); 10133 EVT ShiftEltTy = Shift.getValueType().getVectorElementType(); 10134 if (!ShiftAmt || ShiftAmt->getZExtValue() != ShiftEltTy.getSizeInBits() - 1) 10135 return SDValue(); 10136 10137 return DAG.getNode(AArch64ISD::CMGEz, SDLoc(N), VT, Shift.getOperand(0)); 10138 } 10139 10140 // Generate SUBS and CSEL for integer abs. 10141 static SDValue performIntegerAbsCombine(SDNode *N, SelectionDAG &DAG) { 10142 EVT VT = N->getValueType(0); 10143 10144 SDValue N0 = N->getOperand(0); 10145 SDValue N1 = N->getOperand(1); 10146 SDLoc DL(N); 10147 10148 // Check pattern of XOR(ADD(X,Y), Y) where Y is SRA(X, size(X)-1) 10149 // and change it to SUB and CSEL. 10150 if (VT.isInteger() && N->getOpcode() == ISD::XOR && 10151 N0.getOpcode() == ISD::ADD && N0.getOperand(1) == N1 && 10152 N1.getOpcode() == ISD::SRA && N1.getOperand(0) == N0.getOperand(0)) 10153 if (ConstantSDNode *Y1C = dyn_cast<ConstantSDNode>(N1.getOperand(1))) 10154 if (Y1C->getAPIntValue() == VT.getSizeInBits() - 1) { 10155 SDValue Neg = DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, VT), 10156 N0.getOperand(0)); 10157 // Generate SUBS & CSEL. 10158 SDValue Cmp = 10159 DAG.getNode(AArch64ISD::SUBS, DL, DAG.getVTList(VT, MVT::i32), 10160 N0.getOperand(0), DAG.getConstant(0, DL, VT)); 10161 return DAG.getNode(AArch64ISD::CSEL, DL, VT, N0.getOperand(0), Neg, 10162 DAG.getConstant(AArch64CC::PL, DL, MVT::i32), 10163 SDValue(Cmp.getNode(), 1)); 10164 } 10165 return SDValue(); 10166 } 10167 10168 static SDValue performXorCombine(SDNode *N, SelectionDAG &DAG, 10169 TargetLowering::DAGCombinerInfo &DCI, 10170 const AArch64Subtarget *Subtarget) { 10171 if (DCI.isBeforeLegalizeOps()) 10172 return SDValue(); 10173 10174 if (SDValue Cmp = foldVectorXorShiftIntoCmp(N, DAG, Subtarget)) 10175 return Cmp; 10176 10177 return performIntegerAbsCombine(N, DAG); 10178 } 10179 10180 SDValue 10181 AArch64TargetLowering::BuildSDIVPow2(SDNode *N, const APInt &Divisor, 10182 SelectionDAG &DAG, 10183 SmallVectorImpl<SDNode *> &Created) const { 10184 AttributeList Attr = DAG.getMachineFunction().getFunction().getAttributes(); 10185 if (isIntDivCheap(N->getValueType(0), Attr)) 10186 return SDValue(N,0); // Lower SDIV as SDIV 10187 10188 // fold (sdiv X, pow2) 10189 EVT VT = N->getValueType(0); 10190 if ((VT != MVT::i32 && VT != MVT::i64) || 10191 !(Divisor.isPowerOf2() || (-Divisor).isPowerOf2())) 10192 return SDValue(); 10193 10194 SDLoc DL(N); 10195 SDValue N0 = N->getOperand(0); 10196 unsigned Lg2 = Divisor.countTrailingZeros(); 10197 SDValue Zero = DAG.getConstant(0, DL, VT); 10198 SDValue Pow2MinusOne = DAG.getConstant((1ULL << Lg2) - 1, DL, VT); 10199 10200 // Add (N0 < 0) ? Pow2 - 1 : 0; 10201 SDValue CCVal; 10202 SDValue Cmp = getAArch64Cmp(N0, Zero, ISD::SETLT, CCVal, DAG, DL); 10203 SDValue Add = DAG.getNode(ISD::ADD, DL, VT, N0, Pow2MinusOne); 10204 SDValue CSel = DAG.getNode(AArch64ISD::CSEL, DL, VT, Add, N0, CCVal, Cmp); 10205 10206 Created.push_back(Cmp.getNode()); 10207 Created.push_back(Add.getNode()); 10208 Created.push_back(CSel.getNode()); 10209 10210 // Divide by pow2. 10211 SDValue SRA = 10212 DAG.getNode(ISD::SRA, DL, VT, CSel, DAG.getConstant(Lg2, DL, MVT::i64)); 10213 10214 // If we're dividing by a positive value, we're done. Otherwise, we must 10215 // negate the result. 10216 if (Divisor.isNonNegative()) 10217 return SRA; 10218 10219 Created.push_back(SRA.getNode()); 10220 return DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, VT), SRA); 10221 } 10222 10223 static bool IsSVECntIntrinsic(SDValue S) { 10224 switch(getIntrinsicID(S.getNode())) { 10225 default: 10226 break; 10227 case Intrinsic::aarch64_sve_cntb: 10228 case Intrinsic::aarch64_sve_cnth: 10229 case Intrinsic::aarch64_sve_cntw: 10230 case Intrinsic::aarch64_sve_cntd: 10231 return true; 10232 } 10233 return false; 10234 } 10235 10236 static SDValue performMulCombine(SDNode *N, SelectionDAG &DAG, 10237 TargetLowering::DAGCombinerInfo &DCI, 10238 const AArch64Subtarget *Subtarget) { 10239 if (DCI.isBeforeLegalizeOps()) 10240 return SDValue(); 10241 10242 // The below optimizations require a constant RHS. 10243 if (!isa<ConstantSDNode>(N->getOperand(1))) 10244 return SDValue(); 10245 10246 SDValue N0 = N->getOperand(0); 10247 ConstantSDNode *C = cast<ConstantSDNode>(N->getOperand(1)); 10248 const APInt &ConstValue = C->getAPIntValue(); 10249 10250 // Allow the scaling to be folded into the `cnt` instruction by preventing 10251 // the scaling to be obscured here. This makes it easier to pattern match. 10252 if (IsSVECntIntrinsic(N0) || 10253 (N0->getOpcode() == ISD::TRUNCATE && 10254 (IsSVECntIntrinsic(N0->getOperand(0))))) 10255 if (ConstValue.sge(1) && ConstValue.sle(16)) 10256 return SDValue(); 10257 10258 // Multiplication of a power of two plus/minus one can be done more 10259 // cheaply as as shift+add/sub. For now, this is true unilaterally. If 10260 // future CPUs have a cheaper MADD instruction, this may need to be 10261 // gated on a subtarget feature. For Cyclone, 32-bit MADD is 4 cycles and 10262 // 64-bit is 5 cycles, so this is always a win. 10263 // More aggressively, some multiplications N0 * C can be lowered to 10264 // shift+add+shift if the constant C = A * B where A = 2^N + 1 and B = 2^M, 10265 // e.g. 6=3*2=(2+1)*2. 10266 // TODO: consider lowering more cases, e.g. C = 14, -6, -14 or even 45 10267 // which equals to (1+2)*16-(1+2). 10268 // TrailingZeroes is used to test if the mul can be lowered to 10269 // shift+add+shift. 10270 unsigned TrailingZeroes = ConstValue.countTrailingZeros(); 10271 if (TrailingZeroes) { 10272 // Conservatively do not lower to shift+add+shift if the mul might be 10273 // folded into smul or umul. 10274 if (N0->hasOneUse() && (isSignExtended(N0.getNode(), DAG) || 10275 isZeroExtended(N0.getNode(), DAG))) 10276 return SDValue(); 10277 // Conservatively do not lower to shift+add+shift if the mul might be 10278 // folded into madd or msub. 10279 if (N->hasOneUse() && (N->use_begin()->getOpcode() == ISD::ADD || 10280 N->use_begin()->getOpcode() == ISD::SUB)) 10281 return SDValue(); 10282 } 10283 // Use ShiftedConstValue instead of ConstValue to support both shift+add/sub 10284 // and shift+add+shift. 10285 APInt ShiftedConstValue = ConstValue.ashr(TrailingZeroes); 10286 10287 unsigned ShiftAmt, AddSubOpc; 10288 // Is the shifted value the LHS operand of the add/sub? 10289 bool ShiftValUseIsN0 = true; 10290 // Do we need to negate the result? 10291 bool NegateResult = false; 10292 10293 if (ConstValue.isNonNegative()) { 10294 // (mul x, 2^N + 1) => (add (shl x, N), x) 10295 // (mul x, 2^N - 1) => (sub (shl x, N), x) 10296 // (mul x, (2^N + 1) * 2^M) => (shl (add (shl x, N), x), M) 10297 APInt SCVMinus1 = ShiftedConstValue - 1; 10298 APInt CVPlus1 = ConstValue + 1; 10299 if (SCVMinus1.isPowerOf2()) { 10300 ShiftAmt = SCVMinus1.logBase2(); 10301 AddSubOpc = ISD::ADD; 10302 } else if (CVPlus1.isPowerOf2()) { 10303 ShiftAmt = CVPlus1.logBase2(); 10304 AddSubOpc = ISD::SUB; 10305 } else 10306 return SDValue(); 10307 } else { 10308 // (mul x, -(2^N - 1)) => (sub x, (shl x, N)) 10309 // (mul x, -(2^N + 1)) => - (add (shl x, N), x) 10310 APInt CVNegPlus1 = -ConstValue + 1; 10311 APInt CVNegMinus1 = -ConstValue - 1; 10312 if (CVNegPlus1.isPowerOf2()) { 10313 ShiftAmt = CVNegPlus1.logBase2(); 10314 AddSubOpc = ISD::SUB; 10315 ShiftValUseIsN0 = false; 10316 } else if (CVNegMinus1.isPowerOf2()) { 10317 ShiftAmt = CVNegMinus1.logBase2(); 10318 AddSubOpc = ISD::ADD; 10319 NegateResult = true; 10320 } else 10321 return SDValue(); 10322 } 10323 10324 SDLoc DL(N); 10325 EVT VT = N->getValueType(0); 10326 SDValue ShiftedVal = DAG.getNode(ISD::SHL, DL, VT, N0, 10327 DAG.getConstant(ShiftAmt, DL, MVT::i64)); 10328 10329 SDValue AddSubN0 = ShiftValUseIsN0 ? ShiftedVal : N0; 10330 SDValue AddSubN1 = ShiftValUseIsN0 ? N0 : ShiftedVal; 10331 SDValue Res = DAG.getNode(AddSubOpc, DL, VT, AddSubN0, AddSubN1); 10332 assert(!(NegateResult && TrailingZeroes) && 10333 "NegateResult and TrailingZeroes cannot both be true for now."); 10334 // Negate the result. 10335 if (NegateResult) 10336 return DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, VT), Res); 10337 // Shift the result. 10338 if (TrailingZeroes) 10339 return DAG.getNode(ISD::SHL, DL, VT, Res, 10340 DAG.getConstant(TrailingZeroes, DL, MVT::i64)); 10341 return Res; 10342 } 10343 10344 static SDValue performVectorCompareAndMaskUnaryOpCombine(SDNode *N, 10345 SelectionDAG &DAG) { 10346 // Take advantage of vector comparisons producing 0 or -1 in each lane to 10347 // optimize away operation when it's from a constant. 10348 // 10349 // The general transformation is: 10350 // UNARYOP(AND(VECTOR_CMP(x,y), constant)) --> 10351 // AND(VECTOR_CMP(x,y), constant2) 10352 // constant2 = UNARYOP(constant) 10353 10354 // Early exit if this isn't a vector operation, the operand of the 10355 // unary operation isn't a bitwise AND, or if the sizes of the operations 10356 // aren't the same. 10357 EVT VT = N->getValueType(0); 10358 if (!VT.isVector() || N->getOperand(0)->getOpcode() != ISD::AND || 10359 N->getOperand(0)->getOperand(0)->getOpcode() != ISD::SETCC || 10360 VT.getSizeInBits() != N->getOperand(0)->getValueType(0).getSizeInBits()) 10361 return SDValue(); 10362 10363 // Now check that the other operand of the AND is a constant. We could 10364 // make the transformation for non-constant splats as well, but it's unclear 10365 // that would be a benefit as it would not eliminate any operations, just 10366 // perform one more step in scalar code before moving to the vector unit. 10367 if (BuildVectorSDNode *BV = 10368 dyn_cast<BuildVectorSDNode>(N->getOperand(0)->getOperand(1))) { 10369 // Bail out if the vector isn't a constant. 10370 if (!BV->isConstant()) 10371 return SDValue(); 10372 10373 // Everything checks out. Build up the new and improved node. 10374 SDLoc DL(N); 10375 EVT IntVT = BV->getValueType(0); 10376 // Create a new constant of the appropriate type for the transformed 10377 // DAG. 10378 SDValue SourceConst = DAG.getNode(N->getOpcode(), DL, VT, SDValue(BV, 0)); 10379 // The AND node needs bitcasts to/from an integer vector type around it. 10380 SDValue MaskConst = DAG.getNode(ISD::BITCAST, DL, IntVT, SourceConst); 10381 SDValue NewAnd = DAG.getNode(ISD::AND, DL, IntVT, 10382 N->getOperand(0)->getOperand(0), MaskConst); 10383 SDValue Res = DAG.getNode(ISD::BITCAST, DL, VT, NewAnd); 10384 return Res; 10385 } 10386 10387 return SDValue(); 10388 } 10389 10390 static SDValue performIntToFpCombine(SDNode *N, SelectionDAG &DAG, 10391 const AArch64Subtarget *Subtarget) { 10392 // First try to optimize away the conversion when it's conditionally from 10393 // a constant. Vectors only. 10394 if (SDValue Res = performVectorCompareAndMaskUnaryOpCombine(N, DAG)) 10395 return Res; 10396 10397 EVT VT = N->getValueType(0); 10398 if (VT != MVT::f32 && VT != MVT::f64) 10399 return SDValue(); 10400 10401 // Only optimize when the source and destination types have the same width. 10402 if (VT.getSizeInBits() != N->getOperand(0).getValueSizeInBits()) 10403 return SDValue(); 10404 10405 // If the result of an integer load is only used by an integer-to-float 10406 // conversion, use a fp load instead and a AdvSIMD scalar {S|U}CVTF instead. 10407 // This eliminates an "integer-to-vector-move" UOP and improves throughput. 10408 SDValue N0 = N->getOperand(0); 10409 if (Subtarget->hasNEON() && ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() && 10410 // Do not change the width of a volatile load. 10411 !cast<LoadSDNode>(N0)->isVolatile()) { 10412 LoadSDNode *LN0 = cast<LoadSDNode>(N0); 10413 SDValue Load = DAG.getLoad(VT, SDLoc(N), LN0->getChain(), LN0->getBasePtr(), 10414 LN0->getPointerInfo(), LN0->getAlignment(), 10415 LN0->getMemOperand()->getFlags()); 10416 10417 // Make sure successors of the original load stay after it by updating them 10418 // to use the new Chain. 10419 DAG.ReplaceAllUsesOfValueWith(SDValue(LN0, 1), Load.getValue(1)); 10420 10421 unsigned Opcode = 10422 (N->getOpcode() == ISD::SINT_TO_FP) ? AArch64ISD::SITOF : AArch64ISD::UITOF; 10423 return DAG.getNode(Opcode, SDLoc(N), VT, Load); 10424 } 10425 10426 return SDValue(); 10427 } 10428 10429 /// Fold a floating-point multiply by power of two into floating-point to 10430 /// fixed-point conversion. 10431 static SDValue performFpToIntCombine(SDNode *N, SelectionDAG &DAG, 10432 TargetLowering::DAGCombinerInfo &DCI, 10433 const AArch64Subtarget *Subtarget) { 10434 if (!Subtarget->hasNEON()) 10435 return SDValue(); 10436 10437 if (!N->getValueType(0).isSimple()) 10438 return SDValue(); 10439 10440 SDValue Op = N->getOperand(0); 10441 if (!Op.getValueType().isVector() || !Op.getValueType().isSimple() || 10442 Op.getOpcode() != ISD::FMUL) 10443 return SDValue(); 10444 10445 SDValue ConstVec = Op->getOperand(1); 10446 if (!isa<BuildVectorSDNode>(ConstVec)) 10447 return SDValue(); 10448 10449 MVT FloatTy = Op.getSimpleValueType().getVectorElementType(); 10450 uint32_t FloatBits = FloatTy.getSizeInBits(); 10451 if (FloatBits != 32 && FloatBits != 64) 10452 return SDValue(); 10453 10454 MVT IntTy = N->getSimpleValueType(0).getVectorElementType(); 10455 uint32_t IntBits = IntTy.getSizeInBits(); 10456 if (IntBits != 16 && IntBits != 32 && IntBits != 64) 10457 return SDValue(); 10458 10459 // Avoid conversions where iN is larger than the float (e.g., float -> i64). 10460 if (IntBits > FloatBits) 10461 return SDValue(); 10462 10463 BitVector UndefElements; 10464 BuildVectorSDNode *BV = cast<BuildVectorSDNode>(ConstVec); 10465 int32_t Bits = IntBits == 64 ? 64 : 32; 10466 int32_t C = BV->getConstantFPSplatPow2ToLog2Int(&UndefElements, Bits + 1); 10467 if (C == -1 || C == 0 || C > Bits) 10468 return SDValue(); 10469 10470 MVT ResTy; 10471 unsigned NumLanes = Op.getValueType().getVectorNumElements(); 10472 switch (NumLanes) { 10473 default: 10474 return SDValue(); 10475 case 2: 10476 ResTy = FloatBits == 32 ? MVT::v2i32 : MVT::v2i64; 10477 break; 10478 case 4: 10479 ResTy = FloatBits == 32 ? MVT::v4i32 : MVT::v4i64; 10480 break; 10481 } 10482 10483 if (ResTy == MVT::v4i64 && DCI.isBeforeLegalizeOps()) 10484 return SDValue(); 10485 10486 assert((ResTy != MVT::v4i64 || DCI.isBeforeLegalizeOps()) && 10487 "Illegal vector type after legalization"); 10488 10489 SDLoc DL(N); 10490 bool IsSigned = N->getOpcode() == ISD::FP_TO_SINT; 10491 unsigned IntrinsicOpcode = IsSigned ? Intrinsic::aarch64_neon_vcvtfp2fxs 10492 : Intrinsic::aarch64_neon_vcvtfp2fxu; 10493 SDValue FixConv = 10494 DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, ResTy, 10495 DAG.getConstant(IntrinsicOpcode, DL, MVT::i32), 10496 Op->getOperand(0), DAG.getConstant(C, DL, MVT::i32)); 10497 // We can handle smaller integers by generating an extra trunc. 10498 if (IntBits < FloatBits) 10499 FixConv = DAG.getNode(ISD::TRUNCATE, DL, N->getValueType(0), FixConv); 10500 10501 return FixConv; 10502 } 10503 10504 /// Fold a floating-point divide by power of two into fixed-point to 10505 /// floating-point conversion. 10506 static SDValue performFDivCombine(SDNode *N, SelectionDAG &DAG, 10507 TargetLowering::DAGCombinerInfo &DCI, 10508 const AArch64Subtarget *Subtarget) { 10509 if (!Subtarget->hasNEON()) 10510 return SDValue(); 10511 10512 SDValue Op = N->getOperand(0); 10513 unsigned Opc = Op->getOpcode(); 10514 if (!Op.getValueType().isVector() || !Op.getValueType().isSimple() || 10515 !Op.getOperand(0).getValueType().isSimple() || 10516 (Opc != ISD::SINT_TO_FP && Opc != ISD::UINT_TO_FP)) 10517 return SDValue(); 10518 10519 SDValue ConstVec = N->getOperand(1); 10520 if (!isa<BuildVectorSDNode>(ConstVec)) 10521 return SDValue(); 10522 10523 MVT IntTy = Op.getOperand(0).getSimpleValueType().getVectorElementType(); 10524 int32_t IntBits = IntTy.getSizeInBits(); 10525 if (IntBits != 16 && IntBits != 32 && IntBits != 64) 10526 return SDValue(); 10527 10528 MVT FloatTy = N->getSimpleValueType(0).getVectorElementType(); 10529 int32_t FloatBits = FloatTy.getSizeInBits(); 10530 if (FloatBits != 32 && FloatBits != 64) 10531 return SDValue(); 10532 10533 // Avoid conversions where iN is larger than the float (e.g., i64 -> float). 10534 if (IntBits > FloatBits) 10535 return SDValue(); 10536 10537 BitVector UndefElements; 10538 BuildVectorSDNode *BV = cast<BuildVectorSDNode>(ConstVec); 10539 int32_t C = BV->getConstantFPSplatPow2ToLog2Int(&UndefElements, FloatBits + 1); 10540 if (C == -1 || C == 0 || C > FloatBits) 10541 return SDValue(); 10542 10543 MVT ResTy; 10544 unsigned NumLanes = Op.getValueType().getVectorNumElements(); 10545 switch (NumLanes) { 10546 default: 10547 return SDValue(); 10548 case 2: 10549 ResTy = FloatBits == 32 ? MVT::v2i32 : MVT::v2i64; 10550 break; 10551 case 4: 10552 ResTy = FloatBits == 32 ? MVT::v4i32 : MVT::v4i64; 10553 break; 10554 } 10555 10556 if (ResTy == MVT::v4i64 && DCI.isBeforeLegalizeOps()) 10557 return SDValue(); 10558 10559 SDLoc DL(N); 10560 SDValue ConvInput = Op.getOperand(0); 10561 bool IsSigned = Opc == ISD::SINT_TO_FP; 10562 if (IntBits < FloatBits) 10563 ConvInput = DAG.getNode(IsSigned ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND, DL, 10564 ResTy, ConvInput); 10565 10566 unsigned IntrinsicOpcode = IsSigned ? Intrinsic::aarch64_neon_vcvtfxs2fp 10567 : Intrinsic::aarch64_neon_vcvtfxu2fp; 10568 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, Op.getValueType(), 10569 DAG.getConstant(IntrinsicOpcode, DL, MVT::i32), ConvInput, 10570 DAG.getConstant(C, DL, MVT::i32)); 10571 } 10572 10573 /// An EXTR instruction is made up of two shifts, ORed together. This helper 10574 /// searches for and classifies those shifts. 10575 static bool findEXTRHalf(SDValue N, SDValue &Src, uint32_t &ShiftAmount, 10576 bool &FromHi) { 10577 if (N.getOpcode() == ISD::SHL) 10578 FromHi = false; 10579 else if (N.getOpcode() == ISD::SRL) 10580 FromHi = true; 10581 else 10582 return false; 10583 10584 if (!isa<ConstantSDNode>(N.getOperand(1))) 10585 return false; 10586 10587 ShiftAmount = N->getConstantOperandVal(1); 10588 Src = N->getOperand(0); 10589 return true; 10590 } 10591 10592 /// EXTR instruction extracts a contiguous chunk of bits from two existing 10593 /// registers viewed as a high/low pair. This function looks for the pattern: 10594 /// <tt>(or (shl VAL1, \#N), (srl VAL2, \#RegWidth-N))</tt> and replaces it 10595 /// with an EXTR. Can't quite be done in TableGen because the two immediates 10596 /// aren't independent. 10597 static SDValue tryCombineToEXTR(SDNode *N, 10598 TargetLowering::DAGCombinerInfo &DCI) { 10599 SelectionDAG &DAG = DCI.DAG; 10600 SDLoc DL(N); 10601 EVT VT = N->getValueType(0); 10602 10603 assert(N->getOpcode() == ISD::OR && "Unexpected root"); 10604 10605 if (VT != MVT::i32 && VT != MVT::i64) 10606 return SDValue(); 10607 10608 SDValue LHS; 10609 uint32_t ShiftLHS = 0; 10610 bool LHSFromHi = false; 10611 if (!findEXTRHalf(N->getOperand(0), LHS, ShiftLHS, LHSFromHi)) 10612 return SDValue(); 10613 10614 SDValue RHS; 10615 uint32_t ShiftRHS = 0; 10616 bool RHSFromHi = false; 10617 if (!findEXTRHalf(N->getOperand(1), RHS, ShiftRHS, RHSFromHi)) 10618 return SDValue(); 10619 10620 // If they're both trying to come from the high part of the register, they're 10621 // not really an EXTR. 10622 if (LHSFromHi == RHSFromHi) 10623 return SDValue(); 10624 10625 if (ShiftLHS + ShiftRHS != VT.getSizeInBits()) 10626 return SDValue(); 10627 10628 if (LHSFromHi) { 10629 std::swap(LHS, RHS); 10630 std::swap(ShiftLHS, ShiftRHS); 10631 } 10632 10633 return DAG.getNode(AArch64ISD::EXTR, DL, VT, LHS, RHS, 10634 DAG.getConstant(ShiftRHS, DL, MVT::i64)); 10635 } 10636 10637 static SDValue tryCombineToBSL(SDNode *N, 10638 TargetLowering::DAGCombinerInfo &DCI) { 10639 EVT VT = N->getValueType(0); 10640 SelectionDAG &DAG = DCI.DAG; 10641 SDLoc DL(N); 10642 10643 if (!VT.isVector()) 10644 return SDValue(); 10645 10646 SDValue N0 = N->getOperand(0); 10647 if (N0.getOpcode() != ISD::AND) 10648 return SDValue(); 10649 10650 SDValue N1 = N->getOperand(1); 10651 if (N1.getOpcode() != ISD::AND) 10652 return SDValue(); 10653 10654 // We only have to look for constant vectors here since the general, variable 10655 // case can be handled in TableGen. 10656 unsigned Bits = VT.getScalarSizeInBits(); 10657 uint64_t BitMask = Bits == 64 ? -1ULL : ((1ULL << Bits) - 1); 10658 for (int i = 1; i >= 0; --i) 10659 for (int j = 1; j >= 0; --j) { 10660 BuildVectorSDNode *BVN0 = dyn_cast<BuildVectorSDNode>(N0->getOperand(i)); 10661 BuildVectorSDNode *BVN1 = dyn_cast<BuildVectorSDNode>(N1->getOperand(j)); 10662 if (!BVN0 || !BVN1) 10663 continue; 10664 10665 bool FoundMatch = true; 10666 for (unsigned k = 0; k < VT.getVectorNumElements(); ++k) { 10667 ConstantSDNode *CN0 = dyn_cast<ConstantSDNode>(BVN0->getOperand(k)); 10668 ConstantSDNode *CN1 = dyn_cast<ConstantSDNode>(BVN1->getOperand(k)); 10669 if (!CN0 || !CN1 || 10670 CN0->getZExtValue() != (BitMask & ~CN1->getZExtValue())) { 10671 FoundMatch = false; 10672 break; 10673 } 10674 } 10675 10676 if (FoundMatch) 10677 return DAG.getNode(AArch64ISD::BSP, DL, VT, SDValue(BVN0, 0), 10678 N0->getOperand(1 - i), N1->getOperand(1 - j)); 10679 } 10680 10681 return SDValue(); 10682 } 10683 10684 static SDValue performORCombine(SDNode *N, TargetLowering::DAGCombinerInfo &DCI, 10685 const AArch64Subtarget *Subtarget) { 10686 // Attempt to form an EXTR from (or (shl VAL1, #N), (srl VAL2, #RegWidth-N)) 10687 SelectionDAG &DAG = DCI.DAG; 10688 EVT VT = N->getValueType(0); 10689 10690 if (!DAG.getTargetLoweringInfo().isTypeLegal(VT)) 10691 return SDValue(); 10692 10693 if (SDValue Res = tryCombineToEXTR(N, DCI)) 10694 return Res; 10695 10696 if (SDValue Res = tryCombineToBSL(N, DCI)) 10697 return Res; 10698 10699 return SDValue(); 10700 } 10701 10702 static bool isConstantSplatVectorMaskForType(SDNode *N, EVT MemVT) { 10703 if (!MemVT.getVectorElementType().isSimple()) 10704 return false; 10705 10706 uint64_t MaskForTy = 0ull; 10707 switch (MemVT.getVectorElementType().getSimpleVT().SimpleTy) { 10708 case MVT::i8: 10709 MaskForTy = 0xffull; 10710 break; 10711 case MVT::i16: 10712 MaskForTy = 0xffffull; 10713 break; 10714 case MVT::i32: 10715 MaskForTy = 0xffffffffull; 10716 break; 10717 default: 10718 return false; 10719 break; 10720 } 10721 10722 if (N->getOpcode() == AArch64ISD::DUP || N->getOpcode() == ISD::SPLAT_VECTOR) 10723 if (auto *Op0 = dyn_cast<ConstantSDNode>(N->getOperand(0))) 10724 return Op0->getAPIntValue().getLimitedValue() == MaskForTy; 10725 10726 return false; 10727 } 10728 10729 static SDValue performSVEAndCombine(SDNode *N, 10730 TargetLowering::DAGCombinerInfo &DCI) { 10731 if (DCI.isBeforeLegalizeOps()) 10732 return SDValue(); 10733 10734 SelectionDAG &DAG = DCI.DAG; 10735 SDValue Src = N->getOperand(0); 10736 unsigned Opc = Src->getOpcode(); 10737 10738 // Zero/any extend of an unsigned unpack 10739 if (Opc == AArch64ISD::UUNPKHI || Opc == AArch64ISD::UUNPKLO) { 10740 SDValue UnpkOp = Src->getOperand(0); 10741 SDValue Dup = N->getOperand(1); 10742 10743 if (Dup.getOpcode() != AArch64ISD::DUP) 10744 return SDValue(); 10745 10746 SDLoc DL(N); 10747 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Dup->getOperand(0)); 10748 uint64_t ExtVal = C->getZExtValue(); 10749 10750 // If the mask is fully covered by the unpack, we don't need to push 10751 // a new AND onto the operand 10752 EVT EltTy = UnpkOp->getValueType(0).getVectorElementType(); 10753 if ((ExtVal == 0xFF && EltTy == MVT::i8) || 10754 (ExtVal == 0xFFFF && EltTy == MVT::i16) || 10755 (ExtVal == 0xFFFFFFFF && EltTy == MVT::i32)) 10756 return Src; 10757 10758 // Truncate to prevent a DUP with an over wide constant 10759 APInt Mask = C->getAPIntValue().trunc(EltTy.getSizeInBits()); 10760 10761 // Otherwise, make sure we propagate the AND to the operand 10762 // of the unpack 10763 Dup = DAG.getNode(AArch64ISD::DUP, DL, 10764 UnpkOp->getValueType(0), 10765 DAG.getConstant(Mask.zextOrTrunc(32), DL, MVT::i32)); 10766 10767 SDValue And = DAG.getNode(ISD::AND, DL, 10768 UnpkOp->getValueType(0), UnpkOp, Dup); 10769 10770 return DAG.getNode(Opc, DL, N->getValueType(0), And); 10771 } 10772 10773 SDValue Mask = N->getOperand(1); 10774 10775 if (!Src.hasOneUse()) 10776 return SDValue(); 10777 10778 EVT MemVT; 10779 10780 // SVE load instructions perform an implicit zero-extend, which makes them 10781 // perfect candidates for combining. 10782 switch (Opc) { 10783 case AArch64ISD::LD1: 10784 case AArch64ISD::LDNF1: 10785 case AArch64ISD::LDFF1: 10786 MemVT = cast<VTSDNode>(Src->getOperand(3))->getVT(); 10787 break; 10788 case AArch64ISD::GLD1: 10789 case AArch64ISD::GLD1_SCALED: 10790 case AArch64ISD::GLD1_SXTW: 10791 case AArch64ISD::GLD1_SXTW_SCALED: 10792 case AArch64ISD::GLD1_UXTW: 10793 case AArch64ISD::GLD1_UXTW_SCALED: 10794 case AArch64ISD::GLD1_IMM: 10795 case AArch64ISD::GLDFF1: 10796 case AArch64ISD::GLDFF1_SCALED: 10797 case AArch64ISD::GLDFF1_SXTW: 10798 case AArch64ISD::GLDFF1_SXTW_SCALED: 10799 case AArch64ISD::GLDFF1_UXTW: 10800 case AArch64ISD::GLDFF1_UXTW_SCALED: 10801 case AArch64ISD::GLDFF1_IMM: 10802 case AArch64ISD::GLDNT1: 10803 MemVT = cast<VTSDNode>(Src->getOperand(4))->getVT(); 10804 break; 10805 default: 10806 return SDValue(); 10807 } 10808 10809 if (isConstantSplatVectorMaskForType(Mask.getNode(), MemVT)) 10810 return Src; 10811 10812 return SDValue(); 10813 } 10814 10815 static SDValue performANDCombine(SDNode *N, 10816 TargetLowering::DAGCombinerInfo &DCI) { 10817 SelectionDAG &DAG = DCI.DAG; 10818 SDValue LHS = N->getOperand(0); 10819 EVT VT = N->getValueType(0); 10820 if (!VT.isVector() || !DAG.getTargetLoweringInfo().isTypeLegal(VT)) 10821 return SDValue(); 10822 10823 if (VT.isScalableVector()) 10824 return performSVEAndCombine(N, DCI); 10825 10826 BuildVectorSDNode *BVN = 10827 dyn_cast<BuildVectorSDNode>(N->getOperand(1).getNode()); 10828 if (!BVN) 10829 return SDValue(); 10830 10831 // AND does not accept an immediate, so check if we can use a BIC immediate 10832 // instruction instead. We do this here instead of using a (and x, (mvni imm)) 10833 // pattern in isel, because some immediates may be lowered to the preferred 10834 // (and x, (movi imm)) form, even though an mvni representation also exists. 10835 APInt DefBits(VT.getSizeInBits(), 0); 10836 APInt UndefBits(VT.getSizeInBits(), 0); 10837 if (resolveBuildVector(BVN, DefBits, UndefBits)) { 10838 SDValue NewOp; 10839 10840 DefBits = ~DefBits; 10841 if ((NewOp = tryAdvSIMDModImm32(AArch64ISD::BICi, SDValue(N, 0), DAG, 10842 DefBits, &LHS)) || 10843 (NewOp = tryAdvSIMDModImm16(AArch64ISD::BICi, SDValue(N, 0), DAG, 10844 DefBits, &LHS))) 10845 return NewOp; 10846 10847 UndefBits = ~UndefBits; 10848 if ((NewOp = tryAdvSIMDModImm32(AArch64ISD::BICi, SDValue(N, 0), DAG, 10849 UndefBits, &LHS)) || 10850 (NewOp = tryAdvSIMDModImm16(AArch64ISD::BICi, SDValue(N, 0), DAG, 10851 UndefBits, &LHS))) 10852 return NewOp; 10853 } 10854 10855 return SDValue(); 10856 } 10857 10858 static SDValue performSRLCombine(SDNode *N, 10859 TargetLowering::DAGCombinerInfo &DCI) { 10860 SelectionDAG &DAG = DCI.DAG; 10861 EVT VT = N->getValueType(0); 10862 if (VT != MVT::i32 && VT != MVT::i64) 10863 return SDValue(); 10864 10865 // Canonicalize (srl (bswap i32 x), 16) to (rotr (bswap i32 x), 16), if the 10866 // high 16-bits of x are zero. Similarly, canonicalize (srl (bswap i64 x), 32) 10867 // to (rotr (bswap i64 x), 32), if the high 32-bits of x are zero. 10868 SDValue N0 = N->getOperand(0); 10869 if (N0.getOpcode() == ISD::BSWAP) { 10870 SDLoc DL(N); 10871 SDValue N1 = N->getOperand(1); 10872 SDValue N00 = N0.getOperand(0); 10873 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(N1)) { 10874 uint64_t ShiftAmt = C->getZExtValue(); 10875 if (VT == MVT::i32 && ShiftAmt == 16 && 10876 DAG.MaskedValueIsZero(N00, APInt::getHighBitsSet(32, 16))) 10877 return DAG.getNode(ISD::ROTR, DL, VT, N0, N1); 10878 if (VT == MVT::i64 && ShiftAmt == 32 && 10879 DAG.MaskedValueIsZero(N00, APInt::getHighBitsSet(64, 32))) 10880 return DAG.getNode(ISD::ROTR, DL, VT, N0, N1); 10881 } 10882 } 10883 return SDValue(); 10884 } 10885 10886 static SDValue performConcatVectorsCombine(SDNode *N, 10887 TargetLowering::DAGCombinerInfo &DCI, 10888 SelectionDAG &DAG) { 10889 SDLoc dl(N); 10890 EVT VT = N->getValueType(0); 10891 SDValue N0 = N->getOperand(0), N1 = N->getOperand(1); 10892 10893 // Optimize concat_vectors of truncated vectors, where the intermediate 10894 // type is illegal, to avoid said illegality, e.g., 10895 // (v4i16 (concat_vectors (v2i16 (truncate (v2i64))), 10896 // (v2i16 (truncate (v2i64))))) 10897 // -> 10898 // (v4i16 (truncate (vector_shuffle (v4i32 (bitcast (v2i64))), 10899 // (v4i32 (bitcast (v2i64))), 10900 // <0, 2, 4, 6>))) 10901 // This isn't really target-specific, but ISD::TRUNCATE legality isn't keyed 10902 // on both input and result type, so we might generate worse code. 10903 // On AArch64 we know it's fine for v2i64->v4i16 and v4i32->v8i8. 10904 if (N->getNumOperands() == 2 && 10905 N0->getOpcode() == ISD::TRUNCATE && 10906 N1->getOpcode() == ISD::TRUNCATE) { 10907 SDValue N00 = N0->getOperand(0); 10908 SDValue N10 = N1->getOperand(0); 10909 EVT N00VT = N00.getValueType(); 10910 10911 if (N00VT == N10.getValueType() && 10912 (N00VT == MVT::v2i64 || N00VT == MVT::v4i32) && 10913 N00VT.getScalarSizeInBits() == 4 * VT.getScalarSizeInBits()) { 10914 MVT MidVT = (N00VT == MVT::v2i64 ? MVT::v4i32 : MVT::v8i16); 10915 SmallVector<int, 8> Mask(MidVT.getVectorNumElements()); 10916 for (size_t i = 0; i < Mask.size(); ++i) 10917 Mask[i] = i * 2; 10918 return DAG.getNode(ISD::TRUNCATE, dl, VT, 10919 DAG.getVectorShuffle( 10920 MidVT, dl, 10921 DAG.getNode(ISD::BITCAST, dl, MidVT, N00), 10922 DAG.getNode(ISD::BITCAST, dl, MidVT, N10), Mask)); 10923 } 10924 } 10925 10926 // Wait 'til after everything is legalized to try this. That way we have 10927 // legal vector types and such. 10928 if (DCI.isBeforeLegalizeOps()) 10929 return SDValue(); 10930 10931 // If we see a (concat_vectors (v1x64 A), (v1x64 A)) it's really a vector 10932 // splat. The indexed instructions are going to be expecting a DUPLANE64, so 10933 // canonicalise to that. 10934 if (N0 == N1 && VT.getVectorNumElements() == 2) { 10935 assert(VT.getScalarSizeInBits() == 64); 10936 return DAG.getNode(AArch64ISD::DUPLANE64, dl, VT, WidenVector(N0, DAG), 10937 DAG.getConstant(0, dl, MVT::i64)); 10938 } 10939 10940 // Canonicalise concat_vectors so that the right-hand vector has as few 10941 // bit-casts as possible before its real operation. The primary matching 10942 // destination for these operations will be the narrowing "2" instructions, 10943 // which depend on the operation being performed on this right-hand vector. 10944 // For example, 10945 // (concat_vectors LHS, (v1i64 (bitconvert (v4i16 RHS)))) 10946 // becomes 10947 // (bitconvert (concat_vectors (v4i16 (bitconvert LHS)), RHS)) 10948 10949 if (N1->getOpcode() != ISD::BITCAST) 10950 return SDValue(); 10951 SDValue RHS = N1->getOperand(0); 10952 MVT RHSTy = RHS.getValueType().getSimpleVT(); 10953 // If the RHS is not a vector, this is not the pattern we're looking for. 10954 if (!RHSTy.isVector()) 10955 return SDValue(); 10956 10957 LLVM_DEBUG( 10958 dbgs() << "aarch64-lower: concat_vectors bitcast simplification\n"); 10959 10960 MVT ConcatTy = MVT::getVectorVT(RHSTy.getVectorElementType(), 10961 RHSTy.getVectorNumElements() * 2); 10962 return DAG.getNode(ISD::BITCAST, dl, VT, 10963 DAG.getNode(ISD::CONCAT_VECTORS, dl, ConcatTy, 10964 DAG.getNode(ISD::BITCAST, dl, RHSTy, N0), 10965 RHS)); 10966 } 10967 10968 static SDValue tryCombineFixedPointConvert(SDNode *N, 10969 TargetLowering::DAGCombinerInfo &DCI, 10970 SelectionDAG &DAG) { 10971 // Wait until after everything is legalized to try this. That way we have 10972 // legal vector types and such. 10973 if (DCI.isBeforeLegalizeOps()) 10974 return SDValue(); 10975 // Transform a scalar conversion of a value from a lane extract into a 10976 // lane extract of a vector conversion. E.g., from foo1 to foo2: 10977 // double foo1(int64x2_t a) { return vcvtd_n_f64_s64(a[1], 9); } 10978 // double foo2(int64x2_t a) { return vcvtq_n_f64_s64(a, 9)[1]; } 10979 // 10980 // The second form interacts better with instruction selection and the 10981 // register allocator to avoid cross-class register copies that aren't 10982 // coalescable due to a lane reference. 10983 10984 // Check the operand and see if it originates from a lane extract. 10985 SDValue Op1 = N->getOperand(1); 10986 if (Op1.getOpcode() == ISD::EXTRACT_VECTOR_ELT) { 10987 // Yep, no additional predication needed. Perform the transform. 10988 SDValue IID = N->getOperand(0); 10989 SDValue Shift = N->getOperand(2); 10990 SDValue Vec = Op1.getOperand(0); 10991 SDValue Lane = Op1.getOperand(1); 10992 EVT ResTy = N->getValueType(0); 10993 EVT VecResTy; 10994 SDLoc DL(N); 10995 10996 // The vector width should be 128 bits by the time we get here, even 10997 // if it started as 64 bits (the extract_vector handling will have 10998 // done so). 10999 assert(Vec.getValueSizeInBits() == 128 && 11000 "unexpected vector size on extract_vector_elt!"); 11001 if (Vec.getValueType() == MVT::v4i32) 11002 VecResTy = MVT::v4f32; 11003 else if (Vec.getValueType() == MVT::v2i64) 11004 VecResTy = MVT::v2f64; 11005 else 11006 llvm_unreachable("unexpected vector type!"); 11007 11008 SDValue Convert = 11009 DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VecResTy, IID, Vec, Shift); 11010 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, ResTy, Convert, Lane); 11011 } 11012 return SDValue(); 11013 } 11014 11015 // AArch64 high-vector "long" operations are formed by performing the non-high 11016 // version on an extract_subvector of each operand which gets the high half: 11017 // 11018 // (longop2 LHS, RHS) == (longop (extract_high LHS), (extract_high RHS)) 11019 // 11020 // However, there are cases which don't have an extract_high explicitly, but 11021 // have another operation that can be made compatible with one for free. For 11022 // example: 11023 // 11024 // (dupv64 scalar) --> (extract_high (dup128 scalar)) 11025 // 11026 // This routine does the actual conversion of such DUPs, once outer routines 11027 // have determined that everything else is in order. 11028 // It also supports immediate DUP-like nodes (MOVI/MVNi), which we can fold 11029 // similarly here. 11030 static SDValue tryExtendDUPToExtractHigh(SDValue N, SelectionDAG &DAG) { 11031 switch (N.getOpcode()) { 11032 case AArch64ISD::DUP: 11033 case AArch64ISD::DUPLANE8: 11034 case AArch64ISD::DUPLANE16: 11035 case AArch64ISD::DUPLANE32: 11036 case AArch64ISD::DUPLANE64: 11037 case AArch64ISD::MOVI: 11038 case AArch64ISD::MOVIshift: 11039 case AArch64ISD::MOVIedit: 11040 case AArch64ISD::MOVImsl: 11041 case AArch64ISD::MVNIshift: 11042 case AArch64ISD::MVNImsl: 11043 break; 11044 default: 11045 // FMOV could be supported, but isn't very useful, as it would only occur 11046 // if you passed a bitcast' floating point immediate to an eligible long 11047 // integer op (addl, smull, ...). 11048 return SDValue(); 11049 } 11050 11051 MVT NarrowTy = N.getSimpleValueType(); 11052 if (!NarrowTy.is64BitVector()) 11053 return SDValue(); 11054 11055 MVT ElementTy = NarrowTy.getVectorElementType(); 11056 unsigned NumElems = NarrowTy.getVectorNumElements(); 11057 MVT NewVT = MVT::getVectorVT(ElementTy, NumElems * 2); 11058 11059 SDLoc dl(N); 11060 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, NarrowTy, 11061 DAG.getNode(N->getOpcode(), dl, NewVT, N->ops()), 11062 DAG.getConstant(NumElems, dl, MVT::i64)); 11063 } 11064 11065 static bool isEssentiallyExtractHighSubvector(SDValue N) { 11066 if (N.getOpcode() == ISD::BITCAST) 11067 N = N.getOperand(0); 11068 if (N.getOpcode() != ISD::EXTRACT_SUBVECTOR) 11069 return false; 11070 return cast<ConstantSDNode>(N.getOperand(1))->getAPIntValue() == 11071 N.getOperand(0).getValueType().getVectorNumElements() / 2; 11072 } 11073 11074 /// Helper structure to keep track of ISD::SET_CC operands. 11075 struct GenericSetCCInfo { 11076 const SDValue *Opnd0; 11077 const SDValue *Opnd1; 11078 ISD::CondCode CC; 11079 }; 11080 11081 /// Helper structure to keep track of a SET_CC lowered into AArch64 code. 11082 struct AArch64SetCCInfo { 11083 const SDValue *Cmp; 11084 AArch64CC::CondCode CC; 11085 }; 11086 11087 /// Helper structure to keep track of SetCC information. 11088 union SetCCInfo { 11089 GenericSetCCInfo Generic; 11090 AArch64SetCCInfo AArch64; 11091 }; 11092 11093 /// Helper structure to be able to read SetCC information. If set to 11094 /// true, IsAArch64 field, Info is a AArch64SetCCInfo, otherwise Info is a 11095 /// GenericSetCCInfo. 11096 struct SetCCInfoAndKind { 11097 SetCCInfo Info; 11098 bool IsAArch64; 11099 }; 11100 11101 /// Check whether or not \p Op is a SET_CC operation, either a generic or 11102 /// an 11103 /// AArch64 lowered one. 11104 /// \p SetCCInfo is filled accordingly. 11105 /// \post SetCCInfo is meanginfull only when this function returns true. 11106 /// \return True when Op is a kind of SET_CC operation. 11107 static bool isSetCC(SDValue Op, SetCCInfoAndKind &SetCCInfo) { 11108 // If this is a setcc, this is straight forward. 11109 if (Op.getOpcode() == ISD::SETCC) { 11110 SetCCInfo.Info.Generic.Opnd0 = &Op.getOperand(0); 11111 SetCCInfo.Info.Generic.Opnd1 = &Op.getOperand(1); 11112 SetCCInfo.Info.Generic.CC = cast<CondCodeSDNode>(Op.getOperand(2))->get(); 11113 SetCCInfo.IsAArch64 = false; 11114 return true; 11115 } 11116 // Otherwise, check if this is a matching csel instruction. 11117 // In other words: 11118 // - csel 1, 0, cc 11119 // - csel 0, 1, !cc 11120 if (Op.getOpcode() != AArch64ISD::CSEL) 11121 return false; 11122 // Set the information about the operands. 11123 // TODO: we want the operands of the Cmp not the csel 11124 SetCCInfo.Info.AArch64.Cmp = &Op.getOperand(3); 11125 SetCCInfo.IsAArch64 = true; 11126 SetCCInfo.Info.AArch64.CC = static_cast<AArch64CC::CondCode>( 11127 cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue()); 11128 11129 // Check that the operands matches the constraints: 11130 // (1) Both operands must be constants. 11131 // (2) One must be 1 and the other must be 0. 11132 ConstantSDNode *TValue = dyn_cast<ConstantSDNode>(Op.getOperand(0)); 11133 ConstantSDNode *FValue = dyn_cast<ConstantSDNode>(Op.getOperand(1)); 11134 11135 // Check (1). 11136 if (!TValue || !FValue) 11137 return false; 11138 11139 // Check (2). 11140 if (!TValue->isOne()) { 11141 // Update the comparison when we are interested in !cc. 11142 std::swap(TValue, FValue); 11143 SetCCInfo.Info.AArch64.CC = 11144 AArch64CC::getInvertedCondCode(SetCCInfo.Info.AArch64.CC); 11145 } 11146 return TValue->isOne() && FValue->isNullValue(); 11147 } 11148 11149 // Returns true if Op is setcc or zext of setcc. 11150 static bool isSetCCOrZExtSetCC(const SDValue& Op, SetCCInfoAndKind &Info) { 11151 if (isSetCC(Op, Info)) 11152 return true; 11153 return ((Op.getOpcode() == ISD::ZERO_EXTEND) && 11154 isSetCC(Op->getOperand(0), Info)); 11155 } 11156 11157 // The folding we want to perform is: 11158 // (add x, [zext] (setcc cc ...) ) 11159 // --> 11160 // (csel x, (add x, 1), !cc ...) 11161 // 11162 // The latter will get matched to a CSINC instruction. 11163 static SDValue performSetccAddFolding(SDNode *Op, SelectionDAG &DAG) { 11164 assert(Op && Op->getOpcode() == ISD::ADD && "Unexpected operation!"); 11165 SDValue LHS = Op->getOperand(0); 11166 SDValue RHS = Op->getOperand(1); 11167 SetCCInfoAndKind InfoAndKind; 11168 11169 // If neither operand is a SET_CC, give up. 11170 if (!isSetCCOrZExtSetCC(LHS, InfoAndKind)) { 11171 std::swap(LHS, RHS); 11172 if (!isSetCCOrZExtSetCC(LHS, InfoAndKind)) 11173 return SDValue(); 11174 } 11175 11176 // FIXME: This could be generatized to work for FP comparisons. 11177 EVT CmpVT = InfoAndKind.IsAArch64 11178 ? InfoAndKind.Info.AArch64.Cmp->getOperand(0).getValueType() 11179 : InfoAndKind.Info.Generic.Opnd0->getValueType(); 11180 if (CmpVT != MVT::i32 && CmpVT != MVT::i64) 11181 return SDValue(); 11182 11183 SDValue CCVal; 11184 SDValue Cmp; 11185 SDLoc dl(Op); 11186 if (InfoAndKind.IsAArch64) { 11187 CCVal = DAG.getConstant( 11188 AArch64CC::getInvertedCondCode(InfoAndKind.Info.AArch64.CC), dl, 11189 MVT::i32); 11190 Cmp = *InfoAndKind.Info.AArch64.Cmp; 11191 } else 11192 Cmp = getAArch64Cmp( 11193 *InfoAndKind.Info.Generic.Opnd0, *InfoAndKind.Info.Generic.Opnd1, 11194 ISD::getSetCCInverse(InfoAndKind.Info.Generic.CC, CmpVT), CCVal, DAG, 11195 dl); 11196 11197 EVT VT = Op->getValueType(0); 11198 LHS = DAG.getNode(ISD::ADD, dl, VT, RHS, DAG.getConstant(1, dl, VT)); 11199 return DAG.getNode(AArch64ISD::CSEL, dl, VT, RHS, LHS, CCVal, Cmp); 11200 } 11201 11202 // The basic add/sub long vector instructions have variants with "2" on the end 11203 // which act on the high-half of their inputs. They are normally matched by 11204 // patterns like: 11205 // 11206 // (add (zeroext (extract_high LHS)), 11207 // (zeroext (extract_high RHS))) 11208 // -> uaddl2 vD, vN, vM 11209 // 11210 // However, if one of the extracts is something like a duplicate, this 11211 // instruction can still be used profitably. This function puts the DAG into a 11212 // more appropriate form for those patterns to trigger. 11213 static SDValue performAddSubLongCombine(SDNode *N, 11214 TargetLowering::DAGCombinerInfo &DCI, 11215 SelectionDAG &DAG) { 11216 if (DCI.isBeforeLegalizeOps()) 11217 return SDValue(); 11218 11219 MVT VT = N->getSimpleValueType(0); 11220 if (!VT.is128BitVector()) { 11221 if (N->getOpcode() == ISD::ADD) 11222 return performSetccAddFolding(N, DAG); 11223 return SDValue(); 11224 } 11225 11226 // Make sure both branches are extended in the same way. 11227 SDValue LHS = N->getOperand(0); 11228 SDValue RHS = N->getOperand(1); 11229 if ((LHS.getOpcode() != ISD::ZERO_EXTEND && 11230 LHS.getOpcode() != ISD::SIGN_EXTEND) || 11231 LHS.getOpcode() != RHS.getOpcode()) 11232 return SDValue(); 11233 11234 unsigned ExtType = LHS.getOpcode(); 11235 11236 // It's not worth doing if at least one of the inputs isn't already an 11237 // extract, but we don't know which it'll be so we have to try both. 11238 if (isEssentiallyExtractHighSubvector(LHS.getOperand(0))) { 11239 RHS = tryExtendDUPToExtractHigh(RHS.getOperand(0), DAG); 11240 if (!RHS.getNode()) 11241 return SDValue(); 11242 11243 RHS = DAG.getNode(ExtType, SDLoc(N), VT, RHS); 11244 } else if (isEssentiallyExtractHighSubvector(RHS.getOperand(0))) { 11245 LHS = tryExtendDUPToExtractHigh(LHS.getOperand(0), DAG); 11246 if (!LHS.getNode()) 11247 return SDValue(); 11248 11249 LHS = DAG.getNode(ExtType, SDLoc(N), VT, LHS); 11250 } 11251 11252 return DAG.getNode(N->getOpcode(), SDLoc(N), VT, LHS, RHS); 11253 } 11254 11255 // Massage DAGs which we can use the high-half "long" operations on into 11256 // something isel will recognize better. E.g. 11257 // 11258 // (aarch64_neon_umull (extract_high vec) (dupv64 scalar)) --> 11259 // (aarch64_neon_umull (extract_high (v2i64 vec))) 11260 // (extract_high (v2i64 (dup128 scalar))))) 11261 // 11262 static SDValue tryCombineLongOpWithDup(unsigned IID, SDNode *N, 11263 TargetLowering::DAGCombinerInfo &DCI, 11264 SelectionDAG &DAG) { 11265 if (DCI.isBeforeLegalizeOps()) 11266 return SDValue(); 11267 11268 SDValue LHS = N->getOperand(1); 11269 SDValue RHS = N->getOperand(2); 11270 assert(LHS.getValueType().is64BitVector() && 11271 RHS.getValueType().is64BitVector() && 11272 "unexpected shape for long operation"); 11273 11274 // Either node could be a DUP, but it's not worth doing both of them (you'd 11275 // just as well use the non-high version) so look for a corresponding extract 11276 // operation on the other "wing". 11277 if (isEssentiallyExtractHighSubvector(LHS)) { 11278 RHS = tryExtendDUPToExtractHigh(RHS, DAG); 11279 if (!RHS.getNode()) 11280 return SDValue(); 11281 } else if (isEssentiallyExtractHighSubvector(RHS)) { 11282 LHS = tryExtendDUPToExtractHigh(LHS, DAG); 11283 if (!LHS.getNode()) 11284 return SDValue(); 11285 } 11286 11287 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, SDLoc(N), N->getValueType(0), 11288 N->getOperand(0), LHS, RHS); 11289 } 11290 11291 static SDValue tryCombineShiftImm(unsigned IID, SDNode *N, SelectionDAG &DAG) { 11292 MVT ElemTy = N->getSimpleValueType(0).getScalarType(); 11293 unsigned ElemBits = ElemTy.getSizeInBits(); 11294 11295 int64_t ShiftAmount; 11296 if (BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(N->getOperand(2))) { 11297 APInt SplatValue, SplatUndef; 11298 unsigned SplatBitSize; 11299 bool HasAnyUndefs; 11300 if (!BVN->isConstantSplat(SplatValue, SplatUndef, SplatBitSize, 11301 HasAnyUndefs, ElemBits) || 11302 SplatBitSize != ElemBits) 11303 return SDValue(); 11304 11305 ShiftAmount = SplatValue.getSExtValue(); 11306 } else if (ConstantSDNode *CVN = dyn_cast<ConstantSDNode>(N->getOperand(2))) { 11307 ShiftAmount = CVN->getSExtValue(); 11308 } else 11309 return SDValue(); 11310 11311 unsigned Opcode; 11312 bool IsRightShift; 11313 switch (IID) { 11314 default: 11315 llvm_unreachable("Unknown shift intrinsic"); 11316 case Intrinsic::aarch64_neon_sqshl: 11317 Opcode = AArch64ISD::SQSHL_I; 11318 IsRightShift = false; 11319 break; 11320 case Intrinsic::aarch64_neon_uqshl: 11321 Opcode = AArch64ISD::UQSHL_I; 11322 IsRightShift = false; 11323 break; 11324 case Intrinsic::aarch64_neon_srshl: 11325 Opcode = AArch64ISD::SRSHR_I; 11326 IsRightShift = true; 11327 break; 11328 case Intrinsic::aarch64_neon_urshl: 11329 Opcode = AArch64ISD::URSHR_I; 11330 IsRightShift = true; 11331 break; 11332 case Intrinsic::aarch64_neon_sqshlu: 11333 Opcode = AArch64ISD::SQSHLU_I; 11334 IsRightShift = false; 11335 break; 11336 case Intrinsic::aarch64_neon_sshl: 11337 case Intrinsic::aarch64_neon_ushl: 11338 // For positive shift amounts we can use SHL, as ushl/sshl perform a regular 11339 // left shift for positive shift amounts. Below, we only replace the current 11340 // node with VSHL, if this condition is met. 11341 Opcode = AArch64ISD::VSHL; 11342 IsRightShift = false; 11343 break; 11344 } 11345 11346 if (IsRightShift && ShiftAmount <= -1 && ShiftAmount >= -(int)ElemBits) { 11347 SDLoc dl(N); 11348 return DAG.getNode(Opcode, dl, N->getValueType(0), N->getOperand(1), 11349 DAG.getConstant(-ShiftAmount, dl, MVT::i32)); 11350 } else if (!IsRightShift && ShiftAmount >= 0 && ShiftAmount < ElemBits) { 11351 SDLoc dl(N); 11352 return DAG.getNode(Opcode, dl, N->getValueType(0), N->getOperand(1), 11353 DAG.getConstant(ShiftAmount, dl, MVT::i32)); 11354 } 11355 11356 return SDValue(); 11357 } 11358 11359 // The CRC32[BH] instructions ignore the high bits of their data operand. Since 11360 // the intrinsics must be legal and take an i32, this means there's almost 11361 // certainly going to be a zext in the DAG which we can eliminate. 11362 static SDValue tryCombineCRC32(unsigned Mask, SDNode *N, SelectionDAG &DAG) { 11363 SDValue AndN = N->getOperand(2); 11364 if (AndN.getOpcode() != ISD::AND) 11365 return SDValue(); 11366 11367 ConstantSDNode *CMask = dyn_cast<ConstantSDNode>(AndN.getOperand(1)); 11368 if (!CMask || CMask->getZExtValue() != Mask) 11369 return SDValue(); 11370 11371 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, SDLoc(N), MVT::i32, 11372 N->getOperand(0), N->getOperand(1), AndN.getOperand(0)); 11373 } 11374 11375 static SDValue combineAcrossLanesIntrinsic(unsigned Opc, SDNode *N, 11376 SelectionDAG &DAG) { 11377 SDLoc dl(N); 11378 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, N->getValueType(0), 11379 DAG.getNode(Opc, dl, 11380 N->getOperand(1).getSimpleValueType(), 11381 N->getOperand(1)), 11382 DAG.getConstant(0, dl, MVT::i64)); 11383 } 11384 11385 static SDValue LowerSVEIntReduction(SDNode *N, unsigned Opc, 11386 SelectionDAG &DAG) { 11387 SDLoc dl(N); 11388 LLVMContext &Ctx = *DAG.getContext(); 11389 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 11390 11391 EVT VT = N->getValueType(0); 11392 SDValue Pred = N->getOperand(1); 11393 SDValue Data = N->getOperand(2); 11394 EVT DataVT = Data.getValueType(); 11395 11396 if (DataVT.getVectorElementType().isScalarInteger() && 11397 (VT == MVT::i8 || VT == MVT::i16 || VT == MVT::i32 || VT == MVT::i64)) { 11398 if (!TLI.isTypeLegal(DataVT)) 11399 return SDValue(); 11400 11401 EVT OutputVT = EVT::getVectorVT(Ctx, VT, 11402 AArch64::NeonBitsPerVector / VT.getSizeInBits()); 11403 SDValue Reduce = DAG.getNode(Opc, dl, OutputVT, Pred, Data); 11404 SDValue Zero = DAG.getConstant(0, dl, MVT::i64); 11405 SDValue Result = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, Reduce, Zero); 11406 11407 return Result; 11408 } 11409 11410 return SDValue(); 11411 } 11412 11413 static SDValue LowerSVEIntrinsicIndex(SDNode *N, SelectionDAG &DAG) { 11414 SDLoc DL(N); 11415 SDValue Op1 = N->getOperand(1); 11416 SDValue Op2 = N->getOperand(2); 11417 EVT ScalarTy = Op1.getValueType(); 11418 11419 if ((ScalarTy == MVT::i8) || (ScalarTy == MVT::i16)) { 11420 Op1 = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i32, Op1); 11421 Op2 = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i32, Op2); 11422 } 11423 11424 return DAG.getNode(AArch64ISD::INDEX_VECTOR, DL, N->getValueType(0), 11425 Op1, Op2); 11426 } 11427 11428 static SDValue LowerSVEIntrinsicDUP(SDNode *N, SelectionDAG &DAG) { 11429 SDLoc dl(N); 11430 SDValue Scalar = N->getOperand(3); 11431 EVT ScalarTy = Scalar.getValueType(); 11432 11433 if ((ScalarTy == MVT::i8) || (ScalarTy == MVT::i16)) 11434 Scalar = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, Scalar); 11435 11436 return DAG.getNode(AArch64ISD::DUP_PRED, dl, N->getValueType(0), 11437 N->getOperand(1), N->getOperand(2), Scalar); 11438 } 11439 11440 static SDValue LowerSVEIntrinsicEXT(SDNode *N, SelectionDAG &DAG) { 11441 SDLoc dl(N); 11442 LLVMContext &Ctx = *DAG.getContext(); 11443 EVT VT = N->getValueType(0); 11444 11445 assert(VT.isScalableVector() && "Expected a scalable vector."); 11446 11447 // Current lowering only supports the SVE-ACLE types. 11448 if (VT.getSizeInBits().getKnownMinSize() != AArch64::SVEBitsPerBlock) 11449 return SDValue(); 11450 11451 unsigned ElemSize = VT.getVectorElementType().getSizeInBits() / 8; 11452 unsigned ByteSize = VT.getSizeInBits().getKnownMinSize() / 8; 11453 EVT ByteVT = EVT::getVectorVT(Ctx, MVT::i8, { ByteSize, true }); 11454 11455 // Convert everything to the domain of EXT (i.e bytes). 11456 SDValue Op0 = DAG.getNode(ISD::BITCAST, dl, ByteVT, N->getOperand(1)); 11457 SDValue Op1 = DAG.getNode(ISD::BITCAST, dl, ByteVT, N->getOperand(2)); 11458 SDValue Op2 = DAG.getNode(ISD::MUL, dl, MVT::i32, N->getOperand(3), 11459 DAG.getConstant(ElemSize, dl, MVT::i32)); 11460 11461 SDValue EXT = DAG.getNode(AArch64ISD::EXT, dl, ByteVT, Op0, Op1, Op2); 11462 return DAG.getNode(ISD::BITCAST, dl, VT, EXT); 11463 } 11464 11465 static SDValue tryConvertSVEWideCompare(SDNode *N, ISD::CondCode CC, 11466 TargetLowering::DAGCombinerInfo &DCI, 11467 SelectionDAG &DAG) { 11468 if (DCI.isBeforeLegalize()) 11469 return SDValue(); 11470 11471 SDValue Comparator = N->getOperand(3); 11472 if (Comparator.getOpcode() == AArch64ISD::DUP || 11473 Comparator.getOpcode() == ISD::SPLAT_VECTOR) { 11474 unsigned IID = getIntrinsicID(N); 11475 EVT VT = N->getValueType(0); 11476 EVT CmpVT = N->getOperand(2).getValueType(); 11477 SDValue Pred = N->getOperand(1); 11478 SDValue Imm; 11479 SDLoc DL(N); 11480 11481 switch (IID) { 11482 default: 11483 llvm_unreachable("Called with wrong intrinsic!"); 11484 break; 11485 11486 // Signed comparisons 11487 case Intrinsic::aarch64_sve_cmpeq_wide: 11488 case Intrinsic::aarch64_sve_cmpne_wide: 11489 case Intrinsic::aarch64_sve_cmpge_wide: 11490 case Intrinsic::aarch64_sve_cmpgt_wide: 11491 case Intrinsic::aarch64_sve_cmplt_wide: 11492 case Intrinsic::aarch64_sve_cmple_wide: { 11493 if (auto *CN = dyn_cast<ConstantSDNode>(Comparator.getOperand(0))) { 11494 int64_t ImmVal = CN->getSExtValue(); 11495 if (ImmVal >= -16 && ImmVal <= 15) 11496 Imm = DAG.getConstant(ImmVal, DL, MVT::i32); 11497 else 11498 return SDValue(); 11499 } 11500 break; 11501 } 11502 // Unsigned comparisons 11503 case Intrinsic::aarch64_sve_cmphs_wide: 11504 case Intrinsic::aarch64_sve_cmphi_wide: 11505 case Intrinsic::aarch64_sve_cmplo_wide: 11506 case Intrinsic::aarch64_sve_cmpls_wide: { 11507 if (auto *CN = dyn_cast<ConstantSDNode>(Comparator.getOperand(0))) { 11508 uint64_t ImmVal = CN->getZExtValue(); 11509 if (ImmVal <= 127) 11510 Imm = DAG.getConstant(ImmVal, DL, MVT::i32); 11511 else 11512 return SDValue(); 11513 } 11514 break; 11515 } 11516 } 11517 11518 if (!Imm) 11519 return SDValue(); 11520 11521 SDValue Splat = DAG.getNode(ISD::SPLAT_VECTOR, DL, CmpVT, Imm); 11522 return DAG.getNode(AArch64ISD::SETCC_PRED, DL, VT, Pred, N->getOperand(2), 11523 Splat, DAG.getCondCode(CC)); 11524 } 11525 11526 return SDValue(); 11527 } 11528 11529 static SDValue getPTest(SelectionDAG &DAG, EVT VT, SDValue Pg, SDValue Op, 11530 AArch64CC::CondCode Cond) { 11531 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 11532 11533 SDLoc DL(Op); 11534 assert(Op.getValueType().isScalableVector() && 11535 TLI.isTypeLegal(Op.getValueType()) && 11536 "Expected legal scalable vector type!"); 11537 11538 // Ensure target specific opcodes are using legal type. 11539 EVT OutVT = TLI.getTypeToTransformTo(*DAG.getContext(), VT); 11540 SDValue TVal = DAG.getConstant(1, DL, OutVT); 11541 SDValue FVal = DAG.getConstant(0, DL, OutVT); 11542 11543 // Set condition code (CC) flags. 11544 SDValue Test = DAG.getNode(AArch64ISD::PTEST, DL, MVT::Other, Pg, Op); 11545 11546 // Convert CC to integer based on requested condition. 11547 // NOTE: Cond is inverted to promote CSEL's removal when it feeds a compare. 11548 SDValue CC = DAG.getConstant(getInvertedCondCode(Cond), DL, MVT::i32); 11549 SDValue Res = DAG.getNode(AArch64ISD::CSEL, DL, OutVT, FVal, TVal, CC, Test); 11550 return DAG.getZExtOrTrunc(Res, DL, VT); 11551 } 11552 11553 static SDValue combineSVEReductionFP(SDNode *N, unsigned Opc, 11554 SelectionDAG &DAG) { 11555 SDLoc DL(N); 11556 11557 SDValue Pred = N->getOperand(1); 11558 SDValue VecToReduce = N->getOperand(2); 11559 11560 EVT ReduceVT = VecToReduce.getValueType(); 11561 SDValue Reduce = DAG.getNode(Opc, DL, ReduceVT, Pred, VecToReduce); 11562 11563 // SVE reductions set the whole vector register with the first element 11564 // containing the reduction result, which we'll now extract. 11565 SDValue Zero = DAG.getConstant(0, DL, MVT::i64); 11566 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, N->getValueType(0), Reduce, 11567 Zero); 11568 } 11569 11570 static SDValue combineSVEReductionOrderedFP(SDNode *N, unsigned Opc, 11571 SelectionDAG &DAG) { 11572 SDLoc DL(N); 11573 11574 SDValue Pred = N->getOperand(1); 11575 SDValue InitVal = N->getOperand(2); 11576 SDValue VecToReduce = N->getOperand(3); 11577 EVT ReduceVT = VecToReduce.getValueType(); 11578 11579 // Ordered reductions use the first lane of the result vector as the 11580 // reduction's initial value. 11581 SDValue Zero = DAG.getConstant(0, DL, MVT::i64); 11582 InitVal = DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, ReduceVT, 11583 DAG.getUNDEF(ReduceVT), InitVal, Zero); 11584 11585 SDValue Reduce = DAG.getNode(Opc, DL, ReduceVT, Pred, InitVal, VecToReduce); 11586 11587 // SVE reductions set the whole vector register with the first element 11588 // containing the reduction result, which we'll now extract. 11589 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, N->getValueType(0), Reduce, 11590 Zero); 11591 } 11592 11593 static SDValue performIntrinsicCombine(SDNode *N, 11594 TargetLowering::DAGCombinerInfo &DCI, 11595 const AArch64Subtarget *Subtarget) { 11596 SelectionDAG &DAG = DCI.DAG; 11597 unsigned IID = getIntrinsicID(N); 11598 switch (IID) { 11599 default: 11600 break; 11601 case Intrinsic::aarch64_neon_vcvtfxs2fp: 11602 case Intrinsic::aarch64_neon_vcvtfxu2fp: 11603 return tryCombineFixedPointConvert(N, DCI, DAG); 11604 case Intrinsic::aarch64_neon_saddv: 11605 return combineAcrossLanesIntrinsic(AArch64ISD::SADDV, N, DAG); 11606 case Intrinsic::aarch64_neon_uaddv: 11607 return combineAcrossLanesIntrinsic(AArch64ISD::UADDV, N, DAG); 11608 case Intrinsic::aarch64_neon_sminv: 11609 return combineAcrossLanesIntrinsic(AArch64ISD::SMINV, N, DAG); 11610 case Intrinsic::aarch64_neon_uminv: 11611 return combineAcrossLanesIntrinsic(AArch64ISD::UMINV, N, DAG); 11612 case Intrinsic::aarch64_neon_smaxv: 11613 return combineAcrossLanesIntrinsic(AArch64ISD::SMAXV, N, DAG); 11614 case Intrinsic::aarch64_neon_umaxv: 11615 return combineAcrossLanesIntrinsic(AArch64ISD::UMAXV, N, DAG); 11616 case Intrinsic::aarch64_neon_fmax: 11617 return DAG.getNode(ISD::FMAXIMUM, SDLoc(N), N->getValueType(0), 11618 N->getOperand(1), N->getOperand(2)); 11619 case Intrinsic::aarch64_neon_fmin: 11620 return DAG.getNode(ISD::FMINIMUM, SDLoc(N), N->getValueType(0), 11621 N->getOperand(1), N->getOperand(2)); 11622 case Intrinsic::aarch64_neon_fmaxnm: 11623 return DAG.getNode(ISD::FMAXNUM, SDLoc(N), N->getValueType(0), 11624 N->getOperand(1), N->getOperand(2)); 11625 case Intrinsic::aarch64_neon_fminnm: 11626 return DAG.getNode(ISD::FMINNUM, SDLoc(N), N->getValueType(0), 11627 N->getOperand(1), N->getOperand(2)); 11628 case Intrinsic::aarch64_neon_smull: 11629 case Intrinsic::aarch64_neon_umull: 11630 case Intrinsic::aarch64_neon_pmull: 11631 case Intrinsic::aarch64_neon_sqdmull: 11632 return tryCombineLongOpWithDup(IID, N, DCI, DAG); 11633 case Intrinsic::aarch64_neon_sqshl: 11634 case Intrinsic::aarch64_neon_uqshl: 11635 case Intrinsic::aarch64_neon_sqshlu: 11636 case Intrinsic::aarch64_neon_srshl: 11637 case Intrinsic::aarch64_neon_urshl: 11638 case Intrinsic::aarch64_neon_sshl: 11639 case Intrinsic::aarch64_neon_ushl: 11640 return tryCombineShiftImm(IID, N, DAG); 11641 case Intrinsic::aarch64_crc32b: 11642 case Intrinsic::aarch64_crc32cb: 11643 return tryCombineCRC32(0xff, N, DAG); 11644 case Intrinsic::aarch64_crc32h: 11645 case Intrinsic::aarch64_crc32ch: 11646 return tryCombineCRC32(0xffff, N, DAG); 11647 case Intrinsic::aarch64_sve_smaxv: 11648 return LowerSVEIntReduction(N, AArch64ISD::SMAXV_PRED, DAG); 11649 case Intrinsic::aarch64_sve_umaxv: 11650 return LowerSVEIntReduction(N, AArch64ISD::UMAXV_PRED, DAG); 11651 case Intrinsic::aarch64_sve_sminv: 11652 return LowerSVEIntReduction(N, AArch64ISD::SMINV_PRED, DAG); 11653 case Intrinsic::aarch64_sve_uminv: 11654 return LowerSVEIntReduction(N, AArch64ISD::UMINV_PRED, DAG); 11655 case Intrinsic::aarch64_sve_orv: 11656 return LowerSVEIntReduction(N, AArch64ISD::ORV_PRED, DAG); 11657 case Intrinsic::aarch64_sve_eorv: 11658 return LowerSVEIntReduction(N, AArch64ISD::EORV_PRED, DAG); 11659 case Intrinsic::aarch64_sve_andv: 11660 return LowerSVEIntReduction(N, AArch64ISD::ANDV_PRED, DAG); 11661 case Intrinsic::aarch64_sve_index: 11662 return LowerSVEIntrinsicIndex(N, DAG); 11663 case Intrinsic::aarch64_sve_dup: 11664 return LowerSVEIntrinsicDUP(N, DAG); 11665 case Intrinsic::aarch64_sve_dup_x: 11666 return DAG.getNode(ISD::SPLAT_VECTOR, SDLoc(N), N->getValueType(0), 11667 N->getOperand(1)); 11668 case Intrinsic::aarch64_sve_ext: 11669 return LowerSVEIntrinsicEXT(N, DAG); 11670 case Intrinsic::aarch64_sve_sdiv: 11671 return DAG.getNode(AArch64ISD::SDIV_PRED, SDLoc(N), N->getValueType(0), 11672 N->getOperand(1), N->getOperand(2), N->getOperand(3)); 11673 case Intrinsic::aarch64_sve_udiv: 11674 return DAG.getNode(AArch64ISD::UDIV_PRED, SDLoc(N), N->getValueType(0), 11675 N->getOperand(1), N->getOperand(2), N->getOperand(3)); 11676 case Intrinsic::aarch64_sve_smin: 11677 return DAG.getNode(AArch64ISD::SMIN_PRED, SDLoc(N), N->getValueType(0), 11678 N->getOperand(1), N->getOperand(2), N->getOperand(3)); 11679 case Intrinsic::aarch64_sve_umin: 11680 return DAG.getNode(AArch64ISD::UMIN_PRED, SDLoc(N), N->getValueType(0), 11681 N->getOperand(1), N->getOperand(2), N->getOperand(3)); 11682 case Intrinsic::aarch64_sve_smax: 11683 return DAG.getNode(AArch64ISD::SMAX_PRED, SDLoc(N), N->getValueType(0), 11684 N->getOperand(1), N->getOperand(2), N->getOperand(3)); 11685 case Intrinsic::aarch64_sve_umax: 11686 return DAG.getNode(AArch64ISD::UMAX_PRED, SDLoc(N), N->getValueType(0), 11687 N->getOperand(1), N->getOperand(2), N->getOperand(3)); 11688 case Intrinsic::aarch64_sve_lsl: 11689 return DAG.getNode(AArch64ISD::SHL_PRED, SDLoc(N), N->getValueType(0), 11690 N->getOperand(1), N->getOperand(2), N->getOperand(3)); 11691 case Intrinsic::aarch64_sve_lsr: 11692 return DAG.getNode(AArch64ISD::SRL_PRED, SDLoc(N), N->getValueType(0), 11693 N->getOperand(1), N->getOperand(2), N->getOperand(3)); 11694 case Intrinsic::aarch64_sve_asr: 11695 return DAG.getNode(AArch64ISD::SRA_PRED, SDLoc(N), N->getValueType(0), 11696 N->getOperand(1), N->getOperand(2), N->getOperand(3)); 11697 case Intrinsic::aarch64_sve_cmphs: 11698 if (!N->getOperand(2).getValueType().isFloatingPoint()) 11699 return DAG.getNode(AArch64ISD::SETCC_PRED, SDLoc(N), N->getValueType(0), 11700 N->getOperand(1), N->getOperand(2), N->getOperand(3), 11701 DAG.getCondCode(ISD::SETUGE)); 11702 break; 11703 case Intrinsic::aarch64_sve_cmphi: 11704 if (!N->getOperand(2).getValueType().isFloatingPoint()) 11705 return DAG.getNode(AArch64ISD::SETCC_PRED, SDLoc(N), N->getValueType(0), 11706 N->getOperand(1), N->getOperand(2), N->getOperand(3), 11707 DAG.getCondCode(ISD::SETUGT)); 11708 break; 11709 case Intrinsic::aarch64_sve_cmpge: 11710 if (!N->getOperand(2).getValueType().isFloatingPoint()) 11711 return DAG.getNode(AArch64ISD::SETCC_PRED, SDLoc(N), N->getValueType(0), 11712 N->getOperand(1), N->getOperand(2), N->getOperand(3), 11713 DAG.getCondCode(ISD::SETGE)); 11714 break; 11715 case Intrinsic::aarch64_sve_cmpgt: 11716 if (!N->getOperand(2).getValueType().isFloatingPoint()) 11717 return DAG.getNode(AArch64ISD::SETCC_PRED, SDLoc(N), N->getValueType(0), 11718 N->getOperand(1), N->getOperand(2), N->getOperand(3), 11719 DAG.getCondCode(ISD::SETGT)); 11720 break; 11721 case Intrinsic::aarch64_sve_cmpeq: 11722 if (!N->getOperand(2).getValueType().isFloatingPoint()) 11723 return DAG.getNode(AArch64ISD::SETCC_PRED, SDLoc(N), N->getValueType(0), 11724 N->getOperand(1), N->getOperand(2), N->getOperand(3), 11725 DAG.getCondCode(ISD::SETEQ)); 11726 break; 11727 case Intrinsic::aarch64_sve_cmpne: 11728 if (!N->getOperand(2).getValueType().isFloatingPoint()) 11729 return DAG.getNode(AArch64ISD::SETCC_PRED, SDLoc(N), N->getValueType(0), 11730 N->getOperand(1), N->getOperand(2), N->getOperand(3), 11731 DAG.getCondCode(ISD::SETNE)); 11732 break; 11733 case Intrinsic::aarch64_sve_fadda: 11734 return combineSVEReductionOrderedFP(N, AArch64ISD::FADDA_PRED, DAG); 11735 case Intrinsic::aarch64_sve_faddv: 11736 return combineSVEReductionFP(N, AArch64ISD::FADDV_PRED, DAG); 11737 case Intrinsic::aarch64_sve_fmaxnmv: 11738 return combineSVEReductionFP(N, AArch64ISD::FMAXNMV_PRED, DAG); 11739 case Intrinsic::aarch64_sve_fmaxv: 11740 return combineSVEReductionFP(N, AArch64ISD::FMAXV_PRED, DAG); 11741 case Intrinsic::aarch64_sve_fminnmv: 11742 return combineSVEReductionFP(N, AArch64ISD::FMINNMV_PRED, DAG); 11743 case Intrinsic::aarch64_sve_fminv: 11744 return combineSVEReductionFP(N, AArch64ISD::FMINV_PRED, DAG); 11745 case Intrinsic::aarch64_sve_sel: 11746 return DAG.getNode(ISD::VSELECT, SDLoc(N), N->getValueType(0), 11747 N->getOperand(1), N->getOperand(2), N->getOperand(3)); 11748 case Intrinsic::aarch64_sve_cmpeq_wide: 11749 return tryConvertSVEWideCompare(N, ISD::SETEQ, DCI, DAG); 11750 case Intrinsic::aarch64_sve_cmpne_wide: 11751 return tryConvertSVEWideCompare(N, ISD::SETNE, DCI, DAG); 11752 case Intrinsic::aarch64_sve_cmpge_wide: 11753 return tryConvertSVEWideCompare(N, ISD::SETGE, DCI, DAG); 11754 case Intrinsic::aarch64_sve_cmpgt_wide: 11755 return tryConvertSVEWideCompare(N, ISD::SETGT, DCI, DAG); 11756 case Intrinsic::aarch64_sve_cmplt_wide: 11757 return tryConvertSVEWideCompare(N, ISD::SETLT, DCI, DAG); 11758 case Intrinsic::aarch64_sve_cmple_wide: 11759 return tryConvertSVEWideCompare(N, ISD::SETLE, DCI, DAG); 11760 case Intrinsic::aarch64_sve_cmphs_wide: 11761 return tryConvertSVEWideCompare(N, ISD::SETUGE, DCI, DAG); 11762 case Intrinsic::aarch64_sve_cmphi_wide: 11763 return tryConvertSVEWideCompare(N, ISD::SETUGT, DCI, DAG); 11764 case Intrinsic::aarch64_sve_cmplo_wide: 11765 return tryConvertSVEWideCompare(N, ISD::SETULT, DCI, DAG); 11766 case Intrinsic::aarch64_sve_cmpls_wide: 11767 return tryConvertSVEWideCompare(N, ISD::SETULE, DCI, DAG); 11768 case Intrinsic::aarch64_sve_ptest_any: 11769 return getPTest(DAG, N->getValueType(0), N->getOperand(1), N->getOperand(2), 11770 AArch64CC::ANY_ACTIVE); 11771 case Intrinsic::aarch64_sve_ptest_first: 11772 return getPTest(DAG, N->getValueType(0), N->getOperand(1), N->getOperand(2), 11773 AArch64CC::FIRST_ACTIVE); 11774 case Intrinsic::aarch64_sve_ptest_last: 11775 return getPTest(DAG, N->getValueType(0), N->getOperand(1), N->getOperand(2), 11776 AArch64CC::LAST_ACTIVE); 11777 } 11778 return SDValue(); 11779 } 11780 11781 static SDValue performExtendCombine(SDNode *N, 11782 TargetLowering::DAGCombinerInfo &DCI, 11783 SelectionDAG &DAG) { 11784 // If we see something like (zext (sabd (extract_high ...), (DUP ...))) then 11785 // we can convert that DUP into another extract_high (of a bigger DUP), which 11786 // helps the backend to decide that an sabdl2 would be useful, saving a real 11787 // extract_high operation. 11788 if (!DCI.isBeforeLegalizeOps() && N->getOpcode() == ISD::ZERO_EXTEND && 11789 N->getOperand(0).getOpcode() == ISD::INTRINSIC_WO_CHAIN) { 11790 SDNode *ABDNode = N->getOperand(0).getNode(); 11791 unsigned IID = getIntrinsicID(ABDNode); 11792 if (IID == Intrinsic::aarch64_neon_sabd || 11793 IID == Intrinsic::aarch64_neon_uabd) { 11794 SDValue NewABD = tryCombineLongOpWithDup(IID, ABDNode, DCI, DAG); 11795 if (!NewABD.getNode()) 11796 return SDValue(); 11797 11798 return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), N->getValueType(0), 11799 NewABD); 11800 } 11801 } 11802 11803 // This is effectively a custom type legalization for AArch64. 11804 // 11805 // Type legalization will split an extend of a small, legal, type to a larger 11806 // illegal type by first splitting the destination type, often creating 11807 // illegal source types, which then get legalized in isel-confusing ways, 11808 // leading to really terrible codegen. E.g., 11809 // %result = v8i32 sext v8i8 %value 11810 // becomes 11811 // %losrc = extract_subreg %value, ... 11812 // %hisrc = extract_subreg %value, ... 11813 // %lo = v4i32 sext v4i8 %losrc 11814 // %hi = v4i32 sext v4i8 %hisrc 11815 // Things go rapidly downhill from there. 11816 // 11817 // For AArch64, the [sz]ext vector instructions can only go up one element 11818 // size, so we can, e.g., extend from i8 to i16, but to go from i8 to i32 11819 // take two instructions. 11820 // 11821 // This implies that the most efficient way to do the extend from v8i8 11822 // to two v4i32 values is to first extend the v8i8 to v8i16, then do 11823 // the normal splitting to happen for the v8i16->v8i32. 11824 11825 // This is pre-legalization to catch some cases where the default 11826 // type legalization will create ill-tempered code. 11827 if (!DCI.isBeforeLegalizeOps()) 11828 return SDValue(); 11829 11830 // We're only interested in cleaning things up for non-legal vector types 11831 // here. If both the source and destination are legal, things will just 11832 // work naturally without any fiddling. 11833 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 11834 EVT ResVT = N->getValueType(0); 11835 if (!ResVT.isVector() || TLI.isTypeLegal(ResVT)) 11836 return SDValue(); 11837 // If the vector type isn't a simple VT, it's beyond the scope of what 11838 // we're worried about here. Let legalization do its thing and hope for 11839 // the best. 11840 SDValue Src = N->getOperand(0); 11841 EVT SrcVT = Src->getValueType(0); 11842 if (!ResVT.isSimple() || !SrcVT.isSimple()) 11843 return SDValue(); 11844 11845 // If the source VT is a 64-bit vector, we can play games and get the 11846 // better results we want. 11847 if (SrcVT.getSizeInBits() != 64) 11848 return SDValue(); 11849 11850 unsigned SrcEltSize = SrcVT.getScalarSizeInBits(); 11851 unsigned ElementCount = SrcVT.getVectorNumElements(); 11852 SrcVT = MVT::getVectorVT(MVT::getIntegerVT(SrcEltSize * 2), ElementCount); 11853 SDLoc DL(N); 11854 Src = DAG.getNode(N->getOpcode(), DL, SrcVT, Src); 11855 11856 // Now split the rest of the operation into two halves, each with a 64 11857 // bit source. 11858 EVT LoVT, HiVT; 11859 SDValue Lo, Hi; 11860 unsigned NumElements = ResVT.getVectorNumElements(); 11861 assert(!(NumElements & 1) && "Splitting vector, but not in half!"); 11862 LoVT = HiVT = EVT::getVectorVT(*DAG.getContext(), 11863 ResVT.getVectorElementType(), NumElements / 2); 11864 11865 EVT InNVT = EVT::getVectorVT(*DAG.getContext(), SrcVT.getVectorElementType(), 11866 LoVT.getVectorNumElements()); 11867 Lo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, InNVT, Src, 11868 DAG.getConstant(0, DL, MVT::i64)); 11869 Hi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, InNVT, Src, 11870 DAG.getConstant(InNVT.getVectorNumElements(), DL, MVT::i64)); 11871 Lo = DAG.getNode(N->getOpcode(), DL, LoVT, Lo); 11872 Hi = DAG.getNode(N->getOpcode(), DL, HiVT, Hi); 11873 11874 // Now combine the parts back together so we still have a single result 11875 // like the combiner expects. 11876 return DAG.getNode(ISD::CONCAT_VECTORS, DL, ResVT, Lo, Hi); 11877 } 11878 11879 static SDValue splitStoreSplat(SelectionDAG &DAG, StoreSDNode &St, 11880 SDValue SplatVal, unsigned NumVecElts) { 11881 assert(!St.isTruncatingStore() && "cannot split truncating vector store"); 11882 unsigned OrigAlignment = St.getAlignment(); 11883 unsigned EltOffset = SplatVal.getValueType().getSizeInBits() / 8; 11884 11885 // Create scalar stores. This is at least as good as the code sequence for a 11886 // split unaligned store which is a dup.s, ext.b, and two stores. 11887 // Most of the time the three stores should be replaced by store pair 11888 // instructions (stp). 11889 SDLoc DL(&St); 11890 SDValue BasePtr = St.getBasePtr(); 11891 uint64_t BaseOffset = 0; 11892 11893 const MachinePointerInfo &PtrInfo = St.getPointerInfo(); 11894 SDValue NewST1 = 11895 DAG.getStore(St.getChain(), DL, SplatVal, BasePtr, PtrInfo, 11896 OrigAlignment, St.getMemOperand()->getFlags()); 11897 11898 // As this in ISel, we will not merge this add which may degrade results. 11899 if (BasePtr->getOpcode() == ISD::ADD && 11900 isa<ConstantSDNode>(BasePtr->getOperand(1))) { 11901 BaseOffset = cast<ConstantSDNode>(BasePtr->getOperand(1))->getSExtValue(); 11902 BasePtr = BasePtr->getOperand(0); 11903 } 11904 11905 unsigned Offset = EltOffset; 11906 while (--NumVecElts) { 11907 unsigned Alignment = MinAlign(OrigAlignment, Offset); 11908 SDValue OffsetPtr = 11909 DAG.getNode(ISD::ADD, DL, MVT::i64, BasePtr, 11910 DAG.getConstant(BaseOffset + Offset, DL, MVT::i64)); 11911 NewST1 = DAG.getStore(NewST1.getValue(0), DL, SplatVal, OffsetPtr, 11912 PtrInfo.getWithOffset(Offset), Alignment, 11913 St.getMemOperand()->getFlags()); 11914 Offset += EltOffset; 11915 } 11916 return NewST1; 11917 } 11918 11919 // Returns an SVE type that ContentTy can be trivially sign or zero extended 11920 // into. 11921 static MVT getSVEContainerType(EVT ContentTy) { 11922 assert(ContentTy.isSimple() && "No SVE containers for extended types"); 11923 11924 switch (ContentTy.getSimpleVT().SimpleTy) { 11925 default: 11926 llvm_unreachable("No known SVE container for this MVT type"); 11927 case MVT::nxv2i8: 11928 case MVT::nxv2i16: 11929 case MVT::nxv2i32: 11930 case MVT::nxv2i64: 11931 case MVT::nxv2f32: 11932 case MVT::nxv2f64: 11933 return MVT::nxv2i64; 11934 case MVT::nxv4i8: 11935 case MVT::nxv4i16: 11936 case MVT::nxv4i32: 11937 case MVT::nxv4f32: 11938 return MVT::nxv4i32; 11939 case MVT::nxv8i8: 11940 case MVT::nxv8i16: 11941 case MVT::nxv8f16: 11942 return MVT::nxv8i16; 11943 case MVT::nxv16i8: 11944 return MVT::nxv16i8; 11945 } 11946 } 11947 11948 static SDValue performLD1Combine(SDNode *N, SelectionDAG &DAG, unsigned Opc) { 11949 SDLoc DL(N); 11950 EVT VT = N->getValueType(0); 11951 11952 if (VT.getSizeInBits().getKnownMinSize() > AArch64::SVEBitsPerBlock) 11953 return SDValue(); 11954 11955 EVT ContainerVT = VT; 11956 if (ContainerVT.isInteger()) 11957 ContainerVT = getSVEContainerType(ContainerVT); 11958 11959 SDVTList VTs = DAG.getVTList(ContainerVT, MVT::Other); 11960 SDValue Ops[] = { N->getOperand(0), // Chain 11961 N->getOperand(2), // Pg 11962 N->getOperand(3), // Base 11963 DAG.getValueType(VT) }; 11964 11965 SDValue Load = DAG.getNode(Opc, DL, VTs, Ops); 11966 SDValue LoadChain = SDValue(Load.getNode(), 1); 11967 11968 if (ContainerVT.isInteger() && (VT != ContainerVT)) 11969 Load = DAG.getNode(ISD::TRUNCATE, DL, VT, Load.getValue(0)); 11970 11971 return DAG.getMergeValues({ Load, LoadChain }, DL); 11972 } 11973 11974 static SDValue performLDNT1Combine(SDNode *N, SelectionDAG &DAG) { 11975 SDLoc DL(N); 11976 EVT VT = N->getValueType(0); 11977 EVT PtrTy = N->getOperand(3).getValueType(); 11978 11979 EVT LoadVT = VT; 11980 if (VT.isFloatingPoint()) 11981 LoadVT = VT.changeTypeToInteger(); 11982 11983 auto *MINode = cast<MemIntrinsicSDNode>(N); 11984 SDValue PassThru = DAG.getConstant(0, DL, LoadVT); 11985 SDValue L = DAG.getMaskedLoad(LoadVT, DL, MINode->getChain(), 11986 MINode->getOperand(3), DAG.getUNDEF(PtrTy), 11987 MINode->getOperand(2), PassThru, 11988 MINode->getMemoryVT(), MINode->getMemOperand(), 11989 ISD::UNINDEXED, ISD::NON_EXTLOAD, false); 11990 11991 if (VT.isFloatingPoint()) { 11992 SDValue Ops[] = { DAG.getNode(ISD::BITCAST, DL, VT, L), L.getValue(1) }; 11993 return DAG.getMergeValues(Ops, DL); 11994 } 11995 11996 return L; 11997 } 11998 11999 template <unsigned Opcode> 12000 static SDValue performLD1ReplicateCombine(SDNode *N, SelectionDAG &DAG) { 12001 static_assert(Opcode == AArch64ISD::LD1RQ || Opcode == AArch64ISD::LD1RO, 12002 "Unsupported opcode."); 12003 SDLoc DL(N); 12004 EVT VT = N->getValueType(0); 12005 12006 EVT LoadVT = VT; 12007 if (VT.isFloatingPoint()) 12008 LoadVT = VT.changeTypeToInteger(); 12009 12010 SDValue Ops[] = {N->getOperand(0), N->getOperand(2), N->getOperand(3)}; 12011 SDValue Load = DAG.getNode(Opcode, DL, {LoadVT, MVT::Other}, Ops); 12012 SDValue LoadChain = SDValue(Load.getNode(), 1); 12013 12014 if (VT.isFloatingPoint()) 12015 Load = DAG.getNode(ISD::BITCAST, DL, VT, Load.getValue(0)); 12016 12017 return DAG.getMergeValues({Load, LoadChain}, DL); 12018 } 12019 12020 static SDValue performST1Combine(SDNode *N, SelectionDAG &DAG) { 12021 SDLoc DL(N); 12022 SDValue Data = N->getOperand(2); 12023 EVT DataVT = Data.getValueType(); 12024 EVT HwSrcVt = getSVEContainerType(DataVT); 12025 SDValue InputVT = DAG.getValueType(DataVT); 12026 12027 if (DataVT.isFloatingPoint()) 12028 InputVT = DAG.getValueType(HwSrcVt); 12029 12030 SDValue SrcNew; 12031 if (Data.getValueType().isFloatingPoint()) 12032 SrcNew = DAG.getNode(ISD::BITCAST, DL, HwSrcVt, Data); 12033 else 12034 SrcNew = DAG.getNode(ISD::ANY_EXTEND, DL, HwSrcVt, Data); 12035 12036 SDValue Ops[] = { N->getOperand(0), // Chain 12037 SrcNew, 12038 N->getOperand(4), // Base 12039 N->getOperand(3), // Pg 12040 InputVT 12041 }; 12042 12043 return DAG.getNode(AArch64ISD::ST1, DL, N->getValueType(0), Ops); 12044 } 12045 12046 static SDValue performSTNT1Combine(SDNode *N, SelectionDAG &DAG) { 12047 SDLoc DL(N); 12048 12049 SDValue Data = N->getOperand(2); 12050 EVT DataVT = Data.getValueType(); 12051 EVT PtrTy = N->getOperand(4).getValueType(); 12052 12053 if (DataVT.isFloatingPoint()) 12054 Data = DAG.getNode(ISD::BITCAST, DL, DataVT.changeTypeToInteger(), Data); 12055 12056 auto *MINode = cast<MemIntrinsicSDNode>(N); 12057 return DAG.getMaskedStore(MINode->getChain(), DL, Data, MINode->getOperand(4), 12058 DAG.getUNDEF(PtrTy), MINode->getOperand(3), 12059 MINode->getMemoryVT(), MINode->getMemOperand(), 12060 ISD::UNINDEXED, false, false); 12061 } 12062 12063 /// Replace a splat of zeros to a vector store by scalar stores of WZR/XZR. The 12064 /// load store optimizer pass will merge them to store pair stores. This should 12065 /// be better than a movi to create the vector zero followed by a vector store 12066 /// if the zero constant is not re-used, since one instructions and one register 12067 /// live range will be removed. 12068 /// 12069 /// For example, the final generated code should be: 12070 /// 12071 /// stp xzr, xzr, [x0] 12072 /// 12073 /// instead of: 12074 /// 12075 /// movi v0.2d, #0 12076 /// str q0, [x0] 12077 /// 12078 static SDValue replaceZeroVectorStore(SelectionDAG &DAG, StoreSDNode &St) { 12079 SDValue StVal = St.getValue(); 12080 EVT VT = StVal.getValueType(); 12081 12082 // Avoid scalarizing zero splat stores for scalable vectors. 12083 if (VT.isScalableVector()) 12084 return SDValue(); 12085 12086 // It is beneficial to scalarize a zero splat store for 2 or 3 i64 elements or 12087 // 2, 3 or 4 i32 elements. 12088 int NumVecElts = VT.getVectorNumElements(); 12089 if (!(((NumVecElts == 2 || NumVecElts == 3) && 12090 VT.getVectorElementType().getSizeInBits() == 64) || 12091 ((NumVecElts == 2 || NumVecElts == 3 || NumVecElts == 4) && 12092 VT.getVectorElementType().getSizeInBits() == 32))) 12093 return SDValue(); 12094 12095 if (StVal.getOpcode() != ISD::BUILD_VECTOR) 12096 return SDValue(); 12097 12098 // If the zero constant has more than one use then the vector store could be 12099 // better since the constant mov will be amortized and stp q instructions 12100 // should be able to be formed. 12101 if (!StVal.hasOneUse()) 12102 return SDValue(); 12103 12104 // If the store is truncating then it's going down to i16 or smaller, which 12105 // means it can be implemented in a single store anyway. 12106 if (St.isTruncatingStore()) 12107 return SDValue(); 12108 12109 // If the immediate offset of the address operand is too large for the stp 12110 // instruction, then bail out. 12111 if (DAG.isBaseWithConstantOffset(St.getBasePtr())) { 12112 int64_t Offset = St.getBasePtr()->getConstantOperandVal(1); 12113 if (Offset < -512 || Offset > 504) 12114 return SDValue(); 12115 } 12116 12117 for (int I = 0; I < NumVecElts; ++I) { 12118 SDValue EltVal = StVal.getOperand(I); 12119 if (!isNullConstant(EltVal) && !isNullFPConstant(EltVal)) 12120 return SDValue(); 12121 } 12122 12123 // Use a CopyFromReg WZR/XZR here to prevent 12124 // DAGCombiner::MergeConsecutiveStores from undoing this transformation. 12125 SDLoc DL(&St); 12126 unsigned ZeroReg; 12127 EVT ZeroVT; 12128 if (VT.getVectorElementType().getSizeInBits() == 32) { 12129 ZeroReg = AArch64::WZR; 12130 ZeroVT = MVT::i32; 12131 } else { 12132 ZeroReg = AArch64::XZR; 12133 ZeroVT = MVT::i64; 12134 } 12135 SDValue SplatVal = 12136 DAG.getCopyFromReg(DAG.getEntryNode(), DL, ZeroReg, ZeroVT); 12137 return splitStoreSplat(DAG, St, SplatVal, NumVecElts); 12138 } 12139 12140 /// Replace a splat of a scalar to a vector store by scalar stores of the scalar 12141 /// value. The load store optimizer pass will merge them to store pair stores. 12142 /// This has better performance than a splat of the scalar followed by a split 12143 /// vector store. Even if the stores are not merged it is four stores vs a dup, 12144 /// followed by an ext.b and two stores. 12145 static SDValue replaceSplatVectorStore(SelectionDAG &DAG, StoreSDNode &St) { 12146 SDValue StVal = St.getValue(); 12147 EVT VT = StVal.getValueType(); 12148 12149 // Don't replace floating point stores, they possibly won't be transformed to 12150 // stp because of the store pair suppress pass. 12151 if (VT.isFloatingPoint()) 12152 return SDValue(); 12153 12154 // We can express a splat as store pair(s) for 2 or 4 elements. 12155 unsigned NumVecElts = VT.getVectorNumElements(); 12156 if (NumVecElts != 4 && NumVecElts != 2) 12157 return SDValue(); 12158 12159 // If the store is truncating then it's going down to i16 or smaller, which 12160 // means it can be implemented in a single store anyway. 12161 if (St.isTruncatingStore()) 12162 return SDValue(); 12163 12164 // Check that this is a splat. 12165 // Make sure that each of the relevant vector element locations are inserted 12166 // to, i.e. 0 and 1 for v2i64 and 0, 1, 2, 3 for v4i32. 12167 std::bitset<4> IndexNotInserted((1 << NumVecElts) - 1); 12168 SDValue SplatVal; 12169 for (unsigned I = 0; I < NumVecElts; ++I) { 12170 // Check for insert vector elements. 12171 if (StVal.getOpcode() != ISD::INSERT_VECTOR_ELT) 12172 return SDValue(); 12173 12174 // Check that same value is inserted at each vector element. 12175 if (I == 0) 12176 SplatVal = StVal.getOperand(1); 12177 else if (StVal.getOperand(1) != SplatVal) 12178 return SDValue(); 12179 12180 // Check insert element index. 12181 ConstantSDNode *CIndex = dyn_cast<ConstantSDNode>(StVal.getOperand(2)); 12182 if (!CIndex) 12183 return SDValue(); 12184 uint64_t IndexVal = CIndex->getZExtValue(); 12185 if (IndexVal >= NumVecElts) 12186 return SDValue(); 12187 IndexNotInserted.reset(IndexVal); 12188 12189 StVal = StVal.getOperand(0); 12190 } 12191 // Check that all vector element locations were inserted to. 12192 if (IndexNotInserted.any()) 12193 return SDValue(); 12194 12195 return splitStoreSplat(DAG, St, SplatVal, NumVecElts); 12196 } 12197 12198 static SDValue splitStores(SDNode *N, TargetLowering::DAGCombinerInfo &DCI, 12199 SelectionDAG &DAG, 12200 const AArch64Subtarget *Subtarget) { 12201 12202 StoreSDNode *S = cast<StoreSDNode>(N); 12203 if (S->isVolatile() || S->isIndexed()) 12204 return SDValue(); 12205 12206 SDValue StVal = S->getValue(); 12207 EVT VT = StVal.getValueType(); 12208 12209 if (!VT.isFixedLengthVector()) 12210 return SDValue(); 12211 12212 // If we get a splat of zeros, convert this vector store to a store of 12213 // scalars. They will be merged into store pairs of xzr thereby removing one 12214 // instruction and one register. 12215 if (SDValue ReplacedZeroSplat = replaceZeroVectorStore(DAG, *S)) 12216 return ReplacedZeroSplat; 12217 12218 // FIXME: The logic for deciding if an unaligned store should be split should 12219 // be included in TLI.allowsMisalignedMemoryAccesses(), and there should be 12220 // a call to that function here. 12221 12222 if (!Subtarget->isMisaligned128StoreSlow()) 12223 return SDValue(); 12224 12225 // Don't split at -Oz. 12226 if (DAG.getMachineFunction().getFunction().hasMinSize()) 12227 return SDValue(); 12228 12229 // Don't split v2i64 vectors. Memcpy lowering produces those and splitting 12230 // those up regresses performance on micro-benchmarks and olden/bh. 12231 if (VT.getVectorNumElements() < 2 || VT == MVT::v2i64) 12232 return SDValue(); 12233 12234 // Split unaligned 16B stores. They are terrible for performance. 12235 // Don't split stores with alignment of 1 or 2. Code that uses clang vector 12236 // extensions can use this to mark that it does not want splitting to happen 12237 // (by underspecifying alignment to be 1 or 2). Furthermore, the chance of 12238 // eliminating alignment hazards is only 1 in 8 for alignment of 2. 12239 if (VT.getSizeInBits() != 128 || S->getAlignment() >= 16 || 12240 S->getAlignment() <= 2) 12241 return SDValue(); 12242 12243 // If we get a splat of a scalar convert this vector store to a store of 12244 // scalars. They will be merged into store pairs thereby removing two 12245 // instructions. 12246 if (SDValue ReplacedSplat = replaceSplatVectorStore(DAG, *S)) 12247 return ReplacedSplat; 12248 12249 SDLoc DL(S); 12250 12251 // Split VT into two. 12252 EVT HalfVT = VT.getHalfNumVectorElementsVT(*DAG.getContext()); 12253 unsigned NumElts = HalfVT.getVectorNumElements(); 12254 SDValue SubVector0 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, HalfVT, StVal, 12255 DAG.getConstant(0, DL, MVT::i64)); 12256 SDValue SubVector1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, HalfVT, StVal, 12257 DAG.getConstant(NumElts, DL, MVT::i64)); 12258 SDValue BasePtr = S->getBasePtr(); 12259 SDValue NewST1 = 12260 DAG.getStore(S->getChain(), DL, SubVector0, BasePtr, S->getPointerInfo(), 12261 S->getAlignment(), S->getMemOperand()->getFlags()); 12262 SDValue OffsetPtr = DAG.getNode(ISD::ADD, DL, MVT::i64, BasePtr, 12263 DAG.getConstant(8, DL, MVT::i64)); 12264 return DAG.getStore(NewST1.getValue(0), DL, SubVector1, OffsetPtr, 12265 S->getPointerInfo(), S->getAlignment(), 12266 S->getMemOperand()->getFlags()); 12267 } 12268 12269 /// Target-specific DAG combine function for post-increment LD1 (lane) and 12270 /// post-increment LD1R. 12271 static SDValue performPostLD1Combine(SDNode *N, 12272 TargetLowering::DAGCombinerInfo &DCI, 12273 bool IsLaneOp) { 12274 if (DCI.isBeforeLegalizeOps()) 12275 return SDValue(); 12276 12277 SelectionDAG &DAG = DCI.DAG; 12278 EVT VT = N->getValueType(0); 12279 12280 unsigned LoadIdx = IsLaneOp ? 1 : 0; 12281 SDNode *LD = N->getOperand(LoadIdx).getNode(); 12282 // If it is not LOAD, can not do such combine. 12283 if (LD->getOpcode() != ISD::LOAD) 12284 return SDValue(); 12285 12286 // The vector lane must be a constant in the LD1LANE opcode. 12287 SDValue Lane; 12288 if (IsLaneOp) { 12289 Lane = N->getOperand(2); 12290 auto *LaneC = dyn_cast<ConstantSDNode>(Lane); 12291 if (!LaneC || LaneC->getZExtValue() >= VT.getVectorNumElements()) 12292 return SDValue(); 12293 } 12294 12295 LoadSDNode *LoadSDN = cast<LoadSDNode>(LD); 12296 EVT MemVT = LoadSDN->getMemoryVT(); 12297 // Check if memory operand is the same type as the vector element. 12298 if (MemVT != VT.getVectorElementType()) 12299 return SDValue(); 12300 12301 // Check if there are other uses. If so, do not combine as it will introduce 12302 // an extra load. 12303 for (SDNode::use_iterator UI = LD->use_begin(), UE = LD->use_end(); UI != UE; 12304 ++UI) { 12305 if (UI.getUse().getResNo() == 1) // Ignore uses of the chain result. 12306 continue; 12307 if (*UI != N) 12308 return SDValue(); 12309 } 12310 12311 SDValue Addr = LD->getOperand(1); 12312 SDValue Vector = N->getOperand(0); 12313 // Search for a use of the address operand that is an increment. 12314 for (SDNode::use_iterator UI = Addr.getNode()->use_begin(), UE = 12315 Addr.getNode()->use_end(); UI != UE; ++UI) { 12316 SDNode *User = *UI; 12317 if (User->getOpcode() != ISD::ADD 12318 || UI.getUse().getResNo() != Addr.getResNo()) 12319 continue; 12320 12321 // If the increment is a constant, it must match the memory ref size. 12322 SDValue Inc = User->getOperand(User->getOperand(0) == Addr ? 1 : 0); 12323 if (ConstantSDNode *CInc = dyn_cast<ConstantSDNode>(Inc.getNode())) { 12324 uint32_t IncVal = CInc->getZExtValue(); 12325 unsigned NumBytes = VT.getScalarSizeInBits() / 8; 12326 if (IncVal != NumBytes) 12327 continue; 12328 Inc = DAG.getRegister(AArch64::XZR, MVT::i64); 12329 } 12330 12331 // To avoid cycle construction make sure that neither the load nor the add 12332 // are predecessors to each other or the Vector. 12333 SmallPtrSet<const SDNode *, 32> Visited; 12334 SmallVector<const SDNode *, 16> Worklist; 12335 Visited.insert(Addr.getNode()); 12336 Worklist.push_back(User); 12337 Worklist.push_back(LD); 12338 Worklist.push_back(Vector.getNode()); 12339 if (SDNode::hasPredecessorHelper(LD, Visited, Worklist) || 12340 SDNode::hasPredecessorHelper(User, Visited, Worklist)) 12341 continue; 12342 12343 SmallVector<SDValue, 8> Ops; 12344 Ops.push_back(LD->getOperand(0)); // Chain 12345 if (IsLaneOp) { 12346 Ops.push_back(Vector); // The vector to be inserted 12347 Ops.push_back(Lane); // The lane to be inserted in the vector 12348 } 12349 Ops.push_back(Addr); 12350 Ops.push_back(Inc); 12351 12352 EVT Tys[3] = { VT, MVT::i64, MVT::Other }; 12353 SDVTList SDTys = DAG.getVTList(Tys); 12354 unsigned NewOp = IsLaneOp ? AArch64ISD::LD1LANEpost : AArch64ISD::LD1DUPpost; 12355 SDValue UpdN = DAG.getMemIntrinsicNode(NewOp, SDLoc(N), SDTys, Ops, 12356 MemVT, 12357 LoadSDN->getMemOperand()); 12358 12359 // Update the uses. 12360 SDValue NewResults[] = { 12361 SDValue(LD, 0), // The result of load 12362 SDValue(UpdN.getNode(), 2) // Chain 12363 }; 12364 DCI.CombineTo(LD, NewResults); 12365 DCI.CombineTo(N, SDValue(UpdN.getNode(), 0)); // Dup/Inserted Result 12366 DCI.CombineTo(User, SDValue(UpdN.getNode(), 1)); // Write back register 12367 12368 break; 12369 } 12370 return SDValue(); 12371 } 12372 12373 /// Simplify ``Addr`` given that the top byte of it is ignored by HW during 12374 /// address translation. 12375 static bool performTBISimplification(SDValue Addr, 12376 TargetLowering::DAGCombinerInfo &DCI, 12377 SelectionDAG &DAG) { 12378 APInt DemandedMask = APInt::getLowBitsSet(64, 56); 12379 KnownBits Known; 12380 TargetLowering::TargetLoweringOpt TLO(DAG, !DCI.isBeforeLegalize(), 12381 !DCI.isBeforeLegalizeOps()); 12382 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 12383 if (TLI.SimplifyDemandedBits(Addr, DemandedMask, Known, TLO)) { 12384 DCI.CommitTargetLoweringOpt(TLO); 12385 return true; 12386 } 12387 return false; 12388 } 12389 12390 static SDValue performSTORECombine(SDNode *N, 12391 TargetLowering::DAGCombinerInfo &DCI, 12392 SelectionDAG &DAG, 12393 const AArch64Subtarget *Subtarget) { 12394 if (SDValue Split = splitStores(N, DCI, DAG, Subtarget)) 12395 return Split; 12396 12397 if (Subtarget->supportsAddressTopByteIgnored() && 12398 performTBISimplification(N->getOperand(2), DCI, DAG)) 12399 return SDValue(N, 0); 12400 12401 return SDValue(); 12402 } 12403 12404 12405 /// Target-specific DAG combine function for NEON load/store intrinsics 12406 /// to merge base address updates. 12407 static SDValue performNEONPostLDSTCombine(SDNode *N, 12408 TargetLowering::DAGCombinerInfo &DCI, 12409 SelectionDAG &DAG) { 12410 if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer()) 12411 return SDValue(); 12412 12413 unsigned AddrOpIdx = N->getNumOperands() - 1; 12414 SDValue Addr = N->getOperand(AddrOpIdx); 12415 12416 // Search for a use of the address operand that is an increment. 12417 for (SDNode::use_iterator UI = Addr.getNode()->use_begin(), 12418 UE = Addr.getNode()->use_end(); UI != UE; ++UI) { 12419 SDNode *User = *UI; 12420 if (User->getOpcode() != ISD::ADD || 12421 UI.getUse().getResNo() != Addr.getResNo()) 12422 continue; 12423 12424 // Check that the add is independent of the load/store. Otherwise, folding 12425 // it would create a cycle. 12426 SmallPtrSet<const SDNode *, 32> Visited; 12427 SmallVector<const SDNode *, 16> Worklist; 12428 Visited.insert(Addr.getNode()); 12429 Worklist.push_back(N); 12430 Worklist.push_back(User); 12431 if (SDNode::hasPredecessorHelper(N, Visited, Worklist) || 12432 SDNode::hasPredecessorHelper(User, Visited, Worklist)) 12433 continue; 12434 12435 // Find the new opcode for the updating load/store. 12436 bool IsStore = false; 12437 bool IsLaneOp = false; 12438 bool IsDupOp = false; 12439 unsigned NewOpc = 0; 12440 unsigned NumVecs = 0; 12441 unsigned IntNo = cast<ConstantSDNode>(N->getOperand(1))->getZExtValue(); 12442 switch (IntNo) { 12443 default: llvm_unreachable("unexpected intrinsic for Neon base update"); 12444 case Intrinsic::aarch64_neon_ld2: NewOpc = AArch64ISD::LD2post; 12445 NumVecs = 2; break; 12446 case Intrinsic::aarch64_neon_ld3: NewOpc = AArch64ISD::LD3post; 12447 NumVecs = 3; break; 12448 case Intrinsic::aarch64_neon_ld4: NewOpc = AArch64ISD::LD4post; 12449 NumVecs = 4; break; 12450 case Intrinsic::aarch64_neon_st2: NewOpc = AArch64ISD::ST2post; 12451 NumVecs = 2; IsStore = true; break; 12452 case Intrinsic::aarch64_neon_st3: NewOpc = AArch64ISD::ST3post; 12453 NumVecs = 3; IsStore = true; break; 12454 case Intrinsic::aarch64_neon_st4: NewOpc = AArch64ISD::ST4post; 12455 NumVecs = 4; IsStore = true; break; 12456 case Intrinsic::aarch64_neon_ld1x2: NewOpc = AArch64ISD::LD1x2post; 12457 NumVecs = 2; break; 12458 case Intrinsic::aarch64_neon_ld1x3: NewOpc = AArch64ISD::LD1x3post; 12459 NumVecs = 3; break; 12460 case Intrinsic::aarch64_neon_ld1x4: NewOpc = AArch64ISD::LD1x4post; 12461 NumVecs = 4; break; 12462 case Intrinsic::aarch64_neon_st1x2: NewOpc = AArch64ISD::ST1x2post; 12463 NumVecs = 2; IsStore = true; break; 12464 case Intrinsic::aarch64_neon_st1x3: NewOpc = AArch64ISD::ST1x3post; 12465 NumVecs = 3; IsStore = true; break; 12466 case Intrinsic::aarch64_neon_st1x4: NewOpc = AArch64ISD::ST1x4post; 12467 NumVecs = 4; IsStore = true; break; 12468 case Intrinsic::aarch64_neon_ld2r: NewOpc = AArch64ISD::LD2DUPpost; 12469 NumVecs = 2; IsDupOp = true; break; 12470 case Intrinsic::aarch64_neon_ld3r: NewOpc = AArch64ISD::LD3DUPpost; 12471 NumVecs = 3; IsDupOp = true; break; 12472 case Intrinsic::aarch64_neon_ld4r: NewOpc = AArch64ISD::LD4DUPpost; 12473 NumVecs = 4; IsDupOp = true; break; 12474 case Intrinsic::aarch64_neon_ld2lane: NewOpc = AArch64ISD::LD2LANEpost; 12475 NumVecs = 2; IsLaneOp = true; break; 12476 case Intrinsic::aarch64_neon_ld3lane: NewOpc = AArch64ISD::LD3LANEpost; 12477 NumVecs = 3; IsLaneOp = true; break; 12478 case Intrinsic::aarch64_neon_ld4lane: NewOpc = AArch64ISD::LD4LANEpost; 12479 NumVecs = 4; IsLaneOp = true; break; 12480 case Intrinsic::aarch64_neon_st2lane: NewOpc = AArch64ISD::ST2LANEpost; 12481 NumVecs = 2; IsStore = true; IsLaneOp = true; break; 12482 case Intrinsic::aarch64_neon_st3lane: NewOpc = AArch64ISD::ST3LANEpost; 12483 NumVecs = 3; IsStore = true; IsLaneOp = true; break; 12484 case Intrinsic::aarch64_neon_st4lane: NewOpc = AArch64ISD::ST4LANEpost; 12485 NumVecs = 4; IsStore = true; IsLaneOp = true; break; 12486 } 12487 12488 EVT VecTy; 12489 if (IsStore) 12490 VecTy = N->getOperand(2).getValueType(); 12491 else 12492 VecTy = N->getValueType(0); 12493 12494 // If the increment is a constant, it must match the memory ref size. 12495 SDValue Inc = User->getOperand(User->getOperand(0) == Addr ? 1 : 0); 12496 if (ConstantSDNode *CInc = dyn_cast<ConstantSDNode>(Inc.getNode())) { 12497 uint32_t IncVal = CInc->getZExtValue(); 12498 unsigned NumBytes = NumVecs * VecTy.getSizeInBits() / 8; 12499 if (IsLaneOp || IsDupOp) 12500 NumBytes /= VecTy.getVectorNumElements(); 12501 if (IncVal != NumBytes) 12502 continue; 12503 Inc = DAG.getRegister(AArch64::XZR, MVT::i64); 12504 } 12505 SmallVector<SDValue, 8> Ops; 12506 Ops.push_back(N->getOperand(0)); // Incoming chain 12507 // Load lane and store have vector list as input. 12508 if (IsLaneOp || IsStore) 12509 for (unsigned i = 2; i < AddrOpIdx; ++i) 12510 Ops.push_back(N->getOperand(i)); 12511 Ops.push_back(Addr); // Base register 12512 Ops.push_back(Inc); 12513 12514 // Return Types. 12515 EVT Tys[6]; 12516 unsigned NumResultVecs = (IsStore ? 0 : NumVecs); 12517 unsigned n; 12518 for (n = 0; n < NumResultVecs; ++n) 12519 Tys[n] = VecTy; 12520 Tys[n++] = MVT::i64; // Type of write back register 12521 Tys[n] = MVT::Other; // Type of the chain 12522 SDVTList SDTys = DAG.getVTList(makeArrayRef(Tys, NumResultVecs + 2)); 12523 12524 MemIntrinsicSDNode *MemInt = cast<MemIntrinsicSDNode>(N); 12525 SDValue UpdN = DAG.getMemIntrinsicNode(NewOpc, SDLoc(N), SDTys, Ops, 12526 MemInt->getMemoryVT(), 12527 MemInt->getMemOperand()); 12528 12529 // Update the uses. 12530 std::vector<SDValue> NewResults; 12531 for (unsigned i = 0; i < NumResultVecs; ++i) { 12532 NewResults.push_back(SDValue(UpdN.getNode(), i)); 12533 } 12534 NewResults.push_back(SDValue(UpdN.getNode(), NumResultVecs + 1)); 12535 DCI.CombineTo(N, NewResults); 12536 DCI.CombineTo(User, SDValue(UpdN.getNode(), NumResultVecs)); 12537 12538 break; 12539 } 12540 return SDValue(); 12541 } 12542 12543 // Checks to see if the value is the prescribed width and returns information 12544 // about its extension mode. 12545 static 12546 bool checkValueWidth(SDValue V, unsigned width, ISD::LoadExtType &ExtType) { 12547 ExtType = ISD::NON_EXTLOAD; 12548 switch(V.getNode()->getOpcode()) { 12549 default: 12550 return false; 12551 case ISD::LOAD: { 12552 LoadSDNode *LoadNode = cast<LoadSDNode>(V.getNode()); 12553 if ((LoadNode->getMemoryVT() == MVT::i8 && width == 8) 12554 || (LoadNode->getMemoryVT() == MVT::i16 && width == 16)) { 12555 ExtType = LoadNode->getExtensionType(); 12556 return true; 12557 } 12558 return false; 12559 } 12560 case ISD::AssertSext: { 12561 VTSDNode *TypeNode = cast<VTSDNode>(V.getNode()->getOperand(1)); 12562 if ((TypeNode->getVT() == MVT::i8 && width == 8) 12563 || (TypeNode->getVT() == MVT::i16 && width == 16)) { 12564 ExtType = ISD::SEXTLOAD; 12565 return true; 12566 } 12567 return false; 12568 } 12569 case ISD::AssertZext: { 12570 VTSDNode *TypeNode = cast<VTSDNode>(V.getNode()->getOperand(1)); 12571 if ((TypeNode->getVT() == MVT::i8 && width == 8) 12572 || (TypeNode->getVT() == MVT::i16 && width == 16)) { 12573 ExtType = ISD::ZEXTLOAD; 12574 return true; 12575 } 12576 return false; 12577 } 12578 case ISD::Constant: 12579 case ISD::TargetConstant: { 12580 return std::abs(cast<ConstantSDNode>(V.getNode())->getSExtValue()) < 12581 1LL << (width - 1); 12582 } 12583 } 12584 12585 return true; 12586 } 12587 12588 // This function does a whole lot of voodoo to determine if the tests are 12589 // equivalent without and with a mask. Essentially what happens is that given a 12590 // DAG resembling: 12591 // 12592 // +-------------+ +-------------+ +-------------+ +-------------+ 12593 // | Input | | AddConstant | | CompConstant| | CC | 12594 // +-------------+ +-------------+ +-------------+ +-------------+ 12595 // | | | | 12596 // V V | +----------+ 12597 // +-------------+ +----+ | | 12598 // | ADD | |0xff| | | 12599 // +-------------+ +----+ | | 12600 // | | | | 12601 // V V | | 12602 // +-------------+ | | 12603 // | AND | | | 12604 // +-------------+ | | 12605 // | | | 12606 // +-----+ | | 12607 // | | | 12608 // V V V 12609 // +-------------+ 12610 // | CMP | 12611 // +-------------+ 12612 // 12613 // The AND node may be safely removed for some combinations of inputs. In 12614 // particular we need to take into account the extension type of the Input, 12615 // the exact values of AddConstant, CompConstant, and CC, along with the nominal 12616 // width of the input (this can work for any width inputs, the above graph is 12617 // specific to 8 bits. 12618 // 12619 // The specific equations were worked out by generating output tables for each 12620 // AArch64CC value in terms of and AddConstant (w1), CompConstant(w2). The 12621 // problem was simplified by working with 4 bit inputs, which means we only 12622 // needed to reason about 24 distinct bit patterns: 8 patterns unique to zero 12623 // extension (8,15), 8 patterns unique to sign extensions (-8,-1), and 8 12624 // patterns present in both extensions (0,7). For every distinct set of 12625 // AddConstant and CompConstants bit patterns we can consider the masked and 12626 // unmasked versions to be equivalent if the result of this function is true for 12627 // all 16 distinct bit patterns of for the current extension type of Input (w0). 12628 // 12629 // sub w8, w0, w1 12630 // and w10, w8, #0x0f 12631 // cmp w8, w2 12632 // cset w9, AArch64CC 12633 // cmp w10, w2 12634 // cset w11, AArch64CC 12635 // cmp w9, w11 12636 // cset w0, eq 12637 // ret 12638 // 12639 // Since the above function shows when the outputs are equivalent it defines 12640 // when it is safe to remove the AND. Unfortunately it only runs on AArch64 and 12641 // would be expensive to run during compiles. The equations below were written 12642 // in a test harness that confirmed they gave equivalent outputs to the above 12643 // for all inputs function, so they can be used determine if the removal is 12644 // legal instead. 12645 // 12646 // isEquivalentMaskless() is the code for testing if the AND can be removed 12647 // factored out of the DAG recognition as the DAG can take several forms. 12648 12649 static bool isEquivalentMaskless(unsigned CC, unsigned width, 12650 ISD::LoadExtType ExtType, int AddConstant, 12651 int CompConstant) { 12652 // By being careful about our equations and only writing the in term 12653 // symbolic values and well known constants (0, 1, -1, MaxUInt) we can 12654 // make them generally applicable to all bit widths. 12655 int MaxUInt = (1 << width); 12656 12657 // For the purposes of these comparisons sign extending the type is 12658 // equivalent to zero extending the add and displacing it by half the integer 12659 // width. Provided we are careful and make sure our equations are valid over 12660 // the whole range we can just adjust the input and avoid writing equations 12661 // for sign extended inputs. 12662 if (ExtType == ISD::SEXTLOAD) 12663 AddConstant -= (1 << (width-1)); 12664 12665 switch(CC) { 12666 case AArch64CC::LE: 12667 case AArch64CC::GT: 12668 if ((AddConstant == 0) || 12669 (CompConstant == MaxUInt - 1 && AddConstant < 0) || 12670 (AddConstant >= 0 && CompConstant < 0) || 12671 (AddConstant <= 0 && CompConstant <= 0 && CompConstant < AddConstant)) 12672 return true; 12673 break; 12674 case AArch64CC::LT: 12675 case AArch64CC::GE: 12676 if ((AddConstant == 0) || 12677 (AddConstant >= 0 && CompConstant <= 0) || 12678 (AddConstant <= 0 && CompConstant <= 0 && CompConstant <= AddConstant)) 12679 return true; 12680 break; 12681 case AArch64CC::HI: 12682 case AArch64CC::LS: 12683 if ((AddConstant >= 0 && CompConstant < 0) || 12684 (AddConstant <= 0 && CompConstant >= -1 && 12685 CompConstant < AddConstant + MaxUInt)) 12686 return true; 12687 break; 12688 case AArch64CC::PL: 12689 case AArch64CC::MI: 12690 if ((AddConstant == 0) || 12691 (AddConstant > 0 && CompConstant <= 0) || 12692 (AddConstant < 0 && CompConstant <= AddConstant)) 12693 return true; 12694 break; 12695 case AArch64CC::LO: 12696 case AArch64CC::HS: 12697 if ((AddConstant >= 0 && CompConstant <= 0) || 12698 (AddConstant <= 0 && CompConstant >= 0 && 12699 CompConstant <= AddConstant + MaxUInt)) 12700 return true; 12701 break; 12702 case AArch64CC::EQ: 12703 case AArch64CC::NE: 12704 if ((AddConstant > 0 && CompConstant < 0) || 12705 (AddConstant < 0 && CompConstant >= 0 && 12706 CompConstant < AddConstant + MaxUInt) || 12707 (AddConstant >= 0 && CompConstant >= 0 && 12708 CompConstant >= AddConstant) || 12709 (AddConstant <= 0 && CompConstant < 0 && CompConstant < AddConstant)) 12710 return true; 12711 break; 12712 case AArch64CC::VS: 12713 case AArch64CC::VC: 12714 case AArch64CC::AL: 12715 case AArch64CC::NV: 12716 return true; 12717 case AArch64CC::Invalid: 12718 break; 12719 } 12720 12721 return false; 12722 } 12723 12724 static 12725 SDValue performCONDCombine(SDNode *N, 12726 TargetLowering::DAGCombinerInfo &DCI, 12727 SelectionDAG &DAG, unsigned CCIndex, 12728 unsigned CmpIndex) { 12729 unsigned CC = cast<ConstantSDNode>(N->getOperand(CCIndex))->getSExtValue(); 12730 SDNode *SubsNode = N->getOperand(CmpIndex).getNode(); 12731 unsigned CondOpcode = SubsNode->getOpcode(); 12732 12733 if (CondOpcode != AArch64ISD::SUBS) 12734 return SDValue(); 12735 12736 // There is a SUBS feeding this condition. Is it fed by a mask we can 12737 // use? 12738 12739 SDNode *AndNode = SubsNode->getOperand(0).getNode(); 12740 unsigned MaskBits = 0; 12741 12742 if (AndNode->getOpcode() != ISD::AND) 12743 return SDValue(); 12744 12745 if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(AndNode->getOperand(1))) { 12746 uint32_t CNV = CN->getZExtValue(); 12747 if (CNV == 255) 12748 MaskBits = 8; 12749 else if (CNV == 65535) 12750 MaskBits = 16; 12751 } 12752 12753 if (!MaskBits) 12754 return SDValue(); 12755 12756 SDValue AddValue = AndNode->getOperand(0); 12757 12758 if (AddValue.getOpcode() != ISD::ADD) 12759 return SDValue(); 12760 12761 // The basic dag structure is correct, grab the inputs and validate them. 12762 12763 SDValue AddInputValue1 = AddValue.getNode()->getOperand(0); 12764 SDValue AddInputValue2 = AddValue.getNode()->getOperand(1); 12765 SDValue SubsInputValue = SubsNode->getOperand(1); 12766 12767 // The mask is present and the provenance of all the values is a smaller type, 12768 // lets see if the mask is superfluous. 12769 12770 if (!isa<ConstantSDNode>(AddInputValue2.getNode()) || 12771 !isa<ConstantSDNode>(SubsInputValue.getNode())) 12772 return SDValue(); 12773 12774 ISD::LoadExtType ExtType; 12775 12776 if (!checkValueWidth(SubsInputValue, MaskBits, ExtType) || 12777 !checkValueWidth(AddInputValue2, MaskBits, ExtType) || 12778 !checkValueWidth(AddInputValue1, MaskBits, ExtType) ) 12779 return SDValue(); 12780 12781 if(!isEquivalentMaskless(CC, MaskBits, ExtType, 12782 cast<ConstantSDNode>(AddInputValue2.getNode())->getSExtValue(), 12783 cast<ConstantSDNode>(SubsInputValue.getNode())->getSExtValue())) 12784 return SDValue(); 12785 12786 // The AND is not necessary, remove it. 12787 12788 SDVTList VTs = DAG.getVTList(SubsNode->getValueType(0), 12789 SubsNode->getValueType(1)); 12790 SDValue Ops[] = { AddValue, SubsNode->getOperand(1) }; 12791 12792 SDValue NewValue = DAG.getNode(CondOpcode, SDLoc(SubsNode), VTs, Ops); 12793 DAG.ReplaceAllUsesWith(SubsNode, NewValue.getNode()); 12794 12795 return SDValue(N, 0); 12796 } 12797 12798 // Optimize compare with zero and branch. 12799 static SDValue performBRCONDCombine(SDNode *N, 12800 TargetLowering::DAGCombinerInfo &DCI, 12801 SelectionDAG &DAG) { 12802 MachineFunction &MF = DAG.getMachineFunction(); 12803 // Speculation tracking/SLH assumes that optimized TB(N)Z/CB(N)Z instructions 12804 // will not be produced, as they are conditional branch instructions that do 12805 // not set flags. 12806 if (MF.getFunction().hasFnAttribute(Attribute::SpeculativeLoadHardening)) 12807 return SDValue(); 12808 12809 if (SDValue NV = performCONDCombine(N, DCI, DAG, 2, 3)) 12810 N = NV.getNode(); 12811 SDValue Chain = N->getOperand(0); 12812 SDValue Dest = N->getOperand(1); 12813 SDValue CCVal = N->getOperand(2); 12814 SDValue Cmp = N->getOperand(3); 12815 12816 assert(isa<ConstantSDNode>(CCVal) && "Expected a ConstantSDNode here!"); 12817 unsigned CC = cast<ConstantSDNode>(CCVal)->getZExtValue(); 12818 if (CC != AArch64CC::EQ && CC != AArch64CC::NE) 12819 return SDValue(); 12820 12821 unsigned CmpOpc = Cmp.getOpcode(); 12822 if (CmpOpc != AArch64ISD::ADDS && CmpOpc != AArch64ISD::SUBS) 12823 return SDValue(); 12824 12825 // Only attempt folding if there is only one use of the flag and no use of the 12826 // value. 12827 if (!Cmp->hasNUsesOfValue(0, 0) || !Cmp->hasNUsesOfValue(1, 1)) 12828 return SDValue(); 12829 12830 SDValue LHS = Cmp.getOperand(0); 12831 SDValue RHS = Cmp.getOperand(1); 12832 12833 assert(LHS.getValueType() == RHS.getValueType() && 12834 "Expected the value type to be the same for both operands!"); 12835 if (LHS.getValueType() != MVT::i32 && LHS.getValueType() != MVT::i64) 12836 return SDValue(); 12837 12838 if (isNullConstant(LHS)) 12839 std::swap(LHS, RHS); 12840 12841 if (!isNullConstant(RHS)) 12842 return SDValue(); 12843 12844 if (LHS.getOpcode() == ISD::SHL || LHS.getOpcode() == ISD::SRA || 12845 LHS.getOpcode() == ISD::SRL) 12846 return SDValue(); 12847 12848 // Fold the compare into the branch instruction. 12849 SDValue BR; 12850 if (CC == AArch64CC::EQ) 12851 BR = DAG.getNode(AArch64ISD::CBZ, SDLoc(N), MVT::Other, Chain, LHS, Dest); 12852 else 12853 BR = DAG.getNode(AArch64ISD::CBNZ, SDLoc(N), MVT::Other, Chain, LHS, Dest); 12854 12855 // Do not add new nodes to DAG combiner worklist. 12856 DCI.CombineTo(N, BR, false); 12857 12858 return SDValue(); 12859 } 12860 12861 // Optimize some simple tbz/tbnz cases. Returns the new operand and bit to test 12862 // as well as whether the test should be inverted. This code is required to 12863 // catch these cases (as opposed to standard dag combines) because 12864 // AArch64ISD::TBZ is matched during legalization. 12865 static SDValue getTestBitOperand(SDValue Op, unsigned &Bit, bool &Invert, 12866 SelectionDAG &DAG) { 12867 12868 if (!Op->hasOneUse()) 12869 return Op; 12870 12871 // We don't handle undef/constant-fold cases below, as they should have 12872 // already been taken care of (e.g. and of 0, test of undefined shifted bits, 12873 // etc.) 12874 12875 // (tbz (trunc x), b) -> (tbz x, b) 12876 // This case is just here to enable more of the below cases to be caught. 12877 if (Op->getOpcode() == ISD::TRUNCATE && 12878 Bit < Op->getValueType(0).getSizeInBits()) { 12879 return getTestBitOperand(Op->getOperand(0), Bit, Invert, DAG); 12880 } 12881 12882 // (tbz (any_ext x), b) -> (tbz x, b) if we don't use the extended bits. 12883 if (Op->getOpcode() == ISD::ANY_EXTEND && 12884 Bit < Op->getOperand(0).getValueSizeInBits()) { 12885 return getTestBitOperand(Op->getOperand(0), Bit, Invert, DAG); 12886 } 12887 12888 if (Op->getNumOperands() != 2) 12889 return Op; 12890 12891 auto *C = dyn_cast<ConstantSDNode>(Op->getOperand(1)); 12892 if (!C) 12893 return Op; 12894 12895 switch (Op->getOpcode()) { 12896 default: 12897 return Op; 12898 12899 // (tbz (and x, m), b) -> (tbz x, b) 12900 case ISD::AND: 12901 if ((C->getZExtValue() >> Bit) & 1) 12902 return getTestBitOperand(Op->getOperand(0), Bit, Invert, DAG); 12903 return Op; 12904 12905 // (tbz (shl x, c), b) -> (tbz x, b-c) 12906 case ISD::SHL: 12907 if (C->getZExtValue() <= Bit && 12908 (Bit - C->getZExtValue()) < Op->getValueType(0).getSizeInBits()) { 12909 Bit = Bit - C->getZExtValue(); 12910 return getTestBitOperand(Op->getOperand(0), Bit, Invert, DAG); 12911 } 12912 return Op; 12913 12914 // (tbz (sra x, c), b) -> (tbz x, b+c) or (tbz x, msb) if b+c is > # bits in x 12915 case ISD::SRA: 12916 Bit = Bit + C->getZExtValue(); 12917 if (Bit >= Op->getValueType(0).getSizeInBits()) 12918 Bit = Op->getValueType(0).getSizeInBits() - 1; 12919 return getTestBitOperand(Op->getOperand(0), Bit, Invert, DAG); 12920 12921 // (tbz (srl x, c), b) -> (tbz x, b+c) 12922 case ISD::SRL: 12923 if ((Bit + C->getZExtValue()) < Op->getValueType(0).getSizeInBits()) { 12924 Bit = Bit + C->getZExtValue(); 12925 return getTestBitOperand(Op->getOperand(0), Bit, Invert, DAG); 12926 } 12927 return Op; 12928 12929 // (tbz (xor x, -1), b) -> (tbnz x, b) 12930 case ISD::XOR: 12931 if ((C->getZExtValue() >> Bit) & 1) 12932 Invert = !Invert; 12933 return getTestBitOperand(Op->getOperand(0), Bit, Invert, DAG); 12934 } 12935 } 12936 12937 // Optimize test single bit zero/non-zero and branch. 12938 static SDValue performTBZCombine(SDNode *N, 12939 TargetLowering::DAGCombinerInfo &DCI, 12940 SelectionDAG &DAG) { 12941 unsigned Bit = cast<ConstantSDNode>(N->getOperand(2))->getZExtValue(); 12942 bool Invert = false; 12943 SDValue TestSrc = N->getOperand(1); 12944 SDValue NewTestSrc = getTestBitOperand(TestSrc, Bit, Invert, DAG); 12945 12946 if (TestSrc == NewTestSrc) 12947 return SDValue(); 12948 12949 unsigned NewOpc = N->getOpcode(); 12950 if (Invert) { 12951 if (NewOpc == AArch64ISD::TBZ) 12952 NewOpc = AArch64ISD::TBNZ; 12953 else { 12954 assert(NewOpc == AArch64ISD::TBNZ); 12955 NewOpc = AArch64ISD::TBZ; 12956 } 12957 } 12958 12959 SDLoc DL(N); 12960 return DAG.getNode(NewOpc, DL, MVT::Other, N->getOperand(0), NewTestSrc, 12961 DAG.getConstant(Bit, DL, MVT::i64), N->getOperand(3)); 12962 } 12963 12964 // vselect (v1i1 setcc) -> 12965 // vselect (v1iXX setcc) (XX is the size of the compared operand type) 12966 // FIXME: Currently the type legalizer can't handle VSELECT having v1i1 as 12967 // condition. If it can legalize "VSELECT v1i1" correctly, no need to combine 12968 // such VSELECT. 12969 static SDValue performVSelectCombine(SDNode *N, SelectionDAG &DAG) { 12970 SDValue N0 = N->getOperand(0); 12971 EVT CCVT = N0.getValueType(); 12972 12973 if (N0.getOpcode() != ISD::SETCC || CCVT.getVectorNumElements() != 1 || 12974 CCVT.getVectorElementType() != MVT::i1) 12975 return SDValue(); 12976 12977 EVT ResVT = N->getValueType(0); 12978 EVT CmpVT = N0.getOperand(0).getValueType(); 12979 // Only combine when the result type is of the same size as the compared 12980 // operands. 12981 if (ResVT.getSizeInBits() != CmpVT.getSizeInBits()) 12982 return SDValue(); 12983 12984 SDValue IfTrue = N->getOperand(1); 12985 SDValue IfFalse = N->getOperand(2); 12986 SDValue SetCC = 12987 DAG.getSetCC(SDLoc(N), CmpVT.changeVectorElementTypeToInteger(), 12988 N0.getOperand(0), N0.getOperand(1), 12989 cast<CondCodeSDNode>(N0.getOperand(2))->get()); 12990 return DAG.getNode(ISD::VSELECT, SDLoc(N), ResVT, SetCC, 12991 IfTrue, IfFalse); 12992 } 12993 12994 /// A vector select: "(select vL, vR, (setcc LHS, RHS))" is best performed with 12995 /// the compare-mask instructions rather than going via NZCV, even if LHS and 12996 /// RHS are really scalar. This replaces any scalar setcc in the above pattern 12997 /// with a vector one followed by a DUP shuffle on the result. 12998 static SDValue performSelectCombine(SDNode *N, 12999 TargetLowering::DAGCombinerInfo &DCI) { 13000 SelectionDAG &DAG = DCI.DAG; 13001 SDValue N0 = N->getOperand(0); 13002 EVT ResVT = N->getValueType(0); 13003 13004 if (N0.getOpcode() != ISD::SETCC) 13005 return SDValue(); 13006 13007 // Make sure the SETCC result is either i1 (initial DAG), or i32, the lowered 13008 // scalar SetCCResultType. We also don't expect vectors, because we assume 13009 // that selects fed by vector SETCCs are canonicalized to VSELECT. 13010 assert((N0.getValueType() == MVT::i1 || N0.getValueType() == MVT::i32) && 13011 "Scalar-SETCC feeding SELECT has unexpected result type!"); 13012 13013 // If NumMaskElts == 0, the comparison is larger than select result. The 13014 // largest real NEON comparison is 64-bits per lane, which means the result is 13015 // at most 32-bits and an illegal vector. Just bail out for now. 13016 EVT SrcVT = N0.getOperand(0).getValueType(); 13017 13018 // Don't try to do this optimization when the setcc itself has i1 operands. 13019 // There are no legal vectors of i1, so this would be pointless. 13020 if (SrcVT == MVT::i1) 13021 return SDValue(); 13022 13023 int NumMaskElts = ResVT.getSizeInBits() / SrcVT.getSizeInBits(); 13024 if (!ResVT.isVector() || NumMaskElts == 0) 13025 return SDValue(); 13026 13027 SrcVT = EVT::getVectorVT(*DAG.getContext(), SrcVT, NumMaskElts); 13028 EVT CCVT = SrcVT.changeVectorElementTypeToInteger(); 13029 13030 // Also bail out if the vector CCVT isn't the same size as ResVT. 13031 // This can happen if the SETCC operand size doesn't divide the ResVT size 13032 // (e.g., f64 vs v3f32). 13033 if (CCVT.getSizeInBits() != ResVT.getSizeInBits()) 13034 return SDValue(); 13035 13036 // Make sure we didn't create illegal types, if we're not supposed to. 13037 assert(DCI.isBeforeLegalize() || 13038 DAG.getTargetLoweringInfo().isTypeLegal(SrcVT)); 13039 13040 // First perform a vector comparison, where lane 0 is the one we're interested 13041 // in. 13042 SDLoc DL(N0); 13043 SDValue LHS = 13044 DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, SrcVT, N0.getOperand(0)); 13045 SDValue RHS = 13046 DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, SrcVT, N0.getOperand(1)); 13047 SDValue SetCC = DAG.getNode(ISD::SETCC, DL, CCVT, LHS, RHS, N0.getOperand(2)); 13048 13049 // Now duplicate the comparison mask we want across all other lanes. 13050 SmallVector<int, 8> DUPMask(CCVT.getVectorNumElements(), 0); 13051 SDValue Mask = DAG.getVectorShuffle(CCVT, DL, SetCC, SetCC, DUPMask); 13052 Mask = DAG.getNode(ISD::BITCAST, DL, 13053 ResVT.changeVectorElementTypeToInteger(), Mask); 13054 13055 return DAG.getSelect(DL, ResVT, Mask, N->getOperand(1), N->getOperand(2)); 13056 } 13057 13058 /// Get rid of unnecessary NVCASTs (that don't change the type). 13059 static SDValue performNVCASTCombine(SDNode *N) { 13060 if (N->getValueType(0) == N->getOperand(0).getValueType()) 13061 return N->getOperand(0); 13062 13063 return SDValue(); 13064 } 13065 13066 // If all users of the globaladdr are of the form (globaladdr + constant), find 13067 // the smallest constant, fold it into the globaladdr's offset and rewrite the 13068 // globaladdr as (globaladdr + constant) - constant. 13069 static SDValue performGlobalAddressCombine(SDNode *N, SelectionDAG &DAG, 13070 const AArch64Subtarget *Subtarget, 13071 const TargetMachine &TM) { 13072 auto *GN = cast<GlobalAddressSDNode>(N); 13073 if (Subtarget->ClassifyGlobalReference(GN->getGlobal(), TM) != 13074 AArch64II::MO_NO_FLAG) 13075 return SDValue(); 13076 13077 uint64_t MinOffset = -1ull; 13078 for (SDNode *N : GN->uses()) { 13079 if (N->getOpcode() != ISD::ADD) 13080 return SDValue(); 13081 auto *C = dyn_cast<ConstantSDNode>(N->getOperand(0)); 13082 if (!C) 13083 C = dyn_cast<ConstantSDNode>(N->getOperand(1)); 13084 if (!C) 13085 return SDValue(); 13086 MinOffset = std::min(MinOffset, C->getZExtValue()); 13087 } 13088 uint64_t Offset = MinOffset + GN->getOffset(); 13089 13090 // Require that the new offset is larger than the existing one. Otherwise, we 13091 // can end up oscillating between two possible DAGs, for example, 13092 // (add (add globaladdr + 10, -1), 1) and (add globaladdr + 9, 1). 13093 if (Offset <= uint64_t(GN->getOffset())) 13094 return SDValue(); 13095 13096 // Check whether folding this offset is legal. It must not go out of bounds of 13097 // the referenced object to avoid violating the code model, and must be 13098 // smaller than 2^21 because this is the largest offset expressible in all 13099 // object formats. 13100 // 13101 // This check also prevents us from folding negative offsets, which will end 13102 // up being treated in the same way as large positive ones. They could also 13103 // cause code model violations, and aren't really common enough to matter. 13104 if (Offset >= (1 << 21)) 13105 return SDValue(); 13106 13107 const GlobalValue *GV = GN->getGlobal(); 13108 Type *T = GV->getValueType(); 13109 if (!T->isSized() || 13110 Offset > GV->getParent()->getDataLayout().getTypeAllocSize(T)) 13111 return SDValue(); 13112 13113 SDLoc DL(GN); 13114 SDValue Result = DAG.getGlobalAddress(GV, DL, MVT::i64, Offset); 13115 return DAG.getNode(ISD::SUB, DL, MVT::i64, Result, 13116 DAG.getConstant(MinOffset, DL, MVT::i64)); 13117 } 13118 13119 // Turns the vector of indices into a vector of byte offstes by scaling Offset 13120 // by (BitWidth / 8). 13121 static SDValue getScaledOffsetForBitWidth(SelectionDAG &DAG, SDValue Offset, 13122 SDLoc DL, unsigned BitWidth) { 13123 assert(Offset.getValueType().isScalableVector() && 13124 "This method is only for scalable vectors of offsets"); 13125 13126 SDValue Shift = DAG.getConstant(Log2_32(BitWidth / 8), DL, MVT::i64); 13127 SDValue SplatShift = DAG.getNode(ISD::SPLAT_VECTOR, DL, MVT::nxv2i64, Shift); 13128 13129 return DAG.getNode(ISD::SHL, DL, MVT::nxv2i64, Offset, SplatShift); 13130 } 13131 13132 /// Check if the value of \p OffsetInBytes can be used as an immediate for 13133 /// the gather load/prefetch and scatter store instructions with vector base and 13134 /// immediate offset addressing mode: 13135 /// 13136 /// [<Zn>.[S|D]{, #<imm>}] 13137 /// 13138 /// where <imm> = sizeof(<T>) * k, for k = 0, 1, ..., 31. 13139 13140 inline static bool isValidImmForSVEVecImmAddrMode(unsigned OffsetInBytes, 13141 unsigned ScalarSizeInBytes) { 13142 // The immediate is not a multiple of the scalar size. 13143 if (OffsetInBytes % ScalarSizeInBytes) 13144 return false; 13145 13146 // The immediate is out of range. 13147 if (OffsetInBytes / ScalarSizeInBytes > 31) 13148 return false; 13149 13150 return true; 13151 } 13152 13153 /// Check if the value of \p Offset represents a valid immediate for the SVE 13154 /// gather load/prefetch and scatter store instructiona with vector base and 13155 /// immediate offset addressing mode: 13156 /// 13157 /// [<Zn>.[S|D]{, #<imm>}] 13158 /// 13159 /// where <imm> = sizeof(<T>) * k, for k = 0, 1, ..., 31. 13160 static bool isValidImmForSVEVecImmAddrMode(SDValue Offset, 13161 unsigned ScalarSizeInBytes) { 13162 ConstantSDNode *OffsetConst = dyn_cast<ConstantSDNode>(Offset.getNode()); 13163 return OffsetConst && isValidImmForSVEVecImmAddrMode( 13164 OffsetConst->getZExtValue(), ScalarSizeInBytes); 13165 } 13166 13167 static SDValue performScatterStoreCombine(SDNode *N, SelectionDAG &DAG, 13168 unsigned Opcode, 13169 bool OnlyPackedOffsets = true) { 13170 const SDValue Src = N->getOperand(2); 13171 const EVT SrcVT = Src->getValueType(0); 13172 assert(SrcVT.isScalableVector() && 13173 "Scatter stores are only possible for SVE vectors"); 13174 13175 SDLoc DL(N); 13176 MVT SrcElVT = SrcVT.getVectorElementType().getSimpleVT(); 13177 13178 // Make sure that source data will fit into an SVE register 13179 if (SrcVT.getSizeInBits().getKnownMinSize() > AArch64::SVEBitsPerBlock) 13180 return SDValue(); 13181 13182 // For FPs, ACLE only supports _packed_ single and double precision types. 13183 if (SrcElVT.isFloatingPoint()) 13184 if ((SrcVT != MVT::nxv4f32) && (SrcVT != MVT::nxv2f64)) 13185 return SDValue(); 13186 13187 // Depending on the addressing mode, this is either a pointer or a vector of 13188 // pointers (that fits into one register) 13189 SDValue Base = N->getOperand(4); 13190 // Depending on the addressing mode, this is either a single offset or a 13191 // vector of offsets (that fits into one register) 13192 SDValue Offset = N->getOperand(5); 13193 13194 // For "scalar + vector of indices", just scale the indices. This only 13195 // applies to non-temporal scatters because there's no instruction that takes 13196 // indicies. 13197 if (Opcode == AArch64ISD::SSTNT1_INDEX) { 13198 Offset = 13199 getScaledOffsetForBitWidth(DAG, Offset, DL, SrcElVT.getSizeInBits()); 13200 Opcode = AArch64ISD::SSTNT1; 13201 } 13202 13203 // In the case of non-temporal gather loads there's only one SVE instruction 13204 // per data-size: "scalar + vector", i.e. 13205 // * stnt1{b|h|w|d} { z0.s }, p0/z, [z0.s, x0] 13206 // Since we do have intrinsics that allow the arguments to be in a different 13207 // order, we may need to swap them to match the spec. 13208 if (Opcode == AArch64ISD::SSTNT1 && Offset.getValueType().isVector()) 13209 std::swap(Base, Offset); 13210 13211 // SST1_IMM requires that the offset is an immediate that is: 13212 // * a multiple of #SizeInBytes, 13213 // * in the range [0, 31 x #SizeInBytes], 13214 // where #SizeInBytes is the size in bytes of the stored items. For 13215 // immediates outside that range and non-immediate scalar offsets use SST1 or 13216 // SST1_UXTW instead. 13217 if (Opcode == AArch64ISD::SST1_IMM) { 13218 if (!isValidImmForSVEVecImmAddrMode(Offset, 13219 SrcVT.getScalarSizeInBits() / 8)) { 13220 if (MVT::nxv4i32 == Base.getValueType().getSimpleVT().SimpleTy) 13221 Opcode = AArch64ISD::SST1_UXTW; 13222 else 13223 Opcode = AArch64ISD::SST1; 13224 13225 std::swap(Base, Offset); 13226 } 13227 } 13228 13229 auto &TLI = DAG.getTargetLoweringInfo(); 13230 if (!TLI.isTypeLegal(Base.getValueType())) 13231 return SDValue(); 13232 13233 // Some scatter store variants allow unpacked offsets, but only as nxv2i32 13234 // vectors. These are implicitly sign (sxtw) or zero (zxtw) extend to 13235 // nxv2i64. Legalize accordingly. 13236 if (!OnlyPackedOffsets && 13237 Offset.getValueType().getSimpleVT().SimpleTy == MVT::nxv2i32) 13238 Offset = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::nxv2i64, Offset).getValue(0); 13239 13240 if (!TLI.isTypeLegal(Offset.getValueType())) 13241 return SDValue(); 13242 13243 // Source value type that is representable in hardware 13244 EVT HwSrcVt = getSVEContainerType(SrcVT); 13245 13246 // Keep the original type of the input data to store - this is needed to be 13247 // able to select the correct instruction, e.g. ST1B, ST1H, ST1W and ST1D. For 13248 // FP values we want the integer equivalent, so just use HwSrcVt. 13249 SDValue InputVT = DAG.getValueType(SrcVT); 13250 if (SrcVT.isFloatingPoint()) 13251 InputVT = DAG.getValueType(HwSrcVt); 13252 13253 SDVTList VTs = DAG.getVTList(MVT::Other); 13254 SDValue SrcNew; 13255 13256 if (Src.getValueType().isFloatingPoint()) 13257 SrcNew = DAG.getNode(ISD::BITCAST, DL, HwSrcVt, Src); 13258 else 13259 SrcNew = DAG.getNode(ISD::ANY_EXTEND, DL, HwSrcVt, Src); 13260 13261 SDValue Ops[] = {N->getOperand(0), // Chain 13262 SrcNew, 13263 N->getOperand(3), // Pg 13264 Base, 13265 Offset, 13266 InputVT}; 13267 13268 return DAG.getNode(Opcode, DL, VTs, Ops); 13269 } 13270 13271 static SDValue performGatherLoadCombine(SDNode *N, SelectionDAG &DAG, 13272 unsigned Opcode, 13273 bool OnlyPackedOffsets = true) { 13274 const EVT RetVT = N->getValueType(0); 13275 assert(RetVT.isScalableVector() && 13276 "Gather loads are only possible for SVE vectors"); 13277 13278 SDLoc DL(N); 13279 13280 // Make sure that the loaded data will fit into an SVE register 13281 if (RetVT.getSizeInBits().getKnownMinSize() > AArch64::SVEBitsPerBlock) 13282 return SDValue(); 13283 13284 // Depending on the addressing mode, this is either a pointer or a vector of 13285 // pointers (that fits into one register) 13286 SDValue Base = N->getOperand(3); 13287 // Depending on the addressing mode, this is either a single offset or a 13288 // vector of offsets (that fits into one register) 13289 SDValue Offset = N->getOperand(4); 13290 13291 // For "scalar + vector of indices", just scale the indices. This only 13292 // applies to non-temporal gathers because there's no instruction that takes 13293 // indicies. 13294 if (Opcode == AArch64ISD::GLDNT1_INDEX) { 13295 Offset = getScaledOffsetForBitWidth(DAG, Offset, DL, 13296 RetVT.getScalarSizeInBits()); 13297 Opcode = AArch64ISD::GLDNT1; 13298 } 13299 13300 // In the case of non-temporal gather loads there's only one SVE instruction 13301 // per data-size: "scalar + vector", i.e. 13302 // * ldnt1{b|h|w|d} { z0.s }, p0/z, [z0.s, x0] 13303 // Since we do have intrinsics that allow the arguments to be in a different 13304 // order, we may need to swap them to match the spec. 13305 if (Opcode == AArch64ISD::GLDNT1 && Offset.getValueType().isVector()) 13306 std::swap(Base, Offset); 13307 13308 // GLD{FF}1_IMM requires that the offset is an immediate that is: 13309 // * a multiple of #SizeInBytes, 13310 // * in the range [0, 31 x #SizeInBytes], 13311 // where #SizeInBytes is the size in bytes of the loaded items. For 13312 // immediates outside that range and non-immediate scalar offsets use GLD1 or 13313 // GLD1_UXTW instead. 13314 if (Opcode == AArch64ISD::GLD1_IMM || Opcode == AArch64ISD::GLDFF1_IMM) { 13315 if (!isValidImmForSVEVecImmAddrMode(Offset, 13316 RetVT.getScalarSizeInBits() / 8)) { 13317 if (MVT::nxv4i32 == Base.getValueType().getSimpleVT().SimpleTy) 13318 Opcode = (Opcode == AArch64ISD::GLD1_IMM) ? AArch64ISD::GLD1_UXTW 13319 : AArch64ISD::GLDFF1_UXTW; 13320 else 13321 Opcode = (Opcode == AArch64ISD::GLD1_IMM) ? AArch64ISD::GLD1 13322 : AArch64ISD::GLDFF1; 13323 13324 std::swap(Base, Offset); 13325 } 13326 } 13327 13328 auto &TLI = DAG.getTargetLoweringInfo(); 13329 if (!TLI.isTypeLegal(Base.getValueType())) 13330 return SDValue(); 13331 13332 // Some gather load variants allow unpacked offsets, but only as nxv2i32 13333 // vectors. These are implicitly sign (sxtw) or zero (zxtw) extend to 13334 // nxv2i64. Legalize accordingly. 13335 if (!OnlyPackedOffsets && 13336 Offset.getValueType().getSimpleVT().SimpleTy == MVT::nxv2i32) 13337 Offset = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::nxv2i64, Offset).getValue(0); 13338 13339 // Return value type that is representable in hardware 13340 EVT HwRetVt = getSVEContainerType(RetVT); 13341 13342 // Keep the original output value type around - this is needed to be able to 13343 // select the correct instruction, e.g. LD1B, LD1H, LD1W and LD1D. For FP 13344 // values we want the integer equivalent, so just use HwRetVT. 13345 SDValue OutVT = DAG.getValueType(RetVT); 13346 if (RetVT.isFloatingPoint()) 13347 OutVT = DAG.getValueType(HwRetVt); 13348 13349 SDVTList VTs = DAG.getVTList(HwRetVt, MVT::Other); 13350 SDValue Ops[] = {N->getOperand(0), // Chain 13351 N->getOperand(2), // Pg 13352 Base, Offset, OutVT}; 13353 13354 SDValue Load = DAG.getNode(Opcode, DL, VTs, Ops); 13355 SDValue LoadChain = SDValue(Load.getNode(), 1); 13356 13357 if (RetVT.isInteger() && (RetVT != HwRetVt)) 13358 Load = DAG.getNode(ISD::TRUNCATE, DL, RetVT, Load.getValue(0)); 13359 13360 // If the original return value was FP, bitcast accordingly. Doing it here 13361 // means that we can avoid adding TableGen patterns for FPs. 13362 if (RetVT.isFloatingPoint()) 13363 Load = DAG.getNode(ISD::BITCAST, DL, RetVT, Load.getValue(0)); 13364 13365 return DAG.getMergeValues({Load, LoadChain}, DL); 13366 } 13367 13368 static SDValue 13369 performSignExtendInRegCombine(SDNode *N, TargetLowering::DAGCombinerInfo &DCI, 13370 SelectionDAG &DAG) { 13371 if (DCI.isBeforeLegalizeOps()) 13372 return SDValue(); 13373 13374 SDLoc DL(N); 13375 SDValue Src = N->getOperand(0); 13376 unsigned Opc = Src->getOpcode(); 13377 13378 // Sign extend of an unsigned unpack -> signed unpack 13379 if (Opc == AArch64ISD::UUNPKHI || Opc == AArch64ISD::UUNPKLO) { 13380 13381 unsigned SOpc = Opc == AArch64ISD::UUNPKHI ? AArch64ISD::SUNPKHI 13382 : AArch64ISD::SUNPKLO; 13383 13384 // Push the sign extend to the operand of the unpack 13385 // This is necessary where, for example, the operand of the unpack 13386 // is another unpack: 13387 // 4i32 sign_extend_inreg (4i32 uunpklo(8i16 uunpklo (16i8 opnd)), from 4i8) 13388 // -> 13389 // 4i32 sunpklo (8i16 sign_extend_inreg(8i16 uunpklo (16i8 opnd), from 8i8) 13390 // -> 13391 // 4i32 sunpklo(8i16 sunpklo(16i8 opnd)) 13392 SDValue ExtOp = Src->getOperand(0); 13393 auto VT = cast<VTSDNode>(N->getOperand(1))->getVT(); 13394 EVT EltTy = VT.getVectorElementType(); 13395 (void)EltTy; 13396 13397 assert((EltTy == MVT::i8 || EltTy == MVT::i16 || EltTy == MVT::i32) && 13398 "Sign extending from an invalid type"); 13399 13400 EVT ExtVT = EVT::getVectorVT(*DAG.getContext(), 13401 VT.getVectorElementType(), 13402 VT.getVectorElementCount() * 2); 13403 13404 SDValue Ext = DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, ExtOp.getValueType(), 13405 ExtOp, DAG.getValueType(ExtVT)); 13406 13407 return DAG.getNode(SOpc, DL, N->getValueType(0), Ext); 13408 } 13409 13410 // SVE load nodes (e.g. AArch64ISD::GLD1) are straightforward candidates 13411 // for DAG Combine with SIGN_EXTEND_INREG. Bail out for all other nodes. 13412 unsigned NewOpc; 13413 unsigned MemVTOpNum = 4; 13414 switch (Opc) { 13415 case AArch64ISD::LD1: 13416 NewOpc = AArch64ISD::LD1S; 13417 MemVTOpNum = 3; 13418 break; 13419 case AArch64ISD::LDNF1: 13420 NewOpc = AArch64ISD::LDNF1S; 13421 MemVTOpNum = 3; 13422 break; 13423 case AArch64ISD::LDFF1: 13424 NewOpc = AArch64ISD::LDFF1S; 13425 MemVTOpNum = 3; 13426 break; 13427 case AArch64ISD::GLD1: 13428 NewOpc = AArch64ISD::GLD1S; 13429 break; 13430 case AArch64ISD::GLD1_SCALED: 13431 NewOpc = AArch64ISD::GLD1S_SCALED; 13432 break; 13433 case AArch64ISD::GLD1_SXTW: 13434 NewOpc = AArch64ISD::GLD1S_SXTW; 13435 break; 13436 case AArch64ISD::GLD1_SXTW_SCALED: 13437 NewOpc = AArch64ISD::GLD1S_SXTW_SCALED; 13438 break; 13439 case AArch64ISD::GLD1_UXTW: 13440 NewOpc = AArch64ISD::GLD1S_UXTW; 13441 break; 13442 case AArch64ISD::GLD1_UXTW_SCALED: 13443 NewOpc = AArch64ISD::GLD1S_UXTW_SCALED; 13444 break; 13445 case AArch64ISD::GLD1_IMM: 13446 NewOpc = AArch64ISD::GLD1S_IMM; 13447 break; 13448 case AArch64ISD::GLDFF1: 13449 NewOpc = AArch64ISD::GLDFF1S; 13450 break; 13451 case AArch64ISD::GLDFF1_SCALED: 13452 NewOpc = AArch64ISD::GLDFF1S_SCALED; 13453 break; 13454 case AArch64ISD::GLDFF1_SXTW: 13455 NewOpc = AArch64ISD::GLDFF1S_SXTW; 13456 break; 13457 case AArch64ISD::GLDFF1_SXTW_SCALED: 13458 NewOpc = AArch64ISD::GLDFF1S_SXTW_SCALED; 13459 break; 13460 case AArch64ISD::GLDFF1_UXTW: 13461 NewOpc = AArch64ISD::GLDFF1S_UXTW; 13462 break; 13463 case AArch64ISD::GLDFF1_UXTW_SCALED: 13464 NewOpc = AArch64ISD::GLDFF1S_UXTW_SCALED; 13465 break; 13466 case AArch64ISD::GLDFF1_IMM: 13467 NewOpc = AArch64ISD::GLDFF1S_IMM; 13468 break; 13469 case AArch64ISD::GLDNT1: 13470 NewOpc = AArch64ISD::GLDNT1S; 13471 break; 13472 default: 13473 return SDValue(); 13474 } 13475 13476 EVT SignExtSrcVT = cast<VTSDNode>(N->getOperand(1))->getVT(); 13477 EVT SrcMemVT = cast<VTSDNode>(Src->getOperand(MemVTOpNum))->getVT(); 13478 13479 if ((SignExtSrcVT != SrcMemVT) || !Src.hasOneUse()) 13480 return SDValue(); 13481 13482 EVT DstVT = N->getValueType(0); 13483 SDVTList VTs = DAG.getVTList(DstVT, MVT::Other); 13484 13485 SmallVector<SDValue, 5> Ops; 13486 for (unsigned I = 0; I < Src->getNumOperands(); ++I) 13487 Ops.push_back(Src->getOperand(I)); 13488 13489 SDValue ExtLoad = DAG.getNode(NewOpc, SDLoc(N), VTs, Ops); 13490 DCI.CombineTo(N, ExtLoad); 13491 DCI.CombineTo(Src.getNode(), ExtLoad, ExtLoad.getValue(1)); 13492 13493 // Return N so it doesn't get rechecked 13494 return SDValue(N, 0); 13495 } 13496 13497 /// Legalize the gather prefetch (scalar + vector addressing mode) when the 13498 /// offset vector is an unpacked 32-bit scalable vector. The other cases (Offset 13499 /// != nxv2i32) do not need legalization. 13500 static SDValue legalizeSVEGatherPrefetchOffsVec(SDNode *N, SelectionDAG &DAG) { 13501 const unsigned OffsetPos = 4; 13502 SDValue Offset = N->getOperand(OffsetPos); 13503 13504 // Not an unpacked vector, bail out. 13505 if (Offset.getValueType().getSimpleVT().SimpleTy != MVT::nxv2i32) 13506 return SDValue(); 13507 13508 // Extend the unpacked offset vector to 64-bit lanes. 13509 SDLoc DL(N); 13510 Offset = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::nxv2i64, Offset); 13511 SmallVector<SDValue, 5> Ops(N->op_begin(), N->op_end()); 13512 // Replace the offset operand with the 64-bit one. 13513 Ops[OffsetPos] = Offset; 13514 13515 return DAG.getNode(N->getOpcode(), DL, DAG.getVTList(MVT::Other), Ops); 13516 } 13517 13518 /// Combines a node carrying the intrinsic 13519 /// `aarch64_sve_prf<T>_gather_scalar_offset` into a node that uses 13520 /// `aarch64_sve_prfb_gather_uxtw_index` when the scalar offset passed to 13521 /// `aarch64_sve_prf<T>_gather_scalar_offset` is not a valid immediate for the 13522 /// sve gather prefetch instruction with vector plus immediate addressing mode. 13523 static SDValue combineSVEPrefetchVecBaseImmOff(SDNode *N, SelectionDAG &DAG, 13524 unsigned ScalarSizeInBytes) { 13525 const unsigned ImmPos = 4, OffsetPos = 3; 13526 // No need to combine the node if the immediate is valid... 13527 if (isValidImmForSVEVecImmAddrMode(N->getOperand(ImmPos), ScalarSizeInBytes)) 13528 return SDValue(); 13529 13530 // ...otherwise swap the offset base with the offset... 13531 SmallVector<SDValue, 5> Ops(N->op_begin(), N->op_end()); 13532 std::swap(Ops[ImmPos], Ops[OffsetPos]); 13533 // ...and remap the intrinsic `aarch64_sve_prf<T>_gather_scalar_offset` to 13534 // `aarch64_sve_prfb_gather_uxtw_index`. 13535 SDLoc DL(N); 13536 Ops[1] = DAG.getConstant(Intrinsic::aarch64_sve_prfb_gather_uxtw_index, DL, 13537 MVT::i64); 13538 13539 return DAG.getNode(N->getOpcode(), DL, DAG.getVTList(MVT::Other), Ops); 13540 } 13541 13542 SDValue AArch64TargetLowering::PerformDAGCombine(SDNode *N, 13543 DAGCombinerInfo &DCI) const { 13544 SelectionDAG &DAG = DCI.DAG; 13545 switch (N->getOpcode()) { 13546 default: 13547 LLVM_DEBUG(dbgs() << "Custom combining: skipping\n"); 13548 break; 13549 case ISD::ADD: 13550 case ISD::SUB: 13551 return performAddSubLongCombine(N, DCI, DAG); 13552 case ISD::XOR: 13553 return performXorCombine(N, DAG, DCI, Subtarget); 13554 case ISD::MUL: 13555 return performMulCombine(N, DAG, DCI, Subtarget); 13556 case ISD::SINT_TO_FP: 13557 case ISD::UINT_TO_FP: 13558 return performIntToFpCombine(N, DAG, Subtarget); 13559 case ISD::FP_TO_SINT: 13560 case ISD::FP_TO_UINT: 13561 return performFpToIntCombine(N, DAG, DCI, Subtarget); 13562 case ISD::FDIV: 13563 return performFDivCombine(N, DAG, DCI, Subtarget); 13564 case ISD::OR: 13565 return performORCombine(N, DCI, Subtarget); 13566 case ISD::AND: 13567 return performANDCombine(N, DCI); 13568 case ISD::SRL: 13569 return performSRLCombine(N, DCI); 13570 case ISD::INTRINSIC_WO_CHAIN: 13571 return performIntrinsicCombine(N, DCI, Subtarget); 13572 case ISD::ANY_EXTEND: 13573 case ISD::ZERO_EXTEND: 13574 case ISD::SIGN_EXTEND: 13575 return performExtendCombine(N, DCI, DAG); 13576 case ISD::SIGN_EXTEND_INREG: 13577 return performSignExtendInRegCombine(N, DCI, DAG); 13578 case ISD::CONCAT_VECTORS: 13579 return performConcatVectorsCombine(N, DCI, DAG); 13580 case ISD::SELECT: 13581 return performSelectCombine(N, DCI); 13582 case ISD::VSELECT: 13583 return performVSelectCombine(N, DCI.DAG); 13584 case ISD::LOAD: 13585 if (performTBISimplification(N->getOperand(1), DCI, DAG)) 13586 return SDValue(N, 0); 13587 break; 13588 case ISD::STORE: 13589 return performSTORECombine(N, DCI, DAG, Subtarget); 13590 case AArch64ISD::BRCOND: 13591 return performBRCONDCombine(N, DCI, DAG); 13592 case AArch64ISD::TBNZ: 13593 case AArch64ISD::TBZ: 13594 return performTBZCombine(N, DCI, DAG); 13595 case AArch64ISD::CSEL: 13596 return performCONDCombine(N, DCI, DAG, 2, 3); 13597 case AArch64ISD::DUP: 13598 return performPostLD1Combine(N, DCI, false); 13599 case AArch64ISD::NVCAST: 13600 return performNVCASTCombine(N); 13601 case ISD::INSERT_VECTOR_ELT: 13602 return performPostLD1Combine(N, DCI, true); 13603 case ISD::INTRINSIC_VOID: 13604 case ISD::INTRINSIC_W_CHAIN: 13605 switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) { 13606 case Intrinsic::aarch64_sve_prfb_gather_scalar_offset: 13607 return combineSVEPrefetchVecBaseImmOff(N, DAG, 1 /*=ScalarSizeInBytes*/); 13608 case Intrinsic::aarch64_sve_prfh_gather_scalar_offset: 13609 return combineSVEPrefetchVecBaseImmOff(N, DAG, 2 /*=ScalarSizeInBytes*/); 13610 case Intrinsic::aarch64_sve_prfw_gather_scalar_offset: 13611 return combineSVEPrefetchVecBaseImmOff(N, DAG, 4 /*=ScalarSizeInBytes*/); 13612 case Intrinsic::aarch64_sve_prfd_gather_scalar_offset: 13613 return combineSVEPrefetchVecBaseImmOff(N, DAG, 8 /*=ScalarSizeInBytes*/); 13614 case Intrinsic::aarch64_sve_prfb_gather_uxtw_index: 13615 case Intrinsic::aarch64_sve_prfb_gather_sxtw_index: 13616 case Intrinsic::aarch64_sve_prfh_gather_uxtw_index: 13617 case Intrinsic::aarch64_sve_prfh_gather_sxtw_index: 13618 case Intrinsic::aarch64_sve_prfw_gather_uxtw_index: 13619 case Intrinsic::aarch64_sve_prfw_gather_sxtw_index: 13620 case Intrinsic::aarch64_sve_prfd_gather_uxtw_index: 13621 case Intrinsic::aarch64_sve_prfd_gather_sxtw_index: 13622 return legalizeSVEGatherPrefetchOffsVec(N, DAG); 13623 case Intrinsic::aarch64_neon_ld2: 13624 case Intrinsic::aarch64_neon_ld3: 13625 case Intrinsic::aarch64_neon_ld4: 13626 case Intrinsic::aarch64_neon_ld1x2: 13627 case Intrinsic::aarch64_neon_ld1x3: 13628 case Intrinsic::aarch64_neon_ld1x4: 13629 case Intrinsic::aarch64_neon_ld2lane: 13630 case Intrinsic::aarch64_neon_ld3lane: 13631 case Intrinsic::aarch64_neon_ld4lane: 13632 case Intrinsic::aarch64_neon_ld2r: 13633 case Intrinsic::aarch64_neon_ld3r: 13634 case Intrinsic::aarch64_neon_ld4r: 13635 case Intrinsic::aarch64_neon_st2: 13636 case Intrinsic::aarch64_neon_st3: 13637 case Intrinsic::aarch64_neon_st4: 13638 case Intrinsic::aarch64_neon_st1x2: 13639 case Intrinsic::aarch64_neon_st1x3: 13640 case Intrinsic::aarch64_neon_st1x4: 13641 case Intrinsic::aarch64_neon_st2lane: 13642 case Intrinsic::aarch64_neon_st3lane: 13643 case Intrinsic::aarch64_neon_st4lane: 13644 return performNEONPostLDSTCombine(N, DCI, DAG); 13645 case Intrinsic::aarch64_sve_ldnt1: 13646 return performLDNT1Combine(N, DAG); 13647 case Intrinsic::aarch64_sve_ld1rq: 13648 return performLD1ReplicateCombine<AArch64ISD::LD1RQ>(N, DAG); 13649 case Intrinsic::aarch64_sve_ld1ro: 13650 return performLD1ReplicateCombine<AArch64ISD::LD1RO>(N, DAG); 13651 case Intrinsic::aarch64_sve_ldnt1_gather_scalar_offset: 13652 return performGatherLoadCombine(N, DAG, AArch64ISD::GLDNT1); 13653 case Intrinsic::aarch64_sve_ldnt1_gather: 13654 return performGatherLoadCombine(N, DAG, AArch64ISD::GLDNT1); 13655 case Intrinsic::aarch64_sve_ldnt1_gather_index: 13656 return performGatherLoadCombine(N, DAG, AArch64ISD::GLDNT1_INDEX); 13657 case Intrinsic::aarch64_sve_ldnt1_gather_uxtw: 13658 return performGatherLoadCombine(N, DAG, AArch64ISD::GLDNT1); 13659 case Intrinsic::aarch64_sve_ld1: 13660 return performLD1Combine(N, DAG, AArch64ISD::LD1); 13661 case Intrinsic::aarch64_sve_ldnf1: 13662 return performLD1Combine(N, DAG, AArch64ISD::LDNF1); 13663 case Intrinsic::aarch64_sve_ldff1: 13664 return performLD1Combine(N, DAG, AArch64ISD::LDFF1); 13665 case Intrinsic::aarch64_sve_st1: 13666 return performST1Combine(N, DAG); 13667 case Intrinsic::aarch64_sve_stnt1: 13668 return performSTNT1Combine(N, DAG); 13669 case Intrinsic::aarch64_sve_stnt1_scatter_scalar_offset: 13670 return performScatterStoreCombine(N, DAG, AArch64ISD::SSTNT1); 13671 case Intrinsic::aarch64_sve_stnt1_scatter_uxtw: 13672 return performScatterStoreCombine(N, DAG, AArch64ISD::SSTNT1); 13673 case Intrinsic::aarch64_sve_stnt1_scatter: 13674 return performScatterStoreCombine(N, DAG, AArch64ISD::SSTNT1); 13675 case Intrinsic::aarch64_sve_stnt1_scatter_index: 13676 return performScatterStoreCombine(N, DAG, AArch64ISD::SSTNT1_INDEX); 13677 case Intrinsic::aarch64_sve_ld1_gather: 13678 return performGatherLoadCombine(N, DAG, AArch64ISD::GLD1); 13679 case Intrinsic::aarch64_sve_ld1_gather_index: 13680 return performGatherLoadCombine(N, DAG, AArch64ISD::GLD1_SCALED); 13681 case Intrinsic::aarch64_sve_ld1_gather_sxtw: 13682 return performGatherLoadCombine(N, DAG, AArch64ISD::GLD1_SXTW, 13683 /*OnlyPackedOffsets=*/false); 13684 case Intrinsic::aarch64_sve_ld1_gather_uxtw: 13685 return performGatherLoadCombine(N, DAG, AArch64ISD::GLD1_UXTW, 13686 /*OnlyPackedOffsets=*/false); 13687 case Intrinsic::aarch64_sve_ld1_gather_sxtw_index: 13688 return performGatherLoadCombine(N, DAG, AArch64ISD::GLD1_SXTW_SCALED, 13689 /*OnlyPackedOffsets=*/false); 13690 case Intrinsic::aarch64_sve_ld1_gather_uxtw_index: 13691 return performGatherLoadCombine(N, DAG, AArch64ISD::GLD1_UXTW_SCALED, 13692 /*OnlyPackedOffsets=*/false); 13693 case Intrinsic::aarch64_sve_ld1_gather_scalar_offset: 13694 return performGatherLoadCombine(N, DAG, AArch64ISD::GLD1_IMM); 13695 case Intrinsic::aarch64_sve_ldff1_gather: 13696 return performGatherLoadCombine(N, DAG, AArch64ISD::GLDFF1); 13697 case Intrinsic::aarch64_sve_ldff1_gather_index: 13698 return performGatherLoadCombine(N, DAG, AArch64ISD::GLDFF1_SCALED); 13699 case Intrinsic::aarch64_sve_ldff1_gather_sxtw: 13700 return performGatherLoadCombine(N, DAG, AArch64ISD::GLDFF1_SXTW, 13701 /*OnlyPackedOffsets=*/false); 13702 case Intrinsic::aarch64_sve_ldff1_gather_uxtw: 13703 return performGatherLoadCombine(N, DAG, AArch64ISD::GLDFF1_UXTW, 13704 /*OnlyPackedOffsets=*/false); 13705 case Intrinsic::aarch64_sve_ldff1_gather_sxtw_index: 13706 return performGatherLoadCombine(N, DAG, AArch64ISD::GLDFF1_SXTW_SCALED, 13707 /*OnlyPackedOffsets=*/false); 13708 case Intrinsic::aarch64_sve_ldff1_gather_uxtw_index: 13709 return performGatherLoadCombine(N, DAG, AArch64ISD::GLDFF1_UXTW_SCALED, 13710 /*OnlyPackedOffsets=*/false); 13711 case Intrinsic::aarch64_sve_ldff1_gather_scalar_offset: 13712 return performGatherLoadCombine(N, DAG, AArch64ISD::GLDFF1_IMM); 13713 case Intrinsic::aarch64_sve_st1_scatter: 13714 return performScatterStoreCombine(N, DAG, AArch64ISD::SST1); 13715 case Intrinsic::aarch64_sve_st1_scatter_index: 13716 return performScatterStoreCombine(N, DAG, AArch64ISD::SST1_SCALED); 13717 case Intrinsic::aarch64_sve_st1_scatter_sxtw: 13718 return performScatterStoreCombine(N, DAG, AArch64ISD::SST1_SXTW, 13719 /*OnlyPackedOffsets=*/false); 13720 case Intrinsic::aarch64_sve_st1_scatter_uxtw: 13721 return performScatterStoreCombine(N, DAG, AArch64ISD::SST1_UXTW, 13722 /*OnlyPackedOffsets=*/false); 13723 case Intrinsic::aarch64_sve_st1_scatter_sxtw_index: 13724 return performScatterStoreCombine(N, DAG, AArch64ISD::SST1_SXTW_SCALED, 13725 /*OnlyPackedOffsets=*/false); 13726 case Intrinsic::aarch64_sve_st1_scatter_uxtw_index: 13727 return performScatterStoreCombine(N, DAG, AArch64ISD::SST1_UXTW_SCALED, 13728 /*OnlyPackedOffsets=*/false); 13729 case Intrinsic::aarch64_sve_st1_scatter_scalar_offset: 13730 return performScatterStoreCombine(N, DAG, AArch64ISD::SST1_IMM); 13731 case Intrinsic::aarch64_sve_tuple_get: { 13732 SDLoc DL(N); 13733 SDValue Chain = N->getOperand(0); 13734 SDValue Src1 = N->getOperand(2); 13735 SDValue Idx = N->getOperand(3); 13736 13737 uint64_t IdxConst = cast<ConstantSDNode>(Idx)->getZExtValue(); 13738 if (IdxConst > Src1->getNumOperands() - 1) 13739 report_fatal_error("index larger than expected"); 13740 13741 EVT ResVT = N->getValueType(0); 13742 uint64_t NumLanes = ResVT.getVectorElementCount().Min; 13743 SDValue Val = 13744 DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, ResVT, Src1, 13745 DAG.getConstant(IdxConst * NumLanes, DL, MVT::i32)); 13746 return DAG.getMergeValues({Val, Chain}, DL); 13747 } 13748 case Intrinsic::aarch64_sve_tuple_set: { 13749 SDLoc DL(N); 13750 SDValue Chain = N->getOperand(0); 13751 SDValue Tuple = N->getOperand(2); 13752 SDValue Idx = N->getOperand(3); 13753 SDValue Vec = N->getOperand(4); 13754 13755 EVT TupleVT = Tuple.getValueType(); 13756 uint64_t TupleLanes = TupleVT.getVectorElementCount().Min; 13757 13758 uint64_t IdxConst = cast<ConstantSDNode>(Idx)->getZExtValue(); 13759 uint64_t NumLanes = Vec.getValueType().getVectorElementCount().Min; 13760 13761 if ((TupleLanes % NumLanes) != 0) 13762 report_fatal_error("invalid tuple vector!"); 13763 13764 uint64_t NumVecs = TupleLanes / NumLanes; 13765 13766 SmallVector<SDValue, 4> Opnds; 13767 for (unsigned I = 0; I < NumVecs; ++I) { 13768 if (I == IdxConst) 13769 Opnds.push_back(Vec); 13770 else { 13771 Opnds.push_back( 13772 DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, Vec.getValueType(), Tuple, 13773 DAG.getConstant(I * NumLanes, DL, MVT::i32))); 13774 } 13775 } 13776 SDValue Concat = 13777 DAG.getNode(ISD::CONCAT_VECTORS, DL, Tuple.getValueType(), Opnds); 13778 return DAG.getMergeValues({Concat, Chain}, DL); 13779 } 13780 case Intrinsic::aarch64_sve_tuple_create2: 13781 case Intrinsic::aarch64_sve_tuple_create3: 13782 case Intrinsic::aarch64_sve_tuple_create4: { 13783 SDLoc DL(N); 13784 SDValue Chain = N->getOperand(0); 13785 13786 SmallVector<SDValue, 4> Opnds; 13787 for (unsigned I = 2; I < N->getNumOperands(); ++I) 13788 Opnds.push_back(N->getOperand(I)); 13789 13790 EVT VT = Opnds[0].getValueType(); 13791 EVT EltVT = VT.getVectorElementType(); 13792 EVT DestVT = EVT::getVectorVT(*DAG.getContext(), EltVT, 13793 VT.getVectorElementCount() * 13794 (N->getNumOperands() - 2)); 13795 SDValue Concat = DAG.getNode(ISD::CONCAT_VECTORS, DL, DestVT, Opnds); 13796 return DAG.getMergeValues({Concat, Chain}, DL); 13797 } 13798 case Intrinsic::aarch64_sve_ld2: 13799 case Intrinsic::aarch64_sve_ld3: 13800 case Intrinsic::aarch64_sve_ld4: { 13801 SDLoc DL(N); 13802 SDValue Chain = N->getOperand(0); 13803 SDValue Mask = N->getOperand(2); 13804 SDValue BasePtr = N->getOperand(3); 13805 SDValue LoadOps[] = {Chain, Mask, BasePtr}; 13806 unsigned IntrinsicID = 13807 cast<ConstantSDNode>(N->getOperand(1))->getZExtValue(); 13808 SDValue Result = 13809 LowerSVEStructLoad(IntrinsicID, LoadOps, N->getValueType(0), DAG, DL); 13810 return DAG.getMergeValues({Result, Chain}, DL); 13811 } 13812 default: 13813 break; 13814 } 13815 break; 13816 case ISD::GlobalAddress: 13817 return performGlobalAddressCombine(N, DAG, Subtarget, getTargetMachine()); 13818 } 13819 return SDValue(); 13820 } 13821 13822 // Check if the return value is used as only a return value, as otherwise 13823 // we can't perform a tail-call. In particular, we need to check for 13824 // target ISD nodes that are returns and any other "odd" constructs 13825 // that the generic analysis code won't necessarily catch. 13826 bool AArch64TargetLowering::isUsedByReturnOnly(SDNode *N, 13827 SDValue &Chain) const { 13828 if (N->getNumValues() != 1) 13829 return false; 13830 if (!N->hasNUsesOfValue(1, 0)) 13831 return false; 13832 13833 SDValue TCChain = Chain; 13834 SDNode *Copy = *N->use_begin(); 13835 if (Copy->getOpcode() == ISD::CopyToReg) { 13836 // If the copy has a glue operand, we conservatively assume it isn't safe to 13837 // perform a tail call. 13838 if (Copy->getOperand(Copy->getNumOperands() - 1).getValueType() == 13839 MVT::Glue) 13840 return false; 13841 TCChain = Copy->getOperand(0); 13842 } else if (Copy->getOpcode() != ISD::FP_EXTEND) 13843 return false; 13844 13845 bool HasRet = false; 13846 for (SDNode *Node : Copy->uses()) { 13847 if (Node->getOpcode() != AArch64ISD::RET_FLAG) 13848 return false; 13849 HasRet = true; 13850 } 13851 13852 if (!HasRet) 13853 return false; 13854 13855 Chain = TCChain; 13856 return true; 13857 } 13858 13859 // Return whether the an instruction can potentially be optimized to a tail 13860 // call. This will cause the optimizers to attempt to move, or duplicate, 13861 // return instructions to help enable tail call optimizations for this 13862 // instruction. 13863 bool AArch64TargetLowering::mayBeEmittedAsTailCall(const CallInst *CI) const { 13864 return CI->isTailCall(); 13865 } 13866 13867 bool AArch64TargetLowering::getIndexedAddressParts(SDNode *Op, SDValue &Base, 13868 SDValue &Offset, 13869 ISD::MemIndexedMode &AM, 13870 bool &IsInc, 13871 SelectionDAG &DAG) const { 13872 if (Op->getOpcode() != ISD::ADD && Op->getOpcode() != ISD::SUB) 13873 return false; 13874 13875 Base = Op->getOperand(0); 13876 // All of the indexed addressing mode instructions take a signed 13877 // 9 bit immediate offset. 13878 if (ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(Op->getOperand(1))) { 13879 int64_t RHSC = RHS->getSExtValue(); 13880 if (Op->getOpcode() == ISD::SUB) 13881 RHSC = -(uint64_t)RHSC; 13882 if (!isInt<9>(RHSC)) 13883 return false; 13884 IsInc = (Op->getOpcode() == ISD::ADD); 13885 Offset = Op->getOperand(1); 13886 return true; 13887 } 13888 return false; 13889 } 13890 13891 bool AArch64TargetLowering::getPreIndexedAddressParts(SDNode *N, SDValue &Base, 13892 SDValue &Offset, 13893 ISD::MemIndexedMode &AM, 13894 SelectionDAG &DAG) const { 13895 EVT VT; 13896 SDValue Ptr; 13897 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) { 13898 VT = LD->getMemoryVT(); 13899 Ptr = LD->getBasePtr(); 13900 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) { 13901 VT = ST->getMemoryVT(); 13902 Ptr = ST->getBasePtr(); 13903 } else 13904 return false; 13905 13906 bool IsInc; 13907 if (!getIndexedAddressParts(Ptr.getNode(), Base, Offset, AM, IsInc, DAG)) 13908 return false; 13909 AM = IsInc ? ISD::PRE_INC : ISD::PRE_DEC; 13910 return true; 13911 } 13912 13913 bool AArch64TargetLowering::getPostIndexedAddressParts( 13914 SDNode *N, SDNode *Op, SDValue &Base, SDValue &Offset, 13915 ISD::MemIndexedMode &AM, SelectionDAG &DAG) const { 13916 EVT VT; 13917 SDValue Ptr; 13918 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) { 13919 VT = LD->getMemoryVT(); 13920 Ptr = LD->getBasePtr(); 13921 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) { 13922 VT = ST->getMemoryVT(); 13923 Ptr = ST->getBasePtr(); 13924 } else 13925 return false; 13926 13927 bool IsInc; 13928 if (!getIndexedAddressParts(Op, Base, Offset, AM, IsInc, DAG)) 13929 return false; 13930 // Post-indexing updates the base, so it's not a valid transform 13931 // if that's not the same as the load's pointer. 13932 if (Ptr != Base) 13933 return false; 13934 AM = IsInc ? ISD::POST_INC : ISD::POST_DEC; 13935 return true; 13936 } 13937 13938 static void ReplaceBITCASTResults(SDNode *N, SmallVectorImpl<SDValue> &Results, 13939 SelectionDAG &DAG) { 13940 SDLoc DL(N); 13941 SDValue Op = N->getOperand(0); 13942 13943 if (N->getValueType(0) != MVT::i16 || 13944 (Op.getValueType() != MVT::f16 && Op.getValueType() != MVT::bf16)) 13945 return; 13946 13947 Op = SDValue( 13948 DAG.getMachineNode(TargetOpcode::INSERT_SUBREG, DL, MVT::f32, 13949 DAG.getUNDEF(MVT::i32), Op, 13950 DAG.getTargetConstant(AArch64::hsub, DL, MVT::i32)), 13951 0); 13952 Op = DAG.getNode(ISD::BITCAST, DL, MVT::i32, Op); 13953 Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i16, Op)); 13954 } 13955 13956 static void ReplaceReductionResults(SDNode *N, 13957 SmallVectorImpl<SDValue> &Results, 13958 SelectionDAG &DAG, unsigned InterOp, 13959 unsigned AcrossOp) { 13960 EVT LoVT, HiVT; 13961 SDValue Lo, Hi; 13962 SDLoc dl(N); 13963 std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(N->getValueType(0)); 13964 std::tie(Lo, Hi) = DAG.SplitVectorOperand(N, 0); 13965 SDValue InterVal = DAG.getNode(InterOp, dl, LoVT, Lo, Hi); 13966 SDValue SplitVal = DAG.getNode(AcrossOp, dl, LoVT, InterVal); 13967 Results.push_back(SplitVal); 13968 } 13969 13970 static std::pair<SDValue, SDValue> splitInt128(SDValue N, SelectionDAG &DAG) { 13971 SDLoc DL(N); 13972 SDValue Lo = DAG.getNode(ISD::TRUNCATE, DL, MVT::i64, N); 13973 SDValue Hi = DAG.getNode(ISD::TRUNCATE, DL, MVT::i64, 13974 DAG.getNode(ISD::SRL, DL, MVT::i128, N, 13975 DAG.getConstant(64, DL, MVT::i64))); 13976 return std::make_pair(Lo, Hi); 13977 } 13978 13979 void AArch64TargetLowering::ReplaceExtractSubVectorResults( 13980 SDNode *N, SmallVectorImpl<SDValue> &Results, SelectionDAG &DAG) const { 13981 SDValue In = N->getOperand(0); 13982 EVT InVT = In.getValueType(); 13983 13984 // Common code will handle these just fine. 13985 if (!InVT.isScalableVector() || !InVT.isInteger()) 13986 return; 13987 13988 SDLoc DL(N); 13989 EVT VT = N->getValueType(0); 13990 13991 // The following checks bail if this is not a halving operation. 13992 13993 ElementCount ResEC = VT.getVectorElementCount(); 13994 13995 if (InVT.getVectorElementCount().Min != (ResEC.Min * 2)) 13996 return; 13997 13998 auto *CIndex = dyn_cast<ConstantSDNode>(N->getOperand(1)); 13999 if (!CIndex) 14000 return; 14001 14002 unsigned Index = CIndex->getZExtValue(); 14003 if ((Index != 0) && (Index != ResEC.Min)) 14004 return; 14005 14006 unsigned Opcode = (Index == 0) ? AArch64ISD::UUNPKLO : AArch64ISD::UUNPKHI; 14007 EVT ExtendedHalfVT = VT.widenIntegerVectorElementType(*DAG.getContext()); 14008 14009 SDValue Half = DAG.getNode(Opcode, DL, ExtendedHalfVT, N->getOperand(0)); 14010 Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, VT, Half)); 14011 } 14012 14013 // Create an even/odd pair of X registers holding integer value V. 14014 static SDValue createGPRPairNode(SelectionDAG &DAG, SDValue V) { 14015 SDLoc dl(V.getNode()); 14016 SDValue VLo = DAG.getAnyExtOrTrunc(V, dl, MVT::i64); 14017 SDValue VHi = DAG.getAnyExtOrTrunc( 14018 DAG.getNode(ISD::SRL, dl, MVT::i128, V, DAG.getConstant(64, dl, MVT::i64)), 14019 dl, MVT::i64); 14020 if (DAG.getDataLayout().isBigEndian()) 14021 std::swap (VLo, VHi); 14022 SDValue RegClass = 14023 DAG.getTargetConstant(AArch64::XSeqPairsClassRegClassID, dl, MVT::i32); 14024 SDValue SubReg0 = DAG.getTargetConstant(AArch64::sube64, dl, MVT::i32); 14025 SDValue SubReg1 = DAG.getTargetConstant(AArch64::subo64, dl, MVT::i32); 14026 const SDValue Ops[] = { RegClass, VLo, SubReg0, VHi, SubReg1 }; 14027 return SDValue( 14028 DAG.getMachineNode(TargetOpcode::REG_SEQUENCE, dl, MVT::Untyped, Ops), 0); 14029 } 14030 14031 static void ReplaceCMP_SWAP_128Results(SDNode *N, 14032 SmallVectorImpl<SDValue> &Results, 14033 SelectionDAG &DAG, 14034 const AArch64Subtarget *Subtarget) { 14035 assert(N->getValueType(0) == MVT::i128 && 14036 "AtomicCmpSwap on types less than 128 should be legal"); 14037 14038 if (Subtarget->hasLSE()) { 14039 // LSE has a 128-bit compare and swap (CASP), but i128 is not a legal type, 14040 // so lower it here, wrapped in REG_SEQUENCE and EXTRACT_SUBREG. 14041 SDValue Ops[] = { 14042 createGPRPairNode(DAG, N->getOperand(2)), // Compare value 14043 createGPRPairNode(DAG, N->getOperand(3)), // Store value 14044 N->getOperand(1), // Ptr 14045 N->getOperand(0), // Chain in 14046 }; 14047 14048 MachineMemOperand *MemOp = cast<MemSDNode>(N)->getMemOperand(); 14049 14050 unsigned Opcode; 14051 switch (MemOp->getOrdering()) { 14052 case AtomicOrdering::Monotonic: 14053 Opcode = AArch64::CASPX; 14054 break; 14055 case AtomicOrdering::Acquire: 14056 Opcode = AArch64::CASPAX; 14057 break; 14058 case AtomicOrdering::Release: 14059 Opcode = AArch64::CASPLX; 14060 break; 14061 case AtomicOrdering::AcquireRelease: 14062 case AtomicOrdering::SequentiallyConsistent: 14063 Opcode = AArch64::CASPALX; 14064 break; 14065 default: 14066 llvm_unreachable("Unexpected ordering!"); 14067 } 14068 14069 MachineSDNode *CmpSwap = DAG.getMachineNode( 14070 Opcode, SDLoc(N), DAG.getVTList(MVT::Untyped, MVT::Other), Ops); 14071 DAG.setNodeMemRefs(CmpSwap, {MemOp}); 14072 14073 unsigned SubReg1 = AArch64::sube64, SubReg2 = AArch64::subo64; 14074 if (DAG.getDataLayout().isBigEndian()) 14075 std::swap(SubReg1, SubReg2); 14076 SDValue Lo = DAG.getTargetExtractSubreg(SubReg1, SDLoc(N), MVT::i64, 14077 SDValue(CmpSwap, 0)); 14078 SDValue Hi = DAG.getTargetExtractSubreg(SubReg2, SDLoc(N), MVT::i64, 14079 SDValue(CmpSwap, 0)); 14080 Results.push_back( 14081 DAG.getNode(ISD::BUILD_PAIR, SDLoc(N), MVT::i128, Lo, Hi)); 14082 Results.push_back(SDValue(CmpSwap, 1)); // Chain out 14083 return; 14084 } 14085 14086 auto Desired = splitInt128(N->getOperand(2), DAG); 14087 auto New = splitInt128(N->getOperand(3), DAG); 14088 SDValue Ops[] = {N->getOperand(1), Desired.first, Desired.second, 14089 New.first, New.second, N->getOperand(0)}; 14090 SDNode *CmpSwap = DAG.getMachineNode( 14091 AArch64::CMP_SWAP_128, SDLoc(N), 14092 DAG.getVTList(MVT::i64, MVT::i64, MVT::i32, MVT::Other), Ops); 14093 14094 MachineMemOperand *MemOp = cast<MemSDNode>(N)->getMemOperand(); 14095 DAG.setNodeMemRefs(cast<MachineSDNode>(CmpSwap), {MemOp}); 14096 14097 Results.push_back(DAG.getNode(ISD::BUILD_PAIR, SDLoc(N), MVT::i128, 14098 SDValue(CmpSwap, 0), SDValue(CmpSwap, 1))); 14099 Results.push_back(SDValue(CmpSwap, 3)); 14100 } 14101 14102 void AArch64TargetLowering::ReplaceNodeResults( 14103 SDNode *N, SmallVectorImpl<SDValue> &Results, SelectionDAG &DAG) const { 14104 switch (N->getOpcode()) { 14105 default: 14106 llvm_unreachable("Don't know how to custom expand this"); 14107 case ISD::BITCAST: 14108 ReplaceBITCASTResults(N, Results, DAG); 14109 return; 14110 case ISD::VECREDUCE_ADD: 14111 case ISD::VECREDUCE_SMAX: 14112 case ISD::VECREDUCE_SMIN: 14113 case ISD::VECREDUCE_UMAX: 14114 case ISD::VECREDUCE_UMIN: 14115 Results.push_back(LowerVECREDUCE(SDValue(N, 0), DAG)); 14116 return; 14117 14118 case ISD::CTPOP: 14119 Results.push_back(LowerCTPOP(SDValue(N, 0), DAG)); 14120 return; 14121 case AArch64ISD::SADDV: 14122 ReplaceReductionResults(N, Results, DAG, ISD::ADD, AArch64ISD::SADDV); 14123 return; 14124 case AArch64ISD::UADDV: 14125 ReplaceReductionResults(N, Results, DAG, ISD::ADD, AArch64ISD::UADDV); 14126 return; 14127 case AArch64ISD::SMINV: 14128 ReplaceReductionResults(N, Results, DAG, ISD::SMIN, AArch64ISD::SMINV); 14129 return; 14130 case AArch64ISD::UMINV: 14131 ReplaceReductionResults(N, Results, DAG, ISD::UMIN, AArch64ISD::UMINV); 14132 return; 14133 case AArch64ISD::SMAXV: 14134 ReplaceReductionResults(N, Results, DAG, ISD::SMAX, AArch64ISD::SMAXV); 14135 return; 14136 case AArch64ISD::UMAXV: 14137 ReplaceReductionResults(N, Results, DAG, ISD::UMAX, AArch64ISD::UMAXV); 14138 return; 14139 case ISD::FP_TO_UINT: 14140 case ISD::FP_TO_SINT: 14141 assert(N->getValueType(0) == MVT::i128 && "unexpected illegal conversion"); 14142 // Let normal code take care of it by not adding anything to Results. 14143 return; 14144 case ISD::ATOMIC_CMP_SWAP: 14145 ReplaceCMP_SWAP_128Results(N, Results, DAG, Subtarget); 14146 return; 14147 case ISD::LOAD: { 14148 assert(SDValue(N, 0).getValueType() == MVT::i128 && 14149 "unexpected load's value type"); 14150 LoadSDNode *LoadNode = cast<LoadSDNode>(N); 14151 if (!LoadNode->isVolatile() || LoadNode->getMemoryVT() != MVT::i128) { 14152 // Non-volatile loads are optimized later in AArch64's load/store 14153 // optimizer. 14154 return; 14155 } 14156 14157 SDValue Result = DAG.getMemIntrinsicNode( 14158 AArch64ISD::LDP, SDLoc(N), 14159 DAG.getVTList({MVT::i64, MVT::i64, MVT::Other}), 14160 {LoadNode->getChain(), LoadNode->getBasePtr()}, LoadNode->getMemoryVT(), 14161 LoadNode->getMemOperand()); 14162 14163 SDValue Pair = DAG.getNode(ISD::BUILD_PAIR, SDLoc(N), MVT::i128, 14164 Result.getValue(0), Result.getValue(1)); 14165 Results.append({Pair, Result.getValue(2) /* Chain */}); 14166 return; 14167 } 14168 case ISD::EXTRACT_SUBVECTOR: 14169 ReplaceExtractSubVectorResults(N, Results, DAG); 14170 return; 14171 case ISD::INTRINSIC_WO_CHAIN: { 14172 EVT VT = N->getValueType(0); 14173 assert((VT == MVT::i8 || VT == MVT::i16) && 14174 "custom lowering for unexpected type"); 14175 14176 ConstantSDNode *CN = cast<ConstantSDNode>(N->getOperand(0)); 14177 Intrinsic::ID IntID = static_cast<Intrinsic::ID>(CN->getZExtValue()); 14178 switch (IntID) { 14179 default: 14180 return; 14181 case Intrinsic::aarch64_sve_clasta_n: { 14182 SDLoc DL(N); 14183 auto Op2 = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i32, N->getOperand(2)); 14184 auto V = DAG.getNode(AArch64ISD::CLASTA_N, DL, MVT::i32, 14185 N->getOperand(1), Op2, N->getOperand(3)); 14186 Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, VT, V)); 14187 return; 14188 } 14189 case Intrinsic::aarch64_sve_clastb_n: { 14190 SDLoc DL(N); 14191 auto Op2 = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i32, N->getOperand(2)); 14192 auto V = DAG.getNode(AArch64ISD::CLASTB_N, DL, MVT::i32, 14193 N->getOperand(1), Op2, N->getOperand(3)); 14194 Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, VT, V)); 14195 return; 14196 } 14197 case Intrinsic::aarch64_sve_lasta: { 14198 SDLoc DL(N); 14199 auto V = DAG.getNode(AArch64ISD::LASTA, DL, MVT::i32, 14200 N->getOperand(1), N->getOperand(2)); 14201 Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, VT, V)); 14202 return; 14203 } 14204 case Intrinsic::aarch64_sve_lastb: { 14205 SDLoc DL(N); 14206 auto V = DAG.getNode(AArch64ISD::LASTB, DL, MVT::i32, 14207 N->getOperand(1), N->getOperand(2)); 14208 Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, VT, V)); 14209 return; 14210 } 14211 } 14212 } 14213 } 14214 } 14215 14216 bool AArch64TargetLowering::useLoadStackGuardNode() const { 14217 if (Subtarget->isTargetAndroid() || Subtarget->isTargetFuchsia()) 14218 return TargetLowering::useLoadStackGuardNode(); 14219 return true; 14220 } 14221 14222 unsigned AArch64TargetLowering::combineRepeatedFPDivisors() const { 14223 // Combine multiple FDIVs with the same divisor into multiple FMULs by the 14224 // reciprocal if there are three or more FDIVs. 14225 return 3; 14226 } 14227 14228 TargetLoweringBase::LegalizeTypeAction 14229 AArch64TargetLowering::getPreferredVectorAction(MVT VT) const { 14230 // During type legalization, we prefer to widen v1i8, v1i16, v1i32 to v8i8, 14231 // v4i16, v2i32 instead of to promote. 14232 if (VT == MVT::v1i8 || VT == MVT::v1i16 || VT == MVT::v1i32 || 14233 VT == MVT::v1f32) 14234 return TypeWidenVector; 14235 14236 return TargetLoweringBase::getPreferredVectorAction(VT); 14237 } 14238 14239 // Loads and stores less than 128-bits are already atomic; ones above that 14240 // are doomed anyway, so defer to the default libcall and blame the OS when 14241 // things go wrong. 14242 bool AArch64TargetLowering::shouldExpandAtomicStoreInIR(StoreInst *SI) const { 14243 unsigned Size = SI->getValueOperand()->getType()->getPrimitiveSizeInBits(); 14244 return Size == 128; 14245 } 14246 14247 // Loads and stores less than 128-bits are already atomic; ones above that 14248 // are doomed anyway, so defer to the default libcall and blame the OS when 14249 // things go wrong. 14250 TargetLowering::AtomicExpansionKind 14251 AArch64TargetLowering::shouldExpandAtomicLoadInIR(LoadInst *LI) const { 14252 unsigned Size = LI->getType()->getPrimitiveSizeInBits(); 14253 return Size == 128 ? AtomicExpansionKind::LLSC : AtomicExpansionKind::None; 14254 } 14255 14256 // For the real atomic operations, we have ldxr/stxr up to 128 bits, 14257 TargetLowering::AtomicExpansionKind 14258 AArch64TargetLowering::shouldExpandAtomicRMWInIR(AtomicRMWInst *AI) const { 14259 if (AI->isFloatingPointOperation()) 14260 return AtomicExpansionKind::CmpXChg; 14261 14262 unsigned Size = AI->getType()->getPrimitiveSizeInBits(); 14263 if (Size > 128) return AtomicExpansionKind::None; 14264 // Nand not supported in LSE. 14265 if (AI->getOperation() == AtomicRMWInst::Nand) return AtomicExpansionKind::LLSC; 14266 // Leave 128 bits to LLSC. 14267 return (Subtarget->hasLSE() && Size < 128) ? AtomicExpansionKind::None : AtomicExpansionKind::LLSC; 14268 } 14269 14270 TargetLowering::AtomicExpansionKind 14271 AArch64TargetLowering::shouldExpandAtomicCmpXchgInIR( 14272 AtomicCmpXchgInst *AI) const { 14273 // If subtarget has LSE, leave cmpxchg intact for codegen. 14274 if (Subtarget->hasLSE()) 14275 return AtomicExpansionKind::None; 14276 // At -O0, fast-regalloc cannot cope with the live vregs necessary to 14277 // implement cmpxchg without spilling. If the address being exchanged is also 14278 // on the stack and close enough to the spill slot, this can lead to a 14279 // situation where the monitor always gets cleared and the atomic operation 14280 // can never succeed. So at -O0 we need a late-expanded pseudo-inst instead. 14281 if (getTargetMachine().getOptLevel() == CodeGenOpt::None) 14282 return AtomicExpansionKind::None; 14283 return AtomicExpansionKind::LLSC; 14284 } 14285 14286 Value *AArch64TargetLowering::emitLoadLinked(IRBuilder<> &Builder, Value *Addr, 14287 AtomicOrdering Ord) const { 14288 Module *M = Builder.GetInsertBlock()->getParent()->getParent(); 14289 Type *ValTy = cast<PointerType>(Addr->getType())->getElementType(); 14290 bool IsAcquire = isAcquireOrStronger(Ord); 14291 14292 // Since i128 isn't legal and intrinsics don't get type-lowered, the ldrexd 14293 // intrinsic must return {i64, i64} and we have to recombine them into a 14294 // single i128 here. 14295 if (ValTy->getPrimitiveSizeInBits() == 128) { 14296 Intrinsic::ID Int = 14297 IsAcquire ? Intrinsic::aarch64_ldaxp : Intrinsic::aarch64_ldxp; 14298 Function *Ldxr = Intrinsic::getDeclaration(M, Int); 14299 14300 Addr = Builder.CreateBitCast(Addr, Type::getInt8PtrTy(M->getContext())); 14301 Value *LoHi = Builder.CreateCall(Ldxr, Addr, "lohi"); 14302 14303 Value *Lo = Builder.CreateExtractValue(LoHi, 0, "lo"); 14304 Value *Hi = Builder.CreateExtractValue(LoHi, 1, "hi"); 14305 Lo = Builder.CreateZExt(Lo, ValTy, "lo64"); 14306 Hi = Builder.CreateZExt(Hi, ValTy, "hi64"); 14307 return Builder.CreateOr( 14308 Lo, Builder.CreateShl(Hi, ConstantInt::get(ValTy, 64)), "val64"); 14309 } 14310 14311 Type *Tys[] = { Addr->getType() }; 14312 Intrinsic::ID Int = 14313 IsAcquire ? Intrinsic::aarch64_ldaxr : Intrinsic::aarch64_ldxr; 14314 Function *Ldxr = Intrinsic::getDeclaration(M, Int, Tys); 14315 14316 Type *EltTy = cast<PointerType>(Addr->getType())->getElementType(); 14317 14318 const DataLayout &DL = M->getDataLayout(); 14319 IntegerType *IntEltTy = Builder.getIntNTy(DL.getTypeSizeInBits(EltTy)); 14320 Value *Trunc = Builder.CreateTrunc(Builder.CreateCall(Ldxr, Addr), IntEltTy); 14321 14322 return Builder.CreateBitCast(Trunc, EltTy); 14323 } 14324 14325 void AArch64TargetLowering::emitAtomicCmpXchgNoStoreLLBalance( 14326 IRBuilder<> &Builder) const { 14327 Module *M = Builder.GetInsertBlock()->getParent()->getParent(); 14328 Builder.CreateCall(Intrinsic::getDeclaration(M, Intrinsic::aarch64_clrex)); 14329 } 14330 14331 Value *AArch64TargetLowering::emitStoreConditional(IRBuilder<> &Builder, 14332 Value *Val, Value *Addr, 14333 AtomicOrdering Ord) const { 14334 Module *M = Builder.GetInsertBlock()->getParent()->getParent(); 14335 bool IsRelease = isReleaseOrStronger(Ord); 14336 14337 // Since the intrinsics must have legal type, the i128 intrinsics take two 14338 // parameters: "i64, i64". We must marshal Val into the appropriate form 14339 // before the call. 14340 if (Val->getType()->getPrimitiveSizeInBits() == 128) { 14341 Intrinsic::ID Int = 14342 IsRelease ? Intrinsic::aarch64_stlxp : Intrinsic::aarch64_stxp; 14343 Function *Stxr = Intrinsic::getDeclaration(M, Int); 14344 Type *Int64Ty = Type::getInt64Ty(M->getContext()); 14345 14346 Value *Lo = Builder.CreateTrunc(Val, Int64Ty, "lo"); 14347 Value *Hi = Builder.CreateTrunc(Builder.CreateLShr(Val, 64), Int64Ty, "hi"); 14348 Addr = Builder.CreateBitCast(Addr, Type::getInt8PtrTy(M->getContext())); 14349 return Builder.CreateCall(Stxr, {Lo, Hi, Addr}); 14350 } 14351 14352 Intrinsic::ID Int = 14353 IsRelease ? Intrinsic::aarch64_stlxr : Intrinsic::aarch64_stxr; 14354 Type *Tys[] = { Addr->getType() }; 14355 Function *Stxr = Intrinsic::getDeclaration(M, Int, Tys); 14356 14357 const DataLayout &DL = M->getDataLayout(); 14358 IntegerType *IntValTy = Builder.getIntNTy(DL.getTypeSizeInBits(Val->getType())); 14359 Val = Builder.CreateBitCast(Val, IntValTy); 14360 14361 return Builder.CreateCall(Stxr, 14362 {Builder.CreateZExtOrBitCast( 14363 Val, Stxr->getFunctionType()->getParamType(0)), 14364 Addr}); 14365 } 14366 14367 bool AArch64TargetLowering::functionArgumentNeedsConsecutiveRegisters( 14368 Type *Ty, CallingConv::ID CallConv, bool isVarArg) const { 14369 return Ty->isArrayTy(); 14370 } 14371 14372 bool AArch64TargetLowering::shouldNormalizeToSelectSequence(LLVMContext &, 14373 EVT) const { 14374 return false; 14375 } 14376 14377 static Value *UseTlsOffset(IRBuilder<> &IRB, unsigned Offset) { 14378 Module *M = IRB.GetInsertBlock()->getParent()->getParent(); 14379 Function *ThreadPointerFunc = 14380 Intrinsic::getDeclaration(M, Intrinsic::thread_pointer); 14381 return IRB.CreatePointerCast( 14382 IRB.CreateConstGEP1_32(IRB.getInt8Ty(), IRB.CreateCall(ThreadPointerFunc), 14383 Offset), 14384 IRB.getInt8PtrTy()->getPointerTo(0)); 14385 } 14386 14387 Value *AArch64TargetLowering::getIRStackGuard(IRBuilder<> &IRB) const { 14388 // Android provides a fixed TLS slot for the stack cookie. See the definition 14389 // of TLS_SLOT_STACK_GUARD in 14390 // https://android.googlesource.com/platform/bionic/+/master/libc/private/bionic_tls.h 14391 if (Subtarget->isTargetAndroid()) 14392 return UseTlsOffset(IRB, 0x28); 14393 14394 // Fuchsia is similar. 14395 // <zircon/tls.h> defines ZX_TLS_STACK_GUARD_OFFSET with this value. 14396 if (Subtarget->isTargetFuchsia()) 14397 return UseTlsOffset(IRB, -0x10); 14398 14399 return TargetLowering::getIRStackGuard(IRB); 14400 } 14401 14402 void AArch64TargetLowering::insertSSPDeclarations(Module &M) const { 14403 // MSVC CRT provides functionalities for stack protection. 14404 if (Subtarget->getTargetTriple().isWindowsMSVCEnvironment()) { 14405 // MSVC CRT has a global variable holding security cookie. 14406 M.getOrInsertGlobal("__security_cookie", 14407 Type::getInt8PtrTy(M.getContext())); 14408 14409 // MSVC CRT has a function to validate security cookie. 14410 FunctionCallee SecurityCheckCookie = M.getOrInsertFunction( 14411 "__security_check_cookie", Type::getVoidTy(M.getContext()), 14412 Type::getInt8PtrTy(M.getContext())); 14413 if (Function *F = dyn_cast<Function>(SecurityCheckCookie.getCallee())) { 14414 F->setCallingConv(CallingConv::Win64); 14415 F->addAttribute(1, Attribute::AttrKind::InReg); 14416 } 14417 return; 14418 } 14419 TargetLowering::insertSSPDeclarations(M); 14420 } 14421 14422 Value *AArch64TargetLowering::getSDagStackGuard(const Module &M) const { 14423 // MSVC CRT has a global variable holding security cookie. 14424 if (Subtarget->getTargetTriple().isWindowsMSVCEnvironment()) 14425 return M.getGlobalVariable("__security_cookie"); 14426 return TargetLowering::getSDagStackGuard(M); 14427 } 14428 14429 Function *AArch64TargetLowering::getSSPStackGuardCheck(const Module &M) const { 14430 // MSVC CRT has a function to validate security cookie. 14431 if (Subtarget->getTargetTriple().isWindowsMSVCEnvironment()) 14432 return M.getFunction("__security_check_cookie"); 14433 return TargetLowering::getSSPStackGuardCheck(M); 14434 } 14435 14436 Value *AArch64TargetLowering::getSafeStackPointerLocation(IRBuilder<> &IRB) const { 14437 // Android provides a fixed TLS slot for the SafeStack pointer. See the 14438 // definition of TLS_SLOT_SAFESTACK in 14439 // https://android.googlesource.com/platform/bionic/+/master/libc/private/bionic_tls.h 14440 if (Subtarget->isTargetAndroid()) 14441 return UseTlsOffset(IRB, 0x48); 14442 14443 // Fuchsia is similar. 14444 // <zircon/tls.h> defines ZX_TLS_UNSAFE_SP_OFFSET with this value. 14445 if (Subtarget->isTargetFuchsia()) 14446 return UseTlsOffset(IRB, -0x8); 14447 14448 return TargetLowering::getSafeStackPointerLocation(IRB); 14449 } 14450 14451 bool AArch64TargetLowering::isMaskAndCmp0FoldingBeneficial( 14452 const Instruction &AndI) const { 14453 // Only sink 'and' mask to cmp use block if it is masking a single bit, since 14454 // this is likely to be fold the and/cmp/br into a single tbz instruction. It 14455 // may be beneficial to sink in other cases, but we would have to check that 14456 // the cmp would not get folded into the br to form a cbz for these to be 14457 // beneficial. 14458 ConstantInt* Mask = dyn_cast<ConstantInt>(AndI.getOperand(1)); 14459 if (!Mask) 14460 return false; 14461 return Mask->getValue().isPowerOf2(); 14462 } 14463 14464 bool AArch64TargetLowering:: 14465 shouldProduceAndByConstByHoistingConstFromShiftsLHSOfAnd( 14466 SDValue X, ConstantSDNode *XC, ConstantSDNode *CC, SDValue Y, 14467 unsigned OldShiftOpcode, unsigned NewShiftOpcode, 14468 SelectionDAG &DAG) const { 14469 // Does baseline recommend not to perform the fold by default? 14470 if (!TargetLowering::shouldProduceAndByConstByHoistingConstFromShiftsLHSOfAnd( 14471 X, XC, CC, Y, OldShiftOpcode, NewShiftOpcode, DAG)) 14472 return false; 14473 // Else, if this is a vector shift, prefer 'shl'. 14474 return X.getValueType().isScalarInteger() || NewShiftOpcode == ISD::SHL; 14475 } 14476 14477 bool AArch64TargetLowering::shouldExpandShift(SelectionDAG &DAG, 14478 SDNode *N) const { 14479 if (DAG.getMachineFunction().getFunction().hasMinSize() && 14480 !Subtarget->isTargetWindows() && !Subtarget->isTargetDarwin()) 14481 return false; 14482 return true; 14483 } 14484 14485 void AArch64TargetLowering::initializeSplitCSR(MachineBasicBlock *Entry) const { 14486 // Update IsSplitCSR in AArch64unctionInfo. 14487 AArch64FunctionInfo *AFI = Entry->getParent()->getInfo<AArch64FunctionInfo>(); 14488 AFI->setIsSplitCSR(true); 14489 } 14490 14491 void AArch64TargetLowering::insertCopiesSplitCSR( 14492 MachineBasicBlock *Entry, 14493 const SmallVectorImpl<MachineBasicBlock *> &Exits) const { 14494 const AArch64RegisterInfo *TRI = Subtarget->getRegisterInfo(); 14495 const MCPhysReg *IStart = TRI->getCalleeSavedRegsViaCopy(Entry->getParent()); 14496 if (!IStart) 14497 return; 14498 14499 const TargetInstrInfo *TII = Subtarget->getInstrInfo(); 14500 MachineRegisterInfo *MRI = &Entry->getParent()->getRegInfo(); 14501 MachineBasicBlock::iterator MBBI = Entry->begin(); 14502 for (const MCPhysReg *I = IStart; *I; ++I) { 14503 const TargetRegisterClass *RC = nullptr; 14504 if (AArch64::GPR64RegClass.contains(*I)) 14505 RC = &AArch64::GPR64RegClass; 14506 else if (AArch64::FPR64RegClass.contains(*I)) 14507 RC = &AArch64::FPR64RegClass; 14508 else 14509 llvm_unreachable("Unexpected register class in CSRsViaCopy!"); 14510 14511 Register NewVR = MRI->createVirtualRegister(RC); 14512 // Create copy from CSR to a virtual register. 14513 // FIXME: this currently does not emit CFI pseudo-instructions, it works 14514 // fine for CXX_FAST_TLS since the C++-style TLS access functions should be 14515 // nounwind. If we want to generalize this later, we may need to emit 14516 // CFI pseudo-instructions. 14517 assert(Entry->getParent()->getFunction().hasFnAttribute( 14518 Attribute::NoUnwind) && 14519 "Function should be nounwind in insertCopiesSplitCSR!"); 14520 Entry->addLiveIn(*I); 14521 BuildMI(*Entry, MBBI, DebugLoc(), TII->get(TargetOpcode::COPY), NewVR) 14522 .addReg(*I); 14523 14524 // Insert the copy-back instructions right before the terminator. 14525 for (auto *Exit : Exits) 14526 BuildMI(*Exit, Exit->getFirstTerminator(), DebugLoc(), 14527 TII->get(TargetOpcode::COPY), *I) 14528 .addReg(NewVR); 14529 } 14530 } 14531 14532 bool AArch64TargetLowering::isIntDivCheap(EVT VT, AttributeList Attr) const { 14533 // Integer division on AArch64 is expensive. However, when aggressively 14534 // optimizing for code size, we prefer to use a div instruction, as it is 14535 // usually smaller than the alternative sequence. 14536 // The exception to this is vector division. Since AArch64 doesn't have vector 14537 // integer division, leaving the division as-is is a loss even in terms of 14538 // size, because it will have to be scalarized, while the alternative code 14539 // sequence can be performed in vector form. 14540 bool OptSize = 14541 Attr.hasAttribute(AttributeList::FunctionIndex, Attribute::MinSize); 14542 return OptSize && !VT.isVector(); 14543 } 14544 14545 bool AArch64TargetLowering::preferIncOfAddToSubOfNot(EVT VT) const { 14546 // We want inc-of-add for scalars and sub-of-not for vectors. 14547 return VT.isScalarInteger(); 14548 } 14549 14550 bool AArch64TargetLowering::enableAggressiveFMAFusion(EVT VT) const { 14551 return Subtarget->hasAggressiveFMA() && VT.isFloatingPoint(); 14552 } 14553 14554 unsigned 14555 AArch64TargetLowering::getVaListSizeInBits(const DataLayout &DL) const { 14556 if (Subtarget->isTargetDarwin() || Subtarget->isTargetWindows()) 14557 return getPointerTy(DL).getSizeInBits(); 14558 14559 return 3 * getPointerTy(DL).getSizeInBits() + 2 * 32; 14560 } 14561 14562 void AArch64TargetLowering::finalizeLowering(MachineFunction &MF) const { 14563 MF.getFrameInfo().computeMaxCallFrameSize(MF); 14564 TargetLoweringBase::finalizeLowering(MF); 14565 } 14566 14567 // Unlike X86, we let frame lowering assign offsets to all catch objects. 14568 bool AArch64TargetLowering::needsFixedCatchObjects() const { 14569 return false; 14570 } 14571 14572 bool AArch64TargetLowering::shouldLocalize( 14573 const MachineInstr &MI, const TargetTransformInfo *TTI) const { 14574 switch (MI.getOpcode()) { 14575 case TargetOpcode::G_GLOBAL_VALUE: { 14576 // On Darwin, TLS global vars get selected into function calls, which 14577 // we don't want localized, as they can get moved into the middle of a 14578 // another call sequence. 14579 const GlobalValue &GV = *MI.getOperand(1).getGlobal(); 14580 if (GV.isThreadLocal() && Subtarget->isTargetMachO()) 14581 return false; 14582 break; 14583 } 14584 // If we legalized G_GLOBAL_VALUE into ADRP + G_ADD_LOW, mark both as being 14585 // localizable. 14586 case AArch64::ADRP: 14587 case AArch64::G_ADD_LOW: 14588 return true; 14589 default: 14590 break; 14591 } 14592 return TargetLoweringBase::shouldLocalize(MI, TTI); 14593 } 14594